text stringlengths 14 6.51M |
|---|
unit DLLList;
interface
uses
System.Generics.Collections;
type
TDLLList = class(TList<string>)
procedure AddUniq(const AName: string);
end;
implementation
uses
System.SysUtils;
procedure TDLLList.AddUniq(const AName: string);
var
s: string;
i: Integer;
begin
s := AnsiUpperCase(AName);
i := IndexOf(s);
if i = -1 then
Add(s);
end;
end.
|
unit clContatosCadastro;
interface
uses clcontatos, clConexao, Vcl.Dialogs, System.SysUtils;
type
TContatosCadastro = class(TContatos)
protected
FCadastro: Integer;
FPadrao: String;
FSequencia: Integer;
conexao: TConexao;
FDivulgar: String;
private
procedure SetCadastro(val: Integer);
procedure SetSequencia(val: Integer);
procedure SetPadrao(val: String);
procedure SetDivulgar(val: String);
public
constructor Create;
property Cadastro: Integer read FCadastro write SetCadastro;
property Sequencia: Integer read FSequencia write SetSequencia;
property Padrao: String read FPadrao write SetPadrao;
procedure MaxSeq;
function Validar: Boolean;
function Insert: Boolean;
function Update: Boolean;
function Delete(sFiltro: String): Boolean;
function getObjects: Boolean;
function getField(sCampo: String; sColuna: String): String;
destructor Destroy; override;
function getObject(sId: String; sFiltro: String): Boolean;
property Divulgar: String read FDivulgar write SetDivulgar;
end;
const
TABLENAME = 'CAD_CONTATOS_CADASTRO';
implementation
uses udm;
constructor TContatosCadastro.Create;
begin
inherited Create;
conexao := TConexao.Create;
end;
procedure TContatosCadastro.SetCadastro(val: Integer);
begin
FCadastro := val;
end;
procedure TContatosCadastro.SetSequencia(val: Integer);
begin
FSequencia := val;
end;
procedure TContatosCadastro.SetPadrao(val: String);
begin
FPadrao := val;
end;
procedure TContatosCadastro.MaxSeq;
begin
try
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
Self.Sequencia := 0;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Text := 'SELECT MAX(SEQ_CONTATO) AS SEQUENCIA FROM ' + TABLENAME +
' WHERE COD_CADASTRO = :CODIGO';
ParamByName('CODIGO').AsInteger := Self.Cadastro;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
First;
Self.Sequencia := (FieldByName('SEQUENCIA').AsInteger) + 1;
end;
end;
dm.QryGetObject.Close;
dm.QryGetObject.SQL.Clear;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatosCadastro.Validar: Boolean;
begin
Result := False;
if Self.Cadastro = 0 then
begin
MessageDlg('Código de Cadastro inválido!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Sequencia = 0 then
begin
MessageDlg('Sequência de inválida!',mtWarning,[mbCancel],0);
Exit;
end;
if Self.Contato.IsEmpty then
begin
MessageDlg('Informe uma Descrição ou Nome do Contato!',mtWarning,[mbCancel],0);
Exit;
end;
if (Self.Telefone.IsEmpty) and (Self.EMail.IsEmpty) then
begin
MessageDlg('Informe um Número de Telefone ou um E-Mail do Contato!',mtWarning,[mbCancel],0);
Exit;
end;
Result := True;
end;
function TContatosCadastro.Insert: Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
MaxSeq;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO ' + TABLENAME + ' ( ' +
'COD_CADASTRO, ' +
'SEQ_CONTATO, ' +
'DES_CONTATO, ' +
'NUM_TELEFONE, ' +
'DES_EMAIL, ' +
'DOM_PADRAO, ' +
'DOM_DIVULGAR) ' +
'VALUES(' +
':CODIGO, ' +
':SEQUENCIA, ' +
':CONTATO, ' +
':TELEFONE, ' +
':EMAIL, ' +
':PADRAO, ' +
':DIVULGAR);';
ParamByName('CODIGO').AsInteger := Self.Cadastro;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('CONTATO').AsString := Self.Contato;
ParamByName('TELEFONE').AsString := Self.Telefone;
ParamByName('EMAIL').AsString := Self.EMail;
ParamByName('PADRAO').AsString := Self.Padrao;
ParamByName('DIVULGAR').AsString := Self.Divulgar;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatosCadastro.Update: Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' +
'DES_CONTATO = :CONTATO, ' +
'NUM_TELEFONE = :TELEFONE, ' +
'DES_EMAIL = :EMAIL, ' +
'DES_PADRAO = :PADRAO, ' +
'DOM_DIVULGAR = :DIVULGAR ' +
'WHERE COD_CADASTRO = :CODIGO AND SEQ_CONTATO = :SEQUENCIA';
ParamByName('CODIGO').AsInteger := Self.Cadastro;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
ParamByName('CONTATO').AsString := Self.Contato;
ParamByName('TELEFONE').AsString := Self.Telefone;
ParamByName('EMAIL').AsString := Self.EMail;
ParamByName('PADRAO').AsString := Self.Padrao;
ParamByName('DIVULGAR').AsString := Self.Divulgar;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatosCadastro.Delete(sFiltro: String): Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('DELETE FROM ' + TABLENAME);
if sFiltro = 'CODIGO' then
begin
SQL.Add('WHERE COD_CADASTRO = :CODIGO');
ParamByName('CODIGO').AsInteger := Self.Cadastro;
end
else if sFiltro = 'SEQUENCIA' then
begin
SQL.Add('WHERE COD_CADASTRO = :CODIGO AND SEQ_CONTATO = :SEQUENCIA');
ParamByName('CODIGO').AsInteger := Self.Cadastro;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
end;
dm.ZConn.PingServer;
ExecSQL;
end;
dm.QryCRUD.Close;
dm.QryCRUD.SQL.Clear;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatosCadastro.getObjects: Boolean;
begin
try
Result := False;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
with dm.QryGetObject do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
First;
end
else
begin
Close;
SQL.Clear;
Exit;
end;
end;
Result := True;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
function TContatosCadastro.getField(sCampo: String; sColuna: String): String;
begin
try
Result := '';
if sCampo.IsEmpty then
begin
Exit;
end;
if sColuna.IsEmpty then
begin
Exit;
end;
with dm.qryFields do
begin
Close;
SQL.Clear;
SQL.Add('SELECT ' + sCampo + ' FROM ' + TABLENAME);
if sColuna = 'SEQUENCIA' then
begin
SQL.Add(' WHERE COD_CADASTRO = :CODIGO AND SEQ_CONTATO = :SEQUENCIA ORDER BY SEQ_CONTATO');
ParamByName('CODIGO').AsInteger := Self.Cadastro;
ParamByName('SEQUENCIA').AsInteger := Self.Sequencia;
end
else if sColuna = 'CODIGO' then
begin
SQL.Add(' WHERE COD_CADASTRO = :CODIGO ORDER BY SEQ_CONTATO');
ParamByName('CODIGO').AsInteger := Self.Cadastro;
end;
dm.ZConn.PingServer;
Open;
if not(IsEmpty) then
begin
First;
Result := FieldByName(sCampo).AsString;
end;
Close;
SQL.Clear;
Exit;
end;
Except on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
destructor TContatosCadastro.Destroy;
begin
conexao.Free;
inherited Destroy;
end;
function TContatosCadastro.getObject(sId: String; sFiltro: String): Boolean;
begin
try
Result := False;
if sId.IsEmpty then
begin
Exit;
end;
if sFiltro.IsEmpty then
begin
Exit;
end;
if (not conexao.VerifyConnZEOS(0)) then
begin
MessageDlg('Erro ao estabelecer conexão ao banco de dados!', mtError, [mbCancel], 0);
Exit;
end;
with dm.QryCRUD do
begin
Close;
SQL.Clear;
SQL.Add('SELECT * FROM ' + TABLENAME);
if sFiltro = 'CODIGO' then
begin
SQL.Add('WHERE COD_CADASTRO = :CODIGO');
ParamByName('CODIGO').AsInteger := StrToInt(sId);
end
else if sFiltro = 'SEQUENCIA' then
begin
SQL.Add('WHERE COD_CADASTRO = :CODIGO AND SEQ_CONTATO = :SEQUENCIA');
ParamByName('CODIGO').AsInteger := Self.Cadastro;
ParamByName('SEQUENCIA').AsInteger := StrToInt(sId);
end
else if sFiltro = 'CONTATO' then
begin
SQL.Add('WHERE DES_CONTATO LIKE :CONTATO');
ParamByName('CONTATO').AsString := QuotedStr('%' + sId + '%');
end
else if sFiltro = 'EMAIL' then
begin
SQL.Add('WHERE DES_EMAIL = :EMAIL');
ParamByName('EMAIL').AsString := sId;
end;
dm.ZConn.PingServer;
Open;
if (not IsEmpty) then
begin
First;
Self.Cadastro := FieldByName('COD_CADASTRO').AsInteger;
Self.Sequencia := FieldByName('SEQ_CONTATO').AsInteger;
Self.Contato := FieldByName('DES_CONTATO').AsString;
Self.Telefone := FieldByName('NUM_TELEFONE').AsString;
Self.EMail := FieldByName('DES_EMAIL').AsString;
Self.Padrao := FieldByName('DOM_PADRAO').AsString;
sELF.Divulgar := FieldByName('DOM_DIVULGAR').AsString;
Result := True;
Exit;
end;
Close;
SQL.Clear;
end;
Except
on E: Exception do
ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' +
E.Message);
end;
end;
procedure TContatosCadastro.SetDivulgar(val: String);
begin
FDivulgar := val;
end;
end.
|
unit stax;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Generics.Collections, stax.helpertypes;
type
TExecutor = class;
ETaskTerminatedException = class(Exception);
ETaskNotActiveException = class(Exception);
TTaskStatus = (tsNone=0, tsScheduled, tsRescheduled, tsRunning, tsFinished, tsError);
{ TTask }
TTask = class
// Maybe this is too much?
public const DefaultTaskStackSize = DefaultStackSize;
private type
TStackData = record
Size: SizeInt;
Memory: Pointer;
end;
TStackCache = specialize TList<TStackData>;
public
class var StackCache: TStackCache;
class constructor InitStatics;
class destructor CleanupStatics;
class function AllocStack(ASize: SizeInt): TStackData; static; {$IFDEF inlining}inline;{$ENDIF}
class procedure FreeStack(constref AStackData: TStackData); static; {$IFDEF inlining}inline;{$ENDIF}
private
FError: Exception;
FStatus: TTaskStatus;
FExecutor: TExecutor;
FStack: TStackData;
FTaskEnv: jmp_buf;
FTerminated: Boolean;
procedure DoExecute(a: Boolean=True);
protected
procedure Execute; virtual; abstract;
public
constructor Create(AStackSize: SizeInt = DefaultTaskStackSize);
destructor Destroy; override;
procedure Terminate; {$IFDEF inlining}inline;{$ENDIF}
procedure Run(AExecutor: TExecutor);
procedure Resume;
procedure Yield;
procedure Sleep(Time: QWord);
procedure Stop; {$IFDEF inlining}inline;{$ENDIF}
property Error: Exception read FError;
property Status: TTaskStatus read FStatus;
property Executor: TExecutor read FExecutor;
property Terminated: Boolean read FTerminated;
end;
{ TRVTask }
generic TRVTask<T> = class(TTask)
protected
FResult: T;
protected
procedure Execute; override;
public
property TaskResult: T read FResult;
end;
TErrorFunction = procedure(Task: TTask; E: Exception);
TErrorMethod = procedure(Task: TTask; E: Exception) of object;
TErrorHandler = specialize TUnion<TErrorFunction, TErrorMethod>;
{ EUnhandledError }
EUnhandledError = class(Exception)
public
Error: Exception;
Task: TTask;
constructor Create(AError: Exception; ATask: TTask);
end;
TTaskQueueEntry = record
Task: TTask;
FreeTask: Boolean;
RaiseError: Boolean;
end;
TTaskQueue = specialize TQueue<TTaskQueueEntry>;
ETaskAlreadyScheduledException = class(Exception);
ENotATaskException = class(Exception);
{ TExecutor }
TExecutor = class
private type
TThreadExecutorMap = specialize TDictionary<TThreadID, TExecutor>;
private
class var ThreadExecutorMap: TThreadExecutorMap;
class constructor InitStatics;
class destructor CleanupStatics;
class procedure RegisterExecutor(ThreadID: TThreadID; Executor: TExecutor); static; {$IFDEF inlining}inline;{$ENDIF}
class procedure RemoveExecutor(Executor: TExecutor); static; {$IFDEF inlining}inline;{$ENDIF}
public
class function GetExecutor(ThreadID: Integer): TExecutor; static; {$IFDEF inlining}inline;{$ENDIF}
private
FErrorHandler: TErrorHandler;
FTaskQueue: TTaskQueue;
FCurrentTask: TTask;
FSchedulerEnv: jmp_buf;
FThread: TThread;
procedure RaiseErrorHandler(Task: TTask); {$IFDEF inlining}inline;{$ENDIF}
procedure ScheduleTask(constref QueueEntry: TTaskQueueEntry);
procedure ExecTask(ATask: TTask); {$IFDEF inlining}inline;{$ENDIF}
procedure FinalizeTask(ATask: TTaskQueueEntry);
public
constructor Create;
destructor Destroy; override;
procedure RunAsync(ATask: TTask; FreeTask: Boolean = True; RaiseErrors: Boolean = True);
procedure Await(ATask: TTask; FreeTask: Boolean = True);
// For some reason this breaks fpc, so we added this as a global function
//generic function Await<TResult>(ATask: specialize TRVTask<TResult>; FreeTask: Boolean = True): TResult;
procedure Yield;
procedure Sleep(time: QWord);
procedure Run;
property OnError: TErrorHandler read FErrorHandler write FErrorHandler;
property Thread: TThread read FThread;
end;
function GetExecutor: TExecutor; {$IFDEF inlining}inline;{$ENDIF}
procedure Await(ATask: TTask; FreeTask: Boolean = True);
generic function Await<TResult>(ATask: specialize TRVTask<TResult>; FreeTask: Boolean = True): TResult;
procedure Yield;
procedure AsyncSleep(time: QWord);
implementation
function GetExecutor: TExecutor;
begin
Result := TExecutor.GetExecutor(TThread.CurrentThread.ThreadID);
end;
procedure Await(ATask: TTask; FreeTask: Boolean);
var
Executor: TExecutor;
begin
Executor := GetExecutor;
if not Assigned(Executor) then
raise ENotATaskException.Create('Await can only be called from within a Task');
Executor.Await(ATask, FreeTask);
end;
generic function Await<TResult>(ATask: specialize TRVTask<TResult>; FreeTask: Boolean = True): TResult;
var
Executor: TExecutor;
begin
Executor := GetExecutor;
if not Assigned(Executor) then
raise ENotATaskException.Create('Await can only be called from within a Task');
try
Executor.Await(ATask, False);
Result := ATask.TaskResult;
finally
if FreeTask then ATask.Free;
end;
end;
procedure Yield;
var
Executor: TExecutor;
begin
Executor := GetExecutor;
if not Assigned(Executor) then
raise ENotATaskException.Create('Yield can only be called from within a Task');
Executor.Yield;
end;
procedure AsyncSleep(time: QWord);
var
Executor: TExecutor;
begin
Executor := GetExecutor;
if not Assigned(Executor) then
raise ENotATaskException.Create('AsyncSleep can only be called from within a Task');
Executor.Sleep(time);
end;
{ EUnhandledError }
constructor EUnhandledError.Create(AError: Exception; ATask: TTask);
begin
Error := AError;
Task := ATask;
end;
{ TExecutor }
class constructor TExecutor.InitStatics;
begin
ThreadExecutorMap := TThreadExecutorMap.Create;
end;
class destructor TExecutor.CleanupStatics;
begin
ThreadExecutorMap.Free;
end;
class procedure TExecutor.RegisterExecutor(ThreadID: TThreadID;
Executor: TExecutor);
begin
ThreadExecutorMap.Add(ThreadID, Executor);
end;
class procedure TExecutor.RemoveExecutor(Executor: TExecutor);
begin
ThreadExecutorMap.Remove(Executor.Thread.ThreadID)
end;
class function TExecutor.GetExecutor(ThreadID: Integer): TExecutor;
begin
if not ThreadExecutorMap.TryGetValue(ThreadID, Result) then
Result := nil;
end;
procedure TExecutor.RaiseErrorHandler(Task: TTask);
begin
if FErrorHandler.isFirst then
FErrorHandler.First()(Task, Task.Error)
else if FErrorHandler.isSecond then
FErrorHandler.Second()(Task, Task.Error)
else
raise EUnhandledError.Create(Task.Error, Task);
end;
procedure TExecutor.ScheduleTask(constref QueueEntry: TTaskQueueEntry);
begin
FTaskQueue.Enqueue(QueueEntry);
if QueueEntry.Task.Status = tsNone then
QueueEntry.Task.FStatus := tsScheduled
else
QueueEntry.Task.FStatus := tsRescheduled;
end;
procedure TExecutor.ExecTask(ATask: TTask);
begin
if setjmp(FSchedulerEnv) <> 0 then
begin
// when the scheduler is called we end up here
FCurrentTask := nil;
Exit;
end;
FCurrentTask := ATask;
if ATask.Status = tsRescheduled then
ATask.Resume
else
ATask.Run(Self);
end;
procedure TExecutor.FinalizeTask(ATask: TTaskQueueEntry);
begin
try
// handle errors
if ATask.RaiseError and (ATask.Task.Status = tsError) then
RaiseErrorHandler(ATask.Task);
finally
if ATask.FreeTask then
ATask.Task.Free;
end;
end;
constructor TExecutor.Create;
begin
FTaskQueue := TTaskQueue.Create;
FCurrentTask := nil;
FThread := nil;
end;
destructor TExecutor.Destroy;
begin
// TODO: handle currently active and scheduled tasks
FTaskQueue.Free;
inherited Destroy;
end;
procedure TExecutor.RunAsync(ATask: TTask; FreeTask: Boolean;
RaiseErrors: Boolean);
var
NewEntry: TTaskQueueEntry;
begin
if ATask.Status <> tsNone then
raise ETaskAlreadyScheduledException.Create('Task already scheduled');
ATask.FExecutor := Self;
NewEntry.Task := ATask;
NewEntry.FreeTask := FreeTask;
NewEntry.RaiseError := RaiseErrors;
ScheduleTask(NewEntry);
end;
procedure TExecutor.Await(ATask: TTask; FreeTask: Boolean);
begin
if (TThread.CurrentThread <> FThread) or not Assigned(FCurrentTask) then
raise ENotATaskException.Create('Can only await inside a task');
try
// schedule task to await
RunAsync(ATask, False, False);
// while not finished, yield to the scheduler to continue the q
while ATask.Status < tsFinished do
FCurrentTask.Yield;
if ATask.Status = tsError then
raise ATask.Error;
finally
if FreeTask then
ATask.Free;
end;
end;
{generic function TExecutor.Await<TResult>(ATask: specialize TRVTask<TResult>; FreeTask: Boolean = True): TResult;
begin
try
Self.Await(ATask, False);
Result := ATask.TaskResult;
finally
if FreeTask then
ATask.Free;
end;
end;}
procedure TExecutor.Yield;
begin
if (TThread.CurrentThread <> FThread) or not Assigned(FCurrentTask) then
raise ENotATaskException.Create('Can only yield inside an asynchronous job');
FCurrentTask.Yield;
end;
procedure TExecutor.Sleep(time: QWord);
begin
if (TThread.CurrentThread <> FThread) or not Assigned(FCurrentTask) then
raise ENotATaskException.Create('Can only sleep inside an asynchronous job');
FCurrentTask.Sleep(time);
end;
procedure TExecutor.Run;
var
NextTask: TTaskQueueEntry;
begin
FThread := TThread.CurrentThread;
RegisterExecutor(FThread.ThreadID, self);
while FTaskQueue.Count > 0 do
begin
NextTask := FTaskQueue.Extract;
ExecTask(NextTask.Task);
// if task is not finished, reschedule
if NextTask.Task.Status < tsFinished then
ScheduleTask(NextTask)
else
FinalizeTask(NextTask);
end;
RemoveExecutor(Self);
end;
{ TRVTask }
procedure TRVTask.Execute;
begin
FResult := Default(T);
end;
{ TTask }
class constructor TTask.InitStatics;
begin
TTask.StackCache := TStackCache.Create;
end;
class destructor TTask.CleanupStatics;
var
st: TStackData;
begin
for st in TTask.StackCache do
Freemem(st.Memory);
TTask.StackCache.Free;
end;
class function TTask.AllocStack(ASize: SizeInt): TStackData;
begin
if (ASize = DefaultTaskStackSize) and (TTask.StackCache.Count > 0) then
Result := TTask.StackCache.ExtractIndex(TTask.StackCache.Count - 1)
else
begin
Result.Size := ASize;
Result.Memory := GetMem(ASize);
end;
end;
class procedure TTask.FreeStack(constref AStackData: TStackData);
begin
if not Assigned(AStackData.Memory) then Exit;
if AStackData.Size = DefaultTaskStackSize then
TTask.StackCache.Add(AStackData)
else
FreeMem(AStackData.Memory, AStackData.Size);
end;
procedure TTask.DoExecute(a: Boolean=True);
begin
// Start the execution
FStatus := tsRunning;
try
Execute;
FStatus := tsFinished;
except on E: Exception do begin
FError := E;
FStatus := tsError;
end
end;
end;
constructor TTask.Create(AStackSize: SizeInt);
begin
FTerminated := False;
FError := nil;
FStatus := tsNone;
FExecutor := nil;
// We don't allocate the stack now, so if another task before this one finishes
// we might be able to reuse it's memory before allocating new one
FStack.Size := AStackSize;
FStack.Memory := nil;
end;
destructor TTask.Destroy;
begin
TTask.FreeStack(FStack);
inherited Destroy;
end;
procedure TTask.Run(AExecutor: TExecutor);
var
StackPtr, BasePtr, NewStackPtr, NewBasePtr: Pointer;
FrameSize: SizeInt;
begin
FExecutor := AExecutor;
// setup stack
if not Assigned(FStack.Memory) then
FStack := TTask.AllocStack(FStack.Size);
// copy current frame so we can use local variables and arguments
{$AsmMode intel}
asm
MOV StackPtr, RSP
MOV BasePtr, RBP
end;
FrameSize := BasePtr - StackPtr;
NewBasePtr := FStack.Memory + FStack.Size;
NewStackPtr := NewBasePtr - FrameSize;
Move(PByte(StackPtr)^, PByte(NewStackPtr)^, FrameSize);
// move to new stack
asm
MOV RSP, NewStackPtr
MOV RBP, NewBasePtr
end;
DoExecute;
longjmp(AExecutor.FSchedulerEnv, 1);
end;
procedure TTask.Resume;
begin
FStatus := tsRunning;
longjmp(FTaskEnv, 1);
end;
procedure TTask.Yield;
begin
if FExecutor.FCurrentTask <> Self then
raise ETaskNotActiveException.Create('Only an active task can yield');
// store current state:
if setjmp(FTaskEnv) = 0 then
// go to scheduler
longjmp(FExecutor.FSchedulerEnv, 1);
// On return, check if we got terminated, if so notify task via exception
if Terminated then
raise ETaskTerminatedException.Create('Task terminated during waiting');
end;
procedure TTask.Sleep(Time: QWord);
var
Start: QWord;
begin
Start := GetTickCount64;
repeat
Yield;
until GetTickCount64 - Start > Time;
end;
procedure TTask.Stop;
begin
Terminate;
Yield;
end;
procedure TTask.Terminate;
begin
FTerminated := True;
end;
end.
|
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi
by Dennis D. Spreen <dennis@spreendigital.de>
see Behavior3.pas header for full license information }
unit Behavior3.Core.BaseNode;
interface
uses
System.Rtti, System.JSON, System.Generics.Collections, System.Generics.Defaults,
Behavior3, Behavior3.Core.Tick, Behavior3.Core.BehaviorTree;
type
(**
* The BaseNode class is used as super class to all nodes in BehaviorJS. It
* comprises all common variables and methods that a node must have to
* execute.
*
* **IMPORTANT:** Do not inherit from this class, use `b3.Composite`,
* `b3.Decorator`, `b3.Action` or `b3.Condition`, instead.
*
* The attributes are specially designed to serialization of the node in a
* JSON format. In special, the `parameters` attribute can be set into the
* visual editor (thus, in the JSON file), and it will be used as parameter
* on the node initialization at `BehaviorTree.load`.
*
* BaseNode also provide 5 callback methods, which the node implementations
* can override. They are `enter`, `open`, `tick`, `close` and `exit`. See
* their documentation to know more. These callbacks are called inside the
* `_execute` method, which is called in the tree traversal.
*
* @module b3
* @class BaseNode
**)
TB3BaseNode = class abstract (TObject)
protected
function LoadProperty<T>(JsonNode: TJSONValue; const Key: String; Default: T): T;
procedure SaveProperty<T>(JsonNode: TJSONValue; const Key: String; Value: T);
public
(**
* This is the main method to propagate the tick signal to this node. This
* method calls all callbacks: `enter`, `open`, `tick`, `close`, and
* `exit`. It only opens a node if it is not already open. In the same
* way, this method only close a node if the node returned a status
* different of `b3.RUNNING`.
*
* @method _execute
* @param {Tick} tick A tick instance.
* @return {Constant} The tick state.
* @protected
**)
function _Execute(Tick: TB3Tick): TB3Status; virtual;
(**
* Wrapper for enter method.
* @method _enter
* @param {Tick} tick A tick instance.
* @protected
**)
procedure _Enter(Tick: TB3Tick); virtual;
(**
* Wrapper for open method.
* @method _open
* @param {Tick} tick A tick instance.
* @protected
**)
procedure _Open(Tick: TB3Tick); virtual;
(**
* Wrapper for tick method.
* @method _tick
* @param {Tick} tick A tick instance.
* @return {Constant} A state constant.
* @protected
**)
function _Tick(Tick: TB3Tick): TB3Status; virtual;
(**
* Wrapper for close method.
* @method _close
* @param {Tick} tick A tick instance.
* @protected
**)
procedure _Close(Tick: TB3Tick); virtual;
(**
* Wrapper for exit method.
* @method _exit
* @param {Tick} tick A tick instance.
* @protected
**)
procedure _Exit(Tick: TB3Tick); virtual;
public
(**
* Node ID.
* @property {string} id
* @readonly
**)
Id: String;
(**
* Node name. Must be a unique identifier, preferable the same name of the
* class. You have to set the node name in the prototype.
*
* @property {String} name
* @readonly
**)
Name: String;
(**
* Node category. Must be `b3.COMPOSITE`, `b3.DECORATOR`, `b3.ACTION` or
* `b3.CONDITION`. This is defined automatically be inheriting the
* correspondent class.
*
* @property {CONSTANT} category
* @readonly
**)
Category: TB3Category;
(**
* Node title.
* @property {String} title
* @optional
* @readonly
**)
Title: String;
(**
* Node description.
* @property {String} description
* @optional
* @readonly
**)
Description: String;
(**
* Tree reference
* @property {BehaviorTree} Tree
* @readonly
**)
Tree: TB3BehaviorTree;
(**
* Initialization method.
* @method initialize
* @constructor
**)
constructor Create; overload; virtual;
(**
* Enter method, override this to use. It is called every time a node is
* asked to execute, before the tick itself.
*
* @method enter
* @param {Tick} tick A tick instance.
**)
procedure Enter(Tick: TB3Tick); virtual;
(**
* Open method, override this to use. It is called only before the tick
* callback and only if the not isn't closed.
*
* Note: a node will be closed if it returned `b3.RUNNING` in the tick.
*
* @method open
* @param {Tick} tick A tick instance.
**)
procedure Open(Tick: TB3Tick); virtual;
(**
* Tick method, override this to use. This method must contain the real
* execution of node (perform a task, call children, etc.). It is called
* every time a node is asked to execute.
*
* @method tick
* @param {Tick} tick A tick instance.
**)
function Tick(Tick: TB3Tick): TB3Status; virtual;
(**
* Close method, override this to use. This method is called after the tick
* callback, and only if the tick return a state different from
* `b3.RUNNING`.
*
* @method close
* @param {Tick} tick A tick instance.
**)
procedure Close(Tick: TB3Tick); virtual;
(**
* Exit method, override this to use. Called every time in the end of the
* execution.
*
* @method exit
* @param {Tick} tick A tick instance.
**)
procedure Exit_(Tick: TB3Tick); virtual;
procedure Load(JsonNode: TJSONValue); overload; virtual;
procedure Save(JsonObject: TJSONObject); overload; virtual;
end;
TB3BaseNodeClass = class of TB3BaseNode;
TB3BaseNodeList = TObjectList<TB3BaseNode>;
TB3BaseNodeDictionary = TObjectDictionary<String, TB3BaseNode>;
TB3BaseNodeDictionaryItem = TPair<String, TB3BaseNode>;
implementation
{ TB3BaseNode }
uses
System.SysUtils,
Behavior3.Helper;
constructor TB3BaseNode.Create;
var
GUID: TGUID;
begin
CreateGUID(GUID);
Id := GUID.ToString;
end;
function TB3BaseNode._Execute(Tick: TB3Tick): TB3Status;
var
Status: TB3Status;
begin
// ENTER
_Enter(Tick);
// OPEN
if not Tick.Blackboard.Get('isOpen', Tick.Tree.Id, Id).AsBoolean then
_Open(Tick);
// TICK
Status := _Tick(Tick);
// CLOSE
if Status <> Behavior3.Running then
_Close(Tick);
// EXIT
_Exit(Tick);
Result := Status;
end;
procedure TB3BaseNode._Enter(Tick: TB3Tick);
begin
Tick._EnterNode(Self);
Enter(Tick);
end;
procedure TB3BaseNode._Open(Tick: TB3Tick);
begin
Tick._OpenNode(Self);
Tick.Blackboard.&Set('isOpen', True, Tick.Tree.Id, Id);
Open(Tick);
end;
function TB3BaseNode._Tick(Tick: TB3Tick): TB3Status;
begin
Tick._TickNode(self);
Result := Self.Tick(Tick);
end;
procedure TB3BaseNode._Close(Tick: TB3Tick);
begin
Tick._CloseNode(Self);
Tick.Blackboard.&Set('isOpen', False, Tick.Tree.Id, Id);
Close(Tick);
end;
procedure TB3BaseNode._Exit(Tick: TB3Tick);
begin
Tick._ExitNode(Self);
Exit_(Tick);
end;
procedure TB3BaseNode.Enter(Tick: TB3Tick);
begin
// Enter method, override this to use. It is called every time a node is
// asked to execute, before the tick itself.
end;
procedure TB3BaseNode.Open(Tick: TB3Tick);
begin
// Open method, override this to use. It is called only before the tick
// callback and only if the not isn't closed.
// Note: a node will be closed if it returned `b3.RUNNING` in the tick.
end;
function TB3BaseNode.Tick(Tick: TB3Tick): TB3Status;
begin
// Tick method, override this to use. This method must contain the real
// execution of node (perform a task, call children, etc.). It is called
// every time a node is asked to execute.
Result := Behavior3.Error;
end;
procedure TB3BaseNode.Close(Tick: TB3Tick);
begin
// Close method, override this to use. This method is called after the tick
// callback, and only if the tick return a state different from
// `b3.RUNNING`.
end;
procedure TB3BaseNode.Exit_(Tick: TB3Tick);
begin
// Exit method, override this to use. Called every time in the end of the
// execution.
end;
function TB3BaseNode.LoadProperty<T>(JsonNode: TJSONValue; const Key: String; Default: T): T;
var
JsonObj: TJSONObject;
begin
JsonObj := TJSONObject(JsonNode).Get('properties').JsonValue as TJSONObject;
Result := JsonObj.GetValue(Key, Default);
end;
procedure TB3BaseNode.SaveProperty<T>(JsonNode: TJSONValue; const Key: String; Value: T);
var
JsonObj: TJSONObject;
begin
JsonObj := TJSONObject(JsonNode).Get('properties').JsonValue as TJSONObject;
// JsonObj.AddPair(Key, Default);
end;
procedure TB3BaseNode.Load(JsonNode: TJSONValue);
begin
Name := JsonNode.GetValue('name', Name);
Id := JsonNode.GetValue('id', Id);
Description := JsonNode.GetValue('description', Description);
Title := JsonNode.GetValue('title', Title);
end;
procedure TB3BaseNode.Save(JsonObject: TJSONObject);
begin
JsonObject.AddPair('name', Name);
JsonObject.AddPair('id', Id);
JsonObject.AddPair('description', Description);
JsonObject.AddPair('title', Title);
end;
end.
|
unit uFrmMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.ComCtrls, Vcl.StdCtrls
, uData, qmsgpack, QWorker, HPSocketSDKUnit;
type
TFrmMain = class(TForm)
memLog: TMemo;
StatusBar1: TStatusBar;
Panel1: TPanel;
btnServerConn: TButton;
btnServerDisconn: TButton;
btnConfig: TButton;
btnTest: TButton;
procedure btnTestClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnServerConnClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnConfigClick(Sender: TObject);
procedure btnServerDisconnClick(Sender: TObject);
private
{ Private declarations }
procedure WmAddLog(var Msg: TMessage); message WM_ADD_LOG;
public
{ Public declarations }
procedure SetAppState(AState: EnAppState);
end;
var
FrmMain: TFrmMain;
appState: EnAppState;
pClient: Pointer;
pListener: Pointer;
implementation
uses
uSMS, uPublic, uFrmConfig;//, ufrmTest;
{$R *.dfm}
function fnSendData(AData: Pointer; ADataLen: integer): Boolean;
begin
Result := False;
try
Result := HP_Client_Send(pClient, AData, ADataLen);
except
AddLogMsg('SendData fail[%s]...', [GetLastError()]);
end;
end;
function fnRetResult(ACmd, APriorCmd: TCommType; AClientID: DWORD; AContent: string): Boolean;
var
vMsgPack: TQMsgPack;
vBuf: TBytes;
begin
vMsgPack := TQMsgPack.Create;
try
vMsgPack.Add('Cmd', Integer(ACmd));
vMsgPack.Add('PriorCmd', Integer(APriorCmd));
vMsgPack.Add('ClientId', AClientID);
if AContent = 'OK' then
vMsgPack.Add('Ret', Integer(rsSuccess))
else
vMsgPack.Add('Ret', Integer(rsFail));
vMsgPack.Add('Content', AContent);
vBuf := vMsgPack.Encode;
fnSendData(vBuf, Length(vBuf));
finally
SetLength(vBuf, 0);
FreeAndNil(vMsgPack);
end;
end;
function SendGroupName(): Boolean;
var
vMsgPack: TQMsgPack;
vBuf: TBytes;
begin
vMsgPack := TQMsgPack.Create;
try
vMsgPack.Add('Cmd', Integer(ctGroupName));
vMsgPack.Add('GroupName', GConfig.GroupName);
vBuf := vMsgPack.Encode;
fnSendData(vBuf, Length(vBuf));
finally
SetLength(vBuf, 0);
FreeAndNil(vMsgPack);
end;
end;
function DoSendSms(AMsgPack: TQMsgPack): string;
var
vCom: TModelCom;
begin
Result := '发送短信时发生未知错误';
if AMsgPack = nil then begin
Result := '数据有问题';
Exit;
end;
vCom := TModelCom.Create(AMsgPack.ItemByName('ComPort').AsString, AMsgPack.ItemByName('TargetPhone').AsString, GConfig.BaudRate);
try
Result := vCom.Open();
if Result <> 'OK' then
begin
AddLogMsg(Result, []);
Exit;
end;
Result := vCom.SendSms(AMsgPack.ItemByName('MsgContent').AsString);
if Result <> 'OK' then
begin
AddLogMsg(Result, []);
Exit;
end;
finally
vCom.Close();
FreeAndNil(vCom);
end;
end;
function DoRecvSms(var AMsgPack: TQMsgPack): string;
begin
Result := '接收短信时发生未知错误';
end;
procedure DoWork(AJob: PQJob);
var
vCmdType: TCommType;
vMsgPack: TQMsgPack;
sRet: string;
begin
vMsgPack := AJob.Data;
try
if vMsgPack = nil then begin
AddLogMsg('数据解析失败', []);
Exit;
end;
vCmdType := TCommType(vMsgPack.ItemByName('Cmd').AsInteger);
case vCmdType of
ctSendMsg: sRet := DoSendSms(vMsgPack);
ctRecvMsg: sRet := DoRecvSms(vMsgPack);
else
sRet := Format('未知命令: %d', [Integer(vCmdType)]);
end;
fnRetResult(ctResult, vCmdType, vMsgPack.ItemByName('ClientId').AsInteger, sRet);
finally
FreeAndNil(vMsgPack);
end;
end;
function DispatchData(const pData: Pointer; iLength: Integer): Boolean;
var
vMsgPack: TQMsgPack;
//vBuf: TBytes;
begin
vMsgPack := TQMsgPack.Create;
try
//SetLength(vBuf, iLength);
//CopyMemory(vBuf, pData, iLength);
vMsgPack.Parse(pData, iLength);
if vMsgPack.ItemByName('Cmd').IsNull then
begin
AddLogMsg('数据解析失败', []);
Exit;
end;
QWorker.Workers.Post(DoWork, vMsgPack);
except
if vMsgPack <> nil then FreeAndNil(vMsgPack);
end;
end;
function OnSend(dwConnID: DWORD; const pData: Pointer; iLength: Integer): En_HP_HandleResult; stdcall;
begin
AddLogMsg('[%d,OnSend] -> (%d bytes)', [dwConnID, iLength], True);
Result := HP_HR_OK;
end;
function OnReceive(dwConnID: DWORD; const pData: Pointer; iLength: Integer): En_HP_HandleResult; stdcall;
begin
DispatchData(pData, iLength);
AddLogMsg('[%d,OnReceive] -> (%d bytes)', [dwConnID, iLength], True);
Result := HP_HR_OK;
end;
function OnConnect(dwConnID: DWORD): En_HP_HandleResult; stdcall;
begin
if GConfig.SyncSocket then
frmMain.SetAppState(ST_STARTED);
AddLogMsg('[%d,OnConnect]', [dwConnID]);
SendGroupName;
Result := HP_HR_OK;
end;
function OnCloseConn(dwConnID: DWORD): En_HP_HandleResult; stdcall;
begin
AddLogMsg('[%d,OnCloseConn]', [dwConnID]);
FrmMain.SetAppState(ST_STOPED);
Result := HP_HR_OK;
end;
function OnError(dwConnID: DWORD; enOperation: En_HP_SocketOperation; iErrorCode: Integer): En_HP_HandleResult; stdcall;
begin
AddLogMsg('[%d,OnError] -> OP:%d,CODE:%d', [dwConnID, Integer(enOperation), iErrorCode]);
frmMain.SetAppState(ST_STOPED);
Result := HP_HR_OK;
end;
procedure TFrmMain.btnTestClick(Sender: TObject);
begin
//fnOpenTest;
end;
procedure TFrmMain.btnServerConnClick(Sender: TObject);
begin
// 写在这个位置是上面可能会异常
SetAppState(ST_STARTING);
if (HP_Client_Start(pClient, PWideChar(GConfig.Host), USHORT(GConfig.Port), GConfig.SyncSocket)) then
begin
if not GConfig.SyncSocket then
SetAppState(ST_STARTED);
AddLogMsg('$Client Starting ... -> (%s:%d)', [GConfig.Host, GConfig.Port]);
end else
begin
SetAppState(ST_STOPED);
AddLogMsg('$Client Start Error -> %s(%d)', [HP_Client_GetLastErrorDesc(pClient), Integer(HP_Client_GetLastError(pClient))]);
end;
end;
procedure TFrmMain.btnServerDisconnClick(Sender: TObject);
begin
if (HP_Client_Stop(pClient)) then
AddLogMsg('Client Stop', [])
else
begin
AddLogMsg('Client Stop Error -> %s(%d)', [HP_Client_GetLastErrorDesc(pClient),
Integer(HP_Client_GetLastError(pClient))]);
Exit;
end;
SetAppState(ST_STOPED);
end;
procedure TFrmMain.btnConfigClick(Sender: TObject);
begin
if not uFrmConfig.fnOpenCfg then Exit;
StatusBar1.Panels[0].Text := Format(' 猫池组名称:%s', [GConfig.GroupName]);
end;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
memLog.Lines.Clear;
uData.hLog := Self.Handle;
StatusBar1.Panels[0].Text := Format(' 猫池组名称:%s', [GConfig.GroupName]);
pListener := Create_HP_TcpClientListener();
// 创建 Socket 对象
pClient := Create_HP_TcpClient(pListener);
// 设置 Socket 监听器回调函数
HP_Set_FN_Client_OnConnect(pListener, OnConnect);
HP_Set_FN_Client_OnSend(pListener, OnSend);
HP_Set_FN_Client_OnReceive(pListener, OnReceive);
HP_Set_FN_Client_OnClose(pListener, OnCloseConn);
HP_Set_FN_Client_OnError(pListener, OnError);
SetAppState(EnAppState.ST_STOPED);
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
// 销毁 Socket 对象
Destroy_HP_TcpClient(pClient);
// 销毁监听器对象
Destroy_HP_TcpClientListener(pListener);
end;
procedure TFrmMain.SetAppState(AState: EnAppState);
begin
appState := AState;
btnConfig.Enabled := (appState = EnAppState.ST_STOPED);
//btnTest.Enabled := (appState = EnAppState.ST_STOPED);
btnServerConn.Enabled := (appState = EnAppState.ST_STOPED);
btnServerDisconn.Enabled := (appState = EnAppState.ST_STARTED);
case appState of
EnAppState.ST_STARTING: StatusBar1.Panels[1].Text := ' 状态:正在连接';
EnAppState.ST_STARTED: StatusBar1.Panels[1].Text := ' 状态:已连接';
EnAppState.ST_STOPING: StatusBar1.Panels[1].Text := ' 状态:正在断开连接';
EnAppState.ST_STOPED: StatusBar1.Panels[1].Text := ' 状态:未连接';
end;
end;
procedure TFrmMain.WmAddLog(var Msg: TMessage);
var
sMsg: string;
begin
if memLog.Lines.Count > 1000 then
memLog.Clear;
sMsg := string(Msg.LParam);
memLog.Lines.Add(sMsg);
end;
end.
|
{ *************************************************************************** }
{ }
{ Audio Tools Library }
{ Class TFLACfile - for manipulating with FLAC file information }
{ }
{ http://mac.sourceforge.net/atl/ }
{ e-mail: macteam@users.sourceforge.net }
{ }
{ Copyright (c) 2000-2002 by Jurgen Faul }
{ Copyright (c) 2003-2005 by The MAC Team }
{ }
{ Version 1.4 (April 2005) by Gambit }
{ - updated to unicode file access }
{ }
{ Version 1.3 (13 August 2004) by jtclipper }
{ - unit rewritten, VorbisComment is obsolete now }
{ }
{ Version 1.2 (23 June 2004) by sundance }
{ - Check for ID3 tags (although not supported) }
{ - Don't parse for other FLAC metablocks if FLAC header is missing }
{ }
{ Version 1.1 (6 July 2003) by Erik }
{ - Class: Vorbis comments (native comment to FLAC files) added }
{ }
{ Version 1.0 (13 August 2002) }
{ - Info: channels, sample rate, bits/sample, file size, duration, ratio }
{ - Class TID3v1: reading & writing support for ID3v1 tags }
{ - Class TID3v2: reading & writing support for ID3v2 tags }
{ }
{ This library is free software; you can redistribute it and/or }
{ modify it under the terms of the GNU Lesser General Public }
{ License as published by the Free Software Foundation; either }
{ version 2.1 of the License, or (at your option) any later version. }
{ }
{ This library is distributed in the hope that it will be useful, }
{ but WITHOUT ANY WARRANTY; without even the implied warranty of }
{ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU }
{ Lesser General Public License for more details. }
{ }
{ You should have received a copy of the GNU Lesser General Public }
{ License along with this library; if not, write to the Free Software }
{ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA }
{ }
{ --------------------------------------------------------------------------- }
{ Adapted to Lazarus by monta 2008 }
{ *************************************************************************** }
unit FLACfile;
{$mode objfpc}
interface
uses
Classes, SysUtils, StrUtils;//;, ID3v2, TntClasses, TntSysUtils, CommonATL;
const
META_STREAMINFO = 0;
META_PADDING = 1;
META_APPLICATION = 2;
META_SEEKTABLE = 3;
META_VORBIS_COMMENT = 4;
META_CUESHEET = 5;
type
TFlacHeader = record
StreamMarker: array[1..4] of Char; //should always be 'fLaC'
MetaDataBlockHeader: array[1..4] of Byte;
Info: array[1..18] of Byte;
MD5Sum: array[1..16] of Byte;
end;
TMetaData = record
MetaDataBlockHeader: array[1..4] of Byte;
Data: TMemoryStream;
end;
TFLACfile = class(TObject)
private
FHeader: TFlacHeader;
FFileName: WideString;
FPaddingIndex: integer;
FPaddingLast: boolean;
FPaddingFragments: boolean;
FVorbisIndex: integer;
FPadding: integer;
FVCOffset: integer;
FAudioOffset: integer;
FChannels: byte;
FSampleRate: integer;
FBitsPerSample: byte;
FBitrate: integer;
FFileLength: integer;
FSamples: Int64;
aMetaBlockOther: array of TMetaData;
// tag data
FVendor: string;
FTagSize: integer;
FExists: boolean;
// FID3v2: TID3v2;
function FGetHasLyrics: boolean;
procedure FResetData( const bHeaderInfo, bTagFields :boolean );
function FIsValid: Boolean;
function FGetDuration: Double;
function FGetRatio: Double;
function FGetChannelMode: string;
function GetInfo( sFile: WideString; bSetTags: boolean ): boolean;
procedure AddMetaDataOther( aMetaHeader: array of Byte; stream: TFileStream; const iBlocklength,iIndex: integer );
procedure ReadTag( Source: TFileStream; bSetTagFields: boolean );
function RebuildFile( const sFile: WideString; VorbisBlock: TStringStream ): Boolean;
public
TrackString: string;
Title: string;
Artist: string;
Album: string;
Year: string;
Genre: string;
Comment: string;
//extra
xTones: string;
xStyles: string;
xMood: string;
xSituation: string;
xRating: string;
xQuality: string;
xTempo: string;
xType: string;
//
Composer: string;
Language: string;
Copyright: string;
Link: string;
Encoder: string;
Lyrics: string;
Performer: string;
License: string;
Organization: string;
Description: string;
Location: string;
Contact: string;
ISRC: string;
aExtraFields: array of array of string;
constructor Create;
destructor Destroy; override;
function ReadFromFile( const sFile: WideString ): boolean;
function SaveToFile( const sFile: WideString; const bBasicOnly: boolean = false ): boolean;
function RemoveFromFile( const sFile: WideString ):boolean;
procedure AddExtraField(const sID, sValue: string);
property Channels: Byte read FChannels; // Number of channels
property SampleRate: Integer read FSampleRate; // Sample rate (hz)
property BitsPerSample: Byte read FBitsPerSample; // Bits per sample
property FileLength: integer read FFileLength; // File length (bytes)
property Samples: Int64 read FSamples; // Number of samples
property Valid: Boolean read FIsValid; // True if header valid
property Duration: Double read FGetDuration; // Duration (seconds)
property Ratio: Double read FGetRatio; // Compression ratio (%)
property Bitrate: integer read FBitrate;
property ChannelMode: string read FGetChannelMode;
property Exists: boolean read FExists;
property Vendor: string read FVendor;
property FileName: WideString read FFileName;
property AudioOffset: integer read FAudioOffset; //offset of audio data
property HasLyrics: boolean read FGetHasLyrics;
end;
var
bTAG_PreserveDate: boolean;
implementation
(* -------------------------------------------------------------------------- *)
procedure TFLACfile.FResetData( const bHeaderInfo, bTagFields :boolean );
var
i: integer;
begin
if bHeaderInfo then begin
FFileName := '';
FPadding := 0;
FPaddingLast := false;
FPaddingFragments := false;
FChannels := 0;
FSampleRate := 0;
FBitsPerSample := 0;
FFileLength := 0;
FSamples := 0;
FVorbisIndex := 0;
FPaddingIndex := 0;
FVCOffset := 0;
FAudioOffset := 0;
for i := 0 to Length( aMetaBlockOther ) - 1 do aMetaBlockOther[ i ].Data.Free;
SetLength( aMetaBlockOther, 0 );
end;
//tag data
if bTagFields then begin
FVendor := '';
FTagSize := 0;
FExists := false;
Title := '';
Artist := '';
Album := '';
TrackString := '';
Year := '';
Genre := '';
Comment := '';
//extra
xTones := '';
xStyles := '';
xMood := '';
xSituation := '';
xRating := '';
xQuality := '';
xTempo := '';
xType := '';
//
Composer := '';
Language := '';
Copyright := '';
Link := '';
Encoder := '';
Lyrics := '';
Performer := '';
License := '';
Organization := '';
Description := '';
Location := '';
Contact := '';
ISRC := '';
SetLength( aExtraFields, 0 );
end;
end;
(* -------------------------------------------------------------------------- *)
// Check for right FLAC file data
function TFLACfile.FIsValid: Boolean;
begin
result := (FHeader.StreamMarker = 'fLaC') and
(FChannels > 0) and
(FSampleRate > 0) and
(FBitsPerSample > 0) and
(FSamples > 0);
end;
(* -------------------------------------------------------------------------- *)
function TFLACfile.FGetDuration: Double;
begin
if (FIsValid) and (FSampleRate > 0) then begin
result := FSamples / FSampleRate
end else begin
result := 0;
end;
end;
(* -------------------------------------------------------------------------- *)
// Get compression ratio
function TFLACfile.FGetRatio: Double;
begin
if FIsValid then begin
result := FFileLength / (FSamples * FChannels * FBitsPerSample / 8) * 100
end else begin
result := 0;
end;
end;
(* -------------------------------------------------------------------------- *)
// Get channel mode
function TFLACfile.FGetChannelMode: string;
begin
if FIsValid then begin
case FChannels of
1 : result := 'Mono';
2 : result := 'Stereo';
else result := 'Multi Channel';
end;
end else begin
result := '';
end;
end;
(* -------------------------------------------------------------------------- *)
function TFLACfile.FGetHasLyrics: boolean;
begin
result := ( Trim( Lyrics ) <> '' );
end;
(* -------------------------------------------------------------------------- *)
constructor TFLACfile.Create;
begin
inherited;
// FID3v2 := TID3v2.Create;
FResetData( true, true );
end;
destructor TFLACfile.Destroy;
begin
FResetData( true, true );
// FID3v2.Free;
inherited;
end;
(* -------------------------------------------------------------------------- *)
function TFLACfile.ReadFromFile( const sFile: WideString ): boolean;
begin
FResetData( false, true );
result := GetInfo( sFile, true );
end;
(* -------------------------------------------------------------------------- *)
function TFLACfile.GetInfo( sFile: WideString; bSetTags: boolean ): boolean;
var
SourceFile: TFileStream;
aMetaDataBlockHeader: array[1..4] of byte;
iBlockLength, iMetaType, iIndex: integer;
bPaddingFound: boolean;
begin
result := true;
bPaddingFound := false;
FResetData( true, false );
try
{ Read data from ID3 tags }
// FID3v2.ReadFromFile(sFile);
// Set read-access and open file
SourceFile := TFileStream.Create( sFile, fmOpenRead or fmShareDenyWrite);
FFileLength := SourceFile.Size;
FFileName := sFile;
{ Seek past the ID3v2 tag, if there is one }
// if FID3v2.Exists then begin
// SourceFile.Seek(FID3v2.Size, soFromBeginning)
// end;
// Read header data
FillChar( FHeader, SizeOf(FHeader), 0 );
SourceFile.Read( FHeader, SizeOf(FHeader) );
// Process data if loaded and header valid
if FHeader.StreamMarker = 'fLaC' then begin
with FHeader do begin
FChannels := ( Info[13] shr 1 and $7 + 1 );
FSampleRate := ( Info[11] shl 12 or Info[12] shl 4 or Info[13] shr 4 );
FBitsPerSample := ( Info[13] and 1 shl 4 or Info[14] shr 4 + 1 );
FSamples := ( Info[15] shl 24 or Info[16] shl 16 or Info[17] shl 8 or Info[18] );
end;
if (FHeader.MetaDataBlockHeader[1] and $80) <> 0 then exit; //no metadata blocks exist
iIndex := 0;
repeat // read more metadata blocks if available
SourceFile.Read( aMetaDataBlockHeader, 4 );
iIndex := iIndex + 1; // metadatablock index
iBlockLength := (aMetaDataBlockHeader[2] shl 16 or aMetaDataBlockHeader[3] shl 8 or aMetaDataBlockHeader[4]); //decode length
if iBlockLength <= 0 then exit; // can it be 0 ?
iMetaType := (aMetaDataBlockHeader[1] and $7F); // decode metablock type
if iMetaType = META_VORBIS_COMMENT then begin // read vorbis block
FVCOffset := SourceFile.Position;
FTagSize := iBlockLength;
FVorbisIndex := iIndex;
ReadTag(SourceFile, bSetTags); // set up fields
end else if (iMetaType = META_PADDING) and not bPaddingFound then begin // we have padding block
FPadding := iBlockLength; // if we find more skip & put them in metablock array
FPaddingLast := ((aMetaDataBlockHeader[1] and $80) <> 0);
FPaddingIndex := iIndex;
bPaddingFound := true;
SourceFile.Seek(FPadding, soCurrent); // advance into file till next block or audio data start
end else begin // all other
if iMetaType <= 5 then begin // is it a valid metablock ?
if (iMetaType = META_PADDING) then begin // set flag for fragmented padding blocks
FPaddingFragments := true;
end;
AddMetaDataOther(aMetaDataBlockHeader, SourceFile, iBlocklength, iIndex);
end else begin
FSamples := 0; //ops...
exit;
end;
end;
until ((aMetaDataBlockHeader[1] and $80) <> 0); // until is last flag ( first bit = 1 )
end;
finally
if FIsValid then begin
FAudioOffset := SourceFile.Position; // we need that to rebuild the file if nedeed
FBitrate := Round( ( ( FFileLength - FAudioOffset ) / 1000 ) * 8 / FGetDuration ); //time to calculate average bitrate
end else begin
result := false;
end;
FreeAndNil(SourceFile);
end;
end;
(* -------------------------------------------------------------------------- *)
procedure TFLACfile.AddMetaDataOther( aMetaHeader: array of Byte; stream: TFileStream; const iBlocklength,iIndex: integer );
var
iMetaLen: integer;
begin
// enlarge array
iMetaLen := Length( aMetaBlockOther ) + 1;
SetLength( aMetaBlockOther, iMetaLen );
// save header
aMetaBlockOther[ iMetaLen - 1 ].MetaDataBlockHeader[1] := aMetaHeader[0];
aMetaBlockOther[ iMetaLen - 1 ].MetaDataBlockHeader[2] := aMetaHeader[1];
aMetaBlockOther[ iMetaLen - 1 ].MetaDataBlockHeader[3] := aMetaHeader[2];
aMetaBlockOther[ iMetaLen - 1 ].MetaDataBlockHeader[4] := aMetaHeader[3];
// save content in a stream
aMetaBlockOther[ iMetaLen - 1 ].Data := TMemoryStream.Create;
aMetaBlockOther[ iMetaLen - 1 ].Data.Position := 0;
aMetaBlockOther[ iMetaLen - 1 ].Data.CopyFrom( stream, iBlocklength );
end;
(* -------------------------------------------------------------------------- *)
procedure TFLACfile.ReadTag( Source: TFileStream; bSetTagFields: boolean );
var
i, iCount, iSize, iSepPos: Integer;
Data: array of Char;
sFieldID, sFieldData, sField: string;
begin
Source.Read( iSize, SizeOf( iSize ) ); // vendor
SetLength( Data, iSize );
Source.Read( Data[ 0 ], iSize );
FVendor := StrPas(PChar(Data));//String( Data );
Source.Read( iCount, SizeOf( iCount ) ); //fieldcount
FExists := ( iCount > 0 );
for i := 0 to iCount - 1 do begin
Source.Read(iSize, SizeOf(iSize));
SetLength(Data , iSize );
Source.Read(Data[0], iSize );
sField := Copy(StrPas(PChar(Data)), 0, iSize);
if not bSetTagFields then Continue; // if we don't want to re asign fields we skip
iSepPos := Pos('=', sField);
if iSepPos > 0 then begin
sFieldID := UpperCase(Trim(Copy( sField, 1, iSepPos - 1) ));
sFieldData := Trim(Copy( sField, iSepPos + 1, MaxInt));
if (sFieldID = 'TRACKNUMBER') and (TrackString = '') then begin
TrackString := sFieldData;
end else if (sFieldID = 'ARTIST') and (Artist = '') then begin
Artist := sFieldData;
end else if (sFieldID = 'ALBUM') and (Album = '') then begin
Album := sFieldData;
end else if (sFieldID = 'TITLE') and (Title = '') then begin
Title := sFieldData;
end else if (sFieldID = 'DATE') and (Year = '') then begin
Year := sFieldData;
end else if (sFieldID = 'GENRE') and (Genre = '') then begin
Genre := sFieldData;
end else if (sFieldID = 'COMMENT') and (Comment = '') then begin
Comment := sFieldData;
end else if (sFieldID = 'COMPOSER') and (Composer = '') then begin
Composer := sFieldData;
end else if (sFieldID = 'LANGUAGE') and (Language = '') then begin
Language := sFieldData;
end else if (sFieldID = 'COPYRIGHT') and (Copyright = '') then begin
Copyright := sFieldData;
end else if (sFieldID = 'URL') and (Link = '') then begin
Link := sFieldData;
end else if (sFieldID = 'ENCODER') and (Encoder = '') then begin
Encoder := sFieldData;
end else if (sFieldID = 'TONES') and (xTones = '') then begin
xTones := sFieldData;
end else if (sFieldID = 'STYLES') and (xStyles = '') then begin
xStyles := sFieldData;
end else if (sFieldID = 'MOOD') and (xMood = '') then begin
xMood := sFieldData;
end else if (sFieldID = 'SITUATION') and (xSituation = '') then begin
xSituation := sFieldData;
end else if (sFieldID = 'RATING') and (xRating = '') then begin
xRating := sFieldData;
end else if (sFieldID = 'QUALITY') and (xQuality = '') then begin
xQuality := sFieldData;
end else if (sFieldID = 'TEMPO') and (xTempo = '') then begin
xTempo := sFieldData;
end else if (sFieldID = 'TYPE') and (xType = '') then begin
xType := sFieldData;
end else if (sFieldID = 'LYRICS') and (Lyrics = '') then begin
Lyrics := sFieldData;
end else if (sFieldID = 'PERFORMER') and (Performer = '') then begin
Performer := sFieldData;
end else if (sFieldID = 'LICENSE') and (License = '') then begin
License := sFieldData;
end else if (sFieldID = 'ORGANIZATION') and (Organization = '') then begin
Organization := sFieldData;
end else if (sFieldID = 'DESCRIPTION') and (Description = '') then begin
Description := sFieldData;
end else if (sFieldID = 'LOCATION') and (Location = '') then begin
Location := sFieldData;
end else if (sFieldID = 'CONTACT') and (Contact = '') then begin
Contact := sFieldData;
end else if (sFieldID = 'ISRC') and (ISRC = '') then begin
ISRC := sFieldData;
end else begin // more fields
AddExtraField( sFieldID, sFieldData );
end;
end;
end;
end;
(* -------------------------------------------------------------------------- *)
procedure TFLACfile.AddExtraField(const sID, sValue: string);
var
iExtraLen: integer;
begin
iExtraLen := Length( aExtraFields ) + 1;
SetLength( aExtraFields, iExtraLen );
SetLength( aExtraFields[ iExtraLen - 1 ], 2 );
aExtraFields[ iExtraLen - 1, 0 ] := sID;
aExtraFields[ iExtraLen - 1, 1 ] := sValue;
end;
(* -------------------------------------------------------------------------- *)
function TFLACfile.SaveToFile( const sFile: WideString; const bBasicOnly: boolean = false ): boolean;
var
i, iFieldCount, iSize: Integer;
VorbisBlock, Tag: TStringStream;
procedure _WriteTagBuff( sID, sData: string );
var
sTmp: string;
iTmp: integer;
begin
if sData <> '' then begin
sTmp := sID + '=' + UTF8Encode( sData );
iTmp := Length( sTmp );
Tag.Write( iTmp, SizeOf( iTmp ) );
Tag.WriteString( sTmp );
iFieldCount := iFieldCount + 1;
end;
end;
begin
try
result := false;
Tag := TStringStream.Create('');
VorbisBlock := TStringStream.Create('');
if not GetInfo( sFile, false ) then exit; //reload all except tag fields
iFieldCount := 0;
_WriteTagBuff( 'TRACKNUMBER', TrackString );
_WriteTagBuff( 'ARTIST', Artist );
_WriteTagBuff( 'ALBUM', Album );
_WriteTagBuff( 'TITLE', Title );
_WriteTagBuff( 'DATE', Year );
_WriteTagBuff( 'GENRE', Genre );
_WriteTagBuff( 'COMMENT', Comment );
_WriteTagBuff( 'COMPOSER', Composer );
_WriteTagBuff( 'LANGUAGE', Language );
_WriteTagBuff( 'COPYRIGHT', Copyright );
_WriteTagBuff( 'URL', Link );
_WriteTagBuff( 'ENCODER', Encoder );
_WriteTagBuff( 'TONES', xTones );
_WriteTagBuff( 'STYLES', xStyles );
_WriteTagBuff( 'MOOD', xMood );
_WriteTagBuff( 'SITUATION', xSituation );
_WriteTagBuff( 'RATING', xRating );
_WriteTagBuff( 'QUALITY', xQuality );
_WriteTagBuff( 'TEMPO', xTempo );
_WriteTagBuff( 'TYPE', xType );
if not bBasicOnly then begin
_WriteTagBuff( 'PERFORMER', Performer );
_WriteTagBuff( 'LICENSE', License );
_WriteTagBuff( 'ORGANIZATION', Organization );
_WriteTagBuff( 'DESCRIPTION', Description );
_WriteTagBuff( 'LOCATION', Location );
_WriteTagBuff( 'CONTACT', Contact );
_WriteTagBuff( 'ISRC', ISRC );
_WriteTagBuff( 'LYRICS', Lyrics );
for i := 0 to Length( aExtraFields ) - 1 do begin
if Trim( aExtraFields[ i, 0 ] ) <> '' then _WriteTagBuff( aExtraFields[ i, 0 ], aExtraFields[ i, 1 ] );
end;
end;
// Write vendor info and number of fields
with VorbisBlock do begin
if FVendor = '' then FVendor := 'reference libFLAC 1.1.0 20030126'; // guess it
iSize := Length( FVendor );
Write( iSize, SizeOf( iSize ) );
WriteString( FVendor );
Write( iFieldCount, SizeOf( iFieldCount ) );
end;
VorbisBlock.CopyFrom( Tag, 0 ); // All tag data is here now
VorbisBlock.Position := 0;
result := RebuildFile( sFile, VorbisBlock );
FExists := result and (Tag.Size > 0 );
finally
FreeAndNil( Tag );
FreeAndNil( VorbisBlock );
end;
end;
(* -------------------------------------------------------------------------- *)
function TFLACfile.RemoveFromFile( const sFile: WideString ):boolean;
begin
FResetData( false, true );
result := SaveToFile( sFile );
if FExists then FExists := not result;
end;
(* -------------------------------------------------------------------------- *)
// saves metablocks back to the file
// always tries to rebuild header so padding exists after comment block and no more than 1 padding block exists
function TFLACfile.RebuildFile( const sFile: WideString; VorbisBlock: TStringStream ): Boolean;
var
Source, Destination: TFileStream;
i, iFileAge, iNewPadding, iMetaCount, iExtraPadding: Integer;
BufferName, sTmp: string;
MetaDataBlockHeader: array[1..4] of Byte;
oldHeader: TFlacHeader;
MetaBlocks: TMemoryStream;
bRebuild, bRearange: boolean;
begin
result := false;
bRearange := false;
iExtraPadding := 0;
if (not FileExists(sFile)) or (FileSetAttr(sFile, 0) <> 0) then exit;
try
iFileAge := 0;
if bTAG_PreserveDate then iFileAge := FileAge( sFile );
// re arrange other metadata in case of
// 1. padding block is not aligned after vorbis comment
// 2. insufficient padding - rearange upon file rebuild
// 3. fragmented padding blocks
iMetaCount := Length( aMetaBlockOther );
if (FPaddingIndex <> FVorbisIndex + 1) or (FPadding <= VorbisBlock.Size - FTagSize ) or FPaddingFragments then begin
MetaBlocks := TMemoryStream.Create;
for i := 0 to iMetaCount - 1 do begin
aMetaBlockOther[ i ].MetaDataBlockHeader[ 1 ] := ( aMetaBlockOther[ i ].MetaDataBlockHeader[ 1 ] and $7f ); // not last
if aMetaBlockOther[ i ].MetaDataBlockHeader[ 1 ] = META_PADDING then begin
iExtraPadding := iExtraPadding + aMetaBlockOther[ i ].Data.Size + 4; // add padding size plus 4 bytes of header block
end else begin
aMetaBlockOther[ i ].Data.Position := 0;
MetaBlocks.Write( aMetaBlockOther[ i ].MetaDataBlockHeader[ 1 ], 4 );
MetaBlocks.CopyFrom( aMetaBlockOther[ i ].Data, 0 );
end;
end;
MetaBlocks.Position := 0;
bRearange := true;
end;
// set up file
if (FPadding <= VorbisBlock.Size - FTagSize ) then begin // no room rebuild the file from scratch
bRebuild := true;
BufferName := sFile + '~';
Source := TFileStream.Create( sFile, fmOpenRead ); // Set read-only and open old file, and create new
Destination := TFileStream.Create( BufferName, fmCreate );
Source.Read( oldHeader, sizeof( oldHeader ) );
oldHeader.MetaDataBlockHeader[ 1 ] := (oldHeader.MetaDataBlockHeader[ 1 ] and $7f ); //just in case no metadata existed
Destination.Write( oldHeader, Sizeof( oldHeader ) );
Destination.CopyFrom( MetaBlocks, 0 );
end else begin
bRebuild := false;
Source := nil;
Destination := TFileStream.Create( sFile, fmOpenWrite); // Set write-access and open file
if bRearange then begin
Destination.Seek( SizeOf( FHeader ), soFromBeginning );
Destination.CopyFrom( MetaBlocks, 0 );
end else begin
Destination.Seek( FVCOffset - 4, soFromBeginning );
end;
end;
// finally write vorbis block
MetaDataBlockHeader[1] := META_VORBIS_COMMENT;
MetaDataBlockHeader[2] := Byte(( VorbisBlock.Size shr 16 ) and 255 );
MetaDataBlockHeader[3] := Byte(( VorbisBlock.Size shr 8 ) and 255 );
MetaDataBlockHeader[4] := Byte( VorbisBlock.Size and 255 );
Destination.Write( MetaDataBlockHeader[ 1 ], SizeOf( MetaDataBlockHeader ) );
Destination.CopyFrom( VorbisBlock, VorbisBlock.Size );
// and add padding
if FPaddingLast or bRearange then begin
MetaDataBlockHeader[1] := META_PADDING or $80;
end else begin
MetaDataBlockHeader[1] := META_PADDING;
end;
if bRebuild then begin
iNewPadding := 4096; // why not...
end else begin
if FTagSize > VorbisBlock.Size then begin // tag got smaller increase padding
iNewPadding := (FPadding + FTagSize - VorbisBlock.Size) + iExtraPadding;
end else begin // tag got bigger shrink padding
iNewPadding := (FPadding - VorbisBlock.Size + FTagSize ) + iExtraPadding;
end;
end;
MetaDataBlockHeader[2] := Byte(( iNewPadding shr 16 ) and 255 );
MetaDataBlockHeader[3] := Byte(( iNewPadding shr 8 ) and 255 );
MetaDataBlockHeader[4] := Byte( iNewPadding and 255 );
Destination.Write(MetaDataBlockHeader[ 1 ], 4);
if (FPadding <> iNewPadding) or bRearange then begin // fill the block with zeros
sTmp := DupeString( #0, iNewPadding );
Destination.Write( sTmp[1], iNewPadding );
end;
// finish
if bRebuild then begin // time to put back the audio data...
Source.Seek( FAudioOffset, soFromBeginning );
Destination.CopyFrom( Source, Source.Size - FAudioOffset );
Source.Free;
Destination.Free;
if (DeleteFile( sFile ) ) and (RenameFile( BufferName, sFile ) ) then begin //Replace old file and delete temporary file
result := true
end else begin
raise Exception.Create('');
end;
end else begin
result := true;
Destination.Free;
end;
// post save tasks
if bTAG_PreserveDate then FileSetDate( sFile, iFileAge );
if bRearange then FreeAndNil( MetaBlocks );
except
// Access error
if FileExists( BufferName ) then DeleteFile( BufferName );
end;
end;
end.
|
{ Convert Leap Websocket data (JSON) to Leap Data Structures
Copyright (C) 2013 Michael Van Canneyt (michael@freepascal.org);
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit dleapjson;
interface
uses
Classes, SysUtils, leapdata, superobject;
Type
{ TJSONFrameConverter }
TJSONFrameConverter = Class(TComponent)
private
FNilOnError: Boolean;
function AddGestures(AFrame: TFrame; const JSON: TSuperArray): Integer;
procedure JSONToCircleGesture(G: TCircleGesture; const JSON: ISuperObject);
procedure JSONToGesture(G: TGesture; const JSON: ISuperObject);
procedure JSONToSwipeGesture(G: TSwipeGesture; const JSON: ISuperObject);
procedure JSONToTapGesture(G: TTapGesture; const JSON: ISuperObject);
function NewGesture(AFrame: TFrame; AID: TLeapID; AType: String): TGesture;
Protected
procedure DoError(Msg: String);
function NewPointable(AFrame: TFrame; AID: TLeapID; ATool: Boolean): TPointable;virtual;
Function NewFrame(AID : TLeapID) : TFrame; virtual;
function NewHand(AFrame: TFrame; AID: TLeapID): THand; virtual;
procedure JSONToHand(H: THand; const JSON: ISuperObject); virtual;
procedure JSONToPointable(P: TPointable; const JSON: ISuperObject); virtual;
function ArrayTo3DVector(A: TSuperArray): T3DVector;
function GetVector(const JSON: ISuperObject; AName: String; const AError: String=''): T3DVector;
function GetMatrix(const JSON: TSuperArray; const AError: String): T3DMatrix;
function AddInteractionBox(AFrame: TFrame; const JSON: ISuperObject): TInteractionBox;
function AddPointables(AFrame: TFrame; const JSON: TSuperArray): Integer;
function AddHands(AFrame: TFrame; const JSON: TSuperArray): Integer;
Public
Function FrameFromStream(Const S : TStream) : TFrame;
Function FrameFromString(Const S : String) : TFrame;
Function FrameFromJSON(Const JSON : ISuperObject) : TFrame;
Property NilOnError : Boolean Read FNilOnError Write FNilOnError;
end;
Function ExtractVersion(S : TStream) : Integer;
Function WriteEnableGestures(Enable : Boolean) : String;
implementation
Function WriteEnableGestures(Enable : Boolean) : String;
Var
O : ISuperObject;
S : String;
begin
O:=SO('{}');
(*
if Enable then
O:=SO('{"enableGestures" : true}')
else
O:=SO('{"enableGestures" : true}');
*)
O.B['enableGestures']:=Enable;
S:=O.AsJSon();
Result:=S;
end;
Function ExtractVersion(S : TStream) : Integer;
Var
D : ISuperObject;
SA : AnsiString;
begin
SetLength(SA,S.Size);
S.Read(SA[1],S.Size);
D:=SO(SA);
Result:=SO.I['Version'];
end;
function TJSONFrameConverter.FrameFromStream(Const S: TStream): TFrame;
Var
O : ISuperObject;
E : AnsiString;
F : TFileStream;
begin
SetLength(E,S.Size);
F:=TFileStream.Create('c:\temp\frame.json',fmcreate);
try
F.CopyFrom(S,0);
finally
F.Free
end;
S.Position:=0;
S.Read(PAnsiChar(E)^,Length(E));
O:=SO(E);
Result:=FrameFromJSON(O)
end;
function TJSONFrameConverter.FrameFromString(Const S: String): TFrame;
Var
SS : TStringStream;
begin
SS:=TStringStream.Create(S);
try
Result:=FrameFromStream(SS);
finally
SS.Free;
end;
end;
Procedure TJSONFrameConverter.DoError(Msg : String);
begin
Raise EConvertError.Create(Msg);
end;
function TJSONFrameConverter.ArrayTo3DVector(A : TSuperArray) : T3DVector;
Var
I : Integer;
begin
If (A.Length<>3) then
DoError('Array is not a vector: wrong length');
For I:=0 to 2 do
If Not (A[I].DataType in [stDouble,stCurrency,stInt]) then
DoError('Array is not a vector: element '+IntToStr(i)+' not a number');
Result.X:=A[0].AsDouble;
Result.Y:=A[1].AsDouble;
Result.Z:=A[2].AsDouble;
end;
function TJSONFrameConverter.AddInteractionBox(AFrame : TFrame;Const JSON: ISuperObject): TInteractionBox;
Var
A1,A2 : TSuperArray;
begin
if (JSON=Nil) then
DoError('Missing interactionBox');
A1:=JSON.A['center'];
A2:=JSON.A['size'];
If (A1=Nil) then
DoError('Missing interactionBox.center');
If (A2=Nil) then
DoError('Missing interactionBox.size');
Result:=TInteractionBox.Create(ArrayTo3DVector(A1),ArrayTo3DVector(A2));
AFrame.InteractionBox:=Result;
end;
function TJSONFrameConverter.GetVector(Const JSON: ISuperObject; AName : String; Const AError : String = '') : T3DVector;
Var
A : TSuperArray;
begin
A:=JSON.A[AName];
If A=Nil then
DoError(AError+': missing '+AName);
Result:=ArrayTo3DVector(A);
end;
Function TJSONFrameConverter.GetMatrix(Const JSON: TSuperArray; Const AError : String) : T3DMatrix;
Var
I,J : Integer;
A : TSuperArray;
S : String;
begin
If JSON.Length<>3 then
DoError(AError+' array element count is not 3');
For I:=0 to 2 do
if (Not JSON[i].IsType(starray)) then
DoError(AError+' array element '+IntToStr(i)+' is not an array')
else
begin
A:=JSON.O[i].AsArray;
S:=AError+' array '+IntToStr(i)+' : ';
If A.Length<>3 then
DoError(S+' element count is not 3');
For J:=0 to 2 do
if (Not (A[j].DataType in [stDouble,stCurrency,stInt])) then
DoError(S+' array element '+IntToStr(j)+' is not a number')
else
begin
Result[i+1][j+1]:=A.D[J];
end;
end;
end;
Procedure TJSONFrameConverter.JSONToHand(H : THand; Const JSON: ISuperObject);
Function Vec(El : String) : T3DVector;
begin
Result:=GetVector(JSON,El,'Hand '+IntToStr(H.ID));
end;
begin
H.Direction:=vec('direction');
H.PalmNormal:=vec('palmNormal');
H.palmPosition:=vec('palmPosition');
H.palmVelocity:=vec('palmVelocity');
H.Scalefactor:=JSON.D['s'];
H.Translation:=vec('t');
H.SphereCenter:=vec('sphereCenter');
H.SphereRadius:=JSON.D['sphereRadius'];
H.RotationMatrix:=GetMatrix(JSON.A['r'],'Hand '+IntToStr(H.ID));
end;
procedure TJSONFrameConverter.JSONToPointable(P: TPointable; const JSON: ISuperObject);
Function Vec(El : String) : T3DVector;
begin
Result:=GetVector(JSON,El,'Pointable '+IntToStr(P.ID));
end;
Var
A : ISuperObject;
begin
P.Direction:=vec('direction');
P.HandID:=JSON.I['handId'];
P.Length:=JSON.D['length'];
P.StabilizedTipPosition:=vec('stabilizedTipPosition');
P.TipPosition:=vec('tipPosition');
P.TipVelocity:=vec('tipVelocity');
P.TouchDist:=JSON.D['touchDist'];
P.TouchZone:=JSON.S['touchZone'];
if (P is TTool) then
TTool(P).Width:=JSON.D['width'];
end;
function TJSONFrameConverter.NewHand(AFrame : TFrame; AID : TLeapID): THand;
begin
Result:=THand.Create(AFrame,AID);
end;
function TJSONFrameConverter.AddHands(AFrame : TFrame; Const JSON: TSuperArray): Integer;
Var
I : Integer;
O : ISuperObject;
begin
For I:=0 to JSON.Length-1 do
if Not JSON[i].IsType(stObject) then
DoError('Hand '+IntToStr(i)+' is not a JSON Object');
For I:=0 to JSON.Length-1 do
begin
O:=JSON.O[I];
JSONToHand(NewHand(AFrame,O.I['id']),O);
end;
Result:=JSON.Length-1
end;
function TJSONFrameConverter.NewPointable(AFrame : TFrame; AID : TLeapID; ATool : Boolean): TPointable;
begin
if ATool then
Result:=TTool.Create(AFrame,AID)
else
Result:=TFinger.Create(AFrame,AID);
end;
function TJSONFrameConverter.AddPointables(AFrame : TFrame; Const JSON: TSuperArray): Integer;
Var
I : Integer;
O : ISuperObject;
begin
For I:=0 to JSON.Length-1 do
if Not JSON[i].IsType(stObject) then
DoError('Pointable '+IntToStr(i)+' is not a JSON Object');
For I:=0 to JSON.Length-1 do
begin
O:=JSON.O[I];
JSONToPointable(NewPointable(AFrame,O.I['id'],O.B['tool']),O);
end;
Result:=JSON.Length-1;
end;
function TJSONFrameConverter.NewGesture(AFrame : TFrame; AID : TLeapID; AType : String): TGesture;
Var
GC : TGestureClass;
begin
GC:=TGesture;
if (AType='circle') then
GC:=TCircleGesture
else if (AType='swipe') then
GC:=TSwipeGesture
else if (AType='screenTap') then
GC:=TScreenTapGesture
else if (AType='keyTap') then
GC:=TKeyTapGesture;
Result:=GC.Create(AFrame,AID);
end;
procedure TJSONFrameConverter.JSONToSwipeGesture(G: TSwipeGesture; const JSON: ISuperObject);
begin
G.Position:=GetVector(JSON,'position','swipe position');
G.Direction:=GetVector(JSON,'direction','swipe position');
G.StartPosition:=GetVector(JSON,'startPosition','swipe startposition');
G.Speed:=JSON.D['speed'];
end;
procedure TJSONFrameConverter.JSONToCircleGesture(G: TCircleGesture; const JSON: ISuperObject);
begin
G.Center:=GetVector(JSON,'center','circle center');
G.Normal:=GetVector(JSON,'normal','circle normal');
G.Progress:=JSON.D['progress'];
G.Radius:=JSON.D['radius'];
end;
procedure TJSONFrameConverter.JSONToTapGesture(G: TTapGesture; const JSON: ISuperObject);
begin
G.Direction:=GetVector(JSON,'direction','tap direction');
G.Position:=GetVector(JSON,'position','tap position');
G.Progress:=JSON.D['progress'];
end;
Var
GC : Integer;
procedure TJSONFrameConverter.JSONToGesture(G: TGesture; const JSON: ISuperObject);
Type
TINarr = Array of INteger;
Function GetA(N : String): TINarr;
Var
A : TSuperArray;
I : Integer;
begin
A:=JSON.A[N];
SetLength(Result,A.Length);
For I:=0 to A.Length-1 do
Result[i]:=A.I[i];
end;
Var
T : TStringList;
S : String;
begin
if JSON=Nil then
Exit;
G.Duration:=JSON.I['duration'];
S:=JSON.S['state'];
if (s='update') then
G.State:=gsUpdate
else if (s='start') then
G.State:=gsStart
else if (s='stop') then
G.State:=gsStop;
G.SetHandIDs(GetA('handIds'));
G.SetPointableIDs(GetA('pointableIds'));
case G.GestureType of
gtSwipe : JSONToSwipeGesture(G as TSwipeGesture,JSON);
gtCircle : JSONToCircleGesture(G as TCircleGesture,JSON);
gtScreenTap,
gtKeytap : JSONToTapGesture(G as TTapGesture,JSON);
end;
end;
function TJSONFrameConverter.AddGestures(AFrame : TFrame; Const JSON: TSuperArray): Integer;
Var
I : Integer;
O : ISuperObject;
begin
if JSON=Nil then
exit;
For I:=0 to JSON.Length-1 do
if Not JSON[i].IsType(stObject) then
DoError('Gesture '+IntToStr(i)+' is not a JSON Object');
For I:=0 to JSON.Length-1 do
begin
O:=JSON.O[I];
JSONToGesture(NewGesture(AFrame,O.I['id'],O.S['type']),O);
end;
Result:=JSON.Length-1
end;
function TJSONFrameConverter.FrameFromJSON(Const JSON: ISuperObject): TFrame;
Var
O : ISuperObject;
begin
Result:=Nil;
if JSON.S['Version']='' then
begin
Result:=NewFrame(JSON.I['id']);
try
AddInteractionBox(Result,JSON.O['interactionBox']);
AddHands(Result,JSON.A['hands']);
AddPointables(Result,JSON.A['pointables']);
AddGestures(Result,JSON.A['gestures']);
Result.Scalefactor:=JSON.D['s'];
Result.Translation:=GetVector(JSON,'t','Translation vector');
Result.RotationMatrix:=GetMatrix(JSON.A['r'],'Rotation matrix');
Result.TimeStamp:=JSON.I['timestamp'];
except
If NilOnError then
FreeAndNil(Result)
else
Raise;
end;
end
else if not NilOnError then
DoError('Not a frame');
end;
{ TJSONFrameConverter }
function TJSONFrameConverter.NewFrame(AID: TLeapID): TFrame;
begin
Result:=TFrame.Create(AID);
end;
end.
|
// defines a stack and a stackstack for the code formatter based on a pseudo template
// Original Author: Egbert van Nes (http://www.dow.wau.nl/aew/People/Egbert_van_Nes.html)
// Contributors: Thomas Mueller (http://www.dummzeuch.de)
unit GX_CodeFormatterStack;
interface
uses
GX_CodeFormatterTypes;
type
PStackRec = ^TStackRec;
TStackRec = record
RT: TReservedType;
nInd: Integer;
end;
const
MaxStack = 150;
type
TStackArray = array[0..MaxStack] of TStackRec;
type
TCodeFormatterStack = class
private
FStack: TStackArray;
FStackPtr: Integer;
FNIndent: Integer;
FProcLevel: Integer;
function TopRec: PStackRec;
public
constructor Create;
destructor Destroy; override;
{: returns the topmost item from the stack without removing it }
function GetTopType: TReservedType;
function GetTopIndent: Integer;
{: Check whether AType is somewhere on the stack }
function HasType(AType: TReservedType): Boolean;
function Pop: TReservedType;
procedure Push(RType: TReservedType; IncIndent: Integer);
{: returns True if the stack is empty }
function IsEmpty: Boolean;
{: clears the stack and returns the number of items that were left }
function Clear: Integer;
function Depth: Integer;
function Clone: TCodeFormatterStack;
property NIndent: Integer read FNIndent write FNIndent;
property ProcLevel: Integer read FProcLevel write FProcLevel;
end;
{$DEFINE STACK_TEMPLATE}
type
_STACK_ITEM_ = TCodeFormatterStack;
const
_MAX_DEPTH_ = 150;
{$INCLUDE DelforStackTemplate.tpl}
type
TCodeFormatterStackStack = class(_STACK_)
end;
implementation
{ TDelForStack }
constructor TCodeFormatterStack.Create;
begin
inherited Create;
FStackPtr := -1;
FNIndent := 0;
FProcLevel := 0;
end;
destructor TCodeFormatterStack.Destroy;
begin
inherited;
end;
function TCodeFormatterStack.GetTopType: TReservedType;
begin
if FStackPtr >= 0 then
Result := TopRec.RT
else
Result := rtNothing;
end;
procedure TCodeFormatterStack.Push(RType: TReservedType; IncIndent: Integer);
begin
Inc(FStackPtr);
if FStackPtr > MaxStack then
raise EFormatException.Create('Stack overflow');
TopRec.RT := RType;
TopRec.nInd := FNIndent;
FNIndent := FNIndent + IncIndent;
end;
function TCodeFormatterStack.HasType(AType: TReservedType): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 to FStackPtr do
if FStack[I].RT = AType then
begin
Result := True;
Exit;
end;
end;
function TCodeFormatterStack.Pop: TReservedType;
begin
if FStackPtr >= 0 then
begin
FNIndent := TopRec.nInd;
if (TopRec.RT = rtProcedure) and (FProcLevel > 0) then
Dec(FProcLevel);
Result := TopRec^.RT;
Dec(FStackPtr);
end
else
begin
FNIndent := 0;
FProcLevel := 0;
Result := rtNothing;
end;
end;
function TCodeFormatterStack.TopRec: PStackRec;
begin
Result := @FStack[FStackPtr];
end;
function TCodeFormatterStack.GetTopIndent: Integer;
begin
if not IsEmpty then
begin
Result := TopRec.nInd;
NIndent := Result;
end
else
Result := NIndent;
end;
function TCodeFormatterStack.IsEmpty: Boolean;
begin
Result := FStackPtr < 0;
end;
function TCodeFormatterStack.Clear: Integer;
begin
Result := Depth;
FStackPtr := -1;
FNIndent := 0;
{ TODO -otwm -ccheck : Is this correct? }
FProcLevel := 0;
end;
function TCodeFormatterStack.Depth: Integer;
begin
Result := FStackPtr + 1;
end;
function TCodeFormatterStack.Clone: TCodeFormatterStack;
begin
Result := TCodeFormatterStack.Create;
Result.FStack := FStack;
Result.FStackPtr := FStackPtr;
Result.FNIndent := FNIndent;
Result.FProcLevel := FProcLevel;
end;
{ TDelForStackStack }
{$INCLUDE DelforStackTemplate.tpl}
end.
|
PROGRAM Practice(INPUT, OUTPUT);
{
Процедуры с лекции про INTEGER
}
PROCEDURE Sum(VAR I,N,S: INTEGER);
BEGIN {Sum}
READ(N);
S := 0;
I := 1;
WHILE I <= N
DO
BEGIN
S := S + 1;
I := I + 1
END;
WRITELN('Сумма первых', N:2, ':', S:3)
END; {Sum}
PROCEDURE StringToInteger(VAR F: TEXT; VAR Base, Result: INTEGER);
{Base - система счисления на входе}
PROCEDURE CharToDigit(VAR Ch: CHAR; VAR Result: INTEGER);
BEGIN {CharToDigit}
IF Ch = '0' THEN Result := 0 ELSE
IF Ch = '1' THEN Result := 1 ELSE
IF Ch = '2' THEN Result := 2 ELSE
IF Ch = '3' THEN Result := 3 ELSE
IF Ch = '4' THEN Result := 4 ELSE
IF Ch = '5' THEN Result := 5 ELSE
IF Ch = '6' THEN Result := 6 ELSE
IF Ch = '7' THEN Result := 7 ELSE
IF Ch = '8' THEN Result := 8 ELSE
IF Ch = '9' THEN Result := 9 ELSE
IF Ch = 'A' THEN Result := 10 ELSE
IF Ch = 'B' THEN Result := 11 ELSE
IF Ch = 'C' THEN Result := 12 ELSE
IF Ch = 'D' THEN Result := 13 ELSE
IF Ch = 'E' THEN Result := 14 ELSE
IF Ch = 'F' THEN Result := 15
ELSE Result := -1
END; {CharToDigit}
VAR
Ch: CHAR;
Digit: INTEGER;
BEGIN {StringToInteger}
Result := 0;
IF NOT EOLN
THEN
READ(F, Ch);
WHILE (Ch <> '#') AND (Ch <> ' ')
DO
BEGIN
CharToDigit(Ch, Digit);
Result := (Result * Base) + Digit;
READ(F, Ch)
END;
WRITELN('И число... ', Result)
END; {StringToInteger}
PROCEDURE Copy(VAR F1, F2: TEXT);
VAR
Ch: CHAR;
BEGIN {Copy}
REWRITE(F2);
WHILE NOT EOLN(F1)
DO
BEGIN
READ(F1, Ch);
WRITE(F2, Ch)
END;
WRITELN(F2)
END; {Copy}
VAR
Number, Base: INTEGER;
F: TEXT;
BEGIN {Practice}
WRITELN('Программа переводит числа из указанной системы счисления в десятичную');
WRITE('Enter a number: ');
Base := 2;
StringToInteger(INPUT, Base, Number)
END. {Practice}
|
unit seModalSupport;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\seModalSupport.pas"
// Стереотип: "UtilityPack"
// Элемент модели: "seModalSupport" MUID: (4FC7541C02BA)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwScriptingInterfaces
, l3ModalService
, l3ProtoObject
;
type
TseModalService = {final} class(Tl3ProtoObject, Il3ModalService)
public
function HasModalWorker: Boolean;
function ExecuteCurrentModalWorker(aModalExecute: TseModalExecute = se_meUsual): Boolean;
class function Instance: TseModalService;
{* Метод получения экземпляра синглетона TseModalService }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
end;//TseModalService
function seAddModalWorker(aWorker: TtfwWord;
const aCtx: TtfwContext): Integer;
function seIsValidModalWorkersCount(aCount: Integer): Boolean;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, seModalWorkerList
, seModalWorker
, l3AFWExceptions
, l3BatchService
, l3MessagesService
, SysUtils
, l3Base
//#UC START# *4FC7541C02BAimpl_uses*
//#UC END# *4FC7541C02BAimpl_uses*
;
var g_TseModalService: TseModalService = nil;
{* Экземпляр синглетона TseModalService }
procedure TseModalServiceFree;
{* Метод освобождения экземпляра синглетона TseModalService }
begin
l3Free(g_TseModalService);
end;//TseModalServiceFree
function seExecuteCurrentModalWorker(aModalExecute: TseModalExecute): Boolean;
//#UC START# *4FC754C20096_4FC7541C02BA_var*
var
l_W : TseModalWorker;
//#UC END# *4FC754C20096_4FC7541C02BA_var*
begin
//#UC START# *4FC754C20096_4FC7541C02BA_impl*
Result := false;
if not Tl3BatchService.Instance.IsBatchMode then
Exit;
if TseModalWorkerList.Instance.Empty then
Exit;
Tl3MessagesService.Instance.ProcessMessages;
l_W := TseModalWorkerList.Instance.Last;
if (aModalExecute <> se_meInLoop) then
TseModalWorkerList.Instance.Delete(Pred(TseModalWorkerList.Instance.Count));
if (aModalExecute > se_meUsual) then
l_W.rContext^.rEngine.PushBool(aModalExecute = se_meAfterLoop);
l_W.rWord.DoIt(l_W.rContext^);
Tl3MessagesService.Instance.ProcessMessages;
Result := true;
//#UC END# *4FC754C20096_4FC7541C02BA_impl*
end;//seExecuteCurrentModalWorker
function seHasModalWorker: Boolean;
//#UC START# *4FC7749201E0_4FC7541C02BA_var*
//#UC END# *4FC7749201E0_4FC7541C02BA_var*
begin
//#UC START# *4FC7749201E0_4FC7541C02BA_impl*
Result := not TseModalWorkerList.Instance.Empty;
//#UC END# *4FC7749201E0_4FC7541C02BA_impl*
end;//seHasModalWorker
function seAddModalWorker(aWorker: TtfwWord;
const aCtx: TtfwContext): Integer;
//#UC START# *4FC7549A03B6_4FC7541C02BA_var*
//#UC END# *4FC7549A03B6_4FC7541C02BA_var*
begin
//#UC START# *4FC7549A03B6_4FC7541C02BA_impl*
TseModalWorkerList.Instance.Add(TseModalWorker_C(aWorker, aCtx));
Result := TseModalWorkerList.Instance.Count;
//#UC END# *4FC7549A03B6_4FC7541C02BA_impl*
end;//seAddModalWorker
function seIsValidModalWorkersCount(aCount: Integer): Boolean;
//#UC START# *5193915002D8_4FC7541C02BA_var*
//#UC END# *5193915002D8_4FC7541C02BA_var*
begin
//#UC START# *5193915002D8_4FC7541C02BA_impl*
Result := (TseModalWorkerList.Instance.Count < aCount);
// - проверяем, что предыдущий модальный код выполнися
if not Result then
TseModalWorkerList.Instance.Delete(Pred(TseModalWorkerList.Instance.Count));
// - снимаем этот код со стека, если он не выполнился
//#UC END# *5193915002D8_4FC7541C02BA_impl*
end;//seIsValidModalWorkersCount
function TseModalService.HasModalWorker: Boolean;
//#UC START# *553F7345032E_553F737A02D6_var*
//#UC END# *553F7345032E_553F737A02D6_var*
begin
//#UC START# *553F7345032E_553F737A02D6_impl*
Result := SeHasModalWorker;
//#UC END# *553F7345032E_553F737A02D6_impl*
end;//TseModalService.HasModalWorker
function TseModalService.ExecuteCurrentModalWorker(aModalExecute: TseModalExecute = se_meUsual): Boolean;
//#UC START# *553F8EA30300_553F737A02D6_var*
//#UC END# *553F8EA30300_553F737A02D6_var*
begin
//#UC START# *553F8EA30300_553F737A02D6_impl*
Result := SeExecuteCurrentModalWorker(aModalExecute);
//#UC END# *553F8EA30300_553F737A02D6_impl*
end;//TseModalService.ExecuteCurrentModalWorker
class function TseModalService.Instance: TseModalService;
{* Метод получения экземпляра синглетона TseModalService }
begin
if (g_TseModalService = nil) then
begin
l3System.AddExitProc(TseModalServiceFree);
g_TseModalService := Create;
end;
Result := g_TseModalService;
end;//TseModalService.Instance
class function TseModalService.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TseModalService <> nil;
end;//TseModalService.Exists
initialization
Tl3ModalService.Instance.Alien := TseModalService.Instance;
{* Регистрация TseModalService }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
{ rxConfigValues unit
Copyright (C) 2005-2010 Lagunov Aleksey alexs@hotbox.ru
original conception from rx library for Delphi (c)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit rxConfigValues;
{$I rx.inc}
interface
uses
Classes, SysUtils;
const
cvtInteger = 1; // целое
cvtString = 2; // строка
cvtBoolean = 3; // логическая
cvtDateTime = 4; // дата
cvtFloat = 5; // вещественное
type
{ TConfigValue }
TConfigValue = class
private
FModified:boolean;
FName: string;
FDataType:byte;
FValue:Variant;
function GetAsBoolean: boolean;
function GetAsDateTime: TDateTime;
function GetAsFloat: Double;
function GetAsInteger: integer;
function GetAsString: string;
procedure SetAsBoolean(const AValue: boolean);
procedure SetAsDateTime(const AValue: TDateTime);
procedure SetAsFloat(const AValue: Double);
procedure SetAsInteger(const AValue: integer);
procedure SetAsString(const AValue: string);
function GetValue: string;
public
constructor Create;
destructor Destroy; override;
property Name:string read FName;
property AsString:string read GetAsString write SetAsString;
property AsInteger:integer read GetAsInteger write SetAsInteger;
property AsFloat:Double read GetAsFloat write SetAsFloat;
property AsBoolean:boolean read GetAsBoolean write SetAsBoolean;
property AsDateTime:TDateTime read GetAsDateTime write SetAsDateTime;
property Modified:boolean read FModified write FModified;
property DataType:byte read FDataType;
property Value:string read GetValue;
end;
{ TConfigValues }
TConfigValues = class
private
FItems:TList;
function CreateValue(AName:string; AType:byte):TConfigValue;
function GetCount: integer;
function GetItem(Index:Integer): TConfigValue;
public
constructor Create;
destructor Destroy; override;
procedure BeginUpdate;
procedure EndUpdate;
procedure Clear;
function ParamByName(AName:string):TConfigValue;
function ByNameAsInteger(AName:string; DefValue:integer):integer;
function ByNameAsString(AName:string; DefValue:string):string;
function ByNameAsFloat(AName:string; DefValue:Double):Double;
function ByNameAsBoolean(AName:string; DefValue:Boolean):Boolean;
function ByNameAsDateTime(AName:string; DefValue:TDateTime):TDateTime;
procedure SetByNameAsInteger(AName:string; AValue:integer);
procedure SetByNameAsString(AName:string; AValue:string);
procedure SetByNameAsFloat(AName:string; ADefValue:Double);
procedure SetByNameAsBoolean(AName:string; ADefValue:Boolean);
procedure SetByNameAsDateTime(AName:string; ADefValue:TDateTime);
public
property Items[Index:Integer]:TConfigValue read GetItem;default;
property Count:integer read GetCount;
end;
implementation
{ TConfigValues }
function TConfigValues.CreateValue(AName: string; AType: byte): TConfigValue;
begin
Result:=TConfigValue.Create;
Result.FDataType:=AType;
Result.FName:=AName;
FItems.Add(Result);
end;
function TConfigValues.GetCount: integer;
begin
Result:=FItems.Count;
end;
function TConfigValues.GetItem(Index:Integer): TConfigValue;
begin
Result:=TConfigValue(FItems[Index]);
end;
constructor TConfigValues.Create;
begin
inherited Create;
FItems:=TList.Create;
end;
destructor TConfigValues.Destroy;
begin
Clear;
FreeAndNil(FItems);
inherited Destroy;
end;
procedure TConfigValues.BeginUpdate;
begin
end;
procedure TConfigValues.EndUpdate;
var
i:integer;
begin
for i:=0 to FItems.Count - 1 do
TConfigValue(FItems[i]).FModified:=false;
end;
procedure TConfigValues.Clear;
var
i:integer;
begin
for i:=0 to FItems.Count - 1 do
TConfigValue(FItems[i]).Free;
FItems.Clear;
end;
function TConfigValues.ParamByName(AName: string): TConfigValue;
var
i:integer;
begin
AName:=AnsiUpperCase(AName);
Result:=nil;
for i:=0 to FItems.Count - 1 do
begin
if AnsiUpperCase(TConfigValue(FItems[i]).FName) = AName then
begin
Result:=TConfigValue(FItems[i]);
exit;
end;
end;
end;
function TConfigValues.ByNameAsInteger(AName: string; DefValue: integer
): integer;
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if Assigned(P) then
Result:=P.AsInteger
else
Result:=DefValue;
end;
function TConfigValues.ByNameAsString(AName: string; DefValue: string): string;
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if Assigned(P) then
Result:=P.AsString
else
Result:=DefValue;
end;
function TConfigValues.ByNameAsFloat(AName: string; DefValue: Double): Double;
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if Assigned(P) then
Result:=P.AsFloat
else
Result:=DefValue;
end;
function TConfigValues.ByNameAsBoolean(AName: string; DefValue: Boolean
): Boolean;
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if Assigned(P) then
Result:=P.AsBoolean
else
Result:=DefValue;
end;
function TConfigValues.ByNameAsDateTime(AName: string; DefValue: TDateTime
): TDateTime;
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if Assigned(P) then
Result:=P.AsDateTime
else
Result:=DefValue;
end;
procedure TConfigValues.SetByNameAsInteger(AName: string; AValue: integer);
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if not Assigned(P) then
P:=CreateValue(AName, cvtInteger);
P.AsInteger:=AValue;
end;
procedure TConfigValues.SetByNameAsString(AName: string; AValue: string);
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if not Assigned(P) then
P:=CreateValue(AName, cvtString);
P.AsString:=AValue;
end;
procedure TConfigValues.SetByNameAsFloat(AName: string; ADefValue: Double);
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if not Assigned(P) then
P:=CreateValue(AName, cvtFloat);
P.AsFloat:=ADefValue;
end;
procedure TConfigValues.SetByNameAsBoolean(AName: string; ADefValue: Boolean);
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if not Assigned(P) then
P:=CreateValue(AName, cvtBoolean);
P.AsBoolean:=ADefValue;
end;
procedure TConfigValues.SetByNameAsDateTime(AName: string; ADefValue: TDateTime
);
var
P:TConfigValue;
begin
P:=ParamByName(AName);
if not Assigned(P) then
P:=CreateValue(AName, cvtDateTime);
P.AsDateTime:=ADefValue;
end;
{ TConfigValue }
function TConfigValue.GetAsBoolean: boolean;
begin
if FDataType = cvtBoolean then
Result:=FValue
else
raise Exception.CreateFmt('Variable %s is not boolean', [FName]);
end;
function TConfigValue.GetAsDateTime: TDateTime;
begin
if FDataType = cvtDateTime then
Result:=FValue
else
raise Exception.CreateFmt('Variable %s is not date/time', [FName]);
end;
function TConfigValue.GetAsFloat: Double;
begin
if FDataType = cvtFloat then
Result:=FValue
else
raise Exception.CreateFmt('Variable %s is not float', [FName]);
end;
function TConfigValue.GetAsInteger: integer;
begin
if FDataType = cvtInteger then
Result:=FValue
else
raise Exception.CreateFmt('Variable %s is not integer', [FName]);
end;
function TConfigValue.GetAsString: string;
begin
if FDataType = cvtString then
Result:=FValue
else
raise Exception.CreateFmt('Variable %s is not string', [FName]);
end;
procedure TConfigValue.SetAsBoolean(const AValue: boolean);
begin
if FDataType = cvtBoolean then
begin
if FValue<>AValue then
begin
FValue:=AValue;
FModified:=true;
end
end
else
raise Exception.CreateFmt('Variable %s is not boolean', [FName]);
end;
procedure TConfigValue.SetAsDateTime(const AValue: TDateTime);
begin
if FDataType = cvtDateTime then
begin
if FValue<>AValue then
begin
FValue:=AValue;
FModified:=true;
end
end
else
raise Exception.CreateFmt('Variable %s is not date/time', [FName]);
end;
procedure TConfigValue.SetAsFloat(const AValue: Double);
begin
if FDataType = cvtFloat then
begin
if FValue<>AValue then
begin
FValue:=AValue;
FModified:=true;
end
end
else
raise Exception.CreateFmt('Variable %s is not float', [FName]);
end;
procedure TConfigValue.SetAsInteger(const AValue: integer);
begin
if FDataType = cvtInteger then
begin
if (FValue = null) or (FValue<>AValue) then
begin
FValue:=AValue;
FModified:=true;
end
end
else
raise Exception.CreateFmt('Variable %s is not integer', [FName]);
end;
procedure TConfigValue.SetAsString(const AValue: string);
begin
if FDataType = cvtString then
begin
if FValue<>AValue then
begin
FValue:=AValue;
FModified:=true;
end
end
else
raise Exception.CreateFmt('Variable %s is not string', [FName]);
end;
constructor TConfigValue.Create;
begin
inherited Create;
FModified:=false;
FValue:=null;
end;
destructor TConfigValue.Destroy;
begin
inherited Destroy;
end;
function TConfigValue.GetValue: string;
begin
case FDataType of
cvtInteger : Result:=IntToStr(AsInteger);
cvtString : Result:=AsString;
cvtBoolean : Result:=IntToStr(Ord(AsBoolean));
cvtDateTime: Result:=DateTimeToStr(AsDateTime);
cvtFloat : Str(AsFloat, Result);
end;
end;
end.
|
unit ExtIDEM_DEBUG;
{$mode objfpc}{$H+}
interface
uses MenuIntf, Controls, IDEWindowIntf, Dialogs,
SysUtils, Forms, StdCtrls, ActnList, Classes;
type
pMethod=^tMethod;
tExtIDEM_wnd_DEBUG = class(TForm)
a_StayOnTop: TAction;
a_Clear: TAction;
a_Save: TAction;
ActionList1: TActionList;
Button1: TButton;
Button2: TButton;
CheckBox1: TCheckBox;
Memo1: TMemo;
procedure a_ClearExecute(Sender: TObject);
procedure a_StayOnTopExecute(Sender: TObject);
procedure a_StayOnTopUpdate(Sender: TObject);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
public
procedure Message(const TextMSG:string);
procedure Message(const msgTYPE,msgTEXT:string);
end;
procedure RegisterInIdeLAZARUS;
procedure DEBUG_window_SHOW;
procedure DEBUG(const msgTYPE,msgTEXT:string);
procedure DEBUG(const msgTEXT:string);
function addr2str(const p:pointer):string; inline;
function addr2txt(const p:pointer):string; inline;
function mthd2txt(const p:pMethod):string; inline;
{$ifNdef ASSERTIONS}
procedure Assert(const B:boolean; const T:string);
{$endIf}
implementation
{$ifNdef ASSERTIONS}
procedure Assert(const B:boolean; const T:string);
begin
if not B then MessageDlg('ExtIDEM ASSERT',T,mtWarning,[mbOK],0);
end;
{$endIf}
const _c_WndDBG_Caption_='[eventLog] lazExt_ExtIDEM';
//==============================================================================
{%region --- for IDE lazarus -------------------------------------- /fold}
procedure _onClickIdeMenuItem_(Sender: TObject);
begin
DEBUG_window_SHOW;
end;
procedure RegisterInIdeLAZARUS;
begin
RegisterIDEMenuCommand(itmViewIDEInternalsWindows, _c_WndDBG_Caption_,_c_WndDBG_Caption_,nil,@_onClickIdeMenuItem_);
end;
{%endregion}
{%region --- local INSTANCE -------------------------------------- /fold}
var _WndDBG_:TextIDEM_wnd_DEBUG;
procedure DEBUG_window_SHOW;
begin
if not Assigned(_WndDBG_) then _WndDBG_:=TextIDEM_wnd_DEBUG.Create(Application);
IDEWindowCreators.ShowForm(_WndDBG_,true);
end;
procedure DEBUG(const msgTYPE,msgTEXT:string);
begin
if Assigned(_WndDBG_) then _WndDBG_.Message(msgTYPE,msgTEXT);
end;
procedure DEBUG(const msgTEXT:string);
begin
if Assigned(_WndDBG_) then _WndDBG_.Message(msgTEXT);
end;
{%endregion}
{%region --- Pointer to TEXT -------------------------------------- /fold}
function addr2str(const p:pointer):string;
begin
result:=IntToHex({%H-}PtrUint(p),sizeOf(PtrUint)*2);
end;
const _c_addr2txt_SMB_='$';
const _c_addr2txt_DVT_=':';
function addr2txt(const p:pointer):string;
begin
result:=_c_addr2txt_SMB_+addr2str(p);
end;
function mthd2txt(const p:pMethod):string;
begin
result:=_c_addr2txt_SMB_+addr2str(p^.Code)+_c_addr2txt_DVT_+addr2str(p^.Data)
end;
{%endregion}
//==============================================================================
{$R *.lfm}
procedure TextIDEM_wnd_DEBUG.FormClose(Sender:TObject; var CloseAction:TCloseAction);
begin
CloseAction:=caFree;
_WndDBG_:=NIL;
end;
procedure TextIDEM_wnd_DEBUG.FormCreate(Sender: TObject);
begin
Caption :=_c_WndDBG_Caption_;
FormStyle:=fsStayOnTop;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TextIDEM_wnd_DEBUG.a_ClearExecute(Sender: TObject);
begin
memo1.Clear;
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
procedure TextIDEM_wnd_DEBUG.a_StayOnTopExecute(Sender: TObject);
begin
if self.FormStyle=fsStayOnTop then self.FormStyle:=fsNormal
else self.FormStyle:=fsStayOnTop;
end;
procedure TextIDEM_wnd_DEBUG.a_StayOnTopUpdate(Sender: TObject);
begin // ????
tAction(Sender).Checked:=(self.FormStyle=fsStayOnTop);
end;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
const
_c_bOPN_='[';
_c_bCLS_=']';
_c_PRBL_=' '; //< ^-) изменить имя
procedure TextIDEM_wnd_DEBUG.Message(const TextMSG:string);
var tmp:string;
begin
DateTimeToString(tmp,'hh:mm:ss`zzz',now);
with memo1 do begin
Lines.Insert(0,tmp+_c_PRBL_+TextMSG);
SelLength:=0;
SelStart :=0;
end;
end;
procedure TextIDEM_wnd_DEBUG.Message(const msgTYPE,msgTEXT:string);
begin
if msgTYPE<>''
then Message(_c_bOPN_+msgTYPE+_c_bCLS_+_c_PRBL_+msgTEXT)
else Message( msgTEXT);
end;
initialization
_WndDBG_:=nil;
finalization
_WndDBG_.Free;
end.
|
{**********************************************************************}
{ }
{ "The contents of this file are subject to the Mozilla Public }
{ License Version 1.1 (the "License"); you may not use this }
{ file except in compliance with the License. You may obtain }
{ a copy of the License at http://www.mozilla.org/MPL/ }
{ }
{ 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. }
{ }
{ Copyright Creative IT. }
{ Eric Grange }
{ }
{**********************************************************************}
unit dwsJSCodeGen;
interface
uses Classes, SysUtils, dwsUtils, dwsSymbols, dwsCodeGen, dwsCoreExprs,
dwsExprs, dwsRelExprs, dwsJSON, dwsMagicExprs, dwsStack, Variants, dwsStrings,
dwsJSLibModule, dwsJSMin;
type
TDataSymbolList = class(TObjectList<TDataSymbol>)
public
destructor Destroy; override;
end;
TdwsCodeGenSymbolMapJSObfuscating = class (TdwsCodeGenSymbolMap)
protected
function DoNeedUniqueName(symbol : TSymbol; tryCount : Integer; canObfuscate : Boolean) : String; override;
end;
TSimpleSymbolHash = class (TSimpleObjectHash<TSymbol>)
end;
TSimpleProgramHash = class (TSimpleObjectHash<TdwsProgram>)
end;
TdwsJSCodeGen = class (TdwsCodeGen)
private
FLocalVarScannedProg : TSimpleProgramHash;
FAllLocalVarSymbols : TSimpleSymbolHash;
FDeclaredLocalVars : TDataSymbolList;
FDeclaredLocalVarsStack : TSimpleStack<TDataSymbolList>;
FMainBodyName : String;
FSelfSymbolName : String;
FResultSymbolName : String;
protected
procedure CollectLocalVars(proc : TdwsProgram);
procedure CollectFuncSymLocalVars(funcSym : TFuncSymbol);
procedure CollectLocalVarParams(expr : TExprBase);
procedure CollectInitExprLocalVars(initExpr : TBlockExprBase);
function CreateSymbolMap(parentMap : TdwsCodeGenSymbolMap; symbol : TSymbol) : TdwsCodeGenSymbolMap; override;
procedure EnterContext(proc : TdwsProgram); override;
procedure LeaveContext; override;
function SameDefaultValue(typ1, typ2 : TTypeSymbol) : Boolean;
procedure WriteDefaultValue(typ : TTypeSymbol; box : Boolean);
procedure WriteValue(typ : TTypeSymbol; const data : TData; addr : Integer);
procedure WriteStringArray(destStream : TWriteOnlyBlockStream; strings : TStrings); overload;
procedure WriteStringArray(strings : TStrings); overload;
procedure WriteFuncParams(func : TFuncSymbol);
procedure CompileFuncBody(func : TFuncSymbol);
procedure CompileMethod(meth : TMethodSymbol);
procedure CompileRecordMethod(meth : TMethodSymbol);
procedure CompileHelperMethod(meth : TMethodSymbol);
procedure DoCompileHelperSymbol(helper : THelperSymbol); override;
procedure DoCompileRecordSymbol(rec : TRecordSymbol); override;
procedure DoCompileClassSymbol(cls : TClassSymbol); override;
procedure DoCompileFieldsInit(cls : TClassSymbol);
procedure DoCompileInterfaceTable(cls : TClassSymbol);
procedure DoCompileFuncSymbol(func : TSourceFuncSymbol); override;
property SelfSymbolName : String read FSelfSymbolName write FSelfSymbolName;
property ResultSymbolName : String read FResultSymbolName write FResultSymbolName;
public
constructor Create; override;
destructor Destroy; override;
procedure Clear; override;
function SymbolMappedName(sym : TSymbol; scope : TdwsCodeGenSymbolScope) : String; override;
procedure CompileValue(expr : TTypedExpr); override;
procedure CompileEnumerationSymbol(enum : TEnumerationSymbol); override;
procedure CompileConditions(func : TFuncSymbol; conditions : TSourceConditions;
preConds : Boolean); override;
procedure CompileProgramBody(expr : TNoResultExpr); override;
procedure CompileSymbolTable(table : TSymbolTable); override;
procedure ReserveSymbolNames; override;
procedure CompileDependencies(destStream : TWriteOnlyBlockStream; const prog : IdwsProgram); override;
procedure CompileResourceStrings(destStream : TWriteOnlyBlockStream; const prog : IdwsProgram); override;
function GetNewTempSymbol : String; override;
procedure WriteSymbolVerbosity(sym : TSymbol); override;
procedure WriteJavaScriptString(const s : String);
function MemberName(sym : TSymbol; cls : TCompositeTypeSymbol) : String;
procedure WriteCompiledOutput(dest : TWriteOnlyBlockStream; const prog : IdwsProgram); override;
class var FDebugInfo: string;
// returns all the RTL support JS functions
class function All_RTL_JS : String;
// removes all RTL dependencies (use in combination with All_RTL_JS)
procedure IgnoreRTLDependencies;
const cBoxFieldName = 'v';
const cVirtualPostfix = '$';
property MainBodyName : String read FMainBodyName write FMainBodyName;
end;
TJSExprCodeGen = class (TdwsExprCodeGen)
class function IsLocalVarParam(codeGen : TdwsCodeGen; sym : TDataSymbol) : Boolean; static;
class procedure WriteLocationString(codeGen : TdwsCodeGen; expr : TExprBase);
end;
TJSBlockInitExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSBlockExprBase = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSBlockExpr = class (TJSBlockExprBase)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSRAWBlockExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSNoResultWrapperExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSExitExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSExitValueExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase); virtual;
end;
TJSAssignDataExpr = class (TJSAssignExpr)
procedure CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignClassOfExpr = class (TJSAssignExpr)
procedure CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignFuncExpr = class (TJSAssignExpr)
procedure CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignConstToIntegerVarExpr = class (TJSAssignExpr)
procedure CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignConstToFloatVarExpr = class (TJSAssignExpr)
procedure CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignConstToBoolVarExpr = class (TJSAssignExpr)
procedure CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignConstToStringVarExpr = class (TJSAssignExpr)
procedure CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignNilToVarExpr = class (TJSAssignExpr)
procedure CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssignConstDataToVarExpr = class (TJSAssignExpr)
procedure CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAppendConstStringVarExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConstExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConstStringExpr = class (TJSConstExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConstNumExpr = class (TJSConstExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConstIntExpr = class (TJSConstNumExpr)
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSConstFloatExpr = class (TJSConstNumExpr)
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSConstBooleanExpr = class (TJSConstExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayConstantExpr = class (TJSConstExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSResourceStringExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSVarExpr = class (TJSExprCodeGen)
class function CodeGenSymbol(codeGen : TdwsCodeGen; expr : TExprBase) : TDataSymbol; static;
class function CodeGenName(codeGen : TdwsCodeGen; expr : TExprBase) : TDataSymbol; static;
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSVarParamExpr = class (TJSVarExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSLazyParamExpr = class (TJSVarExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConstParamExpr = class (TJSVarExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSRecordExpr = class (TJSVarExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSFieldExpr = class (TJSVarExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSNewArrayExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayLengthExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArraySetLengthExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayAddExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayPeekExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayPopExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayDeleteExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayIndexOfExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayInsertExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArrayCopyExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSArraySwapExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSStaticArrayExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSStaticArrayBoolExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSDynamicArrayExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSDynamicArraySetExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSStringArrayOpExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSVarStringArraySetExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSInOpExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSBitwiseInOpExpr = class (TJSExprCodeGen)
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSIfThenExpr = class (TJSExprCodeGen)
function SubExprIsSafeStatement(sub : TExprBase) : Boolean;
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSIfThenElseExpr = class (TJSIfThenExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSCaseExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
class procedure CodeGenCondition(codeGen : TdwsCodeGen; cond : TCaseCondition;
const writeOperand : TProc); static;
end;
TJSObjAsClassExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSIsOpExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSObjAsIntfExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSObjToClassTypeExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSIntfAsClassExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSIntfAsIntfExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSTImplementsIntfOpExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSTClassImplementsIntfOpExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSClassAsClassExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConvIntegerExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConvFloatExpr = class (TJSExprCodeGen)
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSOrdExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSIncDecVarFuncExpr = class (TJSExprCodeGen)
procedure DoCodeGen(codeGen : TdwsCodeGen; expr : TMagicFuncExpr;
op : Char; noWrap : Boolean);
end;
TJSIncVarFuncExpr = class (TJSIncDecVarFuncExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSDecVarFuncExpr = class (TJSIncDecVarFuncExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSSarExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSFuncBaseExpr = class (TJSExprCodeGen)
private
FVirtualCall : Boolean;
public
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol); virtual;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); virtual;
end;
TJSRecordMethodExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSHelperMethodExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSMethodStaticExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); override;
end;
TJSMethodVirtualExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); override;
end;
TJSMethodInterfaceExpr = class (TJSFuncBaseExpr)
procedure CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol); override;
end;
TJSClassMethodStaticExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); override;
end;
TJSClassMethodVirtualExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); override;
end;
TJSConstructorStaticExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol); override;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); override;
end;
TJSConstructorVirtualExpr = class (TJSFuncBaseExpr)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase); override;
end;
TJSConnectorCallExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConnectorReadExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSConnectorWriteExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSFuncPtrExpr = class (TJSFuncBaseExpr)
public
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol); override;
end;
TJSFuncRefExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
class procedure DoCodeGen(codeGen : TdwsCodeGen; funcExpr : TFuncExprBase); static;
end;
TJSAnonymousFuncRefExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSExceptExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSAssertExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSDeclaredExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSDefinedExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
end;
TJSForExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure WriteCompare(codeGen : TdwsCodeGen); virtual; abstract;
procedure WriteStep(codeGen : TdwsCodeGen); virtual; abstract;
end;
TJSForUpwardExpr = class (TJSForExpr)
procedure WriteCompare(codeGen : TdwsCodeGen); override;
procedure WriteStep(codeGen : TdwsCodeGen); override;
end;
TJSForDownwardExpr = class (TJSForExpr)
procedure WriteCompare(codeGen : TdwsCodeGen); override;
procedure WriteStep(codeGen : TdwsCodeGen); override;
end;
TJSForUpwardStepExpr = class (TJSForUpwardExpr)
procedure WriteStep(codeGen : TdwsCodeGen); override;
end;
TJSForDownwardStepExpr = class (TJSForDownwardExpr)
procedure WriteStep(codeGen : TdwsCodeGen); override;
end;
TJSSqrExpr = class (TJSExprCodeGen)
procedure CodeGen(codeGen : TdwsCodeGen; expr : TExprBase); override;
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSOpExpr = class (TJSExprCodeGen)
class procedure WriteWrappedIfNeeded(codeGen : TdwsCodeGen; expr : TTypedExpr); static;
end;
TJSBinOpExpr = class (TJSOpExpr)
protected
FOp : String;
FAssociative : Boolean;
procedure WriteOp(codeGen : TdwsCodeGen; rightExpr : TTypedExpr); virtual;
public
constructor Create(const op : String; associative : Boolean);
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
TJSAddOpExpr = class(TJSBinOpExpr)
protected
procedure WriteOp(codeGen : TdwsCodeGen; rightExpr : TTypedExpr); override;
public
constructor Create;
end;
TJSSubOpExpr = class(TJSBinOpExpr)
protected
public
constructor Create;
procedure CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr); override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
uses dwsJSRTL;
const
cBoolToJSBool : array [False..True] of String = ('false', 'true');
cFormatSettings : TFormatSettings = ( DecimalSeparator : '.' );
cInlineStaticArrayLimit = 20;
const
cJSReservedWords : array [1..202] of String = (
// Main JS keywords
// from https://developer.mozilla.org/en/JavaScript/Reference/Reserved_Words
'break', 'case', 'catch', 'continue', 'debugger', 'default', 'delete',
'do', 'else', 'finally', 'for', 'function', 'if', 'in', 'instanceof',
'new', 'return', 'switch', 'this', 'throw', 'try', 'typeof', 'var',
'void', 'while', 'with',
'class', 'enum', 'export', 'extends', 'import', 'super',
'implements', 'interface', 'let', 'package', 'private', 'protected',
'public', 'static', 'yield',
'null', 'true', 'false',
// supplemental reservations for standard JS class names, instances, etc.
// from http://javascript.about.com/library/blclassobj.htm
'Anchor', 'anchors', 'Applet', 'applets', 'Area', 'Array', 'Body', 'Button',
'Checkbox', 'Date', 'Error', 'EvalError', 'FileUpload', 'Form',
'forms', 'frame', 'frames', 'Function', 'Hidden', 'History', 'history',
'Image', 'images', 'Link', 'links', 'location', 'Math', 'MimeType',
'mimetypes', 'navigator', 'Number', 'Object', 'Option', 'options',
'Password', 'Plugin', 'plugins', 'Radio', 'RangeError', 'ReferenceError',
'RegExp', 'Reset', 'screen', 'Script', 'Select', 'String', 'Style',
'StyleSheet', 'Submit', 'SyntaxError', 'Text', 'Textarea', 'TypeError',
'URIError', 'window',
// global properties and method names
// from http://javascript.about.com/library/blglobal.htm
'Infinity', 'NaN', 'undefined',
'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent',
'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt',
'closed', 'Components', 'content', 'controllers', 'crypto', 'defaultstatus',
'directories', 'document', 'innerHeight', 'innerWidth',
'length', 'locationbar', 'menubar', 'name',
'opener', 'outerHeight', 'outerWidth', 'pageXOffset', 'pageYOffset',
'parent', 'personalbar', 'pkcs11', 'prompter', 'screenX',
'screenY', 'scrollbars', 'scrollX', 'scrollY', 'self', 'statusbar',
'toolbar', 'top',
'alert', 'back', 'blur', 'captureevents', 'clearinterval', 'cleartimeout',
'close', 'confirm', 'dump', 'escape', 'focus', 'forward', 'getAttention',
'getSelection', 'home', 'moveBy', 'moveTo', 'open', 'print', 'prompt',
'releaseevents', 'resizeBy', 'resizeTo', 'scroll', 'scrollBy', 'scrollByLines',
'scrollByPages', 'scrollTo', 'setCursor', 'setinterval', 'settimeout',
'sizeToContents', 'stop', 'unescape', 'updateCommands',
'onabort', 'onblur', 'onchange', 'onclick', 'onclose', 'ondragdrop',
'onerror', 'onfocus', 'onkeydown', 'onkeypress', 'onkeyup', 'onload',
'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover',
'onmouseup', 'onpaint', 'onreset', 'onresize', 'onscroll', 'onselect',
'onsubmit', 'onunload'
);
function ShouldBoxParam(param : TParamSymbol) : Boolean;
begin
Result:= (param is TVarParamSymbol)
or ((param is TByRefParamSymbol) and (param.Typ.UnAliasedType is TRecordSymbol));
end;
// ------------------
// ------------------ TdwsJSCodeGen ------------------
// ------------------
// Create
//
constructor TdwsJSCodeGen.Create;
begin
inherited;
FLocalVarScannedProg:=TSimpleProgramHash.Create;
FAllLocalVarSymbols:=TSimpleSymbolHash.Create;
FDeclaredLocalVars:=TDataSymbolList.Create;
FDeclaredLocalVarsStack:=TSimpleStack<TDataSymbolList>.Create;
FMainBodyName:='$dws';
FSelfSymbolName:='Self';
FResultSymbolName:='Result';
RegisterCodeGen(TBlockInitExpr, TJSBlockInitExpr.Create);
RegisterCodeGen(TBlockExpr, TJSBlockExpr.Create);
RegisterCodeGen(TBlockExprNoTable, TJSBlockExprBase.Create);
RegisterCodeGen(TBlockExprNoTable2, TJSBlockExprBase.Create);
RegisterCodeGen(TBlockExprNoTable3, TJSBlockExprBase.Create);
RegisterCodeGen(TBlockExprNoTable4, TJSBlockExprBase.Create);
RegisterCodeGen(TdwsJSBlockExpr, TJSRAWBlockExpr.Create);
RegisterCodeGen(TNullExpr, TdwsExprGenericCodeGen.Create(['/* null */'#13#10]));
RegisterCodeGen(TNoResultWrapperExpr, TJSNoResultWrapperExpr.Create);
RegisterCodeGen(TConstExpr, TJSConstExpr.Create);
RegisterCodeGen(TUnifiedConstExpr, TJSConstExpr.Create);
RegisterCodeGen(TConstIntExpr, TJSConstIntExpr.Create);
RegisterCodeGen(TConstStringExpr, TJSConstStringExpr.Create);
RegisterCodeGen(TConstFloatExpr, TJSConstFloatExpr.Create);
RegisterCodeGen(TConstBooleanExpr, TJSConstBooleanExpr.Create);
RegisterCodeGen(TResourceStringExpr, TJSResourceStringExpr.Create);
RegisterCodeGen(TArrayConstantExpr, TJSArrayConstantExpr.Create);
RegisterCodeGen(TAssignExpr, TJSAssignExpr.Create);
RegisterCodeGen(TAssignClassOfExpr, TJSAssignClassOfExpr.Create);
RegisterCodeGen(TAssignDataExpr, TJSAssignDataExpr.Create);
RegisterCodeGen(TAssignFuncExpr, TJSAssignFuncExpr.Create);
RegisterCodeGen(TAssignConstToIntegerVarExpr, TJSAssignConstToIntegerVarExpr.Create);
RegisterCodeGen(TAssignConstToFloatVarExpr, TJSAssignConstToFloatVarExpr.Create);
RegisterCodeGen(TAssignConstToBoolVarExpr, TJSAssignConstToBoolVarExpr.Create);
RegisterCodeGen(TAssignConstToStringVarExpr, TJSAssignConstToStringVarExpr.Create);
RegisterCodeGen(TAssignNilToVarExpr, TJSAssignNilToVarExpr.Create);
RegisterCodeGen(TAssignNilClassToVarExpr, TJSAssignNilToVarExpr.Create);
RegisterCodeGen(TAssignConstDataToVarExpr, TJSAssignConstDataToVarExpr.Create);
RegisterCodeGen(TAssignArrayConstantExpr, TdwsExprGenericCodeGen.Create([0, '=', -1], gcgStatement));
RegisterCodeGen(TVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TSelfVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TVarParentExpr, TJSVarExpr.Create);
RegisterCodeGen(TVarParamExpr, TJSVarParamExpr.Create);
RegisterCodeGen(TVarParamParentExpr, TJSVarParamExpr.Create);
RegisterCodeGen(TLazyParamExpr, TJSLazyParamExpr.Create);
RegisterCodeGen(TConstParamExpr, TJSConstParamExpr.Create);
RegisterCodeGen(TConstParamParentExpr, TJSConstParamExpr.Create);
RegisterCodeGen(TIntVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TFloatVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TStrVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TBoolVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TObjectVarExpr, TJSVarExpr.Create);
RegisterCodeGen(TRecordExpr, TJSRecordExpr.Create);
RegisterCodeGen(TConvIntegerExpr, TJSConvIntegerExpr.Create);
RegisterCodeGen(TConvFloatExpr, TJSConvFloatExpr.Create);
RegisterCodeGen(TConvBoolExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '?true:false)']));
RegisterCodeGen(TConvStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '.toString()', ')']));
RegisterCodeGen(TConvStaticArrayToDynamicExpr,
TdwsExprGenericCodeGen.Create([0, '.slice()']));
RegisterCodeGen(TConvExternalExpr,
TdwsExprGenericCodeGen.Create([0]));
RegisterCodeGen(TOrdExpr, TJSOrdExpr.Create);
RegisterCodeGen(TClassAsClassExpr, TJSClassAsClassExpr.Create);
RegisterCodeGen(TObjAsClassExpr, TJSObjAsClassExpr.Create);
RegisterCodeGen(TIsOpExpr, TJSIsOpExpr.Create);
RegisterCodeGen(TObjAsIntfExpr, TJSObjAsIntfExpr.Create);
RegisterCodeGen(TObjToClassTypeExpr, TJSObjToClassTypeExpr.Create);
RegisterCodeGen(TIntfAsClassExpr, TJSIntfAsClassExpr.Create);
RegisterCodeGen(TIntfAsIntfExpr, TJSIntfAsIntfExpr.Create);
RegisterCodeGen(TImplementsIntfOpExpr, TJSTImplementsIntfOpExpr.Create);
RegisterCodeGen(TClassImplementsIntfOpExpr, TJSTClassImplementsIntfOpExpr.Create);
RegisterCodeGen(TIntfCmpExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '===', 1, ')']));
RegisterCodeGen(TAddStrExpr, TJSBinOpExpr.Create('+', True));
RegisterCodeGen(TAddIntExpr, TJSAddOpExpr.Create);
RegisterCodeGen(TAddFloatExpr, TJSAddOpExpr.Create);
RegisterCodeGen(TAddVariantExpr, TJSAddOpExpr.Create);
RegisterCodeGen(TSubIntExpr, TJSSubOpExpr.Create);
RegisterCodeGen(TSubFloatExpr, TJSSubOpExpr.Create);
RegisterCodeGen(TSubVariantExpr, TJSSubOpExpr.Create);
RegisterCodeGen(TMultIntExpr, TJSBinOpExpr.Create('*', True));
RegisterCodeGen(TMultFloatExpr, TJSBinOpExpr.Create('*', True));
RegisterCodeGen(TMultVariantExpr, TJSBinOpExpr.Create('*', True));
RegisterCodeGen(TDivideExpr, TJSBinOpExpr.Create('/', True));
RegisterCodeGen(TDivExpr,
TdwsExprGenericCodeGen.Create(['Math.floor(', 0, '/', 1, ')']));
RegisterCodeGen(TModExpr, TJSBinOpExpr.Create('%', True));
RegisterCodeGen(TSqrFloatExpr, TJSSqrExpr.Create);
RegisterCodeGen(TSqrIntExpr, TJSSqrExpr.Create);
RegisterCodeGen(TNegIntExpr, TdwsExprGenericCodeGen.Create(['(', '-', 0, ')']));
RegisterCodeGen(TNegFloatExpr, TdwsExprGenericCodeGen.Create(['(', '-', 0, ')']));
RegisterCodeGen(TNegVariantExpr, TdwsExprGenericCodeGen.Create(['(', '-', 0, ')']));
RegisterCodeGen(TAppendStringVarExpr,
TdwsExprGenericCodeGen.Create([0, '+=', -1], gcgStatement));
RegisterCodeGen(TAppendConstStringVarExpr, TJSAppendConstStringVarExpr.Create);
RegisterCodeGen(TPlusAssignIntExpr,
TdwsExprGenericCodeGen.Create([0, '+=', -1], gcgStatement));
RegisterCodeGen(TPlusAssignFloatExpr,
TdwsExprGenericCodeGen.Create([0, '+=', -1], gcgStatement));
RegisterCodeGen(TPlusAssignStrExpr,
TdwsExprGenericCodeGen.Create([0, '+=', -1], gcgStatement));
RegisterCodeGen(TPlusAssignExpr,
TdwsExprGenericCodeGen.Create([0, '+=', -1], gcgStatement));
RegisterCodeGen(TMinusAssignIntExpr,
TdwsExprGenericCodeGen.Create([0, '-=', -1], gcgStatement));
RegisterCodeGen(TMinusAssignFloatExpr,
TdwsExprGenericCodeGen.Create([0, '-=', -1], gcgStatement));
RegisterCodeGen(TMinusAssignExpr,
TdwsExprGenericCodeGen.Create([0, '-=', -1], gcgStatement));
RegisterCodeGen(TMultAssignIntExpr,
TdwsExprGenericCodeGen.Create([0, '*=', -1], gcgStatement));
RegisterCodeGen(TMultAssignFloatExpr,
TdwsExprGenericCodeGen.Create([0, '*=', -1], gcgStatement));
RegisterCodeGen(TMultAssignExpr,
TdwsExprGenericCodeGen.Create([0, '*=', -1], gcgStatement));
RegisterCodeGen(TDivideAssignExpr,
TdwsExprGenericCodeGen.Create([0, '/=', -1], gcgStatement));
RegisterCodeGen(TIncIntVarExpr,
TdwsExprGenericCodeGen.Create([0, '+=', -1], gcgStatement));
RegisterCodeGen(TDecIntVarExpr,
TdwsExprGenericCodeGen.Create([0, '-=', -1], gcgStatement));
RegisterCodeGen(TIncVarFuncExpr, TJSIncVarFuncExpr.Create);
RegisterCodeGen(TDecVarFuncExpr, TJSDecVarFuncExpr.Create);
RegisterCodeGen(TSuccFuncExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '+', 1, ')']));
RegisterCodeGen(TPredFuncExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '-', 1, ')']));
RegisterCodeGen(TAbsIntExpr,
TdwsExprGenericCodeGen.Create(['Math.abs', '(', 0, ')']));
RegisterCodeGen(TAbsFloatExpr,
TdwsExprGenericCodeGen.Create(['Math.abs', '(', 0, ')']));
RegisterCodeGen(TAbsVariantExpr,
TdwsExprGenericCodeGen.Create(['Math.abs', '(', 0, ')']));
RegisterCodeGen(TSarExpr, TJSSarExpr.Create);
RegisterCodeGen(TShrExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>>>', 1, ')']));
RegisterCodeGen(TShlExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<<', 1, ')']));
RegisterCodeGen(TIntAndExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '&', 1, ')']));
RegisterCodeGen(TIntOrExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '|', 1, ')']));
RegisterCodeGen(TIntXorExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '^', 1, ')']));
RegisterCodeGen(TNotIntExpr,
TdwsExprGenericCodeGen.Create(['(', '~', 0, ')']));
RegisterCodeGen(TBoolAndExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '&&', 1, ')']));
RegisterCodeGen(TBoolOrExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '||', 1, ')']));
RegisterCodeGen(TBoolXorExpr,
TdwsExprGenericCodeGen.Create(['(!', 0, ' != !', 1, ')']));
RegisterCodeGen(TBoolImpliesExpr,
TdwsExprGenericCodeGen.Create(['(!', 0, ' || ', 1, ')']));
RegisterCodeGen(TNotBoolExpr,
TdwsExprGenericCodeGen.Create(['(', '!', 0, ')']));
RegisterCodeGen(TVariantAndExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '&', 1, ')']));
RegisterCodeGen(TVariantOrExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '|', 1, ')']));
RegisterCodeGen(TVariantXorExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '^', 1, ')']));
RegisterCodeGen(TNotVariantExpr,
TdwsExprGenericCodeGen.Create(['(', '!', 0, ')']));
RegisterCodeGen(TAssignedInstanceExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!==null', ')']));
RegisterCodeGen(TAssignedMetaClassExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!==null', ')']));
RegisterCodeGen(TAssignedFuncPtrExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!==null', ')']));
RegisterCodeGen(TRelEqualBoolExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '==', 1, ')']));
RegisterCodeGen(TRelNotEqualBoolExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!=', 1, ')']));
RegisterCodeGen(TObjCmpEqualExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '===', 1, ')']));
RegisterCodeGen(TObjCmpNotEqualExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!==', 1, ')']));
RegisterCodeGen(TRelEqualIntExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '==', 1, ')']));
RegisterCodeGen(TRelNotEqualIntExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!=', 1, ')']));
RegisterCodeGen(TRelGreaterEqualIntExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>=', 1, ')']));
RegisterCodeGen(TRelLessEqualIntExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<=', 1, ')']));
RegisterCodeGen(TRelGreaterIntExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>', 1, ')']));
RegisterCodeGen(TRelLessIntExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<', 1, ')']));
RegisterCodeGen(TRelEqualStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '==', 1, ')']));
RegisterCodeGen(TRelNotEqualStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!=', 1, ')']));
RegisterCodeGen(TRelGreaterEqualStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>=', 1, ')']));
RegisterCodeGen(TRelLessEqualStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<=', 1, ')']));
RegisterCodeGen(TRelGreaterStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>', 1, ')']));
RegisterCodeGen(TRelLessStringExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<', 1, ')']));
RegisterCodeGen(TRelEqualFloatExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '==', 1, ')']));
RegisterCodeGen(TRelNotEqualFloatExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!=', 1, ')']));
RegisterCodeGen(TRelGreaterEqualFloatExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>=', 1, ')']));
RegisterCodeGen(TRelLessEqualFloatExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<=', 1, ')']));
RegisterCodeGen(TRelGreaterFloatExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>', 1, ')']));
RegisterCodeGen(TRelLessFloatExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<', 1, ')']));
RegisterCodeGen(TRelEqualVariantExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '==', 1, ')']));
RegisterCodeGen(TRelNotEqualVariantExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '!=', 1, ')']));
RegisterCodeGen(TRelGreaterEqualVariantExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>=', 1, ')']));
RegisterCodeGen(TRelLessEqualVariantExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<=', 1, ')']));
RegisterCodeGen(TRelGreaterVariantExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '>', 1, ')']));
RegisterCodeGen(TRelLessVariantExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '<', 1, ')']));
RegisterCodeGen(TIfThenExpr, TJSIfThenExpr.Create);
RegisterCodeGen(TIfThenElseExpr, TJSIfThenElseExpr.Create);
RegisterCodeGen(TInOpExpr, TJSInOpExpr.Create);
RegisterCodeGen(TBitwiseInOpExpr, TJSBitwiseInOpExpr.Create);
RegisterCodeGen(TCaseExpr, TJSCaseExpr.Create);
RegisterCodeGen(TForUpwardExpr, TJSForUpwardExpr.Create);
RegisterCodeGen(TForDownwardExpr, TJSForDownwardExpr.Create);
RegisterCodeGen(TForUpwardStepExpr, TJSForUpwardStepExpr.Create);
RegisterCodeGen(TForDownwardStepExpr, TJSForDownwardStepExpr.Create);
RegisterCodeGen(TWhileExpr,
TdwsExprGenericCodeGen.Create(['while ', '(', 0, ')', ' {', #9, 1, #8, '}'], gcgStatement));
RegisterCodeGen(TRepeatExpr,
TdwsExprGenericCodeGen.Create(['do {', #9, 1, #8, '} while (!', 0, ')'], gcgStatement));
RegisterCodeGen(TLoopExpr,
TdwsExprGenericCodeGen.Create(['while (1) {', #9, 1, #8, '}'], gcgStatement));
RegisterCodeGen(TContinueExpr, TdwsExprGenericCodeGen.Create(['continue'], gcgStatement));
RegisterCodeGen(TBreakExpr, TdwsExprGenericCodeGen.Create(['break'], gcgStatement));
RegisterCodeGen(TExitValueExpr, TJSExitValueExpr.Create);
RegisterCodeGen(TExitExpr, TJSExitExpr.Create);
RegisterCodeGen(TRaiseExpr, TdwsExprGenericCodeGen.Create(['throw ', 0], gcgStatement));
RegisterCodeGen(TReRaiseExpr, TdwsExprGenericCodeGen.Create(['throw $e'], gcgStatement));
RegisterCodeGen(TExceptExpr, TJSExceptExpr.Create);
RegisterCodeGen(TFinallyExpr,
TdwsExprGenericCodeGen.Create(['try {', #9, 0, #8, '} finally {', #9, 1, #8, '}'], gcgStatement));
RegisterCodeGen(TNewArrayExpr, TJSNewArrayExpr.Create);
RegisterCodeGen(TArraySetLengthExpr, TJSArraySetLengthExpr.Create);
RegisterCodeGen(TArrayAddExpr, TJSArrayAddExpr.Create);
RegisterCodeGen(TArrayPeekExpr, TJSArrayPeekExpr.Create);
RegisterCodeGen(TArrayPopExpr, TJSArrayPopExpr.Create);
RegisterCodeGen(TArrayDeleteExpr, TJSArrayDeleteExpr.Create);
RegisterCodeGen(TArrayIndexOfExpr, TJSArrayIndexOfExpr.Create);
RegisterCodeGen(TArrayInsertExpr, TJSArrayInsertExpr.Create);
RegisterCodeGen(TArrayCopyExpr, TJSArrayCopyExpr.Create);
RegisterCodeGen(TArraySwapExpr, TJSArraySwapExpr.Create);
RegisterCodeGen(TArrayReverseExpr, TdwsExprGenericCodeGen.Create([0, '.reverse()'], gcgStatement));
RegisterCodeGen(TStaticArrayExpr, TJSStaticArrayExpr.Create);
RegisterCodeGen(TStaticArrayBoolExpr, TJSStaticArrayBoolExpr.Create);
RegisterCodeGen(TDynamicArrayExpr, TJSDynamicArrayExpr.Create);
RegisterCodeGen(TDynamicArraySetExpr, TJSDynamicArraySetExpr.Create);
RegisterCodeGen(TStringArrayOpExpr, TJSStringArrayOpExpr.Create);
RegisterCodeGen(TVarStringArraySetExpr, TJSVarStringArraySetExpr.Create);
RegisterCodeGen(TStringLengthExpr,
TdwsExprGenericCodeGen.Create([0, '.length']));
RegisterCodeGen(TArrayLengthExpr, TJSArrayLengthExpr.Create);
RegisterCodeGen(TOpenArrayLengthExpr,
TdwsExprGenericCodeGen.Create([0, '.length']));
RegisterCodeGen(TOrdIntExpr,
TdwsExprGenericCodeGen.Create([0]));
RegisterCodeGen(TOrdBoolExpr,
TdwsExprGenericCodeGen.Create(['(', 0, '?1:0)']));
RegisterCodeGen(TOrdStrExpr,
TdwsExprGenericCodeGen.Create(['$OrdS', '(', 0, ')'], gcgExpression, '$OrdS'));
RegisterCodeGen(TFuncExpr, TJSFuncBaseExpr.Create);
RegisterCodeGen(TRecordMethodExpr, TJSRecordMethodExpr.Create);
RegisterCodeGen(THelperMethodExpr, TJSHelperMethodExpr.Create);
RegisterCodeGen(TMagicIntFuncExpr, TJSMagicFuncExpr.Create);
RegisterCodeGen(TMagicStringFuncExpr, TJSMagicFuncExpr.Create);
RegisterCodeGen(TMagicFloatFuncExpr, TJSMagicFuncExpr.Create);
RegisterCodeGen(TMagicBoolFuncExpr, TJSMagicFuncExpr.Create);
RegisterCodeGen(TMagicVariantFuncExpr, TJSMagicFuncExpr.Create);
RegisterCodeGen(TMagicProcedureExpr, TJSMagicFuncExpr.Create);
RegisterCodeGen(TConstructorStaticExpr, TJSConstructorStaticExpr.Create);
RegisterCodeGen(TConstructorVirtualExpr, TJSConstructorVirtualExpr.Create);
RegisterCodeGen(TConstructorVirtualObjExpr, TJSMethodVirtualExpr.Create);
RegisterCodeGen(TConstructorStaticObjExpr, TJSMethodStaticExpr.Create);
RegisterCodeGen(TDestructorStaticExpr, TJSMethodStaticExpr.Create);
RegisterCodeGen(TDestructorVirtualExpr, TJSMethodVirtualExpr.Create);
RegisterCodeGen(TMethodStaticExpr, TJSMethodStaticExpr.Create);
RegisterCodeGen(TMethodVirtualExpr, TJSMethodVirtualExpr.Create);
RegisterCodeGen(TMethodInterfaceExpr, TJSMethodInterfaceExpr.Create);
RegisterCodeGen(TClassMethodStaticExpr, TJSClassMethodStaticExpr.Create);
RegisterCodeGen(TClassMethodVirtualExpr, TJSClassMethodVirtualExpr.Create);
RegisterCodeGen(TConnectorCallExpr, TJSConnectorCallExpr.Create);
RegisterCodeGen(TConnectorReadExpr, TJSConnectorReadExpr.Create);
RegisterCodeGen(TConnectorWriteExpr, TJSConnectorWriteExpr.Create);
RegisterCodeGen(TFuncPtrExpr, TJSFuncPtrExpr.Create);
RegisterCodeGen(TFuncRefExpr, TJSFuncRefExpr.Create);
RegisterCodeGen(TAnonymousFuncRefExpr, TJSAnonymousFuncRefExpr.Create);
RegisterCodeGen(TFieldExpr, TJSFieldExpr.Create);
RegisterCodeGen(TReadOnlyFieldExpr, TJSFieldExpr.Create);
RegisterCodeGen(TAssertExpr, TJSAssertExpr.Create);
RegisterCodeGen(TDeclaredExpr, TJSDeclaredExpr.Create);
RegisterCodeGen(TDefinedExpr, TJSDefinedExpr.Create);
end;
// Destroy
//
destructor TdwsJSCodeGen.Destroy;
begin
inherited;
FLocalVarScannedProg.Free;
FAllLocalVarSymbols.Free;
while FDeclaredLocalVarsStack.Count>0 do begin
FDeclaredLocalVarsStack.Peek.Free;
FDeclaredLocalVarsStack.Pop;
end;
FDeclaredLocalVarsStack.Free;
FDeclaredLocalVars.Free;
end;
// Clear
//
procedure TdwsJSCodeGen.Clear;
begin
FLocalVarScannedProg.Clear;
FAllLocalVarSymbols.Clear;
inherited;
end;
// SymbolMappedName
//
function TdwsJSCodeGen.SymbolMappedName(sym : TSymbol; scope : TdwsCodeGenSymbolScope) : String;
var
ct : TClass;
begin
ct:=sym.ClassType;
if ct=TSelfSymbol then
Result:=SelfSymbolName
else if ct=TResultSymbol then
Result:=ResultSymbolName
else begin
Result:=inherited SymbolMappedName(sym, scope);
end;
end;
// CompileValue
//
procedure TdwsJSCodeGen.CompileValue(expr : TTypedExpr);
function NeedArrayCopy(paramExpr : TArrayConstantExpr) : Boolean;
var
i : Integer;
sub : TExprBase;
begin
for i:=0 to paramExpr.SubExprCount-1 do begin
sub:=paramExpr.SubExpr[i];
if sub is TConstExpr then continue;
if sub is TTypedExpr then begin
if TTypedExpr(sub).Typ.UnAliasedType is TBaseSymbol then continue;
end;
Exit(True);
end;
Result:=False;
end;
var
exprTypClass : TClass;
begin
exprTypClass:=expr.Typ.ClassType;
if not (expr is TFuncExprBase) then begin
if exprTypClass=TRecordSymbol then begin
WriteString('Copy$');
WriteSymbolName(expr.Typ);
WriteString('(');
CompileNoWrap(expr);
WriteString(')');
Exit;
end else if (exprTypClass=TStaticArraySymbol) or (exprTypClass=TOpenArraySymbol) then begin
CompileNoWrap(expr);
if (not (expr is TArrayConstantExpr))
or NeedArrayCopy(TArrayConstantExpr(expr)) then
WriteString('.slice(0)');
Exit;
end;
end;
CompileNoWrap(expr);
end;
// CompileEnumerationSymbol
//
procedure TdwsJSCodeGen.CompileEnumerationSymbol(enum : TEnumerationSymbol);
var
i : Integer;
elem : TElementSymbol;
begin
if enum.Elements.Count=0 then Exit;
if not SmartLink(enum) then Exit;
if cgoOptimizeForSize in Options then Exit;
WriteSymbolVerbosity(enum);
for i:=0 to enum.Elements.Count-1 do begin
elem:=enum.Elements[i] as TElementSymbol;
WriteString(elem.Name);
WriteString('=');
WriteString(IntToStr(elem.Value));
WriteStatementEnd;
end;
end;
// CompileFuncSymbol
//
procedure TdwsJSCodeGen.DoCompileFuncSymbol(func : TSourceFuncSymbol);
begin
FDebugInfo := FDebugInfo + #13 +
IntToStr(func.SourcePosition.Line) + '=' +
IntToStr(Output.Position);
//func.SourcePosition.SourceFile.Name;
WriteString(Format('/*@%d*/',[func.SourcePosition.Line]));
WriteString('function ');
if func.Name<>'' then
WriteSymbolName(func);
WriteString('(');
WriteFuncParams(func);
WriteBlockBegin(') ');
CompileFuncBody(func);
UnIndent;
WriteString('}');
if func.Name<>'' then
WriteStatementEnd;
end;
// CompileConditions
//
procedure TdwsJSCodeGen.CompileConditions(func : TFuncSymbol; conditions : TSourceConditions;
preConds : Boolean);
procedure CompileInheritedConditions;
var
iter : TMethodSymbol;
iterProc : TdwsProcedure;
begin
if func is TMethodSymbol then begin
iter:=TMethodSymbol(func);
while iter.IsOverride and (iter.ParentMeth<>nil) do
iter:=iter.ParentMeth;
if (iter<>func) and (iter is TSourceMethodSymbol) then begin
iterProc:=TSourceMethodSymbol(iter).Executable as TdwsProcedure;
if iterProc<>nil then begin
if preConds then
CompileConditions(iter, iterProc.PreConditions, preConds)
else CompileConditions(iter, iterProc.PostConditions, preConds);
end;
end;
end;
end;
var
i : Integer;
cond : TSourceCondition;
msgFmt : String;
begin
if preConds then
CompileInheritedConditions;
if (conditions=nil) or (conditions.Count=0) then Exit;
Dependencies.Add('$CondFailed');
if preConds then
msgFmt:=RTE_PreConditionFailed
else msgFmt:=RTE_PostConditionFailed;
for i:=0 to conditions.Count-1 do begin
cond:=conditions[i];
WriteString('if (!');
Compile(cond.Test);
WriteString(') $CondFailed(');
WriteJavaScriptString(Format(msgFmt, [func.QualifiedName, cond.Pos.AsInfo, '']));
WriteString(',');
Compile(cond.Msg);
WriteString(')');
WriteStatementEnd;
end;
if not preConds then
CompileInheritedConditions;
end;
// DoCompileHelperSymbol
//
procedure TdwsJSCodeGen.DoCompileHelperSymbol(helper : THelperSymbol);
var
i : Integer;
sym : TSymbol;
begin
// compile methods
for i:=0 to helper.Members.Count-1 do begin
sym:=helper.Members[i];
if sym is TMethodSymbol then
CompileHelperMethod(TMethodSymbol(sym));
end;
end;
// DoCompileRecordSymbol
//
procedure TdwsJSCodeGen.DoCompileRecordSymbol(rec : TRecordSymbol);
var
i : Integer;
sym : TSymbol;
field : TFieldSymbol;
fieldTyp : TTypeSymbol;
firstField : Boolean;
begin
// compile record copier
if not SmartLink(rec) then Exit;
WriteSymbolVerbosity(rec);
WriteString('function Copy$');
WriteSymbolName(rec);
WriteBlockBegin('($s) ');
WriteBlockBegin('return ');
firstField:=True;
for i:=0 to rec.Members.Count-1 do begin
sym:=rec.Members[i];
if sym is TFieldSymbol then begin
field:=TFieldSymbol(sym);
if firstField then
firstField:=False
else WriteString(',');
WriteSymbolName(field);
WriteString(':');
fieldTyp:=field.Typ.UnAliasedType;
if (fieldTyp is TBaseSymbol)
or (fieldTyp is TClassSymbol)
or (fieldTyp is TInterfaceSymbol)
or (fieldTyp is TFuncSymbol)
or (fieldTyp is TDynamicArraySymbol)
or (fieldTyp is TEnumerationSymbol) then begin
WriteString('$s.');
WriteSymbolName(field)
end else if fieldTyp is TRecordSymbol then begin
WriteString('Copy$');
WriteSymbolName(fieldTyp);
WriteString('($s.');
WriteSymbolName(field);
WriteString(')');
end else if fieldTyp is TStaticArraySymbol then begin
WriteString('$s.');
WriteSymbolName(field);
WriteString('.slice(0)');
end else raise ECodeGenUnsupportedSymbol.CreateFmt('Copy record field type %s', [fieldTyp.ClassName]);
WriteStringLn('');
end;
end;
WriteBlockEndLn;
WriteBlockEndLn;
// compile methods
for i:=0 to rec.Members.Count-1 do begin
sym:=rec.Members[i];
if sym is TMethodSymbol then
CompileRecordMethod(TMethodSymbol(sym));
end;
end;
// DoCompileClassSymbol
//
procedure TdwsJSCodeGen.DoCompileClassSymbol(cls : TClassSymbol);
var
i : Integer;
sym : TSymbol;
meth : TMethodSymbol;
begin
inherited;
if not SmartLink(cls) then Exit;
WriteSymbolVerbosity(cls);
WriteString('var ');
WriteSymbolName(cls);
WriteBlockBegin('= ');
WriteString('$ClassName:');
WriteJavaScriptString(cls.Name);
WriteStringLn(',');
WriteString('$Parent:');
WriteSymbolName(cls.Parent);
WriteStringLn(',');
Dependencies.Add('$New');
Dependencies.Add('TObject');
WriteBlockBegin('$Init:function ($) ');
WriteSymbolName(cls.Parent);
WriteString('.$Init($)');
WriteStatementEnd;
DoCompileFieldsInit(cls);
UnIndent;
WriteStringLn('}');
// Compile methods specified by the class
for i:=0 to cls.Members.Count-1 do begin
sym:=cls.Members[i];
if sym is TMethodSymbol then
CompileMethod(TMethodSymbol(sym));
end;
// VMT entries for methods not overridden here
for i:=0 to cls.VMTCount-1 do begin
meth:=cls.VMTMethod(i);
if not SmartLinkMethod(meth) then continue;
if meth.StructSymbol<>cls then begin
WriteString(',');
WriteString(MemberName(meth, meth.StructSymbol));
WriteString(':');
WriteSymbolName(meth.StructSymbol);
WriteString('.');
WriteString(MemberName(meth, meth.StructSymbol));
WriteLineEnd;
end;
if meth.StructSymbol=cls then begin
WriteString(',');
WriteString(MemberName(meth, meth.StructSymbol));
WriteString(cVirtualPostfix+':');
if meth.Kind=fkConstructor then begin
WriteString('function($){return $.ClassType.');
end else if meth.IsClassMethod then begin
WriteString('function($){return $.');
end else begin
WriteString('function($){return $.ClassType.');
end;
WriteString(MemberName(meth, meth.StructSymbol));
if meth.Params.Count=0 then
WriteStringLn('($)}')
else WriteStringLn('.apply($.ClassType, arguments)}');
end;
end;
UnIndent;
WriteString('}');
WriteStatementEnd;
DoCompileInterfaceTable(cls);
end;
// DoCompileFieldsInit
//
procedure TdwsJSCodeGen.DoCompileFieldsInit(cls : TClassSymbol);
var
i, j, n : Integer;
sym, sym2 : TSymbol;
flds : array of TFieldSymbol;
begin
SetLength(flds, cls.Members.Count);
n:=0;
for i:=0 to cls.Members.Count-1 do begin
sym:=cls.Members[i];
if sym is TFieldSymbol then begin
if (TFieldSymbol(sym).Visibility=cvPublished) or SmartLink(sym) then begin
flds[n]:=TFieldSymbol(sym);
Inc(n);
end;
end;
end;
// aggregate initializations by type
for i:=0 to n-1 do begin
sym:=flds[i];
if sym=nil then continue;
for j:=i to n-1 do begin
sym2:=flds[j];
if sym2=nil then continue;
if SameDefaultValue(sym2.Typ, sym.Typ) then begin
WriteString('$.');
WriteString(MemberName(sym2, cls));
WriteString('=');
flds[j]:=nil;
// records, static arrays and other value types can't be assigned together
if not ((sym.Typ is TBaseSymbol) or (sym.Typ is TClassSymbol) or (sym.Typ is TInterfaceSymbol)) then Break;
end;
end;
WriteDefaultValue(sym.Typ, False);
WriteStatementEnd;
end;
end;
// DoCompileInterfaceTable
//
procedure TdwsJSCodeGen.DoCompileInterfaceTable(cls : TClassSymbol);
var
needIntfTable : Boolean;
iter : TClassSymbol;
writtenInterfaces : TList;
begin
needIntfTable:=False;
iter:=cls;
while iter<>nil do begin
if iter.Interfaces<>nil then begin
needIntfTable:=True;
Break;
end;
iter:=iter.Parent;
end;
if not needIntfTable then Exit;
WriteSymbolName(cls);
WriteBlockBegin('.$Intf=');
writtenInterfaces:=TList.Create;
try
iter:=cls;
while iter<>nil do begin
if iter.Interfaces<>nil then begin
iter.Interfaces.Enumerate(
procedure (const item : TResolvedInterface)
var
i : Integer;
begin
if writtenInterfaces.IndexOf(item.IntfSymbol)>=0 then Exit;
if writtenInterfaces.Count>0 then
Self.WriteString(',');
writtenInterfaces.Add(item.IntfSymbol);
Self.WriteSymbolName(item.IntfSymbol);
Self.WriteString(':[');
for i:=0 to High(item.VMT) do begin
if i>0 then
Self.WriteString(',');
WriteSymbolName(iter);
Self.WriteString('.');
Self.WriteSymbolName(item.VMT[i]);
end;
Self.WriteStringLn(']');
end);
end;
iter:=iter.Parent;
end;
finally
writtenInterfaces.Free;
end;
WriteBlockEndLn;
end;
// CompileProgramBody
//
procedure TdwsJSCodeGen.CompileProgramBody(expr : TNoResultExpr);
begin
if expr is TNullExpr then Exit;
if FMainBodyName<>'' then begin
WriteString('var ');
WriteString(FMainBodyName);
WriteBlockBegin('= function() ');
end;
inherited;
if FMainBodyName<>'' then begin
WriteBlockEndLn;
WriteString(FMainBodyName);
WriteString('()');
WriteStatementEnd;
end;
end;
// CompileSymbolTable
//
procedure TdwsJSCodeGen.CompileSymbolTable(table : TSymbolTable);
var
varSym : TDataSymbol;
sym : TSymbol;
declaredOne : Boolean;
begin
inherited;
declaredOne:=False;
for sym in table do begin
if sym.ClassType=TDataSymbol then begin
varSym:=TDataSymbol(sym);
if FDeclaredLocalVars.IndexOf(varSym)<0 then begin
FDeclaredLocalVars.Add(varSym);
if not declaredOne then begin
WriteString('var ');
declaredOne:=True;
end else begin
if cgoOptimizeForSize in Options then
WriteString(',')
else begin
WriteStringLn(',');
WriteString(' ');
end;
end;
WriteSymbolName(varSym);
if varSym.Typ.ClassType=TBaseVariantSymbol then begin
// undefined is JS default for unassigned var
end else begin
WriteString('=');
WriteDefaultValue(varSym.Typ, TJSExprCodeGen.IsLocalVarParam(Self, varSym));
end;
end;
end;
end;
if declaredOne then
WriteStatementEnd;
end;
// ReserveSymbolNames
//
procedure TdwsJSCodeGen.ReserveSymbolNames;
var
i : Integer;
begin
for i:=Low(cJSReservedWords) to High(cJSReservedWords) do
SymbolMap.ReserveName(cJSReservedWords[i]);
SymbolMap.ReserveName(MainBodyName);
if cgoOptimizeForSize in Options then begin
SelfSymbolName:='S';
ResultSymbolName:='R';
end else begin
SelfSymbolName:='Self';
ResultSymbolName:='Result';
end;
SymbolMap.ReserveName(SelfSymbolName);
SymbolMap.ReserveName(ResultSymbolName);
end;
// CompileDependencies
//
procedure TdwsJSCodeGen.CompileDependencies(destStream : TWriteOnlyBlockStream; const prog : IdwsProgram);
var
processedDependencies : TStringList;
procedure InsertResourceDependency(const depName : String);
var
rs : TResourceStream;
buf : UTF8String;
begin
if FlushedDependencies.IndexOf(depName)>=0 then Exit;
rs:=TResourceStream.Create(HInstance, depName, 'dwsjsrtl');
try
SetLength(buf, rs.Size);
rs.Read(buf[1], rs.Size);
destStream.WriteString(UTF8ToString(buf));
finally
rs.Free;
end;
FlushedDependencies.Add(depName);
end;
procedure InsertDependency(dep : PJSRTLDependency);
var
sub : PJSRTLDependency;
begin
if FlushedDependencies.IndexOf(dep.Name)>=0 then Exit;
if (dep.Dependency<>'')
and (processedDependencies.IndexOf(dep.Dependency)<0) then begin
processedDependencies.Add(dep.Dependency);
if dep.Dependency[1]='!' then begin
InsertResourceDependency(Copy(dep.Dependency, 2, MaxInt));
end else begin
sub:=FindJSRTLDependency(dep.Dependency);
if sub<>nil then
InsertDependency(sub);
end;
end;
destStream.WriteString(dep.Code);
destStream.WriteString(';'#13#10);
FlushedDependencies.Add(dep.Name);
end;
var
i : Integer;
dependency : String;
jsRTL : PJSRTLDependency;
begin
processedDependencies:=TStringList.Create;
processedDependencies.Sorted:=True;
try
for i:=Dependencies.Count-1 downto 0 do begin
dependency:=Dependencies[i];
if FlushedDependencies.IndexOf(dependency)>=0 then
continue;
jsRTL:=FindJSRTLDependency(dependency);
processedDependencies.Add(dependency);
if jsRTL<>nil then
InsertDependency(jsRTL)
else if dependency='$ConditionalDefines' then begin
destStream.WriteString('var $ConditionalDefines=');
WriteStringArray(destStream, (prog as TdwsProgram).Root.ConditionalDefines.Value);
destStream.WriteString(';'#13#10);
end;
Dependencies.Delete(i);
end;
finally
processedDependencies.Free;
end;
end;
// CompileResourceStrings
//
procedure TdwsJSCodeGen.CompileResourceStrings(destStream : TWriteOnlyBlockStream; const prog : IdwsProgram);
var
i : Integer;
resList : TResourceStringSymbolList;
begin
if (cgoSmartLink in Options) and (Dependencies.IndexOf('$R')<0) then Exit;
resList:=prog.ProgramObject.ResourceStringList;
destStream.WriteString('var $R = [');
for i:=0 to resList.Count-1 do begin
if i>0 then
destStream.WriteString(','#13#10#9)
else destStream.WriteString(#13#10#9);
dwsJSON.WriteJavaScriptString(destStream, resList[i].Value);
end;
destStream.WriteString('];'#13#10);
end;
// GetNewTempSymbol
//
function TdwsJSCodeGen.GetNewTempSymbol : String;
function IntToBase62(i : Integer) : String;
var
n : Integer;
c : Char;
begin
Result:='';
repeat
n:=(i mod 62);
i:=(i div 62);
case n of
0..9 : c:=Char(Ord('0')+n);
10..35 : c:=Char(Ord('A')+n-10);
else
c:=Char(Ord('a')+n-36);
end;
Result:=Result+c;
until i=0;
end;
begin
if cgoOptimizeForSize in Options then begin
Result:='$t'+IntToBase62(IncTempSymbolCounter)
end else Result:='$temp'+inherited GetNewTempSymbol;
end;
// WriteSymbolVerbosity
//
procedure TdwsJSCodeGen.WriteSymbolVerbosity(sym : TSymbol);
procedure DoWrite;
var
funcSym : TFuncSymbol;
symPos : TSymbolPosition;
begin
if sym is TClassSymbol then begin
WriteString('/// ');
WriteString(sym.QualifiedName);
WriteString(' = class (');
WriteString(TClassSymbol(sym).Parent.QualifiedName);
WriteStringLn(')');
end else if sym is TRecordSymbol then begin
WriteString('/// ');
WriteString(sym.QualifiedName);
WriteStringLn(' = record');
end else if sym is TFuncSymbol then begin
funcSym:=TFuncSymbol(sym);
WriteString('/// ');
WriteString(cFuncKindToString[funcSym.Kind]);
WriteString(' ');
WriteString(funcSym.QualifiedName);
WriteString(funcSym.ParamsDescription);
if funcSym.Typ<>nil then begin
WriteString(' : ');
WriteString(funcSym.Typ.QualifiedName);
end;
WriteLineEnd;
end else if sym is TEnumerationSymbol then begin
WriteString('/// ');
WriteString(sym.QualifiedName);
WriteString(' enumeration');
end else Exit;
if SymbolDictionary<>nil then begin
symPos:=SymbolDictionary.FindSymbolUsage(sym, suImplementation);
if symPos=nil then
symPos:=SymbolDictionary.FindSymbolUsage(sym, suDeclaration);
if symPos<>nil then begin
WriteString('/// ');
WriteString(symPos.ScriptPos.AsInfo);
WriteLineEnd;
end;
end;
end;
begin
if Verbosity>cgovNone then
DoWrite;
end;
// WriteJavaScriptString
//
procedure TdwsJSCodeGen.WriteJavaScriptString(const s : String);
begin
dwsJSON.WriteJavaScriptString(Output, s);
end;
// CollectLocalVars
//
procedure TdwsJSCodeGen.CollectLocalVars(proc : TdwsProgram);
begin
CollectLocalVarParams(proc.InitExpr);
CollectLocalVarParams(proc.Expr);
end;
// CollectFuncSymLocalVars
//
procedure TdwsJSCodeGen.CollectFuncSymLocalVars(funcSym : TFuncSymbol);
var
p : TdwsProgram;
s : TObject;
exec : IExecutable;
begin
if (funcSym.ClassType=TSourceFuncSymbol) or (funcSym.ClassType=TSourceMethodSymbol) then begin
exec:=funcSym.Executable;
if exec<>nil then begin
s:=exec.GetSelf;
if s is TdwsProgram then begin
p:=TdwsProgram(s);
if FLocalVarScannedProg.Add(p) then begin
EnterScope(funcSym);
CollectLocalVars(p);
LeaveScope;
end;
end;
end;
end;
end;
// CollectLocalVarParams
//
procedure TdwsJSCodeGen.CollectLocalVarParams(expr : TExprBase);
begin
if expr=nil then Exit;
expr.RecursiveEnumerateSubExprs(
procedure (parent, expr : TExprBase; var abort : Boolean)
var
funcSym : TFuncSymbol;
varSym : TDataSymbol;
paramSym : TParamSymbol;
i : Integer;
right : TExprBase;
begin
if expr is TFuncExprBase then begin
funcSym:=TFuncExprBase(expr).FuncSym;
if funcSym<>nil then
CollectFuncSymLocalVars(funcSym);
end;
if (expr is TVarExpr) and (parent is TFuncExprBase) then begin
funcSym:=TFuncExprBase(parent).FuncSym;
i:=parent.IndexOfSubExpr(expr);
if parent is TFuncPtrExpr then begin
if i=0 then
Exit
else Dec(i);
end else if (parent is TMethodExpr) then begin
if (i=0) then
Exit
else Dec(i);
end else if (i>0) and (parent is TConstructorStaticExpr) then begin
Dec(i);
end;
if (funcSym=nil) or (i>=funcSym.Params.Count) then begin
if (parent.ClassType=TDecVarFuncExpr) or (parent.ClassType=TIncVarFuncExpr) then begin
right:=TMagicIteratorFuncExpr(parent).Args[1];
if TdwsExprCodeGen.ExprIsConstantInteger(right, 1) then
Exit // special case handled via ++ or --, no need to pass by ref
else varSym:=TVarExpr(expr).DataSym;
end else begin
// else not supported yet
Exit;
end;
end else begin
paramSym:=funcSym.Params[i] as TParamSymbol;
if ShouldBoxParam(paramSym) then
varSym:=TVarExpr(expr).DataSym
else Exit;
end;
end else if (expr is TExitExpr) then begin
// exit with a try.. clause that modifies the result can cause issues
// with JS immutability, this is a heavy-handed solution
varSym:=LocalTable.FindSymbol(SYS_RESULT, cvMagic) as TDataSymbol;
end else begin
// else not supported yet
Exit;
end;
FAllLocalVarSymbols.Add(varSym);
end);
end;
// CollectInitExprLocalVars
//
procedure TdwsJSCodeGen.CollectInitExprLocalVars(initExpr : TBlockExprBase);
var
i : Integer;
curExpr : TExprBase;
expr : TVarExpr;
varSym : TDataSymbol;
begin
for i:=0 to initExpr.SubExprCount-1 do begin
curExpr:=initExpr.SubExpr[i];
if curExpr is TBlockExprBase then begin
CollectInitExprLocalVars(TBlockExprBase(curExpr));
end else begin
Assert((curExpr is TAssignExpr) or (curExpr is TInitDataExpr));
expr:=curExpr.SubExpr[0] as TVarExpr;
varSym:=expr.DataSym; // FindSymbolAtStackAddr(expr.StackAddr, Context.Level);
FDeclaredLocalVars.Add(varSym);
end;
end;
end;
// CreateSymbolMap
//
function TdwsJSCodeGen.CreateSymbolMap(parentMap : TdwsCodeGenSymbolMap; symbol : TSymbol) : TdwsCodeGenSymbolMap;
begin
if cgoObfuscate in Options then
Result:=TdwsCodeGenSymbolMapJSObfuscating.Create(parentMap, symbol)
else Result:=TdwsCodeGenSymbolMap.Create(parentMap, symbol);
end;
// EnterContext
//
procedure TdwsJSCodeGen.EnterContext(proc : TdwsProgram);
begin
inherited;
FDeclaredLocalVarsStack.Push(FDeclaredLocalVars);
FDeclaredLocalVars:=TDataSymbolList.Create;
CollectInitExprLocalVars(proc.InitExpr);
CollectLocalVarParams(proc.Expr);
end;
// LeaveContext
//
procedure TdwsJSCodeGen.LeaveContext;
begin
FDeclaredLocalVars.Free;
FDeclaredLocalVars:=FDeclaredLocalVarsStack.Peek;
FDeclaredLocalVarsStack.Pop;
inherited;
end;
// SameDefaultValue
//
function TdwsJSCodeGen.SameDefaultValue(typ1, typ2 : TTypeSymbol) : Boolean;
begin
Result:= (typ1=typ2)
or ( ((typ1 is TClassSymbol) or (typ1 is TFuncSymbol) or (typ1 is TInterfaceSymbol))
and ((typ2 is TClassSymbol) or (typ2 is TFuncSymbol) or (typ2 is TInterfaceSymbol)) );
end;
// WriteDefaultValue
//
procedure TdwsJSCodeGen.WriteDefaultValue(typ : TTypeSymbol; box : Boolean);
var
i : Integer;
comma : Boolean;
sas : TStaticArraySymbol;
recSym : TRecordSymbol;
member : TFieldSymbol;
begin
typ:=typ.UnAliasedType;
if box then
WriteString('{'+cBoxFieldName+':');
if typ is TBaseIntegerSymbol then
WriteString('0')
else if typ is TBaseFloatSymbol then
WriteString('0.0')
else if typ is TBaseStringSymbol then
WriteString('""')
else if typ is TBaseBooleanSymbol then
WriteString(cBoolToJSBool[false])
else if typ is TBaseVariantSymbol then
WriteString('undefined')
else if typ is TClassSymbol then
WriteString('null')
else if typ is TClassOfSymbol then
WriteString('null')
else if typ is TFuncSymbol then
WriteString('null')
else if typ is TInterfaceSymbol then
WriteString('null')
else if typ is TEnumerationSymbol then
WriteString(IntToStr(TEnumerationSymbol(typ).DefaultValue))
else if typ is TStaticArraySymbol then begin
sas:=TStaticArraySymbol(typ);
if sas.ElementCount<cInlineStaticArrayLimit then begin
// initialize "small" static arrays inline
WriteString('[');
for i:=0 to sas.ElementCount-1 do begin
if i>0 then
WriteString(',');
WriteDefaultValue(sas.Typ, False);
end;
WriteString(']');
end else begin
// use a function for larger ones
WriteBlockBegin('function () ');
WriteString('for (var r=[],i=0; i<'+IntToStr(sas.ElementCount)+'; i++) r.push(');
WriteDefaultValue(sas.Typ, False);
WriteStringLn(');');
WriteStringLn('return r');
WriteBlockEnd;
WriteString('()');
end;
end else if typ is TDynamicArraySymbol then begin
WriteString('[]');
end else if typ is TRecordSymbol then begin
recSym:=TRecordSymbol(typ);
WriteString('{');
comma:=False;
for i:=0 to recSym.Members.Count-1 do begin
if not (recSym.Members[i] is TFieldSymbol) then continue;
if comma then
WriteString(',')
else comma:=True;
member:=TFieldSymbol(recSym.Members[i]);
WriteSymbolName(member);
WriteString(':');
WriteDefaultValue(member.Typ, False);
end;
WriteString('}');
end else raise ECodeGenUnsupportedSymbol.CreateFmt('Default value of type %s', [typ.ClassName]);
if box then
WriteString('}');
end;
// WriteValue
//
procedure TdwsJSCodeGen.WriteValue(typ : TTypeSymbol; const data : TData; addr : Integer);
var
i : Integer;
recSym : TRecordSymbol;
member : TFieldSymbol;
sas : TStaticArraySymbol;
intf : IUnknown;
comma : Boolean;
begin
typ:=typ.UnAliasedType;
if typ is TBaseIntegerSymbol then
WriteString(IntToStr(data[addr]))
else if typ is TBaseFloatSymbol then
WriteString(FloatToStr(data[addr], cFormatSettings))
else if typ is TBaseStringSymbol then
WriteJavaScriptString(VarToStr(data[addr]))
else if typ is TBaseBooleanSymbol then begin
WriteString(cBoolToJSBool[Boolean(data[addr])])
end else if typ is TBaseVariantSymbol then begin
case VarType(data[addr]) of
varEmpty :
WriteString('undefined');
varNull :
WriteString('null');
varInteger, varSmallint, varShortInt, varInt64, varByte, varWord, varUInt64 :
WriteString(IntToStr(data[addr]));
varSingle, varDouble, varCurrency :
WriteString(FloatToStr(data[addr], cFormatSettings));
varString, varUString, varOleStr :
WriteJavaScriptString(VarToStr(data[addr]));
varBoolean :
WriteString(cBoolToJSBool[Boolean(data[addr])])
else
raise ECodeGenUnsupportedSymbol.CreateFmt('Value of type %s (VarType = %d)',
[typ.ClassName, VarType(data[addr])]);
end;
end else if typ is TNilSymbol then begin
WriteString('null')
end else if typ is TClassOfSymbol then begin
WriteSymbolName(TClassOfSymbol(typ).TypClassSymbol);
end else if typ is TStaticArraySymbol then begin
sas:=TStaticArraySymbol(typ);
WriteString('[');
for i:=0 to sas.ElementCount-1 do begin
if i>0 then
WriteString(',');
WriteValue(sas.Typ, data, addr+i*sas.Typ.Size);
end;
WriteString(']');
end else if typ is TRecordSymbol then begin
recSym:=TRecordSymbol(typ);
WriteString('{');
comma:=False;
for i:=0 to recSym.Members.Count-1 do begin
if not (recSym.Members[i] is TFieldSymbol) then continue;
if comma then
WriteString(',')
else comma:=True;
member:=TFieldSymbol(recSym.Members[i]);
WriteSymbolName(member);
WriteString(':');
WriteValue(member.Typ, data, addr+member.Offset);
end;
WriteString('}');
end else if typ is TClassSymbol then begin
intf:=data[addr];
if intf=nil then
WriteString('null')
else raise ECodeGenUnsupportedSymbol.Create('Non nil class symbol');
end else if typ is TDynamicArraySymbol then begin
intf:=data[addr];
if (IScriptObj(intf).InternalObject as TScriptDynamicArray).Length=0 then
WriteString('[]')
else raise ECodeGenUnsupportedSymbol.Create('Non empty dynamic array symbol');
end else if typ is TInterfaceSymbol then begin
intf:=data[addr];
if intf=nil then
WriteString('null')
else raise ECodeGenUnsupportedSymbol.Create('Non nil interface symbol');
end else begin
raise ECodeGenUnsupportedSymbol.CreateFmt('Value of type %s',
[typ.ClassName]);
end;
end;
// WriteStringArray
//
procedure TdwsJSCodeGen.WriteStringArray(destStream : TWriteOnlyBlockStream; strings : TStrings);
var
i : Integer;
begin
destStream.WriteString('[');
for i:=0 to strings.Count-1 do begin
if i<>0 then
destStream.WriteString(',');
dwsJSON.WriteJavaScriptString(destStream, strings[i]);
end;
destStream.WriteString(']');
end;
// WriteStringArray
//
procedure TdwsJSCodeGen.WriteStringArray(strings : TStrings);
begin
WriteStringArray(Output, strings);
end;
// WriteFuncParams
//
procedure TdwsJSCodeGen.WriteFuncParams(func : TFuncSymbol);
var
i : Integer;
needComma : Boolean;
begin
if (func is TMethodSymbol)
and not ( TMethodSymbol(func).IsStatic
or (TMethodSymbol(func).StructSymbol is TRecordSymbol)
or (TMethodSymbol(func).StructSymbol is THelperSymbol)) then begin
WriteString(SelfSymbolName);
needComma:=True;
end else needComma:=False;
for i:=0 to func.Params.Count-1 do begin
if needComma then
WriteString(', ');
WriteSymbolName(func.Params[i]);
needComma:=True;
end;
end;
// CompileFuncBody
//
procedure TdwsJSCodeGen.CompileFuncBody(func : TFuncSymbol);
function ResultIsNotUsedInExpr(anExpr : TExprBase) : Boolean;
var
foundIt : Boolean;
begin
foundIt:=False;
anExpr.RecursiveEnumerateSubExprs(
procedure (parent, expr : TExprBase; var abort : Boolean)
begin
abort:= (expr is TVarExpr)
and (TVarExpr(expr).DataSym is TResultSymbol);
if abort then
foundIt:=True;
end);
Result:=not foundIt;
end;
var
resultTyp : TTypeSymbol;
proc : TdwsProcedure;
resultIsBoxed : Boolean;
param : TParamSymbol;
i : Integer;
cg : TdwsExprCodeGen;
assignExpr : TAssignExpr;
begin
proc:=(func.Executable as TdwsProcedure);
if proc=nil then Exit;
// box params that the function will pass as var
for i:=0 to proc.Func.Params.Count-1 do begin
param:=proc.Func.Params[i] as TParamSymbol;
if (not ShouldBoxParam(param)) and TJSExprCodeGen.IsLocalVarParam(Self, param) then begin
WriteSymbolName(param);
WriteString('={'+cBoxFieldName+':');
WriteSymbolName(param);
WriteString('}');
WriteStatementEnd;
end;
end;
resultTyp:=func.Typ;
if resultTyp<>nil then begin
resultIsBoxed:=TJSExprCodeGen.IsLocalVarParam(Self, func.Result);
resultTyp:=resultTyp.UnAliasedType;
// optimize to a straight "return" statement for trivial functions
if (not resultIsBoxed) and (proc.Table.Count=0)
and ((proc.InitExpr=nil) or (proc.InitExpr.SubExprCount=0))
and (proc.Expr is TAssignExpr) then begin
assignExpr:=TAssignExpr(proc.Expr);
if (assignExpr.Left is TVarExpr)
and (TVarExpr(assignExpr.Left).DataSym is TResultSymbol) then begin
cg:=FindCodeGen(assignExpr);
if (cg is TJSAssignExpr) and ResultIsNotUsedInExpr(assignExpr.Right) then begin
WriteString('return ');
TJSAssignExpr(cg).CodeGenRight(Self, assignExpr);
WriteStatementEnd;
Exit;
end
end;
end;
WriteString('var ');
WriteString(ResultSymbolName);
WriteString('=');
WriteDefaultValue(resultTyp, resultIsBoxed);
WriteStatementEnd;
end else resultIsBoxed:=False;
if resultIsBoxed then
WriteBlockBegin('try ');
if not (cgoNoConditions in Options) then
CompileConditions(func, proc.PreConditions, True);
Compile(proc.InitExpr);
CompileSymbolTable(proc.Table);
Compile(proc.Expr);
if not (cgoNoConditions in Options) then
CompileConditions(func, proc.PostConditions, False);
if resultTyp<>nil then begin
if resultIsBoxed then begin
WriteBlockEnd;
WriteString(' finally {return ');
WriteString(ResultSymbolName);
WriteString('.');
WriteString(cBoxFieldName);
WriteStringLn('}')
end else begin
WriteString('return ');
WriteStringLn(ResultSymbolName);
end;
end;
end;
// CompileMethod
//
procedure TdwsJSCodeGen.CompileMethod(meth : TMethodSymbol);
var
proc : TdwsProcedure;
begin
if not (meth.Executable is TdwsProcedure) then Exit;
proc:=(meth.Executable as TdwsProcedure);
if not SmartLinkMethod(meth) then Exit;
if not (meth.IsVirtual or meth.IsInterfaced) then
if meth.Kind in [fkProcedure, fkFunction, fkMethod] then
if not SmartLink(meth) then Exit;
WriteSymbolVerbosity(meth);
WriteString(',');
WriteString(MemberName(meth, meth.StructSymbol));
EnterScope(meth);
EnterContext(proc);
try
WriteString(':function(');
WriteFuncParams(meth);
WriteBlockBegin(') ');
CompileFuncBody(meth);
if meth.Kind=fkConstructor then begin
WriteString('return ');
WriteStringLn(SelfSymbolName);
end;
WriteBlockEndLn;
finally
LeaveContext;
LeaveScope;
end;
end;
// CompileRecordMethod
//
procedure TdwsJSCodeGen.CompileRecordMethod(meth : TMethodSymbol);
var
proc : TdwsProcedure;
begin
if not (meth.Executable is TdwsProcedure) then Exit;
proc:=(meth.Executable as TdwsProcedure);
if not SmartLink(meth) then Exit;
WriteSymbolVerbosity(meth);
WriteString('function ');
if not meth.IsClassMethod then begin
WriteSymbolName(meth.StructSymbol);
WriteString('$');
end;
WriteSymbolName(meth);
EnterScope(meth);
EnterContext(proc);
try
WriteString('(');
WriteFuncParams(meth);
WriteBlockBegin(') ');
CompileFuncBody(meth);
if meth.Kind=fkConstructor then begin
WriteString('return ');
WriteStringLn(SelfSymbolName);
end;
WriteBlockEndLn;
finally
LeaveContext;
LeaveScope;
end;
end;
// CompileHelperMethod
//
procedure TdwsJSCodeGen.CompileHelperMethod(meth : TMethodSymbol);
var
proc : TdwsProcedure;
begin
if not (meth.Executable is TdwsProcedure) then Exit;
proc:=(meth.Executable as TdwsProcedure);
if not SmartLink(meth) then Exit;
WriteSymbolVerbosity(meth);
WriteString('function ');
if not meth.IsClassMethod then begin
WriteSymbolName(meth.StructSymbol);
WriteString('$');
end;
WriteSymbolName(meth);
EnterScope(meth);
EnterContext(proc);
try
WriteString('(');
WriteFuncParams(meth);
WriteBlockBegin(') ');
CompileFuncBody(meth);
if meth.Kind=fkConstructor then begin
WriteString('return ');
WriteStringLn(SelfSymbolName);
end;
WriteBlockEndLn;
finally
LeaveContext;
LeaveScope;
end;
end;
// MemberName
//
function TdwsJSCodeGen.MemberName(sym : TSymbol; cls : TCompositeTypeSymbol) : String;
//var
// n : Integer;
// match : TSymbol;
begin
Result:=SymbolMappedName(sym, cgssGlobal);
// n:=0;
// cls:=cls.Parent;
// while cls<>nil do begin
// match:=cls.Members.FindSymbol(sym.Name, cvMagic);
// if match<>nil then begin
// if ( (sym.ClassType=match.ClassType)
// or ((sym.ClassType=TSourceMethodSymbol) and (match.ClassType=TMethodSymbol)))
// and (sym is TMethodSymbol)
// and (TMethodSymbol(sym).IsVirtual)
// and (TMethodSymbol(sym).VMTIndex=TMethodSymbol(match).VMTIndex) then begin
// // method override
// end else Inc(n);
// end;
// cls:=cls.Parent;
// end;
// Result:=SymbolMappedName(sym, False);
// if n>0 then
// Result:=Format('%s$%d', [Result, n]);
end;
// WriteCompiledOutput
//
procedure TdwsJSCodeGen.WriteCompiledOutput(dest : TWriteOnlyBlockStream; const prog : IdwsProgram);
var
buf : TWriteOnlyBlockStream;
begin
if cgoOptimizeForSize in Options then begin
buf:=TWriteOnlyBlockStream.Create;
try
inherited WriteCompiledOutput(buf, prog);
JavaScriptMinify(buf.ToString, dest);
finally
buf.Free;
end;
end else inherited WriteCompiledOutput(dest, prog);
end;
// All_RTL_JS
//
class function TdwsJSCodeGen.All_RTL_JS : String;
begin
Result:=All_RTL_JS;
end;
// IgnoreRTLDependencies
//
procedure TdwsJSCodeGen.IgnoreRTLDependencies;
begin
IgnoreJSRTLDependencies(Dependencies);
end;
// ------------------
// ------------------ TJSBlockInitExpr ------------------
// ------------------
// CodeGen
//
procedure TJSBlockInitExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
i : Integer;
blockInit : TBlockExprBase;
initExpr : TExprBase;
sym : TDataSymbol;
oldTable : TSymbolTable;
begin
blockInit:=TBlockExprBase(expr);
for i:=0 to blockInit.SubExprCount-1 do begin
initExpr:=blockInit.SubExpr[i];
if initExpr is TBlockExprBase then begin
oldTable:=codeGen.LocalTable;
if initExpr is TBlockExpr then
codeGen.LocalTable:=TBlockExpr(initExpr).Table;
try
Self.CodeGen(codeGen, initExpr);
finally
codeGen.LocalTable:=oldTable;
end;
end else begin
Assert(initExpr.SubExprCount>=1);
sym:=TJSVarExpr.CodeGenSymbol(codeGen, initExpr.SubExpr[0] as TVarExpr);
codeGen.WriteString('var ');
if initExpr is TInitDataExpr then begin
codeGen.WriteSymbolName(sym);
codeGen.WriteString(' = ');
TdwsJSCodeGen(codeGen).WriteDefaultValue(sym.Typ, IsLocalVarParam(codeGen, sym));
codeGen.WriteStatementEnd;
end else begin
if IsLocalVarParam(codeGen, sym) then begin
codeGen.WriteSymbolName(sym);
codeGen.WriteString(' = {}');
codeGen.WriteStatementEnd;
end;
codeGen.Compile(initExpr);
end;
end;
end;
end;
// ------------------
// ------------------ TJSBlockExpr ------------------
// ------------------
// CodeGen
//
procedure TJSBlockExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
block : TBlockExpr;
begin
block:=TBlockExpr(expr);
codeGen.CompileSymbolTable(block.Table);
inherited;
end;
// ------------------
// ------------------ TJSBlockExprBase ------------------
// ------------------
// CodeGen
//
procedure TJSBlockExprBase.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
i : Integer;
block : TBlockExprNoTable;
begin
block:=TBlockExprNoTable(expr);
for i:=0 to block.SubExprCount-1 do begin
codeGen.Compile(block.SubExpr[i]);
end;
end;
// ------------------
// ------------------ TJSRAWBlockExpr ------------------
// ------------------
// CodeGen
//
procedure TJSRAWBlockExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TdwsJSBlockExpr;
i : Integer;
jsCode : String;
sym : TSymbol;
begin
e:=TdwsJSBlockExpr(expr);
jsCode:=e.Code;
for i:=e.SymbolsCount-1 downto 0 do begin
sym:=e.Symbols[i];
Insert(codeGen.SymbolMappedName(sym, cgssGlobal), jsCode, e.SymbolOffsets[i]);
end;
codeGen.WriteString(jsCode);
end;
// ------------------
// ------------------ TJSNoResultWrapperExpr ------------------
// ------------------
// CodeGen
//
procedure TJSNoResultWrapperExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TNoResultWrapperExpr;
begin
e:=TNoResultWrapperExpr(expr);
if e.Expr<>nil then
codeGen.CompileNoWrap(e.Expr);
codeGen.WriteStatementEnd;
end;
// ------------------
// ------------------ TJSVarExpr ------------------
// ------------------
// CodeGen
//
procedure TJSVarExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
sym : TDataSymbol;
begin
sym:=CodeGenName(codeGen, expr);
if IsLocalVarParam(codeGen, sym) then
codeGen.WriteString('.'+TdwsJSCodeGen.cBoxFieldName);
end;
// CodeGenName
//
class function TJSVarExpr.CodeGenName(codeGen : TdwsCodeGen; expr : TExprBase) : TDataSymbol;
begin
Result:=CodeGenSymbol(codeGen, expr);
codeGen.WriteSymbolName(Result);
end;
// CodeGenSymbol
//
class function TJSVarExpr.CodeGenSymbol(codeGen : TdwsCodeGen; expr : TExprBase) : TDataSymbol;
var
varExpr : TVarExpr;
begin
varExpr:=TVarExpr(expr);
Result:=varExpr.DataSym;
if Result=nil then
raise ECodeGenUnsupportedSymbol.CreateFmt('Var not found at StackAddr %d', [varExpr.StackAddr]);
end;
// ------------------
// ------------------ TJSVarParamExpr ------------------
// ------------------
// CodeGen
//
procedure TJSVarParamExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
begin
CodeGenName(codeGen, expr);
codeGen.WriteString('.'+TdwsJSCodeGen.cBoxFieldName);
end;
// ------------------
// ------------------ TJSLazyParamExpr ------------------
// ------------------
// CodeGen
//
procedure TJSLazyParamExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
sym : TDataSymbol;
begin
sym:=TLazyParamExpr(expr).DataSym;
codeGen.WriteSymbolName(sym);
if IsLocalVarParam(codeGen, sym) then
codeGen.WriteString('.'+TdwsJSCodeGen.cBoxFieldName);
codeGen.WriteString('()');
end;
// ------------------
// ------------------ TJSConstParamExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstParamExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
sym : TDataSymbol;
begin
sym:=CodeGenName(codeGen, expr);
if (sym.Typ.UnAliasedType is TRecordSymbol) or IsLocalVarParam(codeGen, sym) then
codeGen.WriteString('.'+TdwsJSCodeGen.cBoxFieldName);
end;
// ------------------
// ------------------ TJSAssignConstToIntegerVarExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignConstToIntegerVarExpr.CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase);
var
e : TAssignConstToIntegerVarExpr;
begin
e:=TAssignConstToIntegerVarExpr(expr);
CodeGenRight.WriteString(IntToStr(e.Right));
end;
// ------------------
// ------------------ TJSAssignConstToStringVarExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignConstToStringVarExpr.CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase);
var
e : TAssignConstToStringVarExpr;
begin
e:=TAssignConstToStringVarExpr(expr);
WriteJavaScriptString(CodeGenRight.Output, e.Right);
end;
// ------------------
// ------------------ TJSAssignConstToFloatVarExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignConstToFloatVarExpr.CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase);
var
e : TAssignConstToFloatVarExpr;
begin
e:=TAssignConstToFloatVarExpr(expr);
CodeGenRight.WriteString(FloatToStr(e.Right, cFormatSettings));
end;
// ------------------
// ------------------ TJSAssignConstToBoolVarExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignConstToBoolVarExpr.CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase);
var
e : TAssignConstToBoolVarExpr;
begin
e:=TAssignConstToBoolVarExpr(expr);
CodeGenRight.WriteString(cBoolToJSBool[e.Right]);
end;
// ------------------
// ------------------ TJSAssignNilToVarExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignNilToVarExpr.CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase);
begin
CodeGenRight.WriteString('null');
end;
// ------------------
// ------------------ TJSAssignConstDataToVarExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignConstDataToVarExpr.CodeGenRight(CodeGenRight : TdwsCodeGen; expr : TExprBase);
var
e : TAssignConstDataToVarExpr;
begin
e:=TAssignConstDataToVarExpr(expr);
CodeGenRight.CompileNoWrap(e.Right);
end;
// ------------------
// ------------------ TJSAppendConstStringVarExpr ------------------
// ------------------
// CodeGen
//
procedure TJSAppendConstStringVarExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAppendConstStringVarExpr;
begin
e:=TAppendConstStringVarExpr(expr);
codeGen.Compile(e.Left);
codeGen.WriteString('+=');
WriteJavaScriptString(codeGen.Output, e.AppendString);
codeGen.WriteStatementEnd;
end;
// ------------------
// ------------------ TJSConstExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConstExpr;
begin
e:=TConstExpr(expr);
TdwsJSCodeGen(codeGen).WriteValue(e.Typ, e.Data[nil], 0);
end;
// ------------------
// ------------------ TJSConstStringExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstStringExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConstStringExpr;
begin
e:=TConstStringExpr(expr);
WriteJavaScriptString(codeGen.Output, e.Value);
end;
// ------------------
// ------------------ TJSConstNumExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstNumExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConstExpr;
begin
e:=TConstExpr(expr);
if e.Eval(nil)<0 then begin
codeGen.WriteString('(');
CodeGenNoWrap(codeGen, e);
codeGen.WriteString(')');
end else CodeGenNoWrap(codeGen, e);
end;
// ------------------
// ------------------ TJSConstIntExpr ------------------
// ------------------
// CodeGenNoWrap
//
procedure TJSConstIntExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
var
e : TConstIntExpr;
begin
e:=TConstIntExpr(expr);
codeGen.WriteString(IntToStr(e.Value));
end;
// ------------------
// ------------------ TJSConstFloatExpr ------------------
// ------------------
// CodeGenNoWrap
//
procedure TJSConstFloatExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
var
e : TConstFloatExpr;
begin
e:=TConstFloatExpr(expr);
codeGen.WriteString(FloatToStr(e.Value, cFormatSettings));
end;
// ------------------
// ------------------ TJSConstBooleanExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstBooleanExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConstBooleanExpr;
begin
e:=TConstBooleanExpr(expr);
codeGen.WriteString(cBoolToJSBool[e.Value]);
end;
// ------------------
// ------------------ TJSArrayConstantExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayConstantExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayConstantExpr;
i : Integer;
begin
e:=TArrayConstantExpr(expr);
codeGen.WriteString('[');
for i:=0 to e.ElementCount-1 do begin
if i>0 then
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.Elements[i]);
end;
codeGen.WriteString(']');
end;
// ------------------
// ------------------ TJSResourceStringExpr ------------------
// ------------------
// CodeGen
//
procedure TJSResourceStringExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TResourceStringExpr;
begin
e:=TResourceStringExpr(expr);
codeGen.Dependencies.Add('$R');
codeGen.WriteString('$R[');
codeGen.WriteString(IntToStr(e.ResSymbol.Index));
codeGen.WriteString(']');
end;
// ------------------
// ------------------ TJSAssignExpr ------------------
// ------------------
// CodeGen
//
procedure TJSAssignExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAssignExpr;
begin
e:=TAssignExpr(expr);
codeGen.Compile(e.Left);
codeGen.WriteString('=');
CodeGenRight(codeGen, expr);
codeGen.WriteStatementEnd;
end;
// CodeGenRight
//
procedure TJSAssignExpr.CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAssignExpr;
begin
e:=TAssignExpr(expr);
codeGen.CompileNoWrap(e.Right);
end;
// ------------------
// ------------------ TJSAssignDataExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignDataExpr.CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAssignDataExpr;
begin
e:=TAssignDataExpr(expr);
codeGen.CompileValue(e.Right);
end;
// ------------------
// ------------------ TJSAssignClassOfExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignClassOfExpr.CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAssignClassOfExpr;
begin
// TODO: deep copy of records & static arrays
e:=TAssignClassOfExpr(expr);
codeGen.CompileNoWrap(e.Right);
if e.Right.Typ is TClassSymbol then
codeGen.WriteStringLn('.ClassType');
end;
// ------------------
// ------------------ TJSAssignFuncExpr ------------------
// ------------------
// CodeGenRight
//
procedure TJSAssignFuncExpr.CodeGenRight(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAssignFuncExpr;
funcExpr : TFuncExprBase;
begin
e:=TAssignFuncExpr(expr);
funcExpr:=(e.Right as TFuncExprBase);
TJSFuncRefExpr.DoCodeGen(codeGen, funcExpr);
end;
// ------------------
// ------------------ TJSFuncBaseExpr ------------------
// ------------------
// CodeGen
//
procedure TJSFuncBaseExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TFuncExprBase;
i : Integer;
funcSym : TFuncSymbol;
paramExpr : TTypedExpr;
paramSymbol : TParamSymbol;
readBack : TStringList;
begin
// TODO: handle deep copy of records, lazy params
e:=TFuncExprBase(expr);
funcSym:=e.FuncSym;
readBack:=TStringList.Create;
try
CodeGenFunctionName(codeGen, e, funcSym);
codeGen.WriteString('(');
CodeGenBeginParams(codeGen, e);
for i:=0 to e.Args.Count-1 do begin
if i>0 then
codeGen.WriteString(',');
paramExpr:=e.Args.ExprBase[i] as TTypedExpr;
paramSymbol:=funcSym.Params[i] as TParamSymbol;
if ShouldBoxParam(paramSymbol) then begin
if paramExpr is TVarExpr then
TJSVarExpr.CodeGenName(codeGen, TVarExpr(paramExpr))
else begin
codeGen.WriteString('{'+TdwsJSCodeGen.cBoxFieldName+':');
codeGen.Compile(paramExpr);
codeGen.WriteString('}');
end;
end else if paramSymbol is TLazyParamSymbol then begin
codeGen.WriteString('function () { return ');
codeGen.Compile(paramExpr);
codeGen.WriteString('}');
end else if paramSymbol is TByRefParamSymbol then begin
codeGen.Compile(paramExpr);
end else begin
codeGen.CompileValue(paramExpr);
end;
end;
codeGen.WriteString(')');
finally
readBack.Free;
end;
end;
// CodeGenFunctionName
//
procedure TJSFuncBaseExpr.CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol);
var
meth : TMethodSymbol;
begin
if funcSym is TMethodSymbol then begin
meth:=TMethodSymbol(funcSym);
if meth.IsStatic and not (meth.StructSymbol is TRecordSymbol) then begin
codeGen.WriteSymbolName(meth.StructSymbol);
codeGen.WriteString('.');
end;
codeGen.WriteString((codeGen as TdwsJSCodeGen).MemberName(funcSym, meth.StructSymbol))
end else codeGen.WriteSymbolName(funcSym);
if FVirtualCall then
codeGen.WriteString(TdwsJSCodeGen.cVirtualPostfix);
end;
// CodeGenBeginParams
//
procedure TJSFuncBaseExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
begin
// nothing here
end;
// ------------------
// ------------------ TJSRecordMethodExpr ------------------
// ------------------
// CodeGen
//
procedure TJSRecordMethodExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TRecordMethodExpr;
methSym : TMethodSymbol;
begin
e:=TRecordMethodExpr(expr);
methSym:=(e.FuncSym as TMethodSymbol);
if not methSym.IsClassMethod then begin
codeGen.WriteSymbolName(methSym.StructSymbol);
codeGen.WriteString('$');
end;
inherited;
end;
// ------------------
// ------------------ TJSHelperMethodExpr ------------------
// ------------------
// CodeGen
//
procedure TJSHelperMethodExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : THelperMethodExpr;
methSym : TMethodSymbol;
begin
e:=THelperMethodExpr(expr);
methSym:=(e.FuncSym as TMethodSymbol);
if not methSym.IsClassMethod then begin
codeGen.WriteSymbolName(methSym.StructSymbol);
codeGen.WriteString('$');
end;
inherited;
end;
// ------------------
// ------------------ TJSMethodStaticExpr ------------------
// ------------------
// CodeGen
//
procedure TJSMethodStaticExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TMethodStaticExpr;
begin
e:=TMethodStaticExpr(expr);
if e.MethSym.StructSymbol.IsExternal then begin
codeGen.Compile(e.BaseExpr);
end else begin
codeGen.Dependencies.Add('TObject');
codeGen.WriteSymbolName((e.FuncSym as TMethodSymbol).StructSymbol);
end;
codeGen.WriteString('.');
inherited;
end;
// CodeGenBeginParams
//
procedure TJSMethodStaticExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
var
e : TMethodStaticExpr;
begin
e:=TMethodStaticExpr(expr);
if not e.MethSym.StructSymbol.IsExternal then begin
codeGen.Compile(e.BaseExpr);
if e.FuncSym.Params.Count>0 then
codeGen.WriteString(',');
end;
end;
// ------------------
// ------------------ TJSMethodVirtualExpr ------------------
// ------------------
// CodeGen
//
procedure TJSMethodVirtualExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TMethodVirtualExpr;
begin
codeGen.Dependencies.Add('TObject');
e:=TMethodVirtualExpr(expr);
FVirtualCall:=True;
codeGen.WriteSymbolName(e.MethSym.RootParentMeth.StructSymbol);
codeGen.WriteString('.');
inherited;
end;
// CodeGenBeginParams
//
procedure TJSMethodVirtualExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
var
e : TMethodVirtualExpr;
begin
e:=TMethodVirtualExpr(expr);
if cgoNoCheckInstantiated in codeGen.Options then begin
codeGen.Compile(e.BaseExpr);
end else begin
codeGen.Dependencies.Add('$Check');
codeGen.WriteString('$Check(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
if e.FuncSym.Params.Count>0 then
codeGen.WriteString(',');
end;
// ------------------
// ------------------ TJSMethodInterfaceExpr ------------------
// ------------------
// CodeGenFunctionName
//
procedure TJSMethodInterfaceExpr.CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol);
var
e : TMethodInterfaceExpr;
begin
e:=TMethodInterfaceExpr(expr);
if cgoNoCheckInstantiated in codeGen.Options then begin
codeGen.Compile(e.BaseExpr);
end else begin
codeGen.Dependencies.Add('$CheckIntf');
codeGen.WriteString('$CheckIntf(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
codeGen.WriteString('[');
codeGen.WriteString(IntToStr(e.MethSym.VMTIndex));
codeGen.WriteString(']');
end;
// ------------------
// ------------------ TJSClassMethodStaticExpr ------------------
// ------------------
// CodeGen
//
procedure TJSClassMethodStaticExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TClassMethodStaticExpr;
begin
codeGen.Dependencies.Add('TObject');
e:=TClassMethodStaticExpr(expr);
codeGen.WriteSymbolName((e.FuncSym as TMethodSymbol).StructSymbol);
codeGen.WriteString('.');
inherited;
end;
// CodeGenBeginParams
//
procedure TJSClassMethodStaticExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
var
e : TClassMethodStaticExpr;
begin
e:=TClassMethodStaticExpr(expr);
if (cgoNoCheckInstantiated in codeGen.Options) or (e.BaseExpr is TConstExpr) then begin
codeGen.Compile(e.BaseExpr);
end else begin
codeGen.Dependencies.Add('$Check');
codeGen.WriteString('$Check(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
if e.BaseExpr.Typ is TClassSymbol then
codeGen.WriteString('.ClassType');
if e.FuncSym.Params.Count>0 then
codeGen.WriteString(',');
end;
// ------------------
// ------------------ TJSClassMethodVirtualExpr ------------------
// ------------------
// CodeGen
//
procedure TJSClassMethodVirtualExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TClassMethodVirtualExpr;
begin
codeGen.Dependencies.Add('TObject');
e:=TClassMethodVirtualExpr(expr);
FVirtualCall:=True;
codeGen.WriteSymbolName(e.MethSym.RootParentMeth.StructSymbol);
codeGen.WriteString('.');
inherited;
end;
// CodeGenBeginParams
//
procedure TJSClassMethodVirtualExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
var
e : TClassMethodVirtualExpr;
begin
e:=TClassMethodVirtualExpr(expr);
if cgoNoCheckInstantiated in codeGen.Options then begin
codeGen.Compile(e.BaseExpr);
end else begin
codeGen.Dependencies.Add('$Check');
codeGen.WriteString('$Check(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
if e.BaseExpr.Typ is TClassSymbol then
codeGen.WriteString('.ClassType');
if e.FuncSym.Params.Count>0 then
codeGen.WriteString(',');
end;
// ------------------
// ------------------ TJSConstructorStaticExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstructorStaticExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConstructorStaticExpr;
structSymbol : TCompositeTypeSymbol;
begin
e:=TConstructorStaticExpr(expr);
structSymbol:=(e.FuncSym as TMethodSymbol).StructSymbol;
if structSymbol.IsExternal then begin
codeGen.WriteString('new ');
codeGen.WriteString(structSymbol.ExternalName);
end else begin
codeGen.Dependencies.Add('TObject');
codeGen.WriteSymbolName(structSymbol);
codeGen.WriteString('.');
end;
inherited;
end;
// CodeGenFunctionName
//
procedure TJSConstructorStaticExpr.CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol);
var
e : TConstructorStaticExpr;
begin
e:=TConstructorStaticExpr(expr);
if not (e.FuncSym as TMethodSymbol).StructSymbol.IsExternal then
inherited;
end;
// CodeGenBeginParams
//
procedure TJSConstructorStaticExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
var
e : TConstructorStaticExpr;
begin
e:=TConstructorStaticExpr(expr);
if not (e.FuncSym as TMethodSymbol).StructSymbol.IsExternal then begin
if e.BaseExpr is TConstExpr then begin
codeGen.WriteString('$New(');
codeGen.Compile(e.BaseExpr);
end else begin
codeGen.Dependencies.Add('$NewDyn');
codeGen.WriteString('$NewDyn(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
end;
codeGen.WriteString(')');
if e.FuncSym.Params.Count>0 then
codeGen.WriteString(',');
end;
end;
// ------------------
// ------------------ TJSConstructorVirtualExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConstructorVirtualExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConstructorVirtualExpr;
begin
codeGen.Dependencies.Add('TObject');
e:=TConstructorVirtualExpr(expr);
FVirtualCall:=True;
codeGen.WriteSymbolName(e.MethSym.RootParentMeth.StructSymbol);
codeGen.WriteString('.');
inherited;
end;
// CodeGenBeginParams
//
procedure TJSConstructorVirtualExpr.CodeGenBeginParams(codeGen : TdwsCodeGen; expr : TFuncExprBase);
var
e : TConstructorVirtualExpr;
begin
e:=TConstructorVirtualExpr(expr);
if e.BaseExpr is TConstExpr then begin
codeGen.WriteString('$New(');
end else begin
codeGen.Dependencies.Add('$NewDyn');
codeGen.WriteString('$NewDyn(');
end;
codeGen.Compile(e.BaseExpr);
if e.BaseExpr.Typ is TClassSymbol then
codeGen.WriteString('.ClassType');
if not (e.BaseExpr is TConstExpr) then begin
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
end;
codeGen.WriteString(')');
if e.FuncSym.Params.Count>0 then
codeGen.WriteString(',');
end;
// ------------------
// ------------------ TJSConnectorCallExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConnectorCallExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConnectorCallExpr;
jsCall : TdwsJSConnectorCall;
isWrite : Boolean;
i, n : Integer;
begin
e:=TConnectorCallExpr(Expr);
jsCall:=(e.ConnectorCall as TdwsJSConnectorCall);
n:=e.SubExprCount-1;
isWrite:=False;
codeGen.Compile(e.BaseExpr);
if e.IsIndex then begin
if jsCall.CallMethodName<>'' then begin
codeGen.WriteString('.');
codeGen.WriteString(jsCall.CallMethodName);
end;
codeGen.WriteString('[');
isWrite:=(jsCall as TdwsJSIndexCall).IsWrite;
if isWrite then
Dec(n);
end else begin
codeGen.WriteString('.');
codeGen.WriteString(jsCall.CallMethodName);
codeGen.WriteString('(');
end;
for i:=1 to n do begin
if i>1 then
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.SubExpr[i] as TTypedExpr);
end;
if e.IsIndex then begin
codeGen.WriteString(']');
if isWrite then begin
codeGen.WriteString('=');
codeGen.CompileNoWrap(e.SubExpr[n+1] as TTypedExpr);
end;
end else codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSConnectorReadExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConnectorReadExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConnectorReadExpr;
jsMember : TdwsJSConnectorMember;
begin
e:=TConnectorReadExpr(Expr);
jsMember:=(e.ConnectorMember.GetSelf as TdwsJSConnectorMember);
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.');
codeGen.WriteString(jsMember.MemberName);
end;
// ------------------
// ------------------ TJSConnectorWriteExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConnectorWriteExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConnectorWriteExpr;
jsMember : TdwsJSConnectorMember;
begin
e:=TConnectorWriteExpr(Expr);
jsMember:=(e.ConnectorMember.GetSelf as TdwsJSConnectorMember);
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.');
codeGen.WriteString(jsMember.MemberName);
codeGen.WriteString('=');
codeGen.Compile(e.ValueExpr);
codegen.WriteStatementEnd;
end;
// ------------------
// ------------------ TJSFuncPtrExpr ------------------
// ------------------
// CodeGen
//
procedure TJSFuncPtrExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
begin
inherited;
end;
// CodeGenFunctionName
//
procedure TJSFuncPtrExpr.CodeGenFunctionName(codeGen : TdwsCodeGen; expr : TFuncExprBase; funcSym : TFuncSymbol);
var
e : TFuncPtrExpr;
begin
e:=TFuncPtrExpr(expr);
if cgoNoCheckInstantiated in codeGen.Options then begin
codeGen.Compile(e.CodeExpr);
end else begin
codeGen.Dependencies.Add('$CheckFunc');
codeGen.WriteString('$CheckFunc(');
codeGen.Compile(e.CodeExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSFuncRefExpr ------------------
// ------------------
// CodeGen
//
procedure TJSFuncRefExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TFuncRefExpr;
begin
e:=TFuncRefExpr(expr);
if e.FuncExpr is TFuncPtrExpr then
codeGen.Compile(TFuncPtrExpr(e.FuncExpr).CodeExpr)
else DoCodeGen(codeGen, e.FuncExpr);
end;
// DoCodeGen
//
class procedure TJSFuncRefExpr.DoCodeGen(codeGen : TdwsCodeGen; funcExpr : TFuncExprBase);
var
methExpr : TMethodExpr;
funcSym : TFuncSymbol;
methSym : TMethodSymbol;
eventFunc : String;
begin
if funcExpr is TMethodExpr then begin
methExpr:=TMethodExpr(funcExpr);
methSym:=TMethodSymbol(methExpr.funcSym);
case methSym.Params.Count of
0 : eventFunc:='$Event0';
1 : eventFunc:='$Event1';
2 : eventFunc:='$Event2';
3 : eventFunc:='$Event3';
else
eventFunc:='$Event';
end;
codeGen.Dependencies.Add(eventFunc);
codeGen.WriteString(eventFunc);
codeGen.WriteString('(');
codeGen.Compile(methExpr.BaseExpr);
if methExpr is TMethodVirtualExpr then begin
codeGen.WriteString(',');
codeGen.WriteSymbolName(methExpr.MethSym.RootParentMeth.StructSymbol);
codeGen.WriteString('.');
codeGen.WriteString((codeGen as TdwsJSCodeGen).MemberName(methSym, methSym.StructSymbol));
codeGen.WriteString(TdwsJSCodeGen.cVirtualPostfix);
end else if methExpr is TMethodInterfaceExpr then begin
codeGen.WriteString('.O,');
codeGen.Compile(methExpr.BaseExpr);
codeGen.WriteString('[');
codeGen.WriteString(IntToStr(methSym.VMTIndex));
codeGen.WriteString(']');
end else if methExpr is TMethodStaticExpr then begin
if methSym.IsClassMethod and (methExpr.BaseExpr.Typ.UnAliasedType is TClassSymbol) then
codeGen.WriteString('.ClassType');
codeGen.WriteString(',');
codeGen.WriteSymbolName(methSym.StructSymbol);
codeGen.WriteString('.');
codeGen.WriteString((codeGen as TdwsJSCodeGen).MemberName(methSym, methSym.StructSymbol))
end else begin
raise ECodeGenUnknownExpression.CreateFmt('Unsupported AssignFuncExpr for %s', [methExpr.ClassName]);
end;
codeGen.WriteString(')');
end else begin
funcSym:=funcExpr.FuncSym;
if funcSym is TMethodSymbol then begin
methSym:=TMethodSymbol(funcSym);
if not (methSym.StructSymbol is TRecordSymbol) then begin
codeGen.WriteSymbolName(methSym.StructSymbol);
codeGen.WriteString('.');
end;
end;
codeGen.WriteSymbolName(funcSym);
if funcExpr is TMagicFuncExpr then
codeGen.Dependencies.Add(funcSym.QualifiedName);
end;
end;
// ------------------
// ------------------ TJSAnonymousFuncRefExpr ------------------
// ------------------
// CodeGen
//
procedure TJSAnonymousFuncRefExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAnonymousFuncRefExpr;
begin
e:=TAnonymousFuncRefExpr(expr);
codeGen.CompileFuncSymbol(e.FuncExpr.FuncSym as TSourceFuncSymbol);
end;
// ------------------
// ------------------ TJSInOpExpr ------------------
// ------------------
// CodeGen
//
procedure TJSInOpExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TInOpExpr;
i : Integer;
cond : TCaseCondition;
wrapped : Boolean;
writeOperand : TProc;
begin
e:=TInOpExpr(expr);
if e.Count=0 then begin
codeGen.WriteString(cBoolToJSBool[false]);
Exit;
end;
wrapped:=not ((e.Left is TVarExpr) or (e.Left is TConstExpr) or (e.Left is TFieldExpr));
if wrapped then begin
codeGen.WriteString('{f:function(){var v$=');
codeGen.Compile(e.Left);
codeGen.WriteString(';return ');
writeOperand:=procedure begin codegen.WriteString('v$') end;
end else begin
writeOperand:=procedure begin codegen.Compile(e.Left) end;
end;
if e.Count>1 then
codeGen.WriteString('(');
for i:=0 to e.Count-1 do begin
if i>0 then
codeGen.WriteString('||');
cond:=e[i];
codeGen.WriteString('(');
TJSCaseExpr.CodeGenCondition(codeGen, cond, writeOperand);
codeGen.WriteString(')');
end;
if e.Count>1 then
codeGen.WriteString(')');
if wrapped then
codeGen.WriteString('}}.f()');
end;
// ------------------
// ------------------ TJSBitwiseInOpExpr ------------------
// ------------------
// CodeGenNoWrap
//
procedure TJSBitwiseInOpExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
var
e : TBitwiseInOpExpr;
begin
e:=TBitwiseInOpExpr(expr);
// JavaScript << has a higher precedence than &, which is lower than !=
codeGen.WriteString('(1<<');
codeGen.Compile(e.Expr);
codeGen.WriteString('&');
codeGen.WriteString(IntToStr(e.Mask));
codeGen.WriteString(')!=0');
end;
// ------------------
// ------------------ TJSIfThenExpr ------------------
// ------------------
// SubExprIsSafeStatement
//
function TJSIfThenExpr.SubExprIsSafeStatement(sub : TExprBase) : Boolean;
begin
Result:= (sub is TFuncExprBase)
or (sub is TNoResultWrapperExpr)
or (sub is TAssignExpr)
or (sub is TFlowControlExpr);
end;
// CodeGen
//
procedure TJSIfThenExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TIfThenExpr;
begin
e:=TIfThenExpr(expr);
codeGen.WriteString('if (');
codeGen.CompileNoWrap(e.CondExpr);
codeGen.WriteString(') ');
if (cgoOptimizeForSize in codeGen.Options) and SubExprIsSafeStatement(e.ThenExpr) then
codeGen.Compile(e.ThenExpr)
else begin
codeGen.WriteBlockBegin('');
codeGen.Compile(e.ThenExpr);
codeGen.WriteBlockEndLn;
end;
end;
// ------------------
// ------------------ TJSIfThenElseExpr ------------------
// ------------------
// CodeGen
//
procedure TJSIfThenElseExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TIfThenElseExpr;
begin
e:=TIfThenElseExpr(expr);
codeGen.WriteString('if (');
codeGen.CompileNoWrap(e.CondExpr);
codeGen.WriteBlockBegin(') ');
codeGen.Compile(e.ThenExpr);
codeGen.WriteBlockEnd;
codeGen.WriteString(' else ');
if (cgoOptimizeForSize in codeGen.Options) and SubExprIsSafeStatement(e.ElseExpr) then begin
codeGen.Compile(e.ElseExpr);
end else begin
codeGen.WriteBlockBegin('');
codeGen.Compile(e.ElseExpr);
codeGen.WriteBlockEndLn;
end;
end;
// ------------------
// ------------------ TJSCaseExpr ------------------
// ------------------
// CodeGen
//
procedure TJSCaseExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
i, j : Integer;
e : TCaseExpr;
cond : TCaseCondition;
compCond, compCondOther : TCompareCaseCondition;
mark : array of Boolean;
tmp : String;
valType : TTypeSymbol;
switchable : Boolean;
begin
e:=TCaseExpr(expr);
valType:=e.ValueExpr.Typ.UnAliasedType;
switchable:= (valType is TBaseBooleanSymbol)
or (valType is TBaseIntegerSymbol)
or (valType is TBaseStringSymbol)
or (valType is TEnumerationSymbol);
for i:=0 to e.CaseConditions.Count-1 do begin
if not switchable then break;
cond:=TCaseCondition(e.CaseConditions.List[i]);
switchable:= (cond is TCompareCaseCondition)
and (TCompareCaseCondition(cond).CompareExpr is TConstExpr);
end;
if switchable then begin
SetLength(mark, e.CaseConditions.Count);
codeGen.WriteString('switch (');
codeGen.Compile(e.ValueExpr);
codeGen.WriteBlockBegin(') ');
for i:=0 to e.CaseConditions.Count-1 do begin
if mark[i] then continue;
compCond:=TCompareCaseCondition(e.CaseConditions.List[i]);
for j:=i to e.CaseConditions.Count-1 do begin
compCondOther:=TCompareCaseCondition(e.CaseConditions.List[j]);
if compCond.TrueExpr=compCondOther.TrueExpr then begin
if j>i then
codeGen.WriteLineEnd;
codeGen.WriteString('case ');
codeGen.Compile(compCondOther.CompareExpr);
codeGen.WriteStringLn(' :');
mark[j]:=True;
end;
end;
codeGen.Indent;
codeGen.Compile(compCond.TrueExpr);
codeGen.WriteStringLn('break;');
codeGen.UnIndent;
end;
if e.ElseExpr<>nil then begin
codeGen.WriteStringLn('default :');
codeGen.Indent;
codeGen.Compile(e.ElseExpr);
codeGen.UnIndent;
end;
codeGen.WriteBlockEndLn;
end else begin
tmp:=codeGen.GetNewTempSymbol;
codeGen.WriteString('{var ');
codeGen.WriteString(tmp);
codeGen.WriteString('=');
codeGen.Compile(e.ValueExpr);
codeGen.WriteStatementEnd;
codeGen.Indent;
for i:=0 to e.CaseConditions.Count-1 do begin
if i>0 then
codeGen.WriteString(' else ');
codeGen.WriteString('if (');
cond:=TCaseCondition(e.CaseConditions.List[i]);
CodeGenCondition(codeGen, cond, procedure begin codeGen.WriteString(tmp) end);
codeGen.WriteBlockBegin(') ');
codeGen.Compile(cond.TrueExpr);
codeGen.WriteBlockEndLn;
end;
if e.ElseExpr<>nil then begin
codeGen.WriteBlockBegin(' else ');
codeGen.Compile(e.ElseExpr);
codeGen.WriteBlockEndLn;
end;
codeGen.WriteBlockEndLn;
end;
end;
// CodeGenCondition
//
class procedure TJSCaseExpr.CodeGenCondition(codeGen : TdwsCodeGen; cond : TCaseCondition;
const writeOperand : TProc);
begin
if cond is TCompareCaseCondition then begin
writeOperand();
codeGen.WriteString('==');
codeGen.Compile(TCompareCaseCondition(cond).CompareExpr);
end else if cond is TRangeCaseCondition then begin
codeGen.WriteString('(');
writeOperand();
codeGen.WriteString('>=');
codeGen.Compile(TRangeCaseCondition(cond).FromExpr);
codeGen.WriteString(')&&(');
writeOperand();
codeGen.WriteString('<=');
codeGen.Compile(TRangeCaseCondition(cond).ToExpr);
codeGen.WriteString(')');
end else raise ECodeGenUnknownExpression.Create(cond.ClassName);
end;
// ------------------
// ------------------ TJSExitExpr ------------------
// ------------------
// CodeGen
//
procedure TJSExitExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
func : TFuncSymbol;
begin
if codeGen.Context is TdwsProcedure then
func:=TdwsProcedure(codeGen.Context).Func
else func:=nil;
if (func<>nil) and (func.Typ<>nil) then begin
codeGen.WriteString('return ');
codeGen.WriteString(TdwsJSCodeGen(codeGen).ResultSymbolName);
if IsLocalVarParam(codeGen, func.Result) then
codeGen.WriteString('.'+TdwsJSCodeGen.cBoxFieldName);
end else codeGen.WriteString('return');
codeGen.WriteStatementEnd;
end;
// ------------------
// ------------------ TJSExitValueExpr ------------------
// ------------------
// CodeGen
//
procedure TJSExitValueExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TExitValueExpr;
begin
e:=TExitValueExpr(expr);
codeGen.WriteString('return ');
codeGen.Compile(e.AssignExpr);
end;
// ------------------
// ------------------ TJSIncDecVarFuncExpr ------------------
// ------------------
// DoCodeGen
//
procedure TJSIncDecVarFuncExpr.DoCodeGen(codeGen : TdwsCodeGen; expr : TMagicFuncExpr;
op : Char; noWrap : Boolean);
var
e : TIncVarFuncExpr;
left, right : TExprBase;
begin
e:=TIncVarFuncExpr(expr);
left:=e.Args[0];
right:=e.Args[1];
if ExprIsConstantInteger(right, 1) then begin
codeGen.WriteString(op);
codeGen.WriteString(op);
codeGen.Compile(left);
end else begin
if not noWrap then
codeGen.WriteString('(');
codeGen.Compile(left);
codeGen.WriteString(op);
codeGen.WriteString('=');
codeGen.Compile(right);
if not noWrap then
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSIncVarFuncExpr ------------------
// ------------------
// CodeGen
//
procedure TJSIncVarFuncExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
begin
DoCodeGen(codeGen, TIncVarFuncExpr(expr), '+', False);
end;
// CodeGenNoWrap
//
procedure TJSIncVarFuncExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
begin
DoCodeGen(codeGen, TIncVarFuncExpr(expr), '+', True);
end;
// ------------------
// ------------------ TJSDecVarFuncExpr ------------------
// ------------------
// CodeGen
//
procedure TJSDecVarFuncExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
begin
DoCodeGen(codeGen, TIncVarFuncExpr(expr), '-', False);
end;
// CodeGenNoWrap
//
procedure TJSDecVarFuncExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
begin
DoCodeGen(codeGen, TIncVarFuncExpr(expr), '-', True);
end;
// ------------------
// ------------------ TJSSarExpr ------------------
// ------------------
// CodeGen
//
procedure TJSSarExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TSarExpr;
d : Int64;
begin
e:=TSarExpr(expr);
codeGen.WriteString('(');
if e.Right is TConstIntExpr then begin
d:=e.Right.EvalAsInteger(nil);
if d=0 then
codeGen.CompileNoWrap(e.Left)
else begin
codeGen.Compile(e.Left);
if d>31 then
codeGen.WriteString('<0?-1:0')
else begin
codeGen.WriteString('>>');
codeGen.Compile(e.Right);
end;
end;
end else begin
codeGen.Compile(e.Left);
codeGen.WriteString('>>');
codeGen.Compile(e.Right);
end;
codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSConvIntegerExpr ------------------
// ------------------
// CodeGen
//
procedure TJSConvIntegerExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TConvIntegerExpr;
begin
e:=TConvIntegerExpr(expr);
if e.Expr.Typ.UnAliasedType is TBaseBooleanSymbol then begin
codeGen.WriteString('(');
codeGen.Compile(e.Expr);
codeGen.WriteString('?1:0)');
end else codeGen.Compile(e.Expr);
end;
// ------------------
// ------------------ TJSConvFloatExpr ------------------
// ------------------
// CodeGenNoWrap
//
procedure TJSConvFloatExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
var
e : TConvIntegerExpr;
begin
e:=TConvIntegerExpr(expr);
if e.Expr.Typ.UnAliasedType is TBaseIntegerSymbol then
codeGen.CompileNoWrap(e.Expr)
else begin
codeGen.WriteString('Number(');
codeGen.CompileNoWrap(e.Expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSOrdExpr ------------------
// ------------------
// CodeGen
//
procedure TJSOrdExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TOrdExpr;
typ : TTypeSymbol;
begin
e:=TOrdExpr(expr);
typ:=e.Expr.Typ.UnAliasedType;
if typ is TBaseIntegerSymbol then
codeGen.Compile(e.Expr)
else begin
codeGen.Dependencies.Add('$Ord');
codeGen.WriteString('$Ord(');
codeGen.Compile(e.Expr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSClassAsClassExpr ------------------
// ------------------
// CodeGen
//
procedure TJSClassAsClassExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TClassAsClassExpr;
begin
codeGen.Dependencies.Add('$AsClass');
e:=TClassAsClassExpr(expr);
codeGen.WriteString('$AsClass(');
codeGen.Compile(e.Expr);
codeGen.WriteString(',');
codeGen.WriteSymbolName(TClassOfSymbol(e.Typ).TypClassSymbol.UnAliasedType);
codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSObjAsClassExpr ------------------
// ------------------
// CodeGen
//
procedure TJSObjAsClassExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TObjAsClassExpr;
begin
e:=TObjAsClassExpr(expr);
if e.Expr.Typ.IsOfType(e.Typ) then begin
codeGen.Compile(e.Expr);
end else begin
codeGen.Dependencies.Add('$As');
codeGen.WriteString('$As(');
codeGen.Compile(e.Expr);
codeGen.WriteString(',');
codeGen.WriteSymbolName(e.Typ.UnAliasedType);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSIsOpExpr ------------------
// ------------------
// CodeGen
//
procedure TJSIsOpExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TIsOpExpr;
begin
codeGen.Dependencies.Add('$Is');
e:=TIsOpExpr(expr);
codeGen.WriteString('$Is(');
codeGen.Compile(e.Left);
codeGen.WriteString(',');
codeGen.WriteSymbolName(e.Right.Typ.UnAliasedType.Typ);
codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSObjAsIntfExpr ------------------
// ------------------
// CodeGen
//
procedure TJSObjAsIntfExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TObjAsIntfExpr;
begin
codeGen.Dependencies.Add('$AsIntf');
e:=TObjAsIntfExpr(expr);
codeGen.WriteString('$AsIntf(');
codeGen.Compile(e.Expr);
codeGen.WriteString(',"');
codeGen.WriteSymbolName(e.Typ.UnAliasedType);
codeGen.WriteString('")');
end;
// ------------------
// ------------------ TJSObjToClassTypeExpr ------------------
// ------------------
// CodeGen
//
procedure TJSObjToClassTypeExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TObjToClassTypeExpr;
begin
e:=TObjToClassTypeExpr(expr);
codeGen.Dependencies.Add('$ToClassType');
codeGen.WriteString('$ToClassType(');
codeGen.Compile(e.Expr);
codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSIntfAsClassExpr ------------------
// ------------------
// CodeGen
//
procedure TJSIntfAsClassExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TIntfAsClassExpr;
begin
codeGen.Dependencies.Add('$IntfAsClass');
e:=TIntfAsClassExpr(expr);
codeGen.WriteString('$IntfAsClass(');
codeGen.Compile(e.Expr);
codeGen.WriteString(',');
codeGen.WriteSymbolName(e.Typ.UnAliasedType);
codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSIntfAsIntfExpr ------------------
// ------------------
// CodeGen
//
procedure TJSIntfAsIntfExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TIntfAsIntfExpr;
begin
codeGen.Dependencies.Add('$AsIntf');
codeGen.Dependencies.Add('$IntfAsClass');
e:=TIntfAsIntfExpr(expr);
codeGen.WriteString('$AsIntf($IntfAsClass(');
codeGen.Compile(e.Expr);
codeGen.WriteString(',TObject),"');
codeGen.WriteSymbolName(e.Typ.UnAliasedType);
codeGen.WriteString('")');
end;
// ------------------
// ------------------ TJSTImplementsIntfOpExpr ------------------
// ------------------
// CodeGen
//
procedure TJSTImplementsIntfOpExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TImplementsIntfOpExpr;
begin
codeGen.Dependencies.Add('$Implements');
e:=TImplementsIntfOpExpr(expr);
codeGen.WriteString('$Implements(');
codeGen.Compile(e.Left);
codeGen.WriteString(',"');
codeGen.WriteSymbolName(e.Right.Typ);
codeGen.WriteString('")');
end;
// ------------------
// ------------------ TJSTClassImplementsIntfOpExpr ------------------
// ------------------
// CodeGen
//
procedure TJSTClassImplementsIntfOpExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TClassImplementsIntfOpExpr;
begin
codeGen.Dependencies.Add('$ClassImplements');
e:=TClassImplementsIntfOpExpr(expr);
codeGen.WriteString('$ClassImplements(');
codeGen.Compile(e.Left);
codeGen.WriteString(',"');
codeGen.WriteSymbolName(e.Right.Typ);
codeGen.WriteString('")');
end;
// ------------------
// ------------------ TDataSymbolList ------------------
// ------------------
// Destroy
//
destructor TDataSymbolList.Destroy;
begin
ExtractAll;
inherited;
end;
// ------------------
// ------------------ TJSExprCodeGen ------------------
// ------------------
// IsLocalVarParam
//
class function TJSExprCodeGen.IsLocalVarParam(codeGen : TdwsCodeGen; sym : TDataSymbol) : Boolean;
//var
// i : Integer;
begin
// Result:=(TdwsJSCodeGen(codeGen).FLocalVarParams.IndexOf(sym)>=0);
Result:=(TdwsJSCodeGen(codeGen).FAllLocalVarSymbols.Contains(sym));
// if Result then Exit;
// for i:=0 to TdwsJSCodeGen(codeGen).FLocalVarParamsStack.Count-1 do begin
// Result:=(TdwsJSCodeGen(codeGen).FLocalVarParamsStack.Items[i].IndexOf(sym)>=0);
// if Result then Exit;
// end;
end;
// WriteLocationString
//
class procedure TJSExprCodeGen.WriteLocationString(codeGen : TdwsCodeGen; expr : TExprBase);
begin
if cgoNoSourceLocations in codeGen.Options then
codeGen.WriteString('""')
else WriteJavaScriptString(codeGen.Output, codeGen.LocationString(expr));
end;
// ------------------
// ------------------ TJSRecordExpr ------------------
// ------------------
// CodeGen
//
procedure TJSRecordExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TRecordExpr;
member : TFieldSymbol;
begin
e:=TRecordExpr(expr);
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.');
member:=(e.BaseExpr.Typ.UnAliasedType as TRecordSymbol).FieldAtOffset(e.MemberOffset);
codeGen.WriteSymbolName(member);
end;
// ------------------
// ------------------ TJSFieldExpr ------------------
// ------------------
// CodeGen
//
procedure TJSFieldExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TFieldExpr;
field : TFieldSymbol;
begin
e:=TFieldExpr(expr);
if cgoNoCheckInstantiated in codeGen.Options then begin
codeGen.Compile(e.ObjectExpr);
end else begin
codeGen.Dependencies.Add('$Check');
codeGen.WriteString('$Check(');
codeGen.Compile(e.ObjectExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
codeGen.WriteString('.');
field:=(e.ObjectExpr.Typ as TClassSymbol).FieldAtOffset(e.FieldAddr);
codeGen.WriteString((codeGen as TdwsJSCodeGen).MemberName(field, field.StructSymbol));
end;
// ------------------
// ------------------ TJSExceptExpr ------------------
// ------------------
// CodeGen
//
procedure TJSExceptExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TExceptExpr;
de : TExceptDoExpr;
i : Integer;
begin
codeGen.Dependencies.Add('$Is');
codeGen.Dependencies.Add('Exception');
e:=TExceptExpr(expr);
codeGen.WriteBlockBegin('try ');
codeGen.Compile(e.TryExpr);
codeGen.WriteBlockEnd;
codeGen.WriteBlockBegin(' catch ($e) ');
if e.DoExprCount=0 then
codeGen.Compile(e.HandlerExpr)
else begin
codeGen.Dependencies.Add('$W');
if (e.DoExprCount=1) and (e.DoExpr[0].ExceptionVar.Typ.UnAliasedType=codeGen.Context.TypException) then begin
// special case with only "on E: Exception"
de:=e.DoExpr[0];
codeGen.LocalTable.AddSymbolDirect(de.ExceptionVar);
try
codeGen.WriteString('var ');
codeGen.WriteSymbolName(de.ExceptionVar);
codeGen.WriteStringLn('=$W($e);');
codeGen.Compile(de.DoBlockExpr);
finally
codeGen.LocalTable.Remove(de.ExceptionVar);
end;
end else begin
// normal case, multiple exception or filtered exceptions
for i:=0 to e.DoExprCount-1 do begin
de:=e.DoExpr[i];
if i>0 then
codeGen.WriteString('else ');
codeGen.WriteString('if ($Is($e,');
codeGen.WriteSymbolName(de.ExceptionVar.Typ.UnAliasedType);
codeGen.WriteBlockBegin(')) ');
codeGen.LocalTable.AddSymbolDirect(de.ExceptionVar);
try
codeGen.WriteString('var ');
codeGen.WriteSymbolName(de.ExceptionVar);
codeGen.WriteStringLn('=$W($e);');
codeGen.Compile(de.DoBlockExpr);
finally
codeGen.LocalTable.Remove(de.ExceptionVar);
end;
codeGen.WriteBlockEndLn;
end;
if e.ElseExpr<>nil then begin
codeGen.WriteBlockBegin('else ');
codeGen.Compile(e.ElseExpr);
codeGen.WriteBlockEndLn;
end else codeGen.WriteStringLn('else throw $e');
end;
end;
codeGen.WriteBlockEndLn;
end;
// ------------------
// ------------------ TJSNewArrayExpr ------------------
// ------------------
// CodeGen
//
procedure TJSNewArrayExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TNewArrayExpr;
i : Integer;
begin
e:=TNewArrayExpr(expr);
if e.LengthExprCount>1 then begin
codeGen.Dependencies.Add('$NewArrayFn');
for i:=0 to e.LengthExprCount-2 do begin
codeGen.WriteString('$NewArrayFn(');
codeGen.Compile(e.LengthExpr[i]);
codeGen.WriteString(',function (){return ');
end;
end;
if e.Typ.Typ.IsBaseType then begin
codeGen.Dependencies.Add('$NewArray');
codeGen.WriteString('$NewArray(');
codeGen.Compile(e.LengthExpr[e.LengthExprCount-1]);
codeGen.WriteString(',');
(codeGen as TdwsJSCodeGen).WriteDefaultValue(e.Typ.Typ, False);
codeGen.WriteString(')');
end else begin
codeGen.Dependencies.Add('$NewArrayFn');
codeGen.WriteString('$NewArrayFn(');
codeGen.Compile(e.LengthExpr[e.LengthExprCount-1]);
codeGen.WriteString(',function (){return ');
(codeGen as TdwsJSCodeGen).WriteDefaultValue(e.Typ.Typ, False);
codeGen.WriteString('})');
end;
for i:=0 to e.LengthExprCount-2 do
codeGen.WriteString('})');
end;
// ------------------
// ------------------ TJSArrayLengthExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayLengthExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayLengthExpr;
begin
e:=TArrayLengthExpr(expr);
if e.Delta<>0 then
codeGen.WriteString('(');
codeGen.Compile(e.Expr);
codeGen.WriteString('.length');
if e.Delta<>0 then begin
if e.Delta>0 then
codeGen.WriteString('+');
codeGen.WriteString(IntToStr(e.Delta));
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSArraySetLengthExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArraySetLengthExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArraySetLengthExpr;
begin
e:=TArraySetLengthExpr(expr);
if ExprIsConstantInteger(e.LengthExpr, 0) then begin
codeGen.Compile(e.BaseExpr);
codeGen.WriteStringLn('.length=0;');
end else begin
codeGen.Dependencies.Add('$ArraySetLength');
codeGen.WriteString('$ArraySetLength(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
codeGen.Compile(e.LengthExpr);
codeGen.WriteString(',function (){return ');
(codeGen as TdwsJSCodeGen).WriteDefaultValue(e.BaseExpr.Typ.Typ, False);
codeGen.WriteStringLn('});');
end;
end;
// ------------------
// ------------------ TJSArrayAddExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayAddExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayAddExpr;
arg : TDataExpr;
i : Integer;
elementTyp : TTypeSymbol;
pushType : Integer;
inPushElems : Boolean;
begin
e:=TArrayAddExpr(expr);
codeGen.Compile(e.BaseExpr);
elementTyp:=(e.BaseExpr.Typ as TDynamicArraySymbol).Typ;
pushType:=0;
for i:=0 to e.ArgCount-1 do begin
arg:=e.ArgExpr[i];
if elementTyp.IsCompatible(arg.Typ) then
pushType:=pushType or 1
else pushType:=pushType or 2;
end;
if pushType=1 then begin
// only elements
codeGen.WriteString('.push(');
for i:=0 to e.ArgCount-1 do begin
if i>0 then
codeGen.WriteString(', ');
codeGen.CompileValue(e.ArgExpr[i]);
end;
codeGen.WriteString(')');
end else begin
// a mix of elements and arrays
codeGen.Dependencies.Add('$Pusha');
inPushElems:=False;
for i:=0 to e.ArgCount-1 do begin
arg:=e.ArgExpr[i];
if elementTyp.IsCompatible(arg.Typ) then begin
if not inPushElems then begin
codeGen.WriteString('.pusha([');
inPushElems:=True;
end else codeGen.WriteString(', ');
codeGen.CompileValue(arg);
end else begin
if inPushElems then begin
codeGen.WriteString('])');
inPushElems:=False;
end;
codeGen.WriteString('.pusha(');
codeGen.CompileValue(arg);
codeGen.WriteString(')');
end;
end;
if inPushElems then
codeGen.WriteString('])');
end;
codeGen.WriteStatementEnd;
end;
// ------------------
// ------------------ TJSArrayPeekExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayPeekExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayPeekExpr;
begin
e:=TArrayPeekExpr(expr);
codeGen.Dependencies.Add('$Peek');
codeGen.WriteString('$Peek(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
// ------------------
// ------------------ TJSArrayPopExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayPopExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayPopExpr;
begin
e:=TArrayPopExpr(expr);
if cgoNoRangeChecks in codeGen.Options then begin
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.pop()');
end else begin
codeGen.Dependencies.Add('$Pop');
codeGen.WriteString('$Pop(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSArrayDeleteExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayDeleteExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayDeleteExpr;
begin
e:=TArrayDeleteExpr(expr);
codeGen.Compile(e.BaseExpr);
if ExprIsConstantInteger(e.IndexExpr, 0)
and ((e.CountExpr=nil) or ExprIsConstantInteger(e.CountExpr, 1)) then begin
// optimize to shift for Delete(0, 1)
codeGen.WriteString('.shift()');
end else begin
codeGen.WriteString('.splice(');
codeGen.Compile(e.IndexExpr);
codeGen.WriteString(',');
if e.CountExpr<>nil then
codeGen.Compile(e.CountExpr)
else codeGen.WriteString('1');
codeGen.WriteStringLn(')');
end;
codeGen.WriteStatementEnd;
end;
// ------------------
// ------------------ TJSArrayIndexOfExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayIndexOfExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayIndexOfExpr;
begin
e:=TArrayIndexOfExpr(expr);
if (e.ItemExpr.Typ is TRecordSymbol)
or (e.ItemExpr.Typ is TStaticArraySymbol) then begin
codeGen.Dependencies.Add('$IndexOfRecord');
codeGen.WriteString('$IndexOfRecord(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.ItemExpr);
codeGen.WriteString(',');
if e.FromIndexExpr<>nil then
codeGen.CompileNoWrap(e.FromIndexExpr)
else codeGen.WriteString('0');
codeGen.WriteString(')');
end else begin
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.indexOf(');
codeGen.CompileNoWrap(e.ItemExpr);
if e.FromIndexExpr<>nil then begin
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.FromIndexExpr);
end;
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSArrayInsertExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayInsertExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayInsertExpr;
noRangeCheck : Boolean;
begin
e:=TArrayInsertExpr(expr);
noRangeCheck:= (cgoNoRangeChecks in codeGen.Options)
or ExprIsConstantInteger(e.IndexExpr, 0);
if noRangeCheck then begin
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.splice(');
codeGen.Compile(e.IndexExpr);
codeGen.WriteString(',0,');
codeGen.CompileValue(e.ItemExpr);
codeGen.WriteStringLn(');');
end else begin
codeGen.Dependencies.Add('$ArrayInsert');
codeGen.WriteString('$ArrayInsert(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
codeGen.Compile(e.IndexExpr);
codeGen.WriteString(',');
codeGen.CompileValue(e.ItemExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteStringLn(');');
end;
end;
// ------------------
// ------------------ TJSArrayCopyExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArrayCopyExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArrayCopyExpr;
rangeCheckFunc : String;
noRangeCheck : Boolean;
begin
e:=TArrayCopyExpr(expr);
noRangeCheck:=(cgoNoRangeChecks in codeGen.Options) or (e.IndexExpr=nil);
if noRangeCheck then begin
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('.slice(');
if e.IndexExpr=nil then
codeGen.WriteString('0')
else begin
codeGen.Compile(e.IndexExpr);
if e.CountExpr<>nil then begin
codeGen.WriteString(',');
codeGen.Compile(e.CountExpr)
end;
end;
codeGen.WriteString(')');
end else begin
if e.CountExpr=nil then
rangeCheckFunc:='$ArrayCopy'
else rangeCheckFunc:='$ArrayCopyLen';
codeGen.Dependencies.Add(rangeCheckFunc);
codeGen.WriteString(rangeCheckFunc);
codeGen.WriteString('(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
codeGen.Compile(e.IndexExpr);
if e.CountExpr<>nil then begin
codeGen.WriteString(',');
codeGen.Compile(e.CountExpr);
end;
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSArraySwapExpr ------------------
// ------------------
// CodeGen
//
procedure TJSArraySwapExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TArraySwapExpr;
noRangeCheck : Boolean;
begin
e:=TArraySwapExpr(expr);
noRangeCheck:=(cgoNoRangeChecks in codeGen.Options);
if noRangeCheck then begin
codeGen.Dependencies.Add('$ArraySwap');
codeGen.WriteString('$ArraySwap(');
end else begin
codeGen.Dependencies.Add('$ArraySwapChk');
codeGen.WriteString('$ArraySwapChk(');
end;
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
codeGen.Compile(e.Index1Expr);
codeGen.WriteString(',');
codeGen.Compile(e.Index2Expr);
if not noRangeCheck then begin
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
end;
codeGen.WriteStringLn(');');
end;
// ------------------
// ------------------ TJSStaticArrayExpr ------------------
// ------------------
// CodeGen
//
procedure TJSStaticArrayExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TStaticArrayExpr;
noRangeCheck : Boolean;
typ : TStaticArraySymbol;
begin
e:=TStaticArrayExpr(expr);
noRangeCheck:=(cgoNoRangeChecks in codeGen.Options) or e.IndexExpr.IsConstant;
typ:=(e.BaseExpr.Typ as TStaticArraySymbol);
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('[');
if noRangeCheck then begin
if typ.LowBound=0 then
codeGen.CompileNoWrap(e.IndexExpr)
else begin
codeGen.WriteString('(');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(')-');
codeGen.WriteString(IntToStr(typ.LowBound));
end;
end else begin
codeGen.Dependencies.Add('$Idx');
codeGen.WriteString('$Idx(');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(',');
codeGen.WriteString(IntToStr(typ.LowBound));
codeGen.WriteString(',');
codeGen.WriteString(IntToStr(typ.HighBound));
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
codeGen.WriteString(']');
end;
// ------------------
// ------------------ TJSStaticArrayBoolExpr ------------------
// ------------------
// CodeGen
//
procedure TJSStaticArrayBoolExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TStaticArrayBoolExpr;
begin
e:=TStaticArrayBoolExpr(expr);
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('[');
codeGen.Compile(e.IndexExpr);
codeGen.WriteString('?1:0]');
end;
// ------------------
// ------------------ TJSDynamicArrayExpr ------------------
// ------------------
// CodeGen
//
procedure TJSDynamicArrayExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TDynamicArrayExpr;
noRangeCheck : Boolean;
begin
e:=TDynamicArrayExpr(expr);
noRangeCheck:=(cgoNoRangeChecks in codeGen.Options);
if noRangeCheck then begin
codeGen.Compile(e.BaseExpr);
codeGen.WriteString('[');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(']');
end else begin
codeGen.Dependencies.Add('$DIdxR');
codeGen.WriteString('$DIdxR(');
codeGen.Compile(e.BaseExpr);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSDynamicArraySetExpr ------------------
// ------------------
// CodeGen
//
procedure TJSDynamicArraySetExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TDynamicArraySetExpr;
noRangeCheck : Boolean;
begin
e:=TDynamicArraySetExpr(expr);
noRangeCheck:=(cgoNoRangeChecks in codeGen.Options);
if noRangeCheck then begin
codeGen.Compile(e.ArrayExpr);
codeGen.WriteString('[');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(']=');
codeGen.CompileNoWrap(e.ValueExpr);
codeGen.WriteStatementEnd;
end else begin
codeGen.Dependencies.Add('$DIdxW');
codeGen.WriteString('$DIdxW(');
codeGen.CompileNoWrap(e.ArrayExpr);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.ValueExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteStringLn(');');
end;
end;
// ------------------
// ------------------ TJSStringArrayOpExpr ------------------
// ------------------
// CodeGen
//
procedure TJSStringArrayOpExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TStringArrayOpExpr;
noRangeCheck : Boolean;
begin
e:=TStringArrayOpExpr(expr);
noRangeCheck:=(cgoNoRangeChecks in codeGen.Options);
if noRangeCheck then begin
codeGen.Compile(e.Left);
codeGen.WriteString('.charAt((');
codeGen.CompileNoWrap(e.Right);
codeGen.WriteString(')-1)');
end else begin
codeGen.Dependencies.Add('$SIdx');
codeGen.WriteString('$SIdx(');
codeGen.CompileNoWrap(e.Left);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.Right);
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteString(')');
end;
end;
// ------------------
// ------------------ TJSVarStringArraySetExpr ------------------
// ------------------
// CodeGen
//
procedure TJSVarStringArraySetExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TVarStringArraySetExpr;
begin
e:=TVarStringArraySetExpr(expr);
codeGen.Dependencies.Add('$StrSet');
codeGen.Compile(e.StringExpr);
codeGen.WriteString('=$StrSet(');
codeGen.CompileNoWrap(e.StringExpr);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.IndexExpr);
codeGen.WriteString(',');
codeGen.CompileNoWrap(e.ValueExpr);
if not (cgoNoRangeChecks in codeGen.Options) then begin
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
end;
codeGen.WriteStringLn(');');
end;
// ------------------
// ------------------ TJSAssertExpr ------------------
// ------------------
// CodeGen
//
procedure TJSAssertExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TAssertExpr;
begin
e:=TAssertExpr(expr);
codeGen.Dependencies.Add('$Assert');
codeGen.WriteString('$Assert(');
codeGen.CompileNoWrap(e.Cond);
codeGen.WriteString(',');
if e.Message<>nil then
codeGen.CompileNoWrap(e.Message)
else codeGen.WriteString('""');
codeGen.WriteString(',');
WriteLocationString(codeGen, expr);
codeGen.WriteStringLn(');');
end;
// ------------------
// ------------------ TJSForExpr ------------------
// ------------------
// CodeGen
//
procedure TJSForExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
tmpTo, tmpStep : String;
e : TForExpr;
nonIncludedEnd : Boolean;
begin
e:=TForExpr(expr);
codeGen.WriteString(Format('/*@%d*/',[e.ScriptPos.Line]));
// allocate temporary variables to hold bounds
// in Pascal bounds and step are evaluated before the loop is entered
if not e.ToExpr.IsConstant then begin
tmpTo:=codeGen.GetNewTempSymbol;
codeGen.WriteString('var ');
codeGen.WriteString(tmpTo);
codeGen.WriteStatementEnd;
end else tmpTo:='';
if (e is TForStepExpr) and not (TForStepExpr(e).StepExpr.IsConstant) then begin
tmpStep:=codeGen.GetNewTempSymbol;
codeGen.WriteString('var ');
codeGen.WriteString(tmpStep);
codeGen.WriteStatementEnd;
end else tmpStep:='';
// trigger special codegen in case of
// "for i := whatever to something-1 do"
nonIncludedEnd:= (e.ClassType=TForUpwardExpr)
and (tmpTo<>'')
and ( ((e.ToExpr is TArrayLengthExpr) and (TArrayLengthExpr(e.ToExpr).Delta=-1))
or ((e.ToExpr is TSubIntExpr) and ExprIsConstantInteger(TSubIntExpr(e.ToExpr).Right, 1))
);
codeGen.WriteString('for(');
// initialize loop variable
codeGen.Compile(e.VarExpr);
codeGen.WriteString('=');
codeGen.CompileNoWrap(e.FromExpr);
// initialize bound end variable
if tmpTo<>'' then begin
codeGen.WriteString(',');
codeGen.WriteString(tmpTo);
codeGen.WriteString('=');
if nonIncludedEnd then begin
if e.ToExpr is TArrayLengthExpr then begin
codeGen.Compile(TArrayLengthExpr(e.ToExpr).Expr);
codeGen.WriteString('.length');
end else begin
codeGen.Compile(TSubIntExpr(e.ToExpr).Left);
end;
end else codeGen.CompileNoWrap(e.ToExpr);
end;
// initialize step variable
if tmpStep<>'' then begin
codeGen.WriteString(',');
codeGen.WriteString(tmpStep);
if cgoNoCheckLoopStep in codeGen.Options then begin
codeGen.WriteString('=');
codeGen.CompileNoWrap(TForStepExpr(e).StepExpr);
end else begin
codeGen.Dependencies.Add('$CheckStep');
codeGen.WriteString('=$CheckStep(');
codeGen.CompileNoWrap(TForStepExpr(e).StepExpr);
codeGen.WriteString(',');
WriteLocationString(codeGen, e);
codeGen.WriteString(')');
end;
end;
codeGen.WriteString(';');
// comparison sub-expression
codeGen.Compile(e.VarExpr);
if nonIncludedEnd then
codeGen.WriteString('<')
else WriteCompare(codeGen);
if tmpTo<>'' then
codeGen.WriteString(tmpTo)
else codeGen.Compile(e.ToExpr);
codeGen.WriteString(';');
// step sub-expression
codeGen.Compile(e.VarExpr);
WriteStep(codeGen);
if tmpStep<>'' then
codeGen.WriteString(tmpStep)
else if e is TForStepExpr then begin
codeGen.Compile(TForStepExpr(e).StepExpr);
end;
// loop block
codeGen.WriteBlockBegin(') ');
codeGen.Compile(e.DoExpr);
codeGen.WriteBlockEndLn;
end;
// ------------------
// ------------------ TJSForUpwardExpr ------------------
// ------------------
// WriteCompare
//
procedure TJSForUpwardExpr.WriteCompare(codeGen : TdwsCodeGen);
begin
codeGen.WriteString('<=');
end;
// WriteStep
//
procedure TJSForUpwardExpr.WriteStep(codeGen : TdwsCodeGen);
begin
codeGen.WriteString('++');
end;
// ------------------
// ------------------ TJSForDownwardExpr ------------------
// ------------------
// WriteCompare
//
procedure TJSForDownwardExpr.WriteCompare(codeGen : TdwsCodeGen);
begin
codeGen.WriteString('>=');
end;
// WriteStep
//
procedure TJSForDownwardExpr.WriteStep(codeGen : TdwsCodeGen);
begin
codeGen.WriteString('--');
end;
// ------------------
// ------------------ TJSForUpwardStepExpr ------------------
// ------------------
// WriteStep
//
procedure TJSForUpwardStepExpr.WriteStep(codeGen : TdwsCodeGen);
begin
codeGen.WriteString('+=');
end;
// ------------------
// ------------------ TJSForDownwardStepExpr ------------------
// ------------------
// WriteStep
//
procedure TJSForDownwardStepExpr.WriteStep(codeGen : TdwsCodeGen);
begin
codeGen.WriteString('-=');
end;
// ------------------
// ------------------ TJSSqrExpr ------------------
// ------------------
// CodeGen
//
procedure TJSSqrExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
begin
if not (expr.SubExpr[0] is TVarExpr) then
inherited
else CodeGenNoWrap(codeGen, expr as TTypedExpr);
end;
// CodeGenNoWrap
//
procedure TJSSqrExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
begin
expr:=expr.SubExpr[0] as TTypedExpr;
if expr is TVarExpr then begin
codeGen.Compile(expr);
codeGen.WriteString('*');
codeGen.Compile(expr);
end else begin
codeGen.WriteString('Math.pow(');
codeGen.CompileNoWrap(expr);
codeGen.WriteString(',2)');
end;
end;
// ------------------
// ------------------ TJSOpExpr ------------------
// ------------------
// WriteWrappedIfNeeded
//
class procedure TJSOpExpr.WriteWrappedIfNeeded(codeGen : TdwsCodeGen; expr : TTypedExpr);
begin
if (expr is TDataExpr)
or (expr is TConstExpr) then begin
codeGen.CompileNoWrap(expr);
end else begin
codeGen.Compile(expr);
end;
end;
// ------------------
// ------------------ TJSBinOpExpr ------------------
// ------------------
// Create
//
constructor TJSBinOpExpr.Create(const op : String; associative : Boolean);
begin
inherited Create;
FOp:=op;
FAssociative:=associative;
end;
// CodeGen
//
procedure TJSBinOpExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
var
e : TBinaryOpExpr;
begin
e:=TBinaryOpExpr(expr);
if FAssociative and (e.Left.ClassType=e.ClassType) then
codeGen.CompileNoWrap(e.Left)
else WriteWrappedIfNeeded(codeGen, e.Left);
WriteOp(codeGen, e.Right);
if FAssociative and (e.Right.ClassType=e.ClassType) then
codeGen.CompileNoWrap(e.Right)
else WriteWrappedIfNeeded(codeGen, e.Right);
end;
// WriteOp
//
procedure TJSBinOpExpr.WriteOp(codeGen : TdwsCodeGen; rightExpr : TTypedExpr);
begin
codeGen.WriteString(FOp);
end;
// ------------------
// ------------------ TJSAddOpExpr ------------------
// ------------------
// Create
//
constructor TJSAddOpExpr.Create;
begin
inherited Create('+', True);
end;
// WriteOp
//
procedure TJSAddOpExpr.WriteOp(codeGen : TdwsCodeGen; rightExpr : TTypedExpr);
begin
if (rightExpr is TConstExpr) and (rightExpr.Eval(nil)<0) then begin
// right operand will write a minus
end else codeGen.WriteString(FOp);
end;
// ------------------
// ------------------ TJSSubOpExpr ------------------
// ------------------
// Create
//
constructor TJSSubOpExpr.Create;
begin
inherited Create('-', True);
end;
// CodeGenNoWrap
//
procedure TJSSubOpExpr.CodeGenNoWrap(codeGen : TdwsCodeGen; expr : TTypedExpr);
var
e : TBinaryOpExpr;
begin
e:=TBinaryOpExpr(expr);
if (e.Left.ClassType=e.ClassType) then
codeGen.CompileNoWrap(e.Left)
else WriteWrappedIfNeeded(codeGen, e.Left);
WriteOp(codeGen, e.Right);
if (e.Right is TConstExpr) and (e.Right.Eval(nil)<0) then begin
codeGen.Compile(e.Right)
end else WriteWrappedIfNeeded(codeGen, e.Right);
end;
// ------------------
// ------------------ TJSDeclaredExpr ------------------
// ------------------
// CodeGen
//
procedure TJSDeclaredExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TDeclaredExpr;
name : String;
sym : TSymbol;
begin
e:=TDeclaredExpr(expr);
if not (e.Expr is TConstExpr) then
raise ECodeGenUnknownExpression.Create('Declared Expr with non-constant parameter');
e.Expr.EvalAsString(nil, name);
sym:=TDeclaredExpr.FindSymbol(codeGen.Context.Table, name);
codeGen.WriteString(cBoolToJSBool[sym<>nil]);
end;
// ------------------
// ------------------ TJSDefinedExpr ------------------
// ------------------
// CodeGen
//
procedure TJSDefinedExpr.CodeGen(codeGen : TdwsCodeGen; expr : TExprBase);
var
e : TDefinedExpr;
begin
e:=TDefinedExpr(expr);
codeGen.Dependencies.Add('$ConditionalDefines');
codeGen.WriteString('($ConditionalDefines.indexOf(');
codeGen.CompileNoWrap(e.Expr);
codeGen.WriteString(')!=-1)');
end;
// ------------------
// ------------------ TdwsCodeGenSymbolMapJSObfuscating ------------------
// ------------------
// DoNeedUniqueName
//
function TdwsCodeGenSymbolMapJSObfuscating.DoNeedUniqueName(symbol : TSymbol; tryCount : Integer; canObfuscate : Boolean) : String;
function IntToSkewedBase62(i : Cardinal) : String;
var
m : Cardinal;
begin
m:=i mod 52;
i:=i div 52;
if m<26 then
Result:=Char(Ord('A')+m)
else Result:=Char(Ord('a')+m-26);
while i>0 do begin
m:=i mod 62;
i:=i div 62;
case m of
0..9 : Result:=Result+Char(Ord('0')+m);
10..35 : Result:=Result+Char(Ord('A')+m-10);
else
Result:=Result+Char(Ord('a')+m-36);
end;
end;
end;
var
h : Integer;
begin
if not canObfuscate then
Exit(inherited DoNeedUniqueName(symbol, tryCount, canObfuscate));
h:=Random(MaxInt);
case tryCount of
0..4 : h:=h mod 52;
5..15 : h:=h mod (52*62);
16..30 : h:=h mod (52*62*62);
else
h:=h and $7FFFF;
end;
Result:=Prefix+IntToSkewedBase62(h);
end;
end.
|
unit NewsFileUtils_TLB;
{ This file contains pascal declarations imported from a type library.
This file will be written during each import or refresh of the type
library editor. Changes to this file will be discarded during the
refresh process. }
{ NewsFileUtils Library }
{ Version 1.0 }
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
const
LIBID_NewsFileUtils: TGUID = '{36349ED0-AF75-11D2-9764-008029EC1811}';
const
{ Component class GUIDs }
Class_FolderIterator: TGUID = '{36349ED2-AF75-11D2-9764-008029EC1811}';
Class_Tools: TGUID = '{EFE5D5F6-B332-11D2-976F-008029EC1811}';
type
{ Forward declarations: Interfaces }
IFolderIterator = interface;
IFolderIteratorDisp = dispinterface;
ITools = interface;
IToolsDisp = dispinterface;
{ Forward declarations: CoClasses }
FolderIterator = IFolderIterator;
Tools = ITools;
{ Dispatch interface for FolderIterator Object }
IFolderIterator = interface(IDispatch)
['{36349ED1-AF75-11D2-9764-008029EC1811}']
function FindFirst(const path: WideString): WideString; safecall;
function FindNext: WideString; safecall;
procedure FindClose; safecall;
function Get_LangId: WideString; safecall;
procedure Set_LangId(const Value: WideString); safecall;
property LangId: WideString read Get_LangId write Set_LangId;
end;
{ DispInterface declaration for Dual Interface IFolderIterator }
IFolderIteratorDisp = dispinterface
['{36349ED1-AF75-11D2-9764-008029EC1811}']
function FindFirst(const path: WideString): WideString; dispid 1;
function FindNext: WideString; dispid 2;
procedure FindClose; dispid 3;
property LangId: WideString dispid 4;
end;
{ Dispatch interface for Tools Object }
ITools = interface(IDispatch)
['{EFE5D5F5-B332-11D2-976F-008029EC1811}']
function EncodeNewsDate(const date: WideString): WideString; safecall;
function DecodeNewsDate(const date: WideString): WideString; safecall;
end;
{ DispInterface declaration for Dual Interface ITools }
IToolsDisp = dispinterface
['{EFE5D5F5-B332-11D2-976F-008029EC1811}']
function EncodeNewsDate(const date: WideString): WideString; dispid 1;
function DecodeNewsDate(const date: WideString): WideString; dispid 2;
end;
{ FolderIteratorObject }
CoFolderIterator = class
class function Create: IFolderIterator;
class function CreateRemote(const MachineName: string): IFolderIterator;
end;
{ ToolsObject }
CoTools = class
class function Create: ITools;
class function CreateRemote(const MachineName: string): ITools;
end;
implementation
uses ComObj;
class function CoFolderIterator.Create: IFolderIterator;
begin
Result := CreateComObject(Class_FolderIterator) as IFolderIterator;
end;
class function CoFolderIterator.CreateRemote(const MachineName: string): IFolderIterator;
begin
Result := CreateRemoteComObject(MachineName, Class_FolderIterator) as IFolderIterator;
end;
class function CoTools.Create: ITools;
begin
Result := CreateComObject(Class_Tools) as ITools;
end;
class function CoTools.CreateRemote(const MachineName: string): ITools;
begin
Result := CreateRemoteComObject(MachineName, Class_Tools) as ITools;
end;
end.
|
unit UJSON;
interface
uses
System.Generics.Collections, System.JSON.Serializers, UStudent, Winapi.Windows,
Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
MyMemo: TMemo;
btnMyDeSerier: TButton;
btnMySerier: TButton;
btnMy: TButton;
btnMy2: TButton;
procedure btnMyDeSerierClick(Sender: TObject);
procedure btnMySerierClick(Sender: TObject);
procedure btnMyClick(Sender: TObject);
procedure btnMy2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnMy2Click(Sender: TObject);
var
UserJson: string;
StuList: TList<TStudent>;
Serializer: TJsonSerializer;
StuJson: TStudent;
begin
UserJson := '{"FListHelper":{"FCount":2},"FItems":[{"FName":"萧蔷","FAge":30},{"FName":"陈怡彬","FAge":29}],"FComparer":{}}';
Serializer := TJsonSerializer.Create;
StuList := Serializer.Deserialize<TList<TStudent>>(UserJson);
for StuJson in StuList do
begin
MyMemo.Lines.Add('反序列化:' + StuJson.Name + ',' + StuJson.Age.ToString);
end;
end;
procedure TForm1.btnMyClick(Sender: TObject);
var
StuJson: TStudent;
StuList: TList<TStudent>;
Serializer: TJsonSerializer;
begin
StuList := TList<TStudent>.Create;
StuList.Add(TStudent.Create('萧蔷', 30));
StuList.Add(TStudent.Create('陈怡彬', 29));
Serializer := TJsonSerializer.Create();
//创建序列化对象
MyMemo.Lines.Add('序列化:' + Serializer.Serialize<TList<TStudent>>(StuList));
end;
procedure TForm1.btnMyDeSerierClick(Sender: TObject);
var
UserJson: string;
Serializer: TJsonSerializer;
StuJson: TStudent;
begin
{创建了一个字符串类型的JSON对象}
UserJson := '{"FName":"小黑","FAge":18}';
Serializer := TJsonSerializer.Create();
// 反序列化
StuJson := Serializer.Deserialize<TStudent>(UserJson);
MyMemo.Lines.Add('反序列化:' + StuJson.Name + ',' + StuJson.Age.ToString);
end;
procedure TForm1.btnMySerierClick(Sender: TObject);
var
UserJson: string;
Serializer: TJsonSerializer;
StuJson: TStudent;
begin
StuJson := TStudent.Create;
StuJson.Name := '小白';
StuJson.Age := 30;
Serializer := TJsonSerializer.Create;
//创建序列化对象
MyMemo.Lines.Add('序列化:' + Serializer.Serialize<TStudent>(StuJson));
end;
end.
|
unit NtUtils.Security.Sid;
interface
uses
Winapi.WinNt, Winapi.securitybaseapi, NtUtils.Exceptions;
type
TTranslatedName = record
DomainName, UserName: String;
SidType: TSidNameUse;
function FullName: String;
end;
ISid = interface
function Sid: PSid;
function SidLength: Cardinal;
function EqualsTo(Sid2: PSid): Boolean;
function RefreshLookup: TNtxStatus;
function ParentSid: ISid;
function ChildSid(Rid: Cardinal): ISid;
function SDDL: String;
function AsString: String;
function DomainName: String;
function UserName: String;
function SidType: TSidNameUse;
function IdentifyerAuthority: PSidIdentifierAuthority;
function Rid: Cardinal;
function SubAuthorities: Byte;
function SubAuthority(Index: Integer): Cardinal;
procedure SetSubAuthority(Index: Integer; NewValue: Cardinal);
end;
TSid = class(TInterfacedObject, ISid)
protected
FSid: PSid;
FLookupCached: Boolean;
FLookup: TTranslatedName;
constructor CreateOwned(OwnedSid: PSid; Dummy: Integer = 0);
procedure ValidateLookup;
public
constructor CreateCopy(SourceSid: PSid);
constructor CreateNew(const IdentifyerAuthority: TSidIdentifierAuthority;
SubAuthorities: Byte; SubAuthourity0: Cardinal = 0;
SubAuthourity1: Cardinal = 0; SubAuthourity2: Cardinal = 0;
SubAuthourity3: Cardinal = 0; SubAuthourity4: Cardinal = 0);
constructor CreateFromString(AccountOrSID: String); // May raise exceptions
destructor Destroy; override;
function Sid: PSid;
function SidLength: Cardinal;
function EqualsTo(Sid2: PSid): Boolean;
function RefreshLookup: TNtxStatus;
function ParentSid: ISid;
function ChildSid(Rid: Cardinal): ISid;
function SDDL: String;
function AsString: String;
function DomainName: String;
function UserName: String;
function SidType: TSidNameUse;
function IdentifyerAuthority: PSidIdentifierAuthority;
function Rid: Cardinal;
function SubAuthorities: Byte;
function SubAuthority(Index: Integer): Cardinal;
procedure SetSubAuthority(Index: Integer; NewValue: Cardinal);
end;
TGroup = record
SecurityIdentifier: ISid;
Attributes: Cardinal; // SE_GROUP_*
end;
function RtlxpApplySddlOverrides(SID: PSid; var SDDL: String): Boolean;
// Convert an SID to its SDDL representation
function RtlxConvertSidToString(SID: PSid): String;
// Convert SDDL string to SID
function RtlxConvertStringToSid(SDDL: String; out SID: PSid): TNtxStatus;
// Construct a well-known SID
function SddlxGetWellKnownSid(WellKnownSidType: TWellKnownSidType;
out Sid: ISid): TNtxStatus;
implementation
uses
Ntapi.ntdef, Ntapi.ntrtl, Ntapi.ntstatus, Winapi.WinBase, Winapi.Sddl,
NtUtils.Lsa, DelphiUtils.Strings, System.SysUtils;
{ TTranslatedName }
function TTranslatedName.FullName: String;
begin
if SidType = SidTypeDomain then
Result := DomainName
else if (UserName <> '') and (DomainName <> '') then
Result := DomainName + '\' + UserName
else if (UserName <> '') then
Result := UserName
else
Result := '';
end;
{ TSid }
function TSid.AsString: String;
begin
// Return most suitable name we have
ValidateLookup;
Result := FLookup.FullName;
if Result = '' then
Result := SDDL;
end;
function TSid.ChildSid(Rid: Cardinal): ISid;
var
Buffer: PSid;
Status: NTSTATUS;
i: Integer;
begin
Buffer := AllocMem(RtlLengthRequiredSid(SubAuthorities + 1));
// Copy identifier authority
Status := RtlInitializeSid(Buffer, RtlIdentifierAuthoritySid(FSid),
SubAuthorities + 1);
if not NT_SUCCESS(Status) then
begin
FreeMem(Buffer);
NtxAssert(Status, 'RtlInitializeSid');
end;
// Copy existing sub authorities
for i := 0 to SubAuthorities - 1 do
RtlSubAuthoritySid(Buffer, i)^ := RtlSubAuthoritySid(FSid, i)^;
// Set the last sub authority to the RID
RtlSubAuthoritySid(Buffer, SubAuthorities)^ := Rid;
Result := TSid.CreateOwned(Buffer);
end;
constructor TSid.CreateCopy(SourceSid: PSid);
var
Status: NTSTATUS;
begin
if not RtlValidSid(SourceSid) then
NtxAssert(STATUS_INVALID_SID, 'RtlValidSid');
FSid := AllocMem(RtlLengthSid(SourceSid));
Status := RtlCopySid(RtlLengthSid(SourceSid), FSid, SourceSid);
if not NT_SUCCESS(Status) then
begin
FreeMem(FSid);
NtxAssert(Status, 'RtlCopySid');
end;
end;
constructor TSid.CreateFromString(AccountOrSID: String);
var
Status: TNtxStatus;
LookupSid: ISid;
begin
// Since someone might create an account which name is a valid SDDL string,
// lookup the account name first. Parse it as SDDL only if this lookup failed.
Status := LsaxLookupUserName(AccountOrSID, LookupSid);
if Status.IsSuccess then
begin
CreateCopy(LookupSid.Sid);
Exit;
end;
// The string can start with "S-1-" and represent an arbitrary SID or can be
// one of ~40 double-letter abbreviations. See [MS-DTYP] for SDDL definition.
if (Length(AccountOrSID) = 2) or AccountOrSID.StartsWith('S-1-', True) then
Status := RtlxConvertStringToSid(AccountOrSID, FSid);
Status.RaiseOnError;
end;
constructor TSid.CreateNew(const IdentifyerAuthority: TSidIdentifierAuthority;
SubAuthorities: Byte; SubAuthourity0, SubAuthourity1, SubAuthourity2,
SubAuthourity3, SubAuthourity4: Cardinal);
var
Status: NTSTATUS;
begin
FSid := AllocMem(RtlLengthRequiredSid(SubAuthorities));
Status := RtlInitializeSid(FSid, @IdentifyerAuthority, SubAuthorities);
if not NT_SUCCESS(Status) then
begin
FreeMem(FSid);
NtxAssert(Status, 'RtlInitializeSid');
end;
if SubAuthorities > 0 then
RtlSubAuthoritySid(FSid, 0)^ := SubAuthourity0;
if SubAuthorities > 1 then
RtlSubAuthoritySid(FSid, 1)^ := SubAuthourity1;
if SubAuthorities > 2 then
RtlSubAuthoritySid(FSid, 2)^ := SubAuthourity2;
if SubAuthorities > 3 then
RtlSubAuthoritySid(FSid, 3)^ := SubAuthourity3;
if SubAuthorities > 4 then
RtlSubAuthoritySid(FSid, 4)^ := SubAuthourity4;
end;
constructor TSid.CreateOwned(OwnedSid: PSid; Dummy: Integer);
begin
FSid := OwnedSid;
end;
destructor TSid.Destroy;
begin
FreeMem(FSid);
inherited;
end;
function TSid.DomainName: String;
begin
ValidateLookup;
Result := FLookup.DomainName;
end;
function TSid.EqualsTo(Sid2: PSid): Boolean;
begin
Result := RtlEqualSid(FSid, Sid2);
end;
function TSid.IdentifyerAuthority: PSidIdentifierAuthority;
begin
Result := RtlIdentifierAuthoritySid(FSid);
end;
function TSid.ParentSid: ISid;
var
Status: NTSTATUS;
Buffer: PSid;
i: Integer;
begin
// The rule is simple: we drop the last sub-authority and create a new SID.
Assert(SubAuthorities > 0);
Buffer := AllocMem(RtlLengthRequiredSid(SubAuthorities - 1));
// Copy identifier authority
Status := RtlInitializeSid(Buffer, RtlIdentifierAuthoritySid(FSid),
SubAuthorities - 1);
if not NT_SUCCESS(Status) then
begin
FreeMem(Buffer);
NtxAssert(Status, 'RtlInitializeSid');
end;
// Copy sub authorities
for i := 0 to RtlSubAuthorityCountSid(Buffer)^ - 1 do
RtlSubAuthoritySid(Buffer, i)^ := RtlSubAuthoritySid(FSid, i)^;
Result := TSid.CreateOwned(Buffer);
end;
function TSid.RefreshLookup: TNtxStatus;
begin
// TODO: Optimize multiple queries with LsaLookupSids / LsaLookupNames
Result := LsaxLookupSid(FSid, FLookup);
FLookupCached := FLookupCached or Result.IsSuccess;
end;
function TSid.Rid: Cardinal;
begin
if SubAuthorities > 0 then
Result := SubAuthority(SubAuthorities - 1)
else
Result := 0;
end;
function TSid.SDDL: String;
begin
Result := RtlxConvertSidToString(FSid);
end;
procedure TSid.SetSubAuthority(Index: Integer; NewValue: Cardinal);
begin
RtlSubAuthoritySid(FSid, Index)^ := NewValue;
end;
function TSid.Sid: PSid;
begin
Result := FSid;
end;
function TSid.SidLength: Cardinal;
begin
Result := RtlLengthSid(FSid);
end;
function TSid.SidType: TSidNameUse;
begin
ValidateLookup;
Result := FLookup.SidType;
end;
function TSid.SubAuthorities: Byte;
begin
Result := RtlSubAuthorityCountSid(FSid)^;
end;
function TSid.SubAuthority(Index: Integer): Cardinal;
begin
if (Index >= 0) and (Index < SubAuthorities) then
Result := RtlSubAuthoritySid(FSid, Index)^
else
Result := 0;
end;
function TSid.UserName: String;
begin
ValidateLookup;
Result := FLookup.UserName;
end;
procedure TSid.ValidateLookup;
begin
if not FLookupCached then
RefreshLookup;
end;
{ Functions }
function RtlxpApplySddlOverrides(SID: PSid; var SDDL: String): Boolean;
begin
Result := False;
// We override convertion of some SIDs to strings for the sake of readability.
// The result is still a parsable SDDL string.
case RtlIdentifierAuthoritySid(SID).ToInt64 of
// Integrity: S-1-16-x
SECURITY_MANDATORY_LABEL_AUTHORITY_ID:
if RtlSubAuthorityCountSid(SID)^ = 1 then
begin
SDDL := 'S-1-16-' + IntToHexEx(RtlSubAuthoritySid(SID, 0)^, 4);
Result := True;
end;
end;
end;
function RtlxConvertSidToString(SID: PSid): String;
var
SDDL: UNICODE_STRING;
Buffer: array [0 .. SECURITY_MAX_SID_STRING_CHARACTERS - 1] of WideChar;
begin
Result := '';
if RtlxpApplySddlOverrides(SID, Result) then
Exit;
SDDL.Length := 0;
SDDL.MaximumLength := SizeOf(Buffer);
SDDL.Buffer := Buffer;
if NT_SUCCESS(RtlConvertSidToUnicodeString(SDDL, SID, False)) then
Result := SDDL.ToString
else
Result := '';
end;
function RtlxConvertStringToSid(SDDL: String; out SID: PSid): TNtxStatus;
var
Buffer: PSid;
IdAuthorityUInt64: UInt64;
IdAuthority: TSidIdentifierAuthority;
begin
// Despite the fact that RtlConvertSidToUnicodeString can convert SIDs with
// zero sub authorities to SDDL, ConvertStringSidToSidW (for some reason)
// can't convert them back. Fix this behaviour by parsing them manually.
// Expected formats for an SID with 0 sub authorities:
// S-1-(\d+) | S-1-(0x[A-F\d]+)
// where the value fits into a 6-byte (48-bit) buffer
if TryStrToUInt64Ex(Copy(SDDL, Length('S-1-') + 1, Length(SDDL)),
IdAuthorityUInt64) and (IdAuthorityUInt64 < UInt64(1) shl 48) then
begin
IdAuthority.FromInt64(IdAuthorityUInt64);
Buffer := AllocMem(RtlLengthRequiredSid(0));
Result.Location := 'RtlInitializeSid';
Result.Status := RtlInitializeSid(Buffer, @IdAuthority, 0);
if Result.IsSuccess then
SID := Buffer
else
FreeMem(Buffer);
end
else
begin
// Usual SDDLs
Result.Location := 'ConvertStringSidToSidW';
Result.Win32Result := ConvertStringSidToSidW(PWideChar(SDDL), Buffer);
if not Result.IsSuccess then
Exit;
SID := AllocMem(RtlLengthSid(Buffer));
Result.Location := 'RtlCopySid';
Result.Status := RtlCopySid(RtlLengthSid(Buffer), SID, Buffer);
if not Result.IsSuccess then
begin
FreeMem(SID);
SID := nil;
end;
LocalFree(Buffer);
end;
end;
function SddlxGetWellKnownSid(WellKnownSidType: TWellKnownSidType;
out Sid: ISid): TNtxStatus;
var
Buffer: PSid;
BufferSize: Cardinal;
begin
BufferSize := 0;
Result.Location := 'CreateWellKnownSid';
Result.Win32Result := CreateWellKnownSid(WellKnownSidType, nil, nil,
BufferSize);
if not NtxTryCheckBuffer(Result.Status, BufferSize) then
Exit;
Buffer := AllocMem(BufferSize);
Result.Win32Result := CreateWellKnownSid(WellKnownSidType, nil, Buffer,
BufferSize);
if Result.IsSuccess then
Sid := TSid.CreateOwned(Buffer)
else
FreeMem(Buffer);
end;
end.
|
unit WormsWorld;
interface
Uses
Types,
wwClasses, wwWorms, wwMinds;
type
TWormsField = class (TwwWorld)
private
FInstantRessurecctTargets: Boolean;
FInstantRessurecctWorms: Boolean;
FMaxTargetCount: Integer;
FMaxWormsCount: Integer;
FMindCenter: TwwMindCenter;
function GetTargetCount: Integer;
function GetTargets(Index: Integer): TwwTarget;
function GetWorms(Index: Integer): TwwWorm;
function GetWormsCount: Integer;
procedure SetInstantRessurecctTargets(const Value: Boolean);
procedure SetInstantRessurecctWorms(const Value: Boolean);
procedure SetMaxTargetCount(const Value: Integer);
procedure SetMaxWormsCount(const Value: Integer);
protected
procedure Ressurect(aThing: TwwThing); override;
procedure RessurectTargets;
procedure RessurectWorms;
public
constructor Create(const aBounds: TRect);
destructor Destroy; override;
function NearestTarget(const aPoint: TPoint): TwwTarget;
function NearestWorm(const aPoint: TPoint): TwwWorm;
function PowerestTarget: TwwTarget;
function RandomTarget(const aPoint: TPoint): TwwTarget;
procedure Update; override;
property InstantRessurectTargets: Boolean read FInstantRessurecctTargets
write SetInstantRessurecctTargets;
property InstantRessurectWorms: Boolean read FInstantRessurecctWorms write
SetInstantRessurecctWorms;
property MaxTargetCount: Integer read FMaxTargetCount write
SetMaxTargetCount;
property MaxWormsCount: Integer read FMaxWormsCount write SetMaxWormsCount;
property MindCenter: TwwMindCenter
read FMindCenter;
property TargetCount: Integer read GetTargetCount;
property Targets[Index: Integer]: TwwTarget read GetTargets;
property Worms[Index: Integer]: TwwWorm read GetWorms;
property WormsCount: Integer read GetWormsCount;
end;
implementation
Uses
SysUtils, VCL.Forms,
wwDummyMind, wwUtils, wwSimpleMind, wwMaratMinds, wwStarMind,
wwFirst;
{ TWormsField }
{
********************************* TWormsField **********************************
}
constructor TWormsField.Create(const aBounds: TRect);
begin
inherited Create(aBounds);
FMindCenter:= TwwMindCenter.Create(ChangeFileExt(Application.ExeName, '.dat'));
with FMindCenter do
begin
AddMind(TDummyMind.Create);
AddMind(TCarefullMind.Create);
AddMind(TImpudentMind.Create);
AddMind(TCowardMind.Create);
AddMind(TSimpletonMind.Create);
AddMind(TLazyMind.Create);
AddMind(TGourmetMind.Create);
AddMind(TAStarMind.Create);
AddMind(TFirstMind.Create);
end;
end;
destructor TWormsField.Destroy;
begin
FMindCenter.Free;
inherited Destroy;
end;
function TWormsField.GetTargetCount: Integer;
var
i: Integer;
l_T: TwwThing;
begin
Result:= 0;
for i:= 0 to Pred(Count) do
begin
l_T:= Things[i];
if (l_T is TwwTarget){ and l_T.IsLive} then
Inc(Result);
end;
end;
function TWormsField.GetTargets(Index: Integer): TwwTarget;
var
i, l_Current: Integer;
l_T: TwwThing;
begin
l_Current:= 0;
Result:= nil;
for i:= 0 to Pred(Count) do
begin
l_T:= Things[i];
if (l_T is TwwTarget){ and (l_T.IsLive)} then
begin
if (l_Current = Index) then
begin
Result:= l_T as TwwTarget;
break;
end
else
Inc(l_Current);
end;
end;
end;
function TWormsField.GetWorms(Index: Integer): TwwWorm;
var
i, l_Current: Integer;
l_T: TwwThing;
begin
l_Current:= 0;
Result:= nil;
for i:= 0 to Pred(Count) do
begin
l_T:= Things[i];
if (l_T is TwwWorm) then
if (l_Current = Index) then
begin
Result:= l_T as TwwWorm;
break;
end
else
Inc(l_Current);
end;
end;
function TWormsField.GetWormsCount: Integer;
var
i: Integer;
l_T: TwwThing;
begin
Result:= 0;
for i:= 0 to Pred(Count) do
begin
l_T:= Things[i];
if (l_T is TwwWorm) and l_T.IsLive then
Inc(Result);
end;
end;
function TWormsField.NearestTarget(const aPoint: TPoint): TwwTarget;
var
I: Integer;
MinDelta: Integer;
MinIndex: Integer;
l_TD: Integer;
begin
Result := nil;
MinIndex:= -1;
MinDelta:= High(MinDelta);
if TargetCount = 0 then
RessurectTargets;
for i:= 0 to Pred(TargetCount) do
begin
if not Targets[i].IsLive then
Targets[i].Ressurect;
begin
l_TD:= CalcDistance(aPoint, Targets[i].Head.Position);
if l_TD < MinDelta then
begin
MinDelta:= l_TD;
MinIndex:= i;
end;
end;
end;
if MinIndex > -1 then
Result:= Targets[MinIndex];
end;
function TWormsField.NearestWorm(const aPoint: TPoint): TwwWorm;
var
I: Integer;
MinDelta: Integer;
MinIndex: Integer;
l_TD: Integer;
begin
Result := nil;
MinIndex:= -1;
MinDelta:= High(MinDelta);
if WormsCount = 0 then
RessurectWorms;
for i:= 0 to Pred(WormsCount) do
begin
if Worms[i].IsLive then
begin
l_TD:= CalcDistance(aPoint, Worms[i].Head.Position);
if l_TD < MinDelta then
begin
MinDelta:= l_TD;
MinIndex:= i;
end;
end;
end;
if MinIndex > -1 then
Result:= Worms[MinIndex];
end;
function TWormsField.PowerestTarget: TwwTarget;
var
l_Power: Integer;
l_i, I: Integer;
begin
l_Power:= 0;
Result:= nil;
if TargetCount = 0 then
RessurectTargets;
for i:= 0 to Pred(TargetCount) do
begin
if (Targets[i].Power > l_Power) and Targets[i].IsLive then
begin
l_Power:= Targets[i].Power;
l_I:= i;
end;
end;
Result:= Targets[l_i];
end;
function TWormsField.RandomTarget(const aPoint: TPoint): TwwTarget;
begin
Result:= Targets[Random(TargetCount)];
end;
procedure TWormsField.Ressurect(aThing: TwwThing);
begin
if (aThing is TwwWorm) and InstantRessurectWorms then
aThing.Ressurect
else
if (aThing is TwwTarget) and InstantRessurectTargets then
aThing.Ressurect;
end;
procedure TWormsField.RessurectTargets;
var
i: Integer;
begin
for i:= 0 to Pred(MaxTargetCount) do
Targets[i].Ressurect;
end;
procedure TWormsField.RessurectWorms;
var
i: Integer;
begin
for i:= 0 to Pred(MaxWormsCount) do
Worms[i].Ressurect;
end;
procedure TWormsField.SetInstantRessurecctTargets(const Value: Boolean);
begin
FInstantRessurecctTargets := Value;
end;
procedure TWormsField.SetInstantRessurecctWorms(const Value: Boolean);
begin
FInstantRessurecctWorms := Value;
end;
procedure TWormsField.SetMaxTargetCount(const Value: Integer);
var
i: Integer;
begin
FMaxTargetCount := Value;
i:= 0;
while i < Count do
begin
if Things[i] is TwwTarget then
DeleteThing(i)
else
Inc(i);
end;
for i:= 0 to Pred(MaxTargetCount) do
AddThing(TwwTarget.Create(Self));
end;
procedure TWormsField.SetMaxWormsCount(const Value: Integer);
var
i: Integer;
begin
FMaxWormsCount := Value;
i:= 0;
while i < Count do
begin
if Things[i] is TwwWorm then
DeleteThing(i)
else
Inc(i);
end;
for i:= 0 to Pred(MaxWormsCount) do
AddThing(TwwWorm.Create(Self, FMindCenter, i));
end;
procedure TWormsField.Update;
begin
inherited;
if TargetCount = 0 then
RessurectTargets;
if WormsCount = 0 then
RessurectWorms;
end;
end.
|
unit A4onTypeUnit;
interface
uses
SysUtils, Classes;
type
TCustomerInfo = record
CUSTOMER_ID: Integer;
FIO: String;
STREET_ID: Integer;
STREET: String;
HOUSE_ID: Integer;
HOUSE_no: String;
FLAT_NO: String;
cust_code: String;
Account_No: String;
CUST_STATE_DESCR: String;
Debt_sum: Currency;
phone_no: String;
notice: String;
color: string;
porch_n: string;
floor_n: string;
mobile: string;
itBalance: Boolean;
isType: Integer; // 0 - абонент, 1 - узел
isJur : Integer; // 0 - физик 1 - юрик
INN : String;
end;
TAlertItem = record
title: String;
text: String;
Color: String;
FrameColor: String;
Tag: NativeInt;
end;
implementation
end.
|
unit vgAnimation;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "VGScene"
// Модуль: "w:/common/components/rtl/external/VGScene/NOT_FINISHED_vgAnimation.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::VGScene::Impl::TvgAnimation
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
{$Include w:\common\components\rtl\external\VGScene\vg_define.inc}
interface
{$IfNDef NoVGScene}
uses
Classes,
vgTypes,
vgObject
;
type
TvgAnimation = class(TvgObject)
private
FDuration: single;
FDelay, FDelayTime: single;
FTime: single;
FInverse: boolean;
FTrigger, FTriggerInverse: string;
FLoop: boolean;
FPause: boolean;
protected
FRunning: boolean;
private
FOnFinish: TNotifyEvent;
FOnProcess: TNotifyEvent;
FHideOnFinish: boolean;
FInterpolation: TvgInterpolationType;
FAnimationType: TvgAnimationType;
FEnabled: boolean;
FAutoReverse: boolean;
procedure SetEnabled(const Value: boolean);
protected
function NormalizedTime: single;
procedure ProcessAnimation; virtual;
procedure Loaded; override;
public
constructor Create(AOwner: TComponent); override;
procedure Cleanup; override;
procedure Start; virtual;
procedure Stop; virtual;
procedure StopAtCurrent; virtual;
procedure StartTrigger(AInstance: TvgObject; ATrigger: string); virtual;
procedure ProcessTick(time, deltaTime: single);
property Running: boolean read FRunning;
property Pause: boolean read FPause write FPause;
published
property AnimationType: TvgAnimationType read FAnimationType write FAnimationType default vgAnimationIn;
property AutoReverse: boolean read FAutoReverse write FAutoReverse default false;
property Enabled: boolean read FEnabled write SetEnabled default false;
property Delay: single read FDelay write FDelay;
property Duration: single read FDuration write FDuration;
property Interpolation: TvgInterpolationType read FInterpolation write FInterpolation default vgInterpolationLinear;
property Inverse: boolean read FInverse write FInverse default false;
property HideOnFinish: boolean read FHideOnFinish write FHideOnFinish default false;
property Loop: boolean read FLoop write FLoop default false;
property Trigger: string read FTrigger write FTrigger;
property TriggerInverse: string read FTriggerInverse write FTriggerInverse;
property OnProcess: TNotifyEvent read FOnProcess write FOnProcess;
property OnFinish: TNotifyEvent read FOnFinish write FOnFinish;
end;
{$EndIf NoVGScene}
implementation
{$IfNDef NoVGScene}
uses
Windows,
SysUtils,
TypInfo,
vg_Scene,
vgObjectList
;
{ TvgAnimation ===================================================================}
type
TvgAniThread = class(TvgTimer)
private
FAniList: TvgObjectList;
FStartTime, FTime, FDeltaTime: single;
procedure OneStep;
procedure DoSyncTimer(Sender: TObject);
protected
public
constructor Create;
destructor Destroy; override;
end;
{$IFDEF NOVCL}
function GetTickCount: single;
var
H, M, S, MS: word;
begin
DecodeTime(time, H, M, S, MS);
Result := ((((H * 60 * 60) + (M * 60) + S) * 1000) + MS);
end;
{$ENDIF}
{ TvgAniThread }
constructor TvgAniThread.Create;
begin
inherited Create(nil);
Interval := Trunc(1000 / 30);
OnTimer := DoSyncTimer;
FAniList := TvgObjectList.Create;
FStartTime := GetTickCount / 1000;
end;
destructor TvgAniThread.Destroy;
begin
FreeAndNil(FAniList);
inherited;
end;
procedure TvgAniThread.DoSyncTimer(Sender: TObject);
begin
OneStep;
end;
procedure TvgAniThread.OneStep;
var
i: integer;
NewTime: single;
begin
NewTime := (GetTickCount / 1000) - FStartTime;
if NewTime <= FTime then Exit;
FDeltaTime := NewTime - FTime;
FTime := NewTime;
if FAniList.Count > 0 then
begin
i := FAniList.Count - 1;
while i >= 0 do
begin
if TvgAnimation(FAniList[i]).FRunning then
begin
if (TvgAnimation(FAniList[i]).BindingName <> '') and
(CompareText(TvgAnimation(FAniList[i]).BindingName, 'caret') = 0) then
begin
TvgAnimation(FAniList[i]).Tag := TvgAnimation(FAniList[i]).Tag + 1;
if TvgAnimation(FAniList[i]).Tag mod 3 = 0 then
begin
TvgAnimation(FAniList[i]).ProcessTick(FTime, FDeltaTime);
end;
end
else
TvgAnimation(FAniList[i]).ProcessTick(FTime, FDeltaTime);
end;
Dec(i);
if i >= FAniList.Count then
i := FAniList.Count - 1;
end;
end;
end;
constructor TvgAnimation.Create(AOwner: TComponent);
begin
inherited;
FEnabled := false;
Duration := 0.2;
end;
procedure TvgAnimation.Cleanup;
begin
if aniThread <> nil then
begin
TvgAniThread(aniThread).FAniList.Remove(Self);
end;
inherited;
end;
procedure TvgAnimation.Loaded;
begin
inherited;
if not(Assigned(FScene)
and {$IfDef vgDesign}(FScene.GetDesignTime){$Else}false{$EndIf}) and
Enabled then
Start;
end;
procedure TvgAnimation.SetEnabled(const Value: boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
if not (Assigned(Scene)
and {$IfDef vgDesign}Scene.GetDesignTime{$Else}false{$EndIf}) and
not (csLoading in ComponentState) then
begin
if FEnabled then
Start
else
Stop;
end;
end;//FEnabled <> Value
end;
function TvgAnimation.NormalizedTime: single;
begin
if (FDuration > 0) and (FDelayTime <= 0) then
begin
case FInterpolation of
vgInterpolationLinear: Result:= vgInterpolateLinear(FTime, 0, 1, FDuration);
vgInterpolationQuadratic: Result:= vgInterpolateQuad(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationCubic: Result:= vgInterpolateCubic(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationQuartic: Result:= vgInterpolateQuart(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationQuintic: Result:= vgInterpolateQuint(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationSinusoidal: Result:= vgInterpolateSine(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationExponential: Result:= vgInterpolateExpo(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationCircular: Result:= vgInterpolateCirc(FTime, 0, 1, FDuration, FAnimationType);
vgInterpolationElastic: Result:= vgInterpolateElastic(FTime, 0, 1, FDuration, 0, 0, FAnimationType);
vgInterpolationBack: Result:= vgInterpolateBack(FTime, 0, 1, FDuration, 0, FAnimationType);
vgInterpolationBounce: Result:= vgInterpolateBounce(FTime, 0, 1, FDuration, FAnimationType);
end;
end
else
Result := 0;
end;
procedure TvgAnimation.ProcessAnimation;
begin
end;
procedure TvgAnimation.ProcessTick(time, deltaTime: single);
begin
inherited;
{$IfDef vgDesign}
if Assigned(FScene) and (FScene.GetDesignTime) then Exit;
{$EndIf vgDesign}
if csDestroying in ComponentState then Exit;
if (Parent <> nil) and (Parent.IsVisual) and (not TvgVisualObject(Parent).Visible) then
Stop;
if not FRunning then Exit;
if FPause then Exit;
if (FDelay > 0) and (FDelayTime <> 0) then
begin
if FDelayTime > 0 then
begin
FDelayTime := FDelayTime - deltaTime;
if FDelayTime <= 0 then
begin
Start;
FDelayTime := 0;
end;
end;
Exit;
end;
if FInverse then
FTime := FTime - deltaTime
else
FTime := FTime + deltaTime;
if FTime >= FDuration then
begin
FTime := FDuration;
if FLoop then
begin
if FAutoReverse then
begin
FInverse := true;
FTime := FDuration;
end
else
FTime := 0;
end
else
FRunning := false;
end
else
if FTime <= 0 then
begin
FTime := 0;
if FLoop then
begin
if FAutoReverse then
begin
FInverse := false;
FTime := 0;
end
else
FTime := FDuration;
end
else
FRunning := false;
end;
ProcessAnimation;
if Assigned(FOnProcess) then FOnProcess(Self);
if (FScene <> nil) then
if not FRunning then
begin
if aniThread <> nil then
TvgAniThread(aniThread).FAniList.Remove(Self);
if Assigned(FOnFinish) then FOnFinish(Self);
end;
end;
procedure TvgAnimation.Start;
begin
if (Parent <> nil) and (Parent.IsVisual) and (not TvgVisualObject(Parent).Visible) then Exit;
if (Abs(FDuration) < 0.001) or (FScene = nil) or
(Assigned(FScene) and {$IfDef vgDesign}(FScene.GetDesignTime){$Else}false{$EndIf}) then
begin
{ imediatly animation }
FDelayTime := 0;
if FInverse then
begin
FTime := 0;
FDuration := 1;
end
else
begin
FTime := 1;
FDuration := 1;
end;
FRunning := true;
ProcessAnimation;
FRunning := false;
FTime := 0;
FDuration := 0.00001;
if Assigned(FOnFinish) then FOnFinish(Self);
FEnabled := false;
end
else
begin
FDelayTime := FDelay;
FRunning := true;
if FInverse then
FTime := FDuration
else
FTime := 0;
if FDelay = 0 then
ProcessAnimation;
if (FScene <> nil) then
begin
if aniThread = nil then
aniThread := TvgAniThread.Create;
if TvgAniThread(aniThread).FAniList.IndexOf(Self) < 0 then
TvgAniThread(aniThread).FAniList.Add(Self);
end;
FEnabled := true;
end;
end;
procedure TvgAnimation.Stop;
begin
if not FRunning then Exit;
if aniThread <> nil then
begin
TvgAniThread(aniThread).FAniList.Remove(Self);
end;
if FInverse then
FTime := 0
else
FTime := FDuration;
ProcessAnimation;
FRunning := false;
FEnabled := false;
if Assigned(FOnFinish) then FOnFinish(Self);
end;
procedure TvgAnimation.StopAtCurrent;
begin
if not FRunning then Exit;
if aniThread <> nil then
begin
TvgAniThread(aniThread).FAniList.Remove(Self);
end;
if FInverse then
FTime := 0
else
FTime := FDuration;
FRunning := false;
FEnabled := false;
if Assigned(FOnFinish) then FOnFinish(Self);
end;
procedure TvgAnimation.StartTrigger(AInstance: TvgObject; ATrigger: string);
var
StartValue: boolean;
Line, Setter, Prop, Value: AnsiString;
begin
if AInstance = nil then Exit;
if (FTriggerInverse <> '') and (Pos(LowerCase(ATrigger), LowerCase(FTriggerInverse)) > 0) then
begin
Line := FTriggerInverse;
Setter := vgGetToken(Line, ';');
StartValue := false;
while Setter <> '' do
begin
Prop := vgGetToken(Setter, '=');
Value := Setter;
if GetPropInfo(AInstance, Prop, [{$IFDEF FPC}tkBool{$ELSE}tkEnumeration{$ENDIF}]) <> nil then
begin
{$IFDEF FPC}
StartValue := false;
if (CompareText(Value, 'true') = 0) and (GetOrdProp(AInstance, Prop) > 0) then
StartValue := true;
if (CompareText(Value, 'false') = 0) and (GetOrdProp(AInstance, Prop) = 0) then
StartValue := true;
{$ELSE}
StartValue := CompareText(GetEnumProp(AInstance, Prop), Value) = 0;
{$ENDIF}
if not StartValue then Break;
end;
Setter := vgGetToken(Line, ';');
end;
if StartValue then
begin
Inverse := true;
Start;
Exit;
end;
end;
if (FTrigger <> '') and (Pos(LowerCase(ATrigger), LowerCase(FTrigger)) > 0) then
begin
Line := FTrigger;
Setter := vgGetToken(Line, ';');
StartValue := false;
while Setter <> '' do
begin
Prop := vgGetToken(Setter, '=');
Value := Setter;
if GetPropInfo(AInstance, Prop, [{$IFDEF FPC}tkBool{$ELSE}tkEnumeration{$ENDIF}]) <> nil then
begin
{$IFDEF FPC}
StartValue := false;
if (CompareText(Value, 'true') = 0) and (GetOrdProp(AInstance, Prop) > 0) then
StartValue := true;
if (CompareText(Value, 'false') = 0) and (GetOrdProp(AInstance, Prop) = 0) then
StartValue := true;
{$ELSE}
StartValue := CompareText(GetEnumProp(AInstance, Prop), Value) = 0;
{$ENDIF}
if not StartValue then Exit;
end;
Setter := vgGetToken(Line, ';');
end;
if StartValue then
begin
if FTriggerInverse <> '' then
Inverse := false;
Start;
end;
end;
end;
{$EndIf NoVGScene}
end. |
{ Subroutine SST_R_PAS_DOIT (FNAM, GNAM, STAT)
*
* Read the PASCAL input file FNAM into the in-memory data structures. GNAM is
* returned as the generic leaf name of the input file.
}
module sst_r_pas_doit;
define sst_r_pas_doit;
%include 'sst_r_pas.ins.pas';
procedure sst_r_pas_doit ( {read input source code into in-memory data}
in fnam: univ string_var_arg_t; {raw input file name}
in out gnam: univ string_var_arg_t; {returned as generic name of input file}
out stat: sys_err_t); {completion status code}
type
suffix_k_t = ( {identifies which file name suffix was found}
suffix_none_k, {no suffix found that we recognize}
suffix_pas_k, {file name suffix was .pas}
suffix_cog_k); {file name suffix_was .cog}
var
mflag: syo_mflag_k_t; {syntaxed matched yes/no flag}
suffix_id: suffix_k_t; {identifies which file name suffix found}
label
loop, leave;
begin
suffix_id := suffix_none_k; {init to no file name suffix found}
string_generic_fnam (fnam, '.cog .pas', gnam); {make generic input file name}
if {input file name could have a suffix ?}
(fnam.len > 4) and
(fnam.str[fnam.len-3] = '.')
then begin
if
(fnam.str[fnam.len-2] = 'p') and
(fnam.str[fnam.len-1] = 'a') and
(fnam.str[fnam.len] = 's')
then begin {file name suffix is ".pas"}
suffix_id := suffix_pas_k;
end
else begin {file name suffix is not .pas}
if
(fnam.str[fnam.len-2] = 'c') and
(fnam.str[fnam.len-1] = 'o') and
(fnam.str[fnam.len] = 'g')
then begin {file name suffix is ".cog"}
suffix_id := suffix_cog_k;
end;
end
;
end; {done handling input file name suffix}
syo_init; {init syntaxer}
sst_r_pas_preproc_init; {init our pre-processor}
syo_preproc_set (addr(sst_r_pas_preproc)); {install our pre-processor}
if suffix_id = suffix_none_k {set name of top level input file}
then begin {FNAM doesn't have explicit suffix}
syo_infile_top_set (fnam, '.cog .pas');
end
else begin {FNAM already contains explicit suffix}
syo_infile_top_set (fnam, '');
end
;
{
* Keep looping until either an error or end of input.
}
loop: {back here each new top level syntax}
syo_tree_clear; {set up for parsing}
toplev (mflag); {try to parse one top level syntax}
if mflag = syo_mflag_yes_k
then begin {syntax matched}
error_syo_found := false; {indicate no syntax error}
end
else begin {syntax did not match}
syo_p_test_eod (mflag); {check for end of input data}
if mflag = syo_mflag_yes_k then begin {no error, encountered end of data}
sys_error_none (stat); {indicate no error condition}
goto leave;
end;
syo_tree_err; {set up for error re-parse}
toplev (mflag); {do error re-parse}
error_syo_found := true; {indicate we will hit error syntax tree end}
end
;
syo_tree_setup; {set up syntax tree for getting tags}
sst_r_pas_statement (stat); {process top level contruction}
if (not error_syo_found) and (not sys_error(stat)) {everything went well ?}
then goto loop; {back and do next top level construction}
{
* Something unusual happened.
}
if not sys_error(stat) then begin {syntax error not caught as contents error ?}
syo_error_print ('', '', nil, 0); {print message about syntax error}
end;
if sys_stat_match (sst_subsys_k, sst_stat_eod_k, stat)
then begin {no error, just hit end of input data}
sys_error_none (stat); {indicate normal condition}
end
else begin {error condition}
sys_stat_set (sst_subsys_k, sst_stat_err_handled_k, stat); {indicate err handled}
end
; {STAT is all set for return}
leave: {common exit point, STAT already set}
end;
|
unit UMazeGame; // Fully annotated
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.StdCtrls, Vcl.Menus,
UMazeHandler,
UPrimsMazeGenerator, UAStarSearch, UInterface, Vcl.ExtCtrls, DateUtils,
Vcl.Buttons;
type
TMainForm = class(TForm)
MazeStringGrid: TStringGrid;
// Note that single cells are sometimes assigned a different value in order
// to update that cell in the string grid. This is done to update individual
// cells where no others have been updated, or where refreshing the entire
// grid causes the maze to flicker.
WinText: TStaticText;
GenerateBtn: TSpeedButton;
SolveBtn: TSpeedButton;
ResetBtn: TSpeedButton;
procedure GenerateBtnClick(Sender: TObject);
procedure MazeStringGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure Move(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SolveBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure EndGame;
procedure FormDestroy(Sender: TObject);
procedure ResetBtnClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
MainForm: TMainForm;
Maze: TMazeHandler;
Solved, Generated, DisplayRoute, CanMove, NotCompleted, CanReset: boolean;
QuickestPath: TRoute;
implementation
{$R *.dfm}
// Changes a colour of cell displayed in the GUI when its value changes
procedure TMainForm.MazeStringGridDrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
var
Path, Route: boolean;
begin
// If the cell has a value
if not(MazeStringGrid.Cells[ACol, ARow] = '') then
begin
// If a cell is a wall, colour it black
if Maze.GetWall(ACol, ARow) then
MazeStringGrid.Canvas.Brush.Color := clblack
// Otherwise colour it white
else
MazeStringGrid.Canvas.Brush.Color := clwhite;
Path := Maze.GetPassed(ACol, ARow);
Route := Maze.GetSolution(ACol, ARow);
// If the cell forms a part of the character path, colour it yellow
if Path then
MazeStringGrid.Canvas.Brush.Color := clyellow;
// If the cell form a part of the solution and the solution is being
// displayed, colour it red
if (Route) and (DisplayRoute) then
MazeStringGrid.Canvas.Brush.Color := clred;
// If the cell forms a part of the chracter path and the solution and the
// solution is being displayed, colour it purple
if (Path) and (Route) and (DisplayRoute) then
MazeStringGrid.Canvas.Brush.Color := clpurple;
// If the cell is the start cell, colour it orange
if (ACol = Maze.GetStartX) and (ARow = Maze.GetStartY) then
MazeStringGrid.Canvas.Brush.Color := stringtocolor('$006FFF');
// If the cell is the end cell, colour it green
if (ACol = Maze.GetEndX) and (ARow = Maze.GetEndY) then
MazeStringGrid.Canvas.Brush.Color := stringtocolor('$00B000');
// If the cell is the position of the character, colour it aqua
if (ACol = Maze.GetPositionX) and (ARow = Maze.GetPositionY) then
begin
MazeStringGrid.Canvas.Brush.Color := clAqua;
end;
// Ensures that the whole cell will be painted
Rect.Left := Rect.Left - 4;
Rect.Right := Rect.Right + 4;
// Paints the cell with the colour selected
MazeStringGrid.Canvas.FillRect(Rect);
end;
end;
// Moves the chracter in the direction the player specified
procedure TMainForm.Move(Sender: TObject; var Key: Word; Shift: TShiftState);
var
positionX, positionY: Integer;
begin
// If the maze has been generated and the chracter can move
if (Generated) and (CanMove) then
begin
// Gets the position of the chracter
positionX := Maze.GetPositionX;
positionY := Maze.GetPositionY;
// If the move the chracter specified would not place the character outside
// of the maze
if not((((Key = 87) or (Key = 38)) and (positionY = 0)) or
(((Key = 83) or (Key = 40)) and (positionY = Maze.GetLastIndex)) or
(((Key = 65) or (Key = 37)) and (positionX = 0)) or
(((Key = 68) or (Key = 39)) and (positionX = Maze.GetLastIndex))) then
begin
case Key of
// If the w key or up arrow was pressed
87, 38:
begin
// If the position to be moved into is not a wall
if not(Maze.GetWall(positionX, positionY - 1)) then
begin
// Move the character forward one space
Maze.MoveForward;
// Marks it as the position of the character in the GUI
MazeStringGrid.Cells[positionX, positionY - 1] := '3';
// Sets the cell the character previously occupied as having been
// passed by the character
Maze.SetPassed(positionX, positionY);
// Marks it as an empty space in the GUI
MazeStringGrid.Cells[positionX, positionY] := '2';
end;
end;
// If s key or down arrow was pressed
83, 40:
begin
if not(Maze.GetWall(positionX, positionY + 1)) then
begin
// Move the character down one space
Maze.MoveBackward;
MazeStringGrid.Cells[positionX, positionY + 1] := '3';
Maze.SetPassed(positionX, positionY);
MazeStringGrid.Cells[positionX, positionY] := '2';
end;
end;
// If the a key or left arrow was pressed
65, 37:
begin
if not(Maze.GetWall(positionX - 1, positionY)) then
begin
// Move the character left one space
Maze.MoveLeft;
MazeStringGrid.Cells[positionX - 1, positionY] := '3';
Maze.SetPassed(positionX, positionY);
MazeStringGrid.Cells[positionX, positionY] := '2';
end;
end;
// If d key or right arrow was pressed
68, 39:
begin
if not(Maze.GetWall(positionX + 1, positionY)) then
begin
// Move the character right one cell
Maze.MoveRight;
MazeStringGrid.Cells[positionX + 1, positionY] := '3';
Maze.SetPassed(positionX, positionY);
MazeStringGrid.Cells[positionX, positionY] := '2';
end;
end;
end;
end;
// If the character is at the end of the maze, end the game
if (Maze.GetPositionX = Maze.GetEndX) and (Maze.GetPositionY = Maze.GetEndY)
then
EndGame;
end;
end;
// Resets the maze to its default value when the reset button is clicked
procedure TMainForm.ResetBtnClick(Sender: TObject);
var
x, y: Integer;
begin
// If the maze can be reset and it has been generated
if (CanReset) and (Generated) then
begin
// Reset the maze
Maze.ResetMaze;
// Update the values of all cells in the maze on the GUI
for x := 0 to (Maze.GetMazeLength - 1) do
begin
for y := 0 to (Maze.GetMazeLength - 1) do
begin
if Maze.GetWall(x, y) then
MazeStringGrid.Cells[x, y] := '1'
else
MazeStringGrid.Cells[x, y] := '0';
end;
end;
end;
// If the maze has not been generated, tell the user it can't be reset
if Generated = false then
begin
ShowMessage('There is no maze generated to reset');
end;
end;
// Solves the maze when the solve button is clicked
procedure TMainForm.SolveBtnClick(Sender: TObject);
var
index, x, y: Integer;
begin
// If the maze has been generated and has not already been solved
if not(Solved) and (Generated) then
begin
// Returns the quickest path through the maze
QuickestPath := UAStarSearch.FindSolution(Maze);
// For all cells in the route which are not also the start or end cell
for index := 1 to length(QuickestPath) - 2 do
begin
// Get the position of the cell which makes up the solution
x := QuickestPath[index].x;
y := QuickestPath[index].y;
// Set the cell as being part of the solution
Maze.SetSolution(x, y);
// Update the value of the cell to reflect this in the GUI
MazeStringGrid.Cells[x, y] := '3';
end;
// Sets the maze as solved and the route to be displayed
Solved := true;
DisplayRoute := true;
end
// If the maze has been solved and has not been completed
else if Solved and NotCompleted then
begin
// Flips the value of display route
DisplayRoute := not(DisplayRoute);
// Refreshes the string grid to reflect the change
MazeStringGrid.Refresh;
end
// If no maze has been generated, tell the user there is no maze to be solved
else if not(Generated) then
begin
ShowMessage('There is no maze generated to solve');
end;
end;
// Carried out when the form is created
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Initialises the booleans to reflect its state when no maze is generated
// and prevent erranous inputs from being taken action upon by the system
Solved := false;
Generated := false;
DisplayRoute := false;
CanMove := false;
CanReset := false;
WinText.Visible := false;
NotCompleted := true;
randomize;
end;
// Destroys the form
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(Maze);
end;
// Generates the maze when the generate button is clicked
procedure TMainForm.GenerateBtnClick(Sender: TObject);
var
x, y: Integer;
begin
// Sets the winning text to be invisible
WinText.Visible := false;
// If a maze has already been generated, destroy the instance of the maze
if Generated then
FreeAndNil(Maze);
// Create a template for the maze
Maze := TMazeHandler.Create;
// Create the maze
UPrimsMazeGenerator.Generate(Maze);
// Update the values of all cells in the maze on the GUI
for x := 0 to (Maze.GetMazeLength - 1) do
begin
for y := 0 to (Maze.GetMazeLength - 1) do
begin
if Maze.GetWall(x, y) then
MazeStringGrid.Cells[x, y] := '1'
else
MazeStringGrid.Cells[x, y] := '0';
end;
end;
// Update the booleans to reflect the fact that the maze has been generated,
// allowing the user to take more actions
Generated := true;
Solved := false;
CanMove := true;
CanReset := true;
end;
// Carries out the end of the game
procedure TMainForm.EndGame;
var
index, x, y: Integer;
Sender: TObject;
begin
// Update the booleans to prevent the player taking further actions (other
// than generating a new maze)
NotCompleted := false;
CanMove := false;
CanReset := false;
// If the maze has not been solved yet, solve it
if not(Solved) then
SolveBtnClick(Sender)
// Else if it has already been solved, display it
else
begin
DisplayRoute := true;
MazeStringGrid.Refresh;
end;
// Show the text which tells the user they have won
WinText.Visible := true;
end;
end.
|
procedure putstr(source:string;count:integer;dest:string;offset:integer); extern;
{PUTSTR copies a piece of a string into another string.
source - copies this string from its beginning
count - for this many characters
dest - to this string
offset - starting this many characters from its beginning
}
function findnull(source:string):integer; extern;
{FINDNULL looks in SOURCE for a null and returns the offset}
procedure byteset(var f:file;bytepointer:integer); extern;
procedure bytewrite(var f:file;bytepointer:integer); extern;
{
BYTESET and BYTEWRITE work just like STRSET and STRWRITE, but take as
arguments byte pointers for where to start reading or writing.
They are designed to play with strings where JSYS's are also being
used. So READ will return EOF at a null and WRITE will put null at
end of file. No check for end of string is done, since the JSYS's don't.
ARRSET and ARRWRITE are the same, but are used at the beginning of an
array - they take an array as arguments instead of a byte pointer, and
start I/O at the beginning of the array. They differ from STRSET and
STRWRITE in that nulls are treated as in BYTESET and BYTEWRITE.
}
procedure arrset(var f:file;st:string); extern;
procedure arrwrite(var f:file;st:string); extern;
function bytepos(var f:file):integer; extern.
{BYTEPOS returns a byte pointer which when IBP'ed will give the next
character to be read or written for the file. The file is assumed
to be open on a string (with STRSET, STRWRITE, BYTESET, BYTEWRITE,
ARRSET, or ARRWRITE).
|
unit UFormMain;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ATFileNotificationSimple, TntStdCtrls, TntDialogs;
type
TFormMain = class(TForm)
edFileName: TTntEdit;
btnBrowseFile: TButton;
Label2: TLabel;
OpenDialog1: TTntOpenDialog;
btnWatchFile: TButton;
btnClose: TButton;
Label1: TLabel;
Label3: TLabel;
edDelay: TEdit;
procedure btnBrowseFileClick(Sender: TObject);
procedure btnWatchFileClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure FileChanged(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
Notif: TATFileNotificationSimple;
procedure NotifyFile;
public
{ Public declarations }
end;
var
FormMain: TFormMain;
implementation
{$R *.DFM}
procedure TFormMain.FormCreate(Sender: TObject);
begin
Notif := TATFileNotificationSimple.Create(Self);
Notif.OnChanged := FileChanged;
end;
procedure TFormMain.NotifyFile;
begin
with Notif do
begin
Timer.Enabled := False;
Timer.Interval := StrToIntDef(edDelay.Text, Timer.Interval);
FileName := edFileName.Text;
Timer.Enabled := True;
end;
end;
procedure TFormMain.FileChanged(Sender: TObject);
begin
Application.MessageBox(
'File has been changed.'#13+
'To continue file watching, close this message box.',
'Notification',
MB_ICONWARNING or MB_TOPMOST);
end;
procedure TFormMain.btnBrowseFileClick(Sender: TObject);
begin
with OpenDialog1 do
if Execute then
edFileName.Text := FileName;
end;
procedure TFormMain.btnWatchFileClick(Sender: TObject);
begin
if edFileName.Text<>'' then
NotifyFile;
end;
procedure TFormMain.btnCloseClick(Sender: TObject);
begin
Close;
end;
end.
|
unit Configuracoes;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient,
IdHTTP, IOUtils, DBXJSON, IdGlobal, pngimage, ExtCtrls, ShellApi, xmldom, XMLIntf, msxmldom, XMLDoc;
type
TfrmConfiguracoes = class(TForm)
Label9: TLabel;
Label10: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
Label16: TLabel;
Label17: TLabel;
Label18: TLabel;
Label19: TLabel;
Label20: TLabel;
Label21: TLabel;
Label22: TLabel;
Label23: TLabel;
Label24: TLabel;
txtAPP_ROOT_PATH: TMemo;
txtENABLE_GUI: TMemo;
txtWHITE_LABEL: TMemo;
txtPATH_NFCE_NEW: TMemo;
txtPATH_NFCE_SIGN: TMemo;
txtPATH_NFCE_CUSTODY: TMemo;
txtPATH_NFCE_BACKUP: TMemo;
txtPATH_NFCE_ERRORS: TMemo;
txtPATH_NFCE_DANFE: TMemo;
txtPATH_NFCE_DANFE_CONTINGENCIA: TMemo;
txtURL_QRCODE_CONSULTA: TMemo;
txtQRCODE_TOKEN: TMemo;
txtQRCODE_TOKEN_ID: TMemo;
txtTRUST_STORE_PATH: TMemo;
txtFILE_CERTIFICADO: TMemo;
txtURL_DANFE: TMemo;
txtNFCE_AMBIENTE: TMemo;
txtNFCE_UF: TMemo;
txtNFCE_VERSAO: TMemo;
txtINFO_RODAPE_DANFE: TMemo;
txtREMOVE_ACENTOS: TMemo;
txtDADOS_RODAPE_DANFE: TMemo;
txtCONTINGENCIA_AUTOMATICA: TMemo;
txtCONTINGENCY_TIME_IN_MINUTES: TMemo;
btnLerParametros: TButton;
Label8: TLabel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
Label7: TLabel;
txtCONTINGENCY_SWITCHING_AUTO: TMemo;
Label25: TLabel;
txtNOVA_EMISSAO_EM_PRIMEIRA_CONTINGENCIA: TMemo;
Label26: TLabel;
txtCONTINGENCY_RETURN_ONLY_99990: TMemo;
Label27: TLabel;
txtFISCAL_CLOUD_ENABLE: TMemo;
Label28: TLabel;
txtFISCAL_CLOUD_URL: TMemo;
Label29: TLabel;
Label30: TLabel;
Label31: TLabel;
Label32: TLabel;
Label33: TLabel;
Label34: TLabel;
Label35: TLabel;
Label36: TLabel;
Label37: TLabel;
Label38: TLabel;
Label39: TLabel;
Label40: TLabel;
Label42: TLabel;
Label43: TLabel;
Label44: TLabel;
Label45: TLabel;
txtCNPJ_CONTRIBUINTE: TMemo;
txtID_PDV: TMemo;
txtCUSTODY_SEND_MAX_DOCS_PER_MINUTE: TMemo;
txtIE: TMemo;
txtURL_NFE_RECEPCAO: TMemo;
txtURL_NFE_RET_RECEPCAO: TMemo;
txtURL_NFE_AUTORIZACAO: TMemo;
txtURL_NFE_RET_AUTORIZACAO: TMemo;
txtURL_NFE_RECEPCAO_EVE: TMemo;
txtURL_NFE_INUTILIZACAO: TMemo;
txtURL_NFE_STATUS_SERV: TMemo;
txtURL_NFE_CONSULTA_NF: TMemo;
txtCONNECTION_TIMEOUT_IN_SECONDS: TMemo;
txtSOCKET_DYNAMIC: TMemo;
txtPRINTER_URI: TMemo;
txtPRINT_DANFE_ITEMS: TMemo;
txtSMALL_QRCODE: TMemo;
txtDANFE_REDUZIDO: TMemo;
txtPRINT_CLICHE: TMemo;
txtDANFE_LOGO_FILE_PATH: TMemo;
txtPRINT_LOGO_DANFE: TMemo;
txtCUT_DANFE: TMemo;
txtSALVA_DANFE: TMemo;
Label46: TLabel;
Label47: TLabel;
Label48: TLabel;
Label49: TLabel;
Label50: TLabel;
Label51: TLabel;
Label52: TLabel;
Label53: TLabel;
txtDANFE_VIA_EMIT: TMemo;
Label54: TLabel;
txtPRINT_EAN: TMemo;
Label55: TLabel;
txtDEBUG_SALVA_BIN_IMPRESSAO: TMemo;
Label56: TLabel;
txtINCLUIR_DESC_ACRES_ITEM: TMemo;
Label57: TLabel;
txtINCLUIR_DESC_ACRES_NOTA: TMemo;
Label58: TLabel;
Label59: TLabel;
Label60: TLabel;
Label61: TLabel;
Label62: TLabel;
Label63: TLabel;
Label64: TLabel;
Label65: TLabel;
Label66: TLabel;
Label67: TLabel;
Label68: TLabel;
Label69: TLabel;
Label70: TLabel;
Label71: TLabel;
Label72: TLabel;
Label73: TLabel;
Label74: TLabel;
txtINCLUIR_IMPOSTOS_POR_ITEM: TMemo;
txtPROXY: TMemo;
txtPROXY_HOST: TMemo;
txtPROXY_PORT: TMemo;
txtPROXY_USER: TMemo;
txtPROXY_PASSWORD: TMemo;
txtPROXY_DOMAIN: TMemo;
txtPROXY_PREEMPTIVE: TMemo;
txtAUTH: TMemo;
txtSMTP: TMemo;
txtSMTP_HOST: TMemo;
txtSMTP_PORT: TMemo;
txtSMTP_AUTH: TMemo;
txtSMTP_TLS: TMemo;
txtSMTP_USER: TMemo;
txtSMTP_USER_NAME: TMemo;
txtSMTP_USER_LOGIN: TMemo;
txtSMTP_PASSWORD: TMemo;
txtHORA_INUTILIZACAO: TMemo;
txtRETRY_ERROR_LIST_COUNT: TMemo;
txtCONTINGENCY_CODE_LIST: TMemo;
txtRETRY_ERRO_AND_CONTIGENCY: TMemo;
Label75: TLabel;
Label76: TLabel;
Label78: TLabel;
Label79: TLabel;
Label80: TLabel;
Label81: TLabel;
txtSUCCESS_LIST: TMemo;
Label82: TLabel;
txtIGNORE_INUTILIZACAO_LIST: TMemo;
Label83: TLabel;
txtNUMERO_DIAS_PARA_RESOLUCAO_NOTAS_ERRO: TMemo;
Label84: TLabel;
txtQNTD_NOTAS_COM_ERRO_RESOLUCAO: TMemo;
Label85: TLabel;
Label87: TLabel;
txtINCLUIR_RECEBIDO_TROCO_NOTA: TMemo;
Label41: TLabel;
txtDANFE_SUPER_SCRIPT: TMemo;
Label77: TLabel;
txtRETRY_ERROR_LIST: TMemo;
Button1: TButton;
btnJson: TButton;
btnCancelar: TButton;
procedure btnLerParametrosClick(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure btnJsonClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure FormHide(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmConfiguracoes: TfrmConfiguracoes;
implementation
Uses principal, json;
{$R *.dfm}
procedure TfrmConfiguracoes.btnCancelarClick(Sender: TObject);
var
i:Integer;
begin
frmConfiguracoes.Hide;
frmPrincipal.Show;
end;
procedure TfrmConfiguracoes.btnJsonClick(Sender: TObject);
var
URL, Retorno, JsonString: WideString ;
jsonConfiguracoes, cortaExtrato, jsonPair: TJSONObject;
configuracoes:TJSONArray;
jsonPrincipal: TJsonPair;
JsonToSend:TMemoryStream;
JsonStreamRetorno: AnsiString;
begin
//JSon principal
jsonConfiguracoes := TJSONObject.Create;
configuracoes := TJSONArray.Create;
jsonPrincipal := TJSONPair.Create('configuracao', configuracoes);
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'APP_ROOT_PATH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtAPP_ROOT_PATH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'ENABLE_GUI'));
jsonPair.AddPair(TJSONPair.Create('valor', txtENABLE_GUI.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'WHITE_LABEL'));
jsonPair.AddPair(TJSONPair.Create('valor', txtWHITE_LABEL.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_NEW'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_NEW.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_SIGN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_SIGN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_CUSTODY'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_CUSTODY.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_BACKUP'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_BACKUP.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_ERRORS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_ERRORS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_DANFE_CONTINGENCIA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_DANFE_CONTINGENCIA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_QRCODE_CONSULTA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_QRCODE_CONSULTA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'QRCODE_TOKEN_ID'));
jsonPair.AddPair(TJSONPair.Create('valor', txtQRCODE_TOKEN_ID.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'QRCODE_TOKEN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtQRCODE_TOKEN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'TRUST_STORE_PATH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtTRUST_STORE_PATH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'FILE_CERTIFICADO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtFILE_CERTIFICADO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NFCE_AMBIENTE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNFCE_AMBIENTE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NFCE_UF'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNFCE_UF.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NFCE_VERSAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNFCE_VERSAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INFO_RODAPE_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINFO_RODAPE_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'REMOVE_ACENTOS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtREMOVE_ACENTOS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DADOS_RODAPE_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDADOS_RODAPE_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCIA_AUTOMATICA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCIA_AUTOMATICA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_TIME_IN_MINUTES'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_TIME_IN_MINUTES.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_SWITCHING_AUTO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_SWITCHING_AUTO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NOVA_EMISSAO_EM_PRIMEIRA_CONTINGENCIA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNOVA_EMISSAO_EM_PRIMEIRA_CONTINGENCIA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_RETURN_ONLY_99990'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_RETURN_ONLY_99990.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'FISCAL_CLOUD_ENABLE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtFISCAL_CLOUD_ENABLE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'FISCAL_CLOUD_URL'));
jsonPair.AddPair(TJSONPair.Create('valor', txtFISCAL_CLOUD_URL.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CNPJ_CONTRIBUINTE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCNPJ_CONTRIBUINTE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'ID_PDV'));
jsonPair.AddPair(TJSONPair.Create('valor', txtID_PDV.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CUSTODY_SEND_MAX_DOCS_PER_MINUTE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCUSTODY_SEND_MAX_DOCS_PER_MINUTE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'IE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtIE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RECEPCAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RECEPCAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RET_RECEPCAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RET_RECEPCAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_AUTORIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_AUTORIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RET_AUTORIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RET_AUTORIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RECEPCAO_EVE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RECEPCAO_EVE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_INUTILIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_INUTILIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_STATUS_SERV'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_STATUS_SERV.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_CONSULTA_NF'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_CONSULTA_NF.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONNECTION_TIMEOUT_IN_SECONDS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONNECTION_TIMEOUT_IN_SECONDS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SOCKET_DYNAMIC'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSOCKET_DYNAMIC.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINTER_URI'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINTER_URI.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_DANFE_ITEMS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_DANFE_ITEMS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMALL_QRCODE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMALL_QRCODE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_REDUZIDO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_REDUZIDO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_CLICHE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_CLICHE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_LOGO_FILE_PATH'));
txtDANFE_LOGO_FILE_PATH.Text := StringReplace(txtDANFE_LOGO_FILE_PATH.Text,'\','\\',[rfReplaceAll]);
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_LOGO_FILE_PATH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_LOGO_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_LOGO_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_SUPER_SCRIPT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_SUPER_SCRIPT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_SUPER_SCRIPT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_SUPER_SCRIPT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CUT_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCUT_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SALVA_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSALVA_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_VIA_EMIT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_VIA_EMIT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_EAN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_EAN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DEBUG_SALVA_BIN_IMPRESSAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDEBUG_SALVA_BIN_IMPRESSAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_DESC_ACRES_ITEM'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_DESC_ACRES_ITEM.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_DESC_ACRES_NOTA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_DESC_ACRES_NOTA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_RECEBIDO_TROCO_NOTA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_RECEBIDO_TROCO_NOTA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_IMPOSTOS_POR_ITEM'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_IMPOSTOS_POR_ITEM.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_USER'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_USER.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_PASSWORD'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_PASSWORD.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_DOMAIN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_DOMAIN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_PREEMPTIVE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_PREEMPTIVE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'AUTH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtAUTH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_HOST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_HOST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_PORT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_PORT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_AUTH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_AUTH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_TLS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_TLS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_USER'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_USER.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_USER_NAME'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_USER_NAME.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_USER_LOGIN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_USER_LOGIN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_PASSWORD'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_PASSWORD.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'HORA_INUTILIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtHORA_INUTILIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'RETRY_ERROR_LIST_COUNT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtRETRY_ERROR_LIST_COUNT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'RETRY_ERROR_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtRETRY_ERROR_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_CODE_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_CODE_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'RETRY_ERRO_AND_CONTIGENC'));
jsonPair.AddPair(TJSONPair.Create('valor', txtRETRY_ERRO_AND_CONTIGENCY.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SUCCESS_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_CODE_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'IGNORE_INUTILIZACAO_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_CODE_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NUMERO_DIAS_PARA_RESOLUCAO_NOTAS_ERRO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNUMERO_DIAS_PARA_RESOLUCAO_NOTAS_ERRO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'QNTD_NOTAS_COM_ERRO_RESOLUCAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtQNTD_NOTAS_COM_ERRO_RESOLUCAO.Text));
configuracoes.AddElement(jsonPair);
jsonConfiguracoes.AddPair(jsonPrincipal);
JsonString := jsonConfiguracoes.ToString;
JsonString := StringReplace(JsonString,#$A,'',[rfReplaceAll]);
JsonString := StringReplace(JsonString,#$D,'',[rfReplaceAll]);
JsonToSend := TMemoryStream.Create;
//JsonString := jsonPagamento.ToString;
JsonString := StringReplace(JsonString,#$A,'',[rfReplaceAll]);
JsonString := StringReplace(JsonString,#$D,'',[rfReplaceAll]);
frmJSon.memoJSon.Clear;
frmJSon.memoJSon.Text := JsonString;
frmJSon.Show;
end;
procedure TfrmConfiguracoes.btnLerParametrosClick(Sender: TObject);
var
URL, Retorno, JsonString: WideString ;
Json,JsonToSend :TMemoryStream;
JsonStreamRetorno: AnsiString;
jsonObj,item: TJSONObject;
configuracao: TJSONArray;
begin
begin
URL := 'http://localhost:9999/api/v1/sistema/configuracoes';
try
FrmPrincipal.HTTP.Request.ContentType := 'application/json';
FrmPrincipal.HTTP.Request.Accept := 'application/json';
JsonStreamRetorno := frmPrincipal.Http.Get(URL);
JsonStreamRetorno := StringReplace(JsonStreamRetorno,#13,'',[rfReplaceAll]);
JsonStreamRetorno := StringReplace(JsonStreamRetorno,#10,'',[rfReplaceAll]);
jsonObj := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(JsonStreamRetorno), 0) as TJSONObject;
configuracao := TJSONArray(jsonObj.Get('configuracao').JsonValue);
item := TJsonObject(configuracao.Get(0));
txtAPP_ROOT_PATH.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(1));
txtENABLE_GUI.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(2));
txtWHITE_LABEL.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(3));
txtPATH_NFCE_NEW.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(4));
txtPATH_NFCE_SIGN.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(5));
txtPATH_NFCE_CUSTODY.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(6));
txtPATH_NFCE_BACKUP.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(7));
txtPATH_NFCE_ERRORS.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(8));
txtPATH_NFCE_DANFE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(9));
txtPATH_NFCE_DANFE_CONTINGENCIA.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(10));
txtURL_QRCODE_CONSULTA.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(11));
txtQRCODE_TOKEN_ID.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(12));
txtQRCODE_TOKEN.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(13));
txtTRUST_STORE_PATH.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(14));
txtFILE_CERTIFICADO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(15));
txtURL_DANFE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(16));
txtNFCE_AMBIENTE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(17));
txtNFCE_UF.Text :=item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(18));
txtNFCE_VERSAO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(19));
txtINFO_RODAPE_DANFE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(20));
txtREMOVE_ACENTOS.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(21));
txtDADOS_RODAPE_DANFE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(22));
txtCONTINGENCIA_AUTOMATICA.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(23));
txtCONTINGENCY_TIME_IN_MINUTES.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(24));
txtCONTINGENCY_SWITCHING_AUTO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(25));
txtNOVA_EMISSAO_EM_PRIMEIRA_CONTINGENCIA.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(26));
txtCONTINGENCY_RETURN_ONLY_99990.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(27));
txtFISCAL_CLOUD_ENABLE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(28));
txtFISCAL_CLOUD_URL.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(29));
txtCNPJ_CONTRIBUINTE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(30));
txtID_PDV.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(31));
txtCUSTODY_SEND_MAX_DOCS_PER_MINUTE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(32));
txtIE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(33));
txtURL_NFE_RECEPCAO.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(34));
txtURL_NFE_RET_RECEPCAO.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(35));
txtURL_NFE_AUTORIZACAO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(36));
txtURL_NFE_RET_AUTORIZACAO.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(37));
txtURL_NFE_RECEPCAO_EVE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(38));
txtURL_NFE_INUTILIZACAO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(39));
txtURL_NFE_STATUS_SERV.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(40));
txtURL_NFE_CONSULTA_NF.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(41));
txtCONNECTION_TIMEOUT_IN_SECONDS.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(42));
txtSOCKET_DYNAMIC.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(44));
txtPRINTER_URI.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(45));
txtPRINT_DANFE_ITEMS.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(46));
txtSMALL_QRCODE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(47));
txtDANFE_REDUZIDO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(48));
txtPRINT_CLICHE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(49));
txtDANFE_LOGO_FILE_PATH.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(50));
txtPRINT_LOGO_DANFE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(51));
txtDANFE_SUPER_SCRIPT.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(52));
txtCUT_DANFE.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(53));
txtSALVA_DANFE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(54));
txtDANFE_VIA_EMIT.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(55));
txtPRINT_EAN.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(56));
txtDEBUG_SALVA_BIN_IMPRESSAO.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(57));
txtINCLUIR_DESC_ACRES_ITEM.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(58));
txtINCLUIR_DESC_ACRES_NOTA.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(59));
txtINCLUIR_RECEBIDO_TROCO_NOTA.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(60));
txtINCLUIR_IMPOSTOS_POR_ITEM.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(61));
txtPROXY.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(62));
txtPROXY_HOST.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(63));
txtPROXY_PORT.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(64));
txtPROXY_USER.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(65));
txtPROXY_PASSWORD.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(66));
txtPROXY_DOMAIN.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(67));
txtPROXY_PREEMPTIVE.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(68));
txtAUTH.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(69));
txtSMTP.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(70));
txtSMTP_HOST.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(71));
txtSMTP_PORT.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(72));
txtSMTP_AUTH.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(73));
txtSMTP_TLS.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(74));
txtSMTP_USER.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(75));
txtSMTP_USER_NAME.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(76));
txtSMTP_USER_LOGIN.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(77));
txtSMTP_PASSWORD.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(78));
txtHORA_INUTILIZACAO.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(79));
txtRETRY_ERROR_LIST_COUNT.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(80));
txtRETRY_ERROR_LIST.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(81));
txtCONTINGENCY_CODE_LIST.Text := item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(82));
txtRETRY_ERRO_AND_CONTIGENCY.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(83));
txtSUCCESS_LIST.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(84));
txtIGNORE_INUTILIZACAO_LIST.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(85));
txtNUMERO_DIAS_PARA_RESOLUCAO_NOTAS_ERRO.Text:= item.Get(1).JsonValue.Value;
item := TJsonObject(configuracao.Get(86));
txtQNTD_NOTAS_COM_ERRO_RESOLUCAO.Text:= item.Get(1).JsonValue.Value;
frmPrincipal.memoresultado.Lines.add(JsonStreamRetorno);
Button1.Enabled := true;
except on E:EIdHTTPProtocolException do
frmPrincipal.memoresultado.Lines.add(e.ErrorMessage);
end;
end;
end;
procedure TfrmConfiguracoes.Button1Click(Sender: TObject);
var
URL, Retorno, JsonString: WideString ;
jsonConfiguracoes, cortaExtrato, jsonPair: TJSONObject;
configuracoes:TJSONArray;
jsonPrincipal: TJsonPair;
JsonToSend:TMemoryStream;
JsonStreamRetorno: AnsiString;
i:Integer;
begin
if (Application.MessageBox('Tem certeza que deseja gravar? Todos as configurações do Fiscal Manager serão sobreescritas.','Cancelar',mb_yesno + mb_iconquestion) = id_yes) then
begin
//JSon principal
jsonConfiguracoes := TJSONObject.Create;
configuracoes := TJSONArray.Create;
jsonPrincipal := TJSONPair.Create('configuracao', configuracoes);
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'APP_ROOT_PATH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtAPP_ROOT_PATH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'ENABLE_GUI'));
jsonPair.AddPair(TJSONPair.Create('valor', txtENABLE_GUI.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'WHITE_LABEL'));
jsonPair.AddPair(TJSONPair.Create('valor', txtWHITE_LABEL.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_NEW'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_NEW.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_SIGN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_SIGN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_CUSTODY'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_CUSTODY.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_BACKUP'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_BACKUP.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_ERRORS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_ERRORS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PATH_NFCE_DANFE_CONTINGENCIA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPATH_NFCE_DANFE_CONTINGENCIA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_QRCODE_CONSULTA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_QRCODE_CONSULTA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'QRCODE_TOKEN_ID'));
jsonPair.AddPair(TJSONPair.Create('valor', txtQRCODE_TOKEN_ID.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'QRCODE_TOKEN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtQRCODE_TOKEN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'TRUST_STORE_PATH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtTRUST_STORE_PATH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'FILE_CERTIFICADO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtFILE_CERTIFICADO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NFCE_AMBIENTE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNFCE_AMBIENTE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NFCE_UF'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNFCE_UF.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NFCE_VERSAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNFCE_VERSAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INFO_RODAPE_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINFO_RODAPE_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'REMOVE_ACENTOS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtREMOVE_ACENTOS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DADOS_RODAPE_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDADOS_RODAPE_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCIA_AUTOMATICA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCIA_AUTOMATICA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_TIME_IN_MINUTES'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_TIME_IN_MINUTES.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_SWITCHING_AUTO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_SWITCHING_AUTO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NOVA_EMISSAO_EM_PRIMEIRA_CONTINGENCIA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNOVA_EMISSAO_EM_PRIMEIRA_CONTINGENCIA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_RETURN_ONLY_99990'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_RETURN_ONLY_99990.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'FISCAL_CLOUD_ENABLE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtFISCAL_CLOUD_ENABLE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'FISCAL_CLOUD_URL'));
jsonPair.AddPair(TJSONPair.Create('valor', txtFISCAL_CLOUD_URL.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CNPJ_CONTRIBUINTE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCNPJ_CONTRIBUINTE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'ID_PDV'));
jsonPair.AddPair(TJSONPair.Create('valor', txtID_PDV.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CUSTODY_SEND_MAX_DOCS_PER_MINUTE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCUSTODY_SEND_MAX_DOCS_PER_MINUTE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'IE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtIE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RECEPCAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RECEPCAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RET_RECEPCAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RET_RECEPCAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_AUTORIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_AUTORIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RET_AUTORIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RET_AUTORIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_RECEPCAO_EVE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_RECEPCAO_EVE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_INUTILIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_INUTILIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_STATUS_SERV'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_STATUS_SERV.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'URL_NFE_CONSULTA_NF'));
jsonPair.AddPair(TJSONPair.Create('valor', txtURL_NFE_CONSULTA_NF.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONNECTION_TIMEOUT_IN_SECONDS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONNECTION_TIMEOUT_IN_SECONDS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SOCKET_DYNAMIC'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSOCKET_DYNAMIC.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINTER_URI'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINTER_URI.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_DANFE_ITEMS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_DANFE_ITEMS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMALL_QRCODE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMALL_QRCODE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_REDUZIDO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_REDUZIDO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_CLICHE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_CLICHE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_LOGO_FILE_PATH'));
txtDANFE_LOGO_FILE_PATH.Text := StringReplace(txtDANFE_LOGO_FILE_PATH.Text,'\','\\',[rfReplaceAll]);
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_LOGO_FILE_PATH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_LOGO_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_LOGO_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_SUPER_SCRIPT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_SUPER_SCRIPT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_SUPER_SCRIPT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_SUPER_SCRIPT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CUT_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCUT_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SALVA_DANFE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSALVA_DANFE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DANFE_VIA_EMIT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDANFE_VIA_EMIT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PRINT_EAN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPRINT_EAN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'DEBUG_SALVA_BIN_IMPRESSAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtDEBUG_SALVA_BIN_IMPRESSAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_DESC_ACRES_ITEM'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_DESC_ACRES_ITEM.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_DESC_ACRES_NOTA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_DESC_ACRES_NOTA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_RECEBIDO_TROCO_NOTA'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_RECEBIDO_TROCO_NOTA.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'INCLUIR_IMPOSTOS_POR_ITEM'));
jsonPair.AddPair(TJSONPair.Create('valor', txtINCLUIR_IMPOSTOS_POR_ITEM.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_USER'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_USER.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_PASSWORD'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_PASSWORD.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_DOMAIN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_DOMAIN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'PROXY_PREEMPTIVE'));
jsonPair.AddPair(TJSONPair.Create('valor', txtPROXY_PREEMPTIVE.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'AUTH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtAUTH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_HOST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_HOST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_PORT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_PORT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_AUTH'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_AUTH.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_TLS'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_TLS.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_USER'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_USER.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_USER_NAME'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_USER_NAME.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_USER_LOGIN'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_USER_LOGIN.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SMTP_PASSWORD'));
jsonPair.AddPair(TJSONPair.Create('valor', txtSMTP_PASSWORD.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'HORA_INUTILIZACAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtHORA_INUTILIZACAO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'RETRY_ERROR_LIST_COUNT'));
jsonPair.AddPair(TJSONPair.Create('valor', txtRETRY_ERROR_LIST_COUNT.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'RETRY_ERROR_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtRETRY_ERROR_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'CONTINGENCY_CODE_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_CODE_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'RETRY_ERRO_AND_CONTIGENCY'));
jsonPair.AddPair(TJSONPair.Create('valor', txtRETRY_ERRO_AND_CONTIGENCY.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'SUCCESS_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_CODE_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'IGNORE_INUTILIZACAO_LIST'));
jsonPair.AddPair(TJSONPair.Create('valor', txtCONTINGENCY_CODE_LIST.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'NUMERO_DIAS_PARA_RESOLUCAO_NOTAS_ERRO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtNUMERO_DIAS_PARA_RESOLUCAO_NOTAS_ERRO.Text));
configuracoes.AddElement(jsonPair);
jsonPair := nil;
jsonPair := TJsonObject.Create();
jsonPair.AddPair(TJSONPair.Create('nome', 'QNTD_NOTAS_COM_ERRO_RESOLUCAO'));
jsonPair.AddPair(TJSONPair.Create('valor', txtQNTD_NOTAS_COM_ERRO_RESOLUCAO.Text));
configuracoes.AddElement(jsonPair);
jsonConfiguracoes.AddPair(jsonPrincipal);
JsonString := jsonConfiguracoes.ToString;
JsonString := StringReplace(JsonString,#$A,'',[rfReplaceAll]);
JsonString := StringReplace(JsonString,#$D,'',[rfReplaceAll]);
JsonToSend := TMemoryStream.Create;
begin
JsonToSend := TMemoryStream.Create;
WriteStringToStream(JsonToSend, JsonString, enUTF8);
JsonToSend.Position := 0;
URL := 'http://localhost:9999/api/v1/sistema/configuracoes';
try
frmPrincipal.HTTP.Request.ContentType := 'application/json';
frmPrincipal.HTTP.Request.CharSet := 'utf-8';
frmPrincipal.Http.Response.ContentType :='application/json';
frmPrincipal.Http.Response.CharSet := 'UTF-8';
// memojson.Lines.Add(JsonString);
JsonStreamRetorno := frmPrincipal.Http.Post(URL, JsonToSend);
frmPrincipal.memoresultado.Lines.add(JsonStreamRetorno);
//memoresultado.Lines.add('1=' + JsonStreamRetorno);
//memoresultado.Lines.add('3=' + Retorno);
FrmConfiguracoes.Hide;
except on E:EIdHTTPProtocolException do
frmPrincipal.memoresultado.Lines.add(e.ErrorMessage);
end
end;
end;
end;
procedure TfrmConfiguracoes.FormHide(Sender: TObject);
var
i:Integer;
begin
for i := 0 to ComponentCount-1 do
if (Components[i] is TMemo) then
begin
TMemo(Components[i]).Text := '';
end;
Button1.Enabled := false;
end;
end.
|
unit uXPTaskbar;
interface
uses
Classes, QExtCtrls, uCommon,
QControls, uXPStartButton, uXPSysTray,
uXPTaskband, uWMConsts, QDialogs,
SysUtils, QForms;
type
TXPSizeGrip=class;
TXPTaskbar=class(TPanel)
public
leftGrip:TXPSizeGrip;
startButton: TXPStartButton;
systray: TXPSysTray;
taskband: TXPTaskBand;
procedure activatetask(const task:IWMClient);
procedure updatetask(const client:IWMClient);
procedure addtask(const client:IWMClient);
procedure removetask(const task:IWMClient);
procedure onShowStartMenu(sender: TObject);
procedure onCloseMenu(sender: TObject);
procedure setup;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
{ TODO : Add an orientation property }
end;
TXPSizeGrip=class(TPanel)
public
procedure setup;
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
end;
implementation
uses uXPStartMenu;
{ TXPTaskbar }
procedure TXPTaskbar.activatetask(const task: IWMClient);
begin
taskband.activatetask(task);
end;
procedure TXPTaskbar.addtask(const client: IWMClient);
begin
taskband.addtask(client);
end;
constructor TXPTaskbar.Create(AOwner: TComponent);
begin
inherited;
setup;
end;
destructor TXPTaskbar.Destroy;
begin
leftGrip.free;
startButton.free;
sysTray.free;
taskband.free;
inherited;
end;
procedure TXPTaskbar.onCloseMenu(sender: TObject);
var
st: TStartMenu;
begin
//Not needed now, the menu is always present
(*
startButton.release;
st:=getStartMenu;
st.visible:=false;
application.processmessages;
freeStartMenu;
self.Parent.BringToFront;
self.Parent.setfocus;
self.Parent.SetFocus;
*)
end;
procedure TXPTaskbar.onShowStartMenu(sender: TObject);
var
st: TStartMenu;
begin
//Get/Create the start menu and show it
st:=getStartMenu;
st.left:=0;
st.top:=self.parent.top-st.height;
st.OnHide:=onCloseMenu;
st.visible:=true;
st.BringToFront;
// SetMouseGrabControl(st);
// SetMouseGrabControl(nil);
end;
procedure TXPTaskbar.removetask(const task: IWMClient);
begin
taskband.removetask(task);
end;
procedure TXPTaskbar.setup;
var
dir: string;
begin
leftGrip:=TXPSizeGrip.create(nil);
leftGrip.align:=alLeft;
leftGrip.parent:=self;
BevelOuter:=bvNone;
dir:=getSystemInfo(XP_TASKBAR_DIR);
{ TODO : Configure according the orientation property }
bitmap.LoadFromFile(dir+'/taskbar_background_bottom.png');
startButton:=TXPStartButton.create(nil);
startButton.Align:=alLeft;
startButton.Parent:=self;
startButton.OnShowMenu:=onShowStartMenu;
sysTray:=TXPSysTray.create(nil);
sysTray.align:=alRight;
sysTray.parent:=self;
taskband:=TXPTaskBand.create(nil);
taskband.align:=alClient;
taskband.parent:=self;
end;
procedure TXPTaskbar.updatetask(const client: IWMClient);
begin
taskband.updatetask(client);
end;
{ TXPSizeGrip }
constructor TXPSizeGrip.Create(AOwner: TComponent);
begin
inherited;
setup;
end;
destructor TXPSizeGrip.Destroy;
begin
inherited;
end;
procedure TXPSizeGrip.setup;
var
dir: string;
begin
BevelOuter:=bvNone;
dir:=getSystemInfo(XP_TASKBAR_DIR);
bitmap.LoadFromFile(dir+'/taskbar_grip_vert.png');
width:=bitmap.width;
end;
end.
|
program Aufgabe9142 {input,output};
{Eingabe eines Feldes, dann Pruefung ob Feld unsortiert, sortiert oder sortiert duplikatsfrei ist, Ausgabe des Ergebnisses}
const
FELDMAX = 5;
type
tBereich = 1 .. FELDMAX;
tFeld = Array [tBereich] of integer;
tRueckgabe = (unsortiert, sortiert, sortiertDuplikatfrei);
var
i,
Eingabe : integer;
Feld : tFeld;
function pruefeFeld (inFeld:tFeld) : tRueckgabe;
{Prüft ob Feld aufsteigend sortiert ist, Rueckgabe von unsortiert, sortiert oder sortiertDuplikatfrei}
var
i : tBereich;
dupl : boolean;
begin
i := 2;
dupl := false;
while (i < FELDMAX) and (inFeld[i-1] <= inFeld[i]) do
begin
if inFeld[i-1] = inFeld[i] then
dupl := true;
i := i+1;
end;
if (i < FELDMAX) or ((i = FELDMAX) and (inFEld[i-1] > inFeld[i])) then
pruefeFeld := unsortiert
else
if (inFeld[i-1] < inFeld[i]) and not dupl then
pruefeFeld := sortiertDuplikatfrei
else
pruefeFeld := sortiert;
end;
begin
writeln('Bitte geben Sie ',FELDMAX,' ganzzahlige Werte ein. Diese werden in eine Liste übernommen.');
for i:= 1 to FELDMAX do
begin
readln(Eingabe);
Feld[i] := Eingabe;
end;
writeln('Das Feld wurde eingelesen, es wird die Sortierung geprüft.');
writeln('Das Feld ist: ',pruefeFeld(Feld),'.');
end.
|
unit SetOpciones;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, JvExStdCtrls, JvCheckBox, Buttons, Inifiles;
type
TFSetOpciones = class(TForm)
cbRecibo: TJvCheckBox;
cbNCred: TJvCheckBox;
cbDeposito: TJvCheckBox;
btnOK: TBitBtn;
btnAnu: TBitBtn;
procedure btnOKClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
FSetOpciones: TFSetOpciones;
implementation
{$R *.dfm}
procedure TFSetOpciones.btnOKClick(Sender: TObject);
var
FIni: TInifile;
begin
FIni := TIniFile.create( extractFilePath( Application.exename ) + 'conf/Config.ini');
try
FIni.WriteBool('AUTORIZA', 'AUTRECIBO', cbRecibo.Checked );
FIni.WriteBool('AUTORIZA', 'AUTNCRED', cbNCred.Checked );
FIni.WriteBool('AUTORIZA', 'AUTDEPOSITO', cbDeposito.Checked );
finally
FIni.Free;
end;
end;
procedure TFSetOpciones.FormCreate(Sender: TObject);
var
FIni: TInifile;
begin
FIni := TIniFile.create( extractFilePath( Application.exename ) + 'conf/Config.ini');
try
cbRecibo.Checked := FIni.ReadBool('AUTORIZA', 'AUTRECIBO', true );
cbNCred.Checked := FIni.ReadBool('AUTORIZA', 'AUTNCRED', true );
cbDeposito.Checked := FIni.ReadBool('AUTORIZA', 'AUTDEPOSITO', true );
finally
FIni.Free;
end;
end;
end.
|
unit udmContatosSac;
interface
uses
Windows, System.UITypes,Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, udmPadrao, DBAccess, IBC, DB, MemDS;
type
TdmContatosSac = class(TdmPadrao)
qryManutencaoCODIGO: TStringField;
qryManutencaoNOME: TStringField;
qryManutencaoENDERECO: TStringField;
qryManutencaoBAIRRO: TStringField;
qryManutencaoCIDADE: TStringField;
qryManutencaoESTADO: TStringField;
qryManutencaoCEP: TStringField;
qryManutencaoTEL1: TStringField;
qryManutencaoFAX1: TStringField;
qryManutencaoCEL1: TStringField;
qryManutencaoCONTATO: TStringField;
qryManutencaoCARGO: TStringField;
qryManutencaoE_MAIL: TStringField;
qryManutencaoTIPO: TStringField;
qryManutencaoDT_ALTERACAO: TDateTimeField;
qryManutencaoOPERADOR: TStringField;
qryManutencaoEND_NRO: TStringField;
qryManutencaoEND_COMPL: TStringField;
qryLocalizacaoCODIGO: TStringField;
qryLocalizacaoNOME: TStringField;
qryLocalizacaoENDERECO: TStringField;
qryLocalizacaoBAIRRO: TStringField;
qryLocalizacaoCIDADE: TStringField;
qryLocalizacaoESTADO: TStringField;
qryLocalizacaoCEP: TStringField;
qryLocalizacaoTEL1: TStringField;
qryLocalizacaoFAX1: TStringField;
qryLocalizacaoCEL1: TStringField;
qryLocalizacaoCONTATO: TStringField;
qryLocalizacaoCARGO: TStringField;
qryLocalizacaoE_MAIL: TStringField;
qryLocalizacaoTIPO: TStringField;
qryLocalizacaoDT_ALTERACAO: TDateTimeField;
qryLocalizacaoOPERADOR: TStringField;
qryLocalizacaoEND_NRO: TStringField;
qryLocalizacaoEND_COMPL: TStringField;
qryManutencaoOBSERVACAO: TBlobField;
qryLocalizacaoOBSERVACAO: TBlobField;
protected
procedure MontaSQLBusca(DataSet: TDataSet = nil); override;
procedure MontaSQLRefresh; override;
private
FCod_Contato: string;
{ Private declarations }
public
{ Public declarations }
property Cod_Contato: string read FCod_Contato write FCod_Contato;
end;
const
SQL_DEFAULT = 'SELECT CODIGO, ' +
' NOME, ' +
' ENDERECO, ' +
' BAIRRO, ' +
' CIDADE, ' +
' ESTADO, ' +
' CEP, ' +
' TEL1, ' +
' FAX1, ' +
' CEL1, ' +
' CONTATO, ' +
' CARGO, ' +
' E_MAIL, ' +
' TIPO, ' +
' DT_ALTERACAO, ' +
' OPERADOR, ' +
' END_NRO, ' +
' END_COMPL, ' +
' OBSERVACAO ' +
'FROM STWSACTCONT ';
var
dmContatosSac: TdmContatosSac;
implementation
{$R *.dfm}
{ TdmContatosSac }
procedure TdmContatosSac.MontaSQLBusca(DataSet: TDataSet);
begin
inherited;
with (DataSet as TIBCQuery) do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('WHERE ( CODIGO = :CODIGO )');
SQL.Add('ORDER BY CODIGO');
Params[0].AsString := FCod_Contato;
end;
end;
procedure TdmContatosSac.MontaSQLRefresh;
begin
inherited;
with qryManutencao do
begin
SQL.Clear;
SQL.Add(SQL_DEFAULT);
SQL.Add('ORDER BY CODIGO');
end;
end;
end.
|
unit FFSPROCDEFTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TFFSPROCDEFRecord = record
PReportID: Integer;
PListKey: String[10];
PType: Integer;
PDescription: String[100];
End;
TFFSPROCDEFBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TFFSPROCDEFRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEIFFSPROCDEF = (FFSPROCDEFPrimaryKey, FFSPROCDEFByListKeyType);
TFFSPROCDEFTable = class( TDBISAMTableAU )
private
FDFReportID: TAutoIncField;
FDFListKey: TStringField;
FDFType: TIntegerField;
FDFDescription: TStringField;
FDFOptions: TBlobField;
FDFLenderList: TBlobField;
procedure SetPListKey(const Value: String);
function GetPListKey:String;
procedure SetPType(const Value: Integer);
function GetPType:Integer;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetEnumIndex(Value: TEIFFSPROCDEF);
function GetEnumIndex: TEIFFSPROCDEF;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TFFSPROCDEFRecord;
procedure StoreDataBuffer(ABuffer:TFFSPROCDEFRecord);
property DFReportID: TAutoIncField read FDFReportID;
property DFListKey: TStringField read FDFListKey;
property DFType: TIntegerField read FDFType;
property DFDescription: TStringField read FDFDescription;
property DFOptions: TBlobField read FDFOptions;
property DFLenderList: TBlobField read FDFLenderList;
property PListKey: String read GetPListKey write SetPListKey;
property PType: Integer read GetPType write SetPType;
property PDescription: String read GetPDescription write SetPDescription;
published
property Active write SetActive;
property EnumIndex: TEIFFSPROCDEF read GetEnumIndex write SetEnumIndex;
end; { TFFSPROCDEFTable }
procedure Register;
implementation
procedure TFFSPROCDEFTable.CreateFields;
begin
FDFReportID := CreateField( 'ReportID' ) as TAutoIncField;
FDFListKey := CreateField( 'ListKey' ) as TStringField;
FDFType := CreateField( 'Type' ) as TIntegerField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFOptions := CreateField( 'Options' ) as TBlobField;
FDFLenderList := CreateField( 'LenderList' ) as TBlobField;
end; { TFFSPROCDEFTable.CreateFields }
procedure TFFSPROCDEFTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TFFSPROCDEFTable.SetActive }
procedure TFFSPROCDEFTable.SetPListKey(const Value: String);
begin
DFListKey.Value := Value;
end;
function TFFSPROCDEFTable.GetPListKey:String;
begin
result := DFListKey.Value;
end;
procedure TFFSPROCDEFTable.SetPType(const Value: Integer);
begin
DFType.Value := Value;
end;
function TFFSPROCDEFTable.GetPType:Integer;
begin
result := DFType.Value;
end;
procedure TFFSPROCDEFTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TFFSPROCDEFTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TFFSPROCDEFTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ReportID, AutoInc, 0, N');
Add('ListKey, String, 10, N');
Add('Type, Integer, 0, N');
Add('Description, String, 100, N');
Add('Options, Memo, 0, N');
Add('LenderList, Memo, 0, N');
end;
end;
procedure TFFSPROCDEFTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, ReportID, Y, Y, N, N');
Add('ByListKeyType, ListKey;Type;ReportID, N, N, N, Y');
end;
end;
procedure TFFSPROCDEFTable.SetEnumIndex(Value: TEIFFSPROCDEF);
begin
case Value of
FFSPROCDEFPrimaryKey : IndexName := '';
FFSPROCDEFByListKeyType : IndexName := 'ByListKeyType';
end;
end;
function TFFSPROCDEFTable.GetDataBuffer:TFFSPROCDEFRecord;
var buf: TFFSPROCDEFRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PReportID := DFReportID.Value;
buf.PListKey := DFListKey.Value;
buf.PType := DFType.Value;
buf.PDescription := DFDescription.Value;
result := buf;
end;
procedure TFFSPROCDEFTable.StoreDataBuffer(ABuffer:TFFSPROCDEFRecord);
begin
DFListKey.Value := ABuffer.PListKey;
DFType.Value := ABuffer.PType;
DFDescription.Value := ABuffer.PDescription;
end;
function TFFSPROCDEFTable.GetEnumIndex: TEIFFSPROCDEF;
var iname : string;
begin
result := FFSPROCDEFPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := FFSPROCDEFPrimaryKey;
if iname = 'BYLISTKEYTYPE' then result := FFSPROCDEFByListKeyType;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'FFS Tables', [ TFFSPROCDEFTable, TFFSPROCDEFBuffer ] );
end; { Register }
function TFFSPROCDEFBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..4] of string = ('REPORTID','LISTKEY','TYPE','DESCRIPTION' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 4) and (flist[x] <> s) do inc(x);
if x <= 4 then result := x else result := 0;
end;
function TFFSPROCDEFBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftAutoInc;
2 : result := ftString;
3 : result := ftInteger;
4 : result := ftString;
end;
end;
function TFFSPROCDEFBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PReportID;
2 : result := @Data.PListKey;
3 : result := @Data.PType;
4 : result := @Data.PDescription;
end;
end;
end.
|
unit evCustomEdit;
{* Строка ввода. }
// Модуль: "w:\common\components\gui\Garant\Everest\evCustomEdit.pas"
// Стереотип: "GuiControl"
// Элемент модели: "TevCustomEdit" MUID: (4829D7E80085)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, evCustomMemo
, Classes
, l3InternalInterfaces
, l3Region
{$If NOT Defined(NoVCL)}
, Controls
{$IfEnd} // NOT Defined(NoVCL)
, Messages
, evDef
;
const
def_EditScrollStyle = evDef.def_EditScrollStyle;
type
_RegionableControl_Parent_ = TevCustomMemo;
{$Include w:\common\components\gui\Garant\SkinnedControls\RegionableControl.imp.pas}
TevCustomEdit = class(_RegionableControl_)
{* Строка ввода. }
private
f_UpperCase: Boolean;
f_Regionable: Boolean;
private
function cnvLo2Up(Sender: TObject;
aStr: PAnsiChar;
aLen: Integer;
aCodePage: Integer): Boolean;
protected
procedure pm_SetRegionable(aValue: Boolean);
function TextSourceClass: RevCustomMemoTextSource; override;
function GetTopMargin: Integer; override;
{* Возвращает отступ до текста сверху. }
procedure Validate; override;
procedure Paint(const CN: Il3Canvas); override;
{* процедура рисования внешнего вида управляющего элемента }
function WantSoftEnter: Boolean; override;
procedure TuneRegion(aRegion: Tl3Region); override;
public
constructor Create(AOwner: TComponent); override;
public
property UpperCase: Boolean
read f_UpperCase
write f_UpperCase
default False;
property Regionable: Boolean
read f_Regionable
write pm_SetRegionable;
end;//TevCustomEdit
implementation
uses
l3ImplUses
, evCustomEditTextSource
, SysUtils
, evSearch
, l3String
, evTypes
, evConvertTextTools
, l3Units
, Windows
{$If NOT Defined(NoVCL)}
, Themes
{$IfEnd} // NOT Defined(NoVCL)
{$If NOT Defined(NoScripts)}
, TtfwClassRef_Proxy
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *4829D7E80085impl_uses*
//#UC END# *4829D7E80085impl_uses*
;
{$Include w:\common\components\gui\Garant\SkinnedControls\RegionableControl.imp.pas}
procedure TevCustomEdit.pm_SetRegionable(aValue: Boolean);
//#UC START# *4CFFC1BA00EB_4829D7E80085set_var*
//#UC END# *4CFFC1BA00EB_4829D7E80085set_var*
begin
//#UC START# *4CFFC1BA00EB_4829D7E80085set_impl*
if (f_Regionable <> aValue) then
begin
f_Regionable := aValue;
RecreateWnd;
end;//f_Regionable <> aValue
//#UC END# *4CFFC1BA00EB_4829D7E80085set_impl*
end;//TevCustomEdit.pm_SetRegionable
function TevCustomEdit.cnvLo2Up(Sender: TObject;
aStr: PAnsiChar;
aLen: Integer;
aCodePage: Integer): Boolean;
//#UC START# *4860F67C0000_4829D7E80085_var*
//#UC END# *4860F67C0000_4829D7E80085_var*
begin
//#UC START# *4860F67C0000_4829D7E80085_impl*
Result := l3MakeUpperCase(aStr, aLen, aCodePage);
//#UC END# *4860F67C0000_4829D7E80085_impl*
end;//TevCustomEdit.cnvLo2Up
constructor TevCustomEdit.Create(AOwner: TComponent);
//#UC START# *47D1602000C6_4829D7E80085_var*
//#UC END# *47D1602000C6_4829D7E80085_var*
begin
//#UC START# *47D1602000C6_4829D7E80085_impl*
inherited;
ScrollStyle := def_EditScrollStyle;
Width := 121;
Height := 25;
Wrap := false;
LMargin := 1;
NeedReplaceQuotes := false;
//#UC END# *47D1602000C6_4829D7E80085_impl*
end;//TevCustomEdit.Create
function TevCustomEdit.TextSourceClass: RevCustomMemoTextSource;
//#UC START# *482D9D1701E0_4829D7E80085_var*
//#UC END# *482D9D1701E0_4829D7E80085_var*
begin
//#UC START# *482D9D1701E0_4829D7E80085_impl*
Result := TevCustomEditTextSource;
//#UC END# *482D9D1701E0_4829D7E80085_impl*
end;//TevCustomEdit.TextSourceClass
function TevCustomEdit.GetTopMargin: Integer;
{* Возвращает отступ до текста сверху. }
//#UC START# *483D718E0143_4829D7E80085_var*
var
l_DocHeight : Integer;
//#UC END# *483D718E0143_4829D7E80085_var*
begin
//#UC START# *483D718E0143_4829D7E80085_impl*
l_DocHeight := DocumentFullHeight;
Result := ((ClientHeight - l_DocHeight) div 2) - 1;
if (Result < 0) then
Result := 0;
//#UC END# *483D718E0143_4829D7E80085_impl*
end;//TevCustomEdit.GetTopMargin
procedure TevCustomEdit.Validate;
//#UC START# *4860F5DF026F_4829D7E80085_var*
var
l_Op : TevSearchOptionSet;
//#UC END# *4860F5DF026F_4829D7E80085_var*
begin
//#UC START# *4860F5DF026F_4829D7E80085_impl*
if f_UpperCase then
begin
l_Op := [ev_soGlobal, ev_soReplaceAll, ev_soUseInternalCursor];
Find(TevAnyParagraphSearcher.Make,
TevInPlaceTextConverter.Make(cnvLo2Up, l_Op), l_Op);
end;
//#UC END# *4860F5DF026F_4829D7E80085_impl*
end;//TevCustomEdit.Validate
procedure TevCustomEdit.Paint(const CN: Il3Canvas);
{* процедура рисования внешнего вида управляющего элемента }
//#UC START# *48C6C044025E_4829D7E80085_var*
var
l_Delta : Integer;
//#UC END# *48C6C044025E_4829D7E80085_var*
begin
//#UC START# *48C6C044025E_4829D7E80085_impl*
l_Delta := GetTopMargin;
if (l_Delta > 0) then
CN.MoveWindowOrg(l3SPoint(0, -l_Delta));
inherited;
//#UC END# *48C6C044025E_4829D7E80085_impl*
end;//TevCustomEdit.Paint
function TevCustomEdit.WantSoftEnter: Boolean;
//#UC START# *4B28D6780001_4829D7E80085_var*
//#UC END# *4B28D6780001_4829D7E80085_var*
begin
//#UC START# *4B28D6780001_4829D7E80085_impl*
{$IFDEF Archi}
Result := False;
{$ELSE}
Result := inherited WantSoftEnter;
{$ENDIF Archi}
//#UC END# *4B28D6780001_4829D7E80085_impl*
end;//TevCustomEdit.WantSoftEnter
procedure TevCustomEdit.TuneRegion(aRegion: Tl3Region);
//#UC START# *4CC847800383_4829D7E80085_var*
const
cRad = 6;
var
l_R : Tl3Region;
//#UC END# *4CC847800383_4829D7E80085_var*
begin
//#UC START# *4CC847800383_4829D7E80085_impl*
if Regionable then
begin
l_R := Tl3Region.Create;
try
l_R.Rgn := CreateRoundRectRgn(1, 0, Width + 1, Height, cRad, cRad);
aRegion.Combine(l_R, RGN_OR);
aRegion.CombineRect(l3SRect(Width - cRad, 0, Width, Height), RGN_OR);
finally
FreeAndNil(l_R);
end;//try..fianlly
end;//Regionable
//#UC END# *4CC847800383_4829D7E80085_impl*
end;//TevCustomEdit.TuneRegion
initialization
{$If NOT Defined(NoScripts)}
TtfwClassRef.Register(TevCustomEdit);
{* Регистрация TevCustomEdit }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
unit NullableArrayInterceptorUnit;
interface
uses
Windows, REST.JsonReflect, Rtti, SysUtils, System.JSON, System.TypInfo,
System.Generics.Collections;
type
TNullableArrayIntermediateObjectA = class
private
FIsRequired: boolean;
FValue: TArray<TObject>;
public
property IsRequired: boolean read FIsRequired write FIsRequired;
end;
TNullableArrayIntermediateObject = class(TInterfacedObject, IUnknown)
private
FNullableArrayIntermediateObject: TNullableArrayIntermediateObjectA;
public
constructor Create(Value: TValue);
destructor Destroy; override;
end;
TNullableArrayInterceptor = class(TJSONInterceptor)
private
type
TInternalJSONUnMarshal = class(TJSONUnMarshal);
const
IsNullFieldCaption = 'FIsNull';
ValueFieldCaption = 'FValue';
var
FIntermediateObjects: TObjectList<TObject>;
function GetObjectValue(s: String; Clazz: TClass): TValue;
public
destructor Destroy; override;
/// <summary>Converters that transforms a field value into an
/// intermediate object</summary>
/// <param name="Data">Current object instance being serialized</param>
/// <param name="Field">Field name</param>
/// <result> a serializable object </result>
function ObjectConverter(Data: TObject; Field: string): TObject; override;
/// <summary>Reverter that sets an object field to a value based on
/// an array of strings</summary>
/// <param name="Data">Current object instance being populated</param>
/// <param name="Field">Field name</param>
/// <param name="Args"> an array of strings </param>
procedure StringsReverter(Data: TObject; Field: string; Args: TListOfStrings); override;
end;
implementation
{ TNullableArrayInterceptor }
uses JSONNullableAttributeUnit, MarshalUnMarshalUnit;
destructor TNullableArrayInterceptor.Destroy;
begin
FreeAndNil(FIntermediateObjects);
inherited;
end;
function TNullableArrayInterceptor.GetObjectValue(s: String; Clazz: TClass): TValue;
var
Obj: TObject;
JsonValue: TJsonValue;
begin
JsonValue := TJsonObject.ParseJSONValue(s);
try
Obj := TMarshalUnMarshal.FromJson(Clazz, JsonValue);
Result := TValue.From(Obj);
finally
FreeAndNil(JsonValue)
end;
end;
function TNullableArrayInterceptor.ObjectConverter(Data: TObject;
Field: string): TObject;
var
ctx: TRttiContext;
RttiType: TRttiType;
RttiField: TRttiField;
Value: TValue;
begin
Result := nil;
ctx := TRttiContext.Create;
try
rttiType := ctx.GetType(Data.ClassType);
RttiField := rttiType.GetField(Field);
if (RttiField.FieldType.TypeKind <> tkDynArray) then
raise Exception.Create('The field marked attribute "NullableArray" must be an array.');
Value := RttiField.GetValue(Data);
Result := TNullableArrayIntermediateObject.Create(Value);
finally
ctx.Free;
end;
if (Result = nil) then
raise Exception.Create('The result can not be undefinded!');
if (FIntermediateObjects = nil) then
FIntermediateObjects := TObjectList<TObject>.Create;
FIntermediateObjects.Add(Result);
end;
procedure TNullableArrayInterceptor.StringsReverter(Data: TObject;
Field: string; Args: TListOfStrings);
function GetClass(RttiField: TRttiField): TClass;
var
NullableAttribute: NullableArrayAttribute;
Attr: TCustomAttribute;
begin
NullableAttribute := nil;
for Attr in RttiField.GetAttributes do
if Attr is NullableArrayAttribute then
NullableAttribute := NullableArrayAttribute(Attr);
if (NullableAttribute = nil) then
raise Exception.Create('This intercepter (TNullableArrayInterceptor) was created not in NullableArrayAttribute.');
Result := NullableArrayAttribute(NullableAttribute).Clazz;
end;
var
ctx: TRttiContext;
RttiType: TRttiType;
RttiField: TRttiField;
Clazz: TClass;
ArrayValue, NewArrayValue: TValue;
i: integer;
Values: array of TValue;
begin
inherited;
if (Length(Args) = 0) then
Exit;
ctx := TRttiContext.Create;
try
RttiType := ctx.GetType(Data.ClassType);
RttiField := RttiType.GetField(Field);
ArrayValue := RttiField.GetValue(Data);
Clazz := GetClass(RttiField);
SetLength(Values, Length(Args));
for i := 0 to Length(Args) - 1 do
Values[i] := GetObjectValue(Args[i], Clazz);
NewArrayValue := TValue.FromArray(ArrayValue.TypeInfo, Values);
RttiField.SetValue(Data, NewArrayValue);
finally
ctx.Free;
end;
end;
{ TNullableArrayIntermediateObject }
constructor TNullableArrayIntermediateObject.Create(Value: TValue);
var
i: integer;
Len: integer;
begin
FNullableArrayIntermediateObject := TNullableArrayIntermediateObjectA.Create;
Len := Value.GetArrayLength;
SetLength(FNullableArrayIntermediateObject.FValue, Len);
for i := 0 to Len - 1 do
FNullableArrayIntermediateObject.FValue[i] := Value.GetArrayElement(i).AsObject;
end;
destructor TNullableArrayIntermediateObject.Destroy;
begin
FreeAndNil(FNullableArrayIntermediateObject);
inherited;
end;
end.
|
unit Model.ControleAWB;
interface
uses Common.ENum, FireDAC.Comp.Client, FireDAC.Comp.DataSet, Data.DB, DAO.Conexao;
type
TControleAWB = class
private
FAWB2: String;
FAWB1: String;
FID: integer;
FCEP: String;
FRemessa: String;
FAcao: Tacao;
FConexao: TConexao;
FOperacao: String;
FPeso: Double;
FTipo: Integer;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
public
property ID: integer read FID write FID;
property Remessa: String read FRemessa write FRemessa;
property AWB1: String read FAWB1 write FAWB1;
property AWB2: String read FAWB2 write FAWB2;
property CEP: String read FCEP write FCEP;
property Operacao: String read FOperacao write FOperacao;
property Tipo: Integer read FTipo write FTipo;
property Peso: Double read FPeso write FPeso;
property Acao: Tacao read FAcao write FAcao;
constructor Create;
function GetID(): Integer;
function Localizar(aParam: array of variant): TFDQuery;
function LocalizarExato(aParam: array of variant): Boolean;
function Gravar(): Boolean;
procedure SetupSelf(fdQuery: TFDQuery);
procedure ClearSelf;
end;
const
TABLENAME = 'expressas_controle_awb';
SQLINSERT = 'insert into ' + TABLENAME + ' (id_awb, num_remessa, cod_awb1, cod_awb2, num_cep, cod_operacao,cod_tipo,qtd_peso)' +
'values ' +
'(:id_awb, :num_remessa, :cod_awb1, :cod_awb2, :num_cep, :cod_operacao, :cod_tipo, :qtd_peso);';
SQLUPDATE = 'update ' + TABLENAME + ' set num_remessa = :num_remessa, cod_awb1 = :cod_awb1, ' +
'cod_awb2 = cod_awb2, num_cep= :num_cep, cod_operacao = :cod_operacao, ' +
'cod_tipo = :cod_tipo, qtd_peso = :qtd_peso where id_awb = :id_awb;';
implementation
{ TControleAWB }
uses Control.Sistema;
function TControleAWB.Alterar: Boolean;
var
fdQuery: TFDQuery;
begin
try
Result := False;
fdQuery := FConexao.ReturnQuery();
fdQuery.ExecSQL(SQLUPDATE, [Self.Remessa, Self.AWB1, Self.AWB2, Self.CEP, Self.Operacao, Self.Tipo, SelF.Peso, Self.ID]);
Result := True;
finally
fdQuery.Connection.Close;
fdQuery.Free;
end;
end;
procedure TControleAWB.ClearSelf;
begin
Self.ID := 0;
Self.Remessa := '';
Self.AWB1 := '';
Self.AWB2 := '';
Self.CEP := '';
Self.Operacao := '';
Self.Tipo := 0;
Self.Peso := 0;
end;
constructor TControleAWB.Create;
begin
FConexao := TConexao.Create;
end;
function TControleAWB.Excluir: Boolean;
var
fdQuery: TFDQuery;
begin
try
Result := False;
fdQuery := FConexao.ReturnQuery();
fdQuery.ExecSQL('delete from ' + TABLENAME);
Result := True;
finally
fdQuery.Connection.Close;
fdquery.Free;
end;
end;
function TControleAWB.GetID: Integer;
var
fdQuery: TFDQuery;
begin
try
fdQuery := FConexao.ReturnQuery();
fdQuery.Open('select coalesce(max(id_awb),0) + 1 from ' + TABLENAME);
try
Result := fdQuery.Fields[0].AsInteger;
finally
fdQuery.Close;
end;
finally
fdQuery.Connection.Close;
fdQuery.Free;
end;
end;
function TControleAWB.Gravar: Boolean;
begin
Result := False;
case FAcao of
Common.ENum.tacIncluir: Result := Inserir();
Common.ENum.tacAlterar: Result := Alterar();
Common.ENum.tacExcluir: Result := Excluir();
end;
end;
function TControleAWB.Inserir: Boolean;
var
fdQuery: TFDQuery;
begin
try
Result := False;
fdQuery := FConexao.ReturnQuery();
Self.ID := Self.GetID();
fdQuery.ExecSQL(SQLINSERT, [Self.ID, Self.Remessa, Self.AWB1, Self.AWB2, Self.CEP, Self.Operacao, Self.Tipo, SelF.Peso]);
Result := True;
finally
fdQuery.Connection.Close;
fdQuery.Free;
end;
end;
function TControleAWB.Localizar(aParam: array of variant): TFDQuery;
var
FDQuery: TFDQuery;
begin
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_awb = :id_awb');
FDQuery.ParamByName('id_awb').AsInteger := aParam[1];
end;
if aParam[0] = 'REMESSAAWB1' then
begin
FDQuery.SQL.Add('where num_remessa = :num_remessa and cod_awb1 = :cod_awb1');
FDQuery.ParamByName('num_remessa').AsString := aParam[1];
FDQuery.ParamByName('cod_awb1').AsString := aParam[2];
end;
if aParam[0] = 'REMESSAAWB2' then
begin
FDQuery.SQL.Add('where num_remessa = :num_remessa and cod_awb2 = :cod_awb2');
FDQuery.ParamByName('num_remessa').AsString := aParam[1];
FDQuery.ParamByName('cod_awb2').AsString := aParam[2];
end;
if aParam[0] = 'REMESSA' then
begin
FDQuery.SQL.Add('where num_remessa = :num_remessa');
FDQuery.ParamByName('num_remessa').AsString := aParam[1];
end;
if aParam[0] = 'AWB1' then
begin
FDQuery.SQL.Add('where cod_awb1 like :des_roteiro');
FDQuery.ParamByName('des_roteiro').AsString := aParam[1];
end;
if aParam[0] = 'AWB2' then
begin
FDQuery.SQL.Add('where cod_awb2 = :cod_awb2');
FDQuery.ParamByName('cod_awb2').AsString := aParam[1];
end;
if aParam[0] = 'CEP' then
begin
FDQuery.SQL.Add('where num_cep = :num_cep');
FDQuery.ParamByName('num_cep').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open;
if FDQuery.IsEmpty then
begin
ClearSelf;
end
else
begin
SetupSelf(FDQuery);
end;
Result := FDQuery;
end;
function TControleAWB.LocalizarExato(aParam: array of variant): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
if Length(aParam) < 2 then Exit;
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select * from ' + TABLENAME);
if aParam[0] = 'ID' then
begin
FDQuery.SQL.Add('where id_awb = :id_awb');
FDQuery.ParamByName('id_awb').AsInteger := aParam[1];
end;
if aParam[0] = 'REMESSAAWB1' then
begin
FDQuery.SQL.Add('where num_remessa = :num_remessa and cod_awb1 = :cod_awb1');
FDQuery.ParamByName('num_remessa').AsString := aParam[1];
FDQuery.ParamByName('cod_awb1').AsString := aParam[2];
end;
if aParam[0] = 'REMESSAAWB2' then
begin
FDQuery.SQL.Add('where num_remessa = :num_remessa and cod_awb2 = :cod_awb2');
FDQuery.ParamByName('num_remessa').AsString := aParam[1];
FDQuery.ParamByName('cod_awb2').AsString := aParam[2];
end;
if aParam[0] = 'REMESSA' then
begin
FDQuery.SQL.Add('where num_remessa = :num_remessa');
FDQuery.ParamByName('num_remessa').AsString := aParam[1];
end;
if aParam[0] = 'AWB1' then
begin
FDQuery.SQL.Add('where cod_awb1 like :des_roteiro');
FDQuery.ParamByName('des_roteiro').AsString := aParam[1];
end;
if aParam[0] = 'AWB2' then
begin
FDQuery.SQL.Add('where cod_awb2 = :cod_awb2');
FDQuery.ParamByName('cod_awb2').AsString := aParam[1];
end;
if aParam[0] = 'CEP' then
begin
FDQuery.SQL.Add('where num_cep = :num_cep');
FDQuery.ParamByName('num_cep').AsString := aParam[1];
end;
if aParam[0] = 'FILTRO' then
begin
FDQuery.SQL.Add('where ' + aParam[1]);
end;
if aParam[0] = 'APOIO' then
begin
FDQuery.SQL.Clear;
FDQuery.SQL.Add('select ' + aParam[1] + ' from ' + TABLENAME + ' ' + aParam[2]);
end;
FDQuery.Open;
if FDQuery.IsEmpty then
begin
ClearSelf;
Exit;
end
else
begin
SetupSelf(FDQuery);
end;
Result := True;
finally
FDQuery.Connection.Close;
FDQuery.Free
end;
end;
procedure TControleAWB.SetupSelf(fdQuery: TFDQuery);
begin
Self.ID := fdQuery.FieldByName('id_awb').AsInteger;
Self.Remessa := fdQuery.FieldByName('num_remessa').AsString;
Self.AWB1 := fdQuery.FieldByName('cod_awb1').AsString;
Self.AWB2 := fdQuery.FieldByName('cod_awb2').AsString;
Self.CEP := fdQuery.FieldByName('num_cep').AsString;
Self.Operacao := fdQuery.FieldByName('cod_operacao').AsString;
Self.Tipo := fdQuery.FieldByName('cod_tipo').AsInteger;
Self.Peso := fdQuery.FieldByName('qtd_peso').AsFloat;
end;
end.
|
unit uReturSupplier;
interface
uses
uModel, uPenerimaanBarang, uSupplier, System.Classes, System.SysUtils, System.Generics.Collections;
type
{$TYPEINFO ON}
TReturSupplierItem = class;
TReturSupplier = class(TAppObject)
private
FCabang: TCabang;
FDiskon: Double;
FGudang: TGudang;
FIsJurnalized: Integer;
FKeterangan: string;
FNoBukti: string;
FPenerimaanBarang: TPenerimaanBarang;
FPeriode: Integer;
FPPN: Double;
FReturSupplierItems: TObjectList<TReturSupplierItem>;
FSubTotal: Double;
FSupplier: TSupplier;
FTglBukti: TDatetime;
FTotal: Double;
function GetDiskon: Double;
function GetPPN: Double;
function GetReturSupplierItems: TObjectList<TReturSupplierItem>;
function GetSubTotal: Double;
function GetTotal: Double;
procedure SetKeterangan(const Value: string);
procedure SetTglBukti(const Value: TDatetime);
public
published
property Cabang: TCabang read FCabang write FCabang;
property Diskon: Double read GetDiskon write FDiskon;
property Gudang: TGudang read FGudang write FGudang;
property IsJurnalized: Integer read FIsJurnalized write FIsJurnalized;
property Keterangan: string read FKeterangan write SetKeterangan;
property NoBukti: string read FNoBukti write FNoBukti;
property PenerimaanBarang: TPenerimaanBarang read FPenerimaanBarang write
FPenerimaanBarang;
property Periode: Integer read FPeriode write FPeriode;
property PPN: Double read GetPPN write FPPN;
property ReturSupplierItems: TObjectList<TReturSupplierItem> read
GetReturSupplierItems write FReturSupplierItems;
property SubTotal: Double read GetSubTotal write FSubTotal;
property Supplier: TSupplier read FSupplier write FSupplier;
property TglBukti: TDatetime read FTglBukti write SetTglBukti;
property Total: Double read GetTotal write FTotal;
end;
//type
TReturSupplierItem = class(TAppObjectItem)
{$TYPEINFO OFF}
private
FBarang: TBarang;
FDiskon: Double;
FHargaBeli: Double;
FReturSupplier: TReturSupplier;
FPPN: Double;
FQty: Double;
FUOM: TUOM;
FKonversi : Double;
function GetHargaSetelahDiskon: Double;
public
function GetHeaderField: string; override;
procedure SetHeaderProperty(AHeaderProperty : TAppObject); override;
published
property Barang: TBarang read FBarang write FBarang;
property Diskon: Double read FDiskon write FDiskon;
property HargaBeli: Double read FHargaBeli write FHargaBeli;
property HargaSetelahDiskon: Double read GetHargaSetelahDiskon;
property ReturSupplier: TReturSupplier read FReturSupplier write FReturSupplier;
property PPN: Double read FPPN write FPPN;
property Qty: Double read FQty write FQty;
property UOM: TUOM read FUOM write FUOM;
property Konversi : Double read FKonversi write FKonversi;
end;
implementation
function TReturSupplier.GetDiskon: Double;
var
dLineDisc: Double;
I: Integer;
begin
FDiskon := 0;
for I := 0 to ReturSupplierItems.Count - 1 do
begin
dLineDisc := ReturSupplierItems[i].Qty *
ReturSupplierItems[i].HargaBeli *
ReturSupplierItems[i].Diskon / 100;
FDiskon := FDiskon + dLineDisc;
end;
Result := FDiskon;
end;
function TReturSupplier.GetPPN: Double;
var
dLinePPN: Double;
I: Integer;
begin
FPPN := 0;
for I := 0 to ReturSupplierItems.Count - 1 do
begin
dLinePPN := ReturSupplierItems[i].Qty *
ReturSupplierItems[i].HargaBeli *
(100 - ReturSupplierItems[i].Diskon) / 100 *
ReturSupplierItems[i].PPN / 100;
FPPN := FPPN + dLinePPN;
end;
Result := FPPN;
end;
function TReturSupplier.GetReturSupplierItems: TObjectList<TReturSupplierItem>;
begin
if FReturSupplierItems =nil then
FReturSupplierItems := TObjectList<TReturSupplierItem>.Create(True);
Result := FReturSupplierItems;
end;
function TReturSupplier.GetSubTotal: Double;
var
dLinePrice: Double;
I: Integer;
begin
FSubTotal := 0;
for I := 0 to ReturSupplierItems.Count - 1 do
begin
dLinePrice := ReturSupplierItems[i].Qty *
ReturSupplierItems[i].HargaBeli;
FSubTotal := FSubTotal + dLinePrice;
end;
Result := FSubTotal;
end;
function TReturSupplier.GetTotal: Double;
begin
FTotal := SubTotal - Diskon + PPN;
Result := FTotal;
end;
procedure TReturSupplier.SetKeterangan(const Value: string);
begin
FKeterangan := Value;
end;
procedure TReturSupplier.SetTglBukti(const Value: TDatetime);
begin
FTglBukti := Value;
Periode := StrToInt(FormatDateTime('YYYYMM', Value));
end;
function TReturSupplierItem.GetHargaSetelahDiskon: Double;
begin
Result := HargaBeli * (100 - Diskon) / 100;
end;
function TReturSupplierItem.GetHeaderField: string;
begin
Result := 'ReturSupplier';
end;
procedure TReturSupplierItem.SetHeaderProperty(AHeaderProperty : TAppObject);
begin
ReturSupplier := TReturSupplier(AHeaderProperty);
end;
end.
|
{$include lem_directives.inc}
unit LemStyle;
interface
uses
Classes,
{$ifdef flexi}LemDosStructures,{$endif}
LemLevel, LemGraphicSet, LemAnimationSet, LemLevelSystem, LemMusicSystem;
type
TBaseLemmingStyle = class(TPersistent)
published
private
protected
fStyleName : string;
fStyleDescription : string;
fCommonPath : string;
fAnimationSet : TBaseAnimationSet;
fLevelSystem : TBaseLevelSystem;
fMusicSystem : TBaseMusicSystem;
function DoCreateAnimationSet: TBaseAnimationSet; virtual;
function DoCreateLevelSystem: TBaseLevelSystem; virtual;
function DoCreateMusicSystem: TBaseMusicSystem; virtual;
public
{$ifdef flexi}SysDat : TSysDatRec;{$endif}
constructor Create;
destructor Destroy; override;
function CreateGraphicSet: TBaseGraphicSet; virtual;
property AnimationSet: TBaseAnimationSet read fAnimationSet;
property LevelSystem: TBaseLevelSystem read fLevelSystem;
property MusicSystem: TBaseMusicSystem read fMusicSystem;
published
property StyleName: string read fStyleName write fStyleName;
property StyleDescription: string read fStyleDescription write fStyleDescription;
property CommonPath: string read fCommonPath write fCommonPath;
end;
implementation
{ TBaseLemmingStyle }
constructor TBaseLemmingStyle.Create;
begin
inherited Create;
fAnimationSet := DoCreateAnimationSet;
fLevelSystem := DoCreateLevelSystem;
fMusicSystem := DoCreateMusicSystem;
end;
function TBaseLemmingStyle.CreateGraphicSet: TBaseGraphicSet;
begin
Result := nil;
end;
destructor TBaseLemmingStyle.Destroy;
begin
fAnimationSet.Free;
fLevelSystem.Free;
fMusicSystem.Free;
inherited;
end;
function TBaseLemmingStyle.DoCreateAnimationSet: TBaseAnimationSet;
begin
Result := nil;
end;
function TBaseLemmingStyle.DoCreateLevelSystem: TBaseLevelSystem;
begin
Result := nil;
end;
function TBaseLemmingStyle.DoCreateMusicSystem: TBaseMusicSystem;
begin
Result := nil;
end;
end.
(*
TStyleParamsRec = record
Resolution : Single;
LevelWidth : Integer;
LevelHeight : Integer;
MultiPacks : Integer;
end;
*)
(* with aParams do
begin
Resolution := 2.0;
LevelWidth := 3200;
LevelHeight := 320;
MultiPacks := True;
end;
*)
(*
TLevelInfo = class(TCollectionItem)
private
function GetOwnerSection: TPackSection;
protected
fTrimmedTitle : string; // the title: this is only for display purposes.
fDosLevelPackFileName : string; // dos file where we can find this level (levelxxx.dat)
fDosLevelPackIndex : Integer; // dos file position in doslevelpackfilename(in fact: which decompression section)
fDosIsOddTableClone : Boolean; // true if this is a cloned level with other title and skills
fDosOddTableFileName : string; // only dosorig: oddtable.dat
fDosOddTableIndex : Integer; // were can we find this other title and skills in the dosoddtable file
fOwnerFile : string; // lemmini: lemmini ini file containing this level
public
property OwnerSection: TPackSection read GetOwnerSection;
published
// stylename --> for tracing the style
property TrimmedTitle: string read fTrimmedTitle write fTrimmedTitle;
property DosLevelPackFileName: string read fDosLevelPackFileName write fDosLevelPackFileName;
property DosLevelPackIndex: Integer read fDosLevelPackIndex write fDosLevelPackIndex;
property DosIsOddTableClone: Boolean read fDosIsOddTableClone write fDosIsOddTableClone;
property DosOddTableFileName: string read fDosOddTableFileName write fDosOddTableFileName;
property DosOddTableIndex: Integer read fDosOddTableIndex write fDosOddTableIndex;
property OwnerFile: string read fOwnerFile write fOwnerFile;
end;
*)
(*type
TLoadProperties = class(TPersistent)
private
fPath: string;
protected
public
published
property Path: string read fPath write fPath;
end;
*)
|
unit ufrPlugins;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls,
FMX.ListView.Types, FMX.Menus, FMX.StdActns, FMX.MediaLibrary.Actions,
System.Actions, FMX.ActnList, FMX.ListView,
uPlugin;
type
TfrPlugins = class(TFrame)
lvPlugins: TListView;
actlst: TActionList;
actLoadPlugins: TAction;
actEditCurrent: TAction;
actAddPlugin: TAction;
actSavePlugins: TAction;
TakePhotoFromLibraryAction: TTakePhotoFromLibraryAction;
pmEdit: TPopupMenu;
menuAdd: TMenuItem;
menuEdit: TMenuItem;
menuLoad: TMenuItem;
menuSave: TMenuItem;
dlgOpen: TOpenDialog;
procedure actAddPluginExecute(Sender: TObject);
procedure actEditCurrentExecute(Sender: TObject);
procedure actLoadPluginsExecute(Sender: TObject);
procedure actSavePluginsExecute(Sender: TObject);
procedure lvPluginsChange(Sender: TObject);
procedure pmEditPopup(Sender: TObject);
private
{ Private declarations }
procedure LaodListView;
procedure ChangeCurrent(index : Integer);
function GetCurrentPlugin: TPlugin;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property CurrentPlugin : TPlugin read GetCurrentPlugin;
end;
implementation
uses
uUtils, OpenViewUrl,
uPluginEdit;
const
filePlugins : string = 'filePlugins.plg';
var
FPlugins : TPlugins;
{$R *.fmx}
{ TFrame1 }
{------------------------------------------------------------------------------}
procedure TfrPlugins.actAddPluginExecute(Sender: TObject);
var
fPluginEdit : TfPluginEdit;
begin
fPluginEdit := TfPluginEdit.Create(self);
try
if fPluginEdit.ShowModal = mrOk then
begin
FPlugins.Add(fPluginEdit.FPlugin);
LaodListView;
end;
finally
FreeAndNil(fPluginEdit);
end;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.actEditCurrentExecute(Sender: TObject);
var
fPluginEdit : TfPluginEdit;
begin
fPluginEdit := TfPluginEdit.Create(self);
try
fPluginEdit.LoadPLugin(FPlugins.Current);
if fPluginEdit.ShowModal = mrOk then
LaodListView;
finally
FreeAndNil(fPluginEdit);
end;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.actLoadPluginsExecute(Sender: TObject);
begin
if dlgOpen.Execute then
FPlugins.FileName := dlgOpen.FileName;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.actSavePluginsExecute(Sender: TObject);
begin
FPlugins.SaveToFile;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.ChangeCurrent(index: Integer);
begin
lvPlugins.ItemIndex := index;
end;
{------------------------------------------------------------------------------}
constructor TfrPlugins.Create(AOwner: TComponent);
begin
inherited;
FPlugins := TPlugins.Create(uUtils.GetPath + filePlugins);
FPlugins.OnChangeCurrent := ChangeCurrent;
LaodListView;
end;
{------------------------------------------------------------------------------}
destructor TfrPlugins.Destroy;
begin
FPlugins.SaveToFile;
FreeAndNil(FPlugins);
inherited;
end;
{------------------------------------------------------------------------------}
function TfrPlugins.GetCurrentPlugin: TPlugin;
begin
Result := FPlugins.Current;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.LaodListView;
var
plugin : TPlugin;
item : TListViewItem;
begin
lvPlugins.BeginUpdate;
lvPlugins.ClearItems;
for plugin in FPlugins do
begin
item := lvPlugins.Items.Add;
item.Text := plugin.FName;
item.Bitmap := plugin.FIcon;
end;
lvPlugins.EndUpdate;
if not FPlugins.IsEmpty then
FPlugins.ItemIndex := 0;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.lvPluginsChange(Sender: TObject);
begin
FPlugins.ItemIndex := lvPlugins.ItemIndex;
end;
{------------------------------------------------------------------------------}
procedure TfrPlugins.pmEditPopup(Sender: TObject);
begin
menuEdit.Visible := FPlugins.ItemIndex > -1;
end;
{------------------------------------------------------------------------------}
end.
|
{
TForge Library
Copyright (c) Sergey Kasandrov 1997, 2018
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.
-------------------------------------------------------------------------
# exports:
Valid3DesAlgID, Get3DesInstance
}
unit tf3DesGetter;
{$I TFL.inc}
interface
uses
tfTypes, tfCipherInstances, tfBlockCiphers, tfDesCiphers;
function Valid3DesAlgID(AlgID: TAlgID): Boolean;
function Get3DesInstance(var A: Pointer; AlgID: TAlgID): TF_RESULT;
implementation
uses
tfRecords, tfHelpers, tfCipherHelpers;
const
Des3EcbVTable: TCipherHelper.TVTable = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
@TDes3Instance.Burn,
@TDes3Instance.Clone,
@TDes3Instance.ExpandKey,
@TCipherInstance.ExpandKeyIV,
@TCipherInstance.ExpandKeyNonce,
@TCipherInstance.GetBlockSize64,
@TBlockCipherInstance.EncryptUpdateECB,
@TBlockCipherInstance.DecryptUpdateECB,
@TDes3Instance.EncryptBlock,
@TDes3Instance.EncryptBlock,
@TCipherInstance.BlockMethodStub,
@TCipherInstance.DataMethodStub,
@TBlockCipherInstance.EncryptECB,
@TBlockCipherInstance.DecryptECB,
@TCipherInstance.IsBlockCipher,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TBlockCipherInstance.SetIV,
@TBlockCipherInstance.SetNonce,
@TBlockCipherInstance.GetIV,
@TBlockCipherInstance.GetNonce,
@TBlockCipherInstance.GetIVPointer,
@TCipherInstance.SetKeyDir,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub
);
Des3CbcVTable: TCipherHelper.TVTable = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
@TDes3Instance.Burn,
@TDes3Instance.Clone,
@TDes3Instance.ExpandKey,
@TCipherInstance.ExpandKeyIV,
@TCipherInstance.ExpandKeyNonce,
@TCipherInstance.GetBlockSize64,
@TBlockCipherInstance.EncryptUpdateCBC,
@TBlockCipherInstance.DecryptUpdateCBC,
@TDes3Instance.EncryptBlock,
@TDes3Instance.EncryptBlock,
@TCipherInstance.BlockMethodStub,
@TCipherInstance.DataMethodStub,
@TBlockCipherInstance.EncryptCBC,
@TBlockCipherInstance.DecryptCBC,
@TCipherInstance.IsBlockCipher,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TBlockCipherInstance.SetIV,
@TBlockCipherInstance.SetNonce,
@TBlockCipherInstance.GetIV,
@TBlockCipherInstance.GetNonce,
@TBlockCipherInstance.GetIVPointer,
@TCipherInstance.SetKeyDir,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub
);
Des3CfbVTable: TCipherHelper.TVTable = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
@TDes3Instance.Burn,
@TDes3Instance.Clone,
@TDes3Instance.ExpandKey,
@TCipherInstance.ExpandKeyIV,
@TCipherInstance.ExpandKeyNonce,
@TCipherInstance.GetBlockSize64,
@TBlockCipherInstance.EncryptUpdateCFB,
@TBlockCipherInstance.DecryptUpdateCFB,
@TDes3Instance.EncryptBlock,
@TDes3Instance.EncryptBlock,
@TCipherInstance.BlockMethodStub,
@TCipherInstance.DataMethodStub,
@TBlockCipherInstance.EncryptCFB,
@TBlockCipherInstance.DecryptCFB,
@TCipherInstance.IsBlockCipher,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TBlockCipherInstance.SetIV,
@TBlockCipherInstance.SetNonce,
@TBlockCipherInstance.GetIV,
@TBlockCipherInstance.GetNonce,
@TBlockCipherInstance.GetIVPointer,
@TCipherInstance.SetKeyDir,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub
);
Des3OfbVTable: TCipherHelper.TVTable = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
@TDes3Instance.Burn,
@TDes3Instance.Clone,
@TDes3Instance.ExpandKey,
@TCipherInstance.ExpandKeyIV,
@TCipherInstance.ExpandKeyNonce,
@TCipherInstance.GetBlockSize64,
@TBlockCipherInstance.EncryptUpdateOFB,
@TBlockCipherInstance.EncryptUpdateOFB,
@TDes3Instance.EncryptBlock,
@TDes3Instance.EncryptBlock,
@TCipherInstance.BlockMethodStub,
@TCipherInstance.DataMethodStub,
@TBlockCipherInstance.EncryptOFB,
@TBlockCipherInstance.EncryptOFB,
@TCipherInstance.IsBlockCipher,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TCipherInstance.IncBlockNoStub,
@TBlockCipherInstance.SetIV,
@TBlockCipherInstance.SetNonce,
@TBlockCipherInstance.GetIV,
@TBlockCipherInstance.GetNonce,
@TBlockCipherInstance.GetIVPointer,
@TCipherInstance.SetKeyDir,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub
);
Des3CtrVTable: TCipherHelper.TVTable = (
@TForgeInstance.QueryIntf,
@TForgeInstance.Addref,
@TForgeInstance.SafeRelease,
@TDes3Instance.Burn,
@TDes3Instance.Clone,
@TDes3Instance.ExpandKey,
@TCipherInstance.ExpandKeyIV,
@TCipherInstance.ExpandKeyNonce,
@TCipherInstance.GetBlockSize64,
@TBlockCipherInstance.EncryptUpdateCTR,
@TBlockCipherInstance.EncryptUpdateCTR,
@TDes3Instance.EncryptBlock,
@TDes3Instance.EncryptBlock,
@TBlockCipherInstance.GetKeyBlockCTR,
@TBlockCipherInstance.GetKeyStreamCTR,
@TBlockCipherInstance.EncryptCTR,
@TBlockCipherInstance.EncryptCTR,
@TCipherInstance.IsBlockCipher,
@TBlockCipherInstance.IncBlockNoCTR,
@TBlockCipherInstance.DecBlockNoCTR,
@TBlockCipherInstance.SkipCTR,
@TBlockCipherInstance.SetIV,
@TBlockCipherInstance.SetNonce,
@TBlockCipherInstance.GetIV,
@TBlockCipherInstance.GetNonce,
@TBlockCipherInstance.GetIVPointer,
@TCipherInstance.SetKeyDir,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub,
@TCipherInstance.DataMethodStub
);
function Valid3DesAlgID(AlgID: TAlgID): Boolean;
begin
Result:= False;
case AlgID and TF_KEYMODE_MASK of
TF_KEYMODE_ECB,
TF_KEYMODE_CBC:
case AlgID and TF_PADDING_MASK of
TF_PADDING_DEFAULT,
TF_PADDING_NONE,
TF_PADDING_ZERO,
TF_PADDING_ANSI,
TF_PADDING_PKCS,
TF_PADDING_ISO: Result:= True;
end;
TF_KEYMODE_CFB,
TF_KEYMODE_OFB,
TF_KEYMODE_CTR:
case AlgID and TF_PADDING_MASK of
TF_PADDING_DEFAULT,
TF_PADDING_NONE: Result:= True;
end;
end;
end;
function GetVTable(AlgID: TAlgID): Pointer;
begin
case AlgID and TF_KEYMODE_MASK of
TF_KEYMODE_ECB: Result:= @Des3EcbVTable;
TF_KEYMODE_CBC: Result:= @Des3CbcVTable;
TF_KEYMODE_CFB: Result:= @Des3CfbVTable;
TF_KEYMODE_OFB: Result:= @Des3OfbVTable;
TF_KEYMODE_CTR: Result:= @Des3CtrVTable;
else
Result:= nil;
end;
end;
function Get3DesInstance(var A: Pointer; AlgID: TAlgID): TF_RESULT;
var
Tmp: PCipherInstance;
LVTable: Pointer;
begin
if not Valid3DesAlgID(AlgID) then begin
Result:= TF_E_INVALIDARG;
Exit;
end;
LVTable:= GetVTable(AlgID);
try
Tmp:= AllocMem(SizeOf(TDes3Instance));
Tmp.FVTable:= LVTable;
Tmp.FRefCount:= 1;
Tmp.FAlgID:= AlgID;
TForgeHelper.Free(A);
A:= Tmp;
Result:= TF_S_OK;
except
Result:= TF_E_OUTOFMEMORY;
end;
end;
end.
|
unit FindForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, ToolEdit;
type
TFindMainForm = class(TForm)
StartButton: TButton;
FindDriSelector: TDirectoryEdit;
Progress: TLabel;
procedure StartButtonClick(Sender: TObject);
private
{ Private declarations }
procedure FindDocument(aFindEVD: Boolean);
public
{ Public declarations }
end;
var
FindMainForm: TFindMainForm;
implementation
uses
DateUtils,
Document_Const,
l3Types,
l3Filer,
l3Base,
l3FileUtils,
k2Types,
k2Tags,
k2Reader,
k2TagGen,
k2TagTerminator,
evTableCheckerFilter,
evdReader,
ddNSRC_r,
ddUtils;
{$R *.dfm}
type
TevCustomFileParserHack = class(Tk2CustomFileParser);
procedure TFindMainForm.FindDocument(aFindEVD: Boolean);
const
csEVDMask = '*.evd';
csNSRCMask = '*.nsr';
var
l_SR : TSearchRec;
l_Mask : AnsiString;
l_Start : TDateTime;
l_Count : Integer;
l_Filer : Tl3CustomFiler;
l_Reader : Tk2CustomFileParser;
l_Generator : Tk2TagGenerator;
begin
if aFindEVD then
begin
l_Reader:= TevdNativeReader.Create(nil);
l_Mask := csEVDMask;
end // if aFindEVD then
else
begin
l_Reader:= TCustomNSRCReader.Create(nil);
l_Mask := csNSRCMask;
end;
try
l_Filer := Tl3DOSFiler.Create(nil);
try
l_Generator := nil;
TevTableCheckerFilter.SetTo(l_Generator);
(l_Reader As Ik2TagGeneratorChainEnd).Link(l_Generator);
try
l_Reader.Filer := l_Filer;
l_Start := Now;
l_Count := 0;
if FindFirst(ConcatDirName(FindDriSelector.Text, l_Mask), faAnyFile, l_SR) = 0 then
repeat
if l_SR.Attr and faDirectory <> faDirectory then
begin
Inc(l_Count);
Tl3DOSFiler(l_Filer).FileName := ConcatDirName(FindDriSelector.Text, l_SR.Name);
g_SetDocName(Tl3DOSFiler(l_Filer).FileName);
l_Filer.Open;
l_Reader.Start;
try
TevCustomFileParserHack(l_Reader).Read;
finally
l_Reader.Finish;
end;
l_Filer.Close;
end; // l_SR.Attr and faDirectory <> faDirectory
until FindNext(l_SR) <> 0;
Progress.Caption := 'Проверили...';
FindClose(l_SR);
finally
l3Free(l_Generator);
end;
finally
l3Free(l_Filer);
end;
finally
l3Free(l_Reader);
end;
end;
procedure TFindMainForm.StartButtonClick(Sender: TObject);
begin
Progress.Caption := '';
l3system.Msg2Log('');
l3system.Msg2Log('__________Start____________');
FindDocument(True);
FindDocument(False);
end;
end.
|
unit RasterImageCommands;
interface
uses classes,command_class_lib,Image_on_demand,pngImageAdvanced,graphics,types;
type
TRasterImageDocumentCommand = class (TAbstractTreeCommand)
public
function GetDoc: TRasterImageDocument;
end;
TPatchImageCommand = class (TRasterImageDocumentCommand)
//базовая команда при работе с растровыми изображениями
//GetBounds выставляет предварительные размеры прямоугольника, где произойдет действие
//если была палитра, преобразуем картинку в RGB или Grayscale, уж больно неудобно
//с палитрой обращаться.
//и при вызове Execute картинка из него будет сохранена в fDiff, и вызван internalExecute
//в потомках описываем internalExecute - как изменить изображение
//он может в числе прочего поменять формат всего изображения.
//при этом для каждой измененной точки внутри прямоуг. вызываем PointChanged, тем самым
//находим минимально необх. прямоугольник, который нужен для undo.
// (либо, назначаем fUpdateRect самостоятельно)
//далее, Top/Left принимают окончательное значение.
//наконец, вызывается UndoPrediction, который пытается, располагая только результирующей
//картинкой и свойствами команды, которые сохраняются в файл (не считая fDiff), восстановить
//(предсказать) исходное изображение. Если это реализовано, то из fDiff будет вычтен fPredictor.
//UndoPrediction имеет право узнать ColorMode и BitDepth.
//при исполнении Undo первым делом запускается UndoPrediction, который дает ровно то же
//предсказанное изображение, что и раньше. Его мы прибавляем к загруженному fDiff.
//если формат изображения в документе поменялся и fDiff не занимает всю его область,
//то мы приводим его к старому формату, за исключением, возможно, измененной области
//наконец, мы "вклеиваем" на место fDiff.
protected
fDiff: TExtendedPngObject;
fPredictor: TExtendedPngObject;
fRect,fUpdateRect: TRect; //расположение заплатки и вычисление мин. необх.
fOldBitDepth,fOldColorType: Byte;
fImageFormatChanged: Boolean;
fSizeChanged: Boolean;
fOldHeight,fOldWidth: Integer;
procedure SetOldBitDepth(value: Byte);
procedure SetOldColorType(value: Byte);
procedure GetBounds; virtual; abstract;//инициализировать fLeft,fTop,fRight,fBottom
procedure PointChanged(const x,y: Integer); //вызывается из потомка,
// если в (x,y) произошли изменения, нужна для нахождения минимального прямоуг.
function UndoPrediction: Boolean; virtual; //false означает
//что мы ничего не можем предсказать, поэтому оставляем картинку как есть
function InternalExecute: Boolean; virtual; abstract; //false означает,
//что применение команды ничего не изменило и ее стоит изъять из дерева
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean; override;
function Undo: Boolean; override;
published
property diff: TExtendedPngObject read fDiff write fDiff stored fActiveBranch;
property Left: Integer read fRect.Left write fRect.Left;
property Top: Integer read fRect.Top write fRect.Top;
property Width: Integer read fOldWidth write fOldWidth stored fSizeChanged;
property Height: Integer read fOldHeight write fOldHeight stored fSizeChanged;
property BitDepth: Byte read fOldBitDepth write SetOldBitDepth;
property ColorType: Byte read fOldColorType write SetOldColorType default 255;
//на всякий случай, BitDepth и ColorType сохраняем всегда, "не утянет"
//потом подумаем, нельзя ли иногда схалявить
end;
TWordPoint=record
case Integer of
0: (X,Y: Word);
1: (AsPointer: Pointer);
end;
TPixelBelongsToBrushFunc = function (x,y: Integer): Boolean of object;
TBrushCommand = class (TPatchImageCommand)
private
fR2: Integer;
fBrushColor: TColor;
fBrushSize: Word;
fBrushShape: TBrushShape;
fBelongFunc: TPixelBelongsToBrushFunc;
fPoints: TList;
fColorExistsInPalette: Boolean; //есть ли готовый индекс для цвета, которым
//закрашиваем
fNeedToChangeBitDepth: Boolean; //и палитра набита под завязку, придется бит/пиксель повышать
fNewBitDepth: Byte;
fNewColorMode: Byte;
fColorIndex: Cardinal; //от 1 бита до 24 бит, по обстоятельствам
// fRect: TRect;
fPointsReduced: Boolean; //отметка, что не нужно шерстить набор точек по-новой
procedure ReadPointsAsText(reader: TReader);
procedure WritePointsAsText(writer: TWriter);
procedure WritePoints(stream: TStream);
procedure ReadPoints(stream: TStream);
procedure ReducePoints;
procedure FigureAboutColorsAndBitdepth;
procedure SetBrushSize(value: Word);
procedure SetBrushShape(value: TBrushShape);
function PixelBelongsToRectBrush(x,y: Integer): Boolean;
function PixelBelongsToEvenRoundBrush(x,y: Integer): Boolean;
function PixelBelongsToOddRoundBrush(x,y: Integer): Boolean;
protected
procedure DefineProperties(filer: TFiler); override;
procedure GetBounds; override; //заполняет fRect
function UndoPrediction: Boolean; override;
//просто заносит текущее сост. прямоуг.
//тем самым не надо сохранять то, что не изменилось
public
constructor Create(aOwner: TComponent); override;
//поскольку он должен работать с документом (только для чтения) еще до
//исполнения DispatchCommand, передаём ему заблаговременно
destructor Destroy; override; //TList надо освободить
function Draw(aX,aY: Word): boolean; //один мазок кисти
//если хоть как-то меняется, заносим в fXPoints/fYPoints
function InternalExecute: Boolean; override;
published
property BrushColor: TColor read fBrushColor write fBrushColor;
property BrushSize: Word read fBrushSize write SetBrushSize;
property BrushShape: TBrushShape read fBrushShape write SetBrushShape;
end;
TSaveToJPEGCommand = class (TPatchImageCommand,ITerminalCommand)
protected
procedure GetBounds; override;
function UndoPrediction: Boolean; override;
public
function InternalExecute: Boolean; override;
function Caption: string; override;
end;
TArbitraryRotateCommand = class (TPatchImageCommand)
private
fAngle: Real;
protected
procedure GetBounds; override;
function UndoPrediction: Boolean; override;
public
constructor Create(aAngle: Real); reintroduce; overload;
function InternalExecute: Boolean; override;
function Caption: string; override;
published
property Angle: Real read fAngle write fAngle;
end;
TRotate90CWCommand = class (TRasterImageDocumentCommand)
public
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
end;
TRotate90CCWCommand = class (TRasterImageDocumentCommand)
public
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
end;
TRotate180Command = class (TRasterImageDocumentCommand)
public
function Execute: Boolean; override;
function Undo: Boolean; override;
function Caption: string; override;
end;
implementation
uses pngImage,gamma_function,sysUtils,simple_parser_lib,math,PNGImageIterators,
JPEG,strUtils;
(*
TRasterImageDocumentCommand
*)
function TRasterImageDocumentCommand.GetDoc: TRasterImageDocument;
begin
Result:=FindOwner as TRasterImageDocument;
end;
(*
TPatchImageCommand
*)
constructor TPatchImageCommand.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
fDiff:=TExtendedPngObject.Create; //будет сохраняться в файл
fOldColorType:=255;
fOldWidth:=-1;
fOldHeight:=-1;
end;
destructor TPatchImageCommand.Destroy;
begin
fDiff.Free;
inherited Destroy;
end;
procedure TPatchImageCommand.PointChanged(const X,Y: Integer);
begin
fUpdateRect.Left:=min(fUpdateRect.Left,X);
fUpdateRect.Right:=max(fUpdateRect.Right,X+1);
fUpdateRect.Top:=min(fUpdateRect.Top,Y);
fUpdateRect.Bottom:=max(fUpdateRect.Bottom,Y+1);
end;
procedure TPatchImageCommand.SetOldBitDepth(value: Byte);
begin
if fOldBitDepth<>value then begin
fOldBitDepth:=value;
fImageFormatChanged:=true;
end;
end;
procedure TPatchImageCommand.SetOldColorType(value: Byte);
begin
if fOldColorType<>value then begin
fOldColorType:=value;
fImageFormatChanged:=true;
end;
end;
function TPatchImageCommand.Execute: Boolean;
var doc: TRasterImageDocument;
btmp,tmp: TExtendedPNGObject;
src,dest: TPngObjectIterator;
begin
getBounds; //инициализирует fRect
doc:=GetDoc;
btmp:=doc.Btmp;
//избавимся от palette, если таковая имелась
if btmp.GetInMinimalGrayscaleOrRGB(tmp) then begin
doc.btmp.Free;
doc.btmp:=tmp;
btmp:=doc.Btmp;
end;
//вот это и примем за исходную картинку
fOldBitDepth:=btmp.Header.BitDepth;
fOldColorType:=btmp.Header.ColorType;
fOldWidth:=btmp.Width;
fOldHeight:=btmp.Height;
//обозначили заплатку
fDiff.Free;
fDiff:=TExtendedPNGObject.CreateBlank(Btmp.Header.ColorType,
Btmp.Header.BitDepth,fRect.Right-fRect.Left,fRect.Bottom-fRect.Top);
//палитра будет стандартной, если ColorType=COLOR_PALETTE
//перед сохранением необходимо присвоить реальную
// fDiff.Canvas.CopyRect(Rect(0,0,fDiff.Width,fDiff.Height),Doc.Btmp.Canvas,
// Rect(fLeft,fTop,fRight,fBottom));
//copyRect вроде быстрый, но не thread-safe (а мы хотим быть thread-safe, не знаю зачем)
//и кто его знает, что он там делает, этот stretchBlt
//так надежнее:
src:=btmp.CreateIteratorForCropped(fRect);
dest:=fDiff.CreateIterator;
assert(fRect.Right-fRect.Left=fDiff.width,'execute patch command: width not equal:'+IntToStr(fRect.Right-fRect.Left)+' and '+IntToStr(fDiff.Width));
assert(fRect.Bottom-fRect.Top=fDiff.height,'execute patch command: height not equal'+IntToStr(fRect.Bottom-fRect.Top)+' and '+IntToStr(fDiff.Height));
while not src.isEOF do
dest.WriteNextPixel(src.ReadNextPixel);
dest.Free;
src.Free;
//можно еще ввести какой-нибудь пакетный режим, чтоб ещё быстрее
//в fUpdateRect загоняем фактически -Inf и +Inf
fUpdateRect.Left:=fRect.Right;
fUpdateRect.Right:=fRect.Left-1;
fUpdateRect.Top:=fRect.Bottom;
fUpdateRect.Bottom:=fRect.Top-1;
//храним в fDiff копию того фрагмента, который начнем мучать
Result:=InternalExecute and not IsRectEmpty(fUpdateRect);
if Result then begin
if (btmp.Height<>fOldHeight) or (btmp.Width<>fOldWidth) then
fSizeChanged:=true;
//после InternalExecute еще могли поменяться границы
if (fRect.Left<>fUpdateRect.Left) or (fRect.Right<>fUpdateRect.Right)
or (fRect.Top<>fUpdateRect.Top) or (fRect.Bottom<>fUpdateRect.Bottom) then
begin
tmp:=fDiff;
fDiff:=TExtendedPNGObject.CreateBlank(tmp.Header.ColorType,
tmp.Header.BitDepth,fUpdateRect.Right-fUpdateRect.Left,fUpdateRect.Bottom-fUpdateRect.Top);
//и снова станд. палитра
src:=tmp.CreateIteratorForCropped(Rect(fUpdateRect.Left-fRect.Left,fUpdateRect.Top-fRect.Top,
fUpdateRect.Right-fRect.Left,fUpdateRect.Bottom-fRect.Top));
dest:=fDiff.CreateIterator;
while not src.isEOF do
dest.WriteNextPixel(src.ReadNextPixel);
dest.Free;
src.Free;
tmp.Free;
fRect:=fUpdateRect;
end;
//fPredictor должен иметь те же параметры ColorType,BitDepth, Width, Height
fPredictor:=TExtendedPngObject.CreateBlank(fDiff.Header.ColorType,
fDiff.Header.BitDepth,fDiff.Width,fDiff.Height);
//и у предиктора тоже палитра стандартная
if UndoPrediction then begin
//нарисует на Predictor исх. картинку исходя из того, что он
//может знать по конечному результату
//сейчас "скользкая" часть - вычесть одну картинку из другой
//RGB24 - надо вычитать по каждому цвету
//Grayscale - значение целиком
//Palette - значение целиком, адекватность должен обеспечить UndoPrediction
src:=fPredictor.CreateIterator;
dest:=fDiff.CreateIterator;
//that's how I sub.
while not src.isEOF do
dest.WriteNextSubpixel((dest.PeekNextSubpixel-src.ReadNextSubpixel) and 255);
//ох незадача, он же при "умном сохранении" может ужаться в плане цветности, тогда
//мы по нему не восстановим ориг. формат изобр.
//поэтому добавили свойства BitDepth и ColorType
dest.Free;
src.Free;
end;
fPredictor.Free;
//а на нет и суда нет
//наконец, сообщим документу, какую область мы изменили
doc.AddToChangeRect(fRect);
end;
//в противном случае команда вот-вот будет удалена, нет нужды освобождать
//память впереди паровоза
end;
function TPatchImageCommand.Undo: Boolean;
var doc: TRasterImageDocument;
src,dest: TPngObjectIterator;
tmp: TExtendedPngObject;
begin
//формируем прямоугольник, на котором произошли изменения. Его верхний угол хранится в Top/Left
//он по сути на месте, а по размерам заплатки восст. нижний правый угол
fRect.Bottom:=fRect.Top+fDiff.Height;
fRect.Right:=fRect.Left+fDiff.Width;
doc:=GetDoc;
doc.AddToChangeRect(fRect); //можно сразу сообщить, мы уже все знаем.
if ColorType=255 then ColorType:=doc.Btmp.Header.ColorType;//если формат не поменялся,
if BitDepth=0 then BitDepth:=doc.Btmp.Header.BitDepth;//мы его и не сохраняем!
//возможно, формат fDiff успел поменяться после сохранения, для уменьшения размера
if (fDiff.Header.BitDepth<>BitDepth) or (fDiff.Header.ColorType<>ColorType) then begin
tmp:=fDiff.GetInOtherFormat(ColorType,BitDepth);
fDiff.Free;
fDiff:=tmp;
end;
fPredictor:=TExtendedPngObject.CreateBlank(ColorType,BitDepth,fDiff.Width,fDiff.Height);
//если после вып. команды изображение изменило размеры, не спешим их возращать - для
//UndoPrediction оно нужно как есть!
if UndoPrediction then begin
//в прошлый раз вычитали fPredictor, теперь прибавим назад.
src:=fPredictor.CreateIterator;
dest:=fDiff.CreateIterator;
//that's how I add.
while not src.isEOF do
dest.WriteNextSubpixel((dest.PeekNextSubpixel+src.ReadNextSubpixel) and 255);
dest.Free;
src.Free;
end;
fPredictor.Free;
//а на нет и суда нет
//осталось вправить картинку на место
if ((fOldWidth<>-1) and (fOldWidth<>doc.Btmp.Width)) or
((fOldHeight<>-1) and (fOldHeight<>doc.Btmp.Height)) then
doc.Btmp.Resize(fOldWidth,fOldHeight);
if (doc.Btmp.Header.ColorType<>ColorType) or (doc.Btmp.Header.BitDepth<>BitDepth) then begin
tmp:=doc.Btmp.GetInOtherFormat(ColorType,BitDepth);
doc.Btmp.Free;
doc.Btmp:=tmp;
end;
src:=fDiff.CreateIterator;
dest:=doc.Btmp.CreateIteratorForCropped(fRect);
assert(fRect.Right-fRect.Left=fDiff.width,'undo patch: width not equal:'+IntToStr(fRect.Right-fRect.Left)+' and '+IntToStr(fDiff.Width));
assert(fRect.Bottom-fRect.Top=fDiff.height,'undo patch: height not equal'+IntToStr(fRect.Bottom-fRect.Top)+' and '+IntToStr(fDiff.Height));
while not src.isEOF do
dest.WriteNextPixel(src.ReadNextPixel);
dest.Free;
src.Free;
Result:=true;
end;
function TPatchImageCommand.UndoPrediction: Boolean;
begin
Result:=false;
end;
(*
TBrushCommand
*)
function BrushColorIsMonochrome(color: TColor; out index: Cardinal): boolean;
var rgbcol: RGBColor absolute color;
begin
Result:=(rgbcol.R=rgbcol.G) and (rgbcol.G=rgbcol.B);
if Result then index:=rgbcol.R;
end;
function BrushColorInMonochromePalette(color: TColor;aBitDepth: Byte; out index: Cardinal): boolean;
var rgbcol: RGBColor absolute color;
maxColorVal: Word;
begin
maxColorVal:=(1 shl aBitDepth)-1;
Result:= BrushColorIsMonochrome(color,index) and
(((index * maxColorVal div 255) * 255) div maxColorVal = index);
if Result then index:=(index*maxColorVal) div 255; //к примеру
end;
constructor TBrushCommand.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
fPoints:=TList.Create;
end;
procedure TBrushCommand.SetBrushSize(value: Word);
begin
fBrushSize:=value;
fR2:=Sqr((value-1) div 2);
if (value and 1) = 0 then
fR2:=fR2 + (value-1) div 2;
SetBrushShape(fBrushShape); //может поменяться
end;
procedure TBrushCommand.SetBrushShape(value: TBrushShape);
begin
fBrushShape:=value;
if value=bsSquare then fBelongFunc:=PixelBelongsToRectBrush
else if value=bsRound then
if fBrushSize div 2 = 0 then
fBelongFunc:=PixelBelongsToEvenRoundBrush
else
fBelongFunc:=PixelBelongsToOddRoundBrush;
end;
function TBrushCommand.PixelBelongsToRectBrush(x,y: Integer): Boolean;
begin
Result:=true;
end;
function TBrushCommand.PixelBelongsToEvenRoundBrush(x,y: Integer): Boolean;
begin
Result:=(Sqr(x)+Sqr(y)+x+y<fR2);
end;
function TBrushCommand.PixelBelongsToOddRoundBrush(x,y: Integer): Boolean;
begin
Result:=(Sqr(x)+Sqr(y)<fR2);
end;
procedure TBrushCommand.FigureAboutColorsAndBitdepth;
var btmp: TExtendedPNGObject;
fActualCount: Integer;
// p: Integer;
fFutureOwner: TRasterImageDocument;
//можно было бы обойтись и без него
begin
//философия такая: если есть возможность обойтись без переформатирования картинки,
//надо за неё цепляться
//но если все равно повышать количество бит на пиксель, то не жадничать, а сразу
//делать побольше, с запасом.
fFutureOwner:=GetDoc;
btmp:=fFutureOwner.Btmp;
case Btmp.Header.ColorType of
COLOR_RGB: begin
fColorExistsInPalette:=true;
fColorIndex:=TColorToRGBTriple(fBrushColor);
//ничего менять не надо!
end;
COLOR_GRAYSCALE: begin
fColorExistsInPalette:=
BrushColorInMonochromePalette(fBrushColor,Btmp.Header.BitDepth,fColorIndex);
if not fColorExistsInPalette then begin
//очень не хочется изменять биты/пиксель
fNeedToChangeBitDepth:=not Btmp.IsColorNumberLessThen(1 shl Btmp.Header.BitDepth, fActualCount);
if fNeedToChangeBitDepth then begin
fNewBitDepth:=8;
if BrushColorIsMonochrome(fBrushColor,fColorIndex) then
fNewColorMode:=COLOR_GRAYSCALE
else
fNewColorMode:=COLOR_RGB;
end
else begin
fNewColorMode:=COLOR_PALETTE;
fNewBitDepth:=Btmp.Header.BitDepth;
fColorIndex:=fActualCount;
end;
end;
end;
//COLOR_PALETTE никогда не появится, потому что TPatchImageCommand его не любит
else
Raise Exception.Create('sorry, alpha channel support under construction');
end;
end;
destructor TBrushCommand.Destroy;
begin
fPoints.Free;
inherited Destroy;
end;
procedure TBrushCommand.GetBounds;
var ourRect: TRect;
i: Integer;
p: TWordPoint;
begin
BrushColor:=GetDoc.PrimaryColor;
BrushSize:=Round(GetDoc.BrushSize/GetDoc.get_Scale);
BrushShape:=GetDoc.BrushShape;
fRect:=Rect(0,0,0,0);
for i:=0 to fPoints.Count-1 do begin
p.AsPointer:=fPoints[i];
ourRect:=Rect(p.X-fBrushSize div 2,p.Y-fBrushSize div 2,(p.X+(fBrushSize-1) div 2)+1, (p.Y+(fBrushSize-1) div 2)+1);
//вертикаль Left и горизонталь Top содержат изменившиеся пиксели,
//а Right и Bottom - нет.
CoverRect(fRect,ourRect);
end;
end;
function TBrushCommand.Draw(aX,aY: Word): Boolean;
var point: TWordPoint;
begin
point.X:=aX;
point.Y:=aY;
Result:=(fPoints.IndexOf(point.AsPointer)=-1);
if Result then begin
fPoints.Add(point.AsPointer);
end;
end;
procedure TBrushCommand.DefineProperties(filer: TFiler);
begin
// filer.DefineBinaryProperty('points',ReadPoints,WritePoints,true);
filer.DefineProperty('points',ReadPointsAsText,WritePointsAsText,true);
end;
procedure TBrushCommand.WritePoints(stream: TStream);
begin
end;
procedure TBrushCommand.ReadPoints(stream: TStream);
begin
end;
procedure TBrushCommand.WritePointsAsText(writer: TWriter);
var i: Integer;
cur: TWordPoint;
begin
ReducePoints;
writer.WriteListBegin;
for i:=0 to fPoints.Count-1 do begin
cur:=TWordPoint(fPoints[i]);
writer.WriteString('('+IntToStr(cur.X)+';'+IntToStr(cur.Y)+')');
end;
writer.WriteListEnd;
end;
procedure TBrushCommand.ReadPointsAsText(reader: TReader);
var p: TSimpleParser;
cur: TWordPoint;
begin
reader.ReadListBegin;
p:=TSimpleParser.Create;
fPoints.Clear;
while not reader.EndOfList do begin
p.AssignString(reader.ReadString);
p.getChar; //'('
cur.X:=p.getInt;
//; - это delimiter, его читать не надо.
cur.Y:=p.getInt;
fPoints.Add(cur.AsPointer);
end;
p.Free;
reader.ReadListEnd;
fPointsReduced:=true; //их еще давно редуцировали, перед сохранением!
end;
procedure TBrushCommand.ReducePoints;
var pix: array of array of Byte;
i,j,k: Integer;
offset: TWordPoint;
hasUniquePoint: boolean;
begin
if fPointsReduced then Exit;
GetBounds;
//надеемся малость подсократить количество точек
SetLength(pix,fRect.Right-fRect.Left,fRect.Bottom-fRect.Top);
for i:=0 to fPoints.Count-1 do begin
offset.AsPointer:=fPoints[i];
dec(offset.X,fRect.Left);
dec(offset.Y,fRect.Top);
for j:=-(fBrushSize div 2) to ((fBrushSize-1) div 2) do
for k:=-(fBrushSize div 2) to ((fBrushSize-1) div 2) do begin
Assert(offset.X+k>=0,'x<0');
Assert(offset.X+k<fRect.Right-fRect.Left,'x>=length');
Assert(offset.Y+j>=0,'y<0');
Assert(offset.Y+j<fRect.Bottom-fRect.Top,'y>=length');
if fBelongFunc(k,j) and (pix[offset.X+k,offset.Y+j]<255) then
inc(pix[offset.X+k,offset.Y+j])
end;
end; //определили, сколько раз "стирается" каждая точка.
for i:=fPoints.Count-1 downto 0 do begin //а теперь попробуем удалить хоть что-нибудь
offset.AsPointer:=fPoints[i];
dec(offset.X,fRect.Left);
dec(offset.Y,fRect.Top);
HasUniquePoint:=false;
for j:=-(fBrushSize div 2) to ((fBrushSize-1) div 2) do
for k:=-(fBrushSize div 2) to ((fBrushSize-1) div 2) do
if fBelongFunc(k,j) and (pix[offset.X+k,offset.Y+j]=1) then begin
HasUniquePoint:=true;
break;
end;
if not HasUniquePoint then begin
fPoints.Delete(i);
for j:=-(fBrushSize div 2) to ((fBrushSize-1) div 2) do
for k:=-(fBrushSize div 2) to ((fBrushSize-1) div 2) do
if fBelongFunc(k,j) then
dec(pix[offset.X+k,offset.Y+j]);
end;
end;
fPointsReduced:=true;
end;
function TBrushCommand.InternalExecute: Boolean;
var btmp: TExtendedPngObject;
dest: TPngObjectIterator;
i: Integer;
point: TWordPoint;
begin
Result:=fPoints.Count>0;
if not Result then exit;
//пока все выполняем в одной TBrushCommand,
//потом, когда новую команду будем делать, сообразим,
//как общие куски вынести в предка
FigureAboutColorsAndBitdepth;
fPointsReduced:=false; //отладка
ReducePoints;
btmp:=GetDoc.Btmp;
//бекап есть, теперь, если надо, переделываем изображение
if not fColorExistsInPalette then begin
// if fNeedToChangeBitDepth then begin
//коренное переформатирование
Btmp:=btmp.GetInOtherFormat(fNewColorMode,fNewBitDepth);
GetDoc.Btmp.Free;
GetDoc.Btmp:=Btmp;
// end
// else begin
// raise Exception.Create('convert to palette: dangerous procedure, may corrupt data');
// Btmp.ConvertToPalette;
// end;
if (fNewColorMode=COLOR_PALETTE) and (Btmp.GetColorIndex(fBrushColor)=-1) then
fColorIndex:=Btmp.AddToPalette(fBrushColor);
end;
//работаем кистью
for i:=0 to fPoints.Count-1 do begin
point:=TWordPoint(fPoints[i]);
dest:=btmp.CreateIteratorForCropped(Rect(point.X-fBrushSize div 2,point.Y-fBrushSize div 2,
point.X + (fBrushSize-1) div 2 + 1, point.Y+(fBrushSize-1) div 2 + 1));
while not dest.isEOF do
if fBelongFunc(dest.CurColumn-point.X,dest.CurLine-point.Y)
and (dest.PeekNextPixel<>fColorIndex) then begin
PointChanged(dest.CurColumn,dest.CurLine);
dest.WriteNextPixel(fColorIndex);
end
else
dest.SkipPixel;
dest.Free;
end;
end;
function TBrushCommand.UndoPrediction: Boolean;
var src,dest: TPngObjectIterator;
begin
src:=GetDoc.Btmp.CreateIteratorForCropped(fRect);
dest:=fPredictor.CreateIterator;
Result:=true;
//src такой же или "ширше", чем dest по цветам.
if ColorType=Color_GRAYSCALE then
while not src.isEOF do
dest.WriteNextAsGrayscale(src.ReadNextAsGrayscale)
else if ColorType=COLOR_RGB then
while not src.isEOF do
dest.WriteNextAsRGB(src.ReadNextAsRGB)
else
//других не поддерживает
Result:=false; //обеспечит корректную работу, но громоздкий DLRN
src.Free;
dest.Free;
end;
(*
TSaveToJPEGCommand
*)
procedure TSaveToJPEGCommand.GetBounds;
begin
fRect:=Rect(0,0,GetDoc.btmp.width,GetDoc.btmp.height);
end;
function TSaveToJPEGCommand.InternalExecute: Boolean;
var jpgImg: TJPEGImage;
btmp: TBitmap;
s,fn1: string;
begin
btmp:=TBitmap.Create;
try
GetDoc.Btmp.AssignTo(btmp);
jpgImg:=TJPEGImage.Create;
try
jpgImg.Assign(Btmp);
jpgImg.CompressionQuality:=85; //потом сделаем настройку
s:=ExtractFilePath(GetDoc.filename);
s:=LeftStr(s,Length(s)-5);
fn1:=s+ChangeFileExt(ExtractFileName(GetDoc.filename),'.jpg');
jpgImg.SaveToFile(fn1);
//теперь снова загружаем и находим разность
jpgImg.LoadFromFile(fn1);
btmp.Assign(jpgImg);
GetDoc.Btmp.Assign(btmp);
Result:=true;
//и еще одно: updateRect надо выставить. Для начала так:
fUpdateRect:=fRect;
finally
jpgImg.Free;
end;
finally
btmp.Free;
end;
end;
function TSaveToJpegCommand.UndoPrediction: Boolean;
var src,dest: TPngObjectIterator;
begin
//уже искаженная картинка у нас в Btmp
src:=GetDoc.Btmp.CreateIteratorForCropped(fRect);
dest:=fPredictor.CreateIterator;
Result:=true;
//src такой же или "ширше", чем dest по цветам.
if ColorType=Color_GRAYSCALE then
while not src.isEOF do
dest.WriteNextAsGrayscale(src.ReadNextAsGrayscale)
else if ColorType=COLOR_RGB then
while not src.isEOF do
dest.WriteNextAsRGB(src.ReadNextAsRGB)
else
//других не поддерживает
Result:=false; //обеспечит корректную работу, но громоздкий DLRN
src.Free;
dest.Free;
end;
function TSaveToJpegCommand.Caption: String;
var s,fn1: string;
begin
s:=ExtractFilePath(GetDoc.filename);
s:=LeftStr(s,Length(s)-5);
fn1:=s+ChangeFileExt(ExtractFileName(GetDoc.filename),'.jpg');
Result:=Format('saved to %s',[fn1]);
end;
(*
TArbitraryRotateCommand
*)
constructor TArbitraryRotateCommand.Create(aAngle: Real);
begin
inherited Create(nil);
fAngle:=aAngle;
end;
procedure TArbitraryRotateCommand.GetBounds;
begin
fRect:=Rect(0,0,GetDoc.btmp.width,GetDoc.btmp.height);
end;
function TArbitraryRotateCommand.InternalExecute: Boolean;
begin
GetDoc.Btmp.ArbitraryRotateNearestNeighbour(fAngle);
GetDoc.SizesChanged;
fUpdateRect:=fRect;
Result:=true;
end;
function TArbitraryRotateCommand.UndoPrediction: Boolean;
begin
GetDoc.Btmp.GetInverseRotationNearestNeighbourInto(fAngle,fPredictor);
GetDoc.SizesChanged;
Result:=true;
//неужели всё так просто??
//НЕ ВЕРЮ
end;
function TArbitraryRotateCommand.Caption: string;
begin
Result:=Format('rotate %f degrees',[Angle]);
end;
(*
TRotate90CWCommand
*)
function TRotate90CWCommand.Execute: Boolean;
begin
GetDoc.SizesChanged;
GetDoc.Btmp.Rotate270;
Result:=true;
end;
function TRotate90CWCommand.Undo: Boolean;
begin
GetDoc.SizesChanged;
GetDoc.Btmp.Rotate90;
Result:=true;
end;
function TRotate90CWCommand.Caption: string;
begin
Result:='Rotate 90CW';
end;
(*
TRotate90CCWCommand
*)
function TRotate90CCWCommand.Execute: Boolean;
begin
GetDoc.SizesChanged;
GetDoc.Btmp.Rotate90;
Result:=true;
end;
function TRotate90CCWCommand.Undo: Boolean;
begin
GetDoc.SizesChanged;
GetDoc.Btmp.Rotate270;
Result:=true;
end;
function TRotate90CCWCommand.Caption: string;
begin
Result:='Rotate 90°CCW';
end;
(*
TRotate180Command
*)
function TRotate180Command.Execute: Boolean;
begin
GetDoc.SizesChanged;
GetDoc.btmp.Rotate180;
Result:=true;
end;
function TRotate180Command.Undo: Boolean;
begin
GetDoc.SizesChanged;
GetDoc.btmp.Rotate180;
Result:=true;
end;
function TRotate180Command.Caption: string;
begin
Result:='Rotate 180°';
end;
initialization
RegisterClasses([TBrushCommand,TSaveToJpegCommand,TRotate90CWCommand,
TRotate90CCWCommand,TRotate180Command,TArbitraryRotateCommand]);
end.
|
unit uMoon;
{$mode delphi}
interface
uses
glr_render,
glr_render2d,
glr_utils,
glr_math, uPhysics2d;
type
{ TLandingZone }
TLandingZone = packed record
Pos, Size: TglrVec2f;
Multiply: Byte;
Sprite: TglrSprite;
MultText: TglrText;
procedure Update();
end;
{ TMoon }
TMoon = class
private
fEditMode: Boolean;
procedure SetEditMode(AValue: Boolean);
protected
fVB: TglrVertexBuffer;
fIB: TglrIndexBuffer;
fMoonMaterial, fMaterial: TglrMaterial;
fPointTR: PglrTextureRegion;
fVecCount, fIndCount: Integer;
fBatch: TglrSpriteBatch;
fFontBatch: TglrFontBatch;
public
MaxY: Single;
Vertices: array of TglrVec2f;
VerticesPoints: array of TglrSprite;
LandingZones: array of TLandingZone;
b2Body: Tb2Body;
constructor Create(aMoonMaterial, aMaterial: TglrMaterial; aPointTexRegion: PglrTextureRegion;
aBatch: TglrSpriteBatch; aFontBatch: TglrFontBatch); virtual;
destructor Destroy(); override;
procedure UpdateData();
procedure AddVertex(aPos: TglrVec2f; aIndex: Integer = -1);
procedure DeleteVertex(aIndex: Integer);
function GetVertexIndexAtPos(aPos: TglrVec2f): Integer;
procedure AddLandingZone(aPos, aSize: TglrVec2f; aMultiply: Byte);
function GetLandingZoneAtPos(aPos: TglrVec2f): Integer;
procedure DeleteLandingZone(aIndex: Integer);
procedure RenderSelf();
procedure RenderLandingZones();
procedure LoadLevel(const aStream: TglrStream; aFreeStreamOnFinish: Boolean = True);
function SaveLevel(): TglrStream;
property EditMode: Boolean read fEditMode write SetEditMode;
end;
implementation
uses
uMain,
uBox2DImport;
{ TLandingZone }
procedure TLandingZone.Update;
begin
Sprite.SetSize(Size);
Sprite.Position := Vec3f(Pos, 4);
MultText.Text := Convert.ToString(Multiply) + 'x';
MultText.Position := Vec3f(Pos.x - 20, Pos.y - Size.y / 2 + 10, 5);
end;
{ TMoon }
procedure TMoon.SetEditMode(AValue: Boolean);
var
i: Integer;
begin
if fEditMode = AValue then
Exit;
fEditMode := AValue;
for i := 0 to Length(VerticesPoints) - 1 do
VerticesPoints[i].Visible := AValue;
end;
constructor TMoon.Create(aMoonMaterial, aMaterial: TglrMaterial;
aPointTexRegion: PglrTextureRegion; aBatch: TglrSpriteBatch;
aFontBatch: TglrFontBatch);
begin
inherited Create();
fVB := TglrVertexBuffer.Create(nil, 65536, vfPos3Tex2, uStaticDraw);
fIB := TglrIndexBuffer.Create(nil, 65536, ifShort);
fMoonMaterial := aMoonMaterial;
fMaterial := aMaterial;
fPointTR := aPointTexRegion;
fBatch := aBatch;
fFontBatch := aFontBatch;
b2Body := nil;
SetLength(LandingZones, 0);
SetLength(Vertices, 0);
SetLength(VerticesPoints, 0);
end;
destructor TMoon.Destroy;
var
i: Integer;
begin
fVB.Free();
fIB.Free();
for i := 0 to Length(LandingZones) - 1 do
begin
LandingZones[i].MultText.Free();
LandingZones[i].Sprite.Free();
end;
for i := 0 to Length(VerticesPoints) - 1 do
VerticesPoints[i].Free();
inherited Destroy;
end;
procedure TMoon.UpdateData;
var
i: Integer;
data: array of TglrVertexP3T2;
idata: array of Word;
begin
fVecCount := 0;
fIndCount := 0;
SetLength(data, Length(Vertices) * 2);
SetLength(idata, (Length(Vertices) - 1) * 6);
for i := Length(Vertices) - 1 downto 0 do
begin
if i > 0 then
begin
idata[fIndCount + 0] := 0 + fVecCount;
idata[fIndCount + 1] := 1 + fVecCount;
idata[fIndCount + 2] := 3 + fVecCount;
idata[fIndCount + 3] := 3 + fVecCount;
idata[fIndCount + 4] := 2 + fVecCount;
idata[fIndCount + 5] := 0 + fVecCount;
fIndCount += 6;
end;
data[fVecCount].vec := Vec3f(Vertices[i].x, MaxY, 5);
data[fVecCount].tex := Vec2f((data[0].vec.x - data[fVecCount].vec.x) / (fMoonMaterial.Textures[0].Texture.Width), 0);
data[fVecCount + 1].vec := Vec3f(Vertices[i], 5);
data[fVecCount + 1].tex := Vec2f(data[fVecCount].tex.x, (data[fVecCount + 1].vec.y - MaxY) / fMoonMaterial.Textures[0].Texture.Width);
fVecCount += 2;
end;
fVb.Update(@data[0], 0, fVecCount);
fIB.Update(@idata[0], 0, fIndCount);
//box2d
if Assigned(b2Body) then
b2Body.Free();
b2Body := Box2d.ChainStatic(Game.World, Vec2f(0, 0), Vertices, 1.0, 1.5, 0.0, $0001, $0002, 2);
b2Body.UserData := Self;
end;
procedure TMoon.AddVertex(aPos: TglrVec2f; aIndex: Integer);
var
i: Integer;
begin
i := Length(Vertices);
SetLength(Vertices, i + 1);
SetLength(VerticesPoints, i + 1);
if aIndex = -1 then
aIndex := i
else
begin
Move(VerticesPoints[aIndex], VerticesPoints[aIndex + 1], SizeOf(TglrSprite) * (i - aIndex));
Move(Vertices[aIndex], Vertices[aIndex + 1], SizeOf(TglrVec2f) * (i - aIndex));
end;
Vertices[aIndex] := aPos;
VerticesPoints[aIndex] := TglrSprite.Create(15, 15, Vec2f(0.5, 0.5));
VerticesPoints[aIndex].Position := Vec3f(Vertices[aIndex], 10);
VerticesPoints[aIndex].SetTextureRegion(fPointTR, False);
end;
procedure TMoon.DeleteVertex(aIndex: Integer);
begin
if (aIndex < 0) or (aIndex > High(Vertices)) then
begin
Log.Write(lError, 'Moon.DeleteVertex: Index '
+ Convert.ToString(aIndex)
+ ' is out of bounds [0; '
+ Convert.ToString(High(Vertices)) + ']');
Exit();
end;
if aIndex <> High(Vertices) then
begin
Move(Vertices[aIndex + 1], Vertices[aIndex], (High(Vertices) - aIndex) * SizeOf(TglrVec2f));
Move(VerticesPoints[aIndex + 1], VerticesPoints[aIndex], (High(VerticesPoints) - aIndex) * SizeOf(TglrSprite));
end;
SetLength(Vertices, Length(Vertices) - 1);
SetLength(VerticesPoints, Length(VerticesPoints) - 1);
end;
function TMoon.GetVertexIndexAtPos(aPos: TglrVec2f): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Length(Vertices) - 1 do
if (Vertices[i] - aPos).LengthQ < 49 then
Exit(i);
end;
procedure TMoon.AddLandingZone(aPos, aSize: TglrVec2f; aMultiply: Byte);
var
i: Integer;
begin
i := Length(LandingZones);
SetLength(LandingZones, i + 1);
with LandingZones[i] do
begin
Multiply := aMultiply;
Pos := aPos;
Size := aSize;
Sprite := TglrSprite.Create();
Sprite.SetTextureRegion(fPointTR, False);
Sprite.SetVerticesColor(Vec4f(0, 1, 0, 0.1));
MultText := TglrText.Create();
Update();
end;
end;
function TMoon.GetLandingZoneAtPos(aPos: TglrVec2f): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Length(LandingZones) - 1 do
if (aPos.x > LandingZones[i].Pos.x - LandingZones[i].Size.x / 2)
and (aPos.x < LandingZones[i].Pos.x + LandingZones[i].Size.x / 2)
and (aPos.y > LandingZones[i].Pos.y - LandingZones[i].Size.y / 2)
and (aPos.y < LandingZones[i].Pos.y + LandingZones[i].Size.y / 2) then
Exit(i);
end;
procedure TMoon.DeleteLandingZone(aIndex: Integer);
begin
if (aIndex < 0) or (aIndex > High(LandingZones)) then
begin
Log.Write(lError, 'Moon.DeleteLandingZoe: Index '
+ Convert.ToString(aIndex)
+ ' is out of bounds [0; '
+ Convert.ToString(High(LandingZones)) + ']');
Exit();
end;
if aIndex <> High(LandingZones) then
Move(LandingZones[aIndex + 1], LandingZones[aIndex], (High(LandingZones) - aIndex) * SizeOf(TLandingZone));
SetLength(LandingZones, Length(LandingZones) - 1);
end;
procedure TMoon.RenderSelf;
begin
fMoonMaterial.Bind();
Render.DrawTriangles(fVB, fIB, 0, fIndCount);
// fMoonMaterial.Unbind();
end;
procedure TMoon.RenderLandingZones;
var
i: Integer;
begin
fMaterial.Bind();
fBatch.Start();
fFontBatch.Start();
if fEditMode then
fBatch.Draw(VerticesPoints);
for i := 0 to Length(LandingZones) - 1 do
begin
fBatch.Draw(LandingZones[i].Sprite);
fFontBatch.Draw(LandingZones[i].MultText);
end;
fBatch.Finish();
fFontBatch.Finish();
//fMaterial.Unbind();
end;
procedure TMoon.LoadLevel(const aStream: TglrStream;
aFreeStreamOnFinish: Boolean);
var
count: Word;
i: Integer;
begin
aStream.Read(count, SizeOf(Word));
SetLength(Vertices, count);
SetLength(VerticesPoints, count);
aStream.Read(Vertices[0], count * SizeOf(TglrVec2f));
for i := 0 to count - 1 do
begin
VerticesPoints[i] := TglrSprite.Create(15, 15, Vec2f(0.5, 0.5));
VerticesPoints[i].Position := Vec3f(Vertices[i], 10);
VerticesPoints[i].SetTextureRegion(fPointTR, False);
VerticesPoints[i].Visible := False;
end;
UpdateData();
count := 0;
aStream.Read(count, SizeOf(Word));
if count <> 0 then
begin
SetLength(LandingZones, count);
aStream.Read(LandingZones[0], count * SizeOf(TLandingZone));
for i := 0 to count - 1 do
with LandingZones[i] do
begin
Sprite := TglrSprite.Create();
Sprite.SetTextureRegion(fPointTR, False);
Sprite.SetVerticesColor(Vec4f(0, 1, 0, 0.1));
MultText := TglrText.Create();
Update();
end;
end;
if aFreeStreamOnFinish then
aStream.Free();
end;
function TMoon.SaveLevel: TglrStream;
var
count, count2: Word;
size: LongInt;
p: Pointer;
begin
count := Length(Vertices);
count2 := Length(LandingZones);
size := 2 * SizeOf(Word) + count * SizeOf(TglrVec2f) + count2 * SizeOf(TLandingZone);
GetMem(p, size);
Result := TglrStream.Init(p, size, True);
Result.Write(count, SizeOf(Word));
Result.Write(Vertices[0], count * SizeOf(TglrVec2f));
Result.Write(count2, SizeOf(Word));
if count2 <> 0 then
Result.Write(LandingZones[0], count2 * SizeOf(TLandingZone));
end;
end.
|
{ *********************************************************************************** }
{ * CryptoLib Library * }
{ * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * }
{ * Github Repository <https://github.com/Xor-el> * }
{ * Distributed under the MIT software license, see the accompanying file LICENSE * }
{ * or visit http://www.opensource.org/licenses/mit-license.php. * }
{ * Acknowledgements: * }
{ * * }
{ * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * }
{ * development of this library * }
{ * ******************************************************************************* * }
(* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *)
unit ClpDerNumericString;
{$I ..\Include\CryptoLib.inc}
interface
uses
Classes,
SysUtils,
ClpDerStringBase,
ClpAsn1Tags,
ClpAsn1OctetString,
ClpAsn1Object,
ClpIProxiedInterface,
ClpDerOutputStream,
ClpCryptoLibTypes,
ClpIAsn1TaggedObject,
ClpIDerNumericString,
ClpConverters;
resourcestring
SIllegalObject = 'Illegal Object in GetInstance: %s';
SIllegalCharacters = 'String Contains Illegal Characters "str"';
SStrNil = '"str"';
type
/// <summary>
/// Der NumericString object - this is an ascii string of characters
/// {0,1,2,3,4,5,6,7,8,9, }.
/// </summary>
TDerNumericString = class(TDerStringBase, IDerNumericString)
strict private
var
FStr: String;
function GetStr: String; inline;
property Str: String read GetStr;
strict protected
function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override;
public
/// <summary>
/// basic constructor - with bytes.
/// </summary>
constructor Create(const Str: TCryptoLibByteArray); overload;
/// <summary>
/// basic constructor - without validation.
/// </summary>
constructor Create(const Str: String); overload;
/// <summary>
/// Constructor with optional validation.
/// </summary>
/// <param name="Str">
/// the base string to wrap.
/// </param>
/// <param name="validate">
/// whether or not to check the string.
/// </param>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if validate is true and the string contains characters that should
/// not be in an IA5String.
/// </exception>
constructor Create(const Str: String; validate: Boolean); overload;
function GetString(): String; override;
function GetOctets(): TCryptoLibByteArray; inline;
procedure Encode(const derOut: TStream); override;
/// <summary>
/// return a Numeric string from the passed in object
/// </summary>
/// <param name="obj">
/// a DerNumericString or an object that can be converted into one.
/// </param>
/// <returns>
/// return a DerNumericString instance, or null.
/// </returns>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the object cannot be converted.
/// </exception>
class function GetInstance(const obj: TObject): IDerNumericString; overload;
static; inline;
/// <summary>
/// return a Numeric String from a tagged object.
/// </summary>
/// <param name="obj">
/// the tagged object holding the object we want
/// </param>
/// <param name="isExplicit">
/// true if the object is meant to be explicitly tagged false otherwise.
/// </param>
/// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException">
/// if the tagged object cannot be converted.
/// </exception>
class function GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IDerNumericString; overload; static; inline;
/// <summary>
/// Return true if the string can be represented as a NumericString
/// ('0'..'9', ' ')
/// </summary>
/// <param name="Str">
/// string to validate.
/// </param>
/// <returns>
/// true if numeric, false otherwise.
/// </returns>
class function IsNumericString(const Str: String): Boolean; static; inline;
end;
implementation
{ TDerNumericString }
function TDerNumericString.GetStr: String;
begin
result := FStr;
end;
function TDerNumericString.GetOctets: TCryptoLibByteArray;
begin
result := TConverters.ConvertStringToBytes(Str, TEncoding.ASCII);
end;
class function TDerNumericString.IsNumericString(const Str: String): Boolean;
var
ch: Char;
begin
for ch in Str do
begin
// char.IsDigit(ch)
if ((Ord(ch) > $007F) or ((ch <> ' ') and (not CharInSet(ch, ['0' .. '9']))))
then
begin
result := false;
Exit;
end;
end;
result := true;
end;
function TDerNumericString.Asn1Equals(const asn1Object: IAsn1Object): Boolean;
var
other: IDerNumericString;
begin
if (not Supports(asn1Object, IDerNumericString, other)) then
begin
result := false;
Exit;
end;
result := Str = other.Str;
end;
constructor TDerNumericString.Create(const Str: TCryptoLibByteArray);
begin
Create(TConverters.ConvertBytesToString(Str, TEncoding.ASCII), false);
end;
constructor TDerNumericString.Create(const Str: String);
begin
Create(Str, false);
end;
constructor TDerNumericString.Create(const Str: String; validate: Boolean);
begin
Inherited Create();
if (Str = '') then
begin
raise EArgumentNilCryptoLibException.CreateRes(@SStrNil);
end;
if (validate and (not IsNumericString(Str))) then
begin
raise EArgumentCryptoLibException.CreateRes(@SIllegalCharacters);
end;
FStr := Str;
end;
procedure TDerNumericString.Encode(const derOut: TStream);
begin
(derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.NumericString,
GetOctets());
end;
class function TDerNumericString.GetInstance(const obj: TObject)
: IDerNumericString;
begin
if ((obj = Nil) or (obj is TDerNumericString)) then
begin
result := obj as TDerNumericString;
Exit;
end;
raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject,
[obj.ClassName]);
end;
class function TDerNumericString.GetInstance(const obj: IAsn1TaggedObject;
isExplicit: Boolean): IDerNumericString;
var
o: IAsn1Object;
begin
o := obj.GetObject();
if ((isExplicit) or (Supports(o, IDerNumericString))) then
begin
result := GetInstance(o as TAsn1Object);
Exit;
end;
result := TDerNumericString.Create
(TAsn1OctetString.GetInstance(o as TAsn1Object).GetOctets());
end;
function TDerNumericString.GetString: String;
begin
result := Str;
end;
end.
|
unit winipc;
interface
uses
Windows, Messages, Classes, SysUtils;
const
//Message types
mtUnknown = 0;
mtString = 1;
type
TMessageType = LongInt;
{ TWinIPCClient }
TWinIPCClient = class (TComponent)
private
FActive: Boolean;
FServerID: String;
FServerInstance: String;
FWindowName: String;
FHWND: HWnd;
procedure SetActive(const AValue: Boolean);
procedure SetServerID(const AValue: String);
procedure SetServerInstance(const AValue: String);
procedure UpdateWindowName;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Connect;
procedure Disconnect;
function ServerRunning: Boolean;
procedure SendMessage(MsgType: TMessageType; Stream: TStream);
procedure SendStringMessage(Msg: String);
procedure SendStringMessageFmt(Msg: String; Args : array of const);
property Active: Boolean read FActive write SetActive;
property ServerID: String read FServerID write SetServerID;
property ServerInstance: String read FServerInstance write SetServerInstance;
end;
implementation
const
MsgWndClassName : PChar = 'FPCMsgWindowCls';
resourcestring
SErrServerNotActive = 'Server with ID %s is not active.';
{ TWinIPCClient }
procedure TWinIPCClient.SetActive(const AValue: Boolean);
begin
if FActive = AValue then
Exit;
FActive := AValue;
if FActive then
Connect
else
Disconnect;
end;
procedure TWinIPCClient.SetServerID(const AValue: String);
begin
FServerID := AValue;
UpdateWindowName;
end;
procedure TWinIPCClient.SetServerInstance(const AValue: String);
begin
FWindowName := AValue;
UpdateWindowName;
end;
procedure TWinIPCClient.UpdateWindowName;
begin
if FServerInstance <> '' then
FWindowName := FServerID + '_' + FServerInstance
else
FWindowName := FServerID;
end;
constructor TWinIPCClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TWinIPCClient.Destroy;
begin
inherited Destroy;
end;
procedure TWinIPCClient.Connect;
begin
FHWND := FindWindow(MsgWndClassName,PChar(FWindowName));
if FHWND = 0 then
raise Exception.Create(Format(SErrServerNotActive,[FServerID]));
end;
procedure TWinIPCClient.Disconnect;
begin
FHWND := 0;
end;
function TWinIPCClient.ServerRunning: Boolean;
begin
Result := FindWindow(MsgWndClassName,PChar(FWindowName)) <> 0;
end;
procedure TWinIPCClient.SendMessage(MsgType: TMessageType; Stream: TStream);
var
CDS : TCopyDataStruct;
Data, FMemstr : TMemorySTream;
begin
if Stream is TMemoryStream then
begin
Data := TMemoryStream(Stream);
FMemStr := nil
end
else
begin
FMemStr := TMemoryStream.Create;
Data := FMemstr;
end;
try
if Assigned(FMemStr) then
begin
FMemStr.CopyFrom(Stream,0);
FMemStr.Seek(0,soFromBeginning);
end;
CDS.lpData:=Data.Memory;
CDS.cbData:=Data.Size;
Windows.SendMessage(FHWnd,WM_COPYDATA,0,Integer(@CDS));
finally
FreeAndNil(FMemStr);
end;
end;
procedure TWinIPCClient.SendStringMessage(Msg: String);
begin
end;
procedure TWinIPCClient.SendStringMessageFmt(Msg: String;
Args: array of const);
begin
end;
end.
|
unit RedactionsKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы Redactions }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Document\Forms\RedactionsKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "RedactionsKeywordsPack" MUID: (4A8EE2890012_Pack)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3IntfUses
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)}
uses
l3ImplUses
, Redactions_Form
, tfwPropertyLike
, nscTreeViewWithAdapterDragDrop
, tfwScriptingInterfaces
, TypInfo
, tfwTypeInfo
, tfwControlString
, kwBynameControlPush
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *4A8EE2890012_Packimpl_uses*
//#UC END# *4A8EE2890012_Packimpl_uses*
;
type
TkwRedactionsFormRedactionTree = {final} class(TtfwPropertyLike)
{* Слово скрипта .TRedactionsForm.RedactionTree }
private
function RedactionTree(const aCtx: TtfwContext;
aRedactionsForm: TRedactionsForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TRedactionsForm.RedactionTree }
protected
class function GetWordNameForRegister: AnsiString; override;
procedure DoDoIt(const aCtx: TtfwContext); override;
public
function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override;
function GetAllParamsCount(const aCtx: TtfwContext): Integer; override;
function ParamsTypes: PTypeInfoArray; override;
procedure SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext); override;
end;//TkwRedactionsFormRedactionTree
Tkw_Form_Redactions = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы Redactions
----
*Пример использования*:
[code]форма::Redactions TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_Redactions
Tkw_Redactions_Control_RedactionTree = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола RedactionTree
----
*Пример использования*:
[code]контрол::RedactionTree TryFocus ASSERT[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Redactions_Control_RedactionTree
Tkw_Redactions_Control_RedactionTree_Push = {final} class(TkwBynameControlPush)
{* Слово словаря для контрола RedactionTree
----
*Пример использования*:
[code]контрол::RedactionTree:push pop:control:SetFocus ASSERT[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Redactions_Control_RedactionTree_Push
function TkwRedactionsFormRedactionTree.RedactionTree(const aCtx: TtfwContext;
aRedactionsForm: TRedactionsForm): TnscTreeViewWithAdapterDragDrop;
{* Реализация слова скрипта .TRedactionsForm.RedactionTree }
begin
Result := aRedactionsForm.RedactionTree;
end;//TkwRedactionsFormRedactionTree.RedactionTree
class function TkwRedactionsFormRedactionTree.GetWordNameForRegister: AnsiString;
begin
Result := '.TRedactionsForm.RedactionTree';
end;//TkwRedactionsFormRedactionTree.GetWordNameForRegister
function TkwRedactionsFormRedactionTree.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscTreeViewWithAdapterDragDrop);
end;//TkwRedactionsFormRedactionTree.GetResultTypeInfo
function TkwRedactionsFormRedactionTree.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwRedactionsFormRedactionTree.GetAllParamsCount
function TkwRedactionsFormRedactionTree.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TRedactionsForm)]);
end;//TkwRedactionsFormRedactionTree.ParamsTypes
procedure TkwRedactionsFormRedactionTree.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству RedactionTree', aCtx);
end;//TkwRedactionsFormRedactionTree.SetValuePrim
procedure TkwRedactionsFormRedactionTree.DoDoIt(const aCtx: TtfwContext);
var l_aRedactionsForm: TRedactionsForm;
begin
try
l_aRedactionsForm := TRedactionsForm(aCtx.rEngine.PopObjAs(TRedactionsForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aRedactionsForm: TRedactionsForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(RedactionTree(aCtx, l_aRedactionsForm));
end;//TkwRedactionsFormRedactionTree.DoDoIt
function Tkw_Form_Redactions.GetString: AnsiString;
begin
Result := 'RedactionsForm';
end;//Tkw_Form_Redactions.GetString
class procedure Tkw_Form_Redactions.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TRedactionsForm);
end;//Tkw_Form_Redactions.RegisterInEngine
class function Tkw_Form_Redactions.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::Redactions';
end;//Tkw_Form_Redactions.GetWordNameForRegister
function Tkw_Redactions_Control_RedactionTree.GetString: AnsiString;
begin
Result := 'RedactionTree';
end;//Tkw_Redactions_Control_RedactionTree.GetString
class procedure Tkw_Redactions_Control_RedactionTree.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscTreeViewWithAdapterDragDrop);
end;//Tkw_Redactions_Control_RedactionTree.RegisterInEngine
class function Tkw_Redactions_Control_RedactionTree.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::RedactionTree';
end;//Tkw_Redactions_Control_RedactionTree.GetWordNameForRegister
procedure Tkw_Redactions_Control_RedactionTree_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('RedactionTree');
inherited;
end;//Tkw_Redactions_Control_RedactionTree_Push.DoDoIt
class function Tkw_Redactions_Control_RedactionTree_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::RedactionTree:push';
end;//Tkw_Redactions_Control_RedactionTree_Push.GetWordNameForRegister
initialization
TkwRedactionsFormRedactionTree.RegisterInEngine;
{* Регистрация RedactionsForm_RedactionTree }
Tkw_Form_Redactions.RegisterInEngine;
{* Регистрация Tkw_Form_Redactions }
Tkw_Redactions_Control_RedactionTree.RegisterInEngine;
{* Регистрация Tkw_Redactions_Control_RedactionTree }
Tkw_Redactions_Control_RedactionTree_Push.RegisterInEngine;
{* Регистрация Tkw_Redactions_Control_RedactionTree_Push }
TtfwTypeRegistrator.RegisterType(TypeInfo(TRedactionsForm));
{* Регистрация типа TRedactionsForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscTreeViewWithAdapterDragDrop));
{* Регистрация типа TnscTreeViewWithAdapterDragDrop }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)
end.
|
{******************************************************************}
{ MD5 Hashsum Evaluation Unit For Borland Delphi }
{ }
{ Copyright © 2002 by Dimka Maslov }
{ E-mail: mail@endimus.com, }
{ Web-site: http://www.endimus.com }
{ }
{ Derived from the RSA Data Security, Inc. }
{ MD5 Message-Digest Algorithm described in RFC 1321 }
{ http://www.faqs.org/rfcs/rfc1321.html }
{******************************************************************}
unit md5;
interface
uses Windows, SysUtils, Classes;
type
UINT4 = LongWord;
PArray4UINT4 = ^TArray4UINT4;
TArray4UINT4 = array [0..3] of UINT4;
PArray2UINT4 = ^TArray2UINT4;
TArray2UINT4 = array [0..1] of UINT4;
PArray16Byte = ^TArray16Byte;
TArray16Byte = array [0..15] of Byte;
PArray64Byte = ^TArray64Byte;
TArray64Byte = array [0..63] of Byte;
PByteArray = ^TByteArray;
TByteArray = array [0..0] of Byte;
PUINT4Array = ^TUINT4Array;
TUINT4Array = array [0..0] of UINT4;
PMD5Context = ^TMD5Context;
TMD5Context = record
state: TArray4UINT4;
count: TArray2UINT4;
buffer: TArray64Byte;
end;
{ The TMD5Digest record is the type of results of
the MD5 hashsum evaluation functions. The contents
of a record may be used as four 32-bit integer values
or as an array of 16 bytes }
PMD5Digest = ^TMD5Digest;
TMD5Digest = record
case Integer of
0: (A, B, C, D: LongInt);
1: (v: array [0..15] of Byte);
end;
{ The MD5String function evaluates the MD5 hashsum for
a string. The S parameter specifies a string to
evaluate hashsum }
function MD5String(const S: string): TMD5Digest;
{ The MD5File function evaluates the MD5 hashsum for
a file. The FileName parameter specifies the name
of a file to evaluate hashsum }
function MD5File(const FileName: string): TMD5Digest;
{ The MD5Stream function evaluates the MD5 hashsum for
a stream. The Stream parameters specifies the
TStream descendant class object to evaluate hashsum }
function MD5Stream(const Stream: TStream): TMD5Digest;
{ The MD5Buffer function evaluates the MD5 hashsum for
any memory buffer. The Buffer parameters specifies a
buffer to evaluate hashsum. The Size parameter specifies
the size (in bytes) of a buffer }
function MD5Buffer(const Buffer; Size: Integer): TMD5Digest;
{ The MD5DigestToStr function converts the result of
a hashsum evaluation function into a string of
hexadecimal digits }
function MD5DigestToStr(const Digest: TMD5Digest): string;
{ The MD5DigestCompare function compares two
TMD5Digest record variables. This function returns
TRUE if parameters are equal or FALSE otherwise }
function MD5DigestCompare(const Digest1, Digest2: TMD5Digest): Boolean;
procedure MD5Init(var Context: TMD5Context);
procedure MD5Update(var Context: TMD5Context; Input: PByteArray; InputLen: LongWord);
procedure MD5Final(var Digest: TMD5Digest; var Context: TMD5Context);
implementation
{
Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
}
const
S11 = 7;
S12 = 12;
S13 = 17;
S14 = 22;
S21 = 5;
S22 = 9;
S23 = 14;
S24 = 20;
S31 = 4;
S32 = 11;
S33 = 16;
S34 = 23;
S41 = 6;
S42 = 10;
S43 = 15;
S44 = 21;
var
Padding : TArray64Byte =
($80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
function _F(x, y, z: UINT4): UINT4;
begin
Result := (((x) and (y)) or ((not x) and (z)));
end;
function _G(x, y, z: UINT4): UINT4;
begin
Result := (((x) and (z)) or ((y) and (not z)));
end;
function _H(x, y, z: UINT4): UINT4;
begin
Result := ((x) xor (y) xor (z));
end;
function _I(x, y, z: UINT4): UINT4;
begin
Result := ((y) xor ((x) or ( not z)));
end;
function ROTATE_LEFT(x, n: UINT4): UINT4;
begin
Result := (((x) shl (n)) or ((x) shr (32-(n))));
end;
procedure FF(var a: UINT4; b, c, d, x, s, ac: UINT4);
begin
a := a + _F(b, c, d) + x + ac;
a := ROTATE_LEFT (a, s);
a := a + b;
end;
procedure GG(var a: UINT4; b, c, d, x, s, ac: UINT4);
begin
a := a + _G(b, c, d) + x + ac;
a := ROTATE_LEFT(a, s);
a := a + b;
end;
procedure HH(var a: UINT4; b, c, d, x, s, ac: UINT4);
begin
a := a + _H(b, c, d) + x + ac;
a := ROTATE_LEFT(a, s);
a := a + b;
end;
procedure II(var a: UINT4; b, c, d, x, s, ac: UINT4);
begin
a := a + _I(b, c, d) + x + ac;
a := ROTATE_LEFT(a, s);
a := a + b;
end;
procedure MD5Encode(Output: PByteArray; Input: PUINT4Array; Len: LongWord);
var
i, j: LongWord;
begin
j:=0;
i:=0;
while j < Len do begin
output[j] := Byte(input[i] and $ff);
output[j+1] := Byte((input[i] shr 8) and $ff);
output[j+2] := Byte((input[i] shr 16) and $ff);
output[j+3] := Byte((input[i] shr 24) and $ff);
Inc(j, 4);
Inc(i);
end;
end;
procedure MD5Decode(Output: PUINT4Array; Input: PByteArray; Len: LongWord);
var
i, j: LongWord;
begin
j:=0;
i:=0;
while j < Len do begin
Output[i] := UINT4(input[j]) or (UINT4(input[j+1]) shl 8) or
(UINT4(input[j+2]) shl 16) or ( UINT4(input[j+3]) shl 24);
Inc(j, 4);
Inc(i);
end;
end;
procedure MD5_memcpy(Output: PByteArray; Input: PByteArray; Len: LongWord);
begin
Move(Input^, Output^, Len);
end;
procedure MD5_memset(Output: PByteArray; Value: Integer; Len: LongWord);
begin
FillChar(Output^, Len, Byte(Value));
end;
procedure MD5Transform(State: PArray4UINT4; Buffer: PArray64Byte);
var
a, b, c, d: UINT4;
x : array[0..15] of UINT4;
begin
a:=State[0]; b:=State[1]; c:=State[2]; d:=State[3];
MD5Decode(PUINT4Array(@x), PByteArray(Buffer), 64);
FF (a, b, c, d, x[ 0], S11, $d76aa478);
FF (d, a, b, c, x[ 1], S12, $e8c7b756);
FF (c, d, a, b, x[ 2], S13, $242070db);
FF (b, c, d, a, x[ 3], S14, $c1bdceee);
FF (a, b, c, d, x[ 4], S11, $f57c0faf);
FF (d, a, b, c, x[ 5], S12, $4787c62a);
FF (c, d, a, b, x[ 6], S13, $a8304613);
FF (b, c, d, a, x[ 7], S14, $fd469501);
FF (a, b, c, d, x[ 8], S11, $698098d8);
FF (d, a, b, c, x[ 9], S12, $8b44f7af);
FF (c, d, a, b, x[10], S13, $ffff5bb1);
FF (b, c, d, a, x[11], S14, $895cd7be);
FF (a, b, c, d, x[12], S11, $6b901122);
FF (d, a, b, c, x[13], S12, $fd987193);
FF (c, d, a, b, x[14], S13, $a679438e);
FF (b, c, d, a, x[15], S14, $49b40821);
GG (a, b, c, d, x[ 1], S21, $f61e2562);
GG (d, a, b, c, x[ 6], S22, $c040b340);
GG (c, d, a, b, x[11], S23, $265e5a51);
GG (b, c, d, a, x[ 0], S24, $e9b6c7aa);
GG (a, b, c, d, x[ 5], S21, $d62f105d);
GG (d, a, b, c, x[10], S22, $2441453);
GG (c, d, a, b, x[15], S23, $d8a1e681);
GG (b, c, d, a, x[ 4], S24, $e7d3fbc8);
GG (a, b, c, d, x[ 9], S21, $21e1cde6);
GG (d, a, b, c, x[14], S22, $c33707d6);
GG (c, d, a, b, x[ 3], S23, $f4d50d87);
GG (b, c, d, a, x[ 8], S24, $455a14ed);
GG (a, b, c, d, x[13], S21, $a9e3e905);
GG (d, a, b, c, x[ 2], S22, $fcefa3f8);
GG (c, d, a, b, x[ 7], S23, $676f02d9);
GG (b, c, d, a, x[12], S24, $8d2a4c8a);
HH (a, b, c, d, x[ 5], S31, $fffa3942);
HH (d, a, b, c, x[ 8], S32, $8771f681);
HH (c, d, a, b, x[11], S33, $6d9d6122);
HH (b, c, d, a, x[14], S34, $fde5380c);
HH (a, b, c, d, x[ 1], S31, $a4beea44);
HH (d, a, b, c, x[ 4], S32, $4bdecfa9);
HH (c, d, a, b, x[ 7], S33, $f6bb4b60);
HH (b, c, d, a, x[10], S34, $bebfbc70);
HH (a, b, c, d, x[13], S31, $289b7ec6);
HH (d, a, b, c, x[ 0], S32, $eaa127fa);
HH (c, d, a, b, x[ 3], S33, $d4ef3085);
HH (b, c, d, a, x[ 6], S34, $4881d05);
HH (a, b, c, d, x[ 9], S31, $d9d4d039);
HH (d, a, b, c, x[12], S32, $e6db99e5);
HH (c, d, a, b, x[15], S33, $1fa27cf8);
HH (b, c, d, a, x[ 2], S34, $c4ac5665);
II (a, b, c, d, x[ 0], S41, $f4292244);
II (d, a, b, c, x[ 7], S42, $432aff97);
II (c, d, a, b, x[14], S43, $ab9423a7);
II (b, c, d, a, x[ 5], S44, $fc93a039);
II (a, b, c, d, x[12], S41, $655b59c3);
II (d, a, b, c, x[ 3], S42, $8f0ccc92);
II (c, d, a, b, x[10], S43, $ffeff47d);
II (b, c, d, a, x[ 1], S44, $85845dd1);
II (a, b, c, d, x[ 8], S41, $6fa87e4f);
II (d, a, b, c, x[15], S42, $fe2ce6e0);
II (c, d, a, b, x[ 6], S43, $a3014314);
II (b, c, d, a, x[13], S44, $4e0811a1);
II (a, b, c, d, x[ 4], S41, $f7537e82);
II (d, a, b, c, x[11], S42, $bd3af235);
II (c, d, a, b, x[ 2], S43, $2ad7d2bb);
II (b, c, d, a, x[ 9], S44, $eb86d391);
Inc(State[0], a);
Inc(State[1], b);
Inc(State[2], c);
Inc(State[3], d);
MD5_memset (PByteArray(@x), 0, SizeOf (x));
end;
procedure MD5Init(var Context: TMD5Context);
begin
FillChar(Context, SizeOf(Context), 0);
Context.state[0] := $67452301;
Context.state[1] := $efcdab89;
Context.state[2] := $98badcfe;
Context.state[3] := $10325476;
end;
procedure MD5Update(var Context: TMD5Context; Input: PByteArray; InputLen: LongWord);
var
i, index, partLen: LongWord;
begin
index := LongWord( (context.count[0] shr 3) and $3F);
Inc(Context.count[0], UINT4(InputLen) shl 3);
if Context.count[0] < UINT4(InputLen) shl 3 then Inc(Context.count[1]);
Inc(Context.count[1], UINT4(InputLen) shr 29);
partLen := 64 - index;
if inputLen >= partLen then begin
MD5_memcpy(PByteArray(@Context.buffer[index]), Input, PartLen);
MD5Transform(@Context.state, @Context.buffer);
i := partLen;
while i + 63 < inputLen do begin
MD5Transform(@Context.state, PArray64Byte(@Input[i]));
Inc(i, 64);
end;
index := 0;
end else i:=0;
MD5_memcpy(PByteArray(@Context.buffer[index]), PByteArray(@Input[i]), inputLen - i);
end;
procedure MD5Final(var Digest: TMD5Digest; var Context: TMD5Context);
var
bits: array [0..7] of Byte;
index, padLen: LongWord;
begin
MD5Encode(PByteArray(@bits), PUINT4Array(@Context.count), 8);
index := LongWord( (Context.count[0] shr 3) and $3F);
if index < 56 then padLen := 56 - index else padLen := 120 - index;
MD5Update(Context, PByteArray(@PADDING), padLen);
MD5Update(Context, PByteArray(@Bits), 8);
MD5Encode(PByteArray(@Digest), PUINT4Array(@Context.state), 16);
MD5_memset(PByteArray(@Context), 0, SizeOf(Context));
end;
function MD5DigestToStr(const Digest: TMD5Digest): string;
//var
//i: Integer;
begin
Result := Format('%.8x%.8x%.8x%.8x', [Digest.A, Digest.B, Digest.C, Digest.D]);
//for i:=0 to 15 do Result:=Result+IntToHex(Digest.v[i], 2);
end;
function MD5String(const S: string): TMD5Digest;
begin
Result:=MD5Buffer(PChar(S)^, Length(S));
end;
function MD5File(const FileName: string): TMD5Digest;
var
F: TFileStream;
begin
F:=TFileStream.Create(FileName, fmOpenRead);
try
Result:=MD5Stream(F);
finally
F.Free;
end;
end;
function MD5Stream(const Stream: TStream): TMD5Digest;
var
Context: TMD5Context;
Buffer: array[0..4095] of Byte;
Size: Integer;
ReadBytes : Integer;
TotalBytes : Integer;
SavePos: Integer;
begin
MD5Init(Context);
Size:=Stream.Size;
SavePos:=Stream.Position;
TotalBytes:=0;
try
Stream.Seek(0, soFromBeginning);
repeat
ReadBytes:=Stream.Read(Buffer, SizeOf(Buffer));
Inc(TotalBytes, ReadBytes);
MD5Update(Context, @Buffer, ReadBytes);
until (ReadBytes = 0) or (TotalBytes = Size);
finally
Stream.Seek(SavePos, soFromBeginning);
end;
MD5Final(Result, Context);
end;
function MD5Buffer(const Buffer; Size: Integer): TMD5Digest;
var
Context: TMD5Context;
begin
MD5Init(Context);
MD5Update(Context, PByteArray(@Buffer), Size);
MD5Final(Result, Context);
end;
function MD5DigestCompare(const Digest1, Digest2: TMD5Digest): Boolean;
begin
Result:=False;
if Digest1.A <> Digest2.A then Exit;
if Digest1.B <> Digest2.B then Exit;
if Digest1.C <> Digest2.C then Exit;
if Digest1.D <> Digest2.D then Exit;
Result:=True;
end;
end.
|
unit Fli2Rle;
interface
uses
Classes, Windows, Dibs, Flics, FliPlayback, FliPlay;
type
TFliToRleDecoder =
class( TFliPlayer )
protected
fRleHeader : PDib;
fRleEncodedImage : pointer;
fUseRleDecoder : boolean;
fPartialUpdate : boolean;
procedure SetUseRleDecoder( aUseRleDecoder : boolean ); virtual;
procedure AllocDecoder;
procedure FreeDecoder;
public
property RleHeader : PDib read fRleHeader;
property RleEncodedImage : pointer read fRleEncodedImage;
property UseRleDecoder : boolean read fUseRleDecoder write SetUseRleDecoder default true;
property PartialUpdate : boolean read fPartialUpdate write fPartialUpdate stored false;
constructor Create;
destructor Destroy; override;
procedure ProcessFrame; override;
procedure LoadFromStream( aStream : TStream ); override;
end;
// FLI -> RLE low level routines
procedure PlayFrameToRle( Frame : PFliFrame; const FliSize : TPoint; Dest : pointer; DestWidth : integer;
UnkChunkPlayer : TChunkPlayerProc);
function PlayChunksToRle( FirstChunk : pointer; const FliSize : TPoint; Dest : pointer; DestWidth : integer;
Count : integer; UnkChunkPlayer : TChunkPlayerProc) : pointer;
implementation
uses
ObjUtils, DibRle;
// TFliToRleDecoder
procedure TFliToRleDecoder.AllocDecoder;
var
RleMaxSize : integer;
begin
RleMaxSize := DwordAlign( Size.X ) * Size.Y; // Worst case
GetMem( fRleEncodedImage, RleMaxSize );
pword( fRleEncodedImage )^ := rleEndOfBitmap;
fRleHeader := DibNewHeader( Size.X, Size.Y, 8 );
fRleHeader.biCompression := BI_RLE8;
DibSetUsage( fRleHeader, 0, DIB_PAL_COLORS );
end;
procedure TFliToRleDecoder.FreeDecoder;
begin
if Assigned( fRleHeader )
then
begin
DibFree( fRleHeader );
fRleHeader := nil;
FreePtr( fRleEncodedImage );
end;
end;
procedure TFliToRleDecoder.SetUseRleDecoder( aUseRleDecoder : boolean );
begin
fUseRleDecoder := aUseRleDecoder;
if (UseRleDecoder <> aUseRleDecoder) and (not Empty)
then
if UseRleDecoder
then AllocDecoder
else FreeDecoder;
end;
constructor TFliToRleDecoder.Create;
begin
inherited;
fUseRleDecoder := true;
end;
destructor TFliToRleDecoder.Destroy;
begin
FreeDecoder;
inherited;
end;
procedure TFliToRleDecoder.LoadFromStream( aStream : TStream );
begin
if UseRleDecoder
then
begin
FreeDecoder;
inherited;
AllocDecoder;
end
else inherited;
end;
threadvar
fCurrentPlayer : TFliToRleDecoder;
function RleUnkChunkPlayer( Chunk : pointer; const FliSize : TPoint; Buffer : pointer; BufferWidth : integer ) : pointer;
begin
Result := pchar(Chunk) + PFliChunk(Chunk).Size;
fCurrentPlayer.PartialUpdate := false;
end;
procedure TFliToRleDecoder.ProcessFrame;
begin
inherited;
if UseRleDecoder and Assigned( fRleEncodedImage )
then
begin
fCurrentPlayer := Self;
PartialUpdate := true;
PlayFrameToRle( CurrentFrame, Size, fRleEncodedImage, fBufferWidth, RleUnkChunkPlayer );
end;
end;
// FLI -> RLE low level routines
procedure PlayFrameToRle( Frame : PFliFrame; const FliSize : TPoint; Dest : pointer; DestWidth : integer;
UnkChunkPlayer : TChunkPlayerProc);
begin
try
PlayChunksToRle( pchar(Frame) + sizeof(TFliFrame), FliSize, Dest, DestWidth, Frame.Chunks, UnkChunkPlayer );
except // Avoid any exception due to an invalid chunk
end;
end;
// Chunk Players
{$WARNINGS OFF}
function PlayChunksToRle( FirstChunk : pointer; const FliSize : TPoint; Dest : pointer; DestWidth : integer;
Count : integer; UnkChunkPlayer : TChunkPlayerProc ) : pointer;
const
idLastKnownChunk = 18;
var
SaveEAX : integer;
SaveECX : integer;
SaveEDX : integer;
SaveEBX : integer;
SaveESI : integer;
SaveEDI : integer;
TempVar : integer;
var
LastPixel : word;
label
JumpTable;
asm
// EAX = FirstChunk, EDX = @FliSize, ECX = Dest
cmp Count, 0
je @Exit
mov SaveEAX, eax
mov SaveEDX, edx
mov SaveECX, ecx
mov SaveEBX, ebx
mov SaveESI, esi
mov SaveEDI, edi
@PlayChunk:
xor ebx, ebx
mov bx, TFliChunkGeneric([eax]).Magic
cmp ebx, idLastKnownChunk
ja @PlayUnknown
jmp dword ptr JumpTable[ebx * 4]
// ---------------------------------------------------------------------------------------------
@PlayLC: // This chunk is found only in 320x200 FLIs
// Uses esi, edi, eax, ebx, ecx, edx
mov esi, SaveEAX
mov edi, SaveECX
xor eax, eax
xor ecx, ecx
add esi, type TFliChunkGeneric
mov TempVar, eax
lodsw // Lines to skip
or ax, ax
jz @@LCLineCount
mov word ptr [edi+0], rleJump // Store rleJump
shl ax, 8 // Now ah = rows, al = columns (0)
mov word ptr [edi+2], ax
add edi, 4
@@LCLineCount:
lodsw // Line count
mov edx, eax
@@LCLine:
xor ah, ah
lodsb // Load packet count
or al, al
jnz @@LCLinePackets
inc TempVar
jmp @@LCLineNext
@@LCLinePackets:
mov ebx, eax // ebx = packet count
mov eax, TempVar // Do we have lines to skip?
cmp al, 1
jb @@LCPacket // SkipCount = 0, ignore
ja @@LCLineSkip // SkipCount > 1, generate rleJump
mov ax, rleEndOfLine // SkipCount = 1, an rleEndOfLine will do it
stosw
jmp @@LCPacket
@@LCLineSkip:
shl eax, 24
mov ax, rleJump
stosd
xor eax, eax
mov TempVar, eax
@@LCPacket: // Process each packet
lodsb // Columns to skip
or al, al
jz @@LCTypeSize
mov word ptr [edi+0], rleJump // Store rleJump
xor ah, ah
mov word ptr [edi+2], ax // Store coordinates (x += al, y += 0)
add edi, 4
@@LCTypeSize:
lodsb // Type/Size byte
test al, al
js @@LCFill
@@LCMove:
cmp al, 3
jb @@LCMovePatch // If count < 3, we're in trouble, go to patch
mov cl, al
shl ax, 8
stosw // Store move command (al=0) and count (ah)
rep movsb
dec ebx
jnz @@LCPacket
jmp @@LCLineFinished
@@LCMovePatch:
mov cl, al
mov al, 1
@@LCMovePatchLoop:
stosb
movsb
dec ecx
jnz @@LCMovePatchLoop
dec ebx
jnz @@LCPacket
jmp @@LCLineFinished
@@LCFill:
neg al
stosb // Store count (al)
movsb // Store value
dec ebx
jnz @@LCPacket
@@LCLineFinished:
mov ax, rleEndOfLine
stosw
@@LCLineNext:
dec edx
jnz @@LCLine
@@LCChunkFinished:
mov ax, rleEndOfBitmap
stosw
jmp @NextChunk
// ---------------------------------------------------------------------------------------------
@PlaySS2: // Uses esi, edi, eax, ebx, ecx, edx
xor ecx, ecx
xor eax, eax
mov esi, SaveEAX
mov LastPixel, cx
add esi, type TFliChunkGeneric
lodsw // Line count
mov edi, SaveECX
mov TempVar, eax
@@SS2Line:
lodsw
test ah, $40
jnz @@SS2SkipLines
@@SS2OddWidth:
push edi
test ah, $80
jz @@SS2PacketCount
mov LastPixel, ax
lodsw // The packet count always follows this word
or eax, eax
jz @@SS2LastPixel
@@SS2PacketCount:
mov ebx, eax
xor eax, eax
@@SS2Packet: // Process each packet
mov cl, [esi + 0]
mov al, [esi + 1]
add edi, ecx
add esi, 2
test al, al
js @@SS2Fill
@@SS2Move:
mov ecx, eax
shr ecx, 1
and eax, 1
rep movsd
mov ecx, eax
rep movsw
dec ebx
jnz @@SS2Packet
@@SS2LineFinished:
mov ax, LastPixel // If AH = $80, we have to copy the last pixel (odd width flic)
or ah, ah
jz @@SS2Cont
@@SS2LastPixel:
stosb
@@SS2Cont:
pop edi
add edi, DestWidth
dec TempVar
jnz @@SS2Line
jmp @NextChunk
@@SS2SkipLines:
neg ax
@@SkipLines:
mov ax, 255
sub ax, cx // ax = min( cx, 255 ) (255 = maximum run in RLE)
cwd
and ax, dx
add ax, cx
shl ax, 8
stosw
shr ax, 8
sub cx, ax
jnz @@SkipLines
mul DestWidth
add edi, eax
xor eax, eax
jmp @@SS2Line
@@SS2Fill:
neg al
mov ecx, eax
mov ax, [esi] // value to repeat in AX
shl eax, 16
lodsw
shr ecx, 1
rep stosd
adc cl, cl
rep stosw
xor eax, eax
dec ebx
jnz @@SS2Packet
jmp @@SS2LineFinished
// ---------------------------------------------------------------------------------------------
@PlayUnknown:
cmp UnkChunkPlayer, 0
jz @NextChunk
mov eax, SaveEAX
mov edx, SaveEDX
mov ecx, SaveECX
mov ebx, SaveEBX
mov esi, SaveESI
mov edi, SaveEDI
// Chunk, FliSize and Dest are already passsed in EAX,EDX,ECX
push DestWidth // Pass DestWidth
call UnkChunkPlayer
jmp @NextChunk
// ---------------------------------------------------------------------------------------------
JumpTable:
dd @PlayUnknown // 0 ?
dd @PlayUnknown // 1 ?
dd @PlayUnknown // 2 ?
dd @PlayUnknown // 3 ?
dd @PlayUnknown // 4 o FLI_COLOR256
dd @PlayUnknown // 5 ?
dd @PlayUnknown // 6 ?
dd @PlayUnknown // 7 x FLI_SS2
dd @PlayUnknown // 8 ?
dd @PlayUnknown // 9 ?
dd @PlayUnknown // 10 ?
dd @PlayUnknown // 11 o FLI_COLOR
dd @PlayLC // 12 x FLI_LC
dd @PlayUnknown // 13 x FLI_BLACK
dd @PlayUnknown // 14 ?
dd @PlayUnknown // 15 x FLI_BRUN
dd @PlayUnknown // 16 x FLI_COPY
dd @PlayUnknown // 17 ?
dd @PlayUnknown // 18 o FLI_PSTAMP
@NextChunk:
mov eax, SaveEAX
add eax, TFliChunkGeneric([eax]).Size
mov SaveEAX, eax
dec Count
jnz @PlayChunk
mov ebx, SaveEBX
mov esi, SaveESI
mov edi, SaveEDI
@Exit:
end;
{$WARNINGS ON}
end.
|
object TClaveDlg: TTClaveDlg
Left = 301
Top = 206
ActiveControl = Nombre
BorderStyle = bsDialog
Caption = 'Ingrese su Nombre y Clave'
ClientHeight = 110
ClientWidth = 384
Color = clBtnFace
ParentFont = True
OldCreateOrder = True
Position = poScreenCenter
OnActivate = FormActivate
OnCreate = FormCreate
OnDestroy = FormDestroy
PixelsPerInch = 96
TextHeight = 13
object Bevel1: TBevel
Left = 8
Top = 8
Width = 281
Height = 97
Shape = bsFrame
end
object Label1: TLabel
Left = 28
Top = 30
Width = 36
Height = 13
Caption = 'Usuario'
end
object Label2: TLabel
Left = 28
Top = 66
Width = 27
Height = 13
Caption = 'Clave'
end
object OKBtn: TButton
Left = 300
Top = 20
Width = 75
Height = 25
Caption = 'Acepta'
Default = True
ModalResult = 1
TabOrder = 0
end
object CancelBtn: TButton
Left = 300
Top = 58
Width = 75
Height = 25
Cancel = True
Caption = 'Anula'
ModalResult = 2
TabOrder = 1
end
object Nombre: TEdit
Left = 96
Top = 26
Width = 157
Height = 21
CharCase = ecUpperCase
Color = 16765826
MaxLength = 10
TabOrder = 2
end
object Clave: TEdit
Left = 96
Top = 62
Width = 157
Height = 21
CharCase = ecUpperCase
Color = 16765826
PasswordChar = '*'
TabOrder = 3
end
object TClaves: TADODataSet
Connection = DMAdo.ADO
CommandText = 'Claves'
CommandType = cmdTable
IndexName = 'PK_Claves'
Parameters = <>
Left = 32
object TClavesNombre: TStringField
FieldName = 'Nombre'
Size = 12
end
object TClavesClave: TStringField
FieldName = 'Clave'
Size = 10
end
object TClavesDerecho: TStringField
FieldName = 'Derecho'
Size = 1
end
end
end
|
unit Styles;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListBox,
FMX.StdCtrls, FMX.Layouts, FMX.Edit;
type
TForm1 = class(TForm)
Layout1: TLayout;
Label1: TLabel;
cbStyles: TComboBox;
ListBoxItem1: TListBoxItem;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
ListBoxItem4: TListBoxItem;
Layout2: TLayout;
GridPanelLayout1: TGridPanelLayout;
Button1: TButton;
CheckBox1: TCheckBox;
RadioButton1: TRadioButton;
Label2: TLabel;
ProgressBar1: TProgressBar;
ScrollBar1: TScrollBar;
Expander1: TExpander;
TrackBar1: TTrackBar;
Switch1: TSwitch;
ListBox1: TListBox;
Edit1: TEdit;
ArcDial1: TArcDial;
procedure cbStylesChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses FMX.Styles;
procedure TForm1.cbStylesChange(Sender: TObject);
const
tosName: array[0..3] of String = ('Win','OSX','iOS','Android');
var
styleName: String;
begin
if cbStyles.ItemIndex = 0 then
TStyleManager.SetStyle(nil)
else begin
styleName := tosName[integer(TOSVersion.Platform)] + cbStyles.Selected.Text;
TStyleManager.SetStyle(
TStyleStreaming.LoadFromResource(
HInstance, styleName, RT_RCDATA));
end;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, FMX.ScrollBox, FMX.Memo,
DW.Notifications;
type
TForm1 = class(TForm)
ImmediateButton: TButton;
ScheduleButton: TButton;
CancelScheduled: TButton;
LogMemo: TMemo;
ScheduleRepeatingButton: TButton;
CancelImmediateButton: TButton;
procedure ImmediateButtonClick(Sender: TObject);
procedure ScheduleButtonClick(Sender: TObject);
procedure CancelScheduledClick(Sender: TObject);
procedure ScheduleRepeatingButtonClick(Sender: TObject);
procedure CancelImmediateButtonClick(Sender: TObject);
private
FNotifications: TNotifications;
procedure ImmediateNotification;
procedure NotificationReceivedHandler(Sender: TObject; const ANotification: TNotification);
procedure ScheduleNotification(const ASeconds: Integer; const ARepeating: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
{ TForm1 }
constructor TForm1.Create(AOwner: TComponent);
begin
inherited;
FNotifications := DW.Notifications.TNotifications.Create;
FNotifications.OnNotificationReceived := NotificationReceivedHandler;
end;
destructor TForm1.Destroy;
begin
FNotifications.Free;
inherited;
end;
procedure TForm1.ImmediateButtonClick(Sender: TObject);
begin
ImmediateNotification;
end;
procedure TForm1.ImmediateNotification;
var
LNotification: TNotification;
begin
LNotification.EnableSound := False;
LNotification.Name := 'ImmediateNotification';
LNotification.Title := 'Immediate Notification';
LNotification.Subtitle := 'Subtitles are cool';
LNotification.AlertBody := 'This is an immediate notification';
FNotifications.PresentNotification(LNotification);
end;
procedure TForm1.ScheduleButtonClick(Sender: TObject);
begin
ScheduleNotification(30, False);
end;
procedure TForm1.ScheduleNotification(const ASeconds: Integer; const ARepeating: Boolean);
var
LNotification: TNotification;
begin
LNotification.Name := 'ScheduledNotification';
LNotification.Title := 'I do not speak italian';
LNotification.Subtitle := 'Io non parlo italiano';
LNotification.EnableSound := False;
LNotification.AlertBody := 'This notification was scheduled - so there';
LNotification.FireDate := Now + EncodeTime(0, 0, ASeconds, 0);
if ARepeating then
LNotification.RepeatInterval := TRepeatInterval.Minute
else
LNotification.RepeatInterval := TRepeatInterval.None;
FNotifications.ScheduleNotification(LNotification);
end;
procedure TForm1.ScheduleRepeatingButtonClick(Sender: TObject);
begin
ScheduleNotification(10, True);
end;
procedure TForm1.CancelImmediateButtonClick(Sender: TObject);
begin
FNotifications.CancelNotification('ImmediateNotification');
end;
procedure TForm1.CancelScheduledClick(Sender: TObject);
begin
FNotifications.CancelNotification('ScheduledNotification');
end;
procedure TForm1.NotificationReceivedHandler(Sender: TObject; const ANotification: TNotification);
begin
LogMemo.Lines.Add(ANotification.Name + ' received with text: ' + ANotification.AlertBody);
end;
end.
|
unit Benjamim.Payload.Interfaces;
interface
uses
{$IF DEFINED(FPC)}
fpjson, Variants;
{$ELSE}
System.Variants, System.JSON;
{$ENDIF}
Type
iPayload = interface
['{A14B0231-CAB9-40BF-A0D1-91552D33FEA6}']
function Clear: iPayload;
function Add(const aKey: string; const aValue: string; aFormat: string = '"%s":"%s"'): iPayload; overload;
function Add(const aKey: string; const aValue: Int64; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: UInt64; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: Extended; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: TDateTime; aFormat: string = '"%s":"%s"'): iPayload; overload;
function Add(const aKey: string; const aValue: Boolean; aFormat: string = '"%s":%s'): iPayload; overload;
function Add(const aKey: string; const aValue: TJsonObject): iPayload; overload;
function Add(const aKey: string; const aValue: TJsonArray): iPayload; overload;
function Add(const aKey: string; const aValue: Variant): iPayload; overload;
function jti(const aID: UInt64): iPayload; { jti - Jwt ID - Jwt ID ( ID ) }
function iss(const aEmissor: String): iPayload; { iss - Issuer - Emissor ( Emissor ) }
function sub(const aAssunto: String): iPayload; { sub - Subject - Assunto }
function aud(const aRemoteIP: String): iPayload; { aud - Audience - Audiência ( Remote IP ) }
function iat(const aEmissionAt: TDateTime): iPayload; overload; { iat - Issued At - Emitido em ( Quando o Token foi Emitido / Automático ) }
function iat(const aEmissionAtUsDateTime: string): iPayload; overload; { iat - Issued At - Emitido em ( Quando o Token foi Emitido / Automático ) }
function nbf(const aValidityStarted: TDateTime): iPayload; overload; { nbf - Not Before - Validade Iniciada ( Inicia Em ) }
function nbf(const aValidityStartedUsDateTime: string): iPayload; overload; { nbf - Not Before - Validade Iniciada ( Inicia Em ) }
function exp(const aValidityEnded: TDateTime): iPayload; overload; { exp - Expiration Time - Validade Terminada ( Expirar Em ) }
function exp(const aValidityEndedUsDateTime: string): iPayload; overload; { exp - Expiration Time - Validade Terminada ( Expirar Em ) }
function AsJson(const aAsBase64: Boolean = false): string;
function AsJsonObject: TJsonObject;
end;
implementation
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.5 10/26/2004 10:59:30 PM JPMugaas
Updated ref.
Rev 1.4 2004.02.03 5:44:52 PM czhower
Name changes
Rev 1.3 10/5/2003 5:01:34 PM GGrieve
fix to compile Under DotNet
Rev 1.2 10/4/2003 9:09:28 PM GGrieve
DotNet fixes
Rev 1.1 10/3/2003 11:40:38 PM GGrieve
move InfyGetHostName here
Rev 1.0 11/14/2002 02:12:52 PM JPMugaas
2001-Sep-11 : DSiders
Corrected spelling for EIdAlreadyRegisteredAuthenticationMethod
}
unit IdAuthentication;
{
Implementation of the Basic authentication as specified in RFC 2616
Copyright: (c) Chad Z. Hower and The Winshoes Working Group.
Author: Doychin Bondzhev (doychin@dsoft-bg.com)
}
interface
{$i IdCompilerDefines.inc}
uses
Classes,
IdHeaderList,
IdGlobal,
IdException;
type
TIdAuthenticationSchemes = (asBasic, asDigest, asNTLM, asUnknown);
TIdAuthSchemeSet = set of TIdAuthenticationSchemes;
TIdAuthWhatsNext = (wnAskTheProgram, wnDoRequest, wnFail);
TIdAuthentication = class(TPersistent)
protected
FCurrentStep: Integer;
FParams: TIdHeaderList;
FAuthParams: TIdHeaderList;
function ReadAuthInfo(AuthName: String): String;
function DoNext: TIdAuthWhatsNext; virtual; abstract;
procedure SetAuthParams(AValue: TIdHeaderList);
function GetPassword: String;
function GetUserName: String;
function GetSteps: Integer; virtual;
procedure SetPassword(const Value: String); virtual;
procedure SetUserName(const Value: String); virtual;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Reset; virtual;
procedure SetRequest(const AMethod, AUri: String); virtual;
function Authentication: String; virtual; abstract;
function KeepAlive: Boolean; virtual;
function Next: TIdAuthWhatsNext;
property AuthParams: TIdHeaderList read FAuthParams write SetAuthParams;
property Params: TIdHeaderList read FParams;
property Username: String read GetUserName write SetUserName;
property Password: String read GetPassword write SetPassword;
property Steps: Integer read GetSteps;
property CurrentStep: Integer read FCurrentStep;
end;
TIdAuthenticationClass = class of TIdAuthentication;
TIdBasicAuthentication = class(TIdAuthentication)
protected
FRealm: String;
function DoNext: TIdAuthWhatsNext; override;
function GetSteps: Integer; override; // this function determines the number of steps that this
// Authtentication needs take to suceed;
public
function Authentication: String; override;
property Realm: String read FRealm write FRealm;
end;
EIdAlreadyRegisteredAuthenticationMethod = class(EIdException);
{ Support functions }
procedure RegisterAuthenticationMethod(const MethodName: String; const AuthClass: TIdAuthenticationClass);
procedure UnregisterAuthenticationMethod(const MethodName: String);
function FindAuthClass(const AuthName: String): TIdAuthenticationClass;
implementation
uses
IdCoderMIME, IdGlobalProtocols, IdResourceStringsProtocols, SysUtils;
var
AuthList: TStringList = nil;
procedure RegisterAuthenticationMethod(const MethodName: String; const AuthClass: TIdAuthenticationClass);
var
I: Integer;
begin
if not Assigned(AuthList) then begin
AuthList := TStringList.Create;
end;
I := AuthList.IndexOf(MethodName);
if I < 0 then begin
AuthList.AddObject(MethodName, TObject(AuthClass));
end else begin
//raise EIdAlreadyRegisteredAuthenticationMethod.CreateFmt(RSHTTPAuthAlreadyRegistered, [AuthClass.ClassName]);
AuthList.Objects[I] := TObject(AuthClass);
end;
end;
procedure UnregisterAuthenticationMethod(const MethodName: String);
var
I: Integer;
begin
if Assigned(AuthList) then begin
I := AuthList.IndexOf(MethodName);
if I >= 0 then begin
AuthList.Delete(I);
end;
end;
end;
function FindAuthClass(const AuthName: String): TIdAuthenticationClass;
var
I: Integer;
begin
I := AuthList.IndexOf(AuthName);
if I > -1 then begin
Result := TIdAuthenticationClass(AuthList.Objects[I]);
end else begin
Result := nil;
end;
end;
{ TIdAuthentication }
constructor TIdAuthentication.Create;
begin
inherited Create;
FAuthParams := TIdHeaderList.Create(QuoteHTTP);
FParams := TIdHeaderList.Create(QuoteHTTP);
FCurrentStep := 0;
end;
destructor TIdAuthentication.Destroy;
begin
FreeAndNil(FAuthParams);
FreeAndNil(FParams);
inherited Destroy;
end;
procedure TIdAuthentication.SetAuthParams(AValue: TIdHeaderList);
begin
FAuthParams.Assign(AValue);
end;
function TIdAuthentication.ReadAuthInfo(AuthName: String): String;
Var
i: Integer;
begin
for i := 0 to FAuthParams.Count - 1 do begin
if TextStartsWith(FAuthParams[i], AuthName) then begin
Result := FAuthParams[i];
Exit;
end;
end;
Result := ''; {Do not Localize}
end;
function TIdAuthentication.KeepAlive: Boolean;
begin
Result := False;
end;
function TIdAuthentication.Next: TIdAuthWhatsNext;
begin
Result := DoNext;
end;
procedure TIdAuthentication.Reset;
begin
FCurrentStep := 0;
end;
procedure TIdAuthentication.SetRequest(const AMethod, AUri: String);
begin
// empty here, descendants can override as needed...
end;
function TIdAuthentication.GetPassword: String;
begin
Result := Params.Values['Password']; {Do not Localize}
end;
function TIdAuthentication.GetUserName: String;
begin
Result := Params.Values['Username']; {Do not Localize}
end;
procedure TIdAuthentication.SetPassword(const Value: String);
begin
Params.Values['Password'] := Value; {Do not Localize}
end;
procedure TIdAuthentication.SetUserName(const Value: String);
begin
Params.Values['Username'] := Value; {Do not Localize}
end;
function TIdAuthentication.GetSteps: Integer;
begin
Result := 0;
end;
{ TIdBasicAuthentication }
function TIdBasicAuthentication.Authentication: String;
begin
with TIdEncoderMIME.Create do try
Result := 'Basic ' + Encode(Username + ':' + Password); {do not localize}
finally Free; end;
end;
function TIdBasicAuthentication.DoNext: TIdAuthWhatsNext;
var
S: String;
begin
S := ReadAuthInfo('Basic'); {Do not Localize}
Fetch(S);
while Length(S) > 0 do begin
with Params do begin
// realm have 'realm="SomeRealmValue"' format {Do not Localize}
// FRealm never assigned without StringReplace
Add(ReplaceOnlyFirst(Fetch(S, ', '), '=', NameValueSeparator)); {do not localize}
end;
end;
FRealm := Copy(Params.Values['realm'], 2, Length(Params.Values['realm']) - 2); {Do not Localize}
if FCurrentStep = 0 then
begin
if Length(Username) > 0 then begin
Result := wnDoRequest;
end else begin
Result := wnAskTheProgram;
end;
end else begin
Result := wnFail;
end;
end;
function TIdBasicAuthentication.GetSteps: Integer;
begin
Result := 1;
end;
initialization
RegisterAuthenticationMethod('Basic', TIdBasicAuthentication); {Do not Localize}
finalization
// UnregisterAuthenticationMethod('Basic') does not need to be called
// in this case because AuthList is freed.
FreeAndNil(AuthList);
end.
|
unit uPublic;
interface
uses Windows, Messages;
type
TCommType = (
ctNone, //--无类型
ctResult, //--返回结果
ctGroupName, //--设备端告诉中间服自己的组标识
ctSendMsg, //--发送短信
ctRecvMsg //--接收短信,设备端收到短信后返回给服务端
);
//--处理结果
TResultState = (
rsSuccess, //--成功
rsFail //--失败
);
//--记录设备链接信息
PDeviceInfo = ^TDeviceInfo;
TDeviceInfo = record
IsDevice: Boolean; //--标识是设备端, 还是客户端,
ConnectID: DWORD; //--Socket
GroupName: string[50];
IP: string[20];
Port: Word;
end;
// //--设置分组标识
// PGroupData = ^TGroupData;
// TGroupData = packed record
// CommType : TCommType;
// GroupName: TGroupName;
// end;
var
GFrmMainHwnd: HWND;
const
WM_ADD_LOG = WM_USER + 1001;
WM_ADD_DEVICE = WM_USER + 1002;
implementation
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-30
描述: 商品订单收货
*******************************************************************************}
unit UFormProductGet;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, USkinFormBase, UGridPainter, UFrameProductSale, Grids,
UGridExPainter, StdCtrls, ExtCtrls, cxGraphics, cxLookAndFeels,
cxLookAndFeelPainters, Menus, cxButtons;
type
TfFormProductGet = class(TSkinFormBase)
PanelL: TPanel;
PanelR: TPanel;
GridDetail: TDrawGridEx;
GridStyle: TDrawGridEx;
Splitter1: TSplitter;
Label1: TLabel;
LabelHint: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
FPainter: TGridPainter;
FPainterEx: TGridExPainter;
//绘制对象
FProductInfo: PProductItem;
//选中商品
procedure LoadStyleList;
//款式列表
procedure LoadProductList(const nStyleID: string);
//产品明细
procedure OnBtnClick(Sender: TObject);
procedure OnBtnClick2(Sender: TObject);
//点击按钮
public
{ Public declarations }
class function FormSkinID: string; override;
end;
function ShowGetProductForm(const nProduct: PProductItem): Boolean;
//选择商品
implementation
{$R *.dfm}
uses
IniFiles, ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule;
function ShowGetProductForm(const nProduct: PProductItem): Boolean;
begin
with TfFormProductGet.Create(Application) do
begin
FProductInfo := nProduct;
LoadStyleList;
Result := ShowModal = mrOk;
Free;
end;
end;
class function TfFormProductGet.FormSkinID: string;
begin
Result := 'FormDialog';
end;
procedure TfFormProductGet.FormCreate(Sender: TObject);
var nIni: TIniFile;
begin
FPainter := TGridPainter.Create(GridStyle);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('序号', 50);
AddHeader('款式名称', 50);
AddHeader('操作', 50);
end;
FPainterEx := TGridExPainter.Create(GridDetail);
with FPainterEx do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('颜色', 50, True);
AddHeader('尺寸', 50);
AddHeader('现有库存', 50);
AddHeader('零售价', 50);
AddHeader('操作', 50);
end;
nIni := TIniFile.Create(gPath + sFormConfig);
try
LoadFormConfig(Self);
PanelL.Width := nIni.ReadInteger(Name, 'PanelL', 120);
LoadDrawGridConfig(Name, GridStyle);
LoadDrawGridConfig(Name, GridDetail);
finally
nIni.Free;
end;
end;
procedure TfFormProductGet.FormClose(Sender: TObject;
var Action: TCloseAction);
var nIni: TIniFile;
begin
nIni := TIniFile.Create(gPath + sFormConfig);
try
SaveFormConfig(Self);
nIni.WriteInteger(Name, 'PanelL', PanelL.Width);
SaveDrawGridConfig(Name, GridStyle);
SaveDrawGridConfig(Name, GridDetail);
FPainter.Free;
FPainterEx.Free;
finally
nIni.Free;
end;
end;
//------------------------------------------------------------------------------
//Desc: 载入款式
procedure TfFormProductGet.LoadStyleList;
var nStr,nHint: string;
nDS: TDataSet;
nBtn: TcxButton;
nIdx,nInt: Integer;
nData: TGridDataArray;
begin
nStr := 'Select distinct st.StyleID,StyleName from $PT pt ' +
' Left Join $DPT dpt On dpt.ProductID=pt.P_ID ' +
' Left Join $ST st On st.StyleID=dpt.StyleID ' +
'Where P_TerminalID=''$ID'' And P_Number > 0 Order By StyleName';
//xxxxx
nStr := MacroValue(nStr, [MI('$PT', sTable_Product),
MI('$DPT', sTable_DL_Product), MI('$ST', sTable_DL_Style),
MI('$ID', gSysParam.FTerminalID)]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainter.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
First;
nInt := 1;
while not Eof do
begin
SetLength(nData, 4);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nData[1].FText := FieldByName('StyleName').AsString;
with nData[2] do
begin
FText := '';
FCtrls := TList.Create;
nBtn := TcxButton.Create(Self);
FCtrls.Add(nBtn);
with nBtn do
begin
Caption := '选择';
Width := 35;
Height := 18;
OnClick := OnBtnClick;
Tag := FPainter.DataCount;
end;
end;
nData[3].FText := FieldByName('StyleID').AsString;
FPainter.AddData(nData);
Next;
end;
end;
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 载入产品明细
procedure TfFormProductGet.LoadProductList(const nStyleID: string);
var nStr,nHint: string;
nInt,nNum: Integer;
nDS: TDataSet;
nBtn: TcxButton;
nRow: TGridExDataArray;
nCol: TGridExColDataArray;
begin
nStr := 'Select pt.*,StyleName,ColorName,SizeName,BrandName From $PT pt ' +
' Left Join $DPT dpt on dpt.ProductID=pt.P_ID ' +
' Left Join $ST st On st.StyleID=dpt.StyleID ' +
' Left Join $CR cr On cr.ColorID=dpt.ColorID ' +
' Left Join $SZ sz on sz.SizeID=dpt.SizeID ' +
' Left Join $BR br On br.BrandID=dpt.BrandID ' +
'Where dpt.StyleID=''$SID'' ' +
'Order By ColorName,SizeName';
//xxxxx
nStr := MacroValue(nStr, [MI('$PT', sTable_Product),
MI('$DPT', sTable_DL_Product), MI('$BR', sTable_DL_Brand),
MI('$ST', sTable_DL_Style), MI('$CR', sTable_DL_Color),
MI('$SZ', sTable_DL_Size), MI('$ID', gSysParam.FTerminalID),
MI('$SID', nStyleID)]);
//xxxxx
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
FPainterEx.ClearData;
if nDS.RecordCount < 1 then Exit;
with nDS do
begin
First;
LabelHint.Caption := FieldByName('StyleName').AsString;
nHint := '';
nNum := 0;
while not Eof do
begin
SetLength(nRow, 9);
for nInt:=Low(nRow) to High(nRow) do
begin
nRow[nInt].FCtrls := nil;
nRow[nInt].FAlign := taCenter;
end;
nRow[0].FText := FieldByName('SizeName').AsString;
nRow[1].FText := IntToStr(FieldByName('P_Number').AsInteger);
nRow[2].FText := Format('%.2f', [FieldByName('P_Price').AsFloat]);
with nRow[3] do
begin
FText := '';
FCtrls := TList.Create;
nBtn := TcxButton.Create(Self);
FCtrls.Add(nBtn);
with nBtn do
begin
Caption := '选择';
Width := 35;
Height := 18;
OnClick := OnBtnClick2;
Tag := FPainterEx.DataCount;
end;
end;
nRow[4].FText := FieldByName('P_ID').AsString;
nRow[5].FText := Format('%.2f', [FieldByName('P_OldPrice').AsFloat]);
nRow[6].FText := FieldByName('ColorName').AsString;
nRow[7].FText := FieldByName('BrandName').AsString;
nRow[8].FText := FloatToStr(FieldByName('P_InPrice').AsFloat);
FPainterEx.AddRowData(nRow);
//添加行数据
//----------------------------------------------------------------------
if nHint = '' then
nHint := FieldByName('ColorName').AsString;
//first time
if nHint = FieldByName('ColorName').AsString then
begin
Inc(nNum);
Next; Continue;
end;
SetLength(nCol, 1);
with nCol[0] do
begin
FCol := 0;
FRows := nNum;
FAlign := taCenter;
FText := nHint;
nNum := 1;
nHint := FieldByName('ColorName').AsString;
end;
FPainterEx.AddColData(nCol);
Next;
end;
end;
if nNum > 0 then
begin
SetLength(nCol, 1);
with nCol[0] do
begin
FCol := 0;
FRows := nNum;
FAlign := taCenter;
FText := nHint;
end;
FPainterEx.AddColData(nCol);
end;
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 选择款式
procedure TfFormProductGet.OnBtnClick(Sender: TObject);
var nTag: Integer;
begin
nTag := TComponent(Sender).Tag;
FProductInfo.FStyleName := FPainter.Data[nTag][1].FText;
LoadProductList(FPainter.Data[nTag][3].FText);
end;
//Desc: 选择商品
procedure TfFormProductGet.OnBtnClick2(Sender: TObject);
var nTag: Integer;
begin
nTag := TComponent(Sender).Tag;
with FProductInfo^,FPainterEx do
begin
if StrToFloat(Data[nTag][2].FText) <= 0 then
begin
ShowMsg('零售价无效', sHint); Exit;
end;
FProductID := Data[nTag][4].FText;
FColorName := Data[nTag][6].FText;
FSizeName := Data[nTag][0].FText;
FNumSale := 1;
FNumStore := StrToInt(Data[nTag][1].FText);
FPriceSale := StrToFloat(Data[nTag][2].FText);
FPriceOld := StrToFloat(Data[nTag][5].FText);
FPriceIn := StrToFloat(Data[nTag][8].FText);
FBrandName := Data[nTag][7].FText;
ModalResult := mrOk;
end;
end;
end.
|
{ *************************************************************************** }
{ }
{ }
{ Copyright (C) Amarildo Lacerda }
{ }
{ https://github.com/amarildolacerda }
{ }
{ }
{ *************************************************************************** }
{ }
{ 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 Data.ObjectDataSet;
interface
uses System.Classes, System.Rtti, Data.DB,
JvMemoryDataSet,
System.SysUtils, System.Generics.Collections, System.Contnrs;
type
TObjectListEvent = procedure(sender: TObject; Action: TListNotification)
of object;
TObjectListEventing = class(TObjectList)
private
FOnAddEvent: TObjectListEvent;
procedure SetOnAddEvent(const Value: TObjectListEvent);
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
public
property OnNotifyEvent: TObjectListEvent read FOnAddEvent
write SetOnAddEvent;
end;
TObjectDataSet = class(TJvMemoryData)
private
FActiveRow:integer;
FNotifyControls: integer;
FObjectClass: TClass;
FStringMax: integer;
FObjectList: TObjectListEventing;
FObjectListOwned: Boolean;
FObjectClassName: string;
procedure InternalInitFieldDefsObjectClass;
procedure InternalDelete; override;
procedure DoBeforeInsert;override;
procedure InternalInsert; override;
procedure InternalPost; override;
procedure InternalEdit; override;
procedure DoAfterEdit; override;
procedure DoAfterInsert;override;
procedure InternalClose;override;
procedure DoAddToObjectListEvent(sender: TObject;
Action: TListNotification);
function GetRecNo: Integer; override;
procedure SetObjectClass(const Value: TClass);
procedure SetStringMax(const Value: integer);
procedure InternalSetToRecord(Buffer: TRecBuf); overload; override;
procedure SetOwnsObjects(const Value: Boolean);
function GetOwnsObjects: Boolean;
procedure SetObjectClassName(const Value: string);
procedure SetObjectList(const Value: TObjectListEventing);
public
constructor create(AOwner: TComponent); overload; override;
constructor create(AOwnder: TComponent; AClass: TClass); overload;
destructor destroy; override;
procedure FieldToObject(LRow: integer);overload;
procedure FieldToObject(Obj:TObject);overload;
procedure ObjectToField(LRow: integer);overload;
procedure ObjectToField(Obj:TObject);overload;
procedure DisableListControls;
procedure EnableListControls;
procedure Reopen;
published
procedure LoadFromList( AList:TList );
procedure SaveToList( AList:TList );
property ObjectClass: TClass read FObjectClass write SetObjectClass;
property ObjectList: TObjectListEventing read FObjectList
write SetObjectList;
property OwnsObjects: Boolean read GetOwnsObjects write SetOwnsObjects;
property ObjectClassName: string read FObjectClassName
write SetObjectClassName;
property StringWidth: integer read FStringMax write SetStringMax;
end;
implementation
constructor TObjectDataSet.create(AOwner: TComponent);
begin
inherited;
FStringMax := 255;
FObjectList := TObjectListEventing.create(true);
FObjectListOwned := true;
FObjectList.OnNotifyEvent := DoAddToObjectListEvent;
end;
constructor TObjectDataSet.create(AOwnder: TComponent; AClass: TClass);
begin
create(AOwnder);
ObjectClass := AClass;
end;
destructor TObjectDataSet.destroy;
begin
FObjectList.OnNotifyEvent := nil;
if FObjectListOwned then
FreeAndNil(FObjectList);
inherited;
end;
procedure TObjectDataSet.DoAfterEdit;
var
LRow: integer;
begin
inherited;
LRow := GetRecNo - 1;
if (LRow >= 0) and (LRow < FObjectList.Count) then
ObjectToField(LRow);
end;
procedure TObjectDataSet.DoAfterInsert;
begin
inherited;
end;
procedure TObjectDataSet.DoBeforeInsert;
begin
last;
inherited;
end;
procedure TObjectDataSet.DoAddToObjectListEvent(sender: TObject;
Action: TListNotification);
var
LRow: integer;
begin
if (FNotifyControls > 0) then
exit;
case Action of
lnAdded:
begin
if state in dsEditModes then
post;
DisableListControls;
try
insert;
LRow := GetRecNo - 1;
if (LRow >= 0) and (LRow < FObjectList.Count) then
FieldToObject(LRow);
finally
EnableListControls;
end;
end;
lnExtracted:
;
lnDeleted:
;
end;
end;
procedure TObjectDataSet.FieldToObject(LRow: integer);
var obj:TObject;
begin
obj := FObjectList.Items[LRow];
FieldToObject(obj);
end;
function TObjectDataSet.GetOwnsObjects: Boolean;
begin
result := FObjectList.OwnsObjects;
end;
function TObjectDataSet.GetRecNo: Integer;
begin
if state in [dsInsert] then
result := FActiveRow +1
else
result := inherited GetRecNo;
end;
procedure TObjectDataSet.InternalClose;
begin
inherited;
if assigned(FObjectList) then
FObjectList.Clear;
end;
procedure TObjectDataSet.InternalDelete;
var
LRow: integer;
begin
LRow := GetRecNo - 1;
inherited;
if (LRow >= 0) and (LRow < FObjectList.Count) then
FObjectList.Delete(LRow);
end;
procedure TObjectDataSet.InternalEdit;
begin
inherited;
end;
procedure TObjectDataSet.InternalInitFieldDefsObjectClass;
var
LContext: TRttiContext;
LRttiType: TRttiType;
LRttiProp: TRttiProperty;
FType: TFieldType;
FSize: integer;
begin
LContext := TRttiContext.create();
try
LRttiType := LContext.GetType(FObjectClass);
for LRttiProp in LRttiType.GetProperties do
begin
FType := ftString;
FSize := FStringMax;
case LRttiProp.PropertyType.TypeKind of
tkInteger, tkInt64:
begin
FType := ftInteger;
FSize := 0;
end;
tkFloat:
begin
FSize := 0;
if LRttiProp.PropertyType.Name.Equals('TDateTime') then
FType := ftDateTime
else if LRttiProp.PropertyType.Name.Equals('TDate') then
FType := ftDate
else if LRttiProp.PropertyType.Name.Equals('TTime') then
FType := ftTime
else if LRttiProp.PropertyType.Name.Equals('Currency') then
FType := ftCurrency
else
FType := ftFloat;
end;
tkVariant:
FType := ftVariant;
end;
fieldDefs.Add(LRttiProp.Name, FType, FSize);
end;
finally
LContext.Free;
end;
end;
procedure TObjectDataSet.InternalInsert;
begin
inherited;
if FNotifyControls = 0 then
begin
DisableListControls;
try
FObjectList.Add(FObjectClass.create);
FActiveRow := FObjectList.Count-1;
if (FActiveRow >= 0) and (FActiveRow < FObjectList.Count) then
FieldToObject(FActiveRow);
finally
EnableListControls;
end;
end;
end;
procedure TObjectDataSet.InternalPost;
var
LRow: integer;
begin
inherited;
LRow := GetRecNo - 1;
if (LRow >= 0) and (LRow < FObjectList.Count) then
begin
FieldToObject(LRow);
end;
end;
procedure TObjectDataSet.InternalSetToRecord(Buffer: TRecBuf);
begin
inherited InternalSetToRecord(Buffer);
end;
procedure TObjectDataSet.LoadFromList(AList: TList);
var obj:TObject;
nObj:TObject;
i:integer;
begin
if AList.Count=0 then exit; // nao tem nada para ler
try
try
if active then
EmptyTable;
close;
FieldDefs.Clear;
obj := AList.Items[0];
ObjectClass := obj.ClassType;
open;
for I := 0 to AList.Count-1 do
begin
obj := AList.Items[i];
append;
ObjectToField(obj);
Post;
end;
finally
end;
finally
Resync([]);
end;
end;
procedure TObjectDataSet.ObjectToField(Obj: TObject);
var
LNome: string;
LContext: TRttiContext;
LType: TRttiType;
LProp: TRttiProperty;
LVar: TValue;
fld: TField;
begin
LContext := TRttiContext.create;
try
LType := LContext.GetType(obj.ClassType);
for LProp in LType.GetProperties do
begin
fld := Fields.FindField(LProp.Name);
if fld <> nil then
begin
LVar := LProp.GetValue(obj);
fld.Value := LVar.AsVariant;
end;
end;
finally
LContext.Free;
end;
end;
procedure TObjectDataSet.ObjectToField(LRow: integer);
var obj:TObject;
begin
if (LRow >= 0) and (LRow < FObjectList.Count) then
begin
obj := FObjectList.Items[LRow];
ObjectToField(obj);
end;
end;
procedure TObjectDataSet.Reopen;
begin
close;
open;
end;
procedure TObjectDataSet.SaveToList(AList: TList);
var i:integer;
obj:TObject;
book:TBookmark;
OldRow:Integer;
begin
DisableControls;
try
oldRow := GetRecNo;
AList.Clear;
first;
while eof=false do
begin
obj := FObjectClass.Create;
FieldToObject(obj);
AList.Add(obj);
next;
end;
finally
SetRecNo(oldRow);
EnableControls;
end;
end;
procedure TObjectDataSet.SetObjectClass(const Value: TClass);
begin
FObjectClass := Value;
InternalInitFieldDefsObjectClass;
end;
procedure TObjectDataSet.SetObjectClassName(const Value: string);
begin
FObjectClassName := Value;
ObjectClass := FindClass(Value);
end;
procedure TObjectDataSet.SetObjectList(const Value: TObjectListEventing);
begin
FObjectList.OnNotifyEvent := nil;
FreeAndNil(FObjectList);
FObjectList := Value;
FObjectList.OnNotifyEvent := DoAddToObjectListEvent;
FObjectListOwned := false;
end;
procedure TObjectDataSet.SetOwnsObjects(const Value: Boolean);
begin
FObjectList.OwnsObjects := Value;
end;
procedure TObjectDataSet.SetStringMax(const Value: integer);
begin
FStringMax := Value;
end;
{ TObjectListChangeEvent }
procedure TObjectDataSet.DisableListControls;
begin
inc(FNotifyControls);
end;
procedure TObjectDataSet.EnableListControls;
begin
dec(FNotifyControls);
if FNotifyControls < 0 then
FNotifyControls := 0;
end;
procedure TObjectDataSet.FieldToObject(Obj: TObject);
var
LContext: TRttiContext;
LTypes: TRttiType;
LProp: TRttiProperty;
fld: TField;
LVal: TValue;
begin
LContext := TRttiContext.create;
try
LTypes := LContext.GetType(obj.ClassType);
for LProp in LTypes.GetProperties do
begin
fld := Fields.FindField(LProp.Name);
if fld <> nil then
begin
LVal := TValue.From<variant>(fld.Value);
LProp.SetValue(obj, LVal);
end;
end;
finally
LContext.Free;
end;
end;
{ TObjectListEventing }
procedure TObjectListEventing.Notify(Ptr: Pointer; Action: TListNotification);
begin
inherited;
if assigned(FOnAddEvent) then
FOnAddEvent(self, Action);
end;
procedure TObjectListEventing.SetOnAddEvent(const Value: TObjectListEvent);
begin
FOnAddEvent := Value;
end;
end.
|
{
Faça um algoritmo utilizando sub-rotinas que leia um vetor de registros com os campos: nome , P1, P2, P3 e P4 de
N(N<=50) alunos de um colégio. Após a leitura faça:
? Imprima o Nome e a média dos alunos aprovados (Média aritmética >= 5.0).
? Imprima o Nome e a média dos alunos em Recuperação (3.0 >= Média < 5.0).
? Imprima o Nome e a média dos alunos reprovados (Média < 3.0).
? Imprima o percentual de alunos aprovados.
? Imprima o percentual de alunos em exame
? Imprima o percentual de alunos reprovados.
}
Program Exercicio6 ;
Type
reg_aluno = record
nome: string;
p1: real;
p2: real;
p3: real;
p4: real;
media: real;
end;
vet_alunos = array[1..50] of reg_aluno;
var
vet:vet_alunos;
n:integer;
qtdA:integer;
qtdE:integer;
qtdR:integer;
procedure verificarQuantidade(var qtd:integer);
begin
repeat
write('Digite a quantidade de alunso entre 1 e 50: ');
readln(n);
until (qtd >0) and (qtd <= 50);
end;
procedure cadastrarAlunos(var alunos:vet_alunos);
var
i:integer;
nome:string;
begin
for i := 1 to n do
begin
writeln('--------------------------------------------------');
write('Digite o nome do ',i,'o aluno: ');
readln(alunos[i].nome);
write('Digite a p1: ');
readln(alunos[i].p1);
write('Digite a p2: ');
readln(alunos[i].p2);
write('Digite a p3: ');
readln(alunos[i].p3);
write('Digite a p4: ');
readln(alunos[i].p4);
alunos[i].media := (alunos[i].p1 + alunos[i].p2 + alunos[i].p3 + alunos[i].p4)/4;
writeln('A média dele é: ', alunos[i].media);
end;
end;
procedure mostrarNotasPorSituacao(alunos:vet_alunos; n:integer; situacao:char; var count:integer);
var i:integer;
begin
case situacao of
'a':
begin
count :=0;
for i := 1 to n do
begin
if(alunos[i].media >= 5) then
begin
count := count +1;
writeln('Aluno: ',alunos[i].nome,' aprovado com ', alunos[i].media);
end;
end;
end;
'e':
begin
count := 0;
for i := 1 to n do
begin
if((alunos[i].media >= 3) and (alunos[i].media < 5)) then
begin
count := count + 1;
writeln('Aluno: ',alunos[i].nome,' em exame com ', alunos[i].media);
end;
end;
end;
'r':
begin
count := 0;
for i := 1 to n do
begin
if(alunos[i].media < 3) then
begin
count := count + 1;
writeln('Aluno: ',alunos[i].nome,' reprovado com ', alunos[i].media);
end;
end;
end;
end;
end;
Begin
qtdA :=0;
qtdE :=0;
qtdR :=0;
verificarQuantidade(n);
cadastrarAlunos(vet);
writeln('------------------Lista de Aunos Aprovados (>= 5)----------------');
mostrarNotasPorSituacao(vet, n, 'a', qtdA);
writeln('Total de: ', (qtdA/n), '%');
writeln('------------------Lista de Aunos em Exame (>= 3 < 5)----------------');
mostrarNotasPorSituacao(vet, n, 'e', qtdE);
writeln('Total de: ', (qtdE/n), '%');
writeln('------------------Lista de Aunos Reprovados (< 3)----------------');
mostrarNotasPorSituacao(vet, n, 'r', qtdR);
writeln('Total de: ', (qtdR/n), '%');
End. |
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdMessage, IdBaseComponent, IdComponent, IdTCPConnection,
IdTCPClient, IdMessageClient, IdSMTP, StdCtrls, Buttons, ComCtrls,
ImgList, IniFiles;
type
TForm1 = class(TForm)
EdAssunto: TEdit;
Label1: TLabel;
EdEmail: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
IdSMTP1: TIdSMTP;
IdMessage1: TIdMessage;
OpenDialog1: TOpenDialog;
BitBtn1: TBitBtn;
MTexto: TMemo;
Label5: TLabel;
edCopia: TEdit;
btnEnviar: TBitBtn;
btnSair: TBitBtn;
lstAnexos: TListView;
ImageList1: TImageList;
procedure BitBtn1Click(Sender: TObject);
procedure btnEnviarClick(Sender: TObject);
procedure btnSairClick(Sender: TObject);
procedure EdEmailKeyPress(Sender: TObject; var Key: Char);
procedure edCopiaKeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lstAnexosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
listaAnexos: TStrings;
function EnviaEmail(email: string; Copia: string; Assunto: string; Texto: string; ArqAnexo: TStrings): Boolean;
procedure Limpar;
public
end;
var
Form1 : TForm1;
implementation
{$R *.dfm}
function TForm1.EnviaEmail(email: string; Copia: string; Assunto: string; Texto: string; ArqAnexo: TStrings): Boolean;
var
I : Integer;
Ini : TiniFile;
begin
if EMail = '' then
begin
MessageDlg('Digite o e-mail !', mtInformation, [MBOK], 0);
end
else
begin
IdMessage1.Body.Clear;
IdMessage1.MessageParts.Clear;
IdMessage1.Body.Add(Texto);
IdMessage1.From.Address := 'flavio@americasoft.com.br';
IdMessage1.Recipients.EMailAddresses := Email;
IdMessage1.CCList.EMailAddresses := Copia;
IdMessage1.Subject := Assunto;
for I := 0 to ArqAnexo.Count - 1 do
TIdAttachment.Create(IdMessage1.MessageParts, ArqAnexo[I]);
IdSMTP1.AuthenticationType := atLogin;
IdSMTP1.UserId := 'flavio@americasoft.com.br';
IdSMTP1.MailAgent := 'flavio@americasoft.com.br'; //'udimed08@terra.com.br';
IdSMTP1.Password := 'O8dO29Rk'; //'compra02';
IdSMTP1.Host := 'smtp.americasoft.com.br'; //'smtp.sao.terra.com.br';
IdSMTP1.Port := 25;
try
begin
IdSMTP1.Connect;
IdSMTP1.Send(IdMessage1);
Result := True; //'Enviado com sucesso.';
end;
except
Result := False; //'Erro na Conexão, email não enviado.';
end;
IdSMTP1.Disconnect;
IdMessage1.MessageParts.Clear;
end;
end;
procedure TForm1.BitBtn1Click(Sender: TObject);
var
Item : TListItem;
begin
if OpenDialog1.Execute then
begin
listaAnexos.Add(OpenDialog1.FileName);
with lstAnexos do
begin
Item := Items.Add;
Item.Caption := ExtractFileName(OpenDialog1.FileName);
Item.SubItems.Add(OpenDialog1.FileName);
Item.ImageIndex := 0;
end;
end;
end;
procedure TForm1.btnEnviarClick(Sender: TObject);
begin
if EnviaEmail(EdEmail.Text, EdCopia.Text, EdAssunto.Text, MTexto.Text, listaAnexos) then
ShowMessage('E-Mail enviado com Sucesso')
else
ShowMessage('Erro ao enviar email');
end;
procedure TForm1.btnSairClick(Sender: TObject);
begin
Close;
end;
procedure TForm1.EdEmailKeyPress(Sender: TObject; var Key: Char);
begin
if key = ';' then
key := #44
end;
procedure TForm1.edCopiaKeyPress(Sender: TObject; var Key: Char);
begin
if key = ';' then
key := #44
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
listaAnexos := TStringList.Create;
end;
procedure TForm1.Limpar;
begin
EdAssunto.Text := '';
EdEmail.Text := '';
edCopia.Text := '';
MTexto.Lines.Text := '';
lstAnexos.Items.Clear;
EdAssunto.SetFocus;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
Limpar;
end;
procedure TForm1.lstAnexosKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key in [46, 109] then
begin
listaAnexos.Delete(listaAnexos.IndexOf(lstAnexos.ItemFocused.SubItems[0]));
lstAnexos.ItemFocused.Delete;
end;
end;
end.
|
unit m3BaseHeaderStream;
// Модуль: "w:\common\components\rtl\Garant\m3\m3BaseHeaderStream.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "Tm3BaseHeaderStream" MUID: (53FF134A03BA)
{$Include w:\common\components\rtl\Garant\m3\m3Define.inc}
interface
uses
l3IntfUses
, m3LinkedStream
, Classes
, m3Const
;
const
cHeaderFullSize = m3Const.Cm3BasClaDefHeaderSize;
type
Tm3BaseHeaderStream = class(Tm3LinkedStream)
private
FHeaderLocked: Integer;
protected
FHeaderSize: Integer;
FHeaderLoaded: Integer;
protected
procedure DefaultInitAction; virtual;
procedure DefaultDoneAction; virtual;
function DoLockHeader: Boolean; virtual;
function DoUnlockHeader: Boolean; virtual;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure DoSeek(anOffset: Int64;
anOrigin: TSeekOrigin;
var theResult: Int64;
var theReturn: hResult); override;
procedure DoSetSize(aSize: Int64;
var theReturn: hResult); override;
procedure LockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult); override;
procedure UnlockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult); override;
function DoGetSize: Int64; override;
public
procedure LockHeader;
{* закрывает заголовок }
procedure UnlockHeader;
{* открывает заголовок }
procedure DoSaveHeader(aForceSave: Boolean); virtual; abstract;
{* сохраняет заголовок }
procedure DoLoadHeader; virtual; abstract;
{* загружает заголовок в память }
procedure LoadHeader;
procedure SaveHeader(aForceSave: Boolean = False);
end;//Tm3BaseHeaderStream
implementation
uses
l3ImplUses
, ComObj
, m2COMLib
, ActiveX
, l3Base
, l3Interlocked
//#UC START# *53FF134A03BAimpl_uses*
//#UC END# *53FF134A03BAimpl_uses*
;
procedure Tm3BaseHeaderStream.LockHeader;
{* закрывает заголовок }
//#UC START# *53FDFE220358_53FF134A03BA_var*
//#UC END# *53FDFE220358_53FF134A03BA_var*
begin
//#UC START# *53FDFE220358_53FF134A03BA_impl*
Assert(FHeaderSize > CAnyGUIDLength);
if (FHeaderLocked = 0) then
DoLockHeader;
l3InterlockedIncrement(FHeaderLocked);
//#UC END# *53FDFE220358_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.LockHeader
procedure Tm3BaseHeaderStream.UnlockHeader;
{* открывает заголовок }
//#UC START# *53FDFE3802D0_53FF134A03BA_var*
//#UC END# *53FDFE3802D0_53FF134A03BA_var*
begin
//#UC START# *53FDFE3802D0_53FF134A03BA_impl*
Assert(FHeaderSize > CAnyGUIDLength);
if (l3InterlockedDecrement(FHeaderLocked) = 0) then
DoUnlockHeader;
//#UC END# *53FDFE3802D0_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.UnlockHeader
procedure Tm3BaseHeaderStream.LoadHeader;
//#UC START# *53FF1F6901C5_53FF134A03BA_var*
//#UC END# *53FF1F6901C5_53FF134A03BA_var*
begin
//#UC START# *53FF1F6901C5_53FF134A03BA_impl*
if (FHeaderLoaded = 0) then
if (InnerStream <> nil) AND (m2COMGetStatStgMode(InnerStream) AND STGM_WRITE = 0) then
// - мы не можем считать Header - значит он уже должен быть у нас
begin
LockHeader;
try
DoLoadHeader;
finally
UnlockHeader;
end;//try..finally
end;//_Stream <> nil..
l3InterlockedIncrement(FHeaderLoaded);
//#UC END# *53FF1F6901C5_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.LoadHeader
procedure Tm3BaseHeaderStream.SaveHeader(aForceSave: Boolean = False);
//#UC START# *53FF1F90030A_53FF134A03BA_var*
//#UC END# *53FF1F90030A_53FF134A03BA_var*
begin
//#UC START# *53FF1F90030A_53FF134A03BA_impl*
if (l3InterlockedDecrement(FHeaderLoaded) = 0) then
if (InnerStream <> nil) AND not ReadOnly then
begin
LockHeader;
try
DoSaveHeader(aForceSave);
finally
UnlockHeader;
end;//try..finally
end;//FHeaderLoaded = 0..
//#UC END# *53FF1F90030A_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.SaveHeader
procedure Tm3BaseHeaderStream.DefaultInitAction;
//#UC START# *53FDFD1D0164_53FF134A03BA_var*
//#UC END# *53FDFD1D0164_53FF134A03BA_var*
begin
//#UC START# *53FDFD1D0164_53FF134A03BA_impl*
LoadHeader;
//#UC END# *53FDFD1D0164_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DefaultInitAction
procedure Tm3BaseHeaderStream.DefaultDoneAction;
//#UC START# *53FDFD34034B_53FF134A03BA_var*
//#UC END# *53FDFD34034B_53FF134A03BA_var*
begin
//#UC START# *53FDFD34034B_53FF134A03BA_impl*
SaveHeader;
//#UC END# *53FDFD34034B_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DefaultDoneAction
function Tm3BaseHeaderStream.DoLockHeader: Boolean;
//#UC START# *540F07260255_53FF134A03BA_var*
//#UC END# *540F07260255_53FF134A03BA_var*
begin
//#UC START# *540F07260255_53FF134A03BA_impl*
Result := m2COMTimeLock(InnerStream, CAnyGUIDLength, Int64(FHeaderSize) - CAnyGUIDLength);
//#UC END# *540F07260255_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DoLockHeader
function Tm3BaseHeaderStream.DoUnlockHeader: Boolean;
//#UC START# *540F072F02B4_53FF134A03BA_var*
//#UC END# *540F072F02B4_53FF134A03BA_var*
begin
//#UC START# *540F072F02B4_53FF134A03BA_impl*
Result := m2COMTimeUnlock(InnerStream, CAnyGUIDLength, Int64(FHeaderSize) - CAnyGUIDLength);
//#UC END# *540F072F02B4_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DoUnlockHeader
procedure Tm3BaseHeaderStream.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_53FF134A03BA_var*
//#UC END# *479731C50290_53FF134A03BA_var*
begin
//#UC START# *479731C50290_53FF134A03BA_impl*
FHeaderSize := 0;
FHeaderLocked := 0;
FHeaderLoaded := 0;
inherited;
//#UC END# *479731C50290_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.Cleanup
procedure Tm3BaseHeaderStream.DoSeek(anOffset: Int64;
anOrigin: TSeekOrigin;
var theResult: Int64;
var theReturn: hResult);
//#UC START# *4FA27D5302C5_53FF134A03BA_var*
var
LOffset : Int64;
//#UC END# *4FA27D5302C5_53FF134A03BA_var*
begin
//#UC START# *4FA27D5302C5_53FF134A03BA_impl*
if SUCCEEDED(theReturn) then
begin
if (anOrigin = soBeginning) then
LOffset := anOffset + Int64(FHeaderSize)
else
if (anOrigin = soEnd) then
begin
Assert(anOffset = 0, 'Если это всплывёт, то можно этот Assert временно закомментирровать');
LOffset := anOffset;
end//AOrigin = soEnd
else
LOffset := anOffset;
theResult := m2COMSeek(InnerStream, LOffset, Ord(anOrigin)) - Int64(FHeaderSize);
end;//SUCCEEDED(AReturn)
//#UC END# *4FA27D5302C5_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DoSeek
procedure Tm3BaseHeaderStream.DoSetSize(aSize: Int64;
var theReturn: hResult);
//#UC START# *4FA27DCD02B4_53FF134A03BA_var*
//#UC END# *4FA27DCD02B4_53FF134A03BA_var*
begin
//#UC START# *4FA27DCD02B4_53FF134A03BA_impl*
if SUCCEEDED(theReturn) then
theReturn := InnerStream.SetSize(aSize + Int64(FHeaderSize));
//#UC END# *4FA27DCD02B4_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DoSetSize
procedure Tm3BaseHeaderStream.LockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult);
//#UC START# *4FA27E100218_53FF134A03BA_var*
//#UC END# *4FA27E100218_53FF134A03BA_var*
begin
//#UC START# *4FA27E100218_53FF134A03BA_impl*
if SUCCEEDED(theReturn) then
theReturn := InnerStream.LockRegion(Int64(FHeaderSize) + anOffset, aSize, aLockType);
//#UC END# *4FA27E100218_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.LockRegion
procedure Tm3BaseHeaderStream.UnlockRegion(anOffset: Int64;
aSize: Int64;
aLockType: Integer;
var theReturn: hResult);
//#UC START# *4FA27E4C0342_53FF134A03BA_var*
//#UC END# *4FA27E4C0342_53FF134A03BA_var*
begin
//#UC START# *4FA27E4C0342_53FF134A03BA_impl*
if SUCCEEDED(theReturn) then
theReturn := InnerStream.UnlockRegion(Int64(FHeaderSize) + anOffset, aSize, aLockType);
//#UC END# *4FA27E4C0342_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.UnlockRegion
function Tm3BaseHeaderStream.DoGetSize: Int64;
//#UC START# *4FA2802E0231_53FF134A03BA_var*
//#UC END# *4FA2802E0231_53FF134A03BA_var*
begin
//#UC START# *4FA2802E0231_53FF134A03BA_impl*
Result := {m2COMGetStatStgSize}m2COMGetSize(InnerStream) - Int64(FHeaderSize);
//#UC END# *4FA2802E0231_53FF134A03BA_impl*
end;//Tm3BaseHeaderStream.DoGetSize
end.
|
unit ExceptionMaganer;
interface
uses
System.SysUtils, Forms;
type
TExceptionManager = class
private
FLogfile : String;
public
constructor create;
procedure TrataException(Sender: TObject; E: Exception);
procedure GravarLog(Value: String);
end;
implementation
uses
System.Classes, Vcl.Dialogs;
{ TExceptionManager }
constructor TExceptionManager.create;
begin
FLogfile := ChangeFileExt(ParamStr(0), '.Log');
Application.OnException := TrataException;
end;
procedure TExceptionManager.GravarLog(Value: String);
var
txtLog: TextFile;
begin
AssignFile(txtLog, FLogfile);
if FileExists(FLogfile) then
begin
Append(txtLog)
end
else
Rewrite(txtlog);
Writeln(txtLog, FormatDateTime('dd/mm/yy hh:mm:ss - ' , now) + Value);
CloseFile(txtLog);
end;
procedure TExceptionManager.TrataException(Sender: TObject; E: Exception);
begin
GravarLog('=========================================================');
if TComponent(Sender) is TForm then
begin
GravarLog('Form: ' + TForm(Sender).Name);
GravarLog('Caption: ' + TForm(Sender).Caption);
GravarLog('Erro: ' + E.ClassName);
GravarLog('Erro: ' + E.Message);
end
else
begin
GravarLog('Form: ' + TForm(TComponent(Sender).Owner).Name);
GravarLog('Caption: ' + TForm(TComponent(Sender).Owner).Caption);
GravarLog('Erro: ' + E.ClassName);
GravarLog('Erro: ' + E.Message);
end;
Showmessage(E.Message);
end;
end.
|
unit nevVScrollerSpy;
// Модуль: "w:\common\components\gui\Garant\Everest\new\nevVScrollerSpy.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TnevVScrollerSpy" MUID: (4DAEB03E0034)
{$Include w:\common\components\gui\Garant\Everest\evDefine.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, l3Filer
;
type
TnevVScrollerSpy = class;
InevVScrollerPosLogger = interface
['{118E1374-07D5-47D3-B4EF-C921BCC2BA51}']
function OpenLog: AnsiString;
procedure CloseLog(const aLogName: AnsiString);
end;//InevVScrollerPosLogger
TnevVScrollerSpy = class(Tl3ProtoObject)
private
f_LogName: AnsiString;
f_Logger: InevVScrollerPosLogger;
f_Filer: Tl3CustomFiler;
protected
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
public
procedure SetLogger(const aLogger: InevVScrollerPosLogger);
procedure RemoveLogger(const aLogger: InevVScrollerPosLogger);
procedure LogPos(aPos: Integer);
function StartLog: Boolean;
procedure FinishLog;
class function Exists: Boolean;
class function Instance: TnevVScrollerSpy;
{* Метод получения экземпляра синглетона TnevVScrollerSpy }
end;//TnevVScrollerSpy
implementation
uses
l3ImplUses
, SysUtils
, l3Types
, l3Base
//#UC START# *4DAEB03E0034impl_uses*
//#UC END# *4DAEB03E0034impl_uses*
;
var g_TnevVScrollerSpy: TnevVScrollerSpy = nil;
{* Экземпляр синглетона TnevVScrollerSpy }
procedure TnevVScrollerSpyFree;
{* Метод освобождения экземпляра синглетона TnevVScrollerSpy }
begin
l3Free(g_TnevVScrollerSpy);
end;//TnevVScrollerSpyFree
procedure TnevVScrollerSpy.SetLogger(const aLogger: InevVScrollerPosLogger);
//#UC START# *4DAEBD9D0238_4DAEB03E0034_var*
//#UC END# *4DAEBD9D0238_4DAEB03E0034_var*
begin
//#UC START# *4DAEBD9D0238_4DAEB03E0034_impl*
Assert(f_Logger = nil);
f_Logger := aLogger;
//#UC END# *4DAEBD9D0238_4DAEB03E0034_impl*
end;//TnevVScrollerSpy.SetLogger
procedure TnevVScrollerSpy.RemoveLogger(const aLogger: InevVScrollerPosLogger);
//#UC START# *4DAEBDF20386_4DAEB03E0034_var*
//#UC END# *4DAEBDF20386_4DAEB03E0034_var*
begin
//#UC START# *4DAEBDF20386_4DAEB03E0034_impl*
Assert(f_Logger = aLogger);
f_Logger := nil;
//#UC END# *4DAEBDF20386_4DAEB03E0034_impl*
end;//TnevVScrollerSpy.RemoveLogger
procedure TnevVScrollerSpy.LogPos(aPos: Integer);
//#UC START# *4DAEBE61037F_4DAEB03E0034_var*
//#UC END# *4DAEBE61037F_4DAEB03E0034_var*
begin
//#UC START# *4DAEBE61037F_4DAEB03E0034_impl*
if (f_Logger <> nil) then
begin
Assert(f_Filer <> nil);
Assert(f_Filer.Opened);
f_Filer.WriteLn('Позиция скроллера: ' + IntToStr(aPos));
end;//f_Logger <> nil
//#UC END# *4DAEBE61037F_4DAEB03E0034_impl*
end;//TnevVScrollerSpy.LogPos
function TnevVScrollerSpy.StartLog: Boolean;
//#UC START# *4DAEBE840395_4DAEB03E0034_var*
//#UC END# *4DAEBE840395_4DAEB03E0034_var*
begin
//#UC START# *4DAEBE840395_4DAEB03E0034_impl*
Result := f_Logger <> nil;
f_LogName := f_Logger.OpenLog;
f_Filer := Tl3CustomDOSFiler.Make(f_LogName, l3_fmWrite);
try
f_Filer.Open;
except
l3Free(f_Filer);
end;
//#UC END# *4DAEBE840395_4DAEB03E0034_impl*
end;//TnevVScrollerSpy.StartLog
procedure TnevVScrollerSpy.FinishLog;
//#UC START# *4DAEBEBC016B_4DAEB03E0034_var*
//#UC END# *4DAEBEBC016B_4DAEB03E0034_var*
begin
//#UC START# *4DAEBEBC016B_4DAEB03E0034_impl*
try
if f_Filer <> nil then
f_Filer.Close;
finally
try
FreeAndNil(f_Filer);
finally
f_Logger.CloseLog(f_LogName);
f_LogName := '';
end;
end;
//#UC END# *4DAEBEBC016B_4DAEB03E0034_impl*
end;//TnevVScrollerSpy.FinishLog
class function TnevVScrollerSpy.Exists: Boolean;
begin
Result := g_TnevVScrollerSpy <> nil;
end;//TnevVScrollerSpy.Exists
class function TnevVScrollerSpy.Instance: TnevVScrollerSpy;
{* Метод получения экземпляра синглетона TnevVScrollerSpy }
begin
if (g_TnevVScrollerSpy = nil) then
begin
l3System.AddExitProc(TnevVScrollerSpyFree);
g_TnevVScrollerSpy := Create;
end;
Result := g_TnevVScrollerSpy;
end;//TnevVScrollerSpy.Instance
procedure TnevVScrollerSpy.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_4DAEB03E0034_var*
//#UC END# *479731C50290_4DAEB03E0034_var*
begin
//#UC START# *479731C50290_4DAEB03E0034_impl*
FreeAndNil(f_Filer);
inherited;
//#UC END# *479731C50290_4DAEB03E0034_impl*
end;//TnevVScrollerSpy.Cleanup
procedure TnevVScrollerSpy.ClearFields;
begin
f_Logger := nil;
inherited;
end;//TnevVScrollerSpy.ClearFields
end.
|
{ ***************************************************************************
Copyright (c) 2016-2021 Kike Pérez
Unit : Quick.Process
Description : Process functions
Author : Kike Pérez
Version : 1.5
Created : 14/07/2017
Modified : 08/07/2021
This file is part of QuickLib: https://github.com/exilon/QuickLib
***************************************************************************
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*************************************************************************** }
unit Quick.Process;
{$i QuickLib.inc}
interface
uses
{$IFDEF MSWINDOWS}
Windows,
ShellAPI,
Quick.Console,
{$IFNDEF CONSOLE}
Controls,
{$IFNDEF FPC}
Vcl.Forms,
Winapi.Messages,
{$ENDIF}
{$ENDIF}
{$IFNDEF FPC}
TlHelp32,
psapi,
{$ELSE}
JwaTlHelp32,
Process,
{$ENDIF}
{$ELSE}
Posix.Base,
Posix.Fcntl,
{$ENDIF}
Classes,
DateUtils,
SysUtils,
Quick.Commons;
{$IFDEF DELPHILINUX}
type
TStreamHandle = pointer;
function popen(const command: PAnsiChar; const _type: PAnsiChar): TStreamHandle; cdecl; external libc name _PU + 'popen';
function pclose(filehandle: TStreamHandle): int32; cdecl; external libc name _PU + 'pclose';
function fgets(buffer: pointer; size: int32; Stream: TStreamHAndle): pointer; cdecl; external libc name _PU + 'fgets';
{$ENDIF}
//stop a running process
{$IFDEF MSWINDOWS}
function KillProcess(const aFileName : string) : Integer; overload;
{$ELSE}
function KillProcess(const aProcessName : string) : Integer; overload;
{$ENDIF}
function KillProcess(aProcessId : Cardinal) : Boolean; overload;
//run process as Admin privilegies
{$IFDEF MSWINDOWS}
function RunAsAdmin(hWnd: HWND; const aFilename, aParameters: string): Boolean;
//impersonate logon
function Impersonate(const aDomain, aUser, aPassword : string): Boolean;
//revert logon to real logged user
procedure RevertToSelf;
//remove dead icons from taskbar tray
procedure RemoveDeadIcons;
//get a process of running processes
function GetProcessList : TstringList;
//determine if a process is running
function IsProcessRunnig(const aFileName: string; aFullPath: Boolean): Boolean;
//get id running process
function GetProcessId(const aFilename : string; out vProcessId : Integer) : Boolean; overload;
//get user name is running a process
function GetProcessUser(aProcessId : DWORD) : string; overload;
function GetProcessUser(const aFileName : string) : string; overload;
//executes an aplication and wait for terminate
function ExecuteAndWait(const aFilename, aCommandLine: string): Boolean;
function ShellExecuteAndWait(const aOperation, aFileName, aParameter, aDirectory : string; aShowMode : Word; aWaitForTerminate: Boolean) : LongInt;
{$ENDIF}
//runs a command and gets console output
function RunCommand(const aFilename, aParameters : string) : TStringList;
{$IFDEF MSWINDOWS}
{$IFNDEF FPC}
//execute an application and return handle
function ShellExecuteReturnHandle(const aOperation, aFileName, aParameters, aWorkingDir : string; aShowMode: Integer) : THandle;
{$ENDIF}
//find an open main window handle
function FindMainWindow(PID: DWord): DWord;
//wait for a time period to find an opened main window handle
function FindMainWindowTimeout(ProcHND : THandle; TimeoutSecs : Integer = 20) : THandle; overload;
//wait for a time period to find an opened window handle
function FindWindowTimeout(const aWindowsName : string; TimeoutMSecs : Integer = 1000) : THandle;
{$IFNDEF CONSOLE}
//capture a window handle and show it into a wincontrol
procedure CaptureWindowIntoControl(aWindowHandle: THandle; aContainer: TWinControl);
{$ENDIF}
{$ENDIF}
implementation
{$IFDEF MSWINDOWS}
const
DNLEN = 15;
UNLEN = 256;
type
PEnumInfo = ^TEnumInfo;
TEnumInfo = record
ProcessID: DWORD;
HWND: THandle;
end;
PTOKEN_USER = ^TOKEN_USER;
TOKEN_USER = record
User: TSidAndAttributes;
end;
function EnumWindowsProc(hwnd : DWord; var einfo: TEnumInfo) : BOOL; stdcall;
var
PID: DWord;
begin
GetWindowThreadProcessId(hwnd, @PID);
Result := (PID <> einfo.ProcessID) or (not IsWindowVisible(hwnd)) or (not IsWindowEnabled(hwnd));
if not Result then einfo.HWND := hwnd;
end;
{$IFNDEF FPC}
function CreateWin9xProcessList : TStringList;
var
hSnapShot: THandle;
ProcInfo: TProcessEntry32;
begin
Result := TStringList.Create;
hSnapShot := CreateToolHelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnapShot <> THandle(-1)) then
begin
ProcInfo.dwSize := SizeOf(ProcInfo);
if (Process32First(hSnapshot, ProcInfo)) then
begin
Result.Add(ProcInfo.szExeFile);
while (Process32Next(hSnapShot, ProcInfo)) do Result.Add(ProcInfo.szExeFile);
end;
CloseHandle(hSnapShot);
end;
end;
function CreateWinNTProcessList : TstringList;
var
PIDArray: array [0..1023] of DWORD;
cb: DWORD;
I: Integer;
ProcCount: Integer;
hMod: HMODULE;
hProcess: THandle;
ModuleName: array [0..300] of Char;
begin
Result := TStringList.Create;
EnumProcesses(@PIDArray, SizeOf(PIDArray), cb);
ProcCount := cb div SizeOf(DWORD);
for I := 0 to ProcCount - 1 do
begin
hProcess := OpenProcess(PROCESS_QUERY_INFORMATION or
PROCESS_VM_READ,
False,
PIDArray[I]);
if (hProcess <> 0) then
begin
EnumProcessModules(hProcess, @hMod, SizeOf(hMod), cb);
GetModuleFilenameEx(hProcess, hMod, ModuleName, SizeOf(ModuleName));
Result.Add(ModuleName);
CloseHandle(hProcess);
end;
end;
end;
function GetProcessList : TStringList;
var
ovinfo: TOSVersionInfo;
begin
Result := nil;
ovinfo.dwOSVersionInfoSize := SizeOf(TOSVersionInfo);
GetVersionEx(ovinfo);
case ovinfo.dwPlatformId of
VER_PLATFORM_WIN32_WINDOWS : Result := CreateWin9xProcessList;
VER_PLATFORM_WIN32_NT : Result := CreateWinNTProcessList;
end
end;
{$ELSE}
function GetProcessList : TStringList;
var
pr : THandle;
pe: TProcessEntry32;
begin
Result := TStringList.Create;
pr := CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
try
pe.dwSize := SizeOf(pe);
if Process32First(pr,pe) then
begin
while Process32Next(pr,pe) do Result.Add(pe.szExeFile);
end;
finally
CloseHandle(pr);
end;
end;
{$ENDIF}
{$ENDIF}
{$IFDEF MSWINDOWS}
function KillProcess(const aFileName: string): Integer;
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(aFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(aFileName))) then
Result := Integer(TerminateProcess(
OpenProcess(PROCESS_TERMINATE,
BOOL(0),
FProcessEntry32.th32ProcessID),
0));
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
{$ELSE}
function KillProcess(const aProcessName: string): Integer;
var
sl : TStringList;
begin
sl := RunCommand('pkill',aProcessName);
try
Result := 1;
finally
sl.Free;
end;
end;
{$ENDIF}
function KillProcess(aProcessId : Cardinal) : Boolean;
{$IFDEF MSWINDOWS}
var
hProcess : THandle;
begin
Result := False;
hProcess := OpenProcess(PROCESS_TERMINATE,False,aProcessId);
if hProcess > 0 then
try
Result := Win32Check(Windows.TerminateProcess(hProcess,0));
finally
CloseHandle(hProcess);
end;
end;
{$ELSE}
var
sl : TStringList;
begin
sl := RunCommand('kill',aProcessId.ToString);
try
Result := True;
finally
sl.Free;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function RunAsAdmin(hWnd: HWND; const aFilename, aParameters: string): Boolean;
var
shinfo: TShellExecuteInfo;
begin
ZeroMemory(@shinfo, SizeOf(shinfo));
shinfo.cbSize := SizeOf(TShellExecuteInfo);
shinfo.Wnd := hwnd;
shinfo.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI;
shinfo.lpVerb := PChar('runas');
shinfo.lpFile := PChar(aFilename);
if aParameters <> '' then shinfo.lpParameters := PChar(aParameters);
shinfo.nShow := SW_SHOWNORMAL;
{$IFDEF FPC}
Result := ShellExecuteExW(@shinfo);
{$ELSE}
Result := ShellExecuteEx(@shinfo);
{$ENDIF}
end;
function Impersonate(const aDomain, aUser, aPassword : string): Boolean;
var
htoken : THandle;
begin
Result := False;
if LogonUser(PChar(aUser),PChar(aDomain),PChar(aPassword),LOGON32_LOGON_INTERACTIVE,LOGON32_PROVIDER_DEFAULT,htoken) then
begin
Result := ImpersonateLoggedOnUser(htoken);
end;
end;
procedure RevertToSelf;
begin
Windows.RevertToSelf;
end;
procedure RemoveDeadIcons;
var
TrayWindow : HWnd;
WindowRect : TRect;
SmallIconWidth : Integer;
SmallIconHeight : Integer;
CursorPos : TPoint;
Row : Integer;
Col : Integer;
begin
TrayWindow := FindWindowEx(FindWindow('Shell_TrayWnd',NIL),0,'TrayNotifyWnd',NIL);
if not GetWindowRect(TrayWindow,WindowRect) then Exit;
SmallIconWidth := GetSystemMetrics(SM_CXSMICON);
SmallIconHeight := GetSystemMetrics(SM_CYSMICON);
GetCursorPos(CursorPos);
with WindowRect do
begin
for Row := 0 to (Bottom - Top) DIV SmallIconHeight do
begin
for Col := 0 to (Right - Left) DIV SmallIconWidth do
begin
SetCursorPos(Left + Col * SmallIconWidth, Top + Row * SmallIconHeight);
Sleep(0);
end;
end;
end;
SetCursorPos(CursorPos.X,CursorPos.Y);
RedrawWindow(TrayWindow,NIL,0,RDW_INVALIDATE OR RDW_ERASE OR RDW_UPDATENOW);
end;
function IsProcessRunnig(const aFileName: string; aFullPath: Boolean): Boolean;
var
i: Integer;
proclist: TstringList;
begin
try
proclist := GetProcessList;
Result := False;
if proclist = nil then Exit;
for i := 0 to proclist.Count - 1 do
begin
if not aFullPath then
begin
if CompareText(ExtractFileName(proclist.Strings[i]), aFileName) = 0 then Result := True
end
else if CompareText(proclist.strings[i], aFileName) = 0 then Result := True;
if Result then Break;
end;
finally
proclist.Free;
end;
end;
function GetProcessId(const aFilename : string; out vProcessId : Integer) : Boolean;
var
nproc: BOOL;
snapHnd : THandle;
procEntry: TProcessEntry32;
begin
result := false;
snapHnd := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
try
procEntry.dwSize := Sizeof(procEntry);
nproc := Process32First(snapHnd, procEntry);
while Integer(nproc) <> 0 do
begin
if (StrIComp(PChar(ExtractFileName(procEntry.szExeFile)), PChar(aFilename)) = 0)
or (StrIComp(procEntry.szExeFile, PChar(aFilename)) = 0) then
begin
vProcessId := procEntry.th32ProcessID;
Result := true;
Break;
end;
nproc := Process32Next(snapHnd, procEntry);
end;
finally
CloseHandle(snapHnd);
end;
end;
function GetProcessUser(aProcessId : DWORD): string;
var
buffer, domain, user: DWORD;
procHnd, tokenHnd: THandle;
lpUser: PTOKEN_USER;
snu: SID_NAME_USE;
szDomain: array [0..DNLEN] of Char;
szUser: array [0..UNLEN] of Char;
begin
Result := '';
procHnd := OpenProcess(PROCESS_QUERY_INFORMATION, False, aProcessId);
if procHnd = 0 then Exit;
try
if not OpenProcessToken(procHnd, TOKEN_QUERY, tokenHnd) then Exit;
try
if not GetTokenInformation(tokenHnd, TokenUser, nil, 0, buffer) then
begin
if GetLastError <> ERROR_INSUFFICIENT_BUFFER then Exit;
end;
if buffer = 0 then Exit;
GetMem(lpUser, buffer);
if not Assigned(lpUser) then Exit;
try
if not GetTokenInformation(tokenHnd, TokenUser, lpUser, buffer, buffer) then Exit;
domain := DNLEN + 1;
user := UNLEN + 1;
if LookupAccountSid(nil, lpUser.User.Sid, szUser, user, szDomain,
domain, snu) then Result := szUser;
finally
FreeMem(lpUser);
end;
finally
CloseHandle(tokenHnd);
end;
finally
CloseHandle(procHnd);
end;
end;
function GetProcessUser(const aFilename : string) : string;
var
procId : Integer;
begin
if not GetProcessId(aFilename,procId) then raise Exception.Create('Process not found!')
else Result := GetProcessUser(procId);
end;
function ExecuteAndWait(const aFilename, aCommandLine: string): Boolean;
var
dwExitCode: DWORD;
tpiProcess: TProcessInformation;
tsiStartup: TStartupInfo;
begin
Result := False;
FillChar(tsiStartup, SizeOf(TStartupInfo), 0);
tsiStartup.cb := SizeOf(TStartupInfo);
if CreateProcess(PChar(aFilename), PChar(aCommandLine), nil, nil, False, 0,
nil, nil, tsiStartup, tpiProcess) then
begin
if WAIT_OBJECT_0 = WaitForSingleObject(tpiProcess.hProcess, INFINITE) then
begin
if GetExitCodeProcess(tpiProcess.hProcess, dwExitCode) then
begin
if dwExitCode = 0 then
Result := True
else
SetLastError(dwExitCode + $2000);
end;
end;
dwExitCode := GetLastError;
CloseHandle(tpiProcess.hProcess);
CloseHandle(tpiProcess.hThread);
SetLastError(dwExitCode);
end;
end;
{$ENDIF}
function RunCommand(const aFilename, aParameters : string) : TStringList;
{$IFDEF MSWINDOWS}
begin
Result := TStringList.Create;
RunConsoleCommand(aFilename,aParameters,nil,Result);
end;
{$ELSE}
var
Handle: TStreamHandle;
Data: array[0..511] of uint8;
command : PAnsiChar;
begin
Result := TStringList.Create;
try
if aParameters.IsEmpty then command := PAnsiChar(AnsiString(aFilename))
else command := PAnsiChar(AnsiString(aFilename + ' ' + aParameters));
Handle := popen(command, 'r');
try
while fgets(@Data[0], Sizeof(Data), Handle) <> nil do Result.Add(Utf8ToString(@Data[0]));
finally
pclose(Handle);
end;
except
on E: Exception do
begin
Result.Free;
Exception.CreateFmt('RunCommand: %s',[e.Message]);
end;
end;
end;
{$ENDIF}
{$IFDEF MSWINDOWS}
function ShellExecuteAndWait(const aOperation, aFileName, aParameter, aDirectory: string; aShowMode : Word; aWaitForTerminate: Boolean) : LongInt;
var
done: Boolean;
shinfo: TShellExecuteInfo;
begin
FillChar(shinfo, SizeOf(shinfo), Chr(0));
shinfo.cbSize := SizeOf(shinfo);
shinfo.fMask := SEE_MASK_NOCLOSEPROCESS;
shinfo.lpVerb := PChar(aOperation);
shinfo.lpFile := PChar(aFileName);
shinfo.lpParameters := PChar(aParameter);
shinfo.lpDirectory := PChar(aDirectory);
shinfo.nShow := aShowMode;
{$IFDEF FPC}
done := Boolean(ShellExecuteExW(@shinfo));
{$ELSE}
done := Boolean(ShellExecuteEx(@shinfo));
{$ENDIF}
if done then
begin
if aWaitForTerminate then
begin
while WaitForSingleObject(shinfo.hProcess, 100) = WAIT_TIMEOUT do
begin
{$IFDEF CONSOLE}
ProcessMessages;
{$ELSE}
Application.ProcessMessages;
{$ENDIF}
end;
done := GetExitCodeProcess(shinfo.hProcess, DWORD(Result));
end
else Result := 0;
end;
if not done then Result := -1;
end;
{$IFNDEF FPC}
function ShellExecuteReturnHandle(const aOperation, aFileName, aParameters, aWorkingDir : string; aShowMode: Integer) : THandle;
var
exInfo: TShellExecuteInfo;
Ph: THandle;
begin
Result := 0;
FillChar(exInfo, SizeOf(exInfo), 0);
with exInfo do
begin
cbSize := SizeOf(exInfo);
fMask := SEE_MASK_NOCLOSEPROCESS;
Wnd := GetActiveWindow();
ExInfo.lpVerb := PChar(aOperation);
ExInfo.lpParameters := PChar(aParameters);
exInfo.lpDirectory := PChar(aWorkingDir);
lpFile := PChar(aFileName);
nShow := aShowMode;
end;
if ShellExecuteEx(@exInfo) then Ph := exInfo.hProcess;
Result := Windows.GetProcessId(exInfo.hProcess);
End;
{$ENDIF}
function FindMainWindow(PID : DWord): DWORD;
var
eInfo: TEnumInfo;
begin
eInfo.ProcessID := PID;
eInfo.HWND := 0;
EnumWindows(@EnumWindowsProc, Integer(@eInfo));
Result := eInfo.HWND;
end;
function FindMainWindowTimeout(ProcHND : THandle; TimeoutSecs : Integer = 20) : THandle;
var
startime : TDateTime;
begin
if ProcHND = 0 then Exit;
startime := Now();
Result := 0;
repeat
Result := FindMainWindow(ProcHND);
{$IFDEF CONSOLE}
ProcessMessages;
{$ELSE}
Application.ProcessMessages;
{$ENDIF}
until (Result <> 0) or (SecondsBetween(Now(),startime) > TimeoutSecs);
end;
function FindWindowTimeout(const aWindowsName : string; TimeoutMSecs : Integer = 1000) : THandle;
var
startime : TDateTime;
begin
startime := Now();
repeat
Result := FindWindow(0,{$IFDEF FPC}PChar{$ELSE}PWideChar{$ENDIF}(aWindowsName));
{$IFDEF CONSOLE}
ProcessMessages;
{$ELSE}
Application.ProcessMessages;
{$ENDIF}
until (Result <> 0) or (MilliSecondsBetween(Now(),startime) > TimeoutMSecs);
end;
{$IFNDEF CONSOLE}
procedure CaptureWindowIntoControl(aWindowHandle: THandle; aContainer: TWinControl);
var
WindowStyle : Integer;
appthreadId: Cardinal;
begin
WindowStyle := GetWindowLong(aWindowHandle, GWL_STYLE);
WindowStyle := WindowStyle
// - WS_CAPTION
- WS_BORDER
// - WS_OVERLAPPED
- WS_THICKFRAME;
SetWindowLong(aWindowHandle,GWL_STYLE,WindowStyle);
appthreadId := GetWindowThreadProcessId(aWindowHandle, nil);
AttachThreadInput(GetCurrentThreadId, appthreadId, True);
SetParent(aWindowHandle,aContainer.Handle);
SendMessage(aContainer.Handle, WM_UPDATEUISTATE, UIS_INITIALIZE, 0);
UpdateWindow(aWindowHandle);
SetWindowLong(aContainer.Handle, GWL_STYLE, GetWindowLong(aContainer.Handle,GWL_STYLE) or WS_CLIPCHILDREN);
SetWindowPos(aWindowHandle,0,0,0,aContainer.ClientWidth,aContainer.ClientHeight,SWP_NOOWNERZORDER);
SetForegroundWindow(aWindowHandle);
end;
{$ENDIF}
{$ENDIF}
end.
|
unit GX_EnhancedEditor;
interface
{$I GX_CondDefine.inc}
// This is implemented as a TWinControl to ease design-time usage
uses
Windows, Classes, Graphics, Controls,
SynEdit, SynMemo, SynEditTypes, SynEditTextBuffer, GX_SynMemoUtils,
GX_GenericUtils;
type
TGxEnhancedEditor = class(TWinControl)
private
FEditor: TSynMemo;
FHighlighter: TGXSyntaxHighlighter;
FOnChange: TNotifyEvent;
FOnClick: TNotifyEvent;
FOnKeyPress: TKeyPressWEvent;
FOnKeyDown: TKeyEvent;
FOnKeyUp: TKeyEvent;
FOnMouseDown: TMouseEvent;
FONStatusChange: TStatusChangeEvent;
function GetReadOnly: Boolean;
procedure SetReadOnly(const Value: Boolean);
function GetModified: Boolean;
procedure SetModified(const Value: Boolean);
function GetColor: TColor;
procedure SetColor(const Value: TColor);
function GetText: string;
procedure SetText(const Value: string);
function GetFont: TFont;
procedure SetFont(const Value: TFont);
function GetCaretXY: TPoint;
procedure SetCaretXY(const Value: TPoint);
function GetTopLine: Integer;
procedure SetTopLine(const Value: Integer);
function GetHighlighter: TGXSyntaxHighlighter;
procedure SetHighlighter(const Value: TGXSyntaxHighlighter);
function GetSelText: string;
procedure SetSelText(const Value: string);
function GetSelStart: Integer;
procedure SetOnChange(const Value: TNotifyEvent);
procedure SetWantTabs(const Value: Boolean);
function GetWantTabs: Boolean;
function GetNormalizedText: string;
function GetTabWidth: Integer;
procedure SetTabWidth(const Value: Integer);
function GetLineCount: Integer;
procedure SetAsAnsiString(const Value: AnsiString);
procedure SetAsString(const Value: string);
function GetAsAnsiString: AnsiString;
function GetAsString: string;
function GetAsUnicodeString: TGXUnicodeString;
procedure SetAsUnicodeString(const Value: TGXUnicodeString);
procedure SetOnClick(const Value: TNotifyEvent);
procedure SetOnKeyDown(const Value: TKeyEvent);
procedure SetOnKeyPress(const Value: TKeyPressWEvent);
procedure SetOnKeyUp(const Value: TKeyEvent);
procedure SetOnMouseDown(const Value: TMouseEvent);
function GetActiveLineColor: TColor;
procedure SetActiveLineColor(const Value: TColor);
procedure SetOnStatusChange(const Value: TStatusChangeEvent);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Clear;
procedure CopyToClipboard;
procedure CutToClipboard;
procedure PasteFromClipBoard;
procedure SetSelection(AStart, ALength: Integer);
procedure SetFocus; override;
procedure Print(const ATitle: string);
function Focused: Boolean; override;
procedure LoadFromStream(Stream: TStream);
procedure LoadFromFile(const AFilename: string);
procedure SaveToFile(const AFilename: string);
procedure BeginUpdate;
procedure EndUpdate;
procedure GetLines(ALines: TGXUnicodeStringList);
procedure SetLines(ALines: TGXUnicodeStringList);
function GetLine(AIdx: Integer): TGXUnicodeString;
procedure SetLine(AIdx: Integer; ALine: TGXUnicodeString);
property Highlighter: TGXSyntaxHighlighter read GetHighlighter write SetHighlighter;
property Text: string read GetText write SetText;
property Color: TColor read GetColor write SetColor;
property CaretXY: TPoint read GetCaretXY write SetCaretXY;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property Modified: Boolean read GetModified write SetModified;
property Font: TFont read GetFont write SetFont;
property SelText: string read GetSelText write SetSelText;
property SelStart: Integer read GetSelStart;
property TopLine: Integer read GetTopLine write SetTopLine;
property WantTabs: Boolean read GetWantTabs write SetWantTabs;
property NormalizedText: string read GetNormalizedText;
property TabWidth: Integer read GetTabWidth write SetTabWidth;
property LineCount: Integer read GetLineCount;
property ActiveLineColor: TColor read GetActiveLineColor write SetActiveLineColor;
property AsString: string read GetAsString write SetAsString;
property AsAnsiString: AnsiString read GetAsAnsiString write SetAsAnsiString;
property AsUnicodeString: TGXUnicodeString read GetAsUnicodeString write SetAsUnicodeString;
published
property Align;
property Anchors;
property Enabled;
property PopupMenu;
property ShowHint;
property TabOrder;
property Visible;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property OnClick: TNotifyEvent read FOnClick write SetOnClick;
property OnExit;
property OnEnter;
property OnKeyDown: TKeyEvent read FOnKeyDown write SetOnKeyDown;
property OnKeyPress: TKeyPressWEvent read FOnKeyPress write SetOnKeyPress;
property OnKeyUp: TKeyEvent read FOnKeyUp write SetOnKeyUp;
property OnMouseDown: TMouseEvent read FOnMouseDown write SetOnMouseDown;
property OnStatusChange: TStatusChangeEvent read FONStatusChange write SetOnStatusChange;
end;
procedure Register;
implementation
uses
SysUtils, SynUnicode;
procedure Register;
begin
RegisterComponents('GExperts', [TGxEnhancedEditor]);
end;
{ TGxEnhancedEditor }
constructor TGxEnhancedEditor.Create(AOwner: TComponent);
begin
inherited;
if not (csDesigning in ComponentState) then
begin
FEditor := TSynMemo.Create(nil);
FEditor.Gutter.Width := 0;
FEditor.Options := FEditor.Options - [eoScrollPastEof, eoScrollPastEol, eoTabsToSpaces];
(FEditor.Lines as TSynEditStringList).AppendNewLineAtEOF := False;
FEditor.Parent := Self;
FEditor.Align := alClient;
if Assigned(FOnChange) then
FEditor.OnChange := FOnchange;
end; // not csDesigning
TabStop := True;
Width := 185;
Height := 89;
AutoSize := False;
ParentColor := False;
Color := clWindow;
end;
destructor TGxEnhancedEditor.Destroy;
begin
if not (csDesigning in ComponentState) then
begin
if Assigned(FEditor.OnChange) then
FEditor.OnChange := nil;
FreeAndNil(FEditor);
end;
inherited Destroy;
end;
procedure TGxEnhancedEditor.BeginUpdate;
begin
FEditor.Lines.BeginUpdate;
end;
procedure TGxEnhancedEditor.EndUpdate;
begin
FEditor.Lines.EndUpdate;
end;
procedure TGxEnhancedEditor.Clear;
begin
FEditor.ClearAll;
end;
procedure TGxEnhancedEditor.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
FEditor.OnChange := Value;
end;
procedure TGxEnhancedEditor.SetOnClick(const Value: TNotifyEvent);
begin
FOnClick := Value;
FEditor.OnClick := Value;
end;
procedure TGxEnhancedEditor.SetOnStatusChange(const Value: TStatusChangeEvent);
begin
FOnStatusChange := Value;
FEditor.OnStatusChange := Value;
end;
procedure TGxEnhancedEditor.SetOnKeyDown(const Value: TKeyEvent);
begin
FOnKeyDown := Value;
FEditor.OnKeyDown := Value;
end;
procedure TGxEnhancedEditor.SetOnKeyPress(const Value: TKeyPressWEvent);
begin
FOnKeypress := Value;
FEditor.OnKeyPress := Value;
end;
procedure TGxEnhancedEditor.SetOnKeyUp(const Value: TKeyEvent);
begin
FOnKeyUp := Value;
FEditor.OnKeyUp := Value;
end;
procedure TGxEnhancedEditor.SetOnMouseDown(const Value: TMouseEvent);
begin
FOnMouseDown := Value;
FEditor.OnMouseDown := Value;
end;
procedure TGxEnhancedEditor.SetFocus;
begin
inherited SetFocus;
FEditor.SetFocus;
end;
function TGxEnhancedEditor.Focused: Boolean;
begin
Result := False;
if FEditor.Focused then
Result := True;
end;
procedure TGxEnhancedEditor.CopyToClipboard;
begin
FEditor.CopyToClipboard;
end;
procedure TGxEnhancedEditor.CutToClipboard;
begin
FEditor.CutToClipboard;
end;
procedure TGxEnhancedEditor.PasteFromClipBoard;
begin
FEditor.PasteFromClipBoard;
end;
procedure TGxEnhancedEditor.Print(const ATitle: string);
//var
// PrintBuf: TextFile;
// i: Integer;
begin
// TODO: Implement SynEdit printing
// AssignPrn(PrintBuf);
// Rewrite(PrintBuf);
// try
// for i := 0 to FEditor.Lines.Count-1 do
// WriteLn(PrintBuf, FEditor.Lines[i]);
// finally
// CloseFile(PrintBuf);
// end;
end;
function TGxEnhancedEditor.GetActiveLineColor: TColor;
begin
Result := FEditor.ActiveLineColor;
end;
function TGxEnhancedEditor.GetAsAnsiString: AnsiString;
begin
Result := AnsiString(FEditor.Lines.Text);
end;
function TGxEnhancedEditor.GetAsString: string;
begin
Result := FEditor.Lines.Text;
end;
function TGxEnhancedEditor.GetAsUnicodeString: TGXUnicodeString;
begin
Result := FEditor.Lines.Text;
end;
function TGxEnhancedEditor.GetCaretXY: TPoint;
begin
Result := Point(FEditor.CaretX, FEditor.CaretY - 1);
end;
procedure TGxEnhancedEditor.SaveToFile(const AFilename: string);
begin
FEditor.Lines.SaveToFile(AFilename);
end;
procedure TGxEnhancedEditor.SetActiveLineColor(const Value: TColor);
begin
FEditor.ActiveLineColor := Value;
end;
procedure TGxEnhancedEditor.SetAsAnsiString(const Value: AnsiString);
begin
FEditor.Lines.Text := UnicodeString(Value);
end;
procedure TGxEnhancedEditor.SetAsString(const Value: string);
begin
FEditor.Lines.Text := Value;
end;
procedure TGxEnhancedEditor.SetAsUnicodeString(const Value: TGXUnicodeString);
begin
FEditor.Lines.Text := Value;
end;
procedure TGxEnhancedEditor.SetCaretXY(const Value: TPoint);
begin
FEditor.CaretXY := BufferCoord(1, Value.Y + 1);
end;
function TGxEnhancedEditor.GetTopLine: Integer;
begin
Result := FEditor.TopLine;
end;
procedure TGxEnhancedEditor.SetTopLine(const Value: Integer);
begin
FEditor.TopLine := Value;
end;
function TGxEnhancedEditor.GetModified: Boolean;
begin
Result := FEditor.Modified
end;
procedure TGxEnhancedEditor.SetModified(const Value: Boolean);
begin
FEditor.Modified := Value;
end;
function TGxEnhancedEditor.GetLine(AIdx: Integer): TGXUnicodeString;
begin
Result := FEditor.Lines[AIdx];
end;
function TGxEnhancedEditor.GetLineCount: Integer;
begin
Result := FEditor.Lines.Count;
end;
procedure TGxEnhancedEditor.GetLines(ALines: TGXUnicodeStringList);
begin
ALines.Assign(FEditor.Lines);
end;
function TGxEnhancedEditor.GetReadOnly: Boolean;
begin
Result := FEditor.ReadOnly
end;
procedure TGxEnhancedEditor.SetReadOnly(const Value: Boolean);
begin
FEditor.ReadOnly := Value;
end;
procedure TGxEnhancedEditor.SetWantTabs(const Value: Boolean);
begin
FEditor.WantTabs := Value;
end;
function TGxEnhancedEditor.GetWantTabs: Boolean;
begin
Result := FEditor.WantTabs;
end;
procedure TGxEnhancedEditor.LoadFromFile(const AFilename: string);
var
fs: TFileStream;
begin
fs := TFileStream.Create(AFilename, fmOpenRead or fmShareDenyNone);
try
LoadFromStream(fs);
finally
FreeAndNil(fs);
end;
end;
procedure TGxEnhancedEditor.LoadFromStream(Stream: TStream);
begin
FEditor.Lines.LoadFromStream(Stream);
end;
function TGxEnhancedEditor.GetColor: TColor;
begin
Result := FEditor.Color;
end;
procedure TGxEnhancedEditor.SetColor(const Value: TColor);
begin
FEditor.Color := Value;
end;
function TGxEnhancedEditor.GetText: string;
begin
Result := FEditor.Text;
end;
procedure TGxEnhancedEditor.SetText(const Value: string);
begin
FEditor.Text := Value;
end;
function TGxEnhancedEditor.GetSelStart: Integer;
begin
Result := FEditor.SelStart;
end;
procedure TGxEnhancedEditor.SetSelection(AStart, ALength: Integer);
begin
FEditor.SelStart := AStart;
FEditor.SelEnd := AStart + ALength;
end;
function TGxEnhancedEditor.GetFont: TFont;
begin
Result := FEditor.Font;
end;
procedure TGxEnhancedEditor.SetFont(const Value: TFont);
begin
FEditor.Font.Assign(Value);
end;
function TGxEnhancedEditor.GetSelText: string;
begin
Result := FEditor.SelText;
end;
procedure TGxEnhancedEditor.SetSelText(const Value: string);
begin
FEditor.SelText := Value;
end;
function TGxEnhancedEditor.GetHighlighter: TGXSyntaxHighlighter;
begin
Result := FHighlighter;
end;
procedure TGxEnhancedEditor.SetHighlighter(const Value: TGXSyntaxHighlighter);
begin
SetSynEditHighlighter(FEditor, Value);
FHighlighter := Value;
end;
procedure TGxEnhancedEditor.SetLine(AIdx: Integer; ALine: TGXUnicodeString);
begin
FEditor.Lines[AIdx] := ALine;
end;
procedure TGxEnhancedEditor.SetLines(ALines: TGXUnicodeStringList);
begin
FEditor.Lines.Assign(ALines);
end;
function TGxEnhancedEditor.GetNormalizedText: string;
begin
Result := FEditor.Lines.Text;
RemoveLastEOL(Result);
end;
function TGxEnhancedEditor.GetTabWidth: Integer;
begin
Result := FEditor.TabWidth;
end;
procedure TGxEnhancedEditor.SetTabWidth(const Value: Integer);
begin
FEditor.TabWidth := Value;
end;
end.
|
unit FiltersUnit; {$Z4}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "GblAdapterLib"
// Модуль: "w:/garant6x/implementation/Garant/GblAdapterLib/FiltersUnit.pas"
// Delphi интерфейсы для адаптера (.pas)
// Generated from UML model, root element: <<Interfaces::Category>> garant6x::GblAdapterLib::Filters
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
interface
uses
SysUtils
, IOUnit
, BaseTypesUnit
, BaseTreeSupportUnit
//#UC START# *4423F94903C8_45EEA48F011F_UNIT_FOR_Stream*
//#UC END# *4423F94903C8_45EEA48F011F_UNIT_FOR_Stream*
;
type
IFilterFromQuery = interface;
{ - предварительное описание IFilterFromQuery. }
IFiltersFromQuery = interface;
{ - предварительное описание IFiltersFromQuery. }
IFiltersManager = interface;
{ - предварительное описание IFiltersManager. }
// Не все атрибуты поискового запроса восстановлны из базы
ENotAllAttributesRestored = class (Exception);
// Интерфейс фильтруемости. Должен поддерживаться объектами, желающими предоставлять сервис
// фильтров. Сейчас используется для списков.
IFilterable = interface (IInterface) ['{4C08EC41-3957-462B-B9C1-FB91B86469BA}']
function DontUseMe: Pointer;
procedure GetActiveFilters (out aRet {: IFiltersFromQuery}); stdcall;
// Добавляет INode (из дерева папок) как фильтр.
// Если auto_refresh = true (значение по умолчанию), то
// операция приводит к перефильтрации объекта.
procedure AddFilter (
const aFilter: IFilterFromQuery;
aAutoRefresh: Bytebool
); stdcall; // can raise EAllContentIsFiltered, ENotAllAttributesRestored
// Добавляет пачку фильтров с одновременным их применением. При этом эта пачка либо целиком
// применяется, либо (в случае, если все документы отфильтрованы) целиком отклоняется.
//
// Если выясняется, что на сервере нет данных для построения списка, т.е. списка как такового нет
// (см. К244711732), летит CanNotFindData.
procedure ApplyFilters (
const aFilters: IFiltersFromQuery
); stdcall; // can raise ECanNotFindData, EAllContentIsFiltered
// Удаляет все фильтры. В результате операции объект переходит в состояние, соответвующее
// отсутствию фильтров
procedure ClearFilters (); stdcall; // can raise ECanNotFindData
// Удаляет фильтр из списка активных фильтров объекта. Если auto_refresh = true (значение по
// умолчанию), то операция приводит к перефильтрации объекта.
procedure DeleteFilter (
const aFilter: IFilterFromQuery;
aAutoRefresh: Bytebool
); stdcall; // can raise ECanNotFindData, EAllContentIsFiltered
function GetHasActiveFilters (): Bytebool; stdcall;
procedure RefreshFilters (); stdcall; // can raise ECanNotFindData, EAllContentIsFiltered
end;
IFilterNotifier = interface (IInterface) ['{F41C0D69-A5BC-4836-9F33-85807FCAC1A7}']
procedure FilterNameChanged (); stdcall;
procedure FilterPermanenceChanged (); stdcall;
procedure FiltersChanged (); stdcall;
end;
IFilterFromQuery = interface (IInterface) ['{A81EFF04-FAB6-4D1B-846B-66C301594470}']
function DontUseMe: Pointer;
function GetChangeable (): Bytebool; stdcall;
// идентификатор нужен оболочке, чтобы идентифицировать установленные фильтры (К274848126)
function GetId (): Longword; stdcall;
// возвращает true, если оригинальный и переданный фильтры совпадают
function IsSame (
const aOther: IFilterFromQuery
): Bytebool; stdcall;
// наложен ли фильтр
function IsUsed (): Bytebool; stdcall;
// удалить фильтр после того, как он перестанет использоваться
procedure MarkToErase (); stdcall;
function MarkedToErase (): Bytebool; stdcall;
procedure GetName (out aRet {: IString}); stdcall;
procedure SetName (const aName: IString); stdcall;
function GetPermanent (): Bytebool; stdcall;
procedure SetPermanent (aPermanent: Bytebool); stdcall;
// если делать query Search::Query, каковым он и является, на модели получается дофига циклических
// связей, которые небыстро будет развязать
procedure GetQuery (out aRet {: IEntityBase}); stdcall;
end;
IFiltersFromQuery = interface(IInterface)
['{85F5B5FA-3FFE-470E-9F0B-157765264E5D}']
function pm_GetCount: Integer; stdcall;
procedure pm_SetCount(aValue: Integer); stdcall;
{ - методы для доступа к свойству Count. }
procedure Clear; stdcall;
{* очистить список. }
procedure Delete(anIndex: Integer); stdcall;
{* удаляет элемент по индексу Index. }
property Count: Integer
read pm_GetCount
write pm_SetCount;
{* число элементов в хранилище. }
// property methods
procedure pm_GetItem(anIndex: Integer; out aRet: IFilterFromQuery); stdcall;
procedure pm_SetItem(anIndex: Integer; const anItem: IFilterFromQuery); stdcall;
{-}
// public methods
function Add(const anItem: IFilterFromQuery): Integer; stdcall;
{* - добавляет элемент Item в конец. }
procedure Insert(anIndex: Integer; const anItem: IFilterFromQuery); stdcall;
{* - вставляет элемент Item по индексу Index. }
end;//IFiltersFromQuery
IFiltersManager = interface (IInterface) ['{854B1550-A048-4551-AB1C-6FD08FDAF723}']
function DontUseMe: Pointer;
// создать новый фильтр
procedure CreateFilter (
const aQuery: IEntityBase;
const aName: IString
); stdcall;
// получить список фильтров для правовых документов
procedure GetLegalFilters (
out aRet {: IFiltersFromQuery}
); stdcall;
procedure GetPharmFilters (
out aRet {: IFiltersFromQuery}
); stdcall;
procedure SetLegalNotifier (
const aNotifier: IFilterNotifier
); stdcall;
procedure SetPharmNotifier (
const aNotifier: IFilterNotifier
); stdcall;
end;
implementation
end. |
unit UDemo;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.TMSBaseControl,
FMX.Layouts, FMX.TreeView, FMX.Grid, FMX.Printer, Data.Bind.EngExt,
Fmx.Bind.DBEngExt, System.Rtti, System.Bindings.Outputs, Data.Bind.Components,
FMX.TMSGridCell, FMX.TMSGridOptions, FMX.TMSGridData, FMX.TMSGrid, Data.DB, Datasnap.DBClient, Data.Bind.DBScope,
Fmx.Bind.Editors, FMX.TMSGridDataBinding, Fmx.Bind.Navigator, FMX.Edit,
FMX.TMSCustomGrid, FMX.StdCtrls;
type
TForm738 = class(TForm)
EditWithHandler: TEdit;
ImageWithHandler: TImageControl;
BindNavigator1: TBindNavigator;
CheckBoxActiveDataSet: TCheckBox;
LabelPosition: TLabel;
LabelFields: TLabel;
EditWithHandler2: TEdit;
BindingsList: TBindingsList;
BindLinkEditHandler: TBindLink;
BindLinkEditHandler2: TBindLink;
BindLinkImageHandler: TBindLink;
BindLinkPosition: TBindLink;
BindLinkLabel: TBindLink;
BindScopeDB1: TBindScopeDB;
ClientDataSet1: TClientDataSet;
CategoryField: TStringField;
SpeciesNameField: TStringField;
LengthCmField: TFloatField;
LengthInField: TFloatField;
CommonNameField: TStringField;
NotesField: TMemoField;
GraphicField: TBlobField;
ClientDataSetDataSource1: TDataSource;
TMSFMXGrid1: TTMSFMXGrid;
TMSFMXBindDBGridLinkTMSFMXGridLiveBinding11: TTMSFMXBindDBGridLink;
procedure CheckBoxActiveDataSetChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure TMSFMXGridLiveBinding1GetCellProperties(Sender: TObject; ACol,
ARow: Integer; Cell: TFmxObject);
procedure TMSFMXGrid1GetCellEditorType(Sender: TObject; ACol, ARow: Integer;
var CellEditorType: TTMSFMXGridEditorType);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form738: TForm738;
implementation
{$R *.fmx}
procedure TForm738.CheckBoxActiveDataSetChange(Sender: TObject);
begin
ClientDataSetDataSource1.Enabled := True;
ClientDataSet1.Active := CheckBoxActiveDataSet.IsChecked;
end;
procedure TForm738.FormCreate(Sender: TObject);
begin
ClientDataSetDataSource1.Enabled := False;
ClientDataSet1.LoadFromFile('..\..\biolife.xml');
ClientDataSet1.Active := False;
TMSFMXGrid1.DefaultColumnWidth := 150;
TMSFMXGrid1.DefaultRowHeight := 30;
TMSFMXGrid1.ColumnWidths[0] := 30;
TMSFMXGrid1.ColumnCount := 5;
TMSFMXGrid1.Options.Bands.Enabled := True;
end;
procedure TForm738.TMSFMXGrid1GetCellEditorType(Sender: TObject; ACol,
ARow: Integer; var CellEditorType: TTMSFMXGridEditorType);
var
fn: string;
f: TField;
begin
if ACol > 0 then
begin
fn := TMSFMXBindDBGridLinkTMSFMXGridLiveBinding11.ColumnExpressions[ACol- TMSFMXGrid1.FixedColumns].SourceMemberName;
if fn <> '' then
begin
f := ClientDataSet1.FieldByName(fn);
case f.DataType of
ftUnknown: ;
ftString: ;
ftSmallint: ;
ftInteger: ;
ftWord: ;
ftBoolean: ;
ftFloat: ;
ftCurrency: ;
ftBCD: ;
ftDate: ;
ftTime: ;
ftDateTime: ;
ftBytes: ;
ftVarBytes: ;
ftAutoInc: ;
ftBlob: ;
ftMemo: ;
ftGraphic: ;
ftFmtMemo: ;
ftParadoxOle: ;
ftDBaseOle: ;
ftTypedBinary: ;
ftCursor: ;
ftFixedChar: ;
ftWideString: ;
ftLargeint: ;
ftADT: ;
ftArray: ;
ftReference: ;
ftDataSet: ;
ftOraBlob: ;
ftOraClob: ;
ftVariant: ;
ftInterface: ;
ftIDispatch: ;
ftGuid: ;
ftTimeStamp: ;
ftFMTBcd: ;
ftFixedWideChar: ;
ftWideMemo: ;
ftOraTimeStamp: ;
ftOraInterval: ;
ftLongWord: ;
ftShortint: ;
ftByte: ;
ftExtended: ;
ftConnection: ;
ftParams: ;
ftStream: ;
ftTimeStampOffset: ;
ftObject: ;
ftSingle: ;
end;
end;
end;
end;
procedure TForm738.TMSFMXGridLiveBinding1GetCellProperties(Sender: TObject;
ACol, ARow: Integer; Cell: TFmxObject);
begin
if (Cell is TTMSFMXBitmapGridCell) then
(Cell as TTMSFMXBitmapGridCell).Bitmap.Align := TAlignLayout.alClient;
end;
end.
|
{
Version 11.7
Copyright (c) 2008-2016 by HtmlViewer Team
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
unit AuthorizeFormUnit;
{$include htmlcons.inc}
{This module handles getting Usernames and Passwords}
interface
uses
{$ifdef LCL}
LCLIntf, LCLType, LMessages,
{$else}
WinTypes, WinProcs,
{$endif}
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons;
type
{ TAuthForm }
TAuthorizeForm = class(TForm)
AuthUsername: TEdit;
AuthPassword: TEdit;
OKBtn: TBitBtn;
BitBtn2: TBitBtn;
Label1: TLabel;
Label2: TLabel;
LabelRealm: TLabel;
procedure FormShow(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
RealmList: TStringList;
public
class function Execute(TryRealm: Boolean; const Realm: string; var UName, PWord: string): Boolean;
{ Public declarations }
function GetAuthorization(TryRealm: boolean; const Realm: string; var UName, PWord: string): boolean;
end;
implementation
{$ifdef LCL}
{$R *.lfm}
{$else}
{$R *.dfm}
{$endif}
type
PTwoStrings = ^TwoStrings;
TwoStrings = record
UN, PW: string;
end;
var
AuthorizeForm: TAuthorizeForm;
//-- BG ---------------------------------------------------------- 31.05.2016 --
class function TAuthorizeForm.Execute(TryRealm: Boolean; const Realm: string; var UName, PWord: string): Boolean;
begin
if AuthorizeForm = nil then
AuthorizeForm := TAuthorizeForm.Create(Application);
Result := AuthorizeForm.GetAuthorization(TryRealm, Realm, UName, PWord);
end;
procedure TAuthorizeForm.FormShow(Sender: TObject);
begin
AuthUsername.Text := '';
AuthPassword.Text := '';
AuthUsername.SetFocus;
end;
procedure TAuthorizeForm.OKBtnClick(Sender: TObject);
begin
if (AuthUsername.Text = '') or (AuthPassword.Text = '') then
begin
ShowMessage('Entry required for both Username and Password');
ModalResult := mrNone;
end
else
ModalResult := mrOK;
end;
procedure TAuthorizeForm.FormCreate(Sender: TObject);
begin
RealmList := TStringList.Create;
RealmList.Sorted := True;
end;
procedure TAuthorizeForm.FormDestroy(Sender: TObject);
var
I: integer;
begin
for I := 0 to RealmList.Count-1 do
Dispose(PTwoStrings(RealmList.Objects[I]));
RealmList.Free;
end;
function TAuthorizeForm.GetAuthorization(TryRealm: Boolean; const Realm: string; var UName, PWord: string): Boolean;
{TryRealm is only set for one try at most}
var
I: Integer;
P: PTwoStrings;
begin
Result := False;
if TryRealm then
begin
Result := RealmList.Find(Realm, I); {see if the password has already been saved for this Realm}
if Result then
begin
UName := PTwoStrings(RealmList.Objects[I])^.UN;
PWord := PTwoStrings(RealmList.Objects[I])^.PW;
end;
end;
if not Result then
begin
I := Pos('=', Realm);
if I > 0 then // ANGUS: tell user what realm
LabelRealm.Caption := Copy(Realm, I + 1, MaxInt)
else
LabelRealm.Caption := Realm;
Result := ShowModal = mrOK; {Use dialog to get info}
if Result then
begin
UName := AuthUsername.Text;
PWord := AuthPassword.Text;
if RealmList.Find(Realm, I) then {get rid of info for this realm that didn't work}
begin
Dispose(PTwoStrings(RealmList.Objects[I]));
RealmList.Delete(I);
end;
New(P);
P^.UN := UName;
P^.PW := PWord;
RealmList.AddObject(Realm, TObject(P));
end;
end;
end;
end.
|
unit Tablefm;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
System.UIConsts, System.Math, System.Generics.Collections, FMX.Objects,
FMX.Types,
FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Graphics, ClientModuleUnit1,
FMX.StdCtrls, FMX.TabControl, UModel, UMyShape, UMyStringGrid;
type
TTableForm = class(TForm)
TabControl1: TTabControl;
Button1: TButton;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure TabControl1Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
NeedRefresh: boolean;
TableLayouts: TTablePageList;
ShapeLists: TList<TList<TShape>>;
panelList: TList<TPanel>;
TextFont: TFont;
procedure CreateTextFont;
procedure SetPositionAndSize(shape: TShape; TheTable: TTable);
function GetTableColor(table: TTable): TAlphaColor;
procedure RefreshTableStatus;
procedure ChangeTableStatus;
Procedure SetShapeOfATable(table: TTable; TabIndex: integer);
procedure MyShapeClick(Sender: TObject);
procedure DisplayTablesLayouts;
procedure AddTablesToControl;
function ConnectedToServer: boolean;
public
{ Public declarations }
// SelectTable : TTable;
SelectTableStatus: integer;
SelectTableNo: string;
function GetSeatNumber(Tableno:String) : Integer;
end;
var
TableForm: TTableForm;
implementation
{$R *.fmx}
function TTableForm.GetSeatNumber(Tableno: String): Integer;
begin
result := TableLayouts.GetSeatNumber(TableNo);
end;
function TTableForm.GetTableColor(table: TTable): TAlphaColor;
begin
if not table.IsTable then
result := claYellow
else if table.Status = 0 then
result := claGreen
else
result := clared; // claRed;
end;
procedure TTableForm.FormShow(Sender: TObject);
begin
if NeedRefresh then
RefreshTableStatus
else
NeedRefresh := true;
end;
procedure TTableForm.RefreshTableStatus;
var
i: integer;
begin
TableLayouts.RefreshTableStatus;
ChangeTableStatus;
// AddTablesToControl;
end;
procedure TTableForm.FormClose(Sender: TObject; var Action: TCloseAction);
// var
// j, i: integer;
begin
// for j := panelList.Count - 1 downto 0 do
// for i := panelList[j].ControlsCount - 1 downto 0 do
// panelList[j].Controls[i].Free;
end;
procedure TTableForm.FormCreate(Sender: TObject);
begin
if ConnectedToServer then
begin
panelList := TList<TPanel>.Create;
ShapeLists := TList < TList < TShape >>.Create;
NeedRefresh := false;
CreateTextFont;
TableLayouts := TTablePageList.Create;
DisplayTablesLayouts;
end
else
begin
try
ClientModule1.DSRestConnection1.Reset;
except
FMX.Dialogs.MessageDlg('Network error!', TMsgDlgType.mtWarning,
[TMsgDlgBtn.mbOK], 0);
end;
end;
end;
procedure TTableForm.CreateTextFont;
Begin
TextFont := TFont.Create;
TextFont.Size := 18;
TextFont.Style := [TFontStyle.fsBold];
TextFont.Family := 'Arial';
end;
procedure TTableForm.ChangeTableStatus;
var
i, j, tempb: integer;
TheTable: TTable;
temp: string;
begin
for j := 0 to TabControl1.TabCount - 1 do
begin
for i := 0 to TableLayouts.TablePageList[j].Tables.Count - 1 do
begin
TheTable := TableLayouts.TablePageList[j].Tables[i];
ShapeLists[j].Items[i].Fill.Color := self.GetTableColor(TheTable);
ShapeLists[j].Items[i].Tag := TheTable.Status;
end;
end;
TabControl1.ActiveTab := TabControl1.Tabs[0];
end;
procedure TTableForm.AddTablesToControl;
var
i, j: integer;
TheTable: TTable;
list: TList<TShape>;
begin
for j := 0 to TabControl1.TabCount - 1 do
begin
list := TList<TShape>.Create;
ShapeLists.Add(list);
for i := 0 to TableLayouts.TablePageList[j].Tables.Count - 1 do
begin
TheTable := TableLayouts.TablePageList[j].Tables[i];
SetShapeOfATable(TheTable, j);
end;
end;
TabControl1.ActiveTab := TabControl1.Tabs[0];
end;
procedure TTableForm.DisplayTablesLayouts;
var
i: integer;
tabitem: TTabItem;
panel: TPanel;
begin
// 创建楼面 Tabs
if ConnectedToServer then
begin
for i := 0 to TableLayouts.TablePageList.Count - 1 do
begin
tabitem := TTabItem.Create(TabControl1);
tabitem.Font.Size := 20;
tabitem.StyledSettings := [];
tabitem.Text := TableLayouts.TablePageList[i].Description;
tabitem.Tag := TableLayouts.TablePageList[i].PageNo;
tabitem.Parent := TabControl1;
tabitem.Font.Size := 20;
tabitem.Tag := TableLayouts.TablePageList[i].PageNo;
tabitem.Parent := TabControl1;
panel := TPanel.Create(self);
panel.Parent := tabitem;
panel.Align := TAlignLayOut.alClient;
panelList.Add(panel);
end;
AddTablesToControl;
end;
end;
procedure TTableForm.Button1Click(Sender: TObject);
begin
Close;
end;
function TTableForm.ConnectedToServer: boolean;
begin
try
result := proxy.IsConnected();
except
result := false;
end;
end;
procedure TTableForm.MyShapeClick(Sender: TObject);
begin
if not ConnectedToServer then
begin
try
ClientModule1.DSRestConnection1.Reset;
except
FMX.Dialogs.MessageDlg('Network error!', TMsgDlgType.mtWarning,
[TMsgDlgBtn.mbOK], 0);
end
end
else
begin
if Sender is TMyEllipse then
begin
SelectTableStatus := (Sender as TMyEllipse).Tag;
SelectTableNo := (Sender as TMyEllipse).TagString;
end
else
begin
SelectTableStatus := (Sender as TMyRectAngle).Tag;
SelectTableNo := (Sender as TMyRectAngle).TagString;
end;
self.ModalResult := mrOK; // Notify the Orderfm a table has been selected
self.CloseModal;
end;
end;
procedure TTableForm.SetPositionAndSize(shape: TShape; TheTable: TTable);
begin
shape.Position.X := TheTable.X;
shape.Position.Y := TheTable.Y;
shape.Width := TheTable.Width;
shape.Height := TheTable.Height;
if TheTable.IsTable then // Add click handler to table shape
shape.OnClick := self.MyShapeClick;
shape.Tag := TheTable.Status; // Stored the table's Status to shape
shape.TagString := TheTable.TableNo; // Stored the table's TableNo to shape
End;
procedure TTableForm.SetShapeOfATable(table: TTable; TabIndex: integer);
var
ellipse: TMyEllipse;
rectangle: TMyRectAngle;
begin
case table.shape of
0: // circle
begin
ellipse := TMyEllipse.Create(panelList[TabIndex]);
SetPositionAndSize(ellipse, table);
ellipse.Fill.Color := self.GetTableColor(table);
ellipse.Text := table.Description;
ellipse.Font := TextFont;
ellipse.TextColor := claWhite;
// ellipse.StrokeThickness :=0; Can't be run under iOS, it may be a bug in rad studio
// ellipse.TagObject := table;
// ellipse.TagString := table.TableNo;
ellipse.Parent := panelList[TabIndex];
ShapeLists[TabIndex].Add(ellipse);
// panelList[TabIndex].Controls.Add(ellipse);
end; // rectangle
else
begin
rectangle := TMyRectAngle.Create(panelList[TabIndex]);
SetPositionAndSize(rectangle, table);
rectangle.Fill.Color := self.GetTableColor(table);
rectangle.Text := table.Description;
rectangle.Font := TextFont;
if table.IsTable then
begin
rectangle.TextColor := claWhite;
// rectangle.StrokeThickness :=0; Can't be run under iOS, it may be a bug in rad studio
end
else
rectangle.TextColor := claBlack;
rectangle.Parent := panelList[TabIndex];
ShapeLists[TabIndex].Add(rectangle);
// panelList[TabIndex].Controls.Add(rectangle);
end;
end;
end;
procedure TTableForm.TabControl1Click(Sender: TObject);
begin
self.CloseModal;
end;
end.
|
unit PrimAdminMain_utEmptyMainWindow_UserType;
{* Главное окно }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\PrimAdminMain_utEmptyMainWindow_UserType.pas"
// Стереотип: "UserType"
// Элемент модели: "utEmptyMainWindow" MUID: (4BD84DBE0387)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If Defined(Admin)}
uses
l3IntfUses
{$If NOT Defined(NoVCM)}
, vcmUserControls
{$IfEnd} // NOT Defined(NoVCM)
, l3StringIDEx
;
const
{* Локализуемые строки utEmptyMainWindowLocalConstants }
str_utEmptyMainWindowCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'utEmptyMainWindowCaption'; rValue : 'Главное окно');
{* Заголовок пользовательского типа "Главное окно" }
str_utEmptyMainWindowSettingsCaption: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'utEmptyMainWindowSettingsCaption'; rValue : 'Главная панель инструментов');
{* Заголовок пользовательского типа "Главное окно" для настройки панелей инструментов }
{* Константы для типа формы utEmptyMainWindow }
utEmptyMainWindowName = 'utEmptyMainWindow';
{* Строковый идентификатор пользовательского типа "Главное окно" }
utEmptyMainWindow = TvcmUserType(0);
{* Главное окно }
{$IfEnd} // Defined(Admin)
implementation
{$If Defined(Admin)}
uses
l3ImplUses
{$If NOT Defined(NoScripts)}
, tfwInteger
{$IfEnd} // NOT Defined(NoScripts)
;
{$If NOT Defined(NoScripts)}
type
Tkw_FormUserType_utEmptyMainWindow = {final} class(TtfwInteger)
{* Слово словаря для типа формы utEmptyMainWindow }
protected
function GetInteger: Integer; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_FormUserType_utEmptyMainWindow
{$IfEnd} // NOT Defined(NoScripts)
{$If NOT Defined(NoScripts)}
function Tkw_FormUserType_utEmptyMainWindow.GetInteger: Integer;
begin
Result := utEmptyMainWindow;
end;//Tkw_FormUserType_utEmptyMainWindow.GetInteger
class function Tkw_FormUserType_utEmptyMainWindow.GetWordNameForRegister: AnsiString;
begin
Result := 'тип_формы::utEmptyMainWindow';
end;//Tkw_FormUserType_utEmptyMainWindow.GetWordNameForRegister
{$IfEnd} // NOT Defined(NoScripts)
initialization
str_utEmptyMainWindowCaption.Init;
{* Инициализация str_utEmptyMainWindowCaption }
str_utEmptyMainWindowSettingsCaption.Init;
{* Инициализация str_utEmptyMainWindowSettingsCaption }
{$If NOT Defined(NoScripts)}
Tkw_FormUserType_utEmptyMainWindow.RegisterInEngine;
{* Регистрация Tkw_FormUserType_utEmptyMainWindow }
{$IfEnd} // NOT Defined(NoScripts)
{$IfEnd} // Defined(Admin)
end.
|
unit MFichas.Model.GrupoProduto.Metodos.Buscar;
interface
uses
System.SysUtils,
MFichas.Model.GrupoProduto.Interfaces,
MFichas.Controller.Types,
FireDAC.Comp.Client,
FireDAC.Comp.DataSet;
type
TModelGrupoProdutoMetodosBuscar = class(TInterfacedObject, iModelGrupoProdutoMetodosBuscar)
private
[weak]
FParent : iModelGrupoProduto;
FFDMemTable: TFDMemTable;
constructor Create(AParent: iModelGrupoProduto);
procedure Validacao;
procedure CopiarDataSet;
public
destructor Destroy; override;
class function New(AParent: iModelGrupoProduto): iModelGrupoProdutoMetodosBuscar;
function FDMemTable(AFDMemTable: TFDMemTable): iModelGrupoProdutoMetodosBuscar;
function BuscarTodos : iModelGrupoProdutoMetodosBuscar;
function BuscarTodosAtivos : iModelGrupoProdutoMetodosBuscar;
function &End : iModelGrupoProdutoMetodos;
end;
implementation
{ TModelGrupoProdutoMetodosBuscar }
function TModelGrupoProdutoMetodosBuscar.BuscarTodos: iModelGrupoProdutoMetodosBuscar;
begin
//TODO: IMPLEMENTAR MÉTODO DE BUSCA DE GRUPOS
Result := Self;
FParent.DAODataSet.Open;
Validacao;
CopiarDataSet;
end;
function TModelGrupoProdutoMetodosBuscar.&End: iModelGrupoProdutoMetodos;
begin
Result := FParent.Metodos;
end;
procedure TModelGrupoProdutoMetodosBuscar.CopiarDataSet;
begin
FFDMemTable.CopyDataSet(FParent.DAODataSet.DataSet, [coStructure, coRestart, coAppend]);
FFDMemTable.IndexFieldNames := 'DESCRICAO';
end;
procedure TModelGrupoProdutoMetodosBuscar.Validacao;
begin
if not Assigned(FFDMemTable) then
raise Exception.Create(
'Para prosseguir, você deve vincular um FDMemTable ao encadeamento' +
' de funcões do método de GrupoProduto.Metodos.Buscar .'
);
end;
function TModelGrupoProdutoMetodosBuscar.FDMemTable(
AFDMemTable: TFDMemTable): iModelGrupoProdutoMetodosBuscar;
begin
Result := Self;
FFDMemTable := AFDMemTable;
end;
function TModelGrupoProdutoMetodosBuscar.BuscarTodosAtivos: iModelGrupoProdutoMetodosBuscar;
begin
Result := Self;
FParent.DAODataSet.OpenWhere(
' STATUS = ' + Integer(saiAtivo).ToString
);
Validacao;
CopiarDataSet;
end;
constructor TModelGrupoProdutoMetodosBuscar.Create(AParent: iModelGrupoProduto);
begin
FParent := AParent;
end;
destructor TModelGrupoProdutoMetodosBuscar.Destroy;
begin
inherited;
end;
class function TModelGrupoProdutoMetodosBuscar.New(AParent: iModelGrupoProduto): iModelGrupoProdutoMetodosBuscar;
begin
Result := Self.Create(AParent);
end;
end.
|
{ Version 1.0 - Author jasc2v8 at yahoo dot com
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org> }
unit debugunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TDebugForm }
TDebugForm = class(TForm)
Memo: TMemo;
ButtonClear: TButton;
procedure ButtonClearClick(Sender: TObject);
private
public
end;
var
DebugForm: TDebugForm;
procedure Debugln(Arg1: Variant);
procedure Debugln(Arg1, Arg2: Variant);
procedure Debugln(Arg1, Arg2, Arg3: Variant);
procedure Debugln(Arg1, Arg2, Arg3, Arg4: Variant);
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5: Variant);
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6: Variant);
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7: Variant);
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8: Variant);
procedure Debugln(Args: array of Variant);
procedure Debugln(Fmt:string; Args: array of Const);
implementation
{$R *.lfm}
{ TDebugForm }
procedure Debugln(Arg1: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); //will write boolean True or False
sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2, Arg3: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
WriteStr(sbuf,Arg3); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2, Arg3, Arg4: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
WriteStr(sbuf,Arg3); sout:=sout+sbuf;
WriteStr(sbuf,Arg4); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
WriteStr(sbuf,Arg3); sout:=sout+sbuf;
WriteStr(sbuf,Arg4); sout:=sout+sbuf;
WriteStr(sbuf,Arg5); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
WriteStr(sbuf,Arg3); sout:=sout+sbuf;
WriteStr(sbuf,Arg4); sout:=sout+sbuf;
WriteStr(sbuf,Arg5); sout:=sout+sbuf;
WriteStr(sbuf,Arg6); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
WriteStr(sbuf,Arg3); sout:=sout+sbuf;
WriteStr(sbuf,Arg4); sout:=sout+sbuf;
WriteStr(sbuf,Arg5); sout:=sout+sbuf;
WriteStr(sbuf,Arg6); sout:=sout+sbuf;
WriteStr(sbuf,Arg7); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8: Variant);
var
sbuf, sout: string;
begin
WriteStr(sbuf,Arg1); sout:=sout+sbuf;
WriteStr(sbuf,Arg2); sout:=sout+sbuf;
WriteStr(sbuf,Arg3); sout:=sout+sbuf;
WriteStr(sbuf,Arg4); sout:=sout+sbuf;
WriteStr(sbuf,Arg5); sout:=sout+sbuf;
WriteStr(sbuf,Arg6); sout:=sout+sbuf;
WriteStr(sbuf,Arg7); sout:=sout+sbuf;
WriteStr(sbuf,Arg8); sout:=sout+sbuf;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Args: array of Variant);
var
i: integer;
sbuf, sout: string;
begin
for i:=Low(Args) to High(Args) do begin
WriteStr(sbuf, Args[i]);
sout:=sout+sbuf;
end;
DebugForm.Memo.Append(sout);
end;
procedure Debugln(Fmt:string; Args: array of Const);
begin
DebugForm.Memo.Append(Format(Fmt, Args));
end;
procedure TDebugForm.ButtonClearClick(Sender: TObject);
begin
Memo.Clear;
end;
end.
|
unit rxDialogs;
interface
{$Include l3XE.inc}
uses
Classes
;
function BrowseDirectory(var AFolderName: AnsiString; const DlgText: AnsiString;
AHelpContext: THelpContext): Boolean;
implementation
uses
Windows,
Messages,
ShellAPI,
Consts,
SysUtils,
Controls,
Forms,
FileCtrl,
ComObj,
ActiveX,
VCLUtils,
l3FileUtils
;
{ TBrowseFolderDlg }
const
{ message from browser }
BFFM_INITIALIZED = 1;
BFFM_SELCHANGED = 2;
{ messages to browser }
BFFM_SETSTATUSTEXT = (WM_USER + 100);
BFFM_ENABLEOK = (WM_USER + 101);
BFFM_SETSELECTION = (WM_USER + 102);
type
{ TSHItemID -- Item ID }
PSHItemID = ^TSHItemID;
TSHItemID = packed record { mkid }
cb: Word; { Size of the ID (including cb itself) }
abID: array[0..0] of Byte; { The item ID (variable length) }
end;
{ TItemIDList -- List if item IDs (combined with 0-terminator) }
PItemIDList = ^TItemIDList;
TItemIDList = packed record { idl }
mkid: TSHItemID;
end;
TFNBFFCallBack = function(Wnd: HWND; uMsg: UINT; lParam, lpData: LPARAM): Integer stdcall;
PBrowseInfo = ^TBrowseInfo;
TBrowseInfo = packed record
hwndOwner: HWND;
pidlRoot: PItemIDList;
pszDisplayName: LPSTR; { Return display name of item selected. }
lpszTitle: LPCSTR; { text to go in the banner over the tree. }
ulFlags: UINT; { Flags that control the return stuff }
lpfn: TFNBFFCallBack;
lParam: LPARAM; { extra info that's passed back in callbacks }
iImage: Integer; { output var: where to return the Image index. }
end;
TBrowseKind = (bfFolders, bfComputers);
TDialogPosition = (dpDefault, dpScreenCenter);
TBrowseFolderDlg = class(TComponent)
private
FDefWndProc: Pointer;
FHelpContext: THelpContext;
FHandle: HWnd;
FObjectInstance: Pointer;
FDesktopRoot: Boolean;
FBrowseKind: TBrowseKind;
FPosition: TDialogPosition;
FText: AnsiString;
FDisplayName: AnsiString;
FSelectedName: AnsiString;
FFolderName: AnsiString;
FImageIndex: Integer;
FOnInitialized: TNotifyEvent;
FOnSelChanged: TNotifyEvent;
procedure SetSelPath(const Path: AnsiString);
procedure SetOkEnable(Value: Boolean);
procedure DoInitialized;
procedure DoSelChanged(Param: PItemIDList);
procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY;
procedure WMCommand(var Message: TMessage); message WM_COMMAND;
protected
procedure DefaultHandler(var Message); override;
procedure WndProc(var Message: TMessage); virtual;
function TaskModalDialog(var Info: TBrowseInfo): PItemIDList;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean;
property Handle: HWnd read FHandle;
property DisplayName: AnsiString read FDisplayName;
property SelectedName: AnsiString read FSelectedName write FSelectedName;
property ImageIndex: Integer read FImageIndex;
published
property BrowseKind: TBrowseKind read FBrowseKind write FBrowseKind default bfFolders;
property DesktopRoot: Boolean read FDesktopRoot write FDesktopRoot default True;
property DialogText: AnsiString read FText write FText;
property FolderName: AnsiString read FFolderName write FFolderName;
property HelpContext: THelpContext read FHelpContext write FHelpContext default 0;
property Position: TDialogPosition read FPosition write FPosition default dpScreenCenter;
property OnInitialized: TNotifyEvent read FOnInitialized write FOnInitialized;
property OnSelChanged: TNotifyEvent read FOnSelChanged write FOnSelChanged;
end;
function ExplorerHook(Wnd: HWnd; Msg: UINT; LParam: LPARAM; Data: LPARAM): Integer; stdcall;
begin
Result := 0;
if Msg = BFFM_INITIALIZED then begin
if TBrowseFolderDlg(Data).Position = dpScreenCenter then
CenterWindow(Wnd);
TBrowseFolderDlg(Data).FHandle := Wnd;
TBrowseFolderDlg(Data).FDefWndProc := Pointer(SetWindowLong(Wnd, GWL_WNDPROC,
Longint(TBrowseFolderDlg(Data).FObjectInstance)));
TBrowseFolderDlg(Data).DoInitialized;
end
else if Msg = BFFM_SELCHANGED then begin
TBrowseFolderDlg(Data).FHandle := Wnd;
TBrowseFolderDlg(Data).DoSelChanged(PItemIDList(LParam));
end;
end;
const
HelpButtonId = $FFFF;
constructor TBrowseFolderDlg.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FObjectInstance := MakeObjectInstance(WndProc);
FDesktopRoot := True;
FBrowseKind := bfFolders;
FPosition := dpScreenCenter;
SetLength(FDisplayName, MAX_PATH);
end;
destructor TBrowseFolderDlg.Destroy;
begin
if FObjectInstance <> nil then FreeObjectInstance(FObjectInstance);
inherited Destroy;
end;
procedure TBrowseFolderDlg.DoInitialized;
const
SBtn = 'BUTTON';
var
BtnHandle, HelpBtn, BtnFont: THandle;
BtnSize: TRect;
begin
if (FBrowseKind = bfComputers) or DirExists(FFolderName) then
SetSelPath(FFolderName);
if FHelpContext <> 0 then begin
BtnHandle := FindWindowEx(FHandle, 0, SBtn, nil);
if (BtnHandle <> 0) then begin
GetWindowRect(BtnHandle, BtnSize);
ScreenToClient(FHandle, BtnSize.TopLeft);
ScreenToClient(FHandle, BtnSize.BottomRight);
BtnFont := SendMessage(FHandle, WM_GETFONT, 0, 0);
HelpBtn := CreateWindowA(SBtn, PAnsiChar(ResStr(SHelpButton)),
WS_CHILD or WS_CLIPSIBLINGS or WS_VISIBLE or BS_PUSHBUTTON or WS_TABSTOP,
12, BtnSize.Top, BtnSize.Right - BtnSize.Left, BtnSize.Bottom - BtnSize.Top,
FHandle, HelpButtonId, HInstance, nil);
if BtnFont <> 0 then
SendMessage(HelpBtn, WM_SETFONT, BtnFont, MakeLParam(1, 0));
UpdateWindow(FHandle);
end;
end;
if Assigned(FOnInitialized) then FOnInitialized(Self);
end;
const
{ Browsing for directory }
BIF_RETURNONLYFSDIRS = $0001; { For finding a folder to start document searching }
BIF_DONTGOBELOWDOMAIN = $0002; { For starting the Find Computer }
BIF_STATUSTEXT = $0004;
BIF_RETURNFSANCESTORS = $0008;
BIF_BROWSEFORCOMPUTER = $1000; { Browsing for Computers }
BIF_BROWSEFORPRINTER = $2000; { Browsing for Printers }
BIF_BROWSEINCLUDEFILES = $4000; { Browsing for Everything }
const
CSIDL_DRIVES = $0011;
CSIDL_NETWORK = $0012;
function SHBrowseForFolder(var lpbi: TBrowseInfo): PItemIDList; stdcall;
far; external Shell32 name 'SHBrowseForFolder';
function SHGetPathFromIDList(pidl: PItemIDList; pszPath: LPSTR): BOOL; stdcall;
far; external Shell32 name 'SHGetPathFromIDList';
function SHGetSpecialFolderLocation(hwndOwner: HWND; nFolder: Integer;
var ppidl: PItemIDList): HResult; stdcall; far; external Shell32
name 'SHGetSpecialFolderLocation';
procedure TBrowseFolderDlg.DoSelChanged(Param: PItemIDList);
var
Temp: array[0..MAX_PATH] of AnsiChar;
begin
if (FBrowseKind = bfComputers) then begin
FSelectedName := DisplayName;
end
else begin
if SHGetPathFromIDList(Param, Temp) then begin
FSelectedName := StrPas(Temp);
SetOkEnable(DirExists(FSelectedName));
end
else begin
FSelectedName := '';
SetOkEnable(False);
end;
end;
if Assigned(FOnSelChanged) then FOnSelChanged(Self);
end;
procedure TBrowseFolderDlg.SetSelPath(const Path: AnsiString);
begin
if FHandle <> 0 then
SendMessage(FHandle, BFFM_SETSELECTION, 1, Longint(PAnsiChar(Path)));
end;
procedure TBrowseFolderDlg.SetOkEnable(Value: Boolean);
begin
if FHandle <> 0 then SendMessage(FHandle, BFFM_ENABLEOK, 0, Ord(Value));
end;
procedure TBrowseFolderDlg.DefaultHandler(var Message);
begin
if FHandle <> 0 then
with TMessage(Message) do
Result := CallWindowProc(FDefWndProc, FHandle, Msg, WParam, LParam)
else inherited DefaultHandler(Message);
end;
procedure TBrowseFolderDlg.WndProc(var Message: TMessage);
begin
Dispatch(Message);
end;
procedure TBrowseFolderDlg.WMCommand(var Message: TMessage);
begin
if (Message.wParam = HelpButtonId) and (LongRec(Message.lParam).Hi =
BN_CLICKED) and (FHelpContext <> 0) then
begin
Application.HelpContext(FHelpContext);
end
else inherited;
end;
procedure TBrowseFolderDlg.WMNCDestroy(var Message: TWMNCDestroy);
begin
inherited;
FHandle := 0;
end;
function RemoveBackSlash(const DirName: AnsiString): AnsiString;
begin
Result := DirName;
if (Length(Result) > 1) and
(AnsiLastChar(Result)^ = '\') then
begin
if not ((Length(Result) = 3) and (UpCase(Result[1]) in ['A'..'Z']) and
(Result[2] = ':')) then
Delete(Result, Length(Result), 1);
end;
end;
function TBrowseFolderDlg.Execute: Boolean;
var
BrowseInfo: TBrowseInfo;
ItemIDList: PItemIDList;
Temp: array[0..MAX_PATH] of AnsiChar;
begin
if FDesktopRoot and (FBrowseKind = bfFolders) then
BrowseInfo.pidlRoot := nil
else begin
if FBrowseKind = bfComputers then { root - Network }
OleCheck(SHGetSpecialFolderLocation(0, CSIDL_NETWORK,
BrowseInfo.pidlRoot))
else { root - MyComputer }
OleCheck(SHGetSpecialFolderLocation(0, CSIDL_DRIVES,
BrowseInfo.pidlRoot));
end;
try
SetLength(FDisplayName, MAX_PATH);
with BrowseInfo do begin
pszDisplayName := PAnsiChar(DisplayName);
if DialogText <> '' then lpszTitle := PAnsiChar(DialogText)
else lpszTitle := nil;
if FBrowseKind = bfComputers then
ulFlags := BIF_BROWSEFORCOMPUTER
else
ulFlags := BIF_RETURNONLYFSDIRS or BIF_RETURNFSANCESTORS;
lpfn := ExplorerHook;
lParam := Longint(Self);
hWndOwner := Application.Handle;
iImage := 0;
end;
ItemIDList := TaskModalDialog(BrowseInfo);
Result := ItemIDList <> nil;
if Result then
try
if FBrowseKind = bfFolders then begin
Win32Check(SHGetPathFromIDList(ItemIDList, Temp));
FFolderName := RemoveBackSlash(StrPas(Temp));
end
else begin
FFolderName := DisplayName;
end;
FSelectedName := FFolderName;
FImageIndex := BrowseInfo.iImage;
finally
CoTaskMemFree(ItemIDList);
end;
finally
if BrowseInfo.pidlRoot <> nil then CoTaskMemFree(BrowseInfo.pidlRoot);
end;
end;
function TBrowseFolderDlg.TaskModalDialog(var Info: TBrowseInfo): PItemIDList;
var
ActiveWindow: HWnd;
WindowList: Pointer;
begin
ActiveWindow := GetActiveWindow;
WindowList := DisableTaskWindows(0);
try
try
Result := SHBrowseForFolder(Info);
finally
FHandle := 0;
FDefWndProc := nil;
end;
finally
EnableTaskWindows(WindowList);
SetActiveWindow(ActiveWindow);
end;
end;
function BrowseDirectory(var AFolderName: AnsiString; const DlgText: AnsiString;
AHelpContext: THelpContext): Boolean;
{$IfDef XE}
var
l_S : String;
{$EndIf XE}
begin
if NewStyleControls then begin
with TBrowseFolderDlg.Create(Application) do
try
DialogText := DlgText;
FolderName := AFolderName;
HelpContext := AHelpContext;
Result := Execute;
if Result then AFolderName := FolderName;
finally
Free;
end;
end
else
begin
{$IfDef XE}
l_S := AFolderName;
Result := SelectDirectory(l_S, [], AHelpContext);
AFolderName := l_S;
{$Else XE}
Result := SelectDirectory(AFolderName, [], AHelpContext);
{$EndIf XE}
end;
end;
end. |
unit libpostproc;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
Uses
ffmpeg_types;
{$I ffmpeg.inc}
(* *
* Return the LIBPOSTPROC_VERSION_INT constant.
*)
// unsigned postproc_version(void);
function postproc_version(): unsigned; cdecl; external postproc_dll;
(* *
* Return the libpostproc build-time configuration.
*)
// const char *postproc_configuration(void);
function postproc_configuration(): pAnsiChar; cdecl; external postproc_dll;
(* *
* Return the libpostproc license.
*)
// const char *postproc_license(void);
function postproc_license(): pAnsiChar; cdecl; external postproc_dll;
const
PP_QUALITY_MAX = 6;
// #include <inttypes.h>
type
ppp_context = ^pp_context;
pp_context = record
end;
ppp_mode = ^pp_mode;
pp_mode = record
end;
Tpp_src_puint8_t = array [0 .. 2] of puint8_t;
Tpp_dst_puint8_t = Tpp_src_puint8_t;
Tpp_srcStride_int = array [0 .. 2] of int;
Tpp_dstStride_int = Tpp_srcStride_int;
(*
#if LIBPOSTPROC_VERSION_INT < (52<<16)
typedef pp_context pp_context_t;
typedef pp_mode pp_mode_t;
extern const char *const pp_help; ///< a simple help text
#else
extern const char pp_help[]; ///< a simple help text
#endif
*)
// void pp_postprocess(const uint8_t * src[3], const int srcStride[3],
// uint8_t * dst[3], const int dstStride[3],
// int horizontalSize, int verticalSize,
// const int8_t *QP_store, int QP_stride,
// pp_mode *mode, pp_context *ppContext, int pict_type);
procedure pp_postprocess(const src: Tpp_src_puint8_t; const srcStride: Tpp_srcStride_int; dst: Tpp_dst_puint8_t;
const dstStride: Tpp_dstStride_int; horizontalSize: int; verticalSize: int; const QP_store: pint8_t; QP_stride: int; mode: ppp_mode;
ppContext: ppp_context; pict_type: int); cdecl; external postproc_dll;
(* *
* Return a pp_mode or NULL if an error occurred.
*
* @param name the string after "-pp" on the command line
* @param quality a number from 0 to PP_QUALITY_MAX
*)
// pp_mode *pp_get_mode_by_name_and_quality(const char *name, int quality);
function pp_get_mode_by_name_and_quality(const name: pAnsiChar; quality: int): ppp_mode; cdecl; external postproc_dll;
// void pp_free_mode(pp_mode *mode);
procedure pp_free_mode(mode: ppp_mode); cdecl; external postproc_dll;
// pp_context *pp_get_context(int width, int height, int flags);
function pp_get_context(width: int; height: int; flags: int): ppp_context; cdecl; external postproc_dll;
// void pp_free_context(pp_context *ppContext);
procedure pp_free_context(ppContext: ppp_context); cdecl; external postproc_dll;
const
PP_CPU_CAPS_MMX = $80000000;
PP_CPU_CAPS_MMX2 = $20000000;
PP_CPU_CAPS_3DNOW = $40000000;
PP_CPU_CAPS_ALTIVEC = $10000000;
PP_CPU_CAPS_AUTO = $00080000;
PP_FORMAT = $00000008;
PP_FORMAT_420 = ($00000011 or PP_FORMAT);
PP_FORMAT_422 = ($00000001 or PP_FORMAT);
PP_FORMAT_411 = ($00000002 or PP_FORMAT);
PP_FORMAT_444 = ($00000000 or PP_FORMAT);
PP_FORMAT_440 = ($00000010 or PP_FORMAT);
PP_PICT_TYPE_QP2 = $00000010;
/// < MPEG2 style QScale
implementation
end.
|
unit DamFileGenerator;
interface
uses DamUnit;
procedure GenerateFile(Dam: TDam; const Template: string);
implementation
uses
{$IFDEF FPC}
Classes, SysUtils, LazIDEIntf
{$ELSE}
System.Classes, System.SysUtils, ToolsAPI
{$ENDIF};
procedure GenerateFile(Dam: TDam; const Template: string);
var
{$IFNDEF FPC}
ModServices: IOTAModuleServices;
Module: IOTAModule;
{$ENDIF}
C: TComponent;
Dir: string;
StmUnit: string;
Msg: TDamMsg;
S: TStringList;
A, aFuncName, aFuncKind, aResFunc, aPreCmd, aCmd, aEv, aPar1, aPar2, aCab, aTxt: string;
aDecs, Func: string;
aTime: string;
const ENTER = #13#10;
begin
{$IFDEF FPC}
Dir := LazarusIDE.ActiveProject.Directory;
{$ELSE}
ModServices := BorlandIDEServices as IOTAModuleServices;
Module := ModServices.FindFormModule(Dam.Owner.Name);
if Module = nil then
raise Exception.Create('Form Module not found');
Dir := ExtractFilePath(Module.FileName);
{$ENDIF}
StmUnit := Dam.DamUnitName;
aTime := DateTimeToStr(Now);
for C in Dam.Owner do
if C is TDamMsg then
begin
Msg := TDamMsg(C);
if SameText(Msg.Dam.DamUnitName, StmUnit) then
begin
A := Msg.Name;
if A[1] = '_' then Delete(A, 1, 1);
aFuncName := A;
aCmd := Dam.Owner.Name+'.'+Msg.Name;
aPar1 := '';
aPar2 := '';
if Pos('%p', Msg.Message) > 0 then
begin
aPar1 := '(Params: TDamParams)';
aPar2 := '(Params)';
end;
if (Msg.RaiseExcept) or (Msg.Buttons in [dbOK, dbOne]) then
begin
aFuncKind := 'procedure';
aResFunc := '';
aPreCmd := '';
aEv := 'Run';
end else
if (Msg.Buttons in [dbYesNo, dbTwo]) then
begin
aFuncKind := 'function';
aResFunc := ': Boolean';
aPreCmd := 'Result := ';
aEv := 'RunAsBool';
end else
begin
aFuncKind := 'function';
aResFunc := ': TDamMsgRes';
aPreCmd := 'Result := ';
aEv := 'Run';
end;
aCab := aFuncKind+' '+aFuncName+aPar1+aResFunc+';';
aTxt := aCab+ENTER+
'begin'+ENTER+
' '+aPreCmd+aCmd+'.'+aEv+aPar2+';'+ENTER+
'end;'+ENTER;
aDecs := aDecs + aCab + ENTER;
Func := Func + aTxt + ENTER;
end;
end;
A := Template;
A := StringReplace(A, '<UNIT>', ExtractFileName(StmUnit), []);
A := StringReplace(A, '<TIMESTAMP>', aTime, []);
A := StringReplace(A, '<USES>', Dam.Owner.UnitName, []);
A := StringReplace(A, '<DECLARATIONS>', aDecs, []);
A := StringReplace(A, '<FUNCTIONS>', Func, []);
S := TStringList.Create;
try
S.Text := A;
S.SaveToFile(Dir + StmUnit + '.pas');
finally
S.Free;
end;
end;
end.
|
unit uChamadoOcorrenciaVO;
interface
uses
System.SysUtils, System.Generics.Collections;
type
TChamadoOcorrenciaVO = class
private
FIdUsuarioColab2: Integer;
FIdChamado: Integer;
FIdUsuarioColab3: Integer;
FVersao: string;
FIdUsuarioColab1: Integer;
FIdUsuario: Integer;
FTotalHoras: Double;
FId: Integer;
FAnexo: string;
FDescricaoTecnica: string;
FHoraFim: TTime;
FDocto: string;
FHoraInicio: TTime;
FData: TDate;
FDescricaoSolucao: string;
FQtde: Integer;
FValor: Currency;
procedure SetAnexo(const Value: string);
procedure SetData(const Value: TDate);
procedure SetDescricaoSolucao(const Value: string);
procedure SetDescricaoTecnica(const Value: string);
procedure SetDocto(const Value: string);
procedure SetHoraFim(const Value: TTime);
procedure SetHoraInicio(const Value: TTime);
procedure SetId(const Value: Integer);
procedure SetIdChamado(const Value: Integer);
procedure SetIdUsuario(const Value: Integer);
procedure SetIdUsuarioColab1(const Value: Integer);
procedure SetIdUsuarioColab2(const Value: Integer);
procedure SetIdUsuarioColab3(const Value: Integer);
procedure SetTotalHoras(const Value: Double);
procedure SetVersao(const Value: string);
procedure SetQtde(const Value: Integer);
procedure SetValor(const Value: Currency);
public
property Id: Integer read FId write SetId;
property IdChamado: Integer read FIdChamado write SetIdChamado;
property Docto: string read FDocto write SetDocto;
property Data: TDate read FData write SetData;
property HoraInicio: TTime read FHoraInicio write SetHoraInicio;
property HoraFim: TTime read FHoraFim write SetHoraFim;
property IdUsuario: Integer read FIdUsuario write SetIdUsuario;
property IdUsuarioColab1: Integer read FIdUsuarioColab1 write SetIdUsuarioColab1;
property IdUsuarioColab2: Integer read FIdUsuarioColab2 write SetIdUsuarioColab2;
property IdUsuarioColab3: Integer read FIdUsuarioColab3 write SetIdUsuarioColab3;
property DescricaoTecnica: string read FDescricaoTecnica write SetDescricaoTecnica;
property DescricaoSolucao: string read FDescricaoSolucao write SetDescricaoSolucao;
property Anexo: string read FAnexo write SetAnexo;
property TotalHoras: Double read FTotalHoras write SetTotalHoras;
property Versao: string read FVersao write SetVersao;
property Qtde: Integer read FQtde write SetQtde;
property Valor: Currency read FValor write SetValor;
end;
TListaChamadoOcorrencia = TObjectList<TChamadoOcorrenciaVO>;
implementation
{ TChamadoOcorrenciaVO }
procedure TChamadoOcorrenciaVO.SetAnexo(const Value: string);
begin
FAnexo := Value;
end;
procedure TChamadoOcorrenciaVO.SetData(const Value: TDate);
begin
FData := Value;
end;
procedure TChamadoOcorrenciaVO.SetDescricaoSolucao(const Value: string);
begin
FDescricaoSolucao := Value;
end;
procedure TChamadoOcorrenciaVO.SetDescricaoTecnica(const Value: string);
begin
FDescricaoTecnica := Value;
end;
procedure TChamadoOcorrenciaVO.SetDocto(const Value: string);
begin
FDocto := Value;
end;
procedure TChamadoOcorrenciaVO.SetHoraFim(const Value: TTime);
begin
FHoraFim := Value;
end;
procedure TChamadoOcorrenciaVO.SetHoraInicio(const Value: TTime);
begin
FHoraInicio := Value;
end;
procedure TChamadoOcorrenciaVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TChamadoOcorrenciaVO.SetIdChamado(const Value: Integer);
begin
FIdChamado := Value;
end;
procedure TChamadoOcorrenciaVO.SetIdUsuario(const Value: Integer);
begin
FIdUsuario := Value;
end;
procedure TChamadoOcorrenciaVO.SetIdUsuarioColab1(const Value: Integer);
begin
FIdUsuarioColab1 := Value;
end;
procedure TChamadoOcorrenciaVO.SetIdUsuarioColab2(const Value: Integer);
begin
FIdUsuarioColab2 := Value;
end;
procedure TChamadoOcorrenciaVO.SetIdUsuarioColab3(const Value: Integer);
begin
FIdUsuarioColab3 := Value;
end;
procedure TChamadoOcorrenciaVO.SetQtde(const Value: Integer);
begin
FQtde := Value;
end;
procedure TChamadoOcorrenciaVO.SetTotalHoras(const Value: Double);
begin
FTotalHoras := Value;
end;
procedure TChamadoOcorrenciaVO.SetValor(const Value: Currency);
begin
FValor := Value;
end;
procedure TChamadoOcorrenciaVO.SetVersao(const Value: string);
begin
FVersao := Value;
end;
end.
|
unit abstract_graph_command;
interface
uses abstract_command_lib, Hash_wrapper,classes;
type
TCommandState = (csForward,csBackward,csDummy);
TAbstractGraphCommand = class (TAbstractCommand)
private
fPrevState,fNextState: THash; //ссылки на состояния, только они нам и нужны для восст.
//структуры графа
fCommandState: TCommandState;
procedure ReadPrev(stream: TStream); //вот где пригодилось бы каррирование
procedure ReadNext(stream: TStream);
procedure WritePrev(stream: TStream);
procedure WriteNext(stream: TStream);
protected
procedure DefineProperties(filer: TFiler); override;
published
property CommandState: TCommandState read fCommandState write fCommandState;
end;
TCommandGraph = class (TAbstractCommandContainer)
private
public
procedure Add(command: TAbstractCommand); override;
procedure Undo; override;
procedure Redo; override;
function UndoEnabled: Boolean; override;
function RedoEnabled: Boolean; override;
function CheckForExistingCommand(command: TAbstractCommand): boolean; override;
procedure JumpToBranch(command: TAbstractCommand); override;
function currentExecutedCommand: TAbstractCommand; override; //и просто тек. команду возвр.
//и как начало итератора. Executed-чтобы помнить, мы стоим на состоянии ПОСЛЕ ее вып.
function PrevCommand: TAbstractCommand; override;
function NextCommand: TAbstractCommand; override;
end;
implementation
(*
TAbstractGraphCommand
*)
procedure TAbstractGraphCommand.DefineProperties(filer: TFiler);
begin
filer.DefineBinaryProperty('PrevState',ReadPrev,WritePrev,True);
filer.DefineBinaryProperty('NextState',ReadNext,WriteNext,True);
//когда команда внесена в граф, мы знаем и начальное, и конечное состояние
end;
procedure TAbstractGraphCommand.ReadPrev(stream: TStream);
begin
stream.Read(fPrevState[0],SizeOf(fPrevState));
end;
procedure TAbstractGraphCommand.WritePrev(stream: TStream);
begin
stream.Write(fPrevState[0],SizeOf(fPrevState));
end;
procedure TAbstractGraphCommand.ReadNext(stream: TStream);
begin
stream.Read(fNextState[0],SizeOf(fNextState));
end;
procedure TAbstractGraphCommand.WriteNext(stream: TStream);
begin
stream.Write(fNextState[0],SizeOf(fNextState));
end;
(*
TCommandGraph
*)
end.
|
unit CompanyForma;
interface
{$I defines.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ActnList, DB, ComCtrls, DBGridEh, Grids, ToolWin, GridsEh,
ToolCtrlsEh, DBGridEhToolCtrls, DBAxisGridsEh,
System.Actions, DBGridEhGrouping, DynVarsEh, EhLibVCL, Vcl.Mask,
DBCtrlsEh, Vcl.StdCtrls, Vcl.DBCtrls, Vcl.Buttons, Vcl.ExtCtrls,
CnErrorProvider;
type
TCompanyForm = class(TForm)
tlbMain: TToolBar;
ToolButton4: TToolButton;
ToolButton3: TToolButton;
ToolButton9: TToolButton;
tbOk: TToolButton;
ToolButton10: TToolButton;
tbCancel: TToolButton;
srcCompany: TDataSource;
ActionList1: TActionList;
actEdit: TAction;
dbGrid: TDBGridEh;
actNew: TAction;
actDelete: TAction;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
pnlEdit: TPanel;
btnSaveLink: TBitBtn;
btnCancelLink: TBitBtn;
lbl3: TLabel;
edtO_DIMENSION: TDBEditEh;
lbl1: TLabel;
edtName: TDBEditEh;
lbl2: TLabel;
mmoDesc: TDBMemoEh;
lbl4: TLabel;
edtPP: TDBEditEh;
lbl5: TLabel;
edtC_KODE: TDBEditEh;
CnErrors: TCnErrorProvider;
procedure actEditExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure tbCancelClick(Sender: TObject);
procedure tbOkClick(Sender: TObject);
procedure srcCompanyStateChange(Sender: TObject);
procedure actNewExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure srcCompanyDataChange(Sender: TObject; Field: TField);
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnSaveLinkClick(Sender: TObject);
procedure btnCancelLinkClick(Sender: TObject);
procedure dbGridDblClick(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FNeedUpdate: Boolean;
FCanEdit: Boolean;
FCanCreate: Boolean;
FinEditMode: Boolean;
procedure StartEdit(const New: Boolean = False);
procedure StopEdit(const Cancel: Boolean);
public
{ Public declarations }
end;
var
CompanyForm: TCompanyForm;
implementation
uses DM, MAIN, PrjConst;
{$R *.dfm}
procedure TCompanyForm.srcCompanyStateChange(Sender: TObject);
begin
tbOk.Enabled := not((Sender as TDataSource).DataSet.State = dsBrowse);
tbCancel.Enabled := tbOk.Enabled;
actNew.Enabled := not tbOk.Enabled;
FneedUpdate := True;
end;
procedure TCompanyForm.tbOkClick(Sender: TObject);
begin
if (not(dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Company)))
then srcCompany.DataSet.Cancel
else srcCompany.DataSet.Post;
end;
procedure TCompanyForm.tbCancelClick(Sender: TObject);
begin
srcCompany.DataSet.Cancel;
end;
procedure TCompanyForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if FneedUpdate
then begin
srcCompany.DataSet.Close;
srcCompany.DataSet.Open;
end;
Action := CaFree;
CompanyForm := nil;
end;
procedure TCompanyForm.FormCreate(Sender: TObject);
begin
FneedUpdate := False;
if not srcCompany.DataSet.Active
then srcCompany.DataSet.Open;
end;
procedure TCompanyForm.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (Shift = [ssCtrl]) and (Ord(Key) = VK_RETURN) and FinEditMode
then
StopEdit(False);
end;
procedure TCompanyForm.actEditExecute(Sender: TObject);
begin
// if ((dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Shippers)))
// then srcCompany.DataSet.Edit;
StartEdit(False);
end;
procedure TCompanyForm.actNewExecute(Sender: TObject);
begin
// if (not (dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Shippers))) then exit;
// srcCompany.DataSet.Append;
StartEdit(True);
end;
procedure TCompanyForm.actDeleteExecute(Sender: TObject);
begin
if (not(dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Company)))
then exit;
srcCompany.DataSet.Delete;
end;
procedure TCompanyForm.FormShow(Sender: TObject);
begin
// права пользователей
FCanEdit := ((dmMain.AllowedAction(rght_Dictionary_full) or dmMain.AllowedAction(rght_Dictionary_Company)));
FCanCreate := FCanEdit;
actNew.Visible := FCanEdit;
actDelete.Visible := FCanEdit;
actEdit.Visible := FCanEdit;
// tbOk.Visible := False;
// tbCancel.Visible := False;
end;
procedure TCompanyForm.srcCompanyDataChange(Sender: TObject; Field: TField);
begin
actEdit.Enabled := ((Sender as TDataSource).DataSet.RecordCount > 0) and actNew.Enabled;
actDelete.Enabled := ((Sender as TDataSource).DataSet.RecordCount > 0) and actNew.Enabled;
end;
procedure TCompanyForm.StartEdit(const New: Boolean = False);
begin
if not FCanEdit
then exit;
if (not New) and (srcCompany.DataSet.RecordCount = 0)
then exit;
pnlEdit.Visible := True;
dbGrid.Enabled := False;
tlbMain.Enabled := False;
// pnlEdit.SetFocus;
if New
then begin
srcCompany.DataSet.Append;
edtPP.Setfocus;
end
else begin
srcCompany.DataSet.Edit;
if edtName.Text.IsEmpty then edtName.SetFocus
else edtO_DIMENSION.SetFocus;
end;
FinEditMode := True;
end;
procedure TCompanyForm.StopEdit(const Cancel: Boolean);
var
errors: Boolean;
begin
if (Cancel) or (not FCanEdit)
then begin
CnErrors.Dispose(edtPP);
CnErrors.Dispose(edtC_KODE);
CnErrors.Dispose(edtName);
if (srcCompany.DataSet.State in [dsEdit, dsInsert])
then srcCompany.DataSet.Cancel;
errors := False;
end
else begin
errors := False;
if (edtPP.Text = '')
then begin
errors := True;
CnErrors.SetError(edtPP, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink);
end
else CnErrors.Dispose(edtPP);
if (edtC_KODE.Text = '')
then begin
errors := True;
CnErrors.SetError(edtC_KODE, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink);
end
else CnErrors.Dispose(edtC_KODE);
if (edtName.Text = '')
then begin
errors := True;
CnErrors.SetError(edtName, rsEmptyFieldError, iaMiddleLeft, bsNeverBlink);
end
else CnErrors.Dispose(edtName);
if not errors
then srcCompany.DataSet.Post;
end;
pnlEdit.Visible := errors;
dbGrid.Enabled := not errors;
tlbMain.Enabled := not errors;
FinEditMode := errors;
if not errors
then dbGrid.SetFocus;
end;
procedure TCompanyForm.btnSaveLinkClick(Sender: TObject);
begin
StopEdit(False);
end;
procedure TCompanyForm.btnCancelLinkClick(Sender: TObject);
begin
StopEdit(True);
end;
procedure TCompanyForm.dbGridDblClick(Sender: TObject);
begin
if srcCompany.DataSet.RecordCount > 0
then begin
if not(actEdit.Enabled or actEdit.Visible)
then exit;
actEdit.Execute;
end
else begin
if not(actNew.Enabled or actNew.Visible)
then exit;
actNew.Execute;
end;
end;
end.
|
unit QuickList_DayData;
interface
uses
QuickSortList,
define_stock_quotes;
type
PDayDataListItem = ^TDayDataListItem;
TDayDataListItem = record
DealDate: Word;
DayData : PRT_Quote_Day;
end;
{ 行情分钟线数据访问 }
TDayDataList = class(TALBaseQuickSortList)
public
function GetItem(Index: Integer): Word;
procedure SetItem(Index: Integer; const ADealDate: Word);
function GetObject(Index: Integer): PRT_Quote_Day;
procedure PutObject(Index: Integer; ADayData: PRT_Quote_Day);
public
procedure Notify(Ptr: Pointer; Action: TListNotification); override;
procedure InsertItem(Index: Integer; const ADealDate: Word; ADayData: PRT_Quote_Day);
function CompareItems(const Index1, Index2: Integer): Integer; override;
public
function IndexOf(ADealDate: Word): Integer;
function IndexOfObject(ADayData: PRT_Quote_Day): Integer;
Function AddDayData(const ADealDate: Word; ADayData: PRT_Quote_Day): Integer;
function Find(ADealDate: Word; var Index: Integer): Boolean;
procedure InsertObject(Index: Integer; const ADealDate: Word; ADayData: PRT_Quote_Day);
property DealDate[Index: Integer]: Word read GetItem write SetItem; default;
property DayData[Index: Integer]: PRT_Quote_Day read GetObject write PutObject;
end;
implementation
{********************************************************}
function TDayDataList.AddDayData(const ADealDate: Word; ADayData: PRT_Quote_Day): Integer;
begin
if not Sorted then
begin
Result := FCount
end else if Find(ADealDate, Result) then
begin
case Duplicates of
lstDupIgnore: Exit;
lstDupError: Error(@SALDuplicateItem, 0);
end;
end;
InsertItem(Result, ADealDate, ADayData);
end;
{*****************************************************************************************}
procedure TDayDataList.InsertItem(Index: Integer; const ADealDate: Word; ADayData: PRT_Quote_Day);
Var aPDayDataListItem: PDayDataListItem;
begin
New(aPDayDataListItem);
aPDayDataListItem^.DealDate := ADealDate;
aPDayDataListItem^.DayData := ADayData;
try
inherited InsertItem(index,aPDayDataListItem);
except
Dispose(aPDayDataListItem);
raise;
end;
end;
{***************************************************************************}
function TDayDataList.CompareItems(const Index1, Index2: integer): Integer;
begin
result := PDayDataListItem(Get(Index1))^.DealDate - PDayDataListItem(Get(Index2))^.DealDate;
end;
{***********************************************************************}
function TDayDataList.Find(ADealDate: Word; var Index: Integer): Boolean;
var
L, H, I, C: Integer;
begin
Result := False;
L := 0;
H := FCount - 1;
while L <= H do
begin
I := (L + H) shr 1;
C := GetItem(I) - ADealDate;
if C < 0 then
begin
L := I + 1
end else
begin
H := I - 1;
if C = 0 then
begin
Result := True;
if Duplicates <> lstDupAccept then
L := I;
end;
end;
end;
Index := L;
end;
{*******************************************************}
function TDayDataList.GetItem(Index: Integer): Word;
begin
Result := PDayDataListItem(Get(index))^.DealDate;
end;
{******************************************************}
function TDayDataList.IndexOf(ADealDate: Word): Integer;
begin
if not Sorted then
Begin
Result := 0;
while (Result < FCount) and (GetItem(result) <> ADealDate) do
begin
Inc(Result);
end;
if Result = FCount then
Result := -1;
end else if not Find(ADealDate, Result) then
begin
Result := -1;
end;
end;
{*******************************************************************************************}
procedure TDayDataList.InsertObject(Index: Integer; const ADealDate: Word; ADayData: PRT_Quote_Day);
Var aPDayDataListItem: PDayDataListItem;
begin
New(aPDayDataListItem);
aPDayDataListItem^.DealDate := ADealDate;
aPDayDataListItem^.DayData := ADayData;
try
inherited insert(index,aPDayDataListItem);
except
Dispose(aPDayDataListItem);
raise;
end;
end;
{***********************************************************************}
procedure TDayDataList.Notify(Ptr: Pointer; Action: TListNotification);
begin
if Action = lstDeleted then
dispose(ptr);
inherited Notify(Ptr, Action);
end;
{********************************************************************}
procedure TDayDataList.SetItem(Index: Integer; const ADealDate: Word);
var
tmpDayDataListItem: PDayDataListItem;
begin
New(tmpDayDataListItem);
tmpDayDataListItem^.DealDate := ADealDate;
tmpDayDataListItem^.DayData := nil;
Try
Put(Index, tmpDayDataListItem);
except
Dispose(tmpDayDataListItem);
raise;
end;
end;
{*********************************************************}
function TDayDataList.GetObject(Index: Integer): PRT_Quote_Day;
begin
if (Index < 0) or (Index >= FCount) then
Error(@SALListIndexError, Index);
Result := PDayDataListItem(Get(index))^.DayData;
end;
{***************************************************************}
function TDayDataList.IndexOfObject(ADayData: PRT_Quote_Day): Integer;
begin
for Result := 0 to Count - 1 do
begin
if GetObject(Result) = ADayData then
begin
Exit;
end;
end;
Result := -1;
end;
{*******************************************************************}
procedure TDayDataList.PutObject(Index: Integer; ADayData: PRT_Quote_Day);
begin
if (Index < 0) or (Index >= FCount) then
Error(@SALListIndexError, Index);
PDayDataListItem(Get(index))^.DayData := ADayData;
end;
end.
|
unit TestServerMain;
interface
uses
ShareMem, Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, RDOInterfaces, WinSockRDOConnectionsServer, RDOServer;
type
TTestServerForm =
class(TForm)
StartServer: TButton;
StopServer: TButton;
Edit1: TEdit;
Label1: TLabel;
procedure FormDestroy(Sender: TObject);
procedure StartServerClick(Sender: TObject);
procedure StopServerClick(Sender: TObject);
private
{ Private declarations }
fRDOConnectionServer : IRDOConnectionsServer;
fRDOServer : TRDOServer;
public
{ Public declarations }
end;
var
TestServerForm: TTestServerForm;
implementation
{$R *.DFM}
procedure TTestServerForm.FormDestroy(Sender: TObject);
begin
fRDOConnectionServer := nil;
fRDOServer.Free;
fRDOServer := nil;
end;
procedure TTestServerForm.StartServerClick(Sender: TObject);
begin
StartServer.Enabled := false;
StopServer.Enabled := true;
try
if fRDOConnectionServer = nil
then
begin
fRDOConnectionServer := TWinSockRDOConnectionsServer.Create( 5000 );
fRDOServer := TRDOServer.Create( fRDOConnectionServer as IRDOServerConnection, 1, nil );
fRDOServer.RegisterObject('Form', integer(Self));
fRDOConnectionServer.StartListening;
end
else fRDOConnectionServer.StartListening;
except
StartServer.Enabled := true;
StopServer.Enabled := false;
Application.MessageBox('Error initializing RDO', 'TestServer', MB_OK);
end;
end;
procedure TTestServerForm.StopServerClick(Sender: TObject);
begin
StartServer.Enabled := true;
StopServer.Enabled := false;
if fRDOConnectionServer <> nil
then fRDOConnectionServer.StopListening;
end;
end.
|
(*
Michael Neuhold
31.10.2018
Test with one dim. array with element datatype CHAR.
*)
PROGRAM ArrayTest;
CONST
max = 100;
TYPE
CharArray = Array[1..max] OF CHAR;
PROCEDURE FillArray(VAR a: CharArray; n: INTEGER);
VAR
i : INTEGER;
BEGIN
Randomize; (* Prozedur Aufruf ohne Übergabeparametern *)
FOR i := 1 TO n DO BEGIN
a[i] := Chr((Random(25) + Ord('a')));
END;
END; (* FillArray *)
PROCEDURE WriteArray(a: CharArray; n: INTEGER);
VAR
i : INTEGER;
BEGIN
FOR i := 1 TO n DO BEGIN
Write(a[i],' ');
END;
WriteLn();
END;
PROCEDURE FirstOccuranceAt(a: CharArray; n: INTEGER; ch: CHAR; VAR position: INTEGER);
VAR
i: INTEGER;
BEGIN
i := 1;
WHILE (i <= n) AND (a[i] <> ch) DO BEGIN
i := i + 1;
END;
IF i <= n THEN
position := i
ELSE (* ch not in a *)
position := 0;
END;
VAR
chArray : CharArray;
noOfChars: INTEGER;
position: INTEGER;
ch: CHAR;
BEGIN
noOfChars := 25;
FillArray(chArray,noOfChars);
WriteArray(chArray,noOfChars);
WriteLn('Bitte geben Sie eine ch ein: ');
Read(ch);
FirstOccuranceAt(chArray,noOfChars,ch,position);
WriteLn('Position: ',position);
END. |
unit uDisciplina;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uBase, 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,
FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.StdCtrls, Vcl.Grids,
Vcl.DBGrids, Vcl.Buttons, Vcl.ExtCtrls;
type
TfrmCadastroDisciplina = class(TfrmCadastroBase)
Código: TLabel;
edtId: TEdit;
Descrição: TLabel;
edtDescricao: TEdit;
qrDisciplina: TFDQuery;
dsDisciplina: TDataSource;
qrDisciplinaID: TIntegerField;
qrDisciplinaDESCRICAO: TStringField;
procedure sbSalvarClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure sbExcluirClick(Sender: TObject);
procedure dbCellClick(Column: TColumn);
procedure sbEditarClick(Sender: TObject);
procedure sbNovoClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure LimparCampos;
procedure ExibirRegistros;
end;
var
frmCadastroDisciplina: TfrmCadastroDisciplina;
implementation
{$R *.dfm}
uses uModulo, uSystemUtils;
procedure TfrmCadastroDisciplina.dbCellClick(Column: TColumn);
begin
inherited;
if qrDisciplina.FieldByName('id').AsString <> null then
begin
edtId.Text := qrDisciplina.FieldByName('id').AsString;
edtDescricao.Text := qrDisciplina.FieldByName('descricao').AsString;
edtId.Enabled := False;
end;
end;
procedure TfrmCadastroDisciplina.ExibirRegistros;
begin
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('SELECT * FROM disciplinas');
qrDisciplina.SQL.Add(' ORDER BY id ASC ');
qrDisciplina.Open();
end;
procedure TfrmCadastroDisciplina.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
frmCadastroDisciplina := nil;
end;
procedure TfrmCadastroDisciplina.LimparCampos;
begin
edtId.Text := '';
edtDescricao.Text := '';
end;
procedure TfrmCadastroDisciplina.sbEditarClick(Sender: TObject);
begin
inherited;
if Trim(edtId.Text) = '' then
begin
ShowMessage('Selecione um registro para atualização.');
db.SetFocus;
Exit;
end;
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('UPDATE disciplinas');
qrDisciplina.SQL.Add('SET descricao = :descricao');
qrDisciplina.SQL.Add('WHERE id = :id');
qrDisciplina.ParamByName('id').AsString := edtId.Text;
qrDisciplina.ParamByName('descricao').AsString := edtDescricao.Text;
qrDisciplina.ExecSQL;
ShowMessage('Cadastro atualizado com sucesso.');
LimparCampos;
ExibirRegistros;
end;
procedure TfrmCadastroDisciplina.sbExcluirClick(Sender: TObject);
begin
inherited;
if not db.Columns.Grid.Focused then
begin
ShowMessage('Selecione um registro para exclusão.');
db.SetFocus;
Exit;
end;
if MsgConfirm('Deseja excluir registro?') then
begin
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('DELETE FROM disciplinas WHERE id = :id');
qrDisciplina.ParamByName('id').AsString := edtId.Text;
qrDisciplina.ExecSQL;
LimparCampos;
ExibirRegistros;
ShowMessage('Registro excluido com sucesso.');
edtDescricao.SetFocus;
end;
end;
procedure TfrmCadastroDisciplina.sbNovoClick(Sender: TObject);
begin
inherited;
LimparCampos;
edtDescricao.Text := '';
end;
procedure TfrmCadastroDisciplina.sbSalvarClick(Sender: TObject);
begin
inherited;
if Trim(edtDescricao.Text) = '' then
begin
ShowMessage('Campo nome descricão.');
edtDescricao.SetFocus;
Exit;
end;
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('SELECT * FROM disciplinas WHERE descricao = :descricao');
qrDisciplina.ParamByName('descricao').AsString := edtDescricao.Text;
qrDisciplina.Open;
if qrDisciplina.IsEmpty then
begin
qrDisciplina.Close;
qrDisciplina.SQL.Clear;
qrDisciplina.SQL.Add('INSERT INTO disciplinas (descricao)');
qrDisciplina.SQL.Add('VALUES (:descricao)');
qrDisciplina.ParamByName('descricao').AsString := edtDescricao.Text;
qrDisciplina.ExecSQL;
ShowMessage('Cadastro realizado com sucesso.');
LimparCampos;
ExibirRegistros;
Exit;
end
else
begin
ShowMessage('Disciplina possui cadastro.');
Exit;
end;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StLArr.pas 4.04 *}
{*********************************************************}
{* SysTools: Large array classes *}
{*********************************************************}
{$I StDefine.inc}
{Notes:
- requires a 386 or better processor, even for 16-bit Delphi apps
- uses the value in the SYSTEM variable HeapAllocFlags when allocating
memory for the array.
- changing the size of an array allocates a new array, transfers the
old data, and then frees the original array.
- arrays are always indexed from 0 to Count-1.
- after creating a descendant that knows the type of each element, an
indexed default property can be used to access array elements in a
convenient fashion, e.g., A[100] := 6.0;
- the Get and Put methods don't perform range checking.
- for 32-bit matrix, Rows*Cols cannot exceed 2**32.
}
unit StLArr;
interface
uses
Windows,
Classes, StConst, StBase;
type
TStLArray = class(TStContainer)
{.Z+}
protected
{property instance variables}
FElSize : Integer; {Size of each array element}
FElStorable : boolean; {True if elements can be stored directly}
{private instance variables}
laData : Pointer; {Pointer to data block}
{undocumented protected methods}
procedure ForEachUntypedVar(Action : TIterateUntypedFunc;
OtherData : pointer);
override;
procedure GetArraySizes(var RowCount, ColCount, ElSize : Cardinal);
override;
procedure SetArraySizes(RowCount, ColCount, ElSize : Cardinal);
override;
function StoresUntypedVars : boolean;
override;
procedure laSetCount(Elements : Integer);
{.Z-}
public
constructor Create(Elements : Integer; ElementSize : Cardinal);
{-Initialize a large 1D array}
destructor Destroy; override;
{-Free a large 1D array}
procedure LoadFromStream(S : TStream); override;
{-Load a collection's data from a stream}
procedure StoreToStream(S : TStream); override;
{-Write a collection and its data to a stream}
procedure Assign(Source: TPersistent); override;
{-Assign another container's contents to this one}
procedure Clear; override;
{-Fill the array with zeros}
procedure Fill(const Value);
{-Fill array with specified value}
procedure Put(El : Integer; const Value);
{-Set an element}
procedure Get(El : Integer; var Value);
{-Return an element}
procedure Exchange(El1, El2 : Integer);
{-Exchange the specified elements}
procedure Sort(Compare : TUntypedCompareFunc);
{-Sort the array using the given comparison function}
property Count : Integer
{-Read or write the number of elements in the array}
read FCount
write laSetCount;
property ElementSize : Integer
read FElSize;
property ElementsStorable : boolean
{-True if elements can be written directly to (or read from) disk}
read FElStorable write FElStorable;
end;
type
TStLMatrix = class(TStContainer)
{.Z+}
protected
{property instance variables}
FElSize : Integer; {Size of each array element}
FCols : Cardinal; {Number of columns}
FRows : Cardinal; {Number of rows}
FElStorable : boolean; {True if elements can be stored directly}
{private instance variables}
lmData : Pointer; {Pointer to data block}
lmRowSize : Integer; {Number of bytes in a row}
{undocumented protected methods}
procedure ForEachUntypedVar(Action : TIterateUntypedFunc; OtherData : pointer);
override;
procedure GetArraySizes(var RowCount, ColCount, ElSize : Cardinal);
override;
procedure SetArraySizes(RowCount, ColCount, ElSize : Cardinal);
override;
function StoresUntypedVars : boolean;
override;
procedure lmSetRows(Rows : Cardinal);
procedure lmSetCols(Cols : Cardinal);
{.Z-}
public
constructor Create(Rows, Cols, ElementSize : Cardinal);
{-Initialize a large 2D matrix}
destructor Destroy; override;
{-Free a large 2D matrix}
procedure LoadFromStream(S : TStream); override;
{-Load a collection's data from a stream}
procedure StoreToStream(S : TStream); override;
{-Write a collection and its data to a stream}
procedure Assign(Source: TPersistent); override;
{-Assign another container's contents to this one}
procedure Clear; override;
{-Fill the matrix with zeros}
procedure Fill(const Value);
{-Fill matrix with specified value}
procedure Put(Row, Col : Cardinal; const Value);
{-Set an element}
procedure Get(Row, Col : Cardinal; var Value);
{-Return an element}
procedure PutRow(Row : Cardinal; const RowValue);
{-Set an entire row}
procedure GetRow(Row : Cardinal; var RowValue);
{-Return an entire row}
procedure ExchangeRows(Row1, Row2 : Cardinal);
{-Exchange the specified rows}
procedure SortRows(KeyCol : Cardinal; Compare : TUntypedCompareFunc);
{-Sort the array rows using the given comparison function and
the elements in the given column}
property Rows : Cardinal
{-Read or write the number of rows in the array}
read FRows
write lmSetRows;
property Cols : Cardinal
{-Read or write the number of columns in the array}
read FCols
write lmSetCols;
property ElementSize : Integer
read FElSize;
property ElementsStorable : boolean
{-True if elements can be written directly to (or read from) disk}
read FElStorable write FElStorable;
end;
{======================================================================}
implementation
uses
SysUtils;
function AssignArrayData(Container : TStContainer;
var Data;
OtherData : Pointer) : Boolean; far;
var
OurArray : TStLArray absolute OtherData;
RD : TAssignRowData absolute Data;
begin
OurArray.Put(RD.RowNum, RD.Data);
Result := true;
end;
function AssignMatrixData(Container : TStContainer;
var Data;
OtherData : Pointer) : Boolean; far;
var
OurMatrix : TStLMatrix absolute OtherData;
RD : TAssignRowData absolute Data;
begin
OurMatrix.PutRow(RD.RowNum, RD.Data);
Result := true;
end;
procedure TStLArray.Assign(Source: TPersistent);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{The only containers that we allow to be assigned to a large array
are:
- another SysTools large array (TStLArray)
- a SysTools large matrix (TStLMatrix) with one column
- a SysTools virtual matrix (TStVMatrix) with one column}
if not AssignUntypedVars(Source, AssignArrayData) then
inherited Assign(Source);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;{try..finally}
{$ENDIF}
end;
procedure TStLArray.Clear;
var
C : Integer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
C := FCount;
FillChar(laData^, C*FElSize, 0);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.ForEachUntypedVar(Action : TIterateUntypedFunc;
OtherData : pointer);
var
FullRow : ^TAssignRowData;
i : Cardinal;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
GetMem(FullRow, sizeof(Cardinal) + ElementSize);
try
for i := 0 to pred(Count) do
begin
FullRow^.RowNum := i;
Get(i, FullRow^.Data);
Action(Self, FullRow^, OtherData);
end;
finally
FreeMem(FullRow, sizeof(Cardinal) + ElementSize);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.GetArraySizes(var RowCount, ColCount, ElSize : Cardinal);
begin
RowCount := Count;
ColCount := 1;
ElSize := ElementSize;
end;
procedure TStLArray.SetArraySizes(RowCount, ColCount, ElSize : Cardinal);
begin
if (ColCount <> 1) then
RaiseContainerError(stscTooManyCols);
if (Integer(RowCount) <> Count) or
(Integer(ElSize) <> ElementSize) then begin
HugeFreeMem(laData, FCount*FElSize);
FCount := RowCount;
FElSize := ElSize;
GetMem(laData, RowCount*ElSize);
Clear;
end;
end;
function TStLArray.StoresUntypedVars : boolean;
begin
Result := True;
end;
constructor TStLArray.Create(Elements : Integer; ElementSize : Cardinal);
begin
if (Elements <= 0) or (ElementSize = 0) or
ProductOverflow(Elements, ElementSize) then
RaiseContainerError(stscBadSize);
CreateContainer(TStNode, 0);
FCount := Elements;
FElSize := ElementSize;
GetMem(laData, Elements*Integer(ElementSize));
Clear;
end;
destructor TStLArray.Destroy;
begin
HugeFreeMem(laData, FCount*FElSize);
IncNodeProtection;
inherited Destroy;
end;
procedure TStLArray.Exchange(El1, El2 : Integer);
var
pEl1: TBytes;
pEl2: TBytes;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (El1 < 0) or (El1 >= Count) or (El2 < 0) or (El2 >= Count) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
SetLength(pEl1, FElSize);
SetLength(pEl2, FElSize);
Get(El1, pEl1[0]);
Get(El2, pEl2[0]);
Put(El1, pEl2[0]);
Put(El2, pEl1[0]);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.Fill(const Value);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
HugeFillStruc(laData^, FCount, Value, FElSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.Get(El : Integer; var Value);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (El < 0) or (El >= Count) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
Move((PByte(laData) + El * FElSize)^, Value, FElSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.laSetCount(Elements : Integer);
var
CurSize, NewSize : Integer;
CurFData : Pointer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{validate new size}
if (Elements <= 0) or ProductOverflow(Elements, FElSize) then
RaiseContainerError(stscBadSize);
NewSize := Elements*FElSize;
CurSize := FCount*FElSize;
CurFData := laData;
{allocate data block of new size}
GetMem(laData, NewSize);
FCount := Elements;
{fill extra area with zeros and copy old data}
if NewSize > CurSize then begin
Clear;
NewSize := CurSize;
end;
Move(CurFData^, laData^, NewSize);
{free original data area}
HugeFreeMem(CurFData, CurSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.Put(El : Integer; const Value);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (El < 0) or (El >= Count) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
Move(Value, (PByte(laData)+ El * FElSize)^, FElSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.Sort(Compare : TUntypedCompareFunc);
const
StackSize = 32;
type
Stack = array[0..StackSize-1] of Integer;
var
L : Integer;
R : Integer;
PL : Integer;
PR : Integer;
CurEl : Pointer;
PivEl : Pointer;
StackP : Integer;
LStack : Stack;
RStack : Stack;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{Need at least 2 elements to sort}
if FCount <= 1 then
Exit;
GetMem(CurEl, FElSize);
try
GetMem(PivEl, FElSize);
try
{Initialize the stacks}
StackP := 0;
LStack[0] := 0;
RStack[0] := FCount-1;
{Repeatedly take top partition from stack}
repeat
{Pop the stack}
L := LStack[StackP];
R := RStack[StackP];
Dec(StackP);
{Sort current partition}
repeat
{Load the pivot element}
Get((L+R) div 2, PivEl^);
PL := L;
PR := R;
{Swap items in sort order around the pivot index}
repeat
Get(PL, CurEl^);
while Compare(CurEl^, PivEl^) < 0 do begin
Inc(PL);
Get(PL, CurEl^);
end;
Get(PR, CurEl^);
while Compare(PivEl^, CurEl^) < 0 do begin
Dec(PR);
Get(PR, CurEl^);
end;
if PL <= PR then begin
if PL <> PR then
{Swap the two elements}
Exchange(PL, PR);
Inc(PL); {assume we'll never sort 2 billion elements}
Dec(PR);
end;
until PL > PR;
{Decide which partition to sort next}
if (PR-L) < (R-PL) then begin
{Right partition is bigger}
if PL < R then begin
{Stack the request for sorting right partition}
Inc(StackP);
LStack[StackP] := PL;
RStack[StackP] := R;
end;
{Continue sorting left partition}
R := PR;
end else begin
{Left partition is bigger}
if L < PR then begin
{Stack the request for sorting left partition}
Inc(StackP);
LStack[StackP] := L;
RStack[StackP] := PR;
end;
{Continue sorting right partition}
L := PL;
end;
until L >= R;
until StackP < 0;
finally
FreeMem(PivEl, FElSize);
end;
finally
FreeMem(CurEl, FElSize);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.LoadFromStream(S : TStream);
var
Data : pointer;
Reader : TReader;
NumElements : Integer;
ElementSize : Integer;
i : Integer;
TotSize : Integer;
StreamedClass : TPersistentClass;
StreamedClassName : string;
Value : TValueType;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Clear;
Reader := TReader.Create(S, 1024);
try
with Reader do
begin
StreamedClassName := ReadString;
StreamedClass := GetClass(StreamedClassName);
if (StreamedClass = nil) then
RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]);
if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or
(not IsOrInheritsFrom(TStLArray, StreamedClass)) then
RaiseContainerError(stscWrongClass);
NumElements := ReadInteger;
ElementSize := ReadInteger;
if (NumElements <> FCount) or (ElementSize <> FElSize) then
begin
HugeFreeMem(laData, FCount*FElSize);
FCount := NumElements;
FElSize := ElementSize;
GetMem(laData, NumElements*ElementSize);
Clear;
end;
ElementsStorable := ReadBoolean;
if ElementsStorable then
begin
Read(Value, sizeof(Value)); {s/b vaBinary}
Read(TotSize, sizeof(Integer));
GetMem(Data, FElSize);
try
for i := 0 to pred(FCount) do
begin
Read(Data^, FElSize);
Put(i, Data^);
end;
finally
FreeMem(Data, FElSize);
end;
end
else
begin
ReadListBegin;
for i := 0 to pred(FCount) do begin
Data := DoLoadData(Reader);
Put(i, Data^);
end;
ReadListEnd;
end;
end;
finally
Reader.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLArray.StoreToStream(S : TStream);
var
Writer : TWriter;
i : integer;
Data : pointer;
TotSize: Integer;
Value : TValueType;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Writer := TWriter.Create(S, 1024);
try
GetMem(Data, FElSize);
try
with Writer do begin
WriteString(Self.ClassName);
WriteInteger(FCount);
WriteInteger(FElSize);
WriteBoolean(FElStorable);
if ElementsStorable then begin
Value := vaBinary;
Write(Value, sizeof(Value));
TotSize := FCount * FElSize;
Write(TotSize, sizeof(Integer));
for i := 0 to pred(FCount) do begin
Get(i, Data^);
Write(Data^, FElSize);
end;
end else begin
WriteListBegin;
for i := 0 to pred(FCount) do begin
Get(i, Data^);
DoStoreData(Writer, Data);
end;
WriteListEnd;
end;
end;
finally
FreeMem(Data, FElSize);
end;
finally
Writer.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
{----------------------------------------------------------------------}
procedure TStLMatrix.Assign(Source: TPersistent);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{The only containers that we allow to be assigned to a large matrix
are:
- a SysTools large array (TStLArray)
- another SysTools large matrix (TStLMatrix)
- a SysTools virtual matrix (TStVMatrix)}
if not AssignUntypedVars(Source, AssignMatrixData) then
inherited Assign(Source);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;{try..finally}
{$ENDIF}
end;
procedure TStLMatrix.Clear;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
FillChar(lmData^, FCount*FElSize, 0);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.ForEachUntypedVar(Action : TIterateUntypedFunc;
OtherData : pointer);
var
FullRow : ^TAssignRowData;
i : Cardinal;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
GetMem(FullRow, sizeof(Cardinal) + lmRowSize);
try
for i := 0 to pred(Rows) do
begin
FullRow^.RowNum := i;
GetRow(i, FullRow^.Data);
Action(Self, FullRow^, OtherData);
end;
finally
FreeMem(FullRow, sizeof(Cardinal) + lmRowSize);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.GetArraySizes(var RowCount, ColCount, ElSize : Cardinal);
begin
RowCount := Rows;
ColCount := Cols;
ElSize := ElementSize;
end;
procedure TStLMatrix.SetArraySizes(RowCount, ColCount, ElSize : Cardinal);
begin
if (RowCount <> Rows) or (ColCount <> Cols) or
(Integer(ElSize) <> ElementSize) then
begin
HugeFreeMem(lmData, FCount*FElSize);
FElSize := ElSize;
FRows := RowCount;
FCols := ColCount;
FCount := RowCount*ColCount;
lmRowSize := ColCount*ElSize;
GetMem(lmData, FCount*Integer(ElSize));
Clear;
end;
end;
function TStLMatrix.StoresUntypedVars : boolean;
begin
Result := true;
end;
constructor TStLMatrix.Create(Rows, Cols, ElementSize : Cardinal);
begin
CreateContainer(TStNode, 0);
FElSize := ElementSize;
FRows := Rows;
FCols := Cols;
FCount := Integer(Rows)*Integer(Cols);
lmRowSize := Integer(Cols)*Integer(ElementSize);
if (Rows = 0) or (Cols = 0) or (ElementSize = 0) or
ProductOverflow(FCount, ElementSize) then
RaiseContainerError(stscBadSize);
GetMem(lmData, FCount*Integer(ElementSize));
Clear;
end;
destructor TStLMatrix.Destroy;
begin
HugeFreeMem(lmData, FCount*FElSize);
IncNodeProtection;
inherited Destroy;
end;
procedure TStLMatrix.ExchangeRows(Row1, Row2 : Cardinal);
var
pRow1: TBytes;
pRow2: TBytes;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (Row1 >= Rows) or (Row2 >= Rows) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
SetLength(pRow1, lmRowSize);
SetLength(pRow2, lmRowSize);
GetRow(Row1, pRow1[0]);
GetRow(Row2, pRow2[0]);
PutRow(Row1, pRow2[0]);
PutRow(Row2, pRow1[0]);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.Fill(const Value);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
HugeFillStruc(lmData^, FCount, Value, FElSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.Get(Row, Col : Cardinal; var Value);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if (Row >= Rows) or (Col >= Cols) then
RaiseContainerError(stscBadIndex);
Move((PByte(lmData)+ Integer((Row * FCols + Col)) * FElSize)^, Value, FElSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.GetRow(Row : Cardinal; var RowValue);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if Row >= Rows then
RaiseContainerError(stscBadIndex);
{$ENDIF}
move((PAnsiChar(lmData)+(Integer(Row)*lmRowSize))^, RowValue, lmRowSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.lmSetCols(Cols : Cardinal);
var
CurSize, NewSize, CurRowSize, NewRowSize, BufSize : Integer;
R, CurCols : Cardinal;
CurFData, NewFData, RowData : Pointer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Cols = FCols then
Exit;
{validate new size}
if (Cols = 0) or
ProductOverflow(Cols, FRows) or
ProductOverflow(Integer(Cols)*Integer(FRows), FElSize) then
RaiseContainerError(stscBadSize);
{compute and save various sizes}
CurSize := FCount*FElSize;
NewSize := Integer(Cols)*Integer(FRows)*FElSize;
CurRowSize := lmRowSize;
NewRowSize := Integer(Cols)*FElSize;
CurCols := FCols;
CurFData := lmData;
{allocate data block of new size}
GetMem(NewFData, NewSize);
{allocate a buffer to transfer row data}
if NewRowSize > CurRowSize then
BufSize := NewRowSize
else
BufSize := CurRowSize;
try
GetMem(RowData, BufSize);
except
HugeFreeMem(NewFData, NewSize);
end;
{transfer rows from old array to new}
if Cols > CurCols then
FillChar(RowData^, BufSize, 0);
for R := 0 to FRows-1 do begin
FCols := CurCols;
lmRowSize := CurRowSize;
lmData := CurFData;
GetRow(R, RowData^);
FCols := Cols;
lmRowSize := NewRowSize;
lmData := NewFData;
PutRow(R, RowData^);
end;
HugeFreeMem(RowData, BufSize);
FCount := Integer(Cols)*Integer(FRows);
{free original data area}
HugeFreeMem(CurFData, CurSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.lmSetRows(Rows : Cardinal);
var
CurSize, NewSize : Integer;
CurFData : Pointer;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if Rows = FRows then
Exit;
{validate new size}
if (Rows = 0) or
ProductOverflow(Rows, FCols) or
ProductOverflow(Integer(Rows)*Integer(FCols), FElSize) then
RaiseContainerError(stscBadSize);
CurSize := FCount*FElSize;
NewSize := Integer(Rows)*Integer(FCols)*FElSize;
CurFData := lmData;
{allocate data block of new size}
GetMem(lmData, NewSize);
FCount := Integer(Rows)*Integer(FCols);
FRows := Rows;
{fill extra area with zeros and copy old data}
if NewSize > CurSize then begin
Clear;
NewSize := CurSize;
end;
Move(CurFData^, lmData^, NewSize);
{free original data area}
HugeFreeMem(CurFData, CurSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.Put(Row, Col : Cardinal; const Value);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if (Row >= Rows) or (Col >= Cols) then
RaiseContainerError(stscBadIndex);
{$ENDIF}
Move(Value, (PByte(lmData)+ Integer((Row * FCols + Col)) * FElSize)^, FElSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.PutRow(Row : Cardinal; const RowValue);
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
{$IFOPT R+}
if Row >= Rows then
RaiseContainerError(stscBadIndex);
{$ENDIF}
move(RowValue, (PAnsiChar(lmData)+(Integer(Row)*lmRowSize))^, lmRowSize);
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.SortRows(KeyCol : Cardinal; Compare : TUntypedCompareFunc);
const
StackSize = 32;
type
Stack = array[0..StackSize-1] of Integer;
var
L : Integer;
R : Integer;
PL : Integer;
PR : Integer;
CurEl : Pointer;
PivEl : Pointer;
StackP : Integer;
LStack : Stack;
RStack : Stack;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
if KeyCol >= FCols then
RaiseContainerError(stscBadIndex);
{Need at least 2 rows to sort}
if FRows <= 1 then
Exit;
GetMem(CurEl, FElSize);
try
GetMem(PivEl, FElSize);
{Initialize the stacks}
StackP := 0;
LStack[0] := 0;
RStack[0] := FRows-1;
{Repeatedly take top partition from stack}
repeat
{Pop the stack}
L := LStack[StackP];
R := RStack[StackP];
Dec(StackP);
{Sort current partition}
repeat
{Load the pivot element}
Get((L+R) div 2, KeyCol, PivEl^);
PL := L;
PR := R;
{Swap items in sort order around the pivot index}
repeat
Get(PL, KeyCol, CurEl^);
while Compare(CurEl^, PivEl^) < 0 do begin
Inc(PL);
Get(PL, KeyCol, CurEl^);
end;
Get(PR, KeyCol, CurEl^);
while Compare(PivEl^, CurEl^) < 0 do begin
Dec(PR);
Get(PR, KeyCol, CurEl^);
end;
if PL <= PR then begin
if PL <> PR then
{Swap the two elements}
ExchangeRows(PL, PR);
Inc(PL); {assume we'll never sort 2 billion elements}
Dec(PR);
end;
until PL > PR;
{Decide which partition to sort next}
if (PR-L) < (R-PL) then begin
{Right partition is bigger}
if PL < R then begin
{Stack the request for sorting right partition}
Inc(StackP);
LStack[StackP] := PL;
RStack[StackP] := R;
end;
{Continue sorting left partition}
R := PR;
end else begin
{Left partition is bigger}
if L < PR then begin
{Stack the request for sorting left partition}
Inc(StackP);
LStack[StackP] := L;
RStack[StackP] := PR;
end;
{Continue sorting right partition}
L := PL;
end;
until L >= R;
until StackP < 0;
FreeMem(PivEl, FElSize);
finally
FreeMem(CurEl, FElSize);
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.LoadFromStream(S : TStream);
var
Data : pointer;
Reader : TReader;
NumRows : Integer;
NumCols : Integer;
ElementSize : cardinal;
R, C : Integer;
TotSize : Integer;
StreamedClass : TPersistentClass;
StreamedClassName : string;
Value : TValueType;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Clear;
Reader := TReader.Create(S, 1024);
try
with Reader do
begin
StreamedClassName := ReadString;
StreamedClass := GetClass(StreamedClassName);
if (StreamedClass = nil) then
RaiseContainerErrorFmt(stscUnknownClass, [StreamedClassName]);
if (not IsOrInheritsFrom(StreamedClass, Self.ClassType)) or
(not IsOrInheritsFrom(TStLMatrix, StreamedClass)) then
RaiseContainerError(stscWrongClass);
NumRows := ReadInteger;
NumCols := ReadInteger;
ElementSize := ReadInteger;
if (NumRows <> Integer(Rows)) or (NumCols <> Integer(Cols)) or
(Integer(ElementSize) <> FElSize) then
begin
HugeFreeMem(lmData, FCount*FElSize);
FElSize := ElementSize;
FRows := NumRows;
FCols := NumCols;
FCount := Integer(NumRows)*NumCols;
lmRowSize := Integer(NumCols)*Integer(ElementSize);
GetMem(lmData, FCount*Integer(ElementSize));
Clear;
end;
ElementsStorable := ReadBoolean;
if ElementsStorable then
begin
Read(Value, sizeof(Value)); {s/b vaBinary}
Read(TotSize, sizeof(Integer));
GetMem(Data, FElSize);
try
for R := 0 to pred(FRows) do
for C := 0 to pred(FCols) do
begin
Read(Data^, FElSize);
Put(R, C, Data^);
end;
finally
FreeMem(Data, FElSize);
end;
end
else
begin
ReadListBegin;
for R := 0 to pred(FRows) do
for C := 0 to pred(FCols) do begin
Data := DoLoadData(Reader);
Put(R, C, Data^);
end;
ReadListEnd;
end;
end;
finally
Reader.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
procedure TStLMatrix.StoreToStream(S : TStream);
var
Writer : TWriter;
R, C : integer;
Data : pointer;
TotSize: Integer;
Value : TValueType;
begin
{$IFDEF ThreadSafe}
EnterCS;
try
{$ENDIF}
Writer := TWriter.Create(S, 1024);
try
GetMem(Data, FElSize);
try
with Writer do
begin
WriteString(Self.ClassName);
WriteInteger(FRows);
WriteInteger(FCols);
WriteInteger(FElSize);
WriteBoolean(FElStorable);
if ElementsStorable then
begin
Value := vaBinary;
Write(Value, sizeof(Value));
TotSize := FCount * FElSize;
Write(TotSize, sizeof(Integer));
for R := 0 to pred(FRows) do
for C := 0 to pred(FCols) do
begin
Get(R, C, Data^);
Write(Data^, FElSize);
end;
end
else
begin
WriteListBegin;
for R := 0 to pred(FRows) do
for C := 0 to pred(FCols) do
begin
Get(R, C, Data^);
DoStoreData(Writer, Data);
end;
WriteListEnd;
end;
end;
finally
FreeMem(Data, FElSize);
end;
finally
Writer.Free;
end;
{$IFDEF ThreadSafe}
finally
LeaveCS;
end;
{$ENDIF}
end;
end.
|
// the actual code formatter expert, called either from GX_Formatter or GX_eCodeFormatter
// Original Author: Thomas Mueller (http://www.dummzeuch.de)
// Contributors:
// * Ulrich Gerhardt - 2007-08-11: added determining the settings via an external .ini file
// * Ulrich Gerhardt - 2009-09-06: support for stand alone formatter
unit GX_CodeFormatterExpert;
{$I GX_CondDefine.inc}
interface
uses
Classes,
SysUtils,
GX_GenericUtils,
GX_ConfigurationInfo,
GX_CodeFormatterEngine;
type
TCodeFormatterExpert = class
private
FEngine: TCodeFormatterEngine;
function GetSettingsName(const AFileName: string; FullText: TGXUnicodeStringList): string;
protected
public
constructor Create;
destructor Destroy; override;
procedure Configure;
procedure Execute;
procedure InternalLoadSettings(Settings: TExpertSettings);
procedure InternalSaveSettings(Settings: TExpertSettings);
function FormatFile(const _FileName: string): Boolean;
procedure AddToCapitalization(const _Identifier: TGXUnicodeString);
end;
implementation
uses
IniFiles,
ToolsAPI,
GX_OtaUtils,
GX_DbugIntf,
GX_CodeFormatterGXConfigWrapper,
GX_CodeFormatterTypes,
GX_CodeFormatterConfig,
GX_CodeFormatterBookmarks,
GX_CodeFormatterBreakpoints,
GX_CodeFormatterDefaultSettings,
GX_CodeFormatterConfigHandler,
GX_CodeFormatterSettings,
GX_MessageBox;
procedure XSendDebug(const Msg: string);
begin //FI:W519
{$IFOPT D+}SendDebug('GXFormatter: ' + Msg);
{$ENDIF}
end;
{ TCodeFormatterExpert }
procedure TCodeFormatterExpert.AddToCapitalization(const _Identifier: TGXUnicodeString);
var
Idx: Integer;
sl: TStringList;
begin
sl := FEngine.Settings.CapNames;
if sl.Find(_Identifier, Idx) then
sl.Delete(Idx);
sl.Add(_Identifier);
end;
procedure TCodeFormatterExpert.Configure;
begin
TfmCodeFormatterConfig.Execute(FEngine.Settings);
end;
constructor TCodeFormatterExpert.Create;
var
Settings: TCodeFormatterEngineSettings;
begin
inherited Create;
Settings := BorlandDefaults;
FEngine := TCodeFormatterEngine.Create;
FEngine.Settings.Settings := Settings;
end;
destructor TCodeFormatterExpert.Destroy;
begin
FreeAndNil(FEngine);
inherited;
end;
function FileNameMatches(const FileName, Pattern: string): Boolean;
var
sr: TSearchRec;
begin
Result := False;
if FindFirst(Pattern, 0, sr) = 0 then begin
repeat
if SameText(FileName, sr.Name) then begin
Result := True;
Break;
end;
until FindNext(sr) <> 0;
FindClose(sr);
end;
end;
function TCodeFormatterExpert.GetSettingsName(const AFileName: string; FullText: TGXUnicodeStringList): string;
function GetFromConfigFile: string;
var
ConfigFileName, ConfiguredFileName, Path: string;
IniFile: TIniFile;
ConfiguredFileNames: TStringList;
i: Integer;
begin
Result := '';
Path := AddSlash(ExtractFilePath(ExpandFileName(AFileName)));
ConfigFileName := Path + 'GXFormatter.ini'; // Do not localize.
IniFile := TIniFile.Create(ConfigFileName);
try
ConfiguredFileNames := TStringList.Create;
try
// Read section manually to preserve order:
IniFile.ReadSection('FileSettings', ConfiguredFileNames);
for i := 0 to Pred(ConfiguredFileNames.Count) do begin
ConfiguredFileName := ConfiguredFileNames[i];
if FileNameMatches(ExtractFileName(AFileName), Path + ConfiguredFileName) then begin
Result := IniFile.ReadString('FileSettings', ConfiguredFileName, '');
XSendDebug(Format('Settings "%s" from rule %s in %s', [Result, ConfiguredFileName, ConfigFileName]));
Break;
end;
end;
finally
FreeAndNil(ConfiguredFileNames);
end;
finally
FreeAndNil(IniFile);
end;
end;
function GetFromSource: string;
const
cConfigDirective = '{GXFormatter.config='; // Do not localize.
var
FirstLine: string;
begin
FirstLine := Trim(FullText[0]);
if SameText(Copy(FirstLine, 1, Length(cConfigDirective)), cConfigDirective) and
(FirstLine[Length(FirstLine)] = '}') then begin
Result := Trim(Copy(FirstLine, Length(cConfigDirective) + 1, Length(FirstLine) - Length(cConfigDirective) - 1));
XSendDebug(Format('Settings "%s" from in-source directive', [Result]));
end else
Result := '';
end;
function GetSettingNameFor(_Precedence: TConfigPrecedenceEnum; out _Name: string): Boolean;
begin
case _Precedence of
cpDirective: begin
_Name := GetFromSource;
Result := _Name <> '';
end;
cpIniFile: begin
_Name := GetFromConfigFile;
Result := _Name <> '';
end;
cpMyConfig: begin
_Name := '';
Result := True;
end else
Result := False;
end;
end;
var
i: Integer;
begin
for i := Low(TOneToThree) to High(TOneToThree) do
if GetSettingNameFor(FEngine.Settings.ConfigPrecedence[i], Result) then
Exit;
Result := '';
end;
type
TCodeFormatterDone = class(TGxMsgBoxAdaptor)
protected
function GetMessage: string; override;
end;
{ TCodeFormatterDone }
function TCodeFormatterDone.GetMessage: string;
resourcestring
str_FileHasBeenFormatted = 'The file has been reformatted.';
begin
Result := str_FileHasBeenFormatted;
end;
procedure TCodeFormatterExpert.Execute;
resourcestring
str_NoEditor = 'No source editor';
str_UnsupportedFileTypeS = 'Unsupported file type: %s';
str_UnableToGetContentsS = 'Unable to get contents of %s';
const
FORMATTED_BLOCK_START = '****formatted block start****';
FORMATTED_BLOCK_END = '****formatted block end****';
var
SourceEditor: IOTASourceEditor;
FileName: string;
FullTextStr: TGXUnicodeString;
FullText: TGXUnicodeStringList;
Bookmarks: TBookmarkHandler;
Breakpoints: TBreakpointHandler;
i: Integer;
TempSettings: TCodeFormatterSettings;
OrigSettings: TCodeFormatterEngineSettings;
SettingsName: string;
BlockStart: TOTAEditPos;
BlockEnd: TOTAEditPos;
SelStart: Integer;
SelLength: Integer;
FormatSelection: Boolean;
Position: Integer;
FormattedBlockStart: string;
FormattedBlockEnd: string;
begin
if not GxOtaTryGetCurrentSourceEditor(SourceEditor) then
raise ECodeFormatter.Create(str_NoEditor);
FileName := SourceEditor.FileName;
if not (IsPascalSourceFile(FileName) or IsDelphiPackage(FileName) or FileMatchesExtension(FileName, '.tpl')) then
raise ECodeFormatter.CreateFmt(str_UnsupportedFileTypeS, [ExtractFileName(FileName)]);
XSendDebug(Format('Formatting requested for "%s"', [FileName]));
TempSettings := nil;
FullText := TGXUnicodeStringList.Create;
try
if not GxOtaGetActiveEditorTextAsUnicodeString(FullTextStr, False) then
raise ECodeFormatter.CreateFmt(str_UnableToGetContentsS, [FileName]);
if FullTextStr = '' then
Exit;
FullText.Text := FullTextStr;
Breakpoints := nil;
Bookmarks := TBookmarkHandler.Create;
try
Breakpoints := TBreakpointHandler.Create;
Breakpoints.SaveItems;
Bookmarks.SaveItems;
SettingsName := Trim(GetSettingsName(FileName, FullText));
if SettingsName <> '-' then begin
if SettingsName <> '' then begin
XSendDebug(Format('Use settings "%s"', [SettingsName]));
TempSettings := TCodeFormatterSettings.Create;
if TCodeFormatterConfigHandler.GetDefaultConfig(SettingsName, TempSettings) then begin
OrigSettings := FEngine.Settings.Settings;
FEngine.Settings.Settings := TempSettings.Settings;
end else
FreeAndNil(TempSettings);
end else
XSendDebug('Use default settings');
FormatSelection := False;
if GxOtaGetSelection(GxOtaGetTopMostEditView(SourceEditor), BlockStart, BlockEnd, SelStart, SelLength) then begin
FormatSelection := (SelLength > 0) and (BlockStart.Line < BlockEnd.Line);
if FormatSelection then begin
FormattedBlockStart := FORMATTED_BLOCK_START;
FormattedBlockEnd := FORMATTED_BLOCK_END;
while Pos(FormattedBlockStart, FullTextStr) <> 0 do
FormattedBlockStart := '*' + FormattedBlockStart + '*';
while Pos(FormattedBlockEnd, FullTextStr) <> 0 do
FormattedBlockEnd := '*' + FormattedBlockEnd + '*';
FormattedBlockStart := '{' + FormattedBlockStart + '}';
FormattedBlockEnd := '{' + FormattedBlockEnd + '}';
BlockStart.Col := 1;
if BlockEnd.Col > 1 then begin
BlockEnd.Col := 1;
BlockEnd.Line := BlockEnd.Line + 1;
end;
Assert(BlockEnd.Line > 0, 'Blockend.Line <= 0');
Assert(BlockStart.Line > 0, 'BlockStart.Line <= 0');
FullText.Insert(BlockEnd.Line - 1, FormattedBlockEnd);
FullText.Insert(BlockStart.Line - 1, FormattedBlockStart);
end;
end;
FullTextStr := ''; // might save some memory
if FEngine.Execute(FullText) then begin
if FormatSelection then begin
FullTextStr := FullText.Text;
Position := Pos(FormattedBlockEnd, FullTextStr);
FullTextStr := Copy(FullTextStr, 1, Position - 1);
Position := Pos(FormattedBlockStart, FullTextStr);
FullTextStr := Copy(FullTextStr, Position + Length(FormattedBlockStart), MaxInt);
if Copy(FullTextStr, 1, 2) = CRLF then
FullTextStr := Copy(FullTextStr, 3, MaxInt);
GxOtaSelectBlock(SourceEditor, BlockStart, BlockEnd);
GxOtaReplaceSelection(SourceEditor, 0, FullTextStr);
end else
GxOtaReplaceEditorTextWithUnicodeString(SourceEditor, FullText.Text);
Breakpoints.RestoreItems;
Bookmarks.RestoreItems;
for i := 0 to SourceEditor.EditViewCount - 1 do
SourceEditor.EditViews[i].Paint;
ShowGxMessageBox(TCodeFormatterDone);
end;
end else
XSendDebug('Ignoring request, no settings name available');
finally
FreeAndNil(Breakpoints);
FreeAndNil(Bookmarks);
end;
finally
FreeAndNil(FullText);
if Assigned(TempSettings) then begin
FreeAndNil(TempSettings);
FEngine.Settings.Settings := OrigSettings;
end;
end;
end;
procedure TCodeFormatterExpert.InternalLoadSettings(Settings: TExpertSettings);
var
Reader: IConfigReader;
begin
Reader := TGxConfigWrapper.Create(Settings);
TCodeFormatterConfigHandler.ReadSettings(Reader, FEngine.Settings);
end;
procedure TCodeFormatterExpert.InternalSaveSettings(Settings: TExpertSettings);
var
Writer: IConfigWriter;
begin
Writer := TGxConfigWrapper.Create(Settings);
TCodeFormatterConfigHandler.WriteSettings(Writer, FEngine.Settings);
end;
function TCodeFormatterExpert.FormatFile(const _FileName: string): Boolean;
resourcestring
str_UnsupportedFileTypeS = 'Unsupported file type: %s';
var
FullText: TGXUnicodeStringList;
TempSettings: TCodeFormatterSettings;
OrigSettings: TCodeFormatterEngineSettings;
SettingsName: string;
begin
Result := False;
if not (IsPascalSourceFile(_FileName) or IsDelphiPackage(_FileName) or FileMatchesExtension(_FileName, '.tpl')) then
raise ECodeFormatter.CreateFmt(str_UnsupportedFileTypeS, [ExtractFileName(_FileName)]);
XSendDebug(Format('Formatting requested for "%s"', [_FileName]));
TempSettings := nil;
FullText := TGXUnicodeStringList.Create;
try
FullText.LoadFromFile(_FileName);
SettingsName := Trim(GetSettingsName(_FileName, FullText));
if SettingsName <> '-' then begin
if SettingsName <> '' then begin
XSendDebug(Format('Use settings "%s"', [SettingsName]));
TempSettings := TCodeFormatterSettings.Create;
if TCodeFormatterConfigHandler.GetDefaultConfig(SettingsName, TempSettings) then begin
OrigSettings := FEngine.Settings.Settings;
FEngine.Settings.Settings := TempSettings.Settings;
end else
FreeAndNil(TempSettings);
end else
XSendDebug('Use default settings');
Result := FEngine.Execute(FullText);
if Result then begin
XSendDebug('Saving changed file');
// add an empty line to be compatible with running in the IDE
FullText.Add('');
FullText.SaveToFile(_FileName);
ShowGxMessageBox(TCodeFormatterDone);
end else begin
XSendDebug('Nothing changed');
end;
end else
XSendDebug('Ignoring request, no settings name available');
finally
FreeAndNil(FullText);
if Assigned(TempSettings) then begin
FreeAndNil(TempSettings);
FEngine.Settings.Settings := OrigSettings;
end;
end;
end;
end.
|
unit Model.PlanilhaListagemJornal;
interface
uses System.Generics.Collections, System.Classes, System.SysUtils, Forms, Windows, Common.Utils;
type
/// <version>1.0</version>
/// <since>09/2019</since>
/// <author>Celso Mutti</author>
TPlanilhaListagemJornal = class
private
FAgente: String;
FNomeAgente: String;
FEndereco: String;
FNumero: String;
FComplemento: String;
FBairro: String;
FCEP: String;
FProduto: String;
FQuantidade: String;
FCodigo: String;
FNome: String;
FModalidade: String;
FDescricaoModalidade: String;
FReferencia: String;
public
property Agente: String read FAgente write FAgente;
property NomeAgente: String read FNomeAgente write FNomeAgente;
property Endereco: String read FEndereco write FEndereco;
property Numero: String read FNumero write FNumero;
property Complemento: String read FComplemento write FComplemento;
property Bairro: String read FBairro write FBairro;
property CEP: String read FCEP write FCEP;
property Produto: String read FProduto write FProduto;
property Quantidade: String read FQuantidade write FQuantidade;
property Codigo: String read FCodigo write FCodigo;
property Nome: String read FNome write FNome;
property Modalidade: String read FModalidade write FModalidade;
property DescricaoModalidade: String read FDescricaoModalidade write FDescricaoModalidade;
property Referencia: String read FReferencia write FReferencia;
function GetPlanilha(FFile: String): TObjectList<TPlanilhaListagemJornal>;
end;
implementation
function TPlanilhaListagemJornal.GetPlanilha(FFile: String): TObjectList<TPlanilhaListagemJornal>;
var
ArquivoCSV: TextFile;
sLinha: String;
sDetalhe: TStringList;
lista : TObjectList<TPlanilhaListagemJornal>;
i : Integer;
begin
lista := TObjectList<TPlanilhaListagemJornal>.Create;
if not FileExists(FFile) then
begin
TUtils.Dialog('Atenção', 'Arquivo ' + FFile + ' não foi encontrado!', 0);
Exit;
end;
AssignFile(ArquivoCSV, FFile);
if FFile.IsEmpty then Exit;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha;
if Pos('DETALHADA',sLinha) = 0 then
begin
TUtils.Dialog('Atenção', 'Arquivo informado não foi identificado como a Planilha de Assinaturas do Jornal!', 0);
Exit;
end;
i := 0;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
if TUtils.ENumero(sDetalhe[0]) then
begin
lista.Add(TPlanilhaListagemJornal.Create);
i := lista.Count - 1;
lista[i].Agente := sDetalhe[0];
lista[i].NomeAgente := sDetalhe[1];
lista[i].Endereco := sDetalhe[2];
lista[i].Numero := sDetalhe[3];
lista[i].Complemento := sDetalhe[4];
lista[i].Bairro := sDetalhe[5];
lista[i].CEP := sDetalhe[6];
lista[i].Produto := sDetalhe[7];
lista[i].Quantidade := sDetalhe[8];
lista[i].Codigo := sDetalhe[9];
lista[i].Nome := sDetalhe[10];
lista[i].Modalidade := sDetalhe[11];
lista[i].DescricaoModalidade := sDetalhe[12];
lista[i].Referencia := sDetalhe[13];
end;
end;
Result := lista;
CloseFile(ArquivoCSV);
end;
end.
|
(*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* 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 Initial Developer of this code is John Hansen.
* Portions created by John Hansen are Copyright (C) 2009 John Hansen.
* All Rights Reserved.
*
*)
unit uLocalizedStrings;
interface
// BricxCC unit
resourcestring
S_RESET = 'reload defaults from Default directory';
S_COM = 'use the named port for this instance (COM1..COMnnn, usb)';
S_RCX = 'use brick type N for this instance';
S_AUTO = 'auto connect using default or specified port and type';
S_NONE = 'do not connect to brick at startup';
S_POS = 'position windows using values in INI file';
S_HELP = 'display this message before starting up';
S_NT = 'use compiler timeout specified for this instance (in seconds)';
S_DEBUG = 'display debug message when launching compiler';
S_USERPATH = 'set the path for user configuration files';
// MainUnit unit
resourcestring
sNoRCX = 'No connection to the programmable brick. Certain options will be unavailable.';
sNoPort = 'no port';
sNoRobot = 'no robot';
sHideCodeError = 'Hide Code/Error|Warning Listing';
sShowCodeError = 'Show Code/Error|Warning Listing';
sFirmDwnldFailed = 'Firmware download failed. Put the RCX closer and try again.';
sWrongNum = 'wrong download number';
sWarnCancelFD = 'Firmware download cancelled.';
sBrickCommError = 'Unable to communicate with your brick';
sRecording = 'Recording';
sEnterData = 'Enter data';
sEnterRunParams = 'Enter run parameters';
SFilterAllFiles = 'All files|*.*|';
sProgramLocked = 'Program is locked.';
sClearMemConfirm = 'Are you sure you want to clear the brick''s memory?';
sBreakAll = 'Break all';
sContinue = 'Continue';
sFileMenu = '&File';
sEditMenu = '&Edit';
sCopySpecialMenu = 'Copy &Special';
sSearchMenu = '&Search';
sViewMenu = '&View';
sProjectManager = '&Project Manager';
sCodeExplorer = 'Code E&xplorer';
sStatusBar = '&Status bar';
sTemplates = 'T&emplates';
sHideErrors = '&Hide Errors';
sToolWindows = '&Tool Windows';
sMacroManager = '&Macro Manager';
spbForthConsole = 'pbForth Console';
sWindowList = '&Window List';
sToolbarsMenu = 'Tool&bars';
sCompileMenu = '&Compile';
sProgramNumberMenu = '&Program Number';
sProgram = 'Program';
sToolsMenu = '&Tools';
sbrickOSMenu = '&brickOS';
sSetLNPAddress = '&Set LNP Address...';
sLNPAddress = 'LNP &Address';
sAddress = 'Address';
sLNPPort = 'LNP &Port';
sPort = 'Port';
sWindowMenu = '&Window';
sTileHorizontal = 'Tile &Horizontal';
sTileVertical = 'Tile &Vertical';
sCascade = '&Cascade';
sArrangeIcons = '&Arrange Icons';
sPositionsMenu = '&Positions';
sSave = 'Save';
sLoad = 'Load';
sHelpMenu = '&Help';
sIndex = '&Index';
sNQCGuide = '&NQC Guide';
sHowToUseHelp = '&How to Use Help';
sWebPage = '&Web page';
sNextWindow = '&Next window';
sGuidePDFs = 'Guide PDFs';
sTutorialPDFs = 'Tutorial PDFs';
// Editor unit
resourcestring
S_Overwrite = 'Overwrite';
S_Insert = 'Insert';
S_ReadOnly = 'ReadOnly';
S_FileChanged = 'File %s has been modified. Save changes?';
S_Modified = 'Modified';
sErrors = 'Errors';
sFullErrors = 'Full errors in';
sCodeListing = 'Code listing of';
sCompileSuccess = 'Program compiled successfully.';
sCompileErrors = 'Errors found on program compile.';
sCompileDownloadSuccess = 'Program compiled and downloaded successfully.';
sCompileDownloadErrors = 'Errors found on program compile and download.';
sUntitled = 'Untitled';
sFindDeclaration = 'Find Dec&laration';
sClosePage = '&Close Page';
sOpenFileAtCursor = 'Open &File at Cursor';
sTopicSearch = 'Topic &Search';
sUndo = 'U&ndo';
sRedo = '&Redo';
sCut = 'C&ut';
sCopy = 'Co&py';
sPaste = 'P&aste';
sDelete = 'D&elete';
sSelectAll = 'Selec&t All';
sToggleBookmarksMenu = '&Toggle Bookmarks';
sBookmark = 'Bookmark';
sGotoBookmarksMenu = '&Goto Bookmarks';
sViewExplorer = 'View E&xplorer';
sToggleBreakpoint = 'Toggle Breakpoint';
// CodeUnit unit
resourcestring
sFind = '&Find';
sFindNext = 'Find &Next';
sFindPrevious = 'Find &Previous';
sGotoLine = '&Goto Line';
sStayOnTop = 'Stay on &top';
// GotoLine unit
resourcestring
sGotoError = 'Line must be between 1 and %d.';
// GX_ProcedureList
resourcestring
SAllString = '<All>';
SNoneString = '<None>';
SInvalidIndex = 'Invalid index number';
SParseStatistics = 'Procedures processed in %g seconds';
// SearchRCX unit
resourcestring
S_CANNOT_FIND_RCX = 'Cannot find brick. Switch it on or move it closer and press OK.';
S_SEARCHING_NXT = 'Searching for NXTs';
S_SEARCHING_BRICK = 'Searching for a brick';
// Translate unit
resourcestring
S_TRANSLATE = 'Translating an old NQC program into NQC 2.0. ' +
'This might not be completely correct. ' +
'Please check afterwards. Do you want to continue?';
// uCodeExplorer unit
resourcestring
sUnableToParseFile = 'Unable to parse current file';
// uParseCommon unit + others
resourcestring
SImplementationNotFound = 'Implementation section not found (parser error?)';
sUnknown = 'Unknown';
sFunction = 'Function';
sProcedure = 'Procedure';
sConstructor = 'Constructor';
sDestructor = 'Destructor';
sClassFunc = 'Class Func';
sClassProc = 'Class Proc';
sTask = 'Task';
sSubroutine = 'Subroutine';
sMacros = 'Macros';
sFunctions = 'Functions';
sSubroutines = 'Subroutines';
sTasks = 'Tasks';
sProcedures = 'Procedures';
sConstructors = 'Constructors';
sDestructors = 'Destructors';
sExploring = 'Exploring';
// uMacroForm unit
resourcestring
sConfirmDeleteMM = 'Delete selected macro?';
// About unit
resourcestring
sVersion = 'Version';
sBuild = 'Build';
// dlgConfirmReplace
resourcestring
SAskReplaceText = 'Replace this occurence of "%s"?';
// DTestPrintPreview
resourcestring
sPageLabel = ' Page: ';
sPrintCmdHint = 'Print (%0:s)|Print the document on %0:s';
sWholePage = 'Whole page';
sPageWidth = 'Page width';
// Construct unit
resourcestring
sExpandAll = 'Expand All';
sCollapseAll = 'Collapse All';
sDoubleClickToInsert = 'Double Click to Insert';
// ExecProgram unit
resourcestring
sTimeout = 'Program execution timed out. Try increasing the timeout value.';
sAborted = 'Program execution aborted.';
sUnableToExecute = 'Unable to create process:' + #10 + '%s' + #10#10 +
'Make sure %s is in a directory on the system path ' + #10 +
'or in the same directory as the controlling program' + #10 + '(%s).';
// Preferences unit
resourcestring
S_ChangeMacroCaption = 'Changing a Macro';
S_ChangeMacroPrompt = 'Change Macro %s:';
S_ChangeTemplateCaption = 'Changing a Template';
S_ChangeTemplatePrompt = 'Change the Template:';
S_InsertTemplateCaption = 'Inserting a Template';
S_InsertTemplatePrompt = 'Type the template you want to insert:';
S_KeystrokeCaption = 'Keystroke Editor';
S_CodeTemplatesCaption = 'Code Templates';
S_ConfirmAPIDelete = 'Are you sure you want to delete this item?';
// Controller unit
resourcestring
sRaw = 'Raw';
sBoolean = 'Boolean';
sTransCount = 'Trans Count';
sPeriodCount = 'Period Count';
sPercent = 'Percent';
sCelsius = 'Celsius';
sFahrenheit = 'Fahrenheit';
sAngle = 'Angle';
sNone = 'None';
sSwitch = 'Switch';
sTemperature = 'Temperature';
sLight = 'Reflection';
sLightActiv = 'Light Active';
sLightInact = 'Light Inactive';
sSoundDB = 'Sound DB';
sSoundDBA = 'Sound DBA';
sCustom = 'Custom';
sLowspeed = 'Lowspeed';
sLowspeed9v = 'Lowspeed 9V';
sHighspeed = 'Highspeed';
sColorFull = 'Color Full';
sColorRed = 'Color Red';
sColorGreen = 'Color Green';
sColorBlue = 'Color Blue';
sColorNone = 'Color None';
sScoutSourceError = 'Scout only supports variable and constant sources';
sNonSpybotSrcError = 'Only Spybots support sources past Indirect';
// Diagnose unit
resourcestring
sRCXDead = 'Brick is NOT alive';
sRCXAlive = 'Brick is alive';
sVariable = 'Variable ';
sWatch = 'Watch';
sInput1 = 'Input 1';
sInput2 = 'Input 2';
sInput3 = 'Input 3';
sOutputA = 'Output A';
sOutputB = 'Output B';
sOutputC = 'Output C';
sUserSelect = 'User Select';
sExceptions = 'Exceptions';
// EditCodeTemplate unit
resourcestring
sNewTemplate = 'New Code Template';
sEditTemplate = 'Edit Code Template';
// JoystickUnit unit
resourcestring
sDriveMotor = 'Drive Motor';
sSteerMotor = 'Steer Motor';
sLeftMotor = 'Left Motor';
sRightMotor = 'Right Motor';
// MemoryUnit unit
resourcestring
sDownloadMemMapFailed = 'Memory map download failed!';
sSubroutinePointers = 'Subroutine Pointers';
sTaskPointers = 'Task Pointers';
sSoundPointers = 'Sound Pointers';
sAnimationPointers = 'Animation Pointers';
sDataPointer = 'Data Pointer: ';
sTopOfMemory = 'Top of Memory: ';
sFreeMemLeft = 'Free Memory Left: ';
sTotalUsed = 'Total Memory Used: ';
sDatalogStart = 'Datalog Start Pointer: ';
sDatalogCurrent = 'Datalog Current Pointer: ';
// Transdlg unit
resourcestring
sColMacro = 'Cursor column in active editor';
sRowMacro = 'Cursor row in active editor';
sCurTokenMacro = 'Word at cursor in active editor';
sPathMacro = 'Directory portion of parameter';
sNameMacro = 'File name of parameter';
sNameOnlyMacro = 'File name of parameter without extension';
sExtMacro = 'File extension of parameter';
sEdNameMacro = 'Expanded file name of active editor';
sPromptMacro = 'Prompt for information';
sSaveMacro = 'Save file in active editor';
sSaveAllMacro = 'Save all modified files';
sPortMacro = 'Current port';
sTargetMacro = 'Current target';
// Transfer unit
resourcestring
sConfirm = 'Delete the item entitled %s?';
// uCmdLineUtils unit
resourcestring
UsageErrorMessage = 'Use "%s -help" for more information.';
VersionString = ' version ';
BuiltString = ' built ';
// uEEPROM unit
resourcestring
sEEPROMLoadError = 'Error loading EEPROM data';
sConfirmEEPROMWrite = 'Are you sure you want to write data to the brick?';
// uExplorerOptions unit
resourcestring
sHidden = 'Hidden';
sVisible = 'Visible';
sCollapsed = 'Collapsed';
sExpanded = 'Expanded';
// uMacroLib unit
resourcestring
sMacroLibFormatError = 'Invalid macro library format';
// uNewWatch unit
resourcestring
sWatchError = 'Cannot find the brick anymore';
// uNXTExplorer unit
resourcestring
sConfirmDel = 'Delete all the selected files?';
sConfirmDefrag = 'Defragment the NXT filesystem.'#13#10 +
'This operation attempts to a) upload all files from the NXT ' +
'to your computer, b) erase the NXT flash memory, and c) download ' +
'all the files back to the NXT. It is possible that the defragment ' +
'operation may not complete successfully and files may be lost.'#13#10 +
'Do you want to go ahead with the defragmentation operation?';
sConfirmErase = 'Erase all files on the NXT?';
sLowBattery = 'Battery level is too low to complete this operation';
sDefragError = 'Defragmentation failed!';
sDefragSuccess = 'Defragmentation complete!';
sTooBig = 'File size (%d) of "%s" is too large.';
sDownloadFailed = 'Download failed';
sExit = 'E&xit';
sNXTViewStyleMenu = 'NXT View Style';
sPCViewStyleMenu = 'PC View Style';
sAbout = '&About';
// uNXTImage unit
resourcestring
sBTResetConfirm = 'Are you sure you want to reset Bluetooth to factory defaults?';
sBootSAMBAConfirm = 'Are you sure you want to boot the NXT in SAMBA mode?';
sUtilitiesMenu = 'Utilities';
sSetNXTName = 'Set NXT Name';
sBootSAMBA = 'Boot NXT into SAMBA mode';
sResetBluetooth = 'Reset Bluetooth to factory defaults';
sRefreshRate = '&Refresh Rate';
sScale = 'Sca&le';
sDisplay = '&Display';
sNormal = '&Normal';
sPopup = '&Popup';
sPlayClicks = 'Play Clicks';
// uProjectManager unit
resourcestring
sRemoveConfirm = 'Remove the selected file(s) from the project?';
// uSetLNPAddress unit
resourcestring
sFailedToSetLNPAddr = 'Failed to set LNP address.'#13#10 +
'Check the current address setting.';
sSuccessfulSetLNPAddr = 'LNP Address successfully set to %d.';
// uWav2RsoCvt
resourcestring
sErrRiffWaveFmt = 'Error processing %s: wave file is not RIFF/WAVE format';
sErrPCMFmt = 'Error processing %s: wave files must be in PCM, MS ADPCM, or IMA ADPCM format';
sErr64kLimit = 'Error processing %s: wave file exceeds 64k maximum size';
sSuccess = 'Success: %s';
// common to multiple compilers
resourcestring
sException = 'Exception';
sProgramError = '%d errors during compilation';
sInvalidConstExpr = 'Invalid constant expression';
sUnmatchedCloseParen = 'Unmatched close parenthesis';
sParserError = 'parser error';
// uRPGComp
resourcestring
sNothingAfterEnd = 'Commands are not allowed after EndLoop or EndStop';
sUnknownCommand = 'Unknown RPG command';
sTooManyCommands = 'Too many RPG commands in program';
// uRICComp
resourcestring
sInvalidArgument = 'invalid argument: %d';
sInvalidVarMapIndex = 'invalid varmap index: %d';
sInvalidCommandArgument = 'Invalid command argument';
sSpriteLengthError = 'sprite command must have rows with a length > 0';
sInvalidMapSyntax = 'Invalid map element function syntax';
sInvalidPolygonSyntax = 'Invalid polygon point syntax';
sVarMapCountError = 'varmap command must have at least two map elements';
sPolygonCountError = 'polygon command must have at least three points';
sStringNotBinary = 'String is not a valid binary number: %s';
sInvalidHexLength = 'Invalid length of hex string: %d';
sUnableToFindImage = 'Unable to find image file "%s"';
sEllipseRequires127 = 'The ellipse command requires the enhanced NBC/NXC firmware, v1.27 or greater';
sPolygonRequires127 = 'The polygon command requires the enhanced NBC/NXC firmware, v1.27 or greater';
// uPreprocess unit
resourcestring
sInvalidPreprocDirective = 'Invalid preprocessor directive';
sImportRICNotFound = 'Unable to find RIC import file: "%s"';
sImportRICMissingQuotes = '#importric directive requires a filename (e.g., #importric "foo.ric")';
sImportRICInvalid = '#importric directive filename must end in ".ric"';
sDownloadNotFound = 'Unable to find download file: "%s"';
sDownloadMissingQuotes = '#download directive requires a filename (e.g., #download "foo.ric")';
sIncludeNotFound = 'Unable to find include file: "%s"';
sIncludeMissingQuotes = '#include directive requires a filename (e.g., #include "foo.h")';
sMacroMismatch = 'Preprocessor macro function does not match instance (%s)';
sUnmatchedDirective = 'Unmatched preprocessor directive';
sInvalidPreprocExpression = 'Invalid preprocessor expression : %s';
sInvalidCharConstant = 'Invalid char constant';
sMaxRecursionDepthError = 'Max recursion depth (%d) exceeded';
sIncludePath = 'Include path';
sSearchingForFile = 'Searching for file';
sFoundFile = 'Found file';
sProcessingDownload = 'Processing download';
sProcessingImport = 'Processing import';
sProcessingInclude = 'Processing include';
// uNXTClasses
resourcestring
sInvalidStatement = 'Unknown or invalid statement';
sInvalidLine = 'Line type "%s" is not valid while in the "%s" state';
sInvalidNumArgs = 'Invalid number of arguments: %d expected, %d found';
sInvalidNumArgsVar = 'Invalid number of arguments: at least %d expected, %d found';
sInvalidNumArgsOdd = 'Invalid number of arguments: argument count must be odd';
sInvalidCompareCode = 'Invalid comparison code: %s';
sBadConstExpression = 'Invalid constant expression: %s';
sConstOutOfRange = '%d is outside the valid range [%d,%d]';
sInvalidOpcode = 'Invalid opcode: %s';
sDuplicateLabel = 'Duplicate label (%s)';
sDuplicateDSEntry = 'Duplicate variable declaration (%s)';
sDuplicateType = 'Duplicate type declaration (%s)';
sInvalidVarDecl = 'Invalid variable declaration (%s)';
sInvalidVarArg = 'Invalid variable argument: %s';
sInvalidMutexArg = 'Invalid mutex argument: %s';
sInvalidClusterArg = 'Invalid struct argument: %s';
sInvalidArrayArg = 'Invalid array argument: %s';
sInvalidScalarArg = 'Invalid scalar argument: %s';
sInvalidStringArg = 'Invalid string argument: %s';
sInvalidLabelArg = 'Invalid label argument: %s';
sInvalidClumpArg = 'Invalid thread argument: %s';
sReturnNotInSub = 'The return opcode can only be used within a subroutine';
sNoReturnAtEndOfSub = 'The last operation in a subroutine must be a return';
sCompCheckFailed = 'compchk failed. %d is not %s %d.';
sCompCheckTypFailed = 'compchktype failed. %s is not %s.';
sInvalidCompCheck = 'invalid compchk operation';
sInvalidCompCheckTyp = 'invalid compchktype operation';
sUnsafeDivision = 'Dividing a signed number by an unsigned number is unsafe';
sUnusedVar = 'Unused variable: %s. Enable optimization with -Z1 to remove.';
sInvalidSetStatement = 'The set opcode cannot be used with float variables';
sMainUndefined = 'The main thread is not explicitly named';
sNoNegShifts = 'Negative shifts are not supported';
sNBCFinalizeDepends = 'Finalizing dependencies';
sNBCOptimizeLevel = 'Optimizing at level %d';
sNBCBuildRefs = 'Build codespace references';
sNBCOptMutexes = 'Optimize mutexes';
sNBCCompactCode = 'Compact the codespace';
sNBCRemoveLabels = 'Remove unused labels';
sNBCRunCodeOpts = 'Run codespace optimizations';
sNBCCompactAfterOpt = 'Compact the codespace after optimizations';
sNBCCompactData = 'Compact the dataspace';
sNBCSortDataspace = 'Sort the dataspace';
sNBCGenerateRawDS = 'Generate raw dataspace data';
sNBCFillCodeArrays = 'Fill clump and codespace arrays';
sNBCUpdateHeader = 'Update executable file header';
sNBCWriteHeader = 'Write file header to executable';
sNBCWriteDataspace = 'Write dataspace to executable';
sNBCWriteClumpData = 'Write clump data to executable';
sNBCWriteCodespace = 'Write code to executable';
sNBCWriteOptSource = 'Write optimized source to compiler output';
sNBCFinished = 'Finished';
sNBCCompFinished = 'Finished compiling NBC source code';
sNBCLoadSystemFiles = 'Loading NBC system files';
sNBCPreprocess = 'Running NBC Preprocessor';
sNBCCompilingSource = 'Compiling NBC source code';
sNBCOptClump = 'Optimizing clump: %s';
sNBCCompBegin = 'NBC compilation begins';
// uNXCComp unit
resourcestring
sTaskName = 'Task name';
sVariableName = 'Variable name';
sStringReturnValue = 'String return value';
sInvalidAssignment = 'Invalid assignment';
sDatatypesNotCompatible = 'Datatypes are not compatible';
sInlineInvalid = 'The inline keyword may only be used with functions';
sSafeCallInvalid = 'The safecall keyword may only be used with functions';
sBadPrototype = 'Prototypes without parameter names are not supported';
sMainMustBeTask = 'main must be a task';
sUDTNotEqual = 'User-defined types do not match';
sInvalidArrayDeclaration = 'Invalid array declaration';
sInvalidArrayInit = 'Invalid array or struct initialization';
sUnknownUDT = 'Unknown user-defined type';
sReturnInvalid = 'return is invalid outside a subroutine';
sInvalidBreakContinue = '%s is invalid outside of a loop';
sProtoAlreadyDefined = 'Prototype already defined - "begin"';
sNotValidForPrototype = 'Not valid for a prototype';
sMissingDataType = 'Missing Data Type';
sDataTypesAlreadyDefined = 'Data types already defined in prototype';
sParameterList = 'Parameter List';
sUnexpectedChar = 'Unexpected character encountered';
sValidProgBlock = 'Valid Program Block Statement';
sConstInitialization = 'constant initialization';
sInitNotAllowed = 'Initialization is not allowed for mutex variables';
sInvalidStringInit = 'Invalid string initialization';
sConstLocArrNotSupported = 'Constant local arrays are not supported';
sUnknownAPICommand = 'Unknown API command';
sDefaultInvalid = 'default is invalid outside a switch statement';
sCaseInvalid = 'case is invalid outside a switch statement';
sCaseDuplicateNotAllowed = 'duplicate case labels are not allowed';
sInvalidUseOfTaskName = 'Invalid use of task name';
sInvalidArrayExpr = 'Invalid array expression';
sRecursiveInlineError = 'Calling an inline function from an inline function is not supported';
sNestedCallsError = 'Nested calls to the same function are not supported.';
sRecursiveNotAllowed = 'Recursive function calls are not supported';
sExpNotSupported = 'Expressions are not supported for struct, array, or reference parameters';
sEnhancedFirmwareReqd = 'Enhanced firmware is required for this operation';
sSymbolTableFull = 'Symbol Table Full';
sInvalidArrayDim = 'Invalid array dimensions - must be from 1 to 4';
sAssignTaskError = 'Can not assign to a task or subroutine';
sArgMustBeTask = 'Argument must be a task';
sInvalidReturnType = 'Invalid return type';
sInvalidStringAssign = 'Invalid string assignment';
sInvalidArrayIndex = 'Invalid array index';
sFloatNotSupported = 'float types are not supported at the specified firmware version';
sNoUnsignedFloat = 'float types cannot be declared as unsigned';
sMainTaskNotFound = 'No task named "main" exists';
sNXCGenerateTrailer = 'NXC generate trailer';
sNXCProcessGlobals = 'NXC processing global declarations';
sNXCProcedure = 'NXC processing procedure block: %s';
sNXCFunction = 'NXC processing function block: %s';
sNXCCompBegin = 'NXC compilation begins';
sNXCPreprocess = 'Running NXC preprocessor';
sNXCInitProgram = 'NXC init program';
sNXCParseProg = 'NXC parse program code';
sNXCCodeGenComplete = 'NXC code generation finished';
sConstNotInline = 'Only inline functions can correctly use non-reference constant parameters';
sInvalidFuncDecl = 'Declaration syntax error';
sDefaultParamError = 'Invalid parameter syntax with default values';
sInvalidFunctionCall = 'Invalid function call';
sInvalidEnumDecl = 'Invalid enum declaration';
sUnknownDatatype = 'Unknown datatype';
sCompileTargets = 'Compiling for firmware version %d, NBC/NXC enhanced = %s';
sCurrentFile = 'Current file = "%s"';
sConstOrConstExpr = 'constant or constant expression';
sNotAnAPIFunc = '%s is not an API function';
sNotAnAPIStrFunc = '%s is not an API string function';
// uNBCCommon unit
resourcestring
sExpectedString = '%s expected';
sDataType = 'Data type';
sIdentifier = 'Identifier';
sDirective = 'Preprocessor directive';
sNumber = 'Number';
sHexNumber = 'Hex number';
sCharLiteral = 'Character literal';
sStringLiteral = 'String literal';
sStringType = 'string constant or variable of type string';
sByteArrayType = 'byte array type';
sStringVarType = 'string type';
sStructType = 'struct type';
sMutexType = 'mutex type';
sIntegerType = 'integer type';
sNumericType = 'numeric type';
sMathFactor = 'Math Factor';
sArrayOfString = 'array of string';
sArrayDatatype = 'array data type';
sUndefinedIdentifier = 'Undefined Identifier %s';
sDuplicateIdentifier = 'Duplicate Identifier %s';
sTooManyArgs = 'Too many arguments';
sTooFewArgs = 'Too few arguments';
sTooFewParams = 'Too few parameters';
sMaxParamCountExceeded = 'Max param count exceeded';
sConstNotAllowed = 'Constant not allowed on LHS of assignment';
sConstRequired = 'A constant is required in this context';
sFuncParamDeclMismatch = 'Function parameter declaration mismatch';
// nbc.dpr
resourcestring
UsageSyntax = 'Syntax: %s [options] filename [options]';
UsagePort = ' -S=<portname>: specify port name (usb), brick resource name, or alias';
UsageDownload = ' -d: download program';
UsageRunProg = ' -r: download and run program';
UsageBinary = ' -b: treat input file as a binary file (don''t compile it)';
UsageQuiet = ' -q: quiet';
UsageNoSystem = ' -n: prevent the system file from being included';
UsageDefine = ' -D=<sym>[=<value>]: define macro <sym>';
UsageDecompile = ' -x: decompile program';
UsageOptimize = ' -Z[1|2]: turn on compiler optimizations';
UsageMaxErrors = ' -ER=n: set maximum errors before aborting (0 == no limit)';
UsageMaxDepth = ' -PD=n: set max preprocessor recursion depth (default == 10)';
UsageOutput = ' -O=<outfile> : specify output file';
UsageErrors = ' -E=<filename> : write compiler messages to <filename>';
UsageIncludes = ' -I=<path>: search <path> for include files';
UsageNBCOutput = ' -nbc=<filename> : save NXC intermediate NBC code to <filename>';
UsageListing = ' -L=<filename> : generate code listing to <filename>';
UsageSymbols = ' -Y=<filename> : generate symbol table to <filename>';
UsageWarnings = ' -w[-|+] : warnings off or on (default is on)';
UsageStatusMsg = ' -sm[-|+] : status messages off or on (default is on)';
UsageEnhanced = ' -EF : enhanced firmware';
UsageSafecall = ' -safecall: NXC will wrap all function calls in Acquire/Release';
UsageAPI = ' -api: dump the API to stdout';
UsageFirmVer = ' -v=n: set the targeted firmware version (default == 128, NXT 1.1 == 105)';
UsageHelp = ' -help : display command line options';
// uEditorExperts.pas
resourcestring
SNoTokens = 'No tokens found to align on.';
sEECommentName = 'Comment Code';
sEEUncommentName = 'Uncomment Code';
sEEAlignName = 'Align Lines';
sEEPrevIdentName = 'Previous Identifier';
sEENextIdentName = 'Next Identifier';
sEEReverseName = 'Reverse Statement';
sEEGrepSearchName = 'Grep Search';
sEEGrepResultsName = 'Grep Results';
sEECommentHelp = ' This expert comments out a selected block of code. To ' +
'use it, select a block in the Delphi editor and activate this expert. ' + #13#10#13#10 +
' You can configure this expert to use different comment styles.';
sEEUncommentHelp = ' This expert uncomments a selected block of code. To ' +
'use it, select a block in the IDE code editor and activate this expert.' + #13#10 +
' Uncommenting is performed using the comment style that you selected for ' +
'the Comment Code editor expert.';
sEEAlignHelp = ' This expert aligns the text of the selected lines at ' +
'the first occurrence of a chosen token in each line. To use it, select a ' +
'block of code in the code editor and activate this expert. You may find ' +
'this feature useful to align the right hand side of variable, field, or ' +
'constant declarations and other similar lists. ' + #13#10 +
' There are two alignment modes. In the "Align at rightmost token" mode, ' +
'the rightmost token found in the selected text becomes the column position ' +
'the other lines are aligned to. In the "Align at first token" mode, the ' +
'first located token is used to determine the alignment column. In this ' +
'second mode, any line whose token prefix is longer than the position of ' +
'the first token will not be modified. ' + #13#10 +
' You can configure the list of tokens to align on as well as the minimum ' +
'number of space characters that must precede a token that is being aligned.';
sEEPrevIdentHelp = ' This expert detects the identifier under the cursor ' +
'and allows you to quickly jump to the previous occurrence of that ' +
'identifier in the same file.';
sEENextIdentHelp = ' This expert detects the identifier under the ' +
'cursor and allows you to quickly jump to the next occurrence of that ' +
'identifier in the same file.';
sEEReverseHelp = ' This expert reverses all assignment statements in ' +
'a selected block of code. It expects all reversible statements to be ' +
'contained on a single line.';
sEEGrepSearchHelp = 'Start a new grep search.';
sEEGrepResultsHelp = 'Show previous grep search results.';
// nextscreen.dpr
resourcestring
sUnableToConnect = 'Unable to connect to the selected NXT brick.';
// piano.pas
resourcestring
sPianoFilter = 'NQC Files (*.nqc,*.nqh)|*.nqc;*.nqh|' +
'MindScript files (*.rcx2;*.lsc)|*.rcx2;*.lsc|' +
'LASM Files (*.lasm)|*.lasm|' +
'C++ Files (*.c,*.cpp,*.h,*.hpp)|*.c;*.cpp;*.h;*.hpp|' +
'Pascal Files (*.pas,*.dpr,*.dpk,*.inc)|*.pas;*.dpr;*.dpk;*.inc|' +
'Forth Files (*.4th, *.f, *.fr, *.fth)|*.4th;*.f;*.fr;*.fth|' +
'Java Files (*.java)|*.java|' +
'Next Byte Code Files (*.nbc)|*.nbc|' +
'NXC Files (*.nxc)|*.nxc|' +
'NXT Melody Files (*.rmd)|*.rmd|';
// uportsedit.pas
resourcestring
sSaveNXTDatChanges = 'Save changes to nxt.dat file?';
// uNBCInterface.pas
resourcestring
sCannotFindFile = 'Unable to find the specified input file'#13#10'File "%s" ; line 1';
sNXCCompilationFailed = 'NXC compilation failed.';
sNBCCompilationFailed = 'NBC compilation failed.';
sVersionCheckFailed = 'Firmware version check failed.';
// uNXTWatchList
resourcestring
sConfirmDeleteAllWatches = 'Delete all watches?';
sWatchName = 'Watch Name';
sWatchValue = 'Value';
sNotYetImplemented = 'Not yet implemented';
implementation
end.
|
unit VisualClasses;
interface
function GetVisualRootPath : string;
procedure SetCacheRootPath(const aPath : string);
implementation
var
VisualRoot : string = '';
function GetVisualRootPath : string;
begin
if VisualRoot <> ''
then SetVisualRootPath(CacheRegistryData.ReadCacheValue('', 'RootPath'));
end;
procedure SetVisualRootPath(const aPath : string);
begin
if aPath[length(aPath)] = '\'
then VisualRoot := aPath
else VisualRoot := aPath + '\';
end;
end.
|
unit UDMCobEletronica;
interface
uses
SysUtils, Classes, FMTBcd, DB, DBClient, Provider, SqlExpr, DBTables, ACBrBoleto, ACBrBoletoFCFortesFr, ACBrBase,
ACBrUtil, strUtils, Dialogs, dateUtils, Variants;
type
TDMCobEletronica = class(TDataModule)
sdsCobEletronica: TSQLDataSet;
dspCobEletronica: TDataSetProvider;
cdsCobEletronica: TClientDataSet;
dsCobEletronica: TDataSource;
sdsCobEletronicaID: TIntegerField;
sdsCobEletronicaDTGERACAO: TDateField;
sdsCobEletronicaUSUARIO: TStringField;
sdsCobEletronicaHORA: TTimeField;
sdsCobEletronicaQTDTITULOS: TIntegerField;
sdsCobEletronicaVLRTITULOS: TFloatField;
sdsCobEletronicaCODBANCO: TIntegerField;
sdsCobEletronicaCODTIPOCOBRANCA: TIntegerField;
sdsCobEletronicaFILIAL: TIntegerField;
sdsCobEletronicaNOMEARQUIVO: TStringField;
cdsCobEletronicaID: TIntegerField;
cdsCobEletronicaDTGERACAO: TDateField;
cdsCobEletronicaUSUARIO: TStringField;
cdsCobEletronicaHORA: TTimeField;
cdsCobEletronicaQTDTITULOS: TIntegerField;
cdsCobEletronicaVLRTITULOS: TFloatField;
cdsCobEletronicaCODBANCO: TIntegerField;
cdsCobEletronicaCODTIPOCOBRANCA: TIntegerField;
cdsCobEletronicaFILIAL: TIntegerField;
cdsCobEletronicaNOMEARQUIVO: TStringField;
dsCobEletronicaMestre: TDataSource;
sdsCobEletronicaDTINICIAL: TDateField;
sdsCobEletronicaDTFINAL: TDateField;
cdsCobEletronicaDTINICIAL: TDateField;
cdsCobEletronicaDTFINAL: TDateField;
sdsCobEletronica_Nota: TSQLDataSet;
sdsCobEletronica_NotaID: TIntegerField;
sdsCobEletronica_NotaITEM: TIntegerField;
sdsCobEletronica_NotaNUMNOTA: TIntegerField;
sdsCobEletronica_NotaCODCLIENTE: TIntegerField;
sdsCobEletronica_NotaSERIE: TStringField;
sdsCobEletronica_NotaNUMSEQNOTA: TIntegerField;
sdsCobEletronica_NotaVLRTITULO: TFloatField;
sdsCobEletronica_NotaDTVENCIMENTO: TDateField;
sdsCobEletronica_NotaPROCESSO: TStringField;
sdsCobEletronica_NotaPARCELA: TIntegerField;
sdsCobEletronica_NotaNUMCRECEBER: TIntegerField;
sdsCobEletronica_NotaNOMECLIENTE: TStringField;
cdsCobEletronica_Nota: TClientDataSet;
cdsCobEletronicasdsCobEletronica_Nota: TDataSetField;
cdsCobEletronica_NotaID: TIntegerField;
cdsCobEletronica_NotaITEM: TIntegerField;
cdsCobEletronica_NotaNUMNOTA: TIntegerField;
cdsCobEletronica_NotaCODCLIENTE: TIntegerField;
cdsCobEletronica_NotaSERIE: TStringField;
cdsCobEletronica_NotaNUMSEQNOTA: TIntegerField;
cdsCobEletronica_NotaVLRTITULO: TFloatField;
cdsCobEletronica_NotaDTVENCIMENTO: TDateField;
cdsCobEletronica_NotaPROCESSO: TStringField;
cdsCobEletronica_NotaPARCELA: TIntegerField;
cdsCobEletronica_NotaNUMCRECEBER: TIntegerField;
cdsCobEletronica_NotaNOMECLIENTE: TStringField;
dsCobEletronica_Nota: TDataSource;
sdsCobEletronica_NotaFILIAL: TIntegerField;
cdsCobEletronica_NotaFILIAL: TIntegerField;
sdsCobEletronica_NotaNOSSONUMERO: TStringField;
cdsCobEletronica_NotaNOSSONUMERO: TStringField;
sdsCobEletronica_NotaCGCCPF: TStringField;
cdsCobEletronica_NotaCGCCPF: TStringField;
sdsCobEletronica_NotaESPECIEDOC: TStringField;
sdsCobEletronica_NotaACEITE: TStringField;
sdsCobEletronica_NotaNUMCARTEIRA: TStringField;
cdsCobEletronica_NotaESPECIEDOC: TStringField;
cdsCobEletronica_NotaACEITE: TStringField;
cdsCobEletronica_NotaNUMCARTEIRA: TStringField;
sdsCobEletronica_NotaPESSOA: TStringField;
cdsCobEletronica_NotaPESSOA: TStringField;
tContas: TTable;
dsContas: TDataSource;
tContasAcbr_TipoCobranca: TStringField;
tContasCodCedente: TStringField;
tContasCodConta: TIntegerField;
tContasNomeConta: TStringField;
tContasSaldoConta: TFloatField;
tContasTipoConta: TStringField;
tContasCodBanco: TStringField;
tContasInstrucao1: TStringField;
tContasInstrucao2: TStringField;
tContasInstrucao3: TStringField;
tContasInstrucao4: TStringField;
tContasEspecie: TStringField;
tContasLocalPagamento: TStringField;
tContasQtdLinhasInst: TIntegerField;
tContasAgencia: TStringField;
tContasDescNota: TStringField;
tContasDigConta: TStringField;
tContasFilial: TIntegerField;
tContasNumConta: TStringField;
tContasCNAB: TStringField;
tContasConvenioLider: TStringField;
tContasCodTipoCobranca: TIntegerField;
tContasDtEncerramento: TDateField;
tContasAge_PossuiDigVerificador: TBooleanField;
tContasBanco_logo: TStringField;
tFilial: TTable;
dsFilial: TDataSource;
tFilialCodigo: TIntegerField;
tFilialEmpresa: TStringField;
tFilialEndereco: TStringField;
tContasAgencia_Dig: TStringField;
tFilialEstado: TStringField;
tContasAcbr_LayOutRemessa: TStringField;
tContasInicial_Nome_Arq_Rem: TStringField;
tContasEnd_Arq_Rem: TStringField;
tContasExtensao_Arq_Rem: TStringField;
ACBrBoleto1: TACBrBoleto;
ACBrBoletoFCFortes1: TACBrBoletoFCFortes;
sdsContas_Calculo: TSQLDataSet;
dspContas_Calculo: TDataSetProvider;
cdsContas_Calculo: TClientDataSet;
dsContas_Calculo: TDataSource;
cdsContas_CalculoID: TIntegerField;
cdsContas_CalculoANO: TIntegerField;
cdsContas_CalculoITEM: TIntegerField;
cdsContas_CalculoSEQ_NOSSONUMERO: TFMTBCDField;
tContasNossoNumero_Por_Ano: TStringField;
sdsCob_Tipo_Cadastro: TSQLDataSet;
dspCob_Tipo_Cadastro: TDataSetProvider;
cdsCob_Tipo_Cadastro: TClientDataSet;
dsCob_Tipo_Cadastro: TDataSource;
cdsCob_Tipo_CadastroID: TIntegerField;
cdsCob_Tipo_CadastroCODIGO: TStringField;
cdsCob_Tipo_CadastroNOME: TStringField;
cdsCob_Tipo_CadastroTIPO_REG: TStringField;
cdsCob_Tipo_CadastroID_BANCO: TIntegerField;
cdsCob_Tipo_CadastroCOD_REDUZIDO: TStringField;
cdsCob_Tipo_CadastroTIPO_INST: TStringField;
cdsCob_Tipo_CadastroTIPO_PROTESTO: TStringField;
cdsCob_Tipo_CadastroENVIAR_DIAS_PROTESTO: TStringField;
cdsCob_Tipo_CadastroGERAR_NOSSONUMERO: TStringField;
cdsCob_Tipo_CadastroGERAR_REMESSA: TStringField;
sdsEspecie: TSQLDataSet;
sdsEspecieID: TIntegerField;
sdsEspecieCODIGO: TStringField;
sdsEspecieNOME: TStringField;
sdsEspecieTIPO_REG: TStringField;
sdsEspecieID_BANCO: TIntegerField;
dspEspecie: TDataSetProvider;
cdsEspecie: TClientDataSet;
cdsEspecieID: TIntegerField;
cdsEspecieCODIGO: TStringField;
cdsEspecieNOME: TStringField;
cdsEspecieTIPO_REG: TStringField;
cdsEspecieID_BANCO: TIntegerField;
dsEspecie: TDataSource;
tBcoSantander: TTable;
dsBcoSantander: TDataSource;
tBcoSantanderCodConta: TIntegerField;
tBcoSantanderCodCedente: TStringField;
tBcoSantanderCarteira: TStringField;
tBcoSantanderAceite: TStringField;
tBcoSantanderInstrucao: TStringField;
tBcoSantanderDiasProtesto: TIntegerField;
tBcoSantanderCaminho: TStringField;
tBcoSantanderNome: TStringField;
tBcoSantanderExtensao: TStringField;
tBcoSantanderVlrDesconto: TFloatField;
tBcoSantanderVlrJurosPorDia: TFloatField;
tBcoSantanderEspecieDoc: TStringField;
tBcoSantanderNumCarteira: TStringField;
tBcoSantanderDtLimiteDesconto: TDateField;
tBcoSantanderTipoJuro: TStringField;
tBcoSantanderTipoDesconto: TStringField;
tBcoSantanderTaxaMulta: TFloatField;
tBcoSantanderCodTransmissao: TStringField;
tBcoSantanderNumRemessa: TIntegerField;
tBcoSantanderFormaCadastramento: TIntegerField;
tBcoSantanderCodProtesto: TStringField;
tBcoSantanderCodBaixa: TStringField;
tBcoSantanderCodCompensacao: TStringField;
tBcoSantanderTipoDocumento: TStringField;
tBcoSantanderDiasBaixa: TIntegerField;
tBcoSantanderVlrIOF: TFloatField;
tBcoSantanderCodMulta: TStringField;
tBcoSantanderDtMulta: TDateField;
tBcoSantanderVlrMulta: TFloatField;
tBcoSantanderTipoDesconto2: TStringField;
tBcoSantanderDtLimiteDesconto2: TDateField;
tBcoSantanderVlrDesconto2: TFloatField;
tBcoSantanderMensagem1: TStringField;
tBcoSantanderMensagem2: TStringField;
tFilialBairro: TStringField;
tFilialCep: TStringField;
tFilialCidade: TStringField;
tFilialCNPJ: TStringField;
tFilialTel: TStringField;
tFilialTel2: TStringField;
tFilialFax: TStringField;
tFilialInscr: TStringField;
tFilialSimples: TBooleanField;
tFilialEmail: TStringField;
tFilialSimplesGaucho: TBooleanField;
tFilialImpSimplesGaucho: TBooleanField;
tFilialEndLogo: TStringField;
tFilialNomeInterno: TStringField;
tFilialCalculaIpi: TBooleanField;
tFilialInativo: TBooleanField;
tFilialCodCidade: TIntegerField;
tFilialInscMunicipal: TStringField;
tFilialCNAE: TStringField;
tFilialNumEnd: TStringField;
tFilialHomePage: TStringField;
tFilialUsarICMSimples: TBooleanField;
tFilialCodRegimeTrib: TIntegerField;
tFilialCodPis: TStringField;
tFilialCodCofins: TStringField;
tFilialTipoPis: TStringField;
tFilialTipoCofins: TStringField;
tFilialPercCofins: TFloatField;
tFilialPercPis: TFloatField;
tFilialCodSitTrib: TIntegerField;
tFilialCodCSTIPI: TStringField;
tFilialDtEstoque: TDateField;
tFilialEMailNFe: TStringField;
tFilialPerc_Trib_NTS_Ind: TFloatField;
tFilialPerc_Trib_NTS_Ven: TFloatField;
tFilialPerc_Trib_NTS_Ind_Exp: TFloatField;
tFilialPerc_Trib_NTS_Ven_Exp: TFloatField;
tCReceberParc: TTable;
tCReceberParcFilial: TIntegerField;
tCReceberParcNumCReceber: TIntegerField;
tCReceberParcParcCReceber: TIntegerField;
tCReceberParcVlrParcCReceber: TFloatField;
tCReceberParcDtVencCReceber: TDateField;
tCReceberParcQuitParcCReceber: TBooleanField;
tCReceberParcJurosParcCReceber: TFloatField;
tCReceberParcDtPagParcCReceber: TDateField;
tCReceberParcCodCli: TIntegerField;
tCReceberParcNumNota: TIntegerField;
tCReceberParcDesconto: TFloatField;
tCReceberParcPgtoParcial: TFloatField;
tCReceberParcRestParcela: TFloatField;
tCReceberParcContaDupl: TSmallintField;
tCReceberParcSelecionado: TBooleanField;
tCReceberParcCodVendedor: TIntegerField;
tCReceberParcBaixada: TBooleanField;
tCReceberParcPercComissao: TFloatField;
tCReceberParcVlrComissao: TFloatField;
tCReceberParcPlanoContas: TIntegerField;
tCReceberParcAgencia: TStringField;
tCReceberParcTitPortador: TStringField;
tCReceberParcCodTipoCobranca: TIntegerField;
tCReceberParcDespesas: TFloatField;
tCReceberParcAbatimentos: TFloatField;
tCReceberParcCodConta: TIntegerField;
tCReceberParcPgCartorio: TBooleanField;
tCReceberParcDiasAtraso: TFloatField;
tCReceberParcLetraCambio: TBooleanField;
tCReceberParcJurosPagos: TFloatField;
tCReceberParcCancelado: TBooleanField;
tCReceberParcTitProtestado: TBooleanField;
tCReceberParcDtGerado: TDateField;
tCReceberParcTipoDoc: TStringField;
tCReceberParcVlrDevolucao: TFloatField;
tCReceberParcArqGerado: TBooleanField;
tCReceberParcTransferencia: TBooleanField;
tCReceberParcNumTitBanco: TStringField;
tCReceberParcNroLancExtComissao: TIntegerField;
tCReceberParcComissaoItem: TBooleanField;
tCReceberParcVlrComissaoRestante: TFloatField;
tCReceberParcCodPlanoContasItens: TIntegerField;
tCReceberParcCodVendedor2: TIntegerField;
tCReceberParcPercComissao2: TFloatField;
tCReceberParcCodBancoBoleto: TIntegerField;
tCReceberParcNumCarteira: TStringField;
tCReceberParcNumSeqNossoNum: TIntegerField;
tCReceberParcItemSeqNossoNum: TIntegerField;
tCReceberParcDtVencimento2: TDateField;
tCReceberParcSerie: TStringField;
tCReceberParcNumSeqNota: TIntegerField;
tCReceberParcCodBancoCheque: TIntegerField;
tCReceberParcNumCheque: TIntegerField;
tCReceberParcCodCartaoCredito: TIntegerField;
tCReceberParcNumCartaoCredito: TStringField;
tCReceberParcValidadeCartao: TStringField;
tCReceberParcTipoCondicao: TStringField;
tCReceberParcNumAutorizacaoCartao: TStringField;
tCReceberParcIDCobEletronica: TIntegerField;
tCReceberParcAceite: TStringField;
tCReceberParcEspecieDoc: TStringField;
tCReceberParcDescontoDe: TStringField;
tCReceberParcDescontoAte: TStringField;
dsCReceberParc: TDataSource;
sdsCobEletronica_NotaDTEMISSAO: TDateField;
cdsCobEletronica_NotaDTEMISSAO: TDateField;
sdsEspecieCOD_REDUZIDO: TStringField;
cdsEspecieCOD_REDUZIDO: TStringField;
tContasACBR_Montar_NossoNumero: TStringField;
tContasNum_Arq_Rem: TIntegerField;
tContasDt_Remessa: TDateField;
tContasSeq_Remessa_Dia: TSmallintField;
tContasPercJuros: TFloatField;
tContasPercMulta: TFloatField;
tContasDiasProtesto: TSmallintField;
tContasIdBanco: TIntegerField;
tBcoSantanderComplemento: TStringField;
tBcoSantanderGerarNossoNumero: TStringField;
mRetorno: TClientDataSet;
mRetornoCodCarteira: TStringField;
mRetornoCodOcorrenciaRet: TStringField;
mRetornoNomeOcorrenciaRet: TStringField;
mRetornoDtOcorrencia: TStringField;
mRetornoNumNota: TStringField;
mRetornoDtVenc: TStringField;
mRetornoVlrTitulo: TFloatField;
mRetornoEspecieDoc: TStringField;
mRetornoVlrDespesaCobranca: TFloatField;
mRetornoVlrIOF: TFloatField;
mRetornoVlrAbatimento: TFloatField;
mRetornoVlrDesconto: TFloatField;
mRetornoVlrPago: TFloatField;
mRetornoVlrJurosPagos: TFloatField;
mRetornoDtLiquidacao: TStringField;
mRetornoInstrCancelada: TStringField;
mRetornoNomeCliente: TStringField;
mRetornoErros: TStringField;
mRetornoCodLiquidacao: TStringField;
mRetornoDescLiquidacao: TStringField;
mRetornoAtualizado: TStringField;
mRetornoCodCliente: TIntegerField;
mRetornoParcela: TStringField;
mRetornoDescErro1: TStringField;
mRetornoDescErro2: TStringField;
mRetornoDescErro3: TStringField;
mRetornoDescErro4: TStringField;
mRetornoDescErro5: TStringField;
mRetornoDescErro6: TStringField;
mRetornoCodInstrCancelada: TStringField;
mRetornoConfNossoNumero: TStringField;
mRetornoNossoNumero: TStringField;
mRetornoSeuNumero: TStringField;
mRetornoID_Duplicata: TStringField;
mRetornoTitulo_OK: TBooleanField;
mRetornoUsa_NumConta_Cedente: TStringField;
mRetornoTipo_Ret: TStringField;
mRetornoFilial: TIntegerField;
mRetornoAtualizar: TStringField;
dsmRetorno: TDataSource;
dsCReceberParcHist: TDataSource;
tCReceberParcHist: TTable;
tCReceberParcHistFilial: TIntegerField;
tCReceberParcHistNumCReceber: TIntegerField;
tCReceberParcHistParcCReceber: TIntegerField;
tCReceberParcHistItem: TIntegerField;
tCReceberParcHistCodHistorico: TIntegerField;
tCReceberParcHistDtHistorico: TDateField;
tCReceberParcHistHistorico: TStringField;
tCReceberParcHistDtUltPgto: TDateField;
tCReceberParcHistVlrUltPgto: TFloatField;
tCReceberParcHistVlrUltJuros: TFloatField;
tCReceberParcHistVlrUltDescontos: TFloatField;
tCReceberParcHistVlrUltDespesas: TFloatField;
tCReceberParcHistVlrUltAbatimentos: TFloatField;
tCReceberParcHistPgto: TBooleanField;
tCReceberParcHistJurosPagos: TFloatField;
tCReceberParcHistNumMov: TIntegerField;
tCReceberParcHistNumMovJuros: TIntegerField;
tCReceberParcHistJurosCalc: TFloatField;
tCReceberParcHistVlrDevolucao: TFloatField;
tCReceberParcHistDevolucao: TBooleanField;
tCReceberParcHistNroLancExtComissao: TIntegerField;
tCReceberParcHistTipo: TStringField;
tCReceberParcHistCodConta: TIntegerField;
tCReceberParcHistCodBancoCheque: TIntegerField;
tCReceberParcHistNumCheque: TIntegerField;
tCReceberParcHistCodCartaoCredito: TIntegerField;
tCReceberParcHistNumCartaCredito: TStringField;
tCReceberParcHistValidadeCartao: TStringField;
tCReceberParcHistTipoCondicao: TStringField;
sdsRet_Cadastro: TSQLDataSet;
sdsRet_CadastroID: TIntegerField;
sdsRet_CadastroCODIGO: TStringField;
sdsRet_CadastroNOME: TStringField;
sdsRet_CadastroTIPO_REG: TStringField;
sdsRet_CadastroID_BANCO: TIntegerField;
sdsRet_CadastroTIPO_RET: TStringField;
sdsRet_CadastroTIPO_LIQ: TStringField;
dspRet_Cadastro: TDataSetProvider;
cdsRet_Cadastro: TClientDataSet;
cdsRet_CadastroID: TIntegerField;
cdsRet_CadastroCODIGO: TStringField;
cdsRet_CadastroNOME: TStringField;
cdsRet_CadastroTIPO_REG: TStringField;
cdsRet_CadastroID_BANCO: TIntegerField;
cdsRet_CadastroTIPO_RET: TStringField;
cdsRet_CadastroTIPO_LIQ: TStringField;
dsRet_Cadastro: TDataSource;
qContas_Retorno: TSQLQuery;
qContas_RetornoID: TIntegerField;
qContas_RetornoPOS_NUM_NOTA: TIntegerField;
qContas_RetornoQTD_NUM_NOTA: TIntegerField;
qContas_RetornoPOS_NOSSO_NUMERO: TIntegerField;
qContas_RetornoQTD_NOSSO_NUMERO: TIntegerField;
qContas_RetornoPOS_ID_DUPLICATA: TIntegerField;
qContas_RetornoQTD_ID_DUPLICATA: TIntegerField;
qContas_RetornoPOS_OCORRENCIA: TIntegerField;
qContas_RetornoPOS_DT_OCORRENCIA: TIntegerField;
qContas_RetornoPOS_CONF_NOSSO_NUMERO: TIntegerField;
qContas_RetornoQTD_CONF_NOSSO_NUMERO: TIntegerField;
qContas_RetornoPOS_DT_VENCIMENTO: TIntegerField;
qContas_RetornoPOS_VLR_TITULO: TIntegerField;
qContas_RetornoQTD_VLR_TITULO: TIntegerField;
qContas_RetornoPOS_ESPECIE: TIntegerField;
qContas_RetornoPOS_VLR_DESPESA_COB: TIntegerField;
qContas_RetornoQTD_VLR_DESPESA_COB: TIntegerField;
qContas_RetornoPOS_VLR_IOF: TIntegerField;
qContas_RetornoQTD_VLR_IOF: TIntegerField;
qContas_RetornoPOS_VLR_ABATIMENTO: TIntegerField;
qContas_RetornoQTD_VLR_ABATIMENTO: TIntegerField;
qContas_RetornoPOS_VLR_DESCONTO: TIntegerField;
qContas_RetornoQTD_VLR_DESCONTO: TIntegerField;
qContas_RetornoPOS_VLR_PAGO: TIntegerField;
qContas_RetornoQTD_VLR_PAGO: TIntegerField;
qContas_RetornoPOS_VLR_JUROS_PAGO: TIntegerField;
qContas_RetornoQTD_VLR_JUROS_PAGO: TIntegerField;
qContas_RetornoPOS_DT_LIQUIDACAO: TIntegerField;
qContas_RetornoPOS_INST_CANCELADA: TIntegerField;
qContas_RetornoPOS_ERRO: TIntegerField;
qContas_RetornoQTD_ERRO: TIntegerField;
qContas_RetornoPOS_COD_LIQUIDACAO: TIntegerField;
qContas_RetornoQTD_COD_LIQUIDACAO: TIntegerField;
qContas_RetornoPOS_CARTEIRA: TIntegerField;
qContas_RetornoPOS_NOME_CLIENTE: TIntegerField;
qContas_RetornoQTD_NOME_CLIENTE: TIntegerField;
qContas_RetornoPOS_NUMCONTA_RETORNO: TIntegerField;
qContas_RetornoPOS_CODBANCO_RETORNO: TIntegerField;
qContas_RetornoNUMCONTA_CEDENTE: TStringField;
qContas_RetornoQTD_ERRO_CADASTRO: TIntegerField;
qContas_RetornoQTD_CARTEIRA: TIntegerField;
qRet_Erro: TSQLQuery;
qRet_ErroID: TIntegerField;
qRet_ErroCODIGO: TStringField;
qRet_ErroNOME: TStringField;
qRet_ErroTIPO_REG: TStringField;
qRet_ErroID_BANCO: TIntegerField;
qRet_ErroTABELA_REJ: TStringField;
qRet_ErroTIPO_RET: TStringField;
tVendedor: TTable;
tVendedorCodigo: TIntegerField;
tVendedorNome: TStringField;
tVendedorPercComissao: TFloatField;
tVendedorTipoComissao: TStringField;
tCReceberParclkTipoComissao: TStringField;
procedure DataModuleCreate(Sender: TObject);
procedure dspCobEletronicaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError;
UpdateKind: TUpdateKind; var Response: TResolverResponse);
private
{ Private declarations }
ctCobTpCadastro: String;
public
{ Public declarations }
xNossoNum: Int64;
vSeq_Remessa_Dia: Word;
vCodCarteira: String;
vGera_NossoNumero: String; //S= Sim N= Não
vNossoNumero: String;
vNossoNumero_Montado: String;
vNum_Remessa: Integer;
vAceite: String;
vExiste_Rec : Boolean;
vGravou_Hist: Boolean;
vID_Carteira: Integer;
vCod_Carteira: String;
procedure buscaNossoNumero;
procedure prc_Verificar_Carteira;
procedure prc_Gravar_Duplicata(Tipo: String);
procedure prc_Localizar(vFilial, vCod, vParc: Integer);
procedure geraCabecalhoAcbr;
function geraRegistroAcbr(vDtVcto, vDtEmissao: TDateTime; vNN, vNumDupl, vCarteira,
vNomeCli, vCnpjCli, vEndCli, vNumEndCli, vBairroCli, vCidadeCli, vUfCli, vCepCli, vPessoa, vAceite: String;
vVlrParc: Real; vNumParc, vIdBanco, NumCReceber: Integer): String;
procedure prc_Enviar_ACBR;
procedure prc_ConfiguraACBR;
function fnc_Busca_Num_Arquivo_Rem: Integer;
end;
var
DMCobEletronica: TDMCobEletronica;
ctCobEletronica: String;
implementation
uses DmdDatabase;
{$R *.dfm}
procedure TDMCobEletronica.buscaNossoNumero;
begin
cdsContas_calculo.Close;
sdsContas_Calculo.ParamByName('ID').AsInteger := tContasCodConta.AsInteger;
if tContasNOSSONUMERO_POR_ANO.AsString = 'S' then
sdsContas_Calculo.ParamByName('ANO').AsInteger := StrToInt(FormatDateTime('YYYY',Date))
else
sdsContas_Calculo.ParamByName('ANO').AsInteger := 9999;
sdsContas_Calculo.ParamByName('ITEM').AsInteger := 99;
cdsContas_calculo.Open;
if cdsContas_calculo.IsEmpty then
begin
cdsContas_calculo.Insert;
cdsContas_calculoID.AsInteger := tContasCodConta.AsInteger;
if tContasNossoNumero_Por_Ano.AsString = 'S' then
cdsContas_CalculoANO.AsInteger := StrToInt(FormatDateTime('YYYY',Date))
else
cdsContas_calculoANO.AsInteger := 9999;
cdsContas_calculoITEM.AsInteger := 99;
cdsContas_calculoSEQ_NOSSONUMERO.AsInteger := 0;
cdsContas_calculo.Post;
cdsContas_calculo.ApplyUpdates(0);
end;
//xNossoNum := StrToInt(cdsContas_calculoSEQ_NOSSONUMERO.AsString);
xNossoNum := StrToInt64(FormatFloat('0',cdsContas_calculoSEQ_NOSSONUMERO.AsFloat));
end;
procedure TDMCobEletronica.DataModuleCreate(Sender: TObject);
begin
ctCobEletronica := sdsCobEletronica.CommandText;
ctCobTpCadastro := sdsCob_Tipo_Cadastro.CommandText;
end;
procedure TDMCobEletronica.dspCobEletronicaUpdateError(Sender: TObject;
DataSet: TCustomClientDataSet; E: EUpdateError; UpdateKind: TUpdateKind;
var Response: TResolverResponse);
begin
Response := rrAbort;
raise exception.Create(E.Message);
end;
procedure TDMCobEletronica.geraCabecalhoAcbr;
begin
ACBrBoleto1.Banco.Numero := tContasCodBanco.AsInteger;
ACBrBoleto1.Banco.Nome := tContasNomeConta.AsString;// 'Banco do Estado do Rio Grande do Sul S.A.';
ACBrBoleto1.Cedente.Agencia := tContasAGENCIA.AsString; // '0785';
ACBrBoleto1.Cedente.AgenciaDigito := tContasAgencia_Dig.AsString;
ACBrBoleto1.Cedente.Conta := tContasNumConta.AsString;// '06.022038.0';
ACBrBoleto1.Cedente.ContaDigito := tContasDigConta.AsString;// '3';
ACBrBoleto1.Cedente.CNPJCPF := tFilialCNPJ.AsString;// '09.348.462/0001-79';
ACBrBoleto1.Cedente.CodigoCedente := tContasCodCedente.AsString;// '0785022038017';
ACBrBoleto1.Cedente.Logradouro := tFilialEndereco.AsString;
ACBrBoleto1.Cedente.Nome := tFilialEmpresa.AsString;
ACBrBoleto1.Cedente.NumeroRes := tFilialNumEnd.AsString;
ACBrBoleto1.Cedente.Telefone := tFilialTel.AsString;
ACBrBoleto1.Cedente.TipoInscricao := pJuridica;
ACBrBoleto1.Cedente.UF := tFilialEstado.AsString;
ACBrBoleto1.Cedente.Bairro := tFilialBairro.AsString;
ACBrBoleto1.Cedente.CEP := tFilialCep.AsString;;
ACBrBoleto1.Cedente.Cidade := 'NOVO HAMBURGO';//tFilialCIDADE.AsString;;
//ACBrBoleto1.Cedente.CodigoTransmissao := '157800007072171';
ACBrBoleto1.Cedente.CodigoTransmissao := tBcoSantanderCodTransmissao.AsString;
//ACBrBoleto1.Cedente.Complemento := 'I82';//tFilialCOMPLEMENTO_END.AsString;
ACBrBoleto1.Cedente.Complemento := tBcoSantanderComplemento.AsString;
ACBrBoleto1.Cedente.Modalidade := '101';//101 = Cobrança Simples Rápida Com Registro
//29/04/2015
if tBcoSantanderNumCarteira.AsString = '1' then
ACBrBoleto1.Cedente.CaracTitulo := tcSimples //simples com registro
else
if tBcoSantanderNumCarteira.AsString = '3' then
ACBrBoleto1.Cedente.CaracTitulo := tcCaucionada
else
if tBcoSantanderNumCarteira.AsString = '5' then
ACBrBoleto1.Cedente.CaracTitulo := tcVinculada; //simples com registro
if tBcoSantanderTipoDocumento.AsString = '1' then
ACBrBoleto1.Cedente.TipoDocumento := Tradicional
else
if tBcoSantanderTipoDocumento.AsString = '2' then
ACBrBoleto1.Cedente.TipoDocumento := Escritural;
end;
function TDMCobEletronica.geraRegistroAcbr(vDtVcto, vDtEmissao: TDateTime; vNN, vNumDupl, vCarteira,
vNomeCli, vCnpjCli, vEndCli, vNumEndCli, vBairroCli, vCidadeCli, vUfCli, vCepCli, vPessoa, vAceite: String;
vVlrParc: Real; vNumParc, vIdBanco, NumCReceber: Integer): String;
var
Titulo: TACBrTitulo;
vTamAux: Integer;
vNossoNumAux: String;
begin
vAceite := vAceite;
if Assigned(Titulo) then
FreeAndNil(Titulo);
Titulo := ACBrBoleto1.CriarTituloNaLista;
with Titulo do
begin
//05/12/2014
TipoImpressao := tipNormal;//se for carnê, tipCarne
Vencimento := vDtVcto;
DataDocumento := vDtEmissao;
NumeroDocumento := vNumDupl + '/' + IntToStr(vNumParc);
//-------------------------
if not cdsEspecie.Active then
begin
//sdsEspecie.ParamByName('ID_BANCO').AsInteger := 4; //Santander
sdsEspecie.ParamByName('ID_BANCO').AsInteger := tContasIDBanco.AsInteger;
cdsEspecie.Open;
end;
cdsEspecie.IndexFieldNames := 'ID;ID_BANCO';
cdsEspecie.FindKey([tContasEspecie.AsInteger,tContasIDBanco.AsInteger]);
if trim(cdsEspecieCOD_REDUZIDO.AsString) = '' then
EspecieDoc := cdsEspecieCODIGO.AsString
else
EspecieDoc := cdsEspecieCOD_REDUZIDO.AsString;
//-------------------------
if vAceite = 'A' then
Aceite := atSim
else
Aceite := atNao;
DataProcessamento := Now;
//Carteira := vCarteira;
Carteira := tBcoSantanderNumCarteira.AsString;
prc_Verificar_Carteira;
NossoNumero := vNN;
if tBcoSantanderGerarNossoNumero.AsString <> 'B' then
begin
if (vNN = '') or (StrToInt(vNN) = 0) then
begin
if (vGera_NossoNumero = 'S') then
begin
xNossoNum := xNossoNum + 1;
vNossoNumAux := IntToStr(xNossoNum);
vTamAux := ACBrBoleto.Banco.CalcularTamMaximoNossoNumero(Carteira,vNossoNumAux);
NossoNumero := IntToStrZero(xNossoNum,vTamAux);
if tContasACBR_Montar_NossoNumero.AsString = 'S' then
vNossoNumero_Montado := ACBrBoleto.Banco.MontarCampoNossoNumero(Titulo)
else
vNossoNumero_Montado := NossoNumero;
end;
end;
end;
SeuNumero := tContasFILIAL.AsString + '.' + vNumDupl + '/' + IntToStr(vNumParc);
IdentTituloEmpresa := tContasFILIAL.AsString + '.' + IntToStr(NumCReceber) + '/' + IntToStr(vNumParc);
ValorDocumento := vVlrParc;
Sacado.NomeSacado := vNomeCli;
Sacado.CNPJCPF := vCnpjCli;
Sacado.Logradouro := Trim(vEndCli);
Sacado.Numero := Trim(vNumEndCli);
Sacado.Bairro := Trim(vBairroCli);
Sacado.Cidade := Trim(vCidadeCli);
Sacado.UF := Trim(vUfCli);
Sacado.CEP := Trim(vCepCli);
if vPessoa = 'J' then
Sacado.Pessoa := pJuridica
else
if vPessoa = 'F' then
Sacado.Pessoa := pFisica
else
case StrToInt(vPessoa) of
1: Sacado.Pessoa := pFisica;
2: Sacado.Pessoa := pJuridica;
end;
ValorAbatimento := 0;
LocalPagamento := tContasLocalPagamento.AsString;
ValorMoraJuros := tContasPercJuros.AsCurrency / 100 * vVlrParc;
ValorDesconto := 0;
ValorAbatimento := 0;
DataMoraJuros := vDtVcto + 0;
DataDesconto := 0;
DataAbatimento := 0;
//DataProtesto := vDtVcto + tContasDiasProtesto.AsInteger;
DataProtesto := 0;
PercentualMulta := tContasPercMulta.AsCurrency;
Mensagem.Text := tBcoSantanderMensagem1.AsString;
cdsCob_Tipo_Cadastro.Close;
sdsCob_Tipo_Cadastro.CommandText := ctCobTpCadastro + ' WHERE ID_BANCO = ' + IntToStr(vIdBanco);
cdsCob_Tipo_Cadastro.Open;
if trim(tBcoSantanderCodProtesto.AsString) = '' then
Instrucao1 := '2'
else
Instrucao1 := tBcoSantanderCodProtesto.AsString;
QtdDiaProtesto := tBcoSantanderDiasProtesto.AsInteger;
Instrucao2 := '2'; //não baixar / não devolver
Parcela := 0;
OcorrenciaOriginal.Tipo := toRemessaRegistrar;
end;
result := Titulo.NossoNumero;
end;
procedure TDMCobEletronica.prc_Gravar_Duplicata(Tipo: String);
var
vItemAux: Integer;
begin
vGravou_Hist := False;
if (Tipo <> 'R') and (Tipo <> 'LIQ') and (Tipo <> 'LCA') and (Tipo <> 'PRO') then
begin
if (trim(tCReceberParcNumTitBanco.AsString) <> '') and (tCReceberParcCodConta.AsInteger = tContasCodConta.AsInteger) and
(tCReceberParcNumCarteira.AsInteger = vID_Carteira) then
begin
exit;
end;
end;
try
tCReceberParc.Edit;
if (trim(tCReceberParcNumTitBanco.AsString) = '') and (trim(vNossoNumero) <> '') then
begin
//tCReceberParcNumTitBanco.AsString := vNossoNumero_Montado;
tCReceberParcNumTitBanco.AsString := vNossoNumero;
// if (Tipo = 'R') or (Tipo = 'I') or (Tipo = 'E') then
// tCReceberParcNOSSONUMERO_GERADO.AsString := 'S'
// else
// cdsDuplicataNOSSONUMERO_GERADO.AsString := 'B';
end;
if (Tipo <> 'LIQ') AND (Tipo <> 'LCA') and (Tipo <> 'PRO') and (Tipo <> 'NNU') then
begin
tCReceberParcNumCarteira.AsString := vCod_Carteira;
tCReceberParcCodConta.AsInteger := tContasCodConta.AsInteger;
tCReceberParcCodBancoBoleto.AsInteger := tContasIdBanco.AsInteger;
end;
if Tipo = 'PRO' then
tCReceberParcTitProtestado.AsBoolean := True;
tCReceberParc.Post;
// prc_Gravar_Historico(Tipo);
vGravou_Hist := True;
except
raise;
end;
end;
procedure TDMCobEletronica.prc_Verificar_Carteira;
begin
vGera_NossoNumero := 'S';
{ if cdsDuplicataID_CARTEIRA.AsInteger > 0 then
begin
vGera_NossoNumero := cdsDuplicataGERAR_NOSSONUMERO.AsString;
vID_Carteira := cdsDuplicataID_CARTEIRA.AsInteger;
vCod_Carteira := cdsDuplicataCOD_CARTEIRA.AsString;
vGeraRemessa := cdsDuplicataGERAR_REMESSA.AsString;
end
else
if cdsContasID_CARTEIRA.AsInteger > 0 then
begin
vGera_NossoNumero := cdsContasGERAR_NOSSONUMERO.AsString;
vID_Carteira := cdsContasID_CARTEIRA.AsInteger;
vCod_Carteira := cdsContasCOD_CARTEIRA.AsString;
vGeraRemessa := cdsContasGERAR_REMESSA.AsString;
end;
if cdsContasOPCAO_GERAR_NOSSNUMERO.AsString = 'E' then
vGera_NossoNumero := cdsContasGERAR_NOSSONUMERO_ESP.AsString;
}
end;
procedure TDMCobEletronica.prc_Enviar_ACBR;
var
vTitulo: TACBrTitulo;
vGerar: Boolean;
vContadorAux: Integer;
vMsgAux: String;
begin
tContas.Close;
tContas.Open;
// if not fnc_Verificar then
// exit;
//27/08/2014
vNum_Remessa := fnc_Busca_Num_Arquivo_Rem;
prc_ConfiguraACBR;
ACBrBoleto1.ListadeBoletos.Clear;
///////////////////////////////// aqui tratar Juca 2015-03-19
{ mBoletos.First;
while not mBoletos.Eof do
begin
if not SMDBGrid1.SelectedRows.CurrentRowSelected then
begin
mBoletos.Next;
Continue;
end;
if (cdsDuplicataID_CONTA_BOLETO.IsNull) and (cdsDuplicataFILIAL.AsInteger = RxDBLookupCombo1.KeyValue) then
begin
cdsDuplicata.Edit;
cdsDuplicataID_CONTA_BOLETO.AsInteger := RxDBLookupCombo2.KeyValue;
cdsDuplicata.Post;
end;
mBoletos.Next;
end;
cdsDuplicata.ApplyUpdates(0);
buscaNossoNumero;
vMsgAux := '';
vGerar := False;
cdsDuplicata.First;
while not cdsDuplicata.Eof do
begin
if not SMDBGrid1.SelectedRows.CurrentRowSelected then
begin
cdsDuplicata.Next;
Continue;
end;
if cdsDuplicataFILIAL.AsInteger = RxDBLookupCombo1.KeyValue then
begin
prc_Verificar_Carteira;
if vGeraRemessa = 'S' then
begin
vGerar := True;
cdsDuplicata.Last;
end;
end;
if not vGerar then
begin
MessageDlg('Não há títulos selecionados ou carteira não corresponde' + #13 +
'à cobrança do banco definido para gerar remessa!', mtWarning, [mbOk], 0);
cdsDuplicata.Last;
end;
cdsDuplicata.Next;
end;
//27/08/2014
//vNum_Remessa := fnc_Busca_Num_Arquivo_Rem;
vMsgAux := '';
vContadorAux := 0;
geraCabecalhoAcbr;
cdsDuplicata.First;
while not cdsDuplicata.Eof do
begin
if SMDBGrid1.SelectedRows.CurrentRowSelected then
begin
if not(cdsDuplicataNUM_REMESSA.IsNull) and not(ckReenviar.Checked) then
begin
SMDBGrid1.SelectedRows.CurrentRowSelected := False;
cdsDuplicata.Next;
Continue;
end;
if cdsDuplicataFILIAL.AsInteger <> RxDBLookupCombo1.KeyValue then
vMsgAux := 'Alguns títulos não foram gerados;' +#13 + 'Verifique se a Filial informada é a mesma do título;'
else
begin
prc_Verificar_Carteira;
if vGeraRemessa = 'S' then
begin
vContadorAux := vContadorAux + 1;
vNossoNumero := geraRegistroACBR;
//aqui
prc_Gravar_Duplicata('R');
end;
end;
end;
cdsDuplicata.Next;
end;
if vContadorAux <= 0 then
begin
MessageDlg('*** Nenhum título na remessa!' +#13 +
'Motivo:' +#13 +
' 1) Verifique se foi selecionado algum título;' +#13 +
' 2) Verifique se a carteira está marcada para gerar remessa;' +#13, mtInformation, [mbOk], 0);
exit;
end
else
if trim(vMsgAux) <> '' then
MessageDlg(vMsgAux + #13, mtWarning, [mbOk], 0);
FreeAndNil(vTitulo);
cdsDuplicata.ApplyUpdates(0);}
///////////////////////////////// aqui tratar Juca 2015-03-19
try //gera a remessa
// captura o contador de remessa
ACBrBoleto1.GerarRemessa(vNum_Remessa);
// Atualiza a nosso numero no cadastro do banco
cdsContas_calculo.Edit;
cdsContas_calculoSEQ_NOSSONUMERO.AsString := IntToStr(xNossoNum);
cdsContas_calculo.Post;
cdsContas_calculo.ApplyUpdates(0);
// Atualiza o contador de remesa na tabela de configuração
tContas.Edit;
tContasNum_Arq_Rem.AsInteger := vNum_Remessa;
tContas.Post;
MessageDlg('Geração concluída!' + #13, mtConfirmation, [mbOk], 0);
except
MessageDlg('Erro ao gerar arquivo de remessa!',mtWarning,[mbOK],0);
end;
end;
function TDMCobEletronica.fnc_Busca_Num_Arquivo_Rem: Integer;
var
sds: TSQLDataSet;
i: Integer;
vData: TDateTime;
begin
i := tContasNUM_ARQ_REM.AsInteger + 1;
Result := I;
vSeq_Remessa_Dia := 0;
if tContasDT_REMESSA.AsDateTime = Date then
vSeq_Remessa_Dia := tContasSEQ_REMESSA_DIA.AsInteger;
vSeq_Remessa_Dia := vSeq_Remessa_Dia + 1;
tContas.Edit;
tContasDt_Remessa.AsDateTime := Date;
tContasSeq_Remessa_Dia.AsInteger := vSeq_Remessa_Dia;
tContas.Post;
{ try
sds := TSQLDataSet.Create(nil);
sds.SQLConnection := dmDatabase.scoDados;
sds.NoMetadata := True;
sds.GetMetadata := False;
sds.CommandText := 'UPDATE DBCONTAS SET NUM_ARQ_REMESSA = ' + IntToStr(i)
+ ' , DT_REMESSA = ' + QuotedStr(FormatDateTime('MM/DD/YYYY',Date))
+ ' , SEQ_REMESSA_DIA = ' + IntToStr(vSeq_Remessa_Dia)
+ ' WHERE CODCONTA = ' + tContasCodConta.AsString;
sds.ExecSQL;
finally
FreeAndNil(sds);
end;
}
end;
procedure TDMCobEletronica.prc_ConfiguraACBR;
var
vExtensao: String;
begin
if DmCobEletronica.tContasACBR_LAYOUTREMESSA.AsString = 'C240' then
DmCobEletronica.ACBrBoleto1.LayoutRemessa := C240
else
DmCobEletronica.ACBrBoleto1.LayoutRemessa := C400;
case DmCobEletronica.tContasACBR_TIPOCOBRANCA.AsInteger of
1: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBancoDoBrasil;
2: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBancoDoNordeste;
3: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBancoMercantil;
4: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBancoob;
5: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBanestes;
6: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBanrisul;
7: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBicBanco;
8: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBradesco;
9: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBradescoSICOOB;
10: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobBRB;
11: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobCaixaEconomica;
12: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobCaixaSicob;
13: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobHSBC;
14: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobItau;
15: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobNenhum;
16: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobSantander;
17: DmCobEletronica.ACBrBoleto1.Banco.TipoCobranca := cobSicred;
end;
DmCobEletronica.ACBrBoleto1.ACBrBoletoFC.DirLogo := DmCobEletronica.tContasBANCO_LOGO.AsString;
// ACBrBoleto1.ACBrBoletoFC.ArquivoLogo := fDmCob_Eletronica.cdsContasBANCO_LOGO.AsString;
DmCobEletronica.ACBrBoleto1.ACBrBoletoFC.Filtro := fiNenhum;
DmCobEletronica.ACBrBoleto1.Cedente.Nome := DmCobEletronica.tFilialEmpresa.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.CodigoCedente := DmCobEletronica.tContasCodCedente.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.Agencia := DmCobEletronica.tContasAGENCIA.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.AgenciaDigito := DmCobEletronica.tContasAgencia_Dig.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.Conta := DmCobEletronica.tContasNUMCONTA.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.ContaDigito := DmCobEletronica.tContasDIGCONTA.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.Convenio := DmCobEletronica.tContasConvenioLider.AsString;
DmCobEletronica.ACBrBoleto1.Cedente.UF := DmCobEletronica.tFilialEstado.AsString;
DmCobEletronica.ACBrBoleto1.DirArqRemessa := DmCobEletronica.tContasEnd_Arq_Rem.AsString;
//ACBrBoleto1.NomeArqRemessa := 'COB_' + FormatDateTime('YYYYMMDD_HHMMSS',Now)+'.TXT';
DmCobEletronica.ACBrBoleto1.NomeArqRemessa := DmCobEletronica.tContasINICIAL_NOME_ARQ_REM.AsString +
FormatFloat('00',DmCobEletronica.tContasFILIAL.AsInteger) +
FormatFloat('00',MonthOf(Date)) + FormatFloat('00',DayOf(Date));
if trim(DmCobEletronica.tContasExtensao_Arq_Rem.AsString) = '' then
vExtensao := 'REM'
else
vExtensao := DmCobEletronica.tContasExtensao_Arq_Rem.AsString;
vNum_Remessa := DMCobEletronica.fnc_Busca_Num_Arquivo_Rem;
if DmCobEletronica.vSeq_Remessa_Dia = 1 then
DmCobEletronica.ACBrBoleto1.NomeArqRemessa := DmCobEletronica.ACBrBoleto1.NomeArqRemessa + '.' + vExtensao
else
if DmCobEletronica.vSeq_Remessa_Dia < 100 then
DmCobEletronica.ACBrBoleto1.NomeArqRemessa := DmCobEletronica.ACBrBoleto1.NomeArqRemessa + '.' + Copy(vExtensao,1,1) +
FormatFloat('00',DmCobEletronica.vSeq_Remessa_Dia)
else
DmCobEletronica.ACBrBoleto1.NomeArqRemessa := DmCobEletronica.ACBrBoleto1.NomeArqRemessa + '.' +
FormatFloat('000',DmCobEletronica.vSeq_Remessa_Dia);
end;
procedure TDMCobEletronica.prc_Localizar(vFilial, vCod, vParc: Integer);
begin
vExiste_Rec := False;
if not tCReceberParc.Active then
tCReceberParc.Open;
if (vFilial <> 0) and (vCod <> 0) and (vParc <> 0) then
if tCReceberParc.Locate('Filial;NumCReceber;ParcCReceber',VarArrayOf([vFilial,vCod,vParc]),[loCaseInsensitive]) then
vExiste_Rec := True;
// if not tCReceberParc.Locate('Filial;NumCReceber;ParcCReceber',VarArrayOf([vFilial,vCod,vParc]),[loCaseInsensitive]) then
// ShowMessage('Não localizou!');
end;
end.
|
unit SoapEmployeeImpl;
interface
uses InvokeRegistry, Types, XSBuiltIns, SoapEmployeeIntf;
type
TSoapEmployee = class(TInvokableClass, ISoapEmployee)
public
function GetEmployeeNames: string; stdcall;
function GetEmployeeData (EmpID: string): string; stdcall;
end;
implementation
uses
ServerDataModule, DB, StrUtils, SysUtils;
function MakeXmlStr (nodeName, nodeValue: string; attrList: string = ''): string;
begin
Result := '<' + nodeName +
IfThen (attrList <> '', ' ' + attrList, '') + '>' +
nodeValue +
'</' + nodeName + '>';
end;
function MakeXmlAttribute (attrName, attrValue: string): string;
begin
Result := attrName + '="' + attrValue + '"';
end;
function FieldsToXml (rootName: string; data: TDataSet): string;
var
i: Integer;
begin
Result := '<' + rootName + '>' + sLineBreak;;
for i := 0 to data.FieldCount - 1 do
Result := Result + ' ' + MakeXmlStr (
LowerCase (data.Fields[i].FieldName),
data.Fields[i].AsString) + sLineBreak;
Result := Result + '</' + rootName + '>' + sLineBreak;;
end;
{ TSoapEmployee }
function TSoapEmployee.GetEmployeeData(EmpID: string): string;
var
dm: TDataModule3;
begin
dm := TDataModule3.Create (nil);
try
dm.dsEmpData.ParamByName('ID').AsString := EmpId;
dm.dsEmpData.Open;
Result := FieldsToXml ('employee', dm.dsEmpData);
finally
dm.Free;
end;
end;
function TSoapEmployee.GetEmployeeNames: string;
var
dm: TDataModule3;
begin
dm := TDataModule3.Create (nil);
try
dm.dsEmplList.Open;
Result := '<employeeList>' + sLineBreak;
while not dm.dsEmplList.EOF do
begin
Result := Result + ' ' + MakeXmlStr ('employee',
dm.dsEmplListLAST_NAME.AsString + ' ' +
dm.dsEmplListFIRST_NAME.AsString,
MakeXmlAttribute ('id', dm.dsEmplListEMP_NO.AsString)) + sLineBreak;
dm.dsEmplList.Next;
end;
Result := Result + '</employeeList>'
finally
dm.Free;
end;
end;
initialization
{ Invokable classes must be registered }
InvRegistry.RegisterInvokableClass(TSoapEmployee);
end.
|
{
$Project$
$Workfile$
$Revision$
$DateUTC$
$Id$
This file is part of the Indy (Internet Direct) project, and is offered
under the dual-licensing agreement described on the Indy website.
(http://www.indyproject.org/)
Copyright:
(c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved.
}
{
$Log$
}
{
Rev 1.21 3/10/05 3:24:30 PM RLebeau
Updated ReadFromSource() and WriteDirect() to access the Intercept property
directly.
Rev 1.20 10/21/2004 11:07:30 PM BGooijen
works in win32 now too
Rev 1.19 10/21/2004 1:52:56 PM BGooijen
Raid 214235
Rev 1.18 7/23/04 6:20:52 PM RLebeau
Removed memory leaks in Send/ReceiveStream property setters
Rev 1.17 2004.05.20 11:39:08 AM czhower
IdStreamVCL
Rev 1.16 23/04/2004 20:29:36 CCostelloe
Minor change to support IdMessageClient's new TIdIOHandlerStreamMsg
Rev 1.15 2004.04.16 11:30:32 PM czhower
Size fix to IdBuffer, optimizations, and memory leaks
Rev 1.14 2004.04.08 3:56:36 PM czhower
Fixed bug with Intercept byte count. Also removed Bytes from Buffer.
Rev 1.13 2004.03.07 11:48:46 AM czhower
Flushbuffer fix + other minor ones found
Rev 1.12 2004.03.03 11:55:04 AM czhower
IdStream change
Rev 1.11 2004.02.03 4:17:16 PM czhower
For unit name changes.
Rev 1.10 11/01/2004 19:52:44 CCostelloe
Revisions for TIdMessage SaveToFile & LoadFromFile for D7 & D8
Rev 1.8 08/01/2004 23:37:16 CCostelloe
Minor changes
Rev 1.7 1/8/2004 1:01:22 PM BGooijen
Cleaned up
Rev 1.6 1/8/2004 4:23:06 AM BGooijen
temp fixed TIdIOHandlerStream.WriteToDestination
Rev 1.5 08/01/2004 00:25:22 CCostelloe
Start of reimplementing LoadFrom/SaveToFile
Rev 1.4 2003.12.31 7:44:54 PM czhower
Matched constructors visibility to ancestor.
Rev 1.3 2003.10.24 10:44:54 AM czhower
IdStream implementation, bug fixes.
Rev 1.2 2003.10.14 11:19:14 PM czhower
Updated for better functionality.
Rev 1.1 2003.10.14 1:27:14 PM czhower
Uupdates + Intercept support
Rev 1.0 2003.10.13 6:40:40 PM czhower
Moved from root
Rev 1.9 2003.10.11 10:00:36 PM czhower
Compiles again.
Rev 1.8 10/10/2003 10:53:42 PM BGooijen
Changed const-ness of some methods to reflect base class changes
Rev 1.7 7/10/2003 6:07:58 PM SGrobety
.net
Rev 1.6 17/07/2003 00:01:24 CCostelloe
Added (empty) procedures for the base classes' abstract CheckForDataOnSource
and CheckForDisconnect
Rev 1.5 7/1/2003 12:45:56 PM BGooijen
changed FInputBuffer.Size := 0 to FInputBuffer.Clear
Rev 1.4 12-8-2002 21:05:28 BGooijen
Removed call to Close in .Destroy, this is already done in
TIdIOHandler.Destroy
Rev 1.3 12/7/2002 06:42:44 PM JPMugaas
These should now compile except for Socks server. IPVersion has to be a
property someplace for that.
Rev 1.2 12/5/2002 02:53:52 PM JPMugaas
Updated for new API definitions.
Rev 1.1 05/12/2002 15:29:16 AO'Neill
Rev 1.0 11/13/2002 07:55:08 AM JPMugaas
}
unit IdIOHandlerStream;
interface
{$I IdCompilerDefines.inc}
uses
Classes,
IdBaseComponent,
IdGlobal,
IdIOHandler,
IdStream;
type
TIdIOHandlerStream = class;
TIdIOHandlerStreamType = (stRead, stWrite, stReadWrite);
TIdOnGetStreams = procedure(ASender: TIdIOHandlerStream;
var VReceiveStream: TStream; var VSendStream: TStream) of object;
TIdIOHandlerStream = class(TIdIOHandler)
protected
FFreeStreams: Boolean;
FOnGetStreams: TIdOnGetStreams;
FReceiveStream: TStream;
FSendStream: TStream;
FStreamType: TIdIOHandlerStreamType;
//
procedure InitComponent; override;
function ReadDataFromSource(var VBuffer: TIdBytes): Integer; override;
function WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer; override;
function SourceIsAvailable: Boolean; override;
function CheckForError(ALastResult: Integer): Integer; override;
procedure RaiseError(AError: Integer); override;
public
function StreamingAvailable: Boolean;
procedure CheckForDisconnect(ARaiseExceptionIfDisconnected: Boolean = True;
AIgnoreBuffer: Boolean = False); override;
constructor Create(AOwner: TComponent; AReceiveStream: TStream; ASendStream: TStream = nil); reintroduce; overload; virtual;
constructor Create(AOwner: TComponent); reintroduce; overload;
function Connected: Boolean; override;
procedure Close; override;
procedure Open; override;
function Readable(AMSec: integer = IdTimeoutDefault): boolean; override;
//
property ReceiveStream: TStream read FReceiveStream;
property SendStream: TStream read FSendStream;
property StreamType: TIdIOHandlerStreamType read FStreamType;
published
property FreeStreams: Boolean read FFreeStreams write FFreeStreams;
//
property OnGetStreams: TIdOnGetStreams read FOnGetStreams write FOnGetStreams;
end;
implementation
uses
IdException, IdComponent, SysUtils;
{ TIdIOHandlerStream }
procedure TIdIOHandlerStream.InitComponent;
begin
inherited InitComponent;
FDefStringEncoding := Indy8BitEncoding;
end;
procedure TIdIOHandlerStream.CheckForDisconnect(
ARaiseExceptionIfDisconnected: Boolean = True;
AIgnoreBuffer: Boolean = False);
var
LDisconnected: Boolean;
begin
// ClosedGracefully // Server disconnected
// IOHandler = nil // Client disconnected
if ClosedGracefully then begin
if StreamingAvailable then begin
Close;
// Call event handlers to inform the user that we were disconnected
DoStatus(hsDisconnected);
//DoOnDisconnected;
end;
LDisconnected := True;
end else begin
LDisconnected := not StreamingAvailable;
end;
// Do not raise unless all data has been read by the user
if LDisconnected then begin
if (InputBufferIsEmpty or AIgnoreBuffer) and ARaiseExceptionIfDisconnected then begin
RaiseConnClosedGracefully;
end;
end;
end;
procedure TIdIOHandlerStream.Close;
begin
inherited Close;
if FreeStreams then begin
FreeAndNil(FReceiveStream);
FreeAndNil(FSendStream);
end;
end;
function TIdIOHandlerStream.StreamingAvailable: Boolean;
begin
Result := False; // Just to avoid warning message
case FStreamType of
stRead: Result := Assigned(ReceiveStream);
stWrite: Result := Assigned(SendStream);
stReadWrite: Result := Assigned(ReceiveStream) and Assigned(SendStream);
end;
end;
function TIdIOHandlerStream.Connected: Boolean;
begin
Result := (StreamingAvailable and inherited Connected) or (not InputBufferIsEmpty);
end;
constructor TIdIOHandlerStream.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FFreeStreams := True;
FStreamType := stReadWrite;
end;
constructor TIdIOHandlerStream.Create(AOwner: TComponent; AReceiveStream: TStream;
ASendStream: TStream = nil);
begin
inherited Create(AOwner);
//
FFreeStreams := True;
FReceiveStream := AReceiveStream;
FSendStream := ASendStream;
//
if Assigned(FReceiveStream) and (not Assigned(FSendStream)) then begin
FStreamType := stRead;
end else if (not Assigned(FReceiveStream)) and Assigned(FSendStream) then begin
FStreamType := stWrite;
end else begin
FStreamType := stReadWrite;
end;
end;
procedure TIdIOHandlerStream.Open;
begin
inherited Open;
if Assigned(OnGetStreams) then begin
OnGetStreams(Self, FReceiveStream, FSendStream);
end;
if Assigned(FReceiveStream) and (not Assigned(FSendStream)) then begin
FStreamType := stRead;
end else if (not Assigned(FReceiveStream)) and Assigned(FSendStream) then begin
FStreamType := stWrite;
end else begin
FStreamType := stReadWrite;
end;
end;
function TIdIOHandlerStream.Readable(AMSec: Integer): Boolean;
begin
Result := Assigned(ReceiveStream);
// RLebeau: not checking the Position anymore. Was
// causing deadlocks when trying to read past EOF.
// This way, when EOF is reached, ReadFromSource()
// will return 0, which will be interpretted as the
// connnection being closed...
{
if Result then begin
Result := ReceiveStream.Position < ReceiveStream.Size;
end;
}
end;
function TIdIOHandlerStream.ReadDataFromSource(var VBuffer: TIdBytes): Integer;
begin
// We dont want to read the whole stream in at a time. If its a big
// file will consume way too much memory by loading it all at once.
// So lets read it in chunks.
if Assigned(FReceiveStream) then begin
Result := IndyMin(32 * 1024, Length(VBuffer));
if Result > 0 then begin
Result := TIdStreamHelper.ReadBytes(FReceiveStream, VBuffer, Result);
end;
end else begin
Result := 0;
end;
end;
function TIdIOHandlerStream.WriteDataToTarget(const ABuffer: TIdBytes; const AOffset, ALength: Integer): Integer;
begin
if Assigned(FSendStream) then begin
Result := TIdStreamHelper.Write(FSendStream, ABuffer, ALength, AOffset);
end else begin
Result := IndyLength(ABuffer, ALength, AOffset);
end;
end;
function TIdIOHandlerStream.SourceIsAvailable: Boolean;
begin
Result := Assigned(ReceiveStream);
end;
function TIdIOHandlerStream.CheckForError(ALastResult: Integer): Integer;
begin
Result := ALastResult;
if Result < 0 then begin
raise EIdException.Create('Stream error'); {do not localize}
end;
end;
procedure TIdIOHandlerStream.RaiseError(AError: Integer);
begin
raise EIdException.Create('Stream error'); {do not localize}
end;
end.
|
unit untSendingData;
interface
type
TSendingData=class
private
bPilotSymbol:byte;
bCommandLength:byte;
wSubstationAddress:Word;
bCommandType:byte;
bYear, bMonth, bDay, bHour, bMinute, bSecond:byte;
bolClearCommEquipment:boolean;
bolClearIntterupt:boolean;
bolOutgoingData:boolean;
bolClearLastRecord:boolean;
bMaxNumberPeople:byte;
bAlarm:byte;
bWarning:byte;
bOtherCommands:byte;
bHighRandomCode, bLowRandomCode:byte;
bCRC16H:byte;
bCRC16L:byte;
public
property PilotSymbol:byte read bPilotSymbol write bPilotSymbol;
property CommandLength: byte read bCommandLength write bCommandLength;
property SubStationAddress: Word read wSubstationAddress write wSubstationAddress;
property CommandType:byte read bCommandType write bCommandType;
property ClearCommunicationDevice: boolean read bolClearCommEquipment write bolClearCommEquipment;
property ClearIntterupts: boolean read bolClearIntterupt write bolClearIntterupt;
property OutgoingData: boolean read bolOutgoingData write bolOutgoingData;
property ClearLastRecords: boolean read bolClearLastRecord write bolClearLastRecord;
property MaxNumberPeopleReading: byte read bMaxNumberPeople write bMaxNumberPeople;
property Alarm: byte read bAlarm write bAlarm;
property Warning: byte read bWarning write bWarning;
property OtherCommands: byte read bOtherCommands write bOtherCommands;
constructor Create;
end;
implementation
{ TSendingData }
constructor TSendingData.Create;
begin
bPilotSymbol:=$7E;
bCommandType:=$46;
end;
end.
|
(*
_______________________________________________________________________
| |
| CONFIDENTIAL MATERIALS |
| |
| These materials include confidential and valuable trade secrets owned |
| by JP Software Inc. or its suppliers, and are provided to you under |
| the terms of a non-disclosure agreement. These materials may not be |
| transmitted or divulged to others or received, viewed, or used by |
| others in any way. All source code, source code and technical |
| documentation, and related notes, are unpublished materials, except |
| to the extent that they are in part legally available as published |
| works from other suppliers, and use of a copyright notice below does |
| not imply publication of these materials. |
| |
| This notice must remain as part of these materials and must not be |
| removed. |
| |
| Unpublished work, Copyright 1988, 1989, 1990, 1991, J.P. Software |
| Inc., All Rights Reserved. Portions Copyright 1985, 1987, Borland |
| International Inc. |
|_______________________________________________________________________|
*)
{ EDITOOLS.INC
Editor Toolbox 4.0
Copyright (c) 1985, 87 by Borland International, Inc. }
{$I-}
{$S-}
{$R-}
unit EDItools;
interface
uses
tpCrt, {standard screen routines}
Dos, {dos calls - standard unit}
SInst; {fast screen routines}
const
KeyLength = 6; {maximum bytes in keystroke sequence}
Escape = #27;
type
VarString = string[DefNoCols];
KeyString = string[KeyLength];
KeyRec =
record
Modified,
Conflict : Boolean;
Keys : KeyString;
MinCol, MaxCol : Byte;
end;
var
BlankLine : VarString;
function FileExists(Name : VarString; var F : file) : Boolean;
{-return true and an open file if file exists}
Procedure FindFile(Var FileName : String);
{ -Search for the program file }
function GetCursorCommand : Char;
{-return cursor equivalent keys}
(*
function Getkey(Prompt, Choices : VarString) : Char;
{-return a legal menu choice}
function YesNo(Prompt : VarString; Default : Char) : Boolean;
{-return True for yes, False for no}
procedure ClrEol(Col, Row, Attr : Integer);
{-clear to end of line}
*)
procedure HaltError(msg : varstring);
{-display an error message and halt}
function FindString(IdString : String; var Deft; Size : Word) : LongInt;
{-return the location of IdString in ProgramFile and read Size bytes into
Deft.}
function ModifyDefaults(FileOfst : LongInt; var B; Size : Word) : Boolean;
{-Write modified default settings back to disk, returning a success flag}
procedure Initialize(Name, Title : String);
{-Set up for installation}
procedure CleanUp;
{-Clean up at end of program}
{==========================================================================}
implementation
const
SBSize = 65518;
type
SearchBuffer = array[0..SBSize] of Char; {Used to search for ID strings}
var
ProgramFile : file;
ProgramName : string;
BufPtr : ^SearchBuffer;
BytesRead : Word;
FilePtr : LongInt;
BufferFull : Boolean;
function FileExists(Name : VarString; var F : file) : Boolean;
{-return true and an open file if file exists}
begin
Assign(F, Name);
Reset(F, 1);
FileExists := (IOResult = 0);
end; {fileexists}
Procedure FindFile(Var FileName : String);
var
SearchPath : String;
Dir : DirStr;
Name : NameStr;
Ext : ExtStr;
begin
SearchPath := ParamStr(0);
FSplit(SearchPath,Dir,Name,Ext);
SearchPath := Dir + ';' + GetEnv('PATH');
FileName := FSearch(FileName,SearchPath);
If FileName <> '' Then FileName := FExpand(FileName);
end;
function GetCursorCommand : Char;
{-return cursor equivalent keys. Also allows Esc, 'C', and 'R'.}
const
CursorSet : set of Char =
[^H, ^R, ^C, ^E, ^X, ^W, ^Z, ^A, ^S, ^D, ^F, ^M, 'C', 'R', ^T, ^B, ^U, #27, #254];
var
Ch : Char;
begin
repeat
Ch := ReadKey;
if (Ch = #0) then begin
Ch := ReadKey;
case Ch of
#75 : Ch := ^S;
#77 : Ch := ^D;
#72 : Ch := ^E;
#80 : Ch := ^X;
#71 : Ch := ^T;
#73 : Ch := ^R;
#81 : Ch := ^C;
#79 : Ch := ^B;
#82 : Ch := ^U;
#45 : Ch := #254; {Alt-X}
end;
end
else
Ch := UpCase(Ch);
until (Ch in CursorSet);
GetCursorCommand := Ch;
end; {GetCursorCommand}
(*
function Getkey(Prompt, Choices : VarString) : Char;
{-return a legal menu choice}
var
Ch : Char;
begin
Write(prompt);
repeat
Ch := UpCase(ReadKey);
until Pos(Ch, choices) <> 0;
Getkey := Ch;
end; {GetKey}
function YesNo(Prompt : VarString; Default : Char) : Boolean;
{-return True for yes, False for no}
const
{$IFDEF GERMAN}
YesChar = 'J';
NoChar = 'N';
DispStr = '(J/N/<Enter> fr '
{$ELSE}
YesChar = 'Y';
NoChar = 'N';
DispStr = '(Y/N/<Enter> for '
{$ENDIF}
var
Ch : Char;
begin
Write(Prompt, DispStr, Default, ') ');
repeat
Ch := ReadKey;
if Ch = ^M then
Ch := Default;
Ch := UpCase(Ch);
until (Ch = YesChar) or (Ch = NoChar);
WriteLn(Ch);
YesNo := (Ch = YesChar);
end; {YesNo}
procedure ClrEol(Col, Row, Attr : Integer);
{-clear to end of line}
begin
BlankLine[0] := Chr(81-Col);
FastWrite(BlankLine, Row, Col, Attr);
end;
*)
procedure HaltError(Msg : Varstring);
{-Display an error message and halt}
begin {HaltError}
RestoreScreen;
WriteLn;
WriteLn(Msg);
Halt(1);
end; {HaltError}
{$L SEARCH}
{$F+}
function Search(var Buffer; BufLength : Word; St : String) : Word; external;
{-Search through Buffer for St. BufLength is length of range to search.
Returns 0 if not found. Otherwise, the result is the index into an
array whose lower bound is 1. Subtract 1 for 0-based arrays.}
{$F-}
function FindString(IdString : String; var Deft; Size : Word) : LongInt;
{-return the location of IdString in ProgramFile and read Size bytes into
Deft.}
const
{$IFDEF GERMAN}
SeekErrorMsg : string[30] = 'Positionierfehler beim Lesen von ';
ReadErrorMsg : string[22] = 'Ein- Ausgabefehler beim Lesen von ';
{$ELSE}
SeekErrorMsg : string[30] = 'Seek error while reading from ';
ReadErrorMsg : string[22] = 'I/O error reading from ';
{$ENDIF}
var
I, BufPos,
IdSize, BufSize : Word;
FSTemp : LongInt;
label
FoundIdString;
begin
IdSize := Succ(Length(IdString));
BufSize := SizeOf(SearchBuffer);
{if we have a full buffer, see if it contains the ID string}
if BufferFull then begin
BufPos := Search(BufPtr^, BytesRead, IdString);
if BufPos <> 0 then
goto FoundIdString;
end;
{point at start of file}
Seek(ProgramFile, 0);
if (IOResult <> 0) then
HaltError(SeekErrorMsg + ProgramName);
{Read the first bufferful}
BlockRead(ProgramFile, BufPtr^, BufSize, BytesRead);
if (IOResult <> 0) then
HaltError(ReadErrorMsg + ProgramName);
{set flag to indicate the buffer is full}
BufferFull := True;
{keep track of file pointer}
FilePtr := BytesRead;
{scan the first buffer}
BufPos := Search(BufPtr^, BytesRead, IdString);
{loop until IdString found or end of file reached}
while (BufPos = 0) and (BytesRead > IdSize) do begin
{Move the tail end of the buffer to the front of the buffer}
Move(BufPtr^[BytesRead-IdSize], BufPtr^, IdSize);
{Read the next bufferful}
BlockRead(ProgramFile, BufPtr^[IdSize], BufSize-IdSize, BytesRead);
{keep track of where we are in the file}
FilePtr := FilePtr + BytesRead;
{adjust BytesRead to indicate the actual number of bytes in the buffer}
BytesRead := BytesRead + IdSize;
{search the buffer for the IdString}
BufPos := Search(BufPtr^, BytesRead, IdString);
end;
FoundIdString:
if (BufPos = 0) then
FSTemp := 0
else begin
{account for fact that BufPtr^ is a 0-based array}
Dec(BufPos);
{calculate the actual position in the file}
FSTemp := (FilePtr - BytesRead) + BufPos + IdSize;
{get the existing default parameter area into Deft}
{Use contents of existing buffer if possible}
if (BytesRead - BufPos) > Size then
Move(BufPtr^[BufPos + IdSize], Deft, Size)
else begin
{seek to the right location}
Seek(ProgramFile, FSTemp);
if (IOResult <> 0) then
HaltError(SeekErrorMsg + ProgramName);
{read directly into Deft from ProgramFile}
BlockRead(ProgramFile, Deft, Size, I);
if I <> Size then
HaltError(ReadErrorMsg + ProgramName);
end;
end;
FindString := FSTemp;
end; {findstring}
function ModifyDefaults(FileOfst : LongInt; var B; Size : Word) : Boolean;
{-Write modified default settings back to disk, returning a success flag}
var
BytesWritten : Word;
begin {ModifyDefaults}
{seek into file}
Seek(ProgramFile, FileOfst);
if (IOResult <> 0) then
{$IFDEF GERMAN}
HaltError('Positionierfehler beim Schreiben von '+ ProgramName);
{$ELSE}
HaltError('Seek error while writing to '+ ProgramName);
{$ENDIF}
{write modified defaults}
BlockWrite(ProgramFile, B, Size, BytesWritten);
{return success/failure flag}
ModifyDefaults := (BytesWritten = Size);
end; {ModifyDefaults}
procedure Initialize(Name, Title : String);
{-Set up for installation}
var
ScreenOfs : longint;
begin {Initialize}
{setup screen}
SetColor(TiColor);
ClrScr;
{save the name of the program for other routines}
ProgramName := Name;
{signon message}
WriteLn(^M^J, Title, ^M^J);
{Make sure executable file is found}
FindFile(ProgramName);
{$IFDEF GERMAN}
If ProgramName = '' Then
HaltError('Ausfhrbares Programm '+ProgramName+' nicht gefunden');
if not(FileExists(ProgramName, ProgramFile)) then
HaltError('Ausfhrbares Programm '+ProgramName+' nicht gefunden');
{$ELSE}
If ProgramName = '' Then
HaltError('Executable file '+ProgramName+' not found');
if not(FileExists(ProgramName, ProgramFile)) then
HaltError('Executable file '+ProgramName+' not found');
{$ENDIF}
{get a work area}
New(BufPtr);
BufferFull := False;
{anything else}
FillChar(BlankLine[1], 80, #32);
end; {Initialize}
procedure CleanUp;
{-Clean up at end of program}
begin {CleanUp}
Close(ProgramFile);
RestoreScreen;
end; {CleanUp}
end.
|
{
DBAExplorer - Oracle Admin Management Tool
Copyright (C) 2008 Alpaslan KILICKAYA
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
}
unit OraDirectory;
interface
uses Classes, SysUtils, Ora, OraStorage, DB, DBQuery, Forms, Dialogs, VirtualTable;
type
TDBDirectory = class(TObject)
private
FOWNER,
FDIRECTORY_NAME,
FDIRECTORY_PATH: string;
FOraSession: TOraSession;
function GetStatus: string;
function GetDBDirectoryDetail: String;
public
property OWNER: String read FOWNER write FOWNER;
property DIRECTORY_NAME: String read FDIRECTORY_NAME write FDIRECTORY_NAME;
property DIRECTORY_PATH: String read FDIRECTORY_PATH write FDIRECTORY_PATH;
property Status: String read GetStatus;
property OraSession: TOraSession read FOraSession write FOraSession;
procedure SetDDL;
function GetDDL: string;
function GetAlterDDL: string;
function CreateDBDirectory(Script: string) : boolean;
function AlterDBDirectory(Script: string) : boolean;
function DropDBDirectory: boolean;
constructor Create;
destructor Destroy; override;
end;
function GetDBDirectories(): string;
implementation
uses Util, frmSchemaBrowser, OraScripts, Languages;
resourcestring
strDBDirectoryDropped = 'Directory %s has been dropped.';
strDBDirectoryAltered = 'Directory %s has been altered.';
strDBDirectoryCreated = 'Directory %s has been created.';
function GetDBDirectories(): string;
begin
result := 'select * from SYS.DBA_DIRECTORIES '
+' order by DIRECTORY_NAME ';
end;
constructor TDBDirectory.Create;
begin
inherited;
end;
destructor TDBDirectory.destroy;
begin
inherited;
end;
function TDBDirectory.GetDBDirectoryDetail: String;
begin
Result :=
'Select * '
+' from DBA_DIRECTORIES '
+'WHERE DIRECTORY_NAME = :pName ';
end;
function TDBDirectory.GetStatus: string;
var
q1: TOraQuery;
begin
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetObjectStatusSQL;
q1.ParamByName('pOName').AsString := FDIRECTORY_NAME;
q1.ParamByName('pOType').AsString := 'DIRECTORY';
q1.ParamByName('pOwner').AsString := 'SYS';
q1.Open;
result := FDIRECTORY_NAME+' ( Created: '+q1.FieldByName('CREATED').AsString
+' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString
+' Status: '+q1.FieldByName('STATUS').AsString
+' )';
q1.Close;
end;
procedure TDBDirectory.SetDDL;
var
q1: TOraQuery;
begin
if FDIRECTORY_NAME = '' then exit;
if FOWNER = '' then exit;
q1 := TOraQuery.Create(nil);
q1.Session := OraSession;
q1.SQL.Text := GetDBDirectoryDetail;
q1.ParamByName('pName').AsString := FDIRECTORY_NAME;
q1.Open;
FDIRECTORY_NAME := q1.FieldByName('DIRECTORY_NAME').AsString;
FDIRECTORY_PATH := q1.FieldByName('DIRECTORY_PATH').AsString;
Q1.close;
end;
function TDBDirectory.GetDDL: string;
begin
result := 'CREATE OR REPLACE DIRECTORY '+FDIRECTORY_NAME+' AS '+Str(FDIRECTORY_PATH);
end;
function TDBDirectory.GetAlterDDL: string;
begin
result := 'CREATE OR REPLACE DIRECTORY '+FDIRECTORY_NAME+' AS '+Str(FDIRECTORY_PATH);
end;
function TDBDirectory.CreateDBDirectory(Script: string) : boolean;
begin
result := false;
if FDIRECTORY_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strDBDirectoryCreated',strDBDirectoryCreated),[FDIRECTORY_NAME]), FOraSession);
end;
function TDBDirectory.AlterDBDirectory(Script: string) : boolean;
begin
result := false;
if FDIRECTORY_NAME = '' then exit;
result := ExecSQL(Script, Format(ChangeSentence('strDBDirectoryAltered',strDBDirectoryAltered),[FDIRECTORY_NAME]), FOraSession);
end;
function TDBDirectory.DropDBDirectory: boolean;
var
FSQL: string;
begin
result := false;
if FDIRECTORY_NAME = '' then exit;
FSQL := 'drop DIRECTORY '+FDIRECTORY_NAME;
result := ExecSQL(FSQL, Format(ChangeSentence('strDBDirectoryDropped',strDBDirectoryDropped),[FDIRECTORY_NAME]), FOraSession);
end;
end.
|
unit NLDTManager;
{
:: The NLDTranslate Manager provides the management of language files
:: and distribution among the translators.
:$
:$
:$ NLDTranslate is released under the zlib/libpng OSI-approved license.
:$ For more information: http://www.opensource.org/
:$ /n/n
:$ /n/n
:$ Copyright (c) 2002 M. van Renswoude
:$ /n/n
:$ 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.
:$ /n/n
:$ 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:
:$ /n/n
:$ 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.
:$ /n/n
:$ 2. Altered source versions must be plainly marked as such, and must not be
:$ misrepresented as being the original software.
:$ /n/n
:$ 3. This notice may not be removed or altered from any source distribution.
}
{$I NLDTDefines.inc}
{TODO Automatically list language files at startup if appropriate}
{TODO Provide events for adding/removing of items in the Files collection}
interface
uses
SysUtils,
Classes,
XDOM_2_3,
NLDTInterfaces,
NLDTGlobal;
type
{
:$ Holds a single language file.
:: TNLDTFile is used by TNLDTFiles. It holds the filename and parsed
:: description of the language.
}
TNLDTFile = class(TCollectionItem)
private
FDescription: String;
FFilename: String;
protected
procedure SetFilename(const Value: String); virtual;
public
procedure Assign(Source: TPersistent); override;
published
property Description: String read FDescription;
property Filename: String read FFilename write SetFilename;
end;
{
:$ Holds a collection of language files.
:: TNLDTFiles holds a collection of language files which are loaded
:: by the manager. There is generally no need to use TNLDTFiles directly,
:: it is used internally by the manager.
}
TNLDTFiles = class(TCollection)
private
function GetItem(Index: Integer): TNLDTFile;
procedure SetItem(Index: Integer; const Value: TNLDTFile);
public
constructor Create();
//:$ Adds a new language file
//:: Add returns a new TNLDTFile instance.
function Add(const AFilename: String): TNLDTFile;
//:$ Inserts a new language file
//:: Inserts a new TNLDTFile instance at the specified position and
//:: returns the newly created instance.
function Insert(Index: Integer): TNLDTFile;
//:$ Find a file
//:: FindFile searches for a TNLDTFile item using the specified
//:: filename. Returns nil if no item was found. The search is performed
//:: case-insensitive.
function Find(const AFilename: String): TNLDTFile;
//:$ Find a file by it's description
//:: FindByDesc searches for a TNLDTFile item using the specified
//:: description. Returns nil if no item was found. The search is performed
//:: case-insensitive.
function FindByDesc(const ADescription: String): TNLDTFile;
//:$ Provides indexed access to the files in the collection.
//:: Use the Items property to get indexed access to all the files
//:: in the collection. Index is a value between 0 and Count - 1.
property Items[Index: Integer]: TNLDTFile read GetItem
write SetItem; default;
end;
TNLDTManagerStates = (msLoading);
TNLDTManagerState = set of TNLDTManagerStates;
{
:$ Manages the available languages.
:: TNLDTManager is the core component for listing and loading language
:: files. It is responsible for passing this information to all connected
:: sources, such as TNLDTranslate.
}
TCustomNLDTManager = class(TNLDTBaseComponent, INLDTInterface,
INLDTEventSink, INLDTManager)
private
FEvents: TInterfaceList;
FFiles: TNLDTFiles;
FActiveFile: TNLDTFile;
FState: TNLDTManagerState;
FAutoUndo: Boolean;
FFilter: String;
FPath: String;
protected
procedure SetActiveFile(const Value: TNLDTFile); virtual;
procedure SetFiles(const Value: TNLDTFiles); virtual;
procedure SetFilter(const Value: String); virtual;
procedure SetPath(const Value: String); virtual;
procedure Changed(); virtual;
procedure ProcessSection(const ANode: TDomElement;
const AInterested: TInterfaceList); virtual;
function IsRuntime(): Boolean; virtual;
procedure Loaded(); override;
// INLDTManager implementation
procedure AddFile(const AFilename: String); virtual; stdcall;
procedure RemoveFile(const AFilename: String); virtual; stdcall;
procedure ClearFiles(); virtual; stdcall;
// Properties (only available to descendants)
property Events: TInterfaceList read FEvents;
// Properties (published in TNLDTManager)
//:$ Determines whether changes should be automatically reverted
//:: Set AutoUndo to True to revert any language changes when ActiveFile
//:: is changed.
property AutoUndo: Boolean read FAutoUndo write FAutoUndo;
//:$ Determines the filter to use when searching for language files
//:: Set Filter to a DOS-style file filter (for example: *.lng) to list
//:: all files matching that filter.
property Filter: String read FFilter write SetFilter;
//:$ Determines the path to use when searching for language files
//:: Set Path to the path which contains the language files.
property Path: String read FPath write SetPath;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
//:$ Reverts all language changes
//:: Undo reverts any changes made by the language file. Undo itself does
//:: perform any modifications, instead it notifies each registered
//:: INLDTranslate interface.
procedure Undo();
// INLDTManager implementation
//:$ List language files in the specified path.
//:: LoadFromPath lists all language files which match AFilter
//:: and adds it to the Files property. AFilter follows standard
//:: file mask rules, for example: '*.lng'.
procedure LoadFromPath(const APath, AFilter: String;
const ASubDirs: Boolean = False); virtual; stdcall;
// INLDTEventSink implementation
//:$ Register an event interface
//:: Registers an event object in the internal event table. TNLDTManager
//:: will raise events for the following interfaces:
//:: /n/n
//:: - INLDTFileChangeEvent /n
//:: - INLDTTreeWalkEvent /n
procedure RegisterEvent(const AEvent: INLDTEvent); virtual; stdcall;
//:$ Unregister an event interface
//:: Unregisters a previously registered event object.
//:: See also: RegisterEvent
procedure UnregisterEvent(const AEvent: INLDTEvent); virtual; stdcall;
// Public properties
//:$ Determines the currently active language file
//:: Set ActiveFile to an item from the Files collection to apply the
//:: language file. If ActiveFile is set to nil and AutoUndo is set to
//:: True, all changes will be reverted.
property ActiveFile: TNLDTFile read FActiveFile write SetActiveFile;
//:$ Contains the available language files
//:: Files contains a list of language files which were found either by
//:: implicitly calling LoadFromPath, or explicitly setting the Filter
//:: and Path properties.
property Files: TNLDTFiles read FFiles write SetFiles;
end;
TNLDTManager = class(TCustomNLDTManager)
published
property AutoUndo;
property Filter;
property Path;
end;
implementation
uses
{$IFDEF NLDT_FASTSTRINGS}
FastStrings,
{$ENDIF}
NLDTXDOMUtils;
{*************************************** TNLDTFile
Assign
**************************************************}
procedure TNLDTFile.Assign(Source: TPersistent);
begin
if Source is TNLDTFile then
with TNLDTFile(Source) do begin
Self.FDescription := Description;
Self.FFilename := Filename;
end
else
inherited;
end;
{*************************************** TNLDTFile
Load language file
**************************************************}
procedure TNLDTFile.SetFilename;
const
CNodeBegin: String = '<language';
CNodeEnd: String = '>';
CDescBegin: String = 'description="';
CDescEnd: String = '"';
var
fTemp: TextFile;
sData: String;
sLine: String;
iStart: Integer;
iEnd: Integer;
bStart: Boolean;
begin
if FFilename <> Value then begin
if not FileExists(Value) then
raise ENLDTFileDoesNotExist.Create('''' + Value + ''' does not exist!');
FFilename := Value;
FDescription := '(unknown)';
sData := '';
bStart := False;
// Get description from the file
AssignFile(fTemp, FFilename);
try
Reset(fTemp);
while not Eof(fTemp) do begin
ReadLn(fTemp, sLine);
sData := sData + ' ' + Trim(sLine);
if Length(sLine) > 0 then begin
if not bStart then begin
// Check for starting tag
{$IFDEF NLDT_FASTSTRINGS}
iStart := FastPos(sData, CNodeBegin, Length(sData),
Length(CNodeBegin), 1);
{$ELSE}
iStart := AnsiPos(CNodeBegin, sData);
{$ENDIF}
if iStart > 0 then begin
Delete(sData, 1, iStart + Length(CNodeBegin) - 1);
bStart := True;
end;
end;
if bStart then begin
// Check for ending tag
{$IFDEF NLDT_FASTSTRINGS}
iEnd := FastPos(sData, CNodeEnd, Length(sData),
Length(CNodeEnd), 1);
{$ELSE}
iEnd := AnsiPos(CNodeEnd, sData);
{$ENDIF}
if iEnd > 0 then begin
SetLength(sData, iEnd - 1);
// Find attribute start
{$IFDEF NLDT_FASTSTRINGS}
iStart := FastPos(sData, CDescBegin, Length(sData),
Length(CDescBegin), 1);
{$ELSE}
iStart := AnsiPos(CDescBegin, sData);
{$ENDIF}
if iStart > 0 then begin
Delete(sData, 1, iStart + Length(CDescBegin) - 1);
// Find attribute end
{$IFDEF NLDT_FASTSTRINGS}
iEnd := FastPos(sData, CDescEnd, Length(sData),
Length(CDescEnd), 1);
{$ELSE}
iEnd := AnsiPos(CDescEnd, sData);
{$ENDIF}
if iEnd > 0 then begin
SetLength(sData, iEnd - 1);
FDescription := XDOMEntityToChar(sData);
end;
end;
break;
end;
end;
end;
end;
finally
CloseFile(fTemp);
end;
end;
end;
{************************************** TNLDTFiles
TCollectionItem implementation
**************************************************}
constructor TNLDTFiles.Create;
begin
inherited Create(TNLDTFile);
end;
function TNLDTFiles.Find;
var
iItem: Integer;
begin
Result := nil;
for iItem := Count - 1 downto 0 do
if CompareText(Items[iItem].Filename, AFilename) = 0 then begin
Result := Items[iItem];
exit;
end;
end;
function TNLDTFiles.FindByDesc;
var
iItem: Integer;
begin
Result := nil;
for iItem := Count - 1 downto 0 do
if CompareText(Items[iItem].Description, ADescription) = 0 then begin
Result := Items[iItem];
exit;
end;
end;
function TNLDTFiles.Add;
begin
Result := TNLDTFile(inherited Add());
Result.Filename := AFilename;
end;
function TNLDTFiles.Insert;
begin
Result := TNLDTFile(inherited Insert(Index));
end;
function TNLDTFiles.GetItem;
begin
Result := TNLDTFile(inherited GetItem(Index));
end;
procedure TNLDTFiles.SetItem;
begin
inherited SetItem(Index, Value);
end;
{****************************** TCustomNLDTManager
Con/destructor
**************************************************}
constructor TCustomNLDTManager.Create;
begin
inherited;
FEvents := TInterfaceList.Create();
FFiles := TNLDTFiles.Create();
FFilter := '*.lng';
FPath := '{APPPATH}';
FAutoUndo := True;
end;
destructor TCustomNLDTManager.Destroy;
var
iEvent: Integer;
begin
// Notify each event interface
for iEvent := FEvents.Count - 1 downto 0 do
(FEvents[iEvent] as INLDTEvent).Detach(Self);
FreeAndNil(FEvents);
FreeAndNil(FFiles);
inherited;
end;
procedure TCustomNLDTManager.Loaded;
begin
inherited;
LoadFromPath(FPath, FFilter, False);
Changed();
end;
function TCustomNLDTManager.IsRuntime;
begin
Result := (not (csLoading in ComponentState)) and
(not (csDesigning in ComponentState));
end;
{****************************** TCustomNLDTManager
INLDTManager implementation
**************************************************}
procedure TCustomNLDTManager.AddFile;
begin
if FFiles.Find(AFilename) = nil then
FFiles.Add(AFilename);
end;
procedure TCustomNLDTManager.RemoveFile;
var
pFile: TNLDTFile;
begin
pFile := FFiles.Find(AFilename);
if Assigned(pFile) then
FFiles.Delete(pFile.Index);
end;
procedure TCustomNLDTManager.ClearFiles;
begin
FFiles.Clear();
end;
procedure TCustomNLDTManager.LoadFromPath;
var
sPath: String;
pFile: TSearchRec;
begin
if (Length(APath) = 0) or (Length(AFilter) = 0) then
exit;
// Prevent files from getting cleared when searching subdirectories
if not (msLoading in FState) then
FFiles.Clear();
Include(FState, msLoading);
sPath := NLDTReplacePathVars(APath);
sPath := NLDTIncludeDelimiter(sPath);
if DirectoryExists(sPath) then begin
if FindFirst(sPath + AFilter, faAnyFile, pFile) = 0 then begin
repeat
// Filter out directories
if (pFile.Attr and faDirectory) = 0 then
FFiles.Add(sPath + pFile.Name);
until FindNext(pFile) <> 0;
FindClose(pFile);
end;
// List sub-directories if requested
if ASubDirs then
if FindFirst(sPath + '*.', faDirectory, pFile) = 0 then begin
repeat
// Filter out parent directories
if (pFile.Name <> '.') and (pFile.Name <> '..') then
LoadFromPath(sPath + pFile.Name, AFilter, ASubDirs);
until FindNext(pFile) <> 0;
FindClose(pFile);
end;
end;
Exclude(FState, msLoading);
end;
procedure TCustomNLDTManager.RegisterEvent;
begin
FEvents.Add(AEvent)
end;
procedure TCustomNLDTManager.UnregisterEvent;
var
iIndex: Integer;
begin
iIndex := FEvents.IndexOf(AEvent);
if iIndex > -1 then
FEvents.Delete(iIndex);
end;
{****************************** TCustomNLDTManager
Undo
**************************************************}
procedure TCustomNLDTManager.Undo;
var
iEvent: Integer;
ifTranslate: INLDTranslate;
begin
for iEvent := 0 to FEvents.Count - 1 do
if FEvents[iEvent].QueryInterface(IID_INLDTranslate, ifTranslate) = 0 then begin
ifTranslate.Undo();
ifTranslate := nil;
end;
end;
{****************************** TCustomNLDTManager
Load language file
**************************************************}
procedure TCustomNLDTManager.Changed;
var
xmlDom: TDomImplementation;
xmlDoc: TDomDocument;
xmlParser: TXmlToDomParser;
xmlRoot: TDomElement;
xmlSection: TDomElement;
pInterested: TInterfaceList;
iEvent: Integer;
ifTreeWalk: INLDTTreeWalkEvent;
ifItem: INLDTTreeItem;
begin
// Make sure we're not in design time or loading (loading only happens
// when the component is not dynamically created, in that case the Loaded
// procedure will trigger this method again)
if (csDesigning in ComponentState) or (csLoading in ComponentState) then
exit;
// Make sure there is an active file and it exists
if (not Assigned(FActiveFile)) or (not FileExists(FActiveFile.Filename)) then begin
// Undo any changes
if FAutoUndo then
Undo();
exit;
end;
xmlDom := TDomImplementation.Create(nil);
try
xmlParser := TXmlToDomParser.Create(nil);
try
// Parse language file
xmlParser.DOMImpl := xmlDom;
xmlDoc := xmlParser.fileToDom(FActiveFile.Filename);
try
// Undo any changes
if FAutoUndo then
Undo();
xmlRoot := xmlDoc.documentElement;
pInterested := TInterfaceList.Create();
try
// Search for 'sections'
xmlSection := xmlRoot.findFirstChildElement();
while Assigned(xmlSection) do begin
// Build list of interested translators
pInterested.Clear();
for iEvent := 0 to FEvents.Count - 1 do
if FEvents[iEvent].QueryInterface(IID_INLDTTreeWalkEvent, ifTreeWalk) = 0 then begin
ifItem := TNLDTTreeItem.Create(xmlSection);
try
if ifTreeWalk.QuerySection(ifItem) then
pInterested.Add(ifTreeWalk);
finally
ifItem := nil;
end;
ifTreeWalk := nil;
end;
// Start recursive looping trough sub-items
ProcessSection(xmlSection, pInterested);
xmlSection := xmlSection.findNextSiblingElement();
end;
finally
FreeAndNil(pInterested);
end;
finally
xmlDom.freeDocument(xmlDoc);
end;
finally
FreeAndNil(xmlParser);
end;
finally
FreeAndNil(xmlDom);
end;
end;
procedure TCustomNLDTManager.ProcessSection;
procedure InternalProcessSection(const ANode: TDomElement;
const AInterested: TInterfaceList;
const AProcess: array of Boolean);
var
xmlNode: TDomElement;
iEvent: Integer;
ifItem: INLDTTreeItem;
bProcess: array of Boolean;
begin
SetLength(bProcess, High(AProcess) + 1);
for iEvent := High(AProcess) downto 0 do
bProcess[iEvent] := AProcess[iEvent];
xmlNode := ANode.findFirstChildElement();
while Assigned(xmlNode) do begin
ifItem := TNLDTTreeItem.Create(xmlNode);
try
// Query interested interfaces
for iEvent := AInterested.Count - 1 downto 0 do
if bProcess[iEvent] then
bProcess[iEvent] := INLDTTreeWalkEvent(AInterested[iEvent]).QueryTreeItem(ifItem);
// Process sub-nodes
InternalProcessSection(xmlNode, AInterested, bProcess);
// Let interested interfaces know we're done with the node
for iEvent := AInterested.Count - 1 downto 0 do
if bProcess[iEvent] then
INLDTTreeWalkEvent(AInterested[iEvent]).EndTreeItem(ifItem);
finally
ifItem := nil;
end;
xmlNode := xmlNode.findNextSiblingElement();
end;
end;
var
bProcess: array of Boolean;
iProcess: Integer;
begin
SetLength(bProcess, AInterested.Count);
for iProcess := AInterested.Count - 1 downto 0 do
bProcess[iProcess] := True;
InternalProcessSection(ANode, AInterested, bProcess);
end;
{****************************** TCustomNLDTManager
Properties
**************************************************}
procedure TCustomNLDTManager.SetFiles;
begin
if Value <> FFiles then
FFiles.Assign(Value);
end;
procedure TCustomNLDTManager.SetFilter;
begin
if Value <> FPath then begin
FFilter := Value;
if IsRuntime() then
LoadFromPath(FPath, FFilter, False);
end;
end;
procedure TCustomNLDTManager.SetPath;
begin
if Value <> FPath then begin
FPath := Value;
if IsRuntime() then
LoadFromPath(FPath, FFilter, False);
end;
end;
procedure TCustomNLDTManager.SetActiveFile;
var
iEvent: Integer;
ifFileChange: INLDTFileChangeEvent;
begin
if Value <> FActiveFile then begin
FActiveFile := Value;
// Notify events
for iEvent := 0 to FEvents.Count - 1 do
if FEvents[iEvent].QueryInterface(IID_INLDTFileChangeEvent, ifFileChange) = 0 then begin
ifFileChange.FileChanged(Self);
ifFileChange := nil;
end;
Changed();
end;
end;
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 6.0 for Delphi and C++Builder ::
:: ::
:: QRMetricLab TQRMetricLabel ::
:: ::
:: Copyright (c) 2013 QBS Software ::
:: All Rights Reserved ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::}
unit QRMetricLab;
interface
uses Messages, Windows, Classes, Controls, StdCtrls, SysUtils, Graphics,
Forms, ExtCtrls, Dialogs, Printers, ComCtrls,
QRPrntr, QuickRpt, QR6Const, qrctrls;
type
TQRMetlabOnPrintEvent = procedure (sender : TObject; gcanvas : TCanvas; var printString : string) of object;
TSpacingMode = (Horiz, HorizAndVertical);
TQRMetricLabel = class(TQRCustomLabel)
private
FBeforePrint : TQRMetlabOnPrintEvent;
FSpacingMode : TSpacingMode;
FXlist : TStrings;
FYList : TStrings;
lzCaption : PChar;
procedure SetBeforePrint( value : TQRMetlabOnPrintEvent);
procedure SetXlist( value : TStrings);
procedure SetYlist( value : TStrings);
protected
procedure Paint; override;
procedure Print(OfsX, OfsY : integer); override;
public
FXValues : array[0..255] of integer;
FYValues : array[0..255] of integer;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Prepare;override;
published
property BeforePrint: TQRMetlabOnPrintEvent read FBeforePrint write SetBeforePrint;
property Autosize;
property Visible;
property XLColumn;
property Font;
property Transparent;
property color;
property Caption;
property SpacingMode : TSpacingMode read FSpacingMode write FSpacingMode;
property X_Spacing : TStrings read FXlist write SetXList;
property Y_Spacing : TStrings read FYlist write SetYlist;
end;
implementation
constructor TQRMetricLabel.Create(AOwner: TComponent);
begin
inherited create(AOwner);
FXList := TStringlist.Create;
FYList := TStringlist.Create;
end;
destructor TQRMetricLabel.Destroy;
begin
FXList.Free;
FYList.Free;
inherited Destroy;
end;
procedure TQRMetricLabel.SetBeforePrint( value : TQRMetlabOnPrintEvent);
begin
FBeforePrint := value;
end;
procedure TQRMetricLabel.SetXList(Value : TStrings);
begin
FXlist.Assign(Value);
end;
procedure TQRMetricLabel.SetYList(Value : TStrings);
begin
FYlist.Assign(Value);
end;
procedure TQRMetricLabel.Paint;
begin
inherited Paint;
end;
procedure TQRMetricLabel.Prepare;
var
clen, k : integer;
xscale : extended;
begin
inherited Prepare;
clen := length(caption);
if clen > 256 then caption := copy(caption,1,256);
if parentreport.QRPrinter.Destination = qrdPrinter then
begin
xscale := parentreport.QRPrinter.XFactor/(screen.PixelsPerInch/254);
end
else
xscale := 1.0;
for k := 0 to fxlist.Count-1 do FXValues[k] := round(strtoint(trim(FXList[k]))*xscale);
if fxlist.Count<clen then
begin
// pad out FXValues
for k := fxlist.Count to clen-1 do FXValues[k] := FXValues[fxlist.Count-1];
end;
end;
procedure TQRMetricLabel.Print(OfsX, OfsY : integer);
var
gcanvas : TCanvas;
CanvasRect : TRect ;
cRgn : HRGN ;
printString : string;
res, clen : integer;
xp, yp : integer;
ochar : char;
expshp : TQRShape;
begin
// determine the rectangle of the canvas of this control:
printString := caption;
CanvasRect.left := QRPrinter.XPos(OfsX + Size.Left);
CanvasRect.top := QRPrinter.YPos(OfsY + Size.Top);
CanvasRect.right := QRPrinter.XPos(OfsX + Size.Left + Size.Width);
CanvasRect.bottom := QRPrinter.YPos(OfsY + Size.Top + Size.Height);
gcanvas := TQuickrep(parentreport).QRPrinter.Canvas;
cRgn := CreateRectRgn(CanvasRect.left-1,CanvasRect.top-1,CanvasRect.right+1,CanvasRect.bottom+1);
SelectClipRgn(QRPrinter.Canvas.Handle,cRgn);
if gcanvas = nil then exit;
if not transparent then
begin
gcanvas.Brush.Color := color;
gcanvas.Brush.Style := bsSolid;
gcanvas.Pen.Color := color;
gcanvas.Pen.Style := psSolid;
gcanvas.Rectangle(CanvasRect.left, CanvasRect.top, CanvasRect.right, CanvasRect.bottom);
if parentreport.Exporting then
begin
expshp := TQRShape.Create(parentreport);
expshp.Top := top;
expshp.Left := left;
expshp.Width := width;
expshp.Height := height;
expshp.Shape := qrsRectangle;
expshp.Brush.Style := bsSolid;
expshp.Brush.Color := self.color;
expshp.Pen.Style := psClear;
parentreport.ExportFilter.AcceptGraphic(CanvasRect.left,CanvasRect.top, expshp);
expshp.Free;
end;
end;
gcanvas.Font.Assign(self.Font);
if assigned( FBeforePrint) and enabled then
FBeforePrint( self, gCanvas, printString );
caption := printString;
clen := length(Caption);
lzCaption := stralloc(clen+1);
for res := 1 to clen do lzCaption[res-1] := Caption[res];
lzCaption[clen] := chr(0);
// print it
ExtTextOutW(gcanvas.Handle, CanvasRect.left, CanvasRect.top,0, nil, lzCaption, clen, @FXValues);
SelectClipRgn(QRPrinter.Canvas.Handle,0);
deleteObject(cRgn);
// export characters
if not parentreport.Exporting then exit;
xp := CanvasRect.left;
yp := CanvasRect.Top;
for res := 1 to clen do
begin
ochar := caption[res];
parentreport.ExportFilter.TextOut(2.65*xp,2.65*yp, font, color,taLeftJustify,ochar);
xp := xp + FXValues[res-1];
end;
end;
end.
|
unit furqTypes;
interface
uses
SysUtils;
const
//chEOL = #0;
chTAB = #9;
type
TCharSet = set of Char;
// виды состояний контекста
TFURQContextState = (
csRun, // выполнение кода
csEnd, // ждем нажатия кнопки-действия (если их список непустой) или квест завершен
csInput, // ждем ввода числа/строки
csInputKey, // ждем нажатия клавиши
csQuit, // немедленный выход из программы
//csCls, // надо очистить экран
//csSound, // требуется проиграть звук
//csMusic, // требуется проиграть музыку
csPause, // ждем некоторое время
csSave, // требуется сохранение игры
//csUpdate // требуется обновление GUI
csLoad, // требуется загрузка сохраненной игры
//csError // произошла ошибка при выполнении
csUndefined // неопределённое состояние (до запуска игры, например)
);
TFURQContextExecutionMode = (
emNormal,
emMenuBuild,
emEvent
);
TFURQClsType = (clText, clButtons);
TFURQClsTypeSet = set of TFURQClsType;
TFURQActionModifier = (amNone, amNonFinal, amMenu);
EFURQRunTimeError = class(Exception);
type
TfurqOnErrorHandler = procedure (const aErrorMessage: string; aLine: Integer) of object;
const
cWhiteSpaces : TCharSet = [' ', chTAB, #0];
cWordSeparators: TCharSet = [' ', chTAB, '&', #0];
cIdentStartSet = ['a'..'z','A'..'Z','А'..'Я','а'..'я','_', 'Ё', 'ё'];
cIdentMidSet = ['a'..'z','A'..'Z','А'..'Я','а'..'я','_', 'Ё', 'ё', '0'..'9'];
cCaretReturn = #13#10;
// Keywords
kwdPln = 'PLN';
kwdPrintLn = 'PRINTLN';
kwdPrint = 'PRINT';
kwdP = 'P';
// DefaultValues
cDefaultPrecision = 2;
cDefaultInvName = 'Действия';
// Системные переменные
cVarHidePhantoms = 'hide_phantoms';
cVarCurrentLoc = 'current_loc';
cVarPreviousLoc = 'previous_loc';
cVarCommon = 'common';
cVarPrecision = 'fp_prec';
cVarTokenDelim = 'tokens_delim';
cVarPi = 'pi';
cVarInventoryEnabled = 'inventory_enabled';
cLocCommonPrefix = 'common_';
cLocCommon = 'common';
//Другое
cSaveFileSignature = 'FURQSF';
cBufSize = 102400; // 100 Кб
// Функции преобразования значений не как надо, а как принято в URQL
function EnsureReal(const aValue: Variant): Extended;
function EnsureString(const aValue: Variant): string;
implementation
uses
Variants;
// Функции преобразования значений не как надо, а как принято в URQL
function EnsureReal(const aValue: Variant): Extended;
var
l_Str: string;
begin
if VarType(aValue) = varString then
begin
l_Str := aValue;
Result := Length(l_Str);
end
else
Result := aValue;
end;
function EnsureString(const aValue: Variant): string;
begin
if VarType(aValue) <> varString then
Result := ''
else
Result := aValue;
end;
end.
|
unit TTSTITMTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSTITMRecord = record
PLenderNum: String[4];
PCifFlag: String[1];
PLoanCif: String[20];
PCollNum: Integer;
PTrackCode: String[8];
PSubNum: Integer;
PModCount: Integer;
PDescription: String[25];
PReference: String[25];
PExpireDate: String[10];
PNoticeDate: String[10];
PNoticeNum: String[1];
PUserName: String[10];
PDateStamp: String[17];
PNoticeScanID: Integer;
PPriorNoticeDate: String[10];
PAgentID: String[8];
PPayeeCode: String[8];
PInceptionDate: String[10];
PMortgageeFlag: Boolean;
PMPSRateCode: String[4];
PContentsCovAmt: Currency;
PCovAmt: Currency;
PPremAmt: Currency;
PPremDueDate: String[10];
PCancellationDate: String[10];
PDeductible: Currency;
PVMMDed: Currency;
PContentsDed: Currency;
PUTLUserName: String[10];
PUTLDateStamp: String[17];
PSpFlags: String[9];
PDocumentID: String[9];
PPremPaidDate: String[10];
End;
TTTSTITMBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSTITMRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSTITM = (TTSTITMPrimaryKey, TTSTITMbyReference, TTSTITMbyCategory);
TTTSTITMTable = class( TDBISAMTableAU )
private
FDFLenderNum: TStringField;
FDFCifFlag: TStringField;
FDFLoanCif: TStringField;
FDFCollNum: TIntegerField;
FDFTrackCode: TStringField;
FDFSubNum: TIntegerField;
FDFModCount: TIntegerField;
FDFDescription: TStringField;
FDFReference: TStringField;
FDFExpireDate: TStringField;
FDFNoticeDate: TStringField;
FDFNoticeNum: TStringField;
FDFUserName: TStringField;
FDFDateStamp: TStringField;
FDFTrackedNotes: TBlobField;
FDFNoticeScanID: TIntegerField;
FDFPriorNoticeDate: TStringField;
FDFAgentID: TStringField;
FDFPayeeCode: TStringField;
FDFInceptionDate: TStringField;
FDFMortgageeFlag: TBooleanField;
FDFMPSRateCode: TStringField;
FDFContentsCovAmt: TCurrencyField;
FDFCovAmt: TCurrencyField;
FDFPremAmt: TCurrencyField;
FDFPremDueDate: TStringField;
FDFCancellationDate: TStringField;
FDFDeductible: TCurrencyField;
FDFVMMDed: TCurrencyField;
FDFContentsDed: TCurrencyField;
FDFUTLUserName: TStringField;
FDFUTLDateStamp: TStringField;
FDFSpFlags: TStringField;
FDFDocumentID: TStringField;
FDFPremPaidDate: TStringField;
procedure SetPLenderNum(const Value: String);
function GetPLenderNum:String;
procedure SetPCifFlag(const Value: String);
function GetPCifFlag:String;
procedure SetPLoanCif(const Value: String);
function GetPLoanCif:String;
procedure SetPCollNum(const Value: Integer);
function GetPCollNum:Integer;
procedure SetPTrackCode(const Value: String);
function GetPTrackCode:String;
procedure SetPSubNum(const Value: Integer);
function GetPSubNum:Integer;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPReference(const Value: String);
function GetPReference:String;
procedure SetPExpireDate(const Value: String);
function GetPExpireDate:String;
procedure SetPNoticeDate(const Value: String);
function GetPNoticeDate:String;
procedure SetPNoticeNum(const Value: String);
function GetPNoticeNum:String;
procedure SetPUserName(const Value: String);
function GetPUserName:String;
procedure SetPDateStamp(const Value: String);
function GetPDateStamp:String;
procedure SetPNoticeScanID(const Value: Integer);
function GetPNoticeScanID:Integer;
procedure SetPPriorNoticeDate(const Value: String);
function GetPPriorNoticeDate:String;
procedure SetPAgentID(const Value: String);
function GetPAgentID:String;
procedure SetPPayeeCode(const Value: String);
function GetPPayeeCode:String;
procedure SetPInceptionDate(const Value: String);
function GetPInceptionDate:String;
procedure SetPMortgageeFlag(const Value: Boolean);
function GetPMortgageeFlag:Boolean;
procedure SetPMPSRateCode(const Value: String);
function GetPMPSRateCode:String;
procedure SetPContentsCovAmt(const Value: Currency);
function GetPContentsCovAmt:Currency;
procedure SetPCovAmt(const Value: Currency);
function GetPCovAmt:Currency;
procedure SetPPremAmt(const Value: Currency);
function GetPPremAmt:Currency;
procedure SetPPremDueDate(const Value: String);
function GetPPremDueDate:String;
procedure SetPCancellationDate(const Value: String);
function GetPCancellationDate:String;
procedure SetPDeductible(const Value: Currency);
function GetPDeductible:Currency;
procedure SetPVMMDed(const Value: Currency);
function GetPVMMDed:Currency;
procedure SetPContentsDed(const Value: Currency);
function GetPContentsDed:Currency;
procedure SetPUTLUserName(const Value: String);
function GetPUTLUserName:String;
procedure SetPUTLDateStamp(const Value: String);
function GetPUTLDateStamp:String;
procedure SetPSpFlags(const Value: String);
function GetPSpFlags:String;
procedure SetPDocumentID(const Value: String);
function GetPDocumentID:String;
procedure SetPPremPaidDate(const Value: String);
function GetPPremPaidDate:String;
procedure SetEnumIndex(Value: TEITTSTITM);
function GetEnumIndex: TEITTSTITM;
protected
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSTITMRecord;
procedure StoreDataBuffer(ABuffer:TTTSTITMRecord);
property DFLenderNum: TStringField read FDFLenderNum;
property DFCifFlag: TStringField read FDFCifFlag;
property DFLoanCif: TStringField read FDFLoanCif;
property DFCollNum: TIntegerField read FDFCollNum;
property DFTrackCode: TStringField read FDFTrackCode;
property DFSubNum: TIntegerField read FDFSubNum;
property DFModCount: TIntegerField read FDFModCount;
property DFDescription: TStringField read FDFDescription;
property DFReference: TStringField read FDFReference;
property DFExpireDate: TStringField read FDFExpireDate;
property DFNoticeDate: TStringField read FDFNoticeDate;
property DFNoticeNum: TStringField read FDFNoticeNum;
property DFUserName: TStringField read FDFUserName;
property DFDateStamp: TStringField read FDFDateStamp;
property DFTrackedNotes: TBlobField read FDFTrackedNotes;
property DFNoticeScanID: TIntegerField read FDFNoticeScanID;
property DFPriorNoticeDate: TStringField read FDFPriorNoticeDate;
property DFAgentID: TStringField read FDFAgentID;
property DFPayeeCode: TStringField read FDFPayeeCode;
property DFInceptionDate: TStringField read FDFInceptionDate;
property DFMortgageeFlag: TBooleanField read FDFMortgageeFlag;
property DFMPSRateCode: TStringField read FDFMPSRateCode;
property DFContentsCovAmt: TCurrencyField read FDFContentsCovAmt;
property DFCovAmt: TCurrencyField read FDFCovAmt;
property DFPremAmt: TCurrencyField read FDFPremAmt;
property DFPremDueDate: TStringField read FDFPremDueDate;
property DFCancellationDate: TStringField read FDFCancellationDate;
property DFDeductible: TCurrencyField read FDFDeductible;
property DFVMMDed: TCurrencyField read FDFVMMDed;
property DFContentsDed: TCurrencyField read FDFContentsDed;
property DFUTLUserName: TStringField read FDFUTLUserName;
property DFUTLDateStamp: TStringField read FDFUTLDateStamp;
property DFSpFlags: TStringField read FDFSpFlags;
property DFDocumentID: TStringField read FDFDocumentID;
property DFPremPaidDate: TStringField read FDFPremPaidDate;
property PLenderNum: String read GetPLenderNum write SetPLenderNum;
property PCifFlag: String read GetPCifFlag write SetPCifFlag;
property PLoanCif: String read GetPLoanCif write SetPLoanCif;
property PCollNum: Integer read GetPCollNum write SetPCollNum;
property PTrackCode: String read GetPTrackCode write SetPTrackCode;
property PSubNum: Integer read GetPSubNum write SetPSubNum;
property PModCount: Integer read GetPModCount write SetPModCount;
property PDescription: String read GetPDescription write SetPDescription;
property PReference: String read GetPReference write SetPReference;
property PExpireDate: String read GetPExpireDate write SetPExpireDate;
property PNoticeDate: String read GetPNoticeDate write SetPNoticeDate;
property PNoticeNum: String read GetPNoticeNum write SetPNoticeNum;
property PUserName: String read GetPUserName write SetPUserName;
property PDateStamp: String read GetPDateStamp write SetPDateStamp;
property PNoticeScanID: Integer read GetPNoticeScanID write SetPNoticeScanID;
property PPriorNoticeDate: String read GetPPriorNoticeDate write SetPPriorNoticeDate;
property PAgentID: String read GetPAgentID write SetPAgentID;
property PPayeeCode: String read GetPPayeeCode write SetPPayeeCode;
property PInceptionDate: String read GetPInceptionDate write SetPInceptionDate;
property PMortgageeFlag: Boolean read GetPMortgageeFlag write SetPMortgageeFlag;
property PMPSRateCode: String read GetPMPSRateCode write SetPMPSRateCode;
property PContentsCovAmt: Currency read GetPContentsCovAmt write SetPContentsCovAmt;
property PCovAmt: Currency read GetPCovAmt write SetPCovAmt;
property PPremAmt: Currency read GetPPremAmt write SetPPremAmt;
property PPremDueDate: String read GetPPremDueDate write SetPPremDueDate;
property PCancellationDate: String read GetPCancellationDate write SetPCancellationDate;
property PDeductible: Currency read GetPDeductible write SetPDeductible;
property PVMMDed: Currency read GetPVMMDed write SetPVMMDed;
property PContentsDed: Currency read GetPContentsDed write SetPContentsDed;
property PUTLUserName: String read GetPUTLUserName write SetPUTLUserName;
property PUTLDateStamp: String read GetPUTLDateStamp write SetPUTLDateStamp;
property PSpFlags: String read GetPSpFlags write SetPSpFlags;
property PDocumentID: String read GetPDocumentID write SetPDocumentID;
property PPremPaidDate: String read GetPPremPaidDate write SetPPremPaidDate;
published
property Active write SetActive;
property EnumIndex: TEITTSTITM read GetEnumIndex write SetEnumIndex;
end; { TTTSTITMTable }
procedure Register;
implementation
procedure TTTSTITMTable.CreateFields;
begin
FDFLenderNum := CreateField( 'LenderNum' ) as TStringField;
FDFCifFlag := CreateField( 'CifFlag' ) as TStringField;
FDFLoanCif := CreateField( 'LoanCif' ) as TStringField;
FDFCollNum := CreateField( 'CollNum' ) as TIntegerField;
FDFTrackCode := CreateField( 'TrackCode' ) as TStringField;
FDFSubNum := CreateField( 'SubNum' ) as TIntegerField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFReference := CreateField( 'Reference' ) as TStringField;
FDFExpireDate := CreateField( 'ExpireDate' ) as TStringField;
FDFNoticeDate := CreateField( 'NoticeDate' ) as TStringField;
FDFNoticeNum := CreateField( 'NoticeNum' ) as TStringField;
FDFUserName := CreateField( 'UserName' ) as TStringField;
FDFDateStamp := CreateField( 'DateStamp' ) as TStringField;
FDFTrackedNotes := CreateField( 'TrackedNotes' ) as TBlobField;
FDFNoticeScanID := CreateField( 'NoticeScanID' ) as TIntegerField;
FDFPriorNoticeDate := CreateField( 'PriorNoticeDate' ) as TStringField;
FDFAgentID := CreateField( 'AgentID' ) as TStringField;
FDFPayeeCode := CreateField( 'PayeeCode' ) as TStringField;
FDFInceptionDate := CreateField( 'InceptionDate' ) as TStringField;
FDFMortgageeFlag := CreateField( 'MortgageeFlag' ) as TBooleanField;
FDFMPSRateCode := CreateField( 'MPSRateCode' ) as TStringField;
FDFContentsCovAmt := CreateField( 'ContentsCovAmt' ) as TCurrencyField;
FDFCovAmt := CreateField( 'CovAmt' ) as TCurrencyField;
FDFPremAmt := CreateField( 'PremAmt' ) as TCurrencyField;
FDFPremDueDate := CreateField( 'PremDueDate' ) as TStringField;
FDFCancellationDate := CreateField( 'CancellationDate' ) as TStringField;
FDFDeductible := CreateField( 'Deductible' ) as TCurrencyField;
FDFVMMDed := CreateField( 'VMMDed' ) as TCurrencyField;
FDFContentsDed := CreateField( 'ContentsDed' ) as TCurrencyField;
FDFUTLUserName := CreateField( 'UTLUserName' ) as TStringField;
FDFUTLDateStamp := CreateField( 'UTLDateStamp' ) as TStringField;
FDFSpFlags := CreateField( 'SpFlags' ) as TStringField;
FDFDocumentID := CreateField( 'DocumentID' ) as TStringField;
FDFPremPaidDate := CreateField( 'PremPaidDate' ) as TStringField;
end; { TTTSTITMTable.CreateFields }
procedure TTTSTITMTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSTITMTable.SetActive }
procedure TTTSTITMTable.SetPLenderNum(const Value: String);
begin
DFLenderNum.Value := Value;
end;
function TTTSTITMTable.GetPLenderNum:String;
begin
result := DFLenderNum.Value;
end;
procedure TTTSTITMTable.SetPCifFlag(const Value: String);
begin
DFCifFlag.Value := Value;
end;
function TTTSTITMTable.GetPCifFlag:String;
begin
result := DFCifFlag.Value;
end;
procedure TTTSTITMTable.SetPLoanCif(const Value: String);
begin
DFLoanCif.Value := Value;
end;
function TTTSTITMTable.GetPLoanCif:String;
begin
result := DFLoanCif.Value;
end;
procedure TTTSTITMTable.SetPCollNum(const Value: Integer);
begin
DFCollNum.Value := Value;
end;
function TTTSTITMTable.GetPCollNum:Integer;
begin
result := DFCollNum.Value;
end;
procedure TTTSTITMTable.SetPTrackCode(const Value: String);
begin
DFTrackCode.Value := Value;
end;
function TTTSTITMTable.GetPTrackCode:String;
begin
result := DFTrackCode.Value;
end;
procedure TTTSTITMTable.SetPSubNum(const Value: Integer);
begin
DFSubNum.Value := Value;
end;
function TTTSTITMTable.GetPSubNum:Integer;
begin
result := DFSubNum.Value;
end;
procedure TTTSTITMTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSTITMTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSTITMTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TTTSTITMTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TTTSTITMTable.SetPReference(const Value: String);
begin
DFReference.Value := Value;
end;
function TTTSTITMTable.GetPReference:String;
begin
result := DFReference.Value;
end;
procedure TTTSTITMTable.SetPExpireDate(const Value: String);
begin
DFExpireDate.Value := Value;
end;
function TTTSTITMTable.GetPExpireDate:String;
begin
result := DFExpireDate.Value;
end;
procedure TTTSTITMTable.SetPNoticeDate(const Value: String);
begin
DFNoticeDate.Value := Value;
end;
function TTTSTITMTable.GetPNoticeDate:String;
begin
result := DFNoticeDate.Value;
end;
procedure TTTSTITMTable.SetPNoticeNum(const Value: String);
begin
DFNoticeNum.Value := Value;
end;
function TTTSTITMTable.GetPNoticeNum:String;
begin
result := DFNoticeNum.Value;
end;
procedure TTTSTITMTable.SetPUserName(const Value: String);
begin
DFUserName.Value := Value;
end;
function TTTSTITMTable.GetPUserName:String;
begin
result := DFUserName.Value;
end;
procedure TTTSTITMTable.SetPDateStamp(const Value: String);
begin
DFDateStamp.Value := Value;
end;
function TTTSTITMTable.GetPDateStamp:String;
begin
result := DFDateStamp.Value;
end;
procedure TTTSTITMTable.SetPNoticeScanID(const Value: Integer);
begin
DFNoticeScanID.Value := Value;
end;
function TTTSTITMTable.GetPNoticeScanID:Integer;
begin
result := DFNoticeScanID.Value;
end;
procedure TTTSTITMTable.SetPPriorNoticeDate(const Value: String);
begin
DFPriorNoticeDate.Value := Value;
end;
function TTTSTITMTable.GetPPriorNoticeDate:String;
begin
result := DFPriorNoticeDate.Value;
end;
procedure TTTSTITMTable.SetPAgentID(const Value: String);
begin
DFAgentID.Value := Value;
end;
function TTTSTITMTable.GetPAgentID:String;
begin
result := DFAgentID.Value;
end;
procedure TTTSTITMTable.SetPPayeeCode(const Value: String);
begin
DFPayeeCode.Value := Value;
end;
function TTTSTITMTable.GetPPayeeCode:String;
begin
result := DFPayeeCode.Value;
end;
procedure TTTSTITMTable.SetPInceptionDate(const Value: String);
begin
DFInceptionDate.Value := Value;
end;
function TTTSTITMTable.GetPInceptionDate:String;
begin
result := DFInceptionDate.Value;
end;
procedure TTTSTITMTable.SetPMortgageeFlag(const Value: Boolean);
begin
DFMortgageeFlag.Value := Value;
end;
function TTTSTITMTable.GetPMortgageeFlag:Boolean;
begin
result := DFMortgageeFlag.Value;
end;
procedure TTTSTITMTable.SetPMPSRateCode(const Value: String);
begin
DFMPSRateCode.Value := Value;
end;
function TTTSTITMTable.GetPMPSRateCode:String;
begin
result := DFMPSRateCode.Value;
end;
procedure TTTSTITMTable.SetPContentsCovAmt(const Value: Currency);
begin
DFContentsCovAmt.Value := Value;
end;
function TTTSTITMTable.GetPContentsCovAmt:Currency;
begin
result := DFContentsCovAmt.Value;
end;
procedure TTTSTITMTable.SetPCovAmt(const Value: Currency);
begin
DFCovAmt.Value := Value;
end;
function TTTSTITMTable.GetPCovAmt:Currency;
begin
result := DFCovAmt.Value;
end;
procedure TTTSTITMTable.SetPPremAmt(const Value: Currency);
begin
DFPremAmt.Value := Value;
end;
function TTTSTITMTable.GetPPremAmt:Currency;
begin
result := DFPremAmt.Value;
end;
procedure TTTSTITMTable.SetPPremDueDate(const Value: String);
begin
DFPremDueDate.Value := Value;
end;
function TTTSTITMTable.GetPPremDueDate:String;
begin
result := DFPremDueDate.Value;
end;
procedure TTTSTITMTable.SetPCancellationDate(const Value: String);
begin
DFCancellationDate.Value := Value;
end;
function TTTSTITMTable.GetPCancellationDate:String;
begin
result := DFCancellationDate.Value;
end;
procedure TTTSTITMTable.SetPDeductible(const Value: Currency);
begin
DFDeductible.Value := Value;
end;
function TTTSTITMTable.GetPDeductible:Currency;
begin
result := DFDeductible.Value;
end;
procedure TTTSTITMTable.SetPVMMDed(const Value: Currency);
begin
DFVMMDed.Value := Value;
end;
function TTTSTITMTable.GetPVMMDed:Currency;
begin
result := DFVMMDed.Value;
end;
procedure TTTSTITMTable.SetPContentsDed(const Value: Currency);
begin
DFContentsDed.Value := Value;
end;
function TTTSTITMTable.GetPContentsDed:Currency;
begin
result := DFContentsDed.Value;
end;
procedure TTTSTITMTable.SetPUTLUserName(const Value: String);
begin
DFUTLUserName.Value := Value;
end;
function TTTSTITMTable.GetPUTLUserName:String;
begin
result := DFUTLUserName.Value;
end;
procedure TTTSTITMTable.SetPUTLDateStamp(const Value: String);
begin
DFUTLDateStamp.Value := Value;
end;
function TTTSTITMTable.GetPUTLDateStamp:String;
begin
result := DFUTLDateStamp.Value;
end;
procedure TTTSTITMTable.SetPSpFlags(const Value: String);
begin
DFSpFlags.Value := Value;
end;
function TTTSTITMTable.GetPSpFlags:String;
begin
result := DFSpFlags.Value;
end;
procedure TTTSTITMTable.SetPDocumentID(const Value: String);
begin
DFDocumentID.Value := Value;
end;
function TTTSTITMTable.GetPDocumentID:String;
begin
result := DFDocumentID.Value;
end;
procedure TTTSTITMTable.SetPPremPaidDate(const Value: String);
begin
DFPremPaidDate.Value := Value;
end;
function TTTSTITMTable.GetPPremPaidDate:String;
begin
result := DFPremPaidDate.Value;
end;
procedure TTTSTITMTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('LenderNum, String, 4, N');
Add('CifFlag, String, 1, N');
Add('LoanCif, String, 20, N');
Add('CollNum, Integer, 0, N');
Add('TrackCode, String, 8, N');
Add('SubNum, Integer, 0, N');
Add('ModCount, Integer, 0, N');
Add('Description, String, 25, N');
Add('Reference, String, 25, N');
Add('ExpireDate, String, 10, N');
Add('NoticeDate, String, 10, N');
Add('NoticeNum, String, 1, N');
Add('UserName, String, 10, N');
Add('DateStamp, String, 17, N');
Add('TrackedNotes, Memo, 0, N');
Add('NoticeScanID, Integer, 0, N');
Add('PriorNoticeDate, String, 10, N');
Add('AgentID, String, 8, N');
Add('PayeeCode, String, 8, N');
Add('InceptionDate, String, 10, N');
Add('MortgageeFlag, Boolean, 0, N');
Add('MPSRateCode, String, 4, N');
Add('ContentsCovAmt, Currency, 0, N');
Add('CovAmt, Currency, 0, N');
Add('PremAmt, Currency, 0, N');
Add('PremDueDate, String, 10, N');
Add('CancellationDate, String, 10, N');
Add('Deductible, Currency, 0, N');
Add('VMMDed, Currency, 0, N');
Add('ContentsDed, Currency, 0, N');
Add('UTLUserName, String, 10, N');
Add('UTLDateStamp, String, 17, N');
Add('SpFlags, String, 9, N');
Add('DocumentID, String, 9, N');
Add('PremPaidDate, String, 10, N');
end;
end;
procedure TTTSTITMTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, LenderNum;CifFlag;LoanCif;CollNum;TrackCode;SubNum, Y, Y, N, N');
Add('byReference, LenderNum;Reference, N, N, Y, N');
Add('byCategory, LenderNum;TrackCode;Reference, N, N, Y, N');
end;
end;
procedure TTTSTITMTable.SetEnumIndex(Value: TEITTSTITM);
begin
case Value of
TTSTITMPrimaryKey : IndexName := '';
TTSTITMbyReference : IndexName := 'byReference';
TTSTITMbyCategory : IndexName := 'byCategory';
end;
end;
function TTTSTITMTable.GetDataBuffer:TTTSTITMRecord;
var buf: TTTSTITMRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PLenderNum := DFLenderNum.Value;
buf.PCifFlag := DFCifFlag.Value;
buf.PLoanCif := DFLoanCif.Value;
buf.PCollNum := DFCollNum.Value;
buf.PTrackCode := DFTrackCode.Value;
buf.PSubNum := DFSubNum.Value;
buf.PModCount := DFModCount.Value;
buf.PDescription := DFDescription.Value;
buf.PReference := DFReference.Value;
buf.PExpireDate := DFExpireDate.Value;
buf.PNoticeDate := DFNoticeDate.Value;
buf.PNoticeNum := DFNoticeNum.Value;
buf.PUserName := DFUserName.Value;
buf.PDateStamp := DFDateStamp.Value;
buf.PNoticeScanID := DFNoticeScanID.Value;
buf.PPriorNoticeDate := DFPriorNoticeDate.Value;
buf.PAgentID := DFAgentID.Value;
buf.PPayeeCode := DFPayeeCode.Value;
buf.PInceptionDate := DFInceptionDate.Value;
buf.PMortgageeFlag := DFMortgageeFlag.Value;
buf.PMPSRateCode := DFMPSRateCode.Value;
buf.PContentsCovAmt := DFContentsCovAmt.Value;
buf.PCovAmt := DFCovAmt.Value;
buf.PPremAmt := DFPremAmt.Value;
buf.PPremDueDate := DFPremDueDate.Value;
buf.PCancellationDate := DFCancellationDate.Value;
buf.PDeductible := DFDeductible.Value;
buf.PVMMDed := DFVMMDed.Value;
buf.PContentsDed := DFContentsDed.Value;
buf.PUTLUserName := DFUTLUserName.Value;
buf.PUTLDateStamp := DFUTLDateStamp.Value;
buf.PSpFlags := DFSpFlags.Value;
buf.PDocumentID := DFDocumentID.Value;
buf.PPremPaidDate := DFPremPaidDate.Value;
result := buf;
end;
procedure TTTSTITMTable.StoreDataBuffer(ABuffer:TTTSTITMRecord);
begin
DFLenderNum.Value := ABuffer.PLenderNum;
DFCifFlag.Value := ABuffer.PCifFlag;
DFLoanCif.Value := ABuffer.PLoanCif;
DFCollNum.Value := ABuffer.PCollNum;
DFTrackCode.Value := ABuffer.PTrackCode;
DFSubNum.Value := ABuffer.PSubNum;
DFModCount.Value := ABuffer.PModCount;
DFDescription.Value := ABuffer.PDescription;
DFReference.Value := ABuffer.PReference;
DFExpireDate.Value := ABuffer.PExpireDate;
DFNoticeDate.Value := ABuffer.PNoticeDate;
DFNoticeNum.Value := ABuffer.PNoticeNum;
DFUserName.Value := ABuffer.PUserName;
DFDateStamp.Value := ABuffer.PDateStamp;
DFNoticeScanID.Value := ABuffer.PNoticeScanID;
DFPriorNoticeDate.Value := ABuffer.PPriorNoticeDate;
DFAgentID.Value := ABuffer.PAgentID;
DFPayeeCode.Value := ABuffer.PPayeeCode;
DFInceptionDate.Value := ABuffer.PInceptionDate;
DFMortgageeFlag.Value := ABuffer.PMortgageeFlag;
DFMPSRateCode.Value := ABuffer.PMPSRateCode;
DFContentsCovAmt.Value := ABuffer.PContentsCovAmt;
DFCovAmt.Value := ABuffer.PCovAmt;
DFPremAmt.Value := ABuffer.PPremAmt;
DFPremDueDate.Value := ABuffer.PPremDueDate;
DFCancellationDate.Value := ABuffer.PCancellationDate;
DFDeductible.Value := ABuffer.PDeductible;
DFVMMDed.Value := ABuffer.PVMMDed;
DFContentsDed.Value := ABuffer.PContentsDed;
DFUTLUserName.Value := ABuffer.PUTLUserName;
DFUTLDateStamp.Value := ABuffer.PUTLDateStamp;
DFSpFlags.Value := ABuffer.PSpFlags;
DFDocumentID.Value := ABuffer.PDocumentID;
DFPremPaidDate.Value := ABuffer.PPremPaidDate;
end;
function TTTSTITMTable.GetEnumIndex: TEITTSTITM;
var iname : string;
begin
result := TTSTITMPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSTITMPrimaryKey;
if iname = 'BYREFERENCE' then result := TTSTITMbyReference;
if iname = 'BYCATEGORY' then result := TTSTITMbyCategory;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TTTSTITMTable, TTTSTITMBuffer ] );
end; { Register }
function TTTSTITMBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..34] of string = ('LENDERNUM','CIFFLAG','LOANCIF','COLLNUM','TRACKCODE','SUBNUM'
,'MODCOUNT','DESCRIPTION','REFERENCE','EXPIREDATE','NOTICEDATE'
,'NOTICENUM','USERNAME','DATESTAMP','NOTICESCANID'
,'PRIORNOTICEDATE','AGENTID','PAYEECODE','INCEPTIONDATE','MORTGAGEEFLAG'
,'MPSRATECODE','CONTENTSCOVAMT','COVAMT','PREMAMT','PREMDUEDATE'
,'CANCELLATIONDATE','DEDUCTIBLE','VMMDED','CONTENTSDED','UTLUSERNAME'
,'UTLDATESTAMP','SPFLAGS','DOCUMENTID','PREMPAIDDATE' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 34) and (flist[x] <> s) do inc(x);
if x <= 34 then result := x else result := 0;
end;
function TTTSTITMBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftString;
3 : result := ftString;
4 : result := ftInteger;
5 : result := ftString;
6 : result := ftInteger;
7 : result := ftInteger;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftString;
12 : result := ftString;
13 : result := ftString;
14 : result := ftString;
15 : result := ftInteger;
16 : result := ftString;
17 : result := ftString;
18 : result := ftString;
19 : result := ftString;
20 : result := ftBoolean;
21 : result := ftString;
22 : result := ftCurrency;
23 : result := ftCurrency;
24 : result := ftCurrency;
25 : result := ftString;
26 : result := ftString;
27 : result := ftCurrency;
28 : result := ftCurrency;
29 : result := ftCurrency;
30 : result := ftString;
31 : result := ftString;
32 : result := ftString;
33 : result := ftString;
34 : result := ftString;
end;
end;
function TTTSTITMBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PLenderNum;
2 : result := @Data.PCifFlag;
3 : result := @Data.PLoanCif;
4 : result := @Data.PCollNum;
5 : result := @Data.PTrackCode;
6 : result := @Data.PSubNum;
7 : result := @Data.PModCount;
8 : result := @Data.PDescription;
9 : result := @Data.PReference;
10 : result := @Data.PExpireDate;
11 : result := @Data.PNoticeDate;
12 : result := @Data.PNoticeNum;
13 : result := @Data.PUserName;
14 : result := @Data.PDateStamp;
15 : result := @Data.PNoticeScanID;
16 : result := @Data.PPriorNoticeDate;
17 : result := @Data.PAgentID;
18 : result := @Data.PPayeeCode;
19 : result := @Data.PInceptionDate;
20 : result := @Data.PMortgageeFlag;
21 : result := @Data.PMPSRateCode;
22 : result := @Data.PContentsCovAmt;
23 : result := @Data.PCovAmt;
24 : result := @Data.PPremAmt;
25 : result := @Data.PPremDueDate;
26 : result := @Data.PCancellationDate;
27 : result := @Data.PDeductible;
28 : result := @Data.PVMMDed;
29 : result := @Data.PContentsDed;
30 : result := @Data.PUTLUserName;
31 : result := @Data.PUTLDateStamp;
32 : result := @Data.PSpFlags;
33 : result := @Data.PDocumentID;
34 : result := @Data.PPremPaidDate;
end;
end;
end.
|
unit Unit_Produtos;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.Menus, Vcl.StdCtrls,
Vcl.Mask, Vcl.Buttons, Vcl.Grids, Vcl.ComCtrls, Unit_Persistencia;
type
Tfrm_Produtos = class(TForm)
ControlePaginasProduto: TPageControl;
Visualização: TTabSheet;
Grid_Produtos: TStringGrid;
cli_Panel1: TPanel;
prod_ComboBox: TLabel;
label_Pesquisa: TLabel;
btn_Fechar1: TBitBtn;
cbx_PesquisaProduto: TComboBox;
prod_Pesquisa: TMaskEdit;
CRUD_Produto: TTabSheet;
PopupGridProdutos: TPopupMenu;
PopupEditarProduto: TMenuItem;
PopupExcluirProduto: TMenuItem;
cli_Panel2: TPanel;
btn_Fechar: TBitBtn;
btn_Gravar: TBitBtn;
btn_Limpar: TBitBtn;
btn_Cancelar: TBitBtn;
btn_Novo: TBitBtn;
prod_Codigo: TLabeledEdit;
prod_Descricao: TLabeledEdit;
prod_Estoque: TLabeledEdit;
prod_EstoqueMinimo: TLabeledEdit;
prod_PrecoCusto: TLabeledEdit;
prod_PrecoVenda: TLabeledEdit;
procedure btn_FecharClick(Sender: TObject);
procedure btn_LimparClick(Sender: TObject);
Procedure Limpa_Componentes;
procedure btn_CancelarClick(Sender: TObject);
Procedure Habilita_Tela(Habilitado:Boolean);
Procedure Habilita_Botoes(Quais:String);
procedure btn_NovoClick(Sender: TObject);
procedure btn_GravarClick(Sender: TObject);
Procedure Popula_Grid(Condicao : String);
Procedure Preenche_Componentes;
procedure PopupExcluirProdutoClick(Sender: TObject);
procedure PopupEditarProdutoClick(Sender: TObject);
Function Validado : Boolean;
procedure FormShow(Sender: TObject);
Procedure Pinta_Grid;
procedure prod_PesquisaChange(Sender: TObject);
procedure ControlePaginasProdutoChanging(Sender: TObject;
var AllowChange: Boolean);
procedure Grid_ProdutosSelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
procedure Grid_ProdutosKeyPress(Sender: TObject; var Key: Char);
procedure cbx_PesquisaProdutoChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_Produtos: Tfrm_Produtos;
Alterando : Boolean;
Linha : Integer;
implementation
{$R *.dfm}
procedure Tfrm_Produtos.btn_FecharClick(Sender: TObject);
begin
frm_Produtos.Close;
end;
Procedure Tfrm_Produtos.Limpa_Componentes;
Begin
prod_Descricao.Clear;
prod_Estoque.Clear;
prod_EstoqueMinimo.Clear;
prod_PrecoCusto.Clear;
prod_PrecoVenda.Clear;
End;
procedure Tfrm_Produtos.btn_LimparClick(Sender: TObject);
begin
if Application.MessageBox('Deseja realmente limpar todos os campos? Tem certeza?',
'Limpar todos os campos?',
MB_ICONQUESTION + MB_YESNO) = mrYes
then Limpa_Componentes;
end;
Procedure Tfrm_Produtos.Habilita_Tela(Habilitado:Boolean);
Begin
prod_Descricao.Enabled := Habilitado;
prod_Estoque.Enabled := Habilitado;
prod_EstoqueMinimo.Enabled := Habilitado;
prod_PrecoCusto.Enabled := Habilitado;
prod_PrecoVenda.Enabled := Habilitado;
End;
Procedure Tfrm_Produtos.Habilita_Botoes(Quais:String);
Begin
if Quais[1] = '0'
then btn_Novo.Enabled := False
Else btn_Novo.Enabled := True;
if Quais[2] = '0'
then btn_Limpar.Enabled := False
Else btn_Limpar.Enabled := True;
if Quais[3] = '0'
then btn_Cancelar.Enabled := False
Else btn_Cancelar.Enabled := True;
if Quais[4] = '0'
then btn_Gravar.Enabled := False
Else btn_Gravar.Enabled := True;
if Quais[5] = '0'
then btn_Fechar.Enabled := False
Else btn_Fechar.Enabled := True;
End;
procedure Tfrm_Produtos.btn_CancelarClick(Sender: TObject);
begin
Habilita_Tela(False);
Limpa_Componentes;
Habilita_Botoes('10001');
end;
procedure Tfrm_Produtos.btn_NovoClick(Sender: TObject);
begin
Habilita_Tela(True);
prod_Descricao.SetFocus;
Limpa_Componentes;
prod_Codigo.Text := Retorna_Proximo_Codigo_Produto;
Habilita_Botoes('01110');
Alterando := False;
end;
procedure Tfrm_Produtos.cbx_PesquisaProdutoChange(Sender: TObject);
begin
prod_Pesquisa.Enabled := True;
prod_Pesquisa.Text := '';
end;
/// Falta controlar que apenas NUMEROS possam ser digitados nos campos de preco e estoque
Function Tfrm_Produtos.Validado : Boolean;
begin
Result := False;
if Trim(prod_Descricao.Text) = ''
then Begin
Application.MessageBox('O campo de Descrição é obrigatório',
'Informe a descrição do produto.',
MB_ICONERROR + MB_OK);
prod_Descricao.SetFocus;
Exit;
End;
if Trim(prod_Estoque.Text) = ''
then Begin
Application.MessageBox('O campo de Estoque é obrigatório',
'Informe o estoque',
MB_ICONERROR + MB_OK);
prod_Estoque.SetFocus;
Exit;
End;
if Trim(prod_EstoqueMinimo.Text) = ''
then Begin
Application.MessageBox('O campo de Estoque Mínimo é obrigatório',
'Informe o estoque mínimo',
MB_ICONERROR + MB_OK);
prod_EstoqueMinimo.SetFocus;
Exit;
End;
if Trim(prod_PrecoCusto.Text) = ''
then Begin
Application.MessageBox('O campo de Preço do Custo é obrigatório',
'Informe o preço do custo.',
MB_ICONERROR + MB_OK);
prod_PrecoCusto.SetFocus;
Exit;
End;
if Trim(prod_PrecoVenda.Text) = ''
then Begin
Application.MessageBox('O campo de Preço de Venda é obrigatório',
'Informe o preço de Venda.',
MB_ICONERROR + MB_OK);
prod_PrecoVenda.SetFocus;
Exit;
End;
Result := True;
end;
Procedure Tfrm_Produtos.Popula_Grid(Condicao : String);
Var
Produtos_Atuais : Produtos_Cadastrados;
I : Integer;
Begin
SetLength(Produtos_Atuais,0);
Grid_Produtos.RowCount := 2;
Grid_Produtos.Cells[0,1] := '';
Grid_Produtos.Cells[1,1] := '';
Grid_Produtos.Cells[2,1] := '';
Grid_Produtos.Cells[3,1] := '';
Grid_Produtos.Cells[4,1] := '';
Grid_Produtos.Cells[5,1] := '';
Produtos_Atuais := Retorna_Produtos_Cadastrados(Condicao);
if Length(Produtos_Atuais) = 0
then Begin
PopupEditarProduto.Enabled := False;
Exit;
End;
PopupEditarProduto.Enabled := True;
For I := 0 To Length(Produtos_Atuais)-1 Do
Begin
Grid_Produtos.RowCount := Grid_Produtos.RowCount + 1;
Grid_Produtos.Cells[0,I+1] := IntToStr(Produtos_Atuais[I].Prod_Codigo);
Grid_Produtos.Cells[1,I+1] := Produtos_Atuais[I].Prod_Descricao;
Grid_Produtos.Cells[2,I+1] := IntToStr(Produtos_Atuais[I].Prod_Estoque);
Grid_Produtos.Cells[3,I+1] := IntToStr(Produtos_Atuais[I].Prod_EstoqueMinimo);
Grid_Produtos.Cells[4,I+1] := Produtos_Atuais[I].Prod_PrecoCusto;
Grid_Produtos.Cells[5,I+1] := Produtos_Atuais[I].Prod_PrecoVenda;
End;
Grid_Produtos.RowCount := Grid_Produtos.RowCount - 1;
End;
procedure Tfrm_Produtos.btn_GravarClick(Sender: TObject);
var
Temp : Dados_Produto;
begin
if Validado
then Begin
if prod_Codigo.Text <> ''
then Temp.prod_Codigo := StrToInt(prod_Codigo.Text);
if prod_Descricao.Text <> ''
then Temp.prod_Descricao := prod_Descricao.Text;
if prod_Estoque.Text <> ''
then Temp.prod_Estoque := StrToInt(prod_Estoque.Text);
if prod_EstoqueMinimo.Text <> ''
then Temp.prod_EstoqueMinimo := StrToInt(prod_EstoqueMinimo.Text);
if prod_PrecoCusto.Text <> ''
then Temp.prod_PrecoCusto := prod_PrecoCusto.Text;
if prod_PrecoVenda.Text <> ''
then Temp.prod_PrecoVenda := prod_PrecoVenda.Text;
Grava_Dados_Produto(Temp, Alterando);
Habilita_Tela(False);
Habilita_Botoes('10001');
Limpa_Componentes;
Popula_Grid('');
Alterando := False;
End;
end;
Procedure Tfrm_Produtos.Preenche_Componentes;
Var
Temp : Dados_Produto;
Begin
if Grid_Produtos.Cells[0,Linha] = ''
then Exit;
Temp := Retorna_Dados_Produto(StrToInt(Grid_Produtos.Cells[0,Linha]));
prod_Codigo.Text := IntToStr(Temp.prod_Codigo);
prod_Descricao.Text := Temp.prod_Descricao;
prod_Estoque.Text := IntToStr(Temp.prod_Estoque);
prod_EstoqueMinimo.Text := IntToStr(Temp.prod_EstoqueMinimo);
prod_PrecoCusto.Text := Temp.prod_PrecoCusto;
prod_PrecoVenda.Text := Temp.prod_PrecoVenda;
End;
procedure Tfrm_Produtos.PopupEditarProdutoClick(Sender: TObject);
begin
Preenche_Componentes;
if Prod_Codigo.Text = ''
then Exit;
ControlePaginasProduto.ActivePageIndex := 1;
Alterando := True;
Habilita_Botoes('01110');
Habilita_Tela(True);
end;
procedure Tfrm_Produtos.PopupExcluirProdutoClick(Sender: TObject);
begin
if Application.MessageBox('Deseja realmente excluir o Produto? Essa opção não pode ser desfeita.',
'Excluir Produto?',
MB_ICONQUESTION + MB_YESNO) = mrYes
then begin
Preenche_Componentes;
if Prod_Codigo.Text = ''
then Exit;
Remove_Produto(StrToInt(Grid_Produtos.Cells[0,Linha]));
Limpa_Componentes;
Popula_Grid('');
end;
end;
Procedure Tfrm_Produtos.Pinta_Grid;
begin
Grid_Produtos.Cells[0,0] := 'Cód.';
Grid_Produtos.Cells[1,0] := 'Descrição';
Grid_Produtos.Cells[2,0] := 'Estoque';
Grid_Produtos.Cells[3,0] := 'Estoque Minimo';
Grid_Produtos.Cells[4,0] := 'Preço de Custo';
Grid_Produtos.Cells[5,0] := 'Preço de Venda';
Grid_Produtos.ColWidths[0] := 50;
Grid_Produtos.ColWidths[1] := 300;
Grid_Produtos.ColWidths[2] := 100;
Grid_Produtos.ColWidths[3] := 100;
Grid_Produtos.ColWidths[4] := 150;
Grid_Produtos.ColWidths[5] := 150;
end;
procedure Tfrm_Produtos.prod_PesquisaChange(Sender: TObject);
begin
if prod_Pesquisa.Text = ''
then Begin
Popula_Grid('');
Exit;
End;
case cbx_PesquisaProduto.ItemIndex of
0 : Popula_Grid('Where Prod_Codigo = '+prod_Pesquisa.Text) ;
1 : Popula_Grid('Where Prod_Descricao Like '+QuotedStr(prod_Pesquisa.Text+'%')) ;
2 : Popula_Grid('Where Prod_Estoque = '+prod_Pesquisa.Text) ;
3 : Popula_Grid('Where Prod_EstoqueMinimo = '+prod_Pesquisa.Text) ;
4 : Popula_Grid('Where Prod_PrecoCusto Like '+QuotedStr(prod_Pesquisa.Text+'%')) ;
5 : Popula_Grid('Where Prod_PrecoVenda Like '+QuotedStr(prod_Pesquisa.Text+'%')) ;
end;
end;
procedure Tfrm_Produtos.ControlePaginasProdutoChanging(Sender: TObject;
var AllowChange: Boolean);
var msg : string;
begin
if Alterando
then msg := 'alteração de um registro existente?'
else msg := 'inclusão de um novo registro?';
if btn_Gravar.Enabled
then Begin
AllowChange := False;
if Application.MessageBox(PChar('Deseja realmente cancelar a '+msg),'Deseja cancelar?',MB_ICONQUESTION + MB_YESNO) = mrYes
Then Begin
btn_Cancelar.Click;
AllowChange := True;
End;
End;
end;
procedure Tfrm_Produtos.Grid_ProdutosSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
Linha := ARow;
end;
procedure Tfrm_Produtos.Grid_ProdutosKeyPress(Sender: TObject; var Key: Char);
begin
if Key = Chr(27)
then btn_Fechar.Click;
end;
procedure Tfrm_Produtos.FormShow(Sender: TObject);
begin
Pinta_Grid;
Popula_Grid('');
end;
end.
|
unit evCustomParaListUtils;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "Everest"
// Модуль: "w:/common/components/gui/Garant/Everest/evCustomParaListUtils.pas"
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::Everest::ParaUtils::evCustomParaListUtils
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include ..\Everest\evDefine.inc}
interface
{$If defined(evNeedEditableCursors)}
uses
nevBase,
nevTools,
evEditorInterfaces,
k2TagTools
;
type
TevLocationProcessorTagTool = class(Tk2ProcessorTagTool)
{* Базовый класс для инструментов для тегов, с использованием _TevLocation. }
private
// private fields
f_View : InevView;
{* Поле для свойства View}
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure ClearFields; override;
protected
// protected fields
f_Location : InevLocation;
public
// public methods
constructor Create(const aView: InevView;
const aTagWrap: InevTag;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil); reintroduce;
public
// public properties
property View: InevView
read f_View;
end;//TevLocationProcessorTagTool
TevTableChild = class(TevLocationProcessorTagTool)
private
// private fields
f_Table : IedTable;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
protected
// protected methods
function GetTable: IedTable;
public
// public methods
constructor Create(const aView: InevView;
const aTable: IedTable;
const aTagWrap: InevTag;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil); reintroduce;
end;//TevTableChild
TevRowChild = class(TevLocationProcessorTagTool)
private
// private fields
f_Row : IedRow;
protected
// overridden protected methods
procedure Cleanup; override;
{* Функция очистки полей объекта. }
protected
// protected methods
function GetRow: IedRow;
public
// public methods
constructor Create(const aView: InevView;
const aRow: IedRow;
const aTagWrap: InevTag;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil); reintroduce;
end;//TevRowChild
procedure EvCheckCellStatus(const anOpPack: InevOp;
const aCell: InevPara);
{$IfEnd} //evNeedEditableCursors
implementation
{$If defined(evNeedEditableCursors)}
uses
evCursorTools,
k2Base,
k2Tags,
evdStyles
;
// start class TevLocationProcessorTagTool
constructor TevLocationProcessorTagTool.Create(const aView: InevView;
const aTagWrap: InevTag;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil);
//#UC START# *4F6C2EBF02EA_4F6C2DB4038D_var*
//#UC END# *4F6C2EBF02EA_4F6C2DB4038D_var*
begin
//#UC START# *4F6C2EBF02EA_4F6C2DB4038D_impl*
inherited Create(aTagWrap, aProcessor);
f_View := aView;
f_Location := aLocation;
//#UC END# *4F6C2EBF02EA_4F6C2DB4038D_impl*
end;//TevLocationProcessorTagTool.Create
procedure TevLocationProcessorTagTool.Cleanup;
//#UC START# *479731C50290_4F6C2DB4038D_var*
//#UC END# *479731C50290_4F6C2DB4038D_var*
begin
//#UC START# *479731C50290_4F6C2DB4038D_impl*
f_View := nil;
f_Location := nil;
inherited;
//#UC END# *479731C50290_4F6C2DB4038D_impl*
end;//TevLocationProcessorTagTool.Cleanup
procedure TevLocationProcessorTagTool.ClearFields;
{-}
begin
f_View := nil;
inherited;
end;//TevLocationProcessorTagTool.ClearFields
// start class TevTableChild
constructor TevTableChild.Create(const aView: InevView;
const aTable: IedTable;
const aTagWrap: InevTag;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil);
//#UC START# *4FA4F2DB015A_4FA4F2AA0302_var*
//#UC END# *4FA4F2DB015A_4FA4F2AA0302_var*
begin
//#UC START# *4FA4F2DB015A_4FA4F2AA0302_impl*
inherited Create(aView, aTagWrap, aProcessor, aLocation);
f_Table := aTable;
//#UC END# *4FA4F2DB015A_4FA4F2AA0302_impl*
end;//TevTableChild.Create
function TevTableChild.GetTable: IedTable;
//#UC START# *4FA4F36702FC_4FA4F2AA0302_var*
//#UC END# *4FA4F36702FC_4FA4F2AA0302_var*
begin
//#UC START# *4FA4F36702FC_4FA4F2AA0302_impl*
Result := f_Table;
//#UC END# *4FA4F36702FC_4FA4F2AA0302_impl*
end;//TevTableChild.GetTable
procedure TevTableChild.Cleanup;
//#UC START# *479731C50290_4FA4F2AA0302_var*
//#UC END# *479731C50290_4FA4F2AA0302_var*
begin
//#UC START# *479731C50290_4FA4F2AA0302_impl*
f_Table := nil;
inherited;
//#UC END# *479731C50290_4FA4F2AA0302_impl*
end;//TevTableChild.Cleanup
// start class TevRowChild
function TevRowChild.GetRow: IedRow;
//#UC START# *4FC47FAC0128_4FC47ECC03C9_var*
//#UC END# *4FC47FAC0128_4FC47ECC03C9_var*
begin
//#UC START# *4FC47FAC0128_4FC47ECC03C9_impl*
Result := f_Row;
//#UC END# *4FC47FAC0128_4FC47ECC03C9_impl*
end;//TevRowChild.GetRow
constructor TevRowChild.Create(const aView: InevView;
const aRow: IedRow;
const aTagWrap: InevTag;
const aProcessor: InevProcessor;
const aLocation: InevLocation = nil);
//#UC START# *4FC4800103A2_4FC47ECC03C9_var*
//#UC END# *4FC4800103A2_4FC47ECC03C9_var*
begin
//#UC START# *4FC4800103A2_4FC47ECC03C9_impl*
inherited Create(aView, aTagWrap, aProcessor, aLocation);
f_Row := aRow;
//#UC END# *4FC4800103A2_4FC47ECC03C9_impl*
end;//TevRowChild.Create
procedure TevRowChild.Cleanup;
//#UC START# *479731C50290_4FC47ECC03C9_var*
//#UC END# *479731C50290_4FC47ECC03C9_var*
begin
//#UC START# *479731C50290_4FC47ECC03C9_impl*
f_Row := nil;
inherited;
//#UC END# *479731C50290_4FC47ECC03C9_impl*
end;//TevRowChild.Cleanup
procedure EvCheckCellStatus(const anOpPack: InevOp;
const aCell: InevPara);
//#UC START# *502CD0E40149_4F6C2D7901D1_var*
//#UC END# *502CD0E40149_4F6C2D7901D1_var*
begin
//#UC START# *502CD0E40149_4F6C2D7901D1_impl*
if aCell.ChildrenCount = 0 then
if evInsertPara(anOpPack, aCell.MakePoint, Tk2Type(aCell.TagType).ArrayProp[k2_tiChildren].DefaultChildType.MakeTag) then
aCell.Child[0].IntW[k2_tiStyle, anOpPack] := ev_saNormalTable;
//#UC END# *502CD0E40149_4F6C2D7901D1_impl*
end;//EvCheckCellStatus
{$IfEnd} //evNeedEditableCursors
end. |
unit UpdateRouteUnit;
interface
uses SysUtils, BaseExampleUnit;
type
TUpdateRoute = class(TBaseExample)
public
procedure Execute(RouteId: String);
end;
implementation
uses RouteParametersUnit, RouteParametersQueryUnit, DataObjectUnit, EnumsUnit;
procedure TUpdateRoute.Execute(RouteId: String);
var
RouteParameters: TRouteParametersQuery;
ErrorString: String;
Route: TDataObjectRoute;
begin
RouteParameters := TRouteParametersQuery.Create;
try
RouteParameters.RouteId := RouteId;
RouteParameters.Parameters := TRouteParameters.Create;
TRouteParameters(RouteParameters.Parameters.Value).RouteName := 'New name of the route';
Route := Route4MeManager.Route.Update(RouteParameters, ErrorString);
WriteLn('');
try
if (Route <> nil) then
begin
WriteLn('UpdateRoute executed successfully');
WriteLn(Format('Route ID: %s', [Route.RouteId]));
end
else
WriteLn(Format('UpdateRoute error: %s', [ErrorString]));
finally
FreeAndNil(Route);
end;
finally
FreeAndNil(RouteParameters);
end;
end;
end.
|
unit AST.Delphi.Errors;
interface
uses SysUtils,
AST.Lexer,
AST.Lexer.Delphi,
AST.Delphi.Operators,
AST.Delphi.Classes,
AST.Delphi.Parser;
resourcestring
// internal errors
sUnitAlreadyExistFmt = 'Unit ''%s'' already exist';
sIntfSectionMissing = 'INTERFACE section are missing';
sKeywordExpected = 'KEYWORD expected but %s found';
sInternalErrorWord = 'Internal error';
sErrorWord = 'Error';
sWarningWord = 'Warning';
sHintWord = 'Hint';
sExpected = '%s expected';
sExpectedButFoundFmt = '%s expected but "%s" found';
sIdentifierExpected = 'Identifier expected';
sIdExpectedButFoundFmt = 'Identifier expected but "%s" found';
sParamNameExpectedButFoundFmt = 'Param name expected but "%s" found';
sTypeIdExpectedButFoundFmt = 'Type identifier expected but "%s" found';
sIdentifierRedeclaredFmt = 'Identifier redeclared: "%s"';
sUndeclaredIdentifier = 'Undeclared identifier: "%s"';
sDeclDifWithPrevDecl = 'Declaration of "%s" differs from previous declaration';
sBeginEndCountAreDiffers = 'Count of BEGIN/END clauses does not equals';
sDevisionByZero = 'Devision by zero';
sVariableRequired = 'Variable required';
sVariableOrTypeRequired = 'VARIABLE or TYPE required';
sCannotModifyObjectPassedAsConstParam = 'Cannot modify object passed as CONST parameter';
sConstCannotBePassedAsVarParam = 'Constant cannot be passed as VAR parameter';
sIncompleteProcFmt = 'Incomplete forward declaration ''%s''';
sVariableIsDeclaredButNeverUsedInFmt = 'Variable "%s" is declared but never used';
// overload:
sOverloadedMustBeMarked = 'Overloaded entry "%s" must be marked with the "overload" directive';
sErrorOverload = 'There isn''t function with such parameters';
sAmbiguousOverloadedCallFmt = 'Ambiguous overloaded call to "%s"';
sInvalidIndex = 'Index is out of bounds';
sNotAllowedHere = 'Not allowed here: "%s"';
sUnexpectedEndOfFile = 'Unexpected end of file';
sUnknownLanguageExpression = 'Unknown language expression: "%s"';
sStatementExpectedButExpFoundFmt = 'Statement expected, but expression "%s" found';
sExpressionExpectedButStmntFoundFmt = 'Expression expected, but statement "%s" found';
sExpressionExpected = 'Expression expected';
sUnnecessaryClosedBracket = 'Unnecessary closed bracket';
sUnnecessaryClosedBlock = 'Unnecessary closed block';
sUnnecessaryEndClause = 'Unnecessary end clause';
sUnclosedOpenBracket = 'Unclosed open bracket';
sUnclosedOpenBlock = 'Unclosed open block';
sMissingOperatorOrSemicolon = 'Missing operator or semicolon';
sSemicolonExpected = 'SEMICOLON expected';
sDublicateOperationFmt = 'Dublicate operation "%s"';
sDuplicateSpecificationFmt = 'Duplicate "%s" specification';
sReturnValueNotAllowedForProc = 'Return value is not allowed for procedure';
sParameterTypeRequred = 'Parameter type required';
// Assignment
sAssignmentIsImpossible = 'The assignment is impossible, "%s" is not a variable';
sRightExpressionHasNoResult = 'Right expression has no result';
// parameters
sNotEnoughActualParametersFmt = 'Not enough actual parameters for "%s"';
sTooManyActualParameters = 'Too many actual parameters';
sCannotPassConstAsVarParamFmt = 'Can not pass const as var parameter "%s"';
// Types
sNoOverloadOperatorForTypesFmt = 'No overload operator "%s" for types "%s" and "%s"';
sNoOverloadOperatorForTypeFmt = 'No overload operator "%s" for type "%s"';
sUnknownOperatorFmt = 'Unknown operator "%s"';
sOperatorNeedNCountOfParameters = 'Operator "%s" need %d explicit parameters';
sIncompatibleTypesFmt = 'Incompatible types: "%s" and "%s"';
sInvalidTypecastFmt = 'Can not explicitly convert type "%s" into "%s"';
sEmptyExpression = 'Empty expression';
sExpressionMustBeBoolean = 'Type of expression must be BOOLEAN';
sExpressionMustBeConstant = 'Expression must be a CONSTANT';
sDeclarationHasNoDataTypeFmt = 'Declaration "%s" has no data type';
sInvalidTypeDeclaration = 'Invalid type declaration';
sTypeKeywordRequred = 'The TYPE keyword required';
sConstValueOverflowFmt = 'CONST value "%s" exceeds values range for "%s" data type';
// uses
sUnitNotFoundFmt = 'Unit not found: %s';
sUnitRecursivelyUsesItselfFmt = 'Program or unit ''%s'' recursively uses itself';
// loops
sContinueAllowedOnlyInLoop = 'continue allowed only in loop';
sBreakOrContinueAreAllowedOnlyInALoops = 'BREAK and CONTINUE are allowed only in a loops';
sLoopLevelExprected = 'Loop level exprected';
sLoopLevelGreaterThenPossibleFmt = 'The loop level is greater than possible, max level is %d';
sForLoopIndexVarsMastBeSimpleIntVar = 'For loop index variable must be local integer variable';
sKeywordToOrDowntoExpected = 'Кeyword TO or DOWNTO are expected';
sForOrWhileLoopExecutesZeroTimes = 'FOR or WHILE-loop executes zero times - deleted';
sZeroDeltaInForLoop = 'Zero delta in FOR-loop, infinity loop';
sCannotModifyForLoopIndexVarFmt = 'Cannot modify FOR-loop index variable %s';
// records
sIdentifierHasNoMembersFmt = 'Identifier "%s" has no members';
sRecordTypeRequired = 'Record type is required';
sStructTypeRequired = 'Structured type is required';
sRecurciveTypeLinkIsNotAllowed = 'Recurcive link is not allowed';
sFieldConstOrFuncRequiredForGetter = 'The field, constant or function are required for a getter';
sFieldOrProcRequiredForSetter = 'The field or procedure are required for a setter';
sCannotModifyReadOnlyProperty = 'Cannot modify the read-only property';
sCannotAccessToWriteOnlyProperty = 'Cannot access to write-only property';
sSetterMustBeMethodWithSignFmt = 'Setter must be a method with signature: procedure(const Value: %s);';
sDefaultPropertyMustBeAnArrayProperty = 'Default property must be an array property';
sDefaultPropertyAlreadyExistsFmt = 'Default property already exist: "%s"';
// classes
sClassTypeCannotBeAnonimous = 'CLASS type cannot be anonimous';
sClassTypeRequired = 'CLASS type required';
// interfaces
sInterfacedTypeCannotBeAnonimous = 'Interfaced type cannot be anonimous';
sInterfaceTypeRequired = 'Interface type required';
// arrays
sOrdinalTypeRequired = 'ORDINAL type required';
sOrdinalConstOrTypeRequred = 'ORDINAL constant or type required';
sArrayTypeRequired = 'Array type required';
sArrayOrStringTypeRequired = 'ARRAY or STRING type required';
sNeedSpecifyNIndexesFmt = 'For access to array ''%s: %s'' need specify %d indexes';
sConstExprOutOfRangeFmt = 'Const expression ''%d'' out of range [%d..%d]';
sOpenArrayAllowedOnlyAsTypeOfParam = 'Open array allowed only as type of parameter';
// New/Free
sPointerTypeRequired = 'POINTER type required';
sReferenceTypeRequired = 'REFERENCE type required';
// Ranges
sLowerBoundExceedsHigherBound = 'Lower bound exceeds higher bound';
sNumericTypeRequired = 'Numeric type required';
sConstRangeRequired = 'Const range required';
// Enums
sComaOrCloseRoundExpected = ''','' or '')'' expected';
// Expressions
sSingleExpressionRequired = 'Single expression required';
sStringExpressionRequired = 'STRING expression required';
// Import/Export
sImportFuncCannotBeInline = 'Import function can not be INLINE';
sExportAllowsOnlyInIntfSection = 'Export allows only in INTERFACE section';
// Interanl errors
sOperatorForTypesAlreadyOverloadedFmt = 'Operator ''%s'' for types ''%s'' and ''%s'' already overloaded';
sFeatureNotSupported = 'Feature is not supported';
// Platform/ASM
sInstructionAlreadyDeclaredFmt = 'Instruction "%s" already declared';
sRegisterAlreadyDeclaredFmt = 'Register "%s" already declared';
sUnknownInstructionFmt = 'Unknown instruction "%s"';
sUnknownPlatformFmt = 'Unknown platform "%s"';
sProcedureOrFunctionKeywordAreExpected = 'PROCEDURE or FUNCTION keyword are expected';
//sProcOrFuncRequired = 'Procedure or function required';
sDuplicateOpenBlock = 'Duplicate open block';
sASMSyntaxError = 'Assembler syntax error';
sDestArgCannotBeConst = 'Destination argument cannot be a constant';
sEmptyArgument = 'Empty argument';
sInvalidArgument = 'Invalid argument';
sLabelRedeclaretedFmt = 'Label "%s" redeclareted';
sImmediateOffsetIsOutOfRangeFmt = 'Immediate offset is out of range (%d..%d)';
// IIF
sTypesMustBeIdentical = 'Types must be identical';
sThenAndElseSectionAreIdentical = 'THEN and ELSE sections are identical';
// Try/Except/Finally
sTryKeywordMissed = 'TRY keyword missed';
sExceptOrFinallySectionWasMissed = 'EXCEPT or FINALLY section was missed';
sSectionFinallyAlreadyDefined = 'Section FINALLY already defined';
sSectionExceptAlreadyDefined = 'Section EXCEPT already defined';
sExceptSectionMustBeDeclareBeforeFinally = 'EXCEPT section must be declared before FINALLY section';
sBreakContinueExitAreNotAllowedInFinallyClause = 'BREAK, CONTINUE or EXIT are not allowed in FINALLY clause';
// case
sCaseStmtRequireAtLeastOneMatchExpr = 'CASE statement require at least one match expression';
sMatchExprTypeMustBeIdenticalToCaseExprFmt = 'Match expression type [%s] must be identical to CASE expression type [%s]';
sDuplicateMatchExpression = 'Duplicate match expression';
// addr
sVarOrProcRequired = 'Variable or procedure required';
sProcOrProcVarRequired = 'Procedure or variable of procedure type is required';
// generics
sNoOneTypeParamsWasFound = 'No one type parameters was found';
sGenericProcInstanceErrorFmt = 'Generic procedure %s specialization ERROR:';
sGenericFuncInstanceErrorFmt = 'Generic function %s specialization ERROR:';
sProcHasNoGenericParams = 'The %s "%s" has no generic parameters';
sProcRequiresExplicitTypeArgumentFmt = 'The %s "%s" requires explicit type argument(s)';
sTooManyActualTypeParameters = 'Too many actual type arguments';
// conditional statements
sInvalidConditionalStatement = 'Invalid conditional statement';
type
TASTDelphiErrors = class helper for TASTDelphiUnit
class procedure ERROR_ARG_VAR_REQUIRED(Expr: TIDExpression); static;
class procedure ERROR_CONST_EXPRESSION_REQUIRED(Expr: TIDExpression); static;
class procedure ERROR_INCOMPATIBLE_TYPES(const Src, Dst: TIDExpression); overload; static;
class procedure ERROR_INCOMPATIBLE_TYPES(const Src: TIDExpression; Dst: TIDType); overload; static;
class procedure ERROR_INVALID_EXPLICIT_TYPECAST(const Src: TIDExpression; Dst: TIDType); static;
class procedure ERROR_VAR_EXPRESSION_REQUIRED(Expr: TIDExpression); static;
class procedure ERROR_VAR_OR_PROC_EXPRESSION_REQUIRED(Expr: TIDExpression); static;
class procedure ERROR_CANNOT_MODIFY_FOR_LOOP_VARIABLE(Expr: TIDExpression); static;
class procedure ERROR_CANNOT_MODIFY_CONSTANT(Expr: TIDExpression); static;
class procedure ERROR_BOOLEAN_EXPRESSION_REQUIRED(Expr: TIDExpression); static;
class procedure ERROR_ARRAY_EXPRESSION_REQUIRED(Expr: TIDExpression); static;
class procedure ERROR_ID_REDECLARATED(Decl: TIDDeclaration); overload; static;
class procedure ERROR_ID_REDECLARATED(const ID: TIdentifier); overload; static;
class procedure ERROR_UNDECLARED_ID(const ID: TIdentifier); overload; static;
class procedure ERROR_UNDECLARED_ID(const ID: TIdentifier; const GenericParams: TIDTypeList); overload; static;
class procedure ERROR_UNDECLARED_ID(const Name: string; const TextPosition: TTextPosition); overload; static;
class procedure ERROR_NOT_ENOUGH_ACTUAL_PARAMS(CallExpr: TIDExpression); static;
class procedure ERROR_TOO_MANY_ACTUAL_PARAMS(CallExpr: TIDExpression); static;
class procedure ERROR_OVERLOADED_MUST_BE_MARKED(const ID: TIdentifier); static;
class procedure ERROR_DECL_DIFF_WITH_PREV_DECL(const ID: TIdentifier); static;
class procedure ERROR_STRUCT_TYPE_REQUIRED(const TextPosition: TTextPosition); static;
class procedure ERROR_ARRAY_TYPE_REQUIRED(const ID: TIdentifier; const TextPosition: TTextPosition); static;
class procedure ERROR_INTEGER_TYPE_REQUIRED(const Pos: TTextPosition); static;
class procedure ERROR_ORDINAL_TYPE_REQUIRED(const Pos: TTextPosition); static;
class procedure ERROR_PROC_OR_PROCVAR_REQUIRED(const ID: TIdentifier); static;
class procedure ERROR_PROC_REQUIRED(const Position: TTextPosition); static;
class procedure ERROR_PROC_OR_TYPE_REQUIRED(const ID: TIdentifier); static;
class procedure ERROR_CANNOT_ACCESS_TO_WRITEONLY_PROPERTY(const Expr: TIDExpression); static;
class procedure ERROR_CANNOT_MODIFY_READONLY_PROPERTY(const Expr: TIDExpression); static;
class procedure ERROR_OVERLOAD(CallExpr: TIDExpression); static;
class procedure ERROR_AMBIGUOUS_OVERLOAD_CALL(CallExpr: TIDExpression); static;
class procedure ERROR_INCOMPLETE_PROC(Decl: TIDDeclaration); static;
class procedure ERROR_NO_OVERLOAD_OPERATOR_FOR_TYPES(Op: TOperatorID; Left, Right: TIDExpression); overload; static;
class procedure ERROR_NO_OVERLOAD_OPERATOR_FOR_TYPES(Op: TOperatorID; Right: TIDExpression); overload;
class procedure ERROR_UNIT_NOT_FOUND(const ID: TIdentifier); static;
class procedure ERROR_UNIT_RECURSIVELY_USES_ITSELF(const ID: TIdentifier); static;
class procedure ERROR_SETTER_MUST_BE_SUCH(const Setter: TIDProcedure; const DeclString: string); static;
class procedure ERROR_GETTER_MUST_BE_SUCH(const Getter: TIDProcedure; const DeclString: string); static;
class procedure ERROR_DIVISION_BY_ZERO(Expr: TIDExpression); static;
class procedure ERROR_CONST_VALUE_OVERFLOW(Expr: TIDExpression; DstDataType: TIDType); static;
class procedure ERROR_CLASS_TYPE_REQUIRED(const TextPosition: TTextPosition); static;
class procedure ERROR_TYPE_REQUIRED(const TextPosition: TTextPosition); static;
class procedure ERROR_CLASS_OR_INTF_TYPE_REQUIRED(const TextPosition: TTextPosition); static;
class procedure ERROR_CLASS_NOT_IMPLEMENT_INTF(const Src: TIDExpression; Dest: TIDType); static;
class procedure ERROR_METHOD_NOT_DECLARED_IN_CLASS(const ID: TIdentifier; Struct: TIDStructure); static;
class procedure ERROR_INPLACEVAR_ALLOWED_ONLY_FOR_OUT_PARAMS(Variable: TIDVariable);
class procedure ERROR_CANNOT_ACCESS_PRIVATE_MEMBER(const ID: TIdentifier); static;
class procedure ERROR_REF_PARAM_MUST_BE_IDENTICAL(Expr: TIDExpression);
class procedure ERROR_UNKNOWN_OPTION(const ID: TIdentifier);
class procedure ERROR_CANNOT_ASSIGN_TEMPORARRY_OBJECT(Expr: TIDExpression);
class procedure ERROR_INTF_TYPE_REQUIRED(Expr: TIDExpression);
class procedure ERROR_INTF_ALREADY_IMPLEMENTED(Expr: TIDExpression);
class procedure ERROR_INTF_METHOD_NOT_IMPLEMENTED(ClassType: TIDClass; Proc: TIDProcedure);
class procedure ERROR_RECORD_STATIC_CONSTRUCTOR_ALREADY_EXIST(const Proc: TIDProcedure);
class procedure ERROR_RECORD_STATIC_DESTRUCTOR_ALREADY_EXIST(const Proc: TIDProcedure);
class procedure ERROR_CTOR_DTOR_MUST_BE_DECLARED_IN_STRUCT(const Position: TTextPosition);
class procedure ERROR_OPERATOR_MUST_BE_DECLARED_IN_STRUCT(const Position: TTextPosition);
class procedure ERROR_CANNOT_ASSIGN_NULL_TO_NOTNULL(const Src: TIDExpression);
class procedure ERROR_ORDINAL_OR_SET_REQUIRED(const Src: TIDExpression);
class procedure ERROR_REFERENCE_TYPE_EXPECTED(const Expr: TIDExpression);
class procedure ERROR_STRING_CONST_IS_NOT_ANSI(const Src: TIDExpression);
class procedure ERROR_VAR_IS_NOT_INITIALIZED(const Variable: TIDExpression);
procedure ERROR_NO_METHOD_IN_BASE_CLASS(Proc: TIDProcedure);
procedure ERROR_DEFAULT_PROP_MUST_BE_ARRAY_PROP;
procedure ERROR_DEFAULT_PROP_ALREADY_EXIST(Prop: TIDProperty);
procedure ERROR_IMPORT_FUNCTION_CANNOT_BE_INLINE;
procedure ERROR_INVALID_TYPE_DECLARATION;
procedure ERROR_EXPECTED_TOKEN(Token: TTokenID; ActulToken: TTokenID = token_unknown);
procedure ERROR_EXPECTED_KEYWORD_OR_ID;
procedure ERROR_IDENTIFIER_EXPECTED(ActualToken: TTokenID); overload;
procedure ERROR_IDENTIFIER_EXPECTED; overload;
procedure ERROR_PARAM_NAME_ID_EXPECTED(ActualToken: TTokenID);
procedure ERROR_SEMICOLON_EXPECTED;
procedure ERROR_EMPTY_EXPRESSION;
procedure ERROR_END_OF_FILE;
procedure ERROR_EXPRESSION_EXPECTED;
procedure ERROR_FEATURE_NOT_SUPPORTED(const UnsupportedKeyword: string = '');
procedure ERROR_INTF_SECTION_MISSING;
procedure ERROR_KEYWORD_EXPECTED;
procedure ERROR_BEGIN_KEYWORD_EXPECTED;
procedure ERROR_DUPLICATE_SPECIFICATION(Spec: TProcSpecification);
procedure ERROR_UNSUPPORTED_OPERATOR(Op: TOperatorID);
procedure ERROR_TRY_KEYWORD_MISSED;
procedure ERROR_EXPORT_ALLOWS_ONLY_IN_INTF_SECTION;
procedure ERROR_NEED_SPECIFY_NINDEXES(const Decl: TIDDeclaration);
procedure ERROR_IDENTIFIER_HAS_NO_MEMBERS(const Decl: TIDDeclaration);
procedure ERROR_INVALID_COND_DIRECTIVE;
procedure ERROR_INCOMPLETE_STATEMENT(const Statement: string = '');
procedure ERROR_PROC_OR_PROP_OR_VAR_REQUIRED;
procedure HINT_TEXT_AFTER_END;
procedure ERROR_PARAM_TYPE_REQUIRED;
procedure ERROR_INHERITED_ALLOWED_ONLY_IN_OVERRIDE_METHODS;
procedure ERROR_UNCLOSED_OPEN_BLOCK;
procedure ERROR_UNNECESSARY_CLOSED_BLOCK;
procedure ERROR_UNNECESSARY_CLOSED_ROUND;
procedure ERROR_INIT_SECTION_ALREADY_DEFINED;
procedure ERROR_FINAL_SECTION_ALREADY_DEFINED;
procedure ERROR_ORDINAL_CONST_OR_TYPE_REQURED;
procedure ERROR_DESTRUCTOR_CANNOT_BE_CALL_DIRECTLY;
procedure ERROR_VIRTUAL_ALLOWED_ONLY_IN_CLASSES;
procedure ERROR_WEAKREF_CANNOT_BE_DECLARED_FOR_TYPE(TypeDecl: TIDType);
procedure ERROR_TYPE_IS_NOT_AN_ANCESTOR_FOR_THIS_TYPE(TypeDecl, ChildType: TIDType);
procedure ERROR_INVALID_HEX_CONSTANT;
procedure ERROR_INVALID_BIN_CONSTANT;
procedure ERROR_INTERNAL(const Message: string = 'GENERAL ERROR');
//procedure HINT_RESULT_EXPR_IS_NOT_USED(const Expr: TIDExpression);
//procedure HINT_TYPE_DELETE_UNUSED(Decl: TIDDeclaration);
//procedure HINT_PROC_DELETE_UNUSED(Decl: TIDDeclaration);
end;
implementation
uses AST.Parser.Utils,
AST.Parser.Errors,
AST.Parser.Messages;
resourcestring
sIncompleteStatement = 'Incomplete statement';
procedure TASTDelphiErrors.ERROR_INCOMPLETE_STATEMENT(const Statement: string);
begin
if Statement <> '' then
AbortWork(sIncompleteStatement + ': ' + Statement, Lexer.Position)
else
AbortWork(sIncompleteStatement, Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_INHERITED_ALLOWED_ONLY_IN_OVERRIDE_METHODS;
begin
AbortWork('INHERITED calls allowed only in OVERRIDE methods', Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_INIT_SECTION_ALREADY_DEFINED;
begin
AbortWork('INITIALIZATION section is already defined', Lexer.Position);
end;
class procedure TASTDelphiErrors.ERROR_INPLACEVAR_ALLOWED_ONLY_FOR_OUT_PARAMS(Variable: TIDVariable);
begin
AbortWork('Inpalce VAR declaration allowed only for OUT parameters', Variable.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_INCOMPATIBLE_TYPES(const Src, Dst: TIDExpression);
var
SrcName, DstName: string;
begin
if Src.ItemType <> itType then SrcName := Src.DataTypeName else SrcName := Src.DisplayName;
if Dst.ItemType <> itType then DstName := Dst.DataTypeName else DstName := Dst.DisplayName;
AbortWork(sIncompatibleTypesFmt, [SrcName, DstName], Src.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_INCOMPATIBLE_TYPES(const Src: TIDExpression; Dst: TIDType);
begin
AbortWork(sIncompatibleTypesFmt, [Src.DataTypeName, Dst.DisplayName], Src.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CONST_EXPRESSION_REQUIRED(Expr: TIDExpression);
begin
AbortWork(sExpressionMustBeConstant, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CONST_VALUE_OVERFLOW(Expr: TIDExpression; DstDataType: TIDType);
begin
AbortWork(sConstValueOverflowFmt, [Expr.DisplayName, DstDataType.DisplayName], Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CTOR_DTOR_MUST_BE_DECLARED_IN_STRUCT(const Position: TTextPosition);
begin
AbortWork('CONSTRUCTOR or DESTRUCTOR must be declared only in a CLASS or RECORD type', Position);
end;
class procedure TASTDelphiErrors.ERROR_OPERATOR_MUST_BE_DECLARED_IN_STRUCT(const Position: TTextPosition);
begin
AbortWork('OPERATOR must be declared only in a CLASS or RECORD type', Position);
end;
class procedure TASTDelphiErrors.ERROR_VAR_EXPRESSION_REQUIRED(Expr: TIDExpression);
begin
AbortWork(sVariableRequired, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_VAR_IS_NOT_INITIALIZED(const Variable: TIDExpression);
begin
// пока еще не доделано
// AbortWork('Variable "%s" is not initialized', [Variable.DisplayName], Variable.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_VAR_OR_PROC_EXPRESSION_REQUIRED(Expr: TIDExpression);
begin
AbortWork(sVarOrProcRequired, Expr.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_VIRTUAL_ALLOWED_ONLY_IN_CLASSES;
begin
AbortWork('VIRTUAL allowed only for class methods', Lexer_PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_WEAKREF_CANNOT_BE_DECLARED_FOR_TYPE(TypeDecl: TIDType);
begin
AbortWork('The WEAK reference can not be declared for type: %s', [TypeDecl.DisplayName], Lexer_PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_ARG_VAR_REQUIRED(Expr: TIDExpression);
begin
AbortWork(sConstCannotBePassedAsVarParam, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_MODIFY_CONSTANT(Expr: TIDExpression);
begin
AbortWork(sCannotModifyObjectPassedAsConstParam, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_MODIFY_FOR_LOOP_VARIABLE(Expr: TIDExpression);
begin
AbortWork(sCannotModifyForLoopIndexVarFmt, [Expr.DisplayName], Expr.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_BEGIN_KEYWORD_EXPECTED;
begin
AbortWork('BEGIN expected', Lexer_PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_BOOLEAN_EXPRESSION_REQUIRED(Expr: TIDExpression);
begin
AbortWork(sExpressionMustBeBoolean, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_NOT_ENOUGH_ACTUAL_PARAMS(CallExpr: TIDExpression);
begin
AbortWork(sNotEnoughActualParametersFmt, [CallExpr.DisplayName], CallExpr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_OVERLOADED_MUST_BE_MARKED(const ID: TIdentifier);
begin
AbortWork(sOverloadedMustBeMarked, [ID.Name], ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_DECL_DIFF_WITH_PREV_DECL(const ID: TIdentifier);
begin
AbortWork(sDeclDifWithPrevDecl, [ID.Name], ID.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_DEFAULT_PROP_ALREADY_EXIST(Prop: TIDProperty);
begin
AbortWork(sDefaultPropertyAlreadyExistsFmt, [Prop.Name], Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_DEFAULT_PROP_MUST_BE_ARRAY_PROP;
begin
AbortWork(sDefaultPropertyMustBeAnArrayProperty, Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_DESTRUCTOR_CANNOT_BE_CALL_DIRECTLY;
begin
AbortWork('DESTRUCTOR cannot be call directly', Lexer.PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_DIVISION_BY_ZERO(Expr: TIDExpression);
begin
AbortWork(sDevisionByZero, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_TOO_MANY_ACTUAL_PARAMS(CallExpr: TIDExpression);
begin
AbortWork(sTooManyActualParameters, CallExpr.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_SEMICOLON_EXPECTED;
begin
AbortWork(sSemicolonExpected, Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_EXPECTED_KEYWORD_OR_ID;
begin
AbortWork(sExpectedButFoundFmt, ['Identifier or keyword', Lexer.TokenName], Lexer_Position);
end;
procedure TASTDelphiErrors.ERROR_EXPECTED_TOKEN(Token: TTokenID; ActulToken: TTokenID = token_unknown);
begin
if ActulToken = token_unknown then
AbortWork(sExpected, ['Token "' + UpperCase(Lexer.TokenLexem(Token)) + '"'], Lexer.PrevPosition)
else
AbortWork(sExpectedButFoundFmt, ['Token "' + UpperCase(Lexer.TokenLexem(Token)) + '"',
UpperCase(Lexer.TokenLexem(ActulToken))], Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_IDENTIFIER_EXPECTED(ActualToken: TTokenID);
begin
AbortWork(sIdExpectedButFoundFmt, [Lexer.TokenLexem(ActualToken)], Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_PARAM_NAME_ID_EXPECTED(ActualToken: TTokenID);
begin
AbortWork(sIdExpectedButFoundFmt, [Lexer.TokenLexem(ActualToken)], Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_PARAM_TYPE_REQUIRED;
begin
AbortWork(sParameterTypeRequred, Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_IDENTIFIER_EXPECTED;
begin
AbortWork(sIdentifierExpected, Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_EMPTY_EXPRESSION;
begin
AbortWork(sEmptyExpression, Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_EXPRESSION_EXPECTED;
begin
AbortWork(sExpressionExpected, Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_END_OF_FILE;
begin
AbortWork(sUnexpectedEndOfFile, Lexer.PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_FEATURE_NOT_SUPPORTED(const UnsupportedKeyword: string);
begin
if UnsupportedKeyword <> '' then
AbortWork(sFeatureNotSupported + ': ' + UnsupportedKeyword, Lexer.Position)
else
AbortWork(sFeatureNotSupported + UnsupportedKeyword, Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_FINAL_SECTION_ALREADY_DEFINED;
begin
AbortWork('FINALIZATION section is already defined', Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_INTERNAL(const Message: string);
begin
AbortWorkInternal('Internal error: ' + Message, Lexer_Position);
end;
class procedure TASTDelphiErrors.ERROR_INTF_ALREADY_IMPLEMENTED(Expr: TIDExpression);
begin
AbortWork('INTERFACE "%s" is already implemented', [Expr.DisplayName], Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_INTF_METHOD_NOT_IMPLEMENTED(ClassType: TIDClass; Proc: TIDProcedure);
begin
AbortWork('Interface method "%s" is not implemented in class "%s"', [Proc.DisplayName, ClassType.DisplayName], ClassType.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_INTF_SECTION_MISSING;
begin
AbortWork(sIntfSectionMissing, Lexer.Position);
end;
class procedure TASTDelphiErrors.ERROR_INTF_TYPE_REQUIRED(Expr: TIDExpression);
begin
AbortWork('INTERFACE type required', Expr.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_INVALID_BIN_CONSTANT;
begin
AbortWork('Invalid BIN constant', Lexer_Position);
end;
procedure TASTDelphiErrors.ERROR_INVALID_COND_DIRECTIVE;
begin
AbortWork(sInvalidConditionalStatement, Lexer_Position);
end;
procedure TASTDelphiErrors.ERROR_INVALID_HEX_CONSTANT;
begin
AbortWork('Invalid HEX constant', Lexer_Position);
end;
class procedure TASTDelphiErrors.ERROR_INVALID_EXPLICIT_TYPECAST(const Src: TIDExpression; Dst: TIDType);
begin
AbortWork(sInvalidTypecastFmt, [Src.DataTypeName, Dst.DisplayName], Src.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_INVALID_TYPE_DECLARATION;
begin
AbortWork(sInvalidTypeDeclaration, Lexer.PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_ID_REDECLARATED(Decl: TIDDeclaration);
begin
AbortWork(sIdentifierRedeclaredFmt, [Decl.DisplayName], Decl.SourcePosition);
end;
class procedure TASTDelphiErrors.ERROR_ID_REDECLARATED(const ID: TIdentifier);
begin
AbortWork(sIdentifierRedeclaredFmt, [ID.Name], ID.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_IMPORT_FUNCTION_CANNOT_BE_INLINE;
begin
AbortWork(sImportFuncCannotBeInline, Lexer_Position);
end;
procedure TASTDelphiErrors.ERROR_UNCLOSED_OPEN_BLOCK;
begin
AbortWork(sUnclosedOpenBlock, Lexer.PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_UNDECLARED_ID(const ID: TIdentifier);
begin
AbortWork(sUndeclaredIdentifier, [ID.Name], ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_UNDECLARED_ID(const ID: TIdentifier; const GenericParams: TIDTypeList);
var
i: integer;
s: string;
begin
if Assigned(GenericParams) then
begin
for i := 0 to Length(GenericParams) - 1 do
s := AddStringSegment(s, GenericParams[i].Name, ', ');
s := '<' + s + '>';
end;
AbortWork(sUndeclaredIdentifier, [ID.Name + s], ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_UNDECLARED_ID(const Name: string; const TextPosition: TTextPosition);
begin
AbortWork(sUndeclaredIdentifier, [Name], TextPosition);
end;
procedure TASTDelphiErrors.ERROR_UNNECESSARY_CLOSED_BLOCK;
begin
AbortWork(sUnnecessaryClosedBlock, Lexer_Position);
end;
procedure TASTDelphiErrors.ERROR_UNNECESSARY_CLOSED_ROUND;
begin
AbortWork(sUnnecessaryClosedBracket, Lexer_Position);
end;
class procedure TASTDelphiErrors.ERROR_UNIT_NOT_FOUND(const ID: TIdentifier);
begin
AbortWork(sUnitNotFoundFmt, [ID.Name], ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_UNIT_RECURSIVELY_USES_ITSELF(const ID: TIdentifier);
begin
AbortWork(sUnitRecursivelyUsesItselfFmt, [ID.Name], ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_UNKNOWN_OPTION(const ID: TIdentifier);
begin
AbortWork('Unknown option: %s', [ID.Name], ID.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_KEYWORD_EXPECTED;
begin
AbortWork(sKeywordExpected, [Lexer.OriginalToken], Lexer.Position);
end;
class procedure TASTDelphiErrors.ERROR_METHOD_NOT_DECLARED_IN_CLASS(const ID: TIdentifier; Struct: TIDStructure);
begin
AbortWork('Method "%s" is not declared in "%s"', [ID.Name, Struct.Name], ID.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_DUPLICATE_SPECIFICATION(Spec: TProcSpecification);
var
SpecName: string;
begin
case Spec of
PS_FORWARD: SpecName := 'FORWARD';
PS_INLINE: SpecName := 'INLINE';
PS_PURE: SpecName := 'PURE';
PS_NORETURN: SpecName := 'NORETURN';
PS_NOEXCEPT: SpecName := 'NOEXCEPT';
PS_OVELOAD: SpecName := 'OVERLOAD';
PS_EXPORT: SpecName := 'EXPORT';
PS_IMPORT: SpecName := 'EXTERNAL';
PS_VIRTUAL: SpecName := 'VIRTUAL';
PS_OVERRIDE: SpecName := 'OVERRIDE';
PS_STATIC: SpecName := 'STATIC';
PS_STDCALL: SpecName := 'STDCALL';
PS_CDECL: SpecName := 'CDECL';
PS_FASTCALL: SpecName := 'REGISTER';
PS_REINTRODUCE: SpecName := 'REINTRODUCE';
else
SpecName := '<UNKNOWN>';
end;
AbortWork(sDuplicateSpecificationFmt, [SpecName], Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_UNSUPPORTED_OPERATOR(Op: TOperatorID);
begin
AbortWork('Unsupported operator "%s"', [OperatorFullName(Op)], Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_TRY_KEYWORD_MISSED;
begin
AbortWork(sTryKeywordMissed, Lexer.Position);
end;
procedure TASTDelphiErrors.ERROR_TYPE_IS_NOT_AN_ANCESTOR_FOR_THIS_TYPE(TypeDecl, ChildType: TIDType);
begin
AbortWork('The type "%s" is not an ancestor of type "%s"', [TypeDecl.DisplayName, ChildType.DisplayName], Lexer.Position);
end;
class procedure TASTDelphiErrors.ERROR_TYPE_REQUIRED(const TextPosition: TTextPosition);
begin
AbortWork('TYPE specification required', TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_SETTER_MUST_BE_SUCH(const Setter: TIDProcedure; const DeclString: string);
begin
AbortWork('Setter must have declaration: %s', [DeclString], Setter.ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_GETTER_MUST_BE_SUCH(const Getter: TIDProcedure; const DeclString: string);
begin
AbortWork('Getter must have declaration: %s', [DeclString], Getter.ID.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_EXPORT_ALLOWS_ONLY_IN_INTF_SECTION;
begin
AbortWork(sExportAllowsOnlyInIntfSection, Lexer.Position);
end;
class procedure TASTDelphiErrors.ERROR_STRING_CONST_IS_NOT_ANSI(const Src: TIDExpression);
begin
AbortWork('string constant is not an ANSI string', Src.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_STRUCT_TYPE_REQUIRED(const TextPosition: TTextPosition);
begin
AbortWork(sStructTypeRequired, TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_ARRAY_EXPRESSION_REQUIRED(Expr: TIDExpression);
begin
AbortWork('ARRAY expression required', Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_ARRAY_TYPE_REQUIRED(const ID: TIdentifier; const TextPosition: TTextPosition);
begin
AbortWork(sArrayTypeRequired, TextPosition);
end;
procedure TASTDelphiErrors.ERROR_ORDINAL_CONST_OR_TYPE_REQURED;
begin
AbortWork(sOrdinalConstOrTypeRequred, Lexer_PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_ORDINAL_OR_SET_REQUIRED(const Src: TIDExpression);
begin
AbortWork('ORDINAL or SET required', Src.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_INTEGER_TYPE_REQUIRED(const Pos: TTextPosition);
begin
AbortWork('INTEGER type required', Pos);
end;
class procedure TASTDelphiErrors.ERROR_ORDINAL_TYPE_REQUIRED(const Pos: TTextPosition);
begin
AbortWork(sOrdinalTypeRequired, Pos);
end;
class procedure TASTDelphiErrors.ERROR_PROC_OR_PROCVAR_REQUIRED(const ID: TIdentifier);
begin
AbortWork(sProcOrProcVarRequired, ID.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_PROC_OR_PROP_OR_VAR_REQUIRED;
begin
AbortWork('PROCEDURE or FUNCTION or PROPERTY or VAR required', [], Lexer.PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_PROC_OR_TYPE_REQUIRED(const ID: TIdentifier);
begin
AbortWork('PROCEDURE or TYPE required', ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_PROC_REQUIRED(const Position: TTextPosition);
begin
AbortWork('PROCEDURE or FUNCTION required', Position);
end;
class procedure TASTDelphiErrors.ERROR_RECORD_STATIC_CONSTRUCTOR_ALREADY_EXIST(const Proc: TIDProcedure);
begin
AbortWork('Record CONSTRUCTOR already exist', Proc.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_RECORD_STATIC_DESTRUCTOR_ALREADY_EXIST(const Proc: TIDProcedure);
begin
AbortWork('Record DESTRUCTOR already exist', Proc.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_REFERENCE_TYPE_EXPECTED(const Expr: TIDExpression);
begin
AbortWork('REFERENCE type required', Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_REF_PARAM_MUST_BE_IDENTICAL(Expr: TIDExpression);
begin
AbortWork('Types of actual and formal VAR parameters must be identical: ' + Expr.DisplayName, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_MODIFY_READONLY_PROPERTY(const Expr: TIDExpression);
begin
AbortWork(sCannotModifyReadOnlyProperty, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CLASS_NOT_IMPLEMENT_INTF(const Src: TIDExpression; Dest: TIDType);
begin
AbortWork('CLASS "%s" not implement the "%s" interface', [Src.DataTypeName, Dest.DisplayName], Src.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CLASS_OR_INTF_TYPE_REQUIRED(const TextPosition: TTextPosition);
begin
AbortWork('CLASS or INTERFACE type required', TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CLASS_TYPE_REQUIRED(const TextPosition: TTextPosition);
begin
AbortWork(sCLASSTypeRequired, TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_ACCESS_PRIVATE_MEMBER(const ID: TIdentifier);
begin
AbortWork('Cannot access private member: %s', [ID.Name], ID.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_ACCESS_TO_WRITEONLY_PROPERTY(const Expr: TIDExpression);
begin
AbortWork(sCannotAccessToWriteOnlyProperty, Expr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_ASSIGN_NULL_TO_NOTNULL(const Src: TIDExpression);
begin
AbortWork('Cannot assign NULLPTR to NOT NULL variable', [], Src.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_CANNOT_ASSIGN_TEMPORARRY_OBJECT(Expr: TIDExpression);
begin
AbortWork('Cannot modify a temporary object', Expr.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_NEED_SPECIFY_NINDEXES(const Decl: TIDDeclaration);
var
ADataType: TIDArray;
begin
ADataType := TIDArray(Decl.DataType);
AbortWork(sNeedSpecifyNIndexesFmt, [Decl.DisplayName, ADataType.DisplayName, ADataType.DimensionsCount], Lexer_PrevPosition);
end;
procedure TASTDelphiErrors.ERROR_IDENTIFIER_HAS_NO_MEMBERS(const Decl: TIDDeclaration);
begin
AbortWork(sIdentifierHasNoMembersFmt, [Decl.DisplayName], Lexer.PrevPosition);
end;
class procedure TASTDelphiErrors.ERROR_OVERLOAD(CallExpr: TIDExpression);
begin
AbortWork(sErrorOverload, CallExpr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_AMBIGUOUS_OVERLOAD_CALL(CallExpr: TIDExpression);
begin
AbortWork(sAmbiguousOverloadedCallFmt, [CallExpr.DisplayName], CallExpr.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_INCOMPLETE_PROC(Decl: TIDDeclaration);
var
ProcName: string;
begin
ProcName := Decl.DisplayName;
if Assigned(TIDProcedure(Decl).Struct) then
ProcName := TIDProcedure(Decl).Struct.Name + '.' + ProcName;
AbortWork(sIncompleteProcFmt, [ProcName], Decl.SourcePosition);
end;
class procedure TASTDelphiErrors.ERROR_NO_OVERLOAD_OPERATOR_FOR_TYPES(Op: TOperatorID; Left, Right: TIDExpression);
begin
AbortWork(sNoOverloadOperatorForTypesFmt, [OperatorFullName(Op), Left.DataTypeName, Right.DataTypeName], Left.TextPosition);
end;
class procedure TASTDelphiErrors.ERROR_NO_OVERLOAD_OPERATOR_FOR_TYPES(Op: TOperatorID; Right: TIDExpression);
begin
AbortWork(sNoOverloadOperatorForTypeFmt, [OperatorFullName(Op), Right.DataTypeName], Right.TextPosition);
end;
procedure TASTDelphiErrors.ERROR_NO_METHOD_IN_BASE_CLASS(Proc: TIDProcedure);
begin
AbortWork('Method %s is not found in base classes', [Proc.DisplayName], Lexer.Position);
end;
procedure TASTDelphiErrors.HINT_TEXT_AFTER_END;
begin
PutMessage(cmtHint, 'Text after final END. - ignored by compiler', Lexer_PrevPosition);
end;
//procedure TASTDelphiErrors.HINT_RESULT_EXPR_IS_NOT_USED(const Expr: TIDExpression);
//begin
// if Assigned(Expr.DataType) then
// PutMessage(cmtHint, 'Expression result (type: ' + Expr.DataType.DisplayName + ') is not used', Expr.TextPosition)
// else
// PutMessage(cmtHint, 'Expression result is not used', Expr.TextPosition);
//end;
end.
|
unit Abort;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons;
type
tEstado = ( esFuncion, esAborto );
TAbortar = class;
TAbortDlg = class(TForm)
GroupBox1: TGroupBox;
Label1: TLabel;
bbStop: TBitBtn;
procedure bbStopClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
ClsAborto: TAbortar;
end;
TAbortar = class( TObject )
private
FEstado: tEstado;
public
FAbortoDlg: TAbortDlg;
constructor Create;
destructor Destroy;
published
property Estado: tEstado read FEstado write FEstado;
end;
var
AbortDlg: TAbortDlg;
implementation
{$R *.DFM}
{ TAbortar }
constructor TAbortar.Create;
begin
inherited Create;
FEstado := esFuncion;
FAbortoDlg := TAbortDlg.create( application );
FAbortoDlg.clsAborto := self;
FAbortoDlg.Show;
end;
destructor TAbortar.Destroy;
begin
FAbortoDlg.free;
inherited destroy;
end;
procedure TAbortDlg.bbStopClick(Sender: TObject);
begin
clsAborto.Estado := esAborto;
bbStop.caption := 'Detenido';
bbStop.Enabled := false;
Application.ProcessMessages;
end;
procedure TAbortDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end;
end.
|
unit GX_EditorChangeServices;
{
The basic goal of this unit is to flatten the
nice hierarchical structure of what the OTA
has to offer.
Flattening the hierarchy has the advantage of
centralising all "attach" and "detach" code
into one closed part of the code. It also
makes it easier for clients to receive
notification by drastically reducing
admininistrative overhead.
}
interface
{$I GX_CondDefine.inc}
{$UNDEF UseInternalTestClient}
{.$DEFINE UseInternalTestClient}
uses
ToolsAPI;
type
{ Implement the IGxEditorNotification interface to learn of
interesting events that happen deep down inside the IDE.
The notifier is installed via GxEditorChangeServices. }
IGxEditorNotification = interface(IInterface)
['{EF8D8061-F41E-11D3-A7CF-B41D01000000}']
// A new module has been opened in the IDE
procedure NewModuleOpened(const Module: IOTAModule);
// The editor buffer SourceEditor has been modified.
procedure SourceEditorModified(const SourceEditor: IOTASourceEditor);
// The form buffer FormEditor has been modified.
procedure FormEditorModified(const FormEditor: IOTAFormEditor);
// A component on a form was renamed
procedure ComponentRenamed(const FormEditor: IOTAFormEditor;
Component: IOTAComponent; const OldName, NewName: string);
// A key was pressed inside the source editor
function EditorKeyPressed(const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean;
// The index that is used to unregister this notifier from GExperts
function GetIndex: Integer;
end;
type
IGxEditorChangeServices = interface(IInterface)
['{AB0A1721-F1BD-11D3-A7C6-0E7655000000}']
// Installs a notifier to receive change services; returns
// an index >= 0 to be used for removing the notifier.
function AddNotifier(Notifier: IGxEditorNotification): Integer;
// Removes an installed notifier; use the index returned by
// AddNotifier to identify the notifier to be removed.
procedure RemoveNotifierIfNecessary(var Index: Integer);
end;
function GxEditorChangeServices: IGxEditorChangeServices;
procedure ReleaseEditorChangeServices;
implementation
uses
{$IFOPT D+} GX_DbugIntf, TypInfo, {$ENDIF}
SysUtils, Windows, Classes, Messages, Controls, Forms,
GX_GenericUtils, GX_GenericClasses, GX_IdeUtils, GX_OtaUtils;
type
TInternalIdeNotification = (iinNewModule, iinSourceEditorModified, iinFormEditorModified, iinEditorKeyPressed);
{$IFOPT D+}
var
TEditorChangeServicesCount: Integer = 0;
{$ENDIF D+}
type
TEditorChangeServices = class(TSingletonInterfacedObject, IGxEditorChangeServices)
private
FNotifiers: TInterfaceList;
FNextIndex: Integer;
procedure ClearNotifiers;
private
FIdeNotifierIndex: Integer;
procedure InstallInternalIdeNotifier;
procedure RemoveInternalIdeNotifier;
private
procedure GenericInternalIdeNotification(const NotifyType: TInternalIdeNotification;
const GenericParameter: IInterface; CharCode: Word = 0; KeyData: Integer = 0);
public
constructor Create;
destructor Destroy; override;
function AddNotifier(Notifier: IGxEditorNotification): Integer;
procedure RemoveNotifierIfNecessary(var Index: Integer);
end;
{$IFOPT D+}
var
TGxIdeNotifierCount: Integer = 0;
{$ENDIF D+}
type
TGxIdeNotifier = class(TNotifierObject, IOTAIdeNotifier, IOTAIDENotifier50)
private
FChangeServicesClient: TEditorChangeServices;
FInstalledModuleNotifiers: TInterfaceList;
procedure ClearInstalledModuleNotifiers;
procedure RemoveInstalledModuleNotifiers;
procedure InstallModuleNotifiersIntoExistingModules;
procedure InstallModuleNotifier(const IdeNotifiedFileName: string); overload;
procedure InstallModuleNotifier(const IModule: IOTAModule); overload;
function HasNotifierBeenInstalled(const FileName: string): Boolean;
procedure NotifyClientNewModule(const Module: IOTAModule);
function ValidModuleFileName(const FileName: string): Boolean;
protected
// IOTAIdeNotifier
procedure FileNotification(NotifyCode: TOTAFileNotification;
const FileName: string; var Cancel: Boolean);
procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean); overload;
procedure AfterCompile(Succeeded: Boolean); overload;
// IOTAIDENotifier50
procedure BeforeCompile(const Project: IOTAProject; IsCodeInsight: Boolean;
var Cancel: Boolean); overload;
procedure AfterCompile(Succeeded: Boolean; IsCodeInsight: Boolean); overload;
public
constructor Create(Client: TEditorChangeServices);
destructor Destroy; override;
end;
// The IGxNotifierUninstallation interface is used to
// instruct an installed notifier instance to remove
// itself, and all notifiers it makes uses of, from
// the Open Tools API.
// This will be used to completely detach from the IDE
// when a package is (dynamically) uninstalled and
// notifiers are still hooked into the IDE.
IGxNotifierUninstallation = interface(IInterface)
['{E26441D1-250E-11D4-A872-66A3BC000000}']
procedure UninstallNotifier;
end;
IGxModuleNotifier = interface(IOTAModuleNotifier)
['{838446E1-F454-11D3-A7CF-B41D01000000}']
function GetAssociatedModule: IOTAModule;
property AssociatedModule: IOTAModule read GetAssociatedModule;
end;
{$IFOPT D+}
var
TGxModuleNotifierCount: Integer = 0;
{$ENDIF D+}
type
TGxModuleNotifier = class(TInterfacedObject, IOTANotifier,
IOTAModuleNotifier, IGxModuleNotifier,
IGxNotifierUninstallation)
private
FIdeClient: TGxIdeNotifier;
private
FSelfNotifierIndex: Integer;
procedure RemoveSelfNotifier;
private
FCachedSourceEditors: array of IOTASourceEditor;
// Note that this list of editor notifiers contains both
// IOTAEditorNotifier and IOTAFormNotifier interface instances.
FInstalledEditorNotifiers: TInterfaceList;
private
FAssociatedModule: IOTAModule;
FFileName: string;
procedure InstallEditorNotifiers;
procedure RemoveEditorNotifiers;
procedure RemoveSelfFromClient;
protected
// IOTANotifier - just there for playing
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
// IOTAModuleNotifier
function CheckOverwrite: Boolean;
procedure ModuleRenamed(const NewName: string);
// IGxModuleNotifier
function GetAssociatedModule: IOTAModule;
// IGxNotifierUninstallation
procedure UninstallNotifier;
public
constructor Create(AssociatedModule: IOTAModule; Client: TGxIdeNotifier);
destructor Destroy; override;
end;
type
TGxBaseEditorNotifier = class(TNotifierObject, IOTANotifier)
private
FSelfNotifierIndex: Integer;
FModuleClient: TGxModuleNotifier;
procedure GenericNotification(const NotifyType: TInternalIdeNotification;
const GenericParameter: IInterface; CharCode: Word = 0; KeyData: Integer = 0);
protected
// Base implementation of IGxNotifierUninstallation
FFileName: string;
procedure UninstallNotifier;
protected
procedure RemoveSelfFromClient;
procedure RemoveSelfNotifier; virtual; abstract;
end;
{$IFOPT D+}
var
TGxEditorNotifierCount: Integer = 0;
{$ENDIF D+}
type
TGxEditorNotifier = class(TGxBaseEditorNotifier, IOTANotifier,
IOTAEditorNotifier,
IGxNotifierUninstallation)
private
FAssociatedSourceEditor: IOTASourceEditor;
FNewEditControlWndProc: Pointer;
FOldEditControlWndProc: Integer;
//FEditorHandle: THandle;
procedure EditControlWndProc(var Msg: TMessage);
function GetEditControl: TWinControl;
procedure HookEditorWndProc;
procedure UnhookEditorWndProc;
protected
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
// IOTAEditorNotifier
procedure ViewNotification(const View: IOTAEditView; Operation: TOperation);
procedure ViewActivated(const View: IOTAEditView);
procedure RemoveSelfNotifier; override;
public
constructor Create(const Client: TGxModuleNotifier; const ISourceEditor: IOTASourceEditor);
destructor Destroy; override;
end;
{$IFOPT D+}
var
TGxFormNotifierCount: Integer = 0;
{$ENDIF D+}
type
TGxFormNotifier = class(TGxBaseEditorNotifier, IOTANotifier,
IOTAFormNotifier,
IGxNotifierUninstallation)
private
FAssociatedFormEditor: IOTAFormEditor;
protected
// IOTANotifier - just there for playing;
// doesn't do anything and is not used in a meaningful way.
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
protected
// IOTAFormNotifier
procedure FormActivated;
procedure FormSaving;
procedure ComponentRenamed(ComponentHandle: TOTAHandle;
const OldName, NewName: string);
protected
procedure RemoveSelfNotifier; override;
public
constructor Create(const Client: TGxModuleNotifier; const IFormEditor: IOTAFormEditor);
destructor Destroy; override;
end;
var
PrivateEditorChangeServices: TEditorChangeServices;
function GxEditorChangeServices: IGxEditorChangeServices;
begin
if not Assigned(PrivateEditorChangeServices) then
PrivateEditorChangeServices := TEditorChangeServices.Create;
Result := PrivateEditorChangeServices;
end;
procedure ReleaseEditorChangeServices;
begin
FreeAndNil(PrivateEditorChangeServices);
end;
{ TEditorChangeServices }
function TEditorChangeServices.AddNotifier(Notifier: IGxEditorNotification): Integer;
begin
Assert(Assigned(Notifier));
FNotifiers.Add(Notifier);
Result := FNextIndex;
Inc(FNextIndex);
Assert(Result >= 0);
end;
procedure TEditorChangeServices.ClearNotifiers;
begin
if not Assigned(FNotifiers) then
Exit;
{$IFOPT D+}
if FNotifiers.Count > 0 then
begin
MessageBox(0, PChar(Format('TEditorChangeServices has %d dangling notifiers',
[FNotifiers.Count])), 'GExperts warning', MB_ICONHAND or MB_OK);
end;
{$ENDIF D+}
FNotifiers.Clear;
end;
constructor TEditorChangeServices.Create;
begin
{$IFOPT D+} SendDebug('Creating TEditorChangeServices'); {$ENDIF}
{$IFOPT D+} Inc(TEditorChangeServicesCount); {$ENDIF}
inherited Create;
FIdeNotifierIndex := InvalidNotifierIndex;
FNotifiers := TInterfaceList.Create;
InstallInternalIdeNotifier;
{$IFOPT D+} SendDebug('Created TEditorChangeServices'); {$ENDIF}
end;
destructor TEditorChangeServices.Destroy;
begin
RemoveInternalIdeNotifier;
//TODO 3 -oAnyone -cFeature: Unhook all editor windows
ClearNotifiers;
FreeAndNil(FNotifiers);
inherited Destroy;
{$IFOPT D+} Dec(TEditorChangeServicesCount); {$ENDIF}
end;
procedure TEditorChangeServices.GenericInternalIdeNotification(
const NotifyType: TInternalIdeNotification;
const GenericParameter: IInterface; CharCode: Word; KeyData: Integer);
var
i: Integer;
INotification: IGxEditorNotification;
begin
Assert(Assigned(FNotifiers));
Assert(Assigned(GenericParameter));
for i := 0 to FNotifiers.Count-1 do
begin
try
INotification := FNotifiers[i] as IGxEditorNotification;
case NotifyType of
iinNewModule:
INotification.NewModuleOpened(GenericParameter as IOTAModule);
iinSourceEditorModified:
INotification.SourceEditorModified(GenericParameter as IOTASourceEditor);
iinEditorKeyPressed:
INotification.EditorKeyPressed(GenericParameter as IOTASourceEditor, CharCode, KeyData);
iinFormEditorModified:
INotification.FormEditorModified(GenericParameter as IOTAFormEditor);
else
Assert(False, 'Unknown generic internal IDE notify type sent');
end;
except
on E: Exception do
begin
// Silently process the exception and let the IDE take care of the rest
GxLogException(E);
Application.HandleException(Self);
// We deliberately swallow the exception since we do not
// want a failed notifier to mess up anything.
end;
end;
end;
end;
procedure TEditorChangeServices.InstallInternalIdeNotifier;
var
IdeNotifier: TGxIdeNotifier;
begin
IdeNotifier := TGxIdeNotifier.Create(Self);
FIdeNotifierIndex := GxOtaGetIDEServices.AddNotifier(IdeNotifier);
Assert(FIdeNotifierIndex >= 0);
end;
procedure TEditorChangeServices.RemoveInternalIdeNotifier;
begin
if FIdeNotifierIndex <> InvalidNotifierIndex then
begin
GxOtaGetIDEServices.RemoveNotifier(FIdeNotifierIndex);
FIdeNotifierIndex := InvalidNotifierIndex;
end;
end;
procedure TEditorChangeServices.RemoveNotifierIfNecessary(var Index: Integer);
var
i: Integer;
begin
if Index = InvalidNotifierIndex then
Exit;
Assert(Assigned(FNotifiers));
Assert(Index >= 0);
for i := 0 to FNotifiers.Count - 1 do begin
if ((FNotifiers.Items[i] as IGxEditorNotification).GetIndex = Index) then
begin
FNotifiers.Delete(i);
Break;
end;
end;
Index := InvalidNotifierIndex;
end;
{ TGxIdeNotifier }
procedure TGxIdeNotifier.AfterCompile(Succeeded: Boolean);
begin
// Do nothing
end;
procedure TGxIdeNotifier.AfterCompile(Succeeded, IsCodeInsight: Boolean);
begin
// Do nothing
end;
procedure TGxIdeNotifier.BeforeCompile(const Project: IOTAProject; var Cancel: Boolean);
begin
// Do nothing
end;
procedure TGxIdeNotifier.BeforeCompile(const Project: IOTAProject;
IsCodeInsight: Boolean; var Cancel: Boolean);
begin
// Do nothing
end;
procedure TGxIdeNotifier.ClearInstalledModuleNotifiers;
{$IFOPT D+}
var
i: Integer;
UnaccountedModules: string;
{$ENDIF D+}
begin
if not Assigned(FInstalledModuleNotifiers) then
Exit;
{$IFOPT D+}
if FInstalledModuleNotifiers.Count > 0 then
begin
// If we still have module notifiers installed at this
// stage, it means that some cleanup logic failed.
for i := 0 to FInstalledModuleNotifiers.Count - 1 do
begin
with FInstalledModuleNotifiers[i] as IGxModuleNotifier do
UnaccountedModules := UnaccountedModules + AssociatedModule.FileName + '; ';
end;
MessageBox(0, PChar(Format('TGxIdeNotifier has %d unaccounted modules (%s)',
[FInstalledModuleNotifiers.Count, UnaccountedModules])),
'GExperts warning', MB_ICONHAND or MB_OK);
end;
{$ENDIF D+}
FInstalledModuleNotifiers.Clear;
end;
constructor TGxIdeNotifier.Create(Client: TEditorChangeServices);
begin
{$IFOPT D+} Inc(TGxIdeNotifierCount); {$ENDIF}
{$IFOPT D+} SendDebug('Creating TGxIdeNotifier'); {$ENDIF}
inherited Create;
FChangeServicesClient := Client;
FInstalledModuleNotifiers := TInterfaceList.Create;
// Install notifiers into all already loaded modules.
InstallModuleNotifiersIntoExistingModules;
{$IFOPT D+} SendDebug('Created TGxIdeNotifier'); {$ENDIF}
end;
destructor TGxIdeNotifier.Destroy;
begin
{$IFOPT D+} SendDebug('Destroying TGxIdeNotifier'); {$ENDIF}
// Sometimes we never get destroy notifications for DFMs open as text
// This check prevents us from AVing on shutdown trying to remove the
// notifiers for these by-now-closed units
if not Application.Terminated then
begin
RemoveInstalledModuleNotifiers;
ClearInstalledModuleNotifiers;
end;
{$IFOPT D+} SendDebug('Cleared installed module notifiers'); {$ENDIF}
FreeAndNil(FInstalledModuleNotifiers);
{$IFOPT D+} SendDebug('Freed installed module notifiers'); {$ENDIF}
if Assigned(FChangeServicesClient) then
begin
FChangeServicesClient.FIdeNotifierIndex := InvalidNotifierIndex;
FChangeServicesClient := nil;
end;
inherited Destroy;
{$IFOPT D+} SendDebug('TGxIdeNotifier destroyed'); {$ENDIF}
{$IFOPT D+} Dec(TGxIdeNotifierCount); {$ENDIF}
end;
procedure TGxIdeNotifier.FileNotification(NotifyCode: TOTAFileNotification;
const FileName: string; var Cancel: Boolean);
begin
{$IFOPT D+}
SendDebug(Format('File notification %s for "%s"',
[GetEnumName(TypeInfo(TOTAFileNotification), Integer(NotifyCode)), FileName]));
{$ENDIF D+}
case NotifyCode of
ofnFileOpened:
InstallModuleNotifier(FileName);
else // case // FI:W506
// Do nothing
end;
end;
function TGxIdeNotifier.HasNotifierBeenInstalled(const FileName: string): Boolean;
var
GxModuleNotifier: IGxModuleNotifier;
AModule: IOTAModule;
i: Integer;
begin
Assert(Assigned(FInstalledModuleNotifiers));
Result := False;
for i := 0 to FInstalledModuleNotifiers.Count-1 do
begin
GxModuleNotifier := FInstalledModuleNotifiers[i] as IGxModuleNotifier;
Assert(Assigned(GxModuleNotifier));
AModule := GxModuleNotifier.AssociatedModule;
Assert(Assigned(AModule));
Result := SameFileName(AModule.FileName, FileName);
if Result then
Break;
end;
end;
procedure TGxIdeNotifier.InstallModuleNotifier(const IdeNotifiedFileName: string);
var
IModuleServices: IOTAModuleServices;
IModule: IOTAModule;
begin
if not ValidModuleFileName(IdeNotifiedFileName) then
Exit;
IModuleServices := BorlandIDEServices as IOTAModuleServices;
Assert(Assigned(IModuleServices));
IModule := GxOtaGetModule(IdeNotifiedFileName);
if not Assigned(IModule) then begin
{$IFOPT D+} SendDebugError('Module interface not found by the IDE: ' + IdeNotifiedFileName); {$ENDIF}
Exit;
end;
// Sometimes, we are double-notified of modules being opened, so check here
if not HasNotifierBeenInstalled(IdeNotifiedFileName) then
InstallModuleNotifier(IModule);
end;
procedure TGxIdeNotifier.InstallModuleNotifier(const IModule: IOTAModule);
var
GxModuleNotifier: TGxModuleNotifier;
begin
Assert(Assigned(IModule));
if not ValidModuleFileName(IModule.FileName) then
Exit;
GxModuleNotifier := TGxModuleNotifier.Create(IModule, Self);
FInstalledModuleNotifiers.Add(GxModuleNotifier);
NotifyClientNewModule(IModule);
end;
procedure TGxIdeNotifier.InstallModuleNotifiersIntoExistingModules;
var
IModuleServices: IOTAModuleServices;
IModule: IOTAModule;
i: Integer;
begin
IModuleServices := BorlandIDEServices as IOTAModuleServices;
Assert(Assigned(IModuleServices));
for i := 0 to IModuleServices.ModuleCount - 1 do
begin
IModule := IModuleServices.Modules[i];
Assert(Assigned(IModule));
InstallModuleNotifier(IModule);
end;
end;
procedure TGxIdeNotifier.NotifyClientNewModule(const Module: IOTAModule);
begin
Assert(Assigned(FChangeServicesClient));
Assert(Assigned(Module));
{$IFOPT D+} SendDebug('Change services advertise new module ' + Module.FileName); {$ENDIF}
FChangeServicesClient.GenericInternalIdeNotification(iinNewModule, Module);
end;
procedure TGxIdeNotifier.RemoveInstalledModuleNotifiers;
var
INotifierUninstallation: IGxNotifierUninstallation;
begin
if not Assigned(FInstalledModuleNotifiers) then
Exit;
while FInstalledModuleNotifiers.Count > 0 do
begin
INotifierUninstallation := FInstalledModuleNotifiers[0] as IGxNotifierUninstallation;
Assert(Assigned(INotifierUninstallation));
INotifierUninstallation.UninstallNotifier;
// The interface object upon which we call UninstallNotifier
// will remove itself from the list of editor notifiers, i.e.
// from FInstalledEditorNotifiers, thereby reducing
// FInstalledEditorNotifiers.Count down to zero.
end;
end;
function TGxIdeNotifier.ValidModuleFileName(const FileName: string): Boolean;
begin
Result := not FileIsWelcomePage(FileName);
end;
{ TGxModuleNotifier }
procedure TGxModuleNotifier.AfterSave;
begin
// Do nothing
end;
procedure TGxModuleNotifier.BeforeSave;
begin
// Do nothing
end;
function TGxModuleNotifier.CheckOverwrite: Boolean;
begin
Result := True;
end;
constructor TGxModuleNotifier.Create(AssociatedModule: IOTAModule; Client: TGxIdeNotifier);
begin
{$IFOPT D+} Inc(TGxModuleNotifierCount); {$ENDIF}
{$IFOPT D+} SendDebug('Creating TGxModuleNotifier for ' + AssociatedModule.FileName); {$ENDIF}
inherited Create;
FFileName := AssociatedModule.FileName;
SetLength(FCachedSourceEditors, 0);
FSelfNotifierIndex := InvalidNotifierIndex;
Assert(Assigned(Client));
FIdeClient := Client;
FInstalledEditorNotifiers := TInterfaceList.Create;
FSelfNotifierIndex := AssociatedModule.AddNotifier(Self);
// Keep a copy of the associated module around
// without any reference-counting.
NoRefCount(FAssociatedModule) := NoRefCount(AssociatedModule);
InstallEditorNotifiers;
{$IFOPT D+} SendDebug('Created TGxModuleNotifier for ' + AssociatedModule.FileName); {$ENDIF}
end;
destructor TGxModuleNotifier.Destroy;
var
i: Integer;
begin
{$IFOPT D+} SendDebug('Destroying TGxModuleNotifier for ' + FFileName); {$ENDIF}
for i := 0 to Length(FCachedSourceEditors)-1 do
NoRefCount(FCachedSourceEditors[i]) := nil;
RemoveEditorNotifiers;
FreeAndNil(FInstalledEditorNotifiers);
RemoveSelfNotifier;
NoRefCount(FAssociatedModule) := nil;
RemoveSelfFromClient;
{$IFOPT D+} SendDebug('TGxModuleNotifier destroyed for ' + FFileName); {$ENDIF}
{$IFOPT D+} Dec(TGxModuleNotifierCount); {$ENDIF}
inherited;
end;
procedure TGxModuleNotifier.Destroyed;
begin
RemoveSelfNotifier;
// Clear the associated module without invoking
// any reference-counting.
NoRefCount(FAssociatedModule) := nil;
RemoveSelfFromClient;
end;
function TGxModuleNotifier.GetAssociatedModule: IOTAModule;
begin
Result := FAssociatedModule;
end;
procedure TGxModuleNotifier.InstallEditorNotifiers;
var
i: Integer;
IEditor: IOTAEditor;
ISourceEditor: IOTASourceEditor;
IFormEditor: IOTAFormEditor;
INotifier: IOTANotifier;
begin
Assert(Assigned(FAssociatedModule));
for i := 0 to FAssociatedModule.GetModuleFileCount - 1 do
begin
IEditor := GxOtaGetFileEditorForModule(FAssociatedModule, i);
Assert(Assigned(IEditor));
if Trim(IEditor.FileName) = '' then
begin
{$IFOPT D+} SendDebugWarning('Blank filename in module: ' + FAssociatedModule.FileName); {$ENDIF}
Continue; // Don't register notifiers for blank file names (like with TWebModule in D5)
end;
if Supports(IEditor, IOTASourceEditor, ISourceEditor) then
begin
if Assigned(ISourceEditor) then
begin
INotifier := TGxEditorNotifier.Create(Self, ISourceEditor);
FInstalledEditorNotifiers.Add(INotifier);
end;
end;
if Supports(IEditor, IOTAFormEditor, IFormEditor) then
begin
if Assigned(IFormEditor) then
begin
INotifier := TGxFormNotifier.Create(Self, IFormEditor);
FInstalledEditorNotifiers.Add(INotifier);
end;
end;
end;
end;
procedure TGxModuleNotifier.Modified;
begin
end;
procedure TGxModuleNotifier.ModuleRenamed(const NewName: string);
begin
// Do nothing
end;
procedure TGxModuleNotifier.RemoveEditorNotifiers;
var
INotifierUninstallation: IGxNotifierUninstallation;
begin
Assert(Assigned(FInstalledEditorNotifiers));
while FInstalledEditorNotifiers.Count > 0 do
begin
INotifierUninstallation := FInstalledEditorNotifiers[0] as IGxNotifierUninstallation;
Assert(Assigned(INotifierUninstallation));
INotifierUninstallation.UninstallNotifier;
// The interface object upon which we call UninstallNotifier
// will remove itself from the list of editor notifiers, i.e.
// from FInstalledEditorNotifiers, thereby reducing
// FInstalledEditorNotifiers.Count down to zero.
end;
end;
procedure TGxModuleNotifier.RemoveSelfFromClient;
var
RemovalIndex: Integer;
begin
if Assigned(FIdeClient) then
begin
Assert(Assigned(FIdeClient.FInstalledModuleNotifiers));
RemovalIndex := FIdeClient.FInstalledModuleNotifiers.Remove(Self);
Assert(RemovalIndex <> -1);
FIdeClient := nil;
end;
end;
procedure TGxModuleNotifier.RemoveSelfNotifier;
begin
if FSelfNotifierIndex <> InvalidNotifierIndex then
begin
if Assigned(FAssociatedModule) then
FAssociatedModule.RemoveNotifier(FSelfNotifierIndex);
FSelfNotifierIndex := InvalidNotifierIndex;
end;
end;
procedure TGxModuleNotifier.UninstallNotifier;
begin
RemoveSelfNotifier;
RemoveEditorNotifiers;
RemoveSelfFromClient;
end;
{ TGxBaseEditorNotifier }
procedure TGxBaseEditorNotifier.GenericNotification(const NotifyType: TInternalIdeNotification;
const GenericParameter: IInterface; CharCode: Word; KeyData: Integer);
begin
Assert(Assigned(FModuleClient));
Assert(Assigned(FModuleClient.FIdeClient));
Assert(Assigned(FModuleClient.FIdeClient.FChangeServicesClient));
FModuleClient.FIdeClient.FChangeServicesClient.GenericInternalIdeNotification(NotifyType, GenericParameter, CharCode, KeyData);
end;
procedure TGxBaseEditorNotifier.RemoveSelfFromClient;
var
RemovalIndex: Integer;
ISelfNotifier: IOTANotifier;
begin
if Assigned(FModuleClient) then
begin
ISelfNotifier := Self as IOTANotifier;
RemovalIndex := FModuleClient.FInstalledEditorNotifiers.Remove(ISelfNotifier);
Assert(RemovalIndex <> -1);
FModuleClient := nil;
end;
end;
procedure TGxBaseEditorNotifier.UninstallNotifier;
begin
{$IFOPT D+} SendDebug('UninstallNotifier for ' + FFileName); {$ENDIF}
RemoveSelfNotifier;
RemoveSelfFromClient;
end;
{ TGxEditorNotifier }
procedure TGxEditorNotifier.AfterSave;
begin
// Do nothing
end;
procedure TGxEditorNotifier.BeforeSave;
begin
// Do nothing
end;
constructor TGxEditorNotifier.Create(const Client: TGxModuleNotifier; const ISourceEditor: IOTASourceEditor);
begin
{$IFOPT D+} Inc(TGxEditorNotifierCount); {$ENDIF}
{$IFOPT D+} SendDebug('Creating TGxEditorNotifier for ' + ISourceEditor.FileName); {$ENDIF}
inherited Create;
FSelfNotifierIndex := InvalidNotifierIndex;
FFileName := ISourceEditor.FileName;
FModuleClient := Client;
Assert(Assigned(ISourceEditor));
NoRefCount(FAssociatedSourceEditor) := NoRefCount(ISourceEditor);
FSelfNotifierIndex := ISourceEditor.AddNotifier(Self);
if False then
HookEditorWndProc;
{$IFOPT D+} SendDebug('Created TGxEditorNotifier for ' + ISourceEditor.FileName); {$ENDIF}
end;
destructor TGxEditorNotifier.Destroy;
begin
{$IFOPT D+} SendDebug('Destroying TGxEditorNotifier for ' + FFileName); {$ENDIF}
//UnhookEditorWndProc;
FModuleClient := nil;
NoRefCount(FAssociatedSourceEditor) := nil;
inherited;
{$IFOPT D+} Dec(TGxEditorNotifierCount); {$ENDIF}
end;
procedure TGxEditorNotifier.Destroyed;
begin
{$IFOPT D+}
if Assigned(FAssociatedSourceEditor) then
SendDebug('Destroyed notification for: ' + FAssociatedSourceEditor.FileName)
else
SendDebugWarning('Destroyed notification for: <unknown source editor>');
{$ENDIF}
//UnhookEditorWndProc;
NoRefCount(FAssociatedSourceEditor) := nil;
end;
procedure TGxEditorNotifier.HookEditorWndProc;
var
EditControl: TWinControl;
begin
if False then
UnhookEditorWndProc;
EditControl := GetEditControl;
if Assigned(EditControl) then
begin
//FEditorHandle := EditControl.Handle;
FNewEditControlWndProc := Classes.MakeObjectInstance(EditControlWndProc);
FOldEditControlWndProc := SetWindowLong(EditControl.Handle, GWL_WNDPROC, Integer(FNewEditControlWndProc));
if FOldEditControlWndProc = 0 then
begin
{$IFOPT D+} SendDebugError('Windows error hooking EditorWndProc'); {$ENDIF}
end;
end
else
begin
{$IFOPT D+}
if Assigned(FAssociatedSourceEditor) then
SendDebug('Unable too hook edit control for ' + FAssociatedSourceEditor.FileName)
else
SendDebugWarning('Unable too hook edit control for <unknown source editor>');
{$ENDIF}
end;
end;
procedure TGxEditorNotifier.UnhookEditorWndProc;
var
EditorHandle: HWND;
begin
{$IFOPT D+}
if Assigned(FAssociatedSourceEditor) then
SendDebug('Attempting to unhook EditorWndProc for: ' + FAssociatedSourceEditor.FileName)
else
SendDebugWarning('Attempting to unhook EditorWndProc for: <unknown source editor>');
{$ENDIF}
if {(FEditorHandle <> 0) and} (FOldEditControlWndProc <> 0) then
begin
{$IFOPT D+} SendDebug('Starting unhook procedure'); {$ENDIF}
EditorHandle := GetEditControl.Handle;
if SetWindowLong({F}EditorHandle, GWL_WNDPROC, Integer(FOldEditControlWndProc)) = 0 then
begin
{$IFOPT D+} SendDebugError('Windows error unhooking EditorWndProc'); {$ENDIF}
end;
if Assigned(FNewEditControlWndProc) then
Classes.FreeObjectInstance(FNewEditControlWndProc);
FOldEditControlWndProc := 0;
//FEditorHandle := 0;
{$IFOPT D+} SendDebug('Successful unhook procedure'); {$ENDIF}
end;
end;
procedure TGxEditorNotifier.EditControlWndProc(var Msg: TMessage);
var
EditorHandle: HWND;
begin
//{$IFOPT D+} SendDebug('Editor Message coming...'); {$ENDIF}
{$IFOPT D+} SendDebug('Editor Message: ' + MessageName(Msg.Msg) + ' for ' + FAssociatedSourceEditor.FileName); {$ENDIF}
if Msg.Msg = WM_DESTROY then
//UnhookEditorWndProc
else if Msg.Msg = WM_KEYUP then
GenericNotification(iinEditorKeyPressed, FAssociatedSourceEditor, TWMKey(Msg).CharCode, TWMKey(Msg).KeyData);
try
if FOldEditControlWndProc <> 0 then
begin
EditorHandle := GetEditControl.Handle;
Msg.Result := CallWindowProc(Pointer(FOldEditControlWndProc), {F}EditorHandle, Msg.Msg, Msg.WParam, Msg.LParam);
end;
except
on E: Exception do
begin
E.Message := E.Message + ' (GExperts EditControlWndProc Message: ' +IntToStr(Msg.Msg)+ '+)';
raise;
end;
end;
end;
function TGxEditorNotifier.GetEditControl: TWinControl;
var
EditView: IOTAEditView;
EditWindow: INTAEditWindow;
EditForm: TCustomForm;
begin
Result := nil;
if Assigned(FAssociatedSourceEditor) then
begin
if GxOtaTryGetTopMostEditView(FAssociatedSourceEditor, EditView) then
begin
EditWindow := EditView.GetEditWindow;
if Assigned(EditWindow) then
begin
EditForm := EditWindow.Form;
if Assigned(EditForm) then
Result := GetIDEEditControl(EditForm);
end;
end;
end;
end;
procedure TGxEditorNotifier.Modified;
begin
GenericNotification(iinSourceEditorModified, FAssociatedSourceEditor);
end;
procedure TGxEditorNotifier.RemoveSelfNotifier;
begin
Assert(Assigned(FAssociatedSourceEditor));
if FSelfNotifierIndex <> InvalidNotifierIndex then
begin
FAssociatedSourceEditor.RemoveNotifier(FSelfNotifierIndex);
FSelfNotifierIndex := InvalidNotifierIndex;
end;
end;
procedure TGxEditorNotifier.ViewActivated(const View: IOTAEditView);
begin
// Do nothing
end;
procedure TGxEditorNotifier.ViewNotification(const View: IOTAEditView; Operation: TOperation);
begin
if Assigned(View) then
begin
if (Operation = opInsert) then
begin
{$IFOPT D+}
if Assigned(View.Buffer) then
SendDebug('Insert notification for ' + View.Buffer.FileName)
else
SendDebugWarning('Insert notification for <unknown buffer>');
{$ENDIF}
// TODO 3 -cBug -oAnyone: We need to hook secondary edit views, but that requires separate tracking of FEditorHandle, etc.
//HookEditorWndProc;
end
else if Operation = opRemove then
begin
{$IFOPT D+}
if Assigned(View.Buffer) then
SendDebug('Removal notification for ' + View.Buffer.FileName)
else
SendDebugWarning('Removal notification for <unknown buffer>');
{$ENDIF}
//UnHookEditorWndProc;
end;
end;
end;
{ TGxFormNotifier }
procedure TGxFormNotifier.AfterSave;
begin
// Do nothing
end;
procedure TGxFormNotifier.BeforeSave;
begin
// Do nothing
end;
procedure TGxFormNotifier.ComponentRenamed(ComponentHandle: TOTAHandle;
const OldName, NewName: string);
var
i: Integer;
INotification: IGxEditorNotification;
IComponent: IOTAComponent;
begin
Assert(Assigned(PrivateEditorChangeServices.FNotifiers));
for i := 0 to PrivateEditorChangeServices.FNotifiers.Count - 1 do
begin
try
INotification := PrivateEditorChangeServices.FNotifiers[i] as IGxEditorNotification;
IComponent := nil;
if Assigned(FAssociatedFormEditor) then
begin
IComponent := FAssociatedFormEditor.GetComponentFromHandle(ComponentHandle);
Assert(Assigned(IComponent));
end;
INotification.ComponentRenamed(FAssociatedFormEditor, IComponent, OldName, NewName);
except
on E: Exception do
begin
GxLogException(E);
Application.HandleException(Self);
end;
end;
end;
end;
constructor TGxFormNotifier.Create(const Client: TGxModuleNotifier; const IFormEditor: IOTAFormEditor);
begin
{$IFOPT D+} Inc(TGxFormNotifierCount); {$ENDIF}
{$IFOPT D+} SendDebug('Creating TGxFormNotifier'); {$ENDIF}
inherited Create;
FModuleClient := Client;
Assert(Assigned(IFormEditor));
NoRefCount(FAssociatedFormEditor) := NoRefCount(IFormEditor);
FSelfNotifierIndex := IFormEditor.AddNotifier(Self);
{$IFOPT D+} SendDebug('Created TGxFormNotifier'); {$ENDIF}
end;
destructor TGxFormNotifier.Destroy;
begin
{$IFOPT D+} SendDebug('Destroying TGxFormNotifier'); {$ENDIF}
NoRefCount(FAssociatedFormEditor) := nil;
FModuleClient := nil;
inherited Destroy;
{$IFOPT D+} SendDebug('TGxFormNotifier destroyed'); {$ENDIF}
{$IFOPT D+} Dec(TGxFormNotifierCount); {$ENDIF}
end;
procedure TGxFormNotifier.Destroyed;
begin
NoRefCount(FAssociatedFormEditor) := nil;
end;
procedure TGxFormNotifier.FormActivated;
begin
// Do nothing
end;
procedure TGxFormNotifier.FormSaving;
begin
// Do nothing
end;
procedure TGxFormNotifier.Modified;
begin
// This notifier is fired each time a form is modified.
Assert(Assigned(FModuleClient));
Assert(Assigned(FModuleClient.FIdeClient));
Assert(Assigned(FModuleClient.FIdeClient.FChangeServicesClient));
FModuleClient.FIdeClient.FChangeServicesClient.GenericInternalIdeNotification(iinFormEditorModified, FAssociatedFormEditor);
end;
procedure TGxFormNotifier.RemoveSelfNotifier;
begin
if not Assigned(FAssociatedFormEditor) then
begin
{$IFOPT D+} SendDebugError('RemoveSelfNotifier called with nil FAssociatedFormEditor for ' + FFileName); {$ENDIF}
Exit;
end;
if FSelfNotifierIndex <> InvalidNotifierIndex then
begin
FAssociatedFormEditor.RemoveNotifier(FSelfNotifierIndex);
FSelfNotifierIndex := InvalidNotifierIndex;
end;
end;
{$IFDEF UseInternalTestClient}
type
TestClient = class(TInterfacedObject, IGxEditorNotification)
private
procedure NewModuleOpened(const Module: IOTAModule);
procedure SourceEditorModified(const SourceEditor: IOTASourceEditor);
procedure FormEditorModified(const FormEditor: IOTAFormEditor);
end;
{ TestClient }
procedure TestClient.FormEditorModified(const FormEditor: IOTAFormEditor);
begin
Assert(Assigned(FormEditor));
WriteSimpleMessage('TestClient Form Modified: ' + FormEditor.FileName);
end;
procedure TestClient.NewModuleOpened(const Module: IOTAModule);
begin
WriteTitleMessage('TestClient got new module message:');
WriteSimpleMessage(' ' + Module.FileName);
end;
procedure TestClient.SourceEditorModified(const SourceEditor: IOTASourceEditor);
begin
Assert(Assigned(SourceEditor));
WriteSimpleMessage('TestClient Source Modified: ' + SourceEditor.FileName);
end;
{$ENDIF UseInternalTestClient}
{$IFDEF UseInternalTestClient}
var
NotifierIndex: Integer;
procedure Initialize;
begin
NotifierIndex := GxEditorChangeServices.AddNotifier(TestClient.Create);
end;
procedure Finalize;
var
Temp: IGxEditorChangeServices;
begin
// We must take care that the interface that
// GxEditorChangeServices delivers is _IntfClear'ed
// before we release the underlying class instance.
// (Via ReleaseEditorChangeServices)
Temp := GxEditorChangeServices;
Temp.RemoveNotifier(NotifierIndex);
Temp := nil; // Force destruction, just in case
end;
{$ENDIF UseInternalTestClient}
initialization
{$IFDEF UseInternalTestClient}
Initialize;
{$ENDIF UseInternalTestClient}
finalization
{$IFDEF UseInternalTestClient}
Finalize;
{$ENDIF UseInternalTestClient}
ReleaseEditorChangeServices;
{$IFOPT D+}
if TEditorChangeServicesCount <> 0 then
SendDebug(Format('Dangling references to TEditorChangeServicesCount: %d', [TEditorChangeServicesCount]));
if TGxIdeNotifierCount <> 0 then
SendDebug(Format('Dangling references to TGxIdeNotifierCount: %d', [TGxIdeNotifierCount]));
if TGxModuleNotifierCount <> 0 then
SendDebug(Format('Dangling references to TGxModuleNotifierCount: %d', [TGxModuleNotifierCount]));
if TGxEditorNotifierCount <> 0 then
SendDebug(Format('Dangling references to TGxEditorNotifierCount: %d', [TGxEditorNotifierCount]));
if TGxFormNotifierCount <> 0 then
SendDebug(Format('Dangling references to TGxFormNotifierCount: %d', [TGxFormNotifierCount]));
{$ENDIF D+}
end.
|
unit fDataDisp;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, cMegaROM;
type
TfrmDataDisp = class(TForm)
mmoData: TMemo;
cmdOk: TButton;
cmdExport: TButton;
procedure FormShow(Sender: TObject);
private
_ROMData : TMegamanROM;
procedure DisplayData;
{ Private declarations }
public
property ROMData : TMegamanROM read _ROMData write _ROMdata;
{ Public declarations }
end;
var
frmDataDisp: TfrmDataDisp;
implementation
{$R *.dfm}
procedure TfrmDataDisp.DisplayData;
var
i : Integer;
begin
for i := 0 to _ROMData.Levels.Count-1 do
begin
mmoData.Lines.Add( _ROMdata.Levels[i].Name);
mmoData.Lines.Add('');
mmoData.Lines.Add( IntToHex(_ROMData.Levels[i].RoomPointersOffset,2) );
mmoData.Lines.Add('TSA Data: 0x' + IntToHex(_ROMData.Levels[i].TSAOffset,2));
mmoData.Lines.Add('0x' + IntToHex(_ROMData.Levels[i].AttributeOffset,2) + ' - 0x' + IntToHex(_ROMData.Levels[i].AttributeOffset + (_ROMData.Levels[i].NumberOfTiles - 1),2) + '- Attribute Data');
end;
end;
procedure TfrmDataDisp.FormShow(Sender: TObject);
begin
DisplayData;
end;
end.
|
// Upgraded to Delphi 2009: Sebastian Zierer
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower SysTools
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1996-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* SysTools: StNTLog.pas 4.04 *}
{*********************************************************}
{* SysTools: NT Event Logging *}
{*********************************************************}
{$I StDefine.inc}
unit StNTLog;
interface
uses
Windows, SysUtils, Classes, Registry, StBase;
type
TStNTEventType = (etSuccess, etError, etWarning, etInfo,
etAuditSuccess, etAuditFailure);
PStNTEventLogRec = ^TStNTEventLogRec;
TStNTEventLogRec = record
case Integer of
0 : (Length : DWORD; { Length of full record }
Reserved : DWORD; { Used by the service }
RecordNumber : DWORD; { Absolute record number }
TimeGenerated : DWORD; { Seconds since 1-1-1970 }
TimeWritten : DWORD; { Seconds since 1-1-1970 }
EventID : DWORD;
EventType : WORD;
NumStrings : WORD;
EventCategory : WORD;
ReservedFlags : WORD; { For use with paired events (auditing) }
ClosingRecordNumber : DWORD; { For use with paired events (auditing) }
StringOffset : DWORD; { Offset from beginning of record }
UserSidLength : DWORD;
UserSidOffset : DWORD;
DataLength : DWORD;
DataOffset : DWORD); { Offset from beginning of record }
1 : (VarData : array [0..65535] of Byte);
//
// Variable data may contain:
//
// WCHAR SourceName[]
// WCHAR Computername[]
// SID UserSid
// WCHAR Strings[]
// BYTE Data[]
// CHAR Pad[]
// DWORD Length;
//
// Data is contained -after- the static data, the VarData field is set
// to the beginning of the record merely to make the offsets match up.
end;
TStReadRecordEvent = procedure(Sender : TObject; const EventRec : TStNTEventLogRec;
var Abort : Boolean) of object;
TStNTEventLog = class(TStComponent)
private
{ Internal use variables }
elLogHandle : THandle;
elLogList : TStringList;
{ Property variables }
FComputerName : string;
FEnabled : Boolean;
FEventSource : string;
FLogName : string;
FOnReadRecord : TStReadRecordEvent;
protected
{ Internal Methods }
procedure elAddEntry(const EventType : TStNTEventType; EventCategory, EventID : DWORD;
const Strings : TStrings; DataPtr : pointer; DataSize : DWORD);
procedure elCloseLog;
procedure elOpenLog;
{ Property Methods }
function GetLogCount : DWORD;
function GetLogs(Index : Integer) : string;
function GetRecordCount : DWORD;
procedure SetComputerName(const Value : string);
procedure SetLogName(const Value : string);
public
{ Public Methods }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure AddEntry(const EventType : TStNTEventType; EventCategory, EventID : DWORD);
procedure AddEntryEx(const EventType : TStNTEventType; EventCategory, EventID : DWORD;
const Strings : TStrings; DataPtr : pointer; DataSize : DWORD);
procedure ClearLog(const BackupName : TFileName);
procedure CreateBackup(const BackupName : TFileName);
procedure ReadLog(const Reverse : Boolean);
procedure RefreshLogList;
{ Public Properties }
property LogCount : DWORD read GetLogCount;
property Logs[Index : Integer] : string read GetLogs;
property RecordCount : DWORD read GetRecordCount;
published
{ Published Properties }
property ComputerName : string read FComputerName write SetComputerName;
property Enabled : Boolean read FEnabled write FEnabled default True;
property EventSource : string read FEventSource write FEventSource;
property LogName : string read FLogName write SetLogName;
property OnReadRecord : TStReadRecordEvent read FOnReadRecord write FOnReadRecord;
end;
implementation
{$IFDEF FPC}
uses Delphi.Windows;
{$ENDIF}
const
{ Defines for the READ flags for Eventlogging }
EVENTLOG_SEQUENTIAL_READ = $0001;
EVENTLOG_SEEK_READ = $0002;
EVENTLOG_FORWARDS_READ = $0004;
EVENTLOG_BACKWARDS_READ = $0008;
{ The types of events that can be logged. }
EVENTLOG_SUCCESS = $0000;
EVENTLOG_ERROR_TYPE = $0001;
EVENTLOG_WARNING_TYPE = $0002;
EVENTLOG_INFORMATION_TYPE = $0004;
EVENTLOG_AUDIT_SUCCESS = $0008;
EVENTLOG_AUDIT_FAILURE = $0010;
{ Defines for the WRITE flags used by Auditing for paired events }
{ These are not implemented in Product 1 }
EVENTLOG_START_PAIRED_EVENT = $0001;
EVENTLOG_END_PAIRED_EVENT = $0002;
EVENTLOG_END_ALL_PAIRED_EVENTS = $0004;
EVENTLOG_PAIRED_EVENT_ACTIVE = $0008;
EVENTLOG_PAIRED_EVENT_INACTIVE = $0010;
StEventLogKey = '\SYSTEM\CurrentControlSet\Services\EventLog';
{ Create instance of event log component }
constructor TStNTEventLog.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
{ initialization }
elLogHandle := 0;
elLogList := TStringList.Create;
FEnabled := True;
FLogName := 'Application';
{ initialize log list }
RefreshLogList;
end;
{ Destroy instance of event log component }
destructor TStNTEventLog.Destroy;
begin
if elLogHandle <> 0 then elCloseLog;
elLogList.Free;
inherited;
end;
{ Add entry to the event log }
procedure TStNTEventLog.AddEntry(const EventType : TStNTEventType;
EventCategory, EventID : DWORD);
begin
elAddEntry(EventType, EventCategory, EventID, nil, nil, 0);
end;
{ Add entry to the event log - more options }
procedure TStNTEventLog.AddEntryEx(const EventType : TStNTEventType;
EventCategory, EventID : DWORD; const Strings : TStrings;
DataPtr : pointer; DataSize : DWORD);
begin
elAddEntry(EventType, EventCategory, EventID, Strings, DataPtr, DataSize);
end;
{ Clear the event log }
procedure TStNTEventLog.ClearLog(const BackupName : TFileName);
begin
elOpenLog;
try
ClearEventLog(elLogHandle, PChar(BackupName));
finally
elCloseLog;
end;
end;
{ Back up the event log }
procedure TStNTEventLog.CreateBackup(const BackupName : TFileName);
begin
elOpenLog;
try
BackupEventLog(elLogHandle, PChar(BackupName));
finally
elCloseLog;
end;
end;
{ Adds an entry to the event log }
procedure TStNTEventLog.elAddEntry(const EventType : TStNTEventType;
EventCategory, EventID : DWORD; const Strings : TStrings; DataPtr : pointer; DataSize : DWORD);
const
StrArraySize = 1024;
var
TempType, StrCount : DWORD;
StrArray : array[0..StrArraySize-1] of PChar;
StrArrayPtr : pointer;
I : Integer;
begin
StrArrayPtr := nil;
case EventType of
etSuccess : TempType := EVENTLOG_SUCCESS;
etError : TempType := EVENTLOG_ERROR_TYPE;
etWarning : TempType := EVENTLOG_WARNING_TYPE;
etInfo : TempType := EVENTLOG_INFORMATION_TYPE;
etAuditSuccess : TempType := EVENTLOG_AUDIT_SUCCESS;
etAuditFailure : TempType := EVENTLOG_AUDIT_FAILURE;
else
TempType := 0;
end;
elOpenLog;
try
{ Fill string array }
if Assigned(Strings) then begin
FillChar(StrArray, SizeOf(StrArray), #0);
StrCount := Strings.Count;
Assert(StrCount <= StrArraySize);
for I := 0 to StrCount-1 do begin
StrArray[I] := StrAlloc(Length(Strings[I]));
StrPCopy(StrArray[I], Strings[I]);
end;
StrArrayPtr := @StrArray;
end else begin
StrCount := 0;
end;
ReportEvent(elLogHandle, TempType, EventCategory,
EventID, nil, StrCount, DataSize, StrArrayPtr, DataPtr);
finally
{ Release string array memory }
for I := 0 to StrArraySize-1 do begin
if StrArray[I] = nil then Break;
StrDispose(StrArray[I]);
end;
elCloseLog;
end;
end;
{ Close event log }
procedure TStNTEventLog.elCloseLog;
begin
if elLogHandle <> 0 then begin
CloseEventLog(elLogHandle);
elLogHandle := 0;
end;
end;
{ Open event log }
procedure TStNTEventLog.elOpenLog;
begin
if elLogHandle = 0 then
elLogHandle := OpenEventLog(PChar(FComputerName), PChar(FLogName));
end;
{ Get number on logs available on system }
function TStNTEventLog.GetLogCount : DWORD;
begin
Result := elLogList.Count;
end;
{ Get name of logs }
function TStNTEventLog.GetLogs(Index : Integer) : string;
begin
Result := elLogList[Index];
end;
{ Get number of log entries in event log }
function TStNTEventLog.GetRecordCount : DWORD;
begin
elOpenLog;
try
GetNumberOfEventLogRecords(elLogHandle, Result);
finally
elCloseLog;
end;
end;
{ Reads log until complete or aborted }
procedure TStNTEventLog.ReadLog(const Reverse : Boolean);
var
ReadDir, BytesRead, BytesNeeded, LastErr : DWORD;
RetVal, Aborted : Boolean;
TempBuffer : array[0..2047] of Byte;
TempPointer : Pointer;
TempRecPtr : PStNTEventLogRec; { used as an alias, don't actually allocate }
FakeBuf : Byte;
begin
Aborted := False;
TempPointer := nil;
{ Set direction }
if Reverse then
ReadDir := EVENTLOG_SEQUENTIAL_READ or EVENTLOG_BACKWARDS_READ
else
ReadDir := EVENTLOG_SEQUENTIAL_READ or EVENTLOG_FORWARDS_READ;
elOpenLog;
try
repeat
{ Fake read to determine required buffer size }
RetVal := ReadEventLog(elLogHandle, ReadDir, 0, @FakeBuf,
SizeOf(FakeBuf), BytesRead, BytesNeeded);
if not RetVal then begin
LastErr := GetLastError;
if (LastErr = ERROR_INSUFFICIENT_BUFFER) then begin
{ We can use local buffer, which is faster }
if (BytesNeeded <= SizeOf(TempBuffer)) then begin
if not (ReadEventLog(elLogHandle, ReadDir, 0, @TempBuffer,
BytesNeeded, BytesRead, BytesNeeded)) then
{$WARNINGS OFF} { Yeah, we know RaiseLastWin32Error is deprecated }
RaiseLastWin32Error;
{$WARNINGS ON}
TempRecPtr := @TempBuffer
{ Local buffer too small, need to allocate a buffer on the heap }
end else begin
if TempPointer = nil then
GetMem(TempPointer, BytesNeeded)
else
ReallocMem(TempPointer, BytesNeeded);
if not (ReadEventLog(elLogHandle, ReadDir, 0, TempPointer,
BytesNeeded, BytesRead, BytesNeeded)) then
{$WARNINGS OFF} { Yeah, we know RaiseLastWin32Error is deprecated }
RaiseLastWin32Error;
{$WARNINGS ON}
TempRecPtr := TempPointer;
end;
{ At this point, we should have the data -- fire the event }
if Assigned(FOnReadRecord) then
FOnReadRecord(Self, TempRecPtr^, Aborted);
end else begin
Aborted := True;
{ Handle unexpected error }
{$WARNINGS OFF} { Yeah, we know RaiseLastWin32Error is deprecated }
if (LastErr <> ERROR_HANDLE_EOF) then
RaiseLastWin32Error;
{$WARNINGS ON}
end;
end;
until Aborted;
finally
elCloseLog;
if TempPointer = nil then
FreeMem(TempPointer);
end;
end;
{ Refreshes log list }
procedure TStNTEventLog.RefreshLogList;
var
Reg : TRegistry;
begin
elLogList.Clear;
Reg := TRegistry.Create;
try
Reg.RootKey := HKEY_LOCAL_MACHINE;
if Reg.OpenKey(StEventLogKey, False) then begin
Reg.GetKeyNames(elLogList);
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
{ Set log name }
procedure TStNTEventLog.SetLogName(const Value : string);
begin
FLogName := Value
end;
{ Set computer name }
procedure TStNTEventLog.SetComputerName(const Value : string);
begin
FComputerName := Value;
RefreshLogList;
end;
end.
|
unit PrivLoader;
{$PointerMath ON}
interface
uses
Graphics,
Math,
libavcodec,
libavformat,
libswscale,
libavutil,
libavutil_frame,
libavutil_pixfmt,
libavutil_mem,
SysUtils;
type
TVideoMetaData = record
width, height: Integer;
duration: Double;
avgFrameRate: Double;
end;
TPrivLoader = class(TObject)
private
videoStreamIndex: Integer;
pFormatContext: PAVFormatContext;
pCodecContext: PAVCodecContext;
buffer: PByte;
pRawFrame: PAVFrame;
outBufferSize: Integer;
pOutFrame: PAVFrame;
swsContext: PSwsContext;
mCurrentFrame: Integer;
mTotalFrames: Integer;
protected
public
constructor Create;
destructor Destroy; override;
function Open(filename: AnsiString; out errorMsg: String; out meta: TVideoMetaData): boolean;
procedure SetRenderSize(width, height: Integer);
procedure SeekAbs(frameNum: Integer);
function NextFrame(): boolean;
procedure CopyLastFrame(outBitmap: TBitmap);
property TotalFrames: Integer read mTotalFrames;
property CurrentFrame: Integer read mCurrentFrame;
end;
implementation
constructor TPrivLoader.Create;
begin
mCurrentFrame := -1;
mTotalFrames := -1;
end;
destructor TPrivLoader.Destroy;
begin
sws_freeContext(swsContext);
av_frame_free(@pOutFrame);
av_frame_free(@pRawFrame);
av_free(buffer);
avcodec_close(pCodecContext);
avformat_close_input(@pFormatContext);
inherited;
end;
function TPrivLoader.Open(filename: AnsiString; out errorMsg: String; out meta: TVideoMetaData): boolean;
var
i: Integer;
streamPtr: PPAVStream;
pCodecContextOrig: PAVCodecContext;
pCodec: PAVCodec;
openRet: Integer;
begin
pFormatContext := avformat_alloc_context();
{ actually try to open the thing }
openRet := avformat_open_input(@pFormatContext, PAnsiChar(filename), nil, nil);
if openRet <> 0 then
begin
errorMsg := format('ffmpeg could not open file: [%s] (result was: %d)', [filename, openRet]);
result := false;
exit;
end;
{ read info about all streams in the file }
if avformat_find_stream_info(pFormatContext, nil) < 0 then
begin
errorMsg := 'couldn''t find stream info';
result := false;
exit;
end;
{ iterate through the streams, break on first video stream }
pCodecContextOrig := nil;
streamPtr := pFormatContext.streams;
for i := 0 to pFormatContext.nb_streams - 1 do
begin
if streamPtr^.codec.codec_type = AVMEDIA_TYPE_VIDEO then
begin
pCodecContextOrig := streamPtr^.codec;
videoStreamIndex := i;
break;
end;
inc(streamPtr);
end;
{ exit if no video stream found }
if pCodecContextOrig = nil then
begin
errorMsg := 'no video stream found';
result := false;
exit;
end;
{ find decoder for video stream }
pCodec := avcodec_find_decoder(pCodecContextOrig.codec_id);
if pCodec = nil then
begin
errorMsg := 'unsupported codec';
result := false;
exit;
end;
{ create a copy of context -- can't use the one we already had (?) }
pCodecContext := avcodec_alloc_context3(pCodec);
if avcodec_copy_context(pCodecContext, pCodecContextOrig) <> 0 then
begin
errorMsg := 'error copying codec context';
result := false;
exit;
end;
{ open codec! }
if avcodec_open2(pCodecContext, pCodec, nil) < 0 then
begin
errorMsg := 'could not open codec';
result := false;
exit;
end;
{ alloc frame for actual rendering }
pRawFrame := av_frame_alloc();
meta.width := pCodecContext.width;
meta.height := pCodecContext.height;
meta.duration := (streamPtr^.duration * streamPtr^.time_base.num) / streamPtr^.time_base.den;
meta.avgFrameRate := streamPtr^.avg_frame_rate.num / streamPtr^.avg_frame_rate.den;
mTotalFrames := Trunc(meta.duration * meta.avgFrameRate);
result := true;
end;
procedure TPrivLoader.SetRenderSize(width, height: Integer);
begin
pOutFrame := av_frame_alloc();
outBufferSize := avpicture_get_size(AV_PIX_FMT_BGR24, width, height);
buffer := av_malloc(outBufferSize);
avpicture_fill(PAVPicture(pOutFrame), buffer, AV_PIX_FMT_BGR24, width, height);
{ necessary/helpful? }
pOutFrame.width := width;
pOutFrame.height := height;
{ initialize software scaling stuff }
swsContext := sws_getContext(pCodecContext.width, pCodecContext.height, pCodecContext.pix_fmt, width, height,
AV_PIX_FMT_BGR24, SWS_BILINEAR, nil, nil, nil);
end;
procedure TPrivLoader.SeekAbs(frameNum: Integer);
var
videoStream: PAVStream;
streamExt: UInt64;
timestamp: UInt64;
flags: UInt32;
adjustedFrame: UInt32;
begin
videoStream := pFormatContext.streams[videoStreamIndex];
flags := AVSEEK_FLAG_BACKWARD; // seek to keyframe just before where we asked
adjustedFrame := Math.Max(0, frameNum - floor(mTotalFrames * 0.015)); // fudge: subtract 1.5% because this never works just right
timestamp := (adjustedFrame * videoStream.duration) div mTotalFrames;
av_seek_frame(pFormatContext, videoStreamIndex, timestamp, flags);
// flush buffers etc
avcodec_flush_buffers(pCodecContext);
//
mCurrentFrame := -1; // because unknown until nextFrame()
end;
function TPrivLoader.NextFrame(): boolean;
var
packet: TAVPacket;
frameFinished: Integer;
videoStream: PAVStream;
begin
result := false;
while av_read_frame(pFormatContext, @packet) >= 0 do
begin
if packet.stream_index = videoStreamIndex then
begin
{ update position [1/1000th of the total duration] }
videoStream := pFormatContext.streams[videoStreamIndex];
mCurrentFrame := (packet.pts * mTotalFrames) div videoStream.duration;
{ decode video frame }
avcodec_decode_video2(pCodecContext, pRawFrame, @frameFinished, @packet);
if frameFinished <> 0 then
begin
result := true;
av_free_packet(@packet);
break;
end;
end;
av_free_packet(@packet);
end;
end;
procedure TPrivLoader.CopyLastFrame(outBitmap: TBitmap);
var
x, y: Integer;
offs: Integer;
src, dest: PByte;
begin
{ convert from native format to output format/size }
sws_scale(
swsContext,
@pRawFrame.data[0],
@pRawFrame.linesize[0],
0,
pCodecContext.height,
@pOutFrame.data[0],
@pOutFrame.linesize[0]
);
{ copy to client buffer }
//outBitmap.BeginUpdate();
for y := 0 to pOutFrame.height-1 do
begin
offs := (y * pOutFrame.linesize[0]);
src := PByte(UInt32(pOutFrame.data[0]) + offs);
Move(src^, outBitmap.ScanLine[y]^, pOutFrame.linesize[0]);
end;
//outBitmap.EndUpdate();
end;
initialization
begin
av_register_all();
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.