text stringlengths 14 6.51M |
|---|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormResize(Sender: TObject);
private
DC : HDC;
hrc: HGLRC;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
// рисование шести сторон куба
glBegin(GL_QUADS);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glEnd;
glBegin(GL_QUADS);
glVertex3f(1.0, 1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, 1.0, -1.0);
glEnd;
glBegin(GL_QUADS);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(-1.0, -1.0, 1.0);
glEnd;
glBegin(GL_QUADS);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(1.0, 1.0, -1.0);
glEnd;
glBegin(GL_QUADS);
glVertex3f(-1.0, 1.0, -1.0);
glVertex3f(-1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, 1.0);
glVertex3f(1.0, 1.0, -1.0);
glEnd;
glBegin(GL_QUADS);
glVertex3f(-1.0, -1.0, -1.0);
glVertex3f(1.0, -1.0, -1.0);
glVertex3f(1.0, -1.0, 1.0);
glVertex3f(-1.0, -1.0, 1.0);
glEnd;
SwapBuffers(DC);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC (Handle);
SetDCPixelFormat (DC);
hrc := wglCreateContext (DC);
wglMakeCurrent (DC, hrc);
glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона
glColor3f (1.0, 0.0, 0.5); // текущий цвет примитивов
glPolygonMode (GL_FRONT_AND_BACK, GL_LINE);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
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;
procedure TfrmGL.FormResize(Sender: TObject);
begin
glViewport(0, 0, ClientWidth, ClientHeight);
glLoadIdentity;
// задаем перспективу
gluPerspective(30.0, // угол видимости в направлении оси Y
ClientWidth / ClientHeight, // угол видимости в направлении оси X
1.0, // расстояние от наблюдателя до ближней плоскости отсечения
15.0); // расстояние от наблюдателя до дальней плоскости отсечения
glTranslatef (0.0, 0.0, -10.0); // перенос - ось Z
glRotatef (30.0, 1.0, 0.0, 0.0); // поворот - ось X
glRotatef (60.0, 0.0, 1.0, 0.0); // поворот - ось Y
InvalidateRect(Handle, nil, False);
end;
end.
|
unit Ths.Erp.Database.Table.SysLangDataContent;
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
TSysLangDataContent = class(TTable)
private
FLang: TFieldDB;
FTableName: TFieldDB;
FColumnName: TFieldDB;
FRowID: TFieldDB;
FValue: TFieldDB;
protected
procedure BusinessInsert(out pID: Integer; var pPermissionControl: Boolean); override;
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 Lang: TFieldDB read FLang write FLang;
Property TableName1: TFieldDB read FTableName write FTableName;
Property ColumnName: TFieldDB read FColumnName write FColumnName;
Property RowID: TFieldDB read FRowID write FRowID;
Property Value: TFieldDB read FValue write FValue;
end;
implementation
uses
Ths.Erp.Constants
, Ths.Erp.Database.Singleton
, Ths.Erp.Database.Table.SysLang
;
constructor TSysLangDataContent.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'sys_lang_data_content';
SourceCode := '1';
FLang := TFieldDB.Create('lang', ftString, '', 0, True, False);
FLang.FK.FKTable := TSysLang.Create(Database);
FLang.FK.FKCol := TFieldDB.Create(TSysLang(FLang.FK.FKTable).Language.FieldName, TSysLang(FLang.FK.FKTable).Language.FieldType, '');
FTableName := TFieldDB.Create('table_name', ftString, '', 0, False, False);
FColumnName := TFieldDB.Create('column_name', ftString, '', 0, False, False);
FRowID := TFieldDB.Create('row_id', ftInteger, 0, 0, False, False);
FValue := TFieldDB.Create('val', ftString, '', 0, False, False);
end;
procedure TSysLangDataContent.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 + '.' + FLang.FieldName,
TableName + '.' + FTableName.FieldName,
TableName + '.' + FColumnName.FieldName,
TableName + '.' + FRowID.FieldName,
TableName + '.' + FValue.FieldName + '::varchar'
]) +
'WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'Id';
Self.DataSource.DataSet.FindField(FLang.FieldName).DisplayLabel := 'Language';
Self.DataSource.DataSet.FindField(FTableName.FieldName).DisplayLabel := 'Table Name';
Self.DataSource.DataSet.FindField(FColumnName.FieldName).DisplayLabel := 'Column Name';
Self.DataSource.DataSet.FindField(FRowID.FieldName).DisplayLabel := 'Row Id';
Self.DataSource.DataSet.FindField(FValue.FieldName).DisplayLabel := 'Value';
end;
end;
end;
procedure TSysLangDataContent.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 + '.' + FLang.FieldName,
TableName + '.' + FTableName.FieldName,
TableName + '.' + FColumnName.FieldName,
TableName + '.' + FRowID.FieldName,
TableName + '.' + FValue.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);
FLang.Value := FormatedVariantVal(FieldByName(FLang.FieldName).DataType, FieldByName(FLang.FieldName).Value);
FTableName.Value := FormatedVariantVal(FieldByName(FTableName.FieldName).DataType, FieldByName(FTableName.FieldName).Value);
FColumnName.Value := FormatedVariantVal(FieldByName(FColumnName.FieldName).DataType, FieldByName(FColumnName.FieldName).Value);
FRowID.Value := FormatedVariantVal(FieldByName(FRowID.FieldName).DataType, FieldByName(FRowID.FieldName).Value);
FValue.Value := FormatedVariantVal(FieldByName(FValue.FieldName).DataType, FieldByName(FValue.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
Close;
end;
end;
end;
procedure TSysLangDataContent.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, [
FLang.FieldName,
FTableName.FieldName,
FColumnName.FieldName,
FRowID.FieldName,
FValue.FieldName
]);
NewParamForQuery(QueryOfInsert, FLang);
NewParamForQuery(QueryOfInsert, FTableName);
NewParamForQuery(QueryOfInsert, FColumnName);
NewParamForQuery(QueryOfInsert, FRowID);
NewParamForQuery(QueryOfInsert, FValue);
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 TSysLangDataContent.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, [
FLang.FieldName,
FTableName.FieldName,
FColumnName.FieldName,
FRowID.FieldName,
FValue.FieldName
]);
NewParamForQuery(QueryOfUpdate, FLang);
NewParamForQuery(QueryOfUpdate, FTableName);
NewParamForQuery(QueryOfUpdate, FColumnName);
NewParamForQuery(QueryOfUpdate, FRowID);
NewParamForQuery(QueryOfUpdate, FValue);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
procedure TSysLangDataContent.BusinessInsert(out pID: Integer;
var pPermissionControl: Boolean);
var
vSysTableLangContent: TSysLangDataContent;
begin
vSysTableLangContent := TSysLangDataContent.Create(Self.Database);
try
vSysTableLangContent.SelectToList(
' AND ' + vSysTableLangContent.FLang.FieldName + '=' + QuotedStr(FormatedVariantVal(FLang.FieldType, FLang.Value)) +
' AND ' + vSysTableLangContent.FTableName.FieldName + '=' + QuotedStr(FormatedVariantVal(FTableName.FieldType, FTableName.Value)) +
' AND ' + vSysTableLangContent.FColumnName.FieldName + '=' + QuotedStr(FormatedVariantVal(FColumnName.FieldType, FColumnName.Value)) +
' AND ' + vSysTableLangContent.FRowID.FieldName + '=' + QuotedStr(FormatedVariantVal(FRowID.FieldType, FRowID.Value)),
False, False);
if vSysTableLangContent.List.Count = 1 then
begin
Self.Id.Value := vSysTableLangContent.Id.Value;
Self.Update()
end
else
Self.Insert(pID);
finally
vSysTableLangContent.Free;
end;
end;
function TSysLangDataContent.Clone():TTable;
begin
Result := TSysLangDataContent.Create(Database);
Self.Id.Clone(TSysLangDataContent(Result).Id);
FLang.Clone(TSysLangDataContent(Result).FLang);
FTableName.Clone(TSysLangDataContent(Result).FTableName);
FColumnName.Clone(TSysLangDataContent(Result).FColumnName);
FRowID.Clone(TSysLangDataContent(Result).FRowID);
FValue.Clone(TSysLangDataContent(Result).FValue);
end;
end.
|
{
Version 12
Copyright (c) 2011-2012 by Bernd Gabriel
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
{$I htmlcons.inc}
unit HtmlBoxes;
interface
uses
Windows, Graphics, Classes, Controls, StdCtrls,
//
HtmlControls,
HtmlDraw,
HtmlElements,
HtmlFonts,
HtmlGlobals,
HtmlImages,
HtmlStyles,
StyleTypes;
type
//------------------------------------------------------------------------------
// THtmlBox is base class for the visual representation of THtmlElements
//------------------------------------------------------------------------------
THtmlBox = class;
THtmlBoxList = {$ifdef UseEnhancedRecord} record {$else} class {$endif}
private
FFirst: THtmlBox;
FLast: THtmlBox;
public
function IsEmpty: Boolean;
function Contains(View: THtmlBox): Boolean;
procedure Add(View: THtmlBox; Before: THtmlBox = nil);
procedure Clear;
procedure Init;
procedure Remove(View: THtmlBox);
procedure Sort;
property First: THtmlBox read FFirst;
property Last: THtmlBox read FLast;
end;
THtmlBox = class
private
// structure
FParent: THtmlBox; // parent view or nil if this is the root view.
FPrev: THtmlBox; // previous sibling in parent's content.
FNext: THtmlBox; // next sibling in parent's content.
FChildren: THtmlBoxList; // the content.
// position
FBounds: TRect; // outer bounds of box relative to FParent (but without FRelativeOffset).
FRelativeOffset: TRect; // offset of position:relative
FDisplay: TDisplayStyle;
FFloat: TBoxFloatStyle;
FPosition: TBoxPositionStyle;
// background image
FImage: ThtImage;
FTiled: Boolean;
FTileWidth: Integer;
FTileHeight: Integer;
// border
FMargins: TRectIntegers;
FBorderWidths: TRectIntegers;
FBorderColors: TRectColors;
FBorderStyles: TRectStyles;
FBackgroundColor: TColor;
// content
FPadding: TRectIntegers;
// content: text
FText: ThtString;
FFont: ThtFont;
FAlignment: TAlignment;
FElement: THtmlElement; // referenced, don't free
FProperties: TResultingPropertyMap; // owned
procedure SetImage(const Value: ThtImage);
function GetContentRect: TRect;
function GetHeight: Integer;
function GetWidth: Integer;
procedure SetFont(const Value: ThtFont);
procedure SetProperties(const Value: TResultingPropertyMap);
protected
function Clipping: Boolean;
function IsVisible: Boolean; virtual;
public
// construction / destruction
constructor Create;
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
// children
procedure AppendChild(Child: THtmlBox);
procedure InsertChild(Child, Before: THtmlBox);
procedure ExtractChild(Child: THtmlBox);
procedure SortChildren;
// change events sent by THtmlViewer
procedure Resized; virtual;
procedure Rescaled(const NewScale: Double); virtual;
//
procedure Paint(Canvas: TScalingCanvas); virtual;
//
property Parent: THtmlBox read FParent;
property Prev: THtmlBox read FPrev;
property Next: THtmlBox read FNext;
property Element: THtmlElement read FElement write FElement;
property Properties: TResultingPropertyMap read FProperties write SetProperties;
property BoundsRect: TRect read FBounds write FBounds;
property Display: TDisplayStyle read FDisplay write FDisplay;
property Float: TBoxFloatStyle read FFloat write FFloat;
property Position: TBoxPositionStyle read FPosition write FPosition;
property RelativeOffset: TRect read FRelativeOffset write FRelativeOffset;
property Height: Integer read GetHeight;
property Width: Integer read GetWidth;
property Visible: Boolean read IsVisible;
//
property Margins: TRectIntegers read FMargins write FMargins;
property BorderWidths: TRectIntegers read FBorderWidths write FBorderWidths;
property BorderColors: TRectColors read FBorderColors write FBorderColors;
property BorderStyles: TRectStyles read FBorderStyles write FBorderStyles;
property Color: TColor read FBackgroundColor write FBackgroundColor;
property ContentRect: TRect read GetContentRect;
property Paddings: TRectIntegers read FPadding write FPadding;
//
property Alignment: TAlignment read FAlignment write FAlignment;
property Children: THtmlBoxList read FChildren;
property Font: ThtFont read FFont write SetFont;
property Text: ThtString read FText write FText;
property Image: ThtImage read FImage write SetImage;
property Tiled: Boolean read FTiled write FTiled;
property TileHeight: Integer read FTileHeight write FTileHeight;
property TileWidth: Integer read FTileWidth write FTileWidth;
end;
//------------------------------------------------------------------------------
// THtmlElementBox is (base) class for ordinary HTML elements
//------------------------------------------------------------------------------
THtmlElementBox = class(THtmlBox)
end;
//------------------------------------------------------------------------------
// THtmlControlBox is base class for the visual representations of the root
// THtmlElements BODY and FRAMESET.
//------------------------------------------------------------------------------
THtmlControlBox = class(THtmlElementBox)
protected
function GetControl: TControl; virtual; abstract;
function IsVisible: Boolean; override;
public
procedure Resized; override;
property Control: TControl read GetControl;
end;
//------------------------------------------------------------------------------
// THtmlScrollControl is base class for the scroll boxes visually representing
// the root THtmlElements BODY and FRAMESET.
//------------------------------------------------------------------------------
THtmlScrollControl = class(TCustomHtmlScrollBox)
private
// BG, 19.08.2011: FBox is a reference to the box, that owns this scroll control.
// Do not free in desctructor!
FBox: THtmlBox;
protected
function GetContentHeight: Integer; override;
function GetContentWidth: Integer; override;
procedure Init(Box: THtmlBox);
procedure Paint; override;
end;
//------------------------------------------------------------------------------
// THtmlFramesetBox
//------------------------------------------------------------------------------
THtmlFramesetControl = class(THtmlScrollControl)
end;
THtmlFramesetBox = class(THtmlControlBox)
private
FControl: THtmlFramesetControl;
protected
function GetControl: TControl; override;
public
constructor Create(Control: THtmlFramesetControl);
procedure Rescaled(const NewScale: Double); override;
property Control: THtmlFramesetControl read FControl;
end;
//------------------------------------------------------------------------------
// THtmlBodyBox
//------------------------------------------------------------------------------
THtmlBodyControl = class(THtmlScrollControl)
end;
THtmlBodyBox = class(THtmlControlBox)
private
FControl: THtmlBodyControl;
protected
function GetControl: TControl; override;
public
constructor Create(Control: THtmlBodyControl);
procedure Rescaled(const NewScale: Double); override;
property Control: THtmlBodyControl read FControl;
end;
//------------------------------------------------------------------------------
// THtmlFormControlBox
//------------------------------------------------------------------------------
// THtmlFormControlBox = class(THtmlBox)
// protected
// function GetControl: TWinControl; virtual; abstract;
// public
// constructor Create(Owner: TControl; ParentBox: THtmlBox);
// property Control: TWinControl read GetControl;
// end;
//------------------------------------------------------------------------------
// THtmlAnonymousBox
//------------------------------------------------------------------------------
// The renderer generates THtmlAnonymousBoxes to group lines of inline elements
// and text.
//------------------------------------------------------------------------------
THtmlAnonymousBox = class(THtmlBox)
end;
implementation
{ THtmlBoxList }
//-- BG ---------------------------------------------------------- 03.04.2011 --
procedure THtmlBoxList.Clear;
var
View: THtmlBox;
begin
FLast := nil;
while First <> nil do
begin
View := First;
FFirst := View.Next;
View.Free;
end;
end;
//-- BG ---------------------------------------------------------- 18.12.2011 --
function THtmlBoxList.Contains(View: THtmlBox): Boolean;
var
Box: THtmlBox;
begin
Box := First;
while Box <> nil do
begin
if Box = View then
begin
Result := True;
Exit;
end;
Box := Box.Next;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 03.04.2011 --
procedure THtmlBoxList.Init;
begin
FFirst := nil;
FLast := nil;
end;
{
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure THtmlBoxList.Append(View: THtmlBox);
// append View
var
Prev: THtmlBox;
begin
assert(View.Next = nil, 'Don''t add chained links twice. View.Next is not nil.');
assert(View.Prev = nil, 'Don''t add chained links twice. View.Prev is not nil.');
end;
}
//-- BG ---------------------------------------------------------- 18.12.2011 --
procedure THtmlBoxList.Add(View, Before: THtmlBox);
{
Insert View before Before. If Before is nil, append after last box.
}
begin
assert(View.Next = nil, 'Don''t insert chained links twice. View.Next is not nil.');
assert(View.Prev = nil, 'Don''t insert chained links twice. View.Prev is not nil.');
if Before = nil then
begin
// append after last
// link to prev
if Last = nil then
FFirst := View
else
Last.FNext := View;
View.FPrev := Last;
// link to next
FLast := View;
end
else if Before = First then
begin
// insert before first
// link to next
if First = nil then
FLast := View
else
First.FPrev := View;
View.FNext := First;
// link to prev
FFirst := View;
end
else
begin
// link between Before.Prev and Before.
assert(Contains(Before), 'Box to insert before is not mine.');
assert(Before.Prev <> nil, 'Illegal link status: ''Before'' is not first link, but has no previous link.');
// link to prev
Before.Prev.FNext := View;
View.FPrev := Before.Prev;
// link to next
Before.FPrev := View;
View.FNext := Before;
end;
end;
//-- BG ---------------------------------------------------------- 03.04.2011 --
function THtmlBoxList.IsEmpty: Boolean;
begin
Result := FFirst = nil;
end;
//-- BG ---------------------------------------------------------- 03.04.2011 --
procedure THtmlBoxList.Remove(View: THtmlBox);
var
Prev: THtmlBox;
Next: THtmlBox;
begin
Prev := View.Prev;
Next := View.Next;
if Prev = nil then
begin
if First = View then
FFirst := Next;
end
else
begin
Prev.FNext := Next;
View.FPrev := nil;
end;
if Next = nil then
begin
if Last = View then
FLast := Prev;
end
else
begin
Next.FPrev := Prev;
View.FNext := nil;
end;
end;
//-- BG ---------------------------------------------------------- 14.12.2011 --
procedure THtmlBoxList.Sort;
{
Move boxes with relative position to the end as they may overlap and hide other
boxes.
}
var
View, Next, FirstMoved: THtmlBox;
begin
if First <> Last then
begin
// at least 2 entries, thus sorting required:
FirstMoved := nil; // stop at end of list (still nil) or at first relocated box.
View := First;
while View <> FirstMoved do
begin
Next := View.Next;
if View.Position = posRelative then
begin
Remove(View);
Add(View);
if FirstMoved = nil then
FirstMoved := View;
end;
View := Next;
end;
end;
end;
{ THtmlBox }
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure THtmlBox.AfterConstruction;
begin
inherited;
FFont := ThtFont.Create;
{$ifdef UseEnhancedRecord}
{$else}
FChildren := THtmlBoxList.Create;
{$endif}
end;
//-- BG ---------------------------------------------------------- 18.12.2011 --
procedure THtmlBox.AppendChild(Child: THtmlBox);
begin
InsertChild(Child, nil);
end;
//-- BG ---------------------------------------------------------- 05.04.2011 --
procedure THtmlBox.BeforeDestruction;
begin
{$ifdef UseEnhancedRecord}
FChildren.Clear;
{$else}
FChildren.Free;
{$endif}
FFont.Free;
FProperties.Free;
if Parent <> nil then
Parent.ExtractChild(Self);
Image := nil;
inherited;
end;
//-- BG ---------------------------------------------------------- 13.04.2011 --
function THtmlBox.Clipping: Boolean;
begin
Result := False;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
constructor THtmlBox.Create;
begin
inherited Create;
FBackgroundColor := clNone;
FBorderColors := NoneColors;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure THtmlBox.ExtractChild(Child: THtmlBox);
begin
FChildren.Remove(Child);
Child.FParent := nil;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlBox.GetContentRect: TRect;
begin
DeflateRect(Result, BoundsRect, Margins);
DeflateRect(Result, BorderWidths);
DeflateRect(Result, Paddings);
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlBox.GetHeight: Integer;
begin
Result := FBounds.Bottom - FBounds.Top;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlBox.GetWidth: Integer;
begin
Result := FBounds.Right- FBounds.Left;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure THtmlBox.InsertChild(Child: THtmlBox; Before: THtmlBox);
begin
FChildren.Add(Child, Before);
Child.FParent := Self;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlBox.IsVisible: Boolean;
begin
Result := (FDisplay <> pdNone) and ((FParent = nil) or FParent.Visible);
end;
//-- BG ---------------------------------------------------------- 04.04.2011 --
procedure THtmlBox.Paint(Canvas: TScalingCanvas);
procedure DrawTestOutline(const Rect: TRect);
begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := clBlack;
Canvas.FrameRect(Rect);
end;
function CreateClipRegion(Clipping: Boolean; const Rect: TRect; out ExistingRegion, ClippingRegion: Integer): Boolean;
{
Returns True, if there is a draw area because either Clipping is false or clip region is not empty.
}
var
ScrRect: TRect;
begin
ClippingRegion := 0;
ExistingRegion := 0;
Result := True;
if Clipping then
begin
ScrRect.TopLeft := Canvas.ToWindowUnits(Rect.TopLeft);
ScrRect.BottomRight := Canvas.ToWindowUnits(Rect.BottomRight);
ClippingRegion := CreateRectRgnIndirect(ScrRect);
ExistingRegion := GetClipRegion(Canvas);
if ExistingRegion <> 0 then
Result := CombineRgn(ClippingRegion, ClippingRegion, ExistingRegion, RGN_AND) in [SIMPLEREGION, COMPLEXREGION];
if Result then
SelectClipRgn(Canvas.Handle, ClippingRegion);
end;
end;
procedure DeleteClipRegion(ExistingRegion, ClippingRegion: Integer);
begin
if ClippingRegion <> 0 then
begin
SelectClipRgn(Canvas.Handle, ExistingRegion);
DeleteObject(ClippingRegion);
if ExistingRegion <> 0 then
DeleteObject(ExistingRegion);
end;
end;
procedure DrawImage(const Rect: TRect);
var
ClippingRegion, ExistingRegion: Integer;
Tile, TiledEnd: TPoint;
begin
if CreateClipRegion(True, Rect, ExistingRegion, ClippingRegion) then
try
if (Image = ErrorImage) or (Image = DefImage) then
begin
Image.Draw(Canvas, Rect.Left + 4, Rect.Top + 4, Image.Width, Image.Height);
end
else if Tiled then
begin
// prepare horizontal tiling
if TileWidth = 0 then
TileWidth := Image.Width;
Tile.X := 0; // GetPositionInRange(bpCenter, 0, Rect.Right - Rect.Left - TileWidth) + Rect.Left;
AdjustForTiling(Tiled, Rect.Left, Rect.Right, TileWidth, Tile.X, TiledEnd.X);
// prepare vertical tiling
if TileHeight = 0 then
TileHeight := Image.Height;
Tile.Y := 0; // GetPositionInRange(bpCenter, 0, Rect.Bottom - Rect.Top - TileHeight) + Rect.Top;
AdjustForTiling(Tiled, Rect.Top, Rect.Bottom, TileHeight, Tile.Y, TiledEnd.Y);
// clip'n'paint
Image.DrawTiled(Canvas, Tile.X, Tile.Y, TiledEnd.X, TiledEnd.Y, TileWidth, TileHeight);
end
else
Image.Draw(Canvas, Rect.Left, Rect.Top, Rect.Right - Rect.Left, Rect.Bottom - Rect.Top);
finally
DeleteClipRegion(ExistingRegion, ClippingRegion);
end;
end;
var
Rect: TRect;
Child: THtmlBox;
Org: TPoint;
Flags, ContentRegion, ExistingRegion: Integer;
begin
if not Visible then
exit;
Rect := BoundsRect;
if Position = posRelative then
OffsetRect(Rect, RelativeOffset);
// background
if Color <> clNone then
begin
Canvas.Brush.Color := ThemedColor(Color);
Canvas.Brush.Style := bsSolid;
Canvas.FillRect(Rect);
end;
{$ifdef DEBUG}
DrawTestOutline(Rect);
{$endif}
if Image <> nil then
DrawImage(Rect);
DeflateRect(Rect, Margins);
// border
DrawBorder(Canvas, Rect, BorderWidths, BorderColors, BorderStyles, clNone);
DeflateRect(Rect, BorderWidths);
// content
DeflateRect(Rect, Paddings);
if CreateClipRegion(Clipping, Rect, ExistingRegion, ContentRegion) then
try
if Length(Text) > 0 then
begin
// text
DrawTestOutline(Rect);
case Alignment of
taLeftJustify: Flags := DT_LEFT;
taRightJustify: Flags := DT_RIGHT;
taCenter: Flags := DT_CENTER;
else
Flags := 0;
end;
Canvas.Brush.Style := bsClear;
Canvas.Font := Font;
DrawTextW(Canvas.Handle, PhtChar(Text), Length(Text), Rect, Flags + DT_NOCLIP + DT_VCENTER + DT_SINGLELINE);
end;
// children
if Children.First <> nil then
begin
GetViewportOrgEx(Canvas.Handle, Org);
SetViewportOrgEx(Canvas.Handle, Org.X + Rect.Left, Org.Y + Rect.Top, nil);
Child := Children.First;
repeat
Child.Paint(Canvas);
Child := Child.Next;
until Child = nil;
SetViewportOrgEx(Canvas.Handle, Org.X, Org.Y, nil);
end;
finally
DeleteClipRegion(ExistingRegion, ContentRegion);
end;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure THtmlBox.Rescaled(const NewScale: Double);
var
Child: THtmlBox;
begin
Child := Children.First;
while Child <> nil do
begin
Child.Rescaled(NewScale);
Child := Child.Next;
end;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure THtmlBox.Resized;
var
Child: THtmlBox;
begin
Child := Children.First;
while Child <> nil do
begin
Child.Resized;
Child := Child.Next;
end;
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
procedure THtmlBox.SetFont(const Value: ThtFont);
begin
FFont.Assign(Value);
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
procedure THtmlBox.SetImage(const Value: ThtImage);
begin
if FImage <> Value then
begin
if FImage <> nil then
FImage.EndUse;
FImage := Value;
if FImage <> nil then
FImage.BeginUse;
end;
end;
procedure THtmlBox.SetProperties(const Value: TResultingPropertyMap);
begin
if FProperties <> Value then
begin
if FProperties <> nil then
FProperties.Free;
FProperties := Value;
end;
end;
//-- BG ---------------------------------------------------------- 14.12.2011 --
procedure THtmlBox.SortChildren;
begin
Children.Sort;
end;
{ THtmlControlBox }
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlControlBox.IsVisible: Boolean;
begin
Result := GetControl.Visible and inherited IsVisible;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure THtmlControlBox.Resized;
begin
inherited;
Control.BoundsRect := ContentRect;
end;
{ THtmlScrollControl }
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlScrollControl.GetContentHeight: Integer;
begin
Result := FBox.Height;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlScrollControl.GetContentWidth: Integer;
begin
Result := FBox.Width;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure THtmlScrollControl.Init(Box: THtmlBox);
function GetParent(C: TComponent): TWinControl;
begin
while C <> nil do
begin
if C is TWinControl then
begin
Result := TWinControl(C);
exit;
end;
C := C.Owner;
end;
Result := nil;
end;
begin
FBox := Box;
Parent := GetParent(Owner);
Align := alClient;
ScrollBars := ssBoth;
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
procedure THtmlScrollControl.Paint;
begin
inherited;
FBox.Paint(Canvas);
end;
{ THtmlFramesetBox }
//-- BG ---------------------------------------------------------- 24.04.2011 --
constructor THtmlFramesetBox.Create(Control: THtmlFramesetControl);
begin
inherited Create;
FControl := Control;
FControl.Init(Self);
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlFramesetBox.GetControl: TControl;
begin
Result := FControl;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure THtmlFramesetBox.Rescaled(const NewScale: Double);
begin
inherited;
FControl.Scale := NewScale;
end;
{ THtmlBodyBox }
//-- BG ---------------------------------------------------------- 24.04.2011 --
constructor THtmlBodyBox.Create(Control: THtmlBodyControl);
begin
inherited Create;
FControl := Control;
FControl.Init(Self);
end;
//-- BG ---------------------------------------------------------- 24.04.2011 --
function THtmlBodyBox.GetControl: TControl;
begin
Result := FControl;
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
procedure THtmlBodyBox.Rescaled(const NewScale: Double);
begin
inherited;
FControl.Scale := NewScale;
end;
end.
|
unit IdFinger;
interface
uses
Classes,
IdGlobal,
IdTCPClient;
const
Id_TIdFinger_VerboseOutput = False;
type
TIdFinger = class(TIdTCPClient)
protected
FQuery: string;
FVerboseOutput: Boolean;
procedure SetCompleteQuery(AQuery: string);
function GetCompleteQuery: string;
public
constructor Create(AOwner: TComponent); override;
function Finger: string;
published
property Query: string read FQuery write FQuery;
property CompleteQuery: string read GetCompleteQuery write SetCompleteQuery;
property VerboseOutput: Boolean read FVerboseOutPut write FVerboseOutPut
default Id_TIdFinger_VerboseOutput;
property Port default IdPORT_FINGER;
end;
implementation
uses
IdTCPConnection,
SysUtils;
constructor TIdFinger.Create(AOwner: TComponent);
begin
inherited;
Port := IdPORT_FINGER;
FVerboseOutput := Id_TIdFinger_VerboseOutput;
end;
function TIdFinger.Finger: string;
var
QStr: string;
begin
QStr := FQuery;
if VerboseOutPut then
begin
QStr := QStr + '/W';
end;
Connect;
try
Result := '';
WriteLn(QStr);
Result := AllData;
finally
Disconnect;
end;
end;
function TIdFinger.GetCompleteQuery: string;
begin
Result := FQuery + '@' + Host;
end;
procedure TIdFinger.SetCompleteQuery(AQuery: string);
var
p: Integer;
begin
p := RPos('@', AQuery, -1);
if (p <> 0) then
begin
if (p < Length(AQuery)) then
begin
Host := Copy(AQuery, p + 1, Length(AQuery));
end;
FQuery := Copy(AQuery, 1, p - 1);
end
else
begin
FQuery := AQuery;
end;
end;
end.
|
unit xSortControl;
interface
uses xSortInfo, System.SysUtils, System.Classes, xFunction, xSortAction, xQuestionInfo;
type
/// <summary>
/// 题库控制类
/// </summary>
TSortControl = class
private
FSortList: TStringList;
FSortAction : TSortAction;
function GetSortInfo(nIndex: Integer): TSortInfo;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 题库列表
/// </summary>
property SortList : TStringList read FSortList write FSortList;
property SortInfo[nIndex:Integer] : TSortInfo read GetSortInfo;
/// <summary>
/// 添加题库
/// </summary>
procedure AddSort(ASortInfo : TSortInfo);
/// <summary>
/// 删除题库
/// </summary>
procedure DelSort(nSortID : Integer);
/// <summary>
/// 编辑题库
/// </summary>
procedure EditSort(ASortInfo : TSortInfo);
/// <summary>
/// 加载题库
/// </summary>
procedure LoadSort;
/// <summary>
/// 清空题库
/// </summary>
procedure ClearSrot;
/// <summary>
/// 获取考题
/// </summary>
function GetQInfo(nQID : Integer) : TQuestionInfo;
end;
var
SortControl : TSortControl;
implementation
{ TSortControl }
procedure TSortControl.AddSort(ASortInfo: TSortInfo);
begin
if Assigned(ASortInfo) then
begin
ASortInfo.SortID := FSortAction.GetMaxSN + 1;
FSortList.AddObject('', ASortInfo);
FSortAction.AddSort(ASortInfo);
end;
end;
procedure TSortControl.ClearSrot;
var
i : Integer;
begin
for i := FSortList.Count - 1 downto 0 do
begin
TSortInfo(FSortList.Objects[i]).ClearQuestion;
FSortAction.DelSort(TSortInfo(FSortList.Objects[i]).SortID);
TSortInfo(FSortList.Objects[i]).Free;
FSortList.Delete(i);
end;
end;
constructor TSortControl.Create;
begin
FSortList:= TStringList.Create;
FSortAction := TSortAction.Create;
LoadSort;
end;
procedure TSortControl.DelSort(nSortID: Integer);
var
i : Integer;
begin
for i := FSortList.Count - 1 downto 0 do
begin
if TSortInfo(FSortList.Objects[i]).Sortid = nSortID then
begin
TSortInfo(FSortList.Objects[i]).ClearQuestion;
FSortAction.DelSort(nSortID);
TSortInfo(FSortList.Objects[i]).Free;
FSortList.Delete(i);
Break;
end;
end;
end;
destructor TSortControl.Destroy;
begin
ClearStringList(FSortList);
FSortList.Free;
FSortAction.Free;
inherited;
end;
procedure TSortControl.EditSort(ASortInfo: TSortInfo);
begin
FSortAction.EditSort(ASortInfo);
end;
function TSortControl.GetQInfo(nQID: Integer): TQuestionInfo;
var
i : Integer;
ASort : TSortInfo;
begin
Result := nil;
for i := FSortList.Count - 1 downto 0 do
begin
ASort := TSortInfo(FSortList.Objects[i]);
ASort.LoadQuestion;
Result := ASort.GetQInfo(nQID);
if Assigned(Result) then
Break;
end;
end;
function TSortControl.GetSortInfo(nIndex: Integer): TSortInfo;
begin
if (nIndex >= 0) and (nIndex < FSortList.Count) then
begin
Result := TSortInfo(FSortList.Objects[nIndex]);
end
else
begin
Result := nil;
end;
end;
procedure TSortControl.LoadSort;
begin
FSortAction.LoadSort(FSortList);
end;
end.
|
unit Unit_Piano;
interface
uses Main, Classes, Forms, SysUtils, ExtCtrls, Graphics, mmSystem, Notes_MIDI;
type
TPiano = Class(TComponent)
public
//
procedure PianoToucheDown(Touche: string);
procedure PianoToucheUp(Touche: string);
private
//
end;
var
Piano: TPiano;
Form1: TForm1;
MidiOut: hMidiOut;
Instrument: string;
implementation
{---------------------GESTION DU SON-------------------------------}
procedure PianoToucheDown(Touche: string);
var
i : integer;
Note : cardinal;
begin
for i := 0 to Length(Notes) - 1 do
begin
if Notes[i].Note=Touche then
begin
// Paramétrage de l'instrument
Form1.lblInstrument.Caption := Instrument;
// Formatage de la note
// midiOutShortMsg(MidiOut, $007F3C90);
// 1er octet = 00 - inutilisé)
// 2ème octet = 7F - vélocité 0..7F
// 3ème octet = 3C - la note à jouer (DO3 par exemple)
// 4ème octet = le status + canal midi
// 90 = jouer la note sur le canal midi 1
// 80 = stopper la note sur le canal midi 1
Note := StrToInt('$007F' + Notes[i].SonMidi + '90');
// Selection de l'instrument
// midiOutShortMsg(MidiOut, $0000C4C0);
// 1er octet = C4 - numéro du programme (0..127)
// 2ème octet = C0 - commande + canal midi
// 3ème octet = C - ProgramChange
// 4ème octet = 0 - canal midi 1
midiOutShortMsg(MidiOut, StrToInt('$0000' + Instrument + 'C0'));
// Jeu de la note
midiOutShortMsg(MidiOut, Note);
// Affichage de la note en toute lettre
Form1.lblNote.Caption := Touche;
Form1.lblNote.Visible := true;
// Affichage de la note sur la touche du piano (format américain)
if Copy(Touche, Length(Touche), 1)<>'d' then
Form1.Panel1.Visible := true
else
Form1.Panel2.Visible := true;
TImage(Form1.FindComponent('lbl' + Touche)).Visible := true;
// Affichage de la note sur la partition (Do1..Do5)
// Si c'est un Do3 la note s'affiche à la fois
// sur la clé de Sol et la clé de Fa
if i<50 then
begin
if Touche='Do3' then
begin
TImage(Form1.FindComponent('imgDo3_1')).Visible := true;
TImage(Form1.FindComponent('imgDo3_2')).Visible := true;
end
else if Touche='Do3d' then
begin
TImage(Form1.FindComponent('imgDo3d_1')).Visible := true;
TImage(Form1.FindComponent('imgDo3d_2')).Visible := true;
end
else TImage(Form1.FindComponent('img' + Touche)).Visible := true;
end;
// Modification de la couleur de la touche du piano appuyée
if TShape(Form1.FindComponent(Touche)).Brush.Color=clWhite then
TShape(Form1.FindComponent(Touche)).Brush.Color:=clRed
else if TShape(Form1.FindComponent(Touche)).Brush.Color=clBlack then
TShape(Form1.FindComponent(Touche)).Brush.Color:=clLime;
end;
end;
end;
procedure PianoToucheUp(Touche: string);
var
i : integer;
Note:Cardinal;
begin
for i := 0 to Length(Notes) - 1 do
begin
Form1.lblNote.Visible := false;
if Copy(Touche, Length(Touche), 1)<>'d' then
Form1.Panel1.Visible := false
else
Form1.Panel2.Visible := false;
TImage(Form1.FindComponent('lbl' + Touche)).Visible := false;
if Notes[i].Note=Touche then
begin
Note := StrToInt('$007F' + Notes[i].SonMidi + '80');
midiOutShortMsg(MidiOut, Note);
if i<50 then
begin
if Touche='Do3' then
begin
TImage(Form1.FindComponent('imgDo3_1')).Visible := false;
TImage(Form1.FindComponent('imgDo3_2')).Visible := false;
end
else if Touche='Do3d' then
begin
TImage(Form1.FindComponent('imgDo3d_1')).Visible := false;
TImage(Form1.FindComponent('imgDo3d_2')).Visible := false;
end
else TImage(Form1.FindComponent('img' + Touche)).Visible := false;
end;
// Modification de la couleur de la touche du piano relâchée
if TShape(Form1.FindComponent(Touche)).Brush.Color=clRed then
TShape(Form1.FindComponent(Touche)).Brush.Color:=clWhite
else if TShape(Form1.FindComponent(Touche)).Brush.Color=clLime then
TShape(Form1.FindComponent(Touche)).Brush.Color:=clBlack;
end;
end;
end;
{------------------------------------------------------------------}
end.
|
unit IdSMTP;
interface
uses
Classes,
IdAssignedNumbers,
IdEMailAddress,
IdGlobal,
IdHeaderList,
IdMessage, IdMessageClient;
const
IdDEF_UseEhlo = TRUE; //APR: default behavior
type
TAuthenticationType = (atNone, atLogin);
TIdSMTP = class(TIdMessageClient)
protected
{This is just an internal flag we use to determine if we already
authenticated to the server }
FDidAuthenticate : Boolean;
FAuthenticationType: TAuthenticationType;
FAuthSchemesSupported: TStringList;
FMailAgent: string;
{HELO Login}
FHeloName : String;
FUseEhlo: Boolean; //APR: for OLD STUPID server's {Do not Localize}
//
procedure GetAuthTypes;
function IsAuthProtocolAvailable (Auth: TAuthenticationType): Boolean; virtual;
procedure SetAuthenticationType(const Value: TAuthenticationType);
procedure SetUseEhlo(const Value: Boolean);
public
procedure Assign(Source: TPersistent); override;
function Authenticate : Boolean; virtual;
procedure Connect(const ATimeout: Integer = IdTimeoutDefault); override;
constructor Create ( AOwner : TComponent ); override;
destructor Destroy; override;
procedure Disconnect; override;
class procedure QuickSend ( const AHost, ASubject, ATo,
AFrom, AText : String);
procedure Send (AMsg: TIdMessage); virtual;
procedure Expand( AUserName : String; AResults : TStrings); virtual;
function Verify( AUserName : String) : String; virtual;
//
property AuthSchemesSupported: TStringList read FAuthSchemesSupported;
published
property AuthenticationType : TAuthenticationType read FAuthenticationType
write SetAuthenticationType;
property MailAgent: string read FMailAgent write FMailAgent;
property HeloName : string read FHeloName write FHeloName;
property UseEhlo: Boolean read FUseEhlo write SetUseEhlo default IdDEF_UseEhlo;
property Password;
property Username;
end;
implementation
uses
IdCoderMIME,
IdResourceStrings,
SysUtils;
{ TIdSMTP }
procedure TIdSMTP.Assign(Source: TPersistent);
begin
if Source is TIdSMTP then begin
AuthenticationType := TIdSMTP(Source).AuthenticationType;
Host := TIdSMTP(Source).Host;
MailAgent := TIdSMTP(Source).MailAgent;
Password := TIdSMTP(Source).Password;
Port := TIdSMTP(Source).Port;
Username := TIdSMTP(Source).Username;
end else begin
inherited;
end;
end;
function TIdSMTP.Authenticate : Boolean;
function AuthLogin : Boolean;
begin
{for some odd reason wcSMTP does not accept lowercase 'LOGIN" (WcSMTP is
part of the WildCat Interactive Net Server}
SendCmd('AUTH LOGIN', 334); {Do not Localize}
SendCmd(TIdEncoderMIME.EncodeString(Username), 334);
SendCmd(TIdEncoderMIME.EncodeString(Password), 235);
Result := True;
end;
begin
Result := False; //assume failure
case FAUthenticationType of
atLogin : Result := AuthLogin;
end;
FDidAuthenticate := True;
end;
procedure TIdSMTP.Connect(const ATimeout: Integer = IdTimeoutDefault);
var
NameToSend : String;
begin
inherited;
try
GetResponse([220]);
FAuthSchemesSupported.Clear;
if Length(FHeloName) > 0 then
NameToSend := FHeloName
else
NameToSend := LocalName;
if FUseEhlo and (SendCmd('EHLO ' + NameToSend )=250) then begin //APR: user can prevent EHLO {Do not Localize}
GetAuthTypes;
end
else begin
SendCmd( 'HELO ' + NameToSend, 250 ); {Do not Localize}
end;
except
Disconnect;
Raise;
end;
end;
constructor TIdSMTP.Create(AOwner: TComponent);
begin
inherited;
FAuthSchemesSupported := TStringList.Create;
FAuthSchemesSupported.Duplicates := dupIgnore; //prevent duplicates in the supported AUTH protocol list
FUseEhlo:=IdDEF_UseEhlo;
FAuthenticationType:=atNone;
Port := IdPORT_SMTP;
end;
destructor TIdSMTP.Destroy;
begin
FreeAndNil ( FAuthSchemesSupported );
inherited;
end;
procedure TIdSMTP.Disconnect;
begin
try
if Connected then begin
WriteLn('QUIT'); {Do not Localize}
end;
finally
inherited;
FDidAuthenticate := False;
end;
end;
procedure TIdSMTP.Expand(AUserName: String; AResults: TStrings);
begin
SendCMD('EXPN ' + AUserName, [250, 251]); {Do not Localize}
end;
procedure TIdSMTP.GetAuthTypes;
var
i: Integer;
s: string;
LEntry : String;
begin
for i := 0 to LastCmdResult.Text.Count - 1 do begin
s := UpperCase(LastCmdResult.Text[i]);
if AnsiSameText(Copy(s, 1, 5), 'AUTH ') or AnsiSameText(Copy(s, 1, 5), 'AUTH=') then begin {Do not Localize}
s := Copy(s, 5, MaxInt);
while Length(s) > 0 do begin
s := StringReplace(s, '=', ' ', [rfReplaceAll]); {Do not Localize}
LEntry := Fetch(s, ' '); {Do not Localize}
if FAuthSchemesSupported.IndexOf(LEntry) = -1 then begin
FAuthSchemesSupported.Add(LEntry);
end;
end;
end;
end;
end;
function TIdSMTP.IsAuthProtocolAvailable(
Auth : TAuthenticationType ) : Boolean;
begin
case Auth of
atLogin : Result := ( FAuthSchemesSupported.IndexOf ( 'LOGIN' ) <> -1 ); {Do not Localize}
else
Result := False;
end;
end;
class procedure TIdSMTP.QuickSend (const AHost, ASubject, ATo, AFrom, AText : String);
var
LSMTP: TIdSMTP;
LMsg: TIdMessage;
begin
LSMTP := TIdSMTP.Create(nil);
try
LMsg := TIdMessage.Create(LSMTP);
try
with LMsg do
begin
Subject := ASubject;
Recipients.EMailAddresses := ATo;
From.Text := AFrom;
Body.Text := AText;
end;
with LSMTP do
begin
Host := AHost;
Connect; try;
Send(LMsg);
finally Disconnect; end;
end;
finally
FreeAndNil(LMsg);
end;
finally
FreeAndNil(LSMTP);
end;
end;
procedure TIdSMTP.Send(AMsg: TIdMessage);
procedure WriteRecipient(const AEmailAddress: TIdEmailAddressItem);
begin
SendCmd('RCPT TO:<' + AEMailAddress.Address + '>', [250, 251]); {Do not Localize}
end;
procedure WriteRecipients(AList: TIdEmailAddressList);
var
i: integer;
begin
for i := 0 to AList.Count - 1 do begin
WriteRecipient(AList[i]);
end;
end;
function NeedToAuthenticate: Boolean;
begin
if FAuthenticationType <> atNone then begin
Result := IsAuthProtocolAvailable(FAuthenticationType) and (FDidAuthenticate = False);
end else begin
Result := False;
end;
end;
begin
SendCmd('RSET'); {Do not Localize}
if NeedToAuthenticate then begin
Authenticate;
end;
SendCmd('MAIL FROM:<' + AMsg.From.Address + '>', 250); {Do not Localize}
WriteRecipients(AMsg.Recipients);
WriteRecipients(AMsg.CCList);
WriteRecipients(AMsg.BccList);
SendCmd('DATA', 354); {Do not Localize}
AMsg.ExtraHeaders.Values['X-Mailer'] := MailAgent; {Do not Localize}
SendMsg(AMsg);
SendCmd('.', 250); {Do not Localize}
end;
procedure TIdSMTP.SetAuthenticationType(const Value: TAuthenticationType);
Begin
FAuthenticationType:= Value;
if Value=atLogin then FUseEhlo:=TRUE;
End;//
procedure TIdSMTP.SetUseEhlo(const Value: Boolean);
Begin
FUseEhlo:= Value;
if NOT Value then FAuthenticationType:=atNone;
End;//
function TIdSMTP.Verify(AUserName: string): string;
begin
SendCMD('VRFY ' + AUserName, [250, 251]); {Do not Localize}
Result := LastCmdResult.Text[0];
end;
end.
|
unit FSUIPCcontrol;
interface
uses
Classes, FPCuser, Windows, Messages;
type
TFSUIPCcontrol = class
private
{ Private declarations }
fConnected : boolean;
procedure DebugLog(Value: String);
public
{ Public declarations }
constructor Create;
destructor Destroy; Override;
function Open: Boolean;
procedure Close;
function GetDouble(pOffset: Cardinal): Double;
function GetFloat(pOffset: Cardinal; pSize: Short): Double;
function GetInt(pOffset: Cardinal; pSize: Short): Int64;
procedure SetFloat(pOffset: Cardinal; pSize: Short; pValue: Double);
procedure SetInt(pOffset: Cardinal; pSize: Short; pValue: Int64);
function GetRaw(pOffset: Cardinal; pSize: Short): String;
function GetString(pOffset: Cardinal; pSize: Short): String;
procedure SetString(pOffset: Cardinal; pSize: Short; pValue: String);
property Connected : boolean read fConnected;
end;
implementation
uses SysUtils, uGlobals;
procedure TFSUIPCcontrol.Close;
begin
if fConnected then
begin
FSUIPC_Close;
fConnected := False;
end;
end;
constructor TFSUIPCcontrol.Create;
begin
//inherited;
fConnected := False;
end;
destructor TFSUIPCcontrol.Destroy;
begin
inherited;
end;
function TFSUIPCcontrol.GetDouble(pOffset: Cardinal): Double;
var
dwResult : DWORD;
begin
Result := 0;
if not fConnected then
Open;
if fConnected then
begin
if FSUIPC_Read(pOffset, 8, @Result, dwResult) then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
DebugLog('FSUIPC: Variable ' + IntToHex(pOffset, 4) + ' read as '
+ FloatToStr(Result))
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error reading variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end;
end;
function TFSUIPCcontrol.GetFloat(pOffset: Cardinal; pSize: Short): Double;
var
dwResult : DWORD;
lValue: Single;
lValuePtr: PSingle;
lRes: Boolean;
lBuffer: array[0..3] of byte;
begin
Result := 0;
if not fConnected then
Open;
if fConnected then
begin
if (pSize <> 4) and (pSize <> 8) then
pSize := 8;
if pSize = 4 then
lRes := FSUIPC_Read(pOffset, 4, @lBuffer[0], dwResult)
else
lRes := FSUIPC_Read(pOffset, 8, @Result, dwResult);
if lRes then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
begin
if pSize = 4 then
begin
lValuePtr := @lBuffer[0];
Result := lValuePtr^;
DebugLog(Format('FSUIPC: Variable %x raw data: %2x %2x %2x %2x',
[pOffset, lBuffer[0], lBuffer[1], lBuffer[2], lBuffer[3]]));
end;
DebugLog(Format('FSUIPC: Variable %x read as %5.3f', [pOffset, Result]));
end
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error reading variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end;
end;
function TFSUIPCcontrol.GetInt(pOffset: Cardinal; pSize: Short): Int64;
var
dwResult : DWORD;
begin
Result := 0;
if not fConnected then
Open;
if fConnected then
begin
if (pSize < 1) or (pSize > 8) then
pSize := 1;
if FSUIPC_Read(pOffset, pSize, @Result, dwResult) then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
DebugLog('FSUIPC: Variable ' + IntToHex(pOffset, 4) + ' read as '
+ IntToStr(Result))
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error reading variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end;
end;
function TFSUIPCcontrol.GetRaw(pOffset: Cardinal; pSize: Short): String;
var
dwResult : DWORD;
lRes: Boolean;
lBuffer, lTmp: ^byte;
I: Integer;
begin
if not fConnected then
Open;
if fConnected then
begin
if (pSize < 0) or (pSize > 256) then
pSize := 256;
GetMem(lBuffer, pSize);
try
lRes := FSUIPC_Read(pOffset, pSize, lBuffer, dwResult);
if lRes then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
begin
Result := '';
lTmp := lBuffer;
for I := 0 to pSize - 1 do
begin
Result := Result + IntToHex(lTmp^, 2);
Inc(lTmp);
end;
DebugLog(Format('FSUIPC: Variable %x read as %s', [pOffset, Result]))
end
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error reading variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult))
finally
FreeMem(lBuffer);
end;
end;
end;
function TFSUIPCcontrol.GetString(pOffset: Cardinal; pSize: Short): String;
var
dwResult : DWORD;
lRes: Boolean;
lBuffer, lTmp: ^byte;
I: Integer;
begin
if not fConnected then
Open;
if fConnected then
begin
if (pSize < 0) or (pSize > 256) then
pSize := 256;
GetMem(lBuffer, pSize);
try
lRes := FSUIPC_Read(pOffset, pSize, lBuffer, dwResult);
if lRes then
begin
// "Read" proceeded without any problems
if FSUIPC_Process(dwResult) then
begin
System.SetString(Result, PChar(lBuffer), pSize);
lTmp := lBuffer;
for I := 0 to pSize - 1 do
begin
if lTmp^ = 0 then
begin
SetLength(Result, I);
break;
end;
Inc(lTmp);
end;
DebugLog(Format('FSUIPC: Variable %x read as %s', [pOffset, Result]))
end
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error reading variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult))
finally
FreeMem(lBuffer);
end;
end;
end;
function TFSUIPCcontrol.Open: Boolean;
var
dwResult : DWORD;
begin
if fConnected then
begin
FSUIPC_Close;
fConnected := False;
end;
// Try to connect to FSUIPC (or WideFS)
if FSUIPC_Open(SIM_ANY, dwResult) then
begin
fConnected := True;
DebugLog('FSUIPC: Connected, dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Not connected, dwResult ' + IntToStr(dwResult));
Result := fConnected;
end;
procedure TFSUIPCcontrol.SetFloat(pOffset: Cardinal; pSize: Short;
pValue: Double);
var
dwResult : DWORD;
begin
if not fConnected then
Open;
if fConnected then
begin
if (pSize <> 4) and (pSize <> 8) then
pSize := 8;
if FSUIPC_Write(pOffset, pSize, @pValue, dwResult) then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
DebugLog('FSUIPC: Variable ' + IntToHex(pOffset, 4) + ' set to '
+ FloatToStr(pValue))
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error setting variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end;
end;
procedure TFSUIPCcontrol.SetInt(pOffset: Cardinal; pSize: Short;
pValue: Int64);
var
dwResult : DWORD;
begin
if not fConnected then
Open;
if fConnected then
begin
if (pSize < 1) or (pSize > 8) then
pSize := 1;
if FSUIPC_Write(pOffset, pSize, @pValue, dwResult) then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
DebugLog('FSUIPC: Variable ' + IntToHex(pOffset, 4) + ' set to '
+ IntToStr(pValue))
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error setting variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end;
end;
procedure TFSUIPCcontrol.SetString(pOffset: Cardinal; pSize: Short;
pValue: String);
var
dwResult : DWORD;
lRes: Boolean;
lBuffer: ^byte;
I: Integer;
begin
if not fConnected then
Open;
if fConnected then
begin
if (pSize < 0) or (pSize > 256) then
pSize := 256;
GetMem(lBuffer, pSize);
try
//FillChar(lBuffer, pSize, 0);
StrLCopy(PChar(lBuffer), PChar(pValue), pSize-1); // +#0
if FSUIPC_Write(pOffset, pSize, lBuffer, dwResult) then
begin
// "Reed" proceeded without any problems
if FSUIPC_Process(dwResult) then
DebugLog('FSUIPC: Variable ' + IntToHex(pOffset, 4) + ' set to '
+ pValue)
else
DebugLog('FSUIPC: Error processing variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
end
else
DebugLog('FSUIPC: Error setting variable ' + IntToHex(pOffset, 4) +
' dwResult ' + IntToStr(dwResult));
finally
FreeMem(lBuffer);
end;
end;
end;
procedure TFSUIPCcontrol.DebugLog(Value: String);
begin
Glb.DebugLog(Value, 'FSUIPC');
end;
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Winapi.ShellAPI,
Redis.Commons,
Redis.Client,
Redis.NetLib.INDY,
Redis.Values
;
type
TForm2 = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Button1: TButton;
Panel3: TPanel;
Button2: TButton;
CheckBox1: TCheckBox;
Timer1: TTimer;
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
FRedis: IRedisClient;
procedure ProduzirEvento;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
ShellExecute(0, PChar('open'), PChar(Application.ExeName), nil, nil, SW_SHOW);
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
Self.ProduzirEvento();
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
Self.Panel1.Caption := Format('Produtor de Eventos - PID: %d', [GetCurrentProcessID]);
Self.FRedis := TRedisClient.Create('localhost', 6379);
Self.FRedis.Connect;
Self.Timer1.Enabled := True;
end;
procedure TForm2.ProduzirEvento;
var
sConteudo : string;
begin
sConteudo := Format('%d - AQUI PODERIA SER UM CONTE┌DO JSON', [GetCurrentProcessID]);
Self.FRedis.RPUSH('FILA:MOBILEDAYS:2020:VENDAS', [sConteudo]);
end;
procedure TForm2.Timer1Timer(Sender: TObject);
begin
Self.Timer1.Enabled := False;
try
if Self.CheckBox1.Checked then
Self.ProduzirEvento();
finally
Self.Timer1.Enabled := True;
end;
end;
end.
|
unit UpdateParameterValuesParamSubParamQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseQuery, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls;
type
TqUpdateParameterValuesParamSubParam = class(TQueryBase)
fdqDelete: TFDQuery;
fdqUpdate: TFDQuery;
private
{ Private declarations }
public
procedure ExecUpdateSQL(ANewParamSubParamID, AOldParamSubParamID, ACategoryID:
Integer);
class procedure DoUpdate(ANewParamSubParamID, AOldParamSubParamID, ACategoryId:
Integer); static;
class procedure DoDelete(AParamSubParamID, ACategoryId: Integer); static;
procedure ExecDeleteSQL(const AParamSubParamID, ACategoryID: Integer);
{ Public declarations }
end;
implementation
{$R *.dfm}
procedure TqUpdateParameterValuesParamSubParam.ExecUpdateSQL(
ANewParamSubParamID, AOldParamSubParamID, ACategoryID: Integer);
begin
Assert(ANewParamSubParamID > 0);
Assert(AOldParamSubParamID > 0);
Assert(ACategoryID > 0);
// Копируем запрос
FDQuery.SQL.Assign(fdqUpdate.SQL);
FDQuery.Params.Assign(fdqUpdate.Params);
SetParameters(['NewParamSubParamID', 'OldParamSubParamID', 'ProductCategoryId'],
[ANewParamSubParamID, AOldParamSubParamID, ACategoryID]);
// Выполняем SQL запрос
FDQuery.ExecSQL;
end;
class procedure TqUpdateParameterValuesParamSubParam.DoUpdate(
ANewParamSubParamID, AOldParamSubParamID, ACategoryId: Integer);
var
Q: TqUpdateParameterValuesParamSubParam;
begin
Q := TqUpdateParameterValuesParamSubParam.Create(nil);
try
Q.ExecUpdateSQL(ANewParamSubParamID, AOldParamSubParamID, ACategoryId);
finally
FreeAndNil(Q);
end;
end;
class procedure TqUpdateParameterValuesParamSubParam.DoDelete(AParamSubParamID,
ACategoryId: Integer);
var
Q: TqUpdateParameterValuesParamSubParam;
begin
Q := TqUpdateParameterValuesParamSubParam.Create(nil);
try
Q.ExecDeleteSQL(AParamSubParamID, ACategoryId);
finally
FreeAndNil(Q);
end;
end;
procedure TqUpdateParameterValuesParamSubParam.ExecDeleteSQL(const
AParamSubParamID, ACategoryID: Integer);
begin
Assert(AParamSubParamID > 0);
Assert(ACategoryID > 0);
// Копируем запрос
FDQuery.SQL.Assign(fdqDelete.SQL);
FDQuery.Params.Assign(fdqDelete.Params);
// Устанавливаем параметры запроса
SetParameters(['OldParamSubParamID', 'ProductCategoryId'],
[AParamSubParamID, ACategoryID]);
// Выполняем запрос
FDQuery.ExecSQL;
end;
end.
|
unit fGMV_PatientSelector;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, Buttons,
uGMV_ScrollListBox
, Math
;
type
TgetList = function:TStringList of object;
TfrmGMV_PatientSelector = class(TForm)
pnlStatus: TPanel;
pcMain: TPageControl;
tsUnit: TTabSheet;
tsTeam: TTabSheet;
tsClinic: TTabSheet;
tsWard: TTabSheet;
tsAll: TTabSheet;
Splitter1: TSplitter;
Splitter2: TSplitter;
Splitter3: TSplitter;
Splitter4: TSplitter;
pnlTitle: TPanel;
tmSearch: TTimer;
Button1: TButton;
Button2: TButton;
lblSelected: TLabel;
Bevel1: TBevel;
Label2: TLabel;
pnlInfo: TPanel;
lblPatientName: TLabel;
Label7: TLabel;
lblPatientLocationID: TLabel;
Label12: TLabel;
mmList: TMemo;
lblSelectStatus: TLabel;
pnlSelection: TPanel;
pnlPtInfo: TPanel;
lblSelectedName: TLabel;
lblPatientInfo: TLabel;
Panel3: TPanel;
lvUnitPatients: TListView;
Panel16: TPanel;
Panel11: TPanel;
Bevel2: TBevel;
Label14: TLabel;
Panel6: TPanel;
Panel17: TPanel;
cmbUnit: TComboBox;
lbUnits: TListBox;
Panel18: TPanel;
Bevel7: TBevel;
Label15: TLabel;
Panel1: TPanel;
lvWardPatients: TListView;
Panel15: TPanel;
Panel19: TPanel;
Bevel8: TBevel;
Label16: TLabel;
Panel7: TPanel;
Panel20: TPanel;
cmbWard: TComboBox;
lbWards: TListBox;
Panel21: TPanel;
Bevel9: TBevel;
Label17: TLabel;
Panel5: TPanel;
lvAllPatients: TListView;
Panel12: TPanel;
Panel22: TPanel;
Bevel10: TBevel;
Label18: TLabel;
Panel9: TPanel;
cmbAll: TComboBox;
Panel2: TPanel;
lvTeampatients: TListView;
Panel14: TPanel;
Panel23: TPanel;
Bevel11: TBevel;
Label19: TLabel;
Panel8: TPanel;
Panel24: TPanel;
cmbTeam: TComboBox;
lbTeams: TListBox;
Panel25: TPanel;
Bevel12: TBevel;
Label20: TLabel;
Panel4: TPanel;
lvClinicPatients: TListView;
Panel13: TPanel;
Panel26: TPanel;
Bevel13: TBevel;
Label21: TLabel;
pnlClinic: TPanel;
Panel27: TPanel;
cmbClinic: TComboBox;
Panel28: TPanel;
Bevel14: TBevel;
Label22: TLabel;
Bevel15: TBevel;
Label23: TLabel;
cmbPeriod: TComboBox;
pnlClinics: TPanel;
lbClinics0: TListBox;
sbClinics: TScrollBar;
Label1: TLabel;
Panel29: TPanel;
Label5: TLabel;
Label8: TLabel;
lblSelectedPatientNameID: TLabel;
Label9: TLabel;
lblSelectedPatientLocationNameID: TLabel;
lblTarget: TLabel;
Panel30: TPanel;
Label11: TLabel;
Label6: TLabel;
lblLocationName: TLabel;
tmrLoad: TTimer;
lblLoadStatus: TLabel;
procedure tmSearchTimer(Sender: TObject);
procedure pcMainChange(Sender: TObject);
procedure cmbUnitChange(Sender: TObject);
procedure lbUnitsClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbUnitsDblClick(Sender: TObject);
procedure lvUnitPatientsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure lvUnitPatientsKeyPress(Sender: TObject; var Key: Char);
procedure lvUnitPatientsDblClick(Sender: TObject);
procedure lbUnitsKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cmbUnitKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cmbUnitEnter(Sender: TObject);
procedure cmbUnitExit(Sender: TObject);
procedure lbUnitsEnter(Sender: TObject);
procedure lbUnitsExit(Sender: TObject);
procedure lvUnitPatientsEnter(Sender: TObject);
procedure lvUnitPatientsExit(Sender: TObject);
procedure cmbPeriodEnter(Sender: TObject);
procedure cmbPeriodExit(Sender: TObject);
procedure cmbPeriodChange(Sender: TObject);
procedure cmbAllChange(Sender: TObject);
procedure lvAllPatientsKeyPress(Sender: TObject; var Key: Char);
procedure cmbAllKeyPress(Sender: TObject; var Key: Char);
procedure lvUnitPatientsClick(Sender: TObject);
procedure pnlPtInfoMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pnlPtInfoMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cmbClinicKeyPress(Sender: TObject; var Key: Char);
procedure sbClinicsScroll(Sender: TObject; ScrollCode: TScrollCode;
var ScrollPos: Integer);
procedure sbClinicsChange(Sender: TObject);
procedure lbClinics0KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure pcMainMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cmbClinicChange(Sender: TObject);
procedure tmrLoadTimer(Sender: TObject);
procedure lbClinics0MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure lbClinics0MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fSelectedPatientName,
fSelectedPatientID,
fSelectedPatientLocationName,
fSelectedPatientLocationID: String;
fPatientID: string; //
fPatientLocationName,
fPatientLocationID,
fPatientName:String;
fLocationName,
fLocationCaption, // Name of Location record in the list
fLocationID:String;
fTarget: String;
fSource: TComboBox;
fListBox: TListBox;
fLV: TListView;
fGetList: TgetList;
fFound: Integer;
fIgnore:Boolean;
bDown: Boolean;
bUseLocationID:Boolean;
bLastClinicFound: Boolean;
sLastClinicFound: String;
fOnPatChange: TNotifyEvent;
function getUnitList:TStringList;
function getWardList:TStringList;
function getTeamList:TStringList;
function getClinicList:TStringList;
function getAllPatientList:TStringList;
procedure NotifyStart;
procedure NotifyEnd;
procedure setTarget(aValue:String);
function UpdateListView(aSource:TStrings;lvItems:TListItems;
iCaption,iSSN:Integer; iSubItems: array of Integer;aMode:Integer):Integer;
procedure ReportFoundItems(aCount:Integer;aMessage:String);
procedure SetPatientIEN(const Value: string);
procedure SetCurrentPatient;
procedure SetCurrentList;
function getSelectCount:Integer;
function getFocusedPatientID:String;
function UploadClinics(aTarget,aDirection:String;anOption:Word): Integer;
procedure FindClinics(aTarget:String);
function LookupClinicInTheList(aTarget:String):Integer;
procedure UpdateScrollBar;
public
// lbClinics: TListBox;
lbClinics: TNoVScrollListBox; // zzzzzzandria 2008-04-17
{ Public declarations }
bIgnore: Boolean;
bIgnorePtChange:Boolean; // zzzzzzandria 2008-03-07
iMSecondsToStart:Integer; //
sSecondsToStart:String; //
sStatus:String;
SelectionStatus:String;
property Target:String read fTarget write setTarget;
property FoundCount:Integer read fFound;
property SelectCount: Integer read getSelectCount;
property PatientGroup: TListBox read fListBox;
property PatientList: TListView read fLV;
property FocusedPatientID:String read getFocusedPatientID;
property PatientLocationID :String read fPatientLocationID;// zzzzzzandria 2007-10-04
property SelectedPatientName:String read fPatientName;
property SelectedPatientID: string read fSelectedPatientID write SetPatientIEN;
property SelectedPatientLocationName:String read fSelectedPatientLocationName;
property SelectedPatientLocationID:String read fSelectedPatientLocationID;
property OnPatChange: TNotifyEvent read FOnPatChange write FOnPatChange;
procedure SetUp;
procedure SetTimerInterval(sInterval:String);
procedure setInfo;
procedure clearInfo;
procedure SetCurrentLocation;
procedure SilentSearch;
procedure Search;
procedure ClearListView(aLV: TListView);
procedure setPatientLocationIDByFirstSelectedPatient; // zzzzzzandria 2008-02-28
end;
var
frmGMV_PatientSelector: TfrmGMV_PatientSelector;
function SelectPatientDFN(var aDFN: String; var aName:String): Boolean;
function getPatientSelectorForm: TfrmGMV_PatientSelector;
const
ssSelected = 'SELECTED';
ssInProgress = 'Selection In Progress';
var
iLoadLimit: Integer; //500;
implementation
uses uGMV_Common, uGMV_FileEntry, uGMV_Const, uGMV_Engine, uGMV_GlobalVars,
fGMV_PtSelect, uGMV_Patient, fGMV_PtInfo
, fGMV_UserMain, uGMV_Log, system.UITypes;
{$R *.dfm}
function getPatientSelectorForm: TfrmGMV_PatientSelector;
begin
EventAdd('get Patient Selector Form -- Begin');
if not Assigned(frmGMV_PatientSelector) then
begin
EventAdd('Create Patient Selector Form');
Application.CreateForm(TfrmGMV_patientSelector, frmGMV_PatientSelector);
frmGMV_PatientSelector.SetUp;
end;
Result := frmGMV_PatientSelector;
EventAdd('get Patient Selector Form -- Begin');
end;
function SelectPatientDFN(var aDFN: String; var aName:String): Boolean;
begin
EventAdd('Select Patient By DFN - start','DFN: '+aDFN);
Result := False;
if not Assigned(frmGMV_PatientSelector) then
begin
Application.CreateForm(TfrmGMV_patientSelector, frmGMV_PatientSelector);
frmGMV_PatientSelector.SetUp;
end;
if frmGMV_PatientSelector = nil then exit;
if frmGMV_PatientSelector.ShowModal = mrOK then
begin
frmGMV_PatientSelector.tmSearch.Enabled := False;
aName := frmGMV_PatientSelector.SelectedPatientName;
aDFN := frmGMV_PatientSelector.SelectedPatientID;
Result := True;
end;
EventAdd('Select Patient By DFN - stop','DFN: '+aDFN+ ', Name: '+aName);
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.FormCreate(Sender: TObject);
// zzzzzzandria 5.0.23.6 20090218 --------------------------------------------
procedure setLV(aListView: TListView;aValue: Boolean =True);
var
i: Integer;
begin
for i := 0 to aListView.Columns.Count - 1 do
aListView.Columns[i].AutoSize := aValue;
end;
// zzzzzzandria 5.0.23.6 20090218 --------------------------------------------
begin
SelectionStatus := '';
bIgnorePtChange := False;
bIgnore := False;
fIgnore := False;
fFound := 0;
pcMain.ActivePageIndex := 0;
fGetList := getUnitList;
fSource := cmbUnit;
fLV := lvUnitPatients;
fListBox := lbUnits;
lblSelected.Caption := '';
lblSelected.Visible := False;
pnlInfo.Visible := False;
lblPatientName.Caption := '';
lblPatientLocationID.Caption := '';
cmbUnit.Color := clTabIn;
cmbWard.Color := clTabIn;
cmbTeam.Color := clTabIn;
cmbClinic.Color := clTabIn;
cmbAll.Color := clTabIn;
lbClinics := TNoVScrollListBox.Create(pnlClinics);
// lbClinics := TListBox.Create(pnlClinics);
// lbClinics.Sorted := True;
lbClinics.Align := alClient;
lbClinics.Parent := pnlClinics;
lbClinics.Color := clWindow;
lbClinics.OnClick := lbUnitsClick;
lbClinics.OnDblClick := lbUnitsDblClick;
lbClinics.OnEnter := lbUnitsEnter;
lbClinics.OnExit := lbUnitsExit;
lbClinics.OnKeyDown := lbClinics0KeyDown;//lbClinics.OnKeyDown:=lbUnitsKeyDown;
lbClinics.OnMouseDown := lbClinics0MouseDown;
lbClinics.OnMouseUp := lbClinics0MouseUp;
bLastClinicFound := False;
sLastClinicFound := '';
{
setLV(lvUnitPatients); // zzzzzzandria 5.0.23.6 20090218
setLV(lvWardPatients); // zzzzzzandria 5.0.23.6 20090218
setLV(lvAllPatients); // zzzzzzandria 5.0.23.6 20090218
setLV(lvTeampatients); // zzzzzzandria 5.0.23.6 20090218
setLV(lvClinicPatients); // zzzzzzandria 5.0.23.6 20090218
}
end;
procedure TfrmGMV_PatientSelector.FormDestroy(Sender: TObject);
begin
ClearListView(lvAllPatients);
ClearListView(lvUnitPatients);
ClearListView(lvWardPatients);
ClearListView(lvTeamPatients);
ClearListView(lvClinicPatients);
end;
procedure TfrmGMV_PatientSelector.Setup;
var
sl: TStringList;
procedure setLoadLimit;
var
sLoadLimit: String;
begin
if cmdLineSwitch(['ll','LL','LOADLIMIT','LoadLimit'],sLoadLimit) then
iLoadLimit := StrToIntDef(sLoadLimit,iLoadLimit);
end;
procedure setLB(aLB: TListBox;aSL: TStringList);
begin
try
aLB.Items.Clear;
aLB.Items.Assign(aSL);
except
end;
end;
begin
bIgnore := True; // zzzzzzandria 2008-03-07
bIgnorePtChange := True;
if GMVNursingUnits.Entries.Count < 1 then GMVNursingUnits.LoadEntries('211.4');
SetLB(lbUnits, GMVNursingUnits.Entries);
if GMVWardLocations.Entries.Count < 1 then GMVWardLocations.LoadWards;
SetLB(lbWards, GMVWardLocations.Entries);
if GMVTeams.Entries.Count < 1 then GMVTeams.LoadEntries('100.21');
SetLB(lbTeams, GMVTeams.Entries);
{$IFDEF LOADLIMITPARAM}
setLoadLimit;
{$ENDIF}
if GMVClinics.Entries.Count < 1 then
begin
SL := getClinicFileEntriesByName('',intToStr(iLoadLimit),'1');
if Assigned(SL) then
begin
try
GMVClinics.Entries.Assign(SL);
SetLB(lbClinics, GMVClinics.Entries);
sLastClinicFound := SL[SL.Count-1];
finally
SL.Free;
end;
end;
end;
// tmrLoad.Enabled := true; -- no background load
if (lbClinics.Items.Count > 0) and (pcMain.ActivePage= tsClinic) then
begin
lbClinics.setFocus; // zzzzzzandria 060920 -- commented to avoid RTE
UpdateScrollBar;
end;
bIgnorePtChange := False;
bIgnore := False; // zzzzzzandria 2008-03-07
EventAdd('Patient Selector Setup Performed');
end;
procedure TfrmGMV_PatientSelector.SetTimerInterval(sInterval:String);
begin
sSecondsToStart := sInterval;
iMSecondsToStart := round(StrToFloat(GMVSearchDelay)*1000.0);
end;
procedure TfrmGMV_PatientSelector.SetPatientIEN(const Value: string);
begin
fSelectedPatientID := Value;
if Assigned(FOnPatChange) then
FOnPatChange(Self);
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.ReportFoundItems(aCount:Integer;aMessage:String);
begin
if aCount = 0 then
begin
if not bIgnore then
MessageDlg(aMessage, mtInformation, [mbok], 0);
end
else
begin
try
if GetParentForm(Self).Visible then // zzzzzzandria 2007-07-16
GetParentForm(Self).Perform(WM_NEXTDLGCTL, 0, 0);
except // zzzzzzandria 2007-07-16
end; // zzzzzzandria 2007-07-16
lblSelected.Caption := 'Found: '+IntToStr(aCount);
end;
end;
function TfrmGMV_PatientSelector.getUnitList:TStringList;
var
RetList: TStringList;
begin
fPatientLocationID := '';
fPatientLocationName := '';
RetList := getNursingUnitPatients(fLocationID);
if RetList.Count < 1 then
fFound := 0
else
fFound := UpdateListView(RetList,lvUnitPatients.Items,2,3,[4],0);
sStatus := Format('%d patients found for nursing unit %s',[fFound,fLocationName]);
ReportFoundItems(fFound,sStatus);
Result := Retlist;
end;
function TfrmGMV_PatientSelector.getWardList:TStringList;
var
RetList: TStringList;
begin
RetList := getWardPatients(fLocationName);
if RetList.Count < 1 then
fFound := 0
else
fFound := UpdateListView(RetList,lvWardPatients.Items,2,3,[4],1);
{
if fFound > 0 then
begin
fPatientLocationID := fLocationID;
fPatientLocationName := fLocationName;
end;
}
sStatus := Format('%d patients found for the ward <%s>',[fFound,fLocationName]);
ReportFoundItems(fFound,sStatus);
Result := retList;
end;
function TfrmGMV_PatientSelector.getTeamList:TStringList;
var
RetList: TStringList;
begin
fPatientLocationID := '';
fPatientLocationName := '';
RetList := getTeampatients(fLocationID);
if RetList.Count < 1 then
fFound := 0
else
if RetList[0] = 'NO PATIENTS' then fFound := 0
else fFound := UpdateListView(RetList,lvTeamPatients.Items,1,3,[4],2);
sStatus := Format('%d patients found for the team <%s>',[fFound,fLocationName]);
ReportFoundItems(fFound,sStatus);
Result := RetList;
end;
function TfrmGMV_PatientSelector.getClinicList:TStringList;
var
RetList: TStringList;
sFailourReason:String;
begin
if (fLocationName<>'') and (cmbPeriod.Text <> '') then
begin
RetList := getClinicPatients(fLocationCaption,cmbPeriod.Text);
sFailourReason := '';
if (RetList.Count < 1) then
fFound := 0
else if pos('No patient',RetList[0]) <> 0 then
fFound := 0
else if pos('No clinic',RetList[0]) <> 0 then
begin
fFound := 0;
sFailourReason := 'Check clinic name';
end
else if pos('ERROR',Uppercase(RetList[0])) <> 0 then
begin
fFound := 0;
if pos('^',RetList[0]) > 0 then
sFailourReason := piece(RetList[0],'^',2)
else
sFailourReason := RetList[0];
end
else
fFound := UpdateListView(RetList,lvClinicPatients.Items,2,5,[6,4],3);
sStatus := Format('%d patient apointments found for:'+#13+
#13+'Clinic: <%s>'+
#13+'Date: <%s>'+
#13+#13+'%s',[fFound,fLocationName,cmbPeriod.Text,sFailourReason]);
if fFound > 0 then
begin
lvClinicPatients.ItemFocused := lvClinicPatients.Items[0];
GetParentForm(Self).Perform(CM_SELECTPTLIST, 0, 0);
end;
ReportFoundItems(fFound,sStatus);
Result := RetList;
end
else
Result := nil;
end;
function TfrmGMV_PatientSelector.getAllPatientList:TStringList;
var
RetList: TStringList;
begin
fPatientLocationID := '';
fPatientLocationName := '';
RetList := getPatientList(Target);
if Piece(RetList[0], '^', 1) = '-1' then
begin
fFound := 0;
GetParentForm(Self).Perform(CM_PTLISTNOTFOUND, 0, 0); //AAN 07/22/02
MessageDlg(Piece(RetList[0], '^', 2), mtInformation, [mbok], 0);
end
else
begin
RetList.Delete(0);
fFound := UpdateListView(RetList,lvAllPatients.Items,2,11,[10],4);
// zzzzzzandria 2008-03-10 commenting out message to parent form
// parent form will be notified later
// GetParentForm(Self).Perform(CM_PTLISTCHANGED, RetList.Count, 0); //AAN 08/30/02
end;
Result := RetList;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.SilentSearch;
var
tmpList: TStringList;
begin
pcMain.Enabled := False; // zzzzzzandria 2008-04-15
eventAdd('Silent Search');
if assigned(fGetList) then
begin
ClearListView(fLV);
tmSearch.Enabled := False;
tmpList := fGetList;
GetParentForm(Self).Perform(CM_PTLISTCHANGED, 0, 0);
tmpList.Free;
pcMain.Enabled := True; // zzzzzzandria 2008-05-12
if fFound > 0 then
begin
fLV.TabStop := true;
fLV.Enabled := true;
Application.ProcessMessages;
try
fLV.Selected := fLV.Items[0];
if self.Visible then // zzzzzzandria 2007-07-16
fLV.SetFocus;
except
end;
end
else
begin
fLV.TabStop := False;
fLV.Enabled := False;
end;
end;
pcMain.Enabled := True; // zzzzzzandria 2008-04-15
if not self.Visible then
exit; // zzzzzzandria 2008-11-03
if pcMain.ActivePage = tsClinic then
try
if fFound = 0 then
cmbPeriod.SetFocus;
except
// on E: Exception do
// ShowMessage(E.Message);
end;
end;
procedure TfrmGMV_PatientSelector.Search;
begin
NotifyStart;
SilentSearch;
NotifyEnd;
end;
procedure TfrmGMV_PatientSelector.tmSearchTimer(Sender: TObject);
begin
if iMSecondsToStart >= 500 then
begin
iMSecondsToStart := iMSecondsToStart - 500;
sSecondsToStart := Format('%3.1n',[iMSecondsToStart/1000.0]);
lblSelected.Caption := 'Seconds to start: '+sSecondsToStart;
GetParentForm(Self).Perform(CM_PTSEARCHDelay, 0, 0); //AAN 07/22/02
end
else
begin
tmSearch.Enabled := False;
if pcMain.ActivePage = tsAll then
Search
else
if pcMain.ActivePage = tsClinic then
FindClinics(cmbClinic.Text);
end;
end;
procedure TfrmGMV_PatientSelector.clearInfo;
begin
lblPatientName.Caption := '...';
lblLocationName.Caption := '...';
lblPatientLocationID.Caption := '';
lblSelectedPatientNameID.Caption := '';
lblSelectedPatientLocationNameID.Caption := '';
lblSelectStatus.Caption := '?';
end;
procedure TfrmGMV_PatientSelector.setInfo;
begin
try
lblTarget.Caption := fSource.Text;
lblSelectedPatientNameID.Caption :=
fSelectedPatientName + ' /' + fSelectedPatientID;
lblSelectedPatientLocationNameID.Caption :=
fSelectedPatientLocationName + ' /' + fSelectedPatientLocationID;
lblLocationName.Caption := fLocationName + ' / ' + fLocationID;
lblSelectStatus.Caption := SelectionStatus;
lblPatientName.Caption := fPatientName + ' / '+ fPatientID;
lblPatientLocationID.Caption := fPatientLocationName + ' / ' + fPatientLocationID;
if SelectionStatus <> ssSelected then
begin
lblSelectedName.Caption := 'No Patient Selected';
lblPatientInfo.Caption := '000-00-0000';
end;
except
ClearInfo;
end;
end;
procedure TfrmGMV_PatientSelector.SetCurrentList;
var
i: Integer;
begin
eventAdd('Set Current List',fLV.Name);
mmList.Lines.Clear;
for i := 0 to fLV.Items.Count - 1 do
if (fLV.Items[i].Selected)
and Assigned(fLV.Items[i].Data) // zzzzzzandria 2007-07-17
then
mmList.Lines.Add(fLV.Items[i].Caption+' / '+
TGMV_FileEntry(fLV.Items[i].Data).IEN);
GetParentForm(Self).Perform(CM_PTLISTCHANGED, 0, 0); // zzzzzzandria 050518
end;
procedure TfrmGMV_PatientSelector.pcMainChange(Sender: TObject);
const
iUnit = 0;
iWard = 1;
iTeam = 2;
iClinic = 3;
iAll = 4;
begin
eventAdd('Page Control Change', 'Selected Tab: '+pcMain.ActivePage.Name);
tmSearch.Enabled := False;
lblSelected.Caption := '';
clearInfo;
case pcMain.ActivePageIndex of
iUnit: begin
fSource := cmbUnit;
fLV := lvUnitPatients;
fListBox := lbUnits;
fGetList := getUnitList;
bUseLocationID := False;
end;
iWard: begin
fSource := cmbWard;
fLV := lvWardPatients;
fListBox := lbWards;
fGetList := getWardList;
bUseLocationID := True;
end;
iTeam: begin
fSource := cmbTeam;
fLV := lvTeampatients;
fListBox := lbTeams;
fGetList := getTeamList;
bUseLocationID := False;
end;
iClinic: begin
fSource := cmbClinic;
fLV := lvClinicPatients;
fListBox := lbClinics;
fGetList := getClinicList;
bUseLocationID := True;
end;
iAll: begin
fSource := cmbAll;
fLV := lvAllPatients;
fListBox := nil;
fGetList := getAllPatientList;
bUseLocationID := False;
end;
end;
Target := fSource.Text;
try
if self.Visible then // zzzzzzandria 2007-07-16
fSource.SetFocus;
except
on e: Exception do
begin
end;
end;
SetCurrentLocation;
SetCurrentPatient;
SetCurrentList;// list of selected patients, sends message to parent form
SelectionStatus := 'Not selected';
SetInfo;
end;
procedure TfrmGMV_PatientSelector.setTarget(aValue:String);
begin
tmSearch.Enabled := False;
fTarget := aValue;
end;
procedure TfrmGMV_PatientSelector.NotifyStart;
begin
lblSelected.Caption := 'Search...';
GetParentForm(Self).Perform(CM_PTSEARCHING, 0, 0); //AAN 07/22/02
end;
procedure TfrmGMV_PatientSelector.NotifyEnd;
begin
GetParentForm(Self).Perform(CM_PTSEARCHDONE, 0, 0); //AAN 07/18/02
lblSelected.Caption := 'Found: '+IntToStr(fFound);;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.cmbUnitChange(Sender: TObject);
var
i: integer;
Found: Boolean;
LookFor: string;
begin
if fIgnore then Exit;
if fListBox <> nil then
begin
Found := False;
ClearListView(fLV);
Target := fSource.Text; // get search target
if Target <> '' then
begin
i := 0;
LookFor := LowerCase(Target);
while (i < fListBox.Items.Count) and (not Found) do
begin
if LowerCase(Copy(fListBox.Items[i], 1, Length(LookFor))) = LookFor then
begin
fListBox.ItemIndex := i;
fSource.Text := fListBox.Items[i];
fSource.SelStart := Length(LookFor);
fSource.SelLength := Length(fSource.Text);
Found := True;
end
else
inc(i);
end;
end;
if not Found then fListBox.ItemIndex := -1;
end;
SelectionStatus := ssInProgress;
SetInfo;
end;
procedure TfrmGMV_PatientSelector.cmbPeriodChange(Sender: TObject);
begin
if fIgnore Then Exit;
if (fSource.Text <> '') and (cmbPeriod.Text<>'') then
lbUnitsDblClick(nil);
end;
procedure TfrmGMV_PatientSelector.cmbAllChange(Sender: TObject);
var
s: String;
begin
if fIgnore then s := 'True'
else s := 'False';
EventAdd('Search Target Changed', 'Ignore:'+ s+' LV: '+fLV.Name + ' Target: '+fSource.Text);
if fIgnore Then Exit;
ClearListView(fLV);
Target := fSource.Text; // get search target
tmSearch.Enabled := fSource.Text <> ''; // start countdouwn
SetTimerInterval(GMVSearchDelay);
GetParentForm(Self).Perform(CM_PTSEARCHKBMODE, 0, 0); //AAN 07/18/02
SelectionStatus := ssInProgress;
SetInfo;
end;
function TfrmGMV_PatientSelector.UpdateListView(aSource:TStrings;lvItems:TListItems;
iCaption,iSSN:Integer; iSubItems: array of Integer;aMode:Integer):Integer;
var
b: Boolean;
s:String;
ii,jj,
iFound: Integer;
const
Delim = '^';
procedure setNameWidth(aName:String);
var
lv: TListView;
j: Integer;
begin
if lvItems.Owner is TListView then
begin
lv := TListView(lvItems.Owner);
for j := 0 to lv.Columns.Count - 1 do
begin
if lv.Column[j].Caption <> 'Name' then
continue;
if lv.Columns[j].Width < lv.Canvas.TextWidth(aName)+8 then
lv.Columns[j].Width := lv.Canvas.TextWidth(aName)+8;
end;
end;
end;
begin
iFound := 0;
lvItems.BeginUpdate;
b := bIgnorePtChange; // zzzzzzandria 2008-03-07
bIgnorePtChange := True; // zzzzzzandria 2008-03-07
for jj := 0 to aSource.Count - 1 do
begin
s := aSource[jj];
if pos('-1',s)= 1 then Continue;
with lvItems.Add do
begin
Caption := Piece(s,Delim,iCaption);
setNameWidth(Caption);
SubItems.Add(FormatSSN(Piece(s, Delim, iSSN)));
for ii := Low(iSubItems) to High(iSubItems) do
SubItems.Add(Piece(s, Delim, iSubItems[ii]));
case aMode of
0: Data := TGMV_FileEntry.CreateFromRPC('2;' + s);// Nursing Unit
1: Data := TGMV_FileEntry.CreateFromRPC('2;' + s);// PtWard
2: Data := TGMV_FileEntry.CreateFromRPC('2;' + Piece(s, '^', 2) + '^' + Piece(s, '^', 1)); // Team
3: Data := TGMV_FileEntry.CreateFromRPC('2;' + s);// Clinic
4: Data := TGMV_FileEntry.CreateFromRPC(s);// Patients
end;
inc(iFound);
end;
end;
lvItems.EndUpdate;
Result := iFound;
bIgnorePtChange := b; // zzzzzzandria 2008-03-07
end;
procedure TfrmGMV_PatientSelector.ClearListView(aLV: TListView);
var
i: integer;
b: Boolean;
begin
eventAdd('Clean List View',aLV.Name);
aLV.Items.BeginUpdate;
b := bIgnorePtChange; // zzzzzzandria 2008-03-07
bIgnorePtChange := True; // zzzzzzandria 2008-03-07
for i := 0 to aLV.Items.Count - 1 do
if aLV.Items[i].Data <> nil then
begin
TGMV_FileEntry(aLV.Items[i].Data).Free;
aLV.Items[i].Data := nil;
end;
aLV.Items.Clear;
aLV.Items.EndUpdate;
bIgnorePtChange := b; // zzzzzzandria 2008-03-07
SetCurrentPatient;
GetParentForm(Self).Perform(CM_PTLISTCHANGED, 0, 0);
end;
////////////////////////////////////////////////////////////////////////////////
// lbUnitsClick, DblClick, Enter, Exit, KeyDoun methods will be used
// for all inteface elements
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.lbUnitsClick(Sender: TObject);
begin
try
fSource.Text := fListBox.Items[fListBox.ItemIndex];
if Sender <> lbClinics then // 2008-06-20
begin
if (fSource.Text <>'') and (pos(fSource.Text+#13,fSource.Items.Text)=0) then
fSource.Items.Insert(0,fSource.Text);
if fSource.Items.Count > 3 then
fSource.Items.Delete(3);
end;
SetCurrentLocation;
SelectionStatus := 'In progress';
ClearListView(fLV);
setInfo;
except
end;
end;
procedure TfrmGMV_PatientSelector.lbUnitsDblClick(Sender: TObject);
begin
GetParentForm(Self).Perform(CM_PTSEARCHSTART, 0, 0); //AAN 07/18/02
tmSearch.Enabled := False;
SilentSearch;
end;
procedure TfrmGMV_PatientSelector.lvUnitPatientsDblClick(Sender: TObject);
var
s: String;
Patient:TPatient;
begin
SelectionStatus := '';
with fLV do
if Selected <> nil then
begin
s := TGMV_FileEntry(Selected.Data).IEN;
Patient := SelectPatientByDFN(s);
if Patient <> nil then
begin
Screen.Cursor := crHourGlass;
fPatientID := s;
fPatientName := Selected.Caption;
fSelectedPatientName := fPatientName;
if bUseLocationID then // Wards and Clinics
begin
fSelectedPatientLocationName := fLocationName;
fSelectedPatientLocationID := fLocationID;
// fSelectedPatientLocationName := Patient.LocationName; // zzzzzzandria 060608
// fSelectedPatientLocationID := Patient.LocationID; // zzzzzzandria 060608
end
else
begin // Nursing Units, Teams, All
fSelectedPatientLocationName := '';
fSelectedPatientLocationID := '';
if Patient.LocationName <> '' then
begin
fSelectedPatientLocationName := Patient.LocationName;
fSelectedPatientLocationID := Patient.LocationID;
end
end;
SelectionStatus := ssSelected;
lblSelectedName.Caption := Patient.Name;
lblPatientInfo.Caption := Patient.SSN + ' '+Patient.Age;
// No need in sending a message. OnPatSelect will be called instead
// GetParentForm(Self).Perform(CM_PATIENTFOUND, 0, 0); //AAN 06/11/02
// GetParentForm(Self).Perform(WM_NEXTDLGCTL, 0, 0);
SelectedPatientID := fPatientID; // Assignment will invoke OnPatSelect
Screen.Cursor := crDefault;
FreeAndNil(Patient);
end //AAN 06/11/02
else
Selected := nil;
end
else
begin
fPatientID := '';
fPatientName := '';
fSelectedPatientName := fPatientName;
fSelectedPatientID := fPatientID;
fSelectedPatientLocationName := fLocationName;
fSelectedPatientLocationID := fLocationID;
end;
SetInfo;
end;
procedure TfrmGMV_PatientSelector.lvUnitPatientsKeyPress(Sender: TObject;
var Key: Char);
begin
case Key of
char(VK_RETURN): if fLV.SelCount = 1 then lvUnitPatientsDblClick(Sender);
else
end;
end;
procedure TfrmGMV_PatientSelector.lbUnitsKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case Key of
VK_RETURN: if (fListBox.ItemIndex > - 1) then lbUnitsDblClick(Sender);
end;
end;
procedure TfrmGMV_PatientSelector.cmbUnitKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
with fSource do
case Key of
VK_RETURN:
if (fListBox.ItemIndex > -1) then
begin
Key := 0;
lbUnitsClick(nil);
lbUnitsDblClick(Sender);
end;
VK_Back:
if (SelLength > 0) then
begin
fIgnore := True;
Text := Copy(Text, 1, SelStart - 1);
Key := 0;
fIgnore := False;
end;
end;
end;
procedure TfrmGMV_PatientSelector.cmbUnitEnter(Sender: TObject);
begin
fSource.Color := clTabIn;
end;
procedure TfrmGMV_PatientSelector.cmbUnitExit(Sender: TObject);
begin
fSource.Color := clTabOut;
end;
procedure TfrmGMV_PatientSelector.lbUnitsEnter(Sender: TObject);
begin
fListBox.Color := clTabIn;
end;
procedure TfrmGMV_PatientSelector.lbUnitsExit(Sender: TObject);
begin
fListBox.Color := clTabOut;
end;
procedure TfrmGMV_PatientSelector.lvUnitPatientsEnter(Sender: TObject);
begin
fLV.Color := clTabIn;
end;
procedure TfrmGMV_PatientSelector.lvUnitPatientsExit(Sender: TObject);
begin
fLV.Color := clTabOut;
end;
procedure TfrmGMV_PatientSelector.cmbPeriodEnter(Sender: TObject);
begin
cmbPeriod.Color := clTabIn;
end;
procedure TfrmGMV_PatientSelector.cmbPeriodExit(Sender: TObject);
begin
cmbPeriod.Color := clTabOut;
end;
procedure TfrmGMV_PatientSelector.lvAllPatientsKeyPress(Sender: TObject;
var Key: Char);
begin
case Key of
char(VK_RETURN): if fLV.SelCount = 1 then lvUnitPatientsDblClick(Sender);
end;
end;
procedure TfrmGMV_PatientSelector.cmbAllKeyPress(Sender: TObject;
var Key: Char);
begin
if Key = char(VK_RETURN)
then Search;
end;
procedure TfrmGMV_PatientSelector.SetCurrentPatient;
begin
if (fLV.Selected <> nil)
and Assigned(fLV.Selected.Data) // zzzzzzandria 2007-07-17
then
begin
try
fPatientID := TGMV_FileEntry(fLV.Selected.Data).IEN;
fPatientName := fLV.Selected.Caption;
except
fPatientID := '';
fPatientName := '';
end;
end
else
begin
fPatientID := '';
fPatientName := '';
end;
end;
procedure TfrmGMV_PatientSelector.lvUnitPatientsChange(Sender: TObject;
Item: TListItem; Change: TItemChange);
var
f: TCustomForm;
begin
// if bIgnorePtChange then Exit; // zzzzzzandria 2008-03-07
SetCurrentPatient;
SelectionStatus := ssInProgress;
// setCurrentList; -- commented 2008-02-27 zzzzzzandria
// zzzzzzandria 2008-02-27 ----------------------------------------------- begin
if (FocusedPatientID =SelectedPatientID) and
(FocusedPatientID <> '') then
begin
fPatientLocationID := fSelectedPatientLocationID;
fPatientLocationName := fSelectedPatientLocationName;
end
else
begin
if (Sender = lvTeamPatients) or (Sender = lvAllPatients) then
begin
fPatientLocationID := '';
fPatientLocationName := '';
end
else
begin
fPatientLocationID := fLocationID;
fPatientLocationName := fLocationName;
end;
end;
eventAdd(
'Focused Patient changed',
'---------------------------'+#13#10+
'Item:..................... '+ Item.Caption+#13#10+
'Selected Pt ID:........... '+SelectedPatientID + #13#10+
'Focused Pt ID:............ '+FocusedPatientID + #13#10+
'Selected Pt Location ID:.. '+fSelectedPatientLocationID + #13#10+
'Selected Pt Location Name: '+fSelectedPatientLocationName + #13#10+
'Pt Location ID:........... '+fLocationID + #13#10+
'Pt Location Name:......... '+fLocationName);
// zzzzzzandria 2008-02-27 ------------------------------------------------- end
setInfo;
// if not bIgnore then // zzzzzzandria 2008-03-07
f := GetParentForm(Self);
if Assigned(f) then
f.Perform(CM_PTLISTCHANGED, fLV.Items.Count, 0);
end;
procedure TfrmGMV_PatientSelector.SetCurrentLocation;
begin
// zzzzzzandria 2007-07-12 ----------------------------------------------- begin
fLocationID := '';
fLocationCaption := '';
fLocationName := '';
if Assigned(fListBox) and (fListBox.ItemIndex>-1) and Assigned(fListBox.Items.Objects[fListBox.ItemIndex]) then
// zzzzzzandria 2007-07-12 ------------------------------------------------- end
try
fLocationID := TGMV_FileEntry(fListBox.Items.Objects[fListBox.ItemIndex]).IEN;
fLocationCaption := TGMV_FileEntry(fListBox.Items.Objects[fListBox.ItemIndex]).Caption;
fLocationName := fListBox.Items[fListBox.ItemIndex];
except
fLocationID := '';
fLocationCaption := '';
fLocationName := '';
end;
if bUseLocationID then
begin
fPatientLocationName := fLocationName;
fPatientLocationID := fLocationID;
end
else
begin
fPatientLocationName := '';
fPatientLocationID := '';
end;
end;
procedure TfrmGMV_PatientSelector.lvUnitPatientsClick(Sender: TObject);
begin
SelectionStatus := ssInProgress;
SetCurrentList;
SetInfo;
end;
function TfrmGMV_PatientSelector.getSelectCount:Integer;
begin
Result := fLV.SelCount;
end;
procedure TfrmGMV_PatientSelector.pnlPtInfoMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pnlPtInfo.BevelOuter := bvLowered;
end;
procedure TfrmGMV_PatientSelector.pnlPtInfoMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
pnlPtInfo.BevelOuter := bvRaised;
if SelectionStatus = ssSelected then
ShowPatientInfo(SelectedPatientID,'')
else
MessageDlg('Select Patient first.', mtInformation,[mbOk], 0);
end;
function TfrmGMV_PatientSelector.getFocusedPatientID:String;
begin
Result := '';
if Assigned(fLV) and (fLV.Items.Count > 0) then
try
if (fLV.ItemIndex> - 1) and Assigned(fLV.Items[fLV.ItemIndex].Data) then // zzzzzzandria 2007-12-16
Result := TGMV_FileEntry(fLV.Items[fLV.ItemIndex].Data).IEN;
except
end;
end;
procedure TfrmGMV_PatientSelector.setPatientLocationIDByFirstSelectedPatient; // zzzzzzandria 2008-02-28
var
s: String;
begin
s := getHospitalLocationByID(FocusedPatientID);
if s = '0' then
fPatientLocationID := ''
else
fPatientLocationID := s;
end;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.sbClinicsScroll(Sender: TObject;
ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
case ScrollCode of
scLineUp: SendMessage(lbClinics.Handle, WM_KEYDOWN, VK_UP, 1);
scLineDown: SendMessage(lbClinics.Handle, WM_KEYDOWN, VK_DOWN, 1);
end;
end;
procedure TfrmGMV_PatientSelector.UpdateScrollBar;
begin
sbClinics.Min := 0;
if GMVClinics.Entries.Count > 0 then
sbClinics.Max := GMVClinics.Entries.Count - 1
else
sbClinics.Max := 0;
sbClinics.enabled := sbClinics.Max > 0;
end;
procedure TfrmGMV_PatientSelector.sbClinicsChange(Sender: TObject);
begin
if not lbClinics.Focused then
lbClinics.SetFocus;
lbClinics.ItemIndex := sbClinics.Position;
end;
function TfrmGMV_PatientSelector.LookupClinicInTheList(aTarget:String):integer;
var
i: integer;
LookFor: string;
begin
Result := -1;
if fListBox <> nil then
begin
ClearListView(fLV);
if aTarget <> '' then
begin
i := 0;
LookFor := LowerCase(aTarget);
while (i < fListBox.Items.Count) do
begin
if LowerCase(Copy(fListBox.Items[i], 1, Length(LookFor))) = LookFor then
begin
Result := i;
break;
end
else
inc(i);
end;
end;
end;
end;
procedure TfrmGMV_PatientSelector.cmbClinicChange(Sender: TObject);
var
i: integer;
iLen: Integer;
begin
if fIgnore then Exit;
iLen := Length(fSource.Text);
i := LookupClinicInTheList(fSource.Text);
if i >=0 then
begin
fListBox.ItemIndex := i;
fSource.Text := fListBox.Items[i];
fSource.SelStart := iLen;
fSource.SelLength := iLen;
end
else
fListBox.ItemIndex := -1;
SelectionStatus := ssInProgress;
SetInfo;
end;
function TfrmGMV_PatientSelector.UploadClinics(aTarget, aDirection: String;
anOption: Word): Integer;
var
s, sSelected, sTarget, sCount: String;
iSelected, iSL, iIndex: Integer;
fe: TGMV_FileEntry;
sl: TStringList;
begin
Result := 0;
sCount := intToStr(iLoadLimit);
sTarget := aTarget;
iSelected := fListBox.ItemIndex;
if iSelected < 0 then
iSelected := 0;
sSelected := fListBox.Items[iSelected];
sl := getClinicFileEntriesByName(aTarget, sCount, aDirection);
if Assigned(sl) then
begin
try
Result := sl.Count;
for iSL := 0 to sl.Count - 1 do
begin
s := sl[iSL];
iIndex := GMVClinics.Entries.IndexOf(s);
fe := TGMV_FileEntry(sl.Objects[iSL]);
if iIndex >= 0 then
try
if Assigned(fe) then
fe.Free;
except
end
else
begin
if aDirection = '1' then
begin
GMVClinics.Entries.AddObject(sl[iSL], fe);
fListBox.Items.Add(sl[iSL]); // zzzzzzandria 2008-04-15
end
else
begin
GMVClinics.Entries.InsertObject(0, sl[iSL], fe);
fListBox.Items.Insert(0, sl[iSL]); // zzzzzzandria 2008-04-15
end;
end;
end;
Finally
SL.Free;
end;
end;
UpdateScrollBar;
end;
// zzzzzzandria 2008-04-11 =============================================== begin
procedure TfrmGMV_PatientSelector.FindClinics(aTarget:String);
var
iPos: Integer;
iCount: Integer;
iLen: Integer;
procedure ClearClinics;
var
i: Integer;
fe: TGMV_FileEntry;
begin
for i := 0 to GMVClinics.Entries.Count - 1 do
begin
fe := TGMV_FileEntry(GMVClinics.Entries.Objects[i]);
if Assigned(fe) then
fe.Free;
end;
GMVClinics.Entries.Clear;
end;
procedure setPos(aPos,aLen:Integer);
begin
fListBox.ItemIndex := aPos;
fSource.Text := fListBox.Items[aPos];
fSource.SelStart := aLen;
fSource.SelLength := Length(fSource.Text);
end;
begin
iLen := Length(aTarget);
iPos := LookupClinicInTheList(aTarget);
if iPos >= 0 then
setPos(iPos,iLen)
else
begin
ClearClinics; // Clean up GMVClinics list
iCount := UploadClinics(aTarget,'1',0); // Reload Clinics based on target
if iCount > 0 then
begin
try
lbClinics.Items.Clear;
lbClinics.Items.Assign(GMVClinics.Entries);
lbClinics.setFocus;
except
end;
bLastClinicFound := iCount < iLoadLimit;
// added zzzzzzandria 20080701 11:45
iPos := LookupClinicInTheList(aTarget);
if iPos >= 0 then
setPos(iPos,iLen);
end
else
MessageDLG('No records found'+#13#10+'Search target: "'+
aTarget+ '"', mtWarning,[mbOK],0);
UpdateScrollBar;
end;
end;
procedure TfrmGMV_PatientSelector.cmbClinicKeyPress(Sender: TObject;
var Key: Char);
var
s: String;
begin
if Key = char(VK_RETURN) then
begin
if tmSearch.enabled then
begin // stop timer and cleanup indicator
tmSearch.Enabled :=false;
GetParentForm(Self).Perform(CM_PTSEARCHDONE, 0, 0);
end;
s := cmbClinic.Text;
if cmbClinic.SelLength > 0 then
s := copy(s,1,cmbClinic.SelStart - 1);
FindClinics(s);
end;
end;
// zzzzzzandria 2008-04-11 ================================================= end
procedure TfrmGMV_PatientSelector.lbClinics0KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
iTop,iBottom, iSize, iTopPos,
i: Integer;
function LoadMoreDown(bKB:Boolean=True): Integer;
begin
iBottom := fListBox.Items.Count - 1;
i := UploadClinics(fListBox.Items[iBottom],'1',Key);
fListBox.Items.Assign(GMVClinics.Entries); // zzzzzzandria 20080609
Result := i;
if bKB then // k/b request
begin
if i > 0 then
fListBox.ItemIndex := iTop;
end
else
if i > 0 then
fListBox.ItemIndex := min(iBottom+iSize,fListBox.Items.Count - 1)
else
fListBox.ItemIndex := iBottom;
end;
procedure LoadMoreUp;
begin
i := UploadClinics(fListBox.Items[iTopPos],'-1',Key);
fListBox.Items.Assign(GMVClinics.Entries); // zzzzzzandria 20080609
if i > 0 then
fListBox.ItemIndex := i - 1
else
fListBox.ItemIndex := 0;
end;
begin
if Key = VK_RETURN then
cmbPeriod.SetFocus
else
begin
iTop := fListBox.ItemIndex;
iTopPos := fListBox.TopIndex;
iSize := (fListBox.Height div fListBox.ItemHeight) - 1;
iBottom := iTop + iSize;
case Key of
SB_TOP:
if iTopPos = 0 then
LoadMoreUp;
SB_BOTTOM:
if not bLastClinicFound then
LoadMoreDown(False)
else
fListBox.ItemIndex :=
min(iTopPos+iSize,fListBox.Items.Count - 1);
VK_DOWN, VK_Next {VK_end,}:
if not bLastClinicFound and (fListBox.ItemIndex = fListBox.Items.Count - 1) then
LoadMoreDown(True);
VK_Up, VK_Prior:
if not bLastClinicFound and (fListBox.ItemIndex = 0) then
LoadMoreUp;
end;
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure TfrmGMV_PatientSelector.pcMainMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{$IFDEF AANTEST} // shows extra panels on click
if (ssCTRL in Shift) and (ssShift in Shift) then
begin
pnlInfo.Visible := not pnlInfo.Visible;
lblSelected.Visible := not lblSelected.Visible;
end;
{$ENDIF}
end;
procedure TfrmGMV_PatientSelector.tmrLoadTimer(Sender: TObject);
var
fe: TGMV_FileEntry;
iSL: Integer;
iIndex: Integer;
s: String;
aTarget: String;
SL: TStringList;
b: Boolean;
bClinic: Boolean;
begin
tmrLoad.Enabled := False;
aTarget := sLastClinicFound;
b := pcMain.ActivePage = tsClinic;
bClinic := True;
if b then
begin
bClinic := pnlClinic.Enabled;
tsClinic.Enabled := False;
lblLoadStatus.Caption := 'Loading <'+aTarget+'>';
lblLoadStatus.Visible := True;
Application.ProcessMessages;
end;
SL := getClinicFileEntriesByName(aTarget,IntToStr(iLoadLimit),'1');
if Assigned(SL) then
begin
for iSL := 0 to SL.Count - 1 do
begin
s := SL[iSL];
iIndex := GMVClinics.Entries.IndexOf(s);
if iIndex < 0 then
begin
fe := TGMV_FileEntry(SL.Objects[iSL]);
GMVClinics.Entries.AddObject(SL[iSL],fe);
end;
end;
bLastClinicFound := SL.Count < iLoadLimit;
sLastClinicFound := s;
SL.Free;
end;
try
bIgnore := True;
for iSL := 0 to GMVClinics.Entries.Count - 1 do
begin
iIndex := lbClinics.Items.IndexOf(GMVClinics.Entries[iSL]);
if iIndex < 0 then
begin
lbClinics.Items.Add(GMVClinics.Entries[iSL]);
end;
end;
bIgnore := False;
except
end;
if b then
begin
tsClinic.Enabled := bLastClinicFound;
pnlClinic.Enabled := bClinic;
end;
if bLastClinicFound then
lblLoadStatus.Visible := false;
tmrLoad.Enabled := not bLastClinicFound;
end;
procedure TfrmGMV_PatientSelector.lbClinics0MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
bDown := True;
end;
procedure TfrmGMV_PatientSelector.lbClinics0MouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
bDown := False;
end;
initialization
{$IFDEF LOADLIMITPARAM}
iLoadLimit := 10; // test version
{$ELSE}
iLoadLimit := 500; // production version
{$ENDIF}
end.
|
unit BrickCamp.ISettings;
interface
type
IBrickCampSettings = interface
['{F65AA1C0-92AC-4DE6-8E78-910EFFE66D3E}']
function GetDBStringConnection: string;
function GetRedisIpAddress: string;
function GetRedisIpPort: string;
end;
implementation
end.
|
unit ShellProcess;
interface
uses TlHelp32, Windows, Classes, Sysutils, Messages;
procedure GetProcessList(List: TStrings);
procedure GetModuleList(List: TStrings);
function GetProcessHandle(ProcessID: integer): THandle;
procedure GetParentProcessInfo(var ID: Integer; var Path: string);
function ProcessTerminate(dwPID: Cardinal): Boolean;
function TerminateTask(PID: integer): integer;
function KillTask(ExeFileName: string): integer;
function ProcessMessage: Boolean;
const
PROCESS_TERMINATE = $0001;
PROCESS_CREATE_THREAD = $0002;
PROCESS_VM_OPERATION = $0008;
PROCESS_VM_READ = $0010;
PROCESS_VM_WRITE = $0020;
PROCESS_DUP_HANDLE = $0040;
PROCESS_CREATE_PROCESS = $0080;
PROCESS_SET_QUOTA = $0100;
PROCESS_SET_INFORMATION = $0200;
PROCESS_QUERY_INFORMATION = $0400;
PROCESS_ALL_ACCESS =
STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $0FFF;
implementation
function ProcessMessage: Boolean;
function IsKeyMsg(var Msg: TMsg): Boolean;
const
CN_BASE = $BC00;
var
Wnd: HWND;
begin
Result := False;
with Msg do
if (Message >= WM_KEYFIRST) and (Message <= WM_KEYLAST) then
begin
Wnd := GetCapture;
if Wnd = 0 then
begin
Wnd := HWnd;
if SendMessage(Wnd, CN_BASE + Message, WParam, LParam) <> 0 then
Result := True;
end
else
if (LongWord(GetWindowLong(Wnd, GWL_HINSTANCE)) = HInstance) then
if SendMessage(Wnd, CN_BASE + Message, WParam, LParam) <> 0 then
Result := True;
end;
end;
var
Msg: TMsg;
begin
Result := False;
if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
begin
Result := True;
if Msg.Message <> WM_QUIT then
if not IsKeyMsg(Msg) then
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;
end;
procedure GetProcessList(List: TStrings);
var
I: Integer;
hSnapshoot: THandle;
pe32: TProcessEntry32;
begin
List.Clear;
hSnapshoot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshoot = -1) then
Exit;
pe32.dwSize := SizeOf(TProcessEntry32);
if (Process32First(hSnapshoot, pe32)) then
repeat
I := List.Add(LowerCase(pe32.szExeFile));
List.Objects[I] := Pointer(pe32.th32ProcessID);
ProcessMessage;
until not Process32Next(hSnapshoot, pe32);
CloseHandle(hSnapshoot);
end;
procedure GetModuleList(List: TStrings);
var
I: Integer;
hSnapshoot: THandle;
me32: TModuleEntry32;
begin
List.Clear;
hSnapshoot := CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, 0);
if (hSnapshoot = -1) then
Exit;
me32.dwSize := SizeOf(TModuleEntry32);
if (Module32First(hSnapshoot, me32)) then
repeat
I := List.Add(me32.szModule);
List.Objects[I] := Pointer(me32.th32ModuleID);
ProcessMessage;
until not Module32Next(hSnapshoot, me32);
CloseHandle(hSnapshoot);
end;
procedure GetParentProcessInfo(var ID: Integer; var Path: string);
var
ProcessID: Integer;
hSnapshoot: THandle;
pe32: TProcessEntry32;
begin
ProcessID := GetCurrentProcessID;
ID := -1;
Path := '';
hSnapshoot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapshoot = -1) then
Exit;
pe32.dwSize := SizeOf(TProcessEntry32);
if (Process32First(hSnapshoot, pe32)) then
repeat
if pe32.th32ProcessID = ProcessID then
begin
ID := pe32.th32ParentProcessID;
Break;
end;
ProcessMessage;
until not Process32Next(hSnapshoot, pe32);
if ID <> -1 then
begin
if (Process32First(hSnapshoot, pe32)) then
repeat
if pe32.th32ProcessID = ID then
begin
Path := pe32.szExeFile;
Break;
end;
ProcessMessage;
until not Process32Next(hSnapshoot, pe32);
end;
CloseHandle(hSnapshoot);
end;
function GetProcessHandle(ProcessID: Integer): THandle;
begin
Result := OpenProcess(PROCESS_ALL_ACCESS, True, ProcessID);
end;
function TerminateTask(PID: integer): integer;
var
process_handle: integer;
lpExitCode: Cardinal;
begin
process_handle := openprocess(PROCESS_ALL_ACCESS, true, pid);
GetExitCodeProcess(process_handle, lpExitCode);
if (process_handle = 0) then
TerminateTask := GetLastError
else if terminateprocess(process_handle, lpExitCode) then
begin
TerminateTask := 0;
CloseHandle(process_handle);
end
else
begin
TerminateTask := GetLastError;
CloseHandle(process_handle);
end;
end;
function KillTask(ExeFileName: string): integer;
var
list: TStringList;
k: integer;
trys: Integer;
begin
list := TStringList.Create;
try
GetProcessList(List);
trys := 0;
repeat
k := List.IndexOf(ExeFileName);
result := 1;
if k > -1 then
begin
result := TerminateTask(Integer(List.Objects[k]));
if (result <> 0) then
result := Integer(not processTerminate(Integer(List.Objects[k])));
if Result = 0 then
list.Delete(k);
end
else
result := 0;
Inc(trys);
ProcessMessage;
until (k = -1) or (trys > 20);
finally
list.Free;
end;
end;
// Включение, приминение и отключения привилегии.
// Для примера возьмем привилегию отладки приложений 'SeDebugPrivilege'
// необходимую для завершения ЛЮБЫХ процессов в системе (завершение процесов
// созданных текущим пользователем привилегия не нужна.
function ProcessTerminate(dwPID: Cardinal): Boolean;
var
hToken: THandle;
SeDebugNameValue: Int64;
tkp: TOKEN_PRIVILEGES;
ReturnLength: Cardinal;
hProcess: THandle;
begin
Result := false;
if TerminateTask(dwPid) = 0 then
begin
result := true;
exit;
end
else
begin
// Добавляем привилегию SeDebugPrivilege
// Для начала получаем токен нашего процесса
if not OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
or TOKEN_QUERY, hToken) then
exit;
// Получаем LUID привилегии
if not LookupPrivilegeValue(nil, 'SeDebugPrivilege', SeDebugNameValue)
then begin
CloseHandle(hToken);
exit;
end;
tkp.PrivilegeCount := 1;
tkp.Privileges[0].Luid := SeDebugNameValue;
tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
// Добавляем привилегию к нашему процессу
AdjustTokenPrivileges(hToken, false, tkp, SizeOf(tkp), tkp, ReturnLength);
if GetLastError() <> ERROR_SUCCESS then exit;
// Завершаем процесс. Если у нас есть SeDebugPrivilege, то мы можем
// завершить и системный процесс
// Получаем дескриптор процесса для его завершения
hProcess := OpenProcess(PROCESS_TERMINATE, FALSE, dwPID);
if hProcess = 0 then exit;
// Завершаем процесс
if not TerminateProcess(hProcess, DWORD(-1))
then exit;
CloseHandle(hProcess);
// Удаляем привилегию
tkp.Privileges[0].Attributes := 0;
AdjustTokenPrivileges(hToken, FALSE, tkp, SizeOf(tkp), tkp, ReturnLength);
if GetLastError() <> ERROR_SUCCESS
then exit;
Result := true;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 1995, 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit RTLConsts;
interface
resourcestring
SAncestorNotFound = 'Ancestor for ''%s'' not found';
SAssignError = 'Cannot assign a %s to a %s';
SBitsIndexError = 'Bits index out of range';
SBucketListLocked = 'List is locked during an active ForEach';
SCantWriteResourceStreamError = 'Can''t write to a read-only resource stream';
SCharExpected = '''''%s'''' expected';
SCheckSynchronizeError = 'CheckSynchronize called from thread $%x, which is NOT the main thread';
SClassNotFound = 'Class %s not found';
SDelimiterQuoteCharError = 'Delimiter and QuoteChar properties cannot have the same value';
SDuplicateClass = 'A class named %s already exists';
SDuplicateItem = 'List does not allow duplicates ($0%x)';
SDuplicateName = 'A component named %s already exists';
SDuplicateString = 'String list does not allow duplicates';
SFCreateError = 'Cannot create file %s';
SFixedColTooBig = 'Fixed column count must be less than column count';
SFixedRowTooBig = 'Fixed row count must be less than row count';
SFOpenError = 'Cannot open file %s';
SGridTooLarge = 'Grid too large for operation';
SIdentifierExpected = 'Identifier expected';
SIndexOutOfRange = 'Grid index out of range';
SIniFileWriteError = 'Unable to write to %s';
SInvalidActionCreation = 'Invalid action creation';
SInvalidActionEnumeration = 'Invalid action enumeration';
SInvalidActionRegistration = 'Invalid action registration';
SInvalidActionUnregistration = 'Invalid action unregistration';
SInvalidBinary = 'Invalid binary value';
SInvalidDate = '''''%s'''' is not a valid date';
SInvalidDateTime = '''''%s'''' is not a valid date and time';
SInvalidFileName = 'Invalid file name - %s';
SInvalidImage = 'Invalid stream format';
SInvalidInteger = '''''%s'''' is not a valid integer value';
SInvalidMask = '''%s'' is an invalid mask at (%d)';
SInvalidName = '''''%s'''' is not a valid component name';
SInvalidProperty = 'Invalid property value';
SInvalidPropertyElement = 'Invalid property element: %s';
SInvalidPropertyPath = 'Invalid property path';
SInvalidPropertyType = 'Invalid property type: %s';
SInvalidPropertyValue = 'Invalid property value';
SInvalidRegType = 'Invalid data type for ''%s''';
SInvalidString = 'Invalid string constant';
SInvalidStringGridOp = 'Cannot insert or delete rows from grid';
SInvalidTime = '''''%s'''' is not a valid time';
SItemNotFound = 'Item not found ($0%x)';
SLineTooLong = 'Line too long';
SListCapacityError = 'List capacity out of bounds (%d)';
SListCountError = 'List count out of bounds (%d)';
SListIndexError = 'List index out of bounds (%d)';
SMaskErr = 'Invalid input value';
SMaskEditErr = 'Invalid input value. Use escape key to abandon changes';
SMemoryStreamError = 'Out of memory while expanding memory stream';
SNoComSupport = '%s has not been registered as a COM class';
SNotPrinting = 'Printer is not currently printing';
SNumberExpected = 'Number expected';
SParseError = '%s on line %d';
SComponentNameTooLong = 'Component name ''%s'' exceeds 64 character limit';
SPropertyException = 'Error reading %s%s%s: %s';
SPrinting = 'Printing in progress';
SReadError = 'Stream read error';
SReadOnlyProperty = 'Property is read-only';
SRegCreateFailed = 'Failed to create key %s';
SRegGetDataFailed = 'Failed to get data for ''%s''';
SRegisterError = 'Invalid component registration';
SRegSetDataFailed = 'Failed to set data for ''%s''';
SResNotFound = 'Resource %s not found';
SSeekNotImplemented = '%s.Seek not implemented';
SSortedListError = 'Operation not allowed on sorted list';
SStringExpected = 'String expected';
SSymbolExpected = '%s expected';
STimeEncodeError = 'Invalid argument to time encode';
STooManyDeleted = 'Too many rows or columns deleted';
SUnknownGroup = '%s not in a class registration group';
SUnknownProperty = 'Property %s does not exist';
SWriteError = 'Stream write error';
SStreamSetSize = 'Stream.SetSize failure';
SThreadCreateError = 'Thread creation error: %s';
SThreadError = 'Thread Error: %s (%d)';
SInvalidDateDay = '(%d, %d) is not a valid DateDay pair';
SInvalidDateWeek = '(%d, %d, %d) is not a valid DateWeek triplet';
SInvalidDateMonthWeek = '(%d, %d, %d, %d) is not a valid DateMonthWeek quad';
SInvalidDayOfWeekInMonth = '(%d, %d, %d, %d) is not a valid DayOfWeekInMonth quad';
SInvalidJulianDate = '%f Julian cannot be represented as a DateTime';
SMissingDateTimeField = '?';
SConvIncompatibleTypes2 = 'Incompatible conversion types [%s, %s]';
SConvIncompatibleTypes3 = 'Incompatible conversion types [%s, %s, %s]';
SConvIncompatibleTypes4 = 'Incompatible conversion types [%s - %s, %s - %s]';
SConvUnknownType = 'Unknown conversion type %s';
SConvDuplicateType = 'Conversion type (%s) already registered in %s';
SConvUnknownFamily = 'Unknown conversion family %s';
SConvDuplicateFamily = 'Conversion family (%s) already registered';
SConvUnknownDescription = '[%.8x]';
SConvIllegalType = 'Illegal type';
SConvIllegalFamily = 'Illegal family';
SConvFactorZero = '%s has a factor of zero';
SConvStrParseError = 'Could not parse %s';
SFailedToCallConstructor = 'TStrings descendant %s failed to call inherited constructor';
sWindowsSocketError = 'Windows socket error: %s (%d), on API ''%s''';
sAsyncSocketError = 'Asynchronous socket error %d';
sNoAddress = 'No address specified';
sCannotListenOnOpen = 'Can''t listen on an open socket';
sCannotCreateSocket = 'Can''t create new socket';
sSocketAlreadyOpen = 'Socket already open';
sCantChangeWhileActive = 'Can''t change value while socket is active';
sSocketMustBeBlocking = 'Socket must be in blocking mode';
sSocketIOError = '%s error %d, %s';
sSocketRead = 'Read';
sSocketWrite = 'Write';
implementation
end.
|
unit GMScriptBuilderMain;
interface
uses
Windows, SysUtils, Variants, Classes, IniFiles, GMGlobals, StrUtils;
function ProcessCmdLineParameters(): int;
implementation
var
slTemplateFrom, slTemplateTo: TSTringList;
function PrepareRelativePath(const relPath: string): string;
var
root: string;
begin
root := ExpandFileName(ExcludeTrailingPathDelimiter(ExtractFileDir(ParamStr(0)))+ '\..\..\');
Result := root + relPath;
end;
procedure NormalizeConsoleOutput(const consoleOutput: string; slOutput: TStrings);
var
s: string;
i: int;
begin
s := consoleOutput;
for i := 1 to Length(s) do // радикально быстрее StringReplace
if s[i] = #10 then
s[i] := #13;
slOutput.Text := s;
for i := slOutput.Count - 1 downto 0 do
if Trim(slOutput[i]) = '' then
slOutput.Delete(i)
else
break;
end;
procedure CaptureConsoleOutput(const AParameters: String; slOutput: TStrings);
const
CReadBuffer = 2400;
ACommand = 'git';
var
builder: TStringBuilder;
saSecurity: TSecurityAttributes;
hRead: THandle;
hWrite: THandle;
suiStartup: TStartupInfo;
piProcess: TProcessInformation;
pBuffer: array[0..CReadBuffer] of AnsiChar;
dRead: DWord;
dRunning: DWord;
begin
slOutput.Clear();
builder := TStringBuilder.Create();
try
ZeroMemory(@saSecurity, SizeOf(TSecurityAttributes));
saSecurity.nLength := SizeOf(TSecurityAttributes);
saSecurity.bInheritHandle := True;
saSecurity.lpSecurityDescriptor := nil;
if CreatePipe(hRead, hWrite, @saSecurity, 0) then
begin
FillChar(suiStartup, SizeOf(TStartupInfo), #0);
suiStartup.cb := SizeOf(TStartupInfo);
suiStartup.hStdInput := hRead;
suiStartup.hStdOutput := hWrite;
suiStartup.hStdError := hWrite;
suiStartup.dwFlags := STARTF_USESTDHANDLES;
suiStartup.wShowWindow := SW_HIDE;
if CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity, @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess) then
begin
CloseHandle(hWrite); // иначе зависает на считывании последне порции
repeat
dRunning := WaitForSingleObject(piProcess.hProcess, 100);
repeat
dRead := 0;
ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);
pBuffer[dRead] := #0;
OemToAnsi(pBuffer, pBuffer);
builder.Append(String(pBuffer));
until (dRead < CReadBuffer);
until (dRunning <> WAIT_TIMEOUT);
CloseHandle(piProcess.hProcess);
CloseHandle(piProcess.hThread);
end;
CloseHandle(hRead);
end;
NormalizeConsoleOutput(Builder.ToString(), slOutput);
finally
builder.Free();
end;
end;
function RevisionCount(): int;
var
sl: TSTringList;
s: string;
begin
sl := TSTringList.Create();
try
CaptureConsoleOutput('rev-list head --count', sl);
if sl.Count <> 1 then
raise Exception.Create('rev-list head --count failed. git: ' + sl.Text);
s := sl[0].Trim([' ', #13, #10]);
Result := StrToIntDef(s, -1);
if Result <= 0 then
raise Exception.Create('rev-list head --count failed. git: ' + sl.Text);
finally
sl.Free();
end;
end;
function DirectoryRevisionSha(const relPath: string): string;
var
path: string;
sl: TSTringList;
begin
path := PrepareRelativePath(relPath);
sl := TSTringList.Create();
try
CaptureConsoleOutput('rev-list head --max-count=1 -- ' + path, sl);
if sl.Count <> 1 then
raise Exception.Create('rev-list "' + path + '" faled. git: ' + sl.Text);
Result := sl[0].Trim([' ', #13, #10]);
if Length(Result) <> 40 then
raise Exception.Create('rev-list "' + path + '" faled. git: ' + sl.Text);
finally
sl.Free();
end;
end;
function FindRevision(const sha: string): int;
var
sl: TSTringList;
begin
sl := TSTringList.Create();
try
CaptureConsoleOutput('rev-list head', sl);
if sl.Count = 0 then
raise Exception.Create('rev-list head failed');
Result := sl.IndexOf(sha);
finally
sl.Free();
end;
end;
function ReadHeadRevision(const relPath: string): int;
var
sha: string;
cnt, n: int;
begin
// SHA последнего коммита для указанной папки: git rev-list head --max-count=1 -- D:\Programs\Delphi\Geomer\GMIO_git\DB\Builder
// список SHA для всех коммитов в репозиторий: git rev-list head
// общее к-во коммитов в репозиторий: git rev-list head --count
// Т.о. алгоритм следующий
// 1. Получаем SHA для последнего коммита в directory
// 2. Получаем к-во коммитов в корень (CNT)
// 3. Получаем список коммитов в корень
// 4. Находим наш последний коммит в общем списке (N)
// 5. Получаем номер как CNT - N + 912, где 912 - это номер последней ревизии в SVN
cnt := RevisionCount();
sha := DirectoryRevisionSha(relPath);
n := FindRevision(sha);
Result := cnt - n + 912;
end;
function CheckFileTemplate(sl: TStringList; var fnTemplate: string): bool;
var i, n: int;
begin
Result := false;
for i := 0 to sl.Count - 1 do
begin
n := Pos('pg_gm_db_template_from_file', sl[i]);
if n > 0 then
begin
Result := true;
fnTemplate := Trim(Copy(sl[i], PosEx(' ', sl[i], n) + 1, Length(sl[i])));
end;
end;
end;
procedure ProcessFKTemplate(const fileString: string);
var args: TStringList;
n, n1, n2: int;
table, reftable, column, s, refcolumn: string;
isCascade: bool;
begin
n := Pos('pg_gm_db_template_foreign_key', fileString);
if n <= 0 then Exit;
args := TStringList.Create();
args.Delimiter := ' ';
args.DelimitedText := fileString;
if args.Count >= 4 then // pg_gm_db_template_foreign_key table column reftable[(refcolumn)]
begin
table := args[1];
column := args[2];
reftable := args[3];
refcolumn := column;
if pos('(', reftable) > 0 then
begin
n1 := pos('(', reftable);
n2 := pos(')', reftable);
if n2 > 0 then
begin
refcolumn := Copy(refTable, n1 + 1, n2 - n1 - 1);
reftable := Copy(refTable, 1, n1 - 1);
end
else
begin
refColumn := 'Error in declaration: missin ")"';
end;
end;
isCascade := args.Count > 4;
s := StringOfChar(' ', n - 1) + 'if not exists(select * from pg_constraint where conname = ''' + LowerCase(table + '_' + column) + '_fkey'') then '#10 +
StringOfChar(' ', n - 1) + ' update ' + table + ' set ' + column + ' = null where ' + column + ' <= 0;'#10 +
StringOfChar(' ', n - 1) + Format(' delete from %s where %s is not null and %s not in (select %s from %s);'#10, [table, column, column, refcolumn, reftable]) +
StringOfChar(' ', n - 1) + ' alter table ' + table + ' add foreign key (' + column + ') references ' + reftable + '(' + refColumn + ')';
if isCascade then
s := s + ' on delete ' + args.DelimitedRande(4, args.Count);
s := s + ';'#10 +
StringOfChar(' ', n - 1) + 'end if;';
slTemplateFrom.Add(fileString);
slTemplateTo.Add(s + #10);
end;
args.Free();
end;
procedure ProcessAddColumnTemplate(const fileString: string);
var args: TStringList;
n: int;
s, table, column, datatype: string;
begin
n := Pos('pg_gm_db_template_add_column', fileString);
if n <= 0 then Exit;
args := TStringList.Create();
args.Delimiter := ' ';
args.DelimitedText := fileString;
if args.Count >= 4 then // pg_gm_db_template_add_column table column type
begin
table := args[1];
column := args[2];
datatype := args.DelimitedRande(3, args.Count);
s := StringOfChar(' ', n - 1) + 'if not exists (select * from information_schema.columns where table_name = lower(''' + table + ''') and column_name = lower(''' + column + ''')) then'#10 +
StringOfChar(' ', n - 1) + ' alter table ' + table + ' add ' + column + ' ' + datatype +';'#10 +
StringOfChar(' ', n - 1) + 'end if;';
slTemplateFrom.Add(fileString);
slTemplateTo.Add(s + #10);
end;
args.Free();
end;
procedure ProcessStringReplaceTemplate(const fileString: string);
var n, n1, n2: int;
sFrom, sTo: string;
begin
n := Pos('pg_gm_db_template_str_replace', fileString);
if n > 0 then
begin
n1 := PosEx(' ', fileString, n);
n2 := PosEx(' ', fileString, n1 + 1);
if n2 = 0 then
n2 := Length(fileString) + 1;
sFrom := Copy(fileString, n1 + 1, n2 - n1 - 1);
sTo := TrimRight(Copy(fileString, n2 + 1, Length(fileString)));
slTemplateFrom.Add(sFrom);
slTemplateTo.Add(sTo);
end;
end;
procedure PrepareTemplates(sl: TStringList);
var i: int;
begin
slTemplateFrom.Clear();
slTemplateTo.Clear();
for i := 0 to sl.Count - 1 do
begin
ProcessStringReplaceTemplate(sl[i]);
ProcessFKTemplate(sl[i]);
ProcessAddColumnTemplate(sl[i]);
end;
end;
function ApplyTemplates(const s: string): string;
var i: int;
sTo: string;
begin
Result := s;
for i := 0 to slTemplateFrom.Count - 1 do
begin
sTo := slTemplateTo[i];
if sTo = '$HEAD_REVISION$' then
sTo := IntToStr(ReadHeadRevision('DB/Builder'))
else
if sTo = '$HEAD_REVISION_SHA$' then
sTo := DirectoryRevisionSha('DB/Builder');
Result := StringReplace(Result, slTemplateFrom[i], sTo, [rfIgnoreCase, rfReplaceAll]);
end;
end;
procedure BuildScript();
var lstFiles: TStringList;
script: TFileStream;
str: TStringStream;
slFile: TStringList;
i, j: int;
path, resFile, fnTemplate: string;
header: array [0..2] of Byte;
slUsedFiles: TStringList;
procedure LoadPart(fn: string);
var part: TFileStream;
begin
slUsedFiles.Add(ExtractFileName(fn));
part := TFileStream.Create(fn, fmOpenRead);
part.Seek(3, soFromBeginning); // пропускаем кодировку, она везде и так UTF8
slFile.LoadFromStream(part);
part.Free();
end;
procedure CheckAllFilesUsed();
var res, n: int;
rec: TSearchRec;
errfiles: string;
begin
errfiles := '';
res := FindFirst(path + '*.sql', faAnyFile, rec);
while res = 0 do
begin
if (rec.Name <> '.') and (rec.Name <> '..') then
begin
n := slUsedFiles.IndexOf(rec.Name);
if n < 0 then
errfiles := errFiles + rec.Name + #13#10;
end;
res := FindNext(rec);
end;
FindClose(rec);
if errfiles <> '' then
raise Exception.Create('Files not used: ' + errfiles);
end;
begin
if ParamCount() < 3 then
raise Exception.Create('Not enough parameters!');
path := IncludeTrailingPathDelimiter(ParamStr(2));
resFile := ParamStr(3);
lstFiles := TStringList.Create();
str := TStringStream.Create('');
slFile := TStringList.Create();
slUsedFiles := TStringList.Create();
try
lstFiles.LoadFromFile(path + '_script.ini');
for i := 0 to lstFiles.Count - 1 do
begin
if Trim(lstFiles[i]) = '' then continue;
if (Copy(lstFiles[i], 1, 2) = '//') or (Copy(lstFiles[i], 1, 2) = '--') then // Comments
begin
str.WriteString('--' + Copy(lstFiles[i], 3, Length(lstFiles[i])));
str.WriteString(#10);
end
else
begin
LoadPart(path + lstFiles[i] + '.sql');
PrepareTemplates(slFile);
if CheckFileTemplate(slFile, fnTemplate) then
LoadPart(path + fnTemplate + '.sql');
for j := 0 to slFile.Count - 1 do
begin
str.WriteString(ApplyTemplates(slFile[j]));
str.WriteString(#10);
end;
end;
if i < lstFiles.Count - 1 then
str.WriteString(#10);
end;
script := TFileStream.Create(resFile, fmCreate);
header[0] := $EF;
header[1] := $BB;
header[2] := $BF;
script.Write(header, length(header));
str.Seek(0, soFromBeginning);
script.CopyFrom(str, str.Size);
script.Free();
CheckAllFilesUsed();
finally
lstFiles.Free();
slFile.Free();
str.Free();
slUsedFiles.Free();
end;
end;
procedure InsertVersion();
var resFileName: string;
baseVersions: TIniFile;
major, minor, subminor, revision, scriptRevision: int;
sl: TStringList;
i: int;
sha: string;
begin
if ParamCount() < 2 then
raise Exception.Create('Not enough parameters!');
resFileName := ParamStr(2);
baseVersions := TIniFile.Create('..\..\Build\version.ini');
try
major := baseVersions.ReadInteger('VERSION', 'MAJOR', -1);
minor := baseVersions.ReadInteger('VERSION', 'MINOR', -1);
subminor := baseVersions.ReadInteger('VERSION', 'SUBMINOR', -1);
finally
baseVersions.Free();
end;
revision := ReadHeadRevision('');
scriptRevision := ReadHeadRevision('DB/Builder');
if (major < 1) or (minor < 0) or (subminor < 0) then
raise Exception.Create('Wrong version file contents!');
if (revision < 1) then
raise Exception.Create('Wrong revision!');
sha := DirectoryRevisionSha('');
sl := TStringList.Create();
try
sl.LoadFromFile(resFileName);
for i := 0 to sl.Count - 1 do
begin
sl[i] := StringReplace(sl[i], '$MAJOR$', IntToStr(major), [rfReplaceAll]);
sl[i] := StringReplace(sl[i], '$MINOR$', IntToStr(minor), [rfReplaceAll]);
sl[i] := StringReplace(sl[i], '$SUBMINOR$', IntToStr(subminor), [rfReplaceAll]);
sl[i] := StringReplace(sl[i], '$WCREV$', IntToStr(revision), [rfReplaceAll]);
sl[i] := StringReplace(sl[i], '$SCRIPTREV$', IntToStr(scriptRevision), [rfReplaceAll]);
sl[i] := StringReplace(sl[i], '$DATETIME$', FormatDateTime('dd.mm.yyyy hh:nn:ss', Now()), [rfReplaceAll]);
sl[i] := StringReplace(sl[i], '$GITSHA$', sha, [rfReplaceAll]);
end;
sl.SaveToFile(resFileName);
finally
sl.Free();
end;
end;
type
TCheckAllFilesUnderSVN = class
private
FMissingFiles, FExternals: TStringList;
FRepoFiles: THashedStringList;
procedure ProcessDirectory(const dir: string);
procedure CheckSVN;
constructor Create();
destructor Destroy(); override;
procedure CheckFile(const fn: string);
procedure ReadRepoFilesList;
procedure CreateExternalsList;
end;
constructor TCheckAllFilesUnderSVN.Create();
begin
inherited;
FMissingFiles := TStringList.Create();
FExternals := TStringList.Create();
FRepoFiles := THashedStringList.Create();
end;
destructor TCheckAllFilesUnderSVN.Destroy();
begin
FMissingFiles.Free();
FExternals.Free();
FRepoFiles.Free();
inherited;
end;
procedure TCheckAllFilesUnderSVN.CheckFile(const fn: string);
const
FilesUnderSvn: array [0..3] of string = ('.sql', '.pas', '.dfm', '.in');
begin
var ext := ExtractFileExt(fn).ToLower();
var goOn := false;
for var i := 0 to High(FilesUnderSvn) do
goOn := goOn or (ext = FilesUnderSvn[i]);
if goOn and (FRepoFiles.IndexOf(AnsiLowerCase(fn)) < 0) then
FMissingFiles.Add(fn);
end;
procedure TCheckAllFilesUnderSVN.ProcessDirectory(const dir: string);
var rec: TSearchRec;
res: int;
path, fn: string;
begin
if not DirectoryExists(dir) then
raise Exception.Create('Directory not found ' + dir);
if FExternals.IndexOf(UpperCase(ExcludeTrailingPathDelimiter(dir))) >= 0 then Exit;
path := IncludeTrailingPathDelimiter(dir);
res := FindFirst(path + '*.*', faDirectory, rec);
while res = 0 do
begin
if (rec.Name <> '.') and (rec.Name <> '..') then
begin
if (rec.Attr and faDirectory) > 0 then
begin
fn := IncludeTrailingPathDelimiter(path + rec.Name);
ProcessDirectory(fn)
end
else
begin
fn := path + rec.Name;
CheckFile(fn);
end;
end;
res := FindNext(rec);
end;
FindClose(rec);
end;
procedure TCheckAllFilesUnderSVN.ReadRepoFilesList();
var
i: int;
path: string;
begin
CaptureConsoleOutput('ls-tree --full-tree -r --name-only HEAD', FRepoFiles);
path := ExpandFileName('..\..\');
for i := 0 to FRepoFiles.Count - 1 do
FRepoFiles[i] := AnsiLowerCase(path + StringReplace(FRepoFiles[i], '/', '\', [rfReplaceAll]));
end;
procedure TCheckAllFilesUnderSVN.CreateExternalsList();
begin
end;
procedure TCheckAllFilesUnderSVN.CheckSVN();
var i: int;
begin
ReadRepoFilesList();
CreateExternalsList();
for i := 2 to ParamCount do
ProcessDirectory(ExpandFileName('..\..\') + ParamStr(i));
end;
function CheckSVN(): int;
var cf: TCheckAllFilesUnderSVN;
begin
cf := TCheckAllFilesUnderSVN.Create();
try
cf.CheckSVN();
Result := 0;
if cf.FMissingFiles.Count > 0 then
begin
Writeln('Files not under SVN: ' + cf.FMissingFiles.Text);
Result := 1;
end;
finally
cf.Free();
end;
end;
function ProcessCmdLineParameters(): int;
begin
Result := 0;
try
if ParamStr(1) = 'script' then
BuildScript()
else
if ParamStr(1) = 'version' then
InsertVersion()
else
if ParamStr(1) = 'checksvn' then
Result := CheckSVN()
else
begin
Writeln('Uncnown command: ' + ParamStr(1));
Result := 1;
end;
except
on e: Exception do
begin
try
Writeln('Script build error: ' + e.Message);
except end;
Result := 1;
end;
end;
end;
initialization
slTemplateFrom := TSTringList.Create();
slTemplateTo := TSTringList.Create();
finalization
slTemplateFrom.Free();
slTemplateTo.Free();
end.
|
{********************************************}
{ TCustomTeeNavigator }
{ Copyright (c) 2001-2004 by David Berneda }
{ All Rights Reserved }
{********************************************}
unit TeeNavigator;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows, Messages,
{$ENDIF}
{$IFDEF CLX}
QExtCtrls, QControls, QButtons, Types,
{$ELSE}
ExtCtrls, Controls, Buttons,
{$ENDIF}
Classes, TeeProcs;
type
TTeeNavGlyph = (ngEnabled, ngDisabled);
TTeeNavigateBtn = (nbFirst, nbPrior, nbNext, nbLast,
nbInsert, nbDelete, nbEdit, nbPost, nbCancel);
TTeeButtonSet = set of TTeeNavigateBtn;
TTeeNavButton = class(TSpeedButton)
private
FIndex : TTeeNavigateBtn;
FRepeatTimer : TTimer;
procedure TimerExpired(Sender: TObject);
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure Paint; override;
public
Destructor Destroy; override;
property Index : TTeeNavigateBtn read FIndex write FIndex;
end;
TNotifyButtonClickedEvent=Procedure(Index:TTeeNavigateBtn) of object;
TCustomTeeNavigator=class(TCustomPanel,ITeeEventListener)
private
FHints : TStrings;
FDefHints : TStrings;
ButtonWidth : Integer;
MinBtnSize : TPoint;
FocusedButton : TTeeNavigateBtn;
FOnButtonClicked : TNotifyButtonClickedEvent;
FPanel: TCustomTeePanel;
procedure BtnMouseDown (Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ClickHandler(Sender: TObject);
procedure CheckSize;
procedure HintsChanged(Sender: TObject);
procedure SetSize(var W: Integer; var H: Integer);
{$IFNDEF CLX}
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
{$ENDIF}
{$IFNDEF CLX}
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
{$ENDIF}
{$IFDEF CLR}
protected
{$ENDIF}
procedure TeeEvent(Event: TTeeEvent);
protected
{$IFDEF CLX}
procedure BoundsChanged; override;
{$ENDIF}
procedure BtnClick(Index: TTeeNavigateBtn); dynamic;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure InitButtons; virtual;
procedure Loaded; override;
procedure DoTeeEvent(Event: TTeeEvent); virtual;
procedure Notification( AComponent: TComponent;
Operation: TOperation); override;
procedure SetPanel(const Value: TCustomTeePanel); virtual; // 7.0
public
Buttons: Array[TTeeNavigateBtn] of TTeeNavButton;
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
procedure EnableButtons; virtual;
procedure InitHints; { 5.02 }
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
Function PageCount:Integer; virtual;
property Panel:TCustomTeePanel read FPanel write SetPanel;
procedure Print; virtual;
property OnButtonClicked:TNotifyButtonClickedEvent read FOnButtonClicked
write FOnButtonClicked;
published
{ TPanel properties }
property Align;
property BorderStyle;
property Color;
{$IFNDEF CLX}
{$IFNDEF TEEOCX}
property UseDockManager default True;
property DockSite;
{$ENDIF}
{$ENDIF}
property DragMode;
{$IFNDEF CLX}
property DragCursor;
{$ENDIF}
property Enabled;
property ParentColor;
property ParentShowHint;
{$IFNDEF TEEOCX}
property PopupMenu;
{$ENDIF}
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Anchors;
{$IFNDEF TEEOCX}
property Constraints;
{$ENDIF}
{$IFNDEF CLX}
property DragKind;
property Locked;
{$ENDIF}
{ TPanel events }
property OnClick;
property OnDblClick;
{$IFNDEF CLX}
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
{$ENDIF}
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnResize;
{$IFNDEF CLX}
property OnCanResize;
{$ENDIF}
{$IFNDEF TEEOCX}
property OnConstrainedResize;
{$IFNDEF CLX}
property OnDockDrop;
property OnDockOver;
property OnEndDock;
property OnGetSiteInfo;
property OnStartDock;
property OnUnDock;
{$ENDIF}
{$ENDIF}
end;
TTeePageNavigatorClass=class of TCustomTeeNavigator;
implementation
Uses SysUtils,
{$IFDEF CLX}
QForms, Qt,
{$ELSE}
Forms,
{$ENDIF}
TeCanvas, TeeConst;
Const
InitRepeatPause = 400; { pause before repeat timer (ms) }
RepeatPause = 100; { pause before hint window displays (ms)}
SpaceSize = 5; { size of space between special buttons }
BtnTypeName: array[TTeeNavigateBtn] of
{$IFDEF CLR}String{$ELSE}PChar{$ENDIF} = ('First', 'Prior', 'Next',
'Last', 'Insert', 'Delete', 'Edit', 'Post', 'Cancel');
{ TCustomTeeNavigator }
Constructor TCustomTeeNavigator.Create(AOwner: TComponent);
begin
inherited;
ControlStyle:=ControlStyle-[csAcceptsControls,csSetCaption] + [csOpaque];
{$IFNDEF CLX}
if not NewStyleControls then ControlStyle:=ControlStyle + [csFramed];
{$ENDIF}
FHints:=TStringList.Create;
TStringList(FHints).OnChange:=HintsChanged;
InitButtons;
InitHints;
BevelOuter:=bvNone;
BevelInner:=bvNone;
Width:=241;
Height:=25;
FocusedButton:=nbFirst;
{$IFNDEF CLX}
FullRepaint:=False;
{$ENDIF}
end;
Destructor TCustomTeeNavigator.Destroy;
begin
FDefHints.Free;
FHints.Free;
Panel:=nil;
inherited;
end;
procedure TCustomTeeNavigator.InitHints;
var I : Integer;
J : TTeeNavigateBtn;
begin
if not Assigned(FDefHints) then
FDefHints:=TStringList.Create;
with FDefHints do
begin
Clear;
Add(TeeMsg_First);
Add(TeeMsg_Prior);
Add(TeeMsg_Next);
Add(TeeMsg_Last);
Add(TeeMsg_Insert);
Add(TeeMsg_Delete);
Add(TeeMsg_Edit);
Add(TeeMsg_Post);
Add(TeeMsg_Cancel);
end;
for J:=Low(Buttons) to High(Buttons) do
Buttons[J].Hint:=FDefHints[Ord(J)];
J := Low(Buttons);
for I := 0 to (FHints.Count - 1) do
begin
if FHints.Strings[I] <> '' then Buttons[J].Hint := FHints.Strings[I];
if J = High(Buttons) then Exit;
Inc(J);
end;
end;
procedure TCustomTeeNavigator.HintsChanged(Sender: TObject);
begin
InitHints;
end;
procedure TCustomTeeNavigator.SetSize(var W: Integer; var H: Integer);
var Count : Integer;
MinW : Integer;
I : TTeeNavigateBtn;
Space : Integer;
Temp : Integer;
Remain : Integer;
X : Integer;
ButtonH: Integer;
begin
if (csLoading in ComponentState) then Exit;
if Buttons[nbFirst] = nil then Exit;
Count := 0;
for I := Low(Buttons) to High(Buttons) do
begin
if Buttons[I].Visible then
begin
Inc(Count);
end;
end;
if Count = 0 then Inc(Count);
MinW := Count * MinBtnSize.X;
if W < MinW then W := MinW;
if H < MinBtnSize.Y then H := MinBtnSize.Y;
ButtonH:=H;
if BorderStyle=bsSingle then Dec(ButtonH,4);
ButtonWidth := W div Count;
Temp := Count * ButtonWidth;
if Align = alNone then W := Temp;
X := 0;
Remain := W - Temp;
Temp := Count div 2;
for I := Low(Buttons) to High(Buttons) do
begin
if Buttons[I].Visible then
begin
Space := 0;
if Remain <> 0 then
begin
Dec(Temp, Remain);
if Temp < 0 then
begin
Inc(Temp, Count);
Space := 1;
end;
end;
Buttons[I].SetBounds(X, 0, ButtonWidth + Space, ButtonH);
Inc(X, ButtonWidth + Space);
end
else
Buttons[I].SetBounds (Width + 1, 0, ButtonWidth, Height);
end;
end;
procedure TCustomTeeNavigator.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var W : Integer;
H : Integer;
begin
W:=AWidth;
H:=AHeight;
if not HandleAllocated then SetSize(W,H);
inherited SetBounds(ALeft,ATop,W,H);
end;
procedure TCustomTeeNavigator.CheckSize;
var W : Integer;
H : Integer;
begin
{ check for minimum size }
W:=Width;
H:=Height;
SetSize(W,H);
if (W<>Width) or (H<>Height) then inherited SetBounds(Left,Top,W,H);
end;
{$IFNDEF CLX}
procedure TCustomTeeNavigator.WMSize(var Message: TWMSize);
begin
inherited;
CheckSize;
Message.Result := 0;
end;
{$ENDIF}
procedure TCustomTeeNavigator.BtnMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var OldFocus: TTeeNavigateBtn;
begin
OldFocus:=FocusedButton;
FocusedButton:=TTeeNavButton(Sender).Index;
if TabStop {$IFNDEF CLX}and (GetFocus<>Handle){$ENDIF} and CanFocus then
begin
SetFocus;
{$IFNDEF CLX}if (GetFocus<>Handle) then Exit;{$ENDIF}
end
else if TabStop {$IFNDEF CLX}and (GetFocus=Handle){$ENDIF} and (OldFocus<>FocusedButton) then
begin
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
{$IFNDEF CLX}
procedure TCustomTeeNavigator.WMSetFocus(var Message: TWMSetFocus);
begin
Buttons[FocusedButton].Invalidate;
end;
procedure TCustomTeeNavigator.WMKillFocus(var Message: TWMKillFocus);
begin
Buttons[FocusedButton].Invalidate;
end;
{$ENDIF}
procedure TCustomTeeNavigator.KeyDown(var Key: Word; Shift: TShiftState);
var NewFocus : TTeeNavigateBtn;
OldFocus : TTeeNavigateBtn;
begin
OldFocus:=FocusedButton;
case Key of
TeeKey_Right :
begin
NewFocus := FocusedButton;
repeat
if NewFocus < High(Buttons) then NewFocus := Succ(NewFocus);
until (NewFocus = High(Buttons)) or (Buttons[NewFocus].Visible);
if NewFocus <> FocusedButton then
begin
FocusedButton := NewFocus;
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
TeeKey_Left :
begin
NewFocus := FocusedButton;
repeat
if NewFocus > Low(Buttons) then
NewFocus := Pred(NewFocus);
until (NewFocus = Low(Buttons)) or (Buttons[NewFocus].Visible);
if NewFocus <> FocusedButton then
begin
FocusedButton := NewFocus;
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
TeeKey_Space :
if Buttons[FocusedButton].Enabled then Buttons[FocusedButton].Click;
end;
end;
{$IFNDEF CLX}
procedure TCustomTeeNavigator.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result:=DLGC_WANTARROWS;
end;
{$ENDIF}
procedure TCustomTeeNavigator.ClickHandler(Sender: TObject);
begin
BtnClick(TTeeNavButton(Sender).Index);
end;
{$IFNDEF CLX}
procedure TCustomTeeNavigator.CMEnabledChanged(var Message: TMessage);
begin
inherited;
if not (csLoading in ComponentState) then EnableButtons;
end;
{$ENDIF}
procedure TCustomTeeNavigator.BtnClick(Index: TTeeNavigateBtn);
begin
EnableButtons;
if Assigned(FOnButtonClicked) then FOnButtonClicked(Index);
end;
procedure TCustomTeeNavigator.Loaded;
begin
inherited;
CheckSize;
InitHints;
EnableButtons;
end;
procedure TCustomTeeNavigator.EnableButtons;
begin
end;
{$IFDEF CLR}
{$R 'TeeNav_Cancel.bmp'}
{$R 'TeeNav_Edit.bmp'}
{$R 'TeeNav_Delete.bmp'}
{$R 'TeeNav_First.bmp'}
{$R 'TeeNav_Insert.bmp'}
{$R 'TeeNav_Last.bmp'}
{$R 'TeeNav_Next.bmp'}
{$R 'TeeNav_Post.bmp'}
{$R 'TeeNav_Prior.bmp'}
{$ELSE}
{$R TeeNavig.res}
{$ENDIF}
procedure TCustomTeeNavigator.InitButtons;
var I : TTeeNavigateBtn;
X : Integer;
ResName : string;
begin
MinBtnSize:=TeePoint(20,18);
X:=0;
for I:=Low(Buttons) to High(Buttons) do
begin
Buttons[I]:=TTeeNavButton.Create(Self);
With Buttons[I] do
begin
Flat:=True;
Index:=I;
Visible:=True;
Enabled:=False;
SetBounds(X, 0, MinBtnSize.X, MinBtnSize.Y);
FmtStr(ResName, 'TeeNav_%s', [BtnTypeName[I]]);
{$IFDEF CLR}
TeeLoadBitmap(Glyph,ResName,'');
{$ELSE}
Glyph.LoadFromResourceName(HInstance, ResName);
{$ENDIF}
NumGlyphs:=2;
OnClick:=ClickHandler;
OnMouseDown:=BtnMouseDown;
Parent:=Self;
Inc(X,MinBtnSize.X);
end;
end;
Buttons[nbInsert].Visible:=False;
Buttons[nbDelete].Visible:=False;
Buttons[nbEdit].Visible:=False;
Buttons[nbPost].Visible:=False;
Buttons[nbCancel].Visible:=False;
end;
{$IFNDEF CLR}
type
TTeePanelAccess=class(TCustomTeePanel);
{$ENDIF}
procedure TCustomTeeNavigator.SetPanel(const Value: TCustomTeePanel);
begin
if FPanel<>Value then
begin
if Assigned(FPanel) then
begin
{$IFDEF D5}
FPanel.RemoveFreeNotification(Self);
{$ENDIF}
{$IFNDEF CLR}TTeePanelAccess{$ENDIF}(FPanel).RemoveListener(Self);
end;
FPanel:=Value;
if Assigned(FPanel) then
begin
FPanel.FreeNotification(Self);
{$IFNDEF CLR}TTeePanelAccess{$ENDIF}(FPanel).Listeners.Add(Self);
end;
EnableButtons;
end;
end;
procedure TCustomTeeNavigator.TeeEvent(Event: TTeeEvent);
begin
DoTeeEvent(Event);
end;
procedure TCustomTeeNavigator.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and Assigned(FPanel) and (AComponent=FPanel) then
Panel:=nil;
end;
{$IFDEF CLX}
procedure TCustomTeeNavigator.BoundsChanged;
var W, H: Integer;
begin
inherited;
W := Width;
H := Height;
SetSize(W, H);
end;
{$ENDIF}
procedure TCustomTeeNavigator.DoTeeEvent(Event: TTeeEvent);
begin
end;
Function TCustomTeeNavigator.PageCount:Integer;
begin
result:=1; // abstract
end;
procedure TCustomTeeNavigator.Print;
begin
end;
{ TTeeNavButton }
Destructor TTeeNavButton.Destroy;
begin
FRepeatTimer.Free;
inherited;
end;
procedure TTeeNavButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
if FRepeatTimer = nil then
FRepeatTimer := TTimer.Create(Self);
FRepeatTimer.OnTimer := TimerExpired;
FRepeatTimer.Interval := InitRepeatPause;
FRepeatTimer.Enabled := True;
end;
procedure TTeeNavButton.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
if Assigned(FRepeatTimer) then FRepeatTimer.Enabled:=False;
end;
procedure TTeeNavButton.TimerExpired(Sender: TObject);
begin
FRepeatTimer.Interval:=RepeatPause;
if (FState=bsDown) and {$IFDEF CLR}(Self as IControl).{$ENDIF}MouseCapture then
begin
try
Click;
except
FRepeatTimer.Enabled:=False;
raise;
end;
end;
end;
procedure TTeeNavButton.Paint;
var R : TRect;
begin
inherited;
if {$IFNDEF CLX}(GetFocus=Parent.Handle) and{$ENDIF}
(FIndex=TCustomTeeNavigator(Parent).FocusedButton) then
begin
R:=TeeRect(3,3,Width-3,Height-3);
if FState=bsDown then OffsetRect(R,1,1);
{$IFDEF CLX}
Canvas.DrawFocusRect(R);
{$ELSE}
DrawFocusRect(Canvas.Handle,R);
{$ENDIF}
end;
end;
end.
|
unit sanSimplePersistence;
interface
uses
classes,
sanPersistence;
type
TsanSimpleObjectStorage = class (TsanObjectStorage)
private
fList : TList;
protected
function GetObject (AID : TsanOID) : isanObject; override;
public
constructor Create;
destructor Destroy; override;
function AddObject (AObject : isanObject; AObjectClass : TsanClassID = 0) : TsanOID; override;
procedure DeleteObject (AID : TsanOID); override;
end;
implementation
uses
SysUtils; // FreeAndNil
constructor TsanSimpleObjectStorage.Create;
begin
inherited;
fList := TList.Create;
end;
destructor TsanSimpleObjectStorage.Destroy;
begin
FreeAndNil (fList);
inherited;
end;
function TsanSimpleObjectStorage.GetObject (AID : TsanOID) : isanObject;
begin
Result := TsanObject (fList [AID]);
end;
function TsanSimpleObjectStorage.AddObject (AObject : isanObject; AObjectClass : TsanClassID = 0) : TsanOID;
begin
Result := fList.Add (pointer (AObject));
end;
procedure TsanSimpleObjectStorage.DeleteObject (AID : TsanOID);
begin
fList.Delete (AID);
end;
end.
|
unit AbsUsersFrm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids, Db, DBTables, DBGrids, ExtCtrls, DBCtrls, BtrDS, Menus,
ComCtrls, StdCtrls, Buttons, SearchFrm, AbsUserFrm, Common, Basbn,
Utilits, BankCnBn, DbfDataSet, Registr, Orakle;
type
TAbsUsersForm = class(TDataBaseForm)
StatusBar: TStatusBar;
DBGrid: TDBGrid;
DataSource: TDataSource;
ChildMenu: TMainMenu;
OperItem: TMenuItem;
InsItem: TMenuItem;
EditItem: TMenuItem;
CopyItem: TMenuItem;
DelItem: TMenuItem;
EditBreaker: TMenuItem;
FindItem: TMenuItem;
EditPopupMenu: TPopupMenu;
EditBreaker2: TMenuItem;
LoadNewFromQrmItem: TMenuItem;
LoadAndUpdateItem: TMenuItem;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SearchBtnClick(Sender: TObject);
procedure InsItemClick(Sender: TObject);
procedure EditItemClick(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure DelItemClick(Sender: TObject);
procedure DBGridDblClick(Sender: TObject);
procedure LoadNewFromQrmItemClick(Sender: TObject);
procedure LoadAndUpdateItemClick(Sender: TObject);
private
FOperDataSet: TOperDataSet;
procedure UpdateRecord(CopyCurrent, New: Boolean);
public
SearchForm: TSearchForm;
end;
var
ObjList: TList;
AbsUsersForm: TAbsUsersForm;
implementation
{$R *.DFM}
var
KliringBikMask: string = '';
procedure TAbsUsersForm.FormCreate(Sender: TObject);
begin
ObjList.Add(Self);
FOperDataSet := GlobalBase(biOper) as TOperDataSet;
DataSource.DataSet := FOperDataSet;
DefineGridCaptions(DBGrid, PatternDir+'Oper.tab');
SearchForm := TSearchForm.Create(Self);
SearchForm.SourceDBGrid := DBGrid;
TakeMenuItems(OperItem, EditPopupMenu.Items);
EditPopupMenu.Images := ChildMenu.Images;
KliringBikMask := DecodeMask('$(KliringBikMask)', 5, GetUserNumber);
while Length(KliringBikMask)<9 do
KliringBikMask := KliringBikMask + '?';
end;
procedure TAbsUsersForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FormStyle=fsMDIChild then
Action:=caFree;
end;
procedure TAbsUsersForm.FormDestroy(Sender: TObject);
begin
ObjList.Remove(Self);
if Self=AbsUsersForm then
AbsUsersForm := nil;
end;
procedure TAbsUsersForm.SearchBtnClick(Sender: TObject);
begin
SearchForm.ShowModal;
end;
procedure TAbsUsersForm.UpdateRecord(CopyCurrent, New: Boolean);
const
ProcTitle: PChar = 'Редактирование опера';
var
AbsUserForm: TAbsUserForm;
QrmOperRec: TQrmOperRec;
Editing: Boolean;
begin
if not DataSource.DataSet.IsEmpty or (New and not CopyCurrent) then
begin
AbsUserForm := TAbsUserForm.Create(Self);
with AbsUserForm do
begin
if CopyCurrent then
begin
FOperDataSet.GetBtrRecord(PChar(@QrmOperRec));
DosToWinL(QrmOperRec.onName, SizeOf(QrmOperRec.onName));
QrmNameEdit.Text := OrGetUserNameByCode(QrmOperRec.onIder);
end
else
FillChar(QrmOperRec, SizeOf(QrmOperRec), #0);
with QrmOperRec do
begin
IdEdit.Text := IntToStr(onIder);
NameEdit.Text := onName;
if Length(NameEdit.Text)>SizeOf(onName) then
NameEdit.Text := Copy(NameEdit.Text, 1, SizeOf(onName));
end;
Editing := True;
while Editing and (ShowModal = mrOk) do
begin
Editing := False;
FillChar(QrmOperRec, SizeOf(QrmOperRec), #0);
with QrmOperRec do
begin
onIder := StrToInt(IdEdit.Text);
StrPLCopy(onName, NameEdit.Text, SizeOf(onName)-1);
WinToDos(onName);
end;
if New then begin
if FOperDataSet.AddBtrRecord(PChar(@QrmOperRec),
SizeOf(QrmOperRec))
then
FOperDataSet.Refresh
else begin
Editing := True;
MessageDlg('',mtError,[mbOk,mbHelp],0);
MessageBox(Handle, 'Невозможно добавить запись', ProcTitle,
MB_OK or MB_ICONERROR)
end;
end else begin
if FOperDataSet.UpdateBtrRecord(PChar(@QrmOperRec),
SizeOf(QrmOperRec))
then
FOperDataSet.UpdateCursorPos
else begin
Editing := True;
MessageBox(Handle, 'Невозможно изменить запись', ProcTitle,
MB_OK or MB_ICONERROR)
end;
end;
end;
Free;
end;
end;
end;
procedure TAbsUsersForm.InsItemClick(Sender: TObject);
begin
UpdateRecord(False, True);
end;
procedure TAbsUsersForm.EditItemClick(Sender: TObject);
begin
UpdateRecord(True, False);
end;
procedure TAbsUsersForm.CopyItemClick(Sender: TObject);
begin
UpdateRecord(True, True)
end;
procedure TAbsUsersForm.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 or MB_ICONQUESTION) = IDYES)
or (N>=2) and (MessageBox(Handle, PChar('Будет удалено оперов: '
+IntToStr(DBGrid.SelectedRows.Count)+#13#10'Вы уверены?'),
MesTitle, MB_YESNOCANCEL or MB_ICONQUESTION) = IDYES) then
begin
if N>0 then
begin
DBGrid.SelectedRows.Delete;
DBGrid.SelectedRows.Refresh;
end
else
FOperDataSet.Delete;
end;
end;
end;
procedure TAbsUsersForm.DBGridDblClick(Sender: TObject);
begin
if FormStyle=fsMDIChild then
EditItemClick(Sender)
else
ModalResult := mrOk;
end;
procedure TAbsUsersForm.LoadNewFromQrmItemClick(Sender: TObject);
const
MesTitle: PChar = 'Загрузка новых операторов';
var
I, K, J, N, Len, Res: Integer;
S: string;
QrmOperRec: TQrmOperRec;
begin
if OraBase.OrDb.Connected then
begin
K := 0;
J := 0;
N := 0;
if (Sender=nil) and (MessageBox(Handle, 'Вы уверны, что хотите заменить все имена?',
MesTitle, MB_YESNOCANCEL or MB_DEFBUTTON2 or MB_ICONINFORMATION)<>ID_YES)
then
Sender := Self;
with OraBase, OrQuery3 do
begin
SQL.Clear;
SQL.Add('Select xu$id,xu$name from '+OrScheme+'.x$users');
Open;
First;
while not Eof do
begin
Inc(K);
I := FieldByName('xu$id').AsInteger;
Len := SizeOf(QrmOperRec);
Res := FOperDataSet.BtrBase.GetEqual(QrmOperRec, Len, I, 0);
if (Res<>0) or (Sender=nil) then
begin
S := Trim(FieldbyName('xu$name').AsString);
with QrmOperRec do
begin
onIder := I;
StrPLCopy(onName, S, SizeOf(onName)-1);
WinToDos(onName);
Len := 4+StrLen(onName)+1;
end;
if Res=0 then
begin
Res := FOperDataSet.BtrBase.Update(QrmOperRec, Len, I, 0);
if Res=0 then
Inc(N);
end
else begin
Res := FOperDataSet.BtrBase.Insert(QrmOperRec, Len, I, 0);
if Res=0 then
Inc(J);
end;
end;
Next;
end;
FOperDataSet.Refresh;
end;
MessageBox(Handle, PChar('Всего просмотрено: '+IntToStr(K)
+#13#10'добавлено новых: '+IntToStr(J)
+#13#10'изменено: '+IntToStr(N)), MesTitle, MB_OK or MB_ICONINFORMATION);
end;
end;
procedure TAbsUsersForm.LoadAndUpdateItemClick(Sender: TObject);
begin
LoadNewFromQrmItemClick(nil);
end;
end.
|
unit fw_system_types;
interface
type
// ----------------------------------------------- BEGIN OBJECT FILE FORMAT
prt_oCode=^tRt_oCode; // Esto es un programa compilado
tRt_oCode=record
total_size :cardinal; // Tamaņo total en bytes de todo el oCode
user_data :pointer; // Por defecto esta a nil
cache_prop :cardinal; // Offset donde empieza la cache de propiedades: tRt_oCacheProp
num_cache_prop :cardinal; // Tanaņo de la cache de propiedades
num_regs :cardinal; // Nš de registros
blocks :cardinal; // Donde empiezan la lista: tRt_OBlock
num_blocks :cardinal; // Nš de bloques
strings :cardinal; // Donde empiezan los strings: pCharEx
num_strings :cardinal; // Nš de strings
base_address :pointer; // Direccion base
filename :cardinal; // Offset en la tabla de strings con el nombre del archivo
end;
pRt_oBlock=^tRt_oBlock;
tRt_OBlock=record // Esta es la definicion de un bloque
oCode:pRt_oCode; // Codigo al que pertenece el bloque
code_start:cardinal; // Posicion donde comienza el codigo del bloque tRt_Opcode
code_len:cardinal; // Longitud de todo el bloque
vars_len:cardinal; // Nš de variables que se declaran
vars_captures:cardinal; // Nš de variables que el bloque captura
vars_extern_captured:cardinal; // Nš de variables capturadas a las que accede
vars_params:cardinal; // Cuantas de las variables locales son parametros
name:cardinal; // Offset al nombre del bloque
var_names:cardinal; // Offset a una lista con los nombres de las variables
src_start,src_len:cardinal; // Posiciones en el codigo fuente donde empieza y longitud de la funcion que define el bloque
end;
pRt_oOpcode=^tRt_oOpcode;
tRt_oOpcode=record
opcode:cardinal;
k1,k2:cardinal;
v1,v2:longint;
end;
tRt_oCacheProp=record
k1,k2:cardinal;
v1,v2:longint;
end;
pRt_oCacheProp=^tRt_oCacheProp;
// ----------------------------------------------- END OBJECT FILE FORMAT
// ----------------------------------------------- BEGIN Compiler support
// La memoria con el codigo la liberara el host, asi pues el compilador necesita una funcion para asignar la memoria.
// El compilador necesita una funcion para hacer log de los mensajes, los niveles de Log Son
const
LOG_DEBUG =0;
LOG_WARNING =1;
LOG_ERROR =4;
// El compilador exporta la funcionSystem_Compile
type
TSystem_Alloc =function (sender,host_data:pointer;size:cardinal):pointer; stdcall;
TSystem_Log =function (sender,host_data:pointer;level:cardinal;msg:pchar):longint; stdcall;
TSystem_Compile =function (src,filename:pchar;host_data:pointer;alloc:TSystem_Alloc;log:TSystem_Log):pRT_oCode; stdcall;
// ----------------------------------------------- END System Provided routines !!!!
implementation
end.
|
unit EuroConv;
{ ***************************************************************************
Monetary conversion units
The constants, names and monetary logic in this unit follow the various EU
standards layed out in documents 397R1103, 398R2866 and 300R1478.
WARNING: In order for the rounding rules to exactly match the EU dictates
this unit will adjust your application's rounding mode to rmUp.
This will affect how rounding happens globally and may cause
unforeseen side effects in your application.
At the time of the writing of this document those documents where at
http://europa.eu.int/eur-lex/en/lif/dat/1997/en_397R1103.html
http://europa.eu.int/eur-lex/en/lif/dat/1998/en_398R2866.html
http://europa.eu.int/eur-lex/en/lif/dat/2000/en_300R1478.html
If not found there you can search for them on http://europa.eu.int/eur-lex
The conversion rates for US dollar, British pound and Japanese yen are
accurate as of 12/12/2000 at 18:35 EST and were as reported by
CNNfn (http://cnnfn.cnn.com/markets/currency)
Great monetary exchange rate sites
http://pacific.commerce.ubc.ca/xr/rates.html
http://www.imf.org/external/np/tre/sdr/drates/8101.htm
http://www.belgraver.demon.nl/currconv2/
***************************************************************************
References:
[1] Article 1 in http://europa.eu.int/eur-lex/en/lif/dat/1998/en_398R2866.html
[2] Article 1 in http://europa.eu.int/eur-lex/en/lif/dat/2000/en_300R1478.html
[3] Article 4.4 in http://europa.eu.int/eur-lex/en/lif/dat/1997/en_397R1103.html
}
interface
uses
ConvUtils, Math;
var
// *************************************************************************
// Euro Conversion Units
// basic unit of measurement is euro
cbEuro: TConvFamily;
euEUR: TConvType; { EU euro }
euBEF: TConvType; { Belgian francs }
euDEM: TConvType; { German marks }
euGRD: TConvType; { Greek drachmas }
euESP: TConvType; { Spanish pesetas }
euFFR: TConvType; { French francs }
euIEP: TConvType; { Irish pounds }
euITL: TConvType; { Italian lire }
euLUF: TConvType; { Luxembourg francs }
euNLG: TConvType; { Dutch guilders }
euATS: TConvType; { Austrian schillings }
euPTE: TConvType; { Portuguese escudos }
euFIM: TConvType; { Finnish marks }
euUSD: TConvType; { US dollars }
euGBP: TConvType; { British pounds }
euJPY: TConvType; { Japanese yens }
const
// Fixed conversion Euro rates [1]
EURToEUR = 1.00000;
BEFToEUR = 40.3399;
DEMToEUR = 1.95583;
GRDToEUR = 340.750; // [2] effective 1/1/2001
ESPToEUR = 166.386;
FFRToEUR = 6.55957;
IEPToEUR = 0.787564;
ITLToEUR = 1936.27;
LUFToEUR = 40.3399;
NLGToEUR = 2.20371;
ATSToEUR = 13.7603;
PTEToEUR = 200.482;
FIMToEUR = 5.94573;
// Subunit rounding for Euro conversion and expressed as powers of ten [3]
EURSubUnit = -2;
BEFSubUnit = 0;
DEMSubUnit = -2;
GRDSubUnit = 0; // [2] effective 1/1/2001
ESPSubUnit = 0;
FFRSubUnit = -2;
IEPSubUnit = -2;
ITLSubUnit = 0;
LUFSubUnit = -2;
NLGSubUnit = -2;
ATSSubUnit = -2;
PTESubUnit = -2;
FIMSubUnit = 0;
var
// Accurate as of 12/12/2000 at 16:42 PST but almost certainly isn't anymore
// Remember if you are changing these values in realtime you might, depending
// on your application's structure, have to deal with threading issues.
USDToEUR: Double = 1.1369;
GBPToEUR: Double = 1.6462;
JPYToEUR: Double = 0.0102;
// Subunit rounding for Euro conversion and expressed as powers of ten
USDSubUnit: Integer = -2;
GBPSubUnit: Integer = -2;
JPYSubUnit: Integer = -2;
// Registration methods
function RegisterEuroConversionType(const AFamily: TConvFamily;
const ADescription: string; const AFactor: Double;
const ARound: TRoundToRange): TConvType; overload;
function RegisterEuroConversionType(const AFamily: TConvFamily;
const ADescription: string; const AToCommonProc,
AFromCommonProc: TConversionProc): TConvType; overload;
// Types used during the conversion of Euro to and from other currencies
type
TConvTypeEuroFactor = class(TConvTypeFactor)
private
FRound: TRoundToRange;
public
constructor Create(const AConvFamily: TConvFamily;
const ADescription: string; const AFactor: Double;
const ARound: TRoundToRange);
function ToCommon(const AValue: Double): Double; override;
function FromCommon(const AValue: Double): Double; override;
end;
// various strings used in this unit
resourcestring
SEuroDescription = 'Euro';
SEURDescription = 'EUEuro';
SBEFDescription = 'BelgianFrancs';
SDEMDescription = 'GermanMarks';
SGRDDescription = 'GreekDrachmas';
SESPDescription = 'SpanishPesetas';
SFFRDescription = 'FrenchFrancs';
SIEPDescription = 'IrishPounds';
SITLDescription = 'ItalianLire';
SLUFDescription = 'LuxembourgFrancs';
SNLGDescription = 'DutchGuilders';
SATSDescription = 'AustrianSchillings';
SPTEDescription = 'PortugueseEscudos';
SFIMDescription = 'FinnishMarks';
SUSDDescription = 'USDollars';
SGBPDescription = 'BritishPounds';
SJPYDescription = 'JapaneseYens';
implementation
{ TConvTypeEuroFactor }
constructor TConvTypeEuroFactor.Create(const AConvFamily: TConvFamily;
const ADescription: string; const AFactor: Double;
const ARound: TRoundToRange);
begin
inherited Create(AConvFamily, ADescription, AFactor);
FRound := ARound;
end;
function TConvTypeEuroFactor.FromCommon(const AValue: Double): Double;
begin
Result := SimpleRoundTo(AValue * Factor, FRound);
end;
function TConvTypeEuroFactor.ToCommon(const AValue: Double): Double;
begin
Result := AValue / Factor;
end;
function RegisterEuroConversionType(const AFamily: TConvFamily;
const ADescription: string; const AFactor: Double;
const ARound: TRoundToRange): TConvType;
var
LInfo: TConvTypeInfo;
begin
LInfo := TConvTypeEuroFactor.Create(AFamily, ADescription, AFactor, ARound);
if not RegisterConversionType(LInfo, Result) then
begin
LInfo.Free;
RaiseConversionRegError(AFamily, ADescription);
end;
end;
function RegisterEuroConversionType(const AFamily: TConvFamily;
const ADescription: string; const AToCommonProc,
AFromCommonProc: TConversionProc): TConvType;
begin
Result := RegisterConversionType(AFamily, ADescription,
AToCommonProc, AFromCommonProc);
end;
function ConvertUSDToEUR(const AValue: Double): Double;
begin
Result := AValue * USDToEUR;
end;
function ConvertEURToUSD(const AValue: Double): Double;
begin
Result := SimpleRoundTo(AValue / USDToEUR, USDSubUnit);
end;
function ConvertGBPToEUR(const AValue: Double): Double;
begin
Result := AValue * GBPToEUR;
end;
function ConvertEURToGBP(const AValue: Double): Double;
begin
Result := SimpleRoundTo(AValue / GBPToEUR, GBPSubUnit);
end;
function ConvertJPYToEUR(const AValue: Double): Double;
begin
Result := AValue * JPYToEUR;
end;
function ConvertEURToJPY(const AValue: Double): Double;
begin
Result := SimpleRoundTo(AValue / JPYToEUR, JPYSubUnit);
end;
initialization
// Euro's family type
cbEuro := RegisterConversionFamily(SEuroDescription);
// Euro's various conversion types
euEUR := RegisterEuroConversionType(cbEuro, SEURDescription, EURToEUR, EURSubUnit);
euBEF := RegisterEuroConversionType(cbEuro, SBEFDescription, BEFToEUR, BEFSubUnit);
euDEM := RegisterEuroConversionType(cbEuro, SDEMDescription, DEMToEUR, DEMSubUnit);
euGRD := RegisterEuroConversionType(cbEuro, SGRDDescription, GRDToEUR, GRDSubUnit);
euESP := RegisterEuroConversionType(cbEuro, SESPDescription, ESPToEUR, ESPSubUnit);
euFFR := RegisterEuroConversionType(cbEuro, SFFRDescription, FFRToEUR, FFRSubUnit);
euIEP := RegisterEuroConversionType(cbEuro, SIEPDescription, IEPToEUR, IEPSubUnit);
euITL := RegisterEuroConversionType(cbEuro, SITLDescription, ITLToEUR, ITLSubUnit);
euLUF := RegisterEuroConversionType(cbEuro, SLUFDescription, LUFToEUR, LUFSubUnit);
euNLG := RegisterEuroConversionType(cbEuro, SNLGDescription, NLGToEUR, NLGSubUnit);
euATS := RegisterEuroConversionType(cbEuro, SATSDescription, ATSToEUR, ATSSubUnit);
euPTE := RegisterEuroConversionType(cbEuro, SPTEDescription, PTEToEUR, PTESubUnit);
euFIM := RegisterEuroConversionType(cbEuro, SFIMDescription, FIMToEUR, FIMSubUnit);
euUSD := RegisterEuroConversionType(cbEuro, SUSDDescription,
ConvertUSDToEUR, ConvertEURToUSD);
euGBP := RegisterEuroConversionType(cbEuro, SGBPDescription,
ConvertGBPToEUR, ConvertEURToGBP);
euJPY := RegisterEuroConversionType(cbEuro, SJPYDescription,
ConvertJPYToEUR, ConvertEURToJPY);
finalization
// Unregister all the conversion types we are responsible for
UnregisterConversionFamily(cbEuro);
end.
|
program parcial2018_tema5;
uses crt;
type Matriz = array[1..6,1..6] of Integer;
procedure CargarMatriz(var M: Matriz);
var
i,j: Integer;
begin
for i := 1 to 6 do
begin
for j := 1 to 6 do
begin
M[i,j]:=100+random(999+1-100);
end;
end;
end;
procedure MostrarMatriz(M:Matriz);
var
i,j: Integer;
begin
for i := 1 to 6 do
begin
for j:=1 to 6 do
begin
write(M[i,j]:5);
end;
writeln;
end;
end;
procedure Transponer(M1:Matriz;var M2:Matriz);
var
i,j: Integer;
begin
for i := 1 to 6 do
begin
for j := 1 to 6 do
begin
M2[i,j]:=M1[j,i];
end;
end;
end;
{Main}
var
M1,M2: Matriz;
BEGIN
CargarMatriz(M1);
MostrarMatriz(M1);
Transponer(M1,M2);
writeln;writeln;
MostrarMatriz(M2);
END. |
unit BCscore.AskForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TAskForm = class(TForm)
pnlCancel: TPanel;
lblCancelShortcut: TLabel;
lblCancelText: TLabel;
pnlConfirm: TPanel;
lblConfirmShortcut: TLabel;
lblConfirmText: TLabel;
pnlMessage: TPanel;
lblMessageText: TLabel;
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
procedure SetMessage(const Value: string);
{ Private declarations }
public
property &Message: string write SetMessage;
end;
var
AskForm: TAskForm;
implementation
uses BCscore.Consts;
{$R *.dfm}
procedure TAskForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
ckCancel:
ModalResult := mrCancel;
ckConfirm:
ModalResult := mrOk;
else
inherited;
end;
end;
procedure TAskForm.FormShow(Sender: TObject);
begin
Color := clAskBackPanel;
pnlMessage.Color := clMessagePanel;
lblMessageText.Font.Color := clNormalText;
pnlCancel.Color := clCancelPanel;
lblCancelText.Font.Color := clNormalText;
lblCancelShortcut.Color := clShortcutText;
lblCancelShortcut.Font.Color := clCancelPanel;
pnlConfirm.Color := clConfirmPanel;
lblConfirmShortcut.Color := clShortcutText;
lblConfirmShortcut.Font.Color := clConfirmPanel;
lblConfirmText.Font.Color := clNormalText;
end;
procedure TAskForm.SetMessage(const Value: string);
begin
lblMessageText.Caption := Value;
end;
end.
|
{******************************************}
{ }
{ vtk GridReport library }
{ }
{ Copyright (c) 2003 by vtkTools }
{ }
{******************************************}
{ Contains @link(TvgrColorButton) - component used for represents a button that lets users select a color.
Use TvgrColorButton to provide the
user with a button with drop down panel from which to select a color.
See also:
vgr_FontComboBox,vgr_ControlBar,vgr_Label}
unit vgr_ColorButton;
{$I vtk.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
stdctrls, vgr_Button;
const
{ Count of color buttons per width of drop down panel. }
ColorPerX = 4;
{ Count of color buttons per height of drop down panel. }
ColorPerY = 5;
{ Width of color button. }
ColorBoxWidth = 21;
{ Height of color button. }
ColorBoxHeight = 21;
{ Width of "Other color" button. }
OtherColorButtonWidth = 65;
{ Height of "Other color" button. }
OtherColorButtonHeight = 21;
{ Height of "Transparent" button. }
TransparentButtonHeight = 21;
{ Default caption of "Other color" button. }
svgrOtherColor = 'Other...';
{ Default caption of "Transparent" button. }
svgrTransparentColor = 'Transparent';
type
TvgrColorButton = class;
{ Specifies type of place within drop down panel.
Syntax:
TvgrButtonType = (vgrbtNone, vgrbtColorBox, vgrbtOtherColorBox,
vgrbtOtherColor, vgrbtTransparent);
Items:
vgrbtNone - within empty space
vgrbtColorBox - within one of color buttons
vgrbtOtherColorBox - within other color box
vgrbtOtherColor - within "Other color" button
vgrbtTransparent - within "Transparent" button}
TvgrButtonType = (vgrbtNone, vgrbtColorBox, vgrbtOtherColorBox, vgrbtOtherColor, vgrbtTransparent);
{
This event is called when user select a color.
Syntax:
TvgrColorSelectedEvent = procedure (Sender: TObject; Color: TColor) of object
Parameters:
Sender - indicates which component received the event and therefore called the handler
Color - color that the user selects
}
TvgrColorSelectedEvent = procedure (Sender: TObject; Color: TColor) of object;
/////////////////////////////////////////////////
//
// TvgrColorPaletteForm
//
/////////////////////////////////////////////////
{TvgrColorPaletteForm implements drop down panel, which are showing when user click on TvgrColorButton.
Also this form can be shown separately, with use of a PopupPaletteForm method. }
TvgrColorPaletteForm = class(TvgrDropDownForm)
ColorDialog: TColorDialog;
procedure FormPaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ColorDialogShow(Sender: TObject);
private
{ Private declarations }
FSelectedColor: TColor;
FOtherColor: TColor;
FOtherString: string;
FTransparentString: string;
FOnColorSelected: TvgrColorSelectedEvent;
FLastButtonType: TvgrButtonType;
FLastColorButtonPos: TPoint;
FColorButtonsRect: TRect;
FOtherColorButtonRect: TRect;
FOtherColorBox: TRect;
FTransparentButtonRect: TRect;
function GetSelectedColor : TColor;
function IsColorExists(var AColor: TColor): Boolean;
function GetColorButtonRect(const AColorButtonPos: TPoint): TRect;
function GetButtonRect(AButtonType: TvgrButtonType; const AColorButtonPos: TPoint): TRect;
procedure SetSelectedColor(Value : TColor);
procedure SetOtherColor(Value : TColor);
procedure GetPointInfoAt(const APos: TPoint; var AButtonType: TvgrButtonType; var AColorButtonPos: TPoint);
procedure DrawButton(AButtonType: TvgrButtonType; const AColorButtonPos : TPoint; Selected, Highlighted : boolean);
function GetButton: TvgrColorButton;
protected
property Button: TvgrColorButton read GetButton;
public
{ Specifies current selected color.
If user click on "Transparent" button, SelectedColor equals clNone. }
property SelectedColor : TColor read GetSelectedColor write SetSelectedColor;
{ Specifies color, selected with "other color" button. }
property OtherColor : TColor read FOtherColor write SetOtherColor;
{ Specifies caption of "Other color" button. Default value - "Other...". }
property OtherString : string read FOtherString write FOtherString;
{ Specifies caption of "Transparent" button. Default value - "Transparent". }
property TransparentString : string read FTransparentString write FTransparentString;
{ Occurs when user select color, by pressing color button or select color in dialog window. }
property OnColorSelected : TvgrColorSelectedEvent read FOnColorSelected write FOnColorSelected;
end;
/////////////////////////////////////////////////
//
// TvgrColorButton
//
/////////////////////////////////////////////////
{TvgrColorButton represents a button that lets users select a color.
Use TvgrColorButton to provide the user with a button with drop down panel
from which to select a color.
Use the SelectedColor property to access the color that the user selects.}
TvgrColorButton = class(TvgrBaseButton)
private
FSelectedColor: TColor;
FOtherColor: TColor;
FOnColorSelected: TvgrColorSelectedEvent;
FOtherString: string;
FTransparentString: string;
procedure SetSelectedColor(Value: TColor);
procedure SetOtherColor(Value: TColor);
procedure DoOnColorSelected(Sender: TObject; Color: TColor);
function IsOtherStringStored: Boolean;
function IsTransparentStringStored: Boolean;
function GetDropDownForm: TvgrColorPaletteForm;
protected
function GetDropDownFormClass: TvgrDropDownFormClass; override;
procedure ShowDropDownForm; override;
procedure DrawButtonInternal(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean; const AInternalRect: TRect); override;
property DropDownForm: TvgrColorPaletteForm read GetDropDownForm;
public
{Creates an instance of the TvgrColorButton class.
Parameters:
AOwner - Component that is responsible for freeing the button.
It becomes the value of the Owner property.}
constructor Create(AOwner : TComponent); override;
{Frees an instance of the TvgrColorButton class.}
destructor Destroy; override;
{Simulates a mouse click, as if the user had clicked the button.}
procedure Click; override;
published
property Action;
property Anchors;
property BiDiMode;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property ParentBiDiMode;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop default True;
property Visible;
{$IFDEF VGR_D5}
property OnContextPopup;
{$ENDIF}
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
{Specifies the value indicating whether the arrow is visible.}
property DropDownArrow default True;
{Use SelectedColor to get or set the selected color as a TColor value.
If user click on "Transparent" button, SelectedColor equals clNone. }
property SelectedColor: TColor read FSelectedColor write SetSelectedColor;
{Use OtherColor to get or set the color showing on other color box.}
property OtherColor: TColor read FOtherColor write SetOtherColor;
{Specifies caption of "Other color" button. Default value - "Other...".}
property OtherString: string read FOtherString write FOtherString stored IsOtherStringStored;
{Specifies caption of "Transparent" button. Default value - "Transparent".}
property TransparentString: string read FTransparentString write FTransparentString stored IsTransparentStringStored;
{Occurs when user select color in drop down panel, by pressing color button or select color in dialog window.}
property OnColorSelected: TvgrColorSelectedEvent read FOnColorSelected write FOnColorSelected;
end;
{ Use this metod to create and show TvgrColorPaletteForm at specified position.
AOwner - owner for the created form
X, Y - coordinates of the created form
this values is relative to the screen in pixels.
ASelectedColor - specifies initial value of TvgrColorPaletteForm.SelectedColor property.
AOtherColor - specifies initial value of TvgrColorPaletteForm.OtherColor property.
OnColorSelected - specifies event procedure, which are called when user select color.
AOtherString - caption for "Other color" button.
ATransparentString - caption for "Transparent" button.
Function returns reference to the created form. }
function PopupPaletteForm(AOwner: TComponent;
X, Y : integer;
ASelectedColor, AOtherColor : TColor;
OnColorSelected : TvgrColorSelectedEvent;
const AOtherString, ATransparentString : string) : TvgrColorPaletteForm;
implementation
uses
vgr_GUIFunctions, vgr_Functions;
const
LeftOffset = 2;
RightOffset = 2;
TopOffset = 2;
BottomOffset = 2;
DeltaXOffset = 2;
DeltaYOffset = 2;
var
aColors : array [0..ColorPerY - 1, 0..ColorPerX - 1] of TColor =
((clWhite,clBlack,clSilver,clGray),
(clRed,clMaroon,clYellow,clOlive),
(clLime,clGreen,clAqua,clTeal),
(clBlue,clNavy,clFuchsia,clPurple),
(clBtnFace,clHighlight,clBtnHighlight,clInactiveCaption));
{$R *.DFM}
function PopupPaletteForm(AOwner: TComponent;
X, Y : integer;
ASelectedColor, AOtherColor : TColor;
OnColorSelected : TvgrColorSelectedEvent;
const AOtherString, ATransparentString : string) : TvgrColorPaletteForm;
var
R: TRect;
begin
Result := TvgrColorPaletteForm.Create(AOwner);
Result.OtherColor := AOtherColor;
Result.SelectedColor := ASelectedColor;
Result.OtherString := AOtherString;
Result.TransparentString := ATransparentString;
Result.OnColorSelected := OnColorSelected;
SystemParametersInfo(SPI_GETWORKAREA, 0, @R, 0);
if X + Result.Width > r.Right then
X := X - Result.Width;
if Y + Result.Height > r.Bottom then
Y := Y - Result.Height;
Result.Left := X;
Result.Top := Y;
Result.Show;
end;
//////////////////////////////
//
// TvgrColorButton
//
//////////////////////////////
constructor TvgrColorButton.Create(AOwner : TComponent);
begin
inherited;
DropDownArrow := True;
Width := 45;
Height := 22;
TabStop := true;
FOtherString := svgrOtherColor;
FTransparentString := svgrTransparentColor;
end;
destructor TvgrColorButton.Destroy;
begin
inherited;
end;
function TvgrColorButton.IsOtherStringStored: Boolean;
begin
Result := FOtherString <> svgrOtherColor;
end;
function TvgrColorButton.IsTransparentStringStored: Boolean;
begin
Result := FTransparentString <> svgrTransparentColor;
end;
procedure TvgrColorButton.SetSelectedColor(Value: TColor);
begin
if FSelectedColor <> Value then
begin
FSelectedColor := Value;
Invalidate;
end;
end;
procedure TvgrColorButton.SetOtherColor(Value: TColor);
begin
if FOtherColor <> Value then
begin
FOtherColor := Value;
end;
end;
function TvgrColorButton.GetDropDownForm: TvgrColorPaletteForm;
begin
Result := TvgrColorPaletteForm(inherited DropDownForm);
end;
function TvgrColorButton.GetDropDownFormClass: TvgrDropDownFormClass;
begin
Result := TvgrColorPaletteForm;
end;
procedure TvgrColorButton.ShowDropDownForm;
begin
inherited;
DropDownForm.OnColorSelected := DoOnColorSelected;
DropDownForm.OtherColor := OtherColor;
DropDownForm.SelectedColor := SelectedColor;
DropDownForm.OtherString := OtherString;
DropDownForm.TransparentString := TransparentString;
end;
procedure TvgrColorButton.DrawButtonInternal(ADC: HDC; ADisabled, APushed, AFocused, AUnderMouse: Boolean; const AInternalRect: TRect);
var
r: TRect;
nbr: HBRUSH;
begin
r := AInternalRect;
if APushed then
begin
r.Top := r.Top + 1;
r.Left := r.Left + 1;
end;
// draw color box
if FSelectedColor<>clNone then
begin
R.Right := R.Right - 4;
R.Left := R.Left + 2;
DrawInnerBorder(ADC, r, false);
nbr := CreateSolidBrush(GetRGBColor(SelectedColor));
FillRect(ADC, R, nbr);
DeleteObject(nbr);
end;
end;
procedure TvgrColorButton.DoOnColorSelected(Sender: TObject; Color: TColor);
begin
OtherColor := DropDownForm.OtherColor;
SelectedColor := Color;
if Assigned(OnColorSelected) then
OnColorSelected(Self, SelectedColor);
end;
procedure TvgrColorButton.Click;
begin
ShowDropDownForm;
inherited;
end;
/////////////////////////////////////////////////
//
// TprColorPaletteForm
//
/////////////////////////////////////////////////
function TvgrColorPaletteForm.GetSelectedColor;
begin
if FSelectedColor <> clNone then
Result := GetRGBColor(FSelectedColor)
else
Result := FSelectedColor;
end;
function TvgrColorPaletteForm.IsColorExists(var AColor: TColor): Boolean;
var
I, J: integer;
begin
for I := 0 to ColorPerX - 1 do
for J := 0 to ColorPerY - 1 do
if GetRGBColor(aColors[J, I]) = AColor then
begin
AColor := AColors[J, I];
Result := True;
exit;
end;
Result := False;
end;
function TvgrColorPaletteForm.GetColorButtonRect(const AColorButtonPos: TPoint): TRect;
begin
Result.Left := LeftOffset + AColorButtonPos.X * (ColorBoxWidth + DeltaXOffset);
Result.Top := TopOffset + AColorButtonPos.Y * (ColorBoxHeight + DeltaYOffset);
Result.Right := Result.Left + ColorBoxWidth;
Result.Bottom := Result.Top + ColorBoxHeight;
end;
function TvgrColorPaletteForm.GetButtonRect(AButtonType: TvgrButtonType; const AColorButtonPos: TPoint): TRect;
begin
case AButtonType of
vgrbtColorBox: Result := GetColorButtonRect(AColorButtonPos);
vgrbtOtherColorBox: Result := FOtherColorBox;
vgrbtOtherColor: Result := FOtherColorButtonRect;
vgrbtTransparent: Result := FTransparentButtonRect;
else
Result := Rect(0, 0, 0, 0);
end;
end;
procedure TvgrColorPaletteForm.SetSelectedColor(Value: TColor);
begin
if FSelectedColor <> Value then
begin
if not IsColorExists(Value) then
FOtherColor := Value;
FSelectedColor := Value;
Invalidate;
end;
end;
procedure TvgrColorPaletteForm.SetOtherColor;
begin
if FOtherColor <> Value then
begin
FOtherColor := Value;
Invalidate;
end;
end;
procedure TvgrColorPaletteForm.GetPointInfoAt(const APos: TPoint; var AButtonType: TvgrButtonType; var AColorButtonPos: TPoint);
begin
if PtInRect(FColorButtonsRect, APos) then
begin
AButtonType := vgrbtColorBox;
AColorButtonPos.X := (APos.X - LeftOffset) div (ColorBoxWidth + DeltaXOffset);
AColorButtonPos.Y := (APos.Y - TopOffset) div (ColorBoxHeight + DeltaYOffset);
end
else
if PtInRect(FOtherColorBox, APos) then
AButtonType := vgrbtOtherColorBox
else
if PtInRect(FOtherColorButtonRect, APos) then
AButtonType := vgrbtOtherColor
else
if PtInRect(FTransparentButtonRect, APos) then
AButtonType := vgrbtTransparent
else
AButtonType := vgrbtNone;
end;
function TvgrColorPaletteForm.GetButton: TvgrColorButton;
begin
Result := TvgrColorButton(inherited Button);
end;
procedure TvgrColorPaletteForm.DrawButton(AButtonType: TvgrButtonType; const AColorButtonPos : TPoint; Selected, Highlighted : boolean);
var
r: TRect;
procedure DrawColorBox(Color: TColor);
begin
Canvas.Brush.Color := clBtnFace;
Canvas.FillRect(r);
if Selected or Highlighted then
begin
Canvas.Brush.Color := clHighlight;
Canvas.FrameRect(r);
InflateRect(r,-1,-1);
end;
if Highlighted then
begin
Canvas.Brush.Color := clBtnHighlight;
Canvas.FillRect(r);
end;
InflateRect(r,-4,-4);
Canvas.Brush.Color := clHighlight;
Canvas.FrameRect(r);
InflateRect(r,-1,-1);
Canvas.Brush.Color := Color;
Canvas.FillRect(r);
end;
procedure DrawPushButton(const s : string);
begin
if Selected or Highlighted then
begin
Canvas.Brush.Color := clHighlight;
Canvas.FrameRect(r);
InflateRect(r,-1,-1);
end;
if Highlighted then
Canvas.Brush.Color := clBtnHighlight
else
Canvas.Brush.Color := clBtnFace;
Canvas.FillRect(r);
DrawText(Canvas.Handle,PChar(s),length(s),r,DT_CENTER or DT_VCENTER or DT_SINGLELINE);
end;
begin
case AButtonType of
vgrbtColorBox:
begin
R := GetColorButtonRect(AColorButtonPos);
DrawColorBox(aColors[AColorButtonPos.y, AColorButtonPos.x]);
end;
vgrbtOtherColorBox:
begin
R := FOtherColorBox;
DrawColorBox(FOtherColor);
end;
vgrbtOtherColor:
begin
R := FOtherColorButtonRect;
DrawPushButton(FOtherString);
end;
vgrbtTransparent:
begin
R := FTransparentButtonRect;
DrawPushButton(FTransparentString);
end;
end;
end;
procedure TvgrColorPaletteForm.FormPaint(Sender: TObject);
var
r: TRect;
I, J: integer;
begin
Canvas.Brush.Color := clBtnFace;
Canvas.FillRect(ClientRect);
for I := 0 to ColorPerX - 1 do
for J := 0 to ColorPerY - 1 do
DrawButton(vgrbtColorBox, Point(I, J),
aColors[J, I] = FSelectedColor,
(FLastButtonType = vgrbtColorBox) and
(FLastColorButtonPos.X = I) and (FLastColorButtonPos.Y = J));
r := Rect(FColorButtonsRect.Left,
FColorButtonsRect.Bottom + 5,
FColorButtonsRect.Right,
FColorButtonsRect.Bottom + 5);
DrawEdge(Canvas.Handle, r, EDGE_ETCHED, BF_TOP);
DrawButton(vgrbtOtherColorBox, Point(0, 0), FSelectedColor = FOtherColor, FLastButtonType = vgrbtOtherColorBox);
DrawButton(vgrbtOtherColor, Point(0, 0), False, FLastButtonType = vgrbtOtherColor);
DrawButton(vgrbtTransparent, Point(0, 0), FSelectedColor = clNone, FLastButtonType = vgrbtTransparent);
end;
procedure TvgrColorPaletteForm.FormCreate(Sender: TObject);
begin
FOtherString := svgrOtherColor;
FTransparentString := svgrTransparentColor;
FColorButtonsRect := Rect(LeftOffset,
TopOffset,
LeftOffset + ColorPerX * ColorBoxWidth + (ColorPerX - 1) * DeltaXOffset,
TopOffset + ColorPerY * ColorBoxHeight+ (ColorPerY - 1) * DeltaYOffset);
FOtherColorButtonRect := Rect(LeftOffset,
FColorButtonsRect.Bottom + 10,
LeftOffset + OtherColorButtonWidth,
FColorButtonsRect.Bottom + 10 + OtherColorButtonHeight);
FOtherColorBox := Rect(FColorButtonsRect.Right - ColorBoxWidth,
FColorButtonsRect.Bottom + 10,
FColorButtonsRect.Right,
FColorButtonsRect.Bottom + 10 + ColorBoxHeight);
FTransparentButtonRect := Rect(FColorButtonsRect.Left,
FOtherColorButtonRect.Bottom + 4,
FColorButtonsRect.Right,
FOtherColorButtonRect.Bottom + 4 + TransparentButtonHeight);
ClientWidth := FColorButtonsRect.Right + RightOffset;
ClientHeight := FTransparentButtonRect.Bottom + BottomOffset
end;
procedure TvgrColorPaletteForm.FormMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
ANewColorButtonPos: TPoint;
ANewButtonType: TvgrButtonType;
ARect: TRect;
begin
GetPointInfoAt(Point(X, Y), ANewButtonType, ANewColorButtonPos);
if (FLastButtonType = ANewButtonType) and
((FLastButtonType <> vgrbtColorBox) or
((FLastColorButtonPos.x = ANewColorButtonPos.X) and
(FLastColorButtonPos.y = ANewColorButtonPos.Y))) then exit;
ARect := GetButtonRect(FLastButtonType, FLastColorButtonPos);
FLastButtonType := ANewButtonType;
FLastColorButtonPos := ANewColorButtonPos;
InvalidateRect(Handle, @ARect, False);
if FLastButtonType <> vgrbtNone then
begin
ARect := GetButtonRect(FLastButtonType, FLastColorButtonPos);
InvalidateRect(Handle, @ARect, False);
end;
end;
procedure TvgrColorPaletteForm.FormMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
ANewColorButtonPos : TPoint;
ANewButtonType : TvgrButtonType;
Color : TColor;
begin
GetPointInfoAt(Point(X,Y), ANewButtonType, ANewColorButtonPos);
if ANewButtonType = vgrbtNone then exit;
Color := clWhite;
case ANewButtonType of
vgrbtColorBox: Color := aColors[ANewColorButtonPos.Y, ANewColorButtonPos.X];
vgrbtOtherColorBox: Color := FOtherColor;
vgrbtOtherColor:
begin
ColorDialog.Color := FOtherColor;
if not ColorDialog.Execute then
exit;
Color := ColorDialog.Color;
OtherColor := Color;
end;
vgrbtTransparent: Color := clNone;
end;
SelectedColor := Color;
if Assigned(FOnColorSelected) then
FOnColorSelected(Self, SelectedColor);
Close;
end;
procedure TvgrColorPaletteForm.ColorDialogShow(Sender: TObject);
begin
SetWindowPos(ColorDialog.Handle,
HWND_TOPMOST,
0, 0, 0, 0,
SWP_NOMOVE or SWP_NOSIZE or SWP_NOACTIVATE);
end;
end.
|
unit View.Principal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, View.Base, System.Actions, Vcl.ActnList,
System.ImageList, Vcl.ImgList, Vcl.Menus, Enumerated.Menu;
type
TShowMenu = procedure(AIndex: Integer) of object;
type
TfrmMain = class(TfrmBase)
mmMenu: TMainMenu;
Detail1: TMenuItem;
Version1: TMenuItem;
Exit1: TMenuItem;
actVersion: TAction;
actExit: TAction;
actTax: TAction;
Register1: TMenuItem;
ax1: TMenuItem;
actFuel: TAction;
Fuel1: TMenuItem;
actTank: TAction;
ank1: TMenuItem;
actBomb: TAction;
actTankBomb: TAction;
actToFuel: TAction;
Bomb1: TMenuItem;
ankBomb1: TMenuItem;
oFuel1: TMenuItem;
procedure actVersionExecute(Sender: TObject);
procedure actExitExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure actTaxExecute(Sender: TObject);
private
FOnShowMenu: TShowMenu;
procedure SetOnShowMenu(const Value: TShowMenu);
function AssignMenu(AMenu: EMenu): Integer;
public
property OnShowMenu: TShowMenu read FOnShowMenu write SetOnShowMenu;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
procedure TfrmMain.actExitExecute(Sender: TObject);
begin
inherited;
if MessageDlg('Close System', TMsgDlgType.mtConfirmation, [mbYes, mbNo], 0,
mbNo) = mrYes then
Close;
end;
procedure TfrmMain.actTaxExecute(Sender: TObject);
begin
inherited;
if TAction(Sender).Tag < 0 then
raise Exception.Create('Menu Not Assigned');
OnShowMenu(TAction(Sender).Tag);
end;
procedure TfrmMain.actVersionExecute(Sender: TObject);
begin
inherited;
MessageDlg('Auto Post Version 1.0', TMsgDlgType.mtInformation, [mbOK], 0);
end;
function TfrmMain.AssignMenu(AMenu: EMenu): Integer;
begin
Result := -1;
case AMenu of
eTax:
Result := 0;
eFuel:
Result := 1;
eTank:
Result := 2;
eBomb:
Result := 3;
eTankBomb:
Result := 4;
eToFuel:
Result := 5;
end;
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
inherited;
actTax.Tag := AssignMenu(eTax);
actFuel.Tag := AssignMenu(eFuel);
actTank.Tag := AssignMenu(eTank);
actBomb.Tag := AssignMenu(eBomb);
actTankBomb.Tag := AssignMenu(eTankBomb);
actToFuel.Tag := AssignMenu(eToFuel);
end;
procedure TfrmMain.SetOnShowMenu(const Value: TShowMenu);
begin
FOnShowMenu := Value;
end;
initialization
ReportMemoryLeaksOnShutdown := True;
end.
|
unit MediaProcessing.Drawer.RGB.Impl;
interface
uses SysUtils,Windows,Classes, Graphics, BitmapStreamMediator,
MediaProcessing.Definitions,MediaProcessing.Global,MediaProcessing.Drawer.RGB;
type
TMediaProcessor_Drawer_Rgb_Impl =class (TMediaProcessor_Drawer_Rgb,IMediaProcessorImpl)
private
FBimap: TBitmap;
FBitmapStream : TBimapStreamMediator;
protected
procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses uBaseClasses;
constructor TMediaProcessor_Drawer_Rgb_Impl.Create;
begin
inherited;
FBimap:=TBitmap.Create;
FBitmapStream:=TBimapStreamMediator.Create;
end;
destructor TMediaProcessor_Drawer_Rgb_Impl.Destroy;
begin
FreeAndNil(FBitmapStream);
FreeAndNil(FBimap);
inherited;
end;
procedure TMediaProcessor_Drawer_Rgb_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal);
//var
//aFileHeader: BITMAPFILEHEADER;
//aBitmapHeader : BITMAPINFOHEADER;
begin
TArgumentValidation.NotNil(aInData);
aOutData:=nil;
aOutDataSize:=0;
aOutInfo:=nil;
aOutInfoSize:=0;
aOutFormat:=aInFormat;
(* TODO
ZeroMemory(@aFileHeader,sizeof(aFileHeader));
aFileHeader.bfType := $4d42; //"BM"
aFileHeader.bfReserved1 := 0;
aFileHeader.bfReserved2 := 0;
aFileHeader.bfOffBits := sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
aFileHeader.bfSize := aInDataSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
//Записываем в MJpeg наш bmp
aBitmapHeader:=aInFormat.ToBitMapInfoHeader(aInDataSize);
Assert(aBitmapHeader.biCompression=BI_RGB);
FBitmapStream.Init(@aFileHeader,@aBitmapHeader,aInData,aInDataSize);
//Записываем вверх ногами. Потому что MJpeg тоже записывает вверх ногами, в результате получится правильно
FBimap.LoadFromStream(FBitmapStream);
aOutData:=FBimap.ScanLine[0];
Assert(FBimap.PixelFormat=pf24bit);
aOutDataSize:=FBimap.Width*FBimap.Height*3;
aOutFormat:=aInFormat;
*)
end;
//initialization
//MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_Drawer_Rgb_Impl);
end.
|
unit UnClienteLookUp;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, StdCtrls, Controls,
Forms, Dialogs, ExtCtrls, ComCtrls, DB, SqlExpr, FMTBcd, Provider, DBClient,
Grids, DBGrids
{ Fluente }
;
type
TClienteLookUp = class(TObject)
private
FDataSource: TDataSource;
FEdit: TCustomEdit;
FList: TDBGrid;
FObserver: TNotifyEvent;
FParent: TControl;
protected
procedure ActivateList(const Sender: TObject);
procedure DeactivateList(const Sender: TObject);
procedure SelectProduto;
public
constructor Create(const EditControl: TCustomEdit;
const DataSource: TDataSource; const Parent: TControl;
const Observer: TNotifyEvent); reintroduce;
procedure ClearInstance;
procedure OnChange(Sender: TObject);
procedure OnEnter(Sender: TObject);
procedure OnExit(Sender: TObject);
procedure OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure OnKeyPress(Sender: TObject);
procedure OnKeyUp(Sender: TObject);
procedure ListOnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ListOnDblClick(Sender: TObject);
end;
var
ClienteLookUp: TClienteLookUp;
implementation
procedure TClienteLookUp.ActivateList(const Sender: TObject);
begin
if not Self.FList.Visible then
begin
Self.FList.Align := alClient;
Self.FList.Visible := True;
Self.FList.Parent := TWinControl(Sender);
Self.FParent.Height := 240;
Self.FParent.Visible := True;
end;
end;
procedure TClienteLookUp.ClearInstance;
begin
// Desfaz Referencias
Self.FDataSource := nil;
Self.FEdit := nil;
Self.FObserver := nil;
Self.FParent := nil;
// Libera objetos instanciados
Self.FList.DataSource := nil;
FreeAndNil(Self.FList);
end;
constructor TClienteLookUp.Create(const EditControl: TCustomEdit;
const DataSource: TDataSource; const Parent: TControl;
const Observer: TNotifyEvent);
begin
inherited Create();
Self.FDataSource := DataSource;
Self.FParent := Parent;
Self.FObserver := Observer;
// Referência ao Controle de Edição
Self.FEdit := EditControl;
//
// to-do: ligar eventos aos métodos
//
TEdit(Self.FEdit).OnChange := Self.OnChange;
TEdit(Self.FEdit).OnKeyDown := Self.OnKeyDown;
// Grid
Self.FList := TDBGrid.Create(nil);
Self.FList.Visible := False;
Self.FList.DataSource := Self.FDataSource;
Self.FList.Ctl3D := False;
Self.FList.Options := Self.FList.Options - [dgTitles, dgEditing, dgIndicator, dgColLines, dgRowLines] + [dgRowSelect];
Self.FList.Font.Name := 'Segoe UI';
Self.FList.Font.Size := 12;
Self.FList.Font.Style := [fsBold];
Self.FList.OnKeyDown := Self.ListOnKeyDown;
Self.FList.OnDblClick := Self.ListOnDblClick;
end;
procedure TClienteLookUp.DeactivateList(const Sender: TObject);
begin
Self.FParent.Visible := False;
Self.FList.Visible := False;
end;
procedure TClienteLookUp.ListOnDblClick(Sender: TObject);
begin
Self.SelectProduto();
Self.DeactivateList(Sender);
end;
procedure TClienteLookUp.ListOnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
begin
Self.SelectProduto();
Self.DeactivateList(Sender);
end
else
if not (Key in [VK_DOWN, VK_UP]) then
Self.FEdit.SetFocus();
end;
procedure TClienteLookUp.OnChange(Sender: TObject);
var
iDataSet: TClientDataSet;
begin
Self.ActivateList(Self.FParent);
iDataSet := TClientDataSet(Self.FDataSource.DataSet);
iDataSet.Active := False;
iDataSet.CommandText := Format('SELECT CL_OID, CL_COD, CL_NOME, CL_RG, CL_FONE, CL_CPF FROM CL WHERE CL_NOME LIKE %s ORDER BY CL_NOME', [QuotedStr('%' + TEdit(Sender).Text + '%')]);
iDataSet.Active := True;
end;
procedure TClienteLookUp.OnEnter(Sender: TObject);
begin
end;
procedure TClienteLookUp.OnExit(Sender: TObject);
begin
end;
procedure TClienteLookUp.OnKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
else
if Key = VK_RETURN then
begin
Self.SelectProduto();
Self.DeactivateList(Sender);
end
else
if Key = VK_DOWN then
Self.FList.SetFocus()
else
TCustomEdit(Sender).SetFocus();
end;
procedure TClienteLookUp.OnKeyPress(Sender: TObject);
begin
end;
procedure TClienteLookUp.OnKeyUp(Sender: TObject);
begin
end;
procedure TClienteLookUp.SelectProduto;
begin
if Assigned(Self.FObserver) then
Self.FObserver(Self)
end;
end.
|
unit Chostxyr;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, DB, DBTables,
Tabs, Menus, GlblCnst;
type
TChooseTaxYearForm = class(TForm)
CancelButton: TBitBtn;
OKButton: TBitBtn;
ChooseTaxYearRadioGroup: TRadioGroup;
UserProfileTable: TTable;
EditHistoryYear: TEdit;
ParcelTable: TTable;
AssessmentYearControlTable: TTable;
procedure CancelButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure EditHistoryYearEnter(Sender: TObject);
procedure EditHistoryYearExit(Sender: TObject);
procedure ChooseTaxYearRadioGroupClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
OrigTaxYearFlg : Char;
CurrentTaxYearLabel : TLabel; {The tax year label on the user info panel.}
MainFormTabSet : TTabSet; {The tab set from the main from in case we need to close
all of the menu items.}
FormCaptions : TStringList; {The form captions of all open mdi children - we will
have to clear it if they change tax years.}
CloseResult : Integer; {Did they cancel or accept?}
UnitName : String; {For error dialog box.}
HaveAccess : Boolean;
ChangeThisYearandNextYearTogether : TMenuItem;
end;
var
ChooseTaxYearForm : TChooseTaxYearForm;
implementation
{$R *.DFM}
uses WinUtils, PASUTILS, UTILEXSD, GlblVars, Utilitys, MainForm, Types;
{=========================================================}
Procedure TChooseTaxYearForm.FormActivate(Sender: TObject);
begin
UnitName := 'CHOSTXYR.PAS';
try
UserProfileTable.Open;
except
SystemSupport(001, UserProfileTable, 'Error opening user profile table.',
UnitName, GlblErrorDlgBox);
end;
{Change the radio group to include the year.}
ChooseTaxYearRadioGroup.Items.Clear;
ChooseTaxYearRadioGroup.Items.Add('Next Year (' + GlblNextYear + ')');
ChooseTaxYearRadioGroup.Items.Add('This Year (' + GlblThisYear + ')');
ChooseTaxYearRadioGroup.Items.Add('History');
OrigTaxYearFlg := GlblTaxYearFlg;
{Set the button to the right spot in the radio group.}
case OrigTaxYearFlg of
'H' : ChooseTaxYearRadioGroup.ItemIndex := 2;
'T' : ChooseTaxYearRadioGroup.ItemIndex := 1;
'N' : ChooseTaxYearRadioGroup.ItemIndex := 0;
end; {case OrigTaxYearFlg of}
end; {FormActivate}
{================================================================}
Procedure TChooseTaxYearForm.CancelButtonClick(Sender: TObject);
begin
CloseResult := idCancel;
Close;
end;
{==================================================================}
Procedure TChooseTaxYearForm.OKButtonClick(Sender: TObject);
{See if they changed tax years. If they did, check to see if they are allowed
to have access to this tax year. If they are, then close any open jobs and
put them in the new processing status.}
var
CanClose, Proceed, UserFound, Quit : Boolean;
NewTaxYearFlg : Char;
I : Integer;
YearStr : String;
OrigHistYear : String;
begin
OrigHistYear := GlblHistYear;
UserFound := True;
NewTaxYearFlg := ' ';
case ChooseTaxYearRadioGroup.ItemIndex of
-1 : begin
MessageDlg('Please choose a tax year or click Cancel to end.', mtError, [mbOK], 0);
end;
0 : begin
NewTaxYearFlg := 'N';
YearStr := 'Next Year';
end;
1 : If (MessageDlg('Are you sure that you want to switch to the' + #13 +
'This Year (' + GlblThisYear + ') assessment roll?', mtConfirmation, [mbYes, mbNo], 0) = idYes)
then
begin
NewTaxYearFlg := 'T';
YearStr := 'This Year';
end;
2 : begin
HaveAccess := False;
OpenTableForProcessingType(ParcelTable, ParcelTableName, History, Quit);
FindNearestOld(ParcelTable, ['TaxRollYr', 'Name1'],
[EditHistoryYear.Text, '']);
If ((not ParcelTable.EOF) and
(Take(4, EditHistoryYear.Text) =
Take(4, ParcelTable.FieldByName('TaxRollYr').AsString)))
then
begin
HaveAccess := True;
GlblHistYear := EditHistoryYear.Text;
NewTaxYearFlg := 'H';
YearStr := 'History';
end; {If ((not ParcelTable.EOF) and ...}
If not HaveAccess
then
begin
MessageDlg('Invalid Assessement History Year. ' + #13 +
'Please try again.', mtWarning, [mbOK], 0);
EditHistoryYear.SetFocus;
end;
ParcelTable.Close;
end; {History}
end; {case ChooseTaxYearRadioGroup.ItemIndex of}
{Did they change tax years?}
{FXX11191999-11: Problem switching from one year of history to another.}
If (ChooseTaxYearRadioGroup.ItemIndex <> -1)
then
If ((NewTaxYearFlg <> OrigTaxYearFlg) or
((NewTaxYearFlg = 'H') and
(OrigHistYear <> GlblHistYear)))
then
begin
HaveAccess := False;
GlblDialogBoxShowing := True;
try
UserProfileTable.FindNearest([Take(10, GlblUserName)]);
except
SystemSupport(002, UserProfileTable, 'Error getting user profile record.',
UnitName, GlblErrorDlgBox);
end;
If _Compare(GlblUserName, UserProfileTable.FieldByName('UserID').Text, coEqual)
then
begin
{Determine if they have access to this tax year.}
If (NewTaxYearFlg = 'H')
then
If UserProfileTable.FieldByName('HistoryAccess').AsBoolean
then HaveAccess := True
else MessageDlg('Sorry. You do not have history access.' + #13 +
'Please chose a different tax year.', mtWarning,
[mbOK], 0);
If (NewTaxYearFlg = 'T')
then
If _Compare(UserProfileTable.FieldByName('ThisYearAccess').AsInteger, 0, coGreaterThan)
then HaveAccess := True
else MessageDlg('Sorry. You do not have this year access.' + #13 +
'Please chose a different tax year.', mtWarning,
[mbOK], 0);
If (NewTaxYearFlg = 'N')
then
If _Compare(UserProfileTable.FieldByName('NextYearAccess').AsInteger, 0, coGreaterThan)
then HaveAccess := True
else MessageDlg('Sorry. You do not have next year access.' + #13 +
'Please chose a different tax year.', mtWarning,
[mbOK], 0);
end
else
begin
HaveAccess := False;
UserFound := False;
end;
{If we found the user record and they have access to this tax year, then
let's close all other jobs, display a message saying that they are now in
the new year, actually change the new year, and then close.}
If (UserFound and HaveAccess)
then
begin
Proceed := True;
{If there is only one MDI child then it is this form, and we don't need to
ask them about closing all the open menu items.}
If (Application.MainForm.MDIChildCount > 0)
then
begin
{FXX11131997-1: Still having problems with
closing all children, so don't
let them for now.}
MessageDlg('Please close all open menu items before changing assessment year.',
mtInformation, [mbOK], 0);
Proceed := False;
(*ReturnCode := MessageDlg('Warning! To change to a new tax year, ' + #13 +
'all open menu items will be closed.' + #13 +
'Do you want to proceed?', mtWarning,
[mbYes, mbNo], 0);
Proceed := (ReturnCode = idYes);*)
end; {If (Application.MainForm.MDIChildCount > 1)}
If Proceed
then
begin
CanClose := True;
{Close all the other jobs.}
with Application.MainForm do
begin
I := 0;
{First let's go through each child form and make sure that it
is ok to close it by calling the CloseQuery method.
If CloseQuery comes back True for all forms, then we will
close the forms. However, if CloseQuery comes back False for
any form, we will not close any forms, and no tax year change
will be done.}
while (CanClose and
(I <= (MDIChildCount - 1))) do
begin
CanClose := MDIChildren[I].CloseQuery;
I := I + 1;
end; {while (CanClose and ...}
{FXX10281997-1: Try to fix GPF problem when
switching between years
by moving the close to the main form.}
{FXX11131997-2: Move the close of children
back here since moving it
to main form did not work.}
{All form's CloseQuery returned True, so now close all the
child forms. Note that this is not a child form.}
If CanClose
then
For I := 0 to (MDIChildCount - 1) do
MDIChildren[I].Close;
end; {with Application.MainForm do}
{If we were able to close all child forms except this one, then
change the tax year flag, update the label on the main form,
and display a message.}
If CanClose
then
begin
GlblTaxYearFlg := NewTaxYearFlg;
GlblProcessingType := DetermineProcessingType(GlblTaxYearFlg);
{CHG11101997-1: Allow user to set dual processing.}
If not GlblUserIsSearcher
then
If (GlblProcessingType = ThisYear)
then
begin
ChangeThisYearandNextYearTogether.Enabled := True;
{FXX04071998-6: Must keep track of whether or not
dual processing mode is on for TY.}
If GlblModifyBothYearsCheckedInTY
then ChangeThisYearandNextYearTogether.Checked := True;
{FXX04071998-5: If are switching back to TY from
NY, need to determine if
global processing mode on.}
GlblModifyBothYears := ChangeThisYearandNextYearTogether.Checked;
end
else
begin
{FXX04071998-6: Must keep track of whether or not
dual processing mode is on for TY.}
{FXX01312006-1(2.9.5.3): Don't reset the modify TY & NY flag if they switch years.
Always put it back to the default when they come back to TY.}
(*GlblModifyBothYearsCheckedInTY := ChangeThisYearandNextYearTogether.Checked;*)
ChangeThisYearandNextYearTogether.Enabled := False;
ChangeThisYearandNextYearTogether.Checked := False;
{FXX11151998-1: Must turn off glbl modify in NY so
don't modify backwards.}
GlblModifyBothYears := False;
end; {else of If (GlblProcessingType = ThisYear)}
{FXX06241998-1: The veterans maximums need to be
at the county and swis level.}
OpenTableForProcessingType(AssessmentYearControlTable,
AssessmentYearControlTableName,
GlblProcessingType,
Quit);
{FXX02101999-3 Split the SBL format into a by year item.}
SetGlobalSBLSegmentFormats(AssessmentYearControlTable);
with AssessmentYearControlTable do
begin
GlblCountyVeteransMax := FieldByName('VeteranCntyMax').AsFloat;
GlblCountyCombatVeteransMax := FieldByName('CombatVetCntyMax').AsFloat;
GlblCountyDisabledVeteransMax := FieldByName('DisabledVetCntyMax').AsFloat;
end; {with AssessmentYearControlTable do}
AssessmentYearControlTable.Close;
MainFormTabSet.Tabs.Clear;
FormCaptions.Clear;
{Change the tax year label on the user info panel on
the main form.}
SetTaxYearLabelForProcessingType(CurrentTaxYearLabel,
DetermineProcessingType(GlblTaxYearFlg));
MessageDlg('You are now processing in ' + YearStr + '.',
mtInformation, [mbOK], 0);
GlblDialogBoxShowing := False;
CloseResult := idOK;
Close;
end; {If CloseSuccessful}
end; {If Proceed}
end; {If (UserFound and HaveAccess)}
GlblDialogBoxShowing := False;
end {If (NewTaxYearFlg <> OrigTaxYearFlg)}
else
begin
{There was no change, so just close the form and continue.}
CloseResult := idOK;
Close;
end;
end; {OKButtonClick}
{=================================================================}
Procedure TChooseTaxYearForm.EditHistoryYearEnter(Sender: TObject);
begin
If (ChooseTaxYearRadioGroup.ItemIndex <> 2)
then MessageDlg('Sorry. You can only select a year if you select ' + #13 +
'a History Tax Year. Please try again.', mtWarning,
[mbOK], 0);
end; {EditHistoryYearEnter}
{=================================================================}
Procedure TChooseTaxYearForm.EditHistoryYearExit(Sender: TObject);
var
Quit : Boolean;
begin
{FXX01201998-13: Don't try to open any tables unless they filled in
a history tax year.}
If ((ChooseTaxYearRadioGroup.ItemIndex = 2) and
(Deblank(EditHistoryYear.Text) <> ''))
then
begin
HaveAccess := False;
OpenTableForProcessingType(ParcelTable, ParcelTableName, History, Quit);
FindNearestOld(ParcelTable, ['TaxRollYr', 'Name1'],
[EditHistoryYear.Text, '']);
If (ParcelTable.EOF or
(Take(4, EditHistoryYear.Text) <>
Take(4, ParcelTable.FieldByName('TaxRollYr').AsString)))
then
begin
MessageDlg('Invalid Assessement History Year. ' + #13 +
'Please try again.', mtWarning, [mbOK], 0);
EditHistoryYear.SetFocus;
end; {If not HaveAccess}
ParcelTable.Close;
end; {If ((ChooseTaxYearRadioGroup.ItemIndex = 2) and ...}
end; {EditHistoryYearExit}
{=================================================================}
Procedure TChooseTaxYearForm.ChooseTaxYearRadioGroupClick(Sender: TObject);
begin
If ChooseTaxYearRadioGroup.ItemIndex = 2
then
begin
EditHistoryYear.Visible := True;
EditHistoryYear.SetFocus;
end
else EditHistoryYear.Visible := False;
end;
end. |
{ ***************************************************************************
Copyright (c) 2013-2017 Kike Pérez
Unit : Quick.ImageFX.GR32
Description : Image manipulation with GR32
Author : Kike Pérez
Version : 4.0
Created : 12/12/2017
Modified : 11/08/2018
This file is part of QuickImageFX: https://github.com/exilon/QuickImageFX
Third-party libraries used:
Graphics32 (https://github.com/graphics32/graphics32)
CCR-Exif from Chris Rolliston (https://code.google.com/archive/p/ccr-exif)
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.ImageFX.Vampyre;
interface
uses
Windows,
Classes,
Controls,
Vcl.ImgList,
System.SysUtils,
Vcl.Graphics,
Winapi.ShellAPI,
System.Math,
Vcl.Imaging.pngimage,
Vcl.Imaging.jpeg,
Vcl.Imaging.GIFImg,
ImagingFormats,
//ImagingDirect3D9,
//ImagingJpeg,
//ImagingBitmap,
ImagingGif,
ImagingTypes,
Imaging,
ImagingComponents,
ImagingCanvases,
Quick.Base64,
Quick.ImageFX,
Quick.ImageFX.Types;
const
MaxPixelCountA = MaxInt Div SizeOf (TRGBQuad);
type
TScanlineMode = (smHorizontal, smVertical);
PRGBAArray = ^TRGBAArray;
TRGBAArray = Array [0..MaxPixelCountA -1] Of TRGBQuad;
pRGBQuadArray = ^TRGBQuadArray;
TRGBQuadArray = ARRAY [0 .. $EFFFFFF] OF TRGBQuad;
TRGBArray = ARRAY[0..32767] OF TRGBTriple;
pRGBArray = ^TRGBArray;
TImageFXVampyre = class(TImageFX,IImageFX)
protected
fImageData : TImageData;
fPImage : PImageData;
private
procedure DoScanlines(ScanlineMode : TScanlineMode);
function ResizeImage(w, h : Integer; ResizeOptions : TResizeOptions) : IImageFX;
procedure SetPixelImage(const x, y: Integer; const P: TPixelInfo; bmp32 : TBitmap);
function GetPixelImage(const x, y: Integer; bmp32 : TBitmap): TPixelInfo;
protected
function GetPixel(const x, y: Integer): TPixelInfo;
procedure SetPixel(const x, y: Integer; const P: TPixelInfo);
public
function AsImageData : PImageData;
constructor Create; overload; override;
destructor Destroy; override;
function NewBitmap(w, h : Integer) : IImageFX;
property Pixel[const x, y: Integer]: TPixelInfo read GetPixel write SetPixel;
function IsEmpty : Boolean;
function LoadFromFile(const fromfile : string; CheckIfFileExists : Boolean = False) : IImageFX;
function LoadFromStream(stream : TStream) : IImageFX;
function LoadFromString(const str : string) : IImageFX;
function LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : IImageFX;
function LoadFromIcon(Icon : TIcon) : IImageFX;
function LoadFromFileIcon(const FileName : string; IconIndex : Word) : IImageFX;
function LoadFromFileExtension(const aFilename : string; LargeIcon : Boolean) : IImageFX;
function LoadFromResource(const ResourceName : string) : IImageFX;
function Clone : IImageFX;
function IsGray : Boolean;
procedure GetResolution(var x,y : Integer); overload;
function GetResolution : string; overload;
function AspectRatio : Double;
function Clear(pcolor : TColor = clNone) : IImageFX;
procedure Assign(Graphic : TGraphic);
function Resize(w, h : Integer) : IImageFX; overload;
function Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : IImageFX; overload;
function Draw(Graphic : TGraphic; x, y : Integer; alpha : Double = 1) : IImageFX; overload;
function Draw(stream: TStream; x: Integer; y: Integer; alpha: Double = 1) : IImageFX; overload;
function DrawCentered(Graphic : TGraphic; alpha : Double = 1) : IImageFX; overload;
function DrawCentered(stream: TStream; alpha : Double = 1) : IImageFX; overload;
function Rotate90 : IImageFX;
function Rotate180 : IImageFX;
function Rotate270 : IImageFX;
function RotateAngle(RotAngle : Single) : IImageFX;
function RotateBy(RoundAngle : Integer) : IImageFX;
function FlipX : IImageFX;
function FlipY : IImageFX;
function GrayScale : IImageFX;
function ScanlineH : IImageFX;
function ScanlineV : IImageFX;
function Lighten(StrenghtPercent : Integer = 30) : IImageFX;
function Darken(StrenghtPercent : Integer = 30) : IImageFX;
function Tint(mColor : TColor) : IImageFX;
function TintAdd(R, G , B : Integer) : IImageFX;
function TintBlue : IImageFX;
function TintRed : IImageFX;
function TintGreen : IImageFX;
function Solarize : IImageFX;
function Rounded(RoundLevel : Integer = 27) : IImageFX;
function AntiAliasing : IImageFX;
function SetAlpha(Alpha : Byte) : IImageFX;
procedure SaveToPNG(const outfile : string);
procedure SaveToJPG(const outfile : string);
procedure SaveToBMP(const outfile : string);
procedure SaveToGIF(const outfile : string);
function AsBitmap : TBitmap;
function AsString(imgFormat : TImageFormat = ifJPG) : string;
procedure SaveToStream(stream : TStream; imgFormat : TImageFormat = ifJPG);
function AsPNG : TPngImage;
function AsJPG : TJpegImage;
function AsGIF : TGifImage;
end;
implementation
constructor TImageFXVampyre.Create;
begin
inherited Create;
fPImage := @fImageData;
Imaging.FreeImage(fPImage^);
end;
destructor TImageFXVampyre.Destroy;
begin
Imaging.FreeImage(fPImage^);
inherited;
end;
{function TImageFXGR32.LoadFromFile(fromfile: string) : TImageFX;
var
fs: TFileStream;
FirstBytes: AnsiString;
Graphic: TGraphic;
bmp : TBitmap;
begin
Result := Self;
if not FileExists(fromfile) then
begin
fLastResult := arFileNotExist;
Exit;
end;
Graphic := nil;
fs := TFileStream.Create(fromfile, fmOpenRead);
try
SetLength(FirstBytes, 8);
fs.Read(FirstBytes[1], 8);
if Copy(FirstBytes, 1, 2) = 'BM' then
begin
Graphic := TBitmap.Create;
end else
if FirstBytes = #137'PNG'#13#10#26#10 then
begin
Graphic := TPngImage.Create;
end else
if Copy(FirstBytes, 1, 3) = 'GIF' then
begin
Graphic := TGIFImage.Create;
end else
if Copy(FirstBytes, 1, 2) = #$FF#$D8 then
begin
Graphic := TJPEGImage.Create;
end;
if Assigned(Graphic) then
begin
try
fs.Seek(0, soFromBeginning);
Graphic.LoadFromStream(fs);
bmp := TBitmap.Create;
try
InitBitmap(bmp);
bmp.Assign(Graphic);
fBitmap.Assign(bmp);
fLastResult := arOk;
finally
bmp.Free;
end;
except
end;
Graphic.Free;
end;
finally
fs.Free;
end;
end;}
function TImageFXVampyre.LoadFromFile(const fromfile: string; CheckIfFileExists : Boolean = False) : IImageFX;
var
//GPBitmap : TGPBitmap;
//Status : TStatus;
//PropItem : PPropertyItem;
//PropSize: UINT;
//Orientation : PWORD;
fs : TFileStream;
begin
Result := Self;
if (CheckIfFileExists) and (not FileExists(fromfile)) then
begin
LastResult := arFileNotExist;
Exit;
end;
//loads file into image
fs := TFileStream.Create(fromfile,fmShareDenyWrite);
try
Self.LoadFromStream(fs);
finally
fs.Free;
end;
{GPBitmap := TGPBitmap.Create(fromfile);
try
//read EXIF orientation to rotate if needed
PropSize := GPBitmap.GetPropertyItemSize(PropertyTagOrientation);
GetMem(PropItem,PropSize);
try
Status := GPBitmap.GetPropertyItem(PropertyTagOrientation,PropSize,PropItem);
if Status = TStatus.Ok then
begin
Orientation := PWORD(PropItem^.Value);
case Orientation^ of
6 : GPBitmap.RotateFlip(Rotate90FlipNone);
8 : GPBitmap.RotateFlip(Rotate270FlipNone);
3 : GPBitmap.RotateFlip(Rotate180FlipNone);
end;
end;
finally
FreeMem(PropItem);
end;
GPBitmapToImage(GPBitmap,fPImage^);
LastResult := arOk;
finally
GPBitmap.Free;
end;}
end;
function TImageFXVampyre.LoadFromStream(stream: TStream) : IImageFX;
var
GraphicClass : TGraphicClass;
begin
Result := Self;
if (not Assigned(stream)) or (stream.Size < 1024) then
begin
LastResult := arZeroBytes;
Exit;
end;
stream.Seek(0,soBeginning);
if not FindGraphicClass(Stream, GraphicClass) then raise EInvalidGraphic.Create('Unknow Graphic format');
stream.Seek(0,soBeginning);
Imaging.LoadImageFromStream(stream,fPImage^);
if ExifRotation then ProcessEXIFRotation(stream);
LastResult := arOk;
end;
function TImageFXVampyre.LoadFromString(const str: string) : IImageFX;
var
stream : TStringStream;
begin
Result := Self;
if str = '' then
begin
LastResult := arZeroBytes;
Exit;
end;
stream := TStringStream.Create(Base64Decode(str));
try
LoadFromStream(stream);
LastResult := arOk;
finally
stream.Free;
end;
end;
function TImageFXVampyre.LoadFromFileIcon(const FileName : string; IconIndex : Word) : IImageFX;
var
Icon : TIcon;
begin
Result := Self;
Icon := TIcon.Create;
try
Icon.Handle := ExtractAssociatedIcon(hInstance,pChar(FileName),IconIndex);
Icon.Transparent := True;
//fBitmap.Assign(Icon);
finally
Icon.Free;
end;
end;
function TImageFXVampyre.LoadFromResource(const ResourceName : string) : IImageFX;
var
icon : TIcon;
ms : TMemoryStream;
begin
Result := Self;
icon:=TIcon.Create;
try
icon.LoadFromResourceName(HInstance,ResourceName);
icon.Transparent:=True;
ms := TMemoryStream.Create;
try
icon.SaveToStream(ms);
Imaging.LoadImageFromStream(ms,fPImage^);
finally
ms.Free;
end;
finally
icon.Free;
end;
end;
function TImageFXVampyre.LoadFromImageList(imgList : TImageList; ImageIndex : Integer) : IImageFX;
var
icon : TIcon;
ms : TMemoryStream;
begin
Result := Self;
//imgList.ColorDepth := cd32bit;
//imgList.DrawingStyle := dsTransparent;
icon := TIcon.Create;
try
imgList.GetIcon(ImageIndex,icon);
ms := TMemoryStream.Create;
try
icon.SaveToStream(ms);
Imaging.LoadImageFromStream(ms,fPImage^);
finally
ms.Free;
end;
finally
icon.Free;
end;
end;
function TImageFXVampyre.LoadFromIcon(Icon : TIcon) : IImageFX;
var
ms : TMemoryStream;
begin
Result := Self;
ms := TMemoryStream.Create;
try
icon.SaveToStream(ms);
Imaging.LoadImageFromStream(ms,fPImage^);
finally
ms.Free;
end;
end;
function TImageFXVampyre.LoadFromFileExtension(const aFilename : string; LargeIcon : Boolean) : IImageFX;
var
icon : TIcon;
aInfo : TSHFileInfo;
ms : TMemoryStream;
begin
Result := Self;
LastResult := arUnknowFmtType;
if GetFileInfo(ExtractFileExt(aFilename),aInfo,LargeIcon) then
begin
icon := TIcon.Create;
try
Icon.Handle := AInfo.hIcon;
Icon.Transparent := True;
ms := TMemoryStream.Create;
try
icon.SaveToStream(ms);
Imaging.LoadImageFromStream(ms,fPImage^);
finally
ms.Free;
end;
LastResult := arOk;
finally
icon.Free;
DestroyIcon(aInfo.hIcon);
end;
end;
end;
function TImageFXVampyre.AspectRatio : Double;
begin
if not IsEmpty then Result := fPImage.width / fPImage.Height
else Result := 0;
end;
procedure TImageFXVampyre.GetResolution(var x,y : Integer);
begin
if not IsEmpty then
begin
x := fPImage.Width;
y := fPImage.Height;
LastResult := arOk;
end
else
begin
x := -1;
y := -1;
LastResult := arCorruptedData;
end;
end;
function TImageFXVampyre.Clear(pcolor : TColor = clNone) : IImageFX;
var
color : TColor32Rec;
begin
Result := Self;
color.Color := ColorToRGB(pcolor);
Imaging.FillRect(fPImage^,0,0,fPImage.Width,fPImage.Height,@color);
LastResult := arOk;
end;
function TImageFXVampyre.Clone : IImageFX;
begin
Result := TImageFXVampyre.Create;
Imaging.CloneImage(fPImage^,(Result as TImageFXVampyre).fPImage^);
CloneValues(Result);
end;
function TImageFXVampyre.ResizeImage(w, h : Integer; ResizeOptions : TResizeOptions) : IImageFX;
var
resam : TResizeFilter;
srcRect,
tgtRect : TRect;
crop : Integer;
srcRatio : Double;
nw, nh : Integer;
DestImageData : TImageData;
PDestImage : PImageData;
fillcolor : TColor32Rec;
begin
Result := Self;
LastResult := arResizeError;
if (not Assigned(fPImage)) or ((fPImage.Width * fPImage.Height) = 0) then
begin
LastResult := arZeroBytes;
Exit;
end;
//if any value is 0, calculates proportionaly
if (w * h) = 0 then
begin
//scales max w or h
if ResizeOptions.ResizeMode = rmScale then
begin
if (h = 0) and (fPImage.Height > fPImage.Width) then
begin
h := w;
w := 0;
end;
end
else ResizeOptions.ResizeMode := rmFitToBounds;
begin
if w > h then
begin
nh := (w * fPImage.Height) div fPImage.Width;
h := nh;
nw := w;
end
else
begin
nw := (h * fPImage.Width) div fPImage.Height;
w := nw;
nh := h;
end;
end;
end;
case ResizeOptions.ResizeMode of
rmScale: //recalculate width or height target size to preserve original aspect ratio
begin
if fPImage.Width > fPImage.Height then
begin
nh := (w * fPImage.Height) div fPImage.Width;
h := nh;
nw := w;
end
else
begin
nw := (h * fPImage.Width) div fPImage.Height;
w := nw;
nh := h;
end;
srcRect := Rect(0,0,fPImage.Width,fPImage.Height);
end;
rmCropToFill: //preserve target aspect ratio cropping original image to fill whole size
begin
nw := w;
nh := h;
crop := Round(h / w * fPImage.Width);
if crop < fPImage.Height then
begin
//target image is wider, so crop top and bottom
srcRect.Left := 0;
srcRect.Top := (fPImage.Height - crop) div 2;
srcRect.Width := fPImage.Width;
srcRect.Height := crop;
end
else
begin
//target image is narrower, so crop left and right
crop := Round(w / h * fPImage.Height);
srcRect.Left := (fPImage.Width - crop) div 2;
srcRect.Top := 0;
srcRect.Width := crop;
srcRect.Height := fPImage.Height;
end;
end;
rmFitToBounds: //resize image to fit max bounds of target size
begin
srcRatio := fPImage.Width / fPImage.Height;
if fPImage.Width > fPImage.Height then
begin
nw := w;
nh := Round(w / srcRatio);
if nh > h then //too big
begin
nh := h;
nw := Round(h * srcRatio);
end;
end
else
begin
nh := h;
nw := Round(h * srcRatio);
if nw > w then //too big
begin
nw := w;
nh := Round(w / srcRatio);
end;
end;
srcRect := Rect(0,0,fPImage.Width,fPImage.Height);
end;
else
begin
nw := w;
nh := h;
srcRect := Rect(0,0,fPImage.Width,fPImage.Height);
end;
end;
//if image is smaller no upsizes
if ResizeOptions.NoMagnify then
begin
if (fPImage.Width < nw) or (fPImage.Height < nh) then
begin
//if FitToBounds then preserve original size
if ResizeOptions.ResizeMode = rmFitToBounds then
begin
nw := fPImage.Width;
nh := fPImage.Height;
end
else
begin
//all cases no resizes, but CropToFill needs to grow to fill target size
if ResizeOptions.ResizeMode <> rmCropToFill then
begin
if not ResizeOptions.SkipSmaller then
begin
LastResult := arAlreadyOptim;
nw := srcRect.Width;
nh := srcRect.Height;
w := nw;
h := nh;
end
else Exit;
end;
end;
end;
end;
if ResizeOptions.Center then
begin
tgtRect.Top := (h - nh) div 2;
tgtRect.Left := (w - nw) div 2;
tgtRect.Width := nw;
tgtRect.Height := nh;
end
else tgtRect := Rect(0,0,nw,nh);
//selects resampler algorithm
case ResizeOptions.ResamplerMode of
rsAuto :
begin
if (w < fPImage.Width ) or (h < fPImage.Height) then Resam := rfBilinear
else Resam := rfBicubic;
end;
rsNearest : Resam := rfNearest;
rsVAMPLanczos : Resam := rfLanczos;
rsVAMPBicubic : Resam := rfBicubic;
rsLinear : Resam := rfBilinear;
else Resam := rfBilinear;
end;
PDestImage := @DestImageData;
//Imaging.InitImage(PDestImage^);
Imaging.NewImage(w,h,fPImage^.Format,PDestImage^);
try
try
if ResizeOptions.FillBorders then
begin
//ColorToRGBValues()
fillcolor.Color := ColorToRGB(ResizeOptions.BorderColor);
Imaging.FillRect(PDestImage^,0,0,PDestImage.Width,PDestImage.Height,@fillcolor);
end;
Imaging.StretchRect(fPImage^,srcRect.Left,srcRect.Top, srcRect.Width, srcRect.Height,
PDestImage^, tgtRect.Left, tgtRect.Top, tgtRect.Width, tgtRect.Height, resam);
Imaging.FreeImage(fPImage^);
//fPImage := @DestImageData;
Imaging.CloneImage(PDestImage^,fPImage^);
FreeImage(PDestImage^);
LastResult := arOk;
except
LastResult := arCorruptedData;
raise Exception.Create('Resize Error');
end;
finally
FreeImage(PDestImage^);
end;
end;
function TImageFXVampyre.Resize(w, h : Integer) : IImageFX;
begin
Result := ResizeImage(w,h,ResizeOptions);
end;
function TImageFXVampyre.Resize(w, h : Integer; ResizeMode : TResizeMode; ResizeFlags : TResizeFlags = []; ResampleMode : TResamplerMode = rsLinear) : IImageFX;
var
ResizeOptions : TResizeOptions;
begin
ResizeOptions := TResizeOptions.Create;
try
if (rfNoMagnify in ResizeFlags) then ResizeOptions.NoMagnify := True else ResizeOptions.NoMagnify := False;
if (rfCenter in ResizeFlags) then ResizeOptions.Center := True else ResizeOptions.Center := False;
if (rfFillBorders in ResizeFlags) then ResizeOptions.FillBorders := True else ResizeOptions.FillBorders := False;
Result := ResizeImage(w,h,ResizeOptions);
finally
ResizeOptions.Free;
end;
end;
procedure TImageFXVampyre.Assign(Graphic : TGraphic);
var
ms : TMemoryStream;
begin
ms := TMemoryStream.Create;
try
LoadFromStream(ms);
finally
ms.Free;
end;
end;
function TImageFXVampyre.Draw(Graphic : TGraphic; x, y : Integer; alpha : Double = 1) : IImageFX;
var
overlay : PImageData;
ms : TMemoryStream;
begin
Result := Self;
if x = -1 then x := (fPImage.Width - Graphic.Width) div 2;
if y = -1 then y := (fPImage.Height - Graphic.Height) div 2;
ms := TMemoryStream.Create;
try
Graphic.SaveToStream(ms);
ms.Seek(0,soBeginning);
Draw(ms,x,y,alpha);
finally
ms.Free;
end;
end;
function TImageFXVampyre.Draw(stream: TStream; x: Integer; y: Integer; alpha: Double = 1) : IImageFX;
var
overlay : TImageData;
poverlay : PImageData;
srccanvas : TImagingCanvas;
tgtcanvas : TImagingCanvas;
pixel : TColorFPRec;
x1, y1 : Integer;
begin
Result := Self;
stream.Seek(0,soBeginning);
Imaging.LoadImageFromStream(stream,overlay);
poverlay := @overlay;
srccanvas := nil;
tgtcanvas := nil;
try
//if not Imaging.CopyRect(overlay,0,0,overlay.Width,overlay.Height,fPImage^,x,y) then raise EImageDrawError.Create('Drawing error');
tgtcanvas := TImagingCanvas.CreateForData(fPImage);
srccanvas := TImagingCanvas.CreateForData(poverlay);
if x = -1 then x := (fPImage.Width - poverlay.Width) div 2;
if y = -1 then y := (fPImage.Height - poverlay.Height) div 2;
try
for x1 := 0 to poverlay.Width do
begin
for y1 := 0 to poverlay.Height do
begin
pixel := srccanvas.PixelsFP[x1,y1];
pixel.A := pixel.A * alpha;
srccanvas.PixelsFP[x1,y1] := pixel;
end;
end;
srccanvas.DrawAlpha(Rect(0,0,overlay.Width,overlay.Height),tgtcanvas,x,y);
finally
srccanvas.Free;
tgtcanvas.Free;
end;
finally
Imaging.FreeImage(overlay);
end;
end;
function TImageFXVampyre.DrawCentered(Graphic : TGraphic; alpha : Double = 1) : IImageFX;
begin
Result := Draw(Graphic,(fPImage.Width - Graphic.Width) div 2, (fPImage.Height - Graphic.Height) div 2,alpha);
end;
function TImageFXVampyre.DrawCentered(stream: TStream; alpha : Double = 1) : IImageFX;
begin
Result := Draw(stream,-1,-1,alpha);
end;
function TImageFXVampyre.NewBitmap(w, h: Integer): IImageFX;
begin
Result := Self;
if not IsEmpty then Imaging.FreeImage(fPImage^);
if not Imaging.NewImage(w,h,ImagingTypes.TImageFormat.ifA8R8G8B8,fPImage^) then raise EImageError.Create('Error creating image');
end;
function TImageFXVampyre.IsEmpty : Boolean;
begin
Result := not (Assigned(fPImage) and Imaging.TestImage(fPImage^));
end;
function TImageFXVampyre.Rotate90 : IImageFX;
begin
Result := Self;
Imaging.RotateImage(fPImage^,-90);
end;
function TImageFXVampyre.Rotate180 : IImageFX;
begin
Result := Self;
Imaging.RotateImage(fPImage^,-180);
end;
function TImageFXVampyre.RotateAngle(RotAngle: Single) : IImageFX;
begin
Result := Self;
Imaging.RotateImage(fPImage^,RotAngle * -1);
end;
function TImageFXVampyre.RotateBy(RoundAngle: Integer): IImageFX;
begin
Result := Self;
Imaging.RotateImage(fPImage^,RoundAngle * -1);
end;
function TImageFXVampyre.Rotate270 : IImageFX;
begin
Result := Self;
Imaging.RotateImage(fPImage^,-270);
end;
function TImageFXVampyre.FlipX : IImageFX;
begin
Result := Self;
if not Imaging.MirrorImage(fPImage^) then raise EImageRotationError.Create('FlipX error');
end;
function TImageFXVampyre.FlipY : IImageFX;
begin
Result := Self;
if not Imaging.FlipImage(fPImage^) then raise EImageRotationError.Create('FlipY error');
end;
function TImageFXVampyre.GrayScale : IImageFX;
begin
Result := Self;
if not Imaging.ConvertImage(fPImage^,ImagingTypes.TImageFormat.ifA16Gray16) then raise EImageResizeError.Create('Error grayscaling');
end;
function TImageFXVampyre.IsGray: Boolean;
begin
raise ENotImplemented.Create('Not implemented!');
end;
function TImageFXVampyre.Lighten(StrenghtPercent : Integer = 30) : IImageFX;
begin
raise ENotImplemented.Create('Not implemented!');
{var
Bits: PColor32Entry;
I, J: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
if Bits.R + 5 < 255 then Bits.R := Bits.R + 5;
if Bits.G + 5 < 255 then Bits.G := Bits.G + 5;
if Bits.B + 5 < 255 then Bits.B := Bits.B + 5;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;}
end;
function TImageFXVampyre.Darken(StrenghtPercent : Integer = 30) : IImageFX;
begin
raise ENotImplemented.Create('Not implemented!');
{var
Bits: PColor32Entry;
I, J: Integer;
Percent: Single;
Brightness: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Percent := (100 - StrenghtPercent) / 100;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
Brightness := Round((Bits.R+Bits.G+Bits.B)/765);
Bits.R := Lerp(Bits.R, Brightness, Percent);
Bits.G := Lerp(Bits.G, Brightness, Percent);
Bits.B := Lerp(Bits.B, Brightness, Percent);
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;}
end;
function TImageFXVampyre.Tint(mColor : TColor) : IImageFX;
begin
raise ENotImplemented.Create('Not implemented!');
end;
{var
Bits: PColor32Entry;
Color: TColor32Entry;
I, J: Integer;
Percent: Single;
Brightness: Single;
begin
Result := Self;
LastResult := arColorizeError;
Color.ARGB := Color32(mColor);
Percent := 10 / 100;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
Brightness := (Bits.R+Bits.G+Bits.B)/765;
Bits.R := Lerp(Bits.R, Round(Brightness * Color.R), Percent);
Bits.G := Lerp(Bits.G, Round(Brightness * Color.G), Percent);
Bits.B := Lerp(Bits.B, Round(Brightness * Color.B), Percent);
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;}
function TImageFXVampyre.TintAdd(R, G , B : Integer) : IImageFX;
begin
raise ENotImplemented.Create('Not implemented!');
end;
{var
Bits: PColor32Entry;
I, J: Integer;
begin
Result := Self;
LastResult := arColorizeError;
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
//Brightness := (Bits.R+Bits.G+Bits.B)/765;
if R > -1 then Bits.R := Bits.R + R;
if G > -1 then Bits.G := Bits.G + G;
if B > -1 then Bits.B := Bits.B + B;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;}
function TImageFXVampyre.TintBlue : IImageFX;
begin
Result := Tint(clBlue);
end;
function TImageFXVampyre.TintRed : IImageFX;
begin
Result := Tint(clRed);
end;
function TImageFXVampyre.TintGreen : IImageFX;
begin
Result := Tint(clGreen);
end;
function TImageFXVampyre.Solarize : IImageFX;
begin
Result := TintAdd(255,-1,-1);
end;
function TImageFXVampyre.ScanlineH;
begin
Result := Self;
DoScanLines(smHorizontal);
end;
function TImageFXVampyre.ScanlineV;
begin
Result := Self;
DoScanLines(smVertical);
end;
procedure TImageFXVampyre.DoScanLines(ScanLineMode : TScanlineMode);
begin
raise ENotImplemented.Create('Not implemented!');
end;
{var
Bits: PColor32Entry;
Color: TColor32Entry;
I, J: Integer;
DoLine : Boolean;
begin
LastResult := arColorizeError;
Color.ARGB := Color32(clBlack);
Bits := @fBitmap.Bits[0];
fBitmap.BeginUpdate;
try
for I := 0 to fBitmap.Height - 1 do
begin
for J := 0 to fBitmap.Width - 1 do
begin
DoLine := False;
if ScanLineMode = smHorizontal then
begin
if Odd(I) then DoLine := True;
end
else
begin
if Odd(J) then DoLine := True;
end;
if DoLine then
begin
Bits.R := Round(Bits.R-((Bits.R/255)*100));;// Lerp(Bits.R, Round(Brightness * Color.R), Percent);
Bits.G := Round(Bits.G-((Bits.G/255)*100));;//Lerp(Bits.G, Round(Brightness * Color.G), Percent);
Bits.B := Round(Bits.B-((Bits.B/255)*100));;//Lerp(Bits.B, Round(Brightness * Color.B), Percent);
end;
Inc(Bits);
end;
end;
LastResult := arOk;
finally
fBitmap.EndUpdate;
fBitmap.Changed;
end;
end;}
procedure TImageFXVampyre.SaveToPNG(const outfile : string);
var
png : TPngImage;
begin
LastResult := arConversionError;
png := AsPNG;
try
png.SaveToFile(outfile);
finally
png.Free;
end;
LastResult := arOk;
end;
procedure TImageFXVampyre.SaveToJPG(const outfile : string);
var
jpg : TJPEGImage;
begin
LastResult := arConversionError;
jpg := AsJPG;
try
jpg.SaveToFile(outfile);
finally
jpg.Free;
end;
LastResult := arOk;
end;
procedure TImageFXVampyre.SaveToBMP(const outfile : string);
var
bmp : TBitmap;
begin
LastResult := arConversionError;
bmp := AsBitmap;
try
bmp.SaveToFile(outfile);
finally
bmp.Free;
end;
LastResult := arOk;
end;
procedure TImageFXVampyre.SaveToGIF(const outfile : string);
var
gif : TGIFImage;
begin
LastResult := arConversionError;
gif := AsGIF;
try
gif.SaveToFile(outfile);
finally
gif.Free;
end;
LastResult := arOk;
end;
procedure TImageFXVampyre.SaveToStream(stream : TStream; imgFormat : TImageFormat = ifJPG);
var
graf : TGraphic;
begin
if stream.Position > 0 then stream.Seek(0,soBeginning);
case imgFormat of
ifBMP:
begin
graf := TBitmap.Create;
try
graf := Self.AsBitmap;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifJPG:
begin
graf := TJPEGImage.Create;
try
graf := Self.AsJPG;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifPNG:
begin
graf := TPngImage.Create;
try
graf := Self.AsPNG;
graf.SaveToStream(stream);
finally
graf.Free;
end;
end;
ifGIF:
begin
SaveImageToStream('gif',stream,fpImage^);
end;
end;
end;
function TImageFXVampyre.AsBitmap : TBitmap;
begin
LastResult := arConversionError;
Result := TBitmap.Create;
InitBitmap(Result);
ImagingComponents.ConvertDataToBitmap(fPImage^,Result);
end;
function TImageFXVampyre.AsPNG: TPngImage;
var
n, a: Integer;
PNB: TPngImage;
FFF: PRGBAArray;
AAA: pByteArray;
bmp : TBitmap;
begin
LastResult := arConversionError;
Result := TPngImage.CreateBlank(COLOR_RGBALPHA,16,fPImage.Width,fPImage.Height);
PNB := TPngImage.Create;
try
PNB.CompressionLevel := PNGCompressionLevel;
Result.CompressionLevel := PNGCompressionLevel;
bmp := AsBitmap;
try
PNB.Assign(bmp);
PNB.CreateAlpha;
for a := 0 to bmp.Height - 1 do
begin
FFF := bmp.ScanLine[a];
AAA := PNB.AlphaScanline[a];
for n := 0 to bmp.Width - 1 do
begin
AAA[n] := FFF[n].rgbReserved;
end;
end;
finally
bmp.Free;
end;
Result.Assign(PNB);
LastResult := arOk;
finally
PNB.Free;
end;
end;
function TImageFXVampyre.AsJPG : TJPEGImage;
var
jpg : TJPEGImage;
bmp : TBitmap;
begin
LastResult := arConversionError;
jpg := TJPEGImage.Create;
jpg.ProgressiveEncoding := ProgressiveJPG;
jpg.CompressionQuality := JPGQualityPercent;
bmp := AsBitmap;
try
jpg.Assign(bmp);
finally
bmp.Free;
end;
Result := jpg;
LastResult := arOk;
end;
function TImageFXVampyre.AsGIF : TGifImage;
var
gif : TGIFImage;
bmp : TBitmap;
begin
LastResult := arConversionError;
gif := TGIFImage.Create;
bmp := AsBitmap;
try
gif.Assign(bmp);
finally
bmp.Free;
end;
Result := gif;
LastResult := arOk;
end;
function TImageFXVampyre.AsImageData: PImageData;
begin
Result^ := fPImage^;
end;
function TImageFXVampyre.AsString(imgFormat : TImageFormat = ifJPG) : string;
var
ss : TStringStream;
begin
LastResult := arConversionError;
ss := TStringStream.Create;
try
case imgFormat of
ifBMP : Self.AsBitmap.SaveToStream(ss);
ifJPG : Self.AsJPG.SaveToStream(ss);
ifPNG : Self.AsPNG.SaveToStream(ss);
ifGIF : Self.SaveToStream(ss,ifGIF);
else raise Exception.Create('Unknow format!');
end;
Result := Base64Encode(ss.DataString);
LastResult := arOk;
finally
ss.Free;
end;
end;
function TImageFXVampyre.GetPixel(const x, y: Integer): TPixelInfo;
begin
raise ENotImplemented.Create('Not implemented!');
//Result := GetPixelImage(x,y,fImageData^);
end;
function TImageFXVampyre.Rounded(RoundLevel : Integer = 27) : IImageFX;
begin
raise ENotImplemented.Create('Not implemented!');
end;
{var
rgn : HRGN;
auxbmp : TBitmap;
begin
Result := Self;
auxbmp := TBitmap.Create;
try
auxbmp.Assign(fBitmap);
fBitmap.Clear($00FFFFFF);
with fBitmap.Canvas do
begin
Brush.Style:=bsClear;
//Brush.Color:=clTransp;
Brush.Color:=clNone;
FillRect(Rect(0,0,auxbmp.Width,auxbmp.Height));
rgn := CreateRoundRectRgn(0,0,auxbmp.width + 1,auxbmp.height + 1,RoundLevel,RoundLevel);
SelectClipRgn(Handle,rgn);
Draw(0,0,auxbmp);
DeleteObject(Rgn);
end;
//bmp32.Assign(auxbmp);
finally
FreeAndNil(auxbmp);
end;
end; }
function TImageFXVampyre.AntiAliasing : IImageFX;
begin
raise ENotImplemented.Create('Not implemented!');
end;
{var
bmp : TBitmap;
begin
Result := Self;
bmp := TBitmap.Create;
try
//DoAntialias(fBitmap,bmp);
fBitmap.Assign(bmp);
finally
bmp.Free;
end;
end;}
function TImageFXVampyre.SetAlpha(Alpha : Byte) : IImageFX;
begin
Result := Self;
//DoAlpha(fBitmap,Alpha);
end;
procedure TImageFXVampyre.SetPixel(const x, y: Integer; const P: TPixelInfo);
begin
raise ENotImplemented.Create('Not implemented!');
//SetPixelImage(x,y,P,fBitmap);
end;
procedure TImageFXVampyre.SetPixelImage(const x, y: Integer; const P: TPixelInfo; bmp32 : TBitmap);
begin
raise ENotImplemented.Create('Not implemented!');
//bmp32.Pixel[x,y] := RGB(P.R,P.G,P.B);
end;
function TImageFXVampyre.GetPixelImage(const x, y: Integer; bmp32 : TBitmap) : TPixelInfo;
begin
raise ENotImplemented.Create('Not implemented!');
end;
{var
lRGB : TRGB;
begin
lRGB := ColorToRGBValues(bmp32.Pixel[x,y]);
Result.R := lRGB.R;
Result.G := lRGB.G;
Result.B := lRGB.B;
end;}
function TImageFXVampyre.GetResolution: string;
begin
end;
end.
|
unit DataAccessModule;
interface
uses
System.SysUtils, System.Classes, Fmx.Bind.GenData, Data.Bind.GenData,
Data.Bind.Components, Data.Bind.ObjectScope, Fmx.Graphics, System.IOUtils,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async,
FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.Stan.Param,
FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, FireDAC.FMXUI.Wait, FireDAC.Phys.IBBase, FireDAC.Comp.UI,
Data.DBXDataSnap, IPPeerClient, Data.DBXCommon, Datasnap.DBClient,
Datasnap.DSConnect, Data.SqlExpr, Unit1;
type
TdmDataAccess = class(TDataModule)
SQLConnection1: TSQLConnection;
DSProviderConnection1: TDSProviderConnection;
book: TClientDataSet;
booksource: TDataSource;
count: TClientDataSet;
procedure FDConnection1BeforeConnect(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
//procedure Connect; // 데이터베이스 연결
procedure AppendMode; // 입력 모드로 변경
procedure EditMode; // 수정 모드로 변경
procedure SetImage(ABitmap: TBitmap); // 이미지저장(본문, 목록의 썸네일 이미지)
procedure SaveItem; // 항목 저장(입력/수정)
procedure CancelItem; // 입력/수정 모드 취소
procedure DeleteItem; // 선택항목 삭제
end;
var
dmDataAccess: TdmDataAccess;
Demo: TServerMethods1Client;
implementation
{ %CLASSGROUP 'FMX.Controls.TControl' }
{$R *.dfm}
// 입력/수정 모드 취소
procedure TdmDataAccess.CancelItem;
begin
// if FDQuery1.UpdateStatus = TUpdateStatus.usInserted then
// FDQuery1.Cancel;
if book.UpdateStatus = TUpdateStatus.usInserted then
book.Cancel;
end;
// 데이터베이스 연결
//procedure TdmDataAccess.Connect;
//begin
//
// // FDConnection1.Connected := True;
// // FDQuery1.Active := True;
//end;
procedure TdmDataAccess.DataModuleCreate(Sender: TObject);
begin
Demo := TServerMethods1Client.Create(SQLConnection1.DBXConnection);
// FDConnection1BeforeConnect(true);
end;
procedure TdmDataAccess.DataModuleDestroy(Sender: TObject);
begin
Demo.Free;
end;
// 현재항목 삭제
procedure TdmDataAccess.DeleteItem;
begin
// dmDataAccess.DeleteItem;
// FDQuery1.Delete;
// FDQuery1.ApplyUpdates(0);
// FDQuery1.CommitUpdates;
// FDQuery1.Refresh;
book.Delete;
book.ApplyUpdates(-1);
book.Refresh;
end;
// 수정모드
procedure TdmDataAccess.EditMode;
begin
// FDQuery1.Edit;
//SQLConnection1.DriverName.
//Insert('localhost');
book.Edit;
end;
procedure TdmDataAccess.FDConnection1BeforeConnect(Sender: TObject);
begin
{$IFNDEF MSWINDOWS}
FDConnection1.Params.Values['Database'] :=
TPath.Combine(TPath.GetDocumentsPath, 'BOOKLOG.GDB');
{$ENDIF}
end;
// 입력모드
procedure TdmDataAccess.AppendMode;
begin
// FDQuery1.Append;
book.Append;
book.ApplyUpdates(-1);
end;
// 항목 저장
procedure TdmDataAccess.SaveItem;
begin
// 입력 시 BOOK_SEQ 자동생성되지만 미 입력 시 오류
if book.UpdateStatus = TUpdateStatus.usInserted then
book.fieldbyname('book_seq').AsInteger := 0;
book.post;
book.applyupdates(-1);
book.refresh;
end;
// 이미지 저장(본문이미지와 목록에 표시할 썸네일)
procedure TdmDataAccess.SetImage(ABitmap: TBitmap);
var
Thumbnail: TBitmap;
ImgStream, ThumbStream: TMemoryStream;
begin
ImgStream := TMemoryStream.Create;
ThumbStream := TMemoryStream.Create;
try
ABitmap.SaveToStream(ImgStream);
Thumbnail := ABitmap.CreateThumbnail(100, 100);
Thumbnail.SaveToStream(ThumbStream);
(book.FieldByName('BOOK_IMAGE') as TBlobField).LoadFromStream(ImgStream);
(book.FieldByName('BOOK_THUMB') as TBlobField).LoadFromStream(ThumbStream);
finally
ImgStream.Free;
ThumbStream.Free;
end;
end;
end.
|
Program CalcMedia ;
var
nome : string[20];
nota1 : integer;
nota2 : integer;
nota3 : integer;
nota4 : integer;
media : real;
Begin
nome := 'Cristiano';
nota1 := 5;
nota2 := 6;
nota3 := 10;
nota4 := 9;
media := (nota1 + nota2 + nota3 + nota4) / 4;
write ('Aluno: ');
writeln (nome);
writeln ();
write ('Média de: ');
writeln (media);
writeln ();
if (media > 7) and (media <= 10) then
begin
writeln ('O aluno foi APROVADO !');
end;
if (media > 5) and (media <= 7) then
begin
writeln ('O Aluno em RECUPERAÇÃO !');
end;
if (media <= 5) then
begin
writeln ('O aluno foi REPROVADO !');
end;
End. |
unit GrievanceDenialReasonDialogUnit;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, wwdblook, Db, DBTables, Wwkeycb, Grids, Wwdbigrd,
Wwdbgrid, ComCtrls, wwriched, wwrichedspell;
type
TGrievanceDenialReasonDialog = class(TForm)
OKButton: TBitBtn;
CancelButton: TBitBtn;
Label1: TLabel;
Label2: TLabel;
GrievanceDenialReasonCodeTable: TTable;
GrievanceDenialDataSource: TDataSource;
GrievanceDenialReasonGrid: TwwDBGrid;
GrievanceCodeIncrementalSearch: TwwIncrementalSearch;
Label3: TLabel;
ReasonRichEdit: TwwDBRichEditMSWord;
procedure OKButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
GrievanceDenialCode : String;
end;
var
GrievanceDenialReasonDialog: TGrievanceDenialReasonDialog;
implementation
{$R *.DFM}
{===============================================================}
Procedure TGrievanceDenialReasonDialog.FormCreate(Sender: TObject);
begin
try
GrievanceDenialReasonCodeTable.Open;
except
MessageDlg('Error opening grievance denial reason code table.',
mtError, [mbOK], 0);
end;
end; {FormCreate}
{===============================================================}
Procedure TGrievanceDenialReasonDialog.OKButtonClick(Sender: TObject);
begin
GrievanceDenialCode := GrievanceDenialReasonCodeTable.FieldByName('MainCode').Text;
ModalResult := mrOK;
end;
end.
|
{***************************************************************************
*
* Orion-project.org Lazarus Helper Library
* Copyright (C) 2016-2017 by Nikolay Chunosov
*
* This file is part of the Orion-project.org Lazarus Helper Library
* https://github.com/Chunosov/orion-lazarus
*
* This Library is free software: you can redistribute it and/or modify it
* under the terms of the MIT License. See enclosed LICENSE.txt for details.
*
***************************************************************************}
unit OriIniFile;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Classes, IniFiles, Graphics, Forms;
type
TOriIniFile = class(TIniFile)
private
FInMemory: Boolean;
FMemStream: TStream;
FMemStorage: String;
FSection: String;
FFormat: TFormatSettings;
Parts: array of String;
function ResembleString(const S: String): Integer;
function ResolutionSufix: String;
public
constructor Create; reintroduce;
constructor Create(const AFileName: String); reintroduce;
constructor CreateInMemory;
destructor Destroy; override;
function KeyExists(const Key: String): Boolean; overload; inline;
function KeyExists(const Section, Key: String): Boolean; overload; inline;
procedure WriteString(const Key, Value: String); overload;
procedure WriteInteger(const Key: string; Value: Longint); overload;
procedure WriteBool(const Key: string; Value: Boolean); overload;
procedure WriteFloat(const Key: string; Value: Extended); overload;
procedure WriteDate(const Key: string; Value: TDateTime); overload;
procedure WriteTime(const Key: string; Value: TDateTime); overload;
procedure WriteDateTime(const Key: string; Value: TDateTime); overload;
function ReadString(const Key, Value: String): String; overload;
function ReadInteger(const Key: string; Value: Longint): Longint; overload;
function ReadBool(const Key: string; Value: Boolean): Boolean; overload;
function ReadFloat(const Key: string; Value: Extended): Extended; overload;
function ReadDate(const Key: string; Value: TDateTime): TDateTime; overload;
function ReadTime(const Key: string; Value: TDateTime): TDateTime; overload;
function ReadDateTime(const Key: string; Value: TDateTime): TDateTime; overload;
procedure ReadText(const Key: String; Value: TStrings; const Default: String); overload;
procedure WriteText(const Key: String; Value: TStrings); overload;
function ReadText(const Key: String; const Default: String = ''): String; overload;
procedure WriteText(const Key: String; const Value: String); overload;
procedure WriteRect(const Key: String; const Value: TRect);
function ReadRect(const Key: String; const Value: TRect): TRect;
procedure WritePoint(const Key: String; const Value: TPoint); overload;
function ReadPoint(const Key: String; const Value: TPoint): TPoint; overload;
procedure WritePoint(const Key: String; X, Y: Integer); overload;
function ReadPoint(const Key: String; X, Y: Integer): TPoint; overload;
procedure WriteFont(const Key: String; Font: TFont);
procedure ReadFont(const Key: String; Font: TFont);
procedure WriteFormPos(Form: TCustomForm; const Key: String = '');
procedure WriteFormSize(Form: TCustomForm; const Key: String = '');
procedure WriteFormSizePos(Form: TCustomForm; const Key: String = '');
procedure ReadFormSizePos(Form: TCustomForm; const Key: String = ''; DefaultLeft: Integer = 0; DefaultTop: Integer = 0);
procedure ReadFormPos(Form: TCustomForm; const Key: String = ''; DefaultLeft: Integer = 0; DefaultTop: Integer = 0);
procedure ReadFormSize(Form: TCustomForm; const Key: String = '');
function GetMaxSectionIndex(const Prefix: String): Integer;
function NextSection(const Prefix: String): String;
procedure GetSectionKeysOnly(Strings: TStrings); overload;
procedure GetSectionKeysOnly(const Section: string; Strings: TStrings); overload;
procedure Init;
procedure Save;
procedure UpdateFile; override;
property Section: String read FSection write FSection;
end;
TOriMemIniFile = class(TOriIniFile)
end;
TPropSaver = TOriIniFile deprecated 'Use class TOriIniFile';
{ Pointer to a function returning path to application ini-file.
It is used by TOriIniFile when its constructor is called without parameters.
The GetIniFileName function is used by default.
}
var GetIniName: function(): String;
{ The flag defines if application is portable. Portable application stores all
its settings, templates and various user-specific infomation near the program
executable file. So application must have write access to a folder where it
is located. Non-portable (normal) application stores its settings in user
profile catalog (~/.config/appname/ on Linux, $(APPDATA)\appname\ on Windows).
}
var IsPortable: Boolean;
const
CMainSection = 'PREFERENCES';
{$IfDef WINDOWS}
SConfigFileExt = '.ini';
{$Else}
SConfigFileExt = '.cfg';
{$EndIf}
procedure StoreFormGeometry(AForm: TCustomForm);
procedure RestoreFormGeometry(AForm: TCustomForm);
implementation
uses
Math, LazFileUtils, LazUTF8;
{%region Quick helpers}
procedure StoreFormGeometry(AForm: TCustomForm);
begin
with TOriIniFile.Create do
try
WriteFormSizePos(AForm);
finally
Free;
end;
end;
procedure RestoreFormGeometry(AForm: TCustomForm);
begin
with TOriIniFile.Create do
try
ReadFormSizePos(AForm);
finally
Free;
end;
end;
{%endregion}
{%region Ini File Location}
var IniFileName: String;
function GetLocalIniFileName: String;
begin
Result := ChangeFileExt(ParamStrUTF8(0), SConfigFileExt);
end;
function GetIniFileName: String;
begin
if IniFileName = '' then
begin
if IsPortable then
IniFileName := GetLocalIniFileName
else
begin
// Windows: c:\Users\<user name>\AppData\Local\spectrum\spectrum.cfg
IniFileName := GetAppConfigFileUTF8(False, {$ifdef WINDOWS}False{$else}True{$endif});
end;
end;
Result := IniFileName;
end;
{%endregion}
{%region TOriIniFile}
constructor TOriIniFile.Create;
begin
FInMemory := False;
FSection := CMainSection;
if Assigned(GetIniName)
then inherited Create(GetIniName())
else inherited Create(GetIniFileName);
Init;
end;
constructor TOriIniFile.Create(const AFileName: String);
begin
FInMemory := False;
FSection := CMainSection;
inherited Create(AFileName);
Init;
end;
constructor TOriIniFile.CreateInMemory;
begin
FInMemory := True;
FMemStream := TStringStream.Create(FMemStorage);
end;
destructor TOriIniFile.Destroy;
begin
if Dirty and not FInMemory then UpdateFile;
if Assigned(FMemStream) then FMemStream.Free;
inherited;
end;
procedure TOriIniFile.Init;
begin
FFormat.DecimalSeparator := '.';
FFormat.DateSeparator := '.';
FFormat.TimeSeparator := ':';
FFormat.ShortDateFormat := 'dd.mm.yyyy';
FFormat.ShortTimeFormat := 'hh:nn';
FFormat.LongDateFormat := 'dd mmmm yyyy';
FFormat.LongTimeFormat := 'hh:nn:ss.zzzz';
Options := Options + [ifoCaseSensitive];
CacheUpdates := True;
end;
procedure TOriIniFile.Save;
begin
UpdateFile;
end;
procedure TOriIniFile.UpdateFile;
var
Dir: String;
begin
if not Dirty then Exit;
Dir := TrimFilename(ExtractFilePath(FileName));
if not DirectoryExistsUTF8(Dir) then
if not CreateDirUTF8(Dir) then
raise Exception.CreateFmt('Unable to create directory "%s"', [Dir]);
inherited;
end;
// разбивает строку на части, которые содержатся в StringArray,
// разделитель - точка с запятой используется для загрузки массивов
function TOriIniFile.ResembleString(const S: String): Integer;
var
L, I, Index: Integer;
begin
Index := 1;
Parts := nil;
I := 1;
while I <= Length(S) do
begin
if S[I] = ';' then
begin
if I-Index > 0 then
begin
L := Length(Parts);
SetLength(Parts, L+1);
Parts[L] := Copy(S, Index, I-Index);
end;
Index := I+1;
end;
Inc(I);
end;
// от последнего разделителя до конца строки
if I-Index > 0 then
begin
L := Length(Parts);
SetLength(Parts, L+1);
Parts[L] := Copy(S, Index, I-Index);
end;
Result := Length(Parts);
end;
function TOriIniFile.KeyExists(const Key: string): Boolean;
begin
Result := ValueExists(Section, Key);
end;
function TOriIniFile.KeyExists(const Section, Key: string): Boolean;
begin
Result := ValueExists(Section, Key);
end;
{%region Common Types}
procedure TOriIniFile.WriteString(const Key, Value: String);
begin
WriteString(FSection, Key, Value);
end;
function TOriIniFile.ReadString(const Key, Value: String): String;
begin
Result := ReadString(FSection, Key, Value);
end;
procedure TOriIniFile.WriteInteger(const Key: string; Value: Longint);
begin
WriteInteger(FSection, Key, Value);
end;
function TOriIniFile.ReadInteger(const Key: string; Value: Longint): Longint;
begin
Result := ReadInteger(FSection, Key, Value);
end;
procedure TOriIniFile.WriteBool(const Key: string; Value: Boolean);
begin
WriteBool(FSection, Key, Value);
end;
function TOriIniFile.ReadBool(const Key: string; Value: Boolean): Boolean;
begin
Result := ReadBool(FSection, Key, Value);
end;
procedure TOriIniFile.WriteFloat(const Key: string; Value: Extended);
begin
WriteString(FSection, Key, FloatToStr(Value, FFormat));
end;
function TOriIniFile.ReadFloat(const Key: string; Value: Extended): Extended;
var S: String;
begin
S := UpperCase(Trim(ReadString(FSection, Key, '')));
if S = 'INF' then
Result := Infinity
else if S = '-INF' then
Result := -Infinity
else
Result := StrToFloatDef(S, Value, FFormat);
end;
{%endregion}
{%region Date and Time}
procedure TOriIniFile.WriteDate(const Key: string; Value: TDateTime);
begin
WriteString(FSection, Key, DateToStr(Value, FFormat));
end;
procedure TOriIniFile.WriteTime(const Key: string; Value: TDateTime);
begin
WriteString(FSection, Key, TimeToStr(Value, FFormat));
end;
procedure TOriIniFile.WriteDateTime(const Key: string; Value: TDateTime);
begin
WriteString(FSection, Key, DateTimeToStr(Value, FFormat));
end;
function TOriIniFile.ReadDate(const Key: string; Value: TDateTime): TDateTime;
begin
if not TryStrToDate(ReadString(FSection, Key, ''), Result, FFormat) then Result := Value;
end;
function TOriIniFile.ReadTime(const Key: string; Value: TDateTime): TDateTime;
begin
if not TryStrToTime(ReadString(FSection, Key, ''), Result, FFormat) then Result := Value;
end;
function TOriIniFile.ReadDateTime(const Key: string; Value: TDateTime): TDateTime;
begin
if not TryStrToDateTime(ReadString(FSection, Key, ''), Result, FFormat) then Result := Value;
end;
{%endregion}
{%region Text}
procedure TOriIniFile.WriteText(const Key: String; const Value: String);
var
Strs: TStrings;
begin
Strs := TStringList.Create;
try
Strs.Text := Value;
WriteText(Key, Strs);
finally
Strs.Free;
end;
end;
function TOriIniFile.ReadText(const Key: String; const Default: String): String;
var
Strs: TStrings;
begin
if not KeyExists(Key) then
begin
Result := Default;
Exit;
end;
Strs := TStringList.Create;
try
ReadText(Key, Strs, Default);
Result := Strs.Text;
finally
Strs.Free;
end;
end;
// Stores several lines of text into single string parameter.
procedure TOriIniFile.WriteText(const Key: String; Value: TStrings);
var OldDelimiter, OldQuoteChar: Char;
begin
OldDelimiter := Value.Delimiter;
OldQuoteChar := Value.QuoteChar;
try
Value.Delimiter := ',';
Value.QuoteChar := '"';
WriteString(Key, Value.DelimitedText);
finally
Value.Delimiter := OldDelimiter;
Value.QuoteChar := OldQuoteChar;
end;
end;
// Value of parameter Default should be in delimited text format, i.e.:
// "string1 string1","string 2 string2","string3 string3".
// Elsewise string will be splitted - each word will be at different line.
procedure TOriIniFile.ReadText(const Key: String; Value: TStrings; const Default: String);
var OldDelimiter, OldQuoteChar: Char;
begin
OldDelimiter := Value.Delimiter;
OldQuoteChar := Value.QuoteChar;
try
Value.Delimiter := ',';
Value.QuoteChar := '"';
Value.DelimitedText := ReadString(Key, Default);
finally
Value.Delimiter := OldDelimiter;
Value.QuoteChar := OldQuoteChar;
end;
end;
{%endregion}
{%region Point and Rect}
procedure TOriIniFile.WriteRect(const Key: String; const Value: TRect);
begin
with Value do WriteString(Key, Format('%d;%d;%d;%d', [Left, Top, Right, Bottom]));
end;
function TOriIniFile.ReadRect(const Key: String; const Value: TRect): TRect;
begin
if ResembleString(ReadString(Key, '')) > 3 then
begin
Result.Left := StrToIntDef(Parts[0], Value.Left);
Result.Top := StrToIntDef(Parts[1], Value.Top);
Result.Right := StrToIntDef(Parts[2], Value.Right);
Result.Bottom := StrToIntDef(Parts[3], Value.Bottom);
end
else Result := Value;
end;
procedure TOriIniFile.WritePoint(const Key: String; const Value: TPoint);
begin
WriteString(Key, Format('%d;%d', [Value.X, Value.Y]));
end;
procedure TOriIniFile.WritePoint(const Key: String; X, Y: Integer);
begin
WriteString(Key, Format('%d;%d', [X, Y]));
end;
function TOriIniFile.ReadPoint(const Key: String; const Value: TPoint): TPoint;
begin
if ResembleString(ReadString(Key, '')) > 1 then
begin
Result.X := StrToIntDef(Parts[0], Value.X);
Result.Y := StrToIntDef(Parts[1], Value.Y);
end
else Result := Value;
end;
function TOriIniFile.ReadPoint(const Key: String; X, Y: Integer): TPoint;
begin
if ResembleString(ReadString(Key, '')) > 1 then
begin
Result.X := StrToIntDef(Parts[0], X);
Result.Y := StrToIntDef(Parts[1], Y);
end
else
begin
Result.X := X;
Result.Y := Y;
end;
end;
{%endregion}
{%region Font}
procedure TOriIniFile.WriteFont(const Key: String; Font: TFont);
begin
WriteString(Key, Format('%s;%d;$%s;%d;%d;%d;%d;%d',
[Font.Name, Font.Size, IntToHex(Font.Color, 8), Ord(Font.Charset),
Ord(fsBold in Font.Style), Ord(fsItalic in Font.Style),
Ord(fsUnderline in Font.Style), Ord(fsStrikeOut in Font.Style)]));
end;
procedure TOriIniFile.ReadFont(const Key: String; Font: TFont);
begin
if ResembleString(ReadString(Key, '')) > 7 then
with Font do
begin
Name := Parts[0];
Size := StrToIntDef(Parts[1], Size);
Color := StrToIntDef(Parts[2], Color);
Charset := StrToIntDef(Parts[3], Charset);
Style := [];
if StrToBool(Parts[4]) then Style := Style + [fsBold];
if StrToBool(Parts[5]) then Style := Style + [fsItalic];
if StrToBool(Parts[6]) then Style := Style + [fsUnderline];
if StrToBool(Parts[7]) then Style := Style + [fsStrikeOut];
end;
end;
{%endregion}
// Rerurns maximum number of a section whose name like 'PrefixXXX'
function TOriIniFile.GetMaxSectionIndex(const Prefix: String): Integer;
var
I, Index: Integer;
Strs: TStrings;
begin
Result := 0;
Strs := TStringList.Create;
try
ReadSections(Strs);
for I := 0 to Strs.Count-1 do
if Copy(Strs[I], 1, Length(Prefix)) = Prefix then
begin
Index := StrToIntDef(Copy(Strs[I], Length(Prefix)+1, MaxInt), 0);
if Index > Result then Result := Index;
end;
finally
Strs.Free;
end;
end;
function TOriIniFile.NextSection(const Prefix: String): String;
begin
Result := Prefix + IntToStr(GetMaxSectionIndex(Prefix) + 1);
end;
// Копирует из текущей секции только ключи, без значений (Key1)
procedure TOriIniFile.GetSectionKeysOnly(Strings: TStrings);
begin
GetSectionKeysOnly(Section, Strings);
end;
// Копирует из заданной секции только ключи, без значений (Key1)
procedure TOriIniFile.GetSectionKeysOnly(const Section: string; Strings: TStrings);
begin
ReadSection(Section, Strings);
end;
{%endregion}
{%region Forms}
function TOriIniFile.ResolutionSufix: String;
begin
Result := Format('%dx%d', [Screen.Width, Screen.Height]);
end;
procedure TOriIniFile.WriteFormPos(Form: TCustomForm; const Key: String = '');
var _key: String;
begin
if Key = '' then _key := Form.Name else _key := Key;
WriteString(_key + 'Pos' + ResolutionSufix, Format('%d;%d', [Form.Left, Form.Top]));
end;
procedure TOriIniFile.WriteFormSize(Form: TCustomForm; const Key: String = '');
var _key: String;
begin
if Key = '' then _key := Form.Name else _key := Key;
WriteString(_key + 'Size' + ResolutionSufix, Format('%d;%d', [Form.Width, Form.Height]));
end;
procedure TOriIniFile.WriteFormSizePos(Form: TCustomForm; const Key: String = '');
var _key: String;
begin
if Key = '' then _key := Form.Name else _key := Key;
WriteString(_key + 'SizePos'+ ResolutionSufix, Format('%d;%d;%d;%d',
[Form.Width, Form.Height, Form.Left, Form.Top]));
end;
procedure TOriIniFile.ReadFormPos(Form: TCustomForm; const Key: String = '';
DefaultLeft: Integer = 0; DefaultTop: Integer = 0);
const SafeRange = 20;
var
_key: String;
W, H, Left, Top, DefLeft, DefTop: Integer;
begin
if Key = '' then _key := Form.Name else _key := Key;
if DefaultLeft = 0 then DefLeft := Form.Left else DefLeft := DefaultLeft;
if DefaultTop = 0 then DefTop := Form.Top else DefTop := DefaultTop;
if ResembleString(ReadString(_key + 'Pos' + ResolutionSufix, '')) > 1 then
begin
Left := StrToIntDef(Parts[0], DefLeft);
Top := StrToIntDef(Parts[1], DefTop);
W := Screen.DesktopWidth - SafeRange;
H := Screen.DesktopHeight - SafeRange;
if Left > W then Left := W
else if Left < SafeRange-Form.Width then Left := SafeRange;
if Top > H then Top := H
else if Top < SafeRange-Form.Height then Top := SafeRange;
Form.SetBounds(Left, Top, Form.Width, Form.Height);
end
else Form.SetBounds(DefLeft, DefTop, Form.Width, Form.Height);
end;
procedure TOriIniFile.ReadFormSize(Form: TCustomForm; const Key: String = '');
var _key: String;
begin
if Key = '' then _key := Form.Name else _key := Key;
if ResembleString(ReadString(_key + 'Size' + ResolutionSufix, '')) > 1 then
Form.SetBounds(Form.Left, Form.Top,
StrToIntDef(Parts[0], Form.Width), StrToIntDef(Parts[1], Form.Height));
end;
{ Предполагается, что у формы Position = poDesigned.
Если для текущего разрешения параметр не найден, то форма сохраняет размеры
и помещается в положение по умолчанию. Если по умолчанию заданы 0, то форма
остается там же, где была.
}
procedure TOriIniFile.ReadFormSizePos(Form: TCustomForm; const Key: String = '';
DefaultLeft: Integer = 0; DefaultTop: Integer = 0);
const SafeRange = 20;
var
_key: String;
W, H, Left, Top, Width, Height, DefLeft, DefTop: Integer;
begin
if Key = '' then _key := Form.Name else _key := Key;
if DefaultLeft = 0 then DefLeft := Form.Left else DefLeft := DefaultLeft;
if DefaultTop = 0 then DefTop := Form.Top else DefTop := DefaultTop;
if ResembleString(ReadString(_key + 'SizePos' + ResolutionSufix, '')) > 3 then
begin
Width := StrToIntDef(Parts[0], Form.Width);
Height := StrToIntDef(Parts[1], Form.Height);
Left := StrToIntDef(Parts[2], DefLeft);
Top := StrToIntDef(Parts[3], DefTop);
W := Screen.DesktopWidth - SafeRange;
H := Screen.DesktopHeight - SafeRange;
if Left > W then Left := W
else if Left < SafeRange-Width then Left := SafeRange;
if Top > H then Top := H
else if Top < SafeRange-Height then Top := SafeRange;
Form.SetBounds(Left, Top, Width, Height);
end
else Form.SetBounds(DefLeft, DefTop, Form.Width, Form.Height);
end;
{%endregion}
initialization
GetIniName := @GetIniFileName;
IsPortable := FileExistsUTF8(GetLocalIniFileName);
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Datasnap.DSTCPServerTransport;
interface
uses
System.Classes,
Data.DBXTransport,
Datasnap.DSAuth,
Datasnap.DSCommonServer,
Datasnap.DSTransport,
IPPeerAPI,
System.SysUtils;
type
TDSTCPChannel = class(TDBXChannel)
strict private
FContext: IIPContext;
FChannelInfo: TDBXSocketChannelInfo;
FReadBuffer: TBytes;
FConnectionLost: Boolean;
FSessionId: String;
protected
function IsConnectionLost: Boolean; override;
function GetChannelInfo: TDBXChannelInfo; override;
public
constructor Create(AContext: IIPContext);
destructor Destroy; override;
procedure Open; override;
procedure Close; override;
function Read(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
function Write(const Buffer: TBytes; const Offset: Integer; const Count: Integer): Integer; override;
/// <summary>Enables KeepAlive for this channel's socket connection.</summary>
/// <remarks>If the channel is idle for longer than KeepAliveTime, then a KeepAlive packet is sent and
/// a response is waited for for the given interval, before terminating the connection.
/// The number of keep-alive packet retries is OS specific and can't be specified here.
/// </remarks>
/// <param name="KeepAliveTime">The idle time in milliseconds before sending a keep-alive packet.</param>
/// <param name="KeepAliveInterval">How long to wait in milliseconds before sending successive
/// keep-alive packets when the previous one receives no response.</param>
function EnableKeepAlive(KeepAliveTime: Integer; KeepAliveInterval: Integer = 100): Boolean;
/// <summary>Disables keep-alive packets for the channel's connection.</summary>
procedure DisableKeepAlive;
/// <summary>Returns the connection object for this channel if one is available.</summary>
/// <remarks>This is generally an instance of TIdTCPConnection.</remarks>
function GetConnection: TObject;
/// <summary>Returns the session ID for the channel.</summary>
/// <remarks>This will not be populated until a Read has been made.</remarks>
property SessionId: String read FSessionId;
end;
///<summary>
/// Event for TCP connection being established.
///</summary>
TDSTCPConnectEventObject = record
private
FConnection: TObject;
FChannel: TDSTCPChannel;
public
/// <summary>Creates a new instance of TDSTCPConnectEventObject, setting the proper fields.</summary>
constructor Create(AConnection: TObject; AChannel: TDSTCPChannel);
/// <summary>The underlying connection. Generally an instance of TIdTCPConnection.</summary>
property Connection: TObject read FConnection;
/// <summary>The channel wrapping the connection</summary>
property Channel: TDSTCPChannel read FChannel;
end;
///<summary>
/// Event for TCP connection being closed.
///</summary>
TDSTCPDisconnectEventObject = record
private
FConnection: TObject;
public
/// <summary>Creates a new instance of TDSTCPDisconnectEventObject.</summary>
constructor Create(AConnection: TObject);
/// <summary>The underlying connection. Generally an instance of TIdTCPConnection.</summary>
property Connection: TObject read FConnection;
end;
///<summary>
/// Event for TCP connections being established.
///</summary>
TDSTCPConnectEvent = procedure(Event: TDSTCPConnectEventObject) of object;
///<summary>
/// Event for TCP connections being closed.
///</summary>
TDSTCPDisconnectEvent = procedure(Event: TDSTCPDisconnectEventObject) of object;
/// <summary>The enablement options for KeepAlive.</summary>
/// <remarks>A value of Default says to use the OS setting for TCP/IP KeepAlive. A value of
/// Disabled will not enable KeepAlive, and will disable it if it was enabled automatically
/// by the OS. A value of Enabled will enable KeepAlive if it wasn't enabled by the OS,
/// or replace the KeepAlive properties if it was already enabled.
/// </remarks>
TDSKeepAliveEnablement = (kaDefault, kaEnabled, kaDisabled);
///<summary>
/// Socket based transport for a <c>TDSServer</c> server.
///</summary>
TDSTCPServerTransport = class(TDSServerTransport)
strict private
FPort: Integer;
FMaxThreads: Integer;
FPoolSize: Integer;
FProtocolHandlerFactory: TDSJSONProtocolHandlerFactory;
FAuthenticationManager: TDSCustomAuthenticationManager;
FTDSTCPConnectEvent: TDSTCPConnectEvent;
FTDSTCPDisconnectEvent: TDSTCPDisconnectEvent;
FKeepAliveEnablement: TDSKeepAliveEnablement;
FKeepAliveTime: Integer;
FKeepAliveInterval: Integer;
procedure DoOnConnect(AContext: IIPContext);
procedure DoOnDisconnect(AContext: IIPContext);
procedure DoOnExecute(AContext: IIPContext);
protected
FTcpServer: IIPTCPServer;
class function GetTcpChannel(
AConnectionHandler: TDSServerConnectionHandler): TDBXChannel; static;
function CreateTcpServer: IIPTCPServer; virtual;
function CreateTcpChannel(AContext: IIPContext): TDBXChannel; virtual;
procedure SetServer(const AServer: TDSCustomServer); override;
procedure SetAuthenticationManager(const AuthManager: TDSCustomAuthenticationManager);
procedure Notification(AComponent: TComponent; Operation: TOperation);
override;
procedure SetIPImplementationID(const AIPImplementationID: string); override;
public
destructor Destroy; override;
constructor Create(AOwner: TComponent); override;
///<summary>
/// Called by the server when it is starting.
///</summary>
procedure Start; override;
///<summary>
/// Called by the server when it is stoping.
///</summary>
procedure Stop; override;
published
///<summary>
/// TCP/IP server side port. Defaults to 211.
///</summary>
property Port: Integer read FPort write FPort default 211;
///<summary>
/// Maximum amount of threads allowed in the scheduler. No limit is imposed on thread pool size if set to 0.
/// Must be set before server is started.
/// Defaults to 0.
///</summary>
property MaxThreads: Integer read FMaxThreads write FMaxThreads default 0;
///<summary>
/// Maximum amount of threads allocated in the thread pool. Must be set before server is started.
/// Defaults to 10.
///</summary>
property PoolSize: Integer read FPoolSize write FPoolSize default 10;
///<summary>
/// <c>TDSServer</c> instance that this transport is servicing.
///</summary>
property Server;
///<summary>
/// Buffer size in kilobytes to use for TCP/IP read and write operations.
///</summary>
property BufferKBSize;
///<summary>
/// Collection of filters that will process the bytestream in this transport
///</summary>
property Filters;
///<summary>
/// Authentication Manager to use when invoking server methods.
///</summary>
property AuthenticationManager: TDSCustomAuthenticationManager read FAuthenticationManager write SetAuthenticationManager;
///<summary>
/// Event fired when a connections are established.
///</summary>
property OnConnect: TDSTCPConnectEvent read FTDSTCPConnectEvent write FTDSTCPConnectEvent;
///<summary>
/// Event fired when a connections are closed.
///</summary>
property OnDisconnect: TDSTCPDisconnectEvent read FTDSTCPDisconnectEvent write FTDSTCPDisconnectEvent;
///<summary>Decides if new connections have KeepAlive enabled, disabled or OS default setting.</summary>
///<remarks>The other keep-alive values are only used if this is set to kaEnabled.
/// The KeepAlive setting can be overridden on a case-by-case bases for each connection, by
/// implementing the OnConnect event of this component.
///</remarks>
property KeepAliveEnablement: TDSKeepAliveEnablement read FKeepAliveEnablement write FKeepAliveEnablement;
///<summary>If KeepAlive is set to enabled, specifies the KeepAlive time to use (ms).</summary>
///<remarks>See TDSTCPChannel.EnableKeepAlive for more information on this property.</remarks>
property KeepAliveTime: Integer read FKeepAliveTime write FKeepAliveTime default 300000;
///<summary>If KeepAlive is set to enabled, specifies the KeepAlive interval to use (ms).</summary>
///<remarks>See TDSTCPChannel.EnableKeepAlive for more information on this property.</remarks>
property KeepAliveInterval: Integer read FKeepAliveInterval write FKeepAliveInterval default 100;
property IPImplementationID;
end;
implementation
uses
{$IFNDEF POSIX}
Winapi.ActiveX,
System.Win.ComObj,
{$ENDIF}
Data.DBXClientResStrs,
Data.DBXCommon,
Data.DBXMessageHandlerCommon,
Data.DBXTransportFilter,
Datasnap.DSHTTPLayer, // Force HTTP transport to be registered when client use this unit.
Datasnap.DSService,
Data.DBXMessageHandlerJSonServer;
type
// Internal subclass of TDSTCPChannel used to inject new functionality into the channel
// for XE2 updates, without causing any interface breaking changes.
TDSTCPChannelInternal = class(TDSTCPChannel)
public
constructor Create(AContext: IIPContext);
procedure Close; override;
private
FEventMethod: TDSSessionEvent;
//event to log in the TDSSessionManager. When this Channel's session is closed, close the channel
//if it isn't already being closed.
procedure ChannelSessionEvent(Sender: TObject; const EventType: TDSSessionEventType;
const Session: TDSSession);
end;
{ TDSTCPChannelInternal }
procedure TDSTCPChannelInternal.ChannelSessionEvent(Sender: TObject;
const EventType: TDSSessionEventType; const Session: TDSSession);
begin
//if the sesison has been initiated for this connection
if (not ConnectionLost) and
(Session <> nil) and
(SessionId <> EmptyStr) and
//and this is an event for a session closing
(EventType = SessionClose) and
//and the session beign closed is this channel's (connection's) session
(Session.SessionName = SessionId)
then
begin
//close the connection
Close;
end;
end;
{ TDSTCPConnectionEvent }
constructor TDSTCPConnectEventObject.Create(AConnection: TObject; AChannel: TDSTCPChannel);
begin
FConnection := AConnection;
FChannel := AChannel;
end;
procedure TDSTCPChannelInternal.Close;
begin
TDSSessionManager.Instance.RemoveSessionEvent(FEventMethod);
inherited;
end;
constructor TDSTCPChannelInternal.Create(AContext: IIPContext);
begin
inherited Create(AContext);
FEventMethod := ChannelSessionEvent;
TDSSessionManager.Instance.AddSessionEvent(FEventMethod);
end;
{ TDSTCPDisconnectEventObject }
constructor TDSTCPDisconnectEventObject.Create(AConnection: TObject);
begin
FConnection := AConnection;
end;
{ TDSTCPServerTransport }
constructor TDSTCPServerTransport.Create(AOwner: TComponent);
begin
inherited;
FPort := 211;
FProtocolHandlerFactory := TDSJSONProtocolHandlerFactory.Create(Self);
FTDSTCPConnectEvent := nil;
FTDSTCPDisconnectEvent := nil;
FKeepAliveEnablement := kaDefault; //use OS specified KeepAlive settings
FKeepAliveTime := 300000; //5 minutes before using KeepAlive packets
FKeepAliveInterval := 100; //100 millisecond wait between retires
FPoolSize := 10;
end;
destructor TDSTCPServerTransport.Destroy;
begin
Stop;
FreeAndNil(FProtocolHandlerFactory);
inherited;
end;
function TDSTCPServerTransport.CreateTcpChannel(AContext: IIPContext): TDBXChannel;
begin
Result := TDSTCPChannelInternal.Create(AContext);
end;
class function TDSTCPServerTransport.GetTcpChannel(AConnectionHandler: TDSServerConnectionHandler): TDBXChannel;
var
LChannel: TDBXChannel;
begin
Result := nil;
LChannel := AConnectionHandler.Channel;
if LChannel is TDBXFilterSocketChannel then
begin
Result := TDBXFilterSocketChannel(LChannel).Channel;
end;
end;
procedure TDSTCPServerTransport.DoOnConnect(AContext: IIPContext);
var
IndyChannel: TDBXChannel;
FilterChannel: TDBXFilterSocketChannel;
Event: TDSTCPConnectEventObject;
begin
FilterChannel := TDBXFilterSocketChannel.Create(Filters);
IndyChannel := CreateTcpChannel(AContext);
{$IFNDEF POSIX}
if CoInitFlags = -1 then
CoInitializeEx(nil, COINIT_MULTITHREADED)
else
CoInitializeEx(nil, CoInitFlags);
{$ENDIF}
IndyChannel.Open;
// set the delegate
FilterChannel.Channel := IndyChannel;
AContext.Data := FProtocolHandlerFactory.CreateProtocolHandler(FilterChannel);
if AContext.Data is TDBXJSonServerProtocolHandler then
begin
if TDBXJSonServerProtocolHandler(AContext.Data).DSSession = nil then
begin
TDBXJSonServerProtocolHandler(AContext.Data).DSSession :=
TDSSessionManager.Instance.CreateSession<TDSTCPSession>(
function: TDSSession
begin
Result := TDSTCPSession.Create(AuthenticationManager);
Result.PutData('CommunicationProtocol', 'tcp/ip');
Result.PutData('RemoteIP', AContext.Connection.Socket.Binding.PeerIP);
end,
''
);
end;
end;
if Assigned(FTDSTCPConnectEvent) and (AContext <> nil) and (AContext.Connection <> nil) and
(FTcpServer <> nil) and FTcpServer.Active then
begin
if IndyChannel Is TDSTCPChannel then
begin
//enable keep alive, disable it, or leave the OS default setting as it is
if FKeepAliveEnablement = kaEnabled then
TDSTCPChannel(IndyChannel).EnableKeepAlive(FKeepAliveTime, FKeepAliveInterval)
else if FKeepAliveEnablement = kaDisabled then
TDSTCPChannel(IndyChannel).DisableKeepAlive;
Event := TDSTCPConnectEventObject.Create(AContext.Connection.GetObject, TDSTCPChannel(IndyChannel));
end
else
Event := TDSTCPConnectEventObject.Create(AContext.Connection.GetObject, nil);
try
OnConnect(Event);
except
end;
end;
end;
procedure TDSTCPServerTransport.DoOnDisconnect(AContext: IIPContext);
var
TempData: TObject;
Event: TDSTCPDisconnectEventObject;
begin
if Assigned(FTDSTCPDisconnectEvent) and (AContext <> nil) and (AContext.Connection <> nil) and
(FTcpServer <> nil) and FTcpServer.Active then
begin
Event := TDSTCPDisconnectEventObject.Create(AContext.Connection.GetObject);
try
OnDisconnect(Event);
except
end;
end;
TempData := AContext.Data;
AContext.Data := nil;
TempData.Free;
{$IFNDEF POSIX}
CoUninitialize;
{$ENDIF}
end;
procedure TDSTCPServerTransport.DoOnExecute(AContext: IIPContext);
begin
// Added for a several reasons. 1) This method can be called when
// there is nothing to read. Since Indy 10 is polling based, if
// we just return, there will be heavy cpu usage as this this method
// spins in the callers loop. Calling CheckForDataOnSource with
// a value of 10 milliseconds avoids the cpu overhead.
// 2) HandleNonBlockingProtocol should not be called unless there is 1 or
// more bytes to read. An error will occur if nothing can be read.
// 3) In the case of a disconnect message, AContext.Data is freed. However
// this method will continue to be called until the server detects that
// the client socket has been closed.
//
if AContext.Connection.IOHandler.InputBuffer.Size = 0 then
AContext.Connection.IOHandler.CheckForDataOnSource(10);
if AContext.Connection.IOHandler.InputBuffer.Size > 0 then
begin
try
TDBXProtocolHandler(AContext.Data).SetUp(FAuthenticationManager);
Assert(TDSSessionManager.GetThreadSession <> nil);
TDSSessionManager.GetThreadSession.ObjectCreator := self;
TDBXProtocolHandler(AContext.Data).HandleNonBlockingProtocol;
finally
TDSSessionManager.ClearThreadSession;
end;
end;
end;
procedure TDSTCPServerTransport.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) then
begin
if (AComponent = Server) then
Server := nil
else if (AComponent = FAuthenticationManager) then
FAuthenticationManager := nil;
end;
end;
procedure TDSTCPServerTransport.SetAuthenticationManager(const AuthManager: TDSCustomAuthenticationManager);
begin
if Assigned(FAuthenticationManager) then
FAuthenticationManager.RemoveFreeNotification(Self);
FAuthenticationManager := AuthManager;
if Assigned(FAuthenticationManager) then
FAuthenticationManager.FreeNotification(Self);
end;
procedure TDSTCPServerTransport.SetServer(const AServer: TDSCustomServer);
begin
if (AServer <> Server) then
begin
if Assigned(Server) then
RemoveFreeNotification(Server);
if Assigned(AServer) then
begin
FreeNotification(AServer);
DBXContext := AServer.DBXContext;
end;
end;
inherited SetServer(AServer);
end;
procedure TDSTCPServerTransport.SetIPImplementationID(const AIPImplementationID: string);
begin
if FTcpServer <> nil then
raise TDBXError.Create(0, sCannotChangeIPImplID);
inherited SetIPImplementationID(AIPImplementationID);
end;
function TDSTCPServerTransport.CreateTcpServer: IIPTCPServer;
begin
Result := PeerFactory.CreatePeer(IPImplementationID, IIPTCPServer, nil) as IIPTCPServer;
end;
procedure TDSTCPServerTransport.Start;
var
Scheduler: IIPSchedulerOfThreadPool;
begin
inherited;
FTcpServer := CreateTcpServer;
FTcpServer.OnConnect := DoOnConnect;
FTcpServer.OnDisconnect := DoOnDisconnect;
FTcpServer.OnExecute := DoOnExecute;
FTcpServer.UseNagle := false;
FTcpServer.Bindings.Add.Port := FPort;
Scheduler := PeerFactory.CreatePeer(IPImplementationID, IIPSchedulerOfThreadPool, FTCPServer.GetObject as TComponent) as IIPSchedulerOfThreadPool;
Scheduler.MaxThreads := MaxThreads;
Scheduler.PoolSize := PoolSize;
FTCPServer.Scheduler := Scheduler;
FTcpServer.Active := True;
end;
procedure TDSTCPServerTransport.Stop;
begin
if FTcpServer <> nil then
begin
FTcpServer.Active := False;
FTcpServer := nil;
end;
inherited;
end;
{ TDSTCPChannel }
procedure TDSTCPChannel.Close;
begin
inherited;
if Assigned(FContext) and Assigned(FContext.Connection) then
try
FContext.Connection.Disconnect;
except
on Exception do
// nothing
end;
FreeAndNil(FChannelInfo);
end;
constructor TDSTCPChannel.Create(AContext: IIPContext);
begin
inherited Create;
FContext := AContext;
end;
destructor TDSTCPChannel.Destroy;
begin
Close;
inherited;
end;
procedure TDSTCPChannel.DisableKeepAlive;
begin
if (FContext <> nil) and (GStackPeers(FContext.GetIPImplementationID) <> nil) and (FContext.Connection <> nil) and
(FContext.Connection.Socket <> nil) and (FContext.Connection.Socket.Binding <> nil) then
begin
GStackPeers(FContext.GetIPImplementationID).SetKeepAliveValues(FContext.Connection.Socket.Binding.Handle, False, 0, 0);
end;
end;
function TDSTCPChannel.EnableKeepAlive(KeepAliveTime, KeepAliveInterval: Integer): Boolean;
begin
Result := False;
if (FContext <> nil) and (GStackPeers(FContext.GetIPImplementationID) <> nil) and (FContext.Connection <> nil) and
(FContext.Connection.Socket <> nil) and (FContext.Connection.Socket.Binding <> nil) then
begin
GStackPeers(FContext.GetIPImplementationID).SetKeepAliveValues(FContext.Connection.Socket.Binding.Handle, True, KeepAliveTime, KeepAliveInterval);
Result := True;
end;
end;
function TDSTCPChannel.GetChannelInfo: TDBXChannelInfo;
begin
Result := FChannelInfo;
end;
function TDSTCPChannel.GetConnection: TObject;
begin
Result := nil;
if (FContext <> nil) then
Result := FContext.Connection.GetObject;
end;
function TDSTCPChannel.IsConnectionLost: Boolean;
begin
Result := FConnectionLost;
end;
procedure TDSTCPChannel.Open;
var
ClientInfo: TDBXClientInfo;
begin
inherited;
FreeAndNil(FChannelInfo);
FChannelInfo := TDBXSocketChannelInfo.Create(IntPtr(FContext.Connection), FContext.Connection.Socket.Binding.PeerIP);
ClientInfo := FChannelInfo.ClientInfo;
with ClientInfo do
begin
IpAddress := FContext.Connection.Socket.Binding.PeerIP;
ClientPort := IntToStr(FContext.Connection.Socket.Binding.PeerPort);
Protocol := 'tcp/ip';
end;
FChannelInfo.ClientInfo := ClientInfo;
end;
function TDSTCPChannel.Read(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
var
ActualReadCount: Integer;
Session: TDSSession;
begin
//Set the SessionId for this channel if it hasn't already been set
if FSessionId = EmptyStr then
begin
Session := TDSSessionManager.Instance.GetThreadSession;
if Session <> nil then
FSessionId := Session.SessionName;
end;
// wait for data
while FContext.Connection.IOHandler.InputBuffer.Size = 0 do
if FContext.Connection.IOHandler.Connected then
// try again
try
FContext.Connection.IOHandler.CheckForDataOnSource(10);
except
FConnectionLost := True;
raise TDBXError.Create(0, SConnectionLost);
end
else
begin
FConnectionLost := True;
raise TDBXError.Create(0, SConnectionLost);
end;
if FContext.Connection.IOHandler.InputBuffer.Size < Count then
ActualReadCount := FContext.Connection.IOHandler.InputBuffer.Size
else
ActualReadCount := Count;
if Length(FReadBuffer) < ActualReadCount then
SetLength(FReadBuffer, ActualReadCount);
FContext.Connection.IOHandler.ReadBytes(FReadBuffer, ActualReadCount, False);
Move(FReadBuffer[0], Buffer[Offset], ActualReadCount);
Result := ActualReadCount;
end;
function TDSTCPChannel.Write(const Buffer: TBytes; const Offset,
Count: Integer): Integer;
begin
Assert(Offset = 0);
FContext.Connection.IOHandler.Write(Buffer, Count, Offset);
Result := Count;
end;
end.
|
unit caMemory;
{$INCLUDE ca.inc}
interface
uses
Windows, TypInfo, SysUtils, Classes, Forms;
function MemListAsXML: String;
function MemObject(Index: Integer): TObject;
function MemObjectCount: Integer;
implementation
var
ObjList: array[0..65535] of Pointer;
FirstFree: Integer = -1;
function GetClassAttributes(PItem: Pointer; var AObjAddr, AObjClass, AObjName, AObjSize, AObjUnit: ShortString): Boolean;
var
IsClass: Boolean;
IsOwnedComponent: Boolean;
Item: TObject;
PropInfo: PPropInfo;
TypeData: PTypeData;
begin
Item := TObject(PItem);
try
IsClass := PTypeInfo(Item.ClassInfo).Kind = tkClass;
if IsClass then
begin
TypeData := GetTypeData(PTypeInfo(Item.ClassInfo));
IsOwnedComponent := False;
if Item is TComponent then
IsOwnedComponent := TComponent(Item).Owner <> nil;
if not IsOwnedComponent then
begin
PropInfo := GetPropInfo(PTypeInfo(Item.ClassInfo), 'Name');
AObjAddr := IntToHex(Cardinal(PItem), 8);
AObjName := 'NoName';
if PropInfo <> nil then
AObjName := GetStrProp(Item, PropInfo);
AObjClass := PTypeInfo(Item.ClassInfo).Name;
if AObjClass = 'TFont' then
AObjName := 'NoName';
AObjSize := IntToStr(TypeData.ClassType.InstanceSize);
AObjUnit := TypeData.UnitName;
end
else
IsClass := False;
end;
except
IsClass := False;
end;
Result := IsClass;
end;
function MemListAsXML: String;
const
CRLF = #13#10;
var
Index: Integer;
ObjAddr, ObjClass, ObjName, ObjSize, ObjUnit: ShortString;
begin
Result := '<MemList>' + CRLF;
for Index := 0 to FirstFree - 1 do
begin
if GetClassAttributes(ObjList[Index], ObjAddr, ObjClass, ObjName, ObjSize, ObjUnit) then
begin
Result := Result + ' <Object Name="' + ObjName + '" Class="' + ObjClass + '">' + CRLF;
Result := Result + ' <Address>' + ObjAddr + '</Address>' + CRLF;
Result := Result + ' <Size>' + ObjSize + '</Size>' + CRLF;
Result := Result + ' <Unit>' + ObjUnit + '</Unit>' + CRLF;
Result := Result + ' </Object>' + CRLF;
end;
end;
Result := Result + '</MemList>' + CRLF;
end;
procedure WriteMemListToLogFile;
var
LogFileName: ShortString;
LogFile: TextFile;
begin
LogFileName := ExtractFilePath(ParamStr(0));
AssignFile(LogFile, LogFileName + 'MemList.xml');
try
Rewrite(LogFile);
Write(LogFile, MemListAsXML);
finally
CloseFile(LogFile);
end;
end;
function MemObject(Index: Integer): TObject;
begin
Result := nil;
if Index < FirstFree then
Result := TObject(ObjList[Index]);
end;
function MemObjectCount: Integer;
begin
Result := FirstFree;
end;
procedure AddPointer(P: Pointer);
begin
if FirstFree >= Length(ObjList) then
MessageBox(0, 'ObjectList is full', 'caMemory', MB_OK)
else
begin
Inc(FirstFree);
ObjList[FirstFree] := P;
end;
end;
procedure DeletePointer(P: Pointer);
var
Index: Integer;
begin
for Index := 0 to FirstFree - 1 do
begin
if ObjList[Index] = P then
begin
Dec(FirstFree);
Move(ObjList[Index + 1], ObjList[Index], (FirstFree - Index) * SizeOf(Pointer));
Break;
end;
end;
end;
var
DefaultMemoryManager: TMemoryManager;
function EnhGetMem(Size: Integer): Pointer;
begin
Result := DefaultMemoryManager.GetMem(Size);
AddPointer(Result);
end;
function EnhFreeMem(P: Pointer): Integer;
begin
Result := DefaultMemoryManager.FreeMem(P);
DeletePointer(P);
end;
function EnhReallocMem(P: Pointer; Size: Integer): Pointer;
begin
Result := DefaultMemoryManager.ReallocMem(P, Size);
DeletePointer(P);
AddPointer(Result);
end;
var
EnhancedMemoryManager: TMemoryManager =
(GetMem: EnhGetMem;
FreeMem: EnhFreeMem;
ReallocMem: EnhReallocMem);
procedure InitializeMemoryManager;
begin
GetMemoryManager(DefaultMemoryManager);
SetMemoryManager(EnhancedMemoryManager);
end;
procedure FinalizeMemoryManager;
begin
SetMemoryManager(DefaultMemoryManager);
WriteMemListToLogFile;
end;
initialization
InitializeMemoryManager;
finalization
FinalizeMemoryManager;
end.
|
PROGRAM AreaCode;
TYPE
ACArray = ARRAY[0..999] OF String[50];
VAR
AC : ACArray;
PROCEDURE AssignACs;
VAR
n : WORD;
BEGIN
FOR n := 0 TO 999 DO
AC[n] := 'NV';
AC [205] := 'Alabama';
AC [907] := 'Alaska';
AC [602] := 'Arizona';
AC [501] := 'Arkansas';
AC [213] := 'Los Angeles CA';
AC [209] := 'central California';
AC [415] := 'California - greater San Francisco area';
AC [408] := 'California - south of San Franscisco';
AC [707] := 'northwestern California';
AC [714] := 'California - south of Los Angeles';
AC [805] := 'California - north of Los Angeles';
AC [818] := 'California - greater Los Angeles area';
AC [916] := 'northeastern California';
AC [619] := 'southern and eastern California';
AC [303] := 'northern Colorado';
AC [719] := 'southern Colorado';
AC [203] := 'Connecticut';
AC [302] := 'Delaware';
AC [202] := 'Washington DC';
AC [305] := 'southern Florida Atlantic coast';
AC [813] := 'southern Florida Gulf coast';
AC [904] := 'northern Florida both coast';
AC [404] := 'northern Georgia';
AC [912] := 'south Georgia';
AC [808] := 'Hawaii';
AC [208] := 'Idaho';
AC [217] := 'central Illinois';
AC [309] := 'west central Illinois';
AC [312] := 'northeast Illinois';
AC [618] := 'southern Illinois';
AC [219] := 'northern Indiana';
AC [317] := 'central Indiana';
AC [812] := 'southern Indiana';
AC [319] := 'eastern Iowa';
AC [515] := 'central Iowa';
AC [712] := 'western Iowa';
AC [316] := 'southern Kansas';
AC [913] := 'northern Kansas';
AC [502] := 'western Kentucky';
AC [606] := 'eastern Kentucky';
AC [318] := 'southeastern Louisiana';
AC [504] := 'western Louisiana';
AC [207] := 'Maine';
AC [301] := 'Maryland';
AC [413] := 'western Massachusetts';
AC [617] := 'eastern Massachusetts';
AC [313] := 'east Michigan';
AC [517] := 'east central Michigan';
AC [616] := 'west central Michigan';
AC [906] := 'western Michigan';
AC [507] := 'southern Minnesota';
AC [612] := 'south central Minnesota';
AC [218] := 'northern Minnesota';
AC [601] := 'Mississippi';
AC [314] := 'southeastern Missouri';
AC [417] := 'southwestern Missouri';
AC [816] := 'northern Missouri';
AC [406] := 'Montana';
AC [308] := 'western Nebraska';
AC [402] := 'eastern Nebraska';
AC [702] := 'Nevada';
AC [603] := 'New Hampshire';
AC [201] := 'northern New Jersey';
AC [908] := 'central New Jersey';
AC [609] := 'southern New Jersey';
AC [505] := 'New Mexico';
AC [212] := 'New York City - Manhattan / Bronx';
AC [315] := 'north central New York';
AC [516] := 'Long Island NY';
AC [518] := 'northeastern New York';
AC [607] := 'south central New York';
AC [716] := 'western New York';
AC [718] := 'New York City - Brooklyn/Queens/Staten Isle';
AC [914] := 'southern New York';
AC [704] := 'western North Carolina';
AC [919] := 'eastern North Carolina';
AC [701] := 'North Dakota';
AC [216] := 'northeastern Ohio';
AC [419] := 'northwestern Ohio';
AC [513] := 'southwestern Ohio';
AC [614] := 'southeastern Ohio';
AC [405] := 'west and southeast Oklahoma';
AC [918] := 'northeastern Oklahoma';
AC [503] := 'Oregon';
AC [215] := 'southeastern Pennsylvania';
AC [412] := 'southwestern Pennsylvania';
AC [717] := 'east central Pennsylvania';
AC [814] := 'west central Pennsylvania';
AC [401] := 'Rhode Island';
AC [803] := 'South Carolina';
AC [605] := 'South Dakota';
AC [615] := 'central and east Tennessee';
AC [901] := 'western Tennessee';
AC [214] := 'northeastern Texas';
AC [512] := 'south Texas';
AC [713] := 'Texas - greater Houston area';
AC [903] := 'Texas - greater Dallas area';
AC [806] := 'northern Texas panhandle area';
AC [817] := 'north central Texas';
AC [915] := 'southwestern Texas';
AC [801] := 'Utah';
AC [802] := 'Vermont';
AC [703] := 'northern and western Virginia';
AC [804] := 'southeastern Virginia';
AC [206] := 'western Washington';
AC [509] := 'eastern Washington';
AC [304] := 'West Virginia';
AC [414] := 'east Wisconsin';
AC [608] := 'southwestern Wisconsin';
AC [715] := 'northern Wisconsin';
AC [307] := 'Wyoming';
AC [809] := 'US Territories - Virgin Isles/Bahamas/PR';
AC [403] := 'Alberta Canada';
AC [604] := 'British Columbia Canada';
AC [204] := 'Manitoba Canada';
AC [506] := 'New Brunswick Canada';
AC [709] := 'Newfoundland Canada';
AC [902] := 'Nova Scotia and Pr. Edward Isl. Canada';
AC [807] := 'Fort William - Ontario Canada';
AC [519] := 'London - Ontario Canada';
AC [705] := 'North Bay - Ontario Canada';
AC [613] := 'Ottawa - Ontario Canada';
AC [807] := 'Thunder Bay - Ontario Canda';
AC [416] := 'Toronto - Ontario Canada';
AC [514] := 'Montreal - Quebec Canada';
AC [418] := 'Quebec - Quebec Canada';
AC [819] := 'Sherbrooke - Quebec Canada';
AC [306] := 'Saskatchewan Canada';
AC [684] := 'American Samoa';
AC [54 ] := 'Argentina';
AC [61 ] := 'Australia';
AC [43 ] := 'Austria';
AC [973] := 'Bahrain';
AC [32 ] := 'Belgium';
AC [591] := 'Bolivia';
AC [55 ] := 'Brazil';
AC [237] := 'Cameroon';
AC [56 ] := 'Chile';
AC [57 ] := 'Columbia';
AC [357] := 'Cyprus';
AC [42 ] := 'Czechoslovakia';
AC [45 ] := 'Denmark';
AC [593] := 'Ecuador';
AC [20 ] := 'Egypt';
AC [251] := 'Ethiopia';
AC [679] := 'Fiji';
AC [358] := 'Finland';
AC [33 ] := 'France';
AC [596] := 'French Antilles';
AC [689] := 'French Polynesia';
AC [241] := 'Gabon';
AC [37 ] := 'German Democratic Republic';
AC [49 ] := 'Federal Republic of Germany';
AC [30 ] := 'Greece';
AC [671] := 'Guam';
AC [53 ] := 'Guantanamo Bay';
AC [592] := 'Guyana';
AC [852] := 'Hong Kong';
AC [36 ] := 'Hungary';
AC [354] := 'Iceland';
AC [91 ] := 'India';
AC [62 ] := 'Indonesia';
AC [98 ] := 'Iran';
AC [964] := 'Iraq';
AC [353] := 'Ireland';
AC [972] := 'Israel';
AC [39 ] := 'Italy';
AC [225] := 'Ivory Coast';
AC [81 ] := 'Japan';
AC [962] := 'Jordon';
AC [254] := 'Kenya';
AC [82 ] := 'Republic of Korea';
AC [965] := 'Kuwait';
AC [231] := 'Liberia';
AC [352] := 'Luxembourg';
AC [265] := 'Malawi';
AC [60 ] := 'Malaysia';
AC [52 ] := 'Mexico';
AC [264] := 'Namibia';
AC [31 ] := 'Netherlands';
AC [599] := 'Nethrlands Antilles';
AC [687] := 'New Caledonia';
AC [64 ] := 'New Zealand';
AC [234] := 'Nigeria';
AC [47 ] := 'Norway';
AC [968] := 'Oman';
AC [92 ] := 'Pakistan';
AC [675] := 'Papua New Guinea';
AC [595] := 'Paraquay';
AC [51 ] := 'Peru';
AC [63 ] := 'Philippines';
AC [48 ] := 'Poland';
AC [351] := 'Portugal';
AC [974] := 'Qatar';
AC [40 ] := 'Romania';
AC [670] := 'Saipan';
AC [966] := 'Saudia Arabia';
AC [221] := 'Senegal';
AC [65 ] := 'Singapore';
AC [27 ] := 'South Africa';
AC [34 ] := 'Spain';
AC [94 ] := 'Sri Lanka';
AC [597] := 'Suriname';
AC [46 ] := 'Sweden';
AC [41 ] := 'Switzerland';
AC [886] := 'Taiwan';
AC [66 ] := 'Thailand';
AC [90 ] := 'Turkey';
AC [971] := 'United Arab Emirates';
AC [44 ] := 'United Kingdom';
AC [598] := 'Uruguay';
AC [58 ] := 'Venezuela';
AC [967] := 'Yemen Arab Republic';
AC [38 ] := 'Yugoslavia';
END;
PROCEDURE ShowHelp;
BEGIN
writeln('Displays location of Area Code or Area Code for location');
writeln('usage: AREACODE <number or location>');
END;
PROCEDURE SearchByAreaCode(ACNum : WORD);
BEGIN
IF ACNum > 999 THEN
Writeln('You must a number less than 999')
ELSE
BEGIN
AssignACs;
IF AC[ACNum] = 'NV' THEN
Writeln(ACNum, ' is not an actual Area Code')
ELSE
Writeln(ACNum,' is in ',AC[ACNum]);
END;
END {SearchByAreaCode};
PROCEDURE SearchByLocation(lstr : STRING);
VAR
found : BOOLEAN;
i, n : WORD;
BEGIN
AssignACs;
found := FALSE;
{
FOR i := 1 to Length(lstr) DO
lstr[i] := UpCase(lstr[i]);
}
lstr[1] := upcase(lstr[1]);
FOR n := 0 TO 999 DO
IF NOT (AC[n] = 'NV') AND (pos(lstr,AC[n]) > 0) THEN
BEGIN
writeln(AC[n],' is',n:4);
found := TRUE;
END;
IF not found THEN
writeln('No match found for ',lstr);
END {SearchByLocation};
VAR
err : INTEGER;
ACNum : WORD;
BEGIN
IF paramcount = 0 THEN
BEGIN
ShowHelp;
HALT;
END;
val(paramstr(1),ACNum,err);
IF err > 0 THEN
SearchByLocation(paramstr(1))
ELSE
SearchByAreaCode(ACNum);
END. |
unit bcrypt;
(*************************************************************************
DESCRIPTION : bcrypt password hashing
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
REMARKS : - Only version $2a$ is supported
- Passwords in BStrings should be UTF-8 encoded
REFERENCES : - http://www.usenix.org/event/usenix99/provos/provos.pdf
- http://www.openbsd.org/papers/bcrypt-paper.ps
- Damien Miller's Java implementation jBCrypt-0.3 from
http://www.mindrot.org/projects/jBCrypt/
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 15.10.13 W.Ehrhardt Expandkey, EksBlowfishSetup, CryptRaw
0.11 16.10.13 we encode_bsdbase64
0.12 16.10.13 we BFC_MakeDigest
0.13 17.10.13 we decode_bsdbase64
0.14 17.10.13 we D12+ string adjustments
0.15 18.10.13 we BFC_VerifyPassword
0.16 19.10.13 we BFC_Selftest
0.17 19.10.13 we bcrypt unit
0.18 20.10.13 we selftest level parameter
0.19 20.10.13 we All-in-one BFC_HashPassword
0.20 20.10.13 we TP5-6 const adjustments
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2013 Wolfgang Ehrhardt
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.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes, bf_base;
type
TBCDigest = packed array[0..23] of byte;
TBCSalt = packed array[0..15] of byte;
TBCKey = packed array[0..55] of byte;
const
BF_Err_Invalid_Cost = -32; {Cost factor not in [4..31]}
BF_Err_Invalid_Hash = -33; {Invalid hash format}
BF_Err_Verify_failed = -34; {Password verification failed}
{$ifdef CONST}
function BFC_HashPassword(const password: Bstring; const salt: TBCSalt; cost: integer; var HashStr: BString): integer;
{-Compute formatted bcrypt hash string from password, cost, salt}
function BFC_VerifyPassword(const password: Bstring; const HashStr: BString): integer;
{-Verify password against formatted hash string, OK if result=0}
function BFC_Selftest(trace: boolean; level: integer): integer;
{-Run selftest, return failed test nbr or 0; level 0..3: run tests with cost <= 2*level + 6}
function BFC_MakeDigest(const password: Bstring; const salt: TBCSalt; cost: integer; var hash: TBCDigest): integer;
{-Get binary hash digest from salt, password/key, and cost}
function BFC_ParseStr(const HashStr: BString; var cost: integer; var salt: TBCSalt; var hash: TBCDigest): integer;
{-Parse a formatted hash string: get cost, salt, binary hash digest; result=error code}
function BFC_FormatHash(cost: integer; const salt: TBCSalt; const digest: TBCDigest): BString;
{-Get formatted hash string from cost, salt, and binary hash digest}
{$else}
function BFC_HashPassword(password: Bstring; var salt: TBCSalt; cost: integer; var HashStr: BString): integer;
{-Compute formatted bcrypt hash string from password, cost, salt}
function BFC_VerifyPassword(password: Bstring; HashStr: BString): integer;
{-Verify password against formatted hash string, OK if result=0}
function BFC_Selftest(trace: boolean; level: integer): integer;
{-Run selftest, return failed test nbr or 0; level 0..3: run tests with cost <= 2*level + 6}
function BFC_MakeDigest(password: Bstring; var salt: TBCSalt; cost: integer; var hash: TBCDigest): integer;
{-Get binary hash digest from salt, password/key, and cost}
function BFC_ParseStr(HashStr: BString; var cost: integer; var salt: TBCSalt; var hash: TBCDigest): integer;
{-Parse a formatted hash string: get cost, salt, binary hash digest; result=error code}
function BFC_FormatHash(cost: integer; var salt: TBCSalt; var digest: TBCDigest): BString;
{-Get formatted hash string from cost, salt, and binary hash digest}
{$endif}
implementation
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function Expandkey(var ctx: TBFContext; const salt: TBCSalt; const key; len: integer): integer;
{$else}
function Expandkey(var ctx: TBFContext; var salt: TBCSalt; var key; len: integer): integer;
{$endif}
{-Expensive key setup for Blowfish}
var
i,j,k,h: integer;
KL: longint;
tmp: TBFBlock;
var
KB: packed array[0..71] of byte absolute key;
begin
if (len<1) or (len > 56) then begin
Expandkey := BF_Err_Invalid_Key_Size;
exit;
end
else Expandkey := 0;
{Text explanations and comments are from the N.Provos & D.Mazieres paper.}
{ExpandKey(state,salt,key) modifies the P-Array and S-boxes based on the }
{value of the 128-bit salt and the variable length key. First XOR all the}
{subkeys in the P-array with the encryption key. The first 32 bits of the}
{key are XORed with P1, the next 32 bits with P2, and so on. The key is }
{viewed as being cyclic; when the process reaches the end of the key, it }
{starts reusing bits from the beginning to XOR with subkeys. }
{WE: Same as standard key part except that PArray[i] is used for _bf_p[i]}
k := 0;
for i:=0 to 17 do begin
KL := 0;
for j:=0 to 3 do begin
KL := (KL shl 8) or KB[k];
inc(k);
if k=len then k:=0;
end;
ctx.PArray[i] := ctx.PArray[i] xor KL;
end;
{Subsequently, ExpandKey blowfish-encrypts the first 64 bits of}
{its salt argument using the current state of the key schedule.}
BF_Encrypt(ctx, PBFBlock(@salt[0])^, tmp);
{The resulting ciphertext replaces subkeys P_1 and P_2.}
ctx.PArray[0] := RB(TBF2Long(tmp).L);
ctx.PArray[1] := RB(TBF2Long(tmp).R);
{That same ciphertext is also XORed with the second 64-bits of }
{salt, and the result encrypted with the new state of the key }
{schedule. The output of the second encryption replaces subkeys}
{P_3 and P_4. It is also XORed with the first 64-bits of salt }
{and encrypted to replace P_5 and P_6. The process continues, }
{alternating between the first and second 64 bits salt. }
h := 8;
for i:=1 to 8 do begin
BF_XorBlock(tmp, PBFBlock(@salt[h])^, tmp);
h := h xor 8;
BF_Encrypt(ctx, tmp, tmp);
ctx.PArray[2*i] := RB(TBF2Long(tmp).L);
ctx.PArray[2*i+1] := RB(TBF2Long(tmp).R);
end;
{When ExpandKey finishes replacing entries in the P-Array, it continues}
{on replacing S-box entries two at a time. After replacing the last two}
{entries of the last S-box, ExpandKey returns the new key schedule. }
for j:=0 to 3 do begin
for i:=0 to 127 do begin
BF_XorBlock(tmp, PBFBlock(@salt[h])^, tmp);
h := h xor 8;
BF_Encrypt(ctx, tmp, tmp);
ctx.SBox[j, 2*i] := RB(TBF2Long(tmp).L);
ctx.SBox[j, 2*i+1]:= RB(TBF2Long(tmp).R);
end;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function EksBlowfishSetup(var ctx: TBFContext; const salt: TBCSalt; const key: TBCKey; klen, cost: integer): integer;
{$else}
function EksBlowfishSetup(var ctx: TBFContext; var salt: TBCSalt; var key: TBCKey; klen, cost: integer): integer;
{$endif}
{-Expensive key schedule for Blowfish}
var
i,rounds: longint;
err: integer;
const
zero: TBCSalt = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);
begin
if (cost<4) or (cost>31) then begin
EksBlowfishSetup := BF_Err_Invalid_Cost;
exit;
end;
{number of rounds = 2^cost, loop includes 0}
if cost=31 then rounds := MaxLongint
else rounds := (longint(1) shl cost) - 1;
{Just copy the boxes into the context}
BF_InitState(ctx);
err := ExpandKey(ctx, salt, key, klen);
EksBlowfishSetup := err;
if err<>0 then exit;
{This is the time consuming part}
for i:=rounds downto 0 do begin
err := ExpandKey(ctx, zero, key, klen);
if err=0 then err := ExpandKey(ctx, zero, salt, 16);
if err<>0 then begin
EksBlowfishSetup := err;
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function CryptRaw(const salt: TBCSalt; const key: TBCKey; klen, cost: integer; var digest: TBCDigest): integer;
{$else}
function CryptRaw(var salt: TBCSalt; var key: TBCKey; klen, cost: integer; var digest: TBCDigest): integer;
{$endif}
{-Raw bcrypt function: get binary hash digest from salt, key, and cost}
var
i, err: integer;
ctx: TBFContext;
const
ctext: TBCDigest = ($4F,$72,$70,$68,$65,$61,$6E,$42, {'OrpheanBeholderScryDoubt'}
$65,$68,$6F,$6C,$64,$65,$72,$53,
$63,$72,$79,$44,$6F,$75,$62,$74);
begin
{Expensive key schedule for Blowfish}
err := EksBlowfishSetup(ctx,salt,key,klen,cost);
CryptRaw := err;
if err<>0 then exit;
digest := ctext;
{Encrypt the magic initialisation text 64 times using ECB mode}
for i:=1 to 64 do begin
{could be replaced with one call to BF_ECB_Encrypt from unit BF_ECB}
BF_Encrypt(ctx, PBFBlock(@digest[ 0])^, PBFBlock(@digest[ 0])^);
BF_Encrypt(ctx, PBFBlock(@digest[ 8])^, PBFBlock(@digest[ 8])^);
BF_Encrypt(ctx, PBFBlock(@digest[16])^, PBFBlock(@digest[16])^);
CryptRaw := err;
if err<>0 then exit;
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function BFC_MakeDigest(const password: Bstring; const salt: TBCSalt; cost: integer; var hash: TBCDigest): integer;
{$else}
function BFC_MakeDigest(password: Bstring; var salt: TBCSalt; cost: integer; var hash: TBCDigest): integer;
{$endif}
{-Get binary hash digest from salt, password/key, and cost}
var
key: TBCKey;
len: Integer;
begin
len := length(password);
if len > 55 then len := 55;
if len > 0 then Move(Password[1], key[0], len);
key[len] := 0;
BFC_MakeDigest := CryptRaw(salt, key, len+1, cost, hash);
end;
{---------------------------------------------------------------------------}
function encode_bsdbase64(psrc: pointer; len: integer): BString;
{-BSD type base64 string from memory block of length len pointed by psrc}
const
CT64: array[0..63] of char8 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var
c1,c2: word;
bs: BString;
begin
bs := '';
if psrc<>nil then begin
while len>0 do begin
c1 := pByte(psrc)^; inc(Ptr2Inc(psrc)); dec(len);
bs := bs + CT64[(c1 shr 2) and $3f];
c1 := (c1 and $03) shl 4;
if len<=0 then bs := bs + CT64[c1 and $3f]
else begin
c2 := pByte(psrc)^; inc(Ptr2Inc(psrc)); dec(len);
c1 := c1 or ((c2 shr 4) and $0f);
bs := bs + CT64[c1 and $3f];
c1 := (c2 and $0f) shl 2;
if len<=0 then bs := bs + CT64[c1 and $3f]
else begin
c2 := pByte(psrc)^; inc(Ptr2Inc(psrc)); dec(len);
c1 := c1 or ((c2 shr 6) and $03);
bs := bs + CT64[c1 and $3f] + CT64[c2 and $3f];
end;
end;
end;
end;
encode_bsdbase64 := bs;
end;
{---------------------------------------------------------------------------}
procedure decode_bsdbase64(psrc,pdest: pointer; lsrc,ldest: integer; var LA: integer);
{-Decode lsrc chars from psrc, write to pdest max ldest bytes, LA bytes deocoded}
const
BT: array[#0..#127] of shortint = (
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1,
-1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, -1, -1, -1, -1, -1,
-1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1);
function getc: integer;
{-Get next char from psrc, convert to integer, dec lsrc, inc psrc}
var
c: char8;
begin
getc := -1;
if lsrc>0 then begin
c := pchar8(psrc)^;
inc(Ptr2Inc(psrc));
dec(lsrc);
if ord(c)<128 then getc := BT[c];
end;
end;
procedure putb(b: integer);
{-Put next byte into pdest if LA<ldest, inc LA and pdest}
begin
if LA<ldest then begin
inc(LA);
pByte(pdest)^ := byte(b and $ff);
inc(Ptr2Inc(pdest));
end;
end;
var
c1,c2,c3,c4: integer;
begin
LA := 0;
if (psrc=nil) or (pdest=nil) or (ldest<1) or (lsrc<1) then exit;
while lsrc>0 do begin
c1 := getc; if c1<0 then exit;
c2 := getc; if c2<0 then exit;
putb(((c1 and $3f) shl 2) or (c2 shr 4));
c3 := getc; if c3<0 then exit;
putb(((c2 and $0f) shl 4) or (c3 shr 2));
c4 := getc; if c4<0 then exit;
putb(((c3 and $03) shl 6) or c4);
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function BFC_FormatHash(cost: integer; const salt: TBCSalt; const digest: TBCDigest): BString;
{$else}
function BFC_FormatHash(cost: integer; var salt: TBCSalt; var digest: TBCDigest): BString;
{$endif}
{-Get formatted hash string from cost, salt, and binary hash digest}
var
sh: Bstring;
begin
BFC_FormatHash := '';
if (cost<4) or (cost>31) then exit;
{$ifdef D12Plus}
sh := BString('$2a$');
{$else}
sh := '$2a$';
{$endif}
sh := sh + char8(ord('0')+cost div 10)+char8(ord('0')+cost mod 10) + '$';
sh := sh + encode_bsdbase64(@salt, sizeof(salt))
+ encode_bsdbase64(@digest, sizeof(digest) - 1); {Note the -1!!!!!}
BFC_FormatHash := sh;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function BFC_HashPassword(const password: Bstring; const salt: TBCSalt; cost: integer; var HashStr: BString): integer;
{$else}
function BFC_HashPassword(password: Bstring; var salt: TBCSalt; cost: integer; var HashStr: BString): integer;
{$endif}
{-Compute formatted bcrypt hash string from password, cost, salt}
var
hash: TBCDigest;
err: integer;
begin
err := BFC_MakeDigest(password, salt, cost, hash);
BFC_HashPassword := err;
if err<>0 then HashStr := ''
else HashStr := BFC_FormatHash(cost, salt, hash);
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function BFC_ParseStr(const HashStr: BString; var cost: integer; var salt: TBCSalt; var hash: TBCDigest): integer;
{$else}
function BFC_ParseStr(HashStr: BString; var cost: integer; var salt: TBCSalt; var hash: TBCDigest): integer;
{$endif}
{-Parse a formatted hash string: get cost, salt, binary hash digest; result=error code}
var
LA: integer;
d0,d1: integer;
begin
{ 123456789012345678901234567890123456789012345678901234567890
$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q
1234567890123456789012
1234567890123456789012345678901}
BFC_ParseStr := BF_Err_Invalid_Hash;
if length(HashStr)<>60 then exit;
if (HashStr[1]<>'$') or (HashStr[4]<>'$') or (HashStr[7]<>'$') then exit;
if (HashStr[2]<>'2') or (HashStr[3]<>'a') then exit;
decode_bsdbase64(@HashStr[8], @salt[0], 22, sizeof(salt),LA);
if LA<>sizeof(salt) then exit;
decode_bsdbase64(@HashStr[30], @hash[0], 31, sizeof(hash),LA);
if LA<>sizeof(hash)-1 then exit;
d0 := ord(HashStr[6])-48;
d1 := ord(HashStr[5])-48;
cost := 10*d1+d0;
if (d1<0) or (d1>9) or (d1<0) or (d1>3) or (cost<4) or (cost>31) then begin
BFC_ParseStr := BF_Err_Invalid_Cost;
end
else BFC_ParseStr := 0;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function BFC_VerifyPassword(const password: Bstring; const HashStr: BString): integer;
{$else}
function BFC_VerifyPassword(password: Bstring; HashStr: BString): integer;
{$endif}
{-Verify password against formatted hash string, OK if result=0}
var
cost,err: integer;
salt: TBCSalt;
digest: TBCDigest;
NewHashStr: BString;
begin
err := BFC_ParseStr(HashStr,cost,salt,digest);
if err<>0 then begin
BFC_VerifyPassword := err;
exit;
end;
err := BFC_MakeDigest(password, salt, cost, digest);
if err<>0 then begin
BFC_VerifyPassword := err;
exit;
end;
NewHashStr := BFC_FormatHash(cost, salt, digest);
if NewHashStr<>HashStr then begin
BFC_VerifyPassword := BF_Err_Verify_failed;
exit;
end
else BFC_VerifyPassword := 0;
end;
{-------------------------------------------------------------------------}
{ Test vectors are from Damien Miller's Java implementation jBCrypt-0.3: }
{ Copyright (c) 2006 Damien Miller <djm@mindrot.org> }
{ }
{ Permission to use, copy, modify, and distribute this software for any }
{ purpose with or without fee is hereby granted, provided that the above }
{ copyright notice and this permission notice appear in all copies. }
{ }
{ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES}
{ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF }
{ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR }
{ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES }
{ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN }
{ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF }
{ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. }
{---------------------------------------------------------------------------}
function BFC_Selftest(trace: boolean; level: integer): integer;
{-Run selftest, return failed test nbr or 0; level 0..3: run tests with cost <= 2*level + 6}
type
TPair = record
pn: byte;
bs: string[60];
end;
const
PW: array[0..4] of string[40] = ('', 'a', 'abc',
'abcdefghijklmnopqrstuvwxyz', '~!@#$%^&*() ~!@#$%^&*()PNBFRD');
const
test: array[1..20] of TPair = (
(pn: 0; bs: '$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s.'),
(pn: 0; bs: '$2a$08$HqWuK6/Ng6sg9gQzbLrgb.Tl.ZHfXLhvt/SgVyWhQqgqcZ7ZuUtye'),
(pn: 0; bs: '$2a$10$k1wbIrmNyFAPwPVPSVa/zecw2BCEnBwVS2GbrmgzxFUOqW9dk4TCW'),
(pn: 0; bs: '$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO'),
(pn: 1; bs: '$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe'),
(pn: 1; bs: '$2a$08$cfcvVd2aQ8CMvoMpP2EBfeodLEkkFJ9umNEfPD18.hUF62qqlC/V.'),
(pn: 1; bs: '$2a$10$k87L/MF28Q673VKh8/cPi.SUl7MU/rWuSiIDDFayrKk/1tBsSQu4u'),
(pn: 1; bs: '$2a$12$8NJH3LsPrANStV6XtBakCez0cKHXVxmvxIlcz785vxAIZrihHZpeS'),
(pn: 2; bs: '$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i'),
(pn: 2; bs: '$2a$08$Ro0CUfOqk6cXEKf3dyaM7OhSCvnwM9s4wIX9JeLapehKK5YdLxKcm'),
(pn: 2; bs: '$2a$10$WvvTPHKwdBJ3uk0Z37EMR.hLA2W6N9AEBhEgrAOljy2Ae5MtaSIUi'),
(pn: 2; bs: '$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q'),
(pn: 3; bs: '$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC'),
(pn: 3; bs: '$2a$08$aTsUwsyowQuzRrDqFflhgekJ8d9/7Z3GV3UcgvzQW3J5zMyrTvlz.'),
(pn: 3; bs: '$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq'),
(pn: 3; bs: '$2a$12$D4G5f18o7aMMfwasBL7GpuQWuP3pkrZrOAnqP.bmezbMng.QwJ/pG'),
(pn: 4; bs: '$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO'),
(pn: 4; bs: '$2a$08$Eq2r4G/76Wv39MzSX262huzPz612MZiYHVUJe/OcOql2jo4.9UxTW'),
(pn: 4; bs: '$2a$10$LgfYWkbzEvQ4JakH7rOvHe0y8pHKF9OaFgwUZ2q7W2FFZmZzJYlfS'),
(pn: 4; bs: '$2a$12$WApznUOJfkEGSmYRfnkrPOr466oFDCaj4b6HY3EXGvfxm43seyhgC'));
var
i: integer;
begin
for i:=1 to 20 do begin
if (i-1) and 3 < level then begin
if trace then write('.');
if BFC_VerifyPassword(PW[test[i].pn], test[i].bs)<>0 then begin
BFC_Selftest := i;
exit;
end;
end;
end;
BFC_Selftest := 0;
end;
end.
|
unit TestCapture;
interface
{$include rtcDefs.inc}
{$include rtcDeploy.inc}
uses
Windows, Messages, SysUtils, Variants, Dialogs,
Classes, Graphics, Controls, Forms,
ExtCtrls, ComCtrls, StdCtrls, Buttons,
rtcTypes,
rtcInfo,
rtcXScreenUtils,
rtcVScreenUtilsWin,
rtcXBmpUtils,
rtcXImgEncode,
rtcXImgDecode,
rtcXJPEGConst,
rtcVBmpUtils,
rtcBlankOutForm;
type
TForm1 = class(TForm)
MainPanel: TPanel;
eQualityLum: TTrackBar;
mot1Line4a: TLabel;
mot1Line2a: TLabel;
mot1Line3a: TLabel;
mot1LineKb: TLabel;
mot1Line4: TLabel;
mot1Line4b: TLabel;
Bevel1: TBevel;
Bevel2: TBevel;
Bevel3: TBevel;
Label1: TLabel;
xLZW: TCheckBox;
xHQColor: TCheckBox;
eHQDepth: TTrackBar;
eQualityCol: TTrackBar;
Label2: TLabel;
CaptureTimer: TTimer;
Bevel6: TBevel;
Bevel7: TBevel;
Bevel4: TBevel;
lblScreenInfo: TLabel;
xAllMonitors: TCheckBox;
PaintTimer: TTimer;
xBandwidth: TComboBox;
xMirrorDriver: TCheckBox;
xWinAero: TCheckBox;
eMotionVert: TTrackBar;
eMotionHorz: TTrackBar;
eMotionFull: TTrackBar;
Label3: TLabel;
Bevel10: TBevel;
jpgLineKb: TLabel;
jpgLine2a: TLabel;
jpgLine3a: TLabel;
jpgLine4a: TLabel;
jpgLine4b: TLabel;
jpgLine4: TLabel;
rleLineKb: TLabel;
rleLine2a: TLabel;
rleLine3a: TLabel;
rleLine4a: TLabel;
rleLine4b: TLabel;
rleLine4: TLabel;
totLineKb: TLabel;
totLine2a: TLabel;
totLine3a: TLabel;
totLine4a: TLabel;
totLine4b: TLabel;
totLine4: TLabel;
Bevel11: TBevel;
capLine2a: TLabel;
capLine4a: TLabel;
capLine4: TLabel;
eColorDepth: TTrackBar;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
Label8: TLabel;
capLineKb: TLabel;
capLine3a: TLabel;
capLine4b: TLabel;
SubPanel: TPanel;
btnCapture: TSpeedButton;
xConfig: TCheckBox;
xMotionDebug: TCheckBox;
totLine5: TLabel;
UpdateTimer: TTimer;
xSplitData: TCheckBox;
xMaintenanceForm: TCheckBox;
xLayeredWindows: TCheckBox;
ScrollBox1: TScrollBox;
PaintBox1: TPaintBox;
xColorReduceReal: TCheckBox;
xMotionComp1: TCheckBox;
xColorComp: TCheckBox;
xJPG: TCheckBox;
xRLE: TCheckBox;
Bevel5: TBevel;
eWindowCaption: TComboBox;
xCaptureFrame: TCheckBox;
xAutoHide: TCheckBox;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
procedure CaptureClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure PaintBox1Paint(Sender: TObject);
procedure CaptureTimerTimer(Sender: TObject);
procedure PaintTimerTimer(Sender: TObject);
procedure xMirrorDriverClick(Sender: TObject);
procedure xWinAeroClick(Sender: TObject);
procedure xConfigClick(Sender: TObject);
procedure UpdateTimerTimer(Sender: TObject);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure xMaintenanceFormClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure xWindowCaptureClick(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
bmp4,bmp5:TBitmap;
bmp3info:TRtcBitmapInfo;
AutoRefresh:boolean;
FrameTime,totTime,totTime2,totData:Cardinal;
ImgEncoder:TRtcImageEncoder;
ImgDecoder:TRtcImageDecoder;
compStage:integer;
OldParent:HWND;
CaptureRectLeft,
CaptureRectTop:integer;
LDown,RDown,MDown:boolean;
WinHdls:array of HWND;
function GetCaptureWindow:HWND;
procedure PostMouseMessage(Msg:Cardinal; MouseX, MouseY: integer);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.CaptureClick(Sender: TObject);
var
t0:cardinal;
capTime1,capTime2,
mot1Time,mot1Time2,mot1Data,
mot2Time,mot2Time2,mot2Data,
mot3Time,mot3Time2,mot3Data,
jpgTime,jpgTime2,jpgData,
rleTime,rleTime2,rleData,
nowData,curData:Cardinal;
newMouse:RtcByteArray;
curStorage,
mot1Storage,
mot2Storage,
mot3Storage,
jpgStorage,
rleStorage:RtcByteArray;
HqLevelLum,HqLevelCol:word;
HqDepth:byte;
btmp:TRtcBitmapInfo;
capFPS1,capFPS2,capFPS3,
mot1FPS1,mot1FPS2,mot1FPS3,
mot2FPS1,mot2FPS2,mot2FPS3,
mot3FPS1,mot3FPS2,mot3FPS3,
jpgFPS1,jpgFPS2,jpgFPS3,
rleFPS1,rleFPS2,rleFPS3,
totFPS1,totFPS2,totFPS3:double;
have_img:boolean;
CompChg:boolean;
Delay:integer;
function CalcFPS(dataSize:cardinal):double;
begin
if dataSize=0 then
Result:=99.99
else
begin
case xBandwidth.ItemIndex of
0:Result:=round(12500000/32/dataSize)/100;
1:Result:=round(12500000/16/dataSize)/100;
2:Result:=round(12500000/8/dataSize)/100;
3:Result:=round(12500000/4/dataSize)/100;
4:Result:=round(12500000/2/dataSize)/100;
5:Result:=round(12500000/dataSize)/100;
6:Result:=round(12500000/dataSize*2)/100;
7:Result:=round(12500000/dataSize*4)/100;
8:Result:=round(12500000/dataSize*8)/100;
9:Result:=round(12500000/dataSize*16)/100;
else
Result:=99.99;
end;
end;
if Result>99.99 then Result:=99.99;
end;
function CaptureWindowTo(var bmp:TRtcBitmapInfo):boolean;
var
mpt:TPoint;
rct:TRect;
hdl:HWND;
pwi:tagWINDOWINFO;
begin
hdl:=GetCaptureWindow;
if IsWindow(hdl) then
begin
if xCaptureFrame.Checked then
begin
Windows.GetWindowInfo(hdl,pwi);
CaptureRectLeft:=pwi.rcClient.Left;
CaptureRectTop:=pwi.rcClient.Top;
rct:=pwi.rcWindow;
Dec(rct.Left, pwi.rcClient.Left);
Dec(rct.Top, pwi.rcClient.Top);
Dec(rct.Right, pwi.rcClient.Left);
Dec(rct.Bottom, pwi.rcClient.Top);
{
Windows.GetWindowRect(hdl,rct);
Dec(rct.Left,CaptureRectLeft);
Dec(rct.Top,CaptureRectTop);
Dec(rct.Right,CaptureRectLeft);
Dec(rct.Bottom,CaptureRectTop);
}
Inc(CaptureRectLeft,rct.Left);
Inc(CaptureRectTop,rct.Top);
end
else
begin
mpt.X:=0;
mpt.Y:=0;
Windows.ClientToScreen(hdl,mpt);
CaptureRectLeft:=mpt.X;
CaptureRectTop:=mpt.Y;
Windows.GetClientRect(hdl,rct);
rct.Right:=rct.Right-rct.Left;
rct.Bottom:=rct.Bottom-rct.Top;
rct.Left:=0;
rct.Top:=0;
end;
Result:=WindowCapture(WinHdls[eWindowCaption.ItemIndex],rct,bmp);
end
else
Result:=False;
end;
begin
if assigned(Sender) then
begin
AutoRefresh:=not AutoRefresh;
UpdateTimer.Enabled:=AutoRefresh;
if AutoRefresh then
btnCapture.Caption:='STOP'
else
begin
btnCapture.Caption:='START';
Exit;
end;
end;
{if assigned(Sender) then
begin
CompStage:=0;
FreeAndNil(bmp4);
FreeAndNil(bmp5);
ResetBitmapInfo(bmp3Info);
FrameTime:=GetTickCount;
ImgEncoder.FirstFrame;
end;}
nowData:=0;
if CompStage=0 then
begin
totData:=0;
totTime:=0;
totTime2:=0;
// Prepare Screen capture parameters
ImgDecoder.MotionDebug:=xMotionDebug.Checked;
ImgEncoder.MotionComp:=xMotionComp1.Checked;
ImgEncoder.ColorComp:=xColorComp.Checked;
ImgEncoder.MotionHorzScan:=eMotionHorz.Position>0;
ImgEncoder.MotionVertScan:=eMotionVert.Position>0;
ImgEncoder.MotionFullScan:=eMotionFull.Position>0;
if eMotionHorz.Position>0 then
ImgEncoder.MotionHorzScanLimit:=(eMotionHorz.Position-1)*100
else
ImgEncoder.MotionHorzScanLimit:=0;
if eMotionVert.Position>0 then
ImgEncoder.MotionVertScanLimit:=(eMotionVert.Position-1)*100
else
ImgEncoder.MotionVertScanLimit:=0;
if eMotionFull.Position>0 then
ImgEncoder.MotionFullScanLimit:=(eMotionFull.Position-1)*100
else
ImgEncoder.MotionFullScanLimit:=0;
if xColorReduceReal.Checked then
begin
ImgEncoder.ColorBitsR:=eColorDepth.Position;
ImgEncoder.ColorBitsG:=eColorDepth.Position;
ImgEncoder.ColorBitsB:=eColorDepth.Position;
ImgEncoder.ColorReduce:=0;
end
else
begin
ImgEncoder.ColorBitsR:=8;
ImgEncoder.ColorBitsG:=8;
ImgEncoder.ColorBitsB:=8;
ImgEncoder.ColorReduce:=(8-eColorDepth.Position)*2;
end;
ImgEncoder.JPGCompress:=xJPG.Checked;
ImgEncoder.RLECompress:=xRLE.Checked;
ImgEncoder.LZWCompress:=xLZW.Checked;
if ImgEncoder.JPGCompress then
begin
if eHQDepth.Position>0 then
begin
HqLevelLum:=eQualityLum.Position;
HqLevelCol:=eQualityCol.Position;
end
else
begin
HqLevelLum:=0;
HqLevelCol:=0;
end;
HqDepth:=255;
case eHQDepth.Position of
2:HqDepth:=240;
3:HqDepth:=120;
4:HqDepth:=80;
5:HqDepth:=60;
end;
ImgEncoder.QLevelLum:=eQualityLum.Position;
ImgEncoder.QLevelCol:=eQualityCol.Position;
ImgEncoder.HQLevelLum:=HqLevelLum;
ImgEncoder.HQLevelCol:=HqLevelCol;
ImgEncoder.HQDepth:=HqDepth;
ImgEncoder.HQColor:=xHQColor.Checked;
end;
RtcCaptureSettings.CompleteBitmap:=True;
RtcCaptureSettings.LayeredWindows:=xLayeredWindows.Enabled and xLayeredWindows.Checked;
RtcCaptureSettings.AllMonitors:=xAllMonitors.Checked;
// Capture the Screen
t0:=GetTickCount;
capTime1:=t0;
if (ImgEncoder.OldBmpInfo.Data=nil) or
(ImgEncoder.NewBmpInfo.Data=nil) then
begin
ResetBitmapInfo(ImgEncoder.OldBmpInfo);
if eWindowCaption.ItemIndex>0 then
have_img:=CaptureWindowTo(ImgEncoder.NewBmpInfo)
else
begin
have_img:=ScreenCapture(ImgEncoder.NewBmpInfo,ImgEncoder.NeedRefresh);
CaptureRectLeft:=0;
CaptureRectTop:=0;
end;
MouseSetup;
GrabMouse;
newMouse:=CaptureMouseCursor;
end
else
begin
if eWindowCaption.ItemIndex>0 then
have_img:=CaptureWindowTo(ImgEncoder.OldBmpInfo)
else
begin
have_img:=ScreenCapture(ImgEncoder.OldBmpInfo,ImgEncoder.NeedRefresh);
CaptureRectLeft:=0;
CaptureRectTop:=0;
end;
GrabMouse;
newMouse:=CaptureMouseCursorDelta;
if have_img then
begin
btmp:=ImgEncoder.OldBmpInfo;
ImgEncoder.OldBmpInfo:=ImgEncoder.NewBmpInfo;
ImgEncoder.NewBmpInfo:=btmp;
end;
end;
if have_img then
ImgEncoder.ReduceColors(ImgEncoder.NewBmpInfo);
if length(newMouse)>0 then
begin
curStorage:=ImgEncoder.CompressMouse(newMouse);
SetLength(newMouse,0);
end
else
SetLength(curStorage,0);
curData:=length(curStorage);
t0:=GetTickCount;
capTime1:=t0-capTime1;
if capTime1<=0 then
capFPS1:=99.99
else
capFPS1:=round(100000/capTime1)/100;
capFPS2:=CalcFPS(curData);
if capFPS1<capFPS2 then
capFPS3:=capFPS1
else
capFPS3:=capFPS2;
if curData>0 then
begin
t0:=GetTickCount;
capTime2:=t0;
ImgDecoder.Decompress(curStorage,bmp3Info);
t0:=GetTickCount;
capTime2:=t0-capTime2;
end
else
capTime2:=0;
Inc(totTime,capTime1);
Inc(totData,curData);
capLineKb.Caption:=IntToStr(curData div 125)+' Kbit';
capLine2a.Caption:=IntToStr(capTime1)+' ms';
capLine3a.Caption:=IntToStr(capTime2)+' ms';
capLine4a.Caption:=Float2Str(capFPS1)+' /';
capLine4b.Caption:=Float2Str(capFPS2)+' =';
capLine4.Caption:=Float2Str(capFPS3)+' fps';
if not have_img then
begin
PaintTimerTimer(nil);
if AutoRefresh then
begin
CaptureTimer.Interval:=30;
CaptureTimer.Enabled:=True;
end;
Exit;
end
else if not ImgEncoder.BitmapChanged then
begin
PaintTimerTimer(nil);
if AutoRefresh then
begin
CaptureTimer.Interval:=30;
CaptureTimer.Enabled:=True;
end;
Exit;
end;
lblScreenInfo.Caption:=IntToStr(ImgEncoder.NewBmpInfo.Width)+' * '+IntToStr(ImgEncoder.NewBmpInfo.Height);
if xConfig.Checked then
MainPanel.Update;
if curData>0 then
begin
Inc(nowData,curData);
if not xSplitData.Checked then
Inc(CompStage);
end
else
Inc(CompStage);
end;
if CompStage=1 then
begin
// Motion compress ...
t0:=GetTickCount;
mot1Time:=t0;
mot1Storage:=ImgEncoder.CompressMOT;
mot1Data:=length(mot1Storage);
t0:=GetTickCount;
mot1Time:=t0-mot1Time;
if mot1Time<=0 then
mot1FPS1:=99.99
else
mot1FPS1:=round(100000/mot1Time)/100;
mot1FPS2:=CalcFPS(mot1Data);
if mot1FPS1<mot1FPS2 then
mot1FPS3:=mot1FPS1
else
mot1FPS3:=mot1FPS2;
if mot1Data>0 then
begin
mot1Time2:=t0;
ImgDecoder.Decompress(mot1Storage,bmp3Info);
t0:=GetTickCount;
mot1Time2:=t0-mot1Time2;
end
else
mot1Time2:=0;
mot1LineKb.Caption:=IntToStr(mot1Data div 125)+' Kbit';
mot1Line2a.Caption:=IntToStr(mot1Time)+' ms';
mot1Line3a.Caption:=IntToStr(mot1Time2)+' ms';
mot1Line4a.Caption:=Float2Str(mot1FPS1)+' /';
mot1Line4b.Caption:=Float2Str(mot1FPS2)+' =';
mot1Line4.Caption:=Float2Str(mot1FPS3)+' fps';
Inc(totData,mot1Data);
Inc(totTime,mot1Time);
Inc(totTime2,mot1Time2);
if mot1Data>0 then
begin
Inc(nowData,mot1Data);
if not xSplitData.Checked then
Inc(CompStage);
end
else
Inc(CompStage);
end;
if CompStage=2 then
begin
// JPG compress ...
t0:=GetTickCount;
jpgTime:=t0;
jpgStorage:=ImgEncoder.CompressJPG;
jpgData:=length(jpgStorage);
t0:=GetTickCount;
jpgTime:=t0-jpgTime;
if jpgTime<=0 then
jpgFPS1:=99.99
else
jpgFPS1:=round(100000/jpgTime)/100;
jpgFPS2:=CalcFPS(jpgData);
if jpgFPS1<jpgFPS2 then
jpgFPS3:=jpgFPS1
else
jpgFPS3:=jpgFPS2;
if jpgData>0 then
begin
jpgTime2:=t0;
ImgDecoder.Decompress(jpgStorage,bmp3Info);
t0:=GetTickCount;
jpgTime2:=t0-jpgTime2;
end
else
jpgTime2:=0;
jpgLineKb.Caption:=IntToStr(jpgData div 125)+' Kbit';
jpgLine2a.Caption:=IntToStr(jpgTime)+' ms';
jpgLine3a.Caption:=IntToStr(jpgTime2)+' ms';
jpgLine4a.Caption:=Float2Str(jpgFPS1)+' /';
jpgLine4b.Caption:=Float2Str(jpgFPS2)+' =';
jpgLine4.Caption:=Float2Str(jpgFPS3)+' fps';
Inc(totData,jpgData);
Inc(totTime,jpgTime);
Inc(totTime2,jpgTime2);
if jpgData>0 then
begin
Inc(nowData,jpgData);
if not xSplitData.Checked then
Inc(CompStage);
end
else
Inc(CompStage);
end;
if CompStage=3 then
begin
// RLE compress ...
t0:=GetTickCount;
rleTime:=t0;
rleStorage:=ImgEncoder.CompressRLE;
rleData:=length(rleStorage);
t0:=GetTickCount;
rleTime:=t0-rleTime;
if rleTime<=0 then
rleFPS1:=99.99
else
rleFPS1:=round(100000/rleTime)/100;
rleFPS2:=CalcFPS(rleData);
if rleFPS1<rleFPS2 then
rleFPS3:=rleFPS1
else
rleFPS3:=rleFPS2;
if rleData>0 then
begin
rleTime2:=t0;
ImgDecoder.Decompress(rleStorage,bmp3Info);
t0:=GetTickCount;
rleTime2:=t0-rleTime2;
end
else
rleTime2:=0;
rleLineKb.Caption:=IntToStr(rleData div 125)+' Kbit';
rleLine2a.Caption:=IntToStr(rleTime)+' ms';
rleLine3a.Caption:=IntToStr(rleTime2)+' ms';
rleLine4a.Caption:=Float2Str(rleFPS1)+' /';
rleLine4b.Caption:=Float2Str(rleFPS2)+' =';
rleLine4.Caption:=Float2Str(rleFPS3)+' fps';
if rleData>0 then
Inc(nowData,rleData);
// Calculate totals ...
Inc(totData,rleData);
Inc(totTime,rleTime);
Inc(totTime2,rleTime2);
if totTime<=0 then
totFPS1:=99.99
else
totFPS1:=round(100000/totTime)/100;
totFPS2:=CalcFPS(totData);
if totFPS1<totFPS2 then
totFPS3:=totFPS1
else
totFPS3:=totFPS2;
totLineKb.Caption:=IntToStr(totData div 125)+' Kbit';
totLine2a.Caption:=IntToStr(totTime)+' ms';
totLine3a.Caption:=IntToStr(totTime2)+' ms';
totLine4a.Caption:=Float2Str(totFPS1)+' /';
totLine4b.Caption:=Float2Str(totFPS2)+' =';
totLine4.Caption:=Float2Str(totFPS3)+' fps';
end;
Inc(CompStage);
if CompStage>3 then
CompStage:=0;
// Clear Screen capture buffers
SetLength(mot1Storage,0);
SetLength(mot2Storage,0);
SetLength(jpgStorage,0);
SetLength(rleStorage,0);
SetLength(curStorage,0);
if nowData=0 then
Delay:=1
else
begin
case xBandwidth.ItemIndex of
0:Delay:=8 * nowData div 32;
1:Delay:=8 * nowData div 64;
2:Delay:=8 * nowData div 128;
3:Delay:=8 * nowData div 256;
4:Delay:=8 * nowData div 512;
5:Delay:=8 * nowData div 1000;
6:Delay:=8 * nowData div 2000;
7:Delay:=8 * nowData div 4000;
8:Delay:=8 * nowData div 8000;
9:Delay:=8 * nowData div 16000;
else Delay:=1;
end;
end;
// Trigger Repaint or next Screen capture
if Delay<1 then Delay:=1;
PaintTimer.Interval:=Delay;
PaintTimer.Enabled:=True;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
{
SetWindowLong(Handle, GWL_EXSTYLE,
GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_LAYERED or
WS_EX_TRANSPARENT or WS_EX_TOPMOST);
SetLayeredWindowAttributes(Handle, 0,
Trunc((255 / 100) * (100 - 0)), LWA_ALPHA);
}
if not xConfig.Checked then
begin
MainPanel.ClientWidth:=SubPanel.Width;
MainPanel.ClientHeight:=SubPanel.Height;
end;
ClientWidth:=MainPanel.Width;
ClientHeight:=MainPanel.Height;
AutoRefresh:=False;
xWinAero.Checked:=CurrentAero;
LDown:=False;
RDown:=False;
MDown:=False;
bmp3Info:=NewBitmapInfo(True);
bmp4:=nil;
bmp5:=nil;
FrameTime:=0;
ImgEncoder:=TRtcImageEncoder.Create(NewBitmapInfo(True));
ImgDecoder:=TRtcImageDecoder.Create;
end;
(*function BitmapToJSONString(bmp:TBitmap):RtcString;
var
myRecord:TRtcRecord;
myStream:TStream;
begin
myRecord := TRtcRecord.Create;
try
myStream := myRecord.newByteStream('Image');
bmp.SaveToStream( myStream );
Result := myRecord.toJSON;
finally
myRecord.Free;
end;
end;*)
procedure TForm1.FormDestroy(Sender: TObject);
begin
//if assigned(bmp1) then
// Write_File('test.txt',BitmapToJSONString(bmp1));
FreeAndNil(bmp4);
FreeAndNil(bmp5);
ReleaseBitmapInfo(bmp3Info);
FrameTime:=0;
FreeAndNil(ImgEncoder);
FreeAndNil(ImgDecoder);
end;
procedure TForm1.PaintBox1Paint(Sender: TObject);
var
NowMousePos:TPoint;
begin
if assigned(bmp4) then
begin
PaintBox1.Width:=bmp4.Width;
PaintBox1.Height:=bmp4.Height;
// Local paint
GetCursorPos(NowMousePos);
PaintBox1.Canvas.Draw(0,0,bmp4);
PaintCursor(ImgDecoder.Cursor, PaintBox1.Canvas, bmp4, NowMousePos.X-CaptureRectLeft, NowMousePos.Y-CaptureRectTop,True);
end
else
begin
PaintBox1.Canvas.Brush.Color:=Color;
PaintBox1.Canvas.FillRect(Rect(0,0,PaintBox1.Width,PaintBox1.Height));
end;
end;
procedure TForm1.CaptureTimerTimer(Sender: TObject);
begin
CaptureTimer.Enabled:=False;
CaptureClick(nil);
end;
(*
type
TMyForcedMemLeak=class(TObject);
initialization
TMyForcedMemLeak.Create;
*)
procedure TForm1.PaintTimerTimer(Sender: TObject);
var
FramePS:double;
begin
PaintTimer.Enabled:=False;
if (CompStage=0) or xSplitData.Checked then
begin
if assigned(bmp3Info.Data) then
begin
if CompStage=0 then
begin
if FrameTime>0 then
begin
FrameTime:=GetTickCount-FrameTime;
if FrameTime>0 then
begin
FramePS:=round(100000/FrameTime)/100;
totLine5.Caption:=Float2Str(FramePS)+' fps';
end;
end;
FrameTime:=GetTickCount;
end;
CopyInfoToBitmap(bmp3Info,bmp4);
PaintBox1Paint(nil);
end;
end;
if (CompStage>0) or AutoRefresh then
begin
CaptureTimer.Interval:=1;
CaptureTimer.Enabled:=True;
end
else
UpdateTimer.Enabled:=False;
end;
procedure TForm1.xMirrorDriverClick(Sender: TObject);
begin
if xMirrorDriver.Enabled then
if xMirrorDriver.Checked then
begin
if not EnableMirrorDriver then
xMirrorDriver.Checked:=False;
end
else
DisableMirrorDriver;
end;
procedure TForm1.xWinAeroClick(Sender: TObject);
begin
if xWinAero.Enabled then
if xWinAero.Checked<>CurrentAero then
if xWinAero.Checked then
EnableAero
else
DisableAero;
end;
procedure TForm1.xConfigClick(Sender: TObject);
begin
if not xConfig.Checked then
begin
MainPanel.ClientWidth:=SubPanel.Width;
MainPanel.ClientHeight:=SubPanel.Height;
end
else
begin
MainPanel.ClientWidth:=xBandwidth.Left+xBandwidth.Width+5;
MainPanel.ClientHeight:=xBandwidth.Top+xBandwidth.Height+5;
end;
if ClientWidth<MainPanel.Width then
ClientWidth:=MainPanel.Width;
if ClientHeight<MainPanel.Height then
ClientHeight:=MainPanel.Height;
FormResize(nil);
end;
procedure TForm1.UpdateTimerTimer(Sender: TObject);
begin
PaintBox1Paint(nil);
end;
function TForm1.GetCaptureWindow:HWND;
begin
if eWindowCaption.ItemIndex>0 then
begin
Result:=WinHdls[eWindowCaption.ItemIndex];
if not IsWindowVisible(Result) then
begin
xWindowCaptureClick(nil);
eWindowCaption.ItemIndex:=0;
Result:=WinHdls[eWindowCaption.ItemIndex];
end;
end
else
Result := GetDesktopWindow;
end;
procedure TForm1.PostMouseMessage(Msg:Cardinal; MouseX, MouseY: integer);
var
chdl,
hdl:HWND;
wpt,pt:TPoint;
r:TRect;
begin
pt.X:=MouseX+CaptureRectLeft;
pt.Y:=MouseY+CaptureRectTop;
wpt:=pt;
if eWindowCaption.ItemIndex>0 then
begin
hdl:=GetCaptureWindow;
if IsWindow(hdl) then
begin
GetWindowRect(hdl,r);
repeat
pt.X:=wpt.X-r.Left;
pt.Y:=wpt.Y-r.Top;
chdl:=ChildWindowFromPointEx(hdl,pt,1+4);
if not IsWindow(chdl) then
Break
else if chdl=hdl then
Break
else
begin
GetWindowRect(chdl,r);
if (wpt.x>=r.left) and (wpt.x<=r.right) and
(wpt.y>=r.top) and (wpt.y<=r.bottom) then
hdl:=chdl
else
Break;
end;
until False;
end;
end
else
hdl:=WindowFromPoint(pt);
if IsWindow(hdl) then
begin
pt:=wpt;
Windows.ScreenToClient(hdl,pt);
{GetWindowRect(hdl,r);
pt.x:=wpt.X-r.left;
pt.y:=wpt.Y-r.Top;}
PostMessageA(hdl,msg,0,MakeLong(pt.X,pt.Y));
end;
end;
procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
case Button of
mbLeft:
begin
PostMouseMessage(WM_LBUTTONDOWN,X,Y);
LDown:=True;
end;
mbRight:
begin
PostMouseMessage(WM_RBUTTONDOWN,X,Y);
RDown:=True;
end;
mbMiddle:
begin
PostMouseMessage(WM_MBUTTONDOWN,X,Y);
MDown:=True;
end;
end;
end;
procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
case Button of
mbLeft:
begin
PostMouseMessage(WM_LBUTTONUP,X,Y);
LDown:=False;
end;
mbRight:
begin
PostMouseMessage(WM_RBUTTONUP,X,Y);
RDown:=False;
end;
mbMiddle:
begin
PostMouseMessage(WM_MBUTTONUP,X,Y);
MDown:=False;
end;
end;
end;
procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
PX,PY:integer;
begin
if AutoRefresh then
begin
PX:=X-ScrollBox1.HorzScrollBar.Position;
PY:=Y-ScrollBox1.VertScrollBar.Position;
if xAutoHide.Checked and
( (PX<MainPanel.Left) or
(PX>MainPanel.Left+MainPanel.Width) or
(PY<0) or
(PY>MainPanel.Top+MainPanel.Height) ) then
begin
if MainPanel.Visible then
MainPanel.Hide;
end
else if not MainPanel.Visible then
MainPanel.Show;
end
else if not MainPanel.Visible then
MainPanel.Show;
if LDown or RDown or MDown then
PostMouseMessage(WM_MOUSEMOVE,X,Y);
end;
procedure TForm1.xMaintenanceFormClick(Sender: TObject);
begin
if xMaintenanceForm.Checked then
begin
if (Left+ClientWidth>0) and (Top+ClientHeight>0) and (Left<GetScreenWidth) and (Top<GetScreenHeight) then
begin
xMaintenanceForm.Checked:=False;
ShowMessage('Move the Main Form to your Secondary Monitor'#13#10+
'before you enable the "Maintenance" mode.');
end
else
begin
xWinAero.Enabled:=False;
xLayeredWindows.Enabled:=False;
xMirrorDriver.Enabled:=False;
DisableMirrorDriver;
DisableAero;
BlankOutScreen(False);
WindowState:=wsMaximized;
if not AutoRefresh then
btnCapture.Click;
BringToFront;
end;
end
else if not xWinAero.Enabled then
begin
xWinAero.Enabled:=True;
xLayeredWindows.Enabled:=True;
xMirrorDriver.Enabled:=True;
if xWinAero.Checked then
EnableAero;
if xMirrorDriver.Checked then
EnableMirrorDriver;
RestoreScreen;
end;
end;
procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Key=#27) and xMaintenanceForm.Checked then
xMaintenanceForm.Checked:=False;
end;
procedure TForm1.xWindowCaptureClick(Sender: TObject);
var
desk,mh,ch:HWND;
capt:array[1..255] of Char;
caps:String;
clen,i:integer;
r:TRect;
begin
eWindowCaption.Items.Clear;
SetLength(WinHdls,0);
desk:=GetDesktopWindow;
SetLength(WinHdls,1);
WinHdls[0]:=desk;
eWindowCaption.Items.Add('Desktop');
mh:=0;
ch:=0;
repeat
ch:=FindWindowExA(mh,ch,nil,nil);
if ch<>0 then
begin
if IsWindow(ch) and IsWindowVisible(ch) and (ch<>desk) and (ch<>handle) then
begin
Windows.GetClientRect(ch,r);
if (r.Right-r.Left>0) and
(r.Bottom-r.Top>0) then
begin
Windows.GetWindowRect(ch,r);
SetLength(WinHdls,length(WinHdls)+1);
WinHdls[length(WinHdls)-1]:=ch;
clen:=GetWindowText(ch,@capt,254);
caps:='';
for i:=1 to clen do
caps:=caps+capt[i];
clen:=GetClassName(ch,@capt,254);
caps:=caps+' | ';
for i:=1 to clen do
caps:=caps+capt[i];
caps:=caps+' ('+IntToStr(r.Left)+','+IntToStr(r.Top)+
')-('+IntToStr(r.Right)+','+IntToStr(r.Bottom)+')';
eWindowCaption.Items.Add(caps);
end;
end;
end;
until ch=0;
{
mh:=desk;
ch:=0;
repeat
ch:=FindWindowExA(mh,ch,nil,nil);
if ch<>0 then
begin
if IsWindowVisible(ch) and (ch<>Handle) then
begin
Windows.GetClientRect(ch,r);
if (r.Right-r.Left>0) and
(r.Bottom-r.Top>0) then
begin
Windows.GetWindowRect(ch,r);
SetLength(WinHdls,length(WinHdls)+1);
WinHdls[length(WinHdls)-1]:=ch;
clen:=GetWindowText(ch,@capt,254);
caps:='';
for i:=1 to clen do
caps:=caps+capt[i];
clen:=GetClassName(ch,@capt,254);
caps:=caps+' | ';
for i:=1 to clen do
caps:=caps+capt[i];
caps:=caps+' ('+IntToStr(r.Left)+','+IntToStr(r.Top)+
')-('+IntToStr(r.Right)+','+IntToStr(r.Bottom)+')';
eWindowCaption.Items.Add(caps);
end;
end;
end;
until ch=0;
}
end;
procedure TForm1.FormResize(Sender: TObject);
begin
MainPanel.Left:=ClientWidth-MainPanel.Width;
end;
end.
|
uses
Math;
const
INF = MaxInt;
type
TPoint = record
x, y, angle: double;
end;
var
i, j, idx, n: integer;
points, Stack: array of TPoint;
Minim, GMinim: double;
DeletedP: TPoint;
procedure Push(P: TPoint);
begin
setlength(Stack, length(Stack) + 1);
Stack[high(Stack)] := P;
end;
procedure Pop();
begin
setlength(Stack, length(Stack) - 1);
end;
procedure swap_points(var a, b: TPoint);
var
temp: TPoint;
begin
temp := a;
a := b;
b := temp;
end;
function Rotate(A, B, C: TPoint): double;
begin
Result := (B.x - A.x) * (C.y - B.y) - (B.y - A.y) * (C.x - B.x);
end;
function Large(C: TPoint): double;
begin
Result := sqrt(sqr(C.x) + sqr(C.y));
end;
function GetAngle(i: integer): double;
var
A, B: TPoint;
begin
with A do begin
x := Stack[i].x - Stack[i-1].x;
y := Stack[i].y - Stack[i-1].y;
end;
with B do begin
x := Stack[i+1].x - Stack[i].x;
y := Stack[i+1].y - Stack[i].y;
end;
//Result := 180 - (180 * arccos((A.x*B.x + A.y*B.y) / (Large(A) * Large(B))) / Pi);
Result := arccos((A.x*B.x + A.y*B.y) / (Large(A) * Large(B)));
if Result > 3.13 then Result := 0;
end;
procedure qSort(l, r: integer);
var i, j: integer;
w: TPoint;
q: double;
begin
i := l;
j := r;
q := points[(l+r) div 2].angle;
repeat
while (points[i].angle < q) do i += 1;
while (q < points[j].angle) do j -= 1;
if (i <= j) then
begin
w := points[i];
points[i] := points[j];
points[j] := w;
i += 1;
j -= 1;
end;
until (i > j);
if (l < j) then qSort(l,j);
if (i < r) then qSort(i,r);
end;
begin
assign(input, 'input.txt');
assign(output, 'output.txt');
reset(input); rewrite(output);
readln(n);
setlength(points, n + 1);
for i := 0 to n - 1 do
read(points[i].x, points[i].y);
for i := 1 to n - 1 do
if points[idx].y >= points[i].y then
if (points[idx].x > points[i].x) or (points[idx].y > points[i].y) then
idx := i;
swap_points(points[0], points[idx]);
for i := 1 to n - 1 do begin
points[i].angle := arctan2(points[i].y - points[0].y, points[i].x - points[0].x);
end;
qSort(1, n - 1);
for j := 0 to N-1 do begin
DeletedP := points[N - j];
points[N - j].angle := INF;
Push(points[0]); Push(points[1]);
for i := 2 to N-1 do begin
if points[i].angle = INF then continue;
while Rotate(Stack[high(Stack)-1], Stack[high(Stack)], points[i]) < 0 do
Pop();
Push(points[i]);
end;
Push(points[0]); Push(Stack[1]);
Minim:= 360;
for i := 1 to high(stack) - 1 do begin
Minim := min(minim, GetAngle(i));
end;
GMinim := max(GMinim, Minim);
points[N - j] := DeletedP;
setlength(Stack, 0);
end;
write(GMinim:0:2);
end.
|
unit BodyTypesBaseQuery;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, Vcl.StdCtrls, BodiesQuery, BodyDataQuery,
BodyVariationsQuery, BodyOptionsQuery, BodyVariationJedecQuery,
BodyVariationOptionQuery, JEDECQuery, DSWrap, BaseEventsQuery, NotifyEvents;
const
WM_AFTER_CASCADE_DELETE = WM_USER + 574;
type
TBodyTypeBaseW = class(TDSWrap)
private
FAfterCascadeDelete: TNotifyEventsEx;
FBody: TFieldWrap;
FBodyData: TFieldWrap;
FIDBody: TFieldWrap;
FIDBodyData: TFieldWrap;
FIDBodyKind: TFieldWrap;
FIDProducer: TFieldWrap;
FIDS: TFieldWrap;
FImage: TFieldWrap;
FJEDEC: TFieldWrap;
FLandPattern: TFieldWrap;
FOptions: TFieldWrap;
FOutlineDrawing: TFieldWrap;
FVariations: TFieldWrap;
procedure DoAfterOpen(Sender: TObject);
procedure ProcessAfterCascadeDeleteMessage;
protected
procedure OnGetFileNameWithoutExtensionGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
procedure WndProc(var Msg: TMessage); override;
public
constructor Create(AOwner: TComponent); override;
procedure CascadeDelete(const AIDMaster: Variant;
const ADetailKeyFieldName: String;
AFromClientOnly: Boolean = False); override;
property AfterCascadeDelete: TNotifyEventsEx read FAfterCascadeDelete;
property Body: TFieldWrap read FBody;
property BodyData: TFieldWrap read FBodyData;
property IDBody: TFieldWrap read FIDBody;
property IDBodyData: TFieldWrap read FIDBodyData;
property IDBodyKind: TFieldWrap read FIDBodyKind;
property IDProducer: TFieldWrap read FIDProducer;
property IDS: TFieldWrap read FIDS;
// TODO: LocateOrAppend
// procedure LocateOrAppend(AIDParentBodyType: Integer;
// const ABodyType1, ABodyType2, AOutlineDrawing, ALandPattern, AVariation,
// AImage: string);
property Image: TFieldWrap read FImage;
property JEDEC: TFieldWrap read FJEDEC;
property LandPattern: TFieldWrap read FLandPattern;
property Options: TFieldWrap read FOptions;
property OutlineDrawing: TFieldWrap read FOutlineDrawing;
property Variations: TFieldWrap read FVariations;
end;
TQueryBodyTypesBase = class(TQueryBaseEvents)
fdqUnusedBodies: TFDQuery;
fdqUnusedBodyData: TFDQuery;
private
FQueryBodies: TQueryBodies;
FQueryBodyData: TQueryBodyData;
FQueryBodyVariations: TQueryBodyVariations;
FqBodyOptions: TQueryBodyOptions;
FqBodyVariationJedec: TQueryBodyVariationJedec;
FqBodyVariationOption: TQueryBodyVariationOption;
FqJedec: TQueryJEDEC;
FW: TBodyTypeBaseW;
procedure DoAfterCascadeDelete(Sender: TObject);
function GetqBodyOptions: TQueryBodyOptions;
function GetqBodyVariationJedec: TQueryBodyVariationJedec;
function GetqBodyVariationOption: TQueryBodyVariationOption;
function GetqJedec: TQueryJEDEC;
function GetQueryBodies: TQueryBodies;
function GetQueryBodyData: TQueryBodyData;
function GetQueryBodyVariations: TQueryBodyVariations;
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
procedure DropUnusedBodies;
procedure SetMySplitDataValues(AQuery: TFDQuery;
const AFieldPrefix: String);
procedure UpdateJEDEC;
procedure UpdateOptions;
property qBodyOptions: TQueryBodyOptions read GetqBodyOptions;
property qBodyVariationJedec: TQueryBodyVariationJedec
read GetqBodyVariationJedec;
property qBodyVariationOption: TQueryBodyVariationOption
read GetqBodyVariationOption;
property QueryBodies: TQueryBodies read GetQueryBodies;
property QueryBodyData: TQueryBodyData read GetQueryBodyData;
property QueryBodyVariations: TQueryBodyVariations
read GetQueryBodyVariations;
public
constructor Create(AOwner: TComponent); override;
procedure RefreshLinkedData;
property qJedec: TQueryJEDEC read GetqJedec;
property W: TBodyTypeBaseW read FW;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses System.IOUtils, System.Generics.Collections;
constructor TQueryBodyTypesBase.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TBodyTypeBaseW;
TNotifyEventWrap.Create(W.AfterCascadeDelete, DoAfterCascadeDelete, W.EventList);
FDQuery.OnUpdateRecord := DoOnQueryUpdateRecord;
AutoTransaction := False;
end;
function TQueryBodyTypesBase.CreateDSWrap: TDSWrap;
begin
Result := TBodyTypeBaseW.Create(FDQuery);
end;
procedure TQueryBodyTypesBase.DoAfterCascadeDelete(Sender: TObject);
begin
// На сервере из этих таблиц каскадно удалились данные.
// Обновим содержимое этих таблиц на клиенте
RefreshLinkedData;
end;
procedure TQueryBodyTypesBase.DropUnusedBodies;
begin
while True do
begin
fdqUnusedBodyData.Close;
fdqUnusedBodyData.Open;
if fdqUnusedBodyData.RecordCount = 0 then
break;
while not fdqUnusedBodyData.Eof do
begin
QueryBodyData.W.LocateByPKAndDelete(fdqUnusedBodyData['ID']);
fdqUnusedBodyData.Next;
end;
fdqUnusedBodies.Close;
fdqUnusedBodies.Open();
if fdqUnusedBodies.RecordCount = 0 then
break;
while not fdqUnusedBodies.Eof do
begin
QueryBodies.W.LocateByPKAndDelete(fdqUnusedBodies['ID']);
fdqUnusedBodies.Next;
end;
end;
end;
function TQueryBodyTypesBase.GetqBodyOptions: TQueryBodyOptions;
begin
if FqBodyOptions = nil then
begin
FqBodyOptions := TQueryBodyOptions.Create(Self);
FqBodyOptions.FDQuery.Open;
end;
Result := FqBodyOptions;
end;
function TQueryBodyTypesBase.GetqBodyVariationJedec: TQueryBodyVariationJedec;
begin
if FqBodyVariationJedec = nil then
begin
FqBodyVariationJedec := TQueryBodyVariationJedec.Create(Self);
end;
Result := FqBodyVariationJedec;
end;
function TQueryBodyTypesBase.GetqBodyVariationOption: TQueryBodyVariationOption;
begin
if FqBodyVariationOption = nil then
FqBodyVariationOption := TQueryBodyVariationOption.Create(Self);
Result := FqBodyVariationOption;
end;
function TQueryBodyTypesBase.GetqJedec: TQueryJEDEC;
begin
if FqJedec = nil then
begin
FqJedec := TQueryJEDEC.Create(Self);
FqJedec.FDQuery.Open;
end;
Result := FqJedec;
end;
function TQueryBodyTypesBase.GetQueryBodies: TQueryBodies;
begin
if FQueryBodies = nil then
begin
FQueryBodies := TQueryBodies.Create(Self);
FQueryBodies.FDQuery.Open();
end;
Result := FQueryBodies;
end;
function TQueryBodyTypesBase.GetQueryBodyData: TQueryBodyData;
begin
if FQueryBodyData = nil then
begin
FQueryBodyData := TQueryBodyData.Create(Self);
FQueryBodyData.FDQuery.Open;
end;
Result := FQueryBodyData;
end;
function TQueryBodyTypesBase.GetQueryBodyVariations: TQueryBodyVariations;
begin
if FQueryBodyVariations = nil then
begin
FQueryBodyVariations := TQueryBodyVariations.Create(Self);
FQueryBodyVariations.FDQuery.Open;
end;
Result := FQueryBodyVariations;
end;
procedure TQueryBodyTypesBase.RefreshLinkedData;
begin
if FQueryBodies <> nil then
FQueryBodies.W.RefreshQuery;
if FQueryBodyData <> nil then
FQueryBodyData.W.RefreshQuery;
if FQueryBodyVariations <> nil then
FQueryBodyVariations.W.RefreshQuery;
end;
procedure TQueryBodyTypesBase.SetMySplitDataValues(AQuery: TFDQuery;
const AFieldPrefix: String);
var
F: TField;
i: Integer;
begin
Assert(AQuery <> nil);
Assert(FDQuery.State in [dsEdit, dsInsert]);
Assert(AQuery.RecordCount > 0);
Assert(not AFieldPrefix.IsEmpty);
// Заполняем части наименования
i := 0;
F := AQuery.FindField(Format('%s%d', [AFieldPrefix, i]));
while F <> nil do
begin
W.Field(F.FieldName).Value := F.Value;
Inc(i);
F := QueryBodies.FDQuery.FindField(Format('%s%d', [AFieldPrefix, i]));
end;
end;
procedure TQueryBodyTypesBase.UpdateJEDEC;
var
AJEDEC: string;
i: Integer;
JEDECArr: TArray<String>;
JEDECIDList: TList<Integer>;
begin
// Дополнительно обновляем список JEDEC
JEDECIDList := TList<Integer>.Create;
try
JEDECArr := W.JEDEC.F.AsString.Split([';']);
for i := Low(JEDECArr) to High(JEDECArr) do
begin
AJEDEC := JEDECArr[i].Trim;
if AJEDEC.IsEmpty then
Continue;
qJedec.W.LocateOrAppend(AJEDEC);
JEDECIDList.Add(qJedec.W.PK.AsInteger)
end;
// Обновляем JEDEC для текущего варианта корпуса
qBodyVariationJedec.UpdateJEDEC(QueryBodyVariations.W.PK.AsInteger,
JEDECIDList.ToArray);
finally
FreeAndNil(JEDECIDList);
end;
end;
procedure TQueryBodyTypesBase.UpdateOptions;
var
AOption: string;
i: Integer;
OptionArr: TArray<String>;
OptionIDList: TList<Integer>;
begin
// Дополнительно обновляем список вариантов (options)
OptionIDList := TList<Integer>.Create;
try
OptionArr := W.Options.F.AsString.Split([';']);
for i := Low(OptionArr) to High(OptionArr) do
begin
AOption := OptionArr[i].Trim;
if AOption.IsEmpty then
Continue;
qBodyOptions.W.LocateOrAppend(AOption);
OptionIDList.Add(qBodyOptions.W.PK.AsInteger)
end;
// Обновляем OPTIONS для текущего варианта корпуса
qBodyVariationOption.UpdateOption(QueryBodyVariations.W.PK.AsInteger,
OptionIDList.ToArray);
finally
FreeAndNil(OptionIDList);
end;
end;
constructor TBodyTypeBaseW.Create(AOwner: TComponent);
begin
inherited;
FIDS := TFieldWrap.Create(Self, 'IDS', '', True);
FBody := TFieldWrap.Create(Self, 'Body');
FBodyData := TFieldWrap.Create(Self, 'BodyData');
FIDBody := TFieldWrap.Create(Self, 'IDBody');
FIDBodyData := TFieldWrap.Create(Self, 'IDBodyData');
FIDBodyKind := TFieldWrap.Create(Self, 'IDBodyKind');
FIDProducer := TFieldWrap.Create(Self, 'IDProducer');
FImage := TFieldWrap.Create(Self, 'Image');
FJEDEC := TFieldWrap.Create(Self, 'JEDEC');
FLandPattern := TFieldWrap.Create(Self, 'LandPattern');
FOptions := TFieldWrap.Create(Self, 'Options');
FOutlineDrawing := TFieldWrap.Create(Self, 'OutlineDrawing');
FVariations := TFieldWrap.Create(Self, 'Variations');
TNotifyEventWrap.Create(AfterOpen, DoAfterOpen, EventList);
// Создаём ещё одно событие
FAfterCascadeDelete := TNotifyEventsEx.Create(Self);
FNEList.Add(FAfterCascadeDelete);
end;
procedure TBodyTypeBaseW.CascadeDelete(const AIDMaster: Variant;
const ADetailKeyFieldName: String; AFromClientOnly: Boolean = False);
begin
inherited;
if FPostedMessage.IndexOf(WM_AFTER_CASCADE_DELETE) < 0 then
begin
FPostedMessage.Add(WM_AFTER_CASCADE_DELETE);
PostMessage(Handle, WM_AFTER_CASCADE_DELETE, 0, 0);
end;
end;
procedure TBodyTypeBaseW.DoAfterOpen(Sender: TObject);
begin
SetFieldsRequired(False);
IDProducer.F.Required := True;
Body.F.Required := True;
BodyData.F.Required := True;
OutlineDrawing.F.OnGetText := OnGetFileNameWithoutExtensionGetText;
LandPattern.F.OnGetText := OnGetFileNameWithoutExtensionGetText;
Image.F.OnGetText := OnGetFileNameWithoutExtensionGetText;
end;
procedure TBodyTypeBaseW.OnGetFileNameWithoutExtensionGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
if not Sender.AsString.IsEmpty then
Text := TPath.GetFileNameWithoutExtension(Sender.AsString);
end;
procedure TBodyTypeBaseW.ProcessAfterCascadeDeleteMessage;
var
i: Integer;
begin
i := FPostedMessage.IndexOf(WM_AFTER_CASCADE_DELETE);
Assert(i >= 0);
// ещаем всех что каскадное обновление закончено
FAfterCascadeDelete.CallEventHandlers(Self);
FPostedMessage.Delete(i);
end;
procedure TBodyTypeBaseW.WndProc(var Msg: TMessage);
begin
case Msg.Msg of
WM_AFTER_CASCADE_DELETE:
ProcessAfterCascadeDeleteMessage;
else
inherited;
end;
end;
end.
|
unit WasmtimeSample_Linking;
(*
Example of compiling, instantiating, and linking two WebAssembly modules
together.
*)
interface
uses
Wasm, Wasmtime, Wasm.Wasi
;
function LinkingSample() : Boolean;
implementation
procedure exit_with_error(const msg : string; error : TOwnWasmtimeError; trap : PWasmTrap);
begin
writeln('error: '+msg);
var error_message : string;
if (error.IsError) then
begin
error_message := error.Unwrap.GetMessage;
end else if trap <> nil then
begin
error_message := trap.GetMessage();
end;
writeln(error_message);
halt(1);
end;
function LinkingSample() : Boolean;
begin
var engine := TWasmEngine.New();
assert(not engine.IsNone);
var store := TWasmtimeStore.New(+engine, nil, nil);
assert(not store.IsNone);
var context := (+store).Context;
var linking1wasm := TWasmByteVec.NewEmpty;
var ret := (+linking1wasm).Wat2Wasm(
'(module'#10+
' (import "linking2" "double" (func $double (param i32) (result i32)))'#10+
' (import "linking2" "log" (func $log (param i32 i32)))'#10+
' (import "linking2" "memory" (memory 1))'#10+
' (import "linking2" "memory_offset" (global $offset i32))'#10+
' (func (export "run")'#10+
' ;; Call into the other module to double our number, and we could print it'#10+
' ;; here but for now we just drop it'#10+
' i32.const 2'#10+
' call $double'#10+
' drop'#10+
' ;; Our `data` segment initialized our imported memory, so let''s print the'#10+
' ;; string there now.'#10+
' global.get $offset'#10+
' i32.const 14'#10+
' call $log'#10+
' )'#10+
' (data (global.get $offset) "Hello, world!\n")'#10+
')'
);
if ret.IsError then exit_with_error('Failed to wat2wasm linking1', ret, nil);
var linking2wasm := TWasmByteVec.NewEmpty;
ret := (+linking2wasm).Wat2Wasm(
'(module'#10+
' (type $fd_write_ty (func (param i32 i32 i32 i32) (result i32)))'#10+
' (import "wasi_snapshot_preview1" "fd_write" (func $fd_write (type $fd_write_ty)))'#10+
' (func (export "double") (param i32) (result i32)'#10+
' local.get 0'#10+
' i32.const 2'#10+
' i32.mul'#10+
' )'#10+
' (func (export "log") (param i32 i32)'#10+
' ;; store the pointer in the first iovec field'#10+
' i32.const 4'#10+
' local.get 0'#10+
' i32.store'#10+
' ;; store the length in the first iovec field'#10+
' i32.const 4'#10+
' local.get 1'#10+
' i32.store offset=4'#10+
' ;; call the `fd_write` import'#10+
' i32.const 1 ;; stdout fd'#10+
' i32.const 4 ;; iovs start'#10+
' i32.const 1 ;; number of iovs'#10+
' i32.const 0 ;; where to write nwritten bytes'#10+
' call $fd_write'#10+
' drop'#10+
' )'#10+
' (memory (export "memory") 2)'#10+
' (global (export "memory_offset") i32 (i32.const 65536))'#10+
')'
);
if ret.IsError then exit_with_error('Failed to wat2wasm linking2', ret, nil);
var module := TWasmtimeModule.New(+engine, +linking1wasm);
if module.IsError then exit_with_error('Failed to compile linking1', module.Error, nil);
var linking1_module := module.Module;
module := TWasmtimeModule.New(+engine, +linking2wasm);
if module.IsError then exit_with_error('Failed to compile linking2', module.Error, nil);
var linking2_module := module.Module;
var trap : TOwnTrap;
// Configure WASI and store it within our `wasmtime_store_t`
var wasi_config := TWasiConfig.New;
assert(not wasi_config.IsNone);
(+wasi_config).InheritArgv();
(+wasi_config).InheritEnv();
(+wasi_config).InheritStdin();
(+wasi_config).InheritStdout();
(+wasi_config).InheritStderr();
ret := context.SetWasi(wasi_config);
if ret.IsError then exit_with_error('Failed to instantiate wasi', ret, nil);
// Create our linker which will be linking our modules together, and then add
// our WASI instance to it.
var linker := TWasmtimeLinker.New(+engine);
ret := (+linker).DefineWasi;
if ret.IsError then exit_with_error('Failed to link wasi', ret, nil);
// Instantiate `linking2` with our linker.
var linking2 := (+linker).Instantiate(context, +linking2_module);
if linking2.IsError or linking2.Trap.IsError then exit_with_error('Failed to instantiate linking2', linking2.Error, linking2.Trap.Unwrap);
// Register our new `linking2` instance with the linker
ret := (+linker).DefineInstance(context, 'linking2', +linking2.Instance);
if ret.IsError then exit_with_error('Failed to link linking2', ret, nil);
// Instantiate `linking1` with the linker now that `linking2` is defined
var linking1 := (+linker).Instantiate(context, +linking1_module);
if linking1.IsError or linking1.Trap.IsError then exit_with_error('Failed to instantiate linking1', linking1.Error, linking2.Trap.Unwrap);
// Lookup our `run` export function
var run := (+linking1.Instance).GetExport('run');
assert(not run.IsNone);
assert((+run).kind = WASMTIME_EXTERN_FUNC);
ret := (+run).func.Call(nil, 0, nil, 0, trap);
if ret.IsError or trap.IsError then exit_with_error('Failed to call run', ret, nil);
result := true;
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
program HexDump;
Uses
Crt;
const
blocks = 10;
buffsize = 128;
type
str80 = string[80];
var
infile : file;
Buffer : array[1..blocks,1..buffsize] of BYTE;
function HexConv(num : integer) : str80;
const
base = 16;
Hex : string[16] = '0123456789ABCEDF';
var
temp : str80;
n,
check,
digit : integer;
function pwrint(num,raise : integer) : integer;
var
i, temp : integer;
begin
temp := 1;
if raise > 0 then
for i := 1 to raise do temp := temp * num
else temp := 1;
pwrint := temp;
end;
begin {HexConv}
n := 0;
temp := '';
if num > 4095 then writeln('ERROR! in hex conversion')
else
repeat
n := n + 1;
check := pwrint(base,n);
digit := trunc(num/pwrint(base,n-1)) mod base;
temp := Hex[digit+1] + temp;
until check > num;
if length(temp) < 2 then temp := '0'+temp;
HexConv := temp;
end; {HexConv}
procedure OpenFile;
var
name : str80;
function Exist(NameofFile: str80):Boolean;
var
Fil: file;
begin
Assign(Fil,NameOfFile);
{$I-}
Reset(Fil);
if IOresult <> 0 then
begin
Exist := False;
writeln('File ',NameOfFile,' does not exist here.');ClrEol;
writeln('Choose again or <Ctrl><Break> to exit.');ClrEol;
end
else begin
Exist := True;
close(Fil);
end;
{$I+}
end;
begin
repeat
write('File to display: ');
readln(Name);
until exist(Name);
assign(infile,Name);
reset(infile);
end; {OpenFile}
procedure ProcessFile;
const
ChrsOnLine = 16;
var
i,j,k,
RecsRead,
BlockCount,
temp : integer;
begin
BlockCount := 0;
while not EOF(infile) do
begin
BlockCount := BlockCount + 1;
BlockRead(infile,Buffer,blocks,RecsRead);
for i := 1 to RecsRead do
begin
j := 0;
while j < buffsize do
begin
write(HexConv(BlockCount*i*buffsize - buffsize + j):5,': ');
for k := 1 to ChrsOnLine do
write(HexConv(Buffer[i,j+k]),' ');
write(' ');
for k := 1 to ChrsOnLine do
begin
temp := Buffer[i,j+k];
if (temp > 31) and (temp < 128) then
write(chr(temp))
else write('.');
end;
writeln;
j := j + ChrsOnLine;
end; {for j}
end; {for i}
end; {while not EOF}
end; {ProcessFile}
begin {MAIN}
OpenFile;
ProcessFile;
Close(InFile);
end.
|
program CreateTable1;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils,
CustApp,
Amazon.Client in 'Amazon.Client.pas',
Amazon.Interfaces in 'Amazon.Interfaces.pas',
Amazon.Credentials in 'Amazon.Credentials.pas',
Amazon.Environment in 'Amazon.Environment.pas',
Amazon.Utils in 'Amazon.Utils.pas',
Amazon.Request in 'Amazon.Request.pas',
Amazon.Response in 'Amazon.Response.pas',
Amazon.IndyRESTClient in 'Amazon.IndyRESTClient.pas',
Amazon.SignatureV4 in 'Amazon.SignatureV4.pas';
type
{ TCreateTable1 }
TCreateTable1 = class(TCustomApplication)
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
end;
{ TCreateTable3 }
procedure TCreateTable1.DoRun;
var
FAmazonRESTClient: TAmazonIndyRESTClient;
FAmazonRequest: TAmazonRequest;
FAmazonSignatureV4: TAmazonSignatureV4;
FAmazonClient: TAmazonClient;
FAmazonResponse: IAmazonResponse;
begin
try
Try
Writeln('DynamoDB API (CreateTable) using Amazon.Client class');
FAmazonClient:= TAmazonClient.Create;
FAmazonClient.endpoint := 'https://dynamodb.ap-southeast-2.amazonaws.com/';
FAmazonClient.service := 'dynamodb';
FAmazonRequest := TAmazonRequest.Create;
FAmazonSignatureV4 := TAmazonSignatureV4.Create;
FAmazonRESTClient := TAmazonIndyRESTClient.Create;
FAmazonRequest.request_parameters := '{' +
'"KeySchema": [{"KeyType": "HASH","AttributeName": "Id"}],' +
'"TableName": "TestTable",' +
'"AttributeDefinitions": [{"AttributeName": "Id","AttributeType": "S"}],' +
'"ProvisionedThroughput": {"WriteCapacityUnits": 5,"ReadCapacityUnits": 5}' +
'}';
Writeln('Endpoint:'+FAmazonClient.endpoint);
FAmazonRequest.targetPrefix := 'DynamoDB_20120810';
FAmazonRequest.operationName := 'CreateTable';
Writeln('Target:'+FAmazonRequest.Target);
FAmazonResponse := FAmazonClient.execute(FAmazonRequest, fAmazonSignatureV4, FAmazonRESTClient);
Writeln('ResponseCode:' + IntTostr( FAmazonResponse.ResponseCode));
Writeln('ResponseStr:' + FAmazonResponse.ResponseText);
Writeln('Response:' + FAmazonResponse.Response);
Writeln('Press [enter] to finish.');
readln;
Finally
FAmazonClient.Free;
FAmazonResponse := NIL;
End;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
Terminate;
end;
constructor TCreateTable1.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TCreateTable1.Destroy;
begin
inherited Destroy;
end;
var
Application: TCreateTable1;
begin
Application:=TCreateTable1.Create(nil);
Application.Run;
Application.Free;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.Graphics;
interface
uses
System.Types, System.UITypes, System.Classes, FMX.Graphics;
function RoundLogicPointsToMatchPixel(const LogicPoints: Single; const AtLeastOnePixel: Boolean = False): Single;
function RoundToPixel(const Source: TRectF; const AThickness: Single = 1): TRectF; overload;
function RoundToPixel(const Source: TPointF; const AThickness: Single = 1): TPointF; overload;
function RoundToPixel(const Source: Single; const AThickness: Single = 1): Single; overload;
function MakeColor(const ASource: TAlphaColor; AOpacity: Single): TAlphaColor;
function Create9PatchShadow(const ASize: TSizeF; const AColor: TAlphaColor): TBitmap;
implementation
uses
System.Math, System.SysUtils, FMX.Forms, FMX.Platform, FGX.Helpers, FGX.Consts,
FGX.Asserts, FMX.Types, FMX.Filter.Custom, FMX.Filter, System.UIConsts,
FMX.Effects;
function RoundLogicPointsToMatchPixel(const LogicPoints: Single; const AtLeastOnePixel: Boolean = False): Single;
var
Pixels: Single;
begin
Pixels := Round(LogicPoints * Screen.Scale);
if (Pixels < 1) and AtLeastOnePixel then
Pixels := 1.0;
Result := Pixels / Screen.Scale;
end;
function RoundToPixel(const Source: Single; const AThickness: Single = 1): Single; overload;
begin
Result := Source;
if SameValue(Round(Source * Screen.Scale), Source * Screen.Scale, EPSILON_SINGLE) then
Result := Source - AThickness / 2;
end;
function RoundToPixel(const Source: TPointF; const AThickness: Single = 1): TPointF; overload;
begin
Result.X := RoundToPixel(Source.X);
Result.Y := RoundToPixel(Source.Y);
end;
function RoundToPixel(const Source: TRectF; const AThickness: Single = 1): TRectF; overload;
begin
Result.Left := RoundToPixel(Source.Left);
Result.Top := RoundToPixel(Source.Top);
Result.Right := RoundToPixel(Source.Right);
Result.Bottom := RoundToPixel(Source.Bottom);
end;
function MakeColor(const ASource: TAlphaColor; AOpacity: Single): TAlphaColor;
begin
AssertInRange(AOpacity, 0, 1);
Result := ASource;
TAlphaColorRec(Result).A := Round(255 * AOpacity);
end;
function Create9PatchShadow(const ASize: TSizeF; const AColor: TAlphaColor): TBitmap;
const
AShadowThickness = 5;
CornerRadius = 2;
var
CenterRect: TRectF;
Filter: TFilter;
ContentMargin: Single;
begin
Result := TBitmap.Create(Round(ASize.Width + 2 * AShadowThickness), Round(ASize.Height + 2 * AShadowThickness));
Result.Clear(TAlphaColorRec.Null);
with Result.Canvas do
if BeginScene then
try
CenterRect := TRectF.Create(TPointF.Create(AShadowThickness, AShadowThickness), ASize.Width, ASize.Height);
Fill.Color := AColor;
Fill.Kind := TBrushKind.Solid;
FillRect(CenterRect, 0, 0, AllCorners, 1);
finally
EndScene;
end;
Filter := TFilterManager.FilterByName('GlowFilter');
if Assigned(Filter) then
begin
Filter.ValuesAsColor['Color'] := AColor;
Filter.ValuesAsBitmap['Input'] := Result;
Filter.ValuesAsFloat['BlurAmount'] := 0.3;
Filter.ApplyWithoutCopyToOutput;
TFilterManager.FilterContext.CopyToBitmap(Result, TRect.Create(0, 0, Result.Width, Result.Height));
end;
ContentMargin := AShadowThickness + CornerRadius / 2;
with Result.Canvas do
if BeginScene then
try
CenterRect := TRectF.Create(TPointF.Create(AShadowThickness, AShadowThickness), ASize.Width, ASize.Height);
Fill.Color := AColor;
Fill.Kind := TBrushKind.Solid;
FillRect(CenterRect, CornerRadius, CornerRadius, AllCorners, 1);
Stroke.Color := TAlphaColorRec.Black;
StrokeThickness := 1;
Stroke.Kind := TBrushKind.Solid;
DrawLine(TPointF.Create(0.5, ContentMargin + 0.5),
TPointF.Create(0.5, ASize.Height + 2 * AShadowThickness - ContentMargin - 0.5), 1);
DrawLine(TPointF.Create(ContentMargin + 0.5, 0.5),
TPointF.Create(ASize.Width + AShadowThickness - 0.5, 0.5), 1);
// DrawLine(TPointF.Create(ASize.Width + 2 * AShadowThickness - 0.5, ContentMargin + 0.5),
// TPointF.Create(ASize.Width + 2 * AShadowThickness - 0.5, ASize.Height + AShadowThickness - 0.5), 1);
// DrawLine(TPointF.Create(ContentMargin + 0.5, ASize.Height + 2 * AShadowThickness - 0.5),
// TPointF.Create(ASize.Width + 2 * AShadowThickness - ContentMargin - 0.5, ASize.Height + 2 * AShadowThickness - 0.5), 1);
finally
EndScene;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ SOAP Support }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Soap.OPToSOAPDomCustom;
interface
uses
System.TypInfo, Soap.IntfInfo, Soap.InvokeRegistry, Xml.XMLIntf;
type
ICustomConvert = interface
['{96832CB3-BC12-4C45-B482-26F7160EDE51}']
procedure ConvertSoapParamToNative(MethMD: PIntfMethEntry;
InvContext: TInvContext; ArgCount: Integer; Node: IXMLNode);
procedure ConvertNativeParamToSoap(Node: IXMLNode;
Name: string; Info: PTypeInfo; P: Pointer);
end;
TConverterEntry = record
Converter: ICustomConvert;
AClass: TClass;
end;
TOPToSoapDomCustomRegistry = class
private
FConverters: array of TConverterEntry;
public
procedure RegisterCustomConverter(AClass: TClass; URI, TypeName: string; Converter: ICustomConvert);
function GetConverter(AClass: TClass): ICustomConvert;
end;
var
ConverterRegistry: TOPToSoapDomCustomRegistry;
implementation
{ TOPToSoapDomCustomtRegistry }
function TOPToSoapDomCustomRegistry.GetConverter(
AClass: TClass): ICustomConvert;
var
I: Integer;
begin
for I := 0 to Length(FConverters) - 1 do
if FConverters[I].AClass = AClass then
Result := FConverters[I].Converter;
end;
procedure TOPToSoapDomCustomRegistry.RegisterCustomConverter(
AClass: TClass; URI, TypeName: string; Converter: ICustomConvert);
var
Index: Integer;
begin
Index := Length(FConverters);
SetLength(FConverters, Index + 1);
FConverters[Index].Converter := Converter;
FConverters[Index].AClass := AClass;
end;
initialization
ConverterRegistry := TOPToSoapDomCustomRegistry.Create;
finalization
ConverterRegistry.Free;
end.
|
{*******************************************************************************
* *
* TksProgressBar - Progress Bar Component *
* *
* https://bitbucket.org/gmurt/kscomponents *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksProgressBar;
interface
{$I ksComponents.inc}
uses Classes, ksTypes, FMX.Graphics, System.UITypes, System.UIConsts;
type
[ComponentPlatformsAttribute(
pidWin32 or
pidWin64 or
{$IFDEF XE8_OR_NEWER} pidiOSDevice32 or pidiOSDevice64 {$ELSE} pidiOSDevice {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidiOSSimulator32 or pidiOSSimulator64 {$ELSE} pidiOSSimulator {$ENDIF} or
{$IFDEF XE10_3_OR_NEWER} pidAndroid32Arm or pidAndroid64Arm {$ELSE} pidAndroid {$ENDIF}
)]
TksProgressBar = class(TksControl)
private
FBackgroundColor: TAlphaColor;
FBorderColor: TAlphaColor;
FBarColor: TAlphaColor;
FValue: integer;
FMaxValue: integer;
procedure SetBackgroundColor(const Value: TAlphaColor);
procedure SetBarColor(const Value: TAlphaColor);
procedure SetBorderColor(const Value: TAlphaColor);
procedure SetMaxValue(const Value: integer);
procedure SetValue(const Value: integer);
function GetPercent: integer;
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetValues(APosition, AMax: integer);
published
property Align;
property Height;
property Width;
property Size;
property Margins;
property Padding;
property Position;
property BackgroundColor: TAlphaColor read FBackgroundColor write SetBackgroundColor default claGainsboro;
property BarColor: TAlphaColor read FBarColor write SetBarColor default claDodgerblue;
property BorderColor: TAlphaColor read FBorderColor write SetBorderColor default claBlack;
property MaxValue: integer read FMaxValue write SetMaxValue default 100;
property Value: integer read FValue write SetValue default 50;
property Percent: integer read GetPercent;
property Visible;
end;
procedure Register;
implementation
uses FMX.Controls, Math, SysUtils, Types, FMX.Types, FMX.Ani, ksCommon, FMX.Forms;
const
C_SCALE = 3;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksProgressBar]);
end;
{ TksProgressBar }
constructor TksProgressBar.Create(AOwner: TComponent);
begin
inherited;
FBorderColor := claBlack;;
FBarColor := claDodgerblue;
FValue := 50;
FMaxValue := 100;
Width := 100;
Height := 20;
end;
destructor TksProgressBar.Destroy;
begin
inherited;
end;
function TksProgressBar.GetPercent: integer;
begin
Result := 0;
if (FValue > 0) and (FMaxValue > 0) then
begin
Result := Round((FValue / FMaxValue) * 100);
end;
end;
procedure TksProgressBar.Paint;
var
AState: TCanvasSaveState;
ABar: TRectF;
APercent: single;
v,m: integer;
begin
inherited;
if Locked then
Exit;
AState := Canvas.SaveState;
try
Canvas.BeginScene;
Canvas.IntersectClipRect(ClipRect);
// background...
Canvas.Clear(FBackgroundColor);
// bar...
Canvas.Fill.Color := FBarColor;
APercent := 0;
v := FValue;
m := FMaxValue;
v := Min(v, m);
if (v > 0) and (m > 0) then
begin
APercent := (v / m);
end;
ABar := RectF(0, 0, Width * APercent, Height);
Canvas.FillRect(ABar, 0, 0, AllCorners, 1);
// border...
Canvas.Stroke.Thickness := 1;
Canvas.Stroke.Kind := TBrushKind.Solid;
Canvas.Stroke.Color := FBorderColor;
Canvas.DrawRect(ClipRect, 0, 0, AllCorners, 1);
Canvas.EndScene;
finally
canvas.RestoreState(AState);
end;
end;
procedure TksProgressBar.SetBackgroundColor(const Value: TAlphaColor);
begin
FBackgroundColor := Value;
Repaint;
end;
procedure TksProgressBar.SetBarColor(const Value: TAlphaColor);
begin
FBarColor := Value;
Repaint;
end;
procedure TksProgressBar.SetBorderColor(const Value: TAlphaColor);
begin
FBorderColor := Value;
Repaint;
end;
procedure TksProgressBar.SetMaxValue(const Value: integer);
begin
FMaxValue := Value;
Repaint;
end;
procedure TksProgressBar.SetValue(const Value: integer);
begin
FValue := Value;
Repaint;
end;
procedure TksProgressBar.SetValues(APosition, AMax: integer);
begin
FMaxValue := AMax;
FValue := APosition;
Repaint;
end;
end.
|
unit Common.DatabaseUtils;
interface
uses
System.Classes, Uni;
type
TCreateMode = (cmCreate, cmReplicate);
function UpdateDatabaseShema(ADBFile: string): Boolean;
procedure FillData;
function GetFieldValue(AParams: array of Variant): Variant;
implementation
uses
System.IniFiles,
System.SysUtils,
Vcl.FileCtrl,
Common.Utils,
ConnectionModule,
WaitForm, SplashScreenU, Vcl.Forms;
var
AutoReplicate, SilentMode: Boolean;
function RecordFind(TableName, SQLCond: string; AParams: array of Variant): Boolean; overload;
var
Q: TUniQuery;
I : Integer;
begin
Q := TUniQuery.Create(nil);
with Q do try
Connection := DM.conn;
if SQLCond > '' then
SQLCond := 'where ' + SQLCond;
SQL.Text := Format('select count(*) from %s %s',
[TableName, SQLCond]);
if Length(AParams) > 0 then begin
for I := Low(AParams) to High(AParams) do
Params[I].Value := AParams[i];
end;
ExecSQL;
Result := Fields[0].AsInteger > 0;
finally
Free;
end;
end;
function GetFieldValue(AParams: array of Variant): Variant;
const
cSQLBody =
'select %s from %s %s';
var
eSQLWhere: string;
begin
with TUniQuery.Create(nil) do try
Connection := DM.conn;
eSQLWhere := '';
if Length(AParams) = 3 then
eSQLWhere := Format('where %s', [ AParams[2] ]);
SQL.Text := Format(cSQLBody, [AParams[0], AParams[1], eSQLWhere]);
ExecSQL;
Result := Fields[0].Value;
finally
Free;
end;
end;
procedure AddRecordsToDatabase(FR: TFileRecordList; AMode: TCreateMode);
var
I: Integer;
ID: Integer;
SQLCond, eFileName: string;
begin
if (AMode = cmCreate) then begin
if (not RecordFind('Categories', 'ID=:ID', [ 1 ])) then begin
with DM.qryCategories do try
Active := True;
Append;
FieldByName('ID').AsInteger := 1;
FieldByName('CategoryName').AsString := 'Все книги';
Post;
except on E: Exception do begin
ShowErrorFmt('Не удалось добавить категрию.'#13'%s', [E.Message]);
Exit;
end;
end;
end;
DM.qryBooks.Active := True;
for I := 0 to FR.Count - 1 do begin
ShowSplashScreenMessage(Format('Добавление записи: %s', [ FR[ I ].FileName ]));
Sleep(5);
with DM.qryBooks do try
Append;
FieldByName('ID').AsInteger := I + 1;
FieldByName('BookName').AsString := FR[ I ].FileName;
FieldByName('BookLink').AsString := FR[ I ].FilePath;
FieldByName('Category_ID').AsInteger := 1;
Post;
except on E: Exception do begin
ShowErrorFmt('Не удалось добавить книгу.'#13'%s', [E.Message]);
Exit;
end;
end;
end;
end else if (AMode = cmReplicate) then begin
if (not RecordFind('Categories', 'ID=:ID', [ 1000 ])) then begin
with DM.qryCategories do try
Active := True;
Append;
FieldByName('ID').AsInteger := 1000;
FieldByName('CategoryName').AsString := 'Новые книги';
Post;
except on E: Exception do begin
ShowErrorFmt('Не удалось добавить категорию.'#13'%s', [E.Message]);
Exit;
end;
end;
end;
DM.qryBooks.Active := True;
for I := 0 to FR.Count - 1 do begin
ShowSplashScreenMessage(Format('Обработка записи: %s', [ FR[ I ].FileName ]));
Sleep(5);
eFileName := StringReplace(FR[ I ].FileName, #39, #39#39, [rfReplaceAll]);
if (not (RecordFind('Books', 'BookLink like :BL', [ '%' + FR[ I ].FileName ]))) then begin
with DM.qryBooks do try
Append;
//FieldByName('ID').AsInteger := I + 1;
FieldByName('BookName').AsString := FR[ I ].FileName;
FieldByName('BookLink').AsString := FR[ I ].FilePath;
FieldByName('Category_ID').AsInteger := 1000;
Post;
except on E: Exception do begin
ShowErrorFmt('Не удалось добавить книгу.'#13'%s', [E.Message]);
Exit;
end;
end;
end else begin
SQLCond := Format('BookLink like ''%s''', [ '%' + eFileName ]);
ID := GetFieldValue(['ID', 'Books', SQLCond]);
if ID > 0 then
with TUniQuery.Create(nil) do try
try
Connection := DM.conn;
SQL.Text := 'update Books set BookLink = :BL where ID = :ID';
ParamByName('BL').AsString := FR[ I ].FilePath;
ParamByName('ID').AsInteger := ID;
ExecSQL;
except on E: Exception do begin
ShowErrorFmt('Не удалось обновить книгу.'#13'%s', [E.Message]);
Exit;
end;
end;
finally
Free;
end;
end;
end;
end;
end;
procedure CreateDataFromFiles(AMode: TCreateMode);
var
FilesList: TFileRecordList;
StartDir: string;
I: Integer;
begin
// Синхронизация библиотеки
with TIniFile.Create(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'conn.ini') do try
StartDir := ReadString('Path', 'SearchPath', 'D:\Книги');
finally
Free;
end;
if (StartDir = '') or (not DirectoryExists(StartDir)) then begin
// вызов диалога для выбора каталога
if not SelectDirectory('Выберите каталог', '', StartDir) then Exit;
end;
with TIniFile.Create(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'conn.ini') do try
WriteString('Path', 'SearchPath', StartDir);
finally
Free;
end;
FilesList := TFileRecordList.Create;
try
FindAllFiles(FilesList, StartDir, ['pdf', 'djvu', 'fb2', 'epub', 'chm']);
AddRecordsToDatabase(FilesList, AMode);
finally
FilesList.Free;
end;
end;
function UpdateDatabaseShema(ADBFile: string): Boolean;
const
cSQLScript =
'CREATE TABLE [BOOKS]( '#13#10 +
' [ID] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '#13#10 +
' [BOOKNAME] VARCHAR(250) NOT NULL, '#13#10 +
' [BOOKLINK] VARCHAR(250), '#13#10 +
' [CATEGORY_ID] INTEGER CONSTRAINT [FK_BOOKS_CATEGORY_ID] REFERENCES CATEGORIES([ID])); '#13#10 +
' '#13#10 +
'CREATE TABLE [CATEGORIES]( '#13#10 +
' [ID] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, '#13#10 +
' [CATEGORYNAME] VARCHAR(250) NOT NULL, '#13#10 +
' [PARENT_ID] INTEGER CONSTRAINT [FK_CATEGORIES_PARENTID] REFERENCES CATEGORIES([ID]));';
begin
if not FileExists(ADBFile) then begin
with DM.conn do try
Database := ADBFile;
SpecificOptions.Values['ForceCreateDatabase'] := 'True';
Connect;
ExecSQL('PRAGMA auto_vacuum = 1');
ExecSQL(cSQLScript);
Disconnect;
Result := True;
except on E: Exception do begin
ShowErrorFmt('При создании базы данных возникла ошибка'#13'%s', [E.Message]);
Result := False;
end;
end;
end else Result := True;
end;
procedure FillData;
var
UpdateMode: TCreateMode;
begin
with TIniFile.Create(IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'conn.ini') do try
// параметр конфигурации "Авторепликация базы"
AutoReplicate := ReadBool('Config', 'AutoReplicate', False);
SilentMode := ReadBool('Config', 'SilentMode', False);
finally
Free;
end;
with DM do begin
conn.StartTransaction;
try
if GetFieldValue(['count(*)','Books']) = 0 then
UpdateMode := cmCreate
else
UpdateMode := cmReplicate;
if (UpdateMode = cmReplicate) and not AutoReplicate then Exit;
if not SilentMode then begin
ShowSplashscreen;
try
CreateDataFromFiles(UpdateMode);
finally
HideSplashScreen;
end;
end else begin
CreateDataFromFiles(UpdateMode);
end;
conn.Commit;
except
conn.Rollback;
raise;
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit EMS.ResourceTypes;
{$SCOPEDENUMS ON}
interface
uses
System.Classes, System.Rtti, System.TypInfo, System.Generics.Collections, System.SysUtils,
EMS.ResourceAPI, System.JSON.Writers, System.JSON.Builders, System.Net.Mime;
type
TEMSResourceEndPoint = class;
TEMSEndpointSegmentList = class;
TEMSEndpointSegment = class;
TAPIDocPathItem = class;
TAPIDocParameter = class;
TAPIDocResponse = class;
TAPIDocPath = class;
EndPointRequestSummaryAttribute = class;
EndPointRequestParameterAttribute = class;
EndPointResponseDetailsAttribute = class;
TEMSResourceAttributes = class;
/// <summary>
/// Attribute for EMS resource class
/// </summary>
TResourceCustomAttribute = class(TCustomAttribute);
/// <summary>
/// Attribute for EMS endpoint method
/// </summary>
TEndpointCustomAttribute = class(TCustomAttribute)
private
FMethod: string;
protected
constructor Create(const AMethod: string); overload;
public
property Method: string read FMethod;
end;
TEMSCommonResource = class abstract(TEMSResource)
private type
TFindCallback = reference to procedure(const AEndPoint: TEMSResourceEndPoint; var ADone: Boolean);
TLeafEndpoint = record
EndpointName: string;
Score: Integer;
public
constructor Create(const AEndpointName: string; AScore: Integer);
end;
TTreeNode = class
private
FMethod: TEndpointRequest.TMethod;
FSegment: TEMSEndPointSegment;
FChildNodes: TList<TTreeNode>;
FLeafEndpoints: TList<TLeafEndpoint>;
function GetChildNodes: TArray<TTreeNode>;
function GetLeafEndpoints: TArray<TLeafEndpoint>;
public
constructor Create(AMethod: TEndpointRequest.TMethod;
const ASegment: TEMSEndpointSegment);
destructor Destroy; override;
procedure AddChildNode(const ANode: TTreeNode);
procedure AddTerminalEndpoint(const AEndpointName: string; AScore: Integer);
property Method: TEndpointRequest.TMethod read FMethod;
property Segment: TEMSEndPointSegment read FSegment;
property ChildNodes: TArray<TTreeNode> read GetChildNodes;
property LeafEndpoints: TArray<TLeafEndpoint> read GetLeafEndpoints;
end;
TNegotiator = class(TObject)
public type
TStatus = (Nothing, Failed, Duplicates, OK);
private
FContext: TEndpointContext;
FBestEndpoints: TList<TEMSResourceEndPoint>;
FBestWeight: Double;
FChooseCount: Integer;
function GetStatus: TStatus;
function GetBestEndpoint: TEMSResourceEndPoint;
function GetDuplicateNames: string;
public
constructor Create(AContext: TEndpointContext);
destructor Destroy; override;
procedure Reset;
procedure Choose(AEndpoint: TEMSResourceEndPoint; AScore: Integer);
property Status: TStatus read GetStatus;
property BestEndpoint: TEMSResourceEndPoint read GetBestEndpoint;
property BestWeight: Double read FBestWeight;
property DuplicateNames: string read GetDuplicateNames;
end;
private
FEndpoints: TList<TEMSResourceEndPoint>;
FEndpointsDict: TDictionary<string, TEMSResourceEndPoint>;
FBaseURL: string;
FResourceName: string;
private
FBaseURLSegmentCount: Integer;
FRootNode: TTreeNode;
function EnumEndPoints(const ACallback: TFindCallback): Boolean;
function FindEndPoint(const AName: string): TEMSResourceEndPoint;
procedure BuildTree;
procedure SearchTree(const AContext: TEndpointContext;
ARequestSegmentIndex: Integer; const ATreeNode: TTreeNode;
const ATerminalNodes: TList<TTreeNode>); overload;
procedure SearchTree(const AContext: TEndpointContext;
out ATerminalNodes: TArray<TTreeNode>); overload;
protected
procedure DoHandleRequest(const AContext: TEndpointContext); override;
function DoCanHandleRequest(const AContext: TEndpointContext;
out AEndpointName: string): Boolean; override;
function GetName: string; override;
function GetEndpointNames: TArray<string>; override;
public
constructor Create(const AResourceName: string);
destructor Destroy; override;
property BaseURLSegmentCount: Integer read FBaseURLSegmentCount;
function IsBaseURL(const ABaseURL: string): Boolean; override;
end;
TEMSResourceEndPoint = class abstract
private
FRoot: TEMSCommonResource;
function GetFullName: string;
protected
function GetName: string; virtual; abstract;
procedure SetName(const AName: string); virtual; abstract;
procedure DoAuthorizeRequest(const AContext: TEndpointContext); virtual;
procedure DoHandleRequest(const AContext: TEndpointContext); virtual; abstract;
/// <summary>Get the URL segment parameters declared for an endpoint</summary>
function GetSegmentParameters: TEMSEndPointSegmentList; virtual; abstract;
/// <summary>Get the method of an endpoint, such as GET or POST</summary>
function GetMethod: TEndpointRequest.TMethod; virtual; abstract;
function GetProduceList: TAcceptValueList; virtual; abstract;
function GetConsumeList: TAcceptValueList; virtual; abstract;
public
constructor Create(const AOwner: TEMSCommonResource);
destructor Destroy; override;
property Name: string read GetName;
property FullName: string read GetFullName;
/// <summary>Get the URL segment parameters declared for an endpoint</summary>
property SegmentParameters: TEMSEndPointSegmentList read GetSegmentParameters;
/// <summary>Get the method of an endpoint, such as GET or POST</summary>
property Method: TEndpointRequest.TMethod read GetMethod;
property ProduceList: TAcceptValueList read GetProduceList;
property ConsumeList: TAcceptValueList read GetConsumeList;
end;
TEMSEndPointSegmentList = class
private
FList: TList<TEMSEndPointSegment>;
function GetCount: Integer;
function GetItem(I: Integer): TEMSEndPointSegment;
public
constructor Create;
destructor Destroy; override;
function GetEnumerator: TEnumerator<TEMSEndPointSegment>;
property Items[I: Integer]: TEMSEndPointSegment read GetItem;
property Count: Integer read GetCount;
end;
TEMSEndPointSegment = class
private
[weak] FOwner: TEMSEndPointSegmentList;
public
constructor Create(const AOwner: TEMSEndPointSegmentList);
destructor Destroy; override;
end;
TEMSEndPointSegmentParameter = class(TEMSEndPointSegment)
private
FName: string;
public
constructor Create(const AOwner: TEMSEndPointSegmentList; const AName: string);
property Name: string read FName;
end;
TEMSResourceEndPointSuffix = class(TEMSResourceEndPoint)
private type
TSegmentParamCallback = TProc<TEMSEndPointSegmentParameter, string>;
public type
THandlerProc = reference to procedure(const Sender: TObject; const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse);
private
FURLSuffix: string;
FName: string;
FMethod: TEndpointRequest.TMethod;
FHandlerProc: THandlerProc;
FSegmentParameters: TEMSEndPointSegmentList;
FProduceList: TAcceptValueList;
FConsumeList: TAcceptValueList;
function ScanSegmentParameters(const AContext: TEndpointContext;
const ACallback: TSegmentParamCallback): Boolean;
protected
function GetSegmentParameters: TEMSEndPointSegmentList; override;
function GetMethod: TEndpointRequest.TMethod; override;
function GetProduceList: TAcceptValueList; override;
function GetConsumeList: TAcceptValueList; override;
function GetName: string; override;
procedure SetName(const AName: string); override;
procedure DoAuthorizeRequest(const AContext: TEndpointContext); override;
procedure DoHandleRequest(const AContext: TEndpointContext); override;
public
constructor Create(const AOwner: TEMSCommonResource; const AName, AURLSuffix: string;
const AMethod: TEndpointRequest.TMethod; const AProduce, AConsume: string;
const AHandlerProc: THandlerProc);
destructor Destroy; override;
end;
TEMSEndPointSegmentSlash = class(TEMSEndPointSegment)
end;
/// <summary>Represents a URL segment that matches any combination of URL
/// segments.</summary>
TEMSEndPointSegmentWildCard = class(TEMSEndPointSegment)
end;
TEMSEndPointSegmentConstant = class(TEMSEndPointSegment)
private
FValue: string;
public
constructor Create(const AOwner: TEMSEndPointSegmentList; const AValue: string);
property Value: string read FValue;
end;
TEMSEndPointSegmentService = class
public
class procedure ExtractSegments(const AString: string; const AList: TEMSEndPointSegmentList); static;
class function CountSegments(const AString: string): Integer; static;
end;
TEMSBasicResource = class(TEMSCommonResource)
end;
ResourceSuffixAttribute = class(TEndpointCustomAttribute)
private
FSuffix: string;
public
constructor Create(const AMethod, ASuffix: string); overload;
constructor Create(const ASuffix: string); overload;
property Suffix: String read FSuffix;
end;
ResourceNameAttribute = class(TResourceCustomAttribute)
private
FName: string;
public
constructor Create(AName: string);
property Name: String read FName;
end;
EndpointNameAttribute = class(TEndpointCustomAttribute)
private
FName: string;
public
constructor Create(const AMethod, AName: string); overload;
constructor Create(const AName: string); overload;
property Name: String read FName;
end;
TResourceStringsTable = class
private
class var FResourcesTable : TDictionary<string, string>;
public
class constructor Create;
class destructor Destroy;
class procedure Add(const Akey, AResource: string); static;
class function Get(const Akey: string): string; static;
end;
TAPIDoc = class
public const
cBlank = ' ';
cEmptySchema = '{}';
cStar = '*';
cWildCard = 'wildcard';
public type
TAPIDocContactInfo = record
private
FName: string;
FURL: string;
FEmail: string;
public
constructor Create (const AName, AURL, AEmail: string);
property Name: string read FName;
property URL: string read FURL;
property Email: string read FEmail;
end;
TAPIDocLicenseInfo = record
private
FName: string;
FURL: string;
public
constructor Create (const AName, AURL: string);
property Name: string read FName;
property URL: string read FURL;
end;
TAPIDocInfo = record
private
FVersion: string;
FTitle: string;
FDescription: string;
FTermsOfUse: string;
FContact:TAPIDocContactInfo;
FLicense: TAPIDocLicenseInfo;
public
constructor Create(const AVersion, ATitle, ADescription: string);
property Version: string read FVersion;
property Title: string read FTitle;
property Description: string read FDescription;
property TermsOfUse: string read FTermsOfUse write FTermsOfUse;
property Contact: TAPIDocContactInfo read FContact write FContact;
property License: TAPIDocLicenseInfo read FLicense write FLicense;
end;
/// <summary>
/// Primitive data types in the Swagger Specification are based on the types supported by the JSON-Schema Draft 4.
/// http://json-schema.org/latest/json-schema-core.html#anchor8
/// An additional primitive data type "file" is used by the Parameter Object and the Response Object
/// to set the parameter type or the response as being a file.
/// </summary>
TPrimitiveType = (spArray, spBoolean, spInteger, spNumber, spNull, spObject, spString, spFile);
/// <summary>
/// Primitives have an optional modifier property format.
/// </summary>
TPrimitiveFormat = (None, Int32, Int64, Float, Double, Byte, Date, DateTime, Password);
/// <summary>
/// The transfer protocol of the API. Values MUST be from the list: "http", "https", "ws", "wss".
/// If the schemes is not included, the default scheme to be used is the one used to access the Swagger definition itself.
/// </summary>
TTransferProtocol = (Http, Https, Ws, Wss);
private
FSwaggerVersion: string;
FInfo: TAPIDocInfo;
FPaths: TList<TAPIDocPath>;
FHost: string;
FBasePath: string;
FDefinitions: string;
function GetPaths: TArray<TAPIDocPath>;
procedure WriteJsonDefinitions(const ADefinitions: string; const AJSONWriter: TJSONWriter);
public
constructor Create(const AHost, ABasePath: string);
destructor Destroy; override;
function GetAPIDocYaml: string;
procedure WriteAPIDocJson(const AWriter: TJsonTextWriter);
function AddPath(const AAPIDocPath:TAPIDocPath): Boolean;
procedure SortPaths;
//TO-DO
//securityDefinitions:
//definitions:
// class function WriteAPIDoc: TStringList;
property Paths: TArray<TAPIDocPath> read GetPaths;
property Definitions: string read FDefinitions write FDefinitions;
class function GetDataTypeAsString(AType: TAPIDoc.TPrimitiveFormat): string; overload;
class function GetDataTypeAsString(AType: TAPIDoc.TPrimitiveType): string; overload;
class function ReplaceStar(AItem: string; IsPath: Boolean = False): string;
end;
TAPIDocPath = class
private
FPath: string;
FResourceName: string;
FPathItems: TObjectList<TAPIDocPathItem>;
function GetPathItems: TArray<TAPIDocPathItem>;
function GetPathInfo: TArray<string>;
procedure WritePathInfo(const ABuilder: TJSONObjectBuilder);
function GetPath: string;
public
constructor Create(const APath, AResourceName: string);
destructor Destroy; override;
function AddPathItem(const AAPIDocPathItem: TAPIDocPathItem): Boolean;
property PathItems: TArray<TAPIDocPathItem> read GetPathItems;
property Path: string read GetPath;
end;
TAPIDocPathItem = class
const
ApplicationId = 'X-Embarcadero-Application-Id';
AppSecret = 'X-Embarcadero-App-Secret';
MasterSecret = 'X-Embarcadero-Master-Secret';
private
FVerb: TEndpointRequest.TMethod;
FTags: string;
FSummary: string;
FDescription: string;
FOperationId: string;
FProduces: string;
FConsumes: string;
FParameters: TArray<TAPIDocParameter>;
FResponses: TArray<TAPIDocResponse>;
function GetAuthoritationHeaderParams: TArray<string>;
procedure WriteAuthoritationHeaderParams(const ABuilder: TJSONObjectBuilder);
public
constructor Create(AHTTPMethod: TEndpointRequest.TMethod; const AOperationID: string;
const AAttribute: EndPointRequestSummaryAttribute; const AAPIDocResponses: TArray<TAPIDocResponse>;
const AAPIDocParameters: TArray<TAPIDocParameter>);
destructor Destroy; override;
function GetMethodInfo: TArray<string>;
procedure WriteMethodInfo(const ABuilder: TJSONObjectBuilder);
end;
TAPIDocParameter = class
public type
TParameterIn = (Path, Query, Header, Body, formData);
private
FName: string;
FIn: TParameterIn;
FDescription: string;
FRequired: Boolean;
FIsReference: Boolean;
FType: TAPIDoc.TPrimitiveType;
FItemType: TAPIDoc.TPrimitiveType;
FFormat: TAPIDoc.TPrimitiveFormat;
FSchema: string;
FReference: string;
function GetParamAsString: string;
function GetName: string;
public
constructor Create(const AAttribute: EndPointRequestParameterAttribute);
function GetParamInfo: TArray<string>;
procedure WriteParamInfo(const ABuilder: TJSONObjectBuilder);
property Name: string read GetName;
end;
TAPIDocParameterHelper = class helper for TAPIDocParameter
public
procedure Assign(ASource: TAPIDocParameter);
end;
TAPIDocResponse = class
FCode: integer;
FDescription: string;
FSchema: string;
FIsReference: Boolean;
FReference: string;
FType: TAPIDoc.TPrimitiveType;
FFormat: TAPIDoc.TPrimitiveFormat;
FExamples: string;
FRef: string;
public
constructor Create(const AAttribute: EndPointResponseDetailsAttribute);
function GetResponseInfo: TArray<string>;
procedure WriteResponseInfo(const ABuilder: TJSONObjectBuilder);
end;
TAPIDocResponseHelper = class helper for TAPIDocResponse
public
procedure Assign(ASource: TAPIDocResponse);
end;
/// <summary>
/// Attribute for EMS resource class method
/// Description of a method
/// </summary>
EndPointRequestSummaryAttribute = class(TEndpointCustomAttribute)
private
FTags: string;
FSummary: string;
FDescription: string;
// FOperationId: String;
FProduces: string;
FConsume: string;
public
/// <summary>
/// Attribute for EMS resource class method
/// Description of a method
/// </summary>
/// <param name="AMethod">
/// An endpoint publisher class method
/// </param>
/// <param name="ATags">
/// Define a Tag
/// </param>
/// <param name="ASummary">
/// A Method Title
/// </param>
/// <param name="ADescription">
/// A Method Description
/// </param>
/// <param name="AProduces">
/// A MIME type the APIs can produce. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under Mime Types.
/// </param>
/// <param name="AConsume">
/// A MIME type the APIs can consume. This is global to all APIs but can be overridden on specific API calls. Value MUST be as described under Mime Types
/// </param>
constructor Create(const AMethod, ATags, ASummary, ADescription, AProduces, AConsume: string); overload;
constructor Create(const ATags, ASummary, ADescription, AProduces, AConsume: string); overload;
property Tags: string read FTags;
property Summary: string read FSummary;
property Description: string read FDescription;
// property OperationId: String read FOperationId;
property Produces: string read FProduces;
property Consume: string read FConsume;
end;
/// <summary>
/// Attribute for EMS resource class metod
/// Description of the parameters used in a request
/// </summary>
EndPointRequestParameterAttribute = class(TEndpointCustomAttribute)
private
FName: string;
FIn: TAPIDocParameter.TParameterIn;
FDescription: string;
FRequired: Boolean;
FJSONSchema: string;
FReference: string;
FType: TAPIDoc.TPrimitiveType;
FItemType: TAPIDoc.TPrimitiveType;
FFormat: TAPIDoc.TPrimitiveFormat;
public
/// <summary>
/// Attribute for EMS resource class metod
/// Description of the parameters used in a request
/// A unique parameter is defined by a combination of a name and location.
/// There are five possible parameter types. <c>'Path</c>', <c>'Query</c>', <c>'Header</c>', <c>'Body</c>', <c>'Form</c>'
/// </summary>
/// <param name="AMethod">
/// An endpoint publisher class method
/// </param>
/// <param name="AIn">
/// The location of the parameter: <c>'Path</c>', <c>'Query</c>', <c>'Header</c>', <c>'Body</c>', <c>'Form</c>'
/// </param>
/// <param name="AName">
/// The name of the parameter. Parameter names are case sensitive. if param inBody name MUST be <c>'body</c>'
/// If in is "path", the name field MUST correspond to the associated path segment from the path field in the Paths Object.
/// For all other cases, the name corresponds to the parameter name used based on the in property
/// </param>
/// <param name="ADescription">
/// A brief description of the parameter. This could contain examples of use. GFM syntax can be used for rich text representation.
/// </param>
/// <param name="ARequired">
/// Determines whether this parameter is mandatory. If the parameter is in "path", this property is required and its value MUST be true.
/// Otherwise, the property MAY be included and its default value is false.
/// </param>
/// <param name="AType">
/// The type of the parameter.
/// Other Value than Body: the value MUST be one of <c>'spArray'</c>, <c>'spBoolean'</c>, <c>'spInteger'</c>, <c>'spNumber'</c>, <c>'spNull'</c>, <c>'spObject'</c>, <c>'spString'</c>, <c>'spFile'</c>.
/// If type is "file", the consumes MUST be either "multipart/form-data" or " application/x-www-form-urlencoded" and the parameter MUST be in "formData".
/// In Body: JSONSchema or Reference required.
/// </param>
/// <param name="AFormat">
/// The extending format for the previously mentioned Type, <c>'None'</c>, <c>'Int32'</c>, <c>'Int64'</c>, <c>'Float'</c>, <c>'Double'</c>, <c>'Byte'</c>, <c>'Date'</c>, <c>'DateTime'</c>, <c>'Password'</c>.
/// </param>
/// <param name="AItemType">
/// Required if type is <c>"array"</c>. Describes the type of items in the array.
/// </param>
/// <param name="AJSONScheme">
/// The Schema of the Primitive sent to the server. A definition of the body request structure.
/// If Type is Array or Object a Schema can be defined
/// For example:
/// - in JSON format {"type": "object","additionalProperties": {"type": "string"}}
/// - in YAML format
/// type: object
/// additionalProperties:
/// type: string
/// </param>
/// <param name="AReference">
/// The Schema Definition of the Primitive sent to the server. A definition of the body request structure.
/// If Type is Array or Object a Schema Definitions can be defined
/// For example: '#/definitions/pet'
/// </param>
constructor Create(const AMethod: string; AIn: TAPIDocParameter.TParameterIn;
const AName, ADescription: string; const ARequired: boolean;
AType: TAPIDoc.TPrimitiveType; AFormat: TAPIDoc.TPrimitiveFormat;
AItemType: TAPIDoc.TPrimitiveType; const AJSONScheme, AReference: string); overload;
constructor Create(AIn: TAPIDocParameter.TParameterIn;
const AName, ADescription: string; const ARequired: boolean;
AType: TAPIDoc.TPrimitiveType; AFormat: TAPIDoc.TPrimitiveFormat;
AItemType: TAPIDoc.TPrimitiveType; const AJSONScheme, AReference: string); overload;
property Name: string read FName;
property ParamIn: TAPIDocParameter.TParameterIn read FIn;
property Description: string read FDescription;
property Required: Boolean read FRequired;
property ParamType: TAPIDoc.TPrimitiveType read FType;
property ItemType: TAPIDoc.TPrimitiveType read FItemType;
property ItemFormat: TAPIDoc.TPrimitiveFormat read FFormat;
property JSONSchema: string read FJSONSchema;
property Reference: string read FReference;
end;
/// <summary>
/// Attribute for EMS resource class methos
/// Description of the request responses
/// </summary>
EndPointResponseDetailsAttribute = class(TEndpointCustomAttribute)
private
FCode: Integer;
FDescription: string;
FSchema: string;
FType: TAPIDoc.TPrimitiveType;
FFormat: TAPIDoc.TPrimitiveFormat;
FReference: string;
public
/// <summary>
/// Response Detail Attribute
/// Description of the request response
/// </summary>
/// <param name="AMethod">
/// An endpoint publisher class method
/// </param>
/// <param name="ACode">
/// The Response Code
/// </param>
/// <param name="ADescription">
/// Description of the response code
/// </param>
/// <param name="AType">
/// The Type of the Primitive returned.
/// Primitive data types in the Swagger Specification are based on the types supported by the JSON-Schema Draft 4.
/// http://json-schema.org/latest/json-schema-core.html#anchor8
/// An additional primitive data type "file" is used by the Parameter Object and the Response Object
/// to set the parameter type or the response as being a file.
/// For example: <c>'spArray'</c>, <c>'spBoolean'</c>, <c>'spInteger'</c>, <c>'spNumber'</c>, <c>'spNull'</c>, <c>'spObject'</c>, <c>'spString'</c>, <c>'spFile'</c>.
/// </param>
/// <param name="AFormat">
/// The Format of the Primitive returned
/// For example: <c>'None'</c>, <c>'Int32'</c>, <c>'Int64'</c>, <c>'Float'</c>, <c>'Double'</c>, <c>'Byte'</c>, <c>'Date'</c>, <c>'DateTime'</c>, <c>'Password'</c>.
/// </param>
/// <param name="ASchema">
/// The Schema of the Primitive returned. A definition of the response structure.
/// If Type is Array or Object a Schema can be defined
/// For example:
/// - in JSON format {"type": "object","additionalProperties": {"type": "string"}}
/// - in YAML format
/// type: object
/// additionalProperties:
/// type: string
/// </param>
/// <param name="AReference">
/// The Schema Definition of the Primitive returned. A definition of the response structure.
/// If Type is Array or Object a Schema Definitions can be defined
/// For example: '#/definitions/pet'
/// </param>
constructor Create(const AMethod: string; ACode: Integer; const ADescription: string; AType: TAPIDoc.TPrimitiveType; AFormat: TAPIDoc.TPrimitiveFormat; const ASchema, AReference: string); overload;
constructor Create(ACode: Integer; const ADescription: string; AType: TAPIDoc.TPrimitiveType; AFormat: TAPIDoc.TPrimitiveFormat; const ASchema, AReference: string); overload;
property Code: Integer read FCode;
property Description: string read FDescription;
property Schema: string read FSchema;
property Reference: string read FReference;
property PrimitiveType: TAPIDoc.TPrimitiveType read FType;
property PrimitiveFormat: TAPIDoc.TPrimitiveFormat read FFormat;
end;
/// <summary>
/// Attribute for EMS resource class
/// Definition of Objects for the API YAML version
/// </summary>
EndPointObjectsYAMLDefinitionsAttribute = class(TResourceCustomAttribute)
private
FObjects: string;
public
constructor Create(const Objects: string);
property Objects: string read FObjects;
end;
/// <summary>
/// Attribute for EMS resource class
/// Definition of Objects for the API JSON version
/// </summary>
EndPointObjectsJSONDefinitionsAttribute = class(TResourceCustomAttribute)
private
FObjects: string;
public
constructor Create(const Objects: string);
property Objects: string read FObjects;
end;
/// <summary>
/// Attribute for EMS resource class
/// Specifies that endpoints and resources are skipped by validating Tenant during authorization.
/// </summary>
AllowAnonymousTenantAttribute = class(TEndpointCustomAttribute)
public
constructor Create(const AMethod: string); overload;
constructor Create; overload;
end;
EndPointProduceAttribute = class(TEndpointCustomAttribute)
private
FTypes: string;
public
constructor Create(const AMethod: string; const ATypes: string); overload;
constructor Create(const ATypes: string); overload;
property Types: string read FTypes;
end;
EndPointConsumeAttribute = class(EndPointProduceAttribute);
EndPointMethodAttribute = class(TEndpointCustomAttribute)
private
FHTTPMethod: TEndpointRequest.TMethod;
public
constructor Create(const AMethod: string; const AHTTPMethod: TEndpointRequest.TMethod); overload;
constructor Create(const AHTTPMethod: TEndpointRequest.TMethod); overload;
property HTTPMethod: TEndpointRequest.TMethod read FHTTPMethod;
end;
TTenantAuthorization = (Default, Full, SkipAll);
TEMSTypeInfoResource = class(TEMSCommonResource)
private type
TConstructorKind = (Simple, Component);
TResourceMethod = record
public type
TSignatureKind = (Unknown, Standard);
private
FRttiField: TRTTIField;
FRttiMethod: TRTTIMethod;
FHTTPMethod: TEndpointRequest.TMethod;
FName: string;
FURLSuffix: string;
FRttiParameters: TArray<TRTTIParameter>;
FRttiReturnType: TRTTIType;
FSignatureKind: TSignatureKind;
FPathItem: TAPIDocPathItem;
FTenantAuthorization: TTenantAuthorization;
FProduce: string;
FConsume: string;
public
property Name: string read FName;
property TenantAuthorization: TTenantAuthorization read FTenantAuthorization;
constructor Create(const AName: string; const ARttiField: TRTTIField; const ARttiMethod: TRTTIMethod; AHTTPMethod: TEndpointRequest.TMethod;
const ABaseURLSuffix: string; const APathItem: TAPIDocPathItem = nil; ATenantAuthorization: TTenantAuthorization = TTenantAuthorization.Full;
const AProduce: string = ''; const AConsume: string = '');
end;
private
FRttiContext: TRttiContext; // Hold references
FRttiConstructor: TRTTIMethod;
FConstructorKind: TConstructorKind;
FRttiType: TRTTIType;
FMethodList: TList<TResourceMethod>;
FAttributes: TEMSResourceAttributes;
FAPIDocPaths: TObjectList<TAPIDocPath>;
FYAMLDefinitions: string;
FJSONDefinitions: string;
FTenantAuthorization: TTenantAuthorization;
procedure InternalScanResource(ARttiObj: TRttiNamedObject;
out AResourceName: string; out ATenantAuthorization: TTenantAuthorization);
procedure ScanResource(out AResourceName: string);
procedure ScanConstructor;
procedure InternalScanMethods(const ARTTIField: TRTTIField;
const AFieldAttributes: TEMSResourceAttributes; const ARTTIMethods: TArray<TRTTIMethod>);
procedure ScanMethods;
procedure ScanFields;
procedure ScanObjectsDefinitions(const AResourceName: string);
function CreateInstance: TObject;
procedure CreateEndPoints;
function GetAPIDocPaths: TArray<TAPIDocPath>;
function GetMethodTenantAuthorization(const AMethod: string): TTenantAuthorization;
public
constructor Create(const ATypeInfo: PTypeInfo); overload;
constructor Create(const ATypeInfo: PTypeInfo; const AAttributes: TEMSResourceAttributes); overload;
destructor Destroy; override;
property YAMLDefinitions: string read FYAMLDefinitions;
property JSONDefinitions: string read FJSONDefinitions;
property APIDocPaths: TArray<TAPIDocPath> read GetAPIDocPaths;
property TenantAuthorization: TTenantAuthorization read FTenantAuthorization;
property MethodTenantAuthorization[const AMethod: string]: TTenantAuthorization read GetMethodTenantAuthorization;
end;
TEMSResourceAttributes = class
private
FResourceName: string;
FEndpointName: TDictionary<string, string>;
FResourceSuffix: TDictionary<string, string>;
FResponseDetails: TObjectDictionary<string, TList<TAPIDocResponse>>;
FRequestSummary: TObjectDictionary<string, EndPointRequestSummaryAttribute>;
FRequestParameters: TObjectDictionary<string, TList<TAPIDocParameter>>;
FYAMLDefinitions: TDictionary<string, string>;
FJSONDefinitions: TDictionary<string, string>;
FResourceTenantAuthorizations: TDictionary<string, TTenantAuthorization>;
FEndPointTenantAuthorizations: TDictionary<string, TTenantAuthorization>;
FEndPointProduce: TDictionary<string, string>;
FEndPointConsume: TDictionary<string, string>;
FEndPointHTTPMethod: TDictionary<string, TEndpointRequest.TMethod>;
function GetEndPointName(const AMethod: string): string; overload;
function GetResourceSuffix(const AMethod: string): string; overload;
function GetResponseDetails(const AMethod: string): TArray<TAPIDocResponse>;
function GetRequestSummary(const AMethod: string): EndPointRequestSummaryAttribute;
function GetRequestParameters(const AMethod: string): TArray<TAPIDocParameter>;
function GetYAMLDefinitions(const AResourceName: string): string;
function GetJSONDefinitions(const AResourceName: string): string;
procedure SetEndPointName(const AMethod, Value: string);
procedure SetResourceSuffix(const AMethod, Value: string);
procedure SetRequestSummary(const AMethod: string; ARequestSummaryAttribute: EndPointRequestSummaryAttribute);
procedure SetYAMLDefinitions(const AResourceName, Value: string);
procedure SetJSONDefinitions(const AResourceName, Value: string);
function GetEndPointTenantAuthorization(const AMethod: string): TTenantAuthorization;
function GetResourceTenantAuthorization(const AResourceName: string): TTenantAuthorization;
procedure SetEndPointTenantAuthorization(const AMethod: string; const Value: TTenantAuthorization);
procedure SetResourceTenantAuthorization(const AResourceName: string; const Value: TTenantAuthorization);
function GetEndPointProduce(const AMethod: string): string;
procedure SetEndPointProduce(const AMethod, AValue: string);
function GetEndPointConsume(const AMethod: string): string;
procedure SetEndPointConsume(const AMethod, AValue: string);
function GetEndPointHTTPMethod(const AMethod: string): TEndpointRequest.TMethod;
procedure SetEndPointHTTPMethod(const AMethod: string; const AValue: TEndpointRequest.TMethod);
public
constructor Create;
destructor Destroy; override;
procedure LoadFromRtti(AMember: TRttiMember);
procedure Clear;
procedure AddResponseDetail(const AMethod: string; const AResponseDetailAttribute: EndPointResponseDetailsAttribute);
procedure AddRequestParameter(const AMethod: string; const ARequestParameterAttribute: EndPointRequestParameterAttribute);
property ResourceName: string read FResourceName write FResourceName;
property ResourceTenantAuthorization[const AResourceName: string]: TTenantAuthorization read GetResourceTenantAuthorization write SetResourceTenantAuthorization;
property YAMLDefinitions[const AResourceName: string]: string read GetYAMLDefinitions write SetYAMLDefinitions;
property JSONDefinitions[const AResourceName: string]: string read GetJSONDefinitions write SetJSONDefinitions;
property EndPointName[const AMethod: string]: string read GetEndPointName write SetEndPointName;
property ResourceSuffix[const AMethod: string]: string read GetResourceSuffix write SetResourceSuffix;
property EndPointProduce[const AMethod: string]: string read GetEndPointProduce write SetEndPointProduce;
property EndPointConsume[const AMethod: string]: string read GetEndPointConsume write SetEndPointConsume;
property EndPointHTTPMethod[const AMethod: string]: TEndpointRequest.TMethod read GetEndPointHTTPMethod write SetEndPointHTTPMethod;
property EndPointTenantAuthorization[const AMethod: string]: TTenantAuthorization read GetEndPointTenantAuthorization write SetEndPointTenantAuthorization;
property ResponseDetails[const AMethod: string]: TArray<TAPIDocResponse> read GetResponseDetails;
property RequestSummary[const AMethod: string]: EndPointRequestSummaryAttribute read GetRequestSummary write SetRequestSummary;
property RequestParameters[const AMethod: string]: TArray<TAPIDocParameter> read GetRequestParameters;
end;
procedure RegisterResource(const TypeInfo: PTypeInfo); overload;
procedure RegisterResource(const TypeInfo: PTypeInfo; const AAttributes: TEMSResourceAttributes); overload;
implementation
uses EMS.Services, EMS.Consts, System.JSON, System.JSON.Readers,
{$IFDEF MACOS}
Macapi.CoreFoundation,
{$ENDIF}
System.Generics.Defaults, System.Variants, System.NetConsts;
const
TAPIDocPathItemTenantId = 'X-Embarcadero-Tenant-Id';
TAPIDocPathItemTenantSecret = 'X-Embarcadero-Tenant-Secret';
function LogResource(const AResource: TEMSResource; AJSON: TJSONObject): Boolean;
const
CMethodNames: array[TEndpointRequest.TMethod] of string =
('Get', 'Put', 'Post', 'Delete', 'Patch', 'Other');
var
LArray: TJSONArray;
LEndpoint: TEMSResourceEndPoint;
LObject: TJSONObject;
LParam: TEMSEndPointSegment;
LPath: string;
LRes: TEMSTypeInfoResource;
S: string;
begin
Result := AResource is TEMSTypeInfoResource;
if not Result then
Exit;
LRes := TEMSTypeInfoResource(AResource);
AJSON.AddPair('name', LRes.Name);
LArray := TJSONArray.Create;
for LEndpoint in LRes.FEndpoints do
begin
LObject := TJSONObject.Create;
LObject.AddPair('name', LEndpoint.Name);
LObject.AddPair('method', CMethodNames[LEndpoint.Method]);
LPath := LRes.FBaseURL;
for LParam in LEndpoint.SegmentParameters do
begin
if not LPath.EndsWith('/') then
LPath := LPath + '/';
if LParam is TEMSEndPointSegmentConstant then
LPath := LPath + TEMSEndPointSegmentConstant(LParam).Value
else if LParam is TEMSEndPointSegmentParameter then
LPath := LPath + '{' + TEMSEndPointSegmentParameter(LParam).Name + '}';
end;
LObject.AddPair('path', LPath);
if (LEndpoint.ProduceList <> nil) and (LEndpoint.ProduceList.Count > 0) then
begin
S := '';
S := LEndpoint.ProduceList.ToString;
LObject.AddPair('produce', S);
end;
if (LEndpoint.ConsumeList <> nil) and (LEndpoint.ConsumeList.Count > 0) then
begin
S := '';
S := LEndpoint.ConsumeList.ToString;
LObject.AddPair('consume', S);
end;
LArray.Add(LObject);
end;
AJSON.AddPair('endpoints', LArray);
end;
procedure RegisterResource(const TypeInfo: PTypeInfo); overload;
var
LResource: TEMSTypeInfoResource;
begin
LResource := TEMSTypeInfoResource.Create(TypeInfo);
try
TEMSEndpointManager.Instance.RegisterResource(LResource)
except
LResource.Free;
raise;
end;
end;
procedure RegisterResource(const TypeInfo: PTypeInfo; const AAttributes: TEMSResourceAttributes); overload;
var
LResource: TEMSTypeInfoResource;
begin
LResource := TEMSTypeInfoResource.Create(TypeInfo, AAttributes);
try
TEMSEndpointManager.Instance.RegisterResource(LResource)
except
LResource.Free;
raise;
end;
end;
{ TEndpointCustomAttribute }
constructor TEndpointCustomAttribute.Create(const AMethod: string);
begin
inherited Create;
FMethod := AMethod;
end;
{ TEMSCommonResource }
constructor TEMSCommonResource.Create(const AResourceName: string);
begin
FResourceName := AResourceName;
FBaseURL := AResourceName.ToLower;
FEndPoints := TObjectList<TEMSResourceEndPoint>.Create;
FEndpointsDict := TDictionary<string, TEMSResourceEndPoint>.Create;
FBaseURLSegmentCount := TEMSEndPointSegmentService.CountSegments(FBaseURL);
FRootNode := TTreeNode.Create(TEndpointRequest.TMethod.Other, nil);
end;
destructor TEMSCommonResource.Destroy;
begin
FRootNode.Free;
FEndPoints.Free;
FEndpointsDict.Free;
inherited;
end;
function TEMSCommonResource.EnumEndPoints(const ACallback: TFindCallback): Boolean;
var
LEndPoint: TEMSResourceEndPoint;
begin
Result := False;
for LEndpoint in FEndpoints do
begin
ACallback(LEndpoint, Result);
if Result then
Break;
end;
end;
function TEMSCommonResource.FindEndPoint(const AName: string): TEMSResourceEndPoint;
begin
Result := FEndpointsDict.Items[AName];
end;
function TEMSCommonResource.GetEndpointNames: TArray<string>;
var
LList: TList<string>;
begin
LList := TList<string>.Create;
try
EnumEndPoints(
procedure(const AEndPoint: TEMSResourceEndPoint; var ADone: Boolean)
begin
LList.Add(AEndpoint.Name)
end);
Result := LList.ToArray;
finally
LList.Free;
end;
end;
function TEMSCommonResource.GetName: string;
begin
Result := FResourceName;
end;
function TEMSCommonResource.IsBaseURL(const ABaseURL: string): Boolean;
begin
Result := SameText(ABaseURL, '/' + FBaseURL) or ABaseURL.ToLower.StartsWith('/' + FBaseURL + '/');
end;
{ TEMSResourceEndPoint }
procedure TEMSResourceEndPoint.DoAuthorizeRequest(const AContext: TEndpointContext);
begin
// Do nothing
end;
function TEMSResourceEndPoint.GetFullName: string;
begin
if FRoot <> nil then
Result := FRoot.Name + '.' + Name
end;
constructor TEMSResourceEndPoint.Create(const AOwner: TEMSCommonResource);
begin
FRoot := AOwner;
FRoot.FEndpoints.Add(Self);
end;
destructor TEMSResourceEndPoint.Destroy;
begin
Assert((FRoot.FEndpoints = nil) or not FRoot.FEndpoints.Contains(Self));
inherited;
end;
{ TEMSResourceEndPointSuffix }
procedure TEMSResourceEndPointSuffix.DoAuthorizeRequest(const AContext: TEndpointContext);
procedure ValidateTenantAuthorization(TenantAuthorization: TTenantAuthorization);
begin
if (AContext.Tenant = nil) and (TenantAuthorization = TTenantAuthorization.Full) then
EEMSHTTPError.RaiseUnauthorized(sInvalidTenant);
end;
function GetResultTenantAuthorization(ResourceTenantAuth, MethodTenantAuth: TTenantAuthorization): TTenantAuthorization;
begin
case ResourceTenantAuth of
TTenantAuthorization.Default,
TTenantAuthorization.Full:
Result := MethodTenantAuth;
else
{TTenantAuthorization.SkipAll:}
Result := TTenantAuthorization.SkipAll;
end;
end;
var
LACL: TEMSEndpointAuthorization.TACL;
LAuthorize: Boolean;
LResourceInfo: TEMSTypeInfoResource;
begin
if FRoot is TEMSTypeInfoResource then
begin
LResourceInfo := TEMSTypeInfoResource(FRoot);
ValidateTenantAuthorization(GetResultTenantAuthorization(
LResourceInfo.TenantAuthorization, LResourceInfo.MethodTenantAuthorization[Name]));
end;
LAuthorize := TEMSEndpointAuthorization.Instance.FindACL(FullName, LACL);
if not LAuthorize then
LAuthorize := TEMSEndpointAuthorization.Instance.FindACL(FRoot.Name, LACL);
if LAuthorize then
TEMSEndpointAuthorization.Instance.Authorize(AContext, LACL);
end;
constructor TEMSResourceEndPointSuffix.Create(const AOwner: TEMSCommonResource;
const AName, AURLSuffix: string; const AMethod: TEndpointRequest.TMethod;
const AProduce, AConsume: string; const AHandlerProc: THandlerProc);
begin
inherited Create(AOwner);
FSegmentParameters := TEMSEndPointSegmentList.Create;
SetName(AName);
FURLSuffix := AURLSuffix;
FMethod := AMethod;
if AProduce <> '' then
FProduceList := TAcceptValueList.Create(AProduce);
if AConsume <> '' then
FConsumeList := TAcceptValueList.Create(AConsume);
FHandlerProc := AHandlerProc;
TEMSEndPointSegmentService.ExtractSegments(FURLSuffix, FSegmentParameters);
end;
destructor TEMSResourceEndPointSuffix.Destroy;
begin
FSegmentParameters.Free;
FProduceList.Free;
FConsumeList.Free;
inherited;
end;
function TEMSResourceEndPointSuffix.ScanSegmentParameters(
const AContext: TEndpointContext; const ACallback: TSegmentParamCallback): Boolean;
var
LRequestSegmentIndex: Integer;
LSegmentParameter: TEMSEndPointSegment;
LSegmentParameterIndex: Integer;
LValue: string;
begin
Result := True;
LSegmentParameterIndex := 0;
LRequestSegmentIndex := FRoot.BaseURLSegmentCount;
while LRequestSegmentIndex < AContext.Request.Segments.Count do
begin
Assert(LSegmentParameterIndex < FSegmentParameters.Count);
if LSegmentParameterIndex < FSegmentParameters.Count then
begin
LSegmentParameter := FSegmentParameters.Items[LSegmentParameterIndex];
if LSegmentParameter is TEMSEndPointSegmentParameter then
begin
if Assigned(ACallback) then
if TEMSEndPointSegmentParameter(LSegmentParameter).Name = '*' then
begin
LValue := '';
while LRequestSegmentIndex < AContext.Request.Segments.Count do
begin
LValue := LValue + AContext.Request.Segments[LRequestSegmentIndex];
Inc(LRequestSegmentIndex);
end;
ACallback(TEMSEndPointSegmentParameter(LSegmentParameter), LValue);
Break;
end
else
ACallback(TEMSEndPointSegmentParameter(LSegmentParameter),
AContext.Request.Segments[LRequestSegmentIndex]);
end
else if LSegmentParameter is TEMSEndPointSegmentWildCard then
Break;
end;
Inc(LRequestSegmentIndex);
Inc(LSegmentParameterIndex);
end;
end;
procedure TEMSResourceEndPointSuffix.DoHandleRequest(const AContext: TEndpointContext);
begin
if Assigned(FHandlerProc) then
begin
if FSegmentParameters.Count > 0 then
ScanSegmentParameters(AContext,
procedure(ASegment: TEMSEndPointSegmentParameter; AValue: string)
var
LValue: string;
begin
if AValue.EndsWith('/') then
LValue := AValue.SubString(0, AValue.Length - 1)
else
LValue := AValue;
AContext.Request.Params.Add(ASegment.Name, LValue);
end);
if ConsumeList <> nil then
AContext.Negotiation.ConsumeList.Intersect(ConsumeList);
if ProduceList <> nil then
AContext.Negotiation.ProduceList.Intersect(ProduceList);
FHandlerProc(Self, AContext, AContext.Request, AContext.Response);
end;
end;
function TEMSResourceEndPointSuffix.GetMethod: TEndpointRequest.TMethod;
begin
Result := FMethod;
end;
function TEMSResourceEndPointSuffix.GetProduceList: TAcceptValueList;
begin
Result := FProduceList;
end;
function TEMSResourceEndPointSuffix.GetConsumeList: TAcceptValueList;
begin
Result := FConsumeList;
end;
function TEMSResourceEndPointSuffix.GetName: string;
begin
Result := FName;
end;
procedure TEMSResourceEndPointSuffix.SetName(const AName: string);
begin
if FName <> '' then
FRoot.FEndpointsDict.Remove(FName);
FName := AName;
if FName <> '' then
FRoot.FEndpointsDict.Add(FName, Self);
end;
function TEMSResourceEndPointSuffix.GetSegmentParameters: TEMSEndPointSegmentList;
begin
Result := FSegmentParameters;
end;
{ TEMSEndPointSegmentList }
constructor TEMSEndPointSegmentList.Create;
begin
FList := TObjectList<TEMSEndPointSegment>.Create;
end;
destructor TEMSEndPointSegmentList.Destroy;
begin
FList.Free;
inherited;
end;
function TEMSEndPointSegmentList.GetCount: Integer;
begin
Result := FList.Count;
end;
function TEMSEndPointSegmentList.GetEnumerator: TEnumerator<TEMSEndPointSegment>;
begin
Result := FList.GetEnumerator;
end;
function TEMSEndPointSegmentList.GetItem(I: Integer): TEMSEndPointSegment;
begin
Result := FList[I];
end;
{ TEMSEndPointSegment }
constructor TEMSEndPointSegment.Create(const AOwner: TEMSEndPointSegmentList);
begin
FOwner := AOwner;
AOwner.FList.Add(Self);
end;
destructor TEMSEndPointSegment.Destroy;
begin
Assert((FOwner.FList = nil) or not FOwner.FList.Contains(Self));
inherited;
end;
{ TEMSEndPointSegmentParameter }
constructor TEMSEndPointSegmentParameter.Create(
const AOwner: TEMSEndPointSegmentList; const AName: string);
begin
inherited Create(AOwner);
FName := AName;
end;
{ TEMSEndPointSegmentConstant }
constructor TEMSEndPointSegmentConstant.Create(
const AOwner: TEMSEndPointSegmentList; const AValue: string);
begin
inherited Create(AOwner);
FValue := AValue;
end;
{ TEMSEndPointSegmentService }
class procedure TEMSEndPointSegmentService.ExtractSegments(
const AString: string; const AList: TEMSEndPointSegmentList);
begin
TEMSServices.GetService<IEMSEndPointSegmentsService>.ExtractSegments(AString, AList);
end;
class function TEMSEndPointSegmentService.CountSegments(
const AString: string): Integer;
var
LIntf: IInterface;
begin
Result := 0;
LIntf := EMSServices.GetService(IEMSEndPointSegmentsService);
if LIntf <> nil then
Result := IEMSEndPointSegmentsService(LIntf).CountSegments(AString);
end;
{ TEMSTypeInfoResource }
constructor TEMSTypeInfoResource.Create(const ATypeInfo: PTypeInfo);
var
LResourceName: string;
begin
FMethodList := TList<TResourceMethod>.Create;
FAPIDocPaths := TObjectList<TAPIDocPath>.Create;
FRttiType := FRttiContext.GetType(ATypeInfo);
ScanResource(LResourceName);
Assert(LResourceName <> '');
if (FAttributes <> nil) and ('' <> FAttributes.ResourceName) then
LResourceName := FAttributes.ResourceName;
inherited Create(LResourceName);
ScanConstructor;
ScanMethods;
ScanFields;
ScanObjectsDefinitions(LResourceName);
CreateEndpoints;
BuildTree;
end;
constructor TEMSTypeInfoResource.Create(const ATypeInfo: PTypeInfo;
const AAttributes: TEMSResourceAttributes);
begin
FAttributes := AAttributes;
Create(ATypeInfo);
end;
destructor TEMSTypeInfoResource.Destroy;
begin
FMethodList.Free;
FAPIDocPaths.Free;
FAttributes.Free;
inherited;
end;
procedure TEMSTypeInfoResource.InternalScanResource(ARttiObj: TRttiNamedObject;
out AResourceName: string; out ATenantAuthorization: TTenantAuthorization);
var
LAttribute: TCustomAttribute;
begin
Assert(ARttiObj <> nil);
AResourceName := '';
ATenantAuthorization := TTenantAuthorization.Full;
for LAttribute in ARttiObj.GetAttributes do
begin
if LAttribute is ResourceNameAttribute then
AResourceName := ResourceNameAttribute(LAttribute).Name
else if LAttribute is AllowAnonymousTenantAttribute then
ATenantAuthorization := TTenantAuthorization.SkipAll;
end;
if AResourceName = '' then
begin
AResourceName := ARttiObj.Name;
if (ARttiObj is TRttiType) and
AResourceName.StartsWith('T') and (AResourceName.Length > 1) then
AResourceName := AResourceName.Substring(1);
end;
if FAttributes <> nil then
ATenantAuthorization := FAttributes.ResourceTenantAuthorization[AResourceName];
end;
procedure TEMSTypeInfoResource.ScanResource(out AResourceName: string);
begin
InternalScanResource(FRttiType, AResourceName, FTenantAuthorization);
end;
procedure TEMSTypeInfoResource.ScanConstructor;
var
LRTTIMethod: TRTTIMethod;
LRTTIParameters: TArray<TRTTIParameter>;
LSimpleConstructor: TRTTIMethod;
LComponentConstructor: TRTTIMethod;
begin
Assert(FRttiType <> nil);
LSimpleConstructor := nil;
LComponentConstructor := nil;
for LRttiMethod in FRttiType.GetMethods do
begin
if LRttiMethod.HasExtendedInfo and LRttiMethod.IsConstructor and SameText(LRttiMethod.Name, 'create') then
begin
LRttiParameters := LRttiMethod.GetParameters;
if Length(LRttiParameters) = 0 then
LSimpleConstructor := LRttiMethod
else if (Length(LRttiParameters) = 1) and (LRTTIParameters[0].ParamType.TypeKind = tkClass) and
(LRttiParameters[0].ParamType.QualifiedName = 'System.Classes.TComponent') then
begin
LComponentConstructor := LRttiMethod;
break;
end;
end;
end;
if LComponentConstructor <> nil then
begin
FRTTIConstructor := LComponentConstructor;
FConstructorKind := TConstructorKind.Component;
end
else if LSimpleConstructor <> nil then
begin
FRTTIConstructor := LSimpleConstructor;
FConstructorKind := TConstructorKind.Simple;
end
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
Format(sConstructorNotFound, [FRTTIType.QualifiedName]));
end;
function TEMSTypeInfoResource.GetAPIDocPaths: TArray<TAPIDocPath>;
begin
Result := FAPIDocPaths.ToArray;
end;
function TEMSTypeInfoResource.GetMethodTenantAuthorization(
const AMethod: string): TTenantAuthorization;
var
LMethod: TResourceMethod;
begin
Result := TTenantAuthorization.Full;
for LMethod in FMethodList do
if SameText(LMethod.Name, AMethod) then
begin
Result := LMethod.TenantAuthorization;
Break;
end;
if FAttributes <> nil then
Result := FAttributes.EndPointTenantAuthorization[AMethod];
end;
procedure TEMSTypeInfoResource.InternalScanMethods(const ARTTIField: TRTTIField;
const AFieldAttributes: TEMSResourceAttributes; const ARTTIMethods: TArray<TRTTIMethod>);
var
LRTTIMethod: TRTTIMethod;
LRTTIParameters: TArray<TRttiParameter>;
LHTTPMethod: TEndpointRequest.TMethod;
LResourceMethod: TResourceMethod;
LParentURLSuffix: string;
LBaseURLSuffix: string;
LRTTIReturnType: TRttiType;
LSignatureKind: TResourceMethod.TSignatureKind;
LEndpointName: string;
LMethodNames: TDictionary<string, TDispatchKind>;
LEndpointNames: TDictionary<string, Integer>;
LCount: Integer;
LAPIDocMethod: TAPIDocPathItem;
LResponses: TArray<TAPIDocResponse>;
LParameters: TArray<TAPIDocParameter>;
LEndPointRequestSummary: EndPointRequestSummaryAttribute;
LTenantAuthorization: TTenantAuthorization;
LMethodAttributes: TEMSResourceAttributes;
LEndpointProduce: string;
LEndpointConsume: string;
LMeth: string;
function GetSignatureKind(const AParameters: TArray<TRttiParameter>; const AReturnType: TRttiType): TResourceMethod.TSignatureKind;
begin
Result := TResourceMethod.TSignatureKind.Unknown;
if (Length(AParameters) = 3) and (AReturnType = nil) then
begin
if SameText(AParameters[0].ParamType.QualifiedName, 'EMS.ResourceAPI.TEndpointContext') and
SameText(AParameters[1].ParamType.QualifiedName, 'EMS.ResourceAPI.TEndpointRequest') and
SameText(AParameters[2].ParamType.QualifiedName, 'EMS.ResourceAPI.TEndpointResponse') then
begin
Result := TResourceMethod.TSignatureKind.Standard;
end;
end;
end;
procedure ApplyAttributes(AAttributes: TEMSResourceAttributes;
const AName: string; AParentAttrs: Boolean);
var
S: string;
LReqSum: EndPointRequestSummaryAttribute;
LResps: TArray<TAPIDocResponse>;
LParams: TArray<TAPIDocParameter>;
LAuth: TTenantAuthorization;
LMeth: TEndpointRequest.TMethod;
begin
S := AAttributes.ResourceSuffix[AName];
if S <> '' then
if AParentAttrs then
LParentURLSuffix := S
else
LBaseURLSuffix := S;
S := AAttributes.EndPointName[AName];
if S <> '' then
LEndpointName := S;
LReqSum := AAttributes.RequestSummary[AName];
if LReqSum <> nil then
LEndPointRequestSummary := LReqSum;
LResps := AAttributes.ResponseDetails[AName];
if Length(LResps) <> 0 then
LResponses := LResps;
LParams := AAttributes.RequestParameters[AName];
if Length(LParams) <> 0 then
LParameters := LParams;
LAuth := AAttributes.EndPointTenantAuthorization[AName];
if LAuth <> TTenantAuthorization.Default then
LTenantAuthorization := LAuth;
S := AAttributes.EndPointProduce[AName];
if S <> '' then
LEndpointProduce := S;
// else if (LReqSum <> nil) and (LEndpointProduce = '') then
// LEndpointProduce := LReqSum.Produces;
S := AAttributes.EndPointConsume[AName];
if S <> '' then
LEndpointConsume := S;
// else if (LReqSum <> nil) and (LEndpointConsume = '') then
// LEndpointConsume := LReqSum.Consume;
LMeth := AAttributes.EndPointHTTPMethod[AName];
if LMeth <> TEndpointRequest.TMethod.Other then
LHTTPMethod := LMeth;
end;
begin
LMethodNames := TDictionary<string, TDispatchKind>.Create;
LEndpointNames := TDictionary<string, Integer>.Create;
LMethodAttributes := TEMSResourceAttributes.Create;
try
for LRTTIMethod in ARTTIMethods do
begin
// Cpp doesn't support published methods, so support public and published.
if (LRTTIMethod.Visibility in [TMemberVisibility.mvPublic, TMemberVisibility.mvPublished]) and
LMethodNames.TryAdd(LRTTIMethod.ToString, LRTTIMethod.DispatchKind) then
begin
LRTTIParameters := LRTTIMethod.GetParameters;
LRTTIReturnType := LRTTIMethod.ReturnType;
LSignatureKind := GetSignatureKind(LRttiParameters, LRTTIReturnType);
if LSignatureKind <> TResourceMethod.TSignatureKind.Unknown then
begin
LHTTPMethod := TEndpointRequest.TMethod.Other;
LParentURLSuffix := '';
LBaseURLSuffix := '';
LEndpointName := '';
LEndPointRequestSummary := nil;
LResponses := nil;
LParameters := nil;
LTenantAuthorization := TTenantAuthorization.Full;
LEndpointProduce := '';
LEndpointConsume := '';
LMethodAttributes.Clear;
LMethodAttributes.LoadFromRtti(LRTTIMethod);
ApplyAttributes(LMethodAttributes, '', False);
if AFieldAttributes <> nil then
begin
ApplyAttributes(AFieldAttributes, '', True);
ApplyAttributes(AFieldAttributes, LRTTIMethod.Name, False);
end;
if FAttributes <> nil then
if AFieldAttributes <> nil then
begin
ApplyAttributes(FAttributes, AFieldAttributes.ResourceName, True);
ApplyAttributes(FAttributes, AFieldAttributes.ResourceName + '.' + LRTTIMethod.Name, False);
end
else
ApplyAttributes(FAttributes, LRTTIMethod.Name, False);
if LHTTPMethod = TEndpointRequest.TMethod.Other then
begin
LMeth := LRTTIMethod.Name.ToLower;
if LMeth.StartsWith('get') then
LHTTPMethod := TEndpointRequest.TMethod.Get
else if LMeth.StartsWith('put') then
LHTTPMethod := TEndpointRequest.TMethod.Put
else if LMeth.StartsWith('post') then
LHTTPMethod := TEndpointRequest.TMethod.Post
else if LMeth.StartsWith('delete') then
LHTTPMethod := TEndpointRequest.TMethod.Delete
else if LMeth.StartsWith('patch') then
LHTTPMethod := TEndpointRequest.TMethod.Patch;
end;
if LHTTPMethod <> TEndpointRequest.TMethod.Other then
begin
if LEndpointName = '' then
begin
LEndpointName := LRTTIMethod.Name;
if AFieldAttributes <> nil then
LEndpointName := AFieldAttributes.ResourceName + '.' + LEndpointName;
end;
if LEndpointNames.TryGetValue(LEndpointName.ToLower, LCount) then
begin
// Make unique name
LEndpointNames[LEndpointName.ToLower] := LCount + 1;
LEndpointName := LEndpointName + IntToStr(LCount);
end
else
LEndpointNames.Add(LEndpointName.ToLower, 1);
LAPIDocMethod := TAPIDocPathItem.Create(LHTTPMethod, LEndpointName,
LEndPointRequestSummary, LResponses, LParameters);
if LAPIDocMethod.FProduces = '' then
LAPIDocMethod.FProduces := LEndpointProduce;
if LAPIDocMethod.FConsumes = '' then
LAPIDocMethod.FConsumes := LEndpointConsume;
if (LParentURLSuffix = '') and (AFieldAttributes <> nil) then
LParentURLSuffix := AFieldAttributes.ResourceName;
if LParentURLSuffix.StartsWith('./') then
LParentURLSuffix := LParentURLSuffix.Substring(2);
if LBaseURLSuffix = '' then
LBaseURLSuffix := LParentURLSuffix
else if LBaseURLSuffix.StartsWith('./') then
if LParentURLSuffix.EndsWith('/') then
LBaseURLSuffix := LParentURLSuffix + LBaseURLSuffix.Substring(2)
else
LBaseURLSuffix := LParentURLSuffix + LBaseURLSuffix.Substring(1);
LResourceMethod := TResourceMethod.Create(LEndpointName, ARTTIField,
LRTTIMethod, LHTTPMethod, LBaseURLSuffix, LAPIDocMethod, LTenantAuthorization,
LEndpointProduce, LEndpointConsume);
LResourceMethod.FRttiParameters := LRTTIParameters;
LResourceMethod.FRttiReturnType := LRTTIReturnType;
LResourceMethod.FSignatureKind := LSignatureKind;
FMethodList.Add(LResourceMethod);
end;
end;
end;
end;
finally
LMethodAttributes.Free;
LEndpointNames.Free;
LMethodNames.Free;
end;
end;
procedure TEMSTypeInfoResource.ScanMethods;
var
LRTTIMethods: TArray<TRTTIMethod>;
begin
Assert(FRttiType <> nil);
LRTTIMethods := FRTTIType.GetMethods;
InternalScanMethods(nil, nil, LRTTIMethods);
end;
procedure TEMSTypeInfoResource.ScanFields;
var
LRTTIFields: TArray<TRttiField>;
LRTTIField: TRttiField;
LRTTIInterfaces: TArray<TRttiInterfaceType>;
LRTTIInterface: TRttiInterfaceType;
LRTTIMethods: TArray<TRTTIMethod>;
LParentResourceName: string;
LParentTenantAuthorization: TTenantAuthorization;
LAttributes: TEMSResourceAttributes;
begin
Assert(FRttiType <> nil);
LRTTIFields := FRTTIType.GetFields;
for LRTTIField in LRTTIFields do
if (LRTTIField.Visibility in [TMemberVisibility.mvPublic, TMemberVisibility.mvPublished]) and
(LRTTIField.FieldType is TRttiInstanceType) then begin
LRTTIInterfaces := TRttiInstanceType(LRTTIField.FieldType).GetImplementedInterfaces;
for LRTTIInterface in LRTTIInterfaces do
if SameText(LRTTIInterface.QualifiedName, 'EMS.ResourceAPI.IEMSEndpointPublisher') then
begin
LAttributes := TEMSResourceAttributes.Create;
try
InternalScanResource(LRTTIField, LParentResourceName, LParentTenantAuthorization);
LAttributes.ResourceName := LParentResourceName;
LAttributes.ResourceTenantAuthorization[LAttributes.ResourceName] := LParentTenantAuthorization;
LAttributes.LoadFromRtti(LRTTIField);
LRTTIMethods := LRTTIField.FieldType.GetMethods;
InternalScanMethods(LRTTIField, LAttributes, LRTTIMethods);
finally
LAttributes.Free;
end;
Break;
end;
end;
end;
procedure TEMSTypeInfoResource.ScanObjectsDefinitions(const AResourceName: string);
var
LAttribute: TCustomAttribute;
begin
Assert(FRttiType <> nil);
for LAttribute in FRttiType.GetAttributes do
begin
if LAttribute is EndPointObjectsYAMLDefinitionsAttribute then
FYAMLDefinitions := EndPointObjectsYAMLDefinitionsAttribute(LAttribute).Objects
else if LAttribute is EndPointObjectsJSONDefinitionsAttribute then
FJSONDefinitions := EndPointObjectsJSONDefinitionsAttribute(LAttribute).Objects;
end;
if FAttributes <> nil then
begin
FYAMLDefinitions := FAttributes.GetYAMLDefinitions(AResourceName);
FJSONDefinitions := FAttributes.GetJSONDefinitions(AResourceName);
end;
end;
function TEMSTypeInfoResource.CreateInstance: TObject;
var
LMetaClass: TClass;
begin
Result := nil;
LMetaClass := FRttiType.AsInstance.MetaclassType;
case FConstructorKind of
TConstructorKind.Simple:
Result := FRttiConstructor.Invoke(LMetaClass, []).AsObject;
TConstructorKind.Component:
Result := FRttiConstructor.Invoke(LMetaClass, [nil]).AsObject;
else
Assert(False);
end;
end;
procedure TEMSTypeInfoResource.CreateEndPoints;
procedure AddEndPoint(const AResourceMethod: TResourceMethod);
var
LResourceMethod: TResourceMethod;
LResource: TEMSTypeInfoResource;
begin
LResourceMethod := AResourceMethod;
LResource := Self;
TEMSResourceEndPointSuffix.Create(Self, AResourceMethod.FName,
AResourceMethod.FURLSuffix, AResourceMethod.FHTTPMethod,
AResourceMethod.FProduce, AResourceMethod.FConsume,
procedure(const Sender: TObject; const AContext: TEndpointContext;
const ARequest: TEndpointRequest; const AResponse: TEndpointResponse)
var
LObject: TObject;
begin
LObject := LResource.CreateInstance;
try
if LResourceMethod.FRttiField <> nil then
LResourceMethod.FRttiMethod.Invoke(LResourceMethod.FRttiField.GetValue(LObject),
TArray<TValue>.Create(AContext, ARequest, AResponse))
else
LResourceMethod.FRttiMethod.Invoke(LObject,
TArray<TValue>.Create(AContext, ARequest, AResponse));
finally
LObject.DisposeOf;
end;
end);
end;
procedure AddDocPath(const AResourceMethod: TResourceMethod; const ADocPaths: TDictionary<string, TAPIDocPath>);
var
LPath: string;
LAPIDocPath: TAPIDocPath;
begin
LPath := '/' + FBaseURL;
if AResourceMethod.FURLSuffix <> '' then
begin
if not AResourceMethod.FURLSuffix.StartsWith('/') then
LPath := LPath + '/';
LPath := LPath + AResourceMethod.FURLSuffix;
end;
if ADocPaths.TryGetValue(LPath, LAPIDocPath) then
LAPIDocPath.AddPathItem(AResourceMethod.FPathItem)
else
begin
LAPIDocPath := TAPIDocPath.Create(LPath, AResourceMethod.FName);
LAPIDocPath.AddPathItem(AResourceMethod.FPathItem);
ADocPaths.Add(LPath, LAPIDocPath);
end;
end;
var
LResourceMethod: TResourceMethod;
LDocPaths: TDictionary<string, TAPIDocPath>;
LDocArray: TArray<TPair<string, TAPIDocPath>>;
LDocPair: TPair<string, TAPIDocPath>;
begin
LDocPaths := TDictionary<string, TAPIDocPath>.Create;
try
for LResourceMethod in FMethodList do
begin
AddEndPoint(LResourceMethod);
AddDocPath(LResourceMethod, LDocPaths);
end;
LDocArray := LDocPaths.ToArray;
finally
LDocPaths.Free;
end;
for LDocPair in LDocArray do
begin
FAPIDocPaths.Add(LDocPair.Value);
end;
end;
{ ResourceSuffixAttribute }
constructor ResourceSuffixAttribute.Create(const AMethod, ASuffix: string);
begin
inherited Create(AMethod);
FSuffix := ASuffix;
end;
constructor ResourceSuffixAttribute.Create(const ASuffix: string);
begin
Create('', ASuffix);
end;
{ TEMSTypeInfoResource.TResourceMethod }
constructor TEMSTypeInfoResource.TResourceMethod.Create(const AName: string; const ARttiField: TRTTIField;
const ARttiMethod: TRTTIMethod; AHTTPMethod: TEndpointRequest.TMethod; const ABaseURLSuffix: string;
const APathItem: TAPIDocPathItem = nil; ATenantAuthorization: TTenantAuthorization = TTenantAuthorization.Full;
const AProduce: string = ''; const AConsume: string = '');
begin
FName := AName;
FRttiField := ARttiField;
FRttiMethod := ARttiMethod;
FHTTPMethod := AHTTPMethod;
FURLSuffix := ABaseURLSuffix;
FPathItem := APathItem;
FTenantAuthorization := ATenantAuthorization;
FProduce := AProduce;
FConsume := AConsume;
end;
{ ResourceNameAttribute }
constructor ResourceNameAttribute.Create(AName: string);
begin
FName := AName;
end;
{ EndpointNameAttribute }
constructor EndpointNameAttribute.Create(const AMethod, AName: string);
begin
inherited Create(AMethod);
FName := AName;
end;
constructor EndpointNameAttribute.Create(const AName: string);
begin
Create('', AName);
end;
{ TEMSResourceAttributes }
constructor TEMSResourceAttributes.Create;
begin
inherited Create;
FEndpointName := TDictionary<string, string>.Create(TIStringComparer.Ordinal);
FResourceSuffix := TDictionary<string, string>.Create(TIStringComparer.Ordinal);
FResponseDetails := TObjectDictionary<string, TList<TAPIDocResponse>>.Create([doOwnsValues], TIStringComparer.Ordinal);
FRequestSummary := TObjectDictionary<string, EndPointRequestSummaryAttribute>.Create([doOwnsValues], TIStringComparer.Ordinal);
FRequestParameters := TObjectDictionary<string, TList<TAPIDocParameter>>.Create([doOwnsValues], TIStringComparer.Ordinal);
FYAMLDefinitions := TDictionary<string, string>.Create(TIStringComparer.Ordinal);
FJSONDefinitions := TDictionary<string, string>.Create(TIStringComparer.Ordinal);
FResourceTenantAuthorizations := TDictionary<string, TTenantAuthorization>.Create(TIStringComparer.Ordinal);
FEndPointTenantAuthorizations := TDictionary<string, TTenantAuthorization>.Create(TIStringComparer.Ordinal);
FEndPointProduce := TDictionary<string, string>.Create(TIStringComparer.Ordinal);
FEndPointConsume := TDictionary<string, string>.Create(TIStringComparer.Ordinal);
FEndPointHTTPMethod := TDictionary<string, TEndpointRequest.TMethod>.Create(TIStringComparer.Ordinal);
end;
destructor TEMSResourceAttributes.Destroy;
begin
FEndpointName.Free;
FResourceSuffix.Free;
FResponseDetails.Free;
FRequestSummary.Free;
FRequestParameters.Free;
FYAMLDefinitions.Free;
FJSONDefinitions.Free;
FResourceTenantAuthorizations.Free;
FEndPointTenantAuthorizations.Free;
FEndPointProduce.Free;
FEndPointConsume.Free;
FEndPointHTTPMethod.Free;
inherited Destroy;
end;
procedure TEMSResourceAttributes.LoadFromRtti(AMember: TRttiMember);
var
LRTTIAttributes: TArray<System.TCustomAttribute>;
LRTTIAttribute: System.TCustomAttribute;
LMethod: string;
begin
LRTTIAttributes := AMember.GetAttributes;
for LRTTIAttribute in LRTTIAttributes do
begin
if LRTTIAttribute is TEndpointCustomAttribute then
LMethod := TEndpointCustomAttribute(LRTTIAttribute).Method
else
LMethod := '';
if (LMethod <> '') and (AMember is TRttiMethod) and not SameText(AMember.Name, LMethod) then
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
Format(sInvalidAttributeUsage, [AMember.Name]));
if LRTTIAttribute is ResourceSuffixAttribute then
ResourceSuffix[LMethod] := ResourceSuffixAttribute(LRTTIAttribute).Suffix
else if LRTTIAttribute is EndpointNameAttribute then
EndPointName[LMethod] := EndpointNameAttribute(LRTTIAttribute).Name
else if LRTTIAttribute is EndPointResponseDetailsAttribute then
AddResponseDetail(LMethod, EndPointResponseDetailsAttribute(LRTTIAttribute))
else if LRTTIAttribute is EndPointRequestParameterAttribute then
AddRequestParameter(LMethod, EndPointRequestParameterAttribute(LRTTIAttribute))
else if LRTTIAttribute is EndPointRequestSummaryAttribute then
RequestSummary[LMethod] := EndPointRequestSummaryAttribute(LRTTIAttribute)
else if LRTTIAttribute is AllowAnonymousTenantAttribute then
EndPointTenantAuthorization[LMethod] := TTenantAuthorization.SkipAll
else if LRTTIAttribute is EndPointConsumeAttribute then
EndPointConsume[LMethod] := EndPointConsumeAttribute(LRTTIAttribute).Types
else if LRTTIAttribute is EndPointProduceAttribute then
EndPointProduce[LMethod] := EndPointProduceAttribute(LRTTIAttribute).Types
else if LRTTIAttribute is EndPointMethodAttribute then
EndPointHTTPMethod[LMethod] := EndPointMethodAttribute(LRTTIAttribute).HTTPMethod;
end;
end;
procedure TEMSResourceAttributes.Clear;
begin
FResourceName := '';
FEndpointName.Clear;
FResourceSuffix.Clear;
FResponseDetails.Clear;
FRequestSummary.Clear;
FRequestParameters.Clear;
FYAMLDefinitions.Clear;
FJSONDefinitions.Clear;
FResourceTenantAuthorizations.Clear;
FEndPointTenantAuthorizations.Clear;
FEndPointProduce.Clear;
FEndPointConsume.Clear;
FEndPointHTTPMethod.Clear;
end;
function TEMSResourceAttributes.GetEndPointName(const AMethod: string): string;
begin
FEndpointName.TryGetValue(AMethod, Result);
end;
function TEMSResourceAttributes.GetResourceSuffix(const AMethod: string): string;
begin
FResourceSuffix.TryGetValue(AMethod, Result);
end;
procedure TEMSResourceAttributes.SetJSONDefinitions(const AResourceName, Value: string);
begin
FJSONDefinitions.AddOrSetValue(AResourceName, Value);
end;
procedure TEMSResourceAttributes.SetYAMLDefinitions(const AResourceName, Value: string);
begin
FYAMLDefinitions.AddOrSetValue(AResourceName, Value);
end;
procedure TEMSResourceAttributes.SetEndPointTenantAuthorization(
const AMethod: string; const Value: TTenantAuthorization);
begin
FEndPointTenantAuthorizations.AddOrSetValue(AMethod, Value);
end;
procedure TEMSResourceAttributes.SetEndPointName(const AMethod, Value: string);
begin
FEndpointName.AddOrSetValue(AMethod, Value);
end;
procedure TEMSResourceAttributes.SetRequestSummary(const AMethod: string;
ARequestSummaryAttribute: EndPointRequestSummaryAttribute);
var
LRequestSummaryAttribute: EndPointRequestSummaryAttribute;
begin
LRequestSummaryAttribute := EndPointRequestSummaryAttribute.Create(
ARequestSummaryAttribute.Tags, ARequestSummaryAttribute.Summary,
ARequestSummaryAttribute.Description, ARequestSummaryAttribute.Produces,
ARequestSummaryAttribute.Consume);
FRequestSummary.AddOrSetValue(AMethod, LRequestSummaryAttribute);
end;
procedure TEMSResourceAttributes.SetResourceTenantAuthorization(
const AResourceName: string; const Value: TTenantAuthorization);
begin
FResourceTenantAuthorizations.AddOrSetValue(AResourceName, Value);
end;
procedure TEMSResourceAttributes.SetResourceSuffix(const AMethod,
Value: string);
begin
FResourceSuffix.AddOrSetValue(AMethod, Value);
end;
procedure TEMSResourceAttributes.AddRequestParameter(const AMethod: string;
const ARequestParameterAttribute: EndPointRequestParameterAttribute);
var
LAPIDocParameter: TAPIDocParameter;
LListParameter: TList<TAPIDocParameter>;
begin
LAPIDocParameter := TAPIDocParameter.Create(ARequestParameterAttribute);
if not FRequestParameters.TryGetValue(AMethod, LListParameter) then
begin
LListParameter := TObjectList<TAPIDocParameter>.Create;
FRequestParameters.AddOrSetValue(AMethod, LListParameter);
end;
LListParameter.Add(LAPIDocParameter);
end;
procedure TEMSResourceAttributes.AddResponseDetail(const AMethod: string;
const AResponseDetailAttribute: EndPointResponseDetailsAttribute);
var
LAPIDocResponse: TAPIDocResponse;
LListAPIDoc: TList<TAPIDocResponse>;
begin
LAPIDocResponse := TAPIDocResponse.Create(AResponseDetailAttribute);
if not FResponseDetails.TryGetValue(AMethod, LListAPIDoc) then
begin
LListAPIDoc := TObjectList<TAPIDocResponse>.Create;
FResponseDetails.AddOrSetValue(AMethod, LListAPIDoc);
end;
LListAPIDoc.Add(LAPIDocResponse);
end;
function TEMSResourceAttributes.GetEndPointTenantAuthorization(
const AMethod: string): TTenantAuthorization;
begin
if not FEndPointTenantAuthorizations.TryGetValue(AMethod, Result) then
Result := TTenantAuthorization.Default;
end;
function TEMSResourceAttributes.GetYAMLDefinitions(const AResourceName: string): string;
begin
FYAMLDefinitions.TryGetValue(AResourceName, Result);
end;
function TEMSResourceAttributes.GetJSONDefinitions(const AResourceName: string): string;
begin
FJSONDefinitions.TryGetValue(AResourceName, Result);
end;
function TEMSResourceAttributes.GetRequestParameters(const AMethod: string): TArray<TAPIDocParameter>;
var
LAPIDocParameterList: TList<TAPIDocParameter>;
begin
if FRequestParameters.TryGetValue(AMethod, LAPIDocParameterList) then
Result := LAPIDocParameterList.ToArray;
end;
function TEMSResourceAttributes.GetRequestSummary(const AMethod: string): EndPointRequestSummaryAttribute;
begin
FRequestSummary.TryGetValue(AMethod, Result);
end;
function TEMSResourceAttributes.GetResourceTenantAuthorization(
const AResourceName: string): TTenantAuthorization;
begin
if not FResourceTenantAuthorizations.TryGetValue(AResourceName, Result) then
Result := TTenantAuthorization.Full;
end;
function TEMSResourceAttributes.GetResponseDetails(const AMethod: string): TArray<TAPIDocResponse>;
var
LAPIDocResponseList: TList<TAPIDocResponse>;
begin
if FResponseDetails.TryGetValue(AMethod, LAPIDocResponseList) then
Result := LAPIDocResponseList.ToArray;
end;
function TEMSResourceAttributes.GetEndPointProduce(
const AMethod: string): string;
begin
FEndPointProduce.TryGetValue(AMethod, Result);
end;
procedure TEMSResourceAttributes.SetEndPointProduce(const AMethod,
AValue: string);
begin
FEndPointProduce.AddOrSetValue(AMethod, AValue);
end;
function TEMSResourceAttributes.GetEndPointConsume(
const AMethod: string): string;
begin
FEndPointConsume.TryGetValue(AMethod, Result);
end;
procedure TEMSResourceAttributes.SetEndPointConsume(const AMethod,
AValue: string);
begin
FEndPointConsume.AddOrSetValue(AMethod, AValue);
end;
function TEMSResourceAttributes.GetEndPointHTTPMethod(
const AMethod: string): TEndpointRequest.TMethod;
begin
if not FEndPointHTTPMethod.TryGetValue(AMethod, Result) then
Result := TEndpointRequest.TMethod.Other;
end;
procedure TEMSResourceAttributes.SetEndPointHTTPMethod(const AMethod: string;
const AValue: TEndpointRequest.TMethod);
begin
FEndPointHTTPMethod.AddOrSetValue(AMethod, AValue);
end;
{ TEMSCommonResource }
procedure TEMSCommonResource.BuildTree;
begin
EnumEndPoints(
procedure(const AEndPoint: TEMSResourceEndPoint; var ADone: Boolean)
var
LEndPoint: TEMSResourceEndPoint;
LSegment: TEMSEndPointSegment;
LCurrentNode: TTreeNode;
LNode: TTreeNode;
LMatch: TTreeNode;
LMatchingSegment: Boolean;
LEndpointScore: Integer;
begin
LMatch := nil;
LEndPoint := AEndpoint; // TEMSResourceEndPoint(AEndPoint);
LCurrentNode := FRootNode;
LEndpointScore := 0;
for LSegment in LEndPoint.SegmentParameters do
begin
LMatch := nil;
for LNode in LCurrentNode.ChildNodes do
begin
LMatchingSegment := (LEndpoint.Method = LNode.Method) and
(LNode.Segment.ClassType = LSegment.ClassType);
if LMatchingSegment then
if LSegment is TEMSEndPointSegmentConstant then
begin
LMatchingSegment := SameText(TEMSEndPointSegmentConstant(LSegment).Value,
TEMSEndPointSegmentConstant(LNode.Segment).Value);
end;
if LMatchingSegment then
begin
LMatch := LNode;
break;
end;
end;
if LMatch <> nil then
LCurrentNode := LMatch
else
begin
LMatch := TTreeNode.Create(LEndpoint.Method, LSegment);
LCurrentNode.AddChildNode(LMatch);
LCurrentNode := LMatch;
end;
if LSegment is TEMSEndPointSegmentConstant then
Inc(LEndpointScore); // Score is used when duplicate paths
end;
if LMatch <> nil then
LCurrentNode.AddTerminalEndpoint(LEndPoint.Name, LEndpointScore);
end);
end;
procedure TEMSCommonResource.SearchTree(const AContext: TEndpointContext;
ARequestSegmentIndex: Integer; const ATreeNode: TTreeNode;
const ATerminalNodes: TList<TTreeNode>);
var
LRequestSegment: string;
LNode: TTreeNode;
LMatch: Boolean;
LWildcard: Boolean;
LMethod: TEndpointRequest.TMethod;
begin
Assert(ARequestSegmentIndex < AContext.Request.Segments.Count);
LMethod := AContext.Request.Method;
LRequestSegment := AContext.Request.Segments[ARequestSegmentIndex];
for LNode in ATreeNode.ChildNodes do
begin
LWildcard := False;
LMatch := LMethod = LNode.Method;
if LMatch then
if (LNode.Segment is TEMSEndPointSegmentParameter) and
(TEMSEndPointSegmentParameter(LNode.Segment).Name <> '*') then
LMatch := not ('/' = LRequestSegment)
else if LNode.Segment is TEMSEndPointSegmentConstant then
LMatch := SameText(TEMSEndPointSegmentConstant(LNode.Segment).Value, LRequestSegment)
else if LNode.Segment is TEMSEndPointSegmentSlash then
LMatch := '/' = LRequestSegment
else if (LNode.Segment is TEMSEndPointSegmentWildcard) or
(LNode.Segment is TEMSEndPointSegmentParameter) and
(TEMSEndPointSegmentParameter(LNode.Segment).Name = '*') then
begin
LMatch := True;
LWildcard := True;
end
else
begin
LMatch := False;
Assert(False);
end;
if LMatch then
if LWildcard or (ARequestSegmentIndex + 1 = AContext.Request.Segments.Count) then
ATerminalNodes.Add(LNode)
else if ARequestSegmentIndex + 1 < AContext.Request.Segments.Count then
// Recursive
SearchTree(AContext, ARequestSegmentIndex + 1, LNode, ATerminalNodes);
end;
end;
procedure TEMSCommonResource.SearchTree(const AContext: TEndpointContext; out ATerminalNodes: TArray<TTreeNode>);
var
LRequestSegmentIndex: Integer;
LList: TList<TTreeNode>;
begin
LRequestSegmentIndex := BaseURLSegmentCount;
if LRequestSegmentIndex < AContext.Request.Segments.Count then
begin
LList := TList<TTreeNode>.Create;
try
SearchTree(AContext, LRequestSegmentIndex, FRootNode, LList);
ATerminalNodes := LList.ToArray;
finally
LList.Free;
end;
end
else
ATerminalNodes := nil;
end;
function TEMSCommonResource.DoCanHandleRequest(
const AContext: TEndpointContext; out AEndpointName: string): Boolean;
var
LTerminalNodes: TArray<TTreeNode>;
LNode: TTreeNode;
LTerminalEndpoint: TLeafEndpoint;
LNegogiator: TNegotiator;
begin
Result := False;
AEndpointName := '';
LNegogiator := TNegotiator.Create(AContext);
try
if BaseURLSegmentCount = AContext.Request.Segments.Count then
EnumEndPoints(
procedure(const AEndPoint: TEMSResourceEndPoint; var ADone: Boolean)
begin
// No segments
if (AEndpoint.Method = AContext.Request.Method) and
(AEndpoint.SegmentParameters.Count = 0) then
LNegogiator.Choose(AEndpoint, 0);
end)
else
begin
SearchTree(AContext, LTerminalNodes);
for LNode in LTerminalNodes do
for LTerminalEndpoint in LNode.LeafEndpoints do
LNegogiator.Choose(FindEndPoint(LTerminalEndpoint.EndpointName),
LTerminalEndpoint.Score);
end;
case LNegogiator.Status of
TNegotiator.TStatus.Nothing:
;
TNegotiator.TStatus.Failed:
if AContext.Request.Method = TEndpointRequest.TMethod.Get then
EEMSHTTPError.RaiseNotAcceptable()
else
EEMSHTTPError.RaiseUnsupportedMedia();
TNegotiator.TStatus.Duplicates:
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
Format(sDuplicateEndpoints, [LNegogiator.DuplicateNames]));
TNegotiator.TStatus.OK:
begin
Result := True;
AEndpointName := LNegogiator.BestEndpoint.Name;
end;
end;
finally
LNegogiator.Free;
end;
end;
procedure TEMSCommonResource.DoHandleRequest(
const AContext: TEndpointContext);
var
LEndpoint: TEMSResourceEndPoint;
begin
LEndpoint := FindEndPoint(AContext.EndpointName);
LEndpoint.DoAuthorizeRequest(AContext);
LEndpoint.DoHandleRequest(AContext);
end;
{ TEMSResourceWSegments.TTreeNode }
procedure TEMSCommonResource.TTreeNode.AddChildNode(
const ANode: TTreeNode);
begin
FChildNodes.Add(ANode);
end;
procedure TEMSCommonResource.TTreeNode.AddTerminalEndpoint(
const AEndpointName: string; AScore: Integer);
begin
FLeafEndpoints.Add(TLeafEndpoint.Create(AEndpointName, AScore));
end;
constructor TEMSCommonResource.TTreeNode.Create(
AMethod: TEndpointRequest.TMethod; const ASegment: TEMSEndpointSegment);
begin
FChildNodes := TObjectList<TTreeNode>.Create;
FLeafEndpoints := TList<TLeafEndpoint>.Create;
FMethod := AMethod;
FSegment := ASegment;
end;
destructor TEMSCommonResource.TTreeNode.Destroy;
begin
FChildNodes.Free;
FLeafEndpoints.Free;
inherited;
end;
function TEMSCommonResource.TTreeNode.GetChildNodes: TArray<TTreeNode>;
begin
Result := FChildNodes.ToArray;
end;
function TEMSCommonResource.TTreeNode.GetLeafEndpoints: TArray<TLeafEndpoint>;
begin
Result := FLeafEndpoints.ToArray;
end;
{ TEMSCommonResource.TLeafEndpoint }
constructor TEMSCommonResource.TLeafEndpoint.Create(const AEndpointName: string;
AScore: Integer);
begin
EndpointName := AEndpointName;
Score := AScore;
end;
{ TEMSCommonResource.TNegotiator }
constructor TEMSCommonResource.TNegotiator.Create(AContext: TEndpointContext);
begin
inherited Create;
FContext := AContext;
FBestEndpoints := TList<TEMSResourceEndPoint>.Create;
end;
destructor TEMSCommonResource.TNegotiator.Destroy;
begin
FBestEndpoints.Free;
inherited Destroy;
end;
procedure TEMSCommonResource.TNegotiator.Reset;
begin
FChooseCount := 0;
FBestEndpoints.Clear;
FBestWeight := 0;
end;
procedure TEMSCommonResource.TNegotiator.Choose(AEndpoint: TEMSResourceEndPoint; AScore: Integer);
var
LWeight: Double;
begin
Inc(FChooseCount);
LWeight := 1;
if ((FContext.Negotiation.ProduceList.Count = 0) or (AEndpoint.ProduceList = nil) or
(AEndpoint.ProduceList.Negotiate(FContext.Negotiation.ProduceList, LWeight, nil) <> '')) and
((FContext.Negotiation.ConsumeList.Count = 0) or (AEndpoint.ConsumeList = nil) or
(AEndpoint.ConsumeList.Negotiate(FContext.Negotiation.ConsumeList, LWeight, nil) <> '')) then
begin
LWeight := LWeight * (AScore + 1);
case TAcceptValueList.CompareWeights(LWeight, FBestWeight) of
0:
FBestEndpoints.Add(AEndpoint);
1:
begin
FBestEndpoints.Clear;
FBestEndpoints.Add(AEndpoint);
FBestWeight := LWeight;
end;
end;
end;
end;
function TEMSCommonResource.TNegotiator.GetStatus: TStatus;
begin
if FChooseCount = 0 then
Result := TStatus.Nothing
else if FBestEndpoints.Count = 0 then
Result := TStatus.Failed
else if FBestEndpoints.Count > 1 then
Result := TStatus.Duplicates
else
Result := TStatus.OK;
end;
function TEMSCommonResource.TNegotiator.GetBestEndpoint: TEMSResourceEndPoint;
begin
if FBestEndpoints.Count > 0 then
Result := FBestEndpoints[0]
else
Result := nil;
end;
function TEMSCommonResource.TNegotiator.GetDuplicateNames: string;
var
LBuilder: TStringBuilder;
LItem: TEMSResourceEndPoint;
begin
LBuilder := TStringBuilder.Create;
try
for LItem in FBestEndpoints do
begin
if LBuilder.Length > 0 then
LBuilder.Append(', ');
LBuilder.Append(LItem.Name);
end;
Result := LBuilder.ToString(True);
finally
LBuilder.Free;
end;
end;
{ EndPointResponseDetailsAttribute }
constructor EndPointResponseDetailsAttribute.Create(const AMethod: string; ACode: Integer;
const ADescription: string; AType: TAPIDoc.TPrimitiveType;
AFormat: TAPIDoc.TPrimitiveFormat; const ASchema, AReference: string);
begin
inherited Create(AMethod);
FCode := ACode;
FDescription := TResourceStringsTable.Get(ADescription);
FSchema := ASchema;
FType := AType;
FFormat := AFormat;
FReference := AReference;
end;
constructor EndPointResponseDetailsAttribute.Create(ACode: Integer;
const ADescription: string; AType: TAPIDoc.TPrimitiveType;
AFormat: TAPIDoc.TPrimitiveFormat; const ASchema, AReference: string);
begin
Create('', ACode, ADescription, AType, AFormat, ASchema, AReference);
end;
{ EndPointRequestParameter }
constructor EndPointRequestParameterAttribute.Create(const AMethod: string;
AIn: TAPIDocParameter.TParameterIn; const AName, ADescription: string; const ARequired: boolean;
AType: TAPIDoc.TPrimitiveType; AFormat: TAPIDoc.TPrimitiveFormat; AItemType: TAPIDoc.TPrimitiveType;
const AJSONScheme, AReference: string);
begin
inherited Create(AMethod);
FName := AName;
FIn := AIn;
FDescription := ADescription;
FRequired := ARequired;
FType := AType;
FJSONSchema := AJSONScheme;
FFormat := AFormat;
FReference := AReference;
end;
constructor EndPointRequestParameterAttribute.Create(
AIn: TAPIDocParameter.TParameterIn; const AName, ADescription: string; const ARequired: boolean;
AType: TAPIDoc.TPrimitiveType; AFormat: TAPIDoc.TPrimitiveFormat; AItemType: TAPIDoc.TPrimitiveType;
const AJSONScheme, AReference: string);
begin
Create('', AIn, AName, ADescription, ARequired, AType, AFormat, AItemType, AJSONScheme, AReference);
end;
{ EndPointRequestSummary }
constructor EndPointRequestSummaryAttribute.Create(const AMethod, ATags, ASummary,
ADescription, AProduces, AConsume: string);
begin
inherited Create(AMethod);
FTags := ATags;
FSummary := TResourceStringsTable.Get(ASummary);
FDescription := TResourceStringsTable.Get(ADescription);
FProduces := AProduces;
FConsume := AConsume;
end;
constructor EndPointRequestSummaryAttribute.Create(const ATags, ASummary,
ADescription, AProduces, AConsume: string);
begin
Create('', ATags, ASummary, ADescription, AProduces, AConsume);
end;
{ EndPointObjectsYAMLDefinitions }
constructor EndPointObjectsYAMLDefinitionsAttribute.Create(const Objects: string);
begin
FObjects := Objects;
end;
{ EndPointObjectsJSONDefinitions }
constructor EndPointObjectsJSONDefinitionsAttribute.Create(const Objects: string);
begin
FObjects := Objects;
end;
{ AllowAnonymousTenantAttribute }
constructor AllowAnonymousTenantAttribute.Create(const AMethod: string);
begin
inherited Create(AMethod);
end;
constructor AllowAnonymousTenantAttribute.Create;
begin
Create('');
end;
{ EndPointProduceAttribute }
constructor EndPointProduceAttribute.Create(const AMethod, ATypes: string);
begin
inherited Create(AMethod);
FTypes := ATypes;
end;
constructor EndPointProduceAttribute.Create(const ATypes: string);
begin
Create('', ATypes);
end;
{ EndPointMethodAttribute }
constructor EndPointMethodAttribute.Create(const AMethod: string;
const AHTTPMethod: TEndpointRequest.TMethod);
begin
inherited Create(AMethod);
FHTTPMethod := AHTTPMethod;
end;
constructor EndPointMethodAttribute.Create(
const AHTTPMethod: TEndpointRequest.TMethod);
begin
Create('', AHTTPMethod);
end;
{ TResourceStringsTable }
class constructor TResourceStringsTable.Create;
begin
FResourcesTable := TDictionary<string, string>.Create;
end;
class destructor TResourceStringsTable.Destroy;
begin
FResourcesTable.Free;
inherited;
end;
class function TResourceStringsTable.Get(const Akey: string): string;
var
LValue: string;
begin
if FResourcesTable.TryGetValue(Akey, LValue) then
Result := LValue
else
Result := Akey;
end;
class procedure TResourceStringsTable.Add(const Akey, AResource: string);
begin
FResourcesTable.AddOrSetValue(AKey, AResource);
end;
{ TAPIDocResponse }
constructor TAPIDocResponse.Create(const AAttribute: EndPointResponseDetailsAttribute);
begin
inherited Create;
if AAttribute <> nil then
begin
FCode := AAttribute.Code;
FDescription := TResourceStringsTable.Get(AAttribute.Description);
FSchema := AAttribute.Schema;
FReference := AAttribute.Reference;
FIsReference := FReference <> '';
FType := AAttribute.PrimitiveType;
FFormat := AAttribute.PrimitiveFormat;
end;
end;
function TAPIDocResponse.GetResponseInfo: TArray<string>;
var
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '''' + FCode.ToString + ''':');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + FDescription);
if FIsReference then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema:');
if FType = TAPIDoc.TPrimitiveType.spArray then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'type: ' + TAPIDoc.GetDataTypeAsString(FType));
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank,10) + '$ref: ''' + FReference + '''');
end
else
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + '$ref: ''' + FReference + '''');
end
else
if FSchema <> '' then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema: ' + FSchema)
else
if FType <> TAPIDoc.TPrimitiveType.spNull then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema: ' + FSchema);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'type: ' + TAPIDoc.GetDataTypeAsString(FType));
if FFormat <> TAPIDoc.TPrimitiveFormat.None then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'format: ' + TAPIDoc.GetDataTypeAsString(FFormat));
end;
Result := LStringList.ToStringArray;
finally
LStringList.Free;
end;
end;
procedure TAPIDocResponse.WriteResponseInfo(const ABuilder: TJSONObjectBuilder);
begin
ABuilder.ParentObject.BeginObject(FCode.ToString);
ABuilder.ParentObject.Add('description', FDescription);
if FIsReference then
begin
ABuilder.ParentObject.BeginObject('schema');
if FType = TAPIDoc.TPrimitiveType.spArray then
begin
ABuilder.ParentObject.Add('type',TAPIDoc.GetDataTypeAsString(FType));
ABuilder.ParentObject.BeginObject('items');
ABuilder.ParentObject.Add('$ref', FReference);
ABuilder.ParentObject.EndObject;
end
else
ABuilder.ParentObject.Add('$ref', FReference);
ABuilder.ParentObject.EndObject;
end
else
if FSchema <> '' then
ABuilder.ParentObject.Add('schema', FSchema)
else
if FType <> TAPIDoc.TPrimitiveType.spNull then
begin
ABuilder.ParentObject.Add('schema', FSchema);
ABuilder.ParentObject.Add('type', TAPIDoc.GetDataTypeAsString(FType));
if FFormat <> TAPIDoc.TPrimitiveFormat.None then
ABuilder.ParentObject.Add('format', TAPIDoc.GetDataTypeAsString(FFormat));
end;
ABuilder.ParentObject.EndObject;
end;
{ TAPIDocResponseHelper }
procedure TAPIDocResponseHelper.Assign(ASource: TAPIDocResponse);
begin
FCode := ASource.FCode;
FDescription := ASource.FDescription;
FSchema := ASource.FSchema;
FIsReference := ASource.FIsReference;
FReference := ASource.FReference;
FType := ASource.FType;
FFormat := ASource.FFormat;
FExamples := ASource.FExamples;
FRef := ASource.FRef;
end;
{ TAPIDocParameter }
constructor TAPIDocParameter.Create(const AAttribute: EndPointRequestParameterAttribute);
var
LJSONObject: TJSONObject;
begin
inherited Create;
if AAttribute <> nil then
begin
FIn := AAttribute.ParamIn;
FName := AAttribute.Name;
FDescription := TResourceStringsTable.Get(AAttribute.Description);
FType := AAttribute.ParamType;
FItemType := AAttribute.ItemType;
FFormat := AAttribute.ItemFormat;
FRequired := AAttribute.Required;
LJSONObject := TJSONObject.ParseJSONValue(AAttribute.JSONSchema) as TJSONObject;
if LJSONObject <> nil then
begin
FSchema := AAttribute.JSONSchema;
LJSONObject.Free;
end;
FReference := AAttribute.Reference;
FIsReference := FReference <> '';
end;
end;
function TAPIDocParameter.GetName: string;
begin
if FName = TAPIDoc.cStar then
Result := TAPIDoc.ReplaceStar(FName)
else
Result := FName;
end;
function TAPIDocParameter.GetParamAsString: string;
begin
if FIn = TParameterIn.formData then
Result := 'formData'
else
Result := GetEnumName(TypeInfo(TParameterIn), integer(FIn)).ToLower;
end;
function TAPIDocParameter.GetParamInfo: TArray<string>;
var
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- in: ' + GetParamAsString);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'name: ' + GetName);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + FDescription);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'required: ' + FRequired.ToString(TUseBoolStrs.True).ToLower);
if FIn = TParameterIn.Body then
begin
if FType = TAPIDoc.TPrimitiveType.spObject then
begin
if FIsReference then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + '$ref: ''' + FReference + '''');
end
else
if FSchema <> '' then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema: ' + FSchema)
else
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'type: object');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'additionalProperties: true');
end;
end
else if FType = TAPIDoc.TPrimitiveType.spArray then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'type: ' + TAPIDoc.GetDataTypeAsString(FType));
if FIsReference then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 10) + '$ref: ''' + FReference + '''');
end
else if FSchema = '' then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 10) + 'type: ' + TAPIDoc.GetDataTypeAsString(FItemType));
end
else
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items: ' + FSchema);
end
else
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'type: ' + TAPIDoc.GetDataTypeAsString(FType));
end;
end
else
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'type: ' + TAPIDoc.GetDataTypeAsString(FType));
if FType = TAPIDoc.TPrimitiveType.spArray then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'schema:');
if FIsReference then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank,10) + '$ref: ' + FReference)
end
else if FSchema = '' then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank,10) + 'type: ' + TAPIDoc.GetDataTypeAsString(FItemType));
end
else
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 8) + 'items: ' + FSchema);
end
else if FFormat <> TAPIDoc.TPrimitiveFormat.None then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'format: ' + TAPIDoc.GetDataTypeAsString(FFormat));
end;
// if TAPIDoc.TPrimitiveType.spFile consumes MUST be either "multipart/form-data" or " application/x-www-form-urlencoded"
//and the parameter MUST be in "formData".
Result := LStringList.ToStringArray;
finally
LStringList.Free;
end;
end;
procedure TAPIDocParameter.WriteParamInfo(const ABuilder: TJSONObjectBuilder);
begin
ABuilder.ParentArray.BeginObject;
ABuilder.ParentObject.Add('in', GetParamAsString);
ABuilder.ParentObject.Add('name', GetName);
ABuilder.ParentObject.Add('description', FDescription);
ABuilder.ParentObject.Add('required', FRequired);
if FIn = TParameterIn.Body then
begin
if FType = TAPIDoc.TPrimitiveType.spObject then
begin
if FIsReference then
begin
ABuilder.ParentObject.BeginObject('schema');
ABuilder.ParentObject.Add('$ref', FReference);
ABuilder.ParentObject.EndObject;
end
else
if FSchema <> '' then
ABuilder.ParentObject.Add('schema', FSchema)
else
begin
ABuilder.ParentObject.BeginObject('schema');
ABuilder.ParentObject.EndObject;
end;
end
else if FType = TAPIDoc.TPrimitiveType.spArray then
begin
ABuilder.ParentObject.BeginObject('schema');
ABuilder.ParentObject.Add('type', TAPIDoc.GetDataTypeAsString(FType));
if FIsReference then
begin
ABuilder.ParentObject.BeginObject('items');
ABuilder.ParentObject.Add('$ref', FReference);
ABuilder.ParentObject.EndObject;
end
else if FSchema = '' then
begin
ABuilder.ParentObject.BeginObject('items');
ABuilder.ParentObject.Add('type', TAPIDoc.GetDataTypeAsString(FItemType));
ABuilder.ParentObject.EndObject;
end
else
ABuilder.ParentObject.Add('items', FSchema);
ABuilder.ParentObject.EndObject
end
else
begin
ABuilder.ParentObject.BeginObject('schema');
ABuilder.ParentObject.Add('type', TAPIDoc.GetDataTypeAsString(FType));
ABuilder.ParentObject.EndObject;
end;
end
else
begin
ABuilder.ParentObject.Add('type', TAPIDoc.GetDataTypeAsString(FType));
if FType = TAPIDoc.TPrimitiveType.spArray then
begin
ABuilder.ParentObject.BeginObject('schema');
if FIsReference then
begin
ABuilder.ParentObject.BeginObject('items');
ABuilder.ParentObject.Add('$ref', FReference);
ABuilder.ParentObject.EndObject;
end
else if FSchema = '' then
begin
ABuilder.ParentObject.BeginObject('items');
ABuilder.ParentObject.Add('type', TAPIDoc.GetDataTypeAsString(FItemType));
ABuilder.ParentObject.EndObject;
end
else
ABuilder.ParentObject.Add('items', FSchema);
ABuilder.ParentObject.EndObject
end
else if FFormat <> TAPIDoc.TPrimitiveFormat.None then
ABuilder.ParentObject.Add('format', TAPIDoc.GetDataTypeAsString(FFormat));
end;
// if TAPIDoc.TPrimitiveType.spFile consumes MUST be either "multipart/form-data" or " application/x-www-form-urlencoded"
//and the parameter MUST be in "formData".
ABuilder.ParentObject.EndObject;
end;
{ TAPIDocParameterHelper }
procedure TAPIDocParameterHelper.Assign(ASource: TAPIDocParameter);
begin
FName := ASource.FName;
FIn := ASource.FIn;
FDescription := ASource.FDescription;
FRequired := ASource.FRequired;
FIsReference := ASource.FIsReference;
FType := ASource.FType;
FItemType := ASource.FItemType;
FFormat := ASource.FFormat;
FSchema := ASource.FSchema;
FReference := ASource.FReference;
end;
{ TAPIDocMethod }
constructor TAPIDocPathItem.Create(AHTTPMethod: TEndpointRequest.TMethod; const AOperationID: string;
const AAttribute: EndPointRequestSummaryAttribute; const AAPIDocResponses: TArray<TAPIDocResponse>;
const AAPIDocParameters: TArray<TAPIDocParameter>);
var
LDefOkResp: EndPointResponseDetailsAttribute;
LParam: TAPIDocParameter;
i: Integer;
begin
inherited Create;
FVerb := AHTTPMethod;
FOperationId := AOperationID;
if AAttribute <> nil then
begin
FTags := AAttribute.Tags;
FSummary := TResourceStringsTable.Get(AAttribute.Summary);
FDescription := TResourceStringsTable.Get(AAttribute.Description);
FProduces := AAttribute.Produces;
FConsumes := AAttribute.Consume;
end;
if Length(AAPIDocResponses) = 0 then
begin
LDefOkResp := EndPointResponseDetailsAttribute.Create(200, 'Ok',
TAPIDoc.TPrimitiveType.spNull, TAPIDoc.TPrimitiveFormat.None, '', '');
try
FResponses := [TAPIDocResponse.Create(LDefOkResp)];
finally
LDefOkResp.Free;
end;
end
else
begin
SetLength(FResponses, Length(AAPIDocResponses));
for i := 0 to Length(AAPIDocResponses) - 1 do
begin
FResponses[i] := TAPIDocResponse.Create(nil);
FResponses[i].Assign(AAPIDocResponses[i]);
end;
end;
SetLength(FParameters, Length(AAPIDocParameters));
for i := 0 to Length(AAPIDocParameters) - 1 do
begin
FParameters[i] := TAPIDocParameter.Create(nil);
FParameters[i].Assign(AAPIDocParameters[i]);
end;
end;
destructor TAPIDocPathItem.Destroy;
var
I: Integer;
begin
for I := Low(FParameters) to High(FParameters) do
if FParameters[I] <> nil then
FParameters[I].Free;
for I := Low(FResponses) to High(FResponses) do
if FResponses[I] <> nil then
FResponses[I].Free;
inherited Destroy;
end;
function TAPIDocPathItem.GetAuthoritationHeaderParams: TArray<string>;
var
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- in: header');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + sAuthHeaderDesc);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'name: ' + TAPIDocPathItem.ApplicationId);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'type: string');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- in: header');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + sAuthHeaderDesc);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'name: ' + TAPIDocPathItem.AppSecret);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'type: string');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- in: header');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + sAuthHeaderDesc);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'name: ' + TAPIDocPathItem.MasterSecret);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'type: string');
if TEMSEndpointEnvironment.Instance.MultiTenantMode then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- in: header');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + sAuthHeaderDesc);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'name: ' + TAPIDocPathItemTenantId);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'type: string');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- in: header');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'description: ' + sAuthHeaderDesc);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'name: ' + TAPIDocPathItemTenantSecret);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 6) + 'type: string');
end;
Result := LStringList.ToStringArray;
finally
LStringList.Free;
end;
end;
function TAPIDocPathItem.GetMethodInfo: TArray<string>;
var
LAPIDocResponse: TAPIDocResponse;
LAPIDocParameter: TAPIDocParameter;
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add(' ' + GetEnumName(TypeInfo(TEndpointRequest.TMethod), integer(FVerb)).ToLower + ':');
if FTags <> '' then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'tags:');
LStringList.Add(' - ' + FTags);
end;
if FSummary <> '' then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'summary: ''' + FSummary + '''');
if FDescription <> '' then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'description: ' + FDescription );
if FOperationId <> '' then
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'operationId: ' + FOperationId );
if FProduces <> '' then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'produces:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- ' + FProduces);
end;
if FConsumes <> '' then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'consumes:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 4) + '- ' + FConsumes);
end;
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'parameters:');
LStringList.AddStrings(GetAuthoritationHeaderParams);
if Length(FParameters) > 0 then
for LAPIDocParameter in FParameters do
LStringList.AddStrings(LAPIDocParameter.GetParamInfo);
if Length(FResponses) > 0 then
begin
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 3) + 'responses:');
for LAPIDocResponse in FResponses do
LStringList.AddStrings(LAPIDocResponse.GetResponseInfo);
end
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
'No Responses defined for: ' +
GetEnumName(TypeInfo(TEndpointRequest.TMethod), integer(FVerb)).ToLower + ' ' + FSummary);
//TO-DO
// LStringList.Add(StringOfChar(cBlank, 3) + 'security:');
// LStringList.Add(StringOfChar(cBlank, 4) + '- ' + ': []');
// LStringList.Add(StringOfChar(cBlank, 4) + '- ' + ': []');
// LStringList.Add(StringOfChar(cBlank, 4) + '- ' + ': []');
//securityDefinitions:
// api_key:
// type: apiKey
// name: api_key
// in: header
Result := LStringList.ToStringArray;
finally
LStringList.Free;
end;
end;
procedure TAPIDocPathItem.WriteAuthoritationHeaderParams(const ABuilder: TJSONObjectBuilder);
begin
ABuilder.ParentArray.BeginObject;
ABuilder.ParentObject.Add('in', 'header');
ABuilder.ParentObject.Add('name', TAPIDocPathItem.ApplicationId);
ABuilder.ParentObject.Add('type', 'string');
ABuilder.ParentObject.EndObject;
ABuilder.ParentArray.BeginObject;
ABuilder.ParentObject.Add('in', 'header');
ABuilder.ParentObject.Add('name', TAPIDocPathItem.AppSecret);
ABuilder.ParentObject.Add('type', 'string');
ABuilder.ParentObject.EndObject;
ABuilder.ParentArray.BeginObject;
ABuilder.ParentObject.Add('in', 'header');
ABuilder.ParentObject.Add('name', TAPIDocPathItem.MasterSecret);
ABuilder.ParentObject.Add('type', 'string');
ABuilder.ParentObject.EndObject;
if TEMSEndpointEnvironment.Instance.MultiTenantMode then
begin
ABuilder.ParentArray.BeginObject;
ABuilder.ParentObject.Add('in', 'header');
ABuilder.ParentObject.Add('name', TAPIDocPathItemTenantId);
ABuilder.ParentObject.Add('type', 'string');
ABuilder.ParentObject.EndObject;
ABuilder.ParentArray.BeginObject;
ABuilder.ParentObject.Add('in', 'header');
ABuilder.ParentObject.Add('name', TAPIDocPathItemTenantSecret);
ABuilder.ParentObject.Add('type', 'string');
ABuilder.ParentObject.EndObject;
end;
end;
procedure TAPIDocPathItem.WriteMethodInfo(const ABuilder: TJSONObjectBuilder);
var
LAPIDocParameter: TAPIDocParameter;
LAPIDocResponse: TAPIDocResponse;
begin
ABuilder.ParentObject.BeginObject(GetEnumName(TypeInfo(TEndpointRequest.TMethod), Integer(FVerb)).ToLower);
if FTags <> '' then
begin
ABuilder.ParentObject.BeginArray('tags');
ABuilder.ParentArray.Add(FTags);
ABuilder.ParentArray.EndArray;
end;
if FSummary <> '' then
ABuilder.ParentObject.Add('summary', FSummary);
if FDescription <> '' then
ABuilder.ParentObject.Add('description', FDescription);
if FOperationId <> '' then
ABuilder.ParentObject.Add('operationId', FOperationId);
if FProduces <> '' then
begin
ABuilder.ParentObject.BeginArray('produces');
ABuilder.ParentArray.Add(FProduces);
ABuilder.ParentArray.EndArray;
end;
if FConsumes <> '' then
begin
ABuilder.ParentObject.BeginArray('consumes');
ABuilder.ParentArray.Add(FProduces);
ABuilder.ParentArray.EndArray;
end;
ABuilder.ParentObject.BeginArray('parameters');
WriteAuthoritationHeaderParams(ABuilder);
if Length(FParameters) > 0 then
for LAPIDocParameter in FParameters do
LAPIDocParameter.WriteParamInfo(ABuilder);
ABuilder.ParentArray.EndArray;
if Length(FResponses) > 0 then
begin
ABuilder.ParentObject.BeginObject('responses');
for LAPIDocResponse in FResponses do
LAPIDocResponse.WriteResponseInfo(ABuilder);
ABuilder.ParentObject.EndObject;
end
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
'No Responses defined for: ' +
GetEnumName(TypeInfo(TEndpointRequest.TMethod), integer(FVerb)).ToLower + ' ' + FSummary);
//TO-DO
//securityDefinitions:
// api_key:
// type: apiKey
// name: api_key
// in: header
ABuilder.ParentObject.EndObject;
end;
{ TAPIDocPath }
constructor TAPIDocPath.Create(const APath, AResourceName: string);
begin
inherited Create;
FPath := APath;
FResourceName := AResourceName;
FPathItems := TObjectList<TAPIDocPathItem>.Create;
end;
destructor TAPIDocPath.Destroy;
begin
FPathItems.Free;
inherited Destroy;
end;
function TAPIDocPath.AddPathItem(const AAPIDocPathItem: TAPIDocPathItem): Boolean;
begin
Result := FPathItems.Add(AAPIDocPathItem) <> -1;
end;
function TAPIDocPath.GetPath: string;
begin
if FPath.EndsWith(TAPIDoc.cStar) then
Result := TAPIDoc.ReplaceStar(FPath, True)
else
Result := FPath;
end;
function TAPIDocPath.GetPathInfo: TArray<string>;
var
LMethod: TAPIDocPathItem;
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add(' ' + GetPath + ':');
if FPathItems.Count > 0 then
for LMethod in FPathItems do
LStringList.AddStrings(LMethod.GetMethodInfo)
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
'No Verbs defined for ' + FPath);
Result := LStringList.ToStringArray;
finally
LStringList.Free;
end;
end;
function TAPIDocPath.GetPAthItems: TArray<TAPIDocPathItem>;
begin
Result := FPathItems.ToArray;
end;
procedure TAPIDocPath.WritePathInfo(const ABuilder: TJSONObjectBuilder);
var
LMethod: TAPIDocPathItem;
begin
if FPathItems.Count > 0 then
begin
ABuilder.ParentObject.BeginObject(GetPath);
for LMethod in FPathItems do
LMethod.WriteMethodInfo(ABuilder);
ABuilder.ParentObject.EndObject;
end
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
'No Verbs defined for ' + FPath);
end;
{ TAPIDoc }
// Minimum structure
//
//---
//swagger: '2.0'
//info:
// version: 0.0.0
// title: Simple API
//paths:
// /:
// get:
// responses:
// 200:
// description: OK
constructor TAPIDoc.Create(const AHost, ABasePath: string);
begin
inherited Create;
FSwaggerVersion := sSwaggerVersion;
FInfo := TAPIDocInfo.Create(sEMSMetaDataVersion, sEMSMetaDataTitle, sEMSMetaDataDescription);
FHost := AHost;
if not ABasePath.StartsWith('/') then
FBasePath := '/' + ABasePath
else
FBasePath := ABasePath;
FPaths := TList<TAPIDocPath>.Create;
end;
destructor TAPIDoc.Destroy;
begin
// TAPIDoc.FPaths does not own TAPIDocPath's. They are owned by TEMSTypeInfoResource.
FPaths.Free;
inherited Destroy;
end;
function TAPIDoc.AddPath(const AAPIDocPath: TAPIDocPath): Boolean;
begin
Result := FPaths.Add(AAPIDocPath) <> -1;
end;
procedure TAPIDoc.WriteAPIDocJson(const AWriter: TJsonTextWriter);
var
LBuilderObject: TJSONObjectBuilder;
I: integer;
begin
LBuilderObject := TJSONObjectBuilder.Create(AWriter);
try
LBuilderObject.BeginObject;
LBuilderObject.ParentObject.Add('swagger', FSwaggerVersion);
LBuilderObject.ParentObject.BeginObject('info');
LBuilderObject.ParentObject.Add('version', FInfo.Version);
LBuilderObject.ParentObject.Add('title', FInfo.Title);
LBuilderObject.ParentObject.Add('description', FInfo.Description);
LBuilderObject.ParentObject.EndObject;
LBuilderObject.ParentObject.Add('host', FHost);
LBuilderObject.ParentObject.Add('basePath', FBasePath);
LBuilderObject.ParentObject.BeginArray('schemes');
LBuilderObject.ParentArray.Add('http');
LBuilderObject.ParentArray.EndArray;
// TO-DO
// // termsOfService: http://helloreverb.com/terms/
// // contact:
// // name:
// // url:
// // email:
// // license:
// // name: Apache 2.0
// // url: http://www.domain.com/licenses/LICENSE-2.0.html
if FPaths.Count > 0 then
begin
LBuilderObject.ParentObject.BeginObject('paths');
for I := 0 to FPaths.Count - 1 do
FPaths[I].WritePathInfo(LBuilderObject);
LBuilderObject.ParentObject.EndObject;
end
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
'No Paths defined');
if FDefinitions <> '' then
begin
AWriter.WritePropertyName('definitions');
WriteJsonDefinitions('{' + FDefinitions + '}', AWriter);
end;
LBuilderObject.ParentObject.EndObject;
finally
LBuilderObject.Free;
end;
end;
procedure TAPIDoc.WriteJsonDefinitions(const ADefinitions: string; const AJSONWriter: TJSONWriter);
var
LJSONReader: TJsonTextReader;
LStringReader: TStringReader;
begin
LStringReader := TStringReader.Create(ADefinitions);
LJSONReader := TJsonTextReader.Create(LStringReader);
try
AJSONWriter.WriteToken(LJSONReader);
finally
LJSONReader.Free;
LStringReader.Free;
end;
end;
function TAPIDoc.GetAPIDocYaml: string;
var
I: integer;
LStringList: TStringList;
begin
LStringList := TStringList.Create;
try
LStringList.Add('---');
LStringList.Add('swagger: ' + '''' + FSwaggerVersion + '''');
LStringList.Add('info:');
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 1) + 'version: ' + FInfo.Version);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 1) + 'title: ' + FInfo.Title);
LStringList.Add(StringOfChar(TAPIDoc.cBlank, 1) + 'description: ' + '|' + sLineBreak + StringOfChar(cBlank, 2) + FInfo.Description);
LStringList.Add('host: ' + FHost);
LStringList.Add('basePath: ' + FBasePath);
LStringList.Add('schemes:' + sLineBreak + StringOfChar(cBlank, 1) + '- http');
// TO-DO
// LStringList.Add(StringOfChar(cBlank, 1) + 'termsOfService: ' );
// LStringList.Add(StringOfChar(cBlank, 1) + 'contact: ' );
// LStringList.Add(StringOfChar(cBlank, 2) + 'name: ' );
// LStringList.Add(StringOfChar(cBlank, 2) + 'url: ' );
// LStringList.Add(StringOfChar(cBlank, 2) + 'email: ' );
// LStringList.Add(StringOfChar(cBlank, 1) + 'license: ' );
// LStringList.Add(StringOfChar(cBlank, 2) + 'name: ' );
// LStringList.Add(StringOfChar(cBlank, 2) + 'url: ' );
// termsOfService: http://helloreverb.com/terms/
// contact:
// name:
// url:
// email:
// license:
// name: Apache 2.0
// url: http://www.domain.com/licenses/LICENSE-2.0.html
if FPaths.Count > 0 then
begin
LStringList.Add('paths:');
for I := 0 to FPaths.Count - 1 do
LStringList.AddStrings(FPaths[I].GetPathInfo);
end
else
EEMSHTTPError.RaiseError(500, sResourceErrorMessage,
'No Paths defined');
if FDefinitions <> '' then
LStringList.Add('definitions:' + sLineBreak + FDefinitions);
Result := LStringList.Text;
finally
LStringList.Free;
end;
end;
class function TAPIDoc.GetDataTypeAsString(AType: TAPIDoc.TPrimitiveType): string;
begin
Result := GetEnumName(TypeInfo(TAPIDoc.TPrimitiveType), integer(AType)).ToLower;
Result := StringReplace(Result, 'sp', '',[]);
end;
function TAPIDoc.GetPaths: TArray<TAPIDocPath>;
begin
Result := FPaths.ToArray;
end;
class function TAPIDoc.ReplaceStar(AItem: string; IsPath: Boolean): string;
begin
if IsPath then
Result := AItem.Replace(cStar, '{' + cWildCard + '}')
else
Result := AItem.Replace(cStar, cWildCard);
end;
procedure TAPIDoc.SortPaths;
begin
FPaths.Sort(TComparer<TAPIDocPath>.Construct(
function (const L, R: TAPIDocPath): Integer
var
LRes: Integer;
begin
LRes := CompareStr(L.Path, R.Path);
if LRes = 0 then
Result := 0
else if Pos(L.Path, R.Path) > 0 then
Result := -1
else if Pos(R.Path, L.Path) > 0 then
Result := 1
else
Result := LRes;
end
));
end;
class function TAPIDoc.GetDataTypeAsString(AType: TAPIDoc.TPrimitiveFormat): string;
begin
if AType = TAPIDoc.TPrimitiveFormat.DateTime then
Result := 'date-time'
else
Result := GetEnumName(TypeInfo(TAPIDoc.TPrimitiveFormat), integer(AType)).ToLower;
end;
{ TAPIDoc.TAPIDocLicenseInfo }
constructor TAPIDoc.TAPIDocLicenseInfo.Create(const AName, AURL: string);
begin
FName := AName;
FURL := AURL;
end;
{ TAPIDoc.TAPIDocContactInfo }
constructor TAPIDoc.TAPIDocContactInfo.Create(const AName, AURL, AEmail: string);
begin
FName := AName;
FURL := AURL;
FEmail := Email;
end;
{ TAPIDoc.TAPIDocInfo }
constructor TAPIDoc.TAPIDocInfo.Create(const AVersion, ATitle, ADescription: string);
begin
FVersion := AVersion;
FTitle := ATitle;
FDescription := ADescription;
// FTermsOfUse := ATermsOfUse;
// FContact := AContact;
// FLicense := ALicense
end;
initialization
EMSLoggingResourceFunc := @LogResource;
finalization
EMSLoggingResourceFunc := nil;
end.
|
(**
This module contains a class for implementing IOTACustomMessages in the IDE for displaying messages
for this plug-in (custom colours and fonts).
@Author David Hoyle
@Version 1.0
@Date 05 Jan 2018
**)
Unit ITHelper.CustomMessages;
Interface
{$INCLUDE 'CompilerDefinitions.inc'}
Uses
ToolsAPI,
Graphics,
Windows,
ITHelper.Interfaces;
Type
(** This class defined a custom message for the IDE. **)
TITHCustomMessage = Class(TInterfacedObject, IOTACustomMessage, INTACustomDrawMessage,
IITHCustomMessage)
Strict Private
FMsg : String;
FFontName : String;
FForeColour : TColor;
FStyle : TFontStyles;
FBackColour : TColor;
FMessagePntr : Pointer;
Strict Protected
// IOTACustomMessage
Function GetColumnNumber: Integer;
Function GetFileName: String;
Function GetLineNumber: Integer;
Function GetLineText: String;
Procedure ShowHelp;
// INTACustomDrawMessage
Function CalcRect(Canvas: TCanvas; MaxWidth: Integer; Wrap: Boolean): TRect;
Procedure Draw(Canvas: TCanvas; Const Rect: TRect; Wrap: Boolean);
// IITHCustomMessage
Procedure SetForeColour(Const iColour : TColor);
Function GetMessagePntr : Pointer;
Procedure SetMessagePntr(Const ptrValue : Pointer);
// General Methods
Public
Constructor Create(Const strMsg : String; Const FontName : String;
Const ForeColour : TColor = clBlack; Const Style : TFontStyles = [];
Const BackColour : TColor = clWindow);
End;
Implementation
Uses
SysUtils;
(**
Calculates the bounding rectangle. CalcRect computes the bounding box required by the entire message.
The message view itself always displays messages in a single line of a fixed size. If the user hovers
the cursor over a long message, a tooltip displays the entire message. CalcRect returns the size of the
tooltip window. The Canvas parameter is the canvas for drawing the message. The MaxWidth parameter is
the maximum allowed width of the bounding box (e.g., the screen width). The Wrap Parameter is true to
word-wrap the message onto multiple lines. It is false if the message must be kept to one line. The
Return value is the bounding rectangle required by the message.
@precon None.
@postcon We calculate the size of the message here.
@nocheck MissingCONSTInParam
@nohint MaxWidth Wrap
@param Canvas as a TCanvas
@param MaxWidth as an Integer
@param Wrap as a Boolean
@return a TRect
**)
Function TITHCustomMessage.CalcRect(Canvas: TCanvas; MaxWidth: Integer; Wrap: Boolean): TRect; //FI:O804
Const
strTextHeightTest = 'Wp';
Begin
Canvas.Font.Name := FFontName;
Canvas.Font.Style := FStyle;
Result := Canvas.ClipRect;
Result.Bottom := Result.Top + Canvas.TextHeight(strTextHeightTest);
Result.Right := Result.Left + Canvas.TextWidth(FMsg);
End;
(**
This is the constructor for the TCustomMessage class.
@precon None.
@postcon Creates a custom message with fore and background colours and font styles.
@param strMsg as a String as a constant
@param FontName as a String as a constant
@param ForeColour as a TColor as a constant
@param Style as a TFontStyles as a constant
@param BackColour as a TColor as a constant
**)
Constructor TITHCustomMessage.Create(Const strMsg: String; Const FontName: String;
Const ForeColour: TColor = clBlack; Const Style: TFontStyles = [];
Const BackColour: TColor = clWindow);
Const
strValidChars: Set Of AnsiChar = [#10, #13, #32 .. #128];
Var
i: Integer;
iLength: Integer;
Begin
SetLength(FMsg, Length(strMsg));
iLength := 0;
For i := 1 To Length(strMsg) Do
{$IFDEF D2009}
If CharInSet(strMsg[i], strValidChars) Then
{$ELSE}
If strMsg[i] In strValidChars Then
{$ENDIF}
Begin
FMsg[iLength + 1] := strMsg[i];
Inc(iLength);
End;
SetLength(FMsg, iLength);
FFontName := FontName;
FForeColour := ForeColour;
FStyle := Style;
FBackColour := BackColour;
FMessagePntr := Nil;
End;
(**
Draws the message. Draw draws the message in the message view window or in a tooltip window. The Canvas
parameter is the canvas on which to draw the message. The Rect parameter is the bounding box for the
message. If you draw outside this rectangle, you might obscure other messages. The Wrap Parameter is
true to word-wrap the message on multiple lines or false to keep the message on a single line. The
message view window always uses a single line for each message, but the tooltip (which the user sees by
hovering the cursor over the message) can be multiple lines. The drawing objects (brush, pen, and font
) are set up appropriately for drawing messages that look like all the other messages in the message
view. In particular, the brush and font colors are set differently depending on whether the message is
selected. A custom-drawn message should not alter the colors or other graphic parameters without good
reason.
@precon None.
@postcon This is where we draw the message on the canvas.
@nocheck MissingCONSTInParam
@nohint Wrap
@param Canvas as a TCanvas
@param Rect as a TRect as a constant
@param Wrap as a Boolean
**)
Procedure TITHCustomMessage.Draw(Canvas: TCanvas; Const Rect: TRect; Wrap: Boolean); //FI:O804
Begin
If Canvas.Brush.Color = clWindow Then
Begin
Canvas.Font.Color := FForeColour;
Canvas.Brush.Color := FBackColour;
Canvas.FillRect(Rect);
End;
Canvas.Font.Name := FFontName;
Canvas.Font.Style := FStyle;
Canvas.TextOut(Rect.Left, Rect.Top, FMsg);
End;
(**
Returns the column number.
GetColumnNumber returns the column number in the associated source file. When
the user double-clicks the message in the message view, the IDE shows the
source file and positions the cursor at the location given by the line number
and column number.
@precon None.
@postcon We does use this in this implementation but you would return the
column number for your message here.
@return an Integer
**)
Function TITHCustomMessage.GetColumnNumber: Integer;
Begin
Result := 0;
End;
(**
Returns the source file name.
GetFileName returns the complete path to the associated source file. When the
user double-clicks the message in the message view, the IDE shows the source
file and positions the cursor at the location given by the line number and
column number.
Return an empty string if the message is not associated with a source file.
@precon None.
@postcon We return an empty string for this implementation othereise you would
return the full name and path of the file associated with the
message.
@return a String
**)
Function TITHCustomMessage.GetFileName: String;
Begin
Result := '';
End;
(**
Returns the line number.
GetLineNumber returns the line number in the associated source file. When the
user double-clicks the message in the message view, the IDE shows the source
file and positions the cursor at the location given by the line number and
column number.
@precon None.
@postcon We return 0 for out implementation but you would return the line
number of the message here.
@return an Integer
**)
Function TITHCustomMessage.GetLineNumber: Integer;
Begin
Result := 0;
End;
(**
Returns the text of the message.
GetLineText returns the text of the custom message.
@precon None.
@postcon Here we return the message
@return a String
**)
Function TITHCustomMessage.GetLineText: String;
Begin
Result := FMsg;
End;
(**
This is a getter method for the MessagePtr property.
@precon None.
@postcon Returns the message pointer (used in parenting messages).
@return a Pointer
**)
Function TITHCustomMessage.GetMessagePntr: Pointer;
Begin
Result := FMessagePntr;
End;
(**
This is a setter method for the ForeColour property.
@precon None.
@postcon Sets the message fore colour.
@param iColour as a TColor as a constant
**)
Procedure TITHCustomMessage.SetForeColour(Const iColour: TColor);
Begin
If FForeColour <> iColour Then
FForeColour := iColour;
End;
(**
This is a setter method for the MessagePtr property.
@precon None.
@postcon Sets the message pointer (used in parenting messages).
@param ptrValue as a Pointer as a constant
**)
Procedure TITHCustomMessage.SetMessagePntr(Const ptrValue: Pointer);
Begin
If FMessagePntr <> ptrValue Then
FMessagePntr := ptrValue;
End;
(**
Provides help for the message.
When the user selects the custom message and presses the F1 key, the IDE calls
the ShowHelp function to provide help to the user.
@nocheck EmptyMethod
@precon None.
@postcon Not implemented but you would display the custom help for the message
here.
**)
Procedure TITHCustomMessage.ShowHelp;
Begin //FI:W519
End;
End.
|
program Sample;
var
H, G : String;
begin
H := 'Hello World';
G := H;
WriteLn(G);
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, Vcl.ExtCtrls, RzPanel,
RzButton, System.ImageList,
Vcl.ImgList, Vcl.ComCtrls, Vcl.ToolWin, AppConstants, Vcl.StdCtrls, RzLabel,
RzStatus, StatusIntf, DockIntf, RzLstBox, Client, Vcl.AppEvnts,
ClientListIntf, Generics.Collections, LoanListIntf, Loan, LoanClient, RzTabs,
Vcl.Imaging.pngimage, System.Actions, Vcl.ActnList, Vcl.Buttons, RzCmboBx;
type
TRecentClient = class
strict private
FId: string;
FDisplayId: string;
FName: string;
public
property Id: string read FId write FId;
property DisplayId: string read FDisplayId write FDisplayId;
property Name: string read FName write FName;
constructor Create(const id, displayId, name: string);
end;
type
TRecentLoan = class
strict private
FId: string;
FClient: TLoanClient;
FStatus: string;
public
property Id: string read FId write FId;
property Client: TLoanClient read FClient write FClient;
property Status: string read FStatus write FStatus;
constructor Create(const id, status: string; cl: TLoanClient);
end;
type
TfrmMain = class(TForm,IDock)
pnlTitle: TRzPanel;
imgClose: TImage;
lblCaption: TRzLabel;
pnlMain: TRzPanel;
pnlNavBar: TRzPanel;
pnlDockMain: TRzPanel;
mmMain: TMainMenu;
File1: TMenuItem;
Save1: TMenuItem;
alMain: TActionList;
acSave: TAction;
acAddClient: TAction;
Newclient1: TMenuItem;
acNewLoan: TAction;
Newloan1: TMenuItem;
acGenericNew: TAction;
New1: TMenuItem;
lblDate: TLabel;
lblVersion: TLabel;
Client1: TMenuItem;
Loan1: TMenuItem;
Selectclient1: TMenuItem;
acSelectClient: TAction;
lblLocation: TLabel;
Newpayment1: TMenuItem;
acNewPayment: TAction;
Payment1: TMenuItem;
Selectclient2: TMenuItem;
acAddActiveLoan: TAction;
imgMinimize: TImage;
pcMenu: TRzPageControl;
tsHome: TRzTabSheet;
tsAdministration: TRzTabSheet;
tsTools: TRzTabSheet;
pnlAddClient: TRzPanel;
imgAddClient: TImage;
pnlCancel: TRzPanel;
imgCancel: TImage;
pnlNewLoan: TRzPanel;
imgNewLoan: TImage;
pnlPayment: TRzPanel;
imgNewPayment: TImage;
pnlSave: TRzPanel;
imgSave: TImage;
lblWelcome: TRzLabel;
pnlSearchClient: TRzPanel;
imgSearchClient: TImage;
pnlLoanList: TRzPanel;
imgLoanList: TImage;
pnlMaintenance: TRzPanel;
imgMaintenance: TImage;
pnlSettings: TRzPanel;
imgSettings: TImage;
pnlWithdrawals: TRzPanel;
imgWithdrawals: TImage;
pnlPaymentList: TRzPanel;
imgPaymentList: TImage;
pnlChangeDate: TRzPanel;
imgChangeDate: TImage;
pnlFixSequence: TRzPanel;
imgFixSequence: TImage;
RzPanel1: TRzPanel;
Label1: TLabel;
cmbRecentItems: TRzComboBox;
pnlSecurity: TRzPanel;
imgSecurity: TImage;
pnlExpense: TRzPanel;
imgExpense: TImage;
procedure tbAddClientClick(Sender: TObject);
procedure lblRecentlyAddedClick(Sender: TObject);
procedure tbEmployerClick(Sender: TObject);
procedure tbBanksClick(Sender: TObject);
procedure tbDesignationListClick(Sender: TObject);
procedure lblActiveClientsClick(Sender: TObject);
procedure lblAllClientsClick(Sender: TObject);
procedure tbLoanClassClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure tbNewLoanClick(Sender: TObject);
procedure urlCancelledClick(Sender: TObject);
procedure urlPendingLoansClick(Sender: TObject);
procedure urlActiveLoansClick(Sender: TObject);
procedure urlApprovedLoansClick(Sender: TObject);
procedure urlDeniedClick(Sender: TObject);
procedure npMainChange(Sender: TObject);
procedure tbCompetitorClick(Sender: TObject);
procedure urlAssessedLoansClick(Sender: TObject);
procedure pnlTitleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgCloseClick(Sender: TObject);
procedure imgAddClientMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgAddClientMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgPurposeClick(Sender: TObject);
procedure Save1Click(Sender: TObject);
procedure imgSaveClick(Sender: TObject);
procedure imgCancelClick(Sender: TObject);
procedure acGenericNewExecute(Sender: TObject);
procedure imgMaintenanceClick(Sender: TObject);
procedure imgLoanTypeClick(Sender: TObject);
procedure imgAcctTypeClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure imgLoanCancellationReasonListClick(Sender: TObject);
procedure imgRejectionReasonListClick(Sender: TObject);
procedure acSelectClientExecute(Sender: TObject);
procedure imgSettingsClick(Sender: TObject);
procedure imgNewPaymentClick(Sender: TObject);
procedure acAddActiveLoanExecute(Sender: TObject);
procedure urlPaymentsClick(Sender: TObject);
procedure urlWithdrawalsClick(Sender: TObject);
procedure urlClosedClick(Sender: TObject);
procedure imgMinimizeClick(Sender: TObject);
procedure imgChargeTypesClick(Sender: TObject);
procedure imgInfoSourcesClick(Sender: TObject);
procedure imgLoanClosureReasonsListClick(Sender: TObject);
procedure imgSearchClientClick(Sender: TObject);
procedure imgLoanListClick(Sender: TObject);
procedure imgWithdrawalsClick(Sender: TObject);
procedure imgPaymentListClick(Sender: TObject);
procedure cmbRecentItemsClick(Sender: TObject);
procedure imgChangeDateClick(Sender: TObject);
procedure imgFixSequenceClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure imgSecurityClick(Sender: TObject);
procedure imgExpenseClick(Sender: TObject);
private
{ Private declarations }
DOCKED_FORM: TForms;
RecentClients: TObjectList<TRecentClient>;
RecentLoans: TObjectList<TRecentLoan>;
procedure OpenClientList(const filterType: TClientFilterType = cftAll);
procedure OpenLoanList(const filterType: TLoanFilterType = lftAll);
procedure ShowDevParams;
procedure SetCaptions;
procedure OpenRecentClient(AClient: TRecentClient);
procedure OpenRecentLoan(ALoan: TRecentLoan);
public
{ Public declarations }
procedure DockForm(const fm: TForms; const title: string = '');
procedure AddRecentClient(ct: TClient);
procedure AddRecentLoan(lln: TLoan);
end;
var
frmMain: TfrmMain;
const
MAX_RECENT_ITEMS = 10;
implementation
{$R *.dfm}
uses
ClientMain, SaveIntf, ClientList, DockedFormIntf, LoanMain, LoanList, LoanIntf,
FormsUtil, IFinanceGlobal, IFinanceDialogs, NewIntf, AppSettings,
PaymentMain, PaymentIntf, PaymentList, AccountingData, WithdrawalList, DevParams,
MaintenanceDrawer, ClientIntf, DBUtil, AppUtil, SecurityMain, Right,
ExpenseMain;
constructor TRecentClient.Create(const id, displayId, name: string);
begin
FId := id;
FDisplayId := displayId;
FName := name;
end;
constructor TRecentLoan.Create(const id, status: string; cl: TLoanClient);
begin
FId := id;
FStatus := status;
FClient := cl;
end;
procedure TfrmMain.OpenClientList(const filterType: TClientFilterType = cftAll);
var
title: string;
intf: IClientFilter;
intd: IDockedForm;
begin
case filterType of
cftAll: title := 'All clients';
cftActive: title := 'Active clients';
cftRecent: title := 'Newly-added clients';
end;
if (pnlDockMain.ControlCount = 0)
or (not Supports(pnlDockMain.Controls[0] as TForm,IClientFilter,intf)) then
DockForm(fmClientList,title);
if Supports(pnlDockMain.Controls[0] as TForm,IDockedForm,intd) then
intd.SetTitle(title);
if Supports(pnlDockMain.Controls[0] as TForm,IClientFilter,intf) then
intf.FilterList(filterType);
end;
procedure TfrmMain.OpenLoanList(const filterType: TLoanFilterType = lftAll);
var
title: string;
intf: ILoanListFilter;
intd: IDockedForm;
begin
case filterType of
lftAll: title := 'All loans';
lftPending: title := 'Pending loans';
lftAssessed: title := 'Assessed loans';
lftApproved: title := 'Approved loans';
lftActive: title := 'Active loans';
lftCancelled: title := 'Cancelled loans';
lftRejected: title := 'Rejected loans';
lftClosed: title := 'Closed loans';
end;
if (pnlDockMain.ControlCount = 0)
or (not Supports(pnlDockMain.Controls[0] as TForm,ILoanListFilter,intf)) then
DockForm(fmLoanList,title);
if Supports(pnlDockMain.Controls[0] as TForm,IDockedForm,intd) then
intd.SetTitle(title);
if Supports(pnlDockMain.Controls[0] as TForm,ILoanListFilter,intf) then
intf.FilterList(filterType);
end;
procedure TfrmMain.OpenRecentClient(AClient: TRecentClient);
var
intf: IClient;
begin
if Assigned(cln) then
begin
AddRecentClient(cln);
cln.Destroy;
cln := TClient.Create;
cln.Id := TRecentClient(AClient).Id;
cln.DisplayId := TRecentClient(AClient).DisplayId;
cln.Name := TRecentClient(AClient).Name;
cln.Retrieve(true);
if Supports(pnlDockMain.Controls[0] as TForm,IClient,intf) then
begin
intf.SetClientName;
intf.SetUnboundControls;
intf.LoadPhoto;
intf.SetLandLordControlsPres;
intf.SetLandLordControlsProv;
end;
end
else
begin
cln := TClient.Create;
cln.Id := TRecentClient(AClient).Id;
cln.DisplayId := TRecentClient(AClient).DisplayId;
DockForm(fmClientMain);
end;
end;
procedure TfrmMain.OpenRecentLoan(ALoan: TRecentLoan);
var
intf: ILoan;
begin
if Assigned(ln) then
begin
AddRecentLoan(ln);
ln.Destroy;
ln := TLoan.Create;
ln.Id := TRecentLoan(ALoan).Id;
ln.Client := TRecentLoan(ALoan).Client;
ln.Status := TRecentLoan(ALoan).Status;
ln.Action := laNone;
ln.Retrieve(true);
if Supports(pnlDockMain.Controls[0] as TForm,ILoan,intf) then
begin
intf.SetLoanHeaderCaption;
intf.RefreshDropDownSources;
intf.SetUnboundControls;
intf.InitForm;
end;
end
else
begin
ln := TLoan.Create;
ln.Id := TRecentLoan(ALoan).Id;
ln.Client := TRecentLoan(ALoan).Client;
ln.Status := TRecentLoan(ALoan).Status;
ln.Action := laNone;
DockForm(fmLoanMain);
end;
end;
procedure TfrmMain.pnlTitleMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
const
SC_DRAGMOVE = $F012;
begin
if Button = mbLeft then
begin
ReleaseCapture;
Perform(WM_SYSCOMMAND, SC_DRAGMOVE, 0);
end;
end;
procedure TfrmMain.urlClosedClick(Sender: TObject);
begin
OpenLoanList(lftClosed);
end;
procedure TfrmMain.Save1Click(Sender: TObject);
begin
imgSave.OnClick(Sender);
end;
procedure TfrmMain.ShowDevParams;
begin
with TfrmDevParams.Create(Application) do
begin
ShowModal;
Free;
SetCaptions;
DockForm(fmNone);
end;
end;
procedure TfrmMain.lblActiveClientsClick(Sender: TObject);
begin
OpenClientList(cftActive);
end;
procedure TfrmMain.lblAllClientsClick(Sender: TObject);
begin
OpenClientList;
end;
procedure TfrmMain.lblRecentlyAddedClick(Sender: TObject);
begin
OpenClientList(cftRecent);
end;
procedure TfrmMain.npMainChange(Sender: TObject);
const
CLIENTS = 0;
LOANS = 1;
EXPENSE = 2;
INVENTORY = 3;
REPORTS = 4;
begin
{case npMain.ActivePageIndex of
CLIENTS: OpenClientList(cftRecent);
LOANS: OpenLoanList(lftPending);
end;}
end;
procedure TfrmMain.tbAddClientClick(Sender: TObject);
begin
if ifn.User.HasRights([PRIV_CLIENT_ADD_NEW],true) then DockForm(fmClientMain);
end;
procedure TfrmMain.tbBanksClick(Sender: TObject);
begin
DockForm(fmBanksList);
end;
procedure TfrmMain.tbCompetitorClick(Sender: TObject);
begin
DockForm(fmCompetitorList);
end;
procedure TfrmMain.tbDesignationListClick(Sender: TObject);
begin
DockForm(fmDesignationList);
end;
procedure TfrmMain.tbEmployerClick(Sender: TObject);
begin
DockForm(fmEmployerList);
end;
procedure TfrmMain.tbLoanClassClick(Sender: TObject);
begin
DockForm(fmLoanClassList);
end;
procedure TfrmMain.tbNewLoanClick(Sender: TObject);
begin
if ifn.User.HasRights([PRIV_LOAN_ADD_NEW],true) then DockForm(fmLoanMain);
end;
procedure TfrmMain.urlActiveLoansClick(Sender: TObject);
begin
OpenLoanList(lftActive);
end;
procedure TfrmMain.urlApprovedLoansClick(Sender: TObject);
begin
OpenLoanList(lftApproved);
end;
procedure TfrmMain.urlAssessedLoansClick(Sender: TObject);
begin
OpenLoanList(lftAssessed);
end;
procedure TfrmMain.urlCancelledClick(Sender: TObject);
begin
OpenLoanList(lftCancelled);
end;
procedure TfrmMain.urlDeniedClick(Sender: TObject);
begin
OpenLoanList(lftRejected);
end;
procedure TfrmMain.urlPaymentsClick(Sender: TObject);
begin
DockForm(fmPaymentList);
end;
procedure TfrmMain.urlPendingLoansClick(Sender: TObject);
begin
OpenLoanList(lftPending);
end;
procedure TfrmMain.urlWithdrawalsClick(Sender: TObject);
begin
DockForm(fmWithdrawalList);
end;
procedure TfrmMain.DockForm(const fm: TForms; const title: string);
var
frm: TForm;
control: integer;
begin
//if (pnlDockMain.ControlCount = 0) or (DOCKED_FORM <> fm) then
begin
control := 0;
while control < pnlDockMain.ControlCount do
begin
if pnlDockMain.Controls[control] is TForm then
begin
(pnlDockMain.Controls[control] as TForm).Close;
(pnlDockMain.Controls[control] as TForm).Free;
end;
Inc(control);
end;
// instantiate form
case fm of
fmClientMain: frm := TfrmClientMain.Create(Application);
fmClientList: frm := TfrmClientList.Create(Application);
fmLoanMain: frm := TfrmLoanMain.Create(Application);
fmLoanList: frm := TfrmLoanList.Create(Application);
fmSettings: frm := TfrmAppSettings.Create(Application);
fmPaymentMain: frm := TfrmPaymentMain.Create(Application);
fmPaymentList: frm := TfrmPaymentList.Create(Application);
fmWithdrawalList: frm := TfrmWithdrawalList.Create(Application);
fmMaintenanceDrawer: frm := TfrmMaintenanceDrawer.Create(Application);
fmSecurityDrawer: frm := TfrmSecurityMain.Create(Application);
fmExpenseMain: frm := TfrmExpenseMain.Create(Application);
else
frm := nil;
end;
if Assigned(frm) then
begin
DOCKED_FORM := fm;
frm.ManualDock(pnlDockMain);
frm.Show;
end;
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
DOCKED_FORM := fmNone;
Height := 700; // for some reason form keeps on resizing...
dmAccounting := TdmAccounting.Create(Application);
// hide menu bar
Self.Menu := nil;
RecentClients := TObjectList<TRecentClient>.Create;
RecentLoans := TObjectList<TRecentLoan>.Create;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
{$ifdef TESTMODE}
SaveTestInfo;
{$endif}
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
SetCaptions;
// if ifn.RequiredConfigEmpty then
//begin
// ShowErrorBox('Configuration has not been set properly. Please contact the system administrator.');
// Application.Terminate;
// end;
end;
procedure TfrmMain.imgPaymentListClick(Sender: TObject);
begin
DockForm(fmPaymentList);
end;
procedure TfrmMain.imgSearchClientClick(Sender: TObject);
begin
OpenClientList(cftRecent);
end;
procedure TfrmMain.imgSecurityClick(Sender: TObject);
begin
DockForm(fmSecurityDrawer);
end;
procedure TfrmMain.imgAcctTypeClick(Sender: TObject);
begin
DockForm(fmAcctTypeList);
end;
procedure TfrmMain.imgAddClientMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ButtonDown(Sender);
end;
procedure TfrmMain.imgAddClientMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ButtonUp(Sender);
end;
procedure TfrmMain.imgCancelClick(Sender: TObject);
var
intf: ISave;
begin
try
if pnlDockMain.ControlCount > 0 then
if Supports(pnlDockMain.Controls[0] as TForm,ISave,intf) then
intf.Cancel;
except
on e:Exception do
ShowErrorBox(e.Message);
end;
end;
procedure TfrmMain.imgChangeDateClick(Sender: TObject);
begin
ShowDevParams;
end;
procedure TfrmMain.imgChargeTypesClick(Sender: TObject);
begin
DockForm(fmChargeTypeList);
end;
procedure TfrmMain.imgCloseClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TfrmMain.imgExpenseClick(Sender: TObject);
begin
DockForm(fmExpenseMain);
end;
procedure TfrmMain.imgFixSequenceClick(Sender: TObject);
begin
try
FixSequence;
ShowConfirmationBox('ID sequence fixed successfully.');
except
on E: Exception do ShowErrorBox(E.Message);
end;
end;
procedure TfrmMain.imgMaintenanceClick(Sender: TObject);
begin
DockForm(fmMaintenanceDrawer);
end;
procedure TfrmMain.imgInfoSourcesClick(Sender: TObject);
begin
DockForm(fmInfoSourceList);
end;
procedure TfrmMain.imgLoanCancellationReasonListClick(Sender: TObject);
begin
DockForm(fmLoanCancelReasonList);
end;
procedure TfrmMain.imgLoanClosureReasonsListClick(Sender: TObject);
begin
DockForm(fmLoanCloseReasonList);
end;
procedure TfrmMain.imgLoanListClick(Sender: TObject);
begin
OpenLoanList(lftPending);
end;
procedure TfrmMain.imgLoanTypeClick(Sender: TObject);
begin
DockForm(fmLoanTypeList);
end;
procedure TfrmMain.imgMinimizeClick(Sender: TObject);
begin
Application.Minimize;
end;
procedure TfrmMain.imgNewPaymentClick(Sender: TObject);
begin
if ifn.User.HasRights([PRIV_PAY_ADD_NEW],true) then DockForm(fmPaymentMain);
end;
procedure TfrmMain.imgPurposeClick(Sender: TObject);
begin
DockForm(fmPurposeList);
end;
procedure TfrmMain.imgRejectionReasonListClick(Sender: TObject);
begin
DockForm(fmLoanRejectReasonList);
end;
procedure TfrmMain.imgSaveClick(Sender: TObject);
var
intf: ISave;
begin
try
if pnlDockMain.ControlCount > 0 then
if Supports(pnlDockMain.Controls[0] as TForm,ISave,intf) then
if intf.Save then ShowConfirmationBox;
except
on e:Exception do ShowErrorBox(e.Message);
end;
end;
procedure TfrmMain.imgSettingsClick(Sender: TObject);
begin
if ifn.User.HasRights([PRIV_SETTINGS],true) then DockForm(fmSettings);
end;
procedure TfrmMain.imgWithdrawalsClick(Sender: TObject);
begin
DockForm(fmWithdrawalList);
end;
procedure TfrmMain.acGenericNewExecute(Sender: TObject);
var
intf: INew;
begin
try
if pnlDockMain.ControlCount > 0 then
if Supports(pnlDockMain.Controls[0] as TForm,INew,intf) then
intf.New;
except
on e:Exception do
ShowErrorBox(e.Message);
end;
end;
procedure TfrmMain.acAddActiveLoanExecute(Sender: TObject);
var
intf: IPayment;
begin
try
if pnlDockMain.ControlCount > 0 then
if Supports(pnlDockMain.Controls[0] as TForm,IPayment,intf) then
intf.AddActiveLoan;
except
on e:Exception do
ShowErrorBox(e.Message);
end;
end;
procedure TfrmMain.acSelectClientExecute(Sender: TObject);
var
intf: ILoan;
begin
try
if pnlDockMain.ControlCount > 0 then
if Supports(pnlDockMain.Controls[0] as TForm,ILoan,intf) then
intf.SelectClient;
except
on e:Exception do
ShowErrorBox(e.Message);
end;
end;
procedure TfrmMain.AddRecentClient(ct: TClient);
begin
end;
procedure TfrmMain.AddRecentLoan(lln: TLoan);
var
ll: TRecentLoan;
begin
if lln.Action <> laCreating then
begin
for ll in RecentLoans do
begin
if ll.Id = lln.Id then // update when found
begin
ll.Status := lln.Status;
Exit;
end;
end;
ll := TRecentLoan.Create(lln.Id,lln.Status,lln.Client);
if RecentLoans.Count >= MAX_RECENT_ITEMS then
begin
// remove topmost item
RecentLoans.Remove(RecentLoans.Items[0]);
end;
RecentLoans.Add(ll);
// lbxRecentLoans.Items.AddObject(ll.Client.Name,ll);
cmbRecentItems.Items.AddObject(ll.Id + ' ' + ll.Client.Name,ll);
end;
end;
procedure TfrmMain.cmbRecentItemsClick(Sender: TObject);
var
obj: TObject;
index: integer;
begin
index := cmbRecentItems.ItemIndex;
if index > -1 then
begin
obj := cmbRecentItems.Items.Objects[index];
if obj is TRecentClient then OpenRecentClient((obj as TRecentClient))
else OpenRecentLoan((obj as TRecentLoan));
end;
end;
procedure TfrmMain.SetCaptions;
begin
lblCaption.Caption := ifn.AppName + ' - ' + ifn.AppDescription;
lblWelcome.Caption := 'Welcome back ' + ifn.User.Name + '.';
lblDate.Caption := 'Today is ' + FormatDateTime('mmmm dd, yyyy', ifn.AppDate);
lblLocation.Caption := 'Location: ' + ifn.GetLocationNameByCode(ifn.LocationCode);
lblVersion.Caption := 'Version ' + ifn.Version;
end;
end.
|
unit DUnitTestingCore;
interface
uses
SysUtils, Variants, System.Generics.Collections, System.Generics.Defaults, TestFramework, TestStructureUnit, RTTI, Classes;
type
TCoreTestCaseClass = class of TCoreTestCase;
// TestSuites
TCoreTestSuite = class (TTestSuite)
private
FSuiteName: string;
FSuitePath: string;
public
constructor Create(aSuitePath: string; aSuiteName: string; Tests: TTestCaseList; aTestClass: TCoreTestCaseClass); overload;
procedure AddTests(Tests: TTestCaseList; aTestClass: TCoreTestCaseClass); virtual;
end;
//TestCases
TCoreTestCase = class (TTestCase)
protected
FFolderName: string;
FSuitePath: string;
FSuiteName: string;
FTestClass: TCoreTestCaseClass;
FMethodName: string;
FTestInstance: TObject;
public
constructor Create(TestCase: TTestCaseRec); reintroduce; overload;
procedure AssertResults<T>(ExpectedResult: T; FactResult: T; Operation: string; FailMessageTemplate: string);
end;
procedure CreateDUnitTests(Suites: TSuiteList; Tests: TTestCaseList; aTestClass: TCoreTestCaseClass);
implementation
constructor TCoreTestCase.Create(TestCase: TTestCaseRec);
begin
inherited Create(TestCase.MethodName);
FFolderName := TestCase.TestCaseClass;
FSuitePath := TestCase.SuiteName;
FSuiteName := TestCase.SuiteName;
FTestName := TestCase.TestCaseName;
FMethodName := TestCase.MethodName;
end;
procedure TCoreTestCase.AssertResults<T>(ExpectedResult: T; FactResult: T; Operation: string; FailMessageTemplate: string);
var
AssertionResult: Boolean;
FactResultValue: TValue;
ExpectedResultValue: TValue;
FailMessageValue: String;
begin
if Operation = 'except' then
CheckException(fMethod, Exception, '')
else
begin
FactResultValue := TValue.From<T>(FactResult);
ExpectedResultValue := TValue.From<T>(ExpectedResult);
if Operation = 'equals' then
AssertionResult := FactResultValue.AsVariant = ExpectedResultValue.AsVariant;
if Operation = 'not equals' then
AssertionResult := FactResultValue.AsVariant <> ExpectedResultValue.AsVariant;
if Operation = 'larger than' then
AssertionResult := FactResultValue.AsVariant > ExpectedResultValue.AsVariant;
if Operation = 'equals or larger than' then
AssertionResult := FactResultValue.AsVariant >= ExpectedResultValue.AsVariant;
if Operation = 'less than' then
AssertionResult := FactResultValue.AsVariant < ExpectedResultValue.AsVariant;
if Operation = 'equals or less than' then
AssertionResult := FactResultValue.AsVariant <= ExpectedResultValue.AsVariant;
if Operation = 'contains' then
AssertionResult := Pos(VarToStr(FactResultValue.AsVariant), VarToStr(ExpectedResultValue.AsVariant)) > 0;
if Operation = 'not contains' then
AssertionResult := Pos(VarToStr(FactResultValue.AsVariant), VarToStr(ExpectedResultValue.AsVariant)) = 0;
FailMessageValue := StringReplace(FailMessageTemplate, '%r', VarToStr(FactResultValue.AsVariant), [rfReplaceAll]);
FailMessageValue := StringReplace(FailMessageValue, '%o', Operation, [rfReplaceAll]);
FailMessageValue := StringReplace(FailMessageValue, '%e', VarToStr(ExpectedResultValue.AsVariant), [rfReplaceAll]);
if Pos(' not not', FailMessageValue) > 0 then
FailMessageValue := StringReplace(FailMessageValue, ' not not', '', [rfReplaceAll]);
Check(AssertionResult = true, FailMessageValue);
end;
end;
constructor TCoreTestSuite.Create(aSuitePath: string; aSuiteName: string; Tests: TTestCaseList; aTestClass: TCoreTestCaseClass);
begin
inherited Create(aSuiteName);
FSuitePath := aSuitePath;
FSuiteName := aSuiteName;
AddTests(Tests, aTestClass);
end;
procedure TCoreTestSuite.AddTests(Tests: TTestCaseList; aTestClass: TCoreTestCaseClass);
var
TestCaseIndex: integer;
MethodName: string;
TestName: string;
SuiteName: string;
begin
for TestCaseIndex := 0 to Length(Tests) - 1 do
begin
MethodName := Tests[TestCaseIndex].MethodName;
SuiteName := Tests[TestCaseIndex].SuiteName;
if SuiteName = '' then
SuiteName := aTestClass.ClassName;
TestName := Tests[TestCaseIndex].TestCaseName;
if TestName = '' then
TestName := MethodName;
if (Tests[TestCaseIndex].SuiteName = Self.FSuiteName) and
(Tests[TestCaseIndex].TestCaseClass = aTestClass.ClassName)
then
begin
Self.AddTest(aTestClass.Create(Tests[TestCaseIndex]) as ITest);
end;
end;
end;
procedure CreateDUnitTests(Suites: TSuiteList; Tests: TTestCaseList; aTestClass: TCoreTestCaseClass);
var
iSuiteIndex: integer;
Suite: TCoreTestSuite;
begin
for iSuiteIndex := 0 to Length(Suites) - 1 do
begin
if Suites [iSuiteIndex].SuiteClassName = aTestClass.ClassName then
begin
Suite := TCoreTestSuite.Create(aTestClass.ClassName, Suites[iSuiteIndex].SuiteName, Tests, aTestClass);
RegisterTest(aTestClass.ClassName, Suite);
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit FMX.Design.Lang;
interface
uses
DesignIntf, FmxDesignWindows,
System.SysUtils, System.Classes, System.Rtti,
FMX.Forms, FMX.Dialogs, FMX.Types, FMX.Layouts, FMX.ListBox, FMX.Controls, FMX.StdCtrls,
FMX.Objects, FMX.Edit, FMX.Menus, FMX.ExtCtrls, FMX.Styles, FMX.Grid,
FMX.Header, FMX.Controls.Presentation;
type
TLangDesigner = class(TFmxDesignWindow)
OriginalList: TListBox;
btnAddItem: TButton;
langList: TPopupBox;
ToolBar1: TToolBar;
inputLang: TEdit;
HudLabel1: TLabel;
layoutSelect: TLayout;
HudLabel2: TLabel;
btnAddNewLang: TButton;
btnCancalAdd: TButton;
layoutAdd: TLayout;
layoutAddText: TLayout;
btnAddText: TButton;
btnCancelAddText: TButton;
inputAddText: TEdit;
btnRemoveItem: TButton;
btnCollect: TButton;
btnAddLang: TButton;
btnLoadTxt: TButton;
btnCreateTemplate: TButton;
btnLoadLng: TButton;
btnSaveLng: TButton;
OpenDialog1: TOpenDialog;
OpenDialog2: TOpenDialog;
SaveDialog1: TSaveDialog;
SaveDialog2: TSaveDialog;
StatusBar1: TStatusBar;
Layout1: TLayout;
Header1: THeader;
TextHeaderItem: THeaderItem;
StyleBook1: TStyleBook;
ListBoxHeader1: TListBoxHeader;
procedure btnAddClick(Sender: TObject);
procedure btnAddLangClick(Sender: TObject);
procedure langListChange(Sender: TObject);
procedure btnAddItemClick(Sender: TObject);
procedure btnRemoveItemClick(Sender: TObject);
procedure btnAddNewLangClick(Sender: TObject);
procedure btnCancalAddClick(Sender: TObject);
procedure btnCancelAddTextClick(Sender: TObject);
procedure btnAddTextClick(Sender: TObject);
procedure btnCollectClick(Sender: TObject);
procedure btnCreateTemplateClick(Sender: TObject);
procedure btnLoadTxtClick(Sender: TObject);
procedure btnLoadLngClick(Sender: TObject);
procedure btnSaveLngClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OriginalListChange(Sender: TObject);
procedure Header1ResizeItem(Sender: TObject; var NewSize: Single);
private
{ Private declarations }
procedure DoTranslateChanged(Sender: TObject);
public
{ Public declarations }
FLang: TLang;
procedure RebuildOriginalList;
end;
var
vgLangDesigner: TLangDesigner;
procedure ShowDsgnLang(Lang: TLang; ADesigner: IDesigner);
implementation
{$R *.fmx}
uses
System.Generics.Collections, System.Math, System.UITypes;
procedure ShowDsgnLang(Lang: TLang; ADesigner: IDesigner);
begin
vgLangDesigner := TLangDesigner.Create(Application);
vgLangDesigner.Designer := ADesigner;
with vgLangDesigner do
begin
FLang := Lang;
langList.Items.Assign(Lang.Resources);
if langList.Items.Count > 0 then
langList.ItemIndex := Lang.Resources.IndexOf(Lang.Lang);
layoutAdd.Visible := langList.Items.Count = 0;
layoutSelect.Visible := langList.Items.Count > 0;
RebuildOriginalList;
if ShowModal = mrOk then
begin
FLang.Lang := langList.Text;
vgLangDesigner.Designer.Modified;
end;
end;
vgLangDesigner.Free;
end;
procedure TLangDesigner.RebuildOriginalList;
var
I, OldItemIndex: Integer;
Str: TStrings;
Item: TListboxItem;
TextStyle: TControl;
begin
OldItemIndex := OriginalList.ItemIndex;
OriginalList.Clear;
if FLang.Original.Count = 0 then
begin
// create original from Collection
CollectLangStart;
TStyleManager.UpdateScenes;
FLang.Original.Assign(CollectLangStrings);
CollectLangFinish;
end;
Str := FLang.Original;
for I := 0 to Str.Count - 1 do
begin
Item := TListboxItem.Create(Self);
Item.AutoTranslate := false;
Item.StyleLookup := 'langitem';
Item.Text := Str[I];
Item.TextAlign := TTextAlign.Leading;
Item.Height := 23;
Item.Parent := OriginalList;
Item.ApplyStyleLookup;
if Item.FindStyleResource('translate') = nil then Continue;
if (FLang.Resources.Count > 0) and (langList.ItemIndex >= 0) then
begin
if FLang.LangStr[langList.Text] <> nil then
begin
Item.StylesData['translate'] := FLang.LangStr[langList.Text].Values[Str[I]];
Item.StylesData['translate.OnChangeTracking'] := TValue.From<TNotifyEvent>(DoTranslateChanged);
end;
end
else
(Item.FindStyleResource('translate') as IControl).Visible := false;
TextStyle := TControl(Item.FindStyleResource('text'));
if Assigned(TextStyle) then
TextStyle.Width := TextHeaderItem.Width - TextStyle.Margins.Left;
end;
if (OldItemIndex >= 0) and (OldItemIndex < OriginalList.Count) then
OriginalList.ItemIndex := OldItemIndex
else if OriginalList.Count > 0 then
OriginalList.ItemIndex := OriginalList.Count - 1
else
OriginalList.ItemIndex := -1;
end;
procedure TLangDesigner.btnAddClick(Sender: TObject);
begin
{ add new lang }
TListBox.Create(Self);
end;
procedure TLangDesigner.DoTranslateChanged(Sender: TObject);
begin
if (FLang.LangStr[langList.Text] <> nil) and (OriginalList.Selected <> nil) then
with FLang.LangStr[langList.Text] do
begin
Values[OriginalList.Selected.Text] := TEdit(Sender).Text;
end;
end;
procedure TLangDesigner.FormCreate(Sender: TObject);
const
TextMargins = 20;
var
Buttons: TList<TButton>;
i: Integer;
begin
//Layout buttons for localization
Buttons := TList<TButton>.Create;
try
btnRemoveItem.Enabled := False;
Buttons.Add(btnCollect);
Buttons.Add(btnCreateTemplate);
Buttons.Add(btnLoadLng);
Buttons.Add(btnSaveLng);
for i := 0 to Buttons.Count - 1 do
begin
if Assigned(Buttons.Items[i]) then
begin
with Buttons.Items[i] do
Width := System.Math.Max(70, Round(Canvas.TextWidth(Text)) + TextMargins);
end;
end;
finally
Buttons.Free;
end;
end;
procedure TLangDesigner.Header1ResizeItem(Sender: TObject; var NewSize: Single);
var
I: Integer;
Item: TListBoxItem;
TextStyle: TControl;
begin
for I := 0 to OriginalList.Count - 1 do
begin
Item := OriginalList.ItemByIndex(I);
TextStyle := TControl(Item.FindStyleResource('text'));
if Assigned(TextStyle) then
TextStyle.Width := TextHeaderItem.Width - TextStyle.Margins.Left;
end;
end;
procedure TLangDesigner.btnAddLangClick(Sender: TObject);
var
S: string;
begin
if inputLang.Text = '' then Exit;
S := inputLang.Text;
if Length(S) > 2 then
Delete(S, 3, MaxInt);
FLang.AddLang(S);
langList.Items := FLang.Resources;
langList.ItemIndex := langList.Items.IndexOf(S);
RebuildOriginalList;
layoutAdd.Visible := false;
layoutSelect.Visible := true;
Designer.Modified;
end;
procedure TLangDesigner.langListChange(Sender: TObject);
begin
RebuildOriginalList;
end;
procedure TLangDesigner.OriginalListChange(Sender: TObject);
begin
btnRemoveItem.Enabled := OriginalList.ItemIndex > -1 ;
end;
procedure TLangDesigner.btnAddNewLangClick(Sender: TObject);
begin
layoutAdd.Visible := true;
layoutSelect.Visible := false;
btnCancalAdd.Visible := langList.Items.Count > 0;
inputLang.Text := '';
inputLang.SetFocus;
end;
procedure TLangDesigner.btnCancalAddClick(Sender: TObject);
begin
if langList.Items.Count > 0 then
begin
layoutAdd.Visible := false;
layoutSelect.Visible := true;
end;
end;
procedure TLangDesigner.btnAddItemClick(Sender: TObject);
begin
{ Add Word }
layoutAdd.Visible := false;
layoutSelect.Visible := false;
layoutAddText.Visible := true;
inputAddText.Text := '';
inputAddText.SetFocus;
RebuildOriginalList;
end;
procedure TLangDesigner.btnRemoveItemClick(Sender: TObject);
begin
{ Remove Word }
if OriginalList.ItemIndex >= 0 then
begin
FLang.Original.Delete(OriginalList.ItemIndex);
RebuildOriginalList;
end;
end;
procedure TLangDesigner.btnCancelAddTextClick(Sender: TObject);
begin
layoutAdd.Visible := langList.Items.Count = 0;
layoutSelect.Visible := langList.Items.Count > 0;
layoutAddText.Visible := false;
end;
procedure TLangDesigner.btnAddTextClick(Sender: TObject);
begin
btnCancelAddTextClick(Sender);
FLang.Original.Add(inputAddText.Text);
RebuildOriginalList;
OriginalList.ItemIndex := OriginalList.Count - 1;
end;
procedure TLangDesigner.btnCollectClick(Sender: TObject);
var
Str: TStrings;
i: integer;
begin
CollectLangStart;
TStyleManager.UpdateScenes;
Str := TStringList.Create;
Str.Assign(CollectLangStrings);
for i := 0 to Str.Count - 1 do
if FLang.Original.IndexOf(Str[i]) < 0 then
FLang.Original.Add(Str[i]);
Str.Free;
CollectLangFinish;
RebuildOriginalList;
end;
procedure TLangDesigner.btnCreateTemplateClick(Sender: TObject);
var
Str: TStrings;
i: integer;
begin
if SaveDialog1.Execute then
begin
Str := TStringList.Create;
Str.Assign(FLang.Original);
for i := 0 to Str.Count - 1 do
Str[i] := Str[i] + '=';
Str.SaveToFile(SaveDialog1.FileName);
Str.Free;
end;
end;
procedure TLangDesigner.btnLoadTxtClick(Sender: TObject);
var
Str: TStrings;
i: integer;
begin
if OpenDialog1.Execute then
begin
FLang.AddLang(inputLang.Text);
langList.Items := FLang.Resources;
langList.ItemIndex := langList.Items.IndexOf(inputLang.Text);
RebuildOriginalList;
layoutAdd.Visible := false;
layoutSelect.Visible := true;
Str := TStringList.Create;
Str.LoadFromFile(OpenDialog1.FileName);
for i := 0 to Str.Count - 1 do
if FLang.LangStr[langList.Text].IndexOfName(Str.Names[i]) < 0 then
FLang.LangStr[langList.Text].Add(Str[i])
else
FLang.LangStr[langList.Text].Values[Str.Names[i]] := Str.Values[Str.Names[i]];
Str.Free;
RebuildOriginalList;
end;
end;
procedure TLangDesigner.btnLoadLngClick(Sender: TObject);
begin
if OpenDialog2.Execute then
begin
FLang.LoadFromFile(OpenDialog2.FileName);
RebuildOriginalList;
end;
end;
procedure TLangDesigner.btnSaveLngClick(Sender: TObject);
begin
if SaveDialog2.Execute then
begin
FLang.SaveToFile(SaveDialog2.FileName);
end;
end;
end.
|
unit MagicBrushFactory;
interface
uses MagicBrush, Graphics;
{
Фабрика создания кистей представляет собой абстрактную фабрику
}
type
TBrushType =(tsSimple, tsGradientBrush);
TMagicBrushFactory = class
public
function CreateBrush(aCanvas: TCanvas; aBrushType: TBrushType; anActiveColor: TColor; BrushWidth: Integer): TMagicBrush;
end;
var
aFactory: TMagicBrushFactory;
function CreateBrush(aCanvas: TCanvas; aBrushType: TBrushType; anActiveColor: TColor; BrushWidth: Integer): TMagicBrush;
implementation
uses MagicBrushFirstComplect, SysUtils;
{ TMagicBrushFactory }
function TMagicBrushFactory.CreateBrush(aCanvas: TCanvas; aBrushType: TBrushType;
anActiveColor: TColor; BrushWidth: Integer): TMagicBrush;
begin
Result := nil;
// Создаем кисти через фабрику
case aBrushType of
tsSimple: begin
Exception.Create('Unknown brush');
end;
tsGradientBrush: begin
aCanvas.Pen.Mode := pmCopy;
Result := TGradientBrush.Create(aCanvas) ;
Result.Width := BrushWidth;
Result.ActiveColor := anActiveColor;
end;
end;
end;
function CreateBrush(aCanvas: TCanvas; aBrushType: TBrushType; anActiveColor: TColor; BrushWidth: Integer):TMagicBrush;
begin
if Assigned(aFactory) then begin
Result := aFactory.CreateBrush(aCanvas, aBrushType, anActiveColor, BrushWidth);
end else begin
Exception.Create('Class brush not initializated');
end;
end;
// -------------------------При загрузке инициализируем переменную
// При выгрузке уничтожаем
initialization;
aFactory := TMagicBrushFactory.Create;
finalization
aFactory.Free;
aFactory := nil;
end.
|
unit uPow2Parser;
{$I ..\Include\IntXLib.inc}
interface
uses
{$IFDEF DELPHI}
Generics.Collections,
{$ENDIF DELPHI}
{$IFDEF FPC}
fgl,
{$ENDIF FPC}
uIParser,
uXBits,
uConstants,
uStrRepHelper,
uIntX,
uIntXLibTypes;
type
/// <summary>
/// Provides special fast (with linear time) parsing if base is pow of 2.
/// </summary>
TPow2Parser = class sealed(TInterfacedObject, IIParser)
public
/// <summary>
/// Parses provided string representation of <see cref="TIntX" /> object.
/// </summary>
/// <param name="value">Number as string.</param>
/// <param name="numberBase">Number base.</param>
/// <param name="charToDigits">Char->digit dictionary.</param>
/// <param name="checkFormat">Boolean that indicates if to check Input Format.</param>
/// <returns>Big Integer value.</returns>
function Parse(const value: String; numberBase: UInt32;
charToDigits: TDictionary<Char, UInt32>; checkFormat: Boolean)
: TIntX; overload;
/// <summary>
/// Parses provided string representation of <see cref="TIntX" /> object.
/// </summary>
/// <param name="value">Number as string.</param>
/// <param name="startIndex">Index inside string from which to start.</param>
/// <param name="endIndex">Index inside string on which to end.</param>
/// <param name="numberBase">Number base.</param>
/// <param name="charToDigits">Char->digit dictionary.</param>
/// <param name="digitsRes">Resulting digits.</param>
/// <returns>Parsed integer length.</returns>
function Parse(const value: String; startIndex: Integer; endIndex: Integer;
numberBase: UInt32; charToDigits: TDictionary<Char, UInt32>;
digitsRes: TIntXLibUInt32Array): UInt32; overload;
end;
implementation
function TPow2Parser.Parse(const value: String; numberBase: UInt32;
charToDigits: TDictionary<Char, UInt32>; checkFormat: Boolean): TIntX;
begin
result := Default (TIntX);
Exit;
end;
function TPow2Parser.Parse(const value: String; startIndex: Integer;
endIndex: Integer; numberBase: UInt32;
charToDigits: TDictionary<Char, UInt32>;
digitsRes: TIntXLibUInt32Array): UInt32;
var
bitsInChar, initialShift, i: Integer;
valueLength, digitsLength, digitIndex, digit: UInt32;
valueBitLength: UInt64;
begin
// Calculate length of input string
bitsInChar := TBits.Msb(numberBase);
valueLength := UInt32(endIndex - startIndex + 1);
valueBitLength := UInt64(valueLength) * UInt64(bitsInChar);
// Calculate needed digits length and first shift
digitsLength := UInt32(valueBitLength div TConstants.DigitBitCount) + 1;
digitIndex := digitsLength - 1;
initialShift := Integer(valueBitLength mod TConstants.DigitBitCount);
// Probably correct digits length
if (initialShift = 0) then
begin
Dec(digitsLength);
end;
// Do parsing in big cycle
i := startIndex;
while i <= (endIndex) do
begin
digit := TStrRepHelper.GetDigit(charToDigits, value[i], numberBase);
// Correct initial digit shift
if (initialShift = 0) then
begin
// If shift is equals to zero then char is not on digit elements bounds,
// so just go to the previous digit
initialShift := TConstants.DigitBitCount - bitsInChar;
Dec(digitIndex);
end
else
begin
// Here shift might be negative, but it's okay
initialShift := initialShift - bitsInChar;
end;
// Insert new digit in correct place
if initialShift < 0 then
digitsRes[digitIndex] := digitsRes[digitIndex] or
(digit shr - initialShift)
else
digitsRes[digitIndex] := digitsRes[digitIndex] or
(digit shl initialShift);
// In case if shift was negative we also must modify previous digit
if (initialShift < 0) then
begin
initialShift := initialShift + TConstants.DigitBitCount;
Dec(digitIndex);
digitsRes[digitIndex] := digitsRes[digitIndex] or
(digit shl initialShift);
end;
Inc(i);
end;
if (digitsRes[digitsLength - 1] = 0) then
begin
Dec(digitsLength);
end;
result := digitsLength;
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 untEasyClassinfCompany;
interface
uses
Classes, DB, DBClient, Variants;
type
TEasyinfCompany = class
private
{ Private declarations }
FCompanyGUID: string;
FCompanyCName: string;
FCompanyEName: string;
FCorporation: string;
FTel: string;
FFax: string;
FEmail: string;
FHomepage: string;
FCAddr: string;
FEAddr: string;
FPostCode: string;
FTax: string;
FChnTitle: string;
FEngTitle: string;
FChnTitle2: string;
FEngTitle2: string;
// Flogo: EasyNULLType;
FParentGUID: string;
FRemark: string;
FFlag: Integer;
FiOrder: Integer;
public
{ Public declarations }
property CompanyGUID: string read FCompanyGUID write FCompanyGUID;
property CompanyCName: string read FCompanyCName write FCompanyCName;
property CompanyEName: string read FCompanyEName write FCompanyEName;
property Corporation: string read FCorporation write FCorporation;
property Tel: string read FTel write FTel;
property Fax: string read FFax write FFax;
property Email: string read FEmail write FEmail;
property Homepage: string read FHomepage write FHomepage;
property CAddr: string read FCAddr write FCAddr;
property EAddr: string read FEAddr write FEAddr;
property PostCode: string read FPostCode write FPostCode;
property Tax: string read FTax write FTax;
property ChnTitle: string read FChnTitle write FChnTitle;
property EngTitle: string read FEngTitle write FEngTitle;
property ChnTitle2: string read FChnTitle2 write FChnTitle2;
property EngTitle2: string read FEngTitle2 write FEngTitle2;
// property logo: EasyNULLType read Flogo write Flogo;
property ParentGUID: string read FParentGUID write FParentGUID;
property Remark: string read FRemark write FRemark;
property Flag: Integer read FFlag write FFlag;
property iOrder: Integer read FiOrder write FiOrder;
class procedure GenerateinfCompany(var Data: OleVariant; AResult: TList);
class procedure AppendClientDataSet(ACds: TClientDataSet; AObj: TEasyinfCompany; var AObjList: TList);
class procedure EditClientDataSet(ACds: TClientDataSet; AObj: TEasyinfCompany; var AObjList: TList);
class procedure DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasyinfCompany; var AObjList: TList);
end;
implementation
{TEasyinfCompany}
class procedure TEasyinfCompany.GenerateinfCompany(var Data: OleVariant; AResult: TList);
var
I: Integer;
AEasyinfCompany: TEasyinfCompany;
AClientDataSet: TClientDataSet;
begin
//创建数据源,并获取数据
AClientDataSet := TClientDataSet.Create(nil);
AClientDataSet.Data := Data;
AClientDataSet.First;
try
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
//此句为实例化指定的对象
AEasyinfCompany := TEasyinfCompany.Create;
with AEasyinfCompany do
begin
//1 CompanyGUID
CompanyGUID := AClientDataSet.FieldByName('CompanyGUID').AsString;
//2 CompanyCName
CompanyCName := AClientDataSet.FieldByName('CompanyCName').AsString;
//3 CompanyEName
CompanyEName := AClientDataSet.FieldByName('CompanyEName').AsString;
//4 Corporation
Corporation := AClientDataSet.FieldByName('Corporation').AsString;
//5 Tel
Tel := AClientDataSet.FieldByName('Tel').AsString;
//6 Fax
Fax := AClientDataSet.FieldByName('Fax').AsString;
//7 Email
Email := AClientDataSet.FieldByName('Email').AsString;
//8 Homepage
Homepage := AClientDataSet.FieldByName('Homepage').AsString;
//9 CAddr
CAddr := AClientDataSet.FieldByName('CAddr').AsString;
//10 EAddr
EAddr := AClientDataSet.FieldByName('EAddr').AsString;
//11 PostCode
PostCode := AClientDataSet.FieldByName('PostCode').AsString;
//12 Tax
Tax := AClientDataSet.FieldByName('Tax').AsString;
//13 ChnTitle
ChnTitle := AClientDataSet.FieldByName('ChnTitle').AsString;
//14 EngTitle
EngTitle := AClientDataSet.FieldByName('EngTitle').AsString;
//15 ChnTitle2
ChnTitle2 := AClientDataSet.FieldByName('ChnTitle2').AsString;
//16 EngTitle2
EngTitle2 := AClientDataSet.FieldByName('EngTitle2').AsString;
//17 logo
// logo := AClientDataSet.FieldByName('logo').AsEasyNullType;
//18 ParentGUID
ParentGUID := AClientDataSet.FieldByName('ParentGUID').AsString;
//19 Remark
Remark := AClientDataSet.FieldByName('Remark').AsString;
//20 Flag
Flag := AClientDataSet.FieldByName('Flag').AsInteger;
//21 iOrder
iOrder := AClientDataSet.FieldByName('iOrder').AsInteger;
end;
//在此添加将对象存放到指定容器的代码
AResult.Add(AEasyinfCompany);
//如果要关联树也在此添加相应代码
AClientDataSet.Next;
end;
finally
AClientDataSet.Free;
end;
end;
class procedure TEasyinfCompany.AppendClientDataSet(ACds: TClientDataSet; AObj: TEasyinfCompany; var AObjList: TList);
begin
with ACds do
begin
Append;
//1 CompanyGUID
FieldByName('CompanyGUID').AsString := AObj.CompanyGUID;
//2 CompanyCName
FieldByName('CompanyCName').AsString := AObj.CompanyCName;
//3 CompanyEName
FieldByName('CompanyEName').AsString := AObj.CompanyEName;
//4 Corporation
FieldByName('Corporation').AsString := AObj.Corporation;
//5 Tel
FieldByName('Tel').AsString := AObj.Tel;
//6 Fax
FieldByName('Fax').AsString := AObj.Fax;
//7 Email
FieldByName('Email').AsString := AObj.Email;
//8 Homepage
FieldByName('Homepage').AsString := AObj.Homepage;
//9 CAddr
FieldByName('CAddr').AsString := AObj.CAddr;
//10 EAddr
FieldByName('EAddr').AsString := AObj.EAddr;
//11 PostCode
FieldByName('PostCode').AsString := AObj.PostCode;
//12 Tax
FieldByName('Tax').AsString := AObj.Tax;
//13 ChnTitle
FieldByName('ChnTitle').AsString := AObj.ChnTitle;
//14 EngTitle
FieldByName('EngTitle').AsString := AObj.EngTitle;
//15 ChnTitle2
FieldByName('ChnTitle2').AsString := AObj.ChnTitle2;
//16 EngTitle2
FieldByName('EngTitle2').AsString := AObj.EngTitle2;
//17 logo
// FieldByName('logo').AsEasyNullType := AObj.logo;
//18 ParentGUID
FieldByName('ParentGUID').AsString := AObj.ParentGUID;
//19 Remark
FieldByName('Remark').AsString := AObj.Remark;
//20 Flag
FieldByName('Flag').AsInteger := AObj.Flag;
//21 iOrder
FieldByName('iOrder').AsInteger := AObj.iOrder;
post;
end;
AObjList.Add(AObj);
end;
class procedure TEasyinfCompany.EditClientDataSet(ACds: TClientDataSet; AObj: TEasyinfCompany; var AObjList: TList);
begin
if ACds.Locate('CompanyGUID', VarArrayOf([AObj.CompanyGUID]), [loCaseInsensitive]) then
begin
with ACds do
begin
Edit;
//1 CompanyGUID
FieldByName('CompanyGUID').AsString := AObj.CompanyGUID;
//2 CompanyCName
FieldByName('CompanyCName').AsString := AObj.CompanyCName;
//3 CompanyEName
FieldByName('CompanyEName').AsString := AObj.CompanyEName;
//4 Corporation
FieldByName('Corporation').AsString := AObj.Corporation;
//5 Tel
FieldByName('Tel').AsString := AObj.Tel;
//6 Fax
FieldByName('Fax').AsString := AObj.Fax;
//7 Email
FieldByName('Email').AsString := AObj.Email;
//8 Homepage
FieldByName('Homepage').AsString := AObj.Homepage;
//9 CAddr
FieldByName('CAddr').AsString := AObj.CAddr;
//10 EAddr
FieldByName('EAddr').AsString := AObj.EAddr;
//11 PostCode
FieldByName('PostCode').AsString := AObj.PostCode;
//12 Tax
FieldByName('Tax').AsString := AObj.Tax;
//13 ChnTitle
FieldByName('ChnTitle').AsString := AObj.ChnTitle;
//14 EngTitle
FieldByName('EngTitle').AsString := AObj.EngTitle;
//15 ChnTitle2
FieldByName('ChnTitle2').AsString := AObj.ChnTitle2;
//16 EngTitle2
FieldByName('EngTitle2').AsString := AObj.EngTitle2;
//17 logo
// FieldByName('logo').AsEasyNullType := AObj.logo;
//18 ParentGUID
FieldByName('ParentGUID').AsString := AObj.ParentGUID;
//19 Remark
FieldByName('Remark').AsString := AObj.Remark;
//20 Flag
FieldByName('Flag').AsInteger := AObj.Flag;
//21 iOrder
FieldByName('iOrder').AsInteger := AObj.iOrder;
post;
end;
end;
end;
class procedure TEasyinfCompany.DeleteClientDataSet(ACds: TClientDataSet; AObj: TEasyinfCompany; var AObjList: TList);
var
I,
DelIndex: Integer;
begin
DelIndex := -1;
if ACds.Locate('CompanyGUID', VarArrayOf([AObj.CompanyGUID]), [loCaseInsensitive]) then
ACds.Delete;
for I := 0 to AObjList.Count - 1 do
begin
if TEasyinfCompany(AObjList[I]).CompanyGUID = TEasyinfCompany(AObj).CompanyGUID then
begin
DelIndex := I;
Break;
end;
end;
if DelIndex <> -1 then
begin
TEasyinfCompany(AObjList[DelIndex]).Free;
AObjList.Delete(DelIndex);
end;
end;
end.
|
{Algo: Jeu de nim
BUT:faire un jeu de Nim jouable par deux personnes
ENTREE:nombre d'allumette que va retirer chaque joueur
SORTIE:nombre d'allumette restantes, victoire ou défaite
CONSTANTE:
VARIABLE:
nb_allumette,nb_retirer: entier
victoire: booleen
DEBUT
ECRIRE: "Debut de partie de jeu de Nim a deux joueurs"
nb_allumette<-21
nb_retirer<-0
victoire<-FAUX
Repeter
ECRIRE:"Veuillez choisir le nombre d'allumette a retirer"
LIRE nb_retirer
SI nb_retirer <1 OU >3 ALORS
ECRIRE:"Votre nombre d'allumette a retirer n'est pas valide"
SINON
nb_allumette<-nb_allumette-nb_retirer
SI nb_allumette=1 ALORS
victoire<-VRAI
ECRIRE:"Vous avez gagner !"
SINON
ECRIRE:"nombre d allumettes : ",nb_allumette," Au joueur suivant"
SI nb_allumette<=0 ALORS
victoire<-VRAI
ECRIRE:"Vous avez perdu !"
Jusqu'a victoire=VRAI
END.}
program Jeu_de_Nim_deux_joueurs;
uses crt;
var
nb_allumette,nb_retirer:integer;
victoire:boolean;
begin
clrscr;
writeln('Debut de partie de jeu de Nim a deux joueurs');
nb_allumette:=21;
nb_retirer:=0;
victoire:=false;
Repeat
writeln('Veuillez choisir le nombre d allumette a retirer');
readln(nb_retirer);
IF (nb_retirer<1) OR (nb_retirer>3) THEN
writeln('Votre nombre d allumette a retirer n est pas valide')
ELSE
nb_allumette:= nb_allumette-nb_retirer;
IF nb_allumette=1 THEN
begin
victoire:=true;
writeln('Vous avez gagne !');
end
ELSE
begin
writeln('nombre d allumette : ',nb_allumette,' Au joueur suivant')
end;
IF nb_allumette<=0 THEN
begin
victoire:=true;
writeln('Vous avez perdu !');
end;
until victoire=true;
readln;
END.
|
unit sNIF.cmdline;
{ *******************************************************
sNIF
Utilidad para buscar ficheros ofimáticos con
cadenas de caracteres coincidentes con NIF/NIE.
*******************************************************
2012-2018 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
interface
uses
sNIF.params;
function parsearLineaComandos: TsNIFParametros;
implementation
uses
System.variants,
System.Classes,
CLIVersion,
IOUtils,
IOUtilsFix,
sNIF.params.DEF,
KV.Definition,
KV.Validator,
sNIF.cmdline.DEF,
System.SysUtils;
{ Mensaje por pantalla cuando se ejecuta sin parámetros }
procedure noHayParametros;
var
Major, Minor, Release, Build: integer;
I: integer;
begin
WriteLn('Efectúa una exploración binaria de ficheros en busca');
WriteLn('de cadenas coincidentes con el NIF/NIE de persona física.');
WriteLn('Preserva las fechas de último acceso, si es posible.');
WriteLn;
WriteLn('PARÁMETROS');
WriteLn;
for I := 0 to CmdLineParams.Count - 1 do
begin
WriteLn(CmdLineParams.keyDefByIndex[I].Description);
WriteLn(CmdLineParams.keyDefByIndex[I].ValidValueDescription);
WriteLn;
end;
WriteLn('Software en el Dominio Público. PROHIBIDA SU VENTA.');
if CLIExeVersion(Major, Minor, Release, Build) then
WriteLn(Format(' Versión %d.%d', [Major, Minor]));
Halt(10);
end;
{ detectaNIF -FicheroCarpetas <fichero> }
procedure leerFicheroCarpetas(const fichero: string; cfg: TsNIFParametros);
var
txt: TStringList;
I: integer;
begin
txt := TStringList.Create;
try
txt.LoadFromFile(fichero);
for I := 0 to txt.Count - 1 do
cfg.Carpetas.Add(txt.Strings[I]);
except
WriteLn('ERROR: imposible leer fichero de carpetas a explorar');
WriteLn('(' + fichero + ')');
Halt(1000);
end;
end;
{ detectaNIF -plantilla <fichero> }
procedure crearPlantilla(const fichero: string);
var
txt: TStringList;
paramDef: TKeyDefinition;
I: integer;
begin
txt := TStringList.Create;
for I := 0 to GlobalParamDef.Count - 1 do
begin
paramDef := GlobalParamDef.keyDefByIndex[I];
txt.Add('# ' + paramDef.Description);
txt.AddPair(paramDef.tag, paramDef.ValidValueDescription);
end;
try
txt.SaveToFile(fichero, TEncoding.UTF8);
except
WriteLn('ERROR: imposible crear plantilla');
Halt(104);
end;
WriteLn('Plantilla generada');
Halt(0);
end;
{ detectaNIF -cfg <fichero> }
procedure cargarCfg(const fichero: string; cfg: TsNIFParametros);
var
valores: TStringList;
begin
valores := TStringList.Create;
valores.Duplicates := dupAccept;
valores.CaseSensitive := false;
valores.Sorted := false;
try
valores.LoadFromFile(fichero);
KV.Validator.Validate(valores, GlobalParamDef,
procedure(const tag: string; const value: variant)
begin
with cfg do
if (CompareText(tag, PARAM_CARPETA) = 0) then
Carpetas.Add(value)
else if (CompareText(tag, PARAM_EXT) = 0) then
Extensiones.DelimitedText := value
else if (CompareText(tag, PARAM_MAXNIF) = 0) then
MaxNIF := value
else if (CompareText(tag, PARAM_MAXSINNIF) = 0) then
MaxSinNIF := value
else if (CompareText(tag, PARAM_MINBYTES) = 0) then
MinBytes := value
else if (CompareText(tag, PARAM_MINDIAS) = 0) then
MinDiasCreado := value
else if (CompareText(tag, PARAM_HILOS) = 0) then
NumHilos := value
else if (CompareText(tag, PARAM_ERRORES) = 0) then
IncluirErrores := value
else if (CompareText(tag, PARAM_RESUMEN) = 0) then
GenerarResumen := value
else if (CompareText(tag, PARAM_SALIDA) = 0) and (FicheroSalida = '')
then
FicheroSalida := value
end);
valores.Free;
except
on E: EInvalidValueException do
begin
WriteLn('ERROR DE CONFIGURACIÓN: valor inválido en parámetro "' +
E.tag + '"');
WriteLn(GlobalParamDef.KeyDefAtLastException.ValidValueDescription);
Halt(900);
end;
on E: EVariantTypeCastError do
begin
WriteLn('ERROR DE CONFIGURACIÓN: valor de tipo incorrecto en parámetro "'
+ GlobalParamDef.KeyDefAtLastException.tag + '"');
WriteLn(GlobalParamDef.KeyDefAtLastException.ValidValueDescription);
Halt(1000);
end;
// on E: EMinCardinalityException do
// begin
// WriteLn('ERROR DE CONFIGURACIÓN: parámetro "' + E.tag + '" obligatorio');
// Halt(900);
// end;
on E: EMaxCardinalityException do
begin
WriteLn('ERROR DE CONFIGURACIÓN: parámetro "' + E.tag + '" duplicado');
Halt(900);
end;
on E: EUnknownKeyException do
begin
WriteLn('ERROR DE CONFIGURACIÓN: parámetro "' + E.tag +
'" no reconocido');
Halt(900);
end;
on E: EStreamError do
begin
WriteLn('ERROR: el fichero de configuración no existe o no es accesible');
Halt(900);
end
else
raise;
end;
end;
procedure validarCfg(cfg: TsNIFParametros);
begin
if (cfg.esCompleto) then
begin
cfg.comprobarCoherencia;
if (not TFile.CanCreate(cfg.FicheroSalida)) then
begin
WriteLn('ERROR: imposible crear el fichero de salida');
WriteLn(cfg.FicheroSalida);
WriteLn;
Halt(100);
end;
end
else
begin
WriteLn('ERROR: faltan parametros imprescindibles para la exploración');
WriteLn('(carpeta a explorar, fichero de salida o extensiones de fichero)');
WriteLn;
Halt(100);
end;
end;
function parsearLineaComandos: TsNIFParametros;
var
cfg: TsNIFParametros;
begin
Result := nil;
if (ParamCount = 0) then
noHayParametros; // detiene la ejecución
cfg := TsNIFParametros.Create;
try
KV.Validator.ValidateCmdLine(CmdLineParams,
procedure(const tag: string; const value: variant)
begin
if (CompareText(tag, CMDLINE_CFG) = 0) then
cargarCfg(value, cfg)
else if (CompareText(tag, CMDLINE_PLANTILLA) = 0) then
crearPlantilla(value)
else if (CompareText(tag, CMDLINE_SALIDA) = 0) then
cfg.FicheroSalida := value
else if (CompareText(tag, CMDLINE_ENTRADA_FICHERO) = 0) then
leerFicheroCarpetas(value, cfg)
else if (CompareText(tag, CMDLINE_ENTRADA_CARPETA) = 0) then
cfg.Carpetas.Add(value);
end);
validarCfg(cfg);
Result := cfg;
except
on E: EVariantTypeCastError do
begin
WriteLn('ERROR: El parámetro "' + CmdLineParams.KeyDefAtLastException.tag
+ '" no admite el valor dado');
WriteLn(CmdLineParams.KeyDefAtLastException.ValidValueDescription);
Halt(1000);
end;
on E: EInvalidValueException do
begin
WriteLn('ERROR: Ruta mal formada en parámetro "' + E.tag + '"');
WriteLn('(' + CmdLineParams.KeyDefAtLastException.
ValueAtLastException + ')');
Halt(1000);
end;
on E: EMaxCardinalityException do
begin
WriteLn('ERROR: parámetro "' + E.tag + '" duplicado');
Halt(1000);
end;
on E: EUnknownKeyException do
begin
WriteLn('ERROR: parámetro "' + E.tag + '" no reconocido');
Halt(1000);
end
else
raise;
end;
end;
// function parsearLineaComandos: TsNIFParametros;
// var
// fichero, salida: string;
// begin
// Result := nil;
// if (ParamCount = 0) then
// noHayParametros
// else if (FindCmdLineSwitch(CMDLINE_PLANTILLA, fichero)) then
// crearPlantilla(fichero)
// else if (FindCmdLineSwitch(CMDLINE_CFG, fichero)) then
// try
// Result := cargarCfg(fichero);
// if (FindCmdLineSwitch(PARAM_SALIDA, salida)) then
// Result.FicheroSalida := salida;
// validarCfg(Result);
// except
// on E: EInvalidValueException do
// begin
// WriteLn('ERROR: valor inválido en parámetro "' + E.tag + '"');
// WriteLn(GlobalParamDef.KeyDefAtLastException.ValidValueDescription);
// Halt(1000);
// end;
// on E: EVariantTypeCastError do
// begin
// WriteLn('ERROR: valor de tipo incorrecto en parámetro "' +
// GlobalParamDef.KeyDefAtLastException.tag + '"');
// WriteLn(GlobalParamDef.KeyDefAtLastException.ValidValueDescription);
// Halt(1000);
// end;
// on E: EMinCardinalityException do
// begin
// WriteLn('ERROR: parámetro "' + E.tag + '" obligatorio');
// Halt(1000);
// end;
// on E: EMaxCardinalityException do
// begin
// WriteLn('ERROR: parámetro "' + E.tag + '" duplicado');
// Halt(1000);
// end;
// on E: EUnknownKeyException do
// begin
// WriteLn('ERROR: parámetro "' + E.tag + '" no reconocido');
// Halt(1000);
// end;
// on E: EStreamError do
// begin
// WriteLn('ERROR: el fichero de configuración no existe o no es accesible');
// Halt(1000);
// end
// else
// raise;
// end;
// if (Result = nil) then
// begin
// WriteLn('ERROR: se necesita un fichero de configuración');
// Halt(103);
// end;
// end;
end.
|
unit uSerialPort;
// This is a simple demonstration on how to use the SerialPort component
// for communicating with your PC's COM Port.
interface
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Control.Base, CNClrLib.Component.SerialPort;
type
TfrmSerialPort = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
cmbPortName: TComboBox;
cmbBauderate: TComboBox;
cmbParity: TComboBox;
cmbDataBits: TComboBox;
cmbStopBits: TComboBox;
btnConnect: TButton;
GroupBox2: TGroupBox;
rdText: TRadioButton;
rdHex: TRadioButton;
Label2: TLabel;
txtSend: TEdit;
btnSend: TButton;
btnClear: TButton;
CnSerialPort1: TCnSerialPort;
rtxtDataArea: TRichEdit;
procedure FormCreate(Sender: TObject);
procedure btnConnectClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CnSerialPort1DataReceived(Sender: TObject;
E: _SerialDataReceivedEventArgs);
private
procedure UpdatePorts();
procedure Connect();
procedure Disconnect();
procedure SendData();
function HexStringToByteArray(S: String): TArray<Byte>;
public
{ Public declarations }
end;
var
frmSerialPort: TfrmSerialPort;
implementation
{$R *.dfm}
uses CNClrLib.Host, CNClrLib.Host.Utils, CNClrLib.EnumArrays, CNClrLib.Host.Helper;
// Whenever the connect button is clicked, it will check if the port is already open,
// call the disconnect function.
procedure TfrmSerialPort.btnClearClick(Sender: TObject);
begin
// Clear the screen
rtxtDataArea.Clear;
txtSend.Clear;
end;
procedure TfrmSerialPort.btnConnectClick(Sender: TObject);
begin
if CnSerialPort1.IsOpen then
Disconnect
else
Connect;
end;
procedure TfrmSerialPort.btnSendClick(Sender: TObject);
begin
SendData;
end;
// When data is received on the port, it will raise this event
procedure TfrmSerialPort.CnSerialPort1DataReceived(Sender: TObject;
E: _SerialDataReceivedEventArgs);
var
receivedData: String;
begin
receivedData := CnSerialPort1.ReadExisting; // Read all available data in the receiving buffer
rtxtDataArea.Lines.Add(receivedData + 'n');
end;
procedure TfrmSerialPort.Connect;
var
error: Boolean;
clrEx: EClrException;
begin
error := False;
// Check if all settings have been selected
if (cmbPortName.ItemIndex <> -1) and (cmbBauderate.ItemIndex <> -1) and
(cmbParity.ItemIndex <> -1) and (cmbDataBits.ItemIndex <> -1) and
(cmbStopBits.ItemIndex <> -1) then
begin
CnSerialPort1.PortName := cmbPortName.Text;
CnSerialPort1.BaudRate := StrToInt(cmbBauderate.Text);
CnSerialPort1.Parity := TParity(OleEnumToOrd(ParityValues, cmbParity.ItemIndex));
CnSerialPort1.DataBits := StrToInt(cmbDataBits.Text);
CnSerialPort1.StopBits := TStopBits(OleEnumToOrd(StopBitsValues, cmbStopBits.ItemIndex));
try
//Open Port;
CnSerialPort1.Open;
except
on E: Exception do
begin
clrEx := EClrException.CreateEx(E);
try
if clrEx.IsTypeOf('System.UnauthorizedAccessException') or
clrEx.IsTypeOf('System.IO.IOException') or
clrEx.IsTypeOf('System.ArgumentException') then
begin
error := True;
end;
finally
clrEx.Free;
end;
end;
end;
if error then
begin
TClrMessageBox.Show(Self, 'Could not open the COM port. Most likely it is '+
'already in use, has been removed or is unavailable.', 'COM Port unavailable',
TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiStop);
end
else
begin
TClrMessageBox.Show(self, 'Please select all the COM Serial Port Settings', 'Serial Port Interface',
TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiStop);
end;
// If the port is open, change the Connect button to disconnect, enable the send button
if CnSerialPort1.IsOpen then
begin
btnConnect.Caption := 'Disconnect';
btnSend.Enabled := True;
GroupBox1.Enabled := False;
end;
end;
end;
// Call this function to close the port
procedure TfrmSerialPort.Disconnect;
begin
CnSerialPort1.Close;
btnConnect.Caption := 'Connect';
btnSend.Enabled := True;
GroupBox1.Enabled := True;
end;
procedure TfrmSerialPort.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if CnSerialPort1.IsOpen then
CnSerialPort1.Close; //Close the port if open when exiting the application
end;
procedure TfrmSerialPort.FormCreate(Sender: TObject);
begin
UpdatePorts;
end;
// Convert a string of hex digits (example: E1 FF 1B) to a byte array.
// The string containing the hex digits (with or without spaces)
// returns TArray<Byte>
function TfrmSerialPort.HexStringToByteArray(S: String): TArray<Byte>;
var
I: Integer;
m_length: Integer;
begin
S := StringReplace(S, ' ', '', [rfReplaceAll]);
m_length := Trunc(Length(S)/2);
SetLength(Result, m_length);
for I := 0 to Length(S) - 1 do
begin
if I mod 2 <> 0 then Continue;
Result[Trunc(I/2)] := TClrConvert.ToByte(Copy(S, i, 2), 16);
end;
end;
// a function to send data to the serial port
procedure TfrmSerialPort.SendData;
var
error: Boolean;
data: TArray<Byte>;
clrEx: EClrException;
begin
error := False;
if rdText.Checked then //If text mode is selected, send data has text.
begin
// send the user's text straight out the port
CnSerialPort1.Write(txtSend.Text);
// show in the terminal window
rtxtDataArea.Lines.Add(txtSend.Text + 'n');
txtSend.Clear; //Clear screen after sending data
end
else //If Hex Mode is selecetd, send data in hexidecimal
begin
try
// Convert the user's string to hex digits (example: E1 FF 1B) to a byte array;
data := HexStringToByteArray(txtSend.Text);
// Send the binary data out the port
CnSerialPort1.Write(data, 0, Length(data));
//Show the hex digits in the terminal window
rtxtDataArea.Lines.Add(UpperCase(txtSend.Text) + 'n');
txtSend.Clear; // Clear screen after sending
except
on E: Exception do
begin
clrEx := EClrException.CreateEx(E);
try
if clrEx.IsTypeOf('System.FormatException') or // Inform the user if the hex string was not properly formatted
clrEx.IsTypeOf('System.ArgumentException') then
begin
error := True;
end;
finally
clrEx.Free;
end;
end;
end;
if error then
begin
TClrMessageBox.Show(Self, 'Not properly formated hex string: '+ txtSend.Text + 'n', 'Format Error',
TMessageBoxButtons.mbbsOK, TMessageBoxIcon.mbiStop);
end;
end;
end;
procedure TfrmSerialPort.UpdatePorts;
var
port: String;
ports: TArray<String>;
begin
ports := TCnSerialPort.GetPortNames;
for port in ports do
begin
cmbPortName.Items.Add(port);
end;
end;
end.
|
{
File name: uUsersGroups.pas
Date: 2003/07/03
Author: Martin Matusu <xmat@volny.cz>
Copyright (C) 2003
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
in a file called COPYING along with this program; if not, write to
the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA
02139, USA.
}
{mate}
unit uUsersGroups;
{$mode objfpc}{$H+}
interface
uses
Classes, uMyUnix;
const
groupInfo = '/etc/group';
userInfo = '/etc/passwd';
function uidToStr(uid: Cardinal): String;
function gidToStr(gid: Cardinal): String;
function strToUID(uname: AnsiString): Cardinal;
function strToGID(gname: AnsiString): Cardinal;
procedure getUsrGroups(uid: Cardinal; List: TStrings);
procedure getUsers(List: TStrings);
procedure getGroups(List: TStrings);
implementation
uses
SysUtils;
function uidToStr(uid: Cardinal): String;
var
uinfo: PPasswordRecord;
begin
uinfo:= getpwuid(uid);
if (uinfo = nil) then
Result:= ''
else
Result:= String(uinfo^.pw_name);
end;
function gidToStr(gid: Cardinal): String;
var
ginfo: PGroupRecord;
begin
ginfo:= getgrgid(gid);
if (ginfo = nil) then
Result:= ''
else
Result:= String(ginfo^.gr_name);
end;
procedure getUsrGroups(uid: Cardinal; List: TStrings);
var
groups: TStrings;
iC,iD: integer;
sT: string;
begin
// parse groups records
groups:= TStringlist.Create;
try
List.Clear;
groups.LoadFromFile(groupInfo);
for ic:= 0 to (groups.Count - 1) do
begin
st:= groups.Strings[ic]; //get one record to parse
id:= Pos(UIDtoStr(uid), st); //get position of uname
if ((id<>0) or (uid=0)) then
begin
st:= Copy(st, 1, Pos(':',st) - 1);
List.Append(st);
end; // if
end; // for
finally
FreeAndNil(groups);
end;
end;
procedure getGroups(List: TStrings);
begin
getUsrGroups(0, List);
end;
procedure GetUsers(List: TStrings);
var
Users: TStrings;
iC: integer;
sT: string;
begin
users:= TStringList.Create;
try
users.LoadFromFile(userInfo);
List.Clear;
for ic:= 0 to (users.Count - 1) do
begin
st:= users.Strings[ic]; //get one record (line)
st:= copy(st, 1, Pos(':',st) - 1); //extract username
List.Append(st); //append to the list
end;
finally
FreeAndNil(users);
end;
end;
function strToUID(uname: AnsiString): Cardinal;
//Converts username to UID ('root' results to 0)
var
uinfo: PPasswordRecord;
begin
uinfo:= getpwnam(PChar(uname));
if (uinfo = nil) then
Result:= High(Cardinal)
else
Result:= uinfo^.pw_uid;
end;
function strToGID(gname: AnsiString): Cardinal;
var
ginfo: PGroupRecord;
begin
ginfo:= getgrnam(PChar(gname));
if (ginfo = nil) then
Result:= High(Cardinal)
else
Result:= ginfo^.gr_gid;
end;
{/mate}
end.
|
{Unit Start}
unit Fstart;
{Interface}
interface
{Procedure Start}
procedure start ();
{I.S. Tidak ad variabel input}
{F.S. Menampilkan pilihan menu dilayar}
{Implementation}
implementation
{Procedure Start}
procedure start ();
{Algoritma Procedure Start}
begin
writeln (' | -------------------------------------------------------------------------- |');
writeln (' | Selamat datang di Engis Kitchen |');
writeln (' | -------------------------------------------------------------------------- |');
writeln (' load : Membaca semua data dari file');
writeln (' exit : Keluar dari Engis Kitchen');
writeln (' startSimulasi : Memulai simulasi ke-N');
writeln (' stopSimulasi : Menghentikan simulasi');
writeln (' beliBahan : Membeli bahan mentah dari supermarket');
writeln (' olahBahan : Mengolah bahan mentah menjadi bahan olahan');
writeln (' jualOlahan : Menjual bahan olahan');
writeln (' jualResep : Membuat dan menjual hidangan berdasarkan resep');
writeln (' makan : Melakukan aktivitas makan');
writeln (' istirahat : Melakukan aktivitas istirahat');
writeln (' tidur : Melakukan aktivitas tidur');
writeln (' lihatStatistik : Menampilkan statistik');
writeln (' lihatInventori : Menampilkan barang di inventori');
writeln (' lihatResep : Melihat daftar resep');
writeln (' cariResep : Mencari resep');
writeln (' tambahResep : Menambahkan resep baru');
writeln (' upgradeInventori : Menambah kapasitas inventori');
writeln (' | -------------------------------------------------------------------------- |');
end;
end.
|
unit NtUtils.Files;
interface
uses
Winapi.WinNt, Ntapi.ntioapi, NtUtils.Exceptions, NtUtils.Objects;
type
TFileStreamInfo = record
StreamSize: Int64;
StreamAllocationSize: Int64;
StreamName: String;
end;
TFileHardlinkLinkInfo = record
ParentFileId: Int64;
FileName: String;
end;
{ Paths }
// Convert a Win32 path to an NT path
function RtlxDosPathToNtPath(DosPath: String; out NtPath: String): TNtxStatus;
function RtlxDosPathToNtPathVar(var Path: String): TNtxStatus;
// Get current path
function RtlxGetCurrentPath(out CurrentPath: String): TNtxStatus;
function RtlxGetCurrentPathPeb: String;
// Set a current directory
function RtlxSetCurrentPath(CurrentPath: String): TNtxStatus;
{ Open & Create }
// Create/open a file
function NtxCreateFile(out hxFile: IHandle; DesiredAccess: THandle;
FileName: String; Root: THandle = 0; CreateDisposition: Cardinal =
FILE_CREATE; ShareAccess: Cardinal = FILE_SHARE_ALL; CreateOptions:
Cardinal = 0; FileAttributes: Cardinal = FILE_ATTRIBUTE_NORMAL;
HandleAttributes: Cardinal = 0; ActionTaken: PCardinal = nil): TNtxStatus;
// Open a file
function NtxOpenFile(out hxFile: IHandle; DesiredAccess: TAccessMask;
FileName: String; Root: THandle = 0; ShareAccess: THandle = FILE_SHARE_ALL;
OpenOptions: Cardinal = 0; HandleAttributes: Cardinal = 0): TNtxStatus;
// Open a file by ID
function NtxOpenFileById(out hxFile: IHandle; DesiredAccess: TAccessMask;
FileId: Int64; Root: THandle = 0; ShareAccess: THandle = FILE_SHARE_READ or
FILE_SHARE_WRITE or FILE_SHARE_DELETE; HandleAttributes: Cardinal = 0)
: TNtxStatus;
{ Operations }
// Rename a file
function NtxRenameFile(hFile: THandle; NewName: String;
ReplaceIfExists: Boolean = False; RootDirectory: THandle = 0): TNtxStatus;
// Creare a hardlink for a file
function NtxHardlinkFile(hFile: THandle; NewName: String;
ReplaceIfExists: Boolean = False; RootDirectory: THandle = 0): TNtxStatus;
{ Information }
// Query variable-length information
function NtxQueryFile(hFile: THandle; InfoClass: TFileInformationClass;
out xMemory: IMemory; InitialBufferSize: Cardinal = 0): TNtxStatus;
// Set variable-length information
function NtxSetFile(hFile: THandle; InfoClass: TFileInformationClass;
Buffer: Pointer; BufferSize: Cardinal): TNtxStatus;
type
NtxFile = class
// Query fixed-size information
class function Query<T>(hFile: THandle;
InfoClass: TFileInformationClass; out Buffer: T): TNtxStatus; static;
// Set fixed-size information
class function SetInfo<T>(hFile: THandle;
InfoClass: TFileInformationClass; const Buffer: T): TNtxStatus; static;
end;
// Query name of a file
function NtxQueryNameFile(hFile: THandle; out Name: String): TNtxStatus;
// Enumerate file streams
function NtxEnumerateStreamsFile(hFile: THandle; out Streams:
TArray<TFileStreamInfo>) : TNtxStatus;
// Enumerate hardlinks pointing to the file
function NtxEnumerateHardLinksFile(hFile: THandle; out Links:
TArray<TFileHardlinkLinkInfo>) : TNtxStatus;
// Get full name of a hardlink target
function NtxExpandHardlinkTarget(hOriginalFile: THandle;
const Hardlink: TFileHardlinkLinkInfo; out FullName: String): TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntstatus, Ntapi.ntrtl, Ntapi.ntpebteb;
{ Paths }
function RtlxDosPathToNtPath(DosPath: String; out NtPath: String): TNtxStatus;
var
NtPathStr: UNICODE_STRING;
begin
Result.Location := 'RtlDosPathNameToNtPathName_U_WithStatus';
Result.Status := RtlDosPathNameToNtPathName_U_WithStatus(PWideChar(DosPath),
NtPathStr, nil, nil);
if Result.IsSuccess then
begin
NtPath := NtPathStr.ToString;
RtlFreeUnicodeString(NtPathStr);
end;
end;
function RtlxDosPathToNtPathVar(var Path: String): TNtxStatus;
var
NtPath: String;
begin
Result := RtlxDosPathToNtPath(Path, NtPath);
if Result.IsSuccess then
Path := NtPath;
end;
function RtlxGetCurrentPath(out CurrentPath: String): TNtxStatus;
var
Buffer: PWideChar;
BufferSize: Cardinal;
begin
BufferSize := RtlGetLongestNtPathLength;
Buffer := AllocMem(BufferSize);
try
Result.Location := 'RtlGetCurrentDirectory_U';
Result.Status := RtlGetCurrentDirectory_U(BufferSize, Buffer);
if Result.IsSuccess then
CurrentPath := String(Buffer);
finally
FreeMem(Buffer);
end;
end;
function RtlxGetCurrentPathPeb: String;
begin
Result := RtlGetCurrentPeb.ProcessParameters.CurrentDirectory.DosPath.ToString;
end;
function RtlxSetCurrentPath(CurrentPath: String): TNtxStatus;
var
PathStr: UNICODE_STRING;
begin
PathStr.FromString(CurrentPath);
Result.Location := 'RtlSetCurrentDirectory_U';
Result.Status := RtlSetCurrentDirectory_U(PathStr);
end;
{ Open & Create }
function NtxCreateFile(out hxFile: IHandle; DesiredAccess: THandle;
FileName: String; Root: THandle; CreateDisposition: Cardinal;
ShareAccess: Cardinal; CreateOptions: Cardinal; FileAttributes: Cardinal;
HandleAttributes: Cardinal; ActionTaken: PCardinal): TNtxStatus;
var
hFile: THandle;
ObjAttr: TObjectAttributes;
ObjName: UNICODE_STRING;
IoStatusBlock: TIoStatusBlock;
begin
ObjName.FromString(FileName);
InitializeObjectAttributes(ObjAttr, @ObjName, HandleAttributes, Root);
Result.Location := 'NtCreateFile';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @FileAccessType;
Result.Status := NtCreateFile(hFile, DesiredAccess, ObjAttr, IoStatusBlock,
nil, FileAttributes, ShareAccess, CreateDisposition, CreateOptions, nil, 0);
if Result.IsSuccess then
hxFile := TAutoHandle.Capture(hFile);
if Result.IsSuccess and Assigned(ActionTaken) then
ActionTaken^ := Cardinal(IoStatusBlock.Information);
end;
function NtxOpenFile(out hxFile: IHandle; DesiredAccess: TAccessMask;
FileName: String; Root: THandle; ShareAccess: THandle; OpenOptions: Cardinal;
HandleAttributes: Cardinal): TNtxStatus;
var
hFile: THandle;
ObjName: UNICODE_STRING;
ObjAttr: TObjectAttributes;
IoStatusBlock: TIoStatusBlock;
begin
ObjName.FromString(FileName);
InitializeObjectAttributes(ObjAttr, @ObjName, HandleAttributes, Root);
Result.Location := 'NtOpenFile';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @FileAccessType;
Result.Status := NtOpenFile(hFile, DesiredAccess, ObjAttr, IoStatusBlock,
ShareAccess, OpenOptions);
if Result.IsSuccess then
hxFile := TAutoHandle.Capture(hFile);
end;
function NtxOpenFileById(out hxFile: IHandle; DesiredAccess: TAccessMask;
FileId: Int64; Root: THandle; ShareAccess: THandle; HandleAttributes:
Cardinal): TNtxStatus;
var
hFile: THandle;
ObjName: UNICODE_STRING;
ObjAttr: TObjectAttributes;
IoStatusBlock: TIoStatusBlock;
begin
ObjName.Length := SizeOf(FileId);
ObjName.MaximumLength := SizeOf(FileId);
ObjName.Buffer := PWideChar(@FileId); // Pass binary value
InitializeObjectAttributes(ObjAttr, @ObjName, HandleAttributes, Root);
Result.Location := 'NtOpenFile';
Result.LastCall.CallType := lcOpenCall;
Result.LastCall.AccessMask := DesiredAccess;
Result.LastCall.AccessMaskType := @FileAccessType;
Result.Status := NtOpenFile(hFile, DesiredAccess, ObjAttr, IoStatusBlock,
ShareAccess, FILE_OPEN_BY_FILE_ID or FILE_SYNCHRONOUS_IO_NONALERT);
if Result.IsSuccess then
hxFile := TAutoHandle.Capture(hFile);
end;
{ Operations }
function NtxpSetRenameInfoFile(hFile: THandle; TargetName: String;
ReplaceIfExists: Boolean; RootDirectory: THandle;
InfoClass: TFileInformationClass): TNtxStatus;
var
Buffer: PFileRenameInformation; // aka PFileLinkInformation
BufferSize: Cardinal;
begin
// Prepare a variable-length buffer for rename or hardlink operation
BufferSize := SizeOf(TFileRenameInformation) +
Length(TargetName) * SizeOf(WideChar);
Buffer := AllocMem(BufferSize);
Buffer.ReplaceIfExists := ReplaceIfExists;
Buffer.RootDirectory := RootDirectory;
Buffer.FileNameLength := Length(TargetName) * SizeOf(WideChar);
Move(PWideChar(TargetName)^, Buffer.FileName, Buffer.FileNameLength);
Result := NtxSetFile(hFile, InfoClass, Buffer, BufferSize);
FreeMem(Buffer);
end;
function NtxRenameFile(hFile: THandle; NewName: String;
ReplaceIfExists: Boolean; RootDirectory: THandle): TNtxStatus;
begin
// Note: if you get sharing violation when using RootDirectory open it with
// FILE_TRAVERSE | FILE_READ_ATTRIBUTES access.
Result := NtxpSetRenameInfoFile(hFile, NewName, ReplaceIfExists,
RootDirectory, FileRenameInformation);
end;
function NtxHardlinkFile(hFile: THandle; NewName: String;
ReplaceIfExists: Boolean; RootDirectory: THandle): TNtxStatus;
begin
Result := NtxpSetRenameInfoFile(hFile, NewName, ReplaceIfExists,
RootDirectory, FileLinkInformation);
end;
{ Information }
procedure NtxpFormatFileQuery(var Status: TNtxStatus;
InfoClass: TFileInformationClass);
begin
Status.Location := 'NtQueryInformationFile';
Status.LastCall.CallType := lcQuerySetCall;
Status.LastCall.InfoClass := Cardinal(InfoClass);
Status.LastCall.InfoClassType := TypeInfo(TFileInformationClass);
end;
function NtxQueryFile(hFile: THandle; InfoClass: TFileInformationClass;
out xMemory: IMemory; InitialBufferSize: Cardinal): TNtxStatus;
var
IoStatusBlock: TIoStatusBlock;
Buffer: Pointer;
BufferSize: Cardinal;
begin
NtxpFormatFileQuery(Result, InfoClass);
BufferSize := InitialBufferSize;
repeat
Buffer := AllocMem(BufferSize);
IoStatusBlock.Information := 0;
Result.Status := NtQueryInformationFile(hFile, IoStatusBlock, Buffer,
BufferSize, InfoClass);
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, BufferSize shl 1 + 256);
if Result.IsSuccess then
xMemory := TAutoMemory.Capture(Buffer, BufferSize);
end;
function NtxSetFile(hFile: THandle; InfoClass: TFileInformationClass;
Buffer: Pointer; BufferSize: Cardinal): TNtxStatus;
var
IoStatusBlock: TIoStatusBlock;
begin
Result.Location := 'NtSetInformationFile';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TFileInformationClass);
Result.Status := NtSetInformationFile(hFile, IoStatusBlock, Buffer,
BufferSize, InfoClass);
end;
class function NtxFile.Query<T>(hFile: THandle;
InfoClass: TFileInformationClass; out Buffer: T): TNtxStatus;
var
IoStatusBlock: TIoStatusBlock;
begin
Result.Location := 'NtQueryInformationFile';
Result.LastCall.CallType := lcQuerySetCall;
Result.LastCall.InfoClass := Cardinal(InfoClass);
Result.LastCall.InfoClassType := TypeInfo(TFileInformationClass);
Result.Status := NtQueryInformationFile(hFile, IoStatusBlock, @Buffer,
SizeOf(Buffer), InfoClass);
end;
class function NtxFile.SetInfo<T>(hFile: THandle;
InfoClass: TFileInformationClass; const Buffer: T): TNtxStatus;
begin
Result := NtxSetFile(hFile, InfoClass, @Buffer, SizeOf(Buffer));
end;
function NtxQueryNameFile(hFile: THandle; out Name: String): TNtxStatus;
var
Buffer: PFileNameInformation;
BufferSize, Required: Cardinal;
IoStatusBlock: TIoStatusBlock;
begin
NtxpFormatFileQuery(Result, FileNameInformation);
BufferSize := SizeOf(TFileNameInformation);
repeat
Buffer := AllocMem(BufferSize);
Result.Status := NtQueryInformationFile(hFile, IoStatusBlock, Buffer,
BufferSize, FileNameInformation);
Required := SizeOf(Cardinal) + Buffer.FileNameLength;
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
if not Result.IsSuccess then
Exit;
SetString(Name, Buffer.FileName, Buffer.FileNameLength div 2);
FreeMem(Buffer);
end;
function NtxEnumerateStreamsFile(hFile: THandle; out Streams:
TArray<TFileStreamInfo>) : TNtxStatus;
var
Buffer, pStream: PFileStreamInformation;
BufferSize, Required: Cardinal;
IoStatusBlock: TIoStatusBlock;
begin
NtxpFormatFileQuery(Result, FileStreamInformation);
BufferSize := SizeOf(TFileStreamInformation);
repeat
Buffer := AllocMem(BufferSize);
Result.Status := NtQueryInformationFile(hFile, IoStatusBlock, Buffer,
BufferSize, FileStreamInformation);
Required := BufferSize shl 1 + 64;
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
if not Result.IsSuccess then
Exit;
SetLength(Streams, 0);
pStream := Buffer;
repeat
SetLength(Streams, Length(Streams) + 1);
Streams[High(Streams)].StreamSize := pStream.StreamSize;
Streams[High(Streams)].StreamAllocationSize := pStream.StreamAllocationSize;
SetString(Streams[High(Streams)].StreamName, pStream.StreamName,
pStream.StreamNameLength div 2);
if pStream.NextEntryOffset <> 0 then
pStream := Pointer(NativeUInt(pStream) + pStream.NextEntryOffset)
else
Break;
until False;
FreeMem(Buffer);
end;
function NtxEnumerateHardLinksFile(hFile: THandle; out Links:
TArray<TFileHardlinkLinkInfo>) : TNtxStatus;
var
Buffer: PFileLinksInformation;
pLink: PFileLinkEntryInformation;
BufferSize, Required: Cardinal;
IoStatusBlock: TIoStatusBlock;
i: Integer;
begin
NtxpFormatFileQuery(Result, FileHardLinkInformation);
BufferSize := SizeOf(TFileLinksInformation);
repeat
Buffer := AllocMem(BufferSize);
Result.Status := NtQueryInformationFile(hFile, IoStatusBlock, Buffer,
BufferSize, FileHardLinkInformation);
Required := Buffer.BytesNeeded;
if not Result.IsSuccess then
begin
FreeMem(Buffer);
Buffer := nil;
end;
until not NtxExpandBuffer(Result, BufferSize, Required);
if not Result.IsSuccess then
Exit;
SetLength(Links, Buffer.EntriesReturned);
pLink := @Buffer.Entry;
i := 0;
repeat
if i > High(Links) then
Break;
// Note: we have only the filename and the ID of the parent directory
Links[i].ParentFileId := pLink.ParentFileId;
SetString(Links[i].FileName, pLink.FileName, pLink.FileNameLength);
if pLink.NextEntryOffset <> 0 then
pLink := Pointer(NativeUInt(pLink) + pLink.NextEntryOffset)
else
Break;
Inc(i);
until False;
FreeMem(Buffer);
end;
function NtxExpandHardlinkTarget(hOriginalFile: THandle;
const Hardlink: TFileHardlinkLinkInfo; out FullName: String): TNtxStatus;
var
hxFile: IHandle;
begin
Result := NtxOpenFileById(hxFile, SYNCHRONIZE or FILE_READ_ATTRIBUTES,
Hardlink.ParentFileId, hOriginalFile);
if Result.IsSuccess then
begin
Result := NtxQueryNameFile(hxFile.Handle, FullName);
if Result.IsSuccess then
FullName := FullName + '\' + Hardlink.FileName;
end;
end;
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный класс для экспорта котировок. Отличается от MT4-формата
тем, что хранит информацию более компактно
History:
-----------------------------------------------------------------------------}
unit FC.StockData.Export.BinExporter;
{$I Compiler.inc}
interface
uses Windows,Forms,BaseUtils,SysUtils, Classes, Controls, Serialization,
StockChart.Definitions,FC.Definitions, StockChart.Obj,
FC.StockData.Bin.StockDataSource;
type
TStockDataFileExporterBin = class(TStockInterfacedObjectVirtual,IStockDataFileExporter)
private
procedure Run1(const aDS: IStockDataSource; aStream: TStream);
procedure Run2(const aDS: IStockDataSource; aStream: TStream);
public
function Filter: string;
function DefaultExt: string;
function Description: string;
procedure Run(const aDS: IStockDataSource; aStream: TStream);
end;
const
CurrentVersion: TStockDataSource_BinVersion=dsbv2;
implementation
uses Math, DateUtils, SystemService,
Application.Definitions,
FC.Factory,
FC.DataUtils,
FC.StockData.DataSourceToInputDataCollectionMediator;
{ TStockDataFileExporterBin }
function TStockDataFileExporterBin.DefaultExt: string;
begin
result:='.sbf';
end;
function TStockDataFileExporterBin.Description: string;
begin
result:='Binary files (*.sbf)';
end;
function TStockDataFileExporterBin.Filter: string;
begin
result:='*.sbf';
end;
procedure TStockDataFileExporterBin.Run(const aDS: IStockDataSource; aStream: TStream);
begin
TWaitCursor.SetUntilIdle;
Assert(sizeof(TBinHeader)=sizeof(TBinHeader2));
case CurrentVersion of
dsbv1:Run1(aDS,aStream);
dsbv2:Run2(aDS,aStream);
else
raise EAlgoError.Create;
end;
end;
procedure TStockDataFileExporterBin.Run1(const aDS: IStockDataSource; aStream: TStream);
var
i: integer;
s: string;
aDate: integer;
aV: TStockRealNumber;
aVolume: integer;
aMediator: TStockDataSourceToInputDataCollectionMediator;
aMin,aMax: TStockRealNumber;
aIndex16: word;
aIndex32: cardinal;
aSign : word;
aHeader: TBinHeader;
aWriter: TWriter;
begin
//Считаем Min/Max
aMediator:=TStockDataSourceToInputDataCollectionMediator.Create(aDS,nil);
aMediator.FindMinMaxValues(0,aDS.RecordCount-1,aMin,aMax);
aMediator.Free;
//Дальше заголовок
ZeroMemory(@aHeader,sizeof(aHeader));
aHeader.version:=1;
s:='(C) '+Workspace.CompanyName;
StrLCopy(@aHeader.copyright[0],pchar(s),sizeof(aHeader.copyright));
StrLCopy(@aHeader.symbol[0],pchar(aDS.StockSymbol.Name),sizeof(aHeader.symbol));
aHeader.digits:=aDS.GetPricePrecision;
aHeader.minval:=aMin;
aHeader.maxval:=aMax;
if aDS.RecordCount>0 then
begin
aHeader.firsttime:=DateTimeToUnix(aDS.GetDataDateTime(0));
aHeader.lasttime:=DateTimeToUnix(aDS.GetDataDateTime(aDS.RecordCount-1));
end;
aStream.WriteBuffer(aHeader,sizeof(aHeader));
if aDS.PriceToPoint(aMax-aMin)>$FFFF then
raise EStockError.Create('Too large prices diapason to store');
aSign:=$FFFF;
//данные
aWriter:=TWriter.Create(aStream,1024*1024); //использование врайтера дает оптимизацию за счет использования буфера
try
for I := 0 to aDS.RecordCount - 1 do
begin
aDate:=DateTimeToUnix(aDS.GetDataDateTime(i));
aWriter.Write(aDate,sizeof(aDate));
//Open
aV:=aDS.GetDataOpen(i);
aIndex32:=aDS.PriceToPoint(aV-aMin);
if aIndex32<$FFFF then
begin
aIndex16:=aIndex32;
aWriter.Write(aIndex16,sizeof(aIndex16));
end
else begin
aWriter.Write(aSign,2);
aWriter.Write(aIndex32,sizeof(aIndex32));
end;
//High
aV:=aDS.GetDataHigh(i);
aIndex32:=aDS.PriceToPoint(aV-aMin);
if aIndex32<$FFFF then
begin
aIndex16:=aIndex32;
aWriter.Write(aIndex16,sizeof(aIndex16));
end
else begin
aWriter.Write(aSign,2);
aWriter.Write(aIndex32,sizeof(aIndex32));
end;
//Low
aV:=aDS.GetDataLow(i);
aIndex32:=aDS.PriceToPoint(aV-aMin);
if aIndex32<$FFFF then
begin
aIndex16:=aIndex32;
aWriter.Write(aIndex16,sizeof(aIndex16));
end
else begin
aWriter.Write(aSign,2);
aWriter.Write(aIndex32,sizeof(aIndex32));
end;
//Close
aV:=aDS.GetDataClose(i);
aIndex32:=aDS.PriceToPoint(aV-aMin);
if aIndex32<$FFFF then
begin
aIndex16:=aIndex32;
aWriter.Write(aIndex16,sizeof(aIndex16));
end
else begin
aWriter.Write(aSign,2);
aWriter.Write(aIndex32,sizeof(aIndex32));
end;
//Volume
aVolume:=aDS.GetDataVolume(i);
aWriter.Write(aVolume,sizeof(aVolume));
end;
aWriter.FlushBuffer;
finally
aWriter.Free;
end;
end;
function GetValueType(const Value: LongInt): ShortInt; inline;
begin
if (Value >= Low(ShortInt)) and (Value <= High(ShortInt)) then
result:=1
else if (Value >= Low(SmallInt)) and (Value <= High(SmallInt)) then
result:=2
else
result:=3;
end;
procedure TStockDataFileExporterBin.Run2(const aDS: IStockDataSource; aStream: TStream);
var
i: integer;
s: string;
aCurDate,aNewDate,aDDate: integer;
aCurVolume,aNewVolume,aDVolume: integer;
aCurOpen,aCurHigh,aCurLow,aCurClose: Double;
aNewOpen,aNewHigh,aNewLow,aNewClose: Double;
aDOpen,aDHigh,aDLow,aDClose: LongInt;
aDateSize,aOCSize,aHLSize, aVolSize,aAllSize: byte;
aHeader: TBinHeader2;
aWriter: TWriter;
const
aBytes: array [0..3] of integer = (0,1,2,4);
begin
//Дальше заголовок
ZeroMemory(@aHeader,sizeof(aHeader));
aHeader.version:=2;
s:='(C) '+Workspace.CompanyName;
StrLCopy(@aHeader.copyright[0],pchar(s),sizeof(aHeader.copyright));
StrLCopy(@aHeader.symbol[0],pchar(aDS.StockSymbol.Name),sizeof(aHeader.symbol));
aHeader.digits:=aDS.GetPricePrecision;
if aDS.RecordCount>0 then
begin
aCurDate:=DateTimeToUnix(aDS.GetDataDateTime(0));
aCurOpen:=aDS.GetDataOpen(0);
aCurHigh:=aDS.GetDataHigh(0);
aCurLow:=aDS.GetDataLow(0);
aCurClose:=aDS.GetDataClose(0);
aCurVolume:=aDS.GetDataVolume(0);
aHeader.firsttime:=aCurDate;
aHeader.lasttime:=DateTimeToUnix(aDS.GetDataDateTime(aDS.RecordCount-1));
aHeader.firstopen:=aCurOpen;
aHeader.firsthigh:=aCurHigh;
aHeader.firstlow:=aCurLow;
aHeader.firstclose:=aCurClose;
aHeader.firstvolume:=aCurVolume;
end
else begin
//Набор пустой, записываем заголовок и уходим
aStream.WriteBuffer(aHeader,sizeof(aHeader));
exit;
end;
aStream.WriteBuffer(aHeader,sizeof(aHeader));
//Спец. наворот, чтобы сразу загрузить все
aDS.FetchAll;
//данные
aWriter:=TWriter.Create(aStream,1024*1024); //использование врайтера дает оптимизацию за счет использования буфера
try
for I := 0 to aDS.RecordCount - 1 do
begin
//Смысл алгоритма: записываем разницу между предыдущим и текущим
//значением и храним ее в пунктах. Как правило, дельта полчается маленькая
//и помещается в 1 байт
aNewDate:=DateTimeToUnix(aDS.GetDataDateTime(i));
aNewOpen:=aDS.GetDataOpen(i);
aNewHigh:=aDS.GetDataHigh(i);
aNewLow:=aDS.GetDataLow(i);
aNewClose:=aDS.GetDataClose(i);
aNewVolume:=aDS.GetDataVolume(i);
aDDate:=aNewDate-aCurDate;
aDOpen:=aDS.PriceToPoint(aNewOpen-aCurOpen);
aDHigh:=aDS.PriceToPoint(aNewHigh-aCurHigh);
aDLow :=aDS.PriceToPoint(aNewLow-aCurLow);
aDClose:=aDS.PriceToPoint(aNewClose-aCurClose);
aDVolume:=aNewVolume-aCurVolume;
//Выбираем максимальный размер для всех значений
aDateSize:=GetValueType(aDDate);
//Выбираем максимальный размер для значений Open-Close
aOCSize:=max(GetValueType(aDOpen),GetValueType(aDClose));
//Выбираем максимальный размер для значений High-Low
aHLSize:=max(GetValueType(aDHigh),GetValueType(aDLow));
//Выбираем максимальный размер для Volume
aVolSize:=GetValueType(aDVolume);
Assert(aDateSize in [1..3]);
Assert(aOCSize in [1..3]);
Assert(aHLSize in [1..3]);
Assert(aVolSize in [1..3]);
//записываем размеры
aAllSize:=(aDateSize shl 6) or (aOCSize shl 4) or (aHLSize shl 2) or (aVolSize);
aWriter.Write(aAllSize, sizeof(aAllSize));
//записываем дату
aWriter.Write(aDDate, aBytes[aDateSize]);
//Записываем данные
aWriter.Write(aDOpen, aBytes[aOCSize]);
aWriter.Write(aDHigh, aBytes[aHLSize]);
aWriter.Write(aDLow, aBytes[aHLSize]);
aWriter.Write(aDClose,aBytes[aOCSize]);
//Записываем volume
aWriter.Write(aDVolume,aBytes[aVolSize]);
aCurDate:=aNewDate;
aCurOpen:=aNewOpen;
aCurHigh:=aNewHigh;
aCurLow:=aNewLow;
aCurClose:=aNewClose;
aCurVolume:=aNewVolume;
end;
aWriter.FlushBuffer;
finally
aWriter.Free;
end;
end;
initialization
Factory.RegisterCreator(TObjectCreator_Coexistent.Create(TStockDataFileExporterBin));
end.
|
unit MediaProcessing.Convertor.AvcAnyVideo.RGB;
interface
uses SysUtils,Windows,Classes,MediaProcessing.Definitions,MediaProcessing.Global,
MediaProcessing.Common.Processor.FPS, MediaProcessing.Common.Processor.FPS.ImageSize, Avc,
MediaProcessing.Convertor.AvcAnyVideo.RGB.SettingsDialog;
type
TMediaProcessor_Convertor_AvcAnyVideo_Rgb=class (TMediaProcessor_FpsImageSize<TfmMediaProcessingSettingsAvcAny_Rgb>,IMediaProcessor_Convertor_AvcAnyVideo_Rgb)
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses Controls,uBaseClasses;
{ TMediaProcessor_Convertor_AvcAnyVideo_Rgb }
constructor TMediaProcessor_Convertor_AvcAnyVideo_Rgb.Create;
begin
inherited;
FImageSizeScale:=2;
FImageSizeMode:=cismNone;
FImageSizeWidth:=640;
FImageSizeHeight:=480;
end;
destructor TMediaProcessor_Convertor_AvcAnyVideo_Rgb.Destroy;
begin
inherited;
end;
class function TMediaProcessor_Convertor_AvcAnyVideo_Rgb.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Convertor_AvcAnyVideo_Rgb;
result.Name:='Конвертор Any Video->RGB';
result.Description:='Преобразует видеокадры любого видеоформата в формат RGB';
result.InputStreamTypes:=Avc.GetKnownVideoFourccArray;
result.OutputStreamType:=stRGB;
result.ConsumingLevel:=9;
end;
procedure TMediaProcessor_Convertor_AvcAnyVideo_Rgb.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
end;
procedure TMediaProcessor_Convertor_AvcAnyVideo_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_AvcAnyVideo_Rgb);
end.
|
unit uSoundTypes;
interface
type
TVolumeLevel = 0..127;
TSampleRate=(sr8KHz,sr11_025KHz,sr22_05KHz,sr44_1KHz);
TSoundChannel=(chMono,chStereo);
TBitsPerSample=(bps8Bit,bps16Bit,bps32Bit);
function GetSampleRate(SampleRate:TSampleRate):integer;
function GetEnumSampleRate(SampleRate:integer):TSampleRate;
function GetNumChannels(ch:TSoundChannel):word;
function GetSoundChannels(nChannel:word):TSoundChannel;
function GetBitsPerSample(bits:TBitsPerSample):word;
function GetEnumBitsPerSample(bits:word):TBitsPerSample;
implementation
const SampleRates:array[sr8KHz..sr44_1KHz] of integer=
(8000,11025,22050,44100);
Channels:array[chMono..chStereo] of word=
(1,2);
BitsPerSample:array[bps8Bit..bps32Bit] of word=
(8,16,32);
function GetSampleRate(SampleRate:TSampleRate):integer;
begin
result:=SampleRates[SampleRate];
end;
function GetEnumSampleRate(SampleRate:integer):TSampleRate;
begin
result:=sr8KHz;
case sampleRate of
8000:result:=sr8KHz;
11025:result:=sr11_025KHz;
22050:result:=sr22_05KHz;
44100:result:=sr44_1KHz;
end;
end;
function GetNumChannels(ch:TSoundChannel):word;
begin
result:=Channels[ch];
end;
function GetSoundChannels(nChannel:word):TSoundChannel;
begin
result:=chMono;
case nChannel of
1:result:=chMono;
2:result:=chStereo;
end;
end;
function GetBitsPerSample(bits:TBitsPerSample):word;
begin
result:=BitsPerSample[bits];
end;
function GetEnumBitsPerSample(bits:word):TBitsPerSample;
begin
result:=bps8Bit;
case bits of
8:result:=bps8Bit;
16:result:=bps16Bit;
32:result:=bps32Bit;
end;
end;
end.
|
{
Strongly Connected Components
DFS Method O(N2)
Input:
G: Directed simple graph
N: Number of vertices
Output:
CompNum: Number of components.
Comp[I]: Component number of vertex I.
Reference:
CLR, p489
By Ali
}
program
StronglyConnectedComponents;
const
MaxN = 100 + 2;
var
N: Integer;
G: array[1 .. MaxN, 1 .. MaxN] of Integer;
CompNum: Integer;
Comp: array[1 .. MaxN] of Integer;
var
Fin: array[1 .. MaxN] of Integer;
DfsN: Integer;
procedure Dfs(V: Integer);
var
I: Integer;
begin
Comp[V] := 1;
for I := 1 to N do
if (Comp[I] = 0) and (G[V, I] <> 0) then
Dfs(I);
Fin[DfsN] := V;
Dec(DfsN);
end;
procedure Dfs2(V: Integer);
var
I: Integer;
begin
Comp[V] := CompNum;
for I := 1 to N do
if (Comp[I] = 0) and (G[I, V] <> 0) then
Dfs2(I);
end;
procedure StronglyConnected;
var
I: Integer;
begin
FillChar(Comp, SizeOf(Comp), 0);
DfsN := N;
for I := 1 to N do
if Comp[I] = 0 then
Dfs(I);
FillChar(Comp, SizeOf(Comp), 0);
CompNum := 0;
for I := 1 to N do
if Comp[Fin[I]] = 0 then
begin
Inc(CompNum);
Dfs2(Fin[I]);
end;
end;
begin
StronglyConnected;
end.
|
unit UserName;
interface
uses Windows, SysUtils;
function GetCurrentUserName: string;
implementation
function MyWideCharToString(Source: PWideChar): string;
var
p: PAnsiChar;
Len: Integer;
begin
if Source = nil then begin
Result := '';
Exit;
end;
Len := WideCharToMultiByte(CP_ACP, 0, Source, -1, nil, 0, nil, nil);
p := PAnsiChar(LocalAlloc(LMEM_FIXED, Len));
try
Len := WideCharToMultiByte(CP_ACP, 0, Source, -1, p, Len, nil, nil);
if Len = 0 then
raise Exception.Create(Format('Cannot convert WideChar to MultiByte. Error #%u', [GetLastError]))
else
Result := p;
finally
LocalFree(HLOCAL(p));
end;
end;
function GetCurrentUserName: string;
var
Size: DWORD;
Buffer: PWideChar;
WinResult: Boolean;
LastError: LongWord;
begin
Size := 0;
Buffer := nil;
WinResult := Windows.GetUserNameW(Buffer, Size);
LastError := GetLastError;
if not WinResult and (LastError <> ERROR_INSUFFICIENT_BUFFER) then
raise Exception.Create(Format('Cannot retrieve local user name. Error #%u', [GetLastError]));
GetMem(Buffer, 2*Size+2);
try
WinResult := Windows.GetUserNameW(Buffer, Size);
if not WinResult then
raise Exception.Create(Format('Cannot retrieve local user name. Error #%u', [GetLastError]));
Result := MyWideCharToString(Buffer);
finally
FreeMem(Buffer);
end;
end;
end.
|
unit UFrmCampeonatos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids,
Data.DB, Datasnap.DBClient, System.Generics.Collections,Ucampeonato;
type
TfrmCadastroCampeonatos = class(TForm)
edtNome: TEdit;
edtAno: TEdit;
DBGrid1: TDBGrid;
Nome: TLabel;
Ano: TLabel;
btnSalvar: TButton;
btnExcluir: TButton;
DS: TDataSource;
CDS: TClientDataSet;
CDSID: TIntegerField;
CDSNome: TStringField;
CDSAno: TStringField;
btnInserir: TButton;
btnCancelar: TButton;
procedure btnSalvarClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnInserirClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
variavelSequencial : Integer;
procedure ModoBotaoInsercao();
procedure ModoBotaoNaoInsercao();
{ Private declarations }
public
listaCampeonatos : TObjectList<TCampeonatos>;
end;
var
frmCadastroCampeonatos: TfrmCadastroCampeonatos;
implementation
{$R *.dfm}
procedure TfrmCadastroCampeonatos.btnInserirClick(Sender: TObject);
begin
ModoBotaoInsercao;
end;
procedure TfrmCadastroCampeonatos.btnSalvarClick(Sender: TObject);
var
campeonato : TCampeonatos;
begin
if(edtNome.Text = '')then
begin
MessageDlg('Nome não informado. Verifique.',mtInformation,[mbOK],0);
end
else
begin
variavelSequencial:= variavelSequencial+1;
campeonato:= TCampeonatos.Create;
campeonato.id:= variavelSequencial;
campeonato.nome:= edtNome.Text;
campeonato.ano:= StrToInt(edtAno.Text);
CDS.Append;
CDS.FieldByName('id').AsInteger := campeonato.id;
cds.FieldByName('nome').AsString := campeonato.nome;
cds.FieldByName('ano').AsInteger := campeonato.ano;
CDS.Post;
ModoBotaoNaoInsercao;
btnInserir.SetFocus;
CDS.First;
listaCampeonatos.Add(campeonato);
end;
end;
procedure TfrmCadastroCampeonatos.btnCancelarClick(Sender: TObject);
begin
ModoBotaoNaoInsercao;
end;
procedure TfrmCadastroCampeonatos.btnExcluirClick(Sender: TObject);
var
i : Integer;
begin
if CDSID.Value > 0 then
begin
for i := 0 to listaCampeonatos.Count-1 do
begin
if (listaCampeonatos.Items[i].id)= CDSID.Value then
begin
listaCampeonatos.Delete(i);
Break;
end;
end;
CDS.Delete;
ModoBotaoNaoInsercao;
end
else
MessageDlg('Selecione um registro para a realização da exclusão', mtInformation,[mbOK],0);
end;
procedure TfrmCadastroCampeonatos.FormCreate(Sender: TObject);
begin
CDS.CreateDataSet;
listaCampeonatos:=TObjectList<TCampeonatos>.Create;
ModoBotaoNaoInsercao;
end;
procedure TfrmCadastroCampeonatos.FormDestroy(Sender: TObject);
begin
FreeAndNil(listaCampeonatos);
end;
procedure TfrmCadastroCampeonatos.FormShow(Sender: TObject);
var
i :Integer;
lcampeonato : TCampeonatos;
begin
CDS.Close;
CDS.CreateDataSet;
if listaCampeonatos.Count=0 then
begin
for i := 1 to 6 do
begin
variavelSequencial:= variavelSequencial+1;
CDS.Append;
CDS.FieldByName('ID').AsInteger:= variavelSequencial;
CDS.FieldByName('Nome').AsString:='Brasileiro';
CDS.FieldByName('ano').AsInteger:=StrToInt('2009')+i;
CDS.Post;
lcampeonato:= TCampeonatos.Create;
lcampeonato.id:= CDSID.AsInteger;
lcampeonato.nome:= CDSNome.AsString;
lcampeonato.ano:= CDS.FieldByName('ano').AsInteger;
listaCampeonatos.Add(lcampeonato);
end;
end
else
begin
for i := 0 to listaCampeonatos.Count-1 do
begin
CDS.Append;
CDS.FieldByName('Id').AsInteger:= listaCampeonatos.Items[i].id;
CDS.FieldByName('Nome').AsString:= listaCampeonatos.Items[i].nome;
CDS.FieldByName('ano').AsInteger:= listaCampeonatos.Items[i].ano;
CDS.Post;
end;
end;
end;
procedure TfrmCadastroCampeonatos.ModoBotaoInsercao;
begin
btnInserir.Enabled:=false;
edtNome.Enabled:=true;
edtAno.Enabled:=true;
edtNome.Text:='';
edtAno.Text:='';
edtNome.SetFocus;
btnCancelar.Enabled:=true;
btnSalvar.Enabled:=True;
btnExcluir.Enabled:=false;
end;
procedure TfrmCadastroCampeonatos.ModoBotaoNaoInsercao;
begin
btnInserir.Enabled:=true;
edtNome.Text:='';
edtAno.Text:='';
edtNome.Enabled:=false;
edtAno.Enabled:=false;
btnCancelar.Enabled:=false;
btnSalvar.Enabled:=false;
btnExcluir.Enabled:=true;
end;
end.
|
unit MainFrm;
interface
uses
System.SysUtils, System.Types, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FGX.ColorsPanel, FMX.Edit, FMX.Objects,
FMX.ListBox, System.UITypes, FMX.Controls.Presentation, FMX.EditBox, FMX.NumberBox, FMX.Colors, FMX.Layouts,
FMX.MultiView;
type
TFormMain = class(TForm)
fgColorsPanel: TfgColorsPanel;
nbCellSizeWidth: TNumberBox;
nbCellSizeHeight: TNumberBox;
nbBorderRadius: TNumberBox;
cbPresetKind: TComboBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ColorBox: TColorBox;
lSelectedColor: TLabel;
cbStrokeColor: TComboColorBox;
MultiView1: TMultiView;
ListBox1: TListBox;
ListBoxItem4: TListBoxItem;
ListBoxItem5: TListBoxItem;
ListBoxItem6: TListBoxItem;
ListBoxItem7: TListBoxItem;
ListBoxItem8: TListBoxItem;
ListBoxItem9: TListBoxItem;
ListBoxItem10: TListBoxItem;
ListBoxGroupHeader1: TListBoxGroupHeader;
ListBoxGroupHeader2: TListBoxGroupHeader;
ListBoxGroupHeader3: TListBoxGroupHeader;
swUserPainting: TSwitch;
swUsersColors: TSwitch;
procedure nbCellSizeWidthChangeTracking(Sender: TObject);
procedure nbBorderRadiusChangeTracking(Sender: TObject);
procedure cbPresetKindChange(Sender: TObject);
procedure fgColorsPanelGetColor(Sender: TObject; const Column, Row: Integer; var Color: TAlphaColor);
procedure fgColorsPanelPaintCell(Sender: TObject; Canvas: TCanvas; const Column, Row: Integer; const Frame: TRectF;
const AColor: TAlphaColor; Corners: TCorners; var Done: Boolean);
procedure FormShow(Sender: TObject);
procedure fgColorsPanelColorSelected(Sender: TObject; const AColor: TAlphaColor);
procedure cbStrokeColorChange(Sender: TObject);
procedure swUserPaintingSwitch(Sender: TObject);
procedure MultiView1PresenterChanging(Sender: TObject; var PresenterClass: TMultiViewPresentationClass);
procedure swUsersColorsSwitch(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
uses
System.Math, FMX.MultiView.Presentations;
const
USERS_COLORS : array [1..10] of TAlphaColor = (TAlphaColorRec.Aliceblue, TAlphaColorRec.Darkviolet,
TAlphaColorRec.Antiquewhite, TAlphaColorRec.Beige, TAlphaColorRec.Chocolate, TAlphaColorRec.Lightsteelblue,
TAlphaColorRec.Ivory, TAlphaColorRec.Khaki, TAlphaColorRec.Navajowhite, TAlphaColorRec.Violet);
{$R *.fmx}
procedure TFormMain.cbPresetKindChange(Sender: TObject);
begin
fgColorsPanel.PresetKind := TfgColorsPresetKind(cbPresetKind.ItemIndex);
end;
procedure TFormMain.cbStrokeColorChange(Sender: TObject);
begin
fgColorsPanel.Stroke.Color := cbStrokeColor.Color;
end;
procedure TFormMain.fgColorsPanelColorSelected(Sender: TObject; const AColor: TAlphaColor);
begin
ColorBox.Color := AColor;
lSelectedColor.Text := Format('Selected Color: %s', [IntToHEx(AColor, 8)]);
end;
procedure TFormMain.fgColorsPanelGetColor(Sender: TObject; const Column, Row: Integer; var Color: TAlphaColor);
var
ColorIndex: Integer;
begin
ColorIndex := Column;
if Color = TAlphaColorRec.Null then
Color := TAlphaColorRec.White;
if swUsersColors.IsChecked and InRange(ColorIndex, Low(USERS_COLORS), High(USERS_COLORS)) and (Row > 10) then
Color := USERS_COLORS[ColorIndex];
end;
procedure TFormMain.fgColorsPanelPaintCell(Sender: TObject; Canvas: TCanvas; const Column, Row: Integer;
const Frame: TRectF; const AColor: TAlphaColor; Corners: TCorners; var Done: Boolean);
begin
if swUserPainting.IsChecked and (Row = 10) then
begin
Canvas.Fill.Kind := TBrushKind.Gradient;
Canvas.FillRect(Frame, fgColorsPanel.BorderRadius, fgColorsPanel.BorderRadius, Corners, 1);
end;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
MultiView1.Mode := TMultiViewMode.PlatformBehaviour;
end;
procedure TFormMain.FormShow(Sender: TObject);
begin
nbCellSizeWidth.Value := fgColorsPanel.CellSize.Width;
nbCellSizeHeight.Value := fgColorsPanel.CellSize.Height;
nbBorderRadius.Value := fgColorsPanel.BorderRadius;
cbPresetKind.ItemIndex := Integer(fgColorsPanel.PresetKind);
nbBorderRadius.Max := Min(nbCellSizeWidth.Value / 2, nbCellSizeHeight.Value / 2);
end;
procedure TFormMain.MultiView1PresenterChanging(Sender: TObject; var PresenterClass: TMultiViewPresentationClass);
begin
if PresenterClass = TMultiViewNavigationPanePresentation then
PresenterClass := TMultiViewDockedPanelPresentation;
end;
procedure TFormMain.nbBorderRadiusChangeTracking(Sender: TObject);
begin
fgColorsPanel.BorderRadius := nbBorderRadius.Value;
end;
procedure TFormMain.nbCellSizeWidthChangeTracking(Sender: TObject);
begin
fgColorsPanel.CellSize.Width := nbCellSizeWidth.Value;
fgColorsPanel.CellSize.Height := nbCellSizeHeight.Value;
nbBorderRadius.Max := Min(nbCellSizeWidth.Value / 2, nbCellSizeHeight.Value / 2);
end;
procedure TFormMain.swUserPaintingSwitch(Sender: TObject);
begin
fgColorsPanel.Repaint;
end;
procedure TFormMain.swUsersColorsSwitch(Sender: TObject);
begin
fgColorsPanel.Repaint;
end;
end.
|
unit PizzaStore;
interface
type
TPizza = class
procedure Cook; virtual; abstract;
procedure Deliver;
end;
TPizzaClass = class of TPizza;
TPizzaStore = class
private
class var FPizzas: TArray<TPizzaClass>;
public
class procedure RegisterPizza(Pizza: TPizzaClass);
class function GetPizza(classe: string): TPizza;
end;
implementation
{ TPizzaStore }
class function TPizzaStore.GetPizza(classe: string): TPizza;
var
PizzaClasse: TPizzaClass;
begin
for PizzaClasse in FPizzas do
if PizzaClasse.ClassName = classe then
Exit(PizzaClasse.Create);
end;
class procedure TPizzaStore.RegisterPizza(Pizza: TPizzaClass);
begin
FPizzas := FPizzas + [Pizza];
end;
{ TPizza }
procedure TPizza.Deliver;
begin
Writeln('Delivered');
end;
end.
|
unit IdentityDoc;
interface
uses
System.Variants;
type
TIdentityDoc = class(TObject)
private
FIdType: string;
FIdNo: string;
FExpiry: TDate;
FHasExpiry: boolean;
public
property IdType: string read FIdType write FIdType;
property IdNo: string read FIdNo write FIdNo;
property Expiry: TDate read FExpiry write FExpiry;
property HasExpiry: boolean read FHasExpiry write FHasExpiry;
constructor Create(const idType, idNo: string; const expiry: TDate;
const hasExpiry: boolean); overload;
end;
var
identDoc: TIdentityDoc;
implementation
constructor TIdentityDoc.Create(const idType, idNo: string; const expiry: TDate;
const hasExpiry: boolean);
begin
FIdType := idType;
FIdNo := idNo;
FExpiry := expiry;
FHasExpiry := hasExpiry;
end;
end.
|
unit ULogDetailsController;
interface
uses UFLogRegisterDetails;
type
TLogDetailsController = class
private
FView : TFLogRegisterDetails;
procedure Initialize(TypeLog: Integer; Title, DateTime, Msg: String);
public
class procedure Execute(TypeLog: Integer; Title, DateTime, Msg: String);
end;
implementation
{ TLogDetailsController }
class procedure TLogDetailsController.Execute(TypeLog: Integer; Title, DateTime,
Msg: String);
var
LogDetailsController : TLogDetailsController;
begin
LogDetailsController := TLogDetailsController.Create;
LogDetailsController.Initialize(TypeLog,Title,DateTime,Msg);
end;
procedure TLogDetailsController.Initialize(TypeLog: Integer; Title, DateTime,
Msg: String);
begin
FView := TFLogRegisterDetails.Create(nil);
FView.LoadValues(TypeLog,Title,DateTime,Msg);
FView.ShowModal;
end;
end.
|
{$INCLUDE ..\cDefines.inc}
unit cStreams;
{ }
{ Streams v3.08 }
{ }
{ This unit is copyright © 1999-2004 by David J Butler }
{ }
{ This unit is part of Delphi Fundamentals. }
{ Its original file name is cStreams.pas }
{ The latest version is available from the Fundamentals home page }
{ http://fundementals.sourceforge.net/ }
{ }
{ I invite you to use this unit, free of charge. }
{ I invite you to distibute this unit, but it must be for free. }
{ I also invite you to contribute to its development, }
{ but do not distribute a modified copy of this file. }
{ }
{ A forum is available on SourceForge for general discussion }
{ http://sourceforge.net/forum/forum.php?forum_id=2117 }
{ }
{ }
{ Revision history: }
{ 01/03/1999 0.01 Initial version. }
{ 08/02/2000 1.02 AStreamEx. }
{ 08/05/2000 1.03 ATRecordStream. }
{ 01/06/2000 1.04 TFixedLenRecordStreamer. }
{ 29/05/2002 3.05 Created cReaders and cWriters units from cStreams. }
{ 03/08/2002 3.06 Moved TVarSizeAllocator to unit cVarAllocator. }
{ 18/08/2002 3.07 Added TReaderWriter as AStream. }
{ 17/03/2003 3.08 Added new file open mode: fsomCreateOnWrite }
{ }
interface
uses
{ Delphi }
SysUtils,
{ Fundamentals }
cReaders,
cWriters;
{ }
{ AStream }
{ Abstract base class for streams. }
{ }
type
AStream = class;
AStreamCopyProgressEvent = procedure (const Source, Destination: AStream;
const BytesCopied: Int64; var Abort: Boolean) of object;
AStream = class
protected
FOnCopyProgress : AStreamCopyProgressEvent;
function GetPosition: Int64; virtual; abstract;
procedure SetPosition(const Position: Int64); virtual; abstract;
function GetSize: Int64; virtual; abstract;
procedure SetSize(const Size: Int64); virtual; abstract;
function GetReader: AReaderEx; virtual; abstract;
function GetWriter: AWriterEx; virtual; abstract;
procedure TriggerCopyProgressEvent(const Source, Destination: AStream;
const BytesCopied: Int64; var Abort: Boolean); virtual;
public
function Read(var Buffer; const Size: Integer): Integer; virtual; abstract;
function Write(const Buffer; const Size: Integer): Integer; virtual; abstract;
property Position: Int64 read GetPosition write SetPosition;
property Size: Int64 read GetSize write SetSize;
function EOF: Boolean; virtual;
procedure Truncate; virtual;
property Reader: AReaderEx read GetReader;
property Writer: AWriterEx read GetWriter;
procedure ReadBuffer(var Buffer; const Size: Integer);
function ReadByte: Byte;
function ReadStr(const Size: Integer): String;
procedure WriteBuffer(const Buffer; const Size: Integer);
procedure WriteStr(const S: String);
procedure Assign(const Source: TObject); virtual;
function WriteTo(const Destination: AStream; const BlockSize: Integer = 0;
const Count: Int64 = -1): Int64;
property OnCopyProgress: AStreamCopyProgressEvent read FOnCopyProgress write FOnCopyProgress;
end;
EStream = class(Exception);
EStreamOperationAborted = class(EStream)
constructor Create;
end;
{ }
{ Stream proxies }
{ }
type
{ TStreamReaderProxy }
TStreamReaderProxy = class(AReaderEx)
protected
FStream : AStream;
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
public
constructor Create(const Stream: AStream);
property Stream: AStream read FStream;
function Read(var Buffer; const Size: Integer): Integer; override;
function EOF: Boolean; override;
end;
{ TStreamWriterProxy }
TStreamWriterProxy = class (AWriterEx)
protected
FStream : AStream;
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
procedure SetSize(const Size: Int64); override;
public
constructor Create(const Stream: AStream);
property Stream: AStream read FStream;
function Write(const Buffer; const Size: Integer): Integer; override;
end;
{ }
{ Stream functions }
{ }
type
TCopyProgressProcedure = procedure (const Source, Destination: AStream;
const BytesCopied: Int64; var Abort: Boolean);
TCopyDataEvent = procedure (const Offset: Int64; const Data: Pointer;
const DataSize: Integer) of object;
function CopyStream(const Source, Destination: AStream;
const SourceOffset: Int64 = 0; const DestinationOffset: Int64 = 0;
const BlockSize: Integer = 0; const Count: Int64 = -1;
const ProgressCallback: TCopyProgressProcedure = nil;
const CopyFromBack: Boolean = False): Int64; overload;
function CopyStream(const Source: AReaderEx; const Destination: AWriterEx;
const BlockSize: Integer = 0;
const CopyDataEvent: TCopyDataEvent = nil): Int64; overload;
procedure DeleteStreamRange(const Stream: AStream; const Position, Count: Int64;
const ProgressCallback: TCopyProgressProcedure = nil);
procedure InsertStreamRange(const Stream: AStream; const Position, Count: Int64;
const ProgressCallback: TCopyProgressProcedure = nil);
{ }
{ TReaderWriter }
{ Composition of a Reader and a Writer as a Stream. }
{ }
type
TReaderWriter = class(AStream)
protected
FReader : AReaderEx;
FWriter : AWriterEx;
FReaderOwner : Boolean;
FWriterOwner : Boolean;
procedure RaiseNoReaderError;
procedure RaiseNoWriterError;
function GetPosition: Int64; override;
procedure SetPosition(const Position: Int64); override;
function GetSize: Int64; override;
procedure SetSize(const Size: Int64); override;
function GetReader: AReaderEx; override;
function GetWriter: AWriterEx; override;
public
constructor Create(const Reader: AReaderEx; const Writer: AWriterEx;
const ReaderOwner: Boolean = True; const WriterOwner: Boolean = True);
destructor Destroy; override;
property Reader: AReaderEx read FReader;
property Writer: AWriterEx read FWriter;
property ReaderOwner: Boolean read FReaderOwner write FReaderOwner;
property WriterOwner: Boolean read FWriterOwner write FWriterOwner;
function Read(var Buffer; const Size: Integer): Integer; override;
function Write(const Buffer; const Size: Integer): Integer; override;
function EOF: Boolean; override;
procedure Truncate; override;
end;
EReaderWriter = class (Exception);
{ }
{ TFileStream }
{ Stream implementation for a file. }
{ }
type
TFileStreamOpenMode = (
fsomRead,
fsomReadWrite,
fsomCreate,
fsomCreateIfNotExist,
fsomCreateOnWrite);
TFileStreamAccessHint = (
fsahNone,
fsahRandomAccess,
fsahSequentialAccess);
TFileStreamOptions = Set of (
fsoWriteThrough);
TFileStream = class(TReaderWriter)
protected
FFileName : String;
FOpenMode : TFileStreamOpenMode;
FOptions : TFileStreamOptions;
FAccessHint : TFileStreamAccessHint;
procedure SetPosition(const Position: Int64); override;
procedure SetSize(const Size: Int64); override;
function GetReader: AReaderEx; override;
function GetWriter: AWriterEx; override;
function GetFileHandle: Integer;
function GetFileCreated: Boolean;
procedure EnsureCreateOnWrite;
public
constructor Create(const FileName: String;
const OpenMode: TFileStreamOpenMode;
const Options: TFileStreamOptions = [];
const AccessHint: TFileStreamAccessHint = fsahNone); overload;
constructor Create(const FileHandle: Integer; const HandleOwner: Boolean); overload;
property FileName: String read FFileName;
property FileHandle: Integer read GetFileHandle;
property FileCreated: Boolean read GetFileCreated;
procedure DeleteFile;
function Write(const Buffer; const Size: Integer): Integer; override;
end;
EFileStream = class(EStream);
{ }
{ Self-testing code }
{ }
procedure SelfTest;
implementation
{ }
{ EStreamOperationAborted }
{ }
constructor EStreamOperationAborted.Create;
begin
inherited Create('Stream operation aborted');
end;
{ }
{ TStreamReaderProxy }
{ }
constructor TStreamReaderProxy.Create(const Stream: AStream);
begin
inherited Create;
Assert(Assigned(Stream));
FStream := Stream;
end;
function TStreamReaderProxy.GetPosition: Int64;
begin
Result := FStream.Position;
end;
procedure TStreamReaderProxy.SetPosition(const Position: Int64);
begin
FStream.Position := Position;
end;
function TStreamReaderProxy.GetSize: Int64;
begin
Result := FStream.Size;
end;
function TStreamReaderProxy.Read(var Buffer; const Size: Integer): Integer;
begin
Result := FStream.Read(Buffer, Size)
end;
function TStreamReaderProxy.EOF: Boolean;
begin
Result := FStream.EOF;
end;
{ }
{ TStreamWriterProxy }
{ }
constructor TStreamWriterProxy.Create(const Stream: AStream);
begin
inherited Create;
Assert(Assigned(Stream));
FStream := Stream;
end;
function TStreamWriterProxy.GetPosition: Int64;
begin
Result := FStream.Position;
end;
procedure TStreamWriterProxy.SetPosition(const Position: Int64);
begin
FStream.Position := Position;
end;
function TStreamWriterProxy.GetSize: Int64;
begin
Result := FStream.Size;
end;
procedure TStreamWriterProxy.SetSize(const Size: Int64);
begin
FStream.Size := Size;
end;
function TStreamWriterProxy.Write(const Buffer; const Size: Integer): Integer;
begin
Result := FStream.Write(Buffer, Size)
end;
{ }
{ CopyStream }
{ }
const
DefaultBlockSize = 2048;
function CopyStream(const Source, Destination: AStream; const SourceOffset: Int64;
const DestinationOffset: Int64; const BlockSize: Integer; const Count: Int64;
const ProgressCallback: TCopyProgressProcedure; const CopyFromBack: Boolean): Int64;
var Buf : Pointer;
L, I, C : Integer;
R, S, D : Int64;
A : Boolean;
begin
if not Assigned(Source) then
raise EStream.Create('Invalid source');
if not Assigned(Destination) then
raise EStream.Create('Invalid destination');
S := SourceOffset;
D := DestinationOffset;
if (S < 0) or (D < 0) then
raise EStream.Create('Invalid offset');
if (Source = Destination) and (Count < 0) and (S < D) then
raise EStream.Create('Invalid parameters');
A := False;
if Assigned(ProgressCallback) then
begin
ProgressCallback(Source, Destination, 0, A);
if A then
raise EStreamOperationAborted.Create;
end;
Result := 0;
R := Count;
if R = 0 then
exit;
L := BlockSize;
if L <= 0 then
L := DefaultBlockSize;
if (R > 0) and (R < L) then
L := Integer(R);
if CopyFromBack then
begin
if R < 0 then
raise EStream.Create('Invalid count');
Inc(S, R - L);
Inc(D, R - L);
end;
GetMem(Buf, L);
try
While not Source.EOF and (R <> 0) do
begin
C := L;
if (R > 0) and (R < C) then
C := Integer(R);
if CopyFromBack then
Source.Position := S;
I := Source.Read(Buf^, C);
if (I <= 0) and not Source.EOF then
raise EStream.Create('Stream read error');
if CopyFromBack then
Destination.Position := D;
Destination.WriteBuffer(Buf^, I);
Inc(Result, I);
if R > 0 then
Dec(R, I);
if CopyFromBack then
begin
Dec(S, I);
Dec(D, I);
end
else
begin
Inc(S, I);
Inc(D, I);
end;
if Assigned(ProgressCallback) then
begin
ProgressCallback(Source, Destination, Result, A);
if A then
raise EStreamOperationAborted.Create;
end;
end;
finally
FreeMem(Buf);
end;
end;
function CopyStream(const Source: AReaderEx; const Destination: AWriterEx;
const BlockSize: Integer; const CopyDataEvent: TCopyDataEvent): Int64;
var Buf : Pointer;
L, I : Integer;
begin
if not Assigned(Source) then
raise EStream.Create('Invalid source');
if not Assigned(Destination) then
raise EStream.Create('Invalid destination');
L := BlockSize;
if L <= 0 then
L := DefaultBlockSize;
Result := 0;
GetMem(Buf, L);
try
While not Source.EOF do
begin
I := Source.Read(Buf^, L);
if (I = 0) and not Source.EOF then
Source.RaiseReadError;
Destination.WriteBuffer(Buf^, I);
if Assigned(CopyDataEvent) then
CopyDataEvent(Result, Buf, I);
Inc(Result, I);
end;
finally
FreeMem(Buf);
end;
end;
procedure DeleteStreamRange(const Stream: AStream; const Position, Count: Int64;
const ProgressCallback: TCopyProgressProcedure);
begin
if Count <= 0 then
exit;
if CopyStream(Stream, Stream, Position + Count, Position, 0, Count,
ProgressCallback, False) <> Count then
raise EStream.Create('Copy error');
end;
procedure InsertStreamRange(const Stream: AStream; const Position, Count: Int64;
const ProgressCallback: TCopyProgressProcedure);
begin
if Count <= 0 then
exit;
if CopyStream(Stream, Stream, Position, Position + Count, 0, Count,
ProgressCallback, True) <> Count then
raise EStream.Create('Copy error');
end;
{ }
{ AStream }
{ }
function AStream.EOF: Boolean;
begin
Result := Position >= Size;
end;
procedure AStream.Truncate;
begin
Size := Position;
end;
procedure AStream.ReadBuffer(var Buffer; const Size: Integer);
begin
if Size <= 0 then
exit;
if Read(Buffer, Size) <> Size then
raise EStream.Create('Read error');
end;
function AStream.ReadByte: Byte;
begin
ReadBuffer(Result, 1);
end;
function AStream.ReadStr(const Size: Integer): String;
var L : Integer;
begin
if Size <= 0 then
begin
Result := '';
exit;
end;
SetLength(Result, Size);
L := Read(Pointer(Result)^, Size);
if L <= 0 then
begin
Result := '';
exit;
end;
if L < Size then
SetLength(Result, L);
end;
procedure AStream.WriteBuffer(const Buffer; const Size: Integer);
begin
if Size <= 0 then
exit;
if Write(Buffer, Size) <> Size then
raise EStream.Create('Write error');
end;
procedure AStream.WriteStr(const S: String);
begin
WriteBuffer(Pointer(S)^, Length(S));
end;
procedure AStreamCopyCallback(const Source, Destination: AStream;
const BytesCopied: Int64; var Abort: Boolean);
begin
Assert(Assigned(Source) and Assigned(Destination) and not Abort, 'Assigned(Source) and Assigned(Destination) and not Abort');
Source.TriggerCopyProgressEvent(Source, Destination, BytesCopied, Abort);
if Abort then
exit;
Destination.TriggerCopyProgressEvent(Source, Destination, BytesCopied, Abort);
end;
procedure AStream.TriggerCopyProgressEvent(const Source, Destination: AStream;
const BytesCopied: Int64; var Abort: Boolean);
begin
if Assigned(FOnCopyProgress) then
FOnCopyProgress(Source, Destination, BytesCopied, Abort);
end;
procedure AStream.Assign(const Source: TObject);
begin
if not Assigned(Source) then
raise EStream.Create('Invalid source');
if Source is AStream then
Size := CopyStream(AStream(Source), self, 0, 0, 0, -1, AStreamCopyCallback, False) else
raise EStream.Create('Assign not defined for source type');
end;
function AStream.WriteTo(const Destination: AStream; const BlockSize: Integer;
const Count: Int64): Int64;
begin
Result := CopyStream(self, Destination, Position, Destination.Position,
BlockSize, Count, AStreamCopyCallback, False);
end;
{ }
{ TReaderWriter }
{ }
constructor TReaderWriter.Create(const Reader: AReaderEx; const Writer: AWriterEx;
const ReaderOwner: Boolean; const WriterOwner: Boolean);
begin
inherited Create;
FReader := Reader;
FReaderOwner := ReaderOwner;
FWriter := Writer;
FWriterOwner := WriterOwner;
end;
destructor TReaderWriter.Destroy;
begin
if FReaderOwner then
FReader.Free;
FReader := nil;
if FWriterOwner then
FWriter.Free;
FWriter := nil;
inherited Destroy;
end;
procedure TReaderWriter.RaiseNoReaderError;
begin
raise EReaderWriter.Create('No reader');
end;
procedure TReaderWriter.RaiseNoWriterError;
begin
raise EReaderWriter.Create('No writer');
end;
function TReaderWriter.GetReader: AReaderEx;
begin
Result := FReader;
end;
function TReaderWriter.GetWriter: AWriterEx;
begin
Result := FWriter;
end;
function TReaderWriter.GetPosition: Int64;
begin
if Assigned(FReader) then
Result := FReader.Position else
if Assigned(FWriter) then
Result := FWriter.Position else
Result := 0;
end;
procedure TReaderWriter.SetPosition(const Position: Int64);
begin
if Assigned(FReader) then
FReader.Position := Position;
if Assigned(FWriter) then
FWriter.Position := Position;
end;
function TReaderWriter.GetSize: Int64;
begin
if Assigned(FWriter) then
Result := FWriter.Size else
if Assigned(FReader) then
Result := FReader.Size else
Result := 0;
end;
procedure TReaderWriter.SetSize(const Size: Int64);
begin
if not Assigned(FWriter) then
RaiseNoWriterError;
FWriter.Size := Size;
end;
function TReaderWriter.Read(var Buffer; const Size: Integer): Integer;
begin
if not Assigned(FReader) then
RaiseNoReaderError;
Result := FReader.Read(Buffer, Size);
end;
function TReaderWriter.Write(const Buffer; const Size: Integer): Integer;
begin
if not Assigned(FWriter) then
RaiseNoWriterError;
Result := FWriter.Write(Buffer, Size);
end;
function TReaderWriter.EOF: Boolean;
begin
if Assigned(FReader) then
Result := FReader.EOF else
if Assigned(FWriter) then
Result := FWriter.Position >= FWriter.Size else
Result := True;
end;
procedure TReaderWriter.Truncate;
begin
if not Assigned(FWriter) then
RaiseNoWriterError;
FWriter.Truncate;
end;
{ }
{ TFileStream }
{ }
const
WriterModes: Array[TFileStreamOpenMode] of TFileWriterOpenMode =
(fwomOpen, fwomOpen, fwomCreate, fwomCreateIfNotExist, fwomOpen);
ReaderAccessHints: Array[TFileStreamAccessHint] of TFileReaderAccessHint =
(frahNone, frahRandomAccess, frahSequentialAccess);
WriterAccessHints: Array[TFileStreamAccessHint] of TFileWriterAccessHint =
(fwahNone, fwahRandomAccess, fwahSequentialAccess);
constructor TFileStream.Create(const FileName: String;
const OpenMode: TFileStreamOpenMode; const Options: TFileStreamOptions;
const AccessHint: TFileStreamAccessHint);
var W : TFileWriter;
R : AReaderEx;
T : TFileWriterOptions;
begin
FFileName := FileName;
FOpenMode := OpenMode;
FOptions := Options;
FAccessHint := AccessHint;
R := nil;
W := nil;
T := [];
if fsoWriteThrough in Options then
Include(T, fwoWriteThrough);
Case OpenMode of
fsomRead :
R := TFileReader.Create(FileName, ReaderAccessHints[AccessHint]);
fsomCreateOnWrite :
try
W := TFileWriter.Create(FileName, fwomOpen, T,
WriterAccessHints[AccessHint]);
except
W := nil;
end;
else
W := TFileWriter.Create(FileName, WriterModes[OpenMode], T,
WriterAccessHints[AccessHint]);
end;
if Assigned(W) then
try
R := TFileReader.Create(W.Handle, False);
except
W.Free;
raise;
end;
inherited Create(R, W, True, True);
end;
constructor TFileStream.Create(const FileHandle: Integer; const HandleOwner: Boolean);
var W : TFileWriter;
R : TFileReader;
begin
W := TFileWriter.Create(FileHandle, HandleOwner);
try
R := TFileReader.Create(FileHandle, False);
except
W.Free;
raise;
end;
inherited Create(R, W, True, True);
end;
function TFileStream.GetFileHandle: Integer;
begin
Assert(Assigned(FReader), 'Assigned(FReader)');
Result := TFileReader(FReader).Handle;
end;
function TFileStream.GetFileCreated: Boolean;
begin
Result := Assigned(FWriter) and TFileWriter(FWriter).FileCreated;
end;
procedure TFileStream.DeleteFile;
begin
if FFileName = '' then
raise EFileStream.Create('No filename');
SysUtils.DeleteFile(FFileName);
end;
procedure TFileStream.EnsureCreateOnWrite;
var T : TFileWriterOptions;
begin
T := [];
if fsoWriteThrough in FOptions then
Include(T, fwoWriteThrough);
FWriter := TFileWriter.Create(FileName, fwomCreateIfNotExist, T,
WriterAccessHints[FAccessHint]);
FReader := TFileReader.Create(TFileWriter(FWriter).Handle, False);
end;
procedure TFileStream.SetPosition(const Position: Int64);
begin
if (FOpenMode = fsomCreateOnWrite) and not Assigned(FWriter) and
(Position > 0) then
EnsureCreateOnWrite;
if Assigned(FWriter) then
FWriter.Position := Position else
if Assigned(FReader) then
FReader.Position := Position;
end;
procedure TFileStream.SetSize(const Size: Int64);
begin
if (FOpenMode = fsomCreateOnWrite) and not Assigned(FWriter) then
EnsureCreateOnWrite;
inherited SetSize(Size);
end;
function TFileStream.GetReader: AReaderEx;
begin
if (FOpenMode = fsomCreateOnWrite) and not Assigned(FWriter) then
EnsureCreateOnWrite;
Result := FReader;
end;
function TFileStream.GetWriter: AWriterEx;
begin
if (FOpenMode = fsomCreateOnWrite) and not Assigned(FWriter) then
EnsureCreateOnWrite;
Result := FWriter;
end;
function TFileStream.Write(const Buffer; const Size: Integer): Integer;
begin
if (FOpenMode = fsomCreateOnWrite) and not Assigned(FWriter) then
EnsureCreateOnWrite;
Result := inherited Write(Buffer, Size);
end;
{ }
{ Self-testing code }
{ }
{$ASSERTIONS ON}
procedure SelfTest;
begin
end;
end.
|
unit frm_seleccionarpaquetecotemar;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, frm_connection, global, utilerias, StdCtrls, DBCtrls, DB,
ZAbstractRODataset, ZAbstractDataset, ZDataset, Mask, rxToolEdit, rxCurrEdit,
ComCtrls;
type
TfrmSeleccionarAnexoCotemar = class(TForm)
grupoExistente: TGroupBox;
dsPaquetes: TDataSource;
Label1: TLabel;
grupoNuevo: TGroupBox;
Label2: TLabel;
RadioButton1: TRadioButton;
chkSeleccionar: TRadioButton;
RadioButton3: TRadioButton;
chkCrear: TRadioButton;
Label3: TLabel;
cmdCancelar: TButton;
qryPaquetes: TZQuery;
Label4: TLabel;
mDescripcion: TDBMemo;
DBComboBox1: TDBComboBox;
sNumeroActividad: TEdit;
sDescripcion: TMemo;
Label6: TLabel;
Label5: TLabel;
dFechaInicio: TDateTimePicker;
dFechaFinal: TDateTimePicker;
Duracion: TRxCalcEdit;
Label7: TLabel;
procedure chkSeleccionarClick(Sender: TObject);
procedure chkCrearClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dFechaInicioChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmdCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmSeleccionarAnexoCotemar: TfrmSeleccionarAnexoCotemar;
implementation
{$R *.dfm}
//este formulario no sirve para importar los anexos..
procedure TfrmSeleccionarAnexoCotemar.chkCrearClick(Sender: TObject);
begin
grupoExistente.Enabled := false;
grupoNuevo.Enabled := true;
grupoNuevo.Color := clInactiveCaption;
grupoExistente.Color := clBtnFace;
sNumeroActividad.setFocus;
end;
procedure TfrmSeleccionarAnexoCotemar.chkSeleccionarClick(Sender: TObject);
begin
grupoExistente.Enabled := true;
grupoNuevo.Enabled := false;
grupoNuevo.Color := clBtnFace;
grupoExistente.Color := clInactiveCaption;
DBComboBox1.SetFocus;
end;
procedure TfrmSeleccionarAnexoCotemar.cmdCancelarClick(Sender: TObject);
begin
close;
end;
procedure TfrmSeleccionarAnexoCotemar.dFechaInicioChange(Sender: TObject);
begin
Duracion.value := dFechaFinal.Date - dFechaInicio.Date;
end;
procedure TfrmSeleccionarAnexoCotemar.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := cafree;
end;
procedure TfrmSeleccionarAnexoCotemar.FormShow(Sender: TObject);
begin
grupoExistente.Enabled := true;
grupoNuevo.Enabled := false;
grupoNuevo.Color := clBtnFace;
grupoExistente.Color := clInactiveCaption;
DBComboBox1.SetFocus;
qryPaquetes.Active := false;
qryPaquetes.Params.ParamByName('contrato').Value := global_contrato;
qryPaquetes.Open;
end;
end.
|
unit FC.StockChart.UnitTask.Calendar.EditorDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FC.Dialogs.DockedDialogCloseAndAppWindow_B, JvDockControlForm, ImgList, JvComponentBase, JvCaptionButton, StdCtrls,
ExtendControls, ExtCtrls,StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, Grids, DBGrids,
MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, DB,FC.StockData.InputDataCollectionToDataSetMediator,
MemoryDS, ufmDialogOKCancel_B, ActnList, Mask, ComCtrls,
ufmDialogOKCancelApply_B, Menus, ActnPopup, Buttons, OleServer, WordXP;
type
TWorkMode = (wmAdding, wmEditing);
TfmCalendarEditorDialog = class(TfmDialogOKCancelApply_B)
Label1: TLabel;
edOpenDate: TExtendDateTimePicker;
edCountry: TExtendComboBox;
Label6: TLabel;
Label2: TLabel;
edIndicator: TExtendEdit;
Label3: TLabel;
edPeriod: TExtendEdit;
Label4: TLabel;
edPriority: TExtendEdit;
Label5: TLabel;
edForecast: TExtendEdit;
Label7: TLabel;
edFact: TExtendEdit;
Label8: TLabel;
edNotes: TExtendEdit;
Label9: TLabel;
cbPFTrend: TExtendComboBox;
Label10: TLabel;
cbFFTrend: TExtendComboBox;
Label11: TLabel;
edPrevious: TExtendEdit;
buPaste: TSpeedButton;
pmPaste: TPopupActionBar;
miFromIfcMarkets: TMenuItem;
edOpenTime: TExtendMinutePicker;
WordDocument: TWordDocument;
miFromSaxoBankcom: TMenuItem;
cbTimeZone: TExtendComboBox;
Label12: TLabel;
edSource: TExtendEdit;
procedure miFromSaxoBankcomClick(Sender: TObject);
procedure buPasteClick(Sender: TObject);
procedure miFromIfcMarketsClick(Sender: TObject);
private
FItem: ISCCalendarItem;
FSaved: boolean;
protected
function LoadData : boolean; override;
function SaveData : boolean; override;
function IsDataChanged: boolean; override;
function WorkMode: TWorkMode;
public
constructor Create(const aItem: ISCCalendarItem); reintroduce;
class function RunEdit(const aItem: ISCCalendarItem):boolean;
class function RunNew:boolean;
end;
implementation
uses Types, Clipbrd, StrUtils, DateUtils, BaseUtils, SystemService, Application.Definitions,
FC.Singletons,
FC.StockData.StockCalendar,
FC.DataUtils;
{$R *.dfm}
{ TfmCalendarEditorDialog }
procedure TfmCalendarEditorDialog.buPasteClick(Sender: TObject);
var
P: TPoint;
begin
P:=TControl(Sender).ClientToScreen(Point(0,TControl(Sender).Height));
pmPaste.Popup(P.x, P.y);
end;
constructor TfmCalendarEditorDialog.Create(const aItem: ISCCalendarItem);
var
ii: TSCCalendarChangeType;
begin
inherited Create(nil);
for ii := Low(TSCCalendarChangeType) to High(TSCCalendarChangeType) do
begin
cbPFTrend.Items.AddData(CalendarChangeTypeNames[ii],integer(ii));
cbFFTrend.Items.AddData(CalendarChangeTypeNames[ii],integer(ii));
end;
FItem:=aItem;
{
if (FItem=nil) then
begin
edOpenDate.Enabled:=true;
edOpenTime.Enabled:=true;
edCountry.ReadOnly:=false;
edIndicator.ReadOnly:=false;
edPeriod.ReadOnly:=false;
end;
}
cbTimeZone.Items.AddData('GMT',0);
if GetLocalTimeZoneHourOffset>0 then
cbTimeZone.Items.AddData('Local (+'+IntToStr(GetLocalTimeZoneHourOffset)+')',1)
else
cbTimeZone.Items.AddData('Local ('+IntToStr(GetLocalTimeZoneHourOffset)+')',1);
if GetHistoryDataTimeZoneHourOffset>0 then
cbTimeZone.Items.AddData('History Center (+'+IntToStr(GetHistoryDataTimeZoneHourOffset)+')',2)
else
cbTimeZone.Items.AddData('History Center ('+IntToStr(GetHistoryDataTimeZoneHourOffset)+')',2);
cbTimeZone.SelectByData(2);
end;
procedure TfmCalendarEditorDialog.miFromIfcMarketsClick(Sender: TObject);
var
s: string;
aStrings: TStringList;
aSaveChanges: OleVariant;
begin
TWaitCursor.SetUntilIdle;
WordDocument.Connect;
try
WordDocument.Range.Paste;
WordDocument.Range.Select;
WordDocument.Range.Copy;
aSaveChanges:=false;
WordDocument.Close(aSaveChanges);
finally
WordDocument.Disconnect;
end;
Clipboard.Open;
try
s:=StrTrimRight(Clipboard.AsText,[#13,#10]);
finally
Clipboard.Close;
end;
aStrings:=TStringList.Create;
try
SplitString(s,aStrings,[#9],false);
//Country
try
edCountry.Text:=aStrings[0];
except
MsgBox.MessageFailure(Handle,'Bad format: country not found');
exit;
end;
//Indicator
try
edIndicator.Text:=aStrings[1];
except
MsgBox.MessageFailure(Handle,'Bad format: indicator not found');
exit;
end;
//Time
try
edOpenTime.Time:=StrToTime(aStrings[2]);
except
MsgBox.MessageFailure(Handle,'Bad format: time is not valid');
exit;
end;
//Forecast
try
edForecast.Text:=aStrings[3];
except
MsgBox.MessageFailure(Handle,'Bad format: forecast not found');
exit;
end;
//Previous
try
edPrevious.Text:=aStrings[4];
except
MsgBox.MessageFailure(Handle,'Bad format: previous data not found');
exit;
end;
finally
aStrings.Free;
end;
end;
procedure TfmCalendarEditorDialog.miFromSaxoBankcomClick(Sender: TObject);
var
x: integer;
I: Integer;
Data: THandle;
pch: pchar;
aStrings: TStringList;
aCountry: string;
aSaveChanges: OleVariant;
s: string;
begin
inherited;
aStrings:=TStringList.Create;
Clipboard.Open;
Data := GetClipboardData(49358);
try
if Data <> 0 then
pch := PChar(GlobalLock(Data))
else
pch := '';
aStrings.Text:=pch;
finally
if Data <> 0 then GlobalUnlock(Data);
Clipboard.Close;
end;
for i := 0 to aStrings.Count - 1 do
begin
x:=StrIPos('<IMG',aStrings[i]);
if x<>0 then
begin
x:=StrIPosEnd('alt=',aStrings[i],x);
if (x<>0) then
begin
aCountry:=Trim(MidStr(aStrings[i],x,High(word)));
aCountry:=StrDeleteEdges(aCountry);
aCountry:=Trim(aCountry);
break;
end;
end;
end;
WordDocument.Connect;
try
WordDocument.Range.Paste;
WordDocument.Range.Select;
WordDocument.Range.Copy;
aSaveChanges:=false;
WordDocument.Close(aSaveChanges);
finally
WordDocument.Disconnect;
end;
Clipboard.Open;
try
s:=StrTrimRight(Clipboard.AsText,[#13,#10]);
finally
Clipboard.Close;
end;
aStrings.Clear;
try
SplitString(s,aStrings,[#9],false);
//Country
try
edCountry.Text:=aCountry;
except
MsgBox.MessageFailure(Handle,'Bad format: country not found');
exit;
end;
//Indicator
try
edIndicator.Text:=aStrings[2];
except
MsgBox.MessageFailure(Handle,'Bad format: indicator not found');
exit;
end;
//Time
try
edOpenTime.Time:=IncHour(StrToTime(aStrings[0]),2);
except
MsgBox.MessageFailure(Handle,'Bad format: time is not valid');
exit;
end;
//Period
try
edPeriod.Text:=aStrings[3];
except
MsgBox.MessageFailure(Handle,'Bad format: time is not valid');
exit;
end;
//Forecast
try
edForecast.Text:=aStrings[4];
except
MsgBox.MessageFailure(Handle,'Bad format: forecast not found');
exit;
end;
//Previous
try
edPrevious.Text:=aStrings[5];
except
MsgBox.MessageFailure(Handle,'Bad format: previous data not found');
exit;
end;
finally
aStrings.Free;
end;
end;
function TfmCalendarEditorDialog.IsDataChanged: boolean;
begin
if WorkMode=wmEditing then
begin
result:=
(not SameDateTime(Trunc(edOpenDate.DateTime)+Frac(edOpenTime.Time),FItem.GetDateTime)) or
(edCountry.Text<>FItem.GetCountry) or
(edIndicator.Text<>FItem.GetIndicator) or
(edPriority.Text<>FItem.GetPriority) or
(edPeriod.Text<>FItem.GetPeriod) or
(edPrevious.Text<>FItem.GetPreviousValue) or
(edForecast.Text<>FItem.GetForecastValue) or
(edFact.Text<>FItem.GetFactValue) or
(cbPFTrend.CurrentItemData<>integer(FItem.GetPFChangeType)) or
(cbFFTrend.CurrentItemData<>integer(FItem.GetFFChangeType)) or
(edSource.Text<>FItem.GetSource) or
(edNotes.Text<>FItem.GetNotes);
end
else begin
result:=true;
end;
end;
function TfmCalendarEditorDialog.LoadData: boolean;
var
aCountries: TStringDynArray;
i: integer;
begin
aCountries:=StockDataStorage.QueryStockDataCalendarCountries;
for i := 0 to High(aCountries) do
edCountry.Items.Add(aCountries[i]);
if WorkMode=wmEditing then
begin
edOpenDate.DateTime:=FItem.GetDateTime;
edOpenTime.Time:=Frac(FItem.GetDateTime);
edCountry.Text:=FItem.GetCountry;
edIndicator.Text:=FItem.GetIndicator;
edPriority.Text:=FItem.GetPriority;
edPeriod.HandleNeeded; //??? какая-то фигня. теряется Text
edPeriod.Text:=FItem.GetPeriod;
edPrevious.Text:=FItem.GetPreviousValue;
edForecast.Text:=FItem.GetForecastValue;
edFact.Text:=FItem.GetFactValue;
edNotes.Text:=FItem.GetNotes;
edSource.Text:=FItem.GetSource;
//в какую сторону сменился показатель, если сравнивать Previous и Fact
cbPFTrend.SelectByData(integer(FItem.GetPFChangeType));
//в какую сторону сменился показатель, если сравнивать Forecast и Fact
cbFFTrend.SelectByData(integer(FItem.GetFFChangeType));
end
else begin
edOpenDate.DateTime:=GetNowInHistoryCenterZone;
edOpenTime.Time:=Frac(GetNowInHistoryCenterZone);
//в какую сторону сменился показатель, если сравнивать Previous и Fact
cbPFTrend.SelectByData(integer(cttUnknown));
//в какую сторону сменился показатель, если сравнивать Forecast и Fact
cbFFTrend.SelectByData(integer(cttUnknown));
end;
result:=true;
end;
function TfmCalendarEditorDialog.SaveData: boolean;
var
aCalendar: IStockCalendarWriteable;
aDate: TDateTime;
begin
aDate:=Trunc(edOpenDate.DateTime)+Frac(edOpenTime.Time);
if (cbTimeZone.CurrentItemData=0) then //GMT
aDate:=IncHour(aDate,GetHistoryDataTimeZoneHourOffset)
else if cbTimeZone.CurrentItemData=1 then //local
aDate:=LocalTimeToHistoryTime(aDate);
aCalendar:=TStockCalendar.Create;
if WorkMode=wmEditing then
begin
aCalendar.Add(
FItem.GetID,
aDate,
edCountry.Text,
FItem.GetClass,
edIndicator.Text,
edPriority.Text,
edPeriod.Text,
edPrevious.Text,
edForecast.Text,
edFact.Text,
TSCCalendarChangeType(cbPFTrend.CurrentItemData),
TSCCalendarChangeType(cbFFTrend.CurrentItemData),
edSource.Text,
edNotes.Text);
StockDataStorage.UpdateCalendarItem(aCalendar.GetItem(0));
FItem:=aCalendar.GetItem(0);
end
else begin
aCalendar.Add(
-1,
aDate,
edCountry.Text,
0,
edIndicator.Text,
edPriority.Text,
edPeriod.Text,
edPrevious.Text,
edForecast.Text,
edFact.Text,
TSCCalendarChangeType(cbPFTrend.CurrentItemData),
TSCCalendarChangeType(cbFFTrend.CurrentItemData),
edSource.Text,
edNotes.Text);
StockDataStorage.ImportCalendar(aCalendar,imMergeReplaceOld,nil);
end;
FSaved:=true;
result:=true;
end;
function TfmCalendarEditorDialog.WorkMode: TWorkMode;
begin
if FItem=nil then
Result:=wmAdding
else
Result:=wmEditing;
end;
class function TfmCalendarEditorDialog.RunEdit(const aItem: ISCCalendarItem):boolean;
begin
with TfmCalendarEditorDialog.Create(aItem) do
try
ShowModal;
result:=FSaved;
finally
Free;
end;
end;
class function TfmCalendarEditorDialog.RunNew: boolean;
begin
with TfmCalendarEditorDialog.Create(nil) do
try
ShowModal;
result:=FSaved;
finally
Free;
end;
end;
end.
|
//====================================================================//
// uPinjam //
//--------------------------------------------------------------------//
// Unit yang menangani hal-hal yang berhubungan dengan peminjaman //
//====================================================================//
unit uPinjam;
interface
uses uFileLoader, uDate, Crt;
procedure PinjamBuku (var arrHistoryPeminjaman : PinjamArr ; var arrBuku : BArr ; UserIn : User);
{Mengisi data yang diinputkan oleh pengguna ke dalam arrHistoryPeminjaman}
{I.S. : arrHistoryPeminjaman sudah berisi data dari file riwayat peminjaman dan/atau modifikasi di main program}
{F.S. : arrHistoryPeminjaman tercetak ke layar sesuai format data riwayat peminjaman}
procedure cek_riwayat(var arrHistoryPeminjaman: PinjamArr; var arrBuku: BArr);
{ mencetak riwayat peminjaman input username dengan format
tanggal pengembalian | ID Buku | Judul Buku }
procedure PrintHistoryPeminjaman (var arrHistoryPeminjaman : PinjamArr);
{Menulis elemen-elemen dari arrHistoryPeminjaman ke layar dengan format sesuai data riwayat peminjaman}
{I.S. : arrHistoryPeminjaman sudah berisi data dari file riwayat peminjaman dan/atau modifikasi di main program}
{F.S. : arrHistoryPeminjaman tercetak ke layar sesuai format data riwayat peminjaman}
implementation
procedure PinjamBuku (var arrHistoryPeminjaman : PinjamArr ; var arrBuku : BArr ; UserIn : User);
{Mengisi data yang diinputkan oleh pengguna ke dalam arrHistoryPeminjaman}
{I.S. : arrHistoryPeminjaman sudah berisi data dari file riwayat peminjaman dan/atau modifikasi di main program}
{F.S. : arrHistoryPeminjaman tercetak ke layar sesuai format data riwayat peminjaman}
{ KAMUS LOKAL }
var
found : boolean;
i, Tahun, Bulan, Hari : integer;
tanggalpinjamstring, id, judul_buku : string; // variabel tanggalpinjam untuk menyimpan tanggal peminjaman
{ ALGORITMA }
begin
write('Masukkan id buku yang ingin dipinjam : ');
readln(id);
found := false;
i := 1;
judul_buku := '';
while (not found) and (i <= lenBuku) do
// Pengulangan iterate-stop ketika data belum
// ditemukan dan indeks i kurang dari sama dengan lenbuku
// Pengulangan dicari untuk memastikan buku yang ingin dipinjam masih tersedia atau
// sudah habis
begin
if (arrBuku[i].ID_Buku = id) then
begin
found := true;
end else
begin
found := false;
inc(i);
end;
end;
write('Masukkan tanggal hari ini: ');
readln(tanggalpinjamstring); // Data tanggal yang dimasukkan berupa string
if (found = true) then
begin
// Jika jumlah buku lebih dari 0 dan masih tersedia
judul_buku := arrBuku[i].Judul_Buku;
if (arrBuku[i].Jumlah_Buku > 0) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Peminjaman := ParseDate(tanggalpinjamstring);
// Mengubah masukan tanggal yang berupa string menjadi type yang berbentuk Date
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].ID_Buku := id;
writeln('Buku ', judul_buku, ' berhasil dipinjam!');
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Peminjaman := ParseDate(tanggalpinjamstring);
Tahun := arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Peminjaman.YYYY;
Bulan := arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Peminjaman.MM;
Hari := arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Peminjaman.DD;
// Program yang digunakan untuk menangani Tanggal Batas Pengembalian yaitu 7 hari setelah
// Tanggal Peminjaman
if (Bulan = 1) or (Bulan = 3) or (Bulan = 5) or (Bulan = 7) or (Bulan = 8) or (Bulan = 10) then
begin
if (Hari >= 1) and (Hari <= 24) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari + 7;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end else if (Hari > 24) and (Hari <= 31) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari - 24;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan + 1;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end;
end else if (Bulan = 4) or (Bulan = 6) or (Bulan = 9) or (Bulan = 11) then
begin
if (Hari >= 1) and (Hari <= 23) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari + 7;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end else if (Hari > 23) and (Hari <= 30) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari - 23;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan + 1;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end;
end else if (Bulan = 2) then
begin
if ((Tahun mod 4 = 0) and (Tahun mod 100 <> 0)) or (Tahun mod 400 = 0) then
begin
if (Hari >= 1) and (Hari <= 22) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari + 7;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end else if (Hari > 22) and (Hari <= 29) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari - 22;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan + 1;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end;
end else
begin
if (Hari >= 1) and (Hari <= 21) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari + 7;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end else if (Hari > 21) and (Hari <= 28) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari - 21;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan + 1;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end;
end;
end else if (Bulan = 12) then
begin
if (Hari >= 1) and (Hari <= 24) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari + 7;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := Bulan;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun;
end else if (Hari > 24) and (Hari <= 31) then
begin
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.DD := Hari - 24;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.MM := 1;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Tanggal_Batas_Pengembalian.YYYY := Tahun + 1;
end;
end;
arrBuku[i].Jumlah_Buku := arrBuku[i].Jumlah_Buku - 1;
arrHistoryPeminjaman[lenHistoryPeminjaman + 1].Username := UserIn.Username;
// Data username diimpor dari file uFileLoader
writeln('Tersisa ', arrBuku[i].Jumlah_Buku,' ', arrBuku[i].Judul_Buku);
writeln('Terima kasih sudah meminjam');
lenHistoryPeminjaman := lenHistoryPeminjaman + 1
end else // Jika jumlah buku tidak lebih besar dari 0 (tidak tersedia)
begin
writeln('Buku ', judul_buku, ' sedang habis!');
writeln('Coba lain kali');
end;
end;
writeln();
writeln('Ketik 0 untuk kembali ke menu.');
readln();
ClrScr;
end;
procedure cek_riwayat(var arrHistoryPeminjaman: PinjamArr; var arrBuku: BArr);
{ mencetak riwayat peminjaman input username dengan format
tanggal pengembalian | ID Buku | Judul Buku }
{ KAMUS LOKAL }
var
i, j, c, x: integer; { i indeks array pengembalian,
j indeks array buku,
c indeks counter untuk diset 0 semua,
x indeks counter
}
uname, judul_buku: string; { uname input username,
judul buku variabel sementara untuk
menampilkan judul buku dari array buku
}
found : boolean;
counter : array[1..1000] of integer; { array untuk menampung indeks
username untuk mencari judul buku }
tgl : Date; { variabel untuk menuliskan tanggal }
{ ALGORITMA }
begin
write('Masukkan username pengunjung : '); readln(uname);
writeln('Riwayat: ');
{ inisialisasi }
i := 0;
j := 1;
c := 0;
x := 1;
for c:=1 to 1000 do { EOP : c=1000 }
begin
counter[c]:=0; { inisialisasi isi array 0 semua }
end;
for i:=1 to lenHistoryPeminjaman do { EOP : i = lenHistoryPengembalian }
begin
if (uname = arrHistoryPeminjaman[i].Username) then { Proses kasus uname = username pada array pengembalian}
begin
counter[j] := i;
j := j+1;
end;
end;
while (counter[x]<>0) do { EOP : elemen array counter = 0 }
begin
j:=0; { inisialisasi ulang untuk indeks j }
found := false; { inisialisasi found = false }
while (not found) do { EOP : found = true }
begin
j:=j+1;
if (arrHistoryPeminjaman[counter[x]].ID_Buku = arrBuku[j].ID_Buku) then { proses kasus ID buku pada array pengembalian = ID buku array buku }
begin
judul_buku := arrBuku[j].Judul_Buku;
found := true;
end;
end;
tgl := arrHistoryPeminjaman[counter[x]].Tanggal_Peminjaman;
writeln(tgl.DD, '/', tgl.MM, '/', tgl.YYYY ,' | ',arrHistoryPeminjaman[counter[x]].ID_Buku,' | ',judul_buku);
x := x+1;
end;
writeln();
writeln('Ketik 0 untuk kembali ke menu.');
readln();
ClrScr;
end;
procedure PrintHistoryPeminjaman (var arrHistoryPeminjaman : PinjamArr);
{Menulis elemen-elemen dari arrHistoryPeminjaman ke layar dengan format sesuai data riwayat peminjaman}
{I.S. : arrHistoryPeminjaman sudah berisi data dari file riwayat peminjaman dan/atau modifikasi di main program}
{F.S. : arrHistoryPeminjaman tercetak ke layar sesuai format data riwayat peminjaman}
{' | ' digunakan untuk pemisah antar kolom}
{ KAMUS LOKAL }
var
k : integer;
{ ALGORITMA }
begin
for k := 1 to (lenHistoryPeminjaman) do
begin
write(k);
write(' | ');
write(arrHistoryPeminjaman[k].Username);
write(' | ');
write(arrHistoryPeminjaman[k].ID_Buku);
write(' | ');
WriteDate(arrHistoryPeminjaman[k].Tanggal_Peminjaman);
write(' | ');
WriteDate(arrHistoryPeminjaman[k].Tanggal_Batas_Pengembalian);
write(' | ');
if (arrHistoryPeminjaman[k].Status_Pengembalian) then
begin
write('Sudah Kembali');
end else
begin
write('Belum Kembali');
end;
writeln();
end;
writeln();
writeln('Ketik 0 untuk kembali ke menu.');
readln();
ClrScr;
end;
end.
|
unit MediaStream.PtzProtocol.Http.EverFocus;
interface
uses SysUtils, MediaStream.PtzProtocol.Base,MediaStream.PtzProtocol.Http;
type
TPtzProtocol_Http_EverFocus = class (TPtzProtocol_Http)
private
public
procedure PtzApertureDecrease(aDuration: cardinal); override;
procedure PtzApertureDecreaseStop; override;
procedure PtzApertureIncrease(aDuration: cardinal); override;
procedure PtzApertureIncreaseStop; override;
procedure PtzFocusIn(aDuration: cardinal); override;
procedure PtzFocusInStop; override;
procedure PtzFocusOut(aDuration: cardinal); override;
procedure PtzFocusOutStop; override;
procedure PtzZoomIn(aDuration: cardinal); override;
procedure PtzZoomInStop; override;
procedure PtzZoomOut(aDuration: cardinal); override;
procedure PtzZoomOutStop; override;
procedure PtzMoveDown(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveDownStop; override;
procedure PtzMoveLeft(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveLeftStop; override;
procedure PtzMoveRight(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveRightStop; override;
procedure PtzMoveUp(aDuration: cardinal; aSpeed: byte); override;
procedure PtzMoveUpStop; override;
//===== Перемещение на заданную позицию
//Движение на указанную точку-пресет
procedure PtzMoveToPoint(aId: cardinal);override;
//Движение в указанную позицию. Позиция указывается по оси X и Y в градусах
procedure PtzMoveToPosition(const aPositionPan,aPositionTilt: double); override;
class function Name: string; override;
end;
implementation
class function TPtzProtocol_Http_EverFocus.Name: string;
begin
result:='Http EverFocus';
end;
procedure TPtzProtocol_Http_EverFocus.PtzApertureDecrease(aDuration: cardinal);
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzApertureDecreaseStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzApertureIncrease(aDuration: cardinal);
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzApertureIncreaseStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzFocusIn(aDuration: cardinal);
begin
ExecutePost('com/ptz.cgi?rfocus=100');
end;
procedure TPtzProtocol_Http_EverFocus.PtzFocusInStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzFocusOut(aDuration: cardinal);
begin
ExecutePost('com/ptz.cgi?rfocus=-100');
end;
procedure TPtzProtocol_Http_EverFocus.PtzFocusOutStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveDown(aDuration: cardinal;aSpeed: byte);
begin
ExecutePost('com/ptz.cgi?move=down');
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveDownStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveLeft(aDuration: cardinal;aSpeed: byte);
begin
ExecutePost('com/ptz.cgi?move=left');
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveLeftStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveRight(aDuration: cardinal;aSpeed: byte);
begin
ExecutePost('com/ptz.cgi?move=right');
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveRightStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveToPoint(aId: cardinal);
begin
ExecutePost('com/ptz.cgi?gotoserverpresetno='+IntToStr(aId));
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveToPosition(const aPositionPan,aPositionTilt: double);
begin
ExecutePost('com/ptz.cgi?pan='+StringReplace(FloatToStr(aPositionPan),DecimalSeparator,'.',[]));
ExecutePost('com/ptz.cgi?tilt='+StringReplace(FloatToStr(aPositionTilt),DecimalSeparator,'.',[]));
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveUp(aDuration: cardinal;aSpeed: byte);
begin
ExecutePost('com/ptz.cgi?move=up');
end;
procedure TPtzProtocol_Http_EverFocus.PtzMoveUpStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzZoomIn(aDuration: cardinal);
begin
ExecutePost('com/ptz.cgi?rzoom=100');
end;
procedure TPtzProtocol_Http_EverFocus.PtzZoomInStop;
begin
end;
procedure TPtzProtocol_Http_EverFocus.PtzZoomOut(aDuration: cardinal);
begin
ExecutePost('com/ptz.cgi?rzoom=-100');
end;
procedure TPtzProtocol_Http_EverFocus.PtzZoomOutStop;
begin
end;
initialization
ProtocolRegistry.AddProtocol(TPtzProtocol_Http_EverFocus);
end.
|
unit Server_s;
{This file was generated on 11 Aug 2000 20:06:56 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file server.idl. }
{Delphi Pascal unit : Server_s }
{derived from IDL module : Server }
interface
uses
CORBA,
Server_i,
Server_c;
type
TIMyTestSkeleton = class;
TMyTestFactorySkeleton = class;
TIMyTestSkeleton = class(CORBA.TCorbaObject, Server_i.IMyTest)
private
FImplementation : IMyTest;
public
constructor Create(const InstanceName: string; const Impl: IMyTest);
destructor Destroy; override;
function GetImplementation : IMyTest;
function Get_X : Integer;
published
procedure _Get_X(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
TMyTestFactorySkeleton = class(CORBA.TCorbaObject, Server_i.MyTestFactory)
private
FImplementation : MyTestFactory;
public
constructor Create(const InstanceName: string; const Impl: MyTestFactory);
destructor Destroy; override;
function GetImplementation : MyTestFactory;
function CreateInstance ( const InstanceName : AnsiString): Server_i.IMyTest;
published
procedure _CreateInstance(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TIMyTestSkeleton.Create(const InstanceName : string; const Impl : Server_i.IMyTest);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'IMyTest', 'IDL:Server/IMyTest:1.0');
FImplementation := Impl;
end;
destructor TIMyTestSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TIMyTestSkeleton.GetImplementation : Server_i.IMyTest;
begin
result := FImplementation as Server_i.IMyTest;
end;
function TIMyTestSkeleton.Get_X : Integer;
begin
Result := FImplementation.Get_X;
end;
procedure TIMyTestSkeleton._Get_X(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Integer;
begin
_Result := Get_X;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteLong(_Result);
end;
constructor TMyTestFactorySkeleton.Create(const InstanceName : string; const Impl : Server_i.MyTestFactory);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'MyTestFactory', 'IDL:Server/MyTestFactory:1.0');
FImplementation := Impl;
end;
destructor TMyTestFactorySkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TMyTestFactorySkeleton.GetImplementation : Server_i.MyTestFactory;
begin
result := FImplementation as Server_i.MyTestFactory;
end;
function TMyTestFactorySkeleton.CreateInstance ( const InstanceName : AnsiString): Server_i.IMyTest;
begin
Result := FImplementation.CreateInstance( InstanceName);
end;
procedure TMyTestFactorySkeleton._CreateInstance(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_InstanceName : AnsiString;
_Result : Server_i.IMyTest;
begin
_Input.ReadString(_InstanceName);
_Result := CreateInstance( _InstanceName);
GetReplyBuffer(_Cookie, _Output);
Server_c.TIMyTestHelper.Write(_Output, _Result);
end;
initialization
end. |
unit FMX.ImageLayout;
interface
uses
System.Classes,
System.Types,
FMX.Graphics,
FMX.Types,
FMX.Controls,
FMX.Layouts,
FMX.MaterialSources,
FMX.InertialMovement;
type
{ TODO -cTImageLayout : DoubleTap Gesture isn't recognized by FMX }
{ TODO -cTImageLayout : Implement Zoom Gesture "Direction", that is, zoom to the point where
the gesture is located }
{$SCOPEDENUMS ON}
/// <summary> Determines how to calculate the ImageScale property </summary>
TImageChangeAction = (
/// <summary> The ImageScale will be set to the best fit value. See TImageLayout.BestFit </summary>
RecalcBestFit,
/// <summary> The ScaleImage remains unchanged; if a new image is set, the current ImageScale is applied </summary>
PreserveImageScale
);
/// <summary> Determines what type of event fired the TImageChangeEvent event handler </summary>
TImageChangeReason = (
/// <summary> The TImageLayout was resized, for example, when the Parent size changes </summary>
LayoutResized,
/// <summary> The Image property changed </summary>
ImageChanged
);
{$SCOPEDENUMS OFF}
/// <summary> Fired when the Image changes. Allows to set how to calculate the ImageScale property </summary>
TImageChangeEvent = procedure(Sender: TObject; const Reason: TImageChangeReason; var Action: TImageChangeAction) of object;
{$REGION 'TCustomImageLayout'}
/// <summary> Layout that displays an Image and implements Zoom and Pan Gestures </summary>
TCustomImageLayout = class(TControl)
private const
AbsoluteMinScale = 0.01;
AbsoluteMaxScale = 20.0;
private
FScrollBox: TScrollBox;
FImageSource: TTextureMaterialSource;
FImageSurface: TLayout;
FImageOriginalSize: TPointF;
FImageScale: Single;
FImageOriginalScale: Single;
FZoomStartDistance: Integer;
FMouseWheelZoom: Boolean;
FOnImageChanged: TImageChangeEvent;
FBounceAnimationDisableCount: Integer;
FBounceAnimationPropertyValue: Boolean;
FIsZooming: Boolean;
function GetAnimateDecelerationRate: Boolean;
function GetAutoHideScrollbars: Boolean;
function GetBounceAnimation: Boolean;
function GetBounceElasticity: Double;
function GetImage: TBitmap;
function GetAniCalculations: TAniCalculations;
function GetIsZoomed: Boolean;
procedure SetAnimateDecelerationRate(const Value: Boolean);
procedure SetAutoHideScrollbars(const Value: Boolean);
procedure SetBounceAnimation(const Value: Boolean);
procedure SetBounceElasticity(const Value: Double);
procedure SetImage(const Value: TBitmap);
procedure SetImageScale(const Value: Single);
procedure SetMouseWheelZoom(const Value: Boolean);
procedure SetOnImageChanged(const Value: TImageChangeEvent);
procedure InitImageSurface;
procedure InitScrollBox;
procedure InitInertialMovement;
procedure ImageChanged(Sender: TObject);
procedure ImageSurfacePainting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
/// <summary> Disables ScrollBox touch tracking </summary>
procedure DisableTouchTracking;
/// <summary> Enables ScrollBox touch tracking </summary>
procedure EnableTouchTracking;
/// <summary> Enables/Disables TouchTracking if appropiate </summary>
/// <remarks> TouchTracking is disabled if a Zoom Gesture is in process or if the image fits in the
/// layout, in which case the scrolling is not necessary </remarks>
procedure SetTouchTrackingToAppropiate;
protected const
DefaultMouseWheelZoom = True;
DefaultAnimateDecelerationRate = True;
DefaultAutoHideScrollbars = True;
DefaultBounceAnimation = True;
DefaultBounceElasticity = 100;
DefaultImageScale = 1.0;
protected
/// <summary> DisableBounceAnimation and RestoreBounceAnimation are similar to BeginUpdate and EndUpdate,
/// but the operate on the BounceAnimation property. There moments when the scaling of the image, like while
/// doing a zoom gesture or mouse wheeling, that the BounceAnimation better remains disabled </summary>
procedure DisableBounceAnimation;
/// <summary> DisableBounceAnimation and RestoreBounceAnimation are similar to BeginUpdate and EndUpdate,
/// but the operate on the BounceAnimation property. There moments when the scaling of the image, like while
/// doing a zoom gesture or mouse wheeling, that the BounceAnimation better remains disabled </summary>
/// <summary> A call RestoreBounceAnimation restores the BounceAnimation property Value if every call
/// to DisableBounceAnimation was paired with a call to RestoreBounceAnimation </summary>
procedure RestoreBounceAnimation;
procedure Loaded; override;
procedure Paint; override;
procedure Resize; override;
procedure MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean); override;
procedure DoGesture(const EventInfo: TGestureEventInfo; var Handled: Boolean); override;
procedure Change(const Reason: TImageChangeReason); virtual;
procedure HandleZoom(const EventInfo: TGestureEventInfo; var Handled: Boolean); virtual;
procedure HandleDoubleTap(const EventInfo: TGestureEventInfo; var Handled: Boolean); virtual;
/// <summary> Container for the TBitmap we're drawing </summary>
property ImageSource: TTextureMaterialSource read FImageSource;
/// <summary> Layout where the Image is drawn </summary>
property ImageSurface: TLayout read FImageSurface;
/// <summary> Scrollbox that handles the Panning Gesture </summary>
property ScrollBox: TScrollBox read FScrollBox;
/// <summary> AniCalculations from ScrollBox component </summary>
property AniCalculations: TAniCalculations read GetAniCalculations;
/// <summary> The last stored TGestureEventInfo.Distance on a Zoom Gesture Event </summary>
property PriorZoomDistance: Integer read FZoomStartDistance write FZoomStartDistance;
/// <summary> The Size of the Image without any scaling applied </summary>
property ImageOriginalSize: TPointF read FImageOriginalSize;
public
constructor Create(AOwner: TComponent); override;
/// <summary> Calculates the most appropiate ImageScale value </summary>
procedure BestFit;
/// <summary> Removes the Image and displays an empty Layout </summary>
procedure ClearImage;
/// <summary> Returns True if a Zooming Gesture is in process; False otherwise </summary>
property IsZooming: Boolean read FIsZooming;
/// <summary> Returns True if the Image has been zoomed in or out; False otherwise </summary>
property IsZoomed: Boolean read GetIsZoomed;
/// <summary> Determines whether the mouse scroll should trigger a Zoom Gesture Event </summary>
/// <remarks> Only works on Desktop </remarks>
property MouseWheelZoom: Boolean read FMouseWheelZoom write SetMouseWheelZoom;
/// <summary> Specifies whether the inertial movement shoud take into account the DecelerationRate </summary>
property AnimateDecelerationRate: Boolean read GetAnimateDecelerationRate write SetAnimateDecelerationRate;
/// <summary> Hides scrollbars when inertial is stopped; Shows them when it starts, and when it ends,
/// gradually hide them </summary>
property AutoHideScrollbars: Boolean read GetAutoHideScrollbars write SetAutoHideScrollbars;
/// <summary> Determines whether a corner of the scrolling viewport can be dragged inside the visible area </summary>
property BounceAnimation: Boolean read GetBounceAnimation write SetBounceAnimation;
/// <summary> Velocity of the BounceAnimation </summary>
property BounceElasticity: Double read GetBounceElasticity write SetBounceElasticity;
/// <summary> The Image displayed by the control </summary>
property Image: TBitmap read GetImage write SetImage;
/// <summary> Scale applied to the image; the higher the value, more zoom is applied to the image </summary>
property ImageScale: Single read FImageScale write SetImageScale;
/// <summary> Fired when the Image changes. Allows to set how to calculate the ImageScale property </summary>
property OnImageChanged: TImageChangeEvent read FOnImageChanged write SetOnImageChanged;
end;
{$ENDREGION}
{$REGION 'TImageLayout'}
TImageLayout = class(TCustomImageLayout)
published
property Align;
property Visible;
property MouseWheelZoom;
property AnimateDecelerationRate;
property AutoHideScrollbars;
property BounceAnimation;
property BounceElasticity;
property Image;
property ImageScale;
property OnImageChanged;
end;
{$ENDREGION}
procedure Register;
implementation
uses
System.SysUtils,
System.UITypes,
System.Math;
{$REGION 'TCustomImageLayout'}
constructor TCustomImageLayout.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FImageSource := TTextureMaterialSource.Create(Self);
FBounceAnimationDisableCount := 0;
FBounceAnimationPropertyValue := False;
FIsZooming := False;
CanParentFocus := True;
HitTest := True;
MouseWheelZoom := DefaultMouseWheelZoom;
Touch.InteractiveGestures := [TInteractiveGesture.Zoom, TInteractiveGesture.Pan, TInteractiveGesture.DoubleTap];
InitScrollBox;
InitImageSurface;
InitInertialMovement;
SetAcceptsControls(False);
Image.OnChange := ImageChanged;
end;
procedure TCustomImageLayout.DisableBounceAnimation;
begin
if FBounceAnimationDisableCount = 0 then
FBounceAnimationPropertyValue := BounceAnimation;
Inc(FBounceAnimationDisableCount)
end;
procedure TCustomImageLayout.RestoreBounceAnimation;
begin
FBounceAnimationDisableCount := System.Math.Min(FBounceAnimationDisableCount - 1, 0);
if FBounceAnimationDisableCount = 0 then
BounceAnimation := FBounceAnimationPropertyValue;
end;
procedure TCustomImageLayout.Change(const Reason: TImageChangeReason);
var
ImageChangeAction: TImageChangeAction;
begin
ImageChangeAction := TImageChangeAction.RecalcBestFit;
if Assigned(FOnImageChanged) then
FOnImageChanged(Self, Reason, ImageChangeAction);
case ImageChangeAction of
TImageChangeAction.RecalcBestFit: BestFit;
TImageChangeAction.PreserveImageScale: Repaint;
end;
end;
procedure TCustomImageLayout.Paint;
begin
inherited Paint;
if (csDesigning in ComponentState) and not Locked then
DrawDesignBorder;
end;
procedure TCustomImageLayout.Resize;
begin
inherited Resize;
ScrollBox.Size.Assign(Size);
Change(TImageChangeReason.LayoutResized);
end;
procedure TCustomImageLayout.Loaded;
begin
inherited Loaded;
BestFit;
end;
procedure TCustomImageLayout.MouseWheel(Shift: TShiftState; WheelDelta: Integer; var Handled: Boolean);
begin
if MouseWheelZoom then
begin
DisableBounceAnimation;
try
ImageScale := ImageScale + ((WheelDelta * ImageScale) / PointF(Width, Height).Length);
Handled := True;
finally
RestoreBounceAnimation;
end;
end
else
Handled := False;
end;
{$REGION 'Private fields initialization'}
procedure TCustomImageLayout.InitScrollBox;
begin
FScrollBox := TScrollBox.Create(Self);
ScrollBox.Parent := Self;
ScrollBox.ShowScrollBars := True;
ScrollBox.Align := TAlignLayout.Client;
ScrollBox.DisableMouseWheel := True;
ScrollBox.Locked := True;
ScrollBox.Stored := False;
ScrollBox.Touch.InteractiveGestures := [];
end;
procedure TCustomImageLayout.InitImageSurface;
begin
FImageSurface := TLayout.Create(Self);
ImageSurface.Parent := ScrollBox;
ImageSurface.Align := TAlignLayout.Center;
ImageSurface.Locked := True;
ImageSurface.Stored := False;
ImageSurface.HitTest := False;
ImageSurface.OnPainting := ImageSurfacePainting;
end;
procedure TCustomImageLayout.InitInertialMovement;
begin
AniCalculations.BeginUpdate;
try
AniCalculations.Averaging := True;
AnimateDecelerationRate:= DefaultAnimateDecelerationRate;
BounceAnimation := DefaultBounceAnimation;
AutoHideScrollbars := DefaultAutoHideScrollbars;
BounceElasticity := DefaultBounceElasticity;
DisableTouchTracking;
finally
AniCalculations.EndUpdate;
end;
end;
{$ENDREGION}
{$REGION 'Gesture handling'}
procedure TCustomImageLayout.DoGesture(const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
case EventInfo.GestureID of
igiZoom: HandleZoom(EventInfo, Handled);
igiDoubleTap: HandleDoubleTap(EventInfo, Handled);
else
inherited DoGesture(EventInfo, Handled);
end;
end;
procedure TCustomImageLayout.HandleZoom(const EventInfo: TGestureEventInfo; var Handled: Boolean);
var
S: Single;
begin
if TInteractiveGestureFlag.gfBegin in EventInfo.Flags then
begin
FIsZooming := True;
DisableBounceAnimation;
PriorZoomDistance := EventInfo.Distance;
Handled := True;
end;
if not((TInteractiveGestureFlag.gfBegin in EventInfo.Flags) or
(TInteractiveGestureFlag.gfEnd in EventInfo.Flags)) then
begin
S := ((EventInfo.Distance - PriorZoomDistance) * ImageScale) / (PointF(Width, Height).Length * 0.35);
PriorZoomDistance := EventInfo.Distance;
ImageScale := ImageScale + S;
Handled := True;
end;
if TInteractiveGestureFlag.gfEnd in EventInfo.Flags then
begin
FIsZooming := False;
RestoreBounceAnimation;
SetTouchTrackingToAppropiate;
Handled := True;
end;
end;
procedure TCustomImageLayout.HandleDoubleTap(const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
if IsZoomed then
ImageScale := FImageOriginalScale
else
ImageScale := ImageScale * 1.50;
end;
{$ENDREGION}
{$REGION 'Controls Callbacks'}
procedure TCustomImageLayout.ImageChanged(Sender: TObject);
begin
FImageOriginalSize := PointF(Image.Width, Image.Height);
if FImageOriginalSize.IsZero then
FImageOriginalSize := PointF(Width, Height);
Change(TImageChangeReason.ImageChanged);
end;
procedure TCustomImageLayout.ImageSurfacePainting(Sender: TObject; Canvas: TCanvas; const ARect: TRectF);
var
ImageRect: TRectF;
begin
ImageRect := RectF(0, 0, ImageOriginalSize.X, ImageOriginalSize.Y);
ImageSurface.Canvas.DrawBitmap(Image, ImageRect, ARect, 1);
end;
{$ENDREGION}
{$REGION 'Image Handling'}
procedure TCustomImageLayout.BestFit;
var
ScrollBoxRect, R: TRectF;
ImageScaleRatio: Single;
begin
ScrollBoxRect := ScrollBox.BoundsRect;
R := RectF(0, 0, FImageOriginalSize.X, FImageOriginalSize.Y);
try
R.FitInto(ScrollBoxRect, ImageScaleRatio);
FImageOriginalScale := 1 / ImageScaleRatio;
ImageScale := FImageOriginalScale;
except
on EInvalidOp do
ImageScale := 1;
end;
end;
procedure TCustomImageLayout.SetImageScale(const Value: Single);
var
PriorViewportPositionF, C: TPointF;
PriorImageScale, NewImageScale: Single;
begin
DisableBounceAnimation;
try
NewImageScale := Min(Max(Value, AbsoluteMinScale), AbsoluteMaxScale);
PriorImageScale := FImageScale;
FImageScale := NewImageScale;
if PriorImageScale <> 0 then
PriorImageScale := FImageScale / PriorImageScale
else
PriorImageScale := FImageScale;
C := PointF(ScrollBox.Width, ScrollBox.Height);
PriorViewportPositionF := AniCalculations.ViewportPositionF;
ImageSurface.Size.Size := PointF(ImageOriginalSize.X * FImageScale, ImageOriginalSize.Y * FImageScale);
PriorViewportPositionF := PriorViewportPositionF + (C * 0.5);
ScrollBox.Content.BeginUpdate;
try
ScrollBox.RealignContent;
AniCalculations.ViewportPositionF := (PriorViewportPositionF * PriorImageScale) - (C * 0.5);
finally
ScrollBox.Content.EndUpdate;
end;
SetTouchTrackingToAppropiate;
finally
RestoreBounceAnimation;
end;
end;
procedure TCustomImageLayout.ClearImage;
begin
Image.Clear(TAlphaColorRec.Null);
end;
{$ENDREGION}
{$REGION 'AniCalculations'}
procedure TCustomImageLayout.SetTouchTrackingToAppropiate;
begin
if IsZooming then
begin
DisableTouchTracking;
Exit;
end;
if (System.Math.CompareValue(ImageSurface.Size.Width, Width) = GreaterThanValue) or
(System.Math.CompareValue(ImageSurface.Size.Height, Height) = GreaterThanValue) then
EnableTouchTracking
else
DisableTouchTracking;
end;
procedure TCustomImageLayout.DisableTouchTracking;
begin
AniCalculations.TouchTracking := [];
end;
procedure TCustomImageLayout.EnableTouchTracking;
begin
AniCalculations.TouchTracking := [ttVertical, ttHorizontal];
end;
function TCustomImageLayout.GetAniCalculations: TAniCalculations;
begin
Result := ScrollBox.AniCalculations;
end;
function TCustomImageLayout.GetAnimateDecelerationRate: Boolean;
begin
Result := AniCalculations.Animation;
end;
function TCustomImageLayout.GetAutoHideScrollbars: Boolean;
begin
Result := AniCalculations.AutoShowing;
end;
function TCustomImageLayout.GetBounceAnimation: Boolean;
begin
Result := AniCalculations.BoundsAnimation;
end;
function TCustomImageLayout.GetBounceElasticity: Double;
begin
Result := AniCalculations.Elasticity;
end;
procedure TCustomImageLayout.SetAnimateDecelerationRate(const Value: Boolean);
begin
AniCalculations.Animation := Value;
end;
procedure TCustomImageLayout.SetAutoHideScrollbars(const Value: Boolean);
begin
AniCalculations.AutoShowing := Value;
end;
procedure TCustomImageLayout.SetBounceAnimation(const Value: Boolean);
begin
if FBounceAnimationDisableCount = 0 then
AniCalculations.BoundsAnimation := Value;
end;
procedure TCustomImageLayout.SetBounceElasticity(const Value: Double);
begin
AniCalculations.Elasticity := Value;
end;
{$ENDREGION}
procedure TCustomImageLayout.SetImage(const Value: TBitmap);
begin
ImageSource.Texture.Assign(Value);
end;
function TCustomImageLayout.GetImage: TBitmap;
begin
Result := ImageSource.Texture;
end;
function TCustomImageLayout.GetIsZoomed: Boolean;
begin
Result := not System.Math.SameValue(FImageOriginalScale, FImageScale);
end;
procedure TCustomImageLayout.SetMouseWheelZoom(const Value: Boolean);
begin
FMouseWheelZoom := Value;
end;
procedure TCustomImageLayout.SetOnImageChanged(const Value: TImageChangeEvent);
begin
FOnImageChanged := Value;
end;
{$ENDREGION}
procedure Register;
begin
RegisterComponents('Layouts', [TImageLayout]);
end;
end.
|
unit DelphiSkils;
interface
{$Region 'uses'}
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, JvExComCtrls, JvComCtrls,
Vcl.Clipbrd, Utilitarios, Data.DB, Data.Win.ADODB, ActiveX, Vcl.Grids, Vcl.DBGrids;
{$EndRegion}
type
TFormMain = class(TForm)
JvPageControl1: TJvPageControl;
TabSheet1: TTabSheet;
TabSheet2: TTabSheet;
Label1: TLabel;
TSConfigConect: TTabSheet;
EditServidor: TEdit;
EditUsuario: TEdit;
EditSenha: TEdit;
EditDataBase: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure JvPageControl1Change(Sender: TObject);
procedure EditConfiguraConexaoExit(Sender: TObject);
{$Region 'private'}
private
PassarSQLParaDelphiAtivo: Boolean;
InvocarRegionAtivo: Boolean;
IgualarDistanciamentoEntreOsIguaisAtivo, VerificarCamposDaTabelaAtivo: Boolean;
IdentarAtivo: Boolean;
DBGrid: TDBGrid;
procedure PassarSQLParaDelphi(ChamadaPeloTeclado: Boolean = False);
procedure PassarDelphiParaSQL(ChamadaPeloTeclado: Boolean = False);
procedure InvocarRegion;
procedure IgualarDistanciamentoEntreOsIguais;
procedure VerificarCamposDaTabela;
procedure Identar;
procedure VerificarProcedimentos;
{$EndRegion}
public
end;
var
FormMain: TFormMain;
implementation
uses HelpersPadrao;
{$R *.dfm}
procedure TFormMain.EditConfiguraConexaoExit(Sender: TObject);
var
CaminhoENomeArquivo, ExePath: String;
NovoArq: TStringList;
begin
ExePath := ExtractFilePath(Application.ExeName);
CaminhoENomeArquivo := ExePath + 'Config.ini';
NovoArq := TStringList.Create;
NovoArq.Add('Servidor : '+EditServidor.Text);
NovoArq.Add('Usuário : '+EditUsuario.Text);
NovoArq.Add('Senha : '+EditSenha.Text);
NovoArq.Add('LicencaDataBase : '+EditDataBase.Text);
NovoArq.Add('O Sistema só irá considerar as 4 primeiras linhas e somente o que estiver após o ":",');
NovoArq.Add('ele não ira considerar espaços adicionais a direita e esquerda.');
NovoArq.SaveToFile(CaminhoENomeArquivo);
NovoArq.Free;
end;
procedure TFormMain.FormCreate(Sender: TObject);
{$Region 'var ...'}
var
TimerTeclasPressionadas: TTimeOut;
Qry: TAdoQuery;
{$EndRegion}
begin
JvPageControl1.ActivePageIndex := 0;
PassarSQLParaDelphiAtivo := False;
InvocarRegionAtivo := False;
VerificarCamposDaTabelaAtivo := False;
{$Region 'Invocar Timer De Teclas Digitadas'}
TimerTeclasPressionadas :=
SetInterval(
Procedure
begin
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD0) or TeclaEstaPressionada(48)) then begin
Self.WindowState := wsNormal;
ShowWindow(Application.Handle, SW_SHOW);
Application.BringToFront;
end;
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD1) or TeclaEstaPressionada(49))
then PassarSQLParaDelphi(TRUE);
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD2) or TeclaEstaPressionada(50))
then PassarDelphiParaSQL(TRUE);
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD3) or TeclaEstaPressionada(51))
then InvocarRegion;
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD4) or TeclaEstaPressionada(52))
then IgualarDistanciamentoEntreOsIguais;
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD5) or TeclaEstaPressionada(53))
then VerificarCamposDaTabela;
if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD6) or TeclaEstaPressionada(54))
then VerificarProcedimentos;
// if (TeclaEstaPressionada(VK_RCONTROL) or TeclaEstaPressionada(VK_LCONTROL)) and (TeclaEstaPressionada(VK_NUMPAD7) or TeclaEstaPressionada(55))
// then Identar;
if (TeclaEstaPressionada(VK_LSHIFT) or TeclaEstaPressionada(VK_RSHIFT)) and TeclaEstaPressionada(VK_ESCAPE)
then Application.Terminate;
End,
10);
{$EndRegion}
end;
procedure TFormMain.Identar;
var
TextoFinal: string;
NroEspacos: Integer;
char_: char;
EncontrouEspaço: Boolean;
Texto: string;
EncontrouDuploPonto: Boolean;
I: Integer;
begin
{$Region 'Verificar se já está ativo'}
if IdentarAtivo
then Exit;
IdentarAtivo := True;
{$EndRegion}
{$Region 'Control + C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
{$Region 'Identando'}
TextoFinal := '';
NroEspacos := 0;
for char_ in Texto do begin
if (char_ = ' ')
then begin
EncontrouEspaço := True;
Inc(NroEspacos);
end
else
if (char_ = ':') and (not EncontrouDuploPonto)
then begin
EncontrouDuploPonto := True;
end
else
if (char_ = '=') and (EncontrouDuploPonto)
then begin
EncontrouDuploPonto := False;
EncontrouEspaço := False;
NroEspacos := 0;
TextoFinal := TextoFinal + ' :=';
end
else
if EncontrouEspaço
then begin
if EncontrouDuploPonto
then TextoFinal := TextoFinal + ':';
for I := 1 to NroEspacos
do TextoFinal := TextoFinal + ' ';
TextoFinal := TextoFinal + Char_;
NroEspacos := 0;
EncontrouEspaço := False;
end
else begin
EncontrouDuploPonto := False;
TextoFinal := TextoFinal + Char_;
end;
end;
Texto := TextoFinal;
{$EndRegion}
end;
procedure TFormMain.IgualarDistanciamentoEntreOsIguais;
begin
{$Region 'Verificar se já está ativo'}
if IgualarDistanciamentoEntreOsIguaisAtivo
then Exit;
IgualarDistanciamentoEntreOsIguaisAtivo := True;
{$EndRegion}
{$Region 'Control + C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
{$Region 'Transformar o texto e dar control V'}
SetTimeOut(
Procedure
var Texto, TextoFinal, TextoParcial: String;
QtdeMaxDeCaracteresAteODoisPontosIgual, CharCountDaLinha: integer;
Char_: Char;
I, DepoisDo13: Integer;
EncontrouDuploPonto: Boolean;
TextoParcialAteODuploPonto: String;
TextoParcialDepoisDoDuploPonto: String;
EncontrouOperadorIgualNaLinha: Boolean;
EncontrouEspaço: Boolean;
NroEspacos: Integer;
begin
Texto := Clipboard.AsText;
TextoFinal := '';
{$Region 'Igualar altura dos ":="'}
{$Region 'Remover espaços desnecessários'}
TextoFinal := '';
NroEspacos := 0;
for char_ in Texto do begin
if (char_ = ' ')
then begin
EncontrouEspaço := True;
Inc(NroEspacos);
end
else
if (char_ = ':') and (not EncontrouDuploPonto)
then begin
EncontrouDuploPonto := True;
end
else
if (char_ = '=') and (EncontrouDuploPonto)
then begin
EncontrouDuploPonto := False;
EncontrouEspaço := False;
NroEspacos := 0;
TextoFinal := TextoFinal + ' :=';
end
else
if EncontrouEspaço
then begin
if EncontrouDuploPonto
then TextoFinal := TextoFinal + ':';
for I := 1 to NroEspacos
do TextoFinal := TextoFinal + ' ';
TextoFinal := TextoFinal + Char_;
NroEspacos := 0;
EncontrouEspaço := False;
end
else begin
EncontrouDuploPonto := False;
TextoFinal := TextoFinal + Char_;
end;
end;
Texto := TextoFinal;
{$EndRegion}
CharCountDaLinha := 1;
QtdeMaxDeCaracteresAteODoisPontosIgual := 0;
{$Region 'Verificar quantos char possui o operador de receber mais afastado'}
for char_ in Texto do begin
if (char_ = #13)
then begin
CharCountDaLinha := 1;
EncontrouDuploPonto := False;
EncontrouOperadorIgualNaLinha := False;
end
else
if (char_ = ':') and (not EncontrouDuploPonto)
then begin
EncontrouDuploPonto := True;
end
else
if (char_ = '=') and (EncontrouDuploPonto) and (not EncontrouOperadorIgualNaLinha)
then begin
if CharCountDaLinha > QtdeMaxDeCaracteresAteODoisPontosIgual
then QtdeMaxDeCaracteresAteODoisPontosIgual := CharCountDaLinha;
CharCountDaLinha := CharCountDaLinha + 1;
EncontrouDuploPonto := False;
EncontrouOperadorIgualNaLinha := True;
end
else CharCountDaLinha := CharCountDaLinha + 1;
end;
{$EndRegion}
{$Region 'Igualando igual'}
EncontrouOperadorIgualNaLinha := False;
EncontrouDuploPonto := False;
Texto := Texto + #13;
TextoParcial := Texto;
TextoFinal := '';
for char_ in Texto do begin
if (char_ = #13)
then begin
if POS(#10, TextoParcial) > 1
then TextoFinal := TextoFinal + Copy(TextoParcial, 1, POS(#10, TextoParcial)) //Texto Final Recebe a linha
else TextoFinal := TextoFinal + Copy(TextoParcial, 1, POS(#13, TextoParcial)); //Texto Final Recebe a linha
if POS(#10, TextoParcial) > 1
then TextoParcial := Copy(TextoParcial, POS(#10, TextoParcial) + 1, length(TextoParcial))//Texto Parcial Remove a linha
else TextoParcial := Copy(TextoParcial, POS(#13, TextoParcial) + 1, length(TextoParcial));//Texto Parcial Remove a linha
EncontrouDuploPonto := False;
EncontrouOperadorIgualNaLinha := False;
end
else
if (char_ = ':') and (not EncontrouDuploPonto)
then begin
EncontrouDuploPonto := True;
end
else
if (char_ = '=') and (EncontrouDuploPonto) and (not EncontrouOperadorIgualNaLinha)
then begin
EncontrouDuploPonto := False;
EncontrouOperadorIgualNaLinha := True;
if pos('for', TextoParcial) = 0 then begin
TextoParcialAteODuploPonto := Copy(TextoParcial, 1, POS(':=', TextoParcial)-1);
TextoParcialDepoisDoDuploPonto := Copy(TextoParcial, POS(':=', TextoParcial)+2, Length(TextoParcial));
TextoParcial := TextoParcialAteODuploPonto;
for I := 1 to (QtdeMaxDeCaracteresAteODoisPontosIgual - length(TextoParcialAteODuploPonto) - 2)
do TextoParcial := TextoParcial + ' ';
TextoParcial := TextoParcial + ':=';
TextoParcial := TextoParcial + TextoParcialDepoisDoDuploPonto;
end
end
else EncontrouDuploPonto := False;
end;
{$EndRegion}
TextoFinal := Copy(TextoFinal,1,Length(TextoFinal)-1);
Texto := TextoFinal;
{$EndRegion}
ClipBoard.AsText := TextoFinal;
{$Region 'Control + V'}
SetTimeOut(
Procedure
begin
PressionarControlEManter;
PressionarTeclaV;
SoltarControl;
End,
100);
{$EndRegion}
End,
100);
{$EndRegion}
{$Region 'Setar TimeOut para reabilitar uso da funcionalidade'}
SetTimeOut(
Procedure
begin
IgualarDistanciamentoEntreOsIguaisAtivo := False;
End,
1000);
{$EndRegion}
end;
procedure TFormMain.InvocarRegion;
{$Region 'var ...'}
var Texto, TextoFinal, identamento : String;
EncontrouTexto: Boolean;
{$EndRegion}
begin
{$Region 'Verifica se essa funcionalidade já está ativa, ela não pode ser chamada várias vezes seguida'}
if InvocarRegionAtivo
then Exit;
InvocarRegionAtivo := True;
{$EndRegion}
{$Region 'Control C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
{$Region 'Coloca a region'}
SetTimeOut(
Procedure
var i : integer;
Char_ : Char;
begin
Texto := Clipboard.AsText;
TextoFinal := '';
for i := 1 to Length(Texto)-Length(Trim(Texto))-2
do identamento := identamento + ' ';
Texto := identamento + '{$Region ''Procedimentos''}'+FimLinhaStr
+ Texto+FimLinhaStr+
identamento + '{$EndRegion}';
EncontrouTexto := False;
for char_ in Texto do begin
if (char_ <> ' ') and not (EncontrouTexto)
then begin
TextoFinal := TextoFinal + ' ' + char_;
EncontrouTexto := True;
end
else
if char_ = #10
then begin
TextoFinal := TextoFinal + char_;
EncontrouTexto := False;
end
else TextoFinal := TextoFinal + char_;
end;
ClipBoard.AsText := TextoFinal;
SetTimeOut(
Procedure
begin
PressionarControlEManter;
PressionarTeclaV;
SoltarControl;
End,
100);
End,
100);
{$EndRegion}
{$Region 'Reabilita o uso da funcionalidade'}
SetTimeOut(
Procedure
begin
InvocarRegionAtivo := False;
End,
1000);
{$EndRegion}
end;
procedure TFormMain.JvPageControl1Change(Sender: TObject);
var
ExePath, Txt, CaminhoENomeArquivo: String;
arquivo: TStringList;
begin
if JvPageControl1.ActivePageIndex = 1 then begin
ExePath := ExtractFilePath(Application.ExeName);
arquivo := TStringList.Create;
CaminhoENomeArquivo := ExePath + 'Config.ini';
arquivo.LoadFromFile(CaminhoENomeArquivo);
Txt := arquivo.Strings[0];
EditServidor.Text := TRIM(Copy(Txt,POS(':',Txt)+1,Length(Txt) ));
Txt := arquivo.Strings[1];
EditUsuario.Text := TRIM(Copy(Txt,POS(':',Txt)+1,Length(Txt)));
Txt := arquivo.Strings[2];
EditSenha.Text := TRIM(Copy(Txt,POS(':',Txt)+1,Length(Txt)));
Txt := arquivo.Strings[3];
EditDataBase.Text := TRIM(Copy(Txt,POS(':',Txt)+1,Length(Txt)));
arquivo.Free;
end;
end;
procedure TFormMain.FormShow(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_HIDE);
SetWindowLong(Application.Handle, GWL_EXSTYLE, getWindowLong(Handle, GWL_EXSTYLE) or WS_EX_TOOLWINDOW);
ShowWindow(Application.Handle, SW_SHOW);
end;
procedure TFormMain.PassarSQLParaDelphi(ChamadaPeloTeclado: Boolean = False);
{$Region 'var ...'}
var
Linha, Linha_, Texto, Texto_: String;
char_: char;
{$EndRegion}
begin
{$Region 'Verifica se funcionalidade já não foi chamada para evitar reuso'}
if PassarSQLParaDelphiAtivo
then Exit;
PassarSQLParaDelphiAtivo := True;
{$EndRegion}
{$Region 'Control C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
{$Region 'Passa o SQL para Delphi'}
SetTimeOut(
Procedure
var char_: char;
begin
Texto := ClipBoard.AsText;
Texto_ := '''';
for char_ in Texto do begin
if char_ = ''''
then Texto_ := Texto_ + ''''''
else
if char_ = #13
then Texto_ := Texto_ + '''+FimLinhaStr+' + #13
else
if char_ = #10
then Texto_ := Texto_ + #10 + ''''
else Texto_ := Texto_ + char_;
end;
ClipBoard.AsText := Texto_ + '''+FimLinhaStr+' + #13;
SetTimeOut(
Procedure
begin
PressionarControlEManter;
PressionarTeclaV;
SoltarControl;
End,
100);
End,
100);
{$EndRegion}
{$Region 'Reabilita funcionalidade'}
SetTimeOut(
Procedure
begin
PassarSQLParaDelphiAtivo := False;
End,
1000);
{$EndRegion}
end;
procedure TFormMain.PassarDelphiParaSQL(ChamadaPeloTeclado: Boolean = False);
{$Region 'var ...'}
var
Linha, Linha_, Texto, TextoFinal: String;
char_: char;
consecutivo: Boolean;
Strings: TStrings;
{$EndRegion}
begin
{$Region 'Verificar se funcionalidade ja não foi chamada'}
if PassarSQLParaDelphiAtivo
then Exit;
PassarSQLParaDelphiAtivo := True;
{$EndRegion}
{$Region 'Control C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
{$Region 'Passa o delphi para SQL'}
SetTimeOut(
Procedure
var char_: char;
Linha_: String;
begin
Texto := Clipboard.AsText;
TextoFinal := '';
consecutivo := True;
for char_ in Texto do begin
if (char_ = '''') and (not Consecutivo)
then begin
TextoFinal := TextoFinal + '''';
consecutivo := True;
end
else
if (char_ = '''') and (Consecutivo)
then begin
consecutivo := False;
end
else
if char_ = #10
then begin
consecutivo := True;
end
else
if char_ = #13
then begin
TextoFinal := Copy(TRIM(TextoFinal),1,Length(TRIM(TextoFinal))-14) +FimLinhaStr;
consecutivo := false;
end
else begin
TextoFinal := TextoFinal + char_;
consecutivo := False;
end
end;
ClipBoard.AsText := TextoFinal;
SetTimeOut(
Procedure
begin
PressionarControlEManter;
PressionarTeclaV;
SoltarControl;
End,
100);
End,
100);
{$EndRegion}
{$Region 'Seta timer para reabilitar uso da funcionalidade'}
SetTimeOut(
Procedure
begin
PassarSQLParaDelphiAtivo := False;
End,
2000);
{$EndRegion}
end;
procedure TFormMain.VerificarProcedimentos;
var
Thread: TThread;
Texto: String;
Alias: TADOConnection;
Consultant: TADOQuery;
Form: TForm;
DS: TDataSource;
begin
{$Region 'Verificar se já está ativo'}
if VerificarCamposDaTabelaAtivo
then Exit;
VerificarCamposDaTabelaAtivo := True;
{$EndRegion}
{$Region 'Control + C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
SetTimeOut(
Procedure
Begin
Texto := Clipboard.AsText;
Thread := TThread.CreateAnonymousThread(
Procedure
Begin
TRY
{$Region 'Criar objeto de conexão com o banco e configura a conexão'}
Thread.Synchronize(Thread,
Procedure
Begin
Form := Tform.Create(Self);
Form.Width := 500;
Form.Height := 250;
Form.Show;
Form.BorderStyle := bsSizeable;
End);
coInitialize(nil);
Alias := TAdoConnection.Create(Form);
Alias.Attributes([]).CommandTimeout := 1;;
//Com xaCommitRetaining após commitar ele abre uma nova transação,
//Com xaAbortRetaining após abordar ele abre uma nova transação, custo muito alto.
//Se o comando demorar mais de 1 segundos ele aborta
Alias.Connected := False;
//A conexão deve vir inicialmente fechada
Alias.ConnectionTimeout := 15;
//Se demorar mais de 15 segundos para abrir a conexão ele aborta
Alias.CursorLocation := clUseServer;
//Toda informação ao ser alterada sem commitar vai ficar no servidor.
Alias.DefaultDatabase := '';
Alias.IsolationLevel := ilReadUncommitted;
//Quero saber os campos que ainda não foram commitados também
Alias.KeepConnection := True;
Alias.LoginPrompt := False;
Alias.Mode := cmRead;
//Somente leitura
Alias.Name := 'VerificarProcedimentosConnection';
Alias.Provider := 'SQLNCLI11.1';
Alias.Tag := 1;
//Para indicar que é usado em VerificarCamposDaTabela
ConfigurarConexao(Alias);
Alias.Connected := True;
{$EndRegion}
{$Region 'Realiza consulta e escreve dados na tela'}
Consultant := TAdoQuery.Create(Application);
with consultant do begin
Close;
Connection := Alias;
SQL.Text := 'SELECT '+FimLinhaStr+
'case type when ''P'' then ''Stored procedure'' '+FimLinhaStr+
'when ''FN'' then ''Function'' '+FimLinhaStr+
'when ''TF'' then ''Function'' '+FimLinhaStr+
'when ''TR'' then ''Trigger'' '+FimLinhaStr+
'when ''V'' then ''View'' '+FimLinhaStr+
'else ''Outros Objetos'' '+FimLinhaStr+
'end as Procedimento,'+FimLinhaStr+
'B.name Nome_Do_Procedimento, A.Text Conteudo '+FimLinhaStr+
'FROM syscomments A (nolock)'+FimLinhaStr+
'JOIN sysobjects B (nolock) on A.Id = B.Id'+FimLinhaStr+
'WHERE A.Text like ''%'+Texto+'%''';
DS := TDataSource.Create(Form);
DS.DataSet := Consultant;
Open;
Thread.Synchronize(Thread,
Procedure
Begin
DBGrid := TDBGrid.Create(Form);
with DBGrid do begin
Parent := Form;
Align := alClient;
Name := 'Grid';
Visible := True;
Left := 0;
Top := 0;
DataSource := DS;
Columns.Insert(0);
Columns[0].FieldName:='Procedimento';
Columns[0].Title.Caption:='Procedimento';
Columns[0].Title.Alignment := taCenter;
Columns[0].Title.Font.Style := [fsBold];
Columns[0].Width:=155;
Columns.Insert(1);
Columns[1].FieldName:='Nome_Do_Procedimento';
Columns[1].Title.Caption:='Nome';
Columns[1].Title.Alignment := taCenter;
Columns[1].Title.Font.Style := [fsBold];
Columns[1].Width:=200;
Columns.Insert(2);
Columns[2].FieldName:='Conteudo';
Columns[2].Title.Caption:='Conteudo';
Columns[2].Title.Alignment := taCenter;
Columns[2].Title.Font.Style := [fsBold];
Columns[2].Width:=65;
end;
Application.BringToFront;
End);
end;
{$EndRegion}
FINALLY
{$Region 'Setar TimeOut para reabilitar uso da funcionalidade'}
SetTimeOut(
Procedure
begin
VerificarCamposDaTabelaAtivo := False;
End,
1000);
{$EndRegion}
END;
End);
Thread.Start;
end,
100);
end;
procedure TFormMain.VerificarCamposDaTabela;
{$Region 'var ...'}
var
Texto: string;
{$EndRegion}
begin
{$Region 'Verificar se já está ativo'}
if VerificarCamposDaTabelaAtivo
then Exit;
VerificarCamposDaTabelaAtivo := True;
{$EndRegion}
{$Region 'Control + C'}
PressionarControlEManter;
PressionarTeclaC;
SoltarControl;
{$EndRegion}
{$Region 'Realiza consulta para trazer dados da tabela ou campo informado'}
SetTimeOut(
Procedure
{$Region 'Var ...'}
var Alias: TADOConnection;
Consultant: TADOQuery;
Canvas : TCanvas;
vHDC : HDC;
pt: TPoint;
X: Integer;
TamanhoMaxString: integer;
SELECT_: String;
TABELAOUCAMPOOUPROCEDIMENTOS: String;
Thread: TThread;
{$EndRegion}
begin
{$Region 'Cria Thread para realizar a consulta para caso ela for muito grande não fique aparente ao usuário(não usei os eventos da AdoQuery pois daria mais trabalho de vincular.'}
Thread := TThread.CreateAnonymousThread(
procedure
{$Region '...'}
label FimWith;
{$EndRegion}
begin
TRY
Texto := Clipboard.AsText;
{$Region 'Criar objeto de conexão com o banco e configura a conexão'}
CoInitialize(nil);
Alias := TAdoConnection.Create(Application);
Alias.Connected := False;
//A conexão deve vir inicialmente fechada
//Com xaCommitRetaining após commitar ele abre uma nova transação,
//Com xaAbortRetaining após abordar ele abre uma nova transação, custo muito alto.
Alias.Attributes([]).CommandTimeout := 1;
//Se o comando demorar mais de 1 segundos ele aborta
Alias.ConnectionTimeout := 15;
//Se demorar mais de 15 segundos para abrir a conexão ele aborta
Alias.CursorLocation := clUseServer;
//Toda informação ao ser alterada sem commitar vai ficar no servidor.
Alias.DefaultDatabase := '';
Alias.IsolationLevel := ilReadUncommitted;
//Quero saber os campos que ainda não foram commitados também
Alias.KeepConnection := True;
Alias.LoginPrompt := False;
Alias.Mode := cmRead;
//Somente leitura
Alias.Name := 'VerificarCamposDaTabelaConnection';
Alias.Provider := 'SQLNCLI11.1';
Alias.Tag := 1;
//Para indicar que é usado em VerificarCamposDaTabela
ConfigurarConexao(Alias);
Alias.Connected := True;
{$EndRegion}
{$Region 'Realiza consulta e escreve dados na tela'}
Consultant := TAdoQuery.Create(Application);
with consultant do begin
Close;
Connection := Alias;
TABELAOUCAMPOOUPROCEDIMENTOS := 'TABELA';
{$Region 'Montar SELECT'}
SELECT_ := 'Select'+FimLinhaStr+
'object_name(object_id) as Tabela,'+FimLinhaStr+
' sc.name as Campo,'+FimLinhaStr+
' st.name as Tipo,'+FimLinhaStr+
' sc.max_length as tamanho,'+FimLinhaStr+
' case sc.is_nullable when 0 then ''NÃO'' else ''SIM'' end as PermiteNulo'+FimLinhaStr+
'From'+FimLinhaStr+
' sys.columns sc'+FimLinhaStr+
'Inner Join'+FimLinhaStr+
' sys.types st On st.system_type_id = sc.system_type_id and st.user_type_id = sc.user_type_id'+FimLinhaStr+
'where sc.name like @pesquisaCampo and ( (object_name(object_id) = @pesquisaTabela) or (object_name(object_id) like (@pesquisaTabela+''_'')))'+FimLinhaStr+
'order by sc.is_nullable, sc.name';
{$EndRegion}
{$Region 'Colocar SELECT NA QUERY'}
SQL.Text := 'declare @pesquisaCampo varchar(100)'+FimLinhaStr+
'declare @pesquisaTabela varchar(100)'+FimLinhaStr+
'set @pesquisaCampo = ''%'''+FimLinhaStr+
'set @pesquisaTabela = '''+Texto+''''+FimLinhaStr+
''+FimLinhaStr+
SELECT_;
{$EndRegion}
Open;
{$Region 'Se não retornar nada, tentar fazer o mesmo considerando ele como campo ao invés de tabela'}
if IsEmpty then begin
TABELAOUCAMPOOUPROCEDIMENTOS := 'CAMPO';
SQL.Text := 'declare @pesquisaCampo varchar(100)'+FimLinhaStr+
'declare @pesquisaTabela varchar(100)'+FimLinhaStr+
'set @pesquisaTabela = ''%'''+FimLinhaStr+
'set @pesquisaCampo = '''+Texto+''''+FimLinhaStr+
''+FimLinhaStr+
SELECT_;
Open;
{$Region 'Se vazio ir ao fim do with'}
if IsEmpty then begin
goto FimWith;
//Atenção use goto com responsabilidade, ele aumenta a complexidade do código muito fácilmente,
//use o mínimo possível e de preferência simulando um break (indo para baixo);
end;
{$EndRegion}
end;
{$EndRegion}
{$Region 'Configura canvas'}
vHDC := GetDC(0);
Canvas := TCanvas.Create;
Canvas.Handle := vHDC;
Canvas.Pen.Color := ClRed;
Canvas.Brush.Color := ClRed;
GetCursorPos(pt);
{$EndRegion}
{$Region 'Ir ao primeiro registro retornado pela consulta'}
First;
{$EndRegion}
{$Region 'Localiza tamanho máximo das strings retornadas, para que com isso seja possivel definir o tamanho do retangulo'}
TamanhoMaxString := Length(FieldByName('Tabela').AsString);
while not eof do begin
if Length(FieldByName('Campo').AsString) > TamanhoMaxString
then TamanhoMaxString := Length(FieldByName('Campo').AsString);
Next;
end;
{$EndRegion}
{$Region 'Ir ao primeiro registro retornado pela consulta'}
First;
{$EndRegion}
{$Region 'Desenha o retangulo na tela'}
X := 1;
Canvas.Rectangle(Pt.x,Pt.y,Pt.x + ((TamanhoMaxString + 15) * 5), Pt.y + 10 + (52*RecordCount));
{$EndRegion}
{$Region 'Escreve dados das tabelas/campos na tela'}
{$Region 'Escreve dados sobre a Tabela ou Campo base da consulta'}
if TABELAOUCAMPOOUPROCEDIMENTOS = 'TABELA'
then Canvas.TextOut(Pt.x,Pt.y, 'TABELA: ' + FieldByName('Tabela').AsString)
else Canvas.TextOut(Pt.x,Pt.y, 'CAMPO: ' + FieldByName('Campo').AsString);
{$EndRegion}
while not eof do begin
{$Region 'Escreve os dados'}
if TABELAOUCAMPOOUPROCEDIMENTOS = 'TABELA'
then Canvas.TextOut(Pt.x,Pt.y + (13 * X), 'CAMPO: ' + FieldByName('Campo').AsString)
else Canvas.TextOut(Pt.x,Pt.y + (13 * X), 'TABELA: ' + FieldByName('Tabela').AsString);
Inc(X);
Canvas.TextOut(Pt.x,Pt.y + (13 * X), 'TIPO: ' + FieldByName('Tipo').AsString);
Inc(X);
Canvas.TextOut(Pt.x,Pt.y + (13 * X), 'TAMANHO: ' + FieldByName('tamanho').AsString);
Inc(X);
Canvas.TextOut(Pt.x,Pt.y + (13 * X), 'PERMITE NULO: ' + FieldByName('PermiteNulo').AsString);
INC(X);
{$EndRegion}
{$Region 'Vai ao próximo registro'}
Next;
{$EndRegion}
end;
{$EndRegion}
FimWith:
{$Region 'Libera objeto Query da memória'}
Free;
{$EndRegion}
end;
{$EndRegion}
{$Region 'Libera objeto de conexão da memória'}
Alias.Free;
{$EndRegion}
FINALLY
Thread.Synchronize(Thread,
procedure begin
{$Region 'Setar TimeOut para reabilitar uso da funcionalidade'}
SetTimeOut(
Procedure
begin
VerificarCamposDaTabelaAtivo := False;
End,
1000);
{$EndRegion}
end);
END;
end
);
Thread.Start;
{$EndRegion}
End,
100);
{$EndRegion}
end;
end.
|
unit ImportCSVCmd;
interface
procedure ImportCSV(tableName : string;
inputFile : string;
inputFileHasHeader : Boolean;
map : String;
operation : string; // append or overwrite
disableTriggers : Boolean;
dateFormat : string; // made up of yyyy, yy, mm, dd
trueValue : String; // the value that translates to TRUE in the CSV data. All else is false.
truncateStrings: Boolean;
databaseName : String;
userId, password : String;
hostName : String;
hostPort : Integer);
implementation
uses
Variants,
Classes,
SysUtils,
StrUtils,
DB,
Windows,
edbcomps,
SessionManager,
ConsoleHelper;
type
TStringArray = array of String;
Function ParseCSV( TempString : String;
// Field : Integer;
var StringArray : TStringArray;
delimStringField : String = '"'): String;
Var
Count : Integer;
Done : Boolean;
Data : String;
CH : Char;
Begin
Data := '';
TempString := Trim(TempString);
if Length(TempString) > 0 then
Begin
Count := 0;
// While (Count < Field) Do
while(TempString <> '') do
Begin
Data := '';
Inc(Count);
{ If First var is a " then the end deliminater will be a " }
if Length(TempString) > 0 then
Begin
SetLength(StringArray, Count);
if ((TempString[1] = delimStringField)) then
Begin
Delete(TempString,1,1);
Done := False;
Repeat
if (Length(TempString) > 0) then
Begin
CH := Char(TempString[1]);
While(CH <> delimStringField) do
Begin
Data := Data + TempString[1];
Delete(TempString,1,1);
CH := Char(TempString[1]);
end;
if ((TempString[1] = delimStringField)) then
Begin
if Length(TempString) > 2 then
Begin
if TempString[2] = ',' then
Begin
Delete(TempString,1,2);
Done := True
end
else
Begin
Data := Data + TempString[1];
Delete(TempString,1,1);
end;
end
else
Begin
Delete(TempString,1,1);
Done := True;
end;
end;
End
else
Done := True;
until Done;
end
else { Is A Number }
Begin
While((Length(TempString) > 0) and
(TempString[1] <> ',')) Do
Begin
Data := Data + TempString[1];
Delete(TempString,1,1);
end;
{ dump the , }
if Length(TempString) > 0 then
Delete(TempString,1,1);
end;
end;
TempString := Trim(TempString);
StringArray[Count - 1] := Data;
end;
end;
ParseCSV := Data;
end;
procedure ImportCSV(tableName : string;
inputFile : string;
inputFileHasHeader : Boolean;
map : String;
operation : string; // append or overwrite
disableTriggers : Boolean;
dateFormat : string; // made up of yyyy, yy, mm, dd
trueValue : String; // the value that translates to TRUE in the CSV data. All else is false.
truncateStrings: Boolean;
databaseName : String;
userId, password : String;
hostName : String;
hostPort : Integer);
type
TMap = record
fieldName : String;
CSVOffset : Integer;
MaxLength: Integer;
end;
var
sessionMgr : TSessionManager;
db : TEDBDatabase;
session : TEDBSession;
ds : TEDBQuery;
dsForTypes : TEDBQuery;
dqInsert : TEDBQuery;
dqFindEmail : TEDBQuery;
dqInsertEmail : TEDBQuery;
mappings : array of TMap;
fInput : TextFile;
lineCount : Integer;
errorCount : Integer;
csvLine : String;
iMap : Integer;
iMapMax:integer;
sql : String;
sCSVValue : String;
tStart : DWORD;
items : TStringArray;
iOffset, iMaxLen, iEmailOffset: Integer;
fieldName : String;
today : TDateTime;
procedure ParseMap(sMap : String);
var
sl : TStringList;
iMap: Integer;
slItem : TStringList;
begin
try
sl := TStringList.Create;
sl.Delimiter := ';';
sl.StrictDelimiter := true;
sl.DelimitedText := sMap;
except on E:Exception do
begin
writeln(E.Message);
Exit;
end;
end;
SetLength(mappings, sl.Count);
try
slItem := TStringList.Create;
slItem.Delimiter := '=';
slItem.StrictDelimiter := True;
except on E:Exception do
begin
writeln(E.Message);
Exit;
end;
end;
for iMap := 0 to sl.Count - 1 do
begin
slItem.DelimitedText := sl[iMap];
if slItem.Count = 2 then
begin
mappings[iMap].fieldName := slItem[0];
if not TryStrToInt(slItem[1], mappings[iMap].CSVOffset) then
raise Exception.CreateFmt('Invalid column offset in map: %s', [sl[iMap]]);
end
else
raise Exception.CreateFmt('Invalid map: %s', [sl[iMap]]);
end;
end;
procedure AddMaxLengths(tableName: String);
var
sessionMgr :TSessionManager;
dsForTypesLength : TEDBQuery;
i:integer;
sql:string;
begin
sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort);
for i:=0 to Length(mappings) -1 do
begin
if mappings[i].fieldName <> 'Email' then
begin
try
dsForTypesLength := TEDBQuery.Create(nil);
dsForTypesLength.SessionName := sessionMgr.session.SessionName;
dsForTypesLength.DatabaseName := db.Database;
sql:=Format('Select "Length" from information.tableColumns where tableName=''%s'' and Name=''%s''', [tableName,mappings[i].fieldName ]);
VerboseWrite(sql);
dsForTypesLength.SQL.Add(sql); // GetField Length
dsForTypesLength.ExecSQL;
mappings[i].MaxLength := -1;
while not dsForTypesLength.EOF do
begin
mappings[i].MaxLength := dsForTypesLength.FieldByName('Length').AsInteger;
dsForTypesLength.Next;
end;
finally
FreeAndNil(dsForTypesLength);
end;
end;
end;
end;
begin
operation := UpperCase(operation);
if (operation <> 'APPEND') and (operation <> 'OVERWRITE') then
raise Exception.CreateFmt('Invalid operation "%s". Only APPEND and OVERWRITE are valid', [operation]);
VerboseWrite('Operation: ' + operation);
//try session mgr start
sessionMgr := TSessionManager.Create(userId, password, hostName, hostPort);
db := TEDBDatabase.Create(nil);
//sessionmgr add lines
db.OnStatusMessage := sessionMgr.Status;
db.OnLogMessage := sessionMgr.Status;
db.SessionName := sessionMgr.session.Name;
db.Database := databaseName;
db.LoginPrompt := true;
db.DatabaseName := databaseName + DateTimeToStr(now);
dsForTypes := TEDBQuery.Create(nil);
dsForTypes.SessionName := sessionMgr.session.SessionName;
dsForTypes.DatabaseName := db.Database;
dsForTypes.SQL.Add(Format('Select * from "%s" Range 0 to 0', [tableName])); // hack to get field type defs.
dqInsert := TEDBQuery.Create(nil);
dqInsert.SessionName := sessionMgr.session.SessionName;
dqInsert.DatabaseName := db.Database;
dqFindEmail := TEDBQuery.Create(nil);
dqFindEmail.SessionName := sessionMgr.session.SessionName;
dqFindEmail.DatabaseName := db.Database;
dqInsertEmail := TEDBQuery.Create(nil);
dqInsertEmail.SessionName := sessionMgr.session.SessionName;
dqInsertEmail.DatabaseName := db.Database;
ds := TEDBQuery.Create(nil);
ds.SessionName := sessionMgr.session.SessionName;
ds.DatabaseName := db.Database;
dsForTypes.ExecSQL;
ParseMap(map);
AddMaxLengths(tableName);
if disableTriggers then
begin
sql := Format('Disable Triggers on "%s"', [tableName]);
VerboseWrite(sql);
ds.SQL.Add(sql);
ds.ExecSQL;
ds.SQL.Clear;
end;
try
// Delete ALL of the data.
if operation = 'OVERWRITE' then
begin
sql := Format('Empty Table "%s"', [tableName]);
VerboseWrite(sql);
ds.SQL.Add(sql);
ds.ExecSQL;
ds.SQL.Clear;
end;
iMapMax:= High(mappings);
// Create the prepared statement.
sql := Format('Insert Into "%s" (', [tableName]);
for iMap := Low(mappings) to iMapMax do
begin
sql := sql + mappings[iMap].fieldName;
if (iMap < iMapMax) then
sql := sql + ','
end;
sql := sql + ') Values (' + #13#10;
for iMap := Low(mappings) to iMapMax do
begin
sql := sql + ':' + mappings[iMap].fieldName;
if (iMap < iMapMax) then
sql := sql + ','
end;
sql := sql + ')' + #13#10;
VerboseWrite( sql);
dqInsert.SQL.Add(sql);
dqInsert.Prepare;
// Create the lookup for email
sql := 'Select ID from tblEmail Where emailAddress = :email';
dqFindEmail.SQL.Add(sql);
dqFindEmail.Prepare;
// Create the Insert for email
sql := 'Insert into tblEmail (ID, emailAddress, LastUpdatedBy, DateLastUpdated) Values(:ID, :email, ''SYS'', Current_Timestamp)';
dqInsertEmail.SQL.Add(sql);
dqInsertEmail.Prepare;
trueValue := LowerCase(trueValue); // standardize
AssignFile(fInput, inputFile);
Reset(fInput);
lineCount := 0;
errorCount := 0;
// Speed up loop a little by skipping the header if necessary.
if inputFileHasHeader and not Eof(fInput) then
begin
Readln(fInput, CSVLine);
Inc(lineCount);
end;
tStart := GetTickCount;
while not eof(fInput) do
begin
Readln(fInput, CSVLine);
Inc(lineCount);
VerboseWrite(Format('Line %d:', [lineCount]));
if (lineCount mod 1000 = 0) then
VerboseWrite('.');
try
sCSVValue := ParseCSV(csvLine, items);
for iMap := Low(mappings) to High(mappings) do
begin
iMaxLen := mappings[iMap].MaxLength;
iOffset := mappings[iMap].CSVOffset;
fieldName := mappings[iMap].fieldName;
sCSVValue := items[iOffset - 1];
VerboseWrite(Format('Field "%s": Column %d = %s', [fieldName, iOffset, sCSVValue]));
if (sCSVValue = '') and (not dsForTypes.FieldDefs.Find(fieldName).Required) then
dqInsert.ParamByName(fieldName).Value := null
else
begin
case dsForTypes.FieldByName(fieldName).DataType of
ftUnknown, ftString :
begin
if (Length(sCSVValue) > iMaxLen) and (truncateStrings) then
begin
dqInsert.ParamByName(fieldName).AsString := LeftStr(sCSVValue, iMaxLen);
VerboseWrite(Format('Truncated String: %s ',[sCSVValue]));
end
else
dqInsert.ParamByName(fieldName).AsString := sCSVValue;
end;
ftSmallint, ftInteger, ftWord, ftLargeint :
begin
dqInsert.ParamByName(fieldName).AsInteger := StrToInt(sCSVValue);
end;
ftBoolean : dqInsert.ParamByName(fieldName).Value := LowerCase(sCSVValue) = trueValue;
ftFloat : dqInsert.ParamByName(fieldName).AsFloat := StrToFloat(sCSVValue);
ftCurrency : dqInsert.ParamByName(fieldName).AsCurrency := StrToCurr(sCSVValue);
ftDate : dqInsert.ParamByName(fieldName).AsDate := StrToDate(sCSVValue);
ftTime : dqInsert.ParamByName(fieldName).AsDate := StrToTime(sCSVValue);
ftDateTime : dqInsert.ParamByName(fieldName).AsDate := StrToDateTime(sCSVValue);
else
if (dqInsert.ParamByName(fieldName).Size < Length(sCSVValue)) and (truncateStrings =true) then
begin
dqInsert.ParamByName(fieldName).AsString := LeftStr(sCSVValue, dqInsert.ParamByName(fieldName).Size );
WriteLn(Format('Truncated String: [%s] ',[sCSVValue]));
end
else
dqInsert.ParamByName(fieldName).AsString := sCSVValue;
end;
end;
end;
except
on e : Exception do
begin
WritelnError(Format('Exception at line %d. %s', [lineCount, e.Message]));
exit;
end;
end;
try
dqInsert.ExecSQL;
except
on e : Exception do
begin
Inc(ErrorCount);
WritelnError(Format('Exception importing line %d. %s', [lineCount, e.Message]));
if ErrorCount > 1000 then
raise Exception.Create('Too many exceptions');
end;
end;
end;
Writeln;
Writeln(Format('Done importing. %d seconds. %d lines processed. %d errors.', [(GetTickCount() - tStart) div 1000, lineCount, errorCount]));
finally
// Turn triggers on if we can.
if disableTriggers then
begin
sql := Format('Enable Triggers on "%s"', [tableName]);
ds.SQL.Add(sql);
ds.ExecSQL;
ds.SQL.Clear;
end;
end;
FreeAndNil(ds);
FreeAndNil(dqInsert);
FreeAndNil(dqFindEmail);
FreeAndNil(dqInsertEmail);
FreeAndNil(db);
end;
end.
|
{(*}
(*------------------------------------------------------------------------------
Delphi Code formatter source code
The Original Code is frBlankLines.pas, released Nov 2003.
The Initial Developer of the Original Code is Anthony Steele.
Portions created by Anthony Steele are Copyright (C) 1999-2008 Anthony Steele.
All Rights Reserved.
Contributor(s): Anthony Steele.
The contents of this file are subject to the Mozilla Public License Version 1.1
(the "License"). you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.mozilla.org/NPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied.
See the License for the specific language governing rights and limitations
under the License.
Alternatively, the contents of this file may be used under the terms of
the GNU General Public License Version 2 or later (the "GPL")
See http://www.gnu.org/licenses/gpl.html
------------------------------------------------------------------------------*)
{*)}
unit frBlankLines;
{$I JcfGlobal.inc}
interface
uses
{ delphi }
Classes, Controls, Forms,
StdCtrls,
{ JVCL }
JvEdit, JvExStdCtrls, JvValidateEdit,
{ local}
frmBaseSettingsFrame;
type
TfBlankLines = class(TfrSettingsFrame)
Label1: TLabel;
eNumReturnsAfterFinalEnd: TJvValidateEdit;
cbRemoveConsecutiveBlankLines: TCheckBox;
edtMaxConsecutiveBlankLines: TJvValidateEdit;
Label2: TLabel;
gbRemoveBlankLines: TGroupBox;
cbRemoveBlockBlankLines: TCheckBox;
cbRemoveBlankLinesAfterProcHeader: TCheckBox;
cbRemoveVarBlankLines: TCheckBox;
edtLinesBeforeProcedure: TJvValidateEdit;
Label3: TLabel;
Label4: TLabel;
edtMaxBlankLinesInSection: TJvValidateEdit;
private
public
constructor Create(AOwner: TComponent); override;
procedure Read; override;
procedure Write; override;
end;
implementation
{$ifdef FPC}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
uses
{ delphi }
Math,
{ local }
JcfSettings, SetReturns, JcfHelp;
constructor TfBlankLines.Create(AOwner: TComponent);
begin
inherited;
fiHelpContext := HELP_CLARIFY_BLANK_LINES;
end;
procedure TfBlankLines.Read;
begin
with JcfFormatSettings.Returns do
begin
cbRemoveVarBlankLines.Checked := RemoveVarBlankLines;
cbRemoveBlankLinesAfterProcHeader.Checked := RemoveProcHeaderBlankLines;
cbRemoveBlockBlankLines.Checked := RemoveBlockBlankLines;
eNumReturnsAfterFinalEnd.Value := NumReturnsAfterFinalEnd;
cbRemoveConsecutiveBlankLines.Checked := RemoveConsecutiveBlankLines;
edtMaxConsecutiveBlankLines.Value := MaxConsecutiveBlankLines;
edtMaxBlankLinesInSection.Value := MaxBlankLinesInSection;
edtLinesBeforeProcedure.Value := LinesBeforeProcedure;
end;
end;
procedure TfBlankLines.Write;
begin
with JcfFormatSettings.Returns do
begin
RemoveVarBlankLines := cbRemoveVarBlankLines.Checked;
RemoveProcHeaderBlankLines := cbRemoveBlankLinesAfterProcHeader.Checked;
RemoveBlockBlankLines := cbRemoveBlockBlankLines.Checked;
NumReturnsAfterFinalEnd := eNumReturnsAfterFinalEnd.Value;
RemoveConsecutiveBlankLines := cbRemoveConsecutiveBlankLines.Checked;
// this value is always at least 2
MaxConsecutiveBlankLines := Max(edtMaxConsecutiveBlankLines.Value, 2);
MaxBlankLinesInSection := edtMaxBlankLinesInSection.Value;
LinesBeforeProcedure := edtLinesBeforeProcedure.Value;
end;
end;
end.
|
unit ReadingForm;
interface
uses
TestClasses,
ReadingSQLUnit,
QuestionABCDInputFrame,
ExampleFrame,
QuestionSelectFrame,
ButtonsFrame,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls, DSPack, Buttons, Generics.Collections;
type
TfrReading = class(TForm)
Panel4: TPanel;
PanelLeftInTop: TPanel;
lbCategory: TLabel;
cbExamCategory: TComboBox;
frmQuestionABCDInput: TfrmQuestionABCDInput;
frmQuestionSelect: TfrmQuestionSelect;
FrmButtons: TFrmButtons;
PanelExam: TPanel;
btExamInsert: TButton;
btExamModify: TButton;
btExamDelete: TButton;
btExamAdd: TButton;
Panel1: TPanel;
lbExample: TLabel;
MemoExample: TMemo;
edNumber: TLabeledEdit;
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btExamAddClick(Sender: TObject);
procedure cbExamCategorySelect(Sender: TObject);
procedure btExamInsertClick(Sender: TObject);
procedure btExamModifyClick(Sender: TObject);
procedure btExamDeleteClick(Sender: TObject);
procedure frmQuestionSelectcbNumberSelectSelect(Sender: TObject);
procedure frmButtonsbtQueAddClick(Sender: TObject);
procedure frmButtonsbtModifyClick(Sender: TObject);
procedure frmButtonsbtDeleteClick(Sender: TObject);
procedure frmButtonsbtInsertClick(Sender: TObject);
private
FTest: TTest;
FReadingData: TObjectList<TReading>;
FReadingSQL: TReadingSQL;
FQuizIndex: Integer;
FExampleIndex: Integer;
procedure Initialize(CategoryIndex: Integer);
procedure ExamInsertOn;
procedure ExamAddOn;
procedure AllClear;
procedure NextExampleSetting;
procedure NextQuestionSetting;
procedure On_QuestionAdd(Sender: TObject);
procedure On_QuestionSelect(Sender: TObject);
procedure On_QuestionInsert(var IsNull: Boolean);
procedure On_QuestionUpdate(var IsNull: Boolean);
procedure On_QuestionDelete(var IsNull: Boolean);
public
procedure SetReadingIndex(Test: TTest);
end;
var
frReading: TfrReading;
implementation
{$R *.dfm}
// 초기 파일 입력
procedure TfrReading.SetReadingIndex(Test: TTest);
begin
FTest:= Test;
Initialize(0);
ExamAddOn;
end;
// 모든 컨트롤 Clear
procedure TfrReading.AllClear;
begin
MemoExample.Clear;
edNumber.Clear;
frmQuestionABCDInput.ClearInput;
frmQuestionSelect.cbNumberSelect.Clear;
cbExamCategory.Clear;
end;
// 지문추가 클릭
procedure TfrReading.btExamAddClick(Sender: TObject);
begin
if FTest.Idx = 0 then
begin
ShowMessage('좌측메뉴를 먼저 선택해 주세요');
exit;
end;
NextExampleSetting;
end;
// 지문삭제 클릭
procedure TfrReading.btExamDeleteClick(Sender: TObject);
begin
if (edNumber.Text = '') or (MemoExample.Text = '') then Exit;
if MessageDlg('지문에 포함된 문제도 모두 삭제 됩니다. 정말 삭제하시겠습니까?',
mtWarning, mbYesNo,0)= mrYes then
begin
FReadingSQL.ReadingTextDelete(FTest.Idx, StrToInt(cbExamCategory.Text));
Initialize(0);
end;
end;
// 지문입력 클릭
procedure TfrReading.btExamInsertClick(Sender: TObject);
var
InsertReading : TReading;
begin
if (edNumber.Text = '') or (MemoExample.Text = '') then
begin
ShowMessage('입력 정보가 부족합니다');
exit;
end;
InsertReading := TReading.Create;
try
InsertReading.TestIdx := FTest.Idx;
InsertReading.ExampleNumber := StrToInt(edNumber.Text);
InsertReading.ExampleText := MemoExample.Text;
FReadingSQL.ReadingTextInsert(InsertReading, FTest.Idx);
finally
InsertReading.Free;
end;
NextExampleSetting;
end;
// 지문수정 클릭
procedure TfrReading.btExamModifyClick(Sender: TObject);
var
UpdateText : TReading;
begin
if (edNumber.Text = '') or (MemoExample.Text = '') then Exit;
if messagedlg('정말 수정하시겠습니까?', mtWarning, mbYesNo,0)= mryes then
begin
UpdateText := TReading.Create;
try
UpdateText.ExampleNumber := StrToInt(edNumber.Text);
UpdateText.ExampleText := MemoExample.Text;
FReadingSQL.ReadingTextUpdate(UpdateText, FTest.Idx);
finally
UpdateText.Free;
end;
Initialize(0);
end;
end;
// 카테고리 선택시
procedure TfrReading.cbExamCategorySelect(Sender: TObject);
var
I: Integer;
Reading: TReading;
ComboBox: TComboBox; // absolute Sender;
begin
ExamAddOn;
ComboBox := TComboBox(Sender);
if ComboBox.ItemIndex > -1 then
begin
Reading := ComboBox.Items.Objects[ComboBox.ItemIndex] as TReading;
FExampleIndex := Reading.ExampleIdx;
edNumber.Text := IntToStr(Reading.ExampleNumber);
MemoExample.Text := Reading.ExampleText;
frmQuestionSelect.NumberListing(Reading.QuizList);
end;
if frmQuestionSelect.cbNumberSelect.Text = '' then
frmQuestionABCDInput.ClearInput;
end;
// Example 입력 모드로 버튼 변경
procedure TfrReading.ExamInsertOn;
begin
btExamInsert.Visible := True;
btExamAdd.Visible := False;
btExamModify.Visible := False;
btExamDelete.Visible := False;
end;
// Example 추가 모드로 버튼 변경
procedure TfrReading.ExamAddOn;
begin
btExamInsert.Visible := False;
btExamAdd.Visible := True;
btExamModify.Visible := True;
btExamDelete.Visible := True;
end;
// Reading Form 생성
procedure TfrReading.FormCreate(Sender: TObject);
begin
frmQuestionSelect.OnQuestionSelect := On_QuestionSelect;
frmQuestionSelect.OnQuestionSelect := On_QuestionSelect;
frmButtons.OnUpdate := On_QuestionUpdate;
frmButtons.OnInsert := On_QuestionInsert;
frmButtons.OnDelete := On_QuestionDelete;
frmButtons.OnNewQuestion := On_QuestionAdd;
FReadingSQL := TReadingSQL.Create;
end;
// Reading Form 소멸
procedure TfrReading.FormDestroy(Sender: TObject);
begin
FReadingData.Free;
FReadingSQL.Free;
end;
procedure TfrReading.frmButtonsbtDeleteClick(Sender: TObject);
begin
frmButtons.btDeleteClick(Sender);
end;
procedure TfrReading.frmButtonsbtInsertClick(Sender: TObject);
begin
frmButtons.btInsertClick(Sender);
end;
procedure TfrReading.frmButtonsbtModifyClick(Sender: TObject);
begin
frmButtons.btModifyClick(Sender);
end;
procedure TfrReading.frmButtonsbtQueAddClick(Sender: TObject);
begin
frmButtons.btQueAddClick(Sender);
end;
procedure TfrReading.frmQuestionSelectcbNumberSelectSelect(Sender: TObject);
begin
frmQuestionSelect.cbNumberSelectSelect(Sender);
end;
// Reading Form Defult 값 지정
procedure TfrReading.Initialize(CategoryIndex: Integer);
var
I: Integer;
Reading: TReading;
begin
FreeAndNil(FReadingData);
FReadingData := FReadingSQL.ReadingTextSelect(FTest.Idx);
AllClear;
for I := 0 to FReadingData.Count - 1 do
cbExamCategory.Items.AddObject(IntToStr(FReadingData.Items[I].ExampleNumber), FReadingData.Items[I]);
cbExamCategory.ItemIndex := CategoryIndex;
frmQuestionABCDInput.cbAnswer.Text := '';
if FReadingData.Count > 0 then
begin
edNumber.Text := IntToStr(FReadingData.Items[CategoryIndex].ExampleNumber);
MemoExample.Text := FReadingData.Items[CategoryIndex].ExampleText;
frmQuestionSelect.NumberListing(FReadingData.Items[CategoryIndex].QuizList);
end;
end;
// 다음 지문 입력 셋팅
procedure TfrReading.NextExampleSetting;
begin
ExamInsertOn;
Initialize(0);
MemoExample.Clear;
frmQuestionABCDInput.ClearInput;
frmQuestionSelect.cbNumberSelect.Clear;
cbExamCategory.ItemIndex := -1;
if cbExamCategory.Items.Count > 0 then
begin
edNumber.Text :=
IntToStr(StrToInt(cbExamCategory.Items[cbExamCategory.Items.Count - 1]) + 1);
end
else
begin
edNumber.Text := '1';
end;
end;
procedure TfrReading.NextQuestionSetting;
begin
frmQuestionABCDInput.ClearInput;
frmQuestionABCDInput.edNumber.Text := IntToStr(frmQuestionSelect.Numbering + 1 );
FrmButtons.InsertOn;
frmQuestionSelect.cbNumberSelect.ItemIndex := -1;
end;
procedure TfrReading.on_QuestionSelect(Sender: TObject);
begin
frmButtons.QueAddOn;
frmQuestionABCDInput.Binding(TLRQuiz(Sender));
FQuizIndex := TLRQuiz(Sender).QuizIdx;
end;
procedure TfrReading.On_QuestionUpdate(var IsNull: Boolean);
var
ModifyReading : TLRQuiz;
Idx : Integer;
Temp : Integer;
begin
IsNull := frmQuestionABCDInput.IsNull;
if IsNull then
exit;
if messagedlg('정말 수정하시겠습니까?', mtWarning, mbYesNo,0)= mryes then
begin
ModifyReading := frmQuestionABCDInput.GetReadingData;
try
FReadingSQL.ReadingQuestionUpdate(ModifyReading, FQuizIndex);
finally
ModifyReading.Free;
end;
Initialize(cbExamCategory.ItemIndex);
end;
end;
procedure TfrReading.On_QuestionAdd(Sender: TObject);
begin
if FTest.Idx = 0 then
begin
ShowMessage('좌측메뉴를 먼저 선택해 주세요');
exit;
end;
NextQuestionSetting;
end;
procedure TfrReading.On_QuestionDelete(var IsNull: Boolean);
var
DeleteReading : TLRQuiz;
Temp : Integer;
begin
IsNull := frmQuestionABCDInput.IsNull;
if IsNull then
exit;
if MessageDlg('정말 삭제하시겠습니까?', mtWarning, mbYesNo,0)= mrYes then
begin
DeleteReading := frmQuestionABCDInput.GetReadingData;
try
FReadingSQL.ReadingQuestionDelete(FQuizIndex);
finally
DeleteReading.Free;
end;
Initialize(cbExamCategory.ItemIndex);
end;
end;
procedure TfrReading.On_QuestionInsert(var IsNull: Boolean);
var
InsertReading: TLRQuiz;
begin
IsNull := frmQuestionABCDInput.IsNull;
if IsNull then
exit;
InsertReading := frmQuestionABCDInput.GetReadingData;
try
FReadingSQL.ReadingQuestionInsert(InsertReading, FExampleIndex);
finally
InsertReading.Free;
end;
Initialize(cbExamCategory.ItemIndex);
NextQuestionSetting;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ XML Data Binding Code Generation }
{ }
{ Copyright (c) 2001 Borland Software Corp. }
{ }
{*******************************************************}
unit XMLBindGen;
interface
uses
SysUtils, Classes, Variants, XMLSchema, XMLDoc, XMLIntf, xmldom;
const { Do not localize anything in this unit. }
{ AppInfo }
aiDBWizPrefix = 'xdb';
aiIdentifierName = 'identifierName';
aiDataType = 'dataType';
aiBound = 'bound';
aiReadOnly = 'ReadOnly';
aiRepeated = 'repeated';
aiDocElement = 'docElement';
{ Code }
SIndex = 'Index';
SInteger = 'Integer';
SIndexCode = SIndex + ': ' + SInteger;
SBegin = 'begin';
SEnd = 'end;';
SAdd = 'Add';
SInsert = 'Insert';
SOverride = ' override;';
SPrivate = 'private';
SProtected = 'protected';
SPublic = 'public';
SPublished = 'published';
STrue = 'True';
SFalse = 'False';
{ Option Categories }
SCodeGen = 'CodeGen';
SDataTypeMap = 'DataTypeMap';
{ Code Gen Options }
cgPropGetPrefix = 'PropGetPrefix';
cgPropSetPrefix = 'PropSetPrefix';
cgClassPrefix = 'ClassPrefix';
cgInterfacePrefix = 'IntfPrefix';
cgListTypeSuffix = 'NodeListSuffix';
cgNodeIntfBase = 'NodeIntfBase';
cgNodeClassBase = 'NodeClassBase';
cgCollIntfBase = 'CollIntfBase';
cgCollClassBase = 'CollClassBase';
cgDefaultDataType = 'DefDataType';
NativeTypes: array[0..20] of string = ('string','Variant','WideString',
'Boolean','Integer','Double','Char','WideChar','Shortint','Smallint',
'Byte','Word','Extended','Longint','Cardinal','Single','Extended','Comp',
'Currency','TDateTime','Int64');
resourcestring
{ Comments }
SPropertyAccessors = ' { Property Accessors }';
SMethodsAndProps = ' { Methods & Properties }';
SForwardDecl = 'Forward Decls';
SGlobalFunctions = 'Global Functions';
type
TXMLBindingType = (btComplexType, btSimpleType, btComplexElement,
btCollectionElement, btSimpleElement, btAttribute, btComplexTypeList,
btSimpleTypeList, btNone);
TOptionChangeEvent = procedure(const SectionName, OptionName: string;
const Value: Variant) of object;
TBindingOptions = class(TPersistent)
private
FSectionName: string;
FOptions: TStringList;
FOnOptionChange: TOptionChangeEvent;
function GetOptionData(const Name: string): TObject;
procedure SetOptionData(const Name: string; const Value: TObject);
protected
procedure SetOption(const Name: string; const Value: Variant);
property SectionName: string read FSectionName;
procedure AssignTo(Dest: TPersistent); override;
procedure DoOptionChange(const OptionName: string; const Value: Variant);
public
constructor Create(const SectionName: string;
OnChangeEvent: TOptionChangeEvent = nil);
destructor Destroy; override;
procedure EnsureOption(const OptionStr: string);
function GetOptionValue(const Name: string): Variant;
function GetOption(const Name: string; const Default: Variant): Variant;
procedure InitializeOptions(const Values: array of string); overload;
procedure InitializeOptions(const Values: TStrings); overload;
function IsTrue(const Name: string): Boolean;
property Options[const Name: string]: Variant read GetOptionValue write SetOption; default;
property OptionData[const Name: string]: TObject read GetOptionData write SetOptionData;
procedure Assign(Source: TPersistent); override;
procedure Clear;
property OnOptionChange: TOptionChangeEvent read FOnOptionChange write FOnOptionChange;
end;
{ =========================================================================== }
{ Databinding Interfaces }
{ =========================================================================== }
{ IXMLBindingAppInfo }
{ This interface is used to persist data binding settings into an
AppInfo node of the source schema document. It is use by the
various IXMLBindingInfo interfaces defined below }
IXMLBindingAppInfo = interface(IXMLAppInfo)
['{3FF5455B-C787-4EA8-ADCF-AB0F66874D13}']
{ Property Accessors }
function GetBindingAppInfoURI: DOMString;
function GetBound: Variant;
function GetDataType: Variant;
function GetDocElement: Variant;
function GetIdentifierName: Variant;
function GetPropReadOnly: Variant;
function GetRepeated: Variant;
procedure SetBindingAppInfoURI(const Value: DOMString);
procedure SetBound(const Value: Variant);
procedure SetDataType(const Value: Variant);
procedure SetDocElement(const Value: Variant);
procedure SetIdentifierName(const Value: Variant);
procedure SetPropReadOnly(const Value: Variant);
procedure SetRepeated(const Value: Variant);
{ Public Properties & Methods }
function HasValueFor(const AttrName: DOMString): Boolean;
procedure RemoveValue(const AttrName: DOMString);
property BindingAppInfoURI: DOMString read GetBindingAppInfoURI write SetBindingAppInfoURI;
property Bound: Variant read GetBound write SetBound;
property DataType: Variant read GetDataType write SetDataType;
property DocElement: Variant read GetDocElement write SetDocElement;
property IdentifierName: Variant read GetIdentifierName write SetIdentifierName;
property PropReadOnly: Variant read GetPropReadOnly write SetPropReadOnly;
property Repeated: Variant read GetRepeated write SetRepeated;
end;
{ IXMLBindingInfo }
{ This interface contains the common properties used to bind all schema
components (complextypes, elements, attributes, etc.) }
IXMLBindingInfo = interface
['{1937F2F8-298E-42A6-983C-EA6BA68D30B8}']
{ Property Accessors }
function GetBindingType: TXMLBindingType;
function GetBound: Boolean;
function GetDataType: string;
function GetDocumentation: string;
function GetIdentifierName: string;
function GetSourceName: string;
function GetSourceType: string;
procedure SetBindingType(const Value: TXMLBindingType);
procedure SetBound(const Value: Boolean);
procedure SetDataType(const Value: string);
procedure SetDocumentation(const Value: string);
procedure SetIdentifierName(const Value: string);
{ Public Methods and Properties }
property BindingType: TXMLBindingType read GetBindingType write SetBindingType;
property Bound: Boolean read GetBound write SetBound;
property DataType: string read GetDataType write SetDataType;
property Documentation: string read GetDocumentation write SetDocumentation;
property IdentifierName: string read GetIdentifierName write SetIdentifierName;
property SourceName: string read GetSourceName;
property SourceType: string read GetSourceType;
end;
{ IXMLDataTypeBinding }
IXMLDataTypeBinding = interface(IXMLBindingInfo)
['{24C2FDBD-58BB-443A-9AD6-9256B9668026}']
{ Property Accessors }
function GetRepeated: Boolean;
procedure SetRepeated(const Value: Boolean);
{ Public Methods and Properties }
function TypeDef: IXMLTypeDef;
property Repeated: Boolean read GetRepeated write SetRepeated;
end;
{ IXMLComplexTypeBinding }
{ This interface contains the properties needed to bind a complex type to
a class/interface definition. }
IXMLPropertyBinding = interface;
IXMLComplexTypeBinding = interface(IXMLDataTypeBinding)
['{87908153-1958-48D0-98CE-B0FF93337113}']
{ Property Accessors }
function GetDocElementName: DOMString;
procedure SetDocElementName(const Value: DOMString);
{ Public Methods and Properties }
function AncestorClass: string;
function AncestorInterface: string;
function ClassIdent: string;
function CollectionItem: IXMLPropertyBinding;
function CollectionItemName: string;
function ComplexTypeDef: IXMLComplexTypeDef;
function IsDocElement: Boolean;
function PureCollection: Boolean;
property DocElementName: DOMString read GetDocElementName write SetDocElementName;
end;
{ IXMLDataTypeListBinding }
IXMLDataTypeListBinding = interface(IXMLComplexTypeBinding)
['{80994C17-4BDE-4A6F-A506-026CE43746BC}']
function ItemBindInfo: IXMLDataTypeBinding;
end;
{ IXMLPropertyBinding }
{ This interface contains the properties needed to bind either an attribute
or an element to a property in class/interface definition }
IXMLPropertyBinding = interface(IXMLBindingInfo)
['{565D9C12-E6E5-4F47-8264-1AF2459D7BBF}']
{ Property Accessors }
function GetPropReadOnly: Boolean;
function GetSchemaItem: IXMLTypedSchemaItem;
procedure SetPropReadOnly(const Value: Boolean);
procedure SetDataType(const Value: string);
{ Public Methods and Properties }
function IsListProp: Boolean;
function TypeBindInfo: IXMLDataTypeBinding;
property DataType: string read GetDataType write SetDataType;
property SchemaItem: IXMLTypedSchemaItem read GetSchemaItem;
property PropReadOnly: Boolean read GetPropReadOnly write SetPropReadOnly; { Element / Attr }
end;
{ IXMLBindingManager }
TCodeWriter = class;
TCodeWriterClass = class of TCodeWriter;
TIdentifierCheckEvent = procedure(var Identifier: string) of object;
IXMLBindingManager = interface
{ Property Accessors }
function GetBindingAppInfoURI: DOMString;
function GetClassNameStr: string;
function GetCodeGenOptions: TBindingOptions;
function GetNativeTypeMap: TBindingOptions;
procedure SetBindingAppInfoURI(const Value: DOMString);
procedure SetClassNameStr(const Value: string);
{ Methods and Properties }
procedure DoIdentifierCheck(var Identifier: string);
function GetBindableItems(const Schema: IXMLSchemaDef): IInterfaceList;
function GetBindingInfo(const ASchemaItem: IInterface): IXMLBindingInfo; overload;
function GetBindingInfo(const TypeDef: IXMLTypeDef): IXMLDataTypeBinding; overload;
function GetBindingInfo(const ComplexTypeDef: IXMLComplexTypeDef): IXMLComplexTypeBinding; overload;
function GetBindingInfo(const PropertyItem: IXMLTypedSchemaItem): IXMLPropertyBinding; overload;
function GetListBindingInfo(const TypeDef: IXMLTypeDef): IXMLDataTypeListBinding;
function GenerateBinding(const BindableItems: IInterfaceList;
const Writers: array of TCodeWriterClass): string; overload;
function GenerateBinding(const BindableItem: IXMLComplexTypeDef;
const Writers: array of TCodeWriterClass): string; overload;
procedure SetOnIdentifierCheck(const Value: TIdentifierCheckEvent);
function SchemaTypeToNativeType(const XMLType: Variant): string;
property BindingAppInfoURI: DOMString read GetBindingAppInfoURI write
SetBindingAppInfoURI;
property ClassNameStr: string read GetClassNameStr write SetClassNameStr;
property CodeGenOptions: TBindingOptions read GetCodeGenOptions;
property NativeTypeMap: TBindingOptions read GetNativeTypeMap;
end;
{ *** Classes *** }
{ TXMLBindingAppInfo }
TXMLBindingAppInfo = class(TXMLAnnotationItem, IXMLBindingAppInfo)
private
FBindingAppInfoURI: DOMString;
protected
function GetValue(const AttrName: DOMString): Variant;
procedure SetValue(const AttrName: DOMString; const Value: Variant);
{ IXMLBindingAppInfo }
function GetBindingAppInfoURI: DOMString;
function GetBound: Variant;
function GetDataType: Variant;
function GetDocElement: Variant;
function GetIdentifierName: Variant;
function GetPropReadOnly: Variant;
function GetRepeated: Variant;
function HasValueFor(const AttrName: DOMString): Boolean;
procedure RemoveValue(const AttrName: DOMString);
procedure SetBindingAppInfoURI(const Value: DOMString);
procedure SetBound(const Value: Variant);
procedure SetDataType(const Value: Variant);
procedure SetDocElement(const Value: Variant);
procedure SetIdentifierName(const Value: Variant);
procedure SetPropReadOnly(const Value: Variant);
procedure SetRepeated(const Value: Variant);
end;
{ TXMLBindingInfo }
TXMLBindingInfo = class(TInterfacedObject, IXMLBindingInfo)
private
FBindingManager: IXMLBindingManager;
FSchemaItem: IXMLSchemaItem;
FBindingAppInfo: IXMLBindingAppInfo;
protected
function GetBindingAppInfo: IXMLBindingAppInfo;
function HasAppInfo(const AppInfoName: string): Boolean;
function MakeIdentifier: string; virtual;
procedure RemoveAppInfo(const AppInfoName: string);
property BindingManager: IXMLBindingManager read FBindingManager;
protected
{ IXMLBindingInfo }
function GetBindingType: TXMLBindingType; virtual; abstract;
function GetBound: Boolean; virtual;
function GetDataType: string; virtual; abstract;
function GetDocumentation: string;
function GetIdentifierName: string; virtual;
function GetSourceName: string;
function GetSourceType: string; virtual; abstract;
procedure SetBindingType(const Value: TXMLBindingType); virtual;
procedure SetBound(const Value: Boolean);
procedure SetDataType(const Value: string);
procedure SetDocumentation(const Value: string);
procedure SetIdentifierName(const Value: string); virtual;
{ Data member access }
property BindingAppInfo: IXMLBindingAppInfo read GetBindingAppInfo;
property SchemaItem: IXMLSchemaItem read FSchemaItem;
public
constructor Create(const ASchemaItem: IXMLSchemaItem;
const BindingManager: IXMLBindingManager);
end;
{ TXMLDataTypeBinding }
TXMLDataTypeBinding = class(TXMLBindingInfo, IXMLDataTypeBinding)
private
FTypeDef: IXMLTypeDef;
protected
{ IXMLDataTypeBinding }
function GetRepeated: Boolean; virtual;
function TypeDef: IXMLTypeDef;
procedure SetRepeated(const Value: Boolean);
public
procedure AfterConstruction; override;
end;
{ TXMLSimpleTypeBinding }
TXMLSimpleTypeBinding = class(TXMLDataTypeBinding, IXMLDataTypeBinding)
private
FSimpleTypeDef: IXMLSimpleTypeDef;
protected
{ IXMLBindingInfo }
function GetBindingType: TXMLBindingType; override;
function GetDataType: string; override;
function GetIdentifierName: string; override;
function GetSourceType: string; override;
function SimpleTypeDef: IXMLSimpleTypeDef;
procedure SetIdentifierName(const Value: string); override;
public
procedure AfterConstruction; override;
end;
{ TXMLComplexTypeBinding }
TXMLComplexTypeBinding = class(TXMLDataTypeBinding, IXMLComplexTypeBinding)
private
FComplexTypeDef: IXMLComplexTypeDef;
protected
function BaseBindingInfo: IXMLComplexTypeBinding;
function HasComplexBase: Boolean;
function MakeIdentifier: string; override;
protected
{ IXMLBindingInfo }
function GetBindingType: TXMLBindingType; override;
function GetDataType: string; override;
function GetSourceType: string; override;
{ IXMLComplexTypeBinding }
function AncestorClass: string; virtual;
function AncestorInterface: string; virtual;
function ClassIdent: string; virtual;
function CollectionItem: IXMLPropertyBinding;
function CollectionItemName: string;
function ComplexTypeDef: IXMLComplexTypeDef;
function GetDocElementName: DOMString;
function IsDocElement: Boolean;
function PureCollection: Boolean;
procedure SetDocElementName(const Value: DOMString);
public
procedure AfterConstruction; override;
end;
{ TXMLDataTypeListBinding }
TXMLDataTypeListBinding = class(TXMLComplexTypeBinding, IXMLDataTypeListBinding)
private
FListTypeSuffix: string;
FSimpleType: Boolean;
protected
function AncestorClass: string; override;
function AncestorInterface: string; override;
function ClassIdent: string; override;
function CollectionItemName: string;
function GetIdentifierName: string; override;
function GetRepeated: Boolean; override;
function ItemBindInfo: IXMLDataTypeBinding;
function PureCollection: Boolean;
property ListTypeSuffix: string read FListTypeSuffix write FListTypeSuffix;
public
procedure AfterConstruction; override;
end;
{ TXMLPropertyBinding }
TXMLPropertyBinding = class(TXMLBindingInfo, IXMLPropertyBinding)
private
FSchemaItem: IXMLTypedSchemaItem;
protected
function ReadDataType: string;
{ IXMLBindingInfo }
function GetBindingType: TXMLBindingType; override;
function GetBound: Boolean; override;
function GetDataType: string; override;
function GetSchemaItem: IXMLTypedSchemaItem;
function GetSourceType: string; override;
procedure SetBindingType(const Value: TXMLBindingType); override;
{ IXMLPropertyBinding }
function TypeBindInfo: IXMLDataTypeBinding;
function GetPropReadOnly: Boolean;
function IsListProp: Boolean;
procedure SetPropReadOnly(const Value: Boolean);
procedure SetDataType(const Value: string);
public
procedure AfterConstruction; override;
end;
{ =========================================================================== }
{ Code Generation Classes }
{ =========================================================================== }
{ TCodeWriter }
{ Contains methods used for writing code structures which are common to
different elements of the generated unit. This is the base class for
all other code writers. }
TCodeWriter = class(TStringList)
private
FBindingManager: IXMLBindingManager;
FModified: Boolean;
protected
function PropGetPrefix: string;
function PropSetPrefix: string;
property BindingManager: IXMLBindingManager read FBindingManager;
public
constructor Create(BindingManager: IXMLBindingManager); reintroduce;
procedure Generate(const BindingInfo: IXMLComplexTypeBinding); virtual;
procedure Changed; override;
procedure Write(const Code: string; Indent: Integer = 0); overload;
procedure Write(const FmtLine: string; Params: array of const;
Indent: Integer = 0); overload;
procedure WriteLine;
procedure WriteAfterConstruction(const OverrideStr: string = ''; Indent: Integer = 0);
procedure WriteRegisterChildNode(const TagName, ChildClass: string);
procedure WriteClassDecl(const Name, AncestorName, IntfName: string);
procedure WriteCollCreate(const DataMember, CollClass, ItemInterface,
ItemTag, CollInterface: string);
procedure WriteCollGetItem(const DataType: string; Indent: Integer = 0);
procedure WriteCollItemInit(const ItemTag, ItemInterface: string);
procedure WriteCollItemProp(const DataType: string);
procedure WriteComment(const Comment: string; Indent: Integer = 0;
LinePadding: Integer = 0);
procedure WriteDataMember(const Name, DataType: string);
procedure WriteDataProperty(const Name, DataType: string; HasWriter: Boolean);
procedure WriteDeclComment(const Comment: string; LinePadding: Integer = 2);
procedure WriteFunction(const FuncCode, DataType: string; Indent: Integer = 0); overload;
procedure WriteFunction(const FuncName, DataType: string;
const ParamNames, ParamTypes: array of string; Indent: Integer = 0); overload;
procedure WriteGetMethod(const Name, DataType: string;
Indent: Integer; Indexed: Boolean = False);
procedure WriteGetBindFunc(const SourceName, DataType: string);
procedure WriteLoadBindFunc(const SourceName, DataType: string);
procedure WriteNewBindFunc(const SourceName, DataType: string);
procedure WriteGuid;
procedure WriteIntfDecl(const Name, AncestorType: string);
procedure WriteMethodBody(const Template: string; Params: array of const);
procedure WriteProperty(const Name, DataType: string; HasWriter: Boolean;
Indexed: Boolean = False);
procedure WriteSetMethod(const Name, DataType: string;
Indent: Integer; Indexed: Boolean = False);
property Modified: Boolean read FModified write FModified;
end;
{ TForwardDecl }
TForwardDecl = class(TCodeWriter)
public
procedure AfterConstruction; override;
end;
{ TPropertyContainer }
{ Base class for interface and implementation section entries which contain
property declarations and code. }
PCodeWriter = ^TCodeWriter;
TCodeWriterArray = array of TCodeWriter;
TPropertyContainer = class(TCodeWriter)
private
FCodeWriters: TCodeWriterArray;
FBindingInfo: IXMLComplexTypeBinding;
FTypeDef: IXMLComplexTypeDef;
protected
procedure AppendCode; overload;
procedure AppendCode(const CodeLists: array of TCodeWriter); overload;
procedure InitCodeWriters(CodeWriters: array of PCodeWriter;
CodeLines: array of string);
procedure WriteCollectionMethods(Writer: TCodeWriter;
ItemInfo: IXMLDataTypeBinding; Indent: Integer); virtual;
procedure WriteCollAdd(Writer: TCodeWriter; ItemInfo: IXMLDataTypeBinding;
Indent: Integer); virtual;
procedure WriteCollInsert(Writer: TCodeWriter; ItemInfo: IXMLDataTypeBinding;
Indent: Integer); virtual;
procedure WriteListBinding(const ItemInfo: IXMLDataTypeBinding); virtual;
procedure WriteMethods; virtual;
procedure WriteProperties; virtual;
procedure WriteProperty(const PropBindInfo: IXMLPropertyBinding;
const Indexed: Boolean); virtual;
property BindingInfo: IXMLComplexTypeBinding read FBindingInfo;
property CodeWriters: TCodeWriterArray read FCodeWriters;
property TypeDef: IXMLComplexTypeDef read FTypeDef;
public
destructor Destroy; override;
procedure Generate(const BindingInfo: IXMLComplexTypeBinding); override;
end;
{ TIntfSectionEntry }
{ Base class for Interface and Class Declarations }
TIntfSectionEntry = class(TPropertyContainer)
protected
GetMethods: TCodeWriter;
SetMethods: TCodeWriter;
PrivateItems: TCodeWriter;
ProtectedItems: TCodeWriter;
PublicItems: TCodeWriter;
PublishedItems: TCodeWriter;
procedure WriteDecl; virtual;
public
procedure Generate(const BindingInfo: IXMLComplexTypeBinding); override;
end;
{ TIntfForward }
TIntfForward = class(TForwardDecl)
public
procedure Generate(const BindingInfo: IXMLComplexTypeBinding); override;
end;
{ TIntfDecl }
TIntfDecl = class(TIntfSectionEntry)
protected
procedure WriteDecl; override;
procedure WriteListBinding(const ItemInfo: IXMLDataTypeBinding); override;
procedure WriteProperty(const PropBindInfo: IXMLPropertyBinding;
const Indexed: Boolean); override;
end;
{ TClassForward }
TClassForward = class(TForwardDecl)
public
procedure Generate(const BindingInfo: IXMLComplexTypeBinding); override;
end;
{ TClassDecl }
TClassDecl = class(TIntfSectionEntry)
private
FNeedsRegCode: Boolean;
protected
procedure WriteDecl; override;
procedure WriteListBinding(const ItemInfo: IXMLDataTypeBinding); override;
procedure WriteProperties; override;
procedure WriteProperty(const PropBindInfo: IXMLPropertyBinding;
const Indexed: Boolean); override;
property NeedsRegCode: Boolean read FNeedsRegCode write FNeedsRegCode;
end;
{ TXMLBindingManager }
TXMLBindingManager = class(TInterfacedObject, IXMLBindingManager)
private
FBindingAppInfoURI: DOMString;
FClassNameStr: string;
FCodeGenOptions: TBindingOptions;
FNativeTypeMap: TBindingOptions;
FOnIdentifierCheck: TIdentifierCheckEvent;
protected
{ IXMLBindingManger Property Accessors }
function GetClassNameStr: string;
function GetBindingAppInfoURI: DOMString;
function GetCodeGenOptions: TBindingOptions;
function GetNativeTypeMap: TBindingOptions;
procedure SetBindingAppInfoURI(const Value: DOMString);
procedure SetClassNameStr(const Value: string);
{ IXMLBindingManager Methods }
procedure DoIdentifierCheck(var Identifier: string);
function GetBindableItems(const Schema: IXMLSchemaDef): IInterfaceList;
function GetBindingInfo(const ASchemaItem: IInterface): IXMLBindingInfo; overload;
function GetBindingInfo(const TypeDef: IXMLTypeDef): IXMLDataTypeBinding; overload;
function GetBindingInfo(const ComplexTypeDef: IXMLComplexTypeDef): IXMLComplexTypeBinding; overload;
function GetBindingInfo(const PropertyItem: IXMLTypedSchemaItem): IXMLPropertyBinding; overload;
function GetListBindingInfo(const TypeDef: IXMLTypeDef): IXMLDataTypeListBinding;
function GenerateBinding(const BindableItems: IInterfaceList;
const Writers: array of TCodeWriterClass): string; overload;
function GenerateBinding(const BindableItem: IXMLComplexTypeDef;
const Writers: array of TCodeWriterClass): string; overload;
function SchemaTypeToNativeType(const XMLType: Variant): string;
procedure SetOnIdentifierCheck(const Value: TIdentifierCheckEvent);
public
destructor Destroy; override;
procedure AfterConstruction; override;
end;
procedure MakeValidIdent(var Ident: string);
implementation
uses
XMLSchemaTags;
const
DefaultTypeMap: array[0..19] of string = (
'string=WideString',
'boolean=Boolean',
'float=Single',
'double=Double',
'number=Double',
'integer=Integer',
'nonPositiveInteger=Integer',
'negativeInteger=Integer',
'long=Int64',
'int=Integer',
'short=SmallInt',
'byte=ShortInt',
'nonNegativeInteger=LongWord',
'unsignedLong=Int64',
'unsignedInt=LongWord',
'unsignedShort=Word',
'unsignedByte=Byte',
'positiveInteger=LongWord',
'anySimpleType=Variant',
'ur-type=Variant');
DefaultCode: array[0..9] of string = (
cgPropGetPrefix+'=Get_',
cgPropSetPrefix+'=Set_',
cgClassPrefix+'=TXML',
cgInterfacePrefix+'=IXML',
cgListTypeSuffix+'=List',
cgNodeIntfBase+'=IXMLNode',
cgNodeClassBase+'=TXMLNode',
cgCollIntfBase+'=IXMLNodeCollection',
cgCollClassBase+'=TXMLNodeCollection',
cgDefaultDataType+'=WideString');
{ Utiltity Routines }
{$IFDEF MSWINDOWS}
function CoCreateGuid(out guid: TGUID): HResult; stdcall;
external 'ole32.dll' name 'CoCreateGuid';
function CreateGuid: TGuid;
begin
CoCreateGuid(Result);
end;
{$ELSE}
function CreateGuid: TGuid;
begin
{Need Linux CreateGuid Function}
Result := GUID_NULL;
end;
{$ENDIF}
procedure MakeValidIdent(var Ident: string);
var
I: Integer;
begin
I := 1;
while I <= Length(Ident) do
begin
if Ident[I] in ['A'..'Z','a'..'z','_','0'..'9'] then
Inc(I)
else if Ident[I] in LeadBytes then
Delete(Ident, I, 2)
else
Delete(Ident, I, 1);
end;
end;
{ TBindingOptions }
constructor TBindingOptions.Create(const SectionName: string;
OnChangeEvent: TOptionChangeEvent = nil);
begin
FOptions := TStringList.Create;
FSectionName := SectionName;
if Assigned(OnChangeEvent) then
FOnOptionChange := OnChangeEvent;
inherited Create;
end;
destructor TBindingOptions.Destroy;
var
I: Integer;
begin
{ We are assumed to be the owner of any
objects placed into the OptionData properties }
for I := 0 to FOptions.Count - 1 do
FOptions.Objects[I].Free;
FOptions.Free;
inherited;
end;
procedure TBindingOptions.Assign(Source: TPersistent);
var
I, ValPos: Integer;
S: string;
Strings: TStrings;
begin
if Source is TStrings then
begin
Strings := TStrings(Source);
for I := 0 to Strings.Count - 1 do
begin
S := Strings[I];
ValPos := Pos('=', S);
if ValPos > 0 then
SetOption(Copy(S, 1, ValPos-1), Copy(S, ValPos+1, MAXINT));
end;
end
else
inherited;
end;
procedure TBindingOptions.AssignTo(Dest: TPersistent);
begin
if Dest is TStrings then
begin
TStrings(Dest).Assign(FOptions)
end
else
inherited;
end;
procedure TBindingOptions.DoOptionChange(const OptionName: string;
const Value: Variant);
begin
if Assigned(OnOptionChange) then
OnOptionChange(SectionName, OptionName, Value);
end;
procedure TBindingOptions.EnsureOption(const OptionStr: string);
var
ValPos: Integer;
Name, Value: string;
begin
ValPos := Pos('=', OptionStr);
Name := Copy(OptionStr, 1, ValPos-1);
Value := Copy(OptionStr, ValPos+1, MAXINT);
{ Force option to exist in the list }
if FOptions.Values[Name] <> Value then
SetOption(Name, Value);
end;
function TBindingOptions.GetOption(const Name: string; const Default: Variant): Variant;
begin
Result := FOptions.Values[Name];
if (Result = '') and (VarToStr(Default) <> '') then
Result := Default;
end;
function TBindingOptions.GetOptionValue(const Name: string): Variant;
begin
Result := GetOption(Name, '');
end;
procedure TBindingOptions.SetOption(const Name: string; const Value: Variant);
var
Index: Integer;
StrValue: string;
begin
StrValue := VarToStr(Value);
if FOptions.Values[Name] = StrValue then Exit;
if StrValue = '' then
begin
Index := FOptions.IndexOfName(Name);
FOptions[Index] := Name+'=';
end
else
FOptions.Values[Name] := StrValue;
DoOptionChange(Name, Value);
end;
function TBindingOptions.GetOptionData(const Name: string): TObject;
var
Index: Integer;
begin
Index := FOptions.IndexOfName(Name);
if Index <> -1 then
Result := FOptions.Objects[Index]
else
Result := nil;
end;
procedure TBindingOptions.SetOptionData(const Name: string;
const Value: TObject);
var
Index: Integer;
begin
Index := FOptions.IndexOfName(Name);
if Index <> -1 then
FOptions.Objects[Index] := Value;
end;
procedure TBindingOptions.InitializeOptions(const Values: array of string);
var
I: Integer;
begin
for I := 0 to High(Values) do
EnsureOption(Values[I]);
end;
procedure TBindingOptions.InitializeOptions(const Values: TStrings);
var
I: Integer;
begin
for I := 0 to Values.Count - 1 do
EnsureOption(Values[I]);
end;
procedure TBindingOptions.Clear;
begin
FOptions.Clear;
DoOptionChange('', VarNull);
end;
function TBindingOptions.IsTrue(const Name: string): Boolean;
var
Value: Variant;
begin
Value := GetOption(Name, '');
Result := Value;
end;
{ TXMLBindingAppInfo }
function TXMLBindingAppInfo.GetValue(const AttrName: DOMString): Variant;
begin
Result := GetAttributeNS(Attrname, FBindingAppInfoURI);
end;
procedure TXMLBindingAppInfo.SetValue(const AttrName: DOMString;
const Value: Variant);
begin
SetAttributeNS(MakeNodeName(aiDBWizPrefix, AttrName), FBindingAppInfoURI, Value);
end;
function TXMLBindingAppInfo.HasValueFor(const AttrName: DOMString): Boolean;
begin
Result := HasAttribute(AttrName, FBindingAppInfoURI);
end;
procedure TXMLBindingAppInfo.RemoveValue(const AttrName: DOMString);
begin
AttributeNodes.Delete(AttrName, FBindingAppInfoURI);
end;
function TXMLBindingAppInfo.GetPropReadOnly: Variant;
begin
Result := GetValue(aiReadOnly);
end;
procedure TXMLBindingAppInfo.SetPropReadOnly(const Value: Variant);
begin
SetValue(aiReadOnly, Value);
end;
function TXMLBindingAppInfo.GetBindingAppInfoURI: DOMString;
begin
Result := FBindingAppInfoURI;
end;
procedure TXMLBindingAppInfo.SetBindingAppInfoURI(const Value: DOMString);
begin
FBindingAppInfoURI := Value;
end;
function TXMLBindingAppInfo.GetBound: Variant;
begin
Result := GetValue(aiBound);
end;
procedure TXMLBindingAppInfo.SetBound(const Value: Variant);
begin
SetValue(aiBound, Value);
end;
function TXMLBindingAppInfo.GetIdentifierName: Variant;
begin
Result := GetValue(aiIdentifierName);
end;
procedure TXMLBindingAppInfo.SetIdentifierName(const Value: Variant);
begin
SetValue(aiIdentifierName, Value);
end;
function TXMLBindingAppInfo.GetDocElement: Variant;
begin
Result := GetValue(aiDocElement);
end;
procedure TXMLBindingAppInfo.SetDocElement(const Value: Variant);
begin
SetValue(aiDocElement, Value);
end;
function TXMLBindingAppInfo.GetDataType: Variant;
begin
Result := GetValue(aiDataType);
end;
procedure TXMLBindingAppInfo.SetDataType(const Value: Variant);
begin
SetValue(aiDataType, Value);
end;
function TXMLBindingAppInfo.GetRepeated: Variant;
begin
Result := GetValue(aiRepeated);
end;
procedure TXMLBindingAppInfo.SetRepeated(const Value: Variant);
begin
SetValue(aiRepeated, Value);
end;
{ TXMLBindingInfo }
constructor TXMLBindingInfo.Create(const ASchemaItem: IXMLSchemaItem;
const BindingManager: IXMLBindingManager);
begin
FSchemaItem := ASchemaItem;
FBindingManager := BindingManager;
inherited Create;
end;
function TXMLBindingInfo.HasAppInfo(const AppInfoName: string): Boolean;
begin
Result := False;
if not Assigned(FBindingAppInfo) and SchemaItem.HasAnnotation then
GetBindingAppInfo;
if Assigned(FBindingAppInfo) then
Result := FBindingAppInfo.HasValueFor(AppInfoName);
end;
function TXMLBindingInfo.GetBindingAppInfo: IXMLBindingAppInfo;
begin
if not Assigned(FBindingAppInfo) then
begin
FBindingAppInfo := SchemaItem.AppInfo.GetAppInfo(IXMLBindingAppInfo,
TXMLBindingAppInfo) as IXMLBindingAppInfo;
FBindingAppInfo.BindingAppInfoURI := BindingManager.BindingAppInfoURI;
end;
Result := FBindingAppInfo;
end;
procedure TXMLBindingInfo.RemoveAppInfo(const AppInfoName: string);
begin
if HasAppInfo(AppInfoName) then
begin
BindingAppInfo.RemoveValue(AppInfoName);
{ If we remove the last item then remove the AppInfo element
and also the Annotation element (if it's empty) }
if BindingAppInfo.AttributeNodes.Count = 0 then
begin
SchemaItem.AppInfo.Remove(BindingAppInfo);
SchemaItem.RemoveAnnotation;
end;
end;
end;
function TXMLBindingInfo.MakeIdentifier: string;
begin
Result := ExtractLocalName(SchemaItem.Name);
MakeValidIdent(Result);
if Result = '' then Exit;
BindingManager.DoIdentifierCheck(Result);
end;
{ IXMLBindingInfo }
function TXMLBindingInfo.GetDocumentation: string;
begin
Result := XMLSchema.GetDocumentation(SchemaItem);
end;
procedure TXMLBindingInfo.SetDocumentation(const Value: string);
begin
if SchemaItem.Documentation.Count = 1 then
SchemaItem.Documentation[0].NodeValue := Value
else if SchemaItem.Documentation.Count = 0 then
SchemaItem.Documentation.Add.NodeValue := Value;
end;
function TXMLBindingInfo.GetIdentifierName: string;
begin
if HasAppInfo(aiIdentifierName) then
Result := VarToStr(BindingAppInfo.IdentifierName)
else
Result := MakeIdentifier;
end;
procedure TXMLBindingInfo.SetIdentifierName(const Value: string);
begin
if MakeIdentifier <> Value then
BindingAppInfo.IdentifierName := Value
else
RemoveAppInfo(aiIdentifierName);
end;
function TXMLBindingInfo.GetSourceName: string;
begin
Result := SchemaItem.Name;
end;
function TXMLBindingInfo.GetBound: Boolean;
begin
if HasAppInfo(aiBound) then
Result := BindingAppInfo.Bound
else
Result := True;
end;
procedure TXMLBindingInfo.SetBound(const Value: Boolean);
begin
if not Value then
BindingAppInfo.Bound := SFalse
else
RemoveAppInfo(aiBound);
end;
procedure TXMLBindingInfo.SetDataType(const Value: string);
begin
Assert(False);
end;
procedure TXMLBindingInfo.SetBindingType(const Value: TXMLBindingType);
begin
Assert(False);
end;
{ TXMLDataTypeBinding }
procedure TXMLDataTypeBinding.AfterConstruction;
begin
FTypeDef := SchemaItem as IXMLTypeDef;
inherited;
end;
function TXMLDataTypeBinding.GetRepeated: Boolean;
begin
if HasAppInfo(aiRepeated) then
Result := BindingAppInfo.Repeated
else
Result := False;
end;
procedure TXMLDataTypeBinding.SetRepeated(const Value: Boolean);
begin
if Value then
BindingAppInfo.Repeated := STrue
else
RemoveAppInfo(aiRepeated);
end;
function TXMLDataTypeBinding.TypeDef: IXMLTypeDef;
begin
Result := FTypeDef;
end;
{ TXMLSimpleTypeBinding }
procedure TXMLSimpleTypeBinding.AfterConstruction;
begin
FSimpleTypeDef := SchemaItem as IXMLSimpleTypeDef;
inherited;
end;
function TXMLSimpleTypeBinding.SimpleTypeDef: IXMLSimpleTypeDef;
begin
Result := FSimpleTypeDef;
end;
function TXMLSimpleTypeBinding.GetBindingType: TXMLBindingType;
begin
Result := btSimpleType;
end;
function TXMLSimpleTypeBinding.GetDataType: string;
begin
Result := VarToStr(FSimpleTypeDef.GetAttribute(aiDataType));
if Result = '' then
Result := BindingManager.CodeGenOptions[cgNodeIntfBase];
end;
function TXMLSimpleTypeBinding.GetIdentifierName: string;
begin
if not FSimpleTypeDef.IsBuiltInType then
begin
if HasAppInfo(aiIdentifierName) then
Result := BindingAppInfo.IdentifierName else
Result := BindingManager.SchemaTypeToNativeType(FSimpleTypeDef.BaseTypeName);
end
else
{ For built-in types, there will be no base type }
Result := BindingManager.SchemaTypeToNativeType(FSimpleTypeDef.Name);
end;
procedure TXMLSimpleTypeBinding.SetIdentifierName(const Value: string);
begin
if Assigned(FSimpleTypeDef.OwnerDocument) then
begin
if BindingManager.SchemaTypeToNativeType(FSimpleTypeDef.BaseTypeName) <> Value then
BindingAppInfo.IdentifierName := Value else
RemoveAppInfo(aiIdentifierName);
end else
BindingManager.NativeTypeMap[ExtractLocalName(SchemaItem.Name)] := Value;
end;
function TXMLSimpleTypeBinding.GetSourceType: string;
begin
if FSimpleTypeDef.IsBuiltInType then
Result := SBuiltInType
else
Result := VarToStr(FSimpleTypeDef.BaseTypeName);
end;
{ TXMLComplexTypeBinding }
procedure TXMLComplexTypeBinding.AfterConstruction;
begin
SchemaItem.QueryInterface(IXMLComplexTypeDef, FComplexTypeDef);
inherited;
end;
function TXMLComplexTypeBinding.MakeIdentifier: string;
begin
Result := BindingManager.CodeGenOptions[cgInterfacePrefix] + inherited MakeIdentifier;
end;
function TXMLComplexTypeBinding.BaseBindingInfo: IXMLComplexTypeBinding;
begin
Result := BindingManager.GetBindingInfo(FComplexTypeDef.BaseType as IXMLComplexTypeDef);
end;
function TXMLComplexTypeBinding.HasComplexBase: Boolean;
begin
Result := Assigned(FComplexTypeDef) and
(FComplexTypeDef.DerivationMethod in [dmComplexExtension, dmComplexRestriction]);
end;
function TXMLComplexTypeBinding.AncestorClass: string;
begin
if HasComplexBase and Assigned(FComplexTypeDef.BaseType) then
Result := BaseBindingInfo.ClassIdent
else if PureCollection then
Result := BindingManager.CodeGenOptions[cgCollClassBase]
else
Result := BindingManager.CodeGenOptions[cgNodeClassBase];
end;
function TXMLComplexTypeBinding.AncestorInterface: string;
begin
if HasComplexBase then
Result := BaseBindingInfo.IdentifierName
else if PureCollection then
Result := BindingManager.CodeGenOptions[cgCollIntfBase]
else
Result := BindingManager.CodeGenOptions[cgNodeIntfBase];
end;
function TXMLComplexTypeBinding.ClassIdent: string;
begin
Result := BindingManager.CodeGenOptions[cgClassPrefix] + inherited MakeIdentifier;
end;
function TXMLComplexTypeBinding.ComplexTypeDef: IXMLComplexTypeDef;
begin
Result := FComplexTypeDef;
end;
function TXMLComplexTypeBinding.GetDataType: string;
begin
Result := GetIdentifierName;
end;
function TXMLComplexTypeBinding.GetDocElementName: DOMString;
begin
if HasAppInfo(aiDocElement) then
Result := BindingAppInfo.DocElement
else
Result := '';
end;
procedure TXMLComplexTypeBinding.SetDocElementName(const Value: DOMString);
begin
if Value <> '' then
BindingAppInfo.DocElement := Value
else
RemoveAppInfo(aiDocElement);
end;
function TXMLComplexTypeBinding.IsDocElement: Boolean;
begin
Result := GetDocElementName <> '';
end;
function TXMLComplexTypeBinding.GetSourceType: string;
begin
if FComplexTypeDef.DerivationMethod <> dmNone then
Result := FComplexTypeDef.BaseTypeName
else
Result := 'ComplexType'; { Do not localize }
end;
function TXMLComplexTypeBinding.GetBindingType: TXMLBindingType;
begin
Result := btComplexType;
end;
function TXMLComplexTypeBinding.PureCollection: Boolean;
begin
Result := (FComplexTypeDef.ElementDefList.Count = 1) and
FComplexTypeDef.ElementDefList[0].IsRepeating;
end;
function TXMLComplexTypeBinding.CollectionItemName: string;
begin
Result := CollectionItem.IdentifierName;
end;
{ TXMLDataTypeListBinding }
procedure TXMLDataTypeListBinding.AfterConstruction;
begin
inherited;
ListTypeSuffix := BindingManager.CodeGenOptions[cgListTypeSuffix];
FSimpleType := Supports(SchemaItem, IXMLSimpleTypeDef);
end;
function TXMLDataTypeListBinding.AncestorClass: string;
begin
if HasComplexBase then
Result := BaseBindingInfo.ClassIdent
else
Result := BindingManager.CodeGenOptions[cgCollClassBase];
end;
function TXMLDataTypeListBinding.AncestorInterface: string;
begin
if HasComplexBase then
Result := BaseBindingInfo.IdentifierName
else
Result := BindingManager.CodeGenOptions[cgCollIntfBase];
end;
function TXMLDataTypeListBinding.ClassIdent: string;
begin
Result := inherited ClassIdent + ListTypeSuffix;
end;
function TXMLDataTypeListBinding.CollectionItemName: string;
begin
if FSimpleType then
Result := 'Value' { Do not localize }
else
Result := CollectionItem.IdentifierName;
end;
function TXMLDataTypeListBinding.GetIdentifierName: string;
begin
Result := inherited GetIdentifierName + ListTypeSuffix;
end;
function TXMLDataTypeListBinding.GetRepeated: Boolean;
begin
Result := False;
end;
function TXMLDataTypeListBinding.ItemBindInfo: IXMLDataTypeBinding;
begin
Result := BindingManager.GetBindingInfo(TypeDef);
end;
function TXMLComplexTypeBinding.CollectionItem: IXMLPropertyBinding;
begin
Result := BindingManager.GetBindingInfo(ComplexTypeDef.ElementDefList[0])
end;
function TXMLDataTypeListBinding.PureCollection: Boolean;
begin
Result := False;
end;
{ TXMLPropertyBinding }
procedure TXMLPropertyBinding.AfterConstruction;
begin
FSchemaItem := SchemaItem as IXMLTypedSchemaItem;
inherited;
end;
function TXMLPropertyBinding.TypeBindInfo: IXMLDataTypeBinding;
begin
Result := BindingManager.GetBindingInfo(FSchemaItem.DataType);
end;
function TXMLPropertyBinding.GetBound: Boolean;
begin
Result := inherited GetBound;
if Result then
Result := BindingManager.GetBindingInfo(FSchemaItem.DataType).Bound;
end;
function TXMLPropertyBinding.ReadDataType: string;
begin
if IsListProp then
Result := BindingManager.GetListBindingInfo(FSchemaItem.DataType).IdentifierName
else
Result := BindingManager.GetBindingInfo(FSchemaItem.DataType).IdentifierName;
end;
function TXMLPropertyBinding.GetDataType: string;
begin
if HasAppInfo(aiDataType) then
Result := BindingAppInfo.DataType
else
Result := ReadDataType;
end;
procedure TXMLPropertyBinding.SetDataType(const Value: string);
begin
if ReadDataType <> Value then
BindingAppInfo.DataType := Value
else
RemoveAppInfo(aiDataType);
end;
function TXMLPropertyBinding.GetPropReadOnly: Boolean;
begin
if (GetBindingType in [btAttribute, btSimpleElement]) and not HasAppInfo(aiReadOnly) then
Result := False else
Result := True;
end;
procedure TXMLPropertyBinding.SetPropReadOnly(const Value: Boolean);
begin
if Value then
BindingAppInfo.PropReadOnly := STrue
else
RemoveAppInfo(aiReadOnly);
end;
function TXMLPropertyBinding.GetSourceType: string;
begin
Result := VarToStr(FSchemaItem.DataTypeName);
end;
function TXMLPropertyBinding.GetBindingType: TXMLBindingType;
begin
if Supports(FSchemaItem, IXMLAttributeDef) then
Result := btAttribute
else if (FSchemaItem as IXMLElementDef).IsRepeating then
Result := btCollectionElement
else if not FSchemaItem.DataType.IsComplex then
Result := btSimpleElement
else
Result := btComplexElement;
end;
procedure TXMLPropertyBinding.SetBindingType(const Value: TXMLBindingType);
var
ElementDef: IXMLElementDef;
begin
if Value <> GetBindingType then
begin
ElementDef := FSchemaItem as IXMLElementDef;
TypeBindInfo.Repeated := (Value = btCollectionElement);
case value of
btCollectionElement:
ElementDef.MaxOccurs := SUnbounded;
btComplexType:
ElementDef.MaxOccurs := '1';
end;
end;
end;
function TXMLPropertyBinding.IsListProp: Boolean;
begin
Result := TypeBindInfo.Repeated and
(GetBindingType in [btCollectionElement])
end;
function TXMLPropertyBinding.GetSchemaItem: IXMLTypedSchemaItem;
begin
Result := FSchemaItem;
end;
{ =========================================================================== }
{ Code Generation Classes }
{ =========================================================================== }
{ TCodeWriter }
constructor TCodeWriter.Create(BindingManager: IXMLBindingManager);
begin
FBindingManager := BindingManager;
inherited Create;
end;
procedure TCodeWriter.Changed;
begin
inherited;
Modified := True;
end;
function TCodeWriter.PropGetPrefix: string;
begin
Result := VarToStr(BindingManager.CodeGenOptions[cgPropGetPrefix]);
end;
function TCodeWriter.PropSetPrefix: string;
begin
Result := VarToStr(BindingManager.CodeGenOptions[cgPropSetPrefix]);
end;
procedure TCodeWriter.Generate(const BindingInfo: IXMLComplexTypeBinding);
begin
end;
procedure TCodeWriter.WriteLine;
begin
Add(''); { Write an empty line }
end;
procedure TCodeWriter.Write(const FmtLine: string;
Params: array of const; Indent: Integer = 0);
begin
Add(StringOfChar(' ', 2*Indent)+Format(FmtLine, Params));
end;
procedure TCodeWriter.Write(const Code: string; Indent: Integer = 0);
begin
Write(Code, [], Indent);
end;
procedure TCodeWriter.WriteComment(const Comment: string; Indent: Integer = 0;
LinePadding: Integer = 0);
begin
if LinePadding > 0 then WriteLine;
Write('{ %s }', [Comment], Indent);
if LinePadding > 1 then WriteLine;
end;
procedure TCodeWriter.WriteDeclComment(const Comment: string;
LinePadding: Integer = 2);
begin
WriteComment(Comment, 0, LinePadding);
end;
procedure TCodeWriter.WriteMethodBody(const Template: string; Params: array of const);
begin
Write(SBegin);
Write(Template, Params, 1);
Write(SEnd);
end;
procedure TCodeWriter.WriteFunction(const FuncCode, DataType: string;
Indent: Integer = 0);
begin
Write('function %s%s: %s;', [BindingManager.ClassNameStr, FuncCode, DataType], Indent);
end;
procedure TCodeWriter.WriteFunction(const FuncName, DataType: string;
const ParamNames, ParamTypes: array of string; Indent: Integer);
var
I: Integer;
FuncCode: string;
begin
FuncCode := FuncName+'(';
for I := 0 to High(ParamNames) do
FuncCode := FuncCode + 'const ' + ParamNames[I] + ': '+ ParamTypes[I] + '; ';
System.Delete(FuncCode, Length(FuncCode)-1, 2);
FuncCode := FuncCode + ')';
WriteFunction(FuncCode, DataType, Indent);
end;
procedure TCodeWriter.WriteGetMethod(const Name, DataType: string;
Indent: Integer; Indexed: Boolean = False);
const
IndexPart: array[Boolean] of string = ('', '('+SIndexCode+')');
begin
Write('function %s%s%s%s: %s;', [BindingManager.ClassNameStr,
PropGetPrefix, Name, IndexPart[Indexed], DataType], Indent);
end;
procedure TCodeWriter.WriteSetMethod(const Name, DataType: string;
Indent: Integer; Indexed: Boolean = False);
const
IndexPart: array[Boolean] of string = ('', SIndexCode+'; ');
begin
Write('procedure %s%s%s(%sValue: %s);', [BindingManager.ClassNameStr,
PropSetPrefix, Name, IndexPart[Indexed], DataType], Indent);
end;
procedure TCodeWriter.WriteDataProperty(const Name, DataType: string;
HasWriter: Boolean);
var
NamePart, Writer: string;
begin
NamePart := Format('property %s: %s read F%0:s', [Name, DataType]);
if HasWriter then
Writer := Format(' write F%s', [Name]);
Write('%s%s;', [NamePart, Writer], 2);
end;
procedure TCodeWriter.WriteProperty(const Name, DataType: string;
HasWriter: Boolean; Indexed: Boolean = False);
const
IndexPart: array[Boolean] of string = ('', '['+SIndexCode+']');
DefaultPart: array[Boolean] of string = ('', ' default;');
var
NamePart, Reader, Writer: string;
begin
NamePart := Format('property %s%s: %s', [Name, IndexPart[Indexed], DataType]);
Reader := Format(' read %s%s', [PropGetPrefix, Name]);
if HasWriter then
Writer := Format(' write %s%s', [PropSetPrefix, Name]);
Write('%s%s%s;%s', [NamePart, Reader, Writer, DefaultPart[Indexed]], 2);
end;
procedure TCodeWriter.WriteDataMember(const Name, DataType: string);
begin
Write('F%s: %s;', [Name, DataType], 2);
end;
procedure TCodeWriter.WriteAfterConstruction(const OverrideStr: string = '';
Indent: Integer = 0);
begin
Write('procedure %sAfterConstruction;%s', [BindingManager.ClassNameStr,
OverrideStr], Indent);
end;
procedure TCodeWriter.WriteGetBindFunc(const SourceName, DataType: string);
begin
Write('function Get%s(Doc: IXMLDocument): %s;', [SourceName, DataType]);
end;
procedure TCodeWriter.WriteLoadBindFunc(const SourceName, DataType: string);
begin
Write('function Load%s(const FileName: WideString): %s;', [SourceName, DataType]);
end;
procedure TCodeWriter.WriteNewBindFunc(const SourceName, DataType: string);
begin
Write('function New%s: %s;', [SourceName, DataType]);
end;
procedure TCodeWriter.WriteClassDecl(const Name, AncestorName,
IntfName: string);
var
IntfStr: string;
begin
if IntfName <> '' then IntfStr := ', '+IntfName;
Write('%s = class(%s%s)', [Name, AncestorName, IntfStr], 1);
end;
procedure TCodeWriter.WriteIntfDecl(const Name, AncestorType: string);
begin
Write('%s = interface(%s)', [Name, AncestorType], 1);
end;
procedure TCodeWriter.WriteGuid;
begin
Write('[''%s'']', [GUIDToString(CreateGuid)], 2);
end;
procedure TCodeWriter.WriteCollCreate(const DataMember, CollClass, ItemInterface,
ItemTag, CollInterface: string);
begin
Write('F%s := CreateCollection(%s, %s, ''%s'') as %s;',
[DataMember, CollClass, ItemInterface, ItemTag, CollInterface], 1);
end;
procedure TCodeWriter.WriteCollGetItem(const DataType: string; Indent: Integer = 0);
begin
WriteFunction(string(BindingManager.CodeGenOptions[cgPropGetPrefix] +
'Item(' + SIndexCode + ')'),
DataType, Indent);
end;
procedure TCodeWriter.WriteCollItemInit(const ItemTag, ItemInterface: string);
begin
Write('ItemTag := ''%s'';', [ItemTag], 1);
Write('ItemInterface := %s;', [ItemInterface], 1);
end;
procedure TCodeWriter.WriteCollItemProp(const DataType: string);
begin
Write('property Items[%s]: %s read %sItem; default;',
[SIndexCode, DataType, PropGetPrefix], 2);
end;
procedure TCodeWriter.WriteRegisterChildNode(const TagName,
ChildClass: string);
begin
Write('RegisterChildNode(''%s'', %s);', [TagName, ChildClass], 1);
end;
{ TForwardDecl }
procedure TForwardDecl.AfterConstruction;
begin
inherited;
WriteComment(SForwardDecl, 0, 2);
end;
{ TPropertyContainer }
destructor TPropertyContainer.Destroy;
var
I: Integer;
begin
inherited;
for I := High(CodeWriters) downto 0 do
CodeWriters[I].Free;
end;
procedure TPropertyContainer.Generate(const BindingInfo: IXMLComplexTypeBinding);
begin
FBindingInfo := BindingInfo;
FTypeDef := BindingInfo.ComplexTypeDef;
end;
procedure TPropertyContainer.AppendCode(const CodeLists: array of TCodeWriter);
var
I: Integer;
begin
for I := 0 to High(CodeLists) do
if CodeLists[I].Modified then
begin
AddStrings(CodeLists[I]);
CodeLists[I].Clear;
end;
end;
procedure TPropertyContainer.AppendCode;
begin
AppendCode(FCodeWriters);
end;
procedure TPropertyContainer.InitCodeWriters(CodeWriters: array of PCodeWriter;
CodeLines: array of string);
var
I: Integer;
begin
Assert(High(CodeWriters) = High(CodeLines));
if not Assigned(FCodeWriters) then
SetLength(FCodeWriters, High(CodeWriters) + 1);
for I := 0 to High(CodeWriters) do
begin
if not Assigned(FCodeWriters[I]) then
begin
FCodeWriters[I] := TCodeWriter.Create(BindingManager);
CodeWriters[I]^ := FCodeWriters[I];
end else
FCodeWriters[I].Clear;
if CodeLines[I] <> '' then
begin
FCodeWriters[I].Write(CodeLines[I], 1);
{ Reset Modified flag for default code }
FCodeWriters[I].Modified := False;
end;
end;
end;
procedure TPropertyContainer.WriteMethods;
begin
{ PureCollection list methods }
if BindingInfo.PureCollection then
with TypeDef.ElementDefList[0] do
WriteListBinding(BindingManager.GetBindingInfo(DataType));
end;
procedure TPropertyContainer.WriteListBinding(const ItemInfo: IXMLDataTypeBinding);
begin
end;
procedure TPropertyContainer.WriteCollectionMethods(Writer: TCodeWriter;
ItemInfo: IXMLDataTypeBinding; Indent: Integer);
begin
WriteCollAdd(Writer, ItemInfo, Indent);
WriteCollInsert(Writer, ItemInfo, Indent);
if not BindingInfo.PureCollection then
Writer.WriteCollGetItem(ItemInfo.IdentifierName, Indent);
end;
procedure TPropertyContainer.WriteCollAdd(Writer: TCodeWriter;
ItemInfo: IXMLDataTypeBinding; Indent: Integer);
begin
if ItemInfo.TypeDef.IsComplex then
Writer.WriteFunction(SAdd, ItemInfo.IdentifierName, Indent)
else
Writer.WriteFunction(SAdd, string(BindingManager.CodeGenOptions[cgNodeIntfBase]),
[BindingInfo.CollectionItemName], [ItemInfo.IdentifierName], Indent);
end;
procedure TPropertyContainer.WriteCollInsert(Writer: TCodeWriter;
ItemInfo: IXMLDataTypeBinding; Indent: Integer);
begin
if ItemInfo.TypeDef.IsComplex then
Writer.WriteFunction(SInsert, ItemInfo.IdentifierName,
[SIndex], [SInteger], Indent)
else
Writer.WriteFunction(SInsert, string(BindingManager.CodeGenOptions[cgNodeIntfBase]),
[SIndex, BindingInfo.CollectionItemName],
[SInteger, ItemInfo.IdentifierName], Indent);
end;
procedure TPropertyContainer.WriteProperties;
var
I: Integer;
PropBindInfo: IXMLPropertyBinding;
ListBindInfo: IXMLDataTypeListBinding;
begin
if Supports(BindingInfo, IXMLDataTypeListBinding, ListBindInfo) then
WriteListBinding(ListBindInfo.ItemBindInfo)
else
begin
{ Attributes }
for I := 0 to TypeDef.AttributeDefList.Count - 1 do
begin
PropBindInfo := BindingManager.GetBindingInfo(TypeDef.AttributeDefList[I]);
if PropBindInfo.Bound then
WriteProperty(PropBindInfo, False);
end;
{ Elements }
for I := 0 to TypeDef.ElementDefList.Count - 1 do
begin
PropBindInfo := BindingManager.GetBindingInfo(TypeDef.ElementDefList[I]);
if PropBindInfo.Bound then
WriteProperty(PropBindInfo, BindingInfo.PureCollection);
end;
end;
end;
procedure TPropertyContainer.WriteProperty(
const PropBindInfo: IXMLPropertyBinding; const Indexed: Boolean);
begin
end;
{ TIntfSectionEntry }
procedure TIntfSectionEntry.Generate(const BindingInfo: IXMLComplexTypeBinding);
begin
inherited;
BindingManager.ClassNameStr := '';
WriteDecl;
WriteMethods;
WriteProperties;
AppendCode;
Write(SEnd, 1);
end;
procedure TIntfSectionEntry.WriteDecl;
begin
WriteDeclComment(BindingInfo.ClassIdent);
end;
{ TIntfForward }
procedure TIntfForward.Generate(const BindingInfo: IXMLComplexTypeBinding);
begin
Write('%s = interface;', [BindingInfo.IdentifierName], 1);
end;
{ TIntfDecl }
procedure TIntfDecl.WriteDecl;
begin
InitCodeWriters([@GetMethods, @SetMethods, @PublicItems],
[SPropertyAccessors, '', SMethodsAndProps]);
with BindingInfo do
begin
WriteDeclComment(IdentifierName);
WriteIntfDecl(IdentifierName, AncestorInterface);
WriteGuid;
end;
end;
procedure TIntfDecl.WriteProperty(const PropBindInfo: IXMLPropertyBinding;
const Indexed: Boolean);
begin
with PropBindInfo do
begin
GetMethods.WriteGetMethod(IdentifierName, DataType, 2, Indexed);
if not PropReadOnly then
SetMethods.WriteSetMethod(IdentifierName, DataType, 2, Indexed);
PublicItems.WriteProperty(IdentifierName, DataType, not PropReadOnly, Indexed);
end;
end;
procedure TIntfDecl.WriteListBinding(const ItemInfo: IXMLDataTypeBinding);
begin
WriteCollectionMethods(PublicItems, ItemInfo, 2);
if not BindingInfo.PureCollection then
PublicItems.WriteCollItemProp(ItemInfo.IdentifierName);
end;
{ TClassForward }
procedure TClassForward.Generate(const BindingInfo: IXMLComplexTypeBinding);
begin
Write('%s = class;', [BindingInfo.ClassIdent], 1);
end;
{ TClassDecl }
procedure TClassDecl.WriteDecl;
begin
inherited;
InitCodeWriters([@PrivateItems, @GetMethods, @SetMethods,
@ProtectedItems, @PublicItems],
[SPrivate, '', '', '', SPublic]);
NeedsRegCode := False;
with BindingInfo do
WriteClassDecl(ClassIdent, AncestorClass, IdentifierName);
GetMethods.Write(SProtected, 1);
GetMethods.WriteComment(BindingInfo.IdentifierName, 2);
end;
procedure TClassDecl.WriteProperty(const PropBindInfo: IXMLPropertyBinding;
const Indexed: Boolean);
begin
with PropBindInfo do
begin
GetMethods.WriteGetMethod(IdentifierName, DataType, 2, Indexed);
if not PropReadOnly then
SetMethods.WriteSetMethod(IdentifierName, DataType, 2, Indexed);
if BindingType in [btComplexElement, btCollectionElement] then
NeedsRegCode := True;
if (BindingType = btCollectionElement) and not BindingInfo.PureCollection then
PrivateItems.WriteDataMember(IdentifierName, DataType);
end;
end;
procedure TClassDecl.WriteProperties;
begin
inherited;
if NeedsRegCode then
PublicItems.WriteAfterConstruction(SOverride, 2);
end;
procedure TClassDecl.WriteListBinding(const ItemInfo: IXMLDataTypeBinding);
begin
WriteCollectionMethods(ProtectedItems, ItemInfo, 2);
end;
{ TXMLBindingManager }
procedure TXMLBindingManager.AfterConstruction;
begin
FBindingAppInfoURI := SHttp+'/www.borland.com/schemas/delphi/6.0/XMLDataBinding';
FCodeGenOptions := TBindingOptions.Create(SCodeGen);
FCodeGenOptions.InitializeOptions(DefaultCode);
FNativeTypeMap := TBindingOptions.Create(SDataTypeMap);
FNativeTypeMap.InitializeOptions(DefaultTypeMap);
inherited;
end;
destructor TXMLBindingManager.Destroy;
begin
FreeAndNil(FNativeTypeMap);
FreeAndNil(FCodeGenOptions);
inherited;
end;
function TXMLBindingManager.GetBindableItems(const Schema: IXMLSchemaDef): IInterfaceList;
var
RepeatedSimpleTypes: IInterfaceList;
procedure AddDataType(const DataType: IXMLComplexTypeDef; Repeated: Boolean);
var
I: Integer;
BindingInfo: IXMLComplexTypeBinding;
begin
BindingInfo := GetBindingInfo(DataType);
if Repeated then
BindingInfo.Repeated := True;
if Result.IndexOf(DataType) = -1 then
begin
Result.Add(DataType);
for I := 0 to DataType.ElementDefList.Count - 1 do
with DataType.ElementDefList[I] do
if DataType.IsComplex then
AddDataType(DataType as IXMLComplexTypeDef, IsRepeating and not
BindingInfo.PureCollection)
{ SimpleType }
else if IsRepeating and not BindingInfo.PureCollection then
begin
GetBindingInfo(DataType).Repeated := True;
if RepeatedSimpleTypes.IndexOf(DataType) = -1 then
RepeatedSimpleTypes.Add(DataType);
end;
end;
end;
procedure CheckOrderDependencies;
var
I, BaseIndex: Integer;
BaseType: IXMLComplexTypeDef;
ComplexType: IXMLComplexTypeDef;
begin
I := 0;
while (I < Result.Count) and Supports(Result[I], IXMLComplexTypeDef, ComplexType) do
begin
if (ComplexType.BaseType <> nil) and ComplexType.BaseType.IsComplex then
begin
BaseType := ComplexType.BaseType as IXMLComplexTypeDef;
BaseIndex := Result.IndexOf(BaseType);
if BaseIndex > I then
begin
Result.Exchange(I, BaseIndex);
Dec(I);
end;
end;
Inc(I);
end;
end;
var
I: Integer;
begin
Result := TInterfaceList.Create;
RepeatedSimpleTypes := TInterfaceList.Create;
{ First iterate global elements and get the complex types there }
for I := 0 to Schema.ElementDefs.Count - 1 do
with Schema.ElementDefs[I] do
if DataType.IsComplex then
AddDataType(DataType as IXMLComplexTypeDef, IsRepeating);
{ Next iterate global Complex types and get any nested local types as well }
for I := 0 to Schema.ComplexTypes.Count - 1 do
AddDataType(Schema.Complextypes[I], False);
CheckOrderDependencies;
{ Append any repeated simple types so we can create collections for them too }
for I := 0 to RepeatedSimpleTypes.Count - 1 do
Result.Add(RepeatedSimpleTypes[I]);
end;
function TXMLBindingManager.GetBindingInfo(const ASchemaItem: IInterface): IXMLBindingInfo;
var
TypeDef: IXMLTypeDef;
TypedItem: IXMLTypedSchemaItem;
begin
if Supports(ASchemaItem, IXMLTypeDef, TypeDef) then
Result := GetBindingInfo(TypeDef)
else if Supports(ASchemaItem, IXMLTypedSchemaItem, TypedItem) then
Result := GetBindingInfo(TypedItem);
Assert(Assigned(Result));
end;
function TXMLBindingManager.GetBindingInfo(const TypeDef: IXMLTypeDef): IXMLDataTypeBinding;
begin
if TypeDef.IsComplex then
Result := TXMLComplexTypeBinding.Create(TypeDef as IXMLComplexTypeDef, Self)
else
Result := TXMLSimpleTypeBinding.Create(TypeDef as IXMLSimpleTypeDef, Self);
end;
function TXMLBindingManager.GetBindingInfo(const ComplexTypeDef: IXMLComplexTypeDef): IXMLComplexTypeBinding;
begin
Result := TXMLComplexTypeBinding.Create(ComplexTypeDef, Self);
end;
function TXMLBindingManager.GetBindingInfo(const PropertyItem: IXMLTypedSchemaItem): IXMLPropertyBinding;
begin
Result := TXMLPropertyBinding.Create(PropertyItem, Self);
end;
function TXMLBindingManager.GetListBindingInfo(const TypeDef: IXMLTypeDef): IXMLDataTypeListBinding;
begin
Result := TXMLDataTypeListBinding.Create(TypeDef, Self);
end;
function TXMLBindingManager.SchemaTypeToNativeType(const XMLType: Variant): string;
begin
if not VarIsNull(XMLType) then
Result := FNativeTypeMap[ExtractLocalName(XMLType)];
if Result = '' then
Result := FCodeGenOptions[cgDefaultDataType];
end;
procedure TXMLBindingManager.DoIdentifierCheck(var Identifier: string);
begin
if Assigned(FOnIdentifierCheck) then
FOnIdentifierCheck(Identifier);
end;
function TXMLBindingManager.GenerateBinding(const BindableItems: IInterfaceList;
const Writers: array of TCodeWriterClass): string;
var
CodeWriters: TCodeWriterArray;
procedure CreateCodeWriters;
var
I: Integer;
begin
SetLength(CodeWriters, High(Writers) + 1);
for I := 0 to High(Writers) do
CodeWriters[I]:= Writers[I].Create(Self);
end;
procedure FreeCodeWriters;
var
I: Integer;
begin
for I := High(CodeWriters) downto 0 do
CodeWriters[I].Free;
CodeWriters := nil;
end;
procedure DoGenerate(const BindingInfo: IXMLComplexTypeBinding);
var
I: Integer;
begin
for I := 0 to High(CodeWriters) do
CodeWriters[I].Generate(BindingInfo);
{ Genereate a list type as needed }
if BindingInfo.Repeated then
DoGenerate(GetListBindingInfo(BindingInfo.ComplexTypeDef));
end;
var
I: Integer;
ComplexTypeDef: IXMLComplexTypeDef;
ComplexBinding: IXMLComplexTypeBinding;
begin
Result := '';
CreateCodeWriters;
for I := 0 to BindableItems.Count - 1 do
begin
if Supports(BindableItems[I], IXMLComplexTypeDef, ComplexTypeDef) then
begin
ComplexBinding := GetBindingInfo(ComplexTypeDef);
if ComplexBinding.Bound then
DoGenerate(ComplexBinding);
end else
DoGenerate(GetListBindingInfo(BindableItems[I] as IXMLTypeDef));
end;
{ Concatenate all of the code writer code into list }
for I := 0 to High(CodeWriters) do
Result := Result + CodeWriters[I].Text;
FreeCodeWriters;
end;
function TXMLBindingManager.GenerateBinding(const BindableItem: IXMLComplexTypeDef;
const Writers: array of TCodeWriterClass): string;
var
ItemList: IInterfaceList;
begin
ItemList := TInterfaceList.Create;
ItemList.Add(BindableItem);
Result := GenerateBinding(ItemList, Writers);
end;
{ Property Accessors }
function TXMLBindingManager.GetBindingAppInfoURI: DOMString;
begin
Result := FBindingAppInfoURI;
end;
function TXMLBindingManager.GetCodeGenOptions: TBindingOptions;
begin
Result := FCodeGenOptions;
end;
function TXMLBindingManager.GetNativeTypeMap: TBindingOptions;
begin
Result := FNativeTypeMap;
end;
procedure TXMLBindingManager.SetBindingAppInfoURI(const Value: DOMString);
begin
FBindingAppInfoURI := Value;
end;
procedure TXMLBindingManager.SetOnIdentifierCheck(const Value: TIdentifierCheckEvent);
begin
FOnIdentifierCheck := Value;
end;
function TXMLBindingManager.GetClassNameStr: string;
begin
Result := FClassNameStr;
end;
procedure TXMLBindingManager.SetClassNameStr(const Value: string);
begin
FClassNameStr := Value;
end;
end.
|
unit DBScript;
interface
uses
Classes, ForestConsts, ForestTypes;
type
TDBScript = class(TObject)
private
FLines: TStringList;
procedure SetLineHeader;
procedure SetLineFooter;
function GetNewID(const Values: TValuesRec): AnsiString;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure SetScriptHeader;
procedure AddDelete(const RegionID, ForestryID, ReportQuarter, ReportYear: Integer);
procedure AddInsert(Values: TValuesRec);
procedure SetScriptFooter;
function GetText: AnsiString;
end;
implementation
uses
SysUtils, Data, NsUtils;
//---------------------------------------------------------------------------
{ TDBScript }
procedure TDBScript.AddDelete(const RegionID, ForestryID, ReportQuarter, ReportYear: Integer);
var
SQLLine: AnsiString;
begin
SQLLine := Format(S_DB_DELETE_SCRIPT_FORMAT, [S_DB_TABLE_NAME, ForestryID, ReportQuarter, ReportYear]);
SetLineHeader();
FLines.Append('-- Удаление строк отчета');
FLines.Append(SQLLine);
SetLineFooter();
end;
//---------------------------------------------------------------------------
procedure TDBScript.AddInsert(Values: TValuesRec);
function RepairDot(const C: Currency): AnsiString;
begin
Result := FloatToStr(C);
Result := StringReplace(Result, ',', '.', [rfReplaceAll]);
end;
var
SQLLine: AnsiString;
DateStr: AnsiString;
NewID: AnsiString;
begin
DateTimeToString(DateStr, 'dd.mm.yyyy', Date());
NewID := GetNewID(Values);
SQLLine := Format(
S_DB_INSERT_SCRIPT_FORMAT_BEGIN +
S_DB_INSERT_SCRIPT_FORMAT_FLD1 +
S_DB_INSERT_SCRIPT_FORMAT_FLD2 +
S_DB_INSERT_SCRIPT_FORMAT_FLD3 +
S_DB_INSERT_SCRIPT_FORMAT_FLD4 +
S_DB_INSERT_SCRIPT_FORMAT_FLD5 +
S_DB_INSERT_SCRIPT_FORMAT_FLD6 +
S_DB_INSERT_SCRIPT_FORMAT_FLD7 +
S_DB_INSERT_SCRIPT_FORMAT_FLD8 +
S_DB_INSERT_SCRIPT_FORMAT_FLD9 +
S_DB_INSERT_SCRIPT_FORMAT_FLD10 +
S_DB_INSERT_SCRIPT_FORMAT_FLD11 +
S_DB_INSERT_SCRIPT_FORMAT_FLD12 +
S_DB_INSERT_SCRIPT_FORMAT_FLD13 +
S_DB_INSERT_SCRIPT_FORMAT_FLD14 +
S_DB_INSERT_SCRIPT_FORMAT_MIDDLE +
S_DB_INSERT_SCRIPT_FORMAT_VAL1 +
S_DB_INSERT_SCRIPT_FORMAT_VAL2 +
S_DB_INSERT_SCRIPT_FORMAT_VAL3 +
S_DB_INSERT_SCRIPT_FORMAT_VAL4 +
S_DB_INSERT_SCRIPT_FORMAT_VAL5 +
S_DB_INSERT_SCRIPT_FORMAT_VAL6 +
S_DB_INSERT_SCRIPT_FORMAT_VAL7 +
S_DB_INSERT_SCRIPT_FORMAT_END,
[S_DB_TABLE_NAME, NewID, DateStr, Values.ReportQuarter, Values.ReportYear,
Values.ForestryID, Values.LocalForestryID, Values.Quarter,
Values.Patch, Values.LanduseID, Values.DefenseCategoryID,
Values.MainSpeciesID, Values.DamageSpeciesID, Values.DamageReasonID,
Values.F10, Values.F11, RepairDot(Values.F12),
RepairDot(Values.F13), RepairDot(Values.F14), RepairDot(Values.F15),
RepairDot(Values.F16), RepairDot(Values.F17), RepairDot(Values.F18),
RepairDot(Values.F19), RepairDot(Values.F20), RepairDot(Values.F21),
RepairDot(Values.F22), RepairDot(Values.F23), RepairDot(Values.F24),
RepairDot(Values.F25), RepairDot(Values.F26), RepairDot(Values.F27),
RepairDot(Values.F28), RepairDot(Values.F29), Values.F30,
RepairDot(Values.F31), RepairDot(Values.F32), RepairDot(Values.F33),
RepairDot(Values.F34), RepairDot(Values.F35), RepairDot(Values.F36),
RepairDot(Values.F37), RepairDot(Values.F38), RepairDot(Values.F39),
RepairDot(Values.F40), RepairDot(Values.F41), RepairDot(Values.F42),
RepairDot(Values.F43), RepairDot(Values.F44), RepairDot(Values.F45),
RepairDot(Values.F46), RepairDot(Values.F47), RepairDot(Values.F48),
RepairDot(Values.F49), Values.F50, RepairDot(Values.F51),
RepairDot(Values.F52), RepairDot(Values.F53), RepairDot(Values.F54),
RepairDot(Values.F55), RepairDot(Values.F56), Values.PestStatus,
Values.PestID, RepairDot(Values.F59), RepairDot(Values.F60),
RepairDot(Values.F61), RepairDot(Values.F62), RepairDot(Values.F63),
RepairDot(Values.F64), RepairDot(Values.F65), RepairDot(Values.F66),
RepairDot(Values.F67), RepairDot(Values.F68)]
);
SetLineHeader();
FLines.Append('-- Вставка строки нового отчета');
FLines.Append(SQLLine);
SetLineFooter();
end;
//---------------------------------------------------------------------------
procedure TDBScript.Clear;
begin
FLines.Clear();
end;
//---------------------------------------------------------------------------
constructor TDBScript.Create;
begin
inherited;
FLines := TStringList.Create();
end;
//---------------------------------------------------------------------------
destructor TDBScript.Destroy;
begin
FLines.Free();
inherited;
end;
//---------------------------------------------------------------------------
function TDBScript.GetNewID(const Values: TValuesRec): AnsiString;
var
ADay, AMonth, AYear: Word;
begin
Result := '';
DecodeDate(Date(), AYear, AMonth, ADay);
Result := Result + ExtendLeft(IntToStr(Values.RegionID), 3, '0');
Result := Result + ExtendLeft(IntToStr(Values.ForestryID), 3, '0');
Result := Result + ExtendLeft(IntToStr(Values.LocalForestryID), 3, '0');
Result := Result + ExtendLeft(IntToStr(Values.Quarter), 3, '0');
Result := Result + ExtendLeft(IntToStr(Values.Patch), 3, '0');
Result := Result + IntToStr(Values.ReportQuarter);
Result := Result + ExtendLeft(IntToStr(AMonth), 3, '0');
Result := Result + ExtendLeft(IntToStr(AYear), 3, '0');
end;
//---------------------------------------------------------------------------
function TDBScript.GetText: AnsiString;
var
I: Integer;
begin
Result := '';
for I := 0 to FLines.Count - 1 do
Result := Result + #13#10 + FLines[I];
end;
//---------------------------------------------------------------------------
procedure TDBScript.SetLineFooter;
begin
if S_DB_SCRIPT_LN_FOOTER <> '' then
FLines.Append(S_DB_SCRIPT_LN_FOOTER);
end;
//---------------------------------------------------------------------------
procedure TDBScript.SetLineHeader;
begin
if S_DB_SCRIPT_LN_HEADER <> '' then
FLines.Append(S_DB_SCRIPT_LN_HEADER);
end;
//---------------------------------------------------------------------------
procedure TDBScript.SetScriptFooter;
begin
if S_DB_SCRIPT_FOOTER <> '' then
FLines.Append(S_DB_SCRIPT_FOOTER);
end;
//---------------------------------------------------------------------------
procedure TDBScript.SetScriptHeader;
begin
if S_DB_SCRIPT_HEADER <> '' then
FLines.Insert(0, S_DB_SCRIPT_HEADER);
end;
end.
|
Unit TERRA_Session;
{$I terra.inc}
Interface
Uses TERRA_Utils, TERRA_IO, TERRA_OS;
{-$DEFINE ALLOWBACKUPS}
Const
DefaultSessionFileName = 'session';
Type
KeyValue = Record
Key:AnsiString;
Value:AnsiString;
End;
Session = Class(TERRAObject)
Protected
_Path:AnsiString;
_FileName:AnsiString;
_Data:Array Of KeyValue;
_DataCount:Integer;
_Read:Boolean;
_Backup:Boolean;
Function getKeyID(Key:AnsiString):Integer;
Function GetDefaultFilePath():AnsiString;
Function FixPath(S:AnsiString):AnsiString;
Function GetDataCount: Integer;
Function GetBackUpFileName():AnsiString;
Public
Constructor Create(FileName:AnsiString; Backup:Boolean = False);
Destructor Destroy; Override;
Procedure SetValue(Key, Value:AnsiString);
Function GetValue(Key:AnsiString):AnsiString;
Function HasKey(Key:AnsiString):Boolean;
Function LoadFromFile(SourceFile:AnsiString):Boolean;
Function LoadFromStream(Source:MemoryStream):Boolean;
Function GetKeyByIndex(Index:Integer):AnsiString;
Function GetSaveFileName():AnsiString;
Procedure Clear;
Procedure SetFileName(FileName:AnsiString);
Procedure SetPath(Path:AnsiString);
Procedure CopyKeys(Other:Session);
Function Save(Target:Stream = Nil; Callback:ProgressNotifier = Nil):Boolean;
Function Restore():Boolean;
Property KeyCount:Integer Read GetDataCount;
Property Path:AnsiString Read _Path;
Property FileName:AnsiString Read _FileName;
End;
Implementation
Uses TERRA_FileIO, TERRA_Application, TERRA_FileUtils, TERRA_Unicode, TERRA_Log, TERRA_ZLib;
Const
SessionHeader:FileHeader = 'TESS';
Function IsNumber(S:AnsiString):Boolean;
Var
I:Integer;
Begin
For I:=1 To Length(S) Do
If (S[I]>='0') And (S[I]<='9') Then
Begin
IntToString(1);
End Else
Begin
Result := False;
Exit;
End;
Result := True;
End;
Function OldSessionCypher(const Str:AnsiString):AnsiString;
Var
I:Integer;
Begin
Result := '';
For I:=1 To Length(Str) Do
result := Result + Char(255 - Ord(Str[I]));
End;
Function InvalidString(S:AnsiString):Boolean;
Var
I,Len:Integer;
Begin
Len := ucs2_Length(S);
For I:=1 To Len Do
If (ucs2_ascii(S, I)<#32) Then
Begin
Result := True;
Exit;
End;
Result := False;
End;
Const
ZBufferSize = 1024 * 64;
Function Session.LoadFromStream(Source:MemoryStream):Boolean;
Var
I,J ,N ,Count, Len:Integer;
Key, Path, S, S2:AnsiString;
Pref:MemoryStream;
Data:Array Of Byte;
Header:FileHeader;
OldSession:Boolean;
ZLIB:z_stream;
Begin
_DataCount := 0;
If (Source.Size<4) Then
Begin
Result := False;
Log(logError,'Session','Corrupted session file');
Exit;
End;
Source.Read(@Header, 4);
If Header=SessionHeader Then
Begin
OldSession := False;
Source.Read(@Len, 4);
// Fill record
FillChar(ZLIB,SizeOf(ZLIB),0);
Pref := MemoryStream.Create(Len);
ZLIB.next_in := Source.Buffer;
Inc(ZLIB.next_in, Source.Position);
ZLIB.avail_in := Source.Size - Source.Position;
ZLIB.next_out := Pref.Buffer;
ZLIB.avail_out := Pref.Size;
inflateInit(ZLIB);
inflate(ZLIB, Z_NO_FLUSH);
inflateEnd(ZLIB);
End Else
Begin
Pref := Source;
Pref.Seek(0);
OldSession := True;
End;
While Not Pref.EOF Do
Begin
Pref.ReadString(S);
If (OldSession) And (S<>'') And (S[1]='@') Then
S := OldSessionCypher(System.Copy(S, 2, MaxInt));
//I := Self.getKeyID(S);
Key := S;
If Pref.EOF Then
Break;
Pref.ReadString(S2);
If (S2<>'') And (S2[1]='&') Then
Begin
Count := Length(S2) - 1;
SetLength(Data, Count);
If (Length(S2)>=2) Then
Move(S2[2], Data[0], Count)
Else
For J:=0 To Pred(Count) Do
Data[J] := 0;
S2 := '';
For J:=0 To Pred(Count) Do
S2 := S2 + IntToString(Data[J]);
End;
If (InvalidString(Key)) Or (InvalidString(S2)) Then
Continue;
I := _DataCount;
Inc(_DataCount);
SetLength(_Data, _DataCount);
_Data[I].Key := Key;
_Data[I].Value := S2;
//Log(logDebug,'Session','Session: '+_Data[I].Key+'='+_Data[I].Value);
End;
If Not OldSession Then
Pref.Destroy;
_Read := True;
Log(logDebug,'Session','Loaded session file, '+IntToString(_DataCount)+' items found.');
Result := True;
End;
Function Session.LoadFromFile(SourceFile:AnsiString):Boolean;
Var
Temp:MemoryStream;
Begin
If Not FileStream.Exists(SourceFile) Then
Begin
Result := False;
Log(logError,'Session','Could not load session file: '+SourceFile);
Exit;
End;
Temp := MemoryStream.Create(SourceFile);
Result := LoadFromStream(Temp);
Temp.Destroy();
End;
Function Session.GetSaveFileName:AnsiString;
Var
S:AnsiString;
Begin
S := FixPath(Path);
If S<>'' Then
S := S + PathSeparator;
Result := S + _FileName;
End;
Function Session.Save(Target:Stream = Nil; Callback:ProgressNotifier = Nil):Boolean;
Var
ZLIB:z_stream;
OutBuff:Pointer;
Ret, Rem:Integer;
B:Byte;
I, J, N, Len:Integer;
Dest, Temp:MemoryStream;
Pref:Stream;
Key, S, S2, S3:AnsiString;
FileName:AnsiString;
Header:FileHeader;
Begin
FileName := Self.GetSaveFileName();
{$IFDEF ALLOWBACKUPS}
If (FileStream.Exists(FileName)) And (_Backup) Then
Begin
FileStream.CopyFile(FileName, Self.GetBackUpFileName());
End;
{$ENDIF}
Dest := MemoryStream.Create(1024, Nil, smDefault Or smLargeAlloc);
If Assigned(Callback) Then
Callback.Reset(2);
For I:=0 To Pred(_DataCount) Do
Begin
If Assigned(Callback) Then
Callback.Notify(I/Pred(_DataCount));
Dest.WriteString(_Data[I].Key);
Dest.WriteString(_Data[I].Value);
End;
If Assigned(Callback) Then
Callback.NextPhase();
Dest.Truncate();
// Fill record
FillChar(ZLIB,SizeOf(ZLIB),0);
// Set internal record information
GetMem(OutBuff, ZBufferSize);
ZLIB.next_in := Dest.Buffer;
ZLIB.avail_in := Dest.Size;
// Init compression
DeflateInit_(@zlib, Z_DEFAULT_COMPRESSION, zlib_version, SizeOf(z_Stream));
Len := Dest.Size;
Temp := MemoryStream.Create(Len);
// With ZLIBStream, ZLIBStream.ZLIB Do
// Compress all the data avaliable to compress
Repeat
If Assigned(Callback) Then
Callback.Notify(ZLIB.avail_in/Dest.Size);
ZLIB.next_out := OutBuff;
ZLIB.avail_out := ZBufferSize;
Ret := deflate(ZLIB, Z_FINISH);
Rem := ZBufferSize - ZLIB.avail_out;
If Rem>0 Then
Temp.Write(OutBuff, Rem);
Until (Ret<>Z_OK);
Temp.Truncate();
// Terminates compression
DeflateEnd(zlib);
/// Free internal record
FreeMem(OutBuff);
If (Ret = Z_STREAM_END) Then
Begin
Header := SessionHeader;
Pref := FileStream.Create(FileName);
Pref.Write(@Header, 4);
Pref.Write(@Len, 4);
Temp.Copy(Pref);
Result := Pref.Size>=Temp.Size;
If Assigned(Target) Then
Begin
If (Target.Size<Pref.Size) And (Target Is MemoryStream) Then
MemoryStream(Target).Resize(Pref.Size);
Temp.Seek(0);
Target.Write(@Header, 4);
Target.Write(@Len, 4);
Temp.Copy(Target);
Temp.Seek(0);
End;
Pref.Destroy;
_Read := True;
End Else
Result := False;
Temp.Destroy;
Dest.Destroy;
End;
Function Session.getKeyID(Key:AnsiString):Integer;
Var
I:Integer;
Begin
Key := UpStr(Key);
Result := -1;
For I:=0 To Pred(_DataCount) Do
If _Data[I].Key = Key Then
Begin
Result := I;
Exit;
End;
Result := _DataCount;
Inc(_DataCount);
SetLength(_Data, _DataCount);
_Data[Result].Key := Key;
End;
Procedure Session.SetValue(Key,Value:AnsiString);
Var
N:Integer;
Begin
N := Self.getKeyID(Key);
_Data[N].Value := Value;
End;
Function Session.GetValue(Key:AnsiString):AnsiString;
Var
N:Integer;
S:AnsiString;
Begin
If (Not _Read) Then
Begin
S := Self.GetSaveFileName();
LoadFromFile(S);
End;
N := Self.getKeyID(Key);
Result := _Data[N].Value;
End;
Destructor Session.Destroy;
Begin
End;
Function Session.GetKeyByIndex(Index: Integer):AnsiString;
Begin
If (Index>=0) And (Index<_DataCount) Then
Begin
Result := _Data[Index].Key;
End Else
Result := '';
End;
Function Session.Restore:Boolean;
Var
FileName:AnsiString;
Begin
Result := False;
FileName := Self.GetBackUpFileName();
If Not FileStream.Exists(FileName) Then
Exit;
Self.LoadFromFile(FileName);
Result := True;
End;
Function Session.GetDefaultFilePath:AnsiString;
Begin
If Assigned(Application.Instance()) Then
Result := Application.Instance.DocumentPath + PathSeparator
Else
Result := '';
End;
Function Session.GetBackUpFileName:AnsiString;
Begin
(* {$IFDEF ANDROID}
Result := '/sdcard/';
{$ELSE}
Result := Self.GetDefaultFilePath();
{$ENDIF}*)
Result := Path + PathSeparator + Application.Instance.Client.GetAppID() +'_'+ GetFileName(_FileName, True) + '.bak';
End;
Constructor Session.Create(FileName:AnsiString; Backup:Boolean);
Begin
If (FileName = '') Then
FileName := DefaultSessionFileName;
_Backup := Backup;
Self._Path := Self.GetDefaultFilePath();
Self._FileName := FileName;
End;
Procedure Session.SetPath(Path:AnsiString);
Begin
Self._Path := Path;
End;
Function Session.FixPath(S:AnsiString):AnsiString;
Begin
Result := S;
If (Result<>'') And ((Result[Length(Result)]='/') Or (Result[Length(Result)]='\')) Then
Result := Copy(Result, 1, Pred(Length(Result)));
End;
Procedure Session.CopyKeys(Other: Session);
Var
I:Integer;
Begin
If Other = Nil Then
Exit;
Self._DataCount := Other._DataCount;
SetLength(Self._Data, Self._DataCount);
For I:=0 To Pred(Self._DataCount) Do
Begin
_Data[I].Key := Other._Data[I].Key;
_Data[I].Value := Other._Data[I].Value;
End;
End;
Procedure Session.SetFileName(FileName:AnsiString);
Begin
If FileName<>'' Then
_FileName := LowStr(FileName);
End;
Procedure Session.Clear;
Begin
Self._DataCount := 0;
SetLength(_Data, 0);
_Read := False;
End;
Function Session.GetDataCount: Integer;
Begin
If (Not _Read) Then
Begin
LoadFromFile(Self.GetSaveFileName());
End;
Result := _DataCount;
End;
Function Session.HasKey(Key:AnsiString): Boolean;
Var
I:Integer;
Begin
If (Not _Read) Then
Begin
LoadFromFile(Self.GetSaveFileName());
End;
Key := UpStr(Key);
For I:=0 To Pred(_DataCount) Do
If _Data[I].Key = Key Then
Begin
Result := True;
Exit;
End;
Result := False;
End;
Initialization
Finalization
End.
|
{-----------------------------------------------------------------------------
Unit Name: udBase
Author: n0mad
Version: 1.2.8.x
Creation: 15.05.2004
Purpose: DB container, default transactions
History:
-----------------------------------------------------------------------------}
unit udBase;
interface
{$I kinode01.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, FIBDatabase,
pFIBDatabase, Db, FIB, FIBDataSet, pFIBDataSet, SIBEABase, SIBFIBEA, ExtCtrls,
pFIBErrorHandler, FIBQuery, pFIBQuery, pFIBStoredProc;
type
TMixDS = record
DS_UID: Integer;
DS_Name: string[40];
DS_InsUpd: Integer;
DS_FN_Kod: string[40];
DS_FN_Ver: string[40];
DS_MaxVal: Int64;
end;
Tdm_Base = class(TDataModule)
db_kino2: TpFIBDatabase;
tr_Common_Read2: TpFIBTransaction;
tr_Common_Write2: TpFIBTransaction;
ds_Branch: TpFIBDataSet;
ds_Globset: TpFIBDataSet;
ds_Zal: TpFIBDataSet;
ds_Place: TpFIBDataSet;
ds_Cost: TpFIBDataSet;
ds_Repert: TpFIBDataSet;
ds_Ticket: TpFIBDataSet;
ds_Genre: TpFIBDataSet;
ds_Tariff: TpFIBDataSet;
ds_Film: TpFIBDataSet;
ds_Seans: TpFIBDataSet;
ds_Changelog_Max: TpFIBDataSet;
ds_Changelog_List: TpFIBDataSet;
ev_Changelog: TSIBfibEventAlerter;
tr_Event_Write3: TpFIBTransaction;
ds_Changelog_Buf: TpFIBDataSet;
tmr_Buffer: TTimer;
ds_Moves: TpFIBDataSet;
tr_Session_Finish2: TpFIBTransaction;
sp_Create_Tariff_Version: TpFIBStoredProc;
tr_Tariff_Write: TpFIBTransaction;
tr_Oper_Mod_Write: TpFIBTransaction;
sp_Oper_Mod: TpFIBStoredProc;
tr_Oper_Clr_Write: TpFIBTransaction;
sp_Oper_Clr: TpFIBStoredProc;
ds_Rep_Instant: TpFIBDataSet;
ds_Rep_Ticket: TpFIBDataSet;
ds_Rep_Daily_Odeums: TpFIBDataSet;
ds_Rep_Daily_Repert: TpFIBDataSet;
ds_Rep_Daily_Moves: TpFIBDataSet;
dsrc_Rep_Daily_Odeums: TDataSource;
dsrc_Rep_Daily_Repert: TDataSource;
dsrc_Rep_Daily_Moves: TDataSource;
ds_Price: TpFIBDataSet;
ds_Abjnl: TpFIBDataSet;
ds_Rep_Daily_Abonem: TpFIBDataSet;
dsrc_Rep_Daily_Abonem: TDataSource;
ds_Rep_Ticket_Odeums: TpFIBDataSet;
dsrc_Rep_Ticket_Odeums: TDataSource;
ds_Rep_Ticket_Tickets: TpFIBDataSet;
dsrc_Rep_Ticket_Tickets: TDataSource;
ds_Rep_Daily_Presale: TpFIBDataSet;
dsrc_Rep_Daily_Presale: TDataSource;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure ds_DatasetBeforeOpen(DataSet: TDataSet);
procedure ds_DatasetAfterPostOrCancelOrDelete(DataSet: TDataSet);
procedure ds_DatasetBeforePost(DataSet: TDataSet);
procedure ds_DatasetBeforeDelete(DataSet: TDataSet);
procedure ds_DatasetBeforeClose(DataSet: TDataSet);
procedure db_kino2Connect(Sender: TObject);
procedure ev_ChangelogEventAlert(Sender: TObject; EventName: string; EventCount: Integer);
procedure tmr_BufferTimer(Sender: TObject);
procedure db_kino2BeforeDisconnect(Sender: TObject);
procedure db_kino2ErrorRestoreConnect(Database: TFIBDatabase; E: EFIBError; var Actions:
TOnLostConnectActions);
procedure db_kino2LostConnect(Database: TFIBDatabase; E: EFIBError; var Actions:
TOnLostConnectActions);
procedure eh_Kino2FIBErrorEvent(Sender: TObject; ErrorValue: EFIBError;
KindIBError: TKindIBError; var DoRaise: Boolean);
procedure ds_MovesFieldChange(Sender: TField);
procedure ds_MovesAfterRefresh(DataSet: TDataSet);
procedure ds_RepertFieldChange(Sender: TField);
procedure ds_RepertAfterRefresh(DataSet: TDataSet);
procedure ds_RepertAfterDelete(DataSet: TDataSet);
procedure ds_Rep_Daily_BeforeOpen(DataSet: TDataSet);
private
{ Private declarations }
FChangelog_Max_Value: Int64;
FChangelog_Buf_Busy: Boolean;
FEventsRegistered: Boolean;
FEventProcessed: Boolean;
t1_event_locked_real: Boolean;
t1_event_locked_timed: Boolean;
t1_non_upd_rec: Integer;
FGetMaxProcessed: Boolean;
FEventTableNames: TStrings;
function GetChangelog_Max_Value: Int64;
procedure SetChangelog_Max_Value(Value: Int64);
function Get_DataSetsID_By_Name(DataSet_ID: Integer): TMixDS;
// ------------------------------
procedure All_Events_Unregister(Sender: TObject);
function Changelog_Events_Reg(const AddEvents: Boolean; Dataset: TDataset): integer;
procedure ChangelogEvent(const EventName: string; const EventCount: Integer;
const BufferOnly: Boolean);
procedure Prepare_Buf_Dataset;
procedure Clear_Buf_Dataset(const TableName: string);
public
{ Public declarations }
function DataModule2Connected: Boolean;
function DataBase2Path: string;
property Changelog_Max_Value: Int64 read GetChangelog_Max_Value write SetChangelog_Max_Value;
end;
var
dm_Base: Tdm_Base;
implementation
uses
Bugger, urCommon, StrConsts, Math, uhOper, uhMain;
{$R *.DFM}
const
UnitName: string = 'udBase';
RF_DataSetsCount = 34;
RF_DataSets: array[0..RF_DataSetsCount] of TMixDS = (
(DS_UID: 0; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 1; DS_Name: 'DBUSER'; DS_InsUpd: 0;
DS_FN_Kod: 'DBUSER_KOD'; DS_FN_Ver: 'DBUSER_VER'; DS_MaxVal: 0),
(DS_UID: 2; DS_Name: 'BRANCH'; DS_InsUpd: 0;
DS_FN_Kod: 'BRANCH_KOD'; DS_FN_Ver: 'BRANCH_VER'; DS_MaxVal: 0),
(DS_UID: 3; DS_Name: 'GLOBAL'; DS_InsUpd: 0;
DS_FN_Kod: 'GLOBAL_KOD'; DS_FN_Ver: 'GLOBAL_VER'; DS_MaxVal: 0),
(DS_UID: 4; DS_Name: 'ODEUM'; DS_InsUpd: 0;
DS_FN_Kod: 'ODEUM_KOD'; DS_FN_Ver: 'ODEUM_VER'; DS_MaxVal: 0),
(DS_UID: 5; DS_Name: 'SEAT'; DS_InsUpd: 0;
DS_FN_Kod: 'SEAT_KOD'; DS_FN_Ver: 'SEAT_VER'; DS_MaxVal: 0),
(DS_UID: 6; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 7; DS_Name: 'TICKET'; DS_InsUpd: 0;
DS_FN_Kod: 'TICKET_KOD'; DS_FN_Ver: 'TICKET_VER'; DS_MaxVal: 0),
(DS_UID: 8; DS_Name: 'TARIFF'; DS_InsUpd: 0;
DS_FN_Kod: 'TARIFF_KOD'; DS_FN_Ver: 'TARIFF_VER'; DS_MaxVal: 0),
(DS_UID: 9; DS_Name: 'COST'; DS_InsUpd: 0;
DS_FN_Kod: 'COST_KOD'; DS_FN_Ver: 'COST_VER'; DS_MaxVal: 0),
(DS_UID: 10; DS_Name: 'GENRE'; DS_InsUpd: 0;
DS_FN_Kod: 'GENRE_KOD'; DS_FN_Ver: 'GENRE_VER'; DS_MaxVal: 0),
(DS_UID: 11; DS_Name: 'FILM'; DS_InsUpd: 0;
DS_FN_Kod: 'FILM_KOD'; DS_FN_Ver: 'FILM_VER'; DS_MaxVal: 0),
(DS_UID: 12; DS_Name: 'SEANS'; DS_InsUpd: 0;
DS_FN_Kod: 'SEANS_KOD'; DS_FN_Ver: 'SEANS_VER'; DS_MaxVal: 0),
(DS_UID: 13; DS_Name: 'REPERT'; DS_InsUpd: 0;
DS_FN_Kod: 'REPERT_KOD'; DS_FN_Ver: 'REPERT_VER'; DS_MaxVal: 0),
(DS_UID: 14; DS_Name: 'CINEMA'; DS_InsUpd: 0;
DS_FN_Kod: 'CINEMA_KOD'; DS_FN_Ver: 'CINEMA_VER'; DS_MaxVal: 0),
(DS_UID: 15; DS_Name: 'MAKET'; DS_InsUpd: 0;
DS_FN_Kod: 'MAKET_KOD'; DS_FN_Ver: 'MAKET_VER'; DS_MaxVal: 0),
(DS_UID: 16; DS_Name: 'CARD'; DS_InsUpd: 0;
DS_FN_Kod: 'CARD_KOD'; DS_FN_Ver: 'CARD_VER'; DS_MaxVal: 0),
(DS_UID: 17; DS_Name: 'INVITER'; DS_InsUpd: 0;
DS_FN_Kod: 'INVITER_KOD'; DS_FN_Ver: 'INVITER_VER'; DS_MaxVal: 0),
(DS_UID: 18; DS_Name: 'VISITGRP'; DS_InsUpd: 0;
DS_FN_Kod: 'VISITGRP_KOD'; DS_FN_Ver: 'VISITGRP_VER'; DS_MaxVal: 0),
(DS_UID: 19; DS_Name: 'OPER'; DS_InsUpd: 3;
DS_FN_Kod: 'OPER_KOD'; DS_FN_Ver: 'OPER_VER'; DS_MaxVal: 0),
(DS_UID: 20; DS_Name: 'ABONEM'; DS_InsUpd: 0;
DS_FN_Kod: 'ABONEM_KOD'; DS_FN_Ver: 'ABONEM_VER'; DS_MaxVal: 0),
(DS_UID: 21; DS_Name: 'PRICE'; DS_InsUpd: 0;
DS_FN_Kod: 'PRICE_KOD'; DS_FN_Ver: 'PRICE_VER'; DS_MaxVal: 0),
(DS_UID: 22; DS_Name: 'ABJNL'; DS_InsUpd: 0;
DS_FN_Kod: 'ABJNL_KOD'; DS_FN_Ver: 'ABJNL_VER'; DS_MaxVal: 0),
(DS_UID: 23; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 24; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 701; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 702; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 703; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 704; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 705; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 706; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 707; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 708; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 709; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0),
(DS_UID: 710; DS_Name: ''; DS_InsUpd: 0; DS_FN_Kod: ''; DS_FN_Ver: ''; DS_MaxVal: 0)
);
function Tdm_Base.DataModule2Connected: Boolean;
begin
Result := false;
if Assigned(db_kino2) then
begin
// Result := db_kino2.Connected;
{
laTerminateApp - the application will be closed automatically
laCloseConnect - the Active property in all FIBPlus objects will equal false
laIgnore - a lost of connection will be ignored
laWaitRestore - the Active property in all FIBPlus objects will equal false and then WaitForRestoreConnect will be called.
}
Result := db_kino2.ExTestConnected(laIgnore);
end;
DBConnected2 := Result;
Update_DB_Conn_State;
end;
function Tdm_Base.DataBase2Path: string;
begin
Result := '<unknown>';
if Assigned(db_kino2) then
Result := db_kino2.DBName;
end;
procedure Tdm_Base.DataModuleCreate(Sender: TObject);
const
ProcName: string = 'DataModuleDestroy';
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
DBConnected2 := False;
FChangelog_Max_Value := -1;
FChangelog_Buf_Busy := false;
FEventsRegistered := false;
FEventProcessed := false;
FGetMaxProcessed := false;
t1_event_locked_real := false;
t1_event_locked_timed := false;
t1_non_upd_rec := 0;
ds_Changelog_List.Active := false;
{construct the list}
FEventTableNames := TStringList.Create;
try
FEventTableNames.Clear;
except
on E: Exception do
begin
FEventTableNames := nil;
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'FEventTableNames.Clear failed.');
end;
end;
if ev_Changelog.Registered then
ev_Changelog.RegisterEvents;
{
if (not Dataset_event_locked) and fibDataset.Active then
try
if Assigned(fibDataset.FN(s_SESSIONID)) then
begin
fibDataset.FN(s_SESSIONID).AsString := IntToStr(UserID);
DEBUGMessEnh(0, UnitName, ProcName, s_SESSIONID + ' = [' +
fibDataset.FN(s_SESSIONID).AsString + ']');
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error during (P) ' + s_SESSIONID +
' assigning ' + s_SESSIONID + ' = (' + IntToStr(UserID) + ')');
end;
end;
}
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.DataModuleDestroy(Sender: TObject);
const
ProcName: string = 'DataModuleDestroy';
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
if Assigned(dm_Base) then
try
dm_Base.All_Events_Unregister(nil);
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'All_Events_Unregister failed.');
end;
end;
{destroy the list object}
FEventTableNames.Free;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
function Tdm_Base.GetChangelog_Max_Value: Int64;
const
ProcName: string = 'GetChangelog_Max_Value';
var
sRes: string;
begin
Result := -1;
// -----------------------------------------------------------
if FEventsRegistered then
begin
Result := FChangelog_Max_Value;
end
else
begin
// -----------------------------------------------------------
if FGetMaxProcessed then
begin
while FGetMaxProcessed do
Application.ProcessMessages;
Result := FChangelog_Max_Value;
end
else
begin
// -----------------------------------------------------------
FGetMaxProcessed := true;
try
with ds_Changelog_Max do
try
if Assigned(ParamByName(s_IN_CHANGE_NUM)) then
begin
try
// -----------------------------------------------------------
if Active then
Close;
DEBUGMessEnh(0, UnitName, ProcName, s_IN_CHANGE_NUM + ' = [' +
IntToStr(FChangelog_Max_Value) + ']');
ParamByName(s_IN_CHANGE_NUM).AsString := IntToStr(FChangelog_Max_Value);
// Обновляем Select-sql из репозитория, если нужно
Prepare;
Open;
if Assigned(FN(s_MAX_CHANGE_KOD)) then
begin
sRes := FN(s_MAX_CHANGE_KOD).AsString;
DEBUGMessEnh(0, UnitName, ProcName, s_MAX_CHANGE_KOD + ' = [' + sRes + ']');
Result := StrToInt(sRes);
end;
Close;
// -----------------------------------------------------------
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Reopening for (' + Name + ') is failed.');
end;
end;
{$IFDEF Debug_Level_6}
DEBUGMessEnh(0, UnitName, ProcName, Name + '.Active = ' + BoolYesNo[Active]
+ ', RecordCount = (' + IntToStr(RecordCount) + ')');
{$ENDIF}
end
else
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Param [' + s_IN_CHANGE_NUM + '] is missed.');
Result := 0;
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error getting Changelog_Max.');
end;
end;
finally
FChangelog_Max_Value := Result;
FGetMaxProcessed := false;
end;
// -----------------------------------------------------------
end;
end;
// -----------------------------------------------------------
end;
procedure Tdm_Base.SetChangelog_Max_Value(Value: Int64);
const
ProcName: string = 'SetChangelog_Max_Value';
begin
if FChangelog_Max_Value <> Value then
begin
FChangelog_Max_Value := Value;
DEBUGMessEnh(0, UnitName, ProcName, 'Setting Changelog_Max = [' + IntToStr(Value) + ']');
end;
end;
function Tdm_Base.Get_DataSetsID_By_Name(DataSet_ID: Integer): TMixDS;
begin
if (DataSet_ID <= 0) or (DataSet_ID > High(RF_DataSets)) then
begin
Result.DS_UID := 0;
Result.DS_Name := '';
Result.DS_InsUpd := 0;
Result.DS_FN_Kod := '';
Result.DS_FN_Ver := '';
Result.DS_MaxVal := 0;
end
else
Result := RF_DataSets[DataSet_ID];
end;
procedure Tdm_Base.All_Events_Unregister(Sender: TObject);
const
ProcName: string = 'All_Events_Unregister';
var
i: integer;
tmp_Component: TComponent;
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
with dm_Base do
for i := 0 to ComponentCount - 1 do
begin
tmp_Component := Components[i];
try
if (tmp_Component is TSIBfibEventAlerter) then
begin
with (tmp_Component as TSIBfibEventAlerter) do
begin
if Registered then
begin
DEBUGMessEnh(0, UnitName, ProcName, Name + '.UnRegisterEvents');
UnRegisterEvents;
end;
end;
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, Name + '.UnRegisterEvents failed.');
end;
end;
end;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
function Tdm_Base.Changelog_Events_Reg(const AddEvents: Boolean; Dataset: TDataset): Integer;
const
ProcName: string = 'Changelog_Events_Reg';
var
Exists0_Table, Exists1_InsertEvent, Exists2_UpdateEvent, Exists3_KillEvent, ExistsAny, ExistsAll,
WasRegistered: Boolean;
Index0_Table, Index1_Insert, Index2_Update, Index3_Kill: Integer;
Res: Int64;
iDataset_ID: Integer;
sEventTable: string;
iEventTable_ID: Integer;
var_MixDS: TMixDS;
begin
Result := FEventTableNames.Count;
sEventTable := '';
iEventTable_ID := 0;
if (DataSet is TpFIBDataSet) then
begin
iDataset_ID := (Dataset as TpFIBDataSet).DataSet_ID;
var_MixDS := Get_DataSetsID_By_Name(iDataset_ID);
sEventTable := Trim(var_MixDS.DS_Name);
iEventTable_ID := iDataset_ID;
end;
if (sEventTable = '') or (iEventTable_ID = 0) then
Exit;
if FEventProcessed or t1_event_locked_real then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Waiting... - EventReg(' + BoolYesNo[AddEvents]
+ ') for [' + sEventTable + ']');
while (FEventProcessed or t1_event_locked_real) and DataModule2Connected do
Application.ProcessMessages;
DEBUGMessEnh(0, UnitName, ProcName, 'Continue... - EventReg(' + BoolYesNo[AddEvents]
+ ') for [' + sEventTable + ']');
end;
if (not DataModule2Connected) then
begin
// todo: Restore connect
DEBUGMessEnh(0, UnitName, ProcName, 'Connection lost - EventReg(' + BoolYesNo[AddEvents]
+ ') for [' + sEventTable + ']');
Exit;
end;
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
DEBUGMessEnh(0, UnitName, ProcName, 'Enter into - EventReg(' + BoolYesNo[AddEvents]
+ ') for [' + sEventTable + ']');
FEventProcessed := true;
WasRegistered := ev_Changelog.Registered;
FEventsRegistered := WasRegistered and (FEventTableNames.Count > 0);
DEBUGMessEnh(0, UnitName, ProcName, 'EvsReged = ' + BoolYesNo[FEventsRegistered] +
', EvTableNames = (' + FEventTableNames.CommaText + ')');
try
// -----------------------------------------------------------
Index0_Table := FEventTableNames.IndexOfName(sEventTable);
Exists0_Table := (Index0_Table > -1);
// -----------------------------------------------------------
Index1_Insert := ev_Changelog.Events.IndexOf(s_EVENT_PREFIX + sEventTable +
s_EVENT_POSTFIX1_INSERT);
Exists1_InsertEvent := (Index1_Insert > -1);
// -----------------------------------------------------------
Index2_Update := ev_Changelog.Events.IndexOf(s_EVENT_PREFIX + sEventTable +
s_EVENT_POSTFIX2_UPDATE);
Exists2_UpdateEvent := (Index2_Update > -1);
// -----------------------------------------------------------
Index3_Kill := ev_Changelog.Events.IndexOf(s_EVENT_PREFIX + sEventTable +
s_EVENT_POSTFIX3_KILL);
Exists3_KillEvent := (Index3_Kill > -1);
// -----------------------------------------------------------
ExistsAny := (Exists1_InsertEvent or Exists2_UpdateEvent or Exists3_KillEvent);
ExistsAll := (Exists1_InsertEvent and Exists2_UpdateEvent and Exists3_KillEvent);
// -----------------------------------------------------------
if AddEvents then
begin
// =========================
if not Exists0_Table then
FEventTableNames.AddObject(sEventTable + '=' + IntToStr(iEventTable_ID), Dataset);
// =========================
if (not ExistsAll) then
begin
if WasRegistered then
begin
ev_Changelog.UnRegisterEvents;
end;
if not Exists1_InsertEvent then
ev_Changelog.Events.Add(s_EVENT_PREFIX + sEventTable + s_EVENT_POSTFIX1_INSERT);
if not Exists2_UpdateEvent then
ev_Changelog.Events.Add(s_EVENT_PREFIX + sEventTable + s_EVENT_POSTFIX2_UPDATE);
if not Exists3_KillEvent then
ev_Changelog.Events.Add(s_EVENT_PREFIX + sEventTable + s_EVENT_POSTFIX3_KILL);
end;
end
else
begin
// =========================
if Exists0_Table then
begin
Index0_Table := FEventTableNames.IndexOfName(sEventTable);
FEventTableNames.Delete(Index0_Table);
end;
// =========================
if ExistsAny then
begin
if WasRegistered then
begin
ev_Changelog.UnRegisterEvents;
end;
if Exists1_InsertEvent then
begin
Index1_Insert := ev_Changelog.Events.IndexOf(s_EVENT_PREFIX + sEventTable +
s_EVENT_POSTFIX1_INSERT);
ev_Changelog.Events.Delete(Index1_Insert);
end;
if Exists2_UpdateEvent then
begin
Index2_Update := ev_Changelog.Events.IndexOf(s_EVENT_PREFIX + sEventTable +
s_EVENT_POSTFIX2_UPDATE);
ev_Changelog.Events.Delete(Index2_Update);
end;
if Exists3_KillEvent then
begin
Index3_Kill := ev_Changelog.Events.IndexOf(s_EVENT_PREFIX + sEventTable +
s_EVENT_POSTFIX3_KILL);
ev_Changelog.Events.Delete(Index3_Kill);
end;
end;
end;
// -----------------------------------------------------------
if FEventTableNames.Count > 0 then
begin
if not ev_Changelog.Registered then
begin
Clear_Buf_Dataset(sEventTable);
Res := Changelog_Max_Value;
DEBUGMessEnh(0, UnitName, ProcName, 'Changelog_Max = [' + IntToStr(Res) + ']');
ev_Changelog.RegisterEvents;
end;
end
else
begin
if ev_Changelog.Registered then
begin
ev_Changelog.UnRegisterEvents;
end;
Clear_Buf_Dataset('');
end;
// -----------------------------------------------------------
finally
Result := FEventTableNames.Count;
FEventsRegistered := ev_Changelog.Registered and (FEventTableNames.Count > 0);
FEventProcessed := false;
end;
// -----------------------------------------------------------
DEBUGMessEnh(0, UnitName, ProcName, 'EvsReged = ' + BoolYesNo[FEventsRegistered] +
', EvTableNames = (' + FEventTableNames.CommaText + ')');
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.ds_DatasetBeforeOpen(DataSet: TDataSet);
const
ProcName: string = 'ds_DatasetBeforeOpen';
{$IFDEF Debug_Level_5}
var
i: Integer;
{$ENDIF}
begin
// -----------------------------------------------------------
if (DataSet is TpFIBDataSet) then
with (DataSet as TpFIBDataSet) do
begin
// -----------------------------------------------------------
try
if Assigned(ParamByName(s_IN_SESSION_ID)) then
begin
ParamByName(s_IN_SESSION_ID).AsVariant := Null;
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error during (O) ' + s_IN_SESSION_ID +
' assigning null.');
end;
end;
// -----------------------------------------------------------
{$IFDEF Debug_Level_5}
DEBUGMessEnh(0, UnitName, ProcName, Name + '.DataSet_ID = ' + IntToStr(DataSet_ID));
for i := 0 to (Params.Count - 1) do
begin
DEBUGMessEnh(0, UnitName, ProcName, Params[i].Name
+ ' = (' + BoolYesNo[Params[i].IsNull] + ') [' + Params[i].AsString + ']');
end; // for
{$ENDIF}
// -----------------------------------------------------------
if (DataSet_ID > 0) and (DataSet_ID <= RF_DataSetsCount) then
begin
{
if Length(InsertSQL.Text) = 0 then
begin
InsertSQL.Text := s_No_Action;
DEBUGMessEnh(0, UnitName, ProcName, 'Setting InsertSQL for [' + Name + ']');
end;
}
Changelog_Events_Reg(true, Dataset);
end; // if
end; // with
// -----------------------------------------------------------
end;
procedure Tdm_Base.ds_DatasetAfterPostOrCancelOrDelete(DataSet: TDataSet);
const
ProcName: string = 'ds_DatasetAfterPCD';
begin
// -----------------------------------------------------------
if (DataSet is TpFIBDataSet) then
with (DataSet as TpFIBDataSet) do
begin
try
if not (t1_event_locked_real or FEventProcessed or FChangelog_Buf_Busy) then
begin
if (ds_Changelog_Buf.RecordCount > 0) then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Calling ChangelogEvent() now');
ChangelogEvent('', 0, true);
end;
tmr_Buffer.Enabled := false;
end
else if not (UpdateSQL.Text = s_No_Action) then
begin
if not tmr_Buffer.Enabled then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Setting ChangelogEvent() on timer');
tmr_Buffer.Enabled := true;
end;
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'ChangelogEvent() failed.');
end;
end; // try
end; // with
// -----------------------------------------------------------
end;
procedure Tdm_Base.ds_DatasetBeforePost(DataSet: TDataSet);
const
ProcName: string = 'ds_DatasetBeforePost';
{$IFDEF Debug_Level_5}
var
i: Integer;
{$ENDIF}
begin
// -----------------------------------------------------------
if (DataSet is TpFIBDataSet) then
with (DataSet as TpFIBDataSet) do
begin
// -----------------------------------------------------------
if (DataSet.State in [dsInsert, dsEdit]) then
if Assigned(ParamByName(s_IN_SESSION_ID)) then
try
begin
if t1_event_locked_real then
ParamByName(s_IN_SESSION_ID).AsVariant := Null
else
ParamByName(s_IN_SESSION_ID).AsString := IntToStr(Global_Session_ID);
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error during (P) ' + s_IN_SESSION_ID +
' assigning ' + s_IN_SESSION_ID + ' = (' + IntToStr(Global_Session_ID) + ')');
end;
end;
// -----------------------------------------------------------
{$IFDEF Debug_Level_5}
DEBUGMessEnh(0, UnitName, ProcName, Name + '.DataSet_ID = ' + IntToStr(DataSet_ID));
{$ENDIF}
{$IFDEF Debug_Level_5}
for i := 0 to (Params.Count - 1) do
begin
DEBUGMessEnh(0, UnitName, ProcName, Params[i].Name
+ ' = (' + BoolYesNo[Params[i].IsNull] + ') [' + Params[i].AsString + ']');
end; // for
{$ENDIF}
{$IFDEF Debug_Level_5}
for i := 0 to (FieldCount - 1) do
begin
DEBUGMessEnh(0, UnitName, ProcName, Fields[i].FieldName
+ ' = (' + BoolYesNo[Fields[i].IsNull] + ') [' + Fields[i].AsString + ']');
end; // for
{$ENDIF}
// -----------------------------------------------------------
end; // with
// -----------------------------------------------------------
end;
procedure Tdm_Base.ds_DatasetBeforeDelete(DataSet: TDataSet);
const
ProcName: string = 'ds_DatasetBeforeDelete';
{$IFDEF Debug_Level_5}
var
i: Integer;
{$ENDIF}
begin
// -----------------------------------------------------------
if (DataSet is TpFIBDataSet) then
with (DataSet as TpFIBDataSet) do
begin
// -----------------------------------------------------------
if (DataSet.State in [dsBrowse]) then
try
if Assigned(ParamByName(s_IN_SESSION_ID)) then
begin
if t1_event_locked_real then
ParamByName(s_IN_SESSION_ID).AsVariant := Null
else
ParamByName(s_IN_SESSION_ID).AsString := IntToStr(Global_Session_ID);
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error during (P) ' + s_IN_SESSION_ID +
' assigning ' + s_IN_SESSION_ID + ' = (' + IntToStr(Global_Session_ID) + ')');
end;
end; // try
// -----------------------------------------------------------
{$IFDEF Debug_Level_5}
DEBUGMessEnh(0, UnitName, ProcName, Name + '.DataSet_ID = ' + IntToStr(DataSet_ID));
{$ENDIF}
{$IFDEF Debug_Level_5}
for i := 0 to (Params.Count - 1) do
begin
DEBUGMessEnh(0, UnitName, ProcName, Params[i].Name
+ ' = (' + BoolYesNo[Params[i].IsNull] + ') [' + Params[i].AsString + ']');
end; // for
{$ENDIF}
{$IFDEF Debug_Level_5}
for i := 0 to (FieldCount - 1) do
begin
DEBUGMessEnh(0, UnitName, ProcName, Fields[i].FieldName
+ ' = (' + BoolYesNo[Fields[i].IsNull] + ') [' + Fields[i].AsString + ']');
end; // for
{$ENDIF}
// -----------------------------------------------------------
end; // with
// -----------------------------------------------------------
end;
procedure Tdm_Base.ds_DatasetBeforeClose(DataSet: TDataSet);
const
ProcName: string = 'ds_DatasetBeforeClose';
begin
// -----------------------------------------------------------
if (DataSet is TpFIBDataSet) then
with (DataSet as TpFIBDataSet) do
begin
if (DataSet_ID > 0) and (DataSet_ID <= RF_DataSetsCount) then
begin
Changelog_Events_Reg(false, Dataset);
end;
end;
// -----------------------------------------------------------
end;
procedure Tdm_Base.Prepare_Buf_Dataset;
const
ProcName: string = 'Prepare_Buf_Dataset';
var
reccount: Integer;
tmp_ChangeKod_Max: Int64;
str_ChangeKod: string;
begin
//
FChangelog_Buf_Busy := ds_Changelog_Buf.Active and FChangelog_Buf_Busy;
if FChangelog_Buf_Busy then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Waiting... - PrepareBuf');
while FChangelog_Buf_Busy do
Application.ProcessMessages;
DEBUGMessEnh(0, UnitName, ProcName, 'Continue... - PrepareBuf');
end;
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
with ds_Changelog_Buf do
begin
FChangelog_Buf_Busy := true;
try
try
Active := false;
{
SelectSQL.Text :=
'select CHANGE_KOD, SESSION_ID, CHANGE_STAMP, CHANGE_ACTION,' +
' CHANGED_TABLE_ID, CHANGED_TABLE_NAM, CHANGED_TABLE_KOD, CHANGED_TABLE_VER' +
' from SP_CHANGELOG_RF(:IN_SESSION_ID, :IN_CHANGE_NUM, :IN_TABLE_LIST)';
}
tmp_ChangeKod_Max := Changelog_Max_Value;
// Копируем Select-sql для идентичности полей
if ((ds_Changelog_List.DataSet_ID <> 0)
and (DataSet_ID <> ds_Changelog_List.DataSet_ID)) then
begin
SelectSQL.Text := ds_Changelog_List.SelectSQL.Text;
DataSet_ID := ds_Changelog_List.DataSet_ID;
// Должен прибыть пустой набор
if Assigned(Params.FindParam(s_IN_SESSION_ID)) then
ParamByName(s_IN_SESSION_ID).AsString := IntToStr(Global_Session_ID);
if Assigned(Params.FindParam(s_IN_CHANGE_NUM)) then
ParamByName(s_IN_CHANGE_NUM).AsString := IntToStr(tmp_ChangeKod_Max);
if Assigned(Params.FindParam(s_IN_TABLE_LIST)) then
ParamByName(s_IN_TABLE_LIST).AsString := '';
Open;
First;
Last;
reccount := RecordCount;
DEBUGMessEnh(0, UnitName, ProcName, 'RecordCount0 = (' + IntToStr(reccount) + ')');
if (reccount > 0) then
begin
str_ChangeKod := '';
if Assigned(FN(s_CHANGE_KOD)) then
try
str_ChangeKod := FN(s_CHANGE_KOD).AsString;
tmp_ChangeKod_Max := StrToInt(str_ChangeKod);
Changelog_Max_Value := tmp_ChangeKod_Max;
finally
DEBUGMessEnh(0, UnitName, ProcName, s_CHANGE_KOD + ' = (' + str_ChangeKod + ')');
end;
end;
// Обновили Select-sql из репозитория
Close;
end;
DataSet_ID := 0;
// DEBUGMessEnh(0, UnitName, ProcName, 'SelectSQL.Text = (' + SelectSQL.Text + ')');
if Assigned(Params.FindParam(s_IN_SESSION_ID)) then
ParamByName(s_IN_SESSION_ID).AsString := IntToStr(Global_Session_ID);
if Assigned(Params.FindParam(s_IN_CHANGE_NUM)) then
ParamByName(s_IN_CHANGE_NUM).AsString := IntToStr(tmp_ChangeKod_Max);
if Assigned(Params.FindParam(s_IN_TABLE_LIST)) then
ParamByName(s_IN_TABLE_LIST).AsString := '';
// ---------
// Чтобы операции (I,U,D) были без обращений к базе
// ---------
// Гуляя по исходникам библиотеки FIBPlus, я обнаружил, что если
// Поставить "No Action", то SQL-операторы на сервер не передаются.
// Основная проблема была в том, что если оставить их пустыми, то
// методы Append, Edit будут недоступны. Однако при Delete этот фокус
// не пройдет, см. ниже.
// ---------
InsertSQL.Text := s_No_Action;
UpdateSQL.Text := s_No_Action;
DeleteSQL.Text := s_No_Action;
// Держим открытым до дисконнекта
Open;
Last; // Это для определения реального числа записей в RecordCount
First;
reccount := RecordCount;
DEBUGMessEnh(0, UnitName, ProcName, 'RecordCount1 = (' + IntToStr(reccount) + ')');
// Очищаем буфер-датасет
while (not Eof) do
try
Delete;
except
Next;
end;
reccount := RecordCount;
DEBUGMessEnh(0, UnitName, ProcName, 'RecordCount2 = (' + IntToStr(reccount) + ')');
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error preparing Buffer_Dataset.');
end;
end;
finally
FChangelog_Buf_Busy := false;
end;
DEBUGMessEnh(0, UnitName, ProcName, 'Buffer_Dataset.Active = [' + BoolYesNo[Active] + ']');
end;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.Clear_Buf_Dataset(const TableName: string);
const
ProcName: string = 'Clear_Buf_Dataset';
var
Field_Exists: Boolean;
reccount: Integer;
begin
if not ds_Changelog_Buf.Active then
begin
FChangelog_Buf_Busy := false;
Exit;
end;
//
if FChangelog_Buf_Busy or t1_event_locked_real then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Waiting... - ClearBuf(' + TableName + ')');
while FChangelog_Buf_Busy or t1_event_locked_real do
Application.ProcessMessages;
DEBUGMessEnh(0, UnitName, ProcName, 'Continue... - ClearBuf(' + TableName + ')');
end;
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
DEBUGMessEnh(0, UnitName, ProcName, 'Enter into - ClearBuf(' + TableName + ')');
with ds_Changelog_Buf do
if Active then
begin
FChangelog_Buf_Busy := true;
try
try
First;
Field_Exists := Assigned(FN(s_CHANGED_TABLE_NAM));
reccount := RecordCount;
DEBUGMessEnh(0, UnitName, ProcName, 'RecordCount1 = (' + IntToStr(reccount) + ')');
// Очищаем буфер-датасет
if (TableName = '') or (not Field_Exists) then
while (not Eof) do
try
Delete;
except
Next;
end
else
while (not Eof) do
begin
try
if (FN(s_CHANGED_TABLE_NAM).AsString <> TableName) then
Next
else
Delete;
except
Next;
end;
end;
reccount := RecordCount;
DEBUGMessEnh(0, UnitName, ProcName, 'RecordCount2 = (' + IntToStr(reccount) + ')');
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error during Buf_Dataset clearing.');
end;
end;
finally
FChangelog_Buf_Busy := false;
end;
end;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.ChangelogEvent(const EventName: string; const EventCount: Integer;
const BufferOnly: Boolean);
const
ProcName: string = 'ChangelogEvent';
var
str_TableName, str_TableKod, str_TableVer: string;
fibDS: TpFIBDataSet;
j, iz_MixDS: Integer;
z_MixDS: TMixDS;
updrec, reccnt: Integer;
sIns, sUpd, sDel: string;
bIns, bUpd, bDel: boolean;
iKey: Integer;
Saved_EnabledControls: Boolean;
var_ChangeKod_Max: Int64;
// -----------------------------------------------------------
procedure ProcessChangelog(ds_Buffer: TpFIBDataSet);
var
i: Integer;
bProcess, bHandled, bFieldTypeError, bRecordFound: Boolean;
begin
bProcess := false;
if (Assigned(ds_Buffer) and (ds_Buffer is TpFIBDataSet)
and ds_Buffer.Active and (ds_Buffer.RecordCount > 0)) then
bProcess := true;
if bProcess then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Processing ' + ds_Buffer.Name + '...');
for i := 0 to FEventTableNames.Count - 1 do
begin
str_TableName := FEventTableNames.Names[i];
iz_MixDS := StrToInt(FEventTableNames.Values[str_TableName]);
z_MixDS := Get_DataSetsID_By_Name(iz_MixDS);
str_TableKod := z_MixDS.DS_FN_Kod;
str_TableVer := z_MixDS.DS_FN_Ver;
fibDS := nil;
if (FEventTableNames.Objects[i] is TpFIBDataSet) then
fibDS := (FEventTableNames.Objects[i] as TpFIBDataSet);
if Assigned(fibDS) and (str_TableName <> '')
and (str_TableKod <> '') and (str_TableVer <> '') then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Cycle for [' + str_TableName + '], ' +
fibDS.Name + '.State = ' + ds_States[fibDS.State] + '');
ds_Buffer.First;
// -----------------------------------------------------------
// Если редактируем, то уходим - сделаем это в другой раз,
// можно здесь пользователя предупредить об обновлениях
// -----------------------------------------------------------
if fibDS.State <> dsBrowse then
begin
if ds_Buffer <> ds_Changelog_Buf then
// fibds.EnableControls;
while not ds_Buffer.Eof do
try
try
if (ds_Buffer.FN(s_CHANGED_TABLE_ID).AsInteger = z_MixDS.DS_UID) then
begin
ds_Changelog_Buf.Append;
//--
ds_Changelog_Buf.FN(s_CHANGE_KOD).AsVariant :=
ds_Buffer.FN(s_CHANGE_KOD).AsVariant;
//--
ds_Changelog_Buf.FN(s_SESSION_ID).AsString :=
ds_Buffer.FN(s_SESSION_ID).AsString;
//--
ds_Changelog_Buf.FN(s_CHANGE_STAMP).AsDateTime :=
ds_Buffer.FN(s_CHANGE_STAMP).AsDateTime;
//--
ds_Changelog_Buf.FN(s_CHANGE_ACTION).AsString :=
ds_Buffer.FN(s_CHANGE_ACTION).AsString;
//--
ds_Changelog_Buf.FN(s_CHANGED_TABLE_ID).AsInteger :=
ds_Buffer.FN(s_CHANGED_TABLE_ID).AsInteger;
//--
ds_Changelog_Buf.FN(s_CHANGED_TABLE_NAM).AsString :=
ds_Buffer.FN(s_CHANGED_TABLE_NAM).AsString;
//--
ds_Changelog_Buf.FN(s_CHANGED_TABLE_KOD).AsVariant :=
ds_Buffer.FN(s_CHANGED_TABLE_KOD).AsVariant;
//--
ds_Changelog_Buf.FN(s_CHANGED_TABLE_VER).AsVariant :=
ds_Buffer.FN(s_CHANGED_TABLE_VER).AsVariant;
//--
try
ds_Changelog_Buf.Post;
Inc(reccnt);
except
ds_Changelog_Buf.Cancel;
end;
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, fibds.Name +
'.Refresh failed.');
end;
end;
// Обновляем "возраст", обработанные записи выбраны больше не будут
var_ChangeKod_Max := Max(var_ChangeKod_Max,
StrToInt(ds_Buffer.FN(s_CHANGE_KOD).AsString));
finally
ds_Buffer.Next;
end; // while and finally
end
else
begin
with fibds do
begin
Saved_EnabledControls := not ControlsDisabled;
// Запоминаем значение ключа, чтобы потом поставить
// пользователя на нужную запись
iKey := FN(str_TableKod).AsInteger;
DisableControls;
end;
try
with fibds do
begin
// -----------------------------------------------------------
// Гуляя по исходникам библиотеки FIBPlus, я обнаружил, что если
// Поставить "No Action", то SQL-операторы на сервер не передаются.
// Основная проблема была в том, что если оставить их пустыми, то
// методы Append, Edit будут недоступны. Однако при Delete этот фокус
// не пройдет, см. ниже.
// -----------------------------------------------------------
sIns := InsertSQL.Text;
bIns := CanInsert;
InsertSQL.Text := s_No_Action;
sUpd := UpdateSQL.Text;
bUpd := CanEdit;
UpdateSQL.Text := s_No_Action;
sDel := DeleteSQL.Text;
bDel := CanDelete;
DeleteSQL.Text := s_No_Action;
end;
while not ds_Buffer.Eof do
begin
bHandled := false;
try
if (ds_Buffer.FN(s_CHANGED_TABLE_ID).AsInteger = z_MixDS.DS_UID) then
begin
// -----------------------------------------------------------
// Добавляем
// -----------------------------------------------------------
if ds_Buffer.FN(s_CHANGE_ACTION).AsString = s_Inserted then
begin
with ds_Buffer do
begin
DEBUGMessEnh(0, UnitName, ProcName, fibds.Name + '.Append(' +
str_TableKod + ' = ' + FN(s_CHANGED_TABLE_KOD).AsString + ', ' +
str_TableVer + ' = ' + FN(s_CHANGED_TABLE_VER).AsString + ')');
fibds.Append;
bFieldTypeError := false;
if fibds.FN(str_TableKod).DataType in [ftInteger, ftSmallint, ftWord] then
begin
fibds.FN(str_TableKod).AsInteger := FN(s_CHANGED_TABLE_KOD).AsInteger;
end
else
try
fibds.FN(str_TableKod).AsVariant := FN(s_CHANGED_TABLE_KOD).AsVariant;
except
bFieldTypeError := true;
end;
fibds.FN(str_TableVer).AsInteger := 0;
{ fibds.FN(str_TableVer).AsInteger := FN(s_CHANGED_TABLE_VER).AsInteger; }
end;
if bFieldTypeError then
fibds.Cancel
else
try
fibds.Post;
Dec(t1_non_upd_rec);
try
fibds.Refresh;
bHandled := true;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, fibds.Name +
'.Refresh failed.');
end;
end;
except
fibds.Cancel;
end;
end;
// -----------------------------------------------------------
// При удалении мы не можем четко узнать число записей,
// нужных для обновления - к ним примешиваются записи, удаленные и
// этим клиентом, но они, в таком случае, не будут найдены по Locate
// -----------------------------------------------------------
if ds_Buffer.FN(s_CHANGE_ACTION).AsString = s_Killed then
begin
dec(t1_non_upd_rec);
dec(updrec);
end;
bRecordFound := false;
if fibds.FN(str_TableKod).DataType in [ftInteger, ftSmallint, ftWord] then
begin
bRecordFound := fibds.Locate(str_TableKod,
ds_Buffer.FN(s_CHANGED_TABLE_KOD).AsInteger, []);
end
else
try
bRecordFound := fibds.Locate(str_TableKod,
ds_Buffer.FN(s_CHANGED_TABLE_KOD).AsVariant, []);
except
end;
if bRecordFound then
begin
// -----------------------------------------------------------
// удаляем, запись была не наша.
// -----------------------------------------------------------
try
if ds_Buffer.FN(s_CHANGE_ACTION).AsString = s_Killed then
begin
with ds_Buffer do
begin
DEBUGMessEnh(0, UnitName, ProcName, fibds.Name + '.Delete(' +
str_TableKod + ' = ' + FN(s_CHANGED_TABLE_KOD).AsString + ', ' +
str_TableVer + ' = ' + FN(s_CHANGED_TABLE_VER).AsString + ')');
end;
fibds.Delete;
inc(updrec);
bHandled := true;
end;
except
end;
// -----------------------------------------------------------
// Обновляем
// -----------------------------------------------------------
if ds_Buffer.FN(s_CHANGE_ACTION).AsString = s_Updated then
begin
with ds_Buffer do
begin
DEBUGMessEnh(0, UnitName, ProcName, fibds.Name + '.Edit(' +
str_TableKod + ' = ' + FN(s_CHANGED_TABLE_KOD).AsString + ', ' +
str_TableVer + ' = ' + FN(s_CHANGED_TABLE_VER).AsString + ')');
fibds.Edit;
bFieldTypeError := false;
if fibds.FN(str_TableKod).DataType in [ftInteger, ftSmallint, ftWord] then
begin
fibds.FN(str_TableKod).AsInteger := FN(s_CHANGED_TABLE_KOD).AsInteger;
end
else
try
fibds.FN(str_TableKod).AsVariant := FN(s_CHANGED_TABLE_KOD).AsVariant;
except
bFieldTypeError := true;
end;
fibds.FN(str_TableVer).AsInteger := 0;
{ fibds.FN(str_TableVer).AsInteger := FN(s_CHANGED_TABLE_VER).AsInteger; }
end;
if bFieldTypeError then
fibds.Cancel
else
try
fibds.Post;
Dec(t1_non_upd_rec);
try
fibds.Refresh;
bHandled := true;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, fibds.Name +
'.Refresh failed.');
end;
end;
except
fibds.Cancel;
end;
end;
end;
// Обновляем "возраст", обработанные записи выбраны больше не будут
var_ChangeKod_Max := Max(var_ChangeKod_Max,
StrToInt(ds_Buffer.FN(s_CHANGE_KOD).AsString));
end;
finally
if bHandled then
try
ds_Buffer.Delete;
except
ds_Buffer.Next;
end
else
ds_Buffer.Next;
end; // finally
end; // while
finally
// восстанавливаем все обратно
fibds.InsertSQL.Text := sIns;
fibds.UpdateSQL.Text := sUpd;
fibds.DeleteSQL.Text := sDel;
if fibds.State = dsBrowse then
fibds.Locate(str_TableKod, iKey, []);
if Saved_EnabledControls then
fibds.EnableControls;
{
Label2.Caption := '';
if t1_non_upd_rec <> 0 then
Label2.Caption := 'Невозможно обновить ' + IntToStr(t1_non_upd_rec) + ' записей'
else
Label2.Caption := 'Другими пользователями обновлено ' + IntToStr(updrec) +
' записей';
}
end;
end;
// -----------------------------------------------------------
end
else
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Cannot do cycle for [' + str_TableName + '].');
end;
end; // for
end; // if
end;
var
Saved_Dataset_ID: Integer;
str_TableList, str_TableIns, str_TableUpd: string;
begin
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
if t1_event_locked_real then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Waiting... - t1_event_locked_real');
while t1_event_locked_real do
Application.ProcessMessages;
DEBUGMessEnh(0, UnitName, ProcName, 'Continue... - t1_event_locked_real');
end;
DEBUGMessEnh(1, UnitName, ProcName, '>>>--->>>--->>>');
// -----------------------------------------------------------
DEBUGMessEnh(0, UnitName, ProcName, 'EventName = (' + EventName + '), Count = (' +
IntToStr(EventCount) + ')');
try
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// t1_event_locked_real введен мною для того, чтобы предотвратить
// повторный вызов этого события, если находимся в нем.
// Может и излишняя предосторожность, но пусть,
// к тому же пригодилось в событии выше
// -----------------------------------------------------------
if 1 = 1 then
begin
// -----------------------------------------------------------
t1_event_locked_real := true;
tmr_Buffer.Enabled := false;
// -----------------------------------------------------------
Saved_Dataset_ID := ds_Changelog_List.DataSet_ID;
var_ChangeKod_Max := Changelog_Max_Value;
try
with ds_Changelog_List do
begin
Active := false;
if (ds_Changelog_List.Tag = 0) then
begin
// Меняем туда и обратно, чтобы автоматически установились нужные флаги и опции
DataSet_ID := 0;
DataSet_ID := Saved_Dataset_ID;
// Должен прибыть пустой набор
if Assigned(Params.FindParam(s_IN_SESSION_ID)) then
ParamByName(s_IN_SESSION_ID).AsVariant := Null;
if Assigned(Params.FindParam(s_IN_CHANGE_NUM)) then
ParamByName(s_IN_CHANGE_NUM).AsVariant := Null;
if Assigned(Params.FindParam(s_IN_TABLE_LIST)) then
ParamByName(s_IN_TABLE_LIST).AsVariant := Null;
if Assigned(Params.FindParam(s_IN_TABLE_INS)) then
ParamByName(s_IN_TABLE_INS).AsVariant := Null;
if Assigned(Params.FindParam(s_IN_TABLE_UPD)) then
ParamByName(s_IN_TABLE_UPD).AsVariant := Null;
// Внутри идет вызов ListDataSetInfo.LoadDataSetInfo,
// если (psApplyRepositary in PrepareOptions) and (DataSet_ID>0)
Prepare;
// Обновили Select-sql из репозитория
Close;
ds_Changelog_List.Tag := 1;
end;
DataSet_ID := 0;
if (1 = 0) then
begin
SelectSQL.Text :=
'select CHANGE_KOD, SESSION_ID, CHANGE_STAMP, CHANGE_ACTION,' +
' CHANGED_TABLE_ID, CHANGED_TABLE_NAM, CHANGED_TABLE_KOD, CHANGED_TABLE_VER' +
' from SP_CHANGELOG_RF(:IN_SESSION_ID, :IN_CHANGE_NUM,' +
' :IN_TABLE_LIST, :IN_TABLE_INS, :IN_TABLE_UPD)';
end;
// No insert, update or delete for ds_Changelog_List
InsertSQL.Text := s_No_Action;
UpdateSQL.Text := s_No_Action;
DeleteSQL.Text := s_No_Action;
// -----------------------------------------------------------
// выбираем записи введенные или измененные не этим пользователем,
// это не относится к удаленным записям - они выбираются все.
// -----------------------------------------------------------
if Assigned(Params.FindParam(s_IN_SESSION_ID)) then
ParamByName(s_IN_SESSION_ID).AsString := IntToStr(Global_Session_ID);
if Assigned(Params.FindParam(s_IN_CHANGE_NUM)) then
ParamByName(s_IN_CHANGE_NUM).AsString := IntToStr(var_ChangeKod_Max);
if Assigned(Params.FindParam(s_IN_TABLE_LIST)) then
begin
str_TableList := s_Delimiter;
for j := 0 to FEventTableNames.Count - 1 do
begin
str_TableName := FEventTableNames.Names[j];
iz_MixDS := StrToInt(FEventTableNames.Values[str_TableName]);
z_MixDS := Get_DataSetsID_By_Name(iz_MixDS);
str_TableList := str_TableList + IntToStr(z_MixDS.DS_UID) + s_Delimiter;
end;
DEBUGMessEnh(0, UnitName, ProcName, 'str_TableList = (' + str_TableList + ')');
ParamByName(s_IN_TABLE_LIST).AsString := str_TableList;
end;
if Assigned(Params.FindParam(s_IN_TABLE_INS)) then
begin
str_TableIns := s_Delimiter;
for j := 0 to FEventTableNames.Count - 1 do
begin
str_TableName := FEventTableNames.Names[j];
iz_MixDS := StrToInt(FEventTableNames.Values[str_TableName]);
z_MixDS := Get_DataSetsID_By_Name(iz_MixDS);
if (z_MixDS.DS_InsUpd and 1 = 1) then
str_TableIns := str_TableIns + IntToStr(z_MixDS.DS_UID) + s_Delimiter;
end;
DEBUGMessEnh(0, UnitName, ProcName, 'str_TableIns = (' + str_TableIns + ')');
ParamByName(s_IN_TABLE_INS).AsString := str_TableIns;
end;
if Assigned(Params.FindParam(s_IN_TABLE_UPD)) then
begin
str_TableUpd := s_Delimiter;
for j := 0 to FEventTableNames.Count - 1 do
begin
str_TableName := FEventTableNames.Names[j];
iz_MixDS := StrToInt(FEventTableNames.Values[str_TableName]);
z_MixDS := Get_DataSetsID_By_Name(iz_MixDS);
if (z_MixDS.DS_InsUpd and 2 = 2) then
str_TableUpd := str_TableUpd + IntToStr(z_MixDS.DS_UID) + s_Delimiter;
end;
DEBUGMessEnh(0, UnitName, ProcName, 'str_TableUpd = (' + str_TableUpd + ')');
ParamByName(s_IN_TABLE_UPD).AsString := str_TableUpd;
end;
// -----------------------------------------------------------
Open;
Last; // Это для определения реального числа записей в RecordCount
First;
updrec := RecordCount;
DEBUGMessEnh(0, UnitName, ProcName, 'UpdRecTotal = (' + IntToStr(updrec) + ')');
end;
//если не все записи будут обновлены
t1_non_upd_rec := updrec;
reccnt := 0;
// -----------------------------------------------------------
ProcessChangelog(ds_Changelog_Buf);
if not BufferOnly then
begin
ProcessChangelog(ds_Changelog_List);
// ProcessChangelog(ds_Changelog_Buf);
end;
// -----------------------------------------------------------
reccnt := ds_Changelog_Buf.RecordCount;
if reccnt <> 0 then
DEBUGMessEnh(0, UnitName, ProcName, 'В буфере ' + IntToStr(reccnt)
+ ' необновленных записей.');
if t1_non_upd_rec <> 0 then
DEBUGMessEnh(0, UnitName, ProcName, 'Невозможно обновить ' + IntToStr(t1_non_upd_rec)
+ ' записей.')
else
DEBUGMessEnh(0, UnitName, ProcName, 'Другими пользователями обновлено ' + IntToStr(updrec)
+ ' записей.');
// -----------------------------------------------------------
finally
Changelog_Max_Value := var_ChangeKod_Max;
try
ds_Changelog_List.Close;
ds_Changelog_List.DataSet_ID := Saved_Dataset_ID;
tmr_Buffer.Enabled := (ds_Changelog_Buf.RecordCount > 0);
except
end;
// -----------------------------------------------------------
t1_event_locked_real := false;
// -----------------------------------------------------------
end;
end;
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Something failed.');
end;
end;
Refresh_TC_Count(30);
// -----------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<<<---<<<---<<<');
// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
end;
procedure Tdm_Base.db_kino2Connect(Sender: TObject);
begin
//
Prepare_Buf_Dataset;
end;
procedure Tdm_Base.ev_ChangelogEventAlert(Sender: TObject; EventName: string; EventCount: Integer);
const
ProcName: string = 'ev_ChangelogEventAlert';
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
try
ChangelogEvent(EventName, EventCount, false);
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'ChangelogEvent() failed.');
end;
end;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.tmr_BufferTimer(Sender: TObject);
const
ProcName: string = 'tmr_BufferTimer';
begin
try
if not (t1_event_locked_real or FEventProcessed or FChangelog_Buf_Busy) then
begin
if (ds_Changelog_Buf.RecordCount > 0) then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Calling ChangelogEvent() on timer');
ChangelogEvent('', 0, true);
end;
tmr_Buffer.Enabled := false;
end
else
begin
if not tmr_Buffer.Enabled then
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Setting ChangelogEvent() on next tick');
tmr_Buffer.Enabled := true;
end;
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'ChangelogEvent() failed.');
end;
end;
end;
procedure Tdm_Base.db_kino2BeforeDisconnect(Sender: TObject);
const
ProcName: string = 'db_kino2BeforeDisconnect';
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.db_kino2LostConnect(Database: TFIBDatabase; E: EFIBError; var Actions:
TOnLostConnectActions);
const
ProcName: string = 'db_kino2LostConnect';
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
{laTerminateApp, laCloseConnect, laIgnore, laWaitRestore}
DEBUGMessEnh(0, UnitName, ProcName, 'E.SQLCode = (' + IntToStr(E.SQLCode) +
') = (' + IntToHex(E.SQLCode, 8) + ')');
DEBUGMessEnh(0, UnitName, ProcName, 'E.Message = (' + E.Message + ')');
Actions := laCloseConnect;
// todo: Restore connect
DBConnected2 := db_kino2.Connected;
Update_DB_Conn_State;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.db_kino2ErrorRestoreConnect(Database: TFIBDatabase; E: EFIBError; var Actions:
TOnLostConnectActions);
const
ProcName: string = 'db_kino2ErrorRestoreConnect';
begin
DEBUGMessEnh(1, UnitName, ProcName, '->');
// --------------------------------------------------------------------------
DEBUGMessEnh(0, UnitName, ProcName, 'E.Message = (' + E.Message + ')');
DEBUGMessEnh(0, UnitName, ProcName, 'E.SQLCode = (' + IntToStr(E.SQLCode) +
') = (' + IntToHex(E.SQLCode, 8) + ')');
Actions := laTerminateApp;
// todo: Restore connect
DBConnected2 := db_kino2.Connected;
Update_DB_Conn_State;
// --------------------------------------------------------------------------
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.eh_Kino2FIBErrorEvent(Sender: TObject;
ErrorValue: EFIBError; KindIBError: TKindIBError; var DoRaise: Boolean);
begin
//
end;
procedure Tdm_Base.ds_MovesFieldChange(Sender: TField);
const
ProcName: string = 'ds_MovesFieldChange';
begin
// DEBUGMessEnh(1, UnitName, ProcName, '->');
{$IFDEF Debug_Level_9}
// --------------------------------------------------------------------------
if Assigned(Sender) and (Sender is TField) then
DEBUGMessEnh(0, UnitName, ProcName, 'Changed ' + (Sender as TField).FieldName + '.');
// --------------------------------------------------------------------------
{$ENDIF}
// Reload_TC(Cur_Repert_Kod);
// DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.ds_MovesAfterRefresh(DataSet: TDataSet);
const
ProcName: string = 'ds_MovesAfterRefresh';
begin
{$IFDEF Debug_Level_9}
DEBUGMessEnh(1, UnitName, ProcName, '->');
{$ENDIF}
// --------------------------------------------------------------------------
Reload_TC(Cur_Repert_Kod);
// --------------------------------------------------------------------------
{$IFDEF Debug_Level_9}
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
{$ENDIF}
end;
procedure Tdm_Base.ds_RepertFieldChange(Sender: TField);
const
ProcName: string = 'ds_RepertFieldChange';
begin
// DEBUGMessEnh(1, UnitName, ProcName, '->');
{$IFDEF Debug_Level_6}
// --------------------------------------------------------------------------
if Assigned(Sender) and (Sender is TField) then
DEBUGMessEnh(0, UnitName, ProcName, 'Changed ' + (Sender as TField).FieldName + '.');
// --------------------------------------------------------------------------
{$ENDIF}
// DEBUGMessEnh(-1, UnitName, ProcName, '<-');
end;
procedure Tdm_Base.ds_RepertAfterRefresh(DataSet: TDataSet);
const
ProcName: string = 'ds_RepertAfterRefresh';
begin
{$IFDEF Debug_Level_9}
DEBUGMessEnh(1, UnitName, ProcName, '->');
{$ENDIF}
// --------------------------------------------------------------------------
Update_Changes_Monitor;
// --------------------------------------------------------------------------
{$IFDEF Debug_Level_9}
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
{$ENDIF}
end;
procedure Tdm_Base.ds_RepertAfterDelete(DataSet: TDataSet);
const
ProcName: string = 'ds_RepertAfterDelete';
begin
{$IFDEF Debug_Level_9}
DEBUGMessEnh(1, UnitName, ProcName, '->');
{$ENDIF}
// --------------------------------------------------------------------------
ds_DatasetAfterPostOrCancelOrDelete(DataSet);
if Assigned(DataSet) and (DataSet is TDataSet) then
DEBUGMessEnh(0, UnitName, ProcName, 'Changed - ' + DataSet.Name + '.AfterDelete');
Update_Changes_Monitor;
// --------------------------------------------------------------------------
{$IFDEF Debug_Level_9}
DEBUGMessEnh(-1, UnitName, ProcName, '<-');
{$ENDIF}
end;
procedure Tdm_Base.ds_Rep_Daily_BeforeOpen(DataSet: TDataSet);
const
ProcName: string = 'ds_Rep_Daily_BeforeOpen';
{$IFDEF Debug_Level_5}
var
i: Integer;
{$ENDIF}
begin
// -----------------------------------------------------------
if (DataSet is TpFIBDataSet) then
with (DataSet as TpFIBDataSet) do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Opening (' + Name + ')');
if (DataSet.State in [dsInactive]) then
try
// -----------------------------------------------------------
if (DataSet_ID > 0) then
begin
{$IFDEF Debug_Level_9}
DEBUGMessEnh(0, UnitName, ProcName, Name + '.SelectSQL.Text = ['
+ SelectSQL.Text + ']');
{$ENDIF}
DataSet_ID := 0;
end;
// -----------------------------------------------------------
if Assigned(ParamByName(s_IN_SESSION_ID)) then
begin
ParamByName(s_IN_SESSION_ID).AsString := IntToStr(Global_Session_ID);
end;
except
on E: Exception do
begin
DEBUGMessEnh(0, UnitName, ProcName, 'Error is [' + E.Message + ']');
DEBUGMessEnh(0, UnitName, ProcName, 'Error during (0) ' + s_IN_SESSION_ID +
' assigning ' + s_IN_SESSION_ID + ' = (' + IntToStr(Global_Session_ID) + ')');
end;
end; // try
// -----------------------------------------------------------
{$IFDEF Debug_Level_5}
for i := 0 to (Params.Count - 1) do
begin
DEBUGMessEnh(0, UnitName, ProcName, Params[i].Name
+ ' = (' + BoolYesNo[Params[i].IsNull] + ') [' + Params[i].AsString + ']');
end; // for
{$ENDIF}
end; // with
// -----------------------------------------------------------
end;
end.
|
unit AMostraEstoqueChapas;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, formularios, StdCtrls, Buttons, DB,
DBClient, Tabela, CBancoDados, Grids, DBGrids, DBKeyViolation, Componentes1, ExtCtrls, PainelGradiente, UnZebra,
UnDadosProduto;
type
TFMostraEstoqueChapas = class(TFormularioPermissao)
PainelGradiente1: TPainelGradiente;
PanelColor2: TPanelColor;
Grade: TGridIndice;
Chapas: TRBSQL;
ChapasC_COD_PRO: TWideStringField;
ChapasC_NOM_PRO: TWideStringField;
ChapasLARCHAPA: TFMTBCDField;
ChapasCOMCHAPA: TFMTBCDField;
ChapasPERCHAPA: TFMTBCDField;
ChapasPESCHAPA: TFMTBCDField;
ChapasSEQNOTAFORNECEDOR: TFMTBCDField;
ChapasCODFILIAL: TFMTBCDField;
DataChapas: TDataSource;
BFechar: TBitBtn;
ChapasSEQCHAPA: TFMTBCDField;
BEtiqueta: TBitBtn;
POK: TPanelColor;
BCancelar: TBitBtn;
BOK: TBitBtn;
PanelColor1: TPanelColor;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BFecharClick(Sender: TObject);
procedure GradeDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
procedure BEtiquetaClick(Sender: TObject);
procedure BOKClick(Sender: TObject);
private
{ Private declarations }
VprCodFilial,
VprSeqNota,
VprSeqProduto : Integer;
VprOrdem : String;
VprAcao : Boolean;
FunZebra : TRBFuncoesZebra;
procedure AtualizaConsulta;
procedure AdicionaFiltros(VpaSelect : TStrings);
public
{ Public declarations }
procedure MostraEstoqueChapasNota(VpaCodFilial, VpaSeqNota : Integer);
function MostraEstoqueChapasProduto(VpaSeqproduto : Integer;VpaDPlanoCorte : TRBDPlanoCorteCorpo) : Integer;
end;
var
FMostraEstoqueChapas: TFMostraEstoqueChapas;
implementation
uses APrincipal, constantes;
{$R *.DFM}
{ ****************** Na criação do Formulário ******************************** }
procedure TFMostraEstoqueChapas.FormCreate(Sender: TObject);
begin
{ abre tabelas }
{ chamar a rotina de atualização de menus }
VprOrdem := 'order by CHA.SEQCHAPA';
FunZebra := TRBFuncoesZebra.cria(Varia.PortaComunicacaoImpTermica,176,lzEPL);
VprAcao := false;
end;
{ **************************************************************************** }
procedure TFMostraEstoqueChapas.GradeDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
begin
if State <> [gdSelected] then
begin
if Column.FieldName = 'SEQCHAPA' then
begin
Grade.Canvas.Brush.Color:= clyellow;
Grade.DefaultDrawDataCell(Rect, Grade.columns[datacol].field, State);
end;
end;
end;
{ **************************************************************************** }
procedure TFMostraEstoqueChapas.MostraEstoqueChapasNota(VpaCodFilial, VpaSeqNota: Integer);
begin
VprCodFilial := VpaCodFilial;
VprSeqNota := VpaSeqNota;
AtualizaConsulta;
showmodal;
end;
{ **************************************************************************** }
function TFMostraEstoqueChapas.MostraEstoqueChapasProduto(VpaSeqproduto: Integer;VpaDPlanoCorte : TRBDPlanoCorteCorpo):Integer;
begin
result := 0;
VprSeqProduto := VpaSeqproduto;
AtualizaConsulta;
PanelColor2.Visible := false;
POK.Visible := true;
showmodal;
if VprAcao then
begin
Result := ChapasSEQCHAPA.AsInteger;
VpaDPlanoCorte.SeqChapa :=ChapasSEQCHAPA.AsInteger;
VpaDPlanoCorte.PesoChapa := ChapasPESCHAPA.AsFloat;
end;
end;
{ ******************* Quando o formulario e fechado ************************** }
procedure TFMostraEstoqueChapas.AdicionaFiltros(VpaSelect: TStrings);
begin
if VprCodFilial <> 0 then
VpaSelect.Add('AND CHA.CODFILIAL = '+IntToStr(VprCodFilial));
if VprSeqNota <> 0 then
VpaSelect.Add('AND CHA.SEQNOTAFORNECEDOR = '+IntToStr(VprSeqNota));
if VprSeqProduto <> 0 then
VpaSelect.Add('AND CHA.SEQPRODUTO = '+IntToStr(VprSeqProduto));
end;
{ **************************************************************************** }
procedure TFMostraEstoqueChapas.AtualizaConsulta;
begin
Chapas.Close;
Chapas.SQL.Clear;
Chapas.SQL.Add('SELECT PRO.C_COD_PRO, PRO.C_NOM_PRO, '+
' CHA.SEQCHAPA, CHA.LARCHAPA, CHA.COMCHAPA, CHA.PERCHAPA, CHA.PESCHAPA, '+
' CHA.SEQNOTAFORNECEDOR, CHA.CODFILIAL '+
' FROM ESTOQUECHAPA CHA, CADPRODUTOS PRO '+
' WHERE PRO.I_SEQ_PRO = CHA.SEQPRODUTO ');
AdicionaFiltros(Chapas.SQL);
Chapas.SQL.Add(VprOrdem);
Chapas.Open;
end;
{ **************************************************************************** }
procedure TFMostraEstoqueChapas.BEtiquetaClick(Sender: TObject);
begin
FunZebra.ImprimeEtiquetaIdentificaChapa33X22(Chapas);
end;
{ **************************************************************************** }
procedure TFMostraEstoqueChapas.BFecharClick(Sender: TObject);
begin
close;
end;
procedure TFMostraEstoqueChapas.BOKClick(Sender: TObject);
begin
VprAcao := true;
close;
end;
{ **************************************************************************** }
procedure TFMostraEstoqueChapas.FormClose(Sender: TObject; var Action: TCloseAction);
begin
{ fecha tabelas }
{ chamar a rotina de atualização de menus }
FunZebra.Free;
Action := CaFree;
end;
{(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((
Ações Diversas
)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))}
Initialization
{ *************** Registra a classe para evitar duplicidade ****************** }
RegisterClasses([TFMostraEstoqueChapas]);
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit SvrLog;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
Web.HTTPApp, System.Classes, System.SyncObjs, Winapi.Messages,
SvrConst;
const
WM_LOGMESSAGE = WM_USER + $100;
type
TTransactionLogEntry = class;
TWmLogMessage = record
Msg: Cardinal;
Unused0: Integer;
Unused1: Longint;
Result: Longint;
end;
TRequestTime = record
ThreadID: Cardinal;
StartTime: TDateTime;
end;
PRequestTime = ^TRequestTime;
THTTPLogEvent =
procedure (Sender: TObject; Transaction: TTransactionLogEntry;
var Release: Boolean) of object;
// jmt.!!! Where was this class
TErrorEvent = class(TObject)
end;
TCustomServerLog = class(TObject)
private
FLock: TCriticalSection;
FBuffer: TList;
FHandle: HWND;
FOnLog: THTTPLogEvent;
FRequestTimes: array of TRequestTime;
function GetLogEntry: TTransactionLogEntry;
procedure LogTransaction(Transaction: TTransactionLogEntry);
procedure WMLogMessage(var Msg: TWMLogMessage); message WM_LOGMESSAGE;
procedure WndProc(var Message: TMessage);
procedure SetRequestTime(AThreadID: Cardinal; AStartTime: TDateTime);
function GetRequestTime(AThreadID: Cardinal): TDateTime;
function FindRequestTime(AThreadID: Cardinal): PRequestTime;
procedure WriteLog;
protected
procedure DoOnLog(Transaction: TTransactionLogEntry; var Release: Boolean); virtual;
public
constructor Create;
destructor Destroy; override;
procedure DefaultHandler(var Message); override;
procedure LogError(AThread: TThread; AErrorEvent: TErrorEvent; AErrorCode: Integer;
const AErrorMsg: string);
procedure LogRequest(ARequest: TWebRequest; const ABuffer: AnsiString);
procedure LogResponse(const Buffer: AnsiString);
property RequestTime[AThreadID: Cardinal]: TDateTime read GetRequestTime write SetRequestTime;
end;
{ TTransactionLogEntry }
TLogColumn = (lcEvent, lcTime, lcDate, lcElapsed, lcPath, lcStatus, lcContentLength, lcContentType,
lcThreadID);
TTransactionLogEntry = class(TObject)
private
protected
FEventName: AnsiString;
FDateTime: TDateTime;
FElapsedTime: TDateTime;
FThreadID: Cardinal;
function GetLogString: AnsiString; virtual; abstract;
function GetColumn(I: TLogColumn): AnsiString; virtual;
public
constructor Create;
property LogString: AnsiString read GetLogString;
property ElapsedTime: TDateTime read FElapsedTime;
property Columns[I: TLogColumn]: AnsiString read GetColumn;
end;
THTTPTransaction = class(TTransactionLogEntry)
protected
FContentLength: Integer;
FContentType: AnsiString;
FBuffer: AnsiString;
function GetColumn(I: TLogColumn): AnsiString; override;
function GetLogString: AnsiString; override;
public
end;
{ TRequestTransaction }
TRequestTransaction = class(THTTPTransaction)
private
FPath: AnsiString;
protected
function GetColumn(I: TLogColumn): AnsiString; override;
public
constructor Create(ARequest: TWebRequest; const ABuffer: AnsiString);
end;
{ TResponseTransaction }
TResponseTransaction = class(THTTPTransaction)
private
FStatus: AnsiString;
FFirstLine: AnsiString;
procedure ParseBuffer(AParser: TObject);
protected
function GetColumn(I: TLogColumn): AnsiString; override;
public
constructor Create(const Buffer: AnsiString);
destructor Destroy; override;
end;
{ TErrorTransaction }
TErrorTransaction = class(TTransactionLogEntry)
private
FErrorEvent: TErrorEvent;
FErrorMsg: string;
FErrorCode: Integer;
public
constructor Create(AErrorEvent: TErrorEvent; AErrorCode: Integer;
const AErrorMsg: string);
function GetLogString: AnsiString; override;
property ErrorType: TErrorEvent read FErrorEvent;
property ErrorMsg: string read FErrorMsg;
property ErrorCode: Integer read FErrorCode;
end;
implementation
uses System.SysUtils, Vcl.Forms, SvrHTTPIndy, HTTPParse, IdHTTPServer;
{ TTransactionLogEntry }
constructor TTransactionLogEntry.Create;
begin
inherited Create;
FDateTime := Now;
{$IFDEF MSWINDOWS}
FThreadID := GetCurrentThreadID;
{$ENDIF}
end;
function TTransactionLogEntry.GetColumn(I: TLogColumn): AnsiString;
begin
case I of
lcEvent: Result := FEventName;
lcTime: Result := AnsiString(FormatDateTime('hh:mm:ss:zzz', FDateTime)); { do not localize }
lcDate: Result := AnsiString(DateToStr(FDateTime));
lcThreadID: Result := AnsiString(IntToStr(FThreadID));
else
Result := '';
end;
end;
{ TErrorTransaction }
constructor TErrorTransaction.Create(AErrorEvent: TErrorEvent; AErrorCode: Integer;
const AErrorMsg: string);
begin
inherited Create;
FEventName := AnsiString(sErrorEvent);
FErrorEvent := AErrorEvent;
FErrorMsg := AErrorMsg;
FErrorCode := AErrorCode;
end;
function TErrorTransaction.GetLogString: AnsiString;
begin
{$IFDEF MSWINDOWS}
// jmt.!!! case FErrorEvent of
// jmt.!!! eeSend: Result := sSend;
// jmt.!!! eeReceive: Result := sReceive;
// jmt.!!! end;
{$ENDIF}
Result := AnsiString(Format(sLogStrTemplate, [
FormatDateTime(DateFormat, FDateTime), Result, FErrorCode, FErrorMsg]));
end;
{ TCustomServerLog }
constructor TCustomServerLog.Create;
begin
inherited Create;
FHandle := System.Classes.AllocateHWnd(WndProc);
FBuffer := TList.Create;
FLock := TCriticalSection.Create;
end;
destructor TCustomServerLog.Destroy;
begin
// ClearLog;
FBuffer.Free;
FLock.Free;
if FHandle <> 0 then System.Classes.DeAllocateHWnd(FHandle);
inherited Destroy;
end;
procedure TCustomServerLog.WriteLog;
var
Transaction: TTransactionLogEntry;
Release: Boolean;
begin
FLock.Enter;
try
Transaction := GetLogEntry;
while Transaction <> nil do
begin
try
Release := True;
DoOnLog(Transaction, Release);
finally
if Release then
Transaction.Free;
end;
Transaction := GetLogEntry;
end;
finally
FLock.Leave;
end;
end;
procedure TCustomServerLog.LogTransaction(Transaction: TTransactionLogEntry);
var
T: TDateTime;
begin
FLock.Enter;
try
if Transaction is TRequestTransaction then
RequestTime[Transaction.FThreadID] := Transaction.FDateTime
else
begin
T := RequestTime[Transaction.FThreadID];
if T <> 0 then
Transaction.FElapsedTime := Transaction.FDateTime - T;
end;
FBuffer.Add(Transaction);
PostMessage(FHandle, WM_LOGMESSAGE, 0, 0);
finally
FLock.Leave;
end;
end;
procedure TCustomServerLog.LogError(AThread: TThread; AErrorEvent: TErrorEvent;
AErrorCode: Integer; const AErrorMsg: string);
begin
LogTransaction(TErrorTransaction.Create(AErrorEvent, AErrorCode, AErrorMsg));
end;
function TCustomServerLog.GetLogEntry: TTransactionLogEntry;
begin
FLock.Enter;
try
if FBuffer.Count > 0 then
begin
Result := TTransactionLogEntry(FBuffer.First);
FBuffer.Delete(0);
end else Result := nil;
finally
FLock.Leave;
end;
end;
procedure TCustomServerLog.WMLogMessage(var Msg: TWMLogMessage);
var
Transaction: TTransactionLogEntry;
Release: Boolean;
begin
Transaction := GetLogEntry;
while Transaction <> nil do
begin
try
Release := True;
DoOnLog(Transaction, Release);
finally
if Release then
Transaction.Free;
end;
Transaction := GetLogEntry;
end;
end;
procedure TCustomServerLog.DoOnLog(Transaction: TTransactionLogEntry;
var Release: Boolean);
begin
if Assigned(FOnLog) then FOnLog(Self, Transaction, Release);
end;
procedure TCustomServerLog.WndProc(var Message: TMessage);
begin
try
Dispatch(Message);
except
Application.HandleException(Self);
end;
end;
procedure TCustomServerLog.DefaultHandler(var Message);
begin
with TMessage(Message) do
Result := DefWindowProc(FHandle, Msg, WParam, LParam);
end;
procedure TCustomServerLog.LogRequest(ARequest: TWebRequest; const ABuffer: AnsiString);
begin
LogTransaction(TRequestTransaction.Create(ARequest, ABuffer));
end;
procedure TCustomServerLog.LogResponse(const Buffer: AnsiString);
begin
LogTransaction(TResponseTransaction.Create(Buffer));
end;
function TCustomServerLog.GetRequestTime(AThreadID: Cardinal): TDateTime;
var
P: PRequestTime;
begin
P := FindRequestTime(AThreadID);
if Assigned(P) then
Result := P.StartTime
else
Result := 0;
end;
function TCustomServerLog.FindRequestTime(AThreadID: Cardinal): PRequestTime;
var
I: Integer;
begin
for I := Low(FRequestTimes) to High(FRequestTimes) do
begin
Result := @FRequestTimes[I];
if Result.ThreadID = AThreadID then Exit;
end;
Result := nil;
end;
procedure TCustomServerLog.SetRequestTime(AThreadID: Cardinal;
AStartTime: TDateTime);
var
P: PRequestTime;
begin
P := FindRequestTime(AThreadID);
if Assigned(P) then
P.StartTime := AStartTime
else
begin
SetLength(FRequestTimes, Length(FRequestTimes) + 1);
with FRequestTimes[High(FRequestTimes)] do
begin
StartTime := AStartTime;
ThreadID := AThreadID;
end;
end;
end;
{ TRequestTransaction }
const
CGIServerVariables: array[0..28] of string = (
'REQUEST_METHOD',
'SERVER_PROTOCOL',
'URL',
'QUERY_STRING',
'PATH_INFO',
'PATH_TRANSLATED',
'HTTP_CACHE_CONTROL',
'HTTP_DATE',
'HTTP_ACCEPT',
'HTTP_FROM',
'HTTP_HOST',
'HTTP_IF_MODIFIED_SINCE',
'HTTP_REFERER',
'HTTP_USER_AGENT',
'HTTP_CONTENT_ENCODING',
'HTTP_CONTENT_TYPE',
'HTTP_CONTENT_LENGTH',
'HTTP_CONTENT_VERSION',
'HTTP_DERIVED_FROM',
'HTTP_EXPIRES',
'HTTP_TITLE',
'REMOTE_ADDR',
'REMOTE_HOST',
'SCRIPT_NAME',
'SERVER_PORT',
'',
'HTTP_CONNECTION',
'HTTP_COOKIE',
'HTTP_AUTHORIZATION');
constructor TRequestTransaction.Create(ARequest: TWebRequest; const ABuffer: AnsiString);
begin
inherited Create;
FDateTime := Now;
FEventName := ARequest.Method;
FPath := ARequest.PathInfo;
FContentLength := ARequest.ContentLength;
FContentType := ARequest.ContentType;
FBuffer := ABuffer;;
end;
function TRequestTransaction.GetColumn(I: TLogColumn): AnsiString;
begin
case I of
lcPath: Result := FPath;
else
Result := inherited GetColumn(I);
end;
end;
{ TResponseTransaction }
constructor TResponseTransaction.Create(const Buffer: AnsiString);
var
S: TStream;
HTTPParser: THTTPParser;
P: Integer;
begin
inherited Create;
FEventName := AnsiString(sResponseEvent);
FBuffer := Buffer;
S := TStringStream.Create(FBuffer);
try
HTTPParser := THTTPParser.Create(S);
try
ParseBuffer(HTTPParser);
finally
HTTPParser.Free;
end;
finally
S.Free;
end;
P := Pos(AnsiChar(' '), FFirstLine);
if P > 0 then
FStatus := Copy(FFirstLine, P+1, MaxInt);
end;
destructor TResponseTransaction.Destroy;
begin
inherited;
end;
procedure TResponseTransaction.ParseBuffer(AParser: TObject);
var
Parser: THTTPParser;
procedure SkipLine;
begin
Parser.CopyToEOL;
Parser.SkipEOL;
end;
procedure ParseContentType;
begin
with Parser do
begin
NextToken;
if Token = ':' then NextToken;
if Self.FContentType = '' then
Self.FContentType := AnsiString(TrimLeft(string(CopyToEOL)))
else CopyToEOL;
NextToken;
end;
end;
procedure ParseContentLen;
begin
with Parser do
begin
NextToken;
if Token = ':' then NextToken;
if Token = toInteger then Self.FContentLength := TokenInt;
CopyToEol;
NextToken;
end;
end;
begin
Parser := AParser as THTTPParser;
FFirstLine := Parser.CopyToEol;
Parser.SkipEol;
while Parser.Token <> toEOF do with Parser do
begin
case Token of
toContentType: ParseContentType;
toContentLength: ParseContentLen;
toEOL: Break; // At content
else
SkipLine;
end;
end;
end;
function TResponseTransaction.GetColumn(I: TLogColumn): AnsiString;
var
S: string;
begin
case I of
lcElapsed:
begin
DateTimeToString(S, 'hh:mm:ss:zzz', FElapsedTime); { do not localize }
Result := AnsiString(S);
end;
lcStatus: Result := FStatus;
else
Result := inherited GetColumn(I);
end;
end;
{ THTTPTransaction }
function THTTPTransaction.GetColumn(I: TLogColumn): AnsiString;
begin
case I of
lcContentLength: Result := AnsiString(IntToStr(FContentLength));
lcContentType: Result := FContentType;
else
Result := inherited GetColumn(I);
end;
end;
function THTTPTransaction.GetLogString: AnsiString;
begin
Result := FBuffer;
end;
end.
|
unit Soccer.VotingRules.Borda;
interface
uses
System.SysUtils,
System.Generics.Collections,
Soccer.Voting.RulesDict,
Soccer.Voting.Preferences,
Soccer.Voting.AbstractRule;
type
TSoccerBordaVotingScoreRule = class(TInterfacedObject, ISoccerVotingRule)
private
function FindWinners(LScores: TDictionary<string, integer>)
: TList<string>;
public
function ExecuteOn(AProfile: TSoccerVotingVotersPreferences;
out Winners: System.Generics.Collections.
TList<string>): Boolean;
function GetName: string;
end;
implementation
{ TBordaScore }
function TSoccerBordaVotingScoreRule.ExecuteOn
(AProfile: TSoccerVotingVotersPreferences;
out Winners: System.Generics.Collections.TList<string>): Boolean;
var
LScores: TDictionary<string, integer>;
LVoter: TSoccerVotingIndividualPreferenceProfile;
i: integer;
LAlternative: string;
begin
Result := false;
if not AProfile.Properties.Complete then
exit;
LScores := TDictionary<string, integer>.Create;
for LAlternative in AProfile.Profile[0] do
LScores.Add(LAlternative, 0);
for LVoter in AProfile.Profile do
begin
for i := LVoter.Count - 1 downto 0 do
begin
LScores[LVoter[i]] := LScores[LVoter[i]] + (LVoter.Count - i);
end;
end;
Winners := FindWinners(LScores);
Result := true;
FreeAndNil(LScores);
end;
function TSoccerBordaVotingScoreRule.FindWinners
(LScores: TDictionary<string, integer>): TList<String>;
var
LAlternative: string;
LMaxScore: integer;
begin
LMaxScore := 0;
for LAlternative in LScores.Keys do
begin
if LScores[LAlternative] > LMaxScore then
LMaxScore := LScores[LAlternative];
end;
Result := TList<String>.Create;
for LAlternative in LScores.Keys do
begin
if LScores[LAlternative] = LMaxScore then
Result.Add(LAlternative);
end;
end;
function TSoccerBordaVotingScoreRule.GetName: string;
begin
Result := 'borda';
end;
var
LRule: ISoccerVotingRule;
initialization
LRule := TSoccerBordaVotingScoreRule.Create;
GlobalVotingRulesDict.Rules.Add(LRule.GetName, LRule);
end.
|
unit Vigilante.View.Component.SituacaoBuild;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls,
Vcl.DBCtrls, Vcl.WinXCtrls, Vcl.Imaging.pngimage, Vcl.ExtCtrls,
Vigilante.Aplicacao.SituacaoBuild;
type
TfrmSituacaoBuild = class(TFrame)
imgAborted: TImage;
imgBuildIndefinido: TImage;
imgBuildOK: TImage;
imgBuildFailed: TImage;
imgProgresso: TActivityIndicator;
lblDescricao: TDBText;
dtsSituacaoBuild: TDataSource;
lblLink: TLinkLabel;
pnlImagem: TPanel;
Bevel1: TBevel;
procedure dtsSituacaoBuildDataChange(Sender: TObject; Field: TField);
procedure dtsSituacaoBuildStateChange(Sender: TObject);
procedure lblLinkLinkClick(Sender: TObject; const Link: string;
LinkType: TSysLinkType);
procedure dtsSituacaoBuildUpdateData(Sender: TObject);
private
FSituacaoBuildFieldName: string;
FSituacaoBuildField: TField;
FDescricaoField: TField;
FURL: string;
FURLField: TField;
procedure CarregarCampos;
procedure SetDataSet(const Value: TDataSet);
procedure SetNomeFieldName(const Value: string);
procedure SetSituacaoBuild(const Value: string);
function GetDataSet: TDataSet;
function GetNomeFieldName: string;
procedure SelecionarImagemBuild;
procedure SetURL(const Value: string);
procedure AtualizarLink;
procedure SincronizarTela;
public
published
property NomeFieldName: string read GetNomeFieldName write SetNomeFieldName;
property SituacaoBuildFieldName: string read FSituacaoBuildFieldName write SetSituacaoBuild;
property URLFieldName: string read FURL write SetURL;
property DataSet: TDataSet read GetDataSet write SetDataSet;
end;
implementation
{$R *.dfm}
uses
Winapi.ShellAPI;
procedure TfrmSituacaoBuild.CarregarCampos;
begin
if not Assigned(dtsSituacaoBuild.DataSet) then
Exit;
if lblDescricao.DataField.Trim.IsEmpty then
Exit;
if FSituacaoBuildFieldName.Trim.IsEmpty then
Exit;
if FURL.Trim.IsEmpty then
Exit;
FDescricaoField := DataSet.FindField(lblDescricao.DataField);
FSituacaoBuildField := DataSet.FindField(FSituacaoBuildFieldName);
FURLField := DataSet.FindField(FURL);
SincronizarTela;
end;
procedure TfrmSituacaoBuild.dtsSituacaoBuildDataChange(Sender: TObject;
Field: TField);
begin
SincronizarTela;
end;
procedure TfrmSituacaoBuild.dtsSituacaoBuildStateChange(Sender: TObject);
begin
SincronizarTela;
end;
procedure TfrmSituacaoBuild.dtsSituacaoBuildUpdateData(Sender: TObject);
begin
SincronizarTela;
end;
procedure TfrmSituacaoBuild.SincronizarTela;
begin
AtualizarLink;
SelecionarImagemBuild;
end;
procedure TfrmSituacaoBuild.AtualizarLink;
const
CONTEUDO_LINK = '<a href="%s">Abrir link da compila��o</a>';
HINT_LINK = 'Abrir a p�gina: %s';
begin
if not Assigned(FURLField) then
Exit;
lblLink.Visible := not FURLField.AsString.Trim.IsEmpty;
lblLink.Caption := Format(CONTEUDO_LINK, [FURLField.AsString]);
lblLink.Hint := Format(HINT_LINK, [FURLField.AsString]);
end;
procedure TfrmSituacaoBuild.SelecionarImagemBuild;
var
_situacaoBuild: TSituacaoBuild;
begin
if not Assigned(FSituacaoBuildField) then
Exit;
_situacaoBuild := TSituacaoBuild.Parse(FSituacaoBuildField.AsInteger);
imgBuildOK.Visible := _situacaoBuild = sbSucesso;
imgBuildFailed.Visible := _situacaoBuild in [sbFalhou, sbFalhouInfra];
imgBuildIndefinido.Visible := _situacaoBuild = sbUnknow;
imgAborted.Visible := _situacaoBuild = sbAbortado;
imgProgresso.Visible := _situacaoBuild = sbProgresso;
if imgProgresso.Animate and (_situacaoBuild = sbProgresso) then
Exit;
imgProgresso.Animate := _situacaoBuild = sbProgresso;
end;
function TfrmSituacaoBuild.GetDataSet: TDataSet;
begin
Result := dtsSituacaoBuild.DataSet;
end;
function TfrmSituacaoBuild.GetNomeFieldName: string;
begin
Result := lblDescricao.DataField;
end;
procedure TfrmSituacaoBuild.lblLinkLinkClick(Sender: TObject;
const Link: string; LinkType: TSysLinkType);
var
_url: PWideChar;
begin
_url := PWideChar(Link);
ShellExecute(Handle, 'open', _url, nil, nil, SW_SHOW);
end;
procedure TfrmSituacaoBuild.SetDataSet(const Value: TDataSet);
begin
dtsSituacaoBuild.DataSet := Value;
CarregarCampos;
end;
procedure TfrmSituacaoBuild.SetNomeFieldName(const Value: string);
begin
lblDescricao.DataField := Value;
CarregarCampos;
end;
procedure TfrmSituacaoBuild.SetSituacaoBuild(const Value: string);
begin
FSituacaoBuildFieldName := Value;
CarregarCampos;
end;
procedure TfrmSituacaoBuild.SetURL(const Value: string);
begin
FURL := Value;
CarregarCampos;
end;
end.
|
unit RN_ValueHistory;
interface
type
TValueHistory = class
private
const MAX_HISTORY = 256;
var
m_samples: array [0..MAX_HISTORY-1] of Single;
m_hsamples: Integer;
public
constructor Create();
destructor Destroy; override;
procedure addSample(const val: Single);
function getSampleCount(): Integer;
function getSample(const i: Integer): Single;
function getSampleMin(): Single;
function getSampleMax(): Single;
function getAverage(): Single;
end;
PGraphParams = ^TGraphParams;
TGraphParams = record
procedure setRect(ix, iy, iw, ih, ipad: Integer);
procedure setValueRange(ivmin, ivmax: Single; indiv: Integer; const iunits: PShortInt);
public
x, y, w, h, pad: Integer;
vmin, vmax: Single;
ndiv: Integer;
units: array [0..15] of ShortInt;
end;
procedure drawGraphBackground(const p: PGraphParams);
procedure drawGraph(const p: PGraphParams; const graph: TValueHistory;
idx: Integer; const &label: PShortInt; const col: Cardinal);
implementation
constructor TValueHistory.Create();
var i: Integer;
begin
inherited;
for i := 0 to MAX_HISTORY - 1 do
m_samples[i] := 0;
end;
destructor TValueHistory.Destroy;
begin
inherited;
end;
procedure TValueHistory.addSample(const val: Single);
begin
m_hsamples := (m_hsamples+MAX_HISTORY-1) mod MAX_HISTORY;
m_samples[m_hsamples] := val;
end;
function TValueHistory.getSampleCount(): Integer;
begin
Result := MAX_HISTORY;
end;
function TValueHistory.getSample(const i: Integer): Single;
begin
Result := m_samples[(m_hsamples+i) mod MAX_HISTORY];
end;
function TValueHistory.getSampleMin(): Single;
var val: Single; i: Integer;
begin
val := m_samples[0];
for i := 1 to MAX_HISTORY - 1 do
if (m_samples[i] < val) then
val := m_samples[i];
Result := val;
end;
function TValueHistory.getSampleMax(): Single;
var val: Single; i: Integer;
begin
val := m_samples[0];
for i := 1 to MAX_HISTORY - 1 do
if (m_samples[i] > val) then
val := m_samples[i];
Result := val;
end;
function TValueHistory.getAverage(): Single;
var val: Single; i: Integer;
begin
val := 0;
for i := 1 to MAX_HISTORY - 1 do
val := val + m_samples[i];
Result := val/MAX_HISTORY;
end;
procedure TGraphParams.setRect(ix, iy, iw, ih, ipad: Integer);
begin
x := ix;
y := iy;
w := iw;
h := ih;
pad := ipad;
end;
procedure TGraphParams.setValueRange(ivmin, ivmax: Single; indiv: Integer; const iunits: PShortInt);
begin
vmin := ivmin;
vmax := ivmax;
ndiv := indiv;
//todo: Delphi: strcpy(units, iunits);
end;
procedure drawGraphBackground(const p: PGraphParams);
begin
{ // BG
imguiDrawRoundedRect((float)p.x, (float)p.y, (float)p.w, (float)p.h, (float)p.pad, imguiRGBA(64,64,64,128));
const float sy := (p.h-p.pad*2) / (p.vmax-p.vmin);
const float oy := p.y+p.pad-p.vmin*sy;
char text[64];
// Divider Lines
for (int i := 0; i <= p.ndiv; ++i)
begin
const float u := (float)i/(float)p.ndiv;
const float v := p.vmin + (p.vmax-p.vmin)*u;
snprintf(text, 64, "%.2f %s", v, p.units);
const float fy := oy + v*sy;
imguiDrawText(p.x + p.w - p.pad, (int)fy-4, IMGUI_ALIGN_RIGHT, text, imguiRGBA(0,0,0,255));
imguiDrawLine((float)p.x + (float)p.pad, fy, (float)p.x + (float)p.w - (float)p.pad - 50, fy, 1.0f, imguiRGBA(0,0,0,64));
end;}
end;
procedure drawGraph(const p: PGraphParams; const graph: TValueHistory;
idx: Integer; const &label: PShortInt; const col: Cardinal);
begin
{ const float sx := (p.w - p.pad*2) / (float)graph.getSampleCount();
const float sy := (p.h - p.pad*2) / (p.vmax - p.vmin);
const float ox := (float)p.x + (float)p.pad;
const float oy := (float)p.y + (float)p.pad - p.vmin*sy;
// Values
float px=0, py=0;
for (int i := 0; i < graph.getSampleCount()-1; ++i)
begin
const float x := ox + i*sx;
const float y := oy + graph.getSample(i)*sy;
if (i > 0)
imguiDrawLine(px,py, x,y, 2.0f, col);
px := x;
py := y;
end;
// Label
const int size := 15;
const int spacing := 10;
int ix := p.x + p.w + 5;
int iy := p.y + p.h - (idx+1)*(size+spacing);
imguiDrawRoundedRect((float)ix, (float)iy, (float)size, (float)size, 2.0f, col);
char text[64];
snprintf(text, 64, "%.2f %s", graph.getAverage(), p.units);
imguiDrawText(ix+size+5, iy+3, IMGUI_ALIGN_LEFT, label, imguiRGBA(255,255,255,192));
imguiDrawText(ix+size+150, iy+3, IMGUI_ALIGN_RIGHT, text, imguiRGBA(255,255,255,128));}
end;
end.
|
unit port_UFrmConfig;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, Registry;
const
ARQ_CONFIG = 'swtutor.cfg';
SEC_MODULOS = 'modulos';
NUM_DIRS = 'ndir';
REG_BASE = '\Software\Decarva\SW-Tutor\';
REG_EDITOR = 'Editor\';
type
TFrmConfig = class(TForm)
PageControl1: TPageControl;
TabSheet1: TTabSheet;
Panel1: TPanel;
BtnOk: TButton;
BtnCancelar: TButton;
ListBox: TListBox;
BtnIncluir: TButton;
BtnExcluir: TButton;
procedure FormActivate(Sender: TObject);
procedure BtnIncluirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnExcluirClick(Sender: TObject);
private
{ Private declarations }
FStrConfig: String;
FSalvaDirsModulos: TStringList;
FRegistry: TRegistry;
function cria_registry: TRegistry;
function StrConfig: String;
function AlterouConfig: Boolean;
procedure GravaConfig;
function get_registry: TRegistry;
public
{ Public declarations }
procedure alt_tam_fonte_editor(tam: integer);
function obt_tam_fonte_editor(): integer;
procedure Execute;
function NomeModuloCompleto(Nome: String): String;
function NomeProgramaCompleto(Nome: String): String;
function NomeArquivoCompleto(Nome: String): String;
function ExtensaoDefaultPrg: String;
function IsWindows64: Boolean;
end;
var
FrmConfig: TFrmConfig;
implementation
{$R *.dfm}
uses
IniFiles;
procedure TFrmConfig.FormActivate(Sender: TObject);
begin
if ListBox.Count > 0 then
ListBox.Selected[0] := True;
BtnOk.SetFocus;
end;
procedure TFrmConfig.BtnIncluirClick(Sender: TObject);
begin
(*
FrmPasta.ShowModal;
if (FrmPasta.ModalResult = mrOK) then
begin
if ListBox.Items.IndexOf(FrmPasta.ShellTreeView.Path) < 0 then
ListBox.Items.Add(FrmPasta.ShellTreeView.Path);
end;
*)
end;
function TFrmConfig.StrConfig: String;
var
I: Integer;
begin
Result := '';
for I := 0 to ListBox.Count - 1 do
Result := Result + ListBox.Items[I] + ';';
end;
function TFrmConfig.AlterouConfig: Boolean;
begin
Result := FStrConfig <> StrConfig();
end;
procedure TFrmConfig.Execute;
begin
FStrConfig := StrConfig();
FSalvaDirsModulos.Assign(ListBox.Items);
ShowModal;
if ((ModalResult = mrOK) and (AlterouConfig())) then
GravaConfig
else
ListBox.Items.Assign(FSalvaDirsModulos);
end;
procedure TFrmConfig.GravaConfig;
(*
var
Ini: TIniFile;
I: Integer;
*)
begin
Exit;
(*
if ListBox.Count = 0 then
begin
GravaConfigDefault;
Exit;
end;
Ini := TIniFile.Create(NomeArqConfig());
try
Ini.WriteInteger(SEC_MODULOS, NUM_DIRS, ListBox.Count);
for I := 0 to ListBox.Count - 1 do
Ini.WriteString(SEC_MODULOS, 'd' + IntToStr(I), ListBox.Items[I]);
finally
Ini.Free;
end;
*)
end;
procedure TFrmConfig.FormCreate(Sender: TObject);
begin
FSalvaDirsModulos := TStringList.Create;
// ObtemConfig;
end;
procedure TFrmConfig.BtnExcluirClick(Sender: TObject);
begin
if ListBox.Count = 0 then
Exit;
if ListBox.SelCount = 0 then
Exit;
ListBox.DeleteSelected;
end;
function TFrmConfig.NomeModuloCompleto(Nome: String): String;
const
DIR_MDLS = 'mdls';
begin
Result := ExtractFilePath(Application.ExeName);
Result := IncludeTrailingPathDelimiter(Result) + DIR_MDLS;
if not IsPathDelimiter(Nome, 1) then
Result := IncludeTrailingPathDelimiter(Result);
Result := Result + Nome;
(*
{ varre a lista }
for I := 0 to ListBox.Count - 1 do
begin
Result := ListBox.Items[I];
Result := ExcludeTrailingPathDelimiter(Result);
Result := IncludeTrailingPathDelimiter(Result);
Result := Result + Nome;
if FileExists(Result) then
Exit;
end;
{ se chegou aqui: lista vazia ou não encontrou o arquivo }
Result := Nome; // não sei se é a melhor alternativa; vai assim por enquanto
*)
end;
function TFrmConfig.NomeProgramaCompleto(Nome: String): String;
const
DIR_PRGS = 'prgs';
begin
Result := ExtractFilePath(Application.ExeName);
Result := IncludeTrailingPathDelimiter(Result) + DIR_PRGS;
if not IsPathDelimiter(Nome, 1) then
Result := IncludeTrailingPathDelimiter(Result);
Result := Result + Nome;
end;
function TFrmConfig.NomeArquivoCompleto(Nome: String): String;
const
DIR_ARQS = 'arqs';
begin
Result := ExtractFilePath(Application.ExeName);
Result := IncludeTrailingPathDelimiter(Result) + DIR_ARQS;
if not IsPathDelimiter(Nome, 1) then
Result := IncludeTrailingPathDelimiter(Result);
Result := Result + Nome;
end;
(*function TFrmConfig.MuralConfFileName: String;
const
MURALCONF = 'mural.conf';
DIR_CONF = 'conf';
begin
Result := ExtractFilePath(Application.ExeName);
Result := IncludeTrailingPathDelimiter(Result) + DIR_CONF;
Result := IncludeTrailingPathDelimiter(Result) + MURALCONF;
end;
*)
function TFrmConfig.ExtensaoDefaultPrg: String;
begin
Result := '.lbr';
end;
procedure TFrmConfig.alt_tam_fonte_editor(tam: integer);
begin
FRegistry := get_registry();
if FRegistry = nil then
Exit; // algum problema; nada a fazer?
try
FRegistry.RootKey := HKEY_CURRENT_USER;
if FRegistry.OpenKey(REG_BASE + REG_EDITOR, True) then
FRegistry.WriteInteger('FontSize', tam);
FRegistry.CloseKey;
except
end;
end;
function TFrmConfig.obt_tam_fonte_editor: integer;
begin
Result := 9; // default
FRegistry := get_registry();
if FRegistry = nil then
Exit; // algum problema; nada a fazer?
try
FRegistry.RootKey := HKEY_CURRENT_USER;
if FRegistry.OpenKey(REG_BASE + REG_EDITOR, False) then
Result := FRegistry.ReadInteger('FontSize');
FRegistry.CloseKey;
except
end;
end;
function TFrmConfig.cria_registry: TRegistry;
begin
try
if not IsWindows64() then
FRegistry := TRegistry.Create
else
FRegistry := TRegistry.Create(KEY_WRITE or $0100);
except
FRegistry := nil;
end;
Result := FRegistry;
end;
function TFrmConfig.IsWindows64: Boolean;
type
TIsWow64Process = function(AHandle:THandle; var AIsWow64: BOOL): BOOL; stdcall;
var
vKernel32Handle: DWORD;
vIsWow64Process: TIsWow64Process;
vIsWow64 : BOOL;
begin
// 1) assume that we are not running under Windows 64 bit
Result := False;
// 2) Load kernel32.dll library
vKernel32Handle := LoadLibrary('kernel32.dll');
if (vKernel32Handle = 0) then Exit; // Loading kernel32.dll was failed, just return
try
// 3) Load windows api IsWow64Process
@vIsWow64Process := GetProcAddress(vKernel32Handle, 'IsWow64Process');
if not Assigned(vIsWow64Process) then Exit; // Loading IsWow64Process was failed, just return
// 4) Execute IsWow64Process against our own process
vIsWow64 := False;
if (vIsWow64Process(GetCurrentProcess, vIsWow64)) then
Result := vIsWow64; // use the returned value
finally
FreeLibrary(vKernel32Handle); // unload the library
end;
end;
function TFrmConfig.get_registry: TRegistry;
begin
if FRegistry = nil then
FRegistry := cria_registry();
Result := FRegistry;
end;
end.
|
unit xElecBox;
interface
uses xElecLine, xElecPoint, xElecBusLine, xWiringError, xElecTV, xElecTA,
xElecLineBox, xElecMeter
;
Type
/// <summary>
/// 电表箱类型
/// </summary>
TElecBoxType = (ebtNot, // 未定义
ebtThree, // 三相三线
ebtFour // 三相四线
);
type
/// <summary>
/// 计量箱
/// </summary>
TElecBox = class
private
FElecBoxName: string;
FElecTA2: TElecTA;
FElecTA3: TElecTA;
FElecTA1: TElecTA;
FElecTV2: TElecTV;
FElecTV3: TElecTV;
FElecTV1: TElecTV;
FElecBoxType: TElecBoxType;
FWiringError: TWIRINGF_ERROR;
FElecLineBox: TElecLineBox;
FElecBusLine: TElecBusLine;
FElecMeter: TElecMeter;
procedure SetElecBoxType(const Value: TElecBoxType);
/// <summary>
/// 需要重新计算电压电流的事件
/// </summary>
procedure VCChangeEvent(Sender : TObject);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 计量箱名称
/// </summary>
property ElecBoxName : string read FElecBoxName write FElecBoxName;
/// <summary>
/// 计量箱类型
/// </summary>
property ElecBoxType : TElecBoxType read FElecBoxType write SetElecBoxType;
/// <summary>
/// 一次电缆线(母线)
/// </summary>
property ElecBusLine : TElecBusLine read FElecBusLine write FElecBusLine;
/// <summary>
/// 电压互感器1 (三线时用前两个互感器)
/// </summary>
property ElecTV1 : TElecTV read FElecTV1 write FElecTV1;
/// <summary>
/// 电压互感器2 (三线时用前两个互感器)
/// </summary>
property ElecTV2 : TElecTV read FElecTV2 write FElecTV2;
/// <summary>
/// 电压互感器3 (三线时用前两个互感器)
/// </summary>
property ElecTV3 : TElecTV read FElecTV3 write FElecTV3;
/// <summary>
/// 电流互感器1 (三线时用前两个互感器)
/// </summary>
property ElecTA1 : TElecTA read FElecTA1 write FElecTA1;
/// <summary>
/// 电流互感器2 (三线时用前两个互感器)
/// </summary>
property ElecTA2 : TElecTA read FElecTA2 write FElecTA2;
/// <summary>
/// 电流互感器3 (三线时用前两个互感器)
/// </summary>
property ElecTA3 : TElecTA read FElecTA3 write FElecTA3;
/// <summary>
/// 联合接线盒
/// </summary>
property ElecLineBox : TElecLineBox read FElecLineBox write FElecLineBox;
/// <summary>
/// 电能表
/// </summary>
property ElecMeter : TElecMeter read FElecMeter write FElecMeter;
public
/// <summary>
/// 接线错误
/// </summary>
property WiringError : TWIRINGF_ERROR read FWiringError write FWiringError;
/// <summary>
/// 刷新值
/// </summary>
procedure RefurshValue;
public
/// <summary>
/// 清空电压值
/// </summary>
procedure ClearVolVlaue;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
/// <summary>
/// 清空电流列表
/// </summary>
procedure ClearCurrentList;
end;
implementation
{ TElecBox }
procedure TElecBox.ClearCurrentList;
begin
FElecTA2.FirstClearCurrentList;
FElecTA3.FirstClearCurrentList;
FElecTA1.FirstClearCurrentList;
FElecTA2.SecondClearCurrentList;
FElecTA3.SecondClearCurrentList;
FElecTA1.SecondClearCurrentList;
FElecTV2.ClearCurrentList;
FElecTV3.ClearCurrentList;
FElecTV1.ClearCurrentList;
FElecLineBox.ClearCurrentList;
FElecBusLine.ClearCurrentList;
FElecMeter.ClearCurrentList;
end;
procedure TElecBox.ClearVolVlaue;
begin
end;
procedure TElecBox.ClearWValue;
begin
FElecTA2.FirstClearWValue;
FElecTA3.FirstClearWValue;
FElecTA1.FirstClearWValue;
FElecTA2.SecondClearWValue;
FElecTA3.SecondClearWValue;
FElecTA1.SecondClearWValue;
FElecTV2.ClearWValue;
FElecTV3.ClearWValue;
FElecTV1.ClearWValue;
FElecLineBox.ClearWValue;
FElecMeter.ClearWValue;
end;
constructor TElecBox.Create;
begin
FElecBoxName:= '计量箱';
FElecTA2:= TElecTA.Create;
FElecTA3:= TElecTA.Create;
FElecTA1:= TElecTA.Create;
FElecTV2:= TElecTV.Create;
FElecTV3:= TElecTV.Create;
FElecTV1:= TElecTV.Create;
FWiringError:= TWIRINGF_ERROR.Create;
FElecLineBox:= TElecLineBox.Create;
FElecBusLine:= TElecBusLine.Create;
FElecMeter:= TElecMeter.Create;
FElecBoxType:= ebtNot;
FElecLineBox.OnChange := VCChangeEvent;
FWiringError.OnChanged := VCChangeEvent;
FElecTA2.TAName := 'TA2';
FElecTA3.TAName := 'TA3';
FElecTA1.TAName := 'TA1';
FElecTV2.TVName := 'TV2';
FElecTV3.TVName := 'TV3';
FElecTV1.TVName := 'TV1';
FElecTA1.SecondCurrentL.Current.WeightValue[100].WValue := 0;
FElecTA2.SecondCurrentL.Current.WeightValue[101].WValue := 0;
FElecTA3.SecondCurrentL.Current.WeightValue[102].WValue := 0;
FElecTA1.SecondCurrentH.WID := 100;
FElecTA2.SecondCurrentH.WID := 101;
FElecTA3.SecondCurrentH.WID := 102;
ElecBoxType:= TElecBoxType.ebtFour;
// 刷新数据值
RefurshValue;
end;
destructor TElecBox.Destroy;
begin
FElecTA2.Free;
FElecTA3.Free;
FElecTA1.Free;
FElecTV2.Free;
FElecTV3.Free;
FElecTV1.Free;
FWiringError.Free;
FElecLineBox.Free;
FElecBusLine.Free;
FElecMeter.Free;
inherited;
end;
procedure TElecBox.RefurshValue;
begin
FElecBusLine.RefurshValue;
// 电流值传递(所有电流都流到电流低端)
// 清空权值
ClearWValue;
// 递归所有电流低端节点
// 赋值权值
FElecBusLine.BusLineN.CalcCurrWValue;
// 清空原件电流列表
ClearCurrentList;
// 初始化电流原件电流列表
FElecBusLine.BusLineA.SendCurrentValue;
FElecBusLine.BusLineB.SendCurrentValue;
FElecBusLine.BusLineC.SendCurrentValue;
FElecTA1.RefurshValue;
FElecTA2.RefurshValue;
FElecTA3.RefurshValue;
end;
procedure TElecBox.SetElecBoxType(const Value: TElecBoxType);
begin
if FElecBoxType <> Value then
begin
FElecBoxType := Value;
case FElecBoxType of
ebtThree :
begin
end;
ebtFour :
begin
// 电缆到电压互感器
FElecBusLine.BusLineA.ConnPointAdd(FElecTV1.FirstVolH);
FElecBusLine.BusLineB.ConnPointAdd(FElecTV2.FirstVolH);
FElecBusLine.BusLineC.ConnPointAdd(FElecTV3.FirstVolH);
FElecBusLine.BusLineN.ConnPointAdd(FElecTV1.FirstVolL);
FElecBusLine.BusLineN.ConnPointAdd(FElecTV2.FirstVolL);
FElecBusLine.BusLineN.ConnPointAdd(FElecTV3.FirstVolL);
// 电缆到电流互感器
FElecBusLine.BusLineA.ConnPointAdd(FElecTA1.FirstCurrentH);
FElecBusLine.BusLineB.ConnPointAdd(FElecTA2.FirstCurrentH);
FElecBusLine.BusLineC.ConnPointAdd(FElecTA3.FirstCurrentH);
FElecBusLine.BusLineN.ConnPointAdd(FElecTA1.FirstCurrentL);
FElecBusLine.BusLineN.ConnPointAdd(FElecTA2.FirstCurrentL);
FElecBusLine.BusLineN.ConnPointAdd(FElecTA3.FirstCurrentL);
// 电压互感器到联合接线盒
FElecTV1.SecondVolH.ConnPointAdd(FElecLineBox.BoxUA.InLineVol);
FElecTV2.SecondVolH.ConnPointAdd(FElecLineBox.BoxUB.InLineVol);
FElecTV3.SecondVolH.ConnPointAdd(FElecLineBox.BoxUC.InLineVol);
FElecTV1.SecondVolL.ConnPointAdd(FElecLineBox.BoxUN.InLineVol);
FElecTV2.SecondVolL.ConnPointAdd(FElecLineBox.BoxUN.InLineVol);
FElecTV3.SecondVolL.ConnPointAdd(FElecLineBox.BoxUN.InLineVol);
// 电流互感器到联合接线盒
FElecTA1.SecondCurrentH.ConnPointAdd(FElecLineBox.BoxIA.InLineCurrent1);
FElecTA2.SecondCurrentH.ConnPointAdd(FElecLineBox.BoxIB.InLineCurrent1);
FElecTA3.SecondCurrentH.ConnPointAdd(FElecLineBox.BoxIC.InLineCurrent1);
FElecTA1.SecondCurrentL.ConnPointAdd(FElecLineBox.BoxIA.InLineCurrent2);
FElecTA2.SecondCurrentL.ConnPointAdd(FElecLineBox.BoxIB.InLineCurrent2);
FElecTA3.SecondCurrentL.ConnPointAdd(FElecLineBox.BoxIC.InLineCurrent2);
// 联合接线盒到电表
FElecMeter.ElecPhase := epFour;
FElecLineBox.BoxUA.OutLineVol.ConnPointAdd(FElecMeter.TerminalInfoByName['Ua']);
FElecLineBox.BoxUB.OutLineVol.ConnPointAdd(FElecMeter.TerminalInfoByName['Ub']);
FElecLineBox.BoxUC.OutLineVol.ConnPointAdd(FElecMeter.TerminalInfoByName['Uc']);
FElecLineBox.BoxUN.OutLineVol.ConnPointAdd(FElecMeter.TerminalInfoByName['Un']);
FElecLineBox.BoxIA.OutLineCurrent1.ConnPointAdd(FElecMeter.TerminalInfoByName['Ia+']);
FElecLineBox.BoxIB.OutLineCurrent1.ConnPointAdd(FElecMeter.TerminalInfoByName['Ib+']);
FElecLineBox.BoxIC.OutLineCurrent1.ConnPointAdd(FElecMeter.TerminalInfoByName['Ic+']);
FElecLineBox.BoxIA.OutLineCurrent3.ConnPointAdd(FElecMeter.TerminalInfoByName['Ia-']);
FElecLineBox.BoxIB.OutLineCurrent3.ConnPointAdd(FElecMeter.TerminalInfoByName['Ib-']);
FElecLineBox.BoxIC.OutLineCurrent3.ConnPointAdd(FElecMeter.TerminalInfoByName['Ic-']);
end;
end;
end;
end;
procedure TElecBox.VCChangeEvent(Sender: TObject);
begin
RefurshValue;
end;
end.
|
namespace RemObjects.SDK.CodeGen4;
{$HIDE W46}
interface
type
JavaRodlCodeGen = public class (RodlCodeGen)
private
method isPrimitive(&type: String):Boolean;
method GenerateROSDKType(aName: String): String;
method GenerateGetProperty(aParent:CGExpression;Name:String): CGExpression;
method GenerateSetProperty(aParent:CGExpression;Name:String; aValue:CGExpression): CGStatement;
method GenerateOperationAttribute(library: RodlLibrary; entity: RodlOperation;Statements: List<CGStatement>);
method GetReaderStatement(library: RodlLibrary; entity: RodlTypedEntity; variableName: String := "aMessage"): CGStatement;
method GetReaderExpression(library: RodlLibrary; entity: RodlTypedEntity; variableName: String := "aMessage"): CGExpression;
method GetWriterStatement(library: RodlLibrary; entity: RodlTypedEntity; useGetter: Boolean := True; variableName: String := "aMessage"): CGStatement;
method GetWriterStatement_DefaultValues(library: RodlLibrary; entity: RodlTypedEntity; variableName: String := "aMessage"): CGStatement;
method WriteToMessage_Method(library: RodlLibrary; entity: RodlStructEntity;useDefaultValues:Boolean): CGMethodDefinition;
method ReadFromMessage_Method(library: RodlLibrary; entity: RodlStructEntity): CGMethodDefinition;
method GenerateServiceProxyMethod(library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
method GenerateServiceProxyMethodDeclaration(library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
method GenerateServiceAsyncProxyBeginMethod(library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
method GenerateServiceAsyncProxyEndMethod(library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
method GenerateServiceAsyncProxyBeginMethodDeclaration(library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
method GenerateServiceAsyncProxyEndMethodDeclaration(library: RodlLibrary; entity: RodlOperation;&locked:Boolean): CGMethodDefinition;
method GenerateServiceConstructors(library: RodlLibrary; entity: RodlService; service:CGClassTypeDefinition);
method HandleAtributes_private(library: RodlLibrary; entity: RodlEntity): CGFieldDefinition;
method HandleAtributes_public(library: RodlLibrary; entity: RodlEntity): CGMethodDefinition;
protected
method AddUsedNamespaces(file: CGCodeUnit; library: RodlLibrary);override;
method AddGlobalConstants(file: CGCodeUnit; library: RodlLibrary);override;
method GenerateEnum(file: CGCodeUnit; library: RodlLibrary; entity: RodlEnum); override;
method GenerateStruct(file: CGCodeUnit; library: RodlLibrary; entity: RodlStruct);override;
method GenerateArray(file: CGCodeUnit; library: RodlLibrary; entity: RodlArray);override;
method GenerateException(file: CGCodeUnit; library: RodlLibrary; entity: RodlException);override;
method GenerateService(file: CGCodeUnit; library: RodlLibrary; entity: RodlService);override;
method GenerateEventSink(file: CGCodeUnit; library: RodlLibrary; entity: RodlEventSink);override;
method GetGlobalName(library: RodlLibrary): String;override;
method GetIncludesNamespace(library: RodlLibrary): String; override;
public
constructor;
property addROSDKPrefix: Boolean := True;
property isCooperMode: Boolean := True;
method GenerateInterfaceFiles(library: RodlLibrary; aTargetNamespace: String): not nullable Dictionary<String,String>; override;
end;
implementation
constructor JavaRodlCodeGen;
begin
CodeGenTypes.Add("integer", ResolveStdtypes(CGPredefinedTypeReference.Int32,true));
CodeGenTypes.Add("datetime", "java.util.Date".AsTypeReference);
CodeGenTypes.Add("double", ResolveStdtypes(CGPredefinedTypeReference.Double,true));
CodeGenTypes.Add("currency", "java.math.BigDecimal".AsTypeReference);
CodeGenTypes.Add("widestring", ResolveStdtypes(CGPredefinedTypeReference.String));
CodeGenTypes.Add("ansistring", ResolveStdtypes(CGPredefinedTypeReference.String));
CodeGenTypes.Add("int64", ResolveStdtypes(CGPredefinedTypeReference.Int64,true));
CodeGenTypes.Add("boolean", ResolveStdtypes(CGPredefinedTypeReference.Boolean,true));
CodeGenTypes.Add("variant", "com.remobjects.sdk.VariantType".AsTypeReference);
CodeGenTypes.Add("binary", new CGArrayTypeReference(ResolveStdtypes(CGPredefinedTypeReference.Int8)));
CodeGenTypes.Add("xml", "com.remobjects.sdk.XmlType".AsTypeReference);
CodeGenTypes.Add("guid", "java.util.UUID".AsTypeReference);
CodeGenTypes.Add("decimal", "java.math.BigDecimal".AsTypeReference);
CodeGenTypes.Add("utf8string", ResolveStdtypes(CGPredefinedTypeReference.String));
CodeGenTypes.Add("xsdatetime", "java.util.Date".AsTypeReference);
ReaderFunctions.Add("integer", "Int32");
ReaderFunctions.Add("datetime", "DateTime");
ReaderFunctions.Add("double", "Double");
ReaderFunctions.Add("currency", "Currency");
ReaderFunctions.Add("widestring", "WideString");
ReaderFunctions.Add("ansistring", "AnsiString");
ReaderFunctions.Add("int64", "Int64");
ReaderFunctions.Add("boolean", "Boolean");
ReaderFunctions.Add("variant", "Variant");
ReaderFunctions.Add("binary", "Binary");
ReaderFunctions.Add("xml", "Xml");
ReaderFunctions.Add("guid", "Guid");
ReaderFunctions.Add("decimal", "Decimal");
ReaderFunctions.Add("utf8string", "Utf8String");
ReaderFunctions.Add("xsdatetime", "DateTime");
ReservedWords.Add([
"abstract", "and", "add", "async", "as", "begin", "break", "case", "class", "const", "constructor", "continue",
"delegate", "default", "div", "do", "downto", "each", "else", "empty", "end", "enum", "ensure", "event", "except",
"exit", "external", "false", "final", "finalizer", "finally", "flags", "for", "forward", "function", "global", "has",
"if", "implementation", "implements", "implies", "in", "index", "inline", "inherited", "interface", "invariants", "is",
"iterator", "locked", "locking", "loop", "matching", "method", "mod", "namespace", "nested", "new", "nil", "not",
"nullable", "of", "old", "on", "operator", "or", "out", "override", "pinned", "partial", "private", "property",
"protected", "public", "reintroduce", "raise", "read", "readonly", "remove", "repeat", "require", "result", "sealed",
"self", "sequence", "set", "shl", "shr", "static", "step", "then", "to", "true", "try", "type", "typeof", "until",
"unsafe", "uses", "using", "var", "virtual", "where", "while", "with", "write", "xor", "yield"]);
end;
method JavaRodlCodeGen.WriteToMessage_Method(&library: RodlLibrary; entity: RodlStructEntity;useDefaultValues:Boolean): CGMethodDefinition;
begin
Result := new CGMethodDefinition("writeToMessage",
Parameters := [new CGParameterDefinition("aName", ResolveStdtypes(CGPredefinedTypeReference.String)),
new CGParameterDefinition("aMessage", GenerateROSDKType("Message").AsTypeReference)].ToList,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public);
var lIfRecordStrictOrder_True := new CGBeginEndBlockStatement;
var lIfRecordStrictOrder_False := new CGBeginEndBlockStatement;
var lIfRecordStrictOrder := new CGIfThenElseStatement(GenerateGetProperty("aMessage".AsNamedIdentifierExpression,"UseStrictFieldOrderForStructs"),
lIfRecordStrictOrder_True,
lIfRecordStrictOrder_False
);
Result.Statements.Add(lIfRecordStrictOrder);
if assigned(entity.AncestorEntity) then begin
lIfRecordStrictOrder_True.Statements.Add(
new CGMethodCallExpression(CGInheritedExpression.Inherited, "writeToMessage",
["aName".AsNamedIdentifierExpression.AsCallParameter,
"aMessage".AsNamedIdentifierExpression.AsCallParameter].ToList)
);
end;
var lSortedFields := new Dictionary<String,RodlField>;
var lAncestorEntity := entity.AncestorEntity as RodlStructEntity;
while assigned(lAncestorEntity) do begin
for field: RodlField in lAncestorEntity.Items do
lSortedFields.Add(field.Name.ToLowerInvariant, field);
lAncestorEntity := lAncestorEntity.AncestorEntity as RodlStructEntity;
end;
for field: RodlField in entity.Items do
if not lSortedFields.ContainsKey(field.Name.ToLowerInvariant) then begin
lSortedFields.Add(field.Name.ToLowerInvariant, field);
lIfRecordStrictOrder_True.Statements.Add(
iif(useDefaultValues, GetWriterStatement_DefaultValues(library, field),GetWriterStatement(library, field))
);
end;
for lvalue: String in lSortedFields.Keys.ToList.Sort_OrdinalIgnoreCase(b->b) do
lIfRecordStrictOrder_False.Statements.Add(
iif(useDefaultValues, GetWriterStatement_DefaultValues(library, lSortedFields.Item[lvalue]),GetWriterStatement(library, lSortedFields.Item[lvalue]))
);
end;
method JavaRodlCodeGen.AddUsedNamespaces(file: CGCodeUnit; &library: RodlLibrary);
begin
for Rodl: RodlUse in library.Uses.Items do begin
if length(Rodl.Includes:JavaModule) > 0 then
file.Imports.Add(new CGImport(Rodl.Includes:JavaModule))
else if not String.IsNullOrEmpty(Rodl.Namespace) then
file.Imports.Add(new CGImport(Rodl.Namespace));
end;
if not addROSDKPrefix then
file.Imports.Add(new CGImport("com.remobjects.sdk"));
{
file.Imports.Add(new CGImport(new CGNamedTypeReference("java.net.URI")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("java.util.Collection")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("com.remobjects.sdk.ClientChannel")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("com.remobjects.sdk.Message")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("com.remobjects.sdk.ReferenceType")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("com.remobjects.sdk.TypeManager")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("com.remobjects.sdk.AsyncRequest")));
file.Imports.Add(new CGImport(new CGNamedTypeReference("com.remobjects.sdk.AsyncProxy")));
}
end;
method JavaRodlCodeGen.GenerateStruct(file: CGCodeUnit; library: RodlLibrary; entity: RodlStruct);
begin
var lancestorName := entity.AncestorName;
if String.IsNullOrEmpty(lancestorName) then lancestorName := GenerateROSDKType("ComplexType");
var lstruct := new CGClassTypeDefinition(SafeIdentifier(entity.Name), lancestorName.AsTypeReference,
&Partial := true,
Visibility := CGTypeVisibilityKind.Public
);
lstruct.Comment := GenerateDocumentation(entity);
file.Types.Add(lstruct);
{$REGION private class _attributes: HashMap<String, String>;}
if (entity.CustomAttributes.Count > 0) then
lstruct.Members.Add(HandleAtributes_private(&library,entity));
{$ENDREGION}
{$REGION protected class var s_%fldname%: %fldtype%}
for lm :RodlTypedEntity in entity.Items do begin
lstruct.Members.Add(
new CGFieldDefinition("s_"+lm.Name, ResolveDataTypeToTypeRef(&library,lm.DataType),
&Static := true,
Visibility := CGMemberVisibilityKind.Protected
));
end;
{$ENDREGION}
{$REGION public class method getAttributeValue(aName: String): String; override;}
if (entity.CustomAttributes.Count > 0) then
lstruct.Members.Add(HandleAtributes_public(&library,entity));
{$ENDREGION}
if entity.Items.Count >0 then begin
{$REGION public class method setDefaultValues(p_%fldname%: %fldtype%)}
var lsetDefaultValues := new CGMethodDefinition("setDefaultValues",
Visibility := CGMemberVisibilityKind.Public,
&Static := true
);
lstruct.Members.Add(lsetDefaultValues);
for lm: RodlTypedEntity in entity.Items do begin
lsetDefaultValues.Parameters.Add(
new CGParameterDefinition("p_"+lm.Name, ResolveDataTypeToTypeRef(&library,lm.DataType)));
lsetDefaultValues.Statements.Add(
new CGAssignmentStatement(
("s_"+lm.Name).AsNamedIdentifierExpression,
("p_"+lm.Name).AsNamedIdentifierExpression
)
);
end;
{$ENDREGION}
{$REGION private %f_fldname%: %fldtype% + public getter/setter}
for lm :RodlTypedEntity in entity.Items do begin
var ltype := ResolveDataTypeToTypeRef(&library,lm.DataType);
var f_name :='f_'+lm.Name;
var s_name :='s_'+lm.Name;
lstruct.Members.Add(new CGFieldDefinition(f_name,
ltype,
Visibility := CGMemberVisibilityKind.Private));
if not isCooperMode then begin
lstruct.Members.Add(new CGMethodDefinition('set'+lm.Name,
[new CGAssignmentStatement(f_name.AsNamedIdentifierExpression,'aValue'.AsNamedIdentifierExpression)],
Parameters := [new CGParameterDefinition('aValue',ltype)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
lstruct.Members.Add(new CGMethodDefinition('get'+lm.Name,
[new CGIfThenElseStatement(new CGBinaryOperatorExpression(f_name.AsNamedIdentifierExpression, CGNilExpression.Nil, CGBinaryOperatorKind.NotEquals),
f_name.AsNamedIdentifierExpression.AsReturnStatement,
s_name.AsNamedIdentifierExpression.AsReturnStatement)],
ReturnType := ltype,
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
end;
end;
{$ENDREGION}
{$REGION public method writeToMessage(aName: String; aMessage: Message); override;}
lstruct.Members.Add(WriteToMessage_Method(&library,entity,true));
{$ENDREGION}
{$REGION method ReadFromMessage_Method(aName: String; aMessage: Message); override;}
lstruct.Members.Add(ReadFromMessage_Method(&library,entity));
{$ENDREGION}
{$REGION public property %fldname%: %fldtype%}
if isCooperMode then begin
for lm :RodlTypedEntity in entity.Items do begin
var f_name :='f_'+lm.Name;
var s_name :='s_'+lm.Name;
var st1: CGStatement :=new CGIfThenElseStatement(new CGBinaryOperatorExpression(f_name.AsNamedIdentifierExpression, CGNilExpression.Nil, CGBinaryOperatorKind.NotEquals),
f_name.AsNamedIdentifierExpression.AsReturnStatement,
s_name.AsNamedIdentifierExpression.AsReturnStatement);
//var st2: CGStatement :=new CGAssignmentStatement(f_name.AsNamedIdentifierExpression,CGPropertyDefinition.MAGIC_VALUE_PARAMETER_NAME.AsNamedIdentifierExpression);
lstruct.Members.Add(new CGPropertyDefinition(lm.Name,
ResolveDataTypeToTypeRef(&library,lm.DataType),
[st1].ToList,
SetExpression := f_name.AsNamedIdentifierExpression,
Visibility := CGMemberVisibilityKind.Public,
Comment := GenerateDocumentation(lm)));
end;
end;
{$ENDREGION}
end;
end;
method JavaRodlCodeGen.GenerateArray(file: CGCodeUnit; library: RodlLibrary; entity: RodlArray);
begin
var lElementType: CGTypeReference := ResolveDataTypeToTypeRef(&library, SafeIdentifier(entity.ElementType));
var lElementTypeName: String := entity.ElementType.ToLowerInvariant();
var lIsStandardType: Boolean := ReaderFunctions.ContainsKey(lElementTypeName);
var lIsEnum: Boolean := isEnum(&library, entity.ElementType);
var lIsArray: Boolean := isArray(&library, entity.ElementType);
var lIsStruct: Boolean := isStruct(&library, entity.ElementType);
var lArray := new CGClassTypeDefinition(SafeIdentifier(entity.Name), GenerateROSDKType("ArrayType").AsTypeReference,
Visibility := CGTypeVisibilityKind.Public,
&Partial := true
);
lArray.Comment := GenerateDocumentation(entity);
file.Types.Add(lArray);
if not isCooperMode then begin
lArray.Attributes.Add(new CGAttribute("SuppressWarnings".AsTypeReference,
["rawtypes".AsLiteralExpression.AsCallParameter].ToList));
end;
{$REGION Private class _attributes: HashMap<String, String>;}
if (entity.CustomAttributes.Count > 0) then begin
lArray.Members.Add(HandleAtributes_private(&library,entity));
end;
{$ENDREGION}
{$REGION Enum values cache}
// Actually this should be a static variable. Unfortunately it seems that atm the codegen doesn't allow to define static constructors
if lIsEnum then begin
// Cache field
lArray.Members.Add(new CGFieldDefinition('fEnumValues', new CGArrayTypeReference(lElementType)));
// Cache initializer
lArray.Members.Add(
new CGMethodDefinition('initEnumValues',
[ new CGAssignmentStatement(new CGFieldAccessExpression(CGSelfExpression.Self, 'fEnumValues'),
new CGMethodCallExpression(lElementType.AsExpression(), 'values')) ],
Visibility := CGMemberVisibilityKind.Private));
end;
{$ENDREGION}
{$REGION Optional initializer call}
var lInitializerCall: CGStatement := iif(lIsEnum, new CGMethodCallExpression(CGSelfExpression.Self, 'initEnumValues'), nil);
{$ENDREGION}
{$REGION .ctor}
var lStatements1 := new List<CGStatement>();
lStatements1.Add(new CGConstructorCallStatement(CGInheritedExpression.Inherited, new List<CGCallParameter>()));
if assigned(lInitializerCall) then begin
lStatements1.Add(lInitializerCall);
end;
lArray.Members.Add(
new CGConstructorDefinition(
Visibility := CGMemberVisibilityKind.Public,
Statements := lStatements1
)
);
{$ENDREGION}
{$REGION .ctor(aCapacity: Integer)}
var lStatements2 := new List<CGStatement>();
lStatements2.Add(new CGConstructorCallStatement(CGInheritedExpression.Inherited, [ "aCapacity".AsNamedIdentifierExpression().AsCallParameter() ].ToList()));
if assigned(lInitializerCall) then begin
lStatements2.Add(lInitializerCall);
end;
lArray.Members.Add(
new CGConstructorDefinition(
Parameters := [ new CGParameterDefinition("aCapacity", ResolveStdtypes(CGPredefinedTypeReference.Int32)) ].ToList(),
Visibility := CGMemberVisibilityKind.Public,
Statements := lStatements2
)
);
{$ENDREGION}
{$REGION .ctor(aCollection: Collection)}
var lStatements3 := new List<CGStatement>();
lStatements3.Add(new CGConstructorCallStatement(CGInheritedExpression.Inherited, ["aCollection".AsNamedIdentifierExpression().AsCallParameter() ].ToList()));
if assigned(lInitializerCall) then begin
lStatements3.Add(lInitializerCall);
end;
lArray.Members.Add(
new CGConstructorDefinition(
Visibility := CGMemberVisibilityKind.Public,
Parameters := [ new CGParameterDefinition("aCollection", "java.util.Collection".AsTypeReference()) ].ToList(),
Statements := lStatements3
)
);
{$ENDREGION}
{$REGION .ctor(anArray: array of Object)}
var lStatements4 := new List<CGStatement>();
lStatements4.Add(new CGConstructorCallStatement(CGInheritedExpression.Inherited, [ "anArray".AsNamedIdentifierExpression().AsCallParameter() ].ToList()));
if assigned(lInitializerCall) then begin
lStatements4.Add(lInitializerCall);
end;
lArray.Members.Add(
new CGConstructorDefinition(
Visibility := CGMemberVisibilityKind.Public,
Parameters := [ new CGParameterDefinition("anArray", new CGArrayTypeReference(ResolveStdtypes(CGPredefinedTypeReference.Object))) ].ToList(),
Statements:= lStatements4
)
);
{$ENDREGION}
{$REGION method add: %ARRAY_TYPE%;}
if isComplex(&library,entity.ElementType) then
lArray.Members.Add(
new CGMethodDefinition("add",
Visibility := CGMemberVisibilityKind.Public,
ReturnType := lElementType,
Statements:=
[new CGVariableDeclarationStatement('lresult',lElementType,new CGNewInstanceExpression(lElementType)),
new CGMethodCallExpression(CGInheritedExpression.Inherited, "addItem", ["lresult".AsNamedIdentifierExpression.AsCallParameter].ToList),
"lresult".AsNamedIdentifierExpression.AsReturnStatement
].ToList
)
);
{$ENDREGION}
{$REGION public class method getAttributeValue(aName: String): String; override;}
if (entity.CustomAttributes.Count > 0) then
lArray.Members.Add(HandleAtributes_public(&library,entity));
{$ENDREGION}
{$REGION method addItem(anItem: %ARRAY_TYPE%)}
lArray.Members.Add(
new CGMethodDefinition("addItem",
[new CGMethodCallExpression(CGInheritedExpression.Inherited, "addItem", ["anItem".AsNamedIdentifierExpression.AsCallParameter].ToList)],
Visibility := CGMemberVisibilityKind.Public,
Parameters := [new CGParameterDefinition("anItem", lElementType)].ToList));
{$ENDREGION}
{$REGION method insertItem(anItem: %ARRAY_TYPE%; anIndex: Integer);}
lArray.Members.Add(
new CGMethodDefinition("insertItem",
[new CGMethodCallExpression(CGInheritedExpression.Inherited,"insertItem",
["anItem".AsNamedIdentifierExpression.AsCallParameter,
"anIndex".AsNamedIdentifierExpression.AsCallParameter].ToList)],
Parameters := [new CGParameterDefinition("anItem", lElementType),
new CGParameterDefinition("anIndex", ResolveStdtypes(CGPredefinedTypeReference.Int32))].ToList,
Visibility := CGMemberVisibilityKind.Public));
{$ENDREGION}
{$REGION method replaceItemAtIndex(anItem: %ARRAY_TYPE%; anIndex: Integer);}
lArray.Members.Add(
new CGMethodDefinition("replaceItemAtIndex",
[new CGMethodCallExpression(CGInheritedExpression.Inherited, "replaceItemAtIndex",
["anItem".AsNamedIdentifierExpression.AsCallParameter,
"anIndex".AsNamedIdentifierExpression.AsCallParameter].ToList)],
Parameters := [new CGParameterDefinition("anItem", lElementType),
new CGParameterDefinition("anIndex", ResolveStdtypes(CGPredefinedTypeReference.Int32))].ToList,
Visibility := CGMemberVisibilityKind.Public
)
);
{$ENDREGION}
{$REGION method getItemAtIndex(anIndex: Integer): %ARRAY_TYPE%; override;}
lArray.Members.Add(
new CGMethodDefinition("getItemAtIndex",
[
CGStatement(
new CGTypeCastExpression(
new CGMethodCallExpression(CGInheritedExpression.Inherited, 'getItemAtIndex', [ 'anIndex'.AsNamedIdentifierExpression().AsCallParameter() ].ToList()),
lElementType,
ThrowsException := true
).AsReturnStatement()
)
].ToList(),
Parameters := [ new CGParameterDefinition("anIndex", ResolveStdtypes(CGPredefinedTypeReference.Int32)) ].ToList(),
ReturnType := lElementType,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public)
);
{$ENDREGION}
{$REGION method itemClass: &Class;}
lArray.Members.Add(
new CGMethodDefinition("itemClass",
[new CGTypeOfExpression(lElementType.AsExpression).AsReturnStatement],
ReturnType := "Class".AsTypeReference,
Visibility := CGMemberVisibilityKind.Public
)
);
{$ENDREGION}
{$REGION method itemTypeName: String;}
lArray.Members.Add(
new CGMethodDefinition("itemTypeName",
[SafeIdentifier(entity.ElementType).AsLiteralExpression.AsReturnStatement],
ReturnType := ResolveStdtypes(CGPredefinedTypeReference.String),
Visibility := CGMemberVisibilityKind.Public
)
);
{$ENDREGION}
{$REGION method writeItemToMessage(aMessage: Message; anIndex: Integer); override;}
var l_methodName: String;
if lIsStandardType then begin
l_methodName := ReaderFunctions[lElementTypeName];
end
else if lIsArray then begin
l_methodName := "Array";
end
else if lIsStruct then begin
l_methodName := "Complex";
end
else if lIsEnum then begin
l_methodName := "Enum";
end;
var l_arg0 := new CGNilExpression().AsCallParameter;
var l_arg1_exp: CGExpression := new CGMethodCallExpression(CGSelfExpression.Self,"getItemAtIndex",["anIndex".AsNamedIdentifierExpression.AsCallParameter].ToList);
if lIsEnum then begin
l_arg1_exp := new CGMethodCallExpression(l_arg1_exp,"ordinal");
end;
var l_arg1 := l_arg1_exp.AsCallParameter;
lArray.Members.Add(
new CGMethodDefinition("writeItemToMessage",
[new CGMethodCallExpression("aMessage".AsNamedIdentifierExpression,"write" + l_methodName, [l_arg0,l_arg1].ToList)],
Parameters := [new CGParameterDefinition("aMessage", GenerateROSDKType("Message").AsTypeReference),
new CGParameterDefinition("anIndex", ResolveStdtypes(CGPredefinedTypeReference.Int32))].ToList,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public
)
);
{$ENDREGION}
{$REGION method readItemFromMessage(aMessage: Message; anIndex: Integer); override;}
var lArgList: List<CGCallParameter>;
if lIsStruct or lIsArray then begin
lArgList := [ l_arg0, new CGTypeOfExpression(lElementType.AsExpression()).AsCallParameter() ].ToList();
end
else begin
lArgList := [ l_arg0 ].ToList();
end;
var lMethodStatements: List<CGStatement> := new List<CGStatement>();
if lIsEnum then begin
lMethodStatements.Add(
new CGMethodCallExpression(
CGSelfExpression.Self,
"addItem",
[
new CGArrayElementAccessExpression(
new CGFieldAccessExpression(CGSelfExpression.Self, 'fEnumValues'),
[ CGExpression(new CGMethodCallExpression('aMessage'.AsNamedIdentifierExpression(), 'readEnum', lArgList)) ].ToList()
).AsCallParameter()
].ToList()
)
);
end
else begin
lMethodStatements.Add(
new CGMethodCallExpression(
CGSelfExpression.Self,
"addItem",
[ new CGMethodCallExpression("aMessage".AsNamedIdentifierExpression(), "read" + l_methodName, lArgList).AsCallParameter() ].ToList()
)
);
end;
lArray.Members.Add(
new CGMethodDefinition(
"readItemFromMessage",
lMethodStatements,
Parameters := [new CGParameterDefinition("aMessage", GenerateROSDKType("Message").AsTypeReference),
new CGParameterDefinition("anIndex", ResolveStdtypes(CGPredefinedTypeReference.Int32))].ToList,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public
)
);
{$ENDREGION}
end;
method JavaRodlCodeGen.GenerateException(file: CGCodeUnit; library: RodlLibrary; entity: RodlException);
begin
var lexception := new CGClassTypeDefinition(SafeIdentifier(entity.Name),
GenerateROSDKType("ExceptionType").AsTypeReference,
Visibility := CGTypeVisibilityKind.Public,
&Partial := true
);
lexception.Comment := GenerateDocumentation(entity);
file.Types.Add(lexception);
if not isCooperMode then
lexception.Attributes.Add(new CGAttribute("SuppressWarnings".AsTypeReference,
["serial".AsLiteralExpression.AsCallParameter].ToList));
{$REGION private class _attributes: HashMap<String, String>;}
if (entity.CustomAttributes.Count > 0) then
lexception.Members.Add(HandleAtributes_private(&library,entity));
{$ENDREGION}
{$REGION public class method getAttributeValue(aName: String): String; override;}
if (entity.CustomAttributes.Count > 0) then
lexception.Members.Add(HandleAtributes_public(&library,entity));
{$ENDREGION}
if not isCooperMode then begin
{$REGION private property %f_fldname%: %fldtype% + public getter/setter}
for lm :RodlTypedEntity in entity.Items do begin
var ltype := ResolveDataTypeToTypeRef(&library,lm.DataType);
var f_name :='f_'+lm.Name;
lexception.Members.Add(new CGFieldDefinition(f_name,
ltype,
Visibility := CGMemberVisibilityKind.Private));
if not isCooperMode then begin
lexception.Members.Add(new CGMethodDefinition('set'+lm.Name,
[new CGAssignmentStatement(f_name.AsNamedIdentifierExpression,'aValue'.AsNamedIdentifierExpression)],
Parameters := [new CGParameterDefinition('aValue',ltype)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
lexception.Members.Add(new CGMethodDefinition('get'+lm.Name,
[f_name.AsNamedIdentifierExpression.AsReturnStatement],
ReturnType := ltype,
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
end;
end;
{$ENDREGION}
end;
{$REGION .ctor(aExceptionMessage: String)}
lexception.Members.Add(
new CGConstructorDefinition(
Parameters := [new CGParameterDefinition("anExceptionMessage", ResolveStdtypes(CGPredefinedTypeReference.String))].ToList,
Visibility := CGMemberVisibilityKind.Public,
Statements := [CGStatement(new CGConstructorCallStatement(CGInheritedExpression.Inherited,
["anExceptionMessage".AsNamedIdentifierExpression.AsCallParameter].ToList))].ToList
));
{$ENDREGION}
{$REGION .ctor(aExceptionMessage: String; aFromServer: Boolean)}
lexception.Members.Add(
new CGConstructorDefinition(
Parameters :=[new CGParameterDefinition("anExceptionMessage", ResolveStdtypes(CGPredefinedTypeReference.String)),
new CGParameterDefinition("aFromServer", ResolveStdtypes(CGPredefinedTypeReference.Boolean))].ToList,
Visibility := CGMemberVisibilityKind.Public,
Statements:= [CGStatement(
new CGConstructorCallStatement(CGInheritedExpression.Inherited,
["anExceptionMessage".AsNamedIdentifierExpression.AsCallParameter,
"aFromServer".AsNamedIdentifierExpression.AsCallParameter].ToList))].ToList
));
{$ENDREGION}
if entity.Items.Count >0 then begin
{$REGION public method writeToMessage(aName: String; aMessage: Message); override;}
lexception.Members.Add(WriteToMessage_Method(&library,entity,false));
{$ENDREGION}
{$REGION method ReadFromMessage_Method(aName: String; aMessage: Message); override;}
lexception.Members.Add(ReadFromMessage_Method(&library,entity));
{$ENDREGION}
end;
{$REGION public property %fldname%: %fldtype%}
if isCooperMode then begin
for lm :RodlTypedEntity in entity.Items do
lexception.Members.Add(new CGPropertyDefinition(
lm.Name,
ResolveDataTypeToTypeRef(&library,lm.DataType),
Visibility := CGMemberVisibilityKind.Public,
Comment := GenerateDocumentation(lm)));
end;
{$ENDREGION}
end;
method JavaRodlCodeGen.GenerateService(file: CGCodeUnit; library: RodlLibrary; entity: RodlService);
begin
{$REGION I%SERVICE_NAME%}
var lIService := new CGInterfaceTypeDefinition(SafeIdentifier("I"+entity.Name),
Visibility := CGTypeVisibilityKind.Public);
lIService.Comment := GenerateDocumentation(entity);
file.Types.Add(lIService);
for lop : RodlOperation in entity.DefaultInterface:Items do begin
var m := GenerateServiceProxyMethodDeclaration(&library, lop);
m.Comment := GenerateDocumentation(lop,true);
lIService.Members.Add(m);
end;
{$ENDREGION}
{$REGION I%SERVICE_NAME%_Async}
var lIServiceAsync := new CGInterfaceTypeDefinition(SafeIdentifier("I"+entity.Name+"_Async"),
Visibility := CGTypeVisibilityKind.Public
);
file.Types.Add(lIServiceAsync);
for lop : RodlOperation in entity.DefaultInterface:Items do begin
lIServiceAsync.Members.Add(GenerateServiceAsyncProxyBeginMethodDeclaration(&library, lop));
lIServiceAsync.Members.Add(GenerateServiceAsyncProxyEndMethodDeclaration(&library, lop,false));
end;
{$ENDREGION}
{$REGION %SERVICE_NAME%_Proxy}
var lancestorName := entity.AncestorName;
if String.IsNullOrEmpty(lancestorName) then
lancestorName := GenerateROSDKType("Proxy")
else
lancestorName := lancestorName+"_Proxy";
var lServiceProxy := new CGClassTypeDefinition(SafeIdentifier(entity.Name+"_Proxy"),
[lancestorName.AsTypeReference].ToList,
[lIService.Name.AsTypeReference].ToList,
Visibility := CGTypeVisibilityKind.Public,
&Partial := true
);
file.Types.Add(lServiceProxy);
GenerateServiceConstructors(&library,entity, lServiceProxy);
for lop : RodlOperation in entity.DefaultInterface:Items do
lServiceProxy.Members.Add(GenerateServiceProxyMethod(&library,lop));
{$ENDREGION}
{$REGION %SERVICE_NAME%_AsyncProxy}
var lServiceAsyncProxy := new CGClassTypeDefinition(SafeIdentifier(entity.Name+"_AsyncProxy"),
[GenerateROSDKType("AsyncProxy").AsTypeReference].ToList,
[lIServiceAsync.Name.AsTypeReference].ToList,
Visibility := CGTypeVisibilityKind.Public,
&Partial := true);
file.Types.Add(lServiceAsyncProxy);
GenerateServiceConstructors(&library,entity,lServiceAsyncProxy);
for lop : RodlOperation in entity.DefaultInterface:Items do begin
lServiceAsyncProxy.Members.Add(GenerateServiceAsyncProxyBeginMethod(&library, lop));
lServiceAsyncProxy.Members.Add(GenerateServiceAsyncProxyEndMethod(&library, lop));
end;
{$ENDREGION}
end;
method JavaRodlCodeGen.GenerateEventSink(file: CGCodeUnit; library: RodlLibrary; entity: RodlEventSink);
begin
var i_name := 'I'+entity.Name;
var i_adaptername := i_name+'_Adapter';
var lIEvent := new CGInterfaceTypeDefinition(i_name,GenerateROSDKType("IEvents").AsTypeReference,
Visibility := CGTypeVisibilityKind.Public);
lIEvent.Comment := GenerateDocumentation(entity);
file.Types.Add(lIEvent);
for lop : RodlOperation in entity.DefaultInterface:Items do begin
{$REGION %event_sink%Event}
var lOperation := new CGClassTypeDefinition(SafeIdentifier(lop.Name+"Event"),GenerateROSDKType("EventType").AsTypeReference,
Visibility := CGTypeVisibilityKind.Public,
&Partial := true
);
if not isCooperMode then begin
for lm :RodlParameter in lop.Items do begin
var ltype := ResolveDataTypeToTypeRef(&library,lm.DataType);
var f_name :='f_'+lm.Name;
lOperation.Members.Add(new CGFieldDefinition(f_name,
ltype,
Visibility := CGMemberVisibilityKind.Private));
lOperation.Members.Add(new CGMethodDefinition('set'+lm.Name,
[new CGAssignmentStatement(f_name.AsNamedIdentifierExpression,'aValue'.AsNamedIdentifierExpression)],
Parameters := [new CGParameterDefinition('aValue',ltype)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
lOperation.Members.Add(new CGMethodDefinition('get'+lm.Name,
[f_name.AsNamedIdentifierExpression.AsReturnStatement],
ReturnType := ltype,
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
end;
end;
var lop_method := new CGConstructorDefinition(
Parameters:=[new CGParameterDefinition("aBuffer", GenerateROSDKType("Message").AsTypeReference)].ToList,
Visibility := CGMemberVisibilityKind.Public);
lOperation.Members.Add(lop_method);
for lm :RodlParameter in lop.Items do begin
if isCooperMode then begin
lOperation.Members.Add(new CGPropertyDefinition(
lm.Name,
ResolveDataTypeToTypeRef(&library,lm.DataType),
Visibility := CGMemberVisibilityKind.Public,
Comment:= GenerateDocumentation(lm)));
end;
lop_method.Statements.Add(GetReaderStatement(&library,lm,"aBuffer"));
end;
file.Types.Add(lOperation);
{$ENDREGION}
lIEvent.Members.Add(new CGMethodDefinition(SafeIdentifier(lop.Name),
Parameters := [new CGParameterDefinition("aEvent", lOperation.Name.AsTypeReference)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Comment := GenerateDocumentation(lop,false)
));
end;
if not isCooperMode then begin
var lIEventAdapter := new CGClassTypeDefinition(i_adaptername,
ImplementedInterfaces := [i_name.AsTypeReference].ToList,
Visibility := CGTypeVisibilityKind.Public);
file.Types.Add(lIEventAdapter);
for lop : RodlOperation in entity.DefaultInterface:Items do begin
lIEventAdapter.Members.Add(new CGMethodDefinition(SafeIdentifier(lop.Name),
Parameters := [new CGParameterDefinition("aEvent", SafeIdentifier(lop.Name+"Event").AsTypeReference)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Virtuality := CGMemberVirtualityKind.Override
));
end;
lIEventAdapter.Members.Add(new CGMethodDefinition("OnException",
Parameters := [new CGParameterDefinition("aEvent", GenerateROSDKType("OnExceptionEvent").AsTypeReference)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Virtuality := CGMemberVirtualityKind.Override
));
end;
end;
method JavaRodlCodeGen.GetWriterStatement_DefaultValues(&library: RodlLibrary; entity: RodlTypedEntity;variableName: String): CGStatement;
begin
var lentityname := entity.Name;
var lLower: String := entity.DataType.ToLowerInvariant();
var l_isStandard := ReaderFunctions.ContainsKey(lLower);
var l_isArray := False;
var l_isStruct := False;
var l_isEnum := False;
var l_methodName: String;
if l_isStandard then begin
l_methodName := ReaderFunctions[lLower];
end
else if isArray(&library, entity.DataType) then begin
l_methodName := "Array";
l_isArray := True;
end
else if isStruct(&library, entity.DataType) then begin
l_methodName := "Complex";
l_isStruct :=True;
end
else if isEnum(&library, entity.DataType) then begin
l_methodName := "Enum";
l_isEnum := True;
end;
var entityname_ID := GenerateGetProperty(CGSelfExpression.Self,lentityname);
// var s_entityname_ID := ("s_"+lentityname).AsNamedIdentifierExpression;
var l_if_conditional := new CGAssignedExpression(entityname_ID);
var l_varname := variableName.AsNamedIdentifierExpression;
var l_write := "write" + l_methodName;
var l_arg0 := lentityname.AsLiteralExpression.AsCallParameter;
var l_arg1 := entityname_ID.AsCallParameter;
if l_isStandard or l_isStruct or l_isArray then begin
exit new CGMethodCallExpression(l_varname,l_write, [l_arg0,l_arg1].ToList);
end
else if l_isEnum then begin
exit new CGIfThenElseStatement(
l_if_conditional,
new CGMethodCallExpression(l_varname,
l_write,
[l_arg0,
new CGMethodCallExpression(entityname_ID,"ordinal").AsCallParameter].ToList),
new CGBeginEndBlockStatement([CGStatement(
new CGMethodCallExpression(l_varname,l_write, [l_arg0,new CGIntegerLiteralExpression(0).AsCallParameter].ToList)
{ new CGIfThenElseStatement(
new CGAssignedExpression(s_entityname_ID),
new CGMethodCallExpression(l_varname,l_write, [l_arg0,new CGMethodCallExpression(s_entityname_ID,"ordinal").AsCallParameter].ToList),
new CGMethodCallExpression(l_varname,l_write, [l_arg0,new CGIntegerLiteralExpression(0).AsCallParameter].ToList)
)}
)].ToList)
);
end
else begin
raise new Exception(String.Format("unknown type: {0}",[entity.DataType]));
end;
end;
method JavaRodlCodeGen.ReadFromMessage_Method(&library: RodlLibrary; entity: RodlStructEntity): CGMethodDefinition;
begin
Result := new CGMethodDefinition("readFromMessage",
Parameters := [new CGParameterDefinition("aName", ResolveStdtypes(CGPredefinedTypeReference.String)),
new CGParameterDefinition("aMessage",GenerateROSDKType("Message").AsTypeReference)].ToList,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public);
var lIfRecordStrictOrder_True := new CGBeginEndBlockStatement;
var lIfRecordStrictOrder_False := new CGBeginEndBlockStatement;
var lIfRecordStrictOrder := new CGIfThenElseStatement(GenerateGetProperty("aMessage".AsNamedIdentifierExpression,"UseStrictFieldOrderForStructs"),
lIfRecordStrictOrder_True,
lIfRecordStrictOrder_False
);
Result.Statements.Add(lIfRecordStrictOrder);
if assigned(entity.AncestorEntity) then begin
lIfRecordStrictOrder_True.Statements.Add(
new CGMethodCallExpression(CGInheritedExpression.Inherited,"readFromMessage",
["aName".AsNamedIdentifierExpression.AsCallParameter,
"aMessage".AsNamedIdentifierExpression.AsCallParameter].ToList)
);
end;
var lSortedFields := new Dictionary<String,RodlField>;
var lAncestorEntity := entity.AncestorEntity as RodlStructEntity;
while assigned(lAncestorEntity) do begin
for field: RodlField in lAncestorEntity.Items do
lSortedFields.Add(field.Name.ToLowerInvariant, field);
lAncestorEntity := lAncestorEntity.AncestorEntity as RodlStructEntity;
end;
for field: RodlField in entity.Items do
if not lSortedFields.ContainsKey(field.Name.ToLowerInvariant) then begin
lSortedFields.Add(field.Name.ToLowerInvariant, field);
lIfRecordStrictOrder_True.Statements.Add(GetReaderStatement(library, field));
end;
for lvalue: String in lSortedFields.Keys.ToList.Sort_OrdinalIgnoreCase(b->b) do
lIfRecordStrictOrder_False.Statements.Add(GetReaderStatement(library, lSortedFields.Item[lvalue]));
end;
method JavaRodlCodeGen.GetReaderStatement(&library: RodlLibrary; entity: RodlTypedEntity; variableName: String): CGStatement;
begin
var lreader := GetReaderExpression(&library,entity,variableName);
exit GenerateSetProperty(CGSelfExpression.Self,entity.Name, lreader);
end;
method JavaRodlCodeGen.HandleAtributes_private(&library: RodlLibrary; entity: RodlEntity): CGFieldDefinition;
begin
// There is no need to generate CustomAttribute-related methods if there is no custom attributes
if (entity.CustomAttributes.Count = 0) then exit;
exit new CGFieldDefinition("_attributes",
new CGNamedTypeReference("HashMap", GenericArguments := [ResolveStdtypes(CGPredefinedTypeReference.String),ResolveStdtypes(CGPredefinedTypeReference.String)].ToList),
&Static := true,
Visibility := CGMemberVisibilityKind.Private);
end;
method JavaRodlCodeGen.HandleAtributes_public(&library: RodlLibrary; entity: RodlEntity): CGMethodDefinition;
begin
// There is no need to generate CustomAttribute-related methods if there is no custom attributes
if (entity.CustomAttributes.Count = 0) then exit;
Result := new CGMethodDefinition("getAttributeValue",
Parameters:=[new CGParameterDefinition("aName", ResolveStdtypes(CGPredefinedTypeReference.String))].ToList,
ReturnType := ResolveStdtypes(CGPredefinedTypeReference.String),
&Static := True,
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public);
var l_attributes := "_attributes".AsNamedIdentifierExpression;
var l_if_true := new CGBeginEndBlockStatement();
var l_if := new CGIfThenElseStatement(
new CGBinaryOperatorExpression(l_attributes,new CGNilExpression(),CGBinaryOperatorKind.Equals),
l_if_true);
Result.Statements.Add(l_if);
l_if_true.Statements.Add(
new CGAssignmentStatement(
l_attributes,
new CGNewInstanceExpression(new CGNamedTypeReference("HashMap", GenericArguments := [ResolveStdtypes(CGPredefinedTypeReference.String),ResolveStdtypes(CGPredefinedTypeReference.String)].ToList)))
);
for l_key: String in entity.CustomAttributes.Keys do begin
l_if_true.Statements.Add(
new CGMethodCallExpression(l_attributes,"put",
[EscapeString(l_key.ToLowerInvariant).AsLiteralExpression.AsCallParameter,
EscapeString(entity.CustomAttributes[l_key]).AsLiteralExpression.AsCallParameter].ToList
));
end;
Result.Statements.Add(new CGMethodCallExpression(l_attributes,"get", [new CGMethodCallExpression("aName".AsNamedIdentifierExpression,"toLowerCase").AsCallParameter].ToList).AsReturnStatement);
end;
method JavaRodlCodeGen.GetWriterStatement(&library: RodlLibrary; entity: RodlTypedEntity; useGetter: Boolean := True; variableName: String := "aMessage"): CGStatement;
begin
var lentityname := entity.Name;
var lLower: String := entity.DataType.ToLowerInvariant();
var l_isStandard := ReaderFunctions.ContainsKey(lLower);
var l_isArray := False;
var l_isStruct := False;
var l_isEnum := False;
var l_methodName: String;
if l_isStandard then begin
l_methodName := ReaderFunctions[lLower];
end
else if isArray(&library, entity.DataType) then begin
l_methodName := "Array";
l_isArray := True;
end
else if isStruct(&library, entity.DataType) then begin
l_methodName := "Complex";
l_isStruct :=True;
end
else if isEnum(&library, entity.DataType) then begin
l_methodName := "Enum";
l_isEnum := True;
end;
var variableName_ID := variableName.AsNamedIdentifierExpression;
var writer_name := "write" + l_methodName;
var entity_ID := iif(useGetter,
GenerateGetProperty(CGSelfExpression.Self,lentityname),
lentityname.AsNamedIdentifierExpression);
var l_arg0 := lentityname.AsLiteralExpression.AsCallParameter;
var l_arg1 := entity_ID.AsCallParameter;
if l_isStandard or l_isStruct or l_isArray then begin
exit new CGMethodCallExpression(variableName_ID,writer_name,[l_arg0,l_arg1].ToList);
end
else if l_isEnum then begin
exit new CGMethodCallExpression(variableName_ID,writer_name,[l_arg0, new CGMethodCallExpression(entity_ID,"ordinal").AsCallParameter].ToList);
end
else begin
raise new Exception(String.Format("unknown type: {0}",[entity.DataType]));
end;
end;
method JavaRodlCodeGen.GetReaderExpression(&library: RodlLibrary; entity: RodlTypedEntity; variableName: String := "aMessage"): CGExpression;
begin
var lLower: String := entity.DataType.ToLowerInvariant();
var l_isStandard := ReaderFunctions.ContainsKey(lLower);
var l_isArray := False;
var l_isStruct := False;
var l_isEnum := False;
var l_methodName: String;
if l_isStandard then begin
l_methodName := ReaderFunctions[lLower];
end
else if isArray(&library, entity.DataType) then begin
l_methodName := "Array";
l_isArray := True;
end
else if isStruct(&library, entity.DataType) then begin
l_methodName := "Complex";
l_isStruct :=True;
end
else if isEnum(&library, entity.DataType) then begin
l_methodName := "Enum";
l_isEnum := True;
end;
var varname_ID := variableName.AsNamedIdentifierExpression;
var reader_name := "read" + l_methodName;
// var l_reader := new CGIdentifierExpression("read" + l_methodName, variableName);
var l_arg0 : CGCallParameter := entity.Name.AsLiteralExpression.AsCallParameter;
var l_type := ResolveDataTypeToTypeRef(&library,entity.DataType);
if l_isStandard then begin
var temp := new CGMethodCallExpression(varname_ID,reader_name,[l_arg0].ToList);
if isPrimitive(entity.DataType) then
exit temp
else
exit new CGTypeCastExpression(temp,
l_type,
ThrowsException:=true);
end
else if l_isArray or l_isStruct then begin
var l_arg1 := new CGTypeOfExpression(l_type.AsExpression).AsCallParameter;
exit new CGTypeCastExpression(
new CGMethodCallExpression(varname_ID,reader_name,[l_arg0,l_arg1].ToList),
l_type,
ThrowsException:=true);
end
else if l_isEnum then begin
exit new CGArrayElementAccessExpression(new CGMethodCallExpression(l_type.AsExpression, "values"),
[CGExpression(new CGMethodCallExpression(varname_ID,reader_name,[l_arg0].ToList))].ToList
);
end
else begin
raise new Exception(String.Format("unknown type: {0}",[entity.DataType]));
end;
end;
method JavaRodlCodeGen.GenerateServiceProxyMethod(&library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
begin
result := GenerateServiceProxyMethodDeclaration(&library,entity);
var l_in:= new List<RodlParameter>;
var l_out:= new List<RodlParameter>;
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.In,ParamFlags.InOut] then
l_in.Add(lp);
if lp.ParamFlag in [ParamFlags.Out,ParamFlags.InOut] then
l_out.Add(lp);
end;
var llocalmessage := "_localMessage".AsNamedIdentifierExpression;
Result.Statements.Add(new CGVariableDeclarationStatement(
"_localMessage",
GenerateROSDKType("Message").AsTypeReference,
new CGTypeCastExpression(
new CGMethodCallExpression(
GenerateGetProperty(CGSelfExpression.Self, "ProxyMessage"),
"clone"),
GenerateROSDKType("Message").AsTypeReference,
ThrowsException:=True)));
GenerateOperationAttribute(&library,entity,Result.Statements);
Result.Statements.Add(
new CGMethodCallExpression(llocalmessage,"initializeAsRequestMessage",
[entity.OwnerLibrary.Name.AsLiteralExpression.AsCallParameter,
new CGMethodCallExpression(CGSelfExpression.Self, "_getActiveInterfaceName").AsCallParameter,
entity.Name.AsLiteralExpression.AsCallParameter].ToList
));
var ltry := new List<CGStatement>;
var lfinally := new List<CGStatement>;
for lp: RodlParameter in l_in do
ltry.Add(GetWriterStatement(&library,lp,false, llocalmessage.Name));
ltry.Add(new CGMethodCallExpression(llocalmessage, "finalizeMessage"));
ltry.Add(new CGMethodCallExpression(GenerateGetProperty(CGSelfExpression.Self, "ProxyClientChannel"),
"dispatch",
[llocalmessage.AsCallParameter].ToList));
if assigned(entity.Result) then begin
ltry.Add(new CGVariableDeclarationStatement("lResult",Result.ReturnType,GetReaderExpression(&library,entity.Result,llocalmessage.Name)));
end;
for lp: RodlParameter in l_out do
ltry.Add(GenerateSetProperty(("_"+lp.Name).AsNamedIdentifierExpression,
"Value",
GetReaderExpression(&library,lp,llocalmessage.Name) ));
if assigned(entity.Result) then
ltry.Add("lResult".AsNamedIdentifierExpression.AsReturnStatement);
lfinally.Add(GenerateSetProperty(GenerateGetProperty(CGSelfExpression.Self,"ProxyMessage"),
"ClientID",
GenerateGetProperty(llocalmessage,"ClientID")));
lfinally.Add(new CGMethodCallExpression(llocalmessage, "clear"));
Result.Statements.Add(new CGTryFinallyCatchStatement(ltry, &FinallyStatements:= lfinally as not nullable));
end;
method JavaRodlCodeGen.GenerateServiceProxyMethodDeclaration(&library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
begin
Result:= new CGMethodDefinition(SafeIdentifier(entity.Name),
Visibility := CGMemberVisibilityKind.Public);
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.In,ParamFlags.InOut] then
Result.Parameters.Add(new CGParameterDefinition(lp.Name, ResolveDataTypeToTypeRef(&library, lp.DataType)));
end;
if assigned(entity.Result) then Result.ReturnType := ResolveDataTypeToTypeRef(&library, entity.Result.DataType);
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.Out,ParamFlags.InOut] then
Result.Parameters.Add(new CGParameterDefinition("_"+lp.Name, new CGNamedTypeReference(GenerateROSDKType("ReferenceType"), GenericArguments:=[ResolveDataTypeToTypeRef(&library, lp.DataType)].ToList)));
end;
end;
method JavaRodlCodeGen.GenerateServiceAsyncProxyBeginMethodDeclaration(&library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
begin
Result:= new CGMethodDefinition("begin" + PascalCase(entity.Name),
ReturnType := GenerateROSDKType("AsyncRequest").AsTypeReference,
Visibility := CGMemberVisibilityKind.Public);
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.In,ParamFlags.InOut] then
Result.Parameters.Add(new CGParameterDefinition(lp.Name, ResolveDataTypeToTypeRef(&library, lp.DataType)));
end;
result.Parameters.Add(new CGParameterDefinition("start", ResolveStdtypes(CGPredefinedTypeReference.Boolean)));
result.Parameters.Add(new CGParameterDefinition("callback", GenerateROSDKType("AsyncRequest.IAsyncRequestCallback").AsTypeReference));
end;
method JavaRodlCodeGen.GenerateServiceAsyncProxyEndMethodDeclaration(&library: RodlLibrary; entity: RodlOperation;&locked:Boolean): CGMethodDefinition;
begin
Result:= new CGMethodDefinition("end" + PascalCase(entity.Name),
Visibility := CGMemberVisibilityKind.Public);
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.Out,ParamFlags.InOut] then
Result.Parameters.Add(new CGParameterDefinition(lp.Name, new CGNamedTypeReference(GenerateROSDKType("ReferenceType"), GenericArguments :=[ResolveDataTypeToTypeRef(&library, lp.DataType)].ToList)));
end;
if assigned(entity.Result) then
result.ReturnType := ResolveDataTypeToTypeRef(library, entity.Result.DataType);
result.Parameters.Add(new CGParameterDefinition("aAsyncRequest", GenerateROSDKType("AsyncRequest").AsTypeReference));
result.Locked := &locked;
end;
method JavaRodlCodeGen.GenerateServiceAsyncProxyBeginMethod(&library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
begin
result := GenerateServiceAsyncProxyBeginMethodDeclaration(&library,entity);
var l_in:= new List<RodlParameter>;
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.In,ParamFlags.InOut] then
l_in.Add(lp);
end;
var llocalmessage := "_localMessage".AsNamedIdentifierExpression;
Result.Statements.Add(new CGVariableDeclarationStatement("_localMessage",
GenerateROSDKType("Message").AsTypeReference,
new CGTypeCastExpression(
new CGMethodCallExpression(
GenerateGetProperty(CGSelfExpression.Self,"ProxyMessage"),
"clone"),
GenerateROSDKType("Message").AsTypeReference,
ThrowsException:=True)
));
GenerateOperationAttribute(&library,entity,Result.Statements);
Result.Statements.Add(
new CGMethodCallExpression(llocalmessage,"initializeAsRequestMessage",
[entity.OwnerLibrary.Name.AsLiteralExpression.AsCallParameter,
new CGMethodCallExpression(CGSelfExpression.Self, "_getActiveInterfaceName").AsCallParameter,
entity.Name.AsLiteralExpression.AsCallParameter].ToList
));
for lp: RodlParameter in l_in do
Result.Statements.Add(GetWriterStatement(&library,lp,false,llocalmessage.Name));
Result.Statements.Add(new CGMethodCallExpression(llocalmessage, "finalizeMessage"));
Result.Statements.Add(new CGMethodCallExpression(GenerateGetProperty(CGSelfExpression.Self,"ProxyClientChannel"),
"asyncDispatch",
[llocalmessage.AsCallParameter,
new CGSelfExpression().AsCallParameter,
"start".AsNamedIdentifierExpression.AsCallParameter,
"callback".AsNamedIdentifierExpression.AsCallParameter].ToList).AsReturnStatement
);
end;
method JavaRodlCodeGen.GenerateServiceAsyncProxyEndMethod(&library: RodlLibrary; entity: RodlOperation): CGMethodDefinition;
begin
result := GenerateServiceAsyncProxyEndMethodDeclaration(&library,entity,true);
var l_out:= new List<RodlParameter>;
for lp: RodlParameter in entity.Items do begin
if lp.ParamFlag in [ParamFlags.Out,ParamFlags.InOut] then
l_out.Add(lp);
end;
var llocalmessage := "_localMessage".AsNamedIdentifierExpression;
Result.Statements.Add(new CGVariableDeclarationStatement("_localMessage",
GenerateROSDKType("Message").AsTypeReference,
GenerateGetProperty("aAsyncRequest".AsNamedIdentifierExpression,"ProcessMessage")));
GenerateOperationAttribute(&library,entity,Result.Statements);
if assigned(entity.Result) then begin
Result.Statements.Add(new CGVariableDeclarationStatement("lResult",Result.ReturnType,GetReaderExpression(&library,entity.Result,llocalmessage.Name)));
end;
for lp: RodlParameter in l_out do
Result.Statements.Add(GenerateSetProperty(lp.Name.AsNamedIdentifierExpression,
"Value",
GetReaderExpression(&library,lp,llocalmessage.Name)));
var mess := GenerateGetProperty(new CGSelfExpression,"ProxyMessage");
Result.Statements.Add(GenerateSetProperty(mess,"ClientID",GenerateGetProperty(llocalmessage,"ClientID")));
Result.Statements.Add(new CGMethodCallExpression(llocalmessage,"clear"));
if assigned(entity.Result) then
Result.Statements.Add("lResult".AsNamedIdentifierExpression.AsReturnStatement);
end;
method JavaRodlCodeGen.GenerateServiceConstructors(&library: RodlLibrary; entity: RodlService; service: CGClassTypeDefinition);
begin
{$REGION .ctor}
var l_Setpackage := new CGMethodCallExpression(GenerateROSDKType("TypeManager").AsNamedIdentifierExpression,"setPackage",[targetNamespace.AsLiteralExpression.AsCallParameter].ToList);
service.Members.Add(
new CGConstructorDefinition(
Visibility := CGMemberVisibilityKind.Public,
Statements:= [
new CGConstructorCallStatement(CGInheritedExpression.Inherited, new List<CGCallParameter>),
l_Setpackage].ToList
)
);
{$ENDREGION}
{$REGION .ctor(aMessage: Message; aClientChannel: ClientChannel)}
service.Members.Add(
new CGConstructorDefinition(
Parameters := [new CGParameterDefinition("aMessage", GenerateROSDKType("Message").AsTypeReference),
new CGParameterDefinition("aClientChannel", GenerateROSDKType("ClientChannel").AsTypeReference)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Statements:= [
new CGConstructorCallStatement(CGInheritedExpression.Inherited,
["aMessage".AsNamedIdentifierExpression.AsCallParameter,
"aClientChannel".AsNamedIdentifierExpression.AsCallParameter].ToList),
l_Setpackage
].ToList
)
);
{$ENDREGION}
{$REGION .ctor(aMessage: Message; aClientChannel: ClientChannel; aOverrideInterfaceName: String)}
service.Members.Add(
new CGConstructorDefinition(
Parameters := [new CGParameterDefinition("aMessage", GenerateROSDKType("Message").AsTypeReference),
new CGParameterDefinition("aClientChannel", GenerateROSDKType("ClientChannel").AsTypeReference),
new CGParameterDefinition("aOverrideInterfaceName", ResolveStdtypes(CGPredefinedTypeReference.String))].ToList,
Visibility := CGMemberVisibilityKind.Public,
Statements:= [new CGConstructorCallStatement(CGInheritedExpression.Inherited,
["aMessage".AsNamedIdentifierExpression.AsCallParameter,
"aClientChannel".AsNamedIdentifierExpression.AsCallParameter,
"aOverrideInterfaceName".AsNamedIdentifierExpression.AsCallParameter].ToList),
l_Setpackage
].ToList
)
);
{$ENDREGION}
{$REGION .ctor(aSchema: URI)}
service.Members.Add(
new CGConstructorDefinition(
Parameters := [new CGParameterDefinition("aSchema", "java.net.URI".AsTypeReference)].ToList,
Visibility := CGMemberVisibilityKind.Public,
Statements:= [new CGConstructorCallStatement(CGInheritedExpression.Inherited,
["aSchema".AsNamedIdentifierExpression.AsCallParameter].ToList),
l_Setpackage].ToList
)
);
{$ENDREGION}
{$REGION .ctor(aSchema: URI; aOverrideInterfaceName: String)}
service.Members.Add(
new CGConstructorDefinition(
Parameters:=[new CGParameterDefinition("aSchema", "java.net.URI".AsTypeReference),
new CGParameterDefinition("aOverrideInterfaceName", ResolveStdtypes(CGPredefinedTypeReference.String))].ToList,
Visibility := CGMemberVisibilityKind.Public,
Statements:= [new CGConstructorCallStatement(CGInheritedExpression.Inherited,
["aSchema".AsNamedIdentifierExpression.AsCallParameter,
"aOverrideInterfaceName".AsNamedIdentifierExpression.AsCallParameter].ToList),
l_Setpackage
].ToList
)
);
{$ENDREGION}
{$REGION method _getInterfaceName: String; override;}
service.Members.Add(
new CGMethodDefinition("_getInterfaceName",
[SafeIdentifier(entity.Name).AsLiteralExpression.AsReturnStatement],
ReturnType := ResolveStdtypes(CGPredefinedTypeReference.String),
Virtuality := CGMemberVirtualityKind.Override,
Visibility := CGMemberVisibilityKind.Public)
);
{$ENDREGION}
end;
method JavaRodlCodeGen.GenerateOperationAttribute(&library: RodlLibrary; entity: RodlOperation; Statements: List<CGStatement>);
begin
var ld := Operation_GetAttributes(&library, entity);
if ld.Count > 0 then begin
var lhashmaptype := new CGNamedTypeReference("HashMap",GenericArguments := [ResolveStdtypes(CGPredefinedTypeReference.String),ResolveStdtypes(CGPredefinedTypeReference.String)].ToList);
var l_attributes := "lAttributesMap".AsNamedIdentifierExpression;
Statements.Add(new CGVariableDeclarationStatement("lAttributesMap",lhashmaptype,new CGNewInstanceExpression(lhashmaptype)));
for l_key: String in ld.Keys do begin
Statements.Add(
new CGMethodCallExpression(l_attributes, "put",
[EscapeString(l_key.ToLowerInvariant).AsLiteralExpression.AsCallParameter,
EscapeString(ld[l_key]).AsLiteralExpression.AsCallParameter].ToList));
end;
Statements.Add(new CGMethodCallExpression("_localMessage".AsNamedIdentifierExpression,"setupAttributes",[l_attributes.AsCallParameter].ToList));
end;
end;
method JavaRodlCodeGen.GetGlobalName(library: RodlLibrary): String;
begin
exit 'Defines_' + targetNamespace.Replace('.', '_');
end;
method JavaRodlCodeGen.GetIncludesNamespace(library: RodlLibrary): String;
begin
if assigned(library.Includes) then exit library.Includes.JavaModule;
exit inherited GetIncludesNamespace(library);
end;
method JavaRodlCodeGen.GenerateInterfaceFiles(library: RodlLibrary; aTargetNamespace: String): not nullable Dictionary<String,String>;
begin
isCooperMode := False;
result := new Dictionary<String,String>;
var lunit := DoGenerateInterfaceFile(library, aTargetNamespace);
//var lgn := GetGlobalName(library);
for k in lunit.Types.OrderBy(b->b.Name) do begin
{ if (k is CGInterfaceTypeDefinition) and (CGInterfaceTypeDefinition(k).Name = lgn) then
result.Add(Path.ChangeExtension('Defines', Generator.defaultFileExtension), (Generator.GenerateUnitForSingleType(k) &unit(lunit)))
else
} result.Add(Path.ChangeExtension(k.Name, Generator.defaultFileExtension), (Generator.GenerateUnitForSingleType(k) &unit(lunit)));
end;
end;
method JavaRodlCodeGen.GenerateGetProperty(aParent: CGExpression; Name: String): CGExpression;
begin
exit iif(isCooperMode,
new CGFieldAccessExpression(aParent, Name),
new CGMethodCallExpression(aParent, "get"+Name));
end;
method JavaRodlCodeGen.GenerateSetProperty(aParent: CGExpression; Name: String; aValue:CGExpression): CGStatement;
begin
exit iif(isCooperMode,
new CGAssignmentStatement(new CGFieldAccessExpression(aParent, Name), aValue),
new CGMethodCallExpression(aParent, "set"+Name,[aValue.AsCallParameter].ToList));
end;
method JavaRodlCodeGen.GenerateEnum(file: CGCodeUnit; library: RodlLibrary; entity: RodlEnum);
begin
var lenum := new CGEnumTypeDefinition(SafeIdentifier(entity.Name),
Visibility := CGTypeVisibilityKind.Public,
BaseType := new CGNamedTypeReference('Enum'));
lenum.Comment := GenerateDocumentation(entity);
file.Types.Add(lenum);
for enummember: RodlEnumValue in entity.Items do begin
var lname := GenerateEnumMemberName(library, entity, enummember);
var lenummember := new CGEnumValueDefinition(lname);
lenummember.Comment := GenerateDocumentation(enummember);
lenum.Members.Add(lenummember);
end;
end;
method JavaRodlCodeGen.AddGlobalConstants(file: CGCodeUnit; library: RodlLibrary);
begin
var ltype : CGTypeDefinition;
if isCooperMode then
ltype := new CGClassTypeDefinition(GetGlobalName(library), Visibility:= CGTypeVisibilityKind.Public)
else
ltype := new CGInterfaceTypeDefinition(GetGlobalName(library), Visibility:= CGTypeVisibilityKind.Public);
file.Types.Add(ltype);
ltype.Members.Add(new CGFieldDefinition("TARGET_NAMESPACE", ResolveStdtypes(CGPredefinedTypeReference.String),
Constant := true,
&Static := true,
Visibility := CGMemberVisibilityKind.Public,
Initializer := if assigned(targetNamespace) then targetNamespace.AsLiteralExpression));
for lentity: RodlEntity in &library.EventSinks.Items.Sort_OrdinalIgnoreCase(b->b.Name) do begin
if not EntityNeedsCodeGen(lentity) then Continue;
var lName := lentity.Name;
ltype.Members.Add(new CGFieldDefinition(String.Format("EID_{0}",[lName]), ResolveStdtypes(CGPredefinedTypeReference.String),
Constant := true,
&Static := true,
Visibility := CGMemberVisibilityKind.Public,
Initializer := lName.AsLiteralExpression));
end;
end;
method JavaRodlCodeGen.GenerateROSDKType(aName: String): String;
begin
if addROSDKPrefix then
exit "com.remobjects.sdk."+aName
else
exit aName;
end;
method JavaRodlCodeGen.isPrimitive(&type: String): Boolean;
begin
result := not CodeGenTypes.ContainsKey(&type.ToLowerInvariant);
if result then begin
var k := CodeGenTypes[&type.ToLowerInvariant];
result := (k is CGPredefinedTypeReference) and
(CodeGenTypes[&type.ToLowerInvariant].Nullability <> CGTypeNullabilityKind.NullableNotUnwrapped);
end;
end;
end. |
unit uTaskManager;
interface
uses
SysUtils, IOUtils, Generics.Collections, Classes, IniFiles,
uBaseThread, uGlobal, uTypes, uFromHik86;
type
TTaskManager = class
private
FThreadList: TList<TBaseThread>;
public
constructor Create;
destructor Destroy; override;
procedure CreateThreads;
procedure ClearThreads;
procedure SuspendThreads;
procedure ResumeThreads;
end;
var
TaskManager: TTaskManager;
implementation
constructor TTaskManager.Create;
begin
FThreadList := TList<TBaseThread>.Create;
end;
destructor TTaskManager.Destroy;
begin
ClearThreads;
FThreadList.Free;
inherited;
end;
procedure TTaskManager.CreateThreads;
var
ini: TIniFile;
sec: string;
sections: TStrings;
config: TConfig;
thd: TFromHik86;
begin
FThreadList := TList<TBaseThread>.Create;
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
sections := TStringList.Create;
ini.ReadSections(sections);
for sec in sections do
begin
config.Name := sec;
config.Host := ini.ReadString(sec, 'Host', '');
config.Port := ini.ReadString(sec, 'Port', '');
config.SID := ini.ReadString(sec, 'SID', '');
config.Usr := ini.ReadString(sec, 'Usr', '');
config.Pwd := ini.ReadString(sec, 'Pwd', '');
config.BdrUrl := ini.ReadString(sec, 'BdrUrl', '');
config.IsVio := ini.ReadInteger(sec, 'IsVio', 0) = 1;
config.AlarmUrl := ini.ReadString(sec, 'AlarmUrl', '');
if config.Host <> '' then
begin
thd := TFromHik86.Create(config);
FThreadList.Add(thd);
end;
end;
sections.Free;
ini.Free;
end;
procedure TTaskManager.ClearThreads;
var
item: TBaseThread;
allFinished: boolean;
begin
for item in FThreadList do
begin
item.Terminate;
end;
allFinished := false;
while not allFinished do
begin
Sleep(1000);
allFinished := true;
for item in FThreadList do
begin
allFinished := allFinished and item.Finished;
end;
end;
for item in FThreadList do
begin
item.Free;
end;
FThreadList.Clear;
end;
procedure TTaskManager.SuspendThreads;
var
item: TBaseThread;
allPaused: boolean;
begin
for item in FThreadList do
begin
item.Pause;
end;
allPaused := false;
while not allPaused do
begin
Sleep(2000);
allPaused := true;
for item in FThreadList do
begin
allPaused := allPaused and ((item.Status = tsPaused)or(item.Status = tsDead));
if not allPaused then
begin
logger.Info('wait for [' + item.ThreadID.ToString + ']' + item.ClassName);
end;
end;
end;
end;
procedure TTaskManager.ResumeThreads;
var
item: TBaseThread;
begin
for item in FThreadList do
begin
item.GoOn;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQL Server Call Interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.MSSQLCli;
interface
{$IFDEF MSWINDOWS}
uses
Winapi.Windows;
{$ENDIF}
const
SQL_FILESTREAM_READ = 0;
SQL_FILESTREAM_WRITE = 1;
SQL_FILESTREAM_READWRITE = 2;
SQL_FILESTREAM_OPEN_NONE = $00000000;
SQL_FILESTREAM_OPEN_FLAG_ASYNC = $00000001;
SQL_FILESTREAM_OPEN_FLAG_NO_BUFFERING = $00000002;
SQL_FILESTREAM_OPEN_FLAG_NO_WRITE_THROUGH = $00000004;
SQL_FILESTREAM_OPEN_FLAG_SEQUENTIAL_SCAN = $00000008;
SQL_FILESTREAM_OPEN_FLAG_RANDOM_ACCESS = $00000010;
{$IFDEF MSWINDOWS}
FSCTL_SQL_FILESTREAM_FETCH_OLD_CONTENT =
(FILE_DEVICE_FILE_SYSTEM shl 16) or (FILE_ANY_ACCESS shl 14) or (2392 shl 2) or (METHOD_BUFFERED);
{$ENDIF}
type
TMSSQLOpenSqlFilestream = function (
FilestreamPath: PWideChar;
DesiredAccess: LongWord;
OpenOptions: LongWord;
FilestreamTransactionContext: PByte;
FilestreamTransactionContextLength: {$IFDEF FireDAC_64} UInt64 {$ELSE} LongWord {$ENDIF};
AllocationSize: PInt64): THandle; stdcall;
implementation
end.
|
unit PersonCreate;
interface
uses
PersonBuilder;
type
TPersonType = (Thin, Fat);
TPersonCreate = class
private
FPersonBuilder: TPersonBuilder;
procedure CreatePerson;
public
constructor Create(PT: TPersonType);
destructor Destroy; override;
function GetPersonInfo: string;
end;
implementation
{ TPersonCreate }
constructor TPersonCreate.Create(PT: TPersonType);
begin
case PT of
Thin: FPersonBuilder := TPersonThinBuilder.Create;
Fat: FPersonBuilder := TPersonFatBuilder.Create;
end;
CreatePerson;
end;
destructor TPersonCreate.Destroy;
begin
FPersonBuilder.Free;
inherited;
end;
function TPersonCreate.GetPersonInfo: string;
begin
Result := FPersonBuilder.GetPersonInfo;
end;
procedure TPersonCreate.CreatePerson;
begin
FPersonBuilder.BuildHead;
FPersonBuilder.BuildBody;
FPersonBuilder.BuildArmLeft;
FPersonBuilder.BuildArmRight;
FPersonBuilder.BuildLegLeft;
FPersonBuilder.BuildLegRight;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2000-2002 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit QMask;
{$R-,T-,H+,X+}
interface
uses SysUtils, Qt, QTypes, QControls, Classes, QStdCtrls, MaskUtils;
type
{ TCustomMaskEdit }
TEditMask = type string;
EDBEditError = class(Exception);
TMaskedState = set of (msMasked, msReEnter, msDBSetText);
TCustomMaskEdit = class(TCustomEdit)
private
FEditMask: TEditMask;
FMaskBlank: Char;
FMaxChars: Integer;
FWMaxChars: Integer;
FMaskSave: Boolean;
FMaskState: TMaskedState;
FCaretPos: Integer;
FBtnDownX: Integer;
FOldValue: string;
FSettingCursor: Boolean;
FBeepOnError: Boolean;
function DoInputChar(var NewChar: Char; MaskOffset: Integer): Boolean;
function InputChar(var NewChar: Char; Offset: Integer): Boolean;
function DeleteSelection(var Value: string; Offset: Integer;
Len: Integer): Boolean;
function InputString(var Value: string; const NewValue: string;
Offset: Integer): Integer;
function AddEditFormat(const Value: string; Active: Boolean): string;
function RemoveEditFormat(const Value: string): string;
function FindLiteralChar (MaskOffset: Integer; InChar: Char): Integer;
function GetEditText: string;
function GetMasked: Boolean;
function GetMaskedText: TMaskedText;
function GetMaxLength: Integer;
function CharKeys(var CharCode: Char): Boolean;
procedure SetEditText(const Value: string);
procedure SetEditMask(const Value: TEditMask);
procedure SetMaxLength(Value: Integer);
procedure SetMaskedText(const Value: TMaskedText);
procedure DeleteKeys(CharCode: Word);
procedure HomeEndKeys(CharCode: Word; Shift: TShiftState);
procedure CursorInc(CursorPos: Integer; Incr: Integer);
procedure CursorDec(CursorPos: Integer);
procedure ArrowKeys(CharCode: Word; Shift: TShiftState);
protected
procedure DoBeep; override;
procedure ReformatText(const NewMask: string);
procedure GetSel(var SelStart: Integer; var SelStop: Integer);
procedure SetSel(SelStart: Integer; SelStop: Integer);
procedure SetCursor(Pos: Integer);
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyUp(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure KeyString(var S: WideString; var Handled: Boolean); override;
function EditCanModify: Boolean; virtual;
procedure Reset; virtual;
function GetFirstEditChar: Integer;
function GetLastEditChar: Integer;
function GetNextEditChar(Offset: Integer): Integer;
function GetPriorEditChar(Offset: Integer): Integer;
function GetMaxChars: Integer;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer); override;
procedure DoEnter; override;
procedure DoExit; override;
procedure TextChanged; override;
function Validate(const Value: string; var Pos: Integer): Boolean; virtual;
procedure ValidateError; virtual;
procedure CheckCursor;
procedure SetText(const Value: TCaption); override;
procedure SetSelText(const Value: WideString); override;
property BeepOnError: Boolean read FBeepOnError write FBeepOnError default True;
property EditMask: TEditMask read FEditMask write SetEditMask;
property MaskState: TMaskedState read FMaskState write FMaskState;
property MaxLength: Integer read GetMaxLength write SetMaxLength default -1;
public
constructor Create(AOwner: TComponent); override;
procedure CutToClipboard; override;
procedure PasteFromClipboard; override;
procedure ValidateEdit; virtual;
procedure Clear; override;
function GetTextLen: Integer;
property IsMasked: Boolean read GetMasked;
property EditText: string read GetEditText write SetEditText;
property Text: TMaskedText read GetMaskedText write SetMaskedText;
end;
{ TMaskEdit }
TMaskEdit = class(TCustomMaskEdit)
published
property Anchors;
property AutoSelect;
property AutoSize;
property BeepOnError;
property BorderStyle;
property CharCase;
property Color;
property Constraints;
property DragMode;
property Enabled;
property EditMask;
property Font;
property MaxLength;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property Visible;
property OnChange;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyString;
property OnKeyUp;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
implementation
uses {$IFDEF LINUX}Libc, {$ENDIF} {$IFDEF MSWINDOWS} Windows, {$ENDIF}
RTLConsts, QConsts, QClipbrd, QForms;
{ TCustomMaskEdit }
function IsAlphaChar(ch: Char): Boolean;
begin
{$IFDEF LINUX}
Result := IsAlpha(Integer(ch)) <> 0;
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := IsCharAlpha(ch);
{$ENDIF}
end;
function IsAlphaNumericChar(ch: Char): Boolean;
begin
{$IFDEF LINUX}
Result := IsAlNum(Integer(ch)) <> 0;
{$ENDIF}
{$IFDEF MSWINDOWS}
Result := IsCharAlphaNumeric(ch);
{$ENDIF}
end;
constructor TCustomMaskEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMaskState := [];
FMaskBlank := DefaultBlank;
FBeepOnError := True;
InputKeys := InputKeys + [ikReturns, ikEsc];
end;
procedure TCustomMaskEdit.KeyDown(var Key: Word; Shift: TShiftState);
begin
if not FSettingCursor then inherited KeyDown(Key, Shift);
if IsMasked and (Key <> 0) and not (ssAlt in Shift) then
begin
if (Key = Key_Left) or(Key = Key_Right) then
begin
ArrowKeys(Key, Shift);
if not ((ssShift in Shift) or (ssCtrl in Shift)) then
Key := 0;
Exit;
end
else if (Key = Key_Up) or(Key = Key_Down) then
begin
Key := 0;
Exit;
end
else if (Key = Key_Home) or(Key = Key_End) then
begin
HomeEndKeys(Key, Shift);
Key := 0;
Exit;
end
else if ((Key = Key_Delete) and not (ssShift in Shift)) or
(Key = Key_Backspace) then
begin
if EditCanModify then
DeleteKeys(Key);
Key := 0;
Exit;
end//;
else
if ReadOnly then Key := 0;
CheckCursor;
end;
end;
procedure TCustomMaskEdit.KeyUp(var Key: Word; Shift: TShiftState);
begin
if not FSettingCursor then inherited KeyUp(Key, Shift);
if IsMasked and (Key <> 0) then
begin
if ((Key = Key_Left) or(Key = Key_Right)) {and (ssCtrl in Shift)} then
CheckCursor;
end;
end;
procedure TCustomMaskEdit.KeyPress(var Key: Char);
begin
inherited KeyPress(Key);
if IsMasked and (Key <> #0) then
case Key of
#9, ^C: Exit;
else
CharKeys(Key);
Key := #0;
end;
end;
procedure TCustomMaskEdit.KeyString(var S: WideString; var Handled: Boolean);
procedure InsertString(var S : widestring);
var
Str: string;
SelStart, SelStop : Integer;
begin
GetSel(SelStart, SelStop);
Str := EditText;
DeleteSelection(Str, SelStart, SelStop - SelStart);
EditText := Str;
SelStart := InputString(Str, S, SelStart);
EditText := Str;
SetCursor(SelStart);
S := '';
end;
var
I : integer;
W : WideString;
ch : char;
begin
inherited KeyString(S, Handled);
if not IsMasked or ReadOnly then
Exit; // pass KeyPress
W := '';
for I := 1 to Length(S) do
begin
if S[I] < #$20 then
begin
If W <> '' then InsertString(W);
ch := Char(S[I]);
CharKeys(ch);
end
else
W := W + S[I];
end;
if W <> '' then InsertString(W);
S := '';
Handled := True;
end;
procedure TCustomMaskEdit.SetEditText(const Value: string);
begin
inherited MaxLength := length( WideString(Value) );
inherited Text := Value;
SetSel(0, 0);
CheckCursor;
end;
function TCustomMaskEdit.GetEditText: string;
begin
Result := inherited Text;
end;
function TCustomMaskEdit.GetTextLen: Integer;
begin
Result := Length(Text);
end;
function TCustomMaskEdit.GetMaskedText: TMaskedText;
begin
if not IsMasked then
Result := inherited Text
else
begin
Result := RemoveEditFormat(EditText);
if FMaskSave then
Result := AddEditFormat(Result, False);
end;
end;
procedure TCustomMaskEdit.SetMaskedText(const Value: TMaskedText);
var
OldText: string;
Pos: Integer;
begin
if not IsMasked then
begin
inherited Text := Value;
end
else
begin
OldText := Value;
if FMaskSave then
OldText := PadInputLiterals(EditMask, OldText, FMaskBlank)
else
OldText := AddEditFormat(OldText, True);
if not (msDBSetText in FMaskState) and
(csDesigning in ComponentState) and
not (csLoading in ComponentState) and
not Validate(OldText, Pos) then
raise EDBEditError.CreateRes(@SMaskErr);
EditText := OldText;
end;
end;
function TCustomMaskEdit.GetMasked: Boolean;
begin
Result := EditMask <> '';
end;
function TCustomMaskEdit.GetMaxChars: Integer;
begin
if IsMasked then
Result := FMaxChars
else
Result := Length(inherited Text);
end;
procedure TCustomMaskEdit.ReformatText(const NewMask: string);
var
OldText: string;
begin
OldText := RemoveEditFormat(EditText);
FEditMask := NewMask;
FMaxChars := MaskOffsetToOffset(EditMask, Length(NewMask));
FWMaxChars := MaskOffsetToWideOffset(EditMask, Length(NewMask));
FMaskSave := MaskGetMaskSave(NewMask);
FMaskBlank := MaskGetMaskBlank(NewMask);
OldText := AddEditFormat(OldText, True);
EditText := OldText;
end;
procedure TCustomMaskEdit.SetEditMask(const Value: TEditMask);
var
SelStart, SelStop: Integer;
begin
if Value <> EditMask then
begin
if (csDesigning in ComponentState) and (Value <> '') and
not (csLoading in ComponentState) then
EditText := '';
if HandleAllocated then GetSel(SelStart, SelStop);
ReformatText(Value);
Exclude(FMaskState, msMasked);
if EditMask <> '' then Include(FMaskState, msMasked);
end;
end;
function TCustomMaskEdit.GetMaxLength: Integer;
begin
Result := inherited MaxLength;
end;
procedure TCustomMaskEdit.SetMaxLength(Value: Integer);
begin
if not IsMasked then
inherited MaxLength := Value
else
inherited MaxLength := FWMaxChars;
end;
procedure TCustomMaskEdit.GetSel(var SelStart: Integer; var SelStop: Integer);
function WideOffsetToAnsiOffset(offset : integer) : integer;
begin
result := Length(AnsiString(Copy((inherited Text), 1, offset)));
end;
begin
SelStart := WideOffsetToAnsiOffset(GetSelStart);
SelStop := WideOffsetToAnsiOffset(GetSelStart + GetSelLength);
end;
procedure TCustomMaskEdit.SetSel(SelStart: Integer; SelStop: Integer);
function AnsiOffsetToWideOffset( Left, Right : integer ) : integer;
begin
result := Length((WideString(Copy( AnsiString(inherited Text), Left, Right))));
end;
begin
SetSelStart(AnsiOffsetToWideOffset(1, SelStart));
SetSelLength(AnsiOffsetToWideOffset(SelStart+1, SelStop - SelStart));
end;
procedure TCustomMaskEdit.SetCursor(Pos: Integer);
const
ArrowKey: array[Boolean] of Word = (Key_Left, Key_Right);
var
SelStart, SelStop: Integer;
begin
if FSettingCursor then Exit;
if (Pos >= 1) and (ByteType(EditText, Pos) = mbLeadByte) then Dec(Pos);
SelStart := Pos;
if (IsMasked) then
begin
if SelStart < 0 then
SelStart := 0;
if Focused then
SelStop := SelStart + 1
else
SelStop := SelStart;
if (Length(EditText) > SelStop) and (EditText[SelStop] in LeadBytes) then
Inc(SelStop);
if SelStart >= FMaxChars then
begin
SelStart := FMaxChars;
SelStop := SelStart;
end;
SelStart := GetNextEditChar(SelStart);
SetSel(SelStart, SelStop);
FCaretPos := SelStart;
end
else
begin
if SelStart < 0 then
SelStart := 0;
if SelStart >= Length(EditText) then
SelStart := Length(EditText);
SetSel(SelStart, SelStart);
end;
end;
procedure TCustomMaskEdit.CheckCursor;
var
SelStart, SelStop: Integer;
begin
if not HandleAllocated then Exit;
if (IsMasked) then
begin
GetSel(SelStart, SelStop);
if SelStart = SelStop then
SetCursor(SelStart);
end;
end;
procedure TCustomMaskEdit.SetText(const Value: TCaption);
begin
inherited;
if csLoading in ComponentState then
Modified := False;
end;
procedure TCustomMaskEdit.SetSelText(const Value: WideString);
begin
inherited;
if csLoading in ComponentState then
Modified := False;
end;
procedure TCustomMaskEdit.Clear;
begin
Text := '';
end;
function TCustomMaskEdit.EditCanModify: Boolean;
begin
Result := True;
end;
procedure TCustomMaskEdit.Reset;
begin
if Modified then
begin
EditText := FOldValue;
Modified := False;
end;
end;
function TCustomMaskEdit.CharKeys(var CharCode: Char): Boolean;
var
SelStart, SelStop : Integer;
Txt: string;
begin
Result := False;
if CharCode = #27 then
begin
Reset;
Exit;
end;
if not EditCanModify or ReadOnly then Exit;
if CharCode = #8 then Exit;
if CharCode = #13 then
begin
ValidateEdit;
Exit;
end;
GetSel(SelStart, SelStop);
if (SelStop - SelStart) > 1 then
begin
DeleteKeys(Key_Delete);
SelStart := GetNextEditChar(SelStart);
SetCursor(SelStart);
end;
Result := InputChar(CharCode, SelStart);
if Result then
begin
Txt := CharCode;
SelText := Txt;
GetSel(SelStart, SelStop);
CursorInc(SelStart, 1);
end;
end;
procedure TCustomMaskEdit.ArrowKeys(CharCode: Word; Shift: TShiftState);
var
SelStart, SelStop : Integer;
begin
if (ssCtrl in Shift) then Exit;
GetSel(SelStart, SelStop);
if (ssShift in Shift) then
begin
if (CharCode = Key_Right) then
begin
Inc(FCaretPos);
if (SelStop = SelStart + 1) then
begin
SetSel(SelStart, SelStop); {reset caret to end of string}
Inc(FCaretPos);
end;
if FCaretPos > FMaxChars then FCaretPos := FMaxChars;
end
else {if (CharCode = VK_LEFT) then}
begin
Dec(FCaretPos);
if (SelStop = SelStart + 2) and
(FCaretPos > SelStart) then
begin
SetSel(SelStart + 1, SelStart + 1); {reset caret to show up at start}
Dec(FCaretPos);
end;
if FCaretPos < 0 then FCaretPos := 0;
end;
end
else
begin
if (SelStop - SelStart) > 1 then
begin
if ((SelStop - SelStart) = 2) and (EditText[SelStart+1] in LeadBytes) then
begin
if (CharCode = Key_Left) then
CursorDec(SelStart)
else
CursorInc(SelStart, 2);
Exit;
end;
if SelStop = FCaretPos then
Dec(FCaretPos);
SetCursor(FCaretPos);
end
else if (CharCode = Key_Left) then
CursorDec(SelStart)
else { if (CharCode = VK_RIGHT) then }
begin
if SelStop = SelStart then
SetCursor(SelStart + 1)//SelStart)
else
if EditText[SelStart+1] in LeadBytes then
CursorInc(SelStart, 2)
else
CursorInc(SelStart, 1);
end;
end;
end;
procedure TCustomMaskEdit.CursorInc(CursorPos: Integer; Incr: Integer);
var
NuPos: Integer;
begin
NuPos := CursorPos + Incr;
NuPos := GetNextEditChar(NuPos);
if IsLiteralChar(EditMask, nuPos) then
NuPos := CursorPos;
SetCursor(NuPos);
end;
procedure TCustomMaskEdit.CursorDec(CursorPos: Integer);
var
nuPos: Integer;
begin
nuPos := CursorPos;
Dec(nuPos);
nuPos := GetPriorEditChar(nuPos);
SetCursor(NuPos);
end;
function TCustomMaskEdit.GetFirstEditChar: Integer;
begin
Result := 0;
if IsMasked then
Result := GetNextEditChar(0);
end;
function TCustomMaskEdit.GetLastEditChar: Integer;
begin
Result := GetMaxChars;
if IsMasked then
Result := GetPriorEditChar(Result - 1);
end;
function TCustomMaskEdit.GetNextEditChar(Offset: Integer): Integer;
begin
Result := Offset;
while(Result < FMaxChars) and (IsLiteralChar(EditMask, Result)) do
Inc(Result);
end;
function TCustomMaskEdit.GetPriorEditChar(Offset: Integer): Integer;
begin
Result := Offset;
while(Result >= 0) and (IsLiteralChar(EditMask, Result)) do
Dec(Result);
if Result < 0 then
Result := GetNextEditChar(Result);
end;
procedure TCustomMaskEdit.HomeEndKeys(CharCode: Word; Shift: TShiftState);
var
SelStart, SelStop : Integer;
begin
GetSel(SelStart, SelStop);
if (CharCode = Key_Home) then
begin
if (ssShift in Shift) then
begin
if (SelStart <> FCaretPos) and (SelStop <> (SelStart + 1)) then
SelStop := SelStart + 1;
SetSel(0, SelStop);
CheckCursor;
end
else
SetCursor(0);
FCaretPos := 0;
end
else
begin
if (ssShift in Shift) then
begin
if (SelStop <> FCaretPos) and (SelStop <> (SelStart + 1)) then
SelStart := SelStop - 1;
SetSel(SelStart, FMaxChars);
CheckCursor;
end
else
SetCursor(FMaxChars);
FCaretPos := FMaxChars;
end;
end;
procedure TCustomMaskEdit.DeleteKeys(CharCode: Word);
var
SelStart, SelStop : Integer;
NuSelStart: Integer;
Str: string;
begin
if ReadOnly then Exit;
GetSel(SelStart, SelStop);
if ((SelStop - SelStart) <= 1) and (CharCode = Key_Backspace) then
begin
NuSelStart := SelStart;
CursorDec(SelStart);
GetSel(SelStart, SelStop);
if SelStart = NuSelStart then Exit;
end;
if (SelStop - SelStart) < 1 then Exit;
Str := EditText;
DeleteSelection(Str, SelStart, SelStop - SelStart);
inherited MaxLength := Length(WideString(Str));
Str := Copy(Str, SelStart+1, SelStop - SelStart);
SelText := Str;
if (SelStop - SelStart) <> 1 then
begin
SelStart := GetNextEditChar(SelStart);
SetCursor(SelStart);
end
else begin
GetSel(SelStart, SelStop);
SetCursor(SelStart); //- 1);
end;
end;
procedure TCustomMaskEdit.ValidateEdit;
var
Str: string;
Pos: Integer;
begin
Str := EditText;
if IsMasked and Modified then
begin
if not Validate(Str, Pos) then
begin
if not (csDesigning in ComponentState) then
begin
Include(FMaskState, msReEnter);
SetFocus;
end;
SetCursor(Pos);
ValidateError;
end;
end;
end;
procedure TCustomMaskEdit.ValidateError;
begin
if BeepOnError then SysUtils.Beep;
raise EDBEditError.CreateResFmt(@SMaskEditErr, [EditMask]);
end;
function TCustomMaskEdit.AddEditFormat(const Value: string; Active: Boolean): string;
begin
if not Active then
Result := MaskDoFormatText(EditMask, Value, ' ')
else
Result := MaskDoFormatText(EditMask, Value, FMaskBlank);
end;
function TCustomMaskEdit.RemoveEditFormat(const Value: string): string;
var
I: Integer;
OldLen: Integer;
Offset, MaskOffset: Integer;
CType: TMaskCharType;
Dir: TMaskDirectives;
begin
Offset := 1;
Result := Value;
for MaskOffset := 1 to Length(EditMask) do
begin
CType := MaskGetCharType(EditMask, MaskOffset);
if CType in [mcLiteral, mcIntlLiteral] then
Result := Copy(Result, 1, Offset - 1) +
Copy(Result, Offset + 1, Length(Result) - Offset);
if CType in [mcMask, mcMaskOpt] then Inc(Offset);
end;
Dir := MaskGetCurrentDirectives(EditMask, 1);
if mdReverseDir in Dir then
begin
Offset := 1;
for I := 1 to Length(Result) do
begin
if Result[I] = FMaskBlank then
Inc(Offset)
else
break;
end;
if Offset <> 1 then
Result := Copy(Result, Offset, Length(Result) - Offset + 1);
end
else begin
OldLen := Length(Result);
for I := 1 to OldLen do
begin
if Result[OldLen - I + 1] = FMaskBlank then
SetLength(Result, Length(Result) - 1)
else Break;
end;
end;
if FMaskBlank <> ' ' then
begin
OldLen := Length(Result);
for I := 1 to OldLen do
begin
if Result[I] = FMaskBlank then
Result[I] := ' ';
end;
end;
end;
function TCustomMaskEdit.InputChar(var NewChar: Char; Offset: Integer): Boolean;
var
MaskOffset: Integer;
CType: TMaskCharType;
InChar: Char;
begin
Result := True;
if EditMask <> '' then
begin
Result := False;
MaskOffset := OffsetToMaskOffset(EditMask, Offset);
if MaskOffset >= 0 then
begin
CType := MaskGetCharType(EditMask, MaskOffset);
InChar := NewChar;
Result := DoInputChar(NewChar, MaskOffset);
if not Result and (CType in [mcMask, mcMaskOpt]) then
begin
MaskOffset := FindLiteralChar (MaskOffset, InChar);
if MaskOffset > 0 then
begin
MaskOffset := MaskOffsetToOffset(EditMask, MaskOffset);
SetCursor (MaskOffset);
Exit;
end;
end;
end;
end;
if not Result and BeepOnError then
SysUtils.Beep;
end;
function TCustomMaskEdit.DoInputChar(var NewChar: Char; MaskOffset: Integer): Boolean;
var
Dir: TMaskDirectives;
Str: string;
CType: TMaskCharType;
function TestChar(NewChar: Char): Boolean;
var
Offset: Integer;
begin
Offset := MaskOffsetToOffset(EditMask, MaskOffset);
Result := not ((MaskOffset < Length(EditMask)) and
(UpCase(EditMask[MaskOffset]) = UpCase(EditMask[MaskOffset+1]))) or
(ByteType(EditText, Offset) = mbTrailByte) or
(ByteType(EditText, Offset+1) = mbLeadByte);
end;
begin
Result := True;
CType := MaskGetCharType(EditMask, MaskOffset);
if CType in [mcLiteral, mcIntlLiteral] then
NewChar := MaskIntlLiteralToChar(EditMask[MaskOffset])
else
begin
Dir := MaskGetCurrentDirectives(EditMask, MaskOffset);
case EditMask[MaskOffset] of
mMskNumeric, mMskNumericOpt:
begin
if not ((NewChar >= '0') and (NewChar <= '9')) then
Result := False;
end;
mMskNumSymOpt:
begin
if not (((NewChar >= '0') and (NewChar <= '9')) or
(NewChar = ' ') or(NewChar = '+') or(NewChar = '-')) then
Result := False;
end;
mMskAscii, mMskAsciiOpt:
begin
if (NewChar in LeadBytes) and TestChar(NewChar) then
begin
Result := False;
Exit;
end;
if IsAlphaChar(NewChar) then
begin
Str := ' ';
Str[1] := NewChar;
if (mdUpperCase in Dir) then
Str := AnsiUpperCase(Str)
else if mdLowerCase in Dir then
Str := AnsiLowerCase(Str);
NewChar := Str[1];
end;
end;
mMskAlpha, mMskAlphaOpt, mMskAlphaNum, mMskAlphaNumOpt:
begin
if (NewChar in LeadBytes) then
begin
if TestChar(NewChar) then
Result := False;
Exit;
end;
Str := ' ';
Str[1] := NewChar;
if not IsAlphaChar(NewChar) then
begin
Result := False;
if ((EditMask[MaskOffset] = mMskAlphaNum) or
(EditMask[MaskOffset] = mMskAlphaNumOpt)) and
(IsAlphaNumericChar(NewChar)) then
Result := True;
end
else if mdUpperCase in Dir then
Str := AnsiUpperCase(Str)
else if mdLowerCase in Dir then
Str := AnsiLowerCase(Str);
NewChar := Str[1];
end;
end;
end;
end;
function TCustomMaskEdit.Validate(const Value: string; var Pos: Integer): Boolean;
var
Offset, MaskOffset: Integer;
CType: TMaskCharType;
begin
Result := True;
Offset := 1;
for MaskOffset := 1 to Length(EditMask) do
begin
CType := MaskGetCharType(EditMask, MaskOffset);
if CType in [mcLiteral, mcIntlLiteral, mcMaskOpt] then
Inc(Offset)
else if (CType = mcMask) and (Value <> '') then
begin
if (Value [Offset] = FMaskBlank) or
((Value [Offset] = ' ') and (EditMask[MaskOffset] <> mMskAscii)) then
begin
Result := False;
Pos := Offset - 1;
Exit;
end;
Inc(Offset);
end;
end;
end;
function TCustomMaskEdit.DeleteSelection(var Value: string; Offset: Integer;
Len: Integer): Boolean;
var
EndDel: Integer;
StrOffset, MaskOffset, Temp: Integer;
CType: TMaskCharType;
begin
Result := True;
if Len = 0 then Exit;
StrOffset := Offset + 1;
EndDel := StrOffset + Len;
Temp := OffsetToMaskOffset(EditMask, Offset);
if Temp < 0 then Exit;
for MaskOffset := Temp to Length(EditMask) do
begin
CType := MaskGetCharType(EditMask, MaskOffset);
if CType in [mcLiteral, mcIntlLiteral] then
Inc(StrOffset)
else if CType in [mcMask, mcMaskOpt] then
begin
Value[StrOffset] := FMaskBlank;
Inc(StrOffset);
end;
if StrOffset >= EndDel then Break;
end;
end;
function TCustomMaskEdit.InputString(var Value: string; const NewValue: string;
Offset: Integer): Integer;
var
NewOffset, MaskOffset, Temp: Integer;
CType: TMaskCharType;
NewVal: string;
NewChar: Char;
begin
Result := Offset;
if NewValue = '' then Exit;
{ replace chars with new chars, except literals }
NewOffset := 1;
NewVal := NewValue;
Temp := OffsetToMaskOffset(EditMask, Offset);
if Temp < 0 then Exit;
MaskOffset := Temp;
While MaskOffset <= Length(EditMask) do
begin
CType := MaskGetCharType(EditMask, MaskOffset);
if CType in [mcLiteral, mcIntlLiteral, mcMask, mcMaskOpt] then
begin
NewChar := NewVal[NewOffset];
if not (DoInputChar(NewChar, MaskOffset)) then
begin
if (NewChar in LeadBytes) then
NewVal[NewOffset + 1] := FMaskBlank;
NewChar := FMaskBlank;
end;
{ if pasted text does not contain a literal in the right place,
insert one }
if not ((CType in [mcLiteral, mcIntlLiteral]) and
(NewChar <> NewVal[NewOffset])) then
begin
NewVal[NewOffset] := NewChar;
if (NewChar in LeadBytes) then
begin
Inc(NewOffset);
Inc(MaskOffset);
end;
end
else
NewVal := Copy(NewVal, 1, NewOffset-1) + NewChar +
Copy(NewVal, NewOffset, Length (NewVal));
Inc(NewOffset);
end;
if (NewOffset + Offset) > FMaxChars then Break;
if (NewOffset) > Length(NewVal) then Break;
Inc(MaskOffset);
end;
if (Offset + Length(NewVal)) < FMaxChars then
begin
if ByteType(Value, OffSet + Length(NewVal) + 1) = mbTrailByte then
begin
NewVal := NewVal + FMaskBlank;
Inc(NewOffset);
end;
Value := Copy(Value, 1, Offset) + NewVal +
Copy(Value, OffSet + Length(NewVal) + 1,
FMaxChars -(Offset + Length(NewVal)));
end
else
begin
Temp := Offset;
if (ByteType(NewVal, FMaxChars - Offset) = mbLeadByte) then
Inc(Temp);
Value := Copy(Value, 1, Offset) +
Copy(NewVal, 1, FMaxChars - Temp);
end;
Result := NewOffset + Offset - 1;
end;
function TCustomMaskEdit.FindLiteralChar(MaskOffset: Integer; InChar: Char): Integer;
var
CType: TMaskCharType;
LitChar: Char;
begin
Result := -1;
while MaskOffset < Length(EditMask) do
begin
Inc(MaskOffset);
CType := MaskGetCharType(EditMask, MaskOffset);
if CType in [mcLiteral, mcIntlLiteral] then
begin
LitChar := EditMask[MaskOffset];
if CType = mcIntlLiteral then
LitChar := MaskIntlLiteralToChar(LitChar);
if LitChar = InChar then
Result := MaskOffset;
Exit;
end;
end;
end;
procedure TCustomMaskEdit.DoEnter;
begin
if IsMasked and not (csDesigning in ComponentState) then
begin
if not (msReEnter in FMaskState) then
begin
FOldValue := EditText;
inherited;
end;
Exclude(FMaskState, msReEnter);
CheckCursor;
end
else
inherited;
end;
procedure TCustomMaskEdit.DoExit;
begin
if IsMasked and not (csDesigning in ComponentState) then
begin
ValidateEdit;
CheckCursor;
end;
inherited;
end;
procedure TCustomMaskEdit.MouseDown(Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
inherited;
FBtnDownX := X;
end;
procedure TCustomMaskEdit.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
var
SelStart, SelStop : Integer;
begin
inherited;
if (IsMasked) then
begin
GetSel(SelStart, SelStop);
FCaretPos := SelStart;
if (SelStart <> SelStop) and (X > FBtnDownX) then
FCaretPos := SelStop;
CheckCursor;
end;
end;
procedure TCustomMaskEdit.TextChanged;
var
SelStart, SelStop : Integer;
Temp: Integer;
begin
inherited;
FOldValue := EditText;
if HandleAllocated then
begin
GetSel(SelStart, SelStop);
Temp := GetNextEditChar(SelStart);
if Temp <> SelStart then
SetCursor(Temp);
end;
end;
procedure TCustomMaskEdit.CutToClipboard;
begin
if not (IsMasked) then
inherited
else
begin
CopyToClipboard;
DeleteKeys(Key_Delete);
end;
end;
procedure TCustomMaskEdit.PasteFromClipboard;
var
Value: string;
Str: string;
SelStart, SelStop : Integer;
begin
if not IsMasked or ReadOnly then
inherited
else begin
Value := Clipboard.AsText;
GetSel(SelStart, SelStop);
Str := EditText;
DeleteSelection(Str, SelStart, SelStop - SelStart);
EditText := Str;
SelStart := InputString(Str, Value, SelStart);
EditText := Str;
SetCursor(SelStart);
end;
end;
procedure TCustomMaskEdit.DoBeep;
begin
if BeepOnError then
SysUtils.Beep;
end;
end.
|
unit IdEMailAddress;
interface
uses
Classes;
type
TIdEMailAddressItem = class(TCollectionItem)
protected
FAddress: string;
FName: string;
function GetText: string;
procedure SetText(AText: string);
public
procedure Assign(Source: TPersistent); override;
published
property Address: string read FAddress write FAddress;
property Name: string read FName write FName;
property Text: string read GetText write SetText;
end;
TIdEMailAddressList = class(TOwnedCollection)
protected
function GetItem(Index: Integer): TIdEMailAddressItem;
procedure SetItem(Index: Integer; const Value: TIdEMailAddressItem);
function GetEMailAddresses: string;
procedure SetEMailAddresses(AList: string);
public
constructor Create(AOwner: TPersistent); reintroduce;
procedure FillTStrings(AStrings: TStrings);
function Add: TIdEMailAddressItem;
property Items[Index: Integer]: TIdEMailAddressItem read GetItem write
SetItem; default;
property EMailAddresses: string read GetEMailAddresses
write SetEMailAddresses;
end;
implementation
uses IdGlobal, SysUtils;
procedure TIdEMailAddressItem.Assign(Source: TPersistent);
var
Addr: TIdEMailAddressItem;
begin
if ClassType <> Source.ClassType then
begin
inherited
end
else
begin
Addr := TIdEMailAddressItem(Source);
Address := Addr.Address;
Name := Addr.Name;
end;
end;
function TIdEMailAddressItem.GetText: string;
begin
if (Length(FName) > 0) and (UpperCase(FAddress) <> FName) then
begin
Result := FName + ' <' + FAddress + '>';
end
else
begin
Result := FAddress;
end;
end;
procedure TIdEMailAddressItem.SetText(AText: string);
var
nPos: Integer;
begin
FAddress := '';
FName := '';
if Copy(AText, Length(AText), 1) = '>' then
begin
nPos := IndyPos('<', AText);
if nPos > 0 then
begin
FAddress := Trim(Copy(AText, nPos + 1, Length(AText) - nPos - 1));
FName := Trim(Copy(AText, 1, nPos - 1));
end;
end
else
begin
if Copy(AText, Length(AText), 1) = ')' then
begin
nPos := IndyPos('(', AText);
if nPos > 0 then
begin
FName := Trim(Copy(AText, nPos + 1, Length(AText) - nPos - 1));
FAddress := Trim(Copy(AText, 1, nPos - 1));
end;
end
else
begin
FAddress := AText;
end;
end;
while Length(FName) > 1 do
begin
if (FName[1] = '"') and (FName[Length(FName)] = '"') then
begin
FName := Copy(FName, 2, Length(FName) - 2);
end
else
begin
if (FName[1] = '''') and (FName[Length(FName)] = '''') then
begin
FName := Copy(FName, 2, Length(FName) - 2);
end
else
begin
break;
end;
end;
end;
end;
function TIdEMailAddressList.Add: TIdEMailAddressItem;
begin
Result := TIdEMailAddressItem(inherited Add);
end;
constructor TIdEMailAddressList.Create(AOwner: TPersistent);
begin
inherited Create(AOwner, TIdEMailAddressItem);
end;
procedure TIdEMailAddressList.FillTStrings(AStrings: TStrings);
var
idx: Integer;
begin
idx := 0;
while (idx < Count) do
begin
AStrings.Add(GetItem(idx).Text);
Inc(idx);
end;
end;
function TIdEMailAddressList.GetItem(Index: Integer): TIdEMailAddressItem;
begin
Result := TIdEMailAddressItem(inherited Items[Index]);
end;
function TIdEMailAddressList.GetEMailAddresses: string;
var
idx: Integer;
begin
Result := '';
idx := 0;
while (idx < Count) do
begin
Result := Result + ', ' + GetItem(idx).Text;
Inc(idx);
end;
System.Delete(Result, 1, 2);
end;
procedure TIdEMailAddressList.SetItem(Index: Integer;
const Value: TIdEMailAddressItem);
begin
inherited SetItem(Index, Value);
end;
procedure TIdEMailAddressList.SetEMailAddresses(AList: string);
var
EMail: TIdEMailAddressItem;
iStart,
iEnd,
iQuote,
iPos,
iLength: integer;
sTemp: string;
begin
Clear;
iQuote := 0;
iPos := 1;
iLength := Length(AList);
while (iPos <= iLength) do
begin
iStart := iPos;
iEnd := iStart;
while (iPos <= iLength) do
begin
if AList[iPos] = '"' then
begin
inc(iQuote);
end;
if AList[iPos] = ',' then
begin
if iQuote <> 1 then
begin
break;
end;
end;
inc(iEnd);
inc(iPos);
end;
sTemp := Trim(Copy(AList, iStart, iEnd - iStart));
if Length(sTemp) > 0 then
begin
EMail := Add;
EMail.Text := TrimLeft(sTemp);
end;
iPos := iEnd + 1;
iQuote := 0;
end;
end;
end.
|
unit ClientModuleUnit1;
interface
uses
System.SysUtils, System.Classes, ClientClassesUnit1, Datasnap.DSClientRest;
type
TClientModule1 = class(TDataModule)
DSRestConnection1: TDSRestConnection;
private
FInstanceOwner: Boolean;
FSmServicosClient: TSmServicosClient;
function GetSmServicosClient: TSmServicosClient;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property InstanceOwner: Boolean read FInstanceOwner write FInstanceOwner;
property SmServicosClient: TSmServicosClient read GetSmServicosClient write FSmServicosClient;
end;
var
ClientModule1: TClientModule1;
implementation
{%CLASSGROUP 'FMX.Controls.TControl'}
{$R *.dfm}
constructor TClientModule1.Create(AOwner: TComponent);
begin
inherited;
FInstanceOwner := True;
end;
destructor TClientModule1.Destroy;
begin
FSmServicosClient.Free;
inherited;
end;
function TClientModule1.GetSmServicosClient: TSmServicosClient;
begin
if FSmServicosClient = nil then
FSmServicosClient:= TSmServicosClient.Create(DSRestConnection1, FInstanceOwner);
Result := FSmServicosClient;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.