text stringlengths 14 6.51M |
|---|
unit Model.UsuarioDAO;
interface
uses
DB,
Model.Interf,
Model.DAO.Interf,
Model.DMConnZeos,
Model.Usuario.Entidade,
Classes;
type
TUsuarioDAO_Model = class(TInterfacedObject, iUsuarioDAO_Model, iDAO_Model)
private
FThis: TUSUARIO;
FNewThis: TUSUARIO;
FConn: iModelQuery;
FDataSource : TDataSource;
FList : TList;
procedure DataSource1DataChange(Sender: TObject; Field: TField);
public
constructor Create;
destructor Destroy; override;
class function New : iDAO_Model;
function _This : TUSUARIO;
function _NewThis : TUSUARIO;
function Insert(): iDAO_Model;
function Update(): iDAO_Model;
function Delete(AId : string): iDAO_Model; overload;
function Delete(AId : integer): iDAO_Model; overload;
function Find(): iDAO_Model; overload;
function Find(AList : TList): iDAO_Model; overload;
function Find(AId : string): iDAO_Model; overload;
function DataSource(ADataSource : TDataSource): iDAO_Model;
end;
implementation
uses
SysUtils;
{ TUsuarioDAO_Model }
constructor TUsuarioDAO_Model.Create;
begin
inherited;
FThis := TUSUARIO.Create;
FConn := DMConnZeos.ConnZeos;
end;
function TUsuarioDAO_Model.DataSource(ADataSource: TDataSource): iDAO_Model;
begin
Result := Self;
FDataSource := ADataSource;
FDataSource.DataSet := FConn.DataSet;
FDataSource.OnDataChange := DataSource1DataChange;
end;
function TUsuarioDAO_Model.Delete(AId: string): iDAO_Model;
begin
Result := Self;
if (Trim(AId) = '') then
raise Exception.Create('Id da tabela não informado');
FConn.SQL.Clear;
FConn.SQL.Add('delete from USUARIO where CODIGO = :CODIGO');
FConn.Params.ParamByName('CODIGO').Value := AId;
FConn.ExecSQL;
end;
procedure TUsuarioDAO_Model.DataSource1DataChange(Sender: TObject;
Field: TField);
begin
if (not FConn.DataSet.IsEmpty) then
begin
FThis.CODIGO := FConn.DataSet.FieldByName('CODIGO').Value;
FThis.NOME := FConn.DataSet.FieldByName('NOME').Value;
FThis.LOGIN := FConn.DataSet.FieldByName('LOGIN').Value;
FThis.SENHA := FConn.DataSet.FieldByName('SENHA').Value;
FThis.STATUS := FConn.DataSet.FieldByName('STATUS').Value;
FThis.EMAIL := FConn.DataSet.FieldByName('EMAIL').Value;
FThis.DATA_NASCIMENTO := FConn.DataSet.FieldByName('DATA_NASCIMENTO').Value;
end;
end;
function TUsuarioDAO_Model.Delete(AId: integer): iDAO_Model;
begin
Result := Self.Delete(IntToStr(AId));
end;
destructor TUsuarioDAO_Model.Destroy;
begin
FreeAndNil(FThis);
inherited;
end;
function TUsuarioDAO_Model.Find(AId: string): iDAO_Model;
begin
Result := Self;
FConn.SQL.Clear;
//FDB.Get(['CODIGO', 'NOME', 'LOGIN', 'SENHA', 'STATUS', 'EMAIL', 'DATA_NASCIMENTO']);
FConn.SQL.Add('select CODIGO'+
', NOME'+
', LOGIN'+
', SENHA'+
', STATUS'+
', EMAIL'+
', DATA_NASCIMENTO '+
' from USUARIO where :CODIGO in (cast(CODIGO as varchar), '''')');
FConn.Params.ParamByName('CODIGO').Value := AId;
FConn.Open;
end;
function TUsuarioDAO_Model.Find: iDAO_Model;
begin
Result := Self;
Find('');
end;
function TUsuarioDAO_Model.Find(AList: TList): iDAO_Model;
var
LUSUARIO : TUSUARIO;
begin
Result := Self;
Self.Find;
if FConn.DataSet.IsEmpty then Exit;
AList.Clear;
FConn.DataSet.First;
while (not FConn.DataSet.Eof) do
begin
LUSUARIO := TUSUARIO.Create;
LUSUARIO.CODIGO := FConn.DataSet.FieldByName('CODIGO').Value;
LUSUARIO.NOME := FConn.DataSet.FieldByName('NOME').Value;
LUSUARIO.LOGIN := FConn.DataSet.FieldByName('LOGIN').Value;
LUSUARIO.SENHA := FConn.DataSet.FieldByName('SENHA').Value;
LUSUARIO.STATUS := FConn.DataSet.FieldByName('STATUS').Value;
LUSUARIO.EMAIL := FConn.DataSet.FieldByName('EMAIL').Value;
LUSUARIO.DATA_NASCIMENTO := FConn.DataSet.FieldByName('DATA_NASCIMENTO').Value;
AList.Add(LUSUARIO);
FConn.DataSet.Next;
end;
end;
function TUsuarioDAO_Model.Insert: iDAO_Model;
begin
Result := Self;
if (FNewThis.DATA_NASCIMENTO <= StrToDate('01/01/1128')) then
raise Exception.Create('Data informada inválida');
FConn.SQL.Clear;
FConn.SQL.Add('insert into USUARIO '+
'(CODIGO, NOME, LOGIN, SENHA, STATUS, EMAIL, DATA_NASCIMENTO) values ('+
'NULL, :NOME, :LOGIN, :SENHA, :STATUS, :EMAIL, :DATA_NASCIMENTO)');
//FConn.Params.ParamByName('CODIGO').Value := FNewThis.CODIGO;
FConn.Params.ParamByName('NOME').Value := FNewThis.NOME;
FConn.Params.ParamByName('LOGIN').Value := FNewThis.LOGIN;
FConn.Params.ParamByName('SENHA').Value := FNewThis.SENHA;
FConn.Params.ParamByName('STATUS').Value := FNewThis.STATUS;
FConn.Params.ParamByName('EMAIL').Value := FNewThis.EMAIL;
FConn.Params.ParamByName('DATA_NASCIMENTO').Value := FNewThis.DATA_NASCIMENTO;
FConn.ExecSQL;
end;
class function TUsuarioDAO_Model.New: iDAO_Model;
begin
Result := Self.Create;
end;
function TUsuarioDAO_Model.Update: iDAO_Model;
begin
Result := Self;
FConn.SQL.Clear;
FConn.SQL.Text := 'update USUARIO set '+
'NOME = :NOME, '+
'LOGIN = :LOGIN, '+
'SENHA = :SENHA, '+
'STATUS = :STATUS, '+
'EMAIL = :EMAIL, '+
'DATA_NASCIMENTO = :DATA_NASCIMENTO '+
'where CODIGO = :CODIGO';
FConn.Params.ParamByName('CODIGO').Value := FThis.CODIGO;
FConn.Params.ParamByName('NOME').Value := FThis.NOME;
FConn.Params.ParamByName('LOGIN').Value := FThis.LOGIN;
FConn.Params.ParamByName('SENHA').Value := FThis.SENHA;
FConn.Params.ParamByName('STATUS').Value := FThis.STATUS;
FConn.Params.ParamByName('EMAIL').Value := FThis.EMAIL;
FConn.Params.ParamByName('DATA_NASCIMENTO').Value := FThis.DATA_NASCIMENTO;
FConn.ExecSQL;
end;
function TUsuarioDAO_Model._NewThis: TUSUARIO;
begin
if not Assigned(FNewThis) then
FNewThis := TUSUARIO.Create;
Result := FNewThis;
end;
function TUsuarioDAO_Model._This: TUSUARIO;
begin
Result := FThis;
end;
end.
|
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.ProgressDialog.iOS;
interface
uses
System.UITypes, System.UIConsts, System.Messaging, System.TypInfo, Macapi.ObjectiveC, iOSapi.UIKit, iOSapi.Foundation,
FGX.ProgressDialog, FGX.ProgressDialog.Types, FGX.Asserts;
const
SHADOW_ALPHA = 180;
MESSAGE_FONT_SIZE = 15;
MESSAGE_MARGINS = 5;
MESSAGE_HEIGHT = 20;
INDICATOR_MARGIN = 5;
PROGRESSBAR_WIDTH = 200;
PROGRESSBAR_HEIGHT = 20;
type
{ TIOSProgressDialogService }
TIOSProgressDialogService = class(TInterfacedObject, IFGXProgressDialogService)
public
{ IFGXProgressDialogService }
function CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog;
function CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog;
end;
IiOSShadow = interface(NSObject)
['{5E0B5363-01B8-4670-A90A-107EDD428029}']
procedure tap; cdecl;
end;
TiOSDelegate = class(TOCLocal)
private
[Weak] FNativeDialog: TfgNativeDialog;
protected
function GetObjectiveCClass: PTypeInfo; override;
public
constructor Create(const ADialog: TfgNativeDialog);
{ UIView }
procedure tap; cdecl;
end;
TiOSNativeActivityDialog = class(TfgNativeActivityDialog)
private
FActivityIndicator: UIActivityIndicatorView;
FShadow: TiOSDelegate;
FShadowColor: TAlphaColor;
FShadowView: UIView;
FMessageLabel: UILabel;
FDelegate: TiOSDelegate;
FTapRecognizer: UITapGestureRecognizer;
procedure DoOrientationChanged(const Sender: TObject; const M: TMessage);
protected
procedure MessageChanged; override;
public
constructor Create(const AOwner: TObject); override;
destructor Destroy; override;
procedure Show; override;
procedure Hide; override;
procedure Realign;
end;
TiOSNativeProgressDialog = class(TfgNativeProgressDialog)
private
FDelegate: TiOSDelegate;
FTapRecognizer: UITapGestureRecognizer;
FProgressView: UIProgressView;
FShadowColor: TAlphaColor;
FShadowView: UIView;
FMessageLabel: UILabel;
procedure DoOrientationChanged(const Sender: TObject; const M: TMessage);
protected
procedure MessageChanged; override;
procedure ProgressChanged; override;
public
constructor Create(const AOwner: TObject); override;
destructor Destroy; override;
procedure ResetProgress; override;
procedure Show; override;
procedure Hide; override;
procedure Realign;
end;
procedure RegisterService;
procedure UnregisterService;
implementation
uses
System.Types, System.Math, System.SysUtils, iOSapi.CoreGraphics, Macapi.ObjCRuntime, Macapi.Helpers,
FMX.Platform, FMX.Platform.iOS, FMX.Forms, FMX.Helpers.iOS, FGX.Helpers.iOS;
procedure RegisterService;
begin
TPlatformServices.Current.AddPlatformService(IFGXProgressDialogService, TIOSProgressDialogService.Create);
end;
procedure UnregisterService;
begin
TPlatformServices.Current.RemovePlatformService(IFGXProgressDialogService);
end;
{ TIOSProgressDialogService }
function TIOSProgressDialogService.CreateNativeActivityDialog(const AOwner: TObject): TfgNativeActivityDialog;
begin
Result := TiOSNativeActivityDialog.Create(AOwner);
end;
function TIOSProgressDialogService.CreateNativeProgressDialog(const AOwner: TObject): TfgNativeProgressDialog;
begin
Result := TiOSNativeProgressDialog.Create(AOwner);
end;
{ TiOSNativeProgressDialog }
constructor TiOSNativeActivityDialog.Create(const AOwner: TObject);
begin
AssertIsNotNil(MainScreen);
AssertIsNotNil(SharedApplication.keyWindow);
AssertIsNotNil(SharedApplication.keyWindow.rootViewController);
AssertIsNotNil(SharedApplication.keyWindow.rootViewController.view);
inherited Create(AOwner);
FShadowColor := MakeColor(0, 0, 0, SHADOW_ALPHA);
FDelegate := TiOSDelegate.Create(Self);
FTapRecognizer := TUITapGestureRecognizer.Create;
FTapRecognizer.setNumberOfTapsRequired(1);
FTapRecognizer.addTarget(FDelegate.GetObjectID, sel_getUid('tap'));
// Shadow
FShadowView := TUIView.Create;
FShadowView.setUserInteractionEnabled(True);
FShadowView.setHidden(True);
FShadowView.setAutoresizingMask(UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight);
FShadowView.setBackgroundColor(TUIColor.MakeColor(FShadowColor));
FShadowView.addGestureRecognizer(FTapRecognizer);
// Creating Ani indicator
FActivityIndicator := TUIActivityIndicatorView.Alloc;
FActivityIndicator.initWithActivityIndicatorStyle(UIActivityIndicatorViewStyleWhite);
FActivityIndicator.setUserInteractionEnabled(False);
FActivityIndicator.startAnimating;
FActivityIndicator.setAutoresizingMask(UIViewAutoresizingFlexibleLeftMargin or UIViewAutoresizingFlexibleRightMargin);
// Creating message label
FMessageLabel := TUILabel.Create;
FMessageLabel.setUserInteractionEnabled(False);
FMessageLabel.setTextColor(TUIColor.whiteColor);
FMessageLabel.setBackgroundColor(TUIColor.clearColor);
FMessageLabel.setFont(FMessageLabel.font.fontWithSize(MESSAGE_FONT_SIZE));
FMessageLabel.setTextAlignment(UITextAlignmentCenter);
// Adding view
FShadowView.addSubview(FActivityIndicator);
FShadowView.addSubview(FMessageLabel);
// Adding Shadow to application
SharedApplication.keyWindow.rootViewController.view.AddSubview(FShadowView);
Realign;
{ Message subscription }
TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, DoOrientationChanged);
end;
destructor TiOSNativeActivityDialog.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage, DoOrientationChanged);
FreeAndNil(FShadow);
FActivityIndicator.removeFromSuperview;
FActivityIndicator.release;
FActivityIndicator := nil;
FMessageLabel.removeFromSuperview;
FMessageLabel.release;
FMessageLabel := nil;
FShadowView.removeFromSuperview;
FShadowView.release;
FShadowView := nil;
inherited Destroy;
end;
procedure TiOSNativeActivityDialog.DoOrientationChanged(const Sender: TObject; const M: TMessage);
begin
Realign;
end;
procedure TiOSNativeActivityDialog.Hide;
begin
AssertIsNotNil(FShadowView);
inherited;
FadeOut(FShadowView, DEFAULT_ANIMATION_DURATION);
DoHide;
end;
procedure TiOSNativeActivityDialog.MessageChanged;
begin
AssertIsNotNil(FMessageLabel);
FMessageLabel.setText(StrToNSStr(Message));
// We should call it once for starting animation
if IsShown then
Application.ProcessMessages;
end;
procedure TiOSNativeActivityDialog.Realign;
var
ScreenBounds: TSize;
CenterPoint: NSPoint;
begin
ScreenBounds := Screen.Size;
FShadowView.setFrame(CGRect.Create(ScreenBounds.Width, ScreenBounds.Height));
CenterPoint := FShadowView.center;
FActivityIndicator.setCenter(CGPointMake(CenterPoint.X, CenterPoint.Y - FActivityIndicator.bounds.height - INDICATOR_MARGIN));
FMessageLabel.setBounds(CGRect.Create(FShadowView.bounds.width, 25));
FMessageLabel.setCenter(CGPointMake(CenterPoint.X, CenterPoint.Y + MESSAGE_MARGINS));
end;
procedure TiOSNativeActivityDialog.Show;
begin
AssertIsNotNil(FShadowView);
AssertIsNotNil(FMessageLabel);
inherited;
FadeIn(FShadowView, DEFAULT_ANIMATION_DURATION);
DoShow;
// We should call it once for starting animation
Application.ProcessMessages;
end;
{ TiOSNativeProgressDialog }
constructor TiOSNativeProgressDialog.Create(const AOwner: TObject);
begin
AssertIsNotNil(MainScreen);
AssertIsNotNil(SharedApplication.keyWindow);
AssertIsNotNil(SharedApplication.keyWindow.rootViewController);
AssertIsNotNil(SharedApplication.keyWindow.rootViewController.view);
inherited Create(AOwner);
FShadowColor := MakeColor(0, 0, 0, SHADOW_ALPHA);
FDelegate := TiOSDelegate.Create(Self);
FTapRecognizer := TUITapGestureRecognizer.Create;
FTapRecognizer.setNumberOfTapsRequired(1);
FTapRecognizer.addTarget(FDelegate.GetObjectID, sel_getUid('tap'));
// Shadow
FShadowView := TUIView.Create;
FShadowView.setUserInteractionEnabled(True);
FShadowView.setHidden(True);
FShadowView.setAutoresizingMask(UIViewAutoresizingFlexibleWidth or UIViewAutoresizingFlexibleHeight);
FShadowView.setBackgroundColor(TUIColor.MakeColor(FShadowColor));
FShadowView.addGestureRecognizer(FTapRecognizer);
// Creating message label
FMessageLabel := TUILabel.Create;
FMessageLabel.setBackgroundColor(TUIColor.clearColor);
FMessageLabel.setTextColor(TUIColor.whiteColor);
FMessageLabel.setTextAlignment(UITextAlignmentCenter);
FMessageLabel.setFont(FMessageLabel.font.fontWithSize(MESSAGE_FONT_SIZE));
// Creating Ani indicator
FProgressView := TUIProgressView.Alloc;
FProgressView.initWithProgressViewStyle(UIProgressViewStyleDefault);
// Adding view
FShadowView.addSubview(FProgressView);
FShadowView.addSubview(FMessageLabel);
// Adding Shadow to application
SharedApplication.keyWindow.rootViewController.view.AddSubview(FShadowView);
Realign;
{ Message subscription }
TMessageManager.DefaultManager.SubscribeToMessage(TOrientationChangedMessage, DoOrientationChanged);
end;
destructor TiOSNativeProgressDialog.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TOrientationChangedMessage, DoOrientationChanged);
FreeAndNil(FDelegate);
FProgressView.removeFromSuperview;
FProgressView.release;
FProgressView := nil;
FMessageLabel.removeFromSuperview;
FMessageLabel.release;
FMessageLabel := nil;
FShadowView.removeFromSuperview;
FShadowView.release;
FShadowView := nil;
inherited Destroy;
end;
procedure TiOSNativeProgressDialog.DoOrientationChanged(const Sender: TObject; const M: TMessage);
begin
Realign;
end;
procedure TiOSNativeProgressDialog.Hide;
begin
AssertIsNotNil(FShadowView);
inherited;
FadeOut(FShadowView, DEFAULT_ANIMATION_DURATION);
DoHide;
end;
procedure TiOSNativeProgressDialog.MessageChanged;
begin
AssertIsNotNil(FMessageLabel);
FMessageLabel.setText(StrToNSStr(Message));
// We should call it once for starting animation
if IsShown then
Application.ProcessMessages;
end;
procedure TiOSNativeProgressDialog.ProgressChanged;
begin
AssertIsNotNil(FProgressView);
AssertInRange(Progress, 0, Max);
if Max > 0 then
FProgressView.setProgress(Progress / Max, True)
else
FProgressView.setProgress(0);
// We should call it once for starting animation
if IsShown then
Application.ProcessMessages;
end;
procedure TiOSNativeProgressDialog.Realign;
var
ScreenBounds: TSize;
CenterPoint: NSPoint;
begin
ScreenBounds := Screen.size;
FShadowView.setFrame(CGRect.Create(ScreenBounds.Width, ScreenBounds.Height));
CenterPoint := FShadowView.center;
FMessageLabel.setBounds(CGRect.Create(FShadowView.bounds.width, MESSAGE_HEIGHT));
FMessageLabel.setCenter(CGPointMake(CenterPoint.X, CenterPoint.Y - FMessageLabel.bounds.height));
FProgressView.setBounds(CGRect.Create(PROGRESSBAR_WIDTH, PROGRESSBAR_HEIGHT));
FProgressView.setCenter(CenterPoint);
end;
procedure TiOSNativeProgressDialog.ResetProgress;
begin
AssertIsNotNil(FProgressView);
inherited ResetProgress;
FProgressView.setProgress(0);
end;
procedure TiOSNativeProgressDialog.Show;
begin
AssertIsNotNil(FShadowView);
inherited;
FadeIn(FShadowView, DEFAULT_ANIMATION_DURATION);
DoShow;
// We should call it once for starting animation
Application.ProcessMessages;
end;
{ TiOSShadow }
constructor TiOSDelegate.Create(const ADialog: TfgNativeDialog);
begin
AssertIsNotNil(ADialog);
inherited Create;
FNativeDialog := ADialog;
end;
function TiOSDelegate.GetObjectiveCClass: PTypeInfo;
begin
Result := TypeInfo(IiOSShadow);
end;
procedure TiOSDelegate.tap;
begin
AssertIsNotNil(FNativeDialog);
if FNativeDialog.Cancellable then
begin
FNativeDialog.Hide;
if Assigned(FNativeDialog.OnCancel) then
FNativeDialog.OnCancel(FNativeDialog.Owner);
end;
end;
end.
|
unit classesPersonen;
interface
uses System.SysUtils, System.StrUtils, Vcl.Dialogs, System.UITypes, System.Generics.Collections,
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;
type
TMitarbeiter = class
private
SqlQuery: TFDQuery;
FId : Variant;
FName : string;
FVorname: string;
FTeam : string;
procedure IdErmitteln();
procedure DatenEinlesen(Id: integer);
function getVollName(): string;
public
property Id : Variant read FId write FId;
property Name : string read FName write FName;
property Vorname : string read FVorname write FVorname;
property Team : string read FTeam write FTeam;
property VollName: string read getVollName;
constructor Create(name, Vorname, Team: string; Connection: TFDConnection);
constructor CreateFromId(Id: integer; Connection: TFDConnection);
function Speichern(): boolean;
function Aktualisieren(): boolean;
function Loeschen(): boolean;
const
TABLE_NAME = 'Mitarbeiter';
end;
type
TBenutzer = class(TMitarbeiter)
private
FLogin : string;
FMd5Passwort: string;
FMd5Salt : string;
procedure setMd5Passwort(hash: string);
procedure setMd5Salt(salt: string);
procedure DatenEinlesen(Id: integer);
function istAnmeldeNameFrei(login: string; neuerNutzer: boolean): boolean;
public
property login : string read FLogin write FLogin;
property Md5Passwort: string read FMd5Passwort write setMd5Passwort;
property Md5Salt : string read FMd5Salt write setMd5Salt;
constructor Create(login, Md5Passwort, Md5Salt, name, Vorname: string;
Connection: TFDConnection);
constructor CreateFromId(Id: integer; Connection: TFDConnection);
function Speichern(): boolean;
function Aktualisieren(): boolean;
function Loeschen(): boolean;
const
TABLE_NAME = 'Benutzer';
end;
type
TBenutzerVerwaltung = class
private
SqlQuery : TFDQuery;
FBenutzerListe: TList<TBenutzer>;
public
property BenutzerListe: TList<TBenutzer> read FBenutzerListe write FBenutzerListe;
constructor Create(Connection: TFDConnection);
procedure BenutzerSuchen(Suchbegriff: string; Connection: TFDConnection);
const
TABLE_NAME: string = 'Benutzer';
end;
implementation
{ TMitarbeiter }
function TMitarbeiter.Aktualisieren(): boolean;
begin
result := false;
if self.Id <> 0 then
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('UPDATE ' + self.TABLE_NAME + ' SET');
Add('Name = :name, ');
Add('Vorname = :vorname,');
Add('Team = :team');
Add('WHERE Id = :id');
ParamByName('name').Value := self.name;
ParamByName('vorname').Value := self.Vorname;
ParamByName('team').Value := self.Team;
ParamByName('id').Value := self.Id;
end;
self.SqlQuery.ExecSQL;
end;
if self.SqlQuery.RowsAffected = 1 then
result := true
else
raise Exception.Create('Bei der Aktualisierung trat ein Fehler auf.');
end;
constructor TMitarbeiter.Create(name, Vorname, Team: string; Connection: TFDConnection);
begin
self.Id := 0;
self.name := name;
self.Vorname := Vorname;
self.Team := Team;
self.SqlQuery := TFDQuery.Create(nil);
self.SqlQuery.Connection := Connection;
end;
constructor TMitarbeiter.CreateFromId(Id: integer; Connection: TFDConnection);
begin
self.SqlQuery := TFDQuery.Create(nil);
self.SqlQuery.Connection := Connection;
self.DatenEinlesen(Id);
end;
procedure TMitarbeiter.DatenEinlesen(Id: integer);
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE Id = :id');
ParamByName('id').Value := Id;
end;
self.SqlQuery.Open;
if self.SqlQuery.RecordCount = 1 then
begin
self.Id := self.SqlQuery.FieldByName('Id').AsInteger;
self.name := self.SqlQuery.FieldByName('Name').AsString;
self.Vorname := self.SqlQuery.FieldByName('Vorname').AsString;
self.Team := self.SqlQuery.FieldByName('Team').AsString;
self.SqlQuery.Close;
end
else
raise Exception.Create
(Format('Fehler bei der Datenabfrage. Der Mitarbeiter mit der Id:%d konnte nicht gefunden werden.', [Id]));
end;
function TMitarbeiter.getVollName: string;
begin
result := self.Vorname + ' ' + self.name;
end;
procedure TMitarbeiter.IdErmitteln;
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('SELECT Id FROM ' + self.TABLE_NAME + ' ORDER BY Id DESC LIMIT 1');
Add('WHERE Name = :name');
Add('AND Vorname = :vorname');
ParamByName('name').Value := self.name;
ParamByName('vorname').Value := self.Vorname;
end;
self.SqlQuery.Open;
if self.SqlQuery.RecordCount = 1 then
self.Id := self.SqlQuery.FieldByName('Id').AsInteger;
self.SqlQuery.Close
end;
function TMitarbeiter.Loeschen(): boolean;
begin
result := false;
if self.Id <> 0 then
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('DELETE FROM ' + self.TABLE_NAME + ' WHERE Id = :id');
ParamByName('id').Value := self.Id;
end;
self.SqlQuery.ExecSQL;
end;
if self.SqlQuery.RowsAffected = 1 then
result := true
else
raise Exception.Create
(Format('Fehler beim Löschen. Der Mitarbeiter mit der Id:%d konnte nicht gefunden werden.', [Id]));
end;
function TMitarbeiter.Speichern(): boolean;
begin
result := false;
if self.Id = 0 then
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('INSERT INTO ' + self.TABLE_NAME + ' (Name, Vorname)');
Add('VALUES (:name,:vorname)');
ParamByName('name').Value := self.name;
ParamByName('vorname').Value := self.Vorname;
end;
self.SqlQuery.ExecSQL;
if self.SqlQuery.RowsAffected = 1 then
begin
result := true;
self.IdErmitteln;
end
else
raise Exception.Create('Es ist ein Fehler beim Speichern aufgetreten. Bitte wiederholen sie den Vorgang!');
end
else
result := self.Aktualisieren;
end;
{ TBenutzer }
function TBenutzer.Aktualisieren(): boolean;
begin
result := false;
if self.istAnmeldeNameFrei(self.login, false) then
begin
if self.Id <> 0 then
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('UPDATE ' + self.TABLE_NAME + ' SET');
Add('Login = :login,');
Add('Md5Passwort = :pw,');
Add('Md5Salt = :salt,');
Add('Name = :name, ');
Add('Vorname = :vorname');
Add('WHERE Id = :id');
ParamByName('login').Value := self.login;
ParamByName('pw').Value := self.Md5Passwort;
ParamByName('salt').Value := self.Md5Salt;
ParamByName('name').Value := self.name;
ParamByName('vorname').Value := self.Vorname;
ParamByName('id').Value := self.Id;
end;
self.SqlQuery.ExecSQL;
end;
if self.SqlQuery.RowsAffected = 1 then
begin
result := true;
self.DatenEinlesen(self.Id);
end;
end
else
raise Exception.Create('Benutzername bereits vergeben!');
end;
constructor TBenutzer.Create(login, Md5Passwort, Md5Salt, name, Vorname: string;
Connection: TFDConnection);
begin
self.Id := 0;
self.login := login;
self.Md5Passwort := Md5Passwort;
self.Md5Salt := Md5Salt;
self.name := name;
self.Vorname := Vorname;
self.SqlQuery := TFDQuery.Create(nil);
self.SqlQuery.Connection := Connection;
end;
constructor TBenutzer.CreateFromId(Id: integer; Connection: TFDConnection);
begin
self.SqlQuery := TFDQuery.Create(nil);
self.SqlQuery.Connection := Connection;
DatenEinlesen(Id);
end;
procedure TBenutzer.DatenEinlesen(Id: integer);
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE Id = :id');
ParamByName('id').Value := Id;
end;
self.SqlQuery.Open;
if self.SqlQuery.RecordCount = 1 then
begin
self.Id := self.SqlQuery.FieldByName('Id').AsInteger;
self.login := self.SqlQuery.FieldByName('Login').AsString;
self.Md5Passwort := self.SqlQuery.FieldByName('Md5Passwort').AsString;
self.Md5Salt := self.SqlQuery.FieldByName('Md5Salt').AsString;
self.name := self.SqlQuery.FieldByName('Name').AsString;
self.Vorname := self.SqlQuery.FieldByName('Vorname').AsString;
end;
self.SqlQuery.Close;
end;
function TBenutzer.istAnmeldeNameFrei(login: string; neuerNutzer: boolean): boolean;
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('SELECT * FROM ' + self.TABLE_NAME + ' WHERE login = :login');
ParamByName('login').Value := login;
if not neuerNutzer then
begin
Add('AND NOT Id = :id');
ParamByName('id').Value := self.Id;
end;
end;
self.SqlQuery.Open();
if self.SqlQuery.RecordCount = 0 then
result := true
else
result := false;
end;
function TBenutzer.Loeschen: boolean;
begin
result := false;
if self.Id <> 0 then
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('DELETE FROM ' + self.TABLE_NAME + ' WHERE Id = :id');
ParamByName('id').Value := self.Id;
end;
self.SqlQuery.ExecSQL;
end;
if self.SqlQuery.RowsAffected = 1 then
result := true;
end;
procedure TBenutzer.setMd5Passwort(hash: string);
begin
if Length(hash) = 32 then
self.FMd5Passwort := hash
else
raise Exception.Create('Beim setzen des Passworts ist ein Fehler aufgetreten. (Passwort-Hash zu kurz)');
end;
procedure TBenutzer.setMd5Salt(salt: string);
begin
if Length(salt) = 32 then
self.FMd5Salt := salt
else
raise Exception.Create('Beim setzen des Passworts ist ein Fehler aufgetreten. (Passwort-Salt zu kurz)');
end;
function TBenutzer.Speichern;
begin
result := false;
if self.Id = 0 then
begin
if istAnmeldeNameFrei(self.login, true) then
begin
with self.SqlQuery, SQL do
begin
Clear;
Add('INSERT INTO ' + self.TABLE_NAME + ' (Login, Md5Passwort, Md5Salt, Name, Vorname)');
Add('VALUES (:login, :pw, :salt, :name, :vorname)');
ParamByName('login').Value := self.login;
ParamByName('pw').Value := self.Md5Passwort;
ParamByName('salt').Value := self.Md5Salt;
ParamByName('name').Value := self.name;
ParamByName('vorname').Value := self.Vorname
end;
self.SqlQuery.ExecSQL;
self.IdErmitteln;
if self.SqlQuery.RowsAffected = 1 then
result := true;
end
else
raise Exception.Create('Benutzername bereits vergeben!');
end
else
result := self.Aktualisieren;
end;
{ TBenutzerVerwaltung }
procedure TBenutzerVerwaltung.BenutzerSuchen(Suchbegriff: string; Connection: TFDConnection);
var
I : integer;
BenutzerId: integer;
Benutzer : TBenutzer;
begin
with self.SqlQuery, SQL do
begin
Close;
Clear;
Add('SELECT Id FROM ' + self.TABLE_NAME);
Add('WHERE Name = :input');
Add(' OR Vorname = : input');
Add(' OR Vorname + '' '' + Name = :input');
ParamByName('input').Value := Suchbegriff;
Open;
end;
for I := 0 to self.SqlQuery.RecordCount do
begin
BenutzerId := self.SqlQuery.FieldByName('Id').AsInteger;
Benutzer := TBenutzer.CreateFromId(BenutzerId, Connection);
self.BenutzerListe.Add(Benutzer);
Benutzer.Free;
end;
end;
constructor TBenutzerVerwaltung.Create(Connection: TFDConnection);
begin
self.BenutzerListe := TList<TBenutzer>.Create;
end;
end.
|
unit nxNetwork;
{
Uses Synapse library
http://www.ararat.cz/synapse/doku.php
}
interface
uses {$IFDEF UNIX}cthreads,{$ENDIF}
Classes, SysUtils, synsock, blcksock;
const
ExitCode = '#End#';
UDPInit = '#UDPInit#';
type
TConnection = class;
TConnectionEvent = (ceConnected, ceDisconnected, ceError, ceJoined,
ceLeft, ceListening, ceNewSocket, ceAuthOK, ceAuthFail, ceDebug,
ceExitCode);
TConnectionOnEvent = procedure(Sender: TConnection; event: TConnectionEvent;
ID: integer) of object;
TConnectionOnData = procedure(Sender: TConnection; Data:
{$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF}; size, ID: integer)
of object;
{ TClientThread }
TClientThread = class(TThread)
private
Conn: TConnection;
public
freeSocket: boolean;
constructor Create(_conn: TConnection);
procedure Execute; override;
end;
{ TServerThread }
TServerThread = class(TThread)
private
Conn: TConnection;
public
freeSocket: boolean;
constructor Create(_conn: TConnection);
procedure Execute; override;
end;
{ TServerSubThread }
TServerSubThread = class(TThread)
private
Conn: TConnection;
sock: TSocket;
index: integer;
Opened: boolean;
public
tcpSock: TTCPBlockSocket;
ID: integer;
constructor Create(_conn: TConnection; _sock: TSocket; _index, _ID: integer);
procedure Execute; override;
end;
TConnectionOnCrypt = procedure(const Data: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer; decrypt: boolean) of object;
{ TConnection }
TConnection = class
clients: array of TServerSubThread;
private
FHost, FPort, FMyIP, FLastErrorMsg, FMask, FKey: string;
FTCP, FServer, FConnected, FOpened: boolean;
FClients, FClientsMax, FLastError, FClientID: integer;
tcpSock: TTCPBlockSocket;
udpSock: TUDPBlockSocket;
serverThread: TServerThread;
clientThread: TClientThread;
procedure doClose(index: integer);
procedure doConnect(ID: integer);
procedure doData(ID: integer; Data: string; size: integer);
procedure doError(Error: integer; Msg: string; ID: integer);
procedure SetClients(n: integer);
function getUDP: boolean;
function getIsClient: boolean;
function NewClientID: integer;
procedure SetMask(s: string);
procedure SetConnected(enable: boolean);
public
onCrypt: TConnectionOnCrypt;
onData: TConnectionOnData;
onEvent: TConnectionOnEvent;
property Mask: string Read FKey Write SetMask;
property LastError: integer Read FLastError;
property LastErrorMsg: string Read FLastErrorMsg;
property Connected: boolean Read FConnected write SetConnected;
property Count: integer Read FClients;
property Host: string Read FHost write FHost;
property MyIP: string Read FMyIP;
property Port: string Read FPort write FPort;
property Opened: boolean Read FOpened;
property Server: boolean Read FServer;
property Client: boolean Read getIsClient;
property TCP: boolean Read FTCP;
property UDP: boolean Read GetUDP;
destructor Destroy; override;
function Connect: boolean;
procedure Disconnect;
function EventToStr(event: TConnectionEvent): string;
procedure MaskCrypt(p: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer);
end;
TServer = class(TConnection)
public
MaxConnections: integer;
procedure Kick(index: integer);
end;
{ TTCPServer }
TTCPServer = class(TServer)
public
constructor CreateTCPServer(_port: string);
procedure Send(toID: integer; p: {$IFDEF fpc}PByte
{$ELSE}PByteArray{$ENDIF}; size: integer);
procedure SendString(toID: integer; s: string);
end;
{ TUDPServer }
TUDPServer = class(TServer)
public
constructor CreateUDPServer(_port: string);
procedure Send(p: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer);
procedure SendString(s: string);
end;
TClient = class(TConnection)
public
constructor CreateTCPClient(_host, _port: string);
constructor CreateUDPClient(_host, _port: string);
procedure Send(p: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer);
procedure SendString(s: string);
end;
var
ServerThreads: integer = 0;
ClientThreads: integer = 0;
implementation
uses Math;
function Pow2fit(n: integer): integer;
var neg: boolean;
begin
if n<0 then begin
n :=-n; neg := True;
end else neg := False;
if n<3 then Result := n
else Result := round(intpower(2, ceil(log2(n))));
if neg then Result :=-Result;
end;
{ TServer }
procedure TServer.Kick(index: integer);
begin
doClose(index);
end;
function TConnection.Connect: boolean;
begin
Connect := False;
if Connected then exit;
if server and (ServerThreads>0) then exit;
if client and (ClientThreads>0) then exit;
FConnected := False; FOpened := False;
if tcp and Server then tcpSock.Bind(FHost, FPort)
else if udp and Server then begin
udpSock.Bind(FHost, FPort);
end else if tcp and Client then tcpSock.Connect(FHost, FPort)
else if udp and Client then udpSock.Connect(FHost, FPort);
if Server then begin
if tcp and (tcpSock.LastError<>0) then begin
doError(tcpSock.LastError, tcpSock.LastErrorDesc,-1);
doClose(-1); exit;
end else if udp and (udpSock.LastError<>0) then begin
doError(udpSock.LastError, udpSock.LastErrorDesc,-1);
doClose(-1); exit;
end else if tcp then tcpSock.Listen;
end;
if tcp and (tcpSock.LastError<>0) then begin
doError(tcpSock.LastError, tcpSock.LastErrorDesc,-1);
doClose(-1); exit;
end else if udp and (udpSock.LastError<>0) then begin
doError(tcpSock.LastError, tcpSock.LastErrorDesc,-1);
doClose(-1); exit;
end;
FConnected := True;
if server then begin
serverThread := TServerThread.Create(self);
if assigned(onEvent) then onEvent(self, ceListening,-1);
end else begin
if assigned(onEvent) then onEvent(self, ceConnected,-1);
clientThread := TClientThread.Create(self);
end;
Connect := True;
end;
destructor TConnection.Destroy;
var i: integer;
begin
onEvent := nil; onData := nil; onCrypt := nil;
FConnected := False;
if server then begin
for i := Count-1 downto 0 do
if clients[i]<>nil then begin
clients[i].Terminate; clients[i].Conn := nil;
clients[i] := nil;
end;
FClients := 0; Setlength(clients, 0);
if serverThread = nil then begin
if tcpSock<>nil then tcpSock.Free;
if udpSock<>nil then udpSock.Free;
end else begin
serverThread.freeSocket := True; serverThread.Terminate;
serverThread.Conn := nil; serverThread := nil;
if tcpSock<>nil then tcpSock.AbortSocket;
end;
end else begin // If client
if clientThread = nil then begin
if tcpSock<>nil then tcpSock.Free;
if udpSock<>nil then udpSock.Free;
end else begin
clientThread.freeSocket := True; clientThread.Terminate;
clientThread.Conn:=nil; clientThread:=nil;
end;
end;
tcpSock := nil; udpSock := nil;
inherited;
end;
procedure TConnection.Disconnect;
begin
if connected then doClose(-1);
end;
function TConnection.EventToStr(event: TConnectionEvent): string;
begin
case event of
ceAuthFail: EventToStr := 'Authentication Failed';
ceAuthOK: EventToStr := 'Authentication OK';
ceConnected: EventToStr := 'Connected';
ceDebug: EventToStr := 'Debug event';
ceDisconnected: EventToStr := 'Disconnected';
ceError: EventToStr := 'Error';
ceExitCode: EventToStr := 'Exit code';
ceJoined: EventToStr := 'Client joined';
ceLeft: EventToStr := 'Socket closed';
ceListening: EventToStr := 'Listening';
ceNewSocket: EventToStr := 'Opened new socket';
else EventToStr := 'Unknown event';
end;
end;
procedure TConnection.doClose(index: integer);
var i: integer;
begin
if index<0 then begin // Disconnect
FConnected := False; FOpened := False;
if serverThread<>nil then begin
for i := Count-1 downto 0 do
if clients[i]<>nil then begin
clients[i].Terminate; clients[i] := nil;
end;
serverThread.Terminate; serverThread := nil;
FClients := 0; FClientsMax := 0; Setlength(clients, 0);
if tcpSock<>nil then tcpSock.AbortSocket;
end;
if clientThread<>nil then begin
clientThread.Terminate; clientThread := nil;
end;
end else if server and (Count>0) then begin
// Client left
if Clients[index]<>nil then begin
Clients[index].Terminate;
end;
Clients[index] := Clients[Count-1];
Clients[index].index := index; SetClients(Count-1);
if Count<= 0 then FOpened := False;
end;
end;
procedure TConnection.doConnect(ID: integer);
begin
if server then begin
if ID>=0 then begin
if assigned(onEvent) then onEvent(self, ceJoined, ID);
end else if assigned(onEvent) then
onEvent(self, ceConnected, ID);
end;
end;
procedure TConnection.doData(ID: integer; Data: string; size: integer);
begin
MaskCrypt(@Data[1], size);
if assigned(onCrypt) then onCrypt(@Data[1], size, True);
if assigned(onData) then onData(self, @Data[1], size, ID);
end;
procedure TConnection.doError(Error: integer; Msg: string; ID: integer);
begin
FLastError := Error; FLastErrorMsg := Msg;
if assigned(onEvent) then onEvent(self, ceError, ID);
end;
procedure TConnection.MaskCrypt(p: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer);
var i, l: integer;
begin
l := length(FMask);
if l<1 then exit;
for i := 0 to size-1 do p[i] := p[i] xor byte(FMask[(i mod l)+1]);
end;
function TConnection.NewClientID: integer;
var i: integer; accept: boolean;
begin
repeat
accept := True; FClientID := FClientID+1;
if FClientID<0 then FClientID := 0;
for i := 0 to Count-1 do
if FClientID = Clients[i].ID then begin
accept := False; FClientID := FClientID+1;
if FClientID<0 then FClientID := 0;
end;
until accept;
NewClientID := FClientID;
end;
procedure TConnection.SetMask(s: string);
var i, l, l2: integer; n: integer;
begin
FKey := s; l := length(s);
if l>0 then begin
l2 := l;
if l2<64 then l2 := 64;
setlength(FMask, l2);
for i := 1 to l2 do begin
n := byte(s[1+(i-1) mod l]); n := (n+i*59) mod 256;
FMask[i] := char(byte(n));
end;
end else FMask := s;
end;
procedure TConnection.SetConnected(enable: boolean);
begin
if enable then Connect
else Disconnect;
end;
procedure TConnection.SetClients(n: integer);
begin
FClients := n; n := pow2fit(n);
if n<>FClientsMax then begin
FClientsMax := n; setlength(clients, FClientsMax);
end;
end;
function TConnection.getUDP: boolean;
begin
getUDP := not FTCP;
end;
function TConnection.getIsClient: boolean;
begin
getIsClient := not FServer;
end;
{ TClientThread }
constructor TClientThread.Create(_conn: TConnection);
begin
inherited Create(False); Conn := _conn; Inc(ClientThreads);
FreeOnTerminate := True;
end;
procedure TClientThread.Execute;
var err: integer; errDesc: string; _tcpSock: TTCPBlockSocket;
_udpSock: TUDPBlockSocket; _TCP: boolean;
procedure getError;
begin
if _TCP then begin
err := _tcpSock.LastError; errDesc := _tcpSock.LastErrorDesc;
end else begin
err := _udpSock.LastError; errDesc := _udpSock.LastErrorDesc;
end;
end;
var s: string; l, n: integer;
begin
_TCP:=conn.TCP; _tcpSock:=conn.tcpSock; _udpSock:=conn.udpSock;
try
// Authentication (TCP only)
if (not Terminated) and _TCP then begin
//n := length(conn.mask);
//if n<64 then
n := 64;
setlength(s, n); // receive masked string
_tcpSock.RecvBufferEx(@s[1], n, 2000);
//s:=_tcpSock.RecvBlock(2000);
setlength(s, n);
if conn = nil then Terminate;
if not Terminated then begin
getError;
if err<>0 then begin
conn.doError(err, errDesc,-1); Terminate;
end else begin
conn.MaskCrypt(@s[1], n); // Unmask string
// Send unmasked string and wait for reply
_tcpSock.SendBuffer(@s[1], n);
//s:=_tcpSock.RecvString(2000);
s := _tcpSock.RecvBlock(2000); // Wait for 'Accepted'
if conn = nil then Terminate;
if not Terminated then begin
getError;
if err<>0 then begin
conn.doError(err, errDesc,-1); Terminate;
end else if s<>'Accepted' then Terminate;
end;
end;
end;
if (conn<>nil) and assigned(conn.onEvent) then
if terminated then conn.onEvent(conn, ceAuthFail,-1)
else conn.onEvent(conn, ceAuthOk,-1);
// UDP start
end else if (not Terminated) and (not _TCP) then begin
// UDP sends init string to let server know about new connection
// This also checks if connection is possible
_udpSock.SendString(UDPInit); getError;
if err<>0 then begin
if conn<>nil then conn.doError(err, errDesc,-1);
Terminate;
end;
end;
if (not terminated) and (conn<>nil) then conn.FOpened := True;
while not Terminated do begin
if _TCP then s := _tcpSock.RecvBlock(1000)
else s := _udpSock.RecvBlock(1000); // Receive data
if conn = nil then Terminate;
getError;
if (err<>0) and (err<>WSAETIMEDOUT) then begin
if conn<>nil then
conn.doError(err, errDesc,-1);
break;
end;
if terminated then begin
if _TCP then begin
_tcpSock.SendInteger(length(ExitCode));
_tcpSock.SendString(ExitCode); //_tcpSock.RecvByte(1000);
end else begin
_udpSock.SendInteger(length(ExitCode));
_udpSock.SendString(ExitCode); //_udpSock.RecvByte(1000);
end;
break;
end else begin
if s = ExitCode then begin
//if _TCP then _tcpSock.SendByte(1)
//else _udpSock.SendByte(1);
Terminate;
if (conn<>nil) and assigned(conn.onEvent) then
conn.onEvent(conn, ceExitCode,-1); break;
end else if conn<>nil then begin
l := length(s);
if l>0 then conn.doData(-1, s, l); // Handle data
end;
end;
end; // while
finally
if _tcp then _tcpSock.CloseSocket
else _udpSock.CloseSocket;
if freeSocket then begin
if _tcp then _tcpSock.Free
else _udpSock.Free;
end else if conn<>nil then begin
conn.FOpened := False;
if _tcp then _tcpSock.CloseSocket
else _udpSock.CloseSocket;
if conn.Connected then conn.doClose(-1);
end;
end;
if (conn<>nil) and assigned(conn.onEvent) then
conn.onEvent(conn, ceDisconnected,-1);
_tcpSock := nil; _udpSock := nil; conn := nil; Dec(ClientThreads);
end;
{ TServerThread }
constructor TServerThread.Create(_conn: TConnection);
begin
inherited Create(False); Conn := _conn; conn.FClientID := 0;
FreeOnTerminate := True; Inc(ServerThreads);
end;
procedure TServerThread.Execute;
var ClientSock: TSocket; n, l, newid: integer;
_tcpSock: TTCPBlockSocket; _udpSock: TUDPBlockSocket;
_tcp,_opened: boolean; s: string;
begin
_tcp := conn.TCP; _tcpSock := conn.tcpSock;
_udpSock := conn.udpSock; _opened:=conn.Opened;
try
while not Terminated do begin
if conn = nil then Terminate;
if _TCP then begin
// *** TCP Server ***
with _tcpSock do begin
ClientSock := accept; // Wait for new connections
if (conn = nil) or (not conn.Connected) then Terminate;
if not Terminated then
if lastError = 0 then begin
if conn.count<TServer(conn).MaxConnections then begin
newID := conn.NewClientID; n := conn.Count;
conn.SetClients(conn.Count+1);
conn.Clients[n] := TServerSubThread.Create(conn, ClientSock, n, newID);
conn.FOpened := True; _opened:=True;
end else
sleep(1000);
end else begin
if conn<>nil then
conn.doError(LastError, LastErrorDesc,-1);
Terminate;
end;
end;
end else // *** UDP Server ***
with _udpSock do begin
s := RecvBlock(1000); // Receive data
if conn = nil then Terminate;
if lastError = WSAETIMEDOUT then begin // Timed out
//if conn <> nil then conn.doError(LastError, LastErrorDesc, -1);
end else if lastError<>0 then begin
if conn<>nil then
conn.doError(LastError, LastErrorDesc,-1);
break; // Disconnect
end;
if not terminated then begin
if s = ExitCode then begin
//SendByte(1);
if conn<>nil then begin
conn.FOpened := False; _opened:=false;
if assigned(conn.onEvent) then
conn.onEvent(conn, ceExitCode,-1);
end;
end else begin
l := length(s);
if (l>0) and (conn<>nil) then begin
conn.FOpened := True; _opened:=true;
if s<>UDPInit then
conn.doData(-1, s, l) // Handle data
else if assigned(conn.onEvent) then
conn.onEvent(conn, ceAuthOk,-1);
end;
end;
end else begin
// Terminated
if _opened then begin
SendInteger(length(ExitCode));
SendString(ExitCode); //RecvByte(1000);
end;
break;
end;
end;
end;
if freeSocket then begin
if _tcp then _tcpSock.Free
else _udpSock.Free;
end else begin
if _tcp then _tcpSock.CloseSocket
else _udpSock.CloseSocket;
if (conn<>nil) and conn.connected then
conn.doClose(-1);
end;
finally
Dec(ServerThreads);
end;
if (conn<>nil) and assigned(conn.onEvent) and (ServerThreads=0) then
conn.onEvent(conn, ceDisconnected,-1); conn := nil;
end;
{ TServerSubThread }
constructor TServerSubThread.Create(_conn: TConnection; _sock: TSocket;
_index, _ID: integer);
begin
inherited Create(False); Conn := _conn; sock := _sock;
index := _index; ID := _ID; Opened := False;
if Conn.TCP then tcpSock := TTCPBlockSocket.Create;
FreeOnTerminate := True; Inc(ServerThreads);
end;
procedure TServerSubThread.Execute;
var s, s2: string; i, l, n: integer;
begin
tcpSock := TTCPBlockSocket.Create;
try
if (not Terminated) and (conn<>nil) then begin
tcpSock.socket := Sock; tcpsock.GetSins;
if assigned(conn.onEvent) then
conn.onEvent(conn, ceNewSocket, ID);
with tcpSock do begin
// Authenticate
//n := length(conn.mask);
//if n<64 then
n := 64;
setlength(s, n); setlength(s2, n);
for i := 1 to n do s2[i] := chr(random(95)+32);
s := copy(s2,1,n); // Keep original string for comparison later
conn.MaskCrypt(@s[1], n); // Mask string
SendBuffer(@s[1], n); // Send masked string
RecvBufferEx(@s[1], n, 2000); // Receive it unmasked
setlength(s, n);
if not Terminated then
if lastError<>0 then begin
conn.doError(LastError, LastErrorDesc, ID);
Terminate;
end else if s<>s2 then begin
// Authentication failed
if assigned(conn.onEvent) then
conn.onEvent(conn, ceAuthFail, ID);
Terminate;
end else begin
// if sent and received string match
if conn = nil then Terminate
else if not Terminated then begin
SendBlock('Accepted');
if assigned(conn.onEvent) then
conn.onEvent(conn, ceAuthOk, ID);
Opened:=True; conn.doConnect(ID);
end;
// Start listening socket
while not Terminated do begin
s := RecvBlock(1000); // Receive data
if conn = nil then Terminate;
if lastError = WSAETIMEDOUT then begin // Timed out
//if conn <> nil then conn.doError(LastError, LastErrorDesc, ID);
end else if lastError<>0 then begin
if conn<>nil then
conn.doError(LastError, LastErrorDesc, ID);
break; // Disconnect
end;
if not terminated then begin
if s = ExitCode then begin
//SendByte(1);
Terminate;
if (conn<>nil) and assigned(conn.onEvent) then
conn.onEvent(conn, ceExitCode, ID); break;
end else begin
l := length(s);
if l>0 then conn.doData(ID, s, l); // Handle data
end;
end else begin // Terminated
SendInteger(length(ExitCode));
SendString(ExitCode); //RecvByte(1000);
break;
end;
end;
end;
end;
end;
finally
tcpSock.Free; tcpSock := nil; Opened := False;
end;
if conn<>nil then begin
if assigned(conn.onEvent) then conn.onEvent(conn, ceLeft, ID);
if conn.Connected then conn.doClose(index);
end;
Dec(ServerThreads);
if (conn<>nil) and assigned(conn.onEvent) and (ServerThreads=0) then
conn.onEvent(conn, ceDisconnected,-1); conn := nil;
end;
{ TUDPServer }
constructor TUDPServer.CreateUDPServer(_port: string);
begin
FTCP := False; FServer := True; udpSock := TUDPBlockSocket.Create;
FHost := '0.0.0.0'; FPort := _port; FClientID := 0;
MaxConnections:=64;
//FMyIP := udpSock.GetLocalSinIP;
end;
procedure TUDPServer.Send(p: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer);
begin
if client or (not connected) or (not opened) then exit;
if assigned(onCrypt) then onCrypt(p, size, False);
MaskCrypt(p, size);
if udp then
with udpSock do begin
SendInteger(size);
SendBuffer(p, size);
if LastError<>0 then doError(LastError, LastErrorDesc,-1);
end;
MaskCrypt(p, size);
end;
procedure TUDPServer.SendString(s: string);
var l: integer;
begin
if client or (not connected) or (not opened) then exit;
l := length(s);
if assigned(onCrypt) then onCrypt(@s[1], l, False);
MaskCrypt(@s[1], l);
if udp then
with udpSock do begin
SendInteger(l);
SendBuffer(@s[1], l);
if LastError<>0 then doError(LastError, LastErrorDesc,-1);
end;
end;
{ TTCPServer }
constructor TTCPServer.CreateTCPServer(_port: string);
begin
FTCP := True; FServer := True; tcpSock := TTCPBlockSocket.Create;
FHost := '0.0.0.0'; FPort := _port; FClientID := 0;
MaxConnections:=64;
//FMyIP := tcpSock.GetLocalSinIP;
end;
procedure TTCPServer.Send(toID: integer; p: {$IFDEF fpc}PByte
{$ELSE}PByteArray{$ENDIF}; size: integer);
var i: integer;
begin
if (not connected) or client then exit;
if assigned(onCrypt) then onCrypt(p, size, False);
MaskCrypt(p, size);
for i := Count-1 downto 0 do
if (clients[i].ID = toID) or (toID<0) then
if (clients[i].tcpSock<>nil) and clients[i].Opened then
with clients[i].tcpSock do begin
SendInteger(size);
SendBuffer(p, size);
if LastError<>0 then begin
doError(LastError, LastErrorDesc, Clients[i].ID);
clients[i].Terminate; doClose(i);
end;
end;
MaskCrypt(p, size);
end;
procedure TTCPServer.SendString(toID: integer; s: string);
var i, l: integer;
begin
if (not connected) or client then exit;
l := length(s);
if assigned(onCrypt) then onCrypt(@s[1], l, False);
MaskCrypt(@s[1], l);
for i := Count-1 downto 0 do
if (clients[i].ID=toID) or (toID<0) then
if clients[i].opened then
with clients[i].tcpSock do begin
SendInteger(l);
SendBuffer(@s[1], l);
if LastError<>0 then begin
doError(LastError, LastErrorDesc, Clients[i].ID);
clients[i].Terminate; doClose(i);
end;
end;
end;
{ TClient }
constructor TClient.CreateTCPClient(_host, _port: string);
begin
FTCP := True; FServer := False; tcpSock := TTCPBlockSocket.Create;
FHost := _host; FPort := _port;
FMyIP := tcpSock.GetLocalSinIP;
end;
constructor TClient.CreateUDPClient(_host, _port: string);
begin
FTCP := False; FServer := False; udpSock := TUDPBlockSocket.Create;
FHost := _host; FPort := _port;
//FMyIP := udpSock.GetLocalSinIP;
end;
procedure TClient.Send(p: {$IFDEF fpc}PByte{$ELSE}PByteArray{$ENDIF};
size: integer);
begin
if server or (not connected) or (not opened) then exit;
if assigned(onCrypt) then onCrypt(p, size, False);
MaskCrypt(p, size);
if tcp then begin
tcpsock.SendInteger(size);
tcpSock.SendBuffer(p, size);
if tcpSock.LastError<>0 then begin
doError(tcpSock.LastError, tcpSock.LastErrorDesc,-1);
doClose(-1);
end;
end else begin
udpsock.SendInteger(size);
udpsock.SendBuffer(p, size);
if udpSock.LastError<>0 then begin
doError(udpSock.LastError, udpSock.LastErrorDesc,-1);
doClose(-1);
end;
end;
MaskCrypt(p, size);
end;
procedure TClient.SendString(s: string);
var l: integer;
begin
if server or (not connected) or (not opened) then exit;
l := length(s);
if assigned(onCrypt) then onCrypt(@s[1], l, False);
MaskCrypt(@s[1], l);
if tcp then begin
tcpsock.SendInteger(l);
tcpSock.SendBuffer(@s[1], l);
if tcpSock.LastError<>0 then begin
doError(tcpSock.LastError, tcpSock.LastErrorDesc,-1);
doClose(-1);
end;
end else begin
udpsock.SendInteger(l);
udpsock.SendBuffer(@s[1], l);
if udpSock.LastError<>0 then begin
doError(udpSock.LastError, udpSock.LastErrorDesc,-1);
doClose(-1);
end;
end;
end;
end.
|
Unit revhard;
interface
const
DESQviewActive : boolean = false; { true if running under DESQview }
DESQviewMajor : byte = 0;
DESQviewMinor : byte = 0;
Type
CpuType = ( cpu8088,cpu8086,cpu80286,cpu80386,
cpu80486,cpuPentium,cpuFuture);
CpuStrType = String[7];
Const
CpuTypeIdentified : Boolean = False;
Var
ConfirmedCpuType : CpuType;
Procedure HardWareInit;
Procedure ComputerModel(var comp:string);
procedure biosdate(var date:string); {Returns the bios date}
Procedure pci(var pcis:string); {Tells if there is a PCI board}
Procedure detectfpu(var co:string); {Detects a coprocessor, not 100% reliable
Returns true if found, false if not found}
Procedure detectgame(var joy:string); {Tells if there is a game card or joystick port
Returns TRUE if found}
function xms:boolean; {Tells if there is an extended memory manager
Returns true if found}
function emm:boolean; {Tells if there is an expanded memory manager, EMM386
Returns TRUE if found (not tested with QEMM) }
procedure svga(var svg:string); {Checks for a VESA compliant card}
function cdrom:boolean;{Tells if MSCDEX is loaded (and consequently if there is
a CD-ROM drive. Returns TRUE if found}
procedure _4dos(var strr:string){Tells us if 4DOS.COM is loaded and its version};
Function WhichCPU : CpuType;
Function GetCpuType : CpuType;
Procedure IdentifyCpuType;
Function GetCpuTypeStr : CpuStrType;
Procedure show_ram(var b,e:word);
Function detectDESQview:boolean;
function dosemu_Detect:boolean;
implementation
uses crt,dos,revansi,revconst,revdat,revwin,detectso,revgfx;
{$L CPU.OBJ}
{$F+}
Function WhichCPU : CpuType;
{ Determines and returns the currently executing CPU type }
EXTERNAL;
{$F-}
Procedure HardWareInit;
var strr:string;
size,b,e:word;
var regs : registers;
procedure id_version;
begin
regs.ah := $30;
msdos( regs);
end;
begin
extractpointerfromdat(config^.init,hard_file,tempbin,size);
DisplayAnsiPointer(tempbin);
textcolor(darkgray);
textbackground(green);
gotoxy(11,2);write('Relativity Emags Viewer - ');
gotoxy(62,2);write(compile_date);
textcolor(lightgreen);
textbackground(darkgray);
gotoxy(66,20);write(compile_date);
gotoxy(52,21);write(year_now);
textcolor(darkgray);
textbackground(green);
strr:='';computermodel(strr);gotoxy(26,4);write(strr);
strr:='';biosdate(strr);gotoxy(26,5);write('[',strr,']');
gotoxy(26,6);write('Rad Engine');
gotoxy(26,7);
if DetSoundBlaster then write('Sound Blaster Detected')
else write('Nothing Detected');
if voc then
begin
gotoxy(26,8);write('Wave Output Detected');
end
else
begin
gotoxy(26,8);write('Output Not Detected');
end;
gotoxy(26,9);write('Adlib');
strr:='';gotoxy(26,10);write(GetCpuTypeStr);strr:='';detectFpu(strr);write(', ',strr);
show_ram(b,e);gotoxy(26,11);write(b,'K');
if xms then begin
gotoxy(26,13);write('True, ',E,'K');
end else begin
gotoxy(26,13);write('False');
end;
if emm then begin
gotoxy(26,12);write('True');
end else begin
gotoxy(26,12);write('False');
end;
strr:='';gotoxy(26,14);Write(disksize(0) div 1024,' Kbytes Avail. ', DiskFree(0) div 1024, ' Kbytes free.');
strr:='';Pci(strr);gotoxy(26,15);write(strr);
if dosemu_Detect then
begin
gotoxy(26,18);write('Dosemu Detected, Running Under Linux');
end
else
begin
if Win3X then
begin
gotoxy(26,18);write('Windows, Version : ',lo(winver),'.',hi(winver));
end
else
begin
id_version;
gotoxy(26,18);write('Dos Version : ',regs.al,'.');
IF ( regs.ah < 10 ) THEN write( '0' );
write( regs.ah );
end;
end;
gotoxy(26,16);
strr:='';
svga(strr);
write(strr);
{if vga then str:='80x25 Text Mode, Vga 640x480'
else str:='80x25 Text Mode'; write(str);}
gotoxy(26,17);write(config^.font[config^.curfnt]);
gotoxy(26,19);strr:='';
detectDESQview;
_4dos(strr);write(strr);
gotoxy(26,20);
if cdrom then
write('Detected')
else write('Not Found');
gotoxy(26,21);strr:='';
detectgame(strr);write(strr);
gotoxy(26,22);
write(config^.radcurmus,': ',config^.music[config^.radcurmus,1]);
gotoxy(26,23);
if detectDESQview then write('DesqView Detected V',DESQviewMajor,'.',DESQviewMinor)
else write('Not Detected');
hidecursor;
readkey;
end;
function dosemu_Detect:boolean; assembler;
asm
push ds
{ check for the BIOS date }
mov ax,$F000
mov ds,ax
mov bx,$FFF5
mov ax,'20'
cmp word ptr [bx],'20'
jne @no_dosemu
cmp word ptr [bx+2],'2/'
jne @no_dosemu
cmp word ptr [bx+4],'/5'
jne @no_dosemu
cmp word ptr [bx+6],'39'
jne @no_dosemu
{ initialize interrupt $E6 to an IRET }
xor ax,ax
mov ds,ax
mov bx,$E6 * 4
les di,[bx]
mov bl,es:[di]
mov byte ptr es:[di],$CF { put an iret instruction }
{ call the installation check interrupt (int $E6 with ah = 0) }
xor ah,ah
int $E6
mov es:[di],bl { restore the old instruction }
cmp ax,$AA55
jne @no_dosemu
mov ax,01h
jmp @end
@no_dosemu:
xor ax,ax
@end:
pop ds
end;
Function detectDESQview:boolean;
var regs:registers;
begin
regs.cx := $4445;
regs.dx := $5351; { date cx = DE, dx = SQ }
regs.ax := $2B01; { dos set date function }
msdos(regs);
if (regs.al = $ff) then
detectDESQview:= false { if dos detected an error, no DV active }
else begin
detectDESQview:= true;
DESQviewMajor := regs.bh;
DESQviewMinor := regs.bl;
end;
end; {detectDESQview}
Procedure show_ram(var b,e:word);
const
int15: longint = $f000f859;
var
baseram,extram: word;
begin
asm
int 12h
mov baseram,ax
mov ah,88h
pushf
call int15
mov extram,ax
end;
B:=baseram;
e:=extram;
end;
Procedure IdentifyCpuType;
{ Handles initialization of CPU type }
Begin
If Not CpuTypeIdentified Then
Begin
ConfirmedCpuType := WhichCPU;
CpuTypeIdentified := True;
End;
End; { Procedure IdentifyCpuType }
Function GetCpuType : CpuType;
{ Returns the currently executing CPU type }
Begin
IdentifyCpuType;
GetCpuType := ConfirmedCpuType;
End; { Function GetCpuType }
Function GetCpuTypeStr : CpuStrType;
{ Returns the currently executing CPU type as a string }
Begin
IdentifyCpuType;
Case ConfirmedCpuType Of
cpu8088 : GetCpuTypeStr := '8088';
cpu8086 : GetCpuTypeStr := '8086';
cpu80286 : GetCpuTypeStr := '80286';
cpu80386 : GetCpuTypeStr := '80386';
cpu80486 : GetCpuTypeStr := '80486';
cpuPentium : GetCpuTypeStr := 'Pentium';
cpuFuture : GetCpuTypeStr := 'Future';
End; { Case }
End; { Function GetCpuTypeStr }
procedure biosdate(var date:string); {Returns the bios date}
var
l:byte;
c:char;
begin
for l:=1 to 8 do begin
c:=chr(mem[$f000:$fff4+l]);
date:=date+c;
end;
end;
Procedure pci(var pcis:string); {Tells if there is a PCI board Returns TRUE if found}
function ispci:byte;assembler;asm
mov ax,0b101h
int 01ah
mov al,ah
end;
begin
if ispci=0 then
pcis:='PCI board found'
else pcis:='No PCI board found';
end;
Procedure detectfpu(var co:string); {Detects a coprocessor, not 100% reliable
Returns true if found, false if not found}
var
val: byte;
begin
val:= mem[$0000:$0410];
if val and 2=2 then
co:='Coprocessor Detected'{Check bit 2}
else co:='Coprocessor Not Detected';{Check bit 2}
end;
Procedure detectgame(var joy:string); {Tells if there is a game card or joystick port
Returns TRUE if found}
var
val: byte;
begin
val:= mem[$0000:$0411];
if val and 6=6 then
joy:='Joystick Detected'{Check bit 6}
else joy:='NO Joystick';
end;
function xms:boolean; {Tells if there is an extended memory manager
Returns true if found}
function checkxmm:byte;assembler;asm
mov ax,4300h
int 2fh
end;
begin
if checkxmm=$80 then xms:=true
else xms:=false;
end;
function emm:boolean; {Tells if there is an expanded memory manager, EMM386
Returns TRUE if found (not tested with QEMM) }
var
l: byte;
e: boolean;
const
name:string[8]='EMMXXXX0'; {We have to look in memory for this string}
function addressemm:word;assembler;asm {It returns the segment where
the memory manager resides}
mov ax,3567h
int 21h
mov ax,es
end;
begin
e:=true;
for l:=10 to 17 do begin {This is where the string starts}
if chr(mem[addressemm:l])<>name[l-9] then e:=false; {Compare it}
end;
emm:=e;
end;
procedure svga(var svg:string); {Checks for a VESA compliant card}
var
infoptr: pointer; {Pointer where the cards gives us its info}
infoseg: word;
s,d: word;
i : byte;
fabric: string; {Card's manufacturer name}
Function isvesa:byte;assembler;
asm {Checks if there's a VESA compliant card
and finds where to get allits info}
mov ax,infoseg
mov es,ax
xor di,di
mov ax,4f00h
int 10h
xchg ah,al
end;
var sss,ss:string;
begin
getmem(infoptr,257); {Reserve memory for card's info}
infoseg:=seg(infoptr^);
if isvesa<>0 then
begin
svg:='No VESA card found';
end
else begin
str(mem[infoseg:5],sss);
str(mem[infoseg:4],ss);
svg:='VESA Found, Ver: '+sss+'.'+ss;
d:=memw[infoseg:6];
s:=memw[infoseg:8];
i:=0;
repeat
i:=i+1;
fabric[i]:=chr(mem[s:d+i-1]); {The manufacturer's string is in}
until (mem[s:d+i-1]=0); {ASCIIZ so this ends when 0 found}
fabric[0]:=chr(i);
svg:=svg+', '+fabric;
end;
freemem(infoptr,257); {Free the info area}
end;
function cdrom:boolean;{Tells if MSCDEX is loaded (and consequently if there is
a CD-ROM drive. Returns TRUE if found}
function check:byte;assembler;asm
mov ax,1100h
int 2fh
end;
begin
if check=255 then cdrom:=true
else cdrom:=false;
end;
Procedure _4dos(var strr:string){Tells us if 4DOS.COM is loaded and its version};
function _4check:word;assembler;asm {This checks that is loaded}
mov ax,0d44dh
xor bh,bh
int 2fh
end;
function major:byte;assembler;asm
mov ax,0d44dh
xor bh,bh
int 2fh
mov al,bl
end;
function minor:byte;assembler;asm
mov ax,0d44dh
xor bh,bh
int 2fh
mov al,bh
end;
var ss,s:string;
begin
if _4check=$44dd then
begin
str(major,s);
str(minor,ss);
strr:='Detected Ver:'+s+'.'+ss;
end
else
strr:='4DOS not present';
end;
Procedure ComputerModel(var comp:string);
VAR
Model : BYTE ABSOLUTE $F000:$FFFE;
BEGIN
CASE Model OF
$9A : Comp:=( 'COMPAQ Plus' );
$FF : Comp:=( 'IBM PC' );
$FE : Comp:=( 'PC XT, Portable PC' );
$FD : Comp:=( 'PCjr' );
$FC : Comp:=( 'Personal Computer AT, PS/2 Models 50 and 60' );
$FB : Comp:=( 'PC XT (after 1/10/86)' );
$FA : Comp:=( 'PS/2 Model 30' );
$F9 : Comp:=( 'Convertible PC' );
$F8 : Comp:=( 'PS/2 Model 80' );
End;
end;
Procedure CPUSpeed(var mhz,khz:word);
Function WhatCPU:byte;
Const
Cpu8086 = 1;
Cpu80286 = 2;
Cpu80386 = 3;
Cpu80486 = 4;
begin
Asm { Function WhatCPU }
MOV DX,Cpu8086
PUSH SP
POP AX
CMP SP,AX
JNE @OUT
MOV DX,Cpu80286
PUSHF
POP AX
OR AX,4000h
PUSH AX
POPF
PUSHF
POP AX
TEST AX,4000h
JE @OUT
MOV DX,Cpu80386
DB 66h; MOV BX,SP { MOV EBX,ESP }
DB 66h, 83h, 0E4h, 0FCh { AND ESP,FFFC }
DB 66h; PUSHF { PUSHFD }
DB 66h; POP AX { POP EAX }
DB 66h; MOV CX, AX { MOV ECX,EAX }
DB 66h, 35h, 00h
DB 00h, 04h, 00 { XOR EAX,00040000 }
DB 66h; PUSH AX { PUSH EAX }
DB 66h; POPF { POPFD }
DB 66h; PUSHF { PUSHFD }
DB 66h; POP AX { POP EAX }
DB 66h, 25h,00h
DB 00h, 04h,00h { AND EAX,00040000 }
DB 66h, 81h,0E1h,00h
DB 00h, 04h,00h { AND ECX,00040000 }
DB 66h; CMP AX,CX { CMP EAX,ECX }
JE @Not486
MOV DX, Cpu80486
@Not486:
DB 66h; PUSH CX { PUSH ECX }
DB 66h; POPF { POPFD }
DB 66h; MOV SP, BX { MOV ESP,EBX }
@Out:
MOV AX, DX
End;
end; { Function WhatCPU }
Const
Processor_cycles : Array [0..4] of Byte = (165, 165, 25, 103, 42);
{
Notice that here I have defined the 8086 as a Processor type of 0 vice
the returned value of 1 from WhatCPU. Since the original code did not
distinguish between the 8086 and the 80186, I can get away with this.
}
Var
Ticks,
Cycles,
CPS : LongInt;
Which_CPU : Word;
Function i86_to_i286 : Word; Assembler;
Asm { Function i86_to_i286 }
CLI
MOV CX, 1234
XOR DX, DX
XOR AX, AX
MOV AL, $B8
OUT $43, AL
IN AL, $61
OR AL, 1
OUT $61, AL
XOR AL, AL
OUT $42, AL
OUT $42, AL
XOR AX, AX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IDIV CX
IN AL, $42
MOV AH, AL
IN AL, $42
XCHG AL, AH
NEG AX
STI
End; { Function i86_to_i286 }
Function i386_to_i486 : Word; Assembler;
Asm { Function i386_to_i486 }
CLI
MOV AL, $B8
OUT $43, AL
IN AL, $61
OR AL, 1
OUT $61, AL
XOR AL, AL
OUT $42, AL
OUT $42, AL
DB 66H,$B8,00h,00h,00h,80h;
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
DB 66H,0FH,$BC,$C8; { BSF ECX, EAX }
IN AL, 42H
MOV AH, AL
IN AL, 42H
XCHG AL, AH
NEG AX
STI
End; { Function i386_to_486 }
Begin { Procedure CPUSpeed }
Which_CPU := WhatCPU;
If Which_cpu < 3 Then
Ticks := i86_to_i286
Else
Ticks := i386_to_i486;
Cycles := 20 * Processor_cycles[Which_CPU];
CPS := (Cycles * 119318) Div Ticks;
MHz := CPS Div 100000;
KHz := (CPS Mod 100000 + 500) Div 1000
End; { Procedure CPUSpeed }
end. |
{----------------------------------------------------------------------------}
{ Written by Nguyen Le Quang Duy }
{ Nguyen Quang Dieu High School, An Giang }
{----------------------------------------------------------------------------}
Program NKINV;
Const
maxN =60000;
maxV =60000;
Var
n,ans :LongInt;
A :Array[0..maxN] of LongInt;
BIT :Array[0..maxV] of LongInt;
procedure Enter;
var
i :LongInt;
begin
Read(n);
for i:=1 to n do Read(A[i]);
end;
procedure UpdateBIT(i :LongInt);
begin
while (i<=maxV) do
begin
Inc(BIT[i]);
Inc(i,i and (-i));
end;
end;
function SearchBIT(i :LongInt) :LongInt;
var
res :LongInt;
begin
res:=0;
while (i>0) do
begin
Inc(res,BIT[i]);
Dec(i,i and (-i));
end;
Exit(res);
end;
procedure SolveBIT;
var
i :LongInt;
begin
FillChar(BIT,SizeOf(BIT),0);
ans:=0;
for i:=n downto 1 do
begin
Inc(ans,SearchBIT(A[i]-1));
UpdateBIT(A[i]);
end;
end;
Begin
Assign(Input,''); Reset(Input);
Assign(Output,''); Rewrite(Output);
Enter;
SolveBIT;
Write(ans);
Close(Input); Close(Output);
End. |
unit BCscore.Score;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Generics.Collections, Billiards.Member, ExtCtrls, jpeg, GIFImg;
type
TScoreForm = class(TForm)
pnlTop: TPanel;
pnlMiddle: TPanel;
pnlBottom: TPanel;
imgTopLeft: TImage;
lblLastName1: TLabel;
lblLastName2: TLabel;
imgTopRight: TImage;
lblTurns: TLabel;
lblScore1: TLabel;
lblCurrentScore1: TLabel;
lblHandicap1: TLabel;
lblHandicap2: TLabel;
lblScore2: TLabel;
lblCurrentScore2: TLabel;
lblGem: TLabel;
lblHR: TLabel;
lblGem1: TLabel;
lblGem2: TLabel;
lblHR1: TLabel;
lblHR2: TLabel;
ballWhite: TShape;
ballYellow: TShape;
lblFirstName1: TLabel;
lblFirstName2: TLabel;
lblNickName1: TLabel;
lblNickName2: TLabel;
gpnlAdvertisements: TGridPanel;
Image14: TImage;
Image1: TImage;
Image2: TImage;
Image3: TImage;
Image4: TImage;
Image5: TImage;
Image6: TImage;
Image7: TImage;
Image8: TImage;
Image9: TImage;
Image10: TImage;
Image11: TImage;
Image12: TImage;
Image13: TImage;
Image15: TImage;
Image16: TImage;
Image17: TImage;
Image18: TImage;
Image19: TImage;
Image20: TImage;
Image21: TImage;
Image22: TImage;
Image23: TImage;
Image24: TImage;
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
fCurrentPlayer: TBilliardMember;
fScores1: TList<integer>;
fScores2: TList<integer>;
fCurrentScore: integer;
fEndlessGame: boolean;
UnknownImg: TJPEGImage;
procedure LoadUnknownImage(aImage: TImage);
procedure LoadPicture(aImage: TImage; aMember: TBilliardMember);
procedure UpdateStats(FirstTime: boolean = FALSE);
public
property CurrentPlayer: TBilliardMember read fCurrentPlayer write fCurrentPlayer;
property CurrentScore: integer read fCurrentScore write fCurrentScore;
property Scores1: TList<integer>read fScores1;
property Scores2: TList<integer>read fScores2;
property EndlessGame: boolean read fEndlessGame write fEndlessGame;
end;
var
ScoreForm: TScoreForm;
implementation
uses Billiards.Game, BCscore.Consts;
{$R *.dfm}
procedure TScoreForm.FormCreate(Sender: TObject);
begin
fScores1 := TList<integer>.Create;
fScores2 := TList<integer>.Create;
fCurrentScore := 0;
fEndlessGame := FALSE;
end;
procedure TScoreForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fScores1);
FreeAndNil(fScores2);
end;
procedure TScoreForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
ckEscape: // EXIT
begin
ModalResult := mrCancel;
end;
ckSubtractScore: // SUBTRACT SCORE
begin
if fCurrentScore > 0 then
Dec(fCurrentScore);
end;
ckAddScore: // ADD SCORE
begin
Inc(fCurrentScore);
end;
ckUndoTurn: // UNDO TURN
begin
if not Assigned(fCurrentPlayer) then
begin
fCurrentPlayer := BilliardGame.Member1;
fScores1.Clear;
fScores2.Clear;
end
else
begin
if fCurrentPlayer = BilliardGame.Member1 then
begin
if fScores2.Count > 0 then
begin
fCurrentScore := fScores2[fScores2.Count - 1];
BilliardGame.Score2 := BilliardGame.Score2 - fCurrentScore;
fScores2.Delete(fScores2.Count - 1);
fCurrentPlayer := BilliardGame.Member2;
BilliardGame.Turns := BilliardGame.Turns - 1;
end
else
fCurrentScore := 0;
end
else
begin
if fScores1.Count > 0 then
begin
fCurrentScore := fScores1[fScores1.Count - 1];
BilliardGame.Score1 := BilliardGame.Score1 - fCurrentScore;
fScores1.Delete(fScores1.Count - 1);
end
else
fCurrentScore := 0;
fCurrentPlayer := BilliardGame.Member1;
end;
end;
end;
ckEndTurn: // NEXT TURN FOR NEXT PLAYER
begin
if not Assigned(fCurrentPlayer) then
begin
if not fEndlessGame then
begin
// maximum number of turns reached
// show e message and ask if this is an endless game
// if so, continue play en never check turns again
end;
end
else
begin
if fCurrentPlayer = BilliardGame.Member1 then
begin
fScores1.Add(fCurrentScore);
BilliardGame.Score1 := BilliardGame.Score1 + fCurrentScore;
if fCurrentScore > BilliardGame.HighScore1 then
BilliardGame.HighScore1 := fCurrentScore;
fCurrentScore := 0;
fCurrentPlayer := BilliardGame.Member2;
end
else
begin
fScores2.Add(fCurrentScore);
BilliardGame.Score2 := BilliardGame.Score2 + fCurrentScore;
if fCurrentScore > BilliardGame.HighScore2 then
BilliardGame.HighScore2 := fCurrentScore;
fCurrentScore := 0;
if (not fEndlessGame) and (fScores1.Count < BilliardGame.GameDay.GameType.MaxTurns) then
fCurrentPlayer := BilliardGame.Member1
else
fCurrentPlayer := nil;
BilliardGame.Turns := BilliardGame.Turns + 1;
end;
end;
end
else
inherited;
end;
UpdateStats;
end;
procedure TScoreForm.FormShow(Sender: TObject);
begin
ClientHeight := 1024;
ClientWidth := 1280;
Color := clBackPanel;
pnlMiddle.Color := clScorePanel;
// left
lblLastName1.Font.Color := clNormalText;
lblFirstName1.Font.Color := clNormalText;
lblHandicap1.Font.Color := clHandicapText;
lblNickName1.Font.Color := clNormalText;
lblScore1.Font.Color := clNormalText;
lblCurrentScore1.Font.Color := clCurrentScoreText;
// middle
lblTurns.Color := clNormalText;
lblTurns.Font.Color := clScorePanel;
lblGem1.Font.Color := clAverageText;
lblHR1.Font.Color := clAverageText;
lblGem.Font.Color := clAverageText;
lblHR.Font.Color := clAverageText;
lblGem2.Font.Color := clAverageText;
lblHR2.Font.Color := clAverageText;
// right
lblLastName2.Font.Color := clNormalText;
lblFirstName2.Font.Color := clNormalText;
lblHandicap2.Font.Color := clHandicapText;
lblNickName2.Font.Color := clNormalText;
lblScore2.Font.Color := clNormalText;
lblCurrentScore2.Font.Color := clCurrentScoreText;
gpnlAdvertisements.Color := clBackPanel;
fCurrentPlayer := BilliardGame.Member1;
fScores1.Clear;
fScores2.Clear;
UpdateStats(TRUE);
//Timer1.Enabled := TRUE;
end;
procedure TScoreForm.LoadPicture(aImage: TImage; aMember: TBilliardMember);
begin
if Assigned(aMember.Picture) then
begin
// aImage.Stretch := FALSE;
// aMember.Picture.SaveToFile(aMember.LastName+'.jpeg');
aImage.Picture.Bitmap.Assign(aMember.Picture);
end
else
LoadUnknownImage(aImage);
end;
procedure TScoreForm.LoadUnknownImage(aImage: TImage);
var
Stream: TFileStream;
begin
if not Assigned(UnknownImg) then
begin
Stream := TFileStream.Create('unknown.jpg', fmOpenRead);
try
Stream.Position := 0;
UnknownImg := TJPEGImage.Create;
UnknownImg.LoadFromStream(Stream);
finally
FreeAndNil(Stream);
end;
end;
aImage.Stretch := TRUE;
aImage.Picture.Bitmap.Assign(UnknownImg);
end;
procedure TScoreForm.UpdateStats(FirstTime: boolean);
begin
if FirstTime then
begin
LoadPicture(imgTopLeft, BilliardGame.Member1);
lblLastName1.Caption := BilliardGame.Member1.LastName;
lblFirstName1.Caption := BilliardGame.Member1.FirstName;
lblHandicap1.Caption := IntToStr(BilliardGame.GetHandicapForMember(BilliardGame.Member1.ID));
LoadPicture(imgTopRight, BilliardGame.Member2);
lblLastName2.Caption := BilliardGame.Member2.LastName;
lblFirstName2.Caption := BilliardGame.Member2.FirstName;
lblHandicap2.Caption := IntToStr(BilliardGame.GetHandicapForMember(BilliardGame.Member2.ID));
lblNickName1.Caption := BilliardGame.Member1.NickName;
lblNickName2.Caption := BilliardGame.Member2.NickName;
lblTurns.Caption := '0';
lblScore1.Caption := '0';
lblCurrentScore1.Caption := '0';
lblGem1.Caption := '0,0';
lblHR1.Caption := '0';
lblScore2.Caption := '0';
lblCurrentScore2.Caption := '0';
lblGem2.Caption := '0,0';
lblHR2.Caption := '0';
end;
ballWhite.Visible := (fCurrentPlayer = BilliardGame.Member1);
ballYellow.Visible := (fCurrentPlayer = BilliardGame.Member2);
lblCurrentScore1.Visible := (fCurrentPlayer = BilliardGame.Member1);
lblCurrentScore2.Visible := (fCurrentPlayer = BilliardGame.Member2);
lblTurns.Caption := IntToStr(BilliardGame.Turns);
lblScore1.Caption := IntToStr(BilliardGame.Score1);
lblCurrentScore1.Caption := '+' + IntToStr(fCurrentScore);
if fScores1.Count > 0 then
lblGem1.Caption := Format('%2.3f', [BilliardGame.Score1 / fScores1.Count])
else
lblGem1.Caption := '0,0';
lblHR1.Caption := IntToStr(BilliardGame.HighScore1);
lblScore2.Caption := IntToStr(BilliardGame.Score2);
lblCurrentScore2.Caption := '+' + IntToStr(fCurrentScore);
if fScores2.Count > 0 then
lblGem2.Caption := Format('%2.3f', [BilliardGame.Score2 / fScores2.Count])
else
lblGem2.Caption := '0,0';
lblHR2.Caption := IntToStr(BilliardGame.HighScore2);
Update;
end;
end.
|
unit uHikDaoFeng;
interface
uses
System.Classes, Generics.Collections, IdHTTP, IdURI, SysUtils, uGlobal,
DateUtils, ActiveX, uTypes, System.Rtti, Xml.XMLIntf, Xml.XMLDoc,
System.Variants;
type
THik = class
private
FToken: String;
FConfig: THikDaoFengConfig;
function DFLogin: String;
procedure DFLogout;
function HttPPost(AUrl: String; AParams: TStrings; var AResult: String;
AEncoding: TEncoding = nil): Boolean;
function DecodeDFAnalysisOnePicResult(Xml: String): TList<TDFVehInfo>;
procedure InitVehInfo<T>(rec: Pointer);
function GetField(const AName: String; fields: TArray<TRttiField>)
: TRttiField;
public
constructor Create;
destructor Destroy; override;
function DFCreateImageJob(passList: TList<TPass>): String;
function GetJobProcess(jobid: String): Integer;
function DFAnalysisOnePic(Url: String): TList<TDFVehInfo>;
property Token: String read DFLogin;
property Config: THikDaoFengConfig read FConfig write FConfig;
end;
implementation
constructor THik.Create;
begin
FToken := '';
end;
function THik.DecodeDFAnalysisOnePicResult(Xml: String): TList<TDFVehInfo>;
var
XMLDoc, DocIntf: IXMLDocument;
rNode, cNode: IXMLNode;
I, J: Integer;
key, value: String;
veh: TDFVehInfo;
rrt: TRttiRecordType;
rField: TRttiField;
fields: TArray<TRttiField>;
begin
Result := nil;
rrt := TRTTIContext.Create.GetType(TypeInfo(TDFVehInfo)).AsRecord;
fields := rrt.GetFields;
XMLDoc := TXMLDocument.Create(nil);
DocIntf := XMLDoc;
XMLDoc.LoadFromXML(Xml);
rNode := XMLDoc.ChildNodes.Nodes[0];
rNode := rNode.ChildNodes.Nodes[0];
rNode := rNode.ChildNodes.Nodes[0];
if Trim(rNode.ChildValues['ErrorCode']) = '0' then
begin
Result := TList<TDFVehInfo>.Create;
for I := 0 to rNode.ChildNodes.Count - 1 do
begin
if Uppercase(rNode.ChildNodes[I].NodeName) <> Uppercase('stPreProcRet')
then
continue;
InitVehInfo<TDFVehInfo>(@veh);
cNode := rNode.ChildNodes[I];
for J := 0 to cNode.ChildNodes.Count - 1 do
begin
key := cNode.ChildNodes[J].NodeName;
if key.Contains('ns2:') then
key := key.Replace('ns2:', '');
rField := GetField(key, fields);
if rField <> nil then
begin
if cNode.ChildNodes[J].NodeValue <> null then
value := cNode.ChildNodes[J].NodeValue
else
value := '';
rField.SetValue(@veh, TValue.From<string>(value));
end;
end;
if veh.nTagID <> '' then
Result.Add(veh);
end;
end;
XMLDoc := nil;
DocIntf := nil;
end;
destructor THik.Destroy;
begin
DFLogout;
inherited;
end;
function THik.DFAnalysisOnePic(Url: String): TList<TDFVehInfo>;
var
Params: TStrings;
s: String;
begin
Result := nil;
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
Params := TStringList.Create;
try
s := '';
if Token = '' then
exit;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + Token + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:PicAnalysisReq>');
Params.Add(' <wsdl:nDataType>1</wsdl:nDataType>');
Params.Add(' <wsdl:algorithmType>258</wsdl:algorithmType>');
Params.Add(' <wsdl:strPicUrl>' + Url + '</wsdl:strPicUrl>');
Params.Add(' <wsdl:PicData>cid:1211963137164</wsdl:PicData>');
Params.Add(' </wsdl:PicAnalysisReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
if HttPPost(FConfig.DFUrl, Params, s) then
begin
Result := DecodeDFAnalysisOnePicResult(s);
end;
except
end;
Params.Free;
ActiveX.CoUninitialize;
end;
function THik.DFCreateImageJob(passList: TList<TPass>): String;
function DecodeDFSubJobResult(Xml: String): String;
begin
Result := '';
if pos('<errorCode>0</errorCode>', Xml) > 0 then
begin
if pos('<jobId>', Xml) > 0 then
Result := Xml.Substring(pos('<jobId>', Xml) + 6);
if (Result <> '') and (pos('</jobId>', Result) > 0) then
Result := copy(Result, 1, pos('</jobId>', Result) - 1)
else
Result := '';
end;
end;
function URLEncode(s: string): string;
begin
result := '';
try
result := TIdURI.URLEncode(s);
except
on e: exception do
begin
logger.Error('[URLEncode]' + e.Message + ' ' + s);
end;
end;
end;
var
Params: TStrings;
s, imgStr, passTime: String;
pass: TPass;
// formatSetting: TFormatSettings;
begin
Result := '';
ActiveX.CoInitializeEx(nil, COINIT_MULTITHREADED);
if Token = '' then
exit;
// formatSetting.TimeSeparator := ':';
// formatSetting.DateSeparator := '-';
passTime := IntToStr(DateUtils.MilliSecondsBetween(StrToDateTimeDef(pass.GCSJ,
now), 25569.3333333333));
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl" xmlns:ivms="http://www.hikvision.com.cn/ver1/schema/ivms/">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + FToken + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:SubmitJobReq>');
Params.Add(' <wsdl:jobInfo>');
Params.Add(' <ivms:jobName>job_' +
FormatDateTime('yyyymmddhhnnsszzz', now()) + '</ivms:jobName>');
Params.Add(' <ivms:jobType>2</ivms:jobType>');
Params.Add(' <ivms:dataSourceType>2</ivms:dataSourceType>');
Params.Add(' <ivms:priority>30</ivms:priority>');
Params.Add(' <ivms:source>test111</ivms:source>');
Params.Add(' <ivms:algorithmType>770</ivms:algorithmType>');
Params.Add(' <!--1 or more repetitions:-->');
Params.Add(' <ivms:destinationInfos>');
Params.Add(' <ivms:destinationUrl>' + FConfig.K08SaveUrl +
'</ivms:destinationUrl>');
Params.Add(' <ivms:destinationType>11</ivms:destinationType>');
// Params.Add(' <ivms:destinationType>17</ivms:destinationType>');
Params.Add(' </ivms:destinationInfos>');
Params.Add(' <ivms:streamInfo>');
Params.Add(' <ivms:streamType>2</ivms:streamType>');
imgStr := ' <ivms:streamUrl>images://{"imageInfos": [';
for pass in passList do
begin
s := URLEncode(pass.FWQDZ + pass.TP1);
if s <> ''then
begin
imgStr := imgStr + '{"data":"' + s + '",' +
'"dataType":1,"id":"dddddddddddddd","LaneNO":1,"plate":"' + pass.HPHM +
'","vehicleDir":0,' + '"targetAttrs":"{\n\t\"crossing_id\":\t\"' +
gDicDevice[pass.KDBH].ID + '\",\n\t\"pass_id\":\t\"' + pass.GCXH +
'\",\n\t\"lane_no\":\t\"' + pass.CDBH + '\",\n\t\"pass_time\":\t\"' +
passTime + '\"\n}"},';
end;
end;
imgStr := copy(imgStr, 1, Length(imgStr) - 1) +
'],"operate":524287,"targetNum":1,"plateRegMode": 0}</ivms:streamUrl>';
Params.Add(imgStr);
Params.Add(' <ivms:smart>false</ivms:smart>');
Params.Add(' <ivms:maxSplitCount>0</ivms:maxSplitCount>');
Params.Add(' <ivms:splitTime>0</ivms:splitTime>');
Params.Add(' </ivms:streamInfo>');
Params.Add(' </wsdl:jobInfo>');
Params.Add(' </wsdl:SubmitJobReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
logger.Debug(Params.Text);
if HttPPost(FConfig.DFUrl, Params, s) then
begin
logger.Debug(s);
Result := DecodeDFSubJobResult(s);
end;
Params.Free;
ActiveX.CoUninitialize;
end;
function THik.DFLogin: String;
var
Params: TStrings;
s: String;
begin
if FToken = '' then
begin
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header/>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:LoginReq>');
Params.Add(' <wsdl:userName>' + FConfig.DFUser +
'</wsdl:userName>');
Params.Add(' <wsdl:password>' + FConfig.DFPwd +
'</wsdl:password>');
Params.Add(' </wsdl:LoginReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
if HttPPost(FConfig.DFUrl, Params, s) then
begin
if pos('<token>', s) > 0 then
FToken := copy(s, pos('<token>', s) + 7, Length(s));
if (FToken <> '') and (pos('</token>', FToken) > 0) then
FToken := copy(FToken, 1, pos('</token>', FToken) - 1)
else
FToken := '';
end;
Params.Free;
end;
Result := FToken;
if FToken = '' then
logger.Error('Get token error');
end;
procedure THik.DFLogout;
var
Params: TStrings;
s: String;
begin
if FToken <> '' then
begin
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + FToken + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:LogoutReq>');
Params.Add(' <wsdl:token>' + FToken + '</wsdl:token>');
Params.Add(' </wsdl:LogoutReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
HttPPost(FConfig.DFUrl, Params, s);
Params.Free;
end;
end;
function THik.GetField(const AName: String; fields: TArray<TRttiField>)
: TRttiField;
var
Field: TRttiField;
begin
for Field in fields do
if SameText(Field.Name, AName) then
exit(Field);
Result := nil;
end;
function THik.GetJobProcess(jobid: String): Integer;
var
Params: TStrings;
s: String;
begin
Result := 0;
Params := TStringList.Create;
Params.Add
('<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:wsdl="http://www.hikvision.com.cn/ver1/ivms/wsdl">');
Params.Add(' <soap:Header>');
Params.Add(' <wsdl:HeaderReq>');
Params.Add(' <wsdl:token>' + Token + '</wsdl:token>');
Params.Add(' <wsdl:version>1.2</wsdl:version>');
Params.Add(' </wsdl:HeaderReq>');
Params.Add(' </soap:Header>');
Params.Add(' <soap:Body>');
Params.Add(' <wsdl:JobStatusReq>');
Params.Add(' <wsdl:jobIds>' + jobid + '</wsdl:jobIds>');
Params.Add(' </wsdl:JobStatusReq>');
Params.Add(' </soap:Body>');
Params.Add('</soap:Envelope>');
if HttPPost(FConfig.DFUrl, Params, s) then
begin
if pos('<ns2:errorCode>113</ns2:errorCode>', s) > 0 then // 作业id不存在
Result := 100
else if pos('<ns2:process>100.0</ns2:process>', s) > 0 then
Result := 100
else if pos('<ns2:errorCode>106</ns2:errorCode>', s) > 0 then // token过期
FToken := '';
end;
Params.Free;
end;
function THik.HttPPost(AUrl: String; AParams: TStrings; var AResult: String;
AEncoding: TEncoding = nil): Boolean;
var
http: TIdHTTP;
stream: TMemoryStream;
I: Integer;
begin
AResult := '';
Result := false;
I := 0;
while (I < 2) and not Result do
begin
http := TIdHTTP.Create(nil);
stream := TMemoryStream.Create;
try
if AEncoding = nil then
AParams.SaveToStream(stream)
else
AParams.SaveToStream(stream, AEncoding);
AResult := UTF8ToString(http.Post(AUrl, stream));
Result := True;
except
on e: exception do
begin
logger.Error('[THik.HttpPost]' + e.Message);
AResult := http.ResponseText;
inc(I);
end;
end;
stream.Free;
http.Disconnect;
http.Free;
end;
end;
procedure THik.InitVehInfo<T>(rec: Pointer);
var
rrt: TRttiRecordType;
rField: TRttiField;
begin
rrt := TRTTIContext.Create.GetType(TypeInfo(T)).AsRecord;
for rField in rrt.GetFields do
rField.SetValue(rec, TValue.From<string>(''));
rrt := nil;
end;
end.
|
unit v_class_combo;
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils,StdCtrls;
type TxPLClassCombo = class(TCombobox)
private
fRegExpr : string;
fValid : boolean;
procedure SetRegExpr(const AValue: string);
procedure SetValid(const AValue: boolean);
public
constructor create(aOwner : TComponent); override;
procedure EditingDone; override;
property IsValid : boolean read fValid write SetValid;
published
property RegExpr : string read fRegExpr write SetRegExpr;
end;
procedure Register;
implementation
uses uxPLConst, RegEx, Graphics;
procedure Register;
begin
RegisterComponents('xPL Components',[TxPLClassCombo]);
end;
constructor TxPLClassCombo.create(aOwner: TComponent);
var s: tstringlist;
i : integer;
begin
inherited create(aOwner);
RegExpr := '^' + K_REGEXPR_SCHEMA_ELEMENT + '$';
Items.Add('');
s := tstringlist.create;
s.Sorted := true;
for i:=low(K_XPL_CLASS_DESCRIPTORS) to high(K_XPL_CLASS_DESCRIPTORS) do
S.Add(K_XPL_CLASS_DESCRIPTORS[i]);
Items.AddStrings(s);
s.Destroy;
end;
procedure TxPLClassCombo.SetRegExpr(const AValue: string);
begin
if aValue = fRegExpr then exit;
fRegExpr := aValue;
end;
procedure TxPLClassCombo.EditingDone;
var matchpos, offset : integer;
begin
inherited;
if RegExpr='' then exit;
with TRegexEngine.Create(RegExpr) do try
IsValid := MatchString(Text,matchpos,offset);
// Expression := RegExpr;
// IsValid := Exec(Text);
finally
free;
end;
end;
procedure TxPLClassCombo.SetValid(const AValue: boolean);
begin
fValid := aValue;
if fValid then Self.Color := clWindow else Self.Color := clRed;
end;
end.
|
unit DriversAPI;
{
Автор: HoShiMin, 2015
Основные понятия:
IRP - I/O Request Packet, передаваемые драйверу данные
Имя драйвера - имя службы драйвера
Имя устройства - указано в ДРАЙВЕРЕ, ему посылать IOCTL!
IOCTL - пользовательский контрольный код:
0x000 : 0x7FF - зарезервировано Microsoft
0x800 : 0xFFF - определяется пользователем
RawIOCTL - пользовательский код (IOCTL), переведённый в системный вид
с помощью функции GenerateIOCTL (см. ниже):
Параметры GenerateIOCTL:
DeviceType - определяет устройство:
0х0000 : 0х7FFF - зарезервировано Microsoft
0х8000 : 0хFFFF - определяется пользователем
IOCTL - контрольный код:
0x000 : 0x7FF - зарезервировано Microsoft
0x800 : 0xFFF - определяется пользователем
AccessMethod - тип доступа к буферу:
METHOD_BUFFERED:
Драйвер:
Входной буфер в pIrp->AssociatedIrp.SystemBuffer
Выходной буфер - выходные данные копировать во входной буфер,
размер выходных данных определяется размером
наибольшего буфера
Клиент:
Передавать и получать данные во входном буфере
METHOD_IN_DIRECT или METHOD_OUT_DIRECT:
Драйвер:
Входной буфер в pIrp->AssociatedIrp.SystemBuffer
Выходной буфер в pIrp->MdlAddress
Клиент:
Зависит от драйвера, в общем случае отправлять данные во входном буфере,
получать - в выходном, в частном случае выходной буфер получать во входном
METHOD_NEITHER:
Драйвер:
Входной буфер в Parameters.DeviceIoControl.Type3InputBuffer (IO_STACK_LOCATION)
Выходной буфер в pIrp->UserBuffer
Клиент:
Отправка данных во входном буфере
Получение данных в выходном буфере
### ВНИМАНИЕ! Неверный тип доступа к буферу может вызвать BSOD!
Подробнее о типах доступа к буферу:
http://msdn.microsoft.com/en-us/library/windows/hardware/ff540663(v=vs.85).aspx
http://blagin.ru/sozdanie-drajverov-chast-4-obmen-dannymi/
http://drp.su/ru/driver_dev/08_06.htm
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*** Отключение проверки подписи драйверов на 64х-битных ОС:
В консоли набрать:
* Отключение проверки цифровой подписи (разрешить устанавливать неподписанные драйвера):
bcdedit.exe /set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit.exe /set TESTSIGNING ON
* Включение проверки цифровой подписи (запретить устанавливать неподписанные драйвера):
bcdedit.exe /set loadoptions ENABLE_INTEGRITY_CHECKS
bcdedit.exe /set TESTSIGNING OFF
* Включение поддержки ядерной отладки (kernel-debugging) для WinDbg и Kernel Debugger из WDK:
bcdedit.exe /debug on - включить
bcdedit.exe /debug off - выключить
После выполнения необходимо перезагрузить Windows
}
interface
uses
Windows, WinSvc;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
type
INSTALL_DRIVER_STATUS = (
INSTALL_DRIVER_SUCCESS,
INSTALL_DRIVER_ERROR_OPEN_SC_MANAGER,
INSTALL_DRIVER_ERROR_CREATE_SERVICE,
INSTALL_DRIVER_ERROR_START_SERVICE
);
DELETE_DRIVER_STATUS = (
DELETE_DRIVER_SUCCESS,
DELETE_DRIVER_ERROR_OPEN_SC_MANAGER,
DELETE_DRIVER_ERROR_OPEN_SERVICE,
DELETE_DRIVER_ERROR_CONTROL_SERVICE,
DELETE_DRIVER_ERROR_DELETE_SERVICE
);
IRP_STATUS = (
IRP_SUCCESS,
IRP_ERROR_OPEN_DEVICE,
IRP_ERROR_DEVICE_IO_CONTROL
);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const
METHOD_BUFFERED = 0;
METHOD_IN_DIRECT = 1;
METHOD_OUT_DIRECT = 2;
METHOD_NEITHER = 3;
FILE_ANY_ACCESS = 0;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Приводит IOCTL к системному виду:
function GenerateIOCTL(DeviceType, FunctionNumber, AccessMethod, Access: LongWord): LongWord;
// Получить дескриптор устройства, которому будем посылать IOCTL (DeviceName указан в ДРАЙВЕРЕ! Это НЕ имя службы драйвера):
function GetDeviceHandle(const DeviceName: string): THandle;
// Отправка IOCTL драйверу (устройству):
function SendIOCTL(hDevice: THandle; IOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord; Method: LongWord = METHOD_NEITHER): IRP_STATUS; overload;
function SendIOCTL(const DeviceName: string; IOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord; Method: LongWord = METHOD_NEITHER): IRP_STATUS; overload;
function SendRawIOCTL(hDevice: THandle; RawIOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord): IRP_STATUS; overload;
function SendRawIOCTL(const DeviceName: string; RawIOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord): IRP_STATUS; overload;
// Функции установки и удаления драйвера:
function InstallDriver(const DriverPath, DriverName: string): INSTALL_DRIVER_STATUS;
function DeleteDriver(const DriverName: string): DELETE_DRIVER_STATUS;
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
implementation
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
function GenerateIOCTL(DeviceType, FunctionNumber, AccessMethod, Access: LongWord): LongWord;
begin
Result := (DeviceType shl 16) or (Access shl 14) or (FunctionNumber shl 2) or AccessMethod;
end;
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
function GetDeviceHandle(const DeviceName: string): THandle;
begin
Result := CreateFile(
PChar('\\.\' + DeviceName),
GENERIC_READ or GENERIC_WRITE,
FILE_SHARE_READ or FILE_SHARE_WRITE,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL or FILE_ATTRIBUTE_SYSTEM,
0
);
end;
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
function SendIOCTL(hDevice: THandle; IOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord; Method: LongWord = METHOD_NEITHER): IRP_STATUS; overload;
var
RawIOCTL: LongWord;
begin
RawIOCTL := GenerateIOCTL($8000, IOCTL, Method, FILE_ANY_ACCESS);
if not DeviceIoControl(hDevice, RawIOCTL, InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize, BytesReturned, nil) then
Result := IRP_ERROR_DEVICE_IO_CONTROL
else
Result := IRP_SUCCESS;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function SendIOCTL(const DeviceName: string; IOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord; Method: LongWord = METHOD_NEITHER): IRP_STATUS; overload;
var
hDevice: THandle;
RawIOCTL: LongWord;
begin
hDevice := GetDeviceHandle(DeviceName);
if hDevice = INVALID_HANDLE_VALUE then
begin
Result := IRP_ERROR_OPEN_DEVICE;
Exit;
end;
RawIOCTL := GenerateIOCTL($8000, IOCTL, Method, FILE_ANY_ACCESS);
if not DeviceIoControl(hDevice, RawIOCTL, InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize, BytesReturned, nil) then
Result := IRP_ERROR_DEVICE_IO_CONTROL
else
Result := IRP_SUCCESS;
CloseHandle(hDevice);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function SendRawIOCTL(hDevice: THandle; RawIOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord): IRP_STATUS; overload;
begin
if not DeviceIoControl(hDevice, RawIOCTL, InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize, BytesReturned, nil) then
Result := IRP_ERROR_DEVICE_IO_CONTROL
else
Result := IRP_SUCCESS;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function SendRawIOCTL(const DeviceName: string; RawIOCTL: LongWord; InputBuffer: Pointer; InputBufferSize: LongWord; OutputBuffer: Pointer; OutputBufferSize: LongWord; out BytesReturned: LongWord): IRP_STATUS; overload;
var
hDevice: THandle;
begin
hDevice := GetDeviceHandle(DeviceName);
if hDevice = INVALID_HANDLE_VALUE then
begin
Result := IRP_ERROR_OPEN_DEVICE;
Exit;
end;
if not DeviceIoControl(hDevice, RawIOCTL, InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize, BytesReturned, nil) then
Result := IRP_ERROR_DEVICE_IO_CONTROL
else
Result := IRP_SUCCESS;
CloseHandle(hDevice);
end;
//HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH
function InstallDriver(const DriverPath, DriverName: string): INSTALL_DRIVER_STATUS;
var
hSCManager: THandle;
hService: THandle;
ServiceArgVectors: PChar;
begin
// Открываем менеджер сервисов:
hSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if hSCManager = 0 then
begin
Result := INSTALL_DRIVER_ERROR_OPEN_SC_MANAGER;
Exit;
end;
// Создаём сервис:
hService := CreateService(
hSCManager,
PChar(DriverName),
PChar(DriverName),
SERVICE_ALL_ACCESS,
SERVICE_KERNEL_DRIVER,
SERVICE_DEMAND_START,
SERVICE_ERROR_NORMAL,
PChar(DriverPath),
nil,
nil,
nil,
nil,
nil
);
if hService = 0 then
begin
Result := INSTALL_DRIVER_ERROR_CREATE_SERVICE;
CloseServiceHandle(hSCManager);
Exit;
end;
// Запускаем сервис:
if not StartService(hService, 0, ServiceArgVectors) then
begin
Result := INSTALL_DRIVER_ERROR_START_SERVICE;
DeleteService(hService);
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
Exit;
end;
Result := INSTALL_DRIVER_SUCCESS;
// Закрываем хэндлы:
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
function DeleteDriver(const DriverName: string): DELETE_DRIVER_STATUS;
var
hSCManager: THandle;
hService: THandle;
ServiceStatus: _SERVICE_STATUS;
begin
// Открываем менеджер сервисов:
hSCManager := OpenSCManager(nil, nil, SC_MANAGER_ALL_ACCESS);
if hSCManager = 0 then
begin
Result := DELETE_DRIVER_ERROR_OPEN_SC_MANAGER;
Exit;
end;
// Открываем работающий сервис:
hService:= OpenService(hSCManager, PChar(DriverName), SERVICE_ALL_ACCESS);
if hService = 0 then
begin
Result := DELETE_DRIVER_ERROR_OPEN_SERVICE;
CloseServiceHandle(hSCManager);
Exit;
end;
// Останавливаем сервис:
if not ControlService(hService, SERVICE_CONTROL_STOP, ServiceStatus) then
begin
if not DeleteService(hService) then
Result := DELETE_DRIVER_ERROR_CONTROL_SERVICE
else
Result := DELETE_DRIVER_SUCCESS;
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
Exit;
end;
// Удаляем сервис:
if not DeleteService(hService) then
Result := DELETE_DRIVER_ERROR_DELETE_SERVICE
else
Result := DELETE_DRIVER_SUCCESS;
// Закрываем хэндлы:
CloseServiceHandle(hService);
CloseServiceHandle(hSCManager);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
end.
|
FUNCTION UserChar( b : BYTE ) : CHAR;
BEGIN
IF b < $0A THEN
UserChar := Chr(b+$30) { 0-9 }
ELSE
UserChar := Chr(b+$61-10); { a-f }
END;
|
UNIT DT_Especie;
INTERFACE
CONST
(*Constantes definidas para la operación EstadisticaEspecie. Según el
argumento pasado será el resultado que la operación retorne.*)
PS_Base= 1;
ATK_Base= 2;
DEF_Base=3 ;
ATKSp_Base= 4;
DEFSp_Base= 5;
VEL_Base= 6;
AMISTAD_Base= 7;
EXP_Base= 8;
PS_Esfuerzo= 9;
ATK_Esfuerzo= 10;
DEF_Esfuerzo= 11;
ATKSp_Esfuerzo= 12;
DEFSp_Esfuerzo= 13;
VEL_Esfuerzo= 14;
RatioCaptura= 15;
TYPE
Especie= RECORD
Id: INTEGER;
Numero: STRING;
Nombre: STRING;
Tipo1: INTEGER;
Tipo2: INTEGER;
PS_Base: INTEGER;
ATK_Base: INTEGER;
DEF_Base: INTEGER;
ATKSp_Base: INTEGER;
DEFSp_Base: INTEGER;
VEL_Base: INTEGER;
AMISTAD_Base: INTEGER;
EXP_Base: INTEGER;
PS_Esfuerzo: INTEGER;
ATK_Esfuerzo: INTEGER;
DEF_Esfuerzo: INTEGER;
ATKSp_Esfuerzo: INTEGER;
DEFSp_Esfuerzo: INTEGER;
VEL_Esfuerzo: INTEGER;
Crecimiento: STRING;
RatioCaptura: INTEGER;
end;
RangoTiposElementales= 1..2; //Para el argumento 't' de la operación TipoEspecie.
RangoEstadisticasEspecie= 1..15; //Para el argumento 'estadistica' de la operacion EstadisticaEspecie.
(*Crea una Especie Pokemon a partir de los argumentos pasados como parámetro y la retorna.
El Tipo Secundario para especies sin tipo secundario será 'NULL'.*)
PROCEDURE CrearEspecie(id: INTEGER; numero, nombre: STRING; tipo1, tipo2, PS_Base,
ATK_Base, DEF_Base, ATKSp_Base, DEFSp_Base, VEL_Base, AMISTAD_Base, EXP_Base,
PS_Esfuerzo, ATK_Esfuerzo, DEF_Esfuerzo, ATKSp_Esfuerzo, DEFSp_Esfuerzo,
VEL_Esfuerzo: INTEGER; Crecimiento: STRING; RatioCaptura: INTEGER; VAR e: Especie);
(*Retorna el Id de la especie dada.*)
FUNCTION IdEspecie(e: Especie): INTEGER;
(*Retorna el número de la especie dada.*)
FUNCTION NumeroEspecie(e: Especie): STRING;
(*Retorna el nombre de la especie dada.*)
FUNCTION NombreEspecie(e: Especie): STRING;
(*Si t es 1 retorna el Tipo Primario de la especie, si t es 2 retorna el Tipo
Secundario de la especie.*)
FUNCTION TipoEspecie(t: RangoTiposElementales; e: Especie): INTEGER;
(*Retorna una de las estadísticas de la especie 'e' según el valor pasado en el
argumento 'estadistica'. Los posibles valores dicho argumento son las constantes
definidas en esta unidad: PS_Base, ATK_Base, DEF_Base, ATKSp_Base, DEFSp_Base,
VEL_Base, AMISTAD_Base, EXP_Base, PS_Esfuerzo, ATK_Esfuerzo, DEF_Esfuerzo,
ATKSp_Esfuerzo, DEFSp_Esfuerzo, VEL_Esfuerzo, RatioCaptura.*)
FUNCTION EstadisticaEspecie(estadistica: RangoEstadisticasEspecie; e: Especie): INTEGER;
(*Devuelve el tipo de creicmiento de la especie pudiendo ser 'RAPIDO', 'NORMAL',
'LENTO', 'ERRÁTICO', 'FLUCTUANTE' o 'PARABOLICO'.*)
FUNCTION CrecimientoEspecie(e: Especie): STRING;
IMPLEMENTATION
(*Crea una Especie Pokemon a partir de los argumentos pasados como parámetro y la retorna.
El Tipo Secundario para especies sin tipo secundario será 'NULL'.*)
PROCEDURE CrearEspecie(id: INTEGER; numero, nombre: STRING; tipo1, tipo2, PS_Base,
ATK_Base, DEF_Base, ATKSp_Base, DEFSp_Base, VEL_Base, AMISTAD_Base, EXP_Base,
PS_Esfuerzo, ATK_Esfuerzo, DEF_Esfuerzo, ATKSp_Esfuerzo, DEFSp_Esfuerzo,
VEL_Esfuerzo: INTEGER; Crecimiento: STRING; RatioCaptura: INTEGER; VAR e: Especie);
Begin
e.id := id;
e.numero := numero;
e.nombre := nombre;
e.tipo1 := tipo1;
e.tipo2 := tipo2;
e.PS_Base := PS_Base;
e.ATK_Base := ATK_Base;
e.DEF_Base := DEF_Base;
e.ATKSp_Base := ATKSp_Base;
e.DEFSp_Base := DEFSp_Base;
e.VEL_Base := VEL_Base;
e.AMISTAD_Base := AMISTAD_Base;
e.EXP_Base := EXP_Base;
e.PS_Esfuerzo := PS_Esfuerzo;
e.ATK_Esfuerzo := ATK_Esfuerzo;
e.DEF_Esfuerzo := DEF_Esfuerzo;
e.ATKSp_Esfuerzo := ATKSp_Esfuerzo;
e.DEFSp_Esfuerzo := DEFSp_Esfuerzo;
e.VEL_Esfuerzo := VEL_Esfuerzo;
e.Crecimiento := Crecimiento;
e.RatioCaptura := RatioCaptura;
end;
(*Retorna el Id de la especie dada.*)
FUNCTION IdEspecie(e: Especie): INTEGER;
Begin
IdEspecie := e.id;
end;
(*Retorna el número de la especie dada.*)
FUNCTION NumeroEspecie(e: Especie): STRING;
Begin
NumeroEspecie := e.numero;
end;
(*Retorna el nombre de la especie dada.*)
FUNCTION NombreEspecie(e: Especie): STRING;
Begin
NombreEspecie := e.nombre;
end;
(*Si t es 1 retorna el Tipo Primario de la especie, si t es 2 retorna el Tipo
Secundario de la especie.*)
FUNCTION TipoEspecie(t: RangoTiposElementales; e: Especie): INTEGER;
Begin
if t = 1 then TipoEspecie := e.tipo1
else TipoEspecie := e.tipo2;
end;
(*Retorna una de las estadísticas de la especie 'e' según el valor pasado en el
argumento 'estadistica'. Los posibles valores dicho argumento son las constantes
definidas en esta unidad: PS_Base, ATK_Base, DEF_Base, ATKSp_Base, DEFSp_Base,
VEL_Base, AMISTAD_Base, EXP_Base, PS_Esfuerzo, ATK_Esfuerzo, DEF_Esfuerzo,
ATKSp_Esfuerzo, DEFSp_Esfuerzo, VEL_Esfuerzo, RatioCaptura.*)
FUNCTION EstadisticaEspecie(estadistica: RangoEstadisticasEspecie; e: Especie): INTEGER;
Begin
case estadistica of
PS_Base: EstadisticaEspecie := e.PS_Base;
ATK_Base: EstadisticaEspecie := e.ATK_Base;
DEF_Base: EstadisticaEspecie := e.DEF_Base;
ATKSp_Base: EstadisticaEspecie := e.ATKSp_Base;
DEFSp_Base: EstadisticaEspecie := e.DEFSp_Base;
VEL_Base: EstadisticaEspecie := e.VEL_Base;
AMISTAD_Base: EstadisticaEspecie := e.AMISTAD_Base;
EXP_Base: EstadisticaEspecie := e.EXP_Base;
PS_Esfuerzo: EstadisticaEspecie := e.PS_Esfuerzo;
ATK_Esfuerzo: EstadisticaEspecie := e.ATK_Esfuerzo;
DEF_Esfuerzo: EstadisticaEspecie := e.DEF_Esfuerzo;
ATKSp_Esfuerzo: EstadisticaEspecie := e.ATKSp_Esfuerzo;
DEFSp_Esfuerzo: EstadisticaEspecie := e.DEFSp_Esfuerzo;
VEL_Esfuerzo: EstadisticaEspecie := e.VEL_Esfuerzo;
RatioCaptura: EstadisticaEspecie := e.RatioCaptura;
end;
end;
(*Devuelve el tipo de crecimiento de la especie pudiendo ser 'RAPIDO', 'NORMAL',
'LENTO', 'ERRÁTICO', 'FLUCTUANTE' o 'PARABOLICO'.*)
FUNCTION CrecimientoEspecie(e: Especie): STRING;
Begin
CrecimientoEspecie := e.Crecimiento;
end;
end.
|
unit uScriptEngine;
interface
uses
Classes, Windows, MSScriptControl_TLB, uHidmacrosIntf;
type
TScriptEngine = class
private
{ Private declarations }
fTestingSC: TScriptControl;
fExecutionSC: TScriptControl;
fRoutinesSource: String;
fRoutinesCompiled: Boolean;
fHIDMacrosIntf: THIDMacrosIntf;
fProcBegin: String;
fProcEnd: String;
fCompiling: boolean;
//fOnDisconnect: TNotifyEvent;
procedure DebugLog(Value: String);
function GetLanguage: String;
procedure SetLanguage(const Value: String);
procedure SetRoutinesSource(const Value: String);
function GetAllowGUI: Boolean;
function GetScriptTimeout: Integer;
procedure SetAllowGUI(const Value: Boolean);
procedure SetScriptTimeout(const Value: Integer);
procedure SetProcBegin(const Value: String);
procedure SetProcEnd(const Value: String);
public
{ Public declarations }
constructor Create(pOwner: TComponent);
destructor Destroy; Override;
procedure ResetTestingSC;
procedure ResetExecutionSC;
property TestingSC: TScriptControl read fTestingSC;
property ExecutionSC: TScriptControl read fExecutionSC;
property RoutinesSource: String read fRoutinesSource write SetRoutinesSource;
property RoutinesCompiled: Boolean read fRoutinesCompiled write fRoutinesCompiled;
property Language: String read GetLanguage write SetLanguage;
property ScriptTimeout: Integer read GetScriptTimeout write SetScriptTimeout;
property AllowGUI: Boolean read GetAllowGUI write SetAllowGUI;
property ProcBegin: String read fProcBegin write SetProcBegin;
property ProcEnd: String read fProcEnd write SetProcEnd;
property Compiling: Boolean read fCompiling write fCompiling;
//property OnDisconnect: TNotifyEvent read fOnDisconnect write fOnDisconnect;
end;
implementation
uses SysUtils, ComObj, Forms;
constructor TScriptEngine.Create(pOwner: TComponent);
begin
//inherited;
fHIDMacrosIntf := THIDMacrosIntf.Create;
fTestingSC := TScriptControl.Create(pOwner);
fExecutionSC := TScriptControl.Create(pOwner);
fTestingSC.SitehWnd := (pOwner as TForm).Handle;
fExecutionSC.SitehWnd := (pOwner as TForm).Handle;
SetAllowGUI(False);
SetLanguage('VBscript');
AllowGUI := False;
ScriptTimeout := 10;
fCompiling := False;
end;
destructor TScriptEngine.Destroy;
begin
fHIDMacrosIntf.ObjRelease;
fTestingSC.Free;
fExecutionSC.Free;
inherited;
end;
function TScriptEngine.GetAllowGUI: Boolean;
begin
Result := fExecutionSC.AllowUI;
end;
function TScriptEngine.GetLanguage: String;
begin
Result := fExecutionSC.Language;
end;
function TScriptEngine.GetScriptTimeout: Integer;
begin
Result := fExecutionSC.Timeout div 1000;
end;
procedure TScriptEngine.ResetExecutionSC;
begin
fExecutionSC.Reset;
fExecutionSC.AddObject('HIDMacros', fHIDMacrosIntf, True);
fHIDMacrosIntf.ObjAddRef;
end;
procedure TScriptEngine.ResetTestingSC;
begin
fTestingSC.Reset;
fTestingSC.AddObject('HIDMacros', fHIDMacrosIntf, True);
fHIDMacrosIntf.ObjAddRef;
end;
procedure TScriptEngine.SetAllowGUI(const Value: Boolean);
begin
fExecutionSC.AllowUI := Value;
fTestingSC.AllowUI := Value;
end;
procedure TScriptEngine.SetLanguage(const Value: String);
begin
fExecutionSC.Language := Value;
fTestingSC.Language := Value;
if UpperCase(Value) = 'VBSCRIPT' then
begin
fProcBegin := 'Sub %s';
fProcEnd := 'End Sub';
end else if UpperCase(Value) = 'JSCRIPT' then
begin
fProcBegin := 'function %s() {';
fProcEnd := '}';
end;
end;
procedure TScriptEngine.SetProcBegin(const Value: String);
begin
if (UpperCase(Value) <> 'VBSCRIPT') and
(UpperCase(Value) <> 'JSCRIPT') then
fProcBegin := Value;
end;
procedure TScriptEngine.SetProcEnd(const Value: String);
begin
if (UpperCase(Value) <> 'VBSCRIPT') and
(UpperCase(Value) <> 'JSCRIPT') then
fProcEnd := Value;
end;
procedure TScriptEngine.SetRoutinesSource(const Value: String);
begin
fRoutinesSource := Value;
end;
procedure TScriptEngine.SetScriptTimeout(const Value: Integer);
begin
fExecutionSC.Timeout := Value*1000;
fTestingSC.Timeout := Value*1000;
end;
procedure TScriptEngine.DebugLog(Value: String);
begin
//if Assigned(fOnClientLog) then
// fOnClientLog(Value);
end;
end.
|
{ Assuming that your serial port is accessible via AUX (reader &
punch), this is the only 'roll your own' routine. I've added a
RDRST BIOS call (among other things) to the Ampro's extended BIOS
jump table, and the following routine calls it.
Somewhere in your BIOS, it checks for whether a character is
available from the reader device. It's up to you to track that
routine down and use it here to return a TRUE from this routine
when a character is available. }
FUNCTION ModemInReady : BOOLEAN;
CONST
BIOSgettbl = 16; { Get BIOS extended jump table addr }
BIOSmdmIst = $0F; { Offset of modem input status call in }
{ the extended jump table }
VAR
addr : INTEGER;
flag : BYTE;
BEGIN
addr := BiosHL(BiosGettbl) + BIOSmdmIst;
Inline(
$21/*+7/ { LD HL,retAdr ; where JP (HL) RETs }
$E5/ { PUSH HL ; save return addr }
$2A/addr/ { LD HL,(addr) ; addr of rdr status }
$E9/ { JP (HL) ; get rdr status }
$32/flag); { retadr: LD (flag),A ; store rdr status }
ModemInReady := flag <> 0;
END;
|
unit CardHelper;
interface
uses
Winapi.Windows,
Vcl.WinXPanels;
type
TCard = class(Vcl.WinXPanels.TCard)
private
fFormWidth: integer;
fFormHeight: Integer;
public
property FormWidth: Integer read fFormWidth write fFormWidth;
property FormHeight: Integer read fFormHeight write fFormHeight;
end;
implementation
end.
|
unit CRSSLIOHandler;
{$IFDEF FPC}
{$mode delphi}
{$ENDIF}
interface
uses
SysUtils, Classes, ScVio,
{$IFNDEF SBRIDGE}
CRVio, CRTypes, CRFunctions,
{$ELSE}
ScTypes, ScFunctions, MemUtils,
{$ENDIF}
{$IFDEF MSWINDOWS}
ScCryptoAPIStorage,
{$ENDIF}
ScSSLTypes, ScUtils, ScSSLClient, ScBridge;
{$I SecureBridgeVer.inc}
type
{$IFDEF VER16P}
[ComponentPlatformsAttribute({$IFDEF STD}pidDevartWinPlatforms{$ELSE}pidDevartAllPlatforms{$ENDIF})]
{$ENDIF}
TCRSSLIOHandler = class (TCRIOHandler)
private
FCipherSuites: TScSSLCipherSuites;
FProtocols: TScSSLProtocols;
FStorage: TScStorage;
FCertName: string;
FCACertName: string;
FOnServerCertificateValidation: TScRemoteCertificateValidation;
FClientHelloExtensions: TTLSHelloExtensions;
FSecurityOptions: TScSSLSecurityOptions;
FMinDHEKeyLength: integer;
FCompression: TScCompression;
FDisableInsertEmptyFragment: boolean;
FSSLClient: TScSSLClient;
function GetSecure: boolean;
function CheckDefaultCipherSuites: boolean;
procedure SetCipherSuites(Value: TScSSLCipherSuites);
procedure SetStorage(Value: TScStorage);
procedure SetSecurityOptions(Value: TScSSLSecurityOptions);
procedure DoValidateServerCertDN(Sender: TObject;
ServerCertificate: TScCertificate; CertificateList: TCRList; var Errors: TScCertificateStatusSet);
procedure DoServerCertificateValidation(Sender: TObject;
ServerCertificate: TScCertificate; CertificateList: TCRList; var Errors: TScCertificateStatusSet);
protected
procedure Notification(Component: TComponent; Operation: TOperation); override;
class procedure SetIsSecure(Handle: TCRIOHandle; const Value: Boolean); override;
class function GetIsSecure(Handle: TCRIOHandle): Boolean; override;
class procedure Renegotiate(Handle: TCRIOHandle); override;
function GetHandlerType: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Connect(const Server: string; const Port: integer;
HttpOptions: THttpOptions; ProxyOptions: TProxyOptions;
SSLOptions: TSSLOptions; SSHOptions: TSSHOptions;
IPVersion: TIPVersion = ivIPv4): TCRIOHandle; override;
procedure Disconnect(Handle: TCRIOHandle); override;
class function ReadNoWait(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer; override;
class function Read(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer; override;
class function Write(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer; override;
class function WaitForData(Handle: TCRIOHandle; Timeout: integer = -1): boolean; override;
class function GetTimeout(Handle: TCRIOHandle): integer; override;
class procedure SetTimeout(Handle: TCRIOHandle; Value: integer); override;
property IsSecure: boolean read GetSecure;
property ClientHelloExtensions: TTLSHelloExtensions read FClientHelloExtensions;
published
property CipherSuites: TScSSLCipherSuites read FCipherSuites write SetCipherSuites stored CheckDefaultCipherSuites;
property Protocols: TScSSLProtocols read FProtocols write FProtocols default [spTls1, spTls11, spTls12];
// MySQL server 5.1.73 uses 512 bit
property MinDHEKeyLength: integer read FMinDHEKeyLength write FMinDHEKeyLength default 1024;
property Compession: TScCompression read FCompression write FCompression default csNone;
property DisableInsertEmptyFragment: boolean read FDisableInsertEmptyFragment write FDisableInsertEmptyFragment default True;
property SecurityOptions: TScSSLSecurityOptions read FSecurityOptions write SetSecurityOptions;
property Storage: TScStorage read FStorage write SetStorage;
property CertName: string read FCertName write FCertName;
property CACertName: string read FCACertName write FCACertName;
property OnServerCertificateValidation: TScRemoteCertificateValidation read FOnServerCertificateValidation write FOnServerCertificateValidation;
end;
implementation
uses
{$IFNDEF ODBC_DRIVER}
{$IFNDEF SBRIDGE}
CRAccess,
{$ENDIF}
CRSsoStorage,
{$ELSE}
ODBC_SsoStorage,
{$ENDIF}
ScConsts;
{ TCRSSLIOHandler }
constructor TCRSSLIOHandler.Create(AOwner: TComponent);
begin
inherited;
FClientHelloExtensions := TTLSHelloExtensions.Create;
FCipherSuites := TScSSLCipherSuites.Create(Self, TScSSLCipherSuiteItem);
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_AES_256_GCM_SHA384;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_AES_128_GCM_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_AES_256_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_AES_128_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_AES_256_CBC_SHA384;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_AES_128_CBC_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caECDHE_RSA_3DES_168_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_AES_256_GCM_SHA384;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_AES_128_GCM_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_AES_256_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_AES_128_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_AES_256_CBC_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_AES_128_CBC_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caDHE_RSA_3DES_168_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_AES_256_GCM_SHA384;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_AES_128_GCM_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_AES_256_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_AES_128_CBC_SHA;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_AES_256_CBC_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_AES_128_CBC_SHA256;
(FCipherSuites.Add as TScSSLCipherSuiteItem).CipherAlgorithm := caRSA_3DES_168_CBC_SHA;
FProtocols := [spTls1, spTls11, spTls12];
FSecurityOptions := TScSSLSecurityOptions.Create(FClientHelloExtensions);
FMinDHEKeyLength := 1024;
FDisableInsertEmptyFragment := True;
FCompression := csNone;
end;
destructor TCRSSLIOHandler.Destroy;
{$IFNDEF SBRIDGE}
{$IFNDEF ODBC_DRIVER}
var
con: TCRConnection;
i: integer;
{$ENDIF}
{$ENDIF}
begin
{$IFNDEF SBRIDGE}
{$IFNDEF ODBC_DRIVER}
for i := 0 to FList.Count - 1 do begin
if IsClass(TObject(FList[i]), TCRConnection) then begin
con := TCRConnection(FList[i]);
if con.GetConnected then
con.Disconnect;
end;
end;
{$ENDIF}
{$ENDIF}
FClientHelloExtensions.Free;
FCipherSuites.Free;
FSecurityOptions.Free;
inherited;
end;
function TCRSSLIOHandler.GetHandlerType: string;
begin
Result := 'ssl';
end;
function TCRSSLIOHandler.Connect(const Server: string; const Port: integer;
HttpOptions: THttpOptions; ProxyOptions: TProxyOptions;
SSLOptions: TSSLOptions; SSHOptions: TSSHOptions;
IPVersion: TIPVersion = ivIPv4): TCRIOHandle;
{$IFDEF ODBC_DRIVER}
function CreateSsoFileStorage(const WalletPath: string; SSLClient: TScSSLClient): TCRSsoFileStorage;
begin
Result := TCRSsoFileStorage.Create(SSLClient);
try
Result.SetFullWalletPath(WalletPath);
except
Result.Free;
raise;
end;
end;
{$IFDEF MSWINDOWS}
function CreateSsoRegStorage(const WalletReg: string; SSLClient: TScSSLClient): TCRSsoRegStorage;
begin
Result := TCRSsoRegStorage.Create(SSLClient);
try
Result.SetFullWalletRegPath(WalletReg);
except
Result.Free;
raise;
end;
end;
{$ENDIF}
{$ENDIF}
var
SSLClient: TScSSLClient;
Cert: TScCertificate;
begin
SSLClient := TScSSLClient.Create(nil);
try
if HttpOptions <> nil then
SSLClient.HttpOptions.Assign(HttpOptions);
if ProxyOptions <> nil then
SSLClient.ProxyOptions.Assign(ProxyOptions);
SSLClient.HostName := Server;
SSLClient.Port := Port;
SSLClient.CipherSuites := CipherSuites;
SSLClient.Protocols := Protocols;
SSLClient.MinDHEKeyLength := MinDHEKeyLength;
SSLClient.Compression := Compession;
SSLClient.DisableInsertEmptyFragment := DisableInsertEmptyFragment;
SSLClient.ClientHelloExtensions.Assign(ClientHelloExtensions);
{$IFNDEF ODBC_DRIVER}
SSLClient.SecurityOptions.Assign(SecurityOptions);
if SSLOptions.ForceUseTrustServerCertificate then
SSLClient.SecurityOptions.TrustServerCertificate := SSLOptions.TrustServerCertificate; //for VerifyCA, VerifyFull SSL mode PgDAC
{$ELSE}
SSLClient.SecurityOptions.IgnoreServerCertificateValidity := SSLOptions.IgnoreServerCertificateValidity;
SSLClient.SecurityOptions.IgnoreServerCertificateConstraints := SSLOptions.IgnoreServerCertificateConstraints;
SSLClient.SecurityOptions.IgnoreServerCertificateInsecurity := SSLOptions.IgnoreServerCertificateInsecurity; //RDS
SSLClient.SecurityOptions.TrustServerCertificate := SSLOptions.TrustServerCertificate;
{$ENDIF}
{$IFDEF SB_DEMO_VER2}
SSLClient.SecurityOptions.TrustSelfSignedCertificate := SSLOptions.TrustSelfSignedCertificate;
{$ENDIF}
SSLClient.SecurityOptions.IdentityDNSName := SSLOptions.IdentityDNSName;
SSLClient.SecurityOptions.ServerCertDN := SSLOptions.ServerCertDN;
{$IFDEF ODBC_DRIVER}
if SSLOptions.WalletPath <> '' then
SSLClient.Storage := CreateSsoFileStorage(SSLOptions.WalletPath, SSLClient)
else
{$IFDEF MSWINDOWS}
if SSLOptions.WalletReg <> '' then
SSLClient.Storage := CreateSsoRegStorage(SSLOptions.WalletReg, SSLClient)
else
{$ENDIF}
{$ENDIF}
if Storage <> nil then begin
SSLClient.Storage := Storage;
SSLClient.CACertName := CACertName;
SSLClient.CertName := CertName;
end
else begin
SSLClient.Storage := TScMemoryStorage.Create(SSLClient);
SSLClient.CACertName := '';
SSLClient.CertName := '';
end;
if (SSLClient.CACertName = '') and (SSLOptions.CA <> '') then begin
Cert := TScCertificate.Create(SSLClient.Storage.Certificates);
Cert.CertName := 'cacert' + IntToStr(SSLClient.Storage.Certificates.Count);
Cert.ImportFrom(SSLOptions.CA);
SSLClient.CACertName := Cert.CertName;
end;
if (SSLClient.CertName = '') and (SSLOptions.Cert <> '') then begin
Cert := TScCertificate.Create(SSLClient.Storage.Certificates);
Cert.CertName := 'cert' + IntToStr(SSLClient.Storage.Certificates.Count);
Cert.ImportFrom(SSLOptions.Cert);
if SSLOptions.Key <> '' then
Cert.Key.ImportFrom(SSLOptions.Key);
SSLClient.CertName := Cert.CertName;
end;
if (SSLClient.CACertName <> '') and not SSLClient.SecurityOptions.IgnoreServerCertificateInsecurity then
SSLClient.SecurityOptions.IgnoreServerCertificateInsecurity := True; //RDS
SSLClient.IPVersion := ScVio.TIPVersion(IPVersion);
SSLClient.OnServerCertificateValidation := DoServerCertificateValidation;
SSLClient.Connect;
except
SSLClient.Free;
raise;
end;
FSSLClient := SSLClient;
Result := SSLClient;
end;
procedure TCRSSLIOHandler.Disconnect(Handle: TCRIOHandle);
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Client.Connected := False;
FSSLClient := nil;
end;
class procedure TCRSSLIOHandler.Renegotiate(Handle: TCRIOHandle);
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Client.Renegotiate;
end;
class function TCRSSLIOHandler.ReadNoWait(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer;
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Result := Client.ReadNoWait(buffer[offset], count);
end;
class function TCRSSLIOHandler.Read(Handle: TCRIOHandle; const buffer: TValueArr; offset, count: integer): integer;
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Result := Client.ReadBuffer(buffer[offset], count);
end;
class function TCRSSLIOHandler.Write(Handle: TCRIOHandle;
const buffer: TValueArr; offset, count: integer): integer;
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Result := Client.WriteBuffer(buffer[offset], count);
end;
class function TCRSSLIOHandler.WaitForData(Handle: TCRIOHandle; Timeout: integer = -1): boolean;
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Result := Client.WaitForData(Timeout);
end;
class function TCRSSLIOHandler.GetTimeout(Handle: TCRIOHandle): integer;
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Result := Client.Timeout;
end;
class procedure TCRSSLIOHandler.SetTimeout(Handle: TCRIOHandle; Value: integer);
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Client.Timeout := Value;
end;
procedure TCRSSLIOHandler.Notification(Component: TComponent; Operation: TOperation);
begin
if (Component = FStorage) and (Operation = opRemove) then
Storage := nil;
inherited;
end;
class procedure TCRSSLIOHandler.SetIsSecure(Handle: TCRIOHandle; const Value: Boolean);
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Client.IsSecure := Value;
end;
class function TCRSSLIOHandler.GetIsSecure(Handle: TCRIOHandle): Boolean;
var
Client: TScSSLClient;
begin
Client := Handle as TScSSLClient;
Result := Client.IsSecure;
end;
function TCRSSLIOHandler.GetSecure: Boolean;
begin
if FSSLClient = nil then
Result := False
else
Result := FSSLClient.IsSecure;
end;
function TCRSSLIOHandler.CheckDefaultCipherSuites: boolean;
begin
Result := not ((FCipherSuites.Count = 21) and
(((FCipherSuites.Items[0] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_AES_256_GCM_SHA384) and
((FCipherSuites.Items[1] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_AES_128_GCM_SHA256) and
((FCipherSuites.Items[2] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_AES_256_CBC_SHA) and
((FCipherSuites.Items[3] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_AES_128_CBC_SHA) and
((FCipherSuites.Items[4] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_AES_256_CBC_SHA384) and
((FCipherSuites.Items[5] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_AES_128_CBC_SHA256) and
((FCipherSuites.Items[6] as TScSSLCipherSuiteItem).CipherAlgorithm = caECDHE_RSA_3DES_168_CBC_SHA) and
((FCipherSuites.Items[7] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_AES_256_GCM_SHA384) and
((FCipherSuites.Items[8] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_AES_128_GCM_SHA256) and
((FCipherSuites.Items[9] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_AES_256_CBC_SHA) and
((FCipherSuites.Items[10] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_AES_128_CBC_SHA) and
((FCipherSuites.Items[11] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_AES_256_CBC_SHA256) and
((FCipherSuites.Items[12] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_AES_128_CBC_SHA256) and
((FCipherSuites.Items[13] as TScSSLCipherSuiteItem).CipherAlgorithm = caDHE_RSA_3DES_168_CBC_SHA) and
((FCipherSuites.Items[14] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_AES_256_GCM_SHA384) and
((FCipherSuites.Items[15] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_AES_128_GCM_SHA256) and
((FCipherSuites.Items[16] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_AES_256_CBC_SHA) and
((FCipherSuites.Items[17] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_AES_128_CBC_SHA) and
((FCipherSuites.Items[18] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_AES_256_CBC_SHA256) and
((FCipherSuites.Items[19] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_AES_128_CBC_SHA256) and
((FCipherSuites.Items[20] as TScSSLCipherSuiteItem).CipherAlgorithm = caRSA_3DES_168_CBC_SHA)
));
end;
procedure TCRSSLIOHandler.SetCipherSuites(Value: TScSSLCipherSuites);
begin
if Value <> FCipherSuites then
FCipherSuites.Assign(Value);
end;
procedure TCRSSLIOHandler.SetStorage(Value: TScStorage);
begin
if FStorage <> Value then begin
if FStorage <> nil then
FStorage.RemoveFreeNotification(Self);
FStorage := Value;
if Value <> nil then
Value.FreeNotification(Self);
end;
end;
procedure TCRSSLIOHandler.SetSecurityOptions(Value: TScSSLSecurityOptions);
begin
FSecurityOptions.Assign(Value);
end;
procedure TCRSSLIOHandler.DoValidateServerCertDN(Sender: TObject;
ServerCertificate: TScCertificate; CertificateList: TCRList; var Errors: TScCertificateStatusSet);
var
i: Integer;
SSLClient: TScSSLClient;
RemoteCertDN: string;
ServerCertDN: string;
RemoteCertDNList: TStringList;
ServerCertDNList: TStringList;
RemoteAttr: string;
ServerAttr: string;
begin
SSLClient := Sender as TScSSLClient;
ServerCertDN := SSLClient.SecurityOptions.ServerCertDN;
if ServerCertDN = '' then
Exit;
if ServerCertificate = nil then begin
Errors := Errors + [csInvalidSubjectName];
Exit;
end;
if CertificateList = nil then begin
Errors := Errors + [csUnknownCriticalExtension];
Exit;
end;
RemoteCertDNList := TStringList.Create;
try
RemoteCertDN := ServerCertificate.SubjectName.ToString;
RemoteCertDN := StringReplace(RemoteCertDN, ';', #13, [rfReplaceAll]);
RemoteCertDNList.Text := RemoteCertDN;
for i := 0 to RemoteCertDNList.Count - 1 do begin
RemoteAttr := Trim(RemoteCertDNList.Strings[i]);
RemoteCertDNList.Strings[i] := RemoteAttr;
end;
RemoteCertDNList.Sort;
ServerCertDNList := TStringList.Create;
try
ServerCertDN := StringReplace(ServerCertDN, ',', #13, [rfReplaceAll]);
ServerCertDNList.Text := ServerCertDN;
for i := 0 to ServerCertDNList.Count - 1 do begin
ServerAttr := Trim(ServerCertDNList.Strings[i]);
ServerAttr := StringReplace(ServerAttr, 'ST=', 'S=', []);
ServerCertDNList.Strings[i] := ServerAttr;
end;
ServerCertDNList.Sort;
if RemoteCertDNList.Count <> ServerCertDNList.Count then begin
Errors := Errors + [csInvalidSubjectName];
Exit;
end;
for i := 0 to ServerCertDNList.Count - 1 do begin
RemoteAttr := RemoteCertDNList.Strings[i];
ServerAttr := ServerCertDNList.Strings[i];
if RemoteAttr <> ServerAttr then begin
Errors := Errors + [csInvalidSubjectName];
Exit;
end;
end;
finally
ServerCertDNList.Free;
end;
finally
RemoteCertDNList.Free;
end;
end;
procedure TCRSSLIOHandler.DoServerCertificateValidation(Sender: TObject;
ServerCertificate: TScCertificate; CertificateList: TCRList; var Errors: TScCertificateStatusSet);
begin
DoValidateServerCertDN(Sender, ServerCertificate, CertificateList, Errors);
if Assigned(FOnServerCertificateValidation) then
FOnServerCertificateValidation(Self, ServerCertificate, CertificateList, Errors);
end;
end. |
unit LuaStrings;
interface
Uses Classes, Types, Controls, Contnrs, LuaPas, Forms, StdCtrls, FileCtrl, TypInfo;
procedure TStringsToTable(L: Plua_State; Comp:TObject; PInfo:PPropInfo; index: Integer);
type
TLuaStrings = class(TStrings)
published
Property TextLineBreakStyle;
property Delimiter;
property DelimitedText;
Property StrictDelimiter;
property QuoteChar;
Property NameValueSeparator;
// property ValueFromIndex[Index: Integer]: string read GetValueFromIndex write SetValueFromIndex;
property Capacity;
property CommaText;
property Count;
// property Names[Index: Integer]: string read GetName;
// property Objects[Index: Integer]: TObject read GetObject write PutObject;
// property Values[const Name: string]: string read GetValue write SetValue;
// property Strings[Index: Integer]: string read Get write Put; default;
property Text;
property StringsAdapter;
end;
implementation
Uses SysUtils, LuaProperties, Lua, SynEdit, CheckLst, Dialogs;
function StringsAdd(L: Plua_State): Integer; cdecl;
var
lStrings: TStrings;
begin
CheckArg(L, 2);
lStrings := TStrings(GetLuaObject(L, 1));
lStrings.Add(AnsiToUTF8(lua_tostring(L,2)));
Result := 0;
end;
function StringsInsert(L: Plua_State): Integer; cdecl;
var
lStrings: TStrings;
begin
CheckArg(L, 3);
lStrings := TStrings(GetLuaObject(L, 1));
lStrings.Insert(Trunc(lua_tonumber(L,2)),AnsiToUTF8(lua_tostring(L,3)));
Result := 0;
end;
function StringsDelete(L: Plua_State): Integer; cdecl;
var
lStrings: TStrings;
begin
CheckArg(L, 2);
lStrings := TStrings(GetLuaObject(L, 1));
lStrings.Delete(Trunc(lua_tonumber(L,2)));
Result := 0;
end;
function StringsClear(L: Plua_State): Integer; cdecl;
var
lStrings: TStrings;
begin
CheckArg(L, 1);
lStrings := TStrings(GetLuaObject(L, 1));
lStrings.Clear;
Result := 0;
end;
procedure TStringsToTable(L: Plua_State; Comp:TObject; PInfo:PPropInfo; index: Integer);
begin
lua_newtable(L);
LuaSetTableLightUserData(L, index, HandleStr, Pointer(GetInt64Prop(Comp, PInfo.Name)));
LuaSetTableFunction(L, Index, 'Add', StringsAdd);
LuaSetTableFunction(L, Index, 'Insert', StringsInsert);
LuaSetTableFunction(L, Index, 'Delete', StringsDelete);
LuaSetTableFunction(L, Index, 'Clear', StringsClear);
LuaSetMetaFunction(L, index, '__index', LuaGetProperty);
LuaSetMetaFunction(L, index, '__newindex', LuaSetProperty);
end;
end.
|
unit Fonetiza.CodigoFonetico.Core;
interface
uses System.SysUtils;
type
TCodigoFoneticoCore = class
public
function removeElement(var pArray: TArray<string>; const pIndex: integer): boolean;
function fonreg(const i03: Int64): TCharArray;
function tabNor(const str: string): string;
function tabEbc(const str: string): string;
function randomic(const str: string): Int64;
function randomize(const str: string): string;
function generateCodes(const str: string): TArray<String>;
function permutations(const size: Integer): TArray<TArray<Boolean>>;
function allPermutations: TArray<TArray<TArray<Boolean>>>;
end;
implementation
uses System.Classes;
{ TCodigoFoneticoCore }
const
powersOfTwo: TArray<Integer> = [1, 2, 4, 8, 16, 32];
function TCodigoFoneticoCore.allPermutations: TArray<TArray<TArray<Boolean>>>;
begin
Result := [permutations(1), permutations(2), permutations(3), permutations(4), permutations(5)];
end;
function TCodigoFoneticoCore.fonreg(const i03: Int64): TCharArray;
var
i01, i02: Int64;
fonaux: TCharArray;
begin
SetLength(fonaux, 4);
i02 := i03;
fonaux[3] := char(i02 mod $0100);
i01 := (i02 - Ord(fonaux[3])) div $0100;
fonaux[2] := char(i01 mod $0100);
i02 := (i01 - Ord(fonaux[2])) div $0100;
fonaux[1] := char(i02 mod $0100);
i01 := (i02 - Ord(fonaux[1])) div $0100;
fonaux[0] := char(i01 mod $0100);
Result := fonaux;
end;
function TCodigoFoneticoCore.permutations(const size: Integer): TArray<TArray<Boolean>>;
var
i, j: integer;
begin
if size > 5 then
raise Exception.Create('Invalid argument. size must be <= 5');
SetLength(Result, Pred(powersOfTwo[size]), size);
for i := 0 to Pred(Length(Result)) do
for j := 0 to Pred(size) do
result[i][j] := ((i + 1) and powersOfTwo[j]) > 0;
end;
function TCodigoFoneticoCore.removeElement(var pArray: TArray<string>; const pIndex: integer): boolean;
var
i :integer;
begin
Result := (pIndex <= High(pArray)) and (pIndex >= Low(pArray));
if not Result then
raise EListError.Create(Format('List index is out of bounds (%s).', [pIndex]))
else
begin
for i := pIndex to Pred(High(pArray)) do
pArray[i] := pArray[i + 1];
SetLength(pArray, Pred(Length(pArray)));
Result := True;
end;
end;
function TCodigoFoneticoCore.generateCodes(const str: string): TArray<String>;
var
i, j, size, index: Integer;
return: TStringList;
palavras, subPalavras: TArray<string>;
permutations: TArray<TArray<Boolean>>;
palavra, subNome: string;
begin
palavras := str.Split([' ']);
return := TStringList.Create;
try
if Length(palavras) > 5 then
return.add(Self.randomize(str)); // adiciona o nome completo, mesmo grandao
while Length(palavras) > 5 do
begin
index := Length(palavras) div 2;
palavra := palavras[index];
removeElement(palavras, index); // remove um nome do meio
return.add(Self.randomize(palavra)); // adiciona o codigo da palavra removida
end;
size := Length(palavras);
permutations := allPermutations[Pred(size)];
for i := 0 to Pred(Length(permutations)) do
begin
SetLength(subPalavras, 0);
for j := 0 to Pred(size) do
begin
if permutations[i][j] then
begin
SetLength(subPalavras, Succ(Length(subPalavras)));
subPalavras[Pred(Length(subPalavras))] := palavras[j];
end;
end;
subNome := EmptyStr;
for palavra in subPalavras do
begin
if not subNome.Trim.IsEmpty then
subNome := subNome + ' ';
subNome := subNome + palavra;
end;
return.add(Self.randomize(subNome));
end;
SetLength(Result, return.Count);
for I := 0 to Pred(return.Count) do
Result[I] := return[I];
finally
return.Free;
end;
end;
function TCodigoFoneticoCore.randomic(const str: string): Int64;
var
i: integer;
i01, i02: Int64;
fonaux: TCharArray;
begin
SetLength(fonaux, 256);
if str.Length > 1 then
begin
fonaux := str.ToCharArray;
i01 := (Ord(fonaux[0]) * $0100) + Ord(fonaux[1]);
for i := 1 to 255 do
begin
if i = Pred(str.Length) then
Break;
i02 := (Ord(fonaux[i]) * $0100) + Ord(fonaux[i + 1]);
i01 := i01 * i02;
i01 := i01 shr 8;
end;
end
else
begin
fonaux := str.ToCharArray;
i01 := Ord(fonaux[0]) * $0100;
i01 := i01 shr 8;
end;
Result := i01;
end;
function TCodigoFoneticoCore.randomize(const str: string): string;
var
lchar: char;
w0, w1: Integer; // inteiros utilizados para operacoes de shift
i, j, k: Integer; // contadores
fon09, fon11, fon12: Int64; // inteiros utilizados para manipular o codigo
reg09, reg11, reg12: TCharArray; // matrizes de caracteres utilizadas para manipular o codigo
fonrnd, finalRand: TCharArray; // estruturas que armazenam o codigo
work: TCharArray; // variavel de manipulacao
foncmp, fonaux: TCharArray; // matrizes de manipulacao
priStr, auxStr, modStr, rand: string; // string de manipulacao
component: TArray<string>; // texto eh armazenado no vetor
begin
// gera um codigo identificador de 10 caracteres para um texto qualquer
Result := EmptyStr;
fon09 := 0;
fon11 := 0;
fon12 := 0;
SetLength(reg09, 4);
SetLength(reg11, 4);
SetLength(reg12, 4);
SetLength(fonrnd, 5);
SetLength(finalRand, 10);
SetLength(work, 2);
SetLength(foncmp, 256);
SetLength(fonaux, 256);
component := str.Split([' ']);
// percorre o texto, palavra a palavra
for i := 0 to Pred(Length(component)) do
begin
auxStr := component[i];
foncmp := auxStr.ToCharArray;
// se a palavra nao for vazia
if foncmp[0] <> ' ' then
begin
// branqueia matriz
for j := 0 to 255 do
fonaux[j] := ' ';
j := 0;
// percorre a palavra, letra a letra
while j < auxStr.Length do
begin
// se a palavra iniciar por vogal, insere um "R" no inicio da palavra
if ((foncmp[0] = 'I') or (foncmp[0] = 'A') or (foncmp[0] = 'U')) then
begin
fonaux[0] := 'R';
for j := 0 to Pred(auxStr.Length) do
fonaux[j + 1] := foncmp[j];
end
else
begin
// se a palavra iniciar com "GI", suprime o "G"
if ((foncmp[0] = 'G') and (auxStr.Length > 1)) then
begin
if (foncmp[1] = 'I') then
begin
for j := 0 to auxStr.Length - 2 do
fonaux[j] := foncmp[j + 1];
Inc(J);
end
else
begin
// senao apenas copia a palavra original
for j := 0 to Pred(auxStr.Length) do
fonaux[j] := foncmp[j];
end;
end
else
begin
// senao apenas copia a palavra original
for j := 0 to Pred(auxStr.Length) do
fonaux[j] := foncmp[j];
end;
end;
end;
auxStr := EmptyStr; // >>>>>>>> ADDED BY VINICIUS
for lchar in fonaux do
auxStr := auxStr + lchar;
auxStr := auxStr.Trim;
foncmp := auxStr.ToCharArray;
for j := 0 to 255 do
fonaux[j] := ' ';
j := 0;
k := 0;
// percorre a palavra, letra a letra
while j < auxStr.Length do
begin
// se a palavra terminar com BI, DI, FI, GI, JI, PI, KI, TI ou VI suprime estas silabas da palavra
if ((j + 2 = auxStr.Length) and (j <> 0) and ((foncmp[j] = 'B') or (foncmp[j] = 'D') or (foncmp[j] = 'F')
or (foncmp[j] = 'G') or (foncmp[j] = 'J') or (foncmp[j] = 'P') or (foncmp[j] = 'K') or (foncmp[j] = 'T') or (foncmp[j] = 'V'))) then
begin
if foncmp[j + 1] = 'I' then
j := j + 2
else
begin
fonaux[k] := foncmp[j];
Inc(j);
Inc(k);
end;
end
// NI+vogal ou LI+vogal = N+vogal ou L+vogal
else if ((j + 3 <= auxStr.Length) and ((foncmp[j] = 'N') or (foncmp[j] = 'L'))) then
begin
if ((foncmp[j + 1] = 'I') and ((foncmp[j + 2] = 'A') or (foncmp[j + 2] = 'E') or (foncmp[j + 2] = 'O') or (foncmp[j + 2] = 'U'))) then
begin
fonaux[k] := foncmp[j];
fonaux[k + 1] := foncmp[j + 2];
j := j + 3;
k := k + 2;
end
else
begin
fonaux[k] := foncmp[j];
Inc(J);
Inc(K);
end;
end
// vogal+R final = vogal
else if ((foncmp[j] = 'R') and (j > 0)) then
begin
if ((foncmp[j - 1] <> 'A') and (foncmp[j - 1] <> 'E') and (foncmp[j - 1] <> 'I') and (foncmp[j - 1] <> 'O') and (foncmp[j - 1] <> 'U')) then
Inc(J)
else
begin
fonaux[k] := foncmp[j];
Inc(J);
Inc(K);
end;
end
else
begin
fonaux[k] := foncmp[j];
Inc(J);
Inc(K);
end;
end;
auxStr := EmptyStr; // >>>>>>>> ADDED BY VINICIUS
for lchar in fonaux do
auxStr := auxStr + lchar;
auxStr := auxStr.Trim;
foncmp := auxStr.ToCharArray;
for j := 0 to 255 do
fonaux[j] := ' ';
// percorre a palavra, letra a letra
for j := 0 to Pred(auxStr.Length) do
begin
// se a letra for "V", substitui por "F"
if foncmp[j] = 'V' then
fonaux[j] := 'F'
else if ((foncmp[j] = 'X') or (foncmp[j] = 'Z') or (foncmp[j] = 'K')) then // se a letra for "X","Z" ou "K", substitui por "S"
fonaux[j] := 'S'
else if foncmp[j] = 'G' then // G -> D
fonaux[j] := 'D'
else
fonaux[j] := foncmp[j];
end;
end;
auxStr := EmptyStr; // >>>>>>>> ADDED BY VINICIUS
for lchar in fonaux do
auxStr := auxStr + lchar;
auxStr := auxStr.Trim;
// a palavra eh recolocada, modificada, no vetor que contem o texto
component[I] := auxStr;
end;
// percorre o texto, palavra a palavra
for i := 0 to Pred(Length(component)) do
begin
auxStr := component[i];
// considera somente as primeiras 7 letras da palavra
if auxStr.Length > 7 then
begin
foncmp := auxStr.ToCharArray;
for j := 7 to Pred(auxStr.Length) do
foncmp[j] := ' ';
for lchar in foncmp do
auxStr := auxStr + lchar;
auxStr := auxStr.Trim;
component[I] := auxStr;
end;
// componentes do codigo sao calculados
fon11 := fon11 + randomic(tabEbc(auxStr));
fon12 := fon12 + randomic(tabNor(tabEbc(auxStr)));
end;
component := str.Split([' ']);
// percorre o texto, palavra a palavra
for i := 0 to Pred(Length(component)) do
fon09 := fon09 + randomic(component[i]); // componente do codigo eh calculado
// monta o codigo identificador do texto
reg09 := fonreg(fon09);
reg11 := fonreg(fon11);
reg12 := fonreg(fon12);
fonrnd[0] := reg12[2];
fonrnd[1] := reg11[1];
fonrnd[2] := reg11[2];
if ((fonrnd[0] = '0') and (fonrnd[1] = '0') and (fonrnd[2] = '0')) then
begin
fonrnd[0] := reg12[1];
fonrnd[1] := reg11[0];
fonrnd[2] := reg11[3];
end;
fonrnd[3] := reg09[1];
fonrnd[4] := reg09[2];
if ((fonrnd[3] = '0') and (fonrnd[4] = '0')) then
begin
fonrnd[3] := reg09[0];
fonrnd[4] := reg09[3];
if ((fonrnd[3] = '0') and (fonrnd[4] = '0')) then
begin
fon09 := fon11 + fon12;
reg09 := fonreg(fon09);
fonrnd[3] := reg09[1];
fonrnd[4] := reg09[2];
end;
end;
j := 0;
for i := 0 to 4 do
begin
auxStr := fonrnd[i];
w0 := Ord(fonrnd[i]);
w0 := w0 shr 4;
work[0] := char(w0);
if Ord(work[0]) <= $0009 then
finalRand[j] := char(Ord(work[0]) + 48)
else
finalRand[j] := char(Ord(work[0]) - 10 + 97);
w1 := Ord(fonrnd[i]);
w1 := w1 shl 28;
w0 := w1 shr 28;
work[0] := char(w0);
if Ord(work[0]) <= $0009 then
finalRand[j + 1] := char(Ord(work[0]) + 48)
else
finalRand[j + 1] := char(Ord(work[0]) - 10 + 97);
j := j + 2;
end;
for lchar in finalRand do
Result := Result + lchar;
end;
function TCodigoFoneticoCore.tabEbc(const str: string): string;
var
i: integer;
fonaux: TCharArray;
lchar: char;
begin
Result := EmptyStr;
SetLength(fonaux, 256);
fonaux := str.ToCharArray;
for i := 0 to Pred(str.Length) do
begin
case fonaux[i] of
'A':
fonaux[i] := Char($00c1);
'B':
fonaux[i] := Char($00c2);
'C':
fonaux[i] := Char($00c3);
'D':
fonaux[i] := Char($00c4);
'E':
fonaux[i] := Char($00c5);
'F':
fonaux[i] := Char($00c6);
'G':
fonaux[i] := Char($00c7);
'H':
fonaux[i] := Char($00c8);
'I':
fonaux[i] := Char($00c9);
'J':
fonaux[i] := Char($00d1);
'K':
fonaux[i] := Char($00d2);
'L':
fonaux[i] := Char($00d3);
'M':
fonaux[i] := Char($00d4);
'N':
fonaux[i] := Char($00d5);
'O':
fonaux[i] := Char($00d6);
'P':
fonaux[i] := Char($00d7);
'Q':
fonaux[i] := Char($00d8);
'R':
fonaux[i] := Char($00d9);
'S':
fonaux[i] := Char($00e2);
'T':
fonaux[i] := Char($00e3);
'U':
fonaux[i] := Char($00e4);
'V':
fonaux[i] := Char($00e5);
'W':
fonaux[i] := Char($00e6);
'X':
fonaux[i] := Char($00e7);
'Y':
fonaux[i] := Char($00e8);
'Z':
fonaux[i] := Char($00e9);
'0':
fonaux[i] := Char($00f0);
'1':
fonaux[i] := Char($00f1);
'2':
fonaux[i] := Char($00f2);
'3':
fonaux[i] := Char($00f3);
'4':
fonaux[i] := Char($00f4);
'5':
fonaux[i] := Char($00f5);
'6':
fonaux[i] := Char($00f6);
'7':
fonaux[i] := Char($00f7);
'8':
fonaux[i] := Char($00f8);
'9':
fonaux[i] := Char($00f9);
else
fonaux[i] := Char($0040);
end;
end;
for lchar in fonaux do
Result := Result + lchar;
end;
function TCodigoFoneticoCore.tabNor(const str: string): string;
var
i: integer;
fonaux: TCharArray;
lchar: Char;
begin
Result := EmptyStr;
SetLength(fonaux, 256);
fonaux := str.ToCharArray;
for i := 0 to Pred(str.Length) do
begin
case fonaux[i] of
Char($00c1):
fonaux[i] := Char($0013);
Char($00c2):
fonaux[i] := Char($0016);
Char($00c3):
fonaux[i] := Char($0019);
Char($00c4):
fonaux[i] := Char($001c);
Char($00c5):
fonaux[i] := Char($0011);
Char($00c6):
fonaux[i] := Char($0014);
Char($00c7):
fonaux[i] := Char($0017);
Char($00c8):
fonaux[i] := Char($001a);
Char($00c9):
fonaux[i] := Char($001d);
Char($00d1):
fonaux[i] := Char($0033);
Char($00d2):
fonaux[i] := Char($0036);
Char($00d3):
fonaux[i] := Char($0039);
Char($00d4):
fonaux[i] := Char($003c);
Char($00d5):
fonaux[i] := Char($0031);
Char($00d6):
fonaux[i] := Char($0034);
Char($00d7):
fonaux[i] := Char($0037);
Char($00d8):
fonaux[i] := Char($003a);
Char($00d9):
fonaux[i] := Char($003d);
Char($00e2):
fonaux[i] := Char($0053);
Char($00e3):
fonaux[i] := Char($0056);
Char($00e4):
fonaux[i] := Char($0059);
Char($00e5):
fonaux[i] := Char($005c);
Char($00e6):
fonaux[i] := Char($0054);
Char($00e7):
fonaux[i] := Char($0057);
Char($00e8):
fonaux[i] := Char($005a);
Char($00e9):
fonaux[i] := Char($005d);
Char($00f0):
fonaux[i] := Char($0070);
Char($00f1):
fonaux[i] := Char($0071);
Char($00f2):
fonaux[i] := Char($0072);
Char($00f3):
fonaux[i] := Char($0073);
Char($00f4):
fonaux[i] := Char($0074);
Char($00f5):
fonaux[i] := Char($0075);
Char($00f6):
fonaux[i] := Char($0076);
Char($00f7):
fonaux[i] := Char($0077);
Char($00f8):
fonaux[i] := Char($0078);
Char($00f9):
fonaux[i] := Char($0079);
else
fonaux[i] := Char($0040);
end;
end;
for lchar in fonaux do
Result := Result + lchar;
end;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x53;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
implementation
Uses SysUtils;
(*
Type $53 - Barometric Sensors
Buffer[0] = packetlength = $09;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = baro1
Buffer[7] = baro2
Buffer[8] = forecast
Buffer[9] = battery_level:4/rssi:4
xPL Schema
sensor.basic
{
device=baro 0x<hex sensor id>
type=pressure
current=<hPa>
units=hpa
forecast=sunny|partly cloudy|cloudy|rain
}
sensor.basic
{
device=baro 0x<hex sensor id>
type=battery
current=0-100
}
*)
const
// Type
BAROMETER = $53;
// Subtype
BARO1 = $01;
// TO CHECK : what is subtype here ?
// Forecast
FC_NOT_AVAILABLE = $00;
FC_SUNNY = $01;
FC_PARTLY_CLOUDY = $02;
FC_CLOUDY = $03;
FC_RAIN = $04;
// Forecast strings
FC_NOT_AVAILABLE_STR = '';
FC_SUNNY_STR = 'sunny';
FC_PARTLY_CLOUDY_STR = 'partly cloudy';
FC_CLOUDY_STR = 'cloudy';
FC_RAIN_STR = 'rain';
var
SubTypeArray : array[1..1] of TRFXSubTypeRec =
((SubType : BARO1; SubTypeString : 'baro1'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
DeviceID : String;
SubType : String;
Pressure : Integer;
Forecast : String;
BatteryLevel : Integer;
xPLMessage : TxPLMessage;
begin
DeviceID := GetSubTypeString(Buffer[2],SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2);
Pressure := (Buffer[6] shl 8) + Buffer[7];
case Buffer[8] of
FC_NOT_AVAILABLE : Forecast := FC_NOT_AVAILABLE_STR;
FC_SUNNY : Forecast := FC_SUNNY_STR;
FC_PARTLY_CLOUDY : Forecast := FC_PARTLY_CLOUDY_STR;
FC_CLOUDY : Forecast := FC_CLOUDY_STR;
FC_RAIN : Forecast := FC_RAIN_STR;
end;
if (Buffer[9] and $0F) = 0 then // zero out rssi
BatteryLevel := 0
else
BatteryLevel := 100;
// Create sensor.basic messages
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('pressure='+IntToStr(Pressure));
xPLMessage.Body.AddKeyValue('forecast='+Forecast);
xPLMessage.Body.AddKeyValue('type=pressure');
xPLMEssage.Body.AddKeyValue('units=hpa');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel));
xPLMessage.Body.AddKeyValue('type=battery');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
end.
|
{
@html(<b>)
RTC Script Engine
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
This unit implements the RTC Scripting Engine.
}
unit rtcScript;
interface
{$include rtcDefs.inc}
uses
SysUtils, Classes, Windows,
rtcInfo, rtcFunction, rtcConn, rtcDataSrv,
rtcScriptCompile;
type
// @exclude
TRtcScriptCommandInfo=class(TRtcCommandInfo)
public
Globals,Locals: TRtcRecord;
MaxDepth, MaxRecurse, MaxLoop:cardinal;
StopTime, CodeDepth, RecurseCount: cardinal;
end;
{ @abstract(RTC Script Engine) }
TRtcScriptEngine=class(TRtcAbsCommand)
private
FGroup: TRtcFunctionGroup;
FDenyRTCFunctionCalls: boolean;
FDenyScriptFunctionCalls: boolean;
FMaxLoopCount,
FMaxExecutionTime,
FMaxRecursion,
FMaxCodeDepth: cardinal;
FScriptOpen: string;
FScriptClose: string;
procedure SetScriptClose(const Value: string);
procedure SetScriptOpen(const Value: string);
protected
// @exclude
function Call_Execute(const CmdInfo:TRtcCommandInfo; const Param:TRtcFunctionInfo; const Res:TRtcValue):boolean; override;
// @exclude
function Function_Exists(const Function_Name:string):boolean; override;
public
// @exclude
constructor Create(AOwner:TComponent); override;
// @exclude
destructor Destroy; override;
{ Compile a Script string and return a compiled script object.
Unless you pass the object to Execute(), in which case the
object will be destroyed by the Execute() method, you have to
take care of the compiled object (destroy it when not needed).
If you are running complex scripts which take time to compile,
you can compile the script(s) once (store in your variables).
You can then send a copy of your script object to Execute() by
using the ".copyOf" method on your script object ...
Execute(Sender, Script.CopyOf);
... this way, you are keeping the (original) compiled script. }
function Compile(const Script:string; const FileName:string=''):TRtcValue;
{ Execute Compiled Script object and return plain data object.
You can call "asString" on the result object to get the string,
or traverse through the resulting object to get to every element.
NOTE: Script passed as a parameter will always be destroyed,
even if an exception was raised during script execution.
This means that you can safely pass the result from Compile() to Execute().
If you want to keep the compiled script which you are using for execution,
you HAVE TO make a copy before using it in Execute().
If you are running complex scripts which take a long time to compile,
you can compile the script(s) once (store in your variables),
then send a copy of your script object to Execute() by
using the ".copyOf" method on your script object ...
Execute(Sender, Script.CopyOf);
... this way, you are keeping the original script object. }
function Execute(const Sender:TRtcConnection; const CompiledScript:TRtcValueObject; recursive:boolean=False):TRtcValue;
published
{ To make your RTC functions accessible from your Scripts, write your functions
using TRtcFunction components, assign them to a TRtcFunctiongroup component,
then assign this TRtcFunctionGroup component here (FunctionGroup).
If a FunctionGroup is assigned before compilation, each function name
used in script will be checked (does the function exist?), and an exception
will be raised if the Function does NOT exist in the assigned FunctionGroup.
If you do NOT assign a FunctionGroup and try to execute a compiled script
which is calling a RTC Function, an exception will be raised during Script execution. }
property FunctionGroup:TRtcFunctionGroup read FGroup write FGroup;
{ If you set DenyRTCFunctionCalls to TRUE, any attempts to call a RTC function
(implemented using TRtcFunction and TRtcFunctionGroup components) from within
the Script will fail and an exception will be raised. }
property DenyRTCFunctionCalls:boolean read FDenyRTCFunctionCalls write FDenyRTCFunctionCalls default False;
{ If you set DenyScriptFunctionCalls to TRUE, any attempts to define a Script function
(functions implemented inside the script) will fail (exception) during script compilation. }
property DenyScriptFunctionCalls:boolean read FDenyScriptFunctionCalls write FDenyScriptFunctionCalls default False;
{ Characters used to open a script block (default = <? ).
There always need to be exectly 2 characters for this,
and only a subset of character combinations is allowed. }
property ScriptOpen:string read FScriptOpen write SetScriptOpen;
{ Characters used to close a script block (default = ?> ).
There always need to be exectly 2 characters for this,
and only a subset of character combinations is allowed. }
property ScriptClose:string read FScriptClose write SetScriptClose;
{ Safety feature "Max code depth":
Maximum allowed code depth inside Script (example: [(1 + 2) + 3] => 2 calls deep).
Default value = 0 (no limit) }
property MaxCodeDepth:cardinal read FMaxCodeDepth write FMaxCodeDepth default 0;
{ Safety feature "Max Recursion":
Maximum allowed recursive calls from inside Script.
If a script should try to enter more than this number of recursions,
an exception will be raised and execution aborted.
Default value = 0 (no limit) }
property MaxRecursion:cardinal read FMaxRecursion write FMaxRecursion default 0;
{ Safety feature: "Max Loop Count":
Maximum allowed number of loops inside a single repeat/until, for or while statement.
If a script should try to run a single loop for more than specified count,
an exception will be raised and execution aborted.
Default value = 0 (no limit) }
property MaxLoopCount:cardinal read FMaxLoopCount write FMaxLoopCount default 0;
{ Safety feature: "Max Execution Time":
Maximum alowed single script execution time (seconds).
If a script should try to run for longer than specified time,
an exception will be raised and exection aborted.
This is a safety feature to prevent you from having to restart the
Server should there be a problem in one of your scripts (endless loops?)
Default value = 0 (no limit). }
property MaxExecutionTime:cardinal read FMaxExecutionTime write FMaxExecutionTime default 0;
end;
implementation
uses Math;
{ TRtcScriptEngine }
constructor TRtcScriptEngine.Create(AOwner: TComponent);
begin
inherited;
FScriptOpen:='<?';
FScriptClose:='?>';
FGroup:=nil;
FDenyRTCFunctionCalls:=False;
FDenyScriptFunctionCalls:=False;
end;
destructor TRtcScriptEngine.Destroy;
begin
FGroup:=nil;
inherited;
end;
function TRtcScriptEngine.Function_Exists(const Function_Name: string): boolean;
begin
Result:=(Function_Name='!') or // commands
(Function_Name='@') or // code block
(Function_Name='?') or // functions
(Function_Name='$') or // read variable
(Function_Name='$.') or // property
(Function_Name='$!'); // assign to variable
end;
function TRtcScriptEngine.Call_Execute(const CmdInfo: TRtcCommandInfo;
const Param: TRtcFunctionInfo;
const Res: TRtcValue): boolean;
var
Comm:TRtcScriptCommandInfo;
func:string;
obj,objB:TRtcValue;
ctype:TRtcValueTypes;
function GetAsString(const obj:TRtcValueObject):string;
begin
if obj is TRtcSimpleValue then
Result:=TRtcSimpleValue(obj).GetString
else if obj is TRtcValue then
Result:=TRtcValue(obj).asString
else if obj is TRtcArray then
Result:=TRtcArray(obj).GetAsString
else if obj is TRtcRecord then
Result:=TRtcRecord(obj).GetAsString
else if obj is TRtcDataSet then
Result:=TRtcDataSet(obj).GetAsString
else
raise EConvertError.Create('Can not convert '+obj.ClassName+' to String.');
end;
function GetAsBoolean(const obj:TRtcValueObject):boolean;
begin
if obj is TRtcSimpleValue then
Result:=TRtcSimpleValue(obj).GetBoolean
else if obj is TRtcValue then
Result:=TRtcValue(obj).asBoolean
else
raise EConvertError.Create('Can not convert '+obj.ClassName+' to Boolean.');
end;
function GetAsInteger(const obj:TRtcValueObject):Longint;
begin
if obj is TRtcSimpleValue then
Result:=TRtcSimpleValue(obj).GetInteger
else if obj is TRtcValue then
Result:=TRtcValue(obj).asInteger
else
raise EConvertError.Create('Can not convert '+obj.ClassName+' to Integer.');
end;
function GetAsInt64(const obj:TRtcValueObject):int64;
begin
if obj is TRtcSimpleValue then
Result:=TRtcSimpleValue(obj).GetLargeInt
else if obj is TRtcValue then
Result:=TRtcValue(obj).asLargeInt
else
raise EConvertError.Create('Can not convert '+obj.ClassName+' to LargeInt.');
end;
function GetAsDateTime(const obj:TRtcValueObject):TDateTime;
begin
if obj is TRtcSimpleValue then
Result:=TRtcSimpleValue(obj).GetDateTime
else if obj is TRtcValue then
Result:=TRtcValue(obj).asDateTime
else
raise EConvertError.Create('Can not convert '+obj.ClassName+' to DateTime.');
end;
procedure Expose(var obj:TRtcValueObject);
var
obj2:TRtcValueObject;
begin
while obj is TRtcValue do
begin
obj2:=TRtcValue(obj).asObject;
TRtcValue(obj).asObject:=nil;
obj.Free;
obj:=obj2;
end;
end;
{ Check param executes "paramname" and stores the result back into
the variable, then returns the pointer to that variable.
You should NOT destroy the object returned. }
function CheckParam(const parname:string):TRtcValue;
var
obj1,obj2:TRtcValueObject;
begin
// remove old pointer
obj.asObject:=nil;
obj1:=Param.asObject[parname];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object, store new in place
Param.isNull[parname]:=true;
Param.asObject[parname]:=obj2;
obj.asObject:=obj2;
end
else
obj.asObject:=obj1;
Result:=obj;
end;
{ Check param executes "paramname" and stores the result back into
the variable, then returns the pointer to that variable.
You should NOT destroy the object returned. }
function CheckParamB(const parname:string):TRtcValue;
var
obj1,obj2:TRtcValueObject;
begin
// remove old pointer
objB.asObject:=nil;
obj1:=Param.asObject[parname];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object, store new in place
Param.isNull[parname]:=true;
Param.asObject[parname]:=obj2;
objB.asObject:=obj2;
end
else
objB.asObject:=obj1;
Result:=objB;
end;
{ Execute Param returns the result, destroying the original.
You should take care of destroying the object returned. }
function ExecuteParam(const parname:string):TRtcValueObject;
var
obj1,obj2:TRtcValueObject;
begin
obj.asObject:=nil;
obj1:=Param.asObject[parname];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object
Param.isNull[parname]:=true;
obj.asObject:=obj2;
Result:=obj2;
end
else
begin
// extract object pointer
Param.asObject[parname]:=nil;
obj.asObject:=obj1;
Result:=obj1;
end;
end;
{ Execute Param returns the result, destroying the original.
You should take care of destroying the object returned. }
function ExecuteParam_X:TRtcValueObject;
var
obj1,obj2:TRtcValueObject;
begin
obj.asObject:=nil;
obj1:=Param.asObject['X'];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object
Param.isNull['X']:=true;
obj.asObject:=obj2;
Result:=obj2;
end
else
begin
// extract object pointer
Param.asObject['X']:=nil;
obj.asObject:=obj1;
Result:=obj1;
end;
end;
{ Execute Param returns the result, destroying the original.
You should take care of destroying the object returned. }
function ExecuteParam_Y:TRtcValueObject;
var
obj1,obj2:TRtcValueObject;
begin
obj.asObject:=nil;
obj1:=Param.asObject['Y'];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object
Param.isNull['Y']:=true;
obj.asObject:=obj2;
Result:=obj2;
end
else
begin
// extract object pointer
Param.asObject['Y']:=nil;
obj.asObject:=obj1;
Result:=obj1;
end;
end;
{ Execute Param returns the result, destroying the original.
You should take care of destroying the object returned. }
function ExecuteParamB(const parname:string):TRtcValueObject;
var
obj1,obj2:TRtcValueObject;
begin
objB.asObject:=nil;
obj1:=Param.asObject[parname];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object
Param.isNull[parname]:=true;
objB.asObject:=obj2;
Result:=obj2;
end
else
begin
// extract object pointer
Param.asObject[parname]:=nil;
objB.asObject:=obj1;
Result:=obj1;
end;
end;
{ Execute Param returns the result, destroying the original.
You should take care of destroying the object returned. }
function ExecuteParamB_Y:TRtcValueObject;
var
obj1,obj2:TRtcValueObject;
begin
objB.asObject:=nil;
obj1:=Param.asObject['Y'];
obj2:=Comm.Group.ExecuteData(Comm, obj1, false);
if obj2<>obj1 then
begin
Expose(obj2);
// destroy old object
Param.isNull['Y']:=true;
objB.asObject:=obj2;
Result:=obj2;
end
else
begin
// extract object pointer
Param.asObject['Y']:=nil;
objB.asObject:=obj1;
Result:=obj1;
end;
end;
{ Execute Command returns the result, preserving the original.
You should take care of destroying the object returned. }
function ExecuteCommand(const parname:string):TRtcValueObject;
var
orig:TRtcValueObject;
begin
orig := Param.asObject[parname];
if not assigned(orig) then
Result:=nil
else
begin
orig:=orig.copyOf;
Result:=ExecuteParam(parname);
Param.asObject[parname] := orig;
end;
end;
procedure Execute_If;
begin
if CheckParam('I').asBoolean then
Res.asObject:=ExecuteParam_X
else
Res.asObject:=ExecuteParam_Y;
end;
procedure Execute_Repeat;
var
new_cmds:TRtcValueObject;
new_cond:TRtcValueObject;
arr:TRtcArray;
cnt:cardinal;
begin
arr:=nil;
new_cond:=nil;
new_cmds:=nil;
cnt:=0;
try
repeat
if Comm.StopTime>0 then
if GetTickCount>Comm.StopTime then
raise ERtcScript.Create('Script Execution Time Limit exceeded.');
if Comm.MaxLoop>0 then
if cnt>Comm.MaxLoop then
raise ERtcScript.Create('Maximum Loop count exceeded')
else
Inc(cnt);
if assigned(new_cond) then
begin
new_cond.Free;
new_cond:=nil;
end;
new_cmds:=ExecuteCommand('X');
if assigned(new_cmds) then
begin
if not assigned(arr) then
arr:=Res.NewArray;
arr.asObject[arr.Count]:=new_cmds;
new_cmds:=nil;
end;
new_cond := ExecuteCommand('I');
until obj.asBoolean;
finally
new_cond.Free;
new_cmds.Free;
end;
end;
procedure Execute_While;
var
new_cmds:TRtcValueObject;
new_cond:TRtcValueObject;
arr:TRtcArray;
cnt:cardinal;
begin
arr:=nil;
new_cmds:=nil;
new_cond:=nil;
cnt:=0;
try
new_cond := ExecuteCommand('I');
while obj.asBoolean do
begin
if Comm.StopTime>0 then
if GetTickCount>Comm.StopTime then
raise ERtcScript.Create('Script Execution Time Limit exceeded.');
if Comm.MaxLoop>0 then
if cnt>Comm.MaxLoop then
raise ERtcScript.Create('Maximum Loop count exceeded')
else
Inc(cnt);
if assigned(new_cond) then
begin
new_cond.Free;
new_cond:=nil;
end;
new_cmds:=ExecuteCommand('X');
if assigned(new_cmds) then
begin
if not assigned(arr) then
arr:=Res.NewArray;
arr.asObject[arr.Count]:=new_cmds;
new_cmds:=nil;
end;
new_cond := ExecuteCommand('I');
end;
finally
if assigned(new_cond) then new_cond.Free;
if assigned(new_cmds) then new_cmds.Free;
end;
end;
procedure Execute_For;
var
a,b,i:longint;
vname:string;
arr:TRtcArray;
new_cmds:TRtcValueObject;
cnt:cardinal;
begin
vname:=CheckParam('V').asVarName;
a:=CheckParam('A').asInteger;
b:=CheckParam('B').asInteger;
// remove anything else that might have been stored in our loop variable
Comm.Locals.isNull[vname]:=true;
arr:=nil; new_cmds:=nil; cnt:=0;
try
if CheckParam('D').asBoolean then
begin
for i:=a to b do
begin
if Comm.StopTime>0 then
if GetTickCount>Comm.StopTime then
raise ERtcScript.Create('Script Execution Time Limit exceeded.');
if Comm.MaxLoop>0 then
if cnt>Comm.MaxLoop then
raise ERtcScript.Create('Maximum Loop count exceeded')
else
Inc(cnt);
// set loop variable value
Comm.Locals.asInteger[vname]:=i;
new_cmds:=ExecuteCommand('X');
if assigned(new_cmds) then
begin
if not assigned(arr) then
arr:=Res.NewArray;
arr.asObject[arr.Count]:=new_cmds;
new_cmds:=nil;
end;
end;
end
else
begin
for i:=a downto b do
begin
if Comm.StopTime>0 then
if GetTickCount>Comm.StopTime then
raise ERtcScript.Create('Script Execution Time Limit exceeded.');
if Comm.MaxLoop>0 then
if cnt>Comm.MaxLoop then
raise ERtcScript.Create('Maximum Loop count exceeded')
else
Inc(cnt);
// set loop variable value
Comm.Locals.asInteger[vname]:=i;
new_cmds:=ExecuteCommand('X');
if assigned(new_cmds) then
begin
if not assigned(arr) then
arr:=Res.NewArray;
arr.asObject[arr.Count]:=new_cmds;
new_cmds:=nil;
end;
end;
end;
finally
new_cmds.Free;
end;
end;
procedure Execute_ForEach;
begin
// TODO: Foreach
raise ERtcScript.Create('"FOREACH" loops are not yet implemented.');
end;
function Collapse(const obj:TRtcValueObject):TRtcValueObject;
var
i,cnt,x:integer;
arr:TRtcArray;
begin
if obj is TRtcArray then
begin
arr:=TRtcArray(obj);
cnt:=0; x:=0;
for i:=0 to arr.Count-1 do
if arr.isType[i]<>rtc_Null then
begin
x:=i;
Inc(cnt);
if cnt>1 then Break;
end;
if cnt=0 then
Result:=nil
else if cnt=1 then
begin
Result:=arr.asObject[x];
arr.asObject[x]:=nil;
end
else
Result:=obj;
end
else
Result:=obj;
end;
function Execute(const data:TRtcValueObject):TRtcValueObject;
var
temp:TRtcValueObject;
begin
if not assigned(data) then
Result:=nil
else
begin
temp:=data.copyOf;
Result:=temp;
try
Result:=Comm.Group.ExecuteData(Comm, temp);
finally
if Result<>temp then temp.Free;
end;
temp:=Collapse(Result);
if temp<>Result then
begin
Result.Free;
Result:=temp;
end;
end;
end;
function Get_Variable(vname:string; var isCopy:boolean; asAddr:boolean):TRtcValueObject; forward;
function Get_Property(obj:TRtcValueObject; s:string; var isCopy:boolean; asAddr:boolean):TRtcValueObject;
var
dot:integer;
vname:string;
procedure CheckCodeBlocks;
var
done:boolean;
myvar:TRtcFunctionInfo;
objX:TRtcValueObject;
asAddr2:boolean;
vname2,vname3:string;
temp:TRtcValueObject;
tempLocals:TRtcRecord;
par:TRtcRecord;
fname:string;
i:integer;
begin
if Result is TRtcFunctionInfo then
begin
done:=False;
myvar:=TRtcFunctionInfo(Result);
while (myvar.FunctionName='@') and (myvar.isType['Y']=rtc_Function) do
myvar:=myvar.asFunction['Y'];
if (myvar.FunctionName='$') then
begin
vname2:=myvar.asVarName['$V'];
if vname2='-' then
vname2:=vname2+myvar.asVarName['$P'];
asAddr2:=myvar.asBoolean['$A'];
objX:=Execute(myvar.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname3:=GetAsString(objX);
if vname3<>'' then
begin
if vname2<>'' then vname2:=vname2+'.';
vname2:=vname2+vname3;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
if Result<>obj then
if assigned(obj) then
begin
obj.Free;
obj:=nil;
end;
if isCopy then
begin
Result.Free;
Result:=nil;
end;
isCopy:=False;
done:=True;
Result:=Get_Variable(vname2, isCopy, asAddr2);
if isCopy then obj:=Result;
end
else if (myvar.FunctionName='?') and (myvar.asString['C']='.') then
begin
done:=True;
vname2:='';
repeat
objX:=Execute(myvar.asObject['Y']);
try
vname3:=GetAsString(objX);
if vname3<>'' then
begin
if vname2<>'' then vname2:='.'+vname2;
vname2:=vname3+vname2;
end;
finally
objX.Free;
end;
if myvar.isType['X']<>rtc_Function then
begin
done:=False;
Break;
end;
myvar:=TRtcFunctionInfo(myvar.asObject['X']);
until (myvar.FunctionName<>'?') or (myvar.asString['C']<>'.');
if done and (myvar.FunctionName<>'$') then
done:=False;
if done then
begin
objX:=Execute(myvar.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname3:=GetAsString(objX);
if vname3<>'' then
begin
if vname2<>'' then vname2:='.'+vname2;
vname2:=vname3+vname2;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
vname3:=myvar.asVarName['$V'];
if vname3='-' then
vname3:=vname3+myvar.asVarName['$P'];
if vname3<>'' then
begin
if vname2<>'' then vname2:='.'+vname2;
vname2:=vname3+vname2;
end;
asAddr2:=myvar.asBoolean['$A'];
if Result<>obj then
if assigned(obj) then
begin
obj.Free;
obj:=nil;
end;
if isCopy then
begin
Result.Free;
Result:=nil;
end;
isCopy:=False;
Result:=Get_Variable(vname2, isCopy, asAddr2);
if isCopy then obj:=Result;
end;
end
else if myvar.FunctionName='!!' then
begin
if Comm.MaxRecurse>0 then
if Comm.RecurseCount>=Comm.MaxRecurse then
raise ERtcScript.Create('Maximum allowed Recursion Depth exceeded.')
else
Inc(Comm.RecurseCount);
try
Par:=TRtcRecord.Create;
try
for i:=0 to Param.FieldCount-1 do
begin
fname:=Param.FieldName[i];
if (fname<>'$C') and (fname<>'$R') and (fname<>'$V') then
begin
Par.asObject[fname]:=Comm.Group.ExecuteData(Comm, Param.asObject[fname]);
if Par.asObject[fname]<>Param.asObject[fname] then
Param.isNull[fname]:=True
else
Param.asObject[fname]:=nil;
end;
end;
temp:=myvar.asObject['X'];
if assigned(temp) then
temp:=temp.copyOf;
try
// changing Local variables to Global variables
// and input parameters to Local variables
tempLocals:=Comm.Locals;
Comm.Locals:=Par;
objX:=nil;
try
objX:=Comm.Group.ExecuteData(Comm, temp);
finally
Comm.Locals:=tempLocals;
if assigned(objX) and (objX<>temp) then objX.Free;
end;
finally
if assigned(temp) then temp.Free;
end;
// Get the result
if Result<>obj then
if assigned(obj) then
begin
obj.Free;
obj:=nil;
end;
if isCopy then
begin
Result.Free;
Result:=nil;
end;
Result:=Par.asObject['RESULT'];
Par.asObject['RESULT']:=nil;
isCopy:=True;
obj:=Result;
done:=True;
finally
Par.Free;
end;
finally
if Comm.MaxRecurse>0 then
Dec(Comm.RecurseCount);
end;
end;
if not done then
begin
if Result<>obj then
if assigned(obj) then
begin
obj.Free;
obj:=nil;
end;
if isCopy then
obj:=Result // so we can Free it afterwards
else
obj:=nil;
Result:=Execute(Result);
if assigned(obj) then
obj.Free; // free old Result object if it was a copy
isCopy:=True;
obj:=Result;
end;
end;
end;
begin
s:=UpperCase(s);
Result:=obj;
obj:=nil;
CheckCodeBlocks;
try
while s<>'' do
begin
dot:=Pos('.',s);
if dot>0 then
begin
vname:=Copy(s,1,dot-1);
Delete(s,1,dot);
end
else
begin
vname:=s;
s:='';
end;
while assigned(Result) and (Result is TRtcValue) do
Result:=TRtcValue(Result).asObject;
if Result=nil then
raise ERtcScript.Create('Can not get ".'+vname+'" from NULL');
if Result is TRtcArray then
begin
if (vname='COUNT') or (vname='FIELDCOUNT') then
begin
isCopy:=True;
Result:=TRtcIntegerValue.Create(TRtcArray(Result).Count);
Break;
end
else
Result:=TRtcArray(Result).asObject[StrToInt(vname)];
end
else if Result is TRtcRecord then
begin
if (vname='COUNT') or (vname='FIELDCOUNT') then
begin
isCopy:=True;
Result:=TRtcIntegerValue.Create(TRtcRecord(Result).Count);
Break;
end
else
Result:=TRtcRecord(Result).asObject[vname];
end
else if Result is TRtcDataSet then
begin
if vname='FIRST' then
begin
TRtcDataSet(Result).First;
Result:=nil;
end
else if vname='LAST' then
begin
TRtcDataSet(Result).Last;
Result:=nil;
end
else if vname='NEXT' then
begin
TRtcDataSet(Result).Next;
Result:=nil;
end
else if vname='PRIOR' then
begin
TRtcDataSet(Result).Prior;
Result:=nil;
end
else if vname='INSERT' then
begin
TRtcDataSet(Result).Insert;
Result:=nil;
end
else if vname='APPEND' then
begin
TRtcDataSet(Result).Append;
Result:=nil;
end
else if vname='DELETE' then
begin
TRtcDataSet(Result).Delete;
Result:=nil;
end
else
begin
if (vname='COUNT') or (vname='ROWCOUNT') then
begin
Result:=TRtcIntegerValue.Create(TRtcDataSet(Result).RowCount);
isCopy:=True;
Break;
end
else if vname='ROW' then
begin
Result:=TRtcIntegerValue.Create(TRtcDataSet(Result).Row);
isCopy:=True;
Break;
end
else if vname='FIELDCOUNT' then
begin
Result:=TRtcIntegerValue.Create(TRtcDataSet(Result).FieldCount);
isCopy:=True;
Break;
end
else if vname='EOF' then
begin
Result:=TRtcBooleanValue.Create(TRtcDataSet(Result).EOF);
isCopy:=True;
Break;
end
else if vname='EMPTY' then
begin
Result:=TRtcBooleanValue.Create(TRtcDataSet(Result).Empty);
isCopy:=True;
Break;
end
else if vname='BOF' then
begin
Result:=TRtcBooleanValue.Create(TRtcDataSet(Result).BOF);
isCopy:=True;
Break;
end
else if vname[1] in ['0'..'9'] then
Result:=TRtcDataSet(Result).asObject[TRtcDataSet(Result).FieldName[StrToInt(vname)]]
else
Result:=TRtcDataSet(Result).asObject[vname];
end;
end
else
raise ERtcScript.Create('Can not get ".'+vname+'" from a simple data type');
CheckCodeBlocks;
end;
finally
if assigned(obj) and (obj<>Result) then
begin
if assigned(Result) then
Result:=Result.copyOf;
obj.Free;
obj:=nil;
end;
end;
end;
procedure Set_Variable(s:string; value:TRtcValueObject; asAddr:boolean);
var
obj:TRtcValueObject;
dot:integer;
vname:string;
procedure GetNext;
begin
// Get first string before dot
dot:=Pos('.',s);
if dot>0 then
begin
vname:=Copy(s,1,dot-1);
Delete(s,1,dot);
end
else
begin
vname:=s;
s:='';
end;
end;
procedure SetVariable; forward;
procedure Set_Property(obj:TRtcValueObject);
procedure CheckCodeBlocks;
var
myvar:TRtcFunctionInfo;
objX:TRtcValueObject;
vname2,vname3:string;
begin
if obj is TRtcFunctionInfo then
begin
myvar:=TRtcFunctionInfo(obj);
while (myvar.FunctionName='@') and (myvar.isType['Y']=rtc_Function) do
myvar:=myvar.asFunction['Y'];
if (myvar.FunctionName='$') then
begin
vname2:=myvar.asVarName['$V'];
if vname2='-' then
vname2:=vname2+myvar.asVarName['$P'];
asAddr:=myvar.asBoolean['$A'];
objX:=Execute(myvar.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname3:=GetAsString(objX);
if vname3<>'' then
begin
if vname2<>'' then vname2:=vname2+'.';
vname2:=vname2+vname3;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
if s<>'' then s:='.'+s;
s:=vname2+s;
SetVariable;
end
else if (myvar.FunctionName='?') and (myvar.asString['C']='.') then
begin
vname2:='';
repeat
objX:=Execute(myvar.asObject['Y']);
try
vname3:=GetAsString(objX);
if vname3<>'' then
begin
if vname2<>'' then vname2:='.'+vname2;
vname2:=vname3+vname2;
end;
finally
objX.Free;
end;
if myvar.isType['X']<>rtc_Function then
raise ERtcScript.Create('Left side can not be assigned to');
myvar:=TRtcFunctionInfo(myvar.asObject['X']);
until (myvar.FunctionName<>'?') or (myvar.asString['C']<>'.');
if myvar.FunctionName<>'$' then
raise ERtcScript.Create('Left side can not be assigned to');
objX:=Execute(myvar.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname3:=GetAsString(objX);
if vname3<>'' then
begin
if vname2<>'' then vname2:='.'+vname2;
vname2:=vname3+vname2;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
vname3:=myvar.asVarName['$V'];
if vname3='-' then
vname3:=vname3+myvar.asVarName['$P'];
if vname3<>'' then
begin
if vname2<>'' then vname2:='.'+vname2;
vname2:=vname3+vname2;
end;
asAddr:=myvar.asBoolean['$A'];
if s<>'' then s:='.'+s;
s:=vname2+s;
SetVariable;
end
else
raise ERtcScript.Create('Left side can not be assigned to');
end;
end;
begin
CheckCodeBlocks;
while s<>'' do
begin
dot:=Pos('.',s);
if dot>0 then
begin
vname:=Copy(s,1,dot-1);
Delete(s,1,dot);
end
else
begin
vname:=s;
s:='';
end;
while assigned(obj) and (obj is TRtcValue) do
if TRtcValue(obj).asObject=nil then Break
else obj:=TRtcValue(obj).asObject;
if obj=nil then
raise ERtcScript.Create('Can not get ".'+vname+'" from NULL');
if obj is TRtcArray then
begin
if (vname='COUNT') or (vname='FIELDCOUNT') then
raise Exception.Create('Can not assign to ".'+vname+'"')
else if (s='') and not asAddr then
begin
TRtcArray(obj).isNull[StrToInt(vname)]:=True;
TRtcArray(obj).asObject[StrToInt(vname)]:=value;
value:=nil;
Break;
end
else
obj:=TRtcArray(obj).asObject[StrToInt(vname)];
end
else if obj is TRtcRecord then
begin
if (vname='COUNT') or (vname='FIELDCOUNT') then
raise Exception.Create('Can not assign to ".'+vname+'"')
else if (s='') and not asAddr then
begin
TRtcRecord(obj).isNull[vname]:=True;
TRtcRecord(obj).asObject[vname]:=value;
value:=nil;
Break;
end
else
obj:=TRtcRecord(obj).asObject[vname];
end
else if obj is TRtcDataSet then
begin
if (vname='FIRST') or (vname='LAST') or (vname='NEXT') or (vname='PRIOR') or
(vname='INSERT') or (vname='APPEND') or (vname='DELETE') or
(vname='COUNT') or (vname='ROWCOUNT') or (vname='FIELDCOUNT') or
(vname='EOF') or (vname='EMPTY') or (vname='BOF') then
raise ERtcScript.Create('Can not assign to ".'+vname+'"')
else if vname='ROW' then
begin
if (s='') and not asAddr then
begin
TRtcDataSet(obj).Row:=GetAsInteger(value);
value.Free;
value:=nil;
Break;
end
else
raise ERtcScript.Create('Property "ROW" has no sub-properties');
end
else if vname[1] in ['0'..'9'] then
begin
if (s='') and not asAddr then
begin
TRtcDataSet(obj).isNull[TRtcDataSet(obj).FieldName[StrToInt(vname)]]:=True;
TRtcDataSet(obj).asObject[TRtcDataSet(obj).FieldName[StrToInt(vname)]]:=value;
value:=nil;
Break;
end
else
obj:=TRtcDataSet(obj).asObject[TRtcDataSet(obj).FieldName[StrToInt(vname)]];
end
else
begin
if (s='') and not asAddr then
begin
TRtcDataSet(obj).isNull[vname]:=True;
TRtcDataSet(obj).asObject[vname]:=value;
value:=nil;
Break;
end
else
obj:=TRtcDataSet(obj).asObject[vname];
end;
end
else
raise ERtcScript.Create('Can not get ".'+vname+'" from a simple data type');
CheckCodeBlocks;
end;
end;
procedure Set_HTTPValues(const Vals:TRtcHttpValues);
var
idx:integer;
begin
if (vname='') or (vname='TEXT') then
begin
Vals.Text:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='DELIMITER' then
begin
Vals.Delimiter:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='COUNT' then
raise ERtcScript.Create('Can not assign to ".Count"')
else if vname='NAME' then
begin
GetNext;
if vname='' then
raise ERtcScript.Create('Parameter missing after "Item.Name"');
idx:=StrToInt(vname);
Vals.ItemName[idx]:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='VALUE' then
begin
GetNext;
if vname='' then
raise ERtcScript.Create('Parameter missing after "Item.Value"');
idx:=StrToInt(vname);
Vals.ItemValue[idx]:=GetAsString(value);
value.Free;
value:=nil;
end
else
begin
Vals.Value[vname]:=GetAsString(value);
value.Free;
value:=nil;
end;
end;
procedure Set_HTTPHeaderVar(const Vars:TRtcHttpHeader);
var
idx:integer;
begin
if vname='COOKIE' then
begin
GetNext;
if vname='' then
begin
Vars.Cookie.Text:=GetAsString(value);
value.Free;
value:=nil;
end
else
Set_HTTPValues(Vars.Cookie);
end
else if vname='HEADER' then
begin
GetNext;
if vname='COUNT' then
raise ERtcScript.Create('Can not assign to "Header.Count"')
else if vname='NAME' then
begin
GetNext;
if vname='' then raise ERtcScript.Create('Missing item index for "HEADER.NAME"');
idx:=StrToInt(vname);
Vars.ItemName[idx]:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='VALUE' then
begin
GetNext;
if vname='' then raise ERtcScript.Create('Missing item index for "HEADER.VALUE"');
idx:=StrToInt(vname);
Vars.ItemValue[idx]:=GetAsString(value);
value.Free;
value:=nil;
end
else if (vname='TEXT') or (vname='') then
begin
Vars.HeaderText:=GetAsString(value);
value.Free;
value:=nil;
end
else
begin
Vars.Value[vname]:=GetAsString(value);
value.Free;
value:=nil;
end;
end
else if vname='CONTENTTYPE' then
begin
Vars.ContentType:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='CONTENTLENGTH' then
begin
Vars.ContentLength:=GetAsInt64(value);
value.Free;
value:=nil;
end
else if vname<>'' then
begin
Vars.Value[vname]:=GetAsString(value);
value.Free;
value:=nil;
end
else
raise ERtcScript.Create('Missing parameter');
end;
procedure Set_SessionVar;
var
Srv:TRtcDataServer;
begin
Srv:=TRtcDataServer(Comm.Sender);
GetNext;
if vname='ID' then
begin
Srv.FindSession(GetAsString(value));
value.Free;
value:=nil;
end
else if (vname='OPEN') or (vname='FIND') or
(vname='HAVE') or (vname='CLOSE') or
(vname='EXPIRETIME') then
raise ERtcScript.Create('Can not assign to "SESSION.'+vname+'"')
else
begin
if not assigned(Srv.Session) then
raise ERtcScript.Create('No session locked, can not set "SESSION.'+vname+'"');
if vname='KEEPALIVE' then
begin
Srv.Session.KeepAlive:=GetAsInteger(value);
value.Free;
value:=nil;
end
else if vname='FINALEXPIRE' then
begin
Srv.Session.FinalExpire:=GetAsDateTime(value);
value.Free;
value:=nil;
end
else
begin
if s<>'' then
s:=vname+'.'+s
else
s:=vname;
vname:='';
Set_Property(Srv.Session);
end;
end;
end;
procedure Set_QueryVar;
begin
GetNext;
Set_HTTPValues( TRtcDataServer(Comm.Sender).Request.Query );
end;
procedure Set_InputVar;
begin
GetNext;
Set_HTTPValues( TRtcDataServer(Comm.Sender).Request.Params );
end;
procedure Set_RequestVar;
var
Req:TRtcRequest;
begin
GetNext;
Req:=TRtcDataServer(Comm.Sender).Request;
if vname='METHOD' then
begin
Req.Method:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='FILENAME' then
begin
Req.FileName:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='QUERY' then
Set_HTTPValues(Req.Query)
else if vname='PARAMS' then
Set_HTTPValues(Req.Params)
else if vname='CLOSE' then
begin
Req.Close:=GetAsBoolean(value);
value.Free;
value:=nil;
end
else if vname='HOST' then
begin
Req.Host:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='AGENT' then
begin
Req.Agent:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='REFERER' then
begin
Req.Referer:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='FORWARDEDFOR' then
begin
Req.ForwardedFor:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='URI' then
begin
Req.URI:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='URL' then
raise ERtcScript.Create('Can not assign to "REQUEST.URL"')
else if vname='INFO' then
Set_Property(Req.Info)
else
Set_HttpHeaderVar(Req);
end;
procedure Set_ResponseVar;
var
Resp:TRtcResponse;
function ExtractNum:integer;
var
idx:integer;
begin
idx:=0;
while (idx<length(s)) and (s[idx+1] in ['0'..'9']) do
Inc(idx);
if idx>0 then
begin
Result:=StrToInt(Copy(s,1,idx));
Delete(s,1,idx);
s:=Trim(s);
end
else
raise ERtcScript.Create('Status code required before Status Text');
end;
begin
GetNext;
Resp:=TRtcDataServer(Comm.Sender).Response;
if vname='STATUS' then
begin
GetNext;
if vname='CODE' then
begin
Resp.StatusCode:=GetAsInteger(value);
value.Free;
value:=nil;
end
else if vname='TEXT' then
begin
Resp.StatusText:=GetAsString(value);
value.Free;
value:=nil;
end
else if vname='' then
begin
s:=GetAsString(value);
value.Free;
value:=nil;
Resp.StatusCode:=ExtractNum;
Resp.StatusText:=s;
end;
end
else if vname='STATUSCODE' then
begin
Resp.StatusCode:=GetAsInteger(value);
value.Free;
value:=nil;
end
else if vname='STATUSTEXT' then
begin
Resp.StatusText:=GetAsString(value);
value.Free;
value:=nil;
end
else
Set_HttpHeaderVar(Resp);
end;
procedure SetVariable;
begin
s:=UpperCase(s);
GetNext;
if vname[1]='-' then
begin
if not assigned(Comm.Sender) then
raise ERtcScript.Create('Connection unassigned, can not access "'+vname+'"')
else if not (Comm.Sender is TRtcDataServer) then
raise ERtcScript.Create('Not a RtcDataServer connection, can not access "'+vname+'"');
if vname='-REQUEST' then
Set_RequestVar
else if vname='-RESPONSE' then
Set_ResponseVar
else if vname='-SESSION' then
Set_SessionVar
else if vname='-QUERY' then
Set_QueryVar
else if vname='-INPUT' then
Set_InputVar
else
raise ERtcScript.Create('Unknown variabe "'+vname+'"');
end
else if s='' then
begin
if not asAddr then
begin
if vname='RESULT' then
begin
Comm.Locals.isNull[vname]:=True;
Comm.Locals.asObject[vname]:=value;
value:=nil;
end
else if not Comm.Locals.isNull[vname] then
begin
Comm.Locals.isNull[vname]:=True;
Comm.Locals.asObject[vname]:=value;
value:=nil;
end
else if not Comm.Globals.isNull[vname] then
begin
Comm.Globals.isNull[vname]:=True;
Comm.Globals.asObject[vname]:=value;
value:=nil;
end
else
begin
Comm.Locals.asObject[vname]:=value;
value:=nil;
end;
end
else
begin
if vname='RESULT' then
obj:=Comm.Locals.asObject[vname]
else if not Comm.Locals.isNull[vname] then
obj:=Comm.Locals.asObject[vname]
else if not Comm.Globals.isNull[vname] then
obj:=Comm.Globals.asObject[vname]
else
obj:=nil;
if obj=nil then
ERtcScript.Create('Left side is NULL. Can not assign to NULL');
Set_Property(obj);
end;
end
else
begin
if vname='RESULT' then
obj:=Comm.Locals.asObject[vname]
else if not Comm.Locals.isNull[vname] then
obj:=Comm.Locals.asObject[vname]
else if not Comm.Globals.isNull[vname] then
obj:=Comm.Globals.asObject[vname]
else
obj:=nil;
Set_Property(obj);
end;
end;
begin
try
try
SetVariable;
except
on E:Exception do
begin
if assigned(value) then
begin
value.Free;
value:=nil;
end;
raise;
end;
end;
finally
if assigned(value) then
begin
value.Free;
value:=nil;
raise ERtcScript.Create('Error assigning data to variable');
end;
end;
end;
function Get_Variable(vname:string; var isCopy:boolean; asAddr:boolean):TRtcValueObject;
var
dot:integer;
s:string;
procedure GetNext;
begin
// Get first string before dot
dot:=Pos('.',s);
if dot>0 then
begin
vname:=Copy(s,1,dot-1);
Delete(s,1,dot);
end
else
begin
vname:=s;
s:='';
end;
end;
function Get_HTTPValues(const Vals:TRtcHttpValues):TRtcValueObject;
var
idx:integer;
begin
if (vname='') or (vname='TEXT') then
Result:=TRtcStringValue.Create(Vals.Text)
else if vname='DELIMITER' then
Result:=TRtcStringValue.Create(Vals.Delimiter)
else if vname='COUNT' then
Result:=TRtcIntegerValue.Create(Vals.ItemCount)
else if vname='NAME' then
begin
GetNext;
if vname='' then
raise ERtcScript.Create('Parameter missing after Item.Name');
idx:=StrToInt(vname);
Result:=TRtcStringValue.Create(Vals.ItemName[idx]);
end
else if vname='VALUE' then
begin
GetNext;
if vname='' then
raise ERtcScript.Create('Parameter missing after Item.Value');
idx:=StrToInt(vname);
Result:=TRtcStringValue.Create(Vals.ItemValue[idx]);
end
else
Result:=TRtcStringValue.Create(Vals.Value[vname]);
end;
function Get_HTTPHeaderVar(const Vars:TRtcHttpHeader):TRtcValueObject;
var
idx:integer;
begin
if vname='COOKIE' then
begin
GetNext;
if vname='' then
Result:=TRtcStringValue.Create(Vars.Cookie.Text)
else
Result:=Get_HTTPValues(Vars.Cookie);
end
else if vname='HEADER' then
begin
GetNext;
if vname='COUNT' then
Result:=TRtcIntegerValue.Create(Vars.ItemCount)
else if vname='NAME' then
begin
GetNext;
if vname='' then raise ERtcScript.Create('Missing item index for "HEADER.NAME"');
idx:=StrToInt(vname);
Result:=TRtcStringValue.Create(Vars.ItemName[idx]);
end
else if vname='VALUE' then
begin
GetNext;
if vname='' then raise ERtcScript.Create('Missing item index for "HEADER.VALUE"');
idx:=StrToInt(vname);
Result:=TRtcStringValue.Create(Vars.ItemValue[idx]);
end
else if (vname='TEXT') or (vname='') then
Result:=TRtcStringValue.Create(Vars.HeaderText)
else
begin
if Vars.Value[vname]<>'' then
Result:=TRtcStringValue.Create(Vars.Value[vname])
else
Result:=nil;
end;
end
else if vname='CONTENTTYPE' then
begin
if Vars.ContentType<>'' then
Result:=TRtcStringValue.Create(Vars.ContentType)
else
Result:=nil;
end
else if vname='CONTENTLENGTH' then
begin
if Vars.ContentLength<>0 then
Result:=TRtcIntegerValue.Create(Vars.ContentLength)
else
Result:=nil;
end
else if vname<>'' then
begin
if Vars.Value[vname]<>'' then
Result:=TRtcStringValue.Create(Vars.Value[vname])
else
Result:=nil;
end
else
raise ERtcScript.Create('Missing parameter');
end;
function Get_SessionVar:TRtcValueObject;
var
Srv:TRtcDataServer;
begin
Srv:=TRtcDataServer(Comm.Sender);
GetNext;
if vname='ID' then
begin
if assigned(Srv.Session) then
Result:=TRtcStringValue.Create(Srv.Session.ID)
else
Result:=nil;
end
else if vname='COUNT' then
begin
GetNext;
if (vname='') or (vname='TOTAL') then
Result:=TRtcIntegerValue(Srv.TotalSessionsCount)
else if vname='LOCKED' then
Result:=TRtcIntegerValue(Srv.TotalSessionsLocked)
else if vname='UNLOCKED' then
Result:=TRtcIntegerValue(Srv.TotalSessionsUnlocked)
else
raise ERtcScript.Create('Invalid parameter for SESSION.COUNT ... "'+vname+'"');
end
else if vname='OPEN' then
begin
GetNext;
Result:=nil;
if (vname='') or (vname='PRIVATE') or (vname='FWDLOCK') then
Srv.OpenSession(sesFwdLock)
else if (vname='PUBLIC') or (vname='NOLOCK') then
Srv.OpenSession(sesNoLock)
else if (vname='IPLOCK') then
Srv.OpenSession(sesIPLock)
else if (vname='STRONG') or (vname='SECURE') or (vname='IPWNDLOCK') then
Srv.OpenSession(sesIPFwdLock)
else
raise ERtcScript.Create('Can not Open a Session with parameter "'+vname+'"')
end
else if vname='UNLOCK' then
begin
Result:=nil;
Srv.UnLockSession;
end
else if vname='FIND' then
begin
GetNext;
if vname='' then
Result:=TRtcBooleanValue.Create(Srv.Session<>nil)
else
Result:=TRtcBooleanValue.Create(Srv.FindSession(vname));
end
else if vname='LOCK' then
begin
GetNext;
if vname='' then
Result:=TRtcBooleanValue.Create(Srv.Session<>nil)
else
begin
if Srv.FindSession(vname) then
Result:=TRtcBooleanValue.Create(true)
else
begin
repeat
if Comm.StopTime>0 then
if GetTickCount>Comm.StopTime then
raise ERtcScript.Create('Script Execution Time Limit exceeded.');
if not Srv.HaveSession(vname) then Break;
Sleep(10);
until Srv.FindSession(vname);
Result:=TRtcBooleanValue.Create(assigned(Srv.Session));
end;
end;
end
else if vname='HAVE' then
begin
GetNext;
if vname='' then
Result:=TRtcBooleanValue.Create(Srv.Session<>nil)
else
Result:=TRtcBooleanValue.Create(Srv.HaveSession(vname));
end
else if vname='CLOSE' then
begin
GetNext;
Result:=nil;
if vname='' then
begin
if assigned(Srv.Session) then
Srv.Session.Close;
end
else
Srv.CloseSession(vname);
end
else if vname='KEEPALIVE' then
begin
if assigned(Srv.Session) then
Result:=TRtcIntegerValue.Create(Srv.Session.KeepAlive)
else
Result:=nil;
end
else if vname='EXPIRETIME' then
begin
if assigned(Srv.Session) then
Result:=TRtcDateTimeValue.Create(Srv.Session.ExpireTime)
else
Result:=nil;
end
else if vname='FINALEXPIRE' then
begin
if assigned(Srv.Session) then
begin
if Srv.Session.FinalExpire<>0 then
Result:=TRtcDateTimeValue.Create(Srv.Session.FinalExpire)
else
Result:=nil;
end
else
Result:=nil;
end
else if assigned(Srv.Session) then
begin
if s<>'' then
s:=vname+'.'+s
else
s:=vname;
isCopy:=False;
Result:=Get_Property(Srv.Session,s,isCopy,asAddr);
s:='';
end
else
Result:=nil;
end;
function Get_QueryVar:TRtcValueObject;
begin
GetNext;
Result:= Get_HTTPValues( TRtcDataServer(Comm.Sender).Request.Query );
end;
function Get_InputVar:TRtcValueObject;
begin
GetNext;
Result:= Get_HTTPValues( TRtcDataServer(Comm.Sender).Request.Params );
end;
function Get_RequestVar:TRtcValueObject;
var
Req:TRtcRequest;
begin
GetNext;
Req:=TRtcDataServer(Comm.Sender).Request;
if vname='METHOD' then
Result:=TRtcStringValue.Create(Req.Method)
else if vname='FILENAME' then
Result:=TRtcStringValue.Create(Req.FileName)
else if vname='QUERY' then
begin
GetNext;
Result:=Get_HTTPValues(Req.Query);
end
else if vname='PARAMS' then
begin
GetNext;
Result:=Get_HTTPValues(Req.Params);
end
else if vname='CLOSE' then
Result:=TRtcBooleanValue.Create(Req.Close)
else if vname='HOST' then
begin
if Req.Host<>'' then
Result:=TRtcStringValue.Create(Req.Host)
else
Result:=nil;
end
else if vname='AGENT' then
begin
if Req.Agent<>'' then
Result:=TRtcStringValue.Create(Req.Agent)
else
Result:=nil;
end
else if vname='REFERER' then
begin
if Req.Referer<>'' then
Result:=TRtcStringValue.Create(Req.Referer)
else
Result:=nil;
end
else if vname='FORWARDEDFOR' then
begin
if Req.ForwardedFor<>'' then
Result:=TRtcStringValue.Create(Req.ForwardedFor)
else
Result:=nil;
end
else if vname='URI' then
Result:=TRtcStringValue.Create(Req.URI)
else if vname='URL' then
Result:=TRtcStringValue.Create(Req.URL)
else if vname='INFO' then
begin
isCopy:=False;
Result:=Get_Property(Req.Info,s,isCopy,asAddr);
end
else
Result:=Get_HttpHeaderVar(Req);
end;
function Get_ResponseVar:TRtcValueObject;
var
Resp:TRtcResponse;
begin
GetNext;
Resp:=TRtcDataServer(Comm.Sender).Response;
if vname='STATUS' then
begin
GetNext;
if vname='CODE' then
Result:=TRtcIntegerValue.Create(Resp.StatusCode)
else if vname='TEXT' then
Result:=TRtcStringValue.Create(Resp.StatusText)
else if vname='' then
Result:=TRtcStringValue.Create(IntToStr(Resp.StatusCode)+' '+Resp.StatusText)
else
raise ERtcScript.Create('Can not read "RESPONSE.STATUS.'+vname+'"');
end
else if vname='STATUSCODE' then
Result:=TRtcIntegerValue.Create(Resp.StatusCode)
else if vname='STATUSTEXT' then
Result:=TRtcStringValue.Create(Resp.StatusText)
else
Result:=Get_HttpHeaderVar(Resp);
end;
function Get_ClientVar:TRtcValueObject;
var
Srv:TRtcDataServer;
begin
GetNext;
Srv:=TRtcDataServer(Comm.Sender);
if vname='COUNT' then
Result:=TRtcIntegerValue.Create(Srv.TotalServerConnectionCount)
else if (vname='IP') or (vname='ADDR') or (vname='ADDRESS') then
Result:=TRtcStringValue.Create(Srv.PeerAddr)
else if vname='PORT' then
Result:=TRtcStringValue.Create(Srv.PeerPort)
else if vname='' then
Result:=TRtcStringValue.Create(Srv.PeerAddr+':'+Srv.PeerPort)
else
raise ERtcScript.Create('Unsupported function: "CLIENT.'+vname+'"');
end;
function Get_ServerVar:TRtcValueObject;
var
Srv:TRtcDataServer;
begin
GetNext;
Srv:=TRtcDataServer(Comm.Sender);
if (vname='IP') or (vname='ADDR') or (vname='ADDRESS') then
Result:=TRtcStringValue.Create(Srv.LocalAddr)
else if vname='PORT' then
Result:=TRtcStringValue.Create(Srv.LocalPort)
else if vname='' then
Result:=TRtcStringValue.Create(Srv.LocalAddr+':'+Srv.LocalPort)
else
raise ERtcScript.Create('Unsupported function: "SERVER.'+vname+'"');
end;
begin
isCopy:=False;
s:=UpperCase(vname);
GetNext;
if vname[1]='-' then
begin
if not assigned(Comm.Sender) then
raise ERtcScript.Create('No connection object, can not access "'+vname+'"')
else if not (Comm.Sender is TRtcDataServer) then
raise ERtcScript.Create('Not a RtcDataServer connection, can not access "'+vname+'"');
isCopy:=True;
if vname='-REQUEST' then
Result:=Get_RequestVar
else if vname='-RESPONSE' then
Result:=Get_ResponseVar
else if vname='-SESSION' then
Result:=Get_SessionVar
else if vname='-QUERY' then
Result:=Get_QueryVar
else if vname='-INPUT' then
Result:=Get_InputVar
else if vname='-CLIENT' then
Result:=Get_ClientVar
else if vname='-SERVER' then
Result:=Get_ServerVar
else
raise ERtcScript.Create('Unable to read variable "'+vname+'"');
end
else
begin
if vname='RESULT' then
Result:=Comm.Locals.asObject[vname]
else if not Comm.Locals.isNull[vname] then
Result:=Comm.Locals.asObject[vname]
else if not Comm.Globals.isNull[vname] then
Result:=Comm.Globals.asObject[vname]
else
Result:=nil;
Result:=Get_Property(Result,s,isCopy,asAddr);
end;
end;
procedure Execute_Variable;
var
vname:string;
obj:TRtcValueObject;
isCopy:boolean;
what:byte;
asAddr:boolean;
procedure ExtractPropertyValue;
var
obj2,obj3:TRtcValueObject;
isCopy:boolean;
begin
what:=2; // Reading variable property
if Param.isType['PARAMS']<>rtc_Null then
begin
obj2:=Comm.Group.ExecuteData(Comm, Param.asObject['PARAMS']);
try
if obj2<>Param.asObject['PARAMS'] then
Param.isNull['PARAMS']:=True
else
Param.asObject['PARAMS']:=nil;
obj3:=Get_Property(obj,GetAsString(obj2),isCopy,asAddr);
if isCopy then
Res.asObject:=obj3
else if assigned(obj3) then
Res.asObject:=obj3.copyOf;
finally
obj2.Free;
end;
end
else
Res.asObject:=Execute(obj);
end;
procedure ExtractNamedValue;
var
obj2,obj3:TRtcValueObject;
isCopy:boolean;
begin
what:=2; // Reading variable property
if Param.isType['PARAMS']<>rtc_Null then
begin
obj2:=Comm.Group.ExecuteData(Comm, Param.asObject['PARAMS']);
try
if obj2<>Param.asObject['PARAMS'] then
Param.isNull['PARAMS']:=True
else
Param.asObject['PARAMS']:=nil;
if vname<>'' then
vname:=vname+'.'+GetAsString(obj2)
else
vname:=GetAsString(obj2);
finally
obj2.Free;
end;
end;
if vname<>'' then
begin
obj3:=Get_Variable(vname,isCopy,asAddr);
if isCopy then
Res.asObject:=obj3
else if assigned(obj3) then
Res.asObject:=obj3.copyOf;
end;
end;
procedure ExecuteRecursiveCall;
var
temp:TRtcValueObject;
tempLocals:TRtcRecord;
par:TRtcRecord;
fname:string;
i:integer;
begin
what:=3; // Calling script function "vname"
if Comm.MaxRecurse>0 then
if Comm.RecurseCount>=Comm.MaxRecurse then
raise ERtcScript.Create('Maximum allowed Recursion Depth exceeded.')
else
Inc(Comm.RecurseCount);
try
Par:=TRtcRecord.Create;
try
for i:=0 to Param.FieldCount-1 do
begin
fname:=Param.FieldName[i];
if (fname<>'$C') and (fname<>'$R') and (fname<>'$V') then
begin
Par.asObject[fname]:=Comm.Group.ExecuteData(Comm, Param.asObject[fname]);
if Par.asObject[fname]<>Param.asObject[fname] then
Param.isNull[fname]:=True
else
Param.asObject[fname]:=nil;
end;
end;
temp:=TRtcFunctionInfo(obj).asObject['X'];
if assigned(temp) then
temp:=temp.copyOf;
try
// changing Local variables to Global variables
// and input parameters to Local variables
tempLocals:=Comm.Locals;
Comm.Locals:=Par;
obj:=nil;
try
obj:=Comm.Group.ExecuteData(Comm, temp);
finally
Comm.Locals:=tempLocals;
if assigned(obj) and (obj<>temp) then obj.Free;
end;
finally
if assigned(temp) then temp.Free;
end;
// Get the result
Res.asObject:=Par.asObject['RESULT'];
Par.asObject['RESULT']:=nil;
finally
Par.Free;
end;
finally
if Comm.MaxRecurse>0 then
Dec(Comm.RecurseCount);
end;
end;
begin
what:=0; // 'Checking variable';
try
vname:=Param.asVarName['$V'];
asAddr:=Param.asBoolean['$A'];
if vname='' then
ExtractNamedValue
else if vname='-' then // Sender variables
begin
vname:=CheckParam('$P').asVarName;
vname:='-'+vname;
ExtractNamedValue;
end
else
begin
what:=1; // 'Reading variable "'+vname+'"';
obj:=Get_Variable(vname,isCopy,asAddr);
if assigned(obj) and not isCopy then
begin
if obj is TRtcFunctionInfo then
begin
if TRtcFunctionInfo(obj).FunctionName='!!' then
begin
if assigned(TRtcFunctionInfo(obj).asObject['X']) then
ExecuteRecursiveCall;
end
else
Res.asObject:=Execute(obj);
end
else if not isSimpleValue(obj) then
ExtractPropertyValue
else
Res.asObject:=obj.copyOf;
end
else
Res.asObject:=obj;
end;
except
on E:Exception do
begin
if E is ERtcForward then
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '
else
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.ClassName+' ';
case what of
0:func:=func+'Variable Access';
1:func:=func+'Reading Variable "$'+vname+'"';
2:func:=func+'Reading Variable "$'+vname+'()"';
3:func:=func+'Calling Function "$'+vname+'"';
end;
if Pos(func,E.Message)>0 then
begin
if Copy(E.Message,1,1)='>' then
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.Message)
else
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+']'+#13#10+E.Message);
end
else
raise ERtcForward.Create(func+#13#10+E.Message);
end;
end;
end;
procedure Execute_Property;
var
vname,vname2:string;
what:byte;
begin
what:=0; // 'Checking property';
try
vname:=Param.asVarName['$V'];
what:=1; // 'Reading property "'+vname+'"';
vname2:=CheckParam('X').asString;
if vname2<>'' then
begin
if vname<>'' then vname:=vname+'.';
vname:=vname+vname2;
end;
Res.asString:=vname;
except
on E:Exception do
begin
if E is ERtcForward then
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '
else
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.ClassName+' ';
case what of
0:func:=func+'Property Access';
1:func:=func+'Reading Property ".'+vname+'"';
end;
if Pos(func,E.Message)>0 then
begin
if Copy(E.Message,1,1)='>' then
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.Message)
else
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+']'+#13#10+E.Message);
end
else
raise ERtcForward.Create(func+#13#10+E.Message);
end;
end;
end;
procedure CollapseArray(const obj:TRtcValue; makeNull:boolean=True);
var
i,cnt,x:integer;
arr:TRtcArray;
begin
if obj.isType=rtc_Array then
begin
arr:=obj.asArray;
cnt:=0; x:=0;
for i:=0 to arr.Count-1 do
if arr.isType[i]<>rtc_Null then
begin
x:=i;
Inc(cnt);
if cnt>1 then Break;
end;
if makeNull and (cnt=0) then
obj.isNull:=True
else if cnt=1 then
begin
obj.asObject:=nil;
obj.asObject:=arr.asObject[x];
arr.asObject[x]:=nil;
arr.Free;
end;
end;
end;
procedure ExtractX;
begin
ExecuteParam_X;
CollapseArray(obj);
end;
procedure ExtractY;
begin
ExecuteParamB_Y;
CollapseArray(objB);
end;
procedure ExtractBoth;
begin
ExecuteParam_X;
CollapseArray(obj);
ExecuteParamB_Y;
CollapseArray(objB);
end;
procedure ClearBoth;
begin
obj.isNull:=True;
objB.isNull:=True;
end;
function SetOneNull:boolean;
begin
if obj.isType=rtc_Null then
begin
Res.asObject := objB.asObject;
objB.asObject := nil;
Result:=True;
end
else if objB.isType=rtc_Null then
begin
Res.asObject := obj.asObject;
obj.asObject := nil;
Result:=True;
end
else
Result:=False;
end;
procedure ResSetB;
begin
Res.asObject:=objB.asObject;
objB.asObject:=nil;
end;
procedure ResSet;
begin
Res.asObject:=obj.asObject;
obj.asObject:=nil;
end;
procedure Do_Set;
begin
ExecuteParamB_Y;
CollapseArray(objB,False);
ResSetB;
end;
procedure Do_Property;
var
isCopy:boolean;
ObjX:TRtcValueObject;
myvar3:TRtcValueObject;
myvar2:TRtcFunctionInfo;
vname,vname2:string;
asAddr:boolean;
begin
myvar3:=nil;
myvar2:=Param;
vname:='';
repeat
objX:=Execute(myvar2.asObject['Y']);
try
vname2:=GetAsString(objX);
if vname2<>'' then
if vname<>'' then
vname:=vname2+'.'+vname
else
vname:=vname2;
finally
objX.Free;
end;
if myvar2.isType['X']=rtc_Function then
begin
if (myvar2.asFunction['X'].FunctionName='$') then
begin
myvar2:=TRtcFunctionInfo(myvar2.asObject['X']);
Break;
end
else if (myvar2.asFunction['X'].FunctionName='?') and (myvar2.asFunction['X'].asString['C']='.') then
myvar2:=TRtcFunctionInfo(myvar2.asObject['X'])
else
begin
myvar3:=TRtcFunctionInfo(myvar2.asObject['X']);
myvar2:=nil;
Break;
end;
end
else
begin
myvar3:=TRtcFunctionInfo(myvar2.asObject['X']);
myvar2:=nil;
Break;
end;
until not assigned(myvar2);
if assigned(myvar3) then
begin // static data (not a variable)
objX:=Execute(myvar3);
try
if assigned(objX) then
begin
isCopy:=False;
Res.asObject:=Get_Property(objX,vname,isCopy,False);
if not isCopy then objX:=nil;
end;
finally
if assigned(objX) then objX.Free;
end;
end
else
begin
objX:=Execute(myvar2.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname2:=GetAsString(objX);
if vname2<>'' then
begin
if vname<>'' then vname:='.'+vname;
vname:=vname2+vname;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
vname2:=myvar2.asVarName['$V'];
if vname2='-' then
vname2:=vname2+myvar2.asVarName['$P'];
if vname2<>'' then
begin
if vname<>'' then vname:='.'+vname;
vname:=vname2+vname;
end;
asAddr:=myvar2.asBoolean['$A'];
isCopy:=False;
ObjX:=Get_Variable(vname,isCopy,asAddr);
if isCopy then
Res.asObject:=ObjX
else if assigned(ObjX) then
Res.asObject:=ObjX.copyOf;
end;
end;
procedure Do_Plus;
begin
ExtractBoth;
if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText + objB.asText;
rtc_String: Res.asString := obj.asString + objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString + objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean or objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger + objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt + objB.asLargeInt;
rtc_Float: Res.asFloat := obj.asFloat + objB.asFloat;
rtc_Currency: Res.asCurrency := obj.asCurrency + objB.asCurrency;
rtc_DateTime: Res.asDateTime := obj.asDateTime + objB.asDateTime;
rtc_Variant: Res.asValue := obj.asValue + objB.asValue;
{rtc_Array:
rtc_ByteStream:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not add '+rtcTypeName(obj.isType)+' to '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Minus;
begin
ExtractBoth;
if obj.isNull then
begin
SetOneNull;
ctype:=Res.isType;
if ctype<>rtc_Null then
begin
case ctype of
rtc_Text: Res.asText := '-'+Res.asText;
rtc_String: Res.asString := '-'+Res.asString;
rtc_WideString: Res.asWideString := '-'+Res.asWideString;
rtc_Boolean: Res.asBoolean := not Res.asBoolean;
rtc_Integer: Res.asInteger := - Res.asInteger;
rtc_LargeInt: Res.asLargeInt := - Res.asLargeInt;
rtc_Float: Res.asFloat := - Res.asFloat;
rtc_Currency: Res.asCurrency := - Res.asCurrency;
rtc_DateTime: Res.asDateTime := - Res.asDateTime;
rtc_Variant: Res.asValue := - Res.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not negate '+rtcTypeName(Res.isType));
end;
end;
end
else if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+'-'+objB.asText;
rtc_String: Res.asString := obj.asString+'-'+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+'-'+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean xor objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger - objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt - objB.asLargeInt;
rtc_Float: Res.asFloat := obj.asFloat - objB.asFloat;
rtc_Currency: Res.asCurrency := obj.asCurrency - objB.asCurrency;
rtc_DateTime: Res.asDateTime := obj.asDateTime - objB.asDateTime;
rtc_Variant: Res.asValue := obj.asValue - objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not subtract '+rtcTypeName(objB.isType)+' from '+rtcTypeName(obj.isType));
end;
end;
end;
procedure Do_Shl;
begin
ExtractBoth;
if obj.isNull then
// NULL << X = NULL
ClearBoth
else if objB.isNull then
// X << NULL = X
SetOneNull
else if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+'<<'+objB.asText;
rtc_String: Res.asString := obj.asString+'<<'+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+'<<'+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean xor objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger shl objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt shl objB.asLargeInt;
rtc_Float: Res.asFloat := round(obj.asFloat) shl round(objB.asFloat);
rtc_Currency: Res.asCurrency := round(obj.asCurrency) shl round(objB.asCurrency);
rtc_DateTime: Res.asDateTime := round(obj.asDateTime) shl round(objB.asDateTime);
rtc_Variant: Res.asValue := obj.asValue shl objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not execute '+rtcTypeName(objB.isType)+' SHL '+rtcTypeName(obj.isType));
end;
end;
end;
procedure Do_Shr;
begin
ExtractBoth;
if obj.isNull then
// NULL >> X = NULL
ClearBoth
else if objB.isNull then
// X >> NULL = X
SetOneNull
else if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+'>>'+objB.asText;
rtc_String: Res.asString := obj.asString+'>>'+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+'>>'+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean xor objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger shr objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt shr objB.asLargeInt;
rtc_Float: Res.asFloat := round(obj.asFloat) shr round(objB.asFloat);
rtc_Currency: Res.asCurrency := round(obj.asCurrency) shr round(objB.asCurrency);
rtc_DateTime: Res.asDateTime := round(obj.asDateTime) shr round(objB.asDateTime);
rtc_Variant: Res.asValue := obj.asValue shr objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not execute '+rtcTypeName(objB.isType)+' SHR '+rtcTypeName(obj.isType));
end;
end;
end;
procedure Do_Multiply;
begin
ExtractBoth;
if SetOneNull then
begin
// A * NULL = NULL
// NULL * A = NULL
Res.isNull:=True;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+'*'+objB.asText;
rtc_String: Res.asString := obj.asString+'*'+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+'*'+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean and objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger * objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt * objB.asLargeInt;
rtc_Float: Res.asFloat := obj.asFloat * objB.asFloat;
rtc_Currency: Res.asCurrency := obj.asCurrency * objB.asCurrency;
rtc_DateTime: Res.asDateTime := obj.asDateTime * objB.asDateTime;
rtc_Variant: Res.asValue := obj.asValue * objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not multiply '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Divide;
begin
ExtractBoth;
if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+'/'+objB.asText;
rtc_String: Res.asString := obj.asString+'/'+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+'/'+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean xor objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger div objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt div objB.asLargeInt;
rtc_Float: Res.asFloat := obj.asFloat / objB.asFloat;
rtc_Currency: Res.asCurrency := obj.asCurrency / objB.asCurrency;
rtc_DateTime: Res.asDateTime := obj.asDateTime / objB.asDateTime;
rtc_Variant: Res.asValue := obj.asValue / objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not divide '+rtcTypeName(obj.isType)+' by '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Modulo;
begin
ExtractBoth;
if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+'%'+objB.asText;
rtc_String: Res.asString := obj.asString+'%'+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+'%'+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean xor objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger mod objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt mod objB.asLargeInt;
rtc_Float: Res.asFloat := frac(obj.asFloat / objB.asFloat)*objB.asFloat;
rtc_Currency: Res.asCurrency := frac(obj.asCurrency / objB.asCurrency)*objB.asCurrency;
rtc_DateTime: Res.asDateTime := frac(obj.asDateTime / objB.asDateTime)*objB.asDateTime;
rtc_Variant: Res.asValue := frac(obj.asValue / objB.asValue)*objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not execute '+rtcTypeName(obj.isType)+' MOD '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_And;
begin
ExtractBoth;
if SetOneNull then
begin
// A & NULL = NULL
// NULL & A = NULL
Res.isNull:=True;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+objB.asText;
rtc_String: Res.asString := obj.asString+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean and objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger and objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt and objB.asLargeInt;
rtc_Float: Res.asFloat := round(obj.asFloat) and round(objB.asFloat);
rtc_Currency: Res.asCurrency := round(obj.asCurrency) and round(objB.asCurrency);
rtc_DateTime: Res.asDateTime := round(obj.asDateTime) and round(objB.asDateTime);
rtc_Variant: Res.asValue := obj.asValue and objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not execute '+rtcTypeName(obj.isType)+' AND '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Or;
begin
ExtractBoth;
if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asText := obj.asText+objB.asText;
rtc_String: Res.asString := obj.asString+objB.asString;
rtc_WideString: Res.asWideString := obj.asWideString+objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean or objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger or objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt or objB.asLargeInt;
rtc_Float: Res.asFloat := round(obj.asFloat) or round(objB.asFloat);
rtc_Currency: Res.asCurrency := round(obj.asCurrency) or round(objB.asCurrency);
rtc_DateTime: Res.asDateTime := round(obj.asDateTime) or round(objB.asDateTime);
rtc_Variant: Res.asValue := obj.asValue or objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not execute '+rtcTypeName(obj.isType)+' OR '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Max;
begin
ExtractBoth;
if not (obj.isNull or objB.isNull) then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: if (obj.asText<=objB.asText) then ResSet;
rtc_String: if (obj.asString<=objB.asString) then ResSet;
rtc_WideString: if (obj.asWideString<=objB.asWideString) then ResSet;
rtc_Boolean: if (obj.asBoolean<=objB.asBoolean) then ResSet;
rtc_Integer: if (obj.asInteger<=objB.asInteger) then ResSet;
rtc_LargeInt: if (obj.asLargeInt<=objB.asLargeInt) then ResSet;
rtc_Float: if (obj.asFloat<=objB.asFloat) then ResSet;
rtc_Currency: if (obj.asCurrency<=objB.asCurrency) then ResSet;
rtc_DateTime: if (obj.asDateTime<=objB.asDateTime) then ResSet;
rtc_Variant: if (obj.asValue<=objB.asValue) then ResSet;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not compare '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Min;
begin
ExtractBoth;
if not (obj.isNull or objB.isNull) then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: if (obj.asText>=objB.asText) then ResSet;
rtc_String: if (obj.asString>=objB.asString) then ResSet;
rtc_WideString: if (obj.asWideString>=objB.asWideString) then ResSet;
rtc_Boolean: if (obj.asBoolean>=objB.asBoolean) then ResSet;
rtc_Integer: if (obj.asInteger>=objB.asInteger) then ResSet;
rtc_LargeInt: if (obj.asLargeInt>=objB.asLargeInt) then ResSet;
rtc_Float: if (obj.asFloat>=objB.asFloat) then ResSet;
rtc_Currency: if (obj.asCurrency>=objB.asCurrency) then ResSet;
rtc_DateTime: if (obj.asDateTime>=objB.asDateTime) then ResSet;
rtc_Variant: if (obj.asValue>=objB.asValue) then ResSet;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not compare '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Xor;
begin
ExtractBoth;
if not SetOneNull then
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Boolean: Res.asBoolean := obj.asBoolean xor objB.asBoolean;
rtc_Integer: Res.asInteger := obj.asInteger xor objB.asInteger;
rtc_LargeInt: Res.asLargeInt := obj.asLargeInt xor objB.asLargeInt;
rtc_Float: Res.asFloat := round(obj.asFloat) xor round(objB.asFloat);
rtc_Currency: Res.asCurrency := round(obj.asCurrency) xor round(objB.asCurrency);
rtc_DateTime: Res.asDateTime := round(obj.asDateTime) xor round(objB.asDateTime);
rtc_Variant: Res.asValue := obj.asValue xor objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not execute '+rtcTypeName(obj.isType)+' XOR '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Not;
begin
ExtractY;
SetOneNull;
case Res.isType of
rtc_Text: Res.asText := '!'+Res.asText;
rtc_String: Res.asString := '!'+Res.asString;
rtc_WideString: Res.asWideString := '!'+Res.asWideString;
rtc_Boolean: Res.asBoolean := not Res.asBoolean;
rtc_Integer: Res.asInteger := not Res.asInteger;
rtc_LargeInt: Res.asLargeInt := not Res.asLargeInt;
rtc_Float: Res.asFloat := not round(Res.asFloat);
rtc_Currency: Res.asCurrency := not round(Res.asCurrency);
rtc_DateTime: Res.asDateTime := not round(Res.asDateTime);
rtc_Variant: Res.asValue := not Res.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not negate '+rtcTypeName(Res.isType));
end;
end;
procedure Do_Chr;
var
ch:integer;
begin
ExtractY;
SetOneNull;
case Res.isType of
rtc_Text: ch := StrToInt(Res.asText);
rtc_String: ch := StrToInt(Res.asString);
rtc_WideString: ch := StrToInt(Res.asWideString);
rtc_Boolean: if Res.asBoolean then ch := 0 else ch := 1;
rtc_Integer: ch := Res.asInteger;
rtc_LargeInt: ch := Res.asLargeInt;
rtc_Float: ch := round(Res.asFloat);
rtc_Currency: ch := round(Res.asCurrency);
rtc_DateTime: ch := round(Res.asDateTime);
rtc_Variant: ch := round(Res.asValue);
rtc_Array: ch := StrToInt(Res.asString);
{rtc_ByteStream:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not get Integer from '+rtcTypeName(Res.isType));
end;
ExtractX;
Res.isNull:=True;
if assigned(obj) then
Res.asString:=obj.asString+Char(ch)
else
Res.asString:=Char(ch);
end;
procedure Do_Greater;
begin
ExtractBoth;
if objB.isNull then
begin
// NULL > NULL = FALSE
// X > NULL = TRUE
Res.asBoolean:= not obj.isNull;
ClearBoth;
end
else if obj.isNull then
begin
// NULL > X = FALSE
Res.asBoolean:=False;
ClearBoth;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asBoolean := obj.asText > objB.asText;
rtc_String: Res.asBoolean := obj.asString > objB.asString;
rtc_WideString: Res.asBoolean := obj.asWideString > objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean > objB.asBoolean;
rtc_Integer: Res.asBoolean := obj.asInteger > objB.asInteger;
rtc_LargeInt: Res.asBoolean := obj.asLargeInt > objB.asLargeInt;
rtc_Float: Res.asBoolean := obj.asFloat > objB.asFloat;
rtc_Currency: Res.asBoolean := obj.asCurrency > objB.asCurrency;
rtc_DateTime: Res.asBoolean := obj.asDateTime > objB.asDateTime;
rtc_Variant: Res.asBoolean := obj.asValue > objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not compare '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_GreaterEqual;
begin
ExtractBoth;
if objB.isNull then
begin
// NULL >= NULL = TRUE
// X >= NULL = TRUE
Res.asBoolean:= True;
ClearBoth;
end
else if obj.isNull then
begin
// NULL >= X = FALSE
Res.asBoolean:=False;
ClearBoth;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asBoolean := obj.asText >= objB.asText;
rtc_String: Res.asBoolean := obj.asString >= objB.asString;
rtc_WideString: Res.asBoolean := obj.asWideString >= objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean >= objB.asBoolean;
rtc_Integer: Res.asBoolean := obj.asInteger >= objB.asInteger;
rtc_LargeInt: Res.asBoolean := obj.asLargeInt >= objB.asLargeInt;
rtc_Float: Res.asBoolean := obj.asFloat >= objB.asFloat;
rtc_Currency: Res.asBoolean := obj.asCurrency >= objB.asCurrency;
rtc_DateTime: Res.asBoolean := obj.asDateTime >= objB.asDateTime;
rtc_Variant: Res.asBoolean := obj.asValue >= objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not compare '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Lower;
begin
ExtractBoth;
if obj.isNull then
begin
// NULL < NULL = FALSE
// NULL < X = TRUE
Res.asBoolean:= not objB.isNull;
ClearBoth;
end
else if objB.isNull then
begin
// X < NULL = FALSE
Res.asBoolean:=False;
ClearBoth;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asBoolean := obj.asText < objB.asText;
rtc_String: Res.asBoolean := obj.asString < objB.asString;
rtc_WideString: Res.asBoolean := obj.asWideString < objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean < objB.asBoolean;
rtc_Integer: Res.asBoolean := obj.asInteger < objB.asInteger;
rtc_LargeInt: Res.asBoolean := obj.asLargeInt < objB.asLargeInt;
rtc_Float: Res.asBoolean := obj.asFloat < objB.asFloat;
rtc_Currency: Res.asBoolean := obj.asCurrency < objB.asCurrency;
rtc_DateTime: Res.asBoolean := obj.asDateTime < objB.asDateTime;
rtc_Variant: Res.asBoolean := obj.asValue < objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not compare '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_LowerEqual;
begin
ExtractBoth;
if obj.isNull then
begin
// NULL <= NULL = TRUE
// NULL <= X = TRUE
Res.asBoolean:= True;
ClearBoth;
end
else if objB.isNull then
begin
// X <= NULL = FALSE
Res.asBoolean:=False;
ClearBoth;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asBoolean := obj.asText <= objB.asText;
rtc_String: Res.asBoolean := obj.asString <= objB.asString;
rtc_WideString: Res.asBoolean := obj.asWideString <= objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean <= objB.asBoolean;
rtc_Integer: Res.asBoolean := obj.asInteger <= objB.asInteger;
rtc_LargeInt: Res.asBoolean := obj.asLargeInt <= objB.asLargeInt;
rtc_Float: Res.asBoolean := obj.asFloat <= objB.asFloat;
rtc_Currency: Res.asBoolean := obj.asCurrency <= objB.asCurrency;
rtc_DateTime: Res.asBoolean := obj.asDateTime <= objB.asDateTime;
rtc_Variant: Res.asBoolean := obj.asValue <= objB.asValue;
{rtc_ByteStream:
rtc_Array:
rtc_Record:
rtc_DataSet:}
else
raise ERtcScript.Create('Can not compare '+rtcTypeName(obj.isType)+' and '+rtcTypeName(objB.isType));
end;
end;
end;
procedure Do_Equal;
begin
ExtractBoth;
if obj.isNull then
begin
// NULL = NULL = TRUE
// NULL = X = FALSE
Res.asBoolean:= objB.isNull;
ClearBoth;
end
else if objB.isNull then
begin
// X = NULL = FALSE
Res.asBoolean:=False;
ClearBoth;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asBoolean := obj.asText = objB.asText;
rtc_String: Res.asBoolean := obj.asString = objB.asString;
rtc_WideString: Res.asBoolean := obj.asWideString = objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean = objB.asBoolean;
rtc_Integer: Res.asBoolean := obj.asInteger = objB.asInteger;
rtc_LargeInt: Res.asBoolean := obj.asLargeInt = objB.asLargeInt;
rtc_Float: Res.asBoolean := obj.asFloat = objB.asFloat;
rtc_Currency: Res.asBoolean := obj.asCurrency = objB.asCurrency;
rtc_DateTime: Res.asBoolean := obj.asDateTime = objB.asDateTime;
rtc_Variant: Res.asBoolean := obj.asValue = objB.asValue;
else Res.asBoolean := obj.toCode = objB.toCode;
end;
end;
end;
procedure Do_NotEqual;
begin
ExtractBoth;
if obj.isNull then
begin
// NULL != NULL = FALSE
// NULL != X = TRUE
Res.asBoolean:= not objB.isNull;
ClearBoth;
end
else if objB.isNull then
begin
// X != NULL = TRUE
Res.asBoolean:=True;
ClearBoth;
end
else
begin
ctype:=rtcCombineTypes(obj.isType, objB.isType);
case ctype of
rtc_Text: Res.asBoolean := obj.asText <> objB.asText;
rtc_String: Res.asBoolean := obj.asString <> objB.asString;
rtc_WideString: Res.asBoolean := obj.asWideString <> objB.asWideString;
rtc_Boolean: Res.asBoolean := obj.asBoolean <> objB.asBoolean;
rtc_Integer: Res.asBoolean := obj.asInteger <> objB.asInteger;
rtc_LargeInt: Res.asBoolean := obj.asLargeInt <> objB.asLargeInt;
rtc_Float: Res.asBoolean := obj.asFloat <> objB.asFloat;
rtc_Currency: Res.asBoolean := obj.asCurrency <> objB.asCurrency;
rtc_DateTime: Res.asBoolean := obj.asDateTime <> objB.asDateTime;
rtc_Variant: Res.asBoolean := obj.asValue <> objB.asValue;
else Res.asBoolean := obj.toCode <> objB.toCode;
end;
end;
end;
procedure Do_New;
var
typ:string;
begin
typ:=UpperCase(Param.asString['X']);
if typ='ARRAY' then
Res.NewArray
else if typ='RECORD' then
Res.NewRecord
else if typ='DATASET' then
Res.NewDataSet
else if (typ='STREAM') or (typ='BYTESTREAM') then
Res.NewByteStream
else if (typ='INTEGER') or (typ='INT') or (typ='INT32') then
Res.NewInteger
else if (typ='LARGEINT') or (typ='INT64') then
Res.NewLargeInt
else if (typ='DATETIME') or (typ='DATE') or (typ='TIME') then
Res.NewDateTime
else if (typ='FLOAT') or (typ='DOUBLE') then
Res.NewFloat
else if (typ='CURRENCY') then
Res.NewCurrency
else if (typ='BOOLEAN') or (typ='BOOL') then
Res.NewBoolean
else if (typ='WIDESTRING') then
Res.NewWideString
else if (typ='TEXT') then
Res.NewText
else
raise ERtcScript.Create('Type not supported for NEW');
end;
procedure Execute_Function;
begin
try
if length(func)=1 then
begin
case func[1] of
'#':Do_Chr;
'+':Do_Plus;
'-':Do_Minus;
'*':Do_Multiply;
'/':Do_Divide;
'%':Do_Modulo;
'&':Do_And;
'|':Do_Or;
'!':Do_Not;
'>':Do_Greater;
'<':Do_Lower;
'=':Do_Equal;
'.':Do_Property;
//'^':
else
raise ERtcScript.Create('Function "'+func+'" not found');
end;
end
else if length(func)=2 then
begin
if func[2]='=' then
begin
case func[1] of
'=':Do_Equal;
'!':Do_NotEqual;
'>':Do_GreaterEqual;
'<':Do_LowerEqual;
else
raise ERtcScript.Create('Function "'+func+'" not found');
end;
end
else if func=':>' then Do_Min
else if func=':<' then Do_Max
else if func='<>' then Do_NotEqual
else if func='<<' then Do_Shr
else if func='>>' then Do_Shl
else if func='OR' then Do_Or
else
raise ERtcScript.Create('Function "'+func+'" not found');
end
else if func='AND' then Do_And
else if func='XOR' then Do_Xor
else if func='SHL' then Do_Shl
else if func='SHR' then Do_Shr
else if func='MOD' then Do_Modulo
else if func='DIV' then Do_Divide
else if func='NOT' then Do_Not
else if func='NEW' then Do_New
else
raise ERtcScript.Create('Function "'+func+'" not found');
finally
objB.isNull:=True;
obj.isNull:=True;
end;
end;
procedure Execute_Assignment;
var
myvar,myvar2: TRtcFunctionInfo;
vname,vname2:string;
what:byte;
asAddr:boolean;
objX:TRtcValueObject;
begin
what:=0;
try
try
if Param.isType['X']<>rtc_Function then
raise ERtcScript.Create('Left side can not be assigned to');
if func[1]=':' then
begin
myvar:=TRtcFunctionInfo(Param.asObject['X']);
Param.asObject['X']:=nil;
end
else
myvar:=TRtcFunctionInfo(Param.asObject['X'].copyOf);
try
if (func[1]=':') and
(Param.isType['Y']=rtc_Function) and
(Param.asFunction['Y'].FunctionName='@') then
begin
Res.asObject:=Param.asFunction['Y'].asObject['Y'];
Param.asFunction['Y'].asObject['Y']:=nil;
end
else
begin
case func[1] of
'+':Do_Plus;
'-':Do_Minus;
'*':Do_Multiply;
'/':Do_Divide;
'%':Do_Modulo;
'&':Do_And;
'|':Do_Or;
'!':Do_Not;
':':Do_Set;
//'^':
else
raise ERtcScript.Create('Function "'+func+'" not found');
end;
end;
if (myvar.FunctionName='$') then
begin
vname:=myvar.asVarName['$V'];
if vname='-' then
vname:=vname+myvar.asVarName['$P'];
asAddr:=myvar.asBoolean['$A'];
objX:=Execute(myvar.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname2:=GetAsString(objX);
if vname2<>'' then
begin
if vname<>'' then vname:=vname+'.';
vname:=vname+vname2;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
if asAddr then what:=2 else what:=1;
objX:=Res.asObject;
Res.asObject:=nil;
Set_Variable(vname, objX, asAddr);
end
else if (myvar.FunctionName='?') and (myvar.asString['C']='.') then
begin
vname:='';
myvar2:=myvar;
repeat
objX:=Execute(myvar2.asObject['Y']);
try
vname2:=GetAsString(objX);
if vname2<>'' then
if vname<>'' then
vname:=vname2+'.'+vname
else
vname:=vname2;
finally
objX.Free;
end;
if myvar2.isType['X']<>rtc_Function then
raise ERtcScript.Create('Left side can not be assigned to');
myvar2:=TRtcFunctionInfo(myvar2.asObject['X']);
until (myvar2.FunctionName<>'?') or (myvar2.asString['C']<>'.');
if myvar2.FunctionName<>'$' then
raise ERtcScript.Create('Left side can not be assigned to');
objX:=Execute(myvar2.asObject['PARAMS']);
try
if assigned(objX) then
begin
vname2:=GetAsString(objX);
if vname2<>'' then
begin
if vname<>'' then vname:='.'+vname;
vname:=vname2+vname;
end;
end;
finally
if assigned(ObjX) then ObjX.Free;
end;
vname2:=myvar2.asVarName['$V'];
if vname2='-' then
vname2:=vname2+myvar2.asVarName['$P'];
if vname2<>'' then
begin
if vname<>'' then vname:='.'+vname;
vname:=vname2+vname;
end;
asAddr:=myvar2.asBoolean['$A'];
if asAddr then what:=2 else what:=1;
objX:=Res.asObject;
Res.asObject:=nil;
Set_Variable(vname, objX, asAddr);
end
else
raise ERtcScript.Create('Left side can not be assigned to');
finally
myvar.Free;
end;
except
on E:Exception do
begin
if E is ERtcForward then
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '
else
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.ClassName+' ';
case what of
0:func:=func+'Assignment';
1:func:=func+'Setting variable "$'+vname+'"';
2:func:=func+'Setting variable "@'+vname+'"';
end;
if Pos(func,E.Message)>0 then
begin
if Copy(E.Message,1,1)='>' then
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.Message)
else
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+']'+#13#10+E.Message);
end
else
raise ERtcForward.Create(func+#13#10+E.Message);
end;
end;
finally
objB.isNull:=True;
obj.isNull:=True;
end;
end;
procedure Execute_NewFunction;
var
vname:string;
begin
vname:=Param.asVarName['V'];
Comm.Locals.isNull[vname]:=True;
with Comm.Locals.newFunction(vname,'!!') do
asObject['X']:=Param.asObject['X'];
Param.asObject['X']:=nil;
end;
begin
Comm:=TRtcScriptCommandInfo(CmdInfo);
if Comm.StopTime>0 then
if GetTickCount>Comm.StopTime then
raise ERtcScript.Create('Script Execution Time Limit exceeded.');
if Comm.MaxDepth>0 then
if Comm.CodeDepth>=Comm.MaxDepth then
raise ERtcScript.Create('Maximum Script code depth exceeded.')
else
Inc(Comm.CodeDepth);
try
if Param.FunctionName='!' then // Commands
begin
Result:=True;
obj:=TRtcValue.Create;
try
try
func:=UpperCase(Param.asString['C']);
case func[1] of
'I':Execute_If;
'R':Execute_Repeat;
'W':Execute_While;
'F':Execute_For;
'E':Execute_ForEach;
'X':Execute_NewFunction;
else
raise ERtcScript.Create('Unknown command: "'+func+'"');
end;
except
on E:Exception do
begin
case func[1] of
'I':func:='"IF" statement';
'R':func:='"REPEAT" loop';
'W':func:='"WHILE" loop';
'F':func:='"FOR" loop';
'E':func:='"FOREACH" loop';
'X':func:='Script "FUNCTION"';
else raise;
end;
if E is ERtcForward then
begin
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] '+func;
if Pos(func,E.Message)>0 then
begin
if Copy(E.Message,1,1)='>' then
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.Message)
else
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+']'+#13#10+E.Message);
end
else
raise ERtcForward.Create(func+#13#10+E.Message);
end
else
raise ERtcForward.Create('['+Param.asString['$R']+':'+Param.asString['$C']+'] '+
E.ClassName+' in '+func+':'+#13#10+E.Message);
end;
end;
finally
obj.asObject:=nil;
obj.Free;
end;
end
else if Param.FunctionName='?' then // Functions
begin
Result:=True;
obj:=TRtcValue.Create;
objB:=TRtcValue.Create;
try
try
func:=UpperCase(Param.asString['C']);
Execute_Function;
except
on E:ERtcForward do
begin
func:='['+Param.asString['$R']+':'+Param.asString['$C']+'] Function "'+func+'"';
if Pos(func,E.Message)>0 then
begin
if Copy(E.Message,1,1)='>' then
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+'] '+E.Message)
else
raise ERtcForward.Create('>['+Param.asString['$R']+':'+Param.asString['$C']+']'+#13#10+E.Message);
end
else
raise ERtcForward.Create(func+#13#10+E.Message);
end;
on E:Exception do
raise ERtcForward.Create('['+Param.asString['$R']+':'+Param.asString['$C']+'] '+
E.ClassName+' in Function "'+func+'":'+#13#10+E.Message);
end;
finally
obj.asObject:=nil;
obj.Free;
objB.asObject:=nil;
objB.Free;
end;
end
else if Param.FunctionName='$!' then // variable assignment
begin
Result:=True;
obj:=TRtcValue.Create;
objB:=TRtcValue.Create;
try
func:=UpperCase(Param.asString['C']);
Execute_Assignment;
finally
obj.asObject:=nil;
obj.Free;
objB.asObject:=nil;
objB.Free;
end;
end
else if Param.FunctionName='$.' then // property string
begin
Result:=True;
obj:=TRtcValue.Create;
try
Execute_Property;
finally
obj.asObject:=nil;
obj.Free;
end;
end
else if Param.FunctionName='$' then // read variable
begin
Result:=True;
obj:=TRtcValue.Create;
try
Execute_Variable;
finally
obj.asObject:=nil;
obj.Free;
end;
end
else if Param.FunctionName='@' then // extract data
begin
Result:=True;
Res.asObject:=Param.asObject['Y'];
Param.asObject['Y']:=nil;
end
else
Result:=False;
finally
if Comm.MaxDepth>0 then
Dec(Comm.CodeDepth);
end;
end;
function TRtcScriptEngine.Execute(const Sender: TRtcConnection;
const CompiledScript: TRtcValueObject;
recursive:boolean=False): TRtcValue;
var
Comm:TRtcScriptCommandInfo;
obj:TRtcValueObject;
begin
Result:=nil;
obj:=nil;
try
if not assigned(FGroup) then
raise Exception.Create('Need a FunctionGroup to execute a Script.');
// create temporary storage
Comm:=TRtcScriptCommandInfo.Create;
try
Comm.Sender:=Sender;
Comm.Locals:=TRtcRecord.Create;
Comm.Globals:=Comm.Locals;
Comm.Command:=self;
Comm.Group:=FGroup;
Comm.MaxDepth:=FMaxCodeDepth;
Comm.MaxRecurse:=FMaxRecursion;
Comm.MaxLoop:=FMaxLoopCount;
if FMaxExecutionTime>0 then
Comm.StopTime:=GetTickCount+FMaxExecutionTime*1000
else
Comm.StopTime:=0;
Comm.RecurseCount:=0;
try
// Execute script
obj:=FGroup.ExecuteData(Comm, CompiledScript, recursive);
if obj is TRtcValue then
Result:=TRtcValue(obj)
else
begin
Result:=TRtcValue.Create;
Result.asObject:=obj;
end;
finally
Comm.Globals.Free;
Comm.Free;
end;
except
on E:ERtcForward do
raise ERtcScript.Create(E.Message);
end;
finally
if obj<>CompiledScript then
CompiledScript.Free;
end;
end;
function TRtcScriptEngine.Compile(const Script: string; const FileName:string=''): TRtcValue;
var
Compiler:TRtcScriptCompiler;
begin
Compiler:=TRtcScriptCompiler.Create;
try
Compiler.FunctionGroup:= FGroup;
Compiler.DenyRTCFunctionCalls:= DenyRTCFunctionCalls;
Compiler.DenyScriptFunctionCalls:= DenyScriptFunctionCalls;
if FileName<>'' then
begin
Compiler.FilePath:= ExtractFilePath(FileName);
Compiler.FileName:= ExtractFileName(FileName);
end;
Compiler.ScriptOpen:=FScriptOpen;
Compiler.ScriptClose:=FScriptClose;
Compiler.Script:= Script;
Result:= Compiler.Compile;
finally
Compiler.Free;
end;
end;
procedure TRtcScriptEngine.SetScriptClose(const Value: string);
begin
if length(Value)<>2 then
raise Exception.Create('Need 2 characters for Script closing')
else
FScriptClose:=Value;
end;
procedure TRtcScriptEngine.SetScriptOpen(const Value: string);
begin
if length(Value)<>2 then
raise Exception.Create('Need 2 characters for Script opening')
else
FScriptOpen:=Value;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit Vcl.XPStyleActnCtrls;
interface
uses Vcl.ActnMan, Vcl.ActnMenus, Vcl.ActnCtrls;
type
{$IF NOT DEFINED(CLR)}
{$HPPEMIT ''}
{$HPPEMIT '/* automatically link to xpstyleactnctrls.obj so that the property editors are registered */'}
{$HPPEMIT '#pragma link "Vcl.xpstyleactnctrls.obj"'}
{$HPPEMIT ''}
{$IFEND}
{ TXPStyleActionBars }
TXPStyleActionBars = class(TActionBarStyleEx)
public
function GetColorMapClass(ActionBar: TCustomActionBar): TCustomColorMapClass; override;
function GetControlClass(ActionBar: TCustomActionBar;
AnItem: TActionClientItem): TCustomActionControlClass; override;
function GetPopupClass(ActionBar: TCustomActionBar): TCustomPopupClass; override;
function GetAddRemoveItemClass(ActionBar: TCustomActionBar): TCustomAddRemoveItemClass; override;
function GetStyleName: string; override;
function GetScrollBtnClass: TCustomToolScrollBtnClass; override;
end;
var
XPStyle: TXPStyleActionBars;
implementation
uses
Vcl.ListActns, Vcl.ActnColorMaps, Vcl.XPActnCtrls, Vcl.Themes,
Vcl.PlatformDefaultStyleActnCtrls;
{ TXPStyleActionBars }
function TXPStyleActionBars.GetAddRemoveItemClass(
ActionBar: TCustomActionBar): TCustomAddRemoveItemClass;
begin
if TStyleManager.IsCustomStyleActive then
Result := PlatformDefaultStyle.GetAddRemoveItemClass(ActionBar)
else
Result := TXPStyleAddRemoveItem;
end;
function TXPStyleActionBars.GetColorMapClass(
ActionBar: TCustomActionBar): TCustomColorMapClass;
begin
if TStyleManager.IsCustomStyleActive then
Result := PlatformDefaultStyle.GetColorMapClass(ActionBar)
else
Result := TXPColorMap;
end;
function TXPStyleActionBars.GetControlClass(ActionBar: TCustomActionBar;
AnItem: TActionClientItem): TCustomActionControlClass;
begin
if TStyleManager.IsCustomStyleActive then
Result := PlatformDefaultStyle.GetControlClass(ActionBar, AnItem)
else
begin
if ActionBar is TCustomActionToolBar then
begin
if AnItem.HasItems then
Result := TXPStyleDropDownBtn
else
if (AnItem.Action is TStaticListAction) or
(AnItem.Action is TVirtualListAction) then
Result := TCustomComboControl
else
Result := TXPStyleButton;
end
else if ActionBar is TCustomActionMainMenuBar then
Result := TXPStyleMenuButton
else if ActionBar is TCustomizeActionToolBar then
begin
with TCustomizeActionToolbar(ActionBar) do
if not Assigned(RootMenu) or
(AnItem.ParentItem <> TCustomizeActionToolBar(RootMenu).AdditionalItem) then
Result := TXPStyleMenuItem
else
Result := TXPStyleAddRemoveItem;
end
else if ActionBar is TCustomActionPopupMenu then
Result := TXPStyleMenuItem
else
Result := TXPStyleButton;
end;
end;
function TXPStyleActionBars.GetPopupClass(
ActionBar: TCustomActionBar): TCustomPopupClass;
begin
if TStyleManager.IsCustomStyleActive then
Result := PlatformDefaultStyle.GetPopupClass(ActionBar)
else if ActionBar is TCustomActionToolBar then
Result := TXPStyleCustomizePopup
else
Result := TXPStylePopupMenu;
end;
function TXPStyleActionBars.GetScrollBtnClass: TCustomToolScrollBtnClass;
begin
if TStyleManager.IsCustomStyleActive then
Result := PlatformDefaultStyle.GetScrollBtnClass
else
Result := TXPStyleToolScrollBtn;
end;
function TXPStyleActionBars.GetStyleName: string;
begin
Result := 'XP Style'; { Do not localize }
end;
initialization
XPStyle := TXPStyleActionBars.Create;
RegisterActnBarStyle(XPStyle);
finalization
UnregisterActnBarStyle(XPStyle);
XPStyle.Free;
end.
|
{*******************************************************}
{ }
{ DelphiWebMVC }
{ }
{ 版权所有 (C) 2019 苏兴迎(PRSoft) }
{ }
{*******************************************************}
unit RedisM;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, Winapi.ActiveX,
IdComponent, IdTCPConnection, IdTCPClient, IdGlobal, System.Win.ScktComp;
var
Redis_IP: string;
Redis_Port: Integer;
Redis_PassWord: string;
Redis_InitSize: integer;
Redis_TimerOut: integer;
type
TRedisM = class
private
TcpClient: TIdTCPClient;
isConn: Boolean;
public
procedure setKey(key: string; value: string; timerout: Integer = 0);
procedure delKey(key: string);
function getKey(key: string): string;
function tryconn(): Boolean;
procedure freetcp;
procedure setExpire(key: string; timerout: Integer);
constructor Create();
destructor Destroy; override;
end;
implementation
uses
LogUnit;
{ TRedis }
constructor TRedisM.Create();
begin
TcpClient := nil;
tryconn();
end;
procedure TRedisM.delKey(key: string);
begin
if not isConn then
if not tryconn then
exit;
with TcpClient do
begin
Socket.WriteLn('Del ' + key, IndyTextEncoding(IdTextEncodingType.encUTF8));
Socket.ReadLn(IndyTextEncoding(IdTextEncodingType.encUTF8));
end;
end;
destructor TRedisM.Destroy;
begin
freetcp;
inherited;
end;
procedure TRedisM.freetcp;
begin
try
TcpClient.Disconnect;
finally
TcpClient.Free;
end;
end;
function TRedisM.getKey(key: string): string;
var
s: string;
begin
Result := '';
if not isConn then
if not tryconn then
exit;
try
with TcpClient do
begin
Socket.WriteLn('get ' + key, IndyTextEncoding(IdTextEncodingType.encUTF8));
s := Socket.ReadLn(IndyTextEncoding(IdTextEncodingType.encUTF8));
Result := Socket.ReadLn(IndyTextEncoding(IdTextEncodingType.encUTF8));
end;
except
on e: Exception do
begin
log(e.Message);
end;
end;
end;
function TRedisM.tryconn: Boolean;
var
s: string;
begin
if TcpClient = nil then
tcpclient := TIdTCPClient.Create(nil);
try
try
tcpclient.Host := Redis_IP;
tcpclient.Port := Redis_Port;
TcpClient.ReadTimeout := 30000;
tcpclient.Connect;
TcpClient.Socket.RecvBufferSize := 100 * 1024;
TcpClient.Socket.SendBufferSize := 100 * 1024;
with tcpclient do
begin
if Connected then
begin
if Redis_PassWord <> '' then
begin
Socket.WriteLn('AUTH ' + Redis_PassWord, IndyTextEncoding(IdTextEncodingType.encUTF8));
s := Socket.ReadLn(IndyTextEncoding(IdTextEncodingType.encUTF8));
if s = '+OK' then
begin
isConn := true;
end
else
begin
isConn := true;
log('Redis服务登录失败请检测登录密码');
end;
end
else
begin
isConn := true;
end;
end
else
begin
isConn := false;
log('Redis服务连接失败');
end;
end;
except
on e: Exception do
begin
isConn := false;
log(e.Message);
end;
end;
finally
result := isConn;
end;
end;
procedure TRedisM.setExpire(key: string; timerout: Integer);
var
s: string;
begin
if not isConn then
if not tryconn then
exit;
try
with tcpclient do
begin
Socket.WriteLn('expire ' + key + ' ' + inttostr(timerout), IndyTextEncoding(IdTextEncodingType.encUTF8));
s := Socket.ReadLn(IndyTextEncoding(IdTextEncodingType.encUTF8));
end;
except
on e: Exception do
begin
log(e.Message);
end;
end;
end;
procedure TRedisM.setKey(key, value: string; timerout: Integer = 0);
var
s: string;
begin
if not isConn then
if not tryconn then
exit;
try
tcpclient.Socket.WriteLn('set ' + key + ' ' + value, IndyTextEncoding(IdTextEncodingType.encUTF8));
s := tcpclient.Socket.ReadLn(IndyTextEncoding(IdTextEncodingType.encUTF8));
if timerout > 0 then
setExpire(key, timerout * 60)
else
setExpire(key, Redis_TimerOut * 60)
except
on e: Exception do
begin
log(e.Message);
end;
end;
end;
end.
|
{$O+,F+}
{$DEFINE TRIMVALUESPACES}
{if defined, values will have leading and trailing
spaces trimmed before passed to the user}
unit inifiles;
{
As the name implies, a simple unit to read and write .ini files, which
are extremely simple flat-file databases used to store prorgam configuration
details.
.ini files have SECTIONS. Sections can be empty, but typically contain
one or more KEYS with VALUES. COMMENTS start with a ; or a /. Sections
are separated by one or more BLANK LINES. Values are contained on a SINGLE
LINE.
This unit was thrown together in a hurry to support a very specific
implementation, so it has the following limitations:
- File name/path limited to 80 characters
- SECTION and KEYs are limited to 32 characters
- VALUEs are limited to 255 characters
A typical .ini file looks like this:
///
/// Typical .INI file used for testing.
/// This is one style of comment.
///
[section]
;this is another style of comment
key1=value
key2=A string with spaces in it!
make=Ford
model=Mustang
[Monitors]
colors=16
resolution=640x200
}
interface
uses
objects;
type
sectionType=string[32];
keyType=string[32];
filemodetype=(newfile,appendfile,readfile);
PINIResultType=^TINIResultType;
TINIResultType=record
Section:sectionType;
Key:keyType;
Value:string;
end;
pINIfile=^tINIfile;
tINIfile=object(TObject)
readbufsize:word;
constructor init(filename:string;filemode:filemodetype;bufsize:word);
destructor done; virtual;
Procedure StartNewSection(section:sectiontype;comment:string);
Procedure WriteComment(comment:string);
Procedure WriteKeyValue(key:keytype;value:string);
{GetNextItem returns the section, key, and value from a successful read.
If there are no more items per section, key will be blank.
If there are no more sections in the file, section will be blank.}
Function ReadNextItem:PINIResultType;
{Resets a file in readfile mode so that you can begin reading again}
Procedure ReadReset;
{TRUE if a new section is found. This pauses advancement until
ACKSection is called. The idea is that there are multiple sections
in a file and the user might want to do something before processing
a new section.}
Function NewSection:boolean;
{Acknowledges new section and reading can continue}
Procedure ACKSection;
private
f:text;
fmode:filemodetype;
temps:string;
{readBuf:array[0..readbufsize-1] of Char;}
readBuf:pointer;
readpaused:boolean;
lastResult:TINIResultType;
end;
implementation
uses
support;
const
separator='=';
comstart=';';
nl=#13#10;
Constructor tINIfile.init;
begin
Inherited Init;
if filemode=appendfile
then if not fileexists(filename)
then filemode:=newfile;
if filemode<>newfile
then if not fileexists(filename)
then fail;
fmode:=filemode;
assign(f,filename);
readbufsize:=bufsize;
if readbufsize>=maxavail
then repeat
readbufsize:=readbufsize div 2;
until readbufsize<maxavail;
getmem(readbuf,readbufsize);
SetTextBuf(f,readBuf^,readbufsize);
{SetTextBuf(f,readBuf);}
case fmode of
newfile:rewrite(f);
appendfile:append(f);
readfile:reset(f); {crashes here if filename ends in "+" ????}
end;
lastResult.Section:='';
lastResult.Key:='';
lastResult.Value:='';
readpaused:=false;
end;
Destructor tINIfile.done;
begin
if fmode in [newfile,appendfile]
then writeln(f); {put blank line at end of file}
close(f);
freemem(readbuf,readbufsize);
Inherited Done;
end;
Procedure tINIfile.StartNewSection(section:sectiontype;comment:string);
begin
writeln(f); {blank line}
if comment<>'' then writeln(f,comstart+comment);
writeln(f,'['+section+']');
end;
Procedure tINIfile.WriteComment(comment:string);
begin
writeln(f,comstart+comment);
end;
Procedure tINIfile.WriteKeyValue(key:keytype;value:string);
begin
writeln(f,key+separator+value);
end;
Function TINIFile.ReadNextItem:PINIResultType;
{GetNextItem returns the section, key, and value from a successful read.
If there are no more items per section, key and value will be blank.
If there are no more sections in the file, return NIL.}
var
_seploc:byte;
begin
{are we paused because we hit the end of a section and the user hasn't
acknowledged it yet?}
if readpaused then begin
ReadNextItem:=@lastResult;
exit;
end;
{are we at the end of the file already? bail}
if eof(f) then begin
ReadNextItem:=NIL;
exit;
end;
repeat
{$i-}
readln(f,temps);
{$i+}
until eof(f)
{problem reading}
or (ioresult <> 0)
{has section header in it}
or ((temps<>'') and (temps[1] in ['[','0'..'9','A'..'Z','a'..'z']))
{has key/value in it}
or ((temps[1]<>'[') and (pos(separator,temps) <> 0))
;
if (ioresult <> 0) then begin
{Problem reading file. Return NIL.}
ReadNextItem:=NIL;
exit;
end;
{new section header?}
if temps[1] = '[' then begin
lastResult.Section:=Copy(temps,2,pos(']',temps)-2);
lastResult.Key:='';
lastResult.Value:='';
readpaused:=true;
end else begin
{if there is a separator '=' in the line, it's a valid key/value pair}
_seploc:=pos(separator,temps);
if _seploc <> 0 then begin
lastResult.Key:=Copy(temps,1,_seploc-1);
lastResult.Value:=Copy(temps,_seploc+1,length(temps));
{$IFDEF TRIMVALUESPACES}
with lastResult do begin
{trim leading spaces}
if length(Value)>1 then begin
while (Value<>'') and (Value[1]=#32)
do delete(Value,1,1);
{trim trailing spaces}
while (Value<>'') and (Value[length(Value)]=#32)
do delete(Value,length(Value),1);
end;
end;
{$ENDIF}
end;
end;
ReadNextItem:=@lastResult;
end;
Procedure TINIFile.ReadReset;
begin
if fmode=readfile then begin
reset(f);
readpaused:=false;
end;
end;
Function TINIFile.NewSection:boolean;
begin
NewSection:=readpaused;
end;
Procedure TINIFile.ACKSection;
begin
readpaused:=false;
end;
end.
|
unit DBLookupComboBoxHelper;
interface
uses
DSWrap, cxDBLookupComboBox, Data.DB, cxDropDownEdit, cxDBLabel,
cxDBExtLookupComboBox, cxGridCustomTableView, cxGridDBBandedTableView;
type
TDBLCB = class(TObject)
private
public
class procedure Init(AcxDBLookupComboBox: TcxDBLookupComboBox;
ADataSource: TDataSource; const ADataField: string;
AListSource: TDataSource; const AListFieldWrap: TFieldWrap;
ADropDownListStyle: TcxEditDropDownListStyle = lsEditFixedList); static;
class procedure InitProp(AcxLookupComboBoxProperties:
TcxLookupComboBoxProperties; ADataSource: TDataSource; const
AKeyFieldNames, AListFieldNames: String; ADropDownStyle:
TcxEditDropDownListStyle); static;
end;
TDBL = class(TObject)
public
class procedure Init(AcxDBLabel: TcxDBLabel; ADataSource: TDataSource;
const ADataField: TFieldWrap); static;
end;
TExtDBLCB = class(TObject)
public
class procedure InitProp(AcxExtLookupComboBoxProperties:
TcxExtLookupComboBoxProperties; AView: TcxGridDBBandedTableView; const
AKeyFieldNames, AListFieldNames: String; ADropDownStyle:
TcxEditDropDownListStyle; ADropDownAutoSize, ADropDownSizeable: Boolean);
static;
end;
implementation
uses
System.SysUtils;
class procedure TDBLCB.Init(AcxDBLookupComboBox: TcxDBLookupComboBox;
ADataSource: TDataSource; const ADataField: string; AListSource: TDataSource;
const AListFieldWrap: TFieldWrap;
ADropDownListStyle: TcxEditDropDownListStyle = lsEditFixedList);
begin
Assert(AcxDBLookupComboBox <> nil);
Assert(ADataSource <> nil);
Assert(not ADataField.IsEmpty);
Assert(AListSource <> nil);
AcxDBLookupComboBox.DataBinding.DataSource := ADataSource;
AcxDBLookupComboBox.DataBinding.DataField := ADataField;
InitProp(AcxDBLookupComboBox.Properties, AListSource,
AListFieldWrap.DataSetWrap.PKFieldName,
AListFieldWrap.FieldName, ADropDownListStyle);
end;
class procedure TDBLCB.InitProp(AcxLookupComboBoxProperties:
TcxLookupComboBoxProperties; ADataSource: TDataSource; const
AKeyFieldNames, AListFieldNames: String; ADropDownStyle:
TcxEditDropDownListStyle);
begin
Assert(AcxLookupComboBoxProperties <> nil);
Assert(ADataSource <> nil);
Assert(not AKeyFieldNames.IsEmpty);
Assert(not AListFieldNames.IsEmpty);
with AcxLookupComboBoxProperties do
begin
ListSource := ADataSource;
KeyFieldNames := AKeyFieldNames;
ListFieldNames := AListFieldNames;
DropDownListStyle := ADropDownStyle;
end;
end;
class procedure TDBL.Init(AcxDBLabel: TcxDBLabel; ADataSource: TDataSource;
const ADataField: TFieldWrap);
begin
Assert(AcxDBLabel <> nil);
Assert(ADataSource <> nil);
Assert(ADataField <> nil);
with AcxDBLabel.DataBinding do
begin
DataSource := ADataSource;
DataField := ADataField.FieldName;
end;
end;
class procedure TExtDBLCB.InitProp(AcxExtLookupComboBoxProperties:
TcxExtLookupComboBoxProperties; AView: TcxGridDBBandedTableView; const
AKeyFieldNames, AListFieldNames: String; ADropDownStyle:
TcxEditDropDownListStyle; ADropDownAutoSize, ADropDownSizeable: Boolean);
var
AColumn: TcxGridDBBandedColumn;
begin
Assert(AcxExtLookupComboBoxProperties <> nil);
Assert(AView <> nil);
Assert(not AKeyFieldNames.IsEmpty);
Assert(not AListFieldNames.IsEmpty);
AColumn := AView.GetColumnByFieldName(AListFieldNames);
Assert(AColumn <> nil);
with AcxExtLookupComboBoxProperties do
begin
View := AView;
KeyFieldNames := AKeyFieldNames;
ListFieldItem := AColumn;
// ListFieldNames := AListFieldNames;
DropDownListStyle := ADropDownStyle;
DropDownAutoSize := ADropDownAutoSize;
DropDownSizeable := ADropDownSizeable;
end;
end;
end.
|
unit Exemption_Remove;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, DBCtrls, DBTables, DB, Buttons, Grids,
Wwdbigrd, Wwdbgrid, ExtCtrls, Wwtable, Wwdatsrc, Menus, RPCanvas,
RPrinter, RPDefine, RPBase, RPFiler, locatdir, ComCtrls;
type
TfmRemoveNonRenewedExemptions = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
lb_Title: TLabel;
ReportFiler: TReportFiler;
dlg_Print: TPrintDialog;
ReportPrinter: TReportPrinter;
tbExemptions: TTable;
tbExemptionCodes: TTable;
Panel3: TPanel;
btn_Start: TBitBtn;
btn_Close: TBitBtn;
pgctl_Main: TPageControl;
tbs_Options: TTabSheet;
cbx_TrialRun: TCheckBox;
rg_AssessmentYear: TRadioGroup;
tbs_ExemptionCodes: TTabSheet;
Panel4: TPanel;
Label1: TLabel;
lbx_ExemptionCodes: TListBox;
tbExemptionsLookup: TTable;
tbRemovedExemptions: TTable;
tbAuditEXChange: TTable;
tbAudit: TTable;
tbAssessment: TTable;
tbClass: TTable;
tbSwisCodes: TTable;
tbParcel: TTable;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btn_StartClick(Sender: TObject);
procedure ReportPrintHeader(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
AssessmentYear, UnitName : String;
ProcessingType : Integer;
TrialRun, ReportCancelled : Boolean;
SelectedExemptionCodes : TStringList;
Procedure InitializeForm; {Open the tables and setup.}
Procedure FillListBoxes(ProcessingType : Integer;
AssessmentYear : String);
end;
implementation
uses GlblVars, WinUtils, Utilitys, GlblCnst, PASUtils, Prog, Preview,
Types, PASTypes, UtilEXSD, DataAccessUnit;
{$R *.DFM}
{========================================================}
Procedure TfmRemoveNonRenewedExemptions.FormActivate(Sender: TObject);
begin
SetFormStateMaximized(Self);
end;
{========================================================}
Procedure TfmRemoveNonRenewedExemptions.FillListBoxes(ProcessingType : Integer;
AssessmentYear : String);
var
Quit : Boolean;
begin
OpenTableForProcessingType(tbExemptionCodes, ExemptionCodesTableName,
ProcessingType, Quit);
FillOneListBox(lbx_ExemptionCodes, tbExemptionCodes,
'EXCode', 'Description', 10,
True, True, ProcessingType, AssessmentYear);
end; {FillListBoxes}
{========================================================}
Procedure TfmRemoveNonRenewedExemptions.InitializeForm;
begin
UnitName := 'Exemption_Remove';
{Default assessment year.}
case GlblProcessingType of
NextYear : begin
rg_AssessmentYear.ItemIndex := 1;
ProcessingType := NextYear;
AssessmentYear := GlblNextYear;
end; {NextYear}
ThisYear : begin
rg_AssessmentYear.ItemIndex := 0;
ProcessingType := ThisYear;
AssessmentYear := GlblThisYear;
end; {This Year}
end; {case GlblProcessingType of}
FillListBoxes(ProcessingType, AssessmentYear);
end; {InitializeForm}
{===================================================================}
Procedure TfmRemoveNonRenewedExemptions.ReportPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
{Print the date and page number.}
SectionTop := 0.25;
SectionLeft := 0.5;
SectionRight := PageWidth - 0.5;
SetFont('Times New Roman',8);
PrintHeader('Page: ' + IntToStr(CurrentPage), pjRight);
PrintHeader('Date: ' + DateToStr(Date) + ' Time: ' + TimeToStr(Now), pjLeft);
SectionTop := 0.5;
SetFont('Arial',12);
Bold := True;
Home;
PrintCenter('Remove Non-Renewed Exemptions', (PageWidth / 2));
SetFont('Times New Roman', 9);
CRLF;
Println('');
Print(' Assessment Year: ');
case ProcessingType of
ThisYear : Println(' This Year');
NextYear : Println(' Next Year');
end;
If TrialRun
then Println('Trial run.');
Println('');
Bold := True;
ClearTabs;
SetTab(0.3, pjCenter, 1.3, 0, BOXLINENone, 0); {Parcel ID}
SetTab(1.7, pjCenter, 0.6, 0, BOXLINENone, 0); {EX Code}
SetTab(2.4, pjCenter, 0.8, 0, BOXLINENone, 0); {Initial date}
SetTab(3.3, pjCenter, 1.0, 0, BOXLINENone, 0); {County amount}
SetTab(4.4, pjCenter, 1.0, 0, BOXLINENone, 0); {Municipal amount}
SetTab(5.5, pjCenter, 1.0, 0, BOXLINENone, 0); {School amount}
Print(#9 + #9 +
#9 + 'Initial');
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + 'County')
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + GetMunicipalityTypeName(GlblMunicipalityType))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + 'School')
else Println(#9);
ClearTabs;
SetTab(0.3, pjCenter, 1.3, 0, BOXLINEBottom, 0); {Parcel ID}
SetTab(1.7, pjCenter, 0.6, 0, BOXLINEBottom, 0); {EX Code}
SetTab(2.4, pjCenter, 0.8, 0, BOXLINEBottom, 0); {Initial date}
SetTab(3.3, pjCenter, 1.0, 0, BOXLINEBottom, 0); {County amount}
SetTab(4.4, pjCenter, 1.0, 0, BOXLINEBottom, 0); {Municipal amount}
SetTab(5.5, pjCenter, 1.0, 0, BOXLINEBottom, 0); {School amount}
Print(#9 + 'Parcel ID' +
#9 + 'EX Code' +
#9 + 'Date');
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + 'Amount')
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + 'Amount')
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + 'Amount')
else Println(#9);
ClearTabs;
SetTab(0.3, pjLeft, 1.3, 0, BOXLINENone, 0); {Parcel ID}
SetTab(1.7, pjLeft, 0.6, 0, BOXLINENone, 0); {EX Code}
SetTab(2.4, pjLeft, 0.8, 0, BOXLINENone, 0); {Initial date}
SetTab(3.3, pjRight, 1.0, 0, BOXLINENone, 0); {County amount}
SetTab(4.4, pjRight, 1.0, 0, BOXLINENone, 0); {Municipal amount}
SetTab(5.5, pjRight, 1.0, 0, BOXLINENone, 0); {School amount}
Bold := False;
end; {with Sender as TBaseReport do}
end; {ReportPrintHeader}
{===================================================================}
Procedure TfmRemoveNonRenewedExemptions.ReportPrint(Sender: TObject);
var
ExemptionCode, SwisSBLKey : String;
NumberRemoved : LongInt;
begin
NumberRemoved := 0;
tbExemptions.First;
with Sender as TBaseReport, tbExemptions do
begin
while (not (EOF or ReportCancelled)) do
begin
ExemptionCode := FieldByName('ExemptionCode').AsString;
SwisSBLKey := FieldByName('SwisSBLKey').AsString;
ProgressDialog.Update(Self, ConvertSwisSBLToDashDot(SwisSBLKey));
ProgressDialog.UserLabelCaption := 'Number Removed = ' + IntToStr(NumberRemoved);
Application.ProcessMessages;
If ((SelectedExemptionCodes.IndexOf(ExemptionCode) <> -1) and
(not FieldByName('ExemptionApproved').AsBoolean) and
(not FieldByName('PreventRenewal').AsBoolean))
then
begin
If _Compare(LinesLeft, 5, coLessThan)
then NewPage;
Inc(NumberRemoved);
Print(#9 + ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').Text) +
#9 + ExemptionCode +
#9 + FieldByName('InitialDate').AsString);
If (rtdCounty in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(CurrencyDisplayNoDollarSign, FieldByName('CountyAmount').AsInteger))
else Print(#9);
If (rtdMunicipal in GlblRollTotalsToShow)
then Print(#9 + FormatFloat(CurrencyDisplayNoDollarSign, FieldByName('TownAmount').AsInteger))
else Print(#9);
If (rtdSchool in GlblRollTotalsToShow)
then Println(#9 + FormatFloat(CurrencyDisplayNoDollarSign, FieldByName('SchoolAmount').AsInteger))
else Println(#9);
If not TrialRun
then
try
_Locate(tbParcel, [AssessmentYear, SwisSBLKey], '', [loParseSwisSBLKey]);
DeleteAnExemption(tbExemptions, tbExemptionsLookup,
tbRemovedExemptions, tbAuditEXChange,
tbAudit, tbAssessment,
tbClass, tbSwisCodes,
tbParcel, tbExemptionCodes,
AssessmentYear, SwisSBLKey, nil);
Prior;
except
SystemSupport(80, tbExemptions, 'Error deleting exemption.',
UnitName, GlblErrorDlgBox);
end;
end; {If ((not Done) and ...}
ReportCancelled := ProgressDialog.Cancelled;
Next;
end; {while not EOF do}
ClearTabs;
Println('');
Println(#9 + 'Number removed = ' + IntToStr(NumberRemoved));
end; {with Sender as TBaseReport, tbExemptions do}
end; {ReportPrint}
{===================================================================}
Procedure TfmRemoveNonRenewedExemptions.btn_StartClick(Sender: TObject);
var
Quit : Boolean;
NewFileName : String;
TempFile : File;
begin
Quit := False;
ReportCancelled := False;
TrialRun := cbx_TrialRun.Checked;
ProcessingType := NextYear;
SelectedExemptionCodes := TStringList.Create;
FillSelectedItemList(lbx_ExemptionCodes, SelectedExemptionCodes, 5);
case rg_AssessmentYear.ItemIndex of
0 : ProcessingType := ThisYear;
1 : ProcessingType := NextYear;
end;
OpenTablesForForm(Self, ProcessingType);
btn_Start.Enabled := False;
Application.ProcessMessages;
Quit := False;
SetPrintToScreenDefault(dlg_Print);
If dlg_Print.Execute
then
begin
(* OpenTablesForForm( *)
AssignPrinterSettings(dlg_Print, ReportPrinter, ReportFiler,
[ptLaser], False, Quit);
ProgressDialog.Start(GetRecordCount(tbExemptions), True, True);
{Now print the report.}
If not (Quit or ReportCancelled)
then
begin
If dlg_Print.PrintToFile
then
begin
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
ReportFiler.Execute;
{FXX10111999-3: Make sure they know its done.}
ProgressDialog.StartPrinting(dlg_Print.PrintToFile);
PreviewForm.ShowModal;
finally
PreviewForm.Free;
{Now delete the file.}
try
AssignFile(TempFile, NewFileName);
OldDeleteFile(NewFileName);
finally
{We don't care if it does not get deleted, so we won't put up an
error message.}
ChDir(GlblProgramDir);
end;
end; {try PreviewForm := ...}
end {If PrintDialog.PrintToFile}
else ReportPrinter.Execute;
ResetPrinter(ReportPrinter);
end; {If not Quit}
ProgressDialog.Finish;
{FXX10111999-3: Tell people that printing is starting and
done.}
DisplayPrintingFinishedMessage(dlg_Print.PrintToFile);
end; {If PrintDialog.Execute}
SelectedExemptionCodes.Free;
btn_Start.Enabled := True;
end; {StartButtonClick}
{===================================================================}
Procedure TfmRemoveNonRenewedExemptions.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
CloseTablesForForm(Self);
{Free up the child window and set the ClosingAForm Boolean to
true so that we know to delete the tab.}
Action := caFree;
GlblClosingAForm := True;
GlblClosingFormCaption := Caption;
end; {FormClose}
end. |
unit UFireworks;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics,
Dialogs, ExtCtrls, StdCtrls, BGRABitmap, BGRABitmapTypes, math;
type
//=============================================================
{ TParticle }
TParticle = class
pos : TPointF;
acc : TPointF;
vel : TPointF;
isFirework : Boolean;
lifespan : integer;
dec_lifespan: integer;
hu : integer;
public
constructor Create(x,y: single; v_hu: integer; v_isFirework: boolean);
procedure applyForce(force: TPointF);
procedure update;
function done: Boolean;
procedure Show(canvas: TBGRABitmap);
end;
{ TFirework }
TFirework = class
Owner: TObject;
hu: integer;
firework: TParticle;
exploded: Boolean;
particles: array of TParticle;
public
constructor Create(sender: TObject; width, height: integer);
function done: Boolean;
procedure Update;
procedure Explode;
procedure Show(canvas: TBGRABitmap);
end;
{ TFireworks }
TFireworks = class
gravity : TPointF;
fireworks : array of TFirework;
width : integer;
height : integer;
public
constructor Create(v_width, v_height: integer);
procedure Draw(canvas: TBGRABitmap);
end;
implementation
{ TFireworks }
constructor TFireworks.Create(v_width, v_height: integer);
begin
gravity.x:= 0;
gravity.y:= 0.2;
width:= v_width;
height:= v_height;
end;
procedure TFireworks.Draw(canvas: TBGRABitmap);
var i: integer;
begin
if random(100) < 3 then
begin
SetLength(fireworks, Length(fireworks)+1);
fireworks[Length(fireworks)-1]:= TFirework.Create(self, width, height);
end;
for i:=Length(fireworks)-1 downto 0 do
begin
fireworks[i].Update;
fireworks[i].Show(canvas);
if fireworks[i].done then
begin
fireworks[i].Free;
if i < Length(fireworks)-1 then
fireworks[i]:= fireworks[Length(fireworks)-1];
SetLength(fireworks, Length(fireworks)-1);
end;
end;
end;
{ TFirework }
constructor TFirework.Create(sender: TObject; width, height: integer);
begin
Owner:= sender;
hu:= random(65535);
firework:= TParticle.Create(random(width), height, hu, true);
exploded:= false;
SetLength(particles, 0);
end;
function TFirework.done: Boolean;
begin
if (exploded) and (Length(particles) = 0) then
Result:= true
else
Result:= false;
end;
procedure TFirework.Update;
var i: integer;
begin
if not exploded then
begin
firework.applyForce( TFireworks(Owner).gravity );
firework.update();
if firework.vel.y >= 0 then
begin
exploded:= true;
Explode();
end;
end;
for i:= Length(particles)-1 downto 0 do
begin
particles[i].applyForce( TFireworks(Owner).gravity );
particles[i].update();
if particles[i].done() then
begin
particles[i].Free;
if i < Length(particles)-1 then
particles[i]:= particles[Length(particles)-1];
SetLength(particles, Length(particles)-1);
end;
end;
end;
procedure TFirework.Explode;
var i: integer;
max_p: integer;
begin
max_p:= RandomRange(100, 300);
SetLength(particles, max_p);
for i:=0 to max_p-1 do
begin
particles[i]:= TParticle.Create(firework.pos.x, firework.pos.y, hu, false);
end;
end;
procedure TFirework.Show(canvas: TBGRABitmap);
var i: integer;
begin
if not exploded then
firework.Show(canvas);
for i:=0 to Length(particles)-1 do
particles[i].Show(canvas);
end;
{ TParticle }
constructor TParticle.Create(x, y: single; v_hu: integer; v_isFirework: boolean);
var range: integer;
begin
pos.x:= x;
pos.y:= y;
hu:= v_hu;
isFirework:= v_isFirework;
lifespan:= 255; // Opacity - wygaszanie widoczności
dec_lifespan:= RandomRange(2,5); // org 4 - co ile ma wygaszać
acc.SetLocation(0,0);
if isFirework then
begin
vel.x:= RandomRange(-3,3); // kierunek wystrzałów
vel.y:= RandomRange(-18, -8); // siła strzału
end
else
begin
range:= RandomRange(4, 20);
vel.x:= RandomRange(-100, 100)/ 100;
vel.y:= RandomRange(-100, 100)/ 100;
vel:= vel.Scale(range);
end;
end;
procedure TParticle.applyForce(force: TPointF);
begin
acc:= acc.Add(force);
end;
procedure TParticle.update;
begin
if not isFirework then
begin
vel:= vel.Scale(0.93); // rozproszenie
lifespan -= dec_lifespan;
end;
vel:= vel.Add(acc);
pos:= pos.Add(vel);
acc:= acc.Scale(0);
end;
function TParticle.done: Boolean;
begin
if lifespan < 0 then
Result:= true
else
Result:= false;
end;
procedure TParticle.Show(canvas: TBGRABitmap);
var posR: TPoint;
s: integer;
begin
canvas.CanvasBGRA.Brush.Style:= bsSolid;
canvas.CanvasBGRA.Pen.Style:= psClear;
posR:= pos.Round;
s:= RandomRange(1,4);
if not isFirework then
begin // rozbłyski
canvas.CanvasBGRA.Brush.BGRAColor.FromHSLAPixel(HSLA(hu, 65535, random(65535))); //65535, 32768));
canvas.CanvasBGRA.Brush.Opacity:= lifespan;
canvas.CanvasBGRA.Pen.Style:= psSolid;
canvas.CanvasBGRA.Pen.Width:= 1;
canvas.CanvasBGRA.Pen.BGRAColor.FromHSLAPixel(HSLA(hu, 65535, random(65535)));
canvas.CanvasBGRA.Pen.Opacity:= lifespan;
canvas.CanvasBGRA.MoveTo(posR.x-s-1, posR.y-s-1);
canvas.CanvasBGRA.LineTo(posR.x+s, posR.y+s);
canvas.CanvasBGRA.MoveTo(posR.x+s-1, posR.y-s-1);
canvas.CanvasBGRA.LineTo(posR.x-s-2, posR.y+s);
canvas.CanvasBGRA.Pen.Style:= psClear;
canvas.CanvasBGRA.EllipseC(posR.x, posR.y, s, s);
end
else
begin // rakieta
canvas.CanvasBGRA.Brush.BGRAColor.FromHSLAPixel(HSLA(hu, 65535, 32768));
canvas.CanvasBGRA.Brush.Opacity:= lifespan;
canvas.CanvasBGRA.EllipseC(posR.x, posR.y, 3, 3);
// dodatkowy cien po rakiecie
for s:=1 to 5 do
begin
canvas.CanvasBGRA.Brush.Opacity:= 200 div s;
posR:= posR.Subtract(vel.Round);
canvas.CanvasBGRA.EllipseC(posR.x, posR.y, 3, 3);
end;
end;
end;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
hrc: HGLRC;
Pixel : Array [0..2] of GLByte;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Рисование картинки}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glViewPort (0, 0, ClientWidth, ClientHeight); // область вывода
glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
glColor3f (1.0, 0.5, 0.5); // текущий цвет примитивов
{--- левый треугольник ---}
glBegin (GL_TRIANGLES);
glVertex2f (-1, 0);
glVertex2f (-1, 1);
glVertex2f (-0.1, 0);
glEnd;
{--- правый треугольник ---}
glBegin (GL_TRIANGLES);
glVertex2f (0.1, 0);
glVertex2f (1, 0);
glVertex2f (1, -1);
glEnd;
SwapBuffers(Canvas.Handle); // содержимое буфера - на экран
glClearColor (0.0, 0.0, 0.0, 0.0); // цвет фона
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
{--- левый треугольник красим красным ---}
glColor3f (1.0, 0.0, 0.0); // текущий цвет примитивов
glBegin (GL_TRIANGLES);
glVertex2f (-1, 0);
glVertex2f (-1, 1);
glVertex2f (-0.1, 0);
glEnd;
{--- правый треугольник красим синим ---}
glColor3f (0.0, 0.0, 1.0); // текущий цвет примитивов
glBegin (GL_TRIANGLES);
glVertex2f (0.1, 0);
glVertex2f (1, 0);
glVertex2f (1, -1);
glEnd;
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
SetDCPixelFormat(Canvas.Handle);
hrc := wglCreateContext(Canvas.Handle);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(hrc);
end;
procedure TfrmGL.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
wglMakeCurrent(Canvas.Handle, hrc);
glReadPixels(X, ClientHeight - Y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, @Pixel);
If (Pixel [0] <> 0) and (Pixel [2] = 0)
then ShowMessage ('Выбран левый треугольник')
else
If (Pixel [0] = 0) and (Pixel [2] <> 0)
then ShowMessage ('Выбран правый треугольник')
else ShowMessage ('Ничего не выбрано');
wglMakeCurrent(0, 0);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC GUIx components }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Comp.UI;
interface
uses
System.Classes,
FireDAC.Stan.Intf, FireDAC.Stan.Error, FireDAC.Stan.Consts,
FireDAC.UI.Intf;
type
TFDGUIxComponent = class;
TFDGUIxAsyncExecuteDialog = class;
TFDGUIxErrorDialog = class;
TFDGUIxLoginDialog = class;
TFDGUIxScriptDialog = class;
TFDGUIxWaitCursor = class;
TFDGUIxComponent = class(TFDComponent)
private
FProvider: String;
FProviderSpecified: Boolean;
protected
function GetProvider: String;
procedure SetProvider(const AValue: String); virtual;
public
class function GetGUID: TGUID; virtual;
property ProviderSpecified: Boolean read FProviderSpecified;
published
property Provider: String read GetProvider write SetProvider
stored FProviderSpecified;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDGUIxAsyncExecuteDialog = class(TFDGUIxComponent, IFDGUIxAsyncExecuteDialog)
private
FAsyncDialog: IFDGUIxAsyncExecuteDialog;
FCaption: String;
FPrompt: String;
FShowDelay: Integer;
FHideDelay: Integer;
FOnShow: TNotifyEvent;
FOnHide: TNotifyEvent;
function GetAsyncDialog: IFDGUIxAsyncExecuteDialog;
procedure DoOnShow(ASender: TObject);
procedure DoOnHide(ASender: TObject);
function GetCaption: String;
procedure SetCaption(const AValue: String);
function IsCS: Boolean;
function GetShowDelay: Integer;
procedure SetShowDelay(const AValue: Integer);
function GetHideDelay: Integer;
procedure SetHideDelay(const AValue: Integer);
function GetPrompt: String;
procedure SetPrompt(const AValue: String);
function IsPS: Boolean;
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetGUID: TGUID; override;
property AsyncDialog: IFDGUIxAsyncExecuteDialog read FAsyncDialog
implements IFDGUIxAsyncExecuteDialog;
published
property Caption: String read GetCaption write SetCaption stored IsCS;
property Prompt: String read GetPrompt write SetPrompt stored IsPS;
property ShowDelay: Integer read GetShowDelay write SetShowDelay
default C_FD_DelayBeforeFWait;
property HideDelay: Integer read GetHideDelay write SetHideDelay
default C_FD_DelayBeforeFWait;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDGUIxErrorDialog = class(TFDGUIxComponent, IFDGUIxErrorDialog)
private
FErrorDialog: IFDGUIxErrorDialog;
FCaption: String;
FEnabled: Boolean;
FStayOnTop: Boolean;
FOnHide: TFDGUIxErrorDialogEvent;
FOnShow: TFDGUIxErrorDialogEvent;
function GetErrorDialog: IFDGUIxErrorDialog;
function GetCaption: String;
procedure SetCaption(const AValue: String);
function IsCS: Boolean;
procedure DoOnHide(ASender: TObject; AException: EFDDBEngineException);
procedure DoOnShow(ASender: TObject; AException: EFDDBEngineException);
function GetEnabled: Boolean;
procedure SetEnabled(const AValue: Boolean);
function GetStayOnTop: Boolean;
procedure SetStayOnTop(const AValue: Boolean);
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetGUID: TGUID; override;
procedure Execute(E: EFDDBEngineException);
property ErrorDialog: IFDGUIxErrorDialog read FErrorDialog implements IFDGUIxErrorDialog;
published
property Caption: String read GetCaption write SetCaption stored IsCS;
property Enabled: Boolean read GetEnabled write SetEnabled default True;
property StayOnTop: Boolean read GetStayOnTop write SetStayOnTop default True;
property OnShow: TFDGUIxErrorDialogEvent read FOnShow write FOnShow;
property OnHide: TFDGUIxErrorDialogEvent read FOnHide write FOnHide;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDGUIxLoginDialog = class(TFDGUIxComponent, IFDGUIxLoginDialog)
private
FLoginDialog: IFDGUIxLoginDialog;
FCaption: String;
FHistoryEnabled: Boolean;
FHistoryKey: String;
FHistoryStorage: TFDGUIxLoginHistoryStorage;
FHistoryWithPassword: Boolean;
FLoginRetries: Integer;
FVisibleItems: TStrings;
FChangeExpiredPassword: Boolean;
FConnectionDef: IFDStanConnectionDef;
FOnChangePassword: TFDGUIxLoginDialogEvent;
FOnLogin: TFDGUIxLoginDialogEvent;
FOnHide: TNotifyEvent;
FOnShow: TNotifyEvent;
function GetLoginDialog: IFDGUIxLoginDialog;
function GetCaption: String;
function GetChangeExpiredPassword: Boolean;
function GetConnectionDef: IFDStanConnectionDef;
function GetHistoryEnabled: Boolean;
function GetHistoryKey: String;
function GetHistoryStorage: TFDGUIxLoginHistoryStorage;
function GetHistoryWithPassword: Boolean;
function GetLoginRetries: Integer;
function GetVisibleItems: TStrings;
procedure SetCaption(const AValue: String);
procedure SetConnectionDef(const AConnectionDef: IFDStanConnectionDef);
procedure SetChangeExpiredPassword(const AValue: Boolean);
procedure SetHistoryEnabled(const AValue: Boolean);
procedure SetHistoryKey(const AValue: String);
procedure SetHistoryStorage(const AValue: TFDGUIxLoginHistoryStorage);
procedure SetHistoryWithPassword(const AValue: Boolean);
procedure SetLoginRetries(const AValue: Integer);
procedure SetVisibleItems(const AValue: TStrings);
procedure DoOnHide(ASender: TObject);
procedure DoOnShow(ASender: TObject);
procedure DoChangePassword(ASender: TObject; var AResult: Boolean);
procedure DoLogin(ASender: TObject; var AResult: Boolean);
procedure SetOnChangePassword(const AValue: TFDGUIxLoginDialogEvent);
procedure SetOnLogin(const AValue: TFDGUIxLoginDialogEvent);
function IsCS: Boolean;
function IsHKS: Boolean;
function IsVIS: Boolean;
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetGUID: TGUID; override;
function Execute(ALoginAction: TFDGUIxLoginAction): Boolean;
procedure GetAllLoginParams;
property ConnectionDef: IFDStanConnectionDef read GetConnectionDef write SetConnectionDef;
property LoginDialog: IFDGUIxLoginDialog read FLoginDialog implements IFDGUIxLoginDialog;
published
property Caption: String read GetCaption write SetCaption stored IsCS;
property HistoryEnabled: Boolean read GetHistoryEnabled write SetHistoryEnabled default False;
property HistoryWithPassword: Boolean read GetHistoryWithPassword write SetHistoryWithPassword default True;
property HistoryStorage: TFDGUIxLoginHistoryStorage read GetHistoryStorage write SetHistoryStorage default hsRegistry;
property HistoryKey: String read GetHistoryKey write SetHistoryKey stored IsHKS;
property VisibleItems: TStrings read GetVisibleItems write SetVisibleItems stored IsVIS;
property LoginRetries: Integer read GetLoginRetries write SetLoginRetries default 3;
property ChangeExpiredPassword: Boolean read GetChangeExpiredPassword write SetChangeExpiredPassword default True;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnLogin: TFDGUIxLoginDialogEvent read FOnLogin write SetOnLogin;
property OnChangePassword: TFDGUIxLoginDialogEvent read FOnChangePassword write SetOnChangePassword;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDGUIxScriptDialog = class(TFDGUIxComponent, IFDGUIxScriptDialog)
private
FScriptDialog: IFDGUIxScriptDialog;
FCaption: String;
FOptions: TFDGUIxScriptOptions;
FOnOutput: TFDGUIxScriptOutputEvent;
FOnInput: TFDGUIxScriptInputEvent;
FOnPause: TFDGUIxScriptPauseEvent;
FOnProgress: TFDGUIxScriptProgressEvent;
FOnShow: TNotifyEvent;
FOnHide: TNotifyEvent;
function GetScriptDialog: IFDGUIxScriptDialog;
function GetCaption: String;
function IsCS: Boolean;
procedure SetCaption(const AValue: String);
procedure DoOnHide(ASender: TObject);
procedure DoOnShow(ASender: TObject);
procedure DoOnProgress(ASender: TObject; AInfoProvider: TObject);
procedure DoOnOutput(ASender: TObject; const AStr: String);
procedure DoOnInput(ASender: TObject; const APrompt: String; var AResult: String);
procedure DoOnPause(ASender: TObject; const APrompt: String);
function GetOptions: TFDGUIxScriptOptions;
procedure SetOptions(const AValue: TFDGUIxScriptOptions);
protected
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetGUID: TGUID; override;
property ScriptDialog: IFDGUIxScriptDialog read FScriptDialog
implements IFDGUIxScriptDialog;
published
property Caption: String read GetCaption write SetCaption stored IsCS;
property Options: TFDGUIxScriptOptions read GetOptions write SetOptions
default [ssCallstack, ssConsole, ssAutoHide];
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
property OnProgress: TFDGUIxScriptProgressEvent read FOnProgress write FOnProgress;
property OnOutput: TFDGUIxScriptOutputEvent read FOnOutput write FOnOutput;
property OnInput: TFDGUIxScriptInputEvent read FOnInput write FOnInput;
property OnPause: TFDGUIxScriptPauseEvent read FOnPause write FOnPause;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDGUIxWaitCursor = class(TFDGUIxComponent, IFDGUIxWaitCursor)
private
FWaitCursor: IFDGUIxWaitCursor;
FScreenCursor: TFDGUIxScreenCursor;
FOnHide: TNotifyEvent;
FOnShow: TNotifyEvent;
function GetGUIxWaitCursor: IFDGUIxWaitCursor;
function GetScreenCursor: TFDGUIxScreenCursor;
procedure SetScreenCursor(const AValue: TFDGUIxScreenCursor);
procedure DoOnHide(ASender: TObject);
procedure DoOnShow(ASender: TObject);
protected
procedure Loaded; override;
procedure SetProvider(const AValue: String); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetGUID: TGUID; override;
property WaitCursor: IFDGUIxWaitCursor read FWaitCursor
implements IFDGUIxWaitCursor;
published
property ScreenCursor: TFDGUIxScreenCursor read GetScreenCursor write SetScreenCursor
default gcrSQLWait;
property OnShow: TNotifyEvent read FOnShow write FOnShow;
property OnHide: TNotifyEvent read FOnHide write FOnHide;
end;
implementation
uses
FireDAC.Stan.Util, FireDAC.Stan.Factory, FireDAC.Stan.ResStrs,
FireDAC.Phys.Intf;
{-------------------------------------------------------------------------------}
{ TFDGUIxComponent }
{-------------------------------------------------------------------------------}
function TFDGUIxComponent.GetProvider: String;
begin
if FProviderSpecified then
Result := FProvider
else
Result := FFDGUIxProvider;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxComponent.SetProvider(const AValue: String);
begin
FProvider := AValue;
FProviderSpecified := FProvider <> '';
end;
{-------------------------------------------------------------------------------}
class function TFDGUIxComponent.GetGUID: TGUID;
begin
FillChar(Result, SizeOf(TGUID), 0);
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxAsyncExecuteDialog }
{-------------------------------------------------------------------------------}
constructor TFDGUIxAsyncExecuteDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCaption := S_FD_AsyncDialogDefCaption;
FPrompt := S_FD_AsyncDialogDefPrompt;
FShowDelay := C_FD_DelayBeforeFWait;
FHideDelay := C_FD_DelayBeforeFWait;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxAsyncExecuteDialog.Destroy;
begin
if FAsyncDialog <> nil then begin
(FAsyncDialog as IFDStanComponentReference).SetComponentReference(nil);
FAsyncDialog.OnShow := nil;
FAsyncDialog.OnHide := nil;
FAsyncDialog := nil;
end;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TFDGUIxAsyncExecuteDialog.GetGUID: TGUID;
begin
Result := IFDGUIxAsyncExecuteDialog;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.Loaded;
var
oDlg: IFDGUIxAsyncExecuteDialog;
begin
inherited Loaded;
FDCreateInterface(IFDGUIxAsyncExecuteDialog, oDlg, False, Provider);
if oDlg <> nil then begin
oDlg := GetAsyncDialog;
oDlg.Caption := FCaption;
oDlg.Prompt := FPrompt;
oDlg.ShowDelay := FShowDelay;
oDlg.HideDelay := FHideDelay;
oDlg.OnShow := DoOnShow;
oDlg.OnHide := DoOnHide;
end;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.GetAsyncDialog: IFDGUIxAsyncExecuteDialog;
begin
if FAsyncDialog = nil then begin
FDCreateInterface(IFDGUIxAsyncExecuteDialog, FAsyncDialog, True, Provider);
(FAsyncDialog as IFDStanComponentReference).SetComponentReference(
Self as IInterfaceComponentReference);
end;
Result := FAsyncDialog;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.DoOnHide(ASender: TObject);
begin
if Assigned(FOnHide) then
FOnHide(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.DoOnShow(ASender: TObject);
begin
if Assigned(FOnShow) then
FOnShow(Self);
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.GetCaption: String;
begin
if not (csLoading in ComponentState) then
Result := GetAsyncDialog.Caption
else
Result := FCaption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.SetCaption(const AValue: String);
begin
FCaption := AValue;
if not (csLoading in ComponentState) then
GetAsyncDialog.Caption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.IsCS: Boolean;
begin
Result := Caption <> S_FD_AsyncDialogDefCaption;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.GetPrompt: String;
begin
if not (csLoading in ComponentState) then
Result := GetAsyncDialog.Prompt
else
Result := FPrompt;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.SetPrompt(const AValue: String);
begin
FPrompt := AValue;
if not (csLoading in ComponentState) then
GetAsyncDialog.Prompt := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.IsPS: Boolean;
begin
Result := Prompt <> S_FD_AsyncDialogDefPrompt;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.GetShowDelay: Integer;
begin
if not (csLoading in ComponentState) then
Result := GetAsyncDialog.ShowDelay
else
Result := FShowDelay;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.SetShowDelay(const AValue: Integer);
begin
FShowDelay := AValue;
if not (csLoading in ComponentState) then
GetAsyncDialog.ShowDelay := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxAsyncExecuteDialog.GetHideDelay: Integer;
begin
if not (csLoading in ComponentState) then
Result := GetAsyncDialog.HideDelay
else
Result := FHideDelay;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxAsyncExecuteDialog.SetHideDelay(const AValue: Integer);
begin
FHideDelay := AValue;
if not (csLoading in ComponentState) then
GetAsyncDialog.HideDelay := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxErrorDialog }
{-------------------------------------------------------------------------------}
constructor TFDGUIxErrorDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCaption := S_FD_ErrorDialogDefCaption;
FEnabled := True;
FStayOnTop := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxErrorDialog.Destroy;
begin
if FErrorDialog <> nil then begin
(FErrorDialog as IFDStanComponentReference).SetComponentReference(nil);
FErrorDialog.OnShow := nil;
FErrorDialog.OnHide := nil;
FErrorDialog := nil;
end;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TFDGUIxErrorDialog.GetGUID: TGUID;
begin
Result := IFDGUIxErrorDialog;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxErrorDialog.GetErrorDialog: IFDGUIxErrorDialog;
begin
if FErrorDialog = nil then begin
FDCreateInterface(IFDGUIxErrorDialog, FErrorDialog, True, Provider);
(FErrorDialog as IFDStanComponentReference).SetComponentReference(
Self as IInterfaceComponentReference);
end;
Result := FErrorDialog;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.Loaded;
var
oDlg: IFDGUIxErrorDialog;
begin
inherited Loaded;
FDCreateInterface(IFDGUIxErrorDialog, oDlg, False, Provider);
if oDlg <> nil then begin
oDlg := GetErrorDialog;
oDlg.Caption := FCaption;
oDlg.Enabled := FEnabled;
oDlg.StayOnTop := FStayOnTop;
oDlg.OnShow := DoOnShow;
oDlg.OnHide := DoOnHide;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.DoOnHide(ASender: TObject;
AException: EFDDBEngineException);
begin
if Assigned(FOnHide) then
FOnHide(Self, AException);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.DoOnShow(ASender: TObject;
AException: EFDDBEngineException);
begin
if Assigned(FOnShow) then
FOnShow(Self, AException);
end;
{-------------------------------------------------------------------------------}
function TFDGUIxErrorDialog.GetCaption: String;
begin
if not (csLoading in ComponentState) then
Result := GetErrorDialog.Caption
else
Result := FCaption;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxErrorDialog.IsCS: Boolean;
begin
Result := Caption <> S_FD_ErrorDialogDefCaption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.SetCaption(const AValue: String);
begin
FCaption := AValue;
if not (csLoading in ComponentState) then
GetErrorDialog.Caption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxErrorDialog.GetEnabled: Boolean;
begin
if not (csLoading in ComponentState) then
Result := GetErrorDialog.Enabled
else
Result := FEnabled;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.SetEnabled(const AValue: Boolean);
begin
FEnabled := AValue;
if not (csLoading in ComponentState) then
GetErrorDialog.Enabled := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxErrorDialog.GetStayOnTop: Boolean;
begin
if not (csLoading in ComponentState) then
Result := GetErrorDialog.StayOnTop
else
Result := FStayOnTop;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.SetStayOnTop(const AValue: Boolean);
begin
FStayOnTop := AValue;
if not (csLoading in ComponentState) then
GetErrorDialog.StayOnTop := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxErrorDialog.Execute(E: EFDDBEngineException);
begin
FErrorDialog.Execute(E);
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxLoginDialog }
{-------------------------------------------------------------------------------}
constructor TFDGUIxLoginDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FVisibleItems := TFDStringList.Create;
FCaption := S_FD_LoginDialogDefCaption;
FHistoryWithPassword := True;
FHistoryStorage := hsRegistry;
FHistoryKey := {$IFDEF MSWINDOWS} S_FD_CfgKeyName + '\' + S_FD_Profiles {$ENDIF}
{$IFDEF POSIX} S_FD_Profiles {$ENDIF};
FLoginRetries := 3;
FChangeExpiredPassword := True;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxLoginDialog.Destroy;
begin
if FLoginDialog <> nil then begin
(FLoginDialog as IFDStanComponentReference).SetComponentReference(nil);
FLoginDialog.OnLogin := nil;
FLoginDialog.OnChangePassword := nil;
FLoginDialog.OnShow := nil;
FLoginDialog.OnHide := nil;
FLoginDialog := nil;
FDFreeAndNil(FVisibleItems);
end;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TFDGUIxLoginDialog.GetGUID: TGUID;
begin
Result := IFDGUIxLoginDialog;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetLoginDialog: IFDGUIxLoginDialog;
begin
if FLoginDialog = nil then begin
FDCreateInterface(IFDGUIxLoginDialog, FLoginDialog, True, Provider);
(FLoginDialog as IFDStanComponentReference).SetComponentReference(
Self as IInterfaceComponentReference);
end;
Result := FLoginDialog;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.Loaded;
var
oDlg: IFDGUIxLoginDialog;
begin
inherited Loaded;
FDCreateInterface(IFDGUIxLoginDialog, oDlg, False, Provider);
if oDlg <> nil then begin
oDlg := GetLoginDialog;
oDlg.ConnectionDef := FConnectionDef;
oDlg.Caption := FCaption;
oDlg.HistoryEnabled := FHistoryEnabled;
oDlg.HistoryWithPassword := FHistoryWithPassword;
oDlg.HistoryStorage := FHistoryStorage;
oDlg.HistoryKey := FHistoryKey;
oDlg.VisibleItems := FVisibleItems;
oDlg.LoginRetries := FLoginRetries;
oDlg.ChangeExpiredPassword := FChangeExpiredPassword;
if Assigned(FOnLogin) then
oDlg.OnLogin := DoLogin;
if Assigned(FOnChangePassword) then
oDlg.OnChangePassword := DoChangePassword;
oDlg.OnShow := DoOnShow;
oDlg.OnHide := DoOnHide;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.DoLogin(ASender: TObject; var AResult: Boolean);
begin
if Assigned(FOnLogin) then
FOnLogin(Self, AResult);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.DoChangePassword(ASender: TObject; var AResult: Boolean);
begin
if Assigned(FOnChangePassword) then
FOnChangePassword(Self, AResult);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.DoOnShow(ASender: TObject);
begin
if Assigned(FOnShow) then
FOnShow(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.DoOnHide(ASender: TObject);
begin
if Assigned(FOnHide) then
FOnHide(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetOnChangePassword(const AValue: TFDGUIxLoginDialogEvent);
begin
FOnChangePassword := AValue;
if not (csLoading in ComponentState) then
if Assigned(FOnChangePassword) then
GetLoginDialog.OnChangePassword := DoChangePassword
else
GetLoginDialog.OnChangePassword := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetOnLogin(const AValue: TFDGUIxLoginDialogEvent);
begin
FOnLogin := AValue;
if not (csLoading in ComponentState) then
if Assigned(FOnLogin) then
GetLoginDialog.OnLogin := DoLogin
else
GetLoginDialog.OnLogin := nil;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetConnectionDef: IFDStanConnectionDef;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.ConnectionDef
else
Result := FConnectionDef;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetCaption: String;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.Caption
else
Result := FCaption;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetChangeExpiredPassword: Boolean;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.ChangeExpiredPassword
else
Result := FChangeExpiredPassword;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetHistoryEnabled: Boolean;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.HistoryEnabled
else
Result := FHistoryEnabled;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetHistoryKey: String;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.HistoryKey
else
Result := FHistoryKey;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetHistoryStorage: TFDGUIxLoginHistoryStorage;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.HistoryStorage
else
Result := FHistoryStorage;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetHistoryWithPassword: Boolean;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.HistoryWithPassword
else
Result := FHistoryWithPassword;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetLoginRetries: Integer;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.LoginRetries
else
Result := FLoginRetries;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.GetVisibleItems: TStrings;
begin
if not (csLoading in ComponentState) then
Result := GetLoginDialog.VisibleItems
else
Result := FVisibleItems;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetCaption(const AValue: String);
begin
FCaption := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.Caption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.IsCS: Boolean;
begin
Result := Caption <> S_FD_LoginDialogDefCaption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetChangeExpiredPassword(const AValue: Boolean);
begin
FChangeExpiredPassword := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.ChangeExpiredPassword := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetHistoryEnabled(const AValue: Boolean);
begin
FHistoryEnabled := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.HistoryEnabled := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetHistoryKey(const AValue: String);
begin
FHistoryKey := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.HistoryKey := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.IsHKS: Boolean;
begin
Result := HistoryKey <> ({$IFDEF MSWINDOWS} S_FD_CfgKeyName + '\' + S_FD_Profiles {$ENDIF}
{$IFDEF POSIX} S_FD_Profiles {$ENDIF});
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetHistoryStorage(const AValue: TFDGUIxLoginHistoryStorage);
begin
FHistoryStorage := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.HistoryStorage := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetHistoryWithPassword(const AValue: Boolean);
begin
FHistoryWithPassword := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.HistoryWithPassword := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetLoginRetries(const AValue: Integer);
begin
FLoginRetries := AValue;
if not (csLoading in ComponentState) then
GetLoginDialog.LoginRetries := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetConnectionDef(const AConnectionDef: IFDStanConnectionDef);
begin
FConnectionDef := AConnectionDef;
if not (csLoading in ComponentState) then
GetLoginDialog.ConnectionDef := AConnectionDef;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.SetVisibleItems(const AValue: TStrings);
begin
FVisibleItems.SetStrings(AValue);
if not (csLoading in ComponentState) then
GetLoginDialog.VisibleItems := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.IsVIS: Boolean;
begin
Result := not ((VisibleItems.Count = 2) and
(VisibleItems.IndexOf(S_FD_ConnParam_Common_UserName) >= 0) and
(VisibleItems.IndexOf(S_FD_ConnParam_Common_Password) >= 0));
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxLoginDialog.GetAllLoginParams;
begin
GetLoginDialog.GetAllLoginParams;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxLoginDialog.Execute(ALoginAction: TFDGUIxLoginAction): Boolean;
begin
Result := GetLoginDialog.Execute(ALoginAction);
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxScriptDialog }
{-------------------------------------------------------------------------------}
constructor TFDGUIxScriptDialog.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCaption := S_FD_ScriptDialogDefCaption;
FOptions := [ssCallstack, ssConsole, ssAutoHide];
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxScriptDialog.Destroy;
begin
if FScriptDialog <> nil then begin
(FScriptDialog as IFDStanComponentReference).SetComponentReference(nil);
FScriptDialog.OnShow := nil;
FScriptDialog.OnHide := nil;
FScriptDialog.OnProgress := nil;
FScriptDialog.OnOutput := nil;
FScriptDialog.OnInput := nil;
FScriptDialog.OnPause := nil;
FScriptDialog := nil;
end;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TFDGUIxScriptDialog.GetGUID: TGUID;
begin
Result := IFDGUIxScriptDialog;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptDialog.GetScriptDialog: IFDGUIxScriptDialog;
begin
if FScriptDialog = nil then begin
FDCreateInterface(IFDGUIxScriptDialog, FScriptDialog, True, Provider);
(FScriptDialog as IFDStanComponentReference).SetComponentReference(
Self as IInterfaceComponentReference);
end;
Result := FScriptDialog;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.Loaded;
var
oDlg: IFDGUIxScriptDialog;
begin
inherited Loaded;
FDCreateInterface(IFDGUIxScriptDialog, oDlg, False, Provider);
if oDlg <> nil then begin
oDlg := GetScriptDialog;
oDlg.Caption := FCaption;
oDlg.Options := FOptions;
oDlg.OnShow := DoOnShow;
oDlg.OnHide := DoOnHide;
oDlg.OnProgress := DoOnProgress;
oDlg.OnOutput := DoOnOutput;
oDlg.OnInput := DoOnInput;
oDlg.OnPause := DoOnPause;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.DoOnHide(ASender: TObject);
begin
if Assigned(FOnHide) then
FOnHide(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.DoOnShow(ASender: TObject);
begin
if Assigned(FOnShow) then
FOnShow(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.DoOnProgress(ASender: TObject; AInfoProvider: TObject);
begin
if Assigned(FOnProgress) then
FOnProgress(Self, AInfoProvider);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.DoOnOutput(ASender: TObject;
const AStr: String);
begin
if Assigned(FOnOutput) then
FOnOutput(Self, AStr);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.DoOnInput(ASender: TObject;
const APrompt: String; var AResult: String);
begin
if Assigned(FOnInput) then
FOnInput(Self, APrompt, AResult);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.DoOnPause(ASender: TObject;
const APrompt: String);
begin
if Assigned(FOnPause) then
FOnPause(Self, APrompt);
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptDialog.GetCaption: String;
begin
if not (csLoading in ComponentState) then
Result := GetScriptDialog.Caption
else
Result := FCaption;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.SetCaption(const AValue: String);
begin
FCaption := AValue;
if not (csLoading in ComponentState) then
GetScriptDialog.Caption := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptDialog.IsCS: Boolean;
begin
Result := Caption <> S_FD_ScriptDialogDefCaption;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxScriptDialog.GetOptions: TFDGUIxScriptOptions;
begin
if not (csLoading in ComponentState) then
Result := GetScriptDialog.Options
else
Result := FOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxScriptDialog.SetOptions(const AValue: TFDGUIxScriptOptions);
begin
FOptions := AValue;
if not (csLoading in ComponentState) then
GetScriptDialog.Options := AValue;
end;
{-------------------------------------------------------------------------------}
{ TFDGUIxWaitCursor }
{-------------------------------------------------------------------------------}
constructor TFDGUIxWaitCursor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FScreenCursor := gcrSQLWait;
end;
{-------------------------------------------------------------------------------}
destructor TFDGUIxWaitCursor.Destroy;
begin
if FWaitCursor <> nil then begin
(FWaitCursor as IFDStanComponentReference).SetComponentReference(nil);
FWaitCursor.OnShow := nil;
FWaitCursor.OnHide := nil;
FWaitCursor := nil;
end;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
class function TFDGUIxWaitCursor.GetGUID: TGUID;
begin
Result := IFDGUIxWaitCursor;
end;
{-------------------------------------------------------------------------------}
function TFDGUIxWaitCursor.GetGUIxWaitCursor: IFDGUIxWaitCursor;
begin
if FWaitCursor = nil then begin
FDCreateInterface(IFDGUIxWaitCursor, FWaitCursor, True, Provider);
(FWaitCursor as IFDStanComponentReference).SetComponentReference(
Self as IInterfaceComponentReference);
end;
Result := FWaitCursor;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursor.Loaded;
var
oCursor: IFDGUIxWaitCursor;
begin
inherited Loaded;
FDCreateInterface(IFDGUIxWaitCursor, oCursor, False, Provider);
if oCursor <> nil then begin
oCursor := GetGUIxWaitCursor;
oCursor.WaitCursor := FScreenCursor;
oCursor.OnShow := DoOnShow;
oCursor.OnHide := DoOnHide;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursor.SetProvider(const AValue: String);
begin
inherited SetProvider(AValue);
FFDGUIxProvider := AValue;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursor.DoOnHide(ASender: TObject);
begin
if Assigned(FOnHide) then
FOnHide(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursor.DoOnShow(ASender: TObject);
begin
if Assigned(FOnShow) then
FOnShow(Self);
end;
{-------------------------------------------------------------------------------}
function TFDGUIxWaitCursor.GetScreenCursor: TFDGUIxScreenCursor;
begin
if not (csLoading in ComponentState) then
Result := GetGUIxWaitCursor.WaitCursor
else
Result := FScreenCursor;
end;
{-------------------------------------------------------------------------------}
procedure TFDGUIxWaitCursor.SetScreenCursor(const AValue: TFDGUIxScreenCursor);
begin
FScreenCursor := AValue;
if not (csLoading in ComponentState) then
GetGUIxWaitCursor.WaitCursor := AValue;
end;
end.
|
unit Security.User.View;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, System.Hash, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.Imaging.pngimage,
PngSpeedButton, PngFunctions
, Security.Matrix.Interfaces
;
type
TSecurityUserView = class(TForm)
ShapeBodyRight: TShape;
ShapeBodyLeft: TShape;
ImageLogo: TImage;
PanelTitle: TPanel;
ShapePanelTitleBottom: TShape;
ShapePanelTitleRight: TShape;
ShapePanelTitleLeft: TShape;
ShapePanelTitleTop: TShape;
PanelTitleBackgroung: TPanel;
PanelTitleLabelAutenticacao: TLabel;
PanelTitleDOT: TLabel;
PanelTitleLabelAppName: TLabel;
PanelTitleAppInfo: TPanel;
PanelTitleAppInfoVersion: TPanel;
PanelTitleAppInfoVersionValue: TLabel;
PanelTitleAppInfoVersionCaption: TLabel;
PanelTitleAppInfoUpdated: TPanel;
PanelTitleAppInfoUpdatedValue: TLabel;
PanelTitleAppInfoUpdatedCaption: TLabel;
PanelStatus: TPanel;
PanelStatusShapeLeft: TShape;
PanelStatusShapeRight: TShape;
PanelStatusShapeBottom: TShape;
PanelStatusBackground: TPanel;
LabelIPServerCaption: TLabel;
LabelIPComputerValue: TLabel;
PanelStatusBackgroundClient: TPanel;
LabelIPComputerCaption: TLabel;
LabelIPServerValue: TLabel;
PanelToolbar: TPanel;
ShapeToolbarTop: TShape;
PngSpeedButtonOk: TPngSpeedButton;
PngSpeedButtonCancelar: TPngSpeedButton;
ShapeToolbarLeft: TShape;
ShapeToolbarRight: TShape;
ShapeToolbarBottom: TShape;
LabelTableStatus: TLabel;
LabelID: TLabel;
LabelPassword: TLabel;
LabelEmail: TLabel;
PanelID: TPanel;
PanelImageID: TPanel;
EditID: TEdit;
EditCreatedAt: TEdit;
PanelName: TPanel;
PanelImageName: TPanel;
ImageName: TImage;
PanelImageNameError: TPanel;
ImageNameError: TImage;
EditName: TEdit;
PanelEmail: TPanel;
PanelImageEmail: TPanel;
ImageEmail: TImage;
PanelImageEmailError: TPanel;
ImageEmailError: TImage;
EditEmail: TEdit;
LabelSenha: TLabel;
PanelEditPassword: TPanel;
PanelImagePassword: TPanel;
ImagePassword: TImage;
PanelImagePasswordError: TPanel;
ImagePasswordError: TImage;
EditPassword: TEdit;
LabelMatrix: TLabel;
PanelMatrixID: TPanel;
PanelImageEditMatrixID: TPanel;
PanelImageMatrixIDError: TPanel;
ImageMatrixIDError: TImage;
EditMatrixID: TEdit;
EditMatrixName: TEdit;
PanelImageCombo: TPanel;
ImageCombo: TImage;
ImageEditMatrixID: TImage;
PanelMatrix: TPanel;
shp2: TShape;
shp3: TShape;
shp4: TShape;
DBGridMatrix: TDBGrid;
Panel1: TPanel;
Shape1: TShape;
PngSpeedButtonComboOK: TPngSpeedButton;
PngSpeedButtonComboCancel: TPngSpeedButton;
Shape2: TShape;
Shape3: TShape;
Shape4: TShape;
CheckBoxActive: TCheckBox;
Panel2: TPanel;
Shape6: TShape;
Shape7: TShape;
Shape8: TShape;
Label2: TLabel;
procedure PngSpeedButtonCancelarClick(Sender: TObject);
procedure PngSpeedButtonOkClick(Sender: TObject);
procedure EditMatrixIDChange(Sender: TObject);
procedure ImageEditMatrixIDClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure PngSpeedButtonComboOKClick(Sender: TObject);
procedure PngSpeedButtonComboCancelClick(Sender: TObject);
procedure EditMatrixIDEnter(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
property ID : Int64 read getID write setID;
property UpdatedAt : TDateTime read getUpdatedAt write setUpdatedAt;
property Active : Boolean read getActive write setActive;
property MatrixID : Integer read getMatrixID write setMatrixID;
property NameMatrix: String read getNameMatrix write setNameMatrix;
property Email : String read getEmail write setEmail;
property Password : String read getPassword write setPassword;
property IsMatrix : Boolean read getIsMatrix write setIsMatrix;
end;
var
SecurityUserView: TSecurityUserView;
implementation
{$R *.dfm}
{ ---------- AUXs -> --------------------- }
{$REGION 'AUXs'}
type
THackedDBGrid = class(TDBGrid);
THackedCustomGrid = class(TCustomGrid);
procedure auxAutoSizeLastColumn(const aDBGrid: TDBGrid);
var
DrawInfo : TGridDrawInfo;
LColNo : Integer;
LColCount: Integer;
i : Integer;
begin
with THackedCustomGrid(aDBGrid) do
begin
LColCount := 0;
for i := 0 to Pred(aDBGrid.Columns.Count) do
if aDBGrid.Columns.Items[i].Visible then
Inc(LColCount);
LColNo := LColCount - 1;
CalcDrawInfo(DrawInfo);
if (DrawInfo.Horz.LastFullVisibleCell < LColNo - 1) then
Exit;
if (DrawInfo.Horz.LastFullVisibleCell < LColNo) then
ColWidths[LColNo] := DrawInfo.Horz.GridBoundary - DrawInfo.Horz.FullVisBoundary
else
ColWidths[LColNo] := ColWidths[LColNo] + DrawInfo.Horz.GridExtent - DrawInfo.Horz.FullVisBoundary
end;
end;
function auxEmpty(const aValue: string): Boolean;
begin
Result :=
(
(Length(aValue.Trim) = 0)
or
(aValue = format(' %s %s ', [TFormatSettings.Create.DateSeparator, TFormatSettings.Create.DateSeparator]))
or
(aValue = format(' %s %s ', [TFormatSettings.Create.DateSeparator, TFormatSettings.Create.DateSeparator]))
or
(aValue = ' - - ') or (aValue = ' - - ')
or
(aValue = ' . . ') or (aValue = ' . . ')
or
(aValue = ' / / ') or (aValue = ' / / ')
);
end;
function auxIsEmpty(aValue: string): Boolean;
begin
Result := auxEmpty(aValue);
end;
function auxTrimInOut(value: string): string;
var
cont: Integer;
begin
while True do
begin
cont := Length(value);
value := StringReplace(value, #32#32, #32, [rfReplaceAll, rfIgnoreCase]);
if cont = Length(value) then
Break;
end;
Result := Trim(value);
end;
function auxUppercaseTrim(const aValue: string): string;
begin
Result := auxTrimInOut(UpperCase(aValue));
end;
function auxMD5(const aValue: string; aUpperCase: Boolean = True): string;
begin
Result := System.Hash.THashMD5.GetHashString(aValue);
if aUpperCase then
Result := UpperCase(Result);
end;
{$ENDREGION}
{ ---------- <- AUXs --------------------- }
procedure TSecurityUserView.EditMatrixIDChange(Sender: TObject);
begin
PanelImageMatrixIDError.Visible := false;
if not SameStr(EditMatrixID.Text, DataSourceMatrix.DataSet.FieldByName('matrix_id').AsString) then
if DataSourceMatrix.DataSet.Locate('matrix_id', EditMatrixID.Text, []) then
EditMatrixName.Text := DataSourceMatrix.DataSet.FieldByName('name').AsString
else
EditMatrixName.Clear;
end;
procedure TSecurityUserView.EditMatrixIDEnter(Sender: TObject);
begin
if SameStr(EditMatrixID.Text, EmptyStr) then
PngSpeedButtonComboOK.Click;
end;
procedure TSecurityUserView.FormCreate(Sender: TObject);
begin
PanelMatrix.Visible := false;
PanelMatrix.Left := 154;
PanelMatrix.BringToFront;
end;
procedure TSecurityUserView.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case Key of
VK_F2:
begin
if ActiveControl = EditMatrixID then
begin
PngSpeedButtonComboOK.Click;
Key := VK_CANCEL;
end;
end;
VK_UP:
begin
if ActiveControl = EditMatrixID then
begin
if PanelMatrix.Visible then
if DataSourceMatrix.DataSet.Bof then
DataSourceMatrix.DataSet.Last
else
DataSourceMatrix.DataSet.Prior;
Key := VK_CANCEL;
end;
end;
VK_DOWN:
begin
if ActiveControl = EditMatrixID then
begin
if PanelMatrix.Visible then
if DataSourceMatrix.DataSet.Eof then
DataSourceMatrix.DataSet.First
else
DataSourceMatrix.DataSet.Next;
Key := VK_CANCEL;
end;
end;
VK_RETURN:
begin
if ActiveControl = EditMatrixID then
begin
if SameStr(EditMatrixID.Text, EmptyStr) and (not PanelMatrix.Visible) then
PngSpeedButtonComboOK.Click
else if not SameStr(EditMatrixID.Text, EmptyStr) then
SelectNext(ActiveControl, True, True);
end
else if ActiveControl = EditPassword then
PngSpeedButtonOk.Click
else
SelectNext(ActiveControl, True, True);
Key := VK_CANCEL;
end;
VK_ESCAPE:
begin
if ActiveControl = EditMatrixID then
begin
if not PanelMatrix.Visible then
PngSpeedButtonComboCancel.Click;
end;
Key := VK_CANCEL;
end;
end;
end;
procedure TSecurityUserView.FormShow(Sender: TObject);
begin
auxAutoSizeLastColumn(DBGridMatrix);
PanelMatrix.BringToFront;
end;
procedure TSecurityUserView.ImageEditMatrixIDClick(Sender: TObject);
begin
PanelMatrix.Visible := not PanelMatrix.Visible;
end;
procedure TSecurityUserView.PngSpeedButtonCancelarClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TSecurityUserView.PngSpeedButtonComboCancelClick(Sender: TObject);
begin
PanelMatrix.Visible := false;
end;
procedure TSecurityUserView.PngSpeedButtonComboOKClick(Sender: TObject);
begin
EditMatrixID.Text := DataSourceMatrix.DataSet.FieldByName('matrix_id').AsString;
EditMatrixName.Text := DataSourceMatrix.DataSet.FieldByName('name').AsString;
PanelMatrix.Visible := false;
end;
procedure TSecurityUserView.PngSpeedButtonOkClick(Sender: TObject);
procedure canValidate(const aControl: TWinControl; const aTest: Boolean; const aMessageErroTestFalse: string; const aPanelImageError: TPanel; const aImageError: TImage);
begin
aImageError.Hint := aMessageErroTestFalse;
aPanelImageError.Visible := aTest;
if aTest then
begin
aControl.SetFocus;
Abort;
end;
end;
var
LMatrixID: Integer;
begin
// Validações
canValidate(EditName, auxIsEmpty(EditName.Text), 'Informe o [Nome].', PanelImageNameError, ImageNameError);
canValidate(EditEmail, auxIsEmpty(EditEmail.Text), 'Informe o [Email].', PanelImageEmailError, ImageEmailError);
canValidate(EditPassword, auxIsEmpty(EditPassword.Text) and (DataSourceUser.DataSet.State = dsInsert), 'Informe a [Senha].', PanelImagePasswordError, ImagePasswordError);
canValidate(EditMatrixID, auxIsEmpty(EditMatrixID.Text), 'Informe a [Matrix] com as permissões iniciais.', PanelImageMatrixIDError, ImageMatrixIDError);
canValidate(EditMatrixID, not TryStrToInt(EditMatrixID.Text, LMatrixID), 'Informe a [Matrix] com as permissões iniciais.', PanelImageMatrixIDError, ImageMatrixIDError);
// Atricuições
with DataSourceUser.DataSet do
begin
FieldByName('name').AsString := auxTrimInOut(EditName.Text);
FieldByName('email').AsString := auxTrimInOut(EditEmail.Text);
if not auxIsEmpty(EditPassword.Text) then
FieldByName('password').AsString := auxMD5(auxUppercaseTrim(EditPassword.Text));
FieldByName('matrix_id').AsInteger := LMatrixID;
FieldByName('is_matrix').AsBoolean := false;
FieldByName('active').AsBoolean := CheckBoxActive.Checked;
Post;
end;
ModalResult := mrOk;
end;
end.
|
unit U_MyClass;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,Grids,
StdCtrls, Menus, ToolWin, ComCtrls, ExtCtrls,Dialogs,Forms;
{********************************************************************************
*类名称:TStringGridInputType
*类功能:控件名称定义,每一组用begin和end分隔,第0个表示没有控件,最好一个表示前面的所有控件
*作者:Sen,2008.11.27
********************************************************************************}
type TStringGridInputType=(
InputTypeRemove,//起始为0,没效控件
InputTypeCheckBegin,
InputTypeCheck,
InputTypeUncheck,
InputTypeCheckEnd,
InputTypeListBegin,
InputTypeComboBox,
InputTypeDateTimePicker,
InputTypeListAll,
InputTypeListEnd,
InputTypeAll//上面所有类型
);
{********************************************************************************
*类名称:TStringGridCheckBox
*类功能:在TStringGrid的单元格画CheckBox,比动态生成CheckBox效率高得多
*作者:Sen,2008.10.6
********************************************************************************}
type
TStringGridCheckBox = class
private
FCheck,FNoCheck:TBitmap;
GridDrawState:TGridDrawState;
ACol,ARow:Integer;
public
constructor Create();
destructor Destroy();override;
procedure DrawCellWithCheckBox(Sender: TObject; ACol,ARow: Integer; Rect: TRect; State: TGridDrawState);
procedure CheckHorizontalFixedTile(Sender: TObject;Checked:bool=true);//第一行画上checkbox
procedure CheckVerticalFixedTile(Sender: TObject;Checked:bool=true);//第一列画上checkbox
procedure CheckCell(Sender: TObject;ACol,ARow:Integer;Checked:bool=true);//单元格画上checkbox
function GetCellChecked(Sender: TObject;ACol,ARow:Integer):bool;//获取checkbox的状态
procedure RemoveCheckBox(Sender: TObject;ACol,ARow:Integer);//删除checkbox
procedure StringGridCheckBoxOnMouse(Sender: TObject;Button: TMouseButton; Shift: TShiftState; X, Y: Integer);//切换复选框状态
procedure ClearContent(Sender: TObject);//清空表格内容,不包括标题栏
end;//end type TStringGridCheckBox
var StrintGridCheckBox:TStringGridCheckBox;
{********************************************************************************
*类名称:TStringGridInput
*类功能:在TStringGrid的单元格放置数据输入控件
*作者:Sen,2008.11.26
********************************************************************************}
type
TStringGridInput = class(TForm)
private
nCol,nRow:integer;
StringGrid:TStringGrid;
procedure CreateInput(InputType:TStringGridInputType);
procedure DestroyInput(InputType:TStringGridInputType);
procedure Notification(AComponent:TComponent;Operation:TOperation);override;
public
ComboBox:TComboBox;
DateTimePicker:TDateTimePicker;
constructor Create();
destructor Destroy();override;
procedure SetOwner(AOwner:TStringGrid);
procedure SetCellInputType(Sender:TObject;ACol,ARow:Integer;InputType:TStringGridInputType);
procedure StringGridInputSelectCell(Sender:TObject;ACol,ARow:Integer;var CanSelect:Boolean);
procedure OnClickEvent(Sender:TObject);
procedure OnExitEvent(Sender:TObject);
procedure FreeOwner();
end;//end type TStringGridInput
implementation
{*************************************************************
*下面为TStringGridInput类的实现部分
*************************************************************}
constructor TStringGridInput.Create();
begin
ComboBox:=Nil;
DateTimePicker:=Nil;
StringGrid:=Nil;
end;
destructor TStringGridInput.Destroy();
begin
FreeOwner();
Release;
end;
procedure TStringGridInput.SetOwner(AOwner:TStringGrid);
begin
StringGrid:=AOwner;
CreateInput(InputTypeListAll);
end;
procedure TStringGridInput.StringGridInputSelectCell(Sender: TObject; ACol,ARow: Integer; var CanSelect: Boolean);
var Rect:TRect;
i:integer;
begin
SetOwner(Sender as TStringGrid);
Rect:=StringGrid.CellRect(ACol,ARow);
case TStringGridInputType(StringGrid.Objects[ACol,ARow]) of
InputTypeComboBox:
begin
nCol:=ACol;nRow:=ARow;
ComboBox.ItemIndex:=0;
for i:=0 to ComboBox.Items.Count-1 do
if StringGrid.Cells[Acol,ARow]=ComboBox.Items.Strings[i] then
begin
ComboBox.ItemIndex:=i;
break;
end;
ComboBox.ItemHeight:=Rect.Bottom-Rect.Top-3;
ComboBox.SetBounds(Rect.Left+StringGrid.Left,Rect.Top+StringGrid.Top,Rect.Right-Rect.Left+3,Rect.Bottom-Rect.Top);
ComboBox.Visible:=true;
ComboBox.SetFocus;
end;
InputTypeDateTimePicker:
begin
nCol:=ACol;nRow:=ARow;
DateTimePicker.SetBounds(Rect.Left+StringGrid.Left,Rect.Top+StringGrid.Top,Rect.Right-Rect.Left+3,Rect.Bottom-Rect.Top+4);
DateTimePicker.Visible:=true;
DateTimePicker.SetFocus;
end;
else
begin
nCol:=0;nRow:=0;
end;
end;//end case
end;
procedure TStringGridInput.OnClickEvent(Sender: TObject);
var FormatSettings:TFormatSettings;
Formatstring:string;
i:integer;
begin
if Sender is TComboBox then
begin
StringGrid.Cells[nCol,nRow]:=ComboBox.Items.Strings[ComboBox.ItemIndex];
ComboBox.Visible:=false;
end
else if Sender is TDateTimePicker then
begin
DateTimePicker.Visible:=false;
//FormatSettings.ShortDateFormat:='yyyy-MM-dd';
FormatSettings.ShortDateFormat:=DateTimePicker.Format;
//StringGrid.Cells[nCol,nRow]:=DateTimeToStr(DateTimePicker.DateTime,FormatSettings);
if DateTimePicker.Kind=dtkTime then
begin
Formatstring:=DateTimePicker.Format;
for i:=0 to length(Formatstring)-1 do
begin
if Formatstring[i]='m' then
begin
Formatstring[i]:='n';
end;
end;
StringGrid.Cells[nCol,nRow]:=formatdatetime(Formatstring,DateTimePicker.DateTime);
end
else
begin
StringGrid.Cells[nCol,nRow]:=formatdatetime(DateTimePicker.Format,DateTimePicker.DateTime);
end;
end
else;
end;
procedure TStringGridInput.OnExitEvent(Sender:TObject);
begin
OnClickEvent(Sender);
end;
procedure TStringGridInput.SetCellInputType(Sender:TObject;ACol,ARow:Integer;InputType:TStringGridInputType);
begin
StringGrid.Objects[ACol,ARow]:=TObject(InputType);
end;
procedure TStringGridInput.CreateInput(InputType:TStringGridInputType);
var i:integer;
begin
case InputType of
InputTypeComboBox:
begin
if not Assigned(ComboBox) then
begin
ComboBox:=TComboBox.Create(Application);
ComboBox.Style:=csOwnerDrawFixed;
ComboBox.Visible:=false;
ComboBox.OnClick:=OnClickEvent;
ComboBox.OnExit:=OnExitEvent;
ComboBox.Parent:=StringGrid.Parent;
//ComboBox.FreeNotification(self);//self StringGridInput
end;
if Assigned(ComboBox) and Assigned(StringGrid.Parent) then //
begin
ComboBox.Parent:=StringGrid.Parent;
end;
end;
InputTypeDateTimePicker:
begin
if not Assigned(DateTimePicker) then
begin
DateTimePicker:=TDateTimePicker.Create(Application);
DateTimePicker.Visible:=false;
DateTimePicker.OnCloseUp:=OnClickEvent;
DateTimePicker.OnExit:=OnExitEvent;
DateTimePicker.Parent:=StringGrid.Parent;
DateTimePicker.Format:='yyyy-MM-dd';
end;
if Assigned(DateTimePicker) and Assigned(StringGrid.Parent) then
begin
DateTimePicker.Parent:=StringGrid.Parent;
end;
end;
InputTypeListAll://递归创建所有输入控件
begin
for i:=ord(InputTypeListBegin)+1 to ord(InputTypeListAll)-1 do
begin
CreateInput(TStringGridInputType(i));
end;
end;
else;
end;//end case
end;
procedure TStringGridInput.DestroyInput(InputType:TStringGridInputType);
var i:integer;
begin
case InputType of
InputTypeComboBox:
begin
if Assigned(ComboBox) then
begin
ComboBox.Items.Clear();
ComboBox.Parent:=Nil;
ComboBox:=Nil;
ComboBox.Free();
end;
end;
InputTypeDateTimePicker:
begin
if Assigned(DateTimePicker) then
begin
DateTimePicker.Parent:=Nil;
DateTimePicker:=Nil;
DateTimePicker.Free();
end;
end;
InputTypeListAll://递归注销所有输入控件
begin
for i:=ord(InputTypeListBegin)+1 to ord(InputTypeListAll)-1 do
begin
DestroyInput(TStringGridInputType(i));
end;
end;
else;
end;//end case
end;
procedure TStringGridInput.FreeOwner();
begin
DestroyInput(InputTypeListAll);
end;
procedure TStringGridInput.Notification(AComponent:TComponent;Operation:TOperation);
begin
Showmessage('Notification');
end;
{*************************************************************
*下面为TStringGridCheckBox类的实现部分
*************************************************************}
constructor TStringGridCheckBox.Create();
var bmp: TBitmap;
begin
FCheck:= TBitmap.Create;
FNoCheck:= TBitmap.Create;
bmp:= TBitmap.create;
try
bmp.handle := LoadBitmap( 0, PChar(OBM_CHECKBOXES ));
// bmp now has a 4x3 bitmap of divers state images
// used by checkboxes and radiobuttons
With FNoCheck Do
Begin
// the first subimage is the unchecked box
width := bmp.width div 4;
height := bmp.height div 3;
canvas.copyrect( canvas.cliprect, bmp.canvas, canvas.cliprect );
End;
With FCheck Do
Begin
// the second subimage is the checked box
width := bmp.width div 4;
height := bmp.height div 3;
canvas.copyrect(canvas.cliprect,bmp.canvas,rect( width, 0, 2*width, height ));
End;
finally
bmp.free
end;
end;
destructor TStringGridCheckBox.Destroy();
begin
FNoCheck.Free;
FCheck.Free;
end;
procedure TStringGridCheckBox.DrawCellWithCheckBox(Sender: TObject; ACol,ARow: Integer; Rect: TRect; State: TGridDrawState);
var
grid: TStringgrid;
tmpRect:TRect;
x,y:integer;
begin
//if (ARow=0)or(ACol=0) then
begin
With (Sender As TStringgrid).Canvas Do
Begin
tmpRect:=rect;
//brush.color := $E0E0E0;// checkboxes look better on a non-white background
Fillrect( tmpRect );
x:= rect.left+5;
y:=(rect.bottom + rect.top - FCheck.height) div 2;
If ((Sender As TStringgrid).Objects[ACol,ARow]=TObject(InputTypeCheck)) Then //(ARow<>ACol)and
begin
Draw(x,y,FCheck);
tmpRect.Left:=x+3+FCheck.Width;
Textrect(tmpRect,tmpRect.Left,y,(Sender as TStringGrid).Cells[aCol,aRow]);
end
Else If ((Sender As TStringgrid).Objects[ACol,ARow]=TObject(InputTypeUncheck)) Then //(ARow<>ACol)and
begin
Draw(x,y,FNoCheck);
tmpRect.Left:=x+3+FCheck.Width;
Textrect(tmpRect,tmpRect.Left,y,(Sender as TStringGrid).Cells[aCol,aRow]);
end
Else
begin
tmpRect.Left:=x+3;
Textrect(tmpRect,tmpRect.Left,y,(Sender as TStringGrid).Cells[aCol,aRow]);
end;
End;
end;
end;
procedure TStringGridCheckBox.CheckHorizontalFixedTile(Sender:TObject;Checked:bool=true);
var
grid: TStringgrid;
i:integer;
begin
grid:=Sender As TStringgrid;
ARow:=grid.FixedRows-1;
for i:= grid.FixedCols to grid.ColCount-1 do
begin
//if Checked then grid.Objects[i,ARow]:=TObject(InputTypeCheck)
if (Checked)and(grid.ColWidths[i]<>-1) then grid.Objects[i,ARow]:=TObject(InputTypeCheck)//2009年9月16日14:55:09,不可视行不选中
else grid.Objects[i,ARow]:=TObject(InputTypeUncheck);
end;
end;
procedure TStringGridCheckBox.CheckVerticalFixedTile(Sender: TObject;Checked:bool=true);
var
grid: TStringgrid;
i:integer;
begin
grid:=Sender As TStringgrid;
for i:= grid.FixedRows to grid.RowCount-1 do
begin
//if Checked then grid.Objects[grid.FixedCols-1,i]:=TObject(InputTypeCheck)
if (Checked)and(grid.RowHeights[i]<>-1) then grid.Objects[grid.FixedCols-1,i]:=TObject(InputTypeCheck)//2009年9月16日14:55:09,不可视行不选中
else grid.Objects[grid.FixedCols-1,i]:=TObject(InputTypeUncheck);
end;
end;
procedure TStringGridCheckBox.CheckCell(Sender: TObject;ACol,ARow:Integer;Checked:bool=true);
var
grid: TStringgrid;
begin
grid:=Sender As TStringgrid;
if Checked then
grid.Objects[ACol,ARow]:=TObject(InputTypeCheck)
else
grid.Objects[ACol,ARow]:=TObject(InputTypeUncheck);
end;
function TStringGridCheckBox.GetCellChecked(Sender: TObject;ACol,ARow:Integer):bool;
var grid: TStringgrid;
begin
grid:=Sender As TStringgrid;
if grid.Objects[ACol,ARow]=TObject(InputTypeCheck) then
result:=true
else
result:=false;
end;
procedure TStringGridCheckBox.RemoveCheckBox(Sender: TObject;ACol,ARow:Integer);
var grid: TStringgrid;
begin
grid:=Sender As TStringgrid;
grid.Objects[ACol,ARow]:=TObject(InputTypeRemove);
end;
procedure TStringGridCheckBox.StringGridCheckBoxOnMouse(Sender: TObject;Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var i,j:integer;
grid: TStringgrid;
Rect: TGridRect;
begin
grid:=Sender As TStringgrid;
for i:=0 to grid.RowCount-1 do//第一列
begin
for j:=0 to grid.ColCount-1 do
begin
if PtInRect(grid.CellRect(j,i),Point(X,Y))then
begin
if grid.Objects[j,i]=TObject(InputTypeCheck) then
grid.Objects[j,i]:=TObject(InputTypeUncheck)
else if grid.Objects[j,i]=TObject(InputTypeUncheck) then
grid.Objects[j,i]:=TObject(InputTypeCheck)
else;
exit;
end;
end;
end;
end;
procedure TStringGridCheckBox.ClearContent(Sender: TObject);
var i,j:integer;
grid: TStringgrid;
begin
grid:=Sender As TStringgrid;
for i:=1 to grid.RowCount-1 do
begin
for j:=1 to grid.ColCount-1 do
begin
grid.Cells[j,i]:='';
end;
end;
end;
initialization
end.
|
{ Compute the sine using: sqrt(1 - cosine**2)
This file verifies a unit that uses another unit
}
unit MySineUnit;
interface
function mysine(x : real) : real;
implementation
uses
MyCosineUnit in '501-unit-cosine.pas';
function mysine(x : real) : real;
var
mycos : real
begin
mycos := mycosine(x);
mysine := sqrt(1.0 - sqr(mycos))
end; { mysine }
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: Joystick<p>
Component for handling joystick messages<p>
<b>Historique : </b><font size=-1><ul>
<li>17/03/07 - DaStr - Dropped Kylix support in favor of FPC (BugTracekrID=1681585)
<li>29/01/02 - Egg - Added NoCaptureErrors
<li>18/12/00 - Egg - Fix for supporting 2 joysticks simultaneously
<li>14/04/00 - Egg - Various minor to major fixes, the component should
now work properly for the 4 first buttons and XY axis
<li>20/03/00 - Egg - Creation from GLScene's TGLJoystick
</ul></font>
}
unit GLJoystick;
interface
{$i GLScene.inc}
{$IFDEF UNIX}{$Message Error 'Unit not supported'}{$ENDIF}
uses
Winapi.Windows, Winapi.Messages, Winapi.MMSystem,
System.SysUtils, System.Classes,
VCL.Forms, VCL.Controls;
type
TJoystickButton = (jbButton1, jbButton2, jbButton3, jbButton4);
TJoystickButtons = set of TJoystickButton;
TJoystickID = (jidNoJoystick, jidJoystick1, jidJoystick2);
TJoystickDesignMode = (jdmInactive, jdmActive);
TJoyPos = (jpMin, jpCenter, jpMax);
TJoyAxis = (jaX, jaY, jaZ, jaR, jaU, jaV);
TJoystickEvent = procedure(Sender: TObject; JoyID: TJoystickID; Buttons: TJoystickButtons;
XDeflection, YDeflection: Integer) of Object;
// TJoystick
//
{: A component interfacing the Joystick via the (regular) windows API. }
TGLJoystick = class (TComponent)
private
{ Private Declarations }
FWindowHandle : HWND;
FNumButtons, FLastX, FLastY, FLastZ : Integer;
FThreshold, FInterval : Cardinal;
FCapture, FNoCaptureErrors : Boolean;
FJoystickID : TJoystickID;
FMinMaxInfo : array[TJoyAxis, TJoyPos] of Integer;
FXPosInfo, FYPosInfo : array[0..4] of Integer;
FOnJoystickButtonChange, FOnJoystickMove : TJoystickEvent;
FXPosition, FYPosition : Integer;
FJoyButtons : TJoystickButtons;
procedure SetCapture(AValue: Boolean);
procedure SetInterval(AValue: Cardinal);
procedure SetJoystickID(AValue: TJoystickID);
procedure SetThreshold(AValue: Cardinal);
protected
{ Protected Declarations }
function MakeJoyButtons(Param: UINT): TJoystickButtons;
procedure DoJoystickCapture(AHandle: HWND; AJoystick: TJoystickID);
procedure DoJoystickRelease(AJoystick: TJoystickID);
procedure DoXYMove(Buttons: Word; XPos, YPos: Integer);
procedure DoZMove(Buttons: Word; ZPos: Integer);
procedure ReapplyCapture(AJoystick: TJoystickID);
procedure WndProc(var Msg: TMessage);
procedure Loaded; override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
property JoyButtons : TJoystickButtons read FJoyButtons;
property XPosition : Integer read FXPosition;
property YPosition : Integer read FYPosition;
published
{ Published Declarations }
{: When set to True, the component attempts to capture the joystick.<p>
If capture is successfull, retrieving joystick status is possible,
if not, an error message is triggered. }
property Capture : Boolean read FCapture write SetCapture default False;
{: If true joystick capture errors do not result in exceptions. }
property NoCaptureErrors : Boolean read FNoCaptureErrors write FNoCaptureErrors default True;
{: Polling frequency (milliseconds) }
property Interval : Cardinal read FInterval write SetInterval default 100;
property JoystickID: TJoystickID read FJoystickID write SetJoystickID default jidNoJoystick;
property Threshold: Cardinal read FThreshold write SetThreshold default 1000;
property OnJoystickButtonChange: TJoystickEvent read FOnJoystickButtonChange write FOnJoystickButtonChange;
property OnJoystickMove: TJoystickEvent read FOnJoystickMove write FOnJoystickMove;
end;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
const
cJoystickIDToNative : array [jidNoJoystick..jidJoystick2] of Byte =
(9, JOYSTICKID1, JOYSTICKID2);
resourcestring
glsNoJoystickDriver = 'There''s no joystick driver present';
glsConnectJoystick = 'Joystick is not connected to your system';
glsJoystickError = 'Your system reports a joystick error, can''t do anything about it';
// ------------------
// ------------------ TJoystick ------------------
// ------------------
// Create
//
constructor TGLJoystick.Create(AOwner: TComponent);
begin
inherited;
FWindowHandle := AllocateHWnd(WndProc);
FInterval := 100;
FThreshold := 1000;
FJoystickID := jidNoJoystick;
FLastX := -1;
FLastY := -1;
FLastZ := -1;
FNoCaptureErrors := True;
end;
// Destroy
//
destructor TGLJoystick.Destroy;
begin
DeallocateHWnd(FWindowHandle);
inherited;
end;
// WndProc
//
procedure TGLJoystick.WndProc(var Msg: TMessage);
begin
with Msg do begin
case FJoystickID of
jidJoystick1 : // check only 1st stick
case Msg of
MM_JOY1MOVE :
DoXYMove(wParam, lParamLo, lParamHi);
MM_JOY1ZMOVE :
DoZMove(wParam, lParamLo);
MM_JOY1BUTTONDOWN :
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
MM_JOY1BUTTONUP :
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
end;
jidJoystick2 : // check only 2nd stick
case Msg of
MM_JOY2MOVE :
DoXYMove(wParam, lParamLo, lParamHi);
MM_JOY2ZMOVE :
DoZMove(wParam, lParamLo);
MM_JOY2BUTTONDOWN :
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
MM_JOY2BUTTONUP :
if Assigned(FOnJoystickButtonChange) then
FOnJoystickButtonChange(Self, FJoystickID, MakeJoyButtons(wParam),
FLastX, FLastY);
end;
jidNoJoystick : ; // ignore
else
Assert(False);
end;
Result:=0;
end;
end;
// Loaded
//
procedure TGLJoystick.Loaded;
begin
inherited;
ReapplyCapture(FJoystickID);
end;
// Assign
//
procedure TGLJoystick.Assign(Source: TPersistent);
begin
if Source is TGLJoystick then begin
FInterval := TGLJoystick(Source).FInterval;
FThreshold := TGLJoystick(Source).FThreshold;
FCapture := TGLJoystick(Source).FCapture;
FJoystickID := TGLJoystick(Source).FJoystickID;
try
ReapplyCapture(FJoystickID);
except
FJoystickID := jidNoJoystick;
FCapture := False;
raise;
end;
end else inherited Assign(Source);
end;
// MakeJoyButtons
//
function TGLJoystick.MakeJoyButtons(Param: UINT): TJoystickButtons;
begin
Result := [];
if (Param and JOY_BUTTON1) > 0 then Include(Result, jbButton1);
if (Param and JOY_BUTTON2) > 0 then Include(Result, jbButton2);
if (Param and JOY_BUTTON3) > 0 then Include(Result, jbButton3);
if (Param and JOY_BUTTON4) > 0 then Include(Result, jbButton4);
FJoyButtons:=Result;
end;
// DoScale
//
function DoScale(aValue : Integer) : Integer;
begin
Result:=Round(AValue/1);
end;
// ReapplyCapture
//
procedure TGLJoystick.ReapplyCapture(AJoystick: TJoystickID);
var
jc : TJoyCaps;
begin
DoJoystickRelease(AJoystick);
if FCapture and (not (csDesigning in ComponentState)) then with JC do begin
joyGetDevCaps(cJoystickIDToNative[FJoystickID], @JC, SizeOf(JC));
FNumButtons := wNumButtons;
FMinMaxInfo[jaX, jpMin] := DoScale(wXMin);
FMinMaxInfo[jaX, jpCenter] := DoScale((wXMin + wXMax) div 2); FMinMaxInfo[jaX, jpMax] := DoScale(wXMax);
FMinMaxInfo[jaY, jpMin] := DoScale(wYMin); FMinMaxInfo[jaY, jpCenter] := DoScale((wYMin + wYMax) div 2); FMinMaxInfo[jaY, jpMax] := DoScale(wYMax);
FMinMaxInfo[jaZ, jpMin] := DoScale(wZMin); FMinMaxInfo[jaZ, jpCenter] := DoScale((wZMin + wZMax) div 2); FMinMaxInfo[jaZ, jpMax] := DoScale(wZMax);
FMinMaxInfo[jaR, jpMin] := DoScale(wRMin); FMinMaxInfo[jaR, jpCenter] := DoScale((wRMin + wRMax) div 2); FMinMaxInfo[jaR, jpMax] := DoScale(wRMax);
FMinMaxInfo[jaU, jpMin] := DoScale(wUMin); FMinMaxInfo[jaU, jpCenter] := DoScale((wUMin + wUMax) div 2); FMinMaxInfo[jaU, jpMax] := DoScale(wUMax);
FMinMaxInfo[jaV, jpMin] := DoScale(wVMin); FMinMaxInfo[jaV, jpCenter] := DoScale((wVMin + wVMax) div 2); FMinMaxInfo[jaV, jpMax] := DoScale(wVMax);
DoJoystickCapture(FWindowHandle, AJoystick)
end;
end;
// DoJoystickCapture
//
procedure TGLJoystick.DoJoystickCapture(AHandle: HWND; AJoystick: TJoystickID);
var
res : Cardinal;
begin
res:=joySetCapture(AHandle, cJoystickIDToNative[AJoystick], FInterval, True);
if res<>JOYERR_NOERROR then begin
FCapture:=False;
if not NoCaptureErrors then begin
case res of
MMSYSERR_NODRIVER : raise Exception.Create(glsNoJoystickDriver);
JOYERR_UNPLUGGED : raise Exception.Create(glsConnectJoystick);
JOYERR_NOCANDO : raise Exception.Create(glsJoystickError);
else
raise Exception.Create(glsJoystickError);
end;
end;
end else joySetThreshold(cJoystickIDToNative[AJoystick], FThreshold);
end;
// DoJoystickRelease
//
procedure TGLJoystick.DoJoystickRelease(AJoystick: TJoystickID);
begin
if AJoystick <> jidNoJoystick then
joyReleaseCapture(cJoystickIDToNative[AJoystick]);
end;
// SetCapture
//
procedure TGLJoystick.SetCapture(AValue: Boolean);
begin
if FCapture <> AValue then begin
FCapture := AValue;
if not (csReading in ComponentState) then begin
try
ReapplyCapture(FJoystickID);
except
FCapture := False;
raise;
end;
end;
end;
end;
// SetInterval
//
procedure TGLJoystick.SetInterval(AValue: Cardinal);
begin
if FInterval <> AValue then begin
FInterval := AValue;
if not (csReading in ComponentState) then
ReapplyCapture(FJoystickID);
end;
end;
// SetJoystickID
//
procedure TGLJoystick.SetJoystickID(AValue: TJoystickID);
begin
if FJoystickID <> AValue then begin
try
if not (csReading in ComponentState) then
ReapplyCapture(AValue);
FJoystickID := AValue;
except
on E: Exception do begin
ReapplyCapture(FJoystickID);
Application.ShowException(E);
end;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TGLJoystick.SetThreshold(AValue: Cardinal);
begin
if FThreshold <> AValue then
begin
FThreshold := AValue;
if not (csReading in ComponentState) then ReapplyCapture(FJoystickID);
end;
end;
//------------------------------------------------------------------------------
function Approximation(Data: array of Integer): Integer;
// calculate a better estimation of the last value in the given data, depending
// on the other values (used to approximate a smoother joystick movement)
//
// based on Gauss' principle of smallest squares in Maximum-Likelihood and
// linear normal equations
var
SumX, SumY, SumXX, SumYX: Double;
I, Comps: Integer;
a0, a1: Double;
begin
SumX := 0;
SumY := 0;
SumXX := 0;
SumYX := 0;
Comps := High(Data) + 1;
for I := 0 to High(Data) do
begin
SumX := SumX + I;
SumY := SumY + Data[I];
SumXX := SumXX + I * I;
SumYX := SumYX + I * Data[I];
end;
a0 := (SumY * SumXX - SumX * SumYX) / (Comps * SumXX - SumX * SumX);
a1 := (Comps * SumYX - SumY * SumX) / (Comps * SumXX - SumX * SumX);
Result := Round(a0 + a1 * High(Data));
end;
// DoXYMove
//
procedure TGLJoystick.DoXYMove(Buttons: Word; XPos, YPos: Integer);
var
I: Integer;
dX, dY: Integer;
begin
XPos := DoScale(XPos);
YPos := DoScale(YPos);
if (FLastX = -1) or (FLastY = -1) then begin
FLastX:=XPos;
FLastY:=YPos;
for I:=0 to 4 do begin
FXPosInfo[I]:=XPos;
FYPosInfo[I]:=YPos;
end;
end else begin
Move(FXPosInfo[1], FXPosInfo[0], 16);
FXPosInfo[4] := XPos;
XPos := Approximation(FXPosInfo);
Move(FYPosInfo[1], FYPosInfo[0], 16);
FYPosInfo[4] := YPos;
YPos := Approximation(FYPosInfo);
MakeJoyButtons(Buttons);
dX := Round((XPos-FMinMaxInfo[jaX, jpCenter]) * 100 / FMinMaxInfo[jaX, jpCenter]);
dY := Round((YPos-FMinMaxInfo[jaY, jpCenter]) * 100 / FMinMaxInfo[jaY, jpCenter]);
if Assigned(FOnJoystickMove) then
FOnJoystickMove(Self, FJoystickID, FJoyButtons, dX, dY);
FXPosition:=dX;
FYPosition:=dY;
FLastX:=XPos;
FLastY:=YPos;
end;
end;
// DoZMove
//
procedure TGLJoystick.DoZMove(Buttons: Word; ZPos: Integer);
begin
if FLastZ = -1 then
FLastZ := Round(ZPos * 100 / 65536);
MakeJoyButtons(Buttons);
end;
initialization
RegisterClasses([TGLJoystick]);
end.
|
{
This unit is part of the Lua4Delphi Source Code
Copyright (C) 2009-2012, LaKraven Studios Ltd.
Copyright Protection Packet(s): L4D014
www.Lua4Delphi.com
www.LaKraven.com
--------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and
limitations under the License.
--------------------------------------------------------------------
Unit: L4D.Lua.Constants.pas
Released: 5th February 2012
Changelog:
5th February 2012:
- Released
}
unit L4D.Lua.Constants;
interface
uses
L4D.Lua.Common, L4D.Lua.Intf;
const
{$IFDEF MSWINDOWS}
{$REGION 'Lua Lib Common External Method Names'}
LUA_lua_atpanic = 'lua_atpanic';
LUA_lua_call = 'lua_call';
LUA_lua_checkstack = 'lua_checkstack';
LUA_lua_close = 'lua_close';
LUA_lua_concat = 'lua_concat';
LUA_lua_createtable = 'lua_createtable';
LUA_lua_dump = 'lua_dump';
LUA_lua_error = 'lua_error';
LUA_lua_gc = 'lua_gc';
LUA_lua_getallocf = 'lua_getallocf';
LUA_lua_getfield = 'lua_getfield';
LUA_lua_gethook = 'lua_gethook';
LUA_lua_gethookcount = 'lua_gethookcount';
LUA_lua_gethookmask = 'lua_gethookmask';
LUA_lua_getinfo = 'lua_getinfo';
LUA_lua_getlocal = 'lua_getlocal';
LUA_lua_getmetatable = 'lua_getmetatable';
LUA_lua_getstack = 'lua_getstack';
LUA_lua_gettable = 'lua_gettable';
LUA_lua_gettop = 'lua_gettop';
LUA_lua_getupvalue = 'lua_getupvalue';
LUA_lua_insert = 'lua_insert';
LUA_lua_iscfunction = 'lua_iscfunction';
LUA_lua_isnumber = 'lua_isnumber';
LUA_lua_isstring = 'lua_isstring';
LUA_lua_isuserdata = 'lua_isuserdata';
LUA_lua_load = 'lua_load';
LUA_lua_newthread = 'lua_newthread';
LUA_lua_newstate = 'lua_newstate';
LUA_lua_newuserdata = 'lua_newuserdata';
LUA_lua_next = 'lua_next';
LUA_lua_pcall = 'lua_pcall';
LUA_lua_pushboolean = 'lua_pushboolean';
LUA_lua_pushcclosure = 'lua_pushcclosure';
LUA_lua_pushfstring = 'lua_pushfstring';
LUA_lua_pushinteger = 'lua_pushinteger';
LUA_lua_pushlightuserdata = 'lua_pushlightuserdata';
LUA_lua_pushlstring = 'lua_pushlstring';
LUA_lua_pushnil = 'lua_pushnil';
LUA_lua_pushnumber = 'lua_pushnumber';
LUA_lua_pushstring = 'lua_pushstring';
LUA_lua_pushthread = 'lua_pushthread';
LUA_lua_pushvalue = 'lua_pushvalue';
LUA_lua_pushvfstring = 'lua_pushvfstring';
LUA_lua_rawequal = 'lua_rawequal';
LUA_lua_rawget = 'lua_rawget';
LUA_lua_rawgeti = 'lua_rawgeti';
LUA_lua_rawset = 'lua_rawset';
LUA_lua_rawseti = 'lua_rawseti';
LUA_lua_remove = 'lua_remove';
LUA_lua_replace = 'lua_replace';
LUA_lua_resume = 'lua_resume';
LUA_lua_setallocf = 'lua_setallocf';
LUA_lua_setfield = 'lua_setfield';
LUA_lua_sethook = 'lua_sethook';
LUA_lua_setlocal = 'lua_setlocal';
LUA_lua_setmetatable = 'lua_setmetatable';
LUA_lua_settable = 'lua_settable';
LUA_lua_settop = 'lua_settop';
LUA_lua_setupvalue = 'lua_setupvalue';
LUA_lua_status = 'lua_status';
LUA_lua_toboolean = 'lua_toboolean';
LUA_lua_tocfunction = 'lua_tocfunction';
LUA_lua_tointeger = 'lua_tointeger';
LUA_lua_tolstring = 'lua_tolstring';
LUA_lua_tonumber = 'lua_tonumber';
LUA_lua_topointer = 'lua_topointer';
LUA_lua_tothread = 'lua_tothread';
LUA_lua_touserdata = 'lua_touserdata';
LUA_lua_type = 'lua_type';
LUA_lua_typename = 'lua_typename';
LUA_lua_xmove = 'lua_xmove';
LUA_lua_yield = 'lua_yield';
LUA_luaopen_base = 'luaopen_base';
LUA_luaopen_debug = 'luaopen_debug';
LUA_luaopen_io = 'luaopen_io';
LUA_luaopen_math = 'luaopen_math';
LUA_luaopen_os = 'luaopen_os';
LUA_luaopen_package = 'luaopen_package';
LUA_luaopen_string = 'luaopen_string';
LUA_luaopen_table = 'luaopen_table';
{$ENDREGION}
{$REGION 'Lua Auxiliary Common External Method Names'}
LUA_luaL_addlstring = 'luaL_addlstring';
LUA_luaL_addstring = 'luaL_addstring';
LUA_luaL_addvalue = 'luaL_addvalue';
LUA_luaL_argerror = 'luaL_argerror';
LUA_luaL_buffinit = 'luaL_buffinit';
LUA_luaL_callmeta = 'luaL_callmeta';
LUA_luaL_checkany = 'luaL_checkany';
LUA_luaL_checkinteger = 'luaL_checkinteger';
LUA_luaL_checklstring = 'luaL_checklstring';
LUA_luaL_checknumber = 'luaL_checknumber';
LUA_luaL_checkoption = 'luaL_checkoption';
LUA_luaL_checkstack = 'luaL_checkstack';
LUA_luaL_checktype = 'luaL_checktype';
LUA_luaL_checkudata = 'luaL_checkudata';
LUA_luaL_error = 'luaL_error';
LUA_luaL_getmetafield = 'luaL_getmetafield';
LUA_luaL_gsub = 'luaL_gsub';
LUA_luaL_loadbuffer = 'luaL_loadbuffer';
LUA_luaL_loadfile = 'luaL_loadfile';
LUA_luaL_loadstring = 'luaL_loadstring';
LUA_luaL_newmetatable = 'luaL_newmetatable';
LUA_luaL_newstate = 'luaL_newstate';
LUA_luaL_openlib = 'luaL_openlib';
LUA_luaL_openlibs = 'luaL_openlibs';
LUA_luaL_optinteger = 'luaL_optinteger';
LUA_luaL_optlstring = 'luaL_optlstring';
LUA_luaL_optnumber = 'luaL_optnumber';
LUA_luaL_prepbuffer = 'luaL_prepbuffer';
LUA_luaL_pushresult = 'luaL_pushresult';
LUA_luaL_ref = 'luaL_ref';
LUA_luaL_register = 'luaL_register';
LUA_luaL_unref = 'luaL_unref';
LUA_luaL_where = 'luaL_where';
{$ENDREGION}
{$ELSE}
{$REGION 'Lua Lib Common External Method Names'}
LUA_lua_atpanic = '_lua_atpanic';
LUA_lua_call = '_lua_call';
LUA_lua_checkstack = '_lua_checkstack';
LUA_lua_close = '_lua_close';
LUA_lua_concat = '_lua_concat';
LUA_lua_createtable = '_lua_createtable';
LUA_lua_dump = '_lua_dump';
LUA_lua_error = '_lua_error';
LUA_lua_gc = '_lua_gc';
LUA_lua_getallocf = '_lua_getallocf';
LUA_lua_getfield = '_lua_getfield';
LUA_lua_gethook = '_lua_gethook';
LUA_lua_gethookcount = '_lua_gethookcount';
LUA_lua_gethookmask = '_lua_gethookmask';
LUA_lua_getinfo = '_lua_getinfo';
LUA_lua_getlocal = '_lua_getlocal';
LUA_lua_getmetatable = '_lua_getmetatable';
LUA_lua_getstack = '_lua_getstack';
LUA_lua_gettable = '_lua_gettable';
LUA_lua_gettop = '_lua_gettop';
LUA_lua_getupvalue = '_lua_getupvalue';
LUA_lua_insert = '_lua_insert';
LUA_lua_iscfunction = '_lua_iscfunction';
LUA_lua_isnumber = '_lua_isnumber';
LUA_lua_isstring = '_lua_isstring';
LUA_lua_isuserdata = '_lua_isuserdata';
LUA_lua_load = '_lua_load';
LUA_lua_newthread = '_lua_newthread';
LUA_lua_newstate = '_lua_newstate';
LUA_lua_newuserdata = '_lua_newuserdata';
LUA_lua_next = '_lua_next';
LUA_lua_pcall = '_lua_pcall';
LUA_lua_pushboolean = '_lua_pushboolean';
LUA_lua_pushcclosure = '_lua_pushcclosure';
LUA_lua_pushcclosure = '_lua_pushcclosure';
LUA_lua_pushfstring = '_lua_pushfstring';
LUA_lua_pushinteger = '_lua_pushinteger';
LUA_lua_pushlightuserdata = '_lua_pushlightuserdata';
LUA_lua_pushlstring = '_lua_pushlstring';
LUA_lua_pushnil = '_lua_pushnil';
LUA_lua_pushnumber = '_lua_pushnumber';
LUA_lua_pushstring = 'lua_pushstring';
LUA_lua_pushthread = '_lua_pushthread';
LUA_lua_pushvalue = '_lua_pushvalue';
LUA_lua_pushvfstring = '_lua_pushvfstring';
LUA_lua_rawequal = '_lua_rawequal';
LUA_lua_rawget = '_lua_rawget';
LUA_lua_rawgeti = '_lua_rawgeti';
LUA_lua_rawset = '_lua_rawset';
LUA_lua_rawseti = '_lua_rawseti';
LUA_lua_remove = '_lua_remove';
LUA_lua_replace = '_lua_replace';
LUA_lua_resume = '_lua_resume';
LUA_lua_setallocf = '_lua_setallocf';
LUA_lua_setfield = '_lua_setfield';
LUA_lua_sethook = '_lua_sethook';
LUA_lua_setlocal = '_lua_setlocal';
LUA_lua_setmetatable = '_lua_setmetatable';
LUA_lua_settable = '_lua_settable';
LUA_lua_settop = '_lua_settop';
LUA_lua_setupvalue = '_lua_setupvalue';
LUA_lua_status = '_lua_status';
LUA_lua_toboolean = '_lua_toboolean';
LUA_lua_tocfunction = '_lua_tocfunction';
LUA_lua_tointeger = '_lua_tointeger';
LUA_lua_tolstring = '_lua_tolstring';
LUA_lua_tonumber = '_lua_tonumber';
LUA_lua_topointer = '_lua_topointer';
LUA_lua_tothread = '_lua_tothread';
LUA_lua_touserdata = '_lua_touserdata';
LUA_lua_type = '_lua_type';
LUA_lua_typename = '_lua_typename';
LUA_lua_xmove = '_lua_xmove';
LUA_lua_yield = '_lua_yield';
LUA_luaopen_base = '_luaopen_base';
LUA_luaopen_debug = '_luaopen_debug';
LUA_luaopen_io = '_luaopen_io';
LUA_luaopen_math = '_luaopen_math';
LUA_luaopen_os = '_luaopen_os';
LUA_luaopen_package = '_luaopen_package';
LUA_luaopen_string = '_luaopen_string';
LUA_luaopen_table = '_luaopen_table';
{$ENDREGION}
{$REGION 'Lua Auxiliary Common External Method Names'}
LUA_luaL_addlstring = '_luaL_addlstring';
LUA_luaL_addstring = '_luaL_addstring';
LUA_luaL_addvalue = '_luaL_addvalue';
LUA_luaL_argerror = '_luaL_argerror';
LUA_luaL_buffinit = '_luaL_buffinit';
LUA_luaL_callmeta = '_luaL_callmeta';
LUA_luaL_checkany = '_luaL_checkany';
LUA_luaL_checkinteger = '_luaL_checkinteger';
LUA_luaL_checklstring = '_luaL_checklstring';
LUA_luaL_checknumber = '_luaL_checknumber';
LUA_luaL_checkoption = '_luaL_checkoption';
LUA_luaL_checkstack = '_luaL_checkstack';
LUA_luaL_checktype = '_luaL_checktype';
LUA_luaL_checkudata = '_luaL_checkudata';
LUA_luaL_error = '_luaL_error';
LUA_luaL_getmetafield = '_luaL_getmetafield';
LUA_luaL_gsub = '_luaL_gsub';
LUA_luaL_loadbuffer = '_luaL_loadbuffer';
LUA_luaL_loadfile = '_luaL_loadfile';
LUA_luaL_loadstring = '_luaL_loadstring';
LUA_luaL_newmetatable = '_luaL_newmetatable';
LUA_luaL_newstate = '_luaL_newstate';
LUA_luaL_openlib = '_luaL_openlib';
LUA_luaL_openlibs = '_luaL_openlibs';
LUA_luaL_optinteger = '_luaL_optinteger';
LUA_luaL_optlstring = '_luaL_optlstring';
LUA_luaL_optnumber = '_luaL_optnumber';
LUA_luaL_prepbuffer = '_luaL_prepbuffer';
LUA_luaL_pushresult = '_luaL_pushresult';
LUA_luaL_ref = '_luaL_ref';
LUA_luaL_register = '_luaL_register';
LUA_luaL_unref = '_luaL_unref';
LUA_luaL_where = '_luaL_where';
{$ENDREGION}
{$ENDIF}
implementation
end.
|
unit ReadProgram;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ShellApi,Registry;
type
TReadProgramX = class(TForm)
Label1: TLabel;
Label2: TLabel;
Panel1: TPanel;
Button2: TButton;
Button3: TButton;
Panel2: TPanel;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
WIn32or64 : Boolean;
procedure DetectFileInstaler;
procedure WriteRegistry;
end;
var
ReadProgramX: TReadProgramX;
win32, win64, win3264, AppPath : String;
implementation
function IsWindows64: Boolean;
type
TIsWow64Process = function(AHandle:THandle; var AIsWow64: BOOL): BOOL; stdcall;
var
vKernel32Handle: DWORD;
vIsWow64Process: TIsWow64Process;
vIsWow64 : BOOL;
begin
// 1) assume that we are not running under Windows 64 bit
Result := False;
// 2) Load kernel32.dll library
vKernel32Handle := LoadLibrary('kernel32.dll');
if (vKernel32Handle = 0) then Exit; // Loading kernel32.dll was failed, just return
try
// 3) Load windows api IsWow64Process
@vIsWow64Process := GetProcAddress(vKernel32Handle, 'IsWow64Process');
if not Assigned(vIsWow64Process) then Exit; // Loading IsWow64Process was failed, just return
// 4) Execute IsWow64Process against our own process
vIsWow64 := False;
if (vIsWow64Process(GetCurrentProcess, vIsWow64)) then
Result := vIsWow64; // use the returned value
finally
FreeLibrary(vKernel32Handle); // unload the library
end;
end;
{$R *.dfm}
procedure RunShellInstaler(const AppDir , prog : string; index : integer);
var
StartupInfo: TStartupInfo;
ProcessInformation: TProcessInformation;
Handle: HWnd;
AppProgX : String;
begin
if DirectoryExists(AppDir) then begin
if FileExists(AppDir + prog) then begin
AppProgX := Prog;
FillChar(StartupInfo, SizeOf(StartupInfo), 0);
with StartupInfo do begin
cb := SizeOf(TStartupInfo);
wShowWindow := SW_HIDE;
end;
if CreateProcess(nil, PChar('CMD.exe /C' + trim(prog)),nil, nil, true, CREATE_NO_WINDOW,
nil, PChar(AppDir) , StartupInfo, ProcessInformation) then
begin
while WaitForSingleObject(ProcessInformation.hProcess, 10) > 0 do begin
Application.ProcessMessages;
// if MainForm.AktifMsg = index then MessageToTray('Start '+AppProgX);
// MainForm.FormTray();
end;
CloseHandle(ProcessInformation.hProcess);
CloseHandle(ProcessInformation.hThread);
// MainForm.AktifMsg := 0; MessageToTray('Close '+AppProgX);
if index = 1 then ReadProgramX.DetectFileInstaler;;
end else begin
end;
end else begin
ShellExecute(Handle, 'OPEN',PChar('explorer.exe'),
PChar('/OPEN, "'+ AppDir +'"'), nil,SW_NORMAL);
end;
end else begin
if CreateDir( AppDir ) then
ShellExecute(Handle, 'OPEN',PChar('explorer.exe'),
PChar('/OPEN, "'+ AppDir +'"'), nil,SW_NORMAL);
end;
end;
procedure TReadProgramX.FormCreate(Sender: TObject);
begin
AppPath := ExtractFilePath(Application.ExeName);
win32 := 'C:\Program Files\';
Win64 := 'C:\Program Files (x86)\';
if DirectoryExists(win32) or DirectoryExists(win64) then begin
if IsWindows64 = true then
win3264 := Win64
else
win3264 := Win32;
end;
end;
procedure TReadProgramX.Button1Click(Sender: TObject);
begin
DetectFileInstaler;
end;
procedure TReadProgramX.DetectFileInstaler;
begin
if (DirectoryExists(win3264+ 'Bitvise SSH Client\')) and
(FileExists(win3264+ 'Bitvise SSH Client\BvSsh.exe')) then begin
Panel1.Color := ClRed;
if (DirectoryExists(win3264+ 'Proxifier\')) and
(FileExists(win3264+ 'Proxifier\Proxifier.exe')) then begin
{run Program start}
ReadProgramX.WriteRegistry;
end else begin
RunShellInstaler(AppPath+'Files\' , 'ProxifierSetup.exe', 1);
Label2.Caption := (win3264)+ #13#10'Instaling ProxifierSetup.exe';
end;
end else begin
Label1.Caption := (win3264)+ #13#10'Instaling BvSshClient4.63.exe';
RunShellInstaler(AppPath+'Files\' , 'BvSshClient4.63.exe', 1);
end;
end;
procedure TReadProgramX.WriteRegistry;
Var
Reg : Tregistry ;
regKey : DWORD;
Key : String;
begin
Reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
Key := 'Software\Initex\Proxifier\License';
if Reg.OpenKey(key, true) then Begin
Reg.WriteString('Owner','MFC NetWork') ;
Reg.WriteString('Key','T3ZWQ-P2738-3FJWS-YE7HT-6NA3K') ;
Reg.CloseKey;
ShowMessage('Sukses')
end;
Finally
Reg.Free;
end;
end;
procedure TReadProgramX.Button2Click(Sender: TObject);
Var
Reg : Tregistry ;
regKey : DWORD;
Key : String;
begin
Reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
Key := 'Software\Initex\Proxifier\License';
if Reg.OpenKeyReadOnly(Key) then Begin
if Reg.ValueExists('Owner') then begin
label1.Caption := Reg.ReadString('Owner') ;
end;
if Reg.ValueExists('Key') then begin
label2.Caption := Reg.ReadString('Key')
end;
Reg.CloseKey;
end;
Finally
Reg.Free;
end;
end;
procedure TReadProgramX.Button3Click(Sender: TObject);
Var
Reg : Tregistry ;
regKey : DWORD;
Key : String;
begin
Reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
Key := 'Software\Initex\Proxifier\License';
if Reg.OpenKey(key, true) then Begin
Reg.WriteString('Owner','MFC NetWork') ;
Reg.WriteString('Key','T3ZWQ-P2738-3FJWS-YE7HT-6NA3K') ;
Reg.CloseKey;
ShowMessage('Sukses')
end;
Finally
Reg.Free;
end;
end;
end.
|
unit FDConnectionHelper;
interface
uses
classes, SysUtils, Data.DB, NGFDMemTable, DBXJSON, Variants,
FireDAC.Stan.Intf, FireDAC.Phys, FireDAC.Comp.Client, FireDac.Stan.Param,
FireDAC.UI.Intf, FireDAC.ConsoleUI.Wait, FireDAC.Comp.UI,
{$IFDEF SQLServerDriver}
FireDAC.Phys.MSSQLDef, FireDAC.Phys.ODBCBase, FireDAC.Phys.MSSQL,
{$ENDIF}
{$IFDEF SQLiteDriver}
FireDAC.Stan.ExprFuncs, FireDAC.Phys.SQLiteDef, FireDAC.Phys.SQLite,
{$ENDIF}
UIRestore, DataSetHelper, ParamsHelper, uGlobal;
ResourceString
RS_InvalidNumberOfParams = 'Invalid number of parameters(%d). Expected(%d)';
type
TFDConnectionHelper = class helper for TFDConnection
private
public
procedure LogIt(lstLogs: TStringList; s : string);
function CreateQuery : TFDQuery;
function GetQueryTextTable(const TableName, TableAlias, WhereAnd, KeyFields, OrderBy : string) : string;
procedure CreateFieldInfoCDS(ds: TDataSet; cdsMapping: TNGFDMemTable);
function TextToListText(s: string): string;
function KeyFieldsToWhereAnd(TableAlias, KeyFields : string): string;
function AddFieldBrackets(FieldName: string): string;
function FieldToParam(FieldName: string): string;
procedure SetSQLServerConnectionString(const HostName, DBName,
UserName, Password: string;
OSAuthentication : Boolean);
procedure SetAccessConnectionString(const UserName, Password, FileName: string);
procedure SetExcelConnectionString(const FileName : string);
procedure SetSQLiteConnectionString(const FileName : string);
procedure AssignQueryParams(cds : TNGFDMemTable; qry : TFDQuery);
procedure AssignParamValues(qry: TFDQuery; cds, cdsMapping: TNGFDMemTable);
procedure AssignFieldValues(qry: TFDQuery; cds: TNGFDMemTable);
procedure PrepareQuery(qry: TFDQuery; const SQL: string; Params: TParams);
function DSOpenSQL(const SQL : string; Params : TParams) : TFDQuery;
procedure ExecSQL(const SQL : string; Params : TParams);
function OpenSQL(const SQL : string; Params : TParams;
var XmlData: string) : Boolean;
procedure ApplyUpdates(const XmlData, InsertSQL, UpdateSQL, DeleteSQL : string);
procedure ApplyUpdatesByTable(const TableName, TableAlias,
WhereAnd, KeyFields, XMLData : string);
procedure ApplyUpdatesByQuery(const SQL, XMLData : string;
Params : TParams; lstLogs : TStringList);
function KeyFieldsValue(DataSet: TDataSet; KeyFields: string;
lstLogs : TStringList): Variant;
function GetFieldNames(DataSet: TDataSet; Separator: string;
IgnoreNulls : Boolean): string;
function CheckTableAndField(const s : string): Boolean;
end;
implementation
var
iCount : Integer;
function TFDConnectionHelper.DSOpenSQL(const SQL: string;
Params: TParams): TFDQuery;
begin
Result := CreateQuery;
PrepareQuery(Result, SQL, Params);
Result.Open;
end;
procedure TFDConnectionHelper.ExecSQL(const SQL: string; Params: TParams);
var
qry : TFDQuery; iqry : IObjCleaner;
begin
qry := TFDQuery.Create(nil); iqry := CreateObjCleaner(qry);
PrepareQuery(qry, SQL, Params);
qry.ExecSQL;
end;
function TFDConnectionHelper.FieldToParam(FieldName: string): string;
begin
Result := StringReplace(FieldName, ' ', '_', [rfReplaceAll]);
Result := StringReplace(Result, '/', '_', [rfReplaceAll]);
Result := StringReplace(Result, '?', '_', [rfReplaceAll]);
Result := StringReplace(Result, '-', '_', [rfReplaceAll]);
end;
function TFDConnectionHelper.GetFieldNames(DataSet: TDataSet; Separator: string;
IgnoreNulls: Boolean): string;
var
i : Integer;
begin
Result := '';
if not (Assigned(DataSet) and DataSet.Active) then
exit;
for i := 0 to DataSet.FieldCount - 1 do
begin
if IgnoreNulls and DataSet.Fields[i].isnull then
continue;
if Result > '' then
Result := Result + Separator;
Result := Result + DataSet.Fields[i].FieldName;
end;
end;
function TFDConnectionHelper.GetQueryTextTable(const TableName, TableAlias,
WhereAnd, KeyFields, OrderBy: string): string;
begin
CheckFalseFmt(TableName > ' ', Err_InvalidPointerInCodeRef, ['TableName', 'TFDConnectionHelper.GetQueryTextTable']);
// select * from
Result := Format('select * from [%s] ', [TableName]);
if TableAlias > ' ' then
Result := Result + ' ' + TableAlias;
Result := Result + #13#10' where 1 = 1';
if KeyFields > ' ' then
Result := Result + #13#10 + KeyFieldsToWhereAnd(TableAlias, KeyFields);
// WhereAnd
if WhereAnd > ' ' then
begin
if LowerCase(copy(WhereAnd, 1, 3)) <> 'and' then
Result := Result + #13#10'and ' + WhereAnd + ' '
else
Result := Result + #13#10 + WhereAnd + ' ';
end;
// OrderBy
if OrderBy > ' ' then
Result := Result + #13#10' order by ' + OrderBy;
end;
function TFDConnectionHelper.KeyFieldsToWhereAnd(TableAlias, KeyFields: string): string;
var
lstKeyFields : IGObjCleaner<TStringList>;
i : Integer;
Alias : string;
begin
Result := '';
if KeyFields <= ' ' then
exit;
lstKeyFields := TGObjCleaner<TStringList>.Create(TStringList.Create);
lstKeyFields.Obj.Text := TextToListText(KeyFields);
if TableAlias > ' ' then
Alias := TableAlias + '.'
else
Alias := '';
for i := 0 to lstKeyFields.Obj.Count - 1 do
Result := Result + #13#10' and ' + Alias + AddFieldBrackets(lstKeyFields.Obj[i]) +
' = :' + FieldToParam(lstKeyFields.Obj[i]);
end;
function TFDConnectionHelper.KeyFieldsValue(DataSet: TDataSet; KeyFields: string;
lstLogs : TStringList): Variant;
var
lst : IGObjCleaner<TStringList>;
i : Integer;
begin
Result := Unassigned;
if not (Assigned(DataSet) and DataSet.Active and (not DataSet.EOF)) then
exit;
if (pos(',', KeyFields) <= 0) then
begin
Result := DataSet.FieldByName(KeyFields).AsWideString;
end
else
begin
lst := TGObjCleaner<TStringList>.Create(TStringList.Create);
lst.Obj.Text := StringReplace(KeyFields, ',', #13#10, [rfReplaceAll]);
Result := VarArrayCreate([0, lst.Obj.Count-1], varVariant);
for i := 0 to lst.Obj.count - 1 do
Result[i] := DataSet.FieldByName(lst.Obj[i]).asWideString;
end;
end;
procedure TFDConnectionHelper.LogIt(lstLogs : TStringList; s: string);
begin
if not Assigned(lstLogs) then
exit;
lstLogs.add(s);
end;
function TFDConnectionHelper.OpenSQL(const SQL: string; Params: TParams;
var XmlData : string): Boolean;
var
cds : IGObjCleaner<TNGFDMemTable>;
qry : IGObjCleaner<TFDQuery>;
begin
qry := TGObjCleaner<TFDQuery>.Create(CreateQuery);
cds := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
PrepareQuery(qry.Obj, SQL, Params);
qry.Obj.Open;
cds.Obj.CopyFieldDefs(qry.Obj);
cds.Obj.Open;
cds.Obj.CopyDataSet(qry.Obj);
cds.Obj.MergeChangeLog;
XmlData := cds.Obj.XMLData;
cds := nil;
result := (XmlData <> '');
end;
procedure TFDConnectionHelper.PrepareQuery(qry: TFDQuery;
const SQL: string; Params: TParams);
var
i : Integer;
p : TParam;
begin
if not Assigned(qry) then
exit;
qry.SQL.Text := SQL;
if not Assigned(params) then
exit;
for i := 0 to qry.Params.Count - 1 do
begin
p := Params.FindParam(qry.Params[i].Name);
if not assigned(p) then
continue;
if p.DataType = ftBlob then
TBlobField(qry.Params[i]).Assign(p)
else
qry.Params[i].Value := p.Value;
end;
end;
procedure TFDConnectionHelper.SetAccessConnectionString(const UserName,
Password, FileName: string);
begin
end;
procedure TFDConnectionHelper.SetExcelConnectionString(const FileName: string);
begin
end;
procedure TFDConnectionHelper.SetSQLiteConnectionString(const FileName: string);
begin
Params.Values['DriverID'] := 'SQLite';
Params.Values['Database'] := FileName;
end;
procedure TFDConnectionHelper.SetSQLServerConnectionString(const HostName,
DBName, UserName, Password: string;
OSAuthentication: Boolean);
begin
Params.Values['DriverID'] := 'MSSQL';
Params.Values['SERVER'] := HostName;
Params.Values['Database'] := DBName;
Params.Values['User_Name'] := UserName;
Params.Values['Password'] := Password;
if OSAuthentication then
Params.Values['OSAuthent'] := 'YES'
else
Params.Values['OSAuthent'] := 'NO';
end;
function TFDConnectionHelper.TextToListText(s: string): string;
begin
Result := StringReplace(StringReplace(s, ', ', '', [rfReplaceAll]),
',', #13#10, [rfReplaceAll]);
end;
{ TFDConnectionHelper }
function TFDConnectionHelper.AddFieldBrackets(FieldName: string): string;
begin
Result := FieldName;
if FieldName <= ' ' then
exit;
if Result[1] <> '[' then
Result := '[' + Result;
if Result[length(Result)] <> ']' then
Result := Result + ']';
end;
procedure TFDConnectionHelper.ApplyUpdates(const XmlData, InsertSQL,
UpdateSQL, DeleteSQL: string);
var
cds, cds2 : IGObjCleaner<TNGFDMemTable>;
qry : IGObjCleaner<TFDQuery>;
sFieldName : string;
i : Integer;
begin
cds := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
cds2 := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
qry := TGObjCleaner<TFDQuery>.Create(CreateQuery);
qry.Obj.SQL.Text := InsertSQL;
cds.Obj.XMLData := XmlData;
cds.Obj.Open;
cds2.Obj.CloneCursor(cds.Obj, True, True);
cds.Obj.First;
while not cds.Obj.Eof do
begin
if (cds.Obj.UpdateStatus = usInserted) then
begin
qry.Obj.SQL.Text := InsertSQL;
qry.Obj.Open;
qry.Obj.Insert;
qry.Obj.CopyRecord(cds.Obj);
qry.Obj.Post;
end
else if cds.Obj.UpdateStatus = usDeleted then
begin
qry.Obj.SQL.Text := DeleteSQL;
AssignQueryParams(cds.Obj, qry.Obj);
Qry.Obj.ExecSQL;
end
else if cds.Obj.UpdateStatus = usModified then
begin
cds2.Obj.RecNo := cds.Obj.RecNo-1;
Qry.Obj.SQL.Text := UpdateSQL;
AssignQueryParams(cds.Obj, qry.Obj);
Qry.Obj.Open;
if not qry.Obj.EOF then
begin
qry.Obj.Edit;
for i := 0 to cds.Obj.FieldCount - 1 do
begin
if (cds.Obj.Fields[i].Value = cds2.Obj.Fields[i].Value) then
continue;
sFieldName := cds.Obj.Fields[i].FieldName;
if qry.Obj.FindField(sFieldName) = nil then
continue;
if not cds.Obj.Fields[i].IsNull then
qry.Obj.FieldByName(sFieldName).Value := cds.Obj.Fields[i].Value;
end;
qry.Obj.Post;
end;
end;
cds.Obj.Next;
end;
end;
procedure TFDConnectionHelper.ApplyUpdatesByQuery(const SQL, XMLData: string;
Params: TParams; lstLogs : TStringList);
var
qry : IGObjCleaner<TFDQuery>;
cdsDelta, cdsDelta2 : IGObjCleaner<TNGFDMemTable>;
SearchRecord : Variant;
SearchFields : string;
begin
// Create Vars
qry := TGObjCleaner<TFDQuery>.Create(CreateQuery);
cdsDelta := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
cdsDelta2 := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
PrepareQuery(qry.Obj, SQL, Params);
qry.Obj.Open;
cdsDelta.Obj.XMLData := XmlData;
cdsDelta.Obj.Open;
cdsDelta2.Obj.CloneCursor(cdsDelta.Obj, True, False);
cdsDelta.Obj.First;
while not cdsDelta.Obj.EOF do
begin
if cdsDelta.Obj.UpdateStatus = TUpdateStatus.usModified then
begin
LogIt(lstLogs, 'ApplyUpdatesByQuery: usModified');
cdsDelta2.Obj.RecNo := cdsDelta.Obj.RecNo - 1;
SearchFields := GetFieldNames(TDataSet(cdsDelta2.Obj), ',', True);
SearchRecord := KeyFieldsValue(TDataSet(cdsDelta2.Obj), SearchFields, lstLogs);
LogIt(lstLogs, 'ApplyUpdatesByQuery 5.11 - SearchField = ' + SearchFields);
if qry.Obj.Locate(SearchFields, SearchRecord, []) then
begin
LogIt(lstLogs, 'ApplyUpdatesByQuery 5.121');
qry.Obj.Edit;
AssignFieldValues(qry.Obj, cdsDelta.Obj);
qry.Obj.Post;
LogIt(lstLogs, 'ApplyUpdatesByQuery 5.122');
end;
LogIt(lstLogs, 'ApplyUpdatesByQuery 5.13');
end
else if cdsDelta.Obj.UpdateStatus = TUpdateStatus.usInserted then
begin
LogIt(lstLogs, 'ApplyUpdatesByQuery: usInserted');
exit;
qry.Obj.Append;
AssignFieldValues(qry.Obj, cdsDelta.Obj);
qry.Obj.Post;
end
else if cdsDelta.Obj.UpdateStatus = TUpdateStatus.usDeleted then
begin
LogIt(lstLogs, 'ApplyUpdatesByQuery: usDeleted');
exit;
SearchFields := GetFieldNames(TDataSet(cdsDelta.Obj), ',', True);
SearchRecord := KeyFieldsValue(TDataSet(cdsDelta.Obj), SearchFields, lstLogs);
while qry.Obj.Locate(SearchFields, SearchRecord, []) do
qry.Obj.Delete;
end;
LogIt(lstLogs, 'ApplyUpdatesByQuery: Next');
cdsDelta.Obj.Next;
end;
end;
procedure TFDConnectionHelper.ApplyUpdatesByTable(const TableName, TableAlias,
WhereAnd, KeyFields, XMLData: string);
var
qry : IGObjCleaner<TFDQuery>;
cdsDelta, cdsDelta2, cdsMapping : IGObjCleaner<TNGFDMemTable>;
begin
// Create Vars
cdsDelta := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
cdsDelta2 := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
cdsMapping := TGObjCleaner<TNGFDMemTable>.Create(TNGFDMemTable.Create(nil));
qry := TGObjCleaner<TFDQuery>.Create(CreateQuery);
qry.Obj.SQL.Text := GetQueryTextTable(TableName, TableAlias, WhereAnd, KeyFields, '');
cdsDelta.Obj.XMLData := XmlData;
cdsDelta.Obj.Open;
cdsDelta2.Obj.CloneCursor(cdsDelta.Obj, True, False);
CreateFieldInfoCDS(cdsDelta.Obj, cdsMapping.Obj);
cdsDelta.Obj.First;
cdsDelta.Obj.ForEachRecord(nil,
procedure (ds : TDataSet)
begin
if cdsDelta.Obj.UpdateStatus = TUpdateStatus.usModified then
begin
cdsDelta2.Obj.RecNo := cdsDelta.Obj.RecNo - 1;
AssignParamValues(qry.Obj, cdsDelta2.Obj, cdsMapping.Obj);
qry.Obj.Open;
if not qry.Obj.EOF then
begin
qry.Obj.Edit;
AssignFieldValues(qry.Obj, cdsDelta.Obj);
qry.Obj.Post;
end;
end
else if cdsDelta.Obj.UpdateStatus = TUpdateStatus.usInserted then
begin
AssignParamValues(qry.Obj, cdsDelta.Obj, cdsMapping.Obj);
qry.Obj.Open;
qry.Obj.Append;
AssignFieldValues(qry.Obj, cdsDelta.Obj);
qry.Obj.Post;
//AssignAutoIDValues(qry.Obj, cds., cdsDelta);
end
else if cdsDelta.Obj.UpdateStatus = TUpdateStatus.usDeleted then
begin
AssignParamValues(qry.Obj, cdsDelta.Obj, cdsMapping.Obj);
qry.Obj.Open;
while not qry.Obj.EOF do
qry.Obj.Delete;
end
end
);
end;
procedure TFDConnectionHelper.AssignFieldValues(qry: TFDQuery; cds: TNGFDMemTable);
begin
CheckFalseFmt(Assigned(qry) and qry.Active,
Err_InvalidPointerInCodeRef,
['qry', 'TFDConnectionHelper.AssignFieldValues']);
CheckFalseFmt(Assigned(cds),
Err_InvalidPointerInCodeRef,
['cds', 'TFDConnectionHelper.AssignFieldValues']);
cds.ForEachField(
function (Field: TField) : Boolean
begin
Result := (qry.FindField(Field.FieldName) <> nil)
and ((not Field.IsNull) or (Field.NewValue <> Unassigned))
and (not qry.FieldByName(Field.FieldName).ReadOnly)
and (qry.FieldByName(Field.FieldName).DataType <> ftAutoInc);
end,
procedure (Field: TField)
begin
if Field.IsBlob then
TBlobField(qry.FieldByName(Field.FieldName)).Assign(Field)
else if Field.DataType <> ftAutoInc then
qry.FieldByName(Field.FieldName).Value := Field.Value;
end,
nil
);
end;
procedure TFDConnectionHelper.AssignParamValues(qry: TFDQuery; cds, cdsMapping: TNGFDMemTable);
var
i : Integer;
QryParam : TFDParam;
begin
for i := 0 to qry.ParamCount - 1 do
begin
QryParam := qry.Params[i];
if cdsMapping.Locate('ParamName', QryParam.Name, [loCaseInsensitive]) then
QryParam.Value := cds.Fields[cdsMapping.FieldByName('FieldIndex').AsInteger].Value;
end;
end;
procedure TFDConnectionHelper.AssignQueryParams(cds: TNGFDMemTable;
qry: TFDQuery);
var
i : Integer;
f : TField;
begin
for i := 0 to qry.ParamCount - 1 do
begin
f := cds.FindField(qry.Params[i].Name);
if f <> nil then
qry.Params[i].Value := f.Value;
end;
end;
function TFDConnectionHelper.CheckTableAndField(const s: string): Boolean;
var
qry : TFDQuery;
lst : TStringList;
procedure PrepareStringItems;
var
s1, sCheck : String;
i, n : Integer;
begin
s1 := StringReplace(StringReplace(s, '[', '', [rfReplaceAll]), ']', '', [rfReplaceAll]);
n := 1;
if Pos('DoIfTableExists', s) > 0 then
sCheck := 'DoIfTableExists'
else if Pos('DoIfTableNotExist', s) > 0 then
sCheck := 'DoIfTableNotExist'
else if Pos('DoIfFieldExists', s) > 0 then
begin
sCheck := 'DoIfFieldExists';
n := 2;
end
else if Pos('DoIfFieldNotExist', s) > 0 then
begin
sCheck := 'DoIfFieldNotExist';
n := 2;
end;
lst.Text := StringReplace(trim(StringReplace(s1, sCheck, '', [rfIgnoreCase])), ',', #13#10, [rfReplaceAll]);
CheckFalse(lst.Count = n, Format(RS_InvalidNumberOfParams, [lst.Count, n]));
lst[0] := StringReplace(lst[0], '.', '].[', [rfReplaceAll]);
for i := 0 to lst.Count - 1 do
lst[i] := format('[%s]', [trim(lst[i])]);
end;
begin
Result := False;
if not ((Pos('DoIfTable', s) > 0) or (Pos('DoIfField', s) > 0)) then
exit;
lst := TStringList.Create;
qry := CreateQuery;
try
PrepareStringItems;
if (Pos('DoIfTableExists', s) > 0) then
begin
qry.SQL.Text := Format('select top 1 1 As CheckField from %s', [lst[0]]);
try
qry.Open;
Result := qry.Active;
except
end;
end
else if (Pos('DoIfTableNotExist', s) > 0) then
begin
qry.SQL.Text := Format('select top 1 1 As CheckField from %s', [lst[0]]);
try
qry.Open;
except
Result := True;
end;
end
else if (Pos('DoIfFieldExists', s) > 0) then
begin
qry.SQL.Text := Format('select top 1 %s As CheckField from %s', [lst[1], lst[0]]);
try
qry.Open;
Result := qry.Active;
except
end;
end
else if (Pos('DoIfFieldNotExist', s) > 0) then
begin
qry.SQL.Text := Format('select top 1 %s As CheckField from %s', [lst[1], lst[0]]);
try
qry.Open;
except
Result := True;
end;
end
finally
lst.Free;
qry.Free;
end;
end;
procedure TFDConnectionHelper.CreateFieldInfoCDS(ds: TDataSet; cdsMapping: TNGFDMemTable);
begin
CheckFalseFmt(Assigned(ds) and ds.Active,
Err_InvalidPointerInCodeRef,
['ds', 'TFDConnectionHelpder.CreateFieldInfoCDS']);
CheckFalseFmt(Assigned(cdsMapping),
Err_InvalidPointerInCodeRef,
['cdsMapping', 'TFDConnectionHelpder.CreateFieldInfoCDS']);
cdsMapping.Close;
cdsMapping.FieldDefs.Clear;
cdsMapping.FieldDefs.Add('FieldName', ftWideString, 50, False);
cdsMapping.FieldDefs.Add('DisplayName', ftWideString, 50, True);
cdsMapping.FieldDefs.Add('ParamName', ftWideString, 50, True);
cdsMapping.FieldDefs.Add('FieldIndex', ftInteger, 0, True);
cdsMapping.CreateDataSet;
// FieldName
ds.ForEachField(nil,
procedure (Field : TField)
begin
cdsMapping.Append;
cdsMapping.FieldByName('FieldName').Value := Field.FieldName;
cdsMapping.FieldByName('DisplayName').Value := Field.DisplayName;
cdsMapping.FieldByName('ParamName').Value := FieldToParam(Field.FieldName);
cdsMapping.FieldByName('FieldIndex').Value := Field.Index;
cdsMapping.Post;
end,
nil
);
end;
function TFDConnectionHelper.CreateQuery: TFDQuery;
begin
inc(iCount);
Result := TFDQuery.Create(nil);
Result.Name := 'FDQry' + IntToStr(iCount);
Result.Connection := self;
end;
initialization
iCount := 0;
end.
|
unit register_extras;
{$mode objfpc}{$H+}
interface
//please, do not change this code format/layout!
uses
Classes,
spinner,
bluetoothclientsocket,
bluetoothserversocket,
bluetooth,
menu,
myhello,
textfilemanager,
dumpjavamethods,
mediaplayer,
SysUtils,
LResources;
Procedure Register;
implementation
//please, do not change this code format/layout!
Procedure Register;
begin
{$I jspinner_icon.lrs}
{$I jbluetoothclientsocket_icon.lrs}
{$I jbluetoothserversocket_icon.lrs}
{$I jbluetooth_icon.lrs}
{$I jmenu_icon.lrs}
{$I jmyhello_icon.lrs}
{$I jtextfilemanager_icon.lrs}
{$I jdumpjavamethods_icon.lrs}
{$I jmediaplayer_icon.lrs}
RegisterComponents('Android Bridges Extra',
[
jSpinner,
jBluetoothClientSocket,
jBluetoothServerSocket,
jBluetooth,
jMenu,
jMyHello,
jTextFileManager,
jDumpJavaMethods,
jMediaPlayer
]
);
end;
end.
|
unit ConfigDialog;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
Buttons, ComCtrls, ExtCtrls, IniFiles, StrUtils, Contnrs;
type
TPICConfigDlg = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
PageControl1: TPageControl;
OKBtn: TButton;
CancelBtn: TButton;
HelpBtn: TButton;
private
public
procedure CreatePages(Ini : TMemIniFile);
end;
var
PICConfigDlg: TPICConfigDlg;
implementation
{$R *.dfm}
{
The Tag field of Control contains :
For CheckBox :
- bit# int the byte
For ComboBox :
- LSB byte : LSB bit# of config bits in the byte
- next byte : MSB bit# of config bits in the byte
The ComboBox Items.Object contain the value of bits for the corresponding option
}
type // centralize bit change event and notify other components
TConfigSheetData = class(TComponent)
private
FControls : TComponentList;
FBits : TBits;
function GetAsByte : byte;
procedure SetAsByte(Value : byte);
protected
procedure BitChangeEvent(Sender : TObject);
public
constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
procedure RegisterControl(AControl : TControl);
property AsByte : byte read GetAsByte write SetAsByte;
end;
constructor TConfigSheetData.Create(AOwner: TComponent);
begin
Inherited Create(Aowner);
FControls := TComponentList.Create(false);
FBits := TBits.Create;
FBits.Size := 8;
end;
Destructor TConfigSheetData.Destroy;
begin
FBits.Free;
FControls.Free;
inherited Destroy;
end;
function TConfigSheetData.GetAsByte : byte;
var
i : integer;
begin
result := 0;
for i := 0 to 7 do
if FBits[i] then result := result or (1 shl i);
end;
procedure TConfigSheetData.SetAsByte(Value : byte);
var
i : integer;
begin
for i := 0 to 7 do
FBits[i]:= (Value and (1 shl i)) <> 0;
BitChangeEvent(nil);
end;
procedure TConfigSheetData.BitChangeEvent(Sender : TObject);
var
i,j : integer;
b : byte;
Lsb : integer;
Msb : integer;
begin
if Assigned(Sender) then begin
if Sender is TCheckBox then
with Sender as TCheckBox do begin
FBits[Tag] := Checked;
end
else if Sender is TComboBox then
with Sender as TComboBox do begin
Lsb := Tag mod 256;
Msb := Tag div 256;
if ItemIndex<>-1 then b := Byte(Items.Objects[ItemIndex]) shl Lsb;
for j := Lsb to Msb do
FBits[j] := (b and (1 shl j)) <> 0;
end;
end;
// Notify
i := 0;
while i < FControls.Count do begin
if FControls[i] <> Sender then begin
if FControls[i] is TCheckBox then
with FControls[i] as TCheckBox do Checked := FBits[Tag];
if FControls[i] is TComboBox then
with FControls[i] as TComboBox do begin
// Extract bits
b := 0;
Lsb := Tag mod 256;
Msb := Tag div 256;
for j := Lsb to Msb do
if FBits[j] then b := b or (1 shl (j-Lsb));
ItemIndex := Items.IndexOfObject(TObject(b));
if ItemIndex=-1 then Text := Format('Unknow configuration bits : 0x%x', [b]);
end;
end;
inc(i);
end;
end;
procedure TConfigSheetData.RegisterControl(AControl : TControl);
begin
FControls.Add(AControl);
if AControl is TCheckBox then (AControl as TCheckBox).OnClick := self.BitChangeEvent;
if AControl is TComboBox then (AControl as TComboBox).OnChange := self.BitChangeEvent;
end;
procedure TPICConfigDlg.CreatePages(Ini : TMemIniFile);
var
Sections : TStringList;
Bits : TStringList;
ConfigSheetData : TConfigSheetData;
i,j,k : integer;
TabSheet : TTabSheet;
AControl : TControl;
BitName : string;
Value : integer;
BitMin, BitMax : integer;
PointPos : integer;
CommaPos : integer;
MinusPos : integer;
PosY : integer;
begin
Sections := TStringList.Create;
Bits := TStringList.Create;
Caption := Ini.ReadString('ROOT', 'Proc', 'Unknow processor');
// Create pages
Ini.ReadSections(Sections);
i := 0;
while i < Sections.Count do begin
if AnsiStartsText('CONFIG_REGISTER.', Sections[i]) then begin
TabSheet := TTabSheet.Create(PageControl1);
TabSheet.PageControl := PageControl1;
TabSheet.Caption := Copy(Sections[i], Pos('.', Sections[i])+1, 255);
ConfigSheetData := TConfigSheetData.Create(TabSheet);
AControl := TLabel.Create(TabSheet);
TabSheet.Tag := Ini.ReadInteger(Sections[i], 'Address', 0);
With AControl as TLabel do begin
Parent := TabSheet;
Left := 210;
Top := 5;
Caption := Format('0x%x', [TabSheet.Tag]);
end;
for j := 7 downto 0 do begin
AControl := TCheckBox.Create(TabSheet);
With AControl as TCheckBox do begin
Name := Format('_BIT%u', [j]);
Caption := '';
Tag := j;
Parent := TabSheet;
Top := 5;
Left := 180-(25*j);
Width := 15;
Enabled := false;
end;
ConfigSheetData.RegisterControl(AControl);
end;
Ini.ReadSectionValues(Sections[i], Bits);
Bits.Values['Address'] := '';
PosY := 40;
j := 0;
while j < Bits.Count do begin
PointPos := Pos('.', Bits.Names[j]);
if PointPos = 0 then begin
// Create the control
BitName := Bits.Names[j];
CommaPos := Pos(',', Bits.ValueFromIndex[j]);
if CommaPos <> 0 then begin
AControl := TCheckBox.Create(TabSheet);
with AControl as TCheckbox do begin
Tag := StrToIntDef(Copy(Bits.ValueFromIndex[j], 1, CommaPos-1), -1);
if Tag = -1 then raise EConvertError.CreateFmt('Configuration bit %s', [BitName]);
Caption := BitName+' : '+Trim(Copy(Bits.ValueFromIndex[j], CommaPos+1, 255));
if Tag in [0..7] then
With TabSheet.FindChildControl(Format('_BIT%u', [AControl.Tag])) as TCheckBox do begin
Hint := BitName;
Enabled := true;
end;
end;
end else begin
AControl := TComboBox.Create(TabSheet);
with AControl as TComboBox do begin
Style := csDropDownList;
MinusPos := Pos('-', Bits.ValueFromIndex[j]);
if MinusPos = 0 then begin
BitMin := StrToIntDef(Bits.ValueFromIndex[j], -1);
BitMax := BitMin;
if BitMin < 0 then raise EConvertError.CreateFmt('Configuration bit %s', [BitName]);
if BitMin in [0..7] then
With TabSheet.FindChildControl(Format('_BIT%u', [BitMin])) as TCheckBox do begin
Hint := BitName;
Enabled := true;
end;
end else begin
BitMax := StrToIntDef(Copy(Bits.ValueFromIndex[j], 1, MinusPos-1), -1);
BitMin := StrToIntDef(Copy(Bits.ValueFromIndex[j], MinusPos+1, 255), -1);
if BitMin > BitMax then begin
Value := BitMin;
BitMin := BitMax;
BitMax := Value;
end;
if BitMin < 0 then raise EConvertError.CreateFmt('Configuration bit %s', [BitName]);
for k :=BitMin to BitMax do
if k in [0..7] then
With TabSheet.FindChildControl(Format('_BIT%u', [k])) as TCheckBox do begin
Hint := Format('%s%u', [BitName, k-BitMin]);
Enabled := true;
end;
end;
Tag := BitMin+256*BitMax;
end;
end;
AControl.Name := BitName;
AControl.Parent := TabSheet;
AControl.Top := PosY;
AControl.Width := 350;
ConfigSheetData.RegisterControl(AControl);
Inc(PosY, 25);
end else begin
// Add value to the
BitName := Copy(Bits.Names[j], 1, PointPos-1);
Value := StrToIntDef(Copy(Bits.Names[j], PointPos+1, 255), -1);
if Value = -1 then raise EConvertError.CreateFmt('Configuration bit %s', [Bits.Names[j]]);
AControl := TabSheet.FindChildControl(BitName);
if Assigned(AControl) and (AControl is TComboBox) then
with AControl as TComboBox do begin
Items.AddObject(Bits.ValueFromIndex[j], TObject(Value));
end;
end;
Inc(j);
end;
ConfigSheetData.AsByte := $FF;
end;
inc(i);
end;
Bits.Free;
Sections.Free;
end;
end.
|
unit wizardXPGen;
interface
uses
toolsAPI,
IStreams,
dialogs,
SysUtils,
Windows,
VirtIntf,
ExptIntf,
ToolIntf,
classes;
type
// TNotifierObject has stub implementations for the necessary but
// unused IOTANotifer methods
TXPGenWizard = class(TNotifierObject, IOTANotifier,IOTAKeyboardBinding)
public
// IOTAWizard interafce methods(required for all wizards/experts)
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
procedure KeyBoardHandler(const Context: IOTAKeyContext; KeyCode: TShortcut;
var BindingResult: TKeyBindingResult);
// IOTAMenuWizard (creates a simple menu item on the help menu)
function GetMenuText: string;
procedure BindKeyboard(const BindingServices: IOTAKeyBindingServices);
function GetBindingType: TBindingType;
function GetDisplayName: string;
private
function GenerateTestCode(srcStream : TMemorystream) : string;
function FindSourceEditor(sourceModule: IOTAModule): IOTASourceEditor;
function GetSourceModuleLength(SrceEditor: IOTASourceEditor): longint;
function SrcModuleToMemoryStream(srcModule: IOTAModule): TMemoryStream;
end;
procedure Register;
implementation
uses
menus,
xpParse,
xpCodeGen;
procedure Register;
begin
(BorlandIDEServices as IOTAKeyBoardServices).AddKeyboardBinding(TXPGenWizard.Create);
end;
procedure TXPGenWizard.BindKeyboard(
const BindingServices: IOTAKeyBindingServices);
begin
BindingServices.AddKeyBinding([ShortCut(Ord('X'), [ssShift, ssCtrl])], KeyboardHandler, nil,
kfImplicitShift or kfImplicitModifier or kfImplicitKeypad, '', '');
end;
procedure TXPGenWizard.Execute;
var
ModulePath,
ModuleName,
UnitName, FileName, FormName: string;
SourceStream: TIMemoryStream;
SourceBufferStream : TMemoryStream;
SourceEditor: IOTASourceEditor;
moduleInfo: IOTAModuleInfo;
Writer: IOTAEditWriter;
currentModule,
sourceModule: IOTAModule;
moduleServices: IOTAModuleServices;
sourceText: string;
mlength: longint;
begin
if (toolServices <> nil) then
begin
if BorlandIDEServices.QueryInterface(IOTAModuleServices, ModuleServices) =
S_OK then
begin
CurrentModule := ModuleServices.CurrentModule;
if currentModule <> nil then
begin
ModulePath := currentModule.Filename;
if ExtractFileExt(lowercase(ModulePath)) = '.pas' then
begin
ModulePath := ExtractFilePath(modulePath);
Modulename := currentModule.Filename;
Modulename := ExtractFilename(modulename);
{ ensure this is always a new pass file in case they do this on a DFM file }
ModuleName := ChangeFileExt(moduleName, '.pas');
ModuleName := 'Test_' + ModuleName;
{ copy the module source code to a memory stream we can deal with }
SourceBufferStream := SrcModuleToMemoryStream(CurrentModule);
if sourcebufferSTream <> nil then
begin
sourceText := GenerateTestCode(SourceBufferStream);
SourceStream := TIMemoryStream.Create(TMemoryStream.Create,soOwned);
ToolServices.CreateModule(ModulePath+ModuleName,SourceStream,nil,[cmNewUnit]);
{ get the tool that keeps track of all project modules }
{ you can do a cast here with (BorlandIDEServes as x) but why chance it? }
SourceModule := ModuleServices.FindModule(ModulePath+ModuleName);
if SourceModule <> nil then
begin
SourceEditor := FindSourceEditor(sourceModule);
if sourceEditor <> nil then
begin
mlength := GetSourceModuleLength(SourceEditor);
Writer := SourceEditor.CreateWriter;
Writer.DeleteTo(mlength);
Writer.Insert(pchar(sourceText));
end;
end;
sourceBufferStream.Free;
end;
end
else
MessageBeep(word(-1));
end;
{ filename := currentModule.Filename;
filename := ChangeFileExt(filename,'.pas');}
end;
end;
end;
function TXPGenWizard.GetBindingType: TBindingType;
begin
result := btPartial;
end;
function TXPGenWizard.GetDisplayName: string;
begin
result := 'hello wizard';
end;
function TXPGenWizard.GetIDString: string;
begin
Result := 'EB.HelloWizard';
end;
function TXPGenWizard.GetMenuText: string;
begin
Result := '&Hello Wizard';
end;
function TXPGenWizard.GetName: string;
begin
Result := 'Hello Wizard';
end;
function TXPGenWizard.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
procedure TXPGenWizard.KeyBoardHandler(const Context: IOTAKeyContext;
KeyCode: TShortcut; var BindingResult: TKeyBindingResult);
begin
Execute;
BindingResult := krHandled;
end;
function TXPGenWizard.GenerateTestCode(srcStream : TMemorystream) : string;
var
XPParser : TXPStubParser;
SrcGen : SrcGenExternalTest;
SrcCodeDriver : DriverSrcOutputText;
begin
result := '';
try
XPParser := nil;
try
XPParser := TXPStubParser.Create;
XPParser.SrcStream := srcStream;
srcStream.Position := 0;
XPParser.Parse;
SrcCodeDriver := DriverSrcOutputText.Create;
try
SrcGen := SrcGenExternalTest.Create(XPParser.unitName,SrcCodeDriver);
try
SrcGen.GenerateCode(XPParser.ParseNodeList);
result := srcCodeDriver.text;
finally
SrcGen.Free;
end;
finally
SrcCodeDriver.Free;
end;
finally
XPParser.Free;
end;
finally
end;
end;
function TXPGenWizard.FindSourceEditor(sourceModule: IOTAModule): IOTASourceEditor;
var
i: integer;
begin
i := 0;
with sourceModule do
begin
while (i < GetModuleFileCount) do
if GetModuleFileEditor(i).QueryInterface(IOTASourceEditor, result) =
S_OK then
break
else
inc(i);
end;
end;
function TXPGenWizard.GetSourceModuleLength(SrceEditor: IOTASourceEditor): longint;
var
Reader: IOTAEditReader;
buf: char;
begin
result := 0;
reader := SrceEditor.CreateReader;
while reader.getText(result, @buf, 1) > 0 do
begin
inc(result);
end;
reader := nil;
end;
function TXPGenWizard.SrcModuleToMemoryStream(srcModule : IOTAModule) : TMemoryStream;
var
moduleSize : longint;
SourceEditor: IOTASourceEditor;
Rdr: IOTAEditReader;
pos: longint;
buf: char;
res : integer;
begin
result := TMemoryStream.create;
SourceEditor := FindSourceEditor(srcModule);
if sourceEditor <> nil then
begin
ModuleSize := GetSourceModuleLength(SourceEditor);
result.setSize(ModuleSize);
{ transfere the data from the source module to the memory stream }
sourceEditor := nil;
SourceEditor := FindSourceEditor(srcModule);
rdr := SourceEditor.CreateReader;
pos := 0;
while rdr.getText(pos, @buf, 1) > 0 do
begin
result.write(buf,sizeof(buf));
inc(pos);
end;
end;
end;
end.
|
unit u_WB;
interface
uses
windows, SysUtils, Classes, Controls, OleCtrls, SHDocVw, MSHTML,
Variants, comobj, ActiveX, Messages;
type
TW_FilterMode = (FM_None, FM_Href, FM_Title);
TW_ExecCMD = (EC_SAVEAS, EC_SAVE, EC_PAGESETUP, EC_PRINTPREVIEW, EC_PRINT, EC_STOP,
EC_REFRESH, EC_COPY, EC_PASTE, EC_CUT, EC_SELECTALL, EC_FIND, EC_PROPERTIES);
TW_IEWB = class(TWebBrowser)
private
Furl: string;
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ShowFind();
//使WebBrowser获得焦点
procedure SetFous();
function hasFous(): Boolean;
function FindText(text: string): integer;
procedure ExecCMD(EC: TW_ExecCMD);
procedure SetFontSize(value: olevariant);
procedure ShowHtml(title, content: string);
procedure ADDCollention(const thistilte: string = '');
procedure GoToURL(const url: string);
function Version(): string;
//文档代码
function GetHtml: string;
//插入Html代码
procedure AddHtmlToBody(const html: string);
//模拟鼠标点击
procedure MouseLClick(const x, y: Integer);
//获取ElementById
function getElementById(const id: string): IHTMLElement;
function getElementsByTagName(const Tag: string): IHTMLElementCollection;
//触发TagID的Click事件
procedure DoClickByTagId(const id: string);
//获取连接列表
procedure GetLinks(var LinkList: TStringList; const Filter: string; const FM: TW_FilterMode);
//根据连接获取
function FindLinkForHref(var url: string): IHTMLElement;
published
property Url: string read Furl;
end;
implementation
{TMyWebBrowser}
//使WebBrowser获得焦点
procedure TW_IEWB.SetFous();
begin
if Document <> nil then
IHTMLWindow2(IHTMLDocument2(Document).ParentWindow).focus
end;
function TW_IEWB.hasFous(): Boolean;
begin
Result := IHTMLDocument4(Document).hasfocus;
end;
procedure TW_IEWB.GetLinks(var LinkList: TStringList; const Filter: string; const FM: TW_FilterMode);
var
doc2: IHTMLDocument2;
Links: IHTMLElementCollection;
link: IHTMLElement;
i: Integer;
href: OleVariant;
title: string;
IsFilter: Boolean;
begin
if not Assigned(LinkList) then Exit;
doc2 := Document as IHTMLDocument2;
if not Assigned(doc2) then Exit;
Links := doc2.links;
LinkList.Clear;
for i := 0 to Links.length - 1 do
begin
link := (Links.Item(i, varNull) as IHTMLElement);
if Assigned(link) then
begin
//可能连接字符串javascript ,调用者自行判断
href := link.getAttribute('href', 0);
title := link.innerText;
if (VarIsNull(href) or VarIsEmpty(href)) then Continue;
IsFilter := false;
case FM of
FM_Href: IsFilter := (Pos(Filter, href) <= 0);
FM_Title: IsFilter := (Pos(Filter, title) <= 0);
end;
if not IsFilter then
LinkList.Add(href);
end;
end;
end;
function TW_IEWB.FindLinkForHref(var url: string): IHTMLElement;
var
doc2: IHTMLDocument2;
Links: IHTMLElementCollection;
link: IHTMLElement;
i: Integer;
href: OleVariant;
begin
result := nil;
doc2 := Document as IHTMLDocument2;
if not Assigned(doc2) then Exit;
Links := doc2.links;
for i := 0 to Links.length - 1 do
begin
link := (Links.Item(i, varNull) as IHTMLElement);
if Assigned(link) then
begin
href := link.getAttribute('href', 0);
if not (VarIsNull(href) or VarIsEmpty(href)) then
if href = url then
begin
result := link;
Break;
end;
end;
end;
end;
procedure TW_IEWB.MouseLClick(const x, y: LongInt);
var
LP: LPARAM;
Ph: THandle;
begin
LP := MakeLParam(x, y); // x + y shl 16;
//Ph := FindWindowEx(PageControl.ActivePage.Handle, 0, 'Shell Embedding',nil);
Ph := FindWindowEx(Handle, 0, 'Shell DocObject View', nil);
Ph := FindWindowEx(Ph, 0, 'Internet Explorer_Server', nil);
if Ph > 0 then
begin
//用SendMessage 比较稳妥,但是容易会阻赛
PostMessage(Ph, WM_LBUTTONDOWN, 0, LP); //鼠标按下
PostMessage(Ph, WM_LBUTTONUP, 0, LP); // 鼠标抬起
end;
end;
function TW_IEWB.getElementById(const id: string): IHTMLElement;
var
doc3: IHTMLDocument3;
begin
result := nil;
doc3 := Document as IHTMLDocument3;
if not Assigned(doc3) then Exit;
result := doc3.getElementById(id);
end;
function TW_IEWB.getElementsByTagName(const Tag: string): IHTMLElementCollection;
var
doc3: IHTMLDocument3;
begin
result := nil;
doc3 := Document as IHTMLDocument3;
if not Assigned(doc3) then Exit;
result := doc3.getElementsByTagName(Tag);
end;
procedure TW_IEWB.DoClickByTagId(const id: string);
var
Element: IHTMLElement;
begin
Element := getElementById(id);
if Assigned(Element) then
Element.click;
end;
procedure TW_IEWB.AddHtmlToBody(const html: string);
var
doc2: IHTMLDocument2;
begin
doc2 := Document as IHTMLDocument2;
if not Assigned(doc2) then Exit;
doc2.body.insertAdjacentHTML('afterBegin', html)
{
Range: IHTMLTxtRange;
Range := (body as IHTMLBodyElement).createTextRange;
if not Assigned(Range) then Exit;
Range.collapse(False);
Range.pasteHTML(html);
}
end;
procedure TW_IEWB.GoToURL(const url: string);
begin
Navigate(url, EmptyParam, EmptyParam, EmptyParam, EmptyParam);
end;
procedure TW_IEWB.SetFontSize(Value: olevariant);
begin
ExecWB(OLECMDID_ZOOM, OLECMDEXECOPT_DONTPROMPTUSER, Value, Value);
end;
procedure TW_IEWB.ShowFind;
var
CmdTarget: IOleCommandTarget;
PtrGUID: PGUID;
vaIn, vaOut: Olevariant;
const
CLSID_WebBrowser: TGUID = '{ED016940-BD5B-11cf-BA4E-00C04FD70816}';
HTMLID_FIND = 1;
begin
New(PtrGUID);
try
PtrGUID^ := CLSID_WebBrowser;
if Document <> nil then
try
Document.QueryInterface(IOleCommandTarget, CmdTarget);
if CmdTarget <> nil then
try
CmdTarget.Exec(PtrGuid, HTMLID_FIND, 0, vaIn, vaOut);
finally
CmdTarget._Release;
end;
except
;
end;
finally
Dispose(PtrGUID);
end;
end;
procedure TW_IEWB.ShowHtml(title, content: string);
var
doc2: IHTMLDocument2;
vv: olevariant;
begin
doc2 := Document as IHTMLDocument2;
if not Assigned(doc2) then Exit;
vv := VarArrayCreate([0, 0], varVariant);
vv[0] := content;
doc2.write(PSafeArray(TVarData(vv).VArray));
doc2.title := title;
end;
function TW_IEWB.FindText(text: string): integer;
var
i, k, len: Integer;
begin
k := 0;
len := self.OleObject.Document.All.Length - 1;
for i := 0 to len do
begin
if Pos(text, self.OleObject.Document.All.Item(i).InnerText) <> 0 then
begin
self.OleObject.Document.All.Item(i).Style.Color := '#4BA444';
Inc(k);
end;
if k = len then self.OleObject.Document.All.Item(i).ScrollIntoView(true);
end;
result := k;
end;
procedure TW_IEWB.ExecCMD(EC: TW_ExecCMD);
begin
try
case EC of
EC_SAVEAS: ExecWB(OLECMDID_SAVEAS, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_SAVE: ExecWB(OLECMDID_SAVE, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_PAGESETUP: ExecWB(OLECMDID_PAGESETUP, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_PRINTPREVIEW: ExecWB(OLECMDID_PRINTPREVIEW, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_PRINT: ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_STOP: ExecWB(OLECMDID_STOP, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_REFRESH: ExecWB(OLECMDID_REFRESH, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_Find: ExecWB(OLECMDID_FIND, OLECMDEXECOPT_DODEFAULT, EmptyParam);
///////////////////////////////////////////////////////////////////////////////
EC_COPY: ExecWB(OLECMDID_COPY, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_PASTE: ExecWB(OLECMDID_PASTE, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_CUT: ExecWB(OLECMDID_CUT, OLECMDEXECOPT_DODEFAULT, EmptyParam);
EC_SELECTALL: ExecWB(OLECMDID_SELECTALL, OLECMDEXECOPT_DODEFAULT, EmptyParam);
///////////////////////////////////////////////////////////////////////////////
EC_PROPERTIES: ExecWB(OLECMDID_PROPERTIES, OLECMDEXECOPT_DODEFAULT, EmptyParam);
end;
except
on e: Exception do
begin
MessageBox(0, PChar('出错信息:' + #13#10 + e.Message),
'系统提示', MB_OK + MB_ICONWARNING);
end;
end;
end;
function TW_IEWB.GetHtml: string;
var
doc2: IHTMLDocument2;
begin
Result := '';
doc2 := Document as IHTMLDocument2;
if not Assigned(doc2) then Exit;
result := doc2.Body.OuterHtml;
end;
procedure TW_IEWB.ADDCollention(const thistilte: string = '');
const
CLSID_ShellUIHelper: TGUID = '{64AB4BB7-111E-11D1-8F79-00C04FC2FBE1}';
var
ShellUIHelper: ISHellUIHelper;
url, title: olevariant;
begin
if thistilte <> '' then
title := thistilte
else
title := LocationName;
url := LocationUrl;
if url <> '' then
begin
ShellUIHelper := CreateComObject(CLSID_ShellUIHelper) as ISHellUIHelper;
ShellUIHelper.AddFavorite(url, title);
end;
end;
constructor TW_IEWB.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TW_IEWB.Destroy;
begin
inherited;
end;
function TW_IEWB.Version: string;
begin
Result := 'WB 1.0 By 20100729';
end;
end.
|
unit FC.StockChart.UnitTask.Indicator.Rename;
interface
{$I Compiler.inc}
uses
SysUtils,Classes, BaseUtils, Serialization, Dialogs, StockChart.Definitions.Units,StockChart.Definitions,
FC.Definitions, FC.Singletons,
FC.StockChart.UnitTask.Base;
implementation
type
TStockUnitTaskValueSupportSnapshot = 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;
{ TStockUnitTaskValueSupportSnapshot }
function TStockUnitTaskValueSupportSnapshot.CanApply(const aIndicator: ISCIndicator; out aOperationName: string): boolean;
begin
result:=Supports(aIndicator,ISCWritableName);
if result then
aOperationName:='Rename';
end;
procedure TStockUnitTaskValueSupportSnapshot.Perform(const aIndicator: ISCIndicator; const aStockChart: IStockChart; const aCurrentPosition: TStockPosition);
var
s: string;
aValueSupport : ISCWritableName;
begin
aValueSupport:=aIndicator as ISCWritableName;
s:=aIndicator.Caption;
if InputQuery('Rename','Enter new name of the unit', s) then
aValueSupport.SetName(s);
end;
initialization
StockUnitTaskRegistry.AddUnitTask(TStockUnitTaskValueSupportSnapshot.Create);
end.
|
unit LongInput;
interface
uses
System.SysUtils, System.Classes, FMX.Types, FMX.Controls, System.Types,
FMX.Objects, System.UITypes, FMX.Graphics, FMX.Dialogs, System.Math,
System.Math.Vectors, FMX.Edit, FMX.Layouts, FMX.Effects, FMX.Memo,
FMX.StdCtrls;
type
TIconPosition = (Left, Right);
TLongInput = class(TControl)
private
{ Private declarations }
procedure FMemoOnApplyStyleLookup(Sender: TObject);
procedure EventOnChangeTracking(Sender: TObject);
procedure AnimationLabelTextPromptOnEnter;
procedure AnimationLabelTextPromptOnExit;
procedure RefreshCharacterCounter;
function GetFCharCase: TEditCharCase;
procedure SetFCharCase(const Value: TEditCharCase);
protected
{ Protected declarations }
FPointerOnChangeTracking: TNotifyEvent;
FPointerOnEnter: TNotifyEvent;
FPointerOnExit: TNotifyEvent;
FPointerOnKeyUp: TKeyEvent;
FChangeTextSettings: Boolean;
FSelectedTheme: TAlphaColor;
FTextPromptAnimation: Boolean;
FInvalid: Boolean;
FBackground: TRectangle;
FMemo: TMemo;
FLabel: TLabel;
FLabelLengthCount: TLabel;
FDark: Boolean;
FTabNext: TControl;
FDarkTheme: TAlphaColor;
FLightTheme: TAlphaColor;
procedure Paint; override;
procedure OnKeyUpTabNext(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
{ Repaint }
procedure DoChanged(Sender: TObject);
{ Events settings }
procedure OnEditEnter(Sender: TObject); virtual;
procedure OnEditExit(Sender: TObject); virtual;
function Validate(): Boolean; virtual;
procedure SetFText(const Value: String); virtual;
function GetFCharacterCounter: Boolean;
procedure SetFCharacterCounter(const Value: Boolean);
function GetFTag: NativeInt;
procedure SetFTag(const Value: NativeInt);
procedure SetFTabNext(const Value: TControl);
procedure OnFBackgroundClick(Sender: TObject);
function GetFText: String;
function GetFTextPrompt: String;
procedure SetFTextPrompt(const Value: String);
function GetFOnClick: TNotifyEvent;
procedure SetFOnClick(const Value: TNotifyEvent);
function GetFOnDblClick: TNotifyEvent;
procedure SetFOnDblClick(const Value: TNotifyEvent);
function GetTextSettings: TTextSettings;
procedure SetTextSettings(const Value: TTextSettings);
function GetFBackgroudColor: TAlphaColor;
procedure SetFBackgroudColor(const Value: TAlphaColor);
function GetFDark: Boolean;
procedure SetFDark(const Value: Boolean);
function GetFHitTest: Boolean;
procedure SetFHitTest(const Value: Boolean);
function GetFCursor: TCursor;
procedure SetFCursor(const Value: TCursor);
function GetFOnKeyDown: TKeyEvent;
procedure SetFOnKeyDown(const Value: TKeyEvent);
function GetFOnMouseDown: TMouseEvent;
procedure SetFOnMouseDown(const Value: TMouseEvent);
function GetFOnMouseUp: TMouseEvent;
procedure SetFOnMouseUp(const Value: TMouseEvent);
function GetFOnMouseWheel: TMouseWheelEvent;
procedure SetFOnMouseWheel(const Value: TMouseWheelEvent);
function GetFOnMouseMove: TMouseMoveEvent;
procedure SetFOnMouseMove(const Value: TMouseMoveEvent);
function GetFOnMouseEnter: TNotifyEvent;
procedure SetFOnMouseEnter(const Value: TNotifyEvent);
function GetFOnMouseLeave: TNotifyEvent;
procedure SetFOnMouseLeave(const Value: TNotifyEvent);
function GetFMaxLength: Integer;
procedure SetFMaxLength(const Value: Integer);
function GetFReadOnly: Boolean;
procedure SetFReadOnly(const Value: Boolean);
function GetFCanFocus: Boolean;
procedure SetFCanFocus(const Value: Boolean);
function GetFCaret: TCaret;
procedure SetFCaret(const Value: TCaret);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetFocus; reintroduce;
procedure Clear; virtual;
published
{ Published declarations }
property Align;
property Anchors;
property Enabled;
property Height;
property Opacity;
property Visible;
property Width;
property Size;
property Scale;
property Margins;
property Position;
property RotationAngle;
property RotationCenter;
{ Additional properties }
property Caret: TCaret read GetFCaret write SetFCaret;
property CanFocus: Boolean read GetFCanFocus write SetFCanFocus default True;
property Cursor: TCursor read GetFCursor write SetFCursor;
property HitTest: Boolean read GetFHitTest write SetFHitTest default True;
property ReadOnly: Boolean read GetFReadOnly write SetFReadOnly;
property Dark: Boolean read GetFDark write SetFDark;
property BackgroudColor: TAlphaColor read GetFBackgroudColor write SetFBackgroudColor;
property Text: String read GetFText write SetFText;
property TextPrompt: String read GetFTextPrompt write SetFTextPrompt;
property TextPromptAnimation: Boolean read FTextPromptAnimation write FTextPromptAnimation;
property TextSettings: TTextSettings read GetTextSettings write SetTextSettings;
property MaxLength: Integer read GetFMaxLength write SetFMaxLength;
property CharacterCounter: Boolean read GetFCharacterCounter write SetFCharacterCounter;
property TabNext: TControl read FTabNext write SetFTabNext;
property Tag: NativeInt read GetFTag write SetFTag;
property CharCase: TEditCharCase read GetFCharCase write SetFCharCase;
{ Events }
property OnPainting;
property OnPaint;
property OnResize;
{ Mouse events }
property OnClick: TNotifyEvent read GetFOnClick write SetFOnClick;
property OnDblClick: TNotifyEvent read GetFOnDblClick write SetFOnDblClick;
property OnKeyDown: TKeyEvent read GetFOnKeyDown write SetFOnKeyDown;
property OnKeyUp: TKeyEvent read FPointerOnKeyUp write FPointerOnKeyUp;
property OnMouseDown: TMouseEvent read GetFOnMouseDown write SetFOnMouseDown;
property OnMouseUp: TMouseEvent read GetFOnMouseUp write SetFOnMouseUp;
property OnMouseWheel: TMouseWheelEvent read GetFOnMouseWheel write SetFOnMouseWheel;
property OnMouseMove: TMouseMoveEvent read GetFOnMouseMove write SetFOnMouseMove;
property OnMouseEnter: TNotifyEvent read GetFOnMouseEnter write SetFOnMouseEnter;
property OnMouseLeave: TNotifyEvent read GetFOnMouseLeave write SetFOnMouseLeave;
property OnChangeTracking: TNotifyEvent read FPointerOnChangeTracking write FPointerOnChangeTracking;
property OnEnter: TNotifyEvent read FPointerOnEnter write FPointerOnEnter;
property OnExit: TNotifyEvent read FPointerOnExit write FPointerOnExit;
end;
implementation
uses
Input;
procedure TLongInput.AnimationLabelTextPromptOnEnter;
begin
if FTextPromptAnimation then
begin
FLabel.AnimateFloat('Margins.Top', -17, 0.25, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('Margins.Left', 2, 0.25, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('TextSettings.Font.Size', FMemo.TextSettings.Font.Size - 2, 0.25, TAnimationType.InOut,
TInterpolationType.Circular);
FLabel.AnimateColor('TextSettings.FontColor', FSelectedTheme, 0.25, TAnimationType.InOut,
TInterpolationType.Circular);
end
else
FLabel.AnimateColor('TextSettings.FontColor', TAlphaColor($FF999999), 0.25, TAnimationType.InOut,
TInterpolationType.Circular);
end;
procedure TLongInput.AnimationLabelTextPromptOnExit;
begin
if FTextPromptAnimation and Self.Text.Equals('') then
begin
FLabel.AnimateFloat('Margins.Top', 8, 0.25, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('Margins.Left', 10, 0.25, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('TextSettings.Font.Size', FMemo.TextSettings.Font.Size, 0.25, TAnimationType.InOut,
TInterpolationType.Circular);
end;
if not FInvalid then
FLabel.AnimateColor('TextSettings.FontColor', TAlphaColor($FF999999), 0.25, TAnimationType.InOut,
TInterpolationType.Circular);
end;
procedure TLongInput.OnEditEnter(Sender: TObject);
begin
AnimationLabelTextPromptOnEnter;
if Assigned(FPointerOnEnter) then
FPointerOnEnter(Sender);
end;
procedure TLongInput.OnEditExit(Sender: TObject);
begin
AnimationLabelTextPromptOnExit;
if Assigned(FPointerOnExit) then
FPointerOnExit(Sender);
end;
procedure TLongInput.OnFBackgroundClick(Sender: TObject);
begin
FMemo.SetFocus;
end;
procedure TLongInput.OnKeyUpTabNext(Sender: TObject; var Key: Word; var KeyChar: Char; Shift: TShiftState);
begin
if (Key = vkTab) and (Assigned(FTabNext)) then
begin
if (FTabNext is TInput) then
TInput(FTabNext).SetFocus
else if (FTabNext is TLongInput) then
TLongInput(FTabNext).SetFocus
else
FTabNext.SetFocus;
end;
if Assigned(FPointerOnKeyUp) then
FPointerOnKeyUp(Sender, Key, KeyChar, Shift);
end;
procedure TLongInput.SetFOnClick(const Value: TNotifyEvent);
begin
FMemo.OnClick := Value;
end;
procedure TLongInput.SetFBackgroudColor(const Value: TAlphaColor);
begin
FBackground.Fill.Color := Value;
end;
function TLongInput.GetFBackgroudColor: TAlphaColor;
begin
Result := FBackground.Fill.Color;
end;
procedure TLongInput.SetFCursor(const Value: TCursor);
begin
FBackground.Cursor := Value;
FMemo.Cursor := Value;
end;
function TLongInput.GetFCanFocus: Boolean;
begin
Result := FMemo.CanFocus;
end;
procedure TLongInput.SetFCanFocus(const Value: Boolean);
begin
FMemo.CanFocus := Value;
end;
function TLongInput.GetFCaret: TCaret;
begin
Result := FMemo.Caret;
end;
function TLongInput.GetFCharacterCounter: Boolean;
begin
Result := FLabelLengthCount.Visible;
end;
function TLongInput.GetFCharCase: TEditCharCase;
begin
Result := FMemo.CharCase;
end;
procedure TLongInput.SetFCaret(const Value: TCaret);
begin
FMemo.Caret := Value;
end;
procedure TLongInput.SetFCharacterCounter(const Value: Boolean);
begin
FLabelLengthCount.Visible := Value;
RefreshCharacterCounter;
end;
procedure TLongInput.SetFCharCase(const Value: TEditCharCase);
begin
FMemo.CharCase := Value;
end;
function TLongInput.GetFCursor: TCursor;
begin
Result := FBackground.Cursor;
end;
procedure TLongInput.SetFDark(const Value: Boolean);
begin
FDark := Value;
FBackground.Fill.Kind := TBrushKind.Solid;
if Value then
begin
FBackground.Fill.Color := FDarkTheme;
FMemo.TextSettings.FontColor := TAlphaColor($FFFFFFFF);
end
else
begin
FBackground.Fill.Color := FLightTheme;
FMemo.TextSettings.FontColor := TAlphaColor($FF323232);
end;
end;
procedure TLongInput.SetFocus;
begin
FMemo.SetFocus;
end;
procedure TLongInput.Clear;
begin
Self.Text := '';
end;
function TLongInput.Validate: Boolean;
begin
Result := not(FMemo.Text.Length = 0);
FInvalid := not Result;
end;
function TLongInput.GetFDark: Boolean;
begin
Result := FDark;
end;
procedure TLongInput.SetFHitTest(const Value: Boolean);
begin
FBackground.HitTest := Value;
FMemo.HitTest := Value;
end;
function TLongInput.GetFHitTest: Boolean;
begin
Result := FBackground.HitTest;
end;
procedure TLongInput.SetFMaxLength(const Value: Integer);
begin
FMemo.MaxLength := Value;
RefreshCharacterCounter;
end;
function TLongInput.GetFMaxLength: Integer;
begin
Result := FMemo.MaxLength;
end;
function TLongInput.GetFOnClick: TNotifyEvent;
begin
Result := FMemo.OnClick;
end;
procedure TLongInput.SetFOnDblClick(const Value: TNotifyEvent);
begin
FMemo.OnDblClick := Value;
end;
function TLongInput.GetFOnDblClick: TNotifyEvent;
begin
Result := FMemo.OnDblClick;
end;
procedure TLongInput.SetFOnKeyDown(const Value: TKeyEvent);
begin
FMemo.OnKeyDown := Value;
end;
function TLongInput.GetFOnKeyDown: TKeyEvent;
begin
Result := FMemo.OnKeyDown;
end;
procedure TLongInput.SetFOnMouseDown(const Value: TMouseEvent);
begin
FMemo.OnMouseDown := Value;
end;
function TLongInput.GetFOnMouseDown: TMouseEvent;
begin
Result := FMemo.OnMouseDown;
end;
procedure TLongInput.SetFOnMouseEnter(const Value: TNotifyEvent);
begin
FMemo.OnMouseEnter := Value;
end;
function TLongInput.GetFOnMouseEnter: TNotifyEvent;
begin
Result := FMemo.OnMouseEnter;
end;
procedure TLongInput.SetFOnMouseLeave(const Value: TNotifyEvent);
begin
FMemo.OnMouseLeave := Value;
end;
function TLongInput.GetFOnMouseLeave: TNotifyEvent;
begin
Result := FMemo.OnMouseLeave;
end;
procedure TLongInput.SetFOnMouseMove(const Value: TMouseMoveEvent);
begin
FMemo.OnMouseMove := Value;
end;
function TLongInput.GetFOnMouseMove: TMouseMoveEvent;
begin
Result := FMemo.OnMouseMove;
end;
procedure TLongInput.SetFOnMouseUp(const Value: TMouseEvent);
begin
FMemo.OnMouseUp := Value;
end;
function TLongInput.GetFOnMouseUp: TMouseEvent;
begin
Result := FMemo.OnMouseUp;
end;
procedure TLongInput.SetFOnMouseWheel(const Value: TMouseWheelEvent);
begin
FMemo.OnMouseWheel := Value;
end;
function TLongInput.GetFOnMouseWheel: TMouseWheelEvent;
begin
Result := FMemo.OnMouseWheel;
end;
procedure TLongInput.SetFTabNext(const Value: TControl);
begin
FTabNext := Value;
end;
procedure TLongInput.SetFTag(const Value: NativeInt);
begin
FBackground.Tag := Value;
FMemo.Tag := Value;
TControl(Self).Tag := Value;
end;
procedure TLongInput.SetFText(const Value: String);
begin
FMemo.Text := Value;
if not FMemo.Text.Equals('') then
begin
if FTextPromptAnimation then
begin
FLabel.AnimateFloat('Margins.Top', -17, 0, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('Margins.Left', 2, 0, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('TextSettings.Font.Size', FMemo.TextSettings.Font.Size - 2, 0, TAnimationType.InOut,
TInterpolationType.Circular);
end;
if FInvalid then
FLabel.AnimateColor('TextSettings.FontColor', TAlphaColor($FF999999), 0, TAnimationType.InOut,
TInterpolationType.Circular);
end
else
begin
if FTextPromptAnimation then
begin
FLabel.AnimateFloat('Margins.Top', 8, 0, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('Margins.Left', 10, 0, TAnimationType.InOut, TInterpolationType.Circular);
FLabel.AnimateFloat('TextSettings.Font.Size', FMemo.TextSettings.Font.Size, 0, TAnimationType.InOut,
TInterpolationType.Circular);
end;
if not FInvalid then
FLabel.AnimateColor('TextSettings.FontColor', TAlphaColor($FF999999), 0, TAnimationType.InOut,
TInterpolationType.Circular);
end;
end;
function TLongInput.GetFTag: NativeInt;
begin
Result := TControl(Self).Tag;
end;
function TLongInput.GetFText: String;
begin
Result := FMemo.Text;
end;
procedure TLongInput.SetFTextPrompt(const Value: String);
begin
FLabel.Text := Value;
end;
function TLongInput.GetFTextPrompt: String;
begin
Result := FLabel.Text;
end;
procedure TLongInput.SetTextSettings(const Value: TTextSettings);
begin
FMemo.TextSettings := Value;
FChangeTextSettings := True;
end;
function TLongInput.GetTextSettings: TTextSettings;
begin
Result := FMemo.TextSettings;
end;
procedure TLongInput.SetFReadOnly(const Value: Boolean);
begin
FMemo.ReadOnly := Value;
end;
function TLongInput.GetFReadOnly: Boolean;
begin
Result := FMemo.ReadOnly;
end;
{ Protected declarations }
procedure TLongInput.Paint;
begin
inherited;
if FChangeTextSettings then
begin
FLabel.TextSettings := FMemo.TextSettings;
FLabel.TextSettings.FontColor := TAlphaColor($FF999999);
if not Self.Text.Equals('') and FTextPromptAnimation then
FLabel.TextSettings.Font.Size := FLabel.TextSettings.Font.Size - 2;
FChangeTextSettings := False;
end;
end;
{ Repaint }
procedure TLongInput.DoChanged(Sender: TObject);
begin
Repaint;
end;
procedure TLongInput.RefreshCharacterCounter;
begin
FLabelLengthCount.Text := FMemo.Text.Length.ToString + '/' + FMemo.MaxLength.ToString;
end;
procedure TLongInput.EventOnChangeTracking(Sender: TObject);
begin
if not FTextPromptAnimation then
begin
if FMemo.Text.Equals('') then
FLabel.Visible := True
else
FLabel.Visible := False;
end
else
begin
if not FLabel.Visible then
FLabel.Visible := True;
end;
if Self.CharacterCounter then
RefreshCharacterCounter;
if Assigned(FPointerOnChangeTracking) then
FPointerOnChangeTracking(Sender);
end;
procedure TLongInput.FMemoOnApplyStyleLookup(Sender: TObject);
var
Obj: TFmxObject;
Rectangle1: TRectangle;
begin
Obj := FMemo.FindStyleResource('background');
if Obj <> nil then
begin
TControl(Obj).Margins := TBounds.Create(TRectF.Create(-2, -2, -2, -2));
Rectangle1 := TRectangle.Create(Obj);
Obj.AddObject(Rectangle1);
Rectangle1.Align := TAlignLayout.Contents;
Rectangle1.Fill.Color := GetFBackgroudColor;
Rectangle1.Stroke.Kind := TBrushKind.None;
Rectangle1.HitTest := False;
Rectangle1.SendToBack;
end;
end;
{ Public declarations }
constructor TLongInput.Create(AOwner: TComponent);
begin
inherited;
Self.Width := 400;
Self.Height := 120;
FTextPromptAnimation := True;
FChangeTextSettings := True;
FDarkTheme := TAlphaColor($FF2F2F2F);
FLightTheme := TAlphaColor($FFFFFFFF);
{ Backgroud }
FBackground := TRectangle.Create(Self);
Self.AddObject(FBackground);
FBackground.Align := TAlignLayout.Contents;
FBackground.Stroke.Kind := TBrushKind.None;
FBackground.Fill.Color := FLightTheme;
FBackground.XRadius := 4;
FBackground.YRadius := 4;
FBackground.SetSubComponent(True);
FBackground.Stored := False;
FBackground.OnClick := OnFBackgroundClick;
{ Edit }
FMemo := TMemo.Create(Self);
FBackground.AddObject(FMemo);
FMemo.Align := TAlignLayout.Client;
FMemo.Margins.Top := 8;
FMemo.Margins.Bottom := 8;
FMemo.Margins.Left := 8;
FMemo.Margins.Right := 8;
FMemo.StyledSettings := [];
FMemo.TextSettings.Font.Size := 14;
FMemo.TextSettings.Font.Family := 'SF Pro Display';
FMemo.TextSettings.FontColor := TAlphaColor($FF323232);
FMemo.SetSubComponent(True);
FMemo.Stored := False;
FMemo.OnKeyUp := OnKeyUpTabNext;
FMemo.TabStop := False;
FMemo.WordWrap := True;
FMemo.OnEnter := OnEditEnter;
FMemo.OnExit := OnEditExit;
FMemo.OnApplyStyleLookup := FMemoOnApplyStyleLookup;
FMemo.OnChangeTracking := EventOnChangeTracking;
{ Label }
FLabel := TLabel.Create(Self);
FBackground.AddObject(FLabel);
FLabel.Align := TAlignLayout.Client;
FLabel.HitTest := False;
FLabel.Margins.Top := 8;
FLabel.Margins.Bottom := 8;
FLabel.Margins.Left := 10;
FLabel.Margins.Right := 10;
FLabel.StyledSettings := [];
FLabel.TextSettings.Font.Size := 14;
FLabel.TextSettings.Font.Family := 'SF Pro Display';
FLabel.TextSettings.VertAlign := TTextAlign.Leading;
FLabel.SetSubComponent(True);
FLabel.Stored := False;
FLabel.TextSettings.FontColor := TAlphaColor($FF999999);
{ FLabelLengthCount }
FLabelLengthCount := TLabel.Create(Self);
FBackground.AddObject(FLabelLengthCount);
FLabelLengthCount.Align := TAlignLayout.Bottom;
FLabelLengthCount.HitTest := False;
FLabelLengthCount.Margins.Bottom := -19;
FLabelLengthCount.StyledSettings := [];
FLabelLengthCount.TextSettings.Font.Size := 12;
FLabelLengthCount.TextSettings.Font.Family := 'SF Pro Display';
FLabelLengthCount.TextSettings.HorzAlign := TTextAlign.Trailing;
FLabelLengthCount.SetSubComponent(True);
FLabelLengthCount.Stored := False;
FLabelLengthCount.TextSettings.FontColor := TAlphaColor($FF323232);
FLabelLengthCount.Opacity := 0.5;
FLabelLengthCount.Visible := False;
{ Initial settings }
SetFCursor(crIBeam);
end;
destructor TLongInput.Destroy;
begin
if Assigned(FLabelLengthCount) then
FLabelLengthCount.Free;
if Assigned(FLabel) then
FLabel.Free;
if Assigned(FMemo) then
FMemo.Free;
if Assigned(FBackground) then
FBackground.Free;
inherited;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC expression evaluation engine }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Stan.Expr;
interface
uses
System.Classes,
FireDAC.Stan.Intf;
const
C_FD_FAny = Char('*');
C_FD_FAnsi = Char('a');
C_FD_FUni = Char('u');
C_FD_FStr = Char('s');
C_FD_FDate = Char('d');
C_FD_FInt = Char('i');
C_FD_FFloat = Char('f');
C_FD_FNum = Char('n');
type
TFDExpressionFunction = function (const AArgs: array of Variant): Variant;
TFDExpressionFieldFunction = function (const AArgs: array of Variant;
AExpr: IFDStanExpressionEvaluator): Variant;
TFDExpressionFunctionDesc = class (TObject)
private
FName: String;
FScopeKind: TFDExpressionScopeKind;
FScopeKindArg: Integer;
FDataType: TFDDataType;
FDataTypeArg: Integer;
FArgMin: Integer;
FArgMax: Integer;
FArgTypeFamiles: String;
FCall: Pointer;
public
property Name: String read FName;
property ScopeKind: TFDExpressionScopeKind read FScopeKind;
property ScopeKindArg: Integer read FScopeKindArg;
property DataType: TFDDataType read FDataType;
property DataTypeArg: Integer read FDataTypeArg;
property ArgMin: Integer read FArgMin;
property ArgMax: Integer read FArgMax;
property ArgTypeFamiles: String read FArgTypeFamiles;
property Call: Pointer read FCall;
end;
TFDExpressionCompare = function (AStr1: Pointer; ALen1: Integer;
AStr2: Pointer; ALen2: Integer; ANoCase: Boolean): Integer;
TFDExpressionCollation = class
private
FName: String;
FCalls: array [ecUTF8 .. ecANSI] of TFDExpressionCompare;
function GetCall(AEncoding: TFDEncoding): TFDExpressionCompare;
public
property Name: String read FName;
property Calls[AEncoding: TFDEncoding]: TFDExpressionCompare read GetCall;
end;
TFDExpressionManager = class(TObject)
private
FFunctions: TStringList;
FCollations: TStringList;
function GetFunctionCount: Integer;
function GetFunctions(AIndex: Integer): TFDExpressionFunctionDesc;
function GetCollationCount: Integer;
function GetCollations(AIndex: Integer): TFDExpressionCollation;
public
constructor Create;
destructor Destroy; override;
procedure AddSynonym(const AName, ASynonym: String);
procedure AddFunction(const AName: String; AScopeKind: TFDExpressionScopeKind;
AScopeKindArg: Integer; ADataType: TFDDataType; ADataTypeArg: Integer;
AArgMin: Integer; AArgMax: Integer; const AArgTypeFamiles: String; ACall: Pointer);
procedure RemoveFunction(const AName: String);
procedure AddCollation(const AName: String; AEncoding: TFDEncoding;
ACall: TFDExpressionCompare);
procedure RemoveCollation(const AName: String; AEncoding: TFDEncoding);
function FindFunction(const AName: String): Integer;
function FindCollation(const AName: String; AEncoding: TFDEncoding): Integer;
property FunctionCount: Integer read GetFunctionCount;
property Functions[AIndex: Integer]: TFDExpressionFunctionDesc read GetFunctions;
property CollationCount: Integer read GetCollationCount;
property Collations[AIndex: Integer]: TFDExpressionCollation read GetCollations;
end;
function FDStrIsNull(const V: Variant): Boolean;
function FDStrToVar(const S: String): Variant;
function FDExpressionManager(): TFDExpressionManager;
{-------------------------------------------------------------------------------}
implementation
uses
{$IFDEF MSWINDOWS}
// Preventing from "Inline has not expanded"
Winapi.Windows,
{$ENDIF}
System.SysUtils, System.Variants,
FireDAC.Stan.Util, FireDAC.Stan.Error, FireDAC.Stan.Consts, FireDAC.Stan.Factory;
type
TFDExpressionToken = (etEnd, etSymbol, etName, etLiteral, etLParen, etRParen,
etLCBracket, etRCBracket, etEQ, etNE, etGE, etLE, etGT, etLT, etCONCAT, etADD,
etSUB, etMUL, etDIV, etComma, etLIKE, etISNULL, etISNOTNULL, etIN, etNOTIN,
etANY, etSOME, etALL, etNOTLIKE, etBETWEEN, etNOTBETWEEN, etNULL);
TFDExpressionOperator = (canNOTDEFINED, canASSIGN, canOR, canAND, canNOT,
canEQ, canNE, canGE, canLE, canGT, canLT, canLIKE, canISBLANK, canNOTBLANK,
canIN, canCONCAT, canADD, canSUB, canMUL, canDIV, canNOTIN, canANY,
canALL, canNOTLIKE, canBETWEEN, canNOTBETWEEN);
TFDExpressionNodeKind = (enUnknown, enField, enConst, enOperator, enFunc);
PFDExpressionNode = ^TFDExpressionNode;
TFDExpressionNode = record
FNext: PFDExpressionNode;
FLeft: PFDExpressionNode;
FRight: PFDExpressionNode;
FDataType: TFDDataType;
FScopeKind: TFDExpressionScopeKind;
FKind: TFDExpressionNodeKind;
FOperator: TFDExpressionOperator;
FData: Variant;
FFuncInd: Integer;
FFuncArgs: array of Variant;
FColumnInd: Integer;
FArgs: array of PFDExpressionNode;
FPartial: Boolean;
end;
TFDExpression = class(TInterfacedObject, IFDStanExpressionEvaluator)
private
FRoot, FNodes: PFDExpressionNode;
FSubAggregates: array of PFDExpressionNode;
FDataSource: IFDStanExpressionDataSource;
FOptions: TFDExpressionOptions;
function NewNode(AKind: TFDExpressionNodeKind; AOperator: TFDExpressionOperator;
const AData: Variant; ALeft, ARight: PFDExpressionNode;
AFuncInd: Integer): PFDExpressionNode;
procedure ClearNodes;
function InternalEvaluate(ANode: PFDExpressionNode): Variant;
protected
// IFDStanExpressionEvaluator
function HandleNotification(AKind, AReason: Word; AParam1, AParam2: NativeInt): Boolean;
function Evaluate: Variant;
function GetSubAggregateCount: Integer;
function GetSubAggregateKind(AIndex: Integer): TFDAggregateKind;
function EvaluateSubAggregateArg(AIndex: Integer): Variant;
function GetDataSource: IFDStanExpressionDataSource;
function GetDataType: TFDDataType;
public
constructor Create(AOptions: TFDExpressionOptions;
const ADataSource: IFDStanExpressionDataSource);
{$IFDEF FireDAC_DEBUG}
procedure Dump(AStrs: TStrings);
{$ENDIF}
destructor Destroy; override;
end;
TFDExprParserBmk = record
FSourcePtr: PChar;
FToken: TFDExpressionToken;
FTokenString: String;
FCurPtr: PChar;
end;
TFDExpressionParser = class(TFDObject, IFDStanExpressionParser)
private
FExpression: TFDExpression;
FText: String;
FSourcePtr: PChar;
FTokenPtr: PChar;
FTokenString: String;
FUCTokenString: String;
FToken: TFDExpressionToken;
FLiteralType: TFDDataType;
FLiteralValue: Variant;
FParserOptions: TFDParserOptions;
FDataSource: IFDStanExpressionDataSource;
FFixedColumnName: String;
class function IsBinary(DataType: TFDDataType): Boolean; static;
class function IsBoolean(DataType: TFDDataType): Boolean; static;
class function IsNumeric(DataType: TFDDataType): Boolean; static;
class function IsString(DataType: TFDDataType): Boolean; static;
class function IsTemporal(DataType: TFDDataType): Boolean; static;
procedure NextToken;
function ParseExpr: PFDExpressionNode;
function ParseExpr2: PFDExpressionNode;
function ParseExpr3: PFDExpressionNode;
function ParseExpr4: PFDExpressionNode;
function ParseExpr5(AEnableList: Boolean): PFDExpressionNode;
function ParseExpr6: PFDExpressionNode;
function ParseExpr7: PFDExpressionNode;
function TokenName: String;
function TokenSymbolIs(const S: String): Boolean;
function TokenSymbolPartialIs(const S: String): Boolean;
function TokenSymbolIsFunc(const S: String): Integer;
procedure GetFuncResultInfo(Node: PFDExpressionNode);
procedure TypeCheckArithOp(Node: PFDExpressionNode);
procedure GetScopeKind(Root, Left, Right : PFDExpressionNode);
procedure SaveState(out ABmk: TFDExprParserBmk; ACurPtr: PChar);
procedure RestoreState(const ABmk: TFDExprParserBmk; out ACurPtr: PChar);
procedure FixupFieldNode(ANode: PFDExpressionNode; const AColumnName: String);
protected
// IFDStanExpressionParser
function Prepare(const ADataSource: IFDStanExpressionDataSource;
const AExpression: String; AOptions: TFDExpressionOptions;
AParserOptions: TFDParserOptions; const AFixedColumnName: String): IFDStanExpressionEvaluator;
function GetDataSource: IFDStanExpressionDataSource;
end;
var
rDateTimeFS: TFormatSettings;
{-------------------------------------------------------------------------------}
{ Standard functions }
{-------------------------------------------------------------------------------}
function FDStrIsNull(const V: Variant): Boolean;
var
tp: Integer;
begin
tp := (VarType(V) and varTypeMask);
Result := (tp = varEmpty) or (tp = varNull) or
((tp = varUString) or (tp = varString) or (tp = varOleStr)) and (V = '');
end;
{-------------------------------------------------------------------------------}
function FDStrToVar(const S: String): Variant;
begin
if S = '' then
Result := Null
else
Result := S;
end;
{-------------------------------------------------------------------------------}
function FunLike(const AStr, AMask: Variant; ANoCase: Boolean;
AManyCharsMask, AOneCharMask, AEscapeChar: Char): Variant;
begin
if VarIsNull(AStr) or VarIsNull(AMask) then
Result := False
else
Result := FDStrLike(AStr, AMask, ANoCase, AManyCharsMask, AOneCharMask, AEscapeChar);
end;
{-------------------------------------------------------------------------------}
function FunUpper(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := AnsiUpperCase(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunLower(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := AnsiLowerCase(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunSubstring(const AArgs: array of Variant): Variant;
var
s: String;
ind, cnt: Integer;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else begin
s := AArgs[0];
ind := AArgs[1];
if ind < 0 then
ind := Length(s) + ind + 1;
if Length(AArgs) = 2 then
cnt := Length(s)
else if FDStrIsNull(AArgs[2]) or (AArgs[2] <= 0) then begin
Result := Null;
Exit;
end
else
cnt := AArgs[2];
Result := FDStrToVar(Copy(s, ind, cnt));
end;
end;
{-------------------------------------------------------------------------------}
type
TFDTrimMode = set of (tmLeft, tmRight);
function InternalTrim(const AArgs: array of Variant; AMode: TFDTrimMode): Variant;
var
I, L: Integer;
sWhere, sWhat: String;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
sWhere := AArgs[0];
if Length(AArgs) = 2 then begin
if FDStrIsNull(AArgs[1]) then begin
Result := Null;
Exit;
end
else
sWhat := AArgs[1];
end
else
sWhat := ' ';
L := Length(sWhere);
I := 1;
if tmLeft in AMode then
while (I <= L) and (StrScan(PChar(sWhat), sWhere[I]) <> nil) do
Inc(I);
if I > L then
sWhere := ''
else begin
if tmRight in AMode then
while (L >= I) and (StrScan(PChar(sWhat), sWhere[L]) <> nil) do
Dec(L);
sWhere := Copy(sWhere, I, L - I + 1);
end;
Result := FDStrToVar(sWhere);
end;
end;
{-------------------------------------------------------------------------------}
function FunTrim(const AArgs: array of Variant): Variant;
begin
Result := InternalTrim(AArgs, [tmLeft, tmRight]);
end;
{-------------------------------------------------------------------------------}
function FunTrimLeft(const AArgs: array of Variant): Variant;
begin
Result := InternalTrim(AArgs, [tmLeft]);
end;
{-------------------------------------------------------------------------------}
function FunTrimRight(const AArgs: array of Variant): Variant;
begin
Result := InternalTrim(AArgs, [tmRight]);
end;
{-------------------------------------------------------------------------------}
function FunYear(const AArgs: array of Variant): Variant;
var
Y, M, D: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Y := 0;
M := 0;
D := 0;
DecodeDate(AArgs[0], Y, M, D);
Result := Y;
end;
end;
{-------------------------------------------------------------------------------}
function FunMonth(const AArgs: array of Variant): Variant;
var
Y, M, D: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Y := 0;
M := 0;
D := 0;
DecodeDate(AArgs[0], Y, M, D);
Result := M;
end;
end;
{-------------------------------------------------------------------------------}
function FunDay(const AArgs: array of Variant): Variant;
var
Y, M, D: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Y := 0;
M := 0;
D := 0;
DecodeDate(AArgs[0], Y, M, D);
Result := D;
end;
end;
{-------------------------------------------------------------------------------}
function FunHour(const AArgs: array of Variant): Variant;
var
H, M, S, MS: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
H := 0;
M := 0;
S := 0;
MS := 0;
DecodeTime(AArgs[0], H, M, S, MS);
Result := H;
end;
end;
{-------------------------------------------------------------------------------}
function FunMinute(const AArgs: array of Variant): Variant;
var
H, M, S, MS: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
H := 0;
M := 0;
S := 0;
MS := 0;
DecodeTime(AArgs[0], H, M, S, MS);
Result := M;
end;
end;
{-------------------------------------------------------------------------------}
function FunSecond(const AArgs: array of Variant): Variant;
var
H, M, S, MS: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
H := 0;
M := 0;
S := 0;
MS := 0;
DecodeTime(AArgs[0], H, M, S, MS);
Result := S;
end;
end;
{-------------------------------------------------------------------------------}
function FunGetDate(const AArgs: array of Variant): Variant;
begin
Result := Now;
end;
{-------------------------------------------------------------------------------}
function FunDate(const AArgs: array of Variant): Variant;
var
d: Double;
V: Variant;
tp: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
V := AArgs[0];
tp := VarType(V);
if (tp = varString) or (tp = varOleStr) or (tp = varUString) then
Result := StrToDate(V)
else begin
d := Trunc(Double(V));
Result := TDateTime(d);
end;
end;
end;
{-------------------------------------------------------------------------------}
function FunTime(const AArgs: array of Variant): Variant;
var
dt: TDateTime;
V: Variant;
tp: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
V := AArgs[0];
tp := VarType(V);
if (tp = varString) or (tp = varOleStr) or (tp = varUString) then
Result := StrToTime(V)
else begin
dt := V;
Result := dt - Trunc(dt);
end;
end;
end;
{-------------------------------------------------------------------------------}
function FunCmpFileName(const AArgs: array of Variant): Variant;
var
sName1, sName2, sFile1, sFile2, sExt1, sExt2: String;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := False
else begin
sName1 := AArgs[0];
sName2 := AArgs[1];
sFile1 := FDExtractFileNameNoPath(sName1);
sFile2 := FDExtractFileNameNoPath(sName2);
sExt1 := ExtractFileExt(sName1);
sExt2 := ExtractFileExt(sName2);
Result := (CompareText(sFile1, sFile2) = 0) and
((sExt1 = '') or (CompareText(sExt1, sExt2) = 0));
end;
end;
{-------------------------------------------------------------------------------}
function FunCmpFilePath(const AArgs: array of Variant): Variant;
var
sPath1, sPath2: String;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := False
else begin
sPath1 := FDNormPath(AArgs[0]);
sPath2 := FDNormPath(AArgs[1]);
Result := (sPath1 = '') or (CompareText(sPath1, sPath2) = 0);
end;
end;
{-------------------------------------------------------------------------------}
function FunAggSum(const AArgs: array of Variant): Variant;
begin
Result := akSum;
end;
{-------------------------------------------------------------------------------}
function FunAggAvg(const AArgs: array of Variant): Variant;
begin
Result := akAvg;
end;
{-------------------------------------------------------------------------------}
function FunAggCount(const AArgs: array of Variant): Variant;
begin
Result := akCount;
end;
{-------------------------------------------------------------------------------}
function FunAggMin(const AArgs: array of Variant): Variant;
begin
Result := akMin;
end;
{-------------------------------------------------------------------------------}
function FunAggMax(const AArgs: array of Variant): Variant;
begin
Result := akMax;
end;
{-------------------------------------------------------------------------------}
function FunAggFirst(const AArgs: array of Variant): Variant;
begin
Result := akFirst;
end;
{-------------------------------------------------------------------------------}
function FunAggLast(const AArgs: array of Variant): Variant;
begin
Result := akLast;
end;
{-------------------------------------------------------------------------------}
function FunIIF(const AArgs: array of Variant): Variant;
begin
// it is handled internally by evaluator
Result := Unassigned;
ASSERT(False);
end;
{-------------------------------------------------------------------------------}
{ TFDExpression }
{-------------------------------------------------------------------------------}
constructor TFDExpression.Create(AOptions: TFDExpressionOptions;
const ADataSource: IFDStanExpressionDataSource);
begin
inherited Create;
FOptions := AOptions;
FDataSource := ADataSource;
FSubAggregates := nil;
end;
{-------------------------------------------------------------------------------}
destructor TFDExpression.Destroy;
begin
ClearNodes;
FSubAggregates := nil;
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDExpression.GetSubAggregateCount: Integer;
begin
Result := Length(FSubAggregates);
end;
{-------------------------------------------------------------------------------}
function TFDExpression.GetSubAggregateKind(AIndex: Integer): TFDAggregateKind;
var
pNode: PFDExpressionNode;
pFunc: TFDExpressionFunctionDesc;
begin
pNode := FSubAggregates[AIndex];
pFunc := FDExpressionManager().Functions[pNode^.FFuncInd];
Result := TFDExpressionFunction(pFunc.FCall)([]);
end;
{-------------------------------------------------------------------------------}
function TFDExpression.HandleNotification(AKind, AReason: Word; AParam1, AParam2: NativeInt): Boolean;
begin
Result := False;
end;
{-------------------------------------------------------------------------------}
function TFDExpression.GetDataSource: IFDStanExpressionDataSource;
begin
Result := FDataSource;
end;
{-------------------------------------------------------------------------------}
function TFDExpression.GetDataType: TFDDataType;
begin
Result := FRoot^.FDataType;
end;
{-------------------------------------------------------------------------------}
function TFDExpression.NewNode(AKind: TFDExpressionNodeKind;
AOperator: TFDExpressionOperator; const AData: Variant;
ALeft, ARight: PFDExpressionNode; AFuncInd: Integer): PFDExpressionNode;
begin
New(Result);
Result^.FNext := FNodes;
Result^.FKind := AKind;
Result^.FOperator := AOperator;
Result^.FData := AData;
Result^.FLeft := ALeft;
Result^.FRight := ARight;
SetLength(Result^.FArgs, 0);
Result^.FDataType := dtUnknown;
Result^.FScopeKind := ckUnknown;
Result^.FFuncInd := AFuncInd;
SetLength(Result^.FFuncArgs, 0);
Result^.FColumnInd := -1;
Result^.FPartial := False;
if (AKind = enFunc) and (FDExpressionManager().Functions[AFuncInd].FScopeKind = ckAgg) then begin
SetLength(FSubAggregates, Length(FSubAggregates) + 1);
FSubAggregates[Length(FSubAggregates) - 1] := Result;
end;
FNodes := Result;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpression.ClearNodes;
var
Node: PFDExpressionNode;
begin
FSubAggregates := nil;
while FNodes <> nil do begin
Node := FNodes;
FNodes := Node^.FNext;
Dispose(Node);
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpression.InternalEvaluate(ANode: PFDExpressionNode): Variant;
var
l, r: Variant;
i: Integer;
pR: PFDExpressionNode;
esc: String;
pFunc: TFDExpressionFunctionDesc;
procedure EvalError(const AMsg: String);
begin
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprEvalError, [AMsg]);
end;
function VarIsString(const V: Variant): Boolean;
var
tp: Integer;
begin
tp := VarType(V);
Result := (tp = varString) or (tp = varOleStr) or (tp = varUString);
end;
procedure UpperCaseLR;
begin
if VarIsString(l) then
l := AnsiUpperCase(l);
if VarIsString(r) then
r := AnsiUpperCase(r);
end;
function PartialEQ(AForce: Boolean): Boolean;
var
sL, sR: String;
ln, lnL, lnR: Integer;
partial: Boolean;
begin
if VarIsString(l) and VarIsString(r) then begin
sL := l;
sR := r;
lnL := Length(sL);
lnR := Length(sR);
if l <> '' then begin
partial := False;
if sL[lnL] = '*' then begin
partial := True;
Dec(lnL);
end;
if r <> '' then begin
if sR[lnR] = '*' then begin
partial := True;
Dec(lnR);
end;
if partial or AForce then begin
ln := lnR;
if ln > lnL then
ln := lnL;
if lnL < lnR then
Result := False
else if (ekNoCase in FOptions) then
Result := ({$IFDEF FireDAC_NOLOCALE_DATA} StrLIComp {$ELSE} AnsiStrLIComp {$ENDIF}
(PChar(sL), PChar(sR), ln) = 0)
else
Result := ({$IFDEF FireDAC_NOLOCALE_DATA} StrLComp {$ELSE} AnsiStrLComp {$ENDIF}
(PChar(sL), PChar(sR), ln) = 0);
Exit;
end;
end;
end;
if (ekNoCase in FOptions) then
Result := ({$IFDEF FireDAC_NOLOCALE_DATA} CompareText {$ELSE} AnsiCompareText {$ENDIF}
(sL, sR) = 0)
else
Result := ({$IFDEF FireDAC_NOLOCALE_DATA} CompareStr {$ELSE} AnsiCompareStr {$ENDIF}
(sL, sR) = 0);
end
else begin
UpperCaseLR;
Result := l = r;
end;
end;
function EvaluteNodeValue(ANode: PFDExpressionNode): Variant;
begin
if ANode^.FKind = enField then
Result := FDataSource.VarData[ANode^.FColumnInd]
else if ANode^.FKind = enConst then
Result := ANode^.FData
else
Result := InternalEvaluate(ANode);
end;
begin
try
case ANode^.FKind of
enUnknown:
;
enField:
Result := FDataSource.VarData[ANode^.FColumnInd];
enConst:
Result := ANode^.FData;
enOperator:
case ANode^.FOperator of
canNOTDEFINED:
;
canASSIGN:
FDataSource.VarData[ANode^.FRight^.FColumnInd] := EvaluteNodeValue(ANode^.FLeft);
canOR:
Result := Boolean(EvaluteNodeValue(ANode^.FLeft)) or Boolean(EvaluteNodeValue(ANode^.FRight));
canAND:
Result := Boolean(EvaluteNodeValue(ANode^.FLeft)) and Boolean(EvaluteNodeValue(ANode^.FRight));
canNOT:
Result := not Boolean(EvaluteNodeValue(ANode^.FLeft));
canEQ, canNE, canGE, canLE, canGT, canLT:
begin
l := EvaluteNodeValue(ANode^.FLeft);
pR := ANode^.FRight;
if pR^.FOperator in [canANY, canALL] then begin
for i := 0 to Length(pR^.FArgs) - 1 do begin
r := EvaluteNodeValue(pR^.FArgs[i]);
if (ekNoCase in FOptions) and not ((ANode^.FOperator = canEQ) and (ekPartial in FOptions)) then
UpperCaseLR;
case ANode^.FOperator of
canEQ:
if ekPartial in FOptions then
Result := PartialEQ(ANode^.FPartial)
else
Result := l = r;
canNE: Result := l <> r;
canGE: Result := l >= r;
canLE: Result := l <= r;
canGT: Result := l > r;
canLT: Result := l < r;
end;
if (pR^.FOperator = canANY) and Result or
(pR^.FOperator = canALL) and not Result then
Break;
end;
end
else begin
r := EvaluteNodeValue(ANode^.FRight);
if (ekNoCase in FOptions) and not ((ANode^.FOperator in [canEQ, canNE]) and (ekPartial in FOptions)) then
UpperCaseLR;
case ANode^.FOperator of
canEQ:
if ekPartial in FOptions then
Result := PartialEQ(ANode^.FPartial)
else
Result := l = r;
canNE:
if ekPartial in FOptions then
Result := not PartialEQ(ANode^.FPartial)
else
Result := l <> r;
canGE: Result := l >= r;
canLE: Result := l <= r;
canGT: Result := l > r;
canLT: Result := l < r;
end;
end;
end;
canLIKE, canNOTLIKE:
begin
if Length(ANode^.FArgs) > 0 then
esc := EvaluteNodeValue(ANode^.FArgs[0])
else
esc := #9;
Result := FunLike(EvaluteNodeValue(ANode^.FLeft), EvaluteNodeValue(ANode^.FRight),
ekNoCase in FOptions, '%', '_', esc[1]);
if ANode^.FOperator = canNOTLIKE then
Result := not Result;
end;
canISBLANK, canNOTBLANK:
begin
if ANode^.FLeft^.FKind = enField then
Result := FDStrIsNull(FDataSource.VarData[ANode^.FLeft^.FColumnInd])
else
Result := FDStrIsNull(EvaluteNodeValue(ANode^.FLeft));
if ANode^.FOperator = canNOTBLANK then
Result := not Result;
end;
canIN, canNOTIN:
begin
Result := False;
l := EvaluteNodeValue(ANode^.FLeft);
for i := 0 to Length(ANode^.FArgs) - 1 do
if l = EvaluteNodeValue(ANode^.FArgs[i]) then begin
Result := True;
Break;
end;
if ANode^.FOperator = canNOTIN then
Result := not Result;
end;
canCONCAT, canADD:
Result := EvaluteNodeValue(ANode^.FLeft) + EvaluteNodeValue(ANode^.FRight);
canSUB:
Result := EvaluteNodeValue(ANode^.FLeft) - EvaluteNodeValue(ANode^.FRight);
canMUL:
Result := EvaluteNodeValue(ANode^.FLeft) * EvaluteNodeValue(ANode^.FRight);
canDIV:
Result := EvaluteNodeValue(ANode^.FLeft) / EvaluteNodeValue(ANode^.FRight);
canBETWEEN, canNOTBETWEEN:
begin
l := EvaluteNodeValue(ANode^.FLeft);
Result := (l >= EvaluteNodeValue(ANode^.FArgs[0])) and
(l <= EvaluteNodeValue(ANode^.FArgs[1]));
if ANode^.FOperator = canNOTBETWEEN then
Result := not Result;
end;
end;
enFunc:
begin
pFunc := FDExpressionManager().Functions[ANode^.FFuncInd];
if pFunc.FScopeKind = ckAgg then
Result := FDataSource.SubAggregateValue[FDIndexOf(Pointer(FSubAggregates), -1, ANode)]
else if pFunc.FCall = @FunIIF then begin
r := EvaluteNodeValue(ANode^.FArgs[0]);
if FDStrIsNull(r) then
Result := Null
else if r then
Result := EvaluteNodeValue(ANode^.FArgs[1])
else
Result := EvaluteNodeValue(ANode^.FArgs[2]);
end
else begin
for i := 0 to Length(ANode^.FArgs) - 1 do
ANode^.FFuncArgs[i] := EvaluteNodeValue(ANode^.FArgs[i]);
if pFunc.FScopeKind = ckField then
Result := TFDExpressionFieldFunction(pFunc.FCall)(ANode^.FFuncArgs, Self)
else
Result := TFDExpressionFunction(pFunc.FCall)(ANode^.FFuncArgs);
end;
end;
end;
except
on E: Exception do
if E is EFDException then
raise
else
EvalError(E.Message);
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpression.Evaluate: Variant;
begin
Result := InternalEvaluate(FRoot);
end;
{-------------------------------------------------------------------------------}
function TFDExpression.EvaluateSubAggregateArg(AIndex: Integer): Variant;
var
pNode: PFDExpressionNode;
begin
pNode := FSubAggregates[AIndex];
if Length(pNode^.FArgs) = 0 then
Result := '*'
else
Result := InternalEvaluate(pNode^.FArgs[0]);
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_DEBUG}
procedure TFDExpression.Dump(AStrs: TStrings);
const
enk2s: array[TFDExpressionNodeKind] of String = (
'enUnknown', 'enField', 'enConst', 'enOperator', 'enFunc');
bool2s: array[Boolean] of String = (
'False', 'True');
esk2s: array[TFDExpressionScopeKind] of String = (
'ckUnknown', 'ckField', 'ckAgg', 'ckConst'
);
co2s: array[TFDExpressionOperator] of String = (
'canNOTDEFINED', 'canASSIGN', 'canOR', 'canAND', 'canNOT', 'canEQ', 'canNE',
'canGE', 'canLE', 'canGT', 'canLT', 'canLIKE', 'canISBLANK', 'canNOTBLANK',
'canIN', 'canCONCAT', 'canADD', 'canSUB', 'canMUL', 'canDIV', 'canNOTIN',
'canANY', 'canALL', 'canNOTLIKE', 'canBETWEEN', 'canNOTBETWEEN'
);
function Var2Text(const AValue: Variant): String;
begin
if VarIsEmpty(AValue) then
Result := 'Unassigned'
else if VarIsNull(AValue) then
Result := 'Null'
else
Result := AValue;
end;
procedure DumpNode(ANode: PFDExpressionNode; AIndent: Integer; AList: TStrings);
var
st: String;
i: Integer;
begin
st := '';
for i := 1 to AIndent do
st := st + ' ';
AList.Add(st +
'FKind: ' + enk2s[ANode^.FKind] + ' ' +
'FOper: ' + co2s[ANode^.FOperator] + ' ' +
'FData tp: ' + IntToStr(VarType(ANode^.FData)) + ' ' +
'FData vl: ' + Var2Text(ANode^.FData) + ' ' +
'FDataType: ' + C_FD_DataTypeNames[ANode^.FDataType] + ' ' +
'FScopeKind: ' + esk2s[ANode^.FScopeKind]
);
if Length(ANode^.FArgs) > 0 then begin
AList.Add(st + 'ARGS:');
for i := 0 to Length(ANode^.FArgs) - 1 do
DumpNode(ANode^.FArgs[i], AIndent + 2, AList);
end;
if ANode^.FLeft <> nil then begin
AList.Add(st + 'LEFT:');
DumpNode(ANode^.FLeft, AIndent + 2, AList);
end;
if ANode^.FRight <> nil then begin
AList.Add(st + 'RIGHT:');
DumpNode(ANode^.FRight, AIndent + 2, AList);
end;
end;
begin
AStrs.Clear;
if FRoot <> nil then
DumpNode(FRoot, 0, AStrs)
else
AStrs.Add('-= EMPTY =-');
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
{ TFDExpressionParser }
{-------------------------------------------------------------------------------}
class function TFDExpressionParser.IsNumeric(DataType: TFDDataType): Boolean;
begin
Result := DataType in [
dtSByte, dtInt16, dtInt32, dtInt64,
dtByte, dtUInt16, dtUInt32, dtUInt64,
dtSingle, dtDouble, dtExtended, dtCurrency, dtBCD, dtFmtBCD];
end;
{-------------------------------------------------------------------------------}
class function TFDExpressionParser.IsTemporal(DataType: TFDDataType): Boolean;
begin
Result := DataType in [dtDateTime, dtTime, dtDate, dtDateTimeStamp,
dtTimeIntervalFull, dtTimeIntervalYM, dtTimeIntervalDS];
end;
{-------------------------------------------------------------------------------}
class function TFDExpressionParser.IsString(DataType: TFDDataType): Boolean;
begin
Result := DataType in (C_FD_CharTypes + [dtGUID]);
end;
{-------------------------------------------------------------------------------}
class function TFDExpressionParser.IsBinary(DataType: TFDDataType): Boolean;
begin
Result := DataType in (C_FD_BlobTypes - C_FD_CharTypes + [dtByteString]);
end;
{-------------------------------------------------------------------------------}
class function TFDExpressionParser.IsBoolean(DataType: TFDDataType): Boolean;
begin
Result := DataType = dtBoolean;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.Prepare(const ADataSource: IFDStanExpressionDataSource;
const AExpression: String; AOptions: TFDExpressionOptions;
AParserOptions: TFDParserOptions; const AFixedColumnName: String):
IFDStanExpressionEvaluator;
var
Root, DefField: PFDExpressionNode;
begin
if AExpression = '' then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprEmpty, []);
FExpression := TFDExpression.Create(AOptions, ADataSource);
try
FFixedColumnName := AFixedColumnName;
FDataSource := ADataSource;
FParserOptions := AParserOptions;
FText := AExpression;
FSourcePtr := PChar(FText);
NextToken;
Root := ParseExpr;
if FToken <> etEnd then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTermination, []);
if (poAggregate in FParserOptions) and (Root^.FScopeKind <> ckAgg) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprMBAgg, []);
if (not (poAggregate in FParserOptions)) and (Root^.FScopeKind = ckAgg) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprCantAgg, []);
if (poDefaultExpr in FParserOptions) and (AFixedColumnName <> '') then begin
DefField := FExpression.NewNode(enField, canNOTDEFINED, AFixedColumnName,
nil, nil, -1);
FixupFieldNode(DefField, AFixedColumnName);
if IsTemporal(DefField^.FDataType) and IsString(Root^.FDataType) or
IsBoolean(DefField^.FDataType) and IsString(Root^.FDataType) then
Root^.FDataType := DefField^.FDataType;
if not (
(Root^.FDataType = dtUnknown) or
(Root^.FKind = enConst) and VarIsNull(Root^.FData) or
IsTemporal(DefField^.FDataType) and IsTemporal(Root^.FDataType) or
IsNumeric(DefField^.FDataType) and IsNumeric(Root^.FDataType) or
IsString(DefField^.FDataType) and IsString(Root^.FDataType) or
IsBoolean(DefField^.FDataType) and IsBoolean(Root^.FDataType)
) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTypeMis, []);
Root := FExpression.NewNode(enOperator, canASSIGN, Unassigned, Root,
DefField, -1);
end;
if not ((poAggregate in FParserOptions) or (poDefaultExpr in FParserOptions) or
IsBoolean(Root^.FDataType)) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprIncorrect, []);
FExpression.FRoot := Root;
Result := FExpression;
except
FDFreeAndNil(FExpression);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.GetDataSource: IFDStanExpressionDataSource;
begin
Result := FDataSource;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.FixupFieldNode(ANode: PFDExpressionNode; const AColumnName: String);
begin
if ANode^.FKind = enField then begin
if poFieldNameGiven in FParserOptions then
ANode^.FColumnInd := FDataSource.VarIndex[FFixedColumnName];
if ANode^.FColumnInd = -1 then
ANode^.FColumnInd := FDataSource.VarIndex[AColumnName];
if ANode^.FColumnInd = -1 then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ColumnDoesnotFound,
[AColumnName]);
ANode^.FDataType := FDataSource.VarType[ANode^.FColumnInd];
ANode^.FScopeKind := FDataSource.VarScope[ANode^.FColumnInd];
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.SaveState(out ABmk: TFDExprParserBmk; ACurPtr: PChar);
begin
ABmk.FSourcePtr := FSourcePtr;
ABmk.FToken := FToken;
ABmk.FTokenString := FTokenString;
ABmk.FCurPtr := ACurPtr;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.RestoreState(const ABmk: TFDExprParserBmk; out ACurPtr: PChar);
begin
FSourcePtr := ABmk.FSourcePtr;
FToken := ABmk.FToken;
FTokenString := ABmk.FTokenString;
FUCTokenString := UpperCase(ABmk.FTokenString);
ACurPtr := ABmk.FCurPtr;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.NextToken;
var
P, TokenStart: PChar;
L: Integer;
StrBuf: array[0..255] of Char;
PrevToken: TFDExpressionToken;
PrevTokenStr: String;
ch2: Char;
sign: Double;
bmk: TFDExprParserBmk;
procedure Skip(ASet: TFDCharSet);
begin
while (P^ <> #0) and FDInSet(P^, ASet) do
Inc(P);
end;
procedure SkipWS;
begin
while (P^ <> #0) and (P^ <= ' ') do
Inc(P);
end;
procedure SkpiWhileNot(ASet: TFDCharSet);
begin
while (P^ <> #0) and not FDInSet(P^, ASet) do
Inc(P);
end;
procedure ExtractToken(ASet: TFDCharSet);
begin
SkipWS;
TokenStart := P;
Skip(ASet);
SetString(FTokenString, TokenStart, P - TokenStart);
FUCTokenString := AnsiUpperCase(FTokenString);
end;
procedure ExtractWord;
begin
ExtractToken(['A'..'Z', 'a'..'z']);
end;
begin
PrevToken := FToken;
PrevTokenStr := FUCTokenString;
FTokenString := '';
P := FSourcePtr;
SkipWS;
// /* comment */
if (P^ <> #0) and (P^ = '/') and (P[1] <> #0) and (P[1] = '*') then begin
Inc(P, 2);
SkpiWhileNot(['*']);
if (P^ = '*') and (P[1] <> #0) and (P[1] = '/') then
Inc(P, 2)
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprInvalidChar,
[String(P)]);
end
// -- comment
else if (P^ <> #0) and (P^ = '-') and (P[1] <> #0) and (P[1] = '-') then begin
Inc(P, 2);
SkpiWhileNot([#13, #10]);
end;
SkipWS;
FTokenPtr := P;
case P^ of
'A'..'Z', 'a'..'z':
begin
ExtractToken(['A'..'Z', 'a'..'z', '0'..'9', '$', '#', '_', '.']);
FToken := etSymbol;
if FUCTokenString = 'NOT' then begin
SaveState(bmk, P);
ExtractWord;
if FUCTokenString = 'IN' then
FToken := etNOTIN
else if FUCTokenString = 'LIKE' then
FToken := etNOTLIKE
else if FUCTokenString = 'BETWEEN' then
FToken := etNOTBETWEEN
else
RestoreState(bmk, P);
end
else if FUCTokenString = 'LIKE' then
FToken := etLIKE
else if FUCTokenString = 'IN' then
FToken := etIN
else if FUCTokenString = 'ANY' then
FToken := etANY
else if FUCTokenString = 'SOME' then
FToken := etSOME
else if FUCTokenString = 'ALL' then
FToken := etALL
else if FUCTokenString = 'BETWEEN' then
FToken := etBETWEEN
else if FUCTokenString = 'IS' then begin
ExtractWord;
if FUCTokenString = 'NOT' then begin
ExtractWord;
if FUCTokenString = 'NULL' then
FToken := etISNOTNULL;
end
else if FUCTokenString = 'NULL' then
FToken := etISNULL;
if FToken = etSYMBOL then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_InvalidKeywordUse, []);
end
else if FUCTokenString = 'NULL' then
FToken := etNULL;
end;
'[', '"', '`':
begin
if P^ = '[' then
ch2 := ']'
else
ch2 := P^;
Inc(P);
TokenStart := P;
P := AnsiStrScan(P, ch2);
if P = nil then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNameError, []);
SetString(FTokenString, TokenStart, P - TokenStart);
FToken := etName;
Inc(P);
end;
'''':
begin
Inc(P);
L := 0;
while True do begin
if P^ = #0 then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprStringError, []);
if P^ = '''' then begin
Inc(P);
if P^ <> '''' then
Break;
end;
if L <= High(StrBuf) then begin
StrBuf[L] := P^;
Inc(L);
end
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprStringError, []);
Inc(P);
end;
SetString(FTokenString, StrBuf, L);
FToken := etLiteral;
FLiteralType := dtAnsiString;
FLiteralValue := FTokenString;
end;
'-', '+', '0'..'9', '.':
begin
if (PrevToken <> etLiteral) and (PrevToken <> etName) and
((PrevToken <> etSymbol) or (PrevTokenStr = 'AND')) and
(PrevToken <> etRParen) then begin
if P^ = '-' then begin
sign := -1;
Inc(P);
end
else if P^ = '+' then begin
sign := 1;
Inc(P);
end
else
sign := 1;
ExtractToken(['0'..'9', '.']);
FToken := etLiteral;
FLiteralType := dtDouble;
FLiteralValue := FDStr2Float(FTokenString, '.') * sign;
end
else if P^ = '+' then begin
Inc(P);
FToken := etADD;
end
else if P^ = '-' then begin
FToken := etSUB;
Inc(P);
end
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprInvalidChar,
[String(P)]);
end;
'(':
begin
Inc(P);
FToken := etLParen;
end;
')':
begin
Inc(P);
FToken := etRParen;
end;
'<':
begin
Inc(P);
case P^ of
'=':
begin
Inc(P);
FToken := etLE;
end;
'>':
begin
Inc(P);
FToken := etNE;
end;
else
FToken := etLT;
end;
end;
'^', '!':
begin
Inc(P);
if P^ = '=' then begin
Inc(P);
FToken := etNE;
end
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprInvalidChar,
[String(P)]);
end;
'=':
begin
Inc(P);
FToken := etEQ;
end;
'>':
begin
Inc(P);
if P^ = '=' then begin
Inc(P);
FToken := etGE;
end
else
FToken := etGT;
end;
'|':
begin
Inc(P);
if P^ = '|' then begin
Inc(P);
FToken := etCONCAT;
end
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprInvalidChar,
[String(P)]);
end;
'*':
begin
Inc(P);
FToken := etMUL;
end;
'/':
begin
Inc(P);
FToken := etDIV;
end;
',':
begin
Inc(P);
FToken := etComma;
end;
'{':
begin
SaveState(bmk, P);
FToken := etLiteral;
Inc(P);
ExtractWord;
if FUCTokenString = 'D' then
FLiteralType := dtDate
else if FUCTokenString = 'T' then
FLiteralType := dtTime
else if FUCTokenString = 'DT' then
FLiteralType := dtDateTime
else if FUCTokenString = 'E' then
FLiteralType := dtDouble
else if FUCTokenString = 'L' then
FLiteralType := dtBoolean
else if FUCTokenString = 'S' then
FLiteralType := dtAnsiString
else if FUCTokenString = 'ID' then
FToken := etName
else if FUCTokenString = 'FN' then
FToken := etLCBracket
else begin
RestoreState(bmk, P);
FToken := etLCBracket;
end;
if FToken <> etLCBracket then begin
SkipWS;
TokenStart := P;
P := AnsiStrScan(P, '}');
if P = nil then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTermination, []);
SetString(FTokenString, TokenStart, P - TokenStart);
if FToken = etLiteral then begin
case FLiteralType of
dtDateTime: FLiteralValue := StrToDateTime(FTokenString, rDateTimeFS);
dtTime: FLiteralValue := StrToTime(FTokenString, rDateTimeFS);
dtDate: FLiteralValue := StrToDate(FTokenString, rDateTimeFS);
dtDouble: FLiteralValue := FDStr2Float(FTokenString, '.');
dtBoolean: FLiteralValue := (CompareText(FTokenString, 'TRUE') = 0);
dtAnsiString: FLiteralValue := FTokenString;
end;
end;
end;
Inc(P);
end;
'}':
begin
Inc(P);
FToken := etRCBracket;
end;
#0:
FToken := etEnd;
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprInvalidChar,
[String(P)]);
end;
FSourcePtr := P;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr: PFDExpressionNode;
begin
Result := ParseExpr2;
while TokenSymbolIs('OR') do begin
NextToken;
Result := FExpression.NewNode(enOperator, canOR, Unassigned, Result,
ParseExpr2, -1);
GetScopeKind(Result, Result^.FLeft, Result^.FRight);
Result^.FDataType := dtBoolean;
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr2: PFDExpressionNode;
begin
Result := ParseExpr3;
while TokenSymbolIs('AND') do begin
NextToken;
Result := FExpression.NewNode(enOperator, canAND, Unassigned, Result,
ParseExpr3, -1);
GetScopeKind(Result, Result^.FLeft, Result^.FRight);
Result^.FDataType := dtBoolean;
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr3: PFDExpressionNode;
begin
if TokenSymbolIs('NOT') then begin
NextToken;
Result := FExpression.NewNode(enOperator, canNOT, Unassigned, ParseExpr4,
nil, -1);
Result^.FDataType := dtBoolean;
end
else
Result := ParseExpr4;
GetScopeKind(Result, Result^.FLeft, Result^.FRight);
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr4: PFDExpressionNode;
const
Operators: array[etEQ .. etLT] of TFDExpressionOperator = (
canEQ, canNE, canGE, canLE, canGT, canLT);
var
eOperator: TFDExpressionOperator;
Left, Right: PFDExpressionNode;
begin
Result := ParseExpr5(False);
if (FToken in [etEQ..etLT, etLIKE, etNOTLIKE, etISNULL, etISNOTNULL,
etIN, etNOTIN, etBETWEEN, etNOTBETWEEN]) then begin
case FToken of
etEQ..etLT:
eOperator := Operators[FToken];
etLIKE:
eOperator := canLIKE;
etNOTLIKE:
eOperator := canNOTLIKE;
etISNULL:
eOperator := canISBLANK;
etISNOTNULL:
eOperator := canNOTBLANK;
etIN:
eOperator := canIN;
etNOTIN:
eOperator := canNOTIN;
etBETWEEN:
eOperator := canBETWEEN;
etNOTBETWEEN:
eOperator := canNOTBETWEEN;
else
eOperator := canNOTDEFINED;
end;
NextToken;
Left := Result;
if eOperator in [canIN, canNOTIN] then begin
if FToken <> etLParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoLParen,
[TokenName]);
NextToken;
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, nil, -1);
Result^.FDataType := dtBoolean;
if FToken <> etRParen then begin
repeat
Right := ParseExpr;
if IsTemporal(Left^.FDataType) then
Right^.FDataType := Left^.FDataType;
SetLength(Result^.FArgs, Length(Result^.FArgs) + 1);
Result^.FArgs[Length(Result^.FArgs) - 1] := Right;
if (FToken <> etComma) and (FToken <> etRParen) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParenOrComma,
[TokenName]);
if FToken = etComma then
NextToken;
until (FToken = etRParen) or (FToken = etEnd);
if FToken <> etRParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParen,
[TokenName]);
NextToken;
end
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprEmptyInList, []);
end
else if eOperator in [canBETWEEN, canNOTBETWEEN] then begin
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, nil, -1);
Result^.FDataType := dtBoolean;
SetLength(Result^.FArgs, 2);
Result^.FArgs[0] := ParseExpr5(False);
if TokenSymbolIs('AND') then
NextToken
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprExpected, ['AND']);
Result^.FArgs[1] := ParseExpr5(False);
end
else begin
if eOperator in [canEQ, canNE, canGE, canLE, canGT, canLT] then begin
Right := ParseExpr5(True);
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, Right, -1);
end
else if eOperator in [canLIKE, canNOTLIKE] then begin
Right := ParseExpr5(False);
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, Right, -1);
if TokenSymbolIs('ESCAPE') then begin
NextToken;
SetLength(Result^.FArgs, 1);
Result^.FArgs[0] := ParseExpr5(False);
end;
end
else begin
Right := nil;
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, Right, -1);
end;
if Right <> nil then begin
if (Left^.FKind = enField) and (Right^.FKind = enConst) then begin
if IsBoolean(Left^.FDataType) and IsNumeric(Right^.FDataType) then
Right^.FData := Right^.FData <> 0.0;
Right^.FDataType := Left^.FDataType;
end
else if (Right^.FKind = enField) and (Left^.FKind = enConst) then begin
if IsBoolean(Right^.FDataType) and IsNumeric(Left^.FDataType) then
Left^.FData := Left^.FData <> 0.0;
Left^.FDataType := Right^.FDataType;
end;
end;
if IsBinary(Left^.FDataType) and (eOperator in [canLIKE, canNOTLIKE]) then begin
if Right^.FKind = enConst then
Right^.FDataType := dtAnsiString;
end
else if not (eOperator in [canISBLANK, canNOTBLANK]) and
(IsBinary(Left^.FDataType) or (Right <> nil) and IsBinary(Right^.FDataType)) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTypeMis, []);
Result^.FDataType := dtBoolean;
if Right <> nil then begin
if IsTemporal(Left^.FDataType) and IsString(Right^.FDataType) then
Right^.FDataType := Left^.FDataType
else if IsTemporal(Right^.FDataType) and IsString(Left^.FDataType) then
Left^.FDataType := Right^.FDataType;
end;
GetScopeKind(Result, Left, Right);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr5(AEnableList: Boolean): PFDExpressionNode;
const
OperatorsList: array[etANY .. etALL] of TFDExpressionOperator = (
canANY, canANY, canALL);
Operators: array[etCONCAT .. etSUB] of TFDExpressionOperator = (
canCONCAT, canADD, canSUB);
var
eOperator: TFDExpressionOperator;
Left, Right: PFDExpressionNode;
begin
if FToken in [etANY, etSOME, etALL] then begin
if not AEnableList then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprExpected,
[TokenName]);
eOperator := OperatorsList[FToken];
NextToken;
if FToken <> etLParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoLParen,
[TokenName]);
NextToken;
if FToken = etRParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprEmptyInList, []);
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, nil, nil, -1);
repeat
SetLength(Result^.FArgs, Length(Result^.FArgs) + 1);
Result^.FArgs[Length(Result^.FArgs) - 1] := ParseExpr;
if (FToken <> etComma) and (FToken <> etRParen) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParenOrComma,
[TokenName]);
if FToken = etComma then
NextToken;
until (FToken = etRParen) or (FToken = etEnd);
if FToken <> etRParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParenOrComma,
[TokenName]);
NextToken;
Result^.FDataType := Result^.FArgs[0]^.FDataType;
// Result.FScopeKind := Result.FArgs[0]^.FScopeKind;
end
else begin
Result := ParseExpr6;
while FToken in [etCONCAT, etADD, etSUB] do begin
eOperator := Operators[FToken];
Left := Result;
NextToken;
Right := ParseExpr6;
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, Right, -1);
TypeCheckArithOp(Result);
GetScopeKind(Result, Left, Right);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr6: PFDExpressionNode;
const
Operators: array[etMUL .. etDIV] of TFDExpressionOperator = (
canMUL, canDIV);
var
eOperator: TFDExpressionOperator;
Left, Right: PFDExpressionNode;
begin
Result := ParseExpr7;
while FToken in [etMUL, etDIV] do begin
eOperator := Operators[FToken];
Left := Result;
NextToken;
Right := ParseExpr7;
Result := FExpression.NewNode(enOperator, eOperator, Unassigned, Left, Right, -1);
TypeCheckArithOp(Result);
GetScopeKind(Result, Left, Right);
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.ParseExpr7: PFDExpressionNode;
function NextTokenIsLParen: Boolean;
var
P: PChar;
begin
P := FSourcePtr;
while (P^ <> #0) and (P^ <= ' ') do
Inc(P);
Result := P^ = '(';
end;
function IsField(const AName: String): Boolean;
begin
Result := (FDataSource <> nil) and (FDataSource.VarIndex[AName] <> -1);
end;
var
FuncName: String;
FuncInd: Integer;
begin
Result := nil;
case FToken of
etSymbol:
begin
FuncInd := TokenSymbolIsFunc(FTokenString);
if FuncInd <> -1 then begin
FuncName := FUCTokenString;
if not NextTokenIsLParen then
if IsField(FTokenString) then begin
Result := FExpression.NewNode(enField, canNOTDEFINED, FTokenString, nil, nil, -1);
FixupFieldNode(Result, FTokenString);
end
else
Result := FExpression.NewNode(enFunc, canNOTDEFINED, FuncName, nil, nil, FuncInd)
else begin
NextToken;
if FToken <> etLParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoLParen, [TokenName]);
NextToken;
if (FuncName = 'COUNT') and (FToken = etMUL) then
NextToken;
Result := FExpression.NewNode(enFunc, canNOTDEFINED, FuncName, nil, nil, FuncInd);
if FToken <> etRParen then begin
repeat
SetLength(Result^.FArgs, Length(Result^.FArgs) + 1);
Result^.FArgs[Length(Result^.FArgs) - 1] := ParseExpr;
if (FToken <> etComma) and (FToken <> etRParen) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParenOrComma, [TokenName]);
if FToken = etComma then
NextToken;
until (FToken = etRParen) or (FToken = etEnd);
SetLength(Result^.FFuncArgs, Length(Result^.FArgs));
end;
end;
if Result^.FKind = enFunc then
GetFuncResultInfo(Result);
end
else if TokenSymbolIs('NULL') then begin
Result := FExpression.NewNode(enConst, canNOTDEFINED,
Null, nil, nil, -1);
Result^.FScopeKind := ckConst;
end
else if TokenSymbolPartialIs('TRUE') and not IsField(FTokenString) then begin
Result := FExpression.NewNode(enConst, canNOTDEFINED, True, nil, nil, -1);
Result^.FScopeKind := ckConst;
end
else if TokenSymbolPartialIs('FALSE') and not IsField(FTokenString) then begin
Result := FExpression.NewNode(enConst, canNOTDEFINED, False, nil, nil, -1);
Result^.FScopeKind := ckConst;
end
else begin
Result := FExpression.NewNode(enField, canNOTDEFINED, FTokenString, nil, nil, -1);
FixupFieldNode(Result, FTokenString);
end;
end;
etName:
begin
Result := FExpression.NewNode(enField, canNOTDEFINED, FTokenString, nil, nil, -1);
FixupFieldNode(Result, FTokenString);
end;
etNULL:
begin
Result := FExpression.NewNode(enConst, canNOTDEFINED, Null, nil, nil, -1);
Result^.FDataType := dtUnknown;
Result^.FScopeKind := ckConst;
end;
etLiteral:
begin
Result := FExpression.NewNode(enConst, canNOTDEFINED, FLiteralValue, nil, nil, -1);
Result^.FDataType := FLiteralType;
Result^.FScopeKind := ckConst;
end;
etLParen:
begin
NextToken;
Result := ParseExpr;
if FToken <> etRParen then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParen, [TokenName]);
end;
etLCBracket:
begin
NextToken;
Result := ParseExpr;
if FToken <> etRCBracket then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprNoRParen, [TokenName]);
end;
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprExpected, [TokenName]);
end;
NextToken;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.GetScopeKind(Root, Left, Right: PFDExpressionNode);
begin
if (Left = nil) and (Right = nil) then
Exit;
if Right = nil then begin
Root^.FScopeKind := Left^.FScopeKind;
Exit;
end;
if ((Left^.FScopeKind = ckField) and (Right^.FScopeKind = ckAgg))
or ((Left^.FScopeKind = ckAgg) and (Right^.FScopeKind = ckField)) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprBadScope, []);
if (Left^.FScopeKind = ckConst) and (Right^.FScopeKind = ckConst) then
Root^.FScopeKind := ckConst
else if (Left^.FScopeKind = ckAgg) or (Right^.FScopeKind = ckAgg) then
Root^.FScopeKind := ckAgg
else if (Left^.FScopeKind = ckField) or (Right^.FScopeKind = ckField) then
Root^.FScopeKind := ckField;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.GetFuncResultInfo(Node : PFDExpressionNode);
var
i, n: Integer;
pFuncDesc: TFDExpressionFunctionDesc;
begin
i := TokenSymbolIsFunc(Node^.FData);
n := Length(Node^.FArgs);
pFuncDesc := FDExpressionManager().Functions[i];
if (pFuncDesc.FArgMin > n) or (pFuncDesc.FArgMax < n) then
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTypeMis, []);
if pFuncDesc.FDataType = dtUnknown then begin
if pFuncDesc.FDataTypeArg = -1 then
Node^.FDataType := dtUnknown
else
Node^.FDataType := Node^.FArgs[pFuncDesc.FDataTypeArg]^.FDataType;
end
else
Node^.FDataType := pFuncDesc.FDataType;
if pFuncDesc.FScopeKind = ckUnknown then
Node^.FScopeKind := Node^.FArgs[pFuncDesc.FScopeKindArg]^.FScopeKind
else
Node^.FScopeKind := pFuncDesc.FScopeKind;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.TokenName: String;
begin
if FSourcePtr = FTokenPtr then
Result := '<nothing>'
else begin
SetString(Result, FTokenPtr, FSourcePtr - FTokenPtr);
Result := '''' + Result + '''';
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.TokenSymbolIs(const S: String): Boolean;
begin
Result := (FToken = etSymbol) and (FUCTokenString = S);
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.TokenSymbolPartialIs(const S: String): Boolean;
begin
Result := (FToken = etSymbol) and (Copy(S, 1, Length(FUCTokenString)) = FUCTokenString);
end;
{-------------------------------------------------------------------------------}
function TFDExpressionParser.TokenSymbolIsFunc(const S: String): Integer;
begin
Result := FDExpressionManager().FindFunction(S);
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionParser.TypeCheckArithOp(Node: PFDExpressionNode);
begin
if IsNumeric(Node^.FLeft^.FDataType) and IsNumeric(Node^.FRight^.FDataType) then
Node^.FDataType := dtDouble
else if IsString(Node^.FLeft^.FDataType) and IsString(Node^.FRight^.FDataType) and
((Node^.FOperator = canADD) or (Node^.FOperator = canCONCAT)) then
Node^.FDataType := dtAnsiString
else if IsTemporal(Node^.FLeft^.FDataType) and IsNumeric(Node^.FRight^.FDataType) and
(Node^.FOperator = canADD) then
Node^.FDataType := dtDateTime
else if IsTemporal(Node^.FLeft^.FDataType) and IsNumeric(Node^.FRight^.FDataType) and
(Node^.FOperator = canSUB) then
Node^.FDataType := Node^.FLeft^.FDataType
else if IsTemporal(Node^.FLeft^.FDataType) and IsTemporal(Node^.FRight^.FDataType) and
(Node^.FOperator = canSUB) then
Node^.FDataType := dtDouble
else if IsString(Node^.FLeft^.FDataType) and IsTemporal(Node^.FRight^.FDataType) and
(Node^.FOperator = canSUB) then begin
Node^.FLeft^.FDataType := Node^.FRight^.FDataType;
Node^.FDataType := dtDouble;
end
else if IsString(Node^.FLeft^.FDataType) and IsNumeric(Node^.FRight^.FDataType) and
(Node^.FLeft^.FKind = enConst) then
Node^.FLeft^.FDataType := dtDateTime
else
FDException(Self, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTypeMis, []);
end;
{-------------------------------------------------------------------------------}
{ TFDExpressionCollation }
{-------------------------------------------------------------------------------}
function TFDExpressionCollation.GetCall(AEncoding: TFDEncoding): TFDExpressionCompare;
begin
Result := FCalls[AEncoding];
end;
{-------------------------------------------------------------------------------}
{ TFDExpressionManager }
{-------------------------------------------------------------------------------}
constructor TFDExpressionManager.Create;
begin
inherited Create;
FFunctions := TFDStringList.Create(dupError, True, False);
FFunctions.Capacity := 100;
FFunctions.OwnsObjects := True;
FCollations := TFDStringList.Create(dupAccept, True, False);
FCollations.OwnsObjects := True;
// install standard functions
AddFunction('UPPER', ckUnknown, 0, dtUnknown, 0, 1, 1, 's', @FunUpper);
AddFunction('LOWER', ckUnknown, 0, dtUnknown, 0, 1, 1, 's', @FunLower);
AddFunction('SUBSTRING', ckUnknown, 0, dtUnknown, 0, 2, 3, 'sii', @FunSubstring);
AddFunction('TRIM', ckUnknown, 0, dtUnknown, 0, 1, 2, 'ss', @FunTrim);
AddFunction('TRIMLEFT', ckUnknown, 0, dtUnknown, 0, 1, 2, 'ss', @FunTrimLeft);
AddFunction('TRIMRIGHT', ckUnknown, 0, dtUnknown, 0, 1, 2, 'ss', @FunTrimRight);
AddFunction('YEAR', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunYear);
AddFunction('MONTH', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunMonth);
AddFunction('DAY', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunDay);
AddFunction('HOUR', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunHour);
AddFunction('MINUTE', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunMinute);
AddFunction('SECOND', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunSecond);
AddFunction('GETDATE', ckConst, -1, dtDateTime,-1, 0, 0, '', @FunGetDate);
AddFunction('DATE', ckUnknown, 0, dtDateTime,-1, 1, 1, 'd', @FunDate);
AddFunction('TIME', ckUnknown, 0, dtDateTime,-1, 1, 1, 'd', @FunTime);
AddFunction('CMPFILENAME',ckUnknown,0, dtBoolean, -1, 2, 2, 'ss',@FunCmpFileName);
AddFunction('CMPFILEPATH',ckUnknown,0, dtBoolean, -1, 2, 2, 'ss',@FunCmpFilePath);
AddFunction('SUM', ckAgg, -1, dtDouble, -1, 1, 1, 'n', @FunAggSum);
AddFunction('MIN', ckAgg, -1, dtUnknown, 0, 1, 1, '*', @FunAggMin);
AddFunction('MAX', ckAgg, -1, dtUnknown, 0, 1, 1, '*', @FunAggMax);
AddFunction('AVG', ckAgg, -1, dtDouble, -1, 1, 1, 'n', @FunAggAvg);
AddFunction('COUNT', ckAgg, -1, dtInt32, -1, 0, 1, '*', @FunAggCount);
AddFunction('TFIRST', ckAgg, -1, dtUnknown, 0, 1, 1, '*', @FunAggFirst);
AddFunction('TLAST', ckAgg, -1, dtUnknown, 0, 1, 1, '*', @FunAggLast);
AddFunction('IIF', ckUnknown, 1, dtUnknown, 1, 3, 3, 'b**', @FunIIF);
AddSynonym('IIF', 'IF');
end;
{-------------------------------------------------------------------------------}
destructor TFDExpressionManager.Destroy;
begin
FDFreeAndNil(FFunctions);
FDFreeAndNil(FCollations);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionManager.AddSynonym(const AName, ASynonym: String);
var
i: Integer;
oFunc: TFDExpressionFunctionDesc;
oColl: TFDExpressionCollation;
begin
if FFunctions.Find(UpperCase(AName), i) then begin
oFunc := TFDExpressionFunctionDesc(FFunctions.Objects[i]);
AddFunction(ASynonym, oFunc.FScopeKind, oFunc.FScopeKindArg, oFunc.FDataType,
oFunc.FDataTypeArg, oFunc.FArgMin, oFunc.FArgMax, oFunc.FArgTypeFamiles,
oFunc.FCall);
end;
if FCollations.Find(UpperCase(AName), i) then begin
oColl := TFDExpressionCollation(FCollations.Objects[i]);
AddCollation(ASynonym, ecUTF8, oColl.FCalls[ecUTF8]);
AddCollation(ASynonym, ecUTF16, oColl.FCalls[ecUTF16]);
AddCollation(ASynonym, ecANSI, oColl.FCalls[ecANSI]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionManager.GetFunctionCount: Integer;
begin
Result := FFunctions.Count;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionManager.GetFunctions(AIndex: Integer): TFDExpressionFunctionDesc;
begin
Result := TFDExpressionFunctionDesc(FFunctions.Objects[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionManager.AddFunction(const AName: String;
AScopeKind: TFDExpressionScopeKind; AScopeKindArg: Integer;
ADataType: TFDDataType; ADataTypeArg, AArgMin, AArgMax: Integer;
const AArgTypeFamiles: String; ACall: Pointer);
var
oDesc: TFDExpressionFunctionDesc;
begin
oDesc := TFDExpressionFunctionDesc.Create;
oDesc.FName := AName;
oDesc.FScopeKind := AScopeKind;
oDesc.FScopeKindArg := AScopeKindArg;
oDesc.FDataType := ADataType;
oDesc.FDataTypeArg := ADataTypeArg;
oDesc.FArgMin := AArgMin;
oDesc.FArgMax := AArgMax;
oDesc.FArgTypeFamiles := LowerCase(AArgTypeFamiles);
oDesc.FCall := ACall;
FFunctions.AddObject(UpperCase(AName), oDesc);
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionManager.RemoveFunction(const AName: String);
var
i: Integer;
begin
i := FindFunction(AName);
if i <> -1 then
FFunctions.Delete(i);
end;
{-------------------------------------------------------------------------------}
function TFDExpressionManager.FindFunction(const AName: String): Integer;
begin
Result := -1;
if not FFunctions.Find(UpperCase(AName), Result) then
Result := -1;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionManager.GetCollationCount: Integer;
begin
Result := FCollations.Count;
end;
{-------------------------------------------------------------------------------}
function TFDExpressionManager.GetCollations(AIndex: Integer): TFDExpressionCollation;
begin
Result := TFDExpressionCollation(FCollations.Objects[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionManager.AddCollation(const AName: String;
AEncoding: TFDEncoding; ACall: TFDExpressionCompare);
var
oColl: TFDExpressionCollation;
sUCName: String;
i: Integer;
begin
sUCName := UpperCase(AName);
if FCollations.Find(sUCName, i) then
oColl := TFDExpressionCollation(FCollations.Objects[i])
else begin
oColl := TFDExpressionCollation.Create;
oColl.FName := AName;
FCollations.AddObject(sUCName, oColl);
end;
if AEncoding = ecDefault then
AEncoding := ecUTF16;
oColl.FCalls[AEncoding] := ACall;
end;
{-------------------------------------------------------------------------------}
procedure TFDExpressionManager.RemoveCollation(const AName: String; AEncoding: TFDEncoding);
var
i: Integer;
begin
i := FindCollation(AName, AEncoding);
if i <> -1 then
FCollations.Delete(i);
end;
{-------------------------------------------------------------------------------}
function TFDExpressionManager.FindCollation(const AName: String;
AEncoding: TFDEncoding): Integer;
begin
Result := -1;
if not FCollations.Find(UpperCase(AName), Result) then
Result := -1
else begin
if AEncoding = ecDefault then
AEncoding := ecUTF16;
if not Assigned(TFDExpressionCollation(FCollations.Objects[Result]).FCalls[AEncoding]) then
Result := -1;
end;
end;
{-------------------------------------------------------------------------------}
var
FExpressionManager: TFDExpressionManager = nil;
function FDExpressionManager(): TFDExpressionManager;
begin
if FExpressionManager = nil then
FExpressionManager := TFDExpressionManager.Create;
Result := FExpressionManager;
end;
{-------------------------------------------------------------------------------}
var
oFact: TFDFactory;
initialization
oFact := TFDMultyInstanceFactory.Create(TFDExpressionParser, IFDStanExpressionParser);
rDateTimeFS.DateSeparator := '-';
rDateTimeFS.TimeSeparator := ':';
rDateTimeFS.ShortDateFormat := 'yyyy/mm/dd';
rDateTimeFS.ShortTimeFormat := 'hh:nn:ss';
finalization
FDFreeAndNil(FExpressionManager);
FDReleaseFactory(oFact);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2011-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Internal.Unwind;
interface
type
_Unwind_Reason_Code = Integer;
_Unwind_Action = Integer;
_Unwind_Exception = Pointer;
_Unwind_Context = Pointer;
_Unwind_RegVal = NativeUInt;
_PUnwind_RegVal = ^_Unwind_RegVal;
const
_URC_NO_REASON = 0;
_URC_FOREIGN_EXCEPTION_CAUGHT = 1;
_URC_FATAL_PHASE2_ERROR = 2;
_URC_FATAL_PHASE1_ERROR = 3;
_URC_NORMAL_STOP = 4;
_URC_END_OF_STACK = 5;
_URC_HANDLER_FOUND = 6;
_URC_INSTALL_CONTEXT = 7;
_URC_CONTINUE_UNWIND = 8;
_UA_SEARCH_PHASE = 1;
_UA_CLEANUP_PHASE = 2;
_UA_HANDLER_FRAME = 3;
_UA_FORCE_UNWIND = 4;
_UW_REG_EBP = 0;
_UW_REG_ESP = 1;
_UW_REG_EBX = 2;
_UW_REG_EAX = 3;
_UW_REG_EDX = 4;
_UW_REG_ECX = 5;
_UW_REG_EIP = 6;
function BorUnwind_GetGR(context: _Unwind_Context; Idx: Integer): _Unwind_RegVal; cdecl;
procedure BorUnwind_SetGR(context: _Unwind_Context; Idx: Integer; Value: _Unwind_RegVal); cdecl;
implementation
{$IFDEF MSWINDOWS}
const
unwind = 'unwind.dll';
{$ENDIF MSWINDOWS}
{$IFDEF LINUX32}
const
unwind = 'libcgunwind.so.1';
{$ENDIF LINUX32}
{$IFDEF MACOS32}
const
unwind = 'libcgunwind.1.0.dylib';
{$ENDIF MACOS32}
const
{$IFDEF UNDERSCOREIMPORTNAME}
_PU = '_';
{$ELSE}
_PU = '';
{$ENDIF}
function BorUnwind_GetGR(context: _Unwind_Context; Idx: Integer): _Unwind_RegVal; cdecl;
external unwind name _PU + '_BorUnwind_GetGR';
procedure BorUnwind_SetGR(context: _Unwind_Context; Idx: Integer; Value: _Unwind_RegVal); cdecl;
external unwind name _PU + '_BorUnwind_SetGR';
end.
|
{ compute the cosine using the expansion:
cos(x) = 1 - x**2/(2*1) + x**4/(4*3*2*1) - ... }
program cosine(input, output);
const
eps = 1e-14;
var
x, sx, s, t : real;
i, k, n : integer;
begin
write('Number of cosines: ');
read(n);
for i:=1 to n do
begin
write(n, '. Enter radians: ');
read(x);
t := 1; k := 0; s := 1; sx := sqr(x);
while abs(t) > eps*abs(s) do
begin
k := k+2;
t := -t*sx/(k*(k-1));
s := s+t;
writeln(' cos(', x, ')=', s, ' interation=', k div 2)
end
end
end.
|
unit PascalCoin.FMX.Wallet.Shared;
interface
uses PascalCoin.FMX.Strings, PascalCoin.Wallet.Interfaces,
PascalCoin.Utils.Interfaces,
System.Generics.Collections, Spring;
Type
TNodeRecord = record
Name: string;
URI: string;
NetType: string;
constructor Create(const AName, AURL, ANetType: string);
end;
TWalletAppSettings = class
private
FAdvancedOptions: boolean;
FAdvancedOptionsChanged: Event<TPascalCoinBooleanEvent>;
FNodes: TList<TNodeRecord>;
FUnlockTimeChange: Event<TPascalCoinIntegerEvent>;
FSelected: Integer;
FSelectedNodeURI: String;
FAutoMultiAccountTransactions: boolean;
FUnlockTime: Integer;
function GetAdvancedOptionsChanged: IEvent<TPascalCoinBooleanEvent>;
procedure SetAdvancedOptions(const Value: boolean);
procedure SetAutoMultiAccountTransactions(const Value: boolean);
procedure SetUnlockTime(const Value: Integer);
function GetOnUnlockTimeChange: IEvent<TPascalCoinIntegerEvent>;
function GetAsJSON: string;
procedure SetAsJSON(const Value: String);
public
constructor Create;
destructor Destroy; override;
property AdvancedOptions: boolean read FAdvancedOptions
write SetAdvancedOptions;
property AutoMultiAccountTransactions: boolean
read FAutoMultiAccountTransactions write SetAutoMultiAccountTransactions;
/// <summary>
/// Number of minutes to keep the wallet unlocked with no activity. 0 means
/// never lock
/// </summary>
property UnlockTime: Integer read FUnlockTime write SetUnlockTime;
property SelectedNodeURI: string read FSelectedNodeURI
write FSelectedNodeURI;
property Nodes: TList<TNodeRecord> read FNodes;
property OnAdvancedOptionsChange: IEvent<TPascalCoinBooleanEvent>
read GetAdvancedOptionsChanged;
property OnUnlockTimeChange: IEvent<TPascalCoinIntegerEvent>
read GetOnUnlockTimeChange;
property AsJSON: String read GetAsJSON write SetAsJSON;
end;
var
UConfig: IPascalCoinWalletConfig;
const
cStateText: array [TEncryptionState] of string = (statePlainText,
stateEncrypted, stateDecrypted);
_PayloadEncryptText: array [TPayloadEncryption] of string = ('Nothing',
'My Key', 'Their Key', 'a Password');
_PayloadEncodeText: array [TPayloadEncode] of string = ('Hex',
'Base58', 'ASCII');
implementation
uses System.IOUtils, System.SysUtils, System.JSON, REST.Json;
{ TWalletAppSettings }
function TWalletAppSettings.GetAsJSON: string;
var lObj, lNode: TJSONObject;
lNodes: TJSONArray;
nR: TNodeRecord;
begin
Result := '';
lObj := TJSONObject.Create;
try
lObj.AddPair('FAdvancedOptions', TJSONBool.Create(FAdvancedOptions));
lObj.AddPair('FAutoMultiAccountTransactions', TJSONBool.Create(FAutoMultiAccountTransactions));
lObj.AddPair('FUnlockTime', TJSONNumber.Create(FUnlockTime));
lObj.AddPair('FSelectedNodeURI', FSelectedNodeURI);
lObj.AddPair('FSelected', TJSONNumber.Create(FSelected));
lNodes := TJSONArray.Create;
for nr in FNodes do
begin
lNode := TJSONObject.Create;
lNode.AddPair('Name', nr.Name);
lNode.AddPair('URI', nr.URI);
lNode.AddPair('NetType', nr.NetType);
lNodes.AddElement(lNode);
end;
lObj.AddPair('FNodes', lNodes);
Result := lObj.ToJSON;
finally
lObj.Free;
end;
end;
constructor TWalletAppSettings.Create;
begin
inherited Create;
FNodes := TList<TNodeRecord>.Create;
end;
destructor TWalletAppSettings.Destroy;
begin
FNodes.Free;
inherited;
end;
function TWalletAppSettings.GetAdvancedOptionsChanged
: IEvent<TPascalCoinBooleanEvent>;
begin
result := FAdvancedOptionsChanged;
end;
function TWalletAppSettings.GetOnUnlockTimeChange
: IEvent<TPascalCoinIntegerEvent>;
begin
result := FUnlockTimeChange;
end;
procedure TWalletAppSettings.SetAdvancedOptions(const Value: boolean);
begin
if FAdvancedOptions = Value then
Exit;
FAdvancedOptions := Value;
FAdvancedOptionsChanged.Invoke(FAdvancedOptions);
end;
procedure TWalletAppSettings.SetAsJSON(const Value: String);
var
lObj,nObj: TJSONObject;
lNodes: TJSONArray;
lVal: TJSONValue;
begin
lObj := TJSONObject.ParseJSONValue(Value) as TJSONObject;
FAdvancedOptions := lObj.Values['FAdvancedOptions'].AsType<Boolean>;
FAutoMultiAccountTransactions := lObj.Values['FAutoMultiAccountTransactions'].AsType<boolean>;
FUnlockTime := lObj.Values['FUnlockTime'].AsType<Integer>;
FSelectedNodeURI := lObj.Values['FSelectedNodeURI'].AsType<String>;
FSelected := lObj.Values['FSelected'].AsType<Integer>;
FNodes.Clear;
lNodes := lObj.Values['FNodes'] as TJSONArray;
if lNodes <> nil then
begin
for lVal in lNodes do
begin
nObj := lVal as TJSONObject;
FNodes.Add(TNodeRecord.Create(
nobj.Values['Name'].AsType<string>,
nobj.Values['URI'].AsType<string>,
nobj.Values['NetType'].AsType<string>)
);
end;
end;
end;
procedure TWalletAppSettings.SetAutoMultiAccountTransactions
(const Value: boolean);
begin
FAutoMultiAccountTransactions := Value;
end;
procedure TWalletAppSettings.SetUnlockTime(const Value: Integer);
begin
if FUnlockTime <> Value then
begin
FUnlockTime := Value;
FUnlockTimeChange.Invoke(FUnlockTime);
end;
end;
{ TNodeRecord }
constructor TNodeRecord.Create(const AName, AURL, ANetType: string);
begin
Name := AName;
URI := AURL;
NetType := ANetType;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.Win.ObjBrkr;
{$T-}
interface
uses
Datasnap.Win.MConnect, System.Classes, System.Variants, System.SysUtils;
type
EBrokerException = class(Exception);
{ TServerItem }
TServerItem = class(TCollectionItem)
private
FEnabled: Boolean;
FComputerName: string;
FHasFailed: Boolean;
FPort: Integer;
protected
function GetDisplayName: string; override;
public
constructor Create(AOwner: TCollection); override;
property HasFailed: Boolean read FHasFailed write FHasFailed;
published
property ComputerName: string read FComputerName write FComputerName;
[Default(211)]
property Port: Integer read FPort write FPort default 211;
[Default(True)]
property Enabled: Boolean read FEnabled write FEnabled default True;
end;
{ TServerCollection }
TServerCollection = class(TOwnedCollection)
private
function GetItem(Index: Integer): TServerItem;
procedure SetItem(Index: Integer; Value: TServerItem);
public
constructor Create(AOwner: TComponent);
function GetBalancedName: string;
function GetNextName: string;
function FindServer(const ComputerName: string): TServerItem;
property Items[Index: Integer]: TServerItem read GetItem write SetItem; default;
end;
{ TSimpleObjectBroker }
TSimpleObjectBroker = class(TCustomObjectBroker)
private
FServers: TServerCollection;
FLoadBalanced: Boolean;
procedure SetServers(Value: TServerCollection);
function IsServersStored: Boolean;
function GetNextComputer: string;
function GetServerData: OleVariant;
procedure SetServerData(const Value: OleVariant);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SaveToStream(Stream: TStream);
procedure LoadFromStream(Stream: TStream);
property ServerData: OleVariant read GetServerData write SetServerData;
{ From TCustomObjectBroker }
procedure SetConnectStatus(ComputerName: string; Success: Boolean); override;
function GetComputerForGUID(GUID: TGUID): string; override;
function GetComputerForProgID(const ProgID): string; override;
function GetPortForComputer(const ComputerName: string): Integer; override;
published
[Stored('IsServersStored')]
property Servers: TServerCollection read FServers write SetServers stored IsServersStored;
[Default(False)]
property LoadBalanced: Boolean read FLoadBalanced write FLoadBalanced default False;
end;
implementation
uses Datasnap.MidConst;
{ TServerItem }
constructor TServerItem.Create(AOwner: TCollection);
begin
inherited Create(AOwner);
FPort := 211;
FHasFailed := False;
FEnabled := True;
end;
function TServerItem.GetDisplayName: string;
begin
Result := ComputerName;
if Result = '' then
Result := inherited GetDisplayName;
end;
{ TServerCollection }
constructor TServerCollection.Create(AOwner: TComponent);
begin
inherited Create(AOwner, TServerItem);
end;
function TServerCollection.FindServer(const ComputerName: string): TServerItem;
var
I: Integer;
begin
Result := nil;
for I := 0 to Count - 1 do
if Items[I].ComputerName = ComputerName then
begin
Result := Items[I];
break;
end;
end;
function TServerCollection.GetItem(Index: Integer): TServerItem;
begin
Result := TServerItem(inherited GetItem(Index));
end;
function TServerCollection.GetNextName: string;
var
I: Integer;
begin
Result := '';
for I := 0 to Count - 1 do
if (not Items[I].HasFailed) and (Items[I].Enabled) then
begin
Result := Items[I].ComputerName;
break;
end;
if Result = '' then
raise EBrokerException.CreateRes(@SNoServers);
end;
function TServerCollection.GetBalancedName: string;
var
I, GoodCount: Integer;
GoodServers: array of TServerItem;
begin
GoodCount := 0;
SetLength(GoodServers, Count);
for I := 0 to Count - 1 do
if (not Items[I].HasFailed) and (Items[I].Enabled) then
begin
GoodServers[GoodCount] := Items[I];
Inc(GoodCount);
end;
if GoodCount = 0 then
raise EBrokerException.CreateRes(@SNoServers);
Randomize;
Result := GoodServers[Random(GoodCount)].ComputerName;
end;
procedure TServerCollection.SetItem(Index: Integer; Value: TServerItem);
begin
inherited SetItem(Index, Value);
end;
{ TSimpleObjectBroker }
constructor TSimpleObjectBroker.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLoadBalanced := False;
FServers := TServerCollection.Create(Self);
end;
destructor TSimpleObjectBroker.Destroy;
begin
FServers.Free;
inherited Destroy;
end;
function TSimpleObjectBroker.GetServerData: OleVariant;
var
Stream: TMemoryStream;
P: Pointer;
begin
Stream := TMemoryStream.Create;
try
SaveToStream(Stream);
Result := VarArrayCreate([0, Stream.Size], varByte);
P := VarArrayLock(Result);
try
Move(Stream.Memory^, P^, Stream.Size);
finally
VarArrayUnlock(Result);
end;
finally
Stream.Free;
end;
end;
procedure TSimpleObjectBroker.SetServerData(const Value: OleVariant);
var
Stream: TMemoryStream;
P: Pointer;
begin
if VarIsNull(Value) or VarIsClear(Value) then
Servers.Clear else
begin
Stream := TMemoryStream.Create;
try
Stream.Size := VarArrayHighBound(Value, 1);
P := VarArrayLock(Value);
try
Stream.Write(P^, Stream.Size);
finally
VarArrayUnlock(Value);
end;
Stream.Position := 0;
LoadFromStream(Stream);
finally
Stream.Free;
end;
end;
end;
procedure TSimpleObjectBroker.SaveToStream(Stream: TStream);
var
Writer: TWriter;
begin
Writer := TWriter.Create(Stream, 1024);
try
Writer.WriteCollection(Servers);
finally
Writer.Free;
end;
end;
procedure TSimpleObjectBroker.LoadFromStream(Stream: TStream);
var
Reader: TReader;
begin
Servers.Clear;
Reader := TReader.Create(Stream, 1024);
try
Reader.ReadValue;
Reader.ReadCollection(Servers);
finally
Reader.Free;
end;
end;
function TSimpleObjectBroker.GetNextComputer: string;
begin
if LoadBalanced then
Result := Servers.GetBalancedName else
Result := Servers.GetNextName;
end;
function TSimpleObjectBroker.GetComputerForGUID(GUID: TGUID): string;
begin
Result := GetNextComputer;
end;
function TSimpleObjectBroker.GetComputerForProgID(const ProgID): string;
begin
Result := GetNextComputer;
end;
function TSimpleObjectBroker.GetPortForComputer(const ComputerName: string): Integer;
var
Server: TServerItem;
begin
Server := Servers.FindServer(ComputerName);
if Assigned(Server) then
Result := Server.Port else
Result := 0;
end;
function TSimpleObjectBroker.IsServersStored: Boolean;
begin
Result := Servers.Count > 0;
end;
procedure TSimpleObjectBroker.SetConnectStatus(ComputerName: string;
Success: Boolean);
var
Server: TServerItem;
begin
Server := Servers.FindServer(ComputerName);
if Assigned(Server) then Server.HasFailed := not Success;
end;
procedure TSimpleObjectBroker.SetServers(Value: TServerCollection);
begin
FServers.Assign(Value);
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995,99 Inprise Corporation }
{ }
{*******************************************************}
unit Exptintf;
interface
uses Windows, VirtIntf, ToolIntf;
const
isExperts = 'Experts';
ExpertEntryPoint = 'INITEXPERT0017';
ValidExpertVersion = 3;
type
TExpertStyle = (esStandard, esForm, esProject, esAddIn);
TExpertState = set of (esEnabled, esChecked);
{
This is the declaration of the pure-virtual base class for the expert
interface within the Delphi IDE.
NOTE: In Delphi 1.0, the GetGlyph function used to return an HBITMAP,
whereas now it must return an HICON.
GetName - REQUIRED. This must return a unique descriptive name
identifying this expert.
GetAuthor - REQUIRED is style is esForm or esProject. This should
return the "author" of this add-in/expert. This could
be a person or company, for example. This value will
be displayed in the Object Repository.
GetComment - REQUIRED if style is esForm or esProject. This should
return a 1 - 2 sentence describing the function of this
expert.
GetPage - REQUIRED if style is esForm or esProject. Should return
short string indicating on which page in the repository
this expert should be placed. NOTE: The user can still
override this setting from the Tool|Repository dialog.
GetGlyph - REQUIRED if style is esForm or esProject. This should
return a handle to a icon to be displayed in the form or
project list boxes or dialogs. Return 0 to display the
default icon.
GetStyle - REQUIRED. Returns one of four possible values:
esStandard - Tells the IDE to treat the interface to
this expert as a menu item on the Help
menu.
esForm - Tells the IDE to treat this expert interface
in a fashion similar to form templates.
esProject - Tells the IDE to treat this interface in a
fashion similar to project templates.
esAddIn - Tells the IDE that this expert handles all its
own interfacing to the IDE through the
TIToolServices interface.
GetState - REQUIRED. If the style is esStandard, esChecked will cause
the menu to display a checkmark. NOTE: This function is
called each time the expert is shown in a menu or listbox in
order to determine how it should be displayed.
GetIDString - REQUIRED. This ID string should be unique to all experts
that could be installed. By convention, the format of the
string is:
CompanyName.ExpertFunction, ex. Borland.WidgetExpert
GetMenuText - REQURED if style is esStandard. This should return the
actual text to display for the menu item. NOTE: This
function is called each time the parent menu is pulled-down,
so it is possible to provide context sensative text.
Execute - REQUIRED if style is esStandard, esForm, or esProject.
Called whenever this expert is invoked via the menu, form
repository dialog, or project repository dialog. The style
will determine how the expert was invoked. This procedure
is never called if the style is esAddIn.
TExpertInitProc - defines the number and types of parameters passed to the
single exported entry-point to the expert DLL.
ToolServices - a pure-virtual class containing all the
tool services provided by the IDE.
RegisterProc - The function to call in order to register
an expert. NOTE: This function is called
once for each expert instance that the DLL
wants to register with the IDE.
Terminate - Set this parameter to point to a procedure
that will be called immediately before the
expert DLL is unloaded by the IDE. Leave
nil, if not needed.
}
TIExpert = class(TInterface)
public
{ Expert UI strings }
function GetName: string; virtual; stdcall; abstract;
function GetAuthor: string; virtual; stdcall; abstract;
function GetComment: string; virtual; stdcall; abstract;
function GetPage: string; virtual; stdcall; abstract;
function GetGlyph: HICON; virtual; stdcall; abstract;
function GetStyle: TExpertStyle; virtual; stdcall; abstract;
function GetState: TExpertState; virtual; stdcall; abstract;
function GetIDString: string; virtual; stdcall; abstract;
function GetMenuText: string; virtual; stdcall; abstract;
{ Launch the Expert }
procedure Execute; virtual; stdcall; abstract;
end;
TExpertRegisterProc = function(Expert: TIExpert): Boolean;
TExpertTerminateProc = procedure;
TExpertInitProc = function(ToolServices: TIToolServices;
RegisterProc: TExpertRegisterProc;
var Terminate: TExpertTerminateProc): Boolean stdcall;
var
LibraryExpertProc: TExpertRegisterProc = nil;
ToolServices: TIToolServices = nil;
procedure RegisterLibraryExpert(Expert: TIExpert);
implementation
procedure RegisterLibraryExpert(Expert: TIExpert);
begin
if @LibraryExpertProc <> nil then
LibraryExpertProc(Expert);
end;
end.
|
(***********************************************************)
(* xPLRFX *)
(* part of Digital Home Server project *)
(* http://www.digitalhomeserver.net *)
(* info@digitalhomeserver.net *)
(***********************************************************)
unit uxPLRFX_0x51;
interface
Uses uxPLRFXConst, u_xPL_Message, u_xpl_common, uxPLRFXMessages;
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
implementation
Uses SysUtils;
(*
Type $51 - Humidity Sensors
Buffer[0] = packetlength = $08;
Buffer[1] = packettype
Buffer[2] = subtype
Buffer[3] = seqnbr
Buffer[4] = id1
Buffer[5] = id2
Buffer[6] = humidity
Buffer[7] = humidity_status
Buffer[8] = battery_level:4/rssi:4
Test strings :
085101027700360189
xPL Schema
sensor.basic
{
device=(hum1-hum2) 0x<hex sensor id>
type=humidity
current=(0-100)
description=normal|comfort|dry|wet
}
sensor.basic
{
device=(hum1-hum2) 0x<hex sensor id>
type=battery
current=0-100
}
*)
const
// Type
HUMIDITY = $51;
// Subtype
HUM1 = $01;
HUM2 = $02;
// Humidity status
HUM_NORMAL = $00;
HUM_COMFORT = $01;
HUM_DRY = $02;
HUM_WET = $03;
// Humidity status strings
HUM_NORMAL_STR = 'normal';
HUM_COMFORT_STR = 'comfort';
HUM_DRY_STR = 'dry';
HUM_WET_STR = 'wet';
var
SubTypeArray : array[1..2] of TRFXSubTypeRec =
((SubType : HUM1; SubTypeString : 'hum1'),
(SubType : HUM2; SubTypeString : 'hum2'));
procedure RFX2xPL(Buffer : BytesArray; xPLMessages : TxPLRFXMessages);
var
DeviceID : String;
SubType : String;
Humidity : Integer;
Status : String;
BatteryLevel : Integer;
xPLMessage : TxPLMessage;
begin
DeviceID := GetSubTypeString(Buffer[2],SubTypeArray)+IntToHex(Buffer[4],2)+IntToHex(Buffer[5],2);
Humidity := Buffer[6];
case Buffer[7] of
HUM_NORMAL : Status := HUM_NORMAL_STR;
HUM_COMFORT : Status := HUM_COMFORT_STR;
HUM_DRY : Status := HUM_DRY_STR;
HUM_WET : Status := HUM_WET_STR;
end;
if (Buffer[8] and $0F) = 0 then // zero out rssi
BatteryLevel := 0
else
BatteryLevel := 100;
// Create sensor.basic messages
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(Humidity));
xPLMessage.Body.AddKeyValue('description='+Status);
xPLMessage.Body.AddKeyValue('type=humidity');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
xPLMessage := TxPLMessage.Create(nil);
xPLMessage.schema.RawxPL := 'sensor.basic';
xPLMessage.MessageType := trig;
xPLMessage.source.RawxPL := XPLSOURCE;
xPLMessage.target.IsGeneric := True;
xPLMessage.Body.AddKeyValue('device='+DeviceID);
xPLMessage.Body.AddKeyValue('current='+IntToStr(BatteryLevel));
xPLMessage.Body.AddKeyValue('type=battery');
xPLMessages.Add(xPLMessage.RawXPL);
xPLMessage.Free;
end;
end.
|
unit ArrayUpsizeSingleThread;
interface
uses
Windows, BenchmarkClassUnit, Classes, Math;
type
TArrayUpsizeSingleThread = class(TFastcodeMMBenchmark)
private
procedure Execute;
public
procedure RunBenchmark; override;
class function GetBenchmarkName: string; override;
class function GetBenchmarkDescription: string; override;
class function GetCategory: TBenchmarkCategory; override;
end;
implementation
uses
SysUtils;
{ TArrayUpsizeSingleThread }
procedure TArrayUpsizeSingleThread.Execute;
var
i: Integer;
x: array of Int64;
begin
for i := 1 to 10 * 1024 * 1024 do begin
SetLength(x, i);
x[i - 1] := i;
end;
UpdateUsageStatistics;
end;
class function TArrayUpsizeSingleThread.GetBenchmarkDescription: string;
begin
Result := 'Constantly resize a dynamic array in 8 byte steps upward to '
+ 'reproduce JclDebug behaviour when loading debug information'
+ 'Start size is 16 bytes. Stop size is 8 * 10 * 1024 * 1024 + 8 bytes';
end;
class function TArrayUpsizeSingleThread.GetBenchmarkName: string;
begin
Result := 'Array Upsize 1 thread';
end;
class function TArrayUpsizeSingleThread.GetCategory: TBenchmarkCategory;
begin
Result := bmSingleThreadRealloc;
end;
procedure TArrayUpsizeSingleThread.RunBenchmark;
begin
inherited;
Execute;
end;
end.
|
unit TimeNowForm;
interface
// running this program raises an exception by design
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Memo, FMX.Controls.Presentation, FMX.ScrollBox;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
procedure Show (const msg: string);
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.Button1Click(Sender: TObject);
var
StartTime: TDateTime;
begin
StartTime := Now;
Show ('Time is ' + TimeToStr (StartTime));
Show ('Date is ' + DateToStr (StartTime));
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Timer1.Enabled := True;
end;
procedure TForm1.Show(const msg: string);
begin
Memo1.Lines.Add(msg);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Show ('Time is ' + TimeToStr (Now));
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
// Jazarsoft VCL Pack (JVP) //
////////////////////////////////////////////////////////////////////////////////
// //
// TITLE : MaxMem //
// CLASS : TjsMaxMem //
// VERSION : 1.2 //
// AUTHOR : Jazarsoft VCL Development Team //
// CREATED : 20 October 2000 //
// MODIFIED : 23 December 2001 //
// WEBSITE : http://www.jazarsoft.com/ //
// WEB-SUPPORT : http://www.jazarsoft.com/vcl/forum/ //
// EMAIL-SUPPORT: support@jazarsoft.com, bugreport@jazarsoft.com //
// LEGAL : Copyright (C) 2000-2001 Jazarsoft, All Rights Reserved. //
// //
////////////////////////////////////////////////////////////////////////////////
// //
// This code may be used and modified by anyone so long as this header and //
// copyright information remains intact. //
// //
// The code is provided "AS-IS" and without WARRANTY OF ANY KIND, //
// expressed, implied or otherwise, including and without limitation, any //
// warranty of merchantability or fitness for a particular purpose. //
// //
// In no event shall the author be liable for any special, incidental, //
// indirect or consequential damages whatsoever (including, without //
// limitation, damages for loss of profits, business interruption, loss //
// of information, or any other loss), whether or not advised of the //
// possibility of damage, and on any theory of liability, arising out of //
// or in connection with the use or inability to use this software. //
// //
////////////////////////////////////////////////////////////////////////////////
// //
// HISTORY: //
// 1.0 - [o] Initial Development //
// 1.1 - [+] Abort Procedure //
// - [+] DefragAll Procedure //
// 1.2 - [o] Change classname to TjsMaxMem //
// //
// LEGEND: //
// [o] : Information //
// [+] : Add something //
// [-] : Remove something //
// [*] : Fix //
// //
////////////////////////////////////////////////////////////////////////////////
{$WARNINGS OFF}
{$HINTS OFF}
unit jsMaxMem;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TOnProgress = procedure(Sender: TObject;Progress:Integer) of object;
TjsMaxMem = class(TComponent)
private
FAbort : Boolean;
FTotalMemory : Integer; { Your Computer RAM in Bytes }
FWorking : Boolean;
FOnProgress : TOnProgress;
FOnBeforeDefrag ,
FOnAfterDefrag : TNotifyEvent;
Function GetFreeMemory:Integer; { In Bytes }
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure DefragMemory(MemoryLimit:Integer); { Watchout! In MEGABYTES }
Procedure Abort;
Procedure DefragAll;
published
property TotalMemory : Integer Read FTotalMemory;
property FreeMemory : Integer Read GetFreeMemory;
{ Events }
property OnBeforeDefrag : tNotifyEvent Read FOnBeforeDefrag Write FOnBeforeDefrag;
property OnProgress : TOnProgress Read FOnProgress Write FOnProgress;
property OnAfterDefrag : tNotifyEvent Read FOnAfterDefrag Write FOnAfterDefrag;
end;
procedure Register;
implementation
constructor TjsMaxMem.Create(AOwner: TComponent);
var MS : tMemoryStatus;
Begin
inherited Create(AOwner);
MS.dwLength:=sizeof(MS);
GlobalMemoryStatus(MS);
FTotalMemory:=MS.dwTotalPhys;
End;
destructor TjsMaxMem.Destroy;
Begin
inherited Destroy;
End;
Procedure TjsMaxMem.Abort;
Begin
FAbort:=True;
End;
Procedure TjsMaxMem.DefragAll;
Begin
DefragMemory(TotalMemory div (1024*1024));
End;
Function TjsMaxMem.GetFreeMemory:Integer;
var MS : tMemoryStatus;
Begin
MS.dwLength:=sizeof(MS);
GlobalMemoryStatus(MS);
Result:=MS.dwAvailPhys;
End;
procedure TjsMaxMem.DefragMemory(MemoryLimit:Integer);
var
Pointers : Array [0..1024] of Pointer;
Limit ,
I2,
I : Integer;
P : Pointer;
Step : Integer;
Steps : Integer;
begin
FAbort := False;
If FWorking then Exit;
FWorking:=True;
Limit:=MemoryLimit;
If Limit>1024 then Limit:=1024;
If Assigned(FOnBeforeDefrag) then FOnBeforeDefrag(Self);
{ Calculating how many steps...}
Steps:=(MemoryLimit*2);
Step:=0;
{ Clean pointer...}
For I:= 0 to Limit do Pointers[I]:=nil;
{ Allocating Memory }
For I:=0 to Limit-1 do
Begin
P:=VirtualAlloc(nil, 1024*1024, MEM_COMMIT, PAGE_READWRITE + PAGE_NOCACHE);
Pointers[I]:=p;
asm
pushad
pushfd
mov edi, p
mov ecx, 1024*1024/4
xor eax, eax
cld
repz stosd
popfd
popad
end;
Inc(Step);
If Assigned(FOnProgress) then OnProgress(Self,Round((Step/Steps)*100));
If FAbort then
Begin
For I2:=0 to I do
Begin
VirtualFree(Pointers[I2], 0, MEM_RELEASE);
End;
Step:=(MemoryLimit*2);
FWorking:=False;
If Assigned(FOnAfterDefrag) then FOnAfterDefrag(Self);
Exit;
End;
end;
{ DeAllocating Memory }
For I:=0 to Limit-1 do
Begin
VirtualFree(Pointers[i], 0, MEM_RELEASE);
Inc(Step);
If Assigned(FOnProgress) then OnProgress(Self,Round((Step/Steps)*100));
If FAbort then
Begin
{ Warning! : Force abort, w/o de-allocating memory }
Step:=(MemoryLimit*2);
FWorking:=False;
If Assigned(FOnAfterDefrag) then FOnAfterDefrag(Self);
Exit;
End;
End;
FWorking:=False;
If Assigned(FOnAfterDefrag) then FOnAfterDefrag(Self);
End;
procedure Register;
begin
RegisterComponents('Jazarsoft', [TjsMaxMem]);
end;
end.
|
unit CuentaCredito;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UnitUsuario, UnitCuentaCredito;
type
TFormCuentaCredito = class(TForm)
Label1: TLabel;
txtDeuda: TEdit;
txtNombre: TEdit;
txtMonto: TEdit;
btnPagar: TButton;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
cbPagarIntereses: TCheckBox;
btnAtras: TButton;
Label5: TLabel;
Label6: TLabel;
txtIntereses: TEdit;
txtTotal: TEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure cbPagarInteresesClick(Sender: TObject);
procedure btnPagarClick(Sender: TObject);
procedure btnAtrasClick(Sender: TObject);
private
pagosFaltantes : integer;
monto : integer;
intereses : Currency;
interesesMensuales : Currency;
total : Currency;
pagarIntereses : boolean;
currentDate : TDateTime;
procedure FillTextBoxes;
procedure setVariables;
procedure CreatePago;
procedure updateCuentaCredito;
procedure pagarCuentaIntereses;
public
usuario : TUsuario;
cuentaCredito : TCuentaCredito;
end;
var
FormCuentaCredito: TFormCuentaCredito;
implementation
{$R *.dfm}
uses ElegirCuenta, DataModuleDani;
procedure TFormCuentaCredito.FormShow(Sender: TObject);
begin
usuario := ElegirCuenta.FormElegirCuenta.usuario;
cuentaCredito := ElegirCuenta.FormElegirCuenta.cuentaCredito;
setVariables;
FillTextBoxes;
end;
procedure TFormCuentaCredito.btnPagarClick(Sender: TObject);
begin
currentDate := Now;
begin
CreatePago;
updateCuentaCredito;
pagarCuentaIntereses;
showmessage('El pago se realizó con éxito');
elegirCuenta.FormElegirCuenta.cuentaCredito := cuentaCredito;
cbPagarIntereses.Checked := false;
FormCuentaCredito.Visible := False;
FormElegirCuenta.Show;
end;
end;
procedure TFormCuentaCredito.cbPagarInteresesClick(Sender: TObject);
begin
if cbPagarIntereses.Checked then
begin
if intereses > 0 then
begin
txtTotal.Text := CurrToStrF((total + intereses), ffCurrency, 2);
pagarIntereses := true;
end
Else
begin
showmessage('Esta cuenta no tiene intereses');
cbPagarIntereses.Checked := false;
pagarIntereses := false;
end;
end
Else
begin
txtTotal.Text := CurrToStrF(total, ffCurrency, 2);
end;
end;
procedure TFormCuentaCredito.CreatePago;
begin
with DataModuleDaniBD.createPago do
begin
Open;
Refresh;
Insert;
FieldByName('fecha').AsDateTime := currentDate;
FieldByName('monto').AsInteger := monto;
FieldByName('idCuentaCredito').AsInteger := cuentaCredito.idCuentaCredito;
Post;
end;
end;
procedure TFormCuentaCredito.updateCuentaCredito;
begin
cuentaCredito.deudaTotal := cuentaCredito.deudaTotal - monto;
with DataModuleDaniBD.CRUDCuentaCredito do
begin
Open;
Refresh;
if FindKey([cuentaCredito.idCuentaCredito]) then
begin
Edit;
FieldByName('deudaTotal').asCurrency := cuentaCredito.deudaTotal;
Post;
end;
end;
end;
procedure TFormCuentaCredito.pagarCuentaIntereses;
begin
if pagarIntereses then
begin
with DataModuleDaniBD.CRUDCuentaIntereses do
begin
Open;
Refresh;
if FindKey([cuentaCredito.idCuentaCredito]) then
begin
Edit;
FieldByName('totalInteresesAcumulados').AsCurrency := 0.0;
Post;
end;
end;
end;
end;
procedure TFormCuentaCredito.setVariables;
begin
monto := 0;
pagosFaltantes := 12 - cuentaCredito.getPagos;
if pagosFaltantes > 0 then
begin
monto := Round(cuentaCredito.deudaTotal / pagosFaltantes);
intereses := cuentaCredito.getIntereses;
interesesMensuales := monto * 0.10;
total := interesesMensuales + monto;
end
else
begin
btnPagar.Hide;
end;
end;
procedure TFormCuentaCredito.FillTextBoxes;
begin
txtMonto.Clear;
txtNombre.Text := usuario.getNombreCompleto;
txtDeuda.Text := CurrToStrF(cuentaCredito.deudaTotal, ffCurrency, 2);
txtMonto.Text := Inttostr(monto);
txtIntereses.Text := CurrToStrF(interesesMensuales, ffCurrency, 2);
txtTotal.Text := CurrToStrF(total, ffCurrency, 2)
end;
procedure TFormCuentaCredito.btnAtrasClick(Sender: TObject);
begin
elegirCuenta.FormElegirCuenta.cuentaCredito := cuentaCredito;
cbPagarIntereses.Checked := false;
FormCuentaCredito.Visible := False;
FormElegirCuenta.Show;
end;
procedure TFormCuentaCredito.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Application.Terminate;
end;
end.
|
unit record_properties_1;
interface
type
TRec = record
a, b: int32;
property AR: Int32 read a;
property ARW: Int32 read a write a;
property BR: Int32 read b;
property BRW: Int32 read b write b;
end;
implementation
var
R: TRec;
GA, GB: Int32;
procedure Test;
begin
R.ARW := 5;
R.BRW := 6;
GA := R.AR;
GB := R.BR;
end;
initialization
Test();
finalization
Assert(GA = 5);
Assert(GB = 6);
end. |
// testing array declarations
PROGRAM test13;
TYPE
array1 = ARRAY [0..2] of integer;
array2 = ARRAY [3..5] of integer;
VAR
a : array1;
b : array2;
BEGIN
a[0] := 0;
a[1] := 1;
a[2] := 2;
WRITE(a[0]);
WRITE(a[1]);
WRITE(a[2]);
b[3] := 3;
b[4] := 4;
b[5] := 5;
WRITE(b[3]);
WRITE(b[4]);
WRITE(b[5]);
END.
|
{ Copyright (C) 1998-2011, written by Mike Shkolnik, Scalabium Software
E-Mail: mshkolnik@scalabium
WEB: http://www.scalabium.com
Const strings for localization
freeware SMComponent library
}
unit SMCnst;
interface
{English strings}
const
strMessage = 'Print...';
strSaveChanges = 'Wilt u de wijzigen bewaren?';
strErrSaveChanges = 'Kan de data niet bewaren! Controleer de server verbinding of data validatie.';
strDeleteWarning = 'Wilt u werkelijk de tabel %s verwijderen?';
strEmptyWarning = 'Wilt u werkelijk de tabel %s leeg maken?';
const
PopUpCaption: array [0..24] of string =
('Toevoegen record',
'Invoegen record',
'Wijzig record',
'Verwijder record',
'-',
'Print ...',
'Exporteren ...',
'Filter ...',
'Zoeken ...',
'-',
'Bewaar wijzigingen',
'Annuleer wijzigingen',
'Verversen',
'-',
'Selecteer/Deselecteer records',
'Selecteer record',
'Selecteer alle records',
'-',
'Deselecteer record',
'Deselecteer alle records',
'-',
'Bewaar kolom layout',
'Herstel kolom layout',
'-',
'Setup...');
const //for TSMSetDBGridDialog
SgbTitle = ' Titel ';
SgbData = ' Data ';
STitleCaption = 'Kop:';
STitleAlignment = 'Uitlijnen:';
STitleColor = 'Achtergrond:';
STitleFont = 'Lettertype:';
SWidth = 'Breedte:';
SWidthFix = 'Karakatiers';
SAlignLeft = 'links';
SAlignRight = 'rechts';
SAlignCenter = 'centreren';
const //for TSMDBFilterDialog
strEqual = 'gelijk';
strNonEqual = 'niet gelijk';
strNonMore = 'niet groter';
strNonLess = 'niet minder';
strLessThan = 'kleiner dan';
strLargeThan = 'groter dan';
strExist = 'leeg';
strNonExist = 'niet leeg';
strIn = 'in lijst';
strBetween = 'tussen';
strLike = 'zelfde';
strOR = 'of';
strAND = 'en';
strField = 'Veld';
strCondition = 'Voorwaarden';
strValue = 'Waarden';
strAddCondition = ' Defineer aanvullende voorwaarden:';
strSelection = ' selecteer de records volgens de voorwaarden:';
strAddToList = 'Toevoegen aan lijst';
strEditInList = 'Wijzig in de lijst';
strDeleteFromList = 'Verwjder uit de lijst';
strTemplate = 'Filter template dialoog';
strFLoadFrom = 'Openen uit...';
strFSaveAs = 'Bewaren als..';
strFDescription = 'Omschrijving';
strFFileName = 'Bestandsnaam';
strFCreate = 'Aangemaakt: %s';
strFModify = 'Gewijzigd: %s';
strFProtect = 'Beveiligd tegen overschrijven';
strFProtectErr = Bestand is beveiligid!';
const //for SMDBNavigator
SFirstRecord = 'Eerste record';
SPriorRecord = 'Vorige record';
SNextRecord = 'Volgende record';
SLastRecord = 'Laatste record';
SInsertRecord = 'Toevoegen record';
SCopyRecord = 'Kopieer record';
SDeleteRecord = 'Verwijder record';
SEditRecord = 'Wijzig record';
SFilterRecord = 'Filter voorwaarden';
SFindRecord = 'Zoeken naar record';
SPrintRecord = 'Printen records';
SExportRecord = 'Exporteren records';
SImportRecord = 'Importeren records';
SPostEdit = 'Bewaar wijzigingen';
SCancelEdit = 'Annuleer wijzigen';
SRefreshRecord = 'Ververs data';
SChoice = 'Selecteer een record';
SClear = 'Selecite opheffen';
SDeleteRecordQuestion = 'Verwijder record?';
SDeleteMultipleRecordsQuestion = 'Wilt u alle geselecteerd records verwijderen?';
SRecordNotFound = 'Geen record gevonden';
SFirstName = 'Eerste';
SPriorName = 'Vorige';
SNextName = 'Volgende';
SLastName = 'Laatste';
SInsertName = 'Toevoegen';
SCopyName = 'Kopieer';
SDeleteName = 'Verwijder';
SEditName = 'Wijzig';
SFilterName = 'Filter';
SFindName = 'Zoeken';
SPrintName = 'Print';
SExportName = 'Exporteren';
SImportName = 'Importeren';
SPostName = 'Bewaren';
SCancelName = 'Annuleren';
SRefreshName = 'Ververs';
SChoiceName = 'Kies';
SClearName = 'Leeg maken';
SBtnOk = '&OK';
SBtnCancel = '&Annuleer';
SBtnLoad = 'Openen';
SBtnSave = 'Bewaren';
SBtnCopy = 'Kopieer';
SBtnPaste = 'Plakken';
SBtnClear = 'Leeg maken';
SRecNo = 'rec.';
SRecOf = ' van ';
const //for EditTyped
etValidNumber = 'geldig nummer';
etValidInteger = 'geldig integer nummer';
etValidDateTime = 'geldige datum/tijd';
etValidDate = 'geldige datum';
etValidTime = 'geldige tijd';
etValid = 'geldig(e)';
etIsNot = 'is geen';
etOutOfRange = 'waarde %s buiten bereik %s..%s';
SApplyAll = 'Toepassen op alle';
SNoDataToDisplay = '<Geen gegevens om weer te geven>';
SPrevYear = 'voorgaand jaar';
SPrevMonth = 'Voorgaande maand';
SNextMonth = 'Volgende maand';
SNextYear = 'volgend jaarr';
implementation
end.
|
unit FontFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
Vcl.StdCtrls, Vcl.CheckLst, Vcl.ComCtrls, Vcl.ToolWin, System.ImageList,
Vcl.ImgList, Vcl.Buttons;
const
CharFrom:Integer = 32;
CharTo:Integer = 255;
type
TFontFrm = class(TFrame)
Image1: TImage;
Panel1: TPanel;
Label3: TLabel;
Label1: TLabel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Panel2: TPanel;
CBL: TCheckListBox;
Splitter1: TSplitter;
FD: TFontDialog;
SB: TStatusBar;
ImageList1: TImageList;
TB: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
ToolButton7: TToolButton;
ToolButton8: TToolButton;
ToolButton9: TToolButton;
ToolButton10: TToolButton;
ToolButton11: TToolButton;
ToolButton12: TToolButton;
ToolButton13: TToolButton;
SBX: TScrollBox;
procedure Button3Click(Sender: TObject);
procedure CBLClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure CBLClickCheck(Sender: TObject);
procedure Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure ToolButton1Click(Sender: TObject);
procedure ToolButton12Click(Sender: TObject);
procedure ToolButton10Click(Sender: TObject);
procedure ToolButton11Click(Sender: TObject);
procedure ToolButton8Click(Sender: TObject);
procedure ToolButton13Click(Sender: TObject);
procedure CBLKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SBXMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure SBXMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure ToolButton2Click(Sender: TObject);
procedure ToolButton5Click(Sender: TObject);
procedure ToolButton6Click(Sender: TObject);
private
Koeff:Integer;
FOnNeedMakeProg: TNotifyEvent;
FMouseFlag:Integer;
function GetFontName: String;
procedure SetOnNeedMakeProg(const Value: TNotifyEvent);
procedure MoveLetterRight(AIndex:Integer);
procedure MoveLetterLeft(AIndex:Integer);
procedure MoveLetterTop(AIndex:Integer);
procedure MoveLetterBottom(AIndex:Integer);
function CalcPixel(APoint:TPoint):TPoint;
procedure RefreshLetter;
{ Private declarations }
public
{ Public declarations }
tmpBitmap:TBitmap;
List:TStringList;
MaxW,MaxH:Integer;
constructor Create(AOwner:TComponent); override;
property OnNeedMakeProg:TNotifyEvent read FOnNeedMakeProg write SetOnNeedMakeProg;
property FontName:String read GetFontName;
procedure DrawLetter(AIndex:Integer);
procedure ClearList;
procedure ImportFont;
procedure Optimize;
procedure InitFont;
procedure InsertLeftCol;
procedure InsertRightCol;
procedure InsertTopRow;
procedure InsertBottomRow;
end;
TByteArray = array of byte;
TLetter=class(TObject)
Matrix: array of TByteArray;
BMP:TBitmap;
Width:Integer;
constructor Create(W,H:Integer;C:AnsiChar;Font:TFont); virtual;
destructor Destroy; override;
end;
implementation
{$R *.dfm}
procedure TFontFrm.Button1Click(Sender: TObject);
begin
ImportFont;
Button1.Enabled:=false;
TB.Visible:=true;
if Assigned(FOnNeedMakeProg) then FOnNeedMakeProg(Self);
end;
procedure TFontFrm.Button2Click(Sender: TObject);
begin
if FD.Execute(Handle) then begin
Label3.Font:=FD.Font;
Label3.Caption:=FontName;
end;
end;
procedure TFontFrm.Button3Click(Sender: TObject);
begin
Optimize;
DrawLetter(CBL.ItemIndex);
if Assigned(FOnNeedMakeProg) then FOnNeedMakeProg(Self);
end;
function TFontFrm.CalcPixel(APoint: TPoint): TPoint;
var x,Y:Integer;
begin
Result.X:=Trunc(APoint.X/Koeff);
Result.Y:=Trunc(APoint.Y/Koeff);
end;
procedure TFontFrm.CBLClick(Sender: TObject);
begin
DrawLetter(CBL.ItemIndex);
if Assigned(FOnNeedMakeProg) then FOnNeedMakeProg(Self);
Application.ProcessMessages;
end;
procedure TFontFrm.CBLClickCheck(Sender: TObject);
begin
if Assigned(FOnNeedMakeProg) then FOnNeedMakeProg(Self);
end;
procedure TFontFrm.CBLKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// DrawLetter(CBL.ItemIndex);
// if Assigned(FOnNeedMakeProg) then FOnNeedMakeProg(Self);
end;
procedure TFontFrm.ClearList;
begin
while List.Count<>0 do begin
List.Objects[0].Destroy;
List.Objects[0]:=nil;
List.Delete(0);
end;
CBL.Items.Clear;
end;
constructor TFontFrm.Create(AOwner: TComponent);
begin
inherited;
Koeff:=15;
tmpBitmap:=TBitmap.Create;
List:=TStringList.Create;
end;
procedure TFontFrm.DrawLetter(AIndex: Integer);
var x,y,x1,y1,k,c:Integer;
R,R1:TRect;
L:TLetter;
begin
l:=TLetter(List.Objects[AIndex]);
try
k:=Koeff;
tmpBitmap.SetSize(L.Width*k+1,MaxH*k+1);
R1:=Rect(0,0,L.Width*k-1,MaxH*k-1);
with tmpBitmap.Canvas do begin
Brush.Color:=clWhite;
Pen.Color:=RGB(220,220,220);
Pen.Style:=psSolid;
FillRect(R1);
X:=0;
x1:=0;
while x<=L.Width*k do begin
y:=0;
y1:=0;
MoveTo(x,0);
LineTo(x,MaxH*k);
while y<=MaxH*k do begin
MoveTo(0,Y);
LineTo(L.Width*k,Y);
R:=Rect(x+1,y+1,x+k,y+k);
if x1<=L.Width then if y1<=High(L.Matrix[x1]) then begin
c:=L.Matrix[x1][y1];
if C<>clBlack then C:=clWhite;
Brush.Color:=C;
FillRect(R);
end;
y:=y+k;
y1:=y1+1;
end;
x:=x+k;
x1:=x1+1;
end;
end;
finally
Image1.Picture.Bitmap:=tmpBitmap;
Image1.Width:=R1.Width;
Image1.Height:=R1.Height;
end;
end;
function TFontFrm.GetFontName: String;
begin
Result:=FD.Font.Name+', '+IntToStr(FD.Font.Size);
if fsBold in FD.Font.Style then Result:=Result+', bold';
if fsItalic in FD.Font.Style then Result:=Result+', italic';
if fsUnderline in FD.Font.Style then Result:=Result+', underline';
if fsStrikeOut in FD.Font.Style then Result:=Result+', strikeout';
end;
procedure TFontFrm.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button=mbLeft then FMouseFlag:=1;
if Button=mbRight then FMouseFlag:=2;
end;
procedure TFontFrm.Image1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var P:TPoint;
L:TLetter;
begin
if CBL.ItemIndex=-1 then exit;
P.X:=Trunc((x-1)/koeff);
P.Y:=Trunc((y-1)/koeff);
SB.Panels[0].Text:=IntToStr(x)+', '+IntToStr(y)+' | '+IntToStr(P.X)+', '+IntToStr(P.Y);
if FMouseFlag<>0 then begin
L:=TLetter(List.Objects[CBL.ItemIndex]);
if FMouseFlag=1 then L.Matrix[p.X][p.Y]:=0;
if FMouseFlag=2 then L.Matrix[p.X][p.Y]:=255;
DrawLetter(CBL.ItemIndex);
end;
end;
procedure TFontFrm.Image1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
FMouseFlag:=0;
end;
procedure TFontFrm.ImportFont;
var x:Byte;
S:String;
H,W:Integer;
L:TLetter;
Enc:TEncoding;
begin
with tmpBitmap.Canvas do begin
Font:=FD.Font;
Font.Color:=clBlack;
Brush.Color:=clWhite;
// get max width and height
MaxW:=0;
MaxH:=0;
for x := CharFrom to CharTo do begin
S:=AnsiChar(X);
h:=TextHeight(S);
w:=TextWidth(S);
if H>MaxH then MaxH:=H;
if W>MaxW then MaxW:=W;
end;
CBL.Items.Clear;
ClearList;
CBL.Visible:=false;
for x := CharFrom to CharTo do begin
L:=TLetter.Create(MaxW,MaxH,AnsiChar(X),FD.Font);
List.AddObject(AnsiChar(X),L);
CBL.Items.Add(IntToStr(X)+' ('+IntToHex(X)+') '+AnsiChar(X));
if not(((x>=128) and (x<=167)) or ((x>=169)and(x<=183)) or ((x>=185)and(x<=191))) then CBL.Checked[CBL.Items.Count-1]:=true;
end;
CBL.Visible:=True;
CBL.ItemIndex:=0;
DrawLetter(0);
end;
Label1.Caption:='Высота шрифта '+IntToStr(MaxH);
end;
procedure TFontFrm.InitFont;
begin
Label3.Font:=FD.Font;
Label3.Caption:=FontName;
end;
procedure TFontFrm.InsertBottomRow;
begin
end;
procedure TFontFrm.InsertLeftCol;
var a:Integer;
begin
InsertRightCol;
for a := 0 to List.Count-1 do begin
MoveLetterRight(a);
end;
end;
procedure TFontFrm.InsertRightCol;
var a,x,y:Integer;
L:TLetter;
begin
for a := 0 to List.Count-1 do begin
L:=TLetter(List.Objects[a]);
SetLength(L.Matrix,L.Width+1);
SetLength(L.Matrix[L.Width],MaxH);
L.Width:=L.Width+1;
for y := 0 to MaxH-1 do begin
L.Matrix[L.Width-1][y]:=255;
end;
end;
end;
procedure TFontFrm.InsertTopRow;
begin
end;
procedure TFontFrm.MoveLetterBottom(AIndex: Integer);
var x,y:Integer;
L:TLetter;
begin
L:=TLetter(List.Objects[AIndex]);
L:=TLetter(List.Objects[AIndex]);
for x := 0 to L.Width-1 do begin
for y := MaxH-1 downto 1 do begin
L.Matrix[x][y]:=L.Matrix[x][y-1];
end;
end;
for x := 0 to L.Width-1 do
L.Matrix[x][0]:=255;
end;
procedure TFontFrm.MoveLetterLeft(AIndex: Integer);
var x,y:Integer;
L:TLetter;
begin
L:=TLetter(List.Objects[AIndex]);
L:=TLetter(List.Objects[AIndex]);
for x := 0 to L.Width-2 do begin
for y := 0 to MaxH-1 do begin
L.Matrix[x][y]:=L.Matrix[x+1][y];
end;
end;
for y := 0 to MaxH do begin
L.Matrix[L.Width-1][y]:=255;
end;
end;
procedure TFontFrm.MoveLetterRight(AIndex: Integer);
var x,y:Integer;
L:TLetter;
begin
L:=TLetter(List.Objects[AIndex]);
for x := L.Width-1 downto 1 do begin
for y := 0 to MaxH-1 do begin
L.Matrix[x][y]:=L.Matrix[x-1][y];
end;
end;
for y := 0 to MaxH do begin
L.Matrix[0][y]:=255;
end;
end;
procedure TFontFrm.MoveLetterTop(AIndex: Integer);
var x,y:Integer;
L:TLetter;
begin
L:=TLetter(List.Objects[AIndex]);
L:=TLetter(List.Objects[AIndex]);
for x := 0 to L.Width-1 do begin
for y := 0 to MaxH-1 do begin
L.Matrix[x][y]:=L.Matrix[x][y+1];
end;
end;
for x := 0 to L.Width-1 do
L.Matrix[x][MaxH-1]:=255;
end;
procedure TFontFrm.Optimize;
var x,y,m,lastcol:Integer;
L:TLetter;
Flag:Boolean;
begin
for x := 0 to CBL.Count-1 do begin
L:=TLetter(List.Objects[x]);
Flag:=true;
lastCol:=0;
repeat
repeat
for m := High(L.Matrix[L.Width-1])-1 downto 0 do
if L.Matrix[L.Width-1][m]=clBlack then begin
Flag:=false;
L.Width:=L.Width+1;
break;
end;
if Flag then L.Width:=L.Width-1;
until (not flag) or (L.Width=0);
// for y := 0 to High(L.Matrix) do begin
// for m := 0 to High(L.Matrix[y])-1 do
// if L.Matrix[y][m]=clBlack then begin
// Flag:=false;
// L.Width:=m+1;
// break;
// end;
// if not Flag then break;
//
// end;
if L.Width=0 then begin
Flag:=false;
L.Width:=Round(MaxW/2);
end;
Until not flag;
end;
end;
procedure TFontFrm.RefreshLetter;
begin
if CBL.ItemIndex<>-1 then DrawLetter(CBL.ItemIndex);
end;
procedure TFontFrm.SBXMouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if ssCtrl in Shift then Begin
if CBL.ItemIndex<>-1 then begin
Koeff:=Koeff-1;
if Koeff<2 then Koeff:=2;
DrawLetter(CBL.ItemIndex);
end;
End;
end;
procedure TFontFrm.SBXMouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if ssCtrl in Shift then Begin
if CBL.ItemIndex<>-1 then begin
Koeff:=Koeff+1;
DrawLetter(CBL.ItemIndex);
end;
End;
end;
procedure TFontFrm.SetOnNeedMakeProg(const Value: TNotifyEvent);
begin
FOnNeedMakeProg := Value;
end;
procedure TFontFrm.ToolButton10Click(Sender: TObject);
begin
if CBL.ItemIndex<>-1 then begin
MoveLetterLeft(CBL.ItemIndex);
DrawLetter(CBl.ItemIndex);
end;
end;
procedure TFontFrm.ToolButton11Click(Sender: TObject);
begin
if CBL.ItemIndex<>-1 then begin
MoveLetterTop(CBL.ItemIndex);
DrawLetter(CBl.ItemIndex);
end;
end;
procedure TFontFrm.ToolButton12Click(Sender: TObject);
begin
if CBL.ItemIndex<>-1 then begin
MoveLetterRight(CBL.ItemIndex);
DrawLetter(CBl.ItemIndex);
end;
end;
procedure TFontFrm.ToolButton13Click(Sender: TObject);
begin
if CBL.ItemIndex<>-1 then begin
MoveLetterBottom(CBL.ItemIndex);
DrawLetter(CBl.ItemIndex);
end;
end;
procedure TFontFrm.ToolButton1Click(Sender: TObject);
begin
InsertLeftCol;
RefreshLetter;
end;
procedure TFontFrm.ToolButton2Click(Sender: TObject);
begin
InsertRightCol;
RefreshLetter;
end;
procedure TFontFrm.ToolButton5Click(Sender: TObject);
begin
InsertTopRow;
RefreshLetter;
end;
procedure TFontFrm.ToolButton6Click(Sender: TObject);
begin
InsertBottomRow;
RefreshLetter;
end;
procedure TFontFrm.ToolButton8Click(Sender: TObject);
begin
if CBL.ItemIndex<>-1 then begin
MaxH:=MaxH-1;
Label1.Caption:='Высота шрифта '+IntToStr(MaxH);
DrawLetter(CBl.ItemIndex);
end;
end;
{ TLetter }
constructor TLetter.Create(W,H:Integer;C:AnsiChar;Font:TFont);
var R:TRect;
x,y:Integer;
S:String;
Flag:Boolean;
begin
TObject.Create;
Width:=W;
BMP:=TBitmap.Create;
BMP.Monochrome:=True;
BMP.SetSize(W+1,H+1);
R:=Rect(0,0,W,H);
BMP.Canvas.Font:=Font;
BMP.Canvas.Brush.Color:=clWhite;
BMP.Canvas.Font.Color:=clBlack;
BMP.Canvas.FillRect(R);
S:=C;
DrawText(BMP.Canvas.Handle,S,1,R,DT_SINGLELINE);
SetLength(Matrix,W);
for x := 0 to W-1 do begin
SetLength(Matrix[x],H);
for y := 0 to H-1 do begin
Matrix[x][y]:=BMP.Canvas.Pixels[x,y];
end;
end;
// анализ, вдруг надо вставить колонку в конце, чтобы оптимизатор не глючил
Flag:=False;
for y := 0 to H-1 do
if Matrix[w-1][y]=clBlack then Flag:=true;
if Flag then begin
//добавим пустую колонку
SetLength(Matrix,W+1);
SetLength(Matrix[W],H);
for y := 0 to H-1 do Matrix[W][y]:=255;
Width:=W+1;
end;
end;
destructor TLetter.Destroy;
begin
SetLength(Matrix,0);
BMP.Destroy;
BMP:=nil;
inherited;
end;
end.
|
unit Getter.Filesystem.Name;
interface
uses
Windows,
OSFile.ForInternal;
type
TFileSystemNameGetter = class(TOSFileForInternal)
private
FileSystemNameInCharArray: Array[0..MAX_PATH - 1] of Char;
public
function GetFileSystemName: String;
end;
implementation
{ TFileSystemNameGetter }
function TFileSystemNameGetter.GetFileSystemName: String;
var
Useless: DWORD;
PathToGetFileSystemName: String;
begin
Useless := 0;
PathToGetFileSystemName := GetPathOfFileAccessing + '\';
GetVolumeInformation(PChar(PathToGetFileSystemName), nil, 0, nil, Useless,
Useless, FileSystemNameInCharArray, SizeOf(FileSystemNameInCharArray));
result := PChar(@FileSystemNameInCharArray[0]);
end;
end.
|
unit xProtocolDL645;
interface
uses xProtocolBase, xDL645Type, xProtocolPacksDL645_07, xProtocolPacksDL645_97,
system.SysUtils, xProtocolPacksDl645, System.Classes;
type
TProtocolDL645 = class(TProtocolBase)
private
FProrocolType: TDL645_PROTOCOL_TYPE;
FPack97 : TProtocolPacksDL645_97;
fPack07 : TProtocolPacksDL645_07;
FOnRev645Data: TGet645Data;
function GetDL645Pack : TProtocolPacksDl645;
/// <summary>
/// 接收数据
/// </summary>
procedure Rve645Data( A645data : TStringList );
protected
/// <summary>
/// 生成数据包
/// </summary>
function CreatePacks: TBytes; override;
public
constructor Create; override;
destructor Destroy; override;
/// <summary>
/// 协议类型
/// </summary>
property ProrocolType : TDL645_PROTOCOL_TYPE read FProrocolType write FProrocolType;
/// <summary>
/// 接收数据包
/// </summary>
procedure ReceivedData(aPacks: TBytes; sParam1, sParam2 : string); override;
/// <summary>
/// 接收数据事件
/// </summary>
property OnRev645Data : TGet645Data read FOnRev645Data write FOnRev645Data;
end;
implementation
{ TProtocolDL645 }
constructor TProtocolDL645.Create;
begin
inherited;
FPack97 := TProtocolPacksDL645_97.Create;
fPack07 := TProtocolPacksDL645_07.Create;
FPack97.OnRev645Data := Rve645Data;
fPack07.OnRev645Data := Rve645Data;
end;
function TProtocolDL645.CreatePacks: TBytes;
begin
if Assigned(FDev) then
begin
if FDev is TDL645_DATA then
begin
case TDL645_DATA(FDev).MeterProtocolType of
dl645pt1997 :
begin
Result := FPack97.GetPacks(FOrderType, FDev);
end;
dl645pt2007:
begin
Result := FPack07.GetPacks(FOrderType, FDev);
end
else
Result := nil;
end;
end
else
begin
Result := nil;
end;
end
else
begin
Result := nil;
end;
end;
destructor TProtocolDL645.Destroy;
begin
inherited;
end;
function TProtocolDL645.GetDL645Pack: TProtocolPacksDl645;
begin
if FProrocolType = dl645pt2007 then
begin
Result := fPack07;
end
else if FProrocolType = dl645pt1997 then
begin
Result := FPack97;
end
else
begin
result := nil;
end;
end;
procedure TProtocolDL645.ReceivedData(aPacks: TBytes; sParam1, sParam2: string);
var
APack : TProtocolPacksDl645;
begin
inherited;
APack := GetDL645Pack;
if Assigned(APack) then
begin
APack.RevPacks( FOrderType, FDev, aPacks);
end;
end;
procedure TProtocolDL645.Rve645Data(A645data: TStringList);
begin
if Assigned (FOnRev645Data) then
begin
FOnRev645Data(A645data);
end;
end;
end.
|
unit UFrmExample2;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls;
type
TFrmExample2 = class(TForm)
Panel2: TPanel;
Panel3: TPanel;
Panel1: TPanel;
ListBox1: TListBox;
Label1: TLabel;
Panel4: TPanel;
Image1: TImage;
BtnAbrir: TButton;
BtnCancelar: TButton;
procedure ListBox1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
FBmpResName: TStringList;
FFileName: TStringList;
FSelIndex: Integer;
public
{ Public declarations }
function Execute: Boolean;
procedure CarregaExemploSelecionado;
procedure CarregaPrimeiroExemplo;
end;
var
FrmExample2: TFrmExample2;
implementation
{$R *.dfm}
uses
StrUtils, UFrmEditor, port_UFrmConfig;
function CarregaImg(Img: TImage; Nome: String): Boolean;
var
Bmp: Graphics.TBitmap;
begin
Result := True;
Bmp := Graphics.TBitmap.Create;
try
Bmp.LoadFromResourceName(HInstance, Nome);
Img.Picture.Bitmap.Assign(Bmp);
except
Result := False;
end;
Bmp.Free;
end;
procedure TFrmExample2.ListBox1Click(Sender: TObject);
begin
CarregaImg(Image1, FBmpResName[ListBox1.ItemIndex]);
end;
procedure TFrmExample2.FormShow(Sender: TObject);
begin
// ListBox1.ItemIndex := 0;
ListBox1Click(Self);
ListBox1.SetFocus;
end;
procedure TFrmExample2.FormCreate(Sender: TObject);
begin
FBmpResName := TStringList.Create;
FFileName := TStringList.Create;
FBmpResName.Add('Bmp-Ola'); FFileName.Add('olá');
FBmpResName.Add('Bmp-Fato-ou-Fita'); FFileName.Add('fato-ou-fita');
FBmpResName.Add('Bmp-Retangulo'); FFileName.Add('retângulo');
FBmpResName.Add('Bmp-Circulo'); FFileName.Add('círculo');
FBmpResName.Add('Bmp-Triangulo'); FFileName.Add('triângulo');
FBmpResName.Add('Bmp-Linha'); FFileName.Add('linha');
FBmpResName.Add('Bmp-Linhas'); FFileName.Add('linhas');
FBmpResName.Add('Bmp-Retangulos-Coloridos'); FFileName.Add('retângulos-coloridos');
FBmpResName.Add('Bmp-Tamanhos-Caneta'); FFileName.Add('tamanhos-caneta');
FBmpResName.Add('Bmp-Estilos-Caneta'); FFileName.Add('estilos-caneta');
FBmpResName.Add('Bmp-Texto-Grafico'); FFileName.Add('texto-gráfico');
FBmpResName.Add('Bmp-Quadrados'); FFileName.Add('quadrados');
FBmpResName.Add('Bmp-Sucessor'); FFileName.Add('sucessor');
FBmpResName.Add('Bmp-Metade'); FFileName.Add('metade');
FBmpResName.Add('Bmp-Metade-2'); FFileName.Add('metade-2');
FBmpResName.Add('Bmp-Clicou'); FFileName.Add('clicou');
FBmpResName.Add('Bmp-Clicou-Aqui'); FFileName.Add('clicou-aqui');
FBmpResName.Add('Bmp-Clicou-Aqui-Oval');FFileName.Add('clicou-aqui-oval');
FBmpResName.Add('Bmp-Clicou-na-Linha'); FFileName.Add('clicou-na-linha');
FBmpResName.Add('Bmp-Esquerda-ou-Direita');FFileName.Add('esquerda-ou-direita');
FBmpResName.Add('Bmp-No-Corredor'); FFileName.Add('no-corredor');
FBmpResName.Add('Bmp-Fora-do-Corredor');FFileName.Add('fora-do-corredor');
FBmpResName.Add('Bmp-Nove-Retangulos'); FFileName.Add('nove-retângulos');
FBmpResName.Add('Bmp-Retangulos'); FFileName.Add('retângulos');
FBmpResName.Add('Bmp-Cone-Curvo'); FFileName.Add('cone-curvo');
FBmpResName.Add('Bmp-Tab-Quadrados'); FFileName.Add('tab-quadrados');
FBmpResName.Add('Bmp-Curvas-Bezier'); FFileName.Add('curvas-bezier');
FBmpResName.Add('Bmp-Clica-no-Retangulo'); FFileName.Add('clica-no-retângulo');
FBmpResName.Add('Bmp-N-Cliques'); FFileName.Add('n-cliques');
FBmpResName.Add('Bmp-Arco-Fatia'); FFileName.Add('arco-fatia');
FBmpResName.Add('Bmp-Fatias-Coloridas');FFileName.Add('fatias-coloridas');
FBmpResName.Add('Bmp-Tres-Figuras'); FFileName.Add('três-figuras');
FBmpResName.Add('Bmp-P1p2p3'); FFileName.Add('p1p2p3');
FBmpResName.Add('Bmp-Robo'); FFileName.Add('robô');
FBmpResName.Add('Bmp-Marcas'); FFileName.Add('marcas');
FBmpResName.Add('Bmp-Tamanho-Texto'); FFileName.Add('tamanho-texto');
FBmpResName.Add('Bmp-Caracteres'); FFileName.Add('caracteres');
FBmpResName.Add('Bmp-Ovais'); FFileName.Add('ovais');
FBmpResName.Add('Bmp-Menor'); FFileName.Add('menor');
FBmpResName.Add('Bmp-Texto-Invertido'); FFileName.Add('texto-invertido');
FBmpResName.Add('Bmp-Primeiras-Teclas');FFileName.Add('primeiras-teclas');
FBmpResName.Add('Bmp-Eventos'); FFileName.Add('eventos');
FBmpResName.Add('Bmp-Aloc-Var-Local'); FFileName.Add('aloc-var-local');
FBmpResName.Add('Bmp-Passagem-Args'); FFileName.Add('passagem-args');
FBmpResName.Add('Bmp-Linhas-Conectadas');FFileName.Add('linhas-conectadas');
FBmpResName.Add('Bmp-Raios'); FFileName.Add('raios');
FBmpResName.Add('Bmp-Desenho-com-Mouse');FFileName.Add('desenho-com-mouse');
FBmpResName.Add('Bmp-Coord-Mouse'); FFileName.Add('coord-mouse');
FBmpResName.Add('Bmp-Figuras-Aleatorias');FFileName.Add('figuras-aleatórias');
FBmpResName.Add('Bmp-Spray'); FFileName.Add('spray');
FBmpResName.Add('Bmp-Contagem-Regressiva'); FFileName.Add('contagem-regressiva');
FBmpResName.Add('Bmp-Contagem-Regressiva-Dez'); FFileName.Add('contagem-regressiva-dez');
FBmpResName.Add('Bmp-Tic-Tac'); FFileName.Add('tic-tac');
FBmpResName.Add('Bmp-Gary-Chaffee-Idea-2');FFileName.Add('gary-chaffee-idea-2');
FBmpResName.Add('Bmp-Arranjo-Simples'); FFileName.Add('arranjo-simples');
FBmpResName.Add('Bmp-Pontos-Conectados');FFileName.Add('pontos-conectados');
FBmpResName.Add('Bmp-Mesa-de-Bilhar'); FFileName.Add('mesa-de-bilhar');
FBmpResName.Add('Bmp-Figuras-Aleatorias-Jan');FFileName.Add('figuras-aleatórias-jan');
FBmpResName.Add('Bmp-Itens-Graficos'); FFileName.Add('itens-gráficos');
FBmpResName.Add('Bmp-Edita-Rotulo'); FFileName.Add('edita-rótulo');
FBmpResName.Add('Bmp-Eventos-de-Itens');FFileName.Add('eventos-de-itens');
FBmpResName.Add('Bmp-Foto-Rio'); FFileName.Add('foto-rio');
FBmpResName.Add('Bmp-Moldura'); FFileName.Add('moldura');
FBmpResName.Add('Bmp-Inverte-Arq'); FFileName.Add('inverte-arq');
FBmpResName.Add('Bmp-Ponteiros'); FFileName.Add('ponteiros');
FBmpResName.Add('Bmp-Serpente'); FFileName.Add('serpente');
FBmpResName.Add('Bmp-Quadrado-no-Clique');FFileName.Add('quadrado-no-clique');
FBmpResName.Add('Bmp-Jogo-do-Caos'); FFileName.Add('jogo-do-caos');
FBmpResName.Add('Bmp-Estrela'); FFileName.Add('estrela');
FBmpResName.Add('Bmp-Recursao-Enquanto'); FFileName.Add('recursão-enquanto');
FBmpResName.Add('Bmp-Tri-Sierp'); FFileName.Add('tri-sierp');
FBmpResName.Add('Bmp-Fatorial'); FFileName.Add('fatorial');
FBmpResName.Add('Bmp-Teste-Ordenacao-Visual'); FFileName.Add('teste-ordenação-visual');
FBmpResName.Add('Bmp-Oito-Rainhas'); FFileName.Add('oito-rainhas');
FBmpResName.Add('Bmp-Arvore-Bin-Psq'); FFileName.Add('árvore-bin-psq');
FBmpResName.Add('Bmp-Andromeda'); FFileName.Add('andrômeda');
FBmpResName.Add('Bmp-Estrela-Fractal'); FFileName.Add('estrela-fractal');
FBmpResName.Add('Bmp-Pintor'); FFileName.Add('pintor');
FBmpResName.Add('Bmp-Reveillon'); FFileName.Add('reveillon');
FBmpResName.Add('Bmp-Curva-de-Sierpinski');FFileName.Add('curva-sierpinski');
FBmpResName.Add('Bmp-Fractais-MRCM'); FFileName.Add('fractais-mrcm');
FBmpResName.Add('Bmp-Jogo-da-Memoria'); FFileName.Add('jogo-da-memória');
FBmpResName.Add('Bmp-Curva-de-Hilbert');FFileName.Add('curva-hilbert');
Self.Width := 900;
end;
procedure TFrmExample2.CarregaExemploSelecionado;
var
Str: TStringList;
Res: TResourceStream;
NomeRes, NomeArq: String;
function BmpParaArq(S: String): String;
begin
Result := 'Arq-' + AnsiMidStr(S, 5, Length(S) - 4);
end;
(*
function BmpParaNomeArq(S: String): String;
var
I: Integer;
begin
Result := AnsiMidStr(S, 5, Length(S) - 4); // tira o prefixo 'Bmp-'
Result := AnsiLowerCase(Result); // só minúsculas
for I := 1 to Length(Result) do // troca '-' por '_'
if Result[I] = '-' then
Result[I] := '_';
Result := Result + FrmConfig.ExtensaoDefaultPrg();
end;
*)
begin
// cria o resource
NomeRes := BmpParaArq(FBmpResName[ListBox1.ItemIndex]);
Res := TResourceStream.Create(HInstance, NomeRes, RT_RCDATA);
// cria o tstringlist com base no res
Str := TStringList.Create;
Str.LoadFromStream(Res);
// abre uma aba no editor
NomeArq := FFileName[ListBox1.ItemIndex] + FrmConfig.ExtensaoDefaultPrg();
NomeArq := FrmConfig.NomeProgramaCompleto(NomeArq);
FrmEditor.AddTab(Str, NomeArq, True);
Str.Free;
Res.Free;
FSelIndex := ListBox1.ItemIndex;
end;
function TFrmExample2.Execute: Boolean;
begin
ListBox1.ItemIndex := FSelIndex;
ListBox1Click(Self);
Result := ShowModal() = mrOk;
end;
procedure TFrmExample2.CarregaPrimeiroExemplo;
begin
ListBox1.ItemIndex := 0;
CarregaExemploSelecionado;
end;
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*****************************************************************
The following delphi code is based on Emule (0.46.2.26) Kad's implementation http://emule.sourceforge.net
and KadC library http://kadc.sourceforge.net/
*****************************************************************
}
{
Description:
DHT binary tree code
}
unit dhtzones;
interface
uses
dhtroutingbin,int128,classes,windows,
sysutils,dhtcontact,math,classes2;
type
TRoutingZone=class(Tobject)
m_subZones:array[0..1] of TRoutingZone;
m_superZone:TRoutingZone;
m_bin:TRoutingBin;
m_zoneIndex:CU_INT128;
m_level:cardinal;
m_nextBigTimer:cardinal;
m_nextSmallTimer:cardinal;
function isLeaf:boolean;
function canSplit:boolean;
constructor create;
destructor destroy; override;
procedure init(super_zone:TRoutingZone; level:integer; zone_index:pCU_INT128; shouldStartTimer:boolean=true);
function Add(id:pCU_Int128; ip:cardinal; port:word; tport:word; ttype:byte):boolean;
procedure split;
procedure merge;
function genSubZone(side:integer):TRoutingZone;
function getNumContacts:cardinal;
procedure topDepth(depth:integer; list:Tmylist; emptyFirst:boolean = false);
procedure randomBin(list:Tmylist; emptyFirst:boolean = false);
procedure startTimer;
procedure StopTimer;
function onBigTimer:boolean;
procedure onSmallTimer;
procedure randomLookup;
function getMaxDepth:cardinal;
procedure getAllEntries(list:Tmylist; emptyFirst:boolean=false);
function getClosestTo(maxType:cardinal; target:pCU_INT128; distance:pCU_INT128;
maxRequired:cardinal; ContactMap:tmylist; emptyFirst:boolean=false; inUse:boolean=false):cardinal;
function getContact(id:pCU_INT128; distance:pCU_INT128):TContact;
procedure setAlive(ip:cardinal; port:word; setroundtrip:boolean=false);
function FindHost(ip:cardinal):TContact;
end;
procedure DHT_readnodeFile(m_Filename:widestring; root:TRoutingZone);
procedure DHT_writeNodeFile(m_Filename:widestring; root:TRoutingZone);
procedure DHT_getBootstrapContacts(root:TRoutingZone; var list:Tmylist; maxRequired:cardinal);
implementation
uses
helper_diskio,dhtconsts,dhtsocket,
dhtsearchmanager,vars_global,helper_ipfunc,helper_datetime;
procedure DHT_writeNodeFile(m_Filename:widestring; root:TRoutingZone);
var
stream:thandlestream;
buffer:array[0..24] of byte;
i:integer;
numD:cardinal;
c:TContact;
contacts:tmylist;
begin
stream:=MyFileOpen(m_filename,ARES_OVERWRITE_EXISTING);
if stream=nil then begin
exit;
end;
contacts:=tmylist.create;
DHT_getBootstrapContacts(root,contacts,200);
numD:=min(contacts.Count,CONTACT_FILE_LIMIT);
stream.write(numD,4);
for i:=0 to contacts.count-1 do begin
c:=contacts[i];
CU_INT128_CopyToBuffer(@c.m_clientID,@buffer[0]);
move(c.m_ip,buffer[16],4); // watch it...emule uses reversed order , we don't
move(c.m_UDPPort,buffer[20],2);
move(c.m_TCPPort,buffer[22],2);
buffer[24]:=c.m_type;
stream.write(buffer,25);
if i=CONTACT_FILE_LIMIT then break;
end;
FreeHandleStream(stream);
contacts.free;
end;
procedure DHT_readnodeFile(m_Filename:widestring; root:TRoutingZone);
var
stream:thandlestream;
numEntries:cardinal;
buffer:array[0..24] of byte;
i:integer;
ipC:cardinal;
UDPPortW,TCPPortW:word;
ttype:byte;
clientID:CU_INT128;
begin
stream:=MyFileOpen(m_filename,ARES_READONLY_BUT_SEQUENTIAL);
if stream=nil then begin
exit;
end;
numEntries:=0;
if stream.read(numEntries,4)<>4 then begin
FreeHandleStream(stream);
exit;
end;
for i:=0 to NumEntries-1 do begin
if stream.read(buffer,25)<>25 then begin
break;
end;
move(buffer[16],ipC,4);
// ipC:=synsock.ntohl(ipC); // watch it...emule uses reversed order , we don't
if isAntiP2PIP(ipC) then continue;
if ip_firewalled(ipC) then continue;
if probable_fw(ipC) then continue;
CU_INT128_CopyFromBuffer(@buffer[0],@ClientID);
move(buffer[20],UDPPortW,2);
move(buffer[22],TCPPortW,2);
ttype:=buffer[24];
if ttype<4 then begin
root.add(@clientID, ipC, UDPPortW, TCPPortW, ttype);
end;
end;
FreeHandleStream(stream);
end;
procedure DHT_getBootstrapContacts(root:TRoutingZone; var list:Tmylist; maxRequired:cardinal);
begin
if root.m_superzone<>nil then exit;
list.clear;
root.topDepth(LOG_BASE_EXPONENT{5}, list);
while (list.count>maxRequired) do list.delete(list.count-1);
end;
///////////////////////////////////////////// TRoutingZone
constructor TRoutingZone.create;
begin
m_subzones[0]:=nil;
m_subzones[1]:=nil;
m_SuperZone:=nil;
end;
destructor TRoutingZone.destroy;
begin
if isLeaf then m_bin.free
else begin
TRoutingZone(m_subZones[0]).free;
TRoutingZone(m_subZones[1]).free;
end;
inherited;
end;
procedure TRoutingZone.init(super_zone:TRoutingZone; level:integer; zone_index:pCU_INT128; shouldStartTimer:boolean=true);
begin
m_superZone:=super_zone;
m_level:=level;
m_zoneIndex[0]:=zone_index[0];
m_zoneIndex[1]:=zone_index[1];
m_zoneIndex[2]:=zone_index[2];
m_zoneIndex[3]:=zone_index[3];
m_subZones[0]:=nil;
m_subZones[1]:=nil;
m_bin:=TRoutingBin.create;
m_nextSmallTimer:=time_now+m_zoneIndex[3];
if shouldStartTimer then startTimer;
end;
function TRoutingZone.canSplit:boolean;
begin
result:=false;
if m_level>=127 then exit;
// Check if we are close to the center
result:=(
((CU_INT128_MinorOf(@m_zoneIndex,KK)) or (m_level<KBASE)) and
(m_bin.m_entries.count=K10)
);
end;
function TRoutingZone.FindHost(ip:cardinal):TContact;
begin
if isLeaf then result:=m_bin.FindHost(ip)
else begin
result:=m_subZones[0].FindHost(ip);
if result<>nil then exit;
result:=m_subZones[1].FindHost(ip);
end;
end;
function TRoutingZone.Add(id:pCU_Int128; ip:cardinal; port:word; tport:word; ttype:byte):boolean;
var
distance:CU_INT128;
c:TContact;
begin
result:=false;
if id[0]=0 then exit;
if ((id[0]=0) and
(id[1]=0) and
(id[2]=0) and
(id[3]=0)) then exit;
if ((DHTme128[0]=id[0]) and
(DHTme128[1]=id[1]) and
(DHTme128[2]=id[2]) and
(DHTme128[3]=id[3])) then exit;
CU_INT128_fillNXor(@distance,@DHTme128,id);
try
if not isLeaf then begin
result:=m_subZones[CU_INT128_getBitNumber(@distance,m_level)].add(id, ip, port, tport, ttype);
exit;
end;
c:=m_bin.getContact(id);
if c<>nil then begin
c.m_ip:=ip;
c.m_udpport:=port;
c.m_tcpport:=tport;
result:=true;
exit;
end;
if m_bin.m_entries.count<K10 then begin
c:=TContact.create;
c.Init(ID,ip,Port,tPort,@DHTme128);
result:=m_bin.add(c);
if not result then c.Free;
exit;
end;
if canSplit then begin
split;
result:=m_subZones[CU_INT128_getBitNumber(@distance,m_level)].add(id, ip, port, tport, ttype);
exit;
end;
merge;
c:=TContact.Create;
c.Init(ID,ip,Port,tPort,@DHTme128);
result:=m_bin.add(c);
if not result then c.free;
except
end;
end;
procedure TRoutingZone.setAlive(ip:cardinal; port:word; setroundtrip:boolean=false);
begin
if isLeaf then m_bin.setAlive(ip, port,setroundtrip)
else begin
m_subZones[0].setAlive(ip, port,setroundtrip);
m_subZones[1].setAlive(ip, port,setroundtrip);
end;
end;
function TRoutingZone.getContact(id:pCU_INT128; distance:pCU_INT128):TContact;
begin
if isLeaf then result:=m_bin.getContact(id)
else result:=m_subZones[CU_INT128_getBitNumber(distance{id},m_level)].getContact(id,distance);
end;
function TRoutingZone.getClosestTo(maxType:cardinal; target:pCU_INT128; distance:pCU_INT128; maxRequired:cardinal;
ContactMap:tmylist; emptyFirst:boolean=false; inUse:boolean=false):cardinal;
var
closer:integer;
found:cardinal;
begin
// If leaf zone, do it here
if isLeaf then begin
result:=m_bin.getClosestTo(maxType, target, maxRequired, ContactMap, emptyFirst, inUse);
exit;
end;
// otherwise, recurse in the closer-to-the-target subzone first
closer:=CU_INT128_GetBitNumber(distance,m_level);
found:=m_subZones[closer].getClosestTo(maxType, target, distance, maxRequired, ContactMap, emptyFirst, inUse);
sortCloserContacts(ContactMap,target);
// if still not enough tokens found, recurse in the other subzone too
if found<maxRequired then begin
found:=found+m_subZones[1-closer].getClosestTo(maxType, target, distance, maxRequired-found, ContactMap, false, inUse);
sortCloserContacts(ContactMap,target);
end;
result:=found;
end;
procedure TRoutingZone.getAllEntries(list:Tmylist; emptyFirst:boolean=false);
begin
if isLeaf then m_bin.getEntries(list, emptyFirst)
else begin
m_subZones[0].getAllEntries(list, emptyFirst);
m_subZones[1].getAllEntries(list, false);
end;
end;
procedure TRoutingZone.topDepth(depth:integer; list:Tmylist; emptyFirst:boolean = false);
begin
if isLeaf then m_bin.getEntries(list, emptyFirst)
else
if depth<=0 then randomBin(list, emptyFirst)
else begin
m_subZones[0].topDepth(depth-1, list, emptyFirst);
m_subZones[1].topDepth(depth-1, list, false);
end;
end;
procedure TRoutingZone.randomBin(list:Tmylist; emptyFirst:boolean = false);
begin
if isLeaf then m_bin.getEntries(list, emptyFirst)
else m_subZones[random(2)].randomBin(list, emptyFirst);
end;
function TRoutingZone.getMaxDepth:cardinal;
begin
result:=0;
if isLeaf then exit;
result:=1+max(m_subZones[0].getMaxDepth,m_subZones[1].getMaxDepth);
end;
procedure TRoutingZone.split;
var
i,sz:integer;
con:Tcontact;
begin
try
stopTimer;
m_subZones[0]:=genSubZone(0);
m_subZones[1]:=genSubZone(1);
for i:=0 to m_bin.m_entries.count-1 do begin
con:=m_bin.m_entries[i];
sz:=CU_INT128_getBitNumber(@con.m_distance,m_level);
m_subZones[sz].m_bin.add(con);
end;
m_bin.m_dontDeleteContacts:=true;
FreeAndNil(m_bin);
except
end;
end;
procedure TRoutingZone.merge;
var
i:integer;
con:TContact;
begin
try
if ((isLeaf) and (m_superZone<>nil)) then m_superZone.merge
else
if ( (not isLeaf) and
((m_subZones[0].isLeaf) and (m_subZones[1].isLeaf)) and
(getNumContacts<(K10 div 2)) ) then begin
m_bin:=TRoutingBin.create;
m_subZones[0].stopTimer;
m_subZones[1].stopTimer;
if getNumContacts>0 then begin
for i:=0 to m_subzones[0].m_bin.m_entries.count-1 do begin
con:=m_subzones[0].m_bin.m_entries[i];
m_bin.add(con);
end;
for i:=0 to m_subzones[1].m_bin.m_entries.count-1 do begin
con:=m_subzones[1].m_bin.m_entries[i];
m_bin.add(con);
end;
end;
m_subZones[0].m_superZone:=nil;
m_subZones[1].m_superZone:=nil;
FreeAndNil(m_subZones[0]);
FreeAndNil(m_subZones[1]);
startTimer;
if m_superZone<>nil then m_superZone.merge;
end;
except
end;
end;
function TRoutingZone.isLeaf:boolean;
begin
result:=(m_bin<>nil);
end;
function TRoutingZone.genSubZone(side:integer):TRoutingZone;
var
newIndex:CU_INT128;
begin
newIndex[0]:=m_zoneIndex[0];
newIndex[1]:=m_zoneIndex[1];
newIndex[2]:=m_zoneIndex[2];
newIndex[3]:=m_zoneIndex[3];
CU_INT128_shiftLeft(@newIndex,1);
if side<>0 then CU_INT128_add(@newIndex,1);
result:=TRoutingZone.create;
result.init(self, m_level+1, @newIndex);
end;
procedure TRoutingZone.startTimer;
begin
// Start filling the tree, closest bins first.
m_nextBigTimer:=time_now+(MIN2S(1)*m_zoneIndex[3])+SEC(10);
DHT_Events.add(self);
end;
procedure TRoutingZone.stopTimer;
var
ind:integer;
begin
try
ind:=DHT_Events.indexof(self);
if ind<>-1 then DHT_events.delete(ind);
except
end;
end;
function TRoutingZone.onBigTimer:boolean;
begin
result:=False;
if not isLeaf then exit;
if ( (CU_INT128_MinorOf(@m_zoneIndex,KK{5})) or
(m_level<KBASE{4}) or
(K10-m_bin.m_entries.count>=(K10*0.4))
) then begin
randomLookup;
result:=true;
end;
end;
procedure TRoutingZone.onSmallTimer;
var
c:Tcontact;
i:integer;
nowt:cardinal;
begin
if not isLeaf then exit;
c:=nil;
nowt:=time_now;
try
// Remove dead entries
i:=0;
while (i<m_bin.m_entries.count) do begin
c:=m_bin.m_entries[i];
if c.m_type=4 then begin
if (((c.m_expires>0) and (c.m_expires<=nowt))) then begin
if c.m_inUse=0 then begin
m_bin.m_entries.delete(i);
c.free;
end else inc(i);
continue;
end;
end;
if c.m_expires=0 then c.m_expires:=nowt;
inc(i);
end;
c:=nil;
//Ping only contacts that are in the branches that meet the set level and are not close to our ID.
//The other contacts are checked with the big timer. ( 7-10 m_bin )
if K10-m_bin.m_entries.count<KPINGABLE{4} then c:=m_bin.getOldest;
if c<>nil then begin
if ((c.m_expires>=nowt) or
(c.m_type=4)) then begin // already pinged or awaiting for expiration, move ahead = fresh?
m_bin.moveback(c);
c:=nil;
end;
end;
except
end;
if c<>nil then begin
c.checkingType;
c.m_outHelloTime:=gettickcount;
DHT_sendMyDetails(CMD_DHT_HELLO_REQ, c.m_ip, c.m_UDPPort);
end;
end;
procedure TRoutingZone.randomLookup;
var
prefix:CU_INT128;
rando:CU_INT128;
begin
// Look-up a random client in this zone
CU_INT128_fill(@prefix,@m_zoneIndex);
CU_Int128_shiftLeft(@prefix,128-m_level);
CU_INT128_fill(@rando,@prefix,m_level);
rando[0]:=rando[0] xor DHTme128[0];
rando[1]:=rando[1] xor DHTme128[1];
rando[2]:=rando[2] xor DHTme128[2];
rando[3]:=rando[3] xor DHTme128[3];
DHTSearchManager.findNode(@rando);
end;
function TRoutingZone.getNumContacts:cardinal;
begin
if isLeaf then result:=m_bin.m_entries.count
else result:=m_subZones[0].getNumContacts+m_subZones[1].getNumContacts;
end;
end.
|
unit UJSONFunctions;
{$DEFINE Delphi}
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
{ Copyright (c) 2016 by Albert Molina
Distributed under the MIT software license, see the accompanying file LICENSE
or visit http://www.opensource.org/licenses/mit-license.php.
This unit is a part of Pascal Coin, a P2P crypto currency without need of
historical operations.
If you like it, consider a donation using BitCoin:
16K3HCZRhFUtM8GdWRcfKeaa6KsuyxZaYk
}
interface
Uses
{$IFDEF FPC}
fpjson, jsonparser,
{$ELSE}
DBXJSON,System.Json,
{$ENDIF}
SysUtils, DateUtils, Variants, Classes, ULog;
Type
{$IFDEF FPC}
TJSONValue = TJSONData;
{$ENDIF}
TPCJSONData = Class
private
FParent: TPCJSONData;
protected
Function ToJSONFormatted(pretty: Boolean; Const prefix: AnsiString): AnsiString; virtual; abstract;
public
Constructor Create; virtual;
Destructor Destroy; override;
Class Function ParseJSONValue(Const JSONObject: String): TPCJSONData; overload;
Class Function ParseJSONValue(Const JSONObject: TBytes): TPCJSONData; overload;
Class Function _GetCount: Integer;
Function ToJSON(pretty: Boolean): AnsiString;
Procedure SaveToStream(Stream: TStream);
Procedure Assign(PCJSONData: TPCJSONData);
End;
TPCJSONDataClass = Class of TPCJSONData;
{ TPCJSONVariantValue }
TPCJSONVariantValue = Class(TPCJSONData)
private
FOldValue: Variant;
FWritable: Boolean;
FValue: Variant;
procedure SetValue(const Value: Variant);
protected
Function ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString; override;
public
DecimalSep, ThousandSep: Char;
Constructor Create; override;
Constructor CreateFromJSONValue(JSONValue: TJSONValue);
Property Value: Variant read FValue write SetValue;
Function AsString(DefValue: String): String;
Function AsInteger(DefValue: Integer): Integer;
Function AsInt64(DefValue: Int64): Int64;
Function AsDouble(DefValue: Double): Double;
Function AsBoolean(DefValue: Boolean): Boolean;
Function AsDateTime(DefValue: TDateTime): TDateTime;
Function AsCurrency(DefValue: Currency): Currency;
Function AsCardinal(DefValue: Cardinal): Cardinal;
Function IsNull: Boolean;
End;
TPCJSONNameValue = Class(TPCJSONData)
private
FName: String;
FValue: TPCJSONData;
FFreeValue: Boolean;
procedure SetValue(const Value: TPCJSONData);
protected
Function ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString; override;
public
Constructor Create(AName: String);
Destructor Destroy; override;
Property Name: String read FName;
Property Value: TPCJSONData read FValue write SetValue;
End;
TPCJSONArray = class;
TPCJSONObject = Class;
TPCJSONList = Class(TPCJSONData)
private
FList: TList;
function GetItems(Index: Integer): TPCJSONData;
procedure SetItems(Index: Integer; const Value: TPCJSONData);
protected
Function GetIndexAsVariant(Index: Integer): TPCJSONVariantValue;
Function GetIndexAsArray(Index: Integer): TPCJSONArray;
Function GetIndexAsObject(Index: Integer): TPCJSONObject;
Procedure CheckCanInsert(Index: Integer; PCJSONData: TPCJSONData); virtual;
public
Constructor Create; override;
Destructor Destroy; override;
Property Items[Index: Integer]: TPCJSONData read GetItems write SetItems;
Procedure Insert(Index: Integer; PCJSONData: TPCJSONData);
Procedure Delete(Index: Integer);
function Count: Integer;
Procedure Clear;
End;
TPCJSONArray = class(TPCJSONList)
private
Procedure GrowToIndex(Index: Integer);
function GetItemOfType(Index: Integer; DataClass: TPCJSONDataClass): TPCJSONData;
protected
Function ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString; override;
public
Constructor Create; override;
Constructor CreateFromJSONArray(JSONArray: TJSONArray);
Destructor Destroy; override;
Function GetAsVariant(Index: Integer): TPCJSONVariantValue;
Function GetAsObject(Index: Integer): TPCJSONObject;
Function GetAsArray(Index: Integer): TPCJSONArray;
end;
{ TPCJSONObject }
TPCJSONObject = Class(TPCJSONList)
private
Function GetIndexOrCreateName(Name: String): Integer;
Function GetByName(Name: String): TPCJSONNameValue;
protected
Function ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString; override;
Procedure CheckCanInsert(Index: Integer; PCJSONData: TPCJSONData); override;
Procedure CheckValidName(Name: String);
public
Constructor Create; override;
Constructor CreateFromJSONObject(JSONObject: TJSONObject);
Destructor Destroy; override;
Function FindName(Name: String): TPCJSONNameValue;
Function IndexOfName(Name: String): Integer;
Procedure DeleteName(Name: String);
Function GetAsVariant(Name: String): TPCJSONVariantValue;
Function GetAsObject(Name: String): TPCJSONObject;
Function GetAsArray(Name: String): TPCJSONArray;
Function AsString(ParamName: String; DefValue: String): String;
Function AsInteger(ParamName: String; DefValue: Integer): Integer;
Function AsCardinal(ParamName: String; DefValue: Cardinal): Cardinal;
Function AsInt64(ParamName: String; DefValue: Int64): Int64;
Function AsDouble(ParamName: String; DefValue: Double): Double;
Function AsBoolean(ParamName: String; DefValue: Boolean): Boolean;
Function AsDateTime(ParamName: String; DefValue: TDateTime): TDateTime;
Function AsCurrency(ParamName: String; DefValue: Currency): Currency;
Function SaveAsStream(ParamName: String; Stream: TStream): Integer;
Function LoadAsStream(ParamName: String; Stream: TStream): Integer;
Function GetNameValue(Index: Integer): TPCJSONNameValue;
Function IsNull(ParamName: String): Boolean;
Procedure SetAs(Name: String; Value: TPCJSONData);
End;
EPCParametresError = Class(Exception);
implementation
Function UTF8JSONEncode(plainTxt: String; includeSeparator: Boolean): String;
Var
ws: WideString;
i: Integer;
Begin
ws := UTF8Encode(plainTxt);
{ ALERT:
UTF8Encode function deletes last char if equal to #0, so we put it manually
}
if copy(plainTxt, length(plainTxt), 1) = #0 then
ws := ws + #0;
i := 1;
result := '"';
while i <= length(ws) do
begin
case ws[i] of
'/', '\', '"':
result := result + '\' + ws[i];
#8:
result := result + '\b';
#9:
result := result + '\t';
#10:
result := result + '\n';
#13:
result := result + '\r';
#12:
result := result + '\f';
else
if (ord(ws[i]) < 32) Or (ord(ws[i]) > 122) then
result := result + '\u' + inttohex(ord(ws[i]), 4)
else
result := result + ws[i];
end;
inc(i);
end;
result := result + '"';
End;
{ TPCJSONArray }
constructor TPCJSONArray.Create;
begin
inherited;
end;
constructor TPCJSONArray.CreateFromJSONArray(JSONArray: TJSONArray);
Var
i: Integer;
begin
Create;
{$IFDEF FPC}
for i := 0 to JSONArray.Count - 1 do
begin
if (JSONArray.Items[i] is TJSONArray) then
begin
Insert(i, TPCJSONArray.CreateFromJSONArray(TJSONArray(JSONArray.Items[i])));
end
else if (JSONArray.Items[i] is TJSONObject) then
begin
Insert(i, TPCJSONObject.CreateFromJSONObject(TJSONObject(JSONArray.Items[i])));
end
else if (JSONArray.Items[i] is TJSONValue) then
begin
Insert(i, TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JSONArray.Items[i])));
end
else
raise EPCParametresError.Create('Invalid TJSON Data: ' + JSONArray.Items[i].ClassName);
end;
{$ELSE}
for i := 0 to JSONArray.Size - 1 do
begin
if (JSONArray.Get(i) is TJSONArray) then
begin
Insert(i, TPCJSONArray.CreateFromJSONArray(TJSONArray(JSONArray.Get(i))));
end
else if (JSONArray.Get(i) is TJSONObject) then
begin
Insert(i, TPCJSONObject.CreateFromJSONObject(TJSONObject(JSONArray.Get(i))));
end
else if (JSONArray.Get(i) is TJSONValue) then
begin
Insert(i, TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JSONArray.Get(i))));
end
else
raise EPCParametresError.Create('Invalid TJSON Data: ' + JSONArray.Get(i).ClassName);
end;
{$ENDIF}
end;
destructor TPCJSONArray.Destroy;
begin
inherited;
end;
function TPCJSONArray.GetAsArray(Index: Integer): TPCJSONArray;
begin
result := GetItemOfType(index, TPCJSONArray) as TPCJSONArray;
end;
function TPCJSONArray.GetAsObject(Index: Integer): TPCJSONObject;
begin
result := GetItemOfType(index, TPCJSONObject) as TPCJSONObject;
end;
function TPCJSONArray.GetAsVariant(Index: Integer): TPCJSONVariantValue;
begin
result := GetItemOfType(index, TPCJSONVariantValue) as TPCJSONVariantValue;
end;
function TPCJSONArray.GetItemOfType(Index: Integer; DataClass: TPCJSONDataClass): TPCJSONData;
Var
V, New: TPCJSONData;
begin
GrowToIndex(Index);
V := GetItems(index);
if Not(V is DataClass) then
begin
New := DataClass.Create;
Items[index] := New;
V := New;
end;
result := V as DataClass;
end;
procedure TPCJSONArray.GrowToIndex(Index: Integer);
begin
While (index >= Count) do
Insert(Count, TPCJSONVariantValue.Create);
end;
function TPCJSONArray.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
Var
i: Integer;
begin
If pretty then
result := prefix + '['
else
result := '[';
for i := 0 to Count - 1 do
begin
if (i > 0) then
begin
result := result + ',';
If pretty then
result := result + #10 + prefix;
end;
result := result + Items[i].ToJSONFormatted(pretty, prefix + ' ');
end;
result := result + ']';
end;
{ TPCJSONList }
procedure TPCJSONList.CheckCanInsert(Index: Integer; PCJSONData: TPCJSONData);
begin
if (Index < 0) Or (Index > Count) then
raise Exception.Create('Invalid insert at index ' + Inttostr(Index) + ' (Count:' + Inttostr(Count) + ')');
end;
procedure TPCJSONList.Clear;
begin
while (FList.Count > 0) do
Delete(FList.Count - 1);
end;
function TPCJSONList.Count: Integer;
begin
result := FList.Count;
end;
constructor TPCJSONList.Create;
begin
inherited;
FParent := Nil;
FList := TList.Create;
end;
procedure TPCJSONList.Delete(Index: Integer);
Var
M: TPCJSONData;
begin
M := GetItems(index);
FList.Delete(index);
M.Free;
end;
destructor TPCJSONList.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
function TPCJSONList.GetIndexAsArray(Index: Integer): TPCJSONArray;
Var
D: TPCJSONData;
begin
D := GetItems(Index);
if (Not(D is TPCJSONArray)) then
begin
result := TPCJSONArray.Create;
SetItems(Index, result);
D.Free;
end
else
result := TPCJSONArray(D);
end;
function TPCJSONList.GetIndexAsObject(Index: Integer): TPCJSONObject;
Var
D: TPCJSONData;
begin
D := GetItems(Index);
if (Not(D is TPCJSONObject)) then
begin
result := TPCJSONObject.Create;
SetItems(Index, result);
D.Free;
end
else
result := TPCJSONObject(D);
end;
function TPCJSONList.GetIndexAsVariant(Index: Integer): TPCJSONVariantValue;
Var
D: TPCJSONData;
begin
D := GetItems(Index);
if (Not(D is TPCJSONVariantValue)) then
begin
result := TPCJSONVariantValue.Create;
SetItems(Index, result);
D.Free;
end
else
result := TPCJSONVariantValue(D);
end;
function TPCJSONList.GetItems(Index: Integer): TPCJSONData;
begin
result := FList.Items[Index];
end;
procedure TPCJSONList.Insert(Index: Integer; PCJSONData: TPCJSONData);
begin
CheckCanInsert(Index, PCJSONData);
FList.Insert(Index, PCJSONData);
end;
procedure TPCJSONList.SetItems(Index: Integer; const Value: TPCJSONData);
Var
OldP: TPCJSONData;
begin
OldP := FList.Items[Index];
Try
FList.Items[Index] := Value;
Finally
OldP.Free;
End;
end;
{ TPCJSONVariantValue }
Function VariantToDouble(Value: Variant): Double;
Var
s: String;
Begin
result := 0;
Case varType(Value) of
varSmallint, varInteger, varSingle, varDouble, varCurrency:
result := Value;
Else
Begin
s := VarToStr(Value);
If s = '' Then
Abort
Else
result := StrToFloat(s);
End;
End;
End;
function TPCJSONVariantValue.AsBoolean(DefValue: Boolean): Boolean;
begin
try
result := VarAsType(Value, varBoolean);
except
result := DefValue;
end;
end;
function TPCJSONVariantValue.AsCurrency(DefValue: Currency): Currency;
begin
try
result := VariantToDouble(Value);
except
result := DefValue;
end;
end;
function TPCJSONVariantValue.AsCardinal(DefValue: Cardinal): Cardinal;
begin
result := Cardinal(StrToIntDef(VarToStrDef(Value, ''), DefValue));
end;
function TPCJSONVariantValue.AsDateTime(DefValue: TDateTime): TDateTime;
begin
try
result := VarAsType(Value, varDate);
except
result := DefValue;
end;
end;
function TPCJSONVariantValue.AsDouble(DefValue: Double): Double;
begin
try
result := VariantToDouble(Value);
except
result := DefValue;
end;
end;
function TPCJSONVariantValue.AsInt64(DefValue: Int64): Int64;
begin
result := StrToInt64Def(VarToStrDef(Value, ''), DefValue);
end;
function TPCJSONVariantValue.AsInteger(DefValue: Integer): Integer;
begin
result := StrToIntDef(VarToStrDef(Value, ''), DefValue);
end;
function TPCJSONVariantValue.AsString(DefValue: String): String;
begin
try
Case varType(Value) of
varNull:
result := '';
varSmallint, varInteger:
Begin
result := Inttostr(Value);
End;
varSingle, varDouble, varCurrency:
Begin
result := FloatToStr(VariantToDouble(Value));
End;
varDate:
result := DateTimeToStr(Value);
Else
result := VarToStr(Value);
End;
except
result := DefValue;
end;
end;
constructor TPCJSONVariantValue.Create;
begin
inherited;
FValue := Null;
FOldValue := Unassigned;
FWritable := False;
{$IFDEF FPC}
DecimalSep := DecimalSeparator;
ThousandSep := ThousandSeparator;
{$ELSE}
DecimalSep := FormatSettings.DecimalSeparator;
ThousandSep := FormatSettings.ThousandSeparator;
{$ENDIF}
end;
constructor TPCJSONVariantValue.CreateFromJSONValue(JSONValue: TJSONValue);
{$IFNDEF FPC}
Var
D: Double;
i64: Integer;
ds, ts: Char;
{$ENDIF}
begin
Create;
{$IFDEF FPC}
Value := JSONValue.Value;
{$ELSE}
if JSONValue is TJSONNumber then
begin
D := TJSONNumber(JSONValue).AsDouble;
if Pos('.', JSONValue.ToString) > 0 then
i64 := 0
else
i64 := TJSONNumber(JSONValue).AsInt;
ds := DecimalSep;
ts := ThousandSep;
{$IFDEF FPC}
DecimalSeparator := '.';
ThousandSeparator := ',';
{$ELSE}
FormatSettings.DecimalSeparator := '.';
FormatSettings.ThousandSeparator := ',';
{$ENDIF}
Try
if FormatFloat('0.###########', D) = Inttostr(i64) then
Value := i64
else
Value := D;
Finally
{$IFDEF FPC}
DecimalSeparator := ds;
ThousandSeparator := ts;
{$ELSE}
FormatSettings.DecimalSeparator := ds;
FormatSettings.ThousandSeparator := ts;
{$ENDIF}
End;
end
else if JSONValue is TJSONTrue then
Value := true
else if JSONValue is TJSONFalse then
Value := False
else if JSONValue is TJSONNull then
Value := Null
else
Value := JSONValue.Value;
{$ENDIF}
end;
function TPCJSONVariantValue.IsNull: Boolean;
begin
result := VarIsNull(FValue) or VarIsEmpty(FValue);
end;
procedure TPCJSONVariantValue.SetValue(const Value: Variant);
begin
FOldValue := FValue;
FValue := Value;
end;
function TPCJSONVariantValue.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
Var
ds, ts: Char;
begin
Case varType(Value) of
varSmallint, varInteger, varByte, varWord, varLongWord, varInt64:
result := VarToStr(Value);
varBoolean:
if (Value) then
result := 'true'
else
result := 'false';
varNull:
result := 'null';
varDate, varDouble:
begin
ds := DecimalSep;
ts := ThousandSep;
{$IFDEF FPC}
DecimalSeparator := '.';
ThousandSeparator := ',';
{$ELSE}
FormatSettings.DecimalSeparator := '.';
FormatSettings.ThousandSeparator := ',';
{$ENDIF}
try
result := FormatFloat('0.###########', Value);
finally
{$IFDEF FPC}
DecimalSeparator := ds;
ThousandSeparator := ts;
{$ELSE}
FormatSettings.DecimalSeparator := ds;
FormatSettings.ThousandSeparator := ts;
{$ENDIF}
end;
end
else
result := UTF8JSONEncode(VarToStr(Value), true);
end;
end;
{ TPCJSONObject }
function TPCJSONObject.AsBoolean(ParamName: String; DefValue: Boolean): Boolean;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
if VarIsNull(V) then
result := DefValue
else
result := VarAsType(V, varBoolean);
except
result := DefValue;
end;
end;
function TPCJSONObject.AsCardinal(ParamName: String; DefValue: Cardinal): Cardinal;
begin
result := Cardinal(AsInt64(ParamName, DefValue));
end;
function TPCJSONObject.AsCurrency(ParamName: String; DefValue: Currency): Currency;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
if VarIsNull(V) then
result := DefValue
else
result := VariantToDouble(V);
except
result := DefValue;
end;
end;
function TPCJSONObject.AsDateTime(ParamName: String; DefValue: TDateTime): TDateTime;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
if VarIsNull(V) then
result := DefValue
else
result := VarAsType(V, varDate);
except
result := DefValue;
end;
end;
function TPCJSONObject.AsDouble(ParamName: String; DefValue: Double): Double;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
if VarIsNull(V) then
result := DefValue
else
result := VariantToDouble(V);
except
result := DefValue;
end;
end;
function TPCJSONObject.AsInt64(ParamName: String; DefValue: Int64): Int64;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
if VarIsNull(V) then
result := DefValue
else
result := StrToInt64Def(VarToStrDef(V, ''), DefValue);
except
result := DefValue;
end;
end;
function TPCJSONObject.AsInteger(ParamName: String; DefValue: Integer): Integer;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
if VarIsNull(V) then
result := DefValue
else
result := StrToIntDef(VarToStrDef(V, ''), DefValue);
except
result := DefValue;
end;
end;
function TPCJSONObject.AsString(ParamName: String; DefValue: String): String;
Var
V: Variant;
VV: TPCJSONVariantValue;
begin
VV := GetAsVariant(ParamName);
if (varType(VV.Value) = varNull) AND (varType(VV.FOldValue) = varEmpty) then
begin
result := DefValue;
Exit;
end;
V := GetAsVariant(ParamName).Value;
try
Case varType(V) of
varNull:
result := '';
varSmallint, varInteger:
Begin
result := Inttostr(V);
End;
varSingle, varDouble, varCurrency:
Begin
result := FloatToStr(VariantToDouble(V));
End;
varDate:
result := DateTimeToStr(V);
Else
result := VarToStr(V);
End;
except
result := DefValue;
end;
end;
procedure TPCJSONObject.CheckCanInsert(Index: Integer; PCJSONData: TPCJSONData);
begin
inherited;
if Not Assigned(PCJSONData) then
raise Exception.Create('Object is nil');
if Not(PCJSONData is TPCJSONNameValue) then
raise Exception.Create('Object inside a ' + TPCJSONData.ClassName + ' must be a ' + TPCJSONNameValue.ClassName + ' (currently ' +
PCJSONData.ClassName + ')');
end;
procedure TPCJSONObject.CheckValidName(Name: String);
Var
i: Integer;
begin
for i := 1 to length(Name) do
begin
if i = 1 then
begin
if Not(Name[i] in ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '.']) then
raise Exception.Create(Format('Invalid char %s at pos %d/%d', [Name[i], i, length(Name)]));
end
else
begin
if Not(Name[i] in ['a' .. 'z', 'A' .. 'Z', '0' .. '9', '_', '-', '.']) then
raise Exception.Create(Format('Invalid char %s at pos %d/%d', [Name[i], i, length(Name)]));
end;
end;
end;
constructor TPCJSONObject.Create;
begin
inherited;
end;
constructor TPCJSONObject.CreateFromJSONObject(JSONObject: TJSONObject);
var
i, i2: Integer;
{$IFDEF FPC}
AName: TJSONStringType;
{$ENDIF}
begin
Create;
{$IFDEF FPC}
for i := 0 to JSONObject.Count - 1 do
begin
AName := JSONObject.Names[i];
i2 := GetIndexOrCreateName(JSONObject.Names[i]);
if (JSONObject.Types[AName] = jtArray) then
begin
(Items[i2] as TPCJSONNameValue).Value := TPCJSONArray.CreateFromJSONArray(JSONObject.Arrays[AName]);
end
else if (JSONObject.Types[AName] = jtObject) then
begin
(Items[i2] as TPCJSONNameValue).Value := TPCJSONObject.CreateFromJSONObject(JSONObject.Objects[AName]);
end
else if (JSONObject.Types[AName] in [jtBoolean, jtNull, jtNumber, jtString]) then
begin
(Items[i2] as TPCJSONNameValue).Value := TPCJSONVariantValue.CreateFromJSONValue(JSONObject.Items[i]);
end
else
raise EPCParametresError.Create('Invalid TJSON Data in JSONObject.' + AName + ': ' + JSONObject.Items[i].ClassName);
end;
{$ELSE}
for i := 0 to JSONObject.Size - 1 do
begin
i2 := GetIndexOrCreateName(JSONObject.Get(i).JsonString.Value);
if (JSONObject.Get(i).JSONValue is TJSONArray) then
begin
(Items[i2] as TPCJSONNameValue).Value := TPCJSONArray.CreateFromJSONArray(TJSONArray(JSONObject.Get(i).JSONValue));
end
else if (JSONObject.Get(i).JSONValue is TJSONObject) then
begin
(Items[i2] as TPCJSONNameValue).Value := TPCJSONObject.CreateFromJSONObject(TJSONObject(JSONObject.Get(i).JSONValue));
end
else if (JSONObject.Get(i).JSONValue is TJSONValue) then
begin
(Items[i2] as TPCJSONNameValue).Value := TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JSONObject.Get(i).JSONValue));
end
else
raise EPCParametresError.Create('Invalid TJSON Data in JSONObject.' + JSONObject.Get(i).JsonString.Value + ': ' + JSONObject.Get(i).ClassName);
end;
{$ENDIF}
end;
procedure TPCJSONObject.DeleteName(Name: String);
Var
i: Integer;
begin
i := IndexOfName(Name);
if (i >= 0) then
begin
Delete(i);
end;
end;
destructor TPCJSONObject.Destroy;
begin
inherited;
end;
function TPCJSONObject.FindName(Name: String): TPCJSONNameValue;
Var
i: Integer;
begin
i := IndexOfName(Name);
result := Nil;
if (i >= 0) then
result := Items[i] as TPCJSONNameValue;
end;
function TPCJSONObject.GetAsArray(Name: String): TPCJSONArray;
Var
NV: TPCJSONNameValue;
V: TPCJSONData;
begin
NV := GetByName(Name);
if Not(NV.Value is TPCJSONArray) then
begin
NV.Value := TPCJSONArray.Create;
end;
result := NV.Value as TPCJSONArray;
end;
function TPCJSONObject.GetAsObject(Name: String): TPCJSONObject;
Var
NV: TPCJSONNameValue;
V: TPCJSONData;
begin
NV := GetByName(Name);
if Not(NV.Value is TPCJSONObject) then
begin
NV.Value := TPCJSONObject.Create;
end;
result := NV.Value as TPCJSONObject;
end;
function TPCJSONObject.GetAsVariant(Name: String): TPCJSONVariantValue;
Var
NV: TPCJSONNameValue;
V: TPCJSONData;
begin
NV := GetByName(Name);
if Not(NV.Value is TPCJSONVariantValue) then
begin
NV.Value := TPCJSONVariantValue.Create;
end;
result := NV.Value as TPCJSONVariantValue;
end;
function TPCJSONObject.GetByName(Name: String): TPCJSONNameValue;
Var
i: Integer;
begin
i := GetIndexOrCreateName(Name);
result := Items[i] as TPCJSONNameValue;
end;
function TPCJSONObject.GetIndexOrCreateName(Name: String): Integer;
Var
NV: TPCJSONNameValue;
Begin
result := IndexOfName(Name);
if (result < 0) then
begin
CheckValidName(Name);
NV := TPCJSONNameValue.Create(Name);
result := FList.Add(NV);
end;
end;
function TPCJSONObject.GetNameValue(Index: Integer): TPCJSONNameValue;
begin
result := Items[index] as TPCJSONNameValue;
end;
function TPCJSONObject.IsNull(ParamName: String): Boolean;
Var
i: Integer;
NV: TPCJSONNameValue;
begin
i := IndexOfName(ParamName);
if i < 0 then
result := true
else
begin
result := False;
NV := TPCJSONNameValue(FList.Items[i]);
If (Assigned(NV.Value)) AND (NV.Value is TPCJSONVariantValue) then
begin
result := TPCJSONVariantValue(NV.Value).IsNull;
end;
end;
end;
function TPCJSONObject.IndexOfName(Name: String): Integer;
begin
for result := 0 to FList.Count - 1 do
begin
if (Assigned(FList.Items[result])) And (TObject(FList.Items[result]) is TPCJSONNameValue) then
begin
If TPCJSONNameValue(FList.Items[result]).Name = Name then
begin
Exit;
end;
end;
end;
result := -1;
end;
function TPCJSONObject.LoadAsStream(ParamName: String; Stream: TStream): Integer;
Var
s: AnsiString;
begin
s := AsString(ParamName, '');
if (s <> '') then
begin
Stream.Write(s[1], length(s));
end;
result := length(s);
end;
function TPCJSONObject.SaveAsStream(ParamName: String; Stream: TStream): Integer;
Var
s: AnsiString;
begin
Stream.Position := 0;
SetLength(s, Stream.Size);
Stream.Read(s[1], Stream.Size);
GetAsVariant(ParamName).Value := s;
end;
procedure TPCJSONObject.SetAs(Name: String; Value: TPCJSONData);
// When assigning a object with SetAs this will not be freed automatically
Var
NV: TPCJSONNameValue;
V: TPCJSONData;
i: Integer;
begin
i := GetIndexOrCreateName(Name);
NV := Items[i] as TPCJSONNameValue;
NV.Value := Value;
NV.FFreeValue := False;
end;
function TPCJSONObject.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
Var
i: Integer;
begin
if pretty then
result := prefix + '{'
else
result := '{';
for i := 0 to Count - 1 do
begin
if (i > 0) then
Begin
result := result + ',';
If pretty then
result := result + #10 + prefix;
End;
result := result + Items[i].ToJSONFormatted(pretty, prefix + ' ');
end;
result := result + '}';
end;
{ TPCJSONNameValue }
constructor TPCJSONNameValue.Create(AName: String);
begin
inherited Create;
FName := AName;
FValue := TPCJSONData.Create;
FFreeValue := true;
end;
destructor TPCJSONNameValue.Destroy;
begin
if FFreeValue then
FValue.Free;
inherited;
end;
procedure TPCJSONNameValue.SetValue(const Value: TPCJSONData);
Var
old: TPCJSONData;
begin
if FValue = Value then
Exit;
old := FValue;
FValue := Value;
if FFreeValue then
old.Free;
FFreeValue := true;
end;
function TPCJSONNameValue.ToJSONFormatted(pretty: Boolean; const prefix: AnsiString): AnsiString;
begin
if pretty then
result := prefix
else
result := '';
result := result + UTF8JSONEncode(name, true) + ':' + Value.ToJSONFormatted(pretty, prefix + ' ');
end;
{ TPCJSONData }
Var
_objectsCount: Integer;
procedure TPCJSONData.Assign(PCJSONData: TPCJSONData);
Var
i: Integer;
NV: TPCJSONNameValue;
JSOND: TPCJSONData;
s: AnsiString;
begin
if Not Assigned(PCJSONData) then
Abort;
if (PCJSONData is TPCJSONObject) AND (Self is TPCJSONObject) then
begin
for i := 0 to TPCJSONObject(PCJSONData).Count - 1 do
begin
NV := TPCJSONObject(PCJSONData).Items[i] as TPCJSONNameValue;
if NV.Value is TPCJSONObject then
begin
TPCJSONObject(Self).GetAsObject(NV.Name).Assign(NV.Value);
end
else if NV.Value is TPCJSONArray then
begin
TPCJSONObject(Self).GetAsArray(NV.Name).Assign(NV.Value);
end
else if NV.Value is TPCJSONVariantValue then
begin
TPCJSONObject(Self).GetAsVariant(NV.Name).Assign(NV.Value);
end
else
raise Exception.Create('Error in TPCJSONData.Assign decoding ' + NV.Name + ' (' + NV.Value.ClassName + ')');
end;
end
else if (PCJSONData is TPCJSONArray) AND (Self is TPCJSONArray) then
begin
for i := 0 to TPCJSONArray(PCJSONData).Count - 1 do
begin
JSOND := TPCJSONArray(PCJSONData).Items[i];
s := JSOND.ToJSON(False);
TPCJSONArray(Self).Insert(TPCJSONArray(Self).Count, TPCJSONData.ParseJSONValue(s));
end;
end
else if (PCJSONData is TPCJSONVariantValue) AND (Self is TPCJSONVariantValue) then
begin
TPCJSONVariantValue(Self).Value := TPCJSONVariantValue(PCJSONData).Value;
end
else
begin
raise Exception.Create('Error in TPCJSONData.Assign assigning a ' + PCJSONData.ClassName + ' to a ' + ClassName);
end;
end;
constructor TPCJSONData.Create;
begin
inc(_objectsCount);
end;
destructor TPCJSONData.Destroy;
begin
dec(_objectsCount);
inherited;
end;
class function TPCJSONData.ParseJSONValue(Const JSONObject: TBytes): TPCJSONData;
Var
JS: TJSONValue;
{$IFDEF FPC}
jss: TJSONStringType;
i: Integer;
{$ENDIF}
begin
result := Nil;
JS := Nil;
{$IFDEF FPC}
SetLength(jss, length(JSONObject));
for i := 0 to High(JSONObject) do
jss[i + 1] := AnsiChar(JSONObject[i]);
Try
JS := GetJSON(jss);
Except
On E: Exception do
begin
TLog.NewLog(ltDebug, ClassName, 'Error processing JSON: ' + E.Message);
end;
end;
{$ELSE}
Try
JS := TJSONObject.ParseJSONValue(JSONObject, 0);
Except
On E: Exception do
begin
TLog.NewLog(ltDebug, ClassName, 'Error processing JSON: ' + E.Message);
end;
End;
{$ENDIF}
if Not Assigned(JS) then
Exit;
Try
if JS is TJSONObject then
begin
result := TPCJSONObject.CreateFromJSONObject(TJSONObject(JS));
end
else if JS is TJSONArray then
begin
result := TPCJSONArray.CreateFromJSONArray(TJSONArray(JS));
end
else if JS is TJSONValue then
begin
result := TPCJSONVariantValue.CreateFromJSONValue(TJSONValue(JS));
end
else
raise EPCParametresError.Create('Invalid TJSON Data type ' + JS.ClassName);
Finally
JS.Free;
End;
end;
procedure TPCJSONData.SaveToStream(Stream: TStream);
Var
s: AnsiString;
begin
s := ToJSON(False);
Stream.Write(s[1], length(s));
end;
class function TPCJSONData.ParseJSONValue(Const JSONObject: String): TPCJSONData;
begin
result := ParseJSONValue(TEncoding.ASCII.GetBytes(JSONObject));
end;
function TPCJSONData.ToJSON(pretty: Boolean): AnsiString;
begin
result := ToJSONFormatted(pretty, '');
end;
class function TPCJSONData._GetCount: Integer;
begin
result := _objectsCount;
end;
initialization
_objectsCount := 0;
end.
|
unit uConst;
interface
const
DefaultTheme = 'mirc';
//settings
IdentificationSection = 'Identification';
NickNameIdent = 'Nickname';
AltNickIdent = 'AltNick';
RealNameIdent = 'RealName';
UserNameIdent = 'UserName';
AppearanceSection = 'Appearance';
ConnectionsSection = 'Connections';
ThemeIdent = 'Theme';
function SettingsFilePath: string;
implementation
uses SHFolder, Windows, SysUtils;
function GetSpecialFolderPath(const AFolderID: Integer) : string;
const
SHGFP_TYPE_CURRENT = 0;
var
Path: array [0..MAX_PATH] of Char;
begin
if SUCCEEDED(SHGetFolderPath(0, AFolderID, 0, SHGFP_TYPE_CURRENT, @Path[0])) then
Result := Path
else
Result := '';
end;
function SettingsFilePath: string;
begin
Result := GetSpecialFolderPath(CSIDL_LOCAL_APPDATA) + '\Gist\settings.ini';
if not DirectoryExists(ExtractFilePath(Result)) then
ForceDirectories(ExtractFilePath(Result));
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Buttons;
type
{ TfrmFindReplace }
TfrmFindReplace = class(TForm)
bmbClear: TBitBtn;
btnFindReplace: TButton;
memText: TMemo;
procedure bmbClearClick(Sender: TObject);
procedure btnFindReplaceClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
frmFindReplace: TfrmFindReplace;
implementation
{$R *.lfm}
{ TfrmFindReplace }
procedure TfrmFindReplace.btnFindReplaceClick(Sender: TObject);
var TextToSearch, StrToFind, ReplaceStr: String;
Pozition: Integer;
begin
TextToSearch:=memText.Text;
//get the string to search for
StrToFind:=InputBox('Find', 'Enter the string to find', '');
if StrtoFind <> '' then
begin
//get the position of the string to find in the text
Pozition:=AnsiPos(StrToFind, TextToSearch);
if Pozition > 0 then
begin
//get the replacement string
ReplaceStr:=InputBox('Replace with', 'Enter the replace ment string', '');
//delete the string searched for
Delete(TextToSearch, Pozition, Length(StrToFind));
//insert the replacement string at that position
Insert(ReplaceStr, TextToSearch, Pozition);
memText.Text:=TextToSearch;
ShowMessage('String replaced');
end //if position > 0
else
ShowMessage(StrToFind + ' does not appear in the text');
end //if string to find <> ''
else
ShowMessage('No string provided');
end;
procedure TfrmFindReplace.bmbClearClick(Sender: TObject);
begin
memText.Clear;
memText.SetFocus;
end;
end.
|
{------------------------------------------------------------------------------}
{
Lee Beadle
CS 410W
Pascal Paint Cost Program
}
{------------------------------------------------------------------------------}
{Program info, libraries, and variables}
PROGRAM Paint_Cost;
USES Math;
CONST
HEIGHT = 8;
ONE_GALLON = 350;
VAR
room_type : STRING;
length : REAL;
width : REAL;
can_cost : REAL;
surface_area : REAL;
num_of_gallons : REAL;
num_of_cans : INTEGER;
total_cost : REAL;
{------------------------------------------------------------------------------}
{Read User Input Procedure}
PROCEDURE read_input;
BEGIN
Write('Enter the room type: ');
Readln(room_type);
Write('Enter the room length: ');
Readln(length);
Write('Enter the room width: ');
Readln(width);
Write('Enter the cost of one can of paint: $');
Readln(can_cost);
END;
{------------------------------------------------------------------------------}
{Calculate Surface Area Function}
FUNCTION calc_surface_area(length: REAL; width: REAL; height: REAL) : REAL;
BEGIN
calc_surface_area := (length*width) + 2*(length*height) + 2*(width*height);
END;
{------------------------------------------------------------------------------}
{Calculate Number of Gallons Function}
FUNCTION calc_num_gallons(surface_area: REAL; a_gallon: integer): REAL;
BEGIN
calc_num_gallons := surface_area / a_gallon;
END;
{------------------------------------------------------------------------------}
{Calculate Numeber of Cans Function}
FUNCTION calc_num_cans(num_of_gallons: REAL): INTEGER;
BEGIN
calc_num_cans := Ceil(num_of_gallons);
END;
{------------------------------------------------------------------------------}
{Calculate Total Cost Function}
FUNCTION calc_total_cost(num_of_cans: INTEGER; can_cost: REAL): REAL;
BEGIN
calc_total_cost := num_of_cans * can_cost;
END;
{------------------------------------------------------------------------------}
{Output Results Procedure}
PROCEDURE display_results;
BEGIN
Writeln('Room type: ', room_type);
Writeln('Surface area (minus floor): ', surface_area:0:1, ' sq ft');
Writeln('Number of gallons: ', num_of_gallons:0:3);
Writeln('Number of cans: ', num_of_cans:0);
Writeln('Total Cost: $', total_cost:0:2);
END;
{------------------------------------------------------------------------------}
{Main Driver}
BEGIN
read_input;
surface_area := calc_surface_area(length, width, HEIGHT);
num_of_gallons:= calc_num_gallons(surface_area, ONE_GALLON);
num_of_cans := calc_num_cans(num_of_gallons);
total_cost := calc_total_cost(num_of_cans, can_cost);
display_results;
END.
{------------------------------------------------------------------------------} |
(*
Name: keymanhotkeys
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 1 Aug 2006
Modified Date: 3 May 2011
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 01 Aug 2006 - mcdurdin - Initial version
04 Dec 2006 - mcdurdin - Fix IKeymanHotkeys reference
12 Mar 2010 - mcdurdin - I2230 - Resolve crashes due to incorrect reference counting
03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
*)
unit keymanhotkeys;
interface
uses
System.Win.ComObj,
Winapi.ActiveX,
keymanapi_TLB,
keymanautoobject,
internalinterfaces,
keymancontext,
keymanhotkey;
type
TKeymanHotkeyList = TAutoObjectList;
TKeymanHotkeys = class(TKeymanAutoCollectionObject, IIntKeymanHotkeys, IKeymanHotkeys)
private
FHotkeys: TKeymanHotkeyList;
protected
procedure DoRefresh; override;
{ IKeymanHotkeys }
function Get_Items(Index: Integer): IKeymanHotkey; safecall;
procedure Apply; safecall;
procedure Reset; safecall;
public
constructor Create(AContext: TKeymanContext);
destructor Destroy; override;
end;
implementation
uses
Windows,
Classes,
ComServ,
keymanerrorcodes,
ErrorControlledRegistry,
RegistryKeys,
SysUtils,
Variants;
function TKeymanHotkeys.Get_Items(Index: Integer): IKeymanHotkey;
begin
if (Index < Get_Count) and (Index >= 0) then
Result := FHotkeys[Index] as IKeymanHotkey
else
ErrorFmt(KMN_E_Collection_InvalidIndex, VarArrayOf([Index]));
end;
procedure TKeymanHotkeys.Apply;
var
i: Integer;
si: string;
begin
{ save the hotkeys }
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_CURRENT_USER;
if OpenKey(SRegKey_KeymanHotkeys,True) then
begin
for i := 0 to FHotkeys.Count - 1 do
begin
si := IntToStr(i);
with FHotkeys[i] as IKeymanHotkey do
if IsEmpty then
begin
if ValueExists(si) then
DeleteValue(si);
end
else
WriteInteger(si, RawValue);
end;
end;
finally
Free;
end;
Context.Control.AutoApplyKeyman;
end;
constructor TKeymanHotkeys.Create(AContext: TKeymanContext);
begin
FHotkeys := TKeymanHotkeyList.Create;
inherited Create(AContext, IKeymanHotkeys, FHotkeys);
Refresh;
end;
destructor TKeymanHotkeys.Destroy;
begin
FHotkeys.Free;
inherited Destroy;
end;
procedure TKeymanHotkeys.DoRefresh;
var
Value, i: Integer;
HasRegItems: Boolean;
begin
inherited;
{ Load hotkey }
FHotkeys.Clear;
with TRegistryErrorControlled.Create do // I2890
try
RootKey := HKEY_CURRENT_USER;
HasRegItems := OpenKeyReadOnly(SRegKey_KeymanHotkeys);
for i := kh__Low to kh__High do
begin
if HasRegItems and ValueExists(IntToStr(i))
then Value := ReadInteger(IntToStr(i))
else Value := 0;
FHotkeys.Add(TKeymanHotkey.Create(Context, Value, i));
end;
finally
Free;
end;
end;
procedure TKeymanHotkeys.Reset;
var
i: Integer;
begin
for i := 0 to FHotkeys.Count - 1 do
(FHotkeys[i] as IKeymanHotkey).Clear;
end;
end.
|
{$A+,B-,D+,E+,F-,G+,I-,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 65520,0,0}
{by Behdad Esfahbod 6th IOI Sweden Day1 Problem 5 Fold Unit}
unit FoldUnit;{Folds a map}
interface
const
MaxM = 8;
MaxN = 4;
MaxSurface = 16;
type
TMap = array [1 .. MaxM, 1 .. MaxN] of string[MaxSurface];
procedure Fold (M1 : TMap; var M2 : TMap; B1, A1 : Integer; var B2, A2 : Integer; L : Integer; D, W : Char);
implementation
procedure Fold;
function Inverse (S : string) : string;
var I, J : Integer;
T : string;
begin
T[0] := S[0];
J := Length(S);
for I := 1 to J do
T[I] := S[J + 1 - I];
Inverse := T;
end;
function Max(A, B : Integer) : Integer;
begin
if A > B then Max := A else Max := B;
end;
var I, J, K : Integer;
begin
if D = 'H' then
begin
A2 := A1;
B2 := Max(L, B1 - L);
end
else
begin
B2 := B1;
A2 := Max(L, A1 - L);
end;
if D = 'H' then
if W = 'L' then
begin
for I := L + 1 to B1 do
for J := 1 to A1 do
M1[I, J] := Inverse(M1[I, J]);
if L >= B1 / 2 then
begin
M2 := M1;
for I := 2 * L - B1 + 1 to L do
for J := 1 to A1 do
M2[I, J] := M2[2 * L - I + 1, J] + M2[I, J];
end
else
begin
for I := 2 * L + 1 to B1 do
for J := 1 to A1 do
M2[B1 + 1 - I, J] := M1[I, J];
for I := 1 to L do
for J := 1 to A1 do
M2[B1 - 2 * L + I, J] := M1[2 * L - I + 1, J] + M1[I, J];
end;
end
else
begin
for I := 1 to L do
for J := 1 to A1 do
M1[I, J] := Inverse(M1[I, J]);
if L >= B1 / 2 then
begin
for I := L + 1 to B1 do
for J := 1 to A1 do
M2[I - L, J] := M1[2 * L + 1 - I, J] + M1[I, J];
for I := 1 to 2 * L - B1 do
for J := 1 to A1 do
M2[L - I + 1, J] := M1[I, J];
end
else
begin
for I := 1 to L do
for J := 1 to A1 do
M2[L + 1 - I, J] := M1[I, J] + M1[2 * L - I + 1, J];
for I := 2 * L + 1 to B1 do
for J := 1 to A1 do
M2[I - L, J] := M1[I, J];
end
end
else
if W = 'R' then
begin
for I := L + 1 to A1 do
for J := 1 to B1 do
M1[J, I] := Inverse(M1[J, I]);
if L >= A1 / 2 then
begin
M2 := M1;
for I := 2 * L - A1 + 1 to L do
for J := 1 to B1 do
M2[J, I] := M2[J, 2 * L - I + 1] + M2[J, I];
end
else
begin
for I := 2 * L + 1 to A1 do
for J := 1 to B1 do
M2[J, A1 + 1 - I] := M1[J, I];
for I := 1 to L do
for J := 1 to B1 do
M2[J, A1 - 2 * L + I] := M1[J, 2 * L - I + 1] + M1[J, I];
end;
end
else
begin
for I := 1 to L do
for J := 1 to B1 do
M1[J, I] := Inverse(M1[J, I]);
if L >= A1 / 2 then
begin
for I := L + 1 to A1 do
for J := 1 to B1 do
M2[J, I - L] := M1[J, 2 * L + 1 - I] + M1[J, I];
for I := 1 to 2 * L - A1 do
for J := 1 to B1 do
M2[J, L - I + 1] := M1[J, I];
end
else
begin
for I := 1 to L do
for J := 1 to B1 do
M2[J, L + 1 - I] := M1[J, I] + M1[J, 2 * L - I + 1];
for I := 2 * L + 1 to A1 do
for J := 1 to B1 do
M2[J, I - L] := M1[J, I];
end;
end;
end;
end. |
unit Optimizer.Prefetch;
interface
uses
SysUtils,
OS.EnvironmentVariable, Optimizer.Template, Global.LanguageString,
OS.ProcessOpener, Registry.Helper;
type
TPrefetchOptimizer = class(TOptimizationUnit)
public
function IsOptional: Boolean; override;
function IsCompatible: Boolean; override;
function IsApplied: Boolean; override;
function GetName: String; override;
procedure Apply; override;
procedure Undo; override;
end;
implementation
function TPrefetchOptimizer.IsOptional: Boolean;
begin
exit(false);
end;
function TPrefetchOptimizer.IsCompatible: Boolean;
begin
exit(IsBelowWindows8);
end;
function TPrefetchOptimizer.IsApplied: Boolean;
begin
if not IsBelowWindows8 then
exit(false);
result :=
not (NSTRegistry.GetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager' +
'\Memory Management\PrefetchParameters',
'EnablePrefetcher')) > 0);
end;
function TPrefetchOptimizer.GetName: String;
begin
result := '';
if Win32MajorVersion = 6 then
exit(CapOptSupFetch[CurrLang])
else if Win32MajorVersion = 5 then
exit(CapOptPrefetch[CurrLang]);
end;
procedure TPrefetchOptimizer.Apply;
var
ProcOutput: String;
begin
if Win32MajorVersion = 6 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager' +
'\Memory Management\PrefetchParameters', 'EnablePrefetcher'), 0);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager' +
'\Memory Management\PrefetchParameters', 'EnableSuperfetch'), 0);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\services\SysMain',
'Start'), 2);
ProcOutput := string(ProcessOpener.OpenProcWithOutput(
EnvironmentVariable.WinDir + '\System32',
'net start SysMain'));
end
else if Win32MajorVersion = 5 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager\' +
'Memory Management\PrefetchParameters', 'EnablePrefetcher'), 0);
end;
end;
procedure TPrefetchOptimizer.Undo;
var
ProcOutput: String;
begin
if Win32MajorVersion = 6 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager' +
'\Memory Management\PrefetchParameters', 'EnablePrefetcher'), 3);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager' +
'\Memory Management\PrefetchParameters', 'EnableSuperfetch'), 3);
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\services\SysMain',
'Start'), 4);
ProcOutput := string(ProcessOpener.OpenProcWithOutput(
EnvironmentVariable.WinDir + '\System32',
'net stop SysMain'));
end
else if Win32MajorVersion = 5 then
begin
NSTRegistry.SetRegInt(NSTRegistry.LegacyPathToNew('LM',
'SYSTEM\CurrentControlSet\Control\Session Manager\' +
'Memory Management\PrefetchParameters', 'EnablePrefetcher'), 3);
end;
end;
end.
|
unit uRatingBijdrages;
interface
uses
uRatingBijdrage, ContNrs, uPlayer, uHTPredictor, dxmdaset;
type
TRatingBijdrages = class
private
FRatingBijdrages: TObjectList;
function GetRatingBijdrage(aIndex: integer): TRatingBijdrage;
function GetCount: integer;
function AddRatingBijdrage(aPositie: String): TRatingBijdrage;
public
procedure SaveToXLS(aFileName: String);
procedure LoadFromXLS(aFileName: String);
procedure LoadFromMemData(aMemDataSet: TdxMemData);
procedure SaveToMemData(aMemDataSet:TdxMemData);
function CalcBijdrage(aPlayer: TPlayer; aPosition: TPlayerPosition;
aOrder: TPlayerOrder):double;
procedure LoadFlatterManRatings;
procedure LoadHORatings;
function GetRatingBijdrageByPositie(aPositie: String; aGiveWarning: Boolean = TRUE):TRatingBijdrage;
property Count: integer read GetCount;
property RatingBijdrage[aIndex:integer]:TRatingBijdrage read GetRatingBijdrage;
constructor Create;
destructor Destroy;override;
end;
implementation
uses
SysUtils, Dialogs, db, uBibExcel, ComObj, uBibMessageBox, Forms;
{ TRatingBijdrages }
{-----------------------------------------------------------------------------
Procedure: Create
Author: Harry
Date: 18-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
constructor TRatingBijdrages.Create;
begin
FRatingBijdrages := TObjectList.Create(TRUE);
LoadFromXLS(ExtractFilePath(Application.ExeName)+'ratings.xlsx');
end;
{-----------------------------------------------------------------------------
Procedure: Destroy
Author: Harry
Date: 18-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
destructor TRatingBijdrages.Destroy;
begin
FRatingBijdrages.Free;
inherited;
end;
{-----------------------------------------------------------------------------
Procedure: GetCount
Author: Harry
Date: 18-apr-2012
Arguments: None
Result: integer
-----------------------------------------------------------------------------}
function TRatingBijdrages.GetCount: integer;
begin
result := FRatingBijdrages.Count;
end;
{-----------------------------------------------------------------------------
Procedure: GetRatingBijdrage
Author: Harry
Date: 18-apr-2012
Arguments: aIndex: integer
Result: TRatingBijdrage
-----------------------------------------------------------------------------}
function TRatingBijdrages.GetRatingBijdrage(
aIndex: integer): TRatingBijdrage;
begin
result := TRatingBijdrage(FRatingBijdrages[aIndex]);
end;
{-----------------------------------------------------------------------------
Procedure: GetRatingBijdrageByPositie
Author: Harry
Date: 18-apr-2012
Arguments: aPositie: String
Result: TRatingBijdrage
-----------------------------------------------------------------------------}
function TRatingBijdrages.GetRatingBijdrageByPositie(aPositie: String; aGiveWarning: Boolean = TRUE): TRatingBijdrage;
var
i:integer;
begin
result := nil;
if (FRatingBijdrages.Count > 0) then
begin
i := 0;
while (result = nil) and (i < Count) do
begin
if (TRatingBijdrage(FRatingBijdrages[i]).Positie = UpperCase(aPositie)) then
begin
result := TRatingBijdrage(FRatingBijdrages[i]);
end;
inc(i);
end;
end;
if (Result = nil) and
(aGiveWarning) then
begin
ShowMessage('Geen result bij GetRatingBijdrageByPositie!');
end;
end;
{-----------------------------------------------------------------------------
Procedure: AddRatingBijdrage
Author: Harry
Date: 18-apr-2012
Arguments: aPositie: String
Result: TRatingBijdrage
-----------------------------------------------------------------------------}
function TRatingBijdrages.AddRatingBijdrage(aPositie: String): TRatingBijdrage;
begin
result := GetRatingBijdrageByPositie(aPositie, FALSE);
if (result = nil) then
begin
result := TRatingBijdrage.Create;
result.Positie := aPositie;
FRatingBijdrages.Add(result);
end;
end;
{-----------------------------------------------------------------------------
Procedure: LoadHORatings
Author: Harry
Date: 24-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrages.LoadHORatings;
var
vRating: TRatingBijdrage;
begin
// Keeper
vRating := AddRatingBijdrage('K');
vRating.CD_GK := 0.541809523809524;
vRating.CD_DEF := 0.2649;
vRating.WB_GK := 0.599619047619048;
vRating.WB_DEF := 0.2765;
// Centrale verdediger
vRating := AddRatingBijdrage('CD');
vRating.MID_PM := 0.114332444120847;
vRating.CD_DEF := 0.623608017817372;
vRating.WB_DEF := 0.51732532242192;
// Aanvallende centrale verdediger
vRating := AddRatingBijdrage('OCD');
vRating.MID_PM := 0.154198959584748;
vRating.CD_DEF := 0.45216760760346;
vRating.WB_DEF := 0.378826332418294;
// Centrale verdediger naar de vleugel
vRating := AddRatingBijdrage('CDTW');
vRating.MID_PM := 0.0799146551440389;
vRating.CD_DEF := 0.485316206557207;
vRating.WB_DEF := 0.715857079379445;
vRating.WA_WING := 0.221266898016264;
// Normale vleugelverdediger
vRating := AddRatingBijdrage('NWB');
vRating.MID_PM := 0.0782;
vRating.CD_DEF := 0.2804;
vRating.WB_DEF := 0.9213;
vRating.WA_WING := 0.444111111111111;
// Offensieve vleugelverdediger
vRating := AddRatingBijdrage('OWB');
vRating.MID_PM := 0.1078;
vRating.CD_DEF := 0.2384;
vRating.WB_DEF := 0.6994;
vRating.WA_WING := 0.542;
// Defensieve vleugelverdediger
vRating := AddRatingBijdrage('DWB');
vRating.MID_PM := 0.0309;
vRating.CD_DEF := 0.29868;
vRating.WB_DEF := 1.0024;
vRating.WA_WING := 0.283666666666667;
// Vleugelverdediger 'Naar het Midden'
vRating := AddRatingBijdrage('WBTM');
vRating.MID_PM := 0.0782;
vRating.CD_DEF := 0.4261;
vRating.WB_DEF := 0.6889;
vRating.WA_WING := 0.242535;
// Centrale middenvelder
vRating := AddRatingBijdrage('IM');
vRating.MID_PM := 0.4682;
vRating.CD_DEF := 0.2496;
vRating.WB_DEF := 0.1893;
vRating.CA_PASS := 0.1931;
vRating.WA_PASS := 0.1894;
// Aanvallende centrale middenvelder
vRating := AddRatingBijdrage('OIM');
vRating.MID_PM := 0.4421;
vRating.CD_DEF := 0.1346;
vRating.WB_DEF := 0.1025;
vRating.CA_PASS := 0.287;
vRating.WA_PASS := 0.1877;
// Verdedigende centrale middenvelder
vRating := AddRatingBijdrage('DIM');
vRating.MID_PM := 0.4421;
vRating.CD_DEF := 0.3705;
vRating.WB_DEF := 0.2711;
vRating.CA_PASS := 0.1302;
vRating.WA_PASS := 0.1218;
// Centrale middenvelder 'Naar de Vleugel'
vRating := AddRatingBijdrage('IMTW');
vRating.MID_PM := 0.4124;
vRating.CD_DEF := 0.217;
vRating.WB_DEF := 0.2491;
vRating.CA_PASS := 0.1347;
vRating.WA_PASS := 0.2356;
vRating.WA_WING := 0.4288;
// Vleugelspeler
vRating := AddRatingBijdrage('NW');
vRating.MID_PM := 0.212851757692645;
vRating.CD_DEF := 0.1254;
vRating.WB_DEF := 0.3499;
vRating.CA_PASS := 0.0615;
vRating.WA_PASS := 0.1821;
vRating.WA_WING := 0.749222222222222;
// Aanvallende vleugelspeler
vRating := AddRatingBijdrage('OW');
vRating.MID_PM := 0.178486894012448;
vRating.CD_DEF := 0.0504;
vRating.WB_DEF := 0.181157894736842;
vRating.CA_PASS := 0.0803;
vRating.WA_PASS := 0.2134;
vRating.WA_WING := 0.877;
// Verdedigende vleugelspeler
vRating := AddRatingBijdrage('DW');
vRating.MID_PM := 0.178486894012448;
vRating.CD_DEF := 0.1568;
vRating.WB_DEF := 0.487789473684211;
vRating.CA_PASS := 0.031;
vRating.WA_PASS := 0.1501;
vRating.WA_WING := 0.634444444444444;
// Vleugelspeler 'Naar het Midden'
vRating := AddRatingBijdrage('WTM');
vRating.MID_PM := 0.268694661172964;
vRating.CD_DEF := 0.1524;
vRating.WB_DEF := 0.2848;
vRating.CA_PASS := 0.0876;
vRating.WA_PASS := 0.1152;
vRating.WA_WING := 0.494444444444444;
// Aanvaller
vRating := AddRatingBijdrage('FW');
vRating.CA_PASS := 0.218876084491443;
vRating.CA_SC := 0.593971677962079;
vRating.WA_PASS := 0.105693415258036;
vRating.WA_WING := 0.158112641377712;
vRating.WA_SC := 0.194298673558187;
// Verdedigende aanvaller
vRating := AddRatingBijdrage('DFW');
vRating.MID_PM := 0.200663555076171;
vRating.CA_PASS := 0.350593216445366;
vRating.CA_SC := 0.365602172938477;
vRating.WA_PASS := 0.196724769916405;
vRating.WA_WING := 0.108702440947177;
vRating.WA_SC := 0.100208327839456;
// Technische verdedigende aanvaller
vRating := AddRatingBijdrage('TDFW');
vRating.MID_PM := 0.200663555076171;
vRating.CA_PASS := 0.350593216445366;
vRating.CA_SC := 0.365602172938477;
vRating.WA_PASS := 0.258314800652819;
vRating.WA_WING := 0.108702440947177;
vRating.WA_SC := 0.100208327839456;
// Aanvaller 'Naar de vleugel'
vRating := AddRatingBijdrage('FTW');
vRating.CA_PASS := 0.154848237124548;
vRating.CA_SC := 0.361066427573112;
vRating.WA_PASS := 0.156219508979194;
vRating.WA_WING := 0.459551875390065;
vRating.WA_SC := 0.391339890825664;
vRating.WA_SC_OTHER := 0.159594947390628;
end;
{-----------------------------------------------------------------------------
Procedure: LoadFlatterManRatings
Author: Harry
Date: 18-apr-2012
Arguments: None
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrages.LoadFlatterManRatings;
var
vRating: TRatingBijdrage;
begin
// Keeper
vRating := AddRatingBijdrage('K');
vRating.CD_GK := 0.568918;
vRating.CD_DEF := 0.264934;
vRating.WB_GK := 0.629629;
vRating.WB_DEF := 0.276579;
// Centrale verdediger
vRating := AddRatingBijdrage('CD');
vRating.MID_PM := 0.12596;
vRating.CD_DEF := 0.602083;
vRating.WB_DEF := 0.499476;
// Aanvallende centrale verdediger
vRating := AddRatingBijdrage('OCD');
vRating.MID_PM := 0.169827;
vRating.CD_DEF := 0.43655;
vRating.WB_DEF := 0.365733;
// Centrale verdediger naar de vleugel
vRating := AddRatingBijdrage('CDTW');
vRating.MID_PM := 0.088027;
vRating.CD_DEF := 0.468513;
vRating.WB_DEF := 0.656592;
vRating.WA_WING := 0.213672;
// Normale vleugelverdediger
vRating := AddRatingBijdrage('NWB');
vRating.MID_PM := 0.078229;
vRating.CD_DEF := 0.280401;
vRating.WB_DEF := 0.921337;
vRating.WA_WING := 0.399755;
// Offensieve vleugelverdediger
vRating := AddRatingBijdrage('OWB');
vRating.MID_PM := 0.107886;
vRating.CD_DEF := 0.238437;
vRating.WB_DEF := 0.69943;
vRating.WA_WING := 0.487884;
// Defensieve vleugelverdediger
vRating := AddRatingBijdrage('DWB');
vRating.MID_PM := 0.030981;
vRating.CD_DEF := 0.314461;
vRating.WB_DEF := 1.002422;
vRating.WA_WING := 0.255317;
// Vleugelverdediger 'Naar het Midden'
vRating := AddRatingBijdrage('WBTM');
vRating.MID_PM := 0.078229;
vRating.CD_DEF := 0.426132;
vRating.WB_DEF := 0.688952;
vRating.WA_WING := 0.255317;
// Centrale middenvelder
vRating := AddRatingBijdrage('IM');
vRating.MID_PM := 0.468248;
vRating.CD_DEF := 0.24966;
vRating.WB_DEF := 0.189319;
vRating.CA_PASS := 0.193137;
vRating.WA_PASS := 0.189444;
// Aanvallende centrale middenvelder
vRating := AddRatingBijdrage('OIM');
vRating.MID_PM := 0.442128;
vRating.CD_DEF := 0.134608;
vRating.WB_DEF := 0.102543;
vRating.CA_PASS := 0.287063;
vRating.WA_PASS := 0.187746;
// Verdedigende centrale middenvelder
vRating := AddRatingBijdrage('DIM');
vRating.MID_PM := 0.442128;
vRating.CD_DEF := 0.3705;
vRating.WB_DEF := 0.27115;
vRating.CA_PASS := 0.130214;
vRating.WA_PASS := 0.121811;
// Centrale middenvelder 'Naar de Vleugel'
vRating := AddRatingBijdrage('IMTW');
vRating.MID_PM := 0.412406;
vRating.CD_DEF := 0.217029;
vRating.WB_DEF := 0.249179;
vRating.CA_PASS := 0.134745;
vRating.WA_PASS := 0.235698;
vRating.WA_WING := 0.428863;
// Vleugelspeler
vRating := AddRatingBijdrage('NW');
vRating.MID_PM := 0.242848;
vRating.CD_DEF := 0.125486;
vRating.WB_DEF := 0.349951;
vRating.CA_PASS := 0.061538;
vRating.WA_PASS := 0.182107;
vRating.WA_WING := 0.674398;
// Aanvallende vleugelspeler
vRating := AddRatingBijdrage('OW');
vRating.MID_PM := 0.203662;
vRating.CD_DEF := 0.050401;
vRating.WB_DEF := 0.172133;
vRating.CA_PASS := 0.080314;
vRating.WA_PASS := 0.213452;
vRating.WA_WING := 0.789342;
// Verdedigende vleugelspeler
vRating := AddRatingBijdrage('DW');
vRating.MID_PM := 0.203662;
vRating.CD_DEF := 0.156868;
vRating.WB_DEF := 0.463477;
vRating.CA_PASS := 0.031035;
vRating.WA_PASS := 0.15016;
vRating.WA_WING := 0.571036;
// Vleugelspeler 'Naar het Midden'
vRating := AddRatingBijdrage('WTM');
vRating.MID_PM := 0.306594;
vRating.CD_DEF := 0.152469;
vRating.WB_DEF := 0.284824;
vRating.CA_PASS := 0.08768;
vRating.WA_PASS := 0.115254;
vRating.WA_WING := 0.445048;
// Aanvaller
vRating := AddRatingBijdrage('FW');
vRating.CA_PASS := 0.207589;
vRating.CA_SC := 0.563149;
vRating.WA_PASS := 0.10029;
vRating.WA_WING := 0.142456;
vRating.WA_SC := 0.184292;
// Verdedigende aanvaller
vRating := AddRatingBijdrage('DFW');
vRating.MID_PM := 0.217011;
vRating.CA_PASS := 0.322422;
vRating.CA_SC := 0.346607;
vRating.WA_PASS := 0.186512;
vRating.WA_WING := 0.097975;
vRating.WA_SC := 0.095023;
// Technische verdedigende aanvaller
vRating := AddRatingBijdrage('TDFW');
vRating.MID_PM := 0.21701;
vRating.CA_PASS := 0.470666;
vRating.CA_SC := 0.346607;
vRating.WA_PASS := 0.220424;
vRating.WA_WING := 0.097975;
vRating.WA_SC := 0.095023;
// Aanvaller 'Naar de vleugel'
vRating := AddRatingBijdrage('FTW');
vRating.CA_PASS := 0.146863;
vRating.CA_SC := 0.342343;
vRating.WA_PASS := 0.148148;
vRating.WA_WING := 0.392185;
vRating.WA_SC := 0.371022;
vRating.WA_SC_OTHER := 0.151325;
{TODO: vRating.WING_WG_OTHER ook implementeren??}
end;
{-----------------------------------------------------------------------------
Procedure: CalcBijdrage
Author: Harry
Date: 18-apr-2012
Arguments: aPlayer: TPlayer; aPosition: TPlayerPosition;
aOrder: TPlayerOrder
Result: None
-----------------------------------------------------------------------------}
function TRatingBijdrages.CalcBijdrage(aPlayer: TPlayer; aPosition: TPlayerPosition; aOrder: TPlayerOrder): double;
var
vRating: TRatingBijdrage;
vPos : String;
begin
result := 0;
vPos := uHTPredictor.PlayerPosToRatingPos(aPosition, aOrder, aPlayer.Spec);
vRating := GetRatingBijdrageByPositie(vPos);
if (vRating <> nil) then
begin
// Rating berekenen
result :=
//middenveldrating iets opwaarderen zodat de getoonde comboboxlijstjes representabeler zijn
(vRating.MID_PM * aPlayer.PM * 1.4) +
(vRating.CD_GK * aPlayer.GK) +
(vRating.CD_DEF * aPlayer.DEF) +
(vRating.WB_GK * aPlayer.GK) +
(vRating.WB_DEF * aPlayer.DEF) +
(vRating.CA_PASS * aPlayer.PAS) +
(vRating.CA_SC * aPlayer.SCO) +
(vRating.WA_PASS * aPlayer.PAS) +
(vRating.WA_WING * aPlayer.WNG) +
(vRating.WA_SC * aPlayer.SCO) +
(vRating.WA_SC_OTHER * aPlayer.SCO);
Result := Result * aPlayer.GetConditieFactor * aPlayer.GetFormFactor * aPlayer.GetXPFactor;
end;
end;
{-----------------------------------------------------------------------------
Procedure: LoadFromMemData
Author: Harry
Date: 19-apr-2012
Arguments: aMemDataSet: TdxMemData
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrages.LoadFromMemData(aMemDataSet: TdxMemData);
var
vRating: TRatingBijdrage;
vBookMark: TBookMark;
begin
vBookMark := aMemDataSet.GetBookmark;
aMemDataSet.DisableControls;
try
aMemDataSet.First;
while not aMemDataSet.Eof do
begin
vRating := GetRatingBijdrageByPositie(aMemDataSet.FieldByName('POSITIE').asString);
if (vRating <> nil) then
begin
vRating.MID_PM := aMemDataSet.FieldByName('MID_PM').asFloat;
vRating.CD_GK := aMemDataSet.FieldByName('CD_GK').asFloat;
vRating.CD_DEF := aMemDataSet.FieldByName('CD_DEF').asFloat;
vRating.WB_GK := aMemDataSet.FieldByName('WB_GK').asFloat;
vRating.CA_PASS := aMemDataSet.FieldByName('CA_PASS').asFloat;
vRating.CA_SC := aMemDataSet.FieldByName('CA_SC').asFloat;
vRating.WA_PASS := aMemDataSet.FieldByName('WA_PASS').asFloat;
vRating.WA_WING := aMemDataSet.FieldByName('WA_WING').asFloat;
vRating.WA_SC := aMemDataSet.FieldByName('WA_SC').asFloat;
vRating.WA_SC_OTHER := aMemDataSet.FieldByName('WA_SC_OTHER').asFloat;
end;
aMemDataSet.Next;
end;
finally
aMemDataSet.GotoBookmark(vBookMark);
aMemDataSet.EnableControls;
aMemDataSet.FreeBookmark(vBookMark);
end;
end;
{-----------------------------------------------------------------------------
Procedure: SaveToMemData
Author: Harry
Date: 19-apr-2012
Arguments: aMemDataSet: TdxMemData
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrages.SaveToMemData(aMemDataSet: TdxMemData);
var
i: integer;
vRating: TRatingBijdrage;
begin
if aMemDataSet.Active then
aMemDataSet.Close;
aMemDataSet.Open;
for i:=0 to Count - 1 do
begin
vRating := GetRatingBijdrage(i);
aMemDataSet.Append;
aMemDataSet.FieldByName('POSITIE').asString := vRating.Positie;
if (vRating.MID_PM > 0) then
aMemDataSet.FieldByName('MID_PM').asFloat := vRating.MID_PM;
if (vRating.CD_GK > 0) then
aMemDataSet.FieldByName('CD_GK').asFloat := vRating.CD_GK;
if (vRating.CD_DEF > 0) then
aMemDataSet.FieldByName('CD_DEF').asFloat := vRating.CD_DEF;
if (vRating.WB_GK > 0) then
aMemDataSet.FieldByName('WB_GK').asFloat := vRating.WB_GK;
if (vRating.CA_PASS > 0) then
aMemDataSet.FieldByName('CA_PASS').asFloat := vRating.CA_PASS;
if (vRating.CA_SC > 0) then
aMemDataSet.FieldByName('CA_SC').asFloat := vRating.CA_SC;
if (vRating.WA_PASS > 0) then
aMemDataSet.FieldByName('WA_PASS').asFloat := vRating.WA_PASS;
if (vRating.WA_WING > 0) then
aMemDataSet.FieldByName('WA_WING').asFloat := vRating.WA_WING;
if (vRating.WA_SC > 0) then
aMemDataSet.FieldByName('WA_SC').asFloat := vRating.WA_SC;
if (vRating.WA_SC_OTHER > 0) then
aMemDataSet.FieldByName('WA_SC_OTHER').asFloat := vRating.WA_SC_OTHER;
aMemDataSet.Post;
end;
end;
procedure TRatingBijdrages.SaveToXLS(aFileName: String);
var
vExcelApp: Variant;
vRow, i: Integer;
vDoorgaan: boolean;
begin
if (FileExists(aFileName)) then
begin
DeleteFile(aFileName);
end;
vExcelApp := CreateOleObject('Excel.Application');
try
vExcelApp.Workbooks.Add;
// Specifying name of worksheet:
vExcelApp.Worksheets[1].Name := 'Ratings';
vRow := 0;
for i:=0 to Count - 1 do
begin
TRatingBijdrage(FRatingBijdrages[i]).ExportToXLS(vExcelApp.Worksheets[1],vRow)
end;
vDoorgaan := TRUE;
while (vDoorgaan) do
begin
try
vExcelApp.ActiveWorkbook.SaveAs(aFileName);
vDoorgaan := FALSE;
except
uBibMessageBox.MessageBoxError(
Format('Kan het bestand %s niet opslaan!',[QuotedStr(aFileName)])+#13+
'Controleer of het bestand in gebruik is en probeer het nogmaals.','Export Mulderij');
end;
end;
finally
vExcelApp.Quit;
end;
end;
{-----------------------------------------------------------------------------
Procedure: LoadFromXLS
Author: Harry
Date: 24-apr-2012
Arguments: aFileName: String
Result: None
-----------------------------------------------------------------------------}
procedure TRatingBijdrages.LoadFromXLS(aFileName: String);
var
vExcelApp: TExcelFunctions;
vPos: String;
vCount, i: integer;
vRating : TRatingBijdrage;
begin
LoadHORatings;
if FileExists(aFileName) then
begin
vExcelApp := uBibExcel.TExcelFunctions.Create(FALSE);
with vExcelApp do
begin
try
Open(aFileName);
try
ExcelApp.ActiveWorkbook.Worksheets[1].Activate;
ExcelApp.ActiveSheet.Range['A1'].Select;
vCount := ExcelApp.ActiveSheet.UsedRange.Rows.Count + 1;
for i:=2 to vCount do
begin
vPos := GetCellRange(Format('A%d', [i]));
if (vPos <> '') then
begin
vRating := GetRatingBijdrageByPositie(vPos);
if (vRating <> nil) then
begin
vRating.LoadFromXLS(ExcelApp.ActiveSheet, i);
end;
end;
end;
finally
CloseActiveWorkbook(FALSE);
end;
finally
Free;
end;
end;
end;
end;
end.
|
unit UPedidoProduto;
interface
uses
UProduto, UPedidoDadosGerais, Data.DB, Data.Win.ADODB;
type
TPedidoProduto = class
private
FvalorUnitario: Double;
Fid: Integer;
FvalorTotal: Double;
Fquantidade: Integer;
FcodigoProduto: TProduto;
FnumeroPedido: TPedidoDadosGerais;
procedure Setid(const Value: Integer);
procedure Setquantidade(const Value: Integer);
procedure SetvalorTotal(const Value: Double);
procedure SetvalorUnitario(const Value: Double);
procedure SetcodigoProduto(const Value: TProduto);
procedure SetnumeroPedido(const Value: TPedidoDadosGerais);
public
constructor Create;
destructor Destroy; override;
property id: Integer read Fid write Setid;
property numeroPedido: TPedidoDadosGerais read FnumeroPedido write SetnumeroPedido;
property codigoProduto: TProduto read FcodigoProduto write SetcodigoProduto;
property quantidade: Integer read Fquantidade write Setquantidade;
property valorUnitario: Double read FvalorUnitario write SetvalorUnitario;
property valorTotal: Double read FvalorTotal write SetvalorTotal;
end;
implementation
{ TPedidoProduto }
constructor TPedidoProduto.Create;
begin
inherited;
end;
destructor TPedidoProduto.Destroy;
begin
inherited;
end;
procedure TPedidoProduto.SetcodigoProduto(const Value: TProduto);
begin
FcodigoProduto := Value;
end;
procedure TPedidoProduto.Setid(const Value: Integer);
begin
Fid := Value;
end;
procedure TPedidoProduto.SetnumeroPedido(const Value: TPedidoDadosGerais);
begin
FnumeroPedido := Value;
end;
procedure TPedidoProduto.Setquantidade(const Value: Integer);
begin
Fquantidade := Value;
end;
procedure TPedidoProduto.SetvalorTotal(const Value: Double);
begin
FvalorTotal := Value;
end;
procedure TPedidoProduto.SetvalorUnitario(const Value: Double);
begin
FvalorUnitario := Value;
end;
end.
|
unit ncCommPlus;
interface
uses
SysUtils, Classes, rtcDataCli, rtcInfo, rtcConn, rtcHttpCli, ExtCtrls, dialogs;
type
TplusReq = class
ptrTokenNex : TGUID;
ptrTokenPlus : String;
ptrGettingToken : Boolean;
ptrReq: TRTCDataRequest;
ptrCli: TRTCHttpClient;
ptrResp: TStrings;
FOnResp : TNotifyEvent;
FOnFail : TNotifyEvent;
FLastError : String;
FNoFreeAfterResp : Boolean;
private
procedure TimerAfterToken(Sender: TObject); virtual;
procedure TimerConectar(Sender: TObject);
procedure TimerConectado(Sender: TObject);
procedure _ConnectOk(Sender: TRtcConnection);
procedure _ConnectError(Sender: TRtcConnection; E: Exception);
procedure _ConnectFail(Sender: TRtcConnection);
procedure _ConnectLost(Sender: TRtcConnection);
procedure _ResponseReject(Sender: TRtcConnection);
procedure _ResponseAbort(Sender: TRtcConnection);
procedure _CreateRTC;
procedure _FreeRTC;
protected
procedure _BeginRequest(Sender: TRtcConnection); virtual;
procedure _ResponseDone(Sender: TRtcConnection); virtual;
procedure prepareRequest; virtual;
procedure prepare_getToken;
function ptrTokenNexStr: String;
function ptrKey: String;
destructor Destroy; virtual;
public
constructor Create; virtual;
procedure Start;
property Resposta: TStrings read ptrResp;
property LastError: String read FLastError;
property NoFreeAfterResp: Boolean read FNoFreeAfterResp write FNoFreeAfterResp;
property OnResp: TNotifyEvent read FOnResp write FOnResp;
property OnFail: TNotifyEvent read FOnFail write FOnFail;
end;
TplusPostTranReq = class ( TplusReq )
ptrConta : String;
ptrParceiro : String;
ptrIDTranParceiro : String;
ptrIDTranNex : String;
ptrDTTranNex : TDateTime;
ptrDescr : String;
ptrDTTranParceiro : TDateTime;
ptrValor : Double;
ptrPIN : String;
ptrSucesso : Boolean;
ptrObs : String;
protected
procedure prepareRequest; override;
public
constructor Create; override;
end;
TplusReqProdutos = class ( TplusReq )
protected
procedure prepareRequest; override;
public
function ItemCount: Integer;
function ProdutoExiste(aCodParceiro, aCodigo: String): Boolean;
function Codigo(I: Integer): String;
function CodParceiro(I: Integer): String;
function Nome(I: Integer): String;
function url_imagem(I: Integer): String;
function url_vendas(I: Integer): String;
end;
TplusReqParceiros = class ( TplusReq )
protected
procedure prepareRequest; override;
public
function ItemCount: Integer;
function ParceiroExiste(aCodParceiro: String): Boolean;
function Codigo(i: Integer): String;
function Nome(i: Integer): String;
function KeyIndex(i: Integer): String;
function url_imagem(i: Integer): String;
function url_timeout(I: Integer): String;
end;
TplusReqAdesoes = class ( TplusReq )
praConta : String;
protected
procedure prepareRequest; override;
public
function AdesaoExiste(aCodParceiro: String): Boolean;
constructor Create; override;
end;
TplusReqUpdateAll = class
private
FEtapa : Byte;
FSucesso : Boolean;
FReqParceiros: TplusReqParceiros;
FReqProdutos: TplusReqProdutos;
FReqAdesoes: TplusReqAdesoes;
FOnTerminar : TNotifyEvent;
FTag: Integer;
procedure _Fail(Sender: TObject);
procedure _Resp(Sender: TObject);
procedure OnTimerTerminar(Sender: TObject);
public
constructor Create;
destructor Destroy; override;
procedure Executar;
property Sucesso: Boolean read FSucesso;
property Tag: Integer read FTag write FTag;
property ReqParceiros: TplusReqParceiros read FReqParceiros;
property ReqProdutos: TplusReqProdutos read FReqProdutos;
property ReqAdesoes: TplusReqAdesoes read FReqAdesoes;
property OnTerminar: TNotifyEvent read FOnTerminar write FOnTerminar;
end;
implementation
uses ncaK, ncClassesBase, ncShellStart;
const
BoolStr : Array[Boolean] of Char = ('0', '1');
HostStr : String = 'plus.dev.nexcafe.com.br';
{ TplusReq }
function GetNStr(S: String; P: Integer): String;
begin
while (P>1) do begin
Delete(S, 1, Pos(';', S));
Dec(P);
end;
if Pos(';', S)>0 then
Delete(S, Pos(';', S), 1000);
Result := Trim(S);
end;
constructor TplusReq.Create;
begin
FNoFreeAfterResp := False;
ptrCli := nil;
ptrReq := nil;
FOnResp := nil;
FOnFail := nil;
FLastError := '';
ptrGettingToken := False;
ptrResp := TStringList.Create;
CreateGUID(ptrTokenNex)
end;
destructor TplusReq.Destroy;
begin
_FreeRTC;
ptrResp.Free;
inherited;
end;
procedure TplusReq.prepareRequest;
begin
ptrReq.Request.Host := HostStr;
ptrReq.Request.Method := 'GET';
end;
procedure TplusReq.prepare_getToken;
begin
with ptrReq.Request do begin
ptrGettingToken := True;
Method:='GET';
FileName:='/api/tokenplus/get/';
Host:= HostStr;
ptrCli.ServerAddr := Host;
ptrCli.ServerPort := '80';
Query.Text := '';
end;
end;
function TplusReq.ptrKey: String;
begin
nexGetKH(1, ptrTokenPlus, '', '');
end;
function TplusReq.ptrTokenNexStr: String;
begin
Result := GUIDToString(ptrTokenNex);
end;
procedure TplusReq.Start;
begin
_CreateRTC;
ptrTokenPlus := '';
ptrResp.Text := '';
prepare_getToken;
try
if not ptrCli.isConnected then begin
with TTimer.Create(nil) do begin
Interval := 500;
OnTimer := TimerConectar;
Enabled := True;
end;
end else
ptrReq.Post;
except
if Assigned(FOnFail) then FOnFail(Self);
end;
end;
procedure TplusReq.TimerAfterToken(Sender: TObject);
begin
Sender.Free;
_CreateRTC;
prepareRequest;
try
if not ptrCli.isConnected then begin
with TTimer.Create(nil) do begin
Interval := 500;
OnTimer := TimerConectar;
Enabled := True;
end;
end else
ptrReq.Post;
except
if Assigned(FOnFail) then FOnFail(Self);
end;
end;
procedure TplusReq.TimerConectado(Sender: TObject);
begin
Sender.Free;
ptrReq.Post;
end;
procedure TplusReq.TimerConectar(Sender: TObject);
begin
Sender.Free;
if not ptrCli.isConnected then
ptrCli.Connect;
end;
procedure TplusReq._BeginRequest(Sender: TRtcConnection);
begin
ptrReq.Client.WriteHeader;
end;
procedure TplusReq._ConnectError(Sender: TRtcConnection; E: Exception);
begin
FLastError := 'Connect Error: '+ E.Message;
if Assigned(FOnFail) then FOnFail(Self);
end;
procedure TplusReq._ConnectFail(Sender: TRtcConnection);
begin
FLastError := 'Connect Fail';
if Assigned(FOnFail) then
FOnFail(Self);
end;
procedure TplusReq._ConnectLost(Sender: TRtcConnection);
begin
FLastError := 'Connect Lost';
if Assigned(FOnFail) then
FOnFail(Self);
end;
procedure TplusReq._ConnectOk(Sender: TRtcConnection);
begin
with TTimer.Create(nil) do begin
Interval := 500;
OnTimer := TimerConectado;
Enabled := True;
end;
end;
procedure TplusReq._CreateRTC;
begin
if ptrCli=nil then begin
ptrCli := TRTCHTTPClient.Create(nil);
ptrCli.OnConnect := _ConnectOk;
ptrCli.OnConnectFail := _ConnectFail;
ptrCli.OnResponseAbort := _ResponseAbort;
ptrCli.OnResponseReject := _ResponseReject;
ptrCli.OnConnectError := _ConnectError;
ptrCli.OnConnectLost := _ConnectLost;
ptrCli.AutoConnect := False;
ptrCli.FixupRequest.EncodeQuery := True;
ptrCli.ServerPort := '80';
ptrCli.ServerAddr := HostStr;
end;
if ptrReq=nil then begin
ptrReq := TRtcDataRequest.Create(nil);
ptrReq.AutoSyncEvents := True;
ptrReq.AutoRepost := 5;
ptrReq.Client := ptrCli;
ptrReq.OnBeginRequest := _BeginRequest;
ptrReq.OnResponseDone := _ResponseDone;
end;
end;
procedure TplusReq._FreeRTC;
begin
if Assigned(ptrReq) then FreeAndNil(ptrReq);
if Assigned(ptrCli) then FreeAndNil(ptrCli);
end;
procedure TplusReq._ResponseAbort(Sender: TRtcConnection);
begin
FLastError := 'Response Abort';
if Assigned(FOnFail) then FOnFail(Self);
end;
procedure TplusReq._ResponseDone(Sender: TRtcConnection);
var S: String;
begin
ptrResp.Text := ptrCli.Read;
if ptrGettingToken then begin
ptrGettingToken := False;
ptrTokenPlus := ptrResp[0];
ptrResp.Text := '';
with TTimer.Create(nil) do begin
Interval := 500;
OnTimer := TimerAfterToken;
Enabled := True;
end;
end else begin
if not FNoFreeAfterResp then _FreeRTC;
encodeurl(
ptrResp.Text := UTF8ToAnsi(ptrResp.Text);
if Assigned(FOnResp) then FOnResp(Self);
end;
end;
procedure TplusReq._ResponseReject(Sender: TRtcConnection);
begin
FLastError := 'Response Reject';
if Assigned(FOnFail) then FOnFail(Self);
end;
{ TplusPostTranReq }
constructor TplusPostTranReq.Create;
begin
inherited;
NoFreeAfterResp := True;
ptrConta := '';
ptrParceiro := '';
ptrDescr := '';
ptrIDTranParceiro := '';
ptrIDTranNex := '';
ptrDTTranParceiro := 0;
ptrDTTranNex := 0;
ptrValor := 0;
ptrPIN := '';
ptrSucesso := False;
ptrObs := '';
end;
procedure TplusPostTranReq.prepareRequest;
var S: String; Code: Integer;
begin
inherited;
with ptrReq.Request do begin
Filename := '/api/transacoes/salvar/';
Query.Clear;
Query.asString['account'] := ptrConta;
Query.asString['partner_id'] := ptrParceiro;
Query.asString['transaction_partner_id'] := ptrIDTranParceiro;
Query.asString['transaction_partner_datetime'] := FormatDateTime('yyyy-mm-dd hh:mm:ss', ptrDTTranParceiro);
Query.asString['transaction_nexcafe_id'] := ptrIDTranNex;
Query.asString['transaction_nexcafe_datetime'] := FormatDateTime('yyyy-mm-dd hh:mm:ss', ptrDTTranNex);
Str(ptrValor:0:2, S);
Query.asString['description'] := ptrDescr;
Query.asString['value'] := S;
Query.asString['pin'] := ptrPIN;
Query.asString['success'] := BoolStr[ptrSucesso];
Query.asString['comment'] := ptrObs;
Query.asString['key'] := nexGetKH(1, ptrTokenPlus, '', '');
Query.asString['tokennex'] := ptrTokenNexStr;
Query.asString['tokenplus'] := ptrTokenPlus;
end;
end;
{ TplusReqProdutos }
function TplusReqProdutos.Codigo(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 1);
end;
function TplusReqProdutos.CodParceiro(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 2);
end;
function TplusReqProdutos.ItemCount: Integer;
begin
Result := ptrResp.Count - 1;
end;
function TplusReqProdutos.Nome(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 3);
end;
procedure TplusReqProdutos.prepareRequest;
begin
inherited;
with ptrReq.Request do begin
Method:='GET';
FileName:='/api/produtos/';
Host:= HostStr;
Query.Clear;
Query.asString['key'] := nexGetKH(1, ptrTokenPlus, '', '');
Query.asString['tokennex'] := ptrTokenNexStr;
Query.asString['tokenplus'] := ptrTokenPlus;
end;
end;
function TplusReqProdutos.ProdutoExiste(aCodParceiro, aCodigo: String): Boolean;
var I: Integer;
begin
for I := 1 to ItemCount do
if SameText(Codigo(I), aCodigo) and SameText(CodParceiro(I), aCodParceiro) then begin
Result := True;
Exit;
end;
Result := False;
end;
function TplusReqProdutos.url_imagem(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 4);
end;
function TplusReqProdutos.url_vendas(I: Integer): String;
var S: String;
begin
S := ptrResp[i];
Result := GetNStr(S, 5);
end;
{ TplusReqParceiros }
function TplusReqParceiros.Codigo(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 1);
end;
function TplusReqParceiros.ItemCount: Integer;
begin
Result := ptrResp.Count-1;
end;
function TplusReqParceiros.KeyIndex(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 3);
end;
function TplusReqParceiros.Nome(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 2);
end;
function TplusReqParceiros.ParceiroExiste(aCodParceiro: String): Boolean;
var I: Integer;
begin
for I := 1 to ItemCount do
if SameText(Codigo(I), aCodParceiro) then begin
Result := True;
Exit;
end;
Result := False;
end;
procedure TplusReqParceiros.prepareRequest;
begin
inherited;
with ptrReq.Request do begin
Method:='GET';
FileName:='/api/parceiros/';
Host:= HostStr;
Query.Clear;
Query.asString['key'] := nexGetKH(1, ptrTokenPlus, '', '');
Query.asString['tokennex'] := ptrTokenNexStr;
Query.asString['tokenplus'] := ptrTokenPlus;
end;
end;
function TplusReqParceiros.url_imagem(i: Integer): String;
begin
Result := GetNStr(ptrResp[i], 4);
end;
function TplusReqParceiros.url_timeout(I: Integer): String;
begin
Result := GetNStr(ptrResp[i], 5);
end;
{ TplusReqAdesoes }
function TplusReqAdesoes.AdesaoExiste(aCodParceiro: String): Boolean;
var
S, sCod: String;
P: Integer;
begin
S := Resposta.Values['Adesoes'];
Result := False;
while (not Result) and (Length(S)>0) do begin
P := Pos(';', S);
if P>0 then begin
sCod := Trim(Copy(S, 1, P-1));
Delete(S, 1, P);
end else begin
sCod := Trim(S);
S := '';
end;
if SameText(aCodParceiro, sCod) then
Result := True;
end;
end;
constructor TplusReqAdesoes.Create;
begin
inherited;
praConta := '';
end;
procedure TplusReqAdesoes.prepareRequest;
begin
inherited;
with ptrReq.Request do begin
Method:='GET';
FileName:='/api/adesoes/';
Host:='plus.dev.nexcafe.com.br';
Query.Clear;
Query.asString['account'] := praConta;
Query.asString['key'] := nexGetKH(1, ptrTokenPlus, '', '');
Query.asString['tokennex'] := ptrTokenNexStr;
Query.asString['tokenplus'] := ptrTokenPlus;
end;
end;
{ TplusReqUpdateAll }
constructor TplusReqUpdateAll.Create;
begin
inherited;
FEtapa := 0;
FTag := 0;
FSucesso := False;
FReqParceiros := TplusReqParceiros.Create;
FReqParceiros.OnResp := _Resp;
FReqParceiros.OnFail := _Fail;
FReqProdutos := TplusReqProdutos.Create;
FReqProdutos.OnResp := _Resp;
FReqProdutos.OnFail := _Fail;
FReqAdesoes := TplusReqAdesoes.Create;
FReqAdesoes.OnResp := _Resp;
FReqAdesoes.OnFail := _Fail;
FOnTerminar := nil;
end;
destructor TplusReqUpdateAll.Destroy;
begin
FReqParceiros.Free;
FReqProdutos.Free;
FReqAdesoes.Free;
inherited;
end;
procedure TplusReqUpdateAll.Executar;
begin
FEtapa := 1;
FSucesso := False;
FReqParceiros.Resposta.Clear;
FReqProdutos.Resposta.Clear;
FReqAdesoes.Resposta.Clear;
FReqParceiros.Start;
end;
procedure TplusReqUpdateAll.OnTimerTerminar(Sender: TObject);
begin
Sender.Free;
if Assigned(FOnTerminar) then
FOnTerminar(Self);
end;
procedure TplusReqUpdateAll._Fail(Sender: TObject);
begin
FSucesso := False;
with TTimer.Create(nil) do begin
OnTimer := OnTimerTerminar;
Interval := 50;
Enabled := True;
end;
end;
procedure TplusReqUpdateAll._Resp(Sender: TObject);
begin
Inc(FEtapa);
case FEtapa of
2 : FReqProdutos.Start;
3 : begin
FReqAdesoes.praConta := gConfig.Conta;
FReqAdesoes.Start;
end
else
FSucesso := True;
with TTimer.Create(nil) do begin
OnTimer := OnTimerTerminar;
Interval := 50;
Enabled := True;
end;
end;
end;
end.
|
unit MediaProcessing.Convertor.HH.RGB;
interface
uses SysUtils,Windows,Classes,MediaProcessing.Definitions,MediaProcessing.Global;
type
TChangeFPSMode = (cfmNone,cfmAbsolute, cfmVIFrameOnly);
TChangeImageSizeMode = (cismNone,cismScale,cismCustomSize);
TMediaProcessor_Convertor_Hh_Rgb=class (TMediaProcessor,IMediaProcessor_Convertor_Hh_Rgb)
protected
FChangeFPSMode : TChangeFPSMode;
FFPSValue: integer;
FVIFramesOnly: boolean;
FImageSizeMode : TChangeImageSizeMode;
FImageSizeScale : integer;
FImageSizeWidth : integer;
FImageSizeHeight : integer;
protected
procedure SaveCustomProperties(const aWriter: IPropertiesWriter); override;
procedure LoadCustomProperties(const aReader: IPropertiesReader); override;
class function MetaInfo:TMediaProcessorInfo; override;
public
constructor Create; override;
destructor Destroy; override;
function HasCustomProperties: boolean; override;
procedure ShowCustomProperiesDialog;override;
end;
implementation
uses Controls,uBaseClasses,MediaProcessing.Convertor.HH.RGB.SettingsDialog;
{ TMediaProcessor_Convertor_Hh_Rgb }
constructor TMediaProcessor_Convertor_Hh_Rgb.Create;
begin
inherited;
FImageSizeScale:=2;
FImageSizeMode:=cismNone;
FImageSizeWidth:=640;
FImageSizeHeight:=480;
end;
destructor TMediaProcessor_Convertor_Hh_Rgb.Destroy;
begin
inherited;
end;
function TMediaProcessor_Convertor_Hh_Rgb.HasCustomProperties: boolean;
begin
result:=true;
end;
class function TMediaProcessor_Convertor_Hh_Rgb.MetaInfo: TMediaProcessorInfo;
begin
result.Clear;
result.TypeID:=IMediaProcessor_Convertor_Hh_Rgb;
result.Name:='Конвертор HH->RGB';
result.Description:='Преобразует видеокадры формата HH (камеры Beward) в формат RGB';
result.SetInputStreamType(stHHVI);
result.OutputStreamType:=stRGB;
result.ConsumingLevel:=9;
end;
procedure TMediaProcessor_Convertor_Hh_Rgb.LoadCustomProperties(const aReader: IPropertiesReader);
begin
inherited;
FImageSizeMode:=TChangeImageSizeMode(aReader.ReadInteger('ImageSize.ChangeMode',integer(FImageSizeMode)));
FImageSizeScale:=aReader.ReadInteger('ImageSize.Scale',FImageSizeScale);
FImageSizeWidth:=aReader.ReadInteger('ImageSize.Width',FImageSizeWidth);
FImageSizeHeight:=aReader.ReadInteger('ImageSize.Height',FImageSizeHeight);
FChangeFPSMode:=TChangeFPSMode(aReader.ReadInteger('ChangeFPSMode',0));
FFPSValue:=aReader.ReadInteger('FPSValue',25);
FVIFramesOnly:=aReader.ReadBool('VIFramesOnly',false)
end;
procedure TMediaProcessor_Convertor_Hh_Rgb.SaveCustomProperties(const aWriter: IPropertiesWriter);
begin
inherited;
aWriter.WriteInteger('ImageSize.ChangeMode',integer(FImageSizeMode));
aWriter.WriteInteger('ImageSize.Scale',FImageSizeScale);
aWriter.WriteInteger('ImageSize.Width',FImageSizeWidth);
aWriter.WriteInteger('ImageSize.Height',FImageSizeHeight);
aWriter.WriteInteger('ChangeFPSMode',integer(FChangeFPSMode));
aWriter.WriteInteger('FPSValue',FFPSValue);
aWriter.WriteBool('VIFramesOnly',FVIFramesOnly);
end;
procedure TMediaProcessor_Convertor_Hh_Rgb.ShowCustomProperiesDialog;
var
aDialog: TfmMediaProcessingSettingsHh_Rgb;
begin
aDialog:=TfmMediaProcessingSettingsHh_Rgb.Create(nil);
try
aDialog.ckChangeImageSize.Checked:=FImageSizeMode<>cismNone;
aDialog.cbImageSizeScale.ItemIndex:=aDialog.cbImageSizeScale.Items.IndexOfData(FImageSizeScale);
if aDialog.cbImageSizeScale.ItemIndex=-1 then
aDialog.cbImageSizeScale.ItemIndex:=0;
aDialog.buImageSizeScale.Checked:=FImageSizeMode=cismScale;
aDialog.buImageSizeCustomSize.Checked:=FImageSizeMode=cismCustomSize;
if FImageSizeMode=cismNone then
aDialog.buImageSizeScale.Checked:=true;
aDialog.edImageSizeWidth.Value:=FImageSizeWidth;
aDialog.edimageSizeHeight.Value:=FImageSizeHeight;
aDialog.ckChangeFPS.Checked:=FChangeFPSMode<>cfmNone;
aDialog.ckChangeFPSAbsolute.Checked:=FChangeFPSMode in [cfmAbsolute,cfmNone];
aDialog.ckFPSVIFramesOnly.Checked:=FChangeFPSMode=cfmVIFrameOnly;
aDialog.edFPSValue.Value:=FFPSValue;
if aDialog.ShowModal=mrOK then
begin
if not aDialog.ckChangeImageSize.Checked then
FImageSizeMode:=cismNone
else if aDialog.buImageSizeScale.Checked then
FImageSizeMode:=cismScale
else if aDialog.buImageSizeCustomSize.Checked then
FImageSizeMode:=cismCustomSize
else
Assert(false);
FImageSizeScale:=aDialog.cbImageSizeScale.CurrentItemData;
FImageSizeWidth:=aDialog.edImageSizeWidth.Value;
FImageSizeHeight:=aDialog.edimageSizeHeight.Value;
FChangeFPSMode:=cfmNone;
if aDialog.ckChangeFPS.Checked then
begin
if aDialog.ckChangeFPSAbsolute.Checked then
begin
FChangeFPSMode:=cfmAbsolute;
FFPSValue:=aDialog.edFPSValue.Value
end
else begin
FChangeFPSMode:=cfmVIFrameOnly;
end;
end;
end;
finally
aDialog.Free;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessor(TMediaProcessor_Convertor_Hh_Rgb);
end.
|
unit BD.Kommune;
interface
uses System.SysUtils, System.Classes, Data.DB, OXmlPDOM, BD.Fylke,
Generics.Collections, System.TypInfo, BD.Handler, Spring.Collections;
type
TKommune = class(TObject)
private
FKommunenr: String;
FKommune: String;
FFylkenr: String;
FFylke: TFylke;
public
function GetFylkeNavn: String;
published
property Kommunenr: String read FKommunenr write FKommunenr;
property Kommune: String read FKommune write FKommune;
property Fylkenr: String read FFylkenr write FFylkenr;
property Fylke: TFylke read FFylke write FFylke;
end;
TKommuneListe = IList<TKommune>;
TKommuneHandler = class(THandler)
class function Load(KommuneNode: PXMLNode;
const Mapping: TMapList): TKommune;
class function LinkToFylke(AKommune: TKommune;
FylkeListe: TFylkeListe): Boolean;
class function NewKommuneListe: TKommuneListe;
end;
implementation
{ TKommuneHandler }
class function TKommuneHandler.LinkToFylke(AKommune: TKommune;
FylkeListe: TFylkeListe): Boolean;
var
F: TFylke;
begin
if FylkeListe.TryGetSingle(F,
function(const AFylke: TFylke): Boolean begin
Result := (AFylke.Fylkenr = AKommune.Fylkenr);
end
) then AKommune.Fylke := F;
end;
class function TKommuneHandler.Load(KommuneNode: PXMLNode;
const Mapping: TMapList): TKommune;
begin
LoadFromXML<TKommune>(KommuneNode, Mapping);
end;
class function TKommuneHandler.NewKommuneListe: TKommuneListe;
begin
Result := TCollections.CreateObjectList<TKommune>;
end;
{ TKommune }
function TKommune.GetFylkeNavn: String;
begin
Result := '';
if Fylke <> nil then
Result := Fylke.Fylke;
end;
end.
|
unit Ths.Erp.Database.Table.SysPermissionSource;
interface
{$I ThsERP.inc}
uses
SysUtils, Classes, Dialogs, Forms, Windows, Controls, Types, DateUtils,
FireDAC.Stan.Param, StrUtils, RTTI, Data.DB,
Ths.Erp.Database,
Ths.Erp.Database.Table;
type
TSysPermissionSource = class(TTable)
private
FSourceCode: TFieldDB;
FSourceName: TFieldDB;
FSourceGroupID: TFieldDB;
//not a database field
FSourceGroup: TFieldDB;
protected
published
constructor Create(OwnerDatabase: TDatabase);override;
public
procedure SelectToDatasource(pFilter: string; pPermissionControl: Boolean=True); override;
procedure SelectToList(pFilter: string; pLock: Boolean; pPermissionControl: Boolean=True); override;
procedure Insert(out pID: Integer; pPermissionControl: Boolean=True); override;
procedure Update(pPermissionControl: Boolean=True); override;
function Clone():TTable;override;
property SourceCode: TFieldDB read FSourceCode write FSourceCode;
property SourceName: TFieldDB read FSourceName write FSourceName;
property SourceGroupID: TFieldDB read FSourceGroupID write FSourceGroupID;
//not a database field
property SourceGroup: TFieldDB read FSourceGroup write FSourceGroup;
end;
implementation
uses
Ths.Erp.Constants,
Ths.Erp.Database.Singleton;
constructor TSysPermissionSource.Create(OwnerDatabase:TDatabase);
begin
inherited Create(OwnerDatabase);
TableName := 'sys_permission_source';
TTable(Self).SourceCode := '1';
FSourceCode := TFieldDB.Create('source_code', ftString, '');
FSourceName := TFieldDB.Create('source_name', ftString, '');
FSourceGroupID := TFieldDB.Create('source_group_id', ftInteger, 0);
FSourceGroup := TFieldDB.Create('source_group', ftString, '');
end;
procedure TSysPermissionSource.SelectToDatasource(pFilter: string;
pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptRead, pPermissionControl) then
begin
with QueryOfDS do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
'pg' + '.' + FSourceGroup.FieldName,
TableName + '.' + FSourceCode.FieldName,
TableName + '.' + FSourceName.FieldName,
TableName + '.' + FSourceGroupID.FieldName
]) +
'LEFT JOIN sys_permission_source_group pg ON pg.id =' + TableName + '.' + FSourceGroupID.FieldName +
' WHERE 1=1 ' + pFilter;
Open;
Active := True;
Self.DataSource.DataSet.FindField(Self.Id.FieldName).DisplayLabel := 'ID';
Self.DataSource.DataSet.FindField(FSourceCode.FieldName).DisplayLabel := 'SOURCE CODE';
Self.DataSource.DataSet.FindField(FSourceName.FieldName).DisplayLabel := 'SOURCE NAME';
Self.DataSource.DataSet.FindField(FSourceGroupID.FieldName).DisplayLabel := 'SOURCE GROUP ID';
Self.DataSource.DataSet.FindField(FSourceGroup.FieldName).DisplayLabel := 'SOURCE GROUP';
end;
end;
end;
procedure TSysPermissionSource.SelectToList(pFilter: string; pLock:
Boolean; pPermissionControl: Boolean=True);
begin
if Self.IsAuthorized(ptRead, pPermissionControl) then
begin
if (pLock) then
pFilter := pFilter + ' FOR UPDATE OF ' + TableName + ' NOWAIT';
with QueryOfList do
begin
Close;
SQL.Text := Database.GetSQLSelectCmd(TableName, [
TableName + '.' + Self.Id.FieldName,
TableName + '.' + FSourceCode.FieldName,
TableName + '.' + FSourceName.FieldName,
TableName + '.' + FSourceGroupID.FieldName
]) +
'WHERE 1=1 ' + pFilter;
Open;
FreeListContent();
List.Clear;
while NOT EOF do
begin
Self.Id.Value := FormatedVariantVal(FieldByName(Self.Id.FieldName).DataType, FieldByName(Self.Id.FieldName).Value);
FSourceCode.Value := FormatedVariantVal(FieldByName(FSourceCode.FieldName).DataType, FieldByName(FSourceCode.FieldName).Value);
FSourceName.Value := FormatedVariantVal(FieldByName(FSourceName.FieldName).DataType, FieldByName(FSourceName.FieldName).Value);
FSourceGroupID.Value := FormatedVariantVal(FieldByName(FSourceGroupID.FieldName).DataType, FieldByName(FSourceGroupID.FieldName).Value);
List.Add(Self.Clone());
Next;
end;
EmptyDataSet;
Close;
end;
end;
end;
procedure TSysPermissionSource.Insert(out pID: Integer; pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptAddRecord, pPermissionControl) then
begin
with QueryOfInsert do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLInsertCmd(TableName, QUERY_PARAM_CHAR, [
FSourceCode.FieldName,
FSourceName.FieldName,
FSourceGroupID.FieldName
]);
NewParamForQuery(QueryOfInsert, FSourceCode);
NewParamForQuery(QueryOfInsert, FSourceName);
NewParamForQuery(QueryOfInsert, FSourceGroupID);
Open;
if (Fields.Count > 0) and (not Fields.FieldByName(Self.Id.FieldName).IsNull) then
pID := Fields.FieldByName(Self.Id.FieldName).AsInteger
else
pID := 0;
EmptyDataSet;
Close;
end;
Self.notify;
end;
end;
procedure TSysPermissionSource.Update(pPermissionControl: Boolean=True);
begin
if IsAuthorized(ptUpdate, pPermissionControl) then
begin
with QueryOfUpdate do
begin
Close;
SQL.Clear;
SQL.Text := Database.GetSQLUpdateCmd(TableName, QUERY_PARAM_CHAR, [
FSourceCode.FieldName,
FSourceName.FieldName,
FSourceGroupID.FieldName
]);
NewParamForQuery(QueryOfUpdate, FSourceCode);
NewParamForQuery(QueryOfUpdate, FSourceName);
NewParamForQuery(QueryOfUpdate, FSourceGroupID);
NewParamForQuery(QueryOfUpdate, Id);
ExecSQL;
Close;
end;
Self.notify;
end;
end;
function TSysPermissionSource.Clone():TTable;
begin
Result := TSysPermissionSource.Create(Database);
Self.Id.Clone(TSysPermissionSource(Result).Id);
FSourceCode.Clone(TSysPermissionSource(Result).FSourceCode);
FSourceName.Clone(TSysPermissionSource(Result).FSourceName);
FSourceGroupID.Clone(TSysPermissionSource(Result).FSourceGroupID);
FSourceGroup.Clone(TSysPermissionSource(Result).FSourceGroup);
end;
end.
|
unit clsDBUserAuthContent;
interface
uses SysUtils,Classes,Dialogs,ADODB,clsDBInterface,clsClientDtSet;
type
TDBUserAuthContent=Class (TInterFacedObject,IDBInterface)
public
procedure Add(const obj:TObject);
procedure Edit(const obj:TObject);
procedure Delete(const obj:TObject);
function QueryIFRecordExist(obj:TObject):Boolean;
function getTrimData:TADODataSet;
end;
implementation
uses clsGlobal, clsAuthorizationContent, UserAuthContentForm;
{ TDBFlexField }
procedure TDBUserAuthContent.Add(const obj: TObject);
var
Sqlstr:String;
begin
//do add
with (obj as TclsAuthorizationContent) do begin
Sqlstr:='INSERT INTO TBLTHRAUTHORIZATIONCONTENT(FID,FNAME,FDESC,FFunctionList,';
Sqlstr:=Sqlstr+'FBuilder,FBDate) VALUES (''';
Sqlstr:=Sqlstr+FID+''','''+FName+''',''';
Sqlstr:=Sqlstr+FDesc+''','''+FFunctionList+''',''';
Sqlstr:=Sqlstr+ObjGlobal.objUser.FID+''',''';
Sqlstr:=Sqlstr+FormatDateTime('yyyy/mm/dd hh:nn:ss',now)+''')';
end; //with end
try
objGlobal.objDataConnect.DataExecute(Sqlstr);
//MessageDlg('Add Record successfully!',mtInformation,[mbYes],0);
except
on E:Exception do begin
MessageDlg(e.Message,mtError,[mbOK],0);
end; //on end
end; //try end
end;
procedure TDBUserAuthContent.Delete(const obj: TObject);
var
Sqlstr:String;
begin
with (obj as TclsAuthorizationContent) do begin
Sqlstr:='DELETE from TBLTHRAUTHORIZATIONCONTENT where FID ='''+FID+'''';
end; //with end
try
objGlobal.objDataConnect.DataExecute(Sqlstr);
except
on E:Exception do begin
MessageDlg(e.Message,mtError,[mbOK],0);
end; //on end
end; //try end
end;
procedure TDBUserAuthContent.Edit(const obj: TObject);
var
Sqlstr:String;
strSQL:string;
//slUserAuth:TStringList;
adsTemp:TClientDtSet;
adsTemp2:TClientDtSet;
objUserAuthContent:TclsAuthorizationContent;
i:integer;
Flag:Boolean;
begin
objUserAuthContent:=TclsAuthorizationContent.Create;
with objUserAuthContent do begin
FID:=frmUserAuthContent.edtID.Text;
FName:=frmUserAuthContent.edtName.Text;
FDesc:=frmUserAuthContent.edtDesc.Text;
Sqlstr:='select FFunctionList from TBLTHRAUTHORIZATIONCONTENT where FID='''+FID+'''';
adsTemp:=ObjGlobal.objDataConnect.DataQuery(Sqlstr);
while not adsTemp.EOF do begin
Flag:=false;
for i:=0 to (obj as TStringList).Count-1 do begin
if adsTemp.FieldByName('FFunctionList').AsString=(obj as TStringList).Strings[i] then begin
Flag:=true;
end;
end;
if Flag=False then begin
Sqlstr:='DELETE FROM TBLTHRAUTHORIZATIONCONTENT where FID ='''+FID+'''';
Sqlstr:=Sqlstr+' and FFunctionList='''+adsTemp.FieldbyName('FFunctionList').AsString+'''';
ObjGlobal.objDataConnect.DataExecute(Sqlstr);
end;
adsTemp.next;
end;
adsTemp.Close;
for i:=0 to (obj as TStringList).Count-1 do begin
FFunctionList:=(obj as TStringList).Strings[i];
strSQL:='SELECT COUNT(*) a FROM TBLTHRAUTHORIZATIONCONTENT where FID='''+FID+'''';
strSQL:=strSQL+' and FFunctionList='''+FFunctionList+'''';
adsTemp2:=ObjGlobal.objDataConnect.DataQuery(strSQL);
if adsTemp2.FieldByName('a').AsInteger>0 then begin //edit
Sqlstr:='UPDATE TBLTHRAUTHORIZATIONCONTENT SET FReviser=''';
Sqlstr:=Sqlstr+ObjGlobal.objUser.FID+''', FRdate=''';
Sqlstr:=Sqlstr+FormatDateTime('yyyy/mm/dd hh:nn:ss',now)+''''+' where FID=''';
Sqlstr:=Sqlstr+FID+''' and FFunctionList='''+FFunctionList+'''';
ObjGlobal.objDataConnect.DataExecute(Sqlstr);
end
else begin //add
Sqlstr:='INSERT INTO TBLTHRAUTHORIZATIONCONTENT(FID,FName,FDesc,FFunctionList,';
Sqlstr:=Sqlstr+'FBuilder,FBDate) values (''';
Sqlstr:=Sqlstr+FID+''','''+FName+''',''';
Sqlstr:=Sqlstr+FDesc+''','''+FFunctionList+''',''';
Sqlstr:=Sqlstr+ObjGlobal.objUser.FID+''',''';
Sqlstr:=Sqlstr+FormatDateTime('yyyy/mm/dd hh:nn:ss',now)+''')';
ObjGlobal.objDataConnect.DataExecute(Sqlstr);
end;
adsTemp2.Close;
end;
end;
{with (obj as TclsAuthorizationContent) do begin
Sqlstr:='update TBLTHRAUTHORIZATIONCONTENT set (FID,FName,FDesc,FFunctionList,';
Sqlstr:=Sqlstr+'FBuilder,FBDate,FReviser,FRDate) values (''';
Sqlstr:=Sqlstr+FID+''','''+FName+''',''';
Sqlstr:=Sqlstr+FDesc+''','''+FFunctionList+''',''';
Sqlstr:=Sqlstr+Fbuilder+''','''+FbDate+''',''';
Sqlstr:=Sqlstr+ObjGlobal.objUser.FID+''','''+FormatDateTime('yyyy/mm/dd hh:nn:ss',now)+''')';
end; //with end
try
objGlobal.objDataConnect.objConnection.Execute(Sqlstr);
//MessageDlg('Edit Record successfully!',mtInformation,[mbYes],0);
except
on E:Exception do begin
case objGlobal.objDataConnect.objConnection.Errors.Item[0].NativeError of
170: MessageDlg('Program''s syntax error!',mtError,[mbOK],0);
207: MessageDlg('Field isn''t exists!',mtError,[mbOK],0);
208: MessageDlg('Table isn''t exists!',mtError,[mbOK],0);
547: MessageDlg('Voilate foreign key constraint!',mtError,[mbOK],0);
2627: MessageDlg('Voilate primary key constraint!',mtError,[mbOK],0);
else
MessageDlg(objGlobal.objDataConnect.objConnection.Errors.Item[0].Description,mtError,[mbOK],0);
end; //case end
end; //on end
end; //try end}
end;
function TDBUserAuthContent.getTrimData: TADODataSet;
begin
//
end;
function TDBUserAuthContent.QueryIFRecordExist(obj: TObject): Boolean;
var
adsTemp:TClientDtSet;
Sqlstr:String;
begin
//check database if any the same record
Result:=False;
with (obj as TclsAuthorizationContent) do begin
adsTemp:=TClientDtSet.Create(nil);
Sqlstr:='SELECT COUNT(*) AS a FROM TBLTHRAUTHORIZATIONCONTENT WHERE FID =''';
Sqlstr:=Sqlstr+ FID+'''AND FFunctionList ='''+FFunctionList+'''';
adsTemp.RemoteServer:=objGlobal.objDataConnect.ObjConnection;
adsTemp.ProviderName:=objGlobal.objDaStProvideName;
adsTemp.CommandText:=Sqlstr;
adsTemp.Open;
if adsTemp.FieldByName('a').AsInteger>0 then begin
MessageDlg('DataBase has the same record, ID=['+FID+'] Function List=['+FFunctionList+'], please check!',mtError,[mbOK],0);
Result:=True;
end;
adsTemp.Close;
adsTemp.Free;
end; //end with
end;
end.
|
unit IWDsnPaint;
interface
{$R IWDsnPaintSupport.res}
uses
{$IFDEF Linux}QGraphics,{$ELSE}Graphics,{$ENDIF}
{$IFDEF Linux}QButtons, {$ELSE}Buttons,{$ENDIF}
{$IFDEF Linux}Types, {$ELSE}Windows,{$ENDIF}
IWControl, IWFont, Classes;
type
TIWPaintHandlerDsn = class(TIWPaintHandler)
protected
procedure DrawOutline(const ABGColor: TColor = clSilver);
procedure DrawResource(const AName: string; const ALeft: Integer; const ATop: Integer);
procedure SetTransparent;
procedure Draw3DBox; overload;
procedure Draw3DBox(X1, Y1, X2, Y2: Integer); overload;
procedure DrawArrow(ARect: TRect; ADirection: TArrowDirection);
function DrawButton(const AClient: TRect; const ABevelWidth: Integer = 1;
const AIsDown: Boolean = False; const AIsFocused: Boolean = False): TRect;
procedure DrawScrollBar(ARect: TRect);
procedure DrawTextLines(ARect: TRect; AText: TStrings);
procedure SetCanvasFont(AFont: TIWFont);
public
procedure Paint; override;
end;
TIWPaintHandlerComponent = class(TIWPaintHandlerDsn)
public
procedure Paint; override;
end;
implementation
uses
SysUtils, SWSystem;
{ TIWPaintHandlerDsn }
procedure TIWPaintHandlerDsn.SetCanvasFont(AFont: TIWFont);
begin
with FControl.Canvas do begin
Font.Assign(AFont);
if AFont.Color = clNone then begin
Font.Color := clBlack;
end;
end;
end;
procedure TIWPaintHandlerDsn.DrawOutline(const ABGColor: TColor = clSilver);
var
LPoints: array[0..4] of TPoint;
begin
with FControl.Canvas do begin
Brush.Style := bsSolid;
Brush.Color := ABGColor;
FillRect(Rect(0, 0, FControl.Width, FControl.Height));
Pen.Color := clBlack;
// FrameRect does not exist in Kylix 1. Maybe Kylix 2?
LPoints[0] := Point(0, 0);
LPoints[1] := Point(FControl.Width - 1, 0);
LPoints[2] := Point(FControl.Width - 1, FControl.Height - 1);
LPoints[3] := Point(0, FControl.Height - 1);
LPoints[4] := Point(0, 0);
Polyline(LPoints);
end;
end;
procedure TIWPaintHandlerDsn.DrawResource(const AName: string; const ALeft, ATop: Integer);
var
LBitmap: {$IFDEF Linux}QGraphics{$ELSE}Graphics{$ENDIF}.TBitmap;
LInstance: LongWord;
LName: String;
begin
LInstance := FindInstanceContainingResource(UpperCase(AName), RT_BITMAP);
LName := UpperCase(AName);
if LInstance = 0 then begin
// Paint Blank Image for componenets without coresponding palette image
LInstance := FindInstanceContainingResource(UpperCase('BLANK'), RT_BITMAP);
LName := 'BLANK';
end;
if LInstance <> 0 then begin
LBitMap := {$IFDEF Linux}QGraphics{$ELSE}Graphics{$ENDIF}.TBitMap.Create; try
LBitMap.LoadFromResourceName(LInstance, LName);
FControl.Canvas.Draw(ALeft, ATop, LBitMap);
finally FreeAndNil(LBitMap); end;
end;
end;
procedure TIWPaintHandlerDsn.Paint;
begin
DrawOutline;
end;
procedure TIWPaintHandlerDsn.SetTransparent;
begin
{$IFNDEF Linux}
SetBKMode(FControl.Canvas.Handle, TRANSPARENT);
{$ENDIF}
end;
procedure TIWPaintHandlerDsn.Draw3DBox;
begin
Draw3DBox(0, 0, FControl.Width, FControl.Height);
end;
procedure TIWPaintHandlerDsn.Draw3DBox(X1, Y1, X2, Y2: Integer);
begin
with FControl.Canvas do begin
Pen.Color := clGray;
MoveTo(X1, Y1);
LineTo(X2 - 1, Y1);
MoveTo(X1, Y1);
LineTo(X1, Y2 - 1);
MoveTo(X1 + 1, Y1 + 1);
Pen.Color := $00404040;
LineTo(X2 - 2, Y1 + 1);
MoveTo(X1 + 1, Y1 + 1);
LineTo(X1 + 1, Y2 - 2);
Pen.Color := clGray;
MoveTo(X2 - 1, Y1);
LineTo(X2 - 1, Y2);
MoveTo(X1, Y2 - 1);
LineTo(X2 - 1, Y2 - 1);
end;
end;
procedure TIWPaintHandlerDsn.DrawArrow(ARect: TRect; ADirection: TArrowDirection);
var
Mid: Integer;
begin
with FCOntrol.Canvas do begin
Brush.Color := clBlack;
Pen.Color := clBlack;
case Ord(ADirection) of
0: // Up
begin
Mid := (ARect.Right + ARect.Left) div 2;
Polygon([Point(Mid, ARect.Top + 5), Point(Arect.Right - 3, ARect.Bottom - 5),
Point(Arect.Left + 3, ARect.Bottom - 5), Point(Mid, ARect.Top + 5)]);
end;
1: // Down
begin
Mid := (ARect.Right + ARect.Left) div 2;
Polygon([Point(Mid, ARect.Bottom - 5), Point(ARect.Right - 3, ARect.Top + 5),
Point(ARect.Left + 3, ARect.Top + 5), Point(Mid, ARect.Bottom - 5)]);
end;
2: // Left
begin
Mid := (ARect.Top + ARect.Bottom) div 2;
Polygon([Point(ARect.Left + 3, Mid), Point(ARect.Right - 3, ARect.Top + 2),
Point(ARect.Right - 3, ARect.Bottom - 2), Point(ARect.Left + 3, Mid)]);
end;
3: // Right
begin
Mid := (ARect.Top + ARect.Bottom) div 2;
Polygon([Point(ARect.Left + 3, ARect.Top + 2), Point(ARect.Right - 3, Mid),
Point(ARect.Left + 3, ARect.Bottom - 2), Point(ARect.Left + 3, ARect.Top + 2)]);
end;
end;
end;
end;
procedure TIWPaintHandlerDsn.DrawScrollBar(ARect: TRect);
var
LRect: TRect;
begin
LRect := DrawButton(Rect(ARect.Left, ARect.Top + 1, ARect.Right, 18));
DrawArrow(LRect, adUp);
LRect := DrawButton(
Rect(ARect.Left, ARect.Bottom - 16, ARect.Right, ARect.Bottom - ARect.Top + 1));
DrawArrow(LRect, adDown);
{ with FCanvas do begin
Pen.Color := clSilver;
MoveTo(ARect.Left - 1,ARect.Top + 1);
LineTo(ARect.Left - 1, ARect.Bottom + 1);
end;}
end;
procedure TIWPaintHandlerDsn.DrawTextLines(ARect: TRect; AText: TStrings);
var
YPos: Integer;
Ln: Integer;
Bt: Integer;
LText: string;
begin
Ln := 0;
YPos := ARect.Top;
FControl.Canvas.Brush.Style := bsClear;
while (YPos < ARect.Bottom) and (Ln < AText.Count) do begin
LText := AText[Ln];
if Length(LText) < 1 then
LText := ' ';
Bt := YPos + FControl.Canvas.TextHeight(LText);
FControl.Canvas.TextRect(Rect(ARect.Left, YPos, ARect.Right - ARect.Left, Bt), ARect.Left, YPos
, LText);
Inc(Ln);
YPos := Bt;
end;
end;
function TIWPaintHandlerDsn.DrawButton(const AClient: TRect;
const ABevelWidth: Integer; const AIsDown, AIsFocused: Boolean): TRect;
begin
Result := DrawButtonFace(FControl.Canvas, AClient, ABevelWidth
{$IFNDEF Linux}, bsAutoDetect, False{$ENDIF}, AIsDown, AIsFocused);
end;
{ TIWPaintHandlerComponent }
procedure TIWPaintHandlerComponent.Paint;
begin
DrawOutline;
DrawResource(FControl.ClassName, (FControl.Width - 24) div 2, (FControl.Height - 24) div 2);
end;
initialization
GDefaultPaintHandler := TIWPaintHandlerComponent;
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit frmMain;
interface
uses
Windows, Messages, Classes, Graphics, Forms, ExtCtrls, Controls,
SysUtils, StdCtrls, OpenGL;
type
TfrmGL = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
lblVendor: TLabel;
lblRender: TLabel;
lblVersion: TLabel;
lblExtension: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
DC: HDC;
hrc: HGLRC;
procedure SetDCPixelFormat;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Создание окна}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
DC := GetDC(Handle);
SetDCPixelFormat;
hrc := wglCreateContext(DC);
wglMakeCurrent(DC, hrc);
lblVendor.Caption := StrPas (PChar(glGetString(GL_VENDOR)));
lblRender.Caption := StrPas (PChar(glGetString(GL_RENDERER)));
lblVersion.Caption := StrPas (PChar(glGetString(GL_VERSION)));
lblExtension.Caption := StrPas (PChar(glGetString(GL_EXTENSIONS)));
end;
{=======================================================================
Обработка нажатия клавиши}
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close;
end;
{=======================================================================
Устанавливаем формат пикселей}
procedure TfrmGL.SetDCPixelFormat;
var
nPixelFormat: Integer;
pfd: TPixelFormatDescriptor;
begin
FillChar(pfd, SizeOf(pfd), 0);
nPixelFormat := ChoosePixelFormat(DC, @pfd);
SetPixelFormat(DC, nPixelFormat, @pfd);
end;
{=======================================================================
Конец работы программы}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglMakeCurrent(0, 0);
wglDeleteContext(hrc);
ReleaseDC (Handle, DC);
DeleteDC (DC);
end;
end.
|
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;
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;
end.
|
unit fSeadragon;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, OleCtrls, SHDocVw, StdCtrls, JPEG,
GR32, GR32_Backends;
type
TfrmSeadragon = class(TForm)
WebBrowser1: TWebBrowser;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fTile: TBitmap;
fTileJPEG: TJPEGImage;
fMaxLevel: Integer;
fZoomLevels: array of TBitmap32;
procedure CalcAndFillZoomLevels(const aFilename: String);
function CalcMaxLevel(aWidth, aHeight: Integer): Integer;
procedure SeadragonHandler(aURL: String; var aMIMEType: String; const aPostMIMEType: String; const aPostData: array of byte; aMemoryStream: TCustomMemoryStream); // TProtocolCallback
procedure HandleTile(aPartialURL: String; aMemoryStream: TCustomMemoryStream);
public
{ Public declarations }
end;
var
frmSeadragon: TfrmSeadragon;
implementation
uses
Math, GR32_Resamplers,
uAsyncPlugProto, uStaticHtml;
const
TILE_SIZE = 100;
{$R *.dfm}
function TfrmSeadragon.CalcMaxLevel(aWidth, aHeight: Integer): Integer;
var
iDimension: Integer;
begin
iDimension := Math.Max(aWidth, aHeight);
Result := Math.Ceil(Ln(iDimension) / Ln(2));
end;
procedure TfrmSeadragon.CalcAndFillZoomLevels(const aFilename: String);
var
bmp32: TBitmap32;
nextW, nextH: Double;
i: Integer;
begin
bmp32 := TBitmap32.Create; // Free'd in FormDestroy
bmp32.LoadFromFile(aFilename);
fMaxLevel := CalcMaxLevel(bmp32.Width, bmp32.Height);
SetLength(fZoomLevels, fMaxLevel);
TDraftResampler.Create(bmp32);
fZoomLevels[High(fZoomLevels)] := bmp32;
nextW := bmp32.Width;
nextH := bmp32.Height;
for i := High(fZoomLevels)-1 downto Low(fZoomLevels) do
begin
nextW := nextW / 2;
nextH := nextH / 2;
fZoomLevels[i] := TBitmap32.Create;
fZoomLevels[i].SetSize(Floor(nextW), Floor(nextH));
bmp32.DrawTo(fZoomLevels[i], fZoomLevels[i].BoundsRect);
end;
end;
procedure TfrmSeadragon.FormCreate(Sender: TObject);
begin
fTile := TBitmap.Create;
fTileJPEG := TJPEGImage.Create;
CalcAndFillZoomLevels('earth-map-huge.jpg');
NewHttpProtocolHandler('local', SeadragonHandler);
WebBrowser1.Navigate('local://app');
end;
procedure TfrmSeadragon.FormDestroy(Sender: TObject);
var
i: Integer;
begin
for i := Low(fZoomLevels) to High(fZoomLevels) do
fZoomLevels[i].Free;
SetLength(fZoomLevels, 0);
ReportMemoryLeaksOnShutdown := true;
fTileJPEG.Free;
fTile.Free;
end;
procedure TfrmSeadragon.HandleTile(aPartialURL: String; aMemoryStream: TCustomMemoryStream);
var
idx, level, x, y: Integer;
newWidth, newHeight: Integer;
begin
idx := Pos('/', aPartialURL); level := StrToInt(Copy(aPartialURL, 1, idx-1)); Delete(aPartialURL, 1, idx);
idx := Pos('/', aPartialURL); x := StrToInt(Copy(aPartialURL, 1, idx-1)); Delete(aPartialURL, 1, idx);
y := StrToInt( aPartialURL);
fTile.Height := TILE_SIZE;
fTile.Width := TILE_SIZE;
fTile.Canvas.FillRect(Rect(0, 0, fTile.Width, fTile.Height));
fZoomLevels[level-1].DrawTo(fTile.Canvas.Handle,
Rect(0, 0, TILE_SIZE, TILE_SIZE),
Rect(x * TILE_SIZE, y * TILE_SIZE, (x * TILE_SIZE) + TILE_SIZE, (y * TILE_SIZE) + TILE_SIZE)
);
if ((x + 1) * TILE_SIZE) > fZoomLevels[level-1].Width then
begin
newWidth := Floor(fZoomLevels[level-1].Width - (x * TILE_SIZE));
if newWidth < 1 then
fTile.Width := 1
else
fTile.Width := newWidth;
end;
if ((y + 1) * TILE_SIZE) > fZoomLevels[level-1].Height then
begin
newHeight := Floor(fZoomLevels[level-1].Height - (y * TILE_SIZE));
if newHeight < 1 then
fTile.Height := 1
else
fTile.Height := newHeight;
end;
fTileJPEG.Assign(fTile);
fTileJPEG.Compress;
fTileJPEG.SaveToStream(aMemoryStream);
end;
procedure TfrmSeadragon.SeadragonHandler(aURL: String; var aMIMEType: String; const aPostMIMEType: String; const aPostData: array of byte;
aMemoryStream: TCustomMemoryStream);
procedure WriteOutString(const aStr: String);
var
utf8Out: UTF8String;
begin
utf8Out := UTF8Encode(aStr);
aMemoryStream.WriteBuffer(Pointer(utf8Out)^, Length(utf8Out) * SizeOf(AnsiChar));
end;
procedure WriteOutFile(const aFilename: String);
var
ms: TMemoryStream;
begin
ms := TMemoryStream.Create;
try
ms.LoadFromFile(aFilename);
ms.SaveToStream(aMemoryStream);
finally
ms.Free;
end;
end;
begin
if SameText(aURL, '//app/') then
begin
WriteOutString(
StringReplace(uStaticHtml.MAIN_PAGE, '%W_H%', Format('%d, %d',[fZoomLevels[fMaxlevel-1].Width, fZoomLevels[fMaxlevel-1].Height]), [])
)
end
else if SameText(aURL, '//app/seadragon-min.js') then
begin
aMIMEType := 'application/javascript';
WriteOutFile('seadragon-min.js')
end
else if SameText(Copy(aURL,1,Length('//app/imgs/')), '//app/imgs/') then
begin
// these are the images for Seadragon the "buttons" "+" "-" "home" "full screen"
aMIMEType := 'application/png';
WriteOutFile(Copy(aURL, 7));
end
else if SameText(Copy(aURL,1,Length('//app/getTile/')), '//app/getTile/') then
begin
aMIMEType := 'image/jpeg';
HandleTile(Copy(aURL, Length('//app/getTile/')+1), aMemoryStream);
end
else
begin
WriteOutString('URL: ' + aURL);
end;
end;
end.
|
unit uLogic;
{$MODE Delphi}
interface
uses uProcess;
// global functions
function logic_CreateProcessFromString(s :string) : process;
implementation
function logic_CreateProcessFromString(s :string) : process;
var
id : integer;
sId : string; // string of id
e : integer; // error
begin
{ writeln(s); }
result := process.Create;
// numeric ID is the first few characters
sID := '$' + copy(s, 1, 8);
val(sID, id, e); // convert from str to int
if e<> 0 then
Exit(nil);
result.ID:=id;
// the name is the rest
result.Name:=copy(s,10,length(s)-1);
end;
end.
|
{-----------------------------------------------------------------------------
The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.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 Original Code is: JvGammaPanel.PAS, released on 2001-02-28.
The Initial Developer of the Original Code is Sébastien Buysse [sbuysse att buypin dott com]
Portions created by Sébastien Buysse are Copyright (C) 2001 Sébastien Buysse.
All Rights Reserved.
Contributor(s): Michael Beck [mbeck att bigfoot dott com].
You may retrieve the latest version of this file at the Project JEDI's JVCL home page,
located at http://jvcl.delphi-jedi.org
Modifications:
2/11/2000 Added the Align and AutoSize property (Request of Brad T.)
2004/01/06 VisualCLX compatibilty
Known Issues:
-----------------------------------------------------------------------------}
// $Id$
unit JvGammaPanel;
{$MODE OBJFPC}{$H+}
interface
uses
SysUtils, Classes, Graphics, Controls, Dialogs, ExtCtrls, StdCtrls,
JvTypes;
type
TJvGammaPanel = class(TWinControl)
private
FPanel1: TPanel;
FPanel2: TPanel;
FPanel3: TPanel;
FPanel4: TPanel;
FGamma: TImage;
FForegroundColorImg: TShape;
FBackgroundColorImg: TShape;
FChosen: TShape;
FXLabel: TLabel;
FRLabel: TLabel;
FGLabel: TLabel;
FBLabel: TLabel;
FLastColor: TColor;
FOnChangeColor: TJvChangeColorEvent;
procedure BgColorClick(Sender: TObject);
procedure ChangeColor(Sender: TObject; Button: TMouseButton;
{%H-}Shift: TShiftState; {%H-}X, {%H-}Y: Integer);
procedure ColorSeek(Sender: TObject; {%H-}Shift: TShiftState; X, Y: Integer);
procedure Exchange(Sender: TObject);
procedure FgColorClick(Sender: TObject);
function GetBackgroundColor: TColor;
function GetForegroundColor: TColor;
function IsHeightStored: Boolean;
function IsWidthStored: Boolean;
procedure SetBackgroundColor(const AValue: TColor);
procedure SetForegroundColor(const AValue: TColor);
protected
procedure DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy;
const AXProportion, AYProportion: Double); override;
procedure DoChangeColor(AForegroundColor, ABackgroundColor: TColor); virtual;
procedure Resize; override;
public
constructor Create(AOwner: TComponent); override;
published
property Align;
property Anchors;
property BorderSpacing;
property Height stored IsHeightStored;
property Width stored IsWidthStored;
property ForegroundColor: TColor read GetForegroundColor write SetForegroundColor default clBlack;
property BackgroundColor: TColor read GetBackgroundColor write SetBackgroundColor default clWhite;
property OnChangeColor: TJvChangeColorEvent read FOnChangeColor write FOnChangeColor;
end;
implementation
uses
LCLIntf,
JvResources;
{$R ../../resource/jvgammapanel.res}
const
DEFAULT_WIDTH = 65;
DEFAULT_HEIGHT = 250;
MARGIN_1 = 5;
MARGIN_2 = 2;
IMG_SIZE = 30;
constructor TJvGammaPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := DEFAULT_WIDTH; // Scaling of outer dimensions is done automatically
Height := DEFAULT_HEIGHT;
FPanel1 := TPanel.Create(Self);
with FPanel1 do
begin
Parent := Self;
Align := alClient;
BevelInner := bvLowered;
BevelOuter := bvRaised;
end;
FPanel2 := TPanel.Create(FPanel1);
with FPanel2 do
begin
Parent := FPanel1;
Align := alClient;
BorderSpacing.Around := Scale96ToFont(MARGIN_1); // Scale inner dimensions manually
BevelInner := bvLowered;
BevelOuter := bvRaised;
end;
FPanel3 := TPanel.Create(FPanel1);
with FPanel3 do
begin
Parent := FPanel1;
Align := alBottom;
BorderSpacing.Left := Scale96ToFont(MARGIN_1);
BorderSpacing.Right := Scale96ToFont(MARGIN_1);
Height := Scale96ToFont(3*IMG_SIZE div 2 + 2 * MARGIN_2);
BevelInner := bvLowered;
BevelOuter := bvRaised;
end;
FPanel4 := TPanel.Create(FPanel1);
with FPanel4 do
begin
Parent := FPanel1;
Align := alBottom;
BorderSpacing.Around := Scale96ToFont(MARGIN_1);
BevelInner := bvLowered;
BevelOuter := bvRaised;
AutoSize := true;
Top := self.Height; // Force to be at very bottom
end;
FGamma := TImage.Create(FPanel2);
with FGamma do
begin
Parent := FPanel2;
Align := alClient;
Stretch := true;
OnMouseDown := @ChangeColor;
OnMouseMove := @ColorSeek;
Align := alClient;
Picture.Bitmap.LoadFromResourceName(HInstance, 'JvGammaPanelCOLORS');
Cursor := crCross;
end;
FBackgroundColorImg := TShape.Create(FPanel3);
with FBackgroundColorImg do
begin
Parent := FPanel3;
Height := Scale96ToFont(IMG_SIZE);
Width := Height;
Top := Scale96ToFont(MARGIN_2) + Height div 2;
Left := Scale96ToFont(MARGIN_2) + Width div 2;
Brush.Color := clBlack;
Hint := RsHintBg;
ShowHint := True;
OnClick := @BgColorClick;
end;
FForegroundColorImg := TShape.Create(FPanel3);
with FForegroundColorImg do
begin
Parent := FPanel3;
Height := Scale96ToFont(IMG_SIZE);
Width := Height;
Left := Scale96ToFont(MARGIN_2);
Top := Scale96ToFont(MARGIN_2);
Brush.Color := clWhite;
Hint := RsHintFg;
ShowHint := True;
OnClick := @FgColorClick;
end;
FXLabel := TLabel.Create(FPanel3);
with FXLabel do
begin
Parent := FPanel3;
BorderSpacing.Left := Scale96ToFont(MARGIN_1);
BorderSpacing.Bottom := 0;
Alignment := taCenter;
AutoSize := True;
Caption := RsXCaption;
Hint := RsLabelHint;
OnClick := @Exchange;
ShowHint := True;
end;
FRLabel := TLabel.Create(FPanel4);
with FRLabel do
begin
Parent := FPanel4;
Align := alTop;
BorderSpacing.Left := Scale96ToFont(2);
Caption := RsDefaultR;
Transparent := True;
end;
FGLabel := TLabel.Create(FPanel4);
with FGLabel do
begin
Parent := FPanel4;
Align := alTop;
Top := FRLabel.Top + FRLabel.Height;
BorderSpacing.Left := FRLabel.BorderSpacing.Left;
Caption := RsDefaultG;
Transparent := True;
end;
FBLabel := TLabel.Create(FPanel4);
with FBLabel do
begin
Parent := FPanel4;
Align := alTop;
Top := FGLabel.Top + FGLabel.Height;
BorderSpacing.Left := FRLabel.BorderSpacing.Left;
Caption := RsDefaultB;
Transparent := True;
end;
FChosen := TShape.Create(FPanel4);
with FChosen do
begin
Parent := FPanel4;
Align := alTop;
Top := FBLabel.Top + FBLabel.Height;
Height := FBLabel.Height * 2;
BorderSpacing.Around := Scale96ToFont(MARGIN_1);
Brush.Color := clBlack;
end;
end;
procedure TJvGammaPanel.BgColorClick(Sender: TObject);
begin
with TColorDialog.Create(Self) do
begin
if Execute then
SetBackgroundColor(Color);
Free;
end;
end;
procedure TJvGammaPanel.ChangeColor(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Button = mbLeft then
begin
FForegroundColorImg.Brush.Color := FLastColor;
DoChangeColor(FLastColor, FBackgroundColorImg.Brush.Color);
end else
if Button = mbRight then
begin
FBackgroundColorImg.Brush.Color := FLastColor;
DoChangeColor(FForegroundColorImg.Brush.Color, FLastColor);
end;
end;
procedure TJvGammaPanel.ColorSeek(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
col: TColor;
xbmp, ybmp: Integer;
begin
if not PtInRect(Bounds(0, 0, FGamma.Width, FGamma.Height), Point(X,Y)) then
Exit;
xbmp := round(X * FGamma.Picture.Bitmap.Width / FGamma.Width);
ybmp := round(Y * FGamma.Picture.Bitmap.Height / FGamma.Height);
col := FGamma.Picture.Bitmap.Canvas.Pixels[xbmp, ybmp];
FLastColor := col;
FRLabel.Caption := Format(RsRedFormat, [GetRValue(col)]);
FGLabel.Caption := Format(RsGreenFormat, [GetGValue(col)]);
FBLabel.Caption := Format(RsBlueFormat, [GetBValue(col)]);
FChosen.Brush.Color := col;
end;
procedure TJvGammaPanel.DoAutoAdjustLayout(const AMode: TLayoutAdjustmentPolicy;
const AXProportion, AYProportion: Double);
begin
inherited;
FPanel2.BorderSpacing.Around := round(MARGIN_1 * AXProportion);
FPanel3.BorderSpacing.Left := round(MARGIN_1 * AXProportion);
FPanel3.BorderSpacing.Right := round(MARGIN_1 * AXProportion);
FPanel3.Height := round((IMG_SIZE * 3 div 2 + 2 * MARGIN_2) * AYProportion);
FPanel4.BorderSpacing.Around := round(MARGIN_1 * AXProportion);
FBackgroundColorImg.Height := round(IMG_SIZE * AYProportion);
FBackgroundColorImg.Width := round(IMG_SIZE * AXProportion);
FBackgroundColorImg.Top := round((MARGIN_2 + IMG_SIZE div 2) * AYProportion);
FBackgroundColorImg.Left := round((MARGIN_2 + IMG_SIZE div 2) * AXProportion);
FForegroundColorImg.Height := round(IMG_SIZE * AYProportion);
FBackgroundColorImg.Width := round(IMG_SIZE * AXProportion);
FBackgroundColorImg.Left := round(MARGIN_2 * AXProportion);
FBackgroundColorImg.Top := round(MARGIN_2 * AYProportion);
FXLabel.BorderSpacing.Left := round(MARGIN_1 * AXProportion);
FRLabel.BorderSpacing.Left := round(MARGIN_2 * AXProportion);
FGLabel.BorderSpacing.Left := round(MARGIN_2 * AXProportion);
FBLabel.BorderSpacing.Left := round(MARGIN_2 * AXProportion);
FChosen.BorderSpacing.Left := round(MARGIN_1 * AXProportion);
end;
procedure TJvGammaPanel.DoChangeColor(AForegroundColor, ABackgroundColor: TColor);
begin
if Assigned(FOnChangeColor) then
FOnChangeColor(Self, AForegroundColor, ABackgroundColor);
end;
procedure TJvGammaPanel.Exchange(Sender: TObject);
var
col: TColor;
savedOnChangeColor: TJvChangeColorEvent;
begin
savedOnChangeColor := FOnChangeColor;
FOnChangeColor := nil;
// exchange colors
col := GetForegroundColor;
SetForegroundColor(GetBackgroundColor);
SetBackgroundColor(col);
FOnChangeColor := savedOnChangeColor;
DoChangeColor(GetForegroundColor, GetBackgroundColor);
end;
procedure TJvGammaPanel.FgColorClick(Sender: TObject);
begin
with TColorDialog.Create(Self) do
begin
if Execute then
SetForegroundColor(Color);
Free;
end;
end;
function TJvGammaPanel.GetBackgroundColor: TColor;
begin
Result := FBackgroundColorImg.Brush.Color;
end;
function TJvGammaPanel.GetForegroundColor: TColor;
begin
Result := FForegroundColorImg.Brush.Color;
end;
function TJvGammaPanel.IsHeightStored: Boolean;
begin
Result := Height <> Scale96ToFont(DEFAULT_HEIGHT);
end;
function TJvGammaPanel.IsWidthStored: Boolean;
begin
Result := Width <> Scale96ToFont(DEFAULT_WIDTH);
end;
procedure TJvGammaPanel.Resize;
var
imgSize: Integer;
p: Integer;
m: Integer;
begin
inherited;
if FPanel3 = nil then
exit;
m := Scale96ToFont(MARGIN_1);
if FPanel3.Width > FPanel3.Height then begin
imgSize := (FPanel3.ClientHeight - 2*m) div 3 * 2;
p := (FPanel3.ClientWidth - imgSize*3 div 2) div 2;
FBackgroundColorImg.SetBounds(
p + imgSize*3 div 2 - imgSize, FPanel3.ClientHeight - imgSize - m, imgSize, imgSize);
FForegroundColorImg.SetBounds(p, m, imgSize, imgSize);
FXLabel.Left := FForegroundColorImg.Left;
FXLabel.AnchorSideBottom.Control := FPanel3;
FXLabel.AnchorSideBottom.Side := asrBottom;
FXLabel.Anchors := [akLeft, akBottom];
FXLabel.BorderSpacing.Bottom := 0;
end else begin
imgSize := (FPanel3.ClientWidth - 2*m) div 3 * 2;
p := (FPanel3.ClientHeight - imgSize*3 div 2) div 2;
FBackgroundColorImg.SetBounds(
FPanel3.ClientWidth - imgSize - m, p + imgSize*3 div 2 - imgSize, imgSize, imgSize);
FForegroundColorImg.SetBounds(
m, p, imgSize, imgSize);
end;
end;
procedure TJvGammaPanel.SetBackgroundColor(const AValue: TColor);
begin
if GetBackgroundColor = AValue then
exit;
FBackgroundColorImg.Brush.Color := AValue;
DoChangeColor(GetForegroundColor, AValue);
end;
procedure TJvGammaPanel.SetForegroundColor(const AValue: TColor);
begin
if GetForegroundColor = AValue then
exit;
FForegroundColorImg.Brush.Color := AValue;
DoChangeColor(AValue, GetBackgroundColor);
end;
end.
|
{*********************************************}
{ TeeBI Software Library }
{ TDataItem Kind Conversion }
{ Copyright (c) 2015-2017 by Steema Software }
{ All Rights Reserved }
{*********************************************}
unit BI.Convert;
interface
uses
BI.DataItem;
{
Use TDataKindConvert.Convert method to change the "Kind" property of a
TDataItem object.
All data is preserved and checked for compatibility with the new Kind.
All "Missing" data values are also preserved (not converted).
Note:
TDataItem AsTable (multiple fields) cannot be converted.
All Items must be converted individually.
}
type
TDataKindConvert=record
public
class function CanConvert(const AData:TDataItem; const AKind:TDataKind):Boolean; static;
class function Convert(const AData:TDataItem; const AKind:TDataKind):Boolean; static;
end;
implementation
|
unit Scanner;
interface
uses CRT;
const
ALNG = 30;
eof = #26;
tab = #009;
LineFeed = #010;
space = #032;
car_return = #013;
type
Alfa = string[ALNG];
tokens = (
t_int, t_add, t_sub, t_mul, t_rdiv, t_double_mul,
t_assign { ':=' },
t_lbrack { '[' }, t_rbrack { ']' },
t_lparent { '(' }, t_rparent { ')' },
t_id, t_else, t_if, t_then
);
const
num_reserved_word = 3;
KeyStr : array [1..num_reserved_word] of Alfa = (
'else', 'if', 'then'
);
KeySym : array [1..num_reserved_word] of tokens = (
t_else, t_if, t_then
);
var
FIn : string[12];
FInput : text;
LookAhead : boolean;
Enum : boolean;
Ch : char;
token : tokens;
Id : Alfa;
Inum : longint;
LineNumber : integer;
procedure initialize;
procedure scan;
procedure terminate;
implementation
procedure Initialize;
begin
if (ParamCount < 1)
then repeat
Write(' File Sumber (.pas) ');
Readln(FIn);
until (Length(FIn) <> 0 )
else FIn := ParamStr(1);
if (Pos('.', FIn) = 0 )
then FIn := FIn + '.pas';
{$I-}
Assign(FInput, FIn);
Reset(FInput);
{$I+}
if (IOResult <> 0 )
then begin
Writeln('Tidak bisa mengkases File : "', FIn, "'');
Halt;
end;
FIn ;= Copy(FIn, 1, Pos('.',FIn) -1 ) + '.out';
LookAhead := FALSE;
Enum := FALSE;
Ch := ' ';
Line Number := 1;
end;
procedure Terminate;
begin
close(FInput);
end;
procedure GetCh;
begin
read(FInput, Ch);
end;
procedure error_report(id: byte);
begin
case id of
1 : writeln(' Error -> unknown character "', Ch, ''' Line : ', LineNumber);
2 : writeln(' Error -> comment not limited Line', LineNumber);
end;
end;
procedure Scan;
var
Idx : integer;
e : integer;
begin
if (not LookAhead)
then GetCh;
LookAhead := FALSE;
repeat
case Ch of
tab, LineFeed, space : GetCh;
car_return :
begin
GetCh;
inc (LineNumber);
end;
eof :
Exit;
'A'..'Z','a'..'z' :
begin
Id := '';
repeat
Id := Id + Ch;
GetCh;
until (not (Ch in['0'..'9', 'A'..'Z', 'a'..'z']));
LookAhead := TRUE;
Idx := 0;
repeat
Idx := Idx + 1;
until ((Idx = num_reserved_word) or (Id = KeyStr[Idx]));
if (Id = KeyStr[Idx])
then token := KeySym[Idx]
else token := t_id;
Exit;
end;
'0'..'9' :
begin
Inum := 0;
token := t_int;
repeat
Inum := Inum * 10 + (ord(Ch) - ord('0'));
until (not (Ch in['0'..'9']));
LookAhead := TRUE;
Exit;
end;
'+' :
begin
token := t_add;
exit;
end;
'-' :
begin
token := t_sub;
exit;
end;
'*' :
begin
getch;
if(ch = '*')
then token := t_double_mul
else begin
token := t_mul;
lookahead := true;
end;
exit;
'/' :
begin
token := t_rdiv;
exit;
end;
')' :
begin
token := t_rparent;
exit;
end;
'[' :
begin
token := t_lbrack;
exit;
end;
']' :
begin
token := t_rbrack;
exit;
end;
':' :
begin
GetCh;
if ( Ch = '=')
then begin
token
:=t_assign;
end
else begin
Writeln('Error -> Unknown character'':'' line : ', LineNumber);
lookahead := true;
end;
exit;
end;
'(' :
begin
GetCh;
if(Ch <> '*')
then begin
token := t_lparent;
LookAhead :=TRUE;
Exit;
end
else begin
GetCh;
if (Ch = eof)
then begin
error_report(2);
Exit;
end;
repeat
while (Ch <> '*')
do begin
GetCh;
if (Ch = eof) then
begin
error_report(2);
exit;
end;
end;
Getch;
if(Ch = eof)
then begin
error_report(2);
exit;
end;
until(Ch = ')');
GetCh;
end;
end;
else
begin
error_report(1);
GetCh;
end;
end;
until FALSE;
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.Grids, Vcl.DBGrids, Vcl.StdCtrls,
Data.DB, Datasnap.DBClient,System.Generics.Collections, UTimeFutebol,
Vcl.Menus, UCampeonato;
type
TfrmCadastroTimeFutebol = class(TForm)
GroupBox1: TGroupBox;
GroupBox2: TGroupBox;
DBGrid1: TDBGrid;
DBGrid2: TDBGrid;
btSalvar: TButton;
btnExcluir: TButton;
edtNome: TEdit;
edtQtdeTorcida: TEdit;
Label1: TLabel;
Label2: TLabel;
DS_TITULOS: TDataSource;
CDS_TITULOS: TClientDataSet;
DS_FUTEBOL: TDataSource;
CDS_FUTEBOL: TClientDataSet;
CDS_TITULOSID: TIntegerField;
CDS_TITULOSNome: TStringField;
CDS_FUTEBOLID: TIntegerField;
CDS_FUTEBOLNome: TStringField;
CDS_FUTEBOLQuantidade_Torcida: TIntegerField;
btnQtdeTimesCadastrados: TButton;
btnQtdeCampeonatosCadastrados: TButton;
btnQtdeCampCadastradosTime: TButton;
CDS_TITULOSAno: TSmallintField;
MainMenu: TMainMenu;
Cadastro1: TMenuItem;
Campeonatos1: TMenuItem;
btnCadastrarTitulos: TButton;
cbxIncluirTitulos: TComboBox;
btnNovo: TButton;
btnCancelar: TButton;
btnAlterar: TButton;
btnExcluirTitulo: TButton;
procedure FormCreate(Sender: TObject);
procedure btSalvarClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure btnQtdeTimesCadastradosClick(Sender: TObject);
procedure DBGrid1CellClick(Column: TColumn);
procedure Campeonatos1Click(Sender: TObject);
procedure btnCadastrarTitulosClick(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnQtdeCampeonatosCadastradosClick(Sender: TObject);
procedure btnQtdeCampCadastradosTimeClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnExcluirTituloClick(Sender: TObject);
private
valorSeqencial : Integer;
listaCampeonatos : TObjectList<TCampeonatos>;
statusBotaoAlterar : boolean;
procedure ModoBotaoInsercao();
procedure ModoBotaoNaoInsercao();
{ Private declarations }
public
ListaTimesCadastrados : TObjectList<TTimeFutebol>;
{ Public declarations }
end;
var
frmCadastroTimeFutebol: TfrmCadastroTimeFutebol;
implementation
{$R *.dfm}
uses UFrmCampeonatos, UListaTimes;
procedure TfrmCadastroTimeFutebol.btnAlterarClick(Sender: TObject);
begin
ModoBotaoInsercao;
statusBotaoAlterar:= true;
end;
procedure TfrmCadastroTimeFutebol.btnCadastrarTitulosClick(Sender: TObject);
var
i,a : Integer;
begin
if cbxIncluirTitulos.ItemIndex = -1 then
begin
MessageDlg('Título não selecionado. Verifique!',mtInformation,[mbOK],0);
cbxIncluirTitulos.SetFocus;
Abort;
end;
CDS_TITULOS.First;
while not CDS_TITULOS.Eof do
begin
if listaCampeonatos.Items[cbxIncluirTitulos.ItemIndex].id = CDS_TITULOSID.Value then
begin
MessageDlg('Título já foi inserido',mtInformation,[mbOK],0);
cbxIncluirTitulos.SetFocus;
Abort;
end;
CDS_TITULOS.Next;
end;
for i := 0 to ListaTimesCadastrados.Count-1 do
begin
for a := 0 to ListaTimesCadastrados.Items[i].titulos.Count-1 do
begin
if ListaTimesCadastrados.Items[i].titulos.Items[a].id = listaCampeonatos.Items[cbxIncluirTitulos.ItemIndex].id then
begin
MessageDlg('Título já inserido para o time de futebol: '+ListaTimesCadastrados.Items[i].nome,mtInformation,[mbOK],0);
cbxIncluirTitulos.SetFocus;
Abort;
end;
end;
end;
CDS_TITULOS.Append;
CDS_TITULOS.FieldByName('ID').AsInteger:= listaCampeonatos.Items[cbxIncluirTitulos.ItemIndex].id;
CDS_TITULOS.FieldByName('nome').AsString:= listaCampeonatos.Items[cbxIncluirTitulos.ItemIndex].nome;
CDS_TITULOS.FieldByName('ano').AsInteger:= listaCampeonatos.Items[cbxIncluirTitulos.ItemIndex].ano;
CDS_TITULOS.Post;
end;
procedure TfrmCadastroTimeFutebol.btnCancelarClick(Sender: TObject);
begin
ModoBotaoNaoInsercao;
CDS_TITULOS.Close;
CDS_TITULOS.CreateDataSet;
statusBotaoAlterar:= false;
end;
procedure TfrmCadastroTimeFutebol.btnExcluirClick(Sender: TObject);
var
i : Integer;
begin
statusBotaoAlterar:= false;
if CDS_FUTEBOLID.Value = 0 then
begin
ShowMessage('Selecione um time para ser excluído');
end
else
begin
for i := 0 to ListaTimesCadastrados.Count-1 do
begin
if ListaTimesCadastrados.Items[i].id = CDS_FUTEBOLID.Value then
begin
ListaTimesCadastrados.Delete(i);
Break;
end;
end;
CDS_FUTEBOL.Delete;
CDS_TITULOS.Close;
CDS_TITULOS.CreateDataSet;
ModoBotaoNaoInsercao;
end;
end;
procedure TfrmCadastroTimeFutebol.btnExcluirTituloClick(Sender: TObject);
begin
if CDS_TITULOSID.Value > 0 then
begin
if MessageDlg('Tem certeza que deseja excluir o título selecionado?',mtConfirmation,[mbYes,mbNo],0)=mrYes then
begin
CDS_TITULOS.Delete;
Abort;
end
else
begin
btnExcluirTitulo.SetFocus;
Abort;
end;
end
else
MessageDlg('Nenhum registro a ser excluído. Verifique!',mtInformation,[mbOK],0);
btnExcluirTitulo.SetFocus;
Abort;
end;
procedure TfrmCadastroTimeFutebol.btnNovoClick(Sender: TObject);
begin
CDS_TITULOS.Close;
CDS_TITULOS.CreateDataSet;
ModoBotaoInsercao;
edtNome.Text:='';
edtQtdeTorcida.Text:='';
statusBotaoAlterar:= False;
end;
procedure TfrmCadastroTimeFutebol.btnQtdeCampCadastradosTimeClick(Sender: TObject);
var
i : Integer;
begin
if CDS_FUTEBOLID.Value > 0 then
begin
for I := 0 to ListaTimesCadastrados.Count-1 do
begin
if (CDS_FUTEBOLID.Value = ListaTimesCadastrados.Items[i].id) then
ShowMessage('O time de futebol '+ ListaTimesCadastrados.Items[i].nome + ' possui '+ IntToStr(ListaTimesCadastrados.Items[i].titulos.Count)+' títulos.');
end;
end
else
MessageDlg('Favor selecionar um time de futebol para a realização da busca de quantidade de títulos',mtInformation,[mbOK],0);
end;
procedure TfrmCadastroTimeFutebol.btnQtdeCampeonatosCadastradosClick(Sender: TObject);
begin
MessageDlg('Existem '+ IntToStr(frmCadastroCampeonatos.listaCampeonatos.Count)+' campeonatos cadastrados.',mtInformation,[mbOK],0);
end;
procedure TfrmCadastroTimeFutebol.btnQtdeTimesCadastradosClick(Sender: TObject);
begin
MessageDlg('Existem '+ IntToStr(ListaTimesCadastrados.Count) + ' times de futebol cadastrados.',mtInformation,[mbOK],0);
end;
procedure TfrmCadastroTimeFutebol.btSalvarClick(Sender: TObject);
var
lTimeFutebol : TTimeFutebol;
lCampeonato : TCampeonatos;
lListaCampeonatos : TObjectList<TCampeonatos>;
i,ii,j,lValorSelecionado : Integer;
begin
if edtNome.Text = '' then
begin
MessageDlg('Nome não informado. Verifique!',mtInformation,[mbOK],0);
edtNome.SetFocus;
Abort;
end
else
begin
lTimeFutebol := TTimeFutebol.Create;
valorSeqencial:= valorSeqencial+1;
lTimeFutebol.id:=valorSeqencial;
lTimeFutebol.nome:= edtNome.Text;
if edtQtdeTorcida.Text = '' then
lTimeFutebol.quantidadeTorcida:= 0
else
lTimeFutebol.quantidadeTorcida:= StrToInt(edtQtdeTorcida.Text);
lListaCampeonatos := TObjectList<TCampeonatos>.Create;
if (CDS_TITULOS.IsEmpty) and (not CDS_FUTEBOL.Eof)then
begin
if MessageDlg('O time que está sendo cadastrado não possui títulos.'+#13+
'Deseja copiar os títulos de algum time que já foi cadastrado?', mtConfirmation,[mbYes,mbNo],0) = mrYes then
begin
frmListaTimes.ShowModal;
for i := 0 to ListaTimesCadastrados.Count-1 do
begin
if ListaTimesCadastrados.Items[i].id = frmListaTimes.CDSID.Value then
for ii := 0 to ListaTimesCadastrados.Items[i].titulos.Count-1 do
begin
CDS_TITULOS.Append;
CDS_TITULOS.FieldByName('Id').AsInteger:= ListaTimesCadastrados.Items[i].titulos.Items[ii].id;
CDS_TITULOS.FieldByName('nome').AsString:= ListaTimesCadastrados.Items[i].titulos.Items[ii].nome;
CDS_TITULOS.FieldByName('ano').AsInteger:= ListaTimesCadastrados.Items[i].titulos.Items[ii].ano;
CDS_TITULOS.Post;
end;
end;
end;
end;
end;
CDS_TITULOS.First;
while not CDS_TITULOS.Eof do
begin
lCampeonato := TCampeonatos.Create;
lCampeonato.id := CDS_TITULOS.FieldByName('id').AsInteger;
lCampeonato.nome :=CDS_TITULOS.FieldByName('nome').AsString;
lCampeonato.ano := CDS_TITULOS.FieldByName('ano').AsInteger;
lListaCampeonatos.Add(lCampeonato);
CDS_TITULOS.Next;
end;
lTimeFutebol.titulos:= lListaCampeonatos;
if not statusBotaoAlterar then
begin
CDS_FUTEBOL.Append;
CDS_FUTEBOL.FieldByName('id').AsInteger:= lTimeFutebol.id;
end else
CDS_FUTEBOL.Edit;
CDS_FUTEBOL.FieldByName('nome').AsString := lTimeFutebol.nome;
CDS_FUTEBOL.FieldByName('Quantidade_Torcida').AsFloat:= lTimeFutebol.quantidadeTorcida;
CDS_FUTEBOL.Post;
CDS_TITULOS.Close;
CDS_TITULOS.CreateDataSet;
lValorSelecionado := CDS_FUTEBOLID.Value;
CDS_FUTEBOL.First;
ModoBotaoNaoInsercao;
if not statusBotaoAlterar then
begin
ListaTimesCadastrados.Add(lTimeFutebol);
end else
begin
for i := 0 to ListaTimesCadastrados.Count-1 do
begin
if lValorSelecionado = ListaTimesCadastrados.Items[i].id then
begin
lTimeFutebol.id := ListaTimesCadastrados.Items[i].id;
ListaTimesCadastrados.Delete(i);
break;
end;
end;
ListaTimesCadastrados.Add(lTimeFutebol);
end;
statusBotaoAlterar:= false;
btnNovo.SetFocus;
end;
procedure TfrmCadastroTimeFutebol.Campeonatos1Click(Sender: TObject);
var
i : Integer;
lCampeonato : TCampeonatos;
begin
frmcadastroCampeonatos.ShowModal;
listaCampeonatos.Clear;
for i := 0 to frmCadastroCampeonatos.listaCampeonatos.Count-1 do
begin
lCampeonato:= TCampeonatos.Create;
lCampeonato.copyFromObject(frmCadastroCampeonatos.listaCampeonatos.Items[i]);
listaCampeonatos.Add(lCampeonato);
end;
cbxIncluirTitulos.Clear;
for i := 0 to listaCampeonatos.Count-1 do
begin
cbxIncluirTitulos.Items.AddObject(listaCampeonatos.Items[i].nome +'-' +IntToStr(listaCampeonatos.Items[i].ano),
TObject(listaCampeonatos));
end;
end;
procedure TfrmCadastroTimeFutebol.DBGrid1CellClick(Column: TColumn);
var
i,j :Integer;
lista : TObjectList<TCampeonatos>;
begin
ModoBotaoNaoInsercao;
edtNome.Text:= CDS_FUTEBOLNome.Value;
edtQtdeTorcida.Text := IntToStr(CDS_FUTEBOLQuantidade_Torcida.Value);
CDS_TITULOS.Close;
CDS_TITULOS.CreateDataSet;
lista:= TObjectList<TCampeonatos>.Create;
for I := 0 to ListaTimesCadastrados.Count-1 do
begin
if(CDS_FUTEBOLID.Value = ListaTimesCadastrados.Items[i].id)then
begin
CDS_TITULOS.Close;
CDS_TITULOS.CreateDataSet;
lista:= ListaTimesCadastrados.Items[i].titulos;
for j := 0 to lista.Count-1 do
begin
CDS_TITULOS.Append;
CDS_TITULOS.FieldByName('id').AsInteger:= lista.Items[j].id;
CDS_TITULOS.FieldByName('nome').AsString:=lista.Items[j].nome;
CDS_TITULOS.FieldByName('ano').AsInteger:= lista.Items[j].ano;
CDS_TITULOS.Post;
end;
end;
end;
end;
procedure TfrmCadastroTimeFutebol.FormCreate(Sender: TObject);
begin
CDS_TITULOS.CreateDataSet;
CDS_FUTEBOL.CreateDataSet;
ListaTimesCadastrados := TObjectList<TTimeFutebol>.Create;
listaCampeonatos:= TObjectList<TCampeonatos>.Create;
ModoBotaoNaoInsercao;
end;
procedure TfrmCadastroTimeFutebol.FormDestroy(Sender: TObject);
begin
FreeAndNil(ListaTimesCadastrados);
FreeAndNil(listaCampeonatos);
end;
procedure TfrmCadastroTimeFutebol.ModoBotaoInsercao;
begin
edtNome.Enabled:= true;
edtQtdeTorcida.Enabled:=True;
btnNovo.Enabled:=false;
btSalvar.Enabled:=True;
btnAlterar.Enabled:=false;
btnExcluir.Enabled:=false;
btnCancelar.Enabled:= True;
btnCadastrarTitulos.Enabled:=True;
btnExcluirTitulo.Enabled:=true;
cbxIncluirTitulos.ItemIndex:= -1;
cbxIncluirTitulos.Enabled:=true;
edtNome.SetFocus;
end;
procedure TfrmCadastroTimeFutebol.ModoBotaoNaoInsercao;
begin
edtNome.Enabled:= false;
edtQtdeTorcida.Enabled:=false;
btnNovo.Enabled:=true;
btSalvar.Enabled:=false;
btnAlterar.Enabled:=true;
btnExcluir.Enabled:=true;
btnCancelar.Enabled:=false;
btnExcluirTitulo.Enabled:=false;
cbxIncluirTitulos.ItemIndex:= -1;
btnCadastrarTitulos.Enabled:=False;
cbxIncluirTitulos.Enabled:=false;
end;
end.
|
unit UnFood;
interface
uses
Windows, Variants, Classes, DB,
{ Fluente }
Util, DataUtil, Settings, UnFoodModel, UnComandaModel, UnProduto, UnWidgets,
Controls, Forms, ExtCtrls;
type
TFoodApp = class(TForm)
ScrollBox: TScrollBox;
pnlCommand: TPanel;
procedure FormCreate(Sender: TObject);
procedure ScrollBoxResize(Sender: TObject);
private
FComandaModel: TComandaModel;
FComandas: TList;
FComandaSelecionada: TComanda;
FDataUtil: TDataUtil;
FSettings: TSettings;
FUtil: TUtil;
FModel: TFoodModel;
procedure exibirComanda;
protected
procedure CarregarComandas;
function GetComandaModel: TComandaModel;
function GetComandas: TDictionary<string, TComanda>;
public
function InitInstance(Sender: TObject): TFoodApp;
published
procedure comandaClick(Sender: TObject);
procedure AfterComandaEdit(Sender: TObject);
end;
var
FoodApp: TFoodApp;
implementation
{$R *.dfm}
uses Data.SqlExpr, Vcl.StdCtrls,
{ Fluente }
UnModel, UnAbrirComandaView, UnItemsView;
procedure TFoodApp.AfterComandaEdit(Sender: TObject);
var
_comanda: TComanda;
_comandaModel: TComandaModel;
_dataSet: TDataSet;
begin
_comandaModel := TComandaModel(Sender);
_dataSet := _comandaModel.cds_coma;
if Self.GetComandas().TryGetValue(
_comandaModel.cds_coma.FieldByName('coma_oid').AsString, _comanda) then
begin
// atualiza total de comanda existente
_comanda.Total := _comandaModel.cds_coma.FieldByName('coma_total').AsFloat;
end
else
begin
// carrega nova comanda
Self.FComandaSelecionada.Identificacao :=
_dataSet.FieldByName('coma_oid').AsString;
if _dataSet.FieldByName('cl_oid').AsString <> '' then
Self.FComandaSelecionada.Descricao :=
_dataSet.FieldByName('cl_cod').AsString
else
Self.FComandaSelecionada.Descricao :=
_dataSet.FieldByName('coma_mesa').AsString;
Self.FComandaSelecionada.Total :=
_dataSet.FieldByName('coma_total').AsFloat;
end;
end;
procedure TFoodApp.exibirComanda;
var
_itemView: TItemsView;
begin
_itemView := TItemsView.Create(Self.FComandaModel, Self.AfterComandaEdit);
try
_itemView.InitInstance;
_itemView.ShowModal;
finally
_itemView.ClearInstance;
end;
end;
procedure TFoodApp.CarregarComandas;
var
i, j: Integer;
_Sql: TSQLDataSet;
_comanda: TComanda;
begin
_Sql := Self.FModel.Sql;
_Sql.Active := False;
_Sql.CommandText := 'select c.coma_oid, c.cl_oid, c.coma_mesa, c.coma_total, l.cl_cod ' +
' from coma c left join cl l on c.cl_oid = l.cl_oid ' +
' where c.coma_stt = 0';
_Sql.Open();
j := 0;
while not _Sql.Eof do
begin
Inc(j);
_comanda := TComanda.Create(Self.pnlComandas,
Self.FUtil.iff(_Sql.FieldByName('cl_oid').IsNull,
_Sql.FieldByName('coma_mesa').AsString,
_Sql.FieldByName('cl_cod').AsString),
_Sql.FieldByName('coma_total').AsFloat,
Self.comandaClick);
_comanda.identificacao := _Sql.FieldByName('coma_oid').AsString;
Self.GetComandas().Add(_Sql.FieldByName('coma_oid').AsString, _comanda);
_Sql.Next();
end;
_Sql.Close();
for i := j to 35 do
Self.GetComandas.Add(IntToStr(i + 1),
TComanda.Create(Self.pnlComandas, '*****', 0, Self.comandaClick));
end;
procedure TFoodApp.comandaClick(Sender: TObject);
var
_abrirComandaView: TAbrirComandaView;
_comanda: TComanda;
begin
_comanda := TComanda(TLabel(Sender).Parent);
if _comanda.Identificacao <> '' then
begin
Self.GetComandaModel().carregarComanda(_comanda.Identificacao);
Self.exibirComanda();
end
else
begin
_abrirComandaView := TAbrirComandaView.Create(Self.GetComandaModel());
try
if _abrirComandaView.ShowModal() = mrOk then
begin
Self.FComandaSelecionada := _comanda;
Self.FComandaModel.abrirComanda(
_abrirComandaView.edtCliente.Text,
_abrirComandaView.edtMesa.Text);
Self.exibirComanda();
end;
finally
FreeAndNil(_abrirComandaView);
end;
end;
end;
procedure TFoodApp.FormCreate(Sender: TObject);
begin
Self.InitInstance(Self)
end;
function TFoodApp.GetComandaModel: TComandaModel;
begin
if Self.FComandaModel = nil then
begin
Self.FComandaModel := TComandaModel.Create(nil);
Self.FComandaModel.Connection := Self.FModel.cnn;
Self.FComandaModel.Util := Self.FUtil;
Self.FComandaModel.DataUtil := Self.FDataUtil;
Self.FComandaModel.Settings := Self.FSettings;
Self.FComandaModel.InitInstance(Self);
end;
Result := Self.FComandaModel;
end;
function TFoodApp.GetComandas: TDictionary<string, TComanda>;
begin
if Self.FComandas = nil then
Self.FComandas := TDictionary<string, TComanda>.Create();
Result := Self.FComandas;
end;
function TFoodApp.InitInstance(Sender: TObject): TFoodApp;
begin
Self.FUtil := TUtil.Create;
Self.FDataUtil := TDataUtil.Create;
Self.FSettings := TSettings.Create('.\system\setup.sys');
Self.FModel := TFoodModel.Create(nil);
Self.FDataUtil.GetOIDGenerator(Self.FModel.Sql);
Self.CarregarComandas();
Result := Self;
end;
procedure TFoodApp.ScrollBoxResize(Sender: TObject);
begin
Self.pnlComandas.Align := alLeft;
Self.pnlComandas.Align := alTop;
end;
end.
|
unit StoreClient;
interface
uses
SysUtils, Classes, httpsend, ssl_openssl, ZLib, Synacode;
type
TStorePayloadReq = class(TObject)
private
FDatas: TStringList;
function _escape(AValue: String): AnsiString;
public
appleId: String;
attempt: String;
createSession: String;
password: String;
rmp: String;
why: String;
guid: String;
creditDisplay: String;
salableAdamId: String;
appExtVrsId: String;
customerMessage: String;
constructor Create(appleId, password, attempt, createSession, guid, rmp, why: String); overload;
constructor Create(creditDisplay, guid, salableAdamId, appExtVrsId: String); overload;
destructor Destroy; override;
function GetAuthPayload(): AnsiString;
function GetDownloadPayload(): AnsiString;
function UpdatePlist(buffer: AnsiString): Integer;
property Datas: TStringList read FDatas;
end;
TStoreClient = class(TObject)
private
sess: String;
guid: String;
dsid: String;
storeFront: String;
accountName: String;
HTTP: THTTPSend;
public
constructor Create(Session, Guid: String);
destructor Destroy; override;
function Authenticate(appleId, password: String): String;
function Download(appId: String; appVerId: String = ''): String;
end;
implementation
{ TStoreAuthenticateReq }
constructor TStorePayloadReq.Create(appleId, password, attempt, createSession, guid,
rmp, why: String);
begin
FDatas := TStringList.Create;
self.appleId := appleId;
self.attempt := attempt;
self.createSession := createSession;
self.guid := guid;
self.password := password;
self.rmp := rmp;
self.why := why;
end;
constructor TStorePayloadReq.Create(creditDisplay, guid, salableAdamId,
appExtVrsId: String);
begin
FDatas := TStringList.Create;
self.creditDisplay := creditDisplay;
self.guid := guid;
self.salableAdamId := salableAdamId;
self.appExtVrsId := appExtVrsId;
end;
destructor TStorePayloadReq.Destroy;
begin
FDatas.Free;
inherited;
end;
function TStorePayloadReq.GetAuthPayload: AnsiString;
begin
Result := UTF8Encode(
'<?xml version="1.0" encoding="UTF-8"?>'#10+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'#10+
'<plist version="1.0">'#10+
'<dict>'#10+
#9'<key>appleId</key>'#10+
#9'<string>'+_escape(appleId)+'</string>'#10+
#9'<key>attempt</key>'#10+
#9'<string>'+_escape(attempt)+'</string>'#10+
#9'<key>createSession</key>'#10+
#9'<string>'+_escape(createSession)+'</string>'#10+
#9'<key>guid</key>'#10+
#9'<string>'+_escape(guid)+'</string>'#10+
#9'<key>password</key>'#10+
#9'<string>'+_escape(password)+'</string>'#10+
#9'<key>rmp</key>'#10+
#9'<string>'+_escape(rmp)+'</string>'#10+
#9'<key>why</key>'#10+
#9'<string>'+_escape(why)+'</string>'#10+
'</dict>'#10+
'</plist>'#10);
end;
function TStorePayloadReq.GetDownloadPayload: AnsiString;
begin
Result := UTF8Encode(
'<?xml version="1.0" encoding="UTF-8"?>'#10+
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'#10+
'<plist version="1.0">'#10+
'<dict>'#10+
#9'<key>creditDisplay</key>'#10+
#9'<string>'+_escape(creditDisplay)+'</string>'#10+
#9'<key>guid</key>'#10+
#9'<string>'+_escape(guid)+'</string>'#10+
#9'<key>salableAdamId</key>'#10+
#9'<string>'+_escape(salableAdamId)+'</string>'#10+
'</dict>'#10+
'</plist>'#10);
end;
function TStorePayloadReq.UpdatePlist(buffer: AnsiString): Integer;
var
LoopVar: Integer;
tagFlag, valueFlag: Integer;
processBuffer, valueBuffer,
keyName, lastKey, prefixKey: AnsiString;
PrefixList,
SimpleParser: TStringList;
begin
Result := -1;
// Brutal XML Parsing by jkh. only FAST process.
processBuffer := '';
tagFlag := 0;
valueFlag := 0;
lastKey := '';
prefixKey := '';
SimpleParser := TStringList.Create;
PrefixList := TStringList.Create;
try
for LoopVar := 1 to Length(buffer) do
begin
case buffer[LoopVar] of
'<':
begin
if tagFlag = 0 then
tagFlag := 1;
end;
'>':
begin
if tagFlag = 1 then
begin
if processBuffer = 'key' then
begin
valueBuffer := '';
valueFlag := 1;
end
else if processBuffer = 'string' then
begin
valueBuffer := '';
valueFlag := 2;
end
else if processBuffer = 'integer' then
begin
valueBuffer := '';
valueFlag := 3;
end
else if processBuffer = 'true/' then
begin
valueBuffer := '';
valueFlag := 10;
SimpleParser.Values[prefixKey+lastKey] := 'true';
lastKey := '';
end
else if processBuffer = 'false/' then
begin
valueBuffer := '';
valueFlag := 10;
SimpleParser.Values[prefixKey+lastKey] := 'false';
lastKey := '';
end
else if processBuffer = 'dict' then
begin
valueBuffer := '';
if lastKey <> '' then
begin
valueFlag := 100;
PrefixList.Add(lastKey);
prefixKey := StringReplace(Trim(PrefixList.Text), #13#10, '_', [rfReplaceAll]);
if prefixKey <> '' then
prefixKey := prefixKey + '_';
end;
lastKey := '';
end
else if copy(processBuffer, 1, 1) = '/' then
begin
if valueFlag = 1 then
begin
lastKey := valueBuffer;
end
else if (processBuffer = '/dict') and (PrefixList.Count > 0) then
begin
PrefixList.Delete(PrefixList.Count-1);
prefixKey := StringReplace(Trim(PrefixList.Text), #13#10, '_', [rfReplaceAll]);
if prefixKey <> '' then
prefixKey := prefixKey + '_';
end
else
begin
SimpleParser.Values[prefixKey+lastKey] := valueBuffer;
lastKey := '';
end;
valueBuffer := '';
valueFlag := 0;
end;
processBuffer := '';
tagFlag := 0;
end;
end;
else
if tagFlag = 1 then
processBuffer := processBuffer + buffer[LoopVar]
else if (tagFlag = 0) and (valueFlag > 0) then
valueBuffer := valueBuffer + buffer[LoopVar];
end;
end;
for LoopVar := 0 to SimpleParser.Count-1 do
begin
keyName := SimpleParser.Names[LoopVar];
valueBuffer := SimpleParser.ValueFromIndex[LoopVar];
if keyName = 'appleId' then
Self.appleId := valueBuffer
else if keyName = 'attempt' then
Self.attempt := valueBuffer
else if keyName = 'createSession' then
Self.createSession := valueBuffer
else if keyName = 'guid' then
Self.guid := valueBuffer
else if keyName = 'password' then
Self.password := valueBuffer
else if keyName = 'rmp' then
Self.rmp := valueBuffer
else if keyName = 'why' then
Self.why := valueBuffer
else if keyName = 'customerMessage' then
Self.customerMessage := valueBuffer;
end;
FDatas.Assign(SimpleParser);
Result := 1;
finally
SimpleParser.Free;
PrefixList.Free;
end;
end;
function TStorePayloadReq._escape(AValue: String): AnsiString;
begin
Result := AValue;
Result := StringReplace(Result, #13#10, #13, [rfReplaceAll]);
Result := StringReplace(Result, #13, #10, [rfReplaceAll]);
Result := StringReplace(Result, '&', '&', [rfReplaceAll]);
Result := StringReplace(Result, '<', '<', [rfReplaceAll]);
Result := StringReplace(Result, '>', '>', [rfReplaceAll]);
end;
{ TStoreClient }
function TStoreClient.Authenticate(appleId, password: String): String;
var
MethodRes: Boolean;
Response: TStringList;
Body: AnsiString;
Params: String;
Url: String;
Req: TStorePayloadReq;
function parseHeader(searchHeader: String): String;
var
LoopVar: Integer;
Line: String;
begin
for LoopVar := 0 to HTTP.Headers.Count-1 do
begin
Line := HTTP.Headers[LoopVar];
if LowerCase(Copy(Line, 1, Length(searchHeader))) = searchHeader then
Result := Trim(Copy(Line, Length(searchHeader)+2, Length(Line)-Length(searchHeader)-1));
end;
end;
procedure updateUrl;
begin
Url := parseHeader('location');
end;
begin
Response := TStringList.Create;
Req := TStorePayloadReq.Create(appleId, password, '4', 'true', guid, '0', 'signIn');
Try
Url := 'https://p46-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/authenticate?guid=' + guid;
while True do
begin
HTTP.Headers.Clear;
HTTP.UserAgent := 'Configurator/2.0 (Macintosh; OS X 10.12.6; 16G29) AppleWebKit/2603.3.8';
HTTP.MimeType := 'application/x-www-form-urlencoded';
HTTP.Headers.Add(
'Accept: */*'
);
Body := Req.GetAuthPayload;
HTTP.Document.Size := 0;
HTTP.Document.Write(Body[1], Length(Body));
MethodRes := HTTP.HTTPMethod('POST', Url);
if not MethodRes then break;
if HTTP.ResultCode = 302 then
begin
updateUrl;
continue;
end;
break;
end;
if MethodRes then
begin
SetLength(Body, HTTP.Document.Size);
HTTP.Document.Read(Body[1], HTTP.Document.Size);
if Pos('We are unable to find iTunes on your computer.', Body) > 0 then
begin
Result := 'error : UUID not valid';
exit;
end;
if Req.UpdatePlist(Body) < 0 then
begin
Result := 'error : communicate error.'#13#10+Body;
end
else if Req.Datas.Values['m-allowed'] = 'true' then
begin
dsid := Req.Datas.Values['download-queue-info_dsid'];
storeFront := parseHeader('x-set-apple-store-front');
accountName := Req.Datas.Values['accountInfo_address_firstName'] + ' ' + Req.Datas.Values['accountInfo_address_lastName'];
Result := '';
end
else
begin
Result := 'error : '#13#10+Req.customerMessage;
end;
end;
Finally
Response.Free;
Req.Free;
End;
end;
constructor TStoreClient.Create(Session, Guid: String);
begin
inherited Create;
HTTP := THTTPSend.Create;
self.sess := Session;
self.guid := UpperCase(guid);
end;
destructor TStoreClient.Destroy;
begin
HTTP.Free;
inherited;
end;
function TStoreClient.Download(appId, appVerId: String): String;
var
MethodRes: Boolean;
Response: TStringList;
Body: AnsiString;
Params: String;
Url: String;
Req: TStorePayloadReq;
begin
Response := TStringList.Create;
Req := TStorePayloadReq.Create('', guid, appId, appVerId);
Try
Url := 'https://p25-buy.itunes.apple.com/WebObjects/MZFinance.woa/wa/volumeStoreDownloadProduct?guid=' + guid;
HTTP.Headers.Clear;
HTTP.UserAgent := 'Configurator/2.0 (Macintosh; OS X 10.12.6; 16G29) AppleWebKit/2603.3.8';
HTTP.MimeType := 'application/x-www-form-urlencoded';
HTTP.Headers.Add(
'iCloud-DSID: ' + dsid + #13#10+
'X-Dsid: ' + dsid + #13#10+
'Accept: */*'
);
Body := Req.GetDownloadPayload;
HTTP.Document.Size := 0;
HTTP.Document.Write(Body[1], Length(Body));
MethodRes := HTTP.HTTPMethod('POST', Url);
if MethodRes then
begin
SetLength(Body, HTTP.Document.Size);
HTTP.Document.Read(Body[1], HTTP.Document.Size);
if Req.UpdatePlist(Body) < 0 then
begin
Result := 'error : communicate error.'#13#10+Body;
end
else if Req.Datas.Values['m-allowed'] = 'true' then
begin
Result := Req.Datas.Values['songList'];
end
else
begin
Result := 'error : '#13#10+Req.customerMessage;
end;
end;
Finally
Response.Free;
Req.Free;
End;
end;
end.
|
UNIT httpUtil;
INTERFACE
USES Classes, blcksock, synautil, sysutils, myGenerics,myStringUtil,synsock,opensslsockets;
TYPE
T_httpRequestMethod=(htrm_no_request,htrm_GET,htrm_POST,htrm_HEAD,htrm_PUT,htrm_PATCH,htrm_DELETE,htrm_TRACE,htrm_OPTIONS,htrm_CONNECT);
CONST
C_httpRequestMethodName:array[T_httpRequestMethod] of string=('','GET','POST','HEAD','PUT','PATCH','DELETE','TRACE','OPTIONS','CONNECT');
TYPE
T_httpHeader=array of record key,value:string; end;
P_httpListener=^T_httpListener;
P_httpConnectionForRequest=^T_httpConnectionForRequest;
T_httpConnectionForRequest=object
private
//parent listener
relatedListener:P_httpListener;
//connection for this request
ConnectionSocket: TTCPBlockSocket;
//data parsed from request
method:T_httpRequestMethod;
request,protocol:string;
header:T_httpHeader;
body:string;
public
CONSTRUCTOR create(CONST conn:TSocket; CONST parent:P_httpListener);
DESTRUCTOR destroy;
PROCEDURE sendStringAndClose(CONST s:ansistring);
//Read only access to parsed http fields
PROPERTY getMethod:T_httpRequestMethod read method;
PROPERTY getRequest :string read request;
PROPERTY getProtocol:string read protocol;
PROPERTY getHeader :T_httpHeader read header;
PROPERTY getBody :string read body;
end;
T_httpListener=object
private
ListenerSocket: TTCPBlockSocket;
id:ansistring;
maxConnections:longint;
openConnections:longint;
public
CONSTRUCTOR create(CONST ipAndPort:string; CONST maxConnections_:longint=8);
CONSTRUCTOR create(CONST ip,port:string; CONST maxConnections_:longint=8);
DESTRUCTOR destroy;
FUNCTION getRequest(CONST timeOutInMilliseconds:longint=100):P_httpConnectionForRequest;
FUNCTION getRawRequestSocket(CONST timeOutInMilliseconds:longint=100):TSocket;
FUNCTION toString:ansistring;
FUNCTION getLastListenerSocketError:longint;
end;
CONST HTTP_404_RESPONSE='HTTP/1.0 404' + CRLF;
HTTP_503_RESPONSE='HTTP/1.0 503' + CRLF + 'Retry-After: 10' + CRLF;
FUNCTION wrapTextInHttp(CONST OutputDataString,serverInfo:string; CONST contentType:string='Text/Html'):string;
FUNCTION wrapTextInHttp(CONST data:string; CONST code:longint; CONST header:T_httpHeader):string;
FUNCTION cleanIp(CONST dirtyIp:ansistring):ansistring;
PROCEDURE setHeaderDefaults(VAR header:T_httpHeader; CONST contentLength:longint=0; CONST contentType:string=''; CONST serverInfo:string='');
IMPLEMENTATION
USES strutils;
PROCEDURE disposeSocket(VAR socket:P_httpListener);
begin
dispose(socket,destroy);
end;
CONST
HP_Splitter=': ';
HP_ContentType='Content-type';
HP_ContentLength='Content-length';
HP_Connection='Connection';
HP_Date='Date';
HP_Server='Server';
emptyHeader:T_httpHeader=();
PROCEDURE setHeaderDefaults(VAR header:T_httpHeader; CONST contentLength:longint=0; CONST contentType:string=''; CONST serverInfo:string='');
VAR i :longint;
idxContentType :longint=-1;
idxContentLength:longint=-1;
hasConnection :boolean=false;
hasServer :boolean=false;
hasDate :boolean=false;
begin
for i:=0 to length(header)-1 do begin
if header[i].key=HP_ContentType then begin
if contentType<>'' then header[i].value:=contentType;
idxContentType:=i;
end else if header[i].key=HP_ContentLength then begin
if contentLength<>0 then header[i].value:=intToStr(contentLength);
idxContentLength:=i;
end else if header[i].key=HP_Connection then begin
header[i].value:='close';
hasConnection:=true;
end else if header[i].key=HP_Server then begin
hasServer:=true;
end else if header[i].key=HP_Date then begin
header[i].value:=Rfc822DateTime(now);
hasDate:=true;
end;
end;
if not(hasDate) then begin i:=length(header); setLength(header,i+1); header[i].key:=HP_Date; header[i].value:=Rfc822DateTime(now); end;
if not(hasServer) and (serverInfo<>'') then begin i:=length(header); setLength(header,i+1); header[i].key:=HP_Server; header[i].value:=serverInfo; end;
if not(hasConnection) then begin i:=length(header); setLength(header,i+1); header[i].key:=HP_Connection; header[i].value:='close'; end;
if (contentLength>0) and (idxContentLength<0) then begin i:=length(header); setLength(header,i+1); header[i].key:=HP_ContentLength; header[i].value:=intToStr(contentLength); end;
if (contentType<>'') and (idxContentType <0) then begin i:=length(header); setLength(header,i+1); header[i].key:=HP_ContentType; header[i].value:=contentType; end;
end;
FUNCTION wrapTextInHttp(CONST OutputDataString,serverInfo: string; CONST contentType:string='Text/Html'): string;
VAR header:T_httpHeader;
begin
header:=emptyHeader;
setHeaderDefaults(header,length(OutputDataString),contentType,serverInfo);
result:=wrapTextInHttp(OutputDataString,200,header);
end;
FUNCTION wrapTextInHttp(CONST data:string; CONST code:longint; CONST header:T_httpHeader):string;
FUNCTION headerToString:string;
VAR i:longint;
begin
result:='';
for i:=0 to length(header)-1 do result+=trim(header[i].key)+HP_Splitter+trim(header[i].value)+CRLF;
end;
begin
result:='HTTP/1.0 '+intToStr(code) + CRLF +
headerToString + CRLF +
data;
end;
PROCEDURE cleanSocket(VAR ipAndPort:string; OUT ip,port:string);
CONST default_port=60000;
VAR temp:T_arrayOfString;
intPort:longint;
begin
temp:=split(ipAndPort,':');
if length(temp)>1 then begin
intPort:=strToIntDef(trim(temp[1]),-1);
if intPort<0 then intPort:=default_port;
end else intPort:=default_port;
port:=intToStr(intPort);
ip:=ansiReplaceStr(
cleanString(
ansiReplaceStr(
lowercase(trim(temp[0])),
'localhost',
'127.0.0.1'),
['0'..'9','.'],
' '),
' ',
'');
if CountOfChar(ip,'.')<>3 then ip:='127.0.0.1';
ipAndPort:=ip+':'+port;
end;
FUNCTION cleanIp(CONST dirtyIp:ansistring):ansistring;
VAR ip,port:string;
begin
result:=dirtyIp;
cleanSocket(result,ip,port);
end;
CONSTRUCTOR T_httpConnectionForRequest.create(CONST conn: TSocket; CONST parent: P_httpListener);
PROCEDURE parseTriplet(VAR s:string);
VAR temp:string;
inputLine:string;
htrm:T_httpRequestMethod;
begin
//initialize result
method:=htrm_no_request;
request:='';
protocol:='';
body:='';
setLength(header,0);
//Parse request line
inputLine:=fetch(s,CRLF);
temp:=fetch(inputLine,' ');
for htrm in T_httpRequestMethod do if C_httpRequestMethodName[htrm]=temp then method:=htrm;
if method=htrm_no_request then exit;
request :=fetch(inputLine, ' ');
protocol:=fetch(inputLine, ' ');
//parse additional header entries
inputLine:=fetch(s,CRLF);
while inputLine<>'' do begin
setLength(header,length(header)+1);
with header[length(header)-1] do begin
key:=fetch(inputLine,':');
value:=trim(inputLine);
end;
inputLine:=fetch(s,CRLF);
end;
body:=s;
end;
VAR s:string;
receiveTimeout:longint=2000;
begin
relatedListener:=parent;
ConnectionSocket := TTCPBlockSocket.create;
ConnectionSocket.socket:=conn;
ConnectionSocket.GetSins;
repeat
s := ConnectionSocket.RecvPacket(receiveTimeout);
if method=htrm_no_request then begin
parseTriplet(s);
if method<>htrm_no_request then receiveTimeout:=1;
end;
until ConnectionSocket.LastError<>0;
end;
DESTRUCTOR T_httpConnectionForRequest.destroy;
begin
ConnectionSocket.free;
end;
PROCEDURE T_httpConnectionForRequest.sendStringAndClose(CONST s: ansistring);
begin
ConnectionSocket.sendString(s);
ConnectionSocket.CloseSocket;
interlockedDecrement(relatedListener^.openConnections);
end;
CONSTRUCTOR T_httpListener.create(CONST ipAndPort: string; CONST maxConnections_:longint=8);
VAR ip,port:string;
begin
id:=ipAndPort;
cleanSocket(id,ip,port);
create(ip,port,maxConnections_);
end;
CONSTRUCTOR T_httpListener.create(CONST ip, port: string; CONST maxConnections_:longint=8);
begin
ListenerSocket := TTCPBlockSocket.create;
ListenerSocket.CreateSocket;
ListenerSocket.setLinger(true,100);
ListenerSocket.bind(ip,port);
ListenerSocket.listen;
id:=ip+':'+port;
maxConnections:=maxConnections_;
openConnections:=0;
end;
DESTRUCTOR T_httpListener.destroy;
VAR shutdownTimeout:double;
begin
shutdownTimeout:=now+1/(24*60*60);
ListenerSocket.CloseSocket;
ListenerSocket.free;
while (openConnections>0) and (now<shutdownTimeout) do sleep(1);
end;
FUNCTION T_httpListener.getRequest(CONST timeOutInMilliseconds: longint):P_httpConnectionForRequest;
begin
if not(ListenerSocket.canread(timeOutInMilliseconds)) then exit(nil);
new(result,create(ListenerSocket.accept,@self));
interLockedIncrement(openConnections);
if result^.getMethod=htrm_no_request then begin
result^.sendStringAndClose(HTTP_404_RESPONSE);
dispose(result,destroy);
result:=nil;
end else while openConnections>maxConnections do sleep(1);
end;
FUNCTION T_httpListener.getRawRequestSocket(CONST timeOutInMilliseconds:longint=100):TSocket;
begin
if not(ListenerSocket.canread(timeOutInMilliseconds))
then exit(INVALID_SOCKET)
else begin
interLockedIncrement(openConnections);
result:=ListenerSocket.accept;
while openConnections>maxConnections do sleep(1);
end;
end;
FUNCTION T_httpListener.toString: ansistring;
begin
result:=id;
end;
FUNCTION T_httpListener.getLastListenerSocketError:longint;
begin
result:=ListenerSocket.LastError;
end;
end.
|
////////////////////////////////////////////
// Кодировка и расчет CRC для приборов типа УБЗ-302 и ТР-101
////////////////////////////////////////////
unit Devices.UBZ.Common;
interface
uses GMGlobals, Windows, Classes, StrUtils;
procedure DecodeUBZAlarms(dwErr: DWORD; sl: TSTrings); overload;
function DecodeUBZAlarms(dwErr: DWORD; const Separator: string): string; overload;
procedure DecodeTR101Alarms(dwErr: DWORD; sl: TSTrings); overload;
function DecodeTR101Alarms(dwErr: DWORD; const Separator: string): string; overload;
implementation
procedure DecodeUBZAlarms(dwErr: DWORD; sl: TSTrings);
const UBZ_AlarmStr: array [0..23] of String = (
'максимальная токовая в фазах' // 241:0
,'по тепловой перегрузке' // 241:1
,'от замыкания на землю (по току нулевой последовательности)' // 241:2
,'по превышению кратности обратной последовательности по току к обратной последовательности по напряжению' // 241:3
,'по обратной последовательности по току' // 241:4
,'минимальная токовая в фазах' // 241:5
,'затянутый пуск' // 241:6
,'блокировка ротора' // 241:7
,'по достижению порога температуры первого датчика' // 241:8
,'по достижению порога температуры второго датчика' // 241:9
,'по порядку чередования фаз' // 241:10
,'по наличию токов при отключенном реле нагрузки (авария контактора)' //241:11
,'по минимальному линейному напряжению' // 241:12
,'по максимальному линейному напряжению' // 241:13
,'по перекосу фаз' // 241:14
,'по минимальному сопротивлению изоляции обмоток двигателя' // 241:15
,'по аварии канала дистанционного управления' // 242:0
,'аварийный останов двигателя без возможности повторного пуска' // 242:1
,'аварийный останов двигателя с возможностью повторного пуска одновременным нажатием кнопок ВВЕРХ и ВНИЗ' // 242:2
,'по к.з. датчика температуры 1' // 242:3
,'по обрыву датчика температуры 1' // 242:4
,'по к.з. датчика температуры 2' // 242:5
,'по обрыву датчика температуры 2' // 242:6
,'по обрыву фазы' // 242:7
);
var i: int;
begin
if dwErr = $FFFF then
sl.Add('Обрыв связи с прибором')
else
for i := 0 to High(UBZ_AlarmStr) do
if (dwErr shr i) and 1 > 0 then
sl.Add(UBZ_AlarmStr[i]);
end;
function DelimitedSL(sl: TStrings; const Separator: string): string;
var i: int;
begin
if sl.Count = 0 then
Result := 'Нет аварий'
else
begin
Result := '';
for i := 0 to sl.Count - 1 do
Result := Result + IfThen(i > 0, Separator) + sl[i];
end;
end;
function DecodeUBZAlarms(dwErr: DWORD; const Separator: string): string;
var sl: TStringList;
begin
sl := TStringList.Create();
try
DecodeUBZAlarms(dwErr, sl);
Result := DelimitedSL(sl, Separator);
finally
sl.Free();
end;
end;
procedure DecodeTR101Alarms(dwErr: DWORD; sl: TSTrings);
const TR101_AlarmStr: array [0..9] of String = (
'отказ EEPROM',
'ошибка параметра',
'замыкание датчика 1',
'замыкание датчика 2',
'замыкание датчика 3',
'замыкание датчика 4',
'обрыв датчика 1',
'обрыв датчика 2',
'обрыв датчика 3',
'обрыв датчика 4'
);
var i: int;
begin
if dwErr = $FFFF then
sl.Add('Обрыв связи с прибором')
else
for i := 0 to High(TR101_AlarmStr) do
if (dwErr shr i) and 1 > 0 then
sl.Add(TR101_AlarmStr[i]);
end;
function DecodeTR101Alarms(dwErr: DWORD; const Separator: string): string;
var sl: TStringList;
begin
sl := TStringList.Create();
try
DecodeUBZAlarms(dwErr, sl);
Result := DelimitedSL(sl, Separator);
finally
sl.Free();
end;
end;
end.
|
unit Engine;
interface
uses
Points, Level, Monsters, Textures, EngineTypes, Items, Collisions, Sounds;
procedure EnginePhys (dt : float);
procedure SetMonsterActive (M: PMonster);
var
GameTime : float;
var
CActiveMonsters : integer = 0;
ActiveMonsters : array [0..CMonsters-1] of PMonster;
implementation
uses
Memory, Bullets;
const
ProcessMonsterTime = 2;
function MustContinue (const M: Monster): boolean;
begin
if M.Item.Model.Player then Result := True
else Result := Visible(M.Head^, L.Player.Head^);
end;
procedure IIMonster (var M: Monster);
var
DP : Point;
NeedA : float;
begin
if not Live(M) then Exit;
M.Controls.Forw := True; // tmp
DP := Sub(M.Body.P, L.Player.Body.P);
NeedA := Atan2(DP.x,DP.y)+Pi-M.anglez;
while NeedA> Pi do NeedA := NeedA-2*Pi;
while NeedA<-Pi do NeedA := NeedA+2*Pi;
M.Controls.daz := NeedA*1000;
if M.Controls.daz>+3 then M.Controls.daz := +3;
if M.Controls.daz<-3 then M.Controls.daz := -3;
NeedA := Atan2(DP.z,sqrt(sqr(DP.x)+sqr(DP.y)))+(Pi/2-M.anglex);
while NeedA> Pi do NeedA := NeedA-2*Pi;
while NeedA<-Pi do NeedA := NeedA+2*Pi;
M.Controls.dax := NeedA*1000;
if M.Controls.dax>+3 then M.Controls.dax := +3;
if M.Controls.dax<-3 then M.Controls.dax := -3;
if M.Item.Model.Lightness>0.1 then begin
M.Controls.Jump := M.Item.Center.P.z>L.Player.Head.P.z+0.3;
M.Controls.Sit := M.Item.Center.P.z<L.Player.Head.P.z-0.3;
end else if M.Item.Model.Spring>0.1 then
M.Controls.Jump := True;
M.Controls.WeaponNumber := 9;
while (M.Controls.WeaponNumber>=0) and (not M.Weapons[M.Controls.WeaponNumber].IsWeapon) do
Dec(M.Controls.WeaponNumber);
M.Controls.Shot := True;
end;
function IsMonsterActive (M: PMonster) : boolean;
begin
Result := M.ProcessTime>0;
end;
procedure SetMonsterActive (M: PMonster);
var
wa : boolean;
begin
wa := IsMonsterActive(M);
M.ProcessTime := ProcessMonsterTime;
if not wa then begin
Inc(CActiveMonsters);
ActiveMonsters[CActiveMonsters-1] := M;
end;
end;
procedure MoveActiveMonsters (dt : float);
var
i,j : integer;
begin
j := 0;
for i := 0 to CActiveMonsters-1 do begin
if not ActiveMonsters[i].Item.Model.Player then IIMonster(ActiveMonsters[i]^);
MoveMonster(ActiveMonsters[i], dt);
UpdateItem(ActiveMonsters[i].Item);
if MustContinue (ActiveMonsters[i]^) then
SetMonsterActive(ActiveMonsters[i]); // оно не влияет на массив
ActiveMonsters[i].ProcessTime := ActiveMonsters[i].ProcessTime - dt;
if IsMonsterActive(ActiveMonsters[i]) then begin
ActiveMonsters[j] := ActiveMonsters[i];
Inc(j);
end else
ActiveMonsters[i].Controls.Jump := False; // tmp
end;
CActiveMonsters := j;
end;
procedure FindVisibleMonsters (VP : SPoint);
var
CIS : integer;
IP : PAPItem;
DP : Point;
h,r,a : float;
i : integer;
MS : MemoryState;
tryes : integer;
begin
SetMonsterActive(@L.Player);
for tryes := 0 to 4 do begin
SaveState(MS);
h := random*2-1;
r := sqrt(1-h*h);
a := random*2*pi;
DP.x := r*cos(a);
DP.y := r*sin(a);
DP.z := h;
DP := Scale(DP,100); // на 100 метров палим монстров азаза
CIS := 0;
IP := Alloc(CItems * sizeof(PItem));
TraceWithItems(VP, DP, CIS, IP, True);
// чётто сделать с монстрами
for i := 0 to CIS-1 do
if (IP[i].Monster<>nil) and Live(IP[i].Monster^) and Visible(VP, IP[i].Monster.Head^) then
SetMonsterActive(IP[i].Monster);
for i := 0 to CIS-1 do IP[i].inProcess := False;
RestoreState(MS);
end;
end;
procedure EnginePhys (dt : float);
begin
GameTime := GameTime + dt;
FindVisibleMonsters(L.Player.Item.Convexes[0].Center);
ProcessBullets (dt);
MoveActiveMonsters (dt); // да-да, это включая и игрока!
ProcessSkyTxr (dt);
ProcessHellTxr (dt);
end;
end.
|
unit uPlayerFrame;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.DBCtrls, Vcl.StdCtrls,
Vcl.ExtCtrls;
type
TPlayerFrame = class(TFrame)
pnlPlayer: TPanel;
lblPlayer: TLabel;
lblAC: TLabel;
lblHPval: TLabel;
lblACval: TLabel;
lblHP: TLabel;
lblLVL: TLabel;
lblSTR: TLabel;
lblDEX: TLabel;
lblCON: TLabel;
lblINT: TLabel;
DBText4: TDBText;
lblWIS: TLabel;
lblCHA: TLabel;
lblComingSoon: TLabel;
lblSTRval: TLabel;
lblDEXval: TLabel;
lblCONval: TLabel;
lblINTval: TLabel;
lblWISval: TLabel;
lblCHAval: TLabel;
lblLVLval: TLabel;
lblClass: TLabel;
lblName: TLabel;
private
{ Private declarations }
public
{ Public declarations }
end;
type
TPlayer = record
name: string;
health: string;
ac: string;
str: string;
dex: string;
con: string;
int: string;
wis: string;
cha: string;
lvl: string;
end;
implementation
{$R *.dfm}
end.
|
{***************************************************************
*
* Project : PingGUI
* Unit Name: Main
* Purpose : Demonstrates ICMP "Ping"
* Version : 1.0
* Date : Wed 25 Apr 2001 - 01:31:04
* Author : <unknown>
* History :
* Tested : Wed 25 Apr 2001 // Allen O'Neill <allen_oneill@hotmail.com>
*
****************************************************************}
unit Main;
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls, extctrls,
{$ENDIF}
SysUtils, Classes, IdIcmpClient, IdBaseComponent, IdComponent, IdRawBase, IdRawClient;
type
TfrmPing = class(TForm)
lstReplies: TListBox;
ICMP: TIdIcmpClient;
Panel1: TPanel;
btnPing: TButton;
edtHost: TEdit;
procedure btnPingClick(Sender: TObject);
procedure ICMPReply(ASender: TComponent; const ReplyStatus: TReplyStatus);
private
public
end;
var
frmPing: TfrmPing;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
procedure TfrmPing.btnPingClick(Sender: TObject);
var
i: integer;
begin
ICMP.OnReply := ICMPReply;
ICMP.ReceiveTimeout := 1000;
btnPing.Enabled := False; try
ICMP.Host := edtHost.Text;
for i := 1 to 4 do begin
ICMP.Ping;
Application.ProcessMessages;
//Sleep(1000);
end;
finally btnPing.Enabled := True; end;
end;
procedure TfrmPing.ICMPReply(ASender: TComponent; const ReplyStatus: TReplyStatus);
var
sTime: string;
begin
// TODO: check for error on ping reply (ReplyStatus.MsgType?)
if (ReplyStatus.MsRoundTripTime = 0) then
sTime := '<1'
else
sTime := '=';
lstReplies.Items.Add(Format('%d bytes from %s: icmp_seq=%d ttl=%d time%s%d ms',
[ReplyStatus.BytesReceived,
ReplyStatus.FromIpAddress,
ReplyStatus.SequenceId,
ReplyStatus.TimeToLive,
sTime,
ReplyStatus.MsRoundTripTime]));
end;
end.
|
unit Controller;
interface
uses
taTypes, taCsv, System.Classes;
type
TTomatoAggController = class(TObject)
strict private
FCsv: TTaCsv;
//FExcel: TTaExcel;
FFilterTag: string;
FLastCorrectionDateTime: TDatetime;
FLastTomatoDateTime: TDatetime;
procedure SerializeBegin(AStrings: TStringList; APath: string);
procedure SerializeEnd(AStrings: TStringList; APath: string; ASave: Boolean);
procedure SerializeSettingsValue(AStrings: TStringList; AIdx: Integer; ASave:
Boolean; var AValue: TDatetime); overload;
procedure SerializeSettingsValue(AStrings: TStringList; AIdx: Integer; ASave:
Boolean; var AValue: string); overload;
public
constructor Create;
destructor Destroy; override;
function GetLastPeriodsStr: string;
procedure Process(ACsvInput: Boolean);
procedure SerializeSettings(APath: string; ASave: Boolean);
published
end;
implementation
uses
System.SysUtils, taGlobals;
constructor TTomatoAggController.Create;
begin
inherited Create;
FCsv := TTaCsv.Create();
end;
destructor TTomatoAggController.Destroy;
begin
FreeAndNil(FCsv);
inherited Destroy;
end;
function TTomatoAggController.GetLastPeriodsStr: string;
const
SYyMmddHhNn = 'yy-mmdd hh:nn';
begin
Result := Format('%s / %s',
[FormatDateTime(SYyMmddHhNn, FLastTomatoDateTime),
FormatDateTime(SYyMmddHhNn, FLastCorrectionDateTime)]);
end;
procedure TTomatoAggController.Process(ACsvInput: Boolean);
var
LTomatoes: TTimePeriodList;
LCorrections: TTimePeriodList;
LCsvCorrections: TTaCsv;
LCsvOutput: TTaCsv;
begin
LTomatoes := TTimePeriodList.Create;
LCorrections := TTimePeriodList.Create;
try
//FExcel.InitExcelBook(DataPath('Data.xlsx'), DataPath('Template.xlsx'));
if not ACsvInput then
begin
//FExcel.GetTomatoes(LTomatoes);
NotSupported(ACsvInput, 'ACsvInput');
end
else
begin
FCsv.Open(DataPath('tomato.es.csv'), False);
FCsv.GetTomatoes(LTomatoes, FLastTomatoDateTime);
end;
LCsvCorrections := TTaCsv.Create;
LCsvCorrections.Delimiter := STab;
LCsvCorrections.Open(DataPath('Corrections.csv'), False);
try
LCsvCorrections.GetCorrections(LCorrections, FLastCorrectionDateTime);
finally
FreeAndNil(LCsvCorrections);
end;
LTomatoes.FilterByTag(FFilterTag, True);
LTomatoes.ApplyCorrections(LCorrections);
LTomatoes.MergeSequences;
LTomatoes.TimeShift(OUTPUTTIMEZONE_UTCDELTA_HRS * SECONDSINHOUR);
LTomatoes.JustifyMidnight;
LTomatoes.Check;
//FExcel.PrintPeriods(LTomatoes);
LCsvOutput := TTaCsv.Create;
try
LCsvOutput.Open(DataPath('output.csv'), True);
LCsvOutput.PrintPeriods(LTomatoes);
finally
FreeAndNil(LCsvOutput);
end;
finally
FreeAndNil(LCorrections);
FreeAndNil(LTomatoes);
end;
end;
procedure TTomatoAggController.SerializeBegin(AStrings: TStringList; APath:
string);
begin
if FileExists(APath) then
AStrings.LoadFromFile(APath);
end;
procedure TTomatoAggController.SerializeEnd(AStrings: TStringList; APath:
string; ASave: Boolean);
begin
if ASave then
AStrings.SaveToFile(APath);
end;
procedure TTomatoAggController.SerializeSettings(APath: string; ASave: Boolean);
var
LStrings: TStringList;
begin
LStrings := TStringList.Create;
try
SerializeBegin(LStrings, APath);
SerializeSettingsValue(LStrings, 0, ASave, FLastTomatoDateTime);
SerializeSettingsValue(LStrings, 1, ASave, FLastCorrectionDateTime);
SerializeSettingsValue(LStrings, 2, ASave, FFilterTag);
SerializeEnd(LStrings, APath, ASave);
finally
FreeAndNil(LStrings);
end;
end;
procedure TTomatoAggController.SerializeSettingsValue(AStrings: TStringList;
AIdx: Integer; ASave: Boolean; var AValue: TDatetime);
var
LString: string;
begin
LString := FloatToStr(AValue);
SerializeSettingsValue(AStrings, AIdx, ASave, LString);
if not ASave then
AValue := StrToFloatDef(LString, 0);
end;
procedure TTomatoAggController.SerializeSettingsValue(AStrings: TStringList;
AIdx: Integer; ASave: Boolean; var AValue: string);
begin
if ASave then
begin
while AIdx > AStrings.Count - 1 do
AStrings.Add('');
AStrings[AIdx] := AValue;
end
else
begin
AValue := '';
if AIdx < AStrings.Count then
AValue := AStrings[AIdx];
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ODBC Bridge driver }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Phys.ODBC;
interface
uses
System.Classes,
FireDAC.Phys, FireDAC.Phys.ODBCBase;
type
[ComponentPlatformsAttribute(pfidWindows or pfidOSX or pfidLinux)]
TFDPhysODBCDriverLink = class(TFDPhysODBCBaseDriverLink)
protected
function GetBaseDriverID: String; override;
end;
{-------------------------------------------------------------------------------}
implementation
uses
System.SysUtils, System.Variants,
FireDAC.Stan.Intf, FireDAC.Stan.Consts, FireDAC.Stan.Util,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLGenerator, FireDAC.Phys.Meta,
FireDAC.Phys.ODBCCli, FireDAC.Phys.ODBCWrapper, FireDAC.Phys.ODBCMeta,
FireDAC.Phys.ODBCDef
{$IFDEF FireDAC_ODBC_ALLMETA}
, FireDAC.Phys.MSSQLMeta, FireDAC.Phys.MSAccMeta, FireDAC.Phys.DB2Meta,
FireDAC.Phys.OracleMeta, FireDAC.Phys.ASAMeta, FireDAC.Phys.MySQLMeta,
FireDAC.Phys.ADSMeta, FireDAC.Phys.IBMeta, FireDAC.Phys.PGMeta,
FireDAC.Phys.SQLiteMeta, FireDAC.Phys.NexusMeta, FireDAC.Phys.InfxMeta,
FireDAC.Phys.TDataMeta
{$ENDIF}
;
type
TFDPhysODBCDriver = class;
TFDPhysODBCConnection = class;
TFDPhysODBCDriver = class(TFDPhysODBCDriverBase)
protected
class function GetBaseDriverID: String; override;
class function GetBaseDriverDesc: String; override;
class function GetRDBMSKind: TFDRDBMSKind; override;
class function GetConnectionDefParamsClass: TFDConnectionDefParamsClass; override;
function InternalCreateConnection(AConnHost: TFDPhysConnectionHost): TFDPhysConnection; override;
procedure GetODBCConnectStringKeywords(AKeywords: TStrings); override;
function GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable; override;
end;
TFDPhysODBCConnection = class(TFDPhysODBCConnectionBase)
private
FRdbmsKind: TFDRDBMSKind;
FNumericFormat: TFDDataType;
procedure UpdateRDBMSKind;
protected
function InternalCreateCommandGenerator(
const ACommand: IFDPhysCommand): TFDPhysCommandGenerator; override;
function InternalCreateMetadata: TObject; override;
procedure InternalConnect; override;
function GetNumType: TFDDataType; override;
function GetODBCVersion: Integer; override;
public
constructor Create(ADriverObj: TFDPhysDriver; AConnHost: TFDPhysConnectionHost); override;
end;
const
S_FD_Binary = 'Binary';
S_FD_String = 'String';
S_FD_38 = '3.8';
S_FD_30 = '3.0';
{-------------------------------------------------------------------------------}
{ TFDPhysODBCDriverLink }
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriverLink.GetBaseDriverID: String;
begin
Result := S_FD_ODBCId;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCDriver }
{-------------------------------------------------------------------------------}
class function TFDPhysODBCDriver.GetBaseDriverID: String;
begin
Result := S_FD_ODBCId;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysODBCDriver.GetBaseDriverDesc: String;
begin
Result := 'ODBC Data Source';
end;
{-------------------------------------------------------------------------------}
class function TFDPhysODBCDriver.GetRDBMSKind: TFDRDBMSKind;
begin
Result := TFDRDBMSKinds.Other;
end;
{-------------------------------------------------------------------------------}
class function TFDPhysODBCDriver.GetConnectionDefParamsClass: TFDConnectionDefParamsClass;
begin
Result := TFDPhysODBCConnectionDefParams;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriver.InternalCreateConnection(
AConnHost: TFDPhysConnectionHost): TFDPhysConnection;
begin
Result := TFDPhysODBCConnection.Create(Self, AConnHost);
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCDriver.GetODBCConnectStringKeywords(AKeywords: TStrings);
var
i: Integer;
begin
inherited GetODBCConnectStringKeywords(AKeywords);
i := AKeywords.IndexOf('=DRIVER');
if i >= 0 then
AKeywords.Delete(i);
i := AKeywords.IndexOf('DSN');
if i >= 0 then
AKeywords.Delete(i);
AKeywords.Add(S_FD_ConnParam_ODBC_ODBCDriver + '=DRIVER');
AKeywords.Add(S_FD_ConnParam_ODBC_DataSource + '=DSN');
AKeywords.Add(S_FD_ConnParam_Common_Database + '=DBQ');
AKeywords.Add(S_FD_ConnParam_Common_Database + '=DATABASE');
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCDriver.GetConnParams(AKeys: TStrings; AParams: TFDDatSTable): TFDDatSTable;
var
oList: TFDStringList;
oManMeta: IFDPhysManagerMetadata;
begin
Result := inherited GetConnParams(AKeys, AParams);
Employ;
oList := TFDStringList.Create(#0, ';');
try
ODBCEnvironment.GetDrivers(oList, True);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ODBC_ODBCDriver, oList.DelimitedText, '', S_FD_ConnParam_ODBC_ODBCDriver, -1]);
ODBCEnvironment.GetDSNs(oList, False, True);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ODBC_DataSource, oList.DelimitedText, '', S_FD_ConnParam_ODBC_DataSource, 2]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ODBC_NumericFormat, S_FD_Binary + ';' + S_FD_String, S_FD_String, S_FD_ConnParam_ODBC_NumericFormat, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_ODBC_ODBCVersion, S_FD_38 + ';' + S_FD_30, S_FD_30, S_FD_ConnParam_ODBC_ODBCVersion, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefCatalog, '@S', '', S_FD_ConnParam_Common_MetaDefCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaDefSchema, '@S', '', S_FD_ConnParam_Common_MetaDefSchema, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurCatalog, '@S', '', S_FD_ConnParam_Common_MetaCurCatalog, -1]);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_MetaCurSchema, '@S', '', S_FD_ConnParam_Common_MetaCurSchema, -1]);
FDPhysManager.CreateMetadata(oManMeta);
oManMeta.GetRDBMSNames(oList);
Result.Rows.Add([Unassigned, S_FD_ConnParam_Common_RDBMS, oList.DelimitedText, '', S_FD_ConnParam_Common_RDBMS, -1]);
finally
FDFree(oList);
Vacate;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDPhysODBCConnection }
{-------------------------------------------------------------------------------}
constructor TFDPhysODBCConnection.Create(ADriverObj: TFDPhysDriver;
AConnHost: TFDPhysConnectionHost);
begin
inherited Create(ADriverObj, AConnHost);
UpdateRDBMSKind;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnection.UpdateRDBMSKind;
begin
if FRdbmsKind = TFDRDBMSKinds.Unknown then
FRdbmsKind := TFDPhysODBCConnectionDefParams(ConnectionDef.Params).RDBMS;
if (FRdbmsKind = TFDRDBMSKinds.Unknown) and (ODBCConnection <> nil) then
FRdbmsKind := ODBCConnection.RdbmsKind;
end;
{-------------------------------------------------------------------------------}
procedure TFDPhysODBCConnection.InternalConnect;
begin
FRdbmsKind := TFDRDBMSKinds.Unknown;
inherited InternalConnect;
case TFDPhysODBCConnectionDefParams(ConnectionDef.Params).NumericFormat of
nfBinary: FNumericFormat := dtBCD;
nfString: FNumericFormat := dtAnsiString;
end;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnection.GetNumType: TFDDataType;
begin
Result := FNumericFormat;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnection.GetODBCVersion: Integer;
const
C_Vers: array [TFDODBCVersion] of Integer = (SQL_OV_ODBC3_80, SQL_OV_ODBC3);
begin
Result := C_Vers[TFDPhysODBCConnectionDefParams(ConnectionDef.Params).ODBCVersion];
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnection.InternalCreateCommandGenerator(const ACommand:
IFDPhysCommand): TFDPhysCommandGenerator;
begin
UpdateRDBMSKind;
{$IFDEF FireDAC_ODBC_ALLMETA}
if ACommand <> nil then
case FRdbmsKind of
TFDRDBMSKinds.Oracle: Result := TFDPhysOraCommandGenerator.Create(ACommand, False);
TFDRDBMSKinds.MSSQL: Result := TFDPhysMSSQLCommandGenerator.Create(ACommand);
TFDRDBMSKinds.MSAccess: Result := TFDPhysMSAccCommandGenerator.Create(ACommand);
TFDRDBMSKinds.MySQL: Result := TFDPhysMySQLCommandGenerator.Create(ACommand);
TFDRDBMSKinds.Db2: Result := TFDPhysDb2CommandGenerator.Create(ACommand);
TFDRDBMSKinds.SQLAnywhere: Result := TFDPhysASACommandGenerator.Create(ACommand);
TFDRDBMSKinds.Advantage: Result := TFDPhysADSCommandGenerator.Create(ACommand);
TFDRDBMSKinds.Interbase,
TFDRDBMSKinds.Firebird: Result := TFDPhysIBCommandGenerator.Create(ACommand, 0, ecANSI);
TFDRDBMSKinds.PostgreSQL: Result := TFDPhysPgCommandGenerator.Create(ACommand);
TFDRDBMSKinds.SQLite: Result := TFDPhysSQLiteCommandGenerator.Create(ACommand);
TFDRDBMSKinds.NexusDB: Result := TFDPhysNexusCommandGenerator.Create(ACommand);
TFDRDBMSKinds.Informix: Result := TFDPhysInfxCommandGenerator.Create(ACommand);
TFDRDBMSKinds.Teradata: Result := TFDPhysTDataCommandGenerator.Create(ACommand);
else Result := TFDPhysCommandGenerator.Create(ACommand);
end
else
case FRdbmsKind of
TFDRDBMSKinds.Oracle: Result := TFDPhysOraCommandGenerator.Create(Self, False);
TFDRDBMSKinds.MSSQL: Result := TFDPhysMSSQLCommandGenerator.Create(Self);
TFDRDBMSKinds.MSAccess: Result := TFDPhysMSAccCommandGenerator.Create(Self);
TFDRDBMSKinds.MySQL: Result := TFDPhysMySQLCommandGenerator.Create(Self);
TFDRDBMSKinds.Db2: Result := TFDPhysDb2CommandGenerator.Create(Self);
TFDRDBMSKinds.SQLAnywhere: Result := TFDPhysASACommandGenerator.Create(Self);
TFDRDBMSKinds.Advantage: Result := TFDPhysADSCommandGenerator.Create(Self);
TFDRDBMSKinds.Interbase,
TFDRDBMSKinds.Firebird: Result := TFDPhysIBCommandGenerator.Create(Self, 0, ecANSI);
TFDRDBMSKinds.PostgreSQL: Result := TFDPhysPgCommandGenerator.Create(Self);
TFDRDBMSKinds.SQLite: Result := TFDPhysSQLiteCommandGenerator.Create(Self);
TFDRDBMSKinds.NexusDB: Result := TFDPhysNexusCommandGenerator.Create(Self);
TFDRDBMSKinds.Informix: Result := TFDPhysInfxCommandGenerator.Create(Self);
TFDRDBMSKinds.Teradata: Result := TFDPhysTDataCommandGenerator.Create(Self);
else Result := TFDPhysCommandGenerator.Create(Self);
end;
{$ELSE}
if ACommand <> nil then
Result := TFDPhysCommandGenerator.Create(ACommand)
else
Result := TFDPhysCommandGenerator.Create(Self);
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCConnection.InternalCreateMetadata: TObject;
var
iSrvVer, iClntVer: TFDVersion;
begin
GetVersions(iSrvVer, iClntVer);
UpdateRDBMSKind;
{$IFDEF FireDAC_ODBC_ALLMETA}
case FRdbmsKind of
TFDRDBMSKinds.Oracle: Result := TFDPhysOraMetadata.Create(Self, iSrvVer, iClntVer, False);
TFDRDBMSKinds.MSSQL: Result := TFDPhysMSSQLMetadata.Create(Self, False, True, True, True,
(ODBCConnection <> nil) and (ODBCConnection.DriverKind in [dkSQLSrv, dkSQLNC, dkSQLOdbc]),
iSrvVer, iClntVer, False);
TFDRDBMSKinds.MSAccess: Result := TFDPhysMSAccMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords);
TFDRDBMSKinds.MySQL: Result := TFDPhysMySQLMetadata.Create(Self, False, iSrvVer, iClntVer,
[nmCaseSens, nmDBApply], False);
TFDRDBMSKinds.Db2: Result := TFDPhysDb2Metadata.Create(Self, iSrvVer, iClntVer, GetKeywords, False, True);
TFDRDBMSKinds.SQLAnywhere: Result := TFDPhysASAMetadata.Create(Self, iSrvVer, iClntVer, GetKeywords);
TFDRDBMSKinds.Advantage: Result := TFDPhysADSMetadata.Create(Self, iSrvVer, iClntVer, True);
TFDRDBMSKinds.Interbase: Result := TFDPhysIBMetadata.Create(Self, ibInterbase, iSrvVer, iClntVer, 3, False);
TFDRDBMSKinds.Firebird: Result := TFDPhysIBMetadata.Create(Self, ibFirebird, iSrvVer, iClntVer, 3, False);
TFDRDBMSKinds.PostgreSQL: Result := TFDPhysPgMetadata.Create(Self, iSrvVer, iClntVer, False, False, False, True);
TFDRDBMSKinds.SQLite: Result := TFDPhysSQLiteMetadata.Create(Self, sbSQLite, iSrvVer,
iClntVer, False, False);
TFDRDBMSKinds.NexusDB: Result := TFDPhysNexusMetadata.Create(Self, iSrvVer, iClntVer);
TFDRDBMSKinds.Informix: Result := TFDPhysInfxMetadata.Create(Self, iSrvVer, iClntVer,
GetKeywords, False, True);
TFDRDBMSKinds.Teradata: Result := TFDPhysTDataMetadata.Create(Self, iSrvVer, iClntVer,
GetKeywords, True, tmTeradata, '');
else Result := nil;
end;
{$ELSE}
Result := nil;
{$ENDIF}
if (ODBCConnection <> nil) and ODBCConnection.Connected then
Result := TFDPhysODBCMetadata.Create(Self, iSrvVer, iClntVer, TFDPhysConnectionMetadata(Result))
else if Result = nil then
Result := TFDPhysConnectionMetadata.Create(Self, iSrvVer, iClntVer, False);
end;
{-------------------------------------------------------------------------------}
initialization
FDRegisterDriverClass(TFDPhysODBCDriver);
finalization
FDUnregisterDriverClass(TFDPhysODBCDriver);
end.
|
unit printer_context;
interface
uses
printer;
type
TPrinterContext = class
public
procedure executePrint(); virtual; abstract;
end;
TPrinterManager = class(TPrinterContext)
private
FPrinter: TPrinter;
public
// context interface called by client classes
procedure executePrint(); override;
// constructor configures the context object
constructor Create(aPrinter: TPrinter); virtual;
destructor Destroy; override;
end;
implementation
constructor TPrinterManager.Create(aPrinter: TPrinter);
begin
inherited Create;
FPrinter := aPrinter;
end;
destructor TPrinterManager.Destroy;
begin
FPrinter.Free;
inherited Destroy;
end;
procedure TPrinterManager.executePrint;
begin
FPrinter.print();
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{
GLFileMD3 - Code for loading animated MD3 files into GLScene
FreeForms and Actors.
History :
<li>10/11/12 - PW - Added CPP compatibility: changed vector arrays to records
<li>02/08/04 - LR, YHC - BCB corrections: use record instead array
<li>21/08/03 - EG - Fixed GetNormalFromMD3Normal (lat/lon were inverted)
<li>28/02/03 - SG - Creation
}
unit GLFileMD3;
interface
uses
System.Classes, System.SysUtils,
GLVectorFileObjects, GLMaterial, GLApplicationFileIO,
GLVectorGeometry, FileMD3, GLTexture;
type
TGLMD3VectorFile = class (TVectorFile)
public
class function Capabilities : TDataFileCapabilities; override;
procedure LoadFromStream(aStream : TStream); override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------
// ------------------ TGLMD3VectorFile ------------------
// ------------------
// Capabilities
//
class function TGLMD3VectorFile.Capabilities : TDataFileCapabilities;
begin
Result:=[dfcRead];
end;
// LoadFromStream
//
procedure TGLMD3VectorFile.LoadFromStream(aStream : TStream);
var
i,j,k,
numVerts,
numtris : Integer;
MD3File : TFileMD3;
mesh : TMorphableMeshObject;
faceGroup : TFGIndexTexCoordList;
morphTarget : TMeshMorphTarget;
function GetNormalFromMD3Normal(n : array of Byte) : TAffineVector;
var
lat,lng : single;
begin
// The MD3 normal is a latitude/longitude value that needs
// to be calculated into cartesian space.
lat:=(n[1])*(2*pi)/255; lng:=(n[0])*(2*pi)/255;
result.X:=cos(lat)*sin(lng);
result.Y:=sin(lat)*sin(lng);
result.Z:=cos(lng);
end;
procedure AllocateMaterial(meshname:string);
var
LibMat : TGLLibMaterial;
begin
// If a material library is assigned to the actor/freeform the
// mesh name will be added as a material.
if Assigned(Owner.MaterialLibrary) then with Owner.MaterialLibrary do begin
if Assigned(Materials.GetLibMaterialByName(meshname)) then exit;
LibMat:=Materials.Add;
LibMat.name:=meshname;
LibMat.Material.Texture.Disabled:=False;
end;
end;
begin
MD3File:=TFileMD3.Create;
MD3File.LoadFromStream(aStream);
try
for i:=0 to MD3File.ModelHeader.numMeshes-1 do begin
mesh:=TMorphableMeshObject.CreateOwned(Owner.MeshObjects);
mesh.Name:=trim(string(MD3File.MeshData[i].MeshHeader.strName));
with mesh, MD3File do begin
Mode:=momFaceGroups;
faceGroup:=TFGIndexTexCoordList.CreateOwned(FaceGroups);
with faceGroup do begin
AllocateMaterial(mesh.Name);
MaterialName:=mesh.Name;
numTris:=MeshData[i].MeshHeader.numTriangles;
VertexIndices.Capacity:=numTris*3;
TexCoords.Capacity:=numTris*3;
// Get the vertex indices and texture coordinates
for j:=0 to MeshData[i].MeshHeader.numTriangles-1 do begin
with MeshData[i].Triangles[j] do begin
Add(vertexIndices.X,
MeshData[i].TexCoords[vertexIndices.X].textureCoord.X,
1-MeshData[i].TexCoords[vertexIndices.X].textureCoord.Y);
Add(vertexIndices.Z,
MeshData[i].TexCoords[vertexIndices.Z].textureCoord.X,
1-MeshData[i].TexCoords[vertexIndices.Z].textureCoord.Y);
Add(vertexIndices.Y,
MeshData[i].TexCoords[vertexIndices.Y].textureCoord.X,
1-MeshData[i].TexCoords[vertexIndices.Y].textureCoord.Y);
end;
end;
end;
// Get the mesh data for each morph frame
for j:=0 to ModelHeader.numFrames-1 do begin
morphTarget:=TMeshMorphTarget.CreateOwned(MorphTargets);
morphTarget.Name:=Trim(string(MeshData[i].MeshHeader.strName))+'['+IntToStr(j)+']';
numVerts:=MeshData[i].MeshHeader.numVertices;
morphTarget.Vertices.Capacity:=numVerts;
for k:=numVerts*j to numVerts*(j+1)-1 do begin
morphTarget.Vertices.Add(
MeshData[i].Vertices[k].Vertex.X/64,
MeshData[i].Vertices[k].Vertex.Y/64,
MeshData[i].Vertices[k].Vertex.Z/64);
morphTarget.Normals.Add(
GetNormalFromMD3Normal(MeshData[i].Vertices[k].normal.V));
end;
end;
end;
if mesh.MorphTargets.Count>0 then
mesh.MorphTo(0);
end;
finally
MD3File.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterVectorFileFormat('md3', 'MD3 files', TGLMD3VectorFile);
end.
|
{**********************************************************************}
{* Иллюстрация к книге "OpenGL в проектах Delphi" *}
{* Краснов М.В. softgl@chat.ru *}
{**********************************************************************}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OpenGL;
type
TfrmGL = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
hrc: HGLRC;
dc : HDC;
end;
var
frmGL: TfrmGL;
implementation
{$R *.DFM}
{=======================================================================
Перерисовка окна}
procedure TfrmGL.FormPaint(Sender: TObject);
begin
wglMakeCurrent(dc, hrc);
glClearColor (0.5, 0.5, 0.75, 1.0); // цвет фона
glClear (GL_COLOR_BUFFER_BIT); // очистка буфера цвета
glPointSize (20); // размер точек
glColor3f (1.0, 0.0, 0.5); // текущий цвет примитивов
glBegin (GL_POINTS); // открываем командную скобку
glVertex2f (-1, -1);
glVertex2f (-1, 1);
glVertex2f (0, 0);
glVertex2f (1, -1);
glVertex2f (1, 1);
glEnd; // закрываем командную скобку
SwapBuffers(dc); // содержимое буфера - на экран
wglMakeCurrent(0, 0);
end;
{=======================================================================
Формат пикселя}
procedure SetDCPixelFormat (hdc : HDC);
var
pfd : TPixelFormatDescriptor;
nPixelFormat : Integer;
begin
FillChar (pfd, SizeOf (pfd), 0);
pfd.dwFlags := PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER;
nPixelFormat := ChoosePixelFormat (hdc, @pfd);
SetPixelFormat (hdc, nPixelFormat, @pfd);
end;
{=======================================================================
Создание формы}
procedure TfrmGL.FormCreate(Sender: TObject);
begin
dc := GetDC (0);
SetDCPixelFormat(dc);
hrc := wglCreateContext(dc);
end;
{=======================================================================
Конец работы приложения}
procedure TfrmGL.FormDestroy(Sender: TObject);
begin
wglDeleteContext(dc);
InvalidateRect (0, nil, False);
end;
procedure TfrmGL.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
If Key = VK_ESCAPE then Close
end;
end.
|
unit Dlg;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, StdCtrls, Buttons, ToolIntf, ComCtrls;
type
{ These are the set of flags which determine the type of dialog to create }
TDlgAttr = (daNothing, daMultPg, daBtnsH, daBtnsV);
TDlgAttrs = set of TDlgAttr;
TDlgExpert = class(TForm)
Sample: TPaintBox;
CancelBtn: TButton;
PrevButton: TButton;
NextButton: TButton;
PageControl: TPageControl;
Style: TTabSheet;
Label1: TLabel;
rbSinglePage: TRadioButton;
rbMultPg: TRadioButton;
Pages: TTabSheet;
Label3: TLabel;
PageNames: TMemo;
Buttons: TTabSheet;
Label2: TLabel;
RadioButton1: TRadioButton;
rbBtnsV: TRadioButton;
rbBtnsH: TRadioButton;
procedure SamplePaint(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure StyleClick(Sender: TObject);
procedure BtnClick(Sender: TObject);
procedure CancelClick(Sender: TObject);
procedure PrevClick(Sender: TObject);
procedure NextClick(Sender: TObject);
private
{ Private declarations }
Definition: TDlgAttrs;
DrawBitmap: TBitmap;
SourceBuffer: PChar;
procedure RefreshButtons;
procedure FmtWrite(Stream: TStream; Fmt: PChar; const Args: array of const);
function DoFormCreation(const FormIdent: string): TForm;
function CreateSource(const UnitIdent, FormIdent: string): TMemoryStream;
function CreateForm(const FormIdent: string): TMemoryStream;
public
{ Public declarations }
end;
procedure DialogExpert(ToolServices: TIToolServices);
var
DlgExpert: TDlgExpert;
implementation
uses Proxies, VirtIntf, IStreams, ExConst;
{$R *.DFM}
const
{ page numbers }
pgStyle = 0; { multi vs. single page dialog }
pgPages = 1; { page names }
pgButtons = 2; { button layouts }
SourceBufferSize = 1024;
{ TDlgExpert }
{ Paint the sample pane based on the currently selected options }
procedure TDlgExpert.SamplePaint(Sender: TObject);
var
X, Y: Integer;
begin
{ always paint the background dialog }
DrawBitmap.Handle := CreateGrayMappedRes(HInstance, 'DIALOG');
Sample.Canvas.Draw(0, 0, DrawBitmap);
if daMultPg in Definition then
begin
DrawBitmap.Handle := CreateGrayMappedRes(HInstance, 'MULTPG');
Sample.Canvas.Draw(4, 16, DrawBitmap);
end;
if daBtnsV in Definition then
begin
DrawBitmap.Handle := CreateGrayMappedRes(HInstance, 'BTNSV');
X := 75;
Y := 22;
if daMultPg in Definition then
begin
Dec(X, 2);
Inc(Y, 4);
end;
Sample.Canvas.Draw(X, Y, DrawBitmap);
end;
if daBtnsH in Definition then
begin
DrawBitmap.Handle := CreateGrayMappedRes(HInstance, 'BTNSH');
X := 50;
Y := 55;
if daMultPg in Definition then Dec(Y, 4);
Sample.Canvas.Draw(X, Y, DrawBitmap);
end;
end;
procedure TDlgExpert.FormCreate(Sender: TObject);
begin
DrawBitmap := TBitmap.Create;
PrevClick(Self);
RefreshButtons;
end;
procedure TDlgExpert.FormDestroy(Sender: TObject);
begin
DrawBitmap.Free;
end;
procedure TDlgExpert.StyleClick(Sender: TObject);
begin
if rbMultPg.Checked then Include(Definition, daMultPg)
else Exclude(Definition, daMultPg);
SamplePaint(Self);
end;
procedure TDlgExpert.BtnClick(Sender: TObject);
begin
if rbBtnsV.Checked then Include(Definition, daBtnsV)
else Exclude(Definition, daBtnsV);
if rbBtnsH.Checked then Include(Definition, daBtnsH)
else Exclude(Definition, daBtnsH);
SamplePaint(Self);
end;
procedure TDlgExpert.CancelClick(Sender: TObject);
begin
Close;
end;
procedure TDlgExpert.PrevClick(Sender: TObject);
begin
case PageControl.ActivePage.PageIndex of
pgStyle: Exit;
pgPages: PageControl.ActivePage := PageControl.Pages[pgStyle];
pgButtons: if (daMultPg in Definition) then
PageControl.ActivePage := PageControl.Pages[pgPages]
else PageControl.ActivePage := PageControl.Pages[pgStyle];
end;
RefreshButtons;
end;
procedure TDlgExpert.NextClick(Sender: TObject);
begin
case PageControl.ActivePage.PageIndex of
pgStyle: if (daMultPg in Definition) then
PageControl.ActivePage := PageControl.Pages[pgPages]
else PageControl.ActivePage := PageControl.Pages[pgButtons];
pgPages: PageControl.ActivePage := PageControl.Pages[pgButtons];
pgButtons:
begin
ModalResult := mrOK;
Exit;
end;
end;
RefreshButtons;
end;
procedure TDlgExpert.RefreshButtons;
begin
PrevButton.Enabled := PageControl.ActivePage.PageIndex > 0;
if PageControl.ActivePage.PageIndex = pgButtons then
NextButton.Caption := LoadStr(sFinish)
else
NextButton.Caption := LoadStr(sNext);
end;
{ Create the dialog defined by the user }
function TDlgExpert.DoFormCreation(const FormIdent: string): TForm;
var
BtnPos: TPoint;
PgCtrl: TPageControl;
I: Integer;
begin
Result := TForm.Create(nil);
Proxies.CreateSubClass(Result, 'T' + FormIdent, TForm);
with Result do
begin
BorderStyle := bsDialog;
Width := 400;
Height := 250;
Position := poScreenCenter;
Name := FormIdent;
Caption := FormIdent;
{ create controls }
if daMultPg in Definition then
begin
PgCtrl := TPageControl.Create(Result);
with PgCtrl do
begin
Parent := Result;
Name := 'PageControl1';
Align := alClient;
end;
if PageNames.Lines.Count > 0 then
for I := 0 to PageNames.Lines.Count - 1 do
with TTabSheet.Create(Result) do
begin
PageControl := PgCtrl;
Caption := PageNames.Lines[I];
Name := Format('TabSheet%d', [I + 1]);
end;
end;
if (daBtnsH in Definition) or (daBtnsV in Definition) then
begin
{ get the starting point for the buttons }
if daBtnsH in Definition then
BtnPos := Point(ClientWidth - (77 * 3) - (5 * 3),
ClientHeight - 27 - 5)
else
BtnPos := Point(ClientWidth - 77 - 5, 30);
{ finalize positions }
if daMultPg in Definition then
begin
Dec(BtnPos.X, 5);
if daBtnsV in Definition then Inc(BtnPos.Y, 5)
else Dec(BtnPos.Y, 5);
end;
{ OK }
with TButton.Create(Result) do
begin
Parent := Result;
Left := BtnPos.X;
Top := BtnPos.Y;
Height := 25;
Width := 75;
Caption := LoadStr(sOKButton);
Name := 'Button1';
Default := True;
ModalResult := mrOk;
end;
{ move the next button position }
if daBtnsH in Definition then Inc(BtnPos.X, 75 + 5)
else Inc(BtnPos.Y, 25 + 5);
{ Cancel }
with TButton.Create(Result) do
begin
Parent := Result;
Left := BtnPos.X;
Top := BtnPos.Y;
Height := 25;
Width := 75;
Name := 'Button2';
Caption := LoadStr(sCancelButton);
Cancel := True;
ModalResult := mrCancel;
end;
{ move the next button position }
if daBtnsH in Definition then Inc(BtnPos.X, 75 + 5)
else Inc(BtnPos.Y, 25 + 5);
{ Help }
with TButton.Create(Result) do
begin
Parent := Result;
Left := BtnPos.X;
Top := BtnPos.Y;
Height := 25;
Width := 75;
Name := 'Button3';
Caption := LoadStr(sHelpButton);
end;
end;
end;
end;
procedure TDlgExpert.FmtWrite(Stream: TStream; Fmt: PChar;
const Args: array of const);
begin
if (Stream <> nil) and (SourceBuffer <> nil) then
begin
StrLFmt(SourceBuffer, SourceBufferSize, Fmt, Args);
Stream.Write(SourceBuffer[0], StrLen(SourceBuffer));
end;
end;
function TDlgExpert.CreateSource(const UnitIdent, FormIdent: string): TMemoryStream;
const
CRLF = #13#10;
var
I: Integer;
begin
SourceBuffer := StrAlloc(SourceBufferSize);
try
Result := TMemoryStream.Create;
try
{ unit header and uses clause }
FmtWrite(Result,
'unit %s;' + CRLF + CRLF +
'interface' + CRLF + CRLF +
'uses'#13#10 +
' SysUtils, Windows, Messages, Classes, Graphics, Controls,'#13#10 +
' StdCtrls, ExtCtrls, Forms', [UnitIdent]);
{ additional units that may be needed }
if daMultPg in Definition then FmtWrite(Result, ', ComCtrls', [nil]);
FmtWrite(Result, ';' + CRLF + CRLF, [nil]);
{ begin the class declaration }
FmtWrite(Result,
'type'#13#10 +
' T%s = class(TForm)'#13#10, [FormIdent]);
{ add variable declarations }
if (daBtnsH in Definition) or (daBtnsV in Definition) then
begin
FmtWrite(Result,
' Button1: TButton;' + CRLF +
' Button2: TButton;' + CRLF +
' Button3: TButton;' + CRLF, [nil]);
end;
if daMultPg in Definition then
begin
FmtWrite(Result, ' PageControl1: TPageControl;' + CRLF, [nil]);
if PageNames.Lines.Count > 0 then
for I := 0 to PageNames.Lines.Count - 1 do
FmtWrite(Result, ' TabSheet%d: TTabSheet;'#13#10, [I + 1]);
end;
FmtWrite(Result,
' end;' + CRLF + CRLF +
'var' + CRLF +
' %s: T%s;' + CRLF + CRLF +
'implementation' + CRLF + CRLF +
'{$R *.DFM}' + CRLF + CRLF, [FormIdent, FormIdent]);
FmtWrite(Result, 'end.' + CRLF, [nil]);
Result.Position := 0;
except
Result.Free;
raise;
end;
finally
StrDispose(SourceBuffer);
end;
end;
function TDlgExpert.CreateForm(const FormIdent: string): TMemoryStream;
var
DlgForm: TForm;
begin
DlgForm := DoFormCreation(FormIdent);
try
Result := TMemoryStream.Create;
Result.WriteComponentRes(FormIdent, DlgForm);
Result.Position := 0;
finally
DlgForm.Free;
end;
end;
procedure DialogExpert(ToolServices: TIToolServices);
var
D: TDlgExpert;
SourceStream, FormStream: TIMemoryStream;
UnitIdent, FormIdent: string;
FileName: string;
begin
if ToolServices = nil then Exit;
if ToolServices.GetNewModuleName(UnitIdent, FileName) then
begin
D := TDlgExpert.Create(Application);
try
if D.ShowModal = mrOK then
begin
UnitIdent := AnsiLowerCase(UnitIdent);
UnitIdent[1] := Upcase(UnitIdent[1]);
FormIdent := 'Form' + Copy(UnitIdent, 5, 255);
FormStream := TIMemoryStream.Create(D.CreateForm(FormIdent));
SourceStream := TIMemoryStream.Create(D.CreateSource(UnitIdent,
FormIdent));
ToolServices.CreateModule(FileName, SourceStream, FormStream,
[cmAddToProject, cmShowSource, cmShowForm, cmUnNamed,
cmMarkModified]);
end;
finally
D.Free;
end;
end;
end;
end.
|
unit ParameterKindsQuery;
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, DSWrap, BaseEventsQuery;
type
TParameterKindW = class(TDSWrap)
private
FParameterKind: TFieldWrap;
FID: TFieldWrap;
public
constructor Create(AOwner: TComponent); override;
function GetIDByParameterKind(const AParameterKind: String): Integer;
property ParameterKind: TFieldWrap read FParameterKind;
property ID: TFieldWrap read FID;
end;
TQueryParameterKinds = class(TQueryBaseEvents)
private
FW: TParameterKindW;
{ Private declarations }
protected
function CreateDSWrap: TDSWrap; override;
public
constructor Create(AOwner: TComponent); override;
property W: TParameterKindW read FW;
{ Public declarations }
end;
implementation
uses
NotifyEvents;
{$R *.dfm}
constructor TQueryParameterKinds.Create(AOwner: TComponent);
begin
inherited;
FW := FDSWrap as TParameterKindW;
end;
function TQueryParameterKinds.CreateDSWrap: TDSWrap;
begin
Result := TParameterKindW.Create(FDQuery);
end;
constructor TParameterKindW.Create(AOwner: TComponent);
begin
inherited;
FID := TFieldWrap.Create(Self, 'ID', '', True);
FParameterKind := TFieldWrap.Create(Self, 'ParameterKind', 'Тип параметра');
end;
function TParameterKindW.GetIDByParameterKind(const AParameterKind
: String): Integer;
var
V: Variant;
begin
V := FDDataSet.LookupEx(ParameterKind.FieldName, AParameterKind, PKFieldName,
[lxoCaseInsensitive]);
if VarIsNull(V) then
Result := 0
else
Result := V;
end;
end.
|
unit ufrmSysApplicationSettingsOther;
interface
{$I ThsERP.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls, StrUtils,
Vcl.AppEvnts,
Ths.Erp.Helper.Edit, Ths.Erp.Helper.ComboBox, Ths.Erp.Helper.Memo,
ufrmBase, ufrmBaseInputDB, Vcl.Menus, Vcl.Samples.Spin;
type
TfrmSysApplicationSettingsOther = class(TfrmBaseInputDB)
lblIsEdefterAktif: TLabel;
lblVarsayilanSatisCariKod: TLabel;
lblVarsayilanAlisCariKod: TLabel;
chkIsEdefterAktif: TCheckBox;
edtVarsayilanSatisCariKod: TEdit;
edtVarsayilanAlisCariKod: TEdit;
lblIsBolumAmbardaUretimYap: TLabel;
lblIsUretimMuhasebeKaydiOlustursun: TLabel;
lblIsStokSatimdaNegatifeDusebilir: TLabel;
lblIsMalSatisSayilariniGoster: TLabel;
lblIsPcbUretim: TLabel;
lblIsProformaNoGoster: TLabel;
lblIsSatisTakip: TLabel;
lblIsHammaddeGiriseGoreSirala: TLabel;
lblIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle: TLabel;
lblIsTahsilatListesiVirmanli: TLabel;
lblIsOrtalamaVadeSifirsaSevkiyataIzinVerme: TLabel;
lblIsSiparisteTeslimTarihiYazdir: TLabel;
lblIsTeklifAyrintilariniGoster: TLabel;
lblIsFaturaIrsaliyeNoSifirlaBaslasin: TLabel;
lblIsExcelEkliIrsaliyeYazdirma: TLabel;
lblIsAmbarTransferNumarasiOtomatikGelsin: TLabel;
lblIsAmbarTransferOnayliCalissin: TLabel;
chkIsBolumAmbardaUretimYap: TCheckBox;
chkIsUretimMuhasebeKaydiOlustursun: TCheckBox;
chkIsStokSatimdaNegatifeDusebilir: TCheckBox;
chkIsMalSatisSayilariniGoster: TCheckBox;
chkIsPcbUretim: TCheckBox;
chkIsProformaNoGoster: TCheckBox;
chkIsSatisTakip: TCheckBox;
chkIsHammaddeGiriseGoreSirala: TCheckBox;
chkIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle: TCheckBox;
chkIsTahsilatListesiVirmanli: TCheckBox;
chkIsOrtalamaVadeSifirsaSevkiyataIzinVerme: TCheckBox;
chkIsSiparisteTeslimTarihiYazdir: TCheckBox;
chkIsTeklifAyrintilariniGoster: TCheckBox;
chkIsFaturaIrsaliyeNoSifirlaBaslasin: TCheckBox;
chkIsExcelEkliIrsaliyeYazdirma: TCheckBox;
chkIsAmbarTransferNumarasiOtomatikGelsin: TCheckBox;
chkIsAmbarTransferOnayliCalissin: TCheckBox;
procedure FormCreate(Sender: TObject);override;
procedure RefreshData();override;
procedure btnAcceptClick(Sender: TObject);override;
private
public
protected
published
end;
implementation
uses
Ths.Erp.Database.Singleton,
Ths.Erp.Database.Table.SysApplicationSettingsOther;
{$R *.dfm}
procedure TfrmSysApplicationSettingsOther.FormCreate(Sender: TObject);
begin
TSysApplicationSettingsOther(Table).VarsayilanSatisCariKod.SetControlProperty(Table.TableName, edtVarsayilanSatisCariKod);
TSysApplicationSettingsOther(Table).VarsayilanAlisCariKod.SetControlProperty(Table.TableName, edtVarsayilanAlisCariKod);
inherited;
end;
procedure TfrmSysApplicationSettingsOther.RefreshData();
begin
//control içeriğini table class ile doldur
chkIsEdefterAktif.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsEdefterAktif.FieldType, TSysApplicationSettingsOther(Table).IsEdefterAktif.Value);
edtVarsayilanSatisCariKod.Text := FormatedVariantVal(TSysApplicationSettingsOther(Table).VarsayilanSatisCariKod.FieldType, TSysApplicationSettingsOther(Table).VarsayilanSatisCariKod.Value);
edtVarsayilanAlisCariKod.Text := FormatedVariantVal(TSysApplicationSettingsOther(Table).VarsayilanAlisCariKod.FieldType, TSysApplicationSettingsOther(Table).VarsayilanAlisCariKod.Value);
chkIsBolumAmbardaUretimYap.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsBolumAmbardaUretimYap.FieldType, TSysApplicationSettingsOther(Table).IsBolumAmbardaUretimYap.Value);
chkIsUretimMuhasebeKaydiOlustursun.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsUretimMuhasebeKaydiOlustursun.FieldType, TSysApplicationSettingsOther(Table).IsUretimMuhasebeKaydiOlustursun.Value);
chkIsStokSatimdaNegatifeDusebilir.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsStokSatimdaNegatifeDusebilir.FieldType, TSysApplicationSettingsOther(Table).IsStokSatimdaNegatifeDusebilir.Value);
chkIsMalSatisSayilariniGoster.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsMalSatisSayilariniGoster.FieldType, TSysApplicationSettingsOther(Table).IsMalSatisSayilariniGoster.Value);
chkIsPcbUretim.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsPcbUretim.FieldType, TSysApplicationSettingsOther(Table).IsPcbUretim.Value);
chkIsProformaNoGoster.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsProformaNoGoster.FieldType, TSysApplicationSettingsOther(Table).IsProformaNoGoster.Value);
chkIsSatisTakip.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsSatisTakip.FieldType, TSysApplicationSettingsOther(Table).IsSatisTakip.Value);
chkIsHammaddeGiriseGoreSirala.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsHammaddeGiriseGoreSirala.FieldType, TSysApplicationSettingsOther(Table).IsHammaddeGiriseGoreSirala.Value);
chkIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.FieldType, TSysApplicationSettingsOther(Table).IsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.Value);
chkIsTahsilatListesiVirmanli.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsTahsilatListesiVirmanli.FieldType, TSysApplicationSettingsOther(Table).IsTahsilatListesiVirmanli.Value);
chkIsOrtalamaVadeSifirsaSevkiyataIzinVerme.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsOrtalamaVadeSifirsaSevkiyataIzinVerme.FieldType, TSysApplicationSettingsOther(Table).IsOrtalamaVadeSifirsaSevkiyataIzinVerme.Value);
chkIsSiparisteTeslimTarihiYazdir.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsSiparisteTeslimTarihiYazdir.FieldType, TSysApplicationSettingsOther(Table).IsSiparisteTeslimTarihiYazdir.Value);
chkIsTeklifAyrintilariniGoster.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsTeklifAyrintilariniGoster.FieldType, TSysApplicationSettingsOther(Table).IsTeklifAyrintilariniGoster.Value);
chkIsFaturaIrsaliyeNoSifirlaBaslasin.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsFaturaIrsaliyeNoSifirlaBaslasin.FieldType, TSysApplicationSettingsOther(Table).IsFaturaIrsaliyeNoSifirlaBaslasin.Value);
chkIsExcelEkliIrsaliyeYazdirma.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsExcelEkliIrsaliyeYazdirma.FieldType, TSysApplicationSettingsOther(Table).IsExcelEkliIrsaliyeYazdirma.Value);
chkIsAmbarTransferNumarasiOtomatikGelsin.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsAmbarTransferNumarasiOtomatikGelsin.FieldType, TSysApplicationSettingsOther(Table).IsAmbarTransferNumarasiOtomatikGelsin.Value);
chkIsAmbarTransferOnayliCalissin.Checked := FormatedVariantVal(TSysApplicationSettingsOther(Table).IsAmbarTransferOnayliCalissin.FieldType, TSysApplicationSettingsOther(Table).IsAmbarTransferOnayliCalissin.Value);
end;
procedure TfrmSysApplicationSettingsOther.btnAcceptClick(Sender: TObject);
begin
if (FormMode = ifmNewRecord) or (FormMode = ifmCopyNewRecord) or (FormMode = ifmUpdate) then
begin
if (ValidateInput) then
begin
TSysApplicationSettingsOther(Table).IsEdefterAktif.Value := chkIsEdefterAktif.Checked;
TSysApplicationSettingsOther(Table).VarsayilanSatisCariKod.Value := edtVarsayilanSatisCariKod.Text;
TSysApplicationSettingsOther(Table).VarsayilanAlisCariKod.Value := edtVarsayilanAlisCariKod.Text;
TSysApplicationSettingsOther(Table).IsBolumAmbardaUretimYap.Value := chkIsBolumAmbardaUretimYap.Checked;
TSysApplicationSettingsOther(Table).IsUretimMuhasebeKaydiOlustursun.Value := chkIsUretimMuhasebeKaydiOlustursun.Checked;
TSysApplicationSettingsOther(Table).IsStokSatimdaNegatifeDusebilir.Value := chkIsStokSatimdaNegatifeDusebilir.Checked;
TSysApplicationSettingsOther(Table).IsMalSatisSayilariniGoster.Value := chkIsMalSatisSayilariniGoster.Checked;
TSysApplicationSettingsOther(Table).IsPcbUretim.Value := chkIsPcbUretim.Checked;
TSysApplicationSettingsOther(Table).IsProformaNoGoster.Value := chkIsProformaNoGoster.Checked;
TSysApplicationSettingsOther(Table).IsSatisTakip.Value := chkIsSatisTakip.Checked;
TSysApplicationSettingsOther(Table).IsHammaddeGiriseGoreSirala.Value := chkIsHammaddeGiriseGoreSirala.Checked;
TSysApplicationSettingsOther(Table).IsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.Value := chkIsUretimEntegrasyonHammaddeKullanimHesabiIscilikle.Checked;
TSysApplicationSettingsOther(Table).IsTahsilatListesiVirmanli.Value := chkIsTahsilatListesiVirmanli.Checked;
TSysApplicationSettingsOther(Table).IsOrtalamaVadeSifirsaSevkiyataIzinVerme.Value := chkIsOrtalamaVadeSifirsaSevkiyataIzinVerme.Checked;
TSysApplicationSettingsOther(Table).IsSiparisteTeslimTarihiYazdir.Value := chkIsSiparisteTeslimTarihiYazdir.Checked;
TSysApplicationSettingsOther(Table).IsTeklifAyrintilariniGoster.Value := chkIsTeklifAyrintilariniGoster.Checked;
TSysApplicationSettingsOther(Table).IsFaturaIrsaliyeNoSifirlaBaslasin.Value := chkIsFaturaIrsaliyeNoSifirlaBaslasin.Checked;
TSysApplicationSettingsOther(Table).IsExcelEkliIrsaliyeYazdirma.Value := chkIsExcelEkliIrsaliyeYazdirma.Checked;
TSysApplicationSettingsOther(Table).IsAmbarTransferNumarasiOtomatikGelsin.Value := chkIsAmbarTransferNumarasiOtomatikGelsin.Checked;
TSysApplicationSettingsOther(Table).IsAmbarTransferOnayliCalissin.Value := chkIsAmbarTransferOnayliCalissin.Checked;
inherited;
end;
end
else
inherited;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit,
cxNavigator, DB, cxDBData, dxmdaset, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid;
type
TcxMyGridTablePainter = class(TcxGridTablePainter)
protected
procedure DrawBackground; override;
end;
TcxMyGridDBTableView = class(TcxGridDBTableView)
protected
function GetPainterClass: TcxCustomGridPainterClass; override;
end;
TcxGridDBTableView = class(TcxMyGridDBTableView);
TForm1 = class(TForm)
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1DBTableView1RecId: TcxGridDBColumn;
cxGrid1DBTableView1ID: TcxGridDBColumn;
cxGrid1DBTableView1Name: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
DataSource1: TDataSource;
dxMemData1: TdxMemData;
dxMemData1ID: TIntegerField;
dxMemData1Name: TStringField;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
{ TcxMyGridDBTableView }
function TcxMyGridDBTableView.GetPainterClass: TcxCustomGridPainterClass;
begin
Result := TcxMyGridTablePainter;
end;
{ TcxMyGridTablePainter }
procedure TcxMyGridTablePainter.DrawBackground;
var
AView: TcxGridDBTableView;
I, AWidth, AHeight: Integer;
begin
AView := ViewInfo.GridView as TcxGridDBTableView;
AWidth := 0;
AHeight := 0;
inherited;
for I := 0 to AView.VisibleColumnCount - 1 do
begin
// AWidth := AWidth + AView.VisibleColumns[I].Width;
AWidth := AWidth + AView.ViewInfo.HeaderViewInfo.Items[I].Width;
Canvas.MoveTo(AWidth - 1, 0);
Canvas.LineTo(AWidth - 1, TcxGrid(AView.Owner).Height);
end;
{ while AHeight < TcxGrid(AView.Owner).Height do
begin
AHeight := AHeight + 18;
Canvas.MoveTo(0, AHeight - 1 );
Canvas.LineTo(AWidth - 1, AHeight - 1);
end;}
end;
end.
|
(*
Name: KPUninstallVisualKeyboard
Copyright: Copyright (C) SIL International.
Documentation:
Description:
Create Date: 3 May 2011
Modified Date: 3 Feb 2015
Authors: mcdurdin
Related Files:
Dependencies:
Bugs:
Todo:
Notes:
History: 03 May 2011 - mcdurdin - I2890 - Record diagnostic data when encountering registry errors
01 May 2014 - mcdurdin - I4181 - V9.0 - Stop using DeleteFileAlways, MOVEFILE_DELAY_UNTIL_REBOOT
03 Feb 2015 - mcdurdin - I4574 - V9.0 - If any files are read-only, they need the read-only flag removed on install
*)
unit KPUninstallVisualKeyboard;
interface
uses kpbase;
type
TKPUninstallVisualKeyboard = class(TKPBase)
public
procedure Execute(KeyboardName: string);
end;
implementation
uses windows, classes, sysutils, ErrorControlledRegistry, isadmin, registrykeys,
utilkeyman, utildir, keymanerrorcodes, Variants;
procedure TKPUninstallVisualKeyboard.Execute(KeyboardName: string);
var
FInstByAdmin: Boolean;
KeyboardFullName, Filename: string;
begin
Filename := '';
KeyboardName := GetShortKeyboardName(KeyboardName);
if not KeyboardInstalled(KeyboardName, FInstByAdmin) then
ErrorFmt(KMN_E_Uninstall_InvalidKeyboard, VarArrayOf([KeyboardName]));
KeyboardFullName := GetKeyboardFullName(FInstByAdmin, KeyboardName);
{ Check if keyboard was installed by administrator, and if user has permission to delete it }
if FInstByAdmin and not IsAdministrator then
ErrorFmt(KMN_E_Uninstall_AdminKeyboardInstalled, VarArrayOf([KeyboardName]));
{ Find install path }
with TRegistryErrorControlled.Create do // I2890
try
if FInstByAdmin // as determined by where the keyboard was installed
then RootKey := HKEY_LOCAL_MACHINE
else RootKey := HKEY_CURRENT_USER;
if OpenKey('\'+SRegKey_InstalledKeyboards+'\'+KeyboardName, False) and
ValueExists(SRegValue_VisualKeyboard) then
FileName := ReadString(SRegValue_VisualKeyboard)
else
ErrorFmt(KMN_E_Uninstall_InvalidKeyboard, VarArrayOf([KeyboardFullName]));
DeleteValue(SRegValue_VisualKeyboard);
finally
Free;
end;
{ Delete .kvk file }
if not DeleteFileCleanAttr(FileName) then // I4181 // I4574
begin
WarnFmt(KMN_W_UninstallFileInUse, VarArrayOf([FileName]));
end;
Context.Control.AutoApplyKeyman;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.