text stringlengths 14 6.51M |
|---|
{***************************************************************
*
* Project : Server
* Unit Name: ServerMain
* Purpose : Demonstrates basic use of IdTCPServer
* Date : 16/01/2001 - 03:19:36
* History :
*
****************************************************************}
unit ServerMain;
interface
uses
SysUtils, Classes,
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs,
{$ELSE}
graphics, controls, forms, dialogs,
{$ENDIF}
IdBaseComponent, IdComponent, IdTCPServer;
type
TfrmServer = class(TForm)
TCPServer: TIdTCPServer;
procedure FormCreate(Sender: TObject);
procedure TCPServerExecute(AThread: TIdPeerThread);
private
public
end;
var
frmServer: TfrmServer;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TfrmServer.FormCreate(Sender: TObject);
begin
TCPServer.Active := True;
end;
// Any client that makes a connection is sent a simple message,
// then disconnected.
procedure TfrmServer.TCPServerExecute(AThread: TIdPeerThread);
begin
with AThread.Connection do
begin
WriteLn('Hello from Basic Indy Server server.');
Disconnect;
end;
end;
end.
|
unit MapMenu;
interface
{Процедура инциализации выбора карт }
procedure InitMapMenu();
{Процедура отлова нажатия клавиш в выборе карт }
procedure HandleInputInMapMenu();
{Процедура обновления логики выбора карт }
procedure UpdateMapMenu(dt : integer);
{Процедура отрисовки выбора карт }
procedure RenderMapMenu();
implementation
uses
GraphABC, GlobalVars, UIAssets;
const
MaxOptions = 1; //Максимальное кол-во кнопок в данном состоянии
var
TextFile : Text; //Текстовой файл с названием карт
Count : integer; //Кол-во карт
Maps : array[1..12] of string; //Названия карт
Options : array[1..MaxOptions] of string; //Кнопки
CurrentOp : byte; //Текущая кнопка или карта
procedure InitMapMenu;
begin
CurrentOp := 1;
Options[1] := 'Назад';
Count := 0;
Assign(TextFile, 'maps.txt');
Reset(TextFile);
while (not Eof(TextFile) and (Count < 12)) do
begin
Count := Count + 1;
Readln(TextFile, Maps[Count]);
end;
Close(TextFile);
end;
procedure HandleInputInMapMenu;
begin
if (inputKeys[VK_DOWN] or inputKeys[VK_S]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp + 1 > Count + MaxOptions) then
begin
CurrentOp := 1;
end
else
begin
CurrentOp := CurrentOp + 1;
end;
end;
end;
if (inputKeys[VK_UP] or inputKeys[VK_W]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp - 1 < 1) then
begin
CurrentOp := Count + MaxOptions;
end
else
begin
CurrentOp := CurrentOp - 1;
end;
end;
end;
if (inputKeys[VK_ENTER]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
if (CurrentOp = Count + 1) then
begin
ChangeState(MenuState);
end
else
begin
_CurrentMap := Maps[CurrentOp];
ChangeState(InputNamesState);
end;
end;
end;
if (inputKeys[VK_ESCAPE]) then
begin
if (Milliseconds() - LastChange > DelayInput) then
begin
LastChange := Milliseconds();
ChangeState(MenuState);
end;
end;
end;
procedure UpdateMapMenu;
begin
HandleInputInMapMenu();
end;
procedure RenderMapMenu;
begin
SetBrushStyle(bsSolid);
Window.Clear();
Background.Draw(0, 0);
DrawHeader(Window.Width div 2, 78, 'Выберите карту');
SetFontSize(26);
for var i:=1 to Count do
begin
if (CurrentOp = i) then
begin
SetBrushStyle(bsSolid);
SetPenWidth(2);
SetPenColor(clBlack);
SetBrushColor(RGB(201, 160, 230));
DrawChooseLine(-2, 118 + 50 * i - 20, Window.Width, 40);
SetPenWidth(0);
end;
SetBrushStyle(bsClear);
DrawTextCentered(Window.Width div 2, 118 + 50 * i, Maps[i]);
end;
SetFontColor(clBlack);
for var i:=1 to MaxOptions do
begin
var isActive := false;
if (CurrentOp = (i + Count)) then
begin
isActive := true;
end;
DrawButton(Window.Width div 2, 138 + 50 *(Count + i), Options[i], defaultSize, isActive);
end;
end;
begin
end. |
{Copyright (C) 2008-2021 Benito van der Zander
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
}
(***
@abstract(This unit contains classes to handle multi-page template scripts. A collection of single-page patterns that are applied to multiple webpages.)@br@br
The class TMultiPageTemplate can be used to load a multi-page template script (and there is also the documentation of the template syntax/semantic).
The class TMultipageTemplateReader can be used to run the template.
TMultipageTemplateReader does not modify the TMultipageTemplate, so a single TMultipageTemplate can be used by arbitrary many TMultipageTemplateReader, even if the readers are in different threads.
*)
unit multipagetemplate;
{$mode objfpc}{$H+}
{$COperators on}{$goto on}{$inline on}
interface
uses
Classes, SysUtils,bbutils,extendedhtmlparser, simplehtmltreeparser,simplexmlparser, xquery,internetaccess,bbutilsbeta;
type
{ TTemplateAction }
TMultipageTemplateReader = class;
TLoadTemplateFile = function(name: RawByteString): string;
TTemplateLoadingContext = class
path: string;
loadFileCallback: TLoadTemplateFile;
preferredLanguage: string;
function createParser: TTreeParser;
end;
//**@abstract(Internal used base class for an action within the multi-page template)
TTemplateAction = class
protected
procedure addChildFromTree(context: TTemplateLoadingContext; t: TTreeNode);
procedure performChildren(reader: TMultipageTemplateReader);
function cloneChildren(theResult: TTemplateAction): TTemplateAction;
function parseQuery(reader: TMultipageTemplateReader; const query: string): IXQuery;
function evaluateQuery(reader: TMultipageTemplateReader; const query: string): IXQValue;
public
children: array of TTemplateAction;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); virtual;
procedure addChildrenFromTree(context: TTemplateLoadingContext; t: TTreeNode);
procedure perform(reader: TMultipageTemplateReader); virtual;
function clone: TTemplateAction; virtual;
procedure clear;
destructor Destroy; override;
end;
TTemplateActionClass = class of TTemplateAction;
{ TTemplateActionMeta }
TTemplateActionMeta = class(TTemplateAction)
description: string;
variables: array of record
name: string;
hasDef: boolean;
def: string;
description: string;
end;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform({%H-}reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TMultiPageTemplate }
(***@abstract(A multi-page template, which defines which and how web pages are processed. @br )
A multi-page template defines a list of actions, each action listing webpages to download and queries to run on those webpages. @br
You can then call an action, let it run its queries, and read the result as variables.
(In the past patterns, were called templates, too, but they are very different from the multi-page template of this unit. @br
A multi-page template is a list of explicit actions that are performed in order, like an algorithm or script; @br
A pattern (single-page template) is an implicit pattern that is matched against the page, like a regular expression)
The syntax of a multi-page template is inspired by the XSLT/XProc syntax and looks like this:
@preformatted(
<actions>
<action id="action-1">
<variable name="foobar" value="xyz"/>
<page url="url to send the request to">
<header name="header name">value...</header>
<post name="post variable name"> value... </post>
</page>
<pattern> ...to apply to the previous page (inline)... </pattern>
<pattern href="to apply to the previous page (from a file)"/>
...
</action>
<action id="action-2">
...
</action>
...
</actions>)
<actions> contains a list/map of named actions, each <action> can contain:
@unorderedList(
@item(@code(<page>) Downloads a webpage. )
@item(@code(<json>) Same as <page> but to download JSON data. )
@item(@code(<pattern>) Processes the last page with pattern matching. )
@item(@code(<variable>) Sets an variable, either to a string value or to an evaluated XPath expression. )
@item(@code(<loop>) Repeats the children of the loop element. )
@item(@code(<call>) Calls another action. )
@item(@code(<if>) Tests, if a condition is satisfied. )
@item(@code(<choose><when><otherwise>) Switches depending on a value. )
@item(@code(<s>) Evaluates an XPath/XQuery expression. )
@item(@code(<try><catch>) Catch errors. )
@item(@code(<include>) Includes template elements from another file. )
)
Details for each element:
@definitionList(
@itemLabel(@code(<page url="request url">))
@item(
Specifies a page to download and process. @br
You can use @code(<post name="..name.." value="..value..">..value..</post>) child elements under <page> to add
variables for a post request to send to the url. @br
If the name attribute exists, the content is url-encoded, otherwise not. @br
(currently, the value attribute and the contained text are treated as a string to send.
In future versions, the contained text will be evaluated as XPath expression.) @br
If no <post> children exist, a GET request is sent.
The patterns that should be applied to the downloaded page, can be given directly in a <pattern> element, or
in a separate file linked by the pattern-href attribute.
(see THtmlTemplateParser for a description of the pattern-matching single-page template.)
The attribute @code(test="xpath") can be used to skip a page if the condition in the attribute evaluates to false().
)
@itemLabel(@code(<pattern href="file" name=".."> inline pattern </variable>))
@item(
This applies a pattern to the last page.
The pattern can be given inline or loaded from a file in the href attribute.
The name attribute is only used for debugging.
)
@itemLabel(@code(<variable name="name" value="str value">xpath expression</variable>))
@item(
This sets the value of the variable with name $name.
If the value attribute is given, it is set to the string value of the attribute, otherwise, the xpath expression
is evaluated and its result is used.
The last downloaded webpage is available as the root element in the XPath expression.
)
@itemLabel(@code(<loop var="variable name" list="list (xpath)" test="condition (xpath)">))
@item(
Repeats the children of this element.@br
It can be used like a foreach loop by giving the var/list attributes, like a while loop by using test,
or like a combination of both.@br
In the first case, the expression in list is evaluated, each element of the resulting sequence is assigned
once to the variable with the name $var, and the loop body is evaluated each time.@br
In the second case, the loop is simply repeated forever, until the expression in the test attributes evaluates to false.
)
@itemLabel(@code(<call action="name">))
@item(
Calls the action of the given name.
)
@itemLabel(@code(<if test="...">))
@item(
Evaluates the children of this element, if the test evaluates to true().
)
@itemLabel(@code(<choose> <when test="..."/> <otherwise/> </choose>))
@item(
Evaluates the tests of the when-elements and the children of the first <when> that is true. @br
If no test evaluates to true(), the children of <otherwise> are evaluated.
)
@itemLabel(@code(<s>...</s>))
@item(
Evaluates an XPath/XQuery expression (which can set global variables with :=).
)
@itemLabel(@code(<try> ... <catch errors="...">...</catch> </s>))
@item(
Iff an error occurs during the evaluation of the non-<catch> children of the <try>-element, the children of matching <catch>-element are evaluated.
This behaves similar to the try-except statement in Pascal and <try><catch> in XSLT. @br@br
The errors attribute is a whitespace-separated list of error codes caught by that <catch> element. XPath/XQuery errors have the form @code( err:* ) with the value of * given in the XQuery standard.@br
HTTP errors have the internal form @code( pxp:http123 ) where pxp: is the default prefix. Nevertheless, they can be matched using the namespace prefix http as @code(http:123). Partial wildcards are accepted like @code(http:4* ) to match the range 400 to 499. @br
@code(pxp:pattern) is used for pattern matching failures.
)
@itemLabel(@code(<include href="filename">))
@item(
Includes another XML file. It behaves as if the elements of the other file were copy-pasted here.
)
)
Within all string attributes, you can access the previously defined variables by writing @code({$variable}) .@br
Within an XPath expression, you can access the variable with @code($variable).
*)
TMultiPageTemplate=class
protected
procedure readTemplateFromString(template: string; loadFileCallback: TLoadTemplateFile; path: string; preferredLanguage: string);
procedure readTree(context: TTemplateLoadingContext; t: TTreeNode);
public
//**The primary <actions> element (or the first <action> element, if only one exists)
baseActions: TTemplateAction;
//**A name for the template, for debugging
name:string;
constructor create();
//**Loads a template from a directory. @br
//**The multipage template is read from the file @code(template).
procedure loadTemplateFromDirectory(_dataPath: string; aname: string = 'unknown');
//**Loads a template directly from a string. @br
//**If the template loads additional files like include files, you need to give a path.
procedure loadTemplateFromString(template: string; aname: string = 'unknown'; path: string = '');
//**Loads a template using a callback function. The callback function is called with different files names to load the corresponding file.
procedure loadTemplateWithCallback(loadSomething: TLoadTemplateFile; _dataPath: string; aname: string = 'unknown'; preferredLanguage: string = '');
destructor destroy;override;
//**Returns the <action> element with the given id.
function findAction(_name:string): TTemplateAction;
//**Find the first <variable> element definining a variable with the given name. @br
//**Only returns the value of the value attribute, ignoring any contained xpath expression
function findVariableValue(aname: string): string;
function clone: TMultiPageTemplate;
end;
{ TMultipageTemplateReader }
ETemplateReader=class(Exception)
details:string;
constructor create;
constructor create(s:string;more_details:string='');
end;
//**Event you can use to log, what the template is doing .@br
//**Arguments: logged contains the message, debugLevel the importance of this event
TLogEvent = procedure (sender: TMultipageTemplateReader; logged: string; debugLevel: integer = 0) of object;
//**Event that is called after every <page> element is processed. @br
//**You can use parser to read the variables changed by the template applied to the page
TPageProcessed = procedure (sender: TMultipageTemplateReader; parser: THtmlTemplateParser) of object;
//**@abstract(Class to process a multi-page template)
//**see TMultiPageTemplate for a documentation of the allowed XML elements.
TMultipageTemplateReader = class
protected
template:TMultiPageTemplate;
lastData, lastContentType: string;
lastDataFormat: TInternetToolsFormat;
dataLoaded: boolean;
queryCache: TXQMapStringObject;
procedure needLoadedData;
procedure setTemplate(atemplate: TMultiPageTemplate);
procedure applyPattern(pattern, name: string); virtual;
procedure setVariable(name: string; value: IXQValue; namespace: string = ''); virtual;
procedure setVariable(name: string; value: string; namespace: string = '');
function parseQuery(const query: string): IXQuery;
function evaluateQuery(const query: IXQuery): IXQValue; virtual;
public
//** Object used to send requests and download pages
internet:TInternetAccess;
//** Parser used to apply the given single page templates to a downloaded page
parser: THtmlTemplateParser;
//** Log event
onLog: TLogEvent;
//** Event to access the changed variable state after each processed <page> element
onPageProcessed: TPageProcessed;
retryOnConnectionFailures: boolean;
actionTrace: TStringArrayList;
//** Creates a reader using a certain template (atemplate is mandatory, ainternet optional)
constructor create(atemplate:TMultiPageTemplate; ainternet: TInternetAccess; patternMatcher: THtmlTemplateParser = nil);
destructor destroy();override;
//** Searches the action element with the given id (equivalent to TMultiPageTemplate.findAction)
function findAction(name:string):TTemplateAction;
//** Executes the action with the given id @br(e.g. setting all variables, downloading all pages defined there) @br
//** This does not modify the action, so you can use the same template with multiple readers (even in other threads)
procedure callAction(action:string);
//** Executes the given action @br(e.g. setting all variables, downloading all pages defined there)
//** This does not modify the action, so you can use the same template with multiple readers (even in other threads)
procedure callAction(const action:TTemplateAction);
end;
implementation
uses xquery_json, xquery.namespaces;
type
{ TTemplateActionMain }
TTemplateActionMain = class(TTemplateAction)
name: string;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionVariable }
TTemplateActionVariable = class(TTemplateAction)
name, value, valuex: string;
hasValueStr: boolean;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
TTemplateActionPage = class(TTemplateAction)
url, data:string;
headers, postparams:array of TProperty;
condition, method: string;
inputFormat: TInternetToolsFormat;
errorHandling: string;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
private
procedure onTransferReact(sender: TInternetAccess; var {%H-}transfer: TTransfer; var reaction: TInternetAccessReaction);
end;
TTemplateActionPattern = class(TTemplateAction)
pattern:string;
constructor create;
constructor createFromFile(context: TTemplateLoadingContext; href: string);
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
private
name: string;
procedure loadFile(context: TTemplateLoadingContext;href: string);
end;
{ TTemplateActionCallAction }
TTemplateActionCallAction = class(TTemplateAction)
action, test: string;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionIf }
TTemplateActionIf = class(TTemplateAction)
test: string;
&else: TTemplateAction;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
destructor Destroy; override;
end;
{ TTemplateActionChoose }
TTemplateActionChoose = class(TTemplateAction)
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionChooseWhen }
TTemplateActionChooseWhen = class(TTemplateAction)
test: string;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform({%H-}reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionChooseOtherwise }
TTemplateActionChooseOtherwise = class(TTemplateAction)
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform({%H-}reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionLoop }
TTemplateActionLoop = class(TTemplateAction)
varname, list, test: string;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionShort }
TTemplateActionShort = class(TTemplateAction)
test, query: string;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
{ TTemplateActionShort }
TTemplateActionTry = class(TTemplateAction)
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform(reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
end;
TTemplateActionCatch = class(TTemplateAction)
errNamespaces, errCodes: TStringArray;
procedure initFromTree(context: TTemplateLoadingContext; t: TTreeNode); override;
procedure perform({%H-}reader: TMultipageTemplateReader); override;
function clone: TTemplateAction; override;
function checkError(reader: TMultipageTemplateReader; const namespace, prefix, code: string): boolean;
end;
resourcestring
rsActionNotFound = 'Action %s not found.';
function TTemplateLoadingContext.createParser: TTreeParser;
begin
result := TTreeParser.Create;
result.globalNamespaces.add(TNamespace.create(HTMLPARSER_NAMESPACE_URL, 't'));
result.globalNamespaces.add(TNamespace.create(HTMLPARSER_NAMESPACE_URL, 'template'));
result.TargetEncoding:=CP_UTF8;
end;
procedure TTemplateActionTry.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
var
hadCatch: Boolean;
i: Integer;
begin
addChildrenFromTree(context, t);
hadCatch := false;
for i := 0 to high(children) do
if objInheritsFrom(children[i], TTemplateActionCatch) then hadCatch := true
else if hadCatch then raise ETemplateReader.create('Cannot have non-catch element after catch element');
end;
procedure TTemplateActionTry.perform(reader: TMultipageTemplateReader);
function checkError(namespace, prefix, errCode: string): boolean;
var
i: Integer;
begin
for i := 0 to high(children) do
if objInheritsFrom(children[i], TTemplateActionCatch) then
if TTemplateActionCatch(children[i]).checkError(reader, namespace, prefix, errCode) then
exit(true);
exit(false);
end;
var
tempcode: String;
begin
try
performChildren(reader);
except
on e:EXQException do begin
if (e.namespace <> nil) and checkError(e.namespace.getURL, e.namespace.getPrefix, e.errorCode) then exit;
if (e.namespace = nil) and checkError('', '', e.errorCode) then exit;
raise;
end;
on e:EInternetException do begin
if e.errorCode >= 0 then tempcode := IntToStr(e.errorCode)
else tempcode := '000';
while length(tempcode) < 3 do tempcode := '0' + tempcode;
if checkError(XMLNamespaceURL_MyExtensionsNew, 'x', 'http' + tempcode) then exit;
raise;
end;
on e: EHTMLParseMatchingException do begin
if checkError(XMLNamespaceURL_MyExtensionsNew, 'x', 'pattern') then exit;
raise;
end;
end;
end;
function TTemplateActionTry.clone: TTemplateAction;
begin
Result:=TTemplateActionTry.Create;
result := cloneChildren(result);
end;
procedure TTemplateActionCatch.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
var
errors: TStringArray;
i: Integer;
temp: TStringArray;
begin
if not t.hasAttribute('errors') then begin
SetLength(errNamespaces, 1);
errNamespaces[0] := '*';
errCodes := errNamespaces;
end else begin
errors := strSplit(strTrimAndNormalize(t.getAttribute('errors')), ' ', false);
SetLength(errNamespaces, length(errors));
SetLength(errCodes, length(errors));
for i := 0 to high(errors) do begin
if strBeginsWith(errors[i], 'Q{') then begin
errNamespaces[i] := strDecodeHTMLEntities(strBetween(errors[i], 'Q{','}'),CP_UTF8);
errCodes[i] := strAfter(errors[i], '{');
end else if strContains(errors[i], ':') then begin
temp := strSplit(errors[i], ':');
errNamespaces[i] := temp[0];
errCodes[i] := temp[1];
case errNamespaces[i] of
'err': errNamespaces[i] := XMLNamespaceURL_XQTErrors;
'pxp', 'x': errNamespaces[i] := XMLNamespaceURL_MyExtensionsNew;
'local': errNamespaces[i] := XMLNamespaceURL_XQueryLocalFunctions;
'http': begin
errNamespaces[i] := XMLNamespaceURL_MyExtensionsNew;
errCodes[i] := 'http' + errCodes[i];
case length(errCodes[i]) of
length('http12*'): errCodes[i] := StringReplace(errCodes[i], '*', 'x', []);
length('http1*'): errCodes[i] := StringReplace(errCodes[i], '*', 'xx', []);
length('http*'): errCodes[i] := StringReplace(errCodes[i], '*', 'xxx', []);
end;
end;
'*': errNamespaces[i] := '*';
else begin
raise ETemplateReader.create('Unknown namespace prefix: '+errNamespaces[i] + ' (only err, pxp and local are known)');
end
end;
end else begin
errNamespaces[i] := XMLNamespaceURL_MyExtensionsNew;
errCodes[i] := errors[i];
if errCodes[i] = '*' then errNamespaces[i] := '*';
end;
if errCodes[i] <> '*' then
baseSchema.NCName.createValue(errCodes[i]); //ensure err code is valid
end;
end;
addChildrenFromTree(context, t);
end;
procedure TTemplateActionCatch.perform(reader: TMultipageTemplateReader);
begin
;
end;
function TTemplateActionCatch.clone: TTemplateAction;
begin
Result:=TTemplateActionCatch.Create;
TTemplateActionCatch(result).errNamespaces := errNamespaces;
TTemplateActionCatch(result).errCodes := errCodes;
with TTemplateActionCatch(result) do begin
SetLength(errNamespaces, length(errNamespaces));
SetLength(errCodes, length(errCodes));
end;
cloneChildren(result);
end;
function TTemplateActionCatch.checkError(reader: TMultipageTemplateReader; const namespace, prefix, code: string): boolean;
function check: boolean;
var
i, j: Integer;
ok: Boolean;
begin
for i := 0 to high(errCodes) do begin
if (errNamespaces[i] <> namespace) and (errNamespaces[i] <> '*') then continue;
if (errCodes[i] = code) or (errCodes[i] = '*') then exit(true);
if (errNamespaces[i] = XMLNamespaceURL_MyExtensionsNew) and (strBeginsWith(errCodes[i], 'http')) and (strBeginsWith(code, 'http')) then begin
if length(errCodes[i]) = 4 { = 'http' } then exit(true);
if length(errCodes[i]) <> length(code) then continue;
ok := true;
for j := 5 to length(code) do
if (code[j] <> errCodes[i][j]) and not (errCodes[i][j] in ['X','x']) then begin ok := false; break; end;
if ok then exit(true);
end;
end;
result := false;
end;
begin
result := check;
if result then begin
reader.setVariable('code', xqvalue(TXQBoxedQName.create(namespace,prefix,code)), XMLNamespaceURL_XQTErrors);
//description, value, ...
performChildren(reader);
end;
end;
constructor TTemplateActionPattern.create;
begin
end;
constructor TTemplateActionPattern.createFromFile(context: TTemplateLoadingContext;href: string);
begin
name := href;
loadFile(context, href);
end;
procedure TTemplateActionPattern.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
var
href: String;
begin
ignore(context);
href := t.getAttribute('href'); //Is loaded later
name := t.getAttribute('name');
pattern := t.innerXML();
if (href <> '') then begin
if pattern <> '' then raise ETemplateReader.create('Cannot mix href attribute with direct pattern text');
loadFile(context, href);
end;
end;
procedure TTemplateActionPattern.perform(reader: TMultipageTemplateReader);
begin
if Assigned(reader.onLog) then reader.onLog(reader, 'Apply pattern: '+name + ' to '+reader.internet.lastUrl, 2);
reader.applyPattern(pattern, name);
end;
function TTemplateActionPattern.clone: TTemplateAction;
begin
Result:=TTemplateActionPattern.Create;
TTemplateActionPattern(result).pattern := pattern;
TTemplateActionPattern(result).name := name;
end;
procedure TTemplateActionPattern.loadFile(context: TTemplateLoadingContext; href: string);
begin
pattern:=context.loadFileCallback(context.path+href);
if pattern='' then
raise ETemplateReader.create('Failed to load "'+context.path+href+'".');
end;
{ TTemplateActionShort }
procedure TTemplateActionShort.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
ignore(context);
query := t.deepNodeText();
test := t['test'];
end;
procedure TTemplateActionShort.perform(reader: TMultipageTemplateReader);
begin
if test <> '' then
if not evaluateQuery(reader, test).toBooleanEffective then
exit;
evaluateQuery(reader, query);
end;
function TTemplateActionShort.clone: TTemplateAction;
begin
Result:=TTemplateActionShort.Create;
TTemplateActionShort(result).query:=query;
end;
procedure TTemplateActionIf.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
inherited initFromTree(context, t);
test := t['test'];
addChildrenFromTree(context, t);
//else is handled separately
end;
procedure TTemplateActionIf.perform(reader: TMultipageTemplateReader);
begin
if evaluateQuery(reader, test).toBooleanEffective then performChildren(reader)
else if &else <> nil then &else.performChildren(reader);
end;
function TTemplateActionIf.clone: TTemplateAction;
begin
result := cloneChildren(TTemplateActionIf.Create);
TTemplateActionIf(result).test := test;
if &else <> nil then TTemplateActionIf(result).&else := &else.clone;
end;
destructor TTemplateActionIf.Destroy;
begin
&else.free;
inherited Destroy;
end;
{ TTemplateActionMeta }
type TLanguageScore = (lsBest = 0, lsEmpty = 1, lsEnglish, lsOther, lsUnitialized);
procedure TTemplateActionMeta.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
procedure updateADescription(var desc: string; var oldScore: TLanguageScore; e: TTreeNode); //choose the best language
var score: TLanguageScore;
lang: string;
begin
if oldScore = lsBest then exit;
lang := e['lang'];
if lang = context.preferredLanguage then score := lsBest
else if lang = '' then score := lsEmpty
else if lang = 'en' then score := lsEnglish
else score := lsOther;
if score >= oldScore then exit;
oldScore := score;
desc := e.deepNodeText();
end;
var
e, f: TTreeNode;
templateDescriptionLanguageScore: TLanguageScore = lsUnitialized;
variableDescriptionLanguageScore: TLanguageScore;
begin
ignore(context);
e := t.next;
while e <> nil do begin
if (e.typ = tetOpen) then
case e.value of
'description': updateADescription(description, templateDescriptionLanguageScore, e);
'variable': begin
SetLength(variables, length(variables)+1);
with variables[high(variables)] do begin
name := e['name'];
hasDef:= e.hasAttribute('default');
if hasDef then def := e['default'];
variableDescriptionLanguageScore := lsUnitialized;
f := e.findChild(tetOpen, 'description', []);
while f <> nil do begin
if (f.typ = tetOpen) and (f.value = 'description') then
updateADescription(description, variableDescriptionLanguageScore, f);
f := f.getNextSibling();
end;
end;
end;
end;
e := e.getNextSibling();
end;
end;
procedure TTemplateActionMeta.perform(reader: TMultipageTemplateReader);
begin
end;
function TTemplateActionMeta.clone: TTemplateAction;
begin
Result:=TTemplateActionMeta.Create;
TTemplateActionMeta(result).Description := description;
TTemplateActionMeta(result).variables:=variables;
end;
{ TTemplateActionChooseOtherwise }
procedure TTemplateActionChooseOtherwise.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
inherited initFromTree(context, t);
addChildrenFromTree(context, t);
end;
procedure TTemplateActionChooseOtherwise.perform(reader: TMultipageTemplateReader);
begin
raise ETemplateReader.create('when is only allowed within a choose element');
end;
function TTemplateActionChooseOtherwise.clone: TTemplateAction;
begin
result := cloneChildren(TTemplateActionChooseOtherwise.Create);
end;
{ TTemplateActionChooseWhen }
procedure TTemplateActionChooseWhen.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
inherited initFromTree(context, t);
addChildrenFromTree(context, t);
test := t['test'];
end;
procedure TTemplateActionChooseWhen.perform(reader: TMultipageTemplateReader);
begin
raise ETemplateReader.create('when is only allowed within a choose element');
end;
function TTemplateActionChooseWhen.clone: TTemplateAction;
begin
result := cloneChildren(TTemplateActionChooseWhen.Create);
TTemplateActionChooseWhen(result).test:=test;
end;
{ TTemplateActionChoose }
procedure TTemplateActionChoose.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
inherited initFromTree(context, t);
addChildrenFromTree(context, t);
end;
procedure TTemplateActionChoose.perform(reader: TMultipageTemplateReader);
var
i: Integer;
j: Integer;
begin
for i := 0 to high(children) do
if objInheritsFrom(children[i], TTemplateActionChooseWhen) then begin
if (TTemplateActionChooseWhen(children[i]).evaluateQuery(reader, TTemplateActionChooseWhen(children[i]).test).toBoolean) then begin
for j := 0 to high(children[i].children) do
children[i].children[j].perform(reader);
exit;
end;
end else if objInheritsFrom(children[i], TTemplateActionChooseOtherwise) then begin
for j := 0 to high(children[i].children) do
children[i].children[j].perform(reader);
exit;
end else raise ETemplateReader.create('Only when and otherwise are allowed in choose. Got: '+children[i].ClassName);
end;
function TTemplateActionChoose.clone: TTemplateAction;
begin
result := cloneChildren(TTemplateActionChoose.Create);
end;
procedure TTemplateActionLoop.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
varname:=t['var'];
list:=t['list'];
test:=t['test'];
addChildrenFromTree(context, t);
end;
procedure TTemplateActionLoop.perform(reader: TMultipageTemplateReader);
var
listx, x: IXQValue;
testx: IXQuery;
context: TXQEvaluationContext;
hasList: Boolean;
begin
hasList := list <> '';
listx.clear;
if hasList then begin
if varname = '' then raise ETemplateReader.Create('A list attribute at a loop node requires a var attribute');
listx := evaluateQuery(reader, list);
end;
if test <> '' then begin
reader.needLoadedData;
testx := parseQuery(reader, test);
context := reader.parser.QueryContext;
end else testx := nil;
if not hasList then begin
if testx <> nil then
while testx.evaluate(context).toBoolean do
performChildren(reader);
end else for x in listx do begin
reader.setVariable(varname, x);
if (testx <> nil) and (not testx.evaluate(context).toBoolean) then
break;
performChildren(reader);
end;
end;
function TTemplateActionLoop.clone: TTemplateAction;
begin
Result:=cloneChildren(TTemplateActionLoop.Create);
TTemplateActionLoop(result).varname:=varname;
TTemplateActionLoop(result).list:=list;
TTemplateActionLoop(result).test:=test;
end;
{ TTemplateActionCallAction }
procedure TTemplateActionCallAction.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
ignore(context);
action := t['action'];
test := t['test']
end;
procedure TTemplateActionCallAction.perform(reader: TMultipageTemplateReader);
var
act: TTemplateAction;
actualaction: String;
actionTraceCount: SizeInt;
begin
if test <> '' then
if not evaluateQuery(reader, test).toBooleanEffective then
exit;
actualaction := reader.parser.replaceEnclosedExpressions(action);
act := reader.findAction(actualaction);
if act = nil then raise ETemplateReader.Create('Could not find action: '+action + ' ('+actualaction+')');
actionTraceCount := reader.actionTrace.count;
reader.actionTrace.add(actualaction + ' <call>');
act.perform(reader);
reader.actionTrace.count := actionTraceCount;
end;
function TTemplateActionCallAction.clone: TTemplateAction;
begin
Result:=cloneChildren(TTemplateActionCallAction.Create);
TTemplateActionCallAction(result).action:=action;
TTemplateActionCallAction(result).test:=test;
end;
{ TTemplateActionLoadPage }
procedure TTemplateActionPage.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
SetLength(postparams, 0);
data := t.getAttribute('data', data);
if data <> '' then url := '#data:' + StringReplace( StringReplace( data, '}', '}}', [rfReplaceAll]), '{', '{{', [rfReplaceAll]);
url := t.getAttribute('url', url);
condition := t['test'];
method:='';
if t.hasAttribute('templateFile') then begin //DEPRECATED pattern import syntax
SetLength(children, length(children)+1);
children[high(children)] := TTemplateActionPattern.createFromFile(context, t.getAttribute('templateFile'));
end;
if t.hasAttribute('pattern-href') then begin //alternative to templateFile, not recommended to use
SetLength(children, length(children)+1);
children[high(children)] := TTemplateActionPattern.createFromFile(context, t.getAttribute('pattern-href'));
end;
case LowerCase(t.value) of
'json': inputFormat := itfJSON;
else inputFormat := itfHTML;
end;
t := t.getFirstChild();
while t <> nil do begin
if t.typ = tetOpen then begin
case LowerCase(t.value) of
'post': begin
setlength(postparams, length(postparams)+1);
postparams[high(postparams)].name:=t['name'];
if t.hasAttribute('value') then postparams[high(postparams)].value:=t['value']
else postparams[high(postparams)].value:=t.deepNodeText(); //support old for a while
end;
'template': begin //DEPRECATED pattern direct syntax
SetLength(children, length(children)+1);
children[high(children)] := TTemplateActionPattern.create();
TTemplateActionPattern(children[high(children)]).pattern := TrimLeft(t.innerXML());
end;
'header': begin
setlength(headers, length(headers)+1);
if t.hasAttribute('value') then headers[high(headers)].value:=t['value']
else headers[high(headers)].value:=t.deepNodeText();
if t.hasAttribute('name') then headers[high(headers)].name:=t['name']
else if pos(':', headers[high(headers)].value) > 0 then begin
headers[high(headers)].name := strSplitGet(':', headers[high(headers)].value);
headers[high(headers)].name := trim(headers[high(headers)].name);
headers[high(headers)].value := trim(headers[high(headers)].value);
end;
end;
'method': begin
if t.hasAttribute('value') then method:=t['value']
else method:=t.deepNodeText();
end;
'error-handling': errorHandling := t['value'];
end;
end;
t := t.getNextSibling();
end;
end;
procedure TTemplateActionPage.onTransferReact(sender: TInternetAccess; var transfer: TTransfer; var reaction: TInternetAccessReaction);
begin
TInternetAccess.reactFromCodeString(errorHandling, sender.lastHTTPResultCode, reaction);
end;
procedure TTemplateActionPage.perform(reader: TMultipageTemplateReader);
procedure clearData;
begin
reader.dataLoaded := false;
reader.lastData := '';
end;
var
cururl: String;
post: String;
page: String;
tempname: String;
j: Integer;
tempvalue: IXQValue;
curmethod: String;
oldHeaders: String;
oldReact: TTransferReactEvent;
begin
if (condition <> '') and not evaluateQuery(reader, condition).toBoolean then
exit;
if data <> '' then begin
page := reader.parser.replaceEnclosedExpressions(data);
if url <> '' then
reader.internet.lastUrl := strResolveURI(reader.parser.replaceEnclosedExpressions(url), reader.internet.lastUrl);
clearData;
end else if url <> '' then begin
cururl := url;
curmethod := method;
post := '';
oldHeaders := reader.internet.additionalHeaders.Text;
if cururl <> '' then begin
if (pos('"', url) = 0) and (pos('{', url) = 0) and (pos('}', url) = 0) then cururl := url
else if (url[1] = '{') and (url[length(url)] = '}') and (pos('$', url) > 0) and (trim(copy(url, 2, length(url)-2))[1] = '$') and
reader.parser.variableChangeLog.hasVariable(trim(copy(url, pos('$', url)+1, length(url) - pos('$', url) - 1)), tempvalue) then begin
if tempvalue.isUndefined then exit;
with reader.parser.QueryEngine.evaluateXPath3('pxp:resolve-html(., pxp:get("url"))', tempvalue.get(1)) do
if kind = pvkObject then prepareInternetRequest(curmethod, cururl, post, reader.internet)
else cururl := toString;
end else cururl := reader.parser.replaceEnclosedExpressions(url);
if cururl = '' then exit;
end else begin
//allow pages without url to set variables.
reader.parser.parseHTML('<html></html>'); //apply template to empty "page"
if Assigned(reader.onPageProcessed) then reader.onPageProcessed(reader, reader.parser);
exit;
end;
clearData;
for j:=0 to high(postparams) do begin
if post <> '' then post += '&';
tempname := reader.parser.replaceEnclosedExpressions(postparams[j].name);
if tempname = '' then
post += reader.parser.replaceEnclosedExpressions(postparams[j].value) //no urlencode! parameter passes multiple values
else
post += TInternetAccess.urlEncodeData(tempname)+'='+ TInternetAccess.urlEncodeData(reader.parser.replaceEnclosedExpressions(postparams[j].value));
end;
if curmethod = '' then begin
if (Length(postparams) = 0) and (post = '') then curmethod:='GET'
else curmethod:='POST';
end;
if Assigned(reader.onLog) then reader.onLog(reader, curmethod+' internet page '+cururl+#13#10'Post: '+post);
if guessType(cururl) = rtFile then begin
if (reader.internet.lastUrl = '') then
reader.internet.lastUrl := IncludeTrailingPathDelimiter( 'file://' + strPrependIfMissing(GetCurrentDir, '/') );
cururl := strResolveURI(cururl, reader.internet.lastUrl);
end;
reader.lastContentType := '';
case guessType(cururl) of
rtRemoteURL: begin
for j := 0 to high(headers) do
reader.internet.additionalHeaders.Values[trim(headers[j].name)] := trim (reader.parser.replaceEnclosedExpressions(headers[j].value));
try
if errorHandling <> '' then begin
oldReact := reader.internet.OnTransferReact;
reader.internet.OnTransferReact:=@onTransferReact;
end;
page := reader.internet.request(curmethod, cururl, post);
except
on e: EInternetException do begin
reader.actionTrace.add(self.url);
if reader.retryOnConnectionFailures and (e.errorCode <= 0) then begin
if Assigned(reader.onLog) then reader.onLog(reader, 'Retry after error: ' + e.Message);
Sleep(2500);
page := reader.internet.request(curmethod, cururl, post);
end else raise;
end;
end;
if errorHandling <> '' then reader.internet.OnTransferReact := oldReact;
reader.lastContentType := reader.internet.getLastContentType;
reader.internet.additionalHeaders.Text := oldHeaders;
end;
rtFile: begin
try
page := strLoadFromFileUTF8(cururl);
except
on e: Exception do begin
reader.actionTrace.add(self.url);
raise
end;
end;
reader.internet.lastURL:=cururl;
end;
rtXML: begin
page := cururl;
cururl:='';
reader.internet.lastURL:=cururl;
end
else raise ETemplateReader.create('Unknown url type: '+cururl);
end;
if Assigned(reader.onLog) then reader.onLog(reader, 'downloaded: '+inttostr(length(page))+' bytes', 1);
if page='' then raise EInternetException.Create(url +' konnte nicht geladen werden');
end;
reader.lastData := page;
reader.lastDataFormat := inputFormat;
performChildren(reader);
if Assigned(reader.onLog) then reader.onLog(reader, 'page finished', 2);
end;
function TTemplateActionPage.clone: TTemplateAction;
begin
Result:=cloneChildren(TTemplateActionPage.Create);
TTemplateActionPage(result).url := url;
TTemplateActionPage(result).data := data;
TTemplateActionPage(result).headers := headers;
SetLength(TTemplateActionPage(result).headers, length(headers));
TTemplateActionPage(result).postparams := postparams;
SetLength(TTemplateActionPage(result).postparams, length(postparams));
TTemplateActionPage(result).condition:=condition;
TTemplateActionPage(result).method:=method;
TTemplateActionPage(result).inputFormat:=inputFormat;
result := result;
end;
procedure TTemplateActionVariable.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
ignore(context);
name := t['name'];
hasValueStr := t.getAttributeTry('value', value);
valuex := t.deepNodeText();
end;
procedure TTemplateActionVariable.perform(reader: TMultipageTemplateReader);
var
v: IXQValue;
begin
if hasValueStr then
reader.setVariable(name, reader.parser.replaceEnclosedExpressions(value));
if valuex <> '' then begin
v := evaluateQuery(reader, valuex);
if name <> '' then reader.setVariable(name, v);
end;
end;
function TTemplateActionVariable.clone: TTemplateAction;
begin
Result:=cloneChildren(TTemplateActionVariable.Create);
TTemplateActionVariable(result).name:=name;
TTemplateActionVariable(result).value:=value;
TTemplateActionVariable(result).valuex:=valuex;
TTemplateActionVariable(result).hasValueStr:=hasValueStr;
end;
{ TTemplateActionMain }
procedure TTemplateActionMain.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
name := t['id'];
addChildrenFromTree(context, t);
end;
procedure TTemplateActionMain.perform(reader: TMultipageTemplateReader);
begin
performChildren(reader);
end;
function TTemplateActionMain.clone: TTemplateAction;
begin
Result:=cloneChildren(TTemplateActionMain.Create);
TTemplateActionMain(result).name:=name;
end;
{ TTemplateAction }
procedure TTemplateAction.initFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
ignore(context);
ignore(t);
end;
procedure TTemplateAction.addChildFromTree(context: TTemplateLoadingContext; t: TTreeNode);
procedure addChild(c: TTemplateActionClass);
begin
SetLength(children, length(children)+1);
children[high(children)] := c.create();
children[high(children)].initFromTree(context, t);
end;
procedure addChildrenFromInclude();
var
href, oldpath, dir: String;
tree: TTreeParser;
begin
href := t['href'];
oldpath := context.path;
if href.contains('/') or href.contains('\') then begin
href := href.Replace('\', '/', [rfReplaceAll]);
dir := href.pcharViewLeftWith(href.pcharView.findLast('/')).ToString;
if context.path = '' then context.path := dir
else context.path := IncludeTrailingPathDelimiter(context.path) + dir;
end;
tree := context.createParser;
try
addChildrenFromTree(context, tree.parseTree(context.loadFileCallback(oldpath+href)));
finally
tree.free;
context.path := oldpath
end;
end;
begin
if t.typ <> tetOpen then exit;
case LowerCase(t.value) of
'variable': addChild(TTemplateActionVariable);
'action': addChild(TTemplateActionMain);
'actions': addChildrenFromTree(context, t);
'page', 'json': addChild(TTemplateActionPage);
'pattern': addChild(TTemplateActionPattern);
'call': addChild(TTemplateActionCallAction);
'choose': addChild(TTemplateActionChoose);
'when': addChild(TTemplateActionChooseWhen);
'otherwise': addChild(TTemplateActionChooseOtherwise);
'loop': addChild(TTemplateActionLoop);
'meta': addChild(TTemplateActionMeta);
'if': addChild(TTemplateActionIf);
'else':
if (length(children) = 0 ) or not objInheritsFrom(children[high(children)], TTemplateActionIf) then raise ETemplateReader.create('<else> must follow <if>')
else begin
TTemplateActionIf(children[high(children)]).&else := TTemplateAction.Create;
TTemplateActionIf(children[high(children)]).&else.addChildrenFromTree(context, t);
end;
's': addChild(TTemplateActionShort);
'try': addChild(TTemplateActionTry);
'catch': addChild(TTemplateActionCatch);
'include': addChildrenFromInclude();
else raise ETemplateReader.Create('Unknown template node: '+t.outerXML);
end;
end;
procedure TTemplateAction.performChildren(reader: TMultipageTemplateReader);
var
i: Integer;
begin
for i:=0 to high(children) do children[i].perform(reader);
end;
function TTemplateAction.cloneChildren(theResult: TTemplateAction): TTemplateAction;
var
i: Integer;
begin
result := theResult;
setlength(result.children, length(children));
for i := 0 to high(children) do
result.children[i] := children[i].clone;
end;
function TTemplateAction.parseQuery(reader: TMultipageTemplateReader; const query: string): IXQuery;
begin
result := reader.parseQuery(query);
end;
function TTemplateAction.evaluateQuery(reader: TMultipageTemplateReader; const query: string): IXQValue;
begin
reader.needLoadedData;
//result := parseQuery(reader, query).evaluate(reader.parser.HTMLTree);
result := reader.evaluateQuery(parseQuery(reader, query));
end;
procedure TTemplateAction.addChildrenFromTree(context: TTemplateLoadingContext; t: TTreeNode);
begin
t := t.getFirstChild();
while t <> nil do begin
addChildFromTree(context, t);
t := t.getNextSibling();
end;
end;
procedure TTemplateAction.perform(reader: TMultipageTemplateReader);
begin
ignore(reader);
end;
function TTemplateAction.clone: TTemplateAction;
begin
result := TTemplateAction.Create;
cloneChildren(result);
end;
procedure TTemplateAction.clear;
var
i: Integer;
begin
for i:=0 to high(children) do
children[i].free;
SetLength(children,0);
end;
destructor TTemplateAction.Destroy;
begin
clear;
inherited Destroy;
end;
{ TMultiPageTemplate }
procedure setPatternNames(a: TTemplateAction; baseName: string='');
var
i: Integer;
begin
if objInheritsFrom(a, TTemplateActionPage) then begin
baseName+=' page:'+TTemplateActionPage(a).url;
end else if objInheritsFrom(a, TTemplateActionPattern) then begin
if TTemplateActionPattern(a).name = '' then TTemplateActionPattern(a).name:='(pattern of'+baseName+')';
end else if objInheritsFrom(a, TTemplateActionMain) then
baseName+=' action:'+TTemplateActionMain(a).name;
for i := 0 to high(a.children) do
setPatternNames(a.children[i], baseName);
end;
procedure TMultiPageTemplate.readTemplateFromString(template: string; loadFileCallback: TLoadTemplateFile; path: string; preferredLanguage: string);
var
context: TTemplateLoadingContext;
tree: TTreeParser;
begin
context := TTemplateLoadingContext.Create;
if path <> '' then path := IncludeTrailingPathDelimiter(path);
context.path := path;
context.loadFileCallback := loadFileCallback;
context.preferredLanguage := preferredLanguage;
tree := context.createParser;
try
readTree(context, tree.parseTree(template));
setPatternNames(baseActions);
finally
tree.free;
context.free;
end;
end;
procedure TMultiPageTemplate.readTree(context: TTemplateLoadingContext; t: TTreeNode);
var u: TTreeNode;
begin
baseActions.clear;
if not (t.typ in [tetOpen, tetDocument]) then raise ETemplateReader.Create('Empty template');
u := t.findChild(tetOpen,'action',[tefoIgnoreText]);
if u = nil then raise ETemplateReader.Create('Empty template');
baseActions.addChildrenFromTree(context, u.getParent());
end;
constructor TMultiPageTemplate.create();
begin
baseActions:=TTemplateAction.Create;
end;
procedure TMultiPageTemplate.loadTemplateFromDirectory(_dataPath: string; aname: string);
begin
IncludeTrailingPathDelimiter(_dataPath);
if not FileExists(_dataPath+'template') then
raise ETemplateReader.Create('Template '+_dataPath+' nicht gefunden');
loadTemplateWithCallback(@strLoadFromFileUTF8, _dataPath, aname);
end;
procedure TMultiPageTemplate.loadTemplateFromString(template: string; aname: string; path: string = '');
begin
self.name:=aname;
readTemplateFromString(template, @strLoadFromFileUTF8, path, '' );
end;
procedure TMultiPageTemplate.loadTemplateWithCallback(loadSomething: TLoadTemplateFile; _dataPath: string; aname: string; preferredLanguage: string = '');
begin
self.name:=aname;
readTemplateFromString(loadSomething(_dataPath+'template'), loadSomething, _dataPath, preferredLanguage);
end;
destructor TMultiPageTemplate.destroy;
begin
baseActions.Free;
inherited destroy;
end;
function TMultiPageTemplate.findAction(_name: string): TTemplateAction;
function find(a: TTemplateAction): TTemplateAction;
var
i: Integer;
begin
for i:=0 to high(a.children) do begin
if objInheritsFrom(a.children[i], TTemplateActionMain) then
if TTemplateActionMain(a.children[i]).name = _name then exit(a.children[i]);
result := find(a.children[i]);
if result <> nil then exit;
end;
result := nil;
end;
begin
result:=find(baseActions);
end;
function TMultiPageTemplate.findVariableValue(aname: string): string;
function find(a: TTemplateAction): string;
var
i: Integer;
begin
for i:=0 to high(a.children) do begin
if objInheritsFrom(a.children[i], TTemplateActionVariable) then
if TTemplateActionVariable(a.children[i]).name = aname then exit(TTemplateActionVariable(a.children[i]).value);
result := find(a.children[i]);
if result <> '' then exit;
end;
result := '';
end;
begin
result:=find(baseActions);
end;
function TMultiPageTemplate.clone: TMultiPageTemplate;
begin
result := TMultiPageTemplate.create();
result.baseActions.free;
result.name:=name;
result.baseActions:=baseActions.clone;
end;
procedure TMultipageTemplateReader.needLoadedData;
var
curUrl: String;
begin
if dataLoaded then exit;
curUrl := internet.lastUrl;
setVariable('url', cururl);
setVariable('raw', lastData);
case lastDataFormat of
itfJSON: setVariable('json', parser.QueryEngine.DefaultJSONParser.parse(lastData));
else parser.parseHTMLSimple(lastData, curUrl, lastContentType);
end;
dataLoaded := true;
end;
procedure TMultipageTemplateReader.setTemplate(atemplate: TMultiPageTemplate);
var
i: Integer;
begin
template:=atemplate;
for i:=0 to high(atemplate.baseActions.children) do
if objInheritsFrom(atemplate.baseActions.children[i], TTemplateActionVariable) then
atemplate.baseActions.children[i].perform(self);
end;
procedure TMultipageTemplateReader.applyPattern(pattern, name: string);
begin
needLoadedData;
actionTrace.add(name);
parser.parseTemplate(pattern, name);
parser.matchLastTrees;
if Assigned(onPageProcessed) then
onPageProcessed(self, parser);
actionTrace.deleteLast();
end;
procedure TMultipageTemplateReader.setVariable(name: string; value: IXQValue; namespace: string);
begin
parser.variableChangeLog.setOverride(name, value, namespace);
end;
procedure TMultipageTemplateReader.setVariable(name: string; value: string; namespace: string);
begin
setVariable(name, xqvalue(value), namespace);
end;
type TXQueryBreaker = class(TXQuery);
function TMultipageTemplateReader.parseQuery(const query: string): IXQuery;
var
found: Integer;
q: IXQuery;
qb: TXQueryBreaker;
begin
//cache all parsed queries
//this is not for performance reasons, but to ensure that the variables declared by "declare ..." are available in later queries.
//Once a query is freed, the variables declared there disappear
found := queryCache.IndexOf(query);
if found >= 0 then exit(TXQuery(queryCache.Objects[found]));
q := parser.parseQuery(query);
qb := TXQueryBreaker(q as TXQuery);
qb._AddRef;
queryCache.AddObject(query, qb);
result := q;
end;
function TMultipageTemplateReader.evaluateQuery(const query: IXQuery): IXQValue;
begin
result := query.evaluate(parser.HTMLTree);
end;
constructor TMultipageTemplateReader.create(atemplate:TMultiPageTemplate; ainternet: TInternetAccess; patternMatcher: THtmlTemplateParser);
begin
internet:=ainternet;
parser:=patternMatcher;
if parser = nil then parser := THtmlTemplateParser.create;
if atemplate<>nil then setTemplate(atemplate);
retryOnConnectionFailures := true;
queryCache := TXQMapStringObject.Create;
queryCache.OwnsObjects := false;
actionTrace.init;
end;
destructor TMultipageTemplateReader.destroy();
var
i: Integer;
begin
for i := 0 to queryCache.Count - 1 do
TXQueryBreaker(queryCache.Objects[i])._Release;
queryCache.Free;
parser.free;
inherited destroy();
end;
function TMultipageTemplateReader.findAction(name:string): TTemplateAction;
begin
result:=template.findAction(name);
end;
procedure TMultipageTemplateReader.callAction(action: string);
var act: TTemplateAction;
begin
act:=findAction(action);
if act=nil then begin
if strEndsWith(action, '?') then begin
delete(action,length(action),1);
act := findAction(action);
if act = nil then exit;
end;
if act = nil then
raise ETemplateReader.Create(Format(rsActionNotFound, [action]));
end;
callAction(act);
end;
procedure TMultipageTemplateReader.callAction(const action:TTemplateAction);
var
actionTraceCount: SizeInt;
begin
if Assigned(onLog) then onLog(self, 'Enter performAction, finternet:', 5); //TODO: parser log
//OutputDebugString(pchar(lib.defaultVariables.Text));
Assert(internet<>nil,'Internet nicht initialisiert');
if action is TTemplateActionMain then begin
actionTraceCount := actionTrace.count;
actionTrace.add(TTemplateActionMain(action).name);
end;
action.perform(self);
if action is TTemplateActionMain then actionTrace.count := actionTraceCount;
if Assigned(onLog) then onLog(self, 'Leave performAction', 5);
end;
{ ETemplateReader }
constructor ETemplateReader.create;
begin
end;
constructor ETemplateReader.create(s: string; more_details: string);
begin
Message:=s;
details:=more_details;
end;
end.
h
|
unit uParty;
{$mode objfpc}{$H+}
interface
uses
SynCommons, mORMot, uForwardDeclaration;
type
// 1 附录
TSQLAddendum = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项
fAgreementItem: TSQLAgreementItemID;
//创建日期
fCreationDate: TDateTime;
//生效日期
fEffectiveDate: TDateTime;
//附录文本
fText: RawUTF8;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItem: TSQLAgreementItemID read fAgreementItem write fAgreementItem;
property CreationDate: TDateTime read fCreationDate write fCreationDate;
property EffectiveDate: TDateTime read fEffectiveDate write fEffectiveDate;
property Text: RawUTF8 Read fText write fText;
end;
// 2 协议
TSQLAgreement = class(TSQLRecord)
private
//产品
fProduct: TSQLProductID;
//源当事人
fPartyFrom: TSQLPartyID;
//目标当事人
fPartyTo: TSQLPartyID;
//源角色类型
fRoleTypeFrom: TSQLRoleTypeID;
//目标角色类型
fRoleTypeTo: TSQLRoleTypeID;
//协议类型
fAgreementType: TSQLAgreementTypeID;
//协议日期
fAgreementDate: TDateTime;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
//说明
fDescription: RawUTF8;
//协议内容
fTextData: RawUTF8;
published
property Product: TSQLProductID read fProduct write fProduct;
property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
property RoleTypeFrom: TSQLRoleTypeID read fRoleTypeFrom write fRoleTypeFrom;
property RoleTypeTo: TSQLRoleTypeID read fRoleTypeTo write fRoleTypeTo;
property AgreementType: TSQLAgreementTypeID read fAgreementType write fAgreementType;
property AgreementDate: TDateTime read fAgreementDate write fAgreementDate;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime Read fThruDate write fThruDate;
property Description: RawUTF8 Read fDescription write fDescription;
property TextData: RawUTF8 Read fTextData write fTextData;
end;
// 3 协议属性
TSQLAgreementAttribute = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//属性名
fAttrName: TSQLAgreementTypeAttrID;
//属性值
fAttrValue: RawUTF8;
//说明
fAttrDescription: RawUTF8;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AttrName: TSQLAgreementTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 4 协议地理应用
TSQLAgreementGeographicalApplic = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项
fAgreementItem: TSQLAgreementItemID;
//地理
fGeo: TSQLGeoID;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItem: TSQLAgreementItemID read fAgreementItem write fAgreementItem;
property Geo: TSQLGeoID read fGeo write fGeo;
end;
// 5 协议项
TSQLAgreementItem = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项类型
fAgreementItemType: TSQLAgreementItemTypeID;
//币种
fCurrencyUom: TSQLUomID;
//协议项序号
fAgreementItemSeq: Integer;
//协议文本
fAgreementText: RawUTF8;
//协议影像
fAgreementImage: TSQLRawBlob;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemType: TSQLAgreementItemTypeID read fAgreementItemType write fAgreementItemType;
property CurrencyUom: TSQLUomID read fCurrencyUom write fCurrencyUom;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property AgreementText: RawUTF8 read fAgreementText write fAgreementText;
property AgreementImage: TSQLRawBlob read fAgreementImage write fAgreementImage;
end;
// 6 协议项属性
TSQLAgreementItemAttribute = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//属性名
fAttrName: TSQLAgreementItemTypeAttrID;
//属性值
fAttrValue: RawUTF8;
//说明
fAttrDescription: RawUTF8;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property AttrName: TSQLAgreementItemTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 7 协议项类型
TSQLAgreementItemType = class(TSQLRecord)
private
fParent: TSQLAgreementItemTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLAgreementItemTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 8 协议项类型属性
TSQLAgreementItemTypeAttr = class(TSQLRecord)
private
//协议项类型
fAgreementItemType: TSQLAgreementItemTypeID;
//属性名
fAttrName: TSQLAgreementItemAttributeID;
//说明
FDescription: RawUTF8;
published
property AgreementItemType: TSQLAgreementItemTypeID read fAgreementItemType write fAgreementItemType;
property AttrName: TSQLAgreementItemAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 9 协议内容
TSQLAgreementContent = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//协议内容类型
fAgreementContentType: TSQLAgreementContentTypeID;
//内容
fContent: TSQLContentID;
//起始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property AgreementContentType: TSQLAgreementContentTypeID read fAgreementContentType write fAgreementContentType;
property Content: TSQLContentID read fContent write fContent;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 10 协议内容类型
TSQLAgreementContentType = class(TSQLRecord)
private
fParent: TSQLAgreementContentTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLAgreementContentTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 11 协议当事人应用
TSQLAgreementPartyApplic = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//当事人
fParty: TSQLPartyID;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property Party: TSQLPartyID read fParty write fParty;
end;
// 12 协议产品应用
TSQLAgreementProductAppl = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//产品
fProduct: TSQLProductID;
//价格
fPrice: Currency;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property Product: TSQLProductID read fProduct write fProduct;
property Price: Currency read fPrice write fPrice;
end;
// 13 协议促销应用
TSQLAgreementPromoAppl = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//产品促销
fProductPromo: TSQLProductPromoID;
//起始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
//序号
fSequenceNum: Integer;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property ProductPromo: TSQLProductPromoID read fProductPromo write fProductPromo;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
end;
// 14 协议设施应用
TSQLAgreementFacilityAppl = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//设施
fFacility: TSQLFacilityID;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property Facility: TSQLFacilityID read fFacility write fFacility;
end;
// 15 协议角色
TSQLAgreementRole = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//当事人
fParty: TSQLPartyID;
//角色类型
fRoleType: TSQLRoleTypeID;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
end;
// 16 协议条款
TSQLAgreementTerm = class(TSQLRecord)
private
//条款类型
fTermType: TSQLTermTypeID;
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//发票项类型
fInvoiceItemType: TSQLInvoiceItemTypeID;
//起始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
//条款值
fTermValue: Currency;
//条款天数
fTermDays: Integer;
//条款内容
fTextValue: RawUTF8;
//最小数量
fMinQuantity: Double;
//最大数量
fMaxQuantity: Double;
//描述
fDescription: RawUTF8;
published
property TermType: TSQLTermTypeID read fTermType write fTermType;
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property InvoiceItemType: TSQLInvoiceItemTypeID read fInvoiceItemType write fInvoiceItemType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property TermValue: Currency read fTermValue write fTermValue;
property TermDays: Integer read fTermDays write fTermDays;
property TextValue: RawUTF8 read fTextValue write fTextValue;
property MinQuantity: Double read fMinQuantity write fMinQuantity;
property MaxQuantity: Double read fMaxQuantity write fMaxQuantity;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 17 协议条款属性
TSQLAgreementTermAttribute = class(TSQLRecord)
private
//条款
fAgreementTerm: TSQLAgreementTermID;
//属性名
fAttrName: RawUTF8;
//属性值
fAttrValue: RawUTF8;
published
property AgreementTerm: TSQLAgreementTermID read fAgreementTerm write fAgreementTerm;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
end;
// 18 协议类型
TSQLAgreementType = class(TSQLRecord)
private
fParent: TSQLAgreementTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
published
property Parent: TSQLAgreementTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 19 协议类型属性
TSQLAgreementTypeAttr = class(TSQLRecord)
private
fAgreementType: TSQLAgreementTypeID;
fAttrName: TSQLAgreementAttributeID;
fDescription: RawUTF8;
published
property AgreementType: TSQLAgreementTypeID read fAgreementType write fAgreementType;
property AttrName: TSQLAgreementAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 20 协议工作计划应用
TSQLAgreementWorkEffortApplic = class(TSQLRecord)
private
//协议
fAgreement: TSQLAgreementID;
//协议项序号
fAgreementItemSeq: Integer;
//工作计划
fWorkEffort: TSQLWorkEffortID;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property WorkEffort: TSQLWorkEffortID read fWorkEffort write fWorkEffort;
end;
// 21 条款类型
TSQLTermType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLTermTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLTermTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 22 条款类型属性
TSQLTermTypeAttr = class(TSQLRecord)
private
fTermType: TSQLTermTypeID;
fAttrName: Integer;
fDescription: RawUTF8;
published
property TermType: TSQLTermTypeID read fTermType write fTermType;
property AttrName: Integer read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 23 协议雇佣应用
TSQLAgreementEmploymentAppl = class(TSQLRecord)
private
fAgreement: TSQLAgreementID;
fAgreementItemSeq: Integer;
fPartyFrom: TSQLPartyID;
fPartyTo: TSQLPartyID;
fRoleTypeFrom: TSQLRoleTypeID;
fRoleTypeTo: TSQLRoleTypeID;
fAgreementDate: TDateTime;
fFromDate: TDateTime;
fThruDate: TDateTime;
published
property Agreement: TSQLAgreementID read fAgreement write fAgreement;
property AgreementItemSeq: Integer read fAgreementItemSeq write fAgreementItemSeq;
property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
property RoleTypeFrom: TSQLRoleTypeID read fRoleTypeFrom write fRoleTypeFrom;
property RoleTypeTo: TSQLRoleTypeID read fRoleTypeTo write fRoleTypeTo;
property AgreementDate: TDateTime read fAgreementDate write fAgreementDate;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 24
TSQLCommContentAssocType = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 25
TSQLCommEventContentAssoc = class(TSQLRecord)
private
fContent: TSQLContentID;
fCommunicationEvent: TSQLCommunicationEventID;
fCommContentAssocType: TSQLCommContentAssocTypeID;
fFromDate: TDateTime;
fThruDate: TDateTime;
fSequenceNum: Integer;
published
property Content: TSQLContentID read fContent write fContent;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
property CommContentAssocType: TSQLCommContentAssocTypeID read fCommContentAssocType write fCommContentAssocType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
end;
// 26
TSQLCommunicationEvent = class(TSQLRecord)
private
fCommunicationEventType: TSQLCommunicationEventTypeID;
fOrigCommEvent: Integer;
fParentCommEvent: Integer;
fStatusItem: TSQLStatusItemID;
fContactMechType: TSQLContactMechTypeID;
fContactMechFrom: TSQLContactMechID;
fContactMechTo: TSQLContactMechID;
fRoleTypeFrom: TSQLRoleTypeID;
fRoleTypeTo: TSQLRoleTypeID;
fPartyFrom: TSQLPartyID;
fPartyTo: TSQLPartyID;
fEntryDate: TDateTime;
fDatetimeStarted: TDateTime;
fDatetimeEnded: TDateTime;
fSubject: RawUTF8;
fContentMimeType: TSQLMimeTypeID;
fContent: RawUTF8;
fNote: RawUTF8;
fReasonEnum: TSQLEnumerationID;
fContactList: TSQLContactListID;
fHeaderString: RawUTF8;
fFromString: RawUTF8;
fToString: RawUTF8;
fCCString: RawUTF8;
fBCCString: RawUTF8;
fMessage: RawUTF8;
published
property CommunicationEventType: TSQLCommunicationEventTypeID read fCommunicationEventType write fCommunicationEventType;
property OrigCommEvent: Integer read fOrigCommEvent write fOrigCommEvent;
property ParentCommEvent: Integer read fParentCommEvent write fParentCommEvent;
property StatusItem: TSQLStatusItemID read fStatusItem write fStatusItem;
property ContactMechType: TSQLContactMechTypeID read fContactMechType write fContactMechType;
property ContactMechFrom: TSQLContactMechID read fContactMechFrom write fContactMechFrom;
property ContactMechTo: TSQLContactMechID read fContactMechTo write fContactMechTo;
property RoleTypeFrom: TSQLRoleTypeID read fRoleTypeFrom write fRoleTypeFrom;
property RoleTypeTo: TSQLRoleTypeID read fRoleTypeTo write fRoleTypeTo;
property RPartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
property EntryDate: TDateTime read fEntryDate write fEntryDate;
property DatetimeStarted: TDateTime read fDatetimeStarted write fDatetimeStarted;
property DatetimeEnded: TDateTime read fDatetimeEnded write fDatetimeEnded;
property Subject: RawUTF8 read fSubject write fSubject;
property ContentMimeType: TSQLMimeTypeID read fContentMimeType write fContentMimeType;
property Content: RawUTF8 read fContent write fContent;
property Note: RawUTF8 read fNote write fNote;
property ReasonEnum: TSQLEnumerationID read fReasonEnum write fReasonEnum;
property ContactList: TSQLContactListID read fContactList write fContactList;
property HeaderString: RawUTF8 read fHeaderString write fHeaderString;
property FromString: RawUTF8 read fContent write fContent;
property ToString: RawUTF8 read fFromString write fFromString;
property CCString: RawUTF8 read fCCString write fCCString;
property BCCString: RawUTF8 read fBCCString write fBCCString;
property Message: RawUTF8 read fMessage write fMessage;
end;
// 27
TSQLCommunicationEventProduct = class(TSQLRecord)
private
fProduct: TSQLProductID;
fCommunicationEvent: TSQLCommunicationEventID;
published
property Product: TSQLProductID read fProduct write fProduct;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
end;
// 28
TSQLCommunicationEventPrpTyp = class(TSQLRecord)
private
fParent: TSQLCommunicationEventPrpTypID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Parent: TSQLCommunicationEventPrpTypID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 29
TSQLCommunicationEventPurpose = class(TSQLRecord)
private
fCommunicationEventPrpTyp: TSQLCommunicationEventPrpTypID;
fCommunicationEvent: TSQLCommunicationEventID;
fDescription: RawUTF8;
published
property CommunicationEventPrpTyp: TSQLCommunicationEventPrpTypID read fCommunicationEventPrpTyp write fCommunicationEventPrpTyp;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 30
TSQLCommunicationEventRole = class(TSQLRecord)
private
fCommunicationEvent: TSQLCommunicationEventID;
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fContactMech: TSQLContactMechID;
fStatusItem: TSQLStatusItemID;
published
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property StatusItem: TSQLStatusItemID read fStatusItem write fStatusItem;
end;
// 31
TSQLCommunicationEventType = class(TSQLRecord)
private
fParent: TSQLCommunicationEventPrpTypID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
fContactMechType: TSQLContactMechTypeID;
fContactMechTypeEncode: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Parent: TSQLCommunicationEventPrpTypID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
property ContactMechType: TSQLContactMechTypeID read fContactMechType write fContactMechType;
property ContactMechTypeEncode: RawUTF8 read fContactMechTypeEncode write fContactMechTypeEncode;
end;
// 32 联系机制
TSQLContactMech = class(TSQLRecord)
private
fContactMechType: TSQLContactMechTypeID;
fInfoString: RawUTF8;
published
property ContactMechType: TSQLContactMechTypeID read fContactMechType write fContactMechType;
property InfoString: RawUTF8 read fInfoString write fInfoString;
end;
// 33 联系机制属性
TSQLContactMechAttribute = class(TSQLRecord)
private
fContactMech: TSQLContactMechID;
fAttrName: TSQLContactMechTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property AttrName: TSQLContactMechTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 34 联系机制链
TSQLContactMechLink = class(TSQLRecord)
private
fContactMechFrom: TSQLContactMechID;
fContactMechTo: TSQLContactMechID;
published
property ContactMechFrom: TSQLContactMechID read fContactMechFrom write fContactMechFrom;
property ContactMechTo: TSQLContactMechID read fContactMechTo write fContactMechTo;
end;
// 35 联系机制用途类型
TSQLContactMechPurposeType = class(TSQLRecord)
private
fEncode: RawUTF8;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 36 联系机制类型
TSQLContactMechType = class(TSQLRecord)
private
fParent: TSQLContactMechTypeID;
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Parent: TSQLContactMechTypeID read fParent write fParent;
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 37 联系机制类型属性
TSQLContactMechTypeAttr = class(TSQLRecord)
private
fContactMechType: TSQLContactMechTypeID;
fAttrName: TSQLContactMechAttributeID;
fDescription: RawUTF8;
published
property ContactMechType: TSQLContactMechTypeID read fContactMechType write fContactMechType;
property AttrName: TSQLContactMechAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 38 联系机制类型用途
TSQLContactMechTypePurpose = class(TSQLRecord)
private
fContactMechType: TSQLContactMechTypeID;
fContactMechPurposeType: TSQLContactMechPurposeTypeID;
fContactMechTypeEncode: RawUTF8;
fContactMechPurposeTypeEncode: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property ContactMechType: TSQLContactMechTypeID read fContactMechType write fContactMechType;
property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType;
property ContactMechTypeEncode: RawUTF8 read fContactMechTypeEncode write fContactMechTypeEncode;
property ContactMechPurposeTypeEncode: RawUTF8 read fContactMechPurposeTypeEncode write fContactMechPurposeTypeEncode;
end;
// 39 电子邮件地址校验
TSQLEmailAddressVerification = class(TSQLRecord)
private
fEmailAddress: RawUTF8;
fVerifyHash: RawUTF8;
fExpireDate: TDateTime;
published
property EmailAddress: RawUTF8 read fEmailAddress write fEmailAddress;
property VerifyHash: RawUTF8 read fVerifyHash write fVerifyHash;
property ExpireDate: TDateTime read fExpireDate write fExpireDate;
end;
// 40 当事人联系机制
TSQLPartyContactMech = class(TSQLRecord)
private
//当事人
fParty: TSQLPartyID;
//联系机制
fContactMech: TSQLContactMechID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
//角色类型
fRoleType: TSQLPartyRoleID;
//同意请求
fAllowSolicitation: Boolean;
//补充
fExtension: RawUTF8;
//已验证
fVerified: Boolean;
//备注
fComments: RawUTF8;
//联系方式的年数
fYearsWithContactMech: Integer;
//联系方式的月数
fMonthsWithContactMech: Integer;
published
property Party: TSQLPartyID read fParty write fParty;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property RoleType: TSQLPartyRoleID read fRoleType write fRoleType;
property AllowSolicitation: Boolean read fAllowSolicitation write fAllowSolicitation;
property Extension: RawUTF8 read fExtension write fExtension;
property Verified: Boolean read fVerified write fVerified;
property Comments: RawUTF8 read fComments write fComments;
property YearsWithContactMech: Integer read fYearsWithContactMech write fYearsWithContactMech;
property MonthsWithContactMech: Integer read fMonthsWithContactMech write fMonthsWithContactMech;
end;
// 41 当事人联系机制用途
TSQLPartyContactMechPurpose = class(TSQLRecord)
private
fParty: TSQLPartyID;
fContactMech: TSQLContactMechID;
fContactMechPurposeType: TSQLContactMechPurposeTypeID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property ContactMechPurposeType: TSQLContactMechPurposeTypeID read fContactMechPurposeType write fContactMechPurposeType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 42 邮政地址表
TSQLPostalAddress = class(TSQLRecord)
private
///联系机制
fContactMech: TSQLContactMechID;
//目标名称
fToName: RawUTF8;
//附加名称
fAttnName: RawUTF8;
fAddress1: RawUTF8;
fAddress2: RawUTF8;
//门牌号
fHouseNumber: Integer;
fHouseNumberExt: RawUTF8;
fDirections: RawUTF8;
fCity: RawUTF8;
fCityGeo: TSQLGeoID;
fPostalCode: RawUTF8;
fPostalCodeExt: RawUTF8;
fCountryGeo: TSQLGeoID;
fStateProvinceGeo: TSQLGeoID;
fCountyGeo: TSQLGeoID;
fMunicipalityGeo: TSQLGeoID;
fPostalCodeGeo: TSQLGeoID;
fGeoPoint: TSQLGeoPointID;
published
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property ToName: RawUTF8 read fToName write fToName;
property AttnName: RawUTF8 read fAttnName write fAttnName;
property Address1: RawUTF8 read fAddress1 write fAddress1;
property Address2: RawUTF8 read fAddress2 write fAddress2;
property HouseNumber: Integer read fHouseNumber write fHouseNumber;
property HouseNumberExt: RawUTF8 read fHouseNumberExt write fHouseNumberExt;
property Directions: RawUTF8 read fDirections write fDirections;
property City: RawUTF8 read fCity write fCity;
property CityGeo: TSQLGeoID read fCityGeo write fCityGeo;
property PostalCode: RawUTF8 read fPostalCode write fPostalCode;
property PostalCodeExt: RawUTF8 read fPostalCodeExt write fPostalCodeExt;
property CountryGeo: TSQLGeoID read fCountryGeo write fCountryGeo;
property StateProvinceGeo: TSQLGeoID read fStateProvinceGeo write fStateProvinceGeo;
property CountyGeo: TSQLGeoID read fCountyGeo write fCountyGeo;
property MunicipalityGeo: TSQLGeoID read fMunicipalityGeo write fMunicipalityGeo;
property PostalCodeGeo: TSQLGeoID read fPostalCodeGeo write fPostalCodeGeo;
property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint;
end;
// 43 邮政地址范围
TSQLPostalAddressBoundary = class(TSQLRecord)
private
fContactMech: TSQLPostalAddressID;
fGeo: TSQLGeoID;
published
property ContactMech: TSQLPostalAddressID read fContactMech write fContactMech;
property Geo: TSQLGeoID read fGeo write fGeo;
end;
// 44
TSQLTelecomNumber = class(TSQLRecord)
private
fContactMech: TSQLContactMechID;
fCountryCode: RawUTF8;
fAreaCode: RawUTF8;
fContactNumber: RawUTF8;
//问候名称
fAskForName: RawUTF8;
published
property ContactMech: TSQLContactMechID read fContactMech write fContactMech;
property CountryCode: RawUTF8 read fCountryCode write fCountryCode;
property AreaCode: RawUTF8 read fAreaCode write fAreaCode;
property ContactNumber: RawUTF8 read fContactNumber write fContactNumber;
property AskForName: RawUTF8 read fAskForName write fAskForName;
end;
// 45 有效联系机制角色
TSQLValidContactMechRole = class(TSQLRecord)
private
fRoleType: TSQLRoleTypeID;
fContactMechType: TSQLContactMechTypeID;
published
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property ContactMechType: TSQLContactMechTypeID read fContactMechType write fContactMechType;
end;
// 46
TSQLNeedType = class(TSQLRecord)
private
fName: RawUTF8;
fDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 47
TSQLPartyNeed = class(TSQLRecord)
private
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
fPartyType: TSQLPartyTypeID;
fNeedType: TSQLNeedTypeID;
fCommunicationEvent: TSQLCommunicationEventID;
fProduct: TSQLProductID;
fProductCategory: TSQLProductCategoryID;
fVisit: Integer;
fDatetimeRecorded: TDateTime;
fDescription: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property PartyType: TSQLPartyTypeID read fPartyType write fPartyType;
property NeedType: TSQLNeedTypeID read fNeedType write fNeedType;
property CommunicationEvent: TSQLCommunicationEventID read fCommunicationEvent write fCommunicationEvent;
property Product: TSQLProductID read fProduct write fProduct;
property ProductCategory: TSQLProductCategoryID read fProductCategory write fProductCategory;
property Visit: Integer read fVisit write fVisit;
property DatetimeRecorded: TDateTime read fDatetimeRecorded write fDatetimeRecorded;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 48 地址匹配映射
TSQLAddressMatchMap = class(TSQLRecord)
private
//映射键
fMapKey: RawUTF8;
//映射值
fMapValue: RawUTF8;
//序号数字
fSequenceNum: Integer;
published
property MapKey: RawUTF8 read fMapKey write fMapKey;
property MapValue: RawUTF8 read fMapValue write fMapValue;
property SequenceNum: Integer read fSequenceNum write fSequenceNum;
end;
// 49 联盟
TSQLAffiliate = class(TSQLRecord)
private
fParty: TSQLPartyID;
//联盟名称
fAffiliateName: RawUTF8;
//联盟描述
fAffiliateDescription: RawUTF8;
//创建的年份
fYearEstablished: Integer;
//站点类型
fSiteType: RawUTF8;
//站点页面显示
fSitePageViews: RawUTF8;
//站点访问者
fSiteVisitors: RawUTF8;
fDateTimeCreated: TDateTime;
//批准日期时间
fDateTimeApproved: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property AffiliateName: RawUTF8 read fAffiliateName write fAffiliateName;
property AffiliateDescription: RawUTF8 read fAffiliateDescription write fAffiliateDescription;
property YearEstablished: Integer read fYearEstablished write fYearEstablished;
property SiteType: RawUTF8 read fSiteType write fSiteType;
property SitePageViews: RawUTF8 read fSitePageViews write fSitePageViews;
property SiteVisitors: RawUTF8 read fSiteVisitors write fSiteVisitors;
property DateTimeCreated: TDateTime read fDateTimeCreated write fDateTimeCreated;
property DateTimeApproved: TDateTime read fDateTimeApproved write fDateTimeApproved;
end;
// 50 当事人
TSQLParty = class(TSQLRecord)
private
//当事人类型
fPartyType: TSQLPartyTypeID;
//外部标识
fExternal: Integer;
//优先使用币种
fPreferredCurrencyUom: TSQLUomID;
fDescription: RawUTF8;
fStatus: TSQLStatusItemID;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
//数据源
fDataSource: TSQLDataSourceID;
//是否没有人看的
fIsUnread: Boolean;
published
property PartyType: TSQLPartyTypeID read fPartyType write fPartyType;
property External: Integer read fExternal write fExternal;
property PreferredCurrencyUom: TSQLUomID read fPreferredCurrencyUom write fPreferredCurrencyUom;
property Description: RawUTF8 read fDescription write fDescription;
property Status: TSQLStatusItemID read fStatus write fStatus;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
property DataSource: TSQLDataSourceID read fDataSource write fDataSource;
property IsUnread: Boolean read fIsUnread write fIsUnread;
end;
// 51
TSQLPartyIdentification = class(TSQLRecord)
private
fParty: TSQLPartyID;
fPartyIdentificationType: TSQLPartyIdentificationTypeID;
fIdValue: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property PartyIdentificationType: TSQLPartyIdentificationTypeID read fPartyIdentificationType write fPartyIdentificationType;
property IdValue: RawUTF8 read fIdValue write fIdValue;
end;
// 52
TSQLPartyIdentificationType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLPartyIdentificationTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLPartyIdentificationTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 53 当事人地理位置
TSQLPartyGeoPoint = class(TSQLRecord)
private
fParty: TSQLPartyID;
fGeoPoint: TSQLGeoPointID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property GeoPoint: TSQLGeoPointID read fGeoPoint write fGeoPoint;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 54 当事人属性
TSQLPartyAttribute = class(TSQLRecord)
private
fParty: TSQLPartyID;
fAttrName: TSQLPartyTypeAttrID;
fAttrValue: RawUTF8;
fAttrDescription: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property AttrName: TSQLPartyTypeAttrID read fAttrName write fAttrName;
property AttrValue: RawUTF8 read fAttrValue write fAttrValue;
property AttrDescription: RawUTF8 read fAttrDescription write fAttrDescription;
end;
// 55 当事人承运账户
TSQLPartyCarrierAccount = class(TSQLRecord)
private
fParty: TSQLPartyID;
//送货人员
fCarrierParty: TSQLPartyID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
//客户或用户的账号,有时也作为承运人编号
fAccountNumber: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property CarrierParty: TSQLPartyID read fCarrierParty write fCarrierParty;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property AccountNumber: RawUTF8 read fAccountNumber write fAccountNumber;
end;
// 56 当事人分类
TSQLPartyClassification = class(TSQLRecord)
private
fParty: TSQLPartyID;
fPartyClassificationGroup: TSQLPartyClassificationGroupID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property PartyClassificationGroup: TSQLPartyClassificationGroupID read fPartyClassificationGroup write fPartyClassificationGroup;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 57 当事人分组
TSQLPartyClassificationGroup = class(TSQLRecord)
private
fPartyClassificationType: TSQLPartyClassificationTypeID;
fParentGroup: TSQLPartyClassificationGroupID;
fDescription: RawUTF8;
published
property PartyClassificationType: TSQLPartyClassificationTypeID read fPartyClassificationType write fPartyClassificationType;
property ParentGroup: TSQLPartyClassificationGroupID read fParentGroup write fParentGroup;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 58 当事人分类类型
TSQLPartyClassificationType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParent: TSQLPartyClassificationTypeID;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property Parent: TSQLPartyClassificationTypeID read fParent write fParent;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 59 当事人内容
TSQLPartyContent = class(TSQLRecord)
private
fParty: TSQLPartyID;
fContent: TSQLContentID;
fPartyContentType: TSQLPartyContentTypeID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property Content: TSQLContentID read fContent write fContent;
property PartyContentType: TSQLPartyContentTypeID read fPartyContentType write fPartyContentType;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
end;
// 60 当事人内容类型
TSQLPartyContentType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParent: TSQLPartyContentTypeID;
fParentEncode: RawUTF8;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Parent: TSQLPartyContentTypeID read fParent write fParent;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 61 当事人数据源
TSQLPartyDataSource = class(TSQLRecord)
private
fParty: TSQLPartyID;
fDataSource: TSQLDataSourceID;
fFromDate: TDateTime;
//访问标识
fVisit: RawUTF8;
fComments: RawUTF8;
//是否创建
fIsCreate: Boolean;
published
property Party: TSQLPartyID read fParty write fParty;
property DataSource: TSQLDataSourceID read fDataSource write fDataSource;
property FromDate: TDateTime read fFromDate write fFromDate;
property Visit: RawUTF8 read fVisit write fVisit;
property Comments: RawUTF8 read fcomments write fcomments;
property IsCreate: Boolean read fIsCreate write fIsCreate;
end;
// 62 组织
TSQLPartyGroup = class(TSQLRecord)
private
fParty: TSQLPartyID;
fGroupName: RawUTF8;
//组织名称本地语言
fGroupNameLocal: RawUTF8;
//办公地点
fOfficeSiteName: RawUTF8;
//年收入
fAnnualRevenue: Currency;
fNumEmployees: Integer;
//股票代码
fTickerSymbol: RawUTF8;
fComments: RawUTF8;
fLogoImageUrl: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property GroupName: RawUTF8 read fGroupName write fGroupName;
property GroupNameLocal: RawUTF8 read fGroupNameLocal write fGroupNameLocal;
property OfficeSiteName: RawUTF8 read fOfficeSiteName write fOfficeSiteName;
property AnnualRevenue: Currency read fAnnualRevenue write fAnnualRevenue;
property NumEmployees: Integer read fNumEmployees write fNumEmployees;
property TickerSymbol: RawUTF8 read fTickerSymbol write fTickerSymbol;
property Comments: RawUTF8 read fComments write fComments;
property LogoImageUrl: RawUTF8 read fLogoImageUrl write fLogoImageUrl;
end;
// 63 当事人地址验证服务
TSQLPartyIcsAvsOverride = class(TSQLRecord)
private
fParty: TSQLPartyID;
//地址验证服务字符串
fAvsDeclineString: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property AvsDeclineString: RawUTF8 read fAvsDeclineString write fAvsDeclineString;
end;
// 64 当事人邀请
TSQLPartyInvitation = class(TSQLRecord)
private
fParty: TSQLPartyID;
fPartyFrom: TSQLPartyID;
fToName: RawUTF8;
fEmailAddress: RawUTF8;
fStatus: TSQLStatusItemID;
//最后邀请日期
fLastInviteDate: TDateTime;
published
property Party: TSQLPartyID read fParty write fParty;
property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property ToName: RawUTF8 read fToName write fToName;
property EmailAddress: RawUTF8 read fEmailAddress write fEmailAddress;
property Status: TSQLStatusItemID read fStatus write fStatus;
property LastInviteDate: TDateTime read fLastInviteDate write fLastInviteDate;
end;
// 65 当事人邀请组关联
TSQLPartyInvitationGroupAssoc = class(TSQLRecord)
private
fPartyInvitation: TSQLPartyInvitationID;
//目标当事人
fPartyTo: TSQLPartyID;
published
property PartyInvitation: TSQLPartyInvitationID read fPartyInvitation write fPartyInvitation;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
end;
// 66 当事人邀请角色关联
TSQLPartyInvitationRoleAssoc = class(TSQLRecord)
private
fPartyInvitation: TSQLPartyInvitationID;
//角色类型
fRoleType: TSQLRoleTypeID;
published
property PartyInvitation: TSQLPartyInvitationID read fPartyInvitation write fPartyInvitation;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
end;
// 67 当事人名称历史
TSQLPartyNameHistory = class(TSQLRecord)
private
fParty: TSQLPartyID;
fChangeDate: TDateTime;
fGroupName: RawUTF8;
fFirstName: RawUTF8;
fMiddleName: RawUTF8;
fLastName: RawUTF8;
fPersonalTitle: RawUTF8;
fSuffix: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property ChangeDate: TDateTime read fChangeDate write fChangeDate;
property GroupName: RawUTF8 read fGroupName write fGroupName;
property FirstName: RawUTF8 read fFirstName write fFirstName;
property MiddleName: RawUTF8 read fMiddleName write fMiddleName;
property LastName: RawUTF8 read fLastName write fLastName;
property PersonalTitle: RawUTF8 read fPersonalTitle write fPersonalTitle;
property Suffix: RawUTF8 read fSuffix write fSuffix;
end;
// 68 当事人注释
TSQLPartyNote = class(TSQLRecord)
private
fParty: TSQLPartyID;
fNote: TSQLNoteDataID;
published
property Party: TSQLPartyID read fParty write fParty;
property Note: TSQLNoteDataID read fNote write fNote;
end;
// 69 当事人默认概况表
TSQLPartyProfileDefault = class(TSQLRecord)
private
fParty: TSQLPartyID;
//产品店铺
fProductStore: TSQLProductStoreID;
//缺省送货地址
fDefaultShipAddr: RawUTF8;
//缺省账单地址
fDefaultBillAddr: RawUTF8;
//缺省支付方式
fDefaultPayMeth: RawUTF8;
//缺省送货方式
fDefaultShipMeth: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property ProductStore: TSQLProductStoreID read fProductStore write fProductStore;
property DefaultShipAddr: RawUTF8 read fDefaultShipAddr write fDefaultShipAddr;
property DefaultBillAddr: RawUTF8 read fDefaultBillAddr write fDefaultBillAddr;
property DefaultPayMeth: RawUTF8 read fDefaultPayMeth write fDefaultPayMeth;
property DefaultShipMeth: RawUTF8 read fDefaultShipMeth write fDefaultShipMeth;
end;
// 70 当事人关系
TSQLPartyRelationship = class(TSQLRecord)
private
fPartyFrom: TSQLPartyID;
fPartyTo: TSQLPartyID;
fRoleTypeFrom: TSQLRoleTypeID;
fRoleTypeTo: TSQLRoleTypeID;
//开始日期
fFromDate: TDateTime;
//结束日期
fThruDate: TDateTime;
fStatus: TSQLStatusItemID;
//当事人关系名称
fRelationshipName: RawUTF8;
//安全组
fSecurityGroup: TSQLSecurityGroupID;
//优先类型
fPriorityType: TSQLPriorityTypeID;
fPartyRelationshipType: TSQLPartyRelationshipTypeID;
//权限枚举
fPermissionsEnum: RawUTF8;
//职位头衔
fPositionTitle: RawUTF8;
fComments: RawUTF8;
published
property PartyFrom: TSQLPartyID read fPartyFrom write fPartyFrom;
property PartyTo: TSQLPartyID read fPartyTo write fPartyTo;
property RoleTypeFrom: TSQLRoleTypeID read fRoleTypeFrom write fRoleTypeFrom;
property RoleTypeTo: TSQLRoleTypeID read fRoleTypeTo write fRoleTypeTo;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property Status: TSQLStatusItemID read fStatus write fStatus;
property RelationshipName: RawUTF8 read fRelationshipName write fRelationshipName;
property SecurityGroup: TSQLSecurityGroupID read fSecurityGroup write fSecurityGroup;
property PriorityType: TSQLPriorityTypeID read fPriorityType write fPriorityType;
property PartyRelationshipType: TSQLPartyRelationshipTypeID read fPartyRelationshipType write fPartyRelationshipType;
property PermissionsEnum: RawUTF8 read fPermissionsEnum write fPermissionsEnum;
property PositionTitle: RawUTF8 read fPositionTitle write fPositionTitle;
property Comments: RawUTF8 read fComments write fComments;
end;
// 71 当事人关系类型
TSQLPartyRelationshipType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fParentType: TSQLPartyRelationshipTypeID;
fHasTable: Boolean;
fName: RawUTF8;
fDescription: RawUTF8;
fRoleTypeFromEncode: RawUTF8;
fRoleTypeToEncode: RawUTF8;
fRoleTypeValidFrom: TSQLRoleTypeID;
fRoleTypeValidTo: TSQLRoleTypeID;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property ParentType: TSQLPartyRelationshipTypeID read fParentType write fParentType;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read fDescription write fDescription;
property RoleTypeFromEncode: RawUTF8 read fRoleTypeFromEncode write fRoleTypeFromEncode;
property RoleTypeToEncode: RawUTF8 read fRoleTypeToEncode write fRoleTypeToEncode;
property RoleTypeValidFrom: TSQLRoleTypeID read fRoleTypeValidFrom write fRoleTypeValidFrom;
property RoleTypeValidTo: TSQLRoleTypeID read fRoleTypeValidTo write fRoleTypeValidTo;
end;
// 72 当事人角色
TSQLPartyRole = class(TSQLRecord)
private
fParty: TSQLPartyID;
fRoleType: TSQLRoleTypeID;
published
property Party: TSQLPartyID read fParty write fParty;
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
end;
// 73 当事人状态
TSQLPartyStatus = class(TSQLRecord)
private
fStatus: TSQLStatusItemID;
fParty: TSQLPartyID;
fStatusDate: TDateTime;
fChangeByUserLogin: TSQLUserLoginID;
published
property Status: TSQLStatusItemID read fStatus write fStatus;
property Party: TSQLPartyID read fParty write fParty;
property StatusDate: TDateTime read fStatusDate write fStatusDate;
property ChangeByUserLogin: TSQLUserLoginID read fChangeByUserLogin write fChangeByUserLogin;
end;
// 74 当事人类型
TSQLPartyType = class(TSQLRecord)
private
fParent: TSQLPartyTypeID;
fEncode: RawUTF8;
fParentEncode: RawUTF8;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Parent: TSQLPartyTypeID read fParent write fParent;
property Encode: RawUTF8 read fEncode write fEncode;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 75 当事人类型属性
TSQLPartyTypeAttr = class(TSQLRecord)
private
fPartyType: TSQLPartyTypeID;
fAttrName: RawUTF8;
fDescription: RawUTF8;
published
property PartyType: TSQLPartyTypeID read fPartyType write fPartyType;
property AttrName: RawUTF8 read fAttrName write fAttrName;
property Description: RawUTF8 read fDescription write fDescription;
end;
// 76
TSQLPerson = class(TSQLRecord)
private
fParty: TSQLPartyID;
fSalutation: RawUTF8;
fFirstName: RawUTF8;
fMiddleName: RawUTF8;
fLastName: RawUTF8;
fPersonTitle: RawUTF8;
fSuffix: RawUTF8;
fNickName: RawUTF8;
fFirstNameLocal: RawUTF8;
fMiddleNameLocal: RawUTF8;
fLastNameLocal: RawUTF8;
fOtherLocal: RawUTF8;
fMember: Integer;
//性别
fGender: Boolean;
fBirthDate: TDateTime;
fDeceasedDate: TDateTime;
fHeight: Double;
fWeight: Double;
fMothersMaidenName: RawUTF8;
fMaritalStatus: Boolean;
fSocialSecurityNumber: RawUTF8;
fPassportNumber: RawUTF8;
fPassportExpireDate: TDateTime;
fTotalYearsWorkExperience: Double;
fComments: RawUTF8;
//雇用状态枚举标识
fEmploymentStatusEnum: TSQLEnumerationID;
//居住状态枚举
fResidenceStatusEnum: TSQLEnumerationID;
fOccupation: RawUTF8;
//雇用年数
fYearsWithEmployer: Double;
fMonthsWithEmployer: Double;
fExistingCustomer: Boolean;
fCard: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property Salutation: RawUTF8 read fSalutation write fSalutation;
property FirstName: RawUTF8 read fFirstName write fFirstName;
property MiddleName: RawUTF8 read fMiddleName write fMiddleName;
property LastName: RawUTF8 read fLastName write fLastName;
property PersonTitle: RawUTF8 read fPersonTitle write fPersonTitle;
property Suffix: RawUTF8 read fSuffix write fSuffix;
property NickName: RawUTF8 read fNickName write fNickName;
property FirstNameLocal: RawUTF8 read fFirstNameLocal write fFirstNameLocal;
property MiddleNameLocal: RawUTF8 read fMiddleNameLocal write fMiddleNameLocal;
property LastNameLocal: RawUTF8 read fLastNameLocal write fLastNameLocal;
property OtherLocal: RawUTF8 read fOtherLocal write fOtherLocal;
property Member: Integer read fMember write fMember;
property Gender: Boolean read fGender write fGender;
property BirthDate: TDateTime read fBirthDate write fBirthDate;
property DeceasedDate: TDateTime read fDeceasedDate write fDeceasedDate;
property Height: Double read fHeight write fHeight;
property Weight: Double read fWeight write fWeight;
property MothersMaidenName: RawUTF8 read fMothersMaidenName write fMothersMaidenName;
property MaritalStatus: Boolean read fMaritalStatus write fMaritalStatus;
property SocialSecurityNumber: RawUTF8 read fSocialSecurityNumber write fSocialSecurityNumber;
property PassportNumber: RawUTF8 read fPassportNumber write fPassportNumber;
property PassportExpireDate: TDateTime read fPassportExpireDate write fPassportExpireDate;
property TotalYearsWorkExperience: Double read fTotalYearsWorkExperience write fTotalYearsWorkExperience;
property Comments: RawUTF8 read fComments write fComments;
property EmploymentStatusEnum: TSQLEnumerationID read fEmploymentStatusEnum write fEmploymentStatusEnum;
property ResidenceStatusEnum: TSQLEnumerationID read fResidenceStatusEnum write fResidenceStatusEnum;
property Occupation: RawUTF8 read fOccupation write fOccupation;
property YearsWithEmployer: Double read fYearsWithEmployer write fYearsWithEmployer;
property MonthsWithEmployer: Double read fMonthsWithEmployer write fMonthsWithEmployer;
property ExistingCustomer: Boolean read fExistingCustomer write fExistingCustomer;
property Card: RawUTF8 read fCard write fCard;
end;
// 77 优先类型
TSQLPriorityType = class(TSQLRecord)
private
fName: RawUTF8;
FDescription: RawUTF8;
published
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 78 角色类型
TSQLRoleType = class(TSQLRecord)
private
fEncode: RawUTF8;
fParent: TSQLRoleTypeID;
fParentEncode: RawUTF8;
fHasTable: Boolean;
fName: RawUTF8;
FDescription: RawUTF8;
public
class procedure InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions); override;
published
property Encode: RawUTF8 read fEncode write fEncode;
property Parent: TSQLRoleTypeID read fParent write fParent;
property ParentEncode: RawUTF8 read fParentEncode write fParentEncode;
property HasTable: Boolean read fHasTable write fHasTable;
property Name: RawUTF8 read fName write fName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 79 角色类型属性
TSQLRoleTypeAttr = class(TSQLRecord)
private
fRoleType: TSQLRoleTypeID;
fAttrName: TSQLPartyAttributeID;
FDescription: RawUTF8;
published
property RoleType: TSQLRoleTypeID read fRoleType write fRoleType;
property AttrName: TSQLPartyAttributeID read fAttrName write fAttrName;
property Description: RawUTF8 read FDescription write FDescription;
end;
// 80 供应商
TSQLVendor = class(TSQLRecord)
private
fParty: TSQLPartyID;
///公司名称
fManifestCompanyName: RawUTF8;
//公司称号
fManifestCompanyTitle: RawUTF8;
//LOGO网址
fManifestLogoUrl: RawUTF8;
//政策
fManifestPolicies: RawUTF8;
published
property Party: TSQLPartyID read fParty write fParty;
property ManifestCompanyName: RawUTF8 read fManifestCompanyName write fManifestCompanyName;
property ManifestCompanyTitle: RawUTF8 read fManifestCompanyTitle write fManifestCompanyTitle;
property ManifestLogoUrl: RawUTF8 read fManifestLogoUrl write fManifestLogoUrl;
property ManifestPolicies: RawUTF8 read fManifestPolicies write fManifestPolicies;
end;
implementation
uses
Classes, SysUtils;
// applications\datamodel\data\seed\PartySeedData.xml
// 1
class procedure TSQLContactMechPurposeType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLContactMechPurposeType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLContactMechPurposeType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ContactMechPurposeType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
finally
Rec.Free;
end;
end;
// 2
class procedure TSQLContactMechType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLContactMechType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLContactMechType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ContactMechType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ContactMechType set parent=(select c.id from ContactMechType c where c.Encode=ContactMechType.ParentEncode);');
Server.Execute('update CommunicationEventType set ContactMechType=(select c.id from ContactMechType c where c.Encode=ContactMechTypeEncode);');
finally
Rec.Free;
end;
end;
// 3
class procedure TSQLContactMechTypePurpose.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLContactMechTypePurpose;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLContactMechTypePurpose.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','ContactMechTypePurpose.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update ContactMechTypePurpose set ContactMechType=(select c.id from ContactMechType c where c.Encode=ContactMechTypeEncode);');
Server.Execute('update ContactMechTypePurpose set ContactMechPurposeType=(select c.id from ContactMechPurposeType c where c.Encode=ContactMechPurposeTypeEncode);');
finally
Rec.Free;
end;
end;
// 4
class procedure TSQLCommunicationEventPrpTyp.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLCommunicationEventPrpTyp;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLCommunicationEventPrpTyp.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CommunicationEventPrpTyp.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update CommunicationEventPrpTyp set parent=(select c.id from CommunicationEventPrpTyp c where c.Encode=CommunicationEventPrpTyp.ParentEncode);');
finally
Rec.Free;
end;
end;
// 5
class procedure TSQLCommunicationEventType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLCommunicationEventType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLCommunicationEventType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','CommunicationEventType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update CommunicationEventType set parent=(select c.id from CommunicationEventType c where c.Encode=CommunicationEventType.ParentEncode);');
Server.Execute('update CommunicationEventType set ContactMechType=(select c.id from ContactMechType c where c.Encode=ContactMechTypeEncode);');
finally
Rec.Free;
end;
end;
// 6
class procedure TSQLPartyContentType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPartyContentType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPartyContentType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PartyContentType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PartyContentType set parent=(select c.id from PartyContentType c where c.Encode=PartyContentType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 7
class procedure TSQLRoleType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLRoleType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLRoleType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','RoleType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update RoleType set Parent=(select c.id from RoleType c where c.Encode=RoleType.ParentEncode);');
Server.Execute('update PartyRelationshipType set RoleTypeValidFrom=(select c.id from RoleType c where c.Encode=RoleTypeFromEncode);');
Server.Execute('update PartyRelationshipType set RoleTypeValidTo=(select c.id from RoleType c where c.Encode=RoleTypeToEncode);');
finally
Rec.Free;
end;
end;
// 8
class procedure TSQLPartyClassificationType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPartyClassificationType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPartyClassificationType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PartyClassificationType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PartyClassificationType set Parent=(select c.id from PartyClassificationType c where c.Encode=PartyClassificationType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 9
class procedure TSQLPartyRelationshipType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPartyRelationshipType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPartyRelationshipType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PartyRelationshipType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PartyRelationshipType set parent=(select c.id from PartyRelationshipType c where c.Encode=PartyRelationshipType.ParentEncode);');
Server.Execute('update PartyRelationshipType set RoleTypeValidFrom=(select c.id from RoleType c where c.Encode=RoleTypeFromEncode);');
Server.Execute('update PartyRelationshipType set RoleTypeValidTo=(select c.id from RoleType c where c.Encode=RoleTypeToEncode);');
finally
Rec.Free;
end;
end;
// 10
class procedure TSQLPartyType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPartyType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPartyType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PartyType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PartyType set parent=(select c.id from PartyType c where c.Encode=PartyType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 11
class procedure TSQLTermType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLTermType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLTermType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','TermType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update TermType set parent=(select c.id from TermType c where c.Encode=TermType.ParentEncode);');
finally
Rec.Free;
end;
end;
// 12
class procedure TSQLPartyIdentificationType.InitializeTable(Server: TSQLRestServer; const FieldName: RawUTF8; Options: TSQLInitializeTableOptions);
var Rec: TSQLPartyIdentificationType;
begin
inherited;
if FieldName<>'' then exit; // create database only if void
Rec := TSQLPartyIdentificationType.CreateAndFillPrepare(StringFromFile(ConcatPaths([ExtractFilePath(paramstr(0)),'../seed','PartyIdentificationType.json'])));
try
while Rec.FillOne do
Server.Add(Rec,true);
Server.Execute('update PartyIdentificationType set parent=(select c.id from PartyIdentificationType c where c.Encode=PartyIdentificationType.ParentEncode);');
finally
Rec.Free;
end;
end;
end.
|
////////////////////////////////////////////
// Кодировка и расчет CRC для приборов Логика СПТ-943
////////////////////////////////////////////
unit Devices.Logica.SPT943;
interface
uses Windows, GMGlobals, GMConst, Devices.Logica.SPT941, Devices.Logica.Base;
function LogicaSPT943_CheckCRC(buf: array of Byte; Len: int): bool;
type
TSPT943ReqCreator = class(TSPT941ReqCreator)
protected
function CurrentsRequestType(Chn: int): T485RequestType; override;
function ChannelCount: int; override;
end;
TSPT943AnswerParser = class(TSPT941AnswerParser)
end;
implementation
function LogicaSPT943_CheckCRC(buf: array of Byte; Len: int): bool;
begin
Result := LogicaM4_CheckCRC(buf, len);
end;
{ TSPT943ReqCreator }
function TSPT943ReqCreator.ChannelCount: int;
begin
Result := 3;
end;
function TSPT943ReqCreator.CurrentsRequestType(Chn: int): T485RequestType;
begin
case Chn of
0: Result := rqtSPT943_0;
1: Result := rqtSPT943_1;
2: Result := rqtSPT943_2;
else Result := rqtNone;
end;
end;
end.
|
unit xThreadUDPSendScreen;
interface
uses System.Types,System.Classes, xFunction, system.SysUtils, xUDPServerBase,
xConsts, System.IniFiles, xClientType, Winapi.WinInet, winsock, Graphics,
xThreadBase;
type
TThreadUDPSendScreen = class(TThreadBase)
private
FStream1 : TMemoryStream;
FStream2 : TMemoryStream;
FIsStream1 : Boolean;
/// <summary>
/// 获取要发送的数据流
/// </summary>
function GetStream : TMemoryStream;
procedure ReadINI;
procedure WriteINI;
procedure SetSendSecreen(const Value: TBitmap);
protected
/// <summary>
/// 执行定时命令 (如果定时命令要执行列表需要判断 FIsStop 是佛停止运行,如果挺尸运行需要跳出循环)
/// </summary>
procedure ExecuteTimerOrder; override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 要发送的屏幕图片
/// </summary>
property SendSecreen : TBitmap write SetSendSecreen;
end;
var
UDPSendScreen : TThreadUDPSendScreen;
implementation
{ TTCPServer }
constructor TThreadUDPSendScreen.Create;
begin
inherited;
ProType := ctUDPServer;
ReadINI;
end;
destructor TThreadUDPSendScreen.Destroy;
begin
WriteINI;
inherited;
end;
procedure TThreadUDPSendScreen.ExecuteTimerOrder;
var
AStream : TMemoryStream;
begin
inherited;
AStream := GetStream;
if AStream.Size > 0 then
begin
end;
end;
function TThreadUDPSendScreen.GetStream: TMemoryStream;
begin
if FIsStream1 then
begin
Result := FStream1;
end
else
begin
Result := FStream2;
end;
end;
procedure TThreadUDPSendScreen.ReadINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
TUDPServerBase(FCommBase).ListenPort := ReadInteger('UPDSendScreen', 'ListenPort', 16100);
Free;
end;
end;
procedure TThreadUDPSendScreen.SetSendSecreen(const Value: TBitmap);
begin
if FIsStream1 then
begin
Value.SaveToStream(FStream2);
FIsStream1 := False;
end
else
begin
Value.SaveToStream(FStream1);
FIsStream1 := True;
end;
end;
procedure TThreadUDPSendScreen.WriteINI;
begin
with TIniFile.Create(sPubIniFileName) do
begin
WriteInteger('UPDSendScreen', 'ListenPort', TUDPServerBase(FCommBase).ListenPort);
Free;
end;
end;
end.
|
unit AnalogForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RootForm,
Vcl.ExtCtrls, GridFrame, GridView, GridViewEx, AnalogGridView, cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, Vcl.StdCtrls, cxButtons;
type
TfrmAnalog = class(TfrmRoot)
pnlMain: TPanel;
cxbtnOK: TcxButton;
private
FViewAnalogGrid: TViewAnalogGrid;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
property ViewAnalogGrid: TViewAnalogGrid read FViewAnalogGrid;
{ Public declarations }
end;
implementation
{$R *.dfm}
constructor TfrmAnalog.Create(AOwner: TComponent);
begin
inherited;
FViewAnalogGrid := TViewAnalogGrid.Create(Self);
FViewAnalogGrid.Parent := pnlMain;
FViewAnalogGrid.Align := alClient;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
//GLS
GLScene, GLHUDObjects, GLObjects, GLCadencer,
GLBitmapFont, GLWin32Viewer, GLTeapot, GLCrossPlatform,
GLCoordinates, GLBaseClasses, GLUtils;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
BitmapFont1: TGLBitmapFont;
GLLightSource1: TGLLightSource;
GLCamera1: TGLCamera;
HUDText1: TGLHUDText;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
HUDText2: TGLHUDText;
HUDText3: TGLHUDText;
Teapot1: TGLTeapot;
HUDTextFPS: TGLHUDText;
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure Timer1Timer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
// Load the font bitmap from media dir
SetGLSceneMediaDir();
BitmapFont1.Glyphs.LoadFromFile('darkgold_font.bmp');
// sorry, couldn't resist...
HUDText1.Text:='Hello World !'#13#10#13#10
+'This is me, '#13#10
+'the HUD Text.'#13#10#13#10
+'Bitmap Fonts!';
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
begin
// make things move a little
HUDText2.Rotation:=HUDText2.Rotation+15*deltaTime;
HUDText3.Scale.X:=0.5*sin(newTime)+1;
HUDText3.Scale.Y:=0.5*cos(newTime)+1;
GLSceneViewer1.Invalidate;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
FormatSettings.DecimalSeparator :=',';
HUDTextFPS.Text := FloatToStr(-2.01);
// HUDTextFPS.Text :=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TForm1.GLSceneViewer1Click(Sender: TObject);
begin
Teapot1.Visible:=not Teapot1.Visible;
end;
end.
|
unit PixelUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls;
type
TPixelForm = class(TForm)
Label1: TLabel;
Edit: TEdit;
TrackBar: TTrackBar;
UpDown: TUpDown;
Button1: TButton;
Button2: TButton;
procedure TrackBarChange(Sender: TObject);
procedure EditChange(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
PixelForm: TPixelForm;
implementation
{$R *.dfm}
Uses MainUnit;
procedure PixelsEffect(Bitmap:TBitmap; Hor,Ver:Word);
function Min(A,B:integer):integer;
begin
if A<B then Result:=A
else Result:=B;
end;
type TRGB=record
B,G,R:byte;
end;
pRGB=^TRGB;
var i,j,x,y,xd,yd,rr,gg,bb,h,hx,hy:integer;
Dest:pRGB;
begin
Bitmap.PixelFormat:=pf24bit;
if (Hor=1) and (Ver=1) then Exit;
xd:=(Bitmap.Width-1) div Hor;
yd:=(Bitmap.Height-1) div Ver;
for i:=0 to xd do
for j:=0 to yd do begin
h:=0;
rr:=0;
gg:=0;
bb:=0;
hx:=Min(Hor*(i+1),Bitmap.Width-1);
hy:=Min(Ver*(j+1),Bitmap.Height-1);
for y:=j*Ver to hy do begin
Dest:=Bitmap.ScanLine[y];
Inc(Dest,i*Hor);
for x:=i*Hor to hx do begin
Inc(rr,Dest^.R);
Inc(gg,Dest^.G);
Inc(bb,Dest^.B);
Inc(h);
Inc(Dest);
end;
end;
Bitmap.Canvas.Brush.Color := RGB(rr div h, gg div h, bb div h);
Bitmap.Canvas.FillRect(Rect(i * Hor, j * Ver, hx + 1, hy + 1));
end;
end;
procedure TPixelForm.Button1Click(Sender: TObject);
begin
img.Assign(buffer);
MainForm.Log('Использован эффект: Укрупнение пикселов');
PixelForm.Close;
end;
procedure TPixelForm.Button2Click(Sender: TObject);
begin
buffer.Assign(img);
MainForm.PaintBox.Visible:=false;
MainForm.PaintBox.Visible:=true;
PixelForm.Close;
end;
procedure TPixelForm.EditChange(Sender: TObject);
begin
buffer.Assign(img);
TrackBar.Position:=StrToInt(Edit.Text);
PixelsEffect(buffer,TrackBar.Position,TrackBar.Position);
MainForm.PaintBox.Visible:=false;
MainForm.PaintBox.Visible:=true;
end;
procedure TPixelForm.TrackBarChange(Sender: TObject);
begin
Edit.Text:=IntToStr(TrackBar.Position);
end;
end.
|
unit IWCompRectangle;
interface
uses
Classes, IWHTMLTag,
IWControl, IWTypes, IWGrids;
type
TIWCustomRectangle = class(TIWControl)
private
protected
FAlignment: TAlignment;
FVAlign: TIWGridVAlign;
//
procedure SetAlignment(const Value: TAlignment);
procedure SetVAlign(const Value: TIWGridVAlign);
public
constructor Create(AOwner: TComponent); override;
function RenderHTML: TIWHTMLTag; override;
property Alignment: TAlignment read FAlignment write SetAlignment;
property VAlign: TIWGridVAlign read FVAlign write SetVAlign;
published
property Text;
property Font;
end;
TIWRectangle = class(TIWCustomRectangle)
published
property Color;
property Alignment;
property VAlign;
end;
implementation
uses
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
{$IFDEF Linux}QControls,{$ELSE}Controls,{$ENDIF}
IWServerControllerBase,
SysUtils, SWSystem;
{ TIWCustomRectangle }
constructor TIWCustomRectangle.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Color := clNone;
Width := 200;
Height := 100;
FRenderSize := true;
end;
function TIWCustomRectangle.RenderHTML: TIWHTMLTag;
begin
Result := TIWHTMLTag.CreateTag('TABLE'); try
Result.AddColor('BGCOLOR', Color);
Result.AddIntegerParam('WIDTH', Width);
Result.AddIntegerParam('HEIGHT', Height);
Result.AddIntegerParam('BORDER', 0);
Result.AddIntegerParam('CELLPADDING', 0);
Result.AddIntegerParam('CELLSPACING', 0);
with Result.Contents.AddTag('TR') do begin
// AddIntegerParam('HEIGHT', Height);
with Contents.AddTag('TD') do begin
// AddIntegerParam('HEIGHT', Height);
if Text = '' then
Contents.AddText('') // ')
else begin
AddStringParam('ALIGN', IWGridAlignments[Alignment]);
case FVAlign of
vaMiddle: AddStringParam('VALIGN', 'MIDDLE');
vaTop: AddStringParam('VALIGN', 'top');
vaBottom: AddStringParam('VALIGN', 'bottom');
vaBaseline: AddStringParam('VALIGN', 'basline');
end;
Contents.AddText(Text)
end;
end;
end;
except FreeAndNil(Result); raise; end;
end;
procedure TIWCustomRectangle.SetAlignment(const Value: TAlignment);
begin
FAlignment := Value;
Invalidate;
end;
procedure TIWCustomRectangle.SetVAlign(const Value: TIWGridVAlign);
begin
FVAlign := Value;
Invalidate;
end;
end.
|
unit ImageCommonTypesUnit;
//////////////////////////////////////////////////////////////////
// //
// Description: Types, enumerated or otherwise, useful to Image //
// Conversion functions for stated types //
// //
//////////////////////////////////////////////////////////////////
interface
type
TImageFileType = (ziftBMP, ziftPNG, ziftJPG, ziftGIF, ziftNone);
TImageTypeSet = set of TImageFileType;
function ExtensionToImageFileType(const sExtension: String): TImageFileType;
function StringToImageFileType(const sValue: String): TImageFileType;
function FileNameToImageFileType(const sFileName: String): TImageFileType;
function ImageFileTypeToString(iftValue: TImageFileType): String;
function ImageFileTypeToExtension(iftValue: TImageFileType): String;
implementation
uses
Classes, SysUtils, ResizerConstsUnit;
function ExtensionToImageFileType(const sExtension: String): TImageFileType;
///////////////////////////////////////////////////////
// Preconditions : //
// sExtension is a valid file extension //
// //
// Output : //
// Corresponding image file type based on extension //
// If sExtension isn't recognized, returns ziftNone //
///////////////////////////////////////////////////////
var
iftTemp: TImageFileType;
sLowerExtension: String;
begin
iftTemp := ziftNone;
sLowerExtension := LowerCase(sExtension);
if (CompareText(sLowerExtension, EXTENSION_JPG) = 0)
or (CompareText(sLowerExtension, EXTENSION_JPEG) = 0) then
iftTemp := ziftJPG
else
if CompareText(sLowerExtension, EXTENSION_BMP) = 0 then
iftTemp := ziftBMP;
///////////////////////////
// Not implemented yet : //
///////////////////////////
{
else
if CompareText(sLowerExtension, EXTENSION_GIF) = 0 then
Result := ziftGIF
else
if CompareTExt(sLowerExtension, EXTENSION_PNG) = 0 then
Result := ziftPNG;
}
Result := iftTemp;
end; // ExtensionToImageFileType
function StringToImageFileType(const sValue: String): TImageFileType;
var
iftTemp: TImageFileType;
sUpperValue: String;
begin
iftTemp := ziftNone;
sUpperValue := UpperCase(sValue);
if CompareText(sUpperValue, COMPARE_BMP) = 0 then
iftTemp := ziftBMP
else
if (CompareText(sUpperValue, COMPARE_JPG) = 0)
or (CompareText(sUpperValue, COMPARE_JPEG) = 0) then
iftTemp := ziftJPG;
//////////////////////////
// Not implemented yet: //
//////////////////////////
{
else
if CompareText(sUpperValue, COMPARE_GIF) = 0 then
iftTemp := ziftGIF
else
if CompareText(sUpperValue, COMPARE_PNG) = 0 then
iftTemp := ziftPNG;
}
Result := iftTemp;
end; // StringToImageFileType
function FileNameToImageFileType(const sFileName: String): TImageFileType;
///////////////////////////////////////////////////////
// Preconditions : //
// sFileName is a valid filename //
// //
// Output : //
// Corresponding image file type based on extension //
// If extension isn't recognized, returns ziftNone //
///////////////////////////////////////////////////////
begin
Result := ExtensionToImageFileType(ExtractFileExt(sFileName));
end; // FileNameToImageFileType
function ImageFileTypeToString(iftValue: TImageFileType): String;
var
sTemp: String;
begin
sTemp := '';
case iftValue of
ziftBMP:
sTemp := COMPARE_BMP;
ziftJPG:
sTemp := COMPARE_JPG;
//////////////////////////
// Not implemented yet: //
//////////////////////////
{
ziftGIF:
sTemp := COMPARE_GIF;
ziftPNG:
sTemp := COMPARE_PNG;
}
end; // case iftValue
Result := sTemp;
end; // ImageFileTypeToString
function ImageFileTypeToExtension(iftValue: TImageFileType): String;
var
sTemp: String;
begin
sTemp := '';
case iftValue of
ziftBMP:
sTemp := EXTENSION_BMP;
ziftJPG:
sTemp := EXTENSION_JPG;
//////////////////////////
// Not implemented yet: //
//////////////////////////
{
ziftGIF:
sTemp := EXTENSION_GIF;
ziftPNG:
sTemp := EXTENSION_PNG;
}
end; // case iftValue
Result := sTemp;
end; // ImageFileTypeToExtension
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ Pascal Invoker Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit Invoker;
interface
uses
SysUtils, Classes, Typinfo, IntfInfo, InvokeRegistry, WSDLIntf;
type
TInterfaceInvoker = class
public
procedure Invoke(const Obj: TObject; IntfMD: TIntfMetaData;
const MethNum: Integer; const Context: TInvContext);
constructor Create;
end;
implementation
uses InvConst, InvRules, SOAPConst, Variants;
constructor TInterfaceInvoker.Create;
begin
inherited Create;
end;
{
PushStackParm
Copies an aligned number of bytes specified by ByteCount from the Parm
to the current stack. N.B. We leave the bytes on the stack when we
exit!
Stack parameters come in many different sizes, ranging from 4 bytes to
16 bytes. This function copies a parameter of arbitrary
size from a prior stack location (assumed the stack), onto the current
stack. On exit, we leave the additional bytes on the stack. We use this
to build the parameter list to the server side functions.
We don't have to worry about copying bytes at the end of a page, because
we assume that Parm is pointing to something higher up on the stack, and
aligned on a proper stack boundary.
}
procedure PushStackParm(Parm: Pointer; ByteCount: Integer);
asm
{
EAX -> Parm (the parameter to be copied)
EDX -> ByteCount (the number of bytes of data in Parm)
}
{ We just use a jump table to copy the bits }
LEA ECX, @JT
{$IFDEF PIC}
ADD ECX, EBX
ADD ECX, EDX // Assume that ByteCount is a DWORD multiple
POP EDX // Remove and save the return address
MOV ECX, [ECX]
ADD ECX, EBX
JMP ECX
{$ELSE}
ADD ECX, EDX // Assume that ByteCount is a DWORD multiple
POP EDX // Remove and save the return address
JMP [ECX]
{$ENDIF}
@L4:
PUSH [EAX+12]
@L3:
PUSH [EAX+8]
@L2:
PUSH [EAX+4]
@L1:
PUSH [EAX]
PUSH EDX // Push back the saved ret addr
RET // All done
@JT:
DD 0 // 0 bytes (never happens)
DD @L1 // 4 bytes
DD @L2 // 8 bytes
DD @L3 // 12 bytes
DD @L4 // 16 bytes
end;
{
GetFloatReturn
Handles the nuances of retrieving the various different sized floating
point values from the FPU and storing them in a buffer.
}
procedure GetFloatReturn(RetP: Pointer; FloatType: TFloatType);
asm
CMP EDX, ftSingle
JE @@Single
CMP EDX, ftDouble
JE @@Double
CMP EDX, ftExtended
JE @@Extended
CMP EDX, ftCurr
JE @@Curr
CMP EDX, ftComp
JE @@Curr { Same as Curr }
{ Should never get here :) }
@@Single:
FSTP DWORD PTR [EAX]
WAIT
RET
@@Double:
FSTP QWORD PTR [EAX]
WAIT
RET
@@Extended:
FSTP TBYTE PTR [EAX]
WAIT
RET
@@Curr:
FISTP QWORD PTR [EAX]
WAIT
end;
procedure TInterfaceInvoker.Invoke(const Obj: TObject;
IntfMD: TIntfMetaData; const MethNum: Integer;
const Context: TInvContext);
var
MethPos: Integer;
Unk: IUnknown;
IntfEntry: PInterfaceEntry;
IntfVTable: Pointer;
RetIsOnStack, RetIsInFPU, RetInAXDX: Boolean;
I: Integer;
RetP : Pointer;
MD : TIntfMethEntry;
DataP: Pointer;
Temp, Temp1: Integer;
RetEAX: Integer;
RetEDX: Integer;
TotalParamBytes: Integer;
ParamBytes: Integer;
begin
{$IFDEF LINUX}
try
{$ENDIF}
TotalParamBytes := 0;
MD := IntfMD.MDA[MethNUm];
if not Obj.GetInterface(IntfMD.IID, Unk) then
raise Exception.CreateFmt(SNoInterfaceGUID,
[Obj.ClassName, GUIDToString(IntfMD.IID)]);
IntfEntry := Obj.GetInterfaceEntry(IntfMD.IID);
IntfVTable := IntfEntry.VTable;
MethPos := MD.Pos * 4; { Pos is absolute to whole VMT }
if MD.ResultInfo <> nil then
begin
RetIsInFPU := RetInFPU(MD.ResultInfo);
RetIsOnStack := RetOnStack(MD.ResultInfo);
RetInAXDX := IsRetInAXDX(MD.ResultInfo);
RetP := Context.GetResultPointer;
end else
begin
RetIsOnStack := False;
RetIsInFPU := False;
RetInAXDX := False;
end;
if MD.CC in [ccCDecl, ccStdCall, ccSafeCall] then
begin
if (MD.ResultInfo <> nil) and (MD.CC = ccSafeCall) then
asm PUSH DWORD PTR [RetP] end;
for I := MD.ParamCount - 1 downto 0 do
begin
DataP := Context.GetParamPointer(I);
if IsParamByRef(MD.Params[I].Flags,MD.Params[I].Info, MD.CC) then
asm
PUSH DWORD PTR [DataP]
end
else
begin
ParamBytes := GetStackTypeSize(MD.Params[I].Info, MD.CC);
PushStackParm(DataP, ParamBytes);
Inc(TotalParamBytes, ParamBytes);
end;
end;
asm PUSH DWORD PTR [Unk] end;
if RetIsOnStack and (MD.CC <> ccSafeCall) then
asm PUSH DWORD PTR [RetP] end;
end
else if MD.CC = ccPascal then
begin
for I := 0 to MD.ParamCount - 1 do
begin
DataP := Context.GetParamPointer(I);
if IsParamByRef(MD.Params[I].Flags,MD.Params[I].Info, MD.CC) then
asm
PUSH DWORD PTR [DataP]
end
else
begin
// PushStackParm(DataP, GetStackTypeSize(MD.Params[I].Info, MD.CC));
ParamBytes := GetStackTypeSize(MD.Params[I].Info, MD.CC);
PushStackParm(DataP, ParamBytes);
Inc(TotalParamBytes, ParamBytes);
end;
end;
if RetIsOnStack then
asm PUSH DWORD PTR [RetP] end;
asm PUSH DWORD PTR [Unk] end;
end else
raise Exception.CreateFmt(SUnsupportedCC, [CallingConventionName[MD.CC]]);
if MD.CC <> ccSafeCall then
begin
asm
MOV DWORD PTR [Temp], EAX
MOV DWORD PTR [Temp1], ECX
MOV EAX, MethPos
MOV ECX, [IntfVtable]
MOV ECX, [ECX + EAX]
CALL ECX
MOV DWORD PTR [RetEAX], EAX
MOV DWORD PTR [RetEDX], EDX
MOV EAX, DWORD PTR [Temp]
MOV ECX, DWORD PTR [Temp1]
end;
end else
begin
asm
MOV DWORD PTR [Temp], EAX
MOV DWORD PTR [Temp1], ECX
MOV EAX, MethPos
MOV ECX, [IntfVtable]
MOV ECX, [ECX + EAX]
CALL ECX
CALL System.@CheckAutoResult
MOV DWORD PTR [RetEAX], EAX
MOV DWORD PTR [RetEDX], EDX
MOV EAX, DWORD PTR [Temp]
MOV ECX, DWORD PTR [Temp1]
end;
end;
// If we're cdecl, we're responsible for cleanup up the stack.
if MD.CC = ccCDecl then
asm
MOV EAX, DWORD PTR [TotalParamBytes]
ADD ESP, EAX
end;
if MD.ResultInfo <> nil then
begin
if MD.CC <> ccSafeCall then
begin
if RetIsInFPU then
begin
GetFloatReturn(RetP, GetTypeData(MD.ResultInfo).FloatType);
end else if not RetIsOnStack then
begin
if RetInAXDX then
asm
PUSH EAX
PUSH ECX
MOV EAX, DWORD PTR [RetP]
MOV ECX, DWORD PTR [RetEAX]
MOV [EAX], ECX
MOV ECX, DWORD PTR [RetEDX]
MOV [EAX + 4], ECX
POP ECX
POP EAX
end
else
asm
PUSH EAX
PUSH ECX
MOV EAX, DWORD PTR [RetP]
MOV ECX, DWORD PTR [RetEAX]
MOV [EAX], ECX
POP ECX
POP EAX
end;
end;
end;
end;
{$IFDEF LINUX}
except
// This little bit of code is required to reset the stack back to a more
// resonable state since the exception unwinder is completely unaware of
// the stack pointer adjustments made in this function.
asm
MOV EAX, DWORD PTR [TotalParamBytes]
ADD ESP, EAX
end;
raise;
end;
{$ENDIF}
end;
end.
|
program SystemConfInfo;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, uSMBIOS
{ you can add units after this };
procedure GetBIOSInfo;
Var
SMBios: TSMBios;
i: Integer;
LSystemConf: TSystemConfInformation;
begin
SMBios:=TSMBios.Create;
try
if SMBios.HasSystemConfInfo then
begin
Writeln('System Config Strings');
Writeln('---------------------');
for LSystemConf in SMBios.SystemConfInfo do
for i:=1 to LSystemConf.RAWSystemConfInformation^.Count do
Writeln(LSystemConf.GetConfString(i));
end;
finally
SMBios.Free;
end;
end;
begin
try
GetBIOSInfo;
except
on E:Exception do
Writeln(E.Classname, ':', E.Message);
end;
Writeln;
Writeln('Press Enter to exit');
Readln;
end.
|
// auteur : Djebien Tarik
// date : Mai 2010
// objet : Programme Test Correcteur orthographique VERSION BASIQUE.
Program verificateurBasique;
uses U_Dico, U_Liste, U_Edition, U_FichierTexte;
var L : LISTE;
unMot : MOT;
plusProche : MOT;
presence : BOOLEAN;
// procedure de description de l'usage du programme
// utilisee uniquement si usage incorrect
// i.e : si l'utilisateur ne rentre pas de paramètre à l'exécution.
procedure usage(const s : STRING);
begin
writeln(stderr,'Nombre de parametres incorrect !');
writeln(stderr,'Usage : ');
writeln(stderr,s+' <F> ');
writeln(stderr,' <F> = nom du fichier.txt contenant le texte a analyser.');
halt(1);
end {usage};
// procedure qui etant donné un mot à tester et une liste de mots, indique si le mot
// est dans la liste et sinon donne le mot le plus proche au sens de la distance d'édition :
procedure verifier(const m : MOT; const L : LISTE; out estPresent: BOOLEAN; out motLePlusProche : String);
var distanceMinimal,distanceCourante : CARDINAL;
ll : LISTE;
begin
// On clone la liste en parametre car elle est en const
ll := cloner(L);
distanceCourante := distance_dynamique(m,tete(ll));
distanceMinimal := distanceCourante;
while not(estListeVide(ll)) do begin
if (distanceCourante = 0) then
begin
estPresent := TRUE;
motLePlusProche := m;
end
else
begin
estPresent := FALSE;
distanceCourante := distance_dynamique(m,tete(ll));
if ( distanceCourante <= distanceMinimal ) then begin
distanceMinimal := distanceCourante;
motLePlusProche := tete(ll);
end;//if
end;//if
ll:= reste(ll);
end;//while
end{verifier};
BEGIN
// Si l'utilisateur oubli le parametre à l'execution
if paramcount() <> 1 then
usage(paramstr(0))
else
begin
// Construction du Dictionnaire à partir de dicotest.txt dans une Liste
L := LISTE_VIDE;
L := tousLesMots;
// On affiche les mots du Dictionnaire contenu dans la liste
writeln;
writeln('MON DICTIONNAIRE :');
AfficherListe(L);writeln;
writeln;
// Le fichier textetest.txt est ouvert en paramètre à l'éxécution
// c'est le fichier dont nous allons verifier les fautes d'orthographes.
ouvrir(paramStr(1));
// Verification orthographique pour chaques mots du textetest.txt grâce à notre dicotest.txt.
while (not(lectureTerminee)) do begin
unMot := lireMotSuivant ;
verifier(unMot,L,presence,plusProche);
// Si le mot n'est pas reconnu par le dictionnaire
if not(presence) then
// alors on propose le mot le plus proche à celui ci dans le dictionnaire dicotest.txt.
begin
write(unMot);
write(' -> ');
writeln(plusProche);
end;//if
end;//while
// On referme le fichier textetest.txt en fin d'éxécution aprés avoir terminé son analyse.
fermer;
end;//PROGRAMME PRINCIPAL
writeln;
END.{verificateurBasique}
|
unit osCustomLoginFormUn;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TLoginFormClass = class of TosCustomLoginForm;
TosCustomLoginForm = class(TForm)
UsernameEdit: TEdit;
Label1: TLabel;
btnOK: TButton;
PasswordEdit: TEdit;
Label2: TLabel;
btnCancelar: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FFocusedControl: TEdit;
{ Private declarations }
public
property FocusedControl: TEdit read FFocusedControl write FFocusedControl;
end;
implementation
{$R *.dfm}
procedure TosCustomLoginForm.FormShow(Sender: TObject);
begin
FocusedControl.SetFocus;
end;
procedure TosCustomLoginForm.FormCreate(Sender: TObject);
begin
FocusedControl := UsernameEdit;
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ Workflow Component }
{ Copyright (c) 2015-2017 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.Workflow;
interface
{
The TBIWorkflow component is a non-visual container of Data items.
Each data item is associated with an "action", like for example adding a
column, remove a column, perform a calculation etc.
Items are organized in a hierarchical tree, so the "action" of an item uses
its Parent data as the source.
At design-time or run-time, any BI control or component can use a Workflow
item output as data source.
This means data will be calculated propagating each tree node level to obtain
the final result.
Example:
Workflow:
Data2 = Data1 -> Add Column -> Query -> Calculation -> Query ... etc
BIGrid1.Data := Data2 // <-- process all steps above from Data1 to Data2
}
uses
System.Classes, BI.DataItem, BI.Persist, BI.Query, BI.Arrays, BI.Arrays.Strings,
BI.DataSource, BI.Summary, BI.Expressions, BI.Algorithm,
BI.CollectionItem, BI.Tools, BI.Expression.Filter, BI.Rank,
BI.Merge;
type
TWorkflowItems=class;
// Collection Item
TWorkflowItem=class(TDataCollectionItem)
private
FItems: TWorkflowItems;
FParentItem : String;
OwnsData : Boolean;
// Temporary during loading
IProvider : Integer;
IOrigins : TDataOrigins;
procedure FixOrigins(const AParent:TDataItem);
function IsItemsStored: Boolean;
procedure ReadProvider(Reader: TReader);
procedure ReadOrigins(Reader: TReader);
procedure SetItems(const Value: TWorkflowItems);
procedure TrySetNeeds(const Value:TComponent);
procedure TrySetSource(const Value:TDataItem); overload;
procedure TrySetSource(const Value:TDataArray); overload;
procedure WriteProvider(Writer: TWriter);
procedure WriteOrigins(Writer: TWriter);
protected
procedure DefineProperties(Filer: TFiler); override;
function OriginsStored:Boolean;
function Owner:TComponent; override;
procedure SetData(const Value: TDataItem); override;
procedure SetProvider(const Value: TComponent); override;
public
Constructor Create(Collection: TCollection); override;
Destructor Destroy; override;
function ParentData:TDataItem;
published
property Items:TWorkflowItems read FItems write SetItems stored IsItemsStored;
property ParentItem:String read FParentItem write FParentItem;
end;
// Collection
TWorkflowItems=class(TOwnedCollection)
private
function Get(const Index: Integer): TWorkflowItem;
procedure Put(const Index: Integer; const Value: TWorkflowItem);
public
Constructor Create(AOwner: TPersistent);
function Add: TWorkflowItem; overload;
function Add(const AProvider:TDataProvider;
const AName:String):TWorkflowItem; overload;
function Add(const ASource:TDataItem;
const AProvider:TDataProvider;
const AName:String):TWorkflowItem; overload;
function Add(const ASources:TDataArray;
const AProvider:TDataProvider;
const AName:String):TWorkflowItem; overload;
property Items[const Index:Integer]:TWorkflowItem read Get write Put; default;
end;
{$IFNDEF FPC}
{$IF CompilerVersion>=23}
[ComponentPlatformsAttribute(pidWin32 or pidWin64 or pidOSX32
{$IF CompilerVersion>=25}or pidiOSSimulator or pidiOSDevice{$ENDIF}
{$IF CompilerVersion>=26}or pidAndroid{$ENDIF}
{$IF CompilerVersion>=29}or pidiOSDevice64{$ENDIF}
)]
{$ENDIF}
{$ENDIF}
TBIWorkflow=class(TBaseDataImporter)
private
FItems: TWorkflowItems;
function IndexOfProvider(const AProvider:TDataProvider):Integer;
procedure SetItems(const Value: TWorkflowItems);
protected
function GetChildOwner: TComponent; override;
Procedure GetChildren(Proc:TGetChildProc; Root:TComponent); override;
procedure Load(const AData:TDataItem; const Children:Boolean); override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
published
property Items:TWorkflowItems read FItems write SetItems;
end;
TConvertItem=class(TCloneProvider)
private
FKind : TDataKind;
procedure SetKind(const Value: TDataKind);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
published
property Kind:TDataKind read FKind write SetKind default TDataKind.dkUnknown;
end;
TReorderItem=class(TCloneProvider)
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Items : TDataArray;
end;
TCompareItem=class(TDataProviderNeeds)
private
function GetA: TDataItem;
function GetB: TDataItem;
procedure SetA(const Value: TDataItem);
procedure SetB(const Value: TDataItem);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
property A:TDataItem read GetA write SetA;
property B:TDataItem read GetB write SetB;
end;
TMergeStyle=(Join,Subtract,Common,Different);
TMergeItem=class(TCloneProvider)
private
FItems : TDataArray;
FStyle : TMergeStyle;
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
published
property Items:TDataArray read FItems write FItems;
property Style:TMergeStyle read FStyle write FStyle default TMergeStyle.Join;
end;
TSplitItem=class(TSingleSourceProvider)
private
FBy : TSplitBy;
FCount : Integer;
FMode : TSplitMode;
FPercent : Single;
procedure SetBy(const Value:TSplitBy);
procedure SetCount(const Value:Integer);
procedure SetMode(const Value:TSplitMode);
procedure SetPercent(const Value:Single);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
published
property By:TSplitBy read FBy write SetBy default TSplitBy.Percent;
property Count:Integer read FCount write SetCount default 0;
property Mode:TSplitMode read FMode write SetMode default TSplitMode.Start;
property Percent:Single read FPercent write SetPercent;
end;
TSortActionItem=class(TCloneProvider)
private
FItems : TSortItems;
procedure SetItems(const Value: TSortItems);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
property SortItems:TSortItems read FItems write SetItems;
published
end;
TDataRankItem=class(TCloneProvider)
private
FAscending: Boolean;
function GetGroups: TDataArray;
function GetValue: TDataItem;
procedure SetAscending(const Value: Boolean);
procedure SetGroups(const Value: TDataArray);
procedure SetValue(const Value: TDataItem);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
property Groups:TDataArray read GetGroups write SetGroups;
property Value:TDataItem read GetValue write SetValue;
published
property Ascending:Boolean read FAscending write SetAscending;
end;
TDataGridifyItem=class(TSingleSourceProvider)
private
function GetColumns: TDataArray;
function GetRows: TDataArray;
function GetValue: TDataItem;
procedure SetColumns(const Value: TDataArray);
procedure SetRows(const Value: TDataArray);
procedure SetValue(const Value: TDataItem);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
property Columns:TDataArray read GetColumns write SetColumns;
property Rows:TDataArray read GetRows write SetRows;
property Value:TDataItem read GetValue write SetValue;
end;
TItemAction=class(TCloneProvider)
private
FItemName : String;
procedure SetItemName(const Value: String);
published
property ItemName:String read FItemName write SetItemName;
end;
TNewItem=class(TItemAction)
private
FKind : TDataKind;
function AddNewItem(const AData:TDataItem):TDataItem;
procedure SetKind(const Value: TDataKind);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
published
property Kind:TDataKind read FKind write SetKind;
end;
TItemsAction=class(TCloneProvider)
private
FItems : TStringArray;
procedure SetItems(const Value: TStringArray);
published
property Items:TStringArray read FItems write SetItems;
end;
TDeleteItems=class(TItemsAction)
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
end;
TDuplicateItems=class(TItemsAction)
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
end;
TRenameItem=class(TItemAction)
private
FNewName : String;
procedure SetNewName(const Value: String);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
property NewName:String read FNewName write SetNewName;
end;
TDataTranspose=class(TSingleSourceProvider)
private
procedure TransposeRow(const ADest:TDataItem; const ARow:TInteger; const AOffset:Integer);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
end;
TNormalizeItem=class(TCloneProvider)
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
end;
TFilterAction=class(TSingleSourceProvider)
private
FQuery : TBIQuery;
procedure SetFilter(const Value: TBIFilter);
function GetFilter: TBIFilter;
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
property Filter:TBIFilter read GetFilter write SetFilter;
end;
TDataShuffle=class(TCloneProvider)
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
end;
TGroupByItem=class(TSingleSourceProvider)
private
function GetGroups: TDataArray;
procedure SetGroups(const Value: TDataArray);
protected
procedure Load(const AData:TDataItem; const Children:Boolean); override;
public
Constructor Create(AOwner:TComponent); override;
property Groups:TDataArray read GetGroups write SetGroups;
end;
// Pending:
// TDataMapReduce=class(TCloneProvider)
// end;
TBIProviderChooser=function(const AOwner:TComponent):TDataProvider;
var
BIFunctionChooser:TBIProviderChooser=nil;
implementation
|
unit DatasetJSON;
interface
uses
DB;
function DatasetToJSONArray(const ds : TDataset; arrayName : String = '') : string;
implementation
uses
SysUtils,
JSONHelper;
function DatasetRowToJSON(const ds:TDataset; makelowercase : Boolean = true):string;
var
iField : integer;
function fieldToJSON(thisField:TField):string;
var
name : String;
begin
if(makelowercase) then
name := LowerCase(thisField.FieldName)
else
name := thisField.fieldName;
case thisField.DataType of
ftInteger,ftSmallint,ftLargeint:
result := JSONElement(name, thisField.AsInteger);
ftDate:
result := JSONElementDate(name, thisField.AsDateTime);
ftDateTime:
result := JSONElementDateTime(name, thisField.AsDateTime);
ftCurrency,
ftFloat:
result := JSONElement(name, FloatToStr(thisField.AsFloat));
else
result := JSONElement(name, thisField.AsString);
end; // case
end; // of fieldToJSON
begin
result := '';
for iField := 0 to ds.fieldcount - 1 do
begin
if iField > 0 then
result := result + ',';
result := result + fieldToJSON(ds.Fields[iField]);
end;
result := '{'+Result+'}';
end;
function DatasetToJSONArray(const ds : TDataset; arrayName : String = '') : string;
begin
result := '';
if (not ds.eof) and (ds <> nil) then
begin
ds.first;
while not ds.eof do
begin
if Result <> '' then
result := result + ',';
result := result + DatasetRowToJSON(ds);
ds.next;
end;
end;
if arrayName = '' then
result := '['+result+']'
else
Result := '{' + JSONArray(arrayName, Result) + '}';
end; // of DSToJSON
end.
|
unit SimpleDemo.View.Page.Principal;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Layouts,
Router4D.Interfaces;
type
TPagePrincipal = class(TForm, iRouter4DComponent)
Layout1: TLayout;
Label1: TLabel;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function Render : TFMXObject;
procedure UnRender;
end;
var
PagePrincipal: TPagePrincipal;
implementation
uses
Router4D,
Router4D.Props;
{$R *.fmx}
{ TPagePrincipal }
procedure TPagePrincipal.Button1Click(Sender: TObject);
begin
TRouter4D.Link.&To('Cadastros');
end;
procedure TPagePrincipal.Button2Click(Sender: TObject);
begin
TRouter4D.Link
.&To(
'Cadastros',
TProps
.Create
.PropString(
'Olá Router4D, Seu Cadastro Recebeu as Props'
)
.PropInteger(0)
.Key('TelaCadastro')
);
end;
function TPagePrincipal.Render: TFMXObject;
begin
Result := Layout1;
end;
procedure TPagePrincipal.UnRender;
begin
//
end;
end.
|
unit FC.StockChart.UnitTask.TradeLine.Analysis;
{$I Compiler.inc}
interface
uses
SysUtils,Classes, BaseUtils, Serialization, StockChart.Definitions.Units,StockChart.Definitions,
FC.Definitions, FC.Singletons,
FC.StockChart.UnitTask.Base;
implementation
uses
FC.StockChart.UnitTask.TradeLine.AnalysisDialog;
type
TStockUnitTradeLineAnalysis = class(TStockUnitTaskBase)
public
function CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean; override;
procedure Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition); override;
end;
{ TStockUnitTradeLineAnalysis }
function TStockUnitTradeLineAnalysis.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean;
begin
result:=Supports(aIndicator,ISCIndicatorTradeLine);
if result then
aOperationName:='Open/Close Order Analysis';
end;
procedure TStockUnitTradeLineAnalysis.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition);
begin
TfmTradeLineAnalysisDialog.Run(aIndicator as ISCIndicatorTradeLine, aStockChart);
end;
initialization
StockUnitTaskRegistry.AddUnitTask(TStockUnitTradeLineAnalysis.Create);
end.
|
unit uService;
{$mode objfpc}{$H+}
interface
uses
SynCommons, mORMot, uForwardDeclaration;//Classes, SysUtils;
type
// 1
TSQLJobSandbox = class(TSQLRecord)
private
fJobId: Integer;
fJobName: RawUTF8;
fRunTime: TDateTime;
fPoolId: Integer;
fStatus: TSQLStatusItemID;
fParentJobId: Integer;
fPreviousJobId: Integer;
fServiceName: RawUTF8;
fLoaderName: RawUTF8;
fMaxRetry: Integer;
fCurrentRetryCount: Integer;
fAuthUserLogin: TSQLUserLoginID;
fRunAsUser: TSQLUserLoginID;
fRuntimeData: TSQLRuntimeDataID;
fRecurrenceInfo: TSQLRecurrenceInfoID;
fTempExpr: TSQLTemporalExpressionID;
fCurrentRecurrenceCount: Integer;
fMaxRecurrenceCount: Integer;
fRunByInstanceId: Integer;
fStartDateTime: TDateTime;
fFinishDateTime: TDateTime;
fCancelDateTime: TDateTime;
fJobResult: RawUTF8;
published
property JobId: Integer read fJobId write fJobId;
property JobName: RawUTF8 read fJobName write fJobName;
property RunTime: TDateTime read fRunTime write fRunTime;
property PoolId: Integer read fPoolId write fPoolId;
property Status: TSQLStatusItemID read fStatus write fStatus;
property ParentJobId: Integer read fParentJobId write fParentJobId;
property PreviousJobId: Integer read fPreviousJobId write fPreviousJobId;
property ServiceName: RawUTF8 read fServiceName write fServiceName;
property LoaderName: RawUTF8 read fLoaderName write fLoaderName;
property MaxRetry: Integer read fMaxRetry write fMaxRetry;
property CurrentRetryCount: Integer read fCurrentRetryCount write fCurrentRetryCount;
property AuthUserLogin: TSQLUserLoginID read fAuthUserLogin write fAuthUserLogin;
property RunAsUser: TSQLUserLoginID read fRunAsUser write fRunAsUser;
property RuntimeData: TSQLRuntimeDataID read fRuntimeData write fRuntimeData;
property RecurrenceInfo: TSQLRecurrenceInfoID read fRecurrenceInfo write fRecurrenceInfo;
property TempExpr: TSQLTemporalExpressionID read fTempExpr write fTempExpr;
property CurrentRecurrenceCount: Integer read fCurrentRecurrenceCount write fCurrentRecurrenceCount;
property MaxRecurrenceCount: Integer read fMaxRecurrenceCount write fMaxRecurrenceCount;
property RunByInstanceId: Integer read fRunByInstanceId write fRunByInstanceId;
property StartDateTime: TDateTime read fStartDateTime write fStartDateTime;
property FinishDateTime: TDateTime read fFinishDateTime write fFinishDateTime;
property CancelDateTime: TDateTime read fCancelDateTime write fCancelDateTime;
property JobResult: RawUTF8 read fJobResult write fJobResult;
end;
// 2
TSQLRecurrenceInfo = class(TSQLRecord)
private
fStartDateTime: TDateTime;
fExceptionDateTimes: Integer;
fRecurrenceDateTimes: Integer;
fExceptionRule: TSQLRecurrenceRuleID;
fRecurrenceRule: TSQLRecurrenceRuleID;
fRecurrenceCount: Integer;
published
property StartDateTime: TDateTime read fStartDateTime write fStartDateTime;
property ExceptionDateTimes: Integer read fExceptionDateTimes write fExceptionDateTimes;
property RecurrenceDateTimes: Integer read fRecurrenceDateTimes write fRecurrenceDateTimes;
property ExceptionRule: TSQLRecurrenceRuleID read fExceptionRule write fExceptionRule;
property RecurrenceRule: TSQLRecurrenceRuleID read fRecurrenceRule write fRecurrenceRule;
property RecurrenceCount: Integer read fRecurrenceCount write fRecurrenceCount;
end;
// 3
TSQLRecurrenceRule = class(TSQLRecord)
private
fFrequency: RawUTF8;
fUntilDateTime: TDateTime;
fCountNumber: Integer;
fIntervalNumber: Integer;
fBySecondList: RawUTF8;
fByMinuteList: RawUTF8;
fByHourList: RawUTF8;
fByDayList: RawUTF8;
fByMonthDayList: RawUTF8;
fByYearDayList: RawUTF8;
fByWeekNoList: RawUTF8;
fByMonthList: RawUTF8;
fBySetPosList: RawUTF8;
fWeekStart: RawUTF8;
fXName: RawUTF8;
published
property Frequency: RawUTF8 read fFrequency write fFrequency;
property UntilDateTime: TDateTime read fUntilDateTime write fUntilDateTime;
property CountNumber: Integer read fCountNumber write fCountNumber;
property IntervalNumber: Integer read fIntervalNumber write fIntervalNumber;
property BySecondList: RawUTF8 read fBySecondList write fBySecondList;
property ByMinuteList: RawUTF8 read fByMinuteList write fByMinuteList;
property ByHourList: RawUTF8 read fByHourList write fByHourList;
property ByDayList: RawUTF8 read fByDayList write fByDayList;
property ByMonthDayList: RawUTF8 read fByMonthDayList write fByMonthDayList;
property ByYearDayList: RawUTF8 read fByYearDayList write fByYearDayList;
property ByWeekNoList: RawUTF8 read fByWeekNoList write fByWeekNoList;
property ByMonthList: RawUTF8 read fByMonthList write fByMonthList;
property BySetPosList: RawUTF8 read fBySetPosList write fBySetPosList;
property WeekStart: RawUTF8 read fWeekStart write fWeekStart;
property XName: RawUTF8 read fXName write fXName;
end;
// 3
TSQLRuntimeData = class(TSQLRecord)
private
fRuntimeInfo: RawUTF8;
published
property RuntimeInfo: RawUTF8 read fRuntimeInfo write fRuntimeInfo;
end;
// 4
TSQLTemporalExpression = class(TSQLRecord)
private
fTempExprTypeId: Integer;
fDescription: RawUTF8;
fDate1: TDateTime;
fDate2: TDateTime;
fInteger1: Integer;
fInteger2: Integer;
fString1: RawUTF8;
fString2: RawUTF8;
published
property TempExprTypeId: Integer read fTempExprTypeId write fTempExprTypeId;
property Description: RawUTF8 read fDescription write fDescription;
property Date1: TDateTime read fDate1 write fDate1;
property Date2: TDateTime read fDate2 write fDate2;
property Integer1: Integer read fInteger1 write fInteger1;
property Integer2: Integer read fInteger2 write fInteger2;
property String1: RawUTF8 read fString1 write fString1;
property String2: RawUTF8 read fString2 write fString2;
end;
// 5
TSQLTemporalExpressionAssoc = class(TSQLRecord)
private
fFromTempExpr: TSQLTemporalExpressionID;
fToTempExpr: TSQLTemporalExpressionID;
fExprAssocType: Integer;
published
property FromTempExpr: TSQLTemporalExpressionID read fFromTempExpr write fFromTempExpr;
property ToTempExpr: TSQLTemporalExpressionID read fToTempExpr write fToTempExpr;
property ExprAssocType: Integer read fExprAssocType write fExprAssocType;
end;
// 6
TSQLJobManagerLock = class(TSQLRecord)
private
fInstanceId: Integer;
fFromDate: TDateTime;
fThruDate: TDateTime;
fReasonEnum: TSQLEnumerationID;
fComments: RawUTF8;
fCreatedDate: TDateTime;
fCreatedByUserLogin: TSQLUserLoginID;
fLastModifiedDate: TDateTime;
fLastModifiedByUserLogin: TSQLUserLoginID;
published
property InstanceId: Integer read fInstanceId write fInstanceId;
property FromDate: TDateTime read fFromDate write fFromDate;
property ThruDate: TDateTime read fThruDate write fThruDate;
property ReasonEnum: TSQLEnumerationID read fReasonEnum write fReasonEnum;
property Comments: RawUTF8 read fComments write fComments;
property CreatedDate: TDateTime read fCreatedDate write fCreatedDate;
property CreatedByUserLogin: TSQLUserLoginID read fCreatedByUserLogin write fCreatedByUserLogin;
property LastModifiedDate: TDateTime read fLastModifiedDate write fLastModifiedDate;
property LastModifiedByUserLogin: TSQLUserLoginID read fLastModifiedByUserLogin write fLastModifiedByUserLogin;
end;
// 7
TSQLServiceSemaphore = class(TSQLRecord)
private
fServiceName: RawUTF8;
fLockedByInstanceId: Integer;
fLockThread: RawUTF8;
fLockTime: TDateTime;
published
property ServiceName: RawUTF8 read fServiceName write fServiceName;
property LockedByInstanceId: Integer read fLockedByInstanceId write fLockedByInstanceId;
property LockThread: RawUTF8 read fLockThread write fLockThread;
property LockTime: TDateTime read fLockTime write fLockTime;
end;
{
//
TSQL = class(TSQLRecord)
private
published
property read write ;
property read write ;
property read write ;
property read write ;
property read write ;
end;
}
implementation
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 21 O(N3) Bfs Method
}
program
GraphCenter;
const
MaxN = 100;
var
N, V, C, C2 : Integer;
A : array [1 .. MaxN, 1 .. MaxN] of Integer;
Q, P : array [1 .. MaxN] of Integer;
M : array [1 .. MaxN] of Boolean;
I, J, L, R : Integer;
F : Text;
procedure ReadInput;
begin
Assign(F, 'input.txt');
Reset(F);
Readln(F, N);
for I := 2 to N do
begin
for J := 1 to I - 1 do
begin
Read(F, A[I, J]); A[J, I] := A[I, J];
end;
Readln(F);
end;
Close(F);
end;
procedure Center;
begin
C := MaxInt;
for Q[1] := 1 to N do
begin
FillChar(M, SizeOf(M), 0);
L := 1;
R := 1;
M[Q[1]] := True;
P[Q[1]] := 0;
while L <= R do
begin
for I := 1 to N do
if (A[I, Q[L]] = 1) and not M[I] then
begin
Inc(R);
Q[R] := I;
M[I] := True;
P[I] := P[Q[L]] + 1;
C2 := P[I];
end;
Inc(L);
end;
if C2 < C then
begin
C := C2; V := Q[1];
end;
end;
end;
procedure WriteOutput;
begin
Assign(F, 'output.txt');
ReWrite(F);
Writeln(F, V);
Writeln(F, C);
Close(F);
end;
begin
ReadInput;
Center;
WriteOutput;
end.
|
unit gfx_const; //v1.2 0801
interface
const // TIFF tags
TIFFTAG_SUBFILETYPE = 254; // subfile data descriptor
FILETYPE_REDUCEDIMAGE = $1; // reduced resolution version
FILETYPE_PAGE = $2; // one page of many
FILETYPE_MASK = $4; // transparency mask
TIFFTAG_OSUBFILETYPE = 255; // kind of data in subfile (obsolete by revision 5.0)
OFILETYPE_IMAGE = 1; // full resolution image data
OFILETYPE_REDUCEDIMAGE = 2; // reduced size image data
OFILETYPE_PAGE = 3; // one page of many
TIFFTAG_IMAGEWIDTH = 256; // image width in pixels
TIFFTAG_IMAGELENGTH = 257; // image height in pixels
TIFFTAG_BITSPERSAMPLE = 258; // bits per channel (sample)
TIFFTAG_COMPRESSION = 259; // data compression technique
COMPRESSION_NONE = 1; // dump mode
COMPRESSION_CCITTRLE = 2; // CCITT modified Huffman RLE
COMPRESSION_CCITTFAX3 = 3; // CCITT Group 3 fax encoding
COMPRESSION_CCITTFAX4 = 4; // CCITT Group 4 fax encoding
COMPRESSION_LZW = 5; // Lempel-Ziv & Welch
COMPRESSION_OJPEG = 6; // 6.0 JPEG
COMPRESSION_JPEG = 7; // JPEG DCT compression
COMPRESSION_NEXT = 32766; // next 2-bit RLE
COMPRESSION_CCITTRLEW = 32771; // #1 w/ Word alignment
COMPRESSION_PACKBITS = 32773; // Macintosh RLE
COMPRESSION_THUNDERSCAN = 32809; // ThunderScan RLE
COMPRESSION_IT8CTPAD = 32895; // IT8 CT w/padding
COMPRESSION_IT8LW = 32896; // IT8 Linework RLE
COMPRESSION_IT8MP = 32897; // IT8 Monochrome picture
COMPRESSION_IT8BL = 32898; // IT8 Binary line art
// compression codes 32908-32911 are reserved for Pixar
COMPRESSION_PIXARFILM = 32908; // Pixar companded 10bit LZW
COMPRESSION_PIXARLOG = 32909; // Pixar companded 11bit ZIP
COMPRESSION_DEFLATE = 32946; // Deflate compression
COMPRESSION_DCS = 32947; // Kodak DCS encoding
COMPRESSION_JBIG = 34661; // ISO JBIG
TIFFTAG_PHOTOMETRIC = 262; // photometric interpretation
PHOTOMETRIC_MINISWHITE = 0; // min value is white
PHOTOMETRIC_MINISBLACK = 1; // min value is black
PHOTOMETRIC_RGB = 2; // RGB color model
PHOTOMETRIC_PALETTE = 3; // color map indexed
PHOTOMETRIC_MASK = 4; // holdout mask
PHOTOMETRIC_SEPARATED = 5; // color separations
PHOTOMETRIC_YCBCR = 6; // CCIR 601
PHOTOMETRIC_CIELAB = 8; // 1976 CIE L*a*b*
TIFFTAG_THRESHHOLDING = 263; // thresholding used on data (obsolete by revision 5.0)
THRESHHOLD_BILEVEL = 1; // b&w art scan
THRESHHOLD_HALFTONE = 2; // or dithered scan
THRESHHOLD_ERRORDIFFUSE = 3; // usually floyd-steinberg
TIFFTAG_CELLWIDTH = 264; // dithering matrix width (obsolete by revision 5.0)
TIFFTAG_CELLLENGTH = 265; // dithering matrix height (obsolete by revision 5.0)
TIFFTAG_FILLORDER = 266; // data order within a Byte
FILLORDER_MSB2LSB = 1; // most significant -> least
FILLORDER_LSB2MSB = 2; // least significant -> most
TIFFTAG_DOCUMENTNAME = 269; // name of doc. image is from
TIFFTAG_IMAGEDESCRIPTION = 270; // info about image
TIFFTAG_MAKE = 271; // scanner manufacturer name
TIFFTAG_MODEL = 272; // scanner model name/number
TIFFTAG_STRIPOFFSETS = 273; // Offsets to data strips
TIFFTAG_ORIENTATION = 274; // image FOrientation (obsolete by revision 5.0)
ORIENTATION_TOPLEFT = 1; // row 0 top, col 0 lhs
ORIENTATION_TOPRIGHT = 2; // row 0 top, col 0 rhs
ORIENTATION_BOTRIGHT = 3; // row 0 bottom, col 0 rhs
ORIENTATION_BOTLEFT = 4; // row 0 bottom, col 0 lhs
ORIENTATION_LEFTTOP = 5; // row 0 lhs, col 0 top
ORIENTATION_RIGHTTOP = 6; // row 0 rhs, col 0 top
ORIENTATION_RIGHTBOT = 7; // row 0 rhs, col 0 bottom
ORIENTATION_LEFTBOT = 8; // row 0 lhs, col 0 bottom
TIFFTAG_SAMPLESPERPIXEL = 277; // samples per pixel
TIFFTAG_ROWSPERSTRIP = 278; // rows per strip of data
TIFFTAG_STRIPBYTECOUNTS = 279; // bytes counts for strips
TIFFTAG_MINSAMPLEVALUE = 280; // minimum sample value (obsolete by revision 5.0)
TIFFTAG_MAXSAMPLEVALUE = 281; // maximum sample value (obsolete by revision 5.0)
TIFFTAG_XRESOLUTION = 282; // pixels/resolution in x
TIFFTAG_YRESOLUTION = 283; // pixels/resolution in y
TIFFTAG_PLANARCONFIG = 284; // storage organization
PLANARCONFIG_CONTIG = 1; // single image plane
PLANARCONFIG_SEPARATE = 2; // separate planes of data
TIFFTAG_PAGENAME = 285; // page name image is from
TIFFTAG_XPOSITION = 286; // x page offset of image lhs
TIFFTAG_YPOSITION = 287; // y page offset of image lhs
TIFFTAG_FREEOFFSETS = 288; // byte offset to free block (obsolete by revision 5.0)
TIFFTAG_FREEBYTECOUNTS = 289; // sizes of free blocks (obsolete by revision 5.0)
TIFFTAG_GRAYRESPONSEUNIT = 290; // gray scale curve accuracy
GRAYRESPONSEUNIT_10S = 1; // tenths of a unit
GRAYRESPONSEUNIT_100S = 2; // hundredths of a unit
GRAYRESPONSEUNIT_1000S = 3; // thousandths of a unit
GRAYRESPONSEUNIT_10000S = 4; // ten-thousandths of a unit
GRAYRESPONSEUNIT_100000S = 5; // hundred-thousandths
TIFFTAG_GRAYRESPONSECURVE = 291; // gray scale response curve
TIFFTAG_GROUP3OPTIONS = 292; // 32 flag bits
GROUP3OPT_2DENCODING = $1; // 2-dimensional coding
GROUP3OPT_UNCOMPRESSED = $2; // data not compressed
GROUP3OPT_FILLBITS = $4; // fill to byte boundary
TIFFTAG_GROUP4OPTIONS = 293; // 32 flag bits
GROUP4OPT_UNCOMPRESSED = $2; // data not compressed
TIFFTAG_RESOLUTIONUNIT = 296; // units of resolutions
RESUNIT_NONE = 1; // no meaningful units
RESUNIT_INCH = 2; // english
RESUNIT_CENTIMETER = 3; // metric
TIFFTAG_PAGENUMBER = 297; // page numbers of multi-page
TIFFTAG_COLORRESPONSEUNIT = 300; // color curve accuracy
COLORRESPONSEUNIT_10S = 1; // tenths of a unit
COLORRESPONSEUNIT_100S = 2; // hundredths of a unit
COLORRESPONSEUNIT_1000S = 3; // thousandths of a unit
COLORRESPONSEUNIT_10000S = 4; // ten-thousandths of a unit
COLORRESPONSEUNIT_100000S = 5; // hundred-thousandths
TIFFTAG_TRANSFERFUNCTION = 301; // colorimetry info
TIFFTAG_SOFTWARE = 305; // name & release
TIFFTAG_DATETIME = 306; // creation date and time
TIFFTAG_ARTIST = 315; // creator of image
TIFFTAG_HOSTCOMPUTER = 316; // machine where created
TIFFTAG_PREDICTOR = 317; // prediction scheme w/ LZW
PREDICTION_NONE = 1; // no prediction scheme used before coding
PREDICTION_HORZ_DIFFERENCING = 2; // horizontal differencing prediction scheme used
TIFFTAG_WHITEPOINT = 318; // image white point
TIFFTAG_PRIMARYCHROMATICITIES = 319; // primary chromaticities
TIFFTAG_COLORMAP = 320; // RGB map for pallette image
TIFFTAG_HALFTONEHINTS = 321; // highlight+shadow info
TIFFTAG_TILEWIDTH = 322; // rows/data tile
TIFFTAG_TILELENGTH = 323; // cols/data tile
TIFFTAG_TILEOFFSETS = 324; // offsets to data tiles
TIFFTAG_TILEBYTECOUNTS = 325; // Byte counts for tiles
TIFFTAG_BADFAXLINES = 326; // lines w/ wrong pixel count
TIFFTAG_CLEANFAXDATA = 327; // regenerated line info
CLEANFAXDATA_CLEAN = 0; // no errors detected
CLEANFAXDATA_REGENERATED = 1; // receiver regenerated lines
CLEANFAXDATA_UNCLEAN = 2; // uncorrected errors exist
TIFFTAG_CONSECUTIVEBADFAXLINES = 328; // max consecutive bad lines
TIFFTAG_SUBIFD = 330; // subimage descriptors
TIFFTAG_INKSET = 332; // inks in separated image
INKSET_CMYK = 1; // cyan-magenta-yellow-black
TIFFTAG_INKNAMES = 333; // ascii names of inks
TIFFTAG_DOTRANGE = 336; // 0% and 100% dot codes
TIFFTAG_TARGETPRINTER = 337; // separation target
TIFFTAG_EXTRASAMPLES = 338; // info about extra samples
EXTRASAMPLE_UNSPECIFIED = 0; // unspecified data
EXTRASAMPLE_ASSOCALPHA = 1; // associated alpha data
EXTRASAMPLE_UNASSALPHA = 2; // unassociated alpha data
TIFFTAG_SAMPLEFORMAT = 339; // data sample format
SAMPLEFORMAT_UINT = 1; // unsigned integer data
SAMPLEFORMAT_INT = 2; // signed integer data
SAMPLEFORMAT_IEEEFP = 3; // IEEE floating point data
SAMPLEFORMAT_VOID = 4; // untyped data
TIFFTAG_SMINSAMPLEVALUE = 340; // variable MinSampleValue
TIFFTAG_SMAXSAMPLEVALUE = 341; // variable MaxSampleValue
TIFFTAG_JPEGTABLES = 347; // JPEG table stream
TIFFTAG_JPEGPROC = 512; // JPEG processing algorithm
JPEGPROC_BASELINE = 1; // baseline sequential
JPEGPROC_LOSSLESS = 14; // Huffman coded lossless
TIFFTAG_JPEGIFOFFSET = 513; // Pointer to SOI marker
TIFFTAG_JPEGIFBYTECOUNT = 514; // JFIF stream length
TIFFTAG_JPEGRESTARTINTERVAL = 515; // restart interval length
TIFFTAG_JPEGLOSSLESSPREDICTORS = 517; // lossless proc predictor
TIFFTAG_JPEGPOINTTRANSFORM = 518; // lossless point transform
TIFFTAG_JPEGQTABLES = 519; // Q matrice offsets
TIFFTAG_JPEGDCTABLES = 520; // DCT table offsets
TIFFTAG_JPEGACTABLES = 521; // AC coefficient offsets
TIFFTAG_YCBCRCOEFFICIENTS = 529; // RGB -> YCbCr transform
TIFFTAG_YCBCRSUBSAMPLING = 530; // YCbCr subsampling factors
TIFFTAG_YCBCRPOSITIONING = 531; // subsample positioning
YCBCRPOSITION_CENTERED = 1; // as in PostScript Level 2
YCBCRPOSITION_COSITED = 2; // as in CCIR 601-1
TIFFTAG_REFERENCEBLACKWHITE = 532; // colorimetry info
TIFFTAG_REFPTS = 32953; // image reference points
TIFFTAG_REGIONTACKPOINT = 32954; // region-xform tack point
TIFFTAG_REGIONWARPCORNERS = 32955; // warp quadrilateral
TIFFTAG_REGIONAFFINE = 32956; // affine transformation mat
TIFFTAG_MATTEING = 32995; // use ExtraSamples
TIFFTAG_DATATYPE = 32996; // use SampleFormat
TIFFTAG_IMAGEDEPTH = 32997; // z depth of image
TIFFTAG_TILEDEPTH = 32998; // z depth/data tile
TIFFTAG_PIXAR_IMAGEFULLWIDTH = 33300; // full image size in x
TIFFTAG_PIXAR_IMAGEFULLLENGTH = 33301; // full image size in y
TIFFTAG_WRITERSERIALNUMBER = 33405; // device serial number
TIFFTAG_COPYRIGHT = 33432; // copyright string
TIFFTAG_IT8SITE = 34016; // site name
TIFFTAG_IT8COLORSEQUENCE = 34017; // color seq. [RGB,CMYK,etc]
TIFFTAG_IT8HEADER = 34018; // DDES Header
TIFFTAG_IT8RASTERPADDING = 34019; // raster scanline padding
TIFFTAG_IT8BITSPERRUNLENGTH = 34020; // # of bits in short run
TIFFTAG_IT8BITSPEREXTENDEDRUNLENGTH = 34021; // # of bits in long run
TIFFTAG_IT8COLORTABLE = 34022; // LW colortable
TIFFTAG_IT8IMAGECOLORINDICATOR = 34023; // BP/BL image color switch
TIFFTAG_IT8BKGCOLORINDICATOR = 34024; // BP/BL bg color switch
TIFFTAG_IT8IMAGECOLORVALUE = 34025; // BP/BL image color value
TIFFTAG_IT8BKGCOLORVALUE = 34026; // BP/BL bg color value
TIFFTAG_IT8PIXELINTENSITYRANGE = 34027; // MP pixel intensity value
TIFFTAG_IT8TRANSPARENCYINDICATOR = 34028; // HC transparency switch
TIFFTAG_IT8COLORCHARACTERIZATION = 34029; // color character. table
TIFFTAG_FRAMECOUNT = 34232; // Sequence Frame Count
TIFFTAG_JBIGOPTIONS = 34750; // JBIG options
TIFFTAG_FAXRECVPARAMS = 34908; // encoded class 2 ses. parms
TIFFTAG_FAXSUBADDRESS = 34909; // received SubAddr string
TIFFTAG_FAXRECVTIME = 34910; // receive time (secs)
TIFFTAG_DCSHUESHIFTVALUES = 65535; // hue shift correction data
TIFFTAG_FAXMODE = 65536; // Group 3/4 format control
FAXMODE_CLASSIC = $0000; // default, include RTC
FAXMODE_NORTC = $0001; // no RTC at end of data
FAXMODE_NOEOL = $0002; // no EOL code at end of row
FAXMODE_BYTEALIGN = $0004; // Byte align row
FAXMODE_WORDALIGN = $0008; // Word align row
FAXMODE_CLASSF = FAXMODE_NORTC; // TIFF class F
TIFFTAG_JPEGQUALITY = 65537; // compression quality level
TIFFTAG_JPEGCOLORMODE = 65538; // Auto RGB<=>YCbCr convert?
JPEGCOLORMODE_RAW = $0000; // no conversion (default)
JPEGCOLORMODE_RGB = $0001; // do auto conversion
TIFFTAG_JPEGTABLESMODE = 65539; // What to put in JPEGTables
JPEGTABLESMODE_QUANT = $0001; // include quantization tbls
JPEGTABLESMODE_HUFF = $0002; // include Huffman tbls
TIFFTAG_FAXFILLFUNC = 65540; // G3/G4 fill function
TIFFTAG_PIXARLOGDATAFMT = 65549; // PixarLogCodec I/O data sz
PIXARLOGDATAFMT_8BIT = 0; // regular u_char samples
PIXARLOGDATAFMT_8BITABGR = 1; // ABGR-order u_chars
PIXARLOGDATAFMT_11BITLOG = 2; // 11-bit log-encoded (raw)
PIXARLOGDATAFMT_12BITPICIO = 3; // as per PICIO (1.0==2048)
PIXARLOGDATAFMT_16BIT = 4; // signed short samples
PIXARLOGDATAFMT_FLOAT = 5; // IEEE float samples
TIFFTAG_DCSIMAGERTYPE = 65550; // imager model & filter
DCSIMAGERMODEL_M3 = 0; // M3 chip (1280 x 1024)
DCSIMAGERMODEL_M5 = 1; // M5 chip (1536 x 1024)
DCSIMAGERMODEL_M6 = 2; // M6 chip (3072 x 2048)
DCSIMAGERFILTER_IR = 0; // infrared filter
DCSIMAGERFILTER_MONO = 1; // monochrome filter
DCSIMAGERFILTER_CFA = 2; // color filter array
DCSIMAGERFILTER_OTHER = 3; // other filter
TIFFTAG_DCSINTERPMODE = 65551; // interpolation mode
DCSINTERPMODE_NORMAL = $0; // whole image, default
DCSINTERPMODE_PREVIEW = $1; // preview of image (384x256)
TIFFTAG_DCSBALANCEARRAY = 65552; // color balance values
TIFFTAG_DCSCORRECTMATRIX = 65553; // color correction values
TIFFTAG_DCSGAMMA = 65554; // gamma value
TIFFTAG_DCSTOESHOULDERPTS = 65555; // toe & shoulder points
TIFFTAG_DCSCALIBRATIONFD = 65556; // calibration file desc
TIFFTAG_ZIPQUALITY = 65557; // compression quality level
TIFFTAG_PIXARLOGQUALITY = 65558; // PixarLog uses same scale
TIFF_NOTYPE = 0; // placeholder
TIFF_BYTE = 1; // 8-bit unsigned integer
TIFF_ASCII = 2; // 8-bit bytes w/ last byte null
TIFF_SHORT = 3; // 16-bit unsigned integer
TIFF_LONG = 4; // 32-bit unsigned integer
TIFF_RATIONAL = 5; // 64-bit unsigned fraction
TIFF_SBYTE = 6; // 8-bit signed integer
TIFF_UNDEFINED = 7; // 8-bit untyped data
TIFF_SSHORT = 8; // 16-bit signed integer
TIFF_SLONG = 9; // 32-bit signed integer
TIFF_SRATIONAL = 10; // 64-bit signed fraction
TIFF_FLOAT = 11; // 32-bit IEEE floating point
TIFF_DOUBLE = 12; // 64-bit IEEE floating point
TIFF_BIGENDIAN = $4D4D;
TIFF_LITTLEENDIAN = $4949;
TIFF_VERSION = 42;
implementation
end.
|
(* PatternMatching: MM, 2020-03-18 *)
(* ------ *)
(* SImple pattern matching algorithms for strings *)
(* ========================================================================= *)
PROGRAM PatternMatching;
TYPE PatternMatcher = FUNCTION(s, p: STRING): INTEGER;
VAR charComps: INTEGER;
PROCEDURE Init;
BEGIN (* Init *)
charComps := 0;
END; (* Init *)
PROCEDURE WriteCharComps;
BEGIN (* WriteCharComps *)
Write(charComps);
END; (* WriteCharComps *)
FUNCTION Equals(a, b: CHAR): BOOLEAN;
BEGIN (* Equals *)
Inc(charComps);
Equals := a = b;
END; (* Equals *)
FUNCTION BruteSearchLR1(s, p: STRING): INTEGER;
VAR sLen, pLen: INTEGER;
i, j: INTEGER;
BEGIN (* BruteSearchLR1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
BruteSearchLR1 := 0;
END ELSE BEGIN
i := 1;
REPEAT
j := 1;
WHILE ((j <= pLen) AND (Equals(p[j], s[i + j - 1]))) DO BEGIN
Inc(j);
END; (* WHILE *)
Inc(i);
UNTIL ((j > pLen) OR (i > sLen - pLen + 1)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
BruteSearchLR1 := i - 1;
END ELSE BEGIN
BruteSearchLR1 := 0;
END; (* IF *)
END; (* IF *)
END; (* BruteSearchLR1 *)
FUNCTION BruteSearchLR2(s, p: STRING): INTEGER;
VAR sLen, pLen: INTEGER;
i, j: INTEGER;
BEGIN (* BruteSearchLR1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
BruteSearchLR2 := 0;
END ELSE BEGIN
i := 1;
j := 1;
REPEAT
IF (Equals(s[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
i := i - j + 2;
j := 1;
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
BruteSearchLR2 := i - pLen;
END ELSE BEGIN
BruteSearchLR2 := 0;
END; (* IF *)
END; (* IF *)
END; (* BruteSearchLR1 *)
FUNCTION KnutMorrisPratt1(s, p: STRING): INTEGER;
VAR next: ARRAY[1..255] OF INTEGER;
sLen, pLen: INTEGER;
i, j: INTEGER;
PROCEDURE InitNext;
BEGIN (* InitNext *)
i := 1;
j := 0;
next[1] := 0;
WHILE (i < pLen) DO BEGIN
IF ((j = 0) OR Equals(p[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
next[i] := j;
END ELSE BEGIN
j := next[j];
END; (* IF *)
END; (* WHILE *)
END; (* InitNext *)
BEGIN (* KnutMorrisPratt1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
KnutMorrisPratt1 := 0;
END ELSE BEGIN
InitNext;
i := 1;
j := 1;
REPEAT
IF (j = 0) OR (Equals(s[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
j := next[j];
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
KnutMorrisPratt1 := i - pLen;
END ELSE BEGIN
KnutMorrisPratt1 := 0;
END; (* IF *)
END; (* IF *)
END; (* KnutMorrisPratt2 *)
FUNCTION KnutMorrisPratt2(s, p: STRING): INTEGER;
VAR next: ARRAY[1..255] OF INTEGER;
sLen, pLen: INTEGER;
i, j: INTEGER;
PROCEDURE InitNext;
BEGIN (* InitNext *)
i := 1;
j := 0;
next[1] := 0;
WHILE (i < pLen) DO BEGIN
IF ((j = 0) OR Equals(p[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
IF (NOT Equals(p[i], p[j])) THEN
next[i] := j
ELSE
next[i] := next[j];
END ELSE BEGIN
j := next[j];
END; (* IF *)
END; (* WHILE *)
END; (* InitNext *)
BEGIN (* KnutMorrisPratt1 *)
sLen := Length(s);
pLen := Length(p);
IF (pLen = 0) OR (sLen = 0) OR (pLen > sLen) THEN BEGIN
KnutMorrisPratt2 := 0;
END ELSE BEGIN
InitNext;
i := 1;
j := 1;
REPEAT
IF (j = 0) OR (Equals(s[i], p[j])) THEN BEGIN
Inc(i);
Inc(j);
END ELSE BEGIN
j := next[j];
END; (* IF *)
UNTIL ((j > pLen) OR (i > sLen)); (* REPEAT *)
IF (j > pLen) THEN BEGIN
KnutMorrisPratt2 := i - pLen;
END ELSE BEGIN
KnutMorrisPratt2 := 0;
END; (* IF *)
END; (* IF *)
END; (* KnutMorrisPratt2 *)
PROCEDURE TestPatternMatcher(pm: PatternMatcher; pmName: STRING; s, p: STRING);
BEGIN (* TestPatternMatcher *)
Init;
Write(pmName, ': ', pm(s, p), ', comparisons: ');
WriteCharComps;
WriteLn();
END; (* TestPatternMatcher *)
var s, p: STRING;
BEGIN (* PatternMatching *)
REPEAT
Init;
Write('Enter s > ');
ReadLn(s);
Write('Enter p > ');
ReadLn(p);
TestPatternMatcher(BruteSearchLR1, 'BruteSearchLR1', s, p);
TestPatternMatcher(BruteSearchLR2, 'BruteSearchLR2', s, p);
TestPatternMatcher(KnutMorrisPratt1, 'KMP1', s, p);
TestPatternMatcher(KnutMorrisPratt2, 'KMP2', s, p);
UNTIL (s = ''); (* REPEAT *)
END. (* PatternMatching *) |
{-------------------------------------------------------------------------------
// 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 untEasyDBTool;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, untEasyPlateDBBaseForm, untEasyPageControl, ImgList,
untEasyStatusBar, untEasyStatusBarStylers, untEasyToolBar,
untEasyToolBarStylers, ActnList, ComCtrls, untEasyTreeView, ExtCtrls,
untEasyGroupBox, DB, DBClient, untEasyDBToolObject, untEasyDBToolUtil,
StdCtrls, Grids, untEasyBaseGrid, untEasyGrid, untEasyMemo;
//插件导出函数
function ShowBplForm(AParamList: TStrings): TForm; stdcall; exports ShowBplForm;
type
TfrmEasyDBTool = class(TfrmEasyPlateDBBaseForm)
pnlMain: TEasyPanel;
Splitter1: TSplitter;
EasyPanel1: TEasyPanel;
tvDataBase: TEasyTreeView;
EasyPanel2: TEasyPanel;
EasyPanel4: TEasyPanel;
actMain: TActionList;
actAcceptMail: TAction;
actSendMail: TAction;
actLinkMans: TAction;
EasyToolBarOfficeStyler1: TEasyToolBarOfficeStyler;
imgImportance: TImageList;
pgcDBDetail: TEasyPageControl;
cdsDataBases: TClientDataSet;
cdsTableField: TClientDataSet;
tsbTableField: TEasyTabSheet;
sgrdTableField: TEasyStringGrid;
EasyDockPanel1: TEasyDockPanel;
EasyToolBar1: TEasyToolBar;
btnNew: TEasyToolBarButton;
EasyToolBarButton3: TEasyToolBarButton;
EasyToolBarButton1: TEasyToolBarButton;
EasyToolBarButton2: TEasyToolBarButton;
EasyToolBarButton4: TEasyToolBarButton;
EasyToolBarButton5: TEasyToolBarButton;
EasyToolBarButton6: TEasyToolBarButton;
SaveDialog1: TSaveDialog;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure tvDataBaseDblClick(Sender: TObject);
procedure sgrdTableFieldGetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
procedure sgrdTableFieldGetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
procedure btnNewClick(Sender: TObject);
procedure EasyToolBarButton3Click(Sender: TObject);
procedure EasyToolBarButton1Click(Sender: TObject);
procedure EasyToolBarButton4Click(Sender: TObject);
procedure EasyToolBarButton2Click(Sender: TObject);
procedure EasyToolBarButton5Click(Sender: TObject);
procedure EasyToolBarButton6Click(Sender: TObject);
private
{ Private declarations }
FEasyDataBase,
FEasyTableField: TList;
FUnitContext : TStrings;
procedure InitFieldGrid;
procedure DisplayTableFieldGrid(AClientDataSet: TClientDataSet; ANode: TTreeNode);
//根据Grid中的字段名称生成对象
procedure GenerateObjFile(AObjPre: string; AType: Integer = 0);
procedure GenerateObjValueFile(AObjPre: string; AType: Integer = 0);
procedure AppendObjValueFile(AObjPre: string; AType: Integer = 0);
procedure EditObjValueFile(AObjPre: string; AType: Integer = 0);
procedure DeleteObjValueFile(AObjPre: string; AType: Integer = 0);
public
{ Public declarations }
end;
var
frmEasyDBTool: TfrmEasyDBTool;
implementation
{$R *.dfm}
uses
untEasyUtilMethod, TypInfo, untEasyDBToolObjectPas;
//引出函数实现
function ShowBplForm(AParamList: TStrings): TForm;
begin
frmEasyDBTool := TfrmEasyDBTool.Create(Application);
if frmEasyDBTool.FormStyle <> fsMDIChild then
frmEasyDBTool.FormStyle := fsMDIChild;
if frmEasyDBTool.WindowState <> wsMaximized then
frmEasyDBTool.WindowState := wsMaximized;
Result := frmEasyDBTool;
end;
procedure TfrmEasyDBTool.FormCreate(Sender: TObject);
begin
inherited;
FEasyDataBase := TList.Create;
FEasyTableField := TList.Create;
FUnitContext := TStringList.Create;
end;
procedure TfrmEasyDBTool.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
EasyFreeAndNilList(FEasyDataBase);
EasyFreeAndNilList(FEasyTableField);
FUnitContext.Free;
end;
procedure TfrmEasyDBTool.FormShow(Sender: TObject);
var
CurrDBNameSQL: string;
ATmpRoot,
ADBNode,
ATableNode: TTreeNode;
I : Integer;
begin
inherited;
CurrDBNameSQL := 'SELECT DB_NAME() AS DBName';
cdsDataBases.Data := EasyRDMDisp.EasyGetRDMData(CurrDBNameSQL);
ATmpRoot := tvDataBase.Items.Item[0]; //第一个节点必须存在
//当前数据库名称的节点
ADBNode := tvDataBase.Items.AddChild(ATmpRoot, cdsDataBases.fieldbyname('DBName').AsString);
ADBNode.ImageIndex := 1;
ADBNode.SelectedIndex := 1;
//取当前数据库下的所有数据表
cdsDataBases.Data := EasyRDMDisp.EasyGetRDMData(EASY_TABLE);
for I := 0 to cdsDataBases.RecordCount - 1 do
begin
ATableNode := tvDataBase.Items.AddChild(ADBNode, cdsDataBases.fieldbyname('Name').AsString);
ATableNode.ImageIndex := 6;
ATableNode.SelectedIndex := 7;
cdsDataBases.Next;
end;
tvDataBase.FullExpand;
end;
procedure TfrmEasyDBTool.tvDataBaseDblClick(Sender: TObject);
var
ATableName: string;
begin
inherited;
ATableName := tvDataBase.Selected.Text;
if tvDataBase.Selected.Level = 2 then
begin
//如果未加载过,则从数据库获取数据
if tvDataBase.Selected.Data = nil then
cdsTableField.Data := EasyRDMDisp.EasyGetRDMData(Format(EASY_TABLEFIELD, [ATableName]));
//刷新显示字段Grid
DisplayTableFieldGrid(cdsTableField, tvDataBase.Selected);
end;
end;
procedure TfrmEasyDBTool.InitFieldGrid;
begin
with sgrdTableField do
begin
Clear;
RowCount := 2;
FixedRows := 1;
ColumnHeaders.Add('');
ColumnHeaders.Add('<p align="center">字段名称</p>');
ColumnHeaders.Add('<p align="center">类型</p>');
ColumnHeaders.Add('<p align="center">长度</p>');
ColumnHeaders.Add('<p align="center">小数位数</p>');
ColumnHeaders.Add('<p align="center">主键</p>');
ColumnHeaders.Add('<p align="center">空否</p>');
ColumnHeaders.Add('<p align="center">默认值</p>');
ColumnHeaders.Add('<p align="center">说明</p>');
end;
end;
procedure TfrmEasyDBTool.DisplayTableFieldGrid(AClientDataSet: TClientDataSet; ANode: TTreeNode);
var
I: Integer;
begin
InitFieldGrid;
if ANode.Data = nil then
begin
for I := 0 to AClientDataSet.RecordCount - 1 do
begin
if I > 0 then sgrdTableField.AddRow;
with sgrdTableField do
begin
Cells[0, I + 1] := IntToStr(I + 1);
Cells[1, I + 1] := AClientDataSet.fieldbyname('FieldName').AsString;
Cells[2, I + 1] := AClientDataSet.fieldbyname('Type').AsString;
Cells[3, I + 1] := AClientDataSet.fieldbyname('Long').AsString;
Cells[4, I + 1] := AClientDataSet.fieldbyname('percent').AsString;
Cells[5, I + 1] := AClientDataSet.fieldbyname('PrimaryKey').AsString;
Cells[6, I + 1] := AClientDataSet.fieldbyname('IsNull').AsString;
Cells[7, I + 1] := AClientDataSet.fieldbyname('DefaultValue').AsString;
//Cells[8, I + 1] := AClientDataSet.fieldbyname('Comment').AsString;
end;
AClientDataSet.Next;
end;
end;
end;
procedure TfrmEasyDBTool.sgrdTableFieldGetAlignment(Sender: TObject; ARow,
ACol: Integer; var HAlign: TAlignment; var VAlign: TVAlignment);
begin
inherited;
VAlign := vtaCenter;
//列对齐方式
if ACol in [0, 5, 6] then
HAlign := taCenter;
end;
procedure TfrmEasyDBTool.sgrdTableFieldGetEditorType(Sender: TObject; ACol,
ARow: Integer; var AEditor: TEditorType);
begin
inherited;
if ACol = 2 then
begin
AEditor := edComboList;
with sgrdTableField do
begin
ClearComboString;
AddComboString('varchar');
AddComboString('datetime');
end;
end;
end;
procedure TfrmEasyDBTool.btnNewClick(Sender: TObject);
begin
inherited;
sgrdTableField.Options := sgrdTableField.Options + [goEditing];
end;
procedure TfrmEasyDBTool.EasyToolBarButton3Click(Sender: TObject);
begin
inherited;
DeleteObjValueFile('Easy');
end;
procedure TfrmEasyDBTool.GenerateObjFile(AObjPre: string; AType: Integer = 0);
var
I: Integer;
ATmpResult, ATmpPublicResult: TStrings;
begin
if tvDataBase.Selected = nil then Exit;
ATmpResult := TStringList.Create;
ATmpPublicResult := TStringList.Create;
ATmpResult.Add(' T' + AObjPre + tvDataBase.Selected.Text + ' = class');
//增加私有变量
ATmpResult.Add(' private');
ATmpResult.Add(' { Private declarations } ');
//增加公共属性
ATmpPublicResult.Add(' public');
ATmpPublicResult.Add(' { Public declarations } ');
for I := 0 to sgrdTableField.RowCount - 2 do
begin
with sgrdTableField do
begin
//字段类型
//varchar
if Cells[2, I + 1] = 'varchar' then
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'string;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'string'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
//int bigint
else if (Cells[2, I + 1] = 'int') or (Cells[2, I + 1] = 'bigint') then
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'Integer;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'Integer'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
//bit
else if Cells[2, I + 1] = 'bit' then
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'Boolean;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'Boolean'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
//decimal numeric
else if (Cells[2, I + 1] = 'decimal') then
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'Double;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'Double'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
//numeric
else if (Cells[2, I + 1] = 'numeric') then
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'Double;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'Double'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
//DateTime
else if Cells[2, I + 1] = 'datetime' then
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'TDateTime;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'TDateTime'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
//
else
begin
ATmpResult.Add(' F' + Cells[1, I + 1] + ': ' + 'EasyNULLType;');
ATmpPublicResult.Add(' property ' + Cells[1, I + 1] + ': ' + 'EasyNULLType'
+ ' read F' + Cells[1, I + 1] + ' write F' + Cells[1, I + 1] +';');
end
end;
end;
ATmpResult.Add(ATmpPublicResult.Text);
if AType = 1 then
begin
FUnitContext.Add('');
FUnitContext.AddStrings(ATmpResult);
end else
begin
frmEasyDBToolObjectPas := TfrmEasyDBToolObjectPas.Create(Self);
frmEasyDBToolObjectPas.mmResult.Lines.Text := ATmpResult.Text;
frmEasyDBToolObjectPas.ShowModal;
frmEasyDBToolObjectPas.Free;
end;
ATmpResult.Free;
ATmpPublicResult.Free;
end;
procedure TfrmEasyDBTool.GenerateObjValueFile(AObjPre: string; AType: Integer = 0);
var
I: Integer;
ATmpResult: TStrings;
begin
if tvDataBase.Selected = nil then Exit;
ATmpResult := TStringList.Create;
ATmpResult.Add('class procedure T' + AObjPre + tvDataBase.Selected.Text + '.Generate' + tvDataBase.Selected.Text
+'(var Data: OleVariant; AResult: TList)');
ATmpResult.Add('var');
ATmpResult.Add(' I: Integer;');
ATmpResult.Add(' A' + AObjPre + tvDataBase.Selected.Text + ': T' + AObjPre + tvDataBase.Selected.Text + ';');
ATmpResult.Add(' AClientDataSet: TClientDataSet;');
ATmpResult.Add('begin');
ATmpResult.Add(' //创建数据源,并获取数据');
ATmpResult.Add(' AClientDataSet := TClientDataSet.Create(nil);');
ATmpResult.Add(' AClientDataSet.Data := Data;');
ATmpResult.Add(' AClientDataSet.First;');
ATmpResult.Add(' try');
ATmpResult.Add(' for I := 0 to AClientDataSet.RecordCount - 1 do');
ATmpResult.Add(' begin');
ATmpResult.Add(' //此句为实例化指定的对象');
ATmpResult.Add(' A' + AObjPre + tvDataBase.Selected.Text
+ ' := T' + AObjPre + tvDataBase.Selected.Text + '.Create;');
ATmpResult.Add(' with ' + 'A' + AObjPre + tvDataBase.Selected.Text + ' do ');
ATmpResult.Add(' begin');
for I := 0 to sgrdTableField.RowCount - 2 do
begin
with sgrdTableField do
begin
ATmpResult.Add(' ' + '//' + IntToStr(I + 1) + ' ' + Cells[1, I + 1]);
//varchar
if Cells[2, I + 1] = 'varchar' then
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsString;')
//int bigint
else if (Cells[2, I + 1] = 'int') or (Cells[2, I + 1] = 'bigint') then
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsInteger;')
//bit
else if Cells[2, I + 1] = 'bit' then
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsBoolean;')
//decimal numeric
else if (Cells[2, I + 1] = 'decimal') then
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsFloat;')
//DateTime
else if Cells[2, I + 1] = 'datetime' then
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsDateTime;')
//numeric
else if (Cells[2, I + 1] = 'numeric') then
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsFloat;')
else
ATmpResult.Add(' ' + Cells[1, I + 1] + ' := ' + 'AClientDataSet.FieldByName('
+ '''' + Cells[1, I + 1] + '''' +').AsEasyNullType;');
end;
end;
ATmpResult.Add(' end;');
ATmpResult.Add(' //在此添加将对象存放到指定容器的代码');
ATmpResult.Add(' AResult.Add(A' + AObjPre + tvDataBase.Selected.Text + ');');
ATmpResult.Add(' //如果要关联树也在此添加相应代码');
ATmpResult.Add(' AClientDataSet.Next;');
ATmpResult.Add(' end;');
ATmpResult.Add(' finally');
ATmpResult.Add(' AClientDataSet.Free;');
ATmpResult.Add(' end;');
ATmpResult.Add('end;');
if AType = 1 then
begin
// FUnitContext.Add('');
FUnitContext.AddStrings(ATmpResult);
end else
begin
frmEasyDBToolObjectPas := TfrmEasyDBToolObjectPas.Create(Self);
frmEasyDBToolObjectPas.mmResult.Lines.Text := ATmpResult.Text;
frmEasyDBToolObjectPas.ShowModal;
frmEasyDBToolObjectPas.Free;
end;
ATmpResult.Free;
end;
procedure TfrmEasyDBTool.EasyToolBarButton1Click(Sender: TObject);
begin
inherited;
GenerateObjFile('Easy');
end;
procedure TfrmEasyDBTool.AppendObjValueFile(AObjPre: string; AType: Integer = 0);
var
I: Integer;
ATmpResult: TStrings;
ObjClassName: string;
begin
if tvDataBase.Selected = nil then Exit;
ATmpResult := TStringList.Create;
ObjClassName := 'T' + AObjPre + tvDataBase.Selected.Text;
ATmpResult.Add('class procedure ' + ObjClassName + '.AppendClientDataSet'
+ '(ACds: TClientDataSet; AObj: ' + ObjClassName + '; var AObjList: TList);');
ATmpResult.Add('begin');
ATmpResult.Add(' with ACds do');
ATmpResult.Add(' begin');
ATmpResult.Add(' Append;');
//
for I := 0 to sgrdTableField.RowCount - 2 do
begin
with sgrdTableField do
begin
ATmpResult.Add(' ' + '//' + IntToStr(I + 1) + ' ' + Cells[1, I + 1]);
//varchar
if Cells[2, I + 1] = 'varchar' then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsString := AObj.' + Cells[1, I + 1] + ';')
//int bigint
else if (Cells[2, I + 1] = 'int') or (Cells[2, I + 1] = 'bigint') then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsInteger := AObj.' + Cells[1, I + 1] + ';')
//bit
else if Cells[2, I + 1] = 'bit' then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsBoolean := AObj.' + Cells[1, I + 1] + ';')
//decimal numeric
else if (Cells[2, I + 1] = 'decimal') then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsFloat := AObj.' + Cells[1, I + 1] + ';')
//DateTime
else if Cells[2, I + 1] = 'datetime' then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsDateTime := AObj.' + Cells[1, I + 1] + ';')
//numeric
else if (Cells[2, I + 1] = 'numeric') then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsFloat := AObj.' + Cells[1, I + 1] + ';')
else
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsEasyNullType := AObj.' + Cells[1, I + 1] + ';');
end;
end;
ATmpResult.Add(' post;');
ATmpResult.Add(' end;');
ATmpResult.Add(' AObjList.Add(AObj);');
ATmpResult.Add('end;');
if AType = 1 then
begin
FUnitContext.Add('');
FUnitContext.AddStrings(ATmpResult);
end else
begin
frmEasyDBToolObjectPas := TfrmEasyDBToolObjectPas.Create(Self);
frmEasyDBToolObjectPas.mmResult.Lines.Text := ATmpResult.Text;
frmEasyDBToolObjectPas.ShowModal;
frmEasyDBToolObjectPas.Free;
end;
ATmpResult.Free;
end;
procedure TfrmEasyDBTool.DeleteObjValueFile(AObjPre: string; AType: Integer = 0);
var
ATmpResult: TStrings;
ObjClassName: string;
KeyField: string;
begin
if tvDataBase.Selected = nil then Exit;
ATmpResult := TStringList.Create;
KeyField := sgrdTableField.Cells[1, 1];
ObjClassName := 'T' + AObjPre + tvDataBase.Selected.Text;
ATmpResult.Add('class procedure ' + ObjClassName + '.DeleteClientDataSet'
+ '(ACds: TClientDataSet; AObj: ' + ObjClassName + ';'
+ ' var AObjList: TList);');
ATmpResult.Add('var');
ATmpResult.Add(' I,');
ATmpResult.Add(' DelIndex: Integer;');
ATmpResult.Add('begin');
ATmpResult.Add(' DelIndex := -1;');
ATmpResult.Add(' if ACds.Locate(''' + KeyField + ''', VarArrayOf([AObj.' + KeyField + ']), [loCaseInsensitive]) then');
ATmpResult.Add(' ACds.Delete;');
ATmpResult.Add(' for I := 0 to AObjList.Count - 1 do');
ATmpResult.Add(' begin');
ATmpResult.Add(' if ' + ObjClassName + '(AObjList[I]).' + KeyField + ' = ' + ObjClassName + '(AObj).' + KeyField + ' then');
ATmpResult.Add(' begin');
ATmpResult.Add(' DelIndex := I;');
ATmpResult.Add(' Break;');
ATmpResult.Add(' end;');
ATmpResult.Add(' end;');
ATmpResult.Add(' if DelIndex <> -1 then');
ATmpResult.Add(' begin');
ATmpResult.Add(' ' + ObjClassName + '(AObjList[DelIndex]).Free;');
ATmpResult.Add(' AObjList.Delete(DelIndex);');
ATmpResult.Add(' end; ');
ATmpResult.Add('end; ');
if AType = 1 then
begin
FUnitContext.Add('');
FUnitContext.AddStrings(ATmpResult);
end else
begin
frmEasyDBToolObjectPas := TfrmEasyDBToolObjectPas.Create(Self);
frmEasyDBToolObjectPas.mmResult.Lines.Text := ATmpResult.Text;
frmEasyDBToolObjectPas.ShowModal;
frmEasyDBToolObjectPas.Free;
end;
ATmpResult.Free;
end;
procedure TfrmEasyDBTool.EditObjValueFile(AObjPre: string; AType: Integer = 0);
var
I: Integer;
ATmpResult: TStrings;
ObjClassName: string;
KeyField: string;
begin
if tvDataBase.Selected = nil then Exit;
ATmpResult := TStringList.Create;
KeyField := sgrdTableField.Cells[1, 1];
ObjClassName := 'T' + AObjPre + tvDataBase.Selected.Text;
ATmpResult.Add('class procedure ' + ObjClassName + '.EditClientDataSet'
+ '(ACds: TClientDataSet; AObj: ' + ObjClassName + ';'
+ ' var AObjList: TList);');
ATmpResult.Add('begin');
ATmpResult.Add(' if ACds.Locate(''' + KeyField + ''', VarArrayOf([AObj.' + KeyField + ']), [loCaseInsensitive]) then');
ATmpResult.Add(' begin');
ATmpResult.Add(' with ACds do');
ATmpResult.Add(' begin');
ATmpResult.Add(' Edit;');
//
for I := 0 to sgrdTableField.RowCount - 2 do
begin
with sgrdTableField do
begin
ATmpResult.Add(' ' + '//' + IntToStr(I + 1) + ' ' + Cells[1, I + 1]);
//varchar
if Cells[2, I + 1] = 'varchar' then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsString := AObj.' + Cells[1, I + 1] + ';')
//int bigint
else if (Cells[2, I + 1] = 'int') or (Cells[2, I + 1] = 'bigint') then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsInteger := AObj.' + Cells[1, I + 1] + ';')
//bit
else if Cells[2, I + 1] = 'bit' then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsBoolean := AObj.' + Cells[1, I + 1] + ';')
//decimal numeric
else if (Cells[2, I + 1] = 'decimal') then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsFloat := AObj.' + Cells[1, I + 1] + ';')
//DateTime
else if Cells[2, I + 1] = 'DateTime' then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsDateTime := AObj.' + Cells[1, I + 1] + ';')
//numeric
else if (Cells[2, I + 1] = 'numeric') then
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsFloat := AObj.' + Cells[1, I + 1] + ';')
else
ATmpResult.Add(' ' + 'FieldByName(' + '''' + Cells[1, I + 1] + ''''
+').AsEasyNullType := AObj.' + Cells[1, I + 1] + ';');
end;
end;
ATmpResult.Add(' post;');
ATmpResult.Add(' end;');
ATmpResult.Add(' end;');
ATmpResult.Add('end;');
if AType = 1 then
begin
FUnitContext.Add('');
FUnitContext.AddStrings(ATmpResult);
end else
begin
frmEasyDBToolObjectPas := TfrmEasyDBToolObjectPas.Create(Self);
frmEasyDBToolObjectPas.mmResult.Lines.Text := ATmpResult.Text;
frmEasyDBToolObjectPas.ShowModal;
frmEasyDBToolObjectPas.Free;
end;
ATmpResult.Free;
end;
procedure TfrmEasyDBTool.EasyToolBarButton4Click(Sender: TObject);
begin
inherited;
AppendObjValueFile('Easy');
end;
procedure TfrmEasyDBTool.EasyToolBarButton2Click(Sender: TObject);
begin
inherited;
EditObjValueFile('Easy');
end;
procedure TfrmEasyDBTool.EasyToolBarButton5Click(Sender: TObject);
begin
inherited;
GenerateObjValueFile('Easy');
end;
procedure TfrmEasyDBTool.EasyToolBarButton6Click(Sender: TObject);
var
ObjClassName: string;
begin
inherited;
if tvDataBase.Selected = nil then Exit;
FUnitContext.Clear;
ObjClassName := 'T' + 'Easy' + tvDataBase.Selected.Text;
SaveDialog1.FileName := 'untEasyClass' + tvDataBase.Selected.Text;
if SaveDialog1.Execute then
begin
FUnitContext.Add('{-------------------------------------------------------------------------------');
FUnitContext.Add('// EasyComponents For Delphi 7 ');
FUnitContext.Add('// 一轩软研第三方开发包 ');
FUnitContext.Add('// @Copyright 2010 hehf ');
FUnitContext.Add('// ------------------------------------ ');
FUnitContext.Add('// ');
FUnitContext.Add('// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何');
FUnitContext.Add('// 人不得外泄,否则后果自负. ');
FUnitContext.Add('// ');
FUnitContext.Add('// 使用权限以及相关解释请联系何海锋 ');
FUnitContext.Add('// ');
FUnitContext.Add('// ');
FUnitContext.Add('// 网站地址:http://www.YiXuan-SoftWare.com ');
FUnitContext.Add('// 电子邮件:hehaifeng1984@126.com ');
FUnitContext.Add('// YiXuan-SoftWare@hotmail.com ');
FUnitContext.Add('// QQ :383530895 ');
FUnitContext.Add('// MSN :YiXuan-SoftWare@hotmail.com ');
FUnitContext.Add('//------------------------------------------------------------------------------');
FUnitContext.Add('//单元说明: ');
FUnitContext.Add('// ');
FUnitContext.Add('//主要实现: ');
FUnitContext.Add('//-----------------------------------------------------------------------------}');
FUnitContext.Add('unit untEasyClass' + tvDataBase.Selected.Text + ';');
FUnitContext.Add('');
FUnitContext.Add('interface');
FUnitContext.Add('');
FUnitContext.Add('uses');
FUnitContext.Add(' Classes, DB, DBClient, Variants;');
FUnitContext.Add('');
FUnitContext.Add('type');
//class type
GenerateObjFile('Easy', 1);
FUnitContext.Add('');
//Append, edit, delete, Generate
FUnitContext.Add(' class procedure Generate' + tvDataBase.Selected.Text
+'(var Data: OleVariant; AResult: TList);');
FUnitContext.Add(' class procedure AppendClientDataSet'
+ '(ACds: TClientDataSet; AObj: ' + ObjClassName + '; var AObjList: TList);');
FUnitContext.Add(' class procedure EditClientDataSet'
+ '(ACds: TClientDataSet; AObj: ' + ObjClassName + ';'
+ ' var AObjList: TList);');
FUnitContext.Add(' class procedure DeleteClientDataSet'
+ '(ACds: TClientDataSet; AObj: ' + ObjClassName + ';'
+ ' var AObjList: TList);');
FUnitContext.Add(' end;');
FUnitContext.Add('');
FUnitContext.Add('implementation');
FUnitContext.Add('');
FUnitContext.Add('{' + ObjClassName +'}');
GenerateObjValueFile('Easy', 1);
//Append, edit, delete
AppendObjValueFile('Easy', 1);
EditObjValueFile('Easy', 1);
DeleteObjValueFile('Easy', 1);
FUnitContext.Add('');
FUnitContext.Add('end.');
if pos('.pas', SaveDialog1.FileName) > 0 then
FUnitContext.SaveToFile(SaveDialog1.FileName)
else
FUnitContext.SaveToFile(SaveDialog1.FileName + '.pas');
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit NewStdAc;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ExtCtrls, ComCtrls, ActnList;
type
TNewStdActionDlg = class(TForm)
HelpBtn: TButton;
OKBtn: TButton;
CancelBtn: TButton;
ActionList1: TActionList;
AcceptAction: TAction;
ActionTree: TTreeView;
Label1: TLabel;
procedure HelpBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ActionListCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure ActionListDblClick(Sender: TObject);
procedure AcceptActionUpdate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FSortColumn: Integer;
procedure AddAction(const Category: string; ActionClass: TBasicActionClass;
Info: Pointer);
function GetRegKey: string;
procedure ReadSettings;
procedure WriteSettings;
end;
implementation
{$R *.dfm}
uses DsnConst, Registry;
procedure TNewStdActionDlg.HelpBtnClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TNewStdActionDlg.AddAction(const Category: string;
ActionClass: TBasicActionClass; Info: Pointer);
var
Node: TTreeNode;
ACat: String;
begin
Node := nil;
ACat := Category;
if Length(ACat) = 0 then
ACat := SActionCategoryNone;
if ActionTree.Items.Count > 0 then
begin
Node := ActionTree.Items[0];
while Assigned(Node) do
if AnsiCompareText(Node.Text, ACat) = 0 then
Break
else
Node := Node.getNextSibling;
end;
if not Assigned(Node) then
Node := ActionTree.Items.AddObject(nil, ACat, nil);
ActionTree.Items.AddChildObject(Node, ActionClass.ClassName, Pointer(ActionClass));
Node.Expanded := True;
end;
function TNewStdActionDlg.GetRegKey: string;
begin
// Result := Designer.GetBaseRegKey + '\' + sIniEditorsName + '\ActionList Editor';
end;
procedure TNewStdActionDlg.ReadSettings;
var
I: Integer;
begin
{ with TRegIniFile.Create(GetRegKey) do
try
I := ReadInteger('StandardActionsDlg', 'Width', Width);
if I <= Screen.Width then
Width := I;
I := ReadInteger('StandardActionsDlg', 'Height', Height);
if I <= Screen.Height then
Height := I;
finally
Free;
end;}
end;
procedure TNewStdActionDlg.WriteSettings;
begin
{ with TRegIniFile.Create(GetRegKey) do
begin
EraseSection('StandardActionsDlg');
WriteInteger('StandardActionsDlg', 'Width', Width);
WriteInteger('StandardActionsDlg', 'Height', Height);
end;}
end;
procedure TNewStdActionDlg.FormCreate(Sender: TObject);
var
Item: TTreeNode;
begin
ReadSettings;
ActionTree.Items.BeginUpdate;
try
EnumRegisteredActions(AddAction, nil);
// ActionTree.AlphaSort;
finally
ActionTree.Items.EndUpdate;
end;
if ActionTree.Items.Count > 1 then
Item := ActionTree.Items[1]
else
Item := ActionTree.Items[0];
if Item <> nil then
begin
Item.Selected := True;
Item.Focused := True;
end;
end;
procedure TNewStdActionDlg.FormShow(Sender: TObject);
begin
ActionTree.SetFocus;
end;
procedure TNewStdActionDlg.ActionListCompare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if Abs(FSortColumn) = 1 then
Compare := FSortColumn * AnsiCompareText(Item1.Caption, Item2.Caption) else
Compare := FSortColumn * AnsiCompareText(Item1.SubItems[0], Item2.SubItems[0]);
end;
procedure TNewStdActionDlg.ActionListDblClick(Sender: TObject);
begin
if OKBtn.Enabled then OKBtn.Click;
end;
procedure TNewStdActionDlg.AcceptActionUpdate(Sender: TObject);
begin
AcceptAction.Enabled := ActionTree.SelectionCount > 0;
end;
procedure TNewStdActionDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
WriteSettings;
end;
end.
|
unit Principal;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, ZConnection,
mORMotSQLite3, mORMot, mORMotHttpServer, SynCommons,SynSQLite3Static,
SynDB, SynDBZeos, SynOleDB, mORMotDB, Types, SynCrypto, uAutenricacaoJWT,
SynEcc;
type
{ TTesteServicos }
TTesteServicos = class( TSQLRestServerFullMemory)
private
fJWT: TJWTAbstract;
public
procedure TesteJWT(Ctxt: TSQLRestServerURIContext);
procedure URI(var Call: TSQLRestURIParams); override;
procedure AfterConstruction; override;
end;
{ TForm1 }
TForm1 = class(TForm)
btnCriarBase: TButton;
btnCriarBase1: TButton;
btnIniciarServidor: TButton;
Button1: TButton;
Memo1: TMemo;
ZConnection1: TZConnection;
procedure btnCriarBase1Click(Sender: TObject);
procedure btnCriarBase1ContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
procedure btnCriarBaseClick(Sender: TObject);
procedure btnIniciarServidorClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
FModeloDados: TSQLModel;
ModeloServicos:TSQLModel;
FBaseDados: TSQLRestServerDB;
FServidorHTTP: TSQLHttpServer;
ServidorServicos: TTesteServicos;
procedure ConfigurarLog;
procedure InicializarBancoDeDados;
procedure InicializarServidorHTTP;
procedure InicializarServicos;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
uses
DAO;
{ TTesteServicos }
procedure TTesteServicos.TesteJWT(Ctxt: TSQLRestServerURIContext);
begin
if Ctxt.AuthenticationCheck(fJWT) then
Ctxt.ReturnFileFromFolder('C:\JavaScript');
end;
procedure TTesteServicos.URI(var Call: TSQLRestURIParams);
var
url: string;
begin
inherited URI(Call);
url := call.Url;
if pos('services/calculadora.somar', url) > 0 then
begin
ShowMessage('Pode passar');
raise exception.create('Erro');
end;
end;
procedure TTesteServicos.AfterConstruction;
begin
inherited AfterConstruction;
fJWT := TJWTHS256.Create('secret',0,[jrcSubject],[]);
end;
procedure TForm1.btnIniciarServidorClick(Sender: TObject);
begin
InicializarServidorHTTP;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
// fConnection: TSQLDBZEOSConnectionProperties;
iRows: ISQLDBRows;
Row: Variant;
intRowCount: integer;
PropsPostgreSQL : TSQLDBZEOSConnectionProperties;
begin
PropsPostgreSQL := TSQLDBZEOSConnectionProperties.Create(
TSQLDBZEOSConnectionProperties.URI(dPostgreSQL,'localhost:5432'),
'budega','postgres','postgres!');
FModeloDados := TSQLModel.Create([TSQLGrupo,TSQLProduto]);
VirtualTableExternalRegister(FModeloDados, [TSQLGrupo, TSQLProduto], PropsPostgreSQL);
FBaseDados := TSQLRestServerDB.Create(FModeloDados, ':memory:');
// Atualizará o esquema da base de dados de acordo
// com o modelo.
FBaseDados.CreateMissingTables(0);
{
Props := TOleDBMSSQL2005ConnectionProperties.Create('.\SQLEXPRESS', 'TestDatabase', 'UserName', 'Password');
Model := TSQLModel.Create([TMovie, TBook]);
VirtualTableExternalRegister(Model, [TMovie, TBook], Props);
// Usual connection method
//fConnection := TSQLDBZEOSConnectionProperties.Create('postgres', 'sakila dvdrental', 'postgres', 'password');
// URI method
fConnection := TSQLDBZEOSConnectionProperties.Create(TSQLDBZEOSConnectionProperties.URI(dPostgreSQL, 'localhost:5432'),
'sakila dvdrental', 'postgres', 'password');
//
try
//
intRowCount := 0;
//
iRows := fConnection.Execute(cboQueries.Text, [], @Row);
//
while iRows.Step do
begin
Inc(intRowCount);
//
ShowMessage('ID : ' + IntToStr(Row.Actor_id) + LineEnding +
'FirstName : ' + Row.First_Name + LineEnding +
'LastName : ' + Row.Last_Name + LineEnding +
'LastUpdate : ' + DateTimeToStr(Row.Last_Update));
//
if intRowCount = 5 then break;
end;
finally
fConnection.Free;
end;
}
end;
procedure TForm1.btnCriarBaseClick(Sender: TObject);
begin
ConfigurarLog;
InicializarBancoDeDados;
InicializarServicos;
end;
procedure TForm1.btnCriarBase1ContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
begin
end;
procedure TForm1.btnCriarBase1Click(Sender: TObject);
var j: TJWTAbstract;
jwt: TJWTContent;
begin
j := TJWTHS256.Create('secret',0,[jrcSubject],[]);
try
j.Verify('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibm'+
'FtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeF'+
'ONFh7HgQ',jwt); // reference from jwt.io
Memo1.Lines.Add((jwt.result=jwtValid).ToString());
Memo1.Lines.Add((jwt.reg[jrcSubject]='12345678901').ToString());
Memo1.Lines.Add((jwt.data.U['name']='John Doe').ToString());
Memo1.Lines.Add((jwt.data.B['admin']).ToString());
finally
j.Free;
end;
end;
procedure TForm1.ConfigurarLog;
begin
TSQLLog.Family.Level := [TSynLogInfo.sllTrace];
end;
procedure TForm1.InicializarBancoDeDados;
var
Props : TOleDBMSSQL2008ConnectionProperties ;
begin
// Cria o modelo da base de dados contendo a classe/tabela
// TSQLPessoa
Props := TOleDBMSSQL2008ConnectionProperties.Create( '.', 'mORMot', 'sa', '');
FModeloDados := TSQLModel.Create([TSQLGrupo,TSQLProduto]);
VirtualTableExternalRegister(FModeloDados, [TSQLGrupo, TSQLProduto], Props);
FBaseDados := TSQLRestServerDB.Create(FModeloDados, ':memory:');
// FBaseDados := TSQLRestServerDB.Create(FModeloDados, 'mormot.db3');
// Atualizará o esquema da base de dados de acordo
// com o modelo.
FBaseDados.CreateMissingTables(0);
end;
procedure TForm1.InicializarServidorHTTP;
begin
// TOleDBMSSQL2005ConnectioçProperties;
FServidorHTTP := TSQLHttpServer.Create('8081', [FBaseDados,ServidorServicos]);
end;
procedure TForm1.InicializarServicos;
begin
ModeloServicos := TSQLModel.Create([],'services');
ServidorServicos := TTesteServicos.Create(ModeloServicos);
ServidorServicos.ServiceRegister(TCalculadora,[TypeInfo(ICalculadora)], sicShared);
end;
end.
|
{ **************************************************************
Package: XWB - Kernel RPCBroker
Date Created: Sept 18, 1997 (Version 1.1)
Site Name: Oakland, OI Field Office, Dept of Veteran Affairs
Developers: Danila Manapsal, Don Craven, Joel Ivey
Description: Contains TRPCBroker and related components.
Unit: MFunStr functions that emulate MUMPS functions.
Current Release: Version 1.1 Patch 65
*************************************************************** }
{ **************************************************
Changes in v1.1.65 (HGW 06/13/2016) XWB*1.1*65
1. Added function RemoveCRLF to strip CR and LF from a string.
Changes in v1.1.60 (HGW 12/18/2013) XWB*1.1*60
1. Reformated indentation and comments to make code more readable.
Changes in v1.1.50 (JLI 9/1/2011) XWB*1.1*50
1. None.
************************************************** }
unit MFunStr;
interface
uses
{System}
System.SysUtils,
{Vcl}
Vcl.Dialogs;
{procedure and function prototypes}
function Piece(x: string; del: string; piece1: integer = 1; piece2: integer=0): string;
function Translate(passedString, identifier, associator: string): string;
function RemoveCRLF(const aString: string): string;
const
U: string = '^';
implementation
{--------------------- Translate ---------------------------------
function TRANSLATE(string,identifier,associator)
Performs a character-for-character replacement within a string.
------------------------------------------------------------------}
function Translate(passedString, identifier, associator: string): string;
{}
var
index, position: integer;
newString: string;
substring: string;
begin
newString := ''; {initialize NewString}
for index := 1 to length(passedString) do
begin
substring := copy(passedString,index,1);
position := pos(substring,identifier);
if position > 0 then
newString := newString + copy(associator,position,1)
else
newString := newString + copy(passedString,index,1)
end;
result := newString;
end; //function Translate
{--------------------- Piece -------------------------------------
function PIECE(string,delimiter,piece number)
Returns a field within a string using the specified delimiter.
------------------------------------------------------------------}
function Piece(x: string; del: string; piece1: integer = 1; piece2: integer=0) : string;
var
delIndex,pieceNumber: integer;
Resval: String;
Str: String;
begin
{initialize variables}
pieceNumber := 1;
Str := x;
{delIndex :=1;}
if piece2 = 0 then
piece2 := piece1;
Resval := '';
repeat
delIndex := Pos(del,Str);
if (delIndex > 0) or ((pieceNumber > Pred(piece1)) and (pieceNumber < (piece2+1))) then
begin
if (pieceNumber > Pred(piece1)) and (pieceNumber < (piece2+1)) then
begin
if (pieceNumber > piece1) and (Str <> '') then
Resval := Resval + del;
if delIndex > 0 then
begin
Resval := Resval + Copy(Str,1,delIndex-1);
Str := Copy(Str,delIndex+Length(del),Length(Str));
end
else
begin
Resval := Resval + Str;
Str := '';
end;
end
else
Str := Copy(Str,delIndex+Length(del),Length(Str));
end
else if Str <> '' then
Str := '';
inc(pieceNumber);
until (pieceNumber > piece2);
Result := Resval;
end; //function Piece
{--------------------- RemoveCRLF --------------------------------
function REMOVECRLF(string)
Removes CR and LF characters from a a string.
------------------------------------------------------------------}
function RemoveCRLF(const aString: string): string;
var
i, j: integer;
begin
result := aString;
j := 0;
for i := 1 to Length(result) do
begin
if (not CharInSet(result[i], [#10,#13])) then
begin
inc (j);
result[j] := result[i]
end;
end;
SetLength(result, j);
end; //function RemoveCRLF
end.
|
unit FIToolkit.CommandLine.Options;
interface
uses
System.Generics.Collections,
FIToolkit.CommandLine.Types;
type
TCLIOption = record
private
type
TCLIOptionTokens = record
Delimiter,
Name,
Prefix,
Value : String;
end;
strict private
FOptionString : TCLIOptionString;
FOptionTokens : TCLIOptionTokens;
private
procedure Parse(const AOptionString : TCLIOptionString; const APrefix, ADelimiter : String;
out Tokens : TCLIOptionTokens);
public
class operator Implicit(const Value : String) : TCLIOption;
class operator Implicit(Value : TCLIOption) : String;
constructor Create(const AOptionString : TCLIOptionString); overload;
constructor Create(const AOptionString : TCLIOptionString; const APrefix, ADelimiter : String); overload;
function HasDelimiter : Boolean;
function HasNonEmptyValue : Boolean;
function HasPrefix : Boolean;
function IsEmpty : Boolean;
function ToString : TCLIOptionString;
function ValueContainsSpaces : Boolean;
property Delimiter : String read FOptionTokens.Delimiter;
property Name : String read FOptionTokens.Name;
property OptionString : TCLIOptionString read FOptionString;
property Prefix : String read FOptionTokens.Prefix;
property Value : String read FOptionTokens.Value;
end;
TCLIOptions = class (TList<TCLIOption>)
public
function ToString : String; override; final;
public
function AddUnique(Value : TCLIOption; IgnoreCase : Boolean) : Integer;
function Contains(const OptionName : String; IgnoreCase : Boolean) : Boolean; overload;
function Find(const OptionName : String; out Value : TCLIOption; IgnoreCase : Boolean) : Boolean;
end;
implementation
uses
System.SysUtils, System.Types,
FIToolkit.CommandLine.Exceptions, FIToolkit.CommandLine.Consts, FIToolkit.Commons.Utils;
{ TCLIOption }
constructor TCLIOption.Create(const AOptionString : TCLIOptionString; const APrefix, ADelimiter : String);
begin
FOptionString := AOptionString;
Parse(FOptionString, APrefix, ADelimiter, FOptionTokens);
end;
constructor TCLIOption.Create(const AOptionString : TCLIOptionString);
begin
Create(AOptionString, STR_CLI_OPTION_PREFIX, STR_CLI_OPTION_DELIMITER);
end;
function TCLIOption.HasDelimiter : Boolean;
begin
Result := not FOptionTokens.Delimiter.IsEmpty;
end;
function TCLIOption.HasNonEmptyValue : Boolean;
begin
Result := not FOptionTokens.Value.IsEmpty;
end;
function TCLIOption.HasPrefix : Boolean;
begin
Result := not FOptionTokens.Prefix.IsEmpty;
end;
class operator TCLIOption.Implicit(const Value : String) : TCLIOption;
begin
Result := TCLIOption.Create(Value);
end;
class operator TCLIOption.Implicit(Value : TCLIOption) : String;
begin
Result := Value.ToString;
end;
function TCLIOption.IsEmpty : Boolean;
begin
Result := FOptionTokens.Name.IsEmpty;
end;
procedure TCLIOption.Parse(const AOptionString : TCLIOptionString; const APrefix, ADelimiter : String;
out Tokens : TCLIOptionTokens);
var
S : String;
iPrefixPos, iDelimiterPos : Integer;
begin
S := AOptionString;
iPrefixPos := S.IndexOf(APrefix);
iDelimiterPos := S.IndexOf(ADelimiter);
if String.IsNullOrWhiteSpace(S) then
raise ECLIOptionIsEmpty.Create;
Tokens := Default(TCLIOptionTokens);
with Tokens do
begin
Prefix := Iff.Get<String>(not String.IsNullOrWhiteSpace(APrefix) and
S.StartsWith(APrefix), APrefix, String.Empty);
Delimiter := Iff.Get<String>(not String.IsNullOrWhiteSpace(ADelimiter) and
(iDelimiterPos > iPrefixPos), ADelimiter, String.Empty);
iPrefixPos := Iff.Get<Integer>(Prefix.IsEmpty, -1, iPrefixPos);
iDelimiterPos := Iff.Get<Integer>(Delimiter.IsEmpty, -1, iDelimiterPos);
Name := Iff.Get<String>(
Delimiter.IsEmpty,
S.Substring(iPrefixPos + Prefix.Length),
S.Substring(iPrefixPos + Prefix.Length, iDelimiterPos - (iPrefixPos + Prefix.Length))
);
Value := Iff.Get<String>(
Delimiter.IsEmpty,
String.Empty,
S.Substring(iDelimiterPos + Delimiter.Length)
);
end;
if Tokens.Name.IsEmpty then
raise ECLIOptionHasNoName.Create;
end;
function TCLIOption.ToString : TCLIOptionString;
begin
with FOptionTokens do
Result := Prefix + Name + Delimiter +
Iff.Get<String>(ValueContainsSpaces, Value.QuotedString(TCLIOptionString.CHR_QUOTE), Value);
end;
function TCLIOption.ValueContainsSpaces : Boolean;
begin
Result := FOptionTokens.Value.Contains(TCLIOptionString.CHR_SPACE);
end;
{ TCLIOptions }
function TCLIOptions.AddUnique(Value : TCLIOption; IgnoreCase : Boolean) : Integer;
var
Option : TCLIOption;
begin
if Find(Value.Name, Option, IgnoreCase) then
Result := IndexOf(Option)
else
Result := Add(Value);
end;
function TCLIOptions.Contains(const OptionName : String; IgnoreCase : Boolean) : Boolean;
var
Option : TCLIOption;
begin
Result := Find(OptionName, Option, IgnoreCase);
end;
function TCLIOptions.Find(const OptionName : String; out Value : TCLIOption; IgnoreCase : Boolean) : Boolean;
var
Option : TCLIOption;
begin
Result := False;
for Option in Self do
if String.Compare(Option.Name, OptionName, IgnoreCase) = EqualsValue then
begin
Value := Option;
Exit(True);
end;
end;
function TCLIOptions.ToString : String;
var
Option : TCLIOption;
begin
Result := String.Empty;
for Option in Self do
Result := Result + Option + STR_CLI_OPTIONS_DELIMITER;
Result := Result.TrimRight;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXClientResStrs;
interface
resourcestring
SAreYouSurePolicy = 'Are you sure you want to delete the access policy from line %d ?';
SNewPolicyCaption = 'New access policy';
SMaxSizeBlock = 'File content exceeds the current block size limit of 4 MB';
SMaxSize = 'Block blob content is limited to maximum 64 MB';
SAzureBlobs = 'Azure Blobs';
SNodeLoading = 'Loading...';
SACL = 'Access Control List';
SPageRegions = 'Page Regions';
SBlockList = 'Block List';
SMetadata = 'Metadata';
SProperties = 'Properties';
SSignedIdentifier = 'Signed Identifier';
SBlobPublicAccess = 'Blob Public Access';
SContentLength = 'Content Length';
SCommittedBlocks = 'Committed Blocks';
SUncommittedBlocks = 'Uncommitted Blocks';
SCreateRootContainer = 'Create Root Container';
SCreateContainer = 'Create Container';
SRefresh = 'Refresh';
SActivate = 'Activate';
SDeleteRootContainer = 'Delete Root Container';
SRootContainerDeleteFailure = 'Root Container deletion failed with code: %d. A possible solution is to try again after a refresh.';
SRootContainerCreateFailure = 'Root Container creation failed with code: %d. A possible solution is to try again after a refresh.';
SContainerCreateFailure = 'Container''s %s creation failed with code: %d';
SCreateRootContainerTitle = 'Create root container';
SCreateNewContainerTitle = 'Create a new container';
SCreateBlockBlob = 'Create Block Blob';
SCreatePageBlob = 'Create Page Blob';
SCreateBlockBlobCaption = 'Create a Block Blob in %s container';
SCreatePageBlobCaption = 'Create a Page Blob in %s container';
SLongTimeOperation = 'Please allow 10 minutes per MB for the operation to complete';
SAreYouSure = 'You are about to delete of %s %s. Proceed with it?';
SRootContainer = 'root container';
SContainer = 'container';
SBlob = 'blob';
SBlobPageItem = 'Add Page';
SBlobPageCaption = 'Page management for %s/%s blob';
SBlobBlockItem = 'Add Block';
SBlobBlockCaption = 'Block management for %s/%s blob';
SDeleteContainer = 'Delete Container';
SDeleteBlob = 'Delete Blob';
SDeleteContainerMsg = 'You are about to delete the %s container and all its content. Proceed with the deletion?';
SDeleteBlobMsg = 'You are about to delete the blob %s from the %s container. Proceed with the deletion?';
SDeleteContainerFailure = 'Container %s deletion failed with code %d.';
SDeleteBlobFailure = 'Blob %s/%s deletion attempt failed with code %d.';
SIsBusy = 'No more new operations are allowed until the completion of the previous one';
SIsBusyItem = 'Busy...';
SMetadataItem = 'Edit Metadata';
SMetadataBlobFailure = 'Blob''s %s/%s metadata access failed. Error code is: %d.';
SMetadataBlobCaption = 'Edit Blob %s/%s Metadata';
SMetadataContainerFailure = 'Container''s %s metadata access failed. Error code is: %d.';
SMetadataContainerCaption = 'Edit Container %s Metadata';
SPropertiesFailure = 'Accessing the properties of %s/%s blob failed. Error code is: %d.';
SPropertiesCaption = 'Properties of %s/%s';
SACLItem = 'Edit Access Control List';
SSnapshotItem = 'Create Snapshot';
SSnapshotCaption = 'Create snapshot of %s/%s';
SCopyBlob = 'Copy';
SCopyBlobCaption = 'Copy blob %s/%s into...';
SDestContainerNotFound = 'The destination container %s cannot be found. You can create it or refresh the storage content';
SDownloadItem = 'Download';
SOverrideFile = 'Are you sure you want to change the content of %s?';
SCommitBlockList = 'Commit Block List';
SCommitBlockListCaption = 'Commit block list for blob %s/%s';
SCommitBlockListFailure = 'Committing the block list of %s/%s failed. Error code is: %d.';
SBlockListIsEmpty = 'The block list is empty for blob %s/%s. Please use %s to add blocks into it and then commit them.';
SLeaseItem = 'Lease...';
SLeaseAcquire = 'Acquire';
SCopyLeaseId = 'Copy Lease ID';
SLeaseRenew = 'Renew';
SLeaseRelease = 'Release';
SLeaseBreak = 'Break';
SLeaseAcquireNotice = 'Lease on %s/%s is aquired for %d seconds';
SLeaseBreakNotice = 'Lease on %s/%s is broken, a new lease can be acquired in %d seconds';
SLeaseRenewNotice = 'Lease on %s/%s is renewed for another %d seconds';
SLeaseReleaseNotice = 'Lease on %s/%s is released';
SUpdateBlockBlob = 'Update Blob Content';
SUpdateBlockBlobCaption = 'Update blob''s %s/%s content';
SErrorGeneric = 'Cloud access error. ';
SOKUpdateCaption = 'Update';
SOKCreateCaption = 'Create';
SNodeAzureQueueRoot = 'Azure Queues';
SMoreMessages = 'Plus %d More...';
SAddQueue = 'Add Queue';
SRemoveQueue = 'Remove Queue';
SQueueMetadataTitle = 'Azure Queue Metadata';
SQueueMetadata = 'Queue Metadata';
SClearQueueMessages = 'Clear Messages';
SAddMessage = 'Add Message';
SRemoveMessage = 'Remove Message';
SAddQueueError = 'Failed to add Queue: %s';
SQueueMetadataError = 'Queue Metadata operation failed for: %s';
SDeleteQueueError = 'Failed to remove Queue: %s';
SAddQueueTitle = 'Add Queue';
SAddQueueMessage = 'Enter New Queue Name:';
SAddMsgTitle = 'Add Message';
SAddMsgMessage = 'Enter Message:';
SAddQueueMessageError = 'Failed to add Message to Queue: %s';
SRemoveQueueMessageError = 'Failed to remove Message(s) from Queue: %s';
SNodeAzureTableRoot = 'Azure Tables';
SAddTableMessage = 'Enter New Table Name:';
SAddTable = 'Add Table';
SRemoveTable = 'Delete Table';
SViewTableData = 'View Data';
SAddTableError = 'Failed to add Table: %s';
SDeleteTableError = 'Failed to remove Table: %s';
STableEditorTitle = 'Azure Table Editor';
STableEditorTitle2 = 'Azure Table Editor: %s';
SMoreTables = 'Load More';
SNewEntityTitle = '[new entity]';
SAddTableEntity = 'Add Entity';
SDeleteTableEntity = 'Delete Entity';
SDeleteEntityError = 'Failed to remove Entity: %s';
SAddEntityError = 'Failed to add Entity';
SUpdateEntityError = 'Failed to update Entity';
SImportTableEntities = 'Import Entities';
SImportEntitiesError = 'One or more Entities were not imported.';
SEntityTitle = 'Entity: %s';
SBadColumnName = 'The specified name cannot be used.';
SColumnNameInUse = 'That name is already in use by another column.';
SAddColumn = 'Add a Property';
SDeleteColumn = 'Delete Property';
SDataTypeItem = 'Data Type';
SEditColumn = 'Edit Property';
SNoColumnModify = 'You may not modify %s';
SDeleteConfirm = 'Are you sure you want to delete this item?';
SDeleteConfirmPlural = 'Are you sure you want to delete these items?';
SInvalidDataType = 'Value is not a valid %s';
SInvalidColumnName = 'Provided Name contains invalid characters.';
SAddPropertyTitle = 'Add Property';
SAddPropertyMessage = 'Enter the new property''s name';
SPropertNameExistsError = 'A Property with name ''%s'' already exists.';
SConfirmRowChangeLoss = 'Continue and lose current changes?';
SResultsTruncated = 'Results Truncated...';
SSharedKeyError = 'The shared key cannot be created. Please check that you have the required OpenSSL libraries.';
SMissingServerSettings = 'Cannot connect %s to server, SQLConnection and ServerClassName must both be set.';
sUnknownCommandType = 'Unknown command type';
SNumberFormatError = 'The parameter has an invalid number format';
SInvalidTunnel = 'The callback tunnel is in an invalid state and should be terminated.';
SProtocolNotSupported = 'Specified protocol in request %s is not supported. Current supported protocols are: %s, json, tunnel';
SProtocolRestEmpty = 'none specified (uses rest)';
SCommandNotSupported = 'Command %s in request is not supported. Accepted commands are: GET, POST, PUT and DELETE';
SUnknownType = 'Unknown data type for parameter %d: %d';
SUnknownTypeName = 'Unknown data type: %s';
SOnGetClassNotSet = 'OnGetClass event not set or it did not provide a class reference';
SInvalidRequestFormat = 'Invalid request format. /className/methodName and eventual parameters expected.';
STooManyParameters = 'Server method %0:s has only %1:d parameters. Too many arguments actual arguments: %2:d.';
SNotInputParameter = 'Server''s method %0:s %1:d parameter in not an input parameter. Either call with less parameters or change the method definition.';
SNoJSONValue = 'Message content is not a valid JSON value.';
SInvalidInternalCmd = 'Internal command %s not implemented.';
SNoConversionToDBX = 'Cannot convert JSON value %0:s input into %1:s';
SNoJSONConversion = 'No conversion exists for JSON value %0:s';
SNoConversionToJSON = 'Cannot convert DBX type %0:s into a JSON value';
STooManyInputParams = 'Server method %0:s consumed only %1:d input parameters out of %2:d. Either call with more parameters or change method definition.';
SNoJSONCmdContent = 'Request type %0:s has an empty content. A JSON command object is expected';
SPOSTExpected = 'JSON protocol expects a POST request instead of %0:s. Submit a POST request with a JSON command to receive proper response';
SJSONArrayExpected = 'JSON protocol expects a JSON array instead a %0:s type. Submit a POST request with a JSON command to receive proper response';
SNoSessionFound = 'Session expired';
SNoSessionInRequest = 'HTTP request is missing the session parameter. Add %s parameter with the session id.';
SNoCountParam = 'HTTP request misses the count parameter. Add %s parameter holding the byte count.';
SCommunicationErr = 'Error redirecting byte flow to internal server.';
SWaitFailure = 'Error in method %s while waiting for a semaphore.';
SWaitTimeout = 'Timeout occured in method %s while waiting for a semaphore.';
SWaitTerminated = 'Communication was terminated.';
SBadParamName = 'Invalid parameter naming. Expected [dcname.]field[numeric range] instead of %s';
SCannotConvertParam = 'The output parameter (%d) cannot be converted by the selected converter (%s)';
SJSONValueNotObject = 'Value must be an instance of TJSONObject';
SCommandNotImplemented = 'Command %s not implemented';
SNoRegisteredCallbackForId = 'Invocation failed as there is currently no registered callback for the given id (%s)';
SRegisteredCallbacksExist = 'Channel is terminated while %d are still registered with it';
SAuthenticationFailed = 'Authentication manager rejected user credentials. This may due to invalid combination of DS user name and password';
SSessionExpiredMsg = 'The specified session has expired due to inactivity or was an invalid Session ID';
SServerClassExists = '%s class has already been added to the server class list';
SServerClassMissing = '%s class not found in the server class list';
SServerMethodMissing = '%s method not found in the server method list';
SCloseCommands = 'All open command objects must be close before changing the server connection';
SInvalidCommandHandle = 'Invalid command handle: %s';
SUnrecognizedCommandType = '%s is an unrecognized command type';
SServerMethodExists = '%s method has already been added to the server method list';
SCommandClosed = 'Command closed or executed again';
SAuthorizationFail = '%s is not authorized to perform the requested action.';
SAuthSessionFail = 'The current session does not have permission to perform the requested action.';
SRemoteError = 'Remote error: %s';
SCommandUnassigned = 'Command closed or unassigned.';
SRESTServiceMissing = 'An appropriate REST Service was not specified.';
SNoCachItem = 'There is no cached item with ID: %d';
SNoCacheParameter = 'There is no parameter for command %d, parameter index %d.';
SConError = 'Connection cannot be nil. Make sure the connection has been opened.';
SProtocolErrorJSON = 'Invalid response: cannot parse %s.';
SProtocolErrorWrite = 'Cannot write %d bytes. Only %d were delivered.';
SProtocolErrorSize = 'Response size (%d bytes) is greater than expected (%d bytes).';
SConnectionLost = 'Connection lost';
ParameterNotSet = 'Parameter not set for column number %d';
SNoRegisteredLayer = 'Protocol %0:s can be used after an adequate instance of %1:s is registered with %2:s.';
SConnectionTimeout = 'Connection timeout error';
SCommunicationTimeout = 'Communication timeout error';
SNotImplemented = 'Feature not implemented';
SCertExpired = 'The certificate has expired.';
SCertNotYetValid = 'The certificate is not yet valid.';
SCertInvalidFile = 'Invalid certificate File.';
SCausedBy = #$a'Caused by: %s';
SNeedsPrepare = 'Commands with output values must be prepared';
SCallbackBadInput = 'Callback input argument cannot be parsed properly. This is due to a parser error or the server side-serialization';
SBadCallbackParameter = 'A callback parameter cannot be found at the provided index';
SNotEnoughReaders = 'Command needs more DBXReader parameters';
SInvalidMetadataMessageFormat = 'Invalid metadata message format';
SCallbackArgParseError = 'Cannot parse properly the callback output argument';
SInvalidCallbackMessageFormat = 'Invalid callback message format';
SMetadataParseError = 'Cannot parse properly the metadata value';
SCannotLoadMetaDataForJds7 = 'MetaData cannot be provided from a Blackfish SQL server older than version 8.0';
SInvalidJSONHeaderByte = 'Invalid JSON header byte encountered';
SCloseError = 'Close error';
SReadError = 'Read error';
SUnexpectedHeader = 'Unexpected header';
SKeyNotNull = 'Encryption key expected to be not null';
SSetupFirst = 'Cypher filter needs to be setUp first';
SNoSpaceAvailable = 'Operation %s cannot complete since it expects a container for at least %s bytes instead of %s';
SKeyDoNotMatch = 'Cypher keys do not match, please use the same key';
SNoReadDataAvailable = 'Read attempt when no read data is available';
SNoWriteDataAvailable = 'Write attempt when write data is already available';
SFilterNotRegistered = 'Communication filter %s is not registered. Filter class needs to be registered in order to communicate with the server.';
SInvalidFilterParameter = 'Filter %s rejected setup parameter %s given value %s. At this point the server communication is not possible due to this incompatibility.';
SNoConnection = 'No connection';
SNoMatchingFilter = 'The Server has no matching %s filter.';
SAzureInvalidAcctKey = 'The Account Key you have entered is invalid.';
sCannotChangeIPImplID = 'IPImplementationID cannot be change while transport is active';
implementation
end.
|
{
"HTTP Client Provider (WinSock)" - Copyright (c) Danijel Tkalcec
@html(<br>)
Using TRtcWSockClientProvider to implement a HTTP Client provider
@exclude
}
unit rtcWSockHttpCliProv;
{$INCLUDE rtcDefs.inc}
interface
uses
Classes,
SysUtils,
rtcLog,
rtcConn,
rtcConnProv,
rtcFastStrings,
rtcWSockCliProv;
type
TRtcWSockHttpClientProvider = class(TRtcWSockClientProvider)
private
FOnInvalidResponse:TRtcEvent;
FMaxHeaderSize:integer;
FMaxResponseSize:integer;
FRequest:TRtcClientRequest;
FResponse:TRtcClientResponse;
FResponseBuffer:TRtcHugeString;
FResponseWaiting:boolean;
ReqComplete:boolean; // internal Request.Complete indicator (to avoid problems with changing Request objects)
FChunked:boolean;
FChunkState:byte;
FResponseLine:boolean; // response line received
InBuffer:string; // data received, including HTTP header (header will be stripped when read)
FHaveResponse:boolean; // response header accepted, receiving request data.
LenToRead:int64; // number of bytes left to read from last Request
LenToWrite:int64; // number of bytes to write out using inherited Write()
LenToSend:int64; // number of bytes left to send out (DataOut event)
FHeaderOut:boolean;
protected
procedure ClearResponse;
procedure TriggerConnect; override;
procedure TriggerConnectLost; override;
procedure TriggerDataReceived; override;
procedure TriggerDataSent; override;
procedure TriggerDataOut; override;
procedure TriggerInvalidResponse; virtual;
public
constructor Create; override;
destructor Destroy; override;
procedure SetTriggerInvalidResponse(Event:TRtcEvent);
procedure WriteHeader(SendNow:boolean=True); overload;
procedure WriteHeader(const Header_Text:string; SendNow:boolean=True); overload;
procedure Write(const ResultData:string; SendNow:boolean=True); override;
// On DataReceived, read server response body using this:
function Read:string; override;
property Request:TRtcClientRequest read FRequest write FRequest;
property Response:TRtcClientResponse read FResponse write FResponse;
// Max. allowed size of the first (status) line in response header
property MaxResponseSize:integer read FMaxResponseSize write FMaxResponseSize;
// Max. allowed size of the complete response Header
property MaxHeaderSize:integer read FMaxHeaderSize write FMaxHeaderSize;
end;
implementation
const
CRLF = #13#10;
END_MARK = CRLF+CRLF;
{ TRtcWSockHttpClientProvider }
procedure TRtcWSockHttpClientProvider.SetTriggerInvalidResponse(Event: TRtcEvent);
begin
FOnInvalidResponse:=Event;
end;
procedure TRtcWSockHttpClientProvider.TriggerInvalidResponse;
begin
if assigned(FOnInvalidResponse) then
FOnInvalidResponse;
end;
constructor TRtcWSockHttpClientProvider.Create;
begin
inherited;
FResponseBuffer:=TRtcHugeString.Create;
InBuffer:='';
LenToWrite:=0;
LenToSend:=0;
FHeaderOut:=False;
FResponseLine:=False;
ReqComplete:=False;
end;
destructor TRtcWSockHttpClientProvider.Destroy;
begin
FResponseBuffer.Free;
InBuffer:='';
LenToWrite:=0;
LenToSend:=0;
FResponseLine:=False;
FHeaderOut:=False;
FResponseWaiting:=False;
inherited;
end;
procedure TRtcWSockHttpClientProvider.ClearResponse;
begin
FResponseBuffer.Clear;
FResponseLine:=False;
FResponse.Clear;
LenToRead:=-1;
end;
procedure TRtcWSockHttpClientProvider.TriggerConnect;
begin
Request.Init;
FResponseBuffer.Clear;
InBuffer:='';
LenToWrite:=0;
LenToSend:=0;
FHeaderOut:=False;
FResponseLine:=False;
FResponseWaiting:=False;
FHaveResponse:=False;
FChunked:=False;
FChunkState:=0;
ClearResponse;
inherited;
end;
procedure TRtcWSockHttpClientProvider.TriggerConnectLost;
begin
if FHaveResponse then // Processing a response ...
begin
if not FChunked and (LenToRead=-1) then // No content-length and not chunked
begin
LenToRead:=0;
Response.Done:=True;
Request.Active:=False;
FHaveResponse:=False; // get ready for next request
FResponseLine:=False;
FHeaderOut:=False;
FChunked:=False;
FChunkState:=0;
ReqComplete:=False; // DataReceived events have to wait until a new request has been sent out
inherited TriggerDataReceived;
end;
end;
inherited;
end;
procedure TRtcWSockHttpClientProvider.TriggerDataReceived;
var
s,
StatusLine,
HeadStr:string;
HeadLen,
MyPos:integer;
function HexToInt(s:string):integer;
var
i,len:integer;
c:char;
begin
Result:=0;
len:=length(s);
i:=1;
while len>0 do
begin
c:=s[len];
if c in ['1'..'9'] then
Result:=Result+i*(Ord(c)-Ord('0'))
else if s[len] in ['A'..'F'] then
Result:=Result+i*(Ord(c)-Ord('A')+10)
else if s[len] in ['a'..'f'] then
Result:=Result+i*(Ord(c)-Ord('a')+10);
i:=i*16;Dec(len);
end;
end;
procedure ResponseError;
begin
ReqComplete:=False; // no more reading, please!
FResponseLine:=False;
TriggerInvalidResponse;
end;
begin
if not ReqComplete then
begin
if assigned(CryptPlugin) then
begin
// Read string from buffer
InBuffer:=InBuffer + inherited Read;
if InBuffer='' then
begin
FResponseWaiting:=True;
Exit;
end
else
FResponseWaiting:=False;
end
else
begin
FResponseWaiting:=True;
Exit;
end;
end
else
FResponseWaiting:=False;
// Read string from buffer
InBuffer:=InBuffer + inherited Read;
repeat
if not FHaveResponse then // Don't have the header yet ...
begin
if not FResponseLine then
begin
// Accept streaming data as response
if ((length(InBuffer)>=5) and (CompareText(Copy(InBuffer,1,5),'HTTP/')<>0)) or
((length(InBuffer)=1) and (CompareText(InBuffer,'H')<>0)) or
((length(InBuffer)=2) and (CompareText(InBuffer,'HT')<>0)) or
((length(InBuffer)=3) and (CompareText(InBuffer,'HTT')<>0)) or
((length(InBuffer)=4) and (CompareText(InBuffer,'HTTP')<>0)) then
begin
ClearResponse;
Response.Receiving:=True;
Response.Started:=True;
FHaveResponse:=True;
FResponseLine:=True;
LenToRead:=-1; // Unlimited length (streaming data until disconnected)
Continue;
end;
MyPos:=Pos(CRLF,InBuffer);
if (MaxResponseSize>0) and
( (MyPos>MaxResponseSize+1) or
((MyPos<=0) and (length(InBuffer)>MaxResponseSize+length(CRLF))) ) then
begin
ClearResponse;
ResponseError;
Exit;
end
else if (MyPos>0) then
begin
ClearResponse;
StatusLine:=Copy(InBuffer,1,MyPos-1);
Delete(InBuffer,1,MyPos+length(CRLF)-1);
if CompareText(Copy(StatusLine,1,5),'HTTP/')<>0 then
begin
ResponseError;
Exit;
end;
Response.Receiving:=True;
Response.Started:=True;
{ Our line probably looks like this:
HTTP/1.1 200 OK }
MyPos:=Pos(' ',StatusLine); // first space before StatusCode
if MyPos<=0 then
begin
ResponseError;
Exit;
end;
Delete(StatusLine,1,MyPos); // remove 'HTTP/1.1 '
MyPos:=Pos(' ',StatusLine); // space after StatusCode
if MyPos<=0 then // no Status Text
begin
s:=StatusLine;
StatusLine:='';
end
else
begin
s:=Copy(StatusLine,1,MyPos-1); // StatusCode
Delete(StatusLine,1,MyPos); // StatusText
end;
if s<>'' then
begin
try
Response.StatusCode:=StrToInt(s);
Response.StatusText:=StatusLine;
except
// if there is something wrong with this, just ignore the exception
end;
end;
FResponseLine:=True;
end;
end;
if FResponseLine then
begin
// See if we can get the whole header ...
HeadLen:=Pos(CRLF, InBuffer);
if HeadLen<>1 then
HeadLen:=Pos(END_MARK, InBuffer);
if HeadLen=1 then
begin
// Delete CRLF from the body
Delete(InBuffer,1,2);
if Response.StatusCode=100 then
begin // special handling of the "100:Continuing" Http status code
FResponseLine:=False;
Continue;
end;
// No Header: disconnect closes the response.
Request.Close:=True;
if Request.Method='HEAD' then
begin
FChunked:=False;
LenToRead:=0;
end;
FHaveResponse:=True;
end
else if (MaxHeaderSize>0) and
( (HeadLen>MaxHeaderSize) or
((HeadLen<=0) and (length(InBuffer)>MaxHeaderSize+length(END_MARK))) ) then
begin
ResponseError;
Exit;
end
else if HeadLen>0 then
begin
// Separate header from the body
HeadStr:=Copy(InBuffer, 1, HeadLen+length(END_MARK)-1);
Delete(InBuffer,1,HeadLen+length(END_MARK)-1);
if Response.StatusCode=100 then
begin // special handling of the "100:Continuing" Http status code
FResponseLine:=False;
Continue;
end;
FHaveResponse:=True;
// Scan for all header attributes ...
MyPos:=Pos(CRLF, HeadStr);
while (MyPos>1) do // at least 1 character inside line
begin
StatusLine:=Copy(HeadStr,1,MyPos-1);
Delete(HeadStr,1,MyPos+Length(CRLF)-1);
MyPos:=Pos(':',StatusLine);
if MyPos>0 then
begin
s:=Trim(Copy(StatusLine,1,MyPos-1));
Delete(StatusLine,1,MyPos);
StatusLine:=Trim(StatusLine);
if CompareText(s,'TRANSFER-ENCODING')=0 then
begin
if CompareText(StatusLine,'CHUNKED')=0 then
begin
FChunked:=True;
FChunkState:=0;
end;
end
else if CompareText(s,'CONTENT-LENGTH')=0 then
begin
LenToRead:=StrToInt64Def(StatusLine,0);
Response.ContentLength:=LenToRead;
end
else if CompareText(s,'CONNECTION')=0 then
begin
if Trim(Uppercase(StatusLine))='CLOSE' then
Request.Close:=True
else if Trim(Uppercase(StatusLine))='KEEP-ALIVE' then
Request.Close:=False;
end;
Response[s]:=StatusLine;
end;
MyPos:=Pos(CRLF, HeadStr);
end;
if LenToRead=-1 then
Request.Close:=True;
if Request.Method='HEAD' then
begin
FChunked:=False;
LenToRead:=0;
end;
StatusLine:='';
HeadStr:='';
end;
end;
end;
if FHaveResponse then // Processing a response ...
begin
if FChunked then // Read data as chunks
begin
if (FChunkState=0) and (InBuffer<>'') then // 1.step = read chunk size
begin
MyPos:=Pos(CRLF,InBuffer);
if MyPos>0 then
begin
StatusLine:=Trim(Copy(InBuffer,1,MyPos-1));
Delete(InBuffer,1,MyPos+1);
LenToRead:=HexToInt(StatusLine);
FChunkState:=1; // ready to read data
end;
end;
if (FChunkState=1) and (InBuffer<>'') then // 2.step = read chunk data
begin
if (LenToRead>length(InBuffer)) then // need more than we have
begin
Response.ContentIn:=Response.ContentIn+length(InBuffer);
if LenToRead>0 then
Dec(LenToRead, length(InBuffer));
FResponseBuffer.Add(InBuffer);
InBuffer:='';
inherited TriggerDataReceived;
Response.Started:=False;
end
else
begin
if LenToRead>0 then
begin
Response.ContentIn:=Response.ContentIn+LenToRead;
FResponseBuffer.Add(Copy(InBuffer,1,LenToRead));
Delete(InBuffer,1,LenToRead);
LenToRead:=0;
FChunkState:=2; // this is not the last chunk, ready to read CRLF
end
else
FChunkState:=3; // this was last chunk, ready to read CRLF
end;
end;
if (FChunkState>=2) and (length(InBuffer)>=2) then // 3.step = close chunk
begin
LenToRead:=-1;
Delete(InBuffer,1,2); // Delete CRLF
if FChunkState=2 then
begin
FChunkState:=0;
end
else
begin
Response.Done:=True;
Request.Active:=False;
FHaveResponse:=False; // get ready for next request
FChunked:=False;
FChunkState:=0;
FResponseLine:=False;
FHeaderOut:=False;
ReqComplete:=False; // DataReceived events have to wait until a new request has been sent out
end;
inherited TriggerDataReceived;
Response.Started:=False;
end;
end
else // Read data as stream or with predefined length
begin
if (LenToRead>0) or (LenToRead=-1) then
begin
if (LenToRead>length(InBuffer)) or
(LenToRead=-1) then // need more than we have
begin
Response.ContentIn:=Response.ContentIn+length(InBuffer);
if LenToRead>0 then
Dec(LenToRead, length(InBuffer));
FResponseBuffer.Add(InBuffer);
InBuffer:='';
end
else
begin
Response.ContentIn:=Response.ContentIn+LenToRead;
FResponseBuffer.Add(Copy(InBuffer,1,LenToRead));
Delete(InBuffer,1,LenToRead);
LenToRead:=0;
Response.Done:=True;
Request.Active:=False;
FHaveResponse:=False; // get ready for next request
FChunked:=False;
FResponseLine:=False;
FHeaderOut:=False;
ReqComplete:=False; // DataReceived events have to wait until a new request has been sent out
end;
end
else
begin
Response.Done:=True;
Request.Active:=False;
FHaveResponse:=False; // get ready for next request
FChunked:=False;
FResponseLine:=False;
FHeaderOut:=False;
ReqComplete:=False; // DataReceived events have to wait until a new request has been sent out
end;
inherited TriggerDataReceived;
Response.Started:=False;
end;
end
else
Break; // Failing to fetch a header will break the loop.
until (InBuffer='') or not ReqComplete;
end;
procedure TRtcWSockHttpClientProvider.WriteHeader(SendNow:boolean=True);
var
s:string;
begin
if FHeaderOut then
raise Exception.Create('Last header intercepted with new header, before data sent out.');
s:=Request.Method+' '+Request.URI+' HTTP/1.1'+CRLF+
Request.HeaderText;
if Request.Close then s:=s+'Connection: close'+CRLF;
s:=s+CRLF;
Request.Started:=True;
Request.Active:=True;
LenToWrite:=Request.ContentLength;
LenToSend:=length(s) + Request.ContentLength;
FHeaderOut:=True;
inherited Write(s, SendNow or (LenToWrite<=0));
end;
procedure TRtcWSockHttpClientProvider.WriteHeader(const Header_Text:string; SendNow:boolean=True);
var
s:string;
begin
if FHeaderOut then
raise Exception.Create('Last header intercepted with new header, before data sent out.');
if Header_Text<>'' then
Request.HeaderText:=Header_Text;
s:=Request.Method+' '+Request.URI+' HTTP/1.1'+CRLF +
Request.HeaderText;
if Request.Close then s:=s+'Connection: close'+CRLF;
s:=s+CRLF;
Request.Started:=True;
Request.Active:=True;
LenToWrite:=Request.ContentLength;
LenToSend:=length(s) + Request.ContentLength;
FHeaderOut:=True;
inherited Write(s, SendNow or (LenToWrite<=0));
end;
procedure TRtcWSockHttpClientProvider.Write(const ResultData: string; SendNow:boolean=True);
begin
if length(ResultData)=0 then Exit;
if not FHeaderOut then
raise Exception.Create('Trying to send Data without Header. Call WriteHeader before Write.');
if length(ResultData)>LenToWrite then
raise Exception.Create('Trying to send more Data out than specified in Header.');
Dec(LenToWrite, length(ResultData));
Request.ContentOut:=Request.ContentOut + length(ResultData);
inherited Write(ResultData, SendNow);
end;
function TRtcWSockHttpClientProvider.Read: string;
begin
if FResponseBuffer.Size>0 then
begin
Result:=FResponseBuffer.Get;
FResponseBuffer.Clear;
end
else
Result:='';
end;
procedure TRtcWSockHttpClientProvider.TriggerDataSent;
begin
if Request.Active then
Request.Started:=False;
inherited TriggerDataSent;
if FResponseWaiting then
if ReqComplete then
TriggerDataReceived;
end;
procedure TRtcWSockHttpClientProvider.TriggerDataOut;
begin
if not ReqComplete then
if assigned(Request) and Request.Active then
begin
Dec(LenToSend, DataOut);
ReqComplete := LenToSend<=0;
Request.Complete := ReqComplete;
end;
inherited TriggerDataOut;
end;
end.
|
unit FilterUnit;
interface
Uses
SysUtils ,Dialogs;//
Type TFilterData = Array[0..2000] of single; // must fit TSubMeas(commonUnit) and TDTSignal (TDTunit)
Function BpFilter(Input:TFilterData;upper,Lower:double):TFilterData;
Function LpFilter(Input:TFilterData;freq:integer):TFilterData;
Procedure LpFilterP(var Input:TFilterData; var freq:integer);
{ FIR Low-Pass Filter, Filter Order = 30}
Const FilterLP2000Hz: array[-15..15] of single=
(0.001691,0.001737,0.001392,-0.000111,-0.003481,-0.008619,-0.014024,-0.016731,
-0.012990,0.000451,0.024871,0.058518,0.096469,0.131607,0.156482,0.165470,
0.156482,0.131607,0.096469,0.058518,0.02487,0.000451,-0.012990,-0.016731,
-0.014024,-0.008619,-0.003481,-0.000111,0.001392,0.001737,0.001691);
Const FilterLP2500Hz: array[-15..15] of single=
(-0.000396,0.000812,0.002544,0.004412,0.004819,0.001541,-0.006577,-0.017688,
-0.026153,-0.023901,-0.003839,0.036106,0.090421,0.146571,0.188958,0.204738,
0.188958,0.146571,0.090421,0.036106,-0.003839,-0.023901,-0.026153,-0.017688,
-0.006577,0.001541,0.004819,0.004412,0.002544,0.000812,-0.000396);
Const FilterLP3000Hz: array[-15..15] of single=
(-0.001085,-0.002045,-0.002243,-0.000337,0.004424,0.009877,0.010527,
0.000988,-0.018111,-0.036268,-0.035839,-0.001703,0.067326,0.153257,0.224865,
0.252734,0.224865,0.153257,0.067326,-0.001703,-0.035839,-0.036268,-0.018111,
0.000988,0.010527,0.009877,0.004424,-0.000337,-0.002243,-0.002045,-0.001085);
Const FilterLP3500Hz: array[-15..15] of single=
(0.001433,0.000205,-0.002112,-0.004409,-0.003383,0.003632,0.013485,0.015975,
0.001343,-0.027292,-0.048143,-0.031000,0.040099,0.148466,0.247726,0.287951,
0.247726,0.148466,0.040099,-0.031000,-0.048143,-0.027292,0.001343,0.015975,
0.013485,0.003632,-0.003383,-0.004409,-0.002112,0.000205,0.001433);
Const FilterLP4000Hz: array[-15..15] of single=
(0.000265,0.001899,0.002312,-0.000557,-0.006152,-0.007964,0.001321,0.017667,
0.022064,-0.002267,-0.043572,-0.056826,0.003033,0.133599,0.270574,0.329203,
0.270574,0.133599,0.003033,-0.056826,-0.043572,-0.002267,0.022064,0.017667,
0.001321,-0.007964,-0.006152,-0.000557,0.002312,0.001899,0.000265);
implementation
Function BpFilter(Input:TFilterData;upper,Lower:double):TFilterData;
var
L,i,J,k:integer;
drift,b,a,bnot,bhat:double;
AA: Array of Array of single;
bb,bb2: Array of single;
fx:TFilterData;
Begin
//Correct for very low freq drift
L:=Length(Input);
SetLength(AA,L,L);
SetLength(bb,L);
SetLength(bb2,L);
drift:= (Input[L-1]- Input[0]) / (L-1);
for i:=0 to L-1 do Result[i]:= Input[i]- drift*i;
//
b:= 2*pi/Lower;
a:= 2*pi/Upper;
bnot:= (b-a)/pi;
bhat:= bnot/2;
for i:=0 to L-1 do bb[i]:= (sin((i+1)*b)-sin((i+1)*a))/((i+1)*pi);
for i:=0 to L-2 do bb2[i+1]:= bb[i];
bb2[0]:=bnot;
for i:=0 to L-1 do
Begin
k:=0;
for J:=i to L-1 do
Begin
AA[i,J]:=bb2[k];
AA[J,i]:=bb2[k];
inc(k);
end;
end;
AA[0,0]:=bhat;
AA[L-1,L-1]:=bhat;
for i:=0 to L-2 do
Begin
AA[i+1,1] := AA[i,1]-bb2[i];
AA[(L-1)-i,L-1]:=AA[i,1]-bb2[i];
end;
for i:=0 to L-1 do
Begin
fx[i]:=0;
for J:=0 to L-1 do
Begin
fx[i]:= fx[i]+ AA[i,J]*Result[J];
end;
end;
//shift
Result:=fx;
end;
Function LpFilter(Input:TFilterData;freq:integer):TFilterData;
var
BigArray : Array[-15..length(Input)+15] of single;
i,j,lang :integer;
sum: single;
Filtered: boolean;
Begin
lang:= length(Input);
Filtered:=False;
for i:=-15 to lang+15 do BigArray[i]:=0;
For i :=0 to lang-1 do BigArray[i]:= Input[i];
If freq=-1 then begin
LpFilter:=Input;
Filtered:=TRUE;
End;
If freq=2000 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP2000Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=2500 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP2500Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=3000 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP3000Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=3500 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP3500Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=4000 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP4000Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If Not filtered then Showmessage('This filter is not installed: '+IntToStr(freq)+'Hz');
End;
Procedure LpFilterP(var Input:TFilterData; var freq:integer);
var
BigArray : Array[-15..length(Input)+15] of single;
i,j,lang :integer;
sum: single;
Filtered: boolean;
LpFilter:TFilterData;
Begin
lang:= length(Input);
Filtered:=False;
for i:=-15 to lang+15 do BigArray[i]:=0;
For i :=0 to lang-1 do BigArray[i]:= Input[i];
If freq=-1 then begin
LpFilter:=Input;
Filtered:=TRUE;
End;
If freq=2000 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP2000Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=2500 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP2500Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=3000 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP3000Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=3500 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP3500Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If freq=4000 then begin
For i :=0 to lang-1 do begin
Sum:=0;
For j:=-15 to 15 do sum:= Sum+ FilterLP4000Hz[j]*BigArray[i+j];
LpFilter[i]:=Sum;
End;
Filtered:=TRUE;
End;
If Not filtered then Showmessage('This filter is not installed: '+IntToStr(freq)+'Hz');
freq:=2000;
for i:=0 to length(Input)-1 do Input[i]:=LpFilter[i];
End;
end.
|
unit ProgressBarForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ExtCtrls,
cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxContainer, cxEdit, cxProgressBar,
cxLabel, ProgressInfo, RootForm, dxSkinsCore, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, ProcRefUnit;
type
TfrmProgressBar = class;
TfrmProgressBar = class(TfrmRoot)
pnlMain: TPanel;
cxlblProgress: TcxLabel;
cxpbMain: TcxProgressBar;
private
FProgressBarLabel: string;
FProgressInfo: TProgressInfo;
procedure DoOnAssign(Sender: TObject);
{ Private declarations }
protected
property ProgressBarLabel: string read FProgressBarLabel
write FProgressBarLabel;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class procedure Process(AHandling: IHandling; AProcRef: TProcRef;
const ACaption, ARowSubstitute: string); static;
property ProgressInfo: TProgressInfo read FProgressInfo;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses NotifyEvents;
constructor TfrmProgressBar.Create(AOwner: TComponent);
begin
inherited;
FProgressBarLabel := 'Обработано строк';
FProgressInfo := TProgressInfo.Create;
TNotifyEventWrap.Create(FProgressInfo.OnAssign, DoOnAssign);
end;
destructor TfrmProgressBar.Destroy;
begin
FreeAndNil(FProgressInfo);
inherited;
end;
procedure TfrmProgressBar.DoOnAssign(Sender: TObject);
begin
cxlblProgress.Caption := Format('%s: %d из %d',
[FProgressBarLabel, FProgressInfo.ProcessRecords,
FProgressInfo.TotalRecords]);
cxpbMain.Position := FProgressInfo.Position;
Application.ProcessMessages;
end;
class procedure TfrmProgressBar.Process(AHandling: IHandling;
AProcRef: TProcRef; const ACaption, ARowSubstitute: string);
var
AfrmProgressBar: TfrmProgressBar;
begin
Assert(Assigned(AProcRef));
AfrmProgressBar := TfrmProgressBar.Create(nil);
try
if not ACaption.IsEmpty then
AfrmProgressBar.Caption := ACaption;
if not ARowSubstitute.IsEmpty then
AfrmProgressBar.FProgressBarLabel :=
Format('Обработано %s', [ARowSubstitute]);
AfrmProgressBar.Show;
// Вызываем метод-обработку табличных данных
AHandling.Process(AProcRef,
procedure(ASender: TObject)
begin
AfrmProgressBar.ProgressInfo.Assign(ASender as TProgressInfo);
end);
finally
FreeAndNil(AfrmProgressBar);
end;
end;
end.
|
{DEFINE DIRECT_LOG_FILE}
unit LinkClient;
interface
uses Classes, SysUtils, fifo, ExtCtrls, Windows, math, umap_debug_log;
type
tLinkState=(link_idle, link_open, link_establish, link_error, link_close);
tLinkClient=class;
tLinkEvent = procedure(sender:tLinkClient) of object;
tLinkLogEvent = procedure(sender:tobject; msg:string) of object;
tLinkErrorEvent = procedure(sender:tLinkClient; Code:integer) of object;
tLinkRxTxEvent = procedure(sender:tLinkClient; data:pbyte; size:integer) of object;
tLinkFastRxTxEvent = function (sender:tLinkClient; data:pbyte; size:integer):boolean of object;
tLinkFastPreCheckEvent = function (var read_ready:boolean; var write_ready:boolean):boolean of object;
tLinkFastPostCheckEvent = function (old_read_ready:boolean; old_write_ready:boolean; var read_ready:boolean; var write_ready:boolean):boolean of object;
tLinkClient=class(TThread)
private
v_State : tLinkState;
v_error_code : integer;
tx_buf : array of byte;
rx_buf : array of byte;
tx2_buf : array of byte;
rx2_buf : array of byte;
api_tread_id : cardinal;
net_tread_id : cardinal;
f_connected : boolean;
f_disconnected : boolean;
f_error : boolean;
exeptions_count : integer;
log_file : file;
log_file_enabled : boolean;
log_file_error : boolean;
procedure run_idle;
procedure run_establish;
procedure run_establish_main;
procedure run_close;
procedure run_open;
procedure run_error;
procedure set_state(new_state:tLinkstate);
procedure run_log(code:integer);
procedure file_open;
procedure file_run;
procedure file_close;
procedure do_rx_event(readed:integer);
property new_state:tLinkstate write set_state;
protected
tx_fifo : tfifo_blocks;
rx_fifo : tfifo_blocks;
txed_fifo : tfifo_blocks;
log_fifo : tfifo_blocks;
tx_max_block : integer;
rx_max_block : integer;
zero_close : boolean;
map_log : tMAP_debug_main;
procedure Execute; override;
function onFastRx_private(sender:tLinkClient; data:pbyte; size:integer):boolean; virtual;
function onFastPreCheck_private(var read_ready:boolean; var write_ready:boolean):boolean; virtual;
function onFastPostCheck_private(old_read_ready:boolean; old_write_ready:boolean; var read_ready:boolean; var write_ready:boolean):boolean; virtual;
procedure onTick_private;virtual;
procedure onTimerTick;virtual;
procedure onConnect_private;virtual;
procedure onDisconnect_private;virtual;
procedure onInit;virtual;
procedure onDone;virtual;
function hardware_open:boolean;virtual;abstract;
function hardware_close:boolean;virtual;abstract;
function hardware_check(var read_ready:boolean; var write_ready:boolean):boolean;virtual;abstract;
function hardware_errorcode:integer;virtual;abstract;
function hardware_write(buf:pointer; size:integer; var writed:integer):boolean;virtual;abstract;
function hardware_read(buf:pointer; size:integer; var readed:integer):boolean;virtual;abstract;
public
timer : ttimer;
log_name : string[255];
onLog : tLinkLogEvent;
onLogBegin : tLinkEvent;
onLogEnd : tLinkEvent;
onRX : tLinkRxTxEvent;
onTX : tLinkRxTxEvent;
onFastRx : tLinkFastRxTxEvent;
onFastTx : tLinkFastRxTxEvent;
onConnect : tLinkEvent;
onDisconnect : tLinkEvent;
onError : tLinkErrorEvent;
noRead : boolean;
stat_iterations : int64;
stat_readed : int64;
stat_writed : int64;
stat_read_speed : int64;
stat_write_speed : int64;
stat_select_timeout_none : int64;
stat_select_timeout_rx : int64;
stat_select_timeout_tx : int64;
debug : integer;
file_main : file;
file_name : string;
file_block_size : integer;
file_block_delay : integer;
RX_clear : boolean;
constructor Create(tx_buf_size:integer=65536;
rx_buf_size:integer=65536;
tx_max_block_size:integer=10000;
rx_max_block_size:integer=10000);
destructor destroy;override;
procedure Log_add(msg:string);virtual;
procedure Open;
procedure Close;
procedure Write(data:pbyte; size:integer);
procedure update_log;
procedure onTimer(sender:tobject); virtual;
procedure stat_reset_speed;virtual;
procedure stat_reset_all;virtual;
function tx_free_bytes:integer; virtual;
function tx_free_blocks:integer; virtual;
function tx_free_ratio:integer; virtual;
function TreadString : string; virtual;
property error_code:integer read v_error_code;
property State:tLinkstate read v_State;
property RX_fifo_blocks:tfifo_blocks read rx_fifo;
property TX_fifo_blocks:tfifo_blocks read tx_fifo;
property TXed_fifo_blocks:tfifo_blocks read txed_fifo;
end;
implementation
constructor tLinkclient.Create;
begin
v_state:=link_idle;
inherited create(false);
zero_close := true;
v_state := link_idle;
onFastRx := nil;
tx_max_block:=tx_max_block_size;
rx_max_block:=rx_max_block_size;
setlength(tx_buf, tx_max_block);
setlength(tx2_buf, tx_max_block);
setlength(rx_buf, rx_max_block);
setlength(rx2_buf, rx_max_block);
timer := TTimer.Create(nil);
timer.Interval := 16;
timer.OnTimer := onTimer;
timer.Enabled := true;
api_tread_id := GetCurrentThreadId;
log_fifo := tfifo_blocks.create($40000, 16384);
tx_fifo := tfifo_blocks.create(tx_buf_size, tx_buf_size div 8);
rx_fifo := tfifo_blocks.create(rx_buf_size, rx_buf_size div 8);
txed_fifo := tfifo_blocks.create(tx_buf_size, tx_buf_size div 8);
Priority:=tpTimeCritical;
onInit;
end;
destructor tLinkclient.destroy;
begin
inherited destroy;
run_log(1);
onDone;
setlength(tx_buf, 0);
setlength(rx_buf, 0);
setlength(tx2_buf, 0);
setlength(rx2_buf, 0);
timer.Free; timer:=nil;
tx_fifo.Free; tx_fifo:=nil;
rx_fifo.Free; rx_fifo:=nil;
log_fifo.Free; log_fifo:=nil;
txed_fifo.Free; txed_fifo:=nil;
if map_log <> nil then
begin
map_log.free;
map_log := nil;
end;
end;
procedure tLinkClient.onInit;
begin
end;
procedure tLinkClient.onDone;
begin
end;
procedure tLinkClient.set_state;
begin
if self=nil then exit;
if (v_State<>link_establish) and (new_state=link_establish) then f_connected:=true;
if (v_State<>link_error) and (new_state=link_error) then f_error:=true;
if (v_State<>link_idle) and (new_state=link_idle) then f_disconnected:=true;
v_State:=new_state;
end;
procedure tLinkClient.Log_add;
var
s : string;
begin
if self=nil then exit;
{$IFDEF DIRECT_LOG_FILE}
if (log_file_enabled = false) and (log_file_error = false) then
begin
{$I-}
s := self.classname + '_'+inttohex(integer(@self), 8)+'.log';
AssignFile(log_file, s);
rewrite(log_file, 1);
if IOResult <> 0 then
log_file_error := true
else
log_file_enabled := true;
{$I+}
end;
if (log_file_enabled = true) and (log_file_error = false) and (length(msg) >= 1) then
begin
{$I-}
s := msg + #13#10;
BlockWrite(log_file, s[1], length(s));
if IOResult <> 0 then
log_file_error := true;
{$I+}
end;
{$ENDIF}
log_fifo.write_str(msg);
if (map_log = nil) and (log_name <> '') then
begin
map_log := tMAP_debug_main.create(log_name + '#link', 'Messages', self.Log_add);
if not map_log.create_log then
begin
log_name := '';
map_log.free;
map_log := nil;
end;
end;
if map_log <> nil then
if pos('To_Commands: ', msg) = 0 then
map_log.send(msg);
end;
procedure tLinkClient.open;
begin
if self=nil then exit;
if State<>link_idle then exit;
new_state:=link_open;
end;
procedure tLinkclient.write;
begin
if self=nil then exit;
if State<>link_establish then exit;
if size>length(tx_buf) then
begin
log_add('write: size>length(tx_buf)');
exit;
end;
tx_fifo.write(data, size);
end;
procedure tLinkClient.close;
begin
if self=nil then exit;
if State in [link_open, link_error, link_establish, link_close] then
new_State:=link_close
else
new_State:=link_idle;
end;
procedure tLinkclient.update_log;
begin
if self=nil then exit;
run_log(1234);
end;
procedure tLinkclient.run_log(code:integer);
var
flag:boolean;
msg:string;
begin
if self=nil then exit;
{ assert(api_tread_id=GetCurrentThreadId, 'Code = '+inttostr(code)+
#13' API thread='+inttohex(api_tread_id,8)+
#13' NET thread='+inttohex(net_tread_id,8)+
#13' Cur thread='+inttohex(GetCurrentThreadId,8)
);
if api_tread_id<>GetCurrentThreadId then exit; }
if log_fifo.blocks_count=0 then exit;
flag:=false;
if (@onLogBegin)<>nil then
if log_fifo.blocks_count>2 then
begin
onLogBegin(self);
flag:=true;
end;
while log_fifo.blocks_count<>0 do
begin
msg:=log_fifo.read_str;
if (@onLog)<>nil then onLog(self, ClassName+': '+msg);
end;
if flag then
if (@onLogEnd)<>nil then
onLogEnd(self);
end;
procedure tLinkClient.ontimer;
var
readed, writed, blocks_count:integer;
last_time:cardinal;
begin
if self=nil then exit;
run_log(0);
onTimerTick();
if f_connected then
begin
Log_add('Connected');
if @onConnect<>nil then onConnect(self);
f_connected:=false;
end;
if f_error then
begin
Log_add('f_error');
if @onError<>nil then onError(self, v_error_code);
f_error:=false;
end;
blocks_count:=0;
last_time:=GetTickCount;
if @onRX<>nil then
while rx_fifo.blocks_count<>0 do
begin
readed:=rx_fifo.read(@(rx_buf[0]), length(rx_buf));
// if @onRX<>nil then
onRX(self, @(rx_buf[0]), readed);
inc(stat_readed, readed);
inc(stat_read_speed, readed);
inc(blocks_count);
if blocks_count>1000 then
begin
blocks_count:=0;
if GetTickCount-last_time>=64 then
begin
// Log_add('CPU timeout');
break;
end;
end;
end
else
if RX_clear then
while rx_fifo.blocks_count<>0 do
begin
readed:=rx_fifo.read(@(rx_buf[0]), length(rx_buf));
inc(stat_read_speed, readed);
end;
if @onTX<>nil then
while txed_fifo.blocks_count<>0 do
begin
writed:=txed_fifo.read(@(tx_buf[0]), length(tx_buf));
if @onTX<>nil then
onTX(self, @(tx_buf[0]), writed);
inc(blocks_count);
if blocks_count>1000 then
begin
blocks_count:=0;
if GetTickCount-last_time>=64 then
begin
Log_add('CPU timeout');
break;
end;
end;
end;
if (f_disconnected) and (rx_fifo.blocks_count=0) then
begin
Log_add('Disconnected');
if @onDisconnect<>nil then onDisconnect(self);
f_disconnected:=false;
end;
end;
procedure tLinkClient.run_idle;
begin
end;
procedure tLinkClient.run_open;
begin
txed_fifo.reset;
tx_fifo.reset;
rx_fifo.reset;
try
if not hardware_open then
begin
Log_add('not hardware_open');
new_State:=link_idle;
exit;
end;
except
on E : Exception do
begin
hardware_close;
Log_add('ERROR Exception: '+E.ClassName+' msg: '+E.Message);
Log_add('not hardware_open');
new_State:=link_idle;
exit;
end;
end;
Log_add('TID = '+inttostr(windows.GetCurrentThreadId));
f_connected:=false;
f_disconnected:=false;
f_error:=false;
v_error_code:=0;
txed_fifo.reset;
tx_fifo.reset;
if self.ClassName <> 'tE1Client' then
rx_fifo.reset;
if state = link_open then
new_State:=link_establish;
onConnect_private;
end;
procedure tLinkClient.do_rx_event(readed:integer);
begin
if @onFastRx=nil then
rx_fifo.write(@(rx2_buf[0]), readed)
else
if onFastRx(self, @(rx2_buf[0]), readed) then
rx_fifo.write(@(rx2_buf[0]), readed)
else
begin
inc(stat_readed, readed);
inc(stat_read_speed, readed);
end;
end;
procedure tLinkClient.run_establish;
begin
try
run_establish_main;
if exeptions_count > 0 then
dec(exeptions_count);
except
on E : Exception do
begin
Log_add('ERROR ('+inttostr(exeptions_count)+'): '+E.ClassName+': '+E.Message);
inc(exeptions_count, 11);
if exeptions_count > 255 then
begin
exeptions_count := 0;
self.close;
end;
exit;
end;
end;
end;
procedure tLinkClient.run_establish_main;
var
readed:integer;
writed:integer;
tx_size:integer;
f_read, f_write, f_write_old, f_read_old:Boolean;
begin
if self=nil then exit;
onTick_private;
f_read:=rx_fifo.data_free>0;
f_write:=tx_fifo.blocks_count>0;
f_write_old:=f_write;
f_read_old:=f_read;
if not onFastPreCheck_private(f_read, f_write) then
begin
Log_add('onFastPreCheck_private error');
new_State:=link_error;
v_error_code:=97;
exit;
end;
if not hardware_check(f_read, f_write) then
begin
Log_add('hardware_check: '+inttostr(hardware_errorcode));
new_State:=link_error;
v_error_code:=90;
exit;
end;
if not onFastPostCheck_private(f_read_old, f_write_old, f_read, f_write) then
begin
Log_add('onFastPostCheck_private error');
new_State:=link_error;
v_error_code:=97;
exit;
end;
if (not f_read) and (not f_write) then
begin
inc(stat_select_timeout_none);
exit;
end;
if f_read then
if noRead then
sleep(1)
else
//if rx_fifo.data_free > 0 then
begin
inc(stat_select_timeout_rx);
if not hardware_read(rx2_buf, min(rx_fifo.data_free, length(rx2_buf)), readed) then
begin
Log_add('Read error: '+inttostr(hardware_errorcode));
new_State:=link_error;
v_error_code:=1;
exit;
end;
// Log_add('Readed '+inttostr(readed));
if zero_close and (readed=0) then
begin
Log_add('Closed by remote host');
new_State:=link_close;
exit;
end;
if onFastRx_private(self, @(rx2_buf[0]), readed) then
do_rx_event(readed)
else
begin
inc(stat_readed, readed);
inc(stat_read_speed, readed);
end;
end;
if (f_write=false) and (f_write_old=false) and (tx_fifo.blocks_count>0) then
begin
f_read:=false;
f_write:=true;
if not hardware_check(f_read, f_write) then
begin
Log_add('hardware_check_2: '+inttostr(hardware_errorcode));
new_State:=link_error;
v_error_code:=91;
exit;
end;
end;
if f_write then
begin
inc(stat_select_timeout_tx);
tx_size:=tx_fifo.read(@(tx2_buf[0]), length(tx2_buf));
// writed := tx_size;
if not hardware_write(tx2_buf, tx_size, writed) then
begin
Log_add('Write error: '+inttostr(hardware_errorcode));
new_State:=link_error;
v_error_code:=2;
exit;
end;
if writed<>tx_size then
begin
Log_add('Write error: writed<>tx_size');
new_State:=link_error;
v_error_code:=3;
exit;
end;
// Log_add('Write '+inttostr(writed));
inc(stat_writed, writed);
inc(stat_write_speed, writed);
if @onFastTx=nil then
begin
if @onTX<>nil then
txed_fifo.write(@(tx2_buf[0]), tx_size);
end
else
if onFastTx(self, @(tx2_buf[0]), tx_size) then
begin
if @onTX<>nil then
txed_fifo.write(@(tx2_buf[0]), tx_size);
end;
end;
end;
procedure tLinkClient.run_close;
begin
if self=nil then exit;
if not hardware_close then
log_add('ERROR: hardware_close');
log_add('Closed');
new_State:=link_idle;
onDisconnect_private;
end;
procedure tLinkClient.run_error;
begin
if self=nil then exit;
new_State:=link_close;
end;
procedure tLinkClient.file_open;
var
result:integer;
begin
{$I-}
AssignFile(file_main, file_name);
FileMode := fmOpenRead;
reset(file_main, 1);
{$I+}
result:=IOResult;
if result<>0 then
begin
Log_add('Error open file : "'+file_name+'", IOResult = '+inttostr(result));
new_State:=link_idle;
exit;
end
else
Log_add('"'+file_name+'" open ok');
f_connected:=false;
f_disconnected:=false;
f_error:=false;
v_error_code:=0;
txed_fifo.reset;
tx_fifo.reset;
rx_fifo.reset;
new_State:=link_establish;
onConnect_private;
end;
procedure tLinkClient.file_run;
var
readed:integer;
size:integer;
result:integer;
begin
tx_fifo.reset;
txed_fifo.reset;
{$I-}
size := Min(length(rx2_buf), file_block_size);
BlockRead(file_main, rx2_buf[0], size, readed);
{$I+}
result:=IOResult;
if result<>0 then
begin
Log_add('Error read file : "'+file_name+'", IOResult = '+inttostr(result));
sleep(500);
new_state := link_close;
end;
if onFastRx_private(self, @(rx2_buf[0]), readed) then
do_rx_event(readed)
else
begin
inc(stat_readed, readed);
inc(stat_read_speed, readed);
end;
if readed<>size then
begin
Log_add('EOF');
sleep(2000);
new_state := link_close;
exit;
end;
sleep(file_block_delay);
end;
procedure tLinkClient.file_close;
var
result:integer;
begin
{$I-}
CloseFile(file_main);
{$I+}
result:=IOResult;
if result<>0 then
Log_add('Error close file : "'+file_name+'", IOResult = '+inttostr(result))
else
Log_add('"'+file_name+'" close ok');
file_name := '';
file_block_size := 0;
file_block_delay := 1;
log_add('Closed');
new_State:=link_idle;
onDisconnect_private;
end;
procedure tLinkClient.Execute;
begin
if self=nil then exit;
net_tread_id:=GetCurrentThreadId;
while not Terminated do
begin
if file_name <> '' then
case State of
link_idle: run_idle;
link_open: file_open;
link_establish: file_run;
link_close: file_close;
link_error: run_error;
end
else
begin
case State of
link_idle: run_idle;
link_open: run_open;
link_establish: run_establish;
link_close: run_close;
link_error: run_error;
end;
if state<>link_establish then sleep(1);
end;
inc(stat_iterations);
end;
end;
procedure tLinkClient.stat_reset_speed;
begin
if self=nil then exit;
stat_read_speed:=0;
stat_write_speed:=0;
end;
procedure tLinkClient.stat_reset_all;
begin
if self=nil then exit;
stat_reset_speed;
stat_readed := 0;
stat_writed := 0;
tx_fifo.stat_reset;
rx_fifo.stat_reset;
txed_fifo.stat_reset;
log_fifo.stat_reset;
end;
function tLinkClient.tx_free_bytes:integer;
begin
result:=tx_fifo.data_free;
end;
function tLinkClient.tx_free_blocks:integer;
begin
result:=tx_fifo.blocks_free;
end;
function tLinkClient.tx_free_ratio:integer;
begin
result:=tx_fifo.free_ratio;
end;
function tLinkClient.onFastRx_private(sender:tLinkClient; data:pbyte; size:integer):boolean;
begin
result:=true;
end;
function tLinkClient.onFastPreCheck_private(var read_ready:boolean; var write_ready:boolean):boolean;
begin
result:=true;
end;
function tLinkClient.onFastPostCheck_private(old_read_ready:boolean; old_write_ready:boolean; var read_ready:boolean; var write_ready:boolean):boolean;
begin
result:=true;
end;
procedure tLinkClient.onConnect_private;
begin
end;
procedure tLinkClient.onDisconnect_private;
begin
end;
procedure tLinkClient.onTick_private;
begin
end;
procedure tLinkClient.onTimerTick;
begin
end;
function tLinkClient.TreadString : string;
begin
result := '';
if self = nil then exit;
result := inttostr(net_tread_id);
end;
end.
|
program BinarySearch;
const
ARR_LENGTH = 100;
var
Arr : Array [0..ARR_LENGTH] of Integer;
i, X : Integer;
left, right, middle : Integer;
begin
for i := 0 to ARR_LENGTH do
begin
Arr[i] := 1+i*2;
end;
write('Enter value to search for: ');
readln(X);
left := 0;
right := ARR_LENGTH;
repeat
writeln('left: ' , left, ', right: ', right);
middle := (left+right) div 2;
if X > Arr[middle] then
left := middle +1
else if x < Arr[middle] then
right := middle -1
until ((left > right) or (Arr[middle] = X));
if Arr[middle] = X then
writeln('found at ', middle)
else
writeln('not found');
end.
|
{-Test prog for SkipJack CTR Seek, (c) we July 2010}
program T_SJ_CSK;
{$i STD.INC}
{$ifdef APPCONS}
{$apptype console}
{$endif}
{$ifdef BIT16}
{$N+,F+}
{$endif}
uses
{$ifdef WINCRT}
wincrt,
{$endif}
HRTimer, BTypes,
{$ifdef USEDLL}
{$ifdef VirtualPascal}
SJ_Intv;
{$else}
SJ_Intf;
{$endif}
{$else}
SJ_base, SJ_ctr;
{$endif}
{USE_INT64: if Int64 and errout available}
{$ifdef FPC}
{$ifdef VER2}
{$define USE_INT64}
{$endif}
{$endif}
{$ifdef CONDITIONALEXPRESSIONS} {D6+}
{$define USE_INT64}
{$endif}
var
HR: THRTimer;
var
ctx1, ctx2: TSJContext;
Err : integer;
{$ifdef USE_INT64}
const
BSIZE=$8000;
{$else}
const
BSIZE=8192;
{$endif}
{---------------------------------------------------------------------------}
procedure My_IncMSBFull(var CTR: TSJBlock);
{$ifdef USEDLL} stdcall; {$endif}
{-Increment CTR[7]..CTR[0]}
var
j: integer;
begin
{This is the same as the standard pre-defined function, but it cannot be }
{recognized by its @address and therefore the seek loop will be performed}
for j:=7 downto 0 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
var
pbuf, cbuf1, cbuf2: array[0..BSIZE-1] of byte;
{---------------------------------------------------------------------------}
procedure CheckError;
begin
if Err<>0 then begin
writeln('Error ',Err);
halt;
end;
end;
{---------------------------------------------------------------------------}
procedure randomtest(userdef: boolean);
const
key : array[0..09] of byte = ($11,$22,$33,$44,$55,$66,$77,$88,$99,$00);
CTR : TSJBlock = ($f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7);
plain : array[0..63] of byte = ($01,$02,$03,$04,$05,$06,$07,$08,
$11,$12,$13,$14,$15,$16,$17,$18,
$21,$22,$23,$24,$25,$26,$27,$28,
$31,$32,$33,$34,$35,$36,$37,$38,
$41,$42,$43,$44,$45,$46,$47,$48,
$51,$52,$53,$54,$55,$56,$57,$58,
$61,$62,$63,$64,$65,$66,$67,$68,
$71,$72,$73,$74,$75,$76,$77,$78);
ct_ctr : array[0..63] of byte = ($58,$a0,$ae,$43,$41,$9d,$ed,$0e,
$00,$8f,$f9,$f3,$0f,$4f,$b0,$f6,
$a4,$b7,$84,$69,$c5,$d8,$e4,$e7,
$32,$64,$fa,$27,$69,$ce,$15,$54,
$cd,$fb,$10,$83,$8b,$fc,$63,$e9,
$72,$99,$d5,$05,$3c,$cf,$90,$f7,
$12,$d0,$0d,$a7,$82,$e7,$7d,$5c,
$36,$3e,$9e,$25,$58,$fc,$e6,$2c);
var
ct: array[0..255] of byte;
SO: integer;
begin
writeln('Checking known vector test');
Err := SJ_CTR_Init(key, sizeof(key), CTR, ctx2);
CheckError;
if userdef then begin
Err := SJ_SetIncProc({$ifdef FPC_ProcVar}@{$endif}My_IncMSBFull, ctx2);
CheckError;
end;
for SO:=0 to 63 do begin
write('.');
Err := SJ_CTR_Seek(CTR, SO, 0, ctx2);
CheckError;
Err := SJ_CTR_Encrypt(@plain[SO], @ct[SO], 1, ctx2);
if ct[SO]<>ct_ctr[SO] then begin
writeln('Diff: SO=',SO:2,' ct_ctr[SO]=',ct_ctr[SO]:3,' ct[SO]=',ct[SO]:3);
end;
end;
writeln(' done');
end;
{---------------------------------------------------------------------------}
procedure bigtest(n: integer);
const
key : array[0..09] of byte = ($11,$22,$33,$44,$55,$66,$77,$88,$99,$00);
CTR : TSJBlock = ($f0,$f1,$f2,$f3,$f4,$f5,$f6,$f7);
{$ifdef USE_INT64}
var
ofs: int64;
const
oma = int64($3FFFFFFF)*$100; {avoid braindamaged D2 error}
{$else}
var
ofs: longint;
const
oma = $6FFFFFFF;
{$endif}
var
i: integer;
begin
for i:=0 to BSIZE-1 do pbuf[i] := random(256);
Err := SJ_CTR_Init(key, sizeof(key), CTR, ctx1);
CheckError;
case n of
1: begin
writeln('IncProc = SJ_IncMSBFull, max. offset = ',oma);
{$ifdef USE_INT64}
writeln(erroutput, 'IncProc = SJ_IncMSBFull, max. offset = ',oma);
{$endif}
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncMSBFull, ctx1);
{$else}
err := SJ_SetIncProc(SJ_IncMSBFull, ctx1);
{$endif}
end;
2: begin
writeln('IncProc = SJ_IncLSBFull, max. offset = ',oma);
{$ifdef USE_INT64}
writeln(erroutput, 'IncProc = SJ_IncLSBFull, max. offset = ',oma);
{$endif}
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncLSBFull, ctx1);
{$else}
err := SJ_SetIncProc(SJ_IncLSBFull, ctx1);
{$endif}
end;
3: begin
writeln('IncProc = SJ_IncMSBPart, max. offset = ',oma);
{$ifdef USE_INT64}
writeln(erroutput, 'IncProc = SJ_IncMSBPart, max. offset = ',oma);
{$endif}
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncMSBPart, ctx1);
{$else}
err := SJ_SetIncProc(SJ_IncMSBPart, ctx1);
{$endif}
end;
4: begin
writeln('IncProc = SJ_IncLSBPart, max. offset = ',oma);
{$ifdef USE_INT64}
writeln(erroutput, 'IncProc = SJ_IncLSBPart, max. offset = ',oma);
{$endif}
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncLSBPart, ctx1);
{$else}
err := SJ_SetIncProc(SJ_IncLSBPart, ctx1);
{$endif}
end;
end;
CheckError;
ofs := 0;
ReStartTimer(HR);
repeat
for i:=1 to 99 do begin
Err := SJ_CTR_Encrypt(@pbuf, @cbuf1, BSIZE, ctx1);
ofs := ofs + BSIZE;
end;
{$ifdef USE_INT64}
write(erroutput, 100.0*ofs/oma:1:3,'%'#13);
{$else}
write(100.0*ofs/oma:1:3,'%'#13);
{$endif}
Err := SJ_CTR_Encrypt(@pbuf, @cbuf1, BSIZE, ctx1);
CheckError;
i := random(BSIZE);
Err := SJ_CTR_Init(key, sizeof(key), CTR, ctx2);
CheckError;
case n of
1: begin
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncMSBFull, ctx2);
{$else}
err := SJ_SetIncProc(SJ_IncMSBFull, ctx2);
{$endif}
end;
2: begin
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncLSBFull, ctx2);
{$else}
err := SJ_SetIncProc(SJ_IncLSBFull, ctx2);
{$endif}
end;
3: begin
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncMSBPart, ctx2);
{$else}
err := SJ_SetIncProc(SJ_IncMSBPart, ctx2);
{$endif}
end;
4: begin
{$ifdef FPC_ProcVar}
err := SJ_SetIncProc(@SJ_IncLSBPart, ctx2);
{$else}
err := SJ_SetIncProc(SJ_IncLSBPart, ctx2);
{$endif}
end;
else begin
writeln('Invalid n');
halt;
end;
end;
CheckError;
{$ifdef USE_INT64}
Err := SJ_CTR_Seek64(CTR, ofs+i, ctx2);
{$else}
Err := SJ_CTR_Seek(CTR, ofs+i, 0, ctx2);
{$endif}
CheckError;
Err := SJ_CTR_Encrypt(@pbuf[i], @cbuf2[i], 1, ctx2);
CheckError;
if cbuf1[i]<>cbuf2[i] then begin
writeln('Diff: Offset=',ofs+i,' cbuf1[]=',cbuf1[i]:3,' cbuf2[]=',cbuf2[i]:3);
halt;
end;
ofs := ofs + BSIZE;
until ofs>oma;
writeln('Done - no differences.');
writeln('Time [s]: ', ReadSeconds(HR):1:3);
end;
var
{$ifdef D12Plus}
s: string;
{$else}
s: string[10];
{$endif}
begin
writeln('Test program "SkipJack CTR Seek" (C) 2010 W.Ehrhardt');
{$ifdef USEDLL}
writeln('DLL Version: ',SJ_DLL_Version);
{$endif}
writeln;
writeln('Test using standard SJ_IncMSBFull');
randomtest(false);
writeln;
writeln('Test using user-defines My_IncMSBFull');
randomtest(true);
writeln;
StartTimer(HR);
s := paramstr(1);
if s='big' then begin
bigtest(1);
bigtest(2);
bigtest(3);
bigtest(4);
end;
end.
|
unit LuaSettings;
{$mode delphi}
interface
uses
Classes, SysUtils, lua, lauxlib, lualib, registry;
procedure initializeLuaSettings;
implementation
uses luahandler, LuaClass, LuaObject;
type
TLuaSettings=class //A wrapper for the registry object to make access to the cheat engine settings easier and uniform
private
freg: Tregistry;
fpath: string;
procedure setPath(v: string);
function getValue(index: string): string;
procedure setValue(index: string; value: string);
public
constructor create(initialpath: pchar);
published
property path:string read fPath write setPath;
property value[index: string]: string read getValue write setValue;
end;
procedure TLuaSettings.setPath(v: string);
begin
if pos('..',v)>0 then
exit;
if freg.OpenKey('\Software\Cheat Engine\'+v, true) then
fpath:=v;
end;
function TLuaSettings.getValue(index: string): string;
begin
result:='';
if freg.ValueExists(index) then
begin
case freg.GetDataType(index) of
rdString, rdExpandString: result:=freg.ReadString(index);
rdInteger: result:=inttostr(freg.ReadInteger(index));
end;
end;
end;
procedure TLuaSettings.setValue(index: string; value: string);
begin
if freg.ValueExists(index) then
begin
case freg.GetDataType(index) of
rdString, rdExpandString: freg.WriteString(index, value);
rdInteger:
begin
try
freg.WriteInteger(index, strtoint(value));
except
end;
end;
end;
end
else
freg.WriteString(index, value);
end;
constructor TLuaSettings.create(initialpath: pchar);
begin
freg:=TRegistry.Create;
freg.RootKey:=HKEY_CURRENT_USER;
freg.OpenKey('\Software\Cheat Engine',true);
if initialpath<>nil then
path:=initialpath;
end;
function getSettings(L: Plua_State): integer; cdecl;
begin
if lua_gettop(l)>0 then
luaclass_newClass(L, TLuaSettings.create(pchar(Lua_ToString(L,1))))
else
luaclass_newClass(L, TLuaSettings.create(nil));
result:=1;
end;
function luasettings_getValue(L: PLua_State): integer; cdecl;
var
s: TLuaSettings;
index: string;
begin
result:=0;
s:=luaclass_getClassObject(L);
if lua_gettop(L)>=1 then
begin
index:=lua_toString(L,-1);
lua_pushstring(L, s.value[index]);
result:=1;
end;
end;
function luasettings_setValue(L: PLua_State): integer; cdecl;
var
parameters: integer;
s: TLuaSettings;
index: string;
newvalue: string;
paramstart, paramcount: integer;
begin
result:=0;
s:=luaclass_getClassObject(L, @paramstart, @paramcount);
if paramcount>=2 then
begin
index:=lua_tostring(L,paramstart);
if lua_isboolean(L, paramstart+1) then
newvalue:=BoolToStr(lua_toboolean(L,paramstart+1), '1','0')
else
newvalue:=lua_tostring(l,paramstart+1);
s.value[index]:=newvalue;
end;
end;
procedure luasettings_addMetaData(L: PLua_state; metatable: integer; userdata: integer );
begin
object_addMetaData(L, metatable, userdata);
luaclass_addArrayPropertyToTable(L, metatable, userdata, 'Value', luasettings_getValue, luasettings_setValue);
end;
procedure initializeLuaSettings;
begin
lua_register(LuaVM, 'getSettings', getSettings);
end;
initialization
luaclass_register(TLuaSettings, luasettings_addMetaData);
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1998 Inprise Corporation }
{ }
{*******************************************************}
unit ActnList;
interface
uses Classes, Messages, ImgList;
type
{ TContainedAction }
TCustomActionList = class;
TContainedAction = class(TBasicAction)
private
FCategory: string;
FActionList: TCustomActionList;
function GetIndex: Integer;
function IsCategoryStored: Boolean;
procedure SetCategory(const Value: string);
procedure SetIndex(Value: Integer);
procedure SetActionList(AActionList: TCustomActionList);
protected
procedure ReadState(Reader: TReader); override;
procedure SetParentComponent(AParent: TComponent); override;
public
destructor Destroy; override;
function Execute: Boolean; override;
function GetParentComponent: TComponent; override;
function HasParent: Boolean; override;
function Update: Boolean; override;
property ActionList: TCustomActionList read FActionList write SetActionList;
property Index: Integer read GetIndex write SetIndex stored False;
published
property Category: string read FCategory write SetCategory stored IsCategoryStored;
end;
TContainedActionClass = class of TContainedAction;
{ TCustomActionList }
TActionEvent = procedure (Action: TBasicAction; var Handled: Boolean) of object;
TCustomActionList = class(TComponent)
private
FActions: TList;
FImageChangeLink: TChangeLink;
FImages: TCustomImageList;
FOnChange: TNotifyEvent;
FOnExecute: TActionEvent;
FOnUpdate: TActionEvent;
procedure AddAction(Action: TContainedAction);
function GetAction(Index: Integer): TContainedAction;
function GetActionCount: Integer;
procedure ImageListChange(Sender: TObject);
procedure RemoveAction(Action: TContainedAction);
procedure SetAction(Index: Integer; Value: TContainedAction);
procedure SetImages(Value: TCustomImageList);
protected
procedure Change; virtual;
procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure SetChildOrder(Component: TComponent; Order: Integer); override;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnExecute: TActionEvent read FOnExecute write FOnExecute;
property OnUpdate: TActionEvent read FOnUpdate write FOnUpdate;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExecuteAction(Action: TBasicAction): Boolean; override;
function IsShortCut(var Message: TWMKey): Boolean;
function UpdateAction(Action: TBasicAction): Boolean; override;
property Actions[Index: Integer]: TContainedAction read GetAction write SetAction; default;
property ActionCount: Integer read GetActionCount;
property Images: TCustomImageList read FImages write SetImages;
end;
{ TActionList }
TActionList = class(TCustomActionList)
published
property Images;
property OnChange;
property OnExecute;
property OnUpdate;
end;
{ TControlAction }
THintEvent = procedure (var HintStr: string; var CanShow: Boolean) of object;
TCustomAction = class(TContainedAction)
private
FDisableIfNoHandler: Boolean;
FCaption: string;
FChecked: Boolean;
FEnabled: Boolean;
FHelpContext: THelpContext;
FHint: string;
FImageIndex: Integer;
FShortCut: TShortCut;
FVisible: Boolean;
FOnHint: THintEvent;
procedure SetCaption(const Value: string);
procedure SetChecked(Value: Boolean);
procedure SetEnabled(Value: Boolean);
procedure SetHelpContext(Value: THelpContext);
procedure SetHint(const Value: string);
procedure SetImageIndex(Value: Integer);
procedure SetShortCut(Value: TShortCut);
procedure SetVisible(Value: Boolean);
protected
FImage: TObject;
FMask: TObject;
procedure AssignTo(Dest: TPersistent); override;
procedure SetName(const Value: TComponentName); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function DoHint(var HintStr: string): Boolean;
function Execute: Boolean; override;
property Caption: string read FCaption write SetCaption;
property Checked: Boolean read FChecked write SetChecked default False;
property DisableIfNoHandler: Boolean read FDisableIfNoHandler write FDisableIfNoHandler default True;
property Enabled: Boolean read FEnabled write SetEnabled default True;
property HelpContext: THelpContext read FHelpContext write SetHelpContext default 0;
property Hint: string read FHint write SetHint;
property ImageIndex: Integer read FImageIndex write SetImageIndex default -1;
property ShortCut: TShortCut read FShortCut write SetShortCut default 0;
property Visible: Boolean read FVisible write SetVisible default True;
property OnHint: THintEvent read FOnHint write FOnHint;
end;
TAction = class(TCustomAction)
published
property Caption;
property Checked;
property Enabled;
property HelpContext;
property Hint;
property ImageIndex;
property ShortCut;
property Visible;
property OnExecute;
property OnHint;
property OnUpdate;
end;
{ TControlActionLink }
TActionLink = class(TBasicActionLink)
protected
function IsCaptionLinked: Boolean; virtual;
function IsCheckedLinked: Boolean; virtual;
function IsEnabledLinked: Boolean; virtual;
function IsHelpContextLinked: Boolean; virtual;
function IsHintLinked: Boolean; virtual;
function IsImageIndexLinked: Boolean; virtual;
function IsShortCutLinked: Boolean; virtual;
function IsVisibleLinked: Boolean; virtual;
procedure SetCaption(const Value: string); virtual;
procedure SetChecked(Value: Boolean); virtual;
procedure SetEnabled(Value: Boolean); virtual;
procedure SetHelpContext(Value: THelpContext); virtual;
procedure SetHint(const Value: string); virtual;
procedure SetImageIndex(Value: Integer); virtual;
procedure SetShortCut(Value: TShortCut); virtual;
procedure SetVisible(Value: Boolean); virtual;
end;
TActionLinkClass = class of TActionLink;
{ Action registration }
TEnumActionProc = procedure (const Category: string; ActionClass: TBasicActionClass;
Info: Pointer) of object;
procedure RegisterActions(const CategoryName: string;
const AClasses: array of TBasicActionClass; Resource: TComponentClass);
procedure UnRegisterActions(const AClasses: array of TBasicActionClass);
procedure EnumRegisteredActions(Proc: TEnumActionProc; Info: Pointer);
function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction;
const
RegisterActionsProc: procedure (const CategoryName: string;
const AClasses: array of TBasicActionClass; Resource: TComponentClass) = nil;
UnRegisterActionsProc: procedure (const AClasses: array of TBasicActionClass) = nil;
EnumRegisteredActionsProc: procedure (Proc: TEnumActionProc; Info: Pointer) = nil;
CreateActionProc: function (AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction = nil;
implementation
uses SysUtils, Forms, Menus, Consts, Graphics, Controls;
procedure RegisterActions(const CategoryName: string;
const AClasses: array of TBasicActionClass; Resource: TComponentClass);
begin
if Assigned(RegisterActionsProc) then
RegisterActionsProc(CategoryName, AClasses, Resource) else
raise Exception.Create(SInvalidActionRegistration);
end;
procedure UnRegisterActions(const AClasses: array of TBasicActionClass);
begin
if Assigned(UnRegisterActionsProc) then
UnRegisterActionsProc(AClasses) else
raise Exception.Create(SInvalidActionUnregistration);
end;
procedure EnumRegisteredActions(Proc: TEnumActionProc; Info: Pointer);
begin
if Assigned(EnumRegisteredActionsProc) then
EnumRegisteredActionsProc(Proc, Info) else
raise Exception.Create(SInvalidActionEnumeration);
end;
function CreateAction(AOwner: TComponent; ActionClass: TBasicActionClass): TBasicAction;
begin
if Assigned(CreateActionProc) then
Result := CreateActionProc(AOwner, ActionClass) else
raise Exception.Create(SInvalidActionCreation);
end;
{ TContainedAction }
destructor TContainedAction.Destroy;
begin
if ActionList <> nil then ActionList.RemoveAction(Self);
inherited Destroy;
end;
function TContainedAction.GetIndex: Integer;
begin
if ActionList <> nil then
Result := ActionList.FActions.IndexOf(Self) else
Result := -1;
end;
function TContainedAction.IsCategoryStored: Boolean;
begin
Result := True;//GetParentComponent <> ActionList;
end;
function TContainedAction.GetParentComponent: TComponent;
begin
if ActionList <> nil then
Result := ActionList else
Result := inherited GetParentComponent;
end;
function TContainedAction.HasParent: Boolean;
begin
if ActionList <> nil then
Result := True else
Result := inherited HasParent;
end;
procedure TContainedAction.ReadState(Reader: TReader);
begin
inherited ReadState(Reader);
if Reader.Parent is TCustomActionList then
ActionList := TCustomActionList(Reader.Parent);
end;
procedure TContainedAction.SetIndex(Value: Integer);
var
CurIndex, Count: Integer;
begin
CurIndex := GetIndex;
if CurIndex >= 0 then
begin
Count := ActionList.FActions.Count;
if Value < 0 then Value := 0;
if Value >= Count then Value := Count - 1;
if Value <> CurIndex then
begin
ActionList.FActions.Delete(CurIndex);
ActionList.FActions.Insert(Value, Self);
end;
end;
end;
procedure TContainedAction.SetCategory(const Value: string);
begin
if Value <> Category then
begin
FCategory := Value;
if ActionList <> nil then
ActionList.Change;
end;
end;
procedure TContainedAction.SetActionList(AActionList: TCustomActionList);
begin
if AActionList <> ActionList then
begin
if ActionList <> nil then ActionList.RemoveAction(Self);
if AActionList <> nil then AActionList.AddAction(Self);
end;
end;
procedure TContainedAction.SetParentComponent(AParent: TComponent);
begin
if not (csLoading in ComponentState) and (AParent is TCustomActionList) then
ActionList := TCustomActionList(AParent);
end;
function TContainedAction.Execute: Boolean;
begin
Result := (ActionList <> nil) and ActionList.ExecuteAction(Self) or
Application.ExecuteAction(Self) or inherited Execute or
(SendAppMessage(CM_ACTIONEXECUTE, 0, Longint(Self)) = 1);
end;
function TContainedAction.Update: Boolean;
begin
Result := (ActionList <> nil) and ActionList.UpdateAction(Self) or
Application.UpdateAction(Self) or inherited Update or
(SendAppMessage(CM_ACTIONUPDATE, 0, Longint(Self)) = 1);
end;
{ TCustomActionList }
constructor TCustomActionList.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FActions := TList.Create;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
end;
destructor TCustomActionList.Destroy;
begin
FImageChangeLink.Free;
while FActions.Count > 0 do TContainedAction(FActions.Last).Free;
FActions.Free;
inherited Destroy;
end;
procedure TCustomActionList.GetChildren(Proc: TGetChildProc; Root: TComponent);
var
I: Integer;
Action: TAction;
begin
for I := 0 to FActions.Count - 1 do
begin
Action := FActions[I];
if Action.Owner = Root then Proc(Action);
end;
end;
procedure TCustomActionList.SetChildOrder(Component: TComponent; Order: Integer);
begin
if FActions.IndexOf(Component) >= 0 then
(Component as TContainedAction).Index := Order;
end;
function TCustomActionList.GetAction(Index: Integer): TContainedAction;
begin
Result := FActions[Index];
end;
function TCustomActionList.GetActionCount: Integer;
begin
Result := FActions.Count;
end;
procedure TCustomActionList.SetAction(Index: Integer; Value: TContainedAction);
begin
TContainedAction(FActions[Index]).Assign(Value);
end;
procedure TCustomActionList.SetImages(Value: TCustomImageList);
begin
if Images <> nil then Images.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if Images <> nil then
begin
Images.RegisterChanges(FImageChangeLink);
Images.FreeNotification(Self);
end;
end;
procedure TCustomActionList.ImageListChange(Sender: TObject);
begin
if Sender = Images then Change;
end;
procedure TCustomActionList.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
if AComponent = Images then
Images := nil
else if (AComponent is TContainedAction) then
RemoveAction(TContainedAction(AComponent));
end;
procedure TCustomActionList.AddAction(Action: TContainedAction);
begin
FActions.Add(Action);
Action.FActionList := Self;
Action.FreeNotification(Self);
end;
procedure TCustomActionList.RemoveAction(Action: TContainedAction);
begin
if FActions.Remove(Action) >= 0 then
Action.FActionList := nil;
end;
procedure TCustomActionList.Change;
var
I: Integer;
begin
if Assigned(FOnChange) then FOnChange(Self);
for I := 0 to FActions.Count - 1 do
TContainedAction(FActions[I]).Change;
if csDesigning in ComponentState then
begin
if (Owner is TForm) and (TForm(Owner).Designer <> nil) then
TForm(Owner).Designer.Modified;
end;
end;
function TCustomActionList.IsShortCut(var Message: TWMKey): Boolean;
var
I: Integer;
ShortCut: TShortCut;
ShiftState: TShiftState;
begin
ShiftState := KeyDataToShiftState(Message.KeyData);
ShortCut := Menus.ShortCut(Message.CharCode, ShiftState);
for I := 0 to FActions.Count - 1 do
if TCustomAction(FActions[I]).ShortCut = ShortCut then
begin
Result := TCustomAction(FActions[I]).Enabled;
if Result then TCustomAction(FActions[I]).Execute;
Exit;
end;
Result := False;
end;
function TCustomActionList.ExecuteAction(Action: TBasicAction): Boolean;
begin
Result := False;
if Assigned(FOnExecute) then FOnExecute(Action, Result);
end;
function TCustomActionList.UpdateAction(Action: TBasicAction): Boolean;
begin
Result := False;
if Assigned(FOnUpdate) then FOnUpdate(Action, Result);
end;
{ TActionLink }
function TActionLink.IsCaptionLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsCheckedLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsEnabledLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsHelpContextLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsHintLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsImageIndexLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsShortCutLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
function TActionLink.IsVisibleLinked: Boolean;
begin
Result := Action is TCustomAction;
end;
procedure TActionLink.SetCaption(const Value: string);
begin
end;
procedure TActionLink.SetChecked(Value: Boolean);
begin
end;
procedure TActionLink.SetEnabled(Value: Boolean);
begin
end;
procedure TActionLink.SetHelpContext(Value: THelpContext);
begin
end;
procedure TActionLink.SetHint(const Value: string);
begin
end;
procedure TActionLink.SetImageIndex(Value: Integer);
begin
end;
procedure TActionLink.SetShortCut(Value: TShortCut);
begin
end;
procedure TActionLink.SetVisible(Value: Boolean);
begin
end;
{ TCustomAction }
constructor TCustomAction.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FDisableIfNoHandler := True;
FEnabled := True;
FImageIndex := -1;
FVisible := True;
end;
destructor TCustomAction.Destroy;
begin
FImage.Free;
FMask.Free;
inherited Destroy;
end;
procedure TCustomAction.AssignTo(Dest: TPersistent);
begin
if Dest is TCustomAction then
with TCustomAction(Dest) do
begin
Caption := Self.Caption;
Checked := Self.Checked;
Enabled := Self.Enabled;
HelpContext := Self.HelpContext;
Hint := Self.Hint;
ImageIndex := Self.ImageIndex;
ShortCut := Self.ShortCut;
Visible := Self.Visible;
end else inherited AssignTo(Dest);
end;
procedure TCustomAction.SetCaption(const Value: string);
var
I: Integer;
begin
if Value <> FCaption then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetCaption(Value);
FCaption := Value;
Change;
end;
end;
procedure TCustomAction.SetChecked(Value: Boolean);
var
I: Integer;
begin
if Value <> FChecked then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetChecked(Value);
FChecked := Value;
Change;
end;
end;
procedure TCustomAction.SetEnabled(Value: Boolean);
var
I: Integer;
begin
if Value <> FEnabled then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetEnabled(Value);
FEnabled := Value;
Change;
end;
end;
procedure TCustomAction.SetHelpContext(Value: THelpContext);
var
I: Integer;
begin
if Value <> FHelpContext then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetHelpContext(Value);
FHelpContext := Value;
Change;
end;
end;
procedure TCustomAction.SetHint(const Value: string);
var
I: Integer;
begin
if Value <> FHint then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetHint(Value);
FHint := Value;
Change;
end;
end;
procedure TCustomAction.SetImageIndex(Value: Integer);
var
I: Integer;
begin
if Value <> FImageIndex then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetImageIndex(Value);
FImageIndex := Value;
Change;
end;
end;
procedure TCustomAction.SetShortCut(Value: TShortCut);
var
I: Integer;
begin
if Value <> FShortCut then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetShortCut(Value);
FShortCut := Value;
Change;
end;
end;
procedure TCustomAction.SetVisible(Value: Boolean);
var
I: Integer;
begin
if Value <> FVisible then
begin
for I := 0 to FClients.Count - 1 do
if TBasicActionLink(FClients[I]) is TActionLink then
TActionLink(FClients[I]).SetVisible(Value);
FVisible := Value;
Change;
end;
end;
procedure TCustomAction.SetName(const Value: TComponentName);
var
ChangeText: Boolean;
begin
ChangeText := (Name = Caption) and ((Owner = nil) or
not (csLoading in Owner.ComponentState));
inherited SetName(Value);
{ Don't update caption to name if we've got clients connected. }
if ChangeText and (FClients.Count = 0) then Caption := Value;
end;
function TCustomAction.DoHint(var HintStr: string): Boolean;
begin
Result := True;
if Assigned(FOnHint) then FOnHint(HintStr, Result);
end;
function TCustomAction.Execute: Boolean;
begin
Update;
Result := Enabled and inherited Execute;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ SOAP Support }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit TypeTrans;
interface
uses TypInfo, IntfInfo, SysUtils, InvokeRegistry;
type
TTypeTranslator = class
public
constructor Create;
destructor Destroy; override;
function CastSoapToNative(Info: PTypeInfo;
SoapData: WideString; NatData: Pointer; IsNull: Boolean): Boolean;
procedure CastNativeToSoap(Info: PTypeInfo;
var SoapData: WideString; NatData: Pointer; var IsNull: Boolean);
procedure CastSoapToVariant(SoapInfo: PTypeInfo; SoapData: WideString; NatData: Pointer); overload;
function CastSoapToVariant(SoapInfo: PTypeInfo; SoapData: WideString): Variant; overload;
procedure Base64ToVar(NatData: Pointer; SoapData: WideString);
end;
ETypeTransException = class(Exception);
var
TypeTranslator: TTypeTranslator;
implementation
uses Variants, SoapConst, EncdDecd, Types;
constructor TTypeTranslator.Create;
begin
inherited Create;
end;
destructor TTypeTranslator.Destroy;
begin
inherited;
end;
type
PWideChar = ^WideChar;
function TTypeTranslator.CastSoapToVariant(SoapInfo: PTypeInfo; SoapData: WideString): Variant;
var
SavedDecSep: Char;
I64: Int64;
begin
SavedDecSep := DecimalSeparator;
try
DecimalSeparator := '.';
case SoapInfo.Kind of
tkString,
tkLString,
tkChar:
Result := SoapData;
tkInt64:
Result := StrToInt64(Trim(SoapData));
tkInteger:
begin
if GetTypeData(SoapInfo).OrdType = otULong then
begin
I64 := StrToInt64(Trim(SoapData));
Result := Cardinal(I64);
end else
Result := StrToInt(Trim(SoapData));
end;
tkFloat:
Result:= StrToFloat(Trim(SoapData));
tkWChar,
tkWString:
Result := WideString(Trim(SoapData));
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkEnumeration,
tkDynArray:
raise ETypeTransException.Create(SVariantCastNotSupported);
end;
finally
DecimalSeparator := SavedDecSep;
end;
end;
procedure TTypeTranslator.CastSoapToVariant(SoapInfo: PTypeInfo; SoapData: WideString; NatData: Pointer);
var
SavedDecSep: Char;
begin
SavedDecSep := DecimalSeparator;
try
DecimalSeparator := '.';
case SoapInfo.Kind of
tkString,
tkLString,
tkChar:
Variant(PVarData(NatData)^) := SoapData;
tkInt64:
Variant(PVarData(NatData)^) := StrToInt64(Trim(SoapData));
tkInteger:
Variant(PVarData(NatData)^) := StrToInt(Trim(SoapData));
tkFloat:
Variant(PVarData(NatData)^) := StrToFloat(Trim(SoapData));
tkWChar,
tkWString:
Variant(PVarData(NatData)^) := WideString(SoapData);
tkDynArray:
begin
if SoapInfo = TypeInfo(Types.TByteDynArray) then
Base64ToVar(NatData, SoapData)
else
raise ETypeTransException.Create(SVariantCastNotSupported);
end;
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkEnumeration:
raise ETypeTransException.Create(SVariantCastNotSupported);
end;
finally
DecimalSeparator := SavedDecSep;
end;
end;
function TTypeTranslator.CastSoapToNative(
Info: PTypeInfo; SoapData: WideString; NatData: Pointer; IsNull: Boolean): Boolean;
var
ParamTypeData: PTypeData;
SavedDecSep: Char;
begin
SavedDecSep := DecimalSeparator;
try
DecimalSeparator := '.';
Result := True;
if IsNull and (Info.Kind = tkVariant) then
begin
Variant(PVarData(NatData)^) := NULL;
Exit;
end;
ParamTypeData := GetTypeData(Info);
case Info^.Kind of
tkInteger:
case ParamTypeData^.OrdType of
otSByte,
otUByte:
PByte(NatData)^ := StrToInt(Trim(SoapData));
otSWord,
otUWord:
PSmallInt(NatData)^ := StrToInt(Trim(SoapData));
otSLong,
otULong:
PInteger(NatData)^ := StrToInt(Trim(SoapData));
end;
tkFloat:
case ParamTypeData^.FloatType of
ftSingle:
PSingle(NatData)^ := StrToFloat(Trim(SoapData));
ftDouble:
PDouble(NatData)^ := StrToFloat(Trim(SoapData));
ftComp:
PComp(NatData)^ := StrToFloat(Trim(SoapData));
ftCurr:
PCurrency(NatData)^ := StrToFloat(Trim(SoapData));
ftExtended:
PExtended(NatData)^ := StrToFloat(Trim(SoapData));
end;
tkWString:
PWideString(NatData)^ := SoapData;
tkString:
PShortString(NatData)^ := SoapData;
tkLString:
PString(NatData)^ := SoapData;
tkChar:
if SoapData <> '' then
PChar(NatData)^ := Char(SoapData[1]);
tkWChar:
if SoapData <> '' then
PWideChar(NatData)^ := WideChar(SoapData[1]);
tkInt64:
PInt64(NatData)^ := StrToInt64(Trim(SoapData));
tkEnumeration:
PByte(NatData)^ := GetEnumValue(Info, Trim(SoapData));
tkClass:
;
tkSet,
tkMethod,
tkArray,
tkRecord,
tkInterface,
tkDynArray:
raise ETypeTransException.CreateFmt(SUnexpectedDataType, [ KindNameArray[Info.Kind]] );
tkVariant:
CastSoapToVariant(Info, SoapData, NatData);
end;
finally
DecimalSeparator := SavedDecSep;
end;
end;
// allow custom streaming for scalars ?
procedure TTypeTranslator.CastNativeToSoap(Info: PTypeInfo;
var SoapData: WideString; NatData: Pointer; var IsNull: Boolean);
var
TypeData: PTypeData;
SavedDecSep: Char;
begin
SavedDecSep := DecimalSeparator;
try
DecimalSeparator := '.';
TypeData := GetTypeData(Info);
case Info.Kind of
tkInteger:
case TypeData.OrdType of
otSByte,
otUByte:
SoapData := IntToStr(byte(NatData^) );
otSWord:
SoapData := IntToStr(SmallInt(NatData^));
otUWord:
SoapData := IntToStr(SmallInt(NatData^));
otSLong,
otULong:
SoapData := IntToStr(Integer(NatData^));
end;
tkFloat:
case TypeData.FloatType of
ftSingle:
SoapData := FloatToStr(Single(NatData^));
ftDouble:
SoapData := FloatToStr(Double(NatData^));
ftComp:
SoapData := FloatToStr(Comp(NatData^));
ftCurr:
SoapData := FloatToStr(Currency(NatData^));
ftExtended:
SoapData := FloatToStr(Extended(NatData^));
end;
tkInt64:
SoapData := IntToStr(Int64(NatData^));
tkChar:
SoapData := Char(NatData^);
tkWChar:
SoapData := WideChar(NatData^);
tkWString:
SoapData := PWideString(NatData)^;
tkString:
SoapData := PShortString(NatData)^;
tkLString:
SoapData := PAnsiString(NatData)^;
end;
finally
DecimalSeparator := SavedDecSep;
end;
end;
procedure TTypeTranslator.Base64ToVar(NatData: Pointer; SoapData: WideString);
var
Base64Dec: String;
P: Pointer;
begin
Base64Dec := DecodeString(SoapData);
Variant(PVarData(NatData)^) := VarArrayCreate([0, Length(Base64Dec) - 1], varByte);
P := VarArrayLock(Variant(PVarData(NatData)^));
try
Move(Base64Dec[1], P^, Length(Base64Dec));
finally
VarArrayUnLock(Variant(PVarData(NatData)^));
end;
end;
initialization
TypeTranslator := TTypeTranslator.Create;
finalization
TypeTranslator.Free;
end.
|
unit lgmPanel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, IniFiles;
type
TGlyphPos = (gpLeft, gpRight);
TTitle = class(TPersistent)
private
FOwner : TWinControl;
FCaption : String;
FBGColor,
FTextColor : TColor;
FGlyphPos : TGlyphPos;
FGlyph : TBitmap;
protected
procedure SetCaption(Value: String);
procedure SetBGColor(Value: TColor);
procedure SetTextColor(Value: TColor);
procedure SetGlyphPos(Value: TGlyphPos);
procedure SetGlyph(Value: TBitmap);
public
constructor Create(aOwner: TWinControl);
destructor Destroy; override;
published
property Caption : String read FCaption write SetCaption;
property BGColor : TColor read FBGColor write SetBGColor;
property TextColor : TColor read FTextColor write SetTextColor;
property GlyphPos : TGlyphPos read FGlyphPos write SetGlyphPos;
property Glyph : TBitmap read FGlyph write SetGlyph;
end;
TFakeCaption = class(TCustomControl)
private
FPaintTitle : procedure of Object;
protected
procedure PaintWindow(DC: HDC); override;
public
property Canvas;
end;
TlgmPanel = class(TCustomPanel)
private
FAllowMin,
FMoveable : Boolean;
FTitle : TTitle;
FCaption : TFakeCaption;
aCaptHeight : Integer;
aOldPos : TRect;
aIniName : String;
aIniFile : TIniFile;
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure PaintTitle;
procedure Paint; override;
procedure SetTitle(Values: TTitle);
procedure SetMoveable(Value: Boolean);
function GetPanelAlign : TAlign;
procedure SetPanelAlign(Value: TAlign);
procedure SetAllowMin(Value: Boolean);
property Align;
procedure TitleMouseDown(Sender: TObject;
Button: TMouseButton;
Shift: TShiftState;
X, Y: Integer);
procedure TitleDblClick(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Caption;
procedure Minimize;
procedure Restore;
published
property AlignPanel : TAlign read GetPanelAlign write SetPanelAlign;
property AllowMinimize : Boolean read FAllowMin write SetAllowMin;
property Anchors;
property Left;
property Top;
property Height;
property Width;
property Color;
property Moveable : Boolean read FMoveable write SetMoveable;
property Title : TTitle read FTitle write SetTitle;
end;
procedure Register;
implementation
constructor TTitle.Create(aOwner: TWinControl);
begin
inherited Create;
FOwner := aOwner;
Caption := '';
BGColor := clGreen;
TextColor := clWhite;
FGlyphPos := gpLeft;
FGlyph := TBitmap.Create;
end;
destructor TTitle.Destroy;
begin
FGlyph.Free;
inherited Destroy;
end;
procedure TTitle.SetCaption(Value: String);
begin
FCaption := Value;
FOwner.Repaint;
end;
procedure TTitle.SetBGColor(Value: TColor);
begin
FBGColor := Value;
FOwner.Repaint;
end;
procedure TTitle.SetTextColor(Value: TColor);
begin
FTextColor := Value;
FOwner.Repaint;
end;
procedure TTitle.SetGlyphPos(Value: TGlyphPos);
begin
FGlyphPos := Value;
FOwner.Repaint;
end;
procedure TTitle.SetGlyph(Value: TBitmap);
begin
FGlyph.Assign(Value);
FOwner.Repaint;
end;
procedure TFakeCaption.PaintWindow(DC: HDC);
begin
FPaintTitle;
end;
constructor TlgmPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMoveable := False;
Caption := '';
aCaptHeight := GetSystemMetrics(SM_CYSMCAPTION) + 1;
Height := aCaptHeight + 48;
aIniName := ChangeFileExt(Application.ExeName, '_lgmPanels.ini');
FTitle := TTitle.Create(TWinControl(Self));
FCaption := TFakeCaption.Create(Self);
with FCaption do
begin
Parent := Self;
FPaintTitle := PaintTitle;
Align := alTop;
Height := aCaptHeight;
OnMouseDown := TitleMouseDown;
OnDblClick := TitleDblClick;
end;
end;
destructor TlgmPanel.Destroy;
begin
if FMoveable and not (csDesigning in ComponentState) then
Try
aIniFile := TIniFile.Create(aIniName);
with aIniFile do
begin
WriteInteger(Name, 'Left', Left);
WriteInteger(Name, 'Top', Top);
end;
Finally
aIniFile.Free;
end;
FTitle.Free;
FCaption.Free;
inherited Destroy;
end;
procedure TlgmPanel.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW or WS_EX_STATICEDGE;
if FMoveable and not (csDesigning in ComponentState) then
Try
aIniFile := TIniFile.Create(aIniName);
with aIniFile do
begin
Params.X := ReadInteger(Name, 'Left', Params.X);
Params.Y := ReadInteger(Name, 'Top', Params.Y);
end;
Finally
aIniFile.Free;
end;
with aOldPos do
begin
Left := Params.X;
Top := Params.Y;
Right := Params.Width;
Bottom := Params.Height;
end;
end;
procedure TlgmPanel.PaintTitle;
var
X : Integer;
Rect : TRect;
begin
with Rect do
begin
Left := 0;
Top := 0;
Right := Width - 4;
Bottom := aCaptHeight - 1;
end;
with FCaption.Canvas do
begin
Lock;
Brush.Color := FTitle.BGColor;
FillRect(Rect);
X := 5;
with FTitle do
if not FGlyph.Empty then
if FGlyphPos = gpLeft then
begin
X := FGlyph.Width + 5;
Draw(3, 2, FGlyph);
end
else
Draw(Width - FGlyph.Width - 5, 2, FGlyph);
TextFlags := ETO_OPAQUE;
Font.Color := FTitle.TextColor;
TextOut(X, 1, FTitle.Caption);
UnLock;
end;
end;
procedure TlgmPanel.SetTitle(Values: TTitle);
begin
FTitle := Values;
end;
procedure TlgmPanel.SetMoveable(Value: Boolean);
begin
FMoveable := Value;
if Value then
begin
Align := alNone;
AllowMinimize := False;
end;
end;
procedure TlgmPanel.Minimize;
begin
TitleDblClick(Nil);
end;
procedure TlgmPanel.Restore;
begin
TitleDblClick(Nil);
end;
function TlgmPanel.GetPanelAlign : TAlign;
begin
Result := Align;
end;
procedure TlgmPanel.SetPanelAlign(Value: TAlign);
begin
Align := Value;
if Value <> alNone then
begin
Moveable := False;
AllowMinimize := False;
end;
end;
procedure TlgmPanel.SetAllowMin(Value: Boolean);
begin
FAllowMin := Value;
if Value then
begin
Moveable := False;
AlignPanel := alNone;
end;
end;
procedure TlgmPanel.Paint;
begin
inherited Paint;
PaintTitle;
end;
procedure TlgmPanel.TitleMouseDown(Sender: TObject;
Button: TMouseButton;
Shift: TShiftState;
X, Y: Integer);
begin
if FMoveable and (Button = mbLeft) then
begin
ReleaseCapture;
Self.Perform(WM_SYSCOMMAND, $F012, 1); // Undocumented magic numbers
end;
end;
procedure TlgmPanel.TitleDblClick(Sender: TObject);
var Y : Integer;
begin
if (AlignPanel <> alNone) or (csDesigning in ComponentState) then
Exit;
if (Left = aOldPos.Left) and (Top = aOldPos.Top) then
if FAllowMin then
begin
if Parent is TlgmPanel then
Y := 4
else
Y := 24;
Height := aCaptHeight;
Top := Parent.Height - aCaptHeight - Y;
end
else
else
begin
Left := aOldPos.Left;
Top := aOldPos.Top;
Height := aOldPos.Bottom;
end;
end;
procedure Register;
begin
RegisterComponents('LGM', [TlgmPanel]);
end;
end.
|
unit Unit_StringGrid;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
System.UITypes,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, VCLTee.Control, VCLTee.Grid,
Vcl.ExtCtrls, Tee.Grid.RowGroup, Vcl.StdCtrls,
Tee.Grid.Data.Strings;
type
TStringGridForm = class(TForm)
TeeGrid1: TTeeGrid;
Panel1: TPanel;
Panel2: TPanel;
Label1: TLabel;
EColumns: TEdit;
Label2: TLabel;
ERows: TEdit;
Button1: TButton;
Label3: TLabel;
LCells: TLabel;
procedure FormCreate(Sender: TObject);
procedure TeeGrid1ClickedHeader(Sender: TObject);
procedure TeeGrid1Select(const Sender: TRowGroup);
procedure EColumnsChange(Sender: TObject);
procedure ERowsChange(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
Data : TStringsData;
procedure RefreshTotalCells;
public
{ Public declarations }
end;
var
StringGridForm1: TStringGridForm;
implementation
{$R *.dfm}
uses
Tee.Grid.Columns, VCLTee.Editor.Grid, Tee.Grid.Bands, VCLTee.Painter.GDIPlus;
procedure TStringGridForm.Button1Click(Sender: TObject);
begin
TTeeGridEditor.Edit(Self,TeeGrid1);
end;
procedure TStringGridForm.EColumnsChange(Sender: TObject);
var tmp : Integer;
begin
if TryStrToInt(EColumns.Text,tmp) then
begin
TStringsData(TeeGrid1.Data).Columns:=tmp;
RefreshTotalCells;
end;
end;
procedure TStringGridForm.ERowsChange(Sender: TObject);
var tmp : Integer;
begin
if TryStrToInt(ERows.Text,tmp) then
begin
TStringsData(TeeGrid1.Data).Rows:=tmp;
RefreshTotalCells;
end;
end;
function NewTitle:TTitleBand;
begin
result:=TTitleBand.Create(nil);
result.Text:='Sub-Title';
result.Format.Font.Style:=[fsBold];
result.Format.Brush.Show;
result.Format.Brush.Color:=TColors.Indianred;
result.Format.Stroke.Show;
end;
procedure TStringGridForm.FormCreate(Sender: TObject);
var t : Integer;
begin
// Create data
Data:=TStringsData.Create;
// Initialize size
//Data.Columns:=1000;
//Data.Rows:=100000;
Data.Resize(1000,100000);
// Set header texts
Data.Headers[0]:='A';
Data.Headers[1]:='B';
Data.Headers[2]:='C';
// Fill rows and cells
for t:=0 to Data.Rows-1 do
begin
Data[0,t]:='0 '+IntToStr(t);
Data[1,t]:='1 '+IntToStr(t);
Data[2,t]:='2 '+IntToStr(t);
end;
// Set data to grid
TeeGrid1.Data:=Data;
// Refresh edit boxes
EColumns.Text:=IntToStr(Data.Columns);
ERows.Text:=IntToStr(Data.Rows);
TeeGrid1.Rows.SubBands[20]:=NewTitle;
RefreshTotalCells;
TeeGrid1.Painter:=TGdiPlusPainter.Create;
end;
procedure TStringGridForm.RefreshTotalCells;
begin
LCells.Caption:=FormatFloat('#,###',Data.Columns*Data.Rows);
end;
procedure TStringGridForm.TeeGrid1ClickedHeader(Sender: TObject);
begin
Panel1.Caption:='Clicked column header: '+(Sender as TColumn).Header.Text;
end;
procedure TStringGridForm.TeeGrid1Select(const Sender: TRowGroup);
begin
if Sender.Selected.IsEmpty then
Panel1.Caption:=''
else
Panel1.Caption:='Selected cell: '+Sender.Selected.Column.Header.Text+
' Row: '+IntToStr(Sender.Selected.Row)+
' Value: '+Sender.Data.AsString(Sender.Selected.Column,Sender.Selected.Row);
end;
end.
|
unit frm_ReportesAlmacen2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, dblookup, sRadioButton, DB, ZAbstractRODataset,
ZAbstractDataset, ZDataset, frm_connection, DBCtrls, global, frxClass,
frxDBSet, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvCheckedMaskEdit,
JvDatePickerEdit, JvExControls, JvLabel;
type
TfrmReportesAlmacen2 = class(TForm)
GroupBox1: TGroupBox;
rMateriales: TRadioButton;
rMaterialesFoto: TRadioButton;
rStockMinimo: TRadioButton;
rStockMaximo: TRadioButton;
rMaterialesPerecederos: TRadioButton;
rMaterialesUbicacion: TRadioButton;
Label1: TLabel;
btnImprime: TBitBtn;
qryAlmacenes: TZQuery;
dsalmacenes: TDataSource;
cboAlmacen: TDBLookupComboBox;
cboFamilia: TDBLookupComboBox;
Label2: TLabel;
qryfamilias: TZQuery;
dsFamilias: TDataSource;
Imp_Insumos: TZQuery;
frxInsumos: TfrxReport;
rAnexoF: TRadioButton;
rAnexoDMA: TRadioButton;
frxReport1: TfrxReport;
DBTotalesxCategoria: TfrxDBDataset;
frxAnexoDMA: TfrxReport;
DBAnexoDMA: TfrxDBDataset;
qryAnexoDMA: TZReadOnlyQuery;
rRecepciondeMateriales: TRadioButton;
Label3: TLabel;
Label4: TLabel;
FechaI: TJvDatePickerEdit;
FechaF: TJvDatePickerEdit;
frxRecepcionDeMateriales: TfrxReport;
zq_historialdemateriales: TZQuery;
frx_historialdemateriales: TfrxDBDataset;
zq_historialdemateriales_detalles: TZQuery;
frx_historialdemateriales_detalles: TfrxDBDataset;
zq_historialdematerialesiId: TIntegerField;
zq_historialdematerialessContrato: TStringField;
zq_historialdematerialessFolio: TStringField;
zq_historialdematerialessTipoMovimiento: TStringField;
zq_historialdematerialesdFechaRecepcion: TDateField;
zq_historialdematerialessIdAlmacen: TStringField;
zq_historialdematerialesmNotas: TMemoField;
zq_historialdematerialessStatus: TStringField;
zq_historialdematerialesEstado: TStringField;
zq_historialdematerialesQuienValida: TStringField;
zq_historialdemateriales_detallesiId: TIntegerField;
zq_historialdemateriales_detallesiId_recepcion: TIntegerField;
zq_historialdemateriales_detallessIdInsumo: TStringField;
zq_historialdemateriales_detallesdCantidad: TFloatField;
zq_historialdemateriales_detallesmDescripcion: TMemoField;
zq_historialdemateriales_detallessMedida: TStringField;
zq_historialdemateriales_detallessDescripcion: TStringField;
zq_historialdemateriales_detallesdFechaRecepcion: TDateField;
ImprimirTodasLasFamilias: TCheckBox;
smaterial: TRadioButton;
frxListado: TfrxDBDataset;
frxmaterial: TfrxReport;
Zmaterial: TZReadOnlyQuery;
Zglobales: TZReadOnlyQuery;
frxglobales: TfrxDBDataset;
Zbitacora: TZReadOnlyQuery;
frxbitacora: TfrxDBDataset;
Zoordentrabajo: TZReadOnlyQuery;
ordentrabajo: TDataSource;
sordentrabajo: TDBLookupComboBox;
JvLabel1: TJvLabel;
Zordentrabajo: TZReadOnlyQuery;
frxzordentrabajo: TfrxDBDataset;
procedure FormShow(Sender: TObject);
procedure btnImprimeClick(Sender: TObject);
procedure frxInsumosGetValue(const VarName: string; var Value: Variant);
procedure rStockMinimoClick(Sender: TObject);
procedure rStockMaximoClick(Sender: TObject);
procedure rMaterialesPerecederosClick(Sender: TObject);
procedure rMaterialesUbicacionClick(Sender: TObject);
procedure rAnexoFClick(Sender: TObject);
procedure rAnexoDMAClick(Sender: TObject);
procedure rMaterialesFotoClick(Sender: TObject);
procedure rMaterialesClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure rRecepciondeMaterialesClick(Sender: TObject);
procedure ImprimirTodasLasFamiliasClick(Sender: TObject);
procedure smaterialClick(Sender: TObject);
procedure frxmaterialGetValue(const VarName: string; var Value: Variant);
procedure frxInsumosClosePreview(Sender: TObject);
procedure frxReport1ClosePreview(Sender: TObject);
procedure frxAnexoDMAClosePreview(Sender: TObject);
procedure frxRecepcionDeMaterialesClosePreview(Sender: TObject);
procedure frxmaterialClosePreview(Sender: TObject);
procedure cboAlmacenKeyPress(Sender: TObject; var Key: Char);
procedure cboFamiliaKeyPress(Sender: TObject; var Key: Char);
procedure ImprimirTodasLasFamiliasKeyPress(Sender: TObject; var Key: Char);
procedure FechaIKeyPress(Sender: TObject; var Key: Char);
procedure FechaFKeyPress(Sender: TObject; var Key: Char);
procedure sordentrabajoKeyPress(Sender: TObject; var Key: Char);
procedure FormContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
private
procedure Materiales;
procedure MaterialesConFoto;
procedure MaterialesInstalado;
procedure MaterialesSetockMinimo;
procedure MaterialesStockMaximo;
procedure MaterialesPerecederos;
procedure MaterialesUbicacion;
procedure AnexoDMA;
procedure AnexoF;
procedure Seguimiento;
procedure RecepcionDeMateriales;
procedure blockFechas(lParam : boolean);
{ Private declarations }
public
{ Public declarations }
end;
var
frmReportesAlmacen2: TfrmReportesAlmacen2;
stock: string;
AplicaFamilia: String;
implementation
{$R *.dfm}
procedure TfrmReportesAlmacen2.FechaFKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
if sordentrabajo.Visible = True then
sordentrabajo.SetFocus
else
btnImprime.SetFocus;
end;
procedure TfrmReportesAlmacen2.FechaIKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
FechaF.SetFocus
end;
procedure TfrmReportesAlmacen2.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := cafree;
end;
procedure TfrmReportesAlmacen2.FormContextPopup(Sender: TObject;
MousePos: TPoint; var Handled: Boolean);
begin
Handled := True;
end;
procedure TfrmReportesAlmacen2.FormShow(Sender: TObject);
begin
try
Zoordentrabajo.Active := false;
Zoordentrabajo.ParamByName('contrato').AsString := global_contrato;
Zoordentrabajo.Open;
qryAlmacenes.Active := false;
qryAlmacenes.Open;
try
cboAlmacen.KeyValue := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
except
end;
qryfamilias.Active := false;
qryfamilias.Open;
try
cboFamilia.KeyValue := qryfamilias.FieldByName('sIdFamilia').AsString;
except
end;
except
end;
blockFechas(False);
end;
procedure TfrmReportesAlmacen2.frxAnexoDMAClosePreview(Sender: TObject);
begin
frmReportesAlmacen2.Visible := True;
end;
procedure TfrmReportesAlmacen2.frxInsumosClosePreview(Sender: TObject);
begin
frmReportesAlmacen2.Visible := True;
end;
procedure TfrmReportesAlmacen2.frxInsumosGetValue(const VarName: string;
var Value: Variant);
begin
if CompareText(VarName, 'sStock') = 0 then
Value := stock;
end;
procedure TfrmReportesAlmacen2.frxmaterialClosePreview(Sender: TObject);
begin
frmReportesAlmacen2.Visible := True;
end;
procedure TfrmReportesAlmacen2.frxmaterialGetValue(const VarName: string;
var Value: Variant);
begin
if CompareText(VarName, 'FechaFinal') = 0 then
Value := DateToStr(FechaF.date) ;
end;
procedure TfrmReportesAlmacen2.frxRecepcionDeMaterialesClosePreview(
Sender: TObject);
begin
frmReportesAlmacen2.Visible := True;
end;
procedure TfrmReportesAlmacen2.frxReport1ClosePreview(Sender: TObject);
begin
frmReportesAlmacen2.Visible := True;
end;
procedure TfrmReportesAlmacen2.btnImprimeClick(Sender: TObject);
begin
if Not ImprimirTodasLasFamilias.Checked then begin
AplicaFamilia := 'AND i.sIdGrupo = ' + QuotedStr(qryFamilias.FieldByName('sIdFamilia').AsString);
end else begin
AplicaFamilia := '';
end;
if smaterial.Checked then
begin
MaterialesInstalado;
end;
if rMateriales.Checked then
begin
Materiales;
end;
if rMaterialesFoto.Checked then
begin
MaterialesConFoto;
end;
if rStockMinimo.Checked then
begin
MaterialesSetockMinimo;
end;
if rStockMaximo.Checked then
begin
MaterialesStockMaximo;
end;
if rMaterialesPerecederos.Checked then
begin
MaterialesPerecederos;
end;
if rMaterialesUbicacion.Checked then
begin
MaterialesUbicacion;
end;
if rAnexoF.Checked then
begin
AnexoF;
end;
if rAnexoDMA.Checked then
begin
AnexoDMA;
end;
if rRecepciondeMateriales.Checked then begin
RecepcionDeMateriales;
end;
end;
procedure TfrmReportesAlmacen2.cboAlmacenKeyPress(Sender: TObject;
var Key: Char);
begin
if key =#13 then
cboFamilia.SetFocus;
end;
procedure TfrmReportesAlmacen2.cboFamiliaKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then
ImprimirTodasLasFamilias.SetFocus;
end;
procedure TfrmReportesAlmacen2.ImprimirTodasLasFamiliasClick(Sender: TObject);
begin
cboFamilia.Enabled := Not ImprimirTodasLasFamilias.Checked;
end;
procedure TfrmReportesAlmacen2.ImprimirTodasLasFamiliasKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then
FechaI.SetFocus
end;
procedure TfrmReportesAlmacen2.MaterialesInstalado;
begin
Zmaterial.Active := false;
Zmaterial.SQL.Clear ;
Zmaterial.SQL.Add('select concat(format(sum(dAvancePonderadoDia),4),"%") as avance '+
' from avancesglobales where sNumeroOrden = :orden and sIdConvenio = :convenio and scontrato = :contrato and dIdFecha <=:fechaF ; ');
Zmaterial.ParamByName('orden').AsString := sordentrabajo.Text ;
Zmaterial.ParamByName('contrato').AsString := global_contrato;
Zmaterial.ParamByName('convenio').AsString := global_convenio;
//Zmaterial.ParamByName('FechaI').AsDate := JvDatePickerEdit1.Date;
Zmaterial.ParamByName('fechaF').AsDate := FechaF.Date;
Zmaterial.Open;
Zglobales.Active := false;
Zglobales.SQL.Clear ;
Zglobales.SQL.Add('select concat(format(sum(dAvance),4),"%") as avancereal '+
'from avancesglobalesxorden where sNumeroOrden = :orden and sIdConvenio = :convenio and scontrato = :contrato and dIdFecha <=:fechaF; ');
Zglobales.ParamByName('orden').AsString := sordentrabajo.Text ;
Zglobales.ParamByName('contrato').AsString := global_contrato;
Zglobales.ParamByName('convenio').AsString := global_convenio;
//Zmaterial.ParamByName('FechaI').AsDate := JvDatePickerEdit1.Date;
Zglobales.ParamByName('fechaF').AsDate := FechaF.Date;
Zglobales.Open;
Zbitacora.Active := false;
Zbitacora.SQL.Clear ;
Zbitacora.SQL.Add('select a.sIdMaterial,a.sDescripcion, b.dExistencia, sum(a.dCantidad)as cantidadinst '+
'from bitacorademateriales a inner join insumos b on ((:Principal=-1 or (:Principal<>-1 and b.sContrato = a.sContrato)) and b.sIdInsumo = a.sIdMaterial) '+
'where a.scontrato = :contrato and dIdFecha between :FechaI and :fechaF group by a.sIdMaterial ; ');
Zbitacora.ParamByName('contrato').AsString := global_contrato;
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Zbitacora.ParamByName('Principal').AsString := 'Si'
else
Zbitacora.ParamByName('Principal').AsInteger :=-1;
Zbitacora.ParamByName('FechaI').AsDate := FechaI.Date;
Zbitacora.ParamByName('fechaF').AsDate := FechaF.Date;
Zbitacora.Open;
Zordentrabajo.SQL.Clear ;
Zordentrabajo.SQL.Add('Select '+
' mDescripcion as descripcionfrente, soficioAutorizacion '+
'From ordenesdetrabajo '+
'Where sContrato = :Contrato ');
Zordentrabajo.ParamByName('Contrato').asString := global_contrato ;
Zordentrabajo.Open ;
frmReportesAlmacen2.Visible := False;
frxmaterial.LoadFromFile(global_files + global_miReporte+ '_ALMMaterialListado.fr3');
if not FileExists(global_files + global_miReporte + '_ALMMaterialListado.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMMaterialListado.fr3 no existe, notifique al administrador del sistema');
frxmaterial.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesAlmacen2.Materiales;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add(' select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
' i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
' i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, ' +
' f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
' left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
' left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
' where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen '+AplicaFamilia+' ' +
' order by i.sIdGrupo, a.sDescripcion, i.sIdinsumo ');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
Imp_Insumos.Open;
frmReportesAlmacen2.Visible := False;
frxinsumos.LoadFromFile(global_files + global_miReporte+ '_ALMinsumos.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos.fr3 no existe, notifique al administrador del sistema');
frxinsumos.ShowReport();
end;
procedure TfrmReportesAlmacen2.RecepcionDeMateriales;
begin
zq_historialdemateriales_detalles.Active := False;
zq_historialdemateriales_detalles.Params.ParamByName('FechaInicio').AsDate := FechaI.Date;
zq_historialdemateriales_detalles.Params.ParamByName('FechaTermino').AsDate := FechaF.Date;
zq_historialdemateriales_detalles.Params.ParamByName('Contrato').AsString := Global_Contrato;
zq_historialdemateriales_detalles.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
zq_historialdemateriales_detalles.Open;
frmReportesAlmacen2.Visible := False;
frxRecepcionDeMateriales.LoadFromFile(global_files + global_miReporte + '_ALMrHistorialDeRecepcionDeMateriales.fr3');
if not FileExists(global_files + global_miReporte + '_ALMrHistorialDeRecepcionDeMateriales.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMrHistorialDeRecepcionDeMateriales.fr3 no existe, notifique al administrador del sistema');
frxRecepcionDeMateriales.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesAlmacen2.MaterialesConFoto;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add('select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
'i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
'i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, i.bImagen, ' +
'f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
'left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
'left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
'where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen '+AplicaFamilia+' order by i.sIdGrupo, a.sDescripcion, i.sIdinsumo ');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').DataType := ftString;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
Imp_Insumos.Open;
frmReportesAlmacen2.Visible := False;
frxinsumos.LoadFromFile(global_files + global_MiReporte + '_ALMinsumos_fotos.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos_fotos.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos_fotos.fr3 no existe, notifique al administrador del sistema');
frxinsumos.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesAlmacen2.MaterialesSetockMinimo;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add(' select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
' i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
' i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, ' +
' f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
' left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
' left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
' where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen ' +
' and i.dExistencia <= i.dStockMin '+AplicaFamilia+' order by f.sDescripcion, i.sIdinsumo');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
Imp_Insumos.Open;
stock := 'MINIMO';
frmReportesAlmacen2.Visible := False;
frxinsumos.LoadFromFile(global_files + global_miReporte +'_ALMinsumos_stockMin.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos_stockMin.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos_stockMin.fr3 no existe, notifique al administrador del sistema');
frxinsumos.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesAlmacen2.MaterialesStockMaximo;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add(' select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
' i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
' i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, ' +
' f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
' left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
' left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
' where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen '+AplicaFamilia+' ' +
' and i.dExistencia >= i.dStockMax and i.dStockMax > 0 order by f.sDescripcion, i.sIdinsumo ');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
Imp_Insumos.Open;
stock := 'MAXIMO';
frmReportesAlmacen2.Visible := False;
frxinsumos.LoadFromFile(global_files + global_miReporte + '_ALMinsumos_stockMin.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos_stockMin.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos_stockMin.fr3 no existe, notifique al administrador del sistema');
frxinsumos.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesalmacen2.MaterialesPerecederos;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add(' select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
' i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
' i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, ' +
' f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
' left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
' left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
' where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen ' +
' and i.dFechaCaducidad <=:fecha and i.lAplicaFecha = "Si" and sIdGrupo like :grupo order by f.sDescripcion, i.sIdinsumo');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
if ImprimirTodaslasfamilias.Checked then
Imp_Insumos.Params.ParamByName('Grupo').AsString := '%'
else
Imp_Insumos.Params.ParamByName('Grupo').AsString := qryFamilias.FieldByName('sIdFamilia').AsString + '%';
Imp_Insumos.Params.ParamByName('fecha').AsDate := fechaF.Date;
Imp_Insumos.Open;
frxinsumos.LoadFromFile(global_files + global_miReporte+ '_ALMinsumos_perecederos.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos_perecederos.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos_perecederos.fr3 no existe, notifique al administrador del sistema');
if Imp_Insumos.RecordCount = 0 then
messagedlg('No se encontraron Materiales Perecederos en las Familias y Fechas Especificados!', mtInformation, [mbOk], 0);
frmReportesAlmacen2.Visible := False;
frxinsumos.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesalmacen2.MaterialesUbicacion;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add(' select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
' i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
' i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, ' +
' f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
' left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
' left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
' where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen '+AplicaFamilia+' ' +
' order by f.sDescripcion, i.sUbicacion, i.sIdinsumo');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
Imp_Insumos.Open;
frmReportesAlmacen2.Visible := False;
frxinsumos.LoadFromFile(global_files + global_miReporte+ '_ALMinsumos_ubicacion.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos_ubicacion.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos_ubicacion.fr3 no existe, notifique al administrador del sistema');
frxinsumos.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesAlmacen2.rAnexoDMAClick(Sender: TObject);
begin
cboFamilia.Enabled := not rAnexoDMA.Checked;
ImprimirTodasLasFamilias.Enabled := False;
sordentrabajo.Visible := false;
blockFechas(True);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rAnexoFClick(Sender: TObject);
begin
cboFamilia.Enabled := not rAnexoF.Checked;
sordentrabajo.Visible := false;
blockFechas(False);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rMaterialesClick(Sender: TObject);
begin
cboFamilia.Enabled := rMateriales.Checked;
blockFechas(False);
sordentrabajo.Visible := false;
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rMaterialesFotoClick(Sender: TObject);
begin
cboFamilia.Enabled := rMaterialesFoto.Checked;
blockFechas(False);
sordentrabajo.Visible := false;
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rMaterialesPerecederosClick(Sender: TObject);
begin
cboFamilia.Enabled := rMaterialesPerecederos.Checked;
blockFechas(True);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rMaterialesUbicacionClick(Sender: TObject);
begin
//cboFamilia.Enabled := not rMaterialesUbicacion.Checked;
sordentrabajo.Visible := false;
blockFechas(False);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rRecepciondeMaterialesClick(Sender: TObject);
begin
FechaI.Enabled := rRecepcionDeMateriales.Checked;
FechaF.Enabled := rRecepcionDeMateriales.Checked;
cboFamilia.Enabled := False;
sordentrabajo.Visible := false;
blockFechas(True);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rStockMaximoClick(Sender: TObject);
begin
cboFamilia.Enabled := rStockMaximo.Checked;
sordentrabajo.Visible := false;
ImprimirTodasLasFamilias.Enabled := True;
blockFechas(False);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesAlmacen2.rStockMinimoClick(Sender: TObject);
begin
cboFamilia.Enabled := rStockMinimo.Checked;
sordentrabajo.Visible := false;
ImprimirTodasLasFamilias.Enabled := True;
blockFechas(False);
ImprimirTodasLasFamilias.Enabled := True;
end;
procedure TfrmReportesalmacen2.AnexoDMA;
begin
qryAnexoDMA.Active := False;
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
qryAnexoDMA.ParamByName('contrato').AsString := global_contrato
else
qryAnexoDMA.ParamByName('Contrato').AsInteger :=-1;
qryAnexoDMA.Params.ParamByName('almacen').DataType := ftString;
qryAnexoDMA.Params.ParamByName('almacen').Value := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
qryAnexoDMA.Open;
frmReportesAlmacen2.Visible := False;
if qryAnexoDMA.RecordCount > 0 then
begin
frxAnexoDMA.LoadFromFile(Global_Files + global_miReporte+ '_ALMDmaMateriales.fr3');
if not FileExists(global_files + global_miReporte + '_ALMDmaMateriales.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMDmaMateriales.fr3 no existe, notifique al administrador del sistema');
frxAnexoDMA.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end
else
messageDLG('No se encontro informacion a Imprimir', mtInformation, [mbOk], 0);
end;
procedure TfrmReportesalmacen2.AnexoF;
begin
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add(' select i.sContrato, i.sIdInsumo, i.sIdProveedor, i.sIdAlmacen, i.sTipoActividad, i.mDescripcion, i.dFecha, i.dFechaInicio, i.dFechaFinal, ' +
' i.dCostoMN, i.dCostoDLL, i.dVentaMN, i.dVentaDLL, i.sMedida, i.dCantidad, i.dInstalado, i.sIdFase, i.dPorcentaje, ' +
' i.sIdGrupo, i.dNuevoPrecio, i.dExistencia, i.sUbicacion, i.dStockMax, i.dStockMin, i.lAplicaFecha, i.dFechaCaducidad, ' +
' f.sDescripcion, a.sDescripcion as almacen from insumos i ' +
' left join familias f ON(i.sIdGrupo = f.sIdFamilia) ' +
' left join almacenes a on(a.sIdAlmacen = i.sIdAlmacen) ' +
' where (:Contrato=-1 or (:Contrato<>-1 and i.sContrato = :Contrato)) and i.sIdAlmacen =:Almacen '+AplicaFamilia+' ' +
' order by f.sDescripcion, i.sIdinsumo');
If Connection.configuracion.fieldValues['sAlmcon'] = 'CONTRATOS' Then
Imp_Insumos.ParamByName('contrato').AsString := global_contrato
else
Imp_Insumos.ParamByName('Contrato').AsInteger :=-1;
Imp_Insumos.Params.ParamByName('Almacen').AsString := qryAlmacenes.FieldByName('sIdAlmacen').AsString;
Imp_Insumos.Open;
frmReportesAlmacen2.Visible := False;
frxinsumos.PreviewOptions.MDIChild := False;
frxinsumos.PreviewOptions.Modal := True;
frxinsumos.PreviewOptions.ShowCaptions := False;
frxinsumos.Previewoptions.ZoomMode := zmPageWidth;
frxinsumos.LoadFromFile(global_files + global_miReporte + '_ALMinsumos_anexo.fr3');
if not FileExists(global_files + global_miReporte + '_ALMinsumos_anexo.fr3') then
showmessage('El archivo de reporte '+global_Mireporte+'_ALMinsumos_anexo.fr3 no existe, notifique al administrador del sistema');
frxinsumos.ShowReport();
FechaI.Date := Date;
FechaF.Date := Date;
end;
procedure TfrmReportesalmacen2.Seguimiento;
var
QryCompras,
QryRequisiciones: TZReadOnlyQuery;
dsCompras,
dsRequisiciones: TfrxDBDataSet;
tOrigen: TComponent;
begin
QryCompras := TZReadOnlyQuery.Create(tOrigen);
QryCompras.Connection := connection.zConnection;
QryRequisiciones := TZReadOnlyQuery.Create(tOrigen);
QryRequisiciones.Connection := connection.zConnection;
dsCompras := TfrxDBDataSet.Create(tOrigen);
dsCompras.DataSet := QryCompras;
dsCompras.FieldAliases.Clear;
dsCompras.UserName := 'dsCompras';
dsRequisiciones := TfrxDBDataSet.Create(tOrigen);
dsRequisiciones.DataSet := QryRequisiciones;
dsRequisiciones.FieldAliases.Clear;
dsRequisiciones.UserName := 'dsRequisiciones';
Imp_Insumos.Active := False;
Imp_Insumos.SQL.Clear;
Imp_Insumos.SQL.Add('select sIdInsumo, sTipoActividad, mDescripcion, sMedida, dExistencia from insumos where sContrato =:Contrato and sIdInsumo =:Insumo ');
Imp_Insumos.Params.ParamByName('Contrato').AsString := global_contrato;
// Imp_Insumos.Params.ParamByName('Insumo').AsString := insumos.FieldValues['sIdInsumo'];
Imp_Insumos.Open;
QryCompras.Active := False;
QryCompras.SQL.Clear;
QryCompras.SQL.Add('select pp.mDescripcion, pp.sMedida, pp.dCantidad, pp.sNumeroOrden, p.sOrdenCompra ' +
'from anexo_ppedido pp ' +
'inner join anexo_pedidos p on (pp.sContrato = p.sContrato and pp.iFolioPedido = p.iFolioPedido) ' +
'where pp.sContrato =:Contrato and pp.sIdInsumo =:Insumo');
QryCompras.Params.ParamByName('Contrato').AsString := global_contrato;
// QryCompras.Params.ParamByName('Insumo').AsString := insumos.FieldValues['sIdInsumo'];
QryCompras.Open;
QryRequisiciones.Active := False;
QryRequisiciones.SQL.Clear;
QryRequisiciones.SQL.Add('select pp.mDescripcion, pp.sMedida, pp.dCantidad, pp.sNumeroOrden, p.iFolioRequisicion, p.sLugarEntrega ' +
'from anexo_prequisicion pp ' +
'inner join anexo_requisicion p on (pp.sContrato = p.sContrato and pp.iFolioRequisicion = p.iFolioRequisicion) ' +
'where pp.sContrato =:Contrato ' +
'and pp.sIdInsumo =:Insumo ');
QryRequisiciones.Params.ParamByName('Contrato').AsString := global_contrato;
// QryRequisiciones.Params.ParamByName('Insumo').AsString := insumos.FieldValues['sIdInsumo'];
QryRequisiciones.Open;
frxInsumos.DataSets.Add(dsCompras);
frxInsumos.DataSets.Add(dsRequisiciones);
frxinsumos.LoadFromFile(global_files + global_MiReporte + '_seguimiento_material.fr3');
frxinsumos.ShowReport();
QryCompras.Destroy;
dsCompras.Destroy;
end;
procedure TfrmReportesAlmacen2.smaterialClick(Sender: TObject);
begin
cboFamilia.Enabled := smaterial.Checked;
blockFechas(True);
cboFamilia.Enabled := False;
sordentrabajo.Visible := true;
JvLabel1.Visible := true;
end;
procedure TfrmReportesAlmacen2.sordentrabajoKeyPress(Sender: TObject;
var Key: Char);
begin
if key=#13 then
btnImprime.SetFocus
end;
procedure TfrmReportesAlmacen2.blockFechas(lParam: Boolean);
begin
FechaI.Visible := lParam;
FechaF.Visible := lParam;
FechaI.Enabled := lParam;
FechaF.Enabled := lParam;
label3.Visible := lParam;
label4.Visible := lParam;
end;
end.
|
{*
FrameAcceptCancel.pas/dfm
-------------------------
Begin: 2005/11/10
Last revision: $Date: 2011-01-26 04:33:22 $ $Author: areeves $
Version number: $Revision: 1.6.20.1 $
Last revision: $Date: 2010-11-02 18:16:23 $ $Author: rhupalo $
Version number: $Revision: 1.8 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Aaron Reeves <aaron.reeves@naadsm.org>
--------------------------------------------------
Copyright (C) 2005 - 2010 Animal Population Health Institute, Colorado State University
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.
-----------------------------------------------------
Click events used from the buttons in this frame can be used on a form to invoke user input validation
rules on accept, or ignore and clear edits on cancel for one or a series of user input controls.
}
(*
Documentation generation tags begin with {* or ///
Replacing these with (* or // foils the documentation generator
*)
unit FrameAcceptCancel;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
StdCtrls,
Buttons
;
type
/// Buttons providing click events to process something on container form
TFrameAcceptCancel = class( TFrame )
btnAccept: TBitBtn; /// provides click event to submit some input entry
btnCancel: TBitBtn; /// provides click event to cancel input entry
protected
procedure translateUI();
public
constructor create( AOwner: TComponent ); override;
end
;
implementation
{$R *.dfm}
uses
I88n
;
{*
Creates an instance of the frame
@param AOwner the form that owns this instance of the frame
}
constructor TFrameAcceptCancel.create( AOwner: TComponent );
begin
inherited create( AOwner );
translateUI();
end
;
/// Specifies the captions, hints, and other component text phrases for translation
procedure TFrameAcceptCancel.translateUI();
begin
// This function was generated automatically by Caption Collector 0.6.0.
// Generation date: Mon Feb 25 15:29:38 2008
// File name: C:/Documents and Settings/apreeves/My Documents/NAADSM/Interface-Fremont/general_purpose_gui/FrameAcceptCancel.dfm
// File date: Thu Nov 10 10:52:48 2005
// Set Caption, Hint, Text, and Filter properties
with self do
begin
btnAccept.Hint := tr( 'Accept changes' );
btnCancel.Hint := tr( 'Cancel changes' );
end
;
end
;
end.
|
unit Controller.Category;
interface
uses
Uni, Model.Entity.Category;
type
TCategoryController = class
private
FConn: TUniConnection;
private
function GenerateID: Integer;
public
function AddCategory(ACategory: TCategory): Boolean;
public
constructor Create(AConn: TUniConnection);
end;
implementation
{ TCategoryController }
function TCategoryController.AddCategory(ACategory: TCategory): Boolean;
const
cSQL =
'insert into Categories(ID, CategoryName, Parent_ID) ' + #13 +
' values (:ID, :CategoryName, :ParentID)';
begin
if ACategory.ID = 0 then
ACategory.ID := GenerateID;
with TUniQuery.Create(nil) do try
Connection := FConn;
finally
Free;
end;
end;
constructor TCategoryController.Create(AConn: TUniConnection);
begin
FConn := AConn;
end;
function TCategoryController.GenerateID: Integer;
const
cSQL =
'select max(ID) + 1 as NewID from ' + #13 +
' (select ID from Categories where ID < 1000)';
begin
Result := 0;
with TUniQuery.Create(nil) do try
Connection := FConn;
SQL.Text := cSQL;
ExecSQL;
if not IsEmpty then
Result := FieldByName('NewID').AsInteger;
finally
Free;
end;
end;
end.
|
{$mode objfpc}
unit Queue;
interface
type EEmpty = class
end;
type generic TQueueSingleNode<_T> = class
private
_Value: _T;
_Next : TQueueSingleNode;
public
constructor CreateFromValue( item : _T );
procedure SetNext( node : TQueueSingleNode );
function GetNext : TQueueSingleNode;
function GetValue : _T;
end;
type generic TQueueSingle<_T> = class
type TNode = specialize TQueueSingleNode<_T>;
private
_Head: TNode;
_Tail: TNode;
_Count: integer;
public
constructor Create;
destructor Free;
procedure Enqueue( item : _T );
function Dequeue : _T;
function GetCount : integer;
end;
implementation
constructor TQueueSingleNode.CreateFromValue( item : _T );
begin
_Value := item;
_Next := nil;
end;
constructor TQueueSingle.Create;
begin
_Head := nil;
_Tail := nil;
_Count := 0;
end;
destructor TQueueSingle.Free;
begin
while _Head <> nil do begin
Dequeue;
end;
end;
procedure TQueueSingleNode.SetNext( node : TQueueSingleNode );
begin
_Next := node;
end;
function TQueueSingleNode.GetNext : TQueueSingleNode;
begin
Result := _Next;
end;
function TQueueSingle.GetCount : integer;
begin
Result := _Count;
end;
function TQueueSingleNode.GetValue : _T;
begin
Result := _Value;
end;
procedure TQueueSingle.Enqueue( item : _T );
var appendee: TNode;
begin
if _Head = nil then begin
_Head := TNode.CreateFromValue( item );
_Tail := _Head;
end else begin
appendee := TNode.CreateFromValue( item );
_Tail.SetNext( appendee );
_Tail := appendee;
end;
_Count := _Count + 1;
end;
function TQueueSingle.Dequeue : _T;
var exHead: TNode;
begin
if _Head = nil then begin
raise EEmpty.Create;
end else begin
exHead := _Head;
_Head := _Head.GetNext;
Result := exHead.GetValue;
exHead.Free;
_Count := _Count - 1;
if _Head = nil then
_Tail := nil;
end;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
//
//
// FileName : SUIMainMenu.pas
// Creator : Shen Min
// Date : 2002-05-26 V1-V3
// 2003-06-15 V4
// Comment :
//
// Copyright (c) 2002-2003 Sunisoft
// http://www.sunisoft.com
// Email: support@sunisoft.com
//
////////////////////////////////////////////////////////////////////////////////
unit SUIMainMenu;
interface
{$I SUIPack.inc}
uses Windows, Classes, Menus, Forms, Graphics, ImgList, Controls, ComCtrls, SysUtils,
SUIForm, SUIThemes, SUIMgr;
type
TsuiMainMenu = class(TMainMenu)
private
m_Images : TCustomImageList;
m_UIStyle : TsuiUIStyle;
m_Height : Integer;
m_SeparatorHeight : Integer;
m_BarColor : TColor;
m_BarWidth : Integer;
m_Color : TColor;
m_SeparatorColor : TColor;
m_SelectedBorderColor : TColor;
m_SelectedColor : TColor;
m_SelectedFontColor : TColor;
m_FontColor : TColor;
m_BorderColor : TColor;
m_FlatMenu : Boolean;
m_FontName : TFontName;
m_FontSize : Integer;
m_FontCharset : TFontCharset;
m_UseSystemFont : Boolean;
m_Form: TsuiForm;
m_FileTheme : TsuiFileTheme;
function GetImages() : TCustomImageList;
procedure SetImages(const Value : TCustomImageList);
function GetOwnerDraw() : Boolean;
procedure SetOwnerDraw(const Value : Boolean);
procedure DrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; Selected: Boolean);
procedure MeasureItem(Sender: TObject; ACanvas: TCanvas; var Width, Height: Integer);
procedure SetUIStyle(const Value: TsuiUIStyle);
procedure SetHeight(const Value: Integer);
procedure SetSeparatorHeight(const Value: Integer);
procedure SetUseSystemFont(const Value: Boolean);
procedure SetFileTheme(const Value: TsuiFileTheme);
protected
procedure MenuChanged(Sender: TObject; Source: TMenuItem; Rebuild: Boolean); override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
procedure AfterConstruction(); override;
procedure MenuAdded();
property Form : TsuiForm read m_Form write m_Form;
published
property Images read GetImages write SetImages;
property OwnerDraw read GetOwnerDraw write SetOwnerDraw;
property FileTheme : TsuiFileTheme read m_FileTheme write SetFileTheme;
property UIStyle : TsuiUIStyle read m_UIStyle write SetUIStyle;
property MenuItemHeight : Integer read m_Height write SetHeight;
property SeparatorHeight : Integer read m_SeparatorHeight write SetSeparatorHeight;
property BarWidth : Integer read m_BarWidth write m_BarWidth;
property BarColor : TColor read m_BarColor write m_BarColor;
property Color : TColor read m_Color write m_Color;
property SeparatorColor : TColor read m_SeparatorColor write m_SeparatorColor;
property SelectedBorderColor : TColor read m_SelectedBorderColor write m_SelectedBorderColor;
property SelectedColor : TColor read m_SelectedColor write m_SelectedColor;
property SelectedFontColor : TColor read m_SelectedFontColor write m_SelectedFontColor;
property FontColor : TColor read m_FontColor write m_FontColor;
property BorderColor : TColor read m_BorderColor write m_BorderColor;
property FlatMenu : Boolean read m_FlatMenu write m_FlatMenu;
property FontName : TFontName read m_FontName write m_FontName;
property FontSize : Integer read m_FontSize write m_FontSize;
property FontCharset : TFontCharset read m_FontCharset write m_FontCharset;
property UseSystemFont : Boolean read m_UseSystemFont write SetUseSystemFont;
end;
implementation
uses SUIResDef, SUIPublic, SUIMenu;
{ TsuiMainMenu }
procedure TsuiMainMenu.AfterConstruction;
begin
inherited;
if not (Owner is TCustomForm) then
Exit;
(Owner as TCustomForm).Menu := nil;
end;
constructor TsuiMainMenu.Create(AOwner: TComponent);
var
Bmp : TBitmap;
begin
inherited;
m_Images := TImageList.Create(self);
Bmp := TBitmap.Create();
Bmp.LoadFromResourceName(
hInstance,
'MENU_CHECKED'
);
Bmp.Transparent := True;
m_Images.AddMasked(Bmp, clWhite);
Bmp.Free();
inherited Images := m_Images;
m_Height := 21;
m_SeparatorHeight := 21;
m_BarColor := clBtnFace;
m_BarWidth := 0;
m_Color := clWhite;
m_SeparatorColor := clGray;
m_SelectedBorderColor := clHighlight;
m_SelectedColor := clHighlight;
m_SelectedFontColor := clWhite;
m_FontColor := clWhite;
m_BorderColor := clBlack;
m_FlatMenu := false;
m_FontName := 'MS Sans Serif';
m_FontSize := 8;
m_FontCharset := DEFAULT_CHARSET;
m_UseSystemFont := true;
UIStyle := GetSUIFormStyle(AOwner);
end;
destructor TsuiMainMenu.Destroy;
begin
m_Images.Free();
m_Images := nil;
inherited;
end;
procedure TsuiMainMenu.DrawItem(Sender: TObject; ACanvas: TCanvas;
ARect: TRect; Selected: Boolean);
var
OutUIStyle : TsuiUIStyle;
R : TRect;
Cap : String;
ShortKey : String;
nCharLength : Integer;
nCharStart : Integer;
Item : TMenuItem;
HandleOfMenuWindow : HWND;
L2R : Boolean;
Style : Cardinal;
X : Integer;
begin
Item := Sender as TMenuItem;
L2R := (BiDiMode = bdLeftToRight) or (not SysLocale.MiddleEast);
if m_FlatMenu then
begin
HandleOfMenuWindow := WindowFromDC(ACanvas.Handle);
if HandleOfMenuWindow <> 0 then
begin
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
Menu_DrawWindowBorder(
HandleOfMenuWindow,
clBlack,
m_FileTheme.GetColor(SUI_THEME_FORM_BACKGROUND_COLOR)
)
else
Menu_DrawWindowBorder(
HandleOfMenuWindow,
clBlack,
GetInsideThemeColor(OutUIStyle, SUI_THEME_FORM_BACKGROUND_COLOR)
)
end;
end;
// draw line
if Item.Caption = '-' then
begin
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Menu_DrawMacOSLineItem(ACanvas, ARect)
else
{$ENDIF}
begin
// draw Left bar
if L2R then
begin
if m_BarWidth > 0 then
begin
R := Rect(ARect.Left, ARect.Top, ARect.Left + m_BarWidth, ARect.Bottom);
Menu_DrawBackGround(ACanvas, R, m_BarColor);
end;
// draw right non-bar
R := Rect(ARect.Left + m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom);
end
else
begin
if m_BarWidth > 0 then
begin
R := Rect(ARect.Right - m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom);
Menu_DrawBackGround(ACanvas, R, m_BarColor);
end;
// draw right non-bar
R := Rect(ARect.Left, ARect.Top, ARect.Right - m_BarWidth, ARect.Bottom);
end;
Menu_DrawBackGround(ACanvas, R, m_Color);
// draw line
Menu_DrawLineItem(ACanvas, ARect, m_SeparatorColor, m_BarWidth, L2R);
end;
Exit;
end; // draw line
// draw background
if Selected and Item.Enabled then
begin
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Menu_DrawMacOSSelectedItem(ACanvas, ARect)
else
{$ENDIF}
begin
Menu_DrawBackGround(ACanvas, ARect, m_SelectedColor);
Menu_DrawBorder(ACanvas, ARect, m_SelectedBorderColor);
end;
end
else
begin
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
Menu_DrawMacOSNonSelectedItem(ACanvas, ARect)
else
{$ENDIF}
begin
// draw left bar
if m_BarWidth > 0 then
begin
if L2R then
R := Rect(ARect.Left, ARect.Top, ARect.Left + m_BarWidth, ARect.Bottom)
else
R := Rect(ARect.Right - m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom);
Menu_DrawBackGround(ACanvas, R, m_BarColor);
end;
if L2R then
R := Rect(ARect.Left + m_BarWidth, ARect.Top, ARect.Right, ARect.Bottom)
else
R := Rect(ARect.Left, ARect.Top, ARect.Right - m_BarWidth, ARect.Bottom);
Menu_DrawBackGround(ACanvas, R, m_Color);
end
end;
// draw caption and shortkey
Cap := Item.Caption;
if m_UseSystemFont then
Menu_GetSystemFont(ACanvas.Font)
else
begin
ACanvas.Font.Name := m_FontName;
ACanvas.Font.Size := m_FontSize;
ACanvas.Font.Charset := m_FontCharset;
end;
ACanvas.Brush.Style := bsClear;
if Item.Enabled then
begin
if Selected then
ACanvas.Font.Color := m_SelectedFontColor
else
ACanvas.Font.Color := m_FontColor;
end
else
ACanvas.Font.Color := clGray;
if Item.Default then
ACanvas.Font.Style := ACanvas.Font.Style + [fsBold];
if L2R then
begin
R := Rect(ARect.Left + m_BarWidth + 4, ARect.Top + 4, ARect.Right, ARect.Bottom);
Style := DT_LEFT;
end
else
begin
R := Rect(ARect.Left, ARect.Top + 4, ARect.Right - m_BarWidth - 4, ARect.Bottom);
Style := DT_RIGHT;
end;
DrawText(ACanvas.Handle, PChar(Cap), -1, R, Style or DT_TOP or DT_SINGLELINE);
ShortKey := ShortCutToText(Item.ShortCut);
if L2R then
begin
nCharLength := ACanvas.TextWidth(ShortKey);
nCharStart := ARect.Right - nCharLength - 16;
end
else
begin
nCharStart := ARect.Left + 16;
end;
ACanvas.TextOut(nCharStart, ARect.Top + 4, ShortKey);
if L2R then
X := ARect.Left + 4
else
X := ARect.Right - 20;
// draw checked
if Item.Checked then
begin
if (
(Item.ImageIndex = -1) or
(Images = nil) or
(Item.ImageIndex >= Images.Count)
) then
m_Images.Draw(ACanvas, X, ARect.Top + 3, 0, Item.Enabled)
else
begin
ACanvas.Brush.Color := clBlack;
ACanvas.FrameRect(Rect(X - 2, ARect.Top + 1, X + 17, ARect.Top + 20));
ACanvas.Brush.Color := m_SelectedColor;
ACanvas.FillRect(Rect(X - 1, ARect.Top + 2, X + 16, ARect.Top + 19));
end;
end;
// draw images
if (Item.ImageIndex <> -1) and (Images <> nil) then
if Item.ImageIndex < Images.Count then
Images.Draw(ACanvas, X, ARect.Top + 3, Item.ImageIndex, Item.Enabled);
end;
function TsuiMainMenu.GetImages: TCustomImageList;
begin
if inherited Images = m_Images then
Result := nil
else
Result := inherited Images;
end;
function TsuiMainMenu.GetOwnerDraw: Boolean;
begin
Result := true;
end;
procedure TsuiMainMenu.Loaded;
begin
inherited;
MenuAdded();
end;
procedure TsuiMainMenu.MeasureItem(Sender: TObject; ACanvas: TCanvas;
var Width, Height: Integer);
var
Item : TMenuItem;
begin
Item := Sender as TMenuItem;
if Item.Caption = '-' then
Height := m_SeparatorHeight
else
Height := m_Height;
Width := ACanvas.TextWidth(Item.Caption) + ACanvas.TextWidth(ShortCutToText(Item.ShortCut)) + m_BarWidth + 40;
end;
procedure TsuiMainMenu.MenuAdded;
var
i : Integer;
begin
for i := 0 to Items.Count - 1 do
Menu_SetItemEvent(Items[i], DrawItem, MeasureItem);
if m_Form <> nil then
m_Form.UpdateMenu();
end;
procedure TsuiMainMenu.MenuChanged(Sender: TObject; Source: TMenuItem;
Rebuild: Boolean);
begin
inherited;
if not (Owner is TCustomForm) then
Exit;
if m_Form <> nil then
m_Form.UpdateTopMenu();
if (
(csLoading in ComponentState) or
(not (csDesigning in ComponentState))
) then
Exit;
if m_Form <> nil then
m_Form.UpdateMenu();
end;
procedure TsuiMainMenu.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (
(Operation = opRemove) and
(AComponent = m_FileTheme)
)then
begin
m_FileTheme := nil;
SetUIStyle(SUI_THEME_DEFAULT);
end;
if (
(Operation = opInsert) and
(AComponent is TMenuItem)
) then
begin
Menu_SetItemEvent(AComponent as TMenuItem, DrawItem, MeasureItem);
end;
end;
procedure TsuiMainMenu.SetFileTheme(const Value: TsuiFileTheme);
begin
m_FileTheme := Value;
SetUIStyle(m_UIStyle);
end;
procedure TsuiMainMenu.SetHeight(const Value: Integer);
begin
// if {$IFDEF RES_MACOS}m_UIStyle <> MacOS {$ELSE} True {$ENDIF} then
m_Height := Value;
end;
procedure TsuiMainMenu.SetImages(const Value: TCustomImageList);
begin
if Value = nil then
inherited Images := m_Images
else
inherited Images := Value;
end;
procedure TsuiMainMenu.SetOwnerDraw(const Value: Boolean);
begin
// Do nothing
end;
procedure TsuiMainMenu.SetSeparatorHeight(const Value: Integer);
begin
if {$IFDEF RES_MACOS}m_UIStyle <> MacOS {$ELSE} True {$ENDIF} then
m_SeparatorHeight := Value;
end;
procedure TsuiMainMenu.SetUIStyle(const Value: TsuiUIStyle);
var
OutUIStyle : TsuiUIStyle;
begin
m_UIStyle := Value;
m_BarWidth := 26;
{$IFDEF RES_MACOS}
if m_UIStyle = MacOS then
begin
m_Height := 20;
m_SeparatorHeight := 12;
m_SeparatorColor := 0;
end
else
{$ENDIF}
begin
m_Height := 21;
m_SeparatorHeight := 5;
m_SeparatorColor := $00848284;
end;
if UsingFileTheme(m_FileTheme, m_UIStyle, OutUIStyle) then
begin
m_BarColor := m_FileTheme.GetColor(SUI_THEME_MENU_LEFTBAR_COLOR);
m_Color := m_FileTheme.GetColor(SUI_THEME_MENU_BACKGROUND_COLOR);
m_FontColor := m_FileTheme.GetColor(SUI_THEME_MENU_FONT_COLOR);
m_SelectedBorderColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_BORDER_COLOR);
m_SelectedColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR);
m_SelectedFontColor := m_FileTheme.GetColor(SUI_THEME_MENU_SELECTED_FONT_COLOR);
end
else
begin
m_BarColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_LEFTBAR_COLOR);
m_Color := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_BACKGROUND_COLOR);
m_FontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_FONT_COLOR);
m_SelectedBorderColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_BORDER_COLOR);
m_SelectedColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_BACKGROUND_COLOR);
m_SelectedFontColor := GetInsideThemeColor(OutUIStyle, SUI_THEME_MENU_SELECTED_FONT_COLOR);
end;
end;
procedure TsuiMainMenu.SetUseSystemFont(const Value: Boolean);
begin
m_UseSystemFont := Value;
if m_Form <> nil then
m_Form.RepaintMenuBar();
end;
end.
|
unit Unit3;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm3 = class(TForm)
Label1: TLabel;
edtValor1: TEdit;
edtValor2: TEdit;
edtValor3: TEdit;
btCalcular: TButton;
edtVerificaSeEumTriangulo: TEdit;
edtTipoTriangulo: TEdit;
function verificarTriangulo(a: integer; b: integer; c: integer): string;
procedure btCalcularClick(Sender: TObject);
function tipoDeTriangulo(a: integer; b: integer; c: integer): string;
function verificar(a: string; b: string; c: string): boolean;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
{$R *.dfm}
{ TForm3 }
procedure TForm3.btCalcularClick(Sender: TObject);
begin
if (verificar(edtValor1.Text, edtValor2.Text, edtValor3.Text) = false) then
begin
ShowMessage('Você digitou um valor inválido, favor digitar um número');
end
else
begin
edtVerificaSeEumTriangulo.Text :=
verificarTriangulo(StrToInt(edtValor1.Text), (StrToInt(edtValor2.Text)),
(StrToInt(edtValor3.Text)));
edtTipoTriangulo.Text := tipoDeTriangulo(StrToInt(edtValor1.Text),
(StrToInt(edtValor2.Text)), (StrToInt(edtValor3.Text)));
end;
end;
function TForm3.tipoDeTriangulo(a, b, c: integer): string;
begin
if (a = b) and (b = c) then
begin
result := 'Equilatero';
end
else if (a = b) and (b <> c) or (a <> b) and (b = c) or (a <> b) and (a = c)
then
begin
result := 'Isosceles';
end
else if (a <> b) and (a <> c) then
begin
result := 'Escaleno';
end;
end;
function TForm3.verificar(a, b, c: string): boolean;
var
v: double;
begin
if (a <> '') and (b <> '') and (c <> '') then
begin
if (TryStrToFloat(a, v) and TryStrToFloat(b, v) and TryStrToFloat(c, v))
then
begin
result := true;
end
else
begin
result := false;
end
end
end;
function TForm3.verificarTriangulo(a, b, c: integer): string;
begin
if (a < b + c) and (b < a + c) and (c < a + b) then
begin
result := 'É um triangulo';
end
else
begin
result := 'Não é um triangulo';
end;
end;
end.
|
unit LibraryForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls, System.ImageList, Vcl.ImgList;
type
TMultiResult = record
OK: Boolean;
Value: string;
end;
TfrmLibrary = class(TForm)
lstLibrary: TListBox;
edtPath: TEdit;
btnOK: TButton;
btnCancel: TButton;
btnAdd: TButton;
btnReplace: TButton;
btnDelete: TButton;
btnInvalid: TButton;
btnLibraryDir: TButton;
il16Bis: TImageList;
procedure lstLibraryClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnReplaceClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure btnInvalidClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmLibrary: TfrmLibrary;
function EditLibrary(NameValue: string; Values: string): TMultiResult;
implementation
uses
GlobalUnit;
{$R *.dfm}
function EditLibrary(NameValue: string; Values: string): TMultiResult;
var
ListValues: TStringList;
begin
Result.OK := False;
frmLibrary := TfrmLibrary.Create(Application.MainForm);
with frmLibrary do
begin
ListValues := TStringList.Create;
Caption := NameValue;
Explode(';', Values, ListValues);
lstLibrary.Items.Assign(ListValues);
if ShowModal = mrOk then
begin
ListValues.Assign(lstLibrary.Items);
Result.Value := Implode(';', ListValues);
Result.OK := True;
end;
ListValues.Free;
end;
frmLibrary.Free;
end;
procedure TfrmLibrary.btnAddClick(Sender: TObject);
begin
if DirectoryExists(edtPath.Text) then
lstLibrary.Items.Add(edtPath.Text);
end;
procedure TfrmLibrary.btnDeleteClick(Sender: TObject);
begin
if lstLibrary.ItemIndex > -1 then
lstLibrary.Items.Delete(lstLibrary.ItemIndex);
end;
procedure TfrmLibrary.btnInvalidClick(Sender: TObject);
var
I: Integer;
Path: string;
begin
I := 0;
while I < lstLibrary.Items.Count do
begin
Path := lstLibrary.Items[I];
if not DirectoryExists(edtPath.Text) then
lstLibrary.Items.Delete(lstLibrary.ItemIndex)
else
Inc(I);
end;
end;
procedure TfrmLibrary.btnReplaceClick(Sender: TObject);
begin
if lstLibrary.ItemIndex > -1 then
if DirectoryExists(edtPath.Text) then
lstLibrary.Items[lstLibrary.ItemIndex] := edtPath.Text;
end;
procedure TfrmLibrary.lstLibraryClick(Sender: TObject);
begin
if lstLibrary.ItemIndex > -1 then
edtPath.Text := lstLibrary.Items[lstLibrary.ItemIndex];
end;
end.
|
unit SearchDescriptionsQuery;
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,
NotifyEvents, ProgressInfo, HandlingQueryUnit, DSWrap;
type
TSearchDescriptionW = class(TDSWrap)
private
FDescrID: TFieldWrap;
FID: TFieldWrap;
FDescriptionID: TFieldWrap;
FProductCategoryId: TParamWrap;
protected
public
constructor Create(AOwner: TComponent); override;
property DescrID: TFieldWrap read FDescrID;
property ID: TFieldWrap read FID;
property DescriptionID: TFieldWrap read FDescriptionID;
property ProductCategoryId: TParamWrap read FProductCategoryId;
end;
TQuerySearchDescriptions = class(THandlingQuery)
FDUpdateSQL: TFDUpdateSQL;
private
FW: TSearchDescriptionW;
{ Private declarations }
protected
property W: TSearchDescriptionW read FW;
public
constructor Create(AOwner: TComponent); override;
function Search(const AIDCategory: Integer): Integer; overload;
procedure SearchAll;
procedure UpdateComponentDescriptions(ASender: TObject);
{ Public declarations }
end;
implementation
{$R *.dfm}
uses ProgressBarForm, StrHelper;
constructor TQuerySearchDescriptions.Create(AOwner: TComponent);
begin
inherited;
FW := TSearchDescriptionW.Create(FDQuery);
end;
function TQuerySearchDescriptions.Search(const AIDCategory: Integer): Integer;
var
ASQL: string;
begin
Assert(AIDCategory > 0);
ASQL := SQL;
// Раскомментируем в запросе JOIN
ASQL := ASQL.Replace('/* ProductCategory', '', [rfReplaceAll]);
ASQL := ASQL.Replace('ProductCategory */', '', [rfReplaceAll]);
// Формируем запрос
FDQuery.SQL.Text := ASQL;
SetParamType(W.ProductCategoryId.FieldName);
Result := Search([W.ProductCategoryId.FieldName], [AIDCategory]);
end;
procedure TQuerySearchDescriptions.SearchAll;
begin
// Возвращаем базовый запрос
FDQuery.SQL.Text := SQL;
W.RefreshQuery;
end;
procedure TQuerySearchDescriptions.UpdateComponentDescriptions
(ASender: TObject);
var
i: Integer;
begin
Assert(FDQuery.Active);
// начинаем транзакцию, если она ещё не началась
if (not FDQuery.Connection.InTransaction) then
FDQuery.Connection.StartTransaction;
FDQuery.Last;
FDQuery.First;
i := 0;
CallOnProcessEvent;
while not FDQuery.Eof do
begin
// Связываем компоненты со своими описаниями
if W.DescriptionID.F.AsInteger <> W.DescrID.F.AsInteger then
begin
W.TryEdit;
W.DescriptionID.F.AsInteger := W.DescrID.F.AsInteger;
W.TryPost;
Inc(i);
// Уже много записей обновили в рамках одной транзакции
if i >= 1000 then
begin
i := 0;
FDQuery.Connection.Commit;
FDQuery.Connection.StartTransaction;
end;
end;
FDQuery.Next;
CallOnProcessEvent;
end;
FDQuery.Connection.Commit;
end;
constructor TSearchDescriptionW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'p.ID', '', True);
FDescrID := TFieldWrap.Create(Self, 'DescrID');
FDescriptionID := TFieldWrap.Create(Self, 'p.DescriptionID');
FProductCategoryId := TParamWrap.Create(Self, 'ppc.ProductCategoryId');
end;
end.
|
unit FIToolkit.Utils;
interface
uses
System.SysUtils,
FIToolkit.Types;
type
{ Helpers }
TApplicationCommandHelper = record helper for TApplicationCommand
public
function ToString : String;
end;
TApplicationStateHelper = record helper for TApplicationState
public
function ToString : String;
end;
{ Utils }
function GetAppVersionInfo : String;
function GetCLIOptionProcessingOrder(const OptionName : String; IgnoreCase : Boolean) : Integer;
function GetInputFileType(const FileName : TFileName) : TInputFileType;
function IsCaseSensitiveCLIOption(const OptionName : String) : Boolean;
function TryCLIOptionToAppCommand(const OptionName : String; IgnoreCase : Boolean;
out Command : TApplicationCommand) : Boolean;
implementation
uses
System.IOUtils, System.Rtti,
FIToolkit.Consts,
FIToolkit.Commons.Utils;
{ Utils }
function GetAppVersionInfo : String;
var
iMajor, iMinor, iRelease, iBuild : Word;
begin
if GetModuleVersion(HInstance, iMajor, iMinor, iRelease, iBuild) then
Result := Format('%s %d.%d.%d', [STR_APP_TITLE, iMajor, iMinor, iRelease])
else
Result := Format('%s %s', [STR_APP_TITLE, RSNoVersionInfoAvailable]);
end;
function GetCLIOptionProcessingOrder(const OptionName : String; IgnoreCase : Boolean) : Integer;
var
i : Integer;
begin
if not String.IsNullOrWhiteSpace(OptionName) then
for i := 0 to High(ARR_CLIOPTION_PROCESSING_ORDER) do
if ARR_CLIOPTION_PROCESSING_ORDER[i].Equals(OptionName) or
(IgnoreCase and AnsiSameText(ARR_CLIOPTION_PROCESSING_ORDER[i], OptionName))
then
Exit(i);
Result := -1;
end;
function GetInputFileType(const FileName : TFileName) : TInputFileType;
var
sFileExt : String;
X : TInputFileType;
begin
Result := iftUnknown;
sFileExt := TPath.GetExtension(FileName);
if not sFileExt.IsEmpty then
for X := Low(TInputFileType) to High(TInputFileType) do
if AnsiSameText(sFileExt, ARR_INPUT_FILE_TYPE_TO_EXT_MAPPING[X]) then
Exit(X);
end;
function IsCaseSensitiveCLIOption(const OptionName : String) : Boolean;
var
S : String;
begin
Result := False;
if not String.IsNullOrWhiteSpace(OptionName) then
for S in ARR_CASE_SENSITIVE_CLI_OPTIONS do
if AnsiSameText(S, OptionName) then
Exit(True);
end;
function TryCLIOptionToAppCommand(const OptionName : String; IgnoreCase : Boolean;
out Command : TApplicationCommand) : Boolean;
var
C : TApplicationCommand;
begin
Result := False;
if not String.IsNullOrWhiteSpace(OptionName) then
for C := Low(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING) to High(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING) do
if ARR_APPCOMMAND_TO_CLIOPTION_MAPPING[C].Equals(OptionName) or
(IgnoreCase and AnsiSameText(ARR_APPCOMMAND_TO_CLIOPTION_MAPPING[C], OptionName)) then
begin
Command := C;
Exit(True);
end;
end;
{ TApplicationCommandHelper }
function TApplicationCommandHelper.ToString : String;
begin
Result := TValue.From<TApplicationCommand>(Self).ToString;
end;
{ TApplicationStateHelper }
function TApplicationStateHelper.ToString : String;
begin
Result := TValue.From<TApplicationState>(Self).ToString;
end;
end.
|
unit LibUtils;
interface
uses
System.JSON, System.SysUtils;
function StrToJSON(AKey, AValue: string): string;
function GetJSONValue(AJSON, AKey: string): string;
function StrToJSONObject(AKey, AValue: string): TJSONObject;
implementation
function StrToJSON(AKey, AValue: string): string;
var
JSONObject: TJSONObject;
begin
JSONObject := TJSONObject.Create;
try
JSONObject.AddPair(AKey, AValue);
Result := JSONObject.ToJSON;
finally
FreeAndNil(JSONObject);
end;
end;
function StrToJSONObject(AKey, AValue: string): TJSONObject;
var
JSONObject: TJSONObject;
begin
JSONObject := TJSONObject.Create;
JSONObject.AddPair(AKey, AValue);
Result := JSONObject;
end;
function GetJSONValue(AJSON, AKey: string): string;
var
JSONValue : TJSONValue;
begin
try
JSONValue := TJSONObject.ParseJSONValue(AJSON);
Result := JSONValue.GetValue<string>(AKey);
finally
FreeAndNil(JSONValue);
end;
end;
end.
|
{*******************************************************************************
* *
* TksSlideMenu - Slide Menu 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 ksSlideMenu;
interface
{$I ksComponents.inc}
//{$DEFINE ADD_SAMPLE_MENU_ITEMS}
uses System.UITypes, FMX.Controls, FMX.Layouts, FMX.Objects, System.Classes,
FMX.Types, Generics.Collections, FMX.Graphics, System.UIConsts, FMX.Effects,
FMX.StdCtrls, System.Types, FMX.Forms, {ksTableView,} ksVirtualListView, ksTypes,
ksSlideMenuUI
{$IFDEF XE8_OR_NEWER}
,FMX.ImgList
{$ENDIF}
;
const
C_DEFAULT_MENU_WIDTH = 220;
C_DEFAULT_MENU_TOOLBAR_HEIGHT = 44;
C_DEFAULT_MENU_HEADER_HEIGHT = 30;
C_DEFAULT_MENU_HEADER_FONT_SIZE = 16;
C_DEFAULT_MENU_HEADER_TEXT_COLOR = claWhite;
C_DEFAULT_MENU_HEADER_COLOR = $FF323232;
C_DEFAULT_MENU_ITEM_HEIGHT = 50;
C_DEFAULT_MENU_FONT_SIZE = 14;
C_DEFAULT_MENU_TOOLBAR_FONT_SIZE = 14;
C_DEFAULT_MENU_SLIDE_SPEED = 0.15;
//C_DEFAULT_MENU_SELECTED_COLOR = claWhite;
C_DEFAULT_MENU_SELECTED_FONT_COLOR = claWhite;
C_DEFAULT_MENU_FONT_COLOR = claBlack;
C_DEFAULT_MENU_BACKGROUND_COLOR = claWhite;
C_DEFAULT_MENU_TOOLBAR_COLOR = claWhite;
type
TksSlideMenu = class;
TksSlideMenuItemList = class;
TksMenuPosition = (mpLeft, mpRight);
TKsMenuStyle = (msOverlap, msReveal);
TKsMenuTheme = (mtCustom, mtDarkGray, mtDarkBlue, mtDarkOrange, mtDarkGreen, mtLightGray, mtLightBlue, mtLightOrange, mtLightGreen);
TBuildMenuEvent = procedure(Sender: TObject; AItems: TksSlideMenuItemList) of object;
TSelectMenuItemEvent = procedure(Sender: TObject; AId: string) of object;
TksSlideMenuAppearence = class(TPersistent)
private
[weak]FSlideMenu: TksSlideMenu;
FBackgroundColor: TAlphaColor;
FHeaderColor: TAlphaColor;
FHeaderFontColor: TAlphaColor;
FItemColor: TAlphaColor;
FFontColor: TAlphaColor;
FSelectedColor: TAlphaColor;
FSelectedFontColor: TAlphaColor;
FTheme: TKsMenuTheme;
FToolBarColor: TAlphaColor;
FAccessoryColor: TAlphaColor;
procedure SetHeaderColor(const Value: TAlphaColor);
procedure SetHeaderFontColor(const Value: TAlphaColor);
procedure SetItemColor(const Value: TAlphaColor);
procedure SetFontColor(const Value: TAlphaColor);
procedure SetSelectedColor(const Value: TAlphaColor);
procedure SetSelectedFontColor(const Value: TAlphaColor);
procedure SetTheme(const Value: TKsMenuTheme);
procedure SetToolBarColor(const Value: TAlphaColor);
procedure SetAccessoryColor(const Value: TAlphaColor);
procedure SetBackgroundColor(const Value: TAlphaColor);
public
constructor Create(ASlideMenu: TksSlideMenu); virtual;
published
property AccessoryColor: TAlphaColor read FAccessoryColor write SetAccessoryColor default claWhite;
property BackgroundColor: TAlphaColor read FBackgroundColor write SetBackgroundColor default $FF222222;
property HeaderColor: TAlphaColor read FHeaderColor write SetHeaderColor default C_DEFAULT_MENU_HEADER_COLOR;
property HeaderFontColor: TAlphaColor read FHeaderFontColor write SetHeaderFontColor default C_DEFAULT_MENU_HEADER_TEXT_COLOR;
property ItemColor: TAlphaColor read FItemColor write SetItemColor default $FF222222;
property FontColor: TAlphaColor read FFontColor write SetFontColor default claWhite;
property SelectedItemColor: TAlphaColor read FSelectedColor write SetSelectedColor default claRed;
property SelectedFontColor: TAlphaColor read FSelectedFontColor write SetSelectedFontColor default claWhite;
property ToolBarColor: TAlphaColor read FToolBarColor write SetToolBarColor default $FF323232;
property Theme: TKsMenuTheme read FTheme write SetTheme default mtDarkGray;
end;
TksSlideMenuItem = class
FID: string;
FText: string;
FBitmap: TBitmap;
FForm: TCommonCustomForm;
FIcon: TksStandardIcon;
FIsHeader: Boolean;
end;
TksSlideMenuItemList = class(TObjectList<TksSlideMenuItem>)
public
procedure AddItem(AID, AText: string; AForm: TCommonCustomForm; const AIcon: TksStandardIcon = Custom; const ABmp: TBitmap = nil);
procedure AddHeader(AText: string);
end;
[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}
)]
TksSlideMenu = class(TComponent)
private
FInitalizedForms: TList<TCommonCustomForm>;
FItems: TksSlideMenuItemList;
FCallingForm: TCommonCustomForm;
FMenuForm: TfrmSlideMenuUI;
FAppearence: TksSlideMenuAppearence;
FOnSelectMenuItemEvent: TSelectMenuItemEvent;
FAfterSelectMenuItemEvent: TSelectMenuItemEvent;
FOnBuildMenu: TBuildMenuEvent;
procedure RebuildMenu;
procedure SelectItem(Sender: TObject; AItem: TksVListItem);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddMenuItem(AID, AText: string; const AForm: TCommonCustomForm = nil; const AIcon: TksStandardIcon = Custom); deprecated 'Use OnBuildMenu event instead';
procedure OpenMenu(ACallingForm: TCommonCustomForm; const APosition: TksMenuPosition = mpLeft);
procedure ShowForm(AID : string);
procedure SelectMenuItem(AID : string);
//procedure CloseMenu;
published
property Appearence: TksSlideMenuAppearence read FAppearence write FAppearence;
property OnSelectMenuItemEvent: TSelectMenuItemEvent read FOnSelectMenuItemEvent write FOnSelectMenuItemEvent;
property AfterSelectItemEvent: TSelectMenuItemEvent read FAfterSelectMenuItemEvent write FAfterSelectMenuItemEvent;
property OnBuildMenu: TBuildMenuEvent read FOnBuildMenu write FOnBuildMenu;
end;
//{$R *.dcr}
procedure Register;
implementation
uses SysUtils, ksCommon, System.TypInfo, ksLoadingIndicator;
procedure Register;
begin
RegisterComponents('Kernow Software FMX', [TksSlideMenu]);
end;
{ TksSlideMenuAppearence }
constructor TksSlideMenuAppearence.Create(ASlideMenu: TksSlideMenu);
begin
inherited Create;
FSlideMenu := ASlideMenu;
FHeaderColor := $FF323232;
FItemColor := $FF222222;
FBackgroundColor := $FF222222;;
FToolBarColor := $FF323232;
FFontColor := claWhite;
FSelectedFontColor := claWhite;
FSelectedColor := claRed;
FAccessoryColor := claWhite;
FTheme := mtDarkGray;
end;
procedure TksSlideMenuAppearence.SetAccessoryColor(const Value: TAlphaColor);
begin
FAccessoryColor := Value;
end;
procedure TksSlideMenuAppearence.SetBackgroundColor(const Value: TAlphaColor);
begin
FBackgroundColor := Value;
end;
procedure TksSlideMenuAppearence.SetFontColor(const Value: TAlphaColor);
begin
FFontColor := Value;
FTheme := mtCustom;
end;
procedure TksSlideMenuAppearence.SetHeaderColor(const Value: TAlphaColor);
begin
FHeaderColor := Value;
FTheme := mtCustom;
end;
procedure TksSlideMenuAppearence.SetHeaderFontColor(const Value: TAlphaColor);
begin
FHeaderFontColor := Value;
FTheme := mtCustom;
end;
procedure TksSlideMenuAppearence.SetItemColor(const Value: TAlphaColor);
begin
FItemColor := Value;
FTheme := mtCustom;
end;
procedure TksSlideMenuAppearence.SetSelectedColor(const Value: TAlphaColor);
begin
FSelectedColor := Value;
FTheme := mtCustom;
end;
procedure TksSlideMenuAppearence.SetSelectedFontColor(const Value: TAlphaColor);
begin
FSelectedFontColor := Value;
FTheme := mtCustom;
end;
procedure TksSlideMenuAppearence.SetTheme(const Value: TKsMenuTheme);
begin
if Value = mtDarkGray then
begin
FHeaderColor := $FF424242;
FToolBarColor := $FF323232;
FItemColor := $FF545454;
FBackgroundColor := FItemColor;
FFontColor := claWhite;
FHeaderFontColor := $FFDADADA;
FSelectedFontColor := claWhite;
FSelectedColor := claRed;
end;
if Value = mtDarkBlue then
begin
FHeaderColor := $FF2A7A9D;
FToolBarColor := $FF323232;
FItemColor := $FF2A7A9D;
FBackgroundColor := FItemColor;
FFontColor := claWhite;
FHeaderFontColor := $FFC7FFFB;
FSelectedFontColor := claWhite;
FSelectedColor := $FF1A5670;
end;
if Value = mtDarkOrange then
begin
FHeaderColor := $FFFF9900;
FToolBarColor := $FF323232;
FItemColor := $FFBC7202;
FBackgroundColor := FItemColor;
FFontColor := claWhite;
FHeaderFontColor := claBlack;
FSelectedFontColor := claWhite;
FSelectedColor := $FFBC7202;
end;
if Value = mtDarkGreen then
begin
FHeaderColor := $FF76D015;
FToolBarColor := $FF323232;
FItemColor := $FF424242;
FBackgroundColor := FItemColor;
FFontColor := claWhite;
FHeaderFontColor := claBlack;
FSelectedFontColor := claBlack;
FSelectedColor := $FFDCFF00;
end;
if Value = mtLightGray then
begin
FHeaderColor := $FF424242;
FToolBarColor := $FF323232;
FItemColor := $FF828282;
FBackgroundColor := FItemColor;
FFontColor := claWhite;
FHeaderFontColor := $FFDADADA;
FSelectedFontColor := claWhite;
FSelectedColor := claRed;
end;
if Value = mtLightBlue then
begin
FHeaderColor := $FF424242;
FToolBarColor := $FF323232;
FItemColor := $FF2A7A9D;
FBackgroundColor := FItemColor;
FFontColor := claWhite;
FHeaderFontColor := $FFDADADA;
FSelectedFontColor := claBlack;
FSelectedColor := $FFC7FFFB;
end;
if Value = mtLightOrange then
begin
FHeaderColor := $FF424242;
FToolBarColor := $FF323232;
FItemColor := $FFFF9900;
FBackgroundColor := FItemColor;
FFontColor := claBlack;
FHeaderFontColor := $FFDADADA;
FSelectedFontColor := claBlack;
FSelectedColor := $FFFFCC00;
end;
if Value = mtLightGreen then
begin
FHeaderColor := $FF424242;
FToolBarColor := $FF323232;
FItemColor := $FF76D015;
FBackgroundColor := FItemColor;
FFontColor := claBlack;
FHeaderFontColor := $FFDADADA;
FSelectedFontColor := claBlack;
FSelectedColor := $FFDCFF00;
end;
FTheme := Value;
end;
procedure TksSlideMenuAppearence.SetToolBarColor(const Value: TAlphaColor);
begin
FToolBarColor := Value;
FTheme := mtCustom;
end;
{ TksSlideMenuExt }
procedure TksSlideMenu.AddMenuItem(AID, AText: string; const AForm: TCommonCustomForm = nil; const AIcon: TksStandardIcon = Custom);
begin
FItems.AddItem(AID, AText, AForm, AIcon);
end;
{
procedure TksSlideMenu.CloseMenu;
begin
FMenuForm.CloseMenu;
FCallingForm.Visible := True;
end; }
constructor TksSlideMenu.Create(AOwner: TComponent);
begin
inherited;
FItems := TksSlideMenuItemList.Create;
FAppearence := TksSlideMenuAppearence.Create(Self);
FInitalizedForms := TList<TCommonCustomForm>.Create;
end;
destructor TksSlideMenu.Destroy;
begin
FMenuForm.DisposeOf;
FreeAndNil(FItems);
FreeAndNil(FAppearence);
FreeAndNil(FInitalizedForms);
inherited;
end;
procedure TksSlideMenu.OpenMenu(ACallingForm: TCommonCustomForm; const APosition: TksMenuPosition = mpLeft);
begin
if FItems.Count = 0 then
begin
if Assigned(FOnBuildMenu) then
FOnBuildMenu(Self, FItems);
end;
FCallingForm := ACallingForm;
HideLoadingIndicator(FCallingForm);
if FMenuForm = nil then
begin
FMenuForm := TfrmSlideMenuUI.Create(nil);
{$IFDEF XE10_2_OR_NEWER}
if ACallingForm.SystemStatusBar <> nil then
FMenuForm.SystemStatusBar.Assign(ACallingForm.SystemStatusBar);
{$ENDIF}
FMenuForm.Caption := ACallingForm.Caption;
FMenuForm.OnSelectItem := SelectItem;
RebuildMenu;
end;
ACallingForm.Visible := False;
FMenuForm.OpenMenu(ACallingForm, APosition = mpLeft);
end;
procedure TksSlideMenu.RebuildMenu;
var
AStream: TResourceStream;
AEnumName: String;
ICount: integer;
lv: TksVirtualListView;
AItem: TksVListItem;
ABmp: TBitmap;
begin
lv := FMenuForm.lvMenu;
lv.Appearence.SelectedColor := FAppearence.SelectedItemColor;
lv.Appearence.SelectedFontColor := FAppearence.SelectedFontColor;
lv.Appearence.ItemBackground := FAppearence.ItemColor;
lv.Appearence.Background := FAppearence.BackgroundColor;
lv.ClearItems;
for ICount := 0 to FItems.Count-1 do
begin
if FItems[ICount].FIsHeader then
begin
AItem := lv.Items.AddHeader(FItems[ICount].FText);
AItem.Background := $FF484848;//claDimgray;// lv.Appearence.HeaderColor;
AItem.Title.TextSettings.FontColor := claWhite;// lv.Appearence.HeaderFontColor;
end
else
begin
AItem := lv.Items.Add(FItems[ICount].FText, '', '', atMore);
AItem.TagInt := ICount;
AItem.TagStr := FItems[ICount].FID;
AItem.Title.TextSettings.FontColor := FAppearence.FontColor;
AItem.Accessory.Color := FAppearence.AccessoryColor;
if lv.ItemIndex = -1 then
AItem.Selected := True;
aBmp := TBitmap.Create;
try
if FItems[ICount].FBitmap <> nil then
begin
ABmp := FItems[ICount].FBitmap;
ReplaceOpaqueColor(ABmp, claWhite);
AItem.Image.Bitmap := ABmp;
AItem.Image.Width := 20;
AItem.Image.Height := 20;
end
else
begin
AEnumName := GetENumName(TypeInfo(TksStandardIcon), Ord(FItems[ICount].FIcon));
if FItems[ICount].FIcon <> Custom then
begin
AStream := TResourceStream.Create(HInstance, AEnumName, RT_RCDATA);
aBmp.LoadFromStream(AStream);
ReplaceOpaqueColor(ABmp, claWhite);
AItem.Image.Bitmap := ABmp;
AItem.Image.Width := 20;
AItem.Image.Height := 20;
AStream.Free;
end;
end;
finally
ABmp.Free;
end;
end;
end;
end;
procedure TksSlideMenu.SelectItem(Sender: TObject; AItem: TksVListItem);
var
mi: TksSlideMenuItem;
AForm: TCommonCustomForm;
ABmp: TBitmap;
begin
AForm := nil;
mi := nil;
if AItem <> nil then
begin
mi := FItems[AItem.TagInt];
if Assigned(FOnSelectMenuItemEvent) then
FOnSelectMenuItemEvent(Self, mi.FID);
AForm := mi.FForm;
end;
if (AForm = nil) or (AForm = FCallingForm) then
begin
AForm := FCallingForm;
FMenuForm.CloseMenu;
AForm.Visible := True;
Exit;
end;
if FCallingForm <> nil then
begin
if FInitalizedForms.IndexOf(FCallingForm) = -1 then
FInitalizedForms.Add(FCallingForm);
end;
{$IFDEF ANDROID}
// fix for Android initial form size
if FInitalizedForms.IndexOf(AForm) = -1 then
begin
//AForm.Visible := True;
//AForm.Visible := False;
FInitalizedForms.Add(AForm);
end;
{$ENDIF}
//AForm.SetBounds(0, 0, FCallingForm.Width, FCallingForm.Height);
{$IFDEF XE10_OR_NEWER}
AForm.SetBounds(FMenuForm.Bounds);
{$ELSE}
AForm.SetBounds(FMenuForm.Left, FMenuForm.Top, FMenuForm.Width, FMenuForm.Height);
{$ENDIF}
ABmp := TBitmap.Create;
try
GenerateFormImageExt(AForm, ABmp);
FMenuForm.Bitmap.Assign(ABmp);
finally
FreeAndNil(ABmp);
end;
//FMenuForm.Image1.Bitmap := GenerateFormImageExt(AForm);
FMenuForm.CloseMenu;
AForm.Visible := True;
AForm.BringToFront;
//Screen.ActiveForm := AForm;
if FCallingForm <> AForm then
FCallingForm.Visible := False;
{TThread.Synchronize (TThread.CurrentThread,
procedure ()
begin
AForm.Visible := True;
AForm.BringToFront;
Screen.ActiveForm := AForm;
if FCallingForm <> AForm then
FCallingForm.Visible := False;
end);}
if mi <> nil then
begin
if Assigned(FAfterSelectMenuItemEvent) then
FAfterSelectMenuItemEvent(Self, mi.FID);
end;
end;
procedure TksSlideMenu.ShowForm(AID : string);
var
listItem: TksVListItem;
begin
if AID = '' then
Exit;
for listItem in FMenuForm.lvMenu.Items do
begin
if (listItem.TagStr = AID) then
begin
FMenuForm.lvMenu.DeselectAll();
listItem.Selected := True;
SelectItem(nil, listItem);
Exit;
end;
end;
end;
procedure TksSlideMenu.SelectMenuItem(AID : string);
var
listItem: TksVListItem;
begin
if AID = '' then
Exit;
for listItem in FMenuForm.lvMenu.Items do
begin
if (listItem.TagStr = AID) then
begin
FMenuForm.lvMenu.DeselectAll();
listItem.Selected := True;
Exit;
end;
end;
end;
{TksSlideMenuItemExtList }
procedure TksSlideMenuItemList.AddHeader(AText: string);
var
AItem: TksSlideMenuItem;
begin
AItem := TksSlideMenuItem.Create;
AItem.FText := AText;
AItem.FIsHeader := True;
Add(AItem);
end;
procedure TksSlideMenuItemList.AddItem(AID, AText: string;
AForm: TCommonCustomForm; const AIcon: TksStandardIcon = Custom; const ABmp: TBitmap = nil);
var
AItem: TksSlideMenuItem;
begin
AItem := TksSlideMenuItem.Create;
AItem.FID := AID;
AItem.FText := AText;
AItem.FForm := AForm;
AItem.FIcon := AIcon;
AItem.FBitmap := ABmp;
AItem.FIsHeader := False;
Add(AItem);
end;
initialization
// frmSlideMenuUI := TfrmSlideMenuUI.Create(nil);
finalization
// frmSlideMenuUI.DisposeOf;
end.
|
unit Roles;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BaseGridDetail, Data.DB, RzButton,
Vcl.StdCtrls, Vcl.Mask, RzEdit, Vcl.Grids, Vcl.DBGrids, RzDBGrid, RzLabel,
Vcl.ExtCtrls, RzPanel, Vcl.DBCtrls, RzDBEdit, Role, AssignRights;
type
TfrmRoles = class(TfrmBaseGridDetail)
Label2: TLabel;
edCode: TRzDBEdit;
Label3: TLabel;
edName: TRzDBEdit;
Label4: TLabel;
mmDescription: TRzDBMemo;
urlRoles: TRzURLLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure urlRolesClick(Sender: TObject);
procedure grListDblClick(Sender: TObject);
private
{ Private declarations }
Role: TRole;
procedure ShowAssignedRights;
procedure SaveRights;
protected
procedure SearchList; override;
procedure BindToObject; override;
function EntryIsValid: boolean; override;
function NewIsAllowed: boolean; override;
function EditIsAllowed: boolean; override;
public
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
SecurityData, IFinanceDialogs, IFinanceGlobal, User, Right, DBUtil;
{ TfrmRoles }
procedure TfrmRoles.BindToObject;
begin
Role.Code := edCode.Text;
Role.Name := edName.Text;
Role.Description := mmDescription.Text;
end;
function TfrmRoles.EditIsAllowed: boolean;
begin
Result := ifn.User.HasRights([PRIV_SEC_ROLE_MODIFY],false);
end;
function TfrmRoles.EntryIsValid: boolean;
var
error: string;
begin
if not Role.HasCode then error := 'Please enter role code.'
else if not Role.HasName then error := 'Please enter role name.';
Result := error = '';
if not Result then ShowErrorBox(error);
end;
procedure TfrmRoles.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Role.Free;
end;
procedure TfrmRoles.FormCreate(Sender: TObject);
begin
Role := TRole.Create;
inherited;
end;
procedure TfrmRoles.grListDblClick(Sender: TObject);
begin
inherited;
ShowAssignedRights;
end;
function TfrmRoles.NewIsAllowed: boolean;
begin
Result := ifn.User.HasRights([PRIV_SEC_ROLE_ADD_NEW],true);
end;
procedure TfrmRoles.SaveRights;
var
right: TRight;
sql: string;
i, cnt: integer;
begin
// Note: Do not turn on the "sort" property of the rights ListBox
// Save function does not work property
try
try
cnt := Role.RightsCount - 1;
for i := 0 to cnt do
begin
right := Role.Rights[i];
if right.Modified then
begin
if right.AssignedNewValue then
sql := 'INSERT INTO SYSROLEPRIVILEGE VALUES (' + QuotedStr(Role.Code) +
',' + QuotedStr(right.Code) + ');'
else
sql := 'DELETE FROM SYSROLEPRIVILEGE WHERE ROLE_CODE = ' + QuotedStr(Role.Code) +
' AND PRIVILEGE_CODE = ' + QuotedStr(right.Code) + ';';
// execute the sql
ExecuteSQL(sql,true);
end;
end; // end for
except
on E: Exception do ShowErrorBox(E.Message);
end;
finally
end;
end;
procedure TfrmRoles.SearchList;
var
filterStr: string;
begin
filterStr := 'ROLE_NAME LIKE ' + QuotedStr('%' + UpperCase(edSearchKey.Text) + '%');
grList.DataSource.DataSet.Filter := filterStr;
end;
procedure TfrmRoles.ShowAssignedRights;
begin
BindToObject;
with TfrmAssignRights.Create(self.Parent,Role) do
begin
try
ShowModal;
if ModalResult = mrOk then SaveRights;
finally
Free;
end;
end;
end;
procedure TfrmRoles.urlRolesClick(Sender: TObject);
begin
ShowAssignedRights;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, XPMan;
type
TForm1 = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Valor1: TEdit;
Valor2: TEdit;
Calcular: TButton;
Label4: TLabel;
Resultado: TLabel;
GroupBox1: TGroupBox;
Somar: TRadioButton;
Subtrair: TRadioButton;
Multiplicar: TRadioButton;
Dividir: TRadioButton;
XPManifest1: TXPManifest;
procedure CalcularClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.CalcularClick(Sender: TObject);
Var
A,B,Resultado1:Real;
Formato:String;
begin
A:=StrToFloat(Valor1.Text);
B:=StrToFloat(Valor2.Text);
Resultado1:= 0;
IF (Somar.Checked) then
Resultado1:= A+B;
IF (Subtrair.Checked) then
Resultado1:= A-B;
IF (Multiplicar.Checked) then
Resultado1:= A*B;
IF (Dividir.Checked) then
IF (B=0) then
ShowMessage('Nao Existe divisao por zero')
Else
Resultado1:= A/B;
Formato:=FormatFloat('0.00;(0.00);Zerado',Resultado1);
Resultado.Caption:=Formato;
Valor1.SetFocus
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2014 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Bde.Bdeconst;
interface
resourcestring
SAutoSessionExclusive = 'フォームまたはデータ モジュールに複数のセッションが存在する場合は AutoSessionName プロパティを有効にはできません';
SAutoSessionExists = 'セッション '#39'%s'#39' の AutoSessionName が有効な間はフォームまたはデータ モジュールに別のセッションを追加できません';
SAutoSessionActive = 'AutoSessionName が有効な間は SessionName を変更できません';
SDuplicateDatabaseName = 'データベース名 '#39'%s'#39' が衝突しています';
SDuplicateSessionName = 'セッション名 '#39'%s'#39' が衝突しています';
SInvalidSessionName = 'セッション名 %s が不正です';
SDatabaseNameMissing = 'データベース名がありません';
SSessionNameMissing = 'セッション名がありません';
SDatabaseOpen = 'データベースが開かれているため, この操作は実行できません';
SDatabaseClosed = 'データベースは閉じているため, この操作は実行できません';
SDatabaseHandleSet = 'データベースハンドルは別のセッションに所有されています';
SSessionActive = 'アクティブなセッションに対しては, この操作は実行できません';
SHandleError = 'カーソルハンドルの作成でエラーが発生しました';
SInvalidFloatField = 'フィールド '#39'%s'#39' を浮動小数点値に変換できません';
SInvalidIntegerField = 'フィールド '#39'%s'#39' を整数値に変換できません';
STableMismatch = '転送元と転送先のテーブルが一致していません';
SFieldAssignError = 'フィールド '#39'%s'#39' とフィールド '#39'%s'#39' の間には代入互換性がありません';
SNoReferenceTableName = 'フィールド '#39'%s'#39' の ReferenceTableName が指定されていません';
SCompositeIndexError = '式インデックスではフィールド値の配列を使用できません';
SInvalidBatchMove = 'バッチ移動のパラメータが無効です';
SEmptySQLStatement = 'SQL 文は利用できません';
SNoParameterValue = 'パラメータ '#39'%s'#39' に値がありません';
SNoParameterType = 'パラメータ '#39'%s'#39' にパラメータ型がありません';
SLoginError = 'データベース '#39'%s'#39' に接続できません';
SInitError = 'Borland Database Engine の初期化中にエラーが発生しました (エラー $%.4x)';
SDatabaseEditor = 'データベースの編集(&T)...';
SExplore = 'エクスプローラ(&X)';
SLinkDetail = #39'%s'#39' を開くことができません.';
SLinkMasterSource = #39'%s'#39' の MasterSource プロパティがデータソースを指している必要があります';
SLinkMaster = 'MasterSource プロパティで定義されたテーブルを開けません';
SGQEVerb = 'SQL ビルダ(&Q)...';
SBindVerb = 'パラメータの定義(&P)...';
SIDAPILangID = '0011';
SDisconnectDatabase = 'データベースは現在接続されています。接続を切断して続行しますか?';
SBDEError = 'BDEエラー $%.4x';
SLookupSourceError = 'DataSource と LookupSource が重複してはいけません';
SLookupTableError = 'LookupSource は TTable コンポーネントに接続していなければなりません';
SLookupIndexError = '%s は参照テーブルのアクティブインデックスでなければなりません';
SParameterTypes = ';入力;出力;入力/出力;結果';
SInvalidParamFieldType = '有効なフィールド型を選択する必要があります';
STruncationError = 'パラメータ '#39'%s'#39' は出力時に丸められました';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = '結果';
SDBCaption = '%s%s%s データベース';
SParamEditor = '%s%s%s パラメータ';
SIndexFilesEditor = '%s%s%s のインデックスファイル';
SNoIndexFiles = '(なし)';
SIndexDoesNotExist = 'インデックスがありません。インデックス: %s';
SNoTableName = 'TableName プロパティがありません';
SNoDataSetField = 'DataSetField プロパティがありません';
SBatchExecute = '実行(&X)';
SNoCachedUpdates = 'キャッシュされた更新モードではありません';
SInvalidAliasName = '無効なエイリアス名 %s';
SNoFieldAccess = 'フィルタ内でフィールド '#39'%s'#39' にアクセスできません';
SUpdateSQLEditor = 'UpdateSQL の設定(&U)...';
SNoDataSet = 'データセットが指定されていません';
SUntitled = '名称未設定アプリケーション';
SUpdateWrongDB = 'アップデートできません。%1:s は %0:s を所有していません';
SUpdateFailed = 'アップデート失敗';
SSQLGenSelect = '少なくとも 1 つのキー フィールドと更新フィールドを選択する必要があります';
SSQLNotGenerated = 'SQL 文が生成されていません。閉じてよいですか?';
SSQLDataSetOpen = '%s のフィールド名を判別できません';
SLocalTransDirty = 'ローカルデータベースに対してはトランザクション排他レベルを Dirty 読み取り (tiDirtyRead) にする必要があります';
SMissingDataSet = 'DataSet プロパティがありません';
SNoProvider = '有効なプロバイダがありません';
SNotAQuery = 'データセットはクエリーではありません';
implementation
end.
|
unit USort;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, DBCtrls, TeEngine, Series, TeeProcs, Chart,
ComCtrls;
const
N = 10;
SlpDur = 1000; //задержка
tab = ' '; //отступ
type
TIndex = 1..N; //индекс
TElem = Integer; //лемент
TMas = array[TIndex] of TElem; //массив
procedure RandomFill(var mas: TMas); // рандомное заполнение массива
function ToString(mas: TMas): string; //возвращат массива в виде строки
procedure BubleSort(var mas: TMas; var lb: TListBox); //сортировка шелла с выводом процесса на listbox
implementation
//заполнение массива случайными числами (в диапазоне 1-99)
procedure RandomFill(var mas: TMas);
var
i: Integer;
begin
Randomize;
for i:= 1 to N do
mas[i]:= 1 + Random(99);
end;
//возвращат массив в виде строки
function ToString(mas: TMas): string;
var
i: Integer;
begin
Result:= '';
for i:= 1 to N do
Result:= Result + IntToStr(mas[i]) + ' ';
end;
//сдвигает i-ю строку в lb на отступ tab
procedure Move(var lb: TListBox; i: Integer);
var
s: string;
begin
s:= tab + Trim(lb.Items[i-1]);
lb.Items[i-1]:= s;
end;
//удаляет отступ i-й строки в lb
procedure MoveBack(var lb: TListBox; i: Integer);
var
s: string;
begin
s:= Trim(lb.Items[i-1]);
lb.Items[i-1]:= s;
end;
//меняет местами i-ю и j-ю строки в lb
procedure Swap(var lb: TListBox; i,j: Integer);
var
s: string;
begin
s:= lb.Items[i-1];
lb.Items[i-1]:= lb.Items[j-1];
lb.Items[j-1]:= s;
end;
procedure BubleSort(var mas: TMas; var lb: TListBox);
var
i, tmp: integer;
firstIndex, lastIndex: integer;
k: integer; //индекс последней перестановки
begin
firstIndex:= 1; //индекс первого элемента рабочей зоны
lastIndex:= N; //индекс последнего элемента рабочей зоны
k:= N-1;
repeat
//действия с listbox
Move(lb,firstIndex);
Application.ProcessMessages;
//проход слева направо (сверху вниз)
for i:= firstIndex to lastIndex-1 do
begin
//действия с listbox
Move(lb,i+1);
Application.ProcessMessages; //чтобы на listbox применились изменения
sleep(SlpDur);
if mas[i] > mas[i+1] then
begin
//обмен элементов
tmp:= mas[i];
mas[i]:= mas[i+1];
mas[i+1]:= tmp;
//действия с listbox
Swap(lb,i,i+1);
Application.ProcessMessages;
sleep(SlpDur);
end;
//действия с listbox
MoveBack(lb,i);
Application.ProcessMessages;
end;
//действия с listbox
MoveBack(lb,lastIndex);
Application.ProcessMessages;
sleep(SlpDur);
lastIndex:= k; //уменьшаем просматриваемую область
Dec(k);
until k<0;
end;
end.
|
unit uFromHik86;
interface
uses
Classes, SysUtils, Generics.Collections, Variants, IniFiles, DateUtils, IdHttp,
FireDAC.Comp.Client, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Pool,
FireDAC.Stan.Def, FireDAC.DApt, FireDAC.Stan.Async, FireDAC.Stan.Expr, IdUri,
uTypes, uBaseThread, IOUtils, uGlobal, uQTZHelper, Types;
type
TFromHik86 = class(TBaseThread)
private
FConfig: TConfig;
FConn: TFDConnection;
FQuery: TFDQuery;
function GetConn: TFDConnection;
function QueryPassFromOracle: boolean;
function GetMaxXH: string;
procedure SetMaxXH(const Value: string);
function SendData(stream: TStream): boolean;
function GetPassList: TList<TPass>;
function GetStream(list: TList<TPass>): TStringStream;
procedure GetAlarm(list: TList<TPass>);
protected
procedure Prepare; override;
procedure Perform; override;
procedure AfterTerminate; override;
public
constructor Create(config: TConfig); overload;
destructor Destroy; override;
end;
implementation
{ TFromHik86 }
procedure TFromHik86.AfterTerminate;
begin
inherited;
logger.Info(FConfig.Name + ' Stoped');
end;
procedure TFromHik86.Prepare;
begin
inherited;
logger.Info(FConfig.Name + ' Start');
end;
constructor TFromHik86.Create(config: TConfig);
begin
FConfig := config;
FConn := GetConn;
inherited Create(false);
self.FSleep := 1000;
if FConfig.IsVio then
self.FSleep := 60000;
end;
destructor TFromHik86.Destroy;
begin
FQuery.Free;
FConn.Free;
inherited;
end;
procedure TFromHik86.Perform;
var
stream: TStream;
list: TList<TPass>;
begin
inherited;
if QueryPassFromOracle then
begin
logger.Info('RecordCount: ' + FQuery.RecordCount.ToString());
if FQuery.RecordCount > 0 then
begin
list := GetPassList;
stream := GetStream(list);
SendData(stream);
stream.Free;
if FConfig.AlarmUrl <> '' then
begin
GetAlarm(list);
end;
list.Free;
end;
end;
end;
function TFromHik86.GetConn: TFDConnection;
begin
result := TFDConnection.Create(nil);
result.Params.Add('DriverID=Ora');
result.Params.Add
(Format('Database=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = %s)(PORT = %s)))'
+ '(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = %s)))',
[FConfig.Host, FConfig.Port, FConfig.SID]));
result.Params.Add(Format('User_Name=%s', [FConfig.Usr]));
result.Params.Add(Format('Password=%s', [FConfig.Pwd]));
result.Params.Add('CharacterSet=UTF8'); // ·ñÔòÖÐÎÄÂÒÂë
result.LoginPrompt := false;
result.FetchOptions.Mode := FireDAC.Stan.Option.fmAll;
FQuery := TFDQuery.Create(nil);
FQuery.Connection := result;
FQuery.SQL.Add('SELECT * FROM (');
if FConfig.IsVio then
begin
FQuery.SQL.Add(' SELECT CLXXBH,KKBH,JGSK,CDBH,HPHM,HPZL,HPYS,CSYS,CLSD,QJTP,QJTP1,QJTP2,WFXW ');
FQuery.SQL.Add(' FROM V_WFXX ');
FQuery.SQL.Add(' WHERE CLXXBH>:MaxXH and JGSK>SYSDATE-15 ');
end
else begin
FQuery.SQL.Add(' SELECT CLXXBH,KKBH,JGSK,CDBH,HPHM,HPZL,HPYS,CSYS,CLSD,QJTP,QJTP1,QJTP2,''0'' as WFXW ');
FQuery.SQL.Add(' FROM V_GCXX ');
FQuery.SQL.Add(' WHERE CLXXBH>:MaxXH and JGSK>SYSDATE-0.1 ');
end;
FQuery.SQL.Add(' ORDER BY CLXXBH ) ');
FQuery.SQL.Add(' WHERE ROWNUM<=2000 ');
FQuery.SQL.Add(' ORDER BY CLXXBH DESC');
end;
function TFromHik86.GetMaxXH: string;
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
result := ini.ReadString(FConfig.Name, 'MaxXH', '0');
ini.Free;
end;
procedure TFromHik86.SetMaxXH(const Value: string);
var
ini: TIniFile;
begin
ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'config.ini');
ini.WriteString(FConfig.Name, 'MaxXH', Value);
ini.Free;
end;
function TFromHik86.QueryPassFromOracle: boolean;
begin
result := True;
FQuery.Close;
FQuery.Params.ParamByName('MaxXH').Value := GetMaxXH;
try
FConn.Open;
FQuery.Open;
except
on e: exception do
begin
result := false;
logger.Error('QueryPassFromOracle: ' + e.Message + #13 + FQuery.SQL.Text);
end;
end;
if FQuery.RecordCount > 0 then
begin
SetMaxXH(FQuery.FieldByName('CLXXBH').AsString);
end;
end;
function TFromHik86.GetPassList: TList<TPass>;
var
pass: TPass;
begin
result := TList<TPass>.Create;
try
with FQuery do
begin
while not Eof do
begin
pass.GCXH := FieldByName('CLXXBH').AsString;
pass.KDBH := FieldByName('KKBH').AsString;
pass.GCSJ := FieldByName('JGSK').AsString;
pass.CDBH := FieldByName('CDBH').AsString;
pass.HPHM := FieldByName('HPHM').AsString;
pass.HPZL := FieldByName('HPZL').AsString;
pass.HPYS := FieldByName('HPYS').AsString;
pass.CSYS := FieldByName('CSYS').AsString;
pass.CLSD := FieldByName('CLSD').AsString;
pass.TP1 := FieldByName('QJTP').AsString;
pass.TP2 := FieldByName('QJTP1').AsString;
pass.TP3 := FieldByName('QJTP2').AsString;
pass.WFXW := FieldByName('WFXW').AsString;
result.Add(pass);
Next;
end;
Close;
end;
except
on e: exception do
begin
logger.Error('TFromHik86.GetPassList' + e.Message);
end;
end;
end;
function TFromHik86.GetStream(list: TList<TPass>): TStringStream;
var
pass: TPass;
begin
result := TStringStream.Create;
for pass in list do
begin
result.WriteString(pass.GCXH);
result.WriteString(#9 + pass.kdbh);
result.WriteString(#9 + pass.gcsj);
result.WriteString(#9 + pass.cdbh);
result.WriteString(#9 + pass.HPHM);
result.WriteString(#9 + pass.HPZL);
result.WriteString(#9 + pass.hpys);
result.WriteString(#9 + pass.CSYS);
result.WriteString(#9 + pass.clsd);
result.WriteString(#9 + pass.tp1);
result.WriteString(#9 + pass.tp2);
result.WriteString(#9 + pass.tp3);
result.WriteString(#9 + pass.WFXW);
result.WriteString(#13#10);
end;
end;
function TFromHik86.SendData(stream: TStream): boolean;
var
http: TIdHttp;
begin
result := true;
http := TIdHttp.Create(nil);
try
stream.Position := 0;
http.Post(FConfig.BdrUrl, stream);
except
on e: exception do
begin
logger.Error('[TFromHik86.SendData]' + e.Message + FConfig.BdrUrl);
result := false;
end;
end;
http.Free;
end;
procedure TFromHik86.GetAlarm(list: TList<TPass>);
function IsValid(HPHM, HPZL: string): boolean;
var
s: string;
begin
s := '';//TQTZHelper.GetVehInfo(HPHM, HPZL);
result := not s.Contains('"ZT":"A"');
end;
function IsYunJing(kdbh: string): boolean;
begin
result := IMEIDic.ContainsKey(kdbh);
end;
procedure HttpPost(alarmList: TList<TPass>);
var
data: TStringList;
http: TIdHttp;
pass: TPass;
first: boolean;
s: string;
begin
http := TIdHttp.Create(nil);
data := TStringList.Create;
first := true;
s := FConfig.ALarmUrl + '?data=[';
for pass in alarmList do
begin
if not first then
s := s + ',';
s := s + '{"jybh":"' + pass.kdbh
+ '","hphm":"' + pass.hphm
+ '","hpzl":"' + pass.hpzl
+ '","csys":"' + pass.csys
+ '","yjlx":"' + pass.WFXW + '"}';
first := false;
end;
s := s + ']';
s := IdUri.TIdURI.URLEncode(s);
try
s := http.Post(s, data);
logger.Info('[TFromHik86.GetAlarm.HttpPost]' + s);
except
on e: exception do
begin
logger.Error('[TFromHik86.GetAlarm.HttpPost]' + e.Message);
end;
end;
data.Free;
http.Free;
end;
function GetIMEI(kdbh: string): string;
begin
result := IMEIDic[kdbh];
end;
var
pass, p: TPass;
alarmList: TList<TPass>;
alarm: TAlarm;
begin
alarmList := TList<TPass>.Create;
for pass in list do
begin
if IsYunJing(pass.kdbh) and AlarmDic.ContainsKey(pass.HPHM) then
begin
alarm := AlarmDic[pass.HPHM];
if alarm.ZT and IsValid(pass.HPHM, pass.HPZL) then
begin
p := pass;
p.WFXW := alarm.BKLX;
p.kdbh := GetIMEI(p.kdbh);
alarmList.Add(p);
logger.Info('[TFromHik86.GetAlarm]:' + p.HPHM);
end
else if alarm.ZT then
begin
alarm.ZT := false;
AlarmDic[pass.HPHM] := alarm;
end;
end;
end;
if alarmList.Count > 0 then
begin
HttpPost(alarmList);
end;
alarmList.Free;
end;
end.
|
unit uDisAssemblerForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uResourceStrings, uView, uDisAssembler, uProcessor, StdCtrls,
ExtCtrls, Menus, EnhCtrls, uMisc, Registry;
type
TProgramCounterUpdateRequestEvent = procedure(Address: Word) of object;
TDisAssemblerForm = class(TForm, ILanguage, IRadixView, IProgramCounter, IProcessor, IRAM, IRegistry)
pDisAssemble: TPanel;
pCode0: TPanel;
pCode1: TPanel;
pCode2: TPanel;
pCode3: TPanel;
pCode4: TPanel;
pCode5: TPanel;
LblSourcecode: TLabel;
Label1: TLabel;
iArrow: TImage;
bDivider: TBevel;
Label2: TLabel;
PopupMenu: TPopupMenu;
miClose: TMenuItem;
N1: TMenuItem;
miStayOnTop: TMenuItem;
eePC: TEnhancedEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure miCloseClick(Sender: TObject);
procedure miStayOnTopClick(Sender: TObject);
procedure ePCKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ePCClick(Sender: TObject);
private
_pCodes: array [0..6] of TPanel;
_DisAssembler: Ti8008DisAssembler;
_SourceCode: TStringList;
_Radix: TRadix;
_View: TView;
_ProgramCounterUpdateRequest: TProgramCounterUpdateRequestEvent;
procedure ShowSourceCode;
procedure RefreshObject(Sender: TObject);
procedure Reset(Sender: TObject);
procedure PCUpdate(Sender: TObject; Value: Word);
procedure BeforeCycle(Sender: TObject);
procedure AfterCycle(Sender: TObject);
procedure StateChange(Sender: TObject; Halt: Boolean);
procedure RAMUpdate(Sender: TObject; Address: Word; Value: Byte);
procedure LoadData(RegistryList: TRegistryList);
procedure SaveData(RegistryList: TRegistryList);
procedure setProcessor(Value: Ti8008Processor);
function getProcessor: Ti8008Processor;
public
procedure LoadLanguage;
procedure RadixChange(Radix: TRadix; View: TView);
property Processor: Ti8008Processor read getProcessor write setProcessor;
property OnProgramCounterUpdateRequest: TProgramCounterUpdateRequestEvent read _ProgramCounterUpdateRequest write _ProgramCounterUpdateRequest;
end;
var
DisAssemblerForm: TDisAssemblerForm;
implementation
uses uEditForm;
{$R *.dfm}
procedure TDisAssemblerForm.FormCreate(Sender: TObject);
begin
_Radix:= rOctal;
_View:= vShort;
_DisAssembler:= Ti8008DisAssembler.Create;
_SourceCode:= TStringList.Create;
_pCodes[0]:= pCode0;
_pCodes[1]:= pCode1;
_pCodes[2]:= pCode2;
_pCodes[3]:= pCode3;
_pCodes[4]:= pCode4;
_pCodes[5]:= pCode5;
AutoSize:= true;
LoadLanguage;
end;
procedure TDisAssemblerForm.FormDestroy(Sender: TObject);
begin
_SourceCode.Free;
_DisAssembler.Free;
end;
procedure TDisAssemblerForm.ePCClick(Sender: TObject);
var
C: Boolean;
P: TPoint;
begin
if (Sender is TEnhancedEdit) then
begin
P.X:= Mouse.CursorPos.X;
P.Y:= Mouse.CursorPos.Y;
EditForm.Value:= RadixToWord((Sender as TEnhancedEdit).Text,_Radix,_View,C);
if (EditForm.ShowModal(_Radix,_View,14,P) = mrOk) and Assigned(OnProgramCounterUpdateRequest) then
OnProgramCounterUpdateRequest(EditForm.Value);
end;
end;
procedure TDisAssemblerForm.ePCKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
ePCClick(Sender);
end;
procedure TDisAssemblerForm.miCloseClick(Sender: TObject);
begin
Close;
end;
procedure TDisAssemblerForm.miStayOnTopClick(Sender: TObject);
begin
if miStayOnTop.Checked then
FormStyle:= fsNormal
else
FormStyle:= fsStayOnTop;
miStayOnTop.Checked:= not miStayOnTop.Checked;
end;
procedure TDisAssemblerForm.ShowSourceCode;
var
i: Byte;
begin
_DisAssembler.Disassemble(_SourceCode);
for i:= 0 to High(_pCodes)-1 do
_pCodes[i].Caption:= _SourceCode.Strings[i];
end;
procedure TDisAssemblerForm.RefreshObject(Sender: TObject);
begin
if Sender is Ti8008Stack then
eePC.Text:= WordToRadix((Sender as Ti8008Stack).ProgramCounter,_Radix,_View,14);
ShowSourceCode;
end;
procedure TDisAssemblerForm.Reset(Sender: TObject);
begin
if Sender is Ti8008Stack then
eePC.Text:= WordToRadix((Sender as Ti8008Stack).ProgramCounter,_Radix,_View,14);
ShowSourceCode;
end;
procedure TDisAssemblerForm.PCUpdate(Sender: TObject; Value: Word);
begin
if Sender is Ti8008Stack then
eePC.Text:= WordToRadix((Sender as Ti8008Stack).ProgramCounter,_Radix,_View,14);
ShowSourceCode;
end;
procedure TDisAssemblerForm.BeforeCycle(Sender: TObject);
begin
ShowSourceCode;
end;
procedure TDisAssemblerForm.AfterCycle(Sender: TObject);
begin
end;
procedure TDisAssemblerForm.StateChange(Sender: TObject; Halt: Boolean);
begin
end;
procedure TDisAssemblerForm.RAMUpdate(Sender: TObject; Address: Word; Value: Byte);
begin
ShowSourceCode;
end;
procedure TDisAssemblerForm.LoadData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,false) then
RegistryList.LoadFormSettings(Self,false);
end;
procedure TDisAssemblerForm.SaveData(RegistryList: TRegistryList);
begin
if RegistryList.Registry.OpenKey(APPLICATION_MAIN_KEY,true) then
RegistryList.SaveFormSettings(Self,false);
end;
procedure TDisAssemblerForm.setProcessor(Value: Ti8008Processor);
begin
_DisAssembler.Processor:= Value;
end;
function TDisAssemblerForm.getProcessor: Ti8008Processor;
begin
result:= _DisAssembler.Processor;
end;
procedure TDisAssemblerForm.LoadLanguage;
begin
LblSourcecode.Caption:= getString(rsSourcecode);
end;
procedure TDisAssemblerForm.RadixChange(Radix: TRadix; View: TView);
begin
if Radix = rDecimalNeg then Radix:= rDecimal;
_Radix:= Radix;
_View:= View;
_DisAssembler.Radix:= Radix;
_DisAssembler.View:= View;
end;
end.
|
{
unit UAboutFrm
ES: formulario Acerca de
EN: form About
=========================================================================
History:
ver 0.1:
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2011, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
unit UAboutFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, jpeg;
type
TAboutFrm = class(TForm)
Image1: TImage;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lVersion: TLabel;
Label5: TLabel;
lMail: TLabel;
lWeb: TLabel;
Image2: TImage;
Label6: TLabel;
lWeb2: TLabel;
Label7: TLabel;
lBugs: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
procedure lMailClick(Sender: TObject);
procedure lWebClick(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure Image2Click(Sender: TObject);
private
public
constructor Create(aOwner: TComponent); override;
end;
var
AboutFrm: TAboutFrm;
implementation
uses
GMConstants, ShellAPI;
{$R *.dfm}
{ TAboutFrm }
constructor TAboutFrm.Create(aOwner: TComponent);
begin
inherited;
lVersion.Caption := GMLIB_VerText;
end;
procedure TAboutFrm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then Close;
end;
procedure TAboutFrm.Image2Click(Sender: TObject);
begin
ShellExecute(Handle,'open', PChar('http://www.gnu.org/licenses/lgpl.html'), nil, nil, SW_SHOWNORMAL) ;
end;
procedure TAboutFrm.lWebClick(Sender: TObject);
begin
if not (Sender is TLabel) then Exit;
ShellExecute(Handle, 'open', PChar(TLabel(Sender).Caption), nil, nil, SW_SHOW);
end;
procedure TAboutFrm.lMailClick(Sender: TObject);
var
Subject,
Body,
Mail: string;
begin
Subject := '(GMLib)-';
Body := '';
Mail := 'mailto:' + (lMail.Hint) + '?subject=' + Subject + '&body=' + Body ;
ShellExecute(Handle,'open', PChar(Mail), nil, nil, SW_SHOWNORMAL) ;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Xml.XMLIniFile;
interface
uses System.IniFiles, Xml.XmlIntf, System.Classes;
type
TXmlIniFile = class(TCustomIniFile)
strict private
FNode: IXmlNode;
function FindXmlNode(const NodeName: string): IXmlNode;
function FindXmlNodeOrAdd(const NodeName: string): IXmlNode;
procedure DeleteChildNode(AParentNode: IXmlNode; AIndex: Integer);
function ReadXmlString(const Section, Name, Default: string): string;
procedure WriteXmlString(const Section, Name, Value: string);
procedure GetSectionValues(const Section: string; Strings: TStrings);
public
constructor Create(const ANode: IXmlNode);
function ReadString(const Section, Ident, Default: string): string; override;
procedure WriteString(const Section, Ident, Value: string); override;
function ReadInteger(const Section, Ident: string; Default: Longint): Longint; override;
procedure WriteInteger(const Section, Ident: string; Value: Longint); override;
function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; override;
procedure WriteBool(const Section, Ident: string; Value: Boolean); override;
procedure DeleteKey(const Section, Ident: string); override;
procedure ReadSection(const Section: string; Strings: TStrings); override;
procedure ReadSections(Strings: TStrings); override;
procedure ReadSectionValues(const Section: string; Strings: TStrings); override;
procedure EraseSection(const Section: string); override;
procedure UpdateFile; override;
function ValueExists(const Section, Ident: string): Boolean; override;
procedure GetStrings(List: TStrings);
end;
TXmlMemIniFile = class(TMemIniFile)
strict private
FXmlIniFile: TXmlIniFile;
procedure LoadValues;
public
constructor Create(const ANode: IXmlNode); reintroduce;
destructor Destroy; override;
procedure UpdateFile; override;
function ReadBool(const Section, Ident: string; Default: Boolean): Boolean; override;
function ReadInteger(const Section, Ident: string; Default: Longint): Longint; override;
function ReadString(const Section, Ident, Default: string): string; override;
procedure DeleteKey(const Section, Ident: String); override;
procedure EraseSection(const Section: string); override;
procedure WriteString(const Section, Ident, Value: String); override;
procedure WriteBool(const Section, Ident: string; Value: Boolean); override;
end;
implementation
uses System.SysUtils, System.Variants;
const
sName = 'Name';
function NormalizeIdent(const Ident: string): string;
var
I: Integer;
begin
Result := Ident;
for I := 1 to Length(Result) do
if (Result[I] = ' ') or (Result[I] = '\') then
Result[I] := '_';
end;
function IsBlankString(const S: string): Boolean;
var
I: Integer;
begin
Result := False;
for I := 1 to Length(S) do
if S[I] > #32 then
Exit;
Result := True;
end;
constructor TXmlIniFile.Create(const ANode: IXmlNode);
begin
FNode := ANode;
end;
function TXmlIniFile.ReadString(const Section, Ident, Default: string): string;
begin
Result := ReadXmlString(Section, Ident, Default);
end;
procedure TXmlIniFile.WriteString(const Section, Ident, Value: String);
begin
WriteXmlString(Section, Ident, Value);
end;
function TXmlIniFile.ReadInteger(const Section, Ident: string; Default: Longint): Longint;
begin
try
Result := StrToInt(ReadXmlString(Section, Ident, IntToStr(Default)));
except
Result := Default;
end;
end;
procedure TXmlIniFile.WriteInteger(const Section, Ident: string; Value: Longint);
begin
WriteXmlString(Section, Ident, IntToStr(Value));
end;
function TXmlIniFile.ReadBool(const Section, Ident: string; Default: Boolean): Boolean;
var
S: string;
begin
S := ReadXmlString(Section, Ident, '');
if S = '' then
Result := Default
else
Result := SameText(S, 'True');
end;
procedure TXmlIniFile.WriteBool(const Section, Ident: string; Value: Boolean);
begin
if Value then
WriteXmlString(Section, Ident, 'True') //Do not Internationalize
else
WriteXmlString(Section, Ident, 'False'); //Do not Internationalize
end;
procedure TXmlIniFile.DeleteChildNode(AParentNode: IXmlNode; AIndex: Integer);
begin
if AIndex <> -1 then
begin
AParentNode.ChildNodes.Delete(AIndex);
// delete the indention
if AIndex - 1 >= 0 then
if (AParentNode.ChildNodes.Get(AIndex - 1).NodeType = ntText) and
IsBlankString(AParentNode.ChildNodes.Get(AIndex - 1).Text) then
AParentNode.ChildNodes.Delete(AIndex - 1);
// delete the line break and parent indention
if AIndex - 2 >= 0 then
if (AParentNode.ChildNodes.Get(AIndex - 2).NodeType = ntText) and
IsBlankString(AParentNode.ChildNodes.Get(AIndex - 2).Text) then
AParentNode.ChildNodes.Delete(AIndex - 2);
// if the section is empty we still have a linebreak + parent indention
if (AParentNode.ChildNodes.Count = 1) and (AParentNode.ChildNodes.Get(0).NodeType = ntText) and
IsBlankString(AParentNode.ChildNodes.Get(0).Text) then
AParentNode.ChildNodes.Clear;
end;
end;
procedure TXmlIniFile.DeleteKey(const Section, Ident: string);
var
I, Index: Integer;
LNode, LChildNode: IXMLNode;
begin
Index := -1;
LNode := FindXMLNode(Section);
if LNode <> nil then
for I := 0 to LNode.ChildNodes.Count - 1 do
begin
LChildNode := LNode.ChildNodes.Get(I);
if (LChildNode.NodeType = ntElement) and (LChildNode.Attributes[sName] = Ident) then
begin
Index := I;
Break;
end;
end;
if Index <> -1 then
DeleteChildNode(LNode, Index);
end;
procedure TXmlIniFile.ReadSection(const Section: string; Strings: TStrings);
var
I: Integer;
LNode: IXMLNode;
ChildNode: IXMLNode;
begin
Strings.Clear;
LNode := FindXMLNode(Section);
if LNode <> nil then
begin
for I := 0 to LNode.ChildNodes.Count - 1 do
begin
ChildNode := LNode.ChildNodes.Get(I);
if (ChildNode.NodeType = ntElement) and not VarIsNull(ChildNode.Attributes[sName]) then
Strings.Add(ChildNode.Attributes[sName]);
end;
end;
end;
procedure TXmlIniFile.ReadSections(Strings: TStrings);
var
I: Integer;
ChildNode: IXMLNode;
begin
if FNode <> nil then
begin
for I := 0 to FNode.ChildNodes.Count - 1 do
begin
ChildNode := FNode.ChildNodes.Get(I);
if ChildNode.NodeType = ntElement then
Strings.Add(ChildNode.NodeName);
end;
end;
end;
procedure TXmlIniFile.ReadSectionValues(const Section: string; Strings: TStrings);
begin
Strings.BeginUpdate;
try
Strings.Clear;
GetSectionValues(Section, Strings);
finally
Strings.EndUpdate;
end;
end;
procedure TXmlIniFile.EraseSection(const Section: string);
var
Node: IXmlNode;
begin
Node := FindXmlNode(Section);
if Node <> nil then
DeleteChildNode(Node.ParentNode, Node.ParentNode.ChildNodes.IndexOf(Node));
end;
procedure TXmlIniFile.UpdateFile;
begin
end;
procedure TXmlIniFile.WriteXmlString(const Section, Name, Value: string);
var
I: Integer;
Existing: IXmlNode;
LocalNode, LocalChildNode: IXmlNode;
ChildNodes: IXMLNodeList;
begin
LocalNode := FindXmlNodeOrAdd(Section);
Existing := nil;
ChildNodes := LocalNode.ChildNodes;
for I := 0 to ChildNodes.Count - 1 do
begin
LocalChildNode := ChildNodes.Get(I);
if (LocalChildNode.NodeType = ntElement) and (LocalChildNode.Attributes[sName] = Name) then
begin
Existing := LocalChildNode;
Break;
end;
end;
if not Assigned(Existing) then
begin
Existing := LocalNode.AddChild(NormalizeIdent(Section));
Existing.Attributes[sName] := Name;
end;
if Existing <> nil then
Existing.Text := Value;
end;
function TXmlIniFile.ReadXmlString(const Section, Name, Default: string): string;
var
I: Integer;
LocalNode: IXmlNode;
LocalChildNode: IXmlNode;
function LocalAttributeIs(const Value: string): Boolean;
var
O: OleVariant;
VarData: PVarData;
A: string;
begin
O := LocalChildNode.Attributes[sName];
VarData := FindVarData(O);
if (VarData.VType = varString) or (VarData.VType = varOleStr) then
begin
A := O;
Result := A = Value;
end
else
Result := False;
end;
begin
LocalNode := FindXmlNode(Section);
if LocalNode <> nil then
begin
for I := 0 to LocalNode.ChildNodes.Count - 1 do
begin
LocalChildNode := LocalNode.ChildNodes.Get(I);
if (LocalChildNode.NodeType = ntElement) and LocalAttributeIs(Name) then
begin
Result := LocalChildNode.Text;
Exit;
end;
end;
end;
Result := Default;
end;
function TXmlIniFile.FindXmlNode(const NodeName: string): IXmlNode;
var
I: Integer;
LNodeName: string;
ChildNode: IXmlNode;
begin
Result := nil;
if FNode <> nil then
begin
LNodeName := NormalizeIdent(NodeName);
for I := 0 to FNode.ChildNodes.Count - 1 do
begin
ChildNode := FNode.ChildNodes.Get(I);
if (ChildNode.NodeType = ntElement) and (ChildNode.NodeName = LNodeName) then
begin
Result := ChildNode;
Exit;
end;
end;
end;
end;
function TXmlIniFile.FindXmlNodeOrAdd(const NodeName: string): IXmlNode;
begin
Result := FindXmlNode(NodeName);
if Result = nil then
Result := FNode.AddChild(NormalizeIdent(NodeName));
end;
procedure TXmlIniFile.GetSectionValues(const Section: string; Strings: TStrings);
var
I: Integer;
SectionNode, ChildNode: IXMLNode;
NameAttrValue: OleVariant;
begin
SectionNode := FindXMLNode(Section);
if SectionNode <> nil then
for I := 0 to SectionNode.ChildNodes.Count - 1 do
begin
ChildNode := SectionNode.ChildNodes.Get(I);
if ChildNode.NodeType = ntElement then
begin
NameAttrValue := ChildNode.Attributes[sName];
if not VarIsNull(NameAttrValue) then
begin
// Variants are not converting properly to a string, so cast it manually.
Strings.Add(string(NameAttrValue) + '=' + ChildNode.Text);
end;
end;
end;
end;
procedure TXmlIniFile.GetStrings(List: TStrings);
var
I: Integer;
Section: string;
Sections: TStrings;
begin
List.BeginUpdate;
try
Sections := TStringList.Create;
try
List.Clear;
ReadSections(Sections);
for I := 0 to Sections.Count - 1 do
begin
Section := Sections[I];
List.Add('['+Section+']');
GetSectionValues(Sections[I], List);
end;
finally
Sections.Free;
end;
finally
List.EndUpdate;
end;
end;
function TXmlIniFile.ValueExists(const Section, Ident: string): Boolean;
var
I: Integer;
LNode: IXMLNode;
ChildNode: IXMLNode;
begin
Result := False;
LNode := FindXMLNode(Section);
if LNode <> nil then
begin
for I := 0 to LNode.ChildNodes.Count - 1 do
begin
ChildNode := LNode.ChildNodes.Get(I);
if ChildNode.IsTextElement and (ChildNode.Attributes[sName] = Ident) then
begin
Result := True;
Exit;
end;
end;
end;
end;
{ TXmlMemIniFile }
constructor TXmlMemIniFile.Create(const ANode: IXmlNode);
begin
inherited Create('');
FXmlIniFile := TXmlIniFile.Create(ANode);
LoadValues;
end;
procedure TXmlMemIniFile.DeleteKey(const Section, Ident: String);
begin
inherited;
FXmlIniFile.DeleteKey(Section, Ident);
end;
destructor TXmlMemIniFile.Destroy;
begin
inherited;
FreeAndNil(FXmlIniFile);
end;
procedure TXmlMemIniFile.EraseSection(const Section: string);
begin
inherited;
FXmlIniFile.EraseSection(Section);
end;
procedure TXmlMemIniFile.LoadValues;
var
Values: TStrings;
begin
Values := TStringList.Create;
try
FXmlIniFile.GetStrings(Values);
SetStrings(Values);
finally
Values.Free;
end;
end;
function TXmlMemIniFile.ReadBool(const Section, Ident: string; Default: Boolean): Boolean;
var
S: string;
begin
// We use the same implementation as TXmlIniFile which handles True and False.
// TCustomIniFile does not handle strings for booleans
S := ReadString(Section, Ident, '');
if S = '' then
Result := Default
else
Result := SameText(S, 'True');
end;
function TXmlMemIniFile.ReadInteger(const Section, Ident: string; Default: Integer): Longint;
begin
try
Result := StrToInt(ReadString(Section, Ident, IntToStr(Default)));
except
Result := Default;
end;
end;
function TXmlMemIniFile.ReadString(const Section, Ident, Default: string): string;
begin
// need to NormalizeIdent the Section before reading the string so that the reads
// match the writes -- since we use TXmlIniFile for writing and TXmlMemIniFile for
// reading of Delphi projects.
Result := inherited ReadString(NormalizeIdent(Section), Ident, Default);
end;
procedure TXmlMemIniFile.UpdateFile;
begin
// Nop since TxmlIniFile is a Nop
end;
procedure TXmlMemIniFile.WriteBool(const Section, Ident: string; Value: Boolean);
begin
inherited;
FXmlIniFile.WriteBool(Section, Ident, Value);
end;
procedure TXmlMemIniFile.WriteString(const Section, Ident, Value: String);
begin
inherited;
FXmlIniFile.WriteString(Section, Ident, Value);
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the GNU General Public License
Version 2.0 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.gnu.org/copyleft/gpl.html
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.
The Initial Developer of the Original Code is Michael Elsdörfer.
All Rights Reserved.
$Id$
You may retrieve the latest version of this file at the Corporeal
Website, located at http://www.elsdoerfer.info/corporeal
Known Issues:
-----------------------------------------------------------------------------}
unit ApplicationSettings;
interface
uses
Classes, SysUtils, Forms;
type
TCorporealSettings = class(TPersistent)
private
FDefaultStore: string;
FAutoLockAfter: Integer;
FLimitToOneInstance: Boolean;
procedure SetDefaultStore(const Value: string);
procedure SetAutoLockAfter(const Value: Integer);
function GetApplicationExePath: WideString;
procedure SetApplicationExePath(const Value: WideString);
procedure SetLimitToOneInstance(const Value: Boolean);
published
public
constructor Create; virtual;
published
property DefaultStore: string read FDefaultStore write SetDefaultStore;
property AutoLockAfter: Integer read FAutoLockAfter write SetAutoLockAfter;
// This makes sure the path to the executable is automatically written to the registry
property ApplicationExePath: WideString read GetApplicationExePath write SetApplicationExePath;
property LimitToOneInstance: Boolean read FLimitToOneInstance write SetLimitToOneInstance;
end;
function Settings: TCorporealSettings;
implementation
var
InternalSettingsObj: TCorporealSettings = nil;
function Settings: TCorporealSettings;
begin
if InternalSettingsObj = nil then
InternalSettingsObj := TCorporealSettings.Create;
Result := InternalSettingsObj;
end;
{ TCorporealSettings }
constructor TCorporealSettings.Create;
begin
FDefaultStore := '';
FAutoLockAfter := 10;
FLimitToOneInstance := True;
end;
function TCorporealSettings.GetApplicationExePath: WideString;
begin
Result := ExtractFilePath(Application.ExeName);
end;
procedure TCorporealSettings.SetApplicationExePath(const Value: WideString);
begin
// do not accept any values for this
end;
procedure TCorporealSettings.SetAutoLockAfter(const Value: Integer);
begin
FAutoLockAfter := Value;
end;
procedure TCorporealSettings.SetDefaultStore(const Value: string);
begin
FDefaultStore := Value;
end;
procedure TCorporealSettings.SetLimitToOneInstance(const Value: Boolean);
begin
FLimitToOneInstance := Value;
end;
initialization
finalization
if InternalSettingsObj <> nil then
InternalSettingsObj.Free;
end.
|
unit UnLancarPagamentoView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
{ Fluente }
UnComandaModel, UnComandaController,
Controls, ExtCtrls, StdCtrls, Classes;
type
TLancarPagamentoView = class(TForm)
Label1: TLabel;
edtProduto: TEdit;
Label2: TLabel;
Edit1: TEdit;
btnOk: TPanel;
btnFechar: TPanel;
procedure btnOkClick(Sender: TObject);
procedure btnFecharClick(Sender: TObject);
private
FComandaModel: TComandaModel;
FComandaController: TComandaController;
public
constructor Create(const ComandaModel: TComandaModel;
const ComandaController: TComandaController); reintroduce;
end;
var
LancarPagamentoView: TLancarPagamentoView;
implementation
{$R *.dfm}
constructor TLancarPagamentoView.Create(const ComandaModel: TComandaModel; const ComandaController: TComandaController);
begin
inherited Create(nil);
Self.FComandaModel := ComandaModel;
Self.FComandaController := ComandaController;
end;
procedure TLancarPagamentoView.btnFecharClick(Sender: TObject);
begin
Self.ModalResult := mrCancel;
end;
procedure TLancarPagamentoView.btnOkClick(Sender: TObject);
begin
Self.ModalResult := mrOk;
end;
end.
|
unit FC.Trade.Trader.PTL;
interface
uses Classes, Math,Graphics, Contnrs, Forms, Controls, SysUtils, BaseUtils, ActnList, Properties.Obj, Properties.Definitions,
StockChart.Definitions, StockChart.Definitions.Units, Properties.Controls, StockChart.Indicators,
Serialization, FC.Definitions, FC.Trade.Trader.Base,FC.Trade.Properties,FC.fmUIDataStorage, Dialogs;
type
//тип игры - никак, прорывы вверх и вниз, отбои вверх и вниз
TTradeType = (ttNothing, ttUp_Break, ttDown_Break, ttUp_Recoil, ttDown_Recoil);
//Идентификационный интерфейс трейдера.
IStockTraderPTL = interface
['{04FA6D2C-252B-4EF2-AA67-5CD97B07CF88}']
end;
TStockTraderPTL = class (TStockTraderBase, IStockTraderPTL)
private
FStopLoss, FTakeProfit: double;
FTrailingStop: double;
FSafeGap: double;
FPropSafeGap: TPropertySmallUint;
FTradeType: TTradeType;
FPC_10 : ISCIndicatorPriceChannel;
FPC_22 : ISCIndicatorPriceChannel;
FPC_3 : ISCIndicatorPriceChannel;
FTF: TStockTimeInterval;
FCurrentBar: integer;
protected
public
//Создание-удаление своих объектов
procedure OnCreateObjects; override;
procedure OnReleaseObjects; override;
constructor Create; override;
destructor Destroy; override;
procedure UpdateStep2(const aTime: TDateTime); override;
procedure OnPropertyChanged(aNotifier:TProperty); override;
end;
implementation
uses FC.Trade.Trader.Factory;
constructor TStockTraderPTL.Create;
begin
inherited Create;
FTF:=sti1440;
FPropSafeGap:=TPropertySmallUint.Create('Method','Safe Gap',self);
FPropSafeGap.Value:=10;
RegisterProperties([FPropSafeGap]);
FCurrentBar:=-1;
FTradeType:=ttNothing;
end;
destructor TStockTraderPTL.Destroy;
begin
inherited;
end;
procedure TStockTraderPTL.OnCreateObjects;
var
aCreated: boolean;
begin
inherited;
//Создаем PC-10 на ТФ_D1
FPC_10:=CreateOrFindIndicator(GetProject.GetStockChart(FTF),ISCIndicatorPriceChannel,'1440, PC(10)',true, aCreated) as ISCIndicatorPriceChannel;
//Если индикатор был только что создан, мы выставляем ему значения по умолчанию,
//иначе оставляем как есть - ведь пользователь мог их изменить
if aCreated then
begin
FPC_10.SetPeriod(10);
FPC_10.SetTopLineColor(clGreen);
FPC_10.SetBottomLineColor(clRed);
FPC_10.SetTopLineStyle(lsDash);
FPC_10.SetBottomLineStyle(lsDot);
end;
//Создаем PC-22 на ТФ_D1
FPC_22:=CreateOrFindIndicator(GetProject.GetStockChart(FTF),ISCIndicatorPriceChannel,'1440, PC(22)',true, aCreated) as ISCIndicatorPriceChannel;
if aCreated then
begin
FPC_22.SetPeriod(22);
FPC_22.SetTopLineColor(clBlack);
FPC_22.SetBottomLineColor(clBlack);
FPC_22.SetTopLineStyle(lsSolid);
FPC_22.SetBottomLineStyle(lsSolid);
end;
{
//Создаем PC-3 на ТФ_D1
FPC_3:=CreateOrFindIndicator(GetProject.GetStockChart(FTF),ISCIndicatorPriceChannel,'1440, PC(3)',true, aCreated) as ISCIndicatorPriceChannel;
if aCreated then
begin
FPC_3.SetPeriod(3);
end;
}
end;
procedure TStockTraderPTL.OnReleaseObjects;
begin
inherited;
if FPC_10<>nil then
OnRemoveObject(FPC_10);
FPC_10:=nil;
if FPC_22<>nil then
OnRemoveObject(FPC_22);
FPC_22:=nil;
if FPC_3<>nil then
OnRemoveObject(FPC_3);
FPC_3:=nil;
end;
procedure TStockTraderPTL.UpdateStep2(const aTime: TDateTime);
var
j: integer;
aChart: IStockChart;
aInputData : ISCInputDataCollection;
aOrder: IStockOrder;
aOrders: IStockOrderCollection;
aBroker: IStockBroker;
aPC_10_Top, aPC_10_Bottom: double;
// aPC_22, aPC_3: double;
aOpenPrice: double;
aSpread: integer;
// aBid,aAsk: double;
begin
//Спрэд для установки ордеров с экстремумов
//Спрэд, который дает тестовый брокер тут не подходит
aSpread:=3;
aChart:=GetProject.GetStockChart(FTF);
aInputData:=aChart.GetInputData;
aOrders:=GetOrders;
aBroker:=GetBroker;
//aBid:=aBroker.GetCurrentPrice(GetSymbol,bpkBid);
//aAsk:=aBroker.GetCurrentPrice(GetSymbol,bpkAsk);
if aOrders.Count>1 then
begin
ShowMessage('Слишком много ордеров');
exit;
end;
RemoveClosedOrders;
//Если ордеров нет, значит мы никуда не играем
if aOrders.Count<1 then FTradeType:=ttNothing;
//определение номера бара, с запрашиваемым временем
j:=aChart.FindBar(aTime);
if j<2 then exit;
//ловим момент завершение предыдущего бара
if FCurrentBar=j then exit
else FCurrentBar:=j;
//все, что ниже должно происходить один раз за бар
aPC_10_Top:=FPC_10.GetTopValue(j-2);
if aPC_10_Top<=0 then exit;
aPC_10_Bottom:=FPC_10.GetBottomValue(j-2);
if aPC_10_Bottom<=0 then exit;
if FTradeType=ttNothing then
begin
//ждем касания вчерашней цены позавчерашнего PC-10
//(вчерашняя свеча только что закончилась)
//касание верхней линии
if aInputData[j-1].DataHigh>=aPC_10_Top then
begin
//пробой верхней линии закрытием свечи
if aInputData[j-1].DataClose>aPC_10_Top then
begin
aOpenPrice:=aInputData[j-1].DataHigh+GetBroker.PointToPrice(GetSymbol,aSpread)+FSafeGap;
aOrder:=OpenOrderAt(okBuy,aOpenPrice,'');
// aOrder.OpenAt(okBuy,aOpenPrice,1);
{
aOrder.SetStopLoss(aOpenPrice-FStopLoss);
aOrder.SetTakeProfit(aOpenPrice+FTakeProfit);
aOrder.SetTrailingStop(FTrailingStop);
}
FTradeType:=ttUp_Break;
end
//пробоя нет - играем на отбой от верхней линии
else
begin
aOpenPrice:=aInputData[j-1].DataLow-FSafeGap;
aOrder:=OpenOrderAt(okSell,aOpenPrice,'');
// aOrder:=CreateEmptyOrder;
// aOrder.OpenAt(okSell,aOpenPrice,1);
{
aOrder.SetStopLoss(aOpenPrice+FStopLoss);
aOrder.SetTakeProfit(aOpenPrice-FTakeProfit);
aOrder.SetTrailingStop(FTrailingStop);
}
FTradeType:=ttDown_Recoil;
end;
end;
//касание нижней линии
if aInputData[j-1].DataLow<=aPC_10_Bottom then
begin
//пробой нижней линии закрытием
if aInputData[j-1].DataClose<aPC_10_Bottom then
begin
aOpenPrice:=aInputData[j-1].DataLow-FSafeGap;
aOrder:=OpenOrderAt(okSell,aOpenPrice,'');
// aOrder:=CreateEmptyOrder;
// aOrder.OpenAt(okSell,aOpenPrice,1);
{
aOrder.SetStopLoss(aOpenPrice+FStopLoss);
aOrder.SetTakeProfit(aOpenPrice-FTakeProfit);
aOrder.SetTrailingStop(FTrailingStop);
}
FTradeType:=ttDown_Break;
end
//пробоя нет - играем на отбой от нижней линии
else
begin
aOpenPrice:=aInputData[j-1].DataHigh+GetBroker.PointToPrice(GetSymbol,aSpread)+FSafeGap;
aOrder:=OpenOrderAt(okBuy,aOpenPrice,'');
// aOrder:=CreateEmptyOrder;
// aOrder.OpenAt(okBuy,aOpenPrice,1);
{
aOrder.SetStopLoss(aOpenPrice-FStopLoss);
aOrder.SetTakeProfit(aOpenPrice+FTakeProfit);
aOrder.SetTrailingStop(FTrailingStop);
}
FTradeType:=ttUp_Recoil;
end;
end;
end
//корректируем отложенные ордеры на отбой от нижней линии
else if (FTradeType=ttUp_Recoil) then
if (aOrders.Items[0].GetState=osPending) and (aInputData[j-1].DataLow<=aPC_10_Bottom) and (aInputData[j-1].DataClose>=aPC_10_Bottom) then
begin
end
//корректируем отложенные ордеры на отбой от верхней линии
else if (FTradeType=ttDown_Recoil) then
if(aOrders.Items[0].GetState=osPending) and (aInputData[j-1].DataHigh>=aPC_10_Top) and (aInputData[j-1].DataClose<=aPC_10_Top) then
begin
end;
//надо не забыть про ситуацию, когда цена касается обеих линий
//if (aInputData[j].DataHigh>=aPC_10_Top) and (aInputData[j].DataLow<=aPC_10_Bottom) then
end;
procedure TStockTraderPTL.OnPropertyChanged(aNotifier:TProperty);
var
aPropName: string;
i: integer;
begin
//берем значения из свойств трэйдера
for i := 0 to GetProperties.Count-1 do
begin
aPropName:=GetProperties.Items[i].GetName;
if aPropName='Enough Profit' then FTakeProfit:=GetBroker.PointToPrice(GetSymbol,GetProperties.Items[i].Value)
else if aPropName='Max Subsidence' then FStopLoss:=GetBroker.PointToPrice(GetSymbol,GetProperties.Items[i].Value)
else if aPropName='Trailing stop' then FTrailingStop:=GetBroker.PointToPrice(GetSymbol,GetProperties.Items[i].Value)
else if aPropName='Safe Gap' then FSafeGap:=GetBroker.PointToPrice(GetSymbol,GetProperties.Items[i].Value);
end;
end;
initialization
FC.Trade.Trader.Factory.TraderFactory.RegisterTrader('Test','Primitive Technical Look',TStockTraderPTL,IStockTraderPTL);
end.
|
{***************************************************************
*
* Project : CGIMailer
* Unit Name: fMain
* Purpose : Demonstrates using SMTP comp to sendmail using CGI
* Version : 1.0
* Date : Fri 16 Feb 2001 - 04:27:01
* Author : Allen O'Neill <allen_oneill@hotmail.com>
* History :
*
****************************************************************}
unit fMain;
interface
uses
windows, messages, SysUtils, Classes, HTTPApp, IdMessage,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdMessageClient, IdSMTP
{$IFDEF VER140},HTTPProd;{$ELSE};{$ENDIF}
type
TWebModule1 = class(TWebModule)
IdSMTP: TIdSMTP;
IdMessage: TIdMessage;
pgeError: TPageProducer;
pgeForm: TPageProducer;
pgeSuccess: TPageProducer;
procedure WebModule1actMainAction(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
procedure pgeErrorHTMLTag(Sender: TObject; Tag: TTag;
const TagString: String; TagParams: TStrings;
var ReplaceText: String);
procedure pgeFormHTMLTag(Sender: TObject; Tag: TTag;
const TagString: String; TagParams: TStrings;
var ReplaceText: String);
private
{ Private declarations }
Err_Msg: string;
slstVarsIn: TStrings;
public
{ Public declarations }
end;
var
WebModule1: TWebModule1;
implementation
{$R *.DFM}
procedure TWebModule1.WebModule1actMainAction(Sender: TObject;
Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
Err_Msg := '<ul>';
if Request.MethodType = mtGet then
slstVarsIn := Request.QueryFields
else if Request.MethodType = mtPost then
slstVarsIn := Request.ContentFields
else
begin
Response.content := pgeError.content;
end;
if slstVarsIn.Count = 0 then Response.content := pgeForm.content // if there is no data sent in then returnthe mailer input form
else
begin
// set message parts
with IdMessage do
begin
if trim(slstVarsIn.Values['Sender']) <> '' then
begin
Sender.Address := slstVarsIn.Values['Sender'];
From.Address := slstVarsIn.Values['Sender'];
end
else Err_Msg := Err_Msg + #13 + '<li>' + 'Cannot send without sender information ..';
if trim(slstVarsIn.Values['Too']) <> '' then
Recipients.EMailAddresses := slstVarsIn.Values['too']
else Err_Msg := Err_Msg + #13 + '<li>' + 'Cannot send without recipient <i>(to)</i> information ..';
if trim(slstVarsIn.Values['Body']) <> '' then
Body.Append(slstVarsIn.Values['Body'])
else Err_Msg := Err_Msg + #13 + '<li>' + 'Ahhh come on ... how about some text in the message? ..';
if trim(slstVarsIn.Values['Subject']) <> '' then
Subject := slstVarsIn.Values['Subject']
else Subject := '<no subject>';
end;
// set recipient parts and send it off !
with IdSMTP do
begin
if length(trim(slstVarsIn.Values['Host'])) > 0 then
Host := slstVarsIn.Values['Host']
else Err_Msg := Err_Msg + #13 + '<li>' + 'You must fill in the SMTP host name!';
if length(trim(slstVarsIn.Values['user'])) > 0 then
UserId := slstVarsIn.Values['user']
else Err_Msg := Err_Msg + #13 + '<li>' + 'You must fill in the SMTP user name!';
if Err_Msg = '<ul>' then
begin
try
Connect;
Send(IdMessage);
Disconnect;
Response.content := pgeSuccess.content;
except
on E : Exception do
begin
Err_Msg := Err_Msg + #13 + '<li>' + E.Message;
Response.content := pgeError.content;
end;
end
end
else Response.content := pgeError.content;
end;
end;
end;
procedure TWebModule1.pgeErrorHTMLTag(Sender: TObject; Tag: TTag;
const TagString: String; TagParams: TStrings; var ReplaceText: String);
begin
if TagString = 'ERROR_MSG' then ReplaceText := Err_Msg + '</ul>';
end;
procedure TWebModule1.pgeFormHTMLTag(Sender: TObject; Tag: TTag;
const TagString: String; TagParams: TStrings; var ReplaceText: String);
begin
if TagString = 'HOST' then ReplaceText := Request.Host;
if TagString = 'SCRIPT' then ReplaceText := Request.ScriptName;
end;
end.
|
unit ParametricTableErrorForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, RootForm, Vcl.ExtCtrls, GridFrame,
GridView, GridViewEx, ParametricTableErrorView, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Vcl.Menus, dxSkinsCore, dxSkinBlack, dxSkinBlue,
dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide,
dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, Vcl.StdCtrls, cxButtons, System.Contnrs;
type
TfrmParametricTableError = class(TfrmRoot)
pnlMain: TPanel;
cxButtonNext: TcxButton;
cxButtonCancel: TcxButton;
private
FEvents: TObjectList;
FViewParametricTableError: TViewParametricTableError;
procedure DoOnAssignDataSet(Sender: TObject);
procedure DoOnFixError(Sender: TObject);
procedure UpdateView;
{ Private declarations }
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ViewParametricTableError: TViewParametricTableError
read FViewParametricTableError;
{ Public declarations }
end;
implementation
uses
NotifyEvents, ParametricErrorTable;
{$R *.dfm}
constructor TfrmParametricTableError.Create(AOwner: TComponent);
begin
inherited;
FEvents := TObjectList.Create;
FViewParametricTableError := TViewParametricTableError.Create(Self);
FViewParametricTableError.Parent := pnlMain;
FViewParametricTableError.Align := alClient;
TNotifyEventWrap.Create(FViewParametricTableError.OnAssignDataSet,
DoOnAssignDataSet, FEvents);
UpdateView;
end;
destructor TfrmParametricTableError.Destroy;
begin
FreeAndNil(FEvents);
inherited;
end;
procedure TfrmParametricTableError.DoOnAssignDataSet(Sender: TObject);
begin
TNotifyEventWrap.Create(FViewParametricTableError.W.OnFixError,
DoOnFixError, FEvents);
UpdateView;
end;
procedure TfrmParametricTableError.DoOnFixError(Sender: TObject);
begin
UpdateView;
end;
procedure TfrmParametricTableError.UpdateView;
begin
// Кнопка "Далее" активна,
// если в списке ошибок нет ошибок связанных с дублированием параметра
cxButtonNext.Enabled := (FViewParametricTableError.DSWrap <> nil) and
((FViewParametricTableError.W.DataSet as TParametricErrorTable)
.ParamDuplicateClone.RecordCount = 0);
end;
end.
|
unit XT_Base;
(*************************************************************************
DESCRIPTION : XTEA basic routines
REQUIREMENTS : TP5-7, D1-D7/D9-D12/D17-D18/D25S, FPC, VP, WDOSX
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : Roger M. Needham and David J. Wheeler: Tea extensions
ftp://ftp.cl.cam.ac.uk/users/djw3/xtea.ps
REMARK : Number of rounds is hardcoded to 32
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 01.01.05 W.Ehrhardt Initial version a la BF_Base
0.11 01.01.05 we BASM16 inline
0.12 01.01.05 we BIT16: XT_Init mit sumw
0.13 04.01.05 we with RB and Idx, compatible with Botan
0.14 04.01.05 we load K with RB(Key) only once
0.15 06.08.10 we XT_Err_CTR_SeekOffset, XT_Err_Invalid_16Bit_Length
0.16 22.07.12 we 64-bit adjustments
0.17 25.12.12 we {$J+} if needed
0.18 19.11.17 we RB for CPUARM
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2005-2017 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
const
XT_Err_Invalid_Key_Size = -1; {Key size in bytes <1 or >56}
XT_Err_Invalid_Length = -3; {No full block for cipher stealing}
XT_Err_Data_After_Short_Block = -4; {Short block must be last}
XT_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
XT_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
XT_Err_CTR_SeekOffset = -15; {Invalid offset in XT_CTR_Seek}
XT_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TXTBlock = packed array[0..7] of byte;
PXTBlock = ^TXTBlock;
TXTRKArray = packed array[0..31] of longint;
type
TXT2Long = packed record
L,R: longint;
end;
type
TXTIncProc = procedure(var CTR: TXTBlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
type
TXTContext = packed record
XA,XB : TXTRKArray; {round key arrays }
IV : TXTBlock; {IV or CTR }
buf : TXTBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
IncProc : TXTIncProc; {Increment proc CTR-Mode}
end;
const
XTBLKSIZE = sizeof(TXTBlock);
{$ifdef CONST}
function XT_Init(const Key; KeyBytes: word; var ctx: TXTContext): integer;
{-XTEA context initialization}
{$ifdef DLL} stdcall; {$endif}
procedure XT_Encrypt(var ctx: TXTContext; const BI: TXTBlock; var BO: TXTBlock);
{-encrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure XT_Decrypt(var ctx: TXTContext; const BI: TXTBlock; var BO: TXTBlock);
{-decrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure XT_XorBlock(const B1, B2: TXTBlock; var B3: TXTBlock);
{-xor two blocks, result in third}
{$ifdef DLL} stdcall; {$endif}
{$else}
function XT_Init(var Key; KeyBytes: word; var ctx: TXTContext): integer;
{-XTEA context initialization}
{$ifdef DLL} stdcall; {$endif}
procedure XT_Encrypt(var ctx: TXTContext; var BI: TXTBlock; var BO: TXTBlock);
{-encrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure XT_Decrypt(var ctx: TXTContext; var BI: TXTBlock; var BO: TXTBlock);
{-decrypt one block (in ECB mode)}
{$ifdef DLL} stdcall; {$endif}
procedure XT_XorBlock(var B1, B2: TXTBlock; var B3: TXTBlock);
{-xor two blocks, result in third}
{$endif}
procedure XT_Reset(var ctx: TXTContext);
{-Clears ctx fields bLen and Flag}
procedure XT_SetFastInit(value: boolean);
{-set FastInit variable}
{$ifdef DLL} stdcall; {$endif}
function XT_GetFastInit: boolean;
{-Returns FastInit variable}
{$ifdef DLL} stdcall; {$endif}
implementation
{$ifdef D4Plus}
var
{$else}
{$ifdef J_OPT} {$J+} {$endif}
const
{$endif}
FastInit : boolean = true; {Clear only necessary context data at init}
{IV and buf remain uninitialized}
{$ifndef BIT16}
{------- 32/64-bit code --------}
{$ifdef BIT64}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-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;
{$else}
{$ifdef CPUARM}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; {$ifdef HAS_INLINE} inline; {$endif}
{-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;
{$else}
{---------------------------------------------------------------------------}
function RB(A: longint): longint; assembler; {&frame-}
{-reverse byte order in longint}
asm
{$ifdef LoadArgs}
mov eax,[A]
{$endif}
xchg al,ah
rol eax,16
xchg al,ah
end;
{$endif}
{$endif}
{$else}
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ { pop ax }
$5A/ { pop dx }
$86/$C6/ { xchg dh,al}
$86/$E2); { xchg dl,ah}
{$endif}
{---------------------------------------------------------------------------}
procedure XT_Reset(var ctx: TXTContext);
{-Clears ctx fields bLen and Flag}
begin
with ctx do begin
bLen :=0;
Flag :=0;
end;
end;
{---------------------------------------------------------------------------}
procedure XT_XorBlock({$ifdef CONST} const {$else} var {$endif} B1, B2: TXTBlock; var B3: TXTBlock);
{-xor two blocks, result in third}
begin
TXT2Long(B3).L := TXT2Long(B1).L xor TXT2Long(B2).L;
TXT2Long(B3).R := TXT2Long(B1).R xor TXT2Long(B2).R;
end;
{--------------------------------------------------------------------------}
procedure XT_SetFastInit(value: boolean);
{-set FastInit variable}
begin
FastInit := value;
end;
{---------------------------------------------------------------------------}
function XT_GetFastInit: boolean;
{-Returns FastInit variable}
begin
XT_GetFastInit := FastInit;
end;
{$ifdef BASM16}
{---------------------------------------------------------------------------}
function XTR(y: longint): longint;
{returns ((y shl 4) xor (y shr 5)) + y}
inline(
$66/$58/ {pop eax }
$66/$8B/$D0/ {mov edx,eax}
$66/$C1/$E2/$04/ {shl edx,4 }
$66/$8B/$C8/ {mov ecx,eax}
$66/$C1/$E9/$05/ {shr ecx,5 }
$66/$33/$D1/ {xor edx,ecx}
$66/$03/$C2/ {add eax,edx}
$66/$8B/$D0/ {mov edx,eax}
$66/$C1/$EA/$10); {shr edx,16 }
{$endif}
{---------------------------------------------------------------------------}
procedure XT_Encrypt(var ctx: TXTContext; {$ifdef CONST} const {$else} var {$endif} BI: TXTBlock; var BO: TXTBlock);
{-encrypt one block (in ECB mode)}
var
y, z: longint;
i: integer;
begin
with ctx do begin
y := RB(TXT2Long(BI).L);
z := RB(TXT2Long(BI).R);
for i:=0 to 31 do begin
{$ifdef BASM16}
inc(y, XTR(z) xor XA[i]);
inc(z, XTR(y) xor XB[i]);
{$else}
inc(y, ((((z shl 4) xor (z shr 5)) + z) xor XA[i]));
inc(z, ((((y shl 4) xor (y shr 5)) + y) xor XB[i]));
{$endif}
end;
TXT2Long(BO).L := RB(y);
TXT2Long(BO).R := RB(z);
end;
end;
{---------------------------------------------------------------------------}
procedure XT_Decrypt(var ctx: TXTContext; {$ifdef CONST} const {$else} var {$endif} BI: TXTBlock; var BO: TXTBlock);
{-decrypt one block (in ECB mode)}
var
y, z: longint;
i: integer;
begin
with ctx do begin
y := RB(TXT2Long(BI).L);
z := RB(TXT2Long(BI).R);
for i:=31 downto 0 do begin
{$ifdef BASM16}
dec(z, XTR(y) xor XB[i]);
dec(y, XTR(z) xor XA[i]);
{$else}
dec(z, ((((y shl 4) xor (y shr 5)) + y) xor XB[i]));
dec(y, ((((z shl 4) xor (z shr 5)) + z) xor XA[i]));
{$endif}
end;
TXT2Long(BO).L := RB(y);
TXT2Long(BO).R := RB(z);
end;
end;
{---------------------------------------------------------------------------}
function XT_Init({$ifdef CONST} const {$else} var {$endif} Key; KeyBytes: word; var ctx: TXTContext): integer;
{-XTEA context initialization}
type
TWA4 = array[0..3] of longint;
var
K: TWA4;
i: integer;
sum: longint;
{$ifdef BIT16}
idx: word absolute sum;
{$else}
idx: longint absolute sum;
{$endif}
begin
XT_Init := 0;
if FastInit then begin
{Clear only the necessary context data at init. IV and buf}
{remain uninitialized, other fields are initialized below.}
XT_Reset(ctx);
{$ifdef CONST}
ctx.IncProc := nil;
{$else}
{TP5-6 do not like IncProc := nil;}
fillchar(ctx.IncProc, sizeof(ctx.IncProc), 0);
{$endif}
end
else fillchar(ctx, sizeof(ctx), 0);
if KeyBytes<>16 then begin
XT_Init := XT_Err_Invalid_Key_Size;
exit;
end;
with ctx do begin
sum := 0;
for i:=0 to 3 do K[i] := RB(TWA4(Key)[i]);
for i:=0 to 31 do begin
XA[i] := sum + K[idx and 3];
inc(sum, longint($9E3779B9));
XB[i] := sum + K[(idx shr 11) and 3];
end;
end;
end;
end.
|
{ GS1 interface library for FPC and Lazarus
Copyright (C) 2020-2021 Lagunov Aleksey alexs75@yandex.ru
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit LP_base_types;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, xmlobject, AbstractSerializationObjects;
type
//IPv4. Запись в виде четырёх десятичных чисел (от 0 до 255), разделённых точками.
TIPv4Address_type = String;
//IPv6. Запись в виде восьми четырёхзначных шестнадцатеричных чисел (групп по четыре символа), разделённых двоеточием.
TIPv6Address_type = String;
//Текстовое значение не более 200 символов
Tstring200_type = String;
//Текстовое значение не более 255 символов
Tstring255_type = String;
//Произвольная строка длинной до 1000 символов
Tstring1000_type = String;
//ИНН Участника оборота
TTRADE_PARTICIPANT_INN_type = String;
//ИНН ЦЭМ
TLABELLING_CENTER_INN_type = String;
//Дата в формате ДД.ММ.ГГГГ
Tdate_type = String;
Tdatetimeoffset = TDateTime;
//Номер документа, но не более 200 символов
Tdocument_number_200_type = String;
//Справочник видов оборота товара
//1 - Продажа-покупка
//2 - Комиссия
//3 - Агент
//4 - Подряд
Tturnover_type_enum = Longint;
//Уникальный идентификатор товара. Количество символов: 31 либо 37 (с разделителями), 38 либо 44 (без разделителей).
Tgs1_uit_type = String;
//Уникальный идентификатор транспортной упаковки
Tgs1_uitu_type = String;
//Стоимость/Налог
Tprice_type = Double;
//GUID
Tguid_type = String;
//Регистрационный токен СУЗ
Ttoken_type = String;
//Товарная группа ТН ВЭД ЕАС
Ttnved_group_type = Int64;
//Код ТН ВЭД ЕАС
Ttnved_code_type = Int64;
//Справочник видов вывода из оборота
//1 - Розничная продажа
//2 - Экспорт в страны ЕАЭС
//3 - Экспорт за пределы стран ЕАЭС
//4 - Кредитный договор
//5 - Порча или утеря товара
//6 - Безвозмездная передача
//7 - Возврат физическому лицу (при невозможности реализовать товар по договору комиссии товар возвращается физическому лицу обратно)
//8 - Банкротство или ликвидация ЮЛ/ИП
//9 - Реализации конфискованных товаров
//10 - Использование на предприятии
//11 - Договор рассрочки
//12 - Розничная продажа ККТ
Taction_type = Longint;
//Справочник видов документа
//1 - Фискальный документ
//2 - Бланк строгой отчетности (БСО)
//3 - Договор
//4 - Акт уничтожения
//5 - Товарная накладная
//6 - Счет-фактура
//7 - Прочее
Tdoc_type_enum = Longint;
//Уникальный идентификатор транспортной упаковки или товара
Tgs1_uit_uitu_type = String;
Taoguid = String;
Thouseguid = String;
Tflat = String;
type
{ Forward declarations }
Tfias_address_type = class;
{ Generic classes for collections }
Tfias_address_typeList = specialize GXMLSerializationObjectList<Tfias_address_type>;
{ Tfias_address_type }
//Адрес в формате ФИАС
Tfias_address_type = class(TXmlSerializationObject)
private
Faoguid:Taoguid;
Fhouseguid:Thouseguid;
Fflat:Tflat;
procedure Setaoguid( AValue:Taoguid);
procedure Sethouseguid( AValue:Thouseguid);
procedure Setflat( AValue:Tflat);
protected
procedure InternalRegisterPropertys; override;
procedure InternalInitChilds; override;
public
constructor Create;
destructor Destroy; override;
published
//Глобальный уникальный идентификатор адресного объекта
property aoguid:Taoguid read Faoguid write Setaoguid;
//Глобальный уникальный идентификатор домаОбязателен при наличии
property houseguid:Thouseguid read Fhouseguid write Sethouseguid;
//КвартираОбязателен при наличии
property flat:Tflat read Fflat write Setflat;
end;
implementation
{ Tfias_address_type }
procedure Tfias_address_type.Setaoguid(AValue: Taoguid);
begin
CheckStrMinSize('aoguid', AValue);
CheckStrMaxSize('aoguid', AValue);
Faoguid:=AValue;
ModifiedProperty('aoguid');
end;
procedure Tfias_address_type.Sethouseguid(AValue: Thouseguid);
begin
CheckStrMinSize('houseguid', AValue);
CheckStrMaxSize('houseguid', AValue);
Fhouseguid:=AValue;
ModifiedProperty('houseguid');
end;
procedure Tfias_address_type.Setflat(AValue: Tflat);
begin
CheckStrMinSize('flat', AValue);
CheckStrMaxSize('flat', AValue);
Fflat:=AValue;
ModifiedProperty('flat');
end;
procedure Tfias_address_type.InternalRegisterPropertys;
var
P: TPropertyDef;
begin
inherited InternalRegisterPropertys;
P:=RegisterProperty('aoguid', 'aoguid', [xsaSimpleObject], '', 36, 36);
P:=RegisterProperty('houseguid', 'houseguid', [xsaSimpleObject], '', 36, 36);
P:=RegisterProperty('flat', 'flat', [xsaSimpleObject], '', 1, 20);
end;
procedure Tfias_address_type.InternalInitChilds;
begin
inherited InternalInitChilds;
end;
destructor Tfias_address_type.Destroy;
begin
inherited Destroy;
end;
constructor Tfias_address_type.Create;
begin
inherited Create;
end;
end.
|
unit Financas.Controller.Connections.Factory.Connection;
interface
uses Financas.Controller.Connections.Interfaces, Financas.Model.Connections.Interfaces, Financas.Model.Connections.Factory.Connection;
Type
TControllerConnectionsFactoryConnection = class(TInterfacedObject, iControllerFactoryConnection)
private
public
constructor Create;
destructor Destroy; override;
class function New: iControllerFactoryConnection;
function Connection: iModelConnection;
end;
implementation
uses System.SysUtils, Financas.Controller.IniFiles.Factory;
{ TControllerConnectionsFactoryConnection }
function TControllerConnectionsFactoryConnection.Connection: iModelConnection;
var
Connection: Integer;
begin
Connection := 0;
//
case Connection of
0: Result := TModelConnectionFactoryConnections.New
.ConnectionFiredac
.Params
.Database(TControllerIniFileFactory.New.Database)
.UserName(TControllerIniFileFactory.New.UserName)
.Password(TControllerIniFileFactory.New.Password)
.DriverID(TControllerIniFileFactory.New.DriverID)
.Server(TControllerIniFileFactory.New.Server)
.Porta(StrToInt(TControllerIniFileFactory.New.Port))
.EndParams
.Conectar;
1: raise Exception.Create('Componente de acesso não configurado');
end;
end;
constructor TControllerConnectionsFactoryConnection.Create;
begin
end;
destructor TControllerConnectionsFactoryConnection.Destroy;
begin
inherited;
end;
class function TControllerConnectionsFactoryConnection.New: iControllerFactoryConnection;
begin
Result := Self.Create;
end;
end.
|
/// <summary>
/// <para>
/// Documentation for RPC: <see href="https://www.pascalcoin.org/development/rpc" />
/// </para>
/// <para>
/// <br />Every call MUST include 3 params: {"jsonrpc": "2.0", "method":
/// "XXX", "id": YYY}
/// </para>
/// <para>
/// <br />jsonrpc : String value = "2.0" <br />method : String value,
/// name of the method to call <br />id : Integer value <br />
/// </para>
/// <para>
/// Optionally can contain another param called "params" holding an
/// object. Inside we will include params to send to the method <br />
/// {"jsonrpc": "2.0", "method": "XXX", "id": YYY, "params":{"p1":"
/// ","p2":" "}}
/// </para>
/// </summary>
unit PascalCoin.RPC.Interfaces;
interface
uses System.Classes, System.JSON, System.SysUtils, System.Rtti,
System.Generics.Collections, Spring.Container, PascalCoin.Utils.Interfaces;
type
ErpcHTTPException = class(Exception);
ERPCException = class(Exception);
{$SCOPEDENUMS ON}
THTTPStatusType = (OK, Fail, Exception);
TNodeAvailability = (NotTested, NotAvailable, Avaialable);
{$SCOPEDENUMS OFF}
IRPCHTTPRequest = interface(IInvokable)
['{67CDB48B-C4F4-4C0F-BE61-BDA3497CF892}']
function GetResponseStr: string;
function GetStatusCode: integer;
function GetStatusText: string;
function GetStatusType: THTTPStatusType;
procedure Clear;
function Post(AURL: string; AData: string): boolean;
property ResponseStr: string read GetResponseStr;
property StatusCode: integer read GetStatusCode;
property StatusText: string read GetStatusText;
property StstusType: THTTPStatusType read GetStatusType;
end;
IPascalCoinNodeStatus = interface;
IPascalCoinRPCClient = interface
['{A04B65F9-345E-44F7-B834-88CCFFFAC4B6}']
function GetResult: TJSONObject;
function GetResultStr: string;
function GetNodeURI: String;
procedure SetNodeURI(const Value: string);
function RPCCall(const AMethod: String;
const AParams: Array of TParamPair): boolean;
property Result: TJSONObject read GetResult;
property ResultStr: String read GetResultStr;
property NodeURI: string read GetNodeURI write SetNodeURI;
end;
TKeyStyle = (ksUnkown, ksEncKey, ksB58Key);
IPascalCoinAccount = interface
['{10B1816D-A796-46E6-94DA-A4C6C2125F82}']
function GetAccount: Int64;
procedure SetAccount(const Value: Int64);
function GetPubKey: String;
procedure SetPubKey(const Value: String);
function GetBalance: Currency;
procedure SetBalance(const Value: Currency);
function GetN_Operation: integer;
procedure SetN_Operation(const Value: integer);
function GetUpdated_b: integer;
procedure SetUpdated_b(const Value: integer);
function GetState: String;
procedure SetState(const Value: String);
function GetLocked_Until_Block: integer;
procedure SetLocked_Until_Block(const Value: integer);
function GetPrice: Currency;
procedure SetPrice(const Value: Currency);
function GetSeller_Account: integer;
procedure SetSeller_Account(const Value: integer);
function GetPrivate_Sale: boolean;
procedure SetPrivate_Sale(const Value: boolean);
function GetNew_Enc_PubKey: String;
procedure SetNew_Enc_PubKey(const Value: String);
function GetName: String;
procedure SetName(const Value: String);
function GetAccount_Type: integer;
procedure SetAccount_Type(const Value: integer);
function SameAs(AAccount: IPascalCoinAccount): Boolean;
procedure Assign(AAccount: IPascalCoinAccount);
/// <summary>
/// Account Number (PASA)
/// </summary>
property account: Int64 read GetAccount write SetAccount;
/// <summary>
/// HEXASTRING - Encoded public key value (See decodepubkey)
/// </summary>
property enc_pubkey: String read GetPubKey write SetPubKey;
/// <summary>
/// Account Balance
/// </summary>
property balance: Currency read GetBalance write SetBalance;
/// <summary>
/// Operations made by this account (Note: When an account receives a
/// transaction, n_operation is not changed)
/// </summary>
property n_operation: integer read GetN_Operation write SetN_Operation;
/// <summary>
/// Last block that updated this account. If equal to blockchain blocks
/// count it means that it has pending operations to be included to the
/// blockchain.
/// </summary>
property updated_b: integer read GetUpdated_b write SetUpdated_b;
/// <summary>
/// Values can be normal or listed. When listed then account is for sale
/// </summary>
property state: String read GetState write SetState;
/// <summary>
/// Until what block this account is locked. Only set if state is listed
/// </summary>
property locked_until_block: integer read GetLocked_Until_Block
write SetLocked_Until_Block;
/// <summary>
/// Price of account. Only set if state is listed
/// </summary>
property price: Currency read GetPrice write SetPrice;
/// <summary>
/// Seller's account number. Only set if state is listed
/// </summary>
property seller_account: integer read GetSeller_Account
write SetSeller_Account;
/// <summary>
/// Whether sale is private. Only set if state is listed
/// </summary>
property private_sale: boolean read GetPrivate_Sale write SetPrivate_Sale;
/// <summary>
/// HEXSTRING - Private buyers public key. Only set if state is listed and
/// private_sale is true
/// </summary>
property new_enc_pubkey: HexStr read GetNew_Enc_PubKey
write SetNew_Enc_PubKey;
/// <summary>
/// Public name of account. Follows PascalCoin64 Encoding. Min Length = 3;
/// Max Length = 64
/// </summary>
property name: String read GetName write SetName;
/// <summary>
/// Type of account. Valid values range from 0..65535
/// </summary>
property account_type: integer read GetAccount_Type write SetAccount_Type;
end;
IPascalCoinAccounts = interface
['{4C039C2C-4BED-4002-9EA2-7F16843A6860}']
function GetAccount(const Index: integer): IPascalCoinAccount;
function Count: integer;
procedure Clear;
function AddAccount(Value: IPascalCoinAccount): integer;
// procedure AddAccounts(Value: IPascalCoinAccounts);
function FindAccount(const Value: integer): IPascalCoinAccount; overload;
function FindAccount(const Value: String): IPascalCoinAccount; overload;
property account[const Index: integer]: IPascalCoinAccount
read GetAccount; default;
end;
IPascalNetStats = interface
['{0F8214FA-D42F-44A7-9B5B-4D6B3285E860}']
function GetActive: integer;
procedure SetActive(const Value: integer);
function GetClients: integer;
procedure SetClients(const Value: integer);
function GetServers: integer;
procedure SetServers(const Value: integer);
function GetServers_t: integer;
procedure SetServers_t(const Value: integer);
function GetTotal: integer;
procedure SetTotal(const Value: integer);
function GetTClients: integer;
procedure SetTClients(const Value: integer);
function GetTServers: integer;
procedure SetTServers(const Value: integer);
function GetBReceived: integer;
procedure SetBReceived(const Value: integer);
function GetBSend: integer;
procedure SetBSend(const Value: integer);
property active: integer read GetActive write SetActive;
property clients: integer read GetClients write SetClients;
property servers: integer read GetServers write SetServers;
property servers_t: integer read GetServers_t write SetServers_t;
property total: integer read GetTotal write SetTotal;
property tclients: integer read GetTClients write SetTClients;
property tservers: integer read GetTServers write SetTServers;
property breceived: integer read GetBReceived write SetBReceived;
property bsend: integer read GetBSend write SetBSend;
end;
IPascalCoinServer = interface
['{E9878551-ADDF-4D22-93A5-3832588ACC45}']
function GetIP: String;
procedure SetIP(const Value: String);
function GetPort: integer;
procedure SetPort(const Value: integer);
function GetLastCon: integer;
procedure SetLastCon(const Value: integer);
function GetAttempts: integer;
procedure SetAttempts(const Value: integer);
function GetLastConAsDateTime: TDateTime;
procedure SetLastConAsDateTime(const Value: TDateTime);
property ip: String read GetIP write SetIP;
property port: integer read GetPort write SetPort;
property lastcon: integer read GetLastCon write SetLastCon;
property LastConAsDateTime: TDateTime read GetLastConAsDateTime
write SetLastConAsDateTime;
property attempts: integer read GetAttempts write SetAttempts;
end;
IPascalCoinNetProtocol = interface
['{DBAAA45D-5AC1-4805-9FDB-5A6B66B193DC}']
function GetVer: integer;
procedure SetVer(const Value: integer);
function GetVer_A: integer;
procedure SetVer_A(const Value: integer);
property ver: integer read GetVer write SetVer; // Net protocol version
property ver_a: integer read GetVer_A write SetVer_A;
// Net protocol available
end;
IPascalCoinNodeStatus = interface
['{9CDDF2CB-3064-4CD6-859A-9E11348FF621}']
function GetReady: boolean;
procedure SetReady(Const Value: boolean);
function GetReady_S: String;
procedure SetReady_S(Const Value: String);
function GetStatus_S: String;
procedure SetStatus_S(Const Value: String);
function GetPort: integer;
procedure SetPort(Const Value: integer);
function GetLocked: boolean;
procedure SetLocked(Const Value: boolean);
function GetTimeStamp: integer;
procedure SetTimeStamp(Const Value: integer);
function GetVersion: String;
procedure SetVersion(Const Value: String);
function GetNetProtocol: IPascalCoinNetProtocol;
function GetBlocks: integer;
procedure SetBlocks(Const Value: integer);
function GetNetStats: IPascalNetStats;
function GetNodeServers: IPascalCoinList<IPascalCoinServer>;
function GetSBH: String;
procedure SetSBH(const Value: String);
function GetPOW: String;
procedure SetPOW(const Value: String);
function GetOpenSSL: String;
procedure SetOpenSSL(const Value: String);
function GetTimeStampAsDateTime: TDateTime;
procedure SetTimeStampAsDateTime(const Value: TDateTime);
property ready: boolean read GetReady write SetReady;
// Must be true, otherwise Node is not ready to execute operations
property ready_s: String read GetReady_S write SetReady_S;
// Human readable information about ready or not
property status_s: String read GetStatus_S write SetStatus_S;
// Human readable information about node status... Running, downloading blockchain, discovering servers...
property port: integer read GetPort write SetPort; // Server port
property locked: boolean read GetLocked write SetLocked;
// True when this wallet is locked, false otherwise
property timestamp: integer read GetTimeStamp write SetTimeStamp;
// Timestamp of the Node
property TimeStampAsDateTime: TDateTime read GetTimeStampAsDateTime
write SetTimeStampAsDateTime;
property version: String read GetVersion write SetVersion; // Server version
property netprotocol: IPascalCoinNetProtocol read GetNetProtocol;
property blocks: integer read GetBlocks write SetBlocks;
// Blockchain blocks
property netstats: IPascalNetStats read GetNetStats;
// -JSON Object with net information
property nodeservers: IPascalCoinList<IPascalCoinServer>
read GetNodeServers; // JSON Array with servers candidates
property sbh: string read GetSBH write SetSBH;
property pow: string read GetPOW write SetPOW;
property openssl: string read GetOpenSSL write SetOpenSSL;
end;
IPascalCoinBlock = interface
['{9BAA406C-BC52-4DB6-987D-BD458C0766E5}']
function GetBlock: integer;
function GetEnc_PubKey: String;
function GetFee: Currency;
function GetHashRateKHS: integer;
function GetMaturation: integer;
function GetNonce: integer;
function GetOperations: integer;
function GetOPH: String;
function GetPayload: String;
function GetPOW: String;
function GetReward: Currency;
function GetSBH: String;
function GetTarget: integer;
function GetTimeStamp: integer;
function GetVer: integer;
function GetVer_A: integer;
procedure SetBlock(const Value: integer);
procedure SetEnc_PubKey(const Value: String);
procedure SetFee(const Value: Currency);
procedure SetHashRateKHS(const Value: integer);
procedure SetMaturation(const Value: integer);
procedure SetNonce(const Value: integer);
procedure SetOperations(const Value: integer);
procedure SetOPH(const Value: String);
procedure SetPayload(const Value: String);
procedure SetPOW(const Value: String);
procedure SetReward(const Value: Currency);
procedure SetSBH(const Value: String);
procedure SetTarget(const Value: integer);
procedure SetTimeStamp(const Value: integer);
procedure SetVer(const Value: integer);
procedure SetVer_A(const Value: integer);
function GetDelphiTimeStamp: TDateTime;
procedure SetDelphiTimeStamp(const Value: TDateTime);
property block: integer read GetBlock write SetBlock; // Block number
property enc_pubkey: String read GetEnc_PubKey write SetEnc_PubKey;
// Encoded public key value used to init 5 created accounts of this block (See decodepubkey )
property reward: Currency read GetReward write SetReward;
// Reward of first account's block
property fee: Currency read GetFee write SetFee;
// Fee obtained by operations
property ver: integer read GetVer write SetVer; // Pascal Coin protocol used
property ver_a: integer read GetVer_A write SetVer_A;
// Pascal Coin protocol available by the miner
property timestamp: integer read GetTimeStamp write SetTimeStamp;
// Unix timestamp
property target: integer read GetTarget write SetTarget; // Target used
property nonce: integer read GetNonce write SetNonce; // Nonce used
property payload: String read GetPayload write SetPayload;
// Miner's payload
property sbh: String read GetSBH write SetSBH; // SafeBox Hash
property oph: String read GetOPH write SetOPH; // Operations hash
property pow: String read GetPOW write SetPOW; // Proof of work
property operations: integer read GetOperations write SetOperations;
// Number of operations included in this block
property hashratekhs: integer read GetHashRateKHS write SetHashRateKHS;
// Estimated network hashrate calculated by previous 50 blocks average
property maturation: integer read GetMaturation write SetMaturation;
// Number of blocks in the blockchain higher than this
property DelphiTimeStamp: TDateTime Read GetDelphiTimeStamp
write SetDelphiTimeStamp;
end;
/// <summary>
/// straight integer mapping from the returned opType value
/// </summary>
TOperationType = (
/// <summary>
/// 0 - Blockchain Reward
/// </summary>
BlockchainReward,
/// <summary>
/// 1 = Transaction
/// </summary>
Transaction,
/// <summary>
/// 2 = Change Key
/// </summary>
ChangeKey,
/// <summary>
/// 3 = Recover Funds (lost keys)
/// </summary>
RecoverFunds, // (lost keys)
/// <summary>
/// 4 = List account for sale
/// </summary>
ListAccountForSale,
/// <summary>
/// 5 = Delist account (not for sale)
/// </summary>
DelistAccountForSale, // (not for sale)
/// <summary>
/// 6 = Buy account
/// </summary>
BuyAccount,
/// <summary>
/// 7 = Change Key signed by another account
/// </summary>
ChangeAccountKey, // (signed by another account)
/// <summary>
/// 8 = Change account info
/// </summary>
ChangeAccountInfo,
/// <summary>
/// 9 = Multi operation (introduced on Build 3.0)
/// </summary>
Multioperation);
IPascalCoinSender = interface
['{F66B882F-C16E-4447-B881-CC3CFFABD287}']
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetN_Operation: integer;
procedure SetN_Operation(const Value: integer);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetPayload: HexStr;
procedure SetPayload(const Value: HexStr);
/// <summary>
/// Sending account (PASA)
/// </summary>
property account: Cardinal read GetAccount write SetAccount;
property n_operation: integer read GetN_Operation write SetN_Operation;
/// <summary>
/// In negative value, due it's outgoing from "account"
/// </summary>
property amount: Currency read GetAmount write SetAmount;
property payload: HexStr read GetPayload write SetPayload;
end;
IPascalCoinReceiver = interface
['{3036AE17-52D6-4FF5-9541-E0B211FFE049}']
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetPayload: HexStr;
procedure SetPayload(const Value: HexStr);
/// <summary>
/// Receiving account (PASA)
/// </summary>
property account: Cardinal read GetAccount write SetAccount;
/// <summary>
/// In positive value, due it's incoming from a sender to "account"
/// </summary>
property amount: Currency read GetAmount write SetAmount;
property payload: HexStr read GetPayload write SetPayload;
end;
IPascalCoinChanger = interface
['{860CE51D-D0D5-4AF0-9BD3-E2858BF1C59F}']
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetN_Operation: integer;
procedure SetN_Operation(const Value: integer);
function GetNew_Enc_PubKey: string;
procedure SetNew_Enc_PubKey(const Value: string);
function GetNew_Type: string;
procedure SetNew_Type(const Value: string);
function GetSeller_Account: Cardinal;
procedure SetSeller_Account(const Value: Cardinal);
function GetAccount_price: Currency;
procedure SetAccount_price(const Value: Currency);
function GetLocked_Until_Block: UInt64;
procedure SetLocked_Until_Block(const Value: UInt64);
function GetFee: Currency;
procedure SetFee(const Value: Currency);
/// <summary>
/// changing Account
/// </summary>
property account: Cardinal read GetAccount write SetAccount;
property n_operation: integer read GetN_Operation write SetN_Operation;
/// <summary>
/// If public key is changed or when is listed for a private sale <br />
/// property new_name: If name is changed
/// </summary>
property new_enc_pubkey: string read GetNew_Enc_PubKey
write SetNew_Enc_PubKey;
/// <summary>
/// if type is changed
/// </summary>
property new_type: string read GetNew_Type write SetNew_Type;
/// <summary>
/// If is listed for sale (public or private) will show seller account
/// </summary>
property seller_account: Cardinal read GetSeller_Account
write SetSeller_Account;
/// <summary>
/// If is listed for sale (public or private) will show account price
/// </summary>
property account_price: Currency read GetAccount_price
write SetAccount_price;
/// <summary>
/// If is listed for private sale will show block locked
/// </summary>
property locked_until_block: UInt64 read GetLocked_Until_Block
write SetLocked_Until_Block;
/// <summary>
/// In negative value, due it's outgoing from "account"
/// </summary>
property fee: Currency read GetFee write SetFee;
end;
IPascalCoinOperation = interface
['{0C059E68-CE57-4F06-9411-AAD2382246DE}']
function GetValid: boolean;
procedure SetValid(const Value: boolean);
function GetErrors: string;
procedure SetErrors(const Value: string);
function GetBlock: UInt64;
procedure SetBlock(const Value: UInt64);
function GetTime: integer;
procedure SetTime(const Value: integer);
function GetOpblock: integer;
procedure SetOpblock(const Value: integer);
function GetMaturation: integer;
procedure SetMaturation(const Value: integer);
function GetOptype: integer;
procedure SetOptype(const Value: integer);
function GetOperationType: TOperationType;
procedure SetOperationType(const Value: TOperationType);
function GetOptxt: string;
procedure SetOptxt(const Value: string);
function GetAccount: Cardinal;
procedure SetAccount(const Value: Cardinal);
function GetAmount: Currency;
procedure SetAmount(const Value: Currency);
function GetFee: Currency;
procedure SetFee(const Value: Currency);
function GetBalance: Currency;
procedure SetBalance(const Value: Currency);
function GetSender_account: Cardinal;
procedure SetSender_Account(const Value: Cardinal);
function GetDest_account: Cardinal;
procedure SetDest_Account(const Value: Cardinal);
function GetEnc_PubKey: HexStr;
procedure SetEnc_PubKey(const Value: HexStr);
function GetOphash: HexStr;
procedure SetOphash(const Value: HexStr);
function GetOld_ophash: HexStr;
procedure SetOld_ophash(const Value: HexStr);
function GetSubtype: string;
procedure SetSubtype(const Value: string);
function GetSigner_account: Cardinal;
procedure SetSigner_account(const Value: Cardinal);
function GetN_Operation: integer;
procedure SetN_Operation(const Value: integer);
function GetPayload: HexStr;
procedure SetPayload(const Value: HexStr);
function GetSenders: IPascalCoinList<IPascalCoinSender>;
procedure SetSenders(Value: IPascalCoinList<IPascalCoinSender>);
function GetReceivers: IPascalCoinList<IPascalCoinReceiver>;
procedure SetReceivers(Value: IPascalCoinList<IPascalCoinReceiver>);
function GetChangers: IPascalCoinList<IPascalCoinChanger>;
procedure SetChangers(Value: IPascalCoinList<IPascalCoinChanger>);
/// <summary>
/// (optional) - If operation is invalid, value=false
/// </summary>
property valid: boolean read GetValid write SetValid;
/// <summary>
/// (optional) - If operation is invalid, an error description
/// </summary>
property errors: String read GetErrors write SetErrors;
/// <summary>
/// Block number (only when valid)
/// </summary>
property block: UInt64 read GetBlock write SetBlock;
/// <summary>
/// Block timestamp (only when valid)
/// </summary>
property time: integer read GetTime write SetTime;
/// <summary>
/// Operation index inside a block (0..operations-1). Note: If opblock=-1
/// means that is a blockchain reward (only when valid)
/// </summary>
property opblock: integer read GetOpblock write SetOpblock;
/// <summary>
/// Return null when operation is not included on a blockchain yet, 0 means
/// that is included in highest block and so on...
/// </summary>
property maturation: integer read GetMaturation write SetMaturation;
/// <summary>
/// see TOperationType above
/// </summary>
property optype: integer read GetOptype write SetOptype;
/// <summary>
/// converts optype to TOperationType
/// </summary>
property OperationType: TOperationType read GetOperationType
write SetOperationType;
/// <summary>
/// Human readable operation type
/// </summary>
property optxt: String read GetOptxt write SetOptxt;
/// <summary>
/// Account affected by this operation. Note: A transaction has 2 affected
/// accounts.
/// </summary>
property account: Cardinal read GetAccount write SetAccount;
/// <summary>
/// Amount of coins transferred from sender_account to dest_account (Only
/// apply when optype=1)
/// </summary>
property amount: Currency read GetAmount write SetAmount;
/// <summary>
/// Fee of this operation
/// </summary>
property fee: Currency read GetFee write SetFee;
/// <summary>
/// Balance of account after this block is introduced in the Blockchain.
/// Note: balance is a calculation based on current safebox account balance
/// and previous operations, it's only returned on pending operations and
/// account operations <br />
/// </summary>
property balance: Currency read GetBalance write SetBalance;
/// <summary>
/// Sender account in a transaction (only when optype = 1) <b>DEPRECATED</b>,
/// use senders array instead
/// </summary>
property sender_account: Cardinal read GetSender_account
write SetSender_Account;
/// <summary>
/// Destination account in a transaction (only when optype = 1) <b>DEPRECATED</b>
/// , use receivers array instead
/// </summary>
property dest_account: Cardinal read GetDest_account write SetDest_Account;
/// <summary>
/// HEXASTRING - Encoded public key in a change key operation (only when
/// optype = 2). See decodepubkey <b>DEPRECATED</b>, use changers array
/// instead. See commented out enc_pubkey below. A second definition for use
/// with other operation types: Will return both change key and the private
/// sale public key value <b>DEPRECATED</b><br />
/// </summary>
property enc_pubkey: HexStr read GetEnc_PubKey write SetEnc_PubKey;
/// <summary>
/// HEXASTRING - Operation hash used to find this operation in the blockchain
/// </summary>
property ophash: HexStr read GetOphash write SetOphash;
/// <summary>
/// /// <summary> <br />/// HEXSTRING - Operation hash as calculated
/// prior to V2. Will only be <br />/// populated for blocks prior to V2
/// activation. <b>DEPRECATED</b> <br />/// </summary>
/// </summary>
property old_ophash: HexStr read GetOld_ophash write SetOld_ophash;
/// <summary>
/// Associated with optype param, can be used to discriminate from the point
/// of view of operation (sender/receiver/buyer/seller ...)
/// </summary>
property subtype: String read GetSubtype write SetSubtype;
/// <summary>
/// Will return the account that signed (and payed fee) for this operation.
/// Not used when is a Multioperation (optype = 9)
/// </summary>
property signer_account: Cardinal read GetSigner_account
write SetSigner_account;
property n_operation: integer read GetN_Operation write SetN_Operation;
property payload: HexStr read GetPayload write SetPayload;
// property enc_pubkey: HexStr HEXSTRING - Will return both change key and the private sale public key value DEPRECATED, use changers array instead
/// <summary>
/// ARRAY of objects with senders, for example in a transaction (optype = 1)
/// or multioperation senders (optype = 9)
/// </summary>
property senders: IPascalCoinList<IPascalCoinSender> read GetSenders
write SetSenders;
/// <summary>
/// ARRAY of objects - When is a transaction or multioperation, this array
/// contains each receiver
/// </summary>
property receivers: IPascalCoinList<IPascalCoinReceiver> read GetReceivers
write SetReceivers;
/// <summary>
/// ARRAY of objects - When accounts changed state
/// </summary>
property changers: IPascalCoinList<IPascalCoinChanger> read GetChangers
write SetChangers;
end;
IPascalCoinAPI = interface
['{310A40ED-F917-4075-B495-5E4906C4D8EB}']
function GetNodeURI: String;
procedure SetNodeURI(const Value: string);
function GetCurrentNodeStatus: IPascalCoinNodeStatus;
function GetNodeAvailability: TNodeAvailability;
function GetIsTestNet: Boolean;
function GetLastError: String;
function GetJSONResult: TJSONValue;
function GetJSONResultStr: string;
function URI(const Value: string): IPascalCoinAPI;
function GetAccount(const AAccountNumber: Cardinal): IPascalCoinAccount;
function getwalletaccounts(const APublicKey: String;
const AKeyStyle: TKeyStyle; const AMaxCount: integer = -1)
: IPascalCoinAccounts;
function getwalletaccountscount(const APublicKey: String;
const AKeyStyle: TKeyStyle): integer;
function GetBlock(const BlockNumber: integer): IPascalCoinBlock;
/// <summary>
/// Get operations made to an account <br />
/// </summary>
/// <param name="AAcoount">
/// Account number (0..accounts count-1)
/// </param>
/// <param name="ADepth">
/// Optional, default value 100 Depth to search on blocks where this
/// account has been affected. Allowed to use deep as a param name too.
/// </param>
/// <param name="AStart">
/// Optional, default = 0. If provided, will start at this position (index
/// starts at position 0). If start is -1, then will include pending
/// operations, otherwise only operations included on the blockchain
/// </param>
/// <param name="AMax">
/// Optional, default = 100. If provided, will return max registers. If not
/// provided, max=100 by default
/// </param>
function getaccountoperations(const AAccount: Cardinal;
const ADepth: integer = 100; const AStart: integer = 0;
const AMax: integer = 100): IPascalCoinList<IPascalCoinOperation>;
function NodeStatus: IPascalCoinNodeStatus;
function executeoperation(const RawOperation: string): IPascalCoinOperation;
/// <summary>
/// Encrypt a text "payload" using "payload_method" <br /><br /><br /><br />
/// </summary>
/// <param name="APayload">
/// HEXASTRING - Text to encrypt in hexadecimal format
/// </param>
/// <param name="AKey">
/// enc_pubkey : HEXASTRING <br />or <br />b58_pubkey : String
/// </param>
/// <param name="AKeyStyle">
/// ksEncKey or ksB58Key
/// </param>
/// <returns>
/// Returns a HEXASTRING with encrypted payload
/// </returns>
function payloadEncryptWithPublicKey(const APayload: string;
const AKey: string; const AKeyStyle: TKeyStyle): string;
// function getwalletcoins(const APublicKey: String): Currency;
// getblocks - Get a list of blocks (last n blocks, or from start to end)
// getblockcount - Get blockchain high in this node
// getblockoperation - Get an operation of the block information
// getblockoperations - Get all operations of specified block
// getpendings - Get pendings operations to be included in the blockchain
// getpendingscount - Returns node pending buffer count ( New on Build 3.0 )
// findoperation - Find
property JSONResult: TJSONValue read GetJSONResult;
property JSONResultStr: string read GetJSONResultStr;
property NodeURI: string read GetNodeURI write SetNodeURI;
property CurrenNodeStatus: IPascalCoinNodeStatus read GetCurrentNodeStatus;
property NodeAvailability: TNodeAvailability read GetNodeAvailability;
property IsTestNet: Boolean read GetIsTestNet;
property LastError: String read GetLastError;
end;
implementation
end.
|
unit SoccerTests.VotingRulesDictTests;
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections,
Soccer.Voting.Preferences,
Soccer.Voting.RulesDict,
Soccer.Voting.AbstractRule,
DUnitX.TestFramework;
type
[TestFixture]
TVotingRulesDictTest = class(TObject)
public
[SetupFixture]
procedure CallGlobalDict;
[Test]
procedure VotingRulesDictTest;
[Test]
procedure GlobalDictTest;
end;
TFakeVotingRule = class(TInterfacedObject, ISoccerVotingRule)
public
function GetName: string;
function ExecuteOn(AProfile: TSoccerVotingVotersPreferences;
out Winners: System.Generics.Collections.TList<string>): Boolean;
end;
implementation
{ TVotingRulesDictTest }
procedure TVotingRulesDictTest.CallGlobalDict;
begin
GlobalVotingRulesDict;
end;
procedure TVotingRulesDictTest.GlobalDictTest;
begin
Assert.IsTrue(GlobalVotingRulesDict.Rules.Count = 5);
end;
procedure TVotingRulesDictTest.VotingRulesDictTest;
var
LDict: TSoccerVotingRulesDict;
LRule: ISoccerVotingRule;
begin
LDict := TSoccerVotingRulesDict.Create;
LRule := TFakeVotingRule.Create;
LDict.Rules.Add(LRule.GetName, LRule);
Assert.IsTrue(LDict.Rules.Count = 1);
FreeAndNil(LDict);
end;
{ TFakeVotingRule }
function TFakeVotingRule.ExecuteOn(AProfile: TSoccerVotingVotersPreferences;
out Winners: System.Generics.Collections.TList<string>): Boolean;
begin
Result := false;
end;
function TFakeVotingRule.GetName: string;
begin
Result := 'lollingrulefake';
end;
initialization
TDUnitX.RegisterTestFixture(TVotingRulesDictTest);
end.
|
{*******************************************************}
{ }
{ DelphiWebMVC }
{ }
{ °æÈ¨ËùÓÐ (C) 2019 ËÕÐËÓ(PRSoft) }
{ }
{*******************************************************}
unit Roule;
interface
uses
System.Classes, RouleItem, System.StrUtils, System.Generics.Collections,
System.SysUtils;
type
TRoule = class
private
list: TObjectList<TRouleItem>;
public
procedure SetRoule(name: string; ACtion: TClass; path: string = ''; isInterceptor: Boolean = True);
function GetRoule(url: string; var roule: string; var method: string): TRouleItem;
function GetItem(roule: string): TRouleItem;
constructor Create(); virtual;
destructor Destroy; override;
end;
implementation
uses
uConfig;
{ TRoule }
constructor TRoule.Create;
begin
list := TObjectList<TRouleItem>.Create;
end;
destructor TRoule.Destroy;
begin
list.Clear;
list.Free;
end;
function TRoule.GetItem(roule: string): TRouleItem;
var
I: Integer;
item: TRouleItem;
begin
Result := nil;
for I := 0 to list.Count - 1 do
begin
item := list.Items[I];
if UpperCase(item.Name) = UpperCase(roule) then
begin
Result := item;
break;
end;
end;
end;
function TRoule.GetRoule(url: string; var roule: string; var method: string): TRouleItem;
var
I: Integer;
item: TRouleItem;
url1, url2: string;
tmp: TStringList;
tmp1: string;
begin
Result := nil;
url1 := '';
url2 := '';
method := '';
tmp := TStringList.Create;
try
url := Trim(url);
if url[url.Length] = '/' then
begin
tmp1 := '/';
end;
tmp.Delimiter := '/';
tmp.DelimitedText := url;
for I := 0 to tmp.Count - 1 do
begin
if tmp.Strings[I] <> '' then
begin
url1 := url1 + '/' + tmp.Strings[I];
if (tmp.Count >= 2) then
begin
if I <= tmp.Count - 2 then
begin
url2 := url2 + '/' + tmp.Strings[I];
end;
end;
end;
end;
url1 := url1 + tmp1;
url2 := url2 + '/';
if url1 = '' then
url1 := '/';
if url2 = '' then
url2 := '/';
item := GetItem(url1);
if (item <> nil) then
begin
roule := url1;
method := 'index';
end
else
begin
item := GetItem(url2);
if item <> nil then
begin
roule := url2;
method := tmp.Strings[tmp.Count - 1];
end;
end;
Result := item;
finally
tmp.Clear;
tmp.Free;
end;
end;
procedure TRoule.SetRoule(name: string; ACtion: TClass; path: string; isInterceptor: Boolean);
var
item: TRouleItem;
begin
if name.Trim <> '' then
name := '/' + name + '/'
else
name := '/';
if __APP__.Trim <> '' then
begin
name := '/' + __APP__ + name;
end;
item := TRouleItem.Create;
item.name := name;
item.Interceptor := isInterceptor;
item.ACtion := ACtion;
item.path := path;
list.Add(item);
end;
end.
|
{* ------------------------------------------------------------------------ *
* Command Parttern ♥ TCommandAction = command invoker
* ------------------------------------------------------------------------ *}
unit Pattern.CommandAction;
interface
uses
System.Classes,
System.SysUtils,
System.Actions,
Vcl.ActnList,
Pattern.Command;
type
TCommandAction = class(TAction)
private const
Version = '1.0';
private
fCommand: TCommand;
fOnUpdateProc: TProc<TCommandAction>;
fOnAfterProc: TProc<TCommandAction>;
fDisableDuringExecution: boolean;
fActionList: TActionList;
procedure OnExecuteEvent(Sender: TObject);
procedure OnUpdateEvent(Sender: TObject);
procedure DoExecuteAction(Sender: TObject);
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
function WithCaption(const aCaption: string): TCommandAction;
function WithCommand(aCommand: TCommand): TCommandAction;
function WithShortCut(aShorcut: TShortCut): TCommandAction;
function WithEventOnUpdate(AUpdateProc: TProc<TCommandAction>)
: TCommandAction;
function WitEventAfterExecution(aAfterProc: TProc<TCommandAction>)
: TCommandAction;
function WithInjections(const Injections: array of const): TCommandAction;
property Command: TCommand read fCommand write fCommand;
property DisableDuringExecution: boolean read fDisableDuringExecution
write fDisableDuringExecution;
end;
implementation
constructor TCommandAction.Create(aOwner: TComponent);
begin
inherited;
DisableDuringExecution := False;
fActionList := nil;
fCommand := nil;
fOnUpdateProc := nil;
fOnAfterProc := nil;
Self.OnExecute := OnExecuteEvent;
end;
destructor TCommandAction.Destroy;
begin
inherited;
end;
procedure TCommandAction.DoExecuteAction(Sender: TObject);
begin
fCommand.Execute;
if Assigned(fOnAfterProc) then
fOnAfterProc(Self)
end;
function TCommandAction.WithInjections(const Injections: array of const)
: TCommandAction;
begin
System.Assert(fCommand <> nil,
'Command have to be created and provided before injection');
fCommand.WithInjections(Injections);
Result := Self;
end;
procedure TCommandAction.OnExecuteEvent(Sender: TObject);
begin
System.Assert(fCommand <> nil);
if DisableDuringExecution then
begin
try
Self.Enabled := False;
DoExecuteAction(Sender);
finally
Self.Enabled := True;
end;
end
else
DoExecuteAction(Sender);
end;
procedure TCommandAction.OnUpdateEvent(Sender: TObject);
begin
if Assigned(fOnUpdateProc) then
fOnUpdateProc(Self);
end;
function TCommandAction.WithCaption(const aCaption: string): TCommandAction;
begin
Caption := aCaption;
Result := Self;
end;
function TCommandAction.WithCommand(aCommand: TCommand): TCommandAction;
begin
fCommand := aCommand;
Result := Self;
end;
function TCommandAction.WitEventAfterExecution
(aAfterProc: TProc<TCommandAction>): TCommandAction;
begin
fOnAfterProc := aAfterProc;
Result := Self;
end;
function TCommandAction.WithEventOnUpdate(AUpdateProc: TProc<TCommandAction>)
: TCommandAction;
begin
fOnUpdateProc := AUpdateProc;
Self.OnUpdate := OnUpdateEvent;
Result := Self;
end;
function TCommandAction.WithShortCut(aShorcut: TShortCut): TCommandAction;
begin
// ------------------------------------------------------------------
// Too support shortcuts action requires TActionList assigned
// ---
// this code is constructing a new ActionList only once when a new
// shortcut is assigned to this action (deleyed construction)
// ---
// Memory of fActionList is not released by Free but managed by Owner
// ------------------------------------------------------------------
if (Owner <> nil) and (Self.ActionList = nil) and (fActionList = nil) then
begin
fActionList := TActionList.Create(Owner);
Self.ActionList := fActionList;
end;
Self.ShortCut := aShorcut;
Result := Self;
end;
end.
|
unit NtUtils.Exceptions;
interface
uses
Winapi.WinNt, Ntapi.ntdef, Ntapi.ntseapi, System.SysUtils, System.TypInfo,
DelphiUtils.Strings, DelphiUtils.AutoObject;
const
BUFFER_LIMIT = 1024 * 1024 * 256; // 256 MB
type
TMemory = DelphiUtils.AutoObject.TMemory;
IMemory = DelphiUtils.AutoObject.IMemory;
TAutoMemory = DelphiUtils.AutoObject.TAutoMemory;
IHandle = DelphiUtils.AutoObject.IHandle;
TLastCallType = (lcOtherCall, lcOpenCall, lcQuerySetCall);
TExpectedAccess = record
AccessMask: TAccessMask;
AccessMaskType: PAccessMaskType;
end;
TLastCallInfo = record
ExpectedPrivilege: TSeWellKnownPrivilege;
ExpectedAccess: array of TExpectedAccess;
procedure Expects(Mask: TAccessMask; MaskType: PAccessMaskType);
case CallType: TLastCallType of
lcOpenCall:
(AccessMask: TAccessMask; AccessMaskType: PAccessMaskType);
lcQuerySetCall:
(InfoClass: Cardinal; InfoClassType: PTypeInfo);
end;
/// <summary>
/// An enhanced NTSTATUS that stores the location of the failure.
/// </summary>
TNtxStatus = record
private
FLocation: String;
function GetWinError: Cardinal;
procedure SetWinError(Value: Cardinal); inline;
procedure FromLastWin32(RetValue: Boolean);
procedure SetLocation(Value: String); inline;
procedure SetHResult(const Value: HRESULT); inline;
public
Status: NTSTATUS;
LastCall: TLastCallInfo;
function IsSuccess: Boolean; inline;
property WinError: Cardinal read GetWinError write SetWinError;
property HResult: HRESULT write SetHResult;
property Win32Result: Boolean write FromLastWin32;
procedure RaiseOnError; inline;
procedure ReportOnError;
public
property Location: String read FLocation write SetLocation;
function Matches(Status: NTSTATUS; Location: String): Boolean; inline;
function ToString: String;
function MessageHint: String;
end;
ENtError = class(EOSError)
public
ErrorLocation: string;
LastCall: TLastCallInfo;
function Matches(Location: String; Code: Cardinal): Boolean;
class procedure Report(Status: Cardinal; Location: String);
function ToWinErrorCode: Cardinal;
function ToNtxStarus: TNtxStatus;
constructor Create(Status: NTSTATUS; Location: String); reintroduce;
constructor CreateNtx(const Status: TNtxStatus);
constructor CreateWin32(Win32Error: Cardinal; Location: String;
Dummy: Integer = 0);
constructor CreateLastWin32(Location: String);
end;
TNtxStatusWithValue<TValue> = record
Value: TValue;
Status: TNtxStatus;
function GetValueOrRaise: TValue;
end;
// RtlGetLastNtStatus with extra checks to ensure the result is correct
function RtlxGetLastNtStatus: NTSTATUS;
{ Runtime error-checking procedures that may raise exceptions}
procedure WinCheck(RetVal: LongBool; Where: String);
procedure NtxCheck(Status: NTSTATUS; Where: String);
procedure NtxAssert(Status: NTSTATUS; Where: String);
{ Buffer checking functions that do not raise exceptions}
function WinTryCheckBuffer(BufferSize: Cardinal): Boolean;
function NtxTryCheckBuffer(var Status: NTSTATUS; BufferSize: Cardinal): Boolean;
function NtxExpandStringBuffer(var Status: TNtxStatus;
var Str: UNICODE_STRING; Required: Cardinal = 0): Boolean;
function NtxExpandBuffer(var Status: TNtxStatus; var BufferSize: Cardinal;
Required: Cardinal; AddExtra: Boolean = False) : Boolean;
implementation
uses
Ntapi.ntrtl, Ntapi.ntstatus, Winapi.WinBase, Winapi.WinError,
NtUtils.ErrorMsg;
{ TLastCallInfo }
procedure TLastCallInfo.Expects(Mask: TAccessMask; MaskType: PAccessMaskType);
begin
// Add new access mask
SetLength(ExpectedAccess, Length(ExpectedAccess) + 1);
ExpectedAccess[High(ExpectedAccess)].AccessMask := Mask;
ExpectedAccess[High(ExpectedAccess)].AccessMaskType := MaskType;
end;
{ TNtxStatus }
procedure TNtxStatus.FromLastWin32(RetValue: Boolean);
begin
if RetValue then
Status := STATUS_SUCCESS
else
begin
Status := RtlxGetLastNtStatus;
// Make sure that the code is not successful
if IsSuccess then
Status := STATUS_UNSUCCESSFUL;
end;
end;
function TNtxStatus.GetWinError: Cardinal;
begin
if NT_NTWIN32(Status) then
Result := WIN32_FROM_NTSTATUS(Status)
else
Result := RtlNtStatusToDosErrorNoTeb(Status);
end;
function TNtxStatus.IsSuccess: Boolean;
begin
Result := Integer(Status) >= 0; // inlined NT_SUCCESS from Ntapi.ntdef
end;
function TNtxStatus.Matches(Status: NTSTATUS; Location: String): Boolean;
begin
Result := (Self.Status = Status) and (Self.Location = Location);
end;
function TNtxStatus.MessageHint: String;
begin
Result := NtxFormatErrorMessage(Status);
end;
procedure TNtxStatus.RaiseOnError;
begin
if not IsSuccess then
raise ENtError.CreateNtx(Self);
end;
procedure TNtxStatus.ReportOnError;
begin
if not IsSuccess then
ENtError.Report(Status, Location);
end;
procedure TNtxStatus.SetHResult(const Value: HRESULT);
begin
// Inlined Winapi.WinError.Succeeded
if Value and $80000000 = 0 then
Status := Cardinal(Value) and $7FFFFFFF
else
Status := Cardinal(SEVERITY_ERROR shl NT_SEVERITY_SHIFT) or Cardinal(Value);
end;
procedure TNtxStatus.SetLocation(Value: String);
begin
FLocation := Value;
LastCall.ExpectedAccess := nil; // Free the dynamic array
FillChar(LastCall, SizeOf(LastCall), 0); // Zero all other fields
end;
procedure TNtxStatus.SetWinError(Value: Cardinal);
begin
Status := NTSTATUS_FROM_WIN32(Value);
end;
function TNtxStatus.ToString: String;
begin
Result := Location + ': ' + NtxStatusToString(Status);
end;
{ ENtError }
constructor ENtError.Create(Status: NTSTATUS; Location: String);
begin
Message := Location + ' returned ' + NtxStatusToString(Status);
ErrorLocation := Location;
ErrorCode := Status;
end;
constructor ENtError.CreateLastWin32(Location: String);
begin
Create(RtlxGetLastNtStatus, Location);
end;
constructor ENtError.CreateNtx(const Status: TNtxStatus);
begin
Create(Status.Status, Status.Location);
LastCall := Status.LastCall;
end;
constructor ENtError.CreateWin32(Win32Error: Cardinal; Location: String;
Dummy: Integer = 0);
begin
Create(NTSTATUS_FROM_WIN32(Win32Error), Location);
end;
function ENtError.Matches(Location: String; Code: Cardinal): Boolean;
begin
Result := (ErrorCode = Code) and (ErrorLocation = Location);
end;
class procedure ENtError.Report(Status: Cardinal; Location: String);
begin
OutputDebugStringW(PWideChar(Location + ': ' + NtxStatusToString(Status)));
end;
function ENtError.ToNtxStarus: TNtxStatus;
begin
Result.Location := ErrorLocation;
Result.Status := ErrorCode;
Result.LastCall := LastCall;
end;
function ENtError.ToWinErrorCode: Cardinal;
begin
if NT_NTWIN32(ErrorCode) then
Result := WIN32_FROM_NTSTATUS(ErrorCode)
else
Result := RtlNtStatusToDosErrorNoTeb(ErrorCode);
end;
{ TNtxStatusWithValue<TValue> }
function TNtxStatusWithValue<TValue>.GetValueOrRaise: TValue;
begin
Status.RaiseOnError;
Result := Value;
end;
{ Functions }
procedure WinCheck(RetVal: LongBool; Where: String);
begin
if not RetVal then
raise ENtError.CreateLastWin32(Where);
end;
// Note:
// [Error] STATUS_INFO_LENGTH_MISMATCH => ERROR_BAD_LENGTH
// [Error] STATUS_BUFFER_TOO_SMALL => ERROR_INSUFFICIENT_BUFFER
// [Warning] STATUS_BUFFER_OVERFLOW => ERROR_MORE_DATA
function WinTryCheckBuffer(BufferSize: Cardinal): Boolean;
begin
Result := (GetLastError = ERROR_INSUFFICIENT_BUFFER) and (BufferSize > 0) and
(BufferSize <= BUFFER_LIMIT);
if not Result and (BufferSize > BUFFER_LIMIT) then
RtlSetLastWin32ErrorAndNtStatusFromNtStatus(STATUS_IMPLEMENTATION_LIMIT);
end;
procedure NtxCheck(Status: NTSTATUS; Where: String);
begin
if not NT_SUCCESS(Status) then
raise ENtError.Create(Status, Where);
end;
procedure NtxAssert(Status: NTSTATUS; Where: String);
begin
// The same as NtxCheck but for function that are not supposed to fail due
// to the program logic.
if not NT_SUCCESS(Status) then
raise ENtError.Create(Status, Where);
end;
function NtxTryCheckBuffer(var Status: NTSTATUS; BufferSize: Cardinal): Boolean;
begin
Result := (Status = STATUS_INFO_LENGTH_MISMATCH) or
(Status = STATUS_BUFFER_TOO_SMALL);
if BufferSize > BUFFER_LIMIT then
begin
Result := False;
Status := STATUS_IMPLEMENTATION_LIMIT;
end;
end;
function NtxExpandStringBuffer(var Status: TNtxStatus;
var Str: UNICODE_STRING; Required: Cardinal): Boolean;
begin
// True means continue; False means break from the loop
Result := False;
case Status.Status of
STATUS_INFO_LENGTH_MISMATCH, STATUS_BUFFER_TOO_SMALL,
STATUS_BUFFER_OVERFLOW:
begin
// There are two types of UNICODE_STRING querying functions.
// Both read buffer size from Str.MaximumLength, although some
// return the required buffer size in a special parameter,
// and some write it to Str.Length.
if Required = 0 then
begin
// No special parameter
if Str.Length <= Str.MaximumLength then
Exit(False); // Always grow
// Include terminating #0
Str.MaximumLength := Str.Length + SizeOf(WideChar);
end
else
begin
if (Required <= Str.MaximumLength) or (Required > High(Word)) then
Exit(False); // Always grow, but without owerflows
Str.MaximumLength := Word(Required)
end;
Result := True;
end;
end;
end;
function NtxExpandBuffer(var Status: TNtxStatus; var BufferSize: Cardinal;
Required: Cardinal; AddExtra: Boolean) : Boolean;
begin
// True means continue; False means break from the loop
Result := False;
case Status.Status of
STATUS_INFO_LENGTH_MISMATCH, STATUS_BUFFER_TOO_SMALL,
STATUS_BUFFER_OVERFLOW:
begin
// The buffer should always grow with these error codes
if Required <= BufferSize then
Exit(False);
BufferSize := Required;
if AddExtra then
Inc(BufferSize, BufferSize shr 3); // +12% capacity
// Check for the limitation
if BufferSize > BUFFER_LIMIT then
begin
Status.Location := 'NtxExpandBuffer';
Status.Status := STATUS_IMPLEMENTATION_LIMIT;
Exit(False);
end;
Result := True;
end;
end;
end;
function RtlxGetLastNtStatus: NTSTATUS;
begin
// If the last Win32 error was set using RtlNtStatusToDosError call followed
// by RtlSetLastWin32Error call (aka SetLastError), the LastStatusValue in TEB
// should contain the correct NTSTATUS value. The way to check whether it is
// correct is to convert it to Win32 error and compare with LastErrorValue
// from TEB. If, for some reason, they don't match, return a fake NTSTATUS
// with a Win32 facility.
if RtlNtStatusToDosErrorNoTeb(RtlGetLastNtStatus) = RtlGetLastWin32Error then
Result := RtlGetLastNtStatus
else
case RtlGetLastWin32Error of
// Explicitly convert buffer-related errors
ERROR_INSUFFICIENT_BUFFER: Result := STATUS_BUFFER_TOO_SMALL;
ERROR_MORE_DATA: Result := STATUS_BUFFER_OVERFLOW;
ERROR_BAD_LENGTH: Result := STATUS_INFO_LENGTH_MISMATCH;
// After converting, ERROR_SUCCESS becomes unsuccessful, fix it
ERROR_SUCCESS: Result := STATUS_SUCCESS;
// Common errors which we might want to compare
ERROR_ACCESS_DENIED: Result := STATUS_ACCESS_DENIED;
ERROR_PRIVILEGE_NOT_HELD: Result := STATUS_PRIVILEGE_NOT_HELD;
else
Result := NTSTATUS_FROM_WIN32(RtlGetLastWin32Error);
end;
end;
end.
|
{ ---------------------------------------------------------------------------- }
{ BulbTracer for MB3D }
{ Copyright (C) 2016-2017 Andreas Maschke }
{ ---------------------------------------------------------------------------- }
unit VertexList;
interface
uses
SysUtils, Classes, Contnrs, VectorMath, SyncObjs, Generics.Collections;
type
TFace = packed record
Vertex1, Vertex2, Vertex3: Integer;
end;
TPFace = ^TFace;
TPSingle = PSingle;
TPS3VectorList = class
private
FVertices: TList;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure AddVertex(const V: TD3Vector); overload;
procedure AddVertex(const VX, VY, VZ: Double); overload;
function GetVertex(const Idx: Integer): TPS3Vector;
procedure MoveVertices(const Src: TPS3VectorList);
procedure DoCenter(const MaxSize: Double);
procedure DoScale(const ScaleX, ScaleY, ScaleZ: Double);
procedure RemoveDuplicates;
property Count: Integer read GetCount;
end;
TPSMI3VectorList = class
private
FVertices: TList;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
class function FloatToSMI(const Value: Double): Smallint;
class function SMIToFloat(const Value: Smallint): Double;
procedure AddVertex(const VX, VY, VZ: Double); overload;
function GetVertex(const Idx: Integer): TPSMI3Vector;
procedure MoveVertices(const Src: TPSMI3VectorList);
property Count: Integer read GetCount;
end;
TPS4VectorList = class
private
FVertices: TList;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure AddVector(const VX, VY, VZ, VW: Double);
function GetVector(const Idx: Integer): TPS4Vector;
property Count: Integer read GetCount;
end;
TVertexNeighboursList = class;
TFaceNeighboursList = class;
TFacesList = class
private
FFaces: TList;
FVertices: TPS3VectorList;
FVertexKeys: TDictionary<string, integer>;
function GetCount: Integer;
function MakeVertexKey(const X, Y, Z: Double): String; overload;
function ValidateFace(const V1, V2, V3: Integer): Boolean;
procedure LaplaceSmooth(const NeighboursList: TVertexNeighboursList; const Strength: Double);
procedure CompressPlanarVertices;
procedure RemoveVertices(const VerticesToRemove: TList; const FaceNeighbours: TFaceNeighboursList);
function CalculateFaceNormals: TPS4VectorList;
function GetVertexCount: Integer;
procedure CleanupRemovedFaces;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
property Vertices: TPS3VectorList read FVertices;
procedure AddFace(const Vertex1, Vertex2, Vertex3: Integer); overload;
procedure AddFace(const Vertex1, Vertex2, Vertex3: TPD3Vector); overload;
function AddVertex(const X, Y, Z: Single): Integer; overload;
function AddVertex(const V: TPS3Vector): Integer; overload;
function AddVertex(const V: TPS3Vector; const Sync: TCriticalSection ): Integer; overload;
function AddVertex(const V: TPD3Vector): Integer; overload;
function GetFace(const Idx: Integer): TPFace;
function GetVertex(const Idx: Integer): TPS3Vector;
procedure MoveFaces(const Src: TFacesList); overload;
procedure MoveFaces(const Src: TFacesList; const Sync: TCriticalSection ); overload;
procedure RemoveDuplicates;
procedure TaubinSmooth(const Lambda, Mu: Double; const Passes: Integer);
procedure CompressFaces(const Passes: Integer);
procedure DoCenter(const MaxSize: Double);
procedure DoScale(const ScaleX, ScaleY, ScaleZ: Double);
procedure RecalcVertexKeys;
procedure AddUnvalidatedVertex(const X, Y, Z: Double);
procedure AddUnvalidatedFace(const Vertex1, Vertex2, Vertex3: Integer);
function CalculateVertexNormals: TPS3VectorList;
class function MergeFacesLists(const FacesListsToMerge: TList; const MultiThreaded: boolean = false): TFacesList;
property Count: Integer read GetCount;
property VertexCount: Integer read GetVertexCount;
end;
TNeighboursList = class
protected
FVertices: TList;
function CreateNeighboursList(const Faces: TFacesList): TList; virtual; abstract;
public
constructor Create(const Faces: TFacesList);
destructor Destroy; override;
function GetNeighbours(const Idx: Integer): TList;
procedure SaveToFile(const Filename: String);
end;
TVertexNeighboursList = class(TNeighboursList)
protected
function CreateNeighboursList(const Faces: TFacesList): TList; override;
end;
TFaceNeighboursList = class(TNeighboursList)
protected
function CreateNeighboursList(const Faces: TFacesList): TList; override;
end;
procedure ShowDebugInfo(const Msg: String; const RefTime: Int64);
implementation
uses
Windows, Math, DateUtils;
{ ----------------------------------- Misc ----------------------------------- }
procedure ShowDebugInfo(const Msg: String; const RefTime: Int64);
var
MillisNow: Int64;
begin
MillisNow := DateUtils.MilliSecondsBetween(Now, 0);
OutputDebugString(PChar(Msg+': '+IntToStr(MillisNow-RefTime)+' ms'))
end;
{ ----------------------------- TPS3VectorList ------------------------------- }
constructor TPS3VectorList.Create;
begin
inherited Create;
FVertices := TList.Create;
end;
destructor TPS3VectorList.Destroy;
begin
Clear;
FVertices.Free;
inherited Destroy;
end;
procedure TPS3VectorList.Clear;
var
I: Integer;
begin
for I := 0 to FVertices.Count -1 do begin
if FVertices[I] <> nil then
FreeMem(FVertices[I]);
end;
FVertices.Clear;
end;
procedure TPS3VectorList.AddVertex(const V: TD3Vector);
var
Vertex: TPS3Vector;
begin
GetMem(Vertex, SizeOf(TS3Vector));
FVertices.Add(Vertex);
Vertex^.X := V.X;
Vertex^.Y := V.Y;
Vertex^.Z := V.Z;
end;
procedure TPS3VectorList.AddVertex(const VX, VY, VZ: Double);
var
Vertex: TPS3Vector;
begin
GetMem(Vertex, SizeOf(TS3Vector));
FVertices.Add(Vertex);
Vertex^.X := VX;
Vertex^.Y := VY;
Vertex^.Z := VZ;
end;
function TPS3VectorList.GetVertex(const Idx: Integer): TPS3Vector;
begin
Result := FVertices[Idx];
end;
function TPS3VectorList.GetCount: Integer;
begin
Result := FVertices.Count;
end;
procedure TPS3VectorList.MoveVertices(const Src: TPS3VectorList);
var
I: Integer;
begin
if Src <> nil then begin
for I := 0 to Src.FVertices.Count - 1 do begin
FVertices.Add(Src.FVertices[I]);
Src.FVertices[I] := nil;
end;
Src.FVertices.Clear;
Src.Clear;
end;
end;
procedure TPS3VectorList.RemoveDuplicates;
var
I: Integer;
Vertex: TPS3Vector;
Key: String;
KeyList: TStringList;
NewList: TList;
function MakeKey(const Vertex: TPS3Vector): String;
begin
with Vertex^ do begin
Result := FloatToStr(X)+'#'+FloatToStr(Y)+'#'+FloatToStr(Z);
end;
end;
begin
KeyList := TStringList.Create;
try
KeyList.Sorted := True;
KeyList.Duplicates := dupIgnore;
NewList := TList.Create;
try
for I := 0 to FVertices.Count - 1 do begin
Vertex := FVertices[I];
Key := MakeKey(Vertex);
if KeyList.IndexOf(Key) < 0 then begin
KeyList.Add(Key);
NewList.Add(Vertex);
end;
end;
{$ifdef DEBUG_MESHEXP}
if FVertices.Count <> NewList.Count then
OutputDebugString(PChar('TVertexList.RemoveDuplicates: '+IntToStr(FVertices.Count)+' -> '+IntToStr(NewList.Count)));
{$endif}
FVertices.Free;
FVertices := NewList;
except
NewList.Free;
raise;
end;
finally
KeyList.Free;
end;
end;
procedure TPS3VectorList.DoScale(const ScaleX, ScaleY, ScaleZ: Double);
var
I: Integer;
Vertex: TPS3Vector;
begin
for I := 0 to FVertices.Count - 1 do begin
Vertex := FVertices[I];
Vertex^.X := ScaleX * Vertex^.X;
Vertex^.Y := ScaleY * Vertex^.Y;
Vertex^.Z := ScaleZ * Vertex^.Z;
end;
end;
procedure TPS3VectorList.DoCenter(const MaxSize: Double);
var
I: Integer;
Vertex: TPS3Vector;
XMin, XMax, YMin, YMax, ZMin, ZMax: Double;
SX, SY, SZ, DX, DY, DZ, SMAX, Scale: Double;
begin
if FVertices.Count > 0 then begin
Vertex := FVertices[0];
XMin := Vertex^.X;
XMax := XMin;
YMin := Vertex^.Y;
YMax := YMin;
ZMin := Vertex^.Z;
ZMax := ZMin;
for I := 1 to FVertices.Count - 1 do begin
Vertex := FVertices[I];
if Vertex^.X < XMin then
XMin := Vertex^.X
else if Vertex^.X > XMax then
XMax := Vertex^.X;
if Vertex^.Y < YMin then
YMin := Vertex^.Y
else if Vertex^.Y > YMax then
YMax := Vertex^.Y;
if Vertex^.Z < ZMin then
ZMin := Vertex^.Z
else if Vertex^.Z > ZMax then
ZMax := Vertex^.Z;
end;
SX := XMax - XMin;
SY := YMax - YMin;
SZ := ZMax - ZMin;
SMAX := Max( Max( SX, SY ), SZ);
Scale := MaxSize / SMAX;
DX := -XMin - SX / 2.0;
DY := -YMin - SY / 2.0;
DZ := -ZMin - SZ / 2.0;
for I := 0 to FVertices.Count - 1 do begin
Vertex := FVertices[I];
Vertex^.X := (Vertex^.X + DX) * Scale;
Vertex^.Y := (Vertex^.Y + DY) * Scale;
Vertex^.Z := (Vertex^.Z + DZ) * Scale;
end;
end;
end;
{ ----------------------------- TPSMI3VectorList ------------------------------- }
constructor TPSMI3VectorList.Create;
begin
inherited Create;
FVertices := TList.Create;
end;
destructor TPSMI3VectorList.Destroy;
begin
Clear;
FVertices.Free;
inherited Destroy;
end;
procedure TPSMI3VectorList.Clear;
var
I: Integer;
begin
for I := 0 to FVertices.Count -1 do begin
if FVertices[I] <> nil then
FreeMem(FVertices[I]);
end;
FVertices.Clear;
end;
class function TPSMI3VectorList.FloatToSMI(const Value: Double): Smallint;
begin
if ( Value < -1.0 ) or ( Value > 1.0 ) then
raise Exception.Create('TPSMI3VectorList.FloatToSMI: Invalid value <' + FloatToStr( Value ) + '>');
Result := Round( 32767 * Value );
end;
class function TPSMI3VectorList.SMIToFloat(const Value: Smallint): Double;
begin
Result := Value / 32767.0;
end;
procedure TPSMI3VectorList.AddVertex(const VX, VY, VZ: Double);
var
Vertex: TPS3Vector;
begin
GetMem(Vertex, SizeOf(TSMI3Vector));
FVertices.Add(Vertex);
Vertex^.X := FloatToSMI( VX );
Vertex^.Y := FloatToSMI( VY );
Vertex^.Z := FloatToSMI( VZ );
end;
function TPSMI3VectorList.GetVertex(const Idx: Integer): TPSMI3Vector;
begin
Result := FVertices[Idx];
end;
function TPSMI3VectorList.GetCount: Integer;
begin
Result := FVertices.Count;
end;
procedure TPSMI3VectorList.MoveVertices(const Src: TPSMI3VectorList);
var
I: Integer;
begin
if Src <> nil then begin
for I := 0 to Src.FVertices.Count - 1 do begin
FVertices.Add(Src.FVertices[I]);
Src.FVertices[I] := nil;
end;
Src.FVertices.Clear;
Src.Clear;
end;
end;
{ ----------------------------- TPS4VectorList ------------------------------- }
constructor TPS4VectorList.Create;
begin
inherited Create;
FVertices := TList.Create;
end;
destructor TPS4VectorList.Destroy;
begin
Clear;
FVertices.Free;
inherited Destroy;
end;
procedure TPS4VectorList.Clear;
var
I: Integer;
begin
for I := 0 to FVertices.Count -1 do begin
if FVertices[I] <> nil then
FreeMem(FVertices[I]);
end;
FVertices.Clear;
end;
procedure TPS4VectorList.AddVector(const VX, VY, VZ, VW: Double);
var
Vertex: TPS4Vector;
begin
GetMem(Vertex, SizeOf(TS4Vector));
FVertices.Add(Vertex);
Vertex^.X := VX;
Vertex^.Y := VY;
Vertex^.Z := VZ;
Vertex^.W := VW;
end;
function TPS4VectorList.GetVector(const Idx: Integer): TPS4Vector;
begin
Result := FVertices[Idx];
end;
function TPS4VectorList.GetCount: Integer;
begin
Result := FVertices.Count;
end;
{ -------------------------------- TFacesList -------------------------------- }
constructor TFacesList.Create;
begin
inherited Create;
FFaces := TList.Create;
FVertices := TPS3VectorList.Create;
FVertexKeys := TDictionary<string,integer>.Create;
end;
destructor TFacesList.Destroy;
begin
Clear;
FFaces.Free;
FVertices.Free;
FVertexKeys.Free;
inherited Destroy;
end;
procedure TFacesList.Clear;
var
I: Integer;
begin
for I := 0 to FFaces.Count - 1 do begin
if FFaces[I] <> nil then
FreeMem(FFaces[I]);
end;
FFaces.Clear;
FVertices.Clear;
FVertexKeys.Clear;
end;
function TFacesList.GetFace(const Idx: Integer): TPFace;
begin
Result := FFaces[Idx];
end;
function TFacesList.GetVertex(const Idx: Integer): TPS3Vector;
begin
Result := FVertices.GetVertex(Idx);
end;
function TFacesList.GetCount: Integer;
begin
Result := FFaces.Count;
end;
function TFacesList.GetVertexCount: Integer;
begin
Result := FVertices.Count;
end;
procedure TFacesList.AddFace(const Vertex1, Vertex2, Vertex3: Integer);
var
Face: TPFace;
begin
if ValidateFace(Vertex1, Vertex2, Vertex3) then begin
GetMem(Face, SizeOf(TFace));
FFaces.Add(Face);
Face^.Vertex1 := Vertex1;
Face^.Vertex2 := Vertex2;
Face^.Vertex3 := Vertex3;
end
end;
procedure TFacesList.AddUnvalidatedFace(const Vertex1, Vertex2, Vertex3: Integer);
var
Face: TPFace;
begin
GetMem(Face, SizeOf(TFace));
FFaces.Add(Face);
Face^.Vertex1 := Vertex1;
Face^.Vertex2 := Vertex2;
Face^.Vertex3 := Vertex3;
end;
procedure TFacesList.AddUnvalidatedVertex(const X, Y, Z: Double);
var
Key: String;
VerticesCount: Integer;
begin
VerticesCount := FVertices.Count;
Key := MakeVertexKey(X, Y, Z);
FVertices.AddVertex(X, Y, Z);
// Unvalidated Vertices have no keys
// FVertexKeys.Add(Key, VerticesCount);
end;
procedure TFacesList.AddFace(const Vertex1, Vertex2, Vertex3: TPD3Vector);
begin
AddFace(AddVertex(Vertex1), AddVertex(Vertex2), AddVertex(Vertex3));
end;
function TFacesList.MakeVertexKey(const X, Y, Z: Double): String;
const
Prec: Double = 10000.0;
begin
// Result := FloatToStr(X)+'#'+FloatToStr(Y)+'#'+FloatToStr(Z);
Result := IntToStr(Round(X*Prec))+'#'+IntToStr(Round(Y*Prec))+'#'+IntToStr(Round(Z*Prec));
end;
procedure TFacesList.RecalcVertexKeys;
var
I: Integer;
Key: String;
V: TPS3Vector;
begin
FVertexKeys.Clear;
for I := 0 to FVertices.Count - 1 do begin
V := FVertices.GetVertex( I );
Key := MakeVertexKey(V^.X, V^.Y, V^.Z);
FVertexKeys.Add(Key, I);
end;
end;
function TFacesList.AddVertex(const X, Y, Z: Single): Integer;
var
Key: String;
begin
Key := MakeVertexKey(X, Y, Z);
if FVertexKeys.ContainsKey( Key ) then begin
Result := FVertexKeys.Items[ Key ];
end
else begin
Result := FVertices.Count;
FVertices.AddVertex(X, Y, Z);
FVertexKeys.Add(Key, Result);
end;
end;
function TFacesList.AddVertex(const V: TPS3Vector): Integer;
var
Key: String;
begin
Key := MakeVertexKey(V^.X, V^.Y, V^.Z);
if FVertexKeys.ContainsKey( Key ) then begin
Result := FVertexKeys.Items[ Key ];
end
else begin
Result := FVertices.Count;
FVertices.AddVertex(V^.X, V^.Y, V^.Z);
FVertexKeys.Add(Key, Result);
end;
end;
function TFacesList.AddVertex(const V: TPS3Vector; const Sync: TCriticalSection ): Integer;
var
Key: String;
begin
Key := MakeVertexKey(V^.X, V^.Y, V^.Z);
Sync.Acquire;
try
if FVertexKeys.ContainsKey(Key) then begin
Result := FVertexKeys.Items[ Key ];
end
else begin
Result := FVertices.Count;
FVertices.AddVertex(V^.X, V^.Y, V^.Z);
FVertexKeys.Add(Key, Result);
end;
finally
Sync.Release;
end;
end;
function TFacesList.AddVertex(const V: TPD3Vector): Integer;
var
Key: String;
begin
Key := MakeVertexKey(V^.X, V^.Y, V^.Z);
if FVertexKeys.ContainsKey( Key ) then begin
Result := FVertexKeys.Items[ Key ];
end
else begin
Result := FVertices.Count;
FVertices.AddVertex(V^.X, V^.Y, V^.Z);
FVertexKeys.Add(Key, Result);
end;
end;
function TFacesList.ValidateFace(const V1, V2, V3: Integer): Boolean;
begin
Result := (V1 <> V2) and (V2 <> V3) and (V1 <> V3);
end;
procedure TFacesList.MoveFaces(const Src: TFacesList);
var
I: Integer;
Face: TPFace;
begin
if Src <> nil then begin
for I := 0 to Src.FFaces.Count - 1 do begin
Face := Src.FFaces[I];
Src.FFaces[I] := nil;
Face^.Vertex1 := AddVertex(Src.FVertices.GetVertex(Face^.Vertex1));
Face^.Vertex2 := AddVertex(Src.FVertices.GetVertex(Face^.Vertex2));
Face^.Vertex3 := AddVertex(Src.FVertices.GetVertex(Face^.Vertex3));
if ValidateFace(Face^.Vertex1, Face^.Vertex2, Face^.Vertex3) then
FFaces.Add(Face)
else
FreeMem(Face);
end;
Src.FFaces.Clear;
Src.Clear;
end;
end;
procedure TFacesList.MoveFaces(const Src: TFacesList; const Sync: TCriticalSection );
var
I: Integer;
Face: TPFace;
begin
if Src <> nil then begin
for I := 0 to Src.FFaces.Count - 1 do begin
Face := Src.FFaces[I];
Src.FFaces[I] := nil;
Face^.Vertex1 := AddVertex(Src.FVertices.GetVertex(Face^.Vertex1), Sync);
Face^.Vertex2 := AddVertex(Src.FVertices.GetVertex(Face^.Vertex2), Sync);
Face^.Vertex3 := AddVertex(Src.FVertices.GetVertex(Face^.Vertex3), Sync);
if ValidateFace(Face^.Vertex1, Face^.Vertex2, Face^.Vertex3) then begin
Sync.Acquire;
try
FFaces.Add(Face);
finally
Sync.Release;
end;
end
else
FreeMem(Face);
end;
Src.FFaces.Clear;
Src.Clear;
end;
end;
procedure TFacesList.RemoveDuplicates;
var
I: Integer;
OldFaces: TList;
FacesIdxList: TStringList;
Face: TPFace;
function MakeFaceKey: String;
var
V1 , V2, V3: Integer;
begin
V1 :=Min(Min(Face^.Vertex1, Face^.Vertex2), Face^.Vertex3);
V3 :=Max(Max(Face^.Vertex1, Face^.Vertex2), Face^.Vertex3);
if (Face^.Vertex1 > V1) and (Face^.Vertex1 < V3) then
V2 := Face^.Vertex1
else if (Face^.Vertex2 > V1) and (Face^.Vertex2 < V3) then
V2 := Face^.Vertex2
else
V2 := Face^.Vertex3;
Result := IntToStr(V1)+' '+IntToStr(V2)+' '+IntToStr(V3);
end;
begin
FacesIdxList := TStringList.Create;
try
FacesIdxList.Duplicates := dupIgnore;
FacesIdxList.Sorted := True;
OldFaces := FFaces;
FFaces := TList.Create;
try
for I := 0 to OldFaces.Count -1 do begin
Face := OldFaces[I];
if FacesIdxList.IndexOf( MakeFaceKey ) < 0 then begin
OldFaces[I] := nil;
FFaces.Add(Face);
end;
end;
finally
for I := 0 to OldFaces.Count - 1 do begin
Face := OldFaces[I];
if Face <> nil then begin
OldFaces[I] := nil;
FreeMem(Face);
end;
end;
OldFaces.Clear;
OldFaces.Free;
end;
finally
FacesIdxList.Free;
end;
end;
procedure TFacesList.TaubinSmooth(const Lambda, Mu: Double; const Passes: Integer);
var
T0: Int64;
I :Integer;
NeighboursList: TVertexNeighboursList;
begin
NeighboursList := TVertexNeighboursList.Create(Self);
try
T0 := DateUtils.MilliSecondsBetween(Now, 0);
for I := 0 to Passes - 1 do begin
LaplaceSmooth(NeighboursList, Lambda);
LaplaceSmooth(NeighboursList, Mu);
end;
ShowDebugInfo('TaubinSmooth', T0);
finally
NeighboursList.Free;
end;
end;
const
LUT_VERTICES_PER_CONFIGURATION_COUNT = 12;
type
TCompressedFacesConfiguration = Array[0..LUT_VERTICES_PER_CONFIGURATION_COUNT - 1] of Integer;
TPCompressedFacesConfiguration = ^TCompressedFacesConfiguration;
const
COMPRESSED_FACES: Array[0..5, 0..LUT_VERTICES_PER_CONFIGURATION_COUNT - 1 ] of Integer = (
(-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, 2, 2, 3, 0, -1, -1, -1, -1, -1, -1),
(0, 1, 2, 0, 2, 4, 4, 2, 3, -1, -1, -1),
(1, 2, 3, 1, 3, 4, 1, 4, 0, 0, 4, 5)
);
procedure TFacesList.RemoveVertices(const VerticesToRemove: TList; const FaceNeighbours: TFaceNeighboursList);
var
I, J, V, V0, V1, V2, NextV, PrevV, PrevPrevV, Idx: Integer;
VCount, MaxVCount, MaxIdx: Integer;
SortedVertices: TList;
Neighbours, RList: TList;
Edges: TStringList;
Face: TPFace;
RemoveList: TStringList;
FaceIdx: TPCompressedFacesConfiguration;
RemoveVertexList, InvalidRemoveLists: TStringList;
procedure GetBorderVertices(const Face: TPFace;const Center: Integer; var BorderV1, BorderV2: Integer);
begin
if Face^.Vertex1 = Center then begin
BorderV1 := Face^.Vertex2;
BorderV2 := Face^.Vertex3;
end
else if Face^.Vertex2 = Center then begin
BorderV1 := Face^.Vertex3;
BorderV2 := Face^.Vertex1;
end
else if Face^.Vertex3 = Center then begin
BorderV1 := Face^.Vertex1;
BorderV2 := Face^.Vertex2;
end
else
raise Exception.Create('TFacesList.RemoveVertices.GetBorderVertices: Invalid Face <'+IntToStr(Face^.Vertex1)+'/'+IntToStr(Face^.Vertex2)+'/'+IntToStr(Face^.Vertex3)+'>: missing center <'+IntToStr(Center)+'>');
end;
procedure ClearEdges;
var
I: Integer;
begin
for I := 0 to Edges.Count -1 do
TList(Edges.Objects[I]).Free;
Edges.Clear;
end;
procedure AddEdge(const FromVertex, ToVertex: Integer);
var
Key: String;
I, Idx: Integer;
Found: Boolean;
EdgesLst: TList;
begin
Key := IntToStr(FromVertex);
Idx := Edges.IndexOf( Key );
if Idx < 0 then begin
EdgesLst := TList.Create;
Edges.AddObject(Key, EdgesLst);
end
else
EdgesLst := TList(Edges.Objects[Idx]);
Found := False;
for I := 0 to EdgesLst.Count - 1 do begin
if Integer(EdgesLst[I]) = ToVertex then begin
Found := True;
break;
end;
end;
if not Found then
EdgesLst.Add(Pointer(ToVertex));
end;
function IsInnerVertex: Boolean;
var
I: Integer;
begin
Result := Edges.Count = Neighbours.Count;
if Result then begin
for I := 0 to Edges.Count -1 do begin
if TList(Edges.Objects[I]).Count <> 2 then begin
Result := False;
break;
end;
end;
end;
end;
function CreateRemoveVertexList: TStringList;
var
I, J: Integer;
SortedVertices: TList;
procedure AddKey(const Vertex, RemoveListIdx: Integer);
var
I, Idx: Integer;
Key: String;
RemoveLst: TList;
Found: Boolean;
begin
Key := IntToStr(Vertex);
Idx := Result.IndexOf(Key);
if Idx < 0 then begin
RemoveLst := TList.Create;
Result.AddObject(Key, RemoveLst);
end
else
RemoveLst := TList(Result.Objects[Idx]);
Found := False;
for I := 0 to RemoveLst.Count - 1 do begin
if Integer(RemoveLst[I])=RemoveListIdx then begin
Found := True;
break;
end;
end;
if not Found then
RemoveLst.Add(Pointer(RemoveListIdx));
end;
begin
Result := TStringList.Create;
try
Result.Duplicates := dupIgnore;
Result.Sorted := True;
for I := 0 to RemoveList.Count - 1 do begin
SortedVertices := TList(RemoveList.Objects[I]);
for J := 0 to SortedVertices.Count - 1 do begin
AddKey(Integer(SortedVertices[J]), I);
end;
end;
except
for I := 0 to Result.Count - 1 do
TList(Result.Objects[I]).Free;
Result.Free;
end;
end;
begin
OutputDebugString(PChar('Compress '+IntToStr(VerticesToRemove.Count)+' of '+IntToStr(FVertices.Count)));
RemoveList := TStringList.Create;
try
Edges := TStringList.Create;
try
Edges.Duplicates := dupIgnore;
Edges.Sorted :=True;
for I := 0 to VerticesToRemove.Count - 1 do begin
ClearEdges;
V := Integer(VerticesToRemove[I]);
Neighbours := FaceNeighbours.GetNeighbours( V );
for J := 0 to Neighbours.Count -1 do begin
GetBorderVertices(GetFace(Integer(Neighbours[J])), V, V1, V2);
AddEdge(V1, V2);
AddEdge(V2, V1);
end;
if IsInnerVertex then begin
SortedVertices := TList.Create;
try
V0 := StrToInt(Edges[0]);
PrevPrevV := V0;
SortedVertices.Add(Pointer(V0));
PrevV := Integer(TList(Edges.Objects[0])[0]);
SortedVertices.Add(Pointer(PrevV));
while(True) do begin
Idx := Edges.IndexOf(IntToStr(PrevV));
if Idx < 0 then
raise Exception.Create('TFacesList.RemoveVertices: Vertex <'+IntToStr(V1)+'> not found');
NextV := Integer(TList(Edges.Objects[Idx])[0]);
if NextV = PrevPrevV then
NextV := Integer(TList(Edges.Objects[Idx])[1]);
if NextV = V0 then
break;
SortedVertices.Add(Pointer(NextV));
PrevPrevV := PrevV;
PrevV := NextV;
end;
except
SortedVertices.Free;
raise;
end;
if (SortedVertices.Count >= 4) and (SortedVertices.Count <= 6) then
RemoveList.AddObject(IntToStr(V), SortedVertices)
else
SortedVertices.Free;
end;
end;
finally
ClearEdges;
Edges.Free;
end;
if RemoveList.Count > 0 then begin
InvalidRemoveLists := TStringList.Create;
try
InvalidRemoveLists.Duplicates := dupIgnore;
InvalidRemoveLists.Sorted := True;
RemoveVertexList := CreateRemoveVertexList;
try
for I := 0 to RemoveVertexList.Count - 1 do begin
RList := TList(RemoveVertexList.Objects[I]);
if RList.Count > 1 then begin
MaxVCount := -1;
MaxIdx := -1;
for J := 0 to RList.Count - 1 do begin
VCount := TList( RemoveList.Objects[Integer(RList[J])]).Count;
if VCount > MaxVCount then begin
MaxVCount := VCount;
MaxIdx := J;
end;
end;
for J := 0 to RList.Count - 1 do begin
if J <> MaxIdx then begin
InvalidRemoveLists.Add(IntToStr( Integer(RList[J]) ));
end;
end;
end;
end;
finally
for I := 0 to RemoveVertexList.Count - 1 do
TList(RemoveVertexList.Objects[I]).Free;
RemoveVertexList.Free;
end;
for I := 0 to RemoveList.Count - 1 do begin
if InvalidRemoveLists.IndexOf( IntToStr(I) ) < 1 then begin
V := StrToInt(RemoveList[I]);
SortedVertices := TList(RemoveList.Objects[I]);
Neighbours := FaceNeighbours.GetNeighbours( V );
for J := 0 to Neighbours.Count -1 do begin
Face := GetFace(Integer(Neighbours[J]));
Face^.Vertex1 := -1;
end;
FaceIdx := @COMPRESSED_FACES[ SortedVertices.Count - 1 ];
J:=0;
while J < LUT_VERTICES_PER_CONFIGURATION_COUNT do begin
if FaceIdx[J] >= 0 then begin
V0 := Integer(SortedVertices[FaceIdx[J]]);
V1 := Integer(SortedVertices[FaceIdx[J + 1]]);
V2 := Integer(SortedVertices[FaceIdx[J + 2]]);
AddFace( V0, V2, V1);
end;
Inc(J, 3);
end;
end;
end;
finally
InvalidRemoveLists.Free;
end;
CleanupRemovedFaces;
end;
finally
RemoveList.Free;
end;
end;
procedure TFacesList.CompressPlanarVertices;
const
Tolerance: Double = 0.001;
var
I, J, RefNIdx: Integer;
Neighbours: TList;
FaceNormals: TPS4VectorList;
FaceNeighbours: TFaceNeighboursList;
RefN, N: TPS4Vector;
CompressVertex: Boolean;
CosA, Area, MaxArea: Double;
CompressList: TList;
begin
CompressList := TList.Create;
try
FaceNeighbours := TFaceNeighboursList.Create(Self);
try
FaceNormals := CalculateFaceNormals;
try
for I := 0 to FVertices.Count - 1 do begin
Neighbours := FaceNeighbours.GetNeighbours( I );
if (Neighbours <> nil) and (Neighbours.Count > 2) then begin
// Chose face with the largest area as reference
MaxArea := -1.0;
RefNIdx := -1;
for J := 1 to Neighbours.Count -1 do begin
Area := FaceNormals.GetVector(Integer(Neighbours[J])).W;
if Area > MaxArea then begin
MaxArea := Area;
RefNIdx := J;
end;
end;
// compare all normals of the neighbours against reference
RefN := FaceNormals.GetVector(Integer(Neighbours[RefNIdx]));
CompressVertex := True;
for J := 0 to Neighbours.Count -1 do begin
if J <> RefNIdx then begin
N := FaceNormals.GetVector(Integer(Neighbours[J]));
CosA := TSVectorMath.DotProduct(TPS3Vector(RefN), TPS3Vector(N));
if Abs(1.0 - Abs(CosA)) > Tolerance then begin
CompressVertex := False;
break;
end;
end;
end;
// if all normals point into the same direction the vertex may be compressed
if CompressVertex then begin
CompressList.Add(Pointer(I));
end;
end;
end;
finally
FaceNormals.Free;
end;
RemoveVertices(CompressList, FaceNeighbours);
finally
FaceNeighbours.Free;
end;
finally
CompressList.Free;
end;
end;
procedure TFacesList.CompressFaces(const Passes: Integer);
var
T0: Int64;
I, OldCount:Integer;
begin
OldCount := FFaces.Count;
T0 := DateUtils.MilliSecondsBetween(Now, 0);
for I := 0 to Passes - 1 do begin
CompressPlanarVertices;
end;
ShowDebugInfo('CompressFaces ('+IntToStr(OldCount)+'->'+IntToStr(FFaces.Count)+')', T0);
end;
procedure TFacesList.DoCenter(const MaxSize: Double);
begin
FVertices.DoCenter(MaxSize);
end;
procedure TFacesList.DoScale(const ScaleX, ScaleY, ScaleZ: Double);
begin
FVertices.DoScale(ScaleX, ScaleY, ScaleZ);
end;
procedure TFacesList.LaplaceSmooth(const NeighboursList: TVertexNeighboursList; const Strength: Double);
var
I, J: Integer;
Displacements: TList;
D: TPD3Vector;
Weight: Double;
Neighbours: TList;
V, VN: TPS3Vector;
begin
Displacements := TList.Create;
try
// Calc displacements
for I := 0 to FVertices.Count - 1 do begin
GetMem(D, SizeOf(TD3Vector));
D^.X := 0.0;
D^.Y := 0.0;
D^.Z := 0.0;
Displacements.Add(D);
Neighbours := NeighboursList.GetNeighbours( I );
if (Neighbours <> nil) and (Neighbours.Count > 1) then begin
Weight := 1.0 / Neighbours.Count;
V := FVertices.GetVertex( I );
for J:=0 to Neighbours.Count - 1 do begin
VN := FVertices.GetVertex( Integer(Neighbours[J]) );
D^.X := D^.X + (VN.X - V.X)* Weight;
D^.Y := D^.Y + (VN.Y - V.Y)* Weight;
D^.Z := D^.Z + (VN.Z - V.Z)* Weight;
end;
end;
end;
// Apply displacements
for I := 0 to FVertices.Count - 1 do begin
V := FVertices.GetVertex( I );
D := Displacements[I];
V^.X := V^.X + D^.X * Strength;
V^.Y := V^.Y + D^.Y * Strength;
V^.Z := V^.Z + D^.Z * Strength;
end;
finally
for I := 0 to Displacements.Count -1 do begin
if Displacements[I] <> nil then
FreeMem(Displacements[I]);
end;
Displacements.Free;
end;
end;
function TFacesList.CalculateVertexNormals: TPS3VectorList;
var
T0: Int64;
I: Integer;
A, B, C: TS3Vector;
V1, V2, V3: TPS3Vector;
Face: TPFace;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
Result := TPS3VectorList.Create;
try
for I := 0 to FVertices.Count -1 do begin
Result.AddVertex(0.0, 0.0, 0.0);
end;
for I := 0 to FFaces.Count - 1 do begin
Face := FFaces[I];
V1 := FVertices.GetVertex(Face^.Vertex1);
V2 := FVertices.GetVertex(Face^.Vertex2);
V3 := FVertices.GetVertex(Face^.Vertex3);
TSVectorMath.Subtract(V2, V1, @A);
TSVectorMath.Subtract(V3, V1, @B);
TSVectorMath.CrossProduct(@A, @B, @C);
TSVectorMath.AddTo(Result.GetVertex(Face^.Vertex1), @C);
TSVectorMath.AddTo(Result.GetVertex(Face^.Vertex2), @C);
TSVectorMath.AddTo(Result.GetVertex(Face^.Vertex3), @C);
end;
for I := 0 to FVertices.Count -1 do begin
TSVectorMath.Normalize(Result.GetVertex(I));
end;
except
Result.Free;
raise;
end;
ShowDebugInfo('CalculateVertexNormals', T0);
end;
function TFacesList.CalculateFaceNormals: TPS4VectorList;
const
EPS = 1e-50;
var
T0: Int64;
I: Integer;
A, B, C: TS3Vector;
V1, V2, V3: TPS3Vector;
Face: TPFace;
Area: Double;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
Result := TPS4VectorList.Create;
try
for I := 0 to FFaces.Count - 1 do begin
Face := FFaces[I];
V1 := FVertices.GetVertex(Face^.Vertex1);
V2 := FVertices.GetVertex(Face^.Vertex2);
V3 := FVertices.GetVertex(Face^.Vertex3);
TSVectorMath.Subtract(V2, V1, @A);
TSVectorMath.Subtract(V3, V1, @B);
TSVectorMath.CrossProduct(@A, @B, @C);
Area := TSVectorMath.Length(@C);
TSVectorMath.ScalarMul(1.0/Area+EPS, @C, @C);
// TVectorMath.SVNormalize(@C);
Result.AddVector(C.X, C.Y, C.Z, Area);
end;
except
Result.Free;
raise;
end;
ShowDebugInfo('CalculateFaceNormals', T0);
end;
procedure TFacesList.CleanupRemovedFaces;
var
T0: Int64;
I: Integer;
OldFaces: TList;
Face: TPFace;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
OldFaces := FFaces;
FFaces := TList.Create;
try
for I := 0 to OldFaces.Count -1 do begin
Face := OldFaces[I];
if (Face^.Vertex1 >= 0) and (Face^.Vertex2 >= 0) and (Face^.Vertex3 >= 0) then begin
OldFaces[I] := nil;
FFaces.Add(Face);
end;
end;
finally
for I := 0 to OldFaces.Count - 1 do begin
Face := OldFaces[I];
if Face <> nil then begin
OldFaces[I] := nil;
FreeMem(Face);
end;
end;
OldFaces.Clear;
OldFaces.Free;
end;
ShowDebugInfo('CleanupRemovedFaces', T0);
end;
type
TMergeFacesThread = class(TThread)
private
FDest, FSrc: TFacesList;
FDone: boolean;
FSync: TCriticalSection;
public
constructor Create( const Dest, Src: TFacesList; const Sync: TCriticalSection );
protected
procedure Execute; override;
function IsDone: boolean;
end;
constructor TMergeFacesThread.Create( const Dest, Src: TFacesList; const Sync: TCriticalSection );
begin
inherited Create(true);
FDest := Dest;
FSrc := Src;
FSync := Sync;
end;
procedure TMergeFacesThread.Execute;
begin
FDone := false;
try
FDest.MoveFaces(FSrc, FSync);
FSrc.Clear;
finally
FDone := true;
end;
end;
function TMergeFacesThread.IsDone: boolean;
begin
Result := FDone;
end;
class function TFacesList.MergeFacesLists(const FacesListsToMerge: TList; const MultiThreaded: boolean = false): TFacesList;
var
T0: Int64;
I: Integer;
IsDone: boolean;
FacesList: TFacesList;
Sync: TCriticalSection;
CurrThread: TMergeFacesThread;
Threads: TObjectList;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
Result := TFacesList.Create;
try
if MultiThreaded then begin
Sync:=TCriticalSection.Create;
try
Threads := TObjectList.Create;
try
for I := 0 to FacesListsToMerge.Count - 1 do begin
FacesList := FacesListsToMerge[I];
CurrThread := TMergeFacesThread.Create( Result, FacesList, Sync );
Threads.Add( CurrThread );
CurrThread.Start;
end;
IsDone := false;
while( not IsDone ) do begin
IsDone := true;
for I := 0 to Threads.Count - 1 do begin
if( not TMergeFacesThread(Threads[I]).IsDone ) then begin
IsDone := false;
break;
end;
Sleep(10);
end;
end;
finally
Threads.Free;
end;
finally
Sync.Free;
end;
end
else begin
for I := 0 to FacesListsToMerge.Count - 1 do begin
FacesList := FacesListsToMerge[I];
Result.MoveFaces(FacesList);
FacesList.Clear;
end;
end;
ShowDebugInfo('MergeFaces', T0);
except
Result.Free;
raise;
end;
end;
{ ------------------------------ TNeighboursList ----------------------------- }
constructor TNeighboursList.Create(const Faces: TFacesList);
begin
inherited Create;
FVertices := CreateNeighboursList(Faces);
end;
destructor TNeighboursList.Destroy;
var
I: Integer;
begin
if FVertices<>nil then begin
for I := 0 to FVertices.Count - 1 do begin
if FVertices[I] <> nil then
TList(FVertices[I]).Free;
end;
FVertices.Clear;
FVertices.Free;
end;
inherited Destroy;
end;
function TNeighboursList.GetNeighbours(const Idx: Integer): TList;
var
N: TList;
begin
Result := nil;
if (Idx >= 0) and (Idx < FVertices.Count) then begin
N := FVertices[Idx];
if (N<>nil) and (N.Count > 0) then
Result := N;
end;
end;
procedure TNeighboursList.SaveToFile(const Filename: String);
var
I, J: Integer;
S: String;
NList: TList;
Lst: TStringList;
begin
Lst := TStringList.Create;
try
for I := 0 to FVertices.Count - 1 do begin
NList := TList(FVertices[I]);
S:=IntToStr(I)+': ';
if NList <> nil then begin
for J:=0 to NList.Count -1 do begin
S := S + IntToStr(Integer(NList[J]))+' ';
end;
end;
Lst.Add(S);
end;
Lst.SaveToFile(Filename);
finally
Lst.Free;
end;
end;
{ ---------------------------- TVertexNeighboursList ------------------------- }
function TVertexNeighboursList.CreateNeighboursList(const Faces: TFacesList): TList;
var
T0: Int64;
I: Integer;
Face: TPFace;
procedure AddNeighbour(const FromVertex, ToVertex: Integer);
var
NList: TList;
I: Integer;
Found: Boolean;
begin
while Result.Count <= FromVertex do begin
Result.Add(TList.Create);
end;
NList := TList( Result[FromVertex] );
Found := False;
for I := 0 to NList.Count - 1 do begin
if Integer(NList[I]) = ToVertex then begin
Found := True;
break;
end;
end;
if not Found then begin
NList.Add(Pointer(ToVertex))
end;
end;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
Result := TList.Create;
try
for I := 0 to Faces.Count - 1 do begin
Face := Faces.GetFace(I);
AddNeighbour(Face^.Vertex1, Face^.Vertex2);
AddNeighbour(Face^.Vertex1, Face^.Vertex3);
AddNeighbour(Face^.Vertex2, Face^.Vertex1);
AddNeighbour(Face^.Vertex2, Face^.Vertex3);
AddNeighbour(Face^.Vertex3, Face^.Vertex1);
AddNeighbour(Face^.Vertex3, Face^.Vertex2);
end;
except
try
for I := 0 to Result.Count - 1 do begin
if Result[I] <> nil then
TList(Result[I]).Free;
end;
except
// Hide this error
end;
Result.Free;
raise;
end;
ShowDebugInfo('CreateVertexNeighboursList', T0);
end;
{ ----------------------------- TFaceNeighboursList -------------------------- }
function TFaceNeighboursList.CreateNeighboursList(const Faces: TFacesList): TList;
var
T0: Int64;
I: Integer;
Face: TPFace;
procedure AddNeighbour(const FromVertex, ToFace: Integer);
var
NList: TList;
I: Integer;
Found: Boolean;
begin
while Result.Count <= FromVertex do begin
Result.Add(TList.Create);
end;
NList := TList( Result[FromVertex] );
Found := False;
for I := 0 to NList.Count - 1 do begin
if Integer(NList[I]) = ToFace then begin
Found := True;
break;
end;
end;
if not Found then begin
NList.Add(Pointer(ToFace))
end;
end;
begin
T0 := DateUtils.MilliSecondsBetween(Now, 0);
Result := TList.Create;
try
for I := 0 to Faces.Count - 1 do begin
Face := Faces.GetFace(I);
AddNeighbour(Face^.Vertex1, I);
AddNeighbour(Face^.Vertex2, I);
AddNeighbour(Face^.Vertex3, I);
end;
except
try
for I := 0 to Result.Count - 1 do begin
if Result[I] <> nil then
TList(Result[I]).Free;
end;
except
// Hide this error
end;
Result.Free;
raise;
end;
ShowDebugInfo('CreateFaceNeighboursList', T0);
end;
end.
|
unit RelayBox;
interface
uses
Windows, Messages, SysUtils, Variants, Classes,
CPortX;
type
TChangeRelaysEvent = procedure(Sender: TObject) of object;
TChangeRelayEvent = procedure(Sender: TObject; Index: Integer; State: boolean) of object;
type
TRelayBox = class(TComponent)
private
ComPort: TCPortX;
FActive: boolean;
FEnable: boolean;
FCount: Integer;
FRelay: array of boolean;
FChangeRelay: TChangeRelayEvent;
FChangeRelays: TChangeRelaysEvent;
FMode: string;
FSerialNo: string;
FBaudRate: string;
FParity: string;
FStopBits: string;
FPort: string;
FFlowControl: string;
FDataBits: string;
procedure DoDoCmd(Cmd: string; recursive: boolean);
function GetBaudRate: string;
function GetDataBits: string;
function GetFlowControl: string;
function GetParity: string;
function GetPort: string;
function GetRelay(Index: integer): boolean;
function GetStopBits: string;
function MakeSendMess: string;
procedure SetAvtive(const Value: boolean);
procedure SetBaudRate(const Value: string);
procedure SetDataBits(const Value: string);
procedure SetFlowControl(const Value: string);
procedure SetParity(const Value: string);
procedure SetPort(const Value: string);
procedure SetRelay(Index: integer; const Value: boolean);
procedure SetStopBits(const Value: string);
procedure SetEnable(const Value: boolean);
procedure SetCount(const Value: Integer);
procedure SetMode(const Value: string);
procedure SetSerialNo(const Value: string);
public
property Active: boolean read FActive write SetAvtive;
property Count: Integer read FCount write SetCount;
property Enable: boolean read FEnable write SetEnable;
property Mode: string read FMode write SetMode;
property SerialNo: string read FSerialNo write SetSerialNo;
property Relay[Index: integer]: boolean read GetRelay write SetRelay;
property ChangeRelays: TChangeRelaysEvent read FChangeRelays write FChangeRelays;
property ChangeRelay: TChangeRelayEvent read FChangeRelay write FChangeRelay;
// RS232関連
property BaudRate: string read FBaudRate write SetBaudRate;
property DataBits: string read FDataBits write SetDataBits;
property FlowControl: string read FFlowControl write SetFlowControl;
property Parity: string read FParity write SetParity;
property Port: string read FPort write SetPort;
property StopBits: string read FStopBits write SetStopBits;
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Open();
procedure Close();
procedure DoCmd(Cmd: string);
end;
implementation
{ TRelayBox }
constructor TRelayBox.Create(Owner: TComponent);
begin
inherited;
ComPort := TCPortX.Create(self);
FActive := false;
FEnable := false;
FMode := 'Com';
FCount := 0;
FChangeRelay := nil;
FChangeRelays := nil;
end;
destructor TRelayBox.Destroy;
begin
if ComPort <> nil then
FreeAndNil(ComPort);
inherited;
end;
procedure TRelayBox.Open;
var
a: ansistring;
begin
if FEnable and not FActive then
begin
Comport.Delimiter := #10; // GS232用固定
Comport.TriggersOnRxChar := false;
// Comport.OnRecvMsg := GetDirectionOnRx; // RTX-59,GS-232共通化するため使わない
// Comport.OnException := ComException;
// ComPort.OnError := ComError;
ComPort.DataBits := FDataBits;
ComPort.BaudRate := FBaudRate;
ComPort.Parity := FParity;
ComPort.StopBits := FStopBits;
ComPort.Port := FPort;
ComPort.FlowControl := FFlowControl;
ComPort.Open;
ComPort.Clear;
FActive := true;
a := #3;
Comport.Write(a,1);
end;
end;
procedure TRelayBox.Close;
begin
if FActive then
begin
ComPort.Clear;
ComPort.Close;
FActive := false;
end;
end;
procedure TRelayBox.DoCmd(Cmd: string); // Cmdの内容を解析しながら送る
begin
if FActive then
DoDoCmd(Cmd, true);
end;
procedure TRelayBox.DoDoCmd(Cmd: string; recursive: boolean); // Cmdの内容を解析しながら送る
var
b: boolean;
i,j: integer;
s1,s2,s3: string;
begin
try
s1 := Copy(Cmd, 1, 1);
s2 := Copy(Cmd, 2, 1);
s3 := Copy(Cmd, 3, 16);
if (s1 = 'Y') then
begin
TryStrToInt(s2, i);
TryStrToInt(s3, j);
if s3 = '1' then
b := true
else
b := false;
SetRelay(i - 1, b);
end;
finally
end;
end;
function TRelayBox.GetBaudRate: string;
begin
result := Comport.BaudRate;
end;
function TRelayBox.GetDataBits: string;
begin
result := ComPort.DataBits;
end;
function TRelayBox.GetFlowControl: string;
begin
result := ComPort.FlowControl;
end;
function TRelayBox.GetParity: string;
begin
result := ComPort.Parity;
end;
function TRelayBox.GetPort: string;
begin
result := ComPort.Port;
end;
function TRelayBox.GetRelay(Index: integer): boolean;
begin
if FEnable and (Index <= FCount) then
result := FRelay[Index]
else
result := false;
end;
function TRelayBox.GetStopBits: string;
begin
result := ComPort.StopBits;
end;
procedure TRelayBox.SetAvtive(const Value: boolean);
begin
if Value <> FActive then
if Value then
Open
else
Close;
end;
procedure TRelayBox.SetBaudRate(const Value: string);
begin
FBaudRate := Value;
// ComPort.BaudRate := Value;
end;
procedure TRelayBox.SetCount(const Value: Integer);
var
i: integer;
begin
if not FActive then
begin
FCount := Value;
SetLength(FRelay, Count);
for i := Low(FRelay) to High(FRelay) do
FRelay[i] := false;
end;
end;
procedure TRelayBox.SetDataBits(const Value: string);
begin
FDataBits := Value;
// ComPort.DataBits := Value;
end;
procedure TRelayBox.SetEnable(const Value: boolean);
begin
if not FActive then
FEnable := Value;
end;
procedure TRelayBox.SetFlowControl(const Value: string);
begin
// ComPort.FlowControl := Value;
FFlowControl := Value;
end;
procedure TRelayBox.SetMode(const Value: string);
begin
FMode := Value;
end;
procedure TRelayBox.SetParity(const Value: string);
begin
FParity := Value;
// ComPort.Parity := Value;
end;
procedure TRelayBox.SetPort(const Value: string);
begin
FPort := Value;
// ComPort.Port := Value;
end;
procedure TRelayBox.SetRelay(Index: integer; const Value: boolean);
var
s: string;
a: AnsiString;
begin
if not FActive then
exit;
if (Index < Low(FRelay)) or (Index > High(FRelay)) then
exit;
if Value <> Relay[Index] then
begin
FRelay[Index] := value;
s := MakeSendMess;
// ComPort.WriteStr(s);
// a := AnsiString(s)+#0;
a := #255 + #01 + #01;
ComPort.Write(a, 3);
if Assigned(FChangeRelay) then
FChangeRelay(self, Index, Value);
if Assigned(FChangeRelays) then
FChangeRelays(self);
end;
end;
procedure TRelayBox.SetSerialNo(const Value: string);
begin
FSerialNo := Value;
end;
procedure TRelayBox.SetStopBits(const Value: string);
begin
FStopBits := Value;
// ComPort.StopBits := Value;
end;
function TRelayBox.MakeSendMess: string;
var
i: integer;
b: byte;
begin
b := 0;
for i := 7 Downto 0 do
begin
b := b shl 1;
if FRelay[i] then
b := b or 1;
end;
result := chr(b);
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLLinePFX<p>
A PFX whose particles are lines
<b>History : </b><font size=-1><ul>
<li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records
<li>23/08/10 - Yar - Added OpenGLTokens to uses, replaced OpenGL1x functions to OpenGLAdapter
<li>22/04/10 - Yar - Fixes after GLState revision
<li>05/03/10 - DanB - More state added to TGLStateCache
<li>12/10/08 - DanB - updated to use RCI
<li>06/06/07 - DaStr - Added GLColor to uses (BugtrackerID = 1732211)
<li>30/03/07 - DaStr - Added $I GLScene.inc
<li>20/02/05 - EG - Creation
</ul></font>
}
unit GLLinePFX;
interface
{$I GLScene.inc}
uses
Classes, SysUtils, GLPersistentClasses, GLVectorGeometry,
GLParticleFX, GLTexture, GLColor, GLRenderContextInfo,
OpenGLTokens, GLContext , GLVectorTypes;
type
// TGLLineParticle
//
{: Linear particle.<p> }
TGLLineParticle = class (TGLParticle)
private
{ Private Declarations }
FDirection : TAffineVector;
FLength : Single;
protected
{ Protected Declarations }
public
{ Public Declarations }
procedure WriteToFiler(writer : TVirtualWriter); override;
procedure ReadFromFiler(reader : TVirtualReader); override;
{: Direction of the line. }
property Direction : TAffineVector read FDirection write FDirection;
{: Length of the line }
property Length : Single read FLength write FLength;
end;
// TGLLinePFXManager
//
{: Polygonal particles FX manager.<p>
The particles of this manager are made of N-face regular polygon with
a core and edge color. No texturing is available.<br>
If you render large particles and don't have T&L acceleration, consider
using TGLPointLightPFXManager. }
TGLLinePFXManager = class (TGLLifeColoredPFXManager)
private
{ Private Declarations }
Fvx, Fvy : TAffineVector; // NOT persistent
FNvx, FNvy : TAffineVector; // NOT persistent
FDefaultLength : Single;
protected
{ Protected Declarations }
function StoreDefaultLength : Boolean;
function TexturingMode : Cardinal; override;
procedure InitializeRendering(var rci: TRenderContextInfo); override;
procedure BeginParticles(var rci: TRenderContextInfo); override;
procedure RenderParticle(var rci: TRenderContextInfo; aParticle : TGLParticle); override;
procedure EndParticles(var rci: TRenderContextInfo); override;
procedure FinalizeRendering(var rci: TRenderContextInfo); override;
public
{ Public Declarations }
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
class function ParticlesClass : TGLParticleClass; override;
function CreateParticle : TGLParticle; override;
published
{ Published Declarations }
property DefaultLength : Single read FDefaultLength write FDefaultLength stored StoreDefaultLength;
property ParticleSize;
property ColorInner;
property ColorOuter;
property LifeColors;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TGLLinePFXManager ------------------
// ------------------
// Create
//
constructor TGLLinePFXManager.Create(aOwner : TComponent);
begin
inherited;
FDefaultLength:=1;
end;
// Destroy
//
destructor TGLLinePFXManager.Destroy;
begin
inherited Destroy;
end;
// ParticlesClass
//
class function TGLLinePFXManager.ParticlesClass : TGLParticleClass;
begin
Result:=TGLLineParticle;
end;
// CreateParticle
//
function TGLLinePFXManager.CreateParticle : TGLParticle;
begin
Result:=inherited CreateParticle;
TGLLineParticle(Result).FLength:=DefaultLength;
end;
// TexturingMode
//
function TGLLinePFXManager.TexturingMode : Cardinal;
begin
Result:=0;
end;
// InitializeRendering
//
procedure TGLLinePFXManager.InitializeRendering(var rci: TRenderContextInfo);
var
i : Integer;
matrix : TMatrix;
begin
inherited;
GL.GetFloatv(GL_MODELVIEW_MATRIX, @matrix);
for i:=0 to 2 do begin
Fvx.V[i]:=matrix.V[i].V[0];
Fvy.V[i]:=matrix.V[i].V[1];
end;
FNvx:=VectorNormalize(Fvx);
FNvy:=VectorNormalize(Fvy);
end;
// BeginParticles
//
procedure TGLLinePFXManager.BeginParticles(var rci: TRenderContextInfo);
begin
ApplyBlendingMode(rci);
end;
// RenderParticle
//
procedure TGLLinePFXManager.RenderParticle(var rci: TRenderContextInfo; aParticle : TGLParticle);
var
lifeTime, sizeScale, fx, fy, f : Single;
inner, outer : TColorVector;
pos, dir, start, stop, dv : TAffineVector;
begin
lifeTime:=CurrentTime-aParticle.CreationTime;
ComputeColors(lifeTime, inner, outer);
if ComputeSizeScale(lifeTime, sizeScale) then
sizeScale:=sizeScale*ParticleSize
else sizeScale:=ParticleSize;
pos:=aParticle.Position;
with TGLLineParticle(aParticle) do begin
dir:=VectorNormalize(aParticle.Velocity);
f:=Length*0.5;
end;
start:=VectorCombine(pos, dir, 1, f);
stop:=VectorCombine(pos, dir, 1, -f);
fx:=VectorDotProduct(dir, FNvy)*sizeScale;
fy:=-VectorDotProduct(dir, FNvx)*sizeScale;
dv:=VectorCombine(Fvx, Fvy, fx, fy);
GL.Begin_(GL_TRIANGLE_FAN);
GL.Color4fv(@inner);
GL.Vertex3fv(@start);
GL.Color4fv(@outer);
GL.Vertex3f(start.V[0]+dv.V[0], start.V[1]+dv.V[1], start.V[2]+dv.V[2]);
GL.Vertex3f(stop.V[0]+dv.V[0], stop.V[1]+dv.V[1], stop.V[2]+dv.V[2]);
GL.Color4fv(@inner);
GL.Vertex3fv(@stop);
GL.Color4fv(@outer);
GL.Vertex3f(stop.V[0]-dv.V[0], stop.V[1]-dv.V[1], stop.V[2]-dv.V[2]);
GL.Vertex3f(start.V[0]-dv.V[0], start.V[1]-dv.V[1], start.V[2]-dv.V[2]);
GL.End_;
end;
// EndParticles
//
procedure TGLLinePFXManager.EndParticles(var rci: TRenderContextInfo);
begin
UnapplyBlendingMode(rci);
end;
// FinalizeRendering
//
procedure TGLLinePFXManager.FinalizeRendering(var rci: TRenderContextInfo);
begin
inherited;
end;
// StoreDefaultLength
//
function TGLLinePFXManager.StoreDefaultLength : Boolean;
begin
Result:=(FDefaultLength<>1);
end;
// ------------------
// ------------------ TGLLineParticle ------------------
// ------------------
// WriteToFiler
//
procedure TGLLineParticle.WriteToFiler(writer : TVirtualWriter);
begin
inherited WriteToFiler(writer);
with writer do begin
WriteInteger(0); // Archive Version 0
Write(FDirection, SizeOf(FDirection));
WriteFloat(FLength);
end;
end;
// ReadFromFiler
//
procedure TGLLineParticle.ReadFromFiler(reader : TVirtualReader);
var
archiveVersion : integer;
begin
inherited ReadFromFiler(reader);
archiveVersion:=reader.ReadInteger;
if archiveVersion=0 then with reader do begin
Read(FDirection, SizeOf(FDirection));
FLength:=ReadFloat;
end else RaiseFilerException(archiveVersion);
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// class registrations
RegisterClasses([TGLLineParticle, TGLLinePFXManager]);
end.
|
unit NtUtils.ImageHlp;
interface
{$OVERFLOWCHECKS OFF}
uses
Winapi.WinNt, NtUtils.Exceptions;
type
TExportEntry = record
Name: AnsiString;
Ordinal: Word;
VirtualAddress: Cardinal;
Forwards: Boolean;
ForwardsTo: AnsiString;
end;
PExportEntry = ^TExportEntry;
// Get an NT header of an image
function RtlxGetNtHeaderImage(Base: Pointer; ImageSize: NativeUInt;
out NtHeader: PImageNtHeaders): TNtxStatus;
// Get a section that contains a virtual address
function RtlxGetSectionImage(Base: Pointer; ImageSize:
NativeUInt; NtHeaders: PImageNtHeaders; VirtualAddress: Cardinal;
out Section: PImageSectionHeader): TNtxStatus;
// Get a pointer to a virtual address in an image
function RtlxExpandVirtualAddress(Base: Pointer; ImageSize: NativeUInt;
NtHeaders: PImageNtHeaders; MappedAsImage: Boolean; VirtualAddress: Cardinal;
AddressRange: Cardinal; out Status: TNtxStatus): Pointer;
// Get a data directory in an image
function RtlxGetDirectoryEntryImage(Base: Pointer; ImageSize: NativeUInt;
MappedAsImage: Boolean; Entry: TImageDirectoryEntry; out Directory:
PImageDataDirectory): TNtxStatus;
// Enumerate exported functions in a dll
function RtlxEnumerateExportImage(Base: Pointer; ImageSize: Cardinal;
MappedAsImage: Boolean; out Entries: TArray<TExportEntry>): TNtxStatus;
// Find an export enrty by name
function RtlxFindExportedName(const Entries: TArray<TExportEntry>;
Name: AnsiString): PExportEntry;
implementation
uses
Ntapi.ntrtl, ntapi.ntstatus, System.SysUtils;
function RtlxGetNtHeaderImage(Base: Pointer; ImageSize: NativeUInt;
out NtHeader: PImageNtHeaders): TNtxStatus;
begin
try
Result.Location := 'RtlImageNtHeaderEx';
Result.Status := RtlImageNtHeaderEx(0, Base, ImageSize, NtHeader);
except
on E: EAccessViolation do
begin
Result.Location := 'RtlxGetNtHeaderImage';
Result.Status := STATUS_ACCESS_VIOLATION;
end;
end;
end;
function RtlxGetSectionImage(Base: Pointer; ImageSize:
NativeUInt; NtHeaders: PImageNtHeaders; VirtualAddress: Cardinal; out Section:
PImageSectionHeader): TNtxStatus;
var
i: Integer;
begin
// Reproduce behavior of RtlSectionTableFromVirtualAddress with more
// range checks
if not Assigned(NtHeaders) then
begin
Result := RtlxGetNtHeaderImage(Base, ImageSize, NtHeaders);
if not Result.IsSuccess then
Exit;
end;
// Fail with this status if something goes wrong with range checks
Result.Location := 'RtlxGetSectionImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
try
Section := Pointer(NativeUInt(@NtHeaders.OptionalHeader) +
NtHeaders.FileHeader.SizeOfOptionalHeader);
for i := 0 to Integer(NtHeaders.FileHeader.NumberOfSections) - 1 do
begin
// Make sure the section is within the range
if NativeUInt(Section) - NativeUInt(Base) + SizeOf(TImageSectionHeader) >
ImageSize then
Exit;
// Does this virtual address belong to this section?
if (VirtualAddress >= Section.VirtualAddress) and (VirtualAddress <
Section.VirtualAddress + Section.SizeOfRawData) then
begin
// Yes, it does
Result.Status := STATUS_SUCCESS;
Exit;
end;
// Go to the next section
Inc(Section);
end;
except
on E: EAccessViolation do
Result.Status := STATUS_ACCESS_VIOLATION;
end;
// The virtual address is not found within image sections
Result.Status := STATUS_NOT_FOUND;
end;
function RtlxExpandVirtualAddress(Base: Pointer; ImageSize: NativeUInt;
NtHeaders: PImageNtHeaders; MappedAsImage: Boolean; VirtualAddress: Cardinal;
AddressRange: Cardinal; out Status: TNtxStatus): Pointer;
var
Section: PImageSectionHeader;
begin
if not MappedAsImage then
begin
if not Assigned(NtHeaders) then
begin
Status := RtlxGetNtHeaderImage(Base, ImageSize, NtHeaders);
if not Status.IsSuccess then
Exit(nil);
end;
// Mapped as a file, find a section that contains this virtual address
Status := RtlxGetSectionImage(Base, ImageSize, NtHeaders,
VirtualAddress, Section);
if not Status.IsSuccess then
Exit(nil);
// Compute the address
Result := Pointer(NativeUInt(Base) + Section.PointerToRawData -
Section.VirtualAddress + VirtualAddress);
end
else
Result := Pointer(NativeUInt(Base) + VirtualAddress); // Mapped as image
// Make sure the address is within the image
if (NativeUInt(Result) < NativeUInt(Base)) or
(NativeUInt(Result) + AddressRange - NativeUInt(Base) > ImageSize) then
begin
Status.Location := 'RtlxExpandVirtualAddress';
Status.Status := STATUS_INVALID_IMAGE_FORMAT;
end
else
Status.Status := STATUS_SUCCESS;
end;
function RtlxGetDirectoryEntryImage(Base: Pointer; ImageSize: NativeUInt;
MappedAsImage: Boolean; Entry: TImageDirectoryEntry; out Directory:
PImageDataDirectory): TNtxStatus;
var
Header: PImageNtHeaders;
begin
// We are going to reproduce behavior of RtlImageDirectoryEntryToData,
// but with more range checks
Result := RtlxGetNtHeaderImage(Base, ImageSize, Header);
if not Result.IsSuccess then
Exit;
// If something goes wrong, fail with this Result
Result.Location := 'RtlxGetDirectoryEntryImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
try
// Get data directory
case Header.OptionalHeader.Magic of
IMAGE_NT_OPTIONAL_HDR32_MAGIC:
Directory := @Header.OptionalHeader32.DataDirectory[Entry];
IMAGE_NT_OPTIONAL_HDR64_MAGIC:
Directory := @Header.OptionalHeader64.DataDirectory[Entry];
else
// Unknown executable architecture, fail
Exit;
end;
// Make sure we read data within the image
if NativeUInt(Directory) - NativeUInt(Base) +
SizeOf(TImageDataDirectory) > NativeUInt(ImageSize) then
Exit;
except
on E: EAccessViolation do
Result.Status := STATUS_ACCESS_VIOLATION;
end;
Result.Status := STATUS_SUCCESS;
end;
type
TCardinalArray = array [ANYSIZE_ARRAY] of Cardinal;
PCardinalArray = ^TCardinalArray;
TWordArray = array [ANYSIZE_ARRAY] of Word;
PWordArray = ^TWordArray;
function GetAnsiString(Address: PAnsiChar; Boundary: Pointer): AnsiString;
var
Start: PAnsiChar;
begin
Start := Address;
while (Address^ <> #0) and (Address <= Boundary) do
Inc(Address);
SetAnsiString(@Result, Start, NativeUInt(Address) - NativeUInt(Start), 0);
end;
function RtlxEnumerateExportImage(Base: Pointer; ImageSize: Cardinal;
MappedAsImage: Boolean; out Entries: TArray<TExportEntry>): TNtxStatus;
var
Header: PImageNtHeaders;
ExportData: PImageDataDirectory;
ExportDirectory: PImageExportDirectory;
Names, Functions: PCardinalArray;
Ordinals: PWordArray;
i: Integer;
Name: PAnsiChar;
begin
Result := RtlxGetNtHeaderImage(Base, ImageSize, Header);
if not Result.IsSuccess then
Exit;
// Find export directory data
Result := RtlxGetDirectoryEntryImage(Base, ImageSize, MappedAsImage,
ImageDirectoryEntryExport, ExportData);
if not Result.IsSuccess then
Exit;
try
// Check if the image has any exports
if ExportData.VirtualAddress = 0 then
begin
// Nothing to parse, exit
SetLength(Entries, 0);
Result.Status := STATUS_SUCCESS;
Exit;
end;
// Make sure export directory has appropriate size
if ExportData.Size < SizeOf(TImageExportDirectory) then
begin
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
Exit;
end;
// Obtain a pointer to the export directory
ExportDirectory := RtlxExpandVirtualAddress(Base, ImageSize, Header,
MappedAsImage, ExportData.VirtualAddress, SizeOf(TImageExportDirectory),
Result);
if not Result.IsSuccess then
Exit;
// Get an address of names
Names := RtlxExpandVirtualAddress(Base, ImageSize, Header, MappedAsImage,
ExportDirectory.AddressOfNames, ExportDirectory.NumberOfNames *
SizeOf(Cardinal), Result);
if not Result.IsSuccess then
Exit;
// Get an address of name ordinals
Ordinals := RtlxExpandVirtualAddress(Base, ImageSize, Header, MappedAsImage,
ExportDirectory.AddressOfNameOrdinals, ExportDirectory.NumberOfNames *
SizeOf(Word), Result);
if not Result.IsSuccess then
Exit;
// Get an address of functions
Functions := RtlxExpandVirtualAddress(Base, ImageSize, Header, MappedAsImage,
ExportDirectory.AddressOfFunctions, ExportDirectory.NumberOfFunctions *
SizeOf(Cardinal), Result);
if not Result.IsSuccess then
Exit;
// Fail with this status if something goes wrong
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_INVALID_IMAGE_FORMAT;
// Ordinals can reference only up to 65k exported functions
if Cardinal(ExportDirectory.NumberOfFunctions) > High(Word) then
Exit;
SetLength(Entries, ExportDirectory.NumberOfNames);
for i := 0 to ExportDirectory.NumberOfNames - 1 do
begin
Entries[i].Ordinal := Ordinals{$R-}[i]{$R+};
// Get a pointer to a name
Name := RtlxExpandVirtualAddress(Base, ImageSize, Header, MappedAsImage,
Names{$R-}[i]{$R+}, 0, Result);
if Result.IsSuccess then
Entries[i].Name := GetAnsiString(Name, Pointer(NativeUInt(Base) +
ImageSize));
// Each ordinal is an index inside an array of functions
if Entries[i].Ordinal >= ExportDirectory.NumberOfFunctions then
Continue;
Entries[i].VirtualAddress := Functions{$R-}[Ordinals[i]]{$R+};
// Forwarded functions have the virtual address in the same section as
// the export directory
Entries[i].Forwards := (Entries[i].VirtualAddress >=
ExportData.VirtualAddress) and (Entries[i].VirtualAddress <
ExportData.VirtualAddress + ExportData.Size);
if Entries[i].Forwards then
begin
// In case of forwarding the address actually points to the target name
Name := RtlxExpandVirtualAddress(Base, ImageSize, Header,
MappedAsImage, Entries[i].VirtualAddress, 0, Result);
if Result.IsSuccess then
Entries[i].ForwardsTo := GetAnsiString(Name, Pointer(NativeUInt(Base)
+ ImageSize));
end;
{ TODO: add range checks to see if the VA is within the image. Can't
simply compare the VA to the size of an image that is mapped as a file,
though. }
end;
except
on E: EAccessViolation do
begin
Result.Location := 'RtlxEnumerateExportImage';
Result.Status := STATUS_ACCESS_VIOLATION;
end;
end;
Result.Status := STATUS_SUCCESS;
end;
function RtlxFindExportedName(const Entries: TArray<TExportEntry>;
Name: AnsiString): PExportEntry;
var
i: Integer;
begin
// TODO: switch to binary search since they are always ordered
for i := 0 to High(Entries) do
if Entries[i].Name = Name then
Exit(@Entries[i]);
Result := nil;
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ Internet Application Runtime }
{ }
{ Copyright (C) 2002 Borland Software Corporation }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit ApacheTwoApp;
interface
uses SysUtils, Classes, HTTPD2, ApacheTwoHTTP, HTTPApp, WebBroker;
type
{ TApacheApplication }
TApacheTwoApplication = class(TWebApplication)
private
procedure ApacheHandleException(Sender: TObject);
protected
function NewRequest(var r: request_rec): TApacheTwoRequest;
function NewResponse(ApacheRequest: TApacheTwoRequest): TApacheTwoResponse;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Initialize; override;
function ProcessRequest(var r: request_rec): Integer;
end;
TRegisterHooksEvent = procedure(p: Papr_pool_t);
procedure set_module(defModule: Pmodule);
var
Handler: string; { Defaults to "projectname-handler" - all lowercase }
ModuleName: array [0..255] of Char; { Defaults to the DLL/SO's name }
apache_module: module;
{$EXTERNALSYM apache_module}
{ Assign OnRegisterHooks to a procedure and call the ap_hook_XXXX
procedures to register your own Apache 2.0 hooks }
OnRegisterHooks: TRegisterHooksEvent;
implementation
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF}
BrkrConst;
var
default_module_ptr: Pmodule;
procedure set_module(defModule: Pmodule);
begin
default_module_ptr := defModule;
end;
procedure HandleServerException(E: TObject; var r: request_rec);
var
ErrorMessage, EMsg: string;
begin
if E is Exception then
EMsg := Exception(E).Message
else
EMsg := '';
ErrorMessage := Format(sInternalServerError, [E.ClassName, EMsg]);
r.content_type := 'text/html';
apr_table_set(r.headers_out, 'Content-Length', pchar(IntToStr(Length(ErrorMessage))));
// ap_send_http_header(@r); // Not used in apache 2.0
ap_rputs(pchar(ErrorMessage), @r);
end;
constructor TApacheTwoApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Classes.ApplicationHandleException := ApacheHandleException;
end;
destructor TApacheTwoApplication.Destroy;
begin
Classes.ApplicationHandleException := nil;
inherited Destroy;
end;
function DefaultHandler(r: Prequest_rec): Integer; cdecl;
var
RequestedHandler: string;
begin
RequestedHandler := r^.handler;
if SameText(RequestedHandler, Handler) then
Result := (Application as TApacheTwoApplication).ProcessRequest(r^)
else
Result := DECLINED;
end;
procedure RegisterHooks(p: Papr_pool_t); cdecl;
begin
ap_hook_handler(DefaultHandler, nil, nil, APR_HOOK_MIDDLE);
if Assigned(OnRegisterHooks) then
OnRegisterHooks(p);
end;
procedure TApacheTwoApplication.Initialize;
begin
{ NOTE: Use the pointer and not the apache_module instance directly to
allow another module to be set (C++Builder uses that technique) }
FillChar(default_module_ptr^, SizeOf(default_module_ptr^), 0);
with default_module_ptr^ do
begin
version := MODULE_MAGIC_NUMBER_MAJOR;
minor_version := MODULE_MAGIC_NUMBER_MINOR;
module_index := -1;
name := ModuleName;
magic := MODULE_MAGIC_COOKIE;
register_hooks := RegisterHooks;
end;
end;
function TApacheTwoApplication.ProcessRequest(var r: request_rec): Integer;
var
HTTPRequest: TApacheTwoRequest;
HTTPResponse: TApacheTwoResponse;
begin
try
HTTPRequest := NewRequest(r);
try
HTTPResponse := NewResponse(HTTPRequest);
try
HandleRequest(HTTPRequest, HTTPResponse);
Result := HTTPResponse.ReturnCode; { Typically will be AP_OK }
finally
HTTPResponse.Free;
end;
finally
HTTPRequest.Free;
end;
except
HandleServerException(ExceptObject, r);
{ NOTE: Tell Apache we've handled this request; so there's no need to
pass this on to other modules. }
Result := AP_OK;
end;
end;
procedure TApacheTwoApplication.ApacheHandleException(Sender: TObject);
var
Handled: Boolean;
Intf: IWebExceptionHandler;
E: TObject;
begin
Handled := False;
if (ExceptObject is Exception) and
Supports(Sender, IWebExceptionHandler, Intf) then
Intf.HandleException(Exception(ExceptObject), Handled);
if not Handled then
begin
E := ExceptObject;
AcquireExceptionObject;
raise E;
end;
end;
function TApacheTwoApplication.NewRequest(var r: request_rec): TApacheTwoRequest;
begin
Result := TApacheTwoRequest.Create(r);
end;
function TApacheTwoApplication.NewResponse(ApacheRequest: TApacheTwoRequest): TApacheTwoResponse;
begin
Result := TApacheTwoResponse.Create(ApacheRequest);
end;
procedure InitApplication;
var
TempModuleName: string;
begin
set_module(@apache_module);
Application := TApacheTwoApplication.Create(nil);
SetLength(TempModuleName, MAX_PATH+1);
SetLength(TempModuleName, GetModuleFileName(HInstance,
PChar(TempModuleName), Length(TempModuleName)));
TempModuleName := LowerCase(ExtractFileName(TempModuleName));
Handler := Lowercase(ChangeFileExt(TempModuleName, '-handler')); {do not localize}
StrLCopy(ModuleName, PChar(TempModuleName), SizeOf(ModuleName) - 1);
end;
initialization
InitApplication;
end.
|
unit SudokuType;
{
***************************************************************************
* Copyright (C) 2006 Matthijs Willemstein *
* *
* This source is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This code is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details. *
* *
* A copy of the GNU General Public License is available on the World *
* Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also *
* obtain it by writing to the Free Software Foundation, *
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
* *
***************************************************************************
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, StdCtrls;
type
TDigits = 1..9;
TDigitSet = set of TDigits;
TSquare = record
Value: Integer; // The value of this square.
Locked: Boolean; // Wether or not the value is known.
DigitsPossible: TDigitSet;
end;
TValues = Array[1..9,1..9] of Integer;
TRawGrid = Array[1..9, 1..9] of TSquare;
{ TSudoku }
TSudoku = class(TObject)
private
FMaxSteps: Integer;
Grid: TRawGrid;
procedure CalculateValues(out IsSolved: Boolean);
procedure CheckRow(Col, Row: Integer);
procedure CheckCol(Col, Row: Integer);
procedure CheckBlock(Col, Row: Integer);
procedure CheckDigits(ADigit: Integer);
procedure CheckInput(Values: TValues);
procedure ValuesToGrid(Values: TValues);
function GridToValues: TValues;
function Solve(out Steps: Integer): Boolean;
public
constructor Create;
function GiveSolution(var Values: TValues; out RawData: TRawGrid; out Steps: Integer): Boolean;
function GiveSolution(var RawData: TRawGrid; out Values: TValues; out Steps: Integer): Boolean;
property MaxSteps: Integer read FMaxSteps write FMaxSteps default 50;
end;
ESudoku = class(Exception);
const
AllDigits: TDigitSet = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function DbgS(ASet: TDigitSet): String; overload;
function DbgS(ASquare: TSquare): String; overload;
implementation
const
cmin : Array[1..9] of Integer = (1, 1, 1, 4, 4, 4, 7, 7, 7);
cmax : Array[1..9] of Integer = (3, 3, 3, 6, 6, 6, 9, 9, 9);
function DbgS(ASet: TDigitSet): String; overload;
var
D: TDigits;
begin
Result := '[';
for D in ASet do
begin
Result := Result + IntToStr(D) + ',';
end;
if (Result[Length(Result)] = ',') then System.Delete(Result, Length(Result), 1);
Result := Result + ']';
end;
function DbgS(ASquare: TSquare): String; overload;
const
BoolStr: Array[Boolean] of String = ('False','True');
begin
Result := '[Value: ' + IntToStr(ASquare.Value) + ', ';
Result := Result + 'Locked: ' + BoolStr[ASquare.Locked] + ', ';
Result := Result + 'DigitsPossible: ' + DbgS(ASquare.DigitsPossible) + ']';
end;
{
Counts the number of TDigitSet in ASet.
aValue only has meaning if Result = 1 (which means this cell is solved)
}
function CountSetMembers(const ASet: TDigitSet; out aValue: Integer): Integer;
var
D: Integer;
begin
Result := 0;
aValue := 0;
for D := 1 to 9 do
begin
if D in ASet then
begin
Inc(Result);
aValue := D;
end;
end;
end;
function IsEqualGrid(const A, B: TRawGrid): Boolean;
var
Col, Row: Integer;
begin
Result := False;
for Col := 1 to 9 do
begin
for Row := 1 to 9 do
begin
if (A[Col,Row].DigitsPossible <> B[Col,Row].DigitsPossible) or
(A[Col,Row].Locked <> B[Col,Row].Locked) or
(A[Col,Row].Value <> B[Col,Row].Value) then
Exit;
end;
end;
Result := True;
end;
{ TSudoku }
procedure TSudoku.ValuesToGrid(Values: TValues);
var
c, r: Integer;
begin
for c := 1 to 9 do
begin
for r := 1 to 9 do
begin
if Values[c, r] in [1..9] then
begin
Grid[c, r].Locked := True;
Grid[c, r].Value := Values[c, r];
Grid[c, r].DigitsPossible := [(Values[c, r])];
end
else
begin
Grid[c, r].Locked := False;
Grid[c, r].Value := 0;
Grid[c, r].DigitsPossible := AllDigits;
end;
end;
end;
end;
function TSudoku.GridToValues: TValues;
var
Col, Row: Integer;
begin
for Col := 1 to 9 do
begin
for Row := 1 to 9 do
begin
Result[Col, Row] := Grid[Col, Row].Value;
end;
end;
end;
function TSudoku.Solve(out Steps: Integer): Boolean;
var
c, r: Integer;
OldState: TRawGrid;
begin
Steps := 0;
repeat
inc(Steps);
OldState := Grid;
for c := 1 to 9 do
begin
for r := 1 to 9 do
begin
if not Grid[c, r].Locked then
begin
CheckRow(c, r);
CheckCol(c, r);
CheckBlock(c, r);
end;
end;
end;
for c := 1 to 9 do CheckDigits(c);
CalculateValues(Result);
//if IsConsole then
// writeln('Steps = ',Steps,', IsEqualGrid(OldState, Grid) = ',IsEqualGrid(OldState, Grid));
until Result or (Steps >= FMaxSteps) or (IsEqualGrid(OldState, Grid));
end;
constructor TSudoku.Create;
begin
inherited Create;
FMaxSteps := 50;
end;
function TSudoku.GiveSolution(var Values: TValues; out RawData: TRawGrid; out Steps: Integer): Boolean;
begin
CheckInput(Values);
ValuesToGrid(Values);
Result := Solve(Steps);
Values := GridToValues;
RawData := Grid;
end;
{
Note: no sanity check on RawData is performed!
}
function TSudoku.GiveSolution(var RawData: TRawGrid; out Values: TValues; out Steps: Integer): Boolean;
begin
Grid := RawData;
Result := Solve(Steps);
RawData := Grid;
Values := GridToValues;
end;
procedure TSudoku.CalculateValues(out IsSolved: Boolean);
var
c, r: Integer;
Value, Count: Integer;
begin
Count := 0;
for c := 1 to 9 do
begin
for r := 1 to 9 do
begin
if Grid[c, r].Locked then
Inc(Count)
else
begin
if CountSetMembers(Grid[c, r].DigitsPossible, Value) = 1 then
begin
Grid[c, r].Value := Value;
Grid[c, r].Locked := True;
Inc(Count);
end;
end;
end;
end;
IsSolved := Count = 9 * 9;
end;
procedure TSudoku.CheckCol(Col, Row: Integer);
var
i, d: Integer;
begin
for i := 1 to 9 do
begin
if i = Row then continue;
for d := 1 to 9 do
begin
if Grid[Col, i].Value = d then exclude(Grid[Col, Row].DigitsPossible, d);
end;
end;
end;
procedure TSudoku.CheckRow(Col, Row: Integer);
var
i, d: Integer;
begin
for i := 1 to 9 do
begin
if i = Col then continue;
for d := 1 to 9 do
begin
if Grid[i, Row].Value = d then exclude(Grid[Col, Row].DigitsPossible, d);
end;
end;
end;
procedure TSudoku.CheckBlock(Col, Row: Integer);
var
i, j, d: Integer;
begin
for i := cmin[Col] to cmax[Col] do
begin
for j := cmin[Row] to cmax[Row] do
begin
if not ((i = Col) and (j = Row)) then
begin
for d := 1 to 9 do
begin
if Grid[i, j].Value = d then exclude(Grid[Col, Row].DigitsPossible, d);
end;
end;
end;
end;
end;
procedure TSudoku.CheckDigits(ADigit: Integer);
var
OtherPossible: Boolean;
c, r: Integer;
i: Integer;
value: Integer;
begin
for c := 1 to 9 do
begin
for r := 1 to 9 do
begin
if Grid[c, r].Locked
or (CountSetMembers(Grid[c, r].DigitsPossible, Value) = 1) then continue;
if ADigit in Grid[c, r].DigitsPossible then
begin
OtherPossible := False;
for i := 1 to 9 do
begin
if i <> c then OtherPossible := (ADigit in Grid[i, r].DigitsPossible);
if OtherPossible then Break;
end;
if not OtherPossible then
begin
Grid[c, r].DigitsPossible := [ADigit];
end
else
begin
OtherPossible := False;
for i := 1 to 9 do
begin
if i <> r then OtherPossible := (ADigit in Grid[c, i].DigitsPossible);
if OtherPossible then Break;
end;
if not OtherPossible then
begin
Grid[c, r].DigitsPossible := [ADigit];
end;
end;
end;
end;
end;
end;
procedure TSudoku.CheckInput(Values: TValues);
procedure CheckColValues;
var
Col, Row: Integer;
DigitSet: TDigitSet;
D: Integer;
begin
for Col := 1 to 9 do
begin
DigitSet := [];
for Row := 1 to 9 do
begin
D := Values[Col, Row];
if (D <> 0) then
begin
if (D in DigitSet) then
Raise ESudoku.CreateFmt('Duplicate value ("%d") in Col %d',[D, Col]);
Include(DigitSet, D);
end;
end;
end;
end;
procedure CheckRowValues;
var
Col, Row: Integer;
DigitSet: TDigitSet;
D: Integer;
begin
for Row := 1 to 9 do
begin
DigitSet := [];
for Col := 1 to 9 do
begin
D := Values[Col, Row];
if (D <> 0) then
begin
if (D in DigitSet) then
Raise ESudoku.CreateFmt('Duplicate value ("%d") in Row %d',[D, Row]);
Include(DigitSet, D);
end;
end;
end;
end;
procedure CheckBlockValues(StartCol, StartRow: Integer);
var
Col, Row: Integer;
DigitSet: TDigitSet;
D: Integer;
begin
DigitSet := [];
for Col := StartCol to StartCol + 2 do
begin
for Row := StartRow to StartRow + 2 do
begin
D := Values[Col,Row];
if (D <> 0) then
begin
if (D in DigitSet) then
Raise ESudoku.CreateFmt('Duplicate value ("%d") in block at Row: %d, Col: %d',[D, Row, Col]);
Include(DigitSet, D);
end;
end;
end;
end;
begin
CheckRowValues;
CheckColValues;
CheckBlockValues(1,1);
CheckBlockValues(1,4);
CheckBlockValues(1,7);
CheckBlockValues(4,1);
CheckBlockValues(4,4);
CheckBlockValues(4,7);
CheckBlockValues(7,1);
CheckBlockValues(7,4);
CheckBlockValues(7,7);
end;
end.
|
{
"RTC Image Playback"
- Copyright 2004-2017 (c) RealThinClient.com (http://www.realthinclient.com)
@exclude
}
unit rtcXImgPlayback;
interface
{$include rtcDefs.inc}
uses
Classes,
SysUtils,
rtcTypes,
rtcSystem,
rtcConn,
rtcThrPool,
rtcThrJobs,
rtcInfo,
rtcGateConst,
rtcGateCli,
rtcXBmpUtils,
rtcXImgDecode,
rtcXGateCIDs,
rtcXGateRecv;
type
{ @Abstract(RTC Image Playback Link)
Link this component to a TRtcHttpGateClient to handle Image Playback events. }
{$IFDEF IDE_XE2up}
[ComponentPlatformsAttribute(pidAll)]
{$ENDIF}
TRtcImagePlayback=class(TRtcGateReceiverLink)
protected
LastReceiveID:word;
PaintJob: TRtcQuickJob;
PreparePaint: TRtcQuickJob;
ImgDecoder:TRtcImageDecoder;
FLastMouseX,
FLastMouseY:integer;
FImageWidth,
FImageHeight:integer;
Bmp3Data:array of RtcByteArray;
Bmp3Info:TRtcBitmapInfo;
Bmp3Lock:TRtcCritSec;
img_OK, // Image initialized
img_MouseChg, // mouse position or image changed
img_Waiting, // waiting for Bmp3Info to be copied to Bmp4
img_Posting, // PreparePaint has been called or is executing
img_Painting, // PaintJob has been called or is executing
img_Drawing, // Repaint has been called or is executing
img_Ready, // Have a complete image in Bmp4
hadControl,
inControl:boolean;
procedure DoDataFilter(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var Wanted:boolean);
procedure DoDataReceived(Client:TRtcHttpGateClient; Data:TRtcGateClientData; var WantGUI, WantBackThread:boolean);
procedure DoDataReceivedGUI(Client:TRtcHttpGateClient; Data:TRtcGateClientData);
// @exclude
procedure Call_OnDataReceived(Sender:TRtcConnection); override;
procedure PreparePaintExecute(Data: TRtcValue);
procedure PaintJobExecute(Data: TRtcValue);
procedure DecodeFrame(frameID:word);
procedure ClearFrame;
procedure PostMouseUpdate;
procedure PostScreenUpdate;
procedure ImageRepaint;
procedure ImageReset;
procedure ImageDataStart;
procedure ImageData(const data:RtcByteArray);
procedure ImageDataMouse(const data:RtcByteArray);
procedure ImageDataFrame(const data:RtcByteArray);
procedure SetInControl(const Value: boolean);
procedure SetControlAllowed(const Value: boolean); override;
private
FOnCursorOn: TNotifyEvent;
FOnCursorOff: TNotifyEvent;
FOnStartReceive: TNotifyEvent;
FOnImageCreate: TNotifyEvent;
FOnImageUpdate: TNotifyEvent;
FOnImageRepaint: TNotifyEvent;
protected
procedure DoInputReset; override;
procedure DoReceiveStart; override;
procedure DoReceiveStop; override;
protected
procedure DoCursorOn; virtual;
procedure DoCursorOff; virtual;
procedure DoOnStartReceive; virtual;
procedure DoImageCreate; virtual;
procedure DoImageUpdate; virtual;
procedure DoImageRepaint; virtual;
public
constructor Create(AOwner:TComponent); override;
procedure MouseDown(MouseX,MouseY:integer; MouseButton:byte);
procedure MouseMove(MouseX,MouseY:integer);
procedure MouseUp(MouseX,MouseY:integer; MouseButton:byte);
procedure MouseWheel(MouseWheelDelta:integer);
procedure KeyDown(Key:word);
procedure KeyUp(Key:word);
property Image:TRtcBitmapInfo read Bmp3Info write Bmp3Info;
property Decoder:TRtcImageDecoder read ImgDecoder;
property MouseControl:boolean read inControl write SetInControl;
property LastMouseX:integer read FLastMouseX;
property LastMouseY:integer read FLastMouseY;
property ImageWidth:integer read FImageWidth;
property ImageHeight:integer read FImageHeight;
published
property OnImageCreate:TNotifyEvent read FOnImageCreate write FOnImageCreate;
property OnImageUpdate:TNotifyEvent read FOnImageUpdate write FOnImageUpdate;
property OnImageRepaint:TNotifyEvent read FOnImageRepaint write FOnImageRepaint;
property OnCursorShow:TNotifyEvent read FOnCursorOn write FOnCursorOn;
property OnCursorHide:TNotifyEvent read FOnCursorOff write FOnCursorOff;
property OnStartReceive:TNotifyEvent read FOnStartReceive write FOnStartReceive;
end;
implementation
{ TRtcImagePlayback }
constructor TRtcImagePlayback.Create(AOwner: TComponent);
begin
inherited;
// IMPORTANT !!!
cid_GroupInvite:=cid_ImageInvite; // needs to be assigned the Group Invitation ID !!!
Bmp3Lock:=nil;
FillChar(Bmp3Info,SizeOf(Bmp3Info),0);
hadControl:=False;
inControl:=False;
FLastMouseX:=-1;
FLastMouseY:=-1;
end;
procedure TRtcImagePlayback.DoCursorOff;
begin
if assigned(FOnCursorOff) then
FOnCursorOff(self);
end;
procedure TRtcImagePlayback.DoCursorOn;
begin
if assigned(FOnCursorOn) then
FOnCursorOn(self);
end;
procedure TRtcImagePlayback.DoImageCreate;
begin
if assigned(FOnImageCreate) then
FOnImageCreate(self);
end;
procedure TRtcImagePlayback.DoImageRepaint;
begin
if assigned(FOnImageRepaint) then
FOnImageRepaint(self);
end;
procedure TRtcImagePlayback.DoImageUpdate;
begin
if assigned(FOnImageUpdate) then
FOnImageUpdate(self);
end;
procedure TRtcImagePlayback.DoOnStartReceive;
begin
if assigned(FOnStartReceive) then
FOnStartReceive(self);
end;
procedure TRtcImagePlayback.SetInControl(const Value: boolean);
begin
if Value then
begin
if ControlAllowed then
inControl:=True;
end
else
begin
inControl:=False;
hadControl:=False;
DoCursorOn;
end;
end;
procedure TRtcImagePlayback.DecodeFrame(FrameID: word);
var
i:integer;
begin
Bmp3Lock.Acquire;
try
if length(Bmp3Data)>0 then
begin
for i := 0 to length(Bmp3Data)-1 do
begin
ImgDecoder.Decompress(Bmp3Data[i],Bmp3Info);
SetLength(Bmp3Data[i],0);
end;
SetLength(Bmp3Data,0);
end;
if FrameID>0 then
begin
LastReceiveID:=frameID;
img_Waiting:=True;
end;
finally
Bmp3Lock.Release;
end;
end;
procedure TRtcImagePlayback.ClearFrame;
var
i:integer;
begin
Bmp3Lock.Acquire;
try
if length(Bmp3Data)>0 then
begin
for i := 0 to length(Bmp3Data)-1 do
SetLength(Bmp3Data[i],0);
SetLength(Bmp3Data,0);
end;
finally
Bmp3Lock.Release;
end;
end;
procedure TRtcImagePlayback.ImageDataStart;
begin
Bmp3Lock.Acquire;
try
ImageReset;
ClearFrame;
ResetBitmapInfo(Bmp3Info);
finally
Bmp3Lock.Release;
end;
img_OK:=True;
end;
procedure TRtcImagePlayback.ImageData(const data: RtcByteArray);
begin
Bmp3Lock.Acquire;
try
if img_Waiting then
begin
SetLength(Bmp3Data,length(Bmp3Data)+1);
Bmp3Data[length(Bmp3Data)-1]:=data;
end
else
begin
DecodeFrame(0);
ImgDecoder.Decompress(data,Bmp3Info);
end;
finally
Bmp3Lock.Release;
end;
end;
procedure TRtcImagePlayback.ImageDataFrame(const data: RtcByteArray);
begin
if img_OK then
begin
DecodeFrame(Bytes2Word(data));
PostScreenUpdate;
end;
end;
procedure TRtcImagePlayback.ImageDataMouse(const data: RtcByteArray);
begin
if img_OK then
begin
Bmp3Lock.Acquire;
try
if img_Waiting then
begin
SetLength(Bmp3Data,length(Bmp3Data)+1);
Bmp3Data[length(Bmp3Data)-1]:=data;
end
else
begin
DecodeFrame(0);
ImgDecoder.Decompress(data,Bmp3Info);
img_MouseChg:=True;
PostMouseUpdate;
end;
finally
Bmp3Lock.Release;
end;
end;
end;
procedure TRtcImagePlayback.ImageRepaint;
var
myControl:boolean;
begin
try
if img_Waiting or img_MouseChg then
begin
if inControl then
myControl:=ImgDecoder.Cursor.User=Client.MyUID
else
myControl:=False;
if myControl<>hadControl then
if myControl then
begin
hadControl:=True;
DoCursorOff;
end
else
begin
inControl:=False;
hadControl:=False;
DoCursorOn;
end;
if img_Waiting then
begin
Bmp3Lock.Acquire;
try
if assigned(Bmp3Info.Data) then
begin
FImageWidth:=Bmp3Info.Width;
FImageHeight:=Bmp3Info.Height;
DoImageUpdate;
LastConfirmID:=LastReceiveID;
img_Drawing:=True;
img_Ready:=True;
img_Waiting:=False;
end
else
begin
FImageWidth:=0;
FImageHeight:=0;
end;
finally
Bmp3Lock.Release;
end;
end;
img_MouseChg:=False;
if img_Ready then DoImageRepaint;
ConfirmLastReceived;
img_Drawing:=False;
end;
finally
img_Painting:=False;
end;
PostScreenUpdate;
end;
procedure TRtcImagePlayback.ImageReset;
begin
Bmp3Lock.Acquire;
try
img_OK:=False;
img_Posting:=False;
img_Painting:=False;
img_Drawing:=False;
img_Waiting:=False;
img_MouseChg:=False;
img_Ready:=False;
LastReceiveID:=0;
LastConfirmID:=0;
FImageWidth:=0;
FImageHeight:=0;
FLastMouseX:=-1;
FLastMouseY:=-1;
finally
Bmp3Lock.Release;
end;
end;
procedure TRtcImagePlayback.KeyDown(Key: word);
begin
if img_Ready and ControlAllowed and (Client<>nil) and Client.Ready and (Key>0) then
Client.SendBytes(HostUserID,HostGroupID,cid_ControlKeyDown,Word2Bytes(Key));
end;
procedure TRtcImagePlayback.KeyUp(Key: word);
begin
if img_Ready and ControlAllowed and (Client<>nil) and Client.Ready and (Key>0) then
Client.SendBytes(HostUserID,HostGroupID,cid_ControlKeyUp,Word2Bytes(Key));
end;
procedure TRtcImagePlayback.MouseDown(MouseX, MouseY: integer; MouseButton: byte);
var
OutBytes:TRtcHugeByteArray;
begin
if img_Ready and ControlAllowed and (Client<>nil) and Client.Ready then
begin
MouseControl:=True;
FLastMouseX:=MouseX;
FLastMouseY:=MouseY;
if MouseX<0 then MouseX:=0;
if MouseY<0 then MouseY:=0;
OutBytes:=TRtcHugeByteArray.Create;
try
OutBytes.AddEx(Word2Bytes(MouseX));
OutBytes.AddEx(Word2Bytes(MouseY));
OutBytes.AddEx(OneByte2Bytes(MouseButton));
Client.SendBytes(HostUserID,HostGroupID,cid_ControlMouseDown,OutBytes.GetEx);
finally
FreeAndNil(OutBytes);
end;
DoImageRepaint;
end;
end;
procedure TRtcImagePlayback.MouseMove(MouseX, MouseY: integer);
var
OutBytes:TRtcHugeByteArray;
begin
if img_Ready and MouseControl and (Client<>nil) and Client.Ready then
begin
FLastMouseX:=MouseX;
FLastMouseY:=MouseY;
if MouseX<0 then MouseX:=0;
if MouseY<0 then MouseY:=0;
OutBytes:=TRtcHugeByteArray.Create;
try
OutBytes.AddEx(Word2Bytes(MouseX));
OutBytes.AddEx(Word2Bytes(MouseY));
Client.SendBytes(HostUserID,HostGroupID,cid_ControlMouseMove,OutBytes.GetEx);
finally
FreeAndNil(OutBytes);
end;
DoImageRepaint;
end;
end;
procedure TRtcImagePlayback.MouseUp(MouseX, MouseY: integer; MouseButton: byte);
var
OutBytes:TRtcHugeByteArray;
begin
if img_Ready and MouseControl and (Client<>nil) and Client.Ready then
begin
FLastMouseX:=MouseX;
FLastMouseY:=MouseY;
if MouseX<0 then MouseX:=0;
if MouseY<0 then MouseY:=0;
OutBytes:=TRtcHugeByteArray.Create;
try
OutBytes.AddEx(Word2Bytes(MouseX));
OutBytes.AddEx(Word2Bytes(MouseY));
OutBytes.AddEx(OneByte2Bytes(MouseButton));
Client.SendBytes(HostUserID,HostGroupID,cid_ControlMouseUp,OutBytes.GetEx);
finally
FreeAndNil(OutBytes);
end;
DoImageRepaint;
end;
end;
procedure TRtcImagePlayback.MouseWheel(MouseWheelDelta: integer);
begin
if img_Ready and ControlAllowed and (Client<>nil) and Client.Ready then
begin
Client.SendBytes(HostUserID,HostGroupID,cid_ControlMouseWheel,Word2Bytes(32768 + MouseWheelDelta));
DoImageRepaint;
end;
end;
procedure TRtcImagePlayback.PreparePaintExecute(Data: TRtcValue);
begin
if img_OK then
begin
img_Painting:=True;
PaintJob.Post(nil);
Sleep(15);
img_Posting:=False;
end;
if img_OK then
PostScreenUpdate;
end;
procedure TRtcImagePlayback.PaintJobExecute(Data: TRtcValue);
begin
if img_OK then
ImageRepaint
else
img_Painting:=False;
end;
procedure TRtcImagePlayback.PostMouseUpdate;
begin
if img_OK and img_Ready and not (img_Painting or img_Drawing or img_Posting) then
begin
img_Posting:=True;
PreparePaint.Post(nil);
end;
end;
procedure TRtcImagePlayback.PostScreenUpdate;
begin
if img_OK and img_Waiting and not (img_Painting or img_Drawing or img_Posting) then
begin
img_Posting:=True;
PreparePaint.Post(nil);
end;
end;
procedure TRtcImagePlayback.SetControlAllowed(const Value: boolean);
begin
inherited;
inControl:=False;
hadControl:=False;
DoCursorOn;
end;
procedure TRtcImagePlayback.DoInputReset;
begin
ImageReset;
end;
procedure TRtcImagePlayback.DoReceiveStop;
begin
if assigned(ImgDecoder) then
begin
PreparePaint.Stop;
PaintJob.Stop;
ImageReset;
repeat
Sleep(100);
until img_Painting=False;
RtcFreeAndNil(PreparePaint);
RtcFreeAndNil(PaintJob);
ClearFrame;
RtcFreeAndNil(ImgDecoder);
ReleaseBitmapInfo(Bmp3Info);
RtcFreeAndNil(Bmp3Lock);
end;
end;
procedure TRtcImagePlayback.DoReceiveStart;
begin
if not assigned(ImgDecoder) then
begin
Bmp3Lock:=TRtcCritSec.Create;
ImgDecoder:=TRtcImageDecoder.Create;
DoImageCreate;
ImageReset;
PreparePaint:=TRtcQuickJob.Create(nil);
PreparePaint.Serialized:=True;
PreparePaint.OnExecute:=PreparePaintExecute;
PaintJob:=TRtcQuickJob.Create(nil);
PaintJob.Serialized:=True;
PaintJob.AccessGUI:=True;
PaintJob.OnExecute:=PaintJobExecute;
end;
end;
procedure TRtcImagePlayback.DoDataFilter(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var Wanted: boolean);
begin
case Data.CallID of
cid_ImageStart:
if Data.Footer then
Wanted:=IsMyPackage(Data)
else if Data.Header then
Data.ToBuffer:=IsMyPackage(Data);
cid_ImageMouse,
cid_ImageData,
cid_GroupConfirmSend:
if Data.Footer then
Wanted:=img_OK and IsMyPackage(Data)
else if Data.Header then
Data.ToBuffer:=img_OK and IsMyPackage(Data);
end;
end;
procedure TRtcImagePlayback.DoDataReceived(Client: TRtcHttpGateClient; Data: TRtcGateClientData; var WantGUI, WantBackThread: boolean);
begin
case Data.CallID of
cid_ImageData: ImageData(Data.Content);
cid_ImageMouse: ImageDataMouse(Data.Content);
cid_GroupConfirmSend: ImageDataFrame(Data.Content);
cid_ImageStart: WantGUI:=True;
end;
end;
procedure TRtcImagePlayback.DoDataReceivedGUI(Client: TRtcHttpGateClient; Data: TRtcGateClientData);
begin
if Data.CallID=cid_ImageStart then
begin
ImageDataStart;
DoOnStartReceive;
end;
end;
procedure TRtcImagePlayback.Call_OnDataReceived(Sender: TRtcConnection);
begin
if Filter(DoDataFilter,Sender) then
Call(DoDataReceived,DoDataReceivedGUI,Sender);
inherited;
end;
end.
|
unit uprincipal;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TfrmPrincipal = class(TForm)
edtRetornoPesquisa: TEdit;
Label1: TLabel;
btnCliente: TButton;
btnFornecedor: TButton;
procedure btnClienteClick(Sender: TObject);
procedure btnFornecedorClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmPrincipal: TfrmPrincipal;
implementation
uses upesquisa;
{$R *.dfm}
procedure TfrmPrincipal.btnClienteClick(Sender: TObject);
begin
frmPesquisa := tfrmPesquisa.Create(self,['codigo','nome','telefone'],'cliente','nome');
try
if frmPesquisa.ShowModal = mrYes then
edtRetornoPesquisa.Text := frmPesquisa.edtRetorno.Text
else
edtRetornoPesquisa.Clear;
finally
FreeAndNil(frmPesquisa);
end;
end;
procedure TfrmPrincipal.btnFornecedorClick(Sender: TObject);
begin
frmPesquisa := tfrmPesquisa.Create(self,['codigo','nome','endereco','numero'],'fornecedor','nome');
try
if frmPesquisa.ShowModal = mrYes then
edtRetornoPesquisa.Text := frmPesquisa.edtRetorno.Text
else
edtRetornoPesquisa.Clear;
finally
FreeAndNil(frmPesquisa);
end;
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 OriStrings;
{$mode objfpc}{$H+}
interface
uses
SysUtils;
type
TStringArray = array of String;
function SplitStr(const S, Delims: String): TStringArray;
function SplitStr(const S, Delims: String; var Parts: TStringArray): Integer;
procedure SplitString(const S, Delims: String; var Parts: TStringArray);
function ReplaceChar(const AStr: String; const AFrom, ATo: Char): String;
function CharPos(const Str: String; Ch: Char): Integer; overload;
function LeftTill(const Source: String; Ch: Char): String;
function StartsWith(const Source, SubStr: String): Boolean;
function StartsWithI(const Source, SubStr: String): Boolean; inline;
function CharInSet(C: WideChar; const CharSet: TSysCharSet): Boolean; overload; inline;
function CharInSet(C: AnsiChar; const CharSet: TSysCharSet): Boolean; overload; inline;
function PadRight(const S: String; Width: Integer; PadChar: Char): String;
function FormatEx(const Format: String; const Args: array of const): String;
implementation
uses
Strings, LazUTF8;
function SplitStr(const S, Delims: String): TStringArray;
begin
Result := nil;
SplitString(S, Delims, Result);
end;
function SplitStr(const S, Delims: String; var Parts: TStringArray): Integer;
begin
SplitString(S, Delims, Parts);
Result := Length(Parts);
end;
procedure SplitString(const S, Delims: String; var Parts: TStringArray);
var
L, I, Len, Index: Integer;
begin
Parts := nil;
I := 1;
Index := 1;
Len := Length(S);
while I <= Len do
begin
if StrScan(PChar(Delims), S[I]) <> nil 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;
end;
function ReplaceChar(const AStr: String; const AFrom, ATo: Char): String;
var
chFrom, chTo: PChar;
begin
SetLength(Result, Length(AStr));
chFrom := PChar(AStr);
chTo := PChar(Result);
while chFrom^ <> #0 do
begin
if chFrom^ = AFrom
then chTo^ := ATo
else chTo^ := chFrom^;
Inc(chFrom);
Inc(chTo);
end;
end;
function CharPos(const Str: String; Ch: Char): Integer;
var i: Integer;
begin
for i := 1 to Length(Str) do
if Str[i] = Ch then
begin
Result := i;
Exit;
end;
Result := 0;
end;
function LeftTill(const Source: String; Ch: Char): String;
var
I: Integer;
begin
Result := Source;
for I := 1 to Length(Result) do
if Result[I] = Ch then
begin
SetLength(Result, I-1);
Break;
end;
end;
function StartsWith(const Source, SubStr: String): Boolean;
var
I: Integer;
begin
Result := False;
if Length(Source) < Length(SubStr) then Exit;
for I := 1 to Length(SubStr) do
if Source[I] <> SubStr[I] then Exit;
Result := True;
end;
function StartsWithI(const Source, SubStr: String): Boolean; inline;
begin
Result := SameText(Copy(Source, 1, Length(SubStr)), SubStr);
end;
function CharInSet(C: AnsiChar; const CharSet: TSysCharSet): Boolean;
begin
Result := C in CharSet;
end;
function CharInSet(C: WideChar; const CharSet: TSysCharSet): Boolean;
begin
Result := (C < #$0100) and (AnsiChar(C) in CharSet);
end;
function FormatEx(const Format: String; const Args: array of const): String;
var
IsBraket: Boolean;
I, Index, Param: Integer;
begin
Result := '';
Index := 1;
IsBraket := False;
for I := 1 to Length(Format) do
case Format[I] of
'{':
begin
Result := Result + Copy(Format, Index, I-Index);
IsBraket := True;
Index := I;
end;
'}':
begin
if IsBraket then
begin
IsBraket := False;
Param := StrToIntDef(Copy(Format, Index+1, I-Index-1), -1);
if (Param >= Low(Args)) and (Param <= High(Args)) then
case Args[Param].VType of
vtInteger : Result := Result + IntToStr(Args[Param].VInteger);
vtBoolean : Result := Result + BoolToStr(Args[Param].VBoolean, True);
vtChar : Result := Result + String(Args[I].VChar);
vtExtended : Result := Result + FloatToStr(Args[Param].VExtended^);
vtString : Result := Result + String(Args[Param].VString^);
vtPChar : Result := Result + String(Args[Param].VPChar^);
vtAnsiString : Result := Result + String(Args[Param].VAnsiString);
vtWideString : Result := Result + String(Args[Param].VWideString);
vtWideChar : Result := Result + String(Args[Param].VWideChar);
else Result := Result + Copy(Format, Index, I-Index+1);
end
else Result := Result + Copy(Format, Index, I-Index+1);
end
else Result := Result + Copy(Format, Index, I-Index+1);
Index := I+1;
end;
end;
if Index <= Length(Format) then Result := Result + Copy(Format, Index, MaxInt);
end;
function PadRight(const S: String; Width: Integer; PadChar: Char): String;
begin
if Width > Length(S)
then Result := S + StringOfChar(PadChar, Width - Length(S))
else Result := S;
end;
end.
|
unit ClassVykres;
interface
uses Typy, ClassSustava, ExtCtrls, Graphics, Windows, SysUtils, Classes;
type
TStyle = record
Farba : TColor;
Hrubka : integer;
end;
TVykres = class
private
Image : TImage; {Kam sa ma vsetko vykreslit - pointer na ImageVykres}
Sustava : TSustava; {Odkial sa maju ziskat data na vykreslenie}
Norm, Slct : TStyle; {Akym stylom sa ma kreslit}
LavyHorny : TBod; {Suradnice laveho horneho rohu vykresu}
PravyDolny : TBod; {Suradnice praveho dolneho rohu}
FZoom : real; {Ake je aktualne zvacsenie}
FPozicia : TBod; {Suradnice stredu image}
FZobrazitNazvy : boolean; {Maju sa vykreslit aj nazvy objektov?}
FZobrazitOsi : boolean; {Maju sa vykreslit osi suradnej sustavy?}
procedure ZmenZoom( iZoom : real );
procedure ZmenPoziciu( iPozicia : TBod );
procedure ZmenZobrazitNazvy( iZobrazitNazvy : boolean );
procedure ZmenZobrazitOsi( iZobrazitOsi : boolean );
{Pomocne procedury pre vykreslenie :}
procedure NakresliOsi;
procedure NakresliBody;
procedure NakresliNUholniky;
public
procedure Prekresli; {Vsetko nakresli - NAJDOLEZITEJSIA PROCEDURA}
{Prevod suradnic zo Sustavy na Image (a naopak):}
function SusToIm( A : TBod ) : TPoint;
function ImToSus( A : TPoint ) : TBod;
constructor Create( iImage : TImage; iSustava : TSustava );
destructor Destroy; override;
property Zoom : real read FZoom write ZmenZoom;
property Pozicia : TBod read FPozicia write ZmenPoziciu;
property ZobrazitNazvy : boolean read FZobrazitNazvy write ZmenZobrazitNazvy;
property ZobrazitOsi : boolean read FZobrazitOsi write ZmenZobrazitOsi;
end;
implementation
uses Debugging;
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
constructor TVykres.Create( iImage : TImage; iSustava : TSustava);
var Poz : TBod;
begin
inherited Create;
Napis( 'TVykres.Create' );
Image := iImage;
Sustava := iSustava;
with Norm do
begin
Farba := clBlack;
Hrubka := 1;
end;
with Slct do
begin
Farba := clBlue;
Hrubka := 3;
end;
with Image.Canvas do
begin
Pen.Color := Norm.Farba;
Pen.Width := Norm.Hrubka;
end;
FZoom := 1;
with Poz do
begin
X := 0;
Y := 0;
end;
Pozicia := Poz;
FZobrazitNazvy := True;
FZobrazitOsi := True;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
destructor TVykres.Destroy;
begin
inherited
end;
function TVykres.SusToIm( A : TBod ) : TPoint;
begin
result.X := Round((A.X - LavyHorny.X) * Zoom);
result.Y := Round((LavyHorny.Y - A.Y) * Zoom);
end;
function TVykres.ImToSus( A : TPoint ) : TBod;
begin
result.X := LavyHorny.X+(A.X / FZoom);
result.Y := LavyHorny.Y+(A.Y / FZoom);
end;
procedure TVykres.ZmenZoom( iZoom : real );
begin
FZoom := iZoom;
LavyHorny.X := FPozicia.X-((Image.Width / 2) / FZoom);
LavyHorny.Y := FPozicia.Y+((Image.Height / 2) / FZoom);
PravyDolny.X := FPozicia.X+((Image.Width / 2) / FZoom);
PravyDolny.Y := FPozicia.Y-((Image.Height / 2) / FZoom);
Prekresli;
end;
procedure TVykres.ZmenPoziciu( iPozicia : TBod );
begin
FPozicia := iPozicia;
LavyHorny.X := FPozicia.X-((Image.Width / 2) / FZoom);
LavyHorny.Y := FPozicia.Y+((Image.Height / 2) / FZoom);
PravyDolny.X := FPozicia.X+((Image.Width / 2) / FZoom);
PravyDolny.Y := FPozicia.Y-((Image.Height / 2) / FZoom);
Prekresli;
end;
procedure TVykres.ZmenZobrazitNazvy( iZobrazitNazvy : boolean );
begin
FZobrazitNazvy := iZobrazitNazvy;
Prekresli;
end;
procedure TVykres.ZmenZobrazitOsi( iZobrazitOsi : boolean );
begin
FZobrazitOsi := iZobrazitOsi;
if iZobrazitOsi then NakresliOsi
else Prekresli;
end;
(*
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
|| Kreslenie ||
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
*)
procedure TVykres.NakresliOsi;
const MIN_SIRKA = 100;
var A : TBod;
B : TPoint;
K : real;
Zaciatok, Pozicia : real;
begin
with Image.Canvas do
begin
{Os Y:}
if (LavyHorny.X < 0) and
(PravyDolny.X > 0) then
begin
A.X := 0;
A.Y := 0;
MoveTo( SusToIm(A).X , 0 );
LineTo( SusToIm(A).X , Image.Height );
K := 10;
if (K*Zoom < MIN_SIRKA) then
begin
while (K*Zoom < MIN_SIRKA) do
K := K*2;
end
else
begin
while (K*Zoom > MIN_SIRKA) do
K := K/2;
end;
if K > 100000 then K := 100000;
if K < 0.625 then K := 0.625;
Zaciatok := (Int(LavyHorny.Y / K)+1)*K;
Pozicia := Zaciatok;
repeat
A.X := 0;
A.Y := Pozicia;
B := SusToIm( A );
MoveTo( B.X-1 , B.Y );
LineTo( B.X+2 , B.Y );
if Pozicia <> 0 then TextOut( B.X+2 , B.Y-2 , FloatToStr( Pozicia ) );
Pozicia := Pozicia - K;
until Pozicia < PravyDolny.Y;
end;
{Os X:}
if (LavyHorny.Y > 0) and
(PravyDolny.Y < 0) then
begin
A.X := 0;
A.Y := 0;
MoveTo( 0 , SusToIm(A).Y );
LineTo( Image.Width , SusToIm(A).Y );
K := 10;
if (K*Zoom < MIN_SIRKA) then
begin
while (K*Zoom <= MIN_SIRKA) do
K := K*2;
end
else
begin
while (K*Zoom > MIN_SIRKA) do
K := K/2;
end;
if K > 100000 then K := 100000;
if K < 0.625 then K := 0.625;
Zaciatok := (Int(LavyHorny.X / K)-1)*K;
Pozicia := Zaciatok;
repeat
A.X := Pozicia;
A.Y := 0;
B := SusToIm( A );
MoveTo( B.X , B.Y-2 );
LineTo( B.X , B.Y+2 );
TextOut( B.X-2 , B.Y+2 , FloatToStr( Pozicia ) );
Pozicia := Pozicia + K;
until Pozicia > PravyDolny.X;
end;
end;
end;
procedure TVykres.NakresliBody;
var I : integer;
A : TPoint;
B : TBod;
begin
for I := 0 to Sustava.Body.Pole.Count-1 do
if (TBod( Sustava.Body.Pole[I]^ ).X >= LavyHorny.X) and
(TBod( Sustava.Body.Pole[I]^ ).X <= PravyDolny.X) and
(TBod( Sustava.Body.Pole[I]^ ).Y <= LavyHorny.Y) and
(TBod( Sustava.Body.Pole[I]^ ).Y >= PravyDolny.Y) then
begin
B.X := TBod( Sustava.Body.Pole[I]^ ).X;
B.Y := TBod( Sustava.Body.Pole[I]^ ).Y;
B.Nazov := TBod( Sustava.Body.Pole[I]^ ).Nazov;
A := SusToIm( B );
Image.Canvas.MoveTo( A.X-2 , A.Y-2 );
Image.Canvas.LineTo( A.X+3 , A.Y+3 );
Image.Canvas.MoveTo( A.X+2 , A.Y-2 );
Image.Canvas.LineTo( A.X-3 , A.Y+3 );
if ZobrazitNazvy then
Image.Canvas.TextOut( A.X+3, A.Y , B.Nazov );
end;
end;
procedure TVykres.NakresliNUholniky;
var I, J : integer;
JeVidiet : boolean; {Ci je vidiet N-uholnik na obrazovke}
A : TBod;
B, B0 : TPoint;
begin
for I := 0 to Sustava.NUholniky.Pole.Count-1 do
begin
JeVidiet := False;
for J := 0 to TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body.Count-1 do
if (TBod( TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body[J]^ ).X >= LavyHorny.X) and
(TBod( TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body[J]^ ).X <= PravyDolny.X) and
(TBod( TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body[J]^ ).Y <= LavyHorny.Y) and
(TBod( TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body[J]^ ).Y >= PravyDolny.Y) then
begin
JeVidiet := True;
break;
end;
if not JeVidiet then continue;
for J := 0 to TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body.Count-1 do
begin
A := TBod( TNuholnik( Sustava.NUholniky.Pole[I]^ ).Body[I]^ );
B := SusToIm( A );
if J = 0 then
begin
Image.Canvas.MoveTo( B.X , B.Y );
B0 := B;
end
else Image.Canvas.LineTo( B.X , B.Y );
end;
Image.Canvas.LineTo( B0.X , B0.Y );
end;
end;
procedure TVykres.Prekresli;
begin
Image.Canvas.FillRect( Image.ClientRect );
with Image.Canvas do
begin
Pen.Color := Norm.Farba;
Pen.Width := Norm.Hrubka;
end;
NakresliBody;
NakresliNUholniky;
if ZobrazitOsi then NakresliOsi;
end;
end.
|
unit Un_UDF;
interface
Uses
Windows, IniFiles, Dialogs, SysUtils, ConvUtils, Winsock, Registry, Forms;
type
DriveType = ( dtUnknown, dtNotExist, dtRemovable, dtFixed, dtRemote, dtCdRom, dtRamDisk, dtError );
TVolInfo = record
Name: string;
Serial: Cardinal;
IsCompressed: boolean;
MaxCompLen: Cardinal;
FileSysName: string;
end;
Function AbreviaNome( Nome: String ): String;
// Encriptação
Function Encrypt( cSenha : String ) : String;
Function EncDecStr( StrValue : String; Chave: Word ) : String;
function Criptografa( mStr, mChave: string ): string;
// > Tratando de Daos em arquivos .Ini <
Function GravarIni( cArquivo, cSecao, cIdentificador, cValor : String ) : Boolean;
Function LerIni( cArquivo, cSecao, cIdentificador : String ) : String;
// > Tratar Numeros <<
Function Virgula_por_Ponto( cValor : String ) : String;
Function GetNumeros( sStrn: String ): String;
Function TiraFormatacao( cValor : String ) : String;
Function StrZero( nVariavel, nTamanho : Integer ) : String;
Function IsInteger( TestaString: String ) : boolean;
// > Trata Datas <
Function InverteData( dData : String ) : String;
Function InverteDataIB( dData : String ) : String;
Function DataExtenso( Data:TDateTime ): String;
Function UltDiaDoMes( Data: TDateTime ): Word; // Retorna o Ultimo dia do mes de uma determinada data.
Function DateMais( Dat : TDateTime ; Numdias : Integer ) : TDateTime; { Soma um determinado número de dias à data atual }
Function DateMenos( Dat : TDateTime ; Numdias : Integer ) : TDateTime; { Subtrai um determinado número de dias à data atual }
Function NomedoMes( dData : TDateTime ) : String;
Procedure Formato_de_Data;
Function AnoBixesto(Data: TDateTime): Boolean; {Testa se um ano é bixesto, retornando True em caso positivo}
Function BiosDate : String; // Retorna a data da fabricação do Chip da Bios do sistema
// > Unidade de Disco <
Function DriveLetters: string; { Retorna uma string contendo as letras de unidades de existentes }
Function SerialNum( FDrive : String ) : String;
Function VolInfo(const Drive: Char; Path: PChar): TVolInfo; { Retorna informações diversas sobre a unidade. Veja TVolInfo }
Function NomeComputador : String;
Function GetIP : string; //--> Declare a Winsock na clausula uses da unit
Function VerificaRegistro( cUnidade: String ): Boolean;
// > Booleanas <
Function FBoolToStr( Check : Boolean ) : String; // converte de booleano para String
Function FStrToBool( Valor : String ) : Boolean; // converte de string para booleano
Function ControlaCampoTexto( cDado : String ) : String;
Function CampoInforme( cDado : String ) : String;
Function Iif( cDado, cCheck, cValor1, cValor2 : String ) : String;
// Formatação
Function FormataDATA( cDado : String ) : String;
Function FormataCEP( cDado : String ) : String;
Function FormataFone( cDado : String ) : String;
// CPF e CNPJ
Function FCPF( xCPF : String ) : Boolean;
Function FCNPJ( xCNPJ : String ) : Boolean;
Function FCPFCNPJ( xDado : String ) : String;
// Impressao
Function PreparaTexto( Texto: String ) : String;
Function Centralizar( cDado : String ; nEspaco : Integer ) : String;
Function FormataEspaco( cDado : String ; nEspaco : Integer ) : String;
implementation
Function Encrypt( cSenha : String ) : String;
Const
cChave : String = 'Jesus';
Var
x, y : Integer;
cNova : String;
Begin
For X := 1 To Length( cChave ) Do
Begin
cNova := '';
For Y := 1 To Length( cSenha ) do
cNova := cNova + Chr( ( Ord( cChave[x] ) xor Ord( cSenha[y] ) ) );
cSenha := cNova;
End;
Result := cSenha;
End;
Function EncDecStr( StrValue : String; Chave: Word ) : String;
var
I: Integer;
OutValue : String;
begin
OutValue := '';
for I := 1 to Length( StrValue ) do
OutValue := OutValue + char( ( ord( StrValue[ I ] ) - Chave ) );
// OutValue := OutValue + char( Not ( ord( StrValue[ I ] ) - Chave ) ); // Not // <- Erro, gera dados como um Trojan.
Result := OutValue;
end;
function Criptografa( mStr, mChave: string ): string;
var
i, TamanhoString, pos, PosLetra, TamanhoChave: Integer;
begin
Result := mStr;
TamanhoString := Length( mStr );
TamanhoChave := Length( mChave );
for i := 1 to TamanhoString do
begin
pos := ( i mod TamanhoChave );
if pos = 0 then
pos := TamanhoChave;
PosLetra := ord( Result[ i ] ) xor ord( mChave[ pos ] );
if PosLetra = 0 then
PosLetra := ord( Result[ i ] );
Result[i] := chr( PosLetra );
end;
end;
Function GravarIni( cArquivo, cSecao, cIdentificador, cValor : String ) : Boolean;
Var cArqIni : TIniFile;
begin
cArqIni := TIniFile.Create( cArquivo );
try
cArqIni.WriteString( cSecao, cIdentificador, cValor );
Result := True;
except
ShowMessage( 'Não foi possível gravar no arquivo: ' + cArquivo );
Result := False;
end;
cArqIni.Free;
end;
Function LerIni( cArquivo, cSecao, cIdentificador : String ) : String;
Var
cArqIni : TIniFile;
begin
cArqIni := TIniFile.Create( cArquivo );
result := cArqIni.ReadString( cSecao, cIdentificador, '' );
cArqIni.Free;
end;
Function Virgula_por_Ponto( cValor : String ) : String;
Var
i : Integer;
cVal : String;
begin
cVal := cValor;
If cVal <> ' ' Then
Begin
For i := 1 To Length( cValor ) do
Begin
If cVal[i] = '.' Then cVal[i] := ','
Else
If cVal[i] = ',' Then cVal[i] := '.';
End;
End;
Result := cVal;
end;
Function GetNumeros( sStrn: String ): String;
var i: integer;
sResult, sLetra: String;
begin
for i := 1 to Length( sStrn ) do
begin
sLetra := Copy( sStrn, i, 1 );
if ( sLetra > Chr( 47 ) ) and ( sLetra < Chr( 58 ) ) and ( sLetra <> '.' ) and ( sLetra <> '-' ) and ( sLetra <> '/' ) then
sResult := sResult + sLetra;
end;
Result := sResult;
end;
Function TiraFormatacao( cValor : String ) : String;
Var
i : Integer;
cRet : String;
Begin
cRet := '';
for i := 1 to Length( cValor ) do
begin
If Copy( cValor, i, 1 ) <> ',' Then cRet := cRet + Copy( cValor, i, 1 );
If Copy( cValor, i, 1 ) <> '.' Then cRet := cRet + Copy( cValor, i, 1 );
If Copy( cValor, i, 1 ) <> 'R' Then cRet := cRet + Copy( cValor, i, 1 );
If Copy( cValor, i, 1 ) <> '$' Then cRet := cRet + Copy( cValor, i, 1 );
end;
Result := cRet;
End;
Function StrZero( nVariavel, nTamanho : Integer ) : String;
Var
nValor, i : Integer;
cZeros : String;
begin
nValor := nVariavel;
cZeros := '';
If ( nTamanho - Length( IntToStr( nValor ))) > 0 Then
Begin
For i := 1 To ( nTamanho - Length( IntToStr( nValor ))) do
cZeros := cZeros + '0';
End;
Result := cZeros + IntToStr( nValor );
end;
Function IsInteger( TestaString: String ) : boolean;
begin
Result := True;
try
StrToInt( TestaString );
except
On EConvertError do
Result := False;
end;
end;
Function InverteData( dData : String ) : String;
Var
cData : String;
Begin
cData := GetNumeros( dData );
Result := '';
If cData <> '' Then
Result := Copy( cData, 3, 2 ) + '/' + Copy( cData, 1, 2 ) + '/' + Copy( cData, 5, 4 );
End;
Function InverteDataIB( dData : String ) : String;
Var
cData : String;
Begin
cData := GetNumeros( dData );
Result := '';
If cData <> '' Then
Result := Copy( cData, 5, 4 ) + '/' + Copy( cData, 3, 2 ) + '/' + Copy( cData, 1, 2 );
End;
// Exibe a data por extenso.
Function DataExtenso( Data:TDateTime ): String;
var
NoDia : Integer;
// Now: TdateTime;
DiaDaSemana : array [1..7] of String;
Meses : array [1..12] of String;
Dia, Mes, Ano : Word;
begin
DiaDasemana [1] := 'Domingo';
DiaDasemana [2] := 'Segunda-feira';
DiaDasemana [3] := 'Terça-feira';
DiaDasemana [4] := 'Quarta-feira';
DiaDasemana [5] := 'Quinta-feira';
DiaDasemana [6] := 'Sexta-feira';
DiaDasemana [7] := 'Sábado';
Meses [1] := 'Janeiro';
Meses [2] := 'Fevereiro';
Meses [3] := 'Março';
Meses [4] := 'Abril';
Meses [5] := 'Maio';
Meses [6] := 'Junho';
Meses [7] := 'Julho';
Meses [8] := 'Agosto';
Meses [9] := 'Setembro';
Meses [10] := 'Outubro';
Meses [11] := 'Novembro';
Meses [12] := 'Dezembro';
DecodeDate (Data, Ano, Mes, Dia);
NoDia := DayOfWeek (Data);
Result := DiaDaSemana [NoDia] + ', ' + inttostr (Dia) + ' de ' + Meses [Mes]+ ' de ' + inttostr (Ano);
end;
Function UltDiaDoMes( Data: TDateTime ): Word; // Retorna o Ultimo dia do mes de uma determinada data.
var
d, m, a : Word;
dt : TDateTime;
begin
DecodeDate( Data, a, m, d );
Inc( m );
if m = 13 then
begin
m := 1;
end;
dt := EncodeDate( a, m, 1 );
dt := dt - 1;
DecodeDate( dt, a, m, d );
Result := d;
end;
Function DateMais( Dat : TDateTime ; Numdias : Integer ) : TDateTime; { Soma um determinado número de dias à data atual }
begin
Dat := Dat + Numdias;
Result := Dat;
end;
Function DateMenos( Dat : TDateTime ; Numdias : Integer ) : TDateTime; { Subtrai um determinado número de dias à data atual }
begin
Dat := Dat - Numdias;
Result := Dat;
end;
Function NomedoMes( dData : TDateTime ) : String;
var
d, m, a : Word;
cM : String;
begin
DecodeDate( dData, a, m, d );
case m of
1: cM := 'Janeiro';
2: cM := 'Fevereiro';
3: cM := 'Março';
4: cM := 'Abril';
5: cM := 'Maio';
6: cM := 'Junho';
7: cM := 'Julho';
8: cM := 'Agosto';
9: cM := 'Setembro';
10: cM := 'Outubro';
11: cM := 'Novembro';
12: cM := 'Dezembro';
Else cM := '';
end;
Result := cM;
End;
Procedure Formato_de_Data;
Begin
If Not ( Pos( 'dd/MM/yyyy', ShortDateFormat ) > 0 ) Then
Begin
WinExec( 'RunDLL32.exe Shell32.DLL, Control_RunDLL intl.cpl', SW_Show );
MessageDlg( 'O Formato de "Data" configurado não é correto'#13'' +
'para uso no Sistema.'#13''+
''#13''+
'Formato atual: "'+ ShortDateFormat + '"'#13''+
''#13''+
'Formato correto a ser utilizado: "dd/MM/aaaa".'#13''+
''#13''+
'A Janlea exibida:'#13''+
'"Opções Regionais e de Idioma".'#13''+
'Deve ser utilizada para configuração do formato correto.'#13''+
'Favor clicar no Botão "Personalizar",'#13''+
'Logo após clicar na Guia "Data"'#13''+
'Alterar o formato em:'#13''+
'"Formato de Data Abreviada", para: "dd/MM/aaaa"'#13''+
'para ativar esta configuração.'#13'' +
'Depois clicar em "Aplicar" e depois "OK".'#13'' +
'E novamente clicar em "Aplicar" e depois "OK".'#13'' +
''#13''+
'Logo após execute novamente o Sistema.'#13'',
mtInformation, [ mbOK ], 0 );
Application.Terminate;
End;
End;
Function AnoBixesto( Data: TDateTime ) : Boolean; {Testa se um ano é bixesto, retornando True em caso positivo}
Var
Dia, Mes, Ano : Word;
Begin
DecodeDate( Data, Ano, Mes, Dia );
If Ano mod 4 <> 0 Then
Begin
Result := False;
End
Else
If Ano mod 100 <> 0 Then
Begin
Result := True;
End
Else
If Ano mod 400 <> 0 Then
Begin
Result := False;
End
Else
Begin
Result := True;
End;
End;
Function BiosDate : String; // Retorna a data da fabricação do Chip da Bios do sistema
Begin
Result := String( pchar( ptr( $FFFF5 ) ) );
End;
Function DriveLetters: string; { Uso: S := tbDriveLetters; - retorna 'ACD' se existir as unidades: A:, C: e D: }
var
Drives: LongWord;
I: byte;
begin
Result := '';
Drives := GetLogicalDrives;
if Drives <> 0 then
for I := 65 to 90 do
if ((Drives shl (31 - (I - 65))) shr 31) = 1 then
Result := Result + Char(I);
end;
Function SerialNum( FDrive : String ) : String;
Var
Serial:DWord;
DirLen,Flags: DWord;
DLabel : Array[0..11] of Char;
begin
Try GetVolumeInformation( PChar( FDrive + ':\' ), dLabel, 12, @Serial, DirLen, Flags, nil, 0 );
Result := IntToHex( Serial, 8 ); // + ' ' + IntToStr( Serial ); // o 1º é o nº Hexadecimal o 2º o inteiro.
Except
Result :='';
end;
end;
function VolInfo(const Drive: Char; Path: PChar): TVolInfo; { Uso: Info := VolInfo('A', nil); ou Info := VolInfo(#0, '\\computador\c\'); }
const
cVolNameLen = 255;
cSysNameLen = 255;
var
Flags, PrevErrorMode: Cardinal;
begin
if Path = nil then
Path := PChar(Drive + ':\');
SetLength( Result.Name, cVolNameLen );
SetLength( Result.FileSysName, cSysNameLen );
PrevErrorMode := SetErrorMode( SEM_FAILCRITICALERRORS );
try
if GetVolumeInformation( Path, PChar( Result.Name ), cVolNameLen,
@Result.Serial, Result.MaxCompLen, Flags,
PChar( Result.FileSysName ), cSysNameLen ) then
begin
Result.Name := string( PChar( Result.Name ) );
Result.FileSysName := string( PChar( Result.FileSysName ) );
Result.IsCompressed := ( Flags and FS_VOL_IS_COMPRESSED ) > 0;
end
else
begin
Result.Name := '';
Result.Serial := 0;
Result.IsCompressed := false;
Result.MaxCompLen := 0;
Result.FileSysName := '';
end;
finally
SetErrorMode(PrevErrorMode);
end;
end;
function NomeComputador : String;
var
lpBuffer : PChar;
nSize : DWord;
const Buff_Size = MAX_COMPUTERNAME_LENGTH + 1;
begin
nSize := Buff_Size;
lpBuffer := StrAlloc(Buff_Size);
GetComputerName(lpBuffer,nSize);
Result := String(lpBuffer);
StrDispose(lpBuffer);
end;
Function GetIP : string; //--> Declare a Winsock na clausula uses da unit
var
WSAData : TWSAData;
HostEnt : PHostEnt;
Name :string;
begin
WSAStartup(2, WSAData);
SetLength(Name, 255);
Gethostname(PChar(Name), 255);
SetLength(Name, StrLen(PChar(Name)));
HostEnt := gethostbyname(PChar(Name));
with HostEnt^ do
Result := Format( '%d.%d.%d.%d',
[Byte(h_addr^[0]),
Byte(h_addr^[1]),
Byte(h_addr^[2]),
Byte(h_addr^[3])] );
WSACleanup;
end;
Function VerificaRegistro( cUnidade: String ): Boolean;
Var
cReg : TRegistry;
cSrl, cSrr, cChv : String;
lRet : Boolean;
vi : TVolInfo;
begin
lRet := True;
vi := VolInfo( #0, PChar( cUnidade + ':\' ) );
cSrl := SerialNum( cUnidade ) + IntToStr( vi.Serial );
cSrr := EncDecStr( cSrl, 1 );
cReg := TRegistry.Create;
cReg.RootKey := HKEY_LOCAL_MACHINE;
cReg.OpenKeyReadOnly( 'software\HSO_Servico' );
cChv := cReg.ReadString( 'Chave_Liberacao' );
cReg.Free;
cSrl := Copy( cSrl, 1, 4 ) + ' ' +
Copy( cSrl, 5, 4 ) + ' ' +
Copy( cSrl, 9, 4 ) + ' ' +
Copy( cSrl, 13, 4 ) + ' ' +
Copy( cSrl, 17, 2 );
If cSrl <> cChv Then
Begin
// cSerial := Copy( cSrr, 13, 4 ) + ' ' +
// Copy( cSrr, 9, 4 ) + ' ' +
// Copy( cSrr, 1, 4 ) + ' ' +
// Copy( cSrr, 5, 4 ) + ' ' +
// Copy( cSrr, 17, 2 ) +
// ''#13'';
lRet := False;
End;
Result := lRet;
end;
Function FBoolToStr( Check : Boolean ) : String; // Converte de Boolean para String
begin
If Check then Result := 'T'
Else Result := 'F';
end;
Function FStrToBool( Valor : string ) : Boolean; // Converte de String para Boolean
begin
Result := UpperCase( Trim( Valor ) ) = 'T'
end;
Function ControlaCampoTexto( cDado : String ) : String;
Begin
If cDado = '' Then
Result := 'NULL'
Else
If UpperCase( cDado ) = 'NULL' Then
Result := ''
Else
Result := cDado;
End;
Function CampoInforme( cDado : String ) : String;
Begin
If cDado = '' Then
Result := 'NÃO INFORMADO';
End;
Function Iif( cDado, cCheck, cValor1, cValor2 : String ) : String;
Begin
if cDado = cCheck then
Result := cValor1
else
Result := cValor2;
End;
function AbreviaNome( Nome: String ): String;
var
Nomes: array[1..20] of string;
i, TotalNomes: Integer;
begin
Nome := Trim(Nome);
Result := Nome;
Nome := Nome + #32; {Insere um espaço para garantir que todas as letras sejam testadas}
i := Pos(#32, Nome); {Pega a posição do primeiro espaço}
if i > 0 then
begin
TotalNomes := 0;
while i > 0 do {Separa todos os nomes}
begin
Inc(TotalNomes);
Nomes[TotalNomes] := Copy(Nome, 1, i - 1);
Delete(Nome, 1, i);
i := Pos(#32, Nome);
end;
if TotalNomes > 2 then
begin
for i := 2 to TotalNomes - 1 do {Abreviar a partir do segundo nome, exceto o último.}
begin
if Length(Nomes[i]) > 3 then {Contém mais de 3 letras? (ignorar de, da, das, do, dos, etc.)}
Nomes[i] := Nomes[i][1] + '.';{Pega apenas a primeira letra do nome e coloca um ponto após.}
end;
Result := '';
for i := 1 to TotalNomes do
Result := Result + Trim(Nomes[i]) + #32;
Result := Trim(Result);
end;
end;
end;
Function FormataDATA( cDado : String ) : String;
Var
i : Integer;
cTemp : String;
Dia, Mes, Ano : Word;
Begin
cTemp := '';
for i := 1 to Length( cDado ) do
begin
if Pos( Copy( cDado, i, 1 ), '/' ) = 0 then
begin
cTemp := cTemp + Copy( cDado, i, 1 );
end;
end;
cDado := cTemp;
DecodeDate ( Now , Ano, Mes, Dia );
Case Length( cDado ) Of
6 : Result := Copy( cDado, 1, 2 ) + '/' + Copy( cDado, 3, 2 ) + '/' + Copy( IntToStr( Ano ), 1, 2 ) + Copy( cDado, 5, 2 );
8 : Result := Copy( cDado, 1, 2 ) + '/' + Copy( cDado, 3, 2 ) + '/' + Copy( cDado, 5, 4 );
Else
Begin
ShowMessage( 'Favor informar a data'#13'No formato: DDMMAAAA'#13'Sem as barras.' );
Result := '';
End;
End;
End;
Function FormataCEP( cDado : String ) : String;
Begin
If Length( cDado ) = 8 Then Result := Copy( cDado, 1, 2 ) + '.' + Copy( cDado, 3, 3 ) + '-' + Copy( cDado, 6, 3 )
Else Result := cDado;
End;
Function FormataFone( cDado : String ) : String;
Begin
If Length( cDado ) = 8 Then Result := Copy( cDado, 1, 4 ) + '-' + Copy( cDado, 5, 4 )
Else Result := cDado;
End;
Function FCPF( xCPF : String ) : Boolean; {Testa se o CPF é válido ou não}
Var
d1, d4, xx, nCount, resto, digito1, digito2 : Integer;
Check : String;
Begin
d1 := 0; d4 := 0; xx := 1;
for nCount := 1 to Length( xCPF ) - 2 do
begin
if Pos( Copy( xCPF, nCount, 1 ), '/-.' ) = 0 then
begin
d1 := d1 + ( 11 - xx ) * StrToInt( Copy( xCPF, nCount, 1 ) );
d4 := d4 + ( 12 - xx ) * StrToInt( Copy( xCPF, nCount, 1 ) );
xx := xx+1;
end;
end;
resto := (d1 mod 11);
if resto < 2 then
begin
digito1 := 0;
end
else
begin
digito1 := 11 - resto;
end;
d4 := d4 + 2 * digito1;
resto := (d4 mod 11);
if resto < 2 then
begin
digito2 := 0;
end
else
begin
digito2 := 11 - resto;
end;
Check := IntToStr( Digito1 ) + IntToStr( Digito2 );
if Check <> copy( xCPF, succ( length( xCPF ) - 2 ), 2 ) then
begin
Result := False;
end
else
begin
Result := True;
end;
end;
Function FCNPJ( xCNPJ : String ) : Boolean; {Testa se o CGC é válido ou não}
Var
d1, d4, xx, nCount, fator, resto, digito1, digito2 : Integer;
Check : String;
begin
d1 := 0; d4 := 0; xx := 1;
for nCount := 1 to Length( xCNPJ )-2 do
begin
if Pos( Copy( xCNPJ, nCount, 1 ), '/-.' ) = 0 then
begin
if xx < 5 then
begin
fator := 6 - xx;
end
else
begin
fator := 14 - xx;
end;
d1 := d1 + StrToInt( Copy( xCNPJ, nCount, 1 ) ) * fator;
if xx < 6 then
begin
fator := 7 - xx;
end
else
begin
fator := 15 - xx;
end;
d4 := d4 + StrToInt( Copy( xCNPJ, nCount, 1 ) ) * fator;
xx := xx+1;
end;
end;
resto := ( d1 mod 11 );
if resto < 2 then
begin
digito1 := 0;
end
else
begin
digito1 := 11 - resto;
end;
d4 := d4 + 2 * digito1;
resto := ( d4 mod 11 );
if resto < 2 then
begin
digito2 := 0;
end
else
begin
digito2 := 11 - resto;
end;
Check := IntToStr( Digito1 ) + IntToStr( Digito2 );
if Check <> copy( xCNPJ, succ( length( xCNPJ ) - 2 ), 2 ) then
begin
Result := False;
end
else
begin
Result := True;
end;
end;
Function FCPFCNPJ( xDado : String ) : String;
Var
r : String;
Begin
r := '';
xDado := GetNumeros( xDado );
If FCPF( xDado ) Then
Begin
r := Copy( xDado, 1, 3 ) + '.' +
Copy( xDado, 4, 3 ) + '.' +
Copy( xDado, 7, 3 ) + '-' +
Copy( xDado, 10, 2 );
End
Else
Begin
If FCNPJ( xDado ) Then
Begin
r := Copy( xDado, 1, 2 ) + '.' +
Copy( xDado, 3, 3 ) + '.' +
Copy( xDado, 6, 3 ) + '/' +
Copy( xDado, 9, 4 ) + '-' +
Copy( xDado, 13, 2 );
End
Else
Begin
ShowMessage( 'O Número informado não é um CPF ou CNPJ' );
End;
End;
Result := r;
End;
Function PreparaTexto( Texto : String ): String;
var
I: integer;
T: String;
begin
T := '';
// Substitui os caracteres acentuados por caracteres normais,
// usando o BackSpace (#8) para simular acentuações. Por exemplo,
// o caractere "ã" é trocado por "a" + BackSpace + "~". Como resultado,
// o caractere "~" será impresso em cima do caractere "~".
for I := 1 to Length(Texto) do
Case Texto[I] of
'á': T := T + 'a' + #8 + #39;
'Á': T := T + 'A' + #8 + #39;
'à': T := T + 'a' + #8 + '`';
'À': T := T + 'A' + #8 + '`';
'ã': T := T + 'a' + #8 + '~';
'Ã': T := T + 'A' + #8 + '~';
'â': T := T + 'a' + #8 + '^';
'Â': T := T + 'A' + #8 + '^';
'é': T := T + 'e' + #8 + #39;
'É': T := T + 'E' + #8 + #39;
'ê': T := T + 'e' + #8 + '^';
'Ê': T := T + 'E' + #8 + '^';
'í': T := T + 'i' + #8 + #39;
'Í': T := T + 'I' + #8 + #39;
'ó': T := T + 'o' + #8 + #39;
'Ó': T := T + 'O' + #8 + #39;
'õ': T := T + 'o' + #8 + '~';
'Õ': T := T + 'O' + #8 + '~';
'ô': T := T + 'o' + #8 + '^';
'Ô': T := T + 'O' + #8 + '^';
'ú': T := T + 'u' + #8 + #39;
'Ú': T := T + 'U' + #8 + #39;
'ç': T := T + 'c' + #8 + ',';
'Ç': T := T + 'C' + #8 + ',';
else
T := T + Texto[I];
end;
Result := T;
end;
Function Centralizar( cDado : String ; nEspaco : Integer ) : String;
Var
cEspacos : String;
nMedia, i, nSobra : Integer;
Begin
cEspacos := '';
nMedia := Round( ( nEspaco - Length( cDado ) ) / 2 );
nSobra := nEspaco - ( nMedia + Length( cDado ) ) - 1;
For i := 1 to nMedia do
Begin
cEspacos := cEspacos + ' ';
End;
cDado := cEspacos + cDado + ' ';
For i := 1 to nSobra do
Begin
cDado := cDado + ' ';
End;
Result := cDado;
End;
Function FormataEspaco( cDado : String ; nEspaco : Integer ) : String;
Var
cEspacos : String;
nFalta, i : Integer;
Begin
cEspacos := '';
nFalta := nEspaco - Length( cDado );
For i := 1 to nFalta do
Begin
cEspacos := cEspacos + ' ';
End;
cDado := cEspacos + cDado;
Result := cDado;
End;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Executing functions in a thread.
Copyright (C) 2009-2011 Przemysław Nagay (cobines@gmail.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
}
unit uFunctionThread;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, syncobjs;
type
TFunctionThreadMethod = procedure(Params: Pointer) of object;
PFunctionThreadItem = ^TFunctionThreadItem;
TFunctionThreadItem = record
Method: TFunctionThreadMethod;
Params: Pointer;
end;
TFunctionThread = class(TThread)
private
FFunctionsToCall: TFPList;
FWaitEvent: PRTLEvent;
FLock: TCriticalSection;
FFinished: Boolean;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean); reintroduce;
destructor Destroy; override;
procedure QueueFunction(AFunctionToCall: TFunctionThreadMethod; AParams: Pointer = nil);
procedure Finish;
class procedure Finalize(var AThread: TFunctionThread);
property Finished: Boolean read FFinished;
end;
implementation
uses
LCLProc, uDebug, uExceptions
{$IFDEF MSWINDOWS}
, ActiveX
{$ENDIF}
;
constructor TFunctionThread.Create(CreateSuspended: Boolean);
begin
FWaitEvent := RTLEventCreate;
FFunctionsToCall := TFPList.Create;
FLock := TCriticalSection.Create;
FFinished := False;
FreeOnTerminate := False;
inherited Create(CreateSuspended, DefaultStackSize);
end;
destructor TFunctionThread.Destroy;
var
i: Integer;
begin
RTLeventdestroy(FWaitEvent);
FLock.Acquire;
for i := 0 to FFunctionsToCall.Count - 1 do
Dispose(PFunctionThreadItem(FFunctionsToCall[i]));
FLock.Release;
FreeThenNil(FFunctionsToCall);
FreeThenNil(FLock);
inherited Destroy;
end;
procedure TFunctionThread.QueueFunction(AFunctionToCall: TFunctionThreadMethod; AParams: Pointer);
var
pItem: PFunctionThreadItem;
begin
if (not Terminated) and Assigned(AFunctionToCall) then
begin
New(pItem);
pItem^.Method := AFunctionToCall;
pItem^.Params := AParams;
FLock.Acquire;
try
FFunctionsToCall.Add(pItem);
finally
FLock.Release;
end;
RTLeventSetEvent(FWaitEvent);
end;
end;
procedure TFunctionThread.Finish;
begin
Terminate;
RTLeventSetEvent(FWaitEvent);
end;
procedure TFunctionThread.Execute;
var
pItem: PFunctionThreadItem;
begin
{$IFDEF MSWINDOWS}
CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
{$ENDIF}
try
while (not Terminated) or (FFunctionsToCall.Count > 0) do
begin
RTLeventResetEvent(FWaitEvent);
pItem := nil;
FLock.Acquire;
try
if FFunctionsToCall.Count > 0 then
begin
pItem := PFunctionThreadItem(FFunctionsToCall[0]);
FFunctionsToCall.Delete(0);
end;
finally
FLock.Release;
end;
if Assigned(pItem) then
begin
try
pItem^.Method(pItem^.Params);
Dispose(pItem);
except
on e: Exception do
begin
Dispose(pItem);
HandleException(e, Self);
end;
end;
end
else
begin
RTLeventWaitFor(FWaitEvent);
end;
end;
finally
{$IFDEF MSWINDOWS}
CoUninitialize;
{$ENDIF}
FFinished := True;
end;
end;
class procedure TFunctionThread.Finalize(var AThread: TFunctionThread);
begin
AThread.Finish;
{$IF (fpc_version<2) or ((fpc_version=2) and (fpc_release<5))}
If (MainThreadID=GetCurrentThreadID) then
while not AThread.Finished do
CheckSynchronize(100);
{$ENDIF}
AThread.WaitFor;
AThread.Free;
AThread := nil;
end;
end.
|
{ ******************************************************************************
___ __ ____ _ _ _ ____ __ ____ ____ ____
/ __)/ \( _ \( \/ ) / ) ( _ \ / _\ / ___)(_ _)( __)
( (__( O )) __/ ) / / / ) __// \\___ \ )( ) _)
\___)\__/(__) (__/ (_/ (__) \_/\_/(____/ (__) (____)
Application Monitor Control unit
Components:
TCopyApplicationMonitor = This control is application wide and will
contain the overall tracked clipboard.
Functions:
Register = Registers the control
Conditional Defines:
CPLOG = If the CPLOG conditional define is set then when a log file of the
Copy/Paste process is created and saved in the user's
AppData\Local\[Application name] folder. A document is created per
process.
{ ****************************************************************************** }
unit U_CPTAppMonitor;
interface
uses
U_CptUtils, U_CPTCommon, System.Classes, System.SyncObjs, Vcl.Graphics,
Vcl.ExtCtrls, U_CPTExtended, System.SysUtils,
System.Math, Vcl.Dialogs, System.UITypes, System.IniFiles,
Winapi.Windows, Vcl.Forms, Winapi.TlHelp32, IdHashSHA;
Type
/// <summary>This is the "overall" component. Each instance of <see cref="U_CPTPasteDetails|TCopyEditMonitor" /> and/or <see cref="CopyMonitor|TCopyPasteDetails" /> will send into this.
/// This control holds the collection of text that was copied so that each monitor can interact with it</summary>
TCopyApplicationMonitor = class(TComponent)
private
/// <summary><para>Clipboard custom format for copy/paste</para><para><b>Type: </b><c>Word</c></para></summary>
CF_CopyPaste: Word;
/// <summary><para>Number of characters that will halt the highlight from the background</para><para><b>Type: </b><c>Integer</c></para></summary>
// FBackGroundLimit: Integer;
/// <summary><para>Number of characters to break up long lines at</para><para><b>Type: </b><c>Integer</c></para></summary>
FBreakUpLimit: Integer;
/// <summary><para>Holds all records of copied/pasted text</para>
/// <para><b>Type: </b><c>Array of <see cref="U_CPTCommon|TCprsClipboard" /></c></para></summary>
FCPRSClipBoard: CprsClipboardArry;
/// <summary><para>Controls the critical section for the thread</para><para><b>Type: </b><c>TCriticalSection</c></para></summary>
FCriticalSection: TCriticalSection;
/// <summary><para>Controls if the user can see paste details</para><para><b>Type: </b><c>Boolean</c></para></summary>
FDisplayPaste: Boolean;
fSuperUser: Boolean;
FSaveCutOff: Double;
FCompareCutOff: Integer;
/// <summary><para>List of applications to exlude from the past tracking</para><para><b>Type: </b><c>TStringList</c></para></summary>
fExcludeApps: TStringList;
/// <summary><para>Color used to highlight the matched text</para><para><b>Type: </b><c>TColor</c></para></summary>
FHighlightColor: TColor;
/// <summary><para>External load buffer event</para><para><b>Type: </b><c><see cref="U_CPTCommon|TLoadEvent" /></c></para></summary>
FLoadBuffer: TLoadBuffEvent;
/// <summary><para>Flag that indicates if the buffer has been loaded</para><para><b>Type: </b><c>Boolean</c></para></summary>
FLoadedBuffer: Boolean;
fBufferTimer: TTimer;
FBufferPolled: Boolean;
/// <summary><para>Flag that indicates if the buffer will be used to save and load prior session data</para><para><b>Type: </b><c>Boolean</c></para></summary>
fBufferEnabled: Boolean;
/// <summary><para>Flag that indicates if the buffer will store hash value representation of the copy text</para><para><b>Type: </b><c>Boolean</c></para></summary>
fHashBuffer: Boolean;
/// <summary><para>List that can be used to hold excluded information (ie note IENs)</para><para><b>Type: </b><c>TStringList</c></para></summary>
fExcludedList: TStringList;
fStartPollBuff: TPollBuff;
fStopPollBuff: TPollBuff;
fBufferTryLimit: Integer;
fLCSToggle: Boolean;
fLCSCharLimit: Integer;
FLCSTextColor: TColor;
FLCSTextStyle: TFontStyles;
FLCSUseColor: Boolean;
fPasteLimit: Integer;
fpSHA: TIdHashSHA1;
/// <summary><para>External load properties event</para><para><b>Type: </b><c><see cref="U_CPTCommon|TLoadProperties" /></c></para></summary>
FOnLoadProperties: TLoadProperties;
/// <summary><para>Flag indicates if properties have been loaded</para><para><b>Type: </b><c>Boolean</c></para></summary>
FLoadedProperties: Boolean;
fEnabled: Boolean;
FLogObject: TLogComponent;
/// <summary><para>Flag to display highlight when match found</para><para><b>Type: </b><c>Boolean</c></para></summary>
FMatchHighlight: Boolean;
/// <summary><para>Style to use for the matched text font</para><para><b>Type: </b><c>TFontStyles</c></para></summary>
FMatchStyle: TFontStyles;
/// <summary><para>The monitoring application name</para><para><b>Type: </b><c>string</c></para></summary>
FMonitoringApplication: string;
/// <summary><para>The monitoring application's package</para><para><b>Type: </b><c>string</c></para></summary>
FMonitoringPackage: string;
/// <summary><para>Number of words used to trigger copy/paste functionality</para><para><b>Type: </b><c>Double</c></para></summary>
FNumberOfWords: Double;
/// <summary><para>Percent used to match pasted text</para><para><b>Type:</b> <c>Double</c></para></summary>
FPercentToVerify: Double;
/// <summary><para>External save buffer event</para><para><b>Type: </b><c><see cref="U_CPTCommon|TSaveEvent" /></c></para></summary>
FSaveBuffer: TSaveEvent;
/// <summary><para>Stop Watch for metric information</para><para><b>Type: </b><c><see cref="U_CPTUtils|TStopWatch" /></c></para></summary>
fStopWatch: TStopWatch;
/// <summary><para>The current users DUZ</para><para><b>Type: </b><c>Int64</c></para></summary>
FUserDuz: Int64;
/// <summary><para>checks if should be exlcuded</para><para><b>Type: </b><c>Integer</c></para></summary>
/// <param name="AppName">AppName<para><b>Type: </b><c>String</c></para></param>
/// <returns><para><b>Type: </b><c>Boolean</c></para> - </returns>
function FromExcludedApp(AppName: String): Boolean;
procedure SetEnabled(aValue: Boolean);
function GetEnabled: Boolean;
procedure SetLoadedProperties(aValue: Boolean);
function GetLoadedProperties: Boolean;
function GetExcludedList(): TStringList;
function GetOnLoadProperties: TLoadProperties;
procedure SetOnLoadProperties(const Value: TLoadProperties);
function GetMatchStyle: TFontStyles;
procedure SetMatchStyle(const Value: TFontStyles);
function GetMatchHighlight: Boolean;
procedure SetMatchHighlight(const Value: Boolean);
function GetLoadedBuffer: Boolean;
procedure SetLoadedBuffer(const Value: Boolean);
function GetHighlightColor: TColor;
procedure SetHighlightColor(const Value: TColor);
function GetDisplayPaste: Boolean;
procedure SetDisplayPaste(const Value: Boolean);
function GetBufferEnabled: Boolean;
procedure SetBufferEnabled(const Value: Boolean);
function GetBufferPolled: Boolean;
procedure SetBufferPolled(const Value: Boolean);
function GetBufferTimer: TTimer;
procedure SetBufferTimer(const Value: TTimer);
function GetStartPollBuff: TPollBuff;
procedure SetStartPollBuff(const Value: TPollBuff);
function GetBufferTryLimit: Integer;
procedure SetBufferTryLimit(const Value: Integer);
function GetStopPollBuff: TPollBuff;
procedure SetStopPollBuff(const Value: TPollBuff);
function GetLoadBuffer: TLoadBuffEvent;
procedure SetLoadBuffer(const Value: TLoadBuffEvent);
function GetCPRSClipBoard: CprsClipboardArry;
public
/// <summary><para>Holds list of currently running threads</para><para><b>Type: </b><c>Array of <see cref="U_CPTExtended|tCopyPasteThread" /></c></para></summary>
FCopyPasteThread: TCopyPasteThreadArry;
/// <summary><para>List of paste details (panels) to keep in size sync</para><para><b>Type: </b><c>Array of TPanel</c></para></summary>
fSyncSizeList: TPanelArry;
/// <summary>Number of characters that will halt the highlight from the background</summary>
// Property BackGroundLimit: Integer read FBackGroundLimit
// write FBackGroundLimit;
/// <summary>Clear out all SaveForDocument parameters</summary>
procedure ClearCopyPasteClipboard();
/// <summary>Adds the text being copied to the <see cref="U_CPTCommon|TCprsClipboard" /> array and to the clipboard with details</summary>
/// <param name="TextToCopy">Copied text<para><b>Type: </b><c>string</c></para></param>
/// <param name="FromName">Copied text's package<para><b>Type: </b><c>string</c></para></param>
/// <param name="ItemID">ID of document the text was copied from<para><b>Type: </b><c>Integer</c></para></param>
procedure CopyToCopyPasteClipboard(TextToCopy, FromName: string;
ItemID: Int64);
Property CFCopyPaste: Word Read CF_CopyPaste;
/// <summary>Constructor</summary>
/// <param name="AOwner">Object that is calling this</param>
constructor Create(AOwner: TComponent); override;
/// <summary>CriticalSection</summary>
property CriticalSection: TCriticalSection read FCriticalSection;
/// <summary>Destructor</summary>
destructor Destroy; override;
/// <summary>Controls if the user can see paste details</summary>
property DisplayPaste: Boolean read GetDisplayPaste write SetDisplayPaste;
property SuperUser: Boolean read fSuperUser write fSuperUser;
/// <summary>List of applications to exclude from tracking</summary>
property ExcludeApps: TStringList read fExcludeApps write fExcludeApps;
property ExcludedList: TStringList read GetExcludedList;
/// <summary><para>Get the owner (if applicable) from the clipboard</para><para><b>Type: </b><c>Integer</c></para></summary>
/// <returns><para><b>Type: </b><c>tClipInfo</c></para> - </returns>
function GetClipSource(GetLocked: Boolean = false): tClipInfo;
property CPRSClipBoard: CprsClipboardArry Read GetCPRSClipBoard;
/// <summary> Used to calcuate percent </summary>
/// <param name="String1"> Original string </param>
/// <param name="String2"> Compare String </param>
/// <param name="CutOff"> number of character changes to fall in the threshold </param>
/// <returns> Percentage the same </returns>
function LevenshteinDistance(String1, String2: String;
CutOff: Integer): Double;
procedure LoadTheBufferPolled(Sender: TObject);
property LogObject: TLogComponent read FLogObject;
procedure LogText(Action, MessageTxt: String); overload;
procedure LogText(Action: String; MessageTxt: TPasteArray); overload;
property NumberOfWords: Double Read FNumberOfWords write FNumberOfWords;
/// <summary>Perform the lookup of the pasted text and mark as such</summary>
/// <param name="TextToPaste">Text being pasted</param>
/// <param name="PasteDetails">Details from the clipboard</param>
/// <param name="ItemIEN">Destination's IEN </param>
/// <param name="ClipInfo">Clipborad information </param>
procedure PasteToCopyPasteClipboard(TextToPaste, PasteDetails: string;
ItemIEN: Int64; ClipInfo: tClipInfo);
/// <summary><para>Recalculates the percentage after the save</para><para><b>Type: </b><c>Integer</c></para></summary>
/// <param name="ReturnedList">Data that is returned from the save RPC<para><b>Type: </b><c>TStringList</c></para></param>
/// <param name="SaveList">Data that will be transfered back to vista<para><b>Type: </b><c>TStringList</c></para></param>
/// <param name="ExisitingPaste">List of paste that already existed on the document (used for monitoring edits of paste)<para><b>Type: </b><c>array of <see cref="U_CPTCommon|TPasteText" /></c></para></param>
procedure RecalPercentage(ReturnedList: TStringList;
var SaveList: TStringList; ExisitingPaste: TPasteArray);
/// <summary>Saved the copied text for this note</summary>
/// <param name="Sender">Object that is calling this<para><b>Type: </b><c>TComponent</c></para></param>
/// <param name="SaveList">List to save<para><b>Type: </b><c>TStringList</c></para></param>
procedure SaveCopyPasteClipboard(Sender: TComponent; SaveList: TStringList);
Property StopWatch: TStopWatch read fStopWatch;
Function StartStopWatch(): Boolean;
Function StopStopWatch(): Boolean;
procedure IncBufferTryLimit;
/// <summary><para>Sync all the sizes for the marked panels</para><para><b>Type: </b><c>Integer</c></para></summary>
/// <param name="sender">sender<para><b>Type: </b><c>TObject</c></para></param>
procedure SyncSizes(Sender: TObject);
property BufferLoaded: Boolean read GetLoadedBuffer write SetLoadedBuffer;
/// <summary>How many words appear in the text</summary>
/// <param name="TextToCount">Occurences of</param>
/// <returns>Total number of occurences</returns>
function WordCount(TextToCount: string): Integer;
Procedure EnableBuffer(Value: Boolean);
Property PasteLimit: Integer read fPasteLimit;
Property LoadedProperties: Boolean read GetLoadedProperties
Write SetLoadedProperties;
Property BufferTimer: TTimer read GetBufferTimer Write SetBufferTimer;
Property BufferTryLimit: Integer read GetBufferTryLimit
write SetBufferTryLimit;
published
/// <summary><para>where to break the text at</para><para><b>Type: </b>intger</para></summary>
property BreakUpLimit: Integer read FBreakUpLimit write FBreakUpLimit;
/// <summary>Color used to highlight the matched text</summary>
property HighlightColor: TColor read GetHighlightColor
write SetHighlightColor;
/// <summary>Call to load the buffer </summary>
property LoadBuffer: TLoadBuffEvent read GetLoadBuffer write SetLoadBuffer;
/// <summary>Load the copy buffer from VistA</summary>
procedure LoadTheBuffer();
Procedure StopTheBuffer();
/// <summary>External load for the properties</summary>
property LoadProperties: TLoadProperties read GetOnLoadProperties
write SetOnLoadProperties;
/// <summary>External Load Properties</summary>
procedure LoadTheProperties();
/// <summary>Flag to display highlight when match found</summary>
property MatchHighlight: Boolean read GetMatchHighlight
write SetMatchHighlight;
/// <summary>Style to use for the matched text font</summary>
property MatchStyle: TFontStyles read GetMatchStyle write SetMatchStyle;
/// <summary>The application that we are monitoring</summary>
property MonitoringApplication: string read FMonitoringApplication
write FMonitoringApplication;
/// <summary>The package that this application relates to</summary>
property MonitoringPackage: string read FMonitoringPackage
write FMonitoringPackage;
/// <summary>How many words do we start to consider this copy/paste</summary>
property NumberOfWordsToBegin: Double read FNumberOfWords
write FNumberOfWords;
/// <summary>Percent to we consider this copy/paste functionality</summary>
property PercentToVerify: Double read FPercentToVerify
write FPercentToVerify;
/// <summary>Should the buffer call be polled?</summary>
Property PolledBuffer: Boolean read GetBufferPolled write SetBufferPolled;
/// <summary>Is the buffer enabled</summary>
Property BufferEnabled: Boolean read GetBufferEnabled
write SetBufferEnabled;
/// <summary>Do we use a hashed buffer</summary>
property HashBuffer: Boolean read fHashBuffer write fHashBuffer;
/// <summary>Call to save the buffer </summary>
property SaveBuffer: TSaveEvent read FSaveBuffer write FSaveBuffer;
/// <summary>Save copy buffer to VistA</summary>
procedure SaveTheBuffer();
property SaveCutOff: Double read FSaveCutOff write FSaveCutOff;
property CompareCutOff: Integer read FCompareCutOff write FCompareCutOff;
Property StartPollBuff: TPollBuff read GetStartPollBuff
write SetStartPollBuff;
Property StopPollBuff: TPollBuff read GetStopPollBuff write SetStopPollBuff;
property LCSToggle: Boolean read fLCSToggle write fLCSToggle;
property LCSCharLimit: Integer read fLCSCharLimit write fLCSCharLimit;
property LCSUseColor: Boolean read FLCSUseColor write FLCSUseColor;
property LCSTextColor: TColor read FLCSTextColor write FLCSTextColor;
property LCSTextStyle: TFontStyles read FLCSTextStyle write FLCSTextStyle;
/// <summary>The current users DUZ</summary>
property UserDuz: Int64 read FUserDuz write FUserDuz;
Property Enabled: Boolean read GetEnabled write SetEnabled;
end;
procedure Register;
implementation
uses
U_CPTEditMonitor, U_CPTPasteDetails;
procedure Register;
begin
RegisterComponents('Copy/Paste', [TCopyApplicationMonitor]);
end;
{$REGION 'CopyApplicationMonitor'}
procedure TCopyApplicationMonitor.ClearCopyPasteClipboard;
var
I: Integer;
begin
FCriticalSection.Enter;
try
if not Enabled then
Exit;
StartStopWatch;
try
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
FCPRSClipBoard[I].SaveForDocument := false;
FCPRSClipBoard[I].DateTimeOfPaste := '';
FCPRSClipBoard[I].PasteToIEN := -1;
FCPRSClipBoard[I].SaveItemID := -1;
end;
finally
if StopStopWatch then
LogText('METRIC', 'Clear: ' + fStopWatch.Elapsed);
end;
LogText('SAVE', 'Clearing all pasted data that was marked for save');
finally
FCriticalSection.Leave;
end;
end;
Procedure TCopyApplicationMonitor.PasteToCopyPasteClipboard(TextToPaste,
PasteDetails: string; ItemIEN: Int64; ClipInfo: tClipInfo);
var
TextFound, AddItem: Boolean;
I, PosToUSe, CutOff: Integer;
PertoCheck, LastPertToCheck: Double;
CompareText: TStringList;
Len1, Len2: Integer;
aHashString: String;
aMatchFnd: Boolean;
begin
FCriticalSection.Enter;
try
if not Enabled then
Exit;
// load the properties
if not LoadedProperties then
LoadTheProperties;
// load the buffer
if not BufferLoaded then
LoadTheBuffer;
aHashString := fpSHA.HashStringAsHex(TextToPaste);
TextFound := false;
CompareText := TStringList.Create;
try
CompareText.Text := TextToPaste; // Apples to Apples
aMatchFnd := false;
// Direct macthes
StartStopWatch;
try
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if trim(FCPRSClipBoard[I].HashValue) <> '' then
aMatchFnd := FCPRSClipBoard[I].HashValue = aHashString
else if not Assigned(FCPRSClipBoard[I].CopiedText) then
aMatchFnd := false
else if Assigned(FCPRSClipBoard[I].CopiedText) then
aMatchFnd := AnsiSameText(trim(FCPRSClipBoard[I].CopiedText.Text),
trim(CompareText.Text));
If aMatchFnd then
begin
if (FCPRSClipBoard[I].CopiedFromIEN <> ItemIEN) then
begin
FCPRSClipBoard[I].SaveForDocument :=
(FCPRSClipBoard[I].CopiedFromIEN <> ItemIEN);
FCPRSClipBoard[I].DateTimeOfPaste :=
FloatToStr(DateTimeToFMDateTime(Now));
FCPRSClipBoard[I].CopiedFromPackage := FCPRSClipBoard[I]
.CopiedFromPackage; // ????????
FCPRSClipBoard[I].PercentMatch := 100.00;
FCPRSClipBoard[I].PasteToIEN := ItemIEN;
FCPRSClipBoard[I].PasteDBID := -1;
if not Assigned(FCPRSClipBoard[I].CopiedText) then
begin
FCPRSClipBoard[I].CopiedText := TStringList.Create;
FCPRSClipBoard[I].CopiedText.Text := trim(CompareText.Text);
end;
// Log info
LogText('PASTE', 'Direct Match Found');
LogText('PASTE', 'Pasted Text IEN(' + IntToStr(ItemIEN) + ')');
LogText('TEXT', 'Pasted Text:' + #13#10 + CompareText.Text);
LogText('PASTE', 'Matched to Text IEN(' +
IntToStr(FCPRSClipBoard[I].CopiedFromIEN) + '):');
if Assigned(FCPRSClipBoard[I].CopiedText) then
LogText('TEXT', 'Matched to Text: ' + #13#10 +
trim(FCPRSClipBoard[I].CopiedText.Text));
end;
TextFound := true;
Break;
end;
end;
finally
If StopStopWatch then
LogText('METRIC', 'Direct Match: ' + fStopWatch.Elapsed);
end;
// % check or exceed limit
if not TextFound then
begin
// check for text limit
if Length(CompareText.Text) >= PasteLimit then
begin
// never exclude if originated from a tracking app
if Length(PasteDetails) > 0 then
AddItem := true
else
begin
// Check if excluded
AddItem := (not FromExcludedApp(ClipInfo.AppName));
if not AddItem then
LogText('PASTE', 'Excluded Application');
end;
if AddItem then
begin
// Look for the details first
SetLength(FCPRSClipBoard, Length(FCPRSClipBoard) + 1);
with FCPRSClipBoard[High(FCPRSClipBoard)] do
begin
// From tracking app
if Length(PasteDetails) > 0 then
begin
CopiedFromIEN := StrToIntDef(Piece(PasteDetails, '^', 1), -1);
CopiedFromPackage := Piece(PasteDetails, '^', 2);
ApplicationPackage := Piece(PasteDetails, '^', 3);
ApplicationName := Piece(PasteDetails, '^', 4);
PercentMatch := 100.0;
HashValue := aHashString;
LogText('PASTE', 'Paste from cross session - Over Limit ' +
PasteDetails);
LogText('PASTE', 'Added to internal clipboard IEN(-1)');
end
else
begin
// Exceeds the limit set
CopiedFromIEN := -1;
CopiedFromPackage := 'Paste exceeds maximum compare limit.';
if trim(ClipInfo.AppName) <> '' then
CopiedFromPackage := CopiedFromPackage + ' From: ' +
ClipInfo.AppName + ' - ' + ClipInfo.AppTitle;
ApplicationPackage := MonitoringPackage;
ApplicationName := MonitoringApplication;
PercentMatch := 100.0;
HashValue := aHashString;
LogText('PASTE',
'Pasted from outside the tracking - Over Limit (' +
IntToStr(Length(CompareText.Text)) + ')');
LogText('PASTE]', 'Added to internal clipboard IEN(-1)');
end;
PasteToIEN := ItemIEN;
PasteDBID := -1;
DateTimeOfCopy := FloatToStr(DateTimeToFMDateTime(Now));
SaveForDocument := true;
DateTimeOfPaste := FloatToStr(DateTimeToFMDateTime(Now));
SaveToTheBuffer := true;
CopiedText := TStringList.Create;
CopiedText.Text := CompareText.Text;
TextFound := true;
end;
end;
end
else
begin
StartStopWatch;
try
// Percentage match
LastPertToCheck := 0;
PosToUSe := -1;
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if not Assigned(FCPRSClipBoard[I].CopiedText) then
continue;
try
Len1 := Length(trim(FCPRSClipBoard[I].CopiedText.Text));
Len2 := Length(CompareText.Text);
CutOff := ceil(min(Len1, Len2) * (FPercentToVerify * 0.01));
PertoCheck := LevenshteinDistance
(trim(FCPRSClipBoard[I].CopiedText.Text),
CompareText.Text, CutOff);
except
PertoCheck := 0;
end;
if PertoCheck > LastPertToCheck then
begin
if PertoCheck > FPercentToVerify then
begin
PosToUSe := I;
LastPertToCheck := PertoCheck;
end;
end;
end;
if PosToUSe <> -1 then
begin
If (FCPRSClipBoard[PosToUSe].CopiedFromIEN <> ItemIEN) then
begin
LogText('PASTE', 'Partial Match: %' +
FloatToStr(round(LastPertToCheck)));
LogText('PASTE', 'Pasted Text IEN(' + IntToStr(ItemIEN) + ')');
LogText('TEXT', 'Pasted Text:' + #13#10 + CompareText.Text);
LogText('PASTE', 'Matched to Text IEN(' +
IntToStr(FCPRSClipBoard[PosToUSe].CopiedFromIEN) + ')');
If Assigned(FCPRSClipBoard[PosToUSe].CopiedText) then
LogText('TEXT', 'Matched to Text: ' + #13#10 +
trim(FCPRSClipBoard[PosToUSe].CopiedText.Text));
LogText('PASTE', 'Added to internal clipboard IEN(-1)');
// add new
SetLength(FCPRSClipBoard, Length(FCPRSClipBoard) + 1);
with FCPRSClipBoard[High(FCPRSClipBoard)] do
begin
CopiedFromIEN := -1;
CopiedFromPackage := 'Outside of current ' +
MonitoringApplication + ' tracking';
ApplicationPackage := MonitoringPackage;
ApplicationName := MonitoringApplication;
PercentMatch := round(LastPertToCheck);
PercentData :=
IntToStr(FCPRSClipBoard[PosToUSe].CopiedFromIEN) + ';' +
FCPRSClipBoard[PosToUSe].CopiedFromPackage;
PasteToIEN := ItemIEN;
PasteDBID := -1;
DateTimeOfCopy := FloatToStr(DateTimeToFMDateTime(Now));
SaveForDocument := true;
DateTimeOfPaste := FloatToStr(DateTimeToFMDateTime(Now));
SaveToTheBuffer := true;
CopiedText := TStringList.Create;
CopiedText.Text := CompareText.Text;
If Assigned(FCPRSClipBoard[PosToUSe].CopiedText) then
begin
OriginalText := TStringList.Create;
OriginalText.Text := FCPRSClipBoard[PosToUSe]
.CopiedText.Text;
end;
HashValue := aHashString;
end;
end;
TextFound := true;
end;
finally
If StopStopWatch then
LogText('METRIC', 'Percentage Match: ' + fStopWatch.Elapsed);
end;
end;
// add outside paste in here
if (not TextFound) and (WordCount(CompareText.Text) >= FNumberOfWords)
then
begin
StartStopWatch;
try
if Length(PasteDetails) > 0 then
AddItem := true
else
begin
// Check if excluded
AddItem := (not FromExcludedApp(ClipInfo.AppName));
if not AddItem then
LogText('PASTE', 'Excluded Application');
end;
if AddItem then
begin
// Look for the details first
SetLength(FCPRSClipBoard, Length(FCPRSClipBoard) + 1);
with FCPRSClipBoard[High(FCPRSClipBoard)] do
begin
if Length(PasteDetails) > 0 then
begin
CopiedFromIEN := StrToIntDef(Piece(PasteDetails, '^', 1), -1);
CopiedFromPackage := Piece(PasteDetails, '^', 2);
ApplicationPackage := Piece(PasteDetails, '^', 3);
ApplicationName := Piece(PasteDetails, '^', 4);
PercentMatch := 100.0;
HashValue := aHashString;
LogText('PASTE', 'Paste from cross session ' + PasteDetails);
LogText('PASTE', 'Added to internal clipboard IEN(-1)');
end
else
begin
CopiedFromIEN := -1;
CopiedFromPackage := 'Outside of current ' +
MonitoringApplication + ' tracking.';
if trim(ClipInfo.AppName) <> '' then
CopiedFromPackage := CopiedFromPackage + 'From: ' +
ClipInfo.AppName + ' - ' + ClipInfo.AppTitle;
ApplicationPackage := MonitoringPackage;
ApplicationName := MonitoringApplication;
PercentMatch := 100.0;
HashValue := aHashString;
LogText('PASTE', 'Pasted from outside the tracking');
LogText('PASTE]', 'Added to internal clipboard IEN(-1)');
end;
PasteToIEN := ItemIEN;
PasteDBID := -1;
DateTimeOfCopy := FloatToStr(DateTimeToFMDateTime(Now));
SaveForDocument := true;
DateTimeOfPaste := FloatToStr(DateTimeToFMDateTime(Now));
SaveToTheBuffer := true;
CopiedText := TStringList.Create;
CopiedText.Text := CompareText.Text;
end;
end;
finally
If StopStopWatch then
LogText('METRIC', 'Outside Paste: ' + fStopWatch.Elapsed);
end;
end;
end;
finally
CompareText.Free;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.SaveCopyPasteClipboard(Sender: TComponent;
SaveList: TStringList);
var
I, x, z, SaveCnt, FndTotalCnt, FndLineNum: Integer;
IEN2Use: Int64;
Package2Use, tmp: String;
FndList: TStringList;
FndListHash: THashedStringList;
FndPercent: Double;
FndTimeTook: Int64;
begin
if not Enabled then
Exit;
FCriticalSection.Enter;
try
SaveList.Text := '';
if (Sender is TCopyEditMonitor) then
begin
StartStopWatch;
try
FndList := TStringList.Create;
FndListHash := THashedStringList.Create;
try
with (Sender as TCopyEditMonitor) do
begin
SaveCnt := 0;
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if FCPRSClipBoard[I].SaveForDocument = true then
begin
Inc(SaveCnt);
FCPRSClipBoard[I].SaveItemID := SaveCnt;
if FCPRSClipBoard[I].PercentMatch <> 100 then
begin
IEN2Use := StrToIntDef(Piece(FCPRSClipBoard[I].PercentData,
';', 1), -1);
Package2Use := Piece(FCPRSClipBoard[I].PercentData, ';', 2);
end
else
begin
IEN2Use := FCPRSClipBoard[I].CopiedFromIEN;
Package2Use := FCPRSClipBoard[I].CopiedFromPackage;
end;
SaveList.Add(IntToStr(SaveCnt) + ',0=' + IntToStr(UserDuz) + '^'
+ FCPRSClipBoard[I].DateTimeOfPaste + '^' + IntToStr(ItemIEN)
+ ';' + RelatedPackage + '^' + IntToStr(IEN2Use) + ';' +
Package2Use + '^' + FloatToStr(FCPRSClipBoard[I].PercentMatch)
+ '^' + FCPRSClipBoard[I].ApplicationName + '^-1^');
// Line Count (w/out OUR line breaks for size - code below)
If Assigned(FCPRSClipBoard[I].CopiedText) then
BreakUpLongLines(SaveList, IntToStr(SaveCnt),
FCPRSClipBoard[I].CopiedText, FBreakUpLimit);
// Send in the original text if needed
If Assigned(FCPRSClipBoard[I].OriginalText) then
begin
BreakUpLongLines(SaveList, IntToStr(SaveCnt) + ',COPY',
FCPRSClipBoard[I].OriginalText, FBreakUpLimit);
end;
if TCopyEditMonitor(Sender).Owner is TCopyPasteDetails then
begin
TCopyPasteDetails(TCopyEditMonitor(Sender).Owner)
.CPCOMPARE(FCPRSClipBoard[I], FndList, FndPercent,
FndTimeTook);
{ DONE -oChris Bell : if 100 BUT MORE THAN 1 REC IN THE LIST THEN FORCE THE SAVE }
if ((FndPercent <> 100) and (FndPercent <> -3)) or
((FndPercent = 100) and (StrToIntDef(FndList.Values['(0)'],
-1) > 1)) then
begin
FndListHash.Assign(FndList);
// Get the total number of finds
FndTotalCnt := StrToIntDef(FndListHash.Values['(0)'], -1);
SaveList.Add(IntToStr(SaveCnt) + ',Paste,-1=' +
IntToStr(FndTotalCnt) + '^' + IntToStr(FndTimeTook));
tmp := SaveList.Values[IntToStr(SaveCnt) + ',0'];
SetPiece(tmp, '^', 5, formatfloat('##.##', FndPercent));
// If 100% then we need to force the find text
if FndPercent = 100 then
SetPiece(tmp, '^', 8, '1');
SaveList.Values[IntToStr(SaveCnt) + ',0'] := tmp;
// Loop through each return and format for the save
for x := 1 to FndTotalCnt do
begin
FndLineNum :=
StrToIntDef
(FndListHash.Values['(' + IntToStr(x) + ',0)'], -1);
// Reuse
FndList.Clear;
for z := 1 to FndLineNum do
FndList.Add(FndListHash.Values['(' + IntToStr(x) + ',' +
IntToStr(z) + ')']);
BreakUpLongLines(SaveList, IntToStr(SaveCnt) + ',Paste,' +
IntToStr(x), FndList, FBreakUpLimit);
end;
end
else if FndPercent = 100 then
begin
tmp := SaveList.Values[IntToStr(SaveCnt) + ',0'];
SetPiece(tmp, '^', 5, '100');
SaveList.Values[IntToStr(SaveCnt) + ',0'] := tmp;
end
else if FndPercent = -3 then
begin
// Took to long so we need to indicate as such
tmp := SaveList.Values[IntToStr(SaveCnt) + ',0'];
SetPiece(tmp, '^', 8, '2');
SaveList.Values[IntToStr(SaveCnt) + ',0'] := tmp;
end;
end;
end;
end;
SaveList.Add('TotalToSave=' + IntToStr(SaveCnt));
LogText('SAVE', 'Saved ' + IntToStr(SaveCnt) + ' Items');
end;
finally
FndListHash.Free;
FndList.Free;
end;
finally
If StopStopWatch then
LogText('METRIC', 'Build Save: ' + fStopWatch.Elapsed);
end;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.CopyToCopyPasteClipboard(TextToCopy,
FromName: string; ItemID: Int64);
const
Max_Retry = 3;
Hlp_Msg = 'System Error: %s' + #13#10 +
'There was a problem accessing the clipboard please try again.' + #13#10 +
#13#10 + 'The following application has a lock on the clipboard:' + #13#10 +
'App Title: %s' + #13#10 + 'App Name: %s' + #13#10 + #13#10 +
'If this problem persists please close %s and then try again. If you are still experiencing issues please contact your local CPRS help desk.';
var
I, RetryCnt: Integer;
Found, TryCpy: Boolean;
ClpLckInfo: tClipInfo;
TmpStr, aHashString: string;
procedure AddToClipBrd(CPDetails, CPText: string);
var
gMem: HGLOBAL;
lp: Pointer;
begin
{$WARN SYMBOL_PLATFORM OFF}
Win32Check(OpenClipBoard(0));
try
Win32Check(EmptyClipBoard);
// Add the details to the clipboard
gMem := GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE, Length(CPDetails) + 1);
try
Win32Check(gMem <> 0);
lp := GlobalLock(gMem);
Win32Check(lp <> nil);
CopyMemory(lp, Pointer(PAnsiChar(AnsiString(CPDetails))),
Length(CPDetails) + 1);
Win32Check(gMem <> 0);
SetClipboardData(CF_CopyPaste, gMem);
Win32Check(gMem <> 0);
finally
GlobalUnlock(gMem);
end;
// now add the text to the clipboard
CPText := StringReplace(CPText, #13, #13#10, [rfReplaceAll]);
gMem := GlobalAlloc(GMEM_DDESHARE + GMEM_MOVEABLE,
(Length(CPText) + 1) * 2);
try
Win32Check(gMem <> 0);
lp := GlobalLock(gMem);
Win32Check(lp <> nil);
CopyMemory(lp, Pointer(PAnsiChar(AnsiString(CPText))),
(Length(CPText) + 1) * 2);
Win32Check(gMem <> 0);
SetClipboardData(CF_TEXT, gMem);
Win32Check(gMem <> 0);
finally
GlobalUnlock(gMem);
end;
finally
Win32Check(CloseClipBoard);
end;
{$WARN SYMBOL_PLATFORM ON}
end;
begin
if not Enabled then
Exit;
Found := false;
if not LoadedProperties then
LoadTheProperties;
if not BufferLoaded then
LoadTheBuffer;
FCriticalSection.Enter;
try
LogText('COPY', 'Copying data from IEN(' + IntToStr(ItemID) + ')');
StartStopWatch;
try
if WordCount(TextToCopy) >= FNumberOfWords then
begin
aHashString := fpSHA.HashStringAsHex(StringReplace(TextToCopy, #13,
#13#10, [rfReplaceAll]));
// check if this already exist
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if FCPRSClipBoard[I].CopiedFromPackage = UpperCase(FromName) then
begin
if FCPRSClipBoard[I].CopiedFromIEN = ItemID then
begin
if trim(FCPRSClipBoard[I].HashValue) <> '' then
Found := FCPRSClipBoard[I].HashValue = aHashString
else if Assigned(FCPRSClipBoard[I].CopiedText) then
Found := AnsiSameText(trim(FCPRSClipBoard[I].CopiedText.Text),
trim(TextToCopy));
if Found then
begin
LogText('COPY', 'Copied data already being monitored');
Break;
end;
end;
end;
end;
// Copied text doesn't exist so add it in
if (not Found) and (WordCount(TextToCopy) >= FNumberOfWords) then
begin
LogText('COPY', 'Adding copied data to session tracking');
SetLength(FCPRSClipBoard, Length(FCPRSClipBoard) + 1);
FCPRSClipBoard[High(FCPRSClipBoard)].CopiedFromIEN := ItemID;
FCPRSClipBoard[High(FCPRSClipBoard)].CopiedFromPackage :=
UpperCase(FromName);
FCPRSClipBoard[High(FCPRSClipBoard)].ApplicationPackage :=
MonitoringPackage;
FCPRSClipBoard[High(FCPRSClipBoard)].ApplicationName :=
MonitoringApplication;
FCPRSClipBoard[High(FCPRSClipBoard)].DateTimeOfCopy :=
FloatToStr(DateTimeToFMDateTime(Now));
FCPRSClipBoard[High(FCPRSClipBoard)].PasteDBID := -1;
FCPRSClipBoard[High(FCPRSClipBoard)].SaveForDocument := false;
FCPRSClipBoard[High(FCPRSClipBoard)].SaveToTheBuffer := true;
FCPRSClipBoard[High(FCPRSClipBoard)].CopiedText := TStringList.Create;
FCPRSClipBoard[High(FCPRSClipBoard)].CopiedText.Text := TextToCopy;
FCPRSClipBoard[High(FCPRSClipBoard)].HashValue := aHashString;
end;
end;
TryCpy := true;
RetryCnt := 1;
while TryCpy do
begin
while (RetryCnt <= Max_Retry) and TryCpy do
begin
try
AddToClipBrd(IntToStr(ItemID) + '^' + UpperCase(FromName) + '^' +
MonitoringPackage + '^' + MonitoringApplication, TextToCopy);
TryCpy := false;
Except
Inc(RetryCnt);
Sleep(100);
If RetryCnt > Max_Retry then
ClpLckInfo := GetClipSource(true)
End;
end;
// If our retry count is greater than the max we were unable to grab the paste
if RetryCnt > Max_Retry then
begin
TmpStr := Format(Hlp_Msg, [SysErrorMessage(GetLastError),
ClpLckInfo.AppTitle, ClpLckInfo.AppName, ClpLckInfo.AppName]);
if TaskMessageDlg('Clipboard Locked', TmpStr, mtError,
[mbRetry, mbCancel], -1) = mrRetry then
begin
// reset the loop variables
RetryCnt := 1;
TryCpy := true;
end
else
Exit;
end;
end;
finally
If StopStopWatch then
LogText('METRIC', 'Add To Clipboard: ' + fStopWatch.Elapsed);
end;
finally
FCriticalSection.Leave;
end;
end;
constructor TCopyApplicationMonitor.Create(AOwner: TComponent);
Var
I: Integer;
begin
inherited;
if not (csDesigning in ComponentState) then
FCriticalSection := TCriticalSection.Create;
BufferLoaded := false;
LoadedProperties := false;
HighlightColor := clYellow;
MatchStyle := [];
MatchHighlight := true;
DisplayPaste := true;
Enabled := true;
fLCSToggle := true;
fLCSCharLimit := 5000;
FCompareCutOff := 15;
FSaveCutOff := 2;
FLogObject := nil;
fPasteLimit := 20000;
if not(csDesigning in ComponentState) then
begin
CF_CopyPaste := RegisterClipboardFormat('CF_CopyPaste');
for I := 1 to ParamCount do
begin
if UpperCase(ParamStr(I)) = 'CPLOG' then
begin
FLogObject := TLogComponent.Create(Self);
FLogObject.LogToFile := LOG_SUM;
Break;
end
else if UpperCase(ParamStr(I)) = 'CPLOGDEBUG' then
begin
FLogObject := TLogComponent.Create(Self);
FLogObject.LogToFile := LOG_DETAIL;
Break;
end;
end;
if Assigned(FLogObject) then
fStopWatch := TStopWatch.Create(Self, true);
fExcludeApps := TStringList.Create;
fExcludeApps.CaseSensitive := false;
fpSHA := TIdHashSHA1.Create;
SetLength(fSyncSizeList, 0);
LogText('START', StringOfChar('*', 20) + FormatDateTime('mm/dd/yyyy hh:mm:ss',
Now) + StringOfChar('*', 20));
LogText('INIT', 'Monitor object created');
end;
end;
destructor TCopyApplicationMonitor.Destroy;
var
I: Integer;
begin
if not (csDesigning in ComponentState) then
begin
FCriticalSection.Enter;
try
// Clear copy arrays
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if Assigned(FCPRSClipBoard[I].CopiedText) then
FCPRSClipBoard[I].CopiedText.Free;
If Assigned(FCPRSClipBoard[I].OriginalText) then
FCPRSClipBoard[I].OriginalText.Free;
end;
SetLength(FCPRSClipBoard, 0);
SetLength(fSyncSizeList, 0);
if Assigned(ExcludeApps) then
ExcludeApps.Free;
if Assigned(ExcludedList) then
ExcludedList.Free;
if Assigned(fpSHA) then
fpSHA.Free;
for I := Low(FCopyPasteThread) to High(FCopyPasteThread) do
FCopyPasteThread[I].Terminate;
SetLength(FCopyPasteThread, 0);
if Assigned(fStopWatch) then
fStopWatch.Free;
LogText('INIT', 'Monitor object destroyed');
LogText('STOP', StringOfChar('*', 20) +
FormatDateTime('mm/dd/yyyy hh:mm:ss', Now) + StringOfChar('*', 20));
finally
FCriticalSection.Leave;
end;
if Assigned(FCriticalSection) then
FCriticalSection.Free;
end;
inherited;
end;
procedure TCopyApplicationMonitor.LoadTheBufferPolled(Sender: TObject);
const
Wait_Timeout = 60; // Loop time each loop 1 second
Timer_Delay = 5000; // MS
var
BufferList: THashedStringList;
I, x: Integer;
NumLines, BuffLoopStart, BuffLoopStop { , StrtSub, StpSub } : Integer;
ProcessLoad, LoadDone, ErrOccurred: Boolean;
tmpString: String;
begin
FCriticalSection.Enter;
try
ErrOccurred := false;
if not Enabled or BufferLoaded then
Exit;
// Do we need to start the polling
if not Assigned(BufferTimer) then
begin
if not Assigned(StartPollBuff) then
begin
// need to be able to start the buffer
BufferLoaded := true;
Exit;
end
else
begin
LogText('BUFF', 'RPC START POLL');
StartStopWatch;
try
StartPollBuff(Self, ErrOccurred);
finally
If StopStopWatch then
LogText('METRIC', 'Start Buffer RPC: ' + fStopWatch.Elapsed);
end;
if ErrOccurred then
begin
BufferLoaded := true;
Exit;
end;
end;
BufferTimer := TTimer.Create(Self);
BufferTimer.Interval := Timer_Delay;
BufferTimer.OnTimer := LoadTheBufferPolled;
EnableBuffer(true);
BufferTryLimit := 1;
Exit; // Dont run the check right away, let the timmer handle this
end;
// Timmer has been started so lets check
if (Sender is TTimer) then
begin
if not Assigned(LoadBuffer) then
begin
// need to be able to check the buffer
BufferLoaded := true;
Exit;
end
else
begin
BufferList := THashedStringList.Create();
try
ProcessLoad := true;
LoadDone := false;
EnableBuffer(false);
LogText('BUFF', 'RPC BUFFER CALL');
StartStopWatch;
try
LoadBuffer(Self, BufferList, ProcessLoad);
finally
If StopStopWatch then
LogText('METRIC', 'Buffer Load RPC: ' + fStopWatch.Elapsed);
end;
if ProcessLoad then
begin
StartStopWatch;
try
if BufferList.Count > 0 then
begin
if BufferList.Strings[0] <> '-1' then
begin
// first line is always the ~DONE
LoadDone := BufferList.Values['~Done'] = '1';
// If more than 1 line (the done line) then try to start processing the copies
if BufferList.Count > 1 then
begin
BuffLoopStart :=
StrToIntDef(Piece(Piece(BufferList.Strings[1], ',', 1),
'(', 2), 0);
BuffLoopStop :=
StrToIntDef
(Piece(Piece(BufferList.Strings[BufferList.Count - 1],
',', 1), '(', 2), -1);
if BuffLoopStop > 0 then
SetLength(FCPRSClipBoard, BuffLoopStop);
if BuffLoopStart <> 0 then
BufferTryLimit := 1;
for I := BuffLoopStart to BuffLoopStop do
begin
with FCPRSClipBoard[I - 1] do
begin
SaveForDocument := false;
SaveToTheBuffer := false;
tmpString := BufferList.Values
['(' + IntToStr(I) + ',0)'];
DateTimeOfCopy := Piece(tmpString, '^', 1);
ApplicationName := Piece(tmpString, '^', 2);
// ApplicationPackage := Piece(tmpString, '^', 3);
CopiedFromIEN :=
StrToIntDef(Piece(Piece(tmpString, '^', 3),
';', 1), -1);
CopiedFromPackage :=
Piece(Piece(tmpString, '^', 3), ';', 2);
if fHashBuffer then
HashValue := Piece(tmpString, '^', 4)
else
begin
NumLines := StrToIntDef(Piece(tmpString, '^', 5), -1);
if NumLines > 0 then
begin
CopiedText := TStringList.Create;
CopiedText.BeginUpdate;
for x := 1 to NumLines do
CopiedText.Add
(BufferList.Values['(' + IntToStr(I) + ',' +
IntToStr(x) + ')']);
CopiedText.EndUpdate;
end;
end;
end;
end;
end;
end;
end;
finally
If StopStopWatch then
LogText('METRIC', 'Buffer build: ' + fStopWatch.Elapsed);
end;
end;
finally
BufferList.Free;
end;
IncBufferTryLimit;
if BufferTryLimit = 3 then
StopTheBuffer;
// Stop the timer
if LoadDone then
begin
BufferLoaded := true;
EnableBuffer(false);
LogText('BUFF', 'Buffer loaded with ' +
IntToStr(Length(FCPRSClipBoard)) + ' Items');
end
else
EnableBuffer(true);
end;
end
else
begin
// Not from the Timer so we need to wait until the call is done
I := 0;
while BufferTimer.Enabled or (I >= Wait_Timeout) do
begin
// check to see if the buffer has finished yet
Sleep(1000);
Application.ProcessMessages;
Inc(I);
end;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.StopTheBuffer;
var
ErrOccurred: Boolean;
begin
FCriticalSection.Enter;
try
ErrOccurred := false;
if Assigned(StopPollBuff) then
begin
LogText('BUFF', 'RPC STOP POLL');
StartStopWatch;
try
fStopPollBuff(Self, ErrOccurred);
finally
If StopStopWatch then
LogText('METRIC', 'Stop Buffer RPC: ' + fStopWatch.Elapsed);
end;
end;
BufferLoaded := true;
EnableBuffer(false);
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.LoadTheBuffer();
var
BufferList: TStringList;
I, x: Integer;
NumLines, BuffParent: Integer;
ProcessLoad: Boolean;
begin
if not Enabled then
Exit;
if not BufferEnabled then
Exit;
if PolledBuffer then
begin
LoadTheBufferPolled(Self);
Exit;
end;
// Non polled logic
BufferList := TStringList.Create();
try
ProcessLoad := true;
BuffParent := 0;
if Assigned(LoadBuffer) then
begin
LogText('BUFF', 'RPC CALL');
StartStopWatch;
try
LoadBuffer(Self, BufferList, ProcessLoad);
finally
If StopStopWatch then
LogText('METRIC', 'Buffer Load RPC: ' + fStopWatch.Elapsed);
end;
end;
if ProcessLoad then
begin
StartStopWatch;
try
LogText('BUFF', 'Loading the buffer.' + BufferList.Values['(0,0)'] +
' Items.');
if BufferList.Count > 0 then
BuffParent := StrToIntDef(BufferList.Values['(0,0)'], -1);
FCriticalSection.Enter;
try
for I := 1 to BuffParent do
begin // first line is the total number
LogText('BUFF', 'Buffer item (' + IntToStr(I) + '): ' +
BufferList.Values['(' + IntToStr(I) + ',0)']);
SetLength(FCPRSClipBoard, Length(FCPRSClipBoard) + 1);
with FCPRSClipBoard[High(FCPRSClipBoard)] do
begin
SaveForDocument := false;
SaveToTheBuffer := false;
DateTimeOfCopy :=
Piece(BufferList.Values['(' + IntToStr(I) + ',0)'], '^', 1);
ApplicationName :=
Piece(BufferList.Values['(' + IntToStr(I) + ',0)'], '^', 2);
// ApplicationPackage := Piece(BufferList.Values['(' + IntToStr(I) + ',0)'], '^', 3);
CopiedFromIEN :=
StrToIntDef
(Piece(Piece(BufferList.Values['(' + IntToStr(I) + ',0)'], '^',
3), ';', 1), -1);
CopiedFromPackage :=
Piece(Piece(BufferList.Values['(' + IntToStr(I) + ',0)'], '^',
3), ';', 2);
if fHashBuffer then
HashValue :=
Piece(BufferList.Values['(' + IntToStr(I) + ',0)'], '^', 4)
else
begin
CopiedText := TStringList.Create;
// If not hashed then load the full buffer
NumLines :=
StrToIntDef
(Piece(BufferList.Values['(' + IntToStr(I) + ',0)'],
'^', 5), -1);
for x := 1 to NumLines do
CopiedText.Add(BufferList.Values['(' + IntToStr(I) + ',' +
IntToStr(x) + ')']);
end;
end;
end;
finally
FCriticalSection.Leave;
end;
BufferLoaded := true;
finally
If StopStopWatch then
LogText('METRIC', 'Buffer build: ' + fStopWatch.Elapsed);
end;
end;
finally
BufferList.Free;
end;
end;
procedure TCopyApplicationMonitor.SaveTheBuffer();
var
SaveList, ReturnList: TStringList;
I, SaveCnt, aIdx: Integer;
ErrOccurred: Boolean;
begin
FCriticalSection.Enter;
try
ErrOccurred := false;
if not Enabled then
Exit;
if not BufferEnabled then
Exit;
if PolledBuffer and not BufferLoaded then
begin
// Ensure that the buffer poll has stoped
if Assigned(fStopPollBuff) then
begin
LogText('BUFF', 'RPC STOP POLL');
StartStopWatch;
try
fStopPollBuff(Self, ErrOccurred);
finally
If StopStopWatch then
LogText('METRIC', 'Stop Buffer RPC: ' + fStopWatch.Elapsed);
end;
end;
end;
SaveList := TStringList.Create;
ReturnList := TStringList.Create;
try
SaveCnt := 0;
LogText('BUFF', 'Preparing Buffer for Save');
StartStopWatch;
try
for I := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if FCPRSClipBoard[I].SaveToTheBuffer then
begin
Inc(SaveCnt);
aIdx := SaveList.Add(IntToStr(SaveCnt) + ',0=' + IntToStr(UserDuz) +
'^' + FCPRSClipBoard[I].DateTimeOfCopy + '^' +
IntToStr(FCPRSClipBoard[I].CopiedFromIEN) + ';' + FCPRSClipBoard
[I].CopiedFromPackage + '^' + FCPRSClipBoard[I]
.ApplicationName + '^');
if fHashBuffer then
begin
if trim(FCPRSClipBoard[I].HashValue) <> '' then
SaveList.Strings[aIdx] := SaveList.Strings[aIdx] +
FCPRSClipBoard[I].HashValue
else if Assigned(FCPRSClipBoard[I].CopiedText) then
SaveList.Strings[aIdx] := SaveList.Strings[aIdx] +
fpSHA.HashStringAsHex(FCPRSClipBoard[I].CopiedText.Text);
end
else
begin
if Assigned(FCPRSClipBoard[I].CopiedText) then
begin
SaveList.Add(IntToStr(SaveCnt) + ',-1=' +
IntToStr(FCPRSClipBoard[I].CopiedText.Count));
BreakUpLongLines(SaveList, IntToStr(SaveCnt),
FCPRSClipBoard[I].CopiedText, FBreakUpLimit);
end;
end;
end;
end;
SaveList.Add('TotalBufferToSave=' + IntToStr(SaveCnt));
finally
If StopStopWatch then
LogText('METRIC', 'Build Save: ' + fStopWatch.Elapsed);
end;
LogText('BUFF', IntToStr(SaveCnt) + ' Items ready to save');
if Assigned(FSaveBuffer) then
begin
StartStopWatch;
try
FSaveBuffer(Self, SaveList, ReturnList);
finally
If StopStopWatch then
LogText('METRIC', 'Buffer Save RPC: ' + fStopWatch.Elapsed);
end;
end;
finally
ReturnList.Free;
SaveList.Free;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.LoadTheProperties();
begin
if not Enabled then
Exit;
if not LoadedProperties and Assigned(LoadProperties) then
begin
StartStopWatch;
try
LoadProperties(Self);
finally
If StopStopWatch then
LogText('METRIC', 'Load Properties: ' + fStopWatch.Elapsed);
end;
// Log the properties
LogText('PROP', 'Loading properties' + #13#10 + 'Number of words:' +
FloatToStr(FNumberOfWords) + #13#10 + 'Percent to verify:' +
FloatToStr(PercentToVerify));
end;
LoadedProperties := true;
end;
Procedure TCopyApplicationMonitor.EnableBuffer(Value: Boolean);
begin
FCriticalSection.Enter;
try
BufferTimer.Enabled := Value;
finally
FCriticalSection.Leave;
end;
end;
function TCopyApplicationMonitor.WordCount(TextToCount: string): Integer;
var
CharCnt: Integer;
function IsEnd(CharToCheck: char): Boolean;
begin
Result := CharInSet(CharToCheck, [#0 .. #$1F, ' ', '.', ',', '?', ':', ';',
'(', ')', '/', '\']);
end;
begin
FCriticalSection.Enter;
try
Result := 0;
if Enabled then
begin
CharCnt := 1;
while CharCnt <= Length(TextToCount) do
begin
while (CharCnt <= Length(TextToCount)) and
(IsEnd(TextToCount[CharCnt])) do
Inc(CharCnt);
if CharCnt <= Length(TextToCount) then
begin
Inc(Result);
while (CharCnt <= Length(TextToCount)) and
(not IsEnd(TextToCount[CharCnt])) do
Inc(CharCnt);
end;
end;
end;
finally
FCriticalSection.Leave;
end;
end;
function TCopyApplicationMonitor.LevenshteinDistance(String1, String2: String;
CutOff: Integer): Double;
Var
currentRow, previousRow, tmpRow: Array of Integer;
firstLength, secondLength, I, J, tmpTo, tmpFrom, Cost: Integer;
TmpStr: String;
tmpChar: char;
begin
FCriticalSection.Enter;
try
Result := 0.0;
if not Enabled then
Exit;
firstLength := Length(String1);
secondLength := Length(String2);
if (firstLength = 0) then
begin
Result := secondLength;
Exit;
end
else if (secondLength = 0) then
begin
Result := firstLength;
Exit;
end;
if (firstLength > secondLength) then
begin
// Need to swap the text around for the compare
TmpStr := String1;
String1 := String2;
String2 := TmpStr;
// set the new lengths
firstLength := secondLength;
secondLength := Length(String2);
end;
// IF no max then use the longest length
If (CutOff < 0) then
CutOff := secondLength;
// If more characters changed then our % threshold would allow then no need to calc
if (secondLength - firstLength > CutOff) then
begin
Result := -1;
Exit;
end;
SetLength(currentRow, firstLength + 1);
SetLength(previousRow, firstLength + 1);
// Pad the array
for I := 0 to firstLength do
previousRow[I] := I;
for I := 1 to secondLength do
begin
tmpChar := String2[I];
currentRow[0] := I - 1;
tmpFrom := Max(I - CutOff - 1, 1);
tmpTo := min(I + CutOff + 1, firstLength);
for J := tmpFrom to tmpTo do
begin
if String1[J] = tmpChar then
Cost := 0
else
Cost := 1;
currentRow[J] := min(min(currentRow[J - 1] + 1, previousRow[J] + 1),
previousRow[J - 1] + Cost);
end;
// shift the array around
tmpRow := Copy(previousRow, 0, Length(previousRow));
previousRow := Copy(currentRow, 0, Length(currentRow));
currentRow := Copy(tmpRow, 0, Length(tmpRow));
// clean up
SetLength(tmpRow, 0);
end;
Result := (1 - (previousRow[firstLength] / Max(firstLength,
secondLength))) * 100;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.RecalPercentage(ReturnedList: TStringList;
var SaveList: TStringList; ExisitingPaste: TPasteArray);
var
I, z: Integer;
StringA, StringB: WideString;
ArrayIdentifer, RPCIdentifer, Package, FromEdit: string;
NumOfEntries, NumOfLines: Integer;
begin
FCriticalSection.Enter;
try
if not Enabled then
Exit;
LogText('SAVE', 'Recalculate Percentage');
StartStopWatch;
try
NumOfEntries := StrToIntDef(ReturnedList.Values['(0,0)'], 0);
SaveList.Add('0=' + IntToStr(NumOfEntries));
for I := 1 to NumOfEntries do
begin
FromEdit :=
Piece(ReturnedList.Values['(' + IntToStr(I) + ',0)'], '^', 5);
if FromEdit = '1' then
begin
ArrayIdentifer :=
Piece(ReturnedList.Values['(' + IntToStr(I) + ',0)'], '^', 2);
// Build String a from the internal clipboard
for z := Low(ExisitingPaste) to High(ExisitingPaste) do
begin
if ExisitingPaste[z].PasteDBID = StrToIntDef(ArrayIdentifer, -1)
then
begin
if Assigned(ExisitingPaste[z].OriginalText) then
StringA := ExisitingPaste[z].OriginalText.Text
else
StringA := ExisitingPaste[z].PastedText.Text;
Break;
end;
end;
end
else
begin
ArrayIdentifer :=
Piece(ReturnedList.Values['(' + IntToStr(I) + ',0)'], '^', 1);
// Build String a from the internal clipboard
for z := Low(FCPRSClipBoard) to High(FCPRSClipBoard) do
begin
if not Assigned(FCPRSClipBoard[z].CopiedText) then
continue;
if FCPRSClipBoard[z].SaveItemID = StrToIntDef(ArrayIdentifer, -1)
then
begin
StringA := FCPRSClipBoard[z].CopiedText.Text;
Break;
end;
end;
end;
// build string B from what was saved
RPCIdentifer :=
Piece(ReturnedList.Values['(' + IntToStr(I) + ',0)'], '^', 2);
Package := Piece(ReturnedList.Values['(' + IntToStr(I) +
',0)'], '^', 3);
NumOfLines :=
StrToIntDef(Piece(ReturnedList.Values['(' + IntToStr(I) + ',0)'],
'^', 4), 0);
StringB := '';
for z := 1 to NumOfLines do
begin
StringB := StringB + ReturnedList.Values
['(' + IntToStr(I) + ',' + IntToStr(z) + ')'] + #13#10;
end;
// Strip the cariage returns out
StringA := StringReplace(StringReplace(StringA, #13, '', [rfReplaceAll]
), #10, '', [rfReplaceAll]);
StringB := StringReplace(StringReplace(StringB, #13, '', [rfReplaceAll]
), #10, '', [rfReplaceAll]);
SaveList.Add(IntToStr(I) + '=' + RPCIdentifer + '^' + Package + '^' +
IntToStr(round(LevenshteinDistance(StringA, StringB, -1))));
end;
finally
If StopStopWatch then
LogText('METRIC', 'Recal Build: ' + fStopWatch.Elapsed);
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.LogText(Action: string;
MessageTxt: TPasteArray);
begin
if not Enabled then
Exit;
if Assigned(FLogObject) then
if FLogObject.LogToFile = LOG_DETAIL then
FLogObject.LogText(Action, FLogObject.Dump(MessageTxt));
end;
procedure TCopyApplicationMonitor.LogText(Action, MessageTxt: String);
begin
if (csDesigning in ComponentState) then
exit
else begin
if not Enabled then
Exit;
FCriticalSection.Enter;
try
if Assigned(FLogObject) then
FLogObject.LogText(Action, MessageTxt);
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetBufferEnabled: Boolean;
begin
if (csDesigning in ComponentState) then
Result := fBufferEnabled
else
begin
FCriticalSection.Enter;
try
Result := fBufferEnabled;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetBufferPolled: Boolean;
begin
if (csDesigning in ComponentState) then
Result := FBufferPolled
else
begin
FCriticalSection.Enter;
try
Result := FBufferPolled;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetBufferTimer: TTimer;
begin
FCriticalSection.Enter;
try
Result := fBufferTimer;
finally
FCriticalSection.Leave;
end;
end;
function TCopyApplicationMonitor.GetBufferTryLimit: Integer;
begin
FCriticalSection.Enter;
try
Result := fBufferTryLimit;
finally
FCriticalSection.Leave;
end;
end;
function TCopyApplicationMonitor.GetClipSource(GetLocked: Boolean = false)
: tClipInfo;
function GetAppByPID(PID: Cardinal): String;
var
snapshot: THandle;
ProcEntry: TProcessEntry32;
begin
snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot <> INVALID_HANDLE_VALUE) then
begin
ProcEntry.dwSize := SizeOf(ProcessEntry32);
if (Process32First(snapshot, ProcEntry)) then
begin
// check the first entry
if ProcEntry.th32ProcessID = PID then
Result := ProcEntry.szExeFile
else
begin
while Process32Next(snapshot, ProcEntry) do
begin
if ProcEntry.th32ProcessID = PID then
begin
Result := ProcEntry.szExeFile;
Break;
end;
end;
end;
end;
end;
CloseHandle(snapshot);
end;
function GetHandleByPID(PID: Cardinal): HWND;
type
TEInfo = record
PID: DWORD;
HWND: THandle;
end;
var
EInfo: TEInfo;
function CallBack(Wnd: DWORD; var EI: TEInfo): Bool; stdcall;
var
PID: DWORD;
begin
GetWindowThreadProcessID(Wnd, @PID);
Result := (PID <> EI.PID) or (not IsWindowVisible(Wnd)) or
(not IsWindowEnabled(Wnd));
if not Result then
EI.HWND := Wnd;
end;
begin
EInfo.PID := PID;
EInfo.HWND := 0;
EnumWindows(@CallBack, Integer(@EInfo));
Result := EInfo.HWND;
end;
begin
if not Enabled then
Exit;
LogText('PASTE', 'Clip Source');
with Result do
begin
ObjectHwnd := 0;
AppHwnd := 0;
AppPid := 0;
// Get the owners handle (TEdit, etc...)
if GetLocked then
ObjectHwnd := GetOpenClipboardWindow
else
ObjectHwnd := GetClipboardOwner;
if ObjectHwnd <> 0 then
begin
// Get its running applications Process ID
GetWindowThreadProcessID(ObjectHwnd, AppPid);
if AppPid <> 0 then
begin
// Get the applciation name from the Process ID
AppName := GetAppByPID(AppPid);
// Get the main applications hwnd
AppHwnd := GetHandleByPID(AppPid);
SetLength(AppClass, 256);
SetLength(AppClass, GetClassName(AppHwnd, PChar(AppClass),
Length(AppClass)-1));
SetLength(AppTitle, 256);
SetLength(AppTitle, GetWindowText(AppHwnd, PChar(AppTitle),
Length(AppTitle)-1));
end
else
AppName := 'No Process Found';
end
else
AppName := 'No Source Found';
end;
end;
function TCopyApplicationMonitor.GetCPRSClipBoard: CprsClipboardArry;
begin
FCriticalSection.Enter;
try
Result := FCPRSClipBoard;
finally
FCriticalSection.Leave;
end;
end;
function TCopyApplicationMonitor.GetDisplayPaste: Boolean;
begin
if (csDesigning in ComponentState) then
Result := FDisplayPaste
else begin
FCriticalSection.Enter;
try
Result := FDisplayPaste;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.FromExcludedApp(AppName: String): Boolean;
var
I: Integer;
begin
FCriticalSection.Enter;
try
Result := false;
if not Enabled then
Exit;
for I := 0 to ExcludeApps.Count - 1 do
begin
if UpperCase(Piece(ExcludeApps[I], '^', 1)) = UpperCase(AppName) then
begin
Result := true;
Break;
end;
end;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.SyncSizes(Sender: TObject);
var
I, UseHeight: Integer;
begin
if not Enabled then
Exit;
UseHeight := TCopyPasteDetails(Sender).Height;
if Assigned(fSyncSizeList) then
begin
for I := Low(fSyncSizeList) to High(fSyncSizeList) do
begin
if Assigned(fSyncSizeList[I]) then
begin
if not Assigned(TCopyPasteDetails(fSyncSizeList[I]).ParentForm) then
TCopyPasteDetails(fSyncSizeList[I]).ParentForm :=
GetParentForm(TCopyPasteDetails(fSyncSizeList[I]), false);
if (fSyncSizeList[I] <> Sender) and
(TCopyPasteDetails(fSyncSizeList[I]).ParentForm = TCopyPasteDetails
(Sender).ParentForm) then
TCopyPasteDetails(fSyncSizeList[I]).Height := UseHeight;
end;
end;
end;
end;
Function TCopyApplicationMonitor.StartStopWatch(): Boolean;
begin
FCriticalSection.Enter;
try
Result := Assigned(fStopWatch);
if Result then
fStopWatch.Start;
finally
FCriticalSection.Leave;
end;
end;
Function TCopyApplicationMonitor.StopStopWatch(): Boolean;
begin
FCriticalSection.Enter;
try
Result := Assigned(fStopWatch);
if Result then
fStopWatch.Stop;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.IncBufferTryLimit;
var
x: Integer;
begin
FCriticalSection.Enter;
try
x := BufferTryLimit;
Inc(x);
BufferTryLimit := x;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.SetBufferEnabled(const Value: Boolean);
begin
if (csDesigning in ComponentState) then
fBufferEnabled := Value
else
begin
FCriticalSection.Enter;
try
fBufferEnabled := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetBufferPolled(const Value: Boolean);
begin
if (csDesigning in ComponentState) then
FBufferPolled := Value
else
begin
FCriticalSection.Enter;
try
FBufferPolled := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetBufferTimer(const Value: TTimer);
begin
FCriticalSection.Enter;
try
fBufferTimer := Value;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.SetBufferTryLimit(const Value: Integer);
begin
FCriticalSection.Enter;
try
fBufferTryLimit := Value;
finally
FCriticalSection.Leave;
end;
end;
procedure TCopyApplicationMonitor.SetDisplayPaste(const Value: Boolean);
begin
if (csDesigning in ComponentState) then
FDisplayPaste := Value
else begin
FCriticalSection.Enter;
try
FDisplayPaste := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetEnabled(aValue: Boolean);
begin
if (csDesigning in ComponentState) then
fEnabled := aValue
else
begin
FCriticalSection.Enter;
try
fEnabled := aValue;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetHighlightColor(const Value: TColor);
begin
if (csDesigning in ComponentState) then
FHighlightColor := Value
else
begin
FCriticalSection.Enter;
try
FHighlightColor := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetEnabled: Boolean;
begin
if (csDesigning in ComponentState) then
Result := fEnabled
else
begin
FCriticalSection.Enter;
try
Result := fEnabled;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetLoadBuffer(const Value: TLoadBuffEvent);
begin
if (csDesigning in ComponentState) then
FLoadBuffer := Value
else
begin
FCriticalSection.Enter;
try
FLoadBuffer := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetLoadedBuffer(const Value: Boolean);
begin
if (csDesigning in ComponentState) then
FLoadedBuffer := Value
else begin
FCriticalSection.Enter;
try
FLoadedBuffer := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetLoadedProperties(aValue: Boolean);
begin
if (csDesigning in ComponentState) then
FLoadedProperties := aValue
else begin
FCriticalSection.Enter;
try
FLoadedProperties := aValue;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetMatchHighlight(const Value: Boolean);
begin
if (csDesigning in ComponentState) then
FMatchHighlight := Value
else
begin
FCriticalSection.Enter;
try
FMatchHighlight := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetMatchStyle(const Value: TFontStyles);
begin
if (csDesigning in ComponentState) then
FMatchStyle := Value
else
begin
FCriticalSection.Enter;
try
FMatchStyle := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetOnLoadProperties
(const Value: TLoadProperties);
begin
if (csDesigning in ComponentState) then
FOnLoadProperties := Value
else
begin
FCriticalSection.Enter;
try
FOnLoadProperties := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetStartPollBuff(const Value: TPollBuff);
begin
if (csDesigning in ComponentState) then
fStartPollBuff := Value
else
begin
FCriticalSection.Enter;
try
fStartPollBuff := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
procedure TCopyApplicationMonitor.SetStopPollBuff(const Value: TPollBuff);
begin
if (csDesigning in ComponentState) then
fStopPollBuff := Value
else
begin
FCriticalSection.Enter;
try
fStopPollBuff := Value;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetLoadBuffer: TLoadBuffEvent;
begin
if (csDesigning in ComponentState) then
Result := FLoadBuffer
else
begin
FCriticalSection.Enter;
try
Result := FLoadBuffer;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetLoadedBuffer: Boolean;
begin
if (csDesigning in ComponentState) then
Result := FLoadedBuffer
else begin
FCriticalSection.Enter;
try
Result := FLoadedBuffer;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetLoadedProperties: Boolean;
begin
if (csDesigning in ComponentState) then
Result := FLoadedProperties
else begin
FCriticalSection.Enter;
try
Result := FLoadedProperties;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetMatchHighlight: Boolean;
begin
if (csDesigning in ComponentState) then
Result := FMatchHighlight
else
begin
FCriticalSection.Enter;
try
Result := FMatchHighlight;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetMatchStyle: TFontStyles;
begin
if (csDesigning in ComponentState) then
Result := FMatchStyle
else
begin
FCriticalSection.Enter;
try
Result := FMatchStyle;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetOnLoadProperties: TLoadProperties;
begin
if (csDesigning in ComponentState) then
Result := FOnLoadProperties
else
begin
FCriticalSection.Enter;
try
Result := FOnLoadProperties;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetStartPollBuff: TPollBuff;
begin
if (csDesigning in ComponentState) then
Result := fStartPollBuff
else
begin
FCriticalSection.Enter;
try
Result := fStartPollBuff;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetStopPollBuff: TPollBuff;
begin
if (csDesigning in ComponentState) then
Result := fStopPollBuff
else
begin
FCriticalSection.Enter;
try
Result := fStopPollBuff;
finally
FCriticalSection.Leave;
end;
end;
end;
function TCopyApplicationMonitor.GetExcludedList(): TStringList;
begin
CriticalSection.Enter;
try
if not Assigned(fExcludedList) then
fExcludedList := TStringList.Create;
Result := fExcludedList;
finally
CriticalSection.Leave;
end;
end;
function TCopyApplicationMonitor.GetHighlightColor: TColor;
begin
if (csDesigning in ComponentState) then
Result := FHighlightColor
else
begin
FCriticalSection.Enter;
try
Result := FHighlightColor;
finally
FCriticalSection.Leave;
end;
end;
end;
{$ENDREGION}
end.
|
unit Componentes;
interface
uses Classes, Controls, StdCtrls, ExtCtrls, Graphics, Forms, Buttons,
JvExButtons, JvBitBtn, JvExStdCtrls, JvButton, JvCtrls, JvLinkLabel,
JvTransparentButton,
{ Fluente }
DataUtil, UnModelo, UnProduto;
const
// Propriedades componente TComanda
COMANDA_ALTURA = 115;
COMANDA_NOME_FONTE = 'Segoe UI';
COMANDA_LARGURA = 200;
COMANDA_MARGENS = 10;
COMANDA_TAMANHO_FONTE = 28;
// Propriedades componente Item de Comanda
ITEM_ALTURA = 40;
ITEM_NOME_FONTE = 'Segoe UI';
ITEM_TAMANHO_FONTE = 16;
// Propriedades componente Bloco de Aplicação no Menu Principal
APLICACAO_ALTURA = 75;
APLICACAO_LARGURA = 135;
APLICACAO_TAMANHO_FONTE = 24;
// Cores utilizadas nos Blocos de Aplicação
AZUL = $00635542;
VERDE = $00767A5F;
VERMELHO = $00699AFD;
AMARELO = $00674761;
ROSA = $007800F0;
TEAL = $0082A901;
type
TComanda = class(TPanel)
private
FAcaoAoClicarNaComanda: TNotifyEvent;
FDescricao: string;
FIdentificacao: string;
FLabelDescricao: TLabel;
FLabelSaldo: TLabel;
FContainer: TWinControl;
FConsumo: Real;
FbtnRegistrarConta: TJvTransparentButton;
FSaldo: Real;
FStatus: Integer;
FImagem: TBitMap;
FBtnOn: Boolean;
FEventoAoFecharConta: TNotifyEvent;
public
function AoClicarNaComanda(
const ExecutarAoClicarNaComanda: TNotifyEvent): TComanda;
function BotaoFecharContaOff: TComanda;
function BotaoFecharContaOn: TComanda;
function ClienteIrregularOff: TComanda;
function ClienteIrregularOn: TComanda;
function Consumo(const Consumo: Real): TComanda;
function Container(const Container: TWinControl): TComanda;
function Descricao(const Descricao: string): TComanda;
function EstaAberta: Boolean;
function Identificacao(const Identificacao: string): TComanda;
function BotaoFecharConta(const NomeComponente: string;
const Imagem: TBitMap; const EventoAoClicarNoBotao: TNotifyEvent): TComanda;
function ObterConsumo: Real;
function ObterIdentificacao: string;
function ObterSaldo: Real;
function Preparar: TComanda;
function Saldo(const Saldo: Real): TComanda;
function Status(const Status: Integer): TComanda;
function ZerarComanda: TComanda;
published
procedure ProcessarClickBotaoFecharConta(Sender: TObject);
end;
TComandas = class
private
FComandas: TStringList;
public
constructor Create; reintroduce;
function adicionarComanda(const Sequencia: string;
const Comanda: TComanda): TComandas;
function obterComanda(const Sequencia: string): TComanda;
end;
TItemEdit = class(TPanel)
private
FBtnImprimir: TSpeedButton;
FLabelProduto: TLabel;
FLabelQuantidade: TLabel;
FLabelValorUnitario: TLabel;
FLabelTotal: TLabel;
FItem: TItem;
FBtnEditItem: TSpeedButton;
{--inicio---> Edição de Quantidade }
FBtnInc: TButton;
FEditQtde: TEdit;
FBtnDec: TButton;
FAntesDeEditar: TNotifyEvent;
FAlterarIngredientes: TNotifyEvent;
FAposEditar: TNotifyEvent;
{--fim------> Edição de Quantidade }
FImagens: TImageList;
protected
function criaTexto(const aTexto: string): TLabel;
public
function AlterarIngredientes(const AcaoParaExecutarAlteracaoDeIngredientes: TNotifyEvent): TItemEdit;
function AntesDeEditar(const AcaoParaExecutarAntesDeEditar: TNotifyEvent): TItemEdit;
function AposEditar(const AcaoParaExecutarAposEditar: TNotifyEvent): TItemEdit;
function Container(const Container: TWinControl): TItemEdit;
function Imagens(const Imagens: TImageList): TItemEdit;
function Montar: TItemEdit;
function Item(const Item: TItem): TItemEdit;
function ObterItem: TItem;
published
procedure AtivarEdicaoDeQuantidade(Sender: TObject);
procedure DecrementarQuantidade(Sender: TObject);
procedure DesativarEdicaoDeQuantidade;
procedure ExecutarEdicao(Sender: TObject);
procedure IncrementarQuantidade(Sender: TObject);
end;
implementation
uses SysUtils;
{ TComanda }
function TComanda.AoClicarNaComanda(
const ExecutarAoClicarNaComanda: TNotifyEvent): TComanda;
begin
Self.FAcaoAoClicarNaComanda := ExecutarAoClicarNaComanda;
Result := Self;
end;
function TComanda.BotaoFecharContaOff: TComanda;
begin
Self.FbtnRegistrarConta.Visible := False;
Result := Self;
end;
function TComanda.BotaoFecharContaOn: TComanda;
begin
Self.FbtnRegistrarConta.Visible := True;
Self.FbtnRegistrarConta.Invalidate;
Result := Self;
end;
function TComanda.ClienteIrregularOff: TComanda;
begin
Self.FLabelDescricao.Color := clBtnFace;
Self.FLabelDescricao.Transparent := True;
Result := Self;
end;
function TComanda.ClienteIrregularOn: TComanda;
begin
Self.FLabelDescricao.Color := $000080FF;
Self.FLabelDescricao.Transparent := False;
Result := Self;
end;
function TComanda.Consumo(const Consumo: Real): TComanda;
begin
Self.FConsumo := Consumo;
Result := Self;
end;
function TComanda.Container(const Container: TWinControl): TComanda;
begin
Self.FContainer := Container;
Result := Self;
end;
function TComanda.Descricao(const Descricao: string): TComanda;
begin
Self.FDescricao := Descricao;
if Self.FLabelDescricao <> nil then
Self.FLabelDescricao.Caption := Self.FDescricao;
Result := Self;
end;
function TComanda.EstaAberta: Boolean;
begin
Result := Self.FStatus = 0;
end;
function TComanda.Identificacao(const Identificacao: string): TComanda;
begin
Self.FIdentificacao := Identificacao;
Result := Self;
end;
function TComanda.BotaoFecharConta(const NomeComponente: string;
const Imagem: TBitMap; const EventoAoClicarNoBotao: TNotifyEvent): TComanda;
begin
Self.FImagem := Imagem;
if NomeComponente = 'On' then
Self.FBtnOn := True
else
Self.FBtnOn := False;
Self.FEventoAoFecharConta := EventoAoClicarNoBotao;
Result := Self;
end;
function TComanda.ObterConsumo: Real;
begin
Result := Self.FConsumo;
end;
function TComanda.ObterIdentificacao: string;
begin
Result := Self.FIdentificacao;
end;
function TComanda.ObterSaldo: Real;
begin
Result := Self.FSaldo;
end;
function TComanda.Preparar: TComanda;
var
_divisor: TSplitter;
_comandos: TPanel;
begin
// Painel da Comanda
inherited create(Self.FContainer);
Self.Height := COMANDA_ALTURA;
Self.Width := COMANDA_LARGURA;
Self.ParentBackground := False;
Self.Parent := Self.FContainer;
Self.ParentColor := False;
Self.Color := TEAL;
Self.AlignWithMargins := True;
Self.Margins.Top := 15;
Self.Margins.Left := 15;
Self.Margins.Right := 15;
Self.Margins.Bottom := 15;
// Painel de comandos no topo da comanda
_comandos := TPanel.Create(Self);
_comandos.Height := 60;
_comandos.Align := alTop;
_comandos.Parent := Self;
_comandos.BevelInner := bvNone;
_comandos.BevelOuter := bvNone;
// botão de fechamento automático de conta fiado
Self.FbtnRegistrarConta := TJvTransparentButton.Create(_comandos);
Self.FbtnRegistrarConta.Align := alRight;
Self.FbtnRegistrarConta.Width := 60;
Self.FbtnRegistrarConta.FrameStyle := fsNone;
Self.FbtnRegistrarConta.Glyph := Self.FImagem;
Self.FbtnRegistrarConta.Visible := Self.FBtnOn;
Self.FbtnRegistrarConta.OnClick := Self.ProcessarClickBotaoFecharConta;
Self.FbtnRegistrarConta.Parent := _comandos;
// TLabel com o nome do cliente ou mesa
Self.FLabelDescricao := TLabel.Create(Self);
Self.FLabelDescricao.Alignment := taCenter;
Self.FLabelDescricao.Caption := Self.FDescricao;
Self.FLabelDescricao.Font.Name := COMANDA_NOME_FONTE;
Self.FLabelDescricao.Font.Size := COMANDA_TAMANHO_FONTE;
Self.FLabelDescricao.Font.Color := $00F5EAE8;
Self.FLabelDescricao.Font.Style := [fsBold];
Self.FLabelDescricao.Align := alClient;
Self.FLabelDescricao.Parent := _comandos;
Self.FLabelDescricao.Transparent := False;
Self.FLabelDescricao.ParentColor := False;
Self.FLabelDescricao.Color := clBtnFace;
Self.FLabelDescricao.OnClick := Self.FAcaoAoClicarNaComanda;
Self.FLabelDescricao.Transparent := True;
Self.FLabelDescricao.Tag := Integer(Self);
// Splitter
_divisor := TSplitter.Create(Self);
_divisor.Align := alTop;
_divisor.Parent := Self;
// TLabel com o Saldo da Comanda
Self.FLabelSaldo := TLabel.Create(Self);
Self.FLabelSaldo.Alignment := taCenter;
Self.FLabelSaldo.Font.Name := COMANDA_NOME_FONTE;
Self.FLabelSaldo.Font.Style := [fsBold];
Self.FLabelSaldo.Font.Size := COMANDA_TAMANHO_FONTE;
Self.FLabelSaldo.Font.Color := clBtnFace;
Self.FLabelSaldo.Align := alClient;
Self.FLabelSaldo.Parent := Self;
Self.FLabelSaldo.Transparent := False;
Self.FLabelSaldo.ParentColor := False;
Self.FLabelSaldo.OnClick := Self.FAcaoAoClicarNaComanda;
Self.FLabelSaldo.Transparent := True;
Self.FLabelSaldo.Tag := Integer(Self);
Self.Saldo(Self.FSaldo);
Result := Self;
end;
procedure TComanda.ProcessarClickBotaoFecharConta(Sender: TObject);
begin
if Assigned(Self.FEventoAoFecharConta) then
Self.FEventoAoFecharConta(Self);
end;
function TComanda.Saldo(const Saldo: Real): TComanda;
begin
Self.FSaldo := Saldo;
if Self.FSaldo > 0 then
Self.Color := $0082A901
else
Self.Color := clGray;
if Self.FLabelSaldo <> nil then
Self.FLabelSaldo.Caption := FormatFloat('R$ ###,##0.00', Self.FSaldo);
Result := Self;
end;
function TComanda.Status(const Status: Integer): TComanda;
begin
Self.FStatus := Status;
Result := Self;
end;
function TComanda.ZerarComanda: TComanda;
begin
Self.FbtnRegistrarConta.Visible := False;
Self.Saldo(0);
Self.Identificacao(IntToStr(Self.Tag));
Self.Descricao('*****');
Self.Status(-1);
Result := Self;
end;
{ TItemEdit }
function TItemEdit.AlterarIngredientes(
const AcaoParaExecutarAlteracaoDeIngredientes: TNotifyEvent): TItemEdit;
begin
Self.FAlterarIngredientes := AcaoParaExecutarAlteracaoDeIngredientes;
Result := Self;
end;
function TItemEdit.AntesDeEditar(
const AcaoParaExecutarAntesDeEditar: TNotifyEvent): TItemEdit;
begin
Self.FAntesDeEditar := AcaoParaExecutarAntesDeEditar;
Result := Self;
end;
function TItemEdit.AposEditar(
const AcaoParaExecutarAposEditar: TNotifyEvent): TItemEdit;
begin
Self.FAposEditar := AcaoParaExecutarAposEditar;
Result := Self;
end;
procedure TItemEdit.AtivarEdicaoDeQuantidade(Sender: TObject);
begin
if Assigned(Self.FAntesDeEditar) then
Self.FAntesDeEditar(Self);
Self.FBtnEditItem.HelpKeyword := 'Quantidade';
Self.FBtnDec.Visible := True;
Self.FEditQtde.Visible := True;
Self.FBtnInc.Visible := True;
Self.FBtnEditItem.Glyph := nil;
Self.FImagens.GetBitmap(2, Self.FBtnEditItem.Glyph);
Self.FBtnEditItem.Repaint;
end;
function TItemEdit.Container(const Container: TWinControl): TItemEdit;
begin
Self.Visible := False;
Self.Parent := Container;
Result := Self;
end;
function TItemEdit.criaTexto(const aTexto: string): TLabel;
begin
Result := TLabel.Create(Self);
Result.Font.Name := ITEM_NOME_FONTE;
Result.Font.Size := ITEM_TAMANHO_FONTE;
Result.Font.Style := [fsBold];
Result.Font.Color := clTeal;
Result.Caption := aTexto;
end;
procedure TItemEdit.DecrementarQuantidade(Sender: TObject);
var
_quantidade: Integer;
begin
_quantidade := StrToInt(Self.FEditQtde.Text);
// if _quantidade > 1 then
Dec(_quantidade);
if _quantidade = 0 then
_quantidade := -1;
Self.FEditQtde.Text := IntToStr(_quantidade);
end;
procedure TItemEdit.DesativarEdicaoDeQuantidade;
begin
Self.FBtnEditItem.HelpKeyword := '';
Self.FBtnDec.Visible := False;
Self.FEditQtde.Visible := False;
Self.FBtnInc.Visible := False;
Self.FBtnEditItem.Glyph := nil;
Self.FImagens.GetBitmap(1, Self.FBtnEditItem.Glyph);
Self.FBtnEditItem.Repaint;
end;
procedure TItemEdit.ExecutarEdicao(Sender: TObject);
begin
if TControl(Sender).HelpKeyword = 'Quantidade' then
begin
{ Edição de quantidade do item }
Self.FItem.AumentarQuantidadeEm(StrToInt(Self.FEditQtde.Text));
Self.DesativarEdicaoDeQuantidade;
if Assigned(Self.FAposEditar) then
Self.FAposEditar(Self.FItem);
Self.FLabelQuantidade.Caption :=
IntToStr(Trunc(Self.FItem.ObterQuantidade));
Self.FLabelTotal.Caption :=
FormatFloat('#,##0.00',
Self.FItem.ObterProduto.GetValor * Self.FItem.ObterQuantidade);
end
else
begin
{ Edição de ingredientes do item }
if Assigned(Self.FAntesDeEditar) then
Self.FAntesDeEditar(Self);
if Assigned(Self.FAlterarIngredientes) then
Self.FAlterarIngredientes(Self);
if Assigned(Self.FAposEditar) then
Self.FAposEditar(Self);
end;
end;
function TItemEdit.Imagens(const Imagens: TImageList): TItemEdit;
begin
Self.FImagens := Imagens;
Result := Self;
end;
procedure TItemEdit.IncrementarQuantidade(Sender: TObject);
var
_quantidade: Integer;
begin
_quantidade := StrToInt(Self.FEditQtde.Text);
Inc(_quantidade);
Self.FEditQtde.Text := IntToStr(_quantidade);
end;
function TItemEdit.Montar: TItemEdit;
var
_deslocamento: Integer;
begin
_deslocamento := 2;
Self.Height := ITEM_ALTURA;
{ Botão de Impressão }
Self.FBtnImprimir := TSpeedButton.Create(Self);
Self.FBtnImprimir.Caption := '';
Self.FImagens.GetBitmap(0, Self.FBtnImprimir.Glyph);
Self.FBtnImprimir.Top := 2;
Self.FBtnImprimir.Parent := Self;
Self.FBtnImprimir.Left := _deslocamento;
Self.FBtnImprimir.Width := 35;
Self.FBtnImprimir.Height := 35;
_deslocamento := _deslocamento + Self.FBtnImprimir.Width;
{ Produto }
Self.FLabelProduto := Self.criaTexto(Self.FItem.ObterProduto.GetDescricao());
Self.FLabelProduto.Parent := Self;
Self.FLabelProduto.Width := 300;
Self.FLabelProduto.Left := _deslocamento + 2;
Self.FLabelProduto.Top := 5;
_deslocamento := _deslocamento + 2 + Self.FLabelProduto.Width;
{ Valor Unitário }
Self.FLabelValorUnitario := Self.criaTexto(FormatFloat('#,##0.00', Self.FItem.ObterProduto.GetValor));
Self.FLabelValorUnitario.Parent := Self;
Self.FLabelValorUnitario.Alignment := taRightJustify;
Self.FLabelValorUnitario.Width := 80;
Self.FLabelValorUnitario.Left := _deslocamento + 15;
Self.FLabelValorUnitario.Top := 5;
_deslocamento := _deslocamento + 15 + Self.FLabelValorUnitario.Width;
{ Quantidade }
Self.FLabelQuantidade := Self.criaTexto(FormatFloat('##0', Self.FItem.ObterQuantidade));
Self.FLabelQuantidade.Parent := Self;
Self.FLabelQuantidade.Alignment := taLeftJustify;
Self.FLabelQuantidade.Width := 45;
Self.FLabelQuantidade.Left := _deslocamento + 65;
Self.FLabelQuantidade.Color := clGray;
Self.FLabelQuantidade.Top := 5;
Self.FLabelQuantidade.OnClick := Self.AtivarEdicaoDeQuantidade;
_deslocamento := _deslocamento + 65 + Self.FLabelQuantidade.Width;
{---->Campos para edição de quantidade }
Self.FBtnDec := TButton.Create(nil);
Self.FBtnDec.Visible := False;
Self.FBtnDec.Caption := '-';
Self.FBtnDec.Width := 40;
Self.FBtnDec.Height := 40;
Self.FBtnDec.Font.Size := 14;
Self.FBtnDec.Font.Style := [fsBold];
Self.FBtnDec.Left:= _deslocamento - 20;
Self.FBtnDec.Parent := Self;
Self.FBtnDec.OnClick := Self.DecrementarQuantidade;
Self.FEditQtde := TEdit.Create(nil);
Self.FEditQtde.Visible := False;
Self.FEditQtde.ParentCtl3D := False;
Self.FEditQtde.Ctl3D := False;
Self.FEditQtde.Font.Name := 'Segoe UI';
Self.FEditQtde.Font.Size := 18;
Self.FEditQtde.Font.Color := clTeal;
Self.FEditQtde.Width := 45;
Self.FEditQtde.Height := 38;
Self.FEditQtde.Left := _deslocamento + 22;
Self.FEditQtde.Text := '1';
Self.FEditQtde.ReadOnly := True;
Self.FEditQtde.Parent := Self;
Self.FBtnInc := TButton.Create(nil);
Self.FBtnInc.Visible := False;
Self.FBtnInc.Caption := '+';
Self.FBtnInc.Width := 40;
Self.FBtnInc.Height := 40;
Self.FBtnInc.Font.Size := 14;
Self.FBtnInc.Font.Style := [fsBold];
Self.FBtnInc.Left:= _deslocamento -20 + 42 + 45;
Self.FBtnInc.OnClick := Self.IncrementarQuantidade;
Self.FBtnInc.Parent := Self;
{---->}
{ Total }
Self.FLabelTotal := Self.criaTexto(FormatFloat('#,##0.00',
Self.FItem.ObterQuantidade * Self.FItem.ObterProduto.GetValor));
Self.FLabelTotal.Parent := Self;
Self.FLabelTotal.Alignment := taRightJustify;
Self.FLabelTotal.Width := 95;
Self.FLabelTotal.Left := _deslocamento + 87;
Self.FLabelTotal.Top := 5;
_deslocamento := _deslocamento + 87 + Self.FLabelTotal.Width;
{ Botao de Edicao }
Self.FBtnEditItem := TSpeedButton.Create(Self);
Self.FImagens.GetBitmap(1, Self.FBtnEditItem.Glyph);
Self.FBtnEditItem.Parent := Self;
Self.FBtnEditItem.Left := _deslocamento + 20;
Self.FBtnEditItem.Top := 2;
Self.FBtnEditItem.Width := 35;
Self.FBtnEditItem.Height := 35;
Self.FBtnEditItem.OnClick := Self.ExecutarEdicao;
{ Configura Painel}
Self.Align := alTop;
Self.Visible := True;
Result := Self;
end;
function TItemEdit.Item(const Item: TItem): TItemEdit;
begin
Self.FItem := Item;
Result := Self;
end;
function TItemEdit.ObterItem: TItem;
begin
Result := Self.FItem;
end;
{ TComandas }
function TComandas.adicionarComanda(const Sequencia: string;
const Comanda: TComanda): TComandas;
begin
Self.FComandas.AddObject(Sequencia, Comanda);
Result := Self;
end;
constructor TComandas.Create;
begin
Self.FComandas := TStringList.Create;
end;
function TComandas.obterComanda(const Sequencia: string): TComanda;
var
_indice: Integer;
begin
_indice := Self.FComandas.IndexOf(Sequencia);
if _indice <> - 1 then
Result := (Self.FComandas.Objects[_indice] as TComanda)
else
Result := nil;
end;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x20;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray);
implementation
Uses SysUtils;
(*
Type $20 - Security1 - X10, KD101, Visionic, Melantech
Buffer[0] = packetlength = $08;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = id3
Buffer[7] = status
Buffer[8] = battery_level:4/rssi:4
Test Strings :
0820004DD3DC540089
xPL Schema
x10.security
{
command=alert|normal|motion|light|dark|arm-home|arm-away|disarm|panic|lights-on|lights-off
device=<device id>
protocol=x10-door|x10-motion|x10-remote|kd101|visionic-door|visionic-motion|melantech
[tamper=true|false]
[low-battery=true|false]
[delay=min|max]
}
*)
const
// Packet length
PACKETLENGTH = $08;
// Type
SECURITY1 = $20;
// Subtype
X10_DOOR = $00;
X10_MOTION = $01;
X10_REMOTE = $02;
KD101 = $03;
VISIONIC_DOOR = $04;
VISIONIC_MOTION = $05;
MELANTECH = $08;
// SubTypeStrings
X10_DOOR_STR = 'x10-door';
X10_MOTION_STR = 'x10-motion';
X10_REMOTE_STR = 'x10-remote';
KD101_STR = 'kd101';
VISIONIC_DOOR_STR = 'visionic-door';
VISIONIC_MOTION_STR = 'visionic-motion';
MELANTECH_STR = 'melantech';
// Commands
COMMAND_ALERT = 'alert';
COMMAND_NORMAL = 'normal';
COMMAND_MOTION = 'motion';
COMMAND_LIGHT = 'light';
COMMAND_DARK = 'dark';
COMMAND_ARM_HOME = 'arm-home';
COMMAND_ARM_AWAY = 'arm-away';
COMMAND_DISARM = 'disarm';
COMMAND_PANIC = 'panic';
COMMAND_LIGHTS_ON = 'lights-on';
COMMAND_LIGHTS_OFF = 'lights-off';
var
SubTypeArray : array[1..7] of TRFXSubTypeRec =
((SubType : X10_DOOR; SubTypeString : X10_DOOR_STR),
(SubType : X10_MOTION; SubTypeString : X10_MOTION_STR),
(SubType : X10_REMOTE; SubTypeString : X10_REMOTE_STR),
(SubType : KD101; SubTypeString : KD101_STR),
(SubType : VISIONIC_DOOR; SubTypeString : VISIONIC_DOOR_STR),
(SubType : VISIONIC_MOTION; SubTypeString : VISIONIC_MOTION_STR),
(SubType : MELANTECH; SubTypeString : MELANTECH_STR));
//?? RFXCOMMANDARRAY for security ??
// TO CHECK : how this works
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
DeviceID : String;
Command : String;
SubType : Byte;
Tamper : Boolean;
BatteryLevel : Integer;
Delay : Boolean;
xPLMessage : TxPLMessage;
begin
SubType := Buffer[2];
DeviceID := '0x'+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2)+IntToHex(Buffer[6],2);
case Buffer[7] of
$00, $01, $05, $7, $80, $81, $85 : Command := COMMAND_NORMAL;
$02, $03, $82,$83 : Command := COMMAND_ALERT;
$04, $84 : Command := COMMAND_MOTION;
$06 : Command := COMMAND_PANIC;
$09, $0A : Command := COMMAND_ARM_AWAY;
$0B, $0C : Command := COMMAND_ARM_HOME;
$0D : Command := COMMAND_DISARM;
$10, $12 : Command := COMMAND_LIGHTS_OFF;
$11, $13 : Command := COMMAND_LIGHTS_ON;
end;
case Buffer[7] of
$01, $03, $0A, $0C, $81, $83 : Delay := True;
end;
case Buffer[7] of
$80, $82, $84, $85 : Tamper := True;
end;
if (Buffer[8] and $0F) = 0 then // zero out rssi
BatteryLevel := 0
else
BatteryLevel := 100;
// Create control.basic message
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'x10.security';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('protocol='+GetSubTypeString(Buffer[2],SubTypeArray));
xPLMessage.Body.AddKeyValue('command='+Command);
if Tamper then
xPLMessage.Body.AddKeyValue('tamper=true')
else
xPLMessage.Body.AddKeyValue('tamper=false');
if Delay then
xPLMessage.Body.AddKeyValue('delay=max')
else
xPLMessage.Body.AddKeyValue('delay=min');
if BatteryLevel = 0 then
xPLMessage.Body.AddKeyValue('low-battery=true');
xPLMessages.Add(xPLMessage.RawXPL);
end;
procedure xPL2RFX(aMessage : TxPLMessage; var Buffer : BytesArray);
var
Command : String;
Tamper : String;
Delay : String;
begin
ResetBuffer(Buffer);
Buffer[0] := PACKETLENGTH;
Buffer[1] := SECURITY1; // Type
Buffer[2] := GetSubTypeFromString(aMessage.Body.Strings.Values['protocol'],SubTypeArray); // Subtype
// DeviceID
Buffer[4] := StrToInt('$'+Copy(aMessage.Body.Strings.Values['device'],3,2));
Buffer[5] := StrToInt('$'+Copy(aMessage.Body.Strings.Values['device'],5,2));
Buffer[6] := StrToInt('$'+Copy(aMessage.Body.Strings.Values['device'],7,2));
// Command
Command := aMessage.Body.Strings.Values['command'];
Tamper := aMessage.Body.Strings.Values['tamper'];
Delay := aMessage.Body.Strings.Values['delay'];
if CompareText(Command,COMMAND_NORMAL) = 0 then
begin
if (CompareText(Tamper,'true') = 0) and (CompareText(Delay,'true') = 0) then
Buffer[7] := $81 else
if CompareText(Tamper,'true') = 0 then
Buffer[7] := $80 else
if CompareText(Delay,'true') = 0 then
Buffer[7] := $01 else
Buffer[7] := $00;
end else
if CompareText(Command,COMMAND_ALERT) = 0 then
begin
if (CompareText(Tamper,'true') = 0) and (CompareText(Delay,'true') = 0) then
Buffer[7] := $83 else
if CompareText(Tamper,'true') = 0 then
Buffer[7] := $82 else
if CompareText(Delay,'true') = 0 then
Buffer[7] := $03 else
Buffer[7] := $02;
end else
if CompareText(Command,COMMAND_MOTION) = 0 then
begin
if CompareText(Tamper,'true') = 0 then
Buffer[7] := $84
else
Buffer[7] := $04;
end else
if CompareText(Command,COMMAND_PANIC) = 0 then
begin
Buffer[7] := $06;
end else
if CompareText(Command,COMMAND_ARM_AWAY) = 0 then
begin
if CompareText(Delay,'true') = 0 then
Buffer[7] := $0A
else
Buffer[7] := $09;
end else
if CompareText(Command,COMMAND_ARM_HOME) = 0 then
begin
if CompareText(Delay,'true') = 0 then
Buffer[7] := $0C
else
Buffer[7] := $0B;
end else
if CompareText(Command,COMMAND_LIGHTS_ON) = 0 then
begin
Buffer[7] := $11;
end else
if CompareText(Command,COMMAND_LIGHTS_OFF) = 0 then
begin
Buffer[7] := $10;
end;
end;
end.
|
unit UnitConversor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls,
Data.DBXJSON, Data.DBXJSONCommon, Data.DBXJSONReflect, System.JSON,
System.JSONConsts, System.IOUtils, Data.DB, Datasnap.DBClient,
Datasnap.Provider, Vcl.Grids, Vcl.DBGrids, InterfaceConversor,
FactoryConversor;
type
TForm1 = class(TForm)
btnCarregarJson: TButton;
btnCarregarXml: TButton;
btnCarregarCsv: TButton;
rchTextos: TRichEdit;
gridJSON: TDBGrid;
cdsConversor: TClientDataSet;
dsConversor: TDataSource;
procedure btnCarregarCsvClick(Sender: TObject);
procedure btnCarregarJsonClick(Sender: TObject);
procedure btnCarregarXmlClick(Sender: TObject);
private
Factory: TFactoryConversor;
Conversor: TConversor;
const
ArquivoJSON =
'C:\Users\Gabriel Scavassa\Documents\Embarcadero\Studio\Projects\Design Patterns\'
+ 'Design-Patterns\Abstract Factory Conversor\mockdata\data.json';
ArquivoXML =
'C:\Users\Gabriel Scavassa\Documents\Embarcadero\Studio\Projects\Design Patterns\'
+ 'Design-Patterns\Abstract Factory Conversor\mockdata\data.xml';
ArquivoCSV =
'C:\Users\Gabriel Scavassa\Documents\Embarcadero\Studio\Projects\Design Patterns\Design-Patterns\'
+ 'Abstract Factory Conversor\mockdata\data.csv';
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
JSONToDataSet, CSVToDataSet, XMlToDataSet;
{$R *.dfm}
procedure TForm1.btnCarregarCsvClick(Sender: TObject);
begin
Conversor := nil;
Factory := TFactoryConversor.Create;
try
rchTextos.Lines.Clear;
Conversor := Factory.ConverterArquivo(ArquivoCSV, cdsConversor);
Conversor.Converter;
finally
Conversor.Free;
Factory.Free;
end;
end;
procedure TForm1.btnCarregarJsonClick(Sender: TObject);
begin
Conversor := nil;
Factory := TFactoryConversor.Create;
try
rchTextos.Lines.Clear;
Conversor := Factory.ConverterArquivo(ArquivoJSON, cdsConversor);
Conversor.Converter;
finally
Conversor.Free;
Factory.Free;
end;
end;
procedure TForm1.btnCarregarXmlClick(Sender: TObject);
begin
Conversor := nil;
Factory := TFactoryConversor.Create;
try
rchTextos.Lines.Clear;
Conversor := Factory.ConverterArquivo(ArquivoXML, cdsConversor);
Conversor.Converter;
finally
Conversor.Free;
Factory.Free;
end;
end;
end.
|
unit classe.MakeCategory;
interface
type
TMakeCategory = class
private
//
public
procedure createType(valName : String);
end;
implementation
{ TMakeType }
uses classe.Category;
procedure TMakeCategory.createType(valName: String);
var
MyType : TCategory;
begin
MyType := TCategory.Create;
try
MyType.Name := valName;
MyType.SaveInDatabase;
finally
MyType.Free;
end;
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, Vcl.Menus, UWP.Form,
UWP.Caption, UWP.Classes, UWP.Button, UWP.Slider, UWP.Text, ComObj, ActiveX,
UWP.QuickButton, UWP.ColorManager, ShellApi, settings, System.Actions,
Vcl.ActnList, Registry, UWP.Panel, NVAPI;
const
WM_SHELLEVENT = WM_USER + 11;
WM_RESIZEEVENT = WM_USER + 12;
type
WinIsWow64 = function(aHandle: THandle; var Iret: BOOL): Winapi.Windows.BOOL; stdcall;
PHYSICAL_MONITOR = record
hPhysicalMonitor: THandle;
szPhysicalMonitorDescription: array[0..127] of Char;
end;
TMonitorSetting = record
Id: THandle;
Name: array [0..127] of Char;
Contrast: Integer;
Brightness: Integer;
end;
// TUSlider = class (UCL.Slider.TUSlider)
// private
// //https://stackoverflow.com/questions/456488/how-to-add-mouse-wheel-support-to-a-component-descended-from-tgraphiccontrol/34463279#34463279
// fPrevFocus: HWND;
// procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
// procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
// public
// function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
// function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
// procedure MouseWheelHandler(var Message: TMessage); override;
// published
// property OnMouseWheel;
// property OnMouseWheelDown;
// property OnMouseWheelUp;
// end;
TformMain = class(TUWPForm)
TrayIcon1: TTrayIcon;
PopupMenu1: TPopupMenu;
Exit1: TMenuItem;
Settings1: TMenuItem;
N1: TMenuItem;
About1: TMenuItem;
UCaptionBar1: TUWPCaption;
Timer1: TTimer;
USlider1: TUWPSlider;
UButton1: TUWPButton;
UText1: TUWPLabel;
UQuickButton1: TUWPQuickButton;
UButton2: TUWPButton;
USlider2: TUWPSlider;
UText2: TUWPLabel;
tmrHider: TTimer;
ActionList1: TActionList;
actEscape: TAction;
tmr64HelperPersist: TTimer;
UCaptionBar2: TUWPCaption;
UPanel1: TUWPPanel;
UPanel2: TUWPPanel;
USlider3: TUWPSlider;
UText3: TUWPLabel;
DarkerOverlay1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure USlider1Change(Sender: TObject);
procedure UButton1Click(Sender: TObject);
procedure UButton2Click(Sender: TObject);
procedure USlider1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure USlider2Change(Sender: TObject);
procedure Exit1Click(Sender: TObject);
procedure Settings1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure TrayIcon1Click(Sender: TObject);
procedure tmrHiderTimer(Sender: TObject);
procedure About1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actEscapeExecute(Sender: TObject);
procedure tmr64HelperPersistTimer(Sender: TObject);
procedure USlider3MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure UCaptionBar2DblClick(Sender: TObject);
procedure USlider3MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure USlider3Change(Sender: TObject);
procedure DarkerOverlay1Click(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
protected
{ Protected declarations : known to all classes in the hierearchy}
function GetMainTaskbarPosition:Integer;
procedure ShowPopup;
procedure CreateParams(var Params: TCreateParams); override;
private
{ Private declarations : only known to the parent class }
fPrevBrightness: Cardinal;
fPrevContrast: Cardinal;
procedure WMHotkey(var Msg: TWMHotKey); message WM_HOTKEY;
procedure ShellEvent(var Msg: TMessage); message WM_SHELLEVENT;
procedure ResizeEvent(var Msg: TMessage); message WM_RESIZEEVENT;
function Is64bits: Boolean;
procedure RunWinEvent;
function SetDisplayGamma(AGammaValue: Byte): Boolean;
public
Settings: TSettings;
{ Public declarations : known externally by class users}
procedure SetHotKey(Sender: TObject; AHotKey: TShortCut);
function AutoStartState:Boolean;
procedure SetAutoStart(RunWithWindows: Boolean);
end;
var
formMain: TformMain;
prevRect: TRect;
hook: NativeUInt;
function RunHook(aHandle: HWND): BOOL; stdcall;
external 'SystemHooks.dll' name 'RunHook';
function KillHook: BOOL; stdcall;
external 'SystemHooks.dll' name 'KillHook';
implementation
{$R *.dfm}
uses frmSettings, utils, monitorHandler, frmDarkOverlay;
procedure SetBrightness(Timeout: Integer; Brightness: Byte);
var
FSWbemLocator: OleVariant;
FWMIService: OleVariant;
FWbemObjectSet: OleVariant;
FWbemObject: OleVariant;
oEnum: IEnumVariant;
iValue: LongWord;
begin
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\WMI', '', '');
FWbemObjectSet := FWMIService.ExecQuery('SELECT * FROM WmiMonitorBrightnessMethods Where Active=True', 'WQL', $00000020);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVARIANT;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
FWbemObject.WmiSetBrightness(Timeout, Brightness);
FWbemObject := Unassigned;
end;
end;
function GetBrightness(Timeout: Integer): Integer;
var
FSWbemLocator: OleVariant;
FWMIService: OleVariant;
FWbemObjectSet: OleVariant;
FWbemObject: OleVariant;
oEnum: IEnumVariant;
iValue: LongWord;
begin
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer('localhost', 'root\WMI', '', '');
FWbemObjectSet := FWMIService.ExecQuery('SELECT * FROM WmiMonitorBrightnessMethods Where Active=True', 'WQL', $00000020);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVARIANT;
while oEnum.Next(1, FWbemObject, iValue) = 0 do
begin
Result := FWbemObject.Properties['CurrentBrightness'].Value;
FWbemObject := Unassigned;
end;
end;
procedure TformMain.About1Click(Sender: TObject);
begin
if formSettings.SwitchToPanel(formSettings.cardAbout) then
formSettings.Show;
end;
procedure TformMain.actEscapeExecute(Sender: TObject);
begin
Hide;
end;
function TformMain.AutoStartState: Boolean;
var
reg: TRegistry;
begin
Result := False;
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKeyReadOnly('SOFTWARE\Microsoft\Windows\CurrentVersion\Run');
if reg.ValueExists('MonitorXettings') then
if reg.ReadString('MonitorXettings') <> '' then
Result := True;
reg.CloseKey;
finally
reg.Free;
end;
end;
procedure TformMain.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.WinClassName := 'MonitorXettingsHwnd';
end;
procedure TformMain.DarkerOverlay1Click(Sender: TObject);
begin
DarkerOverlay1.Checked := not DarkerOverlay1.Checked;
if DarkerOverlay1.Checked then
begin
formDarker.Show;
end
else
begin
formDarker.Hide;
end;
end;
procedure TformMain.Exit1Click(Sender: TObject);
begin
Close;
end;
procedure TformMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
DarkerOverlay1.Checked := False;
formDarker.Hide;
end;
procedure TformMain.FormCreate(Sender: TObject);
var
mons: array[0..5] of PHYSICAL_MONITOR;
monitor: TMonitor;
num: DWORD;
I: Integer;
min, max, cur: Cardinal;
// value: MINIMIZEDMETRICS;
begin
// FluentEnabled := True;
AlphaBlend := True;
Color := clBlack;
// value.cbSize := SizeOf(MINIMIZEDMETRICS);
// value.iArrange := ARW_HIDE;
// SystemParametersInfo(SPI_SETMINIMIZEDMETRICS, SizeOf(value), @value, SPIF_UPDATEINIFILE or SPIF_SENDCHANGE);
Settings := TSettingsHandler.LoadSettings;
SetHotKey(Sender, TextToShortCut(Settings.HotKey));
ColorizationManager.ColorizationType := ctDark;
UCaptionBar1.Caption := ' ' + Caption;
monitor := Screen.MonitorFromWindow(Handle);
if GetNumberOfPhysicalMonitorsFromHMONITOR(monitor.Handle, @num) then
begin
if GetPhysicalMonitorsFromHMONITOR(monitor.Handle, num, @mons) then
begin
for I := 0 to num - 1 do
begin
GetMonitorBrightness(mons[I].hPhysicalMonitor, min, cur, max);
UCaptionBar1.Caption := ' ' + mons[I].szPhysicalMonitorDescription;
USlider1.Min := min;
USlider1.Max := max;
USlider1.Value := cur;
USlider1Change(Sender);
GetMonitorContrast(mons[I].hPhysicalMonitor, min, cur, max);
USlider2.Min := min;
USlider2.Max := max;
USlider2.Value := cur;
USlider2Change(Sender);
// SetMonitorBrightness(mons[I].hPhysicalMonitor,round( min+(max-min)*(100/100)));
end;
end;
DestroyPhysicalMonitors(num, @mons);
end;
Application.OnDeactivate := FormDeactivate;
// Hook WH_SHELL
RunHook(Handle);
// Run hook helper if 64 bit Windows
if Is64bits then
begin
ShellExecute(Handle, PChar('OPEN'),PChar(ExtractFilePath(ParamStr(0))+'SystemHooks64.exe'),nil,nil,SW_SHOWNOACTIVATE);
// let's persist so if someone kills this process, we launch it again
tmr64HelperPersist.Enabled := True;
end
else
begin
tmr64HelperPersist.Enabled := False;
// hook winevent here since it requires to be a process similar to OS
// otherwise it won't work
RunWinEvent;
end;
end;
procedure TformMain.FormDeactivate(Sender: TObject);
var
TaskbarHandle: THandle;
begin
TaskbarHandle := FindWindow('Shell_TrayWnd', nil);
if TaskbarHandle <> 0 then
begin
if (GetForegroundWindow <> Handle)
and (GetForegroundWindow <> TaskbarHandle) then
Hide;
if GetForegroundWindow = TaskbarHandle then
tmrHider.Enabled := True;
end;
end;
procedure TformMain.FormDestroy(Sender: TObject);
begin
// restore default gamma value (128)
SetDisplayGamma(128);
if Is64bits then
begin
UnhookWinEvent(hook);
CoUninitialize;
end;
KillHook;
try
Settings.Free;
except
end;
if GlobalFindAtom('MXHOTKEY') <> 0 then
begin
UnregisterHotKey(Handle, GlobalFindAtom('MXHOTKEY'));
GlobalDeleteAtom(GlobalFindAtom('MXHOTKEY'));
end;
if Is64bits then
begin
SendMessageTimeout(FindWindow('MonitorXettings64Hwnd', nil),WM_CLOSE,0,0,SMTO_NORMAL or SMTO_ABORTIFHUNG,500,0);
end;
end;
procedure TformMain.FormShow(Sender: TObject);
begin
// hide from taskbar on form show, form will not be hidden btw
ShowWindow(Application.Handle, SW_HIDE);
end;
function TformMain.GetMainTaskbarPosition: Integer;
const ABNONE = -1;
var
AMonitor: TMonitor;
TaskbarHandle: THandle;
ABData: TAppbarData;
Res: HRESULT;
TaskbarRect: TRect;
begin
Result := ABNONE;
ABData.cbSize := SizeOf(TAppbarData);
Res := SHAppBarMessage(ABM_GETTASKBARPOS, ABData);
if BOOL(Res) then
begin
// return ABE_LEFT=0, ABE_TOP, ABE_RIGHT or ABE_BOTTOM values
Result := ABData.uEdge;
end
else // for some unknown this might fail, so lets do it the hard way
begin
TaskbarHandle := FindWindow('Shell_TrayWnd', nil);
if TaskbarHandle <> 0 then
begin
AMonitor := Screen.MonitorFromWindow(TaskbarHandle);
GetWindowRect(TaskbarHandle, TaskbarRect);
if (AMonitor.Left = TaskbarRect.Left) and (AMonitor.Top = TaskbarRect.Top)
and (AMonitor.Width = TaskbarRect.Width)
then
Result := ABE_TOP
else if (AMonitor.Left + AMonitor.Width = TaskbarRect.Right)
and (AMonitor.Width <> TaskbarRect.Width)
then
Result := ABE_RIGHT
else if (AMonitor.Left = TaskbarRect.Left) and (AMonitor.Top + AMonitor.Height = TaskbarRect.Bottom)
and (AMonitor.Width = TaskbarRect.Width)
then
Result := ABE_BOTTOM
else
Result := ABE_LEFT;
end;
// at this point, there is no Taskbar present, maybe explorer is not running
end;
end;
function TformMain.Is64bits: Boolean;
var
HandleTo64bitprocess: WinIsWow64;
Iret: Winapi.Windows.BOOL;
begin
Result := False;
HandleTo64bitprocess := GetProcAddress(GetModuleHandle(kernel32), 'IsWow64Process');
if Assigned(HandleTo64bitprocess) then
begin
if not HandleTo64bitprocess(GetCurrentProcess, Iret) then
raise Exception.Create('Invalid Handle');
Result := Iret;
end;
end;
procedure TformMain.ResizeEvent(var Msg: TMessage);
var
LHWindow: HWND;
begin
LHWindow := GetForegroundWindow;
if (LHWindow <> 0) and (LHWindow <> formDarker.Handle) then
begin
if DetectFullScreenApp(LHWindow) then
begin
USlider3.Value := 220;
if DarkerOverlay1.Checked then
formDarker.Hide;
end
else
begin
USlider3.Value := 100;
if DarkerOverlay1.Checked then
begin
formDarker.Show;
SendMessageTimeout(formDarker.Handle, WM_RESIZEEVENT, wParam(0), lParam(0), SMTO_ABORTIFHUNG or SMTO_NORMAL, 500, nil);
end;
end;
end;
end;
procedure WinEventProc(hWinEventHook: NativeUInt; dwEvent: DWORD; handle: HWND;
idObject, idChild: LONG; dwEventThread, dwmsEventTime: DWORD);
var
LHWindow: HWND;
LHFullScreen: BOOL;
vRect: TRect;
ParentHandle: HWND;
begin
if (dwEvent = EVENT_OBJECT_LOCATIONCHANGE)
or (dwEvent = EVENT_SYSTEM_FOREGROUND) then
begin
if GetForegroundWindow <> 0 then
begin
GetWindowRect(GetForegroundWindow, vRect);
if prevRect <> vRect
then
begin
prevRect := vRect;
ParentHandle := FindWindow('MonitorXettingsHwnd', nil);
if ParentHandle <> 0 then
SendMessageTimeout(ParentHandle, WM_RESIZEEVENT, wParam(0), lParam(0), SMTO_ABORTIFHUNG or SMTO_NORMAL, 500, nil);
end;
end;
end;
end;
procedure TformMain.RunWinEvent;
begin
CoInitialize(nil);
hook := SetWinEventHook(EVENT_MIN, EVENT_MAX, 0, @WinEventProc, 0, 0, WINEVENT_OUTOFCONTEXT or WINEVENT_SKIPOWNPROCESS );
if hook = 0 then
raise Exception.Create('Couldn''t create event hook');
end;
procedure TformMain.SetAutoStart(RunWithWindows: Boolean);
var
reg: TRegistry;
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion\Run', False);
if RunWithWindows then
reg.WriteString('MonitorXettings', ParamStr(0))
else
if reg.ValueExists('MonitorXettings') then
reg.DeleteValue('MonitorXettings');
reg.CloseKey;
finally
reg.Free;
end;
end;
function TformMain.SetDisplayGamma(AGammaValue: Byte): Boolean;
var
GammaDC: HDC;
GammaArray: array[0..2, 0..255] of Word;
I, Value: Integer;
begin
Result := False;
GammaDC := GetDC(0);
if GammaDC <> 0 then
begin
for I := 0 to 255 do
begin
Value := I * (AGammaValue + 128);
if Value > 65535 then
Value := 65535;
GammaArray[0, I] := Value; // R value of I is mapped to brightness of Value
GammaArray[1, I] := Value; // G value of I is mapped to brightness of Value
GammaArray[2, I] := Value; // B value of I is mapped to brightness of Value
end;
// Note: BOOL will be converted to Boolean here.
Result := SetDeviceGammaRamp(GammaDC, GammaArray);
ReleaseDC(0, GammaDC);
end;
end;
procedure TformMain.SetHotKey(Sender: TObject; AHotKey: TShortCut);
var
key: WORD;
modifier: Integer;
begin
if Sender is TformMain then
AHotKey := TextToShortCut(Settings.HotKey);
key := AHotKey and not (scShift + scCtrl + scAlt);
modifier := 0;
if AHotKey and scShift <> 0 then modifier := MOD_SHIFT + MOD_NOREPEAT;
if AHotKey and scAlt <> 0 then modifier := modifier + MOD_ALT;
if AHotKey and scCtrl <> 0 then modifier := modifier + MOD_CONTROL;
// re-register hotkey
if GlobalFindAtom('MXHOTKEY') <> 0 then
begin
UnregisterHotKey(Handle, GlobalFindAtom('MXHOTKEY'));
GlobalDeleteAtom(GlobalFindAtom('MXHOTKEY'));
end;
if not RegisterHotKey(Handle, GlobalAddAtom('MXHOTKEY'), modifier, key) then
begin
MessageDlg(ShortCutToText(AHotKey) + ' failed to register, try another hotkey.', mtError, [mbOK], 0);
end
else
begin
if Sender is TUWPButton then
begin
MessageDlg(ShortCutToText(AHotKey) + ' successfully registered.', mtInformation, [mbOK], 0);
Settings.HotKey := ShortCutToText(AHotKey);
TSettingsHandler.SaveSettings(formMain.Settings);
end;
end;
end;
procedure TformMain.Settings1Click(Sender: TObject);
begin
formSettings.Visible := not formSettings.Visible;
end;
procedure TformMain.ShellEvent(var Msg: TMessage);
var
title: string;
titleLen: Integer;
LHWindow: HWND;
begin
LHWindow := Msg.WParam;
if GetForegroundWindow = LHWindow then
begin
titleLen := GetWindowTextLength(LHWindow);
if titleLen > 0 then
begin
SetLength(title, titlelen);
GetWindowText(LHWindow, PChar(title), titleLen + 1);
title := PChar(title);
UCaptionBar1.Caption := title;
TrayIcon1.Hint := title;
//detect fullscreen
//if not IsDirectXAppRunningFullScreen then
begin
if DetectFullScreenApp(LHWindow) then
begin
USlider3.Value := 220;
end
else
USlider3.Value := 100;
end;
end;
end;
end;
procedure TformMain.ShowPopup;
const
ABE_NONE = -1;
GAP = 0;
var
TaskbarMonitor: THandle;
TaskbarRect: TRect;
AMonitor: TMonitor;
CurPos: TPoint;
LeftGap: Integer;
TopGap: Integer;
begin
TaskbarMonitor := FindWindow('Shell_TrayWnd', nil);
GetCursorPos(CurPos);
LeftGap := Width - ClientWidth;
TopGap := Height - ClientHeight;
if TaskbarMonitor <> 0 then
begin
AMonitor := Screen.MonitorFromWindow(TaskbarMonitor);
GetWindowRect(TaskbarMonitor, TaskbarRect);
case GetMainTaskbarPosition of
ABE_LEFT: begin
Left := AMonitor.Left + TaskbarRect.Width + GAP - LeftGap div 2;
Top := CurPos.Y - Height div 2;
end;
ABE_TOP: begin
Left := AMonitor.Left + AMonitor.Width - Width - GAP + LeftGap;
Top := AMonitor.Top + TaskbarRect.Height + GAP - TopGap;
end;
ABE_RIGHT: begin
Left := AMonitor.Left + AMonitor.Width - TaskbarRect.Width - Width - GAP + LeftGap div 2;
Top := CurPos.Y - Height div 2;
end;
ABE_BOTTOM: begin
Left := AMonitor.Left + AMonitor.Width - Width - GAP + LeftGap;
Top := AMonitor.Top + AMonitor.Height - TaskbarRect.Height - Height - GAP + TopGap;
end;
ABE_NONE: begin
Position := poScreenCenter;
end;
end;
end;
Visible := not Visible;
SetForegroundWindow(Handle);
end;
procedure TformMain.Timer1Timer(Sender: TObject);
var
changed: Boolean;
begin
changed := False;
if fPrevBrightness <> USlider1.Value then
begin
fPrevBrightness := USlider1.Value;
changed := True;
end;
if fPrevContrast <> USlider2.Value then
begin
changed := True;
fPrevContrast := USlider2.Value;
end;
if changed then
UButton2Click(Sender);
end;
procedure TformMain.tmr64HelperPersistTimer(Sender: TObject);
begin
if FindWindow('MonitorXettings64Hwnd', nil) = 0 then
ShellExecute(Handle, PChar('OPEN'),PChar(ExtractFilePath(ParamStr(0))+'SystemHooks64.exe'),nil,nil,SW_SHOWNOACTIVATE);
end;
procedure TformMain.tmrHiderTimer(Sender: TObject);
var
TaskbarHandle: THandle;
begin
if GetForegroundWindow = Handle then
tmrHider.Enabled := False
else
begin
TaskbarHandle := FindWindow('Shell_TrayWnd', nil);
if TaskbarHandle <> 0 then
begin
if GetForegroundWindow <> TaskbarHandle then
begin
Hide;
tmrHider.Enabled := False;
end;
end;
end;
end;
procedure TformMain.TrayIcon1Click(Sender: TObject);
begin
if not Visible then
ShowPopup
else
Hide;
end;
procedure TformMain.UButton1Click(Sender: TObject);
begin
// old not working, at least not in non laptops
try
CoInitialize(nil);
try
GetBrightness(5);
finally
CoUninitialize;
end;
except
on E:EOleException do
ShowMessage(Format('EOleException %s %x', [E.Message, E.ErrorCode]));
on E:Exception do
ShowMessage(E.ClassName + ':' + E.Message);
end;
end;
procedure TformMain.UButton2Click(Sender: TObject);
var
mons: array[0..5] of PHYSICAL_MONITOR;
monitor: TMonitor;
num: DWORD;
I: Integer;
min, max, cur: Cardinal;
begin
monitor := Screen.MonitorFromWindow(Handle);
if GetNumberOfPhysicalMonitorsFromHMONITOR(monitor.Handle, @num) then
begin
if GetPhysicalMonitorsFromHMONITOR(monitor.Handle, num, @mons) then
begin
for I := 0 to num - 1 do
begin
GetMonitorBrightness(mons[I].hPhysicalMonitor, min, cur, max);
//ListBox1.Items.Add(FloatToStr((cur-min)/(max-min)*100));
USlider1.Min := min;
USlider1.Max := max;
// USlider1.Value := cur;
SetMonitorBrightness(mons[I].hPhysicalMonitor,round( min+(max-min)*(USlider1.Value/100)));
SetMonitorContrast(mons[I].hPhysicalMonitor,round( min+(max-min)*(USlider2.Value/100)));
end;
end;
DestroyPhysicalMonitors(num, @mons);
end;
end;
procedure TformMain.UCaptionBar2DblClick(Sender: TObject);
begin
SetDisplayGamma(128);
USlider3.Value := 128;
UText3.Caption := '128';
end;
procedure TformMain.USlider1Change(Sender: TObject);
begin
UText1.Caption := 'Brightness: ' + USlider1.Value.ToString;
// fPrevBrightness := USlider1.Value;
end;
procedure TformMain.USlider1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
UButton2Click(Sender);
end;
procedure TformMain.USlider2Change(Sender: TObject);
begin
UText2.Caption := 'Contrast: ' + USlider2.Value.ToString;
// fPrevContrast := USlider2.Value;
end;
procedure TformMain.USlider3Change(Sender: TObject);
begin
SetDisplayGamma(USlider3.Value);
UText3.Caption := USlider3.Value.ToString;
end;
procedure TformMain.USlider3MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
SetDisplayGamma(USlider3.Value);
UText3.Caption := USlider3.Value.ToString;
end;
procedure TformMain.USlider3MouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
SetDisplayGamma(USlider3.Value);
UText3.Caption := USlider3.Value.ToString;
end;
procedure TformMain.WMHotkey(var Msg: TWMHotKey);
var
vMonitor: TMonitor;
begin
if Msg.HotKey = GlobalFindAtom('MXHOTKEY') then
begin
if formSettings.Visible and formSettings.HotKey1.Focused then
begin
formSettings.HotKey1.HotKey := TextToShortCut(Settings.HotKey);
Exit;
end;
vMonitor := Screen.MonitorFromWindow(Handle);
Left := vMonitor.Left + (vMonitor.Width - Width) div 2;
Top := vMonitor.Top + (vMonitor.Height - Height) div 2;
Show;
SetForegroundWindow(Handle);
end;
end;
{ TUSlider }
//procedure TUSlider.CMMouseEnter(var Message: TMessage);
//begin
// fPrevFocus := SetFocus(Parent.Handle);
// MouseCapture := True;
// inherited;
//end;
//
//function TUSlider.DoMouseWheelDown(Shift: TShiftState;
// MousePos: TPoint): Boolean;
//begin
// if Self.Value > Self.Min then
// begin
// Self.Value := Self.Value - 1;
// //trigger changeevent
// end;
//end;
//
//function TUSlider.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
//begin
// if Self.Value < Self.Max then
// Self.Value := Self.Value + 1;
//end;
//
//procedure TUSlider.MouseWheelHandler(var Message: TMessage);
//begin
// Message.Result := Perform(CM_MOUSEWHEEL, Message.WParam, Message.LParam);
// if Message.Result = 0 then
// inherited MouseWheelHandler(Message);
//end;
//
//procedure TUSlider.WMMouseMove(var Message: TWMMouseMove);
//begin
// if MouseCapture and not PtInRect(ClientRect, SmallPointToPoint(Message.Pos)) then
// begin
// MouseCapture := False;
// SetFocus(fPrevFocus);
// end;
// inherited;
//end;
end.
|
unit FIToolkit.Reports.Builder.Types;
interface
type
TReportRecord = record
Column,
Line : Integer;
FileName,
MessageText,
MessageTypeKeyword,
MessageTypeName,
Snippet : String;
end;
TSummaryItem = record
MessageCount : Integer;
MessageTypeKeyword,
MessageTypeName : String;
end;
implementation
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls,
Spin, StdCtrls, Buttons;
type
{ TfrmSimpleCalculator }
TfrmSimpleCalculator = class(TForm)
bmbReset: TBitBtn;
btnAdd: TButton;
btnSubtract: TButton;
btnMultiply: TButton;
btnDivide: TButton;
btnModulo: TButton;
edtAnswer: TEdit;
lblAnswer: TLabel;
lblValue1: TLabel;
lblValue2: TLabel;
sedValue1: TSpinEdit;
sedValue2: TSpinEdit;
procedure bmbResetClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnDivideClick(Sender: TObject);
procedure btnModuloClick(Sender: TObject);
procedure btnMultiplyClick(Sender: TObject);
procedure btnSubtractClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmSimpleCalculator: TfrmSimpleCalculator;
implementation
{$R *.lfm}
{ TfrmSimpleCalculator }
procedure TfrmSimpleCalculator.btnAddClick(Sender: TObject);
var Answer: integer;
begin
Answer:=sedValue1.Value+sedValue2.Value;
edtAnswer.Text:=IntToStr(Answer);
lblAnswer.Caption:='Integer addition';
sedValue1.setFocus;
end;
procedure TfrmSimpleCalculator.bmbResetClick(Sender: TObject);
begin
sedValue1.Value:=0;
sedValue2.Value:=0;
edtAnswer.Text:='0';
lblAnswer.Caption:='Answer';
sedValue1.SetFocus;
end;
procedure TfrmSimpleCalculator.btnDivideClick(Sender: TObject);
var Answer: integer;
begin
Answer:=sedValue1.Value DIV sedValue2.Value;
edtAnswer.Text:=IntToStr(Answer);
lblAnswer.Caption:='Integer division';
sedValue1.SetFocus;
end;
procedure TfrmSimpleCalculator.btnModuloClick(Sender: TObject);
var Answer: integer;
begin
Answer:=sedValue1.Value MOD sedValue2.Value;
edtAnswer.Text:=IntToStr(Answer);
lblAnswer.Caption:='Mod remainder';
sedValue1.SetFocus;
end;
procedure TfrmSimpleCalculator.btnMultiplyClick(Sender: TObject);
var Answer: integer;
begin
Answer:=sedValue1.Value*sedValue2.Value;
edtAnswer.Text:=IntToStr(Answer);
lblAnswer.Caption:='Integer multiplication';
sedValue1.SetFocus;
end;
procedure TfrmSimpleCalculator.btnSubtractClick(Sender: TObject);
var Answer: integer;
begin
Answer:=sedValue1.Value-sedValue2.Value;
edtAnswer.Text:=IntToStr(Answer);
lblAnswer.Caption:='Integer subtraction';
sedValue1.SetFocus;
end;
end.
|
unit RestarterDataModule;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, TlHelp32,
ExtCtrls, Db, ADODB;
type
TDataModule1 = class(TDataModule)
tmrCheckRunning: TTimer;
Settings_T: TADOTable;
Settings_Tprocname: TStringField;
Settings_Texename: TStringField;
procedure tmrCheckRunningTimer(Sender: TObject);
procedure DataModuleCreate(Sender: TObject);
private
sAppPath: string;
Function IsProcessRunning(processNameStarts: string): boolean;
Function StartProgram: boolean;
Function ReadXMLSettings(fileName: string):_Recordset;
public
end;
var
DataModule1: TDataModule1;
implementation
uses frmMonitorRestart, ComObj;
{$R *.DFM}
Function TDataModule1.IsProcessRunning(processNameStarts: string): Boolean;
var
bExists: boolean;
entry: PROCESSENTRY32;
snapshot: cardinal;
begin
entry.dwSize := sizeof(PROCESSENTRY32);
bExists := false;
snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
if Process32First(snapshot, entry) then
begin
while Process32Next(snapshot, entry) do
begin
if AnsiPos(LowerCase(processNameStarts), LowerCase(entry.szExeFile)) = 1 then
begin
bExists := true;
break;
end;
end;
end;
CloseHandle(snapshot);
Result := bExists;
end;
procedure TDataModule1.tmrCheckRunningTimer(Sender: TObject);
begin
if not IsProcessRunning(Settings_TProcName.AsString) then
begin
Form1.LogMessage('Monitor process is not running, attempting to restart',EVENTLOG_WARNING_TYPE );
if StartProgram then
begin
Form1.LogMessage('Restarted Monitor application', EVENTLOG_INFORMATION_TYPE);
Form1.lblStatus.Caption := 'Status: checking';
end;
end else
begin
Form1.ProgressBar1.StepBy(1);
if Form1.ProgressBar1.Position = Form1.Progressbar1.Max then
begin
Form1.ProgressBar1.Position := 0;
end;
end;
end;
procedure TDataModule1.DataModuleCreate(Sender: TObject);
var
SettingsRecordSet: _Recordset;
begin
sAppPath := ExtractFilePath(Application.ExeName);
Form1.LogMessage('Monitor restarter process is starting',EVENTLOG_INFORMATION_TYPE);
if not fileExists(sAppPath + 'restarter.xml') then
begin
Form1.LogMessage('Restarter.xml not found, closing down',EVENTLOG_ERROR_TYPE);
Application.Terminate
end;
SettingsRecordSet := ReadXMLSettings(sAppPath + 'restarter.xml');
if SettingsRecordSet = nil then
begin
Form1.LogMessage('Failed to read Restarter.xml, closing down',EVENTLOG_ERROR_TYPE);
Application.Terminate;
end;
Try
Settings_T.Recordset := SettingsRecordSet;
SettingsRecordset := nil;
Settings_T.Active := True ;
Except on E: Exception do
begin
Form1.LogMessage('Failed to set settings recordset: ' + E.Message, EVENTLOG_ERROR_TYPE);
Application.Terminate;
end;
end;
Form1.LogMessage('Monitor restarter process is starting',EVENTLOG_INFORMATION_TYPE);
Form1.lblStatus.Caption := 'Status: checking';
end;
Function TDataModule1.StartProgram: boolean;
var
si: STARTUPINFO;
pi: PROCESS_INFORMATION;
bRetVal: bytebool;
iErrNo: integer;
sFullProgName: string;
begin
sFullProgName := sAppPath + Settings_TExeName.Value;
ZeroMemory( @si, sizeof(si) );
si.cb := sizeof(si);
si.dwFlags := si.dwFlags or STARTF_USESHOWWINDOW;
ZeroMemory( @pi, sizeof(pi) );
bRetVal := CreateProcess(
PChar(sFullProgName),
'',
nil,
nil,
true,
0,
nil,
nil,
si,
pi);
Result := bRetVal;
if not bRetVal then
begin
iErrNo := GetLastError;
Form1.LogMessage('CreateProcess failed with error ' + IntToStr(iErrNo));
Form1.lblStatus.Caption := 'Status: restart failed';
end;
end;
function TDataModule1.ReadXMLSettings(fileName: string):_Recordset;
var
RS: Variant;
Stream: TFileStream;
begin
Result := nil;
try
try
Stream := TFileStream.Create(fileName,fmOpenRead);
Stream.Position := 0;
RS := CreateOleObject('ADODB.Recordset');
RS.Open(TStreamAdapter.Create(Stream) as IUnknown);
Result := IUnknown(RS) as _Recordset;
Result.MoveFirst;
Except on E: Exception do
begin
Form1.LogMessage('Exception in ReadXMLSettings: ' + E.Message, EVENTLOG_ERROR_TYPE);
Application.Terminate;
end;
end;
finally
Stream.Free;
end;
RS := Unassigned;
end;
end.
|
unit DSWrap;
interface
uses
System.Classes, Data.DB, System.SysUtils, System.Generics.Collections,
FireDAC.Comp.Client, FireDAC.Comp.DataSet, NotifyEvents, System.Contnrs,
DBRecordHolder;
type
TFieldWrap2 = class;
TDSWrap2 = class(TComponent)
private
FAfterOpen: TNotifyEventsEx;
FAfterClose: TNotifyEventsEx;
FAfterInsert: TNotifyEventsEx;
FBeforePost: TNotifyEventsEx;
FAfterScroll: TNotifyEventsEx;
FBeforeDelete: TNotifyEventsEx;
FAfterPost: TNotifyEventsEx;
FCloneEvents: TObjectList;
FClones: TObjectList<TFDMemTable>;
FDataSet: TDataSet;
FEventList: TObjectList;
FFieldsWrap: TObjectList<TFieldWrap>;
FPKFieldName: string;
FRecHolder: TRecordHolder;
procedure AfterDataSetScroll(DataSet: TDataSet);
procedure AfterDataSetClose(DataSet: TDataSet);
procedure AfterDataSetOpen(DataSet: TDataSet);
procedure AfterDataSetInsert(DataSet: TDataSet);
procedure CloneAfterClose(Sender: TObject);
procedure CloneAfterOpen(Sender: TObject);
procedure CloneCursor(AClone: TFDMemTable);
procedure DoAfterOpen___(Sender: TObject);
function GetActive: Boolean;
function GetAfterOpen: TNotifyEventsEx;
function GetAfterClose: TNotifyEventsEx;
function GetAfterInsert: TNotifyEventsEx;
function GetBeforePost: TNotifyEventsEx;
function GetAfterScroll: TNotifyEventsEx;
function GetBeforeDelete: TNotifyEventsEx;
function GetAfterPost: TNotifyEventsEx;
function GetFDDataSet: TFDDataSet;
function GetPK: TField;
function GetRecordCount: Integer;
protected
procedure BeforeDataSetPost(DataSet: TDataSet);
procedure BeforeDataSetDelete(DataSet: TDataSet);
procedure AfterDataSetPost(DataSet: TDataSet);
procedure UpdateFields; virtual;
property FDDataSet: TFDDataSet read GetFDDataSet;
property RecHolder: TRecordHolder read FRecHolder;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function AddClone(const AFilter: String): TFDMemTable;
procedure AfterConstruction; override;
procedure ClearFilter;
procedure DropClone(AClone: TFDMemTable);
function Field(const AFieldName: string): TField;
function HaveAnyChanges: Boolean;
function Load(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>; ATestResult: Integer = -1)
: Integer; overload;
function LocateByPK(APKValue: Variant; TestResult: Boolean = False)
: Boolean;
procedure RefreshQuery; virtual;
procedure RestoreBookmark; virtual;
function SaveBookmark: Boolean;
procedure SetFieldsRequired(ARequired: Boolean);
procedure SetFieldsVisible(AVisible: Boolean);
procedure SetParameters(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>);
procedure TryAppend;
procedure TryCancel;
function TryEdit: Boolean;
function TryLocate(AFields: TArray<String>;
AValues: TArray<Variant>): Integer;
function Locate(AFields: TArray<String>; AValues: TArray<Variant>): Boolean;
procedure TryOpen;
procedure TryPost;
property Active: Boolean read GetActive;
property AfterOpen: TNotifyEventsEx read GetAfterOpen;
property AfterClose: TNotifyEventsEx read GetAfterClose;
property AfterInsert: TNotifyEventsEx read GetAfterInsert;
property BeforePost: TNotifyEventsEx read GetBeforePost;
property AfterScroll: TNotifyEventsEx read GetAfterScroll;
property BeforeDelete: TNotifyEventsEx read GetBeforeDelete;
property AfterPost: TNotifyEventsEx read GetAfterPost;
property DataSet: TDataSet read FDataSet;
property EventList: TObjectList read FEventList;
property PK: TField read GetPK;
property PKFieldName: string read FPKFieldName write FPKFieldName;
property RecordCount: Integer read GetRecordCount;
end;
TFieldWrap2 = class(TObject)
private
FDataSetWrap: TDSWrap;
FDefaultValue: Variant;
FDisplayLabel: string;
FFieldName: string;
FVisible: Boolean;
function GetF: TField;
public
constructor Create(ADataSetWrap: TDSWrap; const AFieldName: string;
const ADisplayLabel: string = ''; APrimaryKey: Boolean = False);
property DataSetWrap: TDSWrap read FDataSetWrap;
property DefaultValue: Variant read FDefaultValue write FDefaultValue;
property DisplayLabel: string read FDisplayLabel write FDisplayLabel;
property F: TField read GetF;
property FieldName: string read FFieldName;
property Visible: Boolean read FVisible write FVisible;
end;
implementation
uses
FireDAC.Stan.Param, System.Variants, System.StrUtils;
constructor TDSWrap2.Create(AOwner: TComponent);
begin
inherited;
if not(AOwner is TDataSet) then
raise Exception.Create
('Ошибка при создании TDSWrap. Владелец должен быть TDataSet.');
FDataSet := AOwner as TDataSet;
FFieldsWrap := TObjectList<TFieldWrap>.Create;
FEventList := TObjectList.Create;
end;
destructor TDSWrap2.Destroy;
begin
FreeAndNil(FFieldsWrap);
FreeAndNil(FEventList);
if FAfterOpen <> nil then
FreeAndNil(FAfterOpen);
if FAfterScroll <> nil then
FreeAndNil(FAfterScroll);
inherited;
end;
function TDSWrap2.AddClone(const AFilter: String): TFDMemTable;
begin
// Создаём список клонов
if FClones = nil then
begin
FClones := TObjectList<TFDMemTable>.Create;
// Список подписчиков
FCloneEvents := TObjectList.Create;
// Будем клонировать курсоры
TNotifyEventWrap.Create(AfterOpen, CloneAfterOpen, FCloneEvents);
// Будем закрывать курсоры
TNotifyEventWrap.Create(AfterClose, CloneAfterClose, FCloneEvents);
end;
Result := TFDMemTable.Create(nil); // Владельцем будет список
Result.Filter := AFilter;
// Клонируем
if FDataSet.Active then
CloneCursor(Result);
FClones.Add(Result); // Владельцем будет список
end;
procedure TDSWrap2.AfterConstruction;
begin
inherited;
if FFieldsWrap.Count = 0 then
Exit;
TNotifyEventWrap.Create(AfterOpen, DoAfterOpen___, EventList);
if DataSet.Active then
UpdateFields;
end;
procedure TDSWrap2.AfterDataSetOpen(DataSet: TDataSet);
begin
FAfterOpen.CallEventHandlers(Self);
end;
procedure TDSWrap2.BeforeDataSetPost(DataSet: TDataSet);
begin
FBeforePost.CallEventHandlers(Self);
end;
procedure TDSWrap2.AfterDataSetScroll(DataSet: TDataSet);
begin
FAfterScroll.CallEventHandlers(Self);
end;
procedure TDSWrap2.AfterDataSetClose(DataSet: TDataSet);
begin
FAfterClose.CallEventHandlers(Self);
end;
procedure TDSWrap2.AfterDataSetInsert(DataSet: TDataSet);
begin
FAfterInsert.CallEventHandlers(Self);
end;
procedure TDSWrap2.BeforeDataSetDelete(DataSet: TDataSet);
begin
FBeforeDelete.CallEventHandlers(Self);
end;
procedure TDSWrap2.AfterDataSetPost(DataSet: TDataSet);
begin
FAfterPost.CallEventHandlers(Self);
end;
procedure TDSWrap2.ClearFilter;
begin
FDataSet.Filtered := False;
end;
procedure TDSWrap2.CloneAfterClose(Sender: TObject);
var
AClone: TFDMemTable;
begin
// Закрываем клоны
for AClone in FClones do
AClone.Close;
end;
procedure TDSWrap2.CloneAfterOpen(Sender: TObject);
var
AClone: TFDMemTable;
begin
// клонируем курсоры
for AClone in FClones do
begin
CloneCursor(AClone);
end;
end;
procedure TDSWrap2.CloneCursor(AClone: TFDMemTable);
var
AFilter: String;
begin
// Assert(not AClone.Filter.IsEmpty);
AFilter := AClone.Filter;
AClone.CloneCursor(FDDataSet);
// Если фильтр накладывать не надо
if (AFilter.IsEmpty) then
Exit;
AClone.Filter := AFilter;
AClone.Filtered := True;
end;
procedure TDSWrap2.DoAfterOpen___(Sender: TObject);
begin
UpdateFields;
end;
procedure TDSWrap2.DropClone(AClone: TFDMemTable);
begin
Assert(AClone <> nil);
Assert(FClones <> nil);
FClones.Remove(AClone);
if FClones.Count = 0 then
begin
// Отписываемся
FreeAndNil(FCloneEvents);
// Разрушаем список
FreeAndNil(FClones);
end;
end;
function TDSWrap2.Field(const AFieldName: string): TField;
begin
Result := FDataSet.FieldByName(AFieldName);
end;
function TDSWrap2.GetActive: Boolean;
begin
Result := FDataSet.Active;
end;
function TDSWrap2.GetAfterOpen: TNotifyEventsEx;
begin
if FAfterOpen = nil then
begin
Assert(not Assigned(FDataSet.AfterOpen));
FAfterOpen := TNotifyEventsEx.Create(Self);
FDataSet.AfterOpen := AfterDataSetOpen;
end;
Result := FAfterOpen;
end;
function TDSWrap2.GetAfterClose: TNotifyEventsEx;
begin
if FAfterClose = nil then
begin
Assert(not Assigned(FDataSet.AfterClose));
FAfterClose := TNotifyEventsEx.Create(Self);
FDataSet.AfterClose := AfterDataSetClose;
end;
Result := FAfterClose;
end;
function TDSWrap2.GetAfterInsert: TNotifyEventsEx;
begin
if FAfterInsert = nil then
begin
Assert(not Assigned(FDataSet.AfterInsert));
FAfterInsert := TNotifyEventsEx.Create(Self);
FDataSet.AfterInsert := AfterDataSetInsert;
end;
Result := FAfterInsert;
end;
function TDSWrap2.GetBeforePost: TNotifyEventsEx;
begin
if FBeforePost = nil then
begin
Assert(not Assigned(FDataSet.BeforePost));
FBeforePost := TNotifyEventsEx.Create(Self);
FDataSet.BeforePost := BeforeDataSetPost;
end;
Result := FBeforePost;
end;
function TDSWrap2.GetAfterScroll: TNotifyEventsEx;
begin
if FAfterScroll = nil then
begin
Assert(not Assigned(FDataSet.AfterScroll));
FAfterScroll := TNotifyEventsEx.Create(Self);
FDataSet.AfterScroll := AfterDataSetScroll;
end;
Result := FAfterScroll;
end;
function TDSWrap2.GetBeforeDelete: TNotifyEventsEx;
begin
if FBeforeDelete = nil then
begin
Assert(not Assigned(FDataSet.BeforeDelete));
FBeforeDelete := TNotifyEventsEx.Create(Self);
FDataSet.BeforeDelete := BeforeDataSetDelete;
end;
Result := FBeforeDelete;
end;
function TDSWrap2.GetAfterPost: TNotifyEventsEx;
begin
if FAfterPost = nil then
begin
Assert(not Assigned(FDataSet.AfterPost));
FAfterPost := TNotifyEventsEx.Create(Self);
FDataSet.AfterPost := AfterDataSetPost;
end;
Result := FAfterPost;
end;
function TDSWrap2.GetFDDataSet: TFDDataSet;
begin
Result := FDataSet as TFDDataSet;
end;
function TDSWrap2.GetPK: TField;
begin
if FPKFieldName.IsEmpty then
raise Exception.Create('Имя первичного ключа не задано');
Result := Field(FPKFieldName);
end;
function TDSWrap2.GetRecordCount: Integer;
begin
Result := FDataSet.RecordCount;
end;
function TDSWrap2.HaveAnyChanges: Boolean;
begin
Result := FDataSet.State in [dsEdit, dsinsert];
end;
function TDSWrap2.Load(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>; ATestResult: Integer = -1): Integer;
begin
FDataSet.DisableControls;
try
FDataSet.Close;
SetParameters(AParamNames, AParamValues);
FDataSet.Open;
finally
FDataSet.EnableControls;
end;
Result := FDataSet.RecordCount;
if ATestResult >= 0 then
Assert(Result = ATestResult);
end;
function TDSWrap2.LocateByPK(APKValue: Variant;
TestResult: Boolean = False): Boolean;
begin
Assert(not FPKFieldName.IsEmpty);
Result := FDDataSet.LocateEx(FPKFieldName, APKValue);
if TestResult then
begin
Assert(Result);
end;
end;
procedure TDSWrap2.RefreshQuery;
begin
FDataSet.DisableControls;
try
FDataSet.Close;
FDataSet.Open();
finally
FDataSet.EnableControls;
end;
end;
procedure TDSWrap2.RestoreBookmark;
begin
end;
function TDSWrap2.SaveBookmark: Boolean;
begin
Result := DataSet.Active and not DataSet.IsEmpty;
if not Result then
Exit;
if FRecHolder = nil then
FRecHolder := TRecordHolder.Create(DataSet)
else
FRecHolder.Attach(DataSet);
end;
procedure TDSWrap2.SetFieldsRequired(ARequired: Boolean);
var
AField: TField;
begin
inherited;
for AField in FDataSet.Fields do
AField.Required := ARequired;
end;
procedure TDSWrap2.SetFieldsVisible(AVisible: Boolean);
var
F: TField;
begin
for F in FDataSet.Fields do
F.Visible := AVisible;
end;
procedure TDSWrap2.SetParameters(const AParamNames: TArray<String>;
const AParamValues: TArray<Variant>);
var
i: Integer;
begin
Assert(Low(AParamNames) = Low(AParamValues));
Assert(High(AParamNames) = High(AParamValues));
for i := Low(AParamNames) to High(AParamNames) do
begin
FDDataSet.ParamByName(AParamNames[i]).Value := AParamValues[i];
end;
end;
procedure TDSWrap2.TryAppend;
begin
Assert(FDataSet.Active);
if not(FDataSet.State in [dsEdit, dsinsert]) then
FDataSet.Append;
end;
procedure TDSWrap2.TryCancel;
begin
Assert(FDataSet.Active);
if FDataSet.State in [dsEdit, dsinsert] then
FDataSet.Cancel;
end;
function TDSWrap2.TryEdit: Boolean;
begin
Assert(FDataSet.Active);
Result := False;
if FDataSet.State in [dsEdit, dsinsert] then
Exit;
Assert(FDataSet.RecordCount > 0);
FDataSet.Edit;
Result := True;
end;
function TDSWrap2.TryLocate(AFields: TArray<String>;
AValues: TArray<Variant>): Integer;
var
AKeyFields: string;
ALength: Integer;
Arr: Variant;
J: Integer;
OK: Boolean;
begin
Assert(Length(AFields) > 0);
Assert(Length(AValues) > 0);
Assert(Length(AFields) = Length(AValues));
for ALength := Length(AValues) downto 1 do
begin
Result := ALength;
AKeyFields := '';
// Создаём вариантный массив
Arr := VarArrayCreate([0, ALength - 1], varVariant);
for J := 0 to ALength - 1 do
begin
AKeyFields := AKeyFields + IfThen(AKeyFields.IsEmpty, '', ';') +
AFields[J];
Arr[J] := AValues[J];
end;
OK := FDDataSet.LocateEx(AKeyFields, Arr, []);
VarClear(Arr);
if OK then
Exit;
end;
Result := 0;
end;
function TDSWrap2.Locate(AFields: TArray<String>;
AValues: TArray<Variant>): Boolean;
var
AKeyFields: string;
ALength: Integer;
Arr: Variant;
J: Integer;
OK: Boolean;
begin
Assert(Length(AFields) > 0);
Assert(Length(AValues) > 0);
Assert(Length(AFields) = Length(AValues));
ALength := Length(AValues);
AKeyFields := '';
// Создаём вариантный массив
Arr := VarArrayCreate([0, ALength - 1], varVariant);
for J := 0 to ALength - 1 do
begin
AKeyFields := AKeyFields + IfThen(AKeyFields.IsEmpty, '', ';') + AFields[J];
Arr[J] := AValues[J];
end;
Result := FDDataSet.LocateEx(AKeyFields, Arr, []);
VarClear(Arr);
end;
procedure TDSWrap2.TryOpen;
begin
if not FDataSet.Active then
FDataSet.Open;
end;
procedure TDSWrap2.TryPost;
begin
Assert(FDataSet.Active);
if FDataSet.State in [dsEdit, dsinsert] then
FDataSet.Post;
end;
procedure TDSWrap2.UpdateFields;
var
F: TField;
FW: TFieldWrap;
begin
// Прячем все поля
SetFieldsVisible(False);
// Показываем только те, у которых есть DisplayLabel
for FW in FFieldsWrap do
begin
F := FDataSet.FindField(FW.FieldName);
if F = nil then
Continue;
F.Visible := FW.Visible;
if not FW.DisplayLabel.IsEmpty then
F.DisplayLabel := FW.DisplayLabel;
end;
end;
constructor TFieldWrap2.Create(ADataSetWrap: TDSWrap; const AFieldName: string;
const ADisplayLabel: string = ''; APrimaryKey: Boolean = False);
begin
inherited Create;
Assert(ADataSetWrap <> nil);
Assert(not AFieldName.IsEmpty);
FDataSetWrap := ADataSetWrap;
FDataSetWrap.FFieldsWrap.Add(Self);
FFieldName := AFieldName;
FDisplayLabel := ADisplayLabel;
FVisible := not FDisplayLabel.IsEmpty;
// if FDisplayLabel.IsEmpty then
// FDisplayLabel := FFieldName;
if APrimaryKey then
ADataSetWrap.PKFieldName := FFieldName;
FDefaultValue := NULL;
end;
function TFieldWrap2.GetF: TField;
begin
Result := FDataSetWrap.Field(FFieldName);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
/// <summary> DBX Client </summary>
unit Data.DBXClient;
{$Z+}
interface
uses
Data.DBXCommon,
Data.DBXTransport,
Data.DBXCommonTable,
Data.DBXMessageHandlerJSonClient,
Data.DBXStream,
Data.DBXStreamPlatform,
Data.DBXPlatform,
System.Classes,
System.SysUtils,
Data.DBXJSONReflect,
System.Generics.Collections
;
type
TDBXClientDriverLoaderClass = class of TObject;
TDBXClientConnection = class;
TDBXClientCommand = class;
TDBXClientDriverLoader = class(TDBXDriverLoader)
public
constructor Create; override;
function Load(DriverDef: TDBXDriverDef): TDBXDriver; override;
end;
TDBXClientDriver = class(TDBXDriver)
private
function CreateClientCommand(DbxContext: TDBXContext; Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand;
protected
procedure Close; override;
function CreateConnection(ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection; override;
function CreateChannel: TDbxChannel; virtual;
public
constructor Create(DriverDef: TDBXDriverDef); overload; override;
constructor Create(DriverDef: TDBXDriverDef; DriverProps: TDBXProperties); overload;
function GetDriverVersion: string; override;
end;
TDBXClientTransaction = class(TDBXTransaction)
private
FTransactionHandle: Integer;
constructor Create(Connection: TDBXClientConnection; IsolationLevel: TDBXIsolation; TransactionHandle: Integer);
end;
TDBXClientConnection = class(TDBXConnection)
strict private
FChannel: TDBXChannel;
private
[Weak]FDriver: TDBXClientDriver;
FDBXConHandler: TDBXJSonClientOutputConnectionHandler;
[Weak]FDbxReader: TDbxJSonStreamReader;
[Weak]FDbxWriter: TDbxJSonStreamWriter;
FConnectionHandle: Integer;
FProductName: string;
FProtocolVersion: Integer;
FVendorProps: TStringList;
procedure updateIsolationLevel(IsolationLevel: TDBXIsolation);
protected
function CreateAndBeginTransaction(const Isolation: TDBXIsolation): TDBXTransaction; override;
procedure Commit(const InTransaction: TDBXTransaction); override;
procedure Rollback(const InTransaction: TDBXTransaction); override;
procedure SetTraceInfoEvent(const TraceInfoEvent: TDBXTraceEvent); override;
procedure DerivedOpen; override;
procedure DerivedGetCommandTypes(const List: TStrings); override;
procedure DerivedGetCommands(const CommandType: string; const List: TStrings); override;
procedure DerivedClose; override;
function GetProductName: string; override;
public
constructor Create(ConnectionBuilder: TDBXConnectionBuilder);
destructor Destroy; override;
function GetVendorProperty(const Name: string): string; override;
end;
TDBXClientCommand = class(TDBXCommand)
strict private
[Weak]FDbxReader: TDbxJSonStreamReader;
[Weak]FDbxWriter: TDbxJSonStreamWriter;
FConnectionHandle: Integer;
FCommandHandle: Integer;
FRowsAffected: Int64;
FUpdateable: Boolean;
[Weak]FConnection: TDBXClientConnection;
FDbxReaderBuffer: TDBXRowBuffer;
FDBXActiveTableReaderList: TDBXActiveTableReaderList;
function Execute: TDBXReader;
private
FDbxParameterBuffer: TDBXRowBuffer;
FParameterTypeChange: Boolean;
[Weak]FParameterRow: TDBXJSonRow;
constructor Create( DBXContext: TDBXContext;
Connection: TDBXClientConnection;
ConnectionHandle: Integer;
DbxReader: TDbxJSonStreamReader;
DbxWriter: TDbxJSonStreamWriter
);
protected
procedure SetRowSetSize(const RowSetSize: Int64); override;
procedure SetMaxBlobSize(const MaxBlobSize: Int64); override;
function GetRowsAffected: Int64; override;
function CreateParameterRow: TDBXRow; override;
function DerivedExecuteQuery: TDBXReader; override;
procedure DerivedExecuteUpdate; override;
procedure DerivedPrepare; override;
procedure DerivedOpen; override;
procedure DerivedClose; override;
function DerivedGetNextReader: TDBXReader; override;
procedure DerivedClearParameters; override;
procedure SetText(const Value: string); override;
public
destructor Destroy; override;
function GetJSONMarshaler: TJSONMarshal;
function GetJSONUnMarshaler: TJSONUnMarshal;
class procedure AddConverter(event: TConverterEvent);
class procedure AddReverter(event: TReverterEvent);
end;
TDBXJSonByteReader = class(TDBXReaderByteReader)
private
FReaderHandle: Integer;
[Weak]FDbxRowBuffer: TDBXRowBuffer;
[Weak]FDbxClientReader: TDBXJSonReader;
public
constructor Create( DBXContext: TDBXContext;
ReaderHandle: Integer;
ClientReader: TDBXJSonReader;
DbxReader: TDbxJSonStreamReader;
DbxWriter: TDbxJSonStreamWriter;
DbxRowBuffer: TDBXRowBuffer);
{$IFNDEF NEXTGEN}
procedure GetAnsiString(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
{$ENDIF}
procedure GetWideString(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetUInt8(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetInt8(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetUInt16(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetInt16(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetInt32(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetInt64(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
procedure GetDouble(Ordinal: TInt32; const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool); override;
end;
TDBXClientParameterRow = class(TDBXJSonRow)
private
[Weak]FDbxClientCommand: TDBXClientCommand;
protected
constructor Create(DBXContext: TDBXContext; ReaderHandle: Integer;
DbxClientCommand: TDBXClientCommand;
DbxStreamReader: TDbxJSonStreamReader; DbxStreamWriter: TDbxJSonStreamWriter;
DbxRowBuffer: TDBXRowBuffer);
procedure SetValueType( ValueType: TDBXValueType); override;
procedure ValueNotSet(const Value: TDBXWritableValue); override;
public
destructor Destroy; override;
end;
implementation
uses
Data.DbxSocketChannelNative,
Data.DBXTransportFilter,
Data.DBXMessageHandlerCommon,
Data.DBXCommonResStrs
;
{ TDBXClientDriver }
procedure TDBXClientDriver.Close;
begin
inherited;
end;
constructor TDBXClientDriver.Create(DriverDef: TDBXDriverDef);
begin
inherited Create(DriverDef);
{$IF NOT (DEFINED(IOS) or DEFINED(ANDROID))}
rpr;
{$ENDIF}
// '' makes this the default command factory.
//
AddCommandFactory('', CreateClientCommand);
if (DriverProperties = nil) or not DriverProperties.GetBoolean(TDBXPropertyNames.AutoUnloadDriver) then
CacheUntilFinalization;
end;
constructor TDBXClientDriver.Create(DriverDef: TDBXDriverDef; DriverProps: TDBXProperties);
begin
inherited Create(DriverDef);
{$IF NOT (DEFINED(IOS) or DEFINED(ANDROID))}
rpr;
{$ENDIF}
// '' makes this the default command factory.
//
AddCommandFactory('', CreateClientCommand);
InitDriverProperties(DriverProps);
if (DriverProperties = nil) or not DriverProperties.GetBoolean(TDBXPropertyNames.AutoUnloadDriver) then
CacheUntilFinalization;
end;
function TDBXClientDriver.CreateChannel: TDbxChannel;
var
FilterChannel: TDBXFilterSocketChannel;
begin
if AnsiCompareText( self.DriverName, 'DataSnap' ) = 0 then
begin
FilterChannel := TDBXFilterSocketChannel.Create;
FilterChannel.Channel := TDBXSocketChannel.Create;
Result := FilterChannel;
end
else
begin
Result := TDBXSocketChannel.Create;
end;
end;
function TDBXClientDriver.CreateClientCommand(DbxContext: TDBXContext;
Connection: TDBXConnection; MorphicCommand: TDBXCommand): TDBXCommand;
var
ClientConnection: TDBXClientConnection;
begin
ClientConnection := TDBXClientConnection(Connection);
Result := TDBXClientCommand.Create(DbxContext, ClientConnection,
ClientConnection.FConnectionHandle,
ClientConnection.FDbxReader,
ClientConnection.FDbxWriter);
end;
function TDBXClientDriver.CreateConnection(
ConnectionBuilder: TDBXConnectionBuilder): TDBXConnection;
var
Connection: TDBXClientConnection;
begin
Connection := TDBXClientConnection.Create(ConnectionBuilder);
Connection.FDriver := Self;
Result := Connection;
end;
function TDBXClientDriver.GetDriverVersion: string;
begin
Result := DBXVersion40;
end;
{ TDBXClientDriverLoader }
constructor TDBXClientDriverLoader.Create;
begin
inherited Create;
end;
function TDBXClientDriverLoader.Load(DriverDef: TDBXDriverDef): TDBXDriver;
var
DriverUnit: string;
begin
DriverUnit := DriverDef.FDriverProperties[TDBXPropertyNames.DriverUnit];
if SameText(DriverUnit, 'DBXClient') or SameText(DriverUnit, 'DBXDatasnap')
or SameText(DriverUnit, 'Data.DBXClient') or SameText(DriverUnit, 'Data.DBXDatasnap') then
Result := TDBXClientDriver.Create(DriverDef)
else
Result := nil;
end;
{ TDBXClientConnection }
constructor TDBXClientConnection.Create(
ConnectionBuilder: TDBXConnectionBuilder);
begin
inherited Create(ConnectionBuilder);
FVendorProps := TStringList.Create;
FConnectionHandle := -1;
end;
procedure TDBXClientConnection.DerivedClose;
begin
if FConnectionHandle >= 0 then
try
FDbxWriter.WriteDisconnectObject(FConnectionHandle);
// Keep ASP.NET app from complaining about unhandled exception.
// Write failes when server closes socket.
//
try
FDbxWriter.Flush;
except
end;
FConnectionHandle := -1;
inherited;
except
// ignore eventual I/O exceptions here to free the allocated memory
end;
FConnectionHandle := -1;
FreeAndNil(FChannel);
FreeAndNil(FDBXConHandler);
end;
procedure TDBXClientConnection.Commit(const InTransaction: TDBXTransaction);
var
Message: TDBXTxEndMessage;
begin
Message := FDBXConHandler.TxEndMessage;
Message.Commit := true;
Message.TransactionHandle := TDBXClientTransaction(InTransaction).FTransactionHandle;
FDBXConHandler.DbxTxEnd(Message);
end;
procedure TDBXClientConnection.Rollback(const InTransaction: TDBXTransaction);
var
Message: TDBXTxEndMessage;
begin
Message := FDBXConHandler.TxEndMessage;
Message.Commit := false;
Message.TransactionHandle := TDBXClientTransaction(InTransaction).FTransactionHandle;
FDBXConHandler.DbxTxEnd(Message);
end;
function TDBXClientConnection.CreateAndBeginTransaction(
const Isolation: TDBXIsolation): TDBXTransaction;
var
Message: TDBXTxBeginMessage;
begin
Message := FDBXConHandler.TxBeginMessage;
Message.IsolationLevel := Isolation;
FDBXConHandler.DbxTxBegin(Message);
Result := TDBXClientTransaction.Create(Self, Isolation, Message.TransactionHandle);
end;
procedure TDBXClientConnection.DerivedGetCommands(const CommandType: string;
const List: TStrings);
const
GetServerMethodsStr = 'DSAdmin.GetServerMethods';
MethodAliasStr = 'MethodAlias';
var
Command: TDBXCommand;
MethodReader: TDBXReader;
NameOrdinal: Integer;
begin
if CommandType = TDBXCommandTypes.DSServerMethod then
begin
MethodReader := nil;
Command := CreateCommand;
Command.CommandType := TDBXCommandTypes.DSServerMethod;
Command.Text := GetServerMethodsStr;
try
MethodReader := Command.ExecuteQuery;
NameOrdinal := MethodReader.GetOrdinal(MethodAliasStr);
while MethodReader.Next do
List.Add(MethodReader.Value[NameOrdinal].GetWideString);
finally
FreeAndNil(MethodReader);
FreeAndNil(Command);
end;
end;
end;
function TDBXClientConnection.GetProductName: string;
begin
Result := FProductName;
end;
function TDBXClientConnection.GetVendorProperty(
const Name: string): string;
var
Index: Integer;
begin
if FProtocolVersion >= TDbxJSonStreamWriter.ProtocolVersion2 then
begin
Index := FVendorProps.IndexOfName(Name);
if Index > -1 then
begin
Result := FVendorProps.ValueFromIndex[Index];
end else
begin
FDbxWriter.WriteVendorProperty(Name);
FDbxReader.NextResultObjectStart;
FDBXReader.Next(TDBXTokens.ArrayStartToken);
Result := FDBXReader.ReadString;
FDbxReader.SkipToEndOfObject;
FVendorProps.Add(Name+'='+Result);
end;
end else
inherited GetVendorProperty(Name);
end;
procedure TDBXClientConnection.DerivedGetCommandTypes(const List: TStrings);
begin
List.Add(TDBXCommandTypes.DSServerMethod);
end;
procedure TDBXClientConnection.DerivedOpen;
var
Complete: Boolean;
BufferKBSize, Index, Token: Integer;
Count: TInt32;
Names, Values: TWideStringArray;
DBXRowBuffer: TDBXRowBuffer;
DBXInConHandler: TDBXJSonClientInputConnectionHandler;
LDbxReader: TDbxJSonStreamReader;
LDbxWriter: TDbxJSonStreamWriter;
begin
Complete := false;
try
FChannel := FDriver.CreateChannel();
FChannel.DbxProperties := FConnectionProperties;
FChannel.Open;
BufferKBSize := FConnectionProperties.GetInteger(TDBXPropertyNames.BufferKBSize);
if BufferKBSize < 1 then
BufferKBSize := 32;
LDbxReader := TDbxJSonStreamReader.Create;
FDbxReader := LDbxReader;
FDbxReader.DbxChannel := FChannel;
FDbxReader.DbxContext := FDBXContext;
FDbxReader.ReadBufferSize := BufferKBSize * 1024;
FDbxReader.Open;
LDbxWriter := TDbxJSonStreamWriter.Create;
FDbxWriter := LDbxWriter;
FDbxWriter.DbxChannel := FChannel;
FDbxWriter.WriteBufferSize := BufferKBSize * 1024;
FDbxWriter.Open;
DBXRowBuffer := nil;
// A separate row buffer is allocated for each commmand, so this one should
// not be needed.
// DbxRowBuffer := TDBXRowBuffer.Create;
// DbxRowBuffer.Client := true;
// DbxRowBuffer.DbxStreamReader := FDbxReader;
// DbxRowBuffer.DbxStreamWriter := FDbxWriter;
// DbxRowBuffer.MinBufferSize := FDBXWriter.CalcRowBufferSize;
DBXInConHandler := TDBXJSonClientInputConnectionHandler.Create(FDBXContext, FDbxReader, FDbxWriter, DbxRowBuffer);
FDBXConHandler := TDBXJSonClientOutputConnectionHandler.Create(FDBXContext, DBXInConHandler, FDbxReader, FDbxWriter, DbxRowBuffer);
FDbxWriter.WriteConnectObjectStart;
FDbxWriter.WriteParamsStart;
Count := FConnectionProperties.Properties.Count;
FConnectionProperties.GetLists(Names, Values);
Index := 0;
FDbxWriter.WriteObjectStart;
while Index < Count do
begin
FDbxWriter.WriteNamedString(Names[Index], Values[Index]);
inc(Index);
if Index < Count then
FDBXWriter.WriteValueSeparator;
end;
FDbxWriter.WriteObjectEnd;
FDbxWriter.WriteArrayEnd;
FDbxWriter.WriteObjectEnd;
FDbxWriter.Flush;
FDbxReader.NextResultObjectStart;
FDBXReader.Next(TDBXTokens.ArrayStartToken);
FConnectionHandle := FDBXReader.ReadInt;
FDbxReader.Next(TDBXTokens.ValueSeparatorToken);
FProductName := FDbxReader.ReadString;
Token := FDbxReader.Next;
if Token = TDBXTokens.ValueSeparatorToken then
FProtocolVersion := FDBXReader.ReadInt;
FDbxReader.SkipToEndOfObject;
Complete := true;
finally
if not Complete then
Close;
end;
end;
destructor TDBXClientConnection.Destroy;
begin
FreeAndNil(FVendorProps);
inherited;
end;
procedure TDBXClientConnection.SetTraceInfoEvent(
const TraceInfoEvent: TDBXTraceEvent);
begin
inherited;
end;
procedure TDBXClientConnection.updateIsolationLevel(IsolationLevel: TDBXIsolation);
begin
FIsolationLevel := IsolationLevel;
end;
{ TDBXClientCommand }
procedure TDBXClientCommand.DerivedClearParameters;
var
NewCommandHandle: TDBXInt32s;
begin
if FDbxParameterBuffer <> nil then
begin
FDbxParameterBuffer.Cancel;
SetLength(NewCommandHandle, 1);
// This will invalidate anything that refers to the old commanhandle array.
// Simple way to invalidate any TStreams that are kept open and un freed
// by the app.
//
NewCommandHandle[0] := FCommandHandle;
FDbxParameterBuffer.CommandHandle[0] := -1;
FDbxParameterBuffer.CommandHandle := NewCommandHandle;
FDBXActiveTableReaderList.CloseAllActiveTableReaders;
end;
end;
class procedure TDBXClientCommand.AddConverter(event: TConverterEvent);
begin
TJSONConverters.AddConverter(event);
end;
class procedure TDBXClientCommand.AddReverter(event: TReverterEvent);
begin
TJSONConverters.AddReverter(event);
end;
constructor TDBXClientCommand.Create(DBXContext: TDBXContext;
Connection: TDBXClientConnection;
ConnectionHandle: Integer; DbxReader: TDbxJSonStreamReader;
DbxWriter: TDbxJSonStreamWriter);
begin
inherited Create(DBXContext);
FConnectionHandle := ConnectionHandle;
FDbxReader := DbxReader;
FDbxWriter := DbxWriter;
FConnection := Connection;
end;
function TDBXClientCommand.CreateParameterRow: TDBXRow;
begin
if FDbxParameterBuffer = nil then
begin
FDbxParameterBuffer := TDBXRowBuffer.Create;
FDbxParameterBuffer.Client := true;
FDbxParameterBuffer.DbxStreamReader := FDbxReader;
FDbxParameterBuffer.DbxStreamWriter := FDbxWriter;
FDbxParameterBuffer.MinBufferSize := FDbxWriter.CalcRowBufferSize;
FDbxParameterBuffer.ParameterBuffer := true;
end;
FDbxParameterBuffer.CommandHandle[0] := FCommandHandle;
Assert(FDBXActiveTableReaderList = nil);
FDBXActiveTableReaderList := TDBXActiveTableReaderList.Create;
Result := TDBXClientParameterRow.Create(FDBXContext, FCommandHandle, Self, FDbxReader, FDbxWriter, FDbxParameterBuffer);
FParameterRow := TDBXClientParameterRow(Result);
end;
procedure TDBXClientCommand.DerivedClose;
begin
if (FDbxWriter <> nil) and (FCommandHandle >= 0) then
try
FDbxWriter.WriteCommandCloseObject(FCommandHandle);
except
end;
FreeAndNil(FDBXActiveTableReaderList);
end;
function TDBXClientCommand.DerivedExecuteQuery: TDBXReader;
begin
Result := Execute;
// this will cause ownership to be released so that the reader will not
// be automatically freed.
//
if (Result <> nil)
and (FParameters <> nil)
and (FParameters.Count > 0)
and (FParameters[FParameters.Count-1].ParameterDirection = TDBXParameterDirections.ReturnParameter)
and (FParameters[FParameters.Count-1].Value is TDBXReaderValue) then
FParameters[FParameters.Count-1].Value.SetDBXReader(Result, False);
end;
procedure TDBXClientCommand.DerivedExecuteUpdate;
begin
Execute;
end;
function TDBXClientCommand.DerivedGetNextReader: TDBXReader;
var
Message: TDBXNextResultMessage;
begin
if (FCommandHandle > 0) then
begin
Message := FConnection.FDBXConHandler.NextResultMessage;
Message.CommandHandle := FCommandHandle;
FConnection.FDBXConHandler.DbxNextResult(Message);
FRowsAffected := Message.RowsAffected;
FUpdateable := Message.Updateable;
Result := Message.NextResult;
end
else
Result := nil;
end;
procedure TDBXClientCommand.DerivedOpen;
begin
FCommandHandle := -1; // Initialized on execute and/or prepare.
end;
procedure TDBXClientCommand.DerivedPrepare;
var
Message: TDBXPrepareMessage;
I: Integer;
begin
Message := FConnection.FDBXConHandler.PrepareMessage;
Message.Parameters := Parameters;
Message.CommandHandle := FCommandHandle;
Message.CommandType := CommandType;
Message.Command := Text;
Message.ParameterTypeChanged := FParameterTypeChange;
FConnection.FDBXConHandler.DbxPrepare(Message);
for I := 0 to FParameters.Count - 1 do
if FParameters.Parameter[I] <> nil then
FParameters.Parameter[I].ConnectionHandler := self
else
break; // parameters are not existing
FCommandHandle := Message.CommandHandle;
if Assigned(FDbxParameterBuffer) then
FDbxParameterBuffer.CommandHandle[0] := FCommandHandle;
FParameterTypeChange := Message.ParameterTypeChanged;
end;
destructor TDBXClientCommand.Destroy;
begin
FreeAndNil(FDbxReaderBuffer);
FreeAndNil(FDbxParameterBuffer);
FreeAndNil(FDBXActiveTableReaderList);
inherited Destroy;
end;
function TDBXClientCommand.Execute: TDBXReader;
var
Message: TDBXExecuteMessage;
begin
Message := FConnection.FDBXConHandler.ExecuteMessage;
Message.CommandHandle := FCommandHandle;
Message.Prepared := IsPrepared;
Message.Parameters := GetParameters;
Message.Row := FParameterRow;
Message.CommandType := CommandType;
Message.Command := Text;
Message.ActiveStreamerRowList := FDBXActiveTableReaderList;
Message.ParameterTypeChanged := FParameterTypeChange;
FConnection.FDBXConHandler.dbxExecute(Message);
FRowsAffected := Message.RowsAffected;
FCommandHandle := Message.CommandHandle;
if Message.IsolationLevel > -1 then
FConnection.updateIsolationLevel(Message.IsolationLevel); // Isolation level.
FParameterTypeChange := false;
Result := Message.ReturnReader;
Message.ReturnReader := nil;
end;
function TDBXClientCommand.GetJSONMarshaler: TJSONMarshal;
begin
Result := TJSONConverters.GetJSONMarshaler;
end;
function TDBXClientCommand.GetJSONUnMarshaler: TJSONUnMarshal;
begin
Result := TJSONConverters.GetJSONUnMarshaler;
end;
function TDBXClientCommand.GetRowsAffected: Int64;
begin
Result := FRowsAffected;
end;
procedure TDBXClientCommand.SetMaxBlobSize(const MaxBlobSize: Int64);
begin
// Ignore blob size
// Assert(false, 'Not Implemented yet');
end;
procedure TDBXClientCommand.SetRowSetSize(const RowSetSize: Int64);
begin
// Assert(false, 'Not Implemented yet');
end;
procedure TDBXClientCommand.SetText(const Value: string);
var
Temp: string;
Count: Integer;
begin
// VCL code can some times terminate string with
// an null. Ok for c drivers, but not those that
// are Delphi.
//
Count := Value.IndexOf(#0) + 1;
if Count > 0 then
begin
Temp := Value;
SetLength(Temp, Count-1);
inherited SetText(Temp);
end else
inherited SetText(Value);
end;
{ TDBXJSonByteReader }
constructor TDBXJSonByteReader.Create(DBXContext: TDBXContext;
ReaderHandle: Integer;
ClientReader: TDBXJSonReader;
DbxReader: TDbxJSonStreamReader;
DbxWriter: TDbxJSonStreamWriter;
DbxRowBuffer: TDBXRowBuffer);
begin
inherited Create(DBXContext, ClientReader);
FReaderHandle := ReaderHandle;
FDbxRowBuffer := DbxRowBuffer;
FDbxClientReader := ClientReader;
end;
{$IFNDEF NEXTGEN}
procedure TDBXJSonByteReader.GetAnsiString(Ordinal: TInt32;
const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool);
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
FDbxRowBuffer.ReadAnsiStringBytes(FDbxClientReader.RowHandle, Value, Offset);
end;
end;
{$ENDIF}
procedure TDBXJSonByteReader.GetDouble(Ordinal: TInt32;
const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool);
begin
if FDbxClientReader[Ordinal].ValueType.SubType = TDBXDataTypes.SingleType then
inherited
else
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
TDBXPlatform.CopyInt64(FDbxRowBuffer.ReadDoubleAsInt64, Value, 0);
end;
end;
end;
procedure TDBXJSonByteReader.GetInt16(Ordinal: TInt32;
const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool);
var
ValueObject: TDBXValue;
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
ValueObject := FDbxClientReader[Ordinal];
if ValueObject.ValueType.DataType = TDBXDataTypes.BooleanType then
begin
if FDbxRowBuffer.ReadBoolean then
begin
value[Offset] := $FF;
value[Offset+1] := $FF;
end else
begin
value[Offset] := 0;
value[Offset+1] := 0;
end;
end else
begin
TDBXPlatform.CopyInt16(FDbxRowBuffer.ReadInt16, Value, 0);
end;
end;
end;
procedure TDBXJSonByteReader.GetInt32(Ordinal: TInt32;
const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool);
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
TDBXPlatform.CopyInt32(FDbxRowBuffer.ReadInt32, Value, 0);
end;
end;
procedure TDBXJSonByteReader.GetInt64(Ordinal: TInt32;
const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool);
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
TDBXPlatform.CopyInt64(FDbxRowBuffer.ReadInt64, Value, 0);
end;
end;
procedure TDBXJSonByteReader.GetInt8(Ordinal: TInt32; const Value: TArray<Byte>;
Offset: TInt32; var IsNull: LongBool);
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
TDBXPlatform.CopyInt8(FDbxRowBuffer.ReadByte, Value, 0);
end;
end;
procedure TDBXJSonByteReader.GetUInt16(Ordinal: TInt32; const Value: TArray<Byte>;
Offset: TInt32; var IsNull: LongBool);
var
ValueObject: TDBXValue;
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
ValueObject := FDbxClientReader[Ordinal];
if ValueObject.ValueType.DataType = TDBXDataTypes.BooleanType then
begin
if FDbxRowBuffer.ReadBoolean then
begin
value[Offset] := $FF;
value[Offset+1] := $FF;
end else
begin
value[Offset] := 0;
value[Offset+1] := 0;
end;
end else
begin
TDBXPlatform.CopyUInt16(FDbxRowBuffer.ReadInt16, Value, 0);
end;
end;
end;
procedure TDBXJSonByteReader.GetUInt8(Ordinal: TInt32; const Value: TArray<Byte>;
Offset: TInt32; var IsNull: LongBool);
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
TDBXPlatform.CopyUInt8(FDbxRowBuffer.ReadByte, Value, 0);
end;
end;
procedure TDBXJSonByteReader.GetWideString(Ordinal: TInt32;
const Value: TArray<Byte>; Offset: TInt32; var IsNull: LongBool);
begin
FDbxRowBuffer.GoToField(Ordinal);
if FDbxRowBuffer.Null then
IsNull := true
else
begin
IsNull := false;
FDbxRowBuffer.ReadStringBytes(FDbxClientReader.RowHandle, Value, Offset);
end;
end;
{ TDBXClientTransaction }
constructor TDBXClientTransaction.Create(Connection: TDBXClientConnection;
IsolationLevel: TDBXIsolation; TransactionHandle: Integer);
begin
inherited Create(Connection);
FTransactionHandle := TransactionHandle;
FIsolationLevel := IsolationLevel;
end;
{ TDBXClientParameterRow }
constructor TDBXClientParameterRow.Create(DBXContext: TDBXContext;
ReaderHandle: Integer; DbxClientCommand: TDBXClientCommand;
DbxStreamReader: TDbxJSonStreamReader; DbxStreamWriter: TDbxJSonStreamWriter;
DbxRowBuffer: TDBXRowBuffer);
begin
inherited Create(DBXContext,DBXStreamReader, DBXStreamWriter, DBXRowBuffer, false);
FDbxClientCommand := DbxClientCommand;
end;
destructor TDBXClientParameterRow.Destroy;
begin
if FDbxClientCommand <> nil then
FDbxClientCommand.FParameterRow := nil;
inherited;
end;
procedure TDBXClientParameterRow.ValueNotSet(const Value: TDBXWritableValue);
begin
case value.ValueType.ParameterDirection of
TDBXParameterDirections.OutParameter,
TDBXParameterDirections.ReturnParameter:
SetNull(Value);
else
FDbxContext.Error(TDBXErrorCodes.ParameterNotSet, Format(SParameterNotSet, [IntToStr(Value.ValueType.Ordinal)]), nil);
end;
end;
procedure TDBXClientParameterRow.SetValueType(ValueType: TDBXValueType);
begin
FDbxClientCommand.FParameterTypeChange := True;
end;
end.
|
unit PTA40203;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, DB, DBTables, Grids, DBGrids, Messages,Dialogs,SysUtils,
Mask, ExtCtrls,datelib, Tmax_DataSetText, OnPopupEdit, OnGrDBGrid,
OnFocusButton, MemDS, DBAccess, Ora, OnEditBaseCtrl, OnEditStdCtrl,
OnEditBtnCtrl;
type
TCForm = class(TForm)
DataSource1: TDataSource;
codeGrid: TOnGrDbGrid;
Panel1: TPanel;
BT_Select: TOnFocusButton;
BT_Close: TOnFocusButton;
Panel2: TPanel;
E_Search: TOnButtonEdit;
TMaxDataSet1: TTMaxDataSet;
procedure BT_CloseClick(Sender: TObject);
procedure codeGridDblClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure E_SearchButtonClick(Sender: TObject; ButtonIndex: Integer);
procedure E_SearchKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
Edit : TOnWinPopupEdit;
DutyID : String;
FromWhere : String;
Code : String; {코드}
CodeName : String; {코드명}
Procedure Open_Grid;
end;
var
CForm: TCForm;
implementation
uses PTA40201, PTA40202;
{$R *.DFM}
Procedure TCForm.Open_Grid;
begin
with TMaxDataSet1 do
begin
ServiceName := 'PTA4020B_sel2';
Close;
Sql.Clear;
Sql.Add('SELECT EDU_TYPE, EDU_NAME ');
Sql.Add(' FROM PEDU2TYPE ');
Sql.Add(Format('WHERE EDU_NAME like ''%s''',['%'+E_Search.Text+'%']) );
Sql.Add(' union ');
Sql.Add('Select ''0000'' EDU_TYPE, ');
Sql.Add(' ''채널아카데미 제외한 교육유형'' EDU_NAME from dual ');
Sql.Add('ORDER BY EDU_TYPE ');
ClearFieldInfo;
AddField('EDU_TYPE', ftString, 4);
AddField('EDU_NAME', ftString, 30);
Open;
end;
end;
procedure TCForm.BT_CloseClick(Sender: TObject);
begin
Code := '';
CodeName := '';
Edit.PopupForm.ClosePopup(False);
end;
procedure TCForm.codeGridDblClick(Sender: TObject);
begin
Code := TMaxDataSet1.FieldByName('EDU_TYPE').AsString ;
CodeName := TMaxDataSet1.FieldByName('EDU_NAME').AsString ;
Edit.PopupForm.ClosePopup(False);
end;
procedure TCForm.FormShow(Sender: TObject);
begin
E_Search.Text := '';
Open_Grid;
end;
procedure TCForm.E_SearchButtonClick(Sender: TObject;
ButtonIndex: Integer);
begin
Open_Grid;
end;
procedure TCForm.E_SearchKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
Open_Grid;
end;
end.
|
{*******************************************************}
{ }
{ Check performance of code in Delphi }
{ }
{ Copyright (c) 2000 Andrei Roofin }
{ }
{ www - http://dsr.tomsk.ru }
{ mail - ray@mail.tomsknet.ru }
{ }
{*******************************************************}
unit UrsProfiler;
interface
uses Windows, Classes, SysUtils;
const
rsMaxPointCount = 100;
type
TrsProfiler = class;
TrsProfilerPoint = class
private
FProfiler: TrsProfiler;
FAvgTicks: Int64;
FLastTicks: Int64;
FMinTicks: Int64;
FMaxTicks: Int64;
FCount: integer;
FStartTicks: Int64;
function GetAvgTicks: Int64;
public
Name: string;
min, avg, max, last: string;
constructor Create(AOwner: TrsProfiler);
procedure AsString;
procedure Clear;
procedure Start;
procedure Stop;
property Count: integer read FCount;
property AvgTicks: Int64 read GetAvgTicks;
property LastTicks: Int64 read FLastTicks;
property MaxTicks: Int64 read FMaxTicks;
property MinTicks: Int64 read FMinTicks;
end;
TrsProfiler = class
private
FList: TList;
CPUClock: extended;
function GetPoint(index: integer): TrsProfilerPoint;
protected
FStartStopConstant: Int64;
public
constructor Create;
destructor Destroy; override;
function Add: integer;
function CalibrateCPU: Int64;
procedure Clear;
function Count: integer;
procedure Delete(const Index: integer);
function IndexOfName(const Value: string): integer;
function TicksToStr(const Value: Int64): string;
property Points[index: integer]: TrsProfilerPoint read GetPoint; default;
property CPUSpeed: extended read CPUClock;
end;
function GetCPUTick:Int64;
var
rsProfiler: TrsProfiler;
implementation
function GetCPUTick: Int64;
asm
DB $0F,$31
end;
function TrsProfiler.CalibrateCPU: Int64;
var
t: cardinal;
PriorityClass, Priority: Integer;
begin
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
t := GetTickCount;
while t=GetTickCount do;
Result := GetCPUTick;
while GetTickCount<(t+400) do;
Result := GetCPUTick - result;
CPUClock := 2.5e-6*Result;
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
end;
function TrsProfiler.TicksToStr(const Value: Int64): string;
begin
Result := FloatToStrF(Value/CPUClock,fffixed,10,2);{+ ' Ás';}
end;
{ TrsProfilerPoint }
procedure TrsProfilerPoint.Clear;
begin
FMinTicks := High(Int64);
FMaxTicks := 0;
FAvgTicks := 0;
FLastTicks := 0;
FCount := 0;
end;
constructor TrsProfilerPoint.Create(AOwner: TrsProfiler);
begin
FProfiler := AOwner;
Clear;
end;
procedure TrsProfilerPoint.AsString;
begin
min := FProfiler.TicksToStr(MinTicks);
max := FProfiler.TicksToStr(MaxTicks);
avg := FProfiler.TicksToStr(AvgTicks);
last := FProfiler.TicksToStr(LastTicks);
end;
function TrsProfilerPoint.GetAvgTicks: Int64;
begin
if FCount>0 then Result := FAvgTicks div FCount
else Result:= 0;
end;
procedure TrsProfilerPoint.Start;
begin
FStartTicks := GetCPUTick;
end;
procedure TrsProfilerPoint.Stop;
begin
FLastTicks := GetCPUTick - FStartTicks - FProfiler.FStartStopConstant;
if FLastTicks<0 then FLastTicks := 0;
Inc(FCount);
if FLastTicks<FMinTicks then FMinTicks := FLastTicks;
if FLastTicks>FMaxTicks then FMaxTicks := FLastTicks;
Inc(FAvgTicks, FLastTicks);
end;
{ TrsProfiler }
function TrsProfiler.Add: integer;
var
p: TrsProfilerPoint;
begin
p := TrsProfilerPoint.Create(Self);
Result := FList.Add(p);
end;
procedure TrsProfiler.Clear;
begin
While Count>0 do Delete(0);
end;
function TrsProfiler.Count: integer;
begin
Result := FList.Count;
end;
constructor TrsProfiler.Create;
begin
FList := TList.Create;
CalibrateCPU;
Add;
Points[0].Start;
Points[0].Stop;
FStartStopConstant := Points[0].FLastTicks;
Clear;
end;
procedure TrsProfiler.Delete(const Index: integer);
begin
if (Index>=0) and (Index<FList.Count) then begin
TrsProfilerPoint(FList.Items[Index]).Free;
FList.Delete(Index);
end;
end;
destructor TrsProfiler.Destroy;
begin
Clear;
inherited Destroy;
end;
function TrsProfiler.GetPoint(index: integer): TrsProfilerPoint;
begin
if Index<0 then Result := nil
else
if Index<FList.Count then Result := FList.Items[Index]
else
if Index<rsMaxPointCount then begin
While Add<Index do ;
Result := FList.Items[Index];
end else Result := nil;
end;
function TrsProfiler.IndexOfName(const Value: string): integer;
var
i: integer;
begin
Result := -1;
for i:=Count-1 downto 0 do
if AnsiCompareText(Value, Points[i].Name)=0 then begin
Result := i;
Break;
end;
end;
initialization
rsProfiler := TrsProfiler.Create;
finalization
rsProfiler.Free;
rsProfiler := nil;
end.
|
unit ANovoPlanoConta;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Mask, Db, DBTables, Tabela, DBCtrls, ExtCtrls,
Componentes1, BotaoCadastro, PainelGradiente, DBKeyViolation, formularios, constantes, constMsg,
FMTBcd, SqlExpr, DBClient, UnContasAReceber;
Const
CT_PLANOINVALIDO='PLANO DE CONTAS INVÁLIDO!!!'#13'Plano de contas preenchido inválido ou não preenchido...';
CT_NOMEPLANOINVALIDO = 'DESCRIÇÃO DO PLANO DE CONTAS INVÁLIDO!!!'#13'Descrição do plano de contas preenchido inválido ou não preenchido...';
CT_TIPOPLANOINVALIDO = 'TIPO DO PLANO DE CONTAS INVÁLIDO!!!'#13'Tipo do plano de contas preenchido inválido ou não preenchido...';
type
TFNovoPlanoConta = class(TFormularioPermissao)
PanelColor1: TPanelColor;
PanelColor3: TPanelColor;
Label1: TLabel;
Label2: TLabel;
Empresa: TDBEditColor;
Label4: TLabel;
CadPlanoConta: TSQL;
Desc: TDBEditColor;
DataPlanoConta: TDataSource;
PainelGradiente1: TPainelGradiente;
BotaoGravar1: TBotaoGravar;
BotaoCancelar1: TBotaoCancelar;
VerificaPlanoConta: TSQLQuery;
CodCla: TMaskEditColor;
CadPlanoContaC_NOM_PLA: TWideStringField;
CadPlanoContaI_COD_EMP: TFMTBCDField;
CadPlanoContaC_TIP_PLA: TWideStringField;
DBEditChar1: TDBEditChar;
Label3: TLabel;
ValidaGravacao1: TValidaGravacao;
CadPlanoContaD_ULT_ALT: TSQLTimeStampField;
CadPlanoContaC_CLA_PLA: TWideStringField;
Label5: TLabel;
DBEditColor1: TDBEditColor;
CadPlanoContaN_VLR_PRE: TFMTBCDField;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BotaoGravar1DepoisAtividade(Sender: TObject);
procedure BotaoCancelar1DepoisAtividade(Sender: TObject);
procedure CodClaExit(Sender: TObject);
procedure BotaoGravar1Atividade(Sender: TObject);
procedure EmpresaChange(Sender: TObject);
procedure BBAjudaClick(Sender: TObject);
procedure CadPlanoContaBeforePost(DataSet: TDataSet);
procedure CadPlanoContaAfterPost(DataSet: TDataSet);
private
{ Private declarations }
acao:Boolean;
codigo : string;
function DadosValidos(VpaAvisar : Boolean):Boolean;
public
{ Public declarations }
modo:byte;
function Inseri( var Descricao, codigo : string; TamanhoPicture : Integer;var TipoDebCre : String ) : Boolean;
function Alterar(Codigo : string; var Descricao : string; TipoDebCre : String ) : Boolean;
end;
var
FNovoPlanoConta: TFNovoPlanoConta;
implementation
uses APrincipal, FunSql, FunString, UnSistema;
{$R *.DFM}
{******************************************************************************
Inseri novo plano de conta
****************************************************************************** }
function TFNovoPlanoConta.Inseri( var Descricao, codigo : string; TamanhoPicture : Integer;var TipoDebCre : String ) : Boolean;
var
laco : integer;
VpfPlanoContas : String;
begin
self.codigo := codigo;
CodCla.EditMask := '';
for laco := 1 to length(codigo) do
CodCla.EditMask := CodCla.EditMask + '\' + codigo[laco] ;
for laco :=1 to TamanhoPicture do
CodCla.EditMask := CodCla.EditMask + '0';
CodCla.EditMask := CodCla.EditMask + ';0;_';
CadPlanoConta.Insert;
Empresa.Field.AsInteger := varia.CodigoEmpresa;
CodCla.ReadOnly := FALSE;
VpfPlanoContas := FunContasAReceber.RPlanoContasDisponivel(codigo,TamanhoPicture+Length(codigo));
if VpfPlanoContas <> '' then
CodCla.EditText := VpfPlanoContas
else
CodCla.EditText := codigo+ AdicionaCharE('0','1',TamanhoPicture);
if TipoDebCre <> '' then
begin
DBEditChar1.Field.AsString := TipoDebCre;
DBEditChar1.Enabled := false;
end;
ShowModal;
Descricao := Desc.Text;
codigo := CadPlanoContaC_CLA_PLA.AsString; //codigo;
TipoDebCre := CadPlanoContaC_TIP_PLA.AsString;
result := Acao;
end;
{******************************************************************************
Alterar plano de conta
****************************************************************************** }
function TFNovoPlanoConta.Alterar(Codigo : string; var Descricao : string; TipoDebCre : String ) : Boolean;
begin
AdicionaSQLAbreTabela(CadPlanoConta,'Select * from CAD_PLANO_CONTA '+
' Where C_CLA_PLA = '''+Codigo+'''');
CadPlanoConta.edit;
CodCla.Text := Codigo;
CodCla.ReadOnly := true;
if TipoDebCre <> '' then
DBEditChar1.Enabled := false;
ShowModal;
Descricao := Desc.Text;
result := Acao;
end;
{ *****************************************************************************
FormShow : serve para colocar o componente de edicao do
código read only se for uma alteracao
****************************************************************************** }
procedure TFNovoPlanoConta.FormCreate(Sender: TObject);
begin
CadPlanoConta.open;
end;
procedure TFNovoPlanoConta.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := CaFree;
end;
{*****************************************************************************
serve para indicar que o usuario confirmou
****************************************************************************** }
procedure TFNovoPlanoConta.BotaoGravar1DepoisAtividade(Sender: TObject);
begin
Acao:=TRUE;
Close;
end;
{******************************************************************************
serve para indicar que o usuario cancelou
****************************************************************************** }
procedure TFNovoPlanoConta.BotaoCancelar1DepoisAtividade(Sender: TObject);
begin
acao:=FALSE;
Close;
end;
function TFNovoPlanoConta.DadosValidos(VpaAvisar : Boolean):Boolean;
var
VpfErro : String;
begin
result := true;
if CadPlanoContaC_CLA_PLA.IsNull then
begin
result := false;
VpfErro := CT_PLANOINVALIDO;
end;
if result then
begin
if CadPlanoContaC_NOM_PLA.IsNull then
begin
result := false;
VpfErro := CT_NOMEPLANOINVALIDO;
end;
if result then
begin
if CadPlanoContaC_TIP_PLA.IsNull then
begin
result := false;
VpfErro := CT_TIPOPLANOINVALIDO
end;
end;
end;
if not result then
if VpaAvisar then
aviso(Vpferro);
end;
{******************************************************************************
na saida da caixa de codigo, faz verificações de duplicação de código
****************************************************************************** }
procedure TFNovoPlanoConta.CodClaExit(Sender: TObject);
begin
if CadPlanoConta.state = dsinsert Then
if CodCla.text <> '' then
begin
VerificaPlanoConta.close;
VerificaPlanoConta.SQL.Clear;
VerificaPlanoConta.sql.Add('select * from cad_Plano_Conta where i_cod_emp = ' +
empresa.Text +
' and c_cla_pla = ''' + codigo + CodCla.Text + '''');
VerificaPlanoConta.open;
if not VerificaPlanoConta.EOF then
begin
erro(CT_DuplicacaoPlanoConta);
if not BotaoCancelar1.Focused then
codcla.SetFocus;
end;
VerificaPlanoConta.Close;
end;
end;
procedure TFNovoPlanoConta.BotaoGravar1Atividade(Sender: TObject);
begin
if CadPlanoConta.State = dsInsert then
CadPlanoContaC_CLA_PLA.AsString := codigo + CodCla.Text;
end;
procedure TFNovoPlanoConta.EmpresaChange(Sender: TObject);
begin
if CadPlanoConta.State in [ dsEdit, dsInsert ] then
ValidaGravacao1.execute;
if (BotaoGravar1.Enabled) and (CodCla.Text = '') then
BotaoGravar1.Enabled := false;
end;
procedure TFNovoPlanoConta.BBAjudaClick(Sender: TObject);
begin
end;
{******************* antes de gravar o registro *******************************}
procedure TFNovoPlanoConta.CadPlanoContaAfterPost(DataSet: TDataSet);
begin
Sistema.MarcaTabelaParaImportar('CAD_PLANO_CONTA');
end;
procedure TFNovoPlanoConta.CadPlanoContaBeforePost(DataSet: TDataSet);
begin
//atualiza a data de alteracao para poder exportar
if not DadosValidos(true) then
abort;
CadPlanoContaD_ULT_ALT.AsDateTime := Sistema.RDataServidor;
Sistema.MarcaTabelaParaImportar('CAD_PLANO_CONTA');
end;
end.
|
unit TMStruct;
{
Aestan Tray Menu
Made by Onno Broekmans; visit http://www.xs4all.nl/~broekroo/aetraymenu
for more information.
This work is hereby released into the Public Domain. To view a copy of the
public domain dedication, visit:
http://creativecommons.org/licenses/publicdomain/
or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford,
California 94305, USA.
This unit contains some classes that are used for saving the settings
read from the configuration file.
}
{
NOTE:
Lots of code from this unit have been taken from the Inno Setup source code.
The original copyright notice for this code is:
Copyright (C) 1998-2002 Jordan Russell
Portions by Martijn Laan
}
interface
uses Classes, Windows, Contnrs, TMSrvCtrl;
type
TConfigSectionDirective = (
csImageList,
csServiceCheckInterval,
csTrayIconAllRunning,
csTrayIconSomeRunning,
csTrayIconNoneRunning,
csTrayIcon,
csServiceGlyphRunning,
csServiceGlyphPaused,
csServiceGlyphStopped,
csID,
csAboutHeader,
csAboutVersion,
csAboutTextFile,
csHtmlActions
);
TMessagesSectionDirective = (
msAllRunningHint,
msSomeRunningHint,
msNoneRunningHint
);
TMenuSectionDirective = (
mnAutoHotkeys,
mnAutoLineReduction,
mnBarBackPictureDrawStyle,
mnBarBackPictureHorzAlignment,
mnBarBackPictureOffsetX,
mnBarBackPictureOffsetY,
mnBarBackPicturePicture,
mnBarBackPictureTransparent,
mnBarBackPictureVertAlignment,
mnBarCaptionAlignment,
mnBarCaptionCaption,
mnBarCaptionDepth,
mnBarCaptionDirection,
mnBarCaptionFont,
mnBarCaptionHighlightColor,
mnBarCaptionOffsetY,
mnBarCaptionShadowColor,
mnBarPictureHorzAlignment,
mnBarPictureOffsetX,
mnBarPictureOffsetY,
mnBarPicturePicture,
mnBarPictureTransparent,
mnBarPictureVertAlignment,
mnBarBorder,
mnBarGradientEnd,
mnBarGradientStart,
mnBarGradientStyle,
mnBarSide,
mnBarSpace,
mnBarVisible,
mnBarWidth,
mnMenuFont,
mnSeparatorsAlignment,
mnSeparatorsFade,
mnSeparatorsFadeColor,
mnSeparatorsFadeWidth,
mnSeparatorsFlatLines,
mnSeparatorsFont,
mnSeparatorsGradientEnd,
mnSeparatorsGradientStart,
mnSeparatorsGradientStyle,
mnSeparatorsSeparatorStyle
);
TShowCmd = (
swNormal = SW_SHOWNORMAL,
swHidden = SW_HIDE,
swMaximized = SW_SHOWMAXIMIZED,
swMinimized = SW_SHOWMINNOACTIVE
);
TMenuItemType = (
mitItem,
mitSeparator,
mitSubMenu,
mitServiceSubMenu
);
TVarType = (
vtStatic,
vtRegistry,
vtEnvironment,
vtCmdLine,
vtPrompt
);
TVariableFlag = ( //see also VariableFlags
vfIsPath
);
TVariableFlags = set of TVariableFlag;
TActionFlag = ( //see also ActionFlags
afIgnoreErrors,
afWaitUntilTerminated,
afWaitUntilIdle
);
TActionFlags = set of TActionFlag;
THtmlWindowFlag = ( //see also HtmlWindowFlags
hwfMaximized,
hwfNoResize,
hwfNoScrollbars,
hwfEnableContextMenu,
hwfNoCloseButton,
hwfNoHeader,
hwfAlwaysOnTop
);
THtmlWindowFlags = set of THtmlWindowFlag;
TBuiltInAction = (
biaAbout,
biaExit,
biaControlPanelServices,
biaReadConfig,
biaCloseServices,
biaResetServices
);
TServiceAction = (
saStartResume,
saPause,
saStop,
saRestart
);
// TVariable = class
// public
// Name, Value: String;
// Flags: TVariableFlags;
// end;
TVariableBase = class
protected
FName: String;
FFlags: TVariableFlags;
function GetValue: String; virtual; abstract;
procedure SetValue(const AValue: String); virtual; abstract;
public
property Name: String read FName write FName;
property Value: String read GetValue write SetValue;
property Flags: TVariableFlags read FFlags write FFlags;
end;
TVariable = class(TVariableBase)
protected
FValue: String;
function GetValue: String; override;
procedure SetValue(const AValue: String); override;
end;
TPromptVariable = class(TVariableBase)
private
FText: String;
FCaption: String;
FDefaultValue: String;
protected
function GetValue: String; override;
procedure SetValue(const AValue: String); override;
public
property Caption: String read FCaption write FCaption;
property Text: String read FText write FText;
property DefaultValue: String read FDefaultValue write FDefaultValue;
end;
TTMAction = class
private
FFlags: TActionFlags;
public
property Flags: TActionFlags read FFlags write FFlags;
procedure ExecuteAction; virtual; abstract;
//Performs the action
function CanExecute: Boolean; virtual;
//Returns if the corresponding menu item should be enabled;
//the default implementation always returns true.
end; //TTMAction
TTMBuiltInAction = class(TTMAction)
private
FOnExecute: TNotifyEvent;
FBuiltInAction: TBuiltInAction;
public
property OnExecute: TNotifyEvent read FOnExecute write FOnExecute;
property BuiltInAction: TBuiltInAction read FBuiltInAction write FBuiltInAction;
constructor Create(ABuiltInAction: TBuiltInAction); virtual;
procedure ExecuteAction; override;
end; //TTMBuiltInAction
TTMRunAction = class(TTMAction)
private
FFileName: String;
FWorkingDir: String;
FParameters: String;
FShowCmd: TShowCmd;
FVariables: TObjectList;
public
property FileName: String read FFileName write FFileName;
property WorkingDir: String read FWorkingDir write FWorkingDir;
property Parameters: String read FParameters write FParameters;
property ShowCmd: TShowCmd read FShowCmd write FShowCmd;
property Variables: TObjectList read FVariables write FVariables;
constructor Create; virtual;
procedure ExecuteAction; override;
end; //TTMRunAction
TTMShellExecuteAction = class(TTMAction)
private
FFileName: String;
FWorkingDir: String;
FParameters: String;
FShowCmd: TShowCmd;
FVerb: String;
FVariables: TObjectList;
public
property FileName: String read FFileName write FFileName;
property WorkingDir: String read FWorkingDir write FWorkingDir;
property Parameters: String read FParameters write FParameters;
property ShowCmd: TShowCmd read FShowCmd write FShowCmd;
property Verb: String read FVerb write FVerb;
property Variables: TObjectList read FVariables write FVariables;
constructor Create; virtual;
procedure ExecuteAction; override;
end; //TTMShellExecuteAction
TTMServiceAction = class(TTMAction)
private
FService: TTMService;
FAction: TServiceAction;
public
property Service: TTMService read FService write FService;
property Action: TServiceAction read FAction write FAction;
procedure ExecuteAction; override;
function CanExecute: Boolean; override;
end; //TTMServiceAction
TTMMultiAction = class(TTMAction)
private
FItems: TObjectList;
function GetItems(Index: Integer): TTMAction;
function GetCount: Integer;
public
property Items[Index: Integer]: TTMAction read GetItems; default;
property Count: Integer read GetCount;
procedure ExecuteAction; override;
constructor Create; virtual;
destructor Destroy; override;
function Add(AAction: TTMAction): Integer;
procedure Clear;
procedure Delete(Index: Integer);
procedure Insert(Index: Integer; AAction: TTMAction);
procedure Move(CurIndex, NewIndex: Integer);
end; //TTMMultiAction
TTMHtmlWindowAction = class(TTMAction)
private
FSrc: String;
FHeader: String;
FVariables: TObjectList;
FHtmlActions: TStringList;
FHtmlWindowFlags: THtmlWindowFlags;
FHeight: Integer;
FWidth: Integer;
FLeft: Integer;
FTop: Integer;
public
property Header: String read FHeader write FHeader;
property Src: String read FSrc write FSrc;
property HtmlWindowFlags: THtmlWindowFlags read FHtmlWindowFlags write FHtmlWindowFlags;
property Height: Integer read FHeight write FHeight;
property Width: Integer read FWidth write FWidth;
property Left: Integer read FLeft write FLeft;
property Top: Integer read FTop write FTop;
property Variables: TObjectList read FVariables write FVariables;
property HtmlActions: TStringList read FHtmlActions write FHtmlActions;
procedure ExecuteAction; override;
end; //TTmHtmlWindowAction
const
{ Param name constants }
ParamCommonFlags = 'Flags';
ParamServicesName = 'Name';
ParamServicesDisplayName = 'DisplayName';
ParamVariablesName = 'Name';
ParamVariablesType = 'Type';
ParamVariablesFlags = 'Flags';
ParamVariablesValue = 'Value';
ParamVariablesRegRoot = 'Root';
ParamVariablesRegKey = 'Key';
ParamVariablesRegValue = 'ValueName';
ParamVariablesEnvName = 'EnvName';
ParamVariablesCmdLineParamName = 'ParamName';
ParamVariablesDefaultValue = 'DefaultValue';
ParamVariablesPromptCaption = 'PromptCaption';
ParamVariablesPromptText = 'PromptText';
ParamMenuItemType = 'Type';
ParamMenuItemCaption = 'Caption';
ParamMenuItemGlyph = 'Glyph';
ParamMenuItemSection = 'SubMenu';
ParamActionAction = 'Action';
ParamActionFileName = 'FileName';
ParamActionParams = 'Parameters';
ParamActionWorkingDir = 'WorkingDir';
ParamActionShowCmd = 'ShowCmd';
ParamActionShellExecVerb = 'Verb';
ParamActionMultiSection = 'Actions';
ParamActionFlags = 'Flags';
ParamServiceService = 'Service';
ParamActionServiceAction = 'ServiceAction';
ParamActionHtmlSrc = 'Src';
ParamActionHtmlHeader = 'Header';
ParamActionHtmlWindowFlags = 'HtmlWindowFlags';
ParamActionHtmlHeight = 'Height';
ParamActionHtmlWidth = 'Width';
ParamActionHtmlLeft = 'Left';
ParamActionHtmlTop = 'Top';
{ Flag name constants }
VariableFlags: array[0..0] of PChar = ( //see also TVariableFlags
'ispath');
ActionFlags: array[0..2] of PChar = ( //see also TActionFlags
'ignoreerrors', 'waituntilterminated', 'waituntilidle');
HtmlWindowFlags: array[0..6] of PChar = ( //see also THtmlWindowFlags
'maximized', 'noresize', 'noscrollbars', 'enablecontextmenu',
'noclosebutton', 'noheader', 'alwaysontop');
implementation
uses SysUtils, Forms,
TMCmnFunc, Dialogs, TMMsgs, TMHtmlWindow;
{ TTMAction }
function TTMAction.CanExecute: Boolean;
begin
Result := True;
end;
{ TTMBuiltInAction }
constructor TTMBuiltInAction.Create(ABuiltInAction: TBuiltInAction);
begin
BuiltInAction := ABuiltInAction;
end;
procedure TTMBuiltInAction.ExecuteAction;
begin
inherited;
try
if Assigned(OnExecute) then
OnExecute(Self);
except
on E: Exception do
if not (afIgnoreErrors in Flags) then
raise Exception.Create('Could not perform built-in action:'#13#10 + E.Message);
end; //try..except
end;
{ TTMRunAction }
constructor TTMRunAction.Create;
begin
ShowCmd := swNormal;
end;
procedure ProcessMessagesProc; far;
begin
Application.ProcessMessages;
end;
procedure TTMRunAction.ExecuteAction;
var
ResultCode: Integer;
begin
inherited;
if not InstExec(ExpandVariables(FileName, Variables),
ExpandVariables(Parameters, Variables),
ExpandVariables(WorkingDir, Variables),
afWaitUntilTerminated in Flags,
afWaitUntilIdle in Flags,
Ord(ShowCmd),
ProcessMessagesProc,
ResultCode) then
if not (afIgnoreErrors in Flags) then
raise Exception.Create('Could not execute run action:'#13#10 + SysErrorMessage(ResultCode));
{ TODO 0 -cError handling : Improve TTMRunAction error handling (added ignoreerrors flag; need further improvement?}
end;
{ TTMShellExecuteAction }
constructor TTMShellExecuteAction.Create;
begin
ShowCmd := swNormal;
end;
procedure TTMShellExecuteAction.ExecuteAction;
var
ErrorCode: Integer;
begin
inherited;
if not InstShellExec(ExpandVariables(FileName, Variables),
ExpandVariables(Parameters, Variables),
Verb,
ExpandVariables(WorkingDir, Variables),
Ord(ShowCmd), ErrorCode) then
if not (afIgnoreErrors in Flags) then
raise Exception.Create('Could not execute shellexecute action:'#13#10 + SysErrorMessage(ErrorCode));
{ TODO 0 -cError handling : Improve TTMShellExecuteAction error handling (added ignoreerrors flag; need further improvement? }
end;
{ TTMServiceAction }
function TTMServiceAction.CanExecute: Boolean;
begin
Result := True;
with Service do
if not Active then
Result := False
else
case Action of
saStartResume:
Result := (State <> svsRunning);
saPause:
Result := (svcPauseContinue in ControlsAccepted) and (State <> svsPaused);
saStop:
Result := (svcStop in ControlsAccepted) and (State <> svsStopped);
saRestart:
Result := (svcStop in ControlsAccepted) and (State <> svsStopped);
end; //else not active then with service do case action of
end;
procedure TTMServiceAction.ExecuteAction;
begin
inherited;
{ TODO 0 : Improve TTMServiceAction error handling (added ignoreerrors flag; need further improvement?}
try
with Service do
begin
if not Active then
Exit;
case Action of
saStartResume:
if State = svsPaused then
begin
Continue;
if afWaitUntilTerminated in Flags then
while State = svsContinuePending do
begin
Application.ProcessMessages;
if Application.Terminated then
Exit;
end;
end
else
begin
Start;
if afWaitUntilTerminated in Flags then
while State = svsStartPending do
begin
Application.ProcessMessages;
if Application.Terminated then
Exit;
end;
end;
saPause: begin
Pause;
if afWaitUntilTerminated in Flags then
while State = svsPausePending do
begin
Application.ProcessMessages;
if Application.Terminated then
Exit;
end;
end;
saStop: begin
Stop;
if afWaitUntilTerminated in Flags then
while State = svsStopPending do
begin
Application.ProcessMessages;
if Application.Terminated then
Exit;
end;
end;
saRestart: begin
Stop;
while State = svsStopPending do
begin
Application.ProcessMessages;
if Application.Terminated then
Exit;
end;
Start;
end;
end; //case
end; //with service do
except
on E: Exception do
if not (afIgnoreErrors in Flags) then
raise Exception.Create('Could not perform service action:'#13#10 + E.Message);
end; //try..except
end;
{ TTMMultiAction }
function TTMMultiAction.Add(AAction: TTMAction): Integer;
begin
Result := FItems.Add(AAction);
end;
procedure TTMMultiAction.Clear;
begin
FItems.Clear;
end;
constructor TTMMultiAction.Create;
begin
FItems := TObjectList.Create(True);
end;
procedure TTMMultiAction.Delete(Index: Integer);
begin
FItems.Delete(Index);
end;
destructor TTMMultiAction.Destroy;
begin
FreeAndNil(FItems);
end;
procedure TTMMultiAction.ExecuteAction;
var
I: Integer;
begin
inherited;
for I := 0 to FItems.Count - 1 do
(Items[I] as TTMAction).ExecuteAction;
end;
function TTMMultiAction.GetCount: Integer;
begin
Result := FItems.Count;
end;
function TTMMultiAction.GetItems(Index: Integer): TTMAction;
begin
Result := (FItems[Index] as TTMAction);
end;
procedure TTMMultiAction.Insert(Index: Integer; AAction: TTMAction);
begin
FItems.Insert(Index, AAction);
end;
procedure TTMMultiAction.Move(CurIndex, NewIndex: Integer);
begin
FItems.Move(CurIndex, NewIndex);
end;
{ TVariable }
function TVariable.GetValue: String;
begin
Result := FValue;
end;
procedure TVariable.SetValue(const AValue: String);
begin
inherited;
FValue := AValue;
end;
{ TPromptVariable }
function TPromptVariable.GetValue: String;
begin
Result := InputBox(Caption, Text, DefaultValue);
end;
procedure TPromptVariable.SetValue(const AValue: String);
begin
inherited;
raise EInvalidOperation.Create(SCannotSetPromptVarValue);
end;
{ TTMHtmlWindowAction }
procedure TTMHtmlWindowAction.ExecuteAction;
begin
inherited;
if Assigned(HtmlWindow) then
FreeAndNil(HtmlWindow);
HtmlWindow := THtmlWindow.Create(Application);
with HtmlWindow do
begin
HtmlWindowFlags := Self.HtmlWindowFlags;
Src := ExpandVariables(Self.Src, Variables);
Header := ExpandVariables(Self.Header, Variables);
HtmlActions := Self.HtmlActions;
SetPosAndDimensions(Self.Left, Self.Top, Self.Width, Self.Height);
Show;
end; //with htmlwindow
end;
end.
|
unit FIToolkit.Config.Types;
interface
type
TConfigPropCategory = (cpcAny, cpcSerializable, cpcNonSerializable);
TDefaultValueKind = (dvkUndefined, dvkData, dvkCalculated);
TFixInsightOutputFormat = (fiofPlainText, fiofXML);
TConfigAttribute = class abstract (TCustomAttribute)
strict private
FArrayDelimiter : String;
FSerializable : Boolean;
public
constructor Create(Serialize : Boolean = True); overload;
constructor Create(const AnArrayDelimiter : String); overload;
property ArrayDelimiter : String read FArrayDelimiter;
property Serializable : Boolean read FSerializable;
end;
FIToolkitParam = class (TConfigAttribute); //FI:C104
FixInsightParam = class (TConfigAttribute); //FI:C104
implementation
uses
System.SysUtils;
{ TConfigAttribute }
constructor TConfigAttribute.Create(Serialize : Boolean);
begin
inherited Create;
FSerializable := Serialize;
end;
constructor TConfigAttribute.Create(const AnArrayDelimiter : String);
begin
Create(True);
Assert(not AnArrayDelimiter.IsEmpty, Format('Empty array delimiter passed to %s attribute.', [ClassName]));
FArrayDelimiter := AnArrayDelimiter;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.