text stringlengths 14 6.51M |
|---|
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
unit archivos;
interface
uses
Sysutils;
function insertarlista (var l: tLista; var x: tContacto):boolean;
function buscarLista(var lista:tLista; buscado:string; var salida:pNodo):boolean;
procedure removerLista(var lista:tLista; buscado:string; var x:tContacto; var exito:boolean);
function obtenerItem(lista:tLista; nodo:pNodo):tContacto;
procedure recorrerLista(lista:tLista);
implementation
procedure ordenar(var v:vector; var lim: word);
var
aux:tcontacto;
i:word;
j:word;
begin
for i := 1 to lim do
begin
for j := 1 to lim do
begin
if (v[i].apellido >= v[j].apellido) then
begin
aux := v[i];
v[i] := v[j];
v[i] := aux;
end;
end;
end;
end;
function insertarlista (var l: tLista; var x: tContacto):boolean;
var dir: pNodo; ant: pNodo; act : pNodo;
begin
seekEOF(archivo);
ordenar(archivo);
end; // #FIN DE INSERTARLISTA()
function abrirArchivo(var archivo:TextFile; ruta:string):boolean;
begin
{$I-}
{try
reset(archivo);
finally
try
assignFile(archivo, ruta);
reset(archivo);
finally
abrirArchivo := false;
end; // ### FIN DE TRY 2
end; // ### FIN DE TRY 1}
assignFile(archivo, ruta);
reset(archivo);
abrirArchivo := true;
{$I+}
end; // ### FIN DE abrirArchivo
procedure cerrarArchivo(var archivo:TextFile);
begin
closeFile(archivo);
end;
function leer(var archivo:TextFile; ):char;
var
salida:char;
begin
if (not eof(archivo)) then
begin
read(archivo, salida);
leerCaracter := salida;
end;
end;
initialization
begin
function abrirArchivo(var archivo:TextFile; ruta:string):boolean;
procedure cerrarArchivo(var archivo:TextFile);
function leerCaracter(var archivo:TextFile):char;
end; // ### FIN DE INITIALIZATION
end. // ### FIN DE IMPLEMENTATION
|
unit dao.Notificacao;
interface
uses
UConstantes,
classes.ScriptDDL,
model.Notificacao,
System.StrUtils,
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FireDAC.Comp.Client, FireDAC.Comp.DataSet;
type
TNotificacaoDao = class(TObject)
strict private
class var aInstance : TNotificacaoDao;
private
aDDL : TScriptDDL;
aModel : TNotificacao;
aLista : TNotificacoes;
aOperacao : TTipoOperacaoDao;
constructor Create();
procedure SetValues(const aDataSet : TFDQuery; const aObject : TNotificacao);
procedure ClearLista;
public
property Model : TNotificacao read aModel write aModel;
property Lista : TNotificacoes read aLista write aLista;
property Operacao : TTipoOperacaoDao read aOperacao;
procedure Load(const aBusca : String);
procedure Insert();
procedure Update();
procedure Delete();
procedure MarkRead();
procedure Limpar();
procedure AddLista; overload;
procedure AddLista(aNotificacao : TNotificacao); overload;
function Find(const aCodigo : Currency; const IsLoadModel : Boolean) : Boolean;
function GetCount() : Integer;
function GetCountNotRead() : Integer;
class function GetInstance : TNotificacaoDao;
end;
implementation
{ TNotificacaoDao }
uses
UDM;
procedure TNotificacaoDao.AddLista;
var
I : Integer;
o : TNotificacao;
begin
I := High(aLista) + 2;
o := TNotificacao.Create;
if (I <= 0) then
I := 1;
SetLength(aLista, I);
aLista[I - 1] := o;
end;
procedure TNotificacaoDao.AddLista(aNotificacao: TNotificacao);
var
I : Integer;
begin
I := High(aLista) + 2;
if (I <= 0) then
I := 1;
SetLength(aLista, I);
aLista[I - 1] := aNotificacao;
end;
procedure TNotificacaoDao.ClearLista;
begin
SetLength(aLista, 0);
end;
constructor TNotificacaoDao.Create;
begin
inherited Create;
aDDL := TScriptDDL.GetInstance;
aModel := TNotificacao.Create;
aOperacao := TTipoOperacaoDao.toBrowser;
SetLength(aLista, 0);
end;
procedure TNotificacaoDao.Delete;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Delete from ' + aDDL.getTableNameNotificacao);
SQL.Add('where id_notificacao = :id_notificacao ');
SQL.EndUpdate;
ParamByName('id_notificacao').AsString := GUIDToString(aModel.ID);
ExecSQL;
aOperacao := TTipoOperacaoDao.toExcluido;
end;
finally
aQry.DisposeOf;
end;
end;
function TNotificacaoDao.Find(const aCodigo: Currency; const IsLoadModel: Boolean): Boolean;
var
aQry : TFDQuery;
aRetorno : Boolean;
begin
aRetorno := False;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select');
SQL.Add(' c.* ');
SQL.Add('from ' + aDDL.getTableNameNotificacao + ' c');
SQL.Add('where c.cd_notificacao = ' + CurrToStr(aCodigo));
SQL.EndUpdate;
if aQry.OpenOrExecute then
begin
aRetorno := (aQry.RecordCount > 0);
if aRetorno and IsLoadModel then
SetValues(aQry, aModel);
end;
aQry.Close;
end;
aOperacao := TTipoOperacaoDao.toBrowser;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
function TNotificacaoDao.GetCount: Integer;
var
aRetorno : Integer;
aQry : TFDQuery;
begin
aRetorno := 0;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select ');
SQL.Add(' count(*) as qt_notificacoes');
SQL.Add('from ' + aDDL.getTableNameNotificacao);
SQL.EndUpdate;
OpenOrExecute;
aRetorno := FieldByName('qt_notificacoes').AsInteger;
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
function TNotificacaoDao.GetCountNotRead: Integer;
var
aRetorno : Integer;
aQry : TFDQuery;
begin
aRetorno := 0;
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select ');
SQL.Add(' count(*) as qt_notificacoes');
SQL.Add('from ' + aDDL.getTableNameNotificacao);
SQL.Add('where sn_lida = :sn_lida');
SQL.EndUpdate;
ParamByName('sn_lida').AsString := 'N';
OpenOrExecute;
aRetorno := FieldByName('qt_notificacoes').AsInteger;
aQry.Close;
end;
finally
aQry.DisposeOf;
Result := aRetorno;
end;
end;
class function TNotificacaoDao.GetInstance: TNotificacaoDao;
begin
if not Assigned(aInstance) then
aInstance := TNotificacaoDao.Create();
Result := aInstance;
end;
procedure TNotificacaoDao.Insert;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Insert Into ' + aDDL.getTableNameNotificacao + '(');
SQL.Add(' id_notificacao ');
SQL.Add(' , cd_notificacao ');
SQL.Add(' , dt_notificacao ');
SQL.Add(' , ds_titulo ');
SQL.Add(' , ds_mensagem ');
SQL.Add(' , sn_lida ');
SQL.Add(' , sn_destacar ');
SQL.Add(') values (');
SQL.Add(' :id_notificacao ');
SQL.Add(' , :cd_notificacao ');
SQL.Add(' , :dt_notificacao ');
SQL.Add(' , :ds_titulo ');
SQL.Add(' , :ds_mensagem ');
SQL.Add(' , :sn_lida ');
SQL.Add(' , :sn_destacar ');
SQL.Add(')');
SQL.EndUpdate;
if (aModel.ID = GUID_NULL) then
aModel.NewID;
if (aModel.Codigo = 0) then
aModel.Codigo := GetNewID(aDDL.getTableNameNotificacao, 'cd_notificacao', EmptyStr);
ParamByName('id_notificacao').AsString := GUIDToString(aModel.ID);
ParamByName('cd_notificacao').AsCurrency := aModel.Codigo;
ParamByName('dt_notificacao').AsDateTime := aModel.Data;
ParamByName('ds_titulo').AsString := aModel.Titulo;
ParamByName('ds_mensagem').AsString := aModel.Mensagem;
ParamByName('sn_lida').AsString := IfThen(aModel.Lida, 'S', 'N');
ParamByName('sn_destacar').AsString := IfThen(aModel.Destacar, 'S', 'N');
ExecSQL;
aOperacao := TTipoOperacaoDao.toIncluido;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TNotificacaoDao.Limpar;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Delete from ' + aDDL.getTableNameNotificacao);
SQL.EndUpdate;
ExecSQL;
aOperacao := TTipoOperacaoDao.toExcluir;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TNotificacaoDao.Load(const aBusca: String);
var
aQry : TFDQuery;
aNotificacao : TNotificacao;
aFiltro : String;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
aFiltro := AnsiUpperCase(Trim(aBusca));
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Select');
SQL.Add(' c.* ');
SQL.Add('from ' + aDDL.getTableNameNotificacao + ' c');
if (StrToCurrDef(aFiltro, 0) > 0) then
SQL.Add('where c.cd_notificacao = ' + aFiltro)
else
if (Trim(aBusca) <> EmptyStr) then
begin
aFiltro := '%' + StringReplace(aFiltro, ' ', '%', [rfReplaceAll]) + '%';
SQL.Add('where (c.ds_titulo like ' + QuotedStr(aFiltro) + ')');
SQL.Add(' or (c.ds_mensagem like ' + QuotedStr(aFiltro) + ')');
end;
SQL.Add('order by');
SQL.Add(' c.dt_notificacao DESC');
SQL.EndUpdate;
if aQry.OpenOrExecute then
begin
ClearLista;
if (aQry.RecordCount > 0) then
while not aQry.Eof do
begin
aNotificacao := TNotificacao.Create;
SetValues(aQry, aNotificacao);
AddLista(aNotificacao);
aQry.Next;
end;
end;
aQry.Close;
end;
aOperacao := TTipoOperacaoDao.toBrowser;
finally
aQry.DisposeOf;
end;
end;
procedure TNotificacaoDao.MarkRead;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Update ' + aDDL.getTableNameNotificacao + ' Set');
SQL.Add(' sn_lida = :sn_lida ');
SQL.Add('where id_notificacao = :id_notificacao ');
SQL.EndUpdate;
ParamByName('id_notificacao').AsString := GUIDToString(aModel.ID);
ParamByName('sn_lida').AsString := IfThen(aModel.Lida, 'S', 'N');
ExecSQL;
aOperacao := TTipoOperacaoDao.toEditado;
end;
finally
aQry.DisposeOf;
end;
end;
procedure TNotificacaoDao.SetValues(const aDataSet: TFDQuery; const aObject: TNotificacao);
begin
with aDataSet, aObject do
begin
ID := StringToGUID(FieldByName('id_notificacao').AsString);
Codigo := FieldByName('cd_notificacao').AsCurrency;
Data := FieldByName('dt_notificacao').AsDateTime;
Titulo := FieldByName('ds_titulo').AsString;
Mensagem := FieldByName('ds_mensagem').AsString;
Lida := (AnsiUpperCase(FieldByName('sn_lida').AsString) = 'S');
Destacar := (AnsiUpperCase(FieldByName('sn_destacar').AsString) = 'S');
end;
end;
procedure TNotificacaoDao.Update;
var
aQry : TFDQuery;
begin
aQry := TFDQuery.Create(DM);
try
aQry.Connection := DM.conn;
aQry.Transaction := DM.trans;
aQry.UpdateTransaction := DM.trans;
with DM, aQry do
begin
SQL.BeginUpdate;
SQL.Add('Update ' + aDDL.getTableNameNotificacao + ' Set');
SQL.Add(' cd_notificacao = :cd_notificacao ');
SQL.Add(' , dt_notificacao = :dt_notificacao ');
SQL.Add(' , ds_titulo = :ds_titulo ');
SQL.Add(' , ds_mensagem = :ds_mensagem ');
SQL.Add(' , sn_lida = :sn_lida ');
SQL.Add(' , sn_destacar = :sn_destacar ');
SQL.Add('where id_notificacao = :id_notificacao ');
SQL.EndUpdate;
ParamByName('id_notificacao').AsString := GUIDToString(aModel.ID);
ParamByName('cd_notificacao').AsCurrency := aModel.Codigo;
ParamByName('dt_notificacao').AsDateTime := aModel.Data;
ParamByName('ds_titulo').AsString := aModel.Titulo;
ParamByName('ds_mensagem').AsString := aModel.Mensagem;
ParamByName('sn_lida').AsString := IfThen(aModel.Lida, 'S', 'N');
ParamByName('sn_destacar').AsString := IfThen(aModel.Destacar, 'S', 'N');
ExecSQL;
aOperacao := TTipoOperacaoDao.toEditado;
end;
finally
aQry.DisposeOf;
end;
end;
end.
|
unit uEstadoDto;
interface
type
TEstadoDto = class
private
FUF: String;
FIdUF: Integer;
FNome: String;
procedure SetIdUF(const Value: Integer);
procedure SetNome(const Value: String);
procedure SetUF(const Value: String);
public
property IdUF: Integer read FIdUF write SetIdUF;
property Nome: String read FNome write SetNome;
property UF: String read FUF write SetUF;
end;
implementation
{ TEstadoDto }
procedure TEstadoDto.SetIdUF(const Value: Integer);
begin
FIdUF := Value;
end;
procedure TEstadoDto.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TEstadoDto.SetUF(const Value: String);
begin
FUF := Value;
end;
end.
|
unit CommandRegistry;
interface
uses
Vcl.forms,
classes, IdContext, IdCustomHTTPServer, generics.collections,
System.SysUtils;
type
TRESTCommandClass = class of TRESTCommand;
TRESTCommandREG = class;
TRESTCommand = class
private
FParams: TStringList;
FContext: TIdContext;
FRequestInfo: TIdHTTPRequestInfo;
FResponseInfo: TIdHTTPResponseInfo;
FReg: TRESTCommandREG;
FStreamContents: String;
procedure ParseParams(const AURI, AMask:String);
procedure ReadStream(ARequestInfo: TIdHTTPRequestInfo);
public
class function GetCommand: String; virtual;
class function GetRoute: String; virtual;
constructor Create;
procedure Start(AReg: TRESTCommandREG; AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; AParams: TStringList);
procedure Execute(AOwner: TForm); virtual;
procedure ResponseJSON(Json: String);
procedure Error(code: integer);
destructor Destroy; override;
property Context: TIdContext read FContext;
property RequestInfo: TIdHTTPRequestInfo read FRequestInfo;
property ResponseInfo: TIdHTTPResponseInfo read FResponseInfo;
property Params: TStringList read FParams;
property StreamContents : String read FStreamContents;
property Reg: TRESTCommandREG read FReg;
end;
TRESTCommandREG = class
public
FTYPE: String;
FPATH: String;
FCommand: TRESTCommandClass;
FHost: TForm; // TComponent;
constructor Create(ATYPE:String; APATH: String; ACommand: TRESTCommandClass);
end;
THttpServerCommandRegister=class(TComponent)
private
FList: TObjectList<TRESTCommandREG>;
public
procedure Register(ATYPE:String; APATH: String; ACommand: TRESTCommandClass); overload;
procedure Register(ACommand: TRESTCommandClass); overload;
constructor Create(AOwner: TComponent); override;
function isUri(AURI: String; AMask: String; AParams: TStringList): boolean;
function FindCommand(ACommand: String; AURI: String; Params: TStringList): TRESTCommandREG;
destructor Destroy; override;
end;
implementation
uses
RegularExpressions;
{ THttpServerCommandRegister }
constructor THttpServerCommandRegister.Create(AOwner: TComponent);
begin
inherited;
FList:= TObjectList<TRESTCommandREG>.Create(True);
end;
destructor THttpServerCommandRegister.Destroy;
begin
FList.Free;
inherited;
end;
function THttpServerCommandRegister.FindCommand(ACommand, AURI: String; Params: TStringList): TRESTCommandREG;
var
I: Integer;
begin
for I := 0 to FList.Count-1 do
begin
if SameText(ACommand,FList[i].FTYPE) then
begin
if isURI(AURI,FList[i].FPATH, Params) then
begin
exit(FList[i]);
end;
end;
end;
result:= nil;
end;
function THttpServerCommandRegister.isUri(AURI, AMask: String; AParams: TStringList): boolean;
var
x: Integer;
M : TMatch;
begin
result := TRegEx.IsMatch(AURI, AMask);
M := TRegEx.Match(AURI, AMask);
for x := 0 to M.Groups.Count-1 do
begin
AParams.Add(M.Groups[x].Value);
end;
end;
procedure THttpServerCommandRegister.Register(ATYPE, APATH: String; ACommand: TRESTCommandClass);
begin
FList.Add(TRESTCommandREG.Create(ATYPE, APATH, ACommand));
end;
procedure THttpServerCommandRegister.Register(ACommand: TRESTCommandClass);
begin
FList.Add(TRESTCommandREG.Create(ACommand.GetCommand, ACommand.GetRoute, ACommand));
end;
{ TRESTCommandREG }
constructor TRESTCommandREG.Create(ATYPE, APATH: String; ACommand: TRESTCommandClass);
begin
FTYPE := AType;
FPATH := APATH;
FCommand := ACommand;
end;
{ TRESTCommand }
class function TRESTCommand.GetCommand: String;
begin
result := '';
end;
class function TRESTCommand.GetRoute: String;
begin
result := '';
end;
constructor TRESTCommand.create;
begin
FParams:= TStringList.Create;
end;
procedure TRESTCommand.ReadStream(ARequestInfo: TIdHTTPRequestInfo);
var
oStream : TStringStream;
begin
// Decode stream
if ArequestInfo.PostStream <> nil then
begin
oStream := TStringStream.create;
try
oStream.CopyFrom(ArequestInfo.PostStream, ArequestInfo.PostStream.Size);
oStream.Position := 0;
FStreamContents := oStream.readString(oStream.Size);
finally
oStream.free;
end;
end;
end;
procedure TRESTCommand.Start(AReg: TRESTCommandREG; AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo; AParams: TStringList);
begin
FContext:= AContext;
FRequestInfo:= ARequestInfo;
FResponseInfo:= AResponseInfo;
FReg:= AReg;
FParams.Assign(AParams);
ParseParams(ARequestInfo.URI, AReg.FPATH);
ReadStream(ARequestInfo);
end;
destructor TRESTCommand.Destroy;
begin
FParams.free;
inherited;
end;
procedure TRESTCommand.Execute(AOwner: TForm);
begin
end;
procedure TRESTCommand.ParseParams(const AURI, AMask: String);
var
x: Integer;
M : TMatch;
begin
M := TRegEx.Match(AURI, AMask);
for x := 0 to M.Groups.Count-1 do
begin
FParams.Add(M.Groups[x].Value);
end;
end;
procedure TRESTCommand.ResponseJSON(Json: String);
begin
ResponseInfo.ContentText := Json;
ResponseInfo.ContentType := 'Application/JSON';
end;
procedure TRESTCommand.Error(code: integer);
begin
ResponseInfo.ResponseNo := code;
end;
end.
|
unit Fluid;
interface
uses Registrator, BaseObjects, Classes;
type
TFluidCharacteristic = class(TRegisteredIDObject)
public
constructor Create(ACollection: TIDObjects); override;
end;
TFluidCharacteristics = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TFluidCharacteristic;
public
property Items[Index: integer]: TFluidCharacteristic read GetItems;
constructor Create; override;
end;
TFluidType = class(TRegisteredIDObject)
private
FBalanceFluid: integer;
protected
procedure AssignTo(Dest: TPersistent); override;
public
property BalanceFluid: integer read FBalanceFluid write FBalanceFluid;
function List(AListOption: TListOption = loBrief): string; override;
constructor Create(ACollection: TIDObjects); override;
end;
TFluidTypes = class(TRegisteredIDObjects)
private
function GetItems(Index: integer): TFluidType;
public
procedure Reload; override;
property Items[Index: integer]: TFluidType read GetItems;
constructor Create; override;
end;
implementation
uses Facade, FluidPoster;
{ TFluidType }
procedure TFluidType.AssignTo(Dest: TPersistent);
var o : TFluidType;
begin
inherited;
o := Dest as TFluidType;
o.BalanceFluid := BalanceFluid;
end;
constructor TFluidType.Create(ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Тип флюида';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TFluidTypeDataPoster];
BalanceFluid := 0;
end;
function TFluidType.List(AListOption: TListOption): string;
begin
Result := Name;
end;
{ TFluidTypes }
constructor TFluidTypes.Create;
begin
inherited;
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TFluidTypeDataPoster];
FObjectClass := TFluidType;
end;
function TFluidTypes.GetItems(Index: integer): TFluidType;
begin
Result := inherited Items[Index] as TFluidType;
end;
procedure TFluidTypes.Reload;
begin
if Assigned (FDataPoster) then
begin
FDataPoster.GetFromDB('', Self);
FDataPoster.SaveState(PosterState);
end;
end;
{ TTestIntervalFluidCharacteristics }
constructor TFluidCharacteristics.Create;
begin
inherited;
FObjectClass := TFluidCharacteristic;
Poster := TMainFacade.GetInstance.DataPosterByClassType[TFluidCharacteristicDataPoster];
end;
function TFluidCharacteristics.GetItems(
Index: integer): TFluidCharacteristic;
begin
Result := inherited Items[Index] as TFluidCharacteristic;
end;
{ TTestIntervalFluidCharacteristic }
constructor TFluidCharacteristic.Create(
ACollection: TIDObjects);
begin
inherited;
ClassIDString := 'Характеристика типа флюида интервала испытания';
FDataPoster := TMainFacade.GetInstance.DataPosterByClassType[TFluidCharacteristicDataPoster];
end;
end.
|
unit uRelatorioGrossMargin;
interface
uses
System.IOUtils,
System.DateUtils,
dxSpreadSheet,
dxSpreadSheetTypes,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxSkinsCore,
dxSkinscxPCPainter, dxBarBuiltInMenu, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, cxContainer, cxClasses, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf,
FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxCustomPivotGrid, cxDBPivotGrid, cxLabel,
dxGDIPlusClasses, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridCustomView,
cxGrid, cxPC, dxSkinsDefaultPainters, dxSkinOffice2013White, Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, Vcl.StdCtrls,
cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, cxCheckBox, cxCheckComboBox, FireDAC.Comp.ScriptCommands,
FireDAC.Comp.Script, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel,
dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMetropolis, dxSkinMetropolisDark, dxSkinMoneyTwins,
dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green,
dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black,
dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013DarkGray,
dxSkinOffice2013LightGray, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic,
dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust,
dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010,
dxSkinWhiteprint, dxSkinXmas2008Blue,cxGridExportLink, cxButtonEdit,
Vcl.ImgList,ShellApi;
type
TFr_RelatorioGrossMargin = class(TForm)
FDConnection: TFDConnection;
FDQueryVSOP_OrderBilling00: TFDQuery;
DataSourceVSOP_OrderBilling00: TDataSource;
cxPageControlFiltro: TcxPageControl;
FDQueryVSOP_OrderBilling00SITE: TStringField;
FDQueryVSOP_OrderBilling00CANAL: TStringField;
FDQueryVSOP_OrderBilling00COD_CLIENTE: TStringField;
FDQueryVSOP_OrderBilling00RAZAO_SOCIAL: TStringField;
FDQueryVSOP_OrderBilling00GRUPO_CLIENTE: TStringField;
FDQueryVSOP_OrderBilling00ACC_OWNER: TStringField;
FDQueryVSOP_OrderBilling00COD_ITEM: TStringField;
FDQueryVSOP_OrderBilling00MTO_MTS: TStringField;
FDQueryVSOP_OrderBilling00FY: TIntegerField;
FDQueryVSOP_OrderBilling00QTR: TStringField;
FDQueryVSOP_OrderBilling00DTREF: TSQLTimeStampField;
FDQueryVSOP_OrderBilling00COST_LOT_SIZE: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_VENDAS_QTD: TFloatField;
FDQueryVSOP_OrderBilling00UOM: TStringField;
FDQueryVSOP_OrderBilling00NET_SALE: TFloatField;
FDQueryVSOP_OrderBilling00MATERIAL_SETUP: TFloatField;
FDQueryVSOP_OrderBilling00MATERIAL_RESALE_RUN_SCRAP: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_MATERIAL: TFloatField;
FDQueryVSOP_OrderBilling00MACHINE_SETUP: TFloatField;
FDQueryVSOP_OrderBilling00MACHINE_RUN: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_MACHINE: TFloatField;
FDQueryVSOP_OrderBilling00LABOR_SETUP: TFloatField;
FDQueryVSOP_OrderBilling00LABOR_RUN: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_LABOR: TFloatField;
FDQueryVSOP_OrderBilling00DIRECT_COST: TFloatField;
FDQueryVSOP_OrderBilling00CM_VALOR: TFloatField;
FDQueryVSOP_OrderBilling00CM_PERCENTUAL: TFloatField;
FDQueryVSOP_OrderBilling00INDIRECT_COST: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_COST: TFloatField;
FDQueryVSOP_OrderBilling00GM_VALOR: TFloatField;
FDQueryVSOP_OrderBilling00GM_PERCENTUAL: TFloatField;
SaveDialog: TSaveDialog;
FDQueryVSOP_OrderBilling00Região: TStringField;
FDQueryVSOP_OrderBilling00UF: TStringField;
FDQueryVSOP_OrderBilling00MRP_Controler: TStringField;
FDQueryVSOP_OrderBilling00MaterialSETUPSTD: TFloatField;
FDQueryVSOP_OrderBilling00MaterialResaleRUNScrapSTD: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_MATERIAL_STD: TFloatField;
FDQueryVSOP_OrderBilling00MachineSETUPSTD: TFloatField;
FDQueryVSOP_OrderBilling00MachineRUNSTD: TFloatField;
FDQueryVSOP_OrderBilling00TotalMachineSTD: TFloatField;
FDQueryVSOP_OrderBilling00LaborSETUPSTD: TFloatField;
FDQueryVSOP_OrderBilling00LaborRUNSTD: TFloatField;
FDQueryVSOP_OrderBilling00TotalLaborSTD: TFloatField;
FDQueryVSOP_OrderBilling00DIRECT_COST_STD: TFloatField;
FDQueryVSOP_OrderBilling00CM_VALOR_STD: TFloatField;
FDQueryVSOP_OrderBilling00CM_PERCENTUAL_STD: TFloatField;
FDQueryVSOP_OrderBilling00INDIRECT_COST_STD: TFloatField;
FDQueryVSOP_OrderBilling00TOTAL_COST_STD: TFloatField;
FDQueryVSOP_OrderBilling00GM_VALOR_STD: TFloatField;
FDQueryVSOP_OrderBilling00GM_PERCENTUAL_STD: TFloatField;
FDQueryBOM: TFDQuery;
DataSourceBOM: TDataSource;
FDQueryBOMPlanta: TStringField;
FDQueryBOMYNumberPA: TStringField;
FDQueryBOMUN: TStringField;
FDQueryBOMYNumberMP: TStringField;
FDQueryBOMUNMP: TStringField;
FDQueryBOMCostLotSize: TFloatField;
FDQueryBOMQtdeFixaSN: TStringField;
FDQueryBOMQtderMP: TFloatField;
FDQueryBOMCusto: TFloatField;
FDQueryBOMCustoSTD: TFloatField;
FDQueryBOMOrdem: TStringField;
FDQueryCosting: TFDQuery;
FDQueryRouting: TFDQuery;
DataSourceCosting: TDataSource;
DataSourceRouting: TDataSource;
FDQueryCostingCodItemYNumber: TStringField;
FDQueryCostingSite: TStringField;
FDQueryCostingUOM: TStringField;
FDQueryCostingCostLotSize: TBCDField;
FDQueryCostingStandard: TFloatField;
FDQueryCostingMoving: TFloatField;
FDQueryCostingPriceUnit: TFloatField;
FDQueryRoutingSite: TStringField;
FDQueryRoutingYNumber: TStringField;
FDQueryRoutingUN: TStringField;
FDQueryRoutingWorkCenter: TStringField;
FDQueryRoutingCentroCusto: TStringField;
FDQueryRoutingCostLotSize: TFloatField;
FDQueryRoutingSetupMIN: TFloatField;
FDQueryRoutingMachineMIN: TFloatField;
FDQueryRoutingLaborMIN: TFloatField;
FDQueryRoutingOverheadMIN: TFloatField;
FDQueryRoutingSetupcost: TFloatField;
FDQueryRoutingSetupMachineCost: TFloatField;
FDQueryRoutingSetupLaborCost: TFloatField;
FDQueryRoutingSetupOverheadCost: TFloatField;
FDQueryRoutingRunMachineCost: TFloatField;
FDQueryRoutingRunLaborCost: TFloatField;
FDQueryRoutingRunOverheadCost: TFloatField;
PanelSQLSplashScreen: TPanel;
ImageSQLSplashScreen: TImage;
cxLabelMensagem: TcxLabel;
cxSmallImages: TcxImageList;
FDScriptInsert: TFDScript;
FDQueryGMHoras: TFDQuery;
cxTabSheet1: TcxTabSheet;
cxPageControl: TcxPageControl;
cxTabSheetGrossMargin: TcxTabSheet;
cxGridGrossMargin: TcxGrid;
cxTableViewGrossMargin00: TcxGridDBTableView;
cxTableViewGrossMargin00SITE: TcxGridDBColumn;
cxTableViewGrossMargin00Regio: TcxGridDBColumn;
cxTableViewGrossMargin00UF: TcxGridDBColumn;
cxTableViewGrossMargin00CANAL: TcxGridDBColumn;
cxTableViewGrossMargin00COD_CLIENTE: TcxGridDBColumn;
cxTableViewGrossMargin00RAZAO_SOCIAL: TcxGridDBColumn;
cxTableViewGrossMargin00GRUPO_CLIENTE: TcxGridDBColumn;
cxTableViewGrossMargin00ACC_OWNER: TcxGridDBColumn;
cxTableViewGrossMargin00COD_ITEM: TcxGridDBColumn;
cxTableViewGrossMargin00MTO_MTS: TcxGridDBColumn;
cxTableViewGrossMargin00FY: TcxGridDBColumn;
cxTableViewGrossMargin00QTR: TcxGridDBColumn;
cxTableViewGrossMargin00DTREF: TcxGridDBColumn;
cxTableViewGrossMargin00COST_LOT_SIZE: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_VENDAS_QTD: TcxGridDBColumn;
cxTableViewGrossMargin00UOM: TcxGridDBColumn;
cxTableViewGrossMargin00NET_SALE: TcxGridDBColumn;
cxTableViewGrossMargin00MATERIAL_SETUP: TcxGridDBColumn;
cxTableViewGrossMargin00MATERIAL_RESALE_RUN_SCRAP: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_MATERIAL: TcxGridDBColumn;
cxTableViewGrossMargin00MACHINE_SETUP: TcxGridDBColumn;
cxTableViewGrossMargin00MACHINE_RUN: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_MACHINE: TcxGridDBColumn;
cxTableViewGrossMargin00LABOR_SETUP: TcxGridDBColumn;
cxTableViewGrossMargin00LABOR_RUN: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_LABOR: TcxGridDBColumn;
cxTableViewGrossMargin00DIRECT_COST: TcxGridDBColumn;
cxTableViewGrossMargin00CM_VALOR: TcxGridDBColumn;
cxTableViewGrossMargin00CM_PERCENTUAL: TcxGridDBColumn;
cxTableViewGrossMargin00INDIRECT_COST: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_COST: TcxGridDBColumn;
cxTableViewGrossMargin00GM_VALOR: TcxGridDBColumn;
cxTableViewGrossMargin00GM_PERCENTUAL: TcxGridDBColumn;
cxTableViewGrossMargin00MRP_Controler: TcxGridDBColumn;
cxTableViewGrossMargin00MaterialSETUPSTD: TcxGridDBColumn;
cxTableViewGrossMargin00MaterialResaleRUNScrapSTD: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_MATERIAL_STD: TcxGridDBColumn;
cxTableViewGrossMargin00MachineSETUPSTD: TcxGridDBColumn;
cxTableViewGrossMargin00MachineRUNSTD: TcxGridDBColumn;
cxTableViewGrossMargin00TotalMachineSTD: TcxGridDBColumn;
cxTableViewGrossMargin00LaborSETUPSTD: TcxGridDBColumn;
cxTableViewGrossMargin00LaborRUNSTD: TcxGridDBColumn;
cxTableViewGrossMargin00TotalLaborSTD: TcxGridDBColumn;
cxTableViewGrossMargin00DIRECT_COST_STD: TcxGridDBColumn;
cxTableViewGrossMargin00CM_VALOR_STD: TcxGridDBColumn;
cxTableViewGrossMargin00CM_PERCENTUAL_STD: TcxGridDBColumn;
cxTableViewGrossMargin00INDIRECT_COST_STD: TcxGridDBColumn;
cxTableViewGrossMargin00TOTAL_COST_STD: TcxGridDBColumn;
cxTableViewGrossMargin00GM_VALOR_STD: TcxGridDBColumn;
cxTableViewGrossMargin00GM_PERCENTUAL_STD: TcxGridDBColumn;
cxGridLevelGrossMargin00: TcxGridLevel;
cxTabSheetBom: TcxTabSheet;
cxGridBom: TcxGrid;
cxTableViewBom: TcxGridDBTableView;
cxTableViewBomPlanta: TcxGridDBColumn;
cxTableViewBomYNumberPA: TcxGridDBColumn;
cxTableViewBomUN: TcxGridDBColumn;
cxTableViewBomYNumberMP: TcxGridDBColumn;
cxTableViewBomUNMP: TcxGridDBColumn;
cxTableViewBomCostLotSize: TcxGridDBColumn;
cxTableViewBomQtdeFixaSN: TcxGridDBColumn;
cxTableViewBomQtderMP: TcxGridDBColumn;
cxTableViewBomCusto: TcxGridDBColumn;
cxTableViewBomCustoSTD: TcxGridDBColumn;
cxTableViewBomOrdem: TcxGridDBColumn;
cxGridBomLevel1: TcxGridLevel;
cxTabSheetCosting: TcxTabSheet;
cxGridCosting: TcxGrid;
cxTableViewCosting: TcxGridDBTableView;
cxTableViewCostingCodItemYNumber: TcxGridDBColumn;
cxTableViewCostingSite: TcxGridDBColumn;
cxTableViewCostingUOM: TcxGridDBColumn;
cxTableViewCostingCostLotSize: TcxGridDBColumn;
cxTableViewCostingStandard: TcxGridDBColumn;
cxTableViewCostingMoving: TcxGridDBColumn;
cxTableViewCostingPriceUnit: TcxGridDBColumn;
cxGridCostingLevel1: TcxGridLevel;
cxTabSheetRouting: TcxTabSheet;
cxGridRouting: TcxGrid;
cxTableViewRouting: TcxGridDBTableView;
cxTableViewRoutingSite: TcxGridDBColumn;
cxTableViewRoutingYNumber: TcxGridDBColumn;
cxTableViewRoutingUN: TcxGridDBColumn;
cxTableViewRoutingWorkCenter: TcxGridDBColumn;
cxTableViewRoutingCentroCusto: TcxGridDBColumn;
cxTableViewRoutingCostLotSize: TcxGridDBColumn;
cxTableViewRoutingSetupMIN: TcxGridDBColumn;
cxTableViewRoutingMachineMIN: TcxGridDBColumn;
cxTableViewRoutingLaborMIN: TcxGridDBColumn;
cxTableViewRoutingOverheadMIN: TcxGridDBColumn;
cxTableViewRoutingSetupcost: TcxGridDBColumn;
cxTableViewRoutingSetupMachineCost: TcxGridDBColumn;
cxTableViewRoutingSetupLaborCost: TcxGridDBColumn;
cxTableViewRoutingSetupOverheadCost: TcxGridDBColumn;
cxTableViewRoutingRunMachineCost: TcxGridDBColumn;
cxTableViewRoutingRunLaborCost: TcxGridDBColumn;
cxTableViewRoutingRunOverheadCost: TcxGridDBColumn;
cxGridRoutingLevel1: TcxGridLevel;
Panel1: TPanel;
cxButtonRefresh: TcxButton;
cxLabel1: TcxLabel;
cxDateEditTSOP_ORDBILDATDOCINI: TcxDateEdit;
cxLabel2: TcxLabel;
cxDateEditTSOP_ORDBILDATDOCFIM: TcxDateEdit;
cxComboBoxTipo: TcxComboBox;
cxLabel3: TcxLabel;
ButExcel: TcxButton;
cxLabel4: TcxLabel;
cxButtonEditPath: TcxButtonEdit;
cxCheckBoxGerar: TcxCheckBox;
FDScriptDelete: TFDScript;
FDQueryTSOP_GMHoras: TFDQuery;
FDQueryTSOP_GMHorasTSOP_GMHCOD: TFDAutoIncField;
FDQueryTSOP_GMHorasTSOP_GMHSIT: TStringField;
FDQueryTSOP_GMHorasTSOP_GMHCCU: TStringField;
FDQueryTSOP_GMHorasTSOP_GMHSUP: TBCDField;
FDQueryTSOP_GMHorasTSOP_GMHMAQ: TBCDField;
FDQueryTSOP_GMHorasTSOP_GMHLAB: TBCDField;
FDQueryTSOP_GMHorasTSOP_GMHOVE: TBCDField;
FDQueryTSOP_GMHorasTSOP_GMHDAT: TSQLTimeStampField;
FDQueryTSOP_GMHorasTSOP_GMHBUD: TStringField;
cxLabel5: TcxLabel;
dtRefTaxaHora: TcxDateEdit;
cxLabel6: TcxLabel;
DtRefBOM: TcxDateEdit;
Shape1: TShape;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure cxButtonRefreshClick(Sender: TObject);
procedure ButExcelClick(Sender: TObject);
procedure cxButtonEditPathClick(Sender: TObject);
procedure cxButtonProcessarBOM1Click(Sender: TObject);
procedure cxButtonProcessarBOM2Click(Sender: TObject);
procedure cxButtonProcessarITEMClick(Sender: TObject);
procedure cxButtonProcessarROUTINGClick(Sender: TObject);
procedure cxButtonProcessarCUSTOClick(Sender: TObject);
procedure cxButtonProcessarUOMClick(Sender: TObject);
procedure cxButtonAtualizaBOMClick(Sender: TObject);
procedure cxButtonAtualizaBOM2Click(Sender: TObject);
procedure cxButtonAtualizaItemClick(Sender: TObject);
procedure cxButtonAtualizaOrdemMPRClick(Sender: TObject);
procedure cxButtonAtualizaMPRClick(Sender: TObject);
procedure cxButtonAtualizaRoutingClick(Sender: TObject);
procedure cxButtonAtualizaCustoClick(Sender: TObject);
procedure cxButtonAtualizaUOMClick(Sender: TObject);
procedure cxButtonInicioClick(Sender: TObject);
procedure cxButtonInsertSQLClick(Sender: TObject);
procedure cxButtonVerBom1Click(Sender: TObject);
procedure cxButtonProcessarClick(Sender: TObject);
private
dxSpreadSheet: TdxSpreadSheet;
procedure ImportarHoras;
procedure Mensagem( pMensagem: String );
procedure CreatePlanilhaGrossMargin;
procedure CreatePlanilhaBOM;
procedure CreatePlanilhaCosting;
procedure CreatePlanilhaRouting;
{ Private declarations }
public
procedure AbrirDataset;
procedure LoadGridCustomization;
{ Public declarations }
end;
var
Fr_RelatorioGrossMargin: TFr_RelatorioGrossMargin;
implementation
{$R *.dfm}
uses uBrady, uUtils, uUtilsOwner;
procedure TFr_RelatorioGrossMargin.AbrirDataset;
var
VAR_TSOP_GMHBUD : String;
begin
Mensagem( 'Abrindo conexão...' );
try
if not FDConnection.Connected then
begin
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB.ini' );
FDConnection.Open;
end;
VAR_TSOP_GMHBUD := 'E';
if cxComboBoxTipo.ItemIndex = 0 then
VAR_TSOP_GMHBUD := 'E'
else if cxComboBoxTipo.ItemIndex = 1 then
VAR_TSOP_GMHBUD := 'B'
else if cxComboBoxTipo.ItemIndex = 2 then
VAR_TSOP_GMHBUD := 'A'
else if cxComboBoxTipo.ItemIndex = 3 then
VAR_TSOP_GMHBUD := 'T'
else if cxComboBoxTipo.ItemIndex = 4 then
VAR_TSOP_GMHBUD := 'M';
if cxPageControl.ActivePage = cxTabSheetGrossMargin then
begin
FDQueryVSOP_OrderBilling00.Close;
Mensagem( 'Obtendo dados (Gross Margin)...' );
FDQueryVSOP_OrderBilling00.ParamByName( 'V_BILLING_INI' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryVSOP_OrderBilling00.ParamByName( 'V_BILLING_FIM' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCFIM.Date;
FDQueryVSOP_OrderBilling00.ParamByName( 'V_COSTREF' ).AsDateTime := dtRefTaxaHora.Date;
FDQueryVSOP_OrderBilling00.ParamByName( 'V_BOMREF' ).AsDateTime := DtRefBOM.Date;
FDQueryVSOP_OrderBilling00.ParamByName( 'V_TSOP_GMHBUD' ).AsString := VAR_TSOP_GMHBUD;
FDQueryVSOP_OrderBilling00.Open;
end
else if cxPageControl.ActivePage = cxTabSheetBom then
begin
FDQueryBOM.Close;
Mensagem( 'Obtendo dados (BOM)...' );
FDQueryBOM.ParamByName( 'V_DATA1' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryBOM.ParamByName( 'V_DATA2' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryBOM.ParamByName( 'V_TSOP_GMHBUD' ).AsString := VAR_TSOP_GMHBUD;
FDQueryBOM.Open;
end
else if cxPageControl.ActivePage = cxTabSheetCosting then
begin
FDQueryCosting.Close;
Mensagem( 'Obtendo dados (Costing)...' );
FDQueryCosting.ParamByName( 'V_DATA' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryCosting.ParamByName( 'V_TSOP_GMHBUD' ).AsString := VAR_TSOP_GMHBUD;
FDQueryCosting.Open;
end
else if cxPageControl.ActivePage = cxTabSheetRouting then
begin
FDQueryRouting.Close;
Mensagem( 'Obtendo dados (Routing)...' );
FDQueryRouting.ParamByName( 'V_DATA1' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryRouting.ParamByName( 'V_DATA2' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryRouting.ParamByName( 'V_TSOP_GMHBUD' ).AsString := VAR_TSOP_GMHBUD;
FDQueryRouting.Open;
end;
finally
Mensagem( EmptyStr );
end;
end;
procedure TFr_RelatorioGrossMargin.ButExcelClick(Sender: TObject);
var
// dxSpreadSheet: TdxSpreadSheet;
I , X : Integer;
varCor1,varCor2: TColor;
begin
if cxButtonEditPath.Text = EmptyStr then
raise Exception.Create('Informe o arquivo primeiro.');
if (FDQueryVSOP_OrderBilling00.IsEmpty and
FDQueryBOM.IsEmpty and
FDQueryCosting.IsEmpty and
FDQueryRouting.IsEmpty) then
raise Exception.Create('Não há dados para serem exportados ao Excel');
Mensagem( 'Iniciando processo de exportação...' );
try
Mensagem( 'Criando planilha...' );
DeleteFile(PWideChar(MyDocumentsPath+'\GM_PowerQuery.xlsx'));
CopyFile( PWideChar('\\ghos2024\Brady\GM_PowerQuery.xlsx'), PWideChar(MyDocumentsPath+'\GM_PowerQuery.xlsx'), True );
dxSpreadSheet := TdxSpreadSheet.Create(nil);
try
if cxCheckBoxGerar.Checked then
begin
Mensagem( 'Carregando planilha, processo pode demorar alguns minutos...' );
dxSpreadSheet.LoadFromFile( MyDocumentsPath+'\GM_PowerQuery.xlsx' );
dxSpreadSheet.BeginUpdate;
if FDQueryVSOP_OrderBilling00.IsEmpty Then
raise Exception.Create('Não há dados de Gross Margin para serem exportados ao Excel');
if FDQueryBOM.IsEmpty Then
raise Exception.Create('Não há dados de BOM para serem exportados ao Excel');
if FDQueryCosting.IsEmpty Then
raise Exception.Create('Não há dados de Costing para serem exportados ao Excel');
if FDQueryRouting.IsEmpty then
raise Exception.Create('Não há dados de Routing para serem exportados ao Excel');
CreatePlanilhaGrossMargin;
dxSpreadSheet.BeginUpdate;
CreatePlanilhaBOM;
dxSpreadSheet.BeginUpdate;
CreatePlanilhaCosting;
dxSpreadSheet.BeginUpdate;
dxSpreadSheet.SaveToFile( cxButtonEditPath.Text );
FreeAndNil(dxSpreadSheet);
dxSpreadSheet := TdxSpreadSheet.Create(nil);
dxSpreadSheet.LoadFromFile( cxButtonEditPath.Text );
dxSpreadSheet.BeginUpdate;
CreatePlanilhaRouting;
dxSpreadSheet.BeginUpdate;
end
else
if cxPageControl.ActivePage = cxTabSheetGrossMargin Then
begin
Mensagem( 'Carregando planilha do Gross Margin...' );
dxSpreadSheet.LoadFromFile( MyDocumentsPath+'\GM_PowerQuery.xlsx' );
dxSpreadSheet.BeginUpdate;
CreatePlanilhaGrossMargin;
end
else if cxPageControl.ActivePage = cxTabSheetBom then
begin
Mensagem( 'Carregando planilha do BOM...' );
dxSpreadSheet.LoadFromFile( MyDocumentsPath+'\GM_PowerQuery.xlsx' );
dxSpreadSheet.BeginUpdate;
CreatePlanilhaBOM;
end
else
if cxPageControl.ActivePage = cxTabSheetCosting then
begin
Mensagem( 'Carregando planilha do Costing...' );
dxSpreadSheet.LoadFromFile( MyDocumentsPath+'\GM_PowerQuery.xlsx' );
dxSpreadSheet.BeginUpdate;
CreatePlanilhaCosting;
end
else
if cxPageControl.ActivePage = cxTabSheetRouting then
begin
Mensagem( 'Carregando planilha do Routing...' );
dxSpreadSheet.LoadFromFile( MyDocumentsPath+'\GM_PowerQuery.xlsx' );
dxSpreadSheet.BeginUpdate;
CreatePlanilhaRouting;
end;
Mensagem( 'Salvando a planilha...' );
dxSpreadSheet.SaveToFile( cxButtonEditPath.Text );
finally
FreeAndNil(dxSpreadSheet);
end;
finally
Mensagem( EmptyStr );
end;
end;
procedure TFr_RelatorioGrossMargin.CreatePlanilhaBOM;
var
I , X : Integer;
varCor1,varCor2: TColor;
begin
dxSpreadSheet.Sheets[1].Active := True;
for I := 0 to 10 do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(0,I) do;
end;
FDQueryBOM.First;
varCor1 := RGB( 255, 255, 204 );
varCor2 := RGB(255,255,225);
X := 1;
while not FDQueryBOM.eof do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,0) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMPlanta .AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,1) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMYNumberPA .AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,2) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMUN.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,3) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMYNumberMP.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,4) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMUNMP.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,5) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryBOMCostLotSize.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,6) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMQtdeFixaSN.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,7) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryBOMQtderMP.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,8) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryBOMCusto.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,9) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryBOMCustoSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,10) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryBOMOrdem.AsString;
end;
if Odd(X) then
varCor1 := RGB(255,255,225)
else
varCor1 := RGB(216,234,204);
Inc(X);
FDQueryBOM.Next;
end;
end;
procedure TFr_RelatorioGrossMargin.CreatePlanilhaCosting;
var
I , X : Integer;
varCor1,varCor2: TColor;
begin
dxSpreadSheet.Sheets[2].Active := True;
for I := 0 to 6 do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(0,I) do;
end;
FDQueryCosting.First;
varCor1 := RGB( 255, 255, 204 );
varCor2 := RGB(255,255,225);
X := 1;
while not FDQueryCosting.Eof do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,0) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryCostingCodItemYNumber.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,1) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryCostingSite.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,2) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryCostingUOM.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,3) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryCostingCostLotSize.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,4) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryCostingStandard.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,5) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryCostingMoving.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,6) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryCostingPriceUnit.AsFloat;
end;
if Odd(X) then
varCor1 := RGB(255,255,225)
else
varCor1 := RGB(216,234,204);
Inc(X);
FDQueryCosting.Next;
end;
end;
procedure TFr_RelatorioGrossMargin.CreatePlanilhaGrossMargin;
var
I , X : Integer;
varCor1,varCor2: TColor;
begin
dxSpreadSheet.Sheets[0].Active := True;
for I := 0 to 50 do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(0,I) do;
end;
FDQueryVSOP_OrderBilling00.First;
varCor1 := RGB( 255, 255, 204 );
varCor2 := RGB(255,255,225);
X := 1;
while not FDQueryVSOP_OrderBilling00.eof do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,0) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00SITE.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,1) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00CANAL.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,2) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00COD_CLIENTE.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,3) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00RAZAO_SOCIAL.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,4) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00GRUPO_CLIENTE.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,5) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00Região.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,6) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00UF.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,7) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00ACC_OWNER.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,8) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00COD_ITEM.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,9) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00MTO_MTS.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,10) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00FY.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,11) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00QTR.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,12) do
begin
Style.Brush.BackgroundColor := varCor1;
AsString := FormatDateTime('dd/mm/yyyy', FDQueryVSOP_OrderBilling00DTREF.AsDateTime);
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,13) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###,###';
AsVariant := FDQueryVSOP_OrderBilling00COST_LOT_SIZE.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,14) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###,###';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_VENDAS_QTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,15) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00UOM.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,16) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryVSOP_OrderBilling00MRP_Controler.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,17) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00NET_SALE.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,18) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MATERIAL_SETUP.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,19) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MATERIAL_RESALE_RUN_SCRAP.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,20) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_MATERIAL.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,21) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MACHINE_SETUP.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,22) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MACHINE_RUN.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,23) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_MACHINE.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,24) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00LABOR_SETUP.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,25) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00LABOR_RUN.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,26) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_LABOR.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,27) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00DIRECT_COST.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,28) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00CM_VALOR.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,29) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00CM_PERCENTUAL.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,30) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00INDIRECT_COST.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,31) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_COST.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,32) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00GM_VALOR.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,33) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00GM_PERCENTUAL.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,34) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MaterialSETUPSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,35) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MaterialResaleRUNScrapSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,36) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_MATERIAL_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,37) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MachineSETUPSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,38) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00MachineRUNSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,39) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TotalMachineSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,40) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00LaborSETUPSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,41) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00LaborRUNSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,42) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TotalLaborSTD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,43) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00DIRECT_COST_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,44) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00CM_VALOR_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,45) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00CM_PERCENTUAL_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,46) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00INDIRECT_COST_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,47) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00TOTAL_COST_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,48) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00GM_VALOR_STD.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,49) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,##0.00';
AsVariant := FDQueryVSOP_OrderBilling00GM_PERCENTUAL_STD.AsFloat;
end;
if Odd(X) then
varCor1 := RGB(255,255,225)
else
varCor1 := RGB(216,234,204);
Inc(X);
FDQueryVSOP_OrderBilling00.Next;
end;
end;
procedure TFr_RelatorioGrossMargin.CreatePlanilhaRouting;
var
I , X : Integer;
varCor1,varCor2: TColor;
begin
dxSpreadSheet.Sheets[3].Active := True;
for I := 0 to 16 do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(0,I) do;
end;
FDQueryRouting.First;
varCor1 := RGB( 255, 255, 204 );
varCor2 := RGB(255,255,225);
X := 1;
while not FDQueryRouting.eof do
begin
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,0) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryRoutingSite.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,1) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryRoutingYNumber.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,2) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryRoutingUN.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,3) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryRoutingWorkCenter.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,4) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryRoutingCentroCusto.AsString;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,5) do
begin
Style.Brush.BackgroundColor := varCor1;
AsVariant := FDQueryRoutingCostLotSize.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,6) do
begin
Style.Brush.BackgroundColor := varCor1;
// Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingSetupMIN.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,7) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
// AsVariant := FDQueryRoutingMachineMIN.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,8) do
begin
Style.Brush.BackgroundColor := varCor1;
// Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingLaborMIN.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,9) do
begin
Style.Brush.BackgroundColor := varCor1;
// Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingOverheadMIN.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,10) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingSetupcost.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,11) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingSetupMachineCost.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,12) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingSetupLaborCost.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,13) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingSetupOverheadCost.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,14) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingRunMachineCost.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,15) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingRunLaborCost.AsFloat;
end;
with dxSpreadSheet.ActiveSheetAsTable.CreateCell(X,16) do
begin
Style.Brush.BackgroundColor := varCor1;
Style.DataFormat.FormatCode := '#,###.####';
AsVariant := FDQueryRoutingRunOverheadCost.AsString;
end;
if Odd(X) then
varCor1 := RGB(255,255,225)
else
varCor1 := RGB(216,234,204);
Inc(X);
FDQueryRouting.Next;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarBOM2Click(Sender: TObject);
begin
Try
Mensagem( 'Exportando do SAP -> Bill of Material - Parte 2' );
WinExec('\\GHOS2024\Brady\CielSapReadTable.exe Q 10.240.10.11 30 500 sondapwce U333Een3 SYSTQV000449 BR-ENG-BOM2 BR-ENG-BOM2 \\ghos2024\Brady\Files\ENG\BR-ENG-BOM2.TXT', 1);
Finally
Mensagem( EmptyStr );
cxButtonProcessarBOM2.OptionsImage.ImageIndex := 39;
cxButtonProcessarITEM.Enabled := True;
cxButtonVerBom2.Enabled := True;
End;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarClick(Sender: TObject);
begin
if cxButtonEditPath.Text = EmptyStr then
raise Exception.Create('Informe o arquivo primeiro.');
ImportarHoras;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarCUSTOClick(Sender: TObject);
begin
try
Mensagem( 'Exportando do SAP -> Custo 2' );
WinExec('\\GHOS2024\Brady\CielSapReadTable.exe Q 10.240.10.11 30 500 sondapwce U333Een3 SYSTQV000449 BR-GM-002 BR-GM-002 \\ghos2024\Brady\Files\ENG\BR-GM-001.TXT', 1);
finally
Mensagem( EmptyStr );
cxButtonProcessarCUSTO.OptionsImage.ImageIndex := 39;
cxButtonProcessarUOM.Enabled := True;
cxButtonVerCusto.Enabled := true;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarITEMClick(Sender: TObject);
begin
try
Mensagem( 'Exportando do SAP -> Item' );
WinExec('\\GHOS2024\Brady\CielSapReadTable.exe Q 10.240.10.11 30 500 sondapwce U333Een3 SYSTQV000448 BR-ENG-ITEM BR-ENG-ITEM \\ghos2024\Brady\Files\ENG\BR-ENG-ITEM.TXT', 1);
finally
Mensagem( EmptyStr );
cxButtonProcessarITEM.OptionsImage.ImageIndex := 39;
cxButtonProcessarROUTING.Enabled := True;
cxButtonVerItem.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarROUTINGClick(
Sender: TObject);
begin
try
Mensagem( 'Exportando do SAP -> Routing' );
WinExec('\\GHOS2024\Brady\CielSapReadTable.exe Q 10.240.10.11 30 500 sondapwce U333Een3 SYSTQV000449 BR-ROUT-001 BR-ROUT-001 \\ghos2024\Brady\Files\ENG\BR-ENG-ROUTING.TXT', 1);
finally
Mensagem( EmptyStr );
cxButtonProcessarROUTING.OptionsImage.ImageIndex := 39;
cxButtonProcessarCUSTO.Enabled := True;
cxButtonVerRouting.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarUOMClick(Sender: TObject);
begin
try
Mensagem( 'Exportando do SAP -> UOM' );
WinExec('\\GHOS2024\Brady\CielSapReadTable.exe Q 10.240.10.11 30 500 sondapwce U333Een3 SYSTQV000449 BR-UOM-001 BR-UOM-001 \\ghos2024\Brady\Files\ENG\BR-UOM-001.TXT', 1);
finally
cxButtonProcessarBOM2.Enabled := False;
cxButtonProcessarBOM2.Enabled := False;
cxButtonProcessarITEM.Enabled := False;
cxButtonProcessarROUTING.Enabled := False;
cxButtonProcessarCUSTO.Enabled := False;
cxButtonProcessarUOM.Enabled := False;
cxButtonProcessarBOM1.Enabled := False;
cxButtonAtualizaBOM.Enabled := True;
cxButtonVerUOM.Enabled := True;
cxButtonProcessarUOM.OptionsImage.ImageIndex := 39;
Mensagem( EmptyStr );
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaBOM2Click(Sender: TObject);
begin
try
Mensagem( 'Atualizando Bill of Material - Parte 2' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -eng_bom2', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaBOM2.OptionsImage.ImageIndex := 39;
cxButtonAtualizaItem.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaBOMClick(Sender: TObject);
begin
try
Mensagem( 'Atualizando Bill of Material - Parte 1' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -eng_bom', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaBOM.OptionsImage.ImageIndex := 39;
cxButtonAtualizaBOM2.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaCustoClick(Sender: TObject);
begin
try
Mensagem( 'Atualizando Custo' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -gm_custos', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaCusto.OptionsImage.ImageIndex := 39;
cxButtonAtualizaUOM.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaItemClick(Sender: TObject);
begin
try
Mensagem( 'Atualizando Item' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -eng_item', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaItem.OptionsImage.ImageIndex := 39;
cxButtonAtualizaOrdemMPR.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaMPRClick(Sender: TObject);
begin
try
Mensagem( 'Atualizando Ordem de Produção' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -eng_op', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaMPR.OptionsImage.ImageIndex := 39;
cxButtonAtualizaRouting.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaOrdemMPRClick(
Sender: TObject);
begin
try
Mensagem( 'Atualizando Ordem de Produção MPR' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -eng_opmpr', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaOrdemMPR.OptionsImage.ImageIndex := 39;
cxButtonAtualizaMPR.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaRoutingClick(
Sender: TObject);
begin
try
Mensagem( 'Atualizando Routing' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -eng_routing', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaRouting.OptionsImage.ImageIndex := 39;
cxButtonAtualizaCusto.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonAtualizaUOMClick(Sender: TObject);
begin
try
Mensagem( 'Atualizando UOM' );
WinExec('\\GHOS2024\Brady\BradyDataImport.exe -uom', 1);
finally
Mensagem( EmptyStr );
cxButtonAtualizaBOM.Enabled := False;
cxButtonAtualizaBOM2.Enabled := False;
cxButtonAtualizaItem.Enabled := False;
cxButtonAtualizaRouting.Enabled := False;
cxButtonAtualizaOrdemMPR.Enabled := False;
cxButtonAtualizaMPR.Enabled := False;
cxButtonAtualizaCusto.Enabled := False;
cxButtonAtualizaUOM.Enabled := False;
cxButtonInsertSQL.Enabled := True;
cxButtonAtualizaUOM.OptionsImage.ImageIndex := 39;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonEditPathClick(Sender: TObject);
begin
if SaveDialog.Execute(Handle) then
begin
cxButtonEditPath.Text := SaveDialog.FileName;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonInicioClick(Sender: TObject);
Var
VarMesAnterior : TDateTime;
VAR_TSOP_GMHBUD : String;
begin
VAR_TSOP_GMHBUD := 'E';
if cxComboBoxTaxa.ItemIndex = 0 then
VAR_TSOP_GMHBUD := 'E'
else if cxComboBoxTaxa.ItemIndex = 1 then
VAR_TSOP_GMHBUD := 'B'
else if cxComboBoxTaxa.ItemIndex = 2 then
VAR_TSOP_GMHBUD := 'A'
else if cxComboBoxTaxa.ItemIndex = 3 then
VAR_TSOP_GMHBUD := 'T'
else if cxComboBoxTaxa.ItemIndex = 4 then
VAR_TSOP_GMHBUD := 'M';
VarMesAnterior := StartOfTheMonth(Now)-1;
cxDateEditTSOP_ORDBILDATDOCINI.Date := StartOfTheMonth(VarMesAnterior);
cxDateEditTSOP_ORDBILDATDOCFIM.Date := EndOfTheMonth(VarMesAnterior);
FDQueryGMHoras.Close;
FDQueryGMHoras.SQL.Clear;
FDQueryGMHoras.SQL.Add('SELECT * FROM TSOP_GMHORAS WHERE TSOP_GMHDAT BETWEEN ');
FDQueryGMHoras.SQL.Add(' :V_BILLING_INI and :V_BILLING_FIM AND TSOP_GMHBUD = :V_TSOP_GMHBUD ');
FDQueryGMHoras.ParamByName( 'V_BILLING_INI' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCINI.Date;
FDQueryGMHoras.ParamByName( 'V_BILLING_FIM' ).AsDateTime := cxDateEditTSOP_ORDBILDATDOCFIM.Date;
FDQueryGMHoras.ParamByName( 'V_TSOP_GMHBUD' ).AsString := VAR_TSOP_GMHBUD;
FDQueryGMHoras.Open;
if FDQueryGMHoras.IsEmpty then
raise Exception.Create('Taxas Horas não encontrada para o período e tipo de taxa informado.');
try
Mensagem( 'Apagando Tabelas Intermediarias...' );
FDScriptDelete.ExecuteAll;
finally
Mensagem( EmptyStr);
end;
cxButtonInicio.OptionsImage.ImageIndex := 39;
cxButtonProcessarBOM1.Enabled := True;
end;
procedure TFr_RelatorioGrossMargin.cxButtonInsertSQLClick(Sender: TObject);
begin
try
Mensagem( 'Calculando Custo...' );
FDScriptInsert.SQLScripts.Clear;
FDScriptInsert.SQLScripts.Add.SQL.Add( 'EXEC dbo.PSOP_ProcessoGMCustos ' );
FDScriptInsert.ExecuteAll;
Mensagem( 'Calculo Finalizado.' );
finally
Mensagem( EmptyStr );
cxButtonProcessarBOM1.Enabled := False;
cxButtonProcessarBOM2.Enabled := False;
cxButtonProcessarITEM.Enabled := False;
cxButtonProcessarROUTING.Enabled := False;
cxButtonProcessarCUSTO.Enabled := False;
cxButtonProcessarUOM.Enabled := False;
cxButtonAtualizaBOM.Enabled := False;
cxButtonAtualizaBOM2.Enabled := False;
cxButtonAtualizaItem.Enabled := False;
cxButtonAtualizaRouting.Enabled := False;
cxButtonAtualizaOrdemMPR.Enabled := False;
cxButtonAtualizaMPR.Enabled := False;
cxButtonAtualizaCusto.Enabled := False;
cxButtonAtualizaUOM.Enabled := False;
cxButtonInsertSQL.Enabled := False;
cxButtonVerBom1.Enabled := False;
cxButtonVerBom2.Enabled := False;
cxButtonVerItem.Enabled := False;
cxButtonVerRouting.Enabled := False;
cxButtonVerCusto.Enabled := False;
cxButtonVerUOM.Enabled := False;
cxButtonProcessarBOM1.OptionsImage.ImageIndex := 38;
cxButtonProcessarBOM2.OptionsImage.ImageIndex := 38;
cxButtonProcessarITEM.OptionsImage.ImageIndex := 38;
cxButtonProcessarROUTING.OptionsImage.ImageIndex := 38;
cxButtonProcessarCUSTO.OptionsImage.ImageIndex := 38;
cxButtonProcessarUOM.OptionsImage.ImageIndex := 38;
cxButtonAtualizaBOM.OptionsImage.ImageIndex := 38;
cxButtonAtualizaBOM2.OptionsImage.ImageIndex := 38;
cxButtonAtualizaItem.OptionsImage.ImageIndex := 38;
cxButtonAtualizaRouting.OptionsImage.ImageIndex := 38;
cxButtonAtualizaOrdemMPR.OptionsImage.ImageIndex := 38;
cxButtonAtualizaMPR.OptionsImage.ImageIndex := 38;
cxButtonAtualizaCusto.OptionsImage.ImageIndex := 38;
cxButtonAtualizaUOM.OptionsImage.ImageIndex := 38;
cxButtonInsertSQL.OptionsImage.ImageIndex := 38;
cxButtonInicio.OptionsImage.ImageIndex := 38
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonProcessarBOM1Click(Sender: TObject);
begin
cxButtonProcessarBOM2.Enabled := False;
cxButtonProcessarBOM2.Enabled := False;
cxButtonProcessarITEM.Enabled := False;
cxButtonProcessarROUTING.Enabled := False;
cxButtonProcessarCUSTO.Enabled := False;
try
Mensagem( 'Exportando do SAP -> Bill of Material - Parte 1' );
WinExec('\\GHOS2024\Brady\CielSapReadTable.exe Q 10.240.10.11 30 500 sondapwce U333Een3 SYSTQV000448 BR-ENG-BOM BR-ENG-BOM \\ghos2024\Brady\Files\ENG\BR-ENG-BOM.TXT', 1);
finally
cxButtonProcessarBOM1.OptionsImage.ImageIndex := 39;
Mensagem( EmptyStr );
cxButtonProcessarBOM2.Enabled := True;
cxButtonVerBom1.Enabled := True;
end;
end;
procedure TFr_RelatorioGrossMargin.cxButtonRefreshClick(Sender: TObject);
begin
AbrirDataset;
end;
procedure TFr_RelatorioGrossMargin.cxButtonVerBom1Click(Sender: TObject);
begin
if FileExists(TButton(Sender).Hint) then
ShellExecute(Handle,'open', 'c:\windows\notepad.exe', pChar( TButton(Sender).Hint ), nil, SW_SHOWNORMAL)
else raise Exception.Create(' Arquivo ' + pChar( TButton(Sender).Hint ) + ' não encontrado.');
end;
procedure TFr_RelatorioGrossMargin.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FDQueryVSOP_OrderBilling00.Close;
FDQueryBOM.Close;
FDQueryCosting.Close;
FDQueryRouting.Close;
FDConnection.Close;
Fr_RelatorioGrossMargin := nil;
Action := caFree;
end;
procedure TFr_RelatorioGrossMargin.FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
begin
if cxPageControl.ActivePage = cxTabSheetGrossMargin then
Fr_Brady.PopupGridTools( cxGridGrossMargin.ActiveView )
else if cxPageControl.ActivePage = cxTabSheetBom then
Fr_Brady.PopupGridTools( cxGridBom.ActiveView )
else if cxPageControl.ActivePage = cxTabSheetCosting then
Fr_Brady.PopupGridTools( cxGridCosting.ActiveView )
else if cxPageControl.ActivePage = cxTabSheetRouting then
Fr_Brady.PopupGridTools( cxGridRouting.ActiveView );
end;
procedure TFr_RelatorioGrossMargin.FormCreate(Sender: TObject);
var
I: Integer;
VarMesAnterior : TDateTime;
begin
if not FDConnection.Connected then
begin
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB.ini' );
FDConnection.Open;
end;
LoadGridCustomization;
VarMesAnterior := StartOfTheMonth(Now)-1;
cxDateEditTSOP_ORDBILDATDOCINI.Date := StartOfTheMonth(VarMesAnterior);
cxDateEditTSOP_ORDBILDATDOCFIM.Date := EndOfTheMonth(VarMesAnterior);
cxPageControl.ActivePage := cxTabSheetProcessar;
{
if not Fr_Brady.SalesRep then
begin
for I := 0 to cxTableViewGrossMargin00.ColumnCount-1 do
begin
cxTableViewGrossMargin00.Columns[I].VisibleForCustomization := True;
cxTableViewGrossMargin00.Columns[I].Visible := True;
end;
end;
}
end;
procedure TFr_RelatorioGrossMargin.ImportarHoras;
var
I, X: Integer;
dxSpreadSheet: TdxSpreadSheet;
varMes, varAno: Integer;
varData: TDateTime;
varPlanta, varBudget, varCentro: String;
varSetup, varMachine, varLabor, varOverhead: Extended;
begin
Mensagem( 'Iniciando processo de importação...' );
try
dxSpreadSheet := TdxSpreadSheet.Create(nil);
try
Mensagem( 'Carregando planilha...' );
dxSpreadSheet.LoadFromFile( cxButtonEditPath.Text );
dxSpreadSheet.BeginUpdate;
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB.ini' );
Mensagem( 'Abrindo Conexão...' );
FDConnection.Open;
try
FDQueryTSOP_GMHoras.Open;
try
Mensagem( 'Lendo linhas da planilha...' );
for X := dxSpreadSheet.ActiveSheetAsTable.Rows.FirstIndex+1 to dxSpreadSheet.ActiveSheetAsTable.Rows.LastIndex do
begin
try
if dxSpreadSheet.ActiveSheetAsTable.Rows[X].CellCount = 0 then
Continue;
if dxSpreadSheet.ActiveSheetAsTable.Rows[X].CellCount < 9 then
Continue;
Mensagem( 'Linha (" ' + IntToStr(X) + '/' + IntToStr(dxSpreadSheet.ActiveSheetAsTable.Rows.LastIndex) + '") "' + Trim(dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[2].AsString) + '" ...' );
if Trim(dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[0].AsString) = EmptyStr then
Continue;
except
Continue;
end;
varAno := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[0].AsInteger;
varMes := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[1].AsInteger;
varData := EncodeDate( varAno, varMes, 01 );
varBudget := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[2].AsString;
varPlanta := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[3].AsString;
varCentro := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[4].AsString;
varSetup := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[5].AsFloat;
varMachine := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[6].AsFloat;
varLabor := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[7].AsFloat;
varOverhead := dxSpreadSheet.ActiveSheetAsTable.Rows[X].Cells[8].AsFloat;
if FDQueryTSOP_GMHoras.Locate( 'TSOP_GMHDAT;TSOP_GMHBUD;TSOP_GMHSIT;TSOP_GMHCCU', VarArrayOf( [varData,varBudget,varPlanta,varCentro] ) ) then
begin
if (varSetup+varMachine+varLabor+varOverhead) > 0.00 then
begin
FDQueryTSOP_GMHoras.Edit;
FDQueryTSOP_GMHorasTSOP_GMHSUP.AsFloat := varSetup;
FDQueryTSOP_GMHorasTSOP_GMHMAQ.AsFloat := varMachine;
FDQueryTSOP_GMHorasTSOP_GMHLAB.AsFloat := varLabor;
FDQueryTSOP_GMHorasTSOP_GMHOVE.AsFloat := varOverhead;
try
FDQueryTSOP_GMHoras.Post;
except
FDQueryTSOP_GMHoras.Cancel;
end;
end
else
begin
try
FDQueryTSOP_GMHoras.Delete;
except
end;
end;
end
else
begin
if (varSetup+varMachine+varLabor+varOverhead) > 0.00 then
begin
FDQueryTSOP_GMHoras.Append;
FDQueryTSOP_GMHorasTSOP_GMHSIT.AsString := varPlanta;
FDQueryTSOP_GMHorasTSOP_GMHBUD.AsString := varBudget;
FDQueryTSOP_GMHorasTSOP_GMHCCU.AsString := varCentro;
FDQueryTSOP_GMHorasTSOP_GMHDAT.AsDateTime := varData;
FDQueryTSOP_GMHorasTSOP_GMHSUP.AsFloat := varSetup;
FDQueryTSOP_GMHorasTSOP_GMHMAQ.AsFloat := varMachine;
FDQueryTSOP_GMHorasTSOP_GMHLAB.AsFloat := varLabor;
FDQueryTSOP_GMHorasTSOP_GMHOVE.AsFloat := varOverhead;
try
FDQueryTSOP_GMHoras.Post;
except
FDQueryTSOP_GMHoras.Cancel;
end;
end;
end;
Application.ProcessMessages;
end;
finally
FDQueryTSOP_GMHoras.Close;
end;
finally
FDConnection.Close;
end;
finally
FreeAndNil(dxSpreadSheet);
end;
finally
Mensagem( EmptyStr );
end;
end;
procedure TFr_RelatorioGrossMargin.LoadGridCustomization;
begin
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewGrossMargin00.Name + '.ini' ) then
cxTableViewGrossMargin00.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewGrossMargin00.Name + '.ini' );
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewBom.Name + '.ini' ) then
cxTableViewBom.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewBom.Name + '.ini' );
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewCosting.Name + '.ini' ) then
cxTableViewCosting.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewCosting.Name + '.ini' );
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewRouting.Name + '.ini' ) then
cxTableViewRouting.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewRouting.Name + '.ini' );
end;
procedure TFr_RelatorioGrossMargin.Mensagem(pMensagem: String);
begin
cxLabelMensagem.Caption := pMensagem;
PanelSQLSplashScreen.Visible := not pMensagem.IsEmpty;
Update;
Application.ProcessMessages;
end;
end.
|
PROGRAM XPrint(INPUT, OUTPUT);
CONST
Min = 1;
MaxStringLength = 5;
Max = 250;
PrintChar = '*';
TYPE
IntSet = SET OF Min .. Max;
VAR
Ch: CHAR;
FUNCTION ConvertsCharToSet(VAR Ch:CHAR):IntSet;
BEGIN
CASE Ch OF
'A': ConvertsCharToSet := [2, 3, 6, 8, 11, 12, 13, 16, 18, 21, 23];
'B': ConvertsCharToSet := [1, 2, 6, 8, 11, 12, 12, 13, 16, 18, 21, 22, 23];
'M': ConvertsCharToSet := [1, 5, 6, 7, 9, 10, 11, 13, 15, 16, 20, 21, 25]
ELSE
ConvertsCharToSet := []
END
END;
PROCEDURE PrintCharsSet(CharsSet: IntSet);
VAR
Counter, CounterX, CounterY: INTEGER;
BEGIN {PrintCharsSet}
Counter := Min;
IF CharsSet <> []
THEN
BEGIN
FOR CounterY := Min TO MaxStringLength
DO
BEGIN
FOR CounterX := Min TO MaxStringLength
DO
BEGIN
IF Counter IN CharsSet
THEN
WRITE(PrintChar)
ELSE
WRITE(' ');
INC(Counter)
END;
WRITELN
END
END
ELSE
WRITELN('Symbol ''', Ch, ''' is not supported')
END; {PrintCharsSet}
PROCEDURE ReadSet(VAR F1: TEXT);
VAR
Ch: CHAR;
Position: INTEGER;
BEGIN {ReadSet}
WHILE NOT(EOF(F1))
DO
BEGIN
READ(F1, Ch);
WHILE NOT(EOLN(F1))
DO
BEGIN
END
END
END; {ReadSet}
BEGIN {XPrint}
IF NOT(EOLN(INPUT)) AND NOT(EOF(INPUT))
THEN
BEGIN
ReadSet(F1); {
READ(Ch);
PrintCharsSet(ConvertsCharToSet(Ch)) }
END
ELSE
WRITELN }
END. {XPrint}
|
unit BZGizmoImage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, Forms,
BZClasses, BZArrayClasses, BZMath, BZVectorMath, BZColors, BZGraphic, BZBitmap, BZImageViewer;
Type
TBZGizmoImageSelectionMode = (gdmNone, gdmPoint, gsmRectangular, gsmCircular, gsmFence, gsmLasso);
TBZGizmoImageOperation = (goNone, goSelect, goMove, goRotate, goScale);
TBZGizmoSelectionDragMode = (sdmNone, sdmInside, sdmTop, sdmBottom, sdmLeft, sdmRight,
sdmTopLeft, sdmTopRight, sdmBottomLeft, sdmBottomRight);
{ TBZGizmoImage }
{ TBZGizmoImageViewer }
TBZGizmoImageViewer = Class(TBZUpdateAbleComponent)
private
FOperation : TBZGizmoImageOperation;
FSelectionMode : TBZGizmoImageSelectionMode;
FEnabled : Boolean;
FImageViewer : TBZImageViewer;
FControlPoint : TBZArrayOfPoints;
FMoving: Boolean;
FSelectionMouseActive : Boolean;
FEmptySelection : Boolean;
FRectSelectionDragMode : TBZGizmoSelectionDragMode;
FPointRadiusSize : Byte;
FStartPos, FEndPos : TBZPoint;
FPreviousStartPos, FPreviousEndPos : TBZPoint;
FCurrentMousePos, FLastMousePos : TBZPoint;
FBoundTopLeftPoint,
FBoundTopRightPoint,
FBoundTopCenterPoint,
FBoundBottomLeftPoint,
FBoundBottomRightPoint,
FBoundBottomCenterPoint,
FBoundLeftCenterPoint,
FBoundRightCenterPoint,
FBoundCenterPoint,
FSelectionRect : TBZRect;
FPenPointColor : TBZColor;
FBrushPointColor : TBZColor;
FPenShapeColor : TBZColor;
FBrushShapeColor : TBZColor;
FOnUpdate: TNotifyEvent;
//FOnSelect: TGLGizmoExAcceptEvent;
FOnSelectionModeChange: TNotifyEvent;
FOnOperationChange: TNotifyEvent;
FOnSelectionLost: TNotifyEvent;
procedure SetImageViewer(const AValue : TBZImageViewer);
procedure SetSelectionMode(const AValue : TBZGizmoImageSelectionMode);
procedure SetOperation(const AValue : TBZGizmoImageOperation);
protected
procedure DrawPoint(x,y : Integer; VirtualCanvas : TBZBitmapCanvas);
procedure DrawShape(VirtualCanvas : TBZBitmapCanvas);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure ViewerMouseMove(Sender : TObject; Shift : TShiftState; X, Y : Integer);
procedure ViewerMouseDown(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer);
procedure ViewerMouseUp(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer);
procedure UpdateGizmo; overload;
procedure LooseSelection; virtual;
procedure LooseCursorSelection;
function getControlPoints : TBZArrayOfPoints;
published
property ImageViewer: TBZImageViewer read FImageViewer write SetImageViewer;
property SelectionMode: TBZGizmoImageSelectionMode read FSelectionMode write SetSelectionMode default gsmRectangular;
property Operation : TBZGizmoImageOperation read FOperation write SetOperation;
property Enabled: Boolean read FEnabled write FEnabled default True;
//property Visible: Boolean read GetVisible write SetVisible;
//property PenPointColor : TBZColor read FPenPointColor write FPenPointColor;
//property BrushPointColor : TBZColor read FBrushPointColor write FBrushPointColor;
//property PenShapeColor : TBZColor read FPenShapeColor write FPenShapeColor;
//property BrushShapeColor : TBZColor read FBrushShapeColor write FBrushShapeColor;
property PointRadiusSize : Byte read FPointRadiusSize write FPointRadiusSize;
property OnSelectionLost: TNotifyEvent read FOnSelectionLost write FOnSelectionLost;
property OnSelectionModeChange: TNotifyEvent read FOnSelectionModeChange write FOnSelectionModeChange;
property OnOperationChange: TNotifyEvent read FOnOperationChange write FOnOperationChange;
//property OnSelect: TGLGizmoExAcceptEvent read FOnSelect write FOnSelect;
property OnUpdate: TNotifyEvent read FOnUpdate write FOnUpdate;
end;
implementation
{ TBZGizmoImage }
procedure TBZGizmoImageViewer.SetImageViewer(const AValue : TBZImageViewer);
begin
if FImageViewer = AValue then Exit;
FImageViewer := AValue;
//FImageViewer.OnMouseDown := @ViewerMouseDown;
//FImageViewer.OnMouseUp := @ViewerMouseUp;
//FImageViewer.OnMouseMove := @ViewerMouseMove;
FImageViewer.OnAfterPaint := @DrawShape;
end;
procedure TBZGizmoImageViewer.SetOperation(const AValue : TBZGizmoImageOperation);
begin
if FOperation = AValue then Exit;
FOperation := AValue;
end;
procedure TBZGizmoImageViewer.SetSelectionMode(const AValue : TBZGizmoImageSelectionMode);
begin
if FSelectionMode = AValue then Exit;
FSelectionMode := AValue;
end;
procedure TBZGizmoImageViewer.DrawPoint(x, y : Integer; VirtualCanvas : TBZBitmapCanvas);
Var
OldPenStyle : TBZStrokeStyle;
OldBrushStyle : TBZBrushStyle;
OldCombineMode : TBZColorCombineMode;
OldPixelMode : TBZBitmapDrawMode;
OldAlphaMode : TBZBitmapAlphaMode;
OldPenColor : TBZColor;
OldBrushColor : TBZColor;
begin
With VirtualCanvas do
begin
OldPenStyle := Pen.Style;
OldPenColor := Pen.Color;
OldBrushStyle := Brush.Style;
OldBrushColor := Brush.Color;
OldCombineMode := DrawMode.CombineMode;
OldPixelMode := DrawMode.PixelMode;
OldAlphaMode := DrawMode.AlphaMode;
DrawMode.PixelMode := dmCombine;
DrawMode.AlphaMode := amNone; //amAlphaBlendHQ;
DrawMode.CombineMode := cmXOr;
Pen.Style := ssSolid;
Pen.Color := clrYellow;
Brush.Style := bsSolid;
Brush.Color := clrRed;
//Rectangle(X - FPointRadiusSize, Y - FPointRadiusSize, X + FPointRadiusSize, Y + FPointRadiusSize);
Circle(X,Y, FPointRadiusSize);
Pen.Style := OldPenStyle;
Pen.Color := OldPenColor;
Brush.Style := OldBrushStyle;
Brush.Color := OldBrushColor;
DrawMode.CombineMode := OldCombineMode;
DrawMode.PixelMode := OldPixelMode;
DrawMode.AlphaMode := OldAlphaMode;
end;
end;
procedure TBZGizmoImageViewer.DrawShape(VirtualCanvas : TBZBitmapCanvas);
Var
OldPenStyle : TBZStrokeStyle;
OldBrushStyle : TBZBrushStyle;
OldCombineMode : TBZColorCombineMode;
OldAlphaMode : TBZBitmapAlphaMode;
OldPixelMode : TBZBitmapDrawMode;
OldPenColor : TBZColor;
VertMiddle, HorizMiddle : Integer;
begin
Case FSelectionMode of
gdmNone: ;
gdmPoint:
begin
;
end;
gsmRectangular:
begin
With VirtualCanvas do
begin
OldCombineMode := DrawMode.CombineMode;
OldPixelMode := DrawMode.PixelMode;
OldAlphaMode := DrawMode.AlphaMode;
OldPenStyle := Pen.Style;
OldPenColor := Pen.Color;
OldBrushStyle := Brush.Style;
DrawMode.PixelMode := dmCombine;
DrawMode.AlphaMode := amNone; //amAlphaBlendHQ;
DrawMode.CombineMode := cmXor;
Pen.Style := ssSolid;
Pen.Color := clrYellow;
Brush.Style := bsClear;
Rectangle(FSelectionRect);// (FStartPos.X, FStartPos.Y, FEndPos.X, FEndPos.Y);
Pen.Style := OldPenStyle;
Pen.Color := OldPenColor;
Brush.Style := OldBrushStyle;
DrawMode.CombineMode := OldCombineMode;
DrawMode.PixelMode := OldPixelMode;
DrawMode.AlphaMode := OldAlphaMode;
end;
HorizMiddle := FSelectionRect.CenterPoint.X;
VertMiddle := FSelectionRect.CenterPoint.Y;
DrawPoint(FSelectionRect.Left, FSelectionRect.Top, VirtualCanvas);
DrawPoint(FSelectionRect.Left, FSelectionRect.Bottom, VirtualCanvas);
DrawPoint(FSelectionRect.Right, FSelectionRect.Top, VirtualCanvas);
DrawPoint(FSelectionRect.Right, FSelectionRect.Bottom, VirtualCanvas);
DrawPoint(HorizMiddle, FSelectionRect.Top, VirtualCanvas);
DrawPoint(HorizMiddle, FSelectionRect.Bottom, VirtualCanvas);
DrawPoint(FSelectionRect.Left, VertMiddle, VirtualCanvas);
DrawPoint(FSelectionRect.Right, VertMiddle, VirtualCanvas);
DrawPoint(HorizMiddle, VertMiddle, VirtualCanvas);
end;
gsmCircular: ;
gsmFence: ;
gsmLasso: ;
end;
end;
constructor TBZGizmoImageViewer.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
end;
destructor TBZGizmoImageViewer.Destroy;
begin
inherited Destroy;
end;
procedure TBZGizmoImageViewer.Loaded;
begin
inherited Loaded;
end;
procedure TBZGizmoImageViewer.Notification(AComponent : TComponent; Operation : TOperation);
begin
inherited Notification(AComponent, Operation);
end;
procedure TBZGizmoImageViewer.ViewerMouseMove(Sender : TObject; Shift : TShiftState; X, Y : Integer);
Var
DeltaPos : TBZPoint;
begin
FCurrentMousePos.Create(X, Y);
FCurrentMousePos := FCurrentMousePos + FImageViewer.VirtualViewPort.TopLeft;
if FSelectionMouseActive then
begin
if (ssLeft in Shift) then
begin
FPreviousStartPos := FStartPos;
FPreviousEndPos := FEndPos;
if FEmptySelection then
begin
FEndPos := FCurrentMousePos + FImageViewer.VirtualViewPort.TopLeft;
UpdateGizmo;
FImageViewer.Invalidate;
end
else
begin
Case FRectSelectionDragMode of
sdmInside:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FStartPos := FStartPos + DeltaPos;
FEndPos := FEndPos + DeltaPos;
end;
sdmTop:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FStartPos.Y := min((FStartPos.Y + DeltaPos.Y), FEndPos.Y);
end;
sdmBottom:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FEndPos.Y := max((FEndPos.Y + DeltaPos.Y), FStartPos.Y);
end;
sdmLeft:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FStartPos.X := min((FStartPos.X + DeltaPos.X), FEndPos.X);
end;
sdmRight:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FEndPos.X := max((FEndPos.X + DeltaPos.X), FStartPos.X);
end;
sdmTopLeft:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FStartPos := FStartPos + DeltaPos;
FStartPos := FStartPos.Min(FEndPos);
end;
sdmTopRight:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FEndPos.X := max((FEndPos.X + DeltaPos.X), FStartPos.X);
FStartPos.Y := min((FStartPos.Y + DeltaPos.Y), FEndPos.Y);
end;
sdmBottomLeft:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FEndPos.Y := max((FEndPos.Y + DeltaPos.Y), FStartPos.Y);
FStartPos.X := min((FStartPos.X + DeltaPos.X), FEndPos.X);
end;
sdmBottomRight:
begin
DeltaPos := FCurrentMousePos - FLastMousePos;
FEndPos := FEndPos + DeltaPos;
FEndPos := FEndPos.Max(FStartPos);
end;
end;
UpdateGizmo;
FImageViewer.Invalidate;
end;
FLastMousePos := FCurrentMousePos;
end
else
begin
Screen.Cursor := crDefault;
end;
end
else
begin
if Not(FEmptySelection) then
begin
if FBoundTopLeftPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmTopLeft;
Screen.Cursor := crSizeNWSE;
end
else if FBoundTopRightPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmTopRight;
Screen.Cursor := crSizeNESW;
end
else if FBoundTopCenterPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmTop;
Screen.Cursor := crSizeNS;
end
else if FBoundBottomLeftPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmBottomLeft;
Screen.Cursor := crSizeNESW;
end
else if FBoundBottomCenterPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmBottom;
Screen.Cursor := crSizeNS;
end
else if FBoundBottomRightPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmBottomRight;
Screen.Cursor := crSizeNWSE;
end
else if FBoundLeftCenterPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmLeft;
Screen.Cursor := crSizeWE;
end
else if FBoundRightCenterPoint.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmRight;
Screen.Cursor := crSizeWE;
end
else if FSelectionRect.PointInRect(FCurrentMousePos) then
begin
//FRectSelectionDragMode := sdmInside;
Screen.Cursor := crSizeAll;
end
else
begin
//FRectSelectionDragMode := sdmNone;
Screen.Cursor := crDefault;
end;
end;
end;
end;
procedure TBZGizmoImageViewer.ViewerMouseDown(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer);
begin
FSelectionMouseActive := True;
FCurrentMousePos.Create(X, Y);
if FEmptySelection then
begin
FStartPos := FCurrentMousePos + FImageViewer.VirtualViewPort.TopLeft;
FRectSelectionDragMode := sdmBottomRight;
end
else
begin
if FBoundTopLeftPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmTopLeft;
Screen.Cursor := crSizeNWSE;
end
else if FBoundTopRightPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmTopRight;
Screen.Cursor := crSizeNESW;
end
else if FBoundTopCenterPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmTop;
Screen.Cursor := crSizeNS;
end
else if FBoundBottomLeftPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmBottomLeft;
Screen.Cursor := crSizeNESW;
end
else if FBoundBottomCenterPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmBottom;
Screen.Cursor := crSizeNS;
end
else if FBoundBottomRightPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmBottomRight;
Screen.Cursor := crSizeNWSE;
end
else if FBoundLeftCenterPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmLeft;
Screen.Cursor := crSizeWE;
end
else if FBoundRightCenterPoint.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmRight;
Screen.Cursor := crSizeWE;
end
else if FSelectionRect.PointInRect(FCurrentMousePos) then
begin
FRectSelectionDragMode := sdmInside;
Screen.Cursor := crSizeAll;
end
else
begin
FRectSelectionDragMode := sdmNone;
Screen.Cursor := crDefault;
end;
FLastMousePos := FCurrentMousePos;
end;
end;
procedure TBZGizmoImageViewer.ViewerMouseUp(Sender : TObject; Button : TMouseButton; Shift : TShiftState; X, Y : Integer);
Var
TempPos : TBZPoint;
begin
FSelectionMouseActive := False;
if FEmptySelection then FEmptySelection := False;
FRectSelectionDragMode := sdmNone;
if (FStartPos.X > FEndPos.X) or (FStartPos.Y > FEndPos.Y) then
begin
TempPos := FStartPos;
FStartPos := FEndPos;
FEndPos := TempPos;
FImageViewer.Invalidate;
end;
Screen.Cursor := crDefault;
end;
procedure TBZGizmoImageViewer.UpdateGizmo;
begin
FSelectionRect.Create(FStartPos.X + FPointRadiusSize, FStartPos.Y + FPointRadiusSize, FEndPos.X - FPointRadiusSize, FEndPos.Y - FPointRadiusSize, true);
FBoundTopLeftPoint.Create((FSelectionRect.TopLeft - FPointRadiusSize), (FSelectionRect.TopLeft + FPointRadiusSize));
FBoundTopRightPoint.Create((FSelectionRect.Right - FPointRadiusSize), (FSelectionRect.Top - FPointRadiusSize), (FSelectionRect.Right + FPointRadiusSize), (FSelectionRect.Top + FPointRadiusSize));
//FBoundTopRightPoint.Create(FEndPos.X - FPointRadiusSize, FStartPos.Y - FPointRadiusSize, FEndPos.X + FPointRadiusSize, FStartPos.Y + FPointRadiusSize);
FBoundBottomLeftPoint.Create((FSelectionRect.Left - FPointRadiusSize), (FSelectionRect.Bottom - FPointRadiusSize), (FSelectionRect.Left + FPointRadiusSize), (FSelectionRect.Bottom + FPointRadiusSize));
//FBoundBottomLeftPoint.Create(FStartPos.X - FPointRadiusSize, FEndPos.Y - FPointRadiusSize, FStartPos.X + FPointRadiusSize, FEndPos.Y + FPointRadiusSize);
FBoundBottomRightPoint.Create((FSelectionRect.BottomRight - FPointRadiusSize), (FSelectionRect.BottomRight + FPointRadiusSize));
//FBoundBottomRightPoint.Create(FEndPos.X - FPointRadiusSize, FEndPos.Y - FPointRadiusSize, FEndPos.X + FPointRadiusSize, FEndPos.Y + FPointRadiusSize);
FBoundTopCenterPoint.Create((FSelectionRect.CenterPoint.X - FPointRadiusSize), (FSelectionRect.Top - FPointRadiusSize),(FSelectionRect.CenterPoint.X + FPointRadiusSize), (FSelectionRect.Top + FPointRadiusSize));
//FBoundTopCenterPoint.Create(HorizMiddle - FPointRadiusSize, FStartPos.Y - FPointRadiusSize, HorizMiddle + FPointRadiusSize, FStartPos.Y + FPointRadiusSize);
FBoundBottomCenterPoint.Create((FSelectionRect.CenterPoint.X - FPointRadiusSize), (FSelectionRect.Bottom - FPointRadiusSize),(FSelectionRect.CenterPoint.X + FPointRadiusSize), (FSelectionRect.Bottom + FPointRadiusSize));
//FBoundBottomCenterPoint.Create(HorizMiddle - FPointRadiusSize, FEndPos.Y - FPointRadiusSize, HorizMiddle + FPointRadiusSize, FEndPos.Y + FPointRadiusSize);
FBoundLeftCenterPoint.Create((FSelectionRect.Left - FPointRadiusSize), (FSelectionRect.CenterPoint.Y - FPointRadiusSize), (FSelectionRect.Left + FPointRadiusSize), (FSelectionRect.CenterPoint.Y + FPointRadiusSize));
//FBoundLeftCenterPoint.Create(FStartPos.X - FPointRadiusSize, VertMiddle - FPointRadiusSize, FStartPos.X + FPointRadiusSize, VertMiddle + FPointRadiusSize);
FBoundRightCenterPoint.Create((FSelectionRect.Right - FPointRadiusSize), (FSelectionRect.CenterPoint.Y - FPointRadiusSize), (FSelectionRect.Right + FPointRadiusSize), (FSelectionRect.CenterPoint.Y + FPointRadiusSize));
//FBoundRightCenterPoint.Create(FEndPos.X - FPointRadiusSize, VertMiddle - FPointRadiusSize, FEndPos.X + FPointRadiusSize, VertMiddle + FPointRadiusSize);
FBoundCenterPoint.Create((FSelectionRect.CenterPoint.X - FPointRadiusSize), (FSelectionRect.CenterPoint.Y - FPointRadiusSize),(FSelectionRect.CenterPoint.X + FPointRadiusSize), (FSelectionRect.CenterPoint.Y + FPointRadiusSize));
//FBoundCenterPoint.Create(HorizMiddle - FPointRadiusSize, VertMiddle - FPointRadiusSize, HorizMiddle + FPointRadiusSize, VertMiddle + FPointRadiusSize);
end;
procedure TBZGizmoImageViewer.LooseSelection;
begin
FStartPos.Create(0,0);
FEndPos.Create(0,0);
FPreviousStartPos.Create(0,0);
FPreviousEndPos.Create(0,0);
FEmptySelection := True;
FRectSelectionDragMode := sdmNone;
FSelectionMouseActive := False;
FPointRadiusSize := 4;
end;
procedure TBZGizmoImageViewer.LooseCursorSelection;
begin
end;
function TBZGizmoImageViewer.getControlPoints : TBZArrayOfPoints;
begin
end;
end.
|
// *************************************************************
// unit ECS_INFO
//
// 15.11.2010 ria erstellt
// 12.11.2013 ria Delphi XE4 Version
// 09.07.2014 ria neues autec Logo
// 19.11.2014 ria EMail-Adresse und Link auf Website angepasst
// 15.09.2016 ria neues Layout
//
// Funktion: Info Fenster anzeigen
// *************************************************************
unit ECS_INFO;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, jpeg, ExtCtrls;
type
TfrmECS_INFO = class(TForm)
Panel2: TPanel;
Label4: TLabel;
Label5: TLabel;
Label8: TLabel;
Label1: TLabel;
Panel3: TPanel;
Panel1: TPanel;
lblProject: TLabel;
lblVersion: TLabel;
lblCopyright: TLabel;
lblCustomer: TLabel;
lblLicense: TLabel;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
str_Project : string; // Projektname
str_Version : string; // Version
str_Customer : string; // Kunde
str_License : string; // Lizenz
str_Application : string; // Name der Applikation
n_StayOnTop : integer; // 1 -> StayOnTop - Fenster
end;
var
frmECS_INFO: TfrmECS_INFO;
implementation
{$R *.DFM}
var
str_Copyright : string = '© 2005-???? AUTEC process automation GmbH';
// *************************************************************
// Formular wird erzeugt
// *************************************************************
procedure TfrmECS_INFO.FormCreate (Sender: TObject);
var
strYear : string; // Jahr
begin
strYear := IntToStr (CurrentYear); // aktuelles Jahr
// aktuelle Jahr im Copyright setzen
lblCopyright.Caption := StringReplace (str_Copyright, '????', strYear, [rfReplaceAll]);
Self.DefaultMonitor := dmDeskTop;
end;
// *************************************************************
// Formular wird erzeugt
// *************************************************************
procedure TfrmECS_INFO.FormShow (Sender: TObject);
begin
Caption := str_Application; // Projekt anzeigen
lblProject.Caption := str_Project; // Projekt anzeigen
lblVersion.Caption := str_Version; // Version anzeigen
lblCustomer.Caption := str_Customer; // Kunden anzeigen
lblLicense.Caption := str_License; // Kunden anzeigen
end;
// *************************************************************
// Formular wird aktiviert
// *************************************************************
procedure TfrmECS_INFO.FormActivate (Sender: TObject);
begin
if n_StayOnTop = 1 then // wenn es StyoOnTop sein soll
begin
Self.PopupMode := pmAuto;
Self.FormStyle := fsStayOnTop;
SetWindowPos (Self.Handle, HWND_TOPMOST, Self.Left, Self.Top,
Self.width, Self.Height, SWP_SHOWWINDOW);
end;
end;
// *************************************************************
// Klick auf Button Schließen
// *************************************************************
procedure TfrmECS_INFO.btnCloseClick (Sender: TObject);
begin
Self.Close; // Formular schließen
end;
end.
|
unit SelectUnArchItem;
interface
uses
System.SysUtils,System. Classes, Vcl.Forms, VirtualTrees, Vcl.Controls;
type
TSelectUnArchItemFrm = class(TForm)
UnArchItemsGrid: TVirtualStringTree;
procedure FormShow(Sender: TObject);
procedure UnArchItemsGridGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
procedure UnArchItemsGridNodeDblClick(Sender: TBaseVirtualTree;
const HitInfo: THitInfo);
private
fInFile : TFileName;
fItemIndex: integer;
public
constructor Create(AOwner :TComponent; const AInFile : TFileName); reintroduce;
property ItemIndex : integer read fItemIndex;
end;
implementation
uses
sevenzip2;
//sevenzip_16_04;
{$R *.dfm}
type
TGridRec = record
ItemIndex : Word;
Size : LongWord;
Path : String;
end;
pGridRec = ^TGridRec;
{ TArchItemsFrm }
constructor TSelectUnArchItemFrm.Create(AOwner: TComponent; const AInFile: TFileName);
begin
inherited Create(AOwner);
fInFile := AInFile;
fItemIndex := -1;
UnArchItemsGrid.NodeDataSize := SizeOf(TGridRec);
end;
procedure TSelectUnArchItemFrm.FormShow(Sender: TObject);
var
Arch: I7zInArchive;
i : integer;
vNewNode : PVirtualNode;
vNodeData: pGridRec;
begin
i := 0;
Arch := CreateInArchive(CLSID_CFormat7z);
Arch.OpenFile(fInFile);
UnArchItemsGrid.BeginUpdate;
try
UnArchItemsGrid.Clear;
while (cardinal(i) < Arch.NumberOfItems) do
begin
if not Arch.ItemIsFolder[i] then
begin
vNewNode := UnArchItemsGrid.AddChild(UnArchItemsGrid.RootNode);
if not (vsInitialized in vNewNode.States) then
UnArchItemsGrid.ReinitNode(vNewNode, False);
vNodeData := UnArchItemsGrid.GetNodeData(vNewNode);
vNodeData.ItemIndex := i;
vNodeData.Size := Arch.ItemSize[i];
vNodeData.Path := Arch.ItemPath[i];
end;
inc(i);
end;
finally
UnArchItemsGrid.EndUpdate;
end;
end;
procedure TSelectUnArchItemFrm.UnArchItemsGridGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: String);
var RecData: pGridRec;
begin
RecData := Sender.GetNodeData(Node);
case Column of
0: CellText := RecData.Path;
1: CellText := Format('%d',[RecData.Size]);
end;
end;
procedure TSelectUnArchItemFrm.UnArchItemsGridNodeDblClick(
Sender: TBaseVirtualTree; const HitInfo: THitInfo);
var RecData: pGridRec;
begin
RecData := Sender.GetNodeData(Sender.FocusedNode);
fItemIndex := RecData.ItemIndex;
self.ModalResult := mrOk;
end;
end.
|
unit settings;
interface
uses
comctrls, windows, dialogs, classes, xml_lite, objects;
type
TBackupType = (btOnlyOne, btAll);
//--------------------------------
TConfirmationType = (
ctAddsToUserMap,
ctCombineStrings,
ctInputSameAsOutputWithPrefix,
ctInputSameAsOutputWithoutPrefix,
ctInputFolderMissing
);
TConfirmations = packed record
addsToUserMap,
combineStrings,
inputSameAsOutputWithPrefix,
inputSameAsOutputWithoutPrefix,
inputFolderMissing : boolean;
end;
//--------------------------------
TFormSettings = class(TObject)
private
{$IFDEF CONSOLE}{$ELSE}
procedure SaveCoolBar( const cb:TCoolBar;const regkey:string;const Root:HKEY=HKEY_CURRENT_USER);
procedure LoadCoolBar( const cb:TCoolBar;const regkey:string;const Root:HKEY=HKEY_CURRENT_USER);
{$ENDIF}
public
{$IFDEF CONSOLE}{$ELSE}
StateForShow : integer;
lastTabIndexInProjectEditor : string;
{$ENDIF}
LastFilesFolder,
LastTagsFolder,
LastFilesOutputFolder,
LastTagsOutputFolder,
LastFilesMask,
LastTagsMask,
backupFolder : string;
doReportSemicolons,
doShowCompressionSettings,
doCreateBackups,
doShowBottombar,
firstRun,
doPlaySounds : boolean;
backupType : TBackupType;
confirmations : TConfirmations;
Constructor Create;
Destructor Destroy; override;
procedure SaveFormSettings;
procedure LoadFormSettings;
procedure loadMRU(var listOut:tstrings);
procedure saveMRU(const listIn:tstrings);
{$IFDEF CONSOLE}{$ELSE}
function showConfirmation(const msg : string; const messageType : TMsgDlgType; const confirmationType:TConfirmationType):boolean;
{$ENDIF}
end;
implementation
uses
{$IFDEF CONSOLE}{$ELSE}unit1, confirmation,controls,{$ENDIF} registry, sysutils, forms, jclstrings, darin_file, blowfish,
jclfileutils, string_compression, XmlStringManip, HTTPApp;
const
RegKey = '\Software\Nebiru Software\JSCruncher Pro';
MRURegKey = RegKey + '\MRU';
mapKey = 'eJwryTAsjs8sji/JSI3PNq6MT8svis8qTg4qzUvOSC0KKDIIjs81KYhPy8wxNgUAgb8QpQ==';
//------------------------------------------------------------------------------
function rootPath:string;
begin
result := extractfilepath(paramstr(0));
end;
//------------------------------------------------------------------------------
constructor TFormSettings.Create;
var
list : tstrings;
i : integer;
filename : string;
begin
loadFormSettings();
if(firstRun)then try
// cleanup any crap from a previous install
// delete obsolete folders
if(directoryExists(rootPath() + 'database'))then deleteDirectory(rootPath() + 'database', false);
if(directoryExists(rootPath() + 'profiles'))then deleteDirectory(rootPath() + 'profiles', false);
// delete any old *.mapx files
list := tstringlist.create();
try
BuildFileList(rootPath() + 'maps/*.mapx', faAnyFile, list);
for i := 0 to list.count-1 do begin
SetFileReadOnlyStatus(rootPath() + 'maps/' + list[i], false);
deletefile(rootPath() + 'maps/' + list[i]);
end;
finally
list.free();
end;
// if there are *.map files, rename them to *.jmap (if doens't already exist)
list := tstringlist.create();
try
BuildFileList(rootPath() + 'maps/*.map', faAnyFile, list);
for i := 0 to list.count-1 do begin
filename := rootPath() + 'maps/' + list[i];
if(not fileexists( ChangeFileExt(filename, '.jmap' )))then
renameFile(filename, ChangeFileExt(filename, '.jmap' ));
end;
finally
list.free();
end;
// delete registry
with TRegistry.Create() do try
RootKey := HKEY_CURRENT_USER;
deleteKey(RegKey);
finally
free();
end;
firstRun := false;
saveFormSettings(); // to save the firstRun change
LoadFormSettings(); // to reload the correct defaults
except
end;
end;
//------------------------------------------------------------------------------
destructor TFormSettings.Destroy;
begin
inherited;
end;
//------------------------------------------------------------------------------
procedure TFormSettings.SaveFormSettings;
{$IFDEF CONSOLE}{$ELSE}
var
i : integer;
temp : tstrings;
{$ENDIF}
begin
{$IFDEF CONSOLE}{$ELSE}
with form1 do begin
for i := 0 to componentCount-1 do
if(components[i] is TCoolbar) then
SaveCoolBar(Coolbar1,RegKey + '\' + components[i].name);
with Treginifile.create(RegKey) do try
Rootkey := HKEY_CURRENT_USER;
writeinteger('FORM', 'ACTIVETAB', SelectedTab);
if windowstate=wsNormal then begin
writeinteger('FORM', 'LEFT', left);
writeinteger('FORM', 'TOP', top);
writeinteger('FORM', 'WIDTH', width);
writeinteger('FORM', 'HEIGHT', height);
end;
writeBool( 'FORM', 'FIRSTRUN', firstRun);
writeinteger('FORM', 'WINDOWSTATE', ord(WindowState));
writeinteger('FORM', 'TREEWIDTH', FileTree.Width);
writeinteger('FORM', 'TREE2WIDTH', TagTree.Width);
writeinteger('FORM', 'BOTTOMBAR', bottomBar.tag);
writestring( 'FORM', 'LastFilesFolder', LastFilesFolder);
writestring( 'FORM', 'LastTagsFolder', LastTagsFolder);
writestring( 'FORM', 'LastFilesOutputFolder', LastFilesOutputFolder);
writestring( 'FORM', 'LastTagsOutputFolder', LastTagsOutputFolder);
writestring( 'FORM', 'LastFilesMask', LastFilesMask);
writestring( 'FORM', 'LastTagsMask', LastTagsMask);
writestring('PROJECTEDIT', 'LASTPAGE', lastTabIndexInProjectEditor);
writebool( 'FORM', 'SHOW_COMPRESSION_SETTINGS', doShowCompressionSettings);
writebool( 'FORM', 'DO_REPORT_MISSING_SEMICOLONS', doReportSemicolons);
writebool( 'FORM', 'DO_PLAY_SOUNDS', doPlaySounds);
writestring( 'BACKUP', 'BACKUP_FOLDER', backupFolder);
writebool( 'BACKUP', 'ENABLED', doCreateBackups);
writebool( 'BACKUP', 'SHOW_BOTTOM_BAR', doShowBottombar);
writeinteger('BACKUP', 'TYPE', ord(backupType));
writebool( 'FORM', 'SHOW_WELCOME', cbShowWelcomeScreen.checked);
writeString( 'FORM', 'PROJECT_DIR', saveProjectDialog.InitialDir);
writebool( 'CONFIRMATIONS', 'ADDS_TO_USERMAP', confirmations.addsToUserMap);
writebool( 'CONFIRMATIONS', 'COMBINE_STRINGS', confirmations.combineStrings);
writebool( 'CONFIRMATIONS', 'INPUT_SAME_AS_OUTPUT', confirmations.inputSameAsOutputWithPrefix);
writebool( 'CONFIRMATIONS', 'INPUT_SAME_AS_OUTPUT_NO_PREFIX', confirmations.inputSameAsOutputWithoutPrefix);
writebool( 'CONFIRMATIONS', 'INPUT_FOLDER_MISSING', confirmations.inputFolderMissing);
temp := tstringlist.create();
try
for i := 3 to lvFiles.Cols do // start from 3 to ignore image col
temp.add(inttostr(lvFiles.Col[i].Width));
writestring( 'FORM', 'LISTCOLS', temp.CommaText);
temp.clear();
for i := 3 to lvTags.Cols do
temp.add(inttostr(lvTags.Col[i].Width));
writestring( 'FORM', 'LISTCOLS2', temp.CommaText);
finally
temp.Free();
end;
finally free; end;
end;
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TFormSettings.LoadFormSettings;
{$IFDEF CONSOLE}{$ELSE}
var
temp : tstrings;
i : integer;
{$ENDIF}
begin
{$IFDEF CONSOLE}{$ELSE}
for i := 0 to form1.componentCount-1 do
if(form1.components[i] is TCoolbar) then
LoadCoolBar(form1.Coolbar1,RegKey + '\' + form1.components[i].name);
{$ENDIF}
{$IFDEF CONSOLE}{$ELSE}
with Treginifile.create(RegKey) do try
with form1 do begin
Rootkey := HKEY_CURRENT_USER;
//selectedTab := readinteger('FORM', 'ACTIVETAB', filesPane);
firstRun := readBool( 'FORM', 'FIRSTRUN', true);
left := readinteger('FORM', 'LEFT', 100);
top := readinteger('FORM', 'TOP', 100);
width := readinteger('FORM', 'WIDTH', 750);
height := readinteger('FORM', 'HEIGHT', 550);
StateForShow := readinteger('FORM', 'WINDOWSTATE', ord(wsNormal));
FileTree.Width := readinteger('FORM', 'TREEWIDTH', 200);
TagTree.Width := readinteger('FORM', 'TREE2WIDTH', 200);
PlainTextIn.Height := readinteger('FORM', 'PLAINHEIGHT', 130);
LastFilesFolder := readstring( 'FORM', 'LastFilesFolder', appPath());
LastTagsFolder := readstring( 'FORM', 'LastTagsFolder', appPath());
LastFilesOutputFolder := readstring( 'FORM', 'LastFilesOutputFolder', rootPath() + 'output\');
LastTagsOutputFolder := readstring( 'FORM', 'LastTagsOutputFolder', rootPath() + 'output\');
LastFilesMask := readstring( 'FORM', 'LastFilesMask', '*.js');
LastTagsMask := readstring( 'FORM', 'LastTagsMask', '*.htm');
lastTabIndexInProjectEditor := readstring('PROJECTEDIT', 'LASTPAGE', 'basic');
bottomBar.tag := readinteger('FORM', 'BOTTOMBAR', 170);
doShowCompressionSettings:= readbool('FORM', 'SHOW_COMPRESSION_SETTINGS', true);
doReportSemicolons := readbool( 'FORM', 'DO_REPORT_MISSING_SEMICOLONS', true);
doPlaySounds := readbool( 'FORM', 'DO_PLAY_SOUNDS', true);
backupFolder := readstring( 'BACKUP', 'BACKUP_FOLDER', appPath() + 'backup\');
doCreateBackups := readbool( 'BACKUP', 'ENABLED', true);
doShowBottombar := readbool( 'BACKUP', 'SHOW_BOTTOM_BAR', false);
backupType := TBackupType(readinteger('BACKUP', 'TYPE', 0));
cbShowWelcomeScreen.checked := readBool('FORM', 'SHOW_WELCOME', true);
openProjectDialog.InitialDir := readString('FORM', 'PROJECT_DIR', rootPath() + 'projects');
saveProjectDialog.InitialDir := openProjectDialog.InitialDir;
confirmations.addsToUserMap := readbool( 'CONFIRMATIONS', 'ADDS_TO_USERMAP', true);
confirmations.combineStrings := readbool( 'CONFIRMATIONS', 'COMBINE_STRINGS', true);
confirmations.inputSameAsOutputWithPrefix := readbool( 'CONFIRMATIONS', 'INPUT_SAME_AS_OUTPUT', true);
confirmations.inputSameAsOutputWithoutPrefix := readbool( 'CONFIRMATIONS', 'INPUT_SAME_AS_OUTPUT_NO_PREFIX', true);
confirmations.inputFolderMissing := readbool( 'CONFIRMATIONS', 'INPUT_FOLDER_MISSING', true);
if bottomBar.tag > (nb1.Height - 40) then bottomBar.tag := (nb1.Height - 40);
bottomBar.Height := bottomBar.tag;
temp := tstringlist.create();
try
temp.CommaText:=readstring( 'FORM','LISTCOLS', '150,70,60,130,70,70,40');
for i:=0 to temp.Count-1 do
if(lvFiles.Cols > i+2)then
lvFiles.Col[i+3].Width := strtoint(temp[i]);
temp.CommaText:=readstring( 'FORM','LISTCOLS2','150,60,70,70,60,130,40');
for i:=0 to temp.Count-1 do
if(lvTags.Cols > i+2)then
lvTags.Col[i+3].Width := strtoint(temp[i]);
finally
temp.free();
end;
if(not DirectoryExists(LastFilesFolder))then LastFilesFolder := appPath();
if(not DirectoryExists(LastTagsFolder)) then LastTagsFolder := appPath();
if(not DirectoryExists(backupFolder)) then backupFolder := appPath()+'backup\';
//if (PageControl1.ActivePageIndex<0) or (PageControl1.ActivePageIndex>2) then PageControl1.ActivePageIndex:=0;
if height<280 then PlainTextIn.Height:=trunc(height*0.4);
end;
finally free; end;
{$ENDIF}
end;
//------------------------------------------------------------------------------
{$IFDEF CONSOLE}{$ELSE}
procedure TFormSettings.SaveCoolBar(const cb:TCoolBar;const regkey:string;const Root:HKEY=HKEY_CURRENT_USER);
var
i : Integer;
IdStr : String;
begin
with TReginifile.create(regkey) do try
RootKey := Root;
with cb, Bands do begin
for i := 0 to Count-1 do with Bands[i] do begin
IdStr := IntToStr( Id );
EraseSection( IdStr );
writebool( IdStr, 'Break', Break );
WriteInteger( IdStr, 'Width', Width );
WriteInteger( IdStr, 'Index', Index );
end;
end;
finally free() end;
end;
{$ENDIF}
//------------------------------------------------------------------------------
{$IFDEF CONSOLE}{$ELSE}
procedure TFormSettings.LoadCoolBar(const cb:TCoolBar;const regkey:string;const Root:HKEY=HKEY_CURRENT_USER);
var
i : Integer;
band : TCoolBand;
IdStr : String;
begin
with TReginifile.create(regkey) do try
RootKey := Root;
with cb, Bands do begin
for i := 0 to Count-1 do begin
band := TCoolband(Bands.FindItemID(i));
if band = nil then Continue;
with band do begin
IdStr := IntToStr( Id );
Break := ReadBool( IdStr, 'Break', Break );
Width := ReadInteger( IdStr, 'Width', Width );
Index := ReadInteger( IdStr, 'Index', Index );
end;
end;
end;
finally free() end;
end;
{$ENDIF}
//------------------------------------------------------------------------------
procedure TFormSettings.loadMRU(var listOut:tstrings);
var
list : tstrings;
i : integer;
begin
list := tstringlist.create();
try
with TRegistry.Create() do try
RootKey := HKEY_CURRENT_USER;
openkey(MRURegkey, true);
GetValueNames(list);
for i := 0 to list.count-1 do
if(readstring(list[i]) <> '') then
listOut.add(readstring(list[i]));
finally
free();
end;
finally
list.free();
end;
end;
//------------------------------------------------------------------------------
procedure TFormSettings.saveMRU(const listIn:tstrings);
var
i : integer;
begin
with TRegistry.Create() do try
RootKey := HKEY_CURRENT_USER;
deleteKey(MRURegkey);
openkey(MRURegkey, true);
for i := 0 to listIn.count-1 do begin
if(trim(listIn[i]) <> '') then
WriteString(chr(65+i), trim(listIn[i]));
end;
finally
free();
end;
end;
//------------------------------------------------------------------------------
{$IFDEF CONSOLE}{$ELSE}
function TFormSettings.showConfirmation(const msg: string; const messageType: TMsgDlgType; const confirmationType:TConfirmationType): boolean;
var
b : boolean;
begin
result := false;
b := false;
case confirmationType of
ctAddsToUserMap : b := confirmations.addsToUserMap;
ctCombineStrings : b := confirmations.combineStrings;
ctInputSameAsOutputWithPrefix : b := confirmations.inputSameAsOutputWithPrefix;
ctInputSameAsOutputWithoutPrefix : b := confirmations.inputSameAsOutputWithoutPrefix;
ctInputFolderMissing : b := confirmations.inputFolderMissing;
end;
if(not b)then begin
result := true;
exit;
end;
ConfirmationDlg := TConfirmationDlg.create(form1);
try
ConfirmationDlg.label1.Caption := msg;
case messageType of
mtInformation : begin
ConfirmationDlg.width := 295;
ConfirmationDlg.Button1.caption := 'OK';
ConfirmationDlg.caption := 'Information';
end;
mtConfirmation : begin
ConfirmationDlg.width := 380;
ConfirmationDlg.Button1.caption := '&Yes';
ConfirmationDlg.caption := 'Confirmation';
end;
end;
ConfirmationDlg.showmodal();
b := ConfirmationDlg.checkbox1.Checked;
case messageType of
mtInformation : result := b;
mtConfirmation : result := ConfirmationDlg.modalResult = mrOk;
end;
case confirmationType of
ctAddsToUserMap : confirmations.addsToUserMap := b;
ctCombineStrings : confirmations.combineStrings := b;
ctInputSameAsOutputWithPrefix : confirmations.inputSameAsOutputWithPrefix := b;
ctInputSameAsOutputWithoutPrefix : confirmations.inputSameAsOutputWithoutPrefix := b;
ctInputFolderMissing : confirmations.inputFolderMissing := b;
end;
finally
ConfirmationDlg.free();
SaveFormSettings();
end;
end;
{$ENDIF}
//------------------------------------------------------------------------------
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi.
}
unit ormbr.objectset.adapter;
interface
uses
Rtti,
TypInfo,
Classes,
Variants,
SysUtils,
Generics.Collections,
// ORMBr
ormbr.objectset.base.adapter,
ormbr.objects.helper,
dbebr.factory.interfaces,
dbcbr.mapping.classes,
dbcbr.types.mapping;
type
// M - Object M
TObjectSetAdapter<M: class, constructor> = class(TObjectSetBaseAdapter<M>)
private
FConnection: IDBConnection;
public
constructor Create(const AConnection: IDBConnection;
const APageSize: Integer = -1); overload;
destructor Destroy; override;
function Find: TObjectList<M>; overload; override;
function Find(const AID: Integer): M; overload; override;
function Find(const AID: string): M; overload; override;
function FindWhere(const AWhere: string;
const AOrderBy: string = ''): TObjectList<M>; overload; override;
procedure Insert(const AObject: M); override;
procedure Update(const AObject: M); override;
procedure Delete(const AObject: M); override;
end;
implementation
uses
ormbr.session.objectset,
ormbr.core.consts,
dbcbr.mapping.explorer;
{ TObjectSetAdapter<M> }
constructor TObjectSetAdapter<M>.Create(const AConnection: IDBConnection;
const APageSize: Integer);
begin
inherited Create;
FConnection := AConnection;
FSession := TSessionObjectSet<M>.Create(AConnection, APageSize);
end;
destructor TObjectSetAdapter<M>.Destroy;
begin
FSession.Free;
inherited;
end;
procedure TObjectSetAdapter<M>.Delete(const AObject: M);
var
LInTransaction: Boolean;
LIsConnected: Boolean;
begin
inherited;
// Controle de transação externa, controlada pelo desenvolvedor
LInTransaction := FConnection.InTransaction;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
if not LInTransaction then
FConnection.StartTransaction;
try
// Executa comando delete em cascade
CascadeActionsExecute(AObject, CascadeDelete);
// Executa comando delete master
FSession.Delete(AObject);
///
if not LInTransaction then
FConnection.Commit;
except
on E: Exception do
begin
if not LInTransaction then
FConnection.Rollback;
raise Exception.Create(E.Message);
end;
end;
finally
if not LIsConnected then
FConnection.Disconnect;
end;
end;
function TObjectSetAdapter<M>.FindWhere(const AWhere, AOrderBy: string): TObjectList<M>;
var
LIsConnected: Boolean;
begin
inherited;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
Result := FSession.FindWhere(AWhere, AOrderBy);
finally
if not LIsConnected then
FConnection.Disconnect;
end;
end;
function TObjectSetAdapter<M>.Find(const AID: Integer): M;
var
LIsConnected: Boolean;
begin
inherited;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
Result := FSession.Find(AID);
finally
if not LIsConnected then
FConnection.Disconnect;
end;
end;
function TObjectSetAdapter<M>.Find: TObjectList<M>;
var
LIsConnected: Boolean;
begin
inherited;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
Result := FSession.Find;
finally
if not LIsConnected then
FConnection.Disconnect;
end;
end;
procedure TObjectSetAdapter<M>.Insert(const AObject: M);
var
LPrimaryKey: TPrimaryKeyColumnsMapping;
LColumn: TColumnMapping;
LInTransaction: Boolean;
LIsConnected: Boolean;
begin
inherited;
// Controle de transação externa, controlada pelo desenvolvedor
LInTransaction := FConnection.InTransaction;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
if not LInTransaction then
FConnection.StartTransaction;
try
FSession.Insert(AObject);
if FSession.ExistSequence then
begin
LPrimaryKey := TMappingExplorer
.GetMappingPrimaryKeyColumns(AObject.ClassType);
if LPrimaryKey = nil then
raise Exception.Create(cMESSAGEPKNOTFOUND);
for LColumn in LPrimaryKey.Columns do
SetAutoIncValueChilds(AObject, LColumn);
end;
// Executa comando insert em cascade
CascadeActionsExecute(AObject, CascadeInsert);
//
if not LInTransaction then
FConnection.Commit;
except
on E: Exception do
begin
if not LInTransaction then
FConnection.Rollback;
raise Exception.Create(E.Message);
end;
end;
finally
if not LIsConnected then
FConnection.Disconnect;
end;
end;
procedure TObjectSetAdapter<M>.Update(const AObject: M);
var
LRttiType: TRttiType;
LProperty: TRttiProperty;
LObjectKey: TObject;
LKey: string;
LInTransaction: Boolean;
LIsConnected: Boolean;
begin
inherited;
// Controle de transação externa, controlada pelo desenvolvedor
LInTransaction := FConnection.InTransaction;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
if not LInTransaction then
FConnection.StartTransaction;
try
// Executa comando update em cascade
CascadeActionsExecute(AObject, CascadeUpdate);
// Gera a lista com as propriedades que foram alteradas
if TObject(AObject).GetType(LRttiType) then
begin
LKey := GenerateKey(AObject);
if FObjectState.TryGetValue(LKey, LObjectKey) then
begin
FSession.ModifyFieldsCompare(LKey, LObjectKey, AObject);
FSession.Update(AObject, LKey);
FObjectState.Remove(LKey);
FObjectState.TrimExcess;
end;
// Remove o item excluído em Update Mestre-Detalhe
for LObjectKey in FObjectState.Values do
FSession.Delete(LObjectKey);
end;
if not LInTransaction then
FConnection.Commit;
except
on E: Exception do
begin
if not LInTransaction then
FConnection.Rollback;
raise Exception.Create(E.Message);
end;
end;
finally
if not LIsConnected then
FConnection.Disconnect;
FObjectState.Clear;
// Após executar o comando SQL Update, limpa a lista de campos alterados.
FSession.ModifiedFields.Clear;
FSession.ModifiedFields.TrimExcess;
FSession.DeleteList.Clear;
FSession.DeleteList.TrimExcess;
end;
end;
function TObjectSetAdapter<M>.Find(const AID: string): M;
var
LIsConnected: Boolean;
begin
inherited;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
Result := FSession.Find(AID);
finally
if not LIsConnected then
FConnection.Disconnect;
end;
end;
end.
|
unit uConsultaNotaFiscal;
interface
uses
RLConsts,
DateUtils,
FileCtrl,
System.IOUtils,
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, dxSkinsCore,
dxSkinscxPCPainter, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxCheckBox,
cxContainer, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, cxLabel, dxGDIPlusClasses, Vcl.ExtCtrls, cxGridLevel, cxGridCustomTableView,
cxGridTableView, cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, dxSkinOffice2013White, dxBarBuiltInMenu, Vcl.Menus,
cxTextEdit, cxButtons, cxPC, Vcl.StdCtrls, Vcl.ComCtrls, ACBrNFeDANFEClass, ACBrNFeDANFeRLClass, ACBrNFe, Vcl.ToolWin,
Vcl.ImgList, dxSkinsDefaultPainters, ACBrBase, ACBrDFe, ACBrMail, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, ACBrDFeReport, ACBrDFeDANFeReport;
type
TFr_ConsultaNotaFiscal = class(TForm)
cxGridNotaFiscal: TcxGrid;
cxGridLevelNotaFiscal: TcxGridLevel;
cxTableViewNotaFiscal: TcxGridDBTableView;
FDConnection: TFDConnection;
PanelSQLSplashScreen: TPanel;
ImageSQLSplashScreen: TImage;
cxLabelMensagem: TcxLabel;
cxPageControlFiltro: TcxPageControl;
cxTabSheetFiltro: TcxTabSheet;
cxButtonRefresh: TcxButton;
Label1: TLabel;
Label2: TLabel;
LabeledEditCNPJ: TLabeledEdit;
LabeledEditRazaoSocial: TLabeledEdit;
LabeledEditNumeroNFeInicial: TLabeledEdit;
LabeledEditNumeroNFeFinal: TLabeledEdit;
DateTimePickerEmissaoNFeInicial: TDateTimePicker;
DateTimePickerEmissaoNFeFinal: TDateTimePicker;
LabeledEditPlanta: TLabeledEdit;
LabeledEditCodigoCliente: TLabeledEdit;
LabeledEditDescricaoItem: TLabeledEdit;
LabeledEditInformacaoComplementar: TLabeledEdit;
LabeledEditCodigoItem: TLabeledEdit;
LabeledEditObservacaoNF: TLabeledEdit;
LabeledEditIE: TLabeledEdit;
RadioGroupOrdenar: TRadioGroup;
FDQuery: TFDQuery;
FDQueryCOD_FILIAL: TStringField;
FDQueryNUM_NF: TStringField;
FDQuerySERIE: TStringField;
FDQueryCOD_CLIFOR: TStringField;
FDQueryCNPJ: TStringField;
FDQueryINSC_ESTADUAL: TStringField;
FDQueryRAZAO_SOCIAL: TStringField;
FDQueryDT_EMISSAO: TSQLTimeStampField;
FDQueryNOME_MUNICIPIO_DEST: TStringField;
FDQueryCOD_UF: TStringField;
FDQueryENDERECO_ELETRONICO: TStringField;
FDQueryTOTAL_NOTA: TBCDField;
FDQueryID_NFE: TStringField;
FDQueryXML_CAPA: TMemoField;
FDQueryXML_DOCUMENTO: TMemoField;
ACBrNFeDANFeRL: TACBrNFeDANFeRL;
ACBrNFe: TACBrNFe;
DataSource: TDataSource;
cxTableViewNotaFiscalCOD_FILIAL: TcxGridDBColumn;
cxTableViewNotaFiscalNUM_NF: TcxGridDBColumn;
cxTableViewNotaFiscalSERIE: TcxGridDBColumn;
cxTableViewNotaFiscalCOD_CLIFOR: TcxGridDBColumn;
cxTableViewNotaFiscalCNPJ: TcxGridDBColumn;
cxTableViewNotaFiscalINSC_ESTADUAL: TcxGridDBColumn;
cxTableViewNotaFiscalRAZAO_SOCIAL: TcxGridDBColumn;
cxTableViewNotaFiscalDT_EMISSAO: TcxGridDBColumn;
cxTableViewNotaFiscalNOME_MUNICIPIO_DEST: TcxGridDBColumn;
cxTableViewNotaFiscalCOD_UF: TcxGridDBColumn;
cxTableViewNotaFiscalENDERECO_ELETRONICO: TcxGridDBColumn;
cxTableViewNotaFiscalTOTAL_NOTA: TcxGridDBColumn;
ImageListMenu: TImageList;
ToolBarMenu: TToolBar;
ToolButtonEmail: TToolButton;
ToolButton2: TToolButton;
ToolButtonSalvar: TToolButton;
ACBrMail: TACBrMail;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
procedure FormCreate(Sender: TObject);
procedure cxButtonRefreshClick(Sender: TObject);
procedure ToolButtonSalvarClick(Sender: TObject);
procedure ToolButtonEmailClick(Sender: TObject);
private
function getXML: String;
procedure Mensagem( pMensagem: String );
{ Private declarations }
public
procedure AbrirDataset;
procedure LoadGridCustomization;
{ Public declarations }
end;
var
Fr_ConsultaNotaFiscal: TFr_ConsultaNotaFiscal;
implementation
{$R *.dfm}
uses uUtils, uBrady;
procedure TFr_ConsultaNotaFiscal.AbrirDataset;
begin
if not FDConnection.Connected then
begin
Mensagem( 'Abrindo conexão...' );
try
FDConnection.Params.LoadFromFile( MyDocumentsPath + '\DB-SONDA.ini' );
FDConnection.Open;
finally
Mensagem( EmptyStr );
end;
end;
end;
procedure TFr_ConsultaNotaFiscal.cxButtonRefreshClick(Sender: TObject);
var
varSQL: String;
begin
FDQuery.SQL.Clear;
varSQL := varSQL + 'SELECT A01.COD_FILIAL'#13#10;
varSQL := varSQL + ' ,A01.NUM_NF'#13#10;
varSQL := varSQL + ' ,A01.SERIE'#13#10;
varSQL := varSQL + ' ,A01.COD_CLIFOR'#13#10;
varSQL := varSQL + ' ,A01.RAZAO_SOCIAL'#13#10;
varSQL := varSQL + ' ,A01.CNPJ'#13#10;
varSQL := varSQL + ' ,A01.INSC_ESTADUAL'#13#10;
varSQL := varSQL + ' ,A01.DT_EMISSAO'#13#10;
varSQL := varSQL + ' ,A01.NOME_MUNICIPIO_DEST'#13#10;
varSQL := varSQL + ' ,A01.COD_UF'#13#10;
varSQL := varSQL + ' ,A01.ENDERECO_ELETRONICO'#13#10;
varSQL := varSQL + ' ,A01.TOTAL_NOTA'#13#10;
varSQL := varSQL + ' ,A01.ID_NFE'#13#10;
varSQL := varSQL + ' ,A01.XML AS XML_CAPA'#13#10;
varSQL := varSQL + ' ,B01.XML AS XML_DOCUMENTO'#13#10;
varSQL := varSQL + 'FROM NFE_NF_CAPA (NOLOCK) A01 INNER JOIN NFE_DOCUMENTO_XML (NOLOCK) B01 ON ( A01.ID_REGISTRO = B01.ID_REGISTRO )'#13#10;
varSQL := varSQL + 'WHERE A01.STATUS_PROCESSAMENTO IN ( 99, 98 )'#13#10;
varSQL := varSQL + ' AND B01.ID_TP_DOC = ''XRCON'''#13#10;;
varSQL := varSQL + ' AND A01.COD_HOLDING = ''WHBBRA'''#13#10;
varSQL := varSQL + ' AND A01.COD_MATRIZ = ''4100'''#13#10;
if LabeledEditPlanta.Text <> EmptyStr then
varSQL := varSQL + ' AND A01.COD_FILIAL LIKE '''+ StringReplace(LabeledEditPlanta.Text,'*','%',[rfReplaceAll]) +''''#13#10;
varSQL := varSQL + ' AND A01.NUM_NF >= '+ LabeledEditNumeroNFeInicial.Text +#13#10;
varSQL := varSQL + ' AND A01.NUM_NF <= '+ LabeledEditNumeroNFeFinal.Text +#13#10;
varSQL := varSQL + ' AND A01.DT_EMISSAO >= '''+ FormatDateTime( 'yyyymmdd', DateTimePickerEmissaoNFeInicial.Date ) +' 00:00:00.000'''#13#10;
varSQL := varSQL + ' AND A01.DT_EMISSAO <= '''+ FormatDateTime( 'yyyymmdd', DateTimePickerEmissaoNFeFinal.Date ) +' 23:59:59.997'''#13#10;
if LabeledEditCodigoCliente.Text <> EmptyStr then
varSQL := varSQL + ' AND A01.COD_CLIFOR LIKE '''+ StringReplace(LabeledEditCodigoCliente.Text,'*','%',[rfReplaceAll]) +''''#13#10;
if LabeledEditCNPJ.Text <> EmptyStr then
varSQL := varSQL + ' AND A01.CNPJ LIKE '''+ StringReplace(LabeledEditCNPJ.Text,'*','%',[rfReplaceAll]) +''''#13#10;
if LabeledEditIE.Text <> EmptyStr then
varSQL := varSQL + ' AND A01.INSC_ESTADUAL LIKE '''+ StringReplace(LabeledEditIE.Text,'*','%',[rfReplaceAll]) +''''#13#10;
if LabeledEditRazaoSocial.Text <> EmptyStr then
varSQL := varSQL + ' AND A01.RAZAO_SOCIAL LIKE '''+ StringReplace(LabeledEditRazaoSocial.Text,'*','%',[rfReplaceAll]) +''''#13#10;
if (LabeledEditDescricaoItem.Text+LabeledEditInformacaoComplementar.Text+LabeledEditCodigoItem.Text) <> EmptyStr then
begin
varSQL := varSQL + ' AND EXISTS( SELECT 1'#13#10;
varSQL := varSQL + ' FROM NFE_NF_ITEM A02'#13#10;
varSQL := varSQL + ' WHERE A01.COD_HOLDING = A02.COD_HOLDING'#13#10;
varSQL := varSQL + ' AND A01.COD_MATRIZ = A02.COD_MATRIZ'#13#10;
varSQL := varSQL + ' AND A01.COD_FILIAL = A02.COD_FILIAL'#13#10;
varSQL := varSQL + ' AND A01.COD_INTERFACE = A02.COD_INTERFACE'#13#10;
varSQL := varSQL + ' AND A01.DOCNUM = A02.DOCNUM'#13#10;
varSQL := varSQL + ' AND A01.TIPO_NOTA = A02.TIPO_NOTA'#13#10;
if LabeledEditDescricaoItem.Text <> EmptyStr then
varSQL := varSQL + ' AND A02.DESC_PRODUTO LIKE '''+ StringReplace(LabeledEditDescricaoItem.Text,'*','%',[rfReplaceAll]) +''''#13#10;
if LabeledEditInformacaoComplementar.Text <> EmptyStr then
varSQL := varSQL + ' AND A02.INF_COMPLEMENTAR LIKE '''+ StringReplace(LabeledEditInformacaoComplementar.Text,'*','%',[rfReplaceAll]) +''''#13#10;
if LabeledEditCodigoItem.Text <> EmptyStr then
varSQL := varSQL + ' AND A02.COD_PRODUTO LIKE '''+ StringReplace(LabeledEditCodigoItem.Text,'*','%',[rfReplaceAll]) +''' )'#13#10;
end;
if LabeledEditObservacaoNF.Text <> EmptyStr then
begin
varSQL := varSQL + ' AND EXISTS( SELECT 1'#13#10;
varSQL := varSQL + ' FROM NFE_NF_OBSERVACAO A02'#13#10;
varSQL := varSQL + ' WHERE A01.COD_HOLDING = A02.COD_HOLDING'#13#10;
varSQL := varSQL + ' AND A01.COD_MATRIZ = A02.COD_MATRIZ'#13#10;
varSQL := varSQL + ' AND A01.COD_FILIAL = A02.COD_FILIAL'#13#10;
varSQL := varSQL + ' AND A01.COD_INTERFACE = A02.COD_INTERFACE'#13#10;
varSQL := varSQL + ' AND A01.DOCNUM = A02.DOCNUM'#13#10;
varSQL := varSQL + ' AND A01.TIPO_NOTA = A02.TIPO_NOTA'#13#10;
if LabeledEditObservacaoNF.Text <> EmptyStr then
varSQL := varSQL + ' AND A02.DESC_COMPLEMENTAR LIKE '''+ StringReplace(LabeledEditObservacaoNF.Text,'*','%',[rfReplaceAll]) +''' )'#13#10;
end;
if RadioGroupOrdenar.ItemIndex = 0 then
begin
varSQL := varSQL + 'ORDER BY A01.DT_EMISSAO'#13#10;
varSQL := varSQL + ' ,A01.COD_FILIAL'#13#10;
varSQL := varSQL + ' ,A01.NUM_NF'#13#10;
varSQL := varSQL + ' ,A01.SERIE';
end
else
if RadioGroupOrdenar.ItemIndex = 1 then
begin
varSQL := varSQL + 'ORDER BY A01.COD_FILIAL'#13#10;
varSQL := varSQL + ' ,A01.RAZAO_SOCIAL'#13#10;
varSQL := varSQL + ' ,A01.NUM_NF'#13#10;
varSQL := varSQL + ' ,A01.SERIE';
end
else
if RadioGroupOrdenar.ItemIndex = 2 then
begin
varSQL := varSQL + 'ORDER BY A01.COD_FILIAL'#13#10;
varSQL := varSQL + ' ,A01.CNPJ'#13#10;
varSQL := varSQL + ' ,A01.NUM_NF'#13#10;
varSQL := varSQL + ' ,A01.SERIE';
end;
FDQuery.SQL.Add(varSQL);
FDQuery.Close;
FDQuery.Open;
end;
procedure TFr_ConsultaNotaFiscal.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FDQuery.Close;
FDConnection.Close;
Fr_ConsultaNotaFiscal := nil;
Action := caFree;
end;
procedure TFr_ConsultaNotaFiscal.FormContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
begin
Fr_Brady.PopupGridTools( cxGridNotaFiscal.ActiveView );
end;
procedure TFr_ConsultaNotaFiscal.FormCreate(Sender: TObject);
begin
LoadGridCustomization;
ACBrNFeDANFeRL.Logo := ExtractFileDir(ParamStr(0)) + '\brady-co-logo.jpg';
DateTimePickerEmissaoNFeInicial.Date := Trunc(StartOfTheMonth(Now));
DateTimePickerEmissaoNFeFinal.Date := Trunc(EndOfTheMonth(Now));
end;
function TFr_ConsultaNotaFiscal.getXML: String;
begin
Result := StringReplace( FDQuery.FieldByName('XML_CAPA').AsString, '<?xml version="1.0" encoding="UTF-8"?>', '<?xml version="1.0" encoding="UTF-8"?><nfeProc versao="3.10" xmlns="http://www.portalfiscal.inf.br/nfe">', [rfReplaceAll] ) + FDQuery.FieldByName('XML_DOCUMENTO').AsString + '</nfeProc>';
end;
procedure TFr_ConsultaNotaFiscal.LoadGridCustomization;
begin
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + Name + '_' + cxTableViewNotaFiscal.Name + '.ini' ) then
cxTableViewNotaFiscal.RestoreFromIniFile( MyDocumentsPath + '\' + Name + '_' + cxTableViewNotaFiscal.Name + '.ini' );
end;
procedure TFr_ConsultaNotaFiscal.Mensagem(pMensagem: String);
begin
cxLabelMensagem.Caption := pMensagem;
PanelSQLSplashScreen.Visible := not pMensagem.IsEmpty;
Update;
Application.ProcessMessages;
end;
procedure TFr_ConsultaNotaFiscal.ToolButtonEmailClick(Sender: TObject);
var
I, X: Integer;
varMsg: TStringList;
varEmailPara: String;
varXML: TStringList;
varAnexos: TStringList;
varCC: TStringList;
varSMTP: TStringList;
begin
if cxTableViewNotaFiscal.DataController.GetSelectedCount = 0 then
raise Exception.Create('Selecione pelo menos uma nota fiscal.');
varMsg := TStringList.Create;
varAnexos := TStringList.Create;
varCC := TStringList.Create;
varSMTP := TStringList.Create;
try
if FileExists(ExtractFileDir(ParamStr(0)) + '\SMPT-'+ WUserName.Trim.ToUpper +'.ini') then
begin
varSMTP.LoadFromFile(ExtractFileDir(ParamStr(0)) + '\SMPT-'+ WUserName.Trim.ToUpper +'.ini');
end
else
begin
varSMTP.LoadFromFile(ExtractFileDir(ParamStr(0)) + '\SMPT.ini');
end;
varMsg.Add('Prezado Cliente, ');
varMsg.Add(' ');
varMsg.Add('Segue em anexo nota fiscal (DANFE/XML).');
varEmailPara := InputBox( 'Configuração - use ; para mais de um email', 'Email para', FDQuery.FieldByName('ENDERECO_ELETRONICO').AsString );
if Trim(varEmailPara) = EmptyStr then
raise Exception.Create('Email para não foi informado.');
for I := 0 to cxTableViewNotaFiscal.DataController.GetSelectedCount -1 do
begin
FDQuery.GotoBookmark(cxTableViewNotaFiscal.DataController.GetSelectedBookmark(I));
ACBrNFeDANFeRL.PathPDF := MyDocumentsPath + '\';
ACBrNFe.NotasFiscais.Clear;
ACBrNFe.NotasFiscais.LoadFromString(getXML, False);
ACBrNFe.NotasFiscais.ImprimirPDF;
varXML := TStringList.Create;
try
varXML.Add(getXML);
varXML.SaveToFile( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.xml');
finally
FreeAndNil(varXML);
end;
X := 0;
while not System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.pdf' ) do
begin
Inc(X);
Sleep(1000);
Application.ProcessMessages;
if X = 60 then
Break;
end;
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.pdf' ) then
varAnexos.Add( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.pdf' );
if System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.xml' ) then
varAnexos.Add( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.xml' );
end;
if varAnexos.Count > 0 then
begin
ACBrMail.Clear;
ACBrMail.Host := varSMTP.Values['HOST'];
ACBrMail.Port := varSMTP.Values['PORT'];
ACBrMail.SetSSL := varSMTP.Values['SSL'] = 'Sim';
ACBrMail.SetTLS := varSMTP.Values['TLS'] = 'Sim';
ACBrMail.Username := varSMTP.Values['USER'];
ACBrMail.Password := varSMTP.Values['PWD'];
ACBrMail.From := varSMTP.Values['FROM'];
ACBrMail.FromName := varSMTP.Values['FROM'];
Sleep(2000);
Application.ProcessMessages;
for X := 0 to Length(varEmailPara.Split([';']))-1 do
begin
if X = 0 then
ACBrMail.AddAddress(varEmailPara.Split([';'])[X])
else
ACBrMail.AddCC(varEmailPara.Split([';'])[X]);
end;
ACBrMail.Subject := varSMTP.Values['ASSUNTO'] + ' - ' + IntToStr(ACBrNFe.NotasFiscais[0].NFe.Ide.nNF);
ACBrMail.IsHTML := True;
ACBrMail.AltBody.Text := varMsg.Text;
for X := 0 to varAnexos.Count-1 do
begin
ACBrMail.AddAttachment( varAnexos[X] );
end;
try
ACBrMail.Send;
except
on E: Exception do
begin
Writeln( 'Erro ao enviar email: ' + E.Message );
end;
end;
end;
finally
FreeAndNil(varMsg);
FreeAndNil(varAnexos);
FreeAndNil(varCC);
end;
end;
procedure TFr_ConsultaNotaFiscal.ToolButtonSalvarClick(Sender: TObject);
var
varXML: TStringList;
I, X: Integer;
varDir: String;
begin
if cxTableViewNotaFiscal.DataController.GetSelectedCount = 0 then
raise Exception.Create('Selecione pelo menos uma nota fiscal.');
if SelectDirectory('Selecione o Diretório', EmptyStr, varDir, [sdNewUI, sdNewFolder]) then
begin
varDir := varDir + '/';
for I := 0 to cxTableViewNotaFiscal.DataController.GetSelectedCount -1 do
begin
FDQuery.GotoBookmark(cxTableViewNotaFiscal.DataController.GetSelectedBookmark(I));
ACBrNFeDANFeRL.PathPDF := MyDocumentsPath + '\';
ACBrNFe.NotasFiscais.Clear;
ACBrNFe.NotasFiscais.LoadFromString(getXML, False);
ACBrNFe.NotasFiscais.ImprimirPDF;
varXML := TStringList.Create;
try
varXML.Add(getXML);
varXML.SaveToFile(MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.xml');
finally
FreeAndNil(varXML);
end;
X := 0;
while not System.IOUtils.TFile.Exists( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.pdf' ) do
begin
Inc(X);
Sleep(1000);
Application.ProcessMessages;
if X = 60 then
Break;
end;
System.IOUtils.TFile.Copy( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.xml', varDir + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.xml', True );
System.IOUtils.TFile.Copy( MyDocumentsPath + '\' + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.pdf', varDir + StringReplace(ACBrNFe.NotasFiscais[0].NFe.infNFe.ID,'NFe', '', [rfIgnoreCase]) + '-nfe.pdf', True );
end;
end;
end;
//initialization
// SetVersion( CommercialVersion, ReleaseVersion, CommentVersion );
end.
|
unit Seqnum;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs;
type
TSequenceNumber = class(TComponent)
private
{ Private declarations }
fSequenceValue: longint;
fRollOver: boolean;
fWarningBeforeOffset: integer;
fWarningAfterOffset: integer;
protected
{ Protected declarations }
function GetSequence: string;
procedure SetSequence(value: longint);
function GetValue: longint;
procedure SetValue(sequence: string);
function AddZeros:string;
function GetRollover: boolean;
procedure SetRollover(RollOver: boolean);
function GetWarningBeforeOffset: integer;
procedure SetWarningBeforeOffset(WarningBeforeOffset: integer);
function GetWarningAfterOffset: integer;
procedure SetWarningAfterOffset(WarningAfterOffset: integer);
public
{ Public declarations }
constructor Create(Owner: TComponent); override;
procedure Increment; virtual;
procedure Decrement; virtual;
function CountWillRoll(count: integer): boolean;
published
{ Published declarations }
property SequenceValue: longint
read GetValue
write SetSequence;
property SequenceNumber: string
read GetSequence
write SetValue;
property RolloverWarning: boolean
read GetRollover
write SetRollover;
property WarningBeforeOffset: integer
read GetWarningBeforeOffset
write SetWarningBeforeOffset;
property WarningAfterOffset: integer
read GetWarningAfterOffset
write SetWarningAfterOffset;
end;
implementation
constructor TSequenceNumber.Create(Owner: TComponent);
begin
inherited Create(Owner);
fSequenceValue:=1;
end;
procedure TSequenceNumber.Increment;
begin
Inc(fSequenceValue);
if fSequenceValue > 9999 then
fSequenceValue:=1;
end;
procedure TSequenceNumber.Decrement;
begin
Dec(fSequenceValue);
if fSequenceValue < 1 then
fSequenceValue:=9999;
end;
function TSequenceNumber.CountWillRoll(count: integer): boolean;
begin
if count+fSequenceValue>9999 then
result:=true
else
result:=false;
end;
function TSequenceNumber.GetRollover: boolean;
begin
result:=fRollover;
end;
procedure TSequenceNumber.SetRollover(RollOver: boolean);
begin
fRollover:=Rollover;
end;
function TSequenceNumber.GetWarningBeforeOffset: integer;
begin
Result:=fWarningBeforeOffset;
end;
procedure TSequenceNumber.SetWarningBeforeOffset(WarningBeforeOffset: integer);
begin
fWarningBeforeOffset:=WarningBeforeOffset;
end;
function TSequenceNumber.GetWarningAfterOffset: integer;
begin
Result:=fWarningAfterOffset;
end;
procedure TSequenceNumber.SetWarningAfterOffset(WarningAfterOffset: integer);
begin
fWarningAfterOffset:=WarningAfterOffset;
end;
function TSequenceNumber.GetValue: longint;
begin
result:=fSequenceValue;
end;
procedure TSequenceNumber.SetSequence(value: longint);
begin
if (value>9999) or (value<1) then
value:=1;
fSequenceValue:=value;
end;
function TSequenceNumber.GetSequence: string;
begin
result:=AddZeros;
end;
procedure TSequenceNumber.SetValue(sequence: string);
begin
if length(sequence) > 4 then
begin
fSequenceValue:=1;
end
else
begin
try
if (StrToInt(sequence)<1) or (StrToInt(sequence)>9999) then
begin
fSequenceValue:=1;
end
else
begin
fSequenceValue:=StrToInt(sequence);
end;
except
fSequenceValue:=1;
end;
end;
end;
function TSequenceNumber.AddZeros:string;
var
s, data: string;
i,j: integer;
begin
data:=IntToStr(fSequenceValue);
result := data;
j:=1;
s:='';
if length(data) < 4 then
begin
for i := 1 to 4 - length(data) do
begin
insert('0', s, j);
INC(j);
end;
insert(data,s,j);
result := s;
end;
end;
end.
|
unit mainfm;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
Grids, Crypto,
DCPblowfish, DCPtwofish, DCPcast128, DCPcast256, DCPice, DCPidea, DCPdes,
DCPrc2, DCPrc5, DCPrc6, DCPrijndael, DCPserpent, DCPtea,
DCPhaval, DCPmd4, DCPmd5, DCPripemd128, DCPripemd160, DCPsha1, DCPsha256,
DCPsha512, DCPtiger;
type
{ TForm1 }
TForm1 = class(TForm)
SelfTestBtn: TButton;
Grid: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SelfTestBtnClick(Sender: TObject);
private
procedure TestCipher(AClass: TCipherClass);
procedure TestCipherPerf(AClass: TCipherClass; Mode: TCipherMode; var EncPerf,
DecPerf: Single; var ErrorCount: Integer);
procedure TestHash(AClass: THashClass);
procedure TestHashPerf(AClass: THashClass; var Perf: Single);
{ private declarations }
public
RandData: TMemoryStream;
end;
var
Form1: TForm1;
implementation
uses
DateUtils, cryptoutils, Rand;
{$R *.lfm}
{ TForm1 }
procedure TForm1.TestHashPerf(AClass: THashClass; var Perf: Single);
var
H: THash;
D: Pointer;
ST, ET: TDateTime;
begin
H := AClass.Create;
try
D := GetMem(AClass.HashSize div 8);
try
ST := Now;
H.Init;
H.UpdateStream(RandData,RandData.Size);
H.Final(D^);
ET := Now;
Perf := 1000 / MillisecondsBetween(ET,ST);
RandData.Position := 0;
finally
FreeMem(D);
end;
finally
H.Free;
end;
end;
procedure TForm1.TestHash(AClass: THashClass);
var
SelfTestResult: String;
Perf: Single;
begin
if AClass.SelfTest then
SelfTestResult := 'Pass'
else
SelfTestResult := 'FAIL';
TestHashPerf(AClass,Perf);
Grid.InsertRowWithValues(Grid.RowCount,['Hash',HASH_ALGORITHM_STR[AClass.Algorithm],'',IntToStr(AClass.HashSize),'',SelfTestResult,Format('%.2f MB/S',[Perf]),'','']);
end;
function CountStreamDifferences(Stream1,Stream2: TStream): Integer;
var
X: Integer;
B1, B2: Byte;
begin
Result := 0;
if Stream1.Size <> Stream2.Size then
Result := $7FFFFFFF
else
for X := 1 to Stream1.Size do
begin
Stream1.Read(B1,SizeOf(B1));
Stream2.Read(B2,SizeOf(B2));
if B1 <> B2 then
inc(Result);
end;
end;
procedure TForm1.TestCipherPerf(AClass: TCipherClass; Mode: TCipherMode; var EncPerf, DecPerf: Single; var ErrorCount: Integer);
var
ST, ET: TDateTime;
C: TCipher;
K: Pointer;
IVSize: Integer;
IV: Pointer;
Temp1,Temp2: TMemoryStream;
begin
Temp1 := nil;
Temp2 := nil;
ErrorCount := 0;
K := GetMem(AClass.MaxKeySize div 8);
IVSize := AClass.BlockSize div 8;
if IVSize > 0 then
IV := GetMem(IVSize);
try
FillRandom(K,AClass.MaxKeySize div 8);
if IVSize > 0 then
FillRandom(IV,IVSize);
C := AClass.Create(@K,AClass.MaxKeySize div 8);
C.InitMode(Mode,@IV);
Temp1 := TMemoryStream.Create;
Temp2 := TMemoryStream.Create;
try
ST := Now;
ET := Now;
EncPerf := MillisecondsBetween(ET,ST);
DecPerf := EncPerf;
RandData.Position := 0;
ST := Now;
C.EncryptStream(RandData,Temp1);
ET := Now;
EncPerf := EncPerf + MillisecondsBetween(ET,ST);
RandData.Position := 0;
Temp1.Position := 0;
ST := Now;
C.InitMode(Mode,@IV);
C.DecryptStream(Temp1,Temp2);
ET := Now;
DecPerf := DecPerf + MillisecondsBetween(ET,ST);
Temp2.Position := 0;
ErrorCount := CountStreamDifferences(RandData,Temp2);
RandData.Position := 0;
finally
FreeAndNil(Temp1);
FreeAndNil(Temp2);
end;
finally
if IVSize > 0 then
FreeMem(IV);
FreeMem(K);
C.Free;
end;
EncPerf := 1000 / EncPerf;
DecPerf := 1000 / DecPerf;
end;
procedure TForm1.TestCipher(AClass: TCipherClass);
var
SelfTestResult: String;
Mode: TCipherMode; //cmCBC, cmCFB, cmOFB, cmCTR
ModeStr: String;
EncPerf: Single;
DecPerf: Single;
ErrorCount: Integer;
begin
if AClass.SelfTest then
SelfTestResult := 'Pass'
else
SelfTestResult := 'FAIL';
for Mode := Low(Mode) to High(Mode) do
begin
ModeStr := CIPHER_MODE_STR[Mode];
TestCipherPerf(AClass,Mode,EncPerf,DecPerf,ErrorCount);
Grid.InsertRowWithValues(Grid.RowCount,['Cipher',CIPHER_ALGORITHM_STR[AClass.Algorithm],ModeStr,IntToStr(AClass.MaxKeySize),IntToStr(AClass.BlockSize),SelfTestResult,Format('%.2f MB/S',[EncPerf]),Format('%.2f MB/S',[DecPerf]),IntToStr(ErrorCount)]);
Application.ProcessMessages;
if ModeStr = 'Stream' then Exit;
end;
end;
procedure TForm1.SelfTestBtnClick(Sender: TObject);
begin
Grid.RowCount := 1;
TestCipher(TCipherBlowfish); TestCipher(TCipherCAST128); TestCipher(TCipherCAST256); TestCipher(TCipherDES); TestCipher(TCipher3DES);
TestCipher(TCipherICE); TestCipher(TCipherThinICE); TestCipher(TCipherICE2); TestCipher(TCipherIDEA);
TestCipher(TCipherRC2); TestCipher(TCipherRC5); TestCipher(TCipherRC6); TestCipher(TCipherRijndael);
TestCipher(TCipherSerpent); TestCipher(TCipherTEA); TestCipher(TCipherTwofish);
TestHash(THashHaval); TestHash(THashMD4); TestHash(THashMD5); TestHash(THashRipeMD128); TestHash(THashRipeMD160);
TestHash(THashSHA1); TestHash(THashSHA256); TestHash(THashSHA384); TestHash(THashSHA512); TestHash(THashTiger);
end;
procedure TForm1.FormCreate(Sender: TObject);
var
X: Integer;
R: Cardinal;
begin
RandData := TMemoryStream.Create;
for X := 1 to 1024 * 1024 do
begin
R := RNG.Generate;
RandData.Write(R,SizeOf(R));
end;
RandData.Position := 0;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
RandData.Free;
end;
end.
|
unit uUTM;
interface
uses Classes, SysUtils, StrUtils, uLog, IdHTTP, uLogic,
Generics.Collections, Generics.Defaults;
type
TUTMstring = class
Url: String;
ReplyID: String;
end;
var
InboxUTMList: TList<TUTMstring>;
OutboxUTMList: TList<TUTMstring>;
function CheckUTMServer(aAddress: String = ''): Boolean;
function LoadStringFromUTM(RequestURL: String; out ResultString: String): Boolean;
function LoadStreamFromUTM(RequestURL: String; ResultStream: TStream): Boolean;
function LoadFileFromUTM(RequestURL: String; FileName: String): Boolean;
function SendStreamToUTM(DestinationURL: String; InboxStream: TMemoryStream; out ServerAnswer: String): Boolean;
//function SendFileToUTM(DestinationURL: String; FileName: String; out ServerAnswer: String): Boolean;
function GetInboxFileList(): TList<TUTMstring>;
function GetOutboxFileList(): TList<TUTMstring>;
function DeleteUTMobject(Url: string): Boolean;
function DeleteUTMObjectByReplyID(ReplyID: string): Boolean;
implementation
uses uXML;
function CheckUTMServer(aAddress: String = ''): Boolean;
var
HTTP: TIdHTTP;
begin
if aAddress = '' then aAddress:= GetUTMaddress();
try
HTTP:= TIdHTTP.Create(nil);
HTTP.Head(aAddress);
Result:= True;
HTTP.Free;
Except on E:Exception do begin
HTTP.Free;
Result:= False;
end;
end;
end;
function LoadStringFromUTM(RequestURL: String; out ResultString: String): Boolean;
var
HTTP: TIdHTTP;
begin
try
HTTP:= TIdHTTP.Create(nil);
ResultString:= HTTP.Get(RequestURL);
Result:= True;
HTTP.Free;
Except on E:Exception do begin
ErrorLog(e, 'LoadStreamFromUTM' , False);
Log('Неудачная загрузка данных, статус возврата: ' + HTTP.ResponseCode.ToString() );
Log('Ответ сервера: ' + HTTP.ResponseText);
HTTP.Free;
Result:= False;
end;
end;
end;
function LoadStreamFromUTM(RequestURL: String; ResultStream: TStream): Boolean;
var
HTTP: TIdHTTP;
begin
try
HTTP:= TIdHTTP.Create(nil);
HTTP.Get(RequestURL, ResultStream);
Result:= True;
HTTP.Free;
Except on E:Exception do begin
ErrorLog(e, 'LoadStreamFromUTM' , False);
Log('Неудачная загрузка данных, статус возврата: ' + HTTP.ResponseCode.ToString() );
Log('Ответ сервера: ' + HTTP.ResponseText);
HTTP.Free;
Result:= False;
end;
end;
end;
function LoadFileFromUTM(RequestURL: String; FileName: String): Boolean;
var Stream: TFileStream;
begin
try
Stream:= TFileStream.Create(strInboxFolder + FileName, fmCreate);
Result:= LoadStreamFromUTM(RequestURL, Stream);
if Result then
Log('Загружен файл ' + FileName)
else
Log('Ошибка загрузки файла из УТМ');
finally
Stream.Free;
end;
end;
function SendStreamToUTM(DestinationURL: String; InboxStream: TMemoryStream; out ServerAnswer: String): Boolean;
var
HTTP: TIdHTTP;
Boundary: String;
SendStream: TStringStream;
begin
try
HTTP:= TIdHTTP.Create(nil);
SendStream:= TStringStream.Create('', TEncoding.UTF8);
Boundary:= '--------------------' + LeftStr(GenerateGuid(), 20);
HTTP.Request.ContentType := 'multipart/form-data;boundary=' + Boundary + CrLf;
SendStream.WriteString('--' + Boundary + CrLf
+ 'Content-Disposition: form-data;name="xml_file";filename="file.xml"' + CrLf
+ 'Content-Type:application/xml' + CrLf + CrLf);
SendStream.CopyFrom(InboxStream, InboxStream.Size);
SendStream.WriteString(CrLf+ '--' + Boundary + '--');
ServerAnswer:= HTTP.Post(DestinationURL, SendStream);
Result:= True;
SendStream.Free;
HTTP.Free;
Except on E:EIdHTTPProtocolException do begin
ErrorLog(e, 'SendStreamToUTM', true);
Log('Неудачная загрузка данных на сервер, статус возврата: ' + HTTP.ResponseCode.ToString() );
Log('Ответ сервера: ' + HTTP.ResponseText);
Log(e.Message);
Log(e.ErrorMessage);
HTTP.Free;
Result:= False;
end;
end;
end;
function GetInboxFileList(): TList<TUTMstring>;
var InboxStream: TMemoryStream;
begin
InboxStream:= TMemoryStream.Create;
LoadStreamFromUTM(GetUTMaddress + constInboxList, InboxStream);
Result:= TList<TUTMstring>.Create;
ParseInboxList(InboxStream, Result);
end;
function GetOutboxFileList(): TList<TUTMstring>;
var OutboxStream: TMemoryStream;
begin
OutboxStream:= TMemoryStream.Create;
LoadStreamFromUTM(GetUTMaddress + constOutboxList, OutboxStream);
Result:= TList<TUTMstring>.Create;
ParseInboxList(OutboxStream, Result);
end;
function DeleteUTMobject(Url: string): Boolean;
var
HTTP: TIdHTTP;
begin
if StrToBool(xmlCfg.GetValue('DontDeleteUTM', False)) = True then begin
Log('Удаление объектов из УТМ запрещено в настройках!');
Exit;
end;
try
HTTP:= TIdHTTP.Create(nil);
Log('Удаление: ' + Url);
HTTP.Delete(Url);
if HTTP.ResponseCode = 200 then
Result:= True
else
Result:= False;
HTTP.Free;
Except on E:Exception do begin
ErrorLog(e, 'DeleteUTMobject' , False);
Log('Ошибка при попытке удаления: ' + HTTP.ResponseCode.ToString() );
Log('Ответ сервера: ' + HTTP.ResponseText);
HTTP.Free;
Result:= False;
end;
end;
end;
function DeleteUTMObjectByReplyID(ReplyID: string): Boolean;
var
UTMstr: TUTMstring;
InboxList: TList<TUTMstring>;
OutboxList: TList<TUTMstring>;
begin
try
if ReplyID.Length = 0 then Exit;
InboxList:= GetInboxFileList();
// OutboxList:= GetOutboxFileList();
for UTMstr in InboxList do begin
if UTMstr.ReplyID = ReplyID then
DeleteUTMobject(UTMstr.Url);
end;
// for UTMstr in OutboxList do begin
// if UTMstr.ReplyID = ReplyID then
// DeleteUTMobject(UTMstr.Url);
// end;
finally
InboxList.Free;
//OutboxList.Free;
end;
end;
end.
|
unit ssl_init;
interface
procedure SSL_InitLib;
implementation
uses
ssl_ec, ssl_util, ssl_types, ssl_lib, ssl_evp, ssl_const, ssl_rsa, ssl_dsa, ssl_x509, ssl_bio, ssl_pem, ssl_asn,
ssl_aes, ssl_bf, ssl_bn, ssl_buffer, ssl_cast, ssl_cmac, ssl_engine, ssl_rand, ssl_camellia, ssl_comp, ssl_des,
ssl_dh, ssl_err, ssl_objects, ssl_sk, ssl_pkcs12, ssl_pkcs7, ssl_cms, ssl_ecdh, ssl_ecdsa, ssl_hmac, ssl_idea,
ssl_lhash, ssl_md4, ssl_md5, ssl_ocsp, ssl_mdc2, ssl_rc2, ssl_rc4, ssl_rc5, ssl_ripemd, ssl_sha;
procedure SSL_InitLib;
begin
ssl_util.SSL_InitUtil;
ssl_err.SSL_InitERR;
ssl_objects.SSL_InitOBJ;
ssl_bio.SSL_InitBIO;
ssl_ec.SSL_InitEC;
ssl_evp.SSL_InitEVP;
ssl_rsa.SSL_InitRSA;
ssl_dsa.SSL_InitDSA;
ssl_x509.SSL_InitX509;
ssl_pem.SSL_InitPEM;
ssl_asn.SSL_InitASN1;
ssl_aes.SSL_InitAES;
ssl_bf.SSL_InitBF;
ssl_bn.SSL_InitBN;
ssl_buffer.SSL_InitBuffer;
ssl_cast.SLL_InitCAST;
ssl_cmac.SSL_InitCMAC;
ssl_engine.SSL_InitENGINE;
ssl_rand.SSL_InitRAND;
ssl_camellia.SSL_InitCAMELLIA;
ssl_comp.SSL_InitCOMP;
ssl_des.SSL_InitDES;
ssl_dh.SSL_InitDH;
ssl_sk.SSL_initSk;
ssl_pkcs12.SSL_InitPKCS12;
ssl_pkcs7.SSL_InitPKCS7;
ssl_cms.SSL_InitCMS;
ssl_ecdh.SSL_InitSSLDH;
ssl_ecdsa.SSL_InitECDSA;
ssl_hmac.SSL_InitHMAC;
ssl_idea.SSL_InitIDEA;
ssl_lhash.SSL_InitLHASH;
ssl_md4.SSL_InitMD4;
ssl_md5.SSL_InitMD5;
ssl_ocsp.SSL_InitOCSP;
ssl_mdc2.ssl_initmdc2;
ssl_rc2.SSL_Initrc2;
ssl_rc4.SSL_Initrc4;
ssl_rc5.SSL_Initrc5;
ssl_ripemd.SSL_Initripemd;
ssl_sha.ssl_Initsha;
end;
end.
|
// ##################################
// ###### IT PAT 2017 #######
// ###### PHASE 3 #######
// ###### Tiaan van der Riel #######
// ##################################
unit frmLeaderboards_u;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Grids, DBGrids, StdCtrls, Mask, DBCtrls, ComCtrls,
pngimage;
type
TfrmLeaderboards = class(TForm)
pnlLeaderboardsHeading: TPanel;
pnlLeaderboardsLeft: TPanel;
pnlLeaderboardsRight: TPanel;
lblYouAreCurrRanked: TLabel;
lblDispTotalCompetators: TLabel;
pnlDisplayRank: TPanel;
btnLeaderboardsHelp: TButton;
edtSearchUSername: TLabeledEdit;
btnBack: TButton;
dbnAccounts: TDBNavigator;
lblIDInfo: TLabel;
DBEdit1: TDBEdit;
lblUsernameInfo: TLabel;
DBEdit2: TDBEdit;
Label3: TLabel;
DBEdit3: TDBEdit;
lblSurnameInfo: TLabel;
DBEdit4: TDBEdit;
Label5: TLabel;
DBEdit5: TDBEdit;
lblMatchesWInInfo: TLabel;
DBEdit6: TDBEdit;
lblMacthesLostInfo: TLabel;
DBEdit7: TDBEdit;
lblTotalRoundsInfo: TLabel;
DBEdit8: TDBEdit;
lblRoundsWonInfo: TLabel;
DBEdit9: TDBEdit;
lblRoundsLostInfo: TLabel;
DBEdit10: TDBEdit;
dbgAccounts: TDBGrid;
lblUsername: TLabel;
btnHighestWdivM: TButton;
btnUserWdivM: TButton;
lblUserMostRoundsWon: TLabel;
Panel1: TPanel;
redTop10: TRichEdit;
Label11: TLabel;
btnKD: TButton;
lblKillsInfo: TLabel;
DBEdit11: TDBEdit;
lblDeathsInfo: TLabel;
DBEdit12: TDBEdit;
imgLeaderboardLogo: TImage;
procedure FormShow(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnLeaderboardsHelpClick(Sender: TObject);
procedure edtSearchUSernameChange(Sender: TObject);
procedure btnHighestWdivMClick(Sender: TObject);
procedure btnUserWdivMClick(Sender: TObject);
procedure btnKDClick(Sender: TObject);
// procedure btnSortaLeaderboardClick(Sender: TObject);
private
{ Private declarations }
iTotalNumAccounts: integer;
// Custom procedures
procedure GetTotalNumAccounts;
procedure GetMostRoundsWonPlayer;
procedure DetermineUserRank;
procedure ShowTop10;
public
{ Public declarations }
end;
var
frmLeaderboards: TfrmLeaderboards;
implementation
Uses
frmUserHomePage_u, dmAccounts_u;
{$R *.dfm}
/// ================================= Exit Button =============================
procedure TfrmLeaderboards.btnBackClick(Sender: TObject);
begin
frmLeaderboards.Close;
end;
/// ===================== Highest ration W per M played =======================
procedure TfrmLeaderboards.btnHighestWdivMClick(Sender: TObject);
{ This procedure calculates the player with the highest ratio of matches won
to matches played }
var
iMatchesPlayed: integer;
iMatchesWon: integer;
rMaxWonDivPlayed: real;
rCurrWonDivPlayed: real;
sMaxUsername: string;
begin
// enter data for first user - initialise
dmAccounts.tblAccounts.First;
dmAccounts.tblAccounts.DisableControls;
iMatchesPlayed := dmAccounts.tblAccounts['Total Matches Played'];
iMatchesWon := dmAccounts.tblAccounts['Matches Won'];
rMaxWonDivPlayed := iMatchesWon / iMatchesPlayed;
sMaxUsername := dmAccounts.tblAccounts['Username'];
// search through the database
while not dmAccounts.tblAccounts.Eof do
Begin
// Get data from current player
iMatchesPlayed := dmAccounts.tblAccounts['Total Matches Played'];
iMatchesWon := dmAccounts.tblAccounts['Matches Won'];
// 0 divided by 0 will give back an error
if (iMatchesPlayed = 0) AND (iMatchesWon = 0) then
begin
dmAccounts.tblAccounts.Next;
end
else
Begin
rCurrWonDivPlayed := iMatchesWon / iMatchesPlayed;
/// If two players both have the highest ratio
if rCurrWonDivPlayed = rMaxWonDivPlayed then
Begin
sMaxUsername := sMaxUsername + ' and ' + dmAccounts.tblAccounts
['Username'];
End;
if rCurrWonDivPlayed > rMaxWonDivPlayed then
Begin
rMaxWonDivPlayed := rCurrWonDivPlayed;
sMaxUsername := dmAccounts.tblAccounts['Username'];
End; // rCurrPlayedDivWon > rMaxPlayedDivWon
dmAccounts.tblAccounts.Next;
End;
End; // while not dmAccounts.tblAccounts.Eof do
dmAccounts.tblAccounts.EnableControls;
dmAccounts.tblAccounts.First;
// Output
ShowMessage(sMaxUsername +
' has the highesr ratio of matches won to matches played at ' +
FloatToStrF(rMaxWonDivPlayed, ffGeneral, 3, 3));
end;
/// ======================== Highest KD =======================================
procedure TfrmLeaderboards.btnKDClick(Sender: TObject);
{ This procedure calculates the player with the highest ratio of kills to
deaths }
var
iKills: integer;
iDeaths: integer;
rMaxKD: real;
rCurrKD: real;
sMaxUsername: string;
begin
// enter data for first user - initialise
dmAccounts.tblAccounts.First;
dmAccounts.tblAccounts.DisableControls;
iKills := dmAccounts.tblAccounts['Kills'];
iDeaths := dmAccounts.tblAccounts['Deaths'];
rMaxKD := iKills / iDeaths;
sMaxUsername := dmAccounts.tblAccounts['Username'];
// search through the database
while not dmAccounts.tblAccounts.Eof do
Begin
// Get data from current player
iKills := dmAccounts.tblAccounts['Kills'];
iDeaths := dmAccounts.tblAccounts['Deaths'];
// 0 divided by 0 will give back an error
if (iKills = 0) AND (iDeaths = 0) then
begin
dmAccounts.tblAccounts.Next;
end
else
Begin
rCurrKD := iKills / iDeaths;
/// If two players both have the highest ratio
if rCurrKD = rMaxKD then
Begin
sMaxUsername := sMaxUsername + ' and ' + dmAccounts.tblAccounts
['Username'];
End;
if rCurrKD > rMaxKD then
Begin
rMaxKD := rCurrKD;
sMaxUsername := dmAccounts.tblAccounts['Username'];
End; // rCurrPlayedDivWon > rMaxPlayedDivWon
dmAccounts.tblAccounts.Next;
End;
End; // while not dmAccounts.tblAccounts.Eof do
dmAccounts.tblAccounts.EnableControls;
dmAccounts.tblAccounts.First;
// Output
ShowMessage(sMaxUsername + ' has the highest K/D at ' + FloatToStrF
(rMaxKD, ffGeneral, 3, 3));
end;
/// ================================= Help Button =============================
procedure TfrmLeaderboards.btnLeaderboardsHelpClick(Sender: TObject);
var
tHelp: TextFile;
sLine: string;
sMessage: string;
begin
sMessage := '========================================';
AssignFile(tHelp, 'Help_Leaderboards.txt');
try { Code that checks to see if the file about the sponsors can be opened
- displays error if not }
reset(tHelp);
Except
ShowMessage('ERROR: The help file could not be opened.');
Exit;
end;
while NOT Eof(tHelp) do
begin
Readln(tHelp, sLine);
sMessage := sMessage + #13 + sLine;
end;
sMessage := sMessage + #13 + '========================================';
CloseFile(tHelp);
ShowMessage(sMessage);
end;
/// ==================== Calculate user Win to Match ratio ====================
procedure TfrmLeaderboards.btnUserWdivMClick(Sender: TObject);
{ This procedure calculates the user`s own ratio of matches won to matches
played }
var
rUserWdivM: real;
begin
dmAccounts.tblAccounts.First;
while not dmAccounts.tblAccounts.Eof do
Begin
if frmUserHomePage.sLoggedInUser = dmAccounts.tblAccounts['Username'] then
Begin
if dmAccounts.tblAccounts['Total Matches Played'] = 0 then
// dividing by 0 gives an error
Begin
ShowMessage(frmUserHomePage.sLoggedInUser +
' your ratio of matches won to matches played is 0.00');
End
else
Begin
rUserWdivM := dmAccounts.tblAccounts['Matches Won']
/ dmAccounts.tblAccounts['Total Matches Played'];
ShowMessage(frmUserHomePage.sLoggedInUser +
' your ratio of matches won to matches played is ' + FloatToStrF
(rUserWdivM, ffGeneral, 3, 3));
Exit;
End;
End;
dmAccounts.tblAccounts.Next;
End;
dmAccounts.tblAccounts.First;
end;
/// =============================== Username Search ===========================
procedure TfrmLeaderboards.edtSearchUSernameChange(Sender: TObject);
{ This porcedure is used to search, and filter the table of accounts, to
display the smilar usernames, as the user types a username into the edit field }
begin
if (edtSearchUSername.Text <> '') then
Begin
dmAccounts.tblAccounts.Filter := 'Username LIKE ''' +
(edtSearchUSername.Text) + '%'' ';
dmAccounts.tblAccounts.Filtered := True;
End
else
begin
dmAccounts.tblAccounts.Filtered := False;
end;
end;
/// ================================== Form Close =============================
procedure TfrmLeaderboards.FormClose(Sender: TObject; var Action: TCloseAction);
begin
frmUserHomePage.Show;
end;
/// ================================== Form Show ==============================
procedure TfrmLeaderboards.FormShow(Sender: TObject);
begin
lblUsername.Caption := frmUserHomePage.sLoggedInUser;
lblUsername.Width := 150;
dmAccounts.tblAccounts.Sort := '[Matches Won] DESC';
dmAccounts.tblAccounts.First;
// Procedure to get the total number of accounts
GetTotalNumAccounts;
lblDispTotalCompetators.Caption := 'Out of ' + IntToStr(iTotalNumAccounts)
+ ' competators';
// Procedure to get player who won most rounds
GetMostRoundsWonPlayer;
dmAccounts.tblAccounts.First;
// Procedure to show user`s rank
DetermineUserRank;
// Procedure to show top 10 players
ShowTop10;
dmAccounts.tblAccounts.First;
// dmAccounts.tblAccounts.EnableControls;
end;
/// =========================== Show user`s rank ==============================
procedure TfrmLeaderboards.DetermineUserRank;
{ This procedure calculates the user`s rank, based upon matches won, by
calculating the number of users who have won more matches than him/her }
var
iRank: integer;
begin
dmAccounts.tblAccounts.First;
iRank := 1;
while not dmAccounts.tblAccounts.Eof do
Begin
if frmUserHomePage.sLoggedInUser = dmAccounts.tblAccounts['Username'] then
Begin
pnlDisplayRank.Caption := IntToStr(iRank);
Exit;
End;
iRank := iRank + 1;
dmAccounts.tblAccounts.Next;
End;
end;
/// =========================== Procedure get total Accounts ==================
procedure TfrmLeaderboards.GetTotalNumAccounts;
begin
dmAccounts.tblAccounts.First;
iTotalNumAccounts := 0;
while not dmAccounts.tblAccounts.Eof do
Begin
iTotalNumAccounts := iTotalNumAccounts + 1;
dmAccounts.tblAccounts.Next;
End;
dmAccounts.tblAccounts.First;
end;
/// =============== Procedure to get player who won most rounds ===============
procedure TfrmLeaderboards.GetMostRoundsWonPlayer;
{ This procedure alternatively determines the player who has won the most rounds,
since this is not nesseceraly the same as the user who has won the most matches }
var
iMaxRoundsWon: integer;
iCurrRoundsWon: integer;
sMaxUsername: string;
begin
// enter data for first user - initialise
dmAccounts.tblAccounts.First;
iMaxRoundsWon := dmAccounts.tblAccounts['Rounds Won'];
sMaxUsername := dmAccounts.tblAccounts['Username'];
while not dmAccounts.tblAccounts.Eof do
Begin
// Get data from current player
iCurrRoundsWon := dmAccounts.tblAccounts['Rounds Won'];
if iCurrRoundsWon = iMaxRoundsWon then
Begin
sMaxUsername := sMaxUsername + ' and ' + dmAccounts.tblAccounts
['Username'];
End;
if iCurrRoundsWon > iMaxRoundsWon then
Begin
iMaxRoundsWon := iCurrRoundsWon;
sMaxUsername := dmAccounts.tblAccounts['Username'];
End; // iCurrRoundsWon > iMaxRoundsWon
dmAccounts.tblAccounts.Next;
End; // while not dmAccounts.tblAccounts.Eof do
lblUserMostRoundsWon.Caption := sMaxUsername +
' has won the most rounds with ' + IntToStr(iMaxRoundsWon) + ' rounds won.';
lblUserMostRoundsWon.Width := 203;
end;
/// ========================== Procedure to show top 10 ======================
procedure TfrmLeaderboards.ShowTop10;
{ This procedure displayes the top 10 best contetstants, based uppon matches
won, by reading the first 10 usernames from the table, after it has been sorted
from the best to the worst player, and then outputs these names to a rich edit
- If the logged in user`s name appears on the list it will be displayed in green }
var
sUserToAdd: string;
iIndex: integer;
begin
redTop10.Lines.Clear;
redTop10.Lines.Add('========================');
redTop10.SelAttributes.Color := clBlue;
redTop10.Lines.Add('Top 10 Users by Matches Played:');
redTop10.Lines.Add('========================');
dmAccounts.tblAccounts.First;
while not dmAccounts.tblAccounts.Eof do
Begin
for iIndex := 1 to 10 do
Begin
sUserToAdd := dmAccounts.tblAccounts['Username'];
/// If the user is on the list
if sUserToAdd = frmUserHomePage.sLoggedInUser then
begin
redTop10.SelAttributes.Color := clGreen;
redTop10.Lines.Add(IntToStr(iIndex) + '. ' + sUserToAdd + ' - YOU');
dmAccounts.tblAccounts.Next;
end
else
Begin
redTop10.Lines.Add(IntToStr(iIndex) + '. ' + sUserToAdd);
dmAccounts.tblAccounts.Next;
End;
End;
redTop10.Lines.Add('========================');
Exit;
End;
end;
end.
|
(*
* Copyright (c) 2011, Ciobanu Alexandru
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
unit Tests.Internal.Dynamic;
interface
{$IF CompilerVersion > 21}
uses SysUtils,
Rtti,
Tests.Internal.Basics,
TestFramework,
Generics.Collections,
Collections.Dynamic,
Collections.Base,
Collections.Lists;
type
TTestMember = class(TTestCaseEx)
published
procedure Test_Name_TView;
procedure Test_Name_TValue;
procedure Test_Name;
end;
TTestDynamic = class(TTestCaseEx)
published
procedure Test_Select_Exceptions;
procedure Test_Select_Class_TView;
procedure Test_Select_Record_TView;
procedure Test_Select_Class_ByField_TValue;
procedure Test_Select_Class_ByProp_TValue;
procedure Test_Select_Record_ByField_TValue;
procedure Test_Select_Class_ByField;
procedure Test_Select_Class_ByProp;
procedure Test_Select_Record_ByField;
end;
type
TCompositeObject = class
FInteger: Integer;
FString: string;
property _Integer: Integer read FInteger;
property _String: string read FString;
constructor Create(const AInteger: Integer; const AString: string);
end;
type
TCompositeRecord = class
FInteger: Integer;
FString: string;
constructor Create(const AInteger: Integer; const AString: string);
end;
implementation
{ TCompositeObject }
constructor TCompositeObject.Create(const AInteger: Integer; const AString: string);
begin
FInteger := AInteger;
FString := AString;
end;
{ TCompositeObject }
constructor TCompositeRecord.Create(const AInteger: Integer; const AString: string);
begin
FInteger := AInteger;
FString := AString;
end;
{ TTestDynamic }
procedure TTestDynamic.Test_Select_Class_ByField;
var
LList: TObjectList<TCompositeObject>;
LSelectedInts: TList<Integer>;
LSelectedStrs: TList<string>;
begin
LList := TObjectList<TCompositeObject>.Create;
LList.OwnsObjects := True;
{ Populate }
LList.Add(TCompositeObject.Create(111, '111'));
LList.Add(TCompositeObject.Create(222, '222'));
LList.Add(TCompositeObject.Create(888, '888'));
LList.Add(TCompositeObject.Create(444, '444'));
LList.Add(TCompositeObject.Create(999, '999'));
{ Select only integers }
LSelectedInts := TList<Integer>.Create();
LSelectedInts.AddAll(LList.Op.Select<Integer>('FInteger'));
CheckEquals(5, LSelectedInts.Count);
CheckEquals(111, LSelectedInts[0]);
CheckEquals(222, LSelectedInts[1]);
CheckEquals(888, LSelectedInts[2]);
CheckEquals(444, LSelectedInts[3]);
CheckEquals(999, LSelectedInts[4]);
LSelectedStrs := TList<string>.Create();
LSelectedStrs.AddAll(LList.Op.Select<string>('FString'));
CheckEquals(5, LSelectedStrs.Count);
CheckEquals('111', LSelectedStrs[0]);
CheckEquals('222', LSelectedStrs[1]);
CheckEquals('888', LSelectedStrs[2]);
CheckEquals('444', LSelectedStrs[3]);
CheckEquals('999', LSelectedStrs[4]);
LSelectedStrs.Free;
LSelectedInts.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Class_ByField_TValue;
var
LList: TObjectList<TCompositeObject>;
LSelected: TList<TValue>;
begin
LList := TObjectList<TCompositeObject>.Create;
LList.OwnsObjects := True;
{ Populate }
LList.Add(TCompositeObject.Create(111, '111'));
LList.Add(TCompositeObject.Create(222, '222'));
LList.Add(TCompositeObject.Create(888, '888'));
LList.Add(TCompositeObject.Create(444, '444'));
LList.Add(TCompositeObject.Create(999, '999'));
{ Select only integers }
LSelected := TList<TValue>.Create();
LSelected.AddAll(LList.Op.Select('FInteger'));
CheckEquals(5, LSelected.Count);
CheckEquals(111, LSelected[0].AsInteger);
CheckEquals(222, LSelected[1].AsInteger);
CheckEquals(888, LSelected[2].AsInteger);
CheckEquals(444, LSelected[3].AsInteger);
CheckEquals(999, LSelected[4].AsInteger);
LSelected.Clear();
LSelected.AddAll(LList.Op.Select('FString'));
CheckEquals(5, LSelected.Count);
CheckEquals('111', LSelected[0].AsString);
CheckEquals('222', LSelected[1].AsString);
CheckEquals('888', LSelected[2].AsString);
CheckEquals('444', LSelected[3].AsString);
CheckEquals('999', LSelected[4].AsString);
LSelected.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Class_TView;
var
LList: TObjectList<TCompositeObject>;
LSelected: TList<TView>;
begin
LList := TObjectList<TCompositeObject>.Create;
LList.OwnsObjects := True;
{ Populate }
LList.Add(TCompositeObject.Create(111, '111'));
LList.Add(TCompositeObject.Create(222, '222'));
LList.Add(TCompositeObject.Create(888, '888'));
LList.Add(TCompositeObject.Create(444, '444'));
LList.Add(TCompositeObject.Create(999, '999'));
{ Select only integers }
LSelected := TList<TView>.Create();
LSelected.AddAll(LList.Op.Select(['FInteger', '_String']));
CheckEquals(5, LSelected.Count);
CheckEquals(111, LSelected[0].FInteger);
CheckEquals(222, LSelected[1].FInteger);
CheckEquals(888, LSelected[2].FInteger);
CheckEquals(444, LSelected[3].FInteger);
CheckEquals(999, LSelected[4].FInteger);
CheckEquals('111', LSelected[0]._String);
CheckEquals('222', LSelected[1]._String);
CheckEquals('888', LSelected[2]._String);
CheckEquals('444', LSelected[3]._String);
CheckEquals('999', LSelected[4]._String);
LSelected.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Class_ByProp;
var
LList: TObjectList<TCompositeObject>;
LSelectedInts: TList<Integer>;
LSelectedStrs: TList<string>;
begin
LList := TObjectList<TCompositeObject>.Create;
LList.OwnsObjects := True;
{ Populate }
LList.Add(TCompositeObject.Create(111, '111'));
LList.Add(TCompositeObject.Create(222, '222'));
LList.Add(TCompositeObject.Create(888, '888'));
LList.Add(TCompositeObject.Create(444, '444'));
LList.Add(TCompositeObject.Create(999, '999'));
{ Select only integers }
LSelectedInts := TList<Integer>.Create();
LSelectedInts.AddAll(LList.Op.Select<Integer>('_Integer'));
CheckEquals(5, LSelectedInts.Count);
CheckEquals(111, LSelectedInts[0]);
CheckEquals(222, LSelectedInts[1]);
CheckEquals(888, LSelectedInts[2]);
CheckEquals(444, LSelectedInts[3]);
CheckEquals(999, LSelectedInts[4]);
LSelectedStrs := TList<string>.Create();
LSelectedStrs.AddAll(LList.Op.Select<string>('_String'));
CheckEquals(5, LSelectedStrs.Count);
CheckEquals('111', LSelectedStrs[0]);
CheckEquals('222', LSelectedStrs[1]);
CheckEquals('888', LSelectedStrs[2]);
CheckEquals('444', LSelectedStrs[3]);
CheckEquals('999', LSelectedStrs[4]);
LSelectedStrs.Free;
LSelectedInts.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Class_ByProp_TValue;
var
LList: TObjectList<TCompositeObject>;
LSelected: TList<TValue>;
begin
LList := TObjectList<TCompositeObject>.Create;
LList.OwnsObjects := True;
{ Populate }
LList.Add(TCompositeObject.Create(111, '111'));
LList.Add(TCompositeObject.Create(222, '222'));
LList.Add(TCompositeObject.Create(888, '888'));
LList.Add(TCompositeObject.Create(444, '444'));
LList.Add(TCompositeObject.Create(999, '999'));
{ Select only integers }
LSelected := TList<TValue>.Create();
LSelected.AddAll(LList.Op.Select('_Integer'));
CheckEquals(5, LSelected.Count);
CheckEquals(111, LSelected[0].AsInteger);
CheckEquals(222, LSelected[1].AsInteger);
CheckEquals(888, LSelected[2].AsInteger);
CheckEquals(444, LSelected[3].AsInteger);
CheckEquals(999, LSelected[4].AsInteger);
LSelected.Clear();
LSelected.AddAll(LList.Op.Select('_String'));
CheckEquals(5, LSelected.Count);
CheckEquals('111', LSelected[0].AsString);
CheckEquals('222', LSelected[1].AsString);
CheckEquals('888', LSelected[2].AsString);
CheckEquals('444', LSelected[3].AsString);
CheckEquals('999', LSelected[4].AsString);
LSelected.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Exceptions;
var
LList: TList<Integer>;
LObjList: TObjectList<TCompositeObject>;
begin
LList := TList<Integer>.Create;
CheckException(ENotSupportedException,
procedure() begin
LList.Op.Select('Loloi');
end,
'ENotSupportedException not thrown in Select(integer).'
);
CheckException(ENotSupportedException,
procedure() begin
LList.Op.Select<integer>('Loloi');
end,
'ENotSupportedException not thrown in Select<integer>(integer).'
);
LList.Free;
LObjList := TObjectList<TCompositeObject>.Create;
CheckException(ENotSupportedException,
procedure() begin
LObjList.Op.Select('FCucu');
end,
'ENotSupportedException not thrown in Select(field/prop not there).'
);
CheckException(ENotSupportedException,
procedure() begin
LObjList.Op.Select<integer>('FCucu');
end,
'ENotSupportedException not thrown in Select<integer>(field/prop not there).'
);
LObjList.Free;
end;
procedure TTestDynamic.Test_Select_Record_ByField;
var
LList: TList<TCompositeRecord>;
LSelectedInts: TList<Integer>;
LSelectedStrs: TList<string>;
begin
LList := TObjectList<TCompositeRecord>.Create;
{ Populate }
LList.Add(TCompositeRecord.Create(111, '111'));
LList.Add(TCompositeRecord.Create(222, '222'));
LList.Add(TCompositeRecord.Create(888, '888'));
LList.Add(TCompositeRecord.Create(444, '444'));
LList.Add(TCompositeRecord.Create(999, '999'));
{ Select only integers }
LSelectedInts := TList<Integer>.Create();
LSelectedInts.AddAll(LList.Op.Select<Integer>('FInteger'));
CheckEquals(5, LSelectedInts.Count);
CheckEquals(111, LSelectedInts[0]);
CheckEquals(222, LSelectedInts[1]);
CheckEquals(888, LSelectedInts[2]);
CheckEquals(444, LSelectedInts[3]);
CheckEquals(999, LSelectedInts[4]);
LSelectedStrs := TList<string>.Create();
LSelectedStrs.AddAll(LList.Op.Select<string>('FString'));
CheckEquals(5, LSelectedStrs.Count);
CheckEquals('111', LSelectedStrs[0]);
CheckEquals('222', LSelectedStrs[1]);
CheckEquals('888', LSelectedStrs[2]);
CheckEquals('444', LSelectedStrs[3]);
CheckEquals('999', LSelectedStrs[4]);
LSelectedStrs.Free;
LSelectedInts.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Record_ByField_TValue;
var
LList: TList<TCompositeRecord>;
LSelected: TList<TValue>;
begin
LList := TObjectList<TCompositeRecord>.Create;
{ Populate }
LList.Add(TCompositeRecord.Create(111, '111'));
LList.Add(TCompositeRecord.Create(222, '222'));
LList.Add(TCompositeRecord.Create(888, '888'));
LList.Add(TCompositeRecord.Create(444, '444'));
LList.Add(TCompositeRecord.Create(999, '999'));
{ Select only integers }
LSelected := TList<TValue>.Create();
LSelected.AddAll(LList.Op.Select('FInteger'));
CheckEquals(5, LSelected.Count);
CheckEquals(111, LSelected[0].AsInteger);
CheckEquals(222, LSelected[1].AsInteger);
CheckEquals(888, LSelected[2].AsInteger);
CheckEquals(444, LSelected[3].AsInteger);
CheckEquals(999, LSelected[4].AsInteger);
LSelected.Clear();
LSelected.AddAll(LList.Op.Select('FString'));
CheckEquals(5, LSelected.Count);
CheckEquals('111', LSelected[0].AsString);
CheckEquals('222', LSelected[1].AsString);
CheckEquals('888', LSelected[2].AsString);
CheckEquals('444', LSelected[3].AsString);
CheckEquals('999', LSelected[4].AsString);
LSelected.Free;
LList.Free;
end;
procedure TTestDynamic.Test_Select_Record_TView;
var
LList: TList<TCompositeRecord>;
LSelected: TList<TView>;
begin
LList := TList<TCompositeRecord>.Create;
{ Populate }
LList.Add(TCompositeRecord.Create(111, '111'));
LList.Add(TCompositeRecord.Create(222, '222'));
LList.Add(TCompositeRecord.Create(888, '888'));
LList.Add(TCompositeRecord.Create(444, '444'));
LList.Add(TCompositeRecord.Create(999, '999'));
{ Select only integers }
LSelected := TList<TView>.Create();
LSelected.AddAll(LList.Op.Select(['FInteger', 'FString']));
CheckEquals(5, LSelected.Count);
CheckEquals(111, LSelected[0].FInteger);
CheckEquals(222, LSelected[1].FInteger);
CheckEquals(888, LSelected[2].FInteger);
CheckEquals(444, LSelected[3].FInteger);
CheckEquals(999, LSelected[4].FInteger);
CheckEquals('111', LSelected[0].FString);
CheckEquals('222', LSelected[1].FString);
CheckEquals('888', LSelected[2].FString);
CheckEquals('444', LSelected[3].FString);
CheckEquals('999', LSelected[4].FString);
LSelected.Free;
LList.Free;
end;
{ TTestMember }
procedure TTestMember.Test_Name;
var
LObj: TCompositeObject;
LRec: TCompositeRecord;
begin
Check(not Assigned(
Member.Name<Integer>('haha')
));
Check(not Assigned(
Member.Name<TCompositeRecord>('Habla')
));
Check(not Assigned(
Member.Name<TCompositeObject>('Habla')
));
LObj := TCompositeObject.Create(123, '123');
LRec := TCompositeRecord.Create(123, '123');
CheckEquals(123, Member.Name<TCompositeObject, Integer>('FInteger')(LObj));
CheckEquals('123', Member.Name<TCompositeObject, string>('FString')(LObj));
CheckEquals(123, Member.Name<TCompositeObject, Integer>('_Integer')(LObj));
CheckEquals('123', Member.Name<TCompositeObject, string>('_String')(LObj));
CheckEquals(123, Member.Name<TCompositeRecord, Integer>('FInteger')(LRec));
CheckEquals('123', Member.Name<TCompositeRecord, string>('FString')(LRec));
LObj.Free;
end;
procedure TTestMember.Test_Name_TValue;
var
LObj: TCompositeObject;
LRec: TCompositeRecord;
begin
Check(not Assigned(
Member.Name<Integer>('haha')
));
Check(not Assigned(
Member.Name<TCompositeRecord>('Habla')
));
Check(not Assigned(
Member.Name<TCompositeObject>('Habla')
));
LObj := TCompositeObject.Create(123, '123');
LRec := TCompositeRecord.Create(123, '123');
CheckEquals(123, Member.Name<TCompositeObject>('FInteger')(LObj).AsInteger);
CheckEquals('123', Member.Name<TCompositeObject>('FString')(LObj).AsString);
CheckEquals(123, Member.Name<TCompositeObject>('_Integer')(LObj).AsInteger);
CheckEquals('123', Member.Name<TCompositeObject>('_String')(LObj).AsString);
CheckEquals(123, Member.Name<TCompositeRecord>('FInteger')(LRec).AsInteger);
CheckEquals('123', Member.Name<TCompositeRecord>('FString')(LRec).AsString);
LObj.Free;
end;
procedure TTestMember.Test_Name_TView;
var
LObj: TCompositeObject;
LRec: TCompositeRecord;
LView: TView;
begin
Check(not Assigned(
Member.Name<Integer>(['haha', 'buhu'])
));
Check(not Assigned(
Member.Name<Integer>([])
));
Check(not Assigned(
Member.Name<Integer>([''])
));
Check(not Assigned(
Member.Name<TCompositeRecord>([])
));
Check(not Assigned(
Member.Name<TCompositeRecord>([''])
));
Check(not Assigned(
Member.Name<TCompositeRecord>(['FInteger', 'minus'])
));
Check(not Assigned(
Member.Name<TCompositeObject>([])
));
Check(not Assigned(
Member.Name<TCompositeObject>([''])
));
Check(not Assigned(
Member.Name<TCompositeObject>(['FInteger', 'FStringy'])
));
LObj := TCompositeObject.Create(123, '123');
LRec := TCompositeRecord.Create(123, '123');
LView := Member.Name<TCompositeObject>(['FInteger', 'FString'])(LObj);
CheckEquals(123, LView.FInteger);
CheckEquals('123', LView.FString);
LView := Member.Name<TCompositeObject>(['_Integer', '_String'])(LObj);
CheckEquals(123, LView._Integer);
CheckEquals('123', LView._String);
LView := Member.Name<TCompositeRecord>(['FInteger', 'FString'])(LRec);
CheckEquals(123, LView.FInteger);
CheckEquals('123', LView.FString);
LObj.Free;
end;
initialization
TestFramework.RegisterTests('Internal.Dynamic', [
TTestDynamic.Suite,
TTestMember.Suite
]);
{$ELSE}
implementation
{$IFEND}
end.
|
unit xxmCommonUtils;
interface
function RFC822DateGMT(dd: TDateTime): string;
function GetFileModifiedDateTime(FilePath:string):TDateTime;
implementation
uses Windows, SysUtils;
function RFC822DateGMT(dd: TDateTime): string;
const
Days:array [1..7] of string=
('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
Months:array [1..12] of string=
('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
// SignStr:array[boolean] of string=('-','+');
var
dg:TDateTime;
y,m,d,wd,th,tm,ts,tms:Word;
tz:TIME_ZONE_INFORMATION;
begin
GetTimeZoneInformation(tz);
dg:=dd+tz.Bias/1440;
DecodeDateFully(dg,y,m,d,wd);
DecodeTime(dg,th,tm,ts,tms);
FmtStr(Result, '%s, %d %s %d %.2d:%.2d:%.2d GMT',
[Days[wd],d,Months[m],y,th,tm,ts]);
end;
function GetFileModifiedDateTime(FilePath:string):TDateTime;
var
fh:THandle;
fd:TWin32FindData;
st:TSystemTime;
begin
if FilePath='' then Result:=0 else
begin
fh:=FindFirstFile(PChar(FilePath),fd);
if fh=INVALID_HANDLE_VALUE then Result:=0 else
begin
Windows.FindClose(fh);
FileTimeToSystemTime(fd.ftLastWriteTime,st);
Result:=SystemTimeToDateTime(st);
end;
end;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [FIN_LANCAMENTO_PAGAR]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit FinLancamentoPagarController;
interface
uses
Classes, Dialogs, SysUtils, DBClient, DB, Windows, Forms, Controller, Rtti,
Atributos, VO, Generics.Collections, FinLancamentoPagarVO, FinParcelaPagarVO,
FinLctoPagarNtFinanceiraVO;
type
TFinLancamentoPagarController = class(TController)
private
class var FDataSet: TClientDataSet;
public
class procedure Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean = False);
class function ConsultaLista(pFiltro: String): TObjectList<TFinLancamentoPagarVO>;
class function ConsultaObjeto(pFiltro: String): TFinLancamentoPagarVO;
class procedure Insere(pObjeto: TFinLancamentoPagarVO);
class function Altera(pObjeto: TFinLancamentoPagarVO): Boolean;
class function Exclui(pId: Integer): Boolean;
class function GetDataSet: TClientDataSet; override;
class procedure SetDataSet(pDataSet: TClientDataSet); override;
class procedure TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
end;
implementation
uses UDataModule, T2TiORM;
class procedure TFinLancamentoPagarController.Consulta(pFiltro: String; pPagina: String; pConsultaCompleta: Boolean);
var
Retorno: TObjectList<TFinLancamentoPagarVO>;
begin
try
Retorno := TT2TiORM.Consultar<TFinLancamentoPagarVO>(pFiltro, pPagina, pConsultaCompleta);
TratarRetorno<TFinLancamentoPagarVO>(Retorno);
finally
end;
end;
class function TFinLancamentoPagarController.ConsultaLista(pFiltro: String): TObjectList<TFinLancamentoPagarVO>;
begin
try
Result := TT2TiORM.Consultar<TFinLancamentoPagarVO>(pFiltro, '-1', True);
finally
end;
end;
class function TFinLancamentoPagarController.ConsultaObjeto(pFiltro: String): TFinLancamentoPagarVO;
begin
try
Result := TT2TiORM.ConsultarUmObjeto<TFinLancamentoPagarVO>(pFiltro, True);
Result.FornecedorNome := Result.FornecedorVO.Nome;
Result.DocumentoOrigemSigla := Result.DocumentoOrigemVO.SiglaDocumento;
finally
end;
end;
class procedure TFinLancamentoPagarController.Insere(pObjeto: TFinLancamentoPagarVO);
var
UltimoID:Integer;
ParcelaPagar: TFinParcelaPagarVO;
ParcelaPagarEnumerator: TEnumerator<TFinParcelaPagarVO>;
LancamentoNaturezaFinanceira: TFinLctoPagarNtFinanceiraVO;
LancamentoNaturezaFinanceiraEnumerator: TEnumerator<TFinLctoPagarNtFinanceiraVO>;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
// Parcela Pagar
ParcelaPagarEnumerator := pObjeto.ListaParcelaPagarVO.GetEnumerator;
try
with ParcelaPagarEnumerator do
begin
while MoveNext do
begin
ParcelaPagar := Current;
ParcelaPagar.IdFinLancamentoPagar := UltimoID;
TT2TiORM.Inserir(ParcelaPagar);
end;
end;
finally
ParcelaPagarEnumerator.Free;
end;
// Natureza Financeira
LancamentoNaturezaFinanceiraEnumerator := pObjeto.ListaLancPagarNatFinanceiraVO.GetEnumerator;
try
with LancamentoNaturezaFinanceiraEnumerator do
begin
while MoveNext do
begin
LancamentoNaturezaFinanceira := Current;
LancamentoNaturezaFinanceira.IdFinLancamentoPagar := UltimoID;
TT2TiORM.Inserir(LancamentoNaturezaFinanceira);
end;
end;
finally
LancamentoNaturezaFinanceiraEnumerator.Free;
end;
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TFinLancamentoPagarController.Altera(pObjeto: TFinLancamentoPagarVO): Boolean;
var
ParcelaPagarEnumerator: TEnumerator<TFinParcelaPagarVO>;
LancamentoNaturezaFinanceiraEnumerator: TEnumerator<TFinLctoPagarNtFinanceiraVO>;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
// Parcela Pagar
try
ParcelaPagarEnumerator := pObjeto.ListaParcelaPagarVO.GetEnumerator;
with ParcelaPagarEnumerator do
begin
while MoveNext do
begin
if Current.Id > 0 then
Result := TT2TiORM.Alterar(Current)
else
begin
Current.IdFinLancamentoPagar := pObjeto.Id;
Result := TT2TiORM.Inserir(Current) > 0;
end;
end;
end;
finally
FreeAndNil(ParcelaPagarEnumerator);
end;
// Natureza Financeira
try
LancamentoNaturezaFinanceiraEnumerator := pObjeto.ListaLancPagarNatFinanceiraVO.GetEnumerator;
with LancamentoNaturezaFinanceiraEnumerator do
begin
while MoveNext do
begin
if Current.Id > 0 then
Result := TT2TiORM.Alterar(Current)
else
begin
Current.IdFinLancamentoPagar := pObjeto.Id;
Result := TT2TiORM.Inserir(Current) > 0;
end;
end;
end;
finally
FreeAndNil(LancamentoNaturezaFinanceiraEnumerator);
end;
finally
end;
end;
class function TFinLancamentoPagarController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TFinLancamentoPagarVO;
begin
try
ObjetoLocal := TFinLancamentoPagarVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
TratarRetorno(Result);
finally
FreeAndNil(ObjetoLocal)
end;
end;
class function TFinLancamentoPagarController.GetDataSet: TClientDataSet;
begin
Result := FDataSet;
end;
class procedure TFinLancamentoPagarController.SetDataSet(pDataSet: TClientDataSet);
begin
FDataSet := pDataSet;
end;
class procedure TFinLancamentoPagarController.TratarListaRetorno(pListaObjetos: TObjectList<TVO>);
begin
try
TratarRetorno<TFinLancamentoPagarVO>(TObjectList<TFinLancamentoPagarVO>(pListaObjetos));
finally
FreeAndNil(pListaObjetos);
end;
end;
initialization
Classes.RegisterClass(TFinLancamentoPagarController);
finalization
Classes.UnRegisterClass(TFinLancamentoPagarController);
end.
|
program AVLtreework;
uses CRT,Graph;
type PTree = ^TTree;
TTree = record
info:byte;
balance: integer;
left,right: PTree;
end;
function max(v1,v2:integer):integer;
begin
if (v1>v2) then
max:=v1
else
max:=v2;
end;
function getint(ident:string):byte;
var s:byte;
begin
write('Введите ',ident,' : ');
readln(s);
getint:=s;
end;
procedure RotateSingleLL(var root:PTree);
Var LBranch:PTree;
begin
LBranch:=root^.left;
if (LBranch^.balance=-1) then
begin
LBranch^.balance:=0;
root^.balance:=0;
end
else
begin
LBranch^.balance:=1;
root^.balance:=-1;
end;
root^.left:=LBranch^.right;
Lbranch^.right:=root;
root:=LBRanch;
end;
procedure RotateSingleRR(var root:PTree);
var RBranch:PTree;
begin
RBranch:=root^.right;
if (RBranch^.balance=1) then
begin
RBranch^.balance:=0;
root^.balance:=0;
end
else
begin
RBranch^.balance:=-1;
root^.balance:=1;
end;
root^.right:=RBranch^.left;
RBranch^.left:=root;
root:=RBRanch;
end;
procedure RotateDoubleLR(var root:PTree);
Var LBranch,LRBranch:PTree;
begin
Lbranch:=root^.left;
LRbranch:=Lbranch^.right;
if (LRbranch^.balance = 1) then
lbranch^.balance:=-1
else
lbranch^.balance:=0;
if (LRBranch^.balance = -1) then
root^.balance:=1
else
root^.balance:=0;
lrbranch^.balance:=0;
root^.left:=LRbranch^.right;
Lbranch^.right:=LRbranch^.left;
LRbranch^.left:=Lbranch;
LRBranch^.right:=root;
root:=LRbranch;
end;
procedure RotateDoubleRL (var root:PTree);
Var Rbranch,RLbranch:PTree;
begin
Rbranch:=root^.right;
RLbranch:=RBranch^.left;
if (RLBranch^.balance = -1) then
rbranch^.balance:=1
else
rbranch^.balance:=0;
if (RLBranch^.balance=1) then
root^.balance:=-1
else
root^.balance:=0;
rlbranch^.balance:=0;
root^.right:=RLbranch^.left;
Rbranch^.left:=RLbranch^.right;
RLbranch^.right:=Rbranch;
RLbranch^.left:=root;
root:=RLbranch;
end;
procedure RebalanceTree(var root:PTree;var rebalance:boolean);
var branch:PTree;
begin
if (root^.balance=-1) then
begin
branch:=root^.left;
if (branch^.balance=-1) or (branch^.balance=0) then
begin
RotateSingleLL(root);
rebalance:=false;
end
else
if (branch^.balance=1) then
begin
RotateDoubleLR(root);
rebalance:=false;
end;
end
else
if (root^.balance=1) then
begin
branch:=root^.right;
if (branch^.balance=1) or (branch^.balance=0) then
begin
RotateSingleRR(root);
rebalance:=false;
end
else
if (branch^.balance=-1) then
begin
RotateDoubleRL(root);
rebalance:=false;
end;
end;
end;
Procedure HeavyLeft(var root:PTree;var rebalance:boolean);
begin
case root^.balance of
-1 : begin
RebalanceTree(root,rebalance);
end;
0 : begin
root^.balance:=-1;
rebalance:=true;
end;
1 : begin
root^.balance:=0;
rebalance:=false;
end;
end;
end;
Procedure HeavyRight(var root:PTree;var rebalance:boolean);
begin
case root^.balance of
-1 : begin
root^.balance:=0;
rebalance:=false;
end;
0 : begin
root^.balance:=1;
rebalance:=true;
end;
1: begin
RebalanceTree(root,rebalance);
end;
end;
end;
procedure addelem(var root:PTree;info:byte;var rebalance:boolean);
var elem:PTree;
rebalancethiselem:boolean;
begin
if (root=NIL) then
begin
new(elem);
elem^.left:=NIL;
elem^.right:=NIL;
elem^.info:=info;
elem^.balance:=0;
rebalance:=TRUE;
root:=elem;
end
else
begin
if (info<root^.info) then
begin
addelem(root^.left,info,RebalanceThisElem);
if (RebalanceThisElem) then
HeavyLeft(root,rebalance)
else
rebalance:=false;
end
else
begin
addelem(root^.right,info,rebalancethiselem);
if (rebalancethiselem) then
begin
HeavyRight(root,rebalance)
end
else
rebalance:=false;
end;
end;
end;
procedure addelem_wrapper(var root:PTree;info:byte);
var rebalance:boolean;
begin
rebalance:=false;
addelem(root,info,rebalance);
end;
procedure printLKP(root:PTree);
begin
if (root<>NIL) then
begin
printLKP(root^.left);
write(root^.info,' ');
printLKP(root^.right);
end;
end;
procedure printLKP_wrapper(root:PTree);
begin
clrscr;
if (root=NIL) then
writeln('Дерево пусто!')
else
PrintLKP(root);
writeln;
writeln('Нажмите любую клавишу для выхода в главное меню');
readkey;
end;
procedure printKLP(root:PTree);
begin
if (root<>NIL) then
begin
write(root^.info,' ');
printKLP(root^.left);
printKLP(root^.right);
end;
end;
procedure printKLP_wrapper(root:PTree);
begin
clrscr;
if (root=NIL) then
writeln('Дерево пусто!')
else
PrintKLP(root);
writeln;
writeln('Нажмите любую клавишу для выхода в главное меню');
readkey;
end;
procedure printLPK(root:PTree);
begin
if (root<>NIL) then
begin
printLPK(root^.left);
printLPK(root^.right);
write(root^.info,' ');
end;
end;
procedure printLPK_wrapper(root:PTree);
begin
clrscr;
if (root=NIL) then
writeln('Дерево пусто!')
else
PrintLPK(root);
writeln;
writeln('Нажмите любую клавишу для выхода в главное меню');
readkey;
end;
function countels(root:PTree):integer;
begin
if (root<>NIL) then
countels:=1+countels(root^.left)+countels(root^.right)
else
countels:=0;
end;
procedure countels_wrapper(root:PTree);
begin
writeln('Число вершин дерева : ',countels(root));
writeln('Нажмите любую клавишу');
writeln;
readkey;
end;
function countleafs(root:PTree):integer;
begin
if (root<>NIL) then
if (root^.left=NIL) and (root^.right=NIL) then
countleafs:=1
else
countleafs:=countleafs(root^.left)+countleafs(root^.right)
else
countleafs:=0;
end;
procedure countleafs_wrapper(root:PTree);
begin
writeln('Число листов дерева : ',countleafs(root));
writeln;
writeln('Нажмите любую клавишу');
readkey;
end;
function countdepth(root:PTree;level:integer):integer;
var dr,dl:integer;
begin
if (root=NIL) then
countdepth:=level-1
else
countdepth:=max(countdepth(root^.left,level+1),countdepth(root^.right,level+1));
end;
procedure countdepth_wrapper(root:PTree);
begin
if (root<>NIL) then
begin
writeln('Глубина дерева : ',countdepth(root,0));
writeln;
writeln('Нажмите любую клавишу');
end
else
writeln('Дерево пусто!');
readln;
end;
function getmostright(root:PTree):byte;
begin
if (root^.right=NIL) then
getmostright:=root^.info
else
getmostright:=getmostright(root^.right);
end;
procedure DelRebalanceTree(var root:PTree;var rebalance:boolean);
var branch:PTree;
begin
if (root^.balance=-1) then
begin
branch:=root^.left;
if (branch^.balance=-1) or (branch^.balance=0) then
begin
RotateSingleLL(root);
rebalance:=false;
end
else
if (branch^.balance=1) then
begin
RotateDoubleLR(root);
rebalance:=false;
end;
end
else
if (root^.balance=1) then
begin
branch:=root^.right;
if (branch^.balance=1) or (branch^.balance=0) then
begin
RotateSingleRR(root);
rebalance:=false;
end
else
if (branch^.balance=-1) then
begin
RotateDoubleRL(root);
rebalance:=false;
end;
end;
end;
Procedure LightLeft(var root:PTree;var rebalance:boolean);
begin
case root^.balance of
1 : begin
DelRebalanceTree(root,rebalance);
end;
0 : begin
root^.balance:=1;
rebalance:=false;
end;
-1 : begin
root^.balance:=0;
rebalance:=true;
end;
end;
end;
Procedure LightRight(var root:PTree;var rebalance:boolean);
begin
case root^.balance of
1 : begin
root^.balance:=0;
rebalance:=true;
end;
0 : begin
root^.balance:=-1;
rebalance:=false;
end;
-1: begin
DelRebalanceTree(root,rebalance);
end;
end;
end;
procedure delelem(var root:PTree;info:byte;var rebalance:boolean);
var temp:PTree;
RebalanceThisElem:boolean;
OldRebalance:boolean;
OldDepthL,OldDepthR:integer;
DepthL,DepthR:integer;
begin
if (root<>NIL) then
begin
if (info<root^.info) then
begin
delelem(root^.left,info,RebalanceThisElem);
if (RebalanceThisElem) then
LightLeft(root,rebalance)
else
rebalance:=false;
end
else
if (info>root^.info) then
begin
delelem(root^.right,info,RebalanceThisElem);
if (RebalanceThisElem) then
LightRight(root,rebalance)
else
rebalance:=false;
end
else
begin
if (root^.left=NIL) and (root^.right=NIL) then
begin
dispose(root);
root:=NIL;
rebalance:=TRUE;
end
else
if (root^.left=NIL) and (root^.right<>NIL) then
begin
temp:=root;
root:=root^.right;
dispose(temp);
rebalance:=TRUE;
end
else
if (root^.left<>NIL) and (root^.right=NIL) then
begin
temp:=root;
root:=root^.left;
dispose(temp);
rebalance:=TRUE;
end
else
begin
root^.info:=getmostright(root^.left);
olddepthl:=countdepth(root^.left,1);
olddepthr:=countdepth(root^.right,1);
delelem(root^.left,root^.info,RebalanceThisElem);
depthl:=countdepth(root^.left,1);
depthr:=countdepth(root^.right,1);
if (max(olddepthl,olddepthr)<>max(depthl,depthr)) or (abs(depthr-depthl)>1) then
LightLeft(root,rebalance)
else
begin
rebalance:=false;
root^.balance:=depthr-depthl;
end;
end;
end;
end
else
begin
rebalance:=false;
end;
end;
procedure delelem_wrapper(var root:PTree;info:byte);
var rb:boolean;
begin
rb:=false;
delelem(root,info,rb);
end;
procedure printlevel(root:Ptree;level,curlevel:integer);
begin
if (root<>NIL) then
begin
if (curlevel=level) then
write(root^.info,' ')
else
begin
printlevel(root^.left,level,curlevel+1);
printlevel(root^.right,level,curlevel+1);
end;
end;
end;
procedure printlevel_wrapper(root:PTree;level:integer);
begin
clrscr;
writeln('Все вершины на уровне ',level,' : ');
printlevel(root,level,0);
writeln;
writeln('Нажмите любую клавишу для выхода в главное меню');
readkey;
end;
procedure drawtree(root:PTree);
var Width,Height:integer;
CurVPort:ViewPortType;
s,sbal:string;
begin
if (root<>NIL) then
begin
GetViewSettings(CurVPort);
width:=CurVPort.x2-CurVPort.x1;
height:=CurVPort.y2-CurVPort.y1;
str(root^.info,s);
str(root^.balance,sbal);
sbal:='('+sbal+')';
SetColor(15);
Ellipse(width div 2,11,0,360,20,11);
SetFillStyle(SolidFill,7);
FloodFill(width div 2,11,15);
SetColor(8);
OutTextXY(width div 2,4,s);
OutTextXY(width div 2,12,sbal);
SetColor(15);
if (root^.left<>NIL) then
line(width div 2,22,width div 4,height);
if (root^.right<>NIL) then
line(width div 2,22,3*width div 4,height);
with CurVPort do
setviewport(x1,y2,x1+(width div 2),y2+height,ClipOff);
drawtree(root^.left);
with CurVPort do
setviewport(x1+(width div 2),y2,x2,y2+height,ClipOff);
drawtree(root^.right);
end;
end;
procedure drawtree_wrapper(root:PTree);
Var GraphDevice,GraphMode:integer;
PathToDriver:string;
begin
if (root<>NIL) then
begin
GraphDevice:=Detect;
PathToDriver:='';
InitGraph(GraphDevice,GraphMode,PathToDriver);
if (GraphResult<>grOK) then
begin
Writeln('Error initializing graphics!');
readkey;
end
else
begin
SetColor(White);
SetViewPort(15,0,GetMaxX-15,(GetMaxY div (countdepth(root,0)+1)),ClipOff);
SetTextJustify(CenterText,TopText);
drawtree(root);
readkey;
closegraph;
end
end
else
begin
writeln('Дерево пусто!');
readkey;
end;
end;
procedure showmenu;
begin
clrscr;
writeln(' AVL-дерево');
writeln;
writeln(' 1) Добавить элемент в дерево');
writeln(' 2) Распечатать дерево в виде левая ветвь - корень - правая ветвь (ЛКП)');
writeln(' 3) Распечатать дерево в виде корень - левая ветвь - правая ветвь (КЛП)');
writeln(' 4) Распечатать дерево в виде левая ветвь - правая ветвь - корень (ЛПК)');
writeln(' 5) Вывести число вершин дерева');
writeln(' 6) Вывести число листов дерева');
writeln(' 7) Удалить элемент из дерева');
writeln(' 8) Распечатать все вершины на заданном уровне');
writeln(' 9) Вывести глубину дерева');
writeln(' 10) Нарисовать дерево');
writeln(' 11) Выход');
writeln;
write('Ваш выбор : ');
end;
Var Tree:PTree;
selection:integer;
begin
Tree:=NIL;
repeat
showmenu;
readln(selection);
writeln;
case selection of
1: addelem_wrapper(Tree,getint('элемент для добавления'));
2: printLKP_wrapper(Tree);
3: printKLP_wrapper(Tree);
4: printLPK_wrapper(Tree);
5: countels_wrapper(Tree);
6: countleafs_wrapper(Tree);
7: delelem_wrapper(Tree,getint('элемент для удаления'));
8: printlevel_wrapper(Tree,getint('уровень, который нужно распечатать'));
9: countdepth_wrapper(Tree);
10: drawtree_wrapper(Tree);
11:clrscr;
end;
until selection=11;
end.
|
unit Server.Interfaces.Tabela;
interface
type
ITabelaBase = interface ['{1D257E15-B914-436D-A850-F35D75138598}']
{$REGION 'Property Getters & Setters'}
function Getid: Integer;
procedure Setid(const Value: Integer);
function GetDataBase:String;
procedure SetDataBase(const Value: String);
{$ENDREGION}
property id: Integer read Getid write Setid;
property DataBase:String read GetDataBase write SetDataBase;
end;
implementation
end.
|
{==============================================================================|
| MicroCoin |
| Copyright (c) 2018 MicroCoin Developers |
|==============================================================================|
| Permission is hereby granted, free of charge, to any person obtaining a copy |
| of this software and associated documentation files (the "Software"), to |
| deal in the Software without restriction, including without limitation the |
| rights to use, copy, modify, merge, publish, distribute, sublicense, and/or |
| sell opies of the Software, and to permit persons to whom the Software is |
| furnished to do so, subject to the following conditions: |
| |
| The above copyright notice and this permission notice shall be included in |
| all copies or substantial portions of the Software. |
|------------------------------------------------------------------------------|
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| DEALINGS IN THE SOFTWARE. |
|==============================================================================|
| File: MicroCoin.Forms.Keys.KeyManager.pas |
| Created at: 2018-09-11 |
| Purpose: Wallet key manager dialog |
|==============================================================================}
unit MicroCoin.Forms.Keys.KeyManager;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, System.ImageList,
Vcl.ImgList, PngImageList, Vcl.PlatformDefaultStyleActnCtrls, System.Actions,
Vcl.ActnList, Vcl.ActnMan, VirtualTrees, Vcl.Menus, Vcl.ActnPopup,
Vcl.ToolWin, Vcl.ActnCtrls, UCrypto, UITypes, Vcl.StdCtrls, Vcl.Buttons,
PngBitBtn, Vcl.Imaging.pngimage, MicroCoin.Crypto.Keys, Vcl.ExtCtrls,
Printers,
DelphiZXIngQRCode;
type
TWalletKeysForm = class(TForm)
WalletKeyActions: TActionManager;
keyList: TVirtualStringTree;
WalletKeysToolbar: TActionToolBar;
EditNameAction: TAction;
ActionImages: TPngImageList;
ExportPublicKey: TAction;
ExportPrivateKey: TAction;
DeleteKey: TAction;
ListPopupMenu: TPopupActionBar;
ExportPublicKey1: TMenuItem;
ExportPrivateKey1: TMenuItem;
Renamekey1: TMenuItem;
N1: TMenuItem;
DeleteKey1: TMenuItem;
N2: TMenuItem;
ImportPrivateKey: TAction;
ImportPublicKey: TAction;
SaveAll: TAction;
ImportAll: TAction;
AddNewKey: TAction;
Secp256k1: TAction;
Secp384r1: TAction;
Sect283k1: TAction;
Secp521r1: TAction;
SaveKeysDialog: TSaveDialog;
ChangePasswordAction: TAction;
OpenWalletDialog: TOpenDialog;
Panel1: TPanel;
qrPrivate: TImage;
Label1: TLabel;
qrPublic: TImage;
btnPrint: TPngBitBtn;
Image1: TImage;
cbShowPrivate: TCheckBox;
PrintDialog1: TPrintDialog;
procedure FormCreate(Sender: TObject);
procedure keyListInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
procedure keyListGetText(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex; TextType: TVSTTextType; var CellText: string);
procedure EditNameActionUpdate(Sender: TObject);
procedure ExportPublicKeyUpdate(Sender: TObject);
procedure ExportPrivateKeyUpdate(Sender: TObject);
procedure DeleteKeyUpdate(Sender: TObject);
procedure ImportPrivateKeyUpdate(Sender: TObject);
procedure ImportPublicKeyUpdate(Sender: TObject);
procedure SaveAllUpdate(Sender: TObject);
procedure ImportAllUpdate(Sender: TObject);
procedure AddNewKeyUpdate(Sender: TObject);
procedure EditNameActionExecute(Sender: TObject);
procedure AddNewKeyExecute(Sender: TObject);
procedure DeleteKeyExecute(Sender: TObject);
procedure ExportPublicKeyExecute(Sender: TObject);
procedure ExportPrivateKeyExecute(Sender: TObject);
procedure ImportPublicKeyExecute(Sender: TObject);
procedure ImportPrivateKeyExecute(Sender: TObject);
procedure SaveAllExecute(Sender: TObject);
procedure ImportAllExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ChangePasswordActionExecute(Sender: TObject);
procedure keyListFocusChanged(Sender: TBaseVirtualTree; Node: PVirtualNode;
Column: TColumnIndex);
procedure cbShowPrivateClick(Sender: TObject);
procedure btnPrintClick(Sender: TObject);
procedure keyListFreeNode(Sender: TBaseVirtualTree; Node: PVirtualNode);
private
procedure ShowPrivateKey;
function UnlockWallet : Boolean;
function ParseRawKey(AEC_OpenSSL_NID : Word; AEncodedKey : string) : TECKeyPair;
function ParseEncryptedKey(APassword, AKey: AnsiString) : TECKeyPair;
public
{ Public declarations }
end;
var
WalletKeysForm: TWalletKeysForm;
implementation
uses MicroCoin.Node.Node, MicroCoin.Account.AccountKey, UWalletKeys, PlatformVclStylesActnCtrls,
MicroCoin.Common.Config, Clipbrd, UAES, UBaseTypes;
resourcestring
StrKeyName = 'Key name:';
StrEnterName = 'Enter name:';
StrMicroCoinPaperWallet = 'MicroCoin Paper Wallet (%s)';
StrChangeWalletPassword = 'Change wallet password';
StrNewPassword = 'New password';
StrPasswordAgain = 'Password again';
StrPasswordsNotMatch = 'Passwords not match';
StrPasswordChanged = 'Password changed';
StrDoYouWantToDELETE = 'Do you want to DELETE this key? Delete is unrevers' +
'ible!!!';
StrChangeName = 'Change name';
StrInputNewKeyName = 'Input new key name:';
StrEncryptExportedKey = 'Encrypt exported key';
StrEnterPassword = 'Enter password';
StrRepeatPassword = 'Repeat password';
StrPrivateKeyCopiedToClipboard = 'Private key copied to clipboard';
StrPublicKeyCopiedToClipboard = 'Public key copied to clipboard';
StrImportKeys = 'Import keys';
StrInvalidPassword = 'Invalid password';
StrImportPrivateKey = 'Import private key';
StrName = 'Name';
StrPrivateKey = 'Private key';
StrPassword = 'Password';
StrInvalidKey = 'Invalid key';
StrInvalidKeyOrPassw = 'Invalid key or password';
StrImportPublicKey = 'Import public key';
StrEncodedPublicKey = 'Encoded public key';
StrAccountKeyAlreadyExists = 'Account key already exists in wallet';
StrPrivatePublicKey = 'Private & Public key';
StrPublicKey = 'Public key';
StrWalletSavedTo = 'Wallet saved to %s';
StrUnlockWallet = 'Unlock wallet';
StrYourPassword = 'Your password:';
{$R *.dfm}
procedure TWalletKeysForm.AddNewKeyExecute(Sender: TObject);
var
xKey: TECKeyPair;
xName: string;
begin
if not UnlockWallet then exit;
if InputQuery(StrKeyName, StrEnterName, xName) then begin
xKey := TECKeyPair.Create;
xKey.GenerateRandomPrivateKey(TAction(Sender).Tag);
TNode.Node.KeyManager.AddPrivateKey(xName, xKey);
FreeAndNil(xKey);
keyList.RootNodeCount := TNode.Node.KeyManager.Count;
keyList.ReinitNode(nil, true);
end;
end;
procedure TWalletKeysForm.AddNewKeyUpdate(Sender: TObject);
begin
AddNewKey.Enabled := true;
end;
procedure TWalletKeysForm.btnPrintClick(Sender: TObject);
var
xRect: TRect;
xText: string;
xPrinterPixelsPerInch_X, xPrinterPixelsPerInch_Y,
xPrinterLeftMargin, xPrinterTopMargin: integer;
xMargin: integer;
xTop : Integer;
begin
if not UnlockWallet then exit;
if not Assigned( TNode.Node.KeyManager[keyList.FocusedNode.Index].PrivateKey) then exit;
ShowPrivateKey;
if PrintDialog1.Execute(Self.Handle) then begin
Printer.BeginDoc;
xPrinterPixelsPerInch_X := GetDeviceCaps(Printer.Handle, LOGPIXELSX);
xPrinterPixelsPerInch_Y := GetDeviceCaps(Printer.Handle, LOGPIXELSY);
xMargin := xPrinterPixelsPerInch_Y div 2;
Printer.Canvas.Font.Size := 20;
xText:=Format(StrMicroCoinPaperWallet, [ UTF8ToString( TWalletKey(keyList.FocusedNode.GetData^).Name )]);
xRect.Left := 0;
xRect.Top := Printer.Canvas.TextExtent(xText).Height + xMargin;
xRect.Height := Printer.Canvas.TextExtent(xText).Height;
xRect.Width := Printer.PageWidth;
Printer.Canvas.TextRect(xRect, xText, [TTextFormats.tfCenter]);
xRect.Bottom := xRect.Top+Printer.Canvas.TextExtent(xText).Height;
Printer.Canvas.MoveTo(xMargin, xRect.Bottom + xPrinterPixelsPerInch_Y div 5);
Printer.Canvas.LineTo( Printer.PageWidth - xMargin, xRect.Bottom+xPrinterPixelsPerInch_Y div 5);
Printer.Canvas.Font.Size := 15;
xRect.Top := xRect.Bottom + xPrinterPixelsPerInch_Y div 2;
xRect.Left := 0;
xText := 'Public key';
xRect.Width := (Printer.PageWidth) div 2;
xRect.Height := Printer.Canvas.TextExtent(xText).Height;
xTop := xRect.Top;
Printer.Canvas.TextRect(xRect, xText ,[TTextFormats.tfCenter]);
xRect.Top := xRect.Bottom + Printer.Canvas.TextExtent(xText).Height;
xRect.Left := ((Printer.PageWidth div 2) div 2) - xPrinterPixelsPerInch_X;
xRect.Width := xPrinterPixelsPerInch_X*2;
xRect.Height := xPrinterPixelsPerInch_Y*2;
Printer.Canvas.StretchDraw(xRect, qrPublic.Picture.Bitmap);
xRect.Top := xTop;
xRect.Left := Printer.PageWidth div 2;
xText := 'Private key';
xRect.Width := (Printer.PageWidth) div 2;
xRect.Height := Printer.Canvas.TextExtent(xText).Height;
Printer.Canvas.TextRect(xRect, xText ,[TTextFormats.tfCenter]);
xRect.Top := Printer.Canvas.TextExtent(xText).Height + xRect.Bottom;
xRect.Left := (Printer.PageWidth div 2) + ((Printer.PageWidth div 2) div 2) - xPrinterPixelsPerInch_X;
// xRect.Left := xRect.Right + xMargin;
xRect.Width := xPrinterPixelsPerInch_X*2;
xRect.Height := xPrinterPixelsPerInch_Y*2;
Printer.Canvas.StretchDraw(xRect, qrPrivate.Picture.Bitmap);
xRect.Left := xMargin;
xRect.Top := xPrinterPixelsPerInch_Y*2 + xRect.Top + xPrinterPixelsPerInch_Y div 2;
Printer.Canvas.MoveTo(xMargin, xRect.Top);
Printer.Canvas.LineTo( Printer.PageWidth - xMargin, xRect.Top);
xRect.Top := xRect.Top + xPrinterPixelsPerInch_Y div 5;
Printer.Canvas.Font.Size := 10;
xText := 'Private key: '+TCrypto.PrivateKey2Hexa(TNode.Node.KeyManager[keyList.FocusedNode.Index].PrivateKey)
+sLineBreak+sLineBreak+'Printed at: '+FormatDateTime('c', Now);
xRect.Height := xPrinterPixelsPerInch_Y;
xRect.Width := Printer.PageWidth - xMargin;
DrawText(Printer.Canvas.Handle, xText, -1, xRect, DT_NOPREFIX or DT_WORDBREAK);
Printer.EndDoc;
end;
end;
procedure TWalletKeysForm.ChangePasswordActionExecute(Sender: TObject);
var
xPassword: array[0..1] of string;
begin
if not UnlockWallet then exit;
repeat
if not InputQuery(StrChangeWalletPassword, [#30+StrNewPassword, #30+StrPasswordAgain], xPassword)
then exit;
if xPassword[0] <> xPassword[1]
then MessageDlg(StrPasswordsNotMatch, mtError, [mbOk], 0)
else break;
until true;
TNode.Node.KeyManager.WalletPassword := xPassword[0];
MessageDlg(StrPasswordChanged, mtInformation, [mbOK], 0);
end;
procedure TWalletKeysForm.DeleteKeyExecute(Sender: TObject);
begin
if not UnlockWallet then exit;
if MessageDlg(StrDoYouWantToDELETE, mtWarning, [mbYes, mbNo], 0) = mrYes
then begin
TNode.Node.KeyManager.Delete(keyList.FocusedNode.Index);
keyList.RootNodeCount := TNode.Node.KeyManager.Count;
keyList.ReinitNode(nil, true);
end;
end;
procedure TWalletKeysForm.DeleteKeyUpdate(Sender: TObject);
begin
DeleteKey.Enabled := keyList.FocusedNode<>nil;
end;
procedure TWalletKeysForm.EditNameActionExecute(Sender: TObject);
var
xName: String;
begin
if not UnlockWallet then exit;
if InputQuery(StrChangeName,StrInputNewKeyName,xName) then begin
if xName = '' then exit;
TNode.Node.KeyManager.SetName(keyList.FocusedNode.Index, xName);
keyList.ReinitNode(keyList.FocusedNode, true);
end;
end;
procedure TWalletKeysForm.EditNameActionUpdate(Sender: TObject);
begin
EditNameAction.Enabled := keyList.FocusedNode<>nil;
end;
procedure TWalletKeysForm.ExportPrivateKeyExecute(Sender: TObject);
var
xPass: array[0..1] of string;
begin
if not UnlockWallet then exit;
if InputQuery(StrEncryptExportedKey, [#30+StrEnterPassword, #30+StrRepeatPassword], {$IFDEF FPC}true,{$ENDIF} xPass)
then begin
if xPass[0]<>xPass[1] then raise Exception.Create(StrPasswordsNotMatch);
if xPass[0]<>''
then Clipboard.AsText := TBaseType.ToHexaString( TAESComp.EVP_Encrypt_AES256( TNode.Node.KeyManager[keyList.FocusedNode.Index].PrivateKey.ExportToRaw, xPass[0]) )
else Clipboard.AsText := TCrypto.PrivateKey2Hexa(TNode.Node.KeyManager[keyList.FocusedNode.Index].PrivateKey);
MessageDlg(StrPrivateKeyCopiedToClipboard, mtInformation, [mbOk], 0);
end else exit;
end;
procedure TWalletKeysForm.ExportPrivateKeyUpdate(Sender: TObject);
begin
ExportPrivateKey.Enabled := keyList.FocusedNode<>nil;
end;
procedure TWalletKeysForm.ExportPublicKeyExecute(Sender: TObject);
begin
if not UnlockWallet then exit;
Clipboard.AsText := TWalletKey(keyList.FocusedNode.GetData^).AccountKey.AccountPublicKeyExport;
MessageDlg(StrPublicKeyCopiedToClipboard, mtInformation, [mbOk], 0);
end;
procedure TWalletKeysForm.ExportPublicKeyUpdate(Sender: TObject);
begin
ExportPublicKey.Enabled := keyList.FocusedNode<>nil;
end;
procedure TWalletKeysForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
TNode.Node.KeyManager.LockWallet;
Action := caFree;
end;
procedure TWalletKeysForm.FormCreate(Sender: TObject);
begin
keyList.NodeDataSize := SizeOf(TWalletKey);
keyList.RootNodeCount := TNode.Node.KeyManager.Count;
WalletKeyActions.Style := PlatformVclStylesStyle;
end;
procedure TWalletKeysForm.ImportAllExecute(Sender: TObject);
var
xKeys: TWalletKeys;
xPassword: string;
i: integer;
begin
if OpenWalletDialog.Execute then begin
xKeys := TWalletKeys.Create(nil);
xKeys.WalletFileName := OpenWalletDialog.FileName;
if not xKeys.IsValidPassword then begin
if not InputQuery(StrImportKeys, #30+StrEnterPassword, xPassword)
then exit;
xKeys.WalletPassword := xPassword;
if not xKeys.IsValidPassword
then begin
MessageDlg(StrInvalidPassword, mtError, [mbOk], 0);
exit;
end;
end;
for i := 0 to xKeys.Count-1 do begin
if TNode.Node.KeyManager.IndexOfAccountKey(xKeys[i].AccountKey) > -1
then continue;
if assigned(xKeys[i].PrivateKey)
then TNode.Node.KeyManager.AddPrivateKey(xKeys[i].Name, xKeys[i].PrivateKey)
else TNode.Node.KeyManager.AddPublicKey(xKeys[i].Name, xKeys[i].AccountKey);
end;
FreeAndNil(xKeys);
keyList.RootNodeCount := TNode.Node.KeyManager.Count;
keyList.ReinitNode(nil, true);
end;
end;
procedure TWalletKeysForm.ImportAllUpdate(Sender: TObject);
begin
ImportAll.Enabled := true;
end;
function TWalletKeysForm.ParseRawKey(AEC_OpenSSL_NID : Word; AEncodedKey : string) : TECKeyPair;
begin
Result := TECKeyPair.Create;
Try
Result.SetPrivateKeyFromHexa(AEC_OpenSSL_NID, TBaseType.ToHexaString(AEncodedKey));
Except
On E:Exception do begin
Result.Free;
Result := nil;
end;
end;
end;
function TWalletKeysForm.ParseEncryptedKey(APassword, AKey: AnsiString) : TECKeyPair;
var
xDecryptedKey: AnsiString;
begin
Result := nil;
if TAESComp.EVP_Decrypt_AES256(AKey, APassword, xDecryptedKey) then begin
if (xDecryptedKey<>'') then begin
Result := TECKeyPair.ImportFromRaw(xDecryptedKey);
Exit;
end
end;
end;
procedure TWalletKeysForm.ImportPrivateKeyExecute(Sender: TObject);
var
xRawkey, xEncodedKey: string;
xData: array[0..2] of string;
xResult: TECKeyPair;
begin
if not UnlockWallet
then exit;
if not InputQuery(StrImportPrivateKey, [StrName, StrPrivateKey, #30+StrPassword], xData )
then exit;
xData[0] := trim(xData[0]);
xData[1] := trim(xData[1]);
xData[2] := trim(xData[2]);
if xData[1] = ''
then exit;
if xData[0] = ''
then xData[0] := DateTimeToStr(Now);
xEncodedKey := TBaseType.HexaToRaw(xData[1]);
if xEncodedKey = ''
then begin
MessageDlg(StrInvalidKey, mtError, [mbOk], 0);
exit;
end;
case Length(xEncodedKey) of
32: xResult := ParseRawKey(cNID_secp256k1, xEncodedKey);
35,36: xResult := ParseRawKey(cNID_sect283k1, xEncodedKey);
48: xResult := ParseRawKey(cNID_secp384r1, xEncodedKey);
65,66: xResult := ParseRawKey(cNID_secp521r1, xEncodedKey);
64, 80, 96: xResult := ParseEncryptedKey(xData[2], xEncodedKey);
else begin
MessageDlg(StrInvalidKey, mtError, [mbOk], 0);
exit;
end;
end;
if xResult = nil
then begin
MessageDlg(StrInvalidKeyOrPassw, mtError, [mbOk], 0);
exit;
end;
TNode.Node.KeyManager.AddPrivateKey(xData[0], xResult);
keyList.RootNodeCount := TNode.Node.KeyManager.Count;
keyList.ReinitNode(nil, true);
end;
procedure TWalletKeysForm.ImportPrivateKeyUpdate(Sender: TObject);
begin
ImportPrivateKey.Enabled := true;
end;
procedure TWalletKeysForm.ImportPublicKeyExecute(Sender: TObject);
var
xData : array[0..1] of string;
xAccountKey: TAccountKey;
xErrors: AnsiString;
xRawKey: string;
begin
if not UnlockWallet then exit;
if not InputQuery(StrImportPublicKey, [StrKeyName, StrEncodedPublicKey], xData)
then exit;
if not TAccountKey.AccountPublicKeyImport(xData[1], xAccountKey, xErrors)
then begin
xRawKey := TBaseType.HexaToRaw(xData[1]);
if trim(xRawKey)='' then begin
MessageDlg(xErrors, mtError, [mbOk], 0);
exit;
end;
xAccountKey := TAccountKey.FromRawString(xRawKey);
end;
if not xAccountKey.IsValidAccountKey(xErrors)
then begin
MessageDlg(xErrors, mtError, [mbOk], 0);
exit;
end;
if TNode.Node.KeyManager.IndexOfAccountKey(xAccountKey) > -1
then begin
MessageDlg(StrAccountKeyAlreadyExists, mtInformation, [mbOk], 0);
exit;
end;
if xData[0] = ''
then xData[0] := DateTimeToStr(Now);
TNode.Node.KeyManager.AddPublicKey(xData[0], xAccountKey);
keyList.RootNodeCount := TNode.Node.KeyManager.Count;
keyList.ReinitNode(nil, true);
end;
procedure TWalletKeysForm.ImportPublicKeyUpdate(Sender: TObject);
begin
ImportPublicKey.Enabled := true;
end;
procedure TWalletKeysForm.keyListFocusChanged(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex);
var
xQRCode: TDelphiZXingQRCode;
xRow, xCol: Integer;
xQRCodeBitmap: TBitmap;
begin
if Node = nil then exit;
qrPrivate.Picture := Image1.Picture;
xQRCode := TDelphiZXingQRCode.Create;
try
xQRCodeBitmap := qrPublic.Picture.Bitmap;
xQRCode.Data := TWalletKey(Node.GetData^).AccountKey.AccountPublicKeyExport;
xQRCode.Encoding := TQRCodeEncoding(qrISO88591);
xQRCode.QuietZone := 1;
xQRCodeBitmap.SetSize(xQRCode.Rows, xQRCode.Columns);
for xRow := 0 to xQRCode.Rows - 1 do
begin
for xCol := 0 to xQRCode.Columns - 1 do
begin
if (xQRCode.IsBlack[xRow, xCol]) then
begin
xQRCodeBitmap.Canvas.Pixels[xCol, xRow] := clBlack;
end else
begin
xQRCodeBitmap.Canvas.Pixels[xCol, xRow] := clWhite;
end;
end;
end;
QRPublic.Picture.Bitmap := xQRCodeBitmap;
finally
xQRCode.Free;
end;
ShowPrivateKey;
end;
procedure TWalletKeysForm.keyListFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
begin
TWalletKey(Node.GetData^) := Default(TWalletKey);
end;
procedure TWalletKeysForm.keyListGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
xKey: TWalletKey;
begin
xKey := TWalletKey(Node.GetData^);
case Column of
0: CellText := UTF8ToString(xKey.Name);
1: CellText := TAccountKey.GetECInfoTxt(xKey.AccountKey.EC_OpenSSL_NID);
2: if Assigned(xKey.PrivateKey) then CellText := StrPrivatePublicKey else CellText := StrPublicKey;
end;
end;
procedure TWalletKeysForm.keyListInitNode(Sender: TBaseVirtualTree; ParentNode,
Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
begin
Sender.SetNodeData(Node, TNode.Node.KeyManager[Node.Index]);
end;
procedure TWalletKeysForm.ShowPrivateKey;
var
xQRCode: TDelphiZXingQRCode;
xRow, xCol: Integer;
xQRCodeBitmap: TBitmap;
begin
if keyList.FocusedNode = nil
then exit;
if not Assigned( TNode.Node.KeyManager[keyList.FocusedNode.Index].PrivateKey )
then exit;
xQRCode := TDelphiZXingQRCode.Create;
try
xQRCodeBitmap := qrPrivate.Picture.Bitmap;
xQRCode.Data := TCrypto.PrivateKey2Hexa(TNode.Node.KeyManager[keyList.FocusedNode.Index].PrivateKey);
xQRCode.Encoding := TQRCodeEncoding(qrISO88591);
xQRCode.QuietZone := 1;
xQRCodeBitmap.SetSize(xQRCode.Rows, xQRCode.Columns);
for xRow := 0 to xQRCode.Rows - 1 do
begin
for xCol := 0 to xQRCode.Columns - 1 do
begin
if (xQRCode.IsBlack[xRow, xCol]) then
begin
xQRCodeBitmap.Canvas.Pixels[xCol, xRow] := clBlack;
end else
begin
xQRCodeBitmap.Canvas.Pixels[xCol, xRow] := clWhite;
end;
end;
end;
qrPrivate.Picture.Bitmap := xQRCodeBitmap;
finally
xQRCode.Free;
end;
end;
procedure TWalletKeysForm.cbShowPrivateClick(Sender: TObject);
begin
UnlockWallet;
qrPrivate.Visible := cbShowPrivate.Checked;
ShowPrivateKey;
end;
procedure TWalletKeysForm.SaveAllExecute(Sender: TObject);
var
xStream : TStream;
xFilename: TFilename;
begin
if SaveKeysDialog.Execute then begin
xFilename := SaveKeysDialog.FileName;
xStream := TFileStream.Create(xFilename, fmCreate);
try
TNode.Node.KeyManager.SaveToStream(xStream);
MessageDlg(Format(StrWalletSavedTo, [xFilename]), mtInformation, [mbOk], 0);
finally
FreeAndNil(xStream);
end;
end;
end;
procedure TWalletKeysForm.SaveAllUpdate(Sender: TObject);
begin
SaveAll.Enabled := keyList.RootNodeCount > 0;
end;
function TWalletKeysForm.UnlockWallet: Boolean;
var
xPassword: string;
begin
Result := TNode.Node.KeyManager.IsValidPassword;
while not TNode.Node.KeyManager.IsValidPassword
do begin
if not InputQuery(StrUnlockWallet, #30+StrYourPassword, xPassword)
then exit;
TNode.Node.KeyManager.WalletPassword := xPassword;
end;
Result := TNode.Node.KeyManager.IsValidPassword;
end;
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 3.5 for Delphi and C++Builder ::
:: ::
:: QRDATASU.PAS - QuickReport data setup dialog ::
:: ::
:: Copyright (c) 2007 QBS Software ::
:: All Rights Reserved ::
:: ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
{$include QRDefs.inc}
unit QRDatasu;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Buttons, StdCtrls, ExtCtrls, DB, DBTables, FileCtrl, QuickRpt, QREditor,
QRMDSU;
type
TQRDataSetup = class(TForm)
DataType: TRadioGroup;
AliasGB: TGroupBox;
BrowseButton: TButton;
DataBaseName: TComboBox;
TableGroup: TGroupBox;
TableName: TComboBox;
FilterExpression: TEdit;
Label1: TLabel;
FilterLabel: TLabel;
SQLGroup: TGroupBox;
SQL: TMemo;
OpenSQL: TButton;
OKButton: TBitBtn;
BitBtn2: TBitBtn;
Label3: TLabel;
IndexName: TComboBox;
GroupBox1: TGroupBox;
MDEnable: TCheckBox;
MDSetupButton: TButton;
procedure DataTypeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BrowseButtonClick(Sender: TObject);
procedure DataBaseNameChange(Sender: TObject);
procedure TableNameChange(Sender: TObject);
procedure SQLChange(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure MDEnableClick(Sender: TObject);
procedure MDSetupButtonClick(Sender: TObject);
private
FReport : TQuickRep;
TableComp : TTable;
QueryComp : TQuery;
MasterDS : TDataSource;
DetailTable : TTable;
FReportEditor : TQRCustomEditor;
FSubDetail : TQRSubDetail;
protected
procedure GetEditValues;
procedure SetReport(Value : TQuickRep);
procedure SetData;
public
property QuickRep : TQuickRep read FReport write SetReport;
property SubDetail : TQRSubDetail read FSubDetail write FSubDetail;
property ReportEditor : TQRCustomEditor read FReportEditor write FReportEditor;
end;
var
QRDataSetup: TQRDataSetup;
implementation
{$R *.DFM}
procedure Enable(Control : TWinControl; Enabled : boolean);
var
i : integer;
begin
Control.Enabled:=Enabled;
for i:=0 to Control.ControlCount-1 do
Control.Controls[I].Enabled:=Enabled;
end;
procedure TQRDataSetup.GetEditValues;
begin
case DataType.ItemIndex of
0 : begin
TableName.Items.Clear;
IndexName.Items.Clear;
TableName.Text := '';
IndexName.Text := '';
FilterExpression.Text := '';
SQL.Lines.Clear;
end;
1 : begin
if TableComp.DatabaseName <> '' then
begin
DatabaseNameChange(Self);
DatabaseName.Text := TableComp.DatabaseName
end else
TableComp.DatabaseName := DatabaseName.Text;
TableName.Text := TableComp.TableName;
IndexName.Text := TableComp.IndexName;
FilterExpression.Text := TableComp.Filter;
SQL.Lines.Clear;
end;
2 : begin
TableName.Items.Clear;
IndexName.Items.Clear;
TableName.Text := '';
IndexName.Text := '';
FilterExpression.Text := '';
SQL.Lines.Assign(QueryComp.SQL);
if QueryComp.DatabaseName <> '' then
begin
DatabaseName.Text := QueryComp.DatabaseName;
DatabaseNameChange(Self)
end else
QueryComp.DatabaseName := DatabaseName.Text;
end;
end;
end;
procedure TQRDataSetup.SetData;
begin
case DataType.ItemIndex of
1 : begin
TableComp.Active := false;
TableComp.DatabaseName := DatabaseName.Text;
TableComp.TableName := TableName.Text;
TableComp.IndexName := IndexName.Text;
TableComp.Filter := FilterExpression.Text;
if FilterExpression.Text <> '' then
TableComp.Filtered := true;
if TableComp.TableName <> '' then
TableComp.Active := true;
end;
2: begin
QueryComp.Active := false;
QueryComp.SQL.Assign(SQL.Lines);
QueryComp.DatabaseName := DatabaseName.Text;
QueryComp.Active := true;
end;
end
end;
procedure TQRDataSetup.DataTypeClick(Sender: TObject);
begin
Enable(TableGroup,DataType.ItemIndex = 1);
Enable(SQLGroup, DataType.ItemIndex = 2);
case DataType.ItemIndex of
0 : begin
if TableComp <> nil then
begin
TableComp.Free;
TableComp := nil;
end;
if assigned(QueryComp) then
begin
QueryComp.Free;
QueryComp := nil;
end;
if Assigned(MasterDS) then
begin
MasterDS.Free;
MasterDS := nil;
end;
end;
1 : begin
if TableComp = nil then
begin
TableComp := TTable.Create(FReport);
TableComp.Name := UniqueName(FReport.Owner, 'MasterTable'); {<-- do not resource}
FReport.DataSet := TableComp;
end;
if assigned(QueryComp) then
begin
QueryComp.Free;
QueryComp := nil;
end;
if MasterDS = nil then
MasterDS := TDataSource.Create(FReport);
MasterDS.Dataset := TableComp;
end;
2 : begin
if QueryComp = nil then
begin
QueryComp := TQuery.Create(FReport);
QueryComp.Name := UniqueName(FReport.Owner, 'MasterQuery'); {<-- do not resource}
FReport.DataSet := QueryComp;
end;
if assigned(TableComp) then begin
TableComp.Free;
TableComp := nil;
end;
if MasterDS = nil then
MasterDS := TDataSource.Create(FReport);
MasterDS.Dataset := QueryComp;
end;
end;
{ for I := 0 to FReport.ComponentCount - 1 do
if FReport.Components[I] is TDataSource then
begin
FReport.Components[I].Free;
Break;
end;}
GetEditValues;
end;
procedure TQRDataSetup.FormCreate(Sender: TObject);
begin
Session.GetDatabaseNames(DataBaseName.Items);
FilterExpression.Visible := false;
FilterLabel.Visible := false;
MasterDS := nil;
GetEditValues;
end;
procedure TQRDataSetup.SetReport(Value : TQuickRep);
var
I : integer;
begin
SubDetail := nil;
FReport := Value;
if FReport.DataSet <> nil then
begin
if FReport.DataSet is TTable then
begin
TableComp := TTable(FReport.DataSet);
DataType.ItemIndex := 1;
end;
if FReport.DataSet is TQuery then
begin
QueryComp := TQuery(FReport.DataSet);
DataType.ItemIndex := 2;
end;
end;
for I := 0 to FReport.ControlCount - 1 do
if FReport.Controls[I] is TQRSubDetail then
begin
SubDetail := TQRSubDetail(FReport.Controls[I]);
mdEnable.Checked := true;
end;
for I := 0 to FReport.ComponentCount - 1 do
if FReport.Components[I] is TDataSource then
begin
MasterDS := TDataSource(FReport.Components[I]);
end;
MDEnable.Checked := SubDetail <> nil;
MDSetupButton.Enabled := MDEnable.Checked;
DataTypeClick(Self);
end;
procedure TQRDataSetup.BrowseButtonClick(Sender: TObject);
var
ADirectory : String;
begin
ADirectory := '';
if SelectDirectory(ADirectory,[],0) then
DatabaseName.Text:=ADirectory;
DatabaseNameChange(Self);
end;
procedure TQRDataSetup.DataBaseNameChange(Sender: TObject);
begin
Session.GetTableNames(DatabaseName.Text, '', true, false, TableName.Items);
case DataType.ItemIndex of
1 : if TableName.Items.IndexOf(TableName.Text) = -1 then
TableName.Text := '';
end;
end;
procedure TQRDataSetup.TableNameChange(Sender: TObject);
begin
if TableName.Text <> TableComp.TableName then
begin
TableComp.Active := false;
TableComp.IndexName := '';
TableComp.DatabaseName := DatabaseName.Text;
TableComp.TableName := TableName.Text;
if TableName.Text <> '' then
TableComp.Active := true;
IndexName.Items.Clear;
IndexName.Text := '';
TableComp.GetIndexNames(IndexName.Items);
end
end;
procedure TQRDataSetup.SQLChange(Sender: TObject);
begin
OpenSQL.Enabled := true;
end;
procedure TQRDataSetup.OKButtonClick(Sender: TObject);
begin
SetData;
end;
procedure TQRDataSetup.MDEnableClick(Sender: TObject);
var
ASubDetail : TQRSubDetail;
begin
if MDEnable.Checked and (SubDetail = nil) then
begin
ASubDetail := TQRSubDetail.Create(nil);
ASubDetail.Parent := FReport;
ReportEditor.Add(ASubDetail, FReport);
ReportEditor.SetEvents(ReportEditor);
DetailTable := TTable.Create(FReport);
DetailTable.Name := UniqueName(FReport, 'DetailTable'); {<-- do not resource}
DetailTable.MasterSource := MasterDS;
ASubDetail.Dataset := DetailTable;
SubDetail := ASubDetail;
end
else if not MDEnable.Checked then
begin
ReportEditor.Select(SubDetail, false);
ReportEditor.DeleteSelected;
SubDetail := nil;
DetailTable.Free;
end;
MDSetupButton.Enabled := MDEnable.Checked;
end;
procedure TQRDataSetup.MDSetupButtonClick(Sender: TObject);
begin
SetupSubDetail(SubDetail, FReport, MasterDS, ReportEditor);
end;
end.
|
unit GRRObligationPoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, GRRObligation, MeasureUnits, Table,
Well, Organization, SeismWorkType, Structure, Area, State;//, LicenseZone;
type
TBaseObligationDataPoster = class(TImplementedDataPoster)
private
FNirStates : TNIRStates;
FNirTypes: TNIRTypes;
public
property AllNirStates : TNIRStates read FNirStates write FNirStates;
property AllNirTypes : TNIRTypes read FNirTypes write FNirTypes;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TNIRDataPoster = class(TBaseObligationDataPoster)
private
FMainNirObligations: TNIRObligations;
FMeasureUnits: TMeasureUnits;
// FVersion:
public
property AllMainNirObligations: TNIRObligations read FMainNirObligations write FMainNirObligations;
property AllMeasureUnits: TMeasureUnits read FMeasureUnits write FMeasureUnits;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TNIRStateDataPoster = class (TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TNIRTypeDataPoster = class (TImplementedDataPoster)
private
FNIRTypes: TNIRTypes;
public
property AllNIRTypes: TNIRTypes read FNIRTypes write FNIRTypes;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TSeismicObligationDataPoster = class(TBaseObligationDataPoster)
private
FSeismWorkTypes: TSeismWorkTypes;
public
property AllSeismWorkTypes: TSeismWorkTypes read FSeismWorkTypes write FSeismWorkTypes;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TDrillingObligationDataPoster = class(TBaseObligationDataPoster)
private
FWellStates: TStates;
FWellCategories: TWellCategories;
public
property AllWellStates: TStates read FWellStates write FWellStates;
property AllWellCategories: TWellCategories read FWellCategories write FWellCategories;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TNirObligationPlaceDataPoster = class(TImplementedDataPoster)
private
FStructures: TStructures;
public
property AllStructures: TStructures read FStructures write FStructures;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TSeismicObligationPlaceDataPoster = class (TImplementedDataPoster)
private
FStructures: TStructures;
FAllAreas: TSimpleAreas;
public
property AllStructures: TStructures read FStructures write FStructures;
property AllAreas: TSimpleAreas read FAllAreas write FAllAreas;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TDrillingObligationWellDataPoster = class (TImplementedDataPoster)
private
FStructures: TStructures;
FWells : TWells;
FNirStates : TNIRStates;
public
property AllStructures: TStructures read FStructures write FStructures;
property AllWells: TWells read FWells write FWells;
property AllNirStates : TNIRStates read FNirStates write FNirStates;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
implementation
uses Facade, SysUtils, Math, DateUtils, Variants;
{ TNIRDataPoster }
constructor TNIRDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_NIR_OBLIGATION_TMP';
DataDeletionString := 'TBL_NIR_OBLIGATION_TMP';
DataPostString := 'TBL_NIR_OBLIGATION_TMP';
FieldNames := 'OBLIGATION_ID, LICENSE_ID, VERSION_ID, ' +
'DTM_FINISH_DATE, NIR_TYPE_ID, VCH_COMMENT, VCH_DATE_CONDITION,' +
'NUM_NIR_FACT_COST, NUM_VOLUME, VOLUME_MEASURE_UNIT_ID,MAIN_OBLIGATION_ID,' +
'NUM_FOR_FIELD_ONLY, NIR_FACT_STATE_ID, DTM_START_DATE, VCH_OBLIGATION_NAME';
AccessoryFieldNames := 'OBLIGATION_ID, LICENSE_ID, VERSION_ID, ' +
'DTM_FINISH_DATE, NIR_TYPE_ID, VCH_COMMENT, VCH_DATE_CONDITION,' +
'NUM_NIR_FACT_COST, NUM_VOLUME, VOLUME_MEASURE_UNIT_ID,MAIN_OBLIGATION_ID,' +
'NUM_FOR_FIELD_ONLY, NIR_FACT_STATE_ID, DTM_START_DATE, VCH_OBLIGATION_NAME';
AutoFillDates := false;
Sort := '';
end;
function TNIRDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TNIRDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TNIRObligation;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TNIRObligation;
o.ID := ds.FieldByName('OBLIGATION_ID').AsInteger;
o.StartDate := ds.FieldByName('DTM_START_DATE').AsDateTime;
o.FinishDate := ds.FieldByName('DTM_FINISH_DATE').AsDateTime;
o.Comment := trim(ds.FieldByName('VCH_COMMENT').AsString);
o.Name := trim(ds.FieldByName('VCH_OBLIGATION_NAME').AsString);
if Assigned(AllNirStates) then
o.NIRState := AllNirStates.ItemsById[ds.FieldByName('NIR_FACT_STATE_ID').AsInteger] as TNIRState
else
o.NIRState := nil;
if Assigned(AllNirTypes) then
o.NirType := AllNirTypes.ItemsById[ds.FieldByName('NIR_TYPE_ID').AsInteger] as TNIRType
else
o.NirType := nil;
if Assigned(AllMeasureUnits) then
o.MeasureUnit := AllMeasureUnits.ItemsById[ds.FieldByName('VOLUME_MEASURE_UNIT_ID').AsInteger] as TMeasureUnit
else
o.MeasureUnit := nil;
if Assigned(AllMainNirObligations) then
o.MainObligation := AllMainNirObligations.ItemsById[ds.FieldByName('MAIN_OBLIGATION_ID').AsInteger] as TNIRObligation
else
o.MainObligation := nil;
o.DateCondition := ds.FieldByName('VCH_DATE_CONDITION').AsString;
o.FactCost := ds.FieldByName('NUM_NIR_FACT_COST').AsFloat;
o.Volume := ds.FieldByName('NUM_VOLUME').AsFloat;
o.ForFieldOnly := ds.FieldByName('NUM_FOR_FIELD_ONLY').AsInteger;
ds.Next;
end;
end;
ds.First;
end;
end;
function TNIRDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TNIRObligation;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, TMainFacade.GetInstance.ActiveVersion.Id]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
o := AObject as TNIRObligation;
ds.FieldByName('OBLIGATION_ID').Value := o.ID;
ds.FieldByName('DTM_START_DATE').Value := o.StartDate;
ds.FieldByName('DTM_FINISH_DATE').Value := o.FinishDate;
ds.FieldByName('VCH_OBLIGATION_NAME').Value := Trim(o.Name);
ds.FieldByName('VCH_COMMENT').Value := o.Comment ;
ds.FieldByName('VERSION_ID').Value := TMainFacade.GetInstance.ActiveVersion.Id;
ds.FieldByName('LICENSE_ID').Value := o.Owner.ID;
if Assigned(o.NirType) then
ds.FieldByName('NIR_TYPE_ID').Value := o.NirType.ID
else
ds.FieldByName('NIR_TYPE_ID').Value := null;
if Assigned(o.NIRState) then
ds.FieldByName('NIR_FACT_STATE_ID').Value := o.NIRState.ID
else
ds.FieldByName('NIR_FACT_STATE_ID').Value := null;
ds.FieldByName('VCH_DATE_CONDITION').Value := o.DateCondition;
ds.FieldByName('NUM_NIR_FACT_COST').Value := o.FactCost;
ds.FieldByName('NUM_VOLUME').Value := o.Volume;
ds.FieldByName('NUM_FOR_FIELD_ONLY').Value := o.ForFieldOnly;
if Assigned(o.MainObligation) then
ds.FieldByName('MAIN_OBLIGATION_ID').Value := o.MainObligation.Id
else
ds.FieldByName('MAIN_OBLIGATION_ID').Value := null;
if Assigned(o.MeasureUnit) then
ds.FieldByName('VOLUME_MEASURE_UNIT_ID').Value := o.MeasureUnit.ID
else
ds.FieldByName('VOLUME_MEASURE_UNIT_ID').Value := null;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('OBLIGATION_ID').Value;
end;
{TNIRStateDataPoster}
constructor TNIRStateDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_NIR_STATE';
DataDeletionString := 'TBL_NIR_STATE';
DataPostString := 'TBL_NIR_STATE';
KeyFieldNames := 'NIR_STATE_ID';
FieldNames := 'NIR_STATE_ID, VCH_NOR_STATE_NAME';
AccessoryFieldNames := 'NIR_STATE_ID, VCH_NOR_STATE_NAME';
AutoFillDates := false;
Sort := '';
end;
function TNIRStateDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TNIRStateDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TNIRState;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TNIRState;
o.ID := ds.FieldByName('NIR_STATE_ID').AsInteger;
o.Name := ds.FieldByName('VCH_NOR_STATE_NAME').AsString;
ds.Next;
end;
end;
ds.First;
end;
end;
function TNIRStateDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TNIRState;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TNIRState;
ds.FieldByName('NIR_STATE_ID').Value := o.ID;
ds.FieldByName('VCH_NOR_STATE_NAME').Value := o.Name;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('NIR_STATE_ID').Value;
end;
{TNIRTypeDataPoster}
constructor TNIRTypeDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_NIR_TYPE_DICT';
DataDeletionString := 'TBL_NIR_TYPE_DICT';
DataPostString := 'TBL_NIR_TYPE_DICT';
KeyFieldNames := 'NIR_TYPE_ID';
FieldNames := 'NIR_TYPE_ID, VCH_NIR_TYPE, MAIN_NIR_TYPE_ID';
AccessoryFieldNames := 'NIR_TYPE_ID, VCH_NIR_TYPE, MAIN_NIR_TYPE_ID';
AutoFillDates := false;
Sort := '';
end;
function TNIRTypeDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TNIRTypeDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TNIRType;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TNIRType;
o.ID := ds.FieldByName('NIR_TYPE_ID').AsInteger;
o.Name := ds.FieldByName('VCH_NIR_TYPE').AsString;
if Assigned(FNIRTypes) then
o.Main := FNIRTypes.ItemsByID[ds.FieldByName('MAIN_NIR_TYPE_ID').AsInteger] as TNIRType;
ds.Next;
end;
end;
ds.First;
end;
end;
function TNIRTypeDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TNIRType;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TNIRType;
ds.FieldByName('NIR_TYPE_ID').Value := o.ID;
ds.FieldByName('VCH_NIR_TYPE').Value := o.Name;
if Assigned(o.Main) then
ds.FieldByName('MAIN_NIR_TYPE_ID').Value := o.Main.Id
else
ds.FieldByName('MAIN_NIR_TYPE_ID').Value := null;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('NIR_TYPE_ID').Value;
end;
{ TDrillDataPoster }
constructor TDrillingObligationDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_DRILLING_OBLIGATION_TMP';
DataDeletionString := 'TBL_DRILLING_OBLIGATION_TMP';
DataPostString := 'TBL_DRILLING_OBLIGATION_TMP';
KeyFieldNames := 'OBLIGATION_ID; VERSION_ID';
FieldNames := 'OBLIGATION_ID, LICENSE_ID, VERSION_ID,' +
'DTM_DRILLING_START_DATE, DTM_DRILLING_FINISH_DATE,'+
'WELL_STATE_ID, WELL_CATEGORY_ID, NUM_WELL_COUNT,' +
'NUM_WELL_COUNT_IS_UNDEFINED, NUM_FACT_COST, VCH_COMMENT, NIR_STATE_ID';
AccessoryFieldNames := 'OBLIGATION_ID, LICENSE_ID, VERSION_ID,' +
'DTM_DRILLING_START_DATE, DTM_DRILLING_FINISH_DATE,'+
'WELL_STATE_ID, WELL_CATEGORY_ID, NUM_WELL_COUNT,' +
'NUM_WELL_COUNT_IS_UNDEFINED, NUM_FACT_COST, VCH_COMMENT, NIR_STATE_ID';
AutoFillDates := false;
Sort := 'DTM_DRILLING_FINISH_DATE';
end;
function TDrillingObligationDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TDrillingObligationDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TDrillObligation;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TDrillObligation;
o.ID := ds.FieldByName('OBLIGATION_ID').AsInteger;
o.StartDate := ds.FieldByName('DTM_DRILLING_START_DATE').AsDateTime;
o.FinishDate := ds.FieldByName('DTM_DRILLING_FINISH_DATE').AsDateTime;
o.Comment := ds.FieldByName('VCH_COMMENT').AsString;
if Assigned(AllNirStates) then
o.NIRState := AllNirStates.ItemsById[ds.FieldByName('NIR_STATE_ID').AsInteger] as TNIRState
else
o.NIRState := nil;
if Assigned(AllWellStates) then
o.WellState := AllWellStates.ItemsById[ds.FieldByName('WELL_STATE_ID').AsInteger] as TState
else
o.WellState := nil;
if Assigned(AllWellCategories) then
o.WellCategory := AllWellCategories.ItemsById[ds.FieldByName('WELL_CATEGORY_ID').AsInteger] as TWellCategory
else
o.WellCategory := nil;
o.WellCount := ds.FieldByName('NUM_WELL_COUNT').AsInteger;
o.WellCountIsUndefined := ds.FieldByName('NUM_WELL_COUNT_IS_UNDEFINED').AsInteger;
o.FactCost := ds.FieldByName('NUM_FACT_COST').AsFloat;
ds.Next;
end;
end;
ds.First;
end;
end;
function TDrillingObligationDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TDrillObligation;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, TMainFacade.GetInstance.ActiveVersion.Id]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
o := AObject as TDrillObligation;
ds.FieldByName('OBLIGATION_ID').Value := o.ID;
ds.FieldByName('DTM_DRILLING_START_DATE').Value := o.StartDate;
ds.FieldByName('DTM_DRILLING_FINISH_DATE').Value := o.FinishDate;
ds.FieldByName('VCH_COMMENT').Value := o.Comment;
ds.FieldByName('VERSION_ID').Value := TMainFacade.GetInstance.ActiveVersion.Id;
ds.FieldByName('LICENSE_ID').Value := o.Owner.ID;
if Assigned(o.NIRState) then
ds.FieldByName('NIR_STATE_ID').Value := o.NIRState.ID
else
ds.FieldByName('NIR_STATE_ID').Value := null;
if Assigned(o.WellCategory) then
ds.FieldByName('WELL_CATEGORY_ID').Value := o.WellCategory.Id
else
ds.FieldByName('WELL_CATEGORY_ID').Value := null;
if Assigned(o.WellState) then
ds.FieldByName('WELL_STATE_ID').Value := o.WellState.ID
else
ds.FieldByName('WELL_STATE_ID').Value := null;
ds.FieldByName('NUM_WELL_COUNT').Value := o.WellCount;
ds.FieldByName('NUM_WELL_COUNT_IS_UNDEFINED').Value := o.WellCountIsUndefined;
ds.FieldByName('NUM_FACT_COST').Value := o.FactCost;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('OBLIGATION_ID').Value;
end;
{ TSeismicDataPoster }
constructor TSeismicObligationDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_SEISMIC_OBLIGATION_TMP';
DataDeletionString := 'TBL_SEISMIC_OBLIGATION_TMP';
DataPostString := 'TBL_SEISMIC_OBLIGATION_TMP';
KeyFieldNames := 'OBLIGATION_ID; VERSION_ID';
FieldNames := 'OBLIGATION_ID, LICENSE_ID, VERSION_ID,' +
'DTM_START_DATE, DTM_FINISH_DATE, SEISWORK_TYPE_ID,' +
'NUM_VOLUME, NUM_FACT_VOLUME, NUM_COST, VCH_COMMENT,' +
'NUM_VOLUME_IN_GRR_PROGRAM, NIR_STATE_ID';
AccessoryFieldNames := 'OBLIGATION_ID, LICENSE_ID, VERSION_ID,' +
'DTM_START_DATE, DTM_FINISH_DATE, SEISWORK_TYPE_ID,' +
'NUM_VOLUME, NUM_FACT_VOLUME, NUM_COST, VCH_COMMENT,' +
'NUM_VOLUME_IN_GRR_PROGRAM, NIR_STATE_ID';
AutoFillDates := false;
Sort := 'DTM_FINISH_DATE, DTM_START_DATE';
end;
function TSeismicObligationDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TSeismicObligationDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TSeismicObligation;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TSeismicObligation;
o.ID := ds.FieldByName('OBLIGATION_ID').AsInteger;
o.StartDate := ds.FieldByName('DTM_START_DATE').AsDateTime;
o.FinishDate := ds.FieldByName('DTM_FINISH_DATE').AsDateTime;
o.Comment := ds.FieldByName('VCH_COMMENT').AsString;
if Assigned(AllNirStates) then
o.NIRState := AllNirStates.ItemsById[ds.FieldByName('NIR_STATE_ID').AsInteger] as TNIRState
else
o.NIRState := nil;
if Assigned(AllSeismWorkTypes) then
o.SeisWorkType := AllSeismWorkTypes.ItemsById[ds.FieldByName('SEISWORK_TYPE_ID').AsInteger] as TSeismWorkType
else
o.SeisWorkType := nil;
o.Volume := ds.FieldByName('NUM_VOLUME').AsFloat;
o.VolumeInGRRProgram := ds.FieldByName('NUM_VOLUME_IN_GRR_PROGRAM').AsFloat > 0;
o.FactVolume := ds.FieldByName('NUM_FACT_VOLUME').AsFloat;
o.Cost := ds.FieldByName('NUM_COST').AsFloat;
ds.Next;
end;
end;
ds.First;
end;
end;
function TSeismicObligationDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TSeismicObligation;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, TMainFacade.GetInstance.ActiveVersion.Id]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
o := AObject as TSeismicObligation;
ds.FieldByName('OBLIGATION_ID').Value := o.ID;
ds.FieldByName('DTM_START_DATE').Value := o.StartDate;
ds.FieldByName('DTM_FINISH_DATE').Value := o.FinishDate;
ds.FieldByName('VCH_COMMENT').Value := o.Comment;
ds.FieldByName('VERSION_ID').Value := TMainFacade.GetInstance.ActiveVersion.Id;
ds.FieldByName('LICENSE_ID').Value := o.Owner.ID;
if Assigned(o.NIRState) then
ds.FieldByName('NIR_STATE_ID').Value := o.NIRState.ID
else
ds.FieldByName('NIR_STATE_ID').Value := null;
if Assigned(o.SeisWorkType) then
ds.FieldByName('SEISWORK_TYPE_ID').Value := o.SeisWorkType.ID
else
ds.FieldByName('SEISWORK_TYPE_ID').Value := null;
ds.FieldByName('NUM_VOLUME').Value := o.Volume;
ds.FieldByName('NUM_VOLUME_IN_GRR_PROGRAM').Value := Ord(o.VolumeInGRRProgram);
ds.FieldByName('NUM_FACT_VOLUME').Value := o.FactVolume;
ds.FieldByName('NUM_COST').Value := o.Cost;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('OBLIGATION_ID').Value;
end;
{ TNirObligationPlaceDataPoster }
constructor TNirObligationPlaceDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_NIR_OBLIGATION_PLACE';
DataDeletionString := 'TBL_NIR_OBLIGATION_PLACE';
DataPostString := 'TBL_NIR_OBLIGATION_PLACE';
KeyFieldNames := 'NIR_OBLIGATION_PLACE_ID';
FieldNames := 'NIR_OBLIGATION_PLACE_ID, OBLIGATION_ID, VERSION_ID, ' +
'STRUCTURE_ID' ;
AccessoryFieldNames := 'NIR_OBLIGATION_PLACE_ID, OBLIGATION_ID,' +
'VERSION_ID, STRUCTURE_ID' ;
AutoFillDates := false;
Sort := '';
end;
function TNirObligationPlaceDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TNirObligationPlaceDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TNirObligationPlace;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TNirObligationPlace;
o.ID := ds.FieldByName('NIR_OBLIGATION_PLACE_ID').AsInteger;
if Assigned(AllStructures) then
o.Structure := AllStructures.ItemsById[ds.FieldByName('STRUCTURE_ID').AsInteger] as TStructure
else
o.Structure := nil;
ds.Next;
end;
end;
ds.First;
end;
end;
function TNirObligationPlaceDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TNirObligationPlace;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TNirObligationPlace;
ds.FieldByName('NIR_OBLIGATION_PLACE_ID').Value := o.ID;
ds.FieldByName('OBLIGATION_ID').Value := o.Owner.ID;
ds.FieldByName('VERSION_ID').Value := TMainFacade.GetInstance.ActiveVersion.Id;
ds.FieldByName('STRUCTURE_ID').Value := o.Structure.ID;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('NIR_OBLIGATION_PLACE_ID').Value;
end;
{ TSeismicObligationPlaceDataPoster }
constructor TSeismicObligationPlaceDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_SEISMIC_OBLIGATION_PLACE';
DataDeletionString := 'TBL_SEISMIC_OBLIGATION_PLACE';
DataPostString := 'TBL_SEISMIC_OBLIGATION_PLACE';
KeyFieldNames := 'SEISMIC_OBLIGATION_PLACE_ID';
FieldNames := 'SEISMIC_OBLIGATION_PLACE_ID, OBLIGATION_ID,' +
'VERSION_ID, AREA_ID, STRUCTURE_ID';
AccessoryFieldNames := 'SEISMIC_OBLIGATION_PLACE_ID, OBLIGATION_ID,' +
'VERSION_ID, AREA_ID, STRUCTURE_ID';
AutoFillDates := false;
Sort := '';
end;
function TSeismicObligationPlaceDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TSeismicObligationPlaceDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TSeismicObligationPlace;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TSeismicObligationPlace;
o.ID := ds.FieldByName('SEISMIC_OBLIGATION_PLACE_ID').AsInteger;
if Assigned(AllStructures) then
o.Structure := AllStructures.ItemsById[ds.FieldByName('STRUCTURE_ID').AsInteger] as TStructure
else
o.Structure := nil;
if Assigned(AllAreas) then
o.Area := AllAreas.ItemsById[ds.FieldByName('AREA_ID').AsInteger] as TSimpleArea
else
o.Area := nil;
ds.Next;
end;
end;
ds.First;
end;
end;
function TSeismicObligationPlaceDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TSeismicObligationPlace;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TSeismicObligationPlace;
ds.FieldByName('SEISMIC_OBLIGATION_PLACE_ID').Value := o.ID;
ds.FieldByName('OBLIGATION_ID').Value := o.Owner.ID;
ds.FieldByName('VERSION_ID').Value := TMainFacade.GetInstance.ActiveVersion.Id;
ds.FieldByName('STRUCTURE_ID').Value := o.Structure.ID;
ds.FieldByName('AREA_ID').Value := o.Area.ID;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('SEISMIC_OBLIGATION_PLACE_ID').Value;
end;
{ TDrillingObligationWellDataPoster }
constructor TDrillingObligationWellDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'TBL_DRILL_OBLIGATION_WELL_TMP';
DataDeletionString := 'TBL_DRILL_OBLIGATION_WELL_TMP';
DataPostString := 'TBL_DRILL_OBLIGATION_WELL_TMP';
KeyFieldNames := 'OBLIGATION_WELL_ID';
FieldNames := 'OBLIGATION_WELL_ID, OBLIGATION_ID, WELL_UIN,' +
'VERSION_ID, NIR_STATE_ID, STRUCTURE_ID,' +
'NUM_DRILLING_RATE, NUM_FACT_COST, VCH_DRILLING_COMMENT';
AccessoryFieldNames := 'OBLIGATION_WELL_ID, OBLIGATION_ID, WELL_UIN,' +
'VERSION_ID, NIR_STATE_ID, STRUCTURE_ID,' +
'NUM_DRILLING_RATE, NUM_FACT_COST, VCH_DRILLING_COMMENT';
AutoFillDates := false;
Sort := '';
end;
function TDrillingObligationWellDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := inherited DeleteFromDB(AObject, ACollection);
end;
function TDrillingObligationWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TDrillingObligationWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TDrillingObligationWell;
o.ID := ds.FieldByName('OBLIGATION_WELL_ID').AsInteger;
if Assigned(AllStructures) then
o.Structure := AllStructures.ItemsById[ds.FieldByName('STRUCTURE_ID').AsInteger] as TStructure
else
o.Structure := nil;
if Assigned(AllWells) then
o.Well := AllWells.ItemsById[ds.FieldByName('WELL_UIN').AsInteger] as TWell
else
o.Well := nil;
if Assigned(AllNirStates) then
o.NirState := AllNirStates.ItemsById[ds.FieldByName('NIR_STATE_ID').AsInteger] as TNIRState
else
o.NirState := nil;
o.DrillingRate := ds.FieldByName('NUM_DRILLING_RATE').AsFloat;
o.FactCost := ds.FieldByName('NUM_FACT_COST').AsFloat;
o.DrillingComment := ds.FieldByName('VCH_DRILLING_COMMENT').AsString;
ds.Next;
end;
end;
ds.First;
end;
end;
function TDrillingObligationWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TDrillingObligationWell;
begin
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TDrillingObligationWell;
ds.FieldByName('OBLIGATION_WELL_ID').Value := o.ID;
ds.FieldByName('OBLIGATION_ID').Value := o.Owner.ID;
ds.FieldByName('VERSION_ID').Value := TMainFacade.GetInstance.ActiveVersion.Id;
ds.FieldByName('STRUCTURE_ID').Value := o.Structure.ID;
ds.FieldByName('WELL_UIN').Value := o.Well.ID;
ds.FieldByName('NIR_STATE_ID').Value := o.NirState.ID;
ds.FieldByName('NUM_DRILLING_RATE').Value := o.DrillingRate;
ds.FieldByName('NUM_FACT_COST').Value := o.FactCost;
ds.FieldByName('VCH_DRILLING_COMMENT').Value := o.DrillingComment;
ds.Post;
if o.ID = 0 then
o.ID := ds.FieldByName('OBLIGATION_WELL_ID').Value;
end;
{ TBaseObligationDataPoster }
constructor TBaseObligationDataPoster.Create;
begin
inherited;
KeyFieldNames := 'OBLIGATION_ID; VERSION_ID';
end;
function TBaseObligationDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
try
// находим строку соответствующую ключу
//ds.Refresh;
ds.First;
if ds.Locate(ds.KeyFieldNames, VarArrayOf([AObject.ID, TMainFacade.GetInstance.ActiveVersion.ID ]), []) then
ds.Delete
except
Result := -1;
end;
end;
end.
|
unit uBanco;
interface
uses IniFiles, SysUtils, Classes, DBXFirebird, DB, SqlExpr;
type
TdmBanco = class(TDataModule)
connDB1: TSQLConnection;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmBanco: TdmBanco;
implementation
{$R *.dfm}
procedure TdmBanco.DataModuleCreate(Sender: TObject);
var
ini:TiniFile;
database, username, password: String;
begin
try
ini := TIniFile.Create(GetCurrentDir + '\db1.config.ini');
try
connDB1.Connected := False;
if FileExists(GetCurrentDir + '\db1.config.ini') then
begin
database := ini.readString('CONFIG','database','');
username := ini.readString('CONFIG','username','');
password := ini.readString('CONFIG','password','');
connDB1.Params.Values['DataBase'] := database;
connDB1.Params.Values['User_Name']:= username;
connDB1.Params.Values['Password'] := password;
end;
finally
ini.free;
end;
except on E: Exception do
raise Exception.Create(e.Message);
end;
end;
procedure TdmBanco.DataModuleDestroy(Sender: TObject);
begin
if (dmBanco.connDB1.Connected) then
dmBanco.connDB1.Close;
end;
end.
|
unit TestuOrderProcessor;
interface
uses
TestFramework,
uOrderProcessor;
type
TestTOrderProcessor = class(TTestCase)
strict private
FOrderProcessor: TOrderProcessor;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestProcessOrder;
end;
implementation
uses
uOrder;
procedure TestTOrderProcessor.SetUp;
begin
FOrderProcessor := TOrderProcessor.Create();
end;
procedure TestTOrderProcessor.TearDown;
begin
FOrderProcessor.Free;
FOrderProcessor := nil;
end;
procedure TestTOrderProcessor.TestProcessOrder;
var
Order: TOrder;
ReturnValue: Boolean;
begin
Order := TOrder.Create();
try
ReturnValue := FOrderProcessor.ProcessOrder(Order);
Check(ReturnValue);
finally
Order.Free;
end;
end;
initialization
RegisterTest(TestTOrderProcessor.Suite);
end.
|
unit Main.View;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.TabControl, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit, FMX.Layouts, FMX.ListBox, REST.Types,
REST.Client, Data.Bind.Components, Data.Bind.ObjectScope, Game.Interfaces, System.generics.Collections;
type
TMainView = class(TForm)
TabControl1: TTabControl;
ToolBar1: TToolBar;
Label1: TLabel;
StartTab: TTabItem;
YourName: TEdit;
Label2: TLabel;
Button1: TButton;
Layout1: TLayout;
Button2: TButton;
Join: TTabItem;
Host: TTabItem;
Label3: TLabel;
Layout2: TLayout;
Button3: TButton;
GameName: TEdit;
Label4: TLabel;
MinUser: TComboBox;
Label5: TLabel;
MaxUser: TComboBox;
Label6: TLabel;
BackButton: TButton;
ListBox1: TListBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
Green: TTabItem;
Users: TListBox;
PollGames: TTimer;
PollUser: TTimer;
client: TRESTClient;
req: TRESTRequest;
resp: TRESTResponse;
Games: TListBox;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
Button4: TButton;
Turn: TTabItem;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure ListBoxItem1Click(Sender: TObject);
procedure BackButtonClick(Sender: TObject);
procedure TabControl1Change(Sender: TObject);
procedure PollGamesTimer(Sender: TObject);
procedure PollUserTimer(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure YourNameChangeTracking(Sender: TObject);
private
{ Private-Deklarationen }
fPrivateGame : boolean;
fGame : IGameData;
fUser : IUserData;
fIsJoin : boolean;
fGameList : TList<IGameData>;
fUserList : TList<IUserData>;
fGameItems : TObjectDictionary<String,TListBoxItem>;
fSlots : Array[0..9] of TListBoxItem;
Function CheckName : boolean;
Function CheckGamename : boolean;
Procedure ChangeTo(Const aTabItem : TTabItem);
Procedure RefreshGames;
Procedure RefreshUser;
procedure ClearRequest;
procedure ExecuteRequest;
procedure SyncGameList;
procedure SyncUserList;
procedure CreateGame;
Procedure JoinGameClick(Sender : TObject);
procedure AddRequestAuthentication;
procedure CreateGreen;
procedure TurnGame;
procedure StartGame(Sender : TObject);
public
{ Public-Deklarationen }
end;
var
MainView: TMainView;
implementation
Uses
System.Json
, System.Math
, System.Threading
, REST.JSON
, Game.Model
;
{$R *.fmx}
procedure TMainView.AddRequestAuthentication;
var
AuthParam: TRESTRequestParameter;
begin
AuthParam := req.Params.AddItem;
AuthParam.Kind := TRESTRequestParameterKind.pkHTTPHEADER;
AuthParam.Name := 'authentication-string';
AuthParam.Value := fUser.UserID;
end;
procedure TMainView.Button1Click(Sender: TObject);
begin
if CheckName then
begin
fIsJoin := true;
TThread.ForceQueue(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransitionAsync(Join,TTabTransition.Slide,TTabTransitionDirection.Normal,RefreshGames);
end);
end;
end;
procedure TMainView.Button2Click(Sender: TObject);
begin
if CheckName then
begin
fIsJoin := false;
TThread.ForceQueue(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransition(Host,TTabTransition.Slide,TTabTransitionDirection.Normal);
end);
end;
end;
procedure TMainView.BackButtonClick(Sender: TObject);
begin
case TabControl1.TabIndex of
1,2 : ChangeTo(StartTab);
3 : if fIsJoin
then ChangeTo(Join)
else ChangeTo(Host);
end;
end;
procedure TMainView.ChangeTo(const aTabItem: TTabItem);
var
lTabItem: TTabItem;
begin
lTabItem := aTabItem;
TThread.ForceQueue(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransition(lTabItem,TTabTransition.Slide,TTabTransitionDirection.Reversed);
end);
end;
function TMainView.CheckGamename: boolean;
begin
if (GameName.Text.Length < 3) then
begin
ShowMessage('Please Enter a Gamename');
GameName.SetFocus;
exit(false);
end;
Result := true;
end;
Function TMainView.CheckName : boolean;
begin
if (YourName.Text.Length < 3) then
begin
ShowMessage('Please Enter your Name');
YourName.SetFocus;
exit(false);
end;
Result := true;
end;
procedure TMainView.ClearRequest;
begin
req.Params.Clear;
req.Body.ClearBody;
end;
procedure TMainView.CreateGame;
begin
// Create game request data
fGame := TGameData.Create;
fGame.SessionName := GameName.Text;
fGame.MinUser := MinUser.ItemIndex + 3;
fGame.MaxUser := MaxUser.ItemIndex + 3;
fGame.LangID := 'US';
if fPrivateGame then begin
fGame.SessionPassword := 'Generate';
end else begin
fGame.SessionPassword := '';
end;
// Create game request.
ClearRequest;
req.Resource := '/games';
req.Method := TRestRequestMethod.rmPOST;
req.Body.Add(fGame.ToJSON,TRestContentType.ctAPPLICATION_JSON);
ExecuteRequest;
fGame := TJSON.JsonToObject<TGameData>(resp.Content);
// Create user data
fUser := TUserData.Create;
fUser.Name := YourName.Text;
fUser.GameID := fGame.SessionID;
// Create user request.
ClearRequest;
req.Resource := '/users';
req.Method := TRestRequestMethod.rmPOST;
req.Body.Add(fUser.ToJSON,TRestContentType.ctAPPLICATION_JSON);
ExecuteRequest;
fUser := TJSON.JsonToObject<TUserData>(resp.Content);
end;
procedure TMainView.CreateGreen;
var
LBI : TListBoxItem;
begin
Users.BeginUpdate;
try
Users.Clear;
for var i:=0 to fGame.MaxUser do
begin
LBI := TListBoxItem.Create(NIL);
LBI.Parent := Users;
LBI.Height := 49;
LBI.StyleLookup := 'istboxitemleftdetail';
LBI.ItemData.Text := '< Open Slot >';
LBI.ItemData.Detail := '';
fSlots[i] := LBI;
end;
for var i:= fGame.MaxUser to 9 do
if Assigned(fSlots[i]) then
fSlots[i].Free;
finally
Users.EndUpdate;
end;
RefreshUser;
end;
procedure TMainView.ExecuteRequest;
begin
try
req.Execute;
except
on E: Exception do begin
// Response
if resp.StatusCode <> 200 then begin
raise
Exception.Create(resp.Content);
end;
end;
end;
end;
procedure TMainView.FormCreate(Sender: TObject);
begin
TabControl1.ActiveTab := StartTab;
TabControl1.TabPosition := TTabPosition.None;
MinUser.ItemIndex := 0;
MaxUser.Itemindex := 3;
button4.Visible := false;
fGameItems := TObjectDictionary<String,TListBoxItem>.Create([DoownsValues]);
Games.Clear;
Users.Clear;
fGameList := TList<IGameData>.Create;
fUserList := TList<IUserData>.Create;
Fillchar(fSlots,Sizeof(fSlots),0);
end;
procedure TMainView.FormDeactivate(Sender: TObject);
begin
fGameItems.Free;
fGameList.Free;
fUserList.Free;
end;
procedure TMainView.JoinGameClick(Sender: TObject);
begin
TTask.Run(Procedure
begin
fUser := TUserData.Create;
fUser.Name := Yourname.Text;
fUser.GameID := (Sender as TListBoxItem).TagString;
fGame := NIL;
for var i:=0 to fGameList.Count-1 do
if fGameList[i].SessionID = fUser.GameID then
fGame := fGameList[i];
// Create user request.
ClearRequest;
req.Resource := '/users';
req.Method := TRestRequestMethod.rmPOST;
req.Body.Add(fUser.ToJSON,TRestContentType.ctAPPLICATION_JSON);
ExecuteRequest;
fUser := TJSON.JsonToObject<TUserData>(resp.Content);
TThread.Queue(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransitionAsync(Green,TTabTransition.Slide,TTabTransitionDirection.Normal,CreateGreen);
end);
end);
end;
procedure TMainView.ListBoxItem1Click(Sender: TObject);
begin
if CheckGamename then
begin
fPrivateGame := (Sender = ListBoxItem1);
Button4.Visible := true;
TThread.ForceQueue(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransitionAsync(Green,TTabTransition.Slide,TTabTransitionDirection.Normal,Procedure
begin
TTask.Run(Procedure
begin
CreateGame;
TThread.Queue(NIL,CreateGreen);
end);
end);
end);
end;
end;
procedure TMainView.PollGamesTimer(Sender: TObject);
begin
PollGames.Enabled := False;
RefreshGames;
end;
procedure TMainView.PollUserTimer(Sender: TObject);
begin
PollUser.Enabled := False;
RefreshUser;
end;
procedure TMainView.RefreshGames;
begin
Button4.Visible := true;
TTask.Run(Procedure
var
idx: nativeuint;
JSONArray: TJSONArray;
GameIdx: nativeuint;
begin
try
ClearRequest;
req.Resource := 'games';
req.Method := TRestRequestMethod.rmGET;
ExecuteRequest;
JSONArray := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(resp.content),0) as TJSONArray;
if JSONArray.Size=0 then begin
exit;
end;
fGameList.Clear;
for idx := 0 to pred(JSONArray.Count) do begin
fGameList.Add(TJSON.JsonToObject<TGameData>(JSONArray.Get(idx).ToJSON));
end;
finally
TThread.Synchronize(NIL,Procedure
begin
SyncGameList;
PollGames.Enabled := True;
Button4.Visible := false;
end);
end;
end);
end;
procedure TMainView.RefreshUser;
begin
button4.Visible := true;
TTask.Run(Procedure
var
idx : integer;
JSONArray : TJSONArray;
lUser : IUserData;
lStart : boolean;
begin
try
fUserList.Clear;
lStart := false;
ClearRequest;
req.Resource := 'users';
req.Method := TRestRequestMethod.rmGET;
AddRequestAuthentication;
ExecuteRequest;
JSONArray := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(resp.content),0) as TJSONArray;
if JSONArray.Size=0 then begin
exit;
end;
for idx := 0 to pred(JSONArray.Count) do
begin
lUser := TJSON.JsonToObject<TUserData>(JSONArray.Get(idx).ToJSON);
if (lUser.UserID = fUser.UserID) and (lUser.PlayerState <> psInGreenRoom) then
begin
lStart := true;
exit;
end;
fUserList.Add(lUser);
end;
finally
if lStart
then begin
TThread.Synchronize(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransitionAsync(Turn,TTabTransition.Slide,TTabTransitionDirection.Normal,TurnGame);
end);
end
else begin
TThread.Synchronize(NIL,Procedure
begin
SyncUserList;
button4.Visible := false;
PollUser.Enabled := True;
end);
end;
end;
end);
end;
procedure TMainView.StartGame;
begin
PollUsers.Enabled := False;
TTask.Run(Procedure
begin
fGame.GameState := TGameState.gsRunning;
// Create user request.
ClearRequest;
AddRequestAuthentication;
req.Resource := '/games';
req.Method := TRestRequestMethod.rmPUT;
req.Body.Add(fGame.ToJSON,TRestContentType.ctAPPLICATION_JSON);
ExecuteRequest;
fGame := TJSON.JsonToObject<TGameData>(resp.Content);
TThread.Synchronize(NIL,Procedure
begin
TabControl1.SetActiveTabWithTransitionAsync(Turn,TTabTransition.Slide,TTabTransitionDirection.Normal,TurnGame);
end);
end;
if fGame.GameState=TGameState.gsRunning then begin
UpdateGreenRoomPlayers;
end else begin
ShowMessage('Game did not start - Number of required users not met.');
end;
end;
procedure TMainView.SyncGameList;
var
lGame : IGameData;
lLBI : TListBoxItem;
lPair : TPair<String,TListBoxItem>;
lPairs : TArray<TPair<String,TListBoxItem>>;
begin
Games.BeginUpdate;
try
for lGame in fGameList do
begin
if fGameItems.TryGetValue(lGame.SessionID,lLBI)
then begin
lLBI.ItemData.Text := lGame.SessionName;
lLBI.ItemData.Detail := 'Users in Game : '+lGame.UserCount.ToString+' - Game Setting : '+lGame.MinUser.ToString+' / '+lGame.MaxUser.ToString;
lLBI.Tag := 1;
end
else begin
lLBI := TListBoxItem.Create(NIL);
lLBI.Parent := Games;
lLBI.Height := 49;
lLBI.StyleLookup := 'ListBoxItemBottomDetail';
lLBI.ItemData.Accessory := TListBoxItemData.TAccessory.aMore;
lLBI.Tag := 1;
lLBI.OnClick := JoinGameClick;
lLBI.TagString := lGame.SessionID;
fGameItems.TryAdd(lGame.SessionID,lLBI);
end
end;
lPairs := fGameItems.ToArray;
for lPair in lPairs do
if lPair.Value.Tag = 1
then lPair.Value.Tag := 0
else fGameItems.Remove(lPair.Key);
finally
Games.EndUpdate;
end;
end;
procedure TMainView.SyncUserList;
begin
for var i := 0 to Min(fUserList.Count-1,9) do
begin
fSlots[i].ItemData.Text := fUserList.Items[i].Name;
if fUserList.Items[i].IsCurrentUser
then begin
fSlots[i].ItemData.Detail := 'HOST';
if fUserList.Count >= fGame.MinUser then
begin
fSlots[i].ItemData.Accessory := TListBoxItemData.TAccessory.aMore;
fSlots[i].OnClick := StartGame;
end;
end
else begin
fSlots[i].ItemData.Detail := '';
fSlots[i].ItemData.Accessory := TListBoxItemData.TAccessory.aNone;
fSlots[i].OnClick := NIL;
end;
end;
end;
procedure TMainView.TabControl1Change(Sender: TObject);
Procedure NoPoll;
begin
PollGames.Enabled := false;
PollUser.Enabled := false;
end;
begin
BackButton.Visible := true;
case TabControl1.TabIndex of
0 : begin
BackButton.Visible := false;
NoPoll;
end;
2,
4 : NoPoll;
end; // of case
end;
procedure TMainView.TurnGame;
begin
//
end;
procedure TMainView.YourNameChangeTracking(Sender: TObject);
begin
GameName.Text := YourName.Text.Trim + '''s Game';
end;
end.
|
unit ULocalBackupXml;
interface
uses UChangeInfo, UXmlUtil, xmldom, XMLIntf, msxmldom, XMLDoc, SysUtils, UMyUtil;
type
{$Region ' 源路径 修改 ' }
// 修改 父类
TLocalBackupSourceChangeXml = class( TChangeInfo )
public
FullPath : string;
protected
SourcePathNode : IXMLNode;
public
constructor Create( _FullPath : string );
protected
function FindSourcePathNode : Boolean;
end;
// 添加
TLocalBackupSourceAddXml = class( TLocalBackupSourceChangeXml )
private
PathType : string;
IsBackupNow, IsDisable : Boolean;
public
IsAutoSync : Boolean;
SyncTimeType, SyncTimeValue : Integer;
LastSyncTime : TDateTime;
public
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
private
FileCount : Integer;
FileSize : Int64;
public
procedure SetPathType( _PathType : string );
procedure SetBackupInfo( _IsBackupNow, _IsDisable : Boolean );
procedure SetAutoSyncInfo( _IsAutoSync : Boolean; _LastSyncTime : TDateTime );
procedure SetSyncInternalInfo( _SyncTimeType, _SyncTimeValue : Integer );
procedure SetDeleteInfo( _IsKeepDeleted : Boolean; _KeepEditionCount : Integer );
procedure SetSpaceInfo( _FileCount : Integer; _FileSize : Int64 );
procedure Update;override;
end;
// 修改 空间信息
TLocalBackupSourceSpaceXml = class( TLocalBackupSourceChangeXml )
private
FileSize : Int64;
FileCount : Integer;
public
procedure SetSpaceInfo( _FileSize : Int64; _FileCount : Integer );
procedure Update;override;
end;
{$Region ' 设置 状态信息 ' }
// 是否 禁止备份
TLocalBackupSourceIsDisableXml = class( TLocalBackupSourceChangeXml )
public
IsDisable : Boolean;
public
procedure SetIsDisable( _IsDisable : Boolean );
procedure Update;override;
end;
// 是否 Backup Now 备份
TLocalBackupSourceIsBackupNowXml = class( TLocalBackupSourceChangeXml )
public
IsBackupNow : Boolean;
public
procedure SetIsBackupNow( _IsBackupNow : Boolean );
procedure Update;override;
end;
{$EndRegion}
{$Region ' 修改 同步时间 信息 ' }
// 设置 上一次 同步时间
TLocalBackupSourceSetLastSyncTimeXml = class( TLocalBackupSourceChangeXml )
private
LastSyncTime : TDateTime;
public
procedure SetLastSyncTime( _LastSyncTime : TDateTime );
procedure Update;override;
end;
// 设置 上一次 同步时间
TLocalBackupSourceSetSyncMinsXml = class( TLocalBackupSourceChangeXml )
private
IsAutoSync : Boolean;
SyncTimeType, SyncTimeValue : Integer;
public
procedure SetIsAutoSync( _IsAutoSync : Boolean );
procedure SetSyncInterval( _SyncTimeType, _SyncTimeValue : Integer );
procedure Update;override;
end;
{$EndRegion}
{$Region ' 设置保存删除文件信息 ' }
// 设置信息
TLocalBackupSorceSetDeleteXml = class( TLocalBackupSourceChangeXml )
public
IsKeepDeleted : Boolean;
KeepEditionCount : Integer;
public
procedure SetDeleteInfo( _IsKeepDeleted : Boolean; _KeepEditionCount : Integer );
procedure Update;override;
end;
{$EndRegion}
// 删除
TLocalBackupSourceRemoveXml = class( TLocalBackupSourceChangeXml )
public
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 过滤器 修改 ' }
{$Region ' 包含 过滤器 ' }
// 父类
TLocalBackupSourceIncludeFilterChangeXml = class( TLocalBackupSourceChangeXml )
protected
IncludeFilterListNode : IXMLNode;
protected
function FindIncludeFilterListNode : Boolean;
end;
// 清空
TLocalBackupSourceIncludeFilterClearXml = class( TLocalBackupSourceIncludeFilterChangeXml )
public
procedure Update;override;
end;
// 添加
TLocalBackupSourceIncludeFilterAddXml = class( TLocalBackupSourceIncludeFilterChangeXml )
public
FilterType, FilterStr : string;
public
procedure SetFilterInfo( _FilterType, _FilterStr : string );
procedure Update;override;
end;
{$EndRegion}
{$Region ' 排除 过滤器 ' }
// 父类
TLocalBackupSourceExcludeFilterChangeXml = class( TLocalBackupSourceChangeXml )
protected
ExcludeFilterListNode : IXMLNode;
protected
function FindExcludeFilterListNode : Boolean;
end;
// 清空
TLocalBackupSourceExcludeFilterClearXml = class( TLocalBackupSourceExcludeFilterChangeXml )
public
procedure Update;override;
end;
// 添加
TLocalBackupSourceExcludeFilterAddXml = class( TLocalBackupSourceExcludeFilterChangeXml )
public
FilterType, FilterStr : string;
public
procedure SetFilterInfo( _FilterType, _FilterStr : string );
procedure Update;override;
end;
{$EndRegion}
{$EndRegion}
{$Region ' 源路径目标 修改 ' }
// 父类
TLocalBackupSourceChangeDesXml = class( TLocalBackupSourceChangeXml )
public
DesPathListNode : IXMLNode;
public
function FindDesPathListNode : Boolean;
end;
// 修改
TLocalBackupSourceWriteDesXml = class( TLocalBackupSourceChangeDesXml )
public
DesPath : string;
protected
DesPathNode : IXMLNode;
public
procedure SetDesPath( _DesPath : string );
protected
function FindDesPathNode : Boolean;
end;
// 添加
TLocalBackupSourceAddDesXml = class( TLocalBackupSourceWriteDesXml )
public
SourceSize, CompltedSize : Int64;
DeletedSpace : Int64;
public
procedure SetSpaceInfo( _SourceSize, _CompletedSize : Int64 );
procedure SetDeletedSpace( _DeletedSpace : Int64 );
procedure Update;override;
end;
// 添加 已完成空间信息
TLocalBackupSourceAddDesCompletedSpaceXml = class( TLocalBackupSourceWriteDesXml )
public
AddCompltedSize : Int64;
public
procedure SetAddCompltedSize( _AddCompltedSize : Int64 );
procedure Update;override;
end;
// 修改 空间信息
TLocalBackupSourceSetDesSpaceXml = class( TLocalBackupSourceWriteDesXml )
public
SourceSize, CompltedSize : Int64;
public
procedure SetSpaceInfo( _SourceSize, _CompletedSize : Int64 );
procedure Update;override;
end;
// 添加 已删除 空间信息
TLocalBackupSorceAddDeletedSpaceXml = class( TLocalBackupSourceWriteDesXml )
public
AddDeletedSpace : Int64;
public
procedure SetAddDeletedSpace( _AddDeletedSpace : Int64 );
procedure Update;override;
end;
// 设置 已删除 空间信息
TLocalBackupSorceSetDeletedSpaceXml = class( TLocalBackupSourceWriteDesXml )
public
DeletedSpace : Int64;
public
procedure SetDeletedSpace( _DeletedSpace : Int64 );
procedure Update;override;
end;
// 删除
TLocalBackupSourceRemoveDesXml = class( TLocalBackupSourceWriteDesXml )
public
procedure Update;override;
end;
// 版本兼容
TLocalBackupSourceIsAddDesToSourceXml = class( TChangeInfo )
public
procedure Update;override;
end;
{$EndRegion}
{$Region ' 源路径 读取 ' }
// 读取 源路径目标
TLocalBackupSourceReadDesXmlHandle = class
public
DesPathNode : IXMLNode;
SourcePath, PathType : string;
IsKeepDeleted : Boolean;
public
constructor Create( _DesPathNode : IXMLNode );
procedure SetSourcePath( _SourcePath, _PathType : string );
procedure SetIsKeepDeleted( _IsKeepDeleted : Boolean );
procedure Update;
end;
// 读 备份路径 过滤 Xml
TLocalBackupSourceFilterXmlReadHandle = class
public
FilterNode : IXMLNode;
FullPath : string;
protected
FilterType, FilterStr : string;
public
constructor Create( _FilterNode : IXMLNode );
procedure SetFullPath( _FullPath : string );
procedure Update;
protected
procedure AddFilterHandle;virtual;abstract;
end;
// 读 备份路径 包含过滤 Xml
TLocalBackupSourceIncludeFilterXmlReadHandle = class( TLocalBackupSourceFilterXmlReadHandle )
protected
procedure AddFilterHandle;override;
end;
// 读 备份路径 排除过滤 Xml
TLocalBackupSourceExcludeFilterXmlReadHandle = class( TLocalBackupSourceFilterXmlReadHandle )
protected
procedure AddFilterHandle;override;
end;
// 读取 源路径
TLocalBackupSorceReadXmlHandle = class
public
SourcePathNode : IXMLNode;
FullPath, PathType : string;
public
IsKeepDeleted : Boolean;
private
IsAddEditionDes : Boolean;
public
constructor Create( _SourcePathNode : IXMLNode );
procedure SetIsAddEditionDes( _IsAddEditionDes : Boolean );
procedure Update;
private
procedure ReadSourceFilter;
procedure ReadDesPathList;
procedure AddEditionDesPathList;
end;
// 读取 信息
TLocalBackupSourceXmlRead = class
public
procedure Update;
end;
{$EndRegion}
{$Region ' 目标路径 修改 ' }
// 修改 父类
TLocalBackupDesChangeXml = class( TChangeInfo )
public
FullPath : string;
protected
BackupDesNode : IXMLNode;
public
constructor Create( _FullPath : string );
protected
function FindBackupDesNode : Boolean;
end;
// 添加 目标路径
TLocalBackupDesAddXml = class( TLocalBackupDesChangeXml )
public
procedure Update;override;
end;
// 删除 目标路径
TLocalBackupDesRemoveXml = class( TLocalBackupDesChangeXml )
public
procedure Update;override;
end;
// 禁止 添加 默认路径
TLocalBackupDesDisableDefaultPathXml = class( TChangeInfo )
public
procedure Update;override;
end;
{$EndRegion}
{$Region ' 目标路径 读取 ' }
//目标路径 读取
TLocalBackupDesXmlReadHandle = class
public
DesPathNode : IXMLNode;
public
constructor Create( _DesPathNode : IXMLNode );
procedure Update;
end;
// 读取
TLocalBackupDesXmlRead = class
public
procedure Update;
private
procedure AddMyDesPathList;
procedure AddDefaultDesPath;
end;
{$EndRegion}
const // Xml 信息
Xml_IsAddSourceToDes = 'iastd';
Xml_IsAddDesToSource = 'iadts';
// 源信息
Xml_FullPath = 'fp';
Xml_PathType = 'pt';
Xml_IsBackupNow = 'ib';
Xml_IsDisable = 'id';
Xml_IsAuctoSync = 'ias';
Xml_LastSyncTime = 'lst';
Xml_SyncTimeType = 'stt';
Xml_SyncTimeValue = 'stv';
Xml_IsKeepDeleted = 'ikd';
Xml_KeepEdtionCount = 'kec';
Xml_FileSize = 'fs';
Xml_FileCount = 'fc';
Xml_DesPathList = 'dpl';
Xml_IncludeFilterList = 'ifl';
Xml_ExcludeFilterList = 'efl';
// 过滤器 信息
Xml_FilterType = 'ft';
XMl_FilterStr = 'fs';
// 源路径目标
// Xml_FullPath = 'fp';
Xml_SourceSize = 'ss';
Xml_CompltedSize = 'cs';
Xml_DeletedSpace = 'ds';
// 目标信息
Xml_IsAddDefault = 'iad';
implementation
uses ULocalBackupInfo, ULocalBackupControl;
{ TLocalBackupSourceChangeXml }
constructor TLocalBackupSourceChangeXml.Create(_FullPath: string);
begin
FullPath := _FullPath;
end;
function TLocalBackupSourceChangeXml.FindSourcePathNode: Boolean;
begin
SourcePathNode := MyXmlUtil.FindListChild( LocalBackupSourceListXml, FullPath );
Result := SourcePathNode <> nil;
end;
{ TLocalBackupSourceAddXml }
procedure TLocalBackupSourceAddXml.SetAutoSyncInfo(_IsAutoSync: Boolean;
_LastSyncTime: TDateTime);
begin
IsAutoSync := _IsAutoSync;
LastSyncTime := _LastSyncTime;
end;
procedure TLocalBackupSourceAddXml.SetBackupInfo(_IsBackupNow,
_IsDisable: Boolean);
begin
IsBackupNow := _IsBackupNow;
IsDisable := _IsDisable;
end;
procedure TLocalBackupSourceAddXml.SetDeleteInfo(_IsKeepDeleted: Boolean;
_KeepEditionCount: Integer);
begin
IsKeepDeleted := _IsKeepDeleted;
KeepEditionCount := _KeepEditionCount;
end;
procedure TLocalBackupSourceAddXml.SetPathType(_PathType: string);
begin
PathType := _PathType;
end;
procedure TLocalBackupSourceAddXml.SetSpaceInfo(_FileCount: Integer;
_FileSize: Int64);
begin
FileCount := _FileCount;
FileSize := _FileSize;
end;
procedure TLocalBackupSourceAddXml.SetSyncInternalInfo(_SyncTimeType,
_SyncTimeValue: Integer);
begin
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
procedure TLocalBackupSourceAddXml.Update;
begin
// 已存在
if FindSourcePathNode then
Exit;
// 添加
SourcePathNode := MyXmlUtil.AddListChild( LocalBackupSourceListXml, FullPath );
MyXmlUtil.AddChild( SourcePathNode, Xml_FullPath, FullPath );
MyXmlUtil.AddChild( SourcePathNode, Xml_PathType, PathType );
MyXmlUtil.AddChild( SourcePathNode, Xml_IsBackupNow, IsBackupNow );
MyXmlUtil.AddChild( SourcePathNode, Xml_IsDisable, IsDisable );
MyXmlUtil.AddChild( SourcePathNode, Xml_IsAuctoSync, IsAutoSync );
MyXmlUtil.AddChild( SourcePathNode, Xml_LastSyncTime, LastSyncTime );
MyXmlUtil.AddChild( SourcePathNode, Xml_SyncTimeType, SyncTimeType );
MyXmlUtil.AddChild( SourcePathNode, Xml_SyncTimeValue, SyncTimeValue );
MyXmlUtil.AddChild( SourcePathNode, Xml_IsKeepDeleted, IsKeepDeleted );
MyXmlUtil.AddChild( SourcePathNode, Xml_KeepEdtionCount, KeepEditionCount );
MyXmlUtil.AddChild( SourcePathNode, Xml_FileSize, FileSize );
MyXmlUtil.AddChild( SourcePathNode, Xml_FileCount, FileCount );
end;
{ TLocalBackupSourceRemoveXml }
procedure TLocalBackupSourceRemoveXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.DeleteListChild( LocalBackupSourceListXml, FullPath );
end;
{ TLocalBackupSourceSpaceXml }
procedure TLocalBackupSourceSpaceXml.SetSpaceInfo(_FileSize: Int64;
_FileCount: Integer);
begin
FileSize := _FileSize;
FileCount := _FileCount;
end;
procedure TLocalBackupSourceSpaceXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.AddChild( SourcePathNode, Xml_FileSize, IntToStr( FileSize ) );
MyXmlUtil.AddChild( SourcePathNode, Xml_FileCount, IntToStr( FileCount ) );
end;
{ TLocalBackupSourceXmlRead }
procedure TLocalBackupSourceXmlRead.Update;
var
IsAddDesToSource : Boolean;
i : Integer;
Node : IXMLNode;
LocalBackupSorceReadXmlHandle : TLocalBackupSorceReadXmlHandle;
LocalBackupSourceIsAddDesToSourceXml : TLocalBackupSourceIsAddDesToSourceXml;
begin
IsAddDesToSource := StrToBoolDef( MyXmlUtil.GetChildValue( MyLocalBackupSourceXml, Xml_IsAddDesToSource ), true);
// 读取 源路径
for i := 0 to LocalBackupSourceListXml.ChildNodes.Count - 1 do
begin
Node := LocalBackupSourceListXml.ChildNodes[i];
LocalBackupSorceReadXmlHandle := TLocalBackupSorceReadXmlHandle.Create( Node );
LocalBackupSorceReadXmlHandle.SetIsAddEditionDes( IsAddDesToSource );
LocalBackupSorceReadXmlHandle.Update;
LocalBackupSorceReadXmlHandle.Free;
end;
// 已经版本兼容,跳过
if not IsAddDesToSource then
Exit;
// 版本兼容
LocalBackupSourceIsAddDesToSourceXml := TLocalBackupSourceIsAddDesToSourceXml.Create;
MyXmlChange.AddChange( LocalBackupSourceIsAddDesToSourceXml );
end;
{ TMyDesPathChangeXml }
constructor TLocalBackupDesChangeXml.Create(_FullPath: string);
begin
FullPath := _FullPath;
end;
{ TMyDesPathAddXml }
procedure TLocalBackupDesAddXml.Update;
begin
// 已存在
if FindBackupDesNode then
Exit;
BackupDesNode := MyXmlUtil.AddListChild( DestinationListXml, FullPath );
MyXmlUtil.AddChild( BackupDesNode, Xml_FullPath, FullPath );
end;
{ TMyDesPathRemoveXml }
procedure TLocalBackupDesRemoveXml.Update;
begin
// 不存在
if not FindBackupDesNode then
Exit;
MyXmlUtil.DeleteListChild( DestinationListXml, FullPath );
end;
{ TMyDestinationXmlRead }
procedure TLocalBackupDesXmlRead.AddDefaultDesPath;
var
IsAddDefault : Boolean;
DesPath : string;
BackupDestinationReadHandle : TLocalBackupDesReadHandle;
MyDesDisableDefaultPathXml : TLocalBackupDesDisableDefaultPathXml;
begin
IsAddDefault := StrToBoolDef( MyXmlUtil.GetChildValue( MyDestinationXml, Xml_IsAddDefault ), True );
if not IsAddDefault then
Exit;
DesPath := MyHardDisk.getBiggestHardDIsk + DefaultPath_Des;
ForceDirectories( DesPath );
// 添加 默认的 本地 备份目标路径
BackupDestinationReadHandle := TLocalBackupDesReadHandle.Create( DesPath );
BackupDestinationReadHandle.Update;
BackupDestinationReadHandle.Free;
// 禁止下一次添加
MyDesDisableDefaultPathXml := TLocalBackupDesDisableDefaultPathXml.Create;
MyXmlChange.AddChange( MyDesDisableDefaultPathXml );
end;
procedure TLocalBackupDesXmlRead.AddMyDesPathList;
var
i : Integer;
DesNode : IXMLNode;
LocalBackupDesXmlReadHandle : TLocalBackupDesXmlReadHandle;
begin
for i := 0 to DestinationListXml.ChildNodes.Count - 1 do
begin
DesNode := DestinationListXml.ChildNodes[i];
LocalBackupDesXmlReadHandle := TLocalBackupDesXmlReadHandle.Create( DesNode );
LocalBackupDesXmlReadHandle.Update;
LocalBackupDesXmlReadHandle.Free;
end;
end;
procedure TLocalBackupDesXmlRead.Update;
begin
// 添加默认路径
if DestinationListXml.ChildNodes.Count = 0 then
AddDefaultDesPath
else // 添加 本地备份目标路径
AddMyDesPathList;
end;
function TLocalBackupDesChangeXml.FindBackupDesNode: Boolean;
begin
BackupDesNode := MyXmlUtil.FindListChild( DestinationListXml, FullPath );
Result := BackupDesNode <> nil;
end;
{ TMyDesDisableDefaultPathXml }
procedure TLocalBackupDesDisableDefaultPathXml.Update;
begin
MyXmlUtil.AddChild( MyDestinationXml, Xml_IsAddDefault, BoolToStr( False ) );
end;
{ TLocalBackupSourceChangeDesXml }
function TLocalBackupSourceChangeDesXml.FindDesPathListNode: Boolean;
begin
Result := FindSourcePathNode;
if Result then
DesPathListNode := MyXmlUtil.AddChild( SourcePathNode, Xml_DesPathList );
end;
{ TLocalBackupSourceWriteDesXml }
function TLocalBackupSourceWriteDesXml.FindDesPathNode: Boolean;
begin
Result := False;
DesPathListNode := nil;
if not FindDesPathListNode then
Exit;
DesPathNode := MyXmlUtil.FindListChild( DesPathListNode, DesPath );
Result := DesPathNode <> nil;
end;
procedure TLocalBackupSourceWriteDesXml.SetDesPath(_DesPath: string);
begin
DesPath := _DesPath;
end;
{ TLocalBackupSourceAddDesXml }
procedure TLocalBackupSourceAddDesXml.SetDeletedSpace(_DeletedSpace: Int64);
begin
DeletedSpace := _DeletedSpace;
end;
procedure TLocalBackupSourceAddDesXml.SetSpaceInfo(_SourceSize,
_CompletedSize: Int64);
begin
SourceSize := _SourceSize;
CompltedSize := _CompletedSize;
end;
procedure TLocalBackupSourceAddDesXml.Update;
begin
inherited;
// 已存在
if FindDesPathNode then
Exit;
// 源不存在
if DesPathListNode = nil then
Exit;
// 添加
DesPathNode := MyXmlUtil.AddListChild( DesPathListNode, DesPath );
MyXmlUtil.AddChild( DesPathNode, Xml_FullPath, DesPath );
MyXmlUtil.AddChild( DesPathNode, Xml_SourceSize, SourceSize );
MyXmlUtil.AddChild( DesPathNode, Xml_CompltedSize, CompltedSize );
MyXmlUtil.AddChild( DesPathNode, Xml_DeletedSpace, DeletedSpace );
end;
{ TLocalBackupSourceRemoveDesXml }
procedure TLocalBackupSourceRemoveDesXml.Update;
begin
inherited;
// 不存在
if not FindDesPathNode then
Exit;
// 删除
MyXmlUtil.DeleteListChild( DesPathListNode, DesPath );
end;
{ TLocalBackupSourceSetDesSpaceXml }
procedure TLocalBackupSourceSetDesSpaceXml.SetSpaceInfo(_SourceSize,
_CompletedSize: Int64);
begin
SourceSize := _SourceSize;
CompltedSize := _CompletedSize;
end;
procedure TLocalBackupSourceSetDesSpaceXml.Update;
begin
inherited;
// 不存在
if not FindDesPathNode then
Exit;
// 修改 空间信息
MyXmlUtil.AddChild( DesPathNode, Xml_SourceSize, SourceSize );
MyXmlUtil.AddChild( DesPathNode, Xml_CompltedSize, CompltedSize );
end;
{ TLocalBackupSourceAddDesCompletedSpaceXml }
procedure TLocalBackupSourceAddDesCompletedSpaceXml.SetAddCompltedSize(
_AddCompltedSize: Int64);
begin
AddCompltedSize := _AddCompltedSize;
end;
procedure TLocalBackupSourceAddDesCompletedSpaceXml.Update;
var
NewCompltedSpace : Int64;
begin
inherited;
// 不存在
if not FindDesPathNode then
Exit;
NewCompltedSpace := MyXmlUtil.GetChildInt64Value( DesPathNode, Xml_CompltedSize );
NewCompltedSpace := NewCompltedSpace + AddCompltedSize;
// 修改 空间信息
MyXmlUtil.AddChild( DesPathNode, Xml_CompltedSize, NewCompltedSpace );
end;
{ TLocalBackupSorceReadXmlHandle }
procedure TLocalBackupSorceReadXmlHandle.AddEditionDesPathList;
var
i : Integer;
DesNode : IXMLNode;
DesPath : string;
LocalBackupSourceAddDesHandle : TLocalBackupSourceAddDesHandle;
begin
for i := 0 to DestinationListXml.ChildNodes.Count - 1 do
begin
DesNode := DestinationListXml.ChildNodes[i];
DesPath := MyXmlUtil.GetChildValue( DesNode, Xml_FullPath );
// 显示信息
LocalBackupSourceAddDesHandle := TLocalBackupSourceAddDesHandle.Create( FullPath );
LocalBackupSourceAddDesHandle.SetDesPath( DesPath );
LocalBackupSourceAddDesHandle.SetSourcePathType( PathType );
LocalBackupSourceAddDesHandle.SetDeletedInfo( False, 0 );
LocalBackupSourceAddDesHandle.SetSpaceInfo( 0, 0 );
LocalBackupSourceAddDesHandle.Update;
LocalBackupSourceAddDesHandle.Free;
end;
end;
constructor TLocalBackupSorceReadXmlHandle.Create(_SourcePathNode: IXMLNode);
begin
SourcePathNode := _SourcePathNode;
end;
procedure TLocalBackupSorceReadXmlHandle.ReadDesPathList;
var
DesPathListNode : IXMLNode;
i : Integer;
DesPathNode : IXMLNode;
LocalBackupSourceReadDesXmlHandle : TLocalBackupSourceReadDesXmlHandle;
begin
DesPathListNode := MyXmlUtil.AddChild( SourcePathNode, Xml_DesPathList );
for i := 0 to DesPathListNode.ChildNodes.Count - 1 do
begin
DesPathNode := DesPathListNode.ChildNodes[i];
LocalBackupSourceReadDesXmlHandle := TLocalBackupSourceReadDesXmlHandle.Create( DesPathNode );
LocalBackupSourceReadDesXmlHandle.SetSourcePath( FullPath, PathType );
LocalBackupSourceReadDesXmlHandle.SetIsKeepDeleted( IsKeepDeleted );
LocalBackupSourceReadDesXmlHandle.Update;
LocalBackupSourceReadDesXmlHandle.Free;
end;
end;
procedure TLocalBackupSorceReadXmlHandle.ReadSourceFilter;
var
FilterListNode : IXMLNode;
i : Integer;
FilterNode : IXMLNode;
LocalBackupSourceFilterXmlReadHandle : TLocalBackupSourceFilterXmlReadHandle;
begin
FilterListNode := MyXmlUtil.AddChild( SourcePathNode, Xml_IncludeFilterList );
for i := 0 to FilterListNode.ChildNodes.Count - 1 do
begin
FilterNode := FilterListNode.ChildNodes[i];
LocalBackupSourceFilterXmlReadHandle := TLocalBackupSourceIncludeFilterXmlReadHandle.Create( FilterNode );
LocalBackupSourceFilterXmlReadHandle.SetFullPath( FullPath );
LocalBackupSourceFilterXmlReadHandle.Update;
LocalBackupSourceFilterXmlReadHandle.Free;
end;
FilterListNode := MyXmlUtil.AddChild( SourcePathNode, Xml_ExcludeFilterList );
for i := 0 to FilterListNode.ChildNodes.Count - 1 do
begin
FilterNode := FilterListNode.ChildNodes[i];
LocalBackupSourceFilterXmlReadHandle := TLocalBackupSourceExcludeFilterXmlReadHandle.Create( FilterNode );
LocalBackupSourceFilterXmlReadHandle.SetFullPath( FullPath );
LocalBackupSourceFilterXmlReadHandle.Update;
LocalBackupSourceFilterXmlReadHandle.Free;
end;
end;
procedure TLocalBackupSorceReadXmlHandle.SetIsAddEditionDes(
_IsAddEditionDes: Boolean);
begin
IsAddEditionDes := _IsAddEditionDes;
end;
procedure TLocalBackupSorceReadXmlHandle.Update;
var
IsBackupNow, IsDisable : Boolean;
IsAutoSync : Boolean;
SyncTimeType, SyncTimeValue : Integer;
LastSyncTime : TDateTime;
KeepEditionCount : Integer;
FileSize : Int64;
FileCount : Integer;
LocalBackupSourceReadHandle : TLocalBackupSourceReadHandle;
begin
// 提取 节点信息
FullPath := MyXmlUtil.GetChildValue( SourcePathNode, Xml_FullPath );
PathType := MyXmlUtil.GetChildValue( SourcePathNode, Xml_PathType );
IsBackupNow := StrToBoolDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_IsBackupNow ), True );
IsDisable := StrToBoolDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_IsDisable ), False );
IsAutoSync := StrToBoolDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_IsAuctoSync ), True );
SyncTimeType := StrToIntDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_SyncTimeType ), TimeType_Minutes );
SyncTimeValue := StrToIntDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_SyncTimeValue ), 60 );
LastSyncTime := StrToFloatDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_LastSyncTime ), 0 );
IsKeepDeleted := StrToBoolDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_IsKeepDeleted ), False );
KeepEditionCount := StrToIntDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_KeepEdtionCount ), 3 );
FileSize := StrToInt64Def( MyXmlUtil.GetChildValue( SourcePathNode, Xml_FileSize ), 0 );
FileCount := StrToIntDef( MyXmlUtil.GetChildValue( SourcePathNode, Xml_FileCount ), 0 );
// 读取 路径信息
LocalBackupSourceReadHandle := TLocalBackupSourceReadHandle.Create( FullPath );
LocalBackupSourceReadHandle.SetPathType( PathType );
LocalBackupSourceReadHandle.SetBackupInfo( IsBackupNow, IsDisable );
LocalBackupSourceReadHandle.SetAutoSyncInfo( IsAutoSync, LastSyncTime );
LocalBackupSourceReadHandle.SetSyncInternalInfo( SyncTimeType, SyncTimeValue );
LocalBackupSourceReadHandle.SetDeleteInfo( IsKeepDeleted, KeepEditionCount );
LocalBackupSourceReadHandle.SetSpaceInfo( FileCount, FileSize );
LocalBackupSourceReadHandle.Update;
LocalBackupSourceReadHandle.Free;
// 读取 过滤器信息
ReadSourceFilter;
// 读取 目标路径
if IsAddEditionDes then
AddEditionDesPathList // 版本兼容
else
ReadDesPathList;
end;
{ TLocalBackupSourceReadDesXmlHandle }
constructor TLocalBackupSourceReadDesXmlHandle.Create(_DesPathNode: IXMLNode);
begin
DesPathNode := _DesPathNode;
end;
procedure TLocalBackupSourceReadDesXmlHandle.SetIsKeepDeleted(
_IsKeepDeleted: Boolean);
begin
IsKeepDeleted := _IsKeepDeleted;
end;
procedure TLocalBackupSourceReadDesXmlHandle.SetSourcePath(_SourcePath, _PathType: string);
begin
SourcePath := _SourcePath;
PathType := _PathType;
end;
procedure TLocalBackupSourceReadDesXmlHandle.Update;
var
DesPath : string;
SourceSize, CompltedSize : Int64;
DeletedSpace : Int64;
LocalBackupSourceReadDesHandle : TLocalBackupSourceReadDesHandle;
begin
// 提取信息
DesPath := MyXmlUtil.GetChildValue( DesPathNode, Xml_FullPath );
SourceSize := MyXmlUtil.GetChildInt64Value( DesPathNode, Xml_SourceSize );
CompltedSize := MyXmlUtil.GetChildInt64Value( DesPathNode, Xml_CompltedSize );
DeletedSpace := MyXmlUtil.GetChildInt64Value( DesPathNode, Xml_DeletedSpace );
// 显示信息
LocalBackupSourceReadDesHandle := TLocalBackupSourceReadDesHandle.Create( SourcePath );
LocalBackupSourceReadDesHandle.SetDesPath( DesPath );
LocalBackupSourceReadDesHandle.SetSourcePathType( PathType );
LocalBackupSourceReadDesHandle.SetSpaceInfo( SourceSize, CompltedSize );
LocalBackupSourceReadDesHandle.SetDeletedInfo( IsKeepDeleted, DeletedSpace );
LocalBackupSourceReadDesHandle.Update;
LocalBackupSourceReadDesHandle.Free;
end;
{ TLocalBackupDesXmlReadHandle }
constructor TLocalBackupDesXmlReadHandle.Create(_DesPathNode: IXMLNode);
begin
DesPathNode := _DesPathNode;
end;
procedure TLocalBackupDesXmlReadHandle.Update;
var
DesPath : string;
BackupDestinationReadHandle : TLocalBackupDesReadHandle;
begin
// 提取信息
DesPath := MyXmlUtil.GetChildValue( DesPathNode, Xml_FullPath );
// 本地 备份目标路径
BackupDestinationReadHandle := TLocalBackupDesReadHandle.Create( DesPath );
BackupDestinationReadHandle.Update;
BackupDestinationReadHandle.Free;
end;
{ TLocalBackupSourceIncludeFilterChangeXml }
function TLocalBackupSourceIncludeFilterChangeXml.FindIncludeFilterListNode: Boolean;
begin
Result := FindSourcePathNode;
if Result then
IncludeFilterListNode := MyXmlUtil.AddChild( SourcePathNode, Xml_IncludeFilterList );
end;
{ TLocalBackupSourceIncludeFilterClearXml }
procedure TLocalBackupSourceIncludeFilterClearXml.Update;
begin
inherited;
if not FindIncludeFilterListNode then
Exit;
IncludeFilterListNode.ChildNodes.Clear;
end;
{ TLocalBackupSourceIncludeFilterAddXml }
procedure TLocalBackupSourceIncludeFilterAddXml.SetFilterInfo(_FilterType,
_FilterStr: string);
begin
FilterType := _FilterType;
FilterStr := _FilterStr;
end;
procedure TLocalBackupSourceIncludeFilterAddXml.Update;
var
IncludeFilterNode : IXMLNode;
begin
inherited;
// 不存在
if not FindIncludeFilterListNode then
Exit;
IncludeFilterNode := MyXmlUtil.AddListChild( IncludeFilterListNode );
MyXmlUtil.AddChild( IncludeFilterNode, Xml_FilterType, FilterType );
MyXmlUtil.AddChild( IncludeFilterNode, Xml_FilterStr, FilterStr );
end;
{ TLocalBackupSourceExcludeFilterChangeXml }
function TLocalBackupSourceExcludeFilterChangeXml.FindExcludeFilterListNode: Boolean;
begin
Result := FindSourcePathNode;
if Result then
ExcludeFilterListNode := MyXmlUtil.AddChild( SourcePathNode, Xml_ExcludeFilterList );
end;
{ TLocalBackupSourceExcludeFilterClearXml }
procedure TLocalBackupSourceExcludeFilterClearXml.Update;
begin
inherited;
if not FindExcludeFilterListNode then
Exit;
ExcludeFilterListNode.ChildNodes.Clear;
end;
{ TLocalBackupSourceExcludeFilterAddXml }
procedure TLocalBackupSourceExcludeFilterAddXml.SetFilterInfo(_FilterType,
_FilterStr: string);
begin
FilterType := _FilterType;
FilterStr := _FilterStr;
end;
procedure TLocalBackupSourceExcludeFilterAddXml.Update;
var
ExcludeFilterNode : IXMLNode;
begin
inherited;
// 不存在
if not FindExcludeFilterListNode then
Exit;
ExcludeFilterNode := MyXmlUtil.AddListChild( ExcludeFilterListNode );
MyXmlUtil.AddChild( ExcludeFilterNode, Xml_FilterType, FilterType );
MyXmlUtil.AddChild( ExcludeFilterNode, Xml_FilterStr, FilterStr );
end;
{ TLocalBackupSourceFilterXmlReadHandle }
constructor TLocalBackupSourceFilterXmlReadHandle.Create(_FilterNode: IXMLNode);
begin
FilterNode := _FilterNode;
end;
procedure TLocalBackupSourceFilterXmlReadHandle.SetFullPath(_FullPath: string);
begin
FullPath := _FullPath;
end;
procedure TLocalBackupSourceFilterXmlReadHandle.Update;
begin
// 提取 过滤信息
FilterType := MyXmlUtil.GetChildValue( FilterNode, Xml_FilterType );
FilterStr := MyXmlUtil.GetChildValue( FilterNode, Xml_FilterStr );
// 添加 过滤器
AddFilterHandle;
end;
{ TLocalBackupSourceIncludeFilterXmlReadHandle }
procedure TLocalBackupSourceIncludeFilterXmlReadHandle.AddFilterHandle;
var
LocalBackupSourceIncludeFilterReadHandle : TLocalBackupSourceIncludeFilterReadHandle;
begin
LocalBackupSourceIncludeFilterReadHandle := TLocalBackupSourceIncludeFilterReadHandle.Create( FullPath );
LocalBackupSourceIncludeFilterReadHandle.SetFilterInfo( FilterType, FilterStr );
LocalBackupSourceIncludeFilterReadHandle.Update;
LocalBackupSourceIncludeFilterReadHandle.Free;
end;
{ TLocalBackupSourceExcludeFilterXmlReadHandle }
procedure TLocalBackupSourceExcludeFilterXmlReadHandle.AddFilterHandle;
var
LocalBackupSourceExcludeFilterReadHandle : TLocalBackupSourceExcludeFilterReadHandle;
begin
LocalBackupSourceExcludeFilterReadHandle := TLocalBackupSourceExcludeFilterReadHandle.Create( FullPath );
LocalBackupSourceExcludeFilterReadHandle.SetFilterInfo( FilterType, FilterStr );
LocalBackupSourceExcludeFilterReadHandle.Update;
LocalBackupSourceExcludeFilterReadHandle.Free;
end;
{ TLocalBackupSourceIsDisableXml }
procedure TLocalBackupSourceIsDisableXml.SetIsDisable(_IsDisable: Boolean);
begin
IsDisable := _IsDisable;
end;
procedure TLocalBackupSourceIsDisableXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.AddChild( SourcePathNode, Xml_IsDisable, BoolToStr( IsDisable ) );
end;
{ TLocalBackupSourceIsBackupNowXml }
procedure TLocalBackupSourceIsBackupNowXml.SetIsBackupNow(
_IsBackupNow: Boolean);
begin
IsBackupNow := _IsBackupNow;
end;
procedure TLocalBackupSourceIsBackupNowXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.AddChild( SourcePathNode, Xml_IsBackupNow, BoolToStr( IsBackupNow ) );
end;
{ TLocalBackupSourceSetLastSyncTimeXml }
procedure TLocalBackupSourceSetLastSyncTimeXml.SetLastSyncTime(
_LastSyncTime: TDateTime);
begin
LastSyncTime := _LastSyncTime;
end;
procedure TLocalBackupSourceSetLastSyncTimeXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.AddChild( SourcePathNode, Xml_LastSyncTime, FloatToStr( LastSyncTime ) );
end;
{ TLocalBackupSourceSetSyncMinsXml }
procedure TLocalBackupSourceSetSyncMinsXml.SetIsAutoSync(_IsAutoSync: Boolean);
begin
IsAutoSync := _IsAutoSync;
end;
procedure TLocalBackupSourceSetSyncMinsXml.SetSyncInterval(_SyncTimeType,
_SyncTimeValue: Integer);
begin
SyncTimeType := _SyncTimeType;
SyncTimeValue := _SyncTimeValue;
end;
procedure TLocalBackupSourceSetSyncMinsXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.AddChild( SourcePathNode, Xml_IsAuctoSync, BoolToStr( IsAutoSync ) );
MyXmlUtil.AddChild( SourcePathNode, Xml_SyncTimeType, IntToStr( SyncTimeType ) );
MyXmlUtil.AddChild( SourcePathNode, Xml_SyncTimeValue, IntToStr( SyncTimeValue ) );
end;
{ TLocalBackupSourceIsAddDesToSourceXml }
procedure TLocalBackupSourceIsAddDesToSourceXml.Update;
begin
inherited;
MyXmlUtil.AddChild( MyLocalBackupSourceXml, Xml_IsAddDesToSource, False );
end;
{ TLocalBackupSorceSetDeleteXml }
procedure TLocalBackupSorceSetDeleteXml.SetDeleteInfo(_IsKeepDeleted: Boolean;
_KeepEditionCount: Integer);
begin
IsKeepDeleted := _IsKeepDeleted;
KeepEditionCount := _KeepEditionCount;
end;
procedure TLocalBackupSorceSetDeleteXml.Update;
begin
// 不存在
if not FindSourcePathNode then
Exit;
MyXmlUtil.AddChild( SourcePathNode, Xml_IsKeepDeleted, IsKeepDeleted );
MyXmlUtil.AddChild( SourcePathNode, Xml_KeepEdtionCount, KeepEditionCount );
end;
{ TLocalBackupSorceAddDeletedSpaceXml }
procedure TLocalBackupSorceAddDeletedSpaceXml.SetAddDeletedSpace(
_AddDeletedSpace: Int64);
begin
AddDeletedSpace := _AddDeletedSpace;
end;
procedure TLocalBackupSorceAddDeletedSpaceXml.Update;
var
DeletedSpace : Int64;
begin
// 不存在
if not FindDesPathNode then
Exit;
DeletedSpace := MyXmlUtil.GetChildInt64Value( DesPathNode, Xml_DeletedSpace );
DeletedSpace := DeletedSpace + AddDeletedSpace;
MyXmlUtil.AddChild( DesPathNode, Xml_DeletedSpace, DeletedSpace );
end;
{ TLocalBackupSorceSetDeletedSpaceXml }
procedure TLocalBackupSorceSetDeletedSpaceXml.SetDeletedSpace(
_DeletedSpace: Int64);
begin
DeletedSpace := _DeletedSpace;
end;
procedure TLocalBackupSorceSetDeletedSpaceXml.Update;
begin
// 不存在
if not FindDesPathNode then
Exit;
MyXmlUtil.AddChild( DesPathNode, Xml_DeletedSpace, DeletedSpace );
end;
end.
|
unit ScriptTok;
interface
uses
Windows,
SysUtils,
CocoaBase;
const
TOK_eof = 0;
TOK_whitespace = 1;
TOK_comment = 2;
TOK_signature = 3;
TOK_identifier = 4;
TOK_stringQ = 5;
TOK_semicolon = 6;
TOK_number = 7;
TOK_float = 8;
TOK__124__124_ = 9;
TOK__47_ = 10;
TOK__41_ = 11;
TOK__40_ = 12;
TOK__43_ = 13;
TOK__45_ = 14;
TOK__42_ = 15;
TOK_MATCH = 16;
TOK_WHERE = 17;
TOK_BEGIN = 18;
TOK_END = 19;
TOK_SET = 20;
TOK_TO = 21;
TOK_MODIFY = 22;
TOK_OFFSET = 23;
TOK_FACTOR = 24;
TOK_INCLUDE = 25;
TOK_EXCLUDE = 26;
TOK_OR = 27;
TOK_AND = 28;
TOK_NOT = 29;
TOK__45__62_ = 30;
TOK_div = 31;
TOK_mod = 32;
TokStr : array[0..32] of string = (
'<eof>',
'<white-space>',
'<comment>',
'<signature>',
'<identifier>',
'<stringQ>',
'<semicolon>',
'<number>',
'<float>',
'|' + '|',
'/',
')',
'(',
'+',
'-',
'*',
'MATCH',
'WHERE',
'BEGIN',
'END',
'SET',
'TO',
'MODIFY',
'OFFSET',
'FACTOR',
'INCLUDE',
'EXCLUDE',
'OR',
'AND',
'NOT',
'->',
'div',
'mod');
FirstKeyword = 16;
LastKeyword = 30;
FirstDirective = 31;
LastDirective = 32;
type
TScriptTokenizer = class(TBaseTokenizer)
protected
function isTokTerm_float: Boolean;
function isTokFactor_number: Boolean;
function isTokFactor_semicolon: Boolean;
function isTokFactor_stringQ_3: Boolean;
function isTokFactor_stringQ_2: Boolean;
function isTokFactor_stringQ: Boolean;
function isTokTerm_stringQ: Boolean;
function isTokFactor_identifier_7: Boolean;
function isTokFactor_identifier_6: Boolean;
function isTokFactor_identifier_5: Boolean;
function isTokTerm_identifier_2: Boolean;
function isTokFactor_identifier_4: Boolean;
function isTokFactor_identifier_3: Boolean;
function isTokFactor_identifier_2: Boolean;
function isTokFactor_identifier: Boolean;
function isTokTerm_identifier: Boolean;
function isTokFactor_signature: Boolean;
function isTokTerm_signature: Boolean;
public
function Tokenize(Buffer: PChar; Size: Integer;
IncludeComments, IncludeWhitespace: Boolean;
var Tokens: TTokenList): Boolean; override;
end;
function IsKeyword(const Str: string): Boolean;
implementation
var
KeywordTree: TTernaryTree;
function TScriptTokenizer.isTokFactor_signature: Boolean;
begin
case Peek of
'A'..'Z', '_', 'a'..'z' :
begin
Advance;
Result := True;
end;
else
Result := False;
end;
end;
function TScriptTokenizer.isTokTerm_signature: Boolean;
begin
Push;
Result := isTokFactor_signature and isTokFactor_signature and isTokFactor_signature and isTokFactor_signature;
IfDropElsePop(Result);
end;
function TScriptTokenizer.isTokFactor_identifier_2: Boolean;
begin
case Peek of
'0'..'9' :
begin
Advance;
Result := True;
end;
else
Result := False;
end;
end;
function TScriptTokenizer.isTokFactor_identifier_3: Boolean;
begin
if Peek = '/' then begin
Advance;
Result := True;
end else
Result := False;
end;
function TScriptTokenizer.isTokFactor_identifier_4: Boolean;
begin
if Peek = '.' then begin
Advance;
Result := True;
end else
Result := False;
end;
function TScriptTokenizer.isTokFactor_identifier: Boolean;
begin
if ((isTokFactor_signature or isTokFactor_identifier_2 or isTokFactor_identifier_3 or isTokFactor_identifier_4)) then begin
Result := true;
while ((isTokFactor_signature or isTokFactor_identifier_2 or isTokFactor_identifier_3 or isTokFactor_identifier_4)) do
;
end else
Result := false;
end;
function TScriptTokenizer.isTokTerm_identifier: Boolean;
begin
Push;
Result := isTokFactor_signature and isTokFactor_identifier;
IfDropElsePop(Result);
end;
function TScriptTokenizer.isTokFactor_identifier_5: Boolean;
begin
if Peek = '"' then begin
Advance;
Result := True;
end else
Result := False;
end;
function TScriptTokenizer.isTokFactor_identifier_7: Boolean;
begin
case Peek of
#10, #13, ' '..'!', '#'..'ÿ' :
begin
Advance;
Result := True;
end;
else
Result := False;
end;
end;
function TScriptTokenizer.isTokFactor_identifier_6: Boolean;
begin
if (isTokFactor_identifier_7) then begin
repeat
until not (isTokFactor_identifier_7);
end;
Result := true;
end;
function TScriptTokenizer.isTokTerm_identifier_2: Boolean;
begin
Push;
Result := isTokFactor_identifier_5 and isTokFactor_identifier_6 and isTokFactor_identifier_5;
IfDropElsePop(Result);
end;
function TScriptTokenizer.isTokFactor_stringQ: Boolean;
begin
if Peek = #39 then begin
Advance;
Result := True;
end else
Result := False;
end;
function TScriptTokenizer.isTokFactor_stringQ_3: Boolean;
begin
case Peek of
#10, #13, ' '..'&', '('..'ÿ' :
begin
Advance;
Result := True;
end;
else
Result := False;
end;
end;
function TScriptTokenizer.isTokFactor_stringQ_2: Boolean;
begin
if (isTokFactor_stringQ_3) then begin
repeat
until not (isTokFactor_stringQ_3);
end;
Result := true;
end;
function TScriptTokenizer.isTokTerm_stringQ: Boolean;
begin
Push;
Result := isTokFactor_stringQ and isTokFactor_stringQ_2 and isTokFactor_stringQ;
IfDropElsePop(Result);
end;
function TScriptTokenizer.isTokFactor_semicolon: Boolean;
begin
if Peek = ';' then begin
Advance;
Result := True;
end else
Result := False;
end;
function TScriptTokenizer.isTokFactor_number: Boolean;
begin
if (isTokFactor_identifier_2) then begin
Result := true;
while (isTokFactor_identifier_2) do
;
end else
Result := false;
end;
function TScriptTokenizer.isTokTerm_float: Boolean;
begin
Push;
Result := isTokFactor_number and isTokFactor_identifier_4 and isTokFactor_number;
IfDropElsePop(Result);
end;
function TScriptTokenizer.Tokenize(Buffer: PChar; Size: Integer;
IncludeComments, IncludeWhitespace: Boolean;
var Tokens: TTokenList): Boolean;
procedure AddToken(TokenType: Integer);
begin
Tokens.AddToken(StartPtr, CurPtr,
StartLine, CurLine, StartPos, CurPos, TokenType);
end;
var
b: boolean;
var
i: Integer;
SaveChar: Char;
begin
Tokens := TTokenList.Create;
CurPtr := PChar(Buffer);
EndPtr := PChar(DWord(CurPtr) + DWord(Size));
CurLine := 1;
CurPos := 1;
try
while CurPtr < EndPtr do begin
b := false;
StartPtr := CurPtr;
StartLine := CurLine;
StartPos := CurPos;
if (Peek(0) = '#') then begin
Advance(1);
b := true;
end;
if b then begin
b := false;
if (char(Peek(0)) in [ #13]) then begin
Advance(1);
b := true;
end;
if not b and (Peek <> #0) then
repeat
Advance;
if (char(Peek(0)) in [ #13]) then begin
Advance(1);
b := true;
end;
until b or (Peek = #0);
if IncludeComments then
AddToken(TOK_comment);
continue;
end;
if char(CurPtr^) in [#1..' '] then begin
Advance;
while char(Peek) in [#1..' '] do
Advance;
if IncludeWhitespace then
AddToken(TOK_whitespace);
continue;
end;
if (isTokTerm_signature) then begin
AddToken(TOK_signature);
continue;
end;
if (isTokTerm_identifier or isTokTerm_identifier_2) then begin
SaveChar := CurPtr^;
CurPtr^ := #0;
i := KeywordTree.SearchUC(StartPtr);
CurPtr^ := SaveChar;
if i <> 0 then
AddToken(i)
else
AddToken(TOK_identifier);
continue;
end;
if (isTokTerm_stringQ) then begin
AddToken(TOK_stringQ);
continue;
end;
if (isTokFactor_semicolon) then begin
AddToken(TOK_semicolon);
continue;
end;
if (isTokFactor_number) then begin
AddToken(TOK_number);
continue;
end;
if (isTokTerm_float) then begin
AddToken(TOK_float);
continue;
end;
if (CurPtr^ = '|') and (Peek(1) = '|') then begin
Advance(2);
AddToken(TOK__124__124_);
continue;
end;
case CurPtr^ of
'/' : AddToken(TOK__47_);
')' : AddToken(TOK__41_);
'(' : AddToken(TOK__40_);
'+' : AddToken(TOK__43_);
'-' : AddToken(TOK__45_);
'*' : AddToken(TOK__42_);
#0 :
begin
AddToken(TOK_eof);
Result := True;
exit;
end;
else
break;
end;
Advance;
continue;
end;
if CurPtr >= EndPtr then begin
AddToken(TOK_eof);
Result := True;
end else
Result := False;
except
Result := False;
end;
end;
function IsKeyword(const Str: string): Boolean;
var
i: Integer;
begin
i := KeywordTree.SearchUC(PAnsiChar(Str));
Result := (i >= FirstKeyword) and (i <= LastKeyword);
end;
procedure InitKeywordTree;
var i: Integer;
begin
KeywordTree := TTernaryTree.Create;
for i := FirstKeyword to LastKeyword do
KeywordTree.InsertStr(PChar(TokStr[i]), i);
for i := FirstDirective to LastDirective do
KeywordTree.InsertStr(PChar(TokStr[i]), i);
end;
initialization
InitKeywordTree;
finalization
KeywordTree.Free;
end.
|
program Swap;
var
a: Char;
b: Char;
begin
a := 'a';
b := 'b';
{read(a, b);}
writeln(b, a)
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/ControlPanel/cpSettingsForm.pas,v 1.2 2004/04/06 09:29:07 paladin Exp $
------------------------------------------------------------------------}
unit cpSettingsForm;
interface
uses
Forms, cxLookAndFeelPainters, cxCheckBox, cxControls, cxContainer,
cxEdit, cxTextEdit, Controls, ExtCtrls, StdCtrls, cxButtons, Classes,
PluginManagerIntf;
type
TSettingsForm = class(TForm)
Label1: TLabel;
Label2: TLabel;
HttpProxy_label: TLabel;
HttpProxyLogin_label: TLabel;
OK: TcxButton;
Cancel: TcxButton;
Panel2: TPanel;
HttpRoot: TcxTextEdit;
DataBasePrefix: TcxTextEdit;
HttpProxy: TcxTextEdit;
HttpProxyLogin: TcxTextEdit;
HttpProxyPass: TcxTextEdit;
UseHttpProxy: TcxCheckBox;
Panel3: TPanel;
Panel1: TPanel;
Label3: TLabel;
HttpLogin: TcxTextEdit;
HttpPass: TcxTextEdit;
private
FPluginManager: IPluginManager;
procedure SetPluginManager(const Value: IPluginManager);
public
procedure Load;
procedure Save;
property PluginManager: IPluginManager read FPluginManager write SetPluginManager;
end;
function GetSettingsForm(PluginManager: IPluginManager): Integer;
implementation
uses SettingsIntf;
{$R *.dfm}
function GetSettingsForm;
var
Form: TSettingsForm;
begin
Form := TSettingsForm.Create(Application);
try
Form.PluginManager := PluginManager;
Form.Load;
Result := Form.ShowModal;
if Result = mrOK then
Form.Save;
finally
Form.Free;
end;
end;
{ TSettingsForm }
procedure TSettingsForm.Load;
var
Settings: ISettings;
begin
if FPluginManager.GetPlugin(ISettings, Settings) then
begin
HttpRoot.Text := Settings.HttpRoot;
DataBasePrefix.Text := Settings.DataBasePrefix;
HttpLogin.Text := Settings.HttpLogin;
HttpPass.Text := Settings.HttpPass;
end;
end;
procedure TSettingsForm.Save;
var
Settings: ISettings;
begin
if FPluginManager.GetPlugin(ISettings, Settings) then
begin
Settings.HttpRoot := HttpRoot.Text;
Settings.DataBasePrefix := DataBasePrefix.Text;
Settings.HttpLogin := HttpLogin.Text;
Settings.HttpPass := HttpPass.Text;
end;
end;
procedure TSettingsForm.SetPluginManager(const Value: IPluginManager);
begin
FPluginManager := Value;
end;
end.
|
unit BaseReport;
interface
uses BaseObjects, Variants, DB, Contnrs, Classes;
type
TReport = class;
TReportBlockColumn = class(TPersistent)
private
FColumnID: byte;
FColumnName: string;
FColumnDataType: TFieldType;
FVisible: boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
public
property ColumnID: byte read FColumnID write FColumnID;
property ColumnName: string read FColumnName write FColumnName;
property ColumnDataType: TFieldType read FColumnDataType write FColumnDataType;
property Visible: boolean read FVisible write FVisible;
end;
TColumnIdsSet = set of byte;
TReportBlockColumns = class(TObjectList)
private
function GetItems(Index: integer): TReportBlockColumn;
function GetVisibleColumnCount: integer;
public
function Add: TReportBlockColumn; overload;
function Add(AColumnID: integer; AColumnName: string; AColumnDataType: TFieldType; AVisible: boolean): TReportBlockColumn; overload;
function GetReportHeader: OleVariant;
function GetVisibleColumnIDs: TColumnIdsSet;
property VisibleColumnCount: integer read GetVisibleColumnCount;
property Items[Index: integer]: TReportBlockColumn read GetItems;
constructor Create; virtual;
end;
TReportBlock = class(TIDObject)
private
FTop: integer;
FLeft: integer;
protected
FReportingObject: TIDObject;
FReportingCollection: TIDObjects;
FBlockHeader: OleVariant;
FBlockData: OleVariant;
FReportBlockColumns: TReportBlockColumns;
procedure SetReportingObject(const Value: TIDObject); virtual;
procedure SetReportingCollection(const Value: TIDObjects); virtual;
function GetBlockHeader: OleVariant; virtual;
function GetBlockData: OleVariant; virtual;
function GetHeight: integer; virtual;
function GetWidth: integer; virtual;
function GetReportBlockColumns: TReportBlockColumns; virtual;
public
property Left: integer read FLeft write FLeft;
property Top: integer read FTop write FTop;
property Width: integer read GetWidth;
property Height: integer read GetHeight;
property ReportingObject: TIDObject read FReportingObject write SetReportingObject;
property ReportingCollection: TIDObjects read FReportingCollection write SetReportingCollection;
property ReportBlockColumns: TReportBlockColumns read GetReportBlockColumns;
property BlockData: OleVariant read GetBlockData;
property BlockHeader: OleVariant read GetBlockHeader;
procedure Clear; virtual;
constructor Create; reintroduce; virtual;
end;
TReportBlocks = class(TIDObjects)
private
function GetItems(Index: integer): TReportBlock;
public
property Items[Index: integer]: TReportBlock read GetItems; default;
constructor Create; override;
end;
TComplexReportBlock = class(TReportBlock)
private
FReportBlocks: TReportBlocks;
function GetReportBlocks: TReportBlocks;
protected
procedure SetReportingObject(const Value: TIDObject); override;
procedure SetReportingCollection(const Value: TIDObjects); override;
function GetReportBlockColumns: TReportBlockColumns; override;
function GetHeight: integer; override;
function GetWidth: integer; override;
function GetBlockData: OleVariant; override;
public
procedure Clear; override;
property ReportingCollection: TIDObjects read FReportingCollection write SetReportingCollection;
property Blocks: TReportBlocks read GetReportBlocks;
destructor Destroy; override;
end;
IReportVisitor = interface
procedure MakeSingleObjectReport(AObject: TIDObject; Report: TReport);
procedure MakeCollectionReport(ACollection: TIDObjects; Report: TReport);
procedure MakeDatasetReport(ADataSet: TDataSet; Report: TReport);
end;
TDataMover = class(TInterfacedObject, IReportVisitor)
private
FName: string;
public
procedure Prepare; virtual; abstract;
procedure MakeSingleObjectReport(AObject: TIDObject; Report: TReport); virtual;
procedure MakeCollectionReport(ACollection: TIDObjects; Report: TReport); virtual;
procedure MakeDatasetReport(ADataSet: TDataSet; Report: TReport); virtual;
property Name: string read FName write FName;
constructor Create; virtual;
end;
TDataMoverClass = class of TDataMover;
TDataMovers = class(TObjectList)
private
function GetItems(Index: integer): TDataMover;
function GetItemByClassType(
ADataMoverClass: TDataMoverClass): TDataMover;
public
property Items[Index: integer]: TDataMover read GetItems;
property ItemByClassType[ADataMoverClass: TDataMoverClass]: TDataMover read GetItemByClassType;
procedure MakeList(AList: TStrings);
constructor Create; virtual;
end;
TTableReport = class(TIDObjectTable)
private
FReportTitle: string;
function GetItems(ACol, ARow: integer): TReportBlock;
procedure SetItems(ACol, ARow: integer; const Value: TReportBlock);
public
procedure MakeReport(ADataMover: TDataMover); virtual;
property ReportTitle: string read FReportTitle write FReportTitle;
property Items[ACol, ARow: integer]: TReportBlock read GetItems write SetItems;
constructor Create; override;
end;
TReport = class(TIDObject)
private
FReportTitle: string;
FReportBlock: TReportBlock;
procedure SetReportBlock(const Value: TReportBlock);
function GetReportBlockColumns: TReportBlockColumns;
public
procedure MakeReport(ADataMover: TDataMover); virtual;
property ReportTitle: string read FReportTitle write FReportTitle;
property Block: TReportBlock read FReportBlock write SetReportBlock;
property ReportColumns: TReportBlockColumns read GetReportBlockColumns;
constructor Create; reintroduce; virtual;
end;
TSingleObjectReport = class(TReport)
protected
procedure SetReportObject(const Value: TIDObject); virtual;
function GetReportObject: TIDObject; virtual;
public
procedure MakeReport(ADataMover: TDataMover); override;
property ReportObject: TIDObject read GetReportObject write SetReportObject;
end;
TCollectionReport = class(TReport)
protected
procedure SetReportObjects(const Value: TIDObjects); virtual;
function GetReportObjects: TIDObjects; virtual;
public
procedure MakeReport(ADataMover: TDataMover); override;
property ReportObjects: TIDObjects read GetReportObjects write SetReportObjects;
end;
TDataSetReport = class(TReport)
protected
FDataSet: TDataSet;
procedure SetDataSet(const Value: TDataSet); virtual;
public
procedure MakeReport(ADataMover: TDataMover); override;
property DataSet: TDataSet read FDataSet write SetDataSet;
end;
implementation
{ TReportBlock }
procedure TReportBlock.Clear;
begin
FBlockHeader := null;
FBlockData := null;
end;
constructor TReportBlock.Create;
begin
inherited Create(nil);
end;
function TReportBlock.GetBlockData: OleVariant;
begin
Result := FBlockData;
end;
function TReportBlock.GetBlockHeader: OleVariant;
begin
if varIsNull(FBlockHeader) then
FBlockHeader := ReportBlockColumns.GetReportHeader;
Result := FBlockHeader;
end;
function TReportBlock.GetHeight: integer;
begin
try
Result := varArrayHighBound(BlockData, 1);
except
Result := 0;
end;
end;
function TReportBlock.getReportBlockColumns: TReportBlockColumns;
begin
if not Assigned(FReportBlockColumns) then
FReportBlockColumns := TReportBlockColumns.Create;
Result := FReportBlockColumns;
end;
function TReportBlock.GetWidth: integer;
begin
try
Result := varArrayHighBound(BlockData, 2);
except
Result := 0;
end;
end;
procedure TReportBlock.SetReportingCollection(const Value: TIDObjects);
begin
if FReportingCollection <> Value then
FReportingCollection := Value;
end;
procedure TReportBlock.SetReportingObject(const Value: TIDObject);
begin
if FReportingObject <> Value then
FReportingObject := Value;
end;
{ TReportBlocks }
constructor TReportBlocks.Create;
begin
inherited;
FObjectClass := TReportBlock;
end;
function TReportBlocks.GetItems(Index: integer): TReportBlock;
begin
Result := inherited Items[Index] as TReportBlock;
end;
{ TTableReport }
constructor TTableReport.Create;
begin
inherited Create;
end;
function TTableReport.GetItems(ACol, ARow: integer): TReportBlock;
begin
Result := inherited Items[ACol, ARow] as TReportBlock;
end;
procedure TTableReport.MakeReport(ADataMover: TDataMover);
begin
end;
procedure TTableReport.SetItems(ACol, ARow: integer; const Value: TReportBlock);
begin
inherited Items[ACol, ARow] := Value;
end;
function TSingleObjectReport.GetReportObject: TIDObject;
begin
Result := FReportBlock.ReportingObject;
end;
procedure TSingleObjectReport.MakeReport(ADataMover: TDataMover);
begin
inherited;
Block.Clear;
ADataMover.MakeSingleObjectReport(ReportObject, Self);
end;
procedure TSingleObjectReport.SetReportObject(const Value: TIDObject);
begin
FReportBlock.ReportingObject := Value;
end;
function TCollectionReport.GetReportObjects: TIDObjects;
begin
Result := Block.ReportingCollection;
end;
procedure TCollectionReport.MakeReport(ADataMover: TDataMover);
begin
inherited;
Block.Clear;
ADataMover.MakeCollectionReport(ReportObjects, Self);
end;
procedure TCollectionReport.SetReportObjects(const Value: TIDObjects);
begin
Block.ReportingCollection := Value;
end;
{ TComplexReportBlock }
procedure TComplexReportBlock.Clear;
var i: integer;
begin
inherited;
for i := 0 to Blocks.Count - 1 do
Blocks.Items[i].Clear;
end;
destructor TComplexReportBlock.Destroy;
begin
if Assigned(FReportBlocks) then FReportBlocks.Free;
inherited;
end;
function TComplexReportBlock.GetBlockData: OleVariant;
var i, j, k: integer;
iWidth, iHeight, iCurrentColumn: integer;
begin
iWidth := 0;
iHeight := Blocks.Items[0].Height;
for i := 0 to Blocks.Count - 1 do
begin
iWidth := iWidth + Blocks.Items[i].Width;
if iHeight > Blocks.Items[i].Height then iHeight := Blocks.Items[i].Height;
end;
Result := VarArrayCreate([0, iHeight, 0, iWidth + 1], varVariant);
iCurrentColumn := 0;
for i := 0 to Blocks.Count - 1 do
begin
for j := 0 to iHeight do
for k := 0 to Blocks.Items[i].Width do
Result[j, iCurrentColumn + k] := Blocks.Items[i].BlockData[j, k];
iCurrentColumn := iCurrentColumn + Blocks.Items[i].Width + ord(iCurrentColumn = 0);
end;
end;
function TComplexReportBlock.GetHeight: integer;
var i: integer;
begin
Result := 100000000;
for i := 0 to Blocks.Count - 1 do
if Result > Blocks.Items[i].Height then Result := Blocks.Items[i].Height;
end;
function TComplexReportBlock.GetReportBlockColumns: TReportBlockColumns;
var i, j: integer;
begin
if not Assigned(FReportBlockColumns) then
begin
Result := inherited GetReportBlockColumns;
FReportBlockColumns.OwnsObjects := false;
for i := 0 to Blocks.Count - 1 do
for j := 0 to Blocks.Items[i].ReportBlockColumns.Count - 1 do
Result.Add(Blocks.Items[i].ReportBlockColumns.Items[j]);
end
else Result := FReportBlockColumns;
end;
function TComplexReportBlock.GetReportBlocks: TReportBlocks;
begin
if not Assigned(FReportBlocks) then
FReportBlocks := TReportBlocks.Create;
Result := FReportBlocks;
end;
function TComplexReportBlock.GetWidth: integer;
var i: integer;
begin
Result := 0;
for i := 0 to Blocks.Count - 1 do
Result := Result + Blocks.Items[i].Width;
end;
procedure TComplexReportBlock.SetReportingCollection(
const Value: TIDObjects);
var i: integer;
begin
FReportingCollection := Value;
for i := 0 to Blocks.Count - 1 do
Blocks.Items[i].ReportingCollection := FReportingCollection;
end;
procedure TComplexReportBlock.SetReportingObject(const Value: TIDObject);
var i: integer;
begin
inherited;
for i := 0 to Blocks.Count - 1 do
Blocks[i].ReportingObject := ReportingObject;
end;
{ TDataSetReport }
procedure TDataSetReport.MakeReport(ADataMover: TDataMover);
begin
inherited;
Block.Clear;
ADataMover.MakeDatasetReport(DataSet, Self);
end;
procedure TDataSetReport.SetDataSet(const Value: TDataSet);
begin
FDataSet := Value;
end;
{ TReport }
constructor TReport.Create;
begin
end;
function TReport.GetReportBlockColumns: TReportBlockColumns;
begin
Result := Block.ReportBlockColumns;
end;
procedure TReport.MakeReport(ADataMover: TDataMover);
begin
end;
procedure TReport.SetReportBlock(const Value: TReportBlock);
begin
FReportBlock := Value;
end;
{ TReportBlockColumns }
function TReportBlockColumns.Add: TReportBlockColumn;
begin
Result := TReportBlockColumn.Create;
inherited Add(Result);
end;
function TReportBlockColumns.Add(AColumnID: integer; AColumnName: string;
AColumnDataType: TFieldType; AVisible: boolean): TReportBlockColumn;
begin
Result := Add;
with Result do
begin
ColumnID := AColumnID;
ColumnName := AColumnName;
ColumnDataType := AColumnDataType;
Visible := AVisible;
end;
end;
constructor TReportBlockColumns.Create;
begin
inherited Create(true);
end;
function TReportBlockColumns.GetItems(Index: integer): TReportBlockColumn;
begin
Result := inherited Items[Index] as TReportBlockColumn;
end;
function TReportBlockColumns.GetReportHeader: OleVariant;
var i, k: integer;
begin
Result := varArrayCreate([0, VisibleColumnCount - 1], varOleStr);
k := 0;
for i := 0 to Count - 1 do
if Items[i].Visible then
begin
Result[k] := Items[i].ColumnName;
inc(k);
end;
end;
function TReportBlockColumns.GetVisibleColumnCount: integer;
var i: integer;
begin
Result := 0;
for i := 0 to Count - 1 do
Result := Result + ord(Items[i].Visible);
end;
function TReportBlockColumns.GetVisibleColumnIDs: TColumnIdsSet;
var i: integer;
begin
Result := [];
for i := 0 to Count - 1 do
if Items[i].Visible then
Result := Result + [Items[i].ColumnID];
end;
{ TReportBlockColumn }
procedure TReportBlockColumn.AssignTo(Dest: TPersistent);
var rbc: TReportBlockColumn;
begin
rbc := Dest as TReportBlockColumn;
rbc.ColumnID := ColumnID;
rbc.ColumnName := ColumnName;
rbc.ColumnDataType := ColumnDataType;
rbc.Visible := Visible;
end;
{ TDataMovers }
constructor TDataMovers.Create;
begin
inherited Create(true);
end;
function TDataMovers.GetItemByClassType(
ADataMoverClass: TDataMoverClass): TDataMover;
var i: integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if Items[i] is ADataMoverClass then
begin
Result := Items[i];
break;
end;
end;
function TDataMovers.GetItems(Index: integer): TDataMover;
begin
Result := inherited Items[Index] as TDataMover;
end;
procedure TDataMovers.MakeList(AList: TStrings);
var i: integer;
begin
AList.Clear;
for i := 0 to Count - 1 do
AList.AddObject(Items[i].Name, Items[i]);
end;
{ TDataMover }
constructor TDataMover.Create;
begin
inherited;
end;
procedure TDataMover.MakeCollectionReport(ACollection: TIDObjects;
Report: TReport);
begin
Prepare;
end;
procedure TDataMover.MakeDatasetReport(ADataSet: TDataSet;
Report: TReport);
begin
Prepare;
end;
procedure TDataMover.MakeSingleObjectReport(AObject: TIDObject;
Report: TReport);
begin
Prepare;
end;
end.
|
{*******************************************************}
{ }
{ SearchReadForm.pas
{ Copyright @2014/5/15 10:36:11 by 姜梁
{ }
{ 功能描述: 显示构造文件目录信息
{ 函数说明:
{*******************************************************}
unit SearchReadForm;
interface
uses
Windows, Messages, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,SysUtils, ThreadSearchFile, StrUtils;
type
TTFrmSearch = class(TForm)
lblText: TLabel;
lblProgress: TLabel;
lblNum: TLabel;
lbl1: TLabel;
lbl2: TLabel;
private
public
procedure GetMessageAboutThread(text:string; num:Integer);
end;
var
TFrmSearch: TTFrmSearch;
implementation
{$R *.dfm}
{ TTFrmSearch }
/// <summary>
/// 文件查找消息处理
/// </summary>
/// <param name="text">正在查询的文件路径</param>
/// <param name="num">总文件数</param>
procedure TTFrmSearch.GetMessageAboutThread(text:string; num:Integer);
begin
if num = EndNum then Close;
Canvas.TryLock;
try
lblProgress.Caption :=text;
lblNum.Caption := IntToStr(num);
finally
Canvas.Unlock;
end;
end;
end.
|
unit IndyServerUnit;
interface
{$i IdCompilerDefines.inc}
procedure RunTest;
implementation
uses
IdCustomHTTPServer, IdContext, IdGlobalProtocols, IdGlobal, IdURI,
ShellAPI;
type
TMyServer = class(TIdCustomHTTPServer)
private
InputValue: string; // should use session instead ...
protected
procedure DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override;
end;
procedure RunTest;
var
Server: TMyServer;
begin
Server := TMyServer.Create;
try
Server.Active := True;
ShellExecute(0, 'open', PChar('http://localhost/index.html'), '', '', 0);
ReadLn;
finally
Server.Free;
end;
end;
// based on class function TIdURI.URLDecode in Indy rev 5498
//function MyURLDecode(ASrc: string; AByteEncoding: IIdTextEncoding = nil
// ...
// // ----------------------------
// // Free Pascal 3.0.4 workaround: use AByteEncoding
// //{$IFDEF STRING_IS_ANSI}
// //EnsureEncoding(ADestEncoding, encOSDefault);
// //CheckByteEncoding(LBytes, AByteEncoding, ADestEncoding);
// //SetString(Result, PAnsiChar(LBytes), Length(LBytes));
// //{$ELSE}
// //Result := AByteEncoding.GetString(LBytes);
// //{$ENDIF}
// Result := string(AByteEncoding.GetString(LBytes));
// // ----------------------------
//end;
// based on https://stackoverflow.com/questions/24861793
procedure MyDecodeAndSetParams(ARequestInfo: TIdHTTPRequestInfo);
var
i, j : Integer;
AValue, s: string;
// ----------------------------
// Free Pascal 3.0.4 workaround
// LEncoding: IIdTextEncoding;
// ----------------------------
begin
AValue := ARequestInfo.UnparsedParams;
// Convert special characters
// ampersand '&' separates values {Do not Localize}
ARequestInfo.Params.BeginUpdate;
try
ARequestInfo.Params.Clear;
// TODO: provide an event or property that lets the user specify
// which charset to use for decoding query string parameters. We
// should not be using the 'Content-Type' charset for that. For
// 'application/x-www-form-urlencoded' forms, we should be, though...
// Free Pascal 3.0.4 workaround
// LEncoding := CharsetToEncoding(ARequestInfo.CharSet);
i := 1;
while i <= Length(AValue) do
begin
j := i;
while (j <= Length(AValue)) and (AValue[j] <> '&') do {do not localize}
begin
Inc(j);
end;
s := Copy(AValue, i, j-i);
// See RFC 1866 section 8.2.1. TP
s := ReplaceAll(s, '+', ' '); {do not localize}
// ----------------------------
// Free Pascal 3.0.4 workaround
// ARequestInfo.Params.Add(TIdURI.URLDecode(s, LEncoding));
ARequestInfo.Params.Add(TIdURI.URLDecode(s, IndyTextEncoding_UTF8));
// ----------------------------
i := j + 1;
end;
finally
ARequestInfo.Params.EndUpdate;
end;
end;
procedure TMyServer.DoCommandGet(AContext: TIdContext;
ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
if ARequestInfo.Document <> '/index.html' then begin
AResponseInfo.ResponseNo := 404;
Exit;
end;
if (ARequestInfo.CommandType = hcPOST) and
IsHeaderMediaType(ARequestInfo.ContentType, 'application/x-www-form-urlencoded')
then begin
// decode form params
MyDecodeAndSetParams(ARequestInfo);
WriteLn('CharSet: ' + ARequestInfo.CharSet);
WriteLn('FormParams: ' + ARequestInfo.FormParams);
InputValue := ARequestInfo.Params.Values['input'];
WriteLn('Param.Values[''input'']: ' + InputValue);
AResponseInfo.ContentText :=
'<!DOCTYPE HTML>'
+ '<html lang="en">'
+ '<head>'
+ ' <meta charset="utf-8">'
+ ' <title>Hello</title>'
+ '</head>'
+ '<body>'
+ ' Input: ' + InputValue
+ '</body>'
+ '</html>';
end else begin
AResponseInfo.ContentText :=
'<!DOCTYPE HTML>'
+ '<html lang="en">'
+ '<head>'
+ ' <meta charset="utf-8">'
+ ' <title>Form Test</title>'
+ '</head>'
+ '<body>'
+ ' <form method="POST">'
+ ' <input type="text" name="input" />'
+ ' <input type="submit" />'
+ ' </form>'
+ '</body>'
+ '</html>';
end;
AResponseInfo.ContentType := 'text/html';
AResponseInfo.CharSet := 'utf-8';
// this tells TIdHTTPServer what encoding the ContentText is using
// so it can be decoded to Unicode prior to then being charset-encoded
// for output. If the input and output encodings are the same, the
// Ansi string data gets transmitted as-is without decoding/reencoding...
AContext.Connection.IOHandler.DefAnsiEncoding := IndyTextEncoding_UTF8;
end;
end.
|
{$INCLUDE switches}
unit Diplomacy;
interface
uses Protocol;
function DipCommandToString(pSender, pTarget, Treaty, OppCommand, Command: integer;
const OppOffer, Offer: TOffer): string;
implementation
uses
ScreenTools,Tribes,SysUtils;
function DipCommandToString;
function PriceToString(p, Price: integer): string;
begin
case Price and opMask of
opChoose:
result:=Phrases.Lookup('PRICE_CHOOSE');
opCivilReport:
result:=Tribe[p].TPhrase('PRICE_CIVIL');
opMilReport:
result:=Tribe[p].TPhrase('PRICE_MIL');
opMap:
result:=Tribe[p].TPhrase('PRICE_MAP');
opTreaty:
{if Price-opTreaty<Treaty then
case Treaty of
trPeace: result:=Phrases.Lookup('FRENDTREATY_PEACE');
trFriendlyContact: result:=Phrases.Lookup('FRENDTREATY_FRIENDLY');
trAlliance: result:=Phrases.Lookup('FRENDTREATY_ALLIANCE');
end
else} result:=Phrases.Lookup('TREATY',Price-opTreaty);
opShipParts:
case Price shr 16 and $f of
0: result:=Format(Phrases.Lookup('PRICE_SHIPCOMP'),[Price and $FFFF]);
1: result:=Format(Phrases.Lookup('PRICE_SHIPPOW'),[Price and $FFFF]);
2: result:=Format(Phrases.Lookup('PRICE_SHIPHAB'),[Price and $FFFF]);
end;
opMoney:
result:=Format('%d%%c',[Price-opMoney]);
opTribute:
result:=Format(Phrases.Lookup('PRICE_TRIBUTE'),[Price-opTribute]);
opTech:
result:=Phrases.Lookup('ADVANCES',Price-opTech);
opAllTech:
result:=Tribe[p].TPhrase('PRICE_ALLTECH');
opModel:
result:=Tribe[p].ModelName[Price-opModel];
opAllModel:
result:=Tribe[p].TPhrase('PRICE_ALLMODEL');
{ opCity:
result:=Format(TPhrase('PRICE_CITY',p),[CityName(Price-opCity)]);}
end
end;
var
i: integer;
sAdd,sDeliver, sCost: string;
DoIntro: boolean;
begin
DoIntro:= OppCommand=scDipStart;
case Command of
scDipCancelTreaty:
begin
case Treaty of
trPeace: result:=Phrases.Lookup('FRCANCELTREATY_PEACE');
trFriendlyContact: result:=Phrases.Lookup('FRCANCELTREATY_FRIENDLY');
trAlliance: result:=Phrases.Lookup('FRCANCELTREATY_ALLIANCE');
end;
DoIntro:=false;
end;
scDipNotice: result:=Phrases.Lookup('FRNOTICE');
scDipAccept:
begin
if (OppOffer.nDeliver+OppOffer.nCost=1)
and (OppOffer.Price[0] and opMask=opTreaty)
and (integer(OppOffer.Price[0]-opTreaty)>Treaty) then // simple treaty offer
{if OppOffer.Price[0]-opTreaty=trCeaseFire then
result:=Tribe[pTarget].TPhrase('FRACCEPTCEASEFIRE')
else} result:=Tribe[pTarget].TPhrase('FRACCEPTTREATY')
else if OppOffer.nDeliver=0 then
result:=Tribe[pSender].TPhrase('FRACCEPTDEMAND_STRONG')
else if OppOffer.nCost=0 then
result:=Tribe[pSender].TPhrase('FRACCEPTPRESENT')
else result:=Tribe[pSender].TPhrase('FRACCEPTOFFER');
end;
scDipBreak:
begin
result:=Tribe[pTarget].TPhrase('FRBREAK');
DoIntro:=false;
end;
scDipOffer:
begin
result:='';
if (OppCommand=scDipOffer) and ((OppOffer.nDeliver>0) or (OppOffer.nCost>0))
and (Offer.nCost+Offer.nDeliver<=2) then
begin // respond to made offer before making own one
if (OppOffer.nDeliver+OppOffer.nCost=1)
and (OppOffer.Price[0] and opMask=opTreaty)
and (integer(OppOffer.Price[0]-opTreaty)>Treaty) then // simple treaty offer
result:=Tribe[pSender].TPhrase('FRNOTACCEPTTREATY')+'\'
else if OppOffer.nDeliver=0 then
result:=Tribe[pSender].TPhrase('FRNOTACCEPTDEMAND_STRONG')+'\'
else if OppOffer.nCost=0 then
result:=Tribe[pSender].TPhrase('FRNOTACCEPTPRESENT')+'\';
end;
sDeliver:='';
for i:=0 to Offer.nDeliver-1 do
begin
sAdd:=PriceToString(pSender,Offer.Price[i]);
if i=0 then sDeliver:=sAdd
else sDeliver:=Format(Phrases.Lookup('PRICE_CONCAT'),[sDeliver,sAdd])
end;
sCost:='';
for i:=0 to Offer.nCost-1 do
begin
sAdd:=PriceToString(pTarget,Offer.Price[Offer.nDeliver+i]);
if i=0 then sCost:=sAdd
else sCost:=Format(Phrases.Lookup('PRICE_CONCAT'),[sCost,sAdd])
end;
if (Offer.nDeliver=0) and (Offer.nCost=0) then
begin // no offer made
if (OppCommand=scDipOffer) and ((OppOffer.nDeliver=0) and (OppOffer.nCost=0)) then
result:=Tribe[pTarget].TPhrase('FRBYE')
else
begin
if (result='') and (OppCommand=scDipOffer)
and ((OppOffer.nDeliver>0) or (OppOffer.nCost>0)) then
begin
if (OppOffer.nDeliver=1) and (OppOffer.Price[0]=opChoose)
and not Phrases2FallenBackToEnglish then
result:=Tribe[pSender].TString(Phrases2.Lookup('FRNOTACCEPTANYOFFER'))+' '
else if (OppOffer.nCost=1) and (OppOffer.Price[OppOffer.nDeliver]=opChoose)
and not Phrases2FallenBackToEnglish then
result:=Tribe[pSender].TString(Phrases2.Lookup('FRNOTACCEPTANYWANT'))+' '
else result:=Tribe[pSender].TPhrase('FRNOTACCEPTOFFER')+' ';
end;
result:=result+Phrases.Lookup('FRDONE');
DoIntro:=false
end
end
else if (Offer.nDeliver+Offer.nCost=1)
and (Offer.Price[0] and opMask=opTreaty)
and (integer(Offer.Price[0]-opTreaty)>Treaty) then // simple treaty offer
begin
case Offer.Price[0]-opTreaty of
//trCeaseFire: result:=result+Tribe[pTarget].TPhrase('FRCEASEFIRE');
trPeace: result:=result+Tribe[pTarget].TPhrase('FRPEACE');
trFriendlyContact: result:=result+Tribe[pTarget].TPhrase('FRFRIENDLY');
trAlliance: result:=result+Tribe[pTarget].TPhrase('FRALLIANCE');
end
end
else if Offer.nDeliver=0 then // demand
begin
if (Treaty>=trFriendlyContact) and not Phrases2FallenBackToEnglish then
result:=result+Format(Tribe[pTarget].TString(Phrases2.Lookup('FRDEMAND_SOFT')),[sCost])
else
begin
result:=result+Format(Tribe[pTarget].TPhrase('FRDEMAND_STRONG'),[sCost]);
DoIntro:=false
end
end
else if Offer.nCost=0 then // present
result:=result+Format(Tribe[pTarget].TPhrase('FRPRESENT'),[sDeliver])
else if (Offer.nDeliver=1) and (Offer.Price[0]=opChoose) then
result:=result+Format(Phrases.Lookup('FRDELCHOICE'),[sCost])
else if (Offer.nCost=1) and (Offer.Price[Offer.nDeliver]=opChoose) then
result:=result+Format(Phrases.Lookup('FRCOSTCHOICE'),[sDeliver])
else result:=result+Format(Phrases.Lookup('FROFFER'),[sDeliver,sCost]);
end;
end;
if DoIntro then
if Treaty<trPeace then
result:=Tribe[pSender].TPhrase('FRSTART_NOTREATY')+' '+result
else result:=Tribe[pSender].TPhrase('FRSTART_PEACE')+' '+result
end;
end.
|
unit LED680;
interface
uses Windows, SysUtils;
type
TLED680 = class
private
FFunc: integer;
FLEDMessage: string;
FShowDate: integer;
FSpeed: integer;
FCharMode: integer;
FHoldType: integer;
FInType: integer;
FNormalMode: integer;
FOutType: integer;
FShowWeek: integer;
FAddLogo: integer;
FCurrentSec: integer;
FShowTime: integer;
FTotalSec: integer;
FAddMessage: integer;
FShowingTime: integer;
procedure SetFunc(const Value: integer);
procedure SetLEDMessage(const Value: string);
procedure SetAddLogo(const Value: integer);
procedure SetAddMessage(const Value: integer);
procedure SetCharMode(const Value: integer);
procedure SetCurrentSec(const Value: integer);
procedure SetHoldType(const Value: integer);
procedure SetInType(const Value: integer);
procedure SetNormalMode(const Value: integer);
procedure SetOutType(const Value: integer);
procedure SetShowDate(const Value: integer);
procedure SetShowingTime(const Value: integer);
procedure SetShowTime(const Value: integer);
procedure SetShowWeek(const Value: integer);
procedure SetSpeed(const Value: integer);
procedure SetTotalSec(const Value: integer);
public
constructor Create();
function ExecuteCode: string;
function UserDefineMessage: string;
function ExecuteUserDefineMessage: string;
function ExecuteFirstMessage: string;
function ExecuteSecondMessage: string;
function ExecuteThirdMessage: string;
function ShowTempMessage: string;
function Backup: string;
function CheckTime: string;
function SetLogo: string;
published
property Func: integer read FFunc write SetFunc;
property LEDMessage: string read FLEDMessage write SetLEDMessage;
//总段数
property TotalSec: integer read FTotalSec write SetTotalSec;
//当前段
property CurrentSec: integer read FCurrentSec write SetCurrentSec;
//进入方式
property InType: integer read FInType write SetInType;
//退出方式
property OutType: integer read FOutType write SetOutType;
//保持方式
property HoldType: integer read FHoldType write SetHoldType;
//字符或图形显示
property CharMode: integer read FCharMode write SetCharMode;
//正常或反白显示
property NormalMode: integer read FNormalMode write SetNormalMode;
//是否加公司图标
property AddLogo: integer read FAddLogo write SetAddLogo;
//是否显示当前日期
property ShowDate: integer read FShowDate write SetShowDate;
//是否显示当前时间
property ShowTime: integer read FShowTime write SetShowTime;
//是否显示当前星期
property ShowWeek: integer read FShowWeek write SetShowWeek;
//添加原有信息或替换原有信息
property AddMessage: integer read FAddMessage write SetAddMessage;
//显示时间
property ShowingTime: integer read FShowingTime write SetShowingTime;
//移动速度
property Speed: integer read FSpeed write SetSpeed;
end;
implementation
{ TLED680 }
function TLED680.Backup: string;
begin
end;
function TLED680.CheckTime: string;
var y, m, d, h, n, s, w: integer;
t: _SYSTEMTIME;
tmp: string;
i, check: integer;
begin
GetSystemTime(t);
y := t.wYear mod 100;
m := t.wMonth;
d := t.wDay;
h := t.wHour + 8;
n := t.wMinute;
s := t.wSecond;
w := t.wDayOfWeek + 1;
tmp := Chr($7E) + Chr($0C) + Chr($08) + Chr($00)
+ Chr(StrToInt('$' + IntToStr(y))) + Chr(StrToInt('$' + IntToStr(m)))
+ Chr(StrToInt('$' + IntToStr(d))) + Chr(StrToInt('$' + IntToStr(h)))
+ Chr(StrToInt('$' + IntToStr(n))) + Chr(StrToInt('$' + IntToStr(s)))
+ Chr(StrToInt('$' + IntToStr(w)));
check := 0;
for i := 1 to Length(tmp) do
check := check xor Ord(tmp[i]);
result := tmp + Chr(check);
end;
constructor TLED680.Create;
begin
AddLogo := 0; //默认不添加LOGO
AddMessage := 0; //替换当前文字
CharMode := 0; //字符方式
CurrentSec := 1; //第一段
Func := 1; //用户自定义信息
HoldType := 0; //持续保持
InType := 1; //从左移动进入
LEDMessage := '';
NormalMode := 0; //正常显示
OutType := 1; //向左移动退出
ShowDate := 0; //不显示日期
ShowingTime := 1; //持续显示时间
ShowTime := 0; //不显示时间
ShowWeek := 0; //不显示星期
Speed := 0; //系统默认速度
TotalSec := 1; //就只显示一段
end;
function TLED680.ExecuteCode: string;
begin
case Func of
1: result := UserDefineMessage;
2: result := ExecuteUserDefineMessage;
3: result := ExecuteFirstMessage;
4: result := ExecuteSecondMessage;
5: result := ExecuteThirdMessage;
6: result := ShowTempMessage;
7: result := Backup;
8: result := CheckTime;
9: result := SetLogo;
end;
end;
function TLED680.ExecuteFirstMessage: string;
begin
result := Chr($7E) + Chr($04) + Chr($03) + Chr(79);
end;
function TLED680.ExecuteSecondMessage: string;
begin
result := Chr($7E) + Chr($04) + Chr($04) + Chr($7E);
end;
function TLED680.ExecuteThirdMessage: string;
begin
result := Chr($7E) + Chr($04) + Chr($05) + Chr($7F);
end;
function TLED680.ExecuteUserDefineMessage: string;
begin
result := Chr($7E) + Chr($04) + Chr($02) + Chr($78);
end;
procedure TLED680.SetAddLogo(const Value: integer);
begin
FAddLogo := Value;
end;
procedure TLED680.SetAddMessage(const Value: integer);
begin
FAddMessage := Value;
end;
procedure TLED680.SetCharMode(const Value: integer);
begin
FCharMode := Value;
end;
procedure TLED680.SetCurrentSec(const Value: integer);
begin
FCurrentSec := Value;
end;
procedure TLED680.SetFunc(const Value: integer);
begin
FFunc := Value;
end;
procedure TLED680.SetHoldType(const Value: integer);
begin
FHoldType := Value;
end;
procedure TLED680.SetInType(const Value: integer);
begin
FInType := Value;
end;
procedure TLED680.SetLEDMessage(const Value: string);
begin
FLEDMessage := Value;
end;
function TLED680.SetLogo: string;
begin
end;
procedure TLED680.SetNormalMode(const Value: integer);
begin
FNormalMode := Value;
end;
procedure TLED680.SetOutType(const Value: integer);
begin
FOutType := Value;
end;
procedure TLED680.SetShowDate(const Value: integer);
begin
FShowDate := Value;
end;
procedure TLED680.SetShowingTime(const Value: integer);
begin
FShowingTime := Value;
end;
procedure TLED680.SetShowTime(const Value: integer);
begin
FShowTime := Value;
end;
procedure TLED680.SetShowWeek(const Value: integer);
begin
FShowWeek := Value;
end;
procedure TLED680.SetSpeed(const Value: integer);
begin
FSpeed := Value;
end;
procedure TLED680.SetTotalSec(const Value: integer);
begin
FTotalSec := Value;
end;
function TLED680.ShowTempMessage: string;
var tmp: string;
i, check: integer;
begin
tmp := Chr($7E) + Chr(Length(LEDMessage) + 8) + Chr($06)
+ Chr(InType + OutType * 8 + HoldType * 64)
+ Chr(CharMode + NormalMode * 2 + AddLogo * 4 + ShowDate * 8 + ShowTime * 16 + ShowWeek * 32 + AddMessage * 64)
+ Chr(ShowingTime) + Chr(Speed) + LEDMessage;
check := 0;
for i := 1 to Length(tmp) do
check := check xor Ord(tmp[i]);
result := tmp + chr(check);
end; //13923789418 545503956
function TLED680.UserDefineMessage: string;
var tmp: string;
i, check: integer;
begin
tmp := Chr($7E) + Chr(Length(LEDMessage) + 10) + Chr($01) + Chr(TotalSec)
+ Chr(CurrentSec) + Chr(InType + OutType * 8 + HoldType * 64)
+ Chr(CharMode + NormalMode * 2 + AddLogo * 4 + ShowDate * 8 + ShowTime * 16 + ShowWeek * 32 + AddMessage * 64)
+ Chr(ShowingTime) + Chr(Speed) + LEDMessage;
check := 0;
for i := 1 to Length(tmp) do
check := check xor Ord(tmp[i]);
result := tmp + chr(check);
end;
end.
|
unit Options;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, checklst, ExtCtrls, Buttons, ColorGrd;
type
TOptions = record
Str : TColor;
Keyword : TColor;
BoolValue : TColor;
Rem : TColor;
Number : TColor;
Error : TColor;
BGColor : TColor;
NormalText : TColor;
end;
TfrmOptions = class(TForm)
ListEditColor: TListBox;
ColorGrid1: TColorGrid;
TabControl1: TTabControl;
ComboBox1: TComboBox;
GroupBox1: TGroupBox;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
CheckBox3: TCheckBox;
GroupBox2: TGroupBox;
Label1: TLabel;
Memo1: TMemo;
Button3: TButton;
Button4: TButton;
BitBtn1: TBitBtn;
BitBtn2: TBitBtn;
OutText: TLabel;
ComboBox2: TComboBox;
Label2: TLabel;
cbSel: TCheckBox;
procedure ListEditColorClick(Sender: TObject);
procedure ColorGrid1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure BitBtn2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure GroupBox2MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure BitBtn2Click(Sender: TObject);
procedure ComboBox1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure CheckBox2Click(Sender: TObject);
procedure CheckBox3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbSelClick(Sender: TObject);
private
public {home}
tmpEditorOptions : TOptions;
end;
Var
iTypeBold : Boolean;
iTypeItalic : Boolean;
iTypeUnderLine: Boolean;
frmOptions: TfrmOptions;
F:textFile;
implementation
uses Editor;
{$R *.DFM}
function BGColor:TColor;
begin
case frmOptions.ComboBox1.ItemIndex of
0 : BGColor := clWhite;
1 : BGColor := clBlue;
2 : BGColor := clBlack;
3 : BGCOlor := clAqua;
else BGColor:= clMenu;
end;
end;
function IndColor(SelColor:TColor):Byte;
begin
case SelColor of
clBlack : IndColor:=0;
clMaroon : IndColor:=1;
clGreen : IndColor:=2;
clOlive : IndColor:=3;
clNavy : IndColor:=4;
clPurple : IndColor:=5;
clTeal : IndColor:=6;
clGray : IndColor:=7;
clSilver : IndColor:=8;
clRed : IndColor:=9;
clLime : IndColor:=10;
clYellow : IndColor:=11;
clBlue : IndColor:=12;
clFuchsia: IndColor:=13;
clAqua : IndColor:=14;
else IndColor:=0;
end;
end;
procedure ReturnIndexColor;
begin
case frmOptions.ListEditColor.ItemIndex of
0: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.Str);
1: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.Keyword);
2: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.BoolValue);
3: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.Rem);
4: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.Number);
5: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.Error);
6: frmOptions.ColorGrid1.Foregroundindex:=IndColor(frmOptions.tmpEditorOptions.NormalText);
end;
end;
function SelColor(Ind:byte):TColor;
begin
case Ind of
0: SelColor:=clBlack;
1: SelColor:=clMaroon;
2: SelColor:=clGreen;
3: SelColor:=clOlive;
4: SelColor:=clNavy;
5: SelColor:=clPurple;
6: SelColor:=clTeal;
7: SelColor:=clGray;
8: SelColor:=clSilver;
9: SelColor:=clRed;
10: SelColor:=clLime;
11: SelColor:=clYellow;
12: SelColor:=clBlue;
13: SelColor:=clFuchsia;
14: SelColor:=clAqua;
else
SelColor:=clWhite;
end;
end;
procedure ShowColorPalette;
begin
Case frmOptions.ListEditColor.itemIndex of
0: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.Str;
1: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.Keyword;
2: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.BoolValue;
3: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.Rem;
4: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.Number;
5: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.Error;
6: frmOptions.OutText.Font.Color := frmOptions.tmpEditorOptions.NormalText;
End;
end;
procedure TfrmOptions.ListEditColorClick(Sender: TObject);
begin
ReturnIndexColor;
ShowColorPalette;
end;
procedure TfrmOptions.ColorGrid1Click(Sender: TObject);
begin
Case ListEditColor.itemIndex of
0: tmpEditorOptions.Str := SelColor(ColorGrid1.Foregroundindex);
1: tmpEditorOptions.Keyword := SelColor(ColorGrid1.Foregroundindex);
2: tmpEditorOptions.BoolValue := SelColor(ColorGrid1.Foregroundindex);
3: tmpEditorOptions.Rem := SelColor(ColorGrid1.Foregroundindex);
4: tmpEditorOptions.Number := SelColor(ColorGrid1.Foregroundindex);
5: tmpEditorOptions.Error := SelColor(ColorGrid1.Foregroundindex);
6: tmpEditorOptions.NormalText:= SelColor(ColorGrid1.Foregroundindex);
end;
ShowColorPalette;
end;
procedure TfrmOptions.Button1Click(Sender: TObject);
begin
frmEditor.EditorOptions.Str := tmpEditorOptions.Str;
frmEditor.EditorOptions.Keyword := tmpEditorOptions.Keyword;
frmEditor.EditorOptions.BoolValue := tmpEditorOptions.BoolValue;
frmEditor.EditorOptions.Rem := tmpEditorOptions.Rem;
frmEditor.EditorOptions.Number := tmpEditorOptions.Number;
frmEditor.EditorOptions.Error := tmpEditorOptions.Error;
frmEditor.EditorOptions.NormalText := tmpEditorOptions.NormalText;
{frmEditor.EditorOptions.KeyWord := tmpEditorOptions.KeyWord;
frmEditor.EditorOptions.NormalText := tmpEditorOptions.NormalText;
frmEditor.EditorOptions.Rem := tmpEditorOptions.Rem;
frmEditor.EditorOptions.Number := tmpEditorOptions.Number;
frmEditor.EditorOptions.Error := tmpEditorOptions.Error;
frmEditor.EditorOptions.Keyword := tmpEditorOptions.Identificator;}
frmOptions.Hide;
ProcessText;
end;
procedure TfrmOptions.BitBtn1Click(Sender: TObject);
var
TextStyle : TFontStyles;
begin
frmEditor.EditorOptions.Str := tmpEditorOptions.Str;
frmEditor.EditorOptions.Keyword := tmpEditorOptions.Keyword;
frmEditor.EditorOptions.BoolValue := tmpEditorOptions.BoolValue;
frmEditor.EditorOptions.Rem := tmpEditorOptions.Rem;
frmEditor.EditorOptions.Number := tmpEditorOptions.Number;
frmEditor.EditorOptions.Error := tmpEditorOptions.Error;
frmEditor.EditorOptions.NormalText := tmpEditorOptions.NormalText;
frmEditor.EditorOptions.BGColor := BGColor;
frmEditor.rtbEdit.Color:=BGColor;
frmEditor.rtbEdit.font.Name:=ComboBox2.Text;
frmEditor.rtbTemp.font.Name:=ComboBox2.Text;
TextStyle := [];
if iTypeBold then
TextStyle := TextStyle + [fsBold];
if iTypeItalic then
TextStyle := TextStyle + [fsItalic];
if iTypeUnderline then
TextStyle := TextStyle + [fsUnderline];
frmEditor.rtbEdit.Font.Style := TextStyle;
frmEditor.rtbTemp.Font.Style := TextStyle;
ProcessText;
frmOptions.Close;
end;
procedure TfrmOptions.BitBtn1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
BitBtn1.Font.Color:=clBlue;
BitBtn2.Font.Color:=clBlack;
end;
procedure TfrmOptions.BitBtn2MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
begin
BitBtn1.Font.Color:=clBlack;
BitBtn2.Font.Color:=clBlue;
end;
procedure TfrmOptions.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
BitBtn1.Font.Color:=clBlack;
BitBtn2.Font.Color:=clBlack;
end;
procedure TfrmOptions.GroupBox2MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
BitBtn1.Font.Color:=clBlack;
BitBtn2.Font.Color:=clBlack;
end;
procedure TfrmOptions.BitBtn2Click(Sender: TObject);
begin
frmOptions.Close;
end;
procedure TfrmOptions.ComboBox1Click(Sender: TObject);
begin
OutText.Color:=BGColor;
end;
procedure TfrmOptions.Button3Click(Sender: TObject);
var I : Byte;
CurWord : Byte;
begin
CurWord:=Memo1.Lines.Count;
frmEditor.EditorOptions.CurKeyWords:=CurWord;
for I:=0 to CurWord do
begin
frmEditor.EditorOptions.ListKeyWord[I]:=AnsiLowerCase(Memo1.Lines.Strings[I]);
end;
end;
procedure TfrmOptions.FormCreate(Sender: TObject);
var I:Integer;
begin
for I := 0 to Screen.Fonts.Count - 1 do
begin
ComboBox2.Items.Add(Screen.Fonts[i]);
end;
for I:=0 to frmEditor.EditorOptions.CurKeyWords do
begin
Memo1.Lines.Strings[I]:=frmEditor.EditorOptions.ListKeyWord[I];
end;
ComboBox1.ItemIndex := 4;
ComboBox2.ItemIndex := 0;
ListEditColor.ItemIndex:=0;
end;
procedure TfrmOptions.CheckBox1Click(Sender: TObject);
begin
iTypeBold := CheckBox1.Checked;
end;
procedure TfrmOptions.CheckBox2Click(Sender: TObject);
begin
iTypeItalic := CheckBox2.Checked;
end;
procedure TfrmOptions.CheckBox3Click(Sender: TObject);
begin
iTypeUnderLine := CheckBox3.Checked;
end;
procedure TfrmOptions.Button4Click(Sender: TObject);
var
F : TextFile;
sTemp : String;
J:Byte;
begin
J:=0;
AssignFile(F,'ini\keyword.ini');
Reset(F);
Memo1.Lines.Clear;
while Not eof(F) do
begin
Readln(F, sTemp);
frmEditor.EditorOptions.ListKeyWord[J] := AnsiLowerCase(sTemp);
Memo1.Lines.Add(sTemp);
Inc(J);
end;
frmEditor.EditorOptions.CurKeyWords:=J;
CloseFile(F);
end;
procedure TfrmOptions.FormShow(Sender: TObject);
begin
cbSel.Checked := fProcessText;
end;
procedure TfrmOptions.cbSelClick(Sender: TObject);
begin
fProcessText := cbSel.Checked;
end;
end.
|
unit VkApi.Types;
interface
{ display parameter }
type
TVkDisplayType = (dtPage, dtPopup, dtMobile);
{ versions }
type
TVkApiVersion = (av4_0, av4_1, av4_2, av4_3, av4_4, av4_5, av4_6, av4_7,
av4_8, av4_9, av4_91, av4_92, av4_93, av4_94, av4_95, av4_96, av4_97,
av4_98, av4_99, av4_100, av4_101, av4_102, av4_103, av4_104, av5_0, av5_1,
av5_2, av5_3, av5_4, av5_5, av5_6, av5_7, av5_8, av5_9, av5_10, av5_11,
av5_12, av5_13, av5_14, av5_15, av5_16, av5_17, av5_18, av5_19, av5_20,
av5_21, av5_22, av5_23, av5_24, av5_25, av5_26, av5_27);
{ TVkPermissions }
const
VKAPI_PERMISSION_NOTIFY = $000001; // 0 1
VKAPI_PERMISSION_FRIENDS = $000002; // 1 2
VKAPI_PERMISSION_PHOTOS = $000004; // 2 4
VKAPI_PERMISSION_AUDIO = $000008; // 3 8
VKAPI_PERMISSION_VIDEO = $000010; // 4 16
VKAPI_PERMISSION_OFFERS = $000020; // 5 32, obsolete
VKAPI_PERMISSION_QUESTIONS = $000040; // 6 64, obsolete
VKAPI_PERMISSION_PAGES = $000080; // 7 128
VKAPI_PERMISSION_LEFTMENULINK = $000100; // 8 256
// 9 512 - none
VKAPI_PERMISSION_STATUS = $000400; // 10 1024
VKAPI_PERMISSION_NOTES = $000800; // 11 2048
VKAPI_PERMISSION_MESSAGES = $001000; // 12 4096
VKAPI_PERMISSION_WALL = $002000; // 13 8192
// 14 16384 - none
VKAPI_PERMISSION_ADS = $008000; // 15 32768
VKAPI_PERMISSION_OFFLINE = $010000; // 16 65536
VKAPI_PERMISSION_DOCS = $020000; // 17 131072
VKAPI_PERMISSION_GROUPS = $040000; // 18 262144
VKAPI_PERMISSION_NOTIFICATIONS = $080000; // 19 524288
VKAPI_PERMISSION_STATS = $100000; // 20 1048576
// 21 2097152 - none
VKAPI_PERMISSION_EMAIL = $400000; // 22 4194304
// VKAPI_PERMISSION_NOHTTPS - ?
type
TVkPermission = (
vkpNotify,
vkpFriends,
vkpPhotos,
vkpAudio,
vkpVideo,
vkpOffers,
vkpQuestions,
vkpPages,
vkpLeftMenuLink,
vkpStatus,
vkpNotes,
vkpMessages,
vkpWall,
vkpAds,
vkpOffline,
vkpDocs,
vkpGroups,
vkpNotifications,
vkpStats,
vkpEmail,
vkpNoHttps
);
TVkPermissions = set of TVkPermission;
implementation
end.
|
unit UseFastStrings;
interface
uses sysutils,StrUtils,dhStrUtils;
const space=' ';
tabu=#9;
FormFeed=#12;
endl_main=#10;
endl_space=#13;
endl=endl_space+endl_main;
endl_main_offset=1;
const likespace=[space,tabu,formfeed,endl_main,endl_space];
function CopyStr(const aSourceString : String; aStart, aLength : Integer) : String;
function CopyWithout(const s:String; von,bis:integer): String; overload;
function CopyInsert(const s:String; von:integer; const Subst:String): String; overload;
function CopyInsert(const s:String; von,bis:integer; const Subst:String): String; overload;
procedure AbsDelete(var s:String; von,bis:integer);
function AbsCopy(const s:String; von,bis:integer):String;
function ExtractRawFileName(const s:TPathName):TPathName;
function SubEqual(const Substr,s:String; i:integer; StartFIND,LenFIND:integer):boolean; overload;
function SubEqual(const Substr,s:String; i,bs:integer):boolean; overload;
function SubEqual(const Substr,s:String; i:integer=1):boolean; overload;
function SubEqualEnd(const Substr,s:String):boolean;
function SubSame(const Substr,s:String; i:integer=1):boolean; overload;
function SubSame(const Substr,s:String; i,l:integer):boolean; overload;
function SubSameEnd(const Substr,s:String):boolean;
function AdvPos(const FindString, SourceString: String; StartPos: Integer=1): Integer;
function AdvPosAnsi(const FindString, SourceString: AnsiString; StartPos: Integer=1): Integer;
function bAdvPos(var r:integer; const FindString, SourceString: String; StartPos: Integer=1): boolean;
function bAdvPosAnsi(var r:integer; const FindString, SourceString: AnsiString; StartPos: Integer=1): boolean;
function AdvPosTil(const FindString, SourceString: String; StartPos,EndPos: Integer): Integer; overload;
function bAdvPosTil(var r:integer; const FindString, SourceString: String; StartPos,EndPos: Integer): boolean; overload;
function bAdvPosTil(var r:integer; const FindString, SourceString: String; StartPos,EndPos,StartFIND,LenFIND: Integer): boolean; overload;
function bAdvPosTilOver(var r:integer; const FindString, SourceString: String; StartPos,EndPos: Integer): boolean;
function AdvPosBack(const FindString, SourceString: String; StartPos: Integer): Integer;
function bAdvPosBack(var r:integer; const FindString, SourceString: String; StartPos: Integer): boolean;
function AdvPosBackTil(const FindString, SourceString: String; StartPos, EndPos: Integer): integer;
function bAdvPosBackTil(var r:integer; const FindString, SourceString: String; StartPos, EndPos: Integer): boolean; overload;
function bAdvPosBackTil(var r:integer; const FindString, SourceString: String; StartPos, EndPos,StartFIND,LenFIND: Integer): boolean; overload;
function LowerChar(ch:Char):Char; overload;
function AnsiSubstText(const Substr,durch, S: String): String;
function gethex(ch:Char):integer;
implementation
function FastPosBack(const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : Integer) : Integer;
var pResult,Buf:PChar;
begin
Result:=0;
Buf:=PChar(aSourceString);
pResult:=SearchBuf(Buf,aSourceLen,StartPos,0,aFindString,[soMatchCase]);
if pResult<>nil then
Result:=(pResult-PChar(aSourceString))+1;
end;
function FastPosBackTil(const aSourceString: String; aFindString : PChar; aSourceLen, aFindLen, StartPos: Integer; EndPos:integer) : Integer;//!!
var pResult,Buf:PChar;
begin
Result:=0;
Buf:=PChar(aSourceString);
Inc(Buf,EndPos-1);
Dec(aSourceLen,EndPos-1);
Dec(StartPos,EndPos-1);
pResult:=SearchBuf(Buf,aSourceLen,StartPos,0,aFindString,[soMatchCase]);
if pResult<>nil then
Result:=(pResult-PChar(aSourceString))+1;
end;
function FastPos(const aSourceString, aFindString : String; const aSourceLen, aFindLen, StartPos : Integer) : Integer;
var pResult,Buf:PChar;
begin
Result:=0;
Buf:=PChar(aSourceString);
pResult:=SearchBuf(Buf,aSourceLen,StartPos,0,aFindString,[soDown,soMatchCase]);
if pResult<>nil then
Result:=(pResult-PChar(aSourceString))+1;
end;
function FastPosAnsi(const aSourceString, aFindString : AnsiString; const aSourceLen, aFindLen, StartPos : Integer) : Integer;
var pResult,Buf:PAnsiChar;
begin
Result:=0;
Buf:=PAnsiChar(aSourceString);
pResult:=SearchBuf(Buf,aSourceLen,StartPos,0,aFindString,[soDown,soMatchCase]);
if pResult<>nil then
Result:=(pResult-PAnsiChar(aSourceString))+1;
end;
function SubEqual(const Substr,s:String; i:integer; StartFIND,LenFIND:integer):boolean; overload;
begin
//L=LenFIND
result:=not (LenFIND+i-1>length(s)) and ((LenFIND=0) or (StrLComp(PChar(Substr)+StartFIND-1,PChar(s)+i-1,LenFIND)=0));
end;
function SubEqual(const Substr,s:String; i,bs:integer):boolean;
var L:integer;
begin
L:=length(Substr);
result:=(bs-i=L) and not (L+i-1>length(s)) and ((L=0) or (StrLComp(PChar(Substr),PChar(Pointer(s))+i-1,L)=0));
end;
function SubEqual(const Substr,s:String; i:integer=1):boolean;
var L:integer;
begin
L:=length(Substr);
result:=not (L+i-1>length(s)) and ((L=0) or (StrLComp(PChar(Substr),PChar(Pointer(s))+i-1,L)=0));
end;
function SubEqualEnd(const Substr,s:String):boolean;
var i:integer;
begin
i:=length(s)+1-length(Substr);
result:=(i>=1) and SubEqual(Substr,s,i);
end;
function SubSameEnd(const Substr,s:String):boolean;
var i:integer;
begin
i:=length(s)+1-length(Substr);
result:=(i>=1) and SubSame(Substr,s,i);
end;
function SubSame(const Substr,s:String; i:integer=1):boolean;
var L:integer;
begin
L:=length(Substr);
result:=not (L+i-1>length(s)) and ((L=0) or (StrLIComp(PChar(Substr),PChar(Pointer(s))+i-1,L)=0));
end;
function SubSame(const Substr,s:String; i,l:integer):boolean;
begin
result:=not (L+i-1>length(s)) and ((L=0) or (StrLIComp(PChar(Substr),PChar(Pointer(s))+i-1,L)=0));
end;
function bAdvPosBack(var r:integer; const FindString, SourceString: String; StartPos: Integer): boolean;
begin
StartPos:=FastPosBack(SourceString,FindString,length(SourceString),length(FindString),StartPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function AdvPosBack(const FindString, SourceString: String; StartPos: Integer): Integer;
begin
result:=FastPosBack(SourceString,FindString,length(SourceString),length(FindString),StartPos);
end;
function AdvPosBackTil(const FindString, SourceString: String; StartPos, EndPos: Integer): integer;
begin
result:=FastPosBackTil(SourceString,PChar(FindString),length(SourceString),length(FindString),EndPos-length(FindString),StartPos);
end;
function AdvPos(const FindString, SourceString: String; StartPos: Integer): Integer;
begin
result:=PosEx(FindString,SourceString,StartPos);
end;
function AdvPosAnsi(const FindString, SourceString: AnsiString; StartPos: Integer): Integer;
begin
result:=FastPosAnsi(SourceString,FindString,Length(SourceString),Length(FindString),StartPos);
end;
function bAdvPos(var r:integer; const FindString, SourceString: String; StartPos: Integer): boolean;
begin
StartPos:=AdvPos(FindString,SourceString,StartPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function bAdvPosAnsi(var r:integer; const FindString, SourceString: AnsiString; StartPos: Integer): boolean;
begin
StartPos:=AdvPosAnsi(FindString,SourceString,StartPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function AdvPosTil(const FindString, SourceString: String; StartPos,EndPos: Integer): Integer;
begin
result:=FastPos(SourceString,FindString,EndPos-1,length(FindString),StartPos);
end;
function bAdvPosTil(var r:integer; const FindString, SourceString: String; StartPos,EndPos: Integer): boolean;
begin
StartPos:=AdvPosTil(FindString,SourceString,StartPos,EndPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function bAdvPosTilOver(var r:integer; const FindString, SourceString: String; StartPos,EndPos: Integer): boolean;
begin
StartPos:=AdvPosTil(FindString,SourceString,StartPos,EndPos);
result:=StartPos<>0;
if result then
r:=StartPos+Length(FindString);
end;
function bAdvPosTil(var r:integer; const FindString, SourceString: String; StartPos,EndPos,StartFIND,LenFIND: Integer): boolean; overload;
begin
assert(StartFIND+LenFIND-1<=length(FindString));
StartPos:=FastPos(SourceString,PChar(@FindString[StartFIND]),EndPos-1,LenFIND,StartPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function bAdvPosBackTil(var r:integer; const FindString, SourceString: String; StartPos, EndPos: Integer): boolean;
begin
StartPos:=FastPosBackTil(SourceString,PChar(FindString),length(SourceString),length(FindString),EndPos-length(FindString),StartPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function bAdvPosBackTil(var r:integer; const FindString, SourceString: String; StartPos, EndPos,StartFIND,LenFIND: Integer): boolean;
begin
StartPos:=FastPosBackTil(SourceString,@FindString[StartFIND],length(SourceString),LenFIND,EndPos-LenFIND,StartPos);
result:=StartPos<>0;
if result then
r:=StartPos;
end;
function CopyStr(const aSourceString : String; aStart, aLength : Integer) : String;
begin
Result:=Copy(aSourceString, aStart, aLength);
end;
function CopyInsert(const s:String; von:integer; const Subst:String): String;
begin
result:=abscopy(s,1,von)+Subst+abscopy(s,von,maxint);
end;
function CopyInsert(const s:String; von,bis:integer; const Subst:String): String;
begin
result:=abscopy(s,1,von)+Subst+abscopy(s,bis,maxint);
end;
function CopyWithout(const s:String; von,bis:integer): String;
begin
result:=s;
absdelete(result,von,bis);
end;
procedure AbsDelete(var s:String; von,bis:integer);
begin
assert(bis>=von);
delete(s,von,bis-von);
end;
function AbsCopy(const s:String; von,bis:integer):String;
begin
assert(bis>=von);
result:=Copy(s,von,bis-von);
end;
function LowerChar(ch:Char):Char;
begin
if CharInSet(ch,['A'..'Z']) then
result:=Char(ord(ch)-(ord('A')-ord('a'))) else
result:=ch;
end;
function ExtractRawFileName(const s:TPathName):TPathName;
begin
Result:=ChangeFileExt(ExtractFileName(s),'');
end;
function AnsiSubstText(const Substr,durch, S: String): String;
begin
result:=StringReplace(S,Substr,durch,[rfReplaceAll]);
end;
function gethex(ch:Char):integer;
begin
case ch of
'0'..'9': result:=ord(ch)-ord('0');
'a'..'f': result:=ord(ch)-ord('a')+10;
'A'..'F': result:=ord(ch)-ord('A')+10;
else result:=ord(space);
end;
end;
end.
|
unit DesFastReports;
interface
uses
Winapi.Windows, Winapi.ShellApi, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes, System.RegularExpressions,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
AArray, StrUtils, Data.DB,
ZAbstractRODataset, ZAbstractDataset, ZDataset, ZAbstractConnection, ZConnection,
frxClass, frxDBSet, frxDesgn, frxBarcode, frxBarcode2d,
frxExportBaseDialog, frxExportPDF, frxExportPDFHelpers,
DesUtils, AbraEntities;
type
TDesFastReport = class(TForm)
frxReport: TfrxReport;
frxPDFExport1: TfrxPDFExport;
frxBarCodeObject1: TfrxBarCodeObject;
qrAbraDPH: TZQuery;
qrAbraRadky: TZQuery;
fdsRadky: TfrxDBDataset;
fdsDPH: TfrxDBDataset;
procedure frxReportGetValue(const ParName: string; var ParValue: Variant);
procedure frxReportBeginDoc(Sender: TObject);
private
public
reportData: TAArray;
reportType,
exportDirName,
exportFileName,
fr3FileName,
invoiceId : string;
printCount : integer;
published
procedure init(pReportType, pFr3FileName : string);
procedure setExportDirName(newExportDirName : string);
procedure loadFr3File(iFr3FileName : string = '');
procedure prepareInvoiceDataSets(invoiceId : string; DocumentType : string = '03');
function createPdf(FullPdfFileName : string; OverwriteExistingPdf : boolean) : TDesResult;
function print: TDesResult;
procedure resetPrintCount;
end;
var
DesFastReport: TDesFastReport;
implementation
{$R *.dfm}
procedure TDesFastReport.init(pReportType, pFr3FileName : string);
begin
{ asi není potřeba oddalovat load FR3 souboru, tedy udělá se hned takto nazačátku
případně je možné nejdřív nastavit filename self.fr3FileName := pFr3FileName;
a později load pomocí self.loadFr3File(); }
self.reportType := pReportType; // zatím se nepoužívá, máme jen faktury, ale do budoucna
self.loadFr3File(pFr3FileName);
end;
procedure TDesFastReport.setExportDirName(newExportDirName : string);
begin
self.exportDirName := newExportDirName;
if not DirectoryExists(newExportDirName) then Forcedirectories(newExportDirName);
end;
{ Do reportu natáhne FR3 soubor, tím umožní práci s proměnnými atd
pokud je jako vstupní parametr náyev souboru, je použit tento nový soubor.
FR3 soubor může být umístěný buď přímo v adresáři s programem,
nebo v podadresáři FR3\
}
procedure TDesFastReport.loadFr3File(iFr3FileName : string = '');
var
fr3File : string;
begin
if iFr3FileName = '' then
iFr3FileName := self.fr3FileName
else
self.fr3FileName := iFr3FileName;
fr3File := DesU.PROGRAM_PATH + self.fr3FileName;
if not(FileExists(fr3File)) then
//fr3File := DesU.PROGRAM_PATH + '..\DE$_Common\resources\' + self.fr3FileName; //na disku p:, odkud se v praxi spouští, DE$_Common neni
fr3File := DesU.PROGRAM_PATH + 'FR3\' + self.fr3FileName;
if not(FileExists(fr3File)) then begin
MessageDlg('Nenalezen FR3 soubor ' + fr3File, mtError, [mbOk], 0);
// a měla by se ideálně vyhodit Exception a ta zpracovat na správném místě
end
else
frxReport.LoadFromFile(fr3File);
end;
function TDesFastReport.createPdf(FullPdfFileName : string; OverwriteExistingPdf : boolean) : TDesResult;
var
i : integer;
barcode: TfrxBarcode2DView;
begin
if FileExists(FullPdfFileName) AND (not OverwriteExistingPdf) then begin
Result := TDesResult.create('err', Format('Soubor %s už existuje.', [FullPdfFileName]));
Exit;
end else
DeleteFile(FullPdfFileName);
frxReport.PrepareReport;
with frxPDFExport1 do begin
FileName := FullPdfFileName;
Title := reportData['Title'];
Author := reportData['Author'];
{Set the PDF standard
TPDFStandard = (psNone, psPDFA_1a, psPDFA_1b, psPDFA_2a, psPDFA_2b, psPDFA_3a, psPDFA_3b);
It is required to add the frxExportPDFHelpers module to the uses list:
uses frxExportPDFHelpers;}
PDFStandard := psPDFA_1a; //PDF/A-1a satisfies all requirements in the specification
PDFVersion := pv14;
Compressed := True;
EmbeddedFonts := False;
{Disable export of objects with optimization for printing. With option enabled images will be high-quality but 9 times larger in volume}
//frxPDFExport1.PrintOptimized := False;
OpenAfterExport := False;
ShowDialog := False;
ShowProgress := False;
end;
frxReport.Export(frxPDFExport1);
//frxReport.ShowReport; // zobrazí report v samostatném okně, pro test hlavně
// čekání na soubor - max. 5s
for i := 1 to 50 do begin
if FileExists(FullPdfFileName) then Break;
Sleep(100);
end;
// hotovo
if not FileExists(FullPdfFileName) then
Result := TDesResult.create('err', Format('Nepodařilo se vytvořit soubor %s.', [fullPdfFileName]))
else begin
Result := TDesResult.create('ok', Format('Vytvořen soubor %s.', [fullPdfFileName]));
end;
end;
function TDesFastReport.print : TDesResult;
begin
try
frxReport.PrepareReport;
if printCount = 0 then
frxReport.PrintOptions.ShowDialog := true
else
frxReport.PrintOptions.ShowDialog := false;
frxReport.Print;
Result := TDesResult.create('ok', 'Tisk OK');
printCount := printCount + 1;
except on E: exception do
begin
Result := TDesResult.create('err', Format('%s (%s): Doklad %s se nepodařilo vytisknout. Chyba: %s',
[reportData['OJmeno'], reportData['VS'], reportData['Cislo'], E.Message]));
Exit;
end;
end;
end;
procedure TDesFastReport.resetPrintCount;
begin
self.printCount := 0;
end;
// ------------------------------------------------------------------------------------------------
procedure TDesFastReport.frxReportGetValue(const ParName: string; var ParValue: Variant);
// dosadí se proměné do formuláře
begin
if ParName = 'Value = 0' then Exit; //pro jistotu, ve fr3 souboru toto bylo v highlight.condition
try
ParValue := self.reportData[ParName];
except
on E: Exception do
ShowMessage('Chyba frxReportGetValue, parametr: ' + ParName + sLineBreak + e.Message);
end;
end;
procedure TDesFastReport.frxReportBeginDoc(Sender: TObject);
var
barcode: TfrxBarcode2DView;
begin
if reportData['QRText'] <> '' then begin // pokud AArray nemá klíč hledané hodnoty, value je vždy '', to testujeme
barcode := TfrxBarcode2DView(frxReport.FindObject('pQR'));
if Assigned(barcode) then
barcode.Text := reportData['QRText'];
end;
end;
procedure TDesFastReport.prepareInvoiceDataSets(invoiceId : string; DocumentType : string = '03');
begin
// řádky faktury
with qrAbraRadky do begin
Close;
if DocumentType = '10' then //'10' mají zálohové listy (ZL)
SQL.Text := 'SELECT Text, TAmount FROM IssuedDInvoices2'
+ ' WHERE Parent_ID = ' + Ap + invoiceId + Ap
+ ' ORDER BY PosIndex'
else // default '03', cteni z IssuedInvoices
SQL.Text := 'SELECT Text, TAmountWithoutVAT AS BezDane, VATRate AS Sazba, '
+ ' TAmount - TAmountWithoutVAT AS DPH, TAmount AS SDani FROM IssuedInvoices2'
+ ' WHERE Parent_ID = ' + Ap + invoiceId + Ap
+ ' AND NOT (RowType = 4 AND TAmount = 0)' // nebereme nulové zaokrouhlení
+ ' ORDER BY PosIndex';
Open;
end;
// rekapitulace DPH
with qrAbraDPH do begin
Close;
SQL.Text := 'SELECT VATRate AS Sazba, SUM(TAmountWithoutVAT) AS BezDane, '
+ ' SUM(TAmount - TAmountWithoutVAT) AS DPH, SUM(TAmount) AS SDani FROM IssuedInvoices2'
+ ' WHERE Parent_ID = ' + Ap + invoiceId + Ap
+ ' AND VATIndex_ID IS NOT NULL'
+ ' GROUP BY Sazba';
Open;
end;
qrAbraRadky.Close;
qrAbraDPH.Close;
end;
end.
|
unit uFrmOrderItem;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer,
cxEdit, cxTextEdit, cxMemo, Vcl.ExtCtrls, Vcl.StdCtrls, uJsonClass, uTaskManager, uGlobal;
type
TFrmOrderItem = class(TForm)
Panel1: TPanel;
cxMemo1: TcxMemo;
btnOk: TButton;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FrmOrderItem: TFrmOrderItem;
function fnShowOrderItem(AConnItem: TConnItem): Boolean;
implementation
{$R *.dfm}
function fnShowOrderItem(AConnItem: TConnItem): Boolean;
var
F: TFrmOrderItem;
vRoleItem: TRoleItem;
function fnGet订单类型(ACmdType: TTaskType): string;
begin
Result := '';
case ACmdType of
tt发货: Result := '发货';
tt分仓: Result := '分仓';
tt检库: Result := '检库';
tt邮件: Result := '邮件';
end;
end;
begin
Result := True;
if AConnItem.OrderItem = nil then Exit;
F := TFrmOrderItem.Create(Application);
try
F.cxMemo1.Lines.Clear;
F.cxMemo1.Lines.Add(Format('订单类型: %s', [fnGet订单类型(TTaskType(AConnItem.OrderItem.taskType))]));
F.cxMemo1.Lines.Add(Format('组 标 识: %s', [AConnItem.GroupName]));
F.cxMemo1.Lines.Add(Format('订单编号: %s', [AConnItem.OrderItem.orderNo]));
F.cxMemo1.Lines.Add(Format('大 区: %s', [AConnItem.OrderItem.GameArea]));
F.cxMemo1.Lines.Add(Format('服 务: %s', [AConnItem.OrderItem.GameSvr]));
for vRoleItem in AConnItem.OrderItem.roles do
begin
if AConnItem.OrderItem.taskType = Integer(tt分仓) then
begin
if vRoleItem.isMain then
F.cxMemo1.Lines.Add('转入转出: 转出')
else
F.cxMemo1.Lines.Add('转入转出: 转入');
end;
F.cxMemo1.Lines.Add(Format('订 单 ID: %d', [vRoleItem.rowId]));
F.cxMemo1.Lines.Add(Format('游戏账号: %s', [vRoleItem.Account]));
F.cxMemo1.Lines.Add(Format('游戏角色: %s', [vRoleItem.Role]));
F.cxMemo1.Lines.Add(Format('库 存: %d', [vRoleItem.stock]));
F.cxMemo1.Lines.Add(Format('对方角色: %s', [vRoleItem.receiptRole]));
F.cxMemo1.Lines.Add(Format('对方等级: %d', [vRoleItem.receiptLevel]));
F.cxMemo1.Lines.Add(Format('数 量: %d', [vRoleItem.sendNum]));
F.cxMemo1.Lines.Add(Format('订单状态: %d', [Integer(vRoleItem.taskState)]));
AddLogMsg('//-------------------------------------------------------------------', []);
end;
F.ShowModal;
finally
FreeAndNil(F);
end;
end;
end.
|
{ complete overstrike with carriage returns }
program overstrike (input, output);
const
ENDFILE = -1;
NEWLINE = 10; { ASCII value }
BLANK = 32;
BACKSPACE = 8;
CARRIAGERET = 13;
PLUS = 43;
type
character = -1..127; { ASCII, plus ENDFILE }
{ getc -- get one character from standard input }
function getc (var c : character) : character;
const
cr = #13;
var
ch : char;
begin
if (eof) then
c := ENDFILE
else if (eoln) then begin
read(ch);
if (ch = cr) then
c := CARRIAGERET
else
c := NEWLINE
end
else begin
read(ch);
c := ord(ch)
end;
getc := c
end;
{ putc -- put one character on standard output }
procedure putc (c : character);
begin
if (c = NEWLINE) then
writeln
else
write(chr(c))
end;
{ max -- compute maximum of two integers }
function max (x, y : integer) : integer;
begin
if (x > y) then
max := x
else
max := y
end;
{ overstrike -- convert backspaces into multiple lines }
procedure overstrike;
const
SKIP = BLANK;
NOSKIP = PLUS;
var
c : character;
col, newcol, i : integer;
markset : boolean;
begin
col := 1;
markset := false;
repeat
newcol := col;
while (getc(c) = BACKSPACE) do { eat backspaces }
newcol := max(newcol-1, 1);
if (newcol < col) then begin
putc(NEWLINE); { start overstrike line }
putc(NOSKIP);
for i := 1 to newcol-1 do
putc(BLANK);
col := newcol
end
else if (col = 1) and (c <> ENDFILE) and not (markset) then
putc(SKIP); { normal line}
{ else middle of line }
if (c <> ENDFILE) then begin
if (c = CARRIAGERET) then begin
putc(NEWLINE);
putc(NOSKIP);
markset := true
end
else begin
putc(c); { normal character}
markset := false
end;
if (c = NEWLINE) or (c = CARRIAGERET) then
col := 1
else
col := col + 1
end
until (c = ENDFILE)
end;
begin { main program }
overstrike
end.
|
unit FreeOTFEExplorerfrmPropertiesDlg_Multiple;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FreeOTFEExplorerfrmPropertiesDlg_Base, ExtCtrls, StdCtrls, ComCtrls;
type
TfrmPropertiesDialog_Multiple = class(TfrmPropertiesDialog_Base)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
MultipleItems: TStringList;
ParentDir: WideString;
end;
implementation
{$R *.dfm}
uses
SDUGeneral,
SDUGraphics,
SDUi18n,
SDFilesystem_FAT;
procedure TfrmPropertiesDialog_Multiple.FormCreate(Sender: TObject);
begin
inherited;
MultipleItems := TStringList.Create();
end;
procedure TfrmPropertiesDialog_Multiple.FormDestroy(Sender: TObject);
begin
MultipleItems.Free();
inherited;
end;
procedure TfrmPropertiesDialog_Multiple.FormShow(Sender: TObject);
var
totalSize: ULONGLONG;
totalDirCnt: integer;
totalFileCnt: integer;
tmpIcon: TIcon;
tmpSize: ULONGLONG;
tmpDirCnt: integer;
tmpFileCnt: integer;
i: integer;
allOK: boolean;
filenamesOnlyCommaText: string;
begin
inherited;
for i:=0 to (MultipleItems.count - 1) do
begin
if (filenamesOnlyCommaText <> '') then
begin
filenamesOnlyCommaText := filenamesOnlyCommaText + ', ';
end;
filenamesOnlyCommaText := filenamesOnlyCommaText + ExtractFilename(MultipleItems[i]);
end;
self.Caption := SDUParamSubstitute(
_('%1 Properties'),
[filenamesOnlyCommaText]
);
totalSize := 0;
totalDirCnt := 0;
totalFileCnt := 0;
for i:=0 to (MultipleItems.count - 1) do
begin
allOK := Filesystem.ItemSize(MultipleItems[i], tmpSize, tmpDirCnt, tmpFileCnt);
if not(allOK) then
begin
break;
end
else
begin
totalSize := totalSize + tmpSize;
totalDirCnt := totalDirCnt + tmpDirCnt;
totalFileCnt := totalFileCnt + tmpFileCnt;
end;
end;
// Change borders on "filename"; user can *never* edit it, so make it look
// more like a label
edFilename.BevelOuter := bvNone;
edFilename.BevelInner := bvNone;
edFilename.BorderStyle := bsNone;
edFilename.Text := SDUParamSubstitute(
_('%1 Files, %2 Folders'),
[
totalFileCnt,
totalDirCnt
]
);
edFileType.Caption := _('Multiple types');
edLocation.Caption := SDUParamSubstitute(_('All in %1'), [ParentDir]);
edSize.Caption := SDUParamSubstitute(
_('%1 (%2 bytes)'),
[
SDUFormatAsBytesUnits(totalSize, 2),
SDUIntToStrThousands(totalSize)
]
);
tmpIcon := TIcon.Create();
try
if SDULoadDLLIcon(
DLL_SHELL32,
FALSE,
DLL_SHELL32_MULTIPLE_FILES,
tmpIcon
) then
begin
imgFileType.Picture.Assign(tmpIcon)
end;
finally
tmpIcon.Free();
end;
end;
END.
|
unit uUtils;
interface
type
TUtils = class
private
function getExtensive(const pValue: string): string;
function getScale(const pScale: SmallInt): string;
public
function valueByExtensive(const pValue: Currency): string;
end;
implementation
uses
System.SysUtils,
System.Math,
System.StrUtils;
const
cSpace: string = ' ';
{ TUtils }
function TUtils.valueByExtensive(const pValue: Currency): string;
Const
cDivision: SmallInt = 3;
cCent: string = ' cent';
cCents: string = ' cents';
cDollar: string = ' dollar';
cDollars: string = ' dolars';
var
nDollars: Int64;
nCents: SmallInt;
nDivisions: SmallInt;
vIndex: Integer;
sDollars: string;
aDollars: TArray<String>;
sExtensive: string;
begin
nDollars := Trunc(pValue);
nCents := Trunc((pValue - nDollars) * 100);
sDollars := ReverseString(nDollars.ToString);
nDivisions := Ceil(Length(sDollars) / cDivision);
SetLength(aDollars,nDivisions);
for vIndex := nDivisions downto 1 do
aDollars[(nDivisions-vIndex)] := ReverseString(
Copy(sDollars,Succ(cDivision*Pred(vIndex)),cDivision));
sExtensive := EmptyStr;
for sDollars in aDollars do
begin
if (sExtensive <> EmptyStr) then
sExtensive := sExtensive + cSpace;
sExtensive := sExtensive + getExtensive(sDollars) + getScale(nDivisions);
Dec(nDivisions);
end;
if (nDollars > ZeroValue) then
begin
if (Trim(sExtensive) = 'one') then
sExtensive := sExtensive + cDollar
else
sExtensive := sExtensive + cDollars;
end;
if (nCents > ZeroValue) then
begin
if (nDollars > ZeroValue) then
sExtensive := sExtensive + ' and';
sExtensive := sExtensive + getExtensive(nCents.ToString);
if (nCents = 1) then
sExtensive := sExtensive + cCent
else
sExtensive := sExtensive + cCents;
end;
Result := Trim(sExtensive);
end;
function TUtils.getExtensive(const pValue: string): string;
const
cIndexCentena: SmallInt = 1;
cIndexDezena: SmallInt = 2;
cIndexUnidade: SmallInt = 3;
cUnit: TArray<string> = [
'one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen',
'seventeen', 'eighteen', 'nineteen'
];
cDicker: TArray<string> = [
'twenty', 'thirty', 'forty', 'fifty',
'sixty', 'seventy', 'eighty', 'ninety'
];
cHundred: string = 'hundred';
var
sValue: string;
sExtensive: string;
begin
sValue := pValue;
while (Length(sValue) < 3) do
sValue := '0' + sValue;
sExtensive := EmptyStr;
if (string(sValue[cIndexCentena]).ToInteger > 0) then
sExtensive := sExtensive + cUnit[Pred(string(sValue[cIndexCentena]).ToInteger)] +
cSpace + cHundred;
sExtensive := EmptyStr;
if (string(sValue[cIndexCentena]).ToInteger > 0) then
sExtensive := sExtensive + cUnit[Pred(string(sValue[cIndexCentena]).ToInteger)] +
cSpace + cHundred;
if (string(sValue[cIndexDezena]).ToInteger = 1) then
sExtensive := sExtensive + cSpace + cUnit[Pred(Copy(sValue,cIndexDezena).ToInteger)]
else
begin
if (string(sValue[cIndexDezena]).ToInteger > 1) then
sExtensive := sExtensive + cSpace + cDicker[(string(sValue[cIndexDezena]).ToInteger)-2];
if (string(sValue[cIndexUnidade]).ToInteger > 0) then
sExtensive := sExtensive + cSpace + cUnit[Pred(string(sValue[cIndexUnidade]).ToInteger)];
end;
Result := sExtensive;
end;
function TUtils.getScale(const pScale: SmallInt): string;
const
cScale: TArray<string> = [
'thousand', 'million', 'billion', 'trillion'
];
begin
if (pScale = 1) then
Exit(EmptyStr);
Result := cSpace + cScale[(pScale - 2)];
end;
end.
|
unit Aurelius.Drivers.SQLite.Classes;
{$I Aurelius.inc}
interface
uses
Classes, SysUtils,
Generics.Collections,
Aurelius.Drivers.SQLite.Import;
type
ESQLiteException = class(Exception)
end;
TSqliteStatement = class;
TSqliteDatabase = class
private
FHandle: Pointer;
FTransactionCount: integer;
procedure RaiseError(const msg: string);
public
constructor Create(const FileName: string);
destructor Destroy; override;
procedure ExecSQL(const sql: string);
procedure BeginTransaction;
procedure Commit;
procedure Rollback;
function InTransaction: boolean;
function Prepare(ASQL: string): TSQLiteStatement;
function GetLastInsertRowID: int64;
end;
TSQLiteFieldType = (stUnknown, stInteger, stFloat, stText, stBlob, stNull);
TSqliteStatement = class
private
FStmt: Pointer;
FDB: TSqliteDatabase;
FColumnNames: TStrings;
procedure CreateColumnNames;
public
constructor Create(ADatabase: TSQLiteDatabase; ASQL: string);
destructor Destroy; override;
procedure Execute;
function BindParameterIndex(AParamName: string): integer;
procedure BindInt64(AIndex: integer; AValue: Int64);
procedure BindDouble(AIndex: integer; AValue: double);
procedure BindText(AIndex: integer; AValue: string);
procedure BindBlob(AIndex: integer; AValue: TBytes);
function ColumnInt64(i: integer): Int64;
function ColumnText(i: integer): string;
function ColumnDouble(i: integer): double;
function ColumnBlob(i: integer): TBytes;
function ColumnIsNull(i: integer): boolean;
function ColumnType(i: integer): TSQLiteFieldType;
function ColumnIndex(AColumnName: string): integer;
function Next: boolean;
end;
implementation
{TSqliteDatabase}
constructor TSqliteDatabase.Create(const FileName: string);
begin
if not LoadSQLiteLibrary then
raise ESQLiteException.CreateFmt('Could not load SQLite library "%s', [SQLiteDLLName]);
if sqlite3_open16(PChar(FileName), FHandle) <> 0 then
RaiseError(Format('Database: %s', [FileName]));
end;
function TSqliteDatabase.Prepare(ASQL: string): TSQLiteStatement;
begin
Result := TSQLiteStatement.Create(Self, ASQL);
end;
destructor TSqliteDatabase.Destroy;
begin
sqlite3_close(FHandle);
inherited;
end;
procedure TSqliteDatabase.ExecSQL(const sql: string);
var
Stmt: TSQLiteStatement;
begin
Stmt := TSQLiteStatement.Create(Self, sql);
try
Stmt.Execute;
finally
Stmt.Free;
end;
end;
procedure TSqliteDatabase.BeginTransaction;
begin
ExecSQL('begin immediate');
Inc(FTransactionCount);
end;
procedure TSqliteDatabase.Commit;
begin
ExecSQL('commit');
Dec(FTransactionCount);
end;
procedure TSqliteDatabase.Rollback;
begin
ExecSQL('rollback');
Dec(FTransactionCount);
end;
procedure TSqliteDatabase.RaiseError(const msg: string);
var
errmsg: string;
begin
errmsg := sqlite3_errmsg16(FHandle);
if msg <> '' then
errmsg := Format('Error: %s%s%s', [errmsg, #13#10#13#10, msg]);
raise ESQLiteException.Create(errmsg)
end;
function TSqliteDatabase.GetLastInsertRowID: int64;
begin
result := sqlite3_last_insert_rowid(FHandle);
end;
function TSqliteDatabase.InTransaction: boolean;
begin
Result := FTransactionCount > 0;
end;
{ TSqliteStatement }
procedure TSqliteStatement.BindBlob(AIndex: integer; AValue: TBytes);
begin
sqlite3_bind_blob(FStmt, AIndex, @AValue[0], Length(AValue), SQLITE_TRANSIENT)
end;
procedure TSqliteStatement.BindDouble(AIndex: integer; AValue: double);
begin
sqlite3_bind_double(FStmt, AIndex, AValue);
end;
procedure TSqliteStatement.BindInt64(AIndex: integer; AValue: Int64);
begin
sqlite3_bind_int64(FStmt, AIndex, AValue);
end;
{$IFDEF NEXTGEN}
function TSqliteStatement.BindParameterIndex(AParamName: string): integer;
var
M: TMarshaller;
begin
Result := sqlite3_bind_parameter_index(FStmt, M.AsUtf8(AParamName).ToPointer);
if Result <= 0 then
raise ESQLiteException.CreateFmt('Could not bind parameter %s in SQL', [AParamName]);
end;
{$ELSE}
function TSqliteStatement.BindParameterIndex(AParamName: string): integer;
begin
Result := sqlite3_bind_parameter_index(FStmt, PAnsiChar(UTF8Encode(AParamName)));
if Result <= 0 then
raise ESQLiteException.CreateFmt('Could not bind parameter %s in SQL', [AParamName]);
end;
{$ENDIF}
procedure TSqliteStatement.BindText(AIndex: integer; AValue: string);
begin
sqlite3_bind_text16(FStmt, AIndex, PChar(AValue), Length(AValue) * SizeOf(Char), SQLITE_TRANSIENT);
end;
function TSqliteStatement.ColumnBlob(i: integer): TBytes;
var
Size: integer;
Buffer: Pointer;
begin
Buffer := sqlite3_column_blob(FStmt, i);
if Buffer = nil then
begin
SetLength(Result, 0);
Exit;
end;
Size := sqlite3_column_bytes16(FStmt, i);
SetLength(Result, Size);
System.Move(Buffer^, Result[0], Size);
end;
function TSqliteStatement.ColumnDouble(i: integer): double;
begin
Result := sqlite3_column_double(FStmt, i);
end;
function TSqliteStatement.ColumnIndex(AColumnName: string): integer;
begin
if FColumnNames = nil then
CreateColumnNames;
Result := FColumnNames.IndexOf(AColumnName);
end;
function TSqliteStatement.ColumnInt64(i: integer): Int64;
begin
Result := sqlite3_column_int64(FStmt, i);
end;
function TSqliteStatement.ColumnIsNull(i: integer): boolean;
begin
Result := ColumnType(i) = TSQLiteFieldType.stNull;
end;
function TSqliteStatement.ColumnText(i: integer): string;
begin
Result := sqlite3_column_text16(FStmt, i);
end;
function TSqliteStatement.ColumnType(i: integer): TSQLiteFieldType;
var
ColumnType: integer;
begin
ColumnType := sqlite3_column_type(FStmt, i);
if (ColumnType < 0) or (ColumnType > Ord(High(TSQLiteFieldType))) then
Result := TSQLiteFieldType.stUnknown
else
Result := TSQLiteFieldType(ColumnType);
end;
constructor TSqliteStatement.Create(ADatabase: TSQLiteDatabase; ASQL: string);
var
IgnoreNextStmt: Pchar;
begin
FDB := ADatabase;
if sqlite3_prepare16_v2(ADatabase.FHandle, PChar(ASQL), -1, Fstmt, IgnoreNextStmt) <> 0
then FDB.RaiseError(ASQL);
end;
procedure TSqliteStatement.CreateColumnNames;
var
c: Integer;
ColumnName: string;
ColumnCount: Integer;
begin
if FColumnNames = nil then
FColumnNames := TStringList.Create;
ColumnCount := sqlite3_column_count(FStmt);
for c := 0 to ColumnCount - 1 do
begin
ColumnName := sqlite3_column_name16(FStmt, c);
FColumnNames.Add(ColumnName);
end;
end;
destructor TSqliteStatement.Destroy;
begin
FColumnNames.Free;
sqlite3_finalize(FStmt);
inherited;
end;
procedure TSqliteStatement.Execute;
begin
Next;
end;
function TSqliteStatement.Next: boolean;
var
Status: integer;
begin
Status := sqlite3_step(Fstmt);
Result := False; // to avoid warnings
case Status of
SQLITE_ROW:
Result := True;
SQLITE_DONE:
Result := False;
else
FDB.RaiseError('');
end;
end;
end.
|
{: GLSMBASS<p>
BASS based sound-manager (http://www.un4seen.com/music/, free for freeware).<p>
Unsupported feature(s) :<ul>
<li>sound source velocity
<li>looping (sounds are played either once or forever)
<li>source priorities (not relevant, channels are not limited)
</ul><p>
<b>Historique : </b><font size=-1><ul>
<li>05/02/01 - Egg - Fixed TGLSMBASS.CPUUsagePercent
<li>13/01/01 - Egg - Creation (compat BASS 0.8)
</ul></font>
}
unit GLSMBASS;
interface
uses Classes, GLSound, GLScene;
type
// TBASS3DAlgorithm
//
TBASS3DAlgorithm = (algDefault, algOff, algFull, algLight);
// TGLSMBASS
//
TGLSMBASS = class (TGLSoundManager)
private
{ Private Declarations }
FAlgorithm3D : TBASS3DAlgorithm;
protected
{ Protected Declarations }
function DoActivate : Boolean; override;
procedure DoDeActivate; override;
procedure NotifyMasterVolumeChange; override;
procedure KillSource(aSource : TGLBaseSoundSource); override;
procedure UpdateSource(aSource : TGLBaseSoundSource); override;
procedure MuteSource(aSource : TGLBaseSoundSource; muted : Boolean); override;
procedure PauseSource(aSource : TGLBaseSoundSource; paused : Boolean); override;
public
{ Public Declarations }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure UpdateSources; override;
function CPUUsagePercent : Single; override;
published
{ Published Declarations }
property Algorithm3D : TBASS3DAlgorithm read FAlgorithm3D write FAlgorithm3D default algDefault;
end;
procedure Register;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
implementation
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
uses Forms, SysUtils, Bass, Geometry;
type
TBASSInfo = record
channel : HCHANNEL;
sample : HSAMPLE;
end;
PBASSInfo = ^TBASSInfo;
procedure Register;
begin
RegisterComponents('GLScene', [TGLSMBASS]);
end;
// VectorToBASSVector
//
procedure VectorToBASSVector(const aVector : TVector; var aBASSVector : BASS_3DVECTOR);
begin
with aBASSVector do begin
x:=aVector[0];
y:=aVector[1];
z:=-aVector[2];
end;
end;
// ------------------
// ------------------ TGLSMBASS ------------------
// ------------------
// Create
//
constructor TGLSMBASS.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
MaxChannels:=32;
end;
// Destroy
//
destructor TGLSMBASS.Destroy;
begin
inherited Destroy;
end;
// DoActivate
//
function TGLSMBASS.DoActivate : Boolean;
const
c3DAlgo : array [algDefault..algLight] of Integer =
(BASS_3DALG_DEFAULT, BASS_3DALG_OFF, BASS_3DALG_FULL, BASS_3DALG_LIGHT);
begin
BASS_Init(-1, OutputFrequency, BASS_DEVICE_3D, Application.Handle);
BASS_Start;
BASS_Set3DAlgorithm(c3DAlgo[FAlgorithm3D]);
Result:=True;
end;
// DoDeActivate
//
procedure TGLSMBASS.DoDeActivate;
begin
BASS_Stop;
BASS_Free;
end;
// NotifyMasterVolumeChange
//
procedure TGLSMBASS.NotifyMasterVolumeChange;
begin
BASS_SetVolume(Round(MasterVolume*100));
end;
// KillSource
//
procedure TGLSMBASS.KillSource(aSource : TGLBaseSoundSource);
var
p : PBASSInfo;
begin
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if p.channel<>0 then
if not BASS_ChannelStop(p.channel) then Assert(False);
BASS_SampleFree(p.sample);
FreeMem(p);
aSource.ManagerTag:=0;
end;
end;
// UpdateSource
//
procedure TGLSMBASS.UpdateSource(aSource : TGLBaseSoundSource);
var
i : Integer;
p : PBASSInfo;
objPos, objOri, objVel : TVector;
position, orientation, velocity : BASS_3DVECTOR;
begin
if (aSource.Sample=nil) or (aSource.Sample.Data.WAVDataSize=0) then Exit;
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if not BASS_ChannelIsActive(p.channel) then begin
aSource.Free;
Exit;
end;
end else begin
p:=AllocMem(SizeOf(TBASSInfo));
p.channel:=0;
if aSource.NbLoops>1 then
i:=BASS_SAMPLE_LOOP+BASS_SAMPLE_3D
else i:=BASS_SAMPLE_3D;
p.sample:=BASS_SampleLoad(True, aSource.Sample.Data.WAVData, 0, 0,
MaxChannels, i);
aSource.ManagerTag:=Integer(p);
end;
if aSource.Origin<>nil then begin
objPos:=aSource.Origin.AbsolutePosition;
objOri:=aSource.Origin.AbsoluteZVector;
objVel:=NullHmgVector;
end else begin
objPos:=NullHmgPoint;
objOri:=ZHmgVector;
objVel:=NullHmgVector;
end;
VectorToBASSVector(objPos, position);
VectorToBASSVector(objVel, velocity);
VectorToBASSVector(objOri, orientation);
if p.channel=0 then begin
p.channel:=BASS_SamplePlay3D(p.sample, position, orientation, velocity);
BASS_ChannelSet3DAttributes(p.channel, BASS_3DMODE_NORMAL,
aSource.MinDistance, aSource.MaxDistance,
Round(aSource.InsideConeAngle),
Round(aSource.OutsideConeAngle),
Round(aSource.ConeOutsideVolume*100));
end else BASS_ChannelSet3DPosition(p.channel, position, orientation, velocity);
if p.channel<>0 then
BASS_ChannelSetAttributes(p.channel, 0, Round(aSource.Volume*100), -101)
else aSource.Free;
end;
// MuteSource
//
procedure TGLSMBASS.MuteSource(aSource : TGLBaseSoundSource; muted : Boolean);
var
p : PBASSInfo;
begin
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if muted then
BASS_ChannelSetAttributes(p.channel, 0, 0, -101)
else BASS_ChannelSetAttributes(p.channel, 0, Round(aSource.Volume*100), -101);
end;
end;
// PauseSource
//
procedure TGLSMBASS.PauseSource(aSource : TGLBaseSoundSource; paused : Boolean);
var
p : PBASSInfo;
begin
if aSource.ManagerTag<>0 then begin
p:=PBASSInfo(aSource.ManagerTag);
if paused then
BASS_ChannelPause(p.channel)
else BASS_ChannelResume(p.channel);
end;
end;
// UpdateSources
//
procedure TGLSMBASS.UpdateSources;
var
objPos, objVel, objDir, objUp : TVector;
position, velocity, fwd, top : BASS_3DVECTOR;
begin
// update listener
ListenerCoordinates(objPos, objVel, objDir, objUp);
VectorToBASSVector(objPos, position);
VectorToBASSVector(objVel, velocity);
VectorToBASSVector(objDir, fwd);
VectorToBASSVector(objUp, top);
BASS_Set3DPosition(position, velocity, fwd, top);
// update sources
inherited;
BASS_Apply3D;
end;
// CPUUsagePercent
//
function TGLSMBASS.CPUUsagePercent : Single;
begin
Result:=BASS_GetCPU*100;
end;
end.
|
// -------------------------------------------------------------------------------------------------
// Demo program for Html2Pdf.pas.
// You must have HTMLVIEW components by L. David Baldwin installed to open this in IDE.
// This demo origin was written by Pawel Stroinski on 2010/07/07 and is public domain.
// Revisioned by Muzio Valerio on 2019/07/01 and is public domain.
// -------------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------------
// New implementation 2021/04/24
// written by Muzio Valerio
// -------------------------------------------------------------------------------------------------
unit uMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls,
Vcl.Forms, Vcl.Dialogs, vmHtmlToPdf, Vcl.StdCtrls, htmlview, System.IniFiles, Winapi.ShellAPI, Vcl.Printers, HTMLUn2,
framview, FramBrwz, System.ImageList, Vcl.ImgList, Vcl.VirtualImageList, Vcl.BaseImageCollection, Vcl.ImageCollection,
Vcl.ExtCtrls, System.StrUtils, System.IOUtils, System.UITypes;
type
TMainForm = class(TForm)
OpenDialog: TOpenDialog;
Viewer: THTMLViewer;
btnSave: TButton;
btnSaveAs: TButton;
lPDF: TLabel;
SaveDialog: TSaveDialog;
cxOpenAfterSave: TCheckBox;
edMarginLeft: TEdit;
edMarginTop: TEdit;
edMarginRight: TEdit;
edMarginBottom: TEdit;
cxScaleToFit: TCheckBox;
cbOrientation: TComboBox;
cbPaperSize: TComboBox;
btnSynopse: TButton;
cxPrintPage: TCheckBox;
btnSave2: TButton;
lbMargins: TLabel;
lPageFormat: TLabel;
lPageOrientation: TLabel;
lLeft: TLabel;
lTop: TLabel;
lRight: TLabel;
lBottom: TLabel;
lPageNumberPosition: TLabel;
cbPositionPrint: TComboBox;
btnHtmlViewer: TButton;
btnLoadHtml: TButton;
edtFileHtml: TButtonedEdit;
ImgColl: TImageCollection;
VirtualImgLst: TVirtualImageList;
procedure FormCreate(Sender: TObject);
procedure btnSave2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnSaveClick(Sender: TObject);
procedure btnSaveAsClick(Sender: TObject);
procedure btnSynopseClick(Sender: TObject);
procedure btnHtmlViewerClick(Sender: TObject);
procedure btnLoadHtmlClick(Sender: TObject);
procedure edtFileHtmlRightButtonClick(Sender: TObject);
private
{ Private declarations }
FSaveTo: Integer;
FSettings: TMemIniFile;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
uses SynPdf;
{$R *.dfm}
procedure TMainForm.btnSave2Click(Sender: TObject);
var
lFileName: TFileName;
lHtmlToPdf: TvmHtmlToPdfGDI;
begin
if lPDF.Caption = '' then
begin
FSaveTo := 2;
btnSaveAsClick(nil);
end
else
begin
lFileName := lPDF.Caption;
lHtmlToPdf := TvmHtmlToPdfGDI.Create();
try
lHtmlToPdf.PDFMarginLeft := StrToFloat(edMarginLeft.Text);
lHtmlToPdf.PDFMarginTop := StrToFloat(edMarginTop.Text);
lHtmlToPdf.PDFMarginRight := StrToFloat(edMarginRight.Text);
lHtmlToPdf.PDFMarginBottom := StrToFloat(edMarginBottom.Text);
lHtmlToPdf.PDFScaleToFit := cxScaleToFit.Checked;
lHtmlToPdf.PrintOrientation := TPrinterOrientation(cbOrientation.ItemIndex);
lHtmlToPdf.DefaultPaperSize := TPDFPaperSize(cbPaperSize.ItemIndex);
lHtmlToPdf.SrcViewer := Self.Viewer;
lHtmlToPdf.PrintPageNumber := cxPrintPage.Checked;
lHtmlToPdf.TextPageNumber := ExtractFileName(edtFileHtml.Text) + ' - Page %d/%d';
case cbPositionPrint.ItemIndex of
0: lHtmlToPdf.PageNumberPositionPrint := ppBottom;
1: lHtmlToPdf.PageNumberPositionPrint := ppTop;
end;
lHtmlToPdf.Execute;
lHtmlToPdf.SaveToFile(lFileName);
finally
lHtmlToPdf.Free;
end;
if cxOpenAfterSave.Checked then
ShellExecute(Handle, 'open', PChar(lFileName), nil, nil, SW_SHOWNORMAL)
end;
end;
procedure TMainForm.btnSaveAsClick(Sender: TObject);
begin
SaveDialog.InitialDir := ExtractFileDir(lPDF.Caption);
SaveDialog.FileName := ChangeFileExt(ExtractFileName(edtFileHtml.Text), '');
if SaveDialog.Execute then
begin
lPDF.Caption := SaveDialog.FileName;
case FSaveTo of
1: btnSaveClick(nil);
2: btnSave2Click(nil);
end;
end;
end;
procedure TMainForm.btnSaveClick(Sender: TObject);
var
FN: TFileName;
lHtml2Pdf: TvmHtmlToPdf;
begin
if lPDF.Caption = '' then
begin
FSaveTo := 1;
btnSaveAsClick(nil);
end
else
begin
FN := lPDF.Caption;
lHtml2Pdf := TvmHtmlToPdf.Create();
try
lHtml2Pdf.PDFMarginLeft := StrToFloat(edMarginLeft.Text);
lHtml2Pdf.PDFMarginTop := StrToFloat(edMarginTop.Text);
lHtml2Pdf.PDFMarginRight := StrToFloat(edMarginRight.Text);
lHtml2Pdf.PDFMarginBottom := StrToFloat(edMarginBottom.Text);
lHtml2Pdf.PDFScaleToFit := cxScaleToFit.Checked;
lHtml2Pdf.PrintOrientation := TPrinterOrientation(cbOrientation.ItemIndex);
lHtml2Pdf.DefaultPaperSize := TPDFPaperSize(cbPaperSize.ItemIndex);
lHtml2Pdf.SrcViewer := Self.Viewer;
lHtml2Pdf.PrintPageNumber := cxPrintPage.Checked;
lHtml2Pdf.TextPageNumber := ExtractFileName(edtFileHtml.Text)+ ' - Page %d/%d';
case cbPositionPrint.ItemIndex of
0: lHtml2Pdf.PageNumberPositionPrint := ppBottom;
1: lHtml2Pdf.PageNumberPositionPrint := ppTop;
end;
lHtml2Pdf.Execute;
lHtml2Pdf.SaveToFile(FN);
finally
lHtml2Pdf.Free;
end;
if cxOpenAfterSave.Checked then
ShellExecute(Handle, 'open', PChar(FN), nil, nil, SW_SHOWNORMAL)
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FSettings := TMemIniFile.Create(ChangeFileExt(Application.ExeName, '.ini'));
edtFileHtml.Text := FSettings.ReadString('Settings', 'HTML', '');
lPDF.Caption := FSettings.ReadString('Settings', 'PDF', '');
cxOpenAfterSave.Checked := FSettings.ReadBool('Settings', 'OpenAfterSave', True);
cxScaleToFit.Checked := FSettings.ReadBool('Settings', 'ScaleToFit', False);
cbOrientation.ItemIndex := FSettings.ReadInteger('Settings', 'Orientation', 0);
cbPaperSize.ItemIndex := FSettings.ReadInteger('Settings', 'PaperSize', 0);
edMarginLeft.Text := FloatToStr(FSettings.ReadFloat('Margins', 'Left', 1));
edMarginTop.Text := FloatToStr(FSettings.ReadFloat('Margins', 'Top', 1));
edMarginRight.Text := FloatToStr(FSettings.ReadFloat('Margins', 'Right', 1));
edMarginBottom.Text := FloatToStr(FSettings.ReadFloat('Margins', 'Bottom', 1));
cxPrintPage.Checked := FSettings.ReadBool('Margins', 'PrintPage', False);
cbPositionPrint.ItemIndex := FSettings.ReadInteger('Margins', 'PositionPage', 0);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FSettings.WriteString('Settings', 'HTML', edtFileHtml.Text);
FSettings.WriteString('Settings', 'PDF', lPDF.Caption);
FSettings.WriteBool('Settings', 'OpenAfterSave', cxOpenAfterSave.Checked);
FSettings.WriteBool('Settings', 'ScaleToFit', cxScaleToFit.Checked);
FSettings.WriteInteger('Settings', 'Orientation', cbOrientation.ItemIndex);
FSettings.WriteInteger('Settings', 'PaperSize', cbPaperSize.ItemIndex);
FSettings.WriteFloat('Margins', 'Left', StrToFloat(edMarginLeft.Text));
FSettings.WriteFloat('Margins', 'Top', StrToFloat(edMarginTop.Text));
FSettings.WriteFloat('Margins', 'Right', StrToFloat(edMarginRight.Text));
FSettings.WriteFloat('Margins', 'Bottom', StrToFloat(edMarginBottom.Text));
FSettings.WriteBool('Margins','PrintPage', cxPrintPage.Checked);
FSettings.WriteInteger('Margins', 'PositionPage', cbPositionPrint.ItemIndex);
FSettings.UpdateFile;
FreeAndNil(FSettings);
end;
procedure TMainForm.btnSynopseClick(Sender: TObject);
begin
ShellExecute(Handle,'open','http://synopse.info',nil,nil,SW_SHOWNORMAL);
end;
procedure TMainForm.btnHtmlViewerClick(Sender: TObject);
begin
ShellExecute(Handle, 'open', 'https://github.com/BerndGabriel/HtmlViewer', nil, nil, SW_SHOWNORMAL);
end;
procedure TMainForm.btnLoadHtmlClick(Sender: TObject);
var
SrcFileExt: string;
begin
if Trim(edtFileHtml.Text) = '' then
begin
MessageDlg('selezionare un file da caricare', mtInformation, [mbOK], -1);
Exit;
end;
SrcFileExt := ExtractFileExt(edtFileHtml.Text).ToLower;
case IndexText(SrcFileExt, ['.html', '.htm']) of
0..1: Viewer.LoadFromFile(edtFileHtml.Text);
end;
end;
procedure TMainForm.edtFileHtmlRightButtonClick(Sender: TObject);
begin
OpenDialog.InitialDir := ExtractFileDir(edtFileHtml.Text);
OpenDialog.FileName := ExtractFileName(edtFileHtml.Text);
if OpenDialog.Execute then
edtFileHtml.Text := OpenDialog.FileName;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Sockets, Spin;
type
TForm1 = class(TForm)
mLista: TMemo;
btTesta: TButton;
edServer: TEdit;
Label1: TLabel;
lbStatus: TLabel;
btChega: TButton;
Timer1: TTimer;
btTimer: TButton;
edPortaIni: TEdit;
edPortaFin: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
cbSincron: TCheckBox;
cbRefresh: TCheckBox;
edPMT: TSpinEdit;
cbProcess: TCheckBox;
cbRepaint: TCheckBox;
procedure btTestaClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btChegaClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure btTimerClick(Sender: TObject);
procedure cbRefreshClick(Sender: TObject);
private
FAbort: Boolean; // para saber se vamos parar no meio do loop
FPortaTimer: Integer; // o contador interno do timer
procedure Testar(porta: Integer);
public
function PORTA_INI: Integer;
function PORTA_FIN: Integer;
function PROCESS_MESSAGES_TIMEOUT: Integer;
end;
var
Form1: TForm1;
implementation
uses uThreads;
{$R *.dfm}
procedure TForm1.btTestaClick(Sender: TObject);
var
port: Integer;
begin
FAbort := False;
FPortaTimer := PORTA_INI;
for port := PORTA_INI to PORTA_FIN do
begin
if FAbort then
begin
Break; // close;
end;
try
Testar(port);
except
end;
if cbRefresh.Checked then
if (port mod PROCESS_MESSAGES_TIMEOUT) = 0 then
begin
if cbProcess.Checked then
Application.ProcessMessages;
if cbRepaint.Checked then
Repaint;
end;
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Self.DoubleBuffered := True; // para evitar o flicker da tela
FAbort := False; // inicializa como falso para comešar a processar
FPortaTimer := PORTA_INI; // Inteiro que define a porta atual do controle por timer
end;
procedure TForm1.btChegaClick(Sender: TObject);
begin
FAbort := True;
end;
procedure TForm1.Testar(porta: Integer);
begin
lbStatus.Caption := 'testando ' + IntToStr(porta);
TPortScanner.Create(edServer.Text, IntToStr(porta), mLista, cbSincron.Checked);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if FAbort then
begin
Timer1.Enabled := False; // close;
end;
Testar(FPortaTimer);
Inc(FPortaTimer);
if FPortaTimer >= PORTA_FIN then
Timer1.Enabled := False;
end;
procedure TForm1.btTimerClick(Sender: TObject);
begin
FAbort := False;
FPortaTimer := PORTA_INI;
Timer1.Enabled := True;
end;
function TForm1.PORTA_FIN: Integer;
begin
Result := StrToInt(edPortaFin.Text);
end;
function TForm1.PORTA_INI: Integer;
begin
Result := StrToInt(edPortaIni.Text);
end;
function TForm1.PROCESS_MESSAGES_TIMEOUT: Integer;
begin
Result := StrToInt(edPMT.Text);
end;
procedure TForm1.cbRefreshClick(Sender: TObject);
begin
if not cbRefresh.Checked then
begin
cbProcess.Checked := False;
cbRepaint.Checked := False;
cbProcess.Enabled := False;
cbRepaint.Enabled := False;
end
else
begin
cbProcess.Enabled := True;
cbRepaint.Enabled := True;
end;
end;
end.
|
unit LblEditMoney;
interface
Uses SysUtils,StdCtrls,Classes,Buttons,Controls,ExtCtrls,Menus,
Messages,SQLCtrls,DBTables,WinTypes,TSQLCls,EditMoney;
Type TLblEditMoney=class(TSQLControl)
protected
FOnKeyUp:TKeyEvent;
procedure WriteCaption(s:string);
Function ReadCaption:String;
procedure WriteText(s:string);
Function ReadText:String;
procedure WriteOnChange(s:TNotifyEvent);
Function ReadOnChange:TNotifyEvent;
procedure WritePC(s:boolean);
Function ReadPC:boolean;
procedure WriteRO(s:boolean);
Function ReadRO:boolean;
procedure WriteML(s:integer);
Function ReadML:integer;
procedure LEOnEnter(Sender:TObject);
Function ReadAlignment:TAlignment;
procedure WriteAlignment(s:TAlignment);
public
BackUp:String;
Data:longint;
Lbl:TLabel;
EditMoney:TEditMoney;
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure WMSize(var Msg:TMessage); message WM_SIZE;
function GetHeight:integer;
procedure Value(sl:TStringList); override;
procedure SetValue(var q:TQuery); override;
procedure LEOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
published
property Alignment:TAlignment read ReadAlignment write WriteAlignment;
property Caption:String read ReadCaption write WriteCaption;
property Text:String read ReadText write WriteText;
property ParentColor:boolean read ReadPC write WritePC;
property ReadOnly:boolean read ReadRO write WriteRO;
property OnChange:TNotifyEvent read ReadOnChange write WriteOnChange;
property OnKeyUp:TKeyEvent read FOnKeyUp write FOnKeyUp;
property MaxLength:integer read ReadML write WriteML;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
end;
procedure Register;
implementation
function TLblEditMoney.GetHeight:integer;
begin
GetHeight:=-EditMoney.Font.Height+13-Lbl.Font.Height
end;
destructor TLblEditMoney.Destroy;
begin
Lbl.Free;
EditMoney.Free;
inherited Destroy
end;
constructor TLblEditMoney.Create(AOwner:TComponent);
begin
FOnKeyUp:=NIL;
inherited create(AOwner);
Lbl:=TLabel.Create(self);
EditMoney:=TEditMoney.Create(self);
Lbl.Parent:=self;
EditMoney.Parent:=self;
Lbl.Left:=0;
Lbl.Top:=0;
EditMoney.Left:=0;
OnEnter:=LEOnEnter;
EditMoney.OnKeyUp:=LEOnKeyUp
end;
procedure TLblEditMoney.Value(sl:TStringList);
begin
if Assigned(fValueEvent) then fValueEvent(self,sl)
else
if Visible then sl.Add(sql.MakeStr(Text))
else sl.Add('NULL')
end;
procedure TLblEditMoney.SetValue(var q:TQuery);
begin
if Assigned(fSetValueEvent) then fSetValueEvent(self,q)
else
try
Text:=q.FieldByName(fFieldName).AsString;
except
end;
end;
procedure TLblEditMoney.WMSize(var Msg:TMessage);
begin
Lbl.Height:=-Lbl.Font.Height+3;
Lbl.Width:=Msg.LParamLo;
EditMoney.Top:=Lbl.Height;
EditMoney.Height:=-EditMoney.Font.Height+10;
EditMoney.Width:=Msg.LParamLo;
Height:=EditMoney.Height+Lbl.Height;
Width:=Msg.LParamLo;
end;
procedure TLblEditMoney.WriteCaption(s:String);
begin
Lbl.Caption:=s
end;
function TLblEditMoney.ReadCaption:String;
begin
ReadCaption:=Lbl.Caption
end;
procedure TLblEditMoney.WritePC(s:boolean);
begin
EditMoney.ParentColor:=s
end;
function TLblEditMoney.ReadPC:boolean;
begin
ReadPC:=EditMoney.ParentColor
end;
procedure TLblEditMoney.WriteRO(s:boolean);
begin
EditMoney.ReadOnly:=s
end;
function TLblEditMoney.ReadRO:boolean;
begin
ReadRO:=EditMoney.ReadOnly
end;
procedure TLblEditMoney.WriteML(s:integer);
begin
EditMoney.MaxLength:=s
end;
function TLblEditMoney.ReadML:integer;
begin
ReadML:=EditMoney.MaxLength
end;
procedure TLblEditMoney.WriteText(s:String);
begin
EditMoney.Text:=s
end;
function TLblEditMoney.ReadText:String;
begin
ReadText:=EditMoney.Text
end;
procedure TLblEditMoney.WriteOnChange(s:TNotifyEvent);
begin
EditMoney.OnChange:=s
end;
function TLblEditMoney.ReadOnChange:TNotifyEvent;
begin
ReadOnChange:=EditMoney.OnChange
end;
procedure Register;
begin
RegisterComponents('asd',[TLblEditMoney])
end;
procedure TLblEditMoney.LEOnEnter(Sender:TObject);
begin
EditMoney.SetFocus;
BackUp:=EditMoney.Text
end;
procedure TLblEditMoney.LEOnKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=VK_ESCAPE then
EditMoney.Text:=BackUp;
if Assigned(fOnKeyUp) then
fOnKeyUp(Sender, Key, Shift);
end;
Function TLblEditMoney.ReadAlignment;
begin
ReadAlignment:=EditMoney.Alignment;
end;
procedure TLblEditMoney.WriteAlignment(s:TAlignment);
begin
EditMoney.Alignment:=s;
end;
end.
|
unit MemCheck;
interface
uses Windows, SysUtils;
implementation
var
GetMemCount: Integer;
OldMemMgr: TMemoryManager;
function NewGetMem(Size: Integer): Pointer;
begin
if Size>0 then Inc(GetMemCount);
Result := OldMemMgr.GetMem(Size);
end;
function NewFreeMem(P: Pointer): Integer;
begin
if P<>nil then Dec(GetMemCount);
Result := OldMemMgr.FreeMem(P);
end;
function NewReallocMem(P: Pointer; Size: Integer): Pointer;
begin
if (Size=0) and (P<>nil) then
begin
Dec(GetMemCount);
end else if (Size>0) and (P<>nil) then
begin
Dec(GetMemCount);
Inc(GetMemCount);
end else
Inc(GetMemCount);
Result := OldMemMgr.ReallocMem(P, Size);
end;
const
NewMemMgr: TMemoryManager = (
GetMem: NewGetMem;
FreeMem: NewFreeMem;
ReallocMem: NewReallocMem);
initialization
GetMemoryManager(OldMemMgr);
SetMemoryManager(NewMemMgr);
finalization
SetMemoryManager(OldMemMgr);
if GetMemCount>0 then
MessageBox(0, PChar(Format('%d 回メモリーを解放し忘れています', [GetMemCount])), 'メモリーリークエラー', MB_OK or MB_ICONEXCLAMATION);
end.
|
{-----------------------------------------------------------------------------
Unit Name: RbButton
Purpose: Fade in/out gradient button
Author/Copyright: NathanaŽl VERON - r.b.a.g@free.fr - http://r.b.a.g.free.fr
Feel free to modify and improve source code, mail me (r.b.a.g@free.fr)
if you make any big fix or improvement that can be included in the next
versions. If you use the RbControls in your project please
mention it or make a link to my website.
===============================================
/* 03/09/2003 */
Correction of a bug in the ModalResult property
/* 30/09/2003 */
Correction of a graphic bug when clicking
/* 13/11/2003 */
Modifications for D5 compatibility
thx to Pierre Castelain -> www.micropage.fr.st
/* 08/12/2003 */
Added Down, AllowAllUp and GroupIndex property
for SpeedButton like behaviour.
-----------------------------------------------------------------------------}
unit RbButton;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Graphics, ExtCtrls, RbDrawCore,
Buttons, Forms;
type
TRbButton = class(TRbCustomControl)
private
FColors : TRbControlColors;
FGrBitmap: TBitmap;
FGrMouseOver: TBitmap;
FGrClicked: TBitmap;
FGlyph : TBitmap;
FLayout : TButtonLayout;
FModalResult: TModalResult;
FSpacing: integer;
FShowFocusRect : boolean;
FHotTrack : boolean;
FDefault: boolean;
FCancel : boolean;
FGradientBorder: boolean;
FDown: boolean;
FAllowAllUp: boolean;
FGroupIndex: integer;
FGradientType: TGradientType;
FFadeSpeed: TFadeSpeed;
procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY;
procedure SetGlyph(const Value: TBitmap);
procedure SetSpacing(const Value: integer);
procedure SetLayout(const Value: TButtonLayout);
procedure SetFadeSpeed(const Value: TFadeSpeed);
procedure SetFocusRect(const Value: boolean);
procedure SetHotTrack(const Value: boolean);
procedure SetDefault(const Value: boolean);
procedure SetAllowAllUp(const Value: boolean);
procedure SetDown(const Value: boolean);
procedure SetGroupIndex(const Value: integer);
procedure DeActivateSiblings;
function CanBeUp: boolean;
procedure SetGradientType(const Value: TGradientType);
protected
procedure Paint; override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure EventResized; override;
procedure EventMouseEnter; override;
procedure EventMouseLeave; override;
procedure EventMouseDown; override;
procedure EventMouseUp; override;
procedure EventFocusChanged; override;
procedure UpdateGradients; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Click; override;
published
property Caption;
property ModalResult : TModalResult read FModalResult write FModalResult;
property Glyph: TBitmap read FGlyph write SetGlyph;
property Spacing: integer read FSpacing write SetSpacing;
property Layout: TButtonLayout read FLayout write SetLayout;
property Colors : TRbControlColors read FColors write FColors;
property FadeSpeed : TFadeSpeed read FFadeSpeed write SetFadeSpeed;
property ShowFocusRect : boolean read FShowFocusRect write SetFocusRect;
property HotTrack: boolean read FHotTrack write SetHotTrack;
property Default : boolean read FDefault write SetDefault default false;
property Cancel : boolean read FCancel write FCancel default false;
property GradientBorder: boolean read FGradientBorder write FGradientBorder;
property GroupIndex: integer read FGroupIndex write SetGroupIndex;
property AllowAllUp: boolean read FAllowAllUp write SetAllowAllUp;
property Down : boolean read FDown write SetDown;
property GradientType: TGradientType read FGradientType write SetGradientType;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('RbControls', [TRbButton]);
end;
{---------------------------------------------
TRbButton
---------------------------------------------}
procedure TRbButton.Paint;
var
R : TRect;
Flags: integer;
FinalBitmap: TBitmap;
Gl : TBitmap;
begin
inherited;
FinalBitmap := TBitmap.Create;
try
FinalBitmap.PixelFormat := pf24bit;
FinalBitmap.Width := Width;
FinalBitmap.Height := Height;
R := GetClientRect;
//Blend the base gradient and the MouseOver Gradient
BlendBitmaps(FinalBitmap, FGrBitmap, FGrMouseOver, FOverBlendPercent, R, 1);
//Blend the previous gradient and the Selection Gradient
if FClickedBlendPercent > 0 then begin
if GradientBorder then
InflateRect(R, -3, -3);
BlendBitmaps(FinalBitmap, FinalBitmap, FGrClicked, FClickedBlendPercent, R, 1);
if GradientBorder then
InflateRect(R, 3, 3);
end;
FinalBitmap.Canvas.Brush.Style := bsClear;
FinalBitmap.Canvas.Pen.Color := Color;
FinalBitmap.Canvas.Rectangle(R.Left, R.Top, R.Right, R.Bottom);
FinalBitmap.Canvas.Pen.Color := FColors.BorderColor;
FinalBitmap.Canvas.RoundRect(0, 0, Width, Height, 5, 5);
BitBlt(Canvas.Handle, 0, 0, Width, Height, FinalBitmap.Canvas.Handle, 0, 0, SRCCOPY);
finally
FinalBitmap.Free;
end;
//Calc text rect
if not Glyph.Empty then begin
case FLayout of
blGlyphLeft :
Inc(R.Left, FGlyph.Width + FSpacing);
blGlyphRight :
Dec(R.Left, FGlyph.Width + FSpacing);
blGlyphTop :
Inc(R.Top, FGlyph.Width + FSpacing);
blGlyphBottom :
Dec(R.Top, FGlyph.Width + FSpacing);
end;
end;
SetBkMode(Canvas.Handle, Windows.TRANSPARENT);
SetTextFlags(taCenter, false, Flags);
//Draw text
Canvas.Font.Assign(Font);
if FHotTrack and (dsMouseOver in FDrawStates) then Canvas.Font.Color := FColors.HotTrack;
if ShowCaption then
DoDrawText(Canvas, Caption, Canvas.Font, Enabled, false, R, Flags, TextShadow, Colors.TextShadow);
//Draw the glyph
if not Glyph.Empty then begin
gl := TBitmap.Create;
try
gl.Assign(FGlyph);
gl.PixelFormat := pf24bit;
gl.Transparent := true;
if not Enabled then
ColorizeBitmap(gl, $00404040);
case FLayout of
blGlyphLeft :
if (Caption <> '') and ShowCaption then
Canvas.Draw((R.Left + R.Right - canvas.TextWidth(Caption)) div 2 - FSpacing - FGlyph.Width, (Height - FGlyph.Height) div 2, gl)
else
Canvas.Draw((R.Left + R.Right - FSpacing) div 2 - FGlyph.Width, (Height - FGlyph.Height) div 2, gl);
blGlyphRight :
if (Caption <> '') and ShowCaption then
Canvas.Draw((R.Left + R.Right + canvas.TextWidth(Caption)) div 2 + FSpacing, (Height - FGlyph.Height) div 2, gl)
else
Canvas.Draw((R.Left + R.Right) div 2 + FSpacing, (Height - FGlyph.Height) div 2, gl);
blGlyphTop :
if (Caption <> '') and ShowCaption then
Canvas.Draw((Width - FGlyph.Width) div 2, (R.Top + R.Bottom - canvas.TextHeight(Caption)) div 2 - FSpacing - FGlyph.Height, gl)
else
Canvas.Draw((Width - FGlyph.Width) div 2, (R.Top + R.Bottom) div 2 - FSpacing - FGlyph.Height, gl);
blGlyphBottom :
if (Caption <> '') and ShowCaption then
Canvas.Draw((Width - FGlyph.Width) div 2, (R.Top + R.Bottom + canvas.TextHeight(Caption)) div 2 + FSpacing, gl)
else
Canvas.Draw((Width - FGlyph.Width) div 2, (R.Top + R.Bottom) div 2 + FSpacing, gl);
end;
finally
gl.Free;
end;
end;
R := GetClientRect;
if Focused and FShowFocusRect then begin
InflateRect(R, -2, -2);
DrawFocusRect(Canvas.Handle, R);
end;
end;
constructor TRbButton.Create(AOwner: TComponent);
begin
inherited;
Height := 25;
Width := 75;
FGrBitmap := TBitmap.Create;
FGrBitmap.PixelFormat := pf24bit;
FGrBitmap.Width := Width;
FGrBitmap.Height := Height;
FGrMouseOver := TBitmap.Create;
FGrMouseOver.PixelFormat := pf24bit;
FGrMouseOver.Width := Width;
FGrMouseOver.Height := Height;
FGrClicked := TBitmap.Create;
FGrClicked.PixelFormat := pf24bit;
FGrClicked.Width := Width;
FGrClicked.Height := Height;
FGradientType := gtVertical;
FGlyph := TBitmap.Create;
FGlyph.Transparent := true;
FOverBlendPercent := 0;
FClickedBlendPercent := 0;
FDrawStates := [];
FSpacing := 2;
FLayout := blGlyphLeft;
FadeSpeed := fsMedium;
FShowFocusRect := true;
FHotTrack := false;
FGradientBorder := true;
FDown := False;
FAllowAllUp := false;
FGroupIndex := 0;
FColors := TRbControlColors.Create(Self);
end;
destructor TRbButton.Destroy;
begin
FGrBitmap.Free;
FGrMouseOver.Free;
FGrClicked.free;
FGlyph.Free;
FColors.Free;
inherited;
end;
procedure TRbButton.EventResized;
begin
inherited;
UpdateGradients;
end;
procedure TRbButton.EventMouseEnter;
begin
inherited;
Include(FDrawStates, dsMouseOver);
FOnFade := DoBlendMore;
UpdateTimer;
end;
procedure TRbButton.EventMouseLeave;
begin
inherited;
if not FDown then begin
Exclude(FDrawStates, dsMouseOver);
FOnFade := DoBlendLess;
UpdateTimer;
end;
end;
procedure TRbButton.EventMouseDown;
begin
inherited;
Include(FDrawStates, dsClicking);
Include(FDrawStates, dsMouseOver);
FOnFade := DoBlendMore;
UpdateTimer;
end;
procedure TRbButton.EventMouseUp;
begin
inherited;
if (dsClicking in FDrawStates) and not FDown then
Exclude(FDrawStates, dsClicking);
if dsMouseOver in FDrawStates then
FOnFade := DoBlendMore;
UpdateTimer;
end;
procedure TRbButton.SetGlyph(const Value: TBitmap);
begin
FGlyph.Assign(Value);
FGlyph.Transparent := true;
Invalidate;
end;
procedure TRbButton.SetSpacing(const Value: integer);
begin
if Value < 0 then
FSpacing := 0
else
FSpacing := Value;
end;
procedure TRbButton.SetLayout(const Value: TButtonLayout);
begin
if Value = FLayout then Exit;
FLayout := Value;
Invalidate;
end;
procedure TRbButton.SetFadeSpeed(const Value: TFadeSpeed);
begin
FFadeSpeed := Value;
end;
procedure TRbButton.SetHotTrack(const Value: boolean);
begin
if FHotTrack <> Value then begin
FHotTrack := Value;
Invalidate;
end;
end;
procedure TRbButton.SetFocusRect(const Value: boolean);
begin
if FShowFocusRect <> Value then begin
FShowFocusRect := Value;
Invalidate;
end;
end;
procedure TRbButton.UpdateGradients;
var
R : TRect;
begin
FGrBitmap.Width := Width;
FGrBitmap.Height := Height;
R := FGrBitmap.Canvas.ClipRect;
DoBitmapGradient(FGrBitmap, R, Colors.DefaultFrom, Colors.DefaultTo, GradientType, 0);
FGrMouseOver.Width := Width;
FGrMouseOver.Height := Height;
DoBitmapGradient(FGrMouseOver, R, Colors.OverFrom, Colors.OverTo, GradientType, 0);
FGrClicked.Width := Width;
FGrClicked.Height := Height;
DoBitmapGradient(FGrClicked, R, Colors.ClickedFrom, Colors.ClickedTo, GradientType, 0);
Invalidate;
end;
procedure TRbButton.SetDefault(const Value: boolean);
begin
if FDefault <> Value then begin
FDefault := Value;
with GetParentForm(Self) do
Perform(CM_FOCUSCHANGED, 0, LongInt(ActiveControl));
end;
end;
procedure TRbButton.CMDialogKey(var Message: TCMDialogKey);
begin
inherited;
with Message do
if (((CharCode = VK_RETURN) and (Focused or FDefault))
or ((CharCode = VK_ESCAPE) and FCancel) and (KeyDataToShiftState(KeyData) = []))
and CanFocus then
begin
Click;
Result := 1;
end
else
inherited;
end;
procedure TRbButton.KeyDown(var Key: Word; Shift: TShiftState);
begin
if (Shift = []) and (Key = VK_SPACE) then Click;
inherited;
end;
procedure TRbButton.Click;
var
Form: TCustomForm;
begin
Form := GetParentForm(Self);
if Form <> nil then
Form.ModalResult := ModalResult;
Down := (GroupIndex > 0) and not Down;
inherited Click;
end;
procedure TRbButton.EventFocusChanged;
begin
inherited;
Invalidate;
end;
procedure TRbButton.SetAllowAllUp(const Value: boolean);
begin
FAllowAllUp := Value;
end;
procedure TRbButton.SetDown(const Value: boolean);
begin
if (GroupIndex > 0) then begin
if not Value and not CanbeUp then Exit;
FDown := Value;
if FDown then begin
DeactivateSiblings;
Include(FDrawStates, dsMouseOver);
Include(FDrawStates, dsClicking);
FOnFade := DoBlendMore;
UpdateTimer;
end else begin
Exclude(FDrawStates, dsClicking);
FOnFade := DoBlendLess;
UpdateTimer;
end;
end;
end;
procedure TRbButton.SetGroupIndex(const Value: integer);
begin
FGroupIndex := Value;
end;
procedure TRbButton.DeActivateSiblings;
var
i : integer;
begin
if (GroupIndex > 0) and (Parent <> nil) then
with Parent do begin
for i := 0 to ControlCount - 1 do
if (Controls[i] <> Self) and (Controls[i] is TRbButton) and (TRbButton(Controls[i]).GroupIndex = GroupIndex) then
TRbButton(Controls[i]).SetDown(false);
end;
end;
function TRbButton.CanBeUp: boolean;
var
i : integer;
begin
Result := false;
if AllowAllUp then begin
Result := true;
Exit;
end;
if (GroupIndex > 0) and (Parent <> nil) then
with Parent do begin
for i := 0 to ControlCount - 1 do
if (Controls[i] <> Self) and (Controls[i] is TRbButton) and (TRbButton(Controls[i]).GroupIndex = GroupIndex) then
if TRbButton(Controls[i]).Down then begin
Result := true;
Exit;
end;
end;
end;
procedure TRbButton.SetGradientType(const Value: TGradientType);
begin
if FGradientType <> Value then begin
FGradientType := Value;
UpdateGradients;
end;
end;
end.
|
{*********************************************************}
{* OVCUSER.PAS 4.06 *}
{*********************************************************}
{* ***** BEGIN LICENSE BLOCK ***** *}
{* Version: MPL 1.1 *}
{* *}
{* 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. *}
{* *}
{* The Original Code is TurboPower Orpheus *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C)1995-2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
{$I OVC.INC}
{$B-} {Complete Boolean Evaluation}
{$I+} {Input/Output-Checking}
{$P+} {Open Parameters}
{$T-} {Typed @ Operator}
{.W-} {Windows Stack Frame}
{$X+} {Extended Syntax}
unit ovcuser;
{-User data class}
interface
uses
SysUtils,
OvcData;
type
{class for implementing user-defined mask and substitution characters}
TOvcUserData = class(TObject)
{.Z+}
protected {private}
FUserCharSets : TUserCharSets;
FForceCase : TForceCase;
FSubstChars : TSubstChars;
{property methods}
function GetForceCase(Index : TForceCaseRange) : TCaseChange;
{-get the case changing behavior of the specified user mask character}
function GetSubstChar(Index : TSubstCharRange) : Char;
{-get the meaning of the specified substitution character}
function GetUserCharSet(Index : TUserSetRange) : TCharSet;
{-get the specified user-defined character set}
procedure SetForceCase(Index : TForceCaseRange; CC : TCaseChange);
{-set the case changing behavior of the specified user mask character}
procedure SetSubstChar(Index : TSubstCharRange; SC : Char);
{-set the meaning of the specified substitution character}
procedure SetUserCharSet(Index : TUserSetRange; const US : TCharSet);
{-set the specified user-defined character set}
public
constructor Create;
{.Z+}
property ForceCase[Index : TForceCaseRange] : TCaseChange
read GetForceCase
write SetForceCase;
property SubstChars[Index : TSubstCharRange] : Char
read GetSubstChar
write SetSubstChar;
property UserCharSet[Index : TUserSetRange] : TCharSet
read GetUserCharSet
write SetUserCharSet;
end;
var
{global default user data object}
OvcUserData : TOvcUserData;
implementation
{*** TOvcUserData ***}
const
DefUserCharSets : TUserCharSets = (
{User1} [#1..#255], {User2} [#1..#255], {User3} [#1..#255],
{User4} [#1..#255], {User5} [#1..#255], {User6} [#1..#255],
{User7} [#1..#255], {User8} [#1..#255] );
DefForceCase : TForceCase = (
mcNoChange, mcNoChange, mcNoChange, mcNoChange,
mcNoChange, mcNoChange, mcNoChange, mcNoChange);
DefSubstChars : TSubstChars = (
Subst1, Subst2, Subst3, Subst4, Subst5, Subst6, Subst7, Subst8);
constructor TOvcUserData.Create;
begin
inherited Create;
FUserCharSets := DefUserCharSets;
FForceCase := DefForceCase;
FSubstChars := DefSubstChars;
end;
function TOvcUserData.GetForceCase(Index : TForceCaseRange) : TCaseChange;
{-get the case changing behavior of the specified user mask character}
begin
case Index of
pmUser1..pmUser8 : Result := FForceCase[Index];
else
Result := mcNoChange;
end;
end;
function TOvcUserData.GetSubstChar(Index : TSubstCharRange) : Char;
{-get the meaning of the specified substitution character}
begin
case Index of
Subst1..Subst8 : Result := FSubstChars[Index];
else
Result := #0;
end;
end;
function TOvcUserData.GetUserCharSet(Index : TUserSetRange) : TCharSet;
{-get the specified user-defined character set}
begin
case Index of
pmUser1..pmUser8 : Result := FUserCharSets[Index];
end;
end;
procedure TOvcUserData.SetForceCase(Index : TForceCaseRange; CC : TCaseChange);
{-set the case changing behavior of the specified user mask character}
begin
case Index of
pmUser1..pmUser8 : FForceCase[Index] := CC;
end;
end;
procedure TOvcUserData.SetSubstChar(Index : TSubstCharRange; SC : Char);
{-set the meaning of the specified substitution character}
begin
case Index of
Subst1..Subst8 : FSubstChars[Index] := SC;
end;
end;
procedure TOvcUserData.SetUserCharSet(Index : TUserSetRange; const US : TCharSet);
{-set the specified user-defined character set}
begin
case Index of
pmUser1..pmUser8 : FUserCharSets[Index] := US-[#0];
end;
end;
{*** exit procedure ***}
procedure DestroyGlobalUserData; far;
begin
OvcUserData.Free
end;
initialization
{create instance of default user data class}
OvcUserData := TOvcUserData.Create;
finalization
DestroyGlobalUserData;
end.
|
unit uFrmMenu;
interface
uses
uDm,
uFancyDialog,
FMX.Controls,
FMX.Controls.Presentation,
FMX.Dialogs,
FMX.Forms,
FMX.Graphics,
FMX.Layouts,
FMX.Objects,
FMX.StdCtrls,
FMX.Types,
System.Classes,
System.SysUtils,
System.Types,
System.UITypes,
System.Variants;
type
aPermission = record
aOpcao : string;
aPermissao : string;
end;
type
TFrmMenu = class(TForm)
StyleBook: TStyleBook;
lytMenu: TLayout;
rctLogin: TRectangle;
rctPerfil: TRectangle;
lblNome: TLabel;
rctUsuario: TRectangle;
rctCliente: TRectangle;
Image1: TImage;
Image2: TImage;
img_clientes: TImage;
Label1: TLabel;
PERFIL: TLabel;
Label3: TLabel;
procedure rctClienteClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure rctPerfilClick(Sender: TObject);
procedure rctUsuarioClick(Sender: TObject);
private
Fancy : TFancyDialog;
{ Private declarations }
public
PPermission : array[1..3] of aPermission;
UserAdmin : boolean;
function VerificaPermissao(aOpcao : string; aPermiss: Char):Boolean;
{ Public declarations }
end;
var
FrmMenu: TFrmMenu;
implementation
uses
uFrmCliente, uFrmPerfil, UFrmUsuario;
{$R *.fmx}
procedure TFrmMenu.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Fancy.DisposeOf;
end;
procedure TFrmMenu.FormCreate(Sender: TObject);
begin
Fancy := TFancyDialog.Create(FrmMenu);
end;
procedure TFrmMenu.rctClienteClick(Sender: TObject);
begin
if VerificaPermissao('CLI','C') then
begin
if not Assigned(FrmCliente) then
Application.CreateForm(TFrmCliente,FrmCliente);
FrmCliente.Show;
end else
fancy.Show(TIconDialog.Error,'Permissão','Você não tem permissão para acessar essa opção!','Ok');
end;
procedure TFrmMenu.rctPerfilClick(Sender: TObject);
begin
if VerificaPermissao('PER','C') then
begin
if not Assigned(FrmPerfil) then
Application.CreateForm(TFrmPerfil,FrmPerfil);
FrmPerfil.Show;
end else
fancy.Show(TIconDialog.Error,'Permissão','Você não tem permissão para acessar essa opção!','Ok');
end;
procedure TFrmMenu.rctUsuarioClick(Sender: TObject);
begin
if VerificaPermissao('USR','C') then
begin
if not Assigned(FrmUsuario) then
Application.CreateForm(TFrmUsuario,FrmUsuario);
FrmUsuario.Show;
end else
fancy.Show(TIconDialog.Error,'Permissão','Você não tem permissão para acessar essa opção!','Ok');
end;
function TFrmMenu.VerificaPermissao(aOpcao: string; aPermiss: Char): Boolean;
Var
I : Integer;
begin
Result := UserAdmin;
if not UserAdmin then
begin
for I := 1 to Length(PPermission) do
if PPermission[I].aOpcao=aOpcao then Result := (Pos(aPermiss,PPermission[I].aPermissao)>0);
end;
end;
end.
|
unit Helpers;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Dialogs;
type
THelper = Object
procedure test;
function pot_recursively(m, n : integer) : real;
function pot_interatively(m, n : integer) : real;
end;
implementation
procedure THelper.test;
begin
ShowMessage('it works');
end;
function THelper.pot_interatively(m, n : integer) : real;
var
i : integer;
h : integer = 1;
n_helper : integer;
begin
n_helper:= n - 1;
if n < 0 then begin
n_helper:= abs(n);
end;
for i:= 1 to n_helper do begin
h:= h * m;
end;
if n < 0 then begin
result:= 1 / h;
end else begin
result:= h;
end;
end;
function THelper.pot_recursively(m, n : integer) : real;
begin
if n = 0 then begin
result:= 1;
end else begin
if n < 0 then begin
result:= 1 / (m * self.pot_recursively(m, abs(n) - 1));
end else begin
result:= m * self.pot_recursively(m, n - 1);
end;
end;
end;
end.
|
UNIT RT_Watch;
{
Including this unit in your program should replace all the runtime
errors with messages that are a bit more helpful than "Runtime
error 202". Especially helpful when trying to help someone else
debug a program that you wrote (as if you would write a program
with a mistake).
}
INTERFACE
FUNCTION Hex(Value:byte):STRING;
IMPLEMENTATION
USES Crt;
VAR OldExit:pointer;
{====================================================================}
FUNCTION Hex(Value:byte):STRING;
CONST HexTable:ARRAY[0..15] OF Char=('0','1','2','3','4','5','6','7',
'8','9','A','B','C','D','E','F');
VAR HexStr : STRING;
begin
HexStr[2]:=HexTable[Value and $0F]; { Convert low nibble }
HexStr[1]:=HexTable[Value and $F0 div 16]; { Convert high nibble }
HexStr[0]:=#2; { Set STRINGlength }
Hex:=HexStr;
end;
{====================================================================}
{ Try to handle all possible errors }
Procedure RunTimeExitProc;Far;
VAR Message : STRING;
begin
if ErrorAddr<>Nil then { If error occurs }
begin
TextColor(LightRed);
WriteLn;
WriteLn;
WriteLn('RUNTIME WATCHER v1.1 MJ (C) 2004');
TextColor(Red+Blink);
WriteLn('Ein Fehler ist aufgetreten...');
TextColor(White);
case ExitCode OF { Pick the appropriate message }
2:Message:='File not found';
3:Message:='Path not found';
4:Message:='Too many open files';
5:Message:='File access denied';
6:Message:='Invalid file handle';
8:Message:='Insufficient memory';
12:Message:='Invalid file access code';
15:Message:='Invalid drive number';
16:Message:='Cannot remove current directory';
17:Message:='Cannot rename across drives';
100:Message:='Disk read error';
100:Message:='Disk write error';
102:Message:='File not assigned';
103:Message:='File not open';
104:Message:='File not open for input';
105:Message:='File not open for output';
106:Message:='Invalid numeric format';
150:Message:='Disk is write-protected';
151:Message:='Unknown unit';
152:Message:='Drive not ready';
153:Message:='Unknown command';
154:Message:='CRC error in data';
155:Message:='Bad drive request structure length';
156:Message:='Disk seek error';
157:Message:='Unknown media type';
158:Message:='Sector not found';
159:Message:='Printer out of paper';
160:Message:='Device write fault';
161:Message:='Device read fault';
162:Message:='Hardware failure';
200:Message:='Division by zero';
201:Message:='Range check error';
202:Message:='Stack overflow error';
203:Message:='Heap overflow error';
204:Message:='Invalid pointer operation';
205:Message:='Floating-point overflow';
206:Message:='Floating-point underflow';
207:Message:='Invalid floating-point operation';
208:Message:='Overlay manager not installed';
209:Message:='Overlay file read error';
210:Message:='Object not initialized';
211:Message:='Call to abstract method';
212:Message:='Stream register error';
213:Message:='Collection index out OF range';
214:Message:='Collection overflow error';
end;
writeln('Fehler-Code:',ExitCode);
writeln('Segment:',Hex(seg(ErrorAddr^)));
writeln('Offset:',Hex(Ofs(ErrorAddr^)));
writeln(Message);
ErrorAddr:=nil;
ExitCode:=1; { End program with errorlevel 1 }
end;
ExitProc:=OldExit; { Restore the original exit procedure }
end;
{====================================================================}
begin
OldExit:=ExitProc; { Save the original exit procedure }
ExitProc:=@RunTimeExitProc; { Insert the RunTime exit procedure }
end.
|
{* This simple test app is created with the sole purpose to check the validity
* of the structures and ioctl IDs as defined in cryptodev.pas header *}
program cryptodevtest;
uses cryptodev;
const
SEPARATOR = '=============================================================';
procedure DumpStructSizes;
begin
writeln('Struct/Record sizes (in bytes):');
writeln(SEPARATOR);
writeln('TSessionOp: ',sizeof(TSessionOp));
writeln('TAlgInfo: ',sizeof(TAlgInfo));
writeln('TSessionInfoOp: ',sizeof(TSessionInfoOp));
writeln('TCryptOp: ',sizeof(TCryptOp));
writeln('TCryptAuthOp: ',sizeof(TCryptAuthOp));
writeln('TCryptKOp: ',sizeof(TCryptKOp));
end;
procedure DumpIOCtlIDs;
begin
writeln('ioctl IDs:');
writeln(SEPARATOR);
writeln('CRIOGET $',LowerCase(HexStr(CRIOGET,8)));
writeln('CIOCGSESSION $',LowerCase(HexStr(CIOCGSESSION,8)));
writeln('CIOCFSESSION $',LowerCase(HexStr(CIOCFSESSION,8)));
writeln('CIOCCRYPT $',LowerCase(HexStr(CIOCCRYPT,8)));
writeln('CIOCKEY $',LowerCase(HexStr(CIOCKEY,8)));
writeln('CIOCASYMFEAT $',LowerCase(HexStr(CIOCASYMFEAT,8)));
writeln('CIOCGSESSIONINFO $',LowerCase(HexStr(CIOCGSESSINFO,8)));
writeln('CIOCAUTHCRYPT $',LowerCase(HexStr(CIOCAUTHCRYPT,8)));
writeln('CIOCASYNCCRYPT $',LowerCase(HexStr(CIOCASYNCCRYPT,8)));
writeln('CIOCASYNCFETCH $',LowerCase(HexStr(CIOCASYNCFETCH,8)));
end;
begin
writeln;
DumpStructSizes;
writeln;
DumpIOCtlIDs;
writeln;
end.
|
{$include kode.inc}
unit syn_perc;
//{$includepath ./syn_perc}
{
TODO:
* 2 more columns.. 2 cols for each osc, 1 for master
MAYBE:
* 3rd oscillator.. mix 1-2, and mix 2-3
}
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_plugin,
kode_types,
{$ifdef KODE_GUI}
syn_perc_editor,
{$endif}
syn_perc_voice;
const
SYNPERC_NUM_PROGRAMS = 32;
type
synPerc = class(KPlugin)
private
FVoice : synPercVoice;
public
procedure on_create; override;
procedure on_destroy; override;
procedure on_stateChange(AState:LongWord); override;
//procedure on_transportChange(ATransport:LongWord); override;
procedure on_midiEvent(AOffset:LongWord; AData1,AData2,AData3:Byte); override;
procedure on_parameterChange(AIndex:LongWord; AValue:Single); override;
//procedure on_programChange(AIndex:LongWord); override;
//procedure on_processBlock(AInputs,AOutputs:PPSingle; ASize:LongWord); override;
procedure on_processSample(AInputs,AOutputs:PPSingle); override;
//procedure on_postProcess; override;
{$ifdef KODE_GUI}
function on_openEditor(AParent:Pointer) : Pointer; override;
procedure on_closeEditor; override;
procedure on_idleEditor; override;
{$endif}
end;
KPluginClass = synPerc;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
uses
_plugin_id,
Math,
{$ifdef KODE_GUI}
kode_editor,
{$endif}
kode_const,
kode_debug,
kode_flags,
kode_math,
kode_parameter,
kode_program,
kode_random,
kode_utils;
//----------------------------------------------------------------------
// plugin
//----------------------------------------------------------------------
procedure synPerc.on_create;
var
i : longint;
//prog : KProgram;
begin
{ info }
FName := 'syn_perc';
FAuthor := 'skei.audio';
FProduct := FName;
FVersion := 0;
FUniqueId := KODE_MAGIC_USER + syn_perc_id;
FNumInputs := 2;
FNumOutputs := 2;
{ flags }
KSetFlag( FFlags,
kpf_perSample
//+ kpf_sendMidi
+ kpf_receiveMidi
+ kpf_isSynth
//+ kpf_autoUpdateSync // automatically handles getTime and on_transportChange
//+ kpf_reaper // has/uses reaper support
);
{ editor }
{$ifdef KODE_GUI}
KSetFlag(FFlags,kpf_hasEditor);
FEditor := nil;
FEditorRect.setup(340,640{555}); // + 100 + 10
{$endif}
{ 1 }
appendParameter( KParameter.create( 'p1 start', 0.4 ));
appendParameter( KParameter.create( 'p1 end', 0 ));
appendParameter( KParameter.create( 'p1 speed', 0 ));
appendParameter( KParamText.create( 'ps1 type', pmod_type_none, pmod_type_count, txt_pmod ));
appendParameter( KParameter.create( 'ps1 start', 0 ));
appendParameter( KParameter.create( 'ps1 end', 0 ));
appendParameter( KParameter.create( 'ps1 speed', 0 ));
appendParameter( KParamText.create( 'w1 type', osc_type_sin, osc_type_count, txt_osc ));
appendParameter( KParamText.create( 'ws1 type', smod_type_none, smod_type_count, txt_smod ));
appendParameter( KParameter.create( 'ws1 start', 0 ));
appendParameter( KParameter.create( 'ws1 end', 0 ));
appendParameter( KParameter.create( 'ws1 speed', 0 ));
appendParameter( KParamText.create( 'f1 type', flt_type_none, flt_type_count, txt_flt ));
appendParameter( KParameter.create( 'f1 start', 1 ));
appendParameter( KParameter.create( 'f1 end', 0 ));
appendParameter( KParameter.create( 'f1 speed', 0 ));
appendParameter( KParameter.create( 'v1 start', 0.9 ));
appendParameter( KParameter.create( 'v1 end', 0 ));
appendParameter( KParameter.create( 'v1 speed', 0 ));
{ 2 }
appendParameter( KParameter.create( 'p2 start', 0.6 ));
appendParameter( KParameter.create( 'p2 end', 0 ));
appendParameter( KParameter.create( 'p2 speed', 0 ));
appendParameter( KParamText.create( 'ps2 type', pmod_type_none, pmod_type_count, txt_pmod ));
appendParameter( KParameter.create( 'ps2 start', 0 ));
appendParameter( KParameter.create( 'ps2 end', 0 ));
appendParameter( KParameter.create( 'ps2 speed', 0 ));
appendParameter( KParamText.create( 'w2 type', osc_type_sin, osc_type_count, txt_osc ));
appendParameter( KParamText.create( 'ws2 type', smod_type_none, smod_type_count, txt_smod ));
appendParameter( KParameter.create( 'ws2 start', 0 ));
appendParameter( KParameter.create( 'ws2 end', 0 ));
appendParameter( KParameter.create( 'ws2 speed', 0 ));
appendParameter( KParamText.create( 'f2 type', flt_type_none, flt_type_count, txt_flt ));
appendParameter( KParameter.create( 'f2 start', 1 ));
appendParameter( KParameter.create( 'f2 end', 0 ));
appendParameter( KParameter.create( 'f2 speed', 0 ));
appendParameter( KParameter.create( 'v2 start', 0.9 ));
appendParameter( KParameter.create( 'v2 end', 0 ));
appendParameter( KParameter.create( 'v2 speed', 0 ));
{ master}
appendParameter( KParameter.create( 'mix start', 0.5 ));
appendParameter( KParameter.create( 'mix end', 0 ));
appendParameter( KParameter.create( 'mix speed', 0 ));
appendParameter( KParameter.create( 'xfade', 0.5 ));
appendParameter( KParamText.create( 'fm type', flt_type_none, flt_type_count, txt_flt ));
appendParameter( KParameter.create( 'fm start', 1 ));
appendParameter( KParameter.create( 'fm end', 0 ));
appendParameter( KParameter.create( 'fm speed', 0 ));
appendParameter( KParameter.create( 'vm volume', 0.9 ));
appendParameter( KParameter.create( 'vm attack', 1 ));
appendParameter( KParameter.create( 'vm decay', 0.4 ));
{ }
appendParameter( KParameter.create( 'note1', 1 ));
appendParameter( KParameter.create( 'note2', 1 ));
appendParameter( KParamInt.create( 'o1 oct', 0, -4, 4 ));
appendParameter( KParamInt.create( 'o1 semi', 0, -12,12 ));
appendParameter( KParamInt.create( 'o1 cent', 0, -50,50 ));
{ programs }
for i := 0 to SYNPERC_NUM_PROGRAMS-1 do
appendProgram( createDefaultProgram );
{ voice }
FVoice := synPercVoice.create;
end;
//----------
procedure synPerc.on_destroy;
begin
FVoice.destroy;
end;
//----------
procedure synPerc.on_stateChange(AState:LongWord);
begin
case AState of
kps_sampleRate,
kps_resume:
FVoice.samplerate := FSampleRate;
end;
end;
//----------
procedure synPerc.on_midiEvent(AOffset:LongWord; AData1,AData2,AData3:Byte);
begin
case AData1 and $F0 of
144: FVoice.note_on(AData2,AData3*KODE_INV127);
128: FVoice.note_off(AData2,AData3*KODE_INV127);
176: FVoice.ctrl_change(AData2,AData3*KODE_INV127);
end;
end;
//----------
procedure synPerc.on_parameterChange(AIndex:LongWord; AValue:Single);
var
v,vv,vvv,av : single;
begin
v := AValue * 0.5; // nyquist?
vv := v*v*v;
vvv := v*v*v*v*v*v;
av := AValue*AValue*AValue;
case AIndex of
{ 1 }
0: FVoice.p_pitch1_start := vv;
1: FVoice.p_pitch1_end := vv;
2: FVoice.p_pitch1_speed := vvv;
3: FVoice.p_pmod1_type := trunc(AValue);
4: FVoice.p_pmod1_start := AValue;
5: FVoice.p_pmod1_end := AValue;
6: FVoice.p_pmod1_speed := vvv;
7: FVoice.p_osc1_type := trunc(AValue);
8: FVoice.p_smod1_type := trunc(AValue);
9: FVoice.p_smod1_start := AValue;
10: FVoice.p_smod1_end := AValue;
11: FVoice.p_smod1_speed := vvv;
12: FVoice.p_filter1_type := trunc(AValue);
13: FVoice.p_filter1_start := av;
14: FVoice.p_filter1_end := av;
15: FVoice.p_filter1_speed := vvv;
16: FVoice.p_env1_start := av;
17: FVoice.p_env1_end := av;
18: FVoice.p_env1_speed := vvv;
{ 2 }
19: FVoice.p_pitch2_start := vv;
20: FVoice.p_pitch2_end := vv;
21: FVoice.p_pitch2_speed := vvv;
22: FVoice.p_pmod2_type := trunc(AValue);
23: FVoice.p_pmod2_start := AValue;
24: FVoice.p_pmod2_end := AValue;
25: FVoice.p_pmod2_speed := vvv;
26: FVoice.p_osc2_type := trunc(AValue);
27: FVoice.p_smod2_type := trunc(AValue);
28: FVoice.p_smod2_start := AValue;
29: FVoice.p_smod2_end := AValue;
30: FVoice.p_smod2_speed := vvv;
31: FVoice.p_filter2_type := trunc(AValue);
32: FVoice.p_filter2_start := av;
33: FVoice.p_filter2_end := av;
34: FVoice.p_filter2_speed := vvv;
35: FVoice.p_env2_start := av;
36: FVoice.p_env2_end := av;
37: FVoice.p_env2_speed := vvv;
{ master }
38: FVoice.p_mix_start := AValue;
39: FVoice.p_mix_end := AValue;
40: FVoice.p_mix_speed := vvv;
41: FVoice.p_xfade_speed := av;
42: FVoice.p_filterm_type := trunc(AValue);
43: FVoice.p_filterm_start := av;
44: FVoice.p_filterm_end := av;
45: FVoice.p_filterm_speed := vvv;
46: FVoice.p_envm_vol := av;
47: FVoice.p_envm_att := vvv;
48: FVoice.p_envm_dec := vvv;
{ midi }
49: FVoice.p_note_pitch1 := (AValue>=0.5);
50: FVoice.p_note_pitch2 := (AValue>=0.5);
{ tuning }
51: FVoice.p_osc1_oct := trunc(AValue);
52: FVoice.p_osc1_semi := trunc(AValue);
53: FVoice.p_osc1_cent := trunc(AValue);
end;
end;
//----------
procedure synPerc.on_processSample(AInputs,AOutputs:PPSingle);
var
spl0,spl1 : single;
s,v : Single;
begin
spl0 := AInputs[0]^;
spl1 := AInputs[1]^;
s := (spl0 + spl1) * 0.5;
v := FVoice.process(s);
AOutputs[0]^ := v;
AOutputs[1]^ := v;
end;
//----------------------------------------------------------------------
// editor
//----------------------------------------------------------------------
{$ifdef KODE_GUI}
function synPerc.on_openEditor(AParent:Pointer) : Pointer;
var
editor : synPercEditor;
begin
editor := synPercEditor.create(self,FEditorRect,AParent);
result := editor;
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure synPerc.on_closeEditor;
begin
FEditor.hide;
FEditor.destroy;
FEditor := nil;
end;
{$endif}
//----------
{$ifdef KODE_GUI}
procedure synPerc.on_idleEditor;
var
editor : synPercEditor;
begin
editor := FEditor as synPercEditor;
{ wave 1 }
editor.w_buffer1.setBuffer( FVoice.bufferPtr1 );
editor.w_buffer1.setBufferSize( FVoice.cycleCount1 );
editor.do_redraw( editor.w_buffer1, editor.w_buffer1._rect );
{ wave 2 }
editor.w_buffer2.setBuffer( FVoice.bufferPtr2 );
editor.w_buffer2.setBufferSize( FVoice.cycleCount2 );
editor.do_redraw( editor.w_buffer2, editor.w_buffer2._rect );
end;
{$endif}
//----------------------------------------------------------------------
end.
|
unit Blnkbutt;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Litbutt;
type
TBlinkingIndicatorButton = class(TIndicatorButton)
private
FBlinking: Boolean;
FInterval: word;
FOriginalCaption: String;
ClockDriver: TTimer;
protected
procedure SetBlinking(Value: Boolean); virtual;
procedure BlinkCaption(Sender: TObject); virtual;
procedure SetInterval(Value: word); virtual;
public
constructor Create(AOwner: TComponent); override;
published
property Interval: word read FInterval
write SetInterval
default 1000;
property Blinking: Boolean read FBlinking
write SetBlinking
default False;
end;
implementation
procedure TBlinkingIndicatorButton.SetBlinking(Value: Boolean);
begin
if (value = FBlinking) then exit;
FBlinking := Value;
if Value then
begin
FOriginalCaption := Caption;
ClockDriver := TTimer.Create(Self);
SetInterval(FInterval);
ClockDriver.OnTimer := BlinkCaption;
end
else
begin
ClockDriver.Free;
SetCaption(FOriginalCaption);
end;
end;
procedure TBlinkingIndicatorButton.SetInterval(Value: word);
begin
if (Value = FInterval) then exit;
FInterval := Value;
if FBlinking then ClockDriver.Interval := FInterval;
end;
procedure TBlinkingIndicatorButton.BlinkCaption(Sender: TObject);
begin
If Caption = FOriginalCaption then
Caption := ''
else
Caption := FOriginalCaption;
end;
constructor TBlinkingIndicatorButton.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SetInterval(1000);
SetBlinking(False);
end;
end.
|
unit UnitMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Threading, Vcl.StdCtrls, SyncObjs, Vcl.ExtCtrls,
ComObj, ActiveX,Vcl.Menus, cxButtons, System.Generics.Collections, Vcl.ComCtrls;
type
TGeradorDeArquivo = class;
TGeradorDeArquivoStatusPanel = class(TComponent)
private
[Weak]
FGeradorDeArquivo: TGeradorDeArquivo;
FPanel: TPanel;
FButtonCancelar: TcxButton;
FPanelInner: TPanel;
FLabelTitle: TLabel;
FProgressBar: TProgressBar;
FAlign: TAlign;
FTitle: String;
FProgressEnabled: Boolean;
procedure SetAlign(const Value: TAlign);
procedure SetTitle(const Value: String);
procedure SetProgressEnabled(const Value: Boolean);
procedure DoButtonCancelar(Sender: TObject);
public
constructor Create(AOwner: TComponent; const AGeradorDeArquivo: TGeradorDeArquivo); reintroduce;
property Align: TAlign read FAlign write SetAlign;
property Title: String read FTitle write SetTitle;
property ProgressEnabled: Boolean read FProgressEnabled write SetProgressEnabled;
end;
TGeradorDeArquivoAoTerminar = Reference to Procedure(AGerador: TGeradorDeArquivo);
TGeradorDeArquivo = class(TObject)
private
[Weak]
FTask: ITask;
[Weak]
FOwner: TComponent;
FPanelStatus: TGeradorDeArquivoStatusPanel;
FExecutarProcAoTerminar: TGeradorDeArquivoAoTerminar;
FExecutarProcAoCancelar: TGeradorDeArquivoAoTerminar;
FTaskID: String;
function GetTaskID: String;
public
constructor Create; reintroduce;
destructor Destroy; override;
class function Iniciar: TGeradorDeArquivo;
procedure Gerar;
procedure Cancelar;
function MostrarStatusPanel(AOwner: TComponent): TGeradorDeArquivo;
function ExecutarAoTerminar(const AProc: TGeradorDeArquivoAoTerminar): TGeradorDeArquivo;
function ExecutarAoCancelar(const AProc: TGeradorDeArquivoAoTerminar): TGeradorDeArquivo;
property TaskID: String read GetTaskID;
end;
TFormMain = class(TForm)
ButtonSimpleTask: TButton;
ButtonTask: TButton;
PanelContainer: TPanel;
ScrollBox: TScrollBox;
MemoLog: TMemo;
LabelPAth: TLabel;
procedure ButtonSimpleTaskClick(Sender: TObject);
procedure ButtonTaskClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
GeradorDeArquivoList: TDictionary<String, TGeradorDeArquivo>;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
procedure TFormMain.ButtonSimpleTaskClick(Sender: TObject);
var
Task: ITask;
begin
Task := TTask.Create (procedure()
begin
Sleep(3000);
ShowMessage('Hello');
end);
Task.Start;
end;
procedure TFormMain.ButtonTaskClick(Sender: TObject);
var
Gerador: TGeradorDeArquivo;
begin
Gerador := TGeradorDeArquivo.Iniciar
.MostrarStatusPanel(ScrollBox)
.ExecutarAoCancelar(procedure(AGerador: TGeradorDeArquivo)
begin
TThread.Queue(TThread.CurrentThread, procedure()
begin
if Assigned(MemoLog) then
MemoLog.Lines.Add('Cancelou a Task: ' + AGerador.TaskID);
GeradorDeArquivoList.Remove(AGerador.TaskID);
AGerador.Free;
end)
end
)
.ExecutarAoTerminar(procedure(AGerador: TGeradorDeArquivo)
begin
TThread.Queue(TThread.CurrentThread, procedure()
begin
if Assigned(MemoLog) then
MemoLog.Lines.Add('Terminou a Task: ' + AGerador.TaskID);
GeradorDeArquivoList.Remove(AGerador.TaskID);
AGerador.Free;
end)
end
);
GeradorDeArquivoList.Add(Gerador.TaskID, Gerador);
Gerador.Gerar;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
GeradorDeArquivoList := TDictionary<String, TGeradorDeArquivo>.Create();
end;
procedure TFormMain.FormDestroy(Sender: TObject);
var
Gerador: TPair<String, TGeradorDeArquivo>;
I: Integer;
begin
for Gerador in GeradorDeArquivoList do
begin
Gerador.Value.Cancelar;
end;
for Gerador in GeradorDeArquivoList do
begin
Gerador.Value.Free;
end;
GeradorDeArquivoList.Clear;
GeradorDeArquivoList.Free;
end;
{ TGeradorDeArquivo }
function TGeradorDeArquivo.ExecutarAoCancelar(const AProc: TGeradorDeArquivoAoTerminar): TGeradorDeArquivo;
begin
FExecutarProcAoCancelar := AProc;
Result := Self;
end;
function TGeradorDeArquivo.ExecutarAoTerminar(const AProc: TGeradorDeArquivoAoTerminar): TGeradorDeArquivo;
begin
FExecutarProcAoTerminar := AProc;
Result := Self;
end;
procedure TGeradorDeArquivo.Cancelar;
begin
FTask.Cancel;
end;
function TGeradorDeArquivo.MostrarStatusPanel(AOwner: TComponent): TGeradorDeArquivo;
begin
FOwner := AOwner;
Result := Self;
end;
constructor TGeradorDeArquivo.Create;
begin
FTaskID := EmptyStr;
end;
destructor TGeradorDeArquivo.Destroy;
begin
if Assigned(FPanelStatus) then FreeAndNil(FPanelStatus);
inherited;
end;
procedure TGeradorDeArquivo.Gerar;
begin
TThread.Queue(TThread.CurrentThread, procedure()
begin
FPanelStatus := TGeradorDeArquivoStatusPanel.Create(FOwner, Self);
FPanelStatus.Align := alTop;
FPanelStatus.ProgressEnabled := True;
FPanelStatus.Title := TaskID;
end);
FTask := TTask.Create(procedure()
var
Lista: TStringList;
TaskIDAux: String;
Index: Integer;
begin
if (TTask.CurrentTask.Status <> TTaskStatus.Canceled) then
begin
TaskIDAux := TaskID;
Lista := NIL;
try
Lista := TStringList.Create;
Lista.Add('>> Task ' + TaskID + ' <<');
Index := 0;
while (TTask.CurrentTask.Status <> TTaskStatus.Canceled) do
begin
Lista.Add(Index.ToString() + ' -> CurrentThread.ThreadID: ' + TThread.CurrentThread.ThreadID.ToString());
Inc(Index);
Sleep(1000);
if (Index = 5) then
begin
Break;
end;
end;
if (not (DirectoryExists('C:\Temp\Resultado\'))) then
begin
ForceDirectories('C:\Temp\Resultado\');
end;
Lista.SaveToFile('C:\Temp\Resultado\' + TaskIDAux + '.txt');
finally
Lista.Free;
end;
if (TTask.CurrentTask.Status = TTaskStatus.Canceled) then
begin
TThread.Queue(TThread.CurrentThread, procedure()
begin
if (not (Application.Terminated)) then
begin
if Assigned(FExecutarProcAoCancelar) then FExecutarProcAoCancelar(Self);
if Assigned(FPanelStatus) then FPanelStatus.Free;
end;
end);
end
else
begin
TThread.Queue(TThread.CurrentThread, procedure()
begin
if (not (Application.Terminated)) then
begin
if Assigned(FExecutarProcAoTerminar) then FExecutarProcAoTerminar(Self);
if Assigned(FPanelStatus) then FPanelStatus.Free;
end;
end);
end;
end
end
);
FTask.Start;
end;
function TGeradorDeArquivo.GetTaskID: String;
var
ID: TGUID;
begin
if (FTaskID = EmptyStr) then
begin
CoCreateGuid(ID);
FTaskID := GUIDToString(ID);
end;
Result := FTaskID;
end;
class function TGeradorDeArquivo.Iniciar: TGeradorDeArquivo;
begin
Result := TGeradorDeArquivo.Create;
end;
{ TGeradorDeArquivoStatusPanel }
constructor TGeradorDeArquivoStatusPanel.Create(AOwner: TComponent; const AGeradorDeArquivo: TGeradorDeArquivo);
begin
inherited Create(AOwner);
FGeradorDeArquivo := AGeradorDeArquivo;
FPanel := TPanel.Create(Self);
FButtonCancelar := TcxButton.Create(Self);
FPanelInner := TPanel.Create(Self);
FLabelTitle := TLabel.Create(Self);
FProgressBar := TProgressBar.Create(Self);
FPanel.Name := 'Panel';
FPanel.Parent := TWinControl(Self.Owner);
FPanel.BevelOuter := bvNone;
FPanel.TabStop := False;
FPanel.Caption := EmptyStr;
FPanel.Width := 417;
FPanel.Height := 45;
FButtonCancelar.Name := 'ButtonCancelar';
FButtonCancelar.Parent := FPanel;
FButtonCancelar.AlignWithMargins := True;
FButtonCancelar.Width := 60;
FButtonCancelar.Align := alRight;
FButtonCancelar.Caption := 'Cancelar';
FButtonCancelar.TabStop := False;
FButtonCancelar.OnClick := DoButtonCancelar;
FPanelInner.Name := 'PanelInner';
FPanelInner.Parent := FPanel;
FPanelInner.Align := alClient;
FPanelInner.BevelOuter := bvNone;
FPanelInner.TabStop := False;
FPanelInner.Caption := EmptyStr;
FProgressBar.Name := 'ProgressBar';
FProgressBar.Parent := FPanelInner;
FProgressBar.AlignWithMargins := True;
FProgressBar.Align := alBottom;
FProgressBar.Height := 20;
FProgressBar.TabStop := False;
FProgressBar.Style := pbstMarquee;
FProgressBar.MarqueeInterval := 10;
FLabelTitle.Name := 'LabelTitle';
FLabelTitle.Parent := FPanelInner;
FLabelTitle.AlignWithMargins := True;
FLabelTitle.Align := alClient;
FLabelTitle.Caption := 'Descri'#231#227'o';
end;
procedure TGeradorDeArquivoStatusPanel.DoButtonCancelar(Sender: TObject);
begin
FGeradorDeArquivo.FTask.Cancel;
end;
procedure TGeradorDeArquivoStatusPanel.SetAlign(const Value: TAlign);
begin
FAlign := Value;
FPanel.Align := FAlign;
end;
procedure TGeradorDeArquivoStatusPanel.SetProgressEnabled(const Value: Boolean);
begin
FProgressEnabled := Value;
FProgressBar.Enabled := FProgressEnabled;
end;
procedure TGeradorDeArquivoStatusPanel.SetTitle(const Value: String);
begin
FTitle := Value;
FLabelTitle.Caption := FTitle;
end;
end.
|
unit BancoAgencia;
interface
uses
MVCFramework.Serializer.Commons, ModelBase, Banco;
type
[MVCNameCase(ncLowerCase)]
TBancoAgencia = class(TModelBase)
private
FID: Integer;
FID_BANCO: Integer;
FNUMERO: string;
FDIGITO: string;
FNOME: string;
FTELEFONE: string;
FCONTATO: string;
FOBSERVACAO: string;
FGERENTE: string;
FBanco: TBanco;
public
procedure ValidarInsercao; override;
procedure ValidarAlteracao; override;
procedure ValidarExclusao; override;
constructor Create; virtual;
destructor Destroy; override;
[MVCColumnAttribute('ID', True)]
[MVCNameAsAttribute('id')]
property Id: Integer read FID write FID;
[MVCColumnAttribute('ID_BANCO')]
[MVCNameAsAttribute('idBanco')]
property IdBanco: Integer read FID_BANCO write FID_BANCO;
[MVCColumnAttribute('NUMERO')]
[MVCNameAsAttribute('numero')]
property Numero: string read FNUMERO write FNUMERO;
[MVCColumnAttribute('DIGITO')]
[MVCNameAsAttribute('digito')]
property Digito: string read FDIGITO write FDIGITO;
[MVCColumnAttribute('NOME')]
[MVCNameAsAttribute('nome')]
property Nome: string read FNOME write FNOME;
[MVCColumnAttribute('TELEFONE')]
[MVCNameAsAttribute('telefone')]
property Telefone: string read FTELEFONE write FTELEFONE;
[MVCColumnAttribute('CONTATO')]
[MVCNameAsAttribute('contato')]
property Contato: string read FCONTATO write FCONTATO;
[MVCColumnAttribute('OBSERVACAO')]
[MVCNameAsAttribute('observacao')]
property Observacao: string read FOBSERVACAO write FOBSERVACAO;
[MVCColumnAttribute('GERENTE')]
[MVCNameAsAttribute('gerente')]
property Gerente: string read FGERENTE write FGERENTE;
// objetos vinculados
[MVCNameAsAttribute('banco')]
property Banco: TBanco read FBanco write FBanco;
end;
implementation
{ TBancoAgencia }
constructor TBancoAgencia.Create;
begin
FBanco := TBanco.Create;
end;
destructor TBancoAgencia.Destroy;
begin
FBanco.Free;
inherited;
end;
procedure TBancoAgencia.ValidarInsercao;
begin
inherited;
end;
procedure TBancoAgencia.ValidarAlteracao;
begin
inherited;
end;
procedure TBancoAgencia.ValidarExclusao;
begin
inherited;
end;
end.
|
unit uAntWorld;
interface
{$OPTIMIZATION ON}
uses
Windows, SysUtils, Graphics;
type
TAntPalette = (plMonochrome, plColor);
TAntWorld = class(TBitmap)
private
fWrap: boolean;
fPixels: array of PByteArray;
function GetField(X, Y: integer): byte;
procedure SetField(X, Y: integer; const Value: byte);
protected
procedure UpdatePixelArray;
public
Generation: int64;
RawField: array of PByte;
constructor Create(const aWidth, aHeight: integer); reintroduce;
property Wrap: boolean read fWrap write fWrap;
property Field[X, Y: integer]: byte read GetField write SetField;
function WrapCoords(var X,Y: integer): boolean;
procedure Clear;
procedure SetAntPalette(const aPalette: TAntPalette; const aCount: integer);
end;
implementation
{ TAntWorld }
function PalEntry(C: TColor): TPaletteEntry;
begin
Result.peRed:= GetRValue(C);
Result.peGreen:= GetGValue(C);
Result.peBlue:= GetBValue(C);
Result.peFlags:= 0;
end;
procedure TAntWorld.Clear;
var
x,y: integer;
begin
UpdatePixelArray;
for y:= 0 to Height-1 do
for x:= 0 to Width-1 do
Field[x,y]:= 0;
Generation:= 0;
end;
constructor TAntWorld.Create(const aWidth, aHeight: integer);
begin
inherited Create;
PixelFormat:= pf8bit;
SetAntPalette(plColor, 18);
Width:= aWidth;
Height:= aHeight;
Wrap:= true;
Clear;
end;
procedure TAntWorld.UpdatePixelArray;
var
y,x: integer;
begin
SetLength(fPixels, Height);
SetLength(RawField, Height * Width);
for y:= 0 to Height-1 do begin
fPixels[y]:= ScanLine[y];
for x:= 0 to Width-1 do
RawField[y*Width+x]:= @(fPixels[y][x]);
end;
end;
procedure TAntWorld.SetAntPalette(const aPalette: TAntPalette; const aCount: integer);
var
pal: TMaxLogPalette;
procedure PushColor(C: TColor);
begin
pal.palPalEntry[pal.palNumEntries]:= PalEntry(C);
inc(pal.palNumEntries);
end;
procedure PalMono;
var
i: integer;
k: byte;
begin
for i:= aCount-1 downto 0 do begin
k:= 255 * i div (aCount-1);
PushColor(RGB(k,k,k));
end;
end;
procedure PalColor;
begin
PushColor(clWhite);
PushColor(clBlack);
PushColor(clLime);
PushColor(clBlue);
PushColor(clMaroon);
PushColor(clTeal);
PushColor(clGray);
PushColor(clNavy);
PushColor(clFuchsia);
PushColor(clGreen);
PushColor(clOlive);
PushColor(clPurple);
PushColor(clSilver);
PushColor(clRed);
PushColor(clYellow);
PushColor(clAqua);
PushColor(clLtGray);
PushColor(clDkGray);
end;
begin
pal.palVersion:= $0300;
pal.palNumEntries:= 0;
case aPalette of
plMonochrome: PalMono;
plColor: PalColor;
end;
Palette:= CreatePalette(PLOGPALETTE(@pal)^);
UpdatePixelArray;
end;
function TAntWorld.GetField(X, Y: integer): byte;
begin
Result:= fpixels[Y]^[X]
end;
procedure TAntWorld.SetField(X, Y: integer; const Value: byte);
begin
fpixels[Y]^[X]:= Value;
end;
function TAntWorld.WrapCoords(var X, Y: integer): boolean;
begin
if fWrap then begin
Result:= true;
X:= (X + Width) mod Width;
Y:= (Y + Height) mod Height;
end else begin
Result:= (X>=0) and (Y>=0) and (X<Width) and (Y<Height);
end;
end;
end.
|
{ *******************************************************************************
* *
* TksProgressIndicator *
* *
* https://bitbucket.org/gmurt/kscomponents *
* *
* Copyright 2017 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License forthe specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
unit ksProgressIndicator;
interface
uses FMX.Controls, Classes, FMX.StdCtrls, FMX.Graphics, FMX.Types, FMX.Objects,
System.UIConsts, System.UITypes;
type
TksProgressIndicator = class;
TksProgressIndicatorSteps = class(TPersistent)
private
[weak]FOwner: TksProgressIndicator;
FMaxSteps: integer;
FCurrentStep: integer;
FSize: integer;
FVisible: Boolean;
procedure SetCurrentStep(const Value: integer);
procedure SetMaxSteps(const Value: integer);
procedure SetVisible(const Value: Boolean);
procedure Changed;
procedure SetSize(const Value: integer);
public
constructor Create(AOwner: TksProgressIndicator);
published
property MaxSteps: integer read FMaxSteps write SetMaxSteps default 5;
property CurrentStep: integer read FCurrentStep write SetCurrentStep default 1;
property Size: integer read FSize write SetSize default 12;
property Visible: Boolean read FVisible write SetVisible default True;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TksProgressIndicator = class(TControl)
private
FSteps: TksProgressIndicatorSteps;
FActiveColor: TAlphaColor;
FInActiveColor: TAlphaColor;
FBitmap: TBitmap;
FOutlineColor: TAlphaColor;
FKeepHighlighted: Boolean;
procedure SetActiveColor(const Value: TAlphaColor);
procedure SetInActiveColor(const Value: TAlphaColor);
procedure Redraw;
procedure Changed;
protected
procedure Paint; override;
procedure Resize; override;
procedure SetOutlineColor(const Value: TAlphaColor);
procedure SetKeepHighlighted(const Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property ActiveColor: TAlphaColor read FActiveColor write SetActiveColor default claDodgerblue;
property InactiveColor: TAlphaColor read FInActiveColor write SetInActiveColor default claSilver;
property KeepHighlighted: Boolean read FKeepHighlighted write SetKeepHighlighted default False;
property Align;
property Position;
property Width;
property Height;
property Steps: TksProgressIndicatorSteps read FSteps write FSteps;
property OutlineColor: TAlphaColor read FOutlineColor write SetOutlineColor default claNull;
end;
procedure Register;
implementation
uses Types, SysUtils, FMX.Platform, ksCommon;
procedure Register;
begin
RegisterComponents('Pentire FMX', [TksProgressIndicator]);
end;
{ TksProgressIndicatorSteps }
procedure TksProgressIndicatorSteps.Changed;
begin
FOwner.Changed;
end;
constructor TksProgressIndicatorSteps.Create(AOwner: TksProgressIndicator);
begin
inherited Create;
FOwner := AOwner;
FMaxSteps := 5;
FCurrentStep := 1;
FSize := 12;
FVisible := True;
end;
procedure TksProgressIndicatorSteps.SetCurrentStep(const Value: integer);
begin
FCurrentStep := Value;
Changed;
end;
procedure TksProgressIndicatorSteps.SetMaxSteps(const Value: integer);
begin
FMaxSteps := Value;
Changed;
end;
procedure TksProgressIndicatorSteps.SetSize(const Value: integer);
begin
if FSize <> Value then
begin
FSize := Value;
Changed;
end;
end;
procedure TksProgressIndicatorSteps.SetVisible(const Value: Boolean);
begin
if FVisible <> Value then
begin
FVisible := Value;
Changed;
end;
end;
{ TksProgressIndicator }
procedure TksProgressIndicator.Changed;
begin
Redraw;
InvalidateRect(ClipRect);
end;
constructor TksProgressIndicator.Create(AOwner: TComponent);
begin
inherited;
FSteps := TksProgressIndicatorSteps.Create(Self);
FBitmap := TBitmap.Create;
Size.Width := 200;
Size.Height := 40;
FActiveColor := claDodgerblue;
FInActiveColor := claSilver;
FKeepHighlighted := False;
Redraw;
end;
destructor TksProgressIndicator.Destroy;
begin
FreeAndNil(FSteps);
FreeAndNil(FBitmap);
inherited;
end;
procedure TksProgressIndicator.Paint;
begin
inherited;
Canvas.BeginScene;
Canvas.DrawBitmap(FBitmap,
RectF(0, 0, FBitmap.Width, FBitmap.Height),
ClipRect,
1,
False);
Canvas.EndScene;
end;
procedure TksProgressIndicator.Redraw;
var
ARect: TRectF;
AXPos: single;
ASize: single;
ICount: integer;
AColor: TAlphaColor;
begin
if FBitmap = nil then
Exit;
FBitmap.Resize(Round(Size.Width * (GetScreenScale*2)), Round(Size.Height * (GetScreenScale*2)));
FBitmap.Clear(claNull);
ASize := FSteps.Size * (GetScreenScale*2);
if FSteps.Visible = False then
Exit;
ARect := RectF(0, 0, (FSteps.MaxSteps + (FSteps.MaxSteps-1)) * ASize, ASize);
OffsetRect(ARect, ((Width * (GetScreenScale*2)) - ARect.Width) / 2, ((Height * (GetScreenScale*2)) - ARect.Height) / 2);
AXpos := ARect.Left;
FBitmap.Canvas.BeginScene;
try
for ICount := 0 to FSteps.MaxSteps-1 do
begin
AColor := FInactiveColor;
if ((ICount+1) = FSteps.CurrentStep) then
AColor := FActiveColor;
if ((ICount+1) < FSteps.CurrentStep) and (FKeepHighlighted) then
AColor := FActiveColor;
FBitmap.Canvas.Stroke.Color := FOutlineColor;
FBitmap.Canvas.Stroke.Thickness := GetScreenScale * 2;
FBitmap.Canvas.Stroke.Kind := TBrushKind.Solid;
FBitmap.Canvas.Fill.Color := AColor;
FBitmap.Canvas.Fill.Kind := TBrushKind.Solid;
FBitmap.Canvas.FillEllipse(RectF(AXPos, ARect.Top, AXpos+ASize, ARect.Top+ASize), 1);
FBitmap.Canvas.DrawEllipse(RectF(AXPos, ARect.Top, AXpos+ASize, ARect.Top+ASize), 1);
AXPos := AXPos + (ASize*2);
end;
finally
FBitmap.Canvas.EndScene;
end;
end;
procedure TksProgressIndicator.Resize;
begin
inherited;
Changed;
end;
procedure TksProgressIndicator.SetActiveColor(const Value: TAlphaColor);
begin
if FActiveColor <> Value then
begin
FActiveColor := Value;
Repaint;
end;
end;
procedure TksProgressIndicator.SetInActiveColor(const Value: TAlphaColor);
begin
if FInActiveColor <> Value then
begin
FInActiveColor := Value;
Redraw;
end;
end;
procedure TksProgressIndicator.SetKeepHighlighted(const Value: Boolean);
begin
FKeepHighlighted := Value;
Redraw;
end;
procedure TksProgressIndicator.SetOutlineColor(const Value: TAlphaColor);
begin
FOutlineColor := Value;
Redraw;
end;
initialization
Classes.RegisterClass(TksProgressIndicator);
end.
|
unit uContentLink;
interface
uses
Classes, SysUtils;
type
TContentLink = class(TPersistent)
protected
fUrl: String;
fName : String;
fDescription: String;
fContentType: String;
published
property Url: String read fUrl write fUrl;
property Name : String read fName write fName;
property Description: String read fDescription write fDescription;
property ContentType: String read fContentType write fContentType;
end;
implementation
end.
|
unit TextConverter.Model.ConverteInvertido;
interface
uses
System.StrUtils,
TextConverter.Model.ConverteTexto;
type
TConverteInvertido = class(TConverteTexto)
public
function Converter : String; override;
end;
implementation
{ TConverteInvertido }
function TConverteInvertido.Converter: String;
begin
Result := ReverseString(Self.Texto);
end;
end.
|
unit DmRtcUseMonth;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DmRtcCustom, rtcFunction, rtcSrvModule, rtcInfo, rtcConn, rtcDataSrv;
type
TRtcUseMonthDm = class(TRtcCustomDm)
RtcDataServerLinkUseMonth: TRtcDataServerLink;
RtcServerModuleUseMonth: TRtcServerModule;
RtcFunctionGroupUseMonth: TRtcFunctionGroup;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
function GetDefaultGroup: TRtcFunctionGroup;override;
public
{ Public declarations }
procedure RtcUsemonthEdit(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue);
end;
var
RtcUseMonthDm: TRtcUseMonthDm;
implementation
{$R *.dfm}
uses DmMain, DmRtcCommonFunctions, DateVk;
{ TDmRtcUseMonth }
procedure TRtcUseMonthDm.DataModuleCreate(Sender: TObject);
begin
inherited;
RegisterRtcFunction('RtcUsemonthEdit',RtcUsemonthEdit);
end;
function TRtcUseMonthDm.GetDefaultGroup: TRtcFunctionGroup;
begin
Result := RtcFunctionGroupUseMonth;
end;
procedure TRtcUseMonthDm.RtcUsemonthEdit(Sender: TRtcConnection; Param: TRtcFunctionInfo; Result: TRtcValue);
var
mUserName, mPassword: string;
mDmMain: TMainDm;
i: Integer;
nTrOption: Integer;
mYm: String;
nType: Integer;
nClosed: Integer;
begin
mUserName := Param.AsString['username'];
mPassword := Param.AsString['password'];
nType := Param.asInteger['nType'];
mDmMain := TRtcCommonFunctionsDm(Owner).GetDmMainUib(Sender,mUserName,mPassword);
with mDmMain do
begin
// Стартовая дата
case nType of
0:
begin
mYm := Param.asString['ym'];
//Execute('INSERT INTO usemonth(ym,closed) VALUES(:ym,:closed)',[mYm,0],UIBTransactionStability);
end;
1:
begin
//mYm := CoalEsce(QueryValue('SELECT max(ym) FROM usemonth',[]),'');
mYm := GetNextYearMonth(mYm,1);
//Execute('INSERT INTO usemonth(ym,closed) VALUES(:ym,:closed)',[mYm,0],UIBTransactionStability);
end;
2:
begin
mYm := Param.asString['ym'];
nClosed := Param.asInteger['closed'];
//Execute('UPDATE usemonth SET closed=:closed WHERE ym=:ym',[nClosed,mYm],UIBTransactionStability);
end;
3:
begin
//mYm := CoalEsce(QueryValue('SELECT min(ym) FROM usemonth',[]),'');
//Execute('DELETE usemonth WHERE ym=:ym',[mYm],UIBTransactionStability);
end;
end;
end;
end;
end.
|
(* minimal pascal compiler
* (c) 2014 by ir. Marc Dendooven *)
program edPas;
(*****************************************************************
* system parameters. you can make adjustments.
******************************************************************)
// compiler
const maxId = 1024;
// virtual machine
maxProg = 1023;
maxStack = 1023;
maxDivLev = 15; // max difference between static levels
(*****************************************************************
* general stuff
******************************************************************)
var f: text; // input file
procedure error(s: string);
begin
writeln;
writeln(s);writeln;
halt
end;
(*****************************************************************
* virtual machine
******************************************************************)
type mnemonic = (LIT,NEG,ADD,SUB,MUL,DIVi,EQL,NEQ,LESS,LEQ,GTR,GEQ,
ODDi,LOAD,STORE,JMP,JPZ,CALL,RET,ISP,WRITEi,WRITEC,READi,HALT);
instruction = record
m: mnemonic;
dl: 0..maxDivLev;
val : integer
end;
var pm: array[0..maxProg] of instruction; //program memory
procedure interpret;
var PC,SP,LV: cardinal;
IR: instruction;
s: array[0..maxStack] of longInt; //stack
function base : cardinal;
var i: cardinal;
begin
base := LV;
for i := 1 to IR.dl do base := s[base]
end;
begin
PC := 0; SP:=0; LV := 0;
while true do begin
if PC > maxProg then error('RUNTIME ERROR: program memory size exceeded.'); // should not be necessary ...
if SP > maxStack then error('RUNTIME ERROR: stack size exceeded.');
IR := pm[PC];
PC := PC+1;
case IR.m of
LIT: begin s[SP] := IR.val; inc(SP) end;
NEG:s[SP-1] := -s[SP-1];
ADD:begin dec(SP);s[SP-1] := s[SP-1] + s[SP] end;
SUB:begin dec(SP);s[SP-1] := s[SP-1] - s[SP] end;
MUL:begin dec(SP);s[SP-1] := s[SP-1] * s[SP] end;
DIVi:begin dec(SP);s[SP-1] := s[SP-1] div s[SP] end;
EQL: begin dec(SP);s[SP-1] := ord(s[SP-1] = s[SP]) end;
NEQ: begin dec(SP);s[SP-1] := ord(s[SP-1] <> s[SP]) end;
LESS:begin dec(SP);s[SP-1] := ord(s[SP-1] < s[SP]) end;
LEQ: begin dec(SP);s[SP-1] := ord(s[SP-1] <= s[SP]) end;
GTR: begin dec(SP);s[SP-1] := ord(s[SP-1] > s[SP]) end;
GEQ: begin dec(SP);s[SP-1] := ord(s[SP-1] >= s[SP]) end;
ODDi: s[SP-1]:=ord(odd(s[SP-1]));
LOAD: begin s[SP] := s[base+IR.val]; inc(SP) end;
STORE: begin dec(SP); s[base+IR.val] := s[SP] end;
JMP: PC := IR.val;
JPZ: begin dec(SP); if s[SP]=0 then PC := IR.val end;
CALL: begin s[SP] := base; s[SP+1] := LV; s[SP+2] := PC; LV := SP; PC := IR.val end;
RET: begin PC := s[LV+2]; SP := LV; LV := s[LV+1] end;
ISP: SP := SP + IR.val;
WRITEi: begin dec(SP); write(s[SP]) end;
WRITEc: begin dec(SP); write(chr(s[SP])) end;
READi: begin read(s[SP]); inc(SP) end;
HALT: break
end
end
end;
(*****************************************************************
* code generator
******************************************************************)
var address : cardinal = 0;
procedure gen(m0: mnemonic; dl0: cardinal; val0: integer);
begin
if address > maxProg then error('INTERNAL ERROR: program memory size exceeded.');
if dl0 > maxDivLev then error('INTERNAL ERROR: max difference between static levels exceeded.');
with pm[address] do begin
m := m0;
dl := dl0;
val := val0
end;
inc(address);
end;
function nextAdr: cardinal;
begin
nextAdr := address
end;
procedure fix(a: cardinal);
begin
pm[a].val := address
end;
procedure showCode;
var a: cardinal;
begin
for a := 0 to address-1 do
with pm[a] do writeln(a,': ',m,' ',dl,' ',val)
end;
(*****************************************************************
* identifiers
******************************************************************)
type idKind = (id_const, id_var, id_proc, id_func);
idDescr = record
Name: string;
level: cardinal;
kind: idKind;
data: cardinal;
end;
var idList : array[1..maxId] of idDescr;
fip : cardinal = 1; // free id pointer
currentLevel : cardinal = 0;
procedure checkForDouble(name: string);
var i: cardinal;
begin
i := fip-1;
while (i > 0) and (idList[i].level = currentLevel) do
begin
if (name = idList[i].name) then error('ERROR: Duplicate identifier "'+name+'"');
i:=i-1
end
end;
procedure addId(name: string; kind: idKind; data : cardinal);
begin
checkForDouble(name);
if fip > maxId then error('INTERNAL ERROR: max objects exceeded.');
idList[fip].name := name;
idList[fip].level := CurrentLevel;
idList[fip].kind := kind;
idList[fip].data := data;
fip:=fip+1;
// writeln;writeln;writeln('*** ',name,' ',kind,' ',data,' ***');writeln
end;
function getId(name: string): idDescr;
var i : cardinal;
notfound: boolean = true;
begin
i := fip-1;
while (i > 0) do
begin
if (name = idList[i].name) then begin getId := idList[i]; notfound := false; break end;
i:=i-1
end;
if notfound then error('ERROR: identifier not found "'+name+'"')
end;
(*****************************************************************
* scanner
******************************************************************)
type Symbols = (s_number, s_ident, s_program, s_begin, s_end, s_const,
s_var, s_proc, s_func, s_if, s_then, s_else, s_while, s_do, s_for, s_to, s_repeat, s_until, s_write,
s_writeln, s_read, s_odd, s_integer,
s_times, s_div, s_plus, s_minus, s_eql, s_neq, s_less,
s_leq, s_gtr, s_geq, s_comma, s_rparen, s_lparen,
s_becomes, s_semi, s_colon, s_period, s_eof, s_string, s_other);
const symText: array[s_number .. s_other] of string = ('NUMBER',
'IDENTIFIER','PROGRAM', 'BEGIN', 'END', 'CONST',
'VAR', 'PROCEDURE', 'FUNCTION', 'IF', 'THEN', 'ELSE', 'WHILE', 'DO', 'FOR', 'TO', 'REPEAT', 'UNTIL', 'WRITE',
'WRITELN', 'READ', 'ODD', 'INTEGER',
'*','/','+','-','=','<>','<',
'<=','>','>=',',',')','(',
':=',';',':','.','END OF FILE','STATIC STRING','SOMETHING ELSE');
var ch : char; // lookahead character
symbol : Symbols; // lookahead symbol
val: cardinal; // value of a number
name: string; // name of an identifier
procedure getCh;
begin
if eof(f) then ch := #0 // ascii eof value
else begin
read(f,ch);
write(ch)
end
end;
procedure getSym;
procedure number;
begin
symbol := s_number;
val := 0;
while ch in ['0'..'9'] do begin
val := 10*val+ord(ch)-ord('0');
getCh
end
end;
procedure identifier;
var i: Symbols;
begin
symbol := s_ident;
name := '';
while ch in ['a'..'z','A'..'Z','0'..'9'] do begin
name := name + upcase(ch);
getCh
end;
for i := s_program to s_integer do if name = symText[i] then symbol := i
end;
procedure other;
var i: Symbols;
procedure comment;
begin
getCh;
repeat
while ch <> '*' do getCh;
getCh
until ch = ')';
getCh
end;
begin //other
symbol := s_other;
name := ch;
case ch of
#0 : symbol := s_eof;
'(': begin getCh;
if ch = '*' then begin comment; getSym end
end;
'<','>',':': begin
getCh;
if ch in ['=','>'] then begin name := name + ch; getCh end
end;
else getCh
end;
for i := s_times to s_period do if name = symText[i] then symbol := i
end;
procedure aString;
begin
symbol := s_string;
name := '';
getCh;
while ch<>'''' do begin name := name+ch; getCh end;
getCh
end;
begin //getSym
while ch in [#1..#32] do getCh; //skip whiteSpace
case ch of
'0'..'9': number;
'a'..'z','A'..'Z': identifier;
'''': aString;
else other
end
// writeln('***',symbol,'***',val,'***',name,'***')
end;
(********************************************************
* parser
*********************************************************)
procedure nyi;
begin
error('INTERNAL ERROR: '+symtext[symbol]+' : this feature is not yet implemented')
end;
procedure expect(s: Symbols);
begin
if s = symbol then getSym
else error('SYNTAX ERROR: "'+symtext[s]+'" expected but "'+symtext[symbol]+'" found.')
end;
procedure aProgram;
procedure block(paramCount: cardinal);
var oldfip: cardinal;
varcount: cardinal = 3; // 0,1 and 2 are static link, dyn link and old PC
lab0: cardinal;
procedure const_decl;
procedure define_constant;
var cname : string;
begin
cname := name;
expect(s_ident);
expect(s_eql);
addId(cname, id_const, val);
expect(s_number);
expect(s_semi)
end;
begin // const_decl
getSym;
define_constant;
while symbol = s_ident do define_constant
end;
procedure var_decl;
procedure define_var;
begin
getSym;
addId(name,id_var,varCount+paramCount); // var relative address should be added
inc(varCount);
expect(s_ident);
end;
begin // var_decl
define_var;
while symbol = s_comma do define_var;
expect(s_colon);expect(s_integer);
expect(s_semi)
end;
procedure proc;
var formalParamCount: integer = 0;
id: idKind;
procedure formalParamList;
procedure define_param;
begin
getSym;
addId(name,id_var,formalParamCount+3);
inc(formalParamCount);
expect(s_ident);
end;
begin //formalParamList
define_param;
while symbol = s_comma do define_param;
expect(s_colon);expect(s_integer);
expect(s_rparen)
end;
begin //proc
if symbol = s_proc then id := id_proc else id := id_func;
getSym;
addId(name,id,nextAdr);
expect(s_ident);
(**) currentLevel := currentLevel+1; oldfip := fip;
if symbol = s_lparen then formalParamList;
if id = id_func then begin expect(s_colon); expect(s_integer) end;
expect(s_semi);
block(formalParamCount); expect(s_semi);
(**) currentLevel := currentLevel-1; fip := oldfip;
(**) gen(RET,0,0)
end;
procedure statement; forward;
procedure compound_Statement;
begin
expect(s_begin);
statement;
while symbol = s_semi do begin getSym; statement end;
expect(s_end)
end;
procedure statement;
var lab0,lab1: cardinal;
procedure expression;
var s0 : Symbols;
procedure term;
var s0 : Symbols;
procedure factor;
var id: idDescr;
actualParamCount: cardinal = 0;
procedure actualParamList;
begin
expect(s_lparen);
expression; inc(ActualParamCount);
while symbol = s_comma do begin expect(s_comma); expression; inc(actualParamCount) end;
// expect(s_rparen);
end;
begin // factor
case symbol of
s_ident:begin
id := getId(name);
case id.kind of
id_const: gen(LIT,0,id.data);
id_var: gen(LOAD,currentLevel-id.level,id.data);
id_func: begin
getSym;
gen(ISP,0,4); // make room for return value and SL, DL and old PC
if symbol = s_lparen then actualParamList;
gen(ISP,0,-actualParamCount-3);
gen(CALL,currentLevel-id.level,id.data)
end
else
error('ERROR: constant, variable or function expected')
end;
getSym
end;
s_number: begin gen(LIT,0,val);getSym end;
s_lparen: begin expect(s_lparen); expression; expect(s_rparen) end
else error('SYNTAX ERROR: One of "IDENTIFIER", "NUMBER" or "(" expected but "'+symtext[symbol]+'" found.')
end
end;
begin //term
factor;
while symbol in [s_times,s_div] do begin s0 := symbol; getSym;
factor;
if s0 = s_times then gen(MUL,0,0) else gen(DIVi,0,0)
end
end;
begin //expression
s0 := symbol;
if symbol in [s_minus,s_plus] then getSym;
term; if s0 = s_minus then gen(NEG,0,0);
while symbol in [s_minus,s_plus] do begin s0:= symbol;getSym;
term;
if s0 = s_minus then gen(SUB,0,0) else gen(ADD,0,0)
end
end;
procedure assign_or_call;
var id: idDescr;
actualParamCount: cardinal = 0;
procedure actualParamList;
begin
expect(s_lparen);
expression; inc(ActualParamCount);
while symbol = s_comma do begin expect(s_comma); expression; inc(actualParamCount) end;
expect(s_rparen);
end;
begin
id := getId(name);
expect(s_ident);
if symbol = s_becomes
then //assign
begin
expect(s_becomes);
case id.kind of
id_var : begin expression; gen(STORE,currentLevel-id.level,id.data) end;
id_func: begin expression; gen(STORE,currentLevel-id.level-1,-1) end;
else error('error: variable or function name expected')
end
end
else
begin //call procedure
if id.kind <> id_proc then error('error: procedure expected');
gen(ISP,0,3);
if symbol = s_lparen then actualParamList;
gen(ISP,0,-actualParamCount-3);
gen(CALL,currentLevel-id.level,id.data)
end
end;
procedure condition;
procedure diatomic;
var s0: Symbols;
begin
expression;
s0 := symbol;
getSym;
expression;
case s0 of
s_eql: gen(EQL,0,0);
s_neq: gen(NEQ,0,0);
s_less: gen(LESS,0,0);
s_leq: gen(LEQ,0,0);
s_gtr: gen(GTR,0,0);
s_geq: gen(GEQ,0,0);
else error('SYNTAX ERROR: One of "ODD", "=", "<>", "<", ">=", ">", ">=" expected but "'+symtext[symbol]+'" found.')
end
end;
begin //condition
case symbol of
s_odd : begin expect(s_odd); expect(s_lparen); expression; expect(s_rparen);gen(ODDi,0,0) end
// other buildin functions come here
else diatomic;
end
end;
procedure if_stat;
begin
expect(s_if); condition; lab0 := nextAdr; gen(JPZ,0,0); expect(s_then); statement; lab1 := nextAdr; gen(JMP,0,0); fix(lab0);
if symbol = s_else then begin expect(s_else); statement end;
fix(lab1)
end;
procedure while_stat;
begin
expect(s_while); lab0 := nextAdr; condition; lab1 := nextAdr ;gen(JPZ,0,0); expect(s_do); statement; gen(JMP,0,lab0); fix(lab1)
end;
procedure repeat_stat;
begin
expect(s_repeat); lab0 := nextAdr; statement; expect(s_until); condition; gen(JPZ,0,lab0)
end;
procedure for_stat;
var id: idDescr;
begin
expect(s_for); id := getId(name); if id.kind <> id_var then error('error: variable identifier expected');
expect(s_ident); expect(s_becomes); expression; gen(STORE,currentLevel-id.level,id.data); //assign loopvar
expect(s_to); lab1 := nextAdr; gen(LOAD,currentLevel-id.level,id.data); //reload loopvar
expression; ; gen(LEQ,0,0); lab0 := nextAdr; // compare to expression
gen(JPZ,0,0); //jump to end if loopvar > expression
expect(s_do); statement;
gen(LOAD,currentLevel-id.level,id.data); gen(LIT,0,1);
gen(ADD,0,0);gen(STORE,currentLevel-id.level,id.data); gen(JMP,0,LAB1); // increment loopvar and jump back
fix(lab0)
end;
procedure write_stat;
procedure doWrite;
var i: cardinal;
begin
getSym;
if symbol = s_string
then begin
for i := 1 to length(name) do begin gen(LIT,0,ord(name[i]));gen(WRITEc,0,0) end;
expect(s_string)
end
else begin expression;gen(WRITEi,0,0) end
end;
begin
getSym;
if symbol = s_lparen then
begin
doWrite;
while symbol = s_comma do doWrite;
expect(s_rparen)
end
end;
procedure writeln_stat;
begin
write_stat;
gen(LIT,0,10);gen(WRITEc,0,0) // newline... for windows CR should be added
end;
procedure read_stat;
var id: idDescr;
begin
expect(s_read);expect(s_lparen);
id := getId(name); expect(s_ident);
if id.Kind <> id_var then error('ERROR: variable expected');
gen(READi,0,0);gen(STORE,currentLevel-id.level,id.data);
expect(s_rparen)
end;
begin //statement
case symbol of
s_ident: assign_or_call;
s_if: if_stat;
s_while: while_stat;
s_repeat: repeat_stat;
s_for: for_stat;
s_begin: compound_Statement;
s_write: write_stat;
s_writeln: writeln_stat;
s_read: read_stat;
else error('SYNTAX ERROR: Statement expected but "'+symtext[symbol]+'" found.')
end
end;
begin //block
// currentLevel := currentLevel+1; oldfip := fip;
if symbol = s_const then const_decl;
if symbol = s_var then var_decl;
lab0 := nextAdr; gen(JMP,0,0);
while symbol in [s_proc,s_func] do proc;
// while symbol = s_func do func;
fix(lab0);
gen(ISP,0,varCount+paramCount);
compound_Statement;
// currentLevel := currentLevel-1; fip := oldfip;
// if currentLevel > 0 then gen(RET,0,0) else gen(HALT,0,0)
end;
begin //aProgram
expect(s_program);expect(s_ident);expect(s_semi); //header
block(0); expect(s_period);
(**)gen(HALT,0,0)
end;
begin // edPas
writeln('**************************************');
writeln('* Minimal pascal compiler *');
writeln('* (c) 2014 by ir. Marc Dendooven *');
writeln('**************************************');
writeln;
if paramStr(1)='' then error('ERROR: sourcefile missing');
{$I-}
assign (f,paramStr(1));
reset(f);
{$I+}
if IOresult <> 0 then error('ERROR: no such file');
getCh;
getSym;
aProgram;
writeln;
writeln('**************************************');
writeln('* Compilation has succesfully ended *');
writeln('* P-code is: *');
writeln('**************************************');
writeln;
showCode;
writeln;
writeln('**************************************');
writeln('* Executing program: *');
writeln('* *');
writeln('**************************************');
writeln;
interpret;
writeln;
writeln('**************************************');
writeln('* Execution has succesfully ended *');
writeln('* bye *');
writeln('**************************************');
writeln;
close(f)
end.
|
unit uTarefa1Test;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.Variants, FireDAC.Stan.Error, Data.DB, uspQuery,
FireDAC.Stan.Intf, Winapi.Windows, Vcl.Dialogs, FireDAC.Stan.Async, FireDAC.DatS,
Vcl.Forms, FireDAC.Comp.DataSet, FireDAC.Stan.Param, FireDAC.Comp.Client,
Vcl.Controls, FireDAC.Stan.Option, System.Classes, System.SysUtils, Winapi.Messages,
FireDAC.DApt.Intf, Vcl.Graphics, FireDAC.DApt, Vcl.StdCtrls, Vcl.Buttons, ufTarefa1,
FireDAC.Phys.Intf,DUnitX.TestFramework;
type
// Test methods for class TfTarefa1
[TestFixture]
TestTfTarefa1 = class(TTestCase)
strict private
FfTarefa1: TfTarefa1;
public
[Test]
procedure TestMontaSql;
end;
implementation
procedure TestTfTarefa1.TestMontaSql;
var
ReturnValue: string;
Condicoes: TMemo;
Tabelas: TMemo;
Colunas: TMemo;
ResultadoEsperado: String;
begin
// TODO: Setup method call parameters
FfTarefa1 := TfTarefa1.Create(nil);
try
Condicoes.Lines.Strings[0] := 'Condicao = 1';
Tabelas.Lines.Strings[0] := 'Tabela';
Colunas.Lines.Strings[0] := 'Coluna';
ReturnValue := FfTarefa1.MontaSql(Colunas, Tabelas, Condicoes);
ResultadoEsperado := 'Select Coluna From Tabela Where Condicao = 1';
CheckEqualsString(ResultadoEsperado, ReturnValue, 'Funçao MontarSql Falhou');
finally
FreeAndNil(FfTarefa1);
end;
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
TDUnitX.RegisterTestFixture(TestTfTarefa1);
end.
|
unit OpenAPI.Model.Base;
interface
uses
System.SysUtils, System.Classes,
Neon.Core.Types,
Neon.Core.Attributes,
OpenAPI.Model.Reference;
type
/// <summary>
/// Base class for OpenAPI model classes
/// </summary>
TOpenAPIModel = class
protected
function InternalCheckModel: Boolean; virtual;
public
function CheckModel: Boolean; inline;
end;
TOpenAPIModelReference = class(TOpenAPIModel)
protected
FReference: TOpenAPIReference;
public
/// <summary>
/// Reference object.
/// </summary>
[NeonProperty('$ref')][NeonInclude(IncludeIf.NotEmpty)]
property Reference: TOpenAPIReference read FReference write FReference;
end;
implementation
{ TOpenAPIModel }
function TOpenAPIModel.CheckModel: Boolean;
begin
Result := InternalCheckModel;
end;
function TOpenAPIModel.InternalCheckModel: Boolean;
begin
Result := True;
end;
end.
|
unit About;
interface
uses
System.SysUtils, Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Vcl.Imaging.pngimage, BCDialogs.Dlg;
type
TAboutDialog = class(TDialog)
GrayLinePanel: TPanel;
MemoryAvailableLabel: TLabel;
OSLabel: TLabel;
ProgramNameiLabel: TLabel;
TopPanel: TPanel;
VersionLabel: TLabel;
BottomPanel: TPanel;
Button2: TButton;
DonationsButton: TButton;
ImagePanel: TPanel;
OraBoneImage: TImage;
CopyrightLabel: TLabel;
ThanksToPanel: TPanel;
ThirdPartyComponentsLabel: TLabel;
IconsLabel: TLabel;
DevelopmentEnvironmentLabel: TLabel;
LinkLabel2: TLinkLabel;
LinkRow4Label: TLinkLabel;
LinkLabel3: TLinkLabel;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure LinkClick(Sender: TObject; const Link: string; LinkType: TSysLinkType);
procedure DonationsButtonClick(Sender: TObject);
private
function GetVersion: string;
public
procedure Open;
property Version: string read GetVersion;
end;
function AboutDialog: TAboutDialog;
implementation
{$R *.dfm}
uses
BCCommon.Lib, BCCommon.StyleUtils, BCCommon.FileUtils;
var
FAboutDialog: TAboutDialog;
function AboutDialog: TAboutDialog;
begin
if not Assigned(FAboutDialog) then
Application.CreateForm(TAboutDialog, FAboutDialog);
Result := FAboutDialog;
SetStyledFormSize(Result);
end;
procedure TAboutDialog.Open;
var
MemoryStatus: TMemoryStatusEx;
begin
VersionLabel.Caption := Format(VersionLabel.Caption, [BCCommon.FileUtils.GetFileVersion(Application.ExeName),
{$IFDEF WIN64}64{$ELSE}32{$ENDIF}]);
{ initialize the structure }
FillChar(MemoryStatus, SizeOf(MemoryStatus), 0);
MemoryStatus.dwLength := SizeOf(MemoryStatus);
{ check return code for errors }
{$WARNINGS OFF}
Win32Check(GlobalMemoryStatusEx(MemoryStatus));
{$WARNINGS ON}
OSLabel.Caption := GetOSInfo;
MemoryAvailableLabel.Caption := Format(MemoryAvailableLabel.Caption, [FormatFloat('#,###" KB"', MemoryStatus.ullAvailPhys div 1024)]);
ShowModal;
end;
procedure TAboutDialog.LinkClick(Sender: TObject; const Link: string;
LinkType: TSysLinkType);
begin
BrowseURL(Link);
end;
procedure TAboutDialog.DonationsButtonClick(Sender: TObject);
begin
inherited;
BrowseURL(DONATION_URL);
end;
procedure TAboutDialog.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
procedure TAboutDialog.FormDestroy(Sender: TObject);
begin
FAboutDialog := nil;
end;
function TAboutDialog.GetVersion: string;
begin
Result := BCCommon.FileUtils.GetFileVersion(Application.ExeName);
end;
end.
|
{
BASSASIO 1.0 Delphi unit
Copyright (c) 2005-2009 Un4seen Developments Ltd.
See the BASSASIO.CHM file for more detailed documentation
}
unit BassASIO;
interface
uses Windows;
const
BASSASIOVERSION = $100; // API version
// error codes returned by BASS_ASIO_ErrorGetCode
BASS_OK = 0; // all is OK
BASS_ERROR_DRIVER = 3; // can't find a free/valid driver
BASS_ERROR_FORMAT = 6; // unsupported sample format
BASS_ERROR_INIT = 8; // BASS_ASIO_Init has not been successfully called
BASS_ERROR_START = 9; // BASS_ASIO_Start has/hasn't been called
BASS_ERROR_ALREADY = 14; // already initialized/started
BASS_ERROR_NOCHAN = 18; // no channels are enabled
BASS_ERROR_ILLPARAM = 20; // an illegal parameter was specified
BASS_ERROR_DEVICE = 23; // illegal device number
BASS_ERROR_NOTAVAIL = 37; // not available
BASS_ERROR_UNKNOWN = -1; // some other mystery error
// sample formats
BASS_ASIO_FORMAT_16BIT = 16; // 16-bit integer
BASS_ASIO_FORMAT_24BIT = 17; // 24-bit integer
BASS_ASIO_FORMAT_32BIT = 18; // 32-bit integer
BASS_ASIO_FORMAT_FLOAT = 19; // 32-bit floating-point
// BASS_ASIO_ChannelReset flags
BASS_ASIO_RESET_ENABLE = 1; // disable channel
BASS_ASIO_RESET_JOIN = 2; // unjoin channel
BASS_ASIO_RESET_PAUSE = 4; // unpause channel
BASS_ASIO_RESET_FORMAT = 8; // reset sample format to native format
BASS_ASIO_RESET_RATE = 16; // reset sample rate to device rate
BASS_ASIO_RESET_VOLUME = 32; // reset volume to 1.0
// BASS_ASIO_ChannelIsActive return values
BASS_ASIO_ACTIVE_DISABLED = 0;
BASS_ASIO_ACTIVE_ENABLED = 1;
BASS_ASIO_ACTIVE_PAUSED = 2;
type
DWORD = Cardinal;
BOOL = LongBool;
FLOAT = Single;
// device info structure
BASS_ASIO_DEVICEINFO = record
name: PAnsiChar; // description
driver: PAnsiChar; // driver
end;
BASS_ASIO_INFO = record
name: array[0..31] of AnsiChar; // driver name
version: DWORD; // driver version
inputs: DWORD;
outputs: DWORD;
bufmin: DWORD;
bufmax: DWORD;
bufpref: DWORD;
bufgran: integer;
end;
BASS_ASIO_CHANNELINFO = record
group: DWORD;
format: DWORD; // sample format (BASS_ASIO_FORMAT_xxx)
name: array[0..31] of AnsiChar; // channel name
end;
ASIOPROC = function(input:BOOL; channel:DWORD; buffer:Pointer; length:DWORD; user:Pointer): DWORD; stdcall;
{
ASIO channel callback function.
input : input? else output
channel: channel number
buffer : Buffer containing the sample data
length : Number of bytes
user : The 'user' parameter given when calling BASS_ASIO_ChannelEnable
RETURN : The number of bytes written (ignored with input channels)
}
const
bassasiodll = 'bassasio.dll';
function BASS_ASIO_GetVersion: DWORD; stdcall; external bassasiodll;
function BASS_ASIO_ErrorGetCode(): DWORD; stdcall; external bassasiodll;
function BASS_ASIO_GetDeviceInfo(device:DWORD; var info:BASS_ASIO_DEVICEINFO): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_SetDevice(device:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_GetDevice(): DWORD; stdcall; external bassasiodll;
function BASS_ASIO_Init(device:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_Free(): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ControlPanel(): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_GetInfo(var info:BASS_ASIO_INFO): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_SetRate(rate:double): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_GetRate(): double; stdcall; external bassasiodll;
function BASS_ASIO_Start(buflen:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_Stop(): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_IsStarted(): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_GetLatency(input:BOOL): DWORD; stdcall; external bassasiodll;
function BASS_ASIO_GetCPU(): float; stdcall; external bassasiodll;
function BASS_ASIO_Monitor(input:Integer; output,gain,state,pan:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelGetInfo(input:BOOL; channel:DWORD; var info:BASS_ASIO_CHANNELINFO): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelReset(input:BOOL; channel:Integer; flags:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelEnable(input:BOOL; channel:DWORD; proc:ASIOPROC; user:Pointer): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelEnableMirror(channel:DWORD; input2:BOOL; channel2:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelJoin(input:BOOL; channel:DWORD; channel2:Integer): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelPause(input:BOOL; channel:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelIsActive(input:BOOL; channel:DWORD): DWORD; stdcall; external bassasiodll;
function BASS_ASIO_ChannelSetFormat(input:BOOL; channel:DWORD; format:DWORD): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelGetFormat(input:BOOL; channel:DWORD): DWORD; stdcall; external bassasiodll;
function BASS_ASIO_ChannelSetRate(input:BOOL; channel:DWORD; rate:double): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelGetRate(input:BOOL; channel:DWORD): double; stdcall; external bassasiodll;
function BASS_ASIO_ChannelSetVolume(input:BOOL; channel:Integer; volume:single): BOOL; stdcall; external bassasiodll;
function BASS_ASIO_ChannelGetVolume(input:BOOL; channel:Integer): single; stdcall; external bassasiodll;
function BASS_ASIO_ChannelGetLevel(input:BOOL; channel:DWORD): single; stdcall; external bassasiodll;
implementation
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, XPMan, ShellAPI, IniFiles;
type
TMain = class(TForm)
NewBtn: TButton;
ShowBtn: TButton;
FileNameLbl: TLabel;
XPManifest: TXPManifest;
UndoBtn: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure NewBtnClick(Sender: TObject);
procedure UndoBtnClick(Sender: TObject);
procedure ShowBtnClick(Sender: TObject);
procedure FileNameLblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Main: TMain;
RandomFiles, ShowedFiles: TStringList;
MainPath, ExcludeExts, RandomFileName: string;
FilesHistory: boolean;
ID_ALL_FILES_SHOWED, ID_LAST_UPDATE, ID_ABOUT_TITLE: string;
implementation
{$R *.dfm}
function GetLocaleInformation(flag: integer): string;
var
pcLCA: array [0..20] of char;
begin
if GetLocaleInfo(LOCALE_SYSTEM_DEFAULT, flag, pcLCA, 19) <= 0 then
pcLCA[0]:=#0;
Result:=pcLCA;
end;
function CutStr(Str: string; CharCount: integer): string;
begin
if Length(Str) > CharCount then
Result:=Copy(Str, 1, CharCount - 3) + '...'
else
Result:=Str;
end;
procedure ScanDir(Path: string);
var
sr: TSearchRec;
begin
if FindFirst(Path + '*.*', faAnyFile, sr) = 0 then begin
repeat
Application.ProcessMessages;
if (sr.name <> '.') and (sr.name <> '..') then
if (sr.Attr and faDirectory) <> faDirectory then begin
if (Pos(AnsiLowerCase(ExtractFileExt(sr.Name)), ExcludeExts) = 0) and
(Pos(sr.Name, ShowedFiles.Text) = 0) then
RandomFiles.Add(Path + sr.Name)
end else
ScanDir(Path + sr.Name + '\');
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
procedure RandomFile;
begin
ScanDir(MainPath);
if RandomFiles.Count > 0 then begin
RandomFileName:=RandomFiles.Strings[Random(RandomFiles.Count)];
Main.UndoBtn.Enabled:=true;
if FilesHistory then
ShowedFiles.Add(RandomFileName);
end else RandomFileName:=ID_ALL_FILES_SHOWED;
Main.FileNameLbl.Caption:=CutStr(ExtractFileName(RandomFileName), 40);
end;
procedure TMain.FormCreate(Sender: TObject);
var
Ini: TIniFile;
begin
Ini:=TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Config.ini');
MainPath:=Ini.ReadString('Main', 'Path', 'C:\Program Files');
if MainPath[Length(MainPath)] <> '\' then MainPath:=MainPath + '\';
FilesHistory:=Ini.ReadBool('Main', 'FilesHistory', true);
ExcludeExts:=Ini.ReadString('Main', 'ExcludeExts', '.pas');
Ini.Free;
if GetLocaleInformation(LOCALE_SENGLANGUAGE) = 'Russian' then begin
ID_ALL_FILES_SHOWED:='Все файлы показаны';
ID_LAST_UPDATE:='Последнее обновление:';
ID_ABOUT_TITLE:='О программе...';
end else begin
Caption:='Random file';
NewBtn.Caption:='New';
ShowBtn.Caption:='Show';
UndoBtn.Caption:='Undo';
ID_ALL_FILES_SHOWED:='All files showed';
ID_LAST_UPDATE:='Last update:';
ID_ABOUT_TITLE:='About...';
end;
Application.Title:=Caption;
RandomFiles:=TStringList.Create;
ShowedFiles:=TStringList.Create;
if FileExists(ExtractFilePath(ParamStr(0)) + 'Showed.txt') then
ShowedFiles.LoadFromFile(ExtractFilePath(ParamStr(0)) + 'Showed.txt');
Randomize;
RandomFile;
end;
procedure TMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
RandomFiles.Free;
if FilesHistory then
ShowedFiles.SaveToFile(ExtractFilePath(ParamStr(0)) + 'Showed.txt');
ShowedFiles.Free;
end;
procedure TMain.NewBtnClick(Sender: TObject);
begin
RandomFile;
end;
procedure TMain.UndoBtnClick(Sender: TObject);
begin
if ShowedFiles.Count > 0 then
ShowedFiles.Delete(ShowedFiles.Count - 1);
Main.UndoBtn.Enabled:=false;
end;
procedure TMain.ShowBtnClick(Sender: TObject);
begin
if (RandomFileName <> '') and (RandomFileName <> ID_ALL_FILES_SHOWED) then
ShellExecute(0, 'open', 'explorer', PChar('/select, "' + RandomFileName + '"'), nil, SW_SHOW);
end;
procedure TMain.FileNameLblClick(Sender: TObject);
begin
Application.MessageBox(PChar(Caption + #13#10 +
ID_LAST_UPDATE + ' 18.07.2018' + #13#10 +
'https://r57zone.github.io' + #13#10 +
'r57zone@gmail.com'), PChar(ID_ABOUT_TITLE), MB_ICONINFORMATION);
end;
end.
|
unit config;
{$mode objfpc}{$H+}
// Copyright (c) 2007 Julian Moss, G4ILO (www.g4ilo.com) //
// Released under the GNU GPL v2.0 (www.gnu.org/licenses/old-licenses/gpl-2.0.txt) //
interface
uses
Classes, SysUtils, XMLCfg;
procedure SetConfigFileName( const filename: string );
function GetFromConfigFile(const SectionName, ValueName, Attribute, Default: string): string;
function GetFromConfigFile(const SectionName, ValueName, Attribute: string; Default: Integer): Integer;
function GetFromConfigFile(const SectionName, ValueName, Attribute: string; Default: Boolean): Boolean;
function GetValueFromConfigFile(const SectionName, ValueName, Default: string): string;
function GetValueFromConfigFile(const SectionName, ValueName: string; Default: Integer): Integer;
function GetValueFromConfigFile(const SectionName, ValueName: string; Default: Boolean): Boolean;
procedure SaveToConfigFile(const SectionName, ValueName, Attribute, Value: string);
procedure SaveToConfigFile(const SectionName, ValueName, Attribute: string; Value: Integer);
procedure SaveToConfigFile(const SectionName, ValueName, Attribute: string; Value: Boolean);
procedure SaveValueToConfigFile(const SectionName, ValueName, Value: string);
procedure SaveValueToConfigFile(const SectionName, ValueName: string; Value: Integer);
procedure SaveValueToConfigFile(const SectionName, ValueName: string; Value: Boolean);
procedure DeleteValueFromConfigFile(const SectionName, ValueName: string);
const
sConfigRoot = 'Settings';
sValue = 'Value';
implementation
var
XMLConfig: TXMLConfig;
procedure SetConfigFileName( const filename: string );
begin
XMLConfig := TXMLConfig.Create(nil);
XMLConfig.Filename := filename;
end;
function GetFromConfigFile(const SectionName, ValueName, Attribute, Default: string): string;
begin
Result := XMLConfig.GetValue(SectionName+'/'+ValueName+'/'+Attribute, Default);
end;
function GetFromConfigFile(const SectionName, ValueName, Attribute: string; Default: Integer): Integer;
begin
Result := XMLConfig.GetValue(SectionName+'/'+ValueName+'/'+Attribute, Default);
end;
function GetFromConfigFile(const SectionName, ValueName, Attribute: string; Default: Boolean): Boolean;
begin
Result := XMLConfig.GetValue(SectionName+'/'+ValueName+'/'+Attribute, Default);
end;
function GetValueFromConfigFile(const SectionName, ValueName, Default: string): string;
begin
Result := GetFromConfigFile(SectionName, ValueName, sValue, Default);
end;
function GetValueFromConfigFile(const SectionName, ValueName: string; Default: Integer): Integer;
begin
Result := GetFromConfigFile(SectionName, ValueName, sValue, Default);
end;
function GetValueFromConfigFile(const SectionName, ValueName: string; Default: Boolean): Boolean;
begin
Result := GetFromConfigFile(SectionName, ValueName, sValue, Default);
end;
procedure SaveToConfigFile(const SectionName, ValueName, Attribute, Value: string);
begin
if Value = '' then
XMLConfig.DeleteValue(SectionName+'/'+ValueName+'/'+Attribute)
else
XMLConfig.SetValue(SectionName+'/'+ValueName+'/'+Attribute, Value);
end;
procedure SaveToConfigFile(const SectionName, ValueName, Attribute: string; Value: Integer);
begin
XMLConfig.SetValue(SectionName+'/'+ValueName+'/'+Attribute, Value);
end;
procedure SaveToConfigFile(const SectionName, ValueName, Attribute: string; Value: Boolean);
begin
XMLConfig.SetValue(SectionName+'/'+ValueName+'/'+Attribute, Value);
end;
procedure SaveValueToConfigFile(const SectionName, ValueName, Value: string);
begin
SaveToConfigFile(SectionName, ValueName, sValue, Value);
end;
procedure SaveValueToConfigFile(const SectionName, ValueName: string; Value: Integer);
begin
SaveToConfigFile(SectionName, ValueName, sValue, Value);
end;
procedure SaveValueToConfigFile(const SectionName, ValueName: string; Value: Boolean);
begin
SaveToConfigFile(SectionName, ValueName, sValue, Value);
end;
procedure DeleteValueFromConfigFile(const SectionName, ValueName: string);
begin
XMLConfig.DeletePath(SectionName+'/'+ValueName);
end;
initialization
XMLConfig := nil;
finalization
if XMLConfig <> nil then
XMLConfig.Destroy;
end.
|
unit ui_utils;
interface
uses
Windows, sysutils, classes, graphics, extCtrls, Forms, menus, ActnList;
type
TFadeDirection = (fdIn, fdOut);
function LoadAsBitmap(const FileName:String): TBitmap;
procedure FadeBitmap(const BMP:TImage; Pause:integer; Direction: TFadeDirection) ;
implementation
function LoadAsBitmap;
var
p: TPicture;
begin
Result := TBitmap.Create;
if FileExists(FileName) then
begin
p := TPicture.Create;
try
p.LoadFromFile(FileName);
Result.Assign(p.Graphic);
Result.PixelFormat := pf24bit;
finally
p.Free;
end;
end;
end;
procedure FadeBitmap;
var
BytesPorScan : integer;
w,h : integer;
p : pByteArray;
counter : integer;
begin
{This only works with 24 or 32 bits bitmaps}
If Not (BMP.Picture.Bitmap.PixelFormat
in [pf24Bit, pf32Bit])
then raise exception.create
('Error, bitmap format not supported.') ;
try
BytesPorScan:=
Abs(Integer(BMP.Picture.Bitmap.ScanLine[1])-
Integer(BMP.Picture.Bitmap.ScanLine[0])) ;
except
raise exception.create('Error') ;
end;
{Decrease the RGB for each single pixel}
if Direction = fdOut then
begin
for counter:=1 to 256 do
begin
for h:=0 to BMP.Picture.Bitmap.Height-1 do
begin
P:=BMP.Picture.Bitmap.ScanLine[h];
for w:=0 to BytesPorScan-1 do
if P^[w] >0 then P^[w]:=P^[w]-1;
Application.processMessages;
end;
Sleep(Pause) ;
BMP.Refresh;
end;
end
else
begin
end;
end; {procedure FadeOut}
end.
|
unit mDefineMediaFiles;
interface
uses
API_Files,
API_MVC,
eAudioStream,
eExtLink,
eMediaFile,
eVideoFile,
eVideoStream,
eVideoMovie;
type
TModelDefineMediaFiles = class(TModelAbstract)
private
function CreateAudioMediaFile(aFileInfo: TFileInfo; aMediaInfoGeneral: TMediaInfoGeneral;
aAudioStreamArr: TArray<TAudioStream>): TMediaFile;
function GetMediaInfo(const aPath: string; out aVideoStreamArr: TArray<TVideoStream>;
out aAudioStreamArr: TArray<TAudioStream>): TMediaInfoGeneral;
function TryGetTitle(const aFileName: string): string;
function TryGetTitleOrig(const aFileName: string): string;
public
inCookiesPath: string;
inFileArr: TArray<string>;
outMediaFile: TMediaFile;
outMediaFileList: TMediaFileList;
outLibList: TMediaLibList;
//outSearchResultArr: TExtMovieSearchArr;
procedure Start; override;
end;
implementation
uses
API_Strings,
eAudioAlbum,
eAudioArtist,
eAudioTrack,
MediaInfoDLL,
mKinopoiskParser,
mTranslitOnlineRu,
System.SysUtils;
function TModelDefineMediaFiles.CreateAudioMediaFile(aFileInfo: TFileInfo; aMediaInfoGeneral: TMediaInfoGeneral;
aAudioStreamArr: TArray<TAudioStream>): TMediaFile;
var
Artist: TArtist;
Album: TAlbum;
Track: TTrack;
begin
Artist := TArtist.Create;
Album := TAlbum.Create;
Artist.Albums.Add(Album);
Track := TTrack.Create;
Album.AddTrack(Track);
//Result := TMediaFile.Create(Artist, Album, Track);
end;
function TModelDefineMediaFiles.GetMediaInfo(const aPath: string; out aVideoStreamArr: TArray<TVideoStream>;
out aAudioStreamArr: TArray<TAudioStream>): TMediaInfoGeneral;
var
AudioStream: TAudioStream;
Handle: Cardinal;
i: Integer;
StreamCount: Integer;
VideoStream: TVideoStream;
begin
Handle := MediaInfo_New();
try
aVideoStreamArr := [];
aAudioStreamArr := [];
MediaInfo_Option(Handle, 'ParseSpeed', '0');
MediaInfo_Open(Handle, PWideChar(aPath));
//General
Result.Path := aPath;
Result.Format := MediaInfo_Get(Handle, Stream_General, 0, 'Format/String', Info_Text, Info_Name);
Result.Name := MediaInfo_Get(Handle, Stream_General, 0, 'Movie', Info_Text, Info_Name);
Result.Duration := StrToIntDef(MediaInfo_Get(Handle, Stream_General, 0, 'Duration', Info_Text, Info_Name), 0);
Result.Size := StrToInt64Def(MediaInfo_Get(Handle, Stream_General, 0, 'FileSize', Info_Text, Info_Name), 0);
//Video
StreamCount := StrToIntDef(MediaInfo_Get(Handle, Stream_General, 0, 'VideoCount', Info_Text, Info_Name), 0);
for i := 0 to StreamCount - 1 do
begin
VideoStream := TVideoStream.Create;
VideoStream.Codec := MediaInfo_Get(Handle, Stream_Video, i, 'Format', Info_Text, Info_Name);
VideoStream.CodecID := MediaInfo_Get(Handle, Stream_Video, i, 'CodecID', Info_Text, Info_Name);
VideoStream.BitRate := StrToIntDef(MediaInfo_Get(Handle, Stream_Video, i, 'BitRate', Info_Text, Info_Name), 0);
VideoStream.Width := StrToIntDef(MediaInfo_Get(Handle, Stream_Video, i, 'Width', Info_Text, Info_Name), 0);
VideoStream.Height := StrToIntDef(MediaInfo_Get(Handle, Stream_Video, i, 'Height', Info_Text, Info_Name), 0);
VideoStream.BitDepth := StrToIntDef(MediaInfo_Get(Handle, Stream_Video, i, 'BitDepth', Info_Text, Info_Name), 0);
VideoStream.Size := StrToInt64Def(MediaInfo_Get(Handle, Stream_Video, i, 'StreamSize', Info_Text, Info_Name), 0);
aVideoStreamArr := aVideoStreamArr + [VideoStream];
end;
//Audio
StreamCount := StrToIntDef(MediaInfo_Get(Handle, Stream_General, 0, 'AudioCount', Info_Text, Info_Name), 0);
for i := 0 to StreamCount - 1 do
begin
AudioStream := TAudioStream.Create;
AudioStream.Codec := MediaInfo_Get(Handle, Stream_Audio, i, 'Format', Info_Text, Info_Name);
AudioStream.BitRate := StrToIntDef(MediaInfo_Get(Handle, Stream_Audio, i, 'BitRate', Info_Text, Info_Name), 0);
AudioStream.Channels := StrToIntDef(MediaInfo_Get(Handle, Stream_Audio, i, 'Channel(s)', Info_Text, Info_Name), 0);
AudioStream.BitDepth := StrToIntDef(MediaInfo_Get(Handle, Stream_Audio, i, 'BitDepth', Info_Text, Info_Name), 0);
AudioStream.SamplingRate := StrToIntDef(MediaInfo_Get(Handle, Stream_Audio, i, 'SamplingRate', Info_Text, Info_Name), 0);
AudioStream.Size := StrToInt64Def(MediaInfo_Get(Handle, Stream_Audio, i, 'StreamSize', Info_Text, Info_Name), 0);
AudioStream.Language := MediaInfo_Get(Handle, Stream_Audio, i, 'Language/String', Info_Text, Info_Name);
aAudioStreamArr := aAudioStreamArr + [AudioStream];
end;
finally
MediaInfo_Close(Handle);
end;
end;
function TModelDefineMediaFiles.TryGetTitleOrig(const aFileName: string): string;
begin
Result := aFileName.Replace('.', ' ');
Result := TStrTool.GetRegExReplaced(Result, '\d{4}.*', '');
end;
function TModelDefineMediaFiles.TryGetTitle(const aFileName: string): string;
var
Converted: string;
begin
Result := aFileName.Replace('.', ' ');
Result := TStrTool.GetRegExReplaced(Result, '\d{4}.*', '');
if not TStrTool.CheckCyrChar(Result) then
begin
Converted := TModelTranslitOnlineRu.ConvertTrToRu(Result);
Result := Converted.Trim;
end;
end;
procedure TModelDefineMediaFiles.Start;
var
Artist: TArtist;
AudioStreamArr: TArray<TAudioStream>;
FileInfo: TFileInfo;
FileInfoArr: TArray<TFileInfo>;
FileName: string;
MediaDataVariants: TMediaDataVariants;
MediaInfoGeneral: TMediaInfoGeneral;
Movie: TMovie;
VideoStreamArr: TArray<TVideoStream>;
begin
if not MediaInfoDLL_Load('MediaInfo.dll') then
raise Exception.Create('Error load MediaInfo.dll!');
FileInfoArr := [];
outMediaFileList := TMediaFileList.Create(True);
outLibList := TMediaLibList.Create;
for FileName in inFileArr do
FileInfoArr := FileInfoArr + TFilesEngine.GetFileInfoArr(FileName);
for FileInfo in FileInfoArr do
begin
MediaInfoGeneral := GetMediaInfo(FileInfo.FullPath, VideoStreamArr, AudioStreamArr);
outMediaFile := TMediaFile.Create(MediaInfoGeneral, VideoStreamArr, AudioStreamArr);
if outMediaFile.VideoFile <> nil then //video
begin
Movie := TMovie.Create;
Movie.Title := TryGetTitle(FileInfo.Name);
Movie.TitleOrig := TryGetTitleOrig(FileInfo.Name);
Movie.VideoFiles.Add(outMediaFile.VideoFile);
outMediaFile.Movie := Movie;
outLibList.VideoList.Add(Movie);
end
else
if outMediaFile.AudioFile <> nil then //audio
begin
Artist := TArtist.Create;
Artist.Name := outMediaFile.MediaDataVariants.ArtistNameVariantArr[0];
outMediaFile.Artist := Artist;
outLibList.AudioList.Add(Artist);
end;
SendMessage('OnMediaFileAdded', True);
outMediaFileList.Add(outMediaFile);
end;
end;
end.
|
unit DisassemblerArm;
{$mode objfpc}{$H+}
interface
uses
windows, Classes, SysUtils{$ifndef ARMDEV}, newkernelhandler, cefuncproc{$endif}, LastDisassembleData;
const ArmConditions: array [0..15] of string=('EQ','NE','CS', 'CC', 'MI', 'PL', 'VS', 'VC', 'HI', 'LS', 'GE', 'LT', 'GT', 'LE', '','NV');
const DataProcessingOpcodes: array [0..15] of string=('AND','EOR','SUB', 'RSB', 'ADD', 'ADC', 'SBC', 'RSC', 'TST', 'TEQ', 'CMP', 'CMN', 'ORR', 'MOV', 'BIC','MVN');
const ArmRegisters : array [0..15] of string=('R0','R1','R2','R3','R4','R5','R6','R7','R8','R9','R10','FP','IP','SP','LR','PC');
const ArmRegistersNoName : array [0..15] of string=('R0','R1','R2','R3','R4','R5','R6','R7','R8','R9','R10','R11','R12','R13','R14','R15');
function SignExtend(value: int32; mostSignificantBit: integer): int32;
type
TArmDisassembler=object
private
opcode: uint32;
function Condition: string;
procedure Branch;
procedure BX;
procedure DataProcessing;
procedure MRS;
procedure MSR;
procedure MSR_flg;
procedure Mul;
procedure SingleDataTransfer;
procedure LDM_STM;
procedure SWP;
procedure SWI;
procedure CDP;
public
LastDisassembleData: TLastDisassembleData;
function disassemble(var address: ptrUint): string;
end;
implementation
uses processhandlerunit;
function SignExtend(value: int32; mostSignificantBit: integer): int32;
{
Signextends a given offset. mostSignificant bit defines what bit determines if it should be sign extended or not
}
begin
if (value shr mostSignificantBit)=1 then //needs to be sign extended
begin
//set bits 31 to mostSignificantBit to 1
result:=value or ($fffffff shl (mostSignificantBit+1));
end
else
result:=value;
end;
function TArmDisassembler.Condition: string;
begin
result:=ArmConditions[opcode shr 28];
end;
procedure TArmDisassembler.Branch;
var offset: int32;
_condition: string;
begin
_condition:=condition;
if (opcode shr 24) and 1=1 then //Link bit set
begin
LastDisassembleData.opcode:='BL'+Condition;
LastDisassembleData.iscall:=true;
end
else
begin
LastDisassembleData.opcode:='B'+Condition;
LastDisassembleData.isjump:=true;
LastDisassembleData.isconditionaljump:=_condition<>'';
end;
offset:=signextend(opcode and $FFFFFF, 23) shl 2;
LastDisassembleData.parameters:=inttohex(dword(LastDisassembleData.address+8+offset),8);
end;
procedure TArmDisassembler.BX;
var
Rn: integer;
_Rn: string;
_condition: string;
begin
_condition:=condition;
LastDisassembleData.opcode:='BX'+Condition;
LastDisassembleData.isjump:=true;
LastDisassembleData.isconditionaljump:=_condition<>'';
Rn:=opcode and $F;
_Rn:=ArmRegisters[Rn];
LastDisassembleData.parameters:=_Rn;
end;
procedure TArmDisassembler.DataProcessing;
var
ImmediateOperand: integer;
OpcodeIndex: integer;
SetCondition: integer;
Operand1: integer;
Destination: integer;
Operand2: integer;
shift: integer;
rm: integer;
Rotate: integer;
Imm: integer;
shiftformat: integer;
shiftType: integer;
shiftammount: integer;
shiftRegister: integer;
shiftname: string;
_shift: string;
_opcode: string;
_cond: string;
_S: string;
_Rd: string;
_Rn: string;
_rm: string;
_rs: string;
_op2: string;
begin
_opcode:='';
_cond:='';
_S:='';
_Rd:='';
_Rn:='';
_op2:='';
ImmediateOperand:=(opcode shr 25) and 1;
OpcodeIndex:=(opcode shr 21) and $f;
SetCondition:=(opcode shr 20) and 1;
Operand1:=(opcode shr 16) and $f;
Destination:=(opcode shr 12) and $f;
Operand2:=opcode and $fff;
_opcode:=DataProcessingOpcodes[OpcodeIndex];
_cond:=Condition;
if SetCondition=1 then
_s:='S';
_Rn:=ArmRegisters[Operand1];
_Rd:=ArmRegisters[Destination];
//build _op2
if ImmediateOperand=0 then //operand2 is a register
begin
shift:=Operand2 shr 4;
rm:=operand2 and $f;
_rm:=ArmRegisters[rm];
shiftformat:=shift and 1;
shiftType:=(shift shr 1) and 3;
case shifttype of
0: shiftname:='LSL';
1: shiftname:='LSR';
2: shiftname:='ASR';
3: shiftname:='ROR';
end;
_shift:=shiftname;
if shiftformat=0 then
begin
shiftAmmount:=(shift shr (7-4)) and $1f; //7-4 because the doc describes the shift field starting from bit 4
if shiftAmmount>0 then
_shift:=_shift+' '+inttohex(shiftammount,1)
else
_shift:='';
end
else
begin
shiftregister:=(shift shr (8-4)) and $f;
_rs:=ArmRegisters[shiftregister];
_shift:=_shift+' '+_rs;
end;
if _shift<>'' then
_op2:=_rm+','+_shift
else
_op2:=_rm;
end
else
begin
//operand2 is an immediate value
rotate:=Operand2 shr 8;
imm:=Operand2 and $ff;
_op2:=inttohex(RorDWord(imm, rotate*2),1);
end;
if _op2<>'' then
_op2:=','+_op2;
case OpcodeIndex of
13,15:
begin
LastDisassembleData.opcode:=_opcode+_cond+_S;
LastDisassembleData.parameters:=_Rd+_op2;
end;
8,9,10,11:
begin
LastDisassembleData.opcode:=_opcode+_cond;
LastDisassembleData.parameters:=_Rn+_op2;
end
else
begin
LastDisassembleData.opcode:=_opcode+_cond+_S;
LastDisassembleData.parameters:=_Rd+','+_Rn+_op2;
end;
end;
end;
procedure TArmDisassembler.MRS;
var
_cond: string;
_rd: string;
_psr: string;
Ps: integer;
Rd: integer;
begin
_cond:=Condition;
Ps:=(opcode shr 22) and 1;
if (Ps=0) then
_psr:='CPSR'
else
_psr:='SPSR';
Rd:=(opcode shr 12) and $F;
_rd:=ArmRegisters[rd];
LastDisassembleData.opcode:='MRS'+_cond;
LastDisassembleData.parameters:=_Rd+','+_psr;
end;
procedure TArmDisassembler.MSR;
var
_cond: string;
_psr: string;
_Rm: string;
Pd: integer;
Rm: integer;
I: integer;
imm, rotate: integer;
begin
_cond:=Condition;
Pd:=(opcode shr 22) and 1;
if (Pd=0) then
_psr:='CPSR'
else
_psr:='SPSR';
Rm:=opcode and $F;
_rm:=ArmRegisters[rm];
LastDisassembleData.opcode:='MSR'+_cond;
LastDisassembleData.parameters:=_psr+'_all,'+_Rm;
end;
procedure TArmDisassembler.MSR_flg;
var
_cond: string;
_psr: string;
_Rm: string;
Pd: integer;
Rm: integer;
I: integer;
imm, rotate: integer;
begin
_cond:=Condition;
Pd:=(opcode shr 22) and 1;
if (Pd=0) then
_psr:='CPSR'
else
_psr:='SPSR';
i:=(opcode shr 25) and 1;
if i=0 then
begin
Rm:=opcode and $F;
_rm:=ArmRegisters[rm];
LastDisassembleData.opcode:='MSR'+_cond;
LastDisassembleData.parameters:=_psr+'_flg,'+_Rm;
end
else
begin
rotate:=(opcode and $fff) shr 8;
imm:=(opcode and $fff) and $ff;
LastDisassembleData.opcode:='MSR'+_cond;
LastDisassembleData.parameters:=_psr+'_flg,'+inttohex(RorDWord(imm, rotate*2),1);
end;
end;
procedure TArmDisassembler.Mul;
var
_cond: string;
_S: string;
_rd: string;
_rm: string;
_rs: string;
_rn: string;
begin
if (opcode shl 20) and 1=1 then
_S:='S'
else
_S:='';
_cond:=Condition;
_rd:=ArmRegisters[opcode shl 16 and $f];
_rn:=ArmRegisters[opcode shl 12 and $f];
_rs:=ArmRegisters[opcode shl 8 and $f];
_rm:=ArmRegisters[opcode and $f];
if (opcode shl 21) and 1=1 then
begin
LastDisassembleData.opcode:='MLA'+_cond+_S;
LastDisassembleData.parameters:=_Rd+','+_Rm+','+_Rs+','+_Rn
end
else
begin
LastDisassembleData.opcode:='MUL'+_cond+_S;
LastDisassembleData.parameters:=_Rd+','+_Rm+','+_Rs;
end;
end;
procedure TArmDisassembler.SingleDataTransfer;
var
_cond: string;
_opcode: string;
_B: string;
_T: string;
_Rd: string;
_Rn: string;
_Rm: string;
_shift: string;
_U: string;
I: integer;
P: integer;
U: integer;
B: integer;
W: integer;
L: integer;
Rn: integer;
Rd: integer;
Rm: integer;
Offset: integer;
shift: integer;
shifttype: integer;
_shiftname: string;
_shiftAmount: string;
shiftamount: integer;
_address: string;
begin
I:=(opcode shr 25) and 1;
P:=(opcode shr 24) and 1;
U:=(opcode shr 23) and 1;
B:=(opcode shr 22) and 1;
W:=(opcode shr 21) and 1;
L:=(opcode shr 20) and 1;
Rn:=(opcode shr 16) and $f;
Rd:=(opcode shr 12) and $f;
offset:=opcode and $fff;
if L=1 then
_opcode:='LDR'
else
_opcode:='STR';
if u=0 then
_U:='-'
else
_U:='';
_cond:=Condition;
if b=1 then
_B:='B'
else
_B:='';
if (W=1) and (p=0) then //w is set and p=0 (post indexed)
_T:='T'
else
_T:='';
_Rd:=ArmRegisters[Rd];
_Rn:=ArmRegisters[Rn];
if i=0 then
begin
//offset is an immediate value
if Rn=15 then //pc
begin
if u=0 then //decrease
_address:='['+inttohex(dword(LastDisassembleData.address-offset+8),8)+']'
else
_address:='['+inttohex(dword(LastDisassembleData.address+offset+8),8)+']'
end
else
begin
if offset=0 then
_address:='['+_Rn+']'
else
_address:='['+_Rn+','+_U+inttohex(dword(offset),8)+']';
end;
end
else
begin
//offset is a register
Rm:=offset and $f;
Shift:=offset shr 4;
_Rm:=ArmRegisters[Rm];
shiftType:=(shift shr 1) and 3;
case shifttype of
0: _shiftname:='LSL';
1: _shiftname:='LSR';
2: _shiftname:='ASR';
3: _shiftname:='ROR';
end;
shiftAmount:=(shift shr (7-4)) and $1f;
if shiftAmount>0 then
begin
_shiftAmount:=inttohex(shiftamount,1);
_shift:=', '+_U+_Rm+' '+_shiftname+' '+_shiftamount;
end
else
begin
_shiftAmount:='';
_shift:=', '+_Rm;
end;
if p=0 then //post index
_address:='['+_Rn+']'+_shift
else //preindexed
_address:='['+_Rn+_shift+']';
end;
if (w=1) and (p=1) then
_address:=_address+'!';
LastDisassembleData.opcode:=_opcode+_cond+_B+_T;
LastDisassembleData.parameters:=_Rd+','+_Address;
end;
procedure TArmDisassembler.LDM_STM;
var
P: integer;
U: integer;
S: integer;
W: integer;
L: integer;
Rn: integer;
RegisterList: integer;
_opcode: string;
_cond: string;
_addressingmode: string;
_rn: string;
_ex: string;
_exp: string;
_rlist: string;
i: integer;
rcount: integer;
begin
_cond:=Condition;
p:=(opcode shr 24) and 1;
u:=(opcode shr 23) and 1;
s:=(opcode shr 22) and 1;
w:=(opcode shr 21) and 1;
l:=(opcode shr 20) and 1;
Rn:=(opcode shr 16) and $f;
RegisterList:=opcode and $ffff;
_rlist:='{';
rcount:=0;
for i:=0 to 15 do
begin
if (RegisterList shr i) and 1=1 then
begin
if rcount=0 then
_rlist:=_rlist+ArmRegisters[i]
else
_rlist:=_rlist+', '+ArmRegisters[i];
inc(rcount);
end;
end;
_rlist:=_rlist+'}';
if L=0 then
_opcode:='STM'
else
_opcode:='LDM';
_rn:=ArmRegisters[Rn];
if w=1 then
_ex:='!'
else
_ex:='';
if s=1 then
_exp:='^'
else
_exp:='';
_addressingmode:='';
if (L=1) and (P=1) and (U=1) then
begin
if rn=13 then
_addressingmode:='ED'
else
_addressingmode:='IB';
end;
if (L=1) and (P=0) and (U=1) then
begin
if rn=13 then
_addressingmode:='FD'
else
_addressingmode:='IA';
end;
if (L=1) and (P=1) and (U=0) then
begin
if rn=13 then
_addressingmode:='EA'
else
_addressingmode:='DB';
end;
if (L=1) and (P=0) and (U=0) then
begin
if rn=13 then
_addressingmode:='FA'
else
_addressingmode:='DA';
end;
if (L=0) and (P=1) and (U=1) then
begin
if rn=13 then
_addressingmode:='FA'
else
_addressingmode:='IB';
end;
if (L=0) and (P=0) and (U=1) then
begin
if rn=13 then
_addressingmode:='EA'
else
_addressingmode:='IA';
end;
if (L=0) and (P=1) and (U=0) then
begin
if rn=13 then
_addressingmode:='FD'
else
_addressingmode:='DB';
end;
if (L=0) and (P=0) and (U=0) then
begin
if rn=13 then
_addressingmode:='ED'
else
_addressingmode:='DA';
end;
LastDisassembleData.opcode:=_opcode+_cond+_addressingmode;
LastDisassembleData.parameters:=_rn+_ex+','+_rlist+_exp;
end;
procedure TArmDisassembler.SWP;
var
_cond: string;
_B: string;
_rd: string;
_rm: string;
_rn: string;
begin
_cond:=Condition;
if (opcode shr 22) and 1=1 then
_B:='1'
else
_B:='';
_rd:=ArmRegisters[(opcode shr 12) and $f];
_rm:=ArmRegisters[opcode and $f];
_rn:=ArmRegisters[(opcode shr 16) and $f];
LastDisassembleData.opcode:='SWP'+_cond+_B;
LastDisassembleData.parameters:=_rd+','+_rm+',['+_rn+']';
end;
procedure TArmDisassembler.SWI;
begin
LastDisassembleData.opcode:='SWI'+Condition;
LastDisassembleData.parameters:=inttohex(opcode and $FFFFFF,1);
end;
procedure TArmDisassembler.CDP;
var
CP_Opc: integer;
CRn: integer;
CRd: integer;
CPn: integer;
CP: integer;
CRm: integer;
_pn: string;
_cd,_cn,_cm: string;
_expression1,_expression2: string;
begin
CP_Opc:=(opcode shr 20) and $f; //
CRd:=(opcode shr 12) and $f; //
CRn:=(opcode shr 16) and $f; //
CRm:=opcode and $f; //
CPn:=(opcode shr 8) and $f;
CP:=(opcode shr 5) and $7; //
_expression1:=inttohex(CP_OPC,1);
if cp<>0 then
_expression2:=inttohex(CP,1)
else
_expression2:='';
_pn:=inttohex(cp,1);
_cd:='c'+inttostr(CRd);
_cn:='c'+inttostr(CRn);
_cm:='c'+inttostr(CRm);
//CDP{cond} p#,<expression1>,cd,cn,cm{,<expression2>}
LastDisassembleData.opcode:='CDP'+Condition;
LastDisassembleData.parameters:=_pn+','+_expression1+','+_cd+','+_cn+','+_cm+_expression2;
end;
function TArmDisassembler.Disassemble(var address: ptrUint): string;
var
x: ptruint;
begin
result:='';
setlength(LastDisassembleData.bytes,0);
{$ifdef ARMDEV}
opcode:=pdword(address)^;
setlength(LastDisassembleData.Bytes,4);
pdword(@LastDisassembleData.Bytes[0])^:=opcode;
address:=0;
x:=sizeof(opcode);
{$else}
x:=0;
if readprocessmemory(processhandle, pointer(address), @opcode, sizeof(opcode), x) then
begin
setlength(LastDisassembleData.Bytes,4);
pdword(@LastDisassembleData.Bytes[0])^:=opcode;
end;
{$endif}
LastDisassembleData.address:=address;
LastDisassembleData.SeperatorCount:=0;
LastDisassembleData.prefix:='';
LastDisassembleData.PrefixSize:=0;
LastDisassembleData.opcode:='';
LastDisassembleData.parameters:='';
lastdisassembledata.isjump:=false;
lastdisassembledata.iscall:=false;
lastdisassembledata.isret:=false;
lastdisassembledata.isconditionaljump:=false;
lastdisassembledata.modrmValueType:=dvtNone;
lastdisassembledata.parameterValueType:=dvtNone;
if (x=sizeof(opcode)) then
begin
if ((opcode shr 4) and $ffffff)=$12FFF1 then
BX
else
if (((opcode shr 2) and $3f)=0) and (((opcode shr 4) and $f)=$9) then
MUL
else
if (((opcode shr 23) and $1f)=2) and (((opcode shr 16) and $3f)=$f) and ((opcode and $FFF)=0) then
MRS
else
if (((opcode shr 23) and $1f)=2) and (((opcode shr 4) and $3FFFF)=$29F00) then
MSR
else
if (((opcode shr 23) and $3)=2) and (((opcode shr 26) and $3)=2) and (((opcode shr 12) and $3ff)=$28f) then
MSR_flg
else
if ((opcode shr 25) and 7)=5 then
Branch
else
if (((opcode shr 26) and 3)=0) and (((opcode shr 4) and $f)<>9) then
DataProcessing
else
if (opcode shr 26) and 3=1 then
SingleDataTransfer
else
if (opcode shr 25) and 7=4 then
LDM_STM
else
if ((opcode shr 23) and $1f=2) and ((opcode shr 20) and $3=0) and ((opcode shr 4) and $ff=9) then
SWP
else
if (opcode shr 24) and $F=$F then
SWI
else
if (((opcode shr 24) and $F)=$E) and (((opcode shr 4) and 1)=1) then
CDP;
end
else
LastDisassembleData.opcode:='??';
result:=inttohex(LastDisassembleData.address,8);
result:=result+' - ';
if x=sizeof(opcode) then result:=result+inttohex(LastDisassembleData.Bytes[0],2)+' '+inttohex(LastDisassembleData.Bytes[1],2)+' '+inttohex(LastDisassembleData.Bytes[2],2)+' '+inttohex(LastDisassembleData.Bytes[3],2);
result:=result+' - ';
result:=result+LastDisassembleData.opcode;
result:=result+' ';
result:=result+LastDisassembleData.parameters;
inc(address,4);
end;
end.
|
PROGRAM ReadNumberPrgm(INPUT, OUTPUT);
VAR
N, Min, Max, Mean, Number, Summ: INTEGER;
Check, Ch: CHAR;
PROCEDURE ReadNumber(VAR F: TEXT; VAR N: INTEGER);
{Преобразует строку цифр из файла до первого нецифрового
символа, в соответствующее целое число N}
VAR
D: INTEGER;
PROCEDURE ReadDigit(VAR F: TEXT; VAR D: INTEGER);
{Считывает текущий символ из файла, если он - цифра, возвращает его
преобразуя в значение типа INTEGER. Если считанный символ не цифра
возвращает -1
}
VAR
Ch: CHAR;
BEGIN{ReadDigit}
IF NOT EOLN(F)
THEN
BEGIN
READ(F, Ch);
IF Ch = '0' THEN D := 0 ELSE
IF Ch = '1' THEN D := 1 ELSE
IF Ch = '2' THEN D := 2 ELSE
IF Ch = '3' THEN D := 3 ELSE
IF Ch = '4' THEN D := 4 ELSE
IF Ch = '5' THEN D := 5 ELSE
IF Ch = '6' THEN D := 6 ELSE
IF Ch = '7' THEN D := 7 ELSE
IF Ch = '8' THEN D := 8 ELSE
IF Ch = '9' THEN D := 9 ELSE
D := -1
END
ELSE
D := -1
END;{ReadDigit}
BEGIN{ReadNumber}
N := 0;
ReadDigit(F, D);
WHILE (D <> -1) AND (N <> -1)
DO
BEGIN
IF N <= MAXINT DIV 10
THEN
IF MAXINT - N * 10 >= D
THEN
BEGIN
N := N * 10 + D
END
ELSE
N := -1
ELSE
N := -1;
ReadDigit(F, D);
END
END;{ReadNumber}
BEGIN{ReadDigitPrgm}
ReadNumber(INPUT, N);
IF N <> -1
THEN
BEGIN
Summ := N;
Number := 1;
Max := N;
Min := N
END;
WHILE (N <> -1) AND (N <> 0) {Ситуация с нулями. Не могу решить из за того, что функция возвращает '0' при любом символе - не цифре, по усолвию задания}
DO
BEGIN
IF Min > N
THEN
Min := N
ELSE
IF Max < N
THEN
Max := N;
IF (MAXINT - Summ) >= N
THEN
Summ := Summ + N
ELSE
N := -1;
IF (MAXINT - Number) <> 0
THEN
Number := Number + 1
ELSE
N := -1;
ReadNumber(INPUT, N);
END;
IF N <> -1
THEN
BEGIN
Mean := Summ DIV Number;
WRITELN(OUTPUT, 'Максимальное: ', Max);
WRITELN(OUTPUT, 'Минимальное: ', Min);
WRITELN(OUTPUT, 'Среднее: ', Mean);
END
ELSE
IF N = -1
THEN
WRITELN(OUTPUT, 'Произошло переполнение')
END.{ReadDigitPrgm}
|
unit LaserUnit;
// ========================================================================
// MesoScan: Laser control module
// (c) J.Dempster, Strathclyde Institute for Pharmacy & Biomedical Sciences
// ========================================================================
// 8.07.14
interface
uses
System.SysUtils, System.Classes, math ;
type
TLaser = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
FComPort : Integer ;
FShutterControlLine : Integer ;
FShutterOpen : Boolean ;
FShutterChangeTime : Double ;
FIntensityControlLine : Integer ;
FVMaxIntensity : Double ;
FIntensity : Double ;
procedure SetIntensity( Value : double) ;
procedure SetCOMPort( Value : Integer ) ;
public
{ Public declarations }
procedure GetShutterControlLines( List : TStrings ) ;
procedure GetIntensityControlLines( List : TStrings ) ;
procedure GetCOMPorts( List : TStrings ) ;
procedure SetShutterOpen( Value : boolean ) ;
Property ComPort : Integer read FCOMPort write SetComPort ;
Property ShutterControlLine : Integer read FShutterControlLine write FShutterControlLine ;
Property ShutterChangeTime : Double read FShutterChangeTime write FShutterChangeTime ;
Property IntensityControlLine : Integer read FIntensityControlLine write FIntensityControlLine ;
Property ShutterOpen : boolean read FShutterOpen write SetShutterOpen ;
Property VMaxIntensity : Double read FVMaxIntensity write FVMaxIntensity ;
Property Intensity : Double read FIntensity write SetIntensity ;
end;
var
Laser: TLaser;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses LabIOUnit;
{$R *.dfm}
procedure TLaser.DataModuleCreate(Sender: TObject);
//
// Initialisation when module created
// ----------------------------------
begin
FCOMPort := 0 ;
FShutterControlLine := 0 ;
FIntensityControlLine := 0 ;
FShutterOpen := False ;
FShutterChangeTime := 0.5 ;
VMaxIntensity := 5.0 ;
FIntensity := 0.0 ;
end;
procedure TLaser.GetShutterControlLines( List : TStrings ) ;
// -----------------------------------
// Get list of available control ports
// -----------------------------------
var
i : Integer ;
iDev: Integer;
begin
List.Clear ;
List.Add('None') ;
for iDev := 1 to LabIO.NumDevices do begin
for i := 0 to 7 do begin
List.Add(Format('Dev%d:P0.%d',[iDev,i])) ;
end;
end;
end ;
procedure TLaser.GetIntensityControlLines( List : TStrings ) ;
// -----------------------------------
// Get list of available control ports
// -----------------------------------
var
i : Integer ;
iDev: Integer;
begin
List.Clear ;
List.Add('None');
for iDev := 1 to LabIO.NumDevices do
for i := 0 to LabIO.NumDACs[iDev]-1 do begin
List.Add(Format('Dev%d:AO%d',[iDev,i])) ;
end;
end;
procedure TLaser.GetCOMPorts( List : TStrings ) ;
// -------------------------------
// Get list of available COM ports
// -------------------------------
var
i : Integer ;
begin
List.Clear ;
List.Add('None') ;
for i := 1 to 8 do begin
List.Add(Format('COM%d',[i])) ;
end;
end ;
procedure TLaser.SetShutterOpen( Value : boolean ) ;
// ------------------------
// Open/close laser shutter
// ------------------------
var
iLine,iBit,iDev,i : Integer ;
begin
FShutterOpen := Value ;
// Set laser intensity
if FShutterOpen then SetIntensity( FIntensity )
else SetIntensity( 0.0 ) ;
if FShutterControlLine <= 0 then Exit ;
iLine := 1 ;
for iDev := 1 to LabIO.NumDevices do begin
iBit := 1 ;
for i := 0 to 7 do begin
if iLine = FShutterControlLine then begin
LabIO.DigOutState[iDev] := LabIO.DigOutState[iDev] and (not iBit) ;
if FShutterOpen then LabIO.DigOutState[iDev] := LabIO.DigOutState[iDev] or iBit ;
LabIO.WriteToDigitalOutPutPort( iDev, LabIO.DigOutState[iDev] ) ;
end ;
iBit := iBit*2 ;
Inc(iLine) ;
end;
end;
end;
procedure TLaser.SetIntensity( Value : double) ;
// -------------------
// Set laser intensity
// -------------------
var
iLine,iDev,Ch : Integer ;
begin
FIntensity := Min(Max(Value,0),100);
if FIntensityControlLine <= 0 then Exit ;
iLine := 1 ;
for iDev := 1 to LabIO.NumDevices do begin
for Ch := 0 to LabIO.NumDACs[iDev]-1 do begin
if iLine = FIntensityControlLine then begin
LabIO.WriteDAC( iDev, (Value*0.01)/VMaxIntensity, Ch ) ;
end ;
Inc(iLine) ;
end;
end;
end;
procedure TLaser.SetCOMPort( Value : Integer ) ;
// --------------------------
// Set laser control COM port
// --------------------------
begin
FCOMPort := Value ;
end;
end.
|
unit gmClientDataset;
interface
{.$DEFINE BuildInstance} // Creazione strutture QB a livello di istanza (AV ?)
{$REGION 'DatasetHelper'}
{
TDataSet helper classes to simplify access to TDataSet fields and make TDataSet
work with a for-in-loop.
Author: Uwe Raabe - ur@ipteam.de
Techniques used:
- class helpers
- enumerators
- invokable custom variants
This unit implements some "Delphi Magic" to simplify the use of TDataSets and
its fields. Just by USING this unit you can access the individual fields of a
TDataSet like they were properties of a class. For example let's say a DataSet
has fields First_Name and Last_Name. The normal approach to access the field
value would be to write something like this:
DataSet.FieldValues['First_Name']
or
DataSet.FieldByName('First_Name'].Value
With this unit you can simply write
DataSet.CurrentRec.First_Name
You can even assign DataSet.CurrentRec to a local variable of type variant to
shorten the needed typing and clarify the meaning (let PersonDataSet be a
TDataSet descendant with fields as stated above).
var
Person: Variant;
FullName: string;
begin
Person := PersonDataSet.CurrentRec;
...
FullName := Trim(Format('%s %s', [Person.First_Name, Person.Last_Name]));
...
end;
If you write to such a property, the underlying DatsSet is automatically set
into Edit mode.
Obviously you still have to know the field names of the dataset, but this is
just the same as if you are using FieldByName.
The second benefit of this unit shows up when you try to iterate over a
DataSet. This reduces to simply write the following (let Lines be a TStrings
decendant taking the full names of all persons):
var
Person: Variant;
begin
...
// Active state of PersonDataSet is saved during the for loop.
// If PersonDataSet supports bookmarks, the position is also saved.
for Person in PersonDataSet do begin
Lines.Add(Trim(Format('%s %s', [Person.First_Name, Person.Last_Name])));
end;
...
end;
You can even set these "variant-field-properties" during the for loop as the
DataSet will automatically Post your changes within the Next method.
How it works:
We use a class helper to add the CurrentRec property and the enumerator to the
TDataSet class. The CurrentRec property is also used by the enumerator to
return the current record when iterating. The TDataSetEnumerator does some
housekeeping to restore the active state and position of the DataSet after
the iteration, thus your code hasn't to do this each time.
The tricky thing is making the variant to access the dataset fields as if they
were properties. This is accomplished by introducing a custom variant type
descending from TInvokeableVariantType. Besides the obligatory overwriting of
Clear and Copy, which turn out to be quite simple, we implement the GetProperty
and SetProperty methods to map the property names to field names. That's all!
CAUTION! Don't do stupid things with the DataSet while there is some of these
variants connected to it. Especially don't destroy it!
The variant stuff is completely hidden in the implementation section, as for
now I can see no need to expose it.
}
{$ENDREGION}
uses RemoteDB.Client.Dataset, RemoteDB.Client.Database, System.Classes,
Data.DB, System.SysUtils, acSQL92SynProvider, acSQLBuilderPlainText,
acQBBase, acAST;
type
TgmClientDataset = class;
EValidationError = class(Exception)
public
FDataset: TDataset;
Field: TField;
end;
TSequenceField = class(TPersistent)
private
// FField: string;
FSequence: string;
// FApplyMoment: TSequenceApplyMoment;
// function UsesField(const AField: string): Boolean;
// function ApplyFieldOnServer(const AField: string): Boolean;
function GenerateGetNextSequenceValue(SequenceName: string): string;
function GetPrimaryKey: string;
protected
procedure AssignTo(Dest: TPersistent); override;
public
DataSet: TgmClientDataset;
constructor Create(ADataSet: TgmClientDataset);
function ValueName: string;
procedure Apply;
function GetSequenceValue: integer;
function IsComplete: Boolean;
published
// property Field: string read FField write FField;
property Sequence: string read FSequence write FSequence;
// property ApplyMoment: TSequenceApplyMoment read FApplyMoment write FApplyMoment;
end;
TgmDatabase = class(TRemoteDBDatabase)
protected
procedure SetConnected(const Value: boolean); override;
public
function SqlDialect: string;
end;
TDataSetEnumerator = class
private
FBookmark: TBookmark;
FDataSet: TgmClientDataset;
FMoveToFirst: Boolean;
FWasActive: Boolean;
function GetCurrent: Variant;
public
constructor Create(ADataSet: TgmClientDataset);
destructor Destroy; override;
function MoveNext: Boolean;
property Current: Variant read GetCurrent;
end;
TgmClientDataset = class(TXDataset)
private
FDesignActivation: Boolean;
FUpdateTableName: string;
FKeyFields: string;
FSequenceField: TSequenceField;
FActiveOnLoading: Boolean;
FImmediatePost: boolean;
FOldSQL: TStrings;
procedure SetSequenceField(Value: TSequenceField);
procedure InternalSetActive(Value: Boolean);
function GetActive: Boolean;
function GetCurrentRec: Variant;
// function ChangedFromLastQuery(pParam: Variant): boolean;
protected
procedure DoRecordDelete(Index: integer); override;
procedure DoRecordInsert(Index: integer); override;
procedure DoRecordUpdate(Index: integer); override;
procedure DoOnNewRecord; override;
procedure Loaded; override;
procedure DoBeforePost; override;
function PSGetKeyFields: string; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ParamByName(const ParamName: string): TParam;
procedure CheckFields;
procedure CheckFieldsBeforePost;
procedure RaiseError(const msg: string; fField: TField = nil);
procedure AbortError(const msg: string; fField: TField = nil);
function GetPrimaryKey: string;
procedure GetAll; overload;
procedure GetAll(const pExpression: string); overload;
procedure GetAll(const pExpression: string; const Args: array of const); overload;
function GetEnumerator: TDataSetEnumerator;
function DateToString(dd: TDate): string;
procedure UpdateSQL(const pSQL: string);
property CurrentRec: Variant read GetCurrentRec;
published
property DesignActivation: Boolean read FDesignActivation write FDesignActivation default True;
property Active: Boolean read GetActive write InternalSetActive;
property UpdateTableName: string read FUpdateTableName write
FUpdateTablename;
property SequenceField: TSequenceField read FSequenceField write SetSequenceField;
property ImmediatePost: boolean read FImmediatePost write FImmediatePost default True;
end;
TacQBuildWhere = class
private
class var FacSQL92SyntaxProvider: TacSQL92SyntaxProvider;
class var Fqb: TacQueryBuilder;
class var FSQLBuilder: TacSQLBuilderPlainText;
class procedure Initialize;
class procedure Finalize;
class procedure ClearWhere(AUnionSubQuery: TacUnionSubQuery);
class procedure FixupExpression(AQueryContext:TacQueryBuilderControlOwner; AExpression:TSQLExpressionItem);
class procedure AppendWhere(AUnionSubQuery:TacUnionSubQuery; const ANewWhere:WideString);
public
// class constructor Create;
class function AggiungiWhere( const pSQL,pExpression: string ): string;
end;
resourcestring
sgmValoreObbligatorio = 'Valore obbligatorio !';
implementation
uses Vcl.Dialogs, System.Contnrs,
{$REGION 'DatasetHelper'}
System.Variants;
type
{ A custom variant type that implements the mapping from the property names
to the DataSet fields. }
TVarDataRecordType = class(TInvokeableVariantType)
public
procedure Clear(var V: TVarData); override;
procedure Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean); override;
function GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean; override;
function SetProperty(const V: TVarData; const Name: string; const Value: TVarData): Boolean; override;
end;
type
{ Our layout of the variants record data.
We only hold a pointer to the DataSet. }
TVarDataRecordData = packed record
VType: TVarType;
Reserved1, Reserved2, Reserved3: Word;
DataSet: TDataSet;
Reserved4: LongInt;
end;
var
{ The global instance of the custom variant type. The data of the custom
variant is stored in a TVarData record, but the methods and properties
are implemented in this class instance. }
VarDataRecordType: TVarDataRecordType = nil;
{ A global function the get our custom VarType value. This may vary and thus
is determined at runtime. }
function VarDataRecord: TVarType;
begin
result := VarDataRecordType.VarType;
end;
{ A global function that fills the VarData fields with the correct values. }
function VarDataRecordCreate(ADataSet: TDataSet): Variant;
begin
VarClear(result);
TVarDataRecordData(result).VType := VarDataRecord;
TVarDataRecordData(result).DataSet := ADataSet;
end;
procedure TVarDataRecordType.Clear(var V: TVarData);
begin
{ No fancy things to do here, we are only holding a pointer to a TDataSet and
we are not supposed to destroy it here. }
SimplisticClear(V);
end;
procedure TVarDataRecordType.Copy(var Dest: TVarData; const Source: TVarData; const Indirect: Boolean);
begin
{ No fancy things to do here, we are only holding a pointer to a TDataSet and
that can simply be copied here. }
SimplisticCopy(Dest, Source, Indirect);
end;
function TVarDataRecordType.GetProperty(var Dest: TVarData; const V: TVarData; const Name: string): Boolean;
var
fld: TField;
begin
{ Find a field with the property's name. If there is one, return its current value. }
fld := TVarDataRecordData(V).DataSet.FindField(Name);
result := (fld <> nil);
if result then
Variant(dest) := fld.Value;
end;
function TVarDataRecordType.SetProperty(const V: TVarData; const Name: string; const Value: TVarData): Boolean;
var
fld: TField;
begin
{ Find a field with the property's name. If there is one, set its value. }
fld := TVarDataRecordData(V).DataSet.FindField(Name);
result := (fld <> nil);
if result then begin
{ Well, we have to be in Edit mode to do this, don't we? }
TVarDataRecordData(V).DataSet.Edit;
fld.Value := Variant(Value);
end;
end;
constructor TDataSetEnumerator.Create(ADataSet: TgmClientDataset);
{ The enumerator is automatically created and destroyed in the for-in loop.
So we remember the active state and set a flag that the first MoveNext will
not move to the next record, but stays on the first one instead. }
begin
inherited Create;
FDataSet := ADataSet;
Assert(FDataSet <> nil);
{ save the Active state }
FWasActive := FDataSet.Active;
{ avoid flickering }
FDataSet.DisableControls;
if FWasActive then begin
{ get a bookmark of the current position - even if it is invalid }
FBookmark := FDataSet.GetBookmark;
FDataSet.First;
end
else begin
{ FBookmark is initialized to nil anyway, so no need to set it here }
FDataSet.Active := true;
end;
FMoveToFirst := true;
end;
destructor TDataSetEnumerator.Destroy;
{ Restore the DataSet to its previous state. }
begin
if FWasActive then begin
{ if we have a valid bookmark, use it }
if FDataSet.BookmarkValid(FBookmark) then
FDataSet.GotoBookmark(FBookmark);
{ I'm not sure, if FreeBokmark can handle nil pointers - so to be safe }
if FBookmark <> nil then
FDataSet.FreeBookmark(FBookmark);
end
else
FDataSet.Active := false;
{ don't forget this one! }
FDataSet.EnableControls;
inherited;
end;
function TDataSetEnumerator.GetCurrent: Variant;
begin
{ We simply return the CurrentRec property of the DataSet, which is exposed
due to the class helper. }
Result := FDataSet.CurrentRec;
end;
function TDataSetEnumerator.MoveNext: Boolean;
begin
{ Check if we have to move to the first record, which has been done already
during Create. }
if FMoveToFirst then
FMoveToFirst := false
else
FDataSet.Next;
Result := not FDataSet.EoF;
end;
{$ENDREGION}
procedure FieldToField(outField: TField; InField: TField);
begin
if InField.IsNull then
outField.Clear
else
case outField.DataType of
ftstring:
outField.AsString := InField.AsString;
ftfloat,ftcurrency:
outField.AsFloat := InField.AsFloat;
ftInteger,FtsmallInt,Ftword:
outField.AsInteger := InField.AsInteger;
ftdate,ftdatetime:
outField.AsDateTime := InField.AsDateTime;
else
outField.Value := InField.Value;
end;{case}
end;
(*
class constructor TacQBuildWhere.Create;
begin
{$IFDEF BuildInstance}
Initialize;
{$ENDIF}
end;
*)
class procedure TacQBuildWhere.Initialize;
begin
FacSQL92SyntaxProvider := TacSQL92SyntaxProvider.Create(nil);
Fqb := TacQueryBuilder.Create(nil);
Fqb.SyntaxProvider := FacSQL92SyntaxProvider;
FSQLBuilder := TacSQLBuilderPlainText.Create(nil);
FSQLBuilder.QueryBuilder := Fqb;
end;
class procedure TacQBuildWhere.Finalize;
begin
FSQLBuilder.Free;
Fqb.Free;
FacSQL92SyntaxProvider.Free;
end;
class procedure TacQBuildWhere.ClearWhere(AUnionSubQuery: TacUnionSubQuery);
var sl:TacSelectList;
i:integer;
si:TacSelectItem;
j:integer;
begin
// get reference to SelectList
sl:=AUnionSubQuery.SelectList;
// disable SQL updating for QueryBuilder
Fqb.BeginUpdate;
try
// clear old Where
for i:=0 to sl.Count-1 do
begin
si:=sl[i];
if si.ConditionsType = ctWhere
then begin
// clear all WHERE expressions in a row
for j:=0 to si.ConditionsCount-1 do
si.ConditionString[j]:='';
end;
end;
finally
Fqb.EndUpdate;
end;
end;
class procedure TacQBuildWhere.FixupExpression(AQueryContext:TacQueryBuilderControlOwner;
AExpression:TSQLExpressionItem);
var
listCTE, listFromSources: TObjectList;
begin
Assert(AExpression<>nil);
// fixup names in raw AST in given context
listCTE := TObjectList.Create(false);
listFromSources := TObjectList.Create(false);
try
AQueryContext.GatherPrepareAndFixupContext(listCTE,listFromSources,true);
AExpression.PrepareAndFixupRecursive(listCTE,listFromSources);
finally
listCTE.Free;
listFromSources.Free;
end;
end;
class procedure TacQBuildWhere.AppendWhere(AUnionSubQuery:TacUnionSubQuery; const ANewWhere:WideString);
var
oldWhere: TSQLExpressionItem;
newWhere: TSQLExpressionItem;
tmp: TSQLExpressionLogicalCollection;
resultWhere: TSQLExpressionAnd;
function ParseExpression(const AExpression:WideString):TSQLExpressionItem;
begin
// parse expression to get raw AST
Result := Fqb.SQLContext.ParseLogicalExpression(AExpression);
end;
begin
// parse and prepare new WHERE expression
newWhere := ParseExpression(ANewWhere);
// if there are no new expression - nothing to do
if newWhere=nil then exit;
// extract old WHERE expression
oldWhere:=AUnionSubQuery.SelectList.GetConditionTree([ctWhere]);
// "un-fixup" old WHERE expression
if oldWhere<>nil then oldWhere.RestoreColumnPrefixRecursive(true);
// simplify old WHERE expression
if oldWhere<>nil
then begin
// if old WHERE is a collection of ORed or ANDed expressions
// with only one expression in the list - remove external list
while (oldWhere is TSQLExpressionLogicalCollection)and
(TSQLExpressionLogicalCollection(oldWhere).Count=1) do
begin
tmp:=TSQLExpressionLogicalCollection(oldWhere);
oldWhere:=tmp.Extract(0);
tmp.Free;
end;
end;
// combine old and new WHERE expressions
resultWhere:=TSQLExpressionAnd.Create(Fqb.SQLContext);
if oldWhere<>nil then resultWhere.Add(oldWhere);
resultWhere.Add(newWhere);
// fixup combined WHERE expression
FixupExpression(AUnionSubQuery,resultWhere);
// defer SQL updates
AUnionSubQuery.BeginUpdate;
try
// clear old WHERE expression
ClearWhere(AUnionSubQuery);
// load new WHERE expression (if exists)
AUnionSubQuery.SelectList.LoadConditionFromAST(resultWhere,ctWhere);
finally
// enable SQL updates
AUnionSubQuery.EndUpdate;
end;
end;
class function TacQBuildWhere.AggiungiWhere( const pSQL,pExpression: string ): string;
var
usq: TacUnionSubQuery;
begin
{$IFNDEF BuildInstance}
Initialize;
try
{$ENDIF}
Fqb.SQL := pSQL;
// get the active SELECT
usq := Fqb.Query.ActiveUnionSubquery;
AppendWhere(usq, pExpression);
result := FSQLBuilder.SQL;
{$IFNDEF BuildInstance}
finally
Finalize;
end;
{$ENDIF}
end;
{ TgmDatabase }
function TgmDatabase.SqlDialect: string;
begin
result := GetSqlDialect;
end;
procedure TgmDatabase.SetConnected(const Value: boolean);
begin
if {(not (csDesigning in ComponentState)) and}
(csLoading in ComponentState) then Exit;
inherited;
end;
{ TSequenceField }
constructor TSequenceField.Create(ADataSet: TgmClientDataset);
begin
inherited Create;
// FField := '';
FSequence := '';
DataSet := ADataSet;
end;
function TSequenceField.GenerateGetNextSequenceValue(SequenceName: string): string;
begin
if DataSet.Database.SqlDialect='Oracle' then
Result := Format('SELECT CAST(%s.NEXTVAL AS NUMBER(10)) FROM DUAL', [SequenceName])
else // DataSet.Database.GetSqlDialect='MSSql' then
Result := Format('SELECT CAST(NEXT VALUE FOR %s AS INTEGER)', [SequenceName]);
end;
procedure TSequenceField.AssignTo(Dest: TPersistent);
begin
if Dest is TSequenceField then
begin
// TSequenceField(Dest).Field := Field;
TSequenceField(Dest).Sequence := Sequence;
// TSequenceField(Dest).ApplyMoment := ApplyMoment;
Exit;
end;
inherited;
end;
function TSequenceField.GetPrimaryKey: string;
begin
{
if DataSet.PrimeFields.Count>0 then
result := DataSet.PrimeFields[0]
else
result := '';
}
result := DataSet.GetPrimaryKey;
end;
function TSequenceField.IsComplete: Boolean;
begin
Result := (Sequence <> '') and (GetPrimaryKey <> '');
end;
function TSequenceField.ValueName: string;
begin
if IsComplete then
Result := Sequence {+ ' > ' + Field}
else
Result := '';
end;
procedure TSequenceField.Apply;
var
xQuery: TXDataset;
begin
if IsComplete and (DataSet.FieldByName(GetPrimaryKey).IsNull) then
begin
xQuery := TXDataset.Create(DataSet);
Try
xQuery.Database := DataSet.Database;
xQuery.SQL.Text := GenerateGetNextSequenceValue( Sequence );
xQuery.open;
if not xQuery.IsEmpty then
FieldToField(DataSet.FieldByName(GetPrimaryKey),xQuery.Fields[0])
else
raise EDataBaseError.Create('Errore durante la lettura della sequence');
Finally
xQuery.Free;
end;
end;
end;
function TSequenceField.GetSequenceValue: integer;
var
xQuery: TXDataset;
begin
result := -1;
if IsComplete then
begin
xQuery := TXDataset.Create(DataSet);
try
xQuery.Database := DataSet.Database;
xQuery.SQL.Text := GenerateGetNextSequenceValue( Sequence );
xQuery.open;
if not xQuery.IsEmpty then
result := xQuery.Fields[0].AsInteger
else
raise EDataBaseError.Create('Errore durante la lettura della sequence');
finally
xQuery.Free;
end;
end;
end;
{ TgmClientDataset }
constructor TgmClientDataset.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSequenceField := TSequenceField.Create(Self);
FDesignActivation := True;
FImmediatePost := True;
FOldSQL := TStringList.Create;
end;
destructor TgmClientDataset.Destroy;
begin
FSequenceField.Free;
FOldSQL.Free;
inherited;
end;
procedure TgmClientDataset.Loaded;
function OkToOpen: Boolean;
begin
Result := False;
if not Active then
Exit;
// if suitCaseStatus <> scsNone then
// Exit;
Result := (SQL.Count > 0);
end;
begin
inherited Loaded;
if not (csdesigning in componentstate) and
(Database <> nil) and OkToOpen then
begin
if not Database.Connected then
begin
Active := False;
// FNeedsInitialOpenBySocket := True;
// AstaClientSocket.AddtoSession(Self);
end;
end;
{JRT}
try
if FActiveOnLoading then Active := True;
except
{if csDesigning in ComponentState then InternalHandleException else} raise;
end;
{}
end;
function TgmClientDataset.ParamByName(const ParamName: string): TParam;
begin
result := Params.FindParam(ParamName);
end;
procedure TgmClientDataset.InternalSetActive(Value: Boolean);
var
aol: Boolean;
begin
if FDesignActivation and (not (csDesigning in ComponentState)) and
((csLoading in ComponentState)) then Exit;
if ((csReading in ComponentState) or (csLoading in ComponentState)) or
((Database = nil) and (csDesigning in ComponentState)) then
begin
if Value then FActiveOnLoading := True;
end else begin
aol := FActiveOnLoading;
FActiveOnLoading := False;
if Value <> Active then
begin
if aol and Value and (Database <> nil) and (not Database.Connected) and
(not (csDesigning in ComponentState)) then Exit;
inherited Active := Value;
// if Value and QBEMode then EnterQBEMode;
end;
end;
end;
function TgmClientDataset.GetActive: Boolean;
begin
Result := inherited Active;
end;
procedure TgmClientDataset.SetSequenceField(Value: TSequenceField);
begin
FSequenceField.Assign(Value);
end;
procedure TgmClientDataset.DoRecordDelete;
Var
i1, iKeyFieldPos : Integer ;
sSQL, sKey, sWhereClause : String ;
bFirstField : Boolean;
slKey, slKeyVal : TStringList;
xUpdateDataset : TXDataset;
begin
if Assigned(OnRecordDelete) then
begin
inherited;
Exit;
end;
if not FImmediatePost then Exit;
If ((FUpdateTablename = '') or (GetPrimaryKey = '')) then
begin
MessageDlg('Primary Key and UpdatingTable Required for Live Updates',mtWarning,[mbOK],0);
Exit;
end;
// Parse Primary Keys into StringList
slKey := TStringList.Create;
slKey.Delimiter := ';';
slKey.Text := GetPrimaryKey;
slKeyVal := TStringList.Create;
Try
{
for i1 := 0 to FPrimeFields.Count-1 do
begin
sKey := FPrimeFields[i1];
If sKey <> '' then
begin
slKey.Add(sKey);
slKeyVal.Add(FieldByName(sKey).AsString);
end;
}
for i1 := 0 to slKey.Count-1 do
slKeyVal.Add(FieldByName(slKey[i1]).AsString);
sSQL := 'DELETE FROM ' + FUpdateTablename + ' ';
For i1 := 1 to ModifiedFields.Count do
begin
iKeyFieldPos := slKey.IndexOf(ModifiedFields[i1-1].FieldName);
If iKeyFieldPos > -1 then // Primary Key is being modified - adjust list for Where clause accordingly
begin
slKeyVal[iKeyFieldPos] := VarToStr(ModifiedFields[i1-1].OldValue);
end;
end;
//Build Where Clause
bFirstField := True;
For i1 := 0 to slKey.Count-1 do
begin
If bFirstField then
begin
If FieldByName(slKey[i1]).DataType in [ftFloat, ftCurrency, ftBCD, ftSmallint, ftInteger, ftWord, ftLargeint] then
sWhereClause := ' WHERE ' + slKey[i1] + '=' + slKeyVal[i1] else
sWhereClause := ' WHERE ' + slKey[i1] + '=''' + slKeyVal[i1] + '''';
bFirstField := False;
end else
begin
If FieldByName(slKey[i1]).DataType in [ftFloat, ftCurrency, ftBCD, ftSmallint, ftInteger, ftWord, ftLargeint] then
sWhereClause := sWhereClause + ' AND ' + slKey[i1] + '=' + slKeyVal[i1] else
sWhereClause := sWhereClause + ' AND ' + slKey[i1] + '=''' + slKeyVal[i1] + '''';
end;
end;
sSQL := sSQL + sWhereClause;
xUpdateDataset := TXDataset.Create(Self);
Try
xUpdateDataset.Database := Database;
xUpdateDataset.SQL.Text := sSQL;
xUpdateDataset.Execute;
Finally
xUpdateDataSet.Free;
end;
//ShowMessage(sSQL);
Finally
slKey.Free;
slKeyVal.Free;
end;
end;
procedure TgmClientDataset.DoRecordInsert;
Var
i1, iNewValue: Integer ;
sSQL, sKey: String ;
dNewValue : Double;
bFirstField : Boolean;
dtNewValue : TDateTime;
slKey : TStringList;
xUpdateDataset : TgmClientDataset;
begin
if Assigned(OnRecordInsert) then
begin
inherited;
Exit;
end;
if not FImmediatePost then Exit;
If ((FUpdateTablename = '') or (GetPrimaryKey = '')) then
begin
MessageDlg('Primary Key and UpdatingTable Required for Live Updates',mtWarning,[mbOK],0);
Exit;
end;
// Parse Primary Keys into StringList
slKey := TStringList.Create;
slKey.Delimiter := ';';
slKey.Text := GetPrimaryKey;
Try
{
for i1 := 0 to FPrimeFields.Count-1 do
begin
sKey := FPrimeFields[i1];
If sKey <> '' then
begin
slKey.Add(sKey);
end;
end;
}
bFirstField := True;
sSQL := 'INSERT INTO ' + FUpdateTablename + ' (';
For i1 := 1 to ModifiedFields.Count do
begin
If bFirstField then
begin
sSQL := sSQL + ModifiedFields[i1-1].FieldName ;
bFirstField := False;
end else sSQL := sSQL + ',' + ModifiedFields[i1-1].FieldName ;
end;
sSQL := sSQL + ') VALUES (';
For i1 := 1 to ModifiedFields.Count do
begin
sSQL := sSQL + ':' + ModifiedFields[i1-1].FieldName + ',';
end;
sSQL := Copy(sSQL,1,Length(sSQL)-1);
sSQL := sSQL + ')';
// sSQL := 'var xpkambulatori integer'+#13+ sSQL;
// sSQL := sSQL + ' RETURNING PKAMBULATORI INTO xpkambulatori'+#13+'SELECT xpkambulatori from dual';
// ShowMessage(sSQL);
xUpdateDataset := TgmClientDataset.Create(Self);
Try
xUpdateDataset.Database := Database;
xUpdateDataset.UpdateSQL( sSQL );
// xUpdateDataset.ParamByName('PKAMBULATORI').ParamType := ptInputOutput;
// xUpdateDataset.ParamByName('PKAMBULATORI').DataType := ftInteger;
For i1 := 1 to ModifiedFields.Count do
begin
If ModifiedFields[i1-1].DataType in [ftString, ftFixedChar, ftWideString] then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsString := ModifiedFields[i1-1].NewValue;
end;
If ModifiedFields[i1-1].DataType in [ftSmallint, ftInteger, ftWord, ftLargeint] then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsInteger := ModifiedFields[i1-1].NewValue;
end;
If ModifiedFields[i1-1].DataType in [ftFloat, ftCurrency, ftBCD] then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsFloat := ModifiedFields[i1-1].NewValue;
end;
If ModifiedFields[i1-1].DataType = ftDate then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsDate := ModifiedFields[i1-1].NewValue;
end;
If ModifiedFields[i1-1].DataType = ftTime then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsTime := ModifiedFields[i1-1].NewValue;
end;
If ModifiedFields[i1-1].DataType = ftDateTime then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsDateTime := ModifiedFields[i1-1].NewValue;
end;
If ModifiedFields[i1-1].DataType in [ftMemo, ftWideMemo] then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).Clear
else
xUpdateDataset.ParamByName(ModifiedFields[i1-1].FieldName).AsString := ModifiedFields[i1-1].NewValue;
end;
end;
xUpdateDataset.Execute;
// FieldByName('PKAMBULATORI').AsInteger := xUpdateDataset.ParamByName('PKAMBULATORI').AsInteger;
Finally
xUpdateDataSet.Free;
end;
Finally
slKey.Free;
end;
end;
procedure TgmClientDataset.DoRecordUpdate;
Var
i1, iNewValue, iKeyFieldPos : Integer ;
sSQL, sKey, sWhereClause : String ;
dNewValue : Double;
bFirstField : Boolean;
dtNewValue : TDateTime;
slKey, slKeyVal : TStringList;
xUpdateDataset : TXDataset;
begin
if Assigned(OnRecordUpdate) then
begin
inherited;
Exit;
end;
if not FImmediatePost then Exit;
If ((FUpdateTablename = '') or (GetPrimaryKey = '')) then
begin
MessageDlg('Primary Key and UpdatingTable Required for Live Updates',mtWarning,[mbOK],0);
Exit;
end;
// Parse Primary Keys into StringList
slKey := TStringList.Create;
slKey.Delimiter := ';';
slKey.Text := GetPrimaryKey;
slKeyVal := TStringList.Create;
Try
{
for i1 := 0 to FPrimeFields.Count-1 do
begin
sKey := FPrimeFields[i1];
If sKey <> '' then
begin
slKey.Add(sKey);
slKeyVal.Add(FieldByName(sKey).AsString);
end;
end;
}
for i1 := 0 to slKey.Count-1 do
slKeyVal.Add(FieldByName(slKey[i1]).AsString);
bFirstField := True;
sSQL := 'UPDATE ' + FUpdateTablename + ' SET ';
For i1 := 1 to ModifiedFields.Count do
begin
iKeyFieldPos := slKey.IndexOf(ModifiedFields[i1-1].FieldName);
If iKeyFieldPos > -1 then // Primary Key is being modified - adjust list for Where clause accordingly
begin
slKeyVal[iKeyFieldPos] := VarToStr(ModifiedFields[i1-1].OldValue);
end;
If bFirstField then
begin
sSQL := sSQL + ModifiedFields[i1-1].FieldName + '=';
bFirstField := False;
end else sSQL := sSQL + ', ' + ModifiedFields[i1-1].FieldName + '=';
If ModifiedFields[i1-1].DataType in [ftString, ftFixedChar, ftWideString] then
begin
sSQL := sSQL + '''' + VarToStr(ModifiedFields[i1-1].NewValue) + '''';
end;
If ModifiedFields[i1-1].DataType in [ftSmallint, ftInteger, ftWord, ftLargeint] then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then sSQL := sSQL + 'NULL' else
begin
iNewValue := ModifiedFields[i1-1].NewValue;
sSQL := sSQL + IntToStr(iNewValue);
end;
end;
If ModifiedFields[i1-1].DataType in [ftFloat, ftCurrency, ftBCD] then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then sSQL := sSQL + 'NULL' else
begin
dNewValue := ModifiedFields[i1-1].NewValue;
sSQL := sSQL + FormatFloat('#########0.0############',dNewValue);
end;
end;
If ModifiedFields[i1-1].DataType = ftDate then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then sSQL := sSQL + 'NULL' else
begin
dtNewValue := ModifiedFields[i1-1].NewValue;
if dtNewValue <= 0 then sSQL := sSQL + 'NULL' else
sSQL := sSQL + '''' + FormatDateTime('dd/mm/yyyy',dtNewValue) + '''';
end;
end;
If ModifiedFields[i1-1].DataType = ftTime then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then sSQL := sSQL + 'NULL' else
begin
dtNewValue := ModifiedFields[i1-1].NewValue;
sSQL := sSQL + '''' + FormatDateTime('hh:mm:ss am/pm',dtNewValue) + '''';
end;
end;
If ModifiedFields[i1-1].DataType = ftDateTime then
begin
If VarToStr(ModifiedFields[i1-1].NewValue) = '' then sSQL := sSQL + 'NULL' else
begin
dtNewValue := ModifiedFields[i1-1].NewValue;
if dtNewValue <= 0 then sSQL := sSQL + 'NULL' else
sSQL := sSQL + '''' + FormatDateTime('dd/mm/yyyy hh:mm:ss am/pm',dtNewValue) + '''';
end;
end;
If ModifiedFields[i1-1].DataType in [ftMemo, ftWideMemo] then
begin
sSQL := sSQL + '''' + VarToStr(ModifiedFields[i1-1].NewValue) + '''';
end;
end;
//Build Where Clause
bFirstField := True;
For i1 := 0 to slKey.Count-1 do
begin
If bFirstField then
begin
If FieldByName(slKey[i1]).DataType in [ftFloat, ftCurrency, ftBCD, ftSmallint, ftInteger, ftWord, ftLargeint] then
sWhereClause := ' WHERE ' + slKey[i1] + '=' + slKeyVal[i1] else
sWhereClause := ' WHERE ' + slKey[i1] + '=''' + slKeyVal[i1] + '''';
bFirstField := False;
end else
begin
If FieldByName(slKey[i1]).DataType in [ftFloat, ftCurrency, ftBCD, ftSmallint, ftInteger, ftWord, ftLargeint] then
sWhereClause := sWhereClause + ' AND ' + slKey[i1] + '=' + slKeyVal[i1] else
sWhereClause := sWhereClause + ' AND ' + slKey[i1] + '=''' + slKeyVal[i1] + '''';
end;
end;
sSQL := sSQL + sWhereClause;
xUpdateDataset := TXDataset.Create(Self);
Try
xUpdateDataset.Database := Database;
xUpdateDataset.SQL.Text := sSQL;
xUpdateDataset.Execute;
Finally
xUpdateDataSet.Free;
end;
Finally
slKey.Free;
slKeyVal.Free;
end;
end;
procedure TgmClientDataset.DoOnNewRecord;
begin
inherited;
// if not (UpdateMethod=umManual) and (SequenceField.ApplyMoment = amOnNewRecord) then
if SequenceField.IsComplete then
SequenceField.Apply;
end;
procedure TgmClientDataset.DoBeforePost;
begin
inherited;
// sempre! if (FImmediatePost { ??? or (FMasterDataSet<>nil)}) {and not Assigned(BeforePost)} then
CheckFieldsBeforePost;
end;
procedure TgmClientDataset.CheckFieldsBeforePost;
begin
try
CheckFields;
except
on E: EValidationError do
begin
MessageDlg(E.Field.DisplayName + #13 + E.Message,mtWarning,[mbOk],0);
E.Field.FocusControl;
Abort;
end;
end;
end;
procedure TgmClientDataset.CheckFields;
var
i: integer;
// e: EValidationError;
// msg: string;
begin
for i:=0 to FieldCount-1 do
begin
if Fields[i].Required and Fields[i].IsNull then
begin
RaiseError(sgmValoreObbligatorio,Fields[i]);
end;
end;
end;
procedure TgmClientDataset.RaiseError(const msg: string; fField: TField = nil);
var
e: EValidationError;
begin
e := EValidationError.Create(msg);
e.FDataset := self;
e.Field := fField;
raise e;
end;
procedure TgmClientDataset.AbortError(const msg: string; fField: TField = nil);
var
MsgErr: string;
begin
try
RaiseError(msg, fField);
except
on E: EValidationError do
begin
MsgErr := E.Message;
if E.Field<>nil then
MsgErr := E.Field.DisplayName + #13 + MsgErr;
MessageDlg(MsgErr,mtWarning,[mbOk],0);
if E.Field<>nil then
E.Field.FocusControl;
Abort;
end;
end;
end;
function TgmClientDataset.PSGetKeyFields: string;
begin
if FKeyFields='' then
begin
FKeyFields := inherited;
end;
result := FKeyFields;
end;
function TgmClientDataset.GetPrimaryKey: string;
begin
result := PSGetKeyFields;
end;
procedure TgmClientDataset.GetAll;
begin
Close;
// -- ripristino l'SQL originario
if FoldSQL.Count>0 then
begin
SQL := FoldSQL;
FoldSQL.Clear;
end;
Open;
end;
procedure TgmClientDataset.GetAll(const pExpression: string; const Args: array of const);
begin
GetAll( format( pExpression, Args ) );
end;
procedure TgmClientDataset.GetAll(const pExpression: string);
var
tempSQL: string;
begin
Close;
// -- ripristino l'SQL originario
if FoldSQL.Count>0 then
begin
SQL := FoldSQL;
FoldSQL.Clear;
end;
tempSQL := TacQBuildWhere.AggiungiWhere( SQL.Text, pExpression );
UpdateSQL( tempSQL );
Open;
end;
procedure TgmClientDataset.UpdateSQL(const pSQL: string);
var
sTemp: TStrings;
begin
sTemp := TStringList.Create;
Try
sTemp.Text := pSQL;
SQL := sTemp;
finally
sTemp.Free;
End;
end;
{$REGION 'DatasetHelper'}
function TgmClientDataset.GetCurrentRec: Variant;
begin
{ return one of our custom variants }
Result := VarDataRecordCreate(Self);
end;
function TgmClientDataset.GetEnumerator: TDataSetEnumerator;
begin
{ return a new enumerator }
Result := TDataSetEnumerator.Create(Self);
end;
function TgmClientDataset.DateToString(dd: TDate): string;
var
dtemp: string;
begin
DateTimeToString(dtemp,'ddmmyyyy',dd);
if Database.SqlDialect='Oracle' then
Result := Format('TO_CHAR(',[dtemp])
else // DataSet.Database.GetSqlDialect='MSSql' then
Result := Format('CONVERT(',[dtemp]);
end;
(*
function TgmClientDataset.ChangedFromLastQuery(pParam: Variant): boolean;
begin
result := not Active or VarIsNull(FLastQuery) or (FLastQuery<>pParam);
{
if result then
FLastQuery := pParam;
}
end;
*)
initialization
{ Create our custom variant type, which will be registered automatically. }
VarDataRecordType := TVarDataRecordType.Create;
finalization
{ Free our custom variant type. }
FreeAndNil(VarDataRecordType);
{$ENDREGION}
end.
|
unit SiegeTypes;
interface
const
MaxCompanions = 5;
// ThresholdOfPain = 5;
MaxItems = 2047;
MaxTiles = 2047;
ItemListSize = 32767;
MaxScripts = 128;
MaxScriptFrames = 64;
MaxZones = 255;
MaxLightStates = 4;
WorkWidth = 384;
WorkHeight = 160;
MaxSubMaps = 127;
MaxZoneHeight = 2048;
type
TCastingType = ( ctCombat, ctHealing, ctDivination, ctSummoning, ctTranslocation, ctProtection, ctIllusion );
TTargetType = ( ttNone, ttFriend, ttEnemy );
TAIMode = ( aiNone, aiIdle, aiCombat, aiParty );
TAIPriority = ( prNone, prAttack, prGuard, prFlee, prHide, prCast, prFollowClose, prFollowFar );
TAIParameter = ( paNone, paAnyEnemy, paAnyAlly, paAnyPartyMember, paClosestEnemy, paStrongestEnemy,
paWeakestEnemy, paMostMagicalEnemy, paAttacker, paSelf, paSpecificPartyMember, paPlayerTarget );
TMaterial = ( maOther, maMetal );
TNextAction = ( naNone, naWalk, naRun, naAttack, naCast );
TScriptMode = ( smOnce, smRepeat, smRandom );
TDamageRange = record
Min : Single;
Max : Single;
end;
TDamageResistance = record
Invulnerability : Single;
Resistance : Single;
end;
PDamageProfile = ^TDamageProfile;
TDamageProfile = record
Piercing : TDamageRange;
Crushing : TDamageRange;
Cutting : TDamageRange;
Heat : TDamageRange;
Cold : TDamageRange;
Electric : TDamageRange;
Poison : TDamageRange;
Magic : TDamageRange;
Mental : TDamageRange;
Stun : TDamageRange;
Special : TDamageRange;
end;
PDamageResistanceProfile = ^TDamageResistanceProfile;
TDamageResistanceProfile = record
Piercing : TDamageResistance;
Crushing : TDamageResistance;
Cutting : TDamageResistance;
Heat : TDamageResistance;
Cold : TDamageResistance;
Electric : TDamageResistance;
Poison : TDamageResistance;
Magic : TDamageResistance;
Mental : TDamageResistance;
Stun : TDamageResistance;
end;
PStatModifier = ^TStatModifier;
TStatModifier = record
Strength : Integer;
Coordination : Integer;
Constitution : Integer;
Mysticism : Integer;
Combat : Integer;
Stealth : Integer;
Restriction : Integer;
AttackRecovery : Integer;
HitRecovery : Integer;
Perception : Integer;
Charm : Integer;
HealingRate : Integer;
RechargeRate : Integer;
HitPoints : Integer;
Mana : Integer;
Attack : Integer;
Defense : Integer;
Visible : boolean;
DisplayName : string;
end;
TDynamicWordArray = array of Word;
TDynamicSmallIntArray = array of SmallInt;
TFacing = ( fNW, fNN, fNE, fEE, fSE, fSS, fSW, fWW );
TSlot = ( slLeg1, slBoot, slLeg2, slChest1, slChest2, slArm, slBelt, slChest3,
slGauntlet, slOuter, slHelmet, slWeapon, slShield, slMisc1, slMisc2, slMisc3 );
TSlotAllowed = set of TSlot;
TLightSource = record
X, Y, Z : longint;
Intensity : double;
Radius : integer;
end;
PGridInfo = ^GridInfo;
GridInfo = packed record
Figure : Pointer; //For collision detection
FilterID : Smallint;
TriggerID : Smallint;
CollisionMask : Word;
LineOfSightMask : Word;
FilterMask : Word;
TriggerMask : Word;
Tile : array[ 0..4 ] of Word;
Zone : array[ 0..4 ] of Byte;
BitField : Byte; //Bit 7 denotes a diamond tile, Bit 6 is automap.
end;
PTileInfo = ^TileInfo;
TileInfo = packed record
ImageIndex : Word;
Rows : Word;
Columns : Word;
Zone : Word;
Element : Byte;
Reserved : Byte;
end;
MapColumnHeaderInfo = packed record
BaseLine : Longint;
Top : Longint;
Active : Boolean;
Reserved : Byte;
end;
RowUpdateInfo = packed record
Figure : Pointer; //The first figure on the row
OverlapRow : Longint; //The last row that contains an item which could overlap this row
DescendRow : Longint; //The first row which has an item that descends below its position to this row
MaxHeight : Longint; //The tallest item on this row
ItemIndex : Word; //The first item on the row
end;
PItemInfo = ^ItemInfo;
ItemInfo = packed record
Top : Longint;
Left : Longint;
Slope : Single;
StripHeights : THandle;
CollisionMasks : THandle;
LineOfSightMasks : THandle;
LightPoints : THandle;
Width : Word;
Height : Word;
Strips : Word; //=roundup(Width/TileWidth) Strips*Height=next Items top
StripCount : Word;
Used : Boolean;
Visible : Boolean;
AutoTransparent : Boolean;
Vertical : Boolean;
end;
PItemInstanceInfo = ^ItemInstanceInfo;
ItemInstanceInfo = packed record
X : Longint;
Y : Longint;
ImageY : Word;
Slope0 : Single;
Slope1 : Single;
Slope2 : Single;
RefItem : word;
FilterID : Smallint;
XRayID : Smallint;
ImageX : Word;
Width : Word;
Height : Word;
VHeight : Word; //Height of region that may obscure objects behind it
Next : Word;
Zone : Word;
AutoTransparent : Boolean;
Visible : Boolean;
Last : Boolean;
Vertical : Boolean;
end;
ScriptInfo = packed record
Frames : Word;
FrameID : array[ 1..MaxScriptFrames ] of Word;
Name : string[ 32 ];
Multiplier : Word;
Tag : Longint;
end;
BITMAP = record
bmType : Longint;
bmWidth : Longint;
bmHeight : Longint;
bmWidthBytes : Longint;
bmPlanes : Integer;
bmBitsPixel : Integer;
bmBits : Pointer;
end;
TPixelFormat = ( pf555, pf565, pf888 );
TFlicker = ( flNone, flCandle, flTorch, flFluorescent );
TAniSpecialEffect = ( seNone, seTranslucent, seSilhouette, seInvert, seSpooky,
seFunky, seWhite, seNegative, seStrange, seAdd, seSubtract,
seMultiply );
implementation
end.
|
(*
Copyright 2016 Michael Justin
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*)
unit NOPLogger;
interface
uses
djLogAPI, SysUtils;
{$HINTS OFF}
type
TNOPLogger = class(TInterfacedObject, ILogger)
private
FName: string;
public
constructor Create(const AName: string);
procedure Debug(const AMsg: string); overload;
procedure Debug(const AFormat: string; const AArgs: array of const); overload;
procedure Debug(const AMsg: string; const AException: Exception); overload;
procedure Error(const AMsg: string); overload;
procedure Error(const AFormat: string; const AArgs: array of const); overload;
procedure Error(const AMsg: string; const AException: Exception); overload;
procedure Info(const AMsg: string); overload;
procedure Info(const AFormat: string; const AArgs: array of const); overload;
procedure Info(const AMsg: string; const AException: Exception); overload;
procedure Warn(const AMsg: string); overload;
procedure Warn(const AFormat: string; const AArgs: array of const); overload;
procedure Warn(const AMsg: string; const AException: Exception); overload;
procedure Trace(const AMsg: string); overload;
procedure Trace(const AFormat: string; const AArgs: array of const); overload;
procedure Trace(const AMsg: string; const AException: Exception); overload;
function Name: string;
function IsDebugEnabled: Boolean;
function IsErrorEnabled: Boolean;
function IsInfoEnabled: Boolean;
function IsWarnEnabled: Boolean;
function IsTraceEnabled: Boolean;
end;
TNOPLoggerFactory = class(TInterfacedObject, ILoggerFactory)
public
function GetLogger(const AName: string): ILogger;
end;
implementation
{ TNOPLogger }
constructor TNOPLogger.Create(const AName: string);
begin
FName := AName;
end;
procedure TNOPLogger.Debug(const AMsg: string);
begin
end;
procedure TNOPLogger.Debug(const AFormat: string; const AArgs: array of const);
begin
end;
procedure TNOPLogger.Debug(const AMsg: string; const AException: Exception);
begin
end;
procedure TNOPLogger.Error(const AMsg: string; const AException: Exception);
begin
end;
function TNOPLogger.Name: string;
begin
Result := FName;
end;
procedure TNOPLogger.Error(const AFormat: string; const AArgs: array of const);
begin
end;
procedure TNOPLogger.Error(const AMsg: string);
begin
end;
procedure TNOPLogger.Info(const AMsg: string; const AException: Exception);
begin
end;
function TNOPLogger.IsDebugEnabled: Boolean;
begin
Result := False;
end;
function TNOPLogger.IsErrorEnabled: Boolean;
begin
Result := False;
end;
function TNOPLogger.IsInfoEnabled: Boolean;
begin
Result := False;
end;
function TNOPLogger.IsTraceEnabled: Boolean;
begin
Result := False;
end;
function TNOPLogger.IsWarnEnabled: Boolean;
begin
Result := False;
end;
procedure TNOPLogger.Info(const AFormat: string; const AArgs: array of const);
begin
end;
procedure TNOPLogger.Info(const AMsg: string);
begin
end;
procedure TNOPLogger.Trace(const AMsg: string; const AException: Exception);
begin
end;
procedure TNOPLogger.Trace(const AFormat: string; const AArgs: array of const);
begin
end;
procedure TNOPLogger.Trace(const AMsg: string);
begin
end;
procedure TNOPLogger.Warn(const AMsg: string; const AException: Exception);
begin
end;
procedure TNOPLogger.Warn(const AFormat: string; const AArgs: array of const);
begin
end;
procedure TNOPLogger.Warn(const AMsg: string);
begin
end;
{ TNOPLoggerFactory }
function TNOPLoggerFactory.GetLogger(const AName: string): ILogger;
begin
Result := TNOPLogger.Create(AName);
end;
end.
|
{
Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit DataGrabber.FormSettings;
{ Persistable form settings. }
interface
uses
System.Classes,
Vcl.Forms,
Spring;
type
TFormSettings = class(TPersistent)
private
FOnChanged : Event<TNotifyEvent>;
FWidth : Integer;
FHeight : Integer;
FLeft : Integer;
FTop : Integer;
FFormStyle : TFormStyle;
FVSplitterPos : Integer;
FHSplitterPos : Integer;
FWindowState : TWindowState;
{$REGION 'property access methods'}
procedure SetFormStyle(const Value: TFormStyle);
procedure SetHeight(const Value: Integer);
procedure SetLeft(const Value: Integer);
procedure SetTop(const Value: Integer);
procedure SetWidth(const Value: Integer);
function GetOnChanged: IEvent<TNotifyEvent>;
procedure SetHSplitterPos(const Value: Integer);
procedure SetVSplitterPos(const Value: Integer);
procedure SetWindowState(const Value: TWindowState);
{$ENDREGION}
protected
procedure DoChanged;
public
procedure AssignTo(Dest: TPersistent); override;
procedure Assign(Source: TPersistent); override;
property OnChanged: IEvent<TNotifyEvent>
read GetOnChanged;
published
property Left: Integer
read FLeft write SetLeft;
property Top: Integer
read FTop write SetTop;
property Width: Integer
read FWidth write SetWidth;
property Height: Integer
read FHeight write SetHeight;
property FormStyle: TFormStyle
read FFormStyle write SetFormStyle;
property VSplitterPos: Integer
read FVSplitterPos write SetVSplitterPos;
property HSplitterPos: Integer
read FHSplitterPos write SetHSplitterPos;
property WindowState: TWindowState
read FWindowState write SetWindowState;
end;
implementation
{$REGION 'property access methods'}
function TFormSettings.GetOnChanged: IEvent<TNotifyEvent>;
begin
Result := FOnChanged;
end;
procedure TFormSettings.SetFormStyle(const Value: TFormStyle);
begin
if FormStyle <> Value then
begin
FFormStyle := Value;
DoChanged;
end;
end;
procedure TFormSettings.SetHeight(const Value: Integer);
begin
if Height <> Value then
begin
FHeight := Value;
DoChanged;
end;
end;
procedure TFormSettings.SetHSplitterPos(const Value: Integer);
begin
if Value <> HSplitterPos then
begin
FHSplitterPos := Value;
DoChanged;
end;
end;
procedure TFormSettings.SetLeft(const Value: Integer);
begin
if Left <> Value then
begin
FLeft := Value;
DoChanged
end;
end;
procedure TFormSettings.SetTop(const Value: Integer);
begin
if Top <> Value then
begin
FTop := Value;
DoChanged;
end;
end;
procedure TFormSettings.SetVSplitterPos(const Value: Integer);
begin
if Value <> VSplitterPos then
begin
FVSplitterPos := Value;
DoChanged;
end;
end;
procedure TFormSettings.SetWidth(const Value: Integer);
begin
if Width <> Value then
begin
FWidth := Value;
DoChanged;
end;
end;
procedure TFormSettings.SetWindowState(const Value: TWindowState);
begin
if (Value <> WindowState) and (Value <> wsMinimized) then
begin
FWindowState := Value;
DoChanged;
end;
end;
{$ENDREGION}
{$REGION 'protected methods'}
procedure TFormSettings.DoChanged;
begin
FOnChanged.Invoke(Self);
end;
{$ENDREGION}
{$REGION 'public methods'}
procedure TFormSettings.Assign(Source: TPersistent);
var
Form : TForm;
begin
if Source is TForm then
begin
Form := TForm(Source);
Left := Form.Left;
Top := Form.Top;
Width := Form.Width;
Height := Form.Height;
FormStyle := Form.FormStyle;
WindowState := Form.WindowState;
end
else
inherited Assign(Source);
end;
procedure TFormSettings.AssignTo(Dest: TPersistent);
var
Form : TForm;
begin
if Dest is TForm then
begin
Form := TForm(Dest);
Form.Left := Left;
Form.Top := Top;
Form.Width := Width;
Form.Height := Height;
Form.FormStyle := FormStyle;
Form.WindowState := WindowState;
end
else
inherited AssignTo(Dest);
end;
{$ENDREGION}
initialization
RegisterClass(TFormSettings);
end.
|
unit unClientUpdateThread;
interface
uses
System.Classes;
type
TUpdateClientThread = class(TThread)
private
FURI :string;
protected
procedure Execute; override;
public
property URI :string read FURI write FURI;
end;
implementation
uses
unUpdateClient;
{
Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TUpdateClientThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
or
Synchronize(
procedure
begin
Form1.Caption := 'Updated in thread via an anonymous method'
end
)
);
where an anonymous method is passed.
Similarly, the developer can call the Queue method with similar parameters as
above, instead passing another TThread class as the first parameter, putting
the calling thread in a queue with the other thread.
}
{ TUpdateClientThread }
procedure TUpdateClientThread.Execute;
var
Client :TUpdateClient;
begin
NameThreadForDebugging('UpdateClientThread');
{ Place thread code here }
while not Terminated do
begin
Client := TUpdateClient.Create(nil);
try
Client.URI := FURI;
Client.CheckForUpdates;
finally
Client.Free;
end;
end;
end;
end.
|
unit Messanger;
interface
uses SysUtils, Windows;
type
TMessage = record
msg : cardinal;
case integer of
0 : (wparam1, wparam2, wparam3, wparam4 : word);
1 : (iparam1, iparam2 : cardinal);
2 : (i64param1 : int64);
end;
TProccesMsgFunc = procedure(var Msg: TMessage) of object;
TAddress = TProccesMsgFunc;
procedure SendMsg(ToAddress : TAddress; Message : Cardinal; l,r: integer);
procedure StopMessenger();
implementation
uses uLogging, Classes;
{ TMessanger }
type
PMessageQueue = ^TMessageQueue;
TMessageQueue = record
Child : PMessageQueue;
ToAddr : TAddress;
Msg : TMessage;
end;
TThreadParams = record
terminate : Boolean;
Msg : TMessageQueue;
end;
TTHreadFunc = function(ThParams : pointer): integer;stdcall;
TMessanger = class(TThread)
strict private
queuelen : integer;
Head,
Tail : PMessageQueue;
public
procedure Execute(); override;
procedure Put(ToAddress : TAddress; const Msg : TMessage);
function Accept(out NextMsg: TMessageQueue): boolean;
constructor Create();
destructor Destroy; override;
end;
var vMessanger : TMessanger;
Params : TThreadParams;
event : cardinal = 0;
procedure StopMessenger();
begin
FreeAndNil(vMessanger);
Logger.Logg(['Messanger destroyed']);
end;
procedure SendMsg(ToAddress : TAddress; Message : Cardinal; l,r: integer);
var Msg: TMessage;
begin
if vMessanger = nil then
begin
Logger.Logg(['Send Msg Fail Messanger not Assigned. Msg= ', Message]);
exit;
end;
Msg.msg := Message;
Msg.iparam1 := l;
Msg.iparam2 := r;
vMessanger.Put(ToAddress, Msg);
end;
procedure TMessanger.Put(ToAddress: TAddress; const Msg: TMessage);
begin
if Tail = nil then
begin
Tail := AllocMem(sizeof(TMessageQueue));
Head := Tail;
Tail.ToAddr := ToAddress;
Tail.Msg := Msg
end
else begin
Tail.Child := AllocMem(sizeof(TMessageQueue));
Tail.Child.ToAddr := ToAddress;
Tail.Child.Msg := Msg;
Tail := Tail.Child;
end;
inc(queuelen);
SetEvent(Event);
end;
function TMessanger.Accept(out NextMsg: TMessageQueue): boolean;
var t: PMessageQueue;
begin
if Head = nil then exit(false);
NextMsg := Head^;
t := Head;
Head := Head.Child;
if t = Tail then Tail := nil;
FreeMem(t);
dec(queuelen);
Result := true;
end;
procedure TMessanger.Execute();
begin
while not Params.terminate do
begin
WaitForSingleObject(event, INFINITE);
while Assigned(vMessanger) and vMessanger.Accept(Params.Msg) do
if Assigned(Params.Msg.ToAddr) then
begin
Synchronize(procedure begin Params.Msg.ToAddr(Params.Msg.Msg) end);
end;
end;
end;
constructor TMessanger.Create;
begin
Head := nil;
Tail := nil;
Params.terminate := false;
Event := CreateEvent(nil, false, false, 'EvntMsg');
if Event = 0 then
begin
Logger.Logg(['Event create error ', GetLastError]);
exit;
end;
inherited Create(false);
end;
destructor TMessanger.Destroy;
begin
Params.terminate := true;
SetEvent(Event);
CloseHandle(Event);
while Head <> nil do
begin
FreeMem(Head);
Head := Head.Child;
end;
end;
initialization
vMessanger := TMessanger.Create();
end.
|
unit uNotifyEventDispatcher;
interface
uses System.Classes, System.SysUtils;
type
TNotifyEventDispatcher = class(TComponent)
protected
FClosure: TProc<TObject>;
procedure OnNotifyEvent(Sender: TObject);
public
class function Create(Owner: TComponent; Closure: TProc<TObject>): TNotifyEvent; overload;
function Attach(Closure: TProc<TObject>): TNotifyEvent;
end;
implementation
class function TNotifyEventDispatcher.Create(Owner: TComponent; Closure: TProc<TObject>): TNotifyEvent;
begin
Result := TNotifyEventDispatcher.Create(Owner).Attach(Closure)
end;
function TNotifyEventDispatcher.Attach(Closure: TProc<TObject>): TNotifyEvent;
begin
FClosure := Closure;
Result := Self.OnNotifyEvent
end;
procedure TNotifyEventDispatcher.OnNotifyEvent(Sender: TObject);
begin
if Assigned(FClosure) then
FClosure(Sender)
end;
end.
|
unit DevApp.Utils;
interface
uses PascalCoin.RPC.Interfaces, System.Classes, System.SysUtils;
Type
TDevAppUtils = Class
public
class procedure AccountInfo(AAccount: IPascalCoinAccount; Strings: TStrings;
const ExcludePubKey: Boolean = True); static;
class procedure BlockInfo(ABlock: IPascalCoinBlock; Strings: TStrings); static;
class procedure OperationInfo(AOp: IPascalCoinOperation; Strings: TStrings);
static;
class function FormatAsTimeToGo(const ADate: TDateTime): string; static;
End;
implementation
uses System.DateUtils, System.Rtti;
const
bool_array: Array[Boolean] of String = ('False', 'True');
{ TDevAppUtils }
class procedure TDevAppUtils.AccountInfo(AAccount: IPascalCoinAccount; Strings: TStrings; const ExcludePubKey: Boolean = True);
begin
Strings.Add('Account: ' + AAccount.account.ToString);
Strings.Add('Name: ' + AAccount.Name);
if Not ExcludePubkey then
Strings.Add('enc_pubkey: ' + AAccount.enc_pubkey);
Strings.Add('balance: ' + FormatFloat('#,000.0000', AAccount.balance));
Strings.Add('balance_s: ' + AAccount.balance_s);
Strings.Add('n_operation: ' + AAccount.n_operation.ToString);
Strings.Add('updated_b: ' + AAccount.updated_b.ToString);
Strings.Add('updated_b_active_mode: ' + AAccount.updated_b_active_mode.ToString);
Strings.Add('updated_b_passive_mode: ' + AAccount.updated_b_passive_mode.ToString);
Strings.Add('state: ' + AAccount.state);
Strings.Add('locked_until_block: ' + AAccount.locked_until_block.ToString);
Strings.Add('price: ' + FormatFloat('#,000.0000', AAccount.price));
Strings.Add('seller_account: ' + AAccount.seller_account.ToString);
Strings.Add('private_sale: ' + AAccount.private_sale.ToString(True));
Strings.Add('new_enc_pubkey: ' + AAccount.new_enc_pubkey);
Strings.Add('account_type: ' + AAccount.account_type.ToString);
Strings.Add('Seal: ' + AAccount.Seal);
Strings.Add('Data: ' + AAccount.Data); //TEncoding.Unicode.GetString(AAccount.Data));
end;
class procedure TDevAppUtils.BlockInfo(ABlock: IPascalCoinBlock; Strings: TStrings);
begin
Strings.AddPair('Block', ABlock.block.ToString);
Strings.AddPair('enc_pubkey', ABlock.enc_pubkey);
Strings.AddPair('reward', CurrToStr(ABlock.reward));
Strings.AddPair('reward_s', ABlock.reward_s);
Strings.AddPair('fee', CurrToStr(ABlock.fee));
Strings.AddPair('fee_s', ABlock.fee_s);
Strings.AddPair('ver', ABlock.ver.ToString);
Strings.AddPair('ver_a', ABlock.ver_a.ToString);
Strings.AddPair('timestamp', ABlock.timestamp.ToString + ' (' +
FormatDateTime('dd/mm/yyyy hh:nn:ss:zz', ABlock.TimeStampAsDateTime) + ')');
Strings.AddPair('target', ABlock.target.ToString);
Strings.AddPair('nonce', ABlock.nonce.ToString);
Strings.AddPair('payload', ABlock.payload);
Strings.AddPair('sbh', ABlock.sbh);
Strings.AddPair('oph', ABlock.oph);
Strings.AddPair('pow', ABlock.pow);
Strings.AddPair('operations', ABlock.operations.ToString);
Strings.AddPair('maturation', ABlock.maturation.ToString);
Strings.AddPair('hashratekhs', ABlock.hashratekhs.ToString);
end;
class function TDevAppUtils.FormatAsTimeToGo(const ADate: TDateTime): string;
var y,m,d,h,n,s,z: word;
r: string;
begin
r := '';
y := 0;
m := 0;
d := 0;
h := 0;
n := 0;
s := 0;
z := 0;
if ADate >= 1 then
DecodeDateTime(ADate + 1,y,m,d,h,n,s,z)
else
DecodeTime(ADate, h,n,s,z);
y := y - 1900;
if y > 0 then
r := y.ToString + ' years ';
if m > 0 then
begin
r := r + m.ToString + 'mths ';
if y > 0 then
Exit(r.Trim);
end;
if d > 0 then
begin
r := r + d.ToString+ ' days ';
if m > 0 then
Exit(r.Trim);
end;
if h > 0 then
begin
r := r + h.ToString + ' hours ';
if d > 0 then
exit(r.Trim);
end;
if n > 0 then
begin
r := r + n.ToString + ' mins ';
if h > 0 then
exit(r.Trim);
end;
result := '!!!!!!!!';
end;
class procedure TDevAppUtils.OperationInfo(AOp: IPascalCoinOperation; Strings: TStrings);
Var I: Integer;
begin
Strings.AddPair('valid', bool_array[AOp.Valid]);
Strings.AddPair('errors', AOp.Errors);
Strings.AddPair('block', AOp.Block.ToString);
Strings.AddPair('time', AOp.Time.ToString);
Strings.AddPair('opblock', AOp.Opblock.ToString);
Strings.AddPair('maturation', AOp.Maturation.ToString);
Strings.AddPair('optype', AOp.Optype.ToString);
Strings.AddPair('OperationType', TRttiEnumerationType.GetName<TOperationType>(AOp.OperationType));
Strings.AddPair('optxt', AOp.Optxt);
Strings.AddPair('account', AOp.Account.ToString);
Strings.AddPair('amount', CurrToStr(AOp.Amount));
Strings.AddPair('fee', CurrToStr(AOp.Fee));
Strings.AddPair('balance', CurrToStr(AOp.Balance));
Strings.AddPair('sender_account', AOp.Sender_account.ToString);
Strings.AddPair('dest_account', AOp.Dest_account.ToString);
Strings.AddPair('enc_pubkey', AOp.Enc_PubKey);
Strings.AddPair('ophash', AOp.Ophash);
Strings.AddPair('old_ophash', AOp.Old_ophash);
Strings.AddPair('subtype', AOp.Subtype);
Strings.AddPair('signer_account', AOp.Signer_account.ToString);
Strings.AddPair('n_operation', AOp.N_Operation.ToString);
Strings.AddPair('payload', AOp.Payload);
Strings.AddPair('enc_pubkey', AOp.Enc_PubKey);
if AOp.SendersCount = 0 then
Strings.AddPair('Senders', '0')
else
begin
Strings.AddPair('SENDERS', AOp.SendersCount.ToString);
for I := 0 to AOp.SendersCount - 1 do
begin
Strings.AddPair(' ' + I.ToString + ': ' + 'account', AOp.sender[I].Account.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'n_operation', AOp.sender[I].N_Operation.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'amount', CurrToStr(AOp.sender[I].Amount));
Strings.AddPair(' ' + I.ToString + ': ' + 'amount_s', AOp.sender[I].Amount_s);
Strings.AddPair(' ' + I.ToString + ': ' + 'payload', AOp.sender[I].Payload);
Strings.AddPair(' ' + I.ToString + ': ' + 'payloadtype', AOp.sender[I].PayloadType.ToString);
Strings.Add('');
end;
end;
if AOp.ReceiversCount= 0 then
Strings.AddPair('Receivers', '0')
else
begin
Strings.AddPair('RECEIVERS', AOp.SendersCount.ToString);
for I := 0 to AOp.ReceiversCount - 1 do
begin
Strings.AddPair(' ' + I.ToString + ': ' + 'account', AOp.receiver[I].Account.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'amount', CurrToStr(AOp.receiver[I].Amount));
Strings.AddPair(' ' + I.ToString + ': ' + 'amount_s', AOp.receiver[I].Amount_s);
Strings.AddPair(' ' + I.ToString + ': ' + 'payload', AOp.receiver[I].Payload);
Strings.AddPair(' ' + I.ToString + ': ' + 'payloadtype', AOp.receiver[I].PayloadType.ToString);
Strings.Add('');
end;
end;
if AOp.ChangersCount = 0 then
Strings.AddPair('Changers', '0')
else
begin
Strings.AddPair('CHANGERS', AOp.ChangersCount.ToString);
for I := 0 to AOp.ChangersCount - 1 do
begin
Strings.AddPair(' ' + I.ToString + ': ' + 'account', AOp.changers[I].Account.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'n_operation', AOp.changers[I].N_Operation.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'new_enc_pubkey', AOp.changers[I].new_enc_pubkey);
Strings.AddPair(' ' + I.ToString + ': ' + 'new_type', AOp.changers[I].new_type);
Strings.AddPair(' ' + I.ToString + ': ' + 'seller_account', AOp.changers[I].seller_account.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'amount', CurrToStr(AOp.changers[I].account_price));
Strings.AddPair(' ' + I.ToString + ': ' + 'locker_until_block', AOp.changers[I].locked_until_block.ToString);
Strings.AddPair(' ' + I.ToString + ': ' + 'fee', CurrToStr(AOp.changers[I].fee));
Strings.Add('');
end;
end;
end;
end.
|
unit wakaru.identifiable;
{$mode delphi}
interface
uses
Classes,
SysUtils,
wakaru.types;
type
{ TIdentifiableImpl }
(*
base implementation of an Identifiable
*)
TIdentifiableImpl = class(TInterfacedObject, IIdentifiable)
strict private
FID,
FTag : String;
private
function GetID: String;
function GetTag: String;
procedure SetTag(const AValue: String);
strict protected
(*
initializes the ID string, can be overridden by children
*)
function DoInitID : String; virtual;
public
property ID : String read GetID;
property Tag : String read GetTag write SetTag;
constructor Create; virtual;
destructor Destroy; override;
end;
implementation
{ TIdentifiableImpl }
function TIdentifiableImpl.GetID: String;
begin
Result := FID;
end;
function TIdentifiableImpl.GetTag: String;
begin
Result := FTag;
end;
procedure TIdentifiableImpl.SetTag(const AValue: String);
begin
FTag := AValue;
end;
function TIdentifiableImpl.DoInitID: String;
begin
Result := TGuid.NewGuid.ToString();
end;
constructor TIdentifiableImpl.Create;
begin
FID := DoInitID;
end;
destructor TIdentifiableImpl.Destroy;
begin
inherited Destroy;
end;
end.
|
unit SESCam;
{ ================================================================================
SESCam - Camera Acquisition Component (c) J. Dempster, University of Strathclyde
31/7/01 Started
17/06/03 ....
8/7/03 ...... Pixel width and lens magnification properties added
29/7/03 ..... PixelDepth property added
1/12/04 ..... Andor cameras added
8/07/05 ..... Hamamatsu C4880/ITEX board updated
05/06 ....... QImaging support added
11/7/6 ...... Hamamatsu DCAM-SDK support added
24/7/6 ...... Pixel width now scales correctly with bin factor changes
14-9-06 ANdor_CheckROIBoundaries added to ensure that Andor circular buffer size is always even
15-10-6 ..... IMAQ for 1394 updated to work with V2.02
14-2-07 ..... PVCAMSession record added
Virtual chip PentaMax options removed.
Special I-PentaMax camera added (has memory buffer limit)
14-9-07 ..... PCO SensiCam added
25-1-08 ..... National Instrument IMAQ library support added (for analog video boards)
IsLSM function added to report whether a camera index is a
laser scanning microscope
07-04-08 .... Error which caused misallocation of frame buffer when BINFACTOR
changed fixed (causing memory alloc errors with Andor 1024x1024 camera)
05.08.08 .... CameraTemperatureSetPoint property added
(currently only functions for Andor cameras)
21/01/09 AdditionalReadoutTime property added. Adds extra readout time during
triggered exposures which is subtracted from exposure time.
(Not supported by Andor and IMAQ)
15/04/09 .... JD CCD imaging area checks no longer take place when image area set
Now only when .framewidth and .frameheight properties requested
and when NumFramesInBuffer set.
16/04/09 .... FNumBytesPerFrameBuffer now always a multiple of Fnumbytesperframe
Default CCD area limits check added to AllocateFrameBuffer
19/05/09 .... JD .CameraFanOn and .CameraCoolingOn properties added
21/05/09 .... JD X8 bin factor added for sensicam cameras
07/09/09 .... JD .CameraRestartRequired property added. Set = TRUE when a change
to a property (e.g. .DisableEMCCD) requires the camera to be restarted
Hamamatsu Image-EM EMCDD can be disabled
20/01/10 .... JD Error in AllocateBuffer for ITEX_C4880_10,ITEX_C4880_12 which
caused stack overflow when camera opened fixed
22/02/10 .... JD National Instrument IMAQDX library support added
06/09/10 .... JD National Instrument IMAQDX library support now working
07/09/10 .... JD .CCDClearPreExposure property added (functional only for PVCAM)
29-10-10 .... JD Andor cameras readout amplifier and A/D converter channel can now be selected
01.02.11 .... JD .CCDPostExposureReadout property added. Exposure time in ext. trigger mode can
now be shortened to account for post-exposure readout in cameras which do not support
overlapped readout mode. (Current only supported in PVCAM)
14/07/11 .... JD Adding DT Open Layers support
30/07/12 .... JD IMAQDX_SetVideoMode removed from SetCameraADC to avoid frame size being set
incorrectly on program start for IMAQdx cameras
02/05/13 .... JD Andor SDK3 camera support added
30-10-13 .... JD IMAQ_CheckFrameInterval() changed. Camera frame interval now set to fixed video
interval (1/25, 1/30 sec) depending upon RS170 or CCIR camera (IMAQ_CheckFrameInterval()
.ShortenExposureBy property added Exposure time for externally triggered exposures
now shortened by the larger of .ShortenExposureBy or .AdditionalReadoutTime
07-11-13 .... JD Andor SDK2 Readout preamp gain and vertical shift speed can now be set by user
09-12-13 .... JD ITEX.ConfigFileName now ensured to point at program directory (rather than default)
C4880 no longered opened if frame grabber not available.
16.12.13 JD .StartCapture Now returns False if unable to allocate enough frame buffer memory
EOutOfMemory exception now trapped and AllocateFrameBuffer returns false
03.04.14 JD PostExposureReadout flag now force on if camera only supports that mode. (CoolSnap HQ2)
09.07.14 JD Binfactor division by zero trapped in GetPixelWidth()
20.08.14 JD Cam1.DefaultReadoutSpeed added
22.08.14 JD Support for Thorlabs DCx added and .NumPixelShiftFrames added
Support for Vieworks VA-29MC-5M camera with CameraLink interface added
14.05.15 JD .DisableExposureIntervalLimit property added.
FrameInterval checking against readout time can be disabled.
03.05.17 JD Thorlabs: FReadoutSpeed now preserved when camera re-opened to avoid
being reset to minimum. Note this fix may be required for other cameras
15.06.17 JD .FanMode, .CoolerOn .Temperature and .SpotNoiseReduction support added to DCAM cameras
31.07.17 JD .SpotNoiseReduction support removed
03.08.17 JD .CCDXShift and .CCDYShift added setting of CCD X,Y stage position for VNP-29MC camera
15.08.17 JD .SnapImage added (acquires a single image)
06.11.17 JD .CCDTapOffsetLT etc. CCD tap black offset adjustment properties added
18.01.18 JD .LIGHTSPEEDMODE added (enables lightspeed mode of Evolve Delta
30.07.18 JD Support for PCO cameras added
31.10.18 JD Support iDS uEYE cameras (based on ThorlabsUnit.pas added
14.11.18 JD IDSuEYE and Thorlabs now updates FFrameCounter with frame count since StartCapture()
27.03.19 JD DCAM FrameCount property now returns no. of frames captured
================================================================================ }
{$OPTIMIZATION OFF}
{$POINTERMATH ON}
{$R 'sescam.dcr'}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, itex, imaq1394,
pixelflyunit, SensiCamUnit, HamDCAMUnit, Math, AndorUnit,
QCAMUnit, pvcam, imaqunit, nimaqdxunit, strutils, DTOpenLayersUnit, AndorSDK3Unit, ThorlabsUnit, PCOUnit, IDSuEYEUnit, maths ;
const
{ Interface cards supported }
NoCamera8 = 0 ;
NoCamera16 = 1 ;
ITEX_CCIR = 2 ;
ITEX_C4880_10 = 3 ;
ITEX_C4880_12 = 4 ;
RS_PVCAM = 5 ;
RS_PVCAM_PENTAMAX = 6 ;
DTOL = 7 ;
AndorSDK3 = 8 ;
RS_PVCAM_VC68 = 9 ;
RS_PVCAM_VC56 = 10 ;
RS_PVCAM_VC51 = 11 ;
RS_PVCAM_VC41 = 12 ;
RS_PVCAM_VC38 = 13 ;
RS_PVCAM_VC32 = 14 ;
IMAQ_1394 = 15 ;
PIXELFLY = 16 ;
BioRad = 17 ;
Andor = 18 ;
UltimaLSM = 19 ;
QCAM = 20 ;
DCAM = 21 ;
SENSICAM = 22 ; // added by M.Ascherl 14.sept.2007
IMAQ = 23 ;
IMAQDX = 24 ;
Thorlabs = 25 ;
PCOAPI = 26 ;
IDSuEYE = 27 ;
NumLabInterfaceTypes = 28 ; // up from 22; M.Ascherl
// Frame capture trigger modes
CamFreeRun = 0 ;
CamExtTrigger = 1 ;
CamBulbMode = 2 ;
// Trigger types
CamExposureTrigger = 0 ; // External trigger starts exposure
CamReadoutTrigger = 1 ; // External trigger starts readout
type
TBigByteArray = Array[0..$1FFFFFFF] of Byte ;
pBigByteArray = ^TBigByteArray ;
TBigWordArray = Array[0..$1FFFFFFF] of Word ;
pBigWordArray = ^TBigWordArray ;
TSESCam = class(TComponent)
private
{ Private declarations }
FCameraType : Integer ; // Type of lab. interface hardware
FNumCameras : Integer ; // No. of cameras detected
FCameraName : string ; // Name of interface
FCameraModel : string ; // Model
FSelectedCamera : Integer ; // No. of selected camera
FCameraMode : Integer ; // Camera video mode
FCameraADC : Integer ; // Camera A/D converter
FComPortUsed : Boolean ; // Camera control port in use
FComPort : Integer ; // Camera control port
FCCDType : string ; // Type CCD in camera
FCCDClearPreExposure : Boolean ; // Clear CCD before exposure
FCCDPostExposureReadout : Boolean ; // CCD readout is after exposure
FCCDXShift : Double ; // CCD shift (fraction of pixel size)
FCCDYShift : Double ; // CCD shift (fraction of pixel size)
FCameraAvailable : Boolean ; // Camera is available for use
FCameraActive : Boolean ; // Camera is in use
FFrameWidthMax : Integer ; // Maximum width of image frame (pixels)
FFrameHeightMax : Integer ; // Maximum height of image frame (pixels)
FFrameLeft : Integer ; // Left edge of image frame in use (pixels)
FFrameRight : Integer ; // Right edge of image frame in use (pixels)
FFrameTop : Integer ; // Top edge of image frame in use (pixels)
FFrameBottom : Integer ; // Bottom edge of image frame in use (pixels)
FBinFactor : Integer ; // Pixel binning factor
FBinFactorMax : Integer ; // Pixel binning factor
FFrameWidth : Integer ; // Width of image frame in use (binned pixels)
FFrameHeight : Integer ; // Height of image frame in use (binned pixels)
FCCDRegionReadoutAvailable : Boolean ; // CCD sub-region readout supported
FFrameInterval : Double ; // Duration of selected frame time interval (s)
FFrameIntervalMin : Single ; // Min. time interval between frames (s)
FFrameIntervalMax : Single ; // Max. time interval between frames (s)
//FExposureTime : Double ; // Camera exposure time (s)
//FFrameReadoutTime : Double ;
FReadoutSpeed : Integer ; // Frame readout speed
FReadoutTime : Double ; // Time to read out frame (s)
FAmpGain : Integer ; // Camera amplifier gain
FTriggerMode : Integer ; // Frame capture trigger mode
FTriggerType : Integer ; // Camera trigger type
FAdditionalReadoutTime : Double ; // Additional readout time
FShortenExposureBy : Double ; // Shorten exposure
FDisableExposureIntervalLimit : Boolean ;
FPixeldepth : Integer ; // No. of bits per pixel
FGreyLevelMin : Integer ; // Minimum pixel grey level value
FGreyLevelMax : Integer ; // Maximum pixel grey level value
FNumBytesPerPixel : Integer ; // No. of storage bytes per pixel
FNumComponentsPerPixel : Integer ; // No. of colour components per pixel
FMaxComponentsPerPixel : Integer ; // Max. no. of colour components per pixel
FMonochromeImage : Boolean ; // TRUE = Extract monochrome image from colour sources
FLensMagnification : Single ; // Camera lens magification factor
FPixelWidth : Single ; // Pixel width
FPixelUnits : String ; // Pixel width units
FNumFramesInBuffer : Integer ; // Frame buffer capacity (frames)
FNumBytesInFrameBuffer : Integer ; // No. of bytes in frame buffer
FNumBytesPerFrame : Integer ; // No. of bytes per frame
PFrameBuffer : Pointer ;//PByteArray ; // Pointer to ring buffer to store acquired frames
PAllocatedFrameBuffer : Pointer ;//: PByteArray ;
FFrameCount : Cardinal ;
CameraInfo : TStringList ;
CameraGainList : TStringList ;
CameraReadoutSpeedList : TStringList ;
CameraModeList : TStringList ;
CameraADCList : TStringList ;
ADCGainList : TStringList ;
CCDVerticalShiftSpeedList : TStringList ;
FTemperature : Single ;
FTemperatureSetPoint : Single ;
FCameraCoolingOn : Boolean ; // TRUE = Camera peltier cooling on
FCameraFanMode : Integer ; // 0=Off, 1=low, 2=high
FDisableEMCCD : Boolean ; // TRUE=EMCDD function disabled
FCameraRestartRequired : Boolean ; // TRUE=restart of camera required
FADCGain : Integer ; // A/D gain index value
FCCDVerticalShiftSpeed : Integer ; // Vertical CCD line shift speed index
FNumPixelShiftFrames : Integer ; // No. of pixel shifted frames
FCCDTapOffsetLT : Cardinal ; // Top-left tap DC offset
FCCDTapOffsetRT : Cardinal ; // Top-right tap DC offset
FCCDTapOffsetLB : Cardinal ; // Bottom-left tap DC offset
FCCDTapOffsetRB : Cardinal ; // Bottom-right tap DC offset
FLightSpeedMode : Boolean ; // Lightspeed mode on/off flag (supported only by Evolve 512 Delta)
ImageAreaChanged : Boolean ; // TRUE = image area has been changed
ITEX : TITEX ;
// PVCAM fields
PVCAMSession : TPVCAMSession ;
//FFrameBufferHandle : THandle ;
// IMAQ 1394 fields
Session : TIMAQ1394Session ;
FrameCounter : Integer ;
// Pixelfly fields
PixelFlySession : TPixelFlySession ;
// SensiCam fields
SensiCamSession : TSensiCamSession;
// Andor fields
AndorSession : TAndorSession ;
AndorSDK3Session : TAndorSDK3Session ;
// QImaging
QCAMSession : TQCAMSession ;
// Hamamatsu DCAM-API
DCAMSession : TDCAMAPISession ;
// National Instruments (IMAQ) session
IMAQSession : TIMAQSession ;
// National Instruments (IMAQDX) session
IMAQDXSession : TIMAQDXSession ;
// Data Translation Open Layers session
DTOLSession : TDTOLSession ;
// Thorlabs cameras session
ThorlabsSession : TThorlabsSession ;
PCOAPISession : TPCOAPISession ;
IDSSession : TIDSSession ;
function AllocateFrameBuffer : Boolean ;
procedure DeallocateFrameBuffer ;
procedure SetFrameLeft( Value : Integer ) ;
procedure SetFrameRight( Value : Integer ) ;
procedure SetFrameTop( Value : Integer ) ;
procedure SetFrameBottom( Value : Integer ) ;
procedure SetBinFactor( Value : Integer ) ;
function GetFrameWidth : Integer ;
function GetFrameHeight : Integer ;
function GetNumPixelsPerFrame : Integer ;
function GetNumComponentsPerFrame : Integer ;
function GetNumBytesPerFrame : Integer ;
procedure SetReadOutSpeed( Value : Integer ) ;
function GetDefaultReadoutSpeed : Integer ;
procedure SetNumFramesInBuffer( Value : Integer ) ;
function GetMaxFramesInBuffer : Integer ;
procedure SetFrameInterval( Value : Double ) ;
function GetReadOutTime : Double ;
function GetExposureTime : Double ;
function GetPixelWidth : Single ;
function LimitTo(
Value : Integer ;
LoLimit : Integer ;
HiLimit : Integer ) : Integer ;
procedure SetTemperature( Value : Single ) ;
procedure SetCameraCoolingOn( Value : Boolean ) ;
procedure SetCameraFanMode( Value : Integer ) ;
procedure SetDisableEMCCD( Value : Boolean ) ;
procedure SetCameraMode( Value : Integer ) ;
procedure SetCameraADC( Value : Integer ) ;
procedure SetADCGain( Value : Integer ) ;
procedure SetCCDVerticalShiftSpeed( Value : Integer ) ;
procedure SetCCDPostExposureReadout( Value : Boolean ) ;
procedure SetMonochromeImage( Value : Boolean ) ;
procedure SetCCDXShift( Value : Double );
procedure SetCCDYShift( Value : Double );
procedure SetLightSpeedMode( Value : Boolean ) ;
protected
{ Protected declarations }
public
{ Public declarations }
DebugIn : Integer ;
DebugOut : Integer ;
Constructor Create(AOwner : TComponent) ; override ;
Destructor Destroy ; override ;
procedure OpenCamera( InterfaceType : Integer ) ;
procedure CloseCamera ;
procedure ReadCamera ;
function StartCapture : Boolean ;
procedure StopCapture ;
function SnapImage : Boolean ;
procedure SoftwareTriggerCapture ;
procedure GetFrameBufferPointer( var FrameBuf : Pointer ) ;
procedure GetLatestFrameNumber( var FrameNum : Integer ) ;
function GetCameraName( Num : Integer ) : String ;
procedure GetCameraLibList( List : TStrings ) ;
procedure GetCameraTriggerModeList( List : TStrings ) ;
procedure GetCameraGainList( List : TStrings ) ;
procedure GetCameraReadoutSpeedList( List : TStrings ) ;
procedure GetCameraModeList( List : TStrings ) ;
procedure GetCameraADCList( List : TStrings ) ;
procedure GetADCGainList( List : TStrings ) ;
procedure GetCCDVerticalShiftSpeedList( List : TStrings ) ;
procedure GetCameraNameList( List : TStrings ) ;
procedure GetCameraInfo( List : TStrings ) ;
function IsLSM( iCameraType : Integer ) : Boolean ;
procedure SetCCDArea( FrameLeft : Integer ;
FrameTop : Integer ;
FrameRight : Integer ;
FrameBottom : Integer ) ;
function PauseCapture : Boolean ;
function RestartCapture : Boolean ;
published
{ Published declarations }
Property CameraType : Integer Read FCameraType ;
Property SelectedCamera : Integer read FSelectedCamera write FSelectedCamera ;
Property CameraAvailable : Boolean Read FCameraAvailable ;
Property NumCameras : Integer read FNumCameras ;
Property CameraActive : Boolean Read FCameraActive ;
Property CameraName : string read FCameraName ;
Property CameraModel : string read FCameraModel ;
Property ComPort : Integer read FComPort write FComPort ;
Property ComPortUsed : Boolean read FComPortUsed ;
Property CCDClearPreExposure : Boolean read FCCDClearPreExposure write FCCDClearPreExposure ;
Property CCDPostExposureReadout : Boolean read FCCDPostExposureReadout write SetCCDPostExposureReadout ;
Property FrameWidth : Integer Read GetFrameWidth ;
Property FrameHeight : Integer Read GetFrameHeight ;
Property FrameLeft : Integer Read FFrameLeft Write SetFrameLeft Default 0 ;
Property FrameRight : Integer Read FFrameRight Write SetFrameRight Default 511 ;
Property FrameTop : Integer Read FFrameTop Write SetFrameTop Default 0 ;
Property FrameBottom : Integer Read FFrameBottom Write SetFrameBottom Default 511 ;
Property BinFactor : Integer Read FBinFactor Write SetBinFactor Default 1 ;
Property CCDRegionReadoutAvailable : Boolean Read FCCDRegionReadoutAvailable ;
Property ReadoutSpeed : Integer Read FReadoutSpeed write SetReadoutSpeed ;
Property DefaultReadoutSpeed : Integer Read GetDEfaultReadoutSpeed ;
Property ReadoutTime : Double Read GetReadoutTime ;
Property AdditionalReadoutTime : Double
read FAdditionalReadoutTime Write FAdditionalReadoutTime ;
Property ShortenExposureBy : Double
read FShortenExposureBy Write FShortenExposureBy ;
Property FrameInterval : Double Read FFrameInterval Write SetFrameInterval ;
Property ExposureTime : Double Read GetExposureTime ;
Property PixelDepth : Integer Read FPixelDepth ;
Property GreyLevelMin : Integer Read FGreyLevelMin ;
Property GreyLevelMax : Integer Read FGreyLevelMax ;
Property TriggerMode : Integer Read FTriggerMode Write FTriggerMode ;
Property TriggerType : Integer Read FTriggerType ;
Property AmpGain : Integer Read FAmpGain Write FAmpGain ;
Property NumBytesPerPixel : Integer Read FNumBytesPerPixel ;
Property NumComponentsPerPixel : Integer Read FNumComponentsPerPixel ;
Property NumPixelsPerFrame : Integer Read GetNumPixelsPerFrame ;
Property NumComponentsPerFrame : Integer Read GetNumComponentsPerFrame ;
Property NumBytesPerFrame : Integer Read GetNumBytesPerFrame ;
Property NumFramesInBuffer : Integer Read FNumFramesInBuffer Write SetNumFramesInBuffer ;
Property MaxFramesInBuffer : Integer Read GetMaxFramesInBuffer ;
Property FrameWidthMax : Integer Read FFrameWidthMax ;
Property FrameHeightMax : Integer Read FFrameHeightMax ;
Property FrameCount : Cardinal read FFrameCount ;
Property LensMagnification : Single Read FLensMagnification Write FLensMagnification ;
Property PixelWidth : Single Read GetPixelWidth ;
Property PixelUnits : String Read FPixelUnits ;
Property CameraTemperature : Single Read FTemperature ;
Property CameraTemperatureSetPoint : Single Read FTemperatureSetPoint
Write SetTemperature ;
Property CameraCoolingOn : Boolean Read FCameraCoolingOn write SetCameraCoolingOn ;
Property CameraFanMode : Integer Read FCameraFanMode write SetCameraFanMode ;
Property DisableEMCCD : Boolean read FDisableEMCCD write SetDisableEMCCD ;
Property CameraRestartRequired : Boolean read FCameraRestartRequired ;
Property CameraMode : Integer read FCameraMode write SetCameraMode ;
Property CameraADC : Integer read FCameraADC write SetCameraADC ;
Property ADCGain : Integer read FADCGain write SetADCGain ;
Property CCDVerticalShiftSpeed : Integer read FCCDVerticalShiftSpeed write SetCCDVerticalShiftSpeed ;
Property NumPixelShiftFrames : Integer read FNumPixelShiftFrames write FNumPixelShiftFrames ;
Property DisableExposureIntervalLimit : Boolean read FDisableExposureIntervalLimit write FDisableExposureIntervalLimit ;
Property MonochromeImage : Boolean read FMonochromeImage write SetMonochromeImage ;
Property CCDXShift : Double read FCCDXShift write SetCCDXShift ;
Property CCDYShift : Double read FCCDYShift write SetCCDYShift ;
Property CCDTapOffsetLT : Cardinal read FCCDTapOffsetLT write FCCDTapOffsetLT ;
Property CCDTapOffsetRT : Cardinal read FCCDTapOffsetRT write FCCDTapOffsetRT ;
Property CCDTapOffsetLB : Cardinal read FCCDTapOffsetLB write FCCDTapOffsetLB ;
Property CCDTapOffsetRB : Cardinal read FCCDTapOffsetRB write FCCDTapOffsetRB ;
Property LightSpeedMode : Boolean read FLightSpeedMode write SetLightSpeedMode ;
end;
procedure Register;
implementation
uses hamc4880 ;
procedure Register;
begin
RegisterComponents('Samples', [TSESCam]);
end;
constructor TSESCam.Create(AOwner : TComponent) ;
{ --------------------------------------------------
Initialise component's internal objects and fields
-------------------------------------------------- }
begin
inherited Create(AOwner) ;
FCameraType := NoCamera8 ; { No Camera }
FNumCameras := 0 ; // No. of cameraS available
FCameraAvailable := False ;
FCameraActive := False ;
FComPortUsed := False ;
FComPort := 1 ;
FCameraMode := 0 ;
FCameraADC := 0 ;
FCCDType := 'Unknown' ;
FCCDClearPreExposure := False ;
FCCDPostExposureReadout := False ;
FPixelDepth := 8 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := 255 ;
FLensMagnification := 1.0 ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
FFrameWidthMax := 512 ;
FFrameWidth := FFrameWidthMax ;
FFrameHeightMax := 512 ;
FFrameHeight := FFrameHeightMax ;
FFrameCount := 0 ;
FCCDRegionReadoutAvailable := True ;
FBinFactor := 1 ;
FBinFactorMax := 64 ;
FFrameLeft := 0 ;
FFRameRight := FFrameWidthMax - 1 ;
FFrameWidth := (FFrameRight - FFrameLeft + 1) div FBinFactor ;
FFrameTop := 0 ;
FFrameBottom := FFrameHeightMax - 1 ;
FFrameHeight := (FFrameBottom - FFrameTop + 1) div FBinFactor ;
FFrameInterval := 1.0 ;
FFrameIntervalMin := 1.0 ;
FFrameIntervalMax := 1.0 ;
FNumFramesInBuffer := 20 ;
FNumBytesInFrameBuffer := 0 ;
PFrameBuffer := Nil ;
// Digital camera default parameters
FReadoutSpeed := 0 ;
FAmpGain := 0 ;
FTriggerMode := CamFreeRun ;
FTriggerType := CamExposureTrigger ;
FAdditionalReadoutTime := 0.0 ;
FShortenExposureBy := 0.0 ;
FDisableEMCCD := False ;
FCameraRestartRequired := False ;
FDisableExposureIntervalLimit := False ;
// CCD tap black level offsets
FCCDTapOffsetLT := 0 ;
FCCDTapOffsetRT := 0 ;
FCCDTapOffsetLB := 0 ;
FCCDTapOffsetRB := 0 ;
// Initialise ITEX control record
ITEX.ConfigFileName := '' ;
ITEX.PModHandle := Nil ;
ITEX.AModHandle := Nil ;
ITEX.GrabHandle := Nil ;
ITEX.FrameWidth := 0 ;
ITEX.FrameHeight := 0 ;
ITEX.SystemInitialised := False ;
IMAQDXSession.CameraOpen := False ;
// Create camera information list
CameraInfo := TStringList.Create ;
// Create camera readout speed list
CameraReadoutSpeedList := TStringList.Create ;
// List of available camera gains
CameragainList := TStringList.Create ;
// List of available camera operating modes
CameraModeList := TStringList.Create ;
CameraModeList.Add(' ') ;
// A/D converter list
CameraADCList := TStringList.Create ;
ADCGainList := TStringList.Create ;
ADCGainList.Add('X1') ;
CCDVerticalShiftSpeedList := TStringList.Create ;
CCDVerticalShiftSpeedList.Add('n/a') ;
FTemperature := 0.0 ;
FTemperatureSetPoint := -50.0 ;
FCameraCoolingOn := True ;
FCameraFanMode := 1 ; // Andor Low / DCAM On settings
FNumPixelShiftFrames := 1 ; // No. of pixel shift frames acquired
FLightSpeedMode := False ; // Light speed mode off
ImageAreaChanged := False ;
end ;
destructor TSESCam.Destroy ;
{ ------------------------------------
Tidy up when component is destroyed
----------------------------------- }
begin
// Shut down camera/frame grabber
CloseCamera ;
DeallocateFrameBuffer ;
{if PFrameBuffer <> Nil then FreeMem(PFrameBuffer) ;
PFrameBuffer := Nil ;}
CameraInfo.Free ;
CameraReadoutSpeedList.Free ;
CameraGainList.Free ;
CameraModeList.Free ;
CameraADCList.Free ;
ADCGainList.Free ;
CCDVerticalShiftSpeedList.Free ;
{ Call inherited destructor }
inherited Destroy ;
end ;
function TSESCam.GetCameraName( Num : Integer ) : String ;
{ -------------------------------------
Get name of laboratory interface unit
------------------------------------- }
begin
case Num of
NoCamera8 : Result := 'No Camera (8 bit)' ;
NoCamera16 : Result := 'No Camera (16 bit)' ;
ITEX_CCIR : Result := 'PCVISON/CCIR video' ;
ITEX_C4880_10 : Result := 'Hamamatsu C4880-81 (10 bit)' ;
ITEX_C4880_12 : Result := 'Hamamatsu C4880-81 (12 bit)' ;
RS_PVCAM : Result := 'Photometrics/Princeton PVCAM' ;
RS_PVCAM_PENTAMAX : Result := 'Princeton I-PentaMax (PVCAM)' ;
DTOL : Result := 'Data Translation Frame Grabber' ;
AndorSDK3 : Result := 'Andor SDK3 (Neo,Zyla)' ;
RS_PVCAM_VC68 : Result := 'Not in use' ;
RS_PVCAM_VC56 : Result := 'Not in use' ;
RS_PVCAM_VC41 : Result := 'Not in use' ;
RS_PVCAM_VC38 : Result := 'Not in use' ;
RS_PVCAM_VC32 : Result := 'Not in use' ;
IMAQ_1394 : Result := 'National Instruments (IMAQ-1394)' ;
PIXELFLY : Result := 'PCO Pixelfly' ;
BioRad : Result := 'BioRad Radiance/MRC 1024' ;
UltimaLSM : Result := 'Praire Technology Ultima' ;
Andor : Result := 'Andor iXon/Luca ' ;
QCAM : Result := 'QImaging QCAM-API' ;
DCAM : Result := 'Hamamatsu DCAM' ;
SENSICAM : Result := 'PCO SensiCam';
IMAQ : Result := 'National Instruments (IMAQ)' ;
IMAQDX : Result := 'National Instruments (IMAQ-DX)' ;
Thorlabs : Result := 'Thorlabs DCx Cameras' ;
PCOAPI : Result := 'PCO Cameras' ;
IDSuEYE : Result := 'IDS uEYE Cameras' ;
end ;
end ;
procedure TSESCam.GetCameraLibList( List : TStrings ) ;
// -------------------------------------------
// Get list of available camera/interface list
// -------------------------------------------
var
i : Integer ;
begin
List.Clear ;
for i := 0 to NumLabInterfaceTypes-1 do
List.Add(GetCameraName( i )) ;
end ;
procedure TSESCam.GetCameraTriggerModeList( List : TStrings ) ;
// -------------------------------------------
// Get list of available camera triggering modes
// -------------------------------------------
begin
List.Clear ;
List.Add( 'Free Run' ) ;
List.Add( 'Ext. Trigger' ) ;
List.Add( 'Ext. Start' ) ;
end ;
procedure TSESCam.OpenCamera(
InterfaceType : Integer
) ;
{ ------------------------------------------------
Set type of camera/frame grabber hardware in use
------------------------------------------------ }
var
ReadoutRate : Integer ;
i : Integer ;
begin
{ Initialise lab. interface hardware }
FCameraType := InterfaceType ;
FCameraModel := 'Unknown' ;
FCameraMode := 0 ;
FNumCameras := 0 ;
FComPortUsed := False ;
// default settings
FNumBytesPerPixel := 1 ;
FNumComponentsPerPixel := 1 ;
FMaxComponentsPerPixel := 1 ;
FMonochromeImage := false ;
FPixelDepth := 8 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := $FF ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
FTriggerType := CamExposureTrigger ;
FADCGain := 0 ; // A/D gain index value
FCCDVerticalShiftSpeed := -1 ; // Vertical CCD line shift speed index
CameraGainList.Clear ;
CameraGainList.Add( '1 ' ) ;
CameraReadoutSpeedList.Clear ;
CameraReadoutSpeedList.Add( ' n/a ' ) ;
CameraModeList.Clear ;
CameraModeList.Add( ' n/a ' ) ;
CameraADCList.Clear ;
CameraADCList.Add( ' n/a ' ) ;
case FCameraType of
NoCamera8 : begin
FCameraName := 'No Camera' ;
FNumBytesPerPixel := 1 ;
FNumComponentsPerPixel := 1 ;
FMaxComponentsPerPixel := 1 ;
FPixelDepth := 8 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := $FF ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
FTriggerType := CamExposureTrigger ;
FNumCameras := 1 ;
end ;
NoCamera16 : begin
FCameraName := 'No Camera' ;
FNumBytesPerPixel := 2 ;
FNumComponentsPerPixel := 1 ;
FMaxComponentsPerPixel := 1 ;
FPixelDepth := 16 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := $FFFF ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
FTriggerType := CamExposureTrigger ;
FNumCameras := 1 ;
end ;
ITEX_CCIR : begin
FCameraName := GetCameraName( ITEX_CCIR ) ;
CameraInfo.Clear ;
CameraInfo.Add( 'Camera Type: ' + FCameraName ) ;
ITEX.ConfigFileName := ExtractFilePath(ParamStr(0)) + 'ccir.cnf' ;
CameraInfo.Add( 'Config file: ' + ITEX.ConfigFileName ) ;
ITEX.HostTransferPossible := False ;
FNumBytesPerPixel := 1 ;
FCameraAvailable := ITEX_OpenFrameGrabber(
ITEX,
CameraInfo,
FNumBytesPerPixel,
True ) ;
FFrameWidthMax := ITEX.FrameWidth ;
FFrameHeightMax := ITEX.FrameHeight ;
FPixelDepth := 8 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := 255 ;
FBinFactor := 1 ;
FBinFactorMax := 1 ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
// Fixed frame interval
FFrameInterval := 1.0/25.0 ;
FFrameIntervalMin := FFrameInterval ;
FFrameIntervalMax := FFrameInterval ;
FReadoutSpeed := 0 ;
FTriggerType := CamExposureTrigger ;
FNumCameras := 1 ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
// Open Hamamatsu C4880 with ITEX RS422 frame grabber
FCameraName := GetCameraName( FCameraType ) ;
ITEX.ConfigFileName := ExtractFilePath(ParamStr(0)) + 'hamc4880.cnf' ;
CameraInfo.Add( 'Config file: ' + ITEX.ConfigFileName ) ;
ITEX.HostTransferPossible := False ;
FComPortUsed := True ;
FNumBytesPerPixel := 2 ;
// Initialise frame grabber
FCameraAvailable := ITEX_OpenFrameGrabber(
ITEX,
CameraInfo,
FNumBytesPerPixel,
False ) ;
FFrameWidthMax := ITEX.FrameWidth ;
FFrameHeightMax := ITEX.FrameHeight ;
FBinFactorMax := 16 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
if FCameraType = ITEX_C4880_10 then begin
FPixelDepth := 16 ;
FGreyLevelMax := (32768*2) -1;
ReadoutRate := FastReadout ;
end
else begin
FPixelDepth := 16 ;
FGreyLevelMax := (32768*2) -1 ;
ReadoutRate := SlowReadout ;
end ;
FPixelWidth := 9.9 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
if FCameraAvailable then begin
// Initialise camera
C4880_OpenCamera( FComPort, ReadoutRate, CameraInfo ) ;
C4880_GetCameraGainList( CameraGainList ) ;
FNumCameras := 1 ;
end ;
end ;
IMAQ_1394 : begin
CameraInfo.Clear ;
FCameraAvailable := IMAQ1394_OpenCamera(
Session,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
IMAQ1394_GetCameraGainList( CameraGainList ) ;
// Get camera readout speed options
CameraModeList.Clear ;
IMAQ1394_GetCameraVideoMode( Session, True, CameraModeList ) ;
FReadoutSpeed := 1 ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := False ;
// Get frame readout speed
{ IMAQ1394_CheckFrameInterval( 0,FFrameWidthMax-1,
0,FFrameHeightMax-1,
1,
FFrameInterval, FReadoutTime ) ; }
FBinFactor := 1 ;
FBinFactorMax := 1 ;
FNumCameras := 1 ;
end ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelWidth := 15.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
PIXELFLY : begin
CameraInfo.Clear ;
FCameraAvailable := PixelFly_OpenCamera(
PixelFlySession,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
PixelFly_GetCameraGainList( CameraGainList ) ;
// Get camera readout speed options
FReadoutSpeed := 1 ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FBinFactorMax := 2 ;
FCCDRegionReadoutAvailable := False ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelWidth := 15.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
SENSICAM : begin
CameraInfo.Clear ;
FCameraAvailable := SENSICAM_OpenCamera(
SENSICAMSession,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
SENSICAM_GetCameraGainList( CameraGainList ) ; // no gains supported yet
// Get camera readout speed options
FReadoutSpeed := 1 ;
// Calculate grey levels from pixel depth
FPixelDepth := 12 ;
FGreyLevelMax := 4095; //FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FBinFactor := 1 ;
FBinFactorMax := 8 ; // symmetrical;
FCCDRegionReadoutAvailable := False ;
FFrameInterval := 0.100 ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelWidth := 15.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
CameraInfo.Clear ;
FCameraAvailable := PVCAM_OpenCamera(
PVCAMSession,
FSelectedCamera,
FReadoutSpeed,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FGreyLevelMax,
FPixelWidth,
FPixelDepth,
FNumCameras,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
PVCAM_GetCameraGainList( PVCAMSession,CameraGainList ) ;
// Get camera readout speed options
CameraReadoutSpeedList.Clear ;
PVCAM_GetCameraReadoutSpeedList( PVCAMSession,CameraReadoutSpeedList ) ;
FCCDRegionReadoutAvailable := True ;
PVCAM_SetLightSpeedMode( PVCAMSession, FLightSpeedMode) ;
FFrameInterval := 0.1 ;
// Get frame readout speed
PVCAM_CheckFrameInterval( PVCAMSession,
0,FFrameWidthMax-1,
0,FFrameHeightMax-1,
1,
FReadoutSpeed,
FFrameInterval,
FReadoutTime,
FTriggerMode ) ;
end ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 100.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
BioRad : begin
FCameraName := 'BioRad Radiance/MRC 1024' ;
FNumBytesPerPixel := 1 ;
FPixelDepth := 8 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := $FF ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
FTriggerType := CamExposureTrigger ;
FNumCameras := 1 ;
end ;
ANDOR : begin
CameraInfo.Clear ;
AndorSession.ADChannel := FCameraADC ;
AndorSession.CameraMode := FCameraMode ;
FCameraAvailable := Andor_OpenCamera(
AndorSession,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
ADCGainList,
CCDVerticalShiftSpeedList,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
Andor_GetCameraGainList( CameraGainList ) ;
Andor_GetCameraModeList( CameraModeList ) ;
Andor_GetCameraADCList( CameraADCList ) ;
// List of readout speeds
Andor_GetCameraReadoutSpeedList( AndorSession, CameraReadoutSpeedList ) ;
FReadoutSpeed := 0 ;
AndorSession.ReadoutSpeed := FReadoutSpeed ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FBinFactorMax := 4 ;
FCCDRegionReadoutAvailable := True ;
// Set temperature set point
Andor_SetTemperature( AndorSession, FTemperatureSetPoint ) ;
Andor_SetCooling( AndorSession, FCameraCoolingOn ) ;
Andor_SetFanMode( AndorSession, FCameraFanMode ) ;
Andor_SetCameraMode( AndorSession, FCameraMode ) ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamReadoutTrigger ;
end ;
ANDORSDK3 : begin
CameraInfo.Clear ;
AndorSDK3Session.CameraMode := FCameraMode ;
FCameraAvailable := AndorSDK3_OpenCamera(
AndorSDK3Session,
FFrameWidthMax,
FFrameHeightMax,
FBinFactorMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
AndorSDK3_GetCameraGainList( AndorSDK3Session, CameraGainList ) ;
AndorSDK3_GetCameraModeList( AndorSDK3Session,CameraModeList ) ;
AndorSDK3_GetCameraADCList( AndorSDK3Session, CameraADCList ) ;
// List of readout speeds
AndorSDK3_GetCameraReadoutSpeedList( AndorSDK3Session, CameraReadoutSpeedList ) ;
FReadoutSpeed := 0 ;
AndorSDK3Session.ReadoutSpeed := FReadoutSpeed ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
// Set temperature set point
AndorSDK3_SetTemperature( AndorSDK3Session, FTemperatureSetPoint ) ;
AndorSDK3_SetCooling( AndorSDK3Session, FCameraCoolingOn ) ;
AndorSDK3_SetFanMode( AndorSDK3Session, FCameraFanMode ) ;
AndorSDK3_SetCameraMode( AndorSDK3Session, FCameraMode ) ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
UltimaLSM : begin
FCameraName := 'Prairie Technology Ultima' ;
FNumBytesPerPixel := 1 ;
FPixelDepth := 2048 ;
FGreyLevelMin := 0 ;
FGreyLevelMax := 2047 ;
FPixelWidth := 1.0 ;
FPixelUnits := '' ;
FTriggerType := CamExposureTrigger ;
FNumCameras := 1 ;
end ;
QCAM : begin
CameraInfo.Clear ;
FCameraAvailable := QCAMAPI_OpenCamera(
QCAMSession,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
QCAMAPI_GetCameraGainList( QCAMSession, CameraGainList ) ;
// List of readout speeds
QCAMAPI_GetCameraReadoutSpeedList( QCAMSession, CameraReadoutSpeedList ) ;
FReadoutSpeed := 0 ;
// Get camera readout speed options
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FBinFactorMax := 8 ;
FCCDRegionReadoutAvailable := True ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
//FTriggerType := CamReadoutTrigger ;
FTriggerType := CamExposureTrigger ;
end ;
DCAM : begin
CameraInfo.Clear ;
FCameraAvailable := DCAMAPI_OpenCamera(
DCAMSession,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
FBinFactorMax,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
DCAMAPI_GetCameraGainList( DCAMSession, CameraGainList ) ;
// List of readout speeds
DCAMAPI_GetCameraReadoutSpeedList( DCAMSession, CameraReadoutSpeedList ) ;
FReadoutSpeed := Min(Max(FReadoutSpeed,0),CameraReadoutSpeedList.Count-1) ;
// Get camera readout speed options
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
if ANSIContainsText(DCAMSession.CameraModel, 'C9100') then begin
FTriggerType := CamReadoutTrigger ;
end
else FTriggerType := CamExposureTrigger ;
FNumCameras := 1 ;
DCAMAPI_SetTemperature( DCAMSession, FTemperatureSetPoint ) ;
DCAMAPI_SetCooling( DCAMSession, FCameraCoolingOn ) ;
DCAMAPI_SetFanMode( DCAMSession, FCameraFanMode ) ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
IMAQ : begin
CameraInfo.Clear ;
FCameraAvailable := IMAQ_OpenCamera(
IMAQSession,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FBinFactorMax,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
IMAQ_GetCameraGainList( IMAQSession, CameraGainList ) ;
// Get camera readout speed options
FReadoutSpeed := 1 ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
// Get frame readout speed
IMAQ_CheckFrameInterval( IMAQSession, FTriggerMode, FFrameWidthMax,
FFrameInterval,FReadoutTime ) ;
FBinFactor := 1 ;
//FBinFactorMax := 1 ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
// Set tap DC offset adjustment
IMAQSession.CCDTapOffsetLT := FCCDTapOffsetLT ;
IMAQSession.CCDTapOffsetRT := FCCDTapOffsetRT ;
IMAQSession.CCDTapOffsetLB := FCCDTapOffsetLB ;
IMAQSession.CCDTapOffsetRB := FCCDTapOffsetRB ;
FNumCameras := 1 ;
end ;
end ;
IMAQDX : begin
CameraInfo.Clear ;
FCameraAvailable := IMAQDX_OpenCamera(
IMAQDXSession,
FSelectedCamera,
FCameraMode,
FCameraADC,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FBinFactorMax,
FNumCameras,
CameraInfo ) ;
if FCameraAvailable then begin
CameraGainList.Clear ;
IMAQDX_GetCameraGainList( IMAQDXSession, CameraGainList ) ;
// Get camera readout speed options
CameraModeList.Clear ;
IMAQDX_GetCameraVideoModeList( IMAQDXSession, CameraModeList ) ;
IMAQDX_GetCameraPixelFormatList( IMAQDXSession, CameraADCList ) ;
FReadoutSpeed := 1 ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
// Get frame readout speed
IMAQDX_CheckFrameInterval( IMAQDXSession, FFrameInterval ) ;
FBinFactor := 1 ;
// FBinFactorMax := 8 ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FMaxComponentsPerPixel := Min(IMAQDXSession.NumPixelComponents,3) ;
if FMonochromeImage then FNumComponentsPerPixel := 1
else FNumComponentsPerPixel := FMaxComponentsPerPixel ;
end ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelWidth := 15.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
ImageAreaChanged := True ;
end ;
DTOL : begin
CameraInfo.Clear ;
FCameraAvailable := DTOL_OpenCamera(
DTOLSession,
CameraInfo ) ;
if FCameraAvailable then begin
FFrameWidthMax := DTOLSession.FrameWidthMax ;
FFrameHeightMax := DTOLSession.FrameHeightMax ;
FNumBytesPerPixel := DTOLSession.NumBytesPerPixel ;
FPixelDepth := DTOLSession.PixelDepth ;
CameraGainList.Clear ;
DTOL_GetCameraGainList( CameraGainList ) ;
// Get camera readout speed options
CameraModeList.Clear ;
DTOL_GetCameraVideoModeList( DTOLSession, CameraModeList ) ;
FReadoutSpeed := 1 ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
// Get frame readout speed
DTOL_CheckFrameInterval( DTOLSession, FTriggerMode, FFrameInterval, FReadoutTime ) ;
FBinFactor := 1 ;
FBinFactorMax := 1 ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FNumCameras := 1 ;
end ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelWidth := 15.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
ImageAreaChanged := True ;
end ;
Thorlabs : begin
CameraInfo.Clear ;
ThorlabsSession.ShutterMode := FCameraMode ;
FCameraAvailable := Thorlabs_OpenCamera(
ThorlabsSession,
FFrameWidthMax,
FFrameHeightMax,
FBinFactorMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
Thorlabs_GetCameraGainList( ThorlabsSession, CameraGainList ) ;
Thorlabs_GetCameraModeList( ThorlabsSession,CameraModeList ) ;
// Thorlabs_GetCameraADCList( AndorSDK3Session, CameraADCList ) ;
// List of readout speeds
Thorlabs_GetCameraReadoutSpeedList( ThorlabsSession, CameraReadoutSpeedList ) ;
FReadoutSpeed := Max(Min(FReadoutSpeed,CameraReadoutSpeedList.Count-1),0) ;
ThorlabsSession.PixelClock := FReadoutSpeed ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
IDSuEYE : begin
CameraInfo.Clear ;
IDSSession.ShutterMode := FCameraMode ;
FCameraAvailable := IDS_OpenCamera(
IDSSession,
FFrameWidthMax,
FFrameHeightMax,
FBinFactorMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
IDS_GetCameraGainList( IDSSession, CameraGainList ) ;
IDS_GetCameraModeList( IDSSession,CameraModeList ) ;
IDS_GetCameraADCList( IDSSession, CameraADCList ) ;
// List of readout speeds
IDS_GetCameraReadoutSpeedList( IDSSession, CameraReadoutSpeedList ) ;
FReadoutSpeed := Max(Min(FReadoutSpeed,CameraReadoutSpeedList.Count-1),0) ;
IDSSession.PixelClock := FReadoutSpeed ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
PCOAPI : begin
CameraInfo.Clear ;
PCOAPISession.CameraMode := FCameraMode ;
FCameraAvailable := PCOAPI_OpenCamera(
PCOAPISession,
FFrameWidthMax,
FFrameHeightMax,
FBinFactorMax,
FNumBytesPerPixel,
FPixelDepth,
FPixelWidth,
CameraInfo ) ;
if FCameraAvailable then begin
PCOAPI_GetCameraGainList( PCOAPISession, CameraGainList ) ;
PCOAPI_GetCameraModeList( PCOAPISession,CameraModeList ) ;
PCOAPI_GetCameraADCList( PCOAPISession, CameraADCList ) ;
// List of readout speeds
PCOAPI_GetCameraReadoutSpeedList( PCOAPISession, CameraReadoutSpeedList ) ;
FReadoutSpeed := 0 ;
PCOAPISession.ReadoutSpeed := FReadoutSpeed ;
// Calculate grey levels from pixel depth
FGreyLevelMax := 1 ;
for i := 1 to FPixelDepth do FGreyLevelMax := FGreyLevelMax*2 ;
FGreyLevelMax := FGreyLevelMax - 1 ;
FGreyLevelMin := 0 ;
FCCDRegionReadoutAvailable := True ;
// Set temperature set point
PCOAPI_SetTemperature( PCOAPISession, FTemperatureSetPoint ) ;
PCOAPI_SetCooling( PCOAPISession, FCameraCoolingOn ) ;
PCOAPI_SetFanMode( PCOAPISession, FCameraFanMode ) ;
PCOAPI_SetCameraMode( PCOAPISession, FCameraMode ) ;
FNumCameras := 1 ;
end ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameIntervalMin := 1E-3 ;
FFrameIntervalMax := 1000.0 ;
FPixelUnits := 'um' ;
FTriggerType := CamExposureTrigger ;
end ;
end ;
if FCameraAvailable then begin
FFrameLeft := 0 ;
FFrameRight := FFrameWidthMax - 1 ;
FFrameTop := 0 ;
FFrameBottom := FFrameHeightMax - 1 ;
FBinFactor := Max(FBinFactor,1) ;
FFrameWidth := FFrameWidthMax div FBinFactor ;
FFrameHeight := FFrameHeightMax div FBinFactor ;
// Allocate internal frame buffer
AllocateFrameBuffer ;
ImageAreaChanged := False ;
end ;
end ;
procedure TSESCam.ReadCamera ;
// -----------------------
// Read frames from camera
// -----------------------
begin
if FCameraAvailable then begin
case FCameraType of
NoCamera8 : begin
end ;
NoCamera16 : begin
end ;
ITEX_CCIR : begin
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
end ;
IMAQ_1394 : begin
IMAQ1394_GetImage( Session ) ;
end ;
PIXELFLY : begin
{ PixelFly_GetImage( PixelFlySession,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FrameCounter ) ;}
end ;
SENSICAM : Begin
SensiCAM_GetImageFast ( SensicamSession );
end;
ANDOR : begin
Andor_GetImage( AndorSession ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_GetImage( AndorSDK3Session ) ;
end ;
QCAM : begin
QCAMAPI_GetImage( QCAMSession ) ;
end ;
DCAM : begin
DCAMAPI_GetImage( DCAMSession ) ;
FFrameCount := DCAMSession.FrameCounter ;
end ;
IMAQ : begin
IMAQ_GetImage( IMAQSession ) ;
FFrameCount := IMAQSession.FrameCounter ;
end ;
IMAQDX : begin
IMAQDX_GetImage( IMAQDXSession ) ;
FFrameCount := IMAQDXSession.FrameCounter ;
//outputdebugstring(pchar(format('%d',[FFrameCount])));
end ;
DTOL : begin
DTOL_GetImage( DTOLSession ) ;
end ;
Thorlabs : begin
Thorlabs_GetImage( ThorlabsSession ) ;
FFrameCount := ThorlabsSession.ActiveFrameCounter ;
end ;
IDSuEYE : begin
IDS_GetImage( IDSSession ) ;
FFrameCount := IDSSession.ActiveFrameCounter ;
end ;
PCOAPI : begin
PCOAPI_GetImage( PCOAPISession ) ;
end ;
end ;
end ;
end ;
procedure TSESCam.CloseCamera ;
{ -------------------------------------
Close camera/frame grabber sub-system
------------------------------------- }
begin
if FCameraAvailable then begin
case FCameraType of
NoCamera8 : begin
FCameraName := 'No Camera' ;
end ;
NoCamera16 : begin
FCameraName := 'No Camera' ;
end ;
ITEX_CCIR : begin
ITEX_CloseFrameGrabber( ITEX ) ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
C4880_CloseCamera ;
ITEX_CloseFrameGrabber( ITEX ) ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
PVCAM_CloseCamera(PVCAMSession) ;
FCameraAvailable := False ;
end ;
IMAQ_1394 : begin
IMAQ1394_CloseCamera( Session ) ;
end ;
PIXELFLY : begin
PixelFly_CloseCamera( PixelFlySession ) ;
end ;
Sensicam : begin
Sensicam_CloseCamera ( SensicamSession );
end;
ANDOR : begin
Andor_CloseCamera( AndorSession ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_CloseCamera( AndorSDK3Session ) ;
end ;
QCAM : begin
QCAMAPI_CloseCamera( QCAMSession ) ;
end ;
DCAM : begin
DCAMAPI_CloseCamera( DCAMSession ) ;
end ;
IMAQ : begin
IMAQ_CloseCamera( IMAQSession ) ;
end ;
IMAQDX : begin
IMAQDX_CloseCamera( IMAQDXSession ) ;
end ;
DTOL : begin
DTOL_CloseCamera( DTOLSession ) ;
end ;
Thorlabs : begin
Thorlabs_CloseCamera( ThorlabsSession ) ;
end ;
IDSuEYE : begin
IDS_CloseCamera( IDSSession ) ;
end ;
PCOAPI : begin
PCOAPI_CloseCamera( PCOAPISession ) ;
end ;
end ;
end ;
if PFrameBuffer <> Nil then DeallocateFrameBuffer ;
FCameraAvailable := False ;
end ;
function TSESCam.AllocateFrameBuffer : Boolean ;
// -----------------------------------------
// Allocate/reallocate internal frame buffer
// -----------------------------------------
begin
// Default checks (in case checks not implemented for camera)
Result := False ;
FFrameLeft := Min(Max(FFrameLeft,0),FFrameWidthMax-1) ;
FFrameTop := Min(Max(FFrameTop,0),FFrameHeightMax-1) ;
FFrameRight := Min(Max(FFrameRight,0),FFrameWidthMax-1) ;
FFrameBottom := Min(Max(FFrameBottom,0),FFrameHeightMax-1) ;
if FFrameLeft >= FFrameRight then FFrameRight := FFrameLeft + FBinFactor - 1 ;
if FFrameTop >= FFrameBottom then FFrameBottom := FFrameBottom + FBinFactor - 1 ;
if FFrameRight >= FFrameWidthMax then FFrameRight := FFrameWidthMax - FBinFactor ;
if FFrameBottom >= FFrameHeightMax then FFrameBottom := FFrameHeightMax - FBinFactor ;
FFrameLeft := (FFrameLeft div FBinFactor)*FBinFactor ;
FFrameTop := (FFrameTop div FBinFactor)*FBinFactor ;
FFrameRight := (FFrameRight div FBinFactor)*FBinFactor + (FBinFactor-1) ;
FFrameBottom := (FFrameBottom div FBinFactor)*FBinFactor + (FBinFactor-1) ;
// Ensure right/bottom edge does not exceed frame
if FFrameRight >= FFrameWidthMax then FFrameRight := FFrameRight - BinFactor ;
FFrameWidth := ((FFrameRight - FFrameLeft) div FBinFactor) + 1 ;
if FFrameBottom >= FFrameHeightMax then FFrameBottom := FFrameBottom - FBinFactor ;
FFrameHeight := ((FFrameBottom - FFrameTop) div FBinFactor) + 1 ;
case FCameraType of
ITEX_CCIR : begin
FFrameLeft := (FFrameLeft div 8)*8 ;
FFrameWidth := ((FFrameRight - FFrameLeft + 1) div 16)*16 ;
FFrameRight := FFrameLeft + FFrameWidth - 1 ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
FFrameWidth := (FFrameWidth div 4)*4 ;
FFrameRight := FFrameLeft + (FBinFactor*FFrameWidth) - 1 ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
PVCAM_CheckROIBoundaries( FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidthMax,
FFrameHeightMax,
FFrameWidth,
FFrameHeight
) ;
end ;
ANDOR : begin
ANDOR_CheckROIBoundaries( AndorSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidthMax,
FFrameHeightMax,
FFrameWidth,
FFrameHeight
) ;
end ;
ANDORSDK3 : begin
ANDORSDK3_CheckROIBoundaries( AndorSDK3Session,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidthMax,
FFrameHeightMax,
FFrameWidth,
FFrameHeight
) ;
end ;
QCAM : begin
QCAMAPI_CheckROIBoundaries( QCAMSession,
FReadoutSpeed,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FTriggerMode,
FFrameInterval,
FReadoutTime,
FDisableExposureIntervalLimit ) ;
end ;
DCAM : begin
DCAMAPI_CheckROIBoundaries( DCAMSession,
FReadoutSpeed,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FFrameInterval,
FReadoutTime,
FTriggerMode ) ;
end ;
IMAQ : begin
IMAQ_CheckROIBoundaries( IMAQSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight ) ;
end ;
IMAQDX : begin
IMAQDX_CheckROIBoundaries( IMAQDXSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FFrameInterval,
FReadoutTime
) ;
end ;
DTOL : begin
DTOL_CheckROIBoundaries( DTOLSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FFrameWidth,
FFrameHeight ) ;
end ;
Thorlabs : begin
Thorlabs_CheckROIBoundaries( ThorlabsSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FFrameInterval,
FTriggerMode,
FReadoutTime
) ;
end ;
IDSuEYE : begin
IDS_CheckROIBoundaries( IDSSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FFrameInterval,
FTriggerMode,
FReadoutTime
) ;
end ;
PCOAPI : begin
PCOAPI_CheckROIBoundaries( PCOAPISession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidthMax,
FFrameHeightMax,
FFrameWidth,
FFrameHeight
) ;
end ;
end ;
if FMonochromeImage then FNumComponentsPerPixel := 1
else FNumComponentsPerPixel := FMaxComponentsPerPixel ;
FNumBytesPerFrame := FFrameWidth*FFrameHeight*FNumBytesPerPixel*FNumComponentsPerPixel ;
FNumBytesInFrameBuffer := FNumBytesPerFrame*FNumFramesInBuffer ;
DeallocateFrameBuffer ;
if FNumBytesInFrameBuffer > 0 then begin
Try
PFrameBuffer := GetMemory( NativeInt(FNumBytesInFrameBuffer + 4096) ) ;
PAllocatedFrameBuffer := PFrameBuffer ;
// Allocate to 64 bit boundary
PFrameBuffer := Pointer( (NativeUInt(PByte(PFrameBuffer)) + $F) and (not $F)) ;
Except
on E : EOutOfMemory do begin
outputdebugstring(pchar('Allocating buffer failed'));
Exit ;
end;
end ;
end;
ImageAreaChanged := False ;
Result := True ;
end ;
procedure TSESCam.DeallocateFrameBuffer ;
// --------------------------------
// Deallocate internal frame buffer
// --------------------------------
begin
if PFrameBuffer <> Nil then begin
FreeMemory( PAllocatedFrameBuffer ) ;
PFrameBuffer := Nil ;
end ;
end ;
function TSESCam.StartCapture : Boolean ;
{ --------------------
Start frame capture
-------------------- }
var
ReadoutRate : Integer ;
begin
Result := False ;
// Exit if no frame buffer allocated
if PFrameBuffer = Nil then Exit ;
if FAmpGain < 0 then FAmpGain := 0 ;
case FCameraType of
ITEX_CCIR : begin
FCameraActive := ITEX_StartCapture( ITEX,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
PFrameBuffer,
FNumFramesInBuffer,
FFrameWidth,
FFrameHeight ) ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
// Start frame grabber
FCameraActive := ITEX_StartCapture( ITEX,
0,
((FFrameRight - FFrameLeft + 1) div FBinFactor)-1,
0,
((FFrameBottom - FFrameTop + 1) div FBinFactor)-1,
PFrameBuffer,
FNumFramesInBuffer,
FFrameWidth,
FFrameHeight ) ;
FFrameRight := FFrameLeft + FFrameWidth*FBinFactor - 1 ;
// Select camera readout rate
if FCameraType = ITEX_C4880_10 then ReadoutRate := FastReadout
else ReadoutRate := SlowReadout ;
// Start camera
FCameraActive := C4880_StartCapture(
ReadoutRate,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
FReadoutTime ) ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
FCameraActive := PVCAM_StartCapture( PVCAMSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
PFrameBuffer,
FNumBytesInFrameBuffer,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FFrameWidth,
FFrameHeight,
FTriggerMode,
FReadoutSpeed,
FCCDClearPreExposure,
FCCDPostExposureReadout ) ;
FTemperature := PVCAMSession.Temperature ;
end ;
IMAQ_1394 : begin
FCameraActive := IMAQ1394_StartCapture(
Session,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
PIXELFLY : begin
FCameraActive := PixelFly_StartCapture(
PixelFlySession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
SENSICAM : begin
FCameraActive := SENSICAM_StartCapture(
SENSICAMSession,
FFrameInterval, // this should be the ExposureTime ?
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
ANDOR : begin
// Note Andor cameras do not support additional readout time
FCameraActive := Andor_StartCapture(
AndorSession,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
FTemperature := AndorSession.Temperature ;
end ;
ANDORSDK3 : begin
// Note Andor cameras do not support additional readout time
FCameraActive := AndorSDK3_StartCapture(
AndorSDK3Session,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
FTemperature := AndorSDK3Session.Temperature ;
end ;
QCAM : begin
FCameraActive := QCAMAPI_StartCapture(
QCAMSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FReadoutSpeed,
FTriggerMode,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FCCDClearPreExposure
) ;
FrameCounter := 0 ;
FTemperature := QCAMSession.Temperature ;
end ;
DCAM : begin
FCameraActive := DCAMAPI_StartCapture(
DCAMSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FReadoutSpeed,
FTriggerMode,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FDisableEMCCD
) ;
FrameCounter := 0 ;
//FTemperature := QCAMSession.Temperature ;
end ;
IMAQ : begin
// Set tap DC offset adjustment
IMAQSession.CCDTapOffsetLT := FCCDTapOffsetLT ;
IMAQSession.CCDTapOffsetRT := FCCDTapOffsetRT ;
IMAQSession.CCDTapOffsetLB := FCCDTapOffsetLB ;
IMAQSession.CCDTapOffsetRB := FCCDTapOffsetRB ;
FCameraActive := IMAQ_StartCapture(
IMAQSession,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FNumPixelShiftFrames
) ;
FrameCounter := 0 ;
end ;
IMAQDX : begin
// Set tap DC offset adjustment
IMAQSession.CCDTapOffsetLT := FCCDTapOffsetLT ;
IMAQSession.CCDTapOffsetRT := FCCDTapOffsetRT ;
IMAQSession.CCDTapOffsetLB := FCCDTapOffsetLB ;
IMAQSession.CCDTapOffsetRB := FCCDTapOffsetRB ;
FCameraActive := IMAQDX_StartCapture(
IMAQDXSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FMonochromeImage
) ;
FrameCounter := 0 ;
FFrameCount := IMAQDXSession.FrameCounter ;
end ;
DTOL : begin
FCameraActive := DTOL_StartCapture(
DTOLSession,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
Thorlabs : begin
FCameraActive := Thorlabs_StartCapture(
ThorlabsSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
end ;
IDSuEYE : begin
FCameraActive := IDS_StartCapture(
IDSSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
end ;
PCOAPI : begin
FCameraActive := PCOAPI_StartCapture(
PCOAPISession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
FTemperature := PCOAPISession.Temperature ;
end ;
end ;
FCameraRestartRequired := False ;
Result := True ;
end ;
function TSESCam.SnapImage : Boolean ;
{ ----------------------
Acquire a single image
---------------------- }
var
ReadoutRate : Integer ;
begin
Result := False ;
// Exit if no frame buffer allocated
if PFrameBuffer = Nil then Exit ;
if FAmpGain < 0 then FAmpGain := 0 ;
case FCameraType of
ITEX_CCIR : begin
FCameraActive := ITEX_StartCapture( ITEX,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
PFrameBuffer,
FNumFramesInBuffer,
FFrameWidth,
FFrameHeight ) ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
// Start frame grabber
FCameraActive := ITEX_StartCapture( ITEX,
0,
((FFrameRight - FFrameLeft + 1) div FBinFactor)-1,
0,
((FFrameBottom - FFrameTop + 1) div FBinFactor)-1,
PFrameBuffer,
FNumFramesInBuffer,
FFrameWidth,
FFrameHeight ) ;
FFrameRight := FFrameLeft + FFrameWidth*FBinFactor - 1 ;
// Select camera readout rate
if FCameraType = ITEX_C4880_10 then ReadoutRate := FastReadout
else ReadoutRate := SlowReadout ;
// Start camera
FCameraActive := C4880_StartCapture(
ReadoutRate,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
FReadoutTime ) ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
FCameraActive := PVCAM_StartCapture( PVCAMSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
PFrameBuffer,
FNumBytesInFrameBuffer,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FFrameWidth,
FFrameHeight,
FTriggerMode,
FReadoutSpeed,
FCCDClearPreExposure,
FCCDPostExposureReadout ) ;
FTemperature := PVCAMSession.Temperature ;
end ;
IMAQ_1394 : begin
FCameraActive := IMAQ1394_StartCapture(
Session,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
PIXELFLY : begin
FCameraActive := PixelFly_StartCapture(
PixelFlySession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
SENSICAM : begin
FCameraActive := SENSICAM_StartCapture(
SENSICAMSession,
FFrameInterval, // this should be the ExposureTime ?
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
ANDOR : begin
// Note Andor cameras do not support additional readout time
FCameraActive := Andor_StartCapture(
AndorSession,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
FTemperature := AndorSession.Temperature ;
end ;
ANDORSDK3 : begin
// Note Andor cameras do not support additional readout time
FCameraActive := AndorSDK3_StartCapture(
AndorSDK3Session,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
FTemperature := AndorSDK3Session.Temperature ;
end ;
QCAM : begin
FCameraActive := QCAMAPI_StartCapture(
QCAMSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FReadoutSpeed,
FTriggerMode,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FCCDClearPreExposure
) ;
FrameCounter := 0 ;
FTemperature := QCAMSession.Temperature ;
end ;
DCAM : begin
FCameraActive := DCAMAPI_StartCapture(
DCAMSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FReadoutSpeed,
FTriggerMode,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FDisableEMCCD
) ;
FrameCounter := 0 ;
end ;
IMAQ : begin
FCameraActive := IMAQ_SnapImage(
IMAQSession,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FNumPixelShiftFrames
) ;
FrameCounter := 0 ;
end ;
IMAQDX : begin
FCameraActive := IMAQDX_SnapImage(
IMAQDXSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FMonochromeImage
) ;
FrameCounter := 0 ;
FFrameCount := IMAQDXSession.FrameCounter ;
end ;
DTOL : begin
FCameraActive := DTOL_StartCapture(
DTOLSession,
FFrameInterval,
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame
) ;
FrameCounter := 0 ;
end ;
Thorlabs : begin
FCameraActive := Thorlabs_StartCapture(
ThorlabsSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
end ;
IDSuEYE : begin
FCameraActive := IDS_StartCapture(
IDSSession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
end ;
PCOAPI : begin
FCameraActive := PCOAPI_StartCapture(
PCOAPISession,
FFrameInterval,
Max(FAdditionalReadoutTime,FShortenExposureBy),
FAmpGain,
FTriggerMode,
FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
PFrameBuffer,
FNumFramesInBuffer,
FNumBytesPerFrame,
FReadoutTime
) ;
FrameCounter := 0 ;
end ;
end ;
FCameraRestartRequired := False ;
Result := True ;
end ;
procedure TSESCam.StopCapture ;
{ --------------------
Stop frame capture
-------------------- }
begin
if not FCameraActive then Exit ;
case FCameraType of
ITEX_CCIR : begin
FCameraActive := ITEX_StopCapture( ITEX ) ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
C4880_StopCapture ;
FCameraActive := ITEX_StopCapture( ITEX ) ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
PVCAM_StopCapture(PVCAMSession) ;
FCameraActive := False ;
end ;
IMAQ_1394 : begin
IMAQ1394_StopCapture( Session ) ;
FCameraActive := False ;
end ;
PIXELFLY : begin
PixelFly_StopCapture( PixelFlySession ) ;
FCameraActive := False ;
end ;
Sensicam : Begin
SensiCam_StopCapture( SensiCamSession ) ;
FCameraActive := False ;
end;
ANDOR : begin
Andor_StopCapture( AndorSession ) ;
FCameraActive := False ;
end ;
ANDORSDK3 : begin
AndorSDK3_StopCapture( AndorSDK3Session ) ;
FCameraActive := False ;
end ;
QCAM : begin
QCAMAPI_StopCapture( QCAMSession ) ;
FCameraActive := False ;
end ;
DCAM : begin
DCAMAPI_StopCapture( DCAMSession ) ;
FCameraActive := False ;
end ;
IMAQ : begin
IMAQ_StopCapture( IMAQSession ) ;
FCameraActive := False ;
end ;
IMAQDX : begin
IMAQDX_StopCapture( IMAQDXSession ) ;
FCameraActive := False ;
end ;
DTOL : begin
DTOL_StopCapture( DTOLSession ) ;
FCameraActive := False ;
end ;
Thorlabs : begin
Thorlabs_StopCapture( ThorlabsSession ) ;
FCameraActive := False ;
end ;
IDSuEYE : begin
IDS_StopCapture( IDSSession ) ;
FCameraActive := False ;
end ;
PCOAPI : begin
PCOAPI_StopCapture( PCOAPISession ) ;
FCameraActive := False ;
end ;
end ;
end ;
procedure TSESCam.SoftwareTriggerCapture ;
begin
if not FCameraActive then Exit ;
case FCameraType of
IMAQ : begin
IMAQ_TriggerPulse(IMAQSession) ;
end ;
end;
end ;
procedure TSESCam.GetLatestFrameNumber( var FrameNum : Integer ) ;
begin
case FCameraType of
ITEX_CCIR : begin
FrameNum := ITEX_GetLatestFrameNumber( ITEX ) ;
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : Begin
FrameNum := PVCAM_GetLatestFrameNumber(PVCAMSession) ;
end ;
end ;
end ;
procedure TSESCam.GetFrameBufferPointer( var FrameBuf : Pointer ) ;
begin
FrameBuf := PFrameBuffer ;
end ;
procedure TSESCam.SetFrameTop( Value : Integer ) ;
// ----------------------------------
// Set Top edge of camera image frame
// ----------------------------------
begin
if not FCameraActive then begin
FFrameTop := Value ;
ImageAreaChanged := True ;
end ;
end ;
procedure TSESCam.SetFrameBottom( Value : Integer ) ;
// -------------------------------------
// Set bottom edge of camera image frame
// -------------------------------------
begin
if not FCameraActive then begin
FFrameBottom := Value ;
ImageAreaChanged := True ;
end ;
end ;
procedure TSESCam.SetBinFactor( Value : Integer ) ;
// -------------------------
// Set pixel binning factor
// ------------------------
begin
if not FCameraActive then begin
FBinFactor := LimitTo( Value, 1, FBinFactorMax ) ;
case FCameraType of
Sensicam : SensiCam_CheckBinFactor(FBinFactor) ;
end ;
ImageAreaChanged := True ;
end ;
end ;
procedure TSESCam.SetFrameLeft( Value : Integer ) ;
// -----------------------------------
// Set left edge of camera image frame
// -----------------------------------
begin
if not FCameraActive then begin
FFrameLeft := Value ;
ImageAreaChanged := True ;
end ;
end ;
procedure TSESCam.SetFrameRight( Value : Integer ) ;
// -----------------------------------
// Set right edge of camera image frame
// -----------------------------------
begin
if not FCameraActive then begin
FFrameRight := Value ;
ImageAreaChanged := True ;
end ;
end ;
function TSESCam.GetFrameWidth : Integer ;
// --------------------------
// Get pixel width of camera image
// ---------------------------
begin
if (not FCameraActive) and ImageAreaChanged then AllocateFrameBuffer ;
Result := FFrameWidth ;
end ;
function TSESCam.GetFrameHeight : Integer ;
// --------------------------
// Get pixel height of camera image
// ---------------------------
begin
if (not FCameraActive) and ImageAreaChanged then AllocateFrameBuffer ;
Result := FFrameHeight ;
end ;
function TSESCam.GetNumPixelsPerFrame : Integer ;
// --------------------------
// Get no. of pixels in frame
// ---------------------------
begin
if (not FCameraActive) and ImageAreaChanged then AllocateFrameBuffer ;
Result := FFrameHeight*FFrameWidth ;
end ;
function TSESCam.GetNumComponentsPerFrame : Integer ;
// --------------------------
// Get no. of components in frame
// ---------------------------
begin
if (not FCameraActive) and ImageAreaChanged then AllocateFrameBuffer ;
Result := FFrameHeight*FFrameWidth*FNumComponentsPerPixel ;
end ;
function TSESCam.GetNumBytesPerFrame : Integer ;
// --------------------------
// Get pixel height of camera image
// ---------------------------
begin
if (not FCameraActive) and ImageAreaChanged then AllocateFrameBuffer ;
Result := FFrameHeight*FFrameWidth*FNumBytesPerPixel*FNumComponentsPerPixel ;
end ;
procedure TSESCam.SetReadOutSpeed( Value : Integer ) ;
// -------------------------------
// Set camera read out speed index
// -------------------------------
begin
//FReadoutSpeed := Max(Min(Value,CameraReadoutSpeedList.Count-1),0) ;
FReadoutSpeed := Max(Value,0) ;
case FCameraType of
ITEX_CCIR : begin
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
PVCAM_SetReadoutSpeed( PVCAMSession, FReadoutSpeed, FPixelDepth, FGreyLevelMax ) ;
end ;
Andor : begin
AndorSession.ReadoutSpeed := FReadoutSpeed ;
end ;
AndorSDK3 : begin
AndorSDK3Session.ReadoutSpeed := FReadoutSpeed ;
end ;
Thorlabs : begin
ThorlabsSession.PixelClock := FReadoutSpeed ;
if ThorlabsSession.PixelClock >= ThorlabsSession.NumPixelClocks then begin
ThorlabsSession.PixelClock := ThorlabsSession.DefaultPixelClock ;
FReadoutSpeed := ThorlabsSession.PixelClock ;
end ;
end ;
IDSuEYE : begin
IDSSession.PixelClock := FReadoutSpeed ;
if IDSSession.PixelClock >= IDSSession.NumPixelClocks then begin
IDSSession.PixelClock := IDSSession.DefaultPixelClock ;
FReadoutSpeed := IDSSession.PixelClock ;
end ;
end ;
PCOAPI : begin
PCOAPISession.ReadoutSpeed := FReadoutSpeed ;
end ;
end ;
ImageAreaChanged := True ;
end ;
function TSESCam.GetReadOutTime : Double ;
// -------------------------------
// Get camera frame readout time (s)
// -------------------------------
begin
// Set frame interval (updates FReadoutTime)
// If camera is in use latest time
if not FCameraActive then SetFrameInterval( FFrameInterval ) ;
Result := FReadoutTime ;
end ;
function TSESCam.GetDefaultReadoutSpeed : Integer ;
// ---------------------------------------
// Return default readout speed for camera
// ---------------------------------------
var
i : Integer ;
MaxSpeed,ReadSpeed : Single ;
begin
case FCameraType of
Thorlabs : Result := ThorLabsSession.DefaultPixelClock ;
IDSuEYE : Result := IDSSession.DefaultPixelClock ;
else begin
// All other cameras use maximum rate
MaxSpeed := 0.0 ;
Result := 0 ;
for i := 0 to CameraReadoutSpeedList.Count-1 do begin
ReadSpeed := ExtractFloat( CameraReadoutSpeedList.Strings[i], 0.0 ) ;
if ReadSpeed > MaxSpeed then begin
MaxSpeed := ReadSpeed ;
Result := i ;
end ;
end ;
end;
end ;
end;
function TSESCam.GetExposureTime : Double ;
//
// Return camera exposure time
//
begin
Result := FFrameInterval
- 0.001 { Allow for CCD readout time}
- AdditionalReadoutTime ; { Additional user defined readout time}
// If post-exposure readout shorten exposure to account for readout
if FCCDPostExposureReadout then Result := Result - ReadoutTime ;
// No shorter than 1ms exposure
Result := Max(Result,0.001) ;
end ;
procedure TSESCam.SetFrameInterval( Value : Double ) ;
// ---------------------------------
// Set time interval between frames
// ---------------------------------
//var
// ReadoutRate : Integer ;
begin
FFrameInterval := Value ;
case FCameraType of
ITEX_CCIR : begin
// CCIR frame interval is fixed
FFrameInterval := FFrameIntervalMin ;
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
// if FCameraType = ITEX_C4880_10 then ReadoutRate := FastReadout
// else ReadoutRate := SlowReadout ;
{ C4880_CheckFrameInterval( FFrameLeft,
FFrameTop,
FFrameWidth*FBinFactor,
FFrameHeight*FBinFactor,
FBinFactor,
ReadoutRate,
FFrameInterval,
FReadoutTime ) ;}
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
PVCAM_CheckFrameInterval( PVCAMSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FReadoutSpeed,
FFrameInterval,
FReadoutTime,
FTriggerMode ) ;
end ;
PIXELFLY : begin
PixelFlyCheckFrameInterval( FFrameWidthMax,
FBinFactor,
FTriggerMode,
FFrameInterval,
FReadoutTime ) ;
end ;
SensiCam : Begin
SensiCamCheckFrameInterval( SensicamSession,
FFrameWidthMax,
FBinFactor,
FTriggerMode,
FFrameInterval,
FReadoutTime ) ;
end ;
IMAQ_1394 : begin
IMAQ1394_CheckFrameInterval( Session, FFrameInterval ) ;
end ;
ANDOR : begin
Andor_CheckFrameInterval( AndorSession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameInterval,
FReadoutTime ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_CheckFrameInterval( AndorSDK3Session,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidthMax,
FFrameHeightMax,
FFrameInterval,
FReadoutTime ) ;
end ;
QCAM : begin
QCAMAPI_CheckROIBoundaries( QCAMSession,
FReadoutSpeed,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FTriggerMode,
FFrameInterval,
FReadoutTime,
DisableExposureIntervalLimit ) ;
end ;
DCAM : begin
DCAMAPI_CheckROIBoundaries( DCAMSession,
FReadoutSpeed,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidth,
FFrameHeight,
FFrameInterval,
FReadoutTime,
FTriggerMode ) ;
end ;
IMAQ : begin
IMAQ_CheckFrameInterval( IMAQSession, FTriggerMode, FFrameWidthMax,
FFrameInterval,FReadoutTime ) ;
end ;
IMAQDX : begin
IMAQDX_CheckFrameInterval( IMAQDXSession, FFrameInterval ) ;
end ;
DTOL : begin
DTOL_CheckFrameInterval( DTOLSession,
FTriggerMode,
FFrameInterval,
FReadoutTime ) ;
end ;
Thorlabs : begin
Thorlabs_CheckFrameInterval( ThorlabsSession,
FTriggerMode,
FFrameInterval,
FReadoutTime ) ;
end ;
IDSuEYE : begin
IDS_CheckFrameInterval( IDSSession,
FTriggerMode,
FFrameInterval,
FReadoutTime ) ;
end ;
PCOAPI : begin
PCOAPI_CheckFrameInterval( PCOAPISession,
FFrameLeft,
FFrameRight,
FFrameTop,
FFrameBottom,
FBinFactor,
FFrameWidthMax,
FFrameHeightMax,
FFrameInterval,
FReadoutTime,
FTRiggerMode ) ;
end ;
end ;
end ;
procedure TSESCam.SetNumFramesInBuffer( Value : Integer ) ;
// ---------------------------------------------
// Set number of frames in internal image buffer
// ---------------------------------------------
begin
if not FCameraActive then begin
FNumFramesInBuffer := LimitTo( Value, 2, 10000 ) ;
AllocateFrameBuffer ;
end ;
end ;
function TSESCam.GetMaxFramesInBuffer : Integer ;
// -----------------------------------------------------------
// Return max. nunber of frames allowed in camera frame buffer
// -----------------------------------------------------------
var
NumbytesPerFrame : Cardinal ;
begin
if FMonochromeImage then FNumComponentsPerPixel := 1
else FNumComponentsPerPixel := FMaxComponentsPerPixel ;
NumbytesPerFrame := FFrameWidth*FFrameHeight*FNumComponentsPerPixel*FNumBytesPerPixel ;
case FCameraType of
RS_PVCAM_PENTAMAX : Begin
// Pentamax has limited buffer size
Result := (4194304 div NumbytesPerFrame)-1 ;
Result := Min( Result, 36) ;
end ;
PIXELFLY : begin
Result := 8 ;
end ;
Andor : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
if Result > 36 then Result := 36 ;
end ;
AndorSDK3 : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
if Result > 36 then Result := 36 ;
end ;
RS_PVCAM : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
end ;
DCAM : begin
Result := (40000000 div NumbytesPerFrame)-1 ;
end ;
IMAQ : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
end ;
IMAQDX : begin
Result := 64 ;
end ;
QCAM : begin
Result := High(QCAMSession.FrameList)+1 ;
end ;
DTOL : begin
Result := DTOLSession.MaxFrames ;
end ;
Thorlabs : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
end ;
IDSuEYE : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
end ;
PCOAPI : begin
Result := (20000000 div NumbytesPerFrame)-1 ;
// if Result > 36 then Result := 36 ;
Result := 32 ;
end ;
else begin
Result := 32 ;
end ;
end ;
end ;
function TSESCam.GetPixelWidth : Single ;
// --------------------------------------------------
// Return width of camera pixel (after magnification)
// --------------------------------------------------
begin
FBinFactor := Max(FBinFactor,1) ;
if FLensMagnification > 0.0 then Result := (FPixelWidth*FBinFactor) / FLensMagnification
else Result := FPixelWidth*FBinFactor ;
end ;
function TSESCam.LimitTo(
Value : Integer ;
LoLimit : Integer ;
HiLimit : Integer ) : Integer ;
//
// Constrain <value> to lie within <LoLimit> to <HiLimit> range
// ------------------------------------------------------------
begin
if Value < LoLimit then Result := LoLimit
else Result := Value ;
if Value > HiLimit then Result := HiLimit
else Result := Value ;
end ;
procedure TSESCam.GetCameraGainList( List : TStrings ) ;
//
// Get list of available camera amplifier gains
//
var
i : Integer ;
begin
List.Clear ;
for i := 0 to CameraGainList.Count-1 do
List.Add(CameraGainList[i]) ;
end ;
procedure TSESCam.GetCameraReadoutSpeedList( List : TStrings ) ;
// -------------------------------------------
// Get list of available camera readout speeds
// -------------------------------------------
var
i : Integer ;
begin
case FCameraType of
Andor : Andor_GetCameraReadoutSpeedList( AndorSession, CameraReadoutSpeedList ) ;
AndorSDK3 : AndorSDK3_GetCameraReadoutSpeedList( AndorSDK3Session, CameraReadoutSpeedList ) ;
end ;
List.Clear ;
for i := 0 to CameraReadoutSpeedList.Count-1 do
List.Add(CameraReadoutSpeedList[i]) ;
end ;
procedure TSESCam.GetCameraModeList( List : TStrings ) ;
// -------------------------------------------
// Get list of available camera operating modes
// -------------------------------------------
var
i : Integer ;
begin
List.Clear ;
for i := 0 to CameraModeList.Count-1 do
List.Add(CameraModeList[i]) ;
// Ensure list is not empty
if List.Count < 1 then List.Add(' ') ;
end ;
procedure TSESCam.GetCameraADCList( List : TStrings ) ;
// -------------------------------------------
// Get list of available camera A/D converters
// -------------------------------------------
var
i : Integer ;
begin
List.Clear ;
for i := 0 to CameraADCList.Count-1 do
List.Add(CameraADCList[i]) ;
// Ensure list is not empty
if List.Count < 1 then List.Add(' ') ;
end ;
procedure TSESCam.GetADCGainList( List : TStrings ) ;
// --------------------------------------------------------
// Get list of available camera A/D converter gain settings
// --------------------------------------------------------
var
i : Integer ;
begin
List.Clear ;
for i := 0 to ADCGainList.Count-1 do List.Add(ADCGainList[i]) ;
// Ensure list is not empty
if List.Count < 1 then List.Add('X1') ;
end ;
procedure TSESCam.GetCCDVerticalShiftSpeedList( List : TStrings ) ;
// ----------------------------------------------
// Get list of CCD vertical shift speed settings
// ----------------------------------------------
var
i : Integer ;
begin
List.Clear ;
for i := 0 to CCDVerticalShiftSpeedList.Count-1 do List.Add(CCDVerticalShiftSpeedList[i]) ;
// Ensure list is not empty
if List.Count < 1 then List.Add('n/a') ;
end ;
procedure TSESCam.GetCameraNameList( List : TStrings ) ;
// ------------------------------
// Get list of available cameras
// ------------------------------
var
i : Integer ;
begin
List.Clear ;
case FCameraType of
IMAQDX: for i := 0 to IMAQDXSession.NumCameras-1 do List.Add(IMAQDXSession.CameraNames[i]) ;
RS_PVCAM,RS_PVCAM_PENTAMAX: for i := 0 to PVCAMSession.NumCameras-1 do List.Add(PVCAMSession.CameraNames[i]) ;
end;
// Ensure list is not empty
if List.Count < 1 then List.Add('n/a') ;
end ;
procedure TSESCam.GetCameraInfo( List : TStrings ) ;
// ----------------------
// Get camera information
// ----------------------
var
i : Integer ;
begin
List.Clear ;
for i := 0 to CameraInfo.Count-1 do
List.Add(CameraInfo[i]) ;
end ;
function TSESCam.IsLSM( iCameraType : Integer ) : Boolean ;
//
// Return TRUE if supplied camera type is a laser scanning microscope
//
begin
case FCameraType of
BioRad,UltimaLSM : Result := True ;
else Result := False ;
end ;
end ;
procedure TSESCam.SetCCDArea( FrameLeft : Integer ;
FrameTop : Integer ;
FrameRight : Integer ;
FrameBottom : Integer ) ;
// ----------------------
// Set CCD imaging region
// ----------------------
begin
FFrameRight := FrameRight ;
FFrameLeft := FrameLeft ;
FFrameTop := FrameTop ;
FFrameBottom := FrameBottom ;
ImageAreaChanged := True ;
end ;
function TSESCam.PauseCapture : Boolean ;
//
// Pause image capture
//
begin
case FCameraType of
imaQ : IMAQ_PauseCapture(IMAQSession) ;
end;
end;
function TSESCam.RestartCapture : Boolean ;
//
// Restart image capture
//
begin
case FCameraType of
imaQ : IMAQ_RestartCapture(IMAQSession) ;
end;
end;
procedure TSESCam.SetTemperature(
Value : Single
) ;
// --------------------------------
// Set camera temperature set point
// --------------------------------
begin
FTemperatureSetPoint := Value ;
if FCameraActive then Exit ;
case FCameraType of
ITEX_CCIR : begin
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
end ;
IMAQ_1394 : begin
end ;
PIXELFLY : begin
end ;
Sensicam : Begin
end;
ANDOR : begin
Andor_SetTemperature( AndorSession, FTemperatureSetPoint ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_SetTemperature( AndorSDK3Session, FTemperatureSetPoint ) ;
end ;
DCAM : begin
DCAMAPI_SetTemperature( DCAMSession, FTemperatureSetPoint ) ;
end ;
QCAM : begin
end ;
IMAQ : begin
end ;
IMAQDX : begin
end ;
DTOL : begin
end ;
PCOAPI : begin
PCOAPI_SetTemperature( PCOAPISession, FTemperatureSetPoint ) ;
end ;
end ;
end ;
procedure TSESCam.SetCameraCoolingOn(
Value : Boolean
) ;
// --------------------------------
// Set camera cooling on/off
// --------------------------------
begin
FCameraCoolingOn := Value ;
if FCameraActive then Exit ;
case FCameraType of
ITEX_CCIR : begin
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
end ;
IMAQ_1394 : begin
end ;
PIXELFLY : begin
end ;
Sensicam : Begin
end;
ANDOR : begin
Andor_SetCooling( AndorSession, Value ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_SetCooling( AndorSDK3Session, Value ) ;
end ;
QCAM : begin
QCAMAPI_SetCooling( QCAMSession, Value ) ;
end ;
DCAM : begin
DCAMAPI_SetCooling( DCAMSession, Value ) ;
end ;
IMAQ : begin
end ;
IMAQDX : begin
end ;
DTOL : begin
end ;
PCOAPI : begin
// AndorSDK3_SetCooling( PCOAPISession, Value ) ;
end ;
end ;
end ;
procedure TSESCam.SetCameraFanMode(
Value : Integer
) ;
// --------------------------------
// Set camera fan on/off
// --------------------------------
begin
FCameraFanMode := Value ;
if FCameraActive then Exit ;
case FCameraType of
ITEX_CCIR : begin
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
end ;
IMAQ_1394 : begin
end ;
PIXELFLY : begin
end ;
Sensicam : Begin
end;
ANDOR : begin
Andor_SetFanMode( AndorSession, FCameraFanMode ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_SetFanMode( AndorSDK3Session, FCameraFanMode ) ;
end ;
QCAM : begin
end ;
DCAM : begin
DCAMAPI_SetFanMode( DCAMSession, FCameraFanMode ) ;
end ;
IMAQ : begin
end ;
IMAQDX : begin
end ;
DTOL : begin
end ;
end ;
end ;
procedure TSESCam.SetDisableEMCCD(
Value : Boolean
) ;
// --------------------------------
// Enable/disable EMCDD function
// --------------------------------
begin
FDisableEMCCD := Value ;
FCameraRestartRequired := True ;
if FCameraActive then Exit ;
case FCameraType of
ITEX_CCIR : begin
end ;
ITEX_C4880_10,ITEX_C4880_12 : begin
end ;
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
end ;
IMAQ_1394 : begin
end ;
PIXELFLY : begin
end ;
Sensicam : Begin
end;
ANDOR : begin
AndorSession.DisableEMCCD := FDisableEMCCD ;
end ;
QCAM : begin
end ;
DCAM : begin
end ;
IMAQ : begin
end ;
IMAQDX : begin
end ;
DTOL : begin
end ;
end ;
end ;
procedure TSESCam.SetCameraMode( Value : Integer ) ;
// ---------------------
// Set camera video mode
// ---------------------
begin
FCameraMode := Value ;
case FCameraType of
IMAQDX : begin
IMAQDX_SetVideoMode( IMAQDXSession,
Value,
FCameraADC,
FFrameWidthMax,
FFrameHeightMax,
FNumBytesPerPixel,
FPixelDepth,
FGreyLevelMin,
FGreyLevelMax ) ;
FFrameWidth := FFrameWidthMax ;
FFrameHeight := FFrameHeightMax ;
FFrameLeft := 0 ;
FFrameTop := 0 ;
end ;
ANDOR : begin
Andor_SetCameraMode( AndorSession, FCameraMode ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_SetCameraMode( AndorSDK3Session, FCameraMode ) ;
end ;
end ;
ImageAreaChanged := True ;
end ;
procedure TSESCam.SetCameraADC( Value : Integer ) ;
// ------------------------
// Set camera A/D converter
// ------------------------
begin
FCameraADC := Value ;
case FCameraType of
ANDOR : begin
Andor_SetCameraADC( AndorSession,
FCameraADC,
FPixelDepth,
FGreyLevelMin,
FGreyLevelMax ) ;
end ;
ANDORSDK3 : begin
AndorSDK3_SetCameraADC( AndorSDK3Session,
FCameraADC,
FPixelDepth,
FGreyLevelMin,
FGreyLevelMax ) ;
end ;
IMAQDX : begin
IMAQDX_SetPixelFormat( IMAQDXSession,
FCameraADC,
IMAQDXSession.NumBytesPerComponent,
FPixelDepth,
FGreyLevelMin,
FGreyLevelMax ) ;
FMaxComponentsPerPixel := Min(IMAQDXSession.NumPixelComponents,3) ;
end ;
end ;
ImageAreaChanged := True ;
end ;
procedure TSESCam.SetADCGain( Value : Integer ) ;
// -----------------------------
// Set camera A/D converter gain
// -----------------------------
begin
FADCGain := Value ;
case FCameraType of
ANDOR : begin
AndorSession.PreAmpGain := FADCGain ;
end ;
end ;
end ;
procedure TSESCam.SetCCDVerticalShiftSpeed( Value : Integer ) ;
// ---------------------------------
// Set CCD vertical line shift speed
// ---------------------------------
begin
FCCDVerticalShiftSpeed := Value ;
case FCameraType of
ANDOR : begin
AndorSession.VSSpeed := FCCDVerticalShiftSpeed ;
if AndorSession.VSSpeed < 0 then AndorSession.VSSpeed := AndorSession.DefaultVSSpeed ;
FCCDVerticalShiftSpeed := AndorSession.VSSpeed ;
end ;
end ;
end ;
procedure TSESCam.SetCCDPostExposureReadout( Value : Boolean ) ;
// ------------------------------
// Set post exposure readout mode
// ------------------------------
begin
FCCDPostExposureReadout := Value ;
case FCameraType of
RS_PVCAM,RS_PVCAM_PENTAMAX : begin
FCCDPostExposureReadout := FCCDPostExposureReadout or PVCAMSession.PostExposureReadout ;
end;
end;
end;
procedure TSESCam.SetMonochromeImage( Value : Boolean ) ;
// -------------------------------------------------------
// Set flag to extract monochrome image from colour source
// -------------------------------------------------------
begin
FMonochromeImage := Value ;
if FMonochromeImage then FNumComponentsPerPixel := 1
else FNumComponentsPerPixel := FMaxComponentsPerPixel ;
end;
procedure TSESCam.SetCCDYShift( Value : Double );
// ---------------------------------------------------
// Shift CCD stage Y position (fraction of pixel size)
// ---------------------------------------------------
begin
case FCameraType of
IMAQ :
begin
FCCDYShift := Value ;
IMAQ_SetCCDYShift( IMAQSession,Value)
end;
end;
end;
procedure TSESCam.SetCCDXShift( Value : Double );
// ---------------------------------------------------
// Shift CCD stage X position (fraction of pixel size)
// ---------------------------------------------------
begin
case FCameraType of
IMAQ :
begin
FCCDXShift := Value ;
IMAQ_SetCCDXShift( IMAQSession,Value)
end;
end;
end;
procedure TSESCam.SetLightSpeedMode( Value : Boolean ) ;
// ------------------------------------------------------
// Enable/disable LightSpeed mode for Evolve Delta camera
// ------------------------------------------------------
begin
FLightSpeedMode := Value ;
case FCameraType of
RS_PVCAM : PVCAM_SetLightSpeedMode( PVCAMSession, FLightSpeedMode ) ;
end;
end;
end.
|
unit uGerarPlanilhaGeral;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, DB, ZAbstractRODataset,
ZAbstractDataset, ZDataset, ComObj, DateUtils, Mask;
type
arrayDate = Array of TDate;
type
TfGerarPlanilhaGeral = class(TForm)
group: TGroupBox;
lbldata: TLabel;
Status: TStatusBar;
panelBarra: TPanel;
ProgressBar: TProgressBar;
btnGerar: TBitBtn;
CGA035: TZQuery;
CGA036: TZQuery;
CGA039: TZQuery;
CGA040: TZQuery;
CGA038: TZQuery;
CGA120: TZQuery;
CGA100: TZQuery;
CGA044: TZQuery;
SaveDialog: TSaveDialog;
lblPlanilha: TLabel;
cbdtini: TDateTimePicker;
cbdtfim: TDateTimePicker;
CGA78: TZQuery;
CGA043: TZQuery;
CGA042: TZQuery;
CGA041: TZQuery;
CGA130: TZQuery;
CGA69: TZQuery;
CGA68: TZQuery;
CGA33: TZQuery;
CGA75: TZQuery;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnGerarClick(Sender: TObject);
private
{ Private declarations }
xDtInicial, xDtFinal : TDate;
listOfQuery : TList;
tabelasExcecao : Array[0..1] of String;
Function AjustarProgressBar(progress : TProgressBar; arrayQuery : TList) : Boolean;
Function AbrirTabelas(dtini : TDate; dtfim : TDate) : Boolean;
Function GerarExcel(Query : TZQuery; nomeProduto : String; excel : Variant; var linha : Integer) : Boolean;
Function VerificarTabelaExcecao(nome : String) : Boolean;
public
{ Public declarations }
end;
var
fGerarPlanilhaGeral: TfGerarPlanilhaGeral;
implementation
uses DmDados;
{$R *.dfm}
Function TfGerarPlanilhaGeral.VerificarTabelaExcecao(nome : String) : Boolean;
var
I: Integer;
begin
try
for I := 0 to Length(tabelasExcecao) - 1 do
begin
if nome = tabelasExcecao[I] then
begin
Result := True;
Exit;
end;
end;
Result := False;
except
on E: Exception do
begin
Result := True;
end;
end;
end;
Function TfGerarPlanilhaGeral.AjustarProgressBar(progress : TProgressBar; arrayQuery : TList) : Boolean;
var
I: Integer;
begin
try
progress.Min := 0;
progress.Max := 0;
progress.Position := 0;
progress.Step := 1;
for I := 0 to arrayQuery.Count - 1 do
begin
progress.Max := progress.Max + TZQuery(arrayQuery.Items[I]).RecordCount;
end;
Result := True;
except
on E: Exception do
begin
Result := False;
end;
end;
end;
Function TfGerarPlanilhaGeral.AbrirTabelas(dtini : TDate; dtfim : TDate) : Boolean;
var
Query : TZQuery;
I: Integer;
xComponente : TComponent;
xCampoData, xCampoCodBaixa : String;
begin
try
for I := 0 to Self.ComponentCount - 1 do
begin
xComponente := Self.Components[I];
if UpperCase(xComponente.ClassName) = 'TZQUERY' then
begin
Query := TZQuery(xComponente);
if not VerificarTabelaExcecao(Query.Name) then
begin
if UpperCase(Copy(Query.Name, 1, 3)) = 'CGA' then
begin
xCampoData := 'CG'+Trim(Copy(Query.Name, 4, 100))+'_DTBAIXA';
Query.Close;
Query.SQL.Clear;
Query.Params.Clear;
Query.SQL.Add('SELECT');
Query.SQL.Add(' COUNT(*) AS QTD, '+xCampoData+' AS DATA');
Query.SQL.Add('FROM');
Query.SQL.Add(' '+Query.Name+' CGA');
Query.SQL.Add('WHERE');
Query.SQL.Add(' CGA.'+xCampoData+' >= :XPDTINI');
Query.SQL.Add(' AND CGA.'+xCampoData+' <= :XPDTFIM');
Query.SQL.Add('GROUP BY');
Query.SQL.Add(' '+xCampoData);
Query.SQL.Add('ORDER BY');
Query.SQL.Add(' '+xCampoData);
Query.ParamByName('XPDTINI').AsDate := dtini;
Query.ParamByName('XPDTFIM').AsDate := dtfim;
Query.Open;
Query.First;
end;
end
else
begin
//exceção encontrada nos relatórios em U_PesqImp
//TAG 5: // extrato unificado
//TAG 42: // Produçao DRC-Aviso de Cobrança CLLP
xCampoData := 'CG'+Trim(Copy(Query.Name, 4, 100))+'_DTBAIXA';
xCampoCodBaixa := 'CG'+Trim(Copy(Query.Name, 4, 100))+'_CODBAIXA';
Query.Close;
Query.SQL.Clear;
Query.Params.Clear;
Query.SQL.Add('SELECT');
Query.SQL.Add(' COUNT(*) AS QTD, '+xCampoData+' AS DATA');
Query.SQL.Add('FROM');
Query.SQL.Add(' '+Query.Name+' CGA');
Query.SQL.Add('WHERE');
Query.SQL.Add(' CGA.'+xCampoData+' >= :XPDTINI');
Query.SQL.Add(' AND CGA.'+xCampoData+' <= :XPDTFIM');
Query.SQL.Add(' AND CGA.'+xCampoCodBaixa+' <> :XPCODBAIXA');
Query.SQL.Add('GROUP BY');
Query.SQL.Add(' '+xCampoData);
Query.SQL.Add('ORDER BY');
Query.SQL.Add(' '+xCampoData);
Query.ParamByName('XPDTINI').AsDate := dtini;
Query.ParamByName('XPDTFIM').AsDate := dtfim;
Query.ParamByName('XPCODBAIXA').AsString := '119';
Query.Open;
Query.First;
end;
end;
end;
Result := True;
except
on E: Exception do
begin
Result := False;
end;
end;
end;
Function TfGerarPlanilhaGeral.GerarExcel(Query : TZQuery; nomeProduto : String; excel : Variant; var linha : Integer) : Boolean;
var
xLinha :integer;
xPlanilha : Variant;
xTotal: Integer;
begin
try
xLinha := linha;
{
xPlanilha.Cells[xLinha,1] := 'Produto';
xPlanilha.Cells[xLinha,1].Font.Bold := True;
xPlanilha.Cells[xLinha,2] := 'Data';
xPlanilha.Cells[xLinha,2].Font.Bold := True;
xPlanilha.Cells[xLinha,3] := 'Qtde.';
xPlanilha.Cells[xLinha,3].Font.Bold := True;
}
lblPlanilha.Caption := nomeProduto;
Application.ProcessMessages;
xPlanilha := excel.WorkBooks[1].WorkSheets['Relat_Geral'];
if (Query.IsEmpty) or
(Query.RecordCount <= 0) then
begin
Result := False;
Exit;
end;
xLinha := xLinha + 1;
Query.First;
while not Query.Eof do
begin
Application.ProcessMessages;
if Query.RecNo = 1 then
begin
xPlanilha.Cells[xLinha, 1] := nomeProduto;
end;
xPlanilha.Cells[xLinha, 2] := Query.FieldByName('DATA').AsDateTime;
xPlanilha.Cells[xLinha, 3] := Query.FieldByName('QTD').AsInteger;
xTotal := xTotal + Query.FieldByName('QTD').AsInteger;
xLinha := xLinha + 1;
Query.Next;
Application.ProcessMessages;
Status.Panels[0].Text := 'Processando '+IntToStr(ProgressBar.Position)+' de '+IntToStr(ProgressBar.Max);
ProgressBar.StepIt;
Application.ProcessMessages;
end;
xPlanilha.Cells[xLinha, 4].Font.Color := clred;
xPlanilha.Cells[xLinha, 4].Font.Bold := True;
xPlanilha.Cells[xLinha, 4] := xTotal;
xLinha := xLinha + 1;
Status.Panels[0].Text := '';
Excel.columns.AutoFit;
Result := True;
linha := xLinha;
except
on E: Exception do
begin
Result := False;
end;
end;
end;
procedure TfGerarPlanilhaGeral.FormClose(Sender: TObject; var Action: TCloseAction);
var
I: Integer;
begin
if panelBarra.Visible then
begin
Action := caNone;
Exit;
end;
for I := 0 to Self.ComponentCount - 1 do
begin
if Trim(UpperCase(Self.Components[I].ClassName)) = 'TZQUERY' then
begin
try
TZQuery(Self.Components[I]).Close;
except on E: Exception do
end;
end;
end;
end;
procedure TfGerarPlanilhaGeral.FormCreate(Sender: TObject);
begin
cbdtini.Date := Trunc(Now);
cbdtfim.Date := Trunc(Now);
tabelasExcecao[0] := 'CGA78';
tabelasExcecao[1] := 'CGA68';
end;
procedure TfGerarPlanilhaGeral.btnGerarClick(Sender: TObject);
var
xDiretorio : String;
xDtAux : TDate;
excel : Variant;
xInstallExcel : Boolean;
xPlanilha : Variant;
xLinha : Integer;
begin
try
if panelBarra.Visible then
begin
Exit;
end;
if cbdtini.Date = 0 then
begin
Application.MessageBox('Selecione a data inicial do período !', 'Atenção', MB_OK+MB_ICONWARNING);
cbdtini.SetFocus;
Exit;
end;
if cbdtfim.Date = 0 then
begin
Application.MessageBox('Selecione a data final do período !', 'Atenção', MB_OK+MB_ICONWARNING);
cbdtfim.SetFocus;
Exit;
end;
cbdtini.Date := Trunc(cbdtini.Date);
cbdtfim.Date := Trunc(cbdtfim.Date);
if cbdtini.Date > cbdtfim.Date then
begin
if Application.MessageBox('As datas aparentemente estão invertidas, deseja que o sistema inverta ou prefere corrigi-la manualmente ? Sim(Automático) ou Não(Manual).', 'Confirmação', MB_YESNO+MB_ICONQUESTION) = ID_YES then
begin
xDtAux := cbdtini.Date;
cbdtini.Date := cbdtfim.Date;
cbdtfim.Date := xDtAux;
end
else
begin
cbdtini.SetFocus;
Exit;
end;
end;
SaveDialog.Execute;
xDiretorio := ExtractFilePath(SaveDialog.FileName);
if (Trim(xDiretorio) = '') or
(not DirectoryExists(xDiretorio)) then
begin
Application.MessageBox('Defina o local onde os arquivos serão salvos !', 'Atenção', MB_OK+MB_ICONWARNING);
Exit;
end;
Application.Minimize;
xDtInicial := Trunc(cbdtini.Date);
xDtFinal := Trunc(cbdtfim.Date);
if not AbrirTabelas(xDtInicial, xDtFinal) then
begin
Application.MessageBox('Não foi possível abrir as tabelas necessárias !', 'ERRO', MB_OK+MB_ICONERROR);
Exit;
end;
try
excel := CreateOleObject('\excel.application\');
excel.WorkBooks.Add;
excel.WorkBooks[1].WorkSheets.Add;
excel.WorkBooks[1].WorkSheets[1].Name := 'Relat_Geral';
xPlanilha := excel.WorkBooks[1].WorkSheets['Relat_Geral'];
xPlanilha.Cells[1,1] := 'Produto';
xPlanilha.Cells[1,1].Font.Bold := True;
xPlanilha.Cells[1,2] := 'Data';
xPlanilha.Cells[1,2].Font.Bold := True;
xPlanilha.Cells[1,3] := 'Qtde.';
xPlanilha.Cells[1,3].Font.Bold := True;
xInstallExcel := True;
except
on E: Exception do
begin
xInstallExcel := False;
end;
end;
if xInstallExcel then
begin
listOfQuery := TList.Create;
listOfQuery.Add(CGA035);
listOfQuery.Add(CGA036);
listOfQuery.Add(CGA100);
listOfQuery.Add(CGA120);
listOfQuery.Add(CGA039);
listOfQuery.Add(CGA038);
listOfQuery.Add(CGA040);
listOfQuery.Add(CGA044);
listOfQuery.Add(CGA043);
listOfQuery.Add(CGA042);
listOfQuery.Add(CGA041);
listOfQuery.Add(CGA78);
listOfQuery.Add(CGA75);
listOfQuery.Add(CGA33);
listOfQuery.Add(CGA68);
listOfQuery.Add(CGA69);
listOfQuery.Add(CGA130);
AjustarProgressBar(ProgressBar, listOfQuery);
panelBarra.Visible := True;
xLinha := 2;
GerarExcel(CGA035, 'Consórcio -> Produção Carta Senha', excel, xLinha);
GerarExcel(CGA036, 'Consórcio -> Extrato Consorciado', excel, xLinha);
GerarExcel(CGA100, 'Boleto de Recuperação de Crédito', excel, xLinha);
GerarExcel(CGA120, 'DRC Carta Convite', excel, xLinha);
GerarExcel(CGA039, 'Extrato Finasa -> Boleto - CLI', excel, xLinha);
GerarExcel(CGA038, 'Extrato Finasa -> Extrato - FPE', excel, xLinha);
GerarExcel(CGA040, 'Extrato Finasa -> Carta - CLI', excel, xLinha);
GerarExcel(CGA044, 'DRC Amex', excel, xLinha);
GerarExcel(CGA043, 'DRC ZOGBI - MCSI', excel, xLinha);
GerarExcel(CGA042, 'DRC Cartão Fatura', excel, xLinha);
GerarExcel(CGA041, 'DRC Private Label', excel, xLinha);
GerarExcel(CGA78, 'DRC Aviso de Cobrança - CLLP', excel, xLinha);
GerarExcel(CGA75, 'Extrato Consolidado', excel, xLinha);
GerarExcel(CGA33, 'Extrato Conta Corrente Poupança', excel, xLinha);
GerarExcel(CGA68, 'Extrato Unificado', excel, xLinha);
GerarExcel(CGA69, 'Extrato CVM / INVE', excel, xLinha);
GerarExcel(CGA130, 'TanCode', excel, xLinha);
excel.WorkBooks[1].Sheets[2].Delete;
excel.WorkBooks[1].Sheets[2].Delete;
excel.WorkBooks[1].Sheets[2].Delete;
panelBarra.Visible := False;
ProgressBar.Position := 0;
Application.Restore;
try
excel.WorkBooks[1].SaveAs(SaveDialog.FileName);
except
Application.MessageBox('Não foi possível salvar a planilha, salve-a antes de fechá-la !', 'Informação', MB_OK+MB_ICONINFORMATION);
end;
excel.Visible :=True;
Application.MessageBox('Planilha(s) gerada(s) com sucesso !', 'Sucesso', MB_OK+MB_ICONINFORMATION);
end
else
begin
Application.MessageBox('Para gerar planilhas é necessário ter o Excel instalado na máquina! Verifique.', 'Atenção', MB_OK+MB_ICONWARNING);
end;
except
on E: Exception do
begin
Application.MessageBox(PCHAR('Ocorreu um problema durante a geração da(s) planilhas! Erro:'+E.Message), 'ERRO', MB_OK+MB_ICONERROR);
panelBarra.Visible := False;
Status.Panels[0].Text := '';
Exit;
end;
end;
end;
{
método anterior (pega todos os dias entre as datas)
xDias := 0;
while IncDay(xDtFinal, -xDias) >= xDtInicial do
begin
xPlanilha.Cells[1,3+xDias] := StrToDate(FormatDateTime('DD/MM/YYYY', (xDtFinal-xDias)));
xDias := xDias + 1;
end;}
{
Query.First;
xFamiliaAtu := Query.FieldByName('DESCRICAO').AsString;
xMotivoAtu := Query.FieldByName('DS_MOTIVO').AsString;
while not Query.Eof do
begin
if Query.FieldByName('DESCRICAO').AsString <> '' then
begin
if (xFamiliaAnt <> xFamiliaAtu) then
begin
xLinha := xLinha + 1;
xPlanilha.Cells[xLinha, 1] := Query.FieldByName('DESCRICAO').AsString;
xPlanilha.Cells[xLinha, 2] := Query.FieldByName('DS_MOTIVO').AsString;
end
else
begin
if (xMotivoAnt <> xMotivoAtu) then
begin
xLinha := xLinha + 1;
xPlanilha.Cells[xLinha, 2] := Query.FieldByName('DS_MOTIVO').AsString;
end;
end;
for I := 0 to Length(datas)-1 do
begin
if Query.FieldByName('DT_DEVOLUCAO').AsDateTime = datas[I] then
begin
xPlanilha.Cells[xLinha,colunaDias+I]:= Query.FieldByName('QTDDIA').AsInteger;
end
else
begin
xPlanilha.Cells[xLinha,colunaDias+I]:= 0;
end;
end;
end
else
begin
xLinha := xLinha + 1;
xPlanilha.Cells[xLinha, 2] := Query.FieldByName('DS_MOTIVO').AsString;
for I := 0 to Length(datas)-1 do
begin
xPlanilha.Cells[xLinha,colunaDias+I]:= 0;
end;
end;
xFamiliaAnt := Query.FieldByName('DESCRICAO').AsString;
xMotivoAnt := Query.FieldByName('DS_MOTIVO').AsString;
Query.Next;
xFamiliaAtu := Query.FieldByName('DESCRICAO').AsString;
xMotivoAtu := Query.FieldByName('DS_MOTIVO').AsString;
end;
}
end.
|
{ Subroutine STRING_F_INT_MAX (S, I)
*
* Make the string representation of integer I in string S. The string will be
* truncated on the right to the maximum size of S.
}
module string_f_int_max;
define string_f_int_max;
%include 'string2.ins.pas';
procedure string_f_int_max ( {make string from largest available integer}
in out s: univ string_var_arg_t; {output string}
in i: sys_int_max_t); {input integer}
val_param;
var
stat: sys_err_t; {error code}
begin
string_f_int_max_base ( {make string from integer}
s, {output string}
i, {input integer}
10, {number base}
0, {use free format, no fixed field width}
[], {signed number, no lead zeros or plus}
stat);
sys_error_abort (stat, 'string', 'internal', nil, 0);
end;
|
unit uPlace;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo,
FMX.Layouts, FMX.ImgList, FMX.TabControl,
uTabFrame, FullScreenTabs;
type
TPlaceFrame = class(TTabFrame)
TabItem1: TTabItem;
Main1: TLayout;
Map: TGlyph;
Text: TMemo;
TabItem2: TTabItem;
Main2: TLayout;
s0: TLayout;
img0: TGlyph;
Text0: TText;
s1: TLayout;
img1: TGlyph;
Text1: TText;
s2: TLayout;
img2: TGlyph;
Text2: TText;
s3: TLayout;
img3: TGlyph;
Text3: TText;
protected
procedure onFCreate; override;
procedure onFDestroy; override;
public
procedure onFShow; override;
procedure isWin(tab: FSTab);
end;
implementation
{$R *.fmx}
var
fTabs: FSTabs;
procedure TPlaceFrame.onFCreate;
begin
layouts:=[main1, main2];
gTab:=1;
fTabs:=FSTabs.create(self, main2, isWin);
inherited;
end;
procedure TPlaceFrame.onFDestroy;
begin
fTabs.Free;
end;
procedure TPlaceFrame.onFShow;
begin
fTabs.setSize(true, true);
inherited;
end;
procedure TPlaceFrame.isWin(tab: FSTab);
begin
if tab.layer.TabOrder=2 then
begin
win;
if not fail then setMedal(1);
end else wrong;
end;
end.
|
unit unitNTRegistry;
interface
uses Windows, Classes, SysUtils, Registry;
type
TNTRegistry = class (TRegistry)
public
function GetMultiSZ (const valueName : string; sl : TStrings) : Integer;
end;
implementation
{ TNTRegistry }
function TNTRegistry.GetMultiSZ(const valueName: string; sl: TStrings): Integer;
var
st : string;
tp, cb : DWORD;
i : Integer;
begin
cb := 0;
sl.Clear;
if RegQueryValueEx (CurrentKey, PChar (valueName), Nil, @tp, Nil, @cb) = ERROR_SUCCESS then
begin
if tp <> REG_MULTI_SZ then
raise ERegistryException.Create('Not a MULTI_SZ value');
SetLength (st, cb);
if RegQueryValueEx (CurrentKey, PChar (valueName), Nil, @tp, PByte (PChar (st)), @cb) = ERROR_SUCCESS then
begin
i := 1;
while (Length (st) > 0) and (st [Length (st)] = #0) do
Delete (st, Length (st), 1);
while i <= Length (st) do
begin
if st [i] = #0 then
st [i] := #1;
Inc (i);
end;
sl.Delimiter := #1;
sl.DelimitedText := st
end
end;
result := sl.Count
end;
end.
|
unit UTypes;
interface
uses
Classes,
eiTypes;
type
ViewModeEnum = (vmSingle, vmBlock, vmInfo);
HelperTypeEnum = (htNone, htStatusClear);
IView = interface
procedure ClearStatus();
function GetAddress: int;
function GetDataType: DataTypeEnum;
function GetHost: string;
function GetLength: byte;
function GetStatus: string;
function GetValue: Integer;
function GetViewMode: ViewModeEnum;
procedure SetAddress(const value: int);
procedure SetHost(const value: string);
procedure SetInfoValues(const values: TStrings);
procedure SetLength(const value: byte);
procedure SetStatus(const value: string);
procedure SetValue(const value: Integer);
procedure SetValues(const values: TStrings);
property Address: int read GetAddress write SetAddress;
property DataType: DataTypeEnum read GetDataType;
property Host: string read GetHost write SetHost;
property Length: byte read GetLength write SetLength;
property Status: string read GetStatus write SetStatus;
property Value: Integer read GetValue write SetValue;
property ViewMode: ViewModeEnum read GetViewMode;
end;
IPresenter = interface
procedure Refresh;
procedure WriteSingle;
end;
IPlcService = interface
function Read(host: string; offset: Integer; dataType: DataTypeEnum): Word;
function ReadBlock(host: string; offset: Integer; dataType: DataTypeEnum; length: byte): DynamicWordArray;
function ReadInfo(host: string): EasyIpInfoPacket;
procedure Write(host: string; offset: Integer; dataType: DataTypeEnum; value: Word);
end;
ISettings = interface
procedure Load(view: IView);
procedure Save(view: IView);
end;
implementation
end.
|
unit Form.Main;
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Component.GraphicNumber, Vcl.StdCtrls, Vcl.ExtCtrls, System.Actions,
Vcl.ActnList;
type
TForm1 = class(TForm)
grbxOptions: TGroupBox;
GroupBox2: TGroupBox;
Label1: TLabel;
edtIncrease: TEdit;
Splitter1: TSplitter;
ActionList1: TActionList;
Action1: TAction;
CheckBox1: TCheckBox;
procedure Action1Execute(Sender: TObject);
procedure CheckBox1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
GraphicNumber: TGraphicNumber;
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Action1Execute(Sender: TObject);
begin
with GraphicNumber do
Number := Number + StrToInt(edtIncrease.Text);
end;
procedure TForm1.CheckBox1Click(Sender: TObject);
begin
GraphicNumber.Enabled := CheckBox1.Checked;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
aParent: TWinControl;
begin
aParent := GroupBox2;
GraphicNumber := TGraphicNumber.Create(aParent);
GraphicNumber.AlignWithMargins := True;
GraphicNumber.Margins.Bottom := 0;
GraphicNumber.Align := alTop;
GraphicNumber.Parent := aParent;
GraphicNumber.Action := Action1;
// ----------
with TSplitter.Create(aParent) do begin
Parent := aParent;
Top := 999;
Align := alTop;
Height := 5;
end;
end;
end.
|
unit UCadHospedesFJ;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UBaseCadastro, Data.DB, Vcl.Buttons,
Vcl.ExtCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
dxSkinsCore, dxSkinsDefaultPainters, cxPC, cxContainer, cxEdit, Vcl.StdCtrls,
dxGDIPlusClasses, cxButtonEdit, cxDropDownEdit, cxDBEdit, cxTextEdit,
cxMaskEdit, cxCalendar, ACBrBase, ACBrValidador, System.Actions, Vcl.ActnList,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, 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,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, dxSkinBlueprint,
dxSkinDevExpressDarkStyle, dxSkinLilian, dxSkinOffice2007Black,
dxSkinOffice2010Black, dxSkinVisualStudio2013Blue, dxSkinXmas2008Blue;
type
TF_cadHospedesFJ = class(TF_baseCadastro)
pg: TcxPageControl;
tbsFisica: TcxTabSheet;
tbsJuridica: TcxTabSheet;
dtaNascimento: TcxDBDateEdit;
edtApelido: TcxDBTextEdit;
edtBairro: TcxDBTextEdit;
edtCelular: TcxDBMaskEdit;
edtCep: TcxDBMaskEdit;
edtCidade: TcxDBTextEdit;
edtCodigo: TcxDBTextEdit;
edtContato1: TcxDBTextEdit;
edtContato2: TcxDBTextEdit;
edtCPF: TcxDBMaskEdit;
edtEmail: TcxDBTextEdit;
edtEndereco: TcxDBTextEdit;
edtEstCivil: TcxDBComboBox;
edtFone: TcxDBMaskEdit;
edtFoneC1: TcxDBMaskEdit;
edtFoneC2: TcxDBMaskEdit;
edtLocTrabalho: TcxDBTextEdit;
edtNacionalidade: TcxDBTextEdit;
edtNaturalidade: TcxDBTextEdit;
edtNome: TcxDBTextEdit;
edtNumero: TcxDBTextEdit;
edtObs: TcxDBTextEdit;
edtProfissao: TcxDBComboBox;
edtRegiao: TcxButtonEdit;
edtRG: TcxDBTextEdit;
edtSexo: TcxDBComboBox;
edtSite: TcxDBTextEdit;
edtUF: TcxDBTextEdit;
imgBack: TImage;
lblApelido: TLabel;
lblBairro: TLabel;
lblCelular: TLabel;
lblCep: TLabel;
lblCidade: TLabel;
lblCod: TLabel;
lblContato1: TLabel;
lblContato2: TLabel;
lblCPF: TLabel;
lblDtaNascimento: TLabel;
lblEmail: TLabel;
lblEndereco: TLabel;
lblEstadoCivil: TLabel;
lblFone: TLabel;
lblFoneContato2: TLabel;
lblFoneContato1: TLabel;
lblLocTrabalho: TLabel;
lblNacionalidade: TLabel;
lblNaturalidade: TLabel;
lblNome: TLabel;
lblNumero: TLabel;
lblObs: TLabel;
lblProfissao: TLabel;
lblRegiao: TLabel;
lblRG: TLabel;
lblSexo: TLabel;
lblSite: TLabel;
lblUF: TLabel;
ACM_cadHospedeF: TActionManager;
actRegiaoF: TAction;
ACBrValidadorCPF: TACBrValidador;
pnlJ: TPanel;
dtaFundacao: TcxDBDateEdit;
edtBairroJ: TcxDBTextEdit;
edtCelularJ: TcxDBMaskEdit;
edtCepJ: TcxDBMaskEdit;
edtCidadeJ: TcxDBTextEdit;
edtCNPJ: TcxDBMaskEdit;
edtCodigoJ: TcxDBTextEdit;
edtContato1J: TcxDBTextEdit;
edtContato2J: TcxDBTextEdit;
edtEmailJ: TcxDBTextEdit;
edtEnderecoJ: TcxDBTextEdit;
edtFantasia: TcxDBTextEdit;
edtFoneJ: TcxDBMaskEdit;
edtFoneC1J: TcxDBMaskEdit;
edtFoneC2J: TcxDBMaskEdit;
edtIE: TcxDBTextEdit;
edtNumeroJ: TcxDBTextEdit;
edtObsJ: TcxDBTextEdit;
edtRazaoSocial: TcxDBTextEdit;
edtRegiaoJ: TcxButtonEdit;
edtSiteJ: TcxDBTextEdit;
edtUFJ: TcxDBTextEdit;
Image1: TImage;
lblBairroJ: TLabel;
lblCelularJ: TLabel;
lblCepJ: TLabel;
lblCidadeJ: TLabel;
lblCJPJ: TLabel;
lblCodJ: TLabel;
lblContato1J: TLabel;
lblContato2J: TLabel;
lblDtaFundacao: TLabel;
lblEmailJ: TLabel;
lblEnderecoJ: TLabel;
lblFantasia: TLabel;
lblFoneJ: TLabel;
lbllblFoneContato2J: TLabel;
lblFoneContato1J: TLabel;
lblIE: TLabel;
lblNumeroJ: TLabel;
lblObsJ: TLabel;
lblRazaoSocial: TLabel;
lblRegiaoJ: TLabel;
lblSiteJ: TLabel;
lblUFJ: TLabel;
ACM_cadHospedeJ: TActionManager;
actRegiaoJ: TAction;
QRY_verificaCliente: TFDQuery;
QRY_verificaClienteCLI_CODIGO: TIntegerField;
QRY_verificaClienteCLI_CNPJ: TStringField;
ACBrValidadorCNPJ: TACBrValidador;
procedure btnSalvarClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnEditarClick(Sender: TObject);
procedure btnDeletarClick(Sender: TObject);
procedure btnLocalizarClick(Sender: TObject);
procedure edtRegiaoExit(Sender: TObject);
procedure edtCPFExit(Sender: TObject);
procedure edtCNPJExit(Sender: TObject);
procedure edtRegiaoPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure edtSexoEnter(Sender: TObject);
procedure edtRegiaoJExit(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
{ Public declarations }
var tipoFJ: String;
codCliente: Integer;
end;
var
F_cadHospedesFJ: TF_cadHospedesFJ;
implementation
{$R *.dfm}
uses UDMConexao, UDMHospedes, UMsg, UFJ, UPesquisaHospedes, UFunctions,
UPesquisaRegiao, UEntraHospede, UReservaApto;
procedure TF_cadHospedesFJ.btnCancelarClick(Sender: TObject);
begin {cancelar}
inherited;
DS_cadastro.DataSet.Cancel;
end;
procedure TF_cadHospedesFJ.btnDeletarClick(Sender: TObject);
begin {deletar}
inherited;
end;
procedure TF_cadHospedesFJ.btnEditarClick(Sender: TObject);
begin {editar}
inherited;
DS_cadastro.DataSet.Edit;
end;
procedure TF_cadHospedesFJ.btnLocalizarClick(Sender: TObject);
begin {localizar}
inherited;
CriaFormDestroy(TF_pesquisaHospede, F_pesquisaHospede);
end;
procedure TF_cadHospedesFJ.btnNovoClick(Sender: TObject);
begin {novo}
inherited;
DS_cadastro.DataSet.Append;
if tipoFJ = 'F' then begin
pg.ActivePage := tbsFisica;
Height := 558;
if edtCPF.CanFocus then begin
edtCPF.SetFocus;
end;
end
else begin
pg.ActivePage := tbsJuridica;
Height := 558;
if edtCNPJ.CanFocus then begin
edtCNPJ.SetFocus;
end;
end;
end;
procedure TF_cadHospedesFJ.btnSalvarClick(Sender: TObject);
begin {salvar}
inherited;
if tipoFJ = 'F' then begin
try
F_dmConexao.FDConn.StartTransaction;
{1º passa os dados}
F_dmHospedes.QRY_cadHospedeCLI_REGIAO.AsInteger := StrToInt(edtRegiao.Text);
F_dmHospedes.QRY_cadHospedeCLI_SEGUIMENTO.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_CONTRIBUINTE.AsString := '9';
F_dmHospedes.QRY_cadHospedeCLI_PAIS.AsInteger := 1058;
F_dmHospedes.QRY_cadHospedeCLI_COPCAIXA.AsInteger := 0;
F_dmHospedes.QRY_cadHospedeCLI_ATIVO.AsString := 'A';
F_dmHospedes.QRY_cadHospedeCLI_CLIENTEENQUETE.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_GOVERNO.AsString := 'N';
F_dmHospedes.QRY_cadHospedeCLI_CONSFINAL.AsString := '1';
F_dmHospedes.QRY_cadHospedeCLI_TIPOEND.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_SETOR.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_TIPOFJ.AsString := 'F';
{2º gera a chave}
if F_dmHospedes.QRY_cadHospede.State in [dsInsert] then begin
if F_dmHospedes.QRY_cadHospedeCLI_CODIGO.AsInteger < 1 then
begin
if not F_dmConexao.GeraChave('CLIENTE', F_dmHospedes.QRY_cadHospedeCLI_CODIGO) then
begin
abort;
end;
end;
{3º insere os dados - está aqui dentro caso seja edit, não passa aqui novamente. Só se for insert}
F_dmHospedes.QRY_cadHospedeCLI_CODIGO.AsInteger := F_dmConexao.QRY_entidadeENT_CHAVE.Value;
end;
CodCliente := F_dmHospedes.QRY_cadHospedeCLI_CODIGO.AsInteger; {salvo o codigo para mostrar o cliente na tela.}
DS_cadastro.DataSet.Post;
F_dmHospedes.QRY_cadHospede.ApplyUpdates();
F_dmConexao.FDConn.Commit;
except on e:Exception do begin
F_dmHospedes.QRY_cadHospedeCLI_CODIGO.Clear;
F_dmConexao.FDConn.Rollback;
{showMessage('Erro '+e.Message);}
TF_msg.Mensagem('Não foi possível cadastrar o Hóspede. Verifique todos os campos e tente novamente','I',[mbOk]);
exit;
end;
end;
{Mostra o hóspede na tela}
F_dmHospedes.QRY_cadHospede.Close;
F_dmHospedes.QRY_cadHospede.Params[0].AsInteger := CodCliente;
F_dmHospedes.QRY_cadHospede.Open();
end
else begin
try
F_dmConexao.FDConn.StartTransaction;
{1º passa os dados}
F_dmHospedes.QRY_cadHospedeCLI_REGIAO.AsInteger := StrToInt(edtRegiaoJ.Text);
F_dmHospedes.QRY_cadHospedeCLI_SEGUIMENTO.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_CONTRIBUINTE.AsString := '1';
F_dmHospedes.QRY_cadHospedeCLI_PAIS.AsInteger := 1058;
F_dmHospedes.QRY_cadHospedeCLI_COPCAIXA.AsInteger := 0;
F_dmHospedes.QRY_cadHospedeCLI_ATIVO.AsString := 'A';
F_dmHospedes.QRY_cadHospedeCLI_CLIENTEENQUETE.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_GOVERNO.AsString := 'N';
F_dmHospedes.QRY_cadHospedeCLI_CONSFINAL.AsString := '1';
F_dmHospedes.QRY_cadHospedeCLI_TIPOEND.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_SETOR.AsInteger := 1;
F_dmHospedes.QRY_cadHospedeCLI_TIPOFJ.AsString := 'J';
{2º gera a chave}
if F_dmHospedes.QRY_cadHospede.State in [dsInsert] then begin
if F_dmHospedes.QRY_cadHospedeCLI_CODIGO.AsInteger < 1 then
begin
if not F_dmConexao.GeraChave('CLIENTE', F_dmHospedes.QRY_cadHospedeCLI_CODIGO) then
begin
abort;
end;
end;
{3º insere os dados - está aqui dentro caso seja edit, não passa aqui novamente. Só se for insert}
F_dmHospedes.QRY_cadHospedeCLI_CODIGO.AsInteger := F_dmConexao.QRY_entidadeENT_CHAVE.Value;
end;
CodCliente := F_dmHospedes.QRY_cadHospedeCLI_CODIGO.AsInteger; {salvo o codigo para mostrar o cliente na tela.}
DS_cadastro.DataSet.Post;
F_dmHospedes.QRY_cadHospede.ApplyUpdates();
F_dmConexao.FDConn.Commit;
except on e:Exception do begin
F_dmHospedes.QRY_cadHospedeCLI_CODIGO.Clear;
F_dmConexao.FDConn.Rollback;
{showMessage('Erro '+e.Message);}
TF_msg.Mensagem('Não foi possível cadastrar o Hóspede. Verifique todos os campos e tente novamente','I',[mbOk]);
exit;
end;
end;
{Mostra o hóspede na tela}
F_dmHospedes.QRY_cadHospede.Close;
F_dmHospedes.QRY_cadHospede.Params[0].AsInteger := CodCliente;
F_dmHospedes.QRY_cadHospede.Open();
end;
{verifica se o hóspede foi cadastrado pelo entraHospede - manda para a tela F_entraHospede}
if F_entraHospede <> nil then begin
if tipoFJ = 'F' then begin
F_entraHospede.edtCodCli.Text := edtCodigo.Text;
F_entraHospede.edtCliente.Text := edtNome.Text;
{fecha as telas abertas}
F_fj.Close;
F_pesquisaHospede.Close;
Self.Close;
exit;
end
else begin
F_entraHospede.edtCodCli.Text := edtCodigoJ.Text;
F_entraHospede.edtCliente.Text := edtRazaoSocial.Text;
{fecha as telas abertas}
F_fj.Close;
F_pesquisaHospede.Close;
Self.Close;
exit;
end;
end;
{verifica se o hóspede foi cadastrado pelo reservaApto - manda para a tela F_reservaApto}
if F_reservaApto <> nil then begin
if tipoFJ = 'F' then begin
F_reservaApto.edtCodCli.Text := edtCodigo.Text;
F_reservaApto.edtCliente.Text := edtNome.Text;
{fecha as telas abertas}
F_fj.Close;
F_pesquisaHospede.Close;
Self.Close;
exit;
end
else begin
F_reservaApto.edtCodCli.Text := edtCodigoJ.Text;
F_reservaApto.edtCliente.Text := edtRazaoSocial.Text;
{fecha as telas abertas}
F_fj.Close;
F_pesquisaHospede.Close;
Self.Close;
exit;
end;
end;
end;
procedure TF_cadHospedesFJ.edtCNPJExit(Sender: TObject);
begin {saindo do cnpj}
inherited;
if F_dmHospedes.QRY_cadHospede.State in [dsInsert, dsEdit] then begin
ACBrValidadorCNPJ.Documento := edtCNPJ.Text;
if not ACBrValidadorCNPJ.Validar then
begin
TF_msg.Mensagem('CNPJ inválido. Favor, digite um número válido','I',[mbOk]);
TcxDBMaskEdit(Sender).SetFocus;
exit;
end;
end;
{verifica se já existe o cliente físico}
if F_dmHospedes.QRY_cadHospede.State in [dsInsert] then begin
QRY_verificaCliente.Close;
QRY_verificaCliente.Params[0].Value := edtCNPJ.Text;
QRY_verificaCliente.Open();
if QRY_verificaCliente.RecordCount > 0 then begin
TF_msg.Mensagem('Já existe um cliente com esse CNPJ. Favor, informe outro CNPJ.','I',[mbOk]);
TcxDBMaskEdit(Sender).SetFocus;
exit;
end;
end;
end;
procedure TF_cadHospedesFJ.edtCPFExit(Sender: TObject);
begin {saindo do cpf}
inherited;
if F_dmHospedes.QRY_cadHospede.State in [dsInsert, dsEdit] then begin
ACBrValidadorCPF.Documento := edtCPF.Text;
if not ACBrValidadorCPF.Validar then
begin
TF_msg.Mensagem('CPF inválido! Favor, digite um número válido.','I',[mbOk]);
TcxDBMaskEdit(Sender).SetFocus;
exit;
end;
end;
{verifica se já existe o cliente físico}
if F_dmHospedes.QRY_cadHospede.State in [dsInsert] then begin
QRY_verificaCliente.Close;
QRY_verificaCliente.Params[0].Value := edtCPF.Text;
QRY_verificaCliente.Open();
if QRY_verificaCliente.RecordCount > 0 then begin
TF_msg.Mensagem('Já existe um cliente com esse CPF. Favor, informe outro CPF.','I',[mbOk]);
TcxDBMaskEdit(Sender).SetFocus;
exit;
end;
end;
end;
procedure TF_cadHospedesFJ.edtRegiaoExit(Sender: TObject);
begin
inherited;
{Saindo do regiaoFisica}
if not (ENumerico(edtRegiao.Text)) then begin
TF_msg.Mensagem('Campo aceita apenas valores numéricos Positivos. Favor, digita um número válido.','I',[mbOk]);
TcxButtonEdit(Sender).SetFocus;
exit;
end;
F_dmHospedes.QRY_cadHospedeRegiao.Close;
F_dmHospedes.QRY_cadHospedeRegiao.Params[0].AsInteger := StrToInt(edtRegiao.Text);
F_dmHospedes.QRY_cadHospedeRegiao.Open();
if F_dmHospedes.QRY_cadHospedeRegiao.RecordCount > 0 then begin
edtCidade.Text := F_dmHospedes.QRY_cadHospedeRegiaoREG_NOME.AsString;
edtUF.Text := F_dmHospedes.QRY_cadHospedeRegiaoREG_ESTADO.AsString;
end
else begin
TF_msg.Mensagem('Cidade não encontrada.','I',[mbOk]);
TcxButtonEdit(Sender).SetFocus;
exit;
end;
end;
procedure TF_cadHospedesFJ.edtRegiaoJExit(Sender: TObject);
begin
inherited;
{Saindo do regiaoFisica J}
if not (ENumerico(edtRegiaoJ.Text)) then begin
TF_msg.Mensagem('Campo aceita apenas valores numéricos Positivos. Favor, digita um número válido.','I',[mbOk]);
TcxButtonEdit(Sender).SetFocus;
exit;
end;
F_dmHospedes.QRY_cadHospedeRegiao.Close;
F_dmHospedes.QRY_cadHospedeRegiao.Params[0].AsInteger := StrToInt(edtRegiaoJ.Text);
F_dmHospedes.QRY_cadHospedeRegiao.Open();
if F_dmHospedes.QRY_cadHospedeRegiao.RecordCount > 0 then begin
edtCidadeJ.Text := F_dmHospedes.QRY_cadHospedeRegiaoREG_NOME.AsString;
edtUFJ.Text := F_dmHospedes.QRY_cadHospedeRegiaoREG_ESTADO.AsString;
end
else begin
TF_msg.Mensagem('Cidade não encontrada.','I',[mbOk]);
TcxButtonEdit(Sender).SetFocus;
exit;
end;
end;
procedure TF_cadHospedesFJ.edtRegiaoPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
begin {regiao física}
inherited;
CriaFormDestroy(TF_pesquisaRegiao, F_pesquisaRegiao);
end;
procedure TF_cadHospedesFJ.edtSexoEnter(Sender: TObject);
begin
inherited;
if Length((Sender as TcxDBComboBox).Text) = 0 then begin
// SendMessage((Sender as TcxDBComboBox).Handle, CB_SHOWDROPDOWN, 1, 0);
TcxDBComboBox(Sender).DroppedDown := True;
end;
end;
procedure TF_cadHospedesFJ.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
{se o reserva também tivesse que imprimir o relatorio, daria erros. como ele nao precisa, não da erros.}
{só coloca nil se o cadastro nao foi feito pelo entra hospede}
if F_entraHospede = nil then begin
FreeAndNil(F_dmHospedes);
end;
end;
procedure TF_cadHospedesFJ.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if key = VK_F2 then begin
btnNovo.Click;
end;
if key = VK_F3 then begin
btnEditar.Click;
end;
if key = VK_F4 then begin
btnCancelar.Click;
end;
if key = VK_F5 then begin
btnSalvar.Click;
end;
if key = VK_F6 then begin
btnDeletar.Click;
end;
if key = VK_F7 then begin
btnLocalizar.Click;
end;
end;
procedure TF_cadHospedesFJ.FormShow(Sender: TObject);
begin
inherited;
pg.HideTabs := True; {oculta todas}
tipoFJ := F_fj.conFJ; {passa o tipo que vem do F_fj}
if tipoFJ = 'F' then begin
pg.ActivePage := tbsFisica;
Height := 558;
end
else begin
pg.ActivePage := tbsJuridica;
Height := 558;
end;
if F_dmHospedes = nil then begin
Application.CreateForm(TF_dmHospedes, F_dmHospedes);
end;
F_dmHospedes.QRY_cadHospede.Open();
F_dmHospedes.QRY_cadHospedeRegiao.Open();
end;
end.
|
{
DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(DBEBr Framework)
@created(20 Jul 2016)
@author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>)
}
unit dbebr.driver.firedac.transaction;
interface
uses
Classes,
DB,
FireDAC.Comp.Client,
// DBEBr
dbebr.driver.connection,
dbebr.factory.interfaces;
type
// Classe de conexão concreta com FireDAC
TDriverFireDACTransaction = class(TDriverTransaction)
protected
FConnection: TFDConnection;
public
constructor Create(AConnection: TComponent); override;
destructor Destroy; override;
procedure StartTransaction; override;
procedure Commit; override;
procedure Rollback; override;
function InTransaction: Boolean; override;
end;
implementation
{ TDriverFireDACTransaction }
constructor TDriverFireDACTransaction.Create(AConnection: TComponent);
begin
FConnection := AConnection as TFDConnection;
end;
destructor TDriverFireDACTransaction.Destroy;
begin
FConnection := nil;
inherited;
end;
function TDriverFireDACTransaction.InTransaction: Boolean;
begin
Result := FConnection.InTransaction;
end;
procedure TDriverFireDACTransaction.StartTransaction;
begin
inherited;
FConnection.StartTransaction;
end;
procedure TDriverFireDACTransaction.Commit;
begin
inherited;
FConnection.Commit;
end;
procedure TDriverFireDACTransaction.Rollback;
begin
inherited;
FConnection.Rollback;
end;
end.
|
unit CRCoreTransfersEditForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, CommonObjectSelector, BaseObjects, StdCtrls, ToolWin, ComCtrls,
ExtCtrls, CommonFrame, CRCoreTransferEditFrame, ActnList;
type
TfrmCoreTransfersEditForm = class(TForm, IObjectSelector)
gbxTransfers: TGroupBox;
pnlButtons: TPanel;
lbxTransfers: TListBox;
tlbrEditTransfers: TToolBar;
btnOK: TButton;
btnCancel: TButton;
spl1: TSplitter;
frmCoreTransferEdit1: TfrmCoreTransferEdit;
actnlstTransfersEdit: TActionList;
actnAddTransfer: TAction;
actnEditTransfer: TAction;
actnDeleteTransfer: TAction;
btnAdd: TToolButton;
btnEditTransfer: TToolButton;
btnDelete: TToolButton;
actnApply: TAction;
actnCancel: TAction;
btnApply: TToolButton;
btnCancelEdit: TToolButton;
procedure lbxTransfersClick(Sender: TObject);
procedure actnAddTransferExecute(Sender: TObject);
procedure actnAddTransferUpdate(Sender: TObject);
procedure actnEditTransferUpdate(Sender: TObject);
procedure actnDeleteTransferUpdate(Sender: TObject);
procedure actnApplyUpdate(Sender: TObject);
procedure actnCancelUpdate(Sender: TObject);
procedure actnApplyExecute(Sender: TObject);
procedure actnCancelExecute(Sender: TObject);
procedure actnEditTransferExecute(Sender: TObject);
procedure actnDeleteTransferExecute(Sender: TObject);
private
FSelectOnly: boolean;
FMultiSelect: boolean;
FEditMode: boolean;
procedure SetSelectOnly(const Value: boolean);
procedure SetEditMode(const Value: boolean);
{ Private declarations }
protected
procedure SetSelectedObject(AValue: TIDObject);
function GetSelectedObject: TIDObject;
procedure SetMultiSelect(const Value: boolean);
function GetMultiSelect: boolean;
function GetSelectedObjects: TIDObjects;
procedure SetSelectedObjects(AValue: TIDObjects);
public
{ Public declarations }
property SelectOnly: boolean read FSelectOnly write SetSelectOnly;
property MultiSelect: boolean read GetMultiSelect write SetMultiSelect;
property SelectedObjects: TIDObjects read GetSelectedObjects write SetSelectedObjects;
property SelectedObject: TIDObject read GetSelectedObject write SetSelectedObject;
property EditMode: boolean read FEditMode write SetEditMode;
procedure ReadSelectedObjects;
constructor Create(AOwner: TComponent); override;
end;
var
frmCoreTransfersEditForm: TfrmCoreTransfersEditForm;
implementation
uses Facade, CoreTransfer;
{$R *.dfm}
{ TForm1 }
constructor TfrmCoreTransfersEditForm.Create(AOwner: TComponent);
begin
inherited;
TMainFacade.GetInstance.AllCoreTransfers.MakeList(lbxTransfers.Items, true, true);
FEditMode := false;
end;
function TfrmCoreTransfersEditForm.GetMultiSelect: boolean;
begin
Result := FMultiSelect;
end;
function TfrmCoreTransfersEditForm.GetSelectedObject: TIDObject;
begin
Result := frmCoreTransferEdit1.CoreTransfer;
end;
function TfrmCoreTransfersEditForm.GetSelectedObjects: TIDObjects;
begin
Result := nil;
end;
procedure TfrmCoreTransfersEditForm.ReadSelectedObjects;
begin
end;
procedure TfrmCoreTransfersEditForm.SetMultiSelect(const Value: boolean);
begin
FMultiSelect := Value;
end;
procedure TfrmCoreTransfersEditForm.SetSelectedObject(AValue: TIDObject);
begin
frmCoreTransferEdit1.EditingObject := AValue;
lbxTransfers.ItemIndex := lbxTransfers.Items.IndexOfObject(AValue);
end;
procedure TfrmCoreTransfersEditForm.SetSelectedObjects(AValue: TIDObjects);
begin
end;
procedure TfrmCoreTransfersEditForm.SetSelectOnly(const Value: boolean);
begin
FSelectOnly := Value;
if not FSelectOnly then
begin
btnOK.Caption := 'Закрыть';
btnCancel.Visible := false;
end
else
begin
btnOK.Caption := 'OK';
btnCancel.Visible := true;
end;
end;
procedure TfrmCoreTransfersEditForm.lbxTransfersClick(Sender: TObject);
begin
if lbxTransfers.ItemIndex > -1 then
SelectedObject := lbxTransfers.Items.Objects[lbxTransfers.ItemIndex] as TIDObject;
end;
procedure TfrmCoreTransfersEditForm.actnAddTransferExecute(
Sender: TObject);
var t: TCoreTransfer;
begin
t := TMainFacade.GetInstance.AllCoreTransfers.Add as TCoreTransfer;
t.TransferStart := Date;
SelectedObject := t;
actnAddTransfer.Checked := true;
EditMode := true;
end;
procedure TfrmCoreTransfersEditForm.SetEditMode(const Value: boolean);
begin
if FEditMode <> Value then
begin
FEditMode := Value;
end;
end;
procedure TfrmCoreTransfersEditForm.actnAddTransferUpdate(Sender: TObject);
begin
actnAddTransfer.Enabled := not EditMode;
end;
procedure TfrmCoreTransfersEditForm.actnEditTransferUpdate(
Sender: TObject);
begin
actnEditTransfer.Enabled := Not EditMode and Assigned(SelectedObject);
end;
procedure TfrmCoreTransfersEditForm.actnDeleteTransferUpdate(
Sender: TObject);
begin
actnDeleteTransfer.Enabled := Assigned(SelectedObject) and not EditMode;
end;
procedure TfrmCoreTransfersEditForm.actnApplyUpdate(Sender: TObject);
begin
actnApply.Enabled := EditMode And Assigned(SelectedObject);
end;
procedure TfrmCoreTransfersEditForm.actnCancelUpdate(Sender: TObject);
begin
actnCancel.Enabled := EditMode And Assigned(SelectedObject);
end;
procedure TfrmCoreTransfersEditForm.actnApplyExecute(Sender: TObject);
begin
frmCoreTransferEdit1.Save();
SelectedObject.Update();
EditMode := false;
end;
procedure TfrmCoreTransfersEditForm.actnCancelExecute(Sender: TObject);
begin
TMainFacade.GetInstance.AllCoreTransfers.Remove(SelectedObject);
SelectedObject := nil;
EditMode := false;
end;
procedure TfrmCoreTransfersEditForm.actnEditTransferExecute(
Sender: TObject);
begin
actnEditTransfer.Checked := true;
EditMode := true;
end;
procedure TfrmCoreTransfersEditForm.actnDeleteTransferExecute(
Sender: TObject);
begin
TMainFacade.GetInstance.AllCoreTransfers.Remove(SelectedObject);
SelectedObject := nil;
end;
end.
|
{*******************************************************}
{ }
{ NTS Aero UI Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit UI.Aero.Panel;
interface
{$I '../../Common/CompilerVersion.Inc'}
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils,
System.Classes,
Winapi.Windows,
Winapi.Messages,
Winapi.UxTheme,
Winapi.GDIPOBJ,
Winapi.GDIPAPI,
Vcl.Graphics,
Vcl.Controls,
{$ELSE}
Windows, Messages, SysUtils, Classes, Controls, Graphics, Themes, UxTheme,
Winapi.GDIPOBJ,
Winapi.GDIPAPI,
{$ENDIF}
NTS.Code.Common.Types,
UI.Aero.Core.CustomControl,
UI.Aero.Globals;
type
TAeroPanel = Class(TCustomAeroControl)
private
fBorder: TBevelEdges;
fGradientColor,
fBorderColor: TColor;
fAlphaGradientColor: TGPColorValue;
fAlphaBorderColor: TGPColorValue;
fAlphaColor: TGPColorValue;
fBackGround: TAeroBackGround;
fGradientType: LinearGradientMode;
fWrapMode: TWrapMode;
fTexture: TImageFileName;
procedure SetBorder(const Value: TBevelEdges);
procedure SetAlphaBorderColor(const Value: TGPColorValue);
procedure SetAlphaColor(const Value: TGPColorValue);
procedure SetAlphaGradientColor(const Value: TGPColorValue);
procedure SetBackGround(const Value: TAeroBackGround);
procedure SetGradientType(const Value: LinearGradientMode);
function CreateGPBrush(const AGPRect: TGPRect;var Image: TGPImage): TGPBrush;
function CreateGPRect: TGPRect;
procedure SetWrapMode(const Value: TWrapMode);
function CreateGPImage: TGPImage;
procedure SetTexture(const Value: TImageFileName);
Protected
function GetRenderState: TRenderConfig; OverRide;
procedure ClassicRender(const ACanvas: TCanvas); OverRide;
procedure ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig); OverRide;
procedure DarwBorder(Surface: TGPGraphics);
procedure PostRender(const Surface: TCanvas; const RConfig: TRenderConfig); override;
Public
Constructor Create(AOwner: TComponent); OverRide;
Destructor Destroy; OverRide;
Published
property Border: TBevelEdges Read fBorder Write SetBorder Default [];
Property AlphaColor: TGPColorValue Read fAlphaColor Write SetAlphaColor default aclNavy;
Property AlphaGradientColor: TGPColorValue Read fAlphaGradientColor Write SetAlphaGradientColor default aclWhite;
Property AlphaBorderColor: TGPColorValue Read fAlphaBorderColor Write SetAlphaBorderColor default aclBlack;
Property BackGround: TAeroBackGround Read fBackGround Write SetBackGround default bgSolid;
Property GradientType: LinearGradientMode Read fGradientType Write SetGradientType default LinearGradientModeHorizontal;
Property TextureWrapMode: TWrapMode Read fWrapMode Write SetWrapMode default WrapModeTile;
Property Texture: TImageFileName Read fTexture Write SetTexture;
End;
implementation
{ TAeroPanel }
constructor TAeroPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle:= ControlStyle+[csAcceptsControls];
fBorder:= [];
//
fAlphaColor:= aclNavy;
fAlphaGradientColor:= aclWhite;
fAlphaBorderColor:= aclBlack;
//
Color:= RGB(GetRed(fAlphaColor),GetGreen(fAlphaColor),GetBlue(fAlphaColor));
fGradientColor:= RGB(GetRed(fAlphaGradientColor),GetGreen(fAlphaGradientColor),GetBlue(fAlphaGradientColor));
fBorderColor:= RGB(GetRed(fAlphaBorderColor),GetGreen(fAlphaBorderColor),GetBlue(fAlphaBorderColor));
//
fBackGround:= bgSolid;
fGradientType:= LinearGradientModeHorizontal;
//
fWrapMode:= WrapModeTile;
fTexture:= '';
end;
destructor TAeroPanel.Destroy;
begin
inherited Destroy;
end;
function TAeroPanel.GetRenderState: TRenderConfig;
begin
Result:= [rsBuffer, rsGDIP];
end;
procedure TAeroPanel.PostRender(const Surface: TCanvas; const RConfig: TRenderConfig);
begin
end;
procedure TAeroPanel.SetAlphaBorderColor(const Value: TGPColorValue);
begin
if fAlphaBorderColor <> Value then
begin
fAlphaBorderColor:= Value;
fBorderColor:= RGB(GetRed(Value),GetGreen(Value),GetBlue(Value));
Invalidate;
end;
end;
procedure TAeroPanel.SetAlphaColor(const Value: TGPColorValue);
begin
if fAlphaColor <> Value then
begin
fAlphaColor:= Value;
Color:= RGB(GetRed(Value),GetGreen(Value),GetBlue(Value));
end;
end;
procedure TAeroPanel.SetAlphaGradientColor(const Value: TGPColorValue);
begin
if fAlphaGradientColor <> Value then
begin
fAlphaGradientColor:= Value;
fGradientColor:= RGB(GetRed(Value),GetGreen(Value),GetBlue(Value));
Invalidate;
end;
end;
procedure TAeroPanel.SetBackGround(const Value: TAeroBackGround);
begin
if fBackGround <> Value then
begin
fBackGround:= Value;
Invalidate;
end;
end;
procedure TAeroPanel.SetBorder(const Value: TBevelEdges);
begin
if fBorder <> Value then
begin
fBorder:= Value;
Invalidate;
end;
end;
procedure TAeroPanel.SetGradientType(const Value: LinearGradientMode);
begin
if fGradientType <> Value then
begin
fGradientType:= Value;
Invalidate;
end;
end;
procedure TAeroPanel.SetTexture(const Value: TImageFileName);
begin
if fTexture <> Value then
begin
fTexture:= Value;
Invalidate;
end;
end;
procedure TAeroPanel.SetWrapMode(const Value: TWrapMode);
begin
if fWrapMode <> Value then
begin
fWrapMode:= Value;
Invalidate;
end;
end;
procedure TAeroPanel.ClassicRender(const ACanvas: TCanvas);
begin
// {$Message HINT 'Доделать и исправить наконец эту долбаную панель!'}
end;
function TAeroPanel.CreateGPBrush(const AGPRect: TGPRect;var Image: TGPImage): TGPBrush;
begin
Result:= nil;
case fBackGround of
bgSolid : Result:= TGPSolidBrush.Create(fAlphaColor);
bgGradient: Result:= TGPLinearGradientBrush.Create(AGPRect,fAlphaColor,fAlphaGradientColor,fGradientType);
bgTexture : Result:= TGPTextureBrush.Create(Image,fWrapMode,0,0,Image.GetWidth,Image.GetHeight);
end;
end;
function TAeroPanel.CreateGPImage: TGPImage;
begin
if FileExists(fTexture) then
begin
Result:= TGPImage.Create(fTexture);
end
else
Result:= nil;
end;
function TAeroPanel.CreateGPRect: TGPRect;
begin
Result:= MakeRect(0, 0, ClientWidth, ClientHeight);
if beLeft in fBorder then Result.X:= 0;
if beTop in fBorder then Result.Y:= 0;
if beRight in fBorder then
begin
if beLeft in fBorder then
Result.Width:= Result.Width-1
else
Result.Width:= Result.Width-1;
end;
if beBottom in fBorder then
begin
if beTop in fBorder then
Result.Height:= Result.Height-1
else
Result.Height:= Result.Height-1;
end;
end;
procedure TAeroPanel.DarwBorder(Surface: TGPGraphics);
var
ARect: TGPRect;
GPen: TGPPen;
begin
GPen:= TGPPen.Create(fAlphaBorderColor);
ARect:= MakeRect(-1,-1,ClientWidth+1,ClientHeight+1);
if beLeft in fBorder then
ARect.X:= 0;
if beTop in fBorder then
ARect.Y:= 0;
if beRight in fBorder then
begin
if beLeft in fBorder then
ARect.Width:= ClientWidth-1
else
ARect.Width:= ClientWidth;
end;
if beBottom in fBorder then
begin
if beTop in fBorder then
ARect.Height:= ClientHeight-1
else
ARect.Height:= ClientHeight;
end;
Surface.DrawRectangle(GPen,ARect);
GPen.Free;
end;
procedure TAeroPanel.ThemedRender(const PaintDC: hDC; const Surface: TGPGraphics; var RConfig: TRenderConfig);
var
ARect: TGPRect;
Brush: TGPBrush;
Image: TGPImage;
begin
if (fBorder <> []) then DarwBorder(Surface);
//
ARect:= CreateGPRect;
Image:= CreateGPImage;
Brush:= CreateGPBrush(ARect,Image);
//
Surface.SetClip(ARect);
Surface.FillRectangle(Brush,ARect);
Surface.ResetClip;
//
if Assigned(Image) then Image.Free;
Brush.Free;
end;
end.
|
unit uEBKSelectBank;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Grids, DBGridEh, DBClient, ExtCtrls, DB;
type
TfrmSelectBank = class(TForm)
Label1: TLabel;
cmbProvice: TComboBox;
cmbCity: TComboBox;
Label2: TLabel;
Label3: TLabel;
cmbBank: TComboBox;
edtFilter: TEdit;
Label4: TLabel;
btnSearch: TButton;
Panel1: TPanel;
grdWY: TDBGridEh;
cdsWY: TClientDataSet;
dsWY: TDataSource;
btnOK: TButton;
procedure btnSearchClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure cmbProviceChange(Sender: TObject);
procedure btnOKClick(Sender: TObject);
private
FDEPID: String;
procedure SetDEPID(const Value: String);
{ Private declarations }
public
{ Public declarations }
property DEPID:String read FDEPID write SetDEPID;
end;
var
frmSelectBank: TfrmSelectBank;
GEBKParams: TClientDataSet;
implementation
uses
Pub_Function, DateUtils, DataModuleMain, Pub_Global;
{$R *.dfm}
procedure TfrmSelectBank.btnSearchClick(Sender: TObject);
var
vSQL:String;
begin
if cmbBank.ItemIndex < 0 then
begin
Application.MessageBox('请选择银行!','系统提示', MB_ICONWarning + MB_OK);
cmbBank.SetFocus;
Exit;
end;
if cmbProvice.ItemIndex < 0 then
begin
if Trim(edtFilter.Text) = '' then
begin
Application.MessageBox('请输入模糊信息进行查找!','系统提示', MB_ICONWarning + MB_OK);
cmbProvice.SetFocus;
Exit;
end;
end;
if cmbProvice.ItemIndex < 0 then
vSQL := 'Select BANK_CODE, BANK_NAME from EBK_BANKINFO Where DEPID='+QuotedStr(TString.LeftStrBySp(cmbBank.Text))
+IFF(edtFilter.text='', '', ' and BANK_NAME like '+QuotedStr('%'+edtFilter.text+'%'))
else
vSQL := 'Select BANK_CODE, BANK_NAME from EBK_BANKINFO Where DEPID='+QuotedStr(TString.LeftStrBySp(cmbBank.Text))
+IFF(cmbCity.ItemIndex >=0 ,' and AREACODE='+QuotedStr(TString.LeftStrBySp(cmbCity.Text))
,' and AREACODE in (Select AREACODE from EBK_AREACODE where PROVID='+QuotedStr(TString.LeftStrBySp(cmbProvice.Text))+')')
+IFF(edtFilter.text='', '', ' and BANK_NAME like '+QuotedStr('%'+edtFilter.text+'%'));
POpenSQL(cdsWY, vSQL);
end;
procedure TfrmSelectBank.FormCreate(Sender: TObject);
begin
grdWY.FixedColor := Self.Color;
with DataModulePub.GetCdsBySQL('SELECT DEPID, DEP_NAME FROM EBK_DEPID') do
begin
cmbBank.Items.Clear;
while not eof do
begin
cmbBank.Items.Add(FieldByName('DEPID').AsString+' '+FieldByName('DEP_NAME').AsString);
Next;
end;
end;
if cmbProvice.ItemIndex > 0 then
cmbProviceChange(nil);
end;
function ReadParams(CSMC: string): string;
begin
Result := '';
if GEBKParams = nil then
GEBKParams := DataModulePub.GetCdsBySQL('Select * from EBK_ZTCS where GSDM=' + QuotedStr(GszGSDM)
+ ' and KJND=' + QuotedStr(GszKJND));
if GEBKParams.Locate('CSMC', CSMC, []) then
Result := GEBKParams.FieldByName('CSZ').AsString;
end;
procedure TfrmSelectBank.cmbProviceChange(Sender: TObject);
var
DefCity:string;
begin
//查询省市的结果
with DataModulePub.GetCdsBySQL('SELECT AREACODE, AREA_NAME FROM EBK_AREACODE WHERE PROVID='
+QuotedStr(TString.LeftStrBySp(cmbProvice.Text))) do
begin
cmbCity.Clear;
while not eof do
begin
cmbCity.Items.Add(FieldByName('AREACODE').AsString+' '+FieldByName('AREA_NAME').AsString);
Next;
end;
DefCity := ReadParams('CITY');
if cmbCity.Items.IndexOf(DefCity) > 0 then
cmbCity.ItemIndex := cmbCity.Items.IndexOf(DefCity);
end;
end;
procedure TfrmSelectBank.btnOKClick(Sender: TObject);
begin
if not cdsWY.Active then Exit;
if cdsWY.RecordCount = 0 then
begin
Application.MessageBox('无数据, 请重新查询!', '系统提示', MB_ICONWarning+MB_OK);
Exit;
end;
ModalResult := mrOK;
end;
procedure TfrmSelectBank.SetDEPID(const Value: String);
begin
FDEPID := Value;
if cmbBank.Items.IndexOf(Value)>=0 then
cmbBank.ItemIndex := cmbBank.Items.IndexOf(Value);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.