text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ Проект: Repository }
{ Модуль: uNotificationService.pas }
{ Описание: Реализация INotificationService }
{ Copyright (C) 2015 Боборыкин В.В. (bpost@yandex.ru) }
{ }
{ Распространяется по лицензии GPLv3 }
{*******************************************************}
unit uNotificationService;
interface
uses
SysUtils, Classes, uServices, uInterfaceListExt, SyncObjs;
type
TNotificationService = class(TInterfacedObject, INotificationService)
private
FList: IInterfaceListExt;
FEventProcessThread: TThread;
public
constructor Create;
destructor Destroy; override;
procedure Notify(Sender: TObject; AEventData: IInterface); stdcall;
procedure NotifyAsync(Sender: TObject; AEventData: IInterface); stdcall;
procedure Subscribe(Subscriber: TObject; Subscription: ISubscription);
stdcall;
procedure Unsubscribe(Subscriber: TObject; Subscription: ISubscription);
stdcall;
procedure UnsubscribeAll(Subscriber: TObject); stdcall;
end;
implementation
uses Math, Variants;
type
ISubData = interface
['{85609CE5-5C78-4BD1-8FF1-4AEF1E4C1516}']
function Subscriber: TObject; stdcall;
function Subscription: ISubscription; stdcall;
end;
TSubData = class(TInterfacedObject, ISubData)
private
FSubscriber: TObject;
FSubscription: ISubscription;
public
constructor Create(ASubscriber: TObject; ASubscription: ISubscription);
function Subscriber: TObject; stdcall;
function Subscription: ISubscription; stdcall;
end;
IEventInfo = interface
['{C9A4817B-2EA5-4DA0-B27E-EEAD234F0F71}']
function EventData: IInterface; stdcall;
function Sender: TObject; stdcall;
end;
TEventInfo = class(TInterfacedObject, IEventInfo)
private
FEventData: IInterface;
FSender: TObject;
public
constructor Create(ASender: TObject; AEventData: IInterface);
function EventData: IInterface; stdcall;
function Sender: TObject; stdcall;
end;
TEventProcessThread = class(TThread)
private
FNotificationService: TNotificationService;
FEventQueue: IInterfaceListExt;
D: ISubData;
E: IEventInfo;
procedure ProcessEvent;
public
constructor Create(ANotificationService: TNotificationService);
procedure Execute; override;
procedure Enqueue(AEventInfo: IEventInfo);
end;
constructor TNotificationService.Create;
begin
inherited Create;
FList := CreateInterfaceListExt();
end;
{
***************************** TNotificationService *****************************
}
procedure TNotificationService.Notify(Sender: TObject; AEventData: IInterface);
var
D: ISubData;
I: Integer;
CloneList: IInterfaceListExt;
begin
CloneList := FList.Clone();
for I := 0 to CloneList.Count-1 do
begin
if Supports(CloneList[I], ISubData, D) then
begin
if (D.Subscriber <> Sender) then
if D.Subscription.EventIsMatches(Sender, AEventData) then
D.Subscription.DoEvent(Sender, AEventData);
end;
end;
end;
procedure TNotificationService.NotifyAsync(Sender: TObject; AEventData:
IInterface);
begin
if (FEventProcessThread = nil) then
TEventProcessThread.Create(Self);
(FEventProcessThread as TEventProcessThread).
Enqueue(TEventInfo.Create(Sender, AEventData));
end;
function SelectForUnsubscribe(AItem: IInterface; Acontext:
array of const): Boolean;
var
D: ISubData;
Subscriber: TObject;
Subscription: ISubscription;
begin
Supports(AItem, ISubData, D);
Subscriber := AContext[0].VObject;
Subscription := ISubscription(AContext[1].VInterface);
Result := ((Subscriber = nil) or (D.Subscriber = Subscriber))
and ((Subscription = nil) or (D.Subscription = Subscription));
end;
destructor TNotificationService.Destroy;
begin
if FEventProcessThread <> nil then
begin
FEventProcessThread.Terminate;
FEventProcessThread.WaitFor;
FEventProcessThread.Free;
end;
inherited Destroy;
end;
procedure TNotificationService.Subscribe(Subscriber: TObject; Subscription:
ISubscription);
begin
FList.Add(TSubData.Create(Subscriber, Subscription));
end;
procedure TNotificationService.Unsubscribe(Subscriber: TObject; Subscription:
ISubscription);
var
I: Integer;
L: IInterfaceListExt;
begin
L := FList.Select(SelectForUnsubscribe, [Subscriber, Subscription]);
for I := 0 to L.Count-1 do
FList.Remove(L[I]);
end;
procedure TNotificationService.UnsubscribeAll(Subscriber: TObject);
begin
Unsubscribe(Subscriber, nil);
end;
constructor TSubData.Create(ASubscriber: TObject; ASubscription: ISubscription);
begin
inherited Create;
FSubscriber := ASubscriber;
FSubscription := ASubscription;
end;
function TSubData.Subscriber: TObject;
begin
Result := FSubscriber;
end;
function TSubData.Subscription: ISubscription;
begin
Result := FSubscription;
end;
constructor TEventInfo.Create(ASender: TObject; AEventData: IInterface);
begin
inherited Create;
FSender := ASender;
FEventData := AEventData;
end;
function TEventInfo.EventData: IInterface;
begin
Result := FEventData;
end;
function TEventInfo.Sender: TObject;
begin
Result := FSender;
end;
constructor TEventProcessThread.Create(ANotificationService:
TNotificationService);
begin
inherited Create(True);
FNotificationService := ANotificationService;
FEventQueue := CreateInterfaceListExt;
FreeOnTerminate := False;
Resume;
end;
procedure TEventProcessThread.Execute;
var
I: Integer;
CloneList: IInterfaceListExt;
begin
while not Terminated do
begin
while FEventQueue.Count > 0 do
begin
Supports(FEventQueue[0], IEventInfo, E);
FEventQueue.Remove(E);
CloneList := FNotificationService.FList.Clone;
for I := 0 to CloneList.Count-1 do
begin
if Terminated then
Break;
if Supports(CloneList[I], ISubData, D) then
begin
try
Synchronize(ProcessEvent);
if not Terminated then
Sleep(10);
except
end;
end;
end;
if Terminated then
Break;
end;
if not Terminated then
Sleep(50);
end;
end;
procedure TEventProcessThread.ProcessEvent;
begin
if (D <> nil) and (D.Subscription <> nil) and (E <> nil) then
D.Subscription.DoEvent(E.Sender, E.EventData);
end;
procedure TEventProcessThread.Enqueue(AEventInfo: IEventInfo);
begin
if not Terminated then
FEventQueue.Add(AEventInfo);
end;
end.
|
program pbxreader;
{$mode delphi}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
heaptrc,
Classes, SysUtils, pbxfile, pbxcontainer, xcodeproj
{ you can add units after this };
function ReadFileToString(const fn: string): string;
var
fs : TFileStream;
begin
fs:=TFileStream.Create(fn, fmOpenRead or fmShareDenyNone);
try
SetLength(Result, fs.Size);
fs.Read(Result[1], fs.Size);
finally
fs.Free;
end;
end;
procedure WriteStringToFile(const s, fn: string);
var
fs : TFileStream;
begin
fs:=TFileStream.Create(fn, fmCreate);
try
if length(s)>0 then begin
fs.Write(s[1], length(s));
fs.Size:=length(s);
end;
finally
fs.Free;
end;
end;
procedure TestProject(const buf: string);
var
c : TPBXContainer;
st : TStringStream;
info : TPBXFileInfo;
prj : PBXProject;
i : Integer;
begin
c:= TPBXContainer.Create;
st := TStringStream.Create(buf);
try
c.ReadFile(st, info);
writeln('arch ver: ',info.archiveVersion);
writeln(' obj ver: ',info.objectVersion);
writeln('root obj: ', PtrUInt( info.rootObject ));
if info.rootObject is PBXProject then begin
writeln('project!');
prj:=PBXProject(info.rootObject);
writeln(prj.knownRegions.Text);
writeln('targets: ', prj.targets.Count );
for i:=0 to prj.targets.Count-1 do begin
writeln(prj.targets.Items[i].ClassName);
writeln(PBXNativeTarget(prj.targets.Items[i]).name);
end;
writeln(PtrUInt(prj.buildConfigurationList));
writeln('build configuration:');
for i:=0 to prj.buildConfigurationList.buildConfigurations.Count-1 do begin
writeln(' ',XCBuildConfiguration(prj.buildConfigurationList.buildConfigurations[i]).name);
end;
end;
finally
st.Free;
c.Free;
end;
end;
type
{ MyClass }
MyClass = class(TObject)
private
fInt: Integer;
fInt2: Integer;
fInt3: Integer;
fRO: TList;
fRW: TList;
protected
function GetInt3: Integer;
procedure SetInt3(AValue: Integer);
function GetInt2: Integer;
public
constructor Create;
published
property Int: Integer read fInt write fInt;
property Int2: Integer read GetInt2 write fInt2;
property Int3: Integer read GetInt3 write SetInt3;
property RO: TList read fRO;
property RW: TList read fRW write fRW;
end;
var
lst : TList;
m : MyClass;
{ MyClass }
function MyClass.GetInt3: Integer;
begin
Result:=fInt3;
end;
procedure MyClass.SetInt3(AValue: Integer);
begin
fInt3:=AValue;
end;
function MyClass.GetInt2: Integer;
begin
Result:=fInt2;
end;
constructor MyClass.Create;
begin
fRO:=TList.Create;
fRW:=TList.Create;
end;
procedure TestRTTI;
var
lst : TList;
m : MyClass;
begin
lst:=TList.Create;
m:=MyClass.Create;
PBXGatherObjects(m, lst);
end;
procedure TestWriter;
var
w : TPBXWriter;
begin
w := TPBXWriter.Create;
try
w.OpenBlock('{');
w.WriteName('archiveVersion');
w.WriteValue('1');
w.WriteName('classes');
w.OpenBlock('{');
w.CloseBlock('}');
w.WriteName('objectVersion');
w.WriteValue('46');
w.WriteName('objects');
w.OpenBlock('{');
w.CloseBlock('}');
w.WriteName('rootObject');
w.WriteValue('aaaa','Project object');
w.CloseBlock('}');
write(w.Buffer);
finally
w.Free;
end;
end;
procedure TestReadThenWrite;
var
prj : PBXProject;
list : TList;
i : Integer;
st : TStringList;
begin
if ParamCount=0 then begin
writeln('please provide pbx file');
Exit;
end;
//ScanAString( ReadFileToString(ParamStr(1)));
//ParseAString( ReadFileToString(ParamStr(1)));
//TestProject( ReadFileToString(ParamStr(1)));
if LoadProjectFromFile(ParamStr(1), prj) then begin
//list:=TList.Create;
//PBXGatherObjects(prj, list);
Write(ProjectWrite(prj));
prj.Free;
{st:=TStringList.Create;
try
for i:=0 to list.Count-1 do begin
st.AddObject( PBXObject(list[i]).ClassName, PBXObject(list[i]));
end;
st.Sort;
for i:=0 to st.Count-1 do begin
writeln(PBXObject(st.Objects[i]).__id,' : ',PBXObject(st.Objects[i]).ClassName);
end;
finally
st.Free;
end;}
//list.Free;
end else
writeln('not a project');
end;
procedure TestWriteAProject;
var
p : PBXProject;
s : string;
t : PBXNativeTarget;
prd : PBXGroup;
//cfg : XCBuildConfiguration;
ph : PBXShellScriptBuildPhase;
begin
p:=CreateMinProject;
p.buildConfigurationList._headerComment:=p.buildConfigurationList._headerComment+' for PBXProject "test"';
p.attributes.AddStr('LastUpgradeCheck','0610');
t:=ProjectAddTarget(p,'targetto');
ph:=TargetAddRunScript(t);
ph.shellScript:='echo "hello world"';
//ph.buildActionMask:='0';
ph.runOnlyForDeploymentPostprocessing:='0';
t.productReference:=CreateFileRef('targetto', FILETYPE_EXEC);
PBXFileReference(t.productReference).sourceTree:='BUILT_PRODUCTS_DIR';
t.productName:='targetto';
t.productType:=PRODTYPE_TOOL;
// at least one configuration is added !
//todo: a target should automatically copy project's building settings
t.buildConfigurationList:=XCConfigurationList.Create;
t.buildConfigurationList._headerComment:='Build configuration list for PBXNativeTarget "targetto"';
t.buildConfigurationList.addConfig('Default').buildSettings.AddStr('PRODUCT_NAME','targetto');
t.buildConfigurationList.addConfig('Release').buildSettings.AddStr('PRODUCT_NAME','targetto');
t.buildConfigurationList.defaultConfigurationIsVisible:='0';
t.buildConfigurationList.defaultConfigurationName:='Release';
{ cfg:=XCBuildConfiguration(p.buildConfigurationList.buildConfigurations[0]);
cfg.buildSettings.AddStr('COPY_PHASE_STRIP', 'NO');
cfg.buildSettings.AddStr('GCC_DYNAMIC_NO_PIC', 'NO');
cfg.buildSettings.AddStr('GCC_OPTIMIZATION_LEVEL', '0');
cfg.buildSettings.AddStr('PRODUCT_NAME', 'targetto'); }
p.mainGroup:=CreateRootGroup('/Users/dmitry/pbx/utils/test.xcodeproj');
// requirements ?
prd:=p.mainGroup.addSubGroup('Products');
prd.children.Add(t.productReference);
p.productRefGroup:=prd;
p.compatibilityVersion:='Xcode 3.2';
s:=ProjectWrite(p);
WriteStringToFile(s, 'test.xcodeproj/project.pbxproj');
p.Free;
end;
begin
if FileExists('leaks.txt') then DeleteFile('leaks.txt');
SetHeapTraceOutput('leaks.txt');
try
TestReadThenWrite;
except
on e: exception do
writeln(e.Message);
end;
end.
|
unit InputSearch;
interface
uses
Classes, SysUtils, Collection, FluidLinks, CacheCommon;
// InputLink = X×Y×M×Town×Company×FacilityName
type
TInputLink = class; // Temporal object to store an Input
TInputSearch = class; // Performs a query to find the best group of Inputs
TInputLink =
class(TFluidLink)
public
constructor Create(const Name : string);
protected
fCapacity : integer;
fSupLevel : integer;
public
property Capacity : integer read fCapacity;
property SupLevel : integer read fSupLevel;
end;
TInputSearchResult =
class(TFluidSearchResult)
protected
function CreateFluidLink(Name : string) : TFluidLink; override;
function CompareFluidLinks(Item1, Item2 : TObject) : integer; override;
private
function GetFluidLink(index : integer) : TInputLink;
public
property Links[index : integer] : TInputLink read GetFluidLink; default;
end;
TInputSearch =
class
public
constructor Create(const aPath : string; Town, Company : string; aCount : integer; aX, aY, aSortMode : word; aRole : TFacilityRoleSet);
destructor Destroy; override;
private
fResult : TInputSearchResult;
public
property Result : TInputSearchResult read fResult;
end;
implementation
uses
CacheObjects, CompStringsParser, SpecialChars;
// TInputLink
constructor TInputLink.Create(const Name : string);
var
p : integer;
begin
inherited Create(Name);
try
if fRole = rolNeutral
then p := 1
else p := 2;
fX := StrToInt(GetNextStringUpTo(Name, p, BackslashChar));
inc(p);
fY := StrToInt(GetNextStringUpTo(Name, p, BackslashChar));
inc(p);
fCapacity := StrToInt(GetNextStringUpTo(Name, p, BackslashChar));
inc(p);
fSupLevel := StrToInt(GetNextStringUpTo(Name, p, BackslashChar));
inc(p);
fTown := GetNextStringUpTo(Name, p, BackslashChar);
inc(p);
fCompany := GetNextStringUpTo(Name, p, BackslashChar);
inc(p);
fFacility := GetNextStringUpTo(Name, p, BackslashChar);
inc(p);
fCircuits := GetNextStringUpTo(Name, p, #0);
except
end;
end;
// TInputSearchResult
function TInputSearchResult.CreateFluidLink(Name : string) : TFluidLink;
begin
result := TInputLink.Create(Name);
end;
function TInputSearchResult.CompareFluidLinks(Item1, Item2 : TObject) : integer;
var
I1 : TInputLink absolute Item1;
I2 : TInputLink absolute Item2;
begin
result := I1.Distance(fX, fY) - I2.Distance(fX, fY);
end;
function TInputSearchResult.GetFluidLink(index : integer) : TInputLink;
begin
result := TInputLink(fList[index]);
end;
// TInputSearch
constructor TInputSearch.Create(const aPath : string; Town, Company : string; aCount : integer; aX, aY, aSortMode : word; aRole : TFacilityRoleSet);
var
FolderItr : TFolderIterator;
begin
inherited Create;
fResult := TInputSearchResult.Create(aCount, aX, aY, aSortMode, aRole);
if Town = ''
then Town := '*';
if Company = ''
then Company := '*'; // X×Y×C×O×Town×Company×Facility
FolderItr := TFolderIterator.Create(GetCacheRootPath + aPath, '*' + BackslashChar + '*' + BackslashChar + '*' + BackslashChar + '*' + BackslashChar + Town + BackslashChar + Company + BackslashChar + '*', onArchives);
try
if not FolderItr.Empty
then
repeat
fResult.Add(FolderItr.Current);
until not FolderItr.Next;
finally
FolderItr.Free;
end;
end;
destructor TInputSearch.Destroy;
begin
fResult.Free;
inherited;
end;
end.
|
unit Model.UsuariosJornal;
interface
uses Common.ENum, FireDAC.Comp.Client, Controller.Sistema, DAO.Conexao, FireDAC.Comp.DataSet;
type
TUsuarios = class
private
FCodigo: integer;
FNome: String;
FLogin: String;
FSenha: String;
FGrupo: String;
FAtivo: Boolean;
FAcao: TAcao;
FConexao : TConexao;
function Inserir(): Boolean;
function Alterar(): Boolean;
function Excluir(): Boolean;
public
constructor Create;
property Codigo: integer read FCodigo write FCodigo;
property Nome: String read FNome write FNome;
property Login: String read FLogin write FLogin;
property Senha: String read FSenha write FSenha;
property Grupo: String read FGrupo write FGrupo;
property Ativo: Boolean read FAtivo write FAtivo;
property Acao: TAcao read FAcao write FAcao;
function GetID: Integer;
function Localizar(aParam: array of variant): TFDQuery;
function Gravar(): Boolean;
function ValidaLogin(sLogin: String; sSenha: String): Boolean;
function AlteraSenha(AUsuarios: TUsuarios): Boolean;
function LoginExiste(sLogin: String): Boolean;
function SaveData(memTab: TFDMemTable): Boolean;
end;
const
TABLENAME = 'login_usuarios';
implementation
{ TUsuarios }
function TUsuarios.Alterar: Boolean;
var
FDQuery : TFDQuery;
begin
try
REsult := False;
FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET '+
'nom_usuario = :pnom_usuario, des_login = :pdes_login, des_senha = :pdes_senha, cod_agente = :pcod_agente, ' +
'dom_ativo = :pdom_ativo ' +
'WHERE id_usuario = :pid_usuario;', [Self.FNome, Self.FLogin, Self.FSenha, Self.FGrupo,
Self.FAtivo, Self.FCodigo]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TUsuarios.AlteraSenha(AUsuarios: TUsuarios): Boolean;
var
FDQuery : TFDQuery;
begin
try
REsult := False;
FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery;
FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET '+
'des_senha = :pdes_senha ' +
'WHERE id_usuario = :pid_usuario;', [Self.FSenha, Self.FCodigo]);
Result := True;
finally
FDQuery.Free;
end;
end;
constructor TUsuarios.Create;
begin
FConexao := TConexao.Create;
end;
function TUsuarios.Excluir: Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where id_usuario = :pid_usuario', [Self.FCodigo]);
Result := True;
finally
FDquery.Free;
end;
end;
function TUsuarios.GetID: Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(id_usuario),0) + 1 from ' + TABLENAME);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Free;
end;
end;
function TUsuarios.Gravar: Boolean;
begin
Result := False;
case FAcao of
Common.ENum.tacIncluir: Result := Self.Inserir();
Common.ENum.tacAlterar: Result := Self.Alterar();
Common.ENum.tacExcluir: Result := Self.Excluir();
end;
end;
function TUsuarios.Inserir: Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
Self.FCodigo := GetId();
FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' '+
'(id_usuario, nom_usuario, des_login, des_senha, cod_agente, dom_ativo)' +
'VALUES ' +
'(:pid_usuario, :pnom_usuario, :pdes_login, :pdes_senha, :pcod_agente,:pdom_ativo);' ,
[Self.FCodigo, Self.FNome, Self.FLogin, Self.FSenha, Self.FGrupo, Self.FAtivo]);
Result := True;
finally
FDQuery.Free;
end;
end;
function TUsuarios.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] = 'CODIGO' then
begin
FDQuery.SQL.Add('WHERE id_usuario = :pid_usuario');
FDQuery.ParamByName('pid_usuario').AsInteger := aParam[1];
end;
if aParam[0] = 'LOGIN' then
begin
FDQuery.SQL.Add('WHERE des_login = :pdes_login');
FDQuery.ParamByName('pdes_login').AsString := aParam[1];
end;
if aParam[0] = 'NOME' then
begin
FDQuery.SQL.Add('WHERE nom_usuario LIKE :pnom_usuario');
FDQuery.ParamByName('pnom_usuario').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();
Result := FDQuery;
end;
function TUsuarios.LoginExiste(sLogin: String): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDquery := FConexao.ReturnQuery();
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT * FROM ' + TABLENAME);
FDQuery.SQL.Add(' WHERE des_login = :pdes_login');
FDQuery.ParamByName('pdes_login').AsString := sLogin;
FDQuery.Open();
Result := (not FDQuery.IsEmpty);
finally
FDquery.Free;
end;
end;
function TUsuarios.SaveData(memTab: TFDMemTable): Boolean;
var
fdQuery : TFDQuery;
begin
try
Result := False;
FConexao:= TConexao.Create;
fdQuery := FConexao.ReturnQuery();
fdQuery.SQL.Add('select * from ' + TABLENAME);
fdQuery.Open();
fdQuery.CopyDataSet(memTab, [coRestart, coEdit, coAppend]);
fdQuery.Close;
Result := True;
finally
fdQuery.Free;
FConexao.Free;
end;end;
function TUsuarios.ValidaLogin(sLogin, sSenha: String): Boolean;
var
FDquery : TFDQuery;
begin
try
Result := False;
FDquery := FConexao.ReturnQuery();
FDQuery.SQL.Clear;
FDQuery.SQL.Add('SELECT des_senha FROM ' + TABLENAME);
FDQuery.SQL.Add(' WHERE des_login = :pdes_login');
FDQuery.ParamByName('pdes_login').AsString := sLogin;
FDQuery.Open();
if FDquery.IsEmpty then Exit;
if FDQuery.FieldByName('des_senha').AsString <> sSenha then Exit;
Result := True;
finally
FDquery.Free;
end;
end;
end.
|
program Project1;
var
s:string;
i:integer;
begin
s:='Hey! How are you?';
for i:=1 to length(s) do
s[i]:=upcase(s[i]);
write(s); {'HEY! HOW ARE YOU'}
readln;
end.
{Function UpCase(C:Char):Char;
Description
Converts the character C to uppercase and returned. If the character is already
in uppercase form or the character is not within the range of the lower case
alphabet, then it is left as is.}
|
unit DAO.ContatosBases;
interface
uses
FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Model.ContatosBases;
type
TContatosBasesDAO = class
private
FConexao: TConexao;
public
constructor Create;
function GetSeq(AContatos: TContatosBase): Integer;
function Inserir(AContatos: TContatosBase): Boolean;
function Alterar(AContatos: TContatosBase): Boolean;
function Excluir(AContatos: TContatosBase): Boolean;
function Pesquisar(aParam: array of variant): TFDQuery;
end;
const
TABLENAME = 'tbcontatosagentes';
implementation
{ TContatosBasesDAO }
uses Control.Sistema;
function TContatosBasesDAO.Alterar(AContatos: TContatosBase): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
FDQuery.ExecSQL('update ' + TABLENAME + ' set des_contato = :des_contato, num_telefone = :num_telefone, des_email = :des_email ' +
'where cod_agente = :cod_agente and seq_contato = :seq_contato', [AContatos.Descricao, AContatos.Telefone,
AContatos.EMail, AContatos.CodigoDistribuidor, AContatos.Sequencia]);
Result := True;
finally
FDQuery.Close;
FDQuery.Connection.Close;
FDQuery.Free;
end;
end;
constructor TContatosBasesDAO.Create;
begin
FConexao := TSistemaControl.GetInstance.Conexao;
end;
function TContatosBasesDAO.Excluir(AContatos: TContatosBase): Boolean;
var
FDQuery: TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
if AContatos.Sequencia = 0 then
begin
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_agente = :cod_agente',
[AContatos.CodigoDistribuidor]);
end
else
begin
FDQuery.ExecSQL('delete from ' + TABLENAME + ' where cod_agente = :cod_agente and seq_contato = :seq_contato',
[AContatos.CodigoDistribuidor, AContatos.Sequencia]);
end;
Result := True;
finally
FDQuery.Close;
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TContatosBasesDAO.GetSeq(AContatos: TContatosBase): Integer;
var
FDQuery: TFDQuery;
begin
try
FDQuery := FConexao.ReturnQuery();
FDQuery.Open('select coalesce(max(seq_contato),0) + 1 from ' + TABLENAME + ' where cod_agente = ' +
AContatos.CodigoDistribuidor.ToString);
try
Result := FDQuery.Fields[0].AsInteger;
finally
FDQuery.Close;
end;
finally
FDQuery.Connection.Close;
FDQuery.Free;
end;end;
function TContatosBasesDAO.Inserir(AContatos: TContatosBase): Boolean;
var
FDQuery : TFDQuery;
begin
try
Result := False;
FDQuery := FConexao.ReturnQuery();
AContatos.Sequencia := GetSeq(Acontatos);
FDQuery.ExecSQL('insert into ' + TABLENAME + ' (cod_Agente, seq_contato, des_contato, num_telefone, des_email) ' +
'values (:cod_Agente, :seq_contato, :des_contato, :num_telefone, :des_email)');
Result := True;
finally
FDQuery.Close;
FDQuery.Connection.Close;
FDquery.Free;
end;
end;
function TContatosBasesDAO.Pesquisar(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 cod_Agente, seq_contato, des_contato, num_telefone, des_email from ' + TABLENAME);
if aParam[0] = 'AGENTE' then
begin
FDQuery.SQL.Add('where cod_agente = :cod_agente');
FDQuery.ParamByName('cod_agente').AsInteger := aParam[1];
end;
if aParam[0] = 'DESCRICAO' then
begin
FDQuery.SQL.Add('where des_contato like :des_contato');
FDQuery.ParamByName('des_contato').AsString := aParam[1];
end;
if aParam[0] = 'EMAIL' then
begin
FDQuery.SQL.Add('where des_email like :des_email');
FDQuery.ParamByName('des_email').AsString := aParam[1];
end;
if aParam[0] = 'SEQUENCIA' then
begin
FDQuery.SQL.Add('where cod_agente = :cod_agente and seq_contato = :seq_contato');
FDQuery.ParamByName('cod_agente').AsInteger := aParam[1];
FDQuery.ParamByName('seq_contato').AsInteger := aParam[2];
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;
Result := FDQuery;
end;
end.
|
unit SDConsoleForm;
interface
uses
Windows, Forms, BaseForm, Classes, Controls,
StdCtrls, Sysutils, ExtCtrls, Dialogs, VirtualTrees,
define_dealitem, define_dealmarket, define_datasrc, define_price, define_datetime,
StockDataConsoleApp, StockDataConsoleTask, DealItemsTreeView, StockDayDataAccess,
SDFrameDealItemViewer,
SDFrameDataViewer,
SDFrameDataRepair,
SDFrameStockInstant,
SDFrameStockInfo,
SDFrameStockClass,
SDFrameTDXData,
ComCtrls, Tabs;
type
TFormSDConsoleData = record
AppStartTimer: TTimer;
DealItemTree: TDealItemTreeCtrl;
FrameDealItemViewer: TfmeDealItemViewer;
FrameDataViewer: TfmeDataViewer;
FrameDataRepair: TfmeDataRepair;
FrameStockClass: TfmeStockClass;
FrameStockInfo: TfmeStockInfo;
FrameTDXData: TfmeTDXData;
FrameStockInstant: TfmeStockInstant;
end;
TfrmSDConsole = class(TfrmBase)
pnlBottom: TPanel;
pnlTop: TPanel;
pnlMain: TPanel;
pnlLeft: TPanel;
splLeft: TSplitter;
tsfunc: TTabSet;
procedure tsfuncChange(Sender: TObject; NewTab: Integer;
var AllowChange: Boolean);
private
{ Private declarations }
fFormSDConsoleData: TFormSDConsoleData;
procedure tmrAppStartTimer(Sender: TObject);
procedure DoNotifyDealItemChange(ADealItem: PRT_DealItem);
protected
procedure FormCreate(Sender: TObject);
public
constructor Create(Owner: TComponent); override;
end;
implementation
{$R *.dfm}
uses
define_StockDataApp,
define_stock_quotes,
define_dealstore_file,
windef_msg,
win.shutdown,
win.iobuffer,
ShellAPI,
UtilsHttp,
BaseFrame,
//UtilsLog,
HTMLParserAll3,
BaseStockFormApp,
StockDayData_Load,
BaseWinApp,
db_dealItem_LoadIni,
db_dealitem_load,
db_dealitem_save;
constructor TfrmSDConsole.Create(Owner: TComponent);
begin
inherited;
FillChar(fFormSDConsoleData, SizeOf(fFormSDConsoleData), 0);
fFormSDConsoleData.AppStartTimer := TTimer.Create(Application);
fFormSDConsoleData.AppStartTimer.Interval := 100;
fFormSDConsoleData.AppStartTimer.OnTimer := tmrAppStartTimer;
fFormSDConsoleData.AppStartTimer.Enabled := true;
Self.OnCreate := FormCreate;
end;
procedure TfrmSDConsole.FormCreate(Sender: TObject);
begin
DragAcceptFiles(Handle, True) ;
//
end;
procedure TfrmSDConsole.tmrAppStartTimer(Sender: TObject);
begin
if nil <> Sender then
begin
if Sender is TTimer then
begin
TTimer(Sender).Enabled := false;
TTimer(Sender).OnTimer := nil;
end;
if Sender = fFormSDConsoleData.AppStartTimer then
begin
fFormSDConsoleData.AppStartTimer.Enabled := false;
fFormSDConsoleData.AppStartTimer.OnTimer := nil;
end;
end;
// initialize
fFormSDConsoleData.FrameDealItemViewer := TfmeDealItemViewer.Create(Self);
fFormSDConsoleData.FrameDealItemViewer.App := Self.App;
fFormSDConsoleData.FrameDealItemViewer.Parent := Self.pnlLeft;
fFormSDConsoleData.FrameDealItemViewer.Align := alClient;
fFormSDConsoleData.FrameDealItemViewer.Visible := True;
fFormSDConsoleData.FrameDealItemViewer.Initialize;
fFormSDConsoleData.FrameDealItemViewer.OnDealItemChange := DoNotifyDealItemChange;
tsfunc.Tabs.Clear;
fFormSDConsoleData.FrameDataViewer := TfmeDataViewer.Create(Self);
fFormSDConsoleData.FrameDataViewer.App := Self.App;
fFormSDConsoleData.FrameDataViewer.Initialize;
tsfunc.Tabs.AddObject('DayDataView', fFormSDConsoleData.FrameDataViewer);
fFormSDConsoleData.FrameTDXData := TfmeTDXData.Create(Self);
fFormSDConsoleData.FrameTDXData.App := Self.App;
fFormSDConsoleData.FrameTDXData.Initialize;
tsfunc.Tabs.AddObject('TDXData', fFormSDConsoleData.FrameTDXData);
fFormSDConsoleData.FrameStockInstant := TfmeStockInstant.Create(Self);
fFormSDConsoleData.FrameStockInstant.App := Self.App;
fFormSDConsoleData.FrameStockInstant.Initialize;
tsfunc.Tabs.AddObject('StockInstant', fFormSDConsoleData.FrameStockInstant);
fFormSDConsoleData.FrameDataRepair := TfmeDataRepair.Create(Self);
fFormSDConsoleData.FrameDataRepair.App := Self.App;
fFormSDConsoleData.FrameDataRepair.Initialize;
tsfunc.Tabs.AddObject('DataRepair', fFormSDConsoleData.FrameDataRepair);
fFormSDConsoleData.FrameStockClass := TfmeStockClass.Create(Self);
fFormSDConsoleData.FrameStockClass.App := Self.App;
//fFormSDConsoleData.FrameStockClass.Initialize;
tsfunc.Tabs.AddObject('StockClass', fFormSDConsoleData.FrameStockClass);
fFormSDConsoleData.FrameStockInfo := TfmeStockInfo.Create(Self);
fFormSDConsoleData.FrameStockInfo.App := Self.App;
//fFormSDConsoleData.FrameStockInfo.Initialize;
tsfunc.Tabs.AddObject('StockInfo', fFormSDConsoleData.FrameStockInfo);
tsfunc.TabIndex := 0;
end;
procedure TfrmSDConsole.tsfuncChange(Sender: TObject; NewTab: Integer;
var AllowChange: Boolean);
var
tmpFrame: TfmeBase;
begin
inherited;
if 0 <= tsfunc.TabIndex then
begin
tmpFrame := TfmeBase(tsfunc.Tabs.Objects[tsfunc.TabIndex]);
tmpFrame.CallDeactivate;
tmpFrame.Visible := false;
end;
tmpFrame := TfmeBase(tsfunc.Tabs.Objects[NewTab]);
tmpFrame.Parent := Self.pnlMain;
tmpFrame.Align := alClient;
tmpFrame.Visible := true;
tmpFrame.CallActivate;
end;
procedure TfrmSDConsole.DoNotifyDealItemChange(ADealItem: PRT_DealItem);
var
tmpFrame: TfmeBase;
begin
if 0 <= tsfunc.TabIndex then
begin
tmpFrame := TfmeBase(tsfunc.Tabs.Objects[tsfunc.TabIndex]);
if tmpFrame = fFormSDConsoleData.FrameDataViewer then
begin
fFormSDConsoleData.FrameDataViewer.NotifyDealItem(ADealItem);
exit;
end;
if tmpFrame = fFormSDConsoleData.FrameDataRepair then
begin
fFormSDConsoleData.FrameDataRepair.NotifyDealItem(ADealItem);
Exit;
end;
if tmpFrame = fFormSDConsoleData.FrameStockClass then
begin
fFormSDConsoleData.FrameStockClass.NotifyDealItem(ADealItem);
exit;
end;
if tmpFrame = fFormSDConsoleData.FrameStockInfo then
begin
fFormSDConsoleData.FrameStockInfo.NotifyDealItem(ADealItem);
exit;
end;
if tmpFrame = fFormSDConsoleData.FrameTDXData then
begin
fFormSDConsoleData.FrameTDXData.NotifyDealItem(ADealItem);
exit;
end;
end;
end;
end.
|
unit MainWindow;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
D3DXCore, DirectDraw, Direct3D;
type
TMainForm =
class(TForm)
OpenDialog: TOpenDialog;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
function InitD3DX : HRESULT;
function ReleaseD3DX : HRESULT;
function InitRenderer : HRESULT;
function LoadTexture : HRESULT;
function RenderTest(Alpha : single) : HRESULT;
//HandleModeChanges : HRESULT;
private
fD3DXContext : ID3DXContext;
fDirectDraw : IDirectDraw7;
fDirect3D : IDirect3D7;
fDirect3DDevice : IDirect3DDevice7;
fTexture : IDirectDrawSurface7;
fD3DXReady : boolean;
fWidth : integer;
fHeight : integer;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
uses
D3DXSprite, D3DXErr, SurfaceUtils;
const
cScreenWidth = 1024;
cScreenHeight = 768;
procedure TMainForm.FormCreate(Sender: TObject);
begin
Left := 0;
Top := 0;
Width := cScreenWidth;
Height := cScreenHeight;
if Failed(InitD3DX)
then Application.MessageBox('D3DX Initialization failed!', 'Error', MB_OK);
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
ReleaseD3DX;
end;
function TMainForm.InitD3DX : HRESULT;
var
hr : HRESULT;
dwDevice : dword;
dwDeviceCount : dword;
dev : TD3DX_DEVICEDESC;
d3dDesc : TD3DDEVICEDESC7;
devDesc : TD3DX_DEVICEDESC;
begin
hr := D3DXInitialize;
if Succeeded(hr)
then
begin
// Look for fastest device which supports the desired blending for sprites
dwDeviceCount := D3DXGetDeviceCount;
dev.deviceIndex := D3DX_DEFAULT;
dev.hwLevel := D3DX_DEFAULT;
dev.onPrimary := TRUE;
for dwDevice := 0 to pred(dwDeviceCount) do
begin
if Succeeded(D3DXGetDeviceCaps(dwDevice, nil, @d3dDesc, nil, nil))
then
if (((d3dDesc.dpcTriCaps.dwSrcBlendCaps and D3DPBLENDCAPS_SRCALPHA) <> 0) and
((d3dDesc.dpcTriCaps.dwDestBlendCaps and D3DPBLENDCAPS_INVSRCALPHA) <> 0) and
((d3dDesc.dpcTriCaps.dwTextureFilterCaps and D3DPTFILTERCAPS_LINEAR) <> 0) and
((d3dDesc.dpcTriCaps.dwTextureBlendCaps and D3DPTBLENDCAPS_MODULATE) <> 0))
then
if Succeeded(D3DXGetDeviceDescription(dwDevice, devDesc))
then
if (D3DX_DEFAULT = dev.hwLevel) or
(dev.hwLevel > devDesc.hwLevel) or
(dev.hwLevel = devDesc.hwLevel) and (devDesc.onPrimary)
then dev := devDesc;
end;
if D3DX_DEFAULT = dev.hwLevel
then hr := D3DXERR_NODIRECT3DDEVICEAVAILABLE
else
begin
hr := D3DXCreateContext(
dev.hwLevel, // D3DX device
0, //D3DX_CONTEXT_FULLSCREEN, // flags
Handle, // Main window
cScreenWidth, // width
cScreenHeight, // height
fD3DXContext); // returned D3DX interface
if Succeeded(hr)
then
begin
fD3DXReady := true;
hr := InitRenderer;
end;
end;
end;
Result := hr;
end;
function TMainForm.ReleaseD3DX : HRESULT;
begin
fTexture := nil;
fDirectDraw := nil;
fDirect3DDevice := nil;
//fDirect3D := nil;
fD3DXContext := nil;
Result := D3DXUninitialize;
end;
function TMainForm.InitRenderer : HRESULT;
begin
if fD3DXReady
then
begin
fDirectDraw := IDirectDraw7(fD3DXContext.GetDD); // >>> this a temporary patch
SurfaceUtils.DirectDrawObj := fDirectDraw;
fDirect3DDevice := IDirect3DDevice7(fD3DXContext.GetD3DDevice);
fDirect3DDevice.GetCaps(SurfaceUtils.DeviceCaps);
if fDirect3DDevice <> nil
then
begin
fDirectDraw := IDirectDraw7(fD3DXContext.GetDD);
if fDirectDraw <> nil
then
begin
// Enable dither, specular, lighting and z-buffer usage
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_COLORKEYENABLE, 1);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_DITHERENABLE, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_SPECULARENABLE, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_LIGHTING, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_ZENABLE, 0);
// Enable vertices to have colors
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_COLORVERTEX, 0);
fDirect3DDevice.SetRenderState(D3DRENDERSTATE_DIFFUSEMATERIALSOURCE, 0);
// Set the background to bright blue (red/green/blue/alpha)
fD3DXContext.SetClearColor(TD3DCOLOR(D3DRGBA(0.0, 0.0, 1.0, 1.0)));
fD3DXContext.Clear(D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER);
Result := S_OK;
end
else Result := E_FAIL;
end
else Result := E_FAIL;
end
else Result := E_FAIL;
end;
function TMainForm.LoadTexture : HRESULT;
var
hr : HRESULT;
errstr : array [0..1000] of char;
bmp : TBitmap;
hdcTexture : HDC;
palette : IDirectDrawPalette;
palentries : array [0..255] of TPaletteEntry;
numentries : integer;
colorkey : TDDCOLORKEY;
begin
bmp := TBitmap.Create;
bmp.LoadFromFile('C:\Shared\TestImages\mine2.bmp');
fWidth := bmp.Width;
fHeight := bmp.Height;
fTexture := CreateTextureSurface(bmp.Width, bmp.Height, 8, true);
if fTexture <> nil
then
begin
numentries := GetPaletteEntries(bmp.Palette, 0, 256, palentries);
hr := fDirectDraw.CreatePalette(DDPCAPS_8BIT, @palentries[0], palette, nil);
if Succeeded(hr)
then
begin
hr := fTexture.SetPalette(palette);
if Succeeded(hr)
then
begin
hr := fTexture.GetDC(hdcTexture);
if Succeeded(hr)
then
begin
if not BitBlt(hdcTexture, 0, 0, bmp.Width, bmp.Height, bmp.Canvas.Handle, 0, 0, SRCCOPY)
then MessageBeep(0);
fTexture.ReleaseDC(hdcTexture);
colorkey.dwColorSpaceHighValue := byte(pchar(bmp.Scanline[0])[0]);
colorkey.dwColorSpaceLowValue := byte(pchar(bmp.Scanline[0])[0]);
hr := fTexture.SetColorKey(DDCKEY_SRCBLT, @colorkey);
if Failed(hr)
then
begin
D3DXGetErrorString(hr, 1000, @errstr[0]);
Application.MessageBox(pchar(@errstr[0]), 'Error', MB_OK);
end;
end
else
begin
D3DXGetErrorString(hr, 1000, @errstr[0]);
Application.MessageBox(pchar(@errstr[0]), 'Error', MB_OK);
end;
end
else
begin
D3DXGetErrorString(hr, 1000, @errstr[0]);
Application.MessageBox(pchar(@errstr[0]), 'Error', MB_OK);
end;
end
else
begin
D3DXGetErrorString(hr, 1000, @errstr[0]);
Application.MessageBox(pchar(@errstr[0]), 'Error', MB_OK);
end;
end
else hr := S_FALSE;
Result := hr;
end;
function TMainForm.RenderTest(Alpha : single) : HRESULT;
const
cLoopCount = 1;
var
hr : HRESULT;
viewport : TD3DVIEWPORT7;
rectViewport : TRect;
pointDest : TD3DXVECTOR3;
initialtickcount : integer;
elapsedticks : integer;
i : integer;
ClipRect : TRect;
begin
if (fTexture <> nil) and fD3DXReady
then
if Succeeded(fDirect3DDevice.BeginScene)
then
begin
fD3DXContext.Clear(D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER);
// We need to setup the rasterizer for rendering sprites;
// this only needs to be done once for all the sprites that
// are rendered; however this function does need to be called
// again if any render state changes are made outside of the
// bltsprite call.
D3DXPrepareDeviceForSprite(fDirect3DDevice, False);
// Get our current viewport
hr := fDirect3DDevice.GetViewport(viewport);
if Succeeded(hr)
then
begin
// Convert the viewport into a proper Rect
rectViewport.left := viewport.dwX;
rectViewport.top := viewport.dwY;
rectViewport.right := viewport.dwX + viewport.dwWidth;
rectViewport.bottom := viewport.dwY + viewport.dwHeight;
// Our non-rotated render target should be centered in the viewport;
pointDest.x := viewport.dwX + viewport.dwWidth/2.0;
pointDest.y := viewport.dwY + viewport.dwHeight/2.0;
pointDest.z := 0.0;
initialtickcount := GetTickCount();
ClipRect := Rect(0, 0, fWidth, fHeight);
// Go ahead and do the render
for i := 0 to pred(cLoopCount) do
begin
//pointDest.x := random(cScreenWidth);
//pointDest.y := random(cScreenHeight);
hr := D3DXDrawSpriteSimple(
fTexture, // texture
fDirect3DDevice, // 3D device
@pointDest, // destination point (center)
Alpha, // alpha
1.0, // scale
0.0, // rotation
nil, // offset
nil//@ClipRect // src sub rect
);
if Failed(hr)
then break;
end;
fDirect3DDevice.EndScene;
hr := fD3DXContext.UpdateFrame(D3DX_DEFAULT);
{
if (hr = DDERR_SURFACELOST) or (hr = DDERR_SURFACEBUSY)
then hr = HandleModeChanges();
}
elapsedticks := GetTickCount() - initialtickcount;
//Application.MessageBox(pchar(IntToStr(i) + ' images rendered in ' + IntToStr(elapsedticks) + ' milliseconds.'), 'Report', MB_OK);
OutputDebugString(pchar(IntToStr(i) + ' images rendered in ' + IntToStr(elapsedticks) + ' milliseconds.'));
end;
end
else hr := E_FAIL
else hr := E_FAIL;
Result := hr;
end;
procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
case key of
VK_F3:
LoadTexture;
VK_F4:
RenderTest(1.0);
VK_F5:
RenderTest(0.5);
end;
end;
end.
|
unit GX_ClipboardHistory;
{$I GX_CondDefine.inc}
interface
uses
Classes, Controls, Forms, StdCtrls, ExtCtrls, Menus,
ComCtrls, ActnList, ToolWin,
GX_Experts, GX_ConfigurationInfo, GX_IdeDock;
type
TClipInfo = class(TObject)
private
FClipTimeStamp: string;
FClipString: string;
public
property ClipTimeStamp: string read FClipTimeStamp write FClipTimeStamp;
property ClipString: string read FClipString write FClipString;
end;
TfmClipboardHistory = class(TfmIdeDockForm)
Splitter: TSplitter;
mmoClipText: TMemo;
MainMenu: TMainMenu;
mitFile: TMenuItem;
mitFileExit: TMenuItem;
mitEdit: TMenuItem;
mitEditCopy: TMenuItem;
mitHelp: TMenuItem;
mitHelpContents: TMenuItem;
mitHelpAbout: TMenuItem;
mitHelpHelp: TMenuItem;
mitHelpSep1: TMenuItem;
mitEditClear: TMenuItem;
lvClip: TListView;
ToolBar: TToolBar;
tbnClear: TToolButton;
tbnCopy: TToolButton;
tbnHelp: TToolButton;
tbnSep2: TToolButton;
Actions: TActionList;
actFileExit: TAction;
actEditCopy: TAction;
actEditClear: TAction;
actHelpHelp: TAction;
actHelpContents: TAction;
actHelpAbout: TAction;
actEditPasteToIde: TAction;
tbnPaste: TToolButton;
mitEditPasteToIde: TMenuItem;
mitView: TMenuItem;
actViewToolBar: TAction;
mitViewToolBar: TMenuItem;
tbnSep3: TToolButton;
btnOptions: TToolButton;
actViewOptions: TAction;
mitViewOptions: TMenuItem;
actRehookClipboard: TAction;
mitFileRehookClipboard: TMenuItem;
tbnDelete: TToolButton;
actDelete: TAction;
mitEditDelete: TMenuItem;
tbnSep1: TToolButton;
mitEditSep1: TMenuItem;
pmListMenu: TPopupMenu;
mitListCopy: TMenuItem;
mitListPasteIntoIDE: TMenuItem;
mitListDelete: TMenuItem;
mitListSep2: TMenuItem;
actEditPasteAsPascalString: TAction;
mitEditPasteAsPascalString: TMenuItem;
mitListPasteAsPascalString: TMenuItem;
tbnPasteAsPascal: TToolButton;
pnlPasteAsOptions: TPanel;
actViewPasteAsOptions: TAction;
tbnViewPasteAs: TToolButton;
tbnSep4: TToolButton;
ShowPasteAsoptions1: TMenuItem;
lblMaxEntries: TLabel;
cbPasteAsType: TComboBox;
chkCreateQuotedStrings: TCheckBox;
chkAddExtraSpaceAtTheEnd: TCheckBox;
actEditCopyFromPascalString: TAction;
actEditReplaceAsPascalString: TAction;
mitEditCopyfromPascalstring: TMenuItem;
mitEditReplaceasPascalstring: TMenuItem;
mitListSep1: TMenuItem;
mitListCopyfromPascalstring: TMenuItem;
mitReplaceasPascalstring: TMenuItem;
procedure FormResize(Sender: TObject);
procedure SplitterMoved(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure lvClipDblClick(Sender: TObject);
procedure lvClipChange(Sender: TObject; Item: TListItem; Change: TItemChange);
procedure actEditCopyExecute(Sender: TObject);
procedure actEditClearExecute(Sender: TObject);
procedure actFileExitExecute(Sender: TObject);
procedure actHelpHelpExecute(Sender: TObject);
procedure actHelpContentsExecute(Sender: TObject);
procedure actHelpAboutExecute(Sender: TObject);
procedure lvClipKeyPress(Sender: TObject; var Key: Char);
procedure actEditPasteToIdeExecute(Sender: TObject);
procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean);
procedure actViewToolBarExecute(Sender: TObject);
procedure actViewOptionsExecute(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure actRehookClipboardExecute(Sender: TObject);
procedure actDeleteExecute(Sender: TObject);
procedure actEditPasteAsPascalStringExecute(Sender: TObject);
procedure actViewPasteAsOptionsExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FHelperWindow: TWinControl;
IgnoreClip: Boolean;
FDataList: TList;
FLoading: Boolean;
SplitterRatio: Double;
procedure ClearDataList;
procedure LoadClips;
procedure SaveClips;
function ConfigurationKey: string;
procedure HookClipboard;
function ClipInfoForItem(Item: TListItem): TClipInfo;
function ClipInfoFromPointer(Ptr: Pointer): TClipInfo;
function HaveSelectedItem: Boolean;
procedure RemoveDataListItem(Index: Integer);
function GetSelectedItemsText: string;
procedure WmDrawClipBoard;
procedure AddClipItem(const AClipText: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Clear;
procedure SaveSettings;
procedure LoadSettings;
end;
TClipExpert = class(TGX_Expert)
private
FMaxClip: Integer;
FAutoStart: Boolean;
FAutoClose: Boolean;
FStoragePath: string;
function GetStorageFile: string;
protected
procedure SetActive(New: Boolean); override;
procedure InternalLoadSettings(Settings: TExpertSettings); override;
procedure InternalSaveSettings(Settings: TExpertSettings); override;
public
constructor Create; override;
destructor Destroy; override;
function GetActionCaption: string; override;
class function GetName: string; override;
procedure Execute(Sender: TObject); override;
procedure Configure; override;
property MaxClip: Integer read FMaxClip write FMaxClip;
property StorageFile: string read GetStorageFile;
end;
var
fmClipboardHistory: TfmClipboardHistory = nil;
ClipExpert: TClipExpert = nil;
implementation
{$R *.dfm}
uses
{$IFOPT D+} GX_DbugIntf, {$ENDIF}
Windows, Messages, SysUtils, Clipbrd, Dialogs, Math, StrUtils, OmniXML,
GX_GxUtils, GX_GenericUtils, GX_OtaUtils, GX_dzVclUtils,
GX_GExperts, GX_ClipboardOptions, GX_SharedImages, GX_XmlUtils,
GX_PasteAs;
const
ClipStorageFileName = 'ClipboardHistory.xml';
type
THelperWinControl = class(TWinControl)
private
FPrevWindow: HWnd;
procedure WMChangeCBChain(var Msg: TMessage); message WM_CHANGECBCHAIN;
procedure WMDrawClipBoard(var Msg: TMessage); message WM_DRAWCLIPBOARD;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TClipData = record
FirstLine: String;
Count: Integer;
end;
function FirstLineOfText(const AClipString: string): TClipData;
begin
Result.FirstLine := '';
with TStringList.Create do
try
Text := AClipString;
Result.Count := Count;
if Result.Count > 0 then
Result.FirstLine := Strings[0];
finally
Free;
end;
end;
{ THelperWinControl }
constructor THelperWinControl.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Name := 'ClipboardChainHelperWindow';
// The clipboard chaining only works properly if this window is
// not parented by the the clip form. The desktop window may not
// be the best window to hook but it works.
ParentWindow := GetDesktopWindow;
Visible := False;
{$IFOPT D+} SendDebug('In THelperWinControl Create'); {$ENDIF}
FPrevWindow := SetClipBoardViewer(Self.Handle);
{$IFOPT D+} SendDebug('FPrevWindow = ' + IntToStr(FPrevWindow)); {$ENDIF}
end;
destructor THelperWinControl.Destroy;
begin
//{$IFOPT D+} SendDebug('In THelperWinControl Destroy'); {$ENDIF}
try
ChangeClipBoardChain(Self.Handle, FPrevWindow);
except
on E: Exception do
begin
{$IFOPT D+} SendDebugError('Clip Chain Destroy: ' + E.Message); {$ENDIF}
end;
end;
inherited Destroy;
end;
procedure THelperWinControl.WMChangeCBChain(var Msg: TMessage);
begin
{$IFOPT D+} SendDebug('In THelperWinControl WMChangeCBChain'); {$ENDIF}
if Msg.WParam = WPARAM(FPrevWindow) then
FPrevWindow := Msg.lParam
else if (FPrevWindow <> 0) then
SendMessage(FPrevWindow, WM_CHANGECBCHAIN, Msg.WParam, Msg.LParam);
//Msg.Result := 0; //??
end;
procedure THelperWinControl.WMDrawClipBoard(var Msg: TMessage);
begin
try
{$IFOPT D+} SendDebug('In THelperWinControl WMDrawClipBoard'); {$ENDIF}
if not Assigned(fmClipboardHistory) then
Exit;
fmClipboardHistory.WmDrawClipBoard;
finally
if FPrevWindow <> 0 then
SendMessage(FPrevWindow, WM_DRAWCLIPBOARD, Msg.WParam, Msg.LParam);
end;
end;
{ TfmClipboardHistory }
procedure TfmClipboardHistory.FormCreate(Sender: TObject);
begin
inherited;
PasteAsHandler.GetTypeText(cbPasteAsType.Items);
cbPasteAsType.DropDownCount := Integer(High(TPasteAsType)) + 1;
cbPasteAsType.ItemIndex := Integer(PasteAsHandler.PasteAsType);
chkCreateQuotedStrings.Checked := PasteAsHandler.CreateQuotedString;
chkAddExtraSpaceAtTheEnd.Checked := PasteAsHandler.AddExtraSpaceAtTheEnd;
end;
procedure TfmClipboardHistory.FormResize(Sender: TObject);
begin
mmoClipText.Height := Trunc(SplitterRatio * (mmoClipText.Height + lvClip.Height));
end;
procedure TfmClipboardHistory.SplitterMoved(Sender: TObject);
begin
SplitterRatio := mmoClipText.Height / (lvClip.Height + mmoClipText.Height);
FormResize(Self);
end;
procedure TfmClipboardHistory.ClearDataList;
var
i: Integer;
begin
if Assigned(FDataList) then
begin
for i := 0 to FDataList.Count - 1 do
ClipInfoFromPointer(FDataList.Items[i]).Free;
FDataList.Clear;
end;
lvClip.Items.Clear;
end;
procedure TfmClipboardHistory.Clear;
begin
ClearDataList;
mmoClipText.Lines.Clear;
end;
procedure TfmClipboardHistory.SaveSettings;
var
Settings: TGExpertsSettings;
begin
// Do not localize.
Settings := TGExpertsSettings.Create;
try
Settings.SaveForm(Self, ConfigurationKey);
Settings.WriteInteger(ConfigurationKey, 'SplitterRatio', Round(SplitterRatio * 100));
Settings.WriteBool(ConfigurationKey, 'ViewToolBar', ToolBar.Visible);
Settings.WriteBool(ConfigurationKey, 'PasteAsOptions', pnlPasteAsOptions.Visible);
finally
FreeAndNil(Settings);
end;
end;
procedure TfmClipboardHistory.LoadSettings;
var
Settings: TGExpertsSettings;
begin
// Do not localize.
Settings := TGExpertsSettings.Create;
try
Settings.LoadForm(Self, ConfigurationKey);
SplitterRatio := Settings.ReadInteger(ConfigurationKey, 'SplitterRatio', 50) / 100;
mmoClipText.Height := Trunc(SplitterRatio * (mmoClipText.Height + lvClip.Height));
ToolBar.Visible := Settings.ReadBool(ConfigurationKey, 'ViewToolBar', True);
pnlPasteAsOptions.Visible := Settings.ReadBool(ConfigurationKey, 'PasteAsOptions', True);
finally
FreeAndNil(Settings);
end;
EnsureFormVisible(Self);
end;
procedure TfmClipboardHistory.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caHide;
end;
procedure TfmClipboardHistory.lvClipDblClick(Sender: TObject);
begin
actEditCopy.Execute;
end;
procedure TfmClipboardHistory.LoadClips;
var
Doc: IXmlDocument;
Nodes: IXMLNodeList;
i: Integer;
TimeStr: string;
ClipStr: string;
Info: TClipInfo;
ClipItem: TListItem;
TimeNode: IXMLNode;
ClipData: TClipData;
begin
ClearDataList;
Doc := CreateXMLDoc;
if FileExists(ClipExpert.StorageFile) then begin
Doc.Load(ClipExpert.StorageFile);
if not Assigned(Doc.DocumentElement) then
Exit;
Nodes := Doc.DocumentElement.selectNodes('ClipItem');
lvClip.Items.BeginUpdate;
try
FLoading := True;
for i := 0 to Nodes.Length - 1 do
begin
if i >= ClipExpert.MaxClip then
Break;
TimeNode := Nodes.Item[i].Attributes.GetNamedItem('DateTime');
if Assigned(TimeNode) then
TimeStr := TimeNode.NodeValue
else
TimeStr := TimeToStr(Time);
ClipStr := GX_XmlUtils.GetCDataSectionTextOrNodeText(Nodes.Item[i]);
Info := TClipInfo.Create;
FDataList.Add(Info);
Info.ClipString := ClipStr;
Info.ClipTimeStamp := TimeStr;
ClipItem := lvClip.Items.Add;
ClipItem.Caption := Info.ClipTimeStamp;
ClipData := FirstLineOfText(ClipStr);
ClipItem.SubItems.Add(IntToStr(ClipData.Count));
ClipItem.SubItems.Add(Trim(ClipData.FirstLine));
ClipItem.Data := Info;
end;
finally
lvClip.Items.EndUpdate;
FLoading := False;
end;
if lvClip.Items.Count > 0 then
begin
lvClip.Selected := lvClip.Items[0];
lvClip.ItemFocused := lvClip.Selected;
end;
end;
end;
procedure TfmClipboardHistory.SaveClips;
var
Doc: IXmlDocument;
Root: IXMLElement;
i: Integer;
ClipItem: IXMLElement;
ClipText: IXMLCDATASection;
begin
// We are calling SaveClips from the destructor where
// we may be in a forced clean-up due to an exception.
if ExceptObject <> nil then
Exit;
Doc := CreateXMLDoc;
AddXMLHeader(Doc);
Root := Doc.CreateElement('Clips');
Doc.AppendChild(Root);
for i := 0 to FDataList.Count - 1 do
begin
ClipItem := Doc.CreateElement('ClipItem');
ClipItem.SetAttribute('DateTime', ClipInfoFromPointer(FDataList[i]).ClipTimeStamp);
ClipText := Doc.CreateCDATASection(EscapeCDataText(ClipInfoFromPointer(FDataList[i]).ClipString));
ClipItem.AppendChild(ClipText);
Root.AppendChild(ClipItem);
end;
if PrepareDirectoryForWriting(ExtractFileDir(ClipExpert.StorageFile)) then
Doc.Save(ClipExpert.StorageFile, ofFlat);
end;
procedure TfmClipboardHistory.lvClipChange(Sender: TObject; Item: TListItem; Change: TItemChange);
begin
if FLoading or (csDestroying in ComponentState) then
Exit;
if lvClip.Selected <> nil then
mmoClipText.Lines.Text := GetSelectedItemsText
else
mmoClipText.Clear;
end;
constructor TfmClipboardHistory.Create(AOwner: TComponent);
resourcestring
SLoadingFailed = 'Loading of stored clipboard clips failed.' + sLineBreak;
begin
inherited;
SetToolbarGradient(ToolBar);
{$IFOPT D+} SendDebug('Creating clipboard history data list'); {$ENDIF}
FDataList := TList.Create;
SplitterRatio := 0.50;
LoadSettings;
CenterForm(Self);
IgnoreClip := False;
// With large fonts, the TMenuToolBar ends up below the ToolBar, this fixes it
ToolBar.Align := alNone;
ToolBar.Top := 200;
ToolBar.Align := alTop;
pnlPasteAsOptions.Top := ToolBar.Top + ToolBar.Height;
HookClipboard;
// Now load any saved clips from our XML storage.
// Since we do not depend on these snippets, continue
// even in the presence of an exception.
try
LoadClips;
except
on E: Exception do
begin
GxLogAndShowException(E, SLoadingFailed);
// Swallow exceptions
end;
end;
end;
destructor TfmClipboardHistory.Destroy;
begin
SaveClips;
// Now free everything.
ClearDataList;
FreeAndNil(FDataList);
FreeAndNil(FHelperWindow);
SaveSettings;
inherited Destroy;
fmClipboardHistory := nil;
end;
procedure TfmClipboardHistory.AddClipItem(const AClipText: string);
var
Info: TClipInfo;
ClipItem: TListItem;
ClipData: TClipData;
begin
Info := TClipInfo.Create;
FDataList.Insert(0, Info);
Info.ClipString := AClipText;
Info.ClipTimeStamp := TimeToStr(Time);
ClipItem := lvClip.Items.Insert(0);
ClipItem.Caption := Info.ClipTimeStamp;
ClipData := FirstLineOfText(Info.ClipString);
ClipItem.SubItems.Add(IntToStr(ClipData.Count));
ClipItem.SubItems.Add(Trim(ClipData.FirstLine));
ClipItem.Data := Info;
end;
procedure TfmClipboardHistory.actEditCopyExecute(Sender: TObject);
var
idx: Integer;
Buffer: string;
AsPascalString: Boolean;
function GetCopyText(AText: String): String;
var
AList: TStringList;
ALine: String;
APasteAsHandler: TPasteAsHandler;
begin
Result := AText;
if AsPascalString then
begin
AList := TStringList.Create;
try
AList.Text := AText;
if AList.Count = 1 then
begin
ALine := AList[0];
ALine := AnsiReplaceText(ALine, '#$D#$A', #$D#$A);
ALine := AnsiReplaceText(ALine, '#13#10', #13#10);
AList.Text := ALine;
end;
if actViewPasteAsOptions.Checked then
begin
APasteAsHandler := TPasteAsHandler.Create;
try
APasteAsHandler.PasteAsType := TPasteAsType(cbPasteAsType.ItemIndex);
APasteAsHandler.CreateQuotedString := chkCreateQuotedStrings.Checked;
APasteAsHandler.AddExtraSpaceAtTheEnd := chkAddExtraSpaceAtTheEnd.Checked;
APasteAsHandler.ExtractRawStrings(AList, False);
Result := AList.Text;
finally
APasteAsHandler.Free;
end;
end
else begin
PasteAsHandler.ExtractRawStrings(AList, False);
Result := AList.Text;
end;
finally
AList.Free;
end;
end;
end;
begin
try
AsPascalString := Sender = actEditCopyFromPascalString;
if mmoClipText.SelLength = 0 then
begin
if lvClip.SelCount = 1 then
begin
IgnoreClip := True;
try
idx := lvClip.Selected.Index;
Buffer := GetCopyText(mmoClipText.Text);
Clipboard.AsText := Buffer;
lvClip.Items.Delete(idx);
ClipInfoFromPointer(FDataList[idx]).Free;
FDataList.Delete(idx);
AddClipItem(Buffer);
lvClip.Selected := lvClip.Items[0];
lvClip.ItemFocused := lvClip.Selected;
finally
IgnoreClip := False;
end;
end
else
Clipboard.AsText := GetCopyText(GetSelectedItemsText);
end
else
// mmoClipText.CopyToClipBoard;
Clipboard.AsText := GetCopyText(mmoClipText.Text);
if ClipExpert.FAutoClose then
Self.Close;
finally
Application.ProcessMessages;
end;
end;
procedure TfmClipboardHistory.actEditClearExecute(Sender: TObject);
resourcestring
SConfirmClearClipHistory = 'Clear the clipboard history?';
begin
if MessageDlg(SConfirmClearClipHistory, mtConfirmation, [mbOK, mbCancel], 0) = mrOk then
Self.Clear;
end;
procedure TfmClipboardHistory.actFileExitExecute(Sender: TObject);
begin
Self.Hide;
end;
procedure TfmClipboardHistory.actHelpHelpExecute(Sender: TObject);
begin
GxContextHelp(Self, 13);
end;
procedure TfmClipboardHistory.actHelpContentsExecute(Sender: TObject);
begin
GxContextHelpContents(Self);
end;
procedure TfmClipboardHistory.actHelpAboutExecute(Sender: TObject);
begin
ShowGXAboutForm;
end;
procedure TfmClipboardHistory.lvClipKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key = #13 then
actEditCopy.Execute;
end;
procedure TfmClipboardHistory.actEditPasteToIdeExecute(Sender: TObject);
begin
if mmoClipText.SelLength = 0 then
GxOtaInsertTextIntoEditor(mmoClipText.Text)
else
GxOtaInsertTextIntoEditor(mmoClipText.SelText);
end;
procedure TfmClipboardHistory.ActionsUpdate(Action: TBasicAction; var Handled: Boolean);
begin
actEditCopy.Enabled := (mmoClipText.SelLength > 0) or HaveSelectedItem;
actEditPasteToIde.Enabled := actEditCopy.Enabled;
actDelete.Enabled := HaveSelectedItem;
actViewToolBar.Checked := ToolBar.Visible;
actViewPasteAsOptions.Checked := pnlPasteAsOptions.Visible;
end;
procedure TfmClipboardHistory.actViewToolBarExecute(Sender: TObject);
begin
ToolBar.Visible := not ToolBar.Visible;
end;
procedure TfmClipboardHistory.actViewOptionsExecute(Sender: TObject);
begin
ClipExpert.Configure;
end;
procedure TfmClipboardHistory.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
begin
Key := 0;
Close;
end;
end;
function TfmClipboardHistory.ConfigurationKey: string;
begin
Result := TClipExpert.ConfigurationKey + PathDelim + 'Window';
end;
procedure TfmClipboardHistory.HookClipboard;
begin
FreeAndNil(FHelperWindow);
{$IFOPT D+} SendDebug('Creating clipboard history THelperWinControl'); {$ENDIF}
// The helper window is parented by the Desktop Window and
// it chains the clipboard for us.
FHelperWindow := THelperWinControl.Create(nil);
{$IFOPT D+} SendDebug('Clipboard history helper window created'); {$ENDIF}
end;
procedure TfmClipboardHistory.actRehookClipboardExecute(Sender: TObject);
begin
IgnoreClip := True;
try
HookClipboard;
finally
IgnoreClip := False;
end;
end;
function TfmClipboardHistory.ClipInfoForItem(Item: TListItem): TClipInfo;
begin
Assert(Assigned(Item));
Assert(Assigned(Item.Data));
Result := ClipInfoFromPointer(Item.Data);
end;
function TfmClipboardHistory.ClipInfoFromPointer(Ptr: Pointer): TClipInfo;
begin
Assert(Assigned(Ptr));
Result := TObject(Ptr) as TClipInfo;
end;
function TfmClipboardHistory.HaveSelectedItem: Boolean;
begin
Result := Assigned(lvClip.Selected);
end;
procedure TfmClipboardHistory.RemoveDataListItem(Index: Integer);
var
ClipInfo: TClipInfo;
begin
Assert(Assigned(FDataList));
Assert(Index < FDataList.Count);
ClipInfo := ClipInfoFromPointer(FDataList.Items[Index]);
FreeAndNil(ClipInfo);
FDataList.Delete(Index);
end;
procedure TfmClipboardHistory.actDeleteExecute(Sender: TObject);
var
i: Integer;
begin
if not HaveSelectedItem then
Exit;
for i := lvClip.Items.Count - 1 downto 0 do
begin
if lvClip.Items[i].Selected then
begin
lvClip.Items.Delete(i);
RemoveDataListItem(i);
end;
end;
mmoClipText.Clear;
end;
function TfmClipboardHistory.GetSelectedItemsText: string;
var
i: Integer;
ClipItem: TListItem;
begin
Result := '';
for i := lvClip.Items.Count - 1 downto 0 do
begin
ClipItem := lvClip.Items[i];
if ClipItem.Selected then
begin
if NotEmpty(Result) and (not HasTrailingEOL(Result)) then
Result := Result + sLineBreak;
Result := Result + ClipInfoForItem(ClipItem).ClipString;
end;
end;
end;
procedure TfmClipboardHistory.actViewPasteAsOptionsExecute(Sender: TObject);
begin
pnlPasteAsOptions.Visible := not pnlPasteAsOptions.Visible;
if pnlPasteAsOptions.Visible then
pnlPasteAsOptions.Top := ToolBar.Top + ToolBar.Height;
end;
procedure TfmClipboardHistory.actEditPasteAsPascalStringExecute(Sender: TObject);
var
AFromList: TStringList;
APasteAsHandler: TPasteAsHandler;
IsReplace: Boolean;
begin
IsReplace := Sender = actEditReplaceAsPascalString;
AFromList := TStringList.Create;
try
if mmoClipText.SelLength = 0 then
AFromList.Text := mmoClipText.Text
else
AFromList.Text := mmoClipText.SelText;
if actViewPasteAsOptions.Checked then
begin
APasteAsHandler := TPasteAsHandler.Create;
try
APasteAsHandler.PasteAsType := TPasteAsType(cbPasteAsType.ItemIndex);
APasteAsHandler.CreateQuotedString := chkCreateQuotedStrings.Checked;
APasteAsHandler.AddExtraSpaceAtTheEnd := chkAddExtraSpaceAtTheEnd.Checked;
if IsReplace then
APasteAsHandler.ExtractRawStrings(AFromList, True);
APasteAsHandler.ConvertToCode(AFromList, False)
finally
APasteAsHandler.Free;
end;
end
else
begin
if IsReplace then
PasteAsHandler.ExtractRawStrings(AFromList, True);
PasteAsHandler.ConvertToCode(AFromList, False);
end;
finally
AFromList.Free;
end;
end;
procedure TfmClipboardHistory.WmDrawClipBoard;
var
ItemCount: Integer;
ClipText: string;
Handle: Cardinal;
DataSize: Cardinal;
begin
if IgnoreClip then
Exit;
try
if Clipboard.HasFormat(CF_TEXT) then
begin
Clipboard.Open;
try
Handle := Clipboard.GetAsHandle(CF_TEXT);
DataSize := GlobalSize(Handle); // This function might over-estimate by a few bytes
finally
Clipboard.Close;
end;
// Don't try to save clipboard items over 512 KB for speed reasons
if DataSize > ((1024 * 512) + 32) then
Exit;
ClipText := Clipboard.AsText;
if (FDataList.Count = 0) or
(TClipInfo(FDataList[0]).ClipString <> clipText) then begin
{$IFOPT D+} SendDebug('New clipboard text detected'); {$ENDIF}
mmoClipText.Text := ClipText;
AddClipItem(ClipText);
ItemCount := lvClip.Items.Count;
if ItemCount > ClipExpert.MaxClip then
begin
Dec(ItemCount);
lvClip.Items.Delete(ItemCount);
TClipInfo(FDataList[ItemCount]).Free;
FDataList.Delete(ItemCount);
end;
lvClip.Selected := nil;
lvClip.Selected := lvClip.Items[0]; //FI:W508 - assigning to TListView.Selected has side effects
lvClip.ItemFocused := lvClip.Selected;
TListView_Resize(lvClip);
end;
end;
except
on E: Exception do
begin
// Ignore exceptions
end;
end;
end;
{ TClipExpert }
constructor TClipExpert.Create;
begin
inherited Create;
FStoragePath := ConfigInfo.ConfigPath;
FMaxClip := 20;
FreeAndNil(ClipExpert);
ClipExpert := Self;
end;
destructor TClipExpert.Destroy;
begin
FreeAndNil(fmClipboardHistory);
ClipExpert := nil;
inherited Destroy;
end;
function TClipExpert.GetActionCaption: string;
resourcestring
SMenuCaption = 'Clipboard &History';
begin
Result := SMenuCaption;
end;
class function TClipExpert.GetName: string;
begin
Result := 'ClipboardHistory';
end;
procedure TClipExpert.Execute(Sender: TObject);
begin
// If the form doesn't exist, create it.
if fmClipboardHistory = nil then
begin
fmClipboardHistory := TfmClipboardHistory.Create(nil);
SetFormIcon(fmClipboardHistory);
end;
IdeDockManager.ShowForm(fmClipboardHistory);
fmClipboardHistory.lvClip.SetFocus;
end;
procedure TClipExpert.InternalLoadSettings(Settings: TExpertSettings);
begin
inherited InternalLoadSettings(Settings);
// Do not localize.
FMaxClip := Min(Settings.ReadInteger('Maximum', 20), 100);
FAutoStart := Settings.ReadBool('AutoStart', False);
FAutoClose := Settings.ReadBool('AutoClose', False);
// This procedure is only called once, so it is safe to
// register the form for docking here.
if Active then
IdeDockManager.RegisterDockableForm(TfmClipboardHistory, fmClipboardHistory, 'fmClipboardHistory');
if FAutoStart and (fmClipboardHistory = nil) then
fmClipboardHistory := TfmClipboardHistory.Create(nil);
end;
procedure TClipExpert.InternalSaveSettings(Settings: TExpertSettings);
begin
inherited InternalSaveSettings(Settings);
// Do not localize.
Settings.WriteInteger('Maximum', FMaxClip);
Settings.WriteBool('AutoStart', FAutoStart);
Settings.WriteBool('AutoClose', FAutoClose);
end;
procedure TClipExpert.Configure;
var
Dlg: TfmClipboardOptions;
begin
Dlg := TfmClipboardOptions.Create(nil);
try
Dlg.edtMaxClip.Text := IntToStr(FMaxClip);
Dlg.chkAutoStart.Checked := FAutoStart;
Dlg.chkAutoClose.Checked := FAutoClose;
if Dlg.ShowModal = mrOk then
begin
FAutoStart := Dlg.chkAutoStart.Checked;
FAutoClose := Dlg.chkAutoClose.Checked;
FMaxClip := Min(StrToIntDef(Dlg.edtMaxClip.Text, 20), 1000);
SaveSettings;
end;
finally
FreeAndNil(Dlg);
end;
end;
function TClipExpert.GetStorageFile: string;
begin
Result := FStoragePath + ClipStorageFileName;
end;
procedure TClipExpert.SetActive(New: Boolean);
begin
if New <> Active then
begin
inherited SetActive(New);
if New then //FI:W505
// Nothing to initialize here
else
FreeAndNil(fmClipboardHistory);
end;
end;
initialization
RegisterGX_Expert(TClipExpert);
end.
|
unit xLog;
interface
uses
SysUtils, Classes, xClasses;
type
TxLog = class(TComponent)
private
FFileName: TFileName;
FMutex: TxMutex;
FBeginStrWithTime: Boolean;
FTimeout: Cardinal;
FLogStack: TStringList;
procedure SetTimeout(const Value: Cardinal);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Add(const AStr: AnsiString): Integer;
procedure Loaded; override;
procedure AddToStack(const S: string);
function GetLogStack(html: Boolean): String;
published
property BeginStrWithTime: Boolean read FBeginStrWithTime write FBeginStrWithTime default True;
property FileName: TFileName read FFileName write FFileName;
property Timeout: Cardinal read FTimeout write SetTimeout default 1000;
end;
implementation
const
LogStackMax = 100;
//==============================================================================================
function TxLog.Add(const AStr: AnsiString): Integer;
var
F: TextFile;
S: AnsiString;
begin
Result := -1;
if FFileName = EmptyStr then Exit;
s := DateTimeToStr(Now) + ': ';
if FlogStack.Count > 0 then begin
if FLogStack.Strings[FlogStack.Count - 1] = AStr then begin
Result := 0; Exit;
end;
end;
if FMutex.Obtain <> twSuccess then Exit;
try
AssignFile(F, FFileName);
try
if FileExists(FFileName)
then Append(F)
else Rewrite(F);
try
if FlogStack.Count = 0 then begin
Writeln(F, #10#13);
if FBeginStrWithTime then Write(F, s);
Writeln(F,'Log Started -------------------------------');
end;
if FBeginStrWithTime then Write(F, s);
Writeln(F, AStr);
AddToStack(AStr);
Result := 0;
finally
CloseFile(F);
end;
except
raise;
end;
finally
FMutex.Release;
end;
end;
//==============================================================================================
constructor TxLog.Create(AOwner: TComponent);
begin
inherited;
FBeginStrWithTime := True;
FTimeout := 1000;
FMutex := TxMutex.Create(FTimeout);
FlogStack := TstringList.Create;
FLogStack.Capacity := LogStackMax;
end;
//==============================================================================================
destructor TxLog.Destroy;
begin
FMutex.Free;
FlogStack.Destroy;
inherited;
end;
//==============================================================================================
procedure TxLog.Loaded;
begin
inherited;
FMutex.Timeout := FTimeout;
end;
//==============================================================================================
function TxLog.GetLogStack(html: Boolean): String;
var i: Integer;
begin
if not html then begin
Result := FLogStack.Text; Exit;
end;
Result := '<UL>' + #10#13;
for i := 0 to FLogStack.Count - 1 do
Result := Result + '<LI>' + FLogStack.Strings[i] + #10#13;
Result := Result + '</UL>' + #10#13;
end;
//==============================================================================================
procedure TxLog.AddToStack(const S: string);
begin
if FLogStack.Count = LogStackMax then FlogStack.Delete(0);
FLogStack.Append(S);
end;
//==============================================================================================
procedure TxLog.SetTimeout(const Value: Cardinal);
begin
FTimeout := Value;
FMutex.Timeout := Value;
end;
end.
|
unit CambiarBd;
interface
uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls,
ExtCtrls, IniFiles, Dialogs, ImgList, ComCtrls,
Menus, pngimage;
const
ctIniFile = 'BDatos.ini';
ctSeccion = 'BDATOS';
ctError = 'Por favor, seleccione Base de Datos';
type
TCambiarBdDlg = class(TForm)
OKBtn: TButton;
CancelBtn: TButton;
Bevel1: TBevel;
Label1: TLabel;
ImageList1: TImageList;
PopupMenu1: TPopupMenu;
VerIconos1: TMenuItem;
VerLista1: TMenuItem;
Informe1: TMenuItem;
IconoChico1: TMenuItem;
Editor: TListView;
Image1: TImage;
procedure FormCreate(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure VerIconos1Click(Sender: TObject);
procedure VerLista1Click(Sender: TObject);
procedure Informe1Click(Sender: TObject);
procedure IconoChico1Click(Sender: TObject);
private
{ Private declarations }
FIni: TIniFile;
public
{ Public declarations }
end;
function CambiarBaseDeDatos: string;
var
CambiarBdDlg: TCambiarBdDlg;
implementation
{$R *.dfm}
function CambiarBaseDeDatos: string;
begin
Result := '';
With TCambiarBdDlg.Create( Application ) do
try
ShowModal;
if ModalResult = mrOK then
Result := Editor.Selected.SubItems.Strings[ 0 ];
finally
free;
end;
end;
procedure TCambiarBdDlg.FormCreate(Sender: TObject);
var
FLista: TStringList;
x: integer;
FItem: TListItem;
begin
FLista := TStringList.create;
FIni := TIniFile.Create( ExtractFilePath( Application.ExeName ) + '\Conf\' + ctIniFile );
// FIni.ReadSection( ctSeccion, FLista );
FIni.ReadSectionValues( ctSeccion, FLista );
for x:=0 to FLista.count-1 do
begin
FItem := Editor.Items.Add;
FItem.Caption := FLista.Values[ FLista.Names[ x ]];
FItem.SubItems.Add( FLista.Names[ x ]);
end;
end;
procedure TCambiarBdDlg.OKBtnClick(Sender: TObject);
begin
if Editor.Selected.Index < 0 then
begin
ModalResult := mrNone;
ShowMessage( ctError );
end;
end;
procedure TCambiarBdDlg.VerIconos1Click(Sender: TObject);
begin
Editor.ViewStyle := vsIcon;
end;
procedure TCambiarBdDlg.VerLista1Click(Sender: TObject);
begin
Editor.ViewStyle := vsList;
end;
procedure TCambiarBdDlg.Informe1Click(Sender: TObject);
begin
Editor.ViewStyle := vsReport;
end;
procedure TCambiarBdDlg.IconoChico1Click(Sender: TObject);
begin
Editor.ViewStyle := vsSmallIcon;
end;
end.
|
{*****************************************************}
{ }
{ EldoS Themes Support Library }
{ }
{ (C) 2002-2003 EldoS Corporation }
{ http://www.eldos.com/ }
{ }
{*****************************************************}
{$include elpack2.inc}
{$IFDEF ELPACK_SINGLECOMP}
{$I ElPack.inc}
{$ELSE}
{$IFDEF LINUX}
{$I ../ElPack.inc}
{$ELSE}
{$I ..\ElPack.inc}
{$ENDIF}
{$ENDIF}
unit ElThemesMain;
interface
{$IFDEF ELPACK_THEME_ENGINE}
uses
Windows;
const
CMaxIntListCount = 10;
CThemeSizeMin = 0;
CThemeSizeTrue = 1;
CThemeSizeDraw = 2;
CPropOriginState = 0;
CPropOriginPart = 1;
CPropOriginClass = 2;
CPropOriginGlobal = 3;
CPropOriginNotFound = 4;
type
TThemeHandle = THandle;
TThemeManagerHandle = THandle;
TThemeIntList = packed record
ValueCount: integer;
Values: array[0..CMaxIntListCount - 1] of integer;
end;
PThemeIntList = ^TThemeIntList;
TThemeMargins = packed record
LeftWidth: integer;
RightWidth: integer;
TopHeight: integer;
BottomHeight: integer;
end;
PThemeMargins = ^TThemeMargins;
TThemeSize = cardinal;
TSize = packed record
X: longint;
Y: longint;
end;
PSize = ^TSize;
TPropertyOrigin = cardinal;
// Standard Visual Styles API
// For description on each function see MSDN at http://msdn.microsoft.com/
function CloseThemeData(Theme: TThemeHandle): HResult; stdcall;
function DrawThemeBackground(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const Rect: TRect; ClipRect: PRect): HResult; stdcall;
function DrawThemeEdge(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const DestRect: TRect; Edge: cardinal; Flags: cardinal;
ContentRect: PRect): HResult; stdcall;
function DrawThemeIcon(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Rect: PRect; ImageList: THandle;
ImageIndex: integer): HResult; stdcall;
function DrawThemeParentBackground(Wnd: HWnd; DC: HDC; const Rect: TRect):
HResult; stdcall;
function DrawThemeText(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID:
integer;
Text: PWideChar; CharCount: integer; TextFlags: cardinal; TextFlags2:
cardinal;
var Rect: TRect): HResult; stdcall;
function EnableThemeDialogTexture(Wnd: HWnd; Flags: cardinal): HResult; stdcall;
function EnableTheming(Enable: boolean): HResult; stdcall;
function GetCurrentThemeName(ThemeFileName: PWideChar; MaxNameChars: integer;
ColorName: PWideChar; MaxColorChars: integer; FontSize: PWideChar;
MaxSizeChars: integer): HResult; stdcall;
function GetThemeAppProperties: cardinal; stdcall;
function GetThemeBackgroundContentRect(Theme: TThemeHandle; DC: HDC; PartID:
integer;
StateID: integer; const BoundingRect: TRect; var ContentRect: TRect): HResult;
stdcall;
function GetThemeBackgroundExtent(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const ContentRect: PRect; var ExtentRect: TRect): HResult;
stdcall;
function GetThemeBackgroundRegion(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Rect: PRect; var Region: HRgn): HResult; stdcall;
function GetThemeBool(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Value: BOOL): HResult; stdcall;
function GetThemeColor(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Color: ColorRef): HResult; stdcall;
function GetThemeDocumentationProperty(ThemeName: PWideChar;
PropertyName: PWideChar; Value: PWideChar; MaxValueChars: integer): HResult;
stdcall;
function GetThemeEnumValue(Theme: TThemeHandle; PartID: integer; StateID:
integer;
PropID: integer; var Value: integer): HResult; stdcall;
function GetThemeFilename(Theme: TThemeHandle; PartID: integer; StateID:
integer;
PropID: integer; ThemeFileName: PWideChar; MaxNameChars: integer): HResult;
stdcall;
function GetThemeFont(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID:
integer;
PropID: integer; var Font: TLogFontW): HResult; stdcall;
function GetThemeInt(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Value: integer): HResult; stdcall;
function GetThemeIntList(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; out List: TThemeIntList): HResult; stdcall;
function GetThemeMargins(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID:
integer;
PropID: integer; Rect: PRect; var Margins: TThemeMargins): HResult; stdcall;
function GetThemeMetric(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID:
integer;
PropID: integer; var Value: integer): HResult; stdcall;
function GetThemePartSize(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer;
Rect: PRect; SizeType: integer; var Size: Windows.TSize): HResult; stdcall;
function GetThemePosition(Theme: TThemeHandle; PartID: integer; StateID:
integer;
PropID: integer; var Point: TPoint): HResult; stdcall;
function GetThemePropertyOrigin(Theme: TThemeHandle; PartID: integer; StateID:
integer;
PropID: integer; out Origin: TPropertyOrigin): HResult; stdcall;
function GetThemeRect(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Rect: TRect): HResult; stdcall;
function GetThemeString(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; Buffer: PWideChar; MaxBufferChars: integer): HResult;
stdcall;
function GetThemeSysBool(Theme: TThemeHandle; BoolID: integer): BOOL; stdcall;
function GetThemeSysColor(Theme: TThemeHandle; ColorID: integer): ColorRef;
stdcall;
function GetThemeSysColorBrush(Theme: TThemeHandle; ColorID: integer): HBrush;
stdcall;
function GetThemeSysFont(Theme: TThemeHandle; FontID: integer;
var Font: TLogFontW): HResult; stdcall;
function GetThemeSysInt(Theme: TThemeHandle; IntID: integer;
var Value: integer): HResult; stdcall;
function GetThemeSysSize(Theme: TThemeHandle; SizeID: integer): integer;
stdcall;
function GetThemeSysString(Theme: TThemeHandle; StringID: integer; Value:
PWideChar;
MaxStringChars: integer): HResult; stdcall;
function GetThemeTextExtent(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Text: PWideChar; CharCount: integer; TextFlags: cardinal;
BoundingRect: PRect; var ExtentRect: TRect): HResult; stdcall;
function GetThemeTextMetrics(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; var Metrics: TTextMetricW): HResult; stdcall;
function GetWindowTheme(Wnd: HWnd): TThemeHandle; stdcall;
function HitTestThemeBackground(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Options: cardinal; Rect: PRect; Region: HRgn;
Test: TPoint; var HitTestCode: word): HResult; stdcall;
function IsAppThemed: boolean; stdcall;
function IsThemeActive: boolean; stdcall;
function IsThemeBackgroundPartiallyTransparent(Theme: TThemeHandle; PartID:
integer;
StateID: integer): boolean; stdcall;
function IsThemeDialogTextureEnabled: BOOL; stdcall;
function IsThemePartDefined(Theme: TThemeHandle; PartID: integer;
StateID: integer): boolean; stdcall;
function OpenThemeData(Wnd: HWnd; ClassList: PWideChar): TThemeHandle; stdcall;
procedure SetThemeAppProperties(Flags: cardinal); stdcall;
function SetWindowTheme(Wnd: HWnd; SubAppName: PWideChar;
SubIDList: PWideChar): HResult; stdcall;
// Advanced Visual Styles API
(*
Loads Microsoft(r) WindowsXP(r) Visual Style from [*.msstyles] file
and returns theme manager's handle if successfull or 0(NULL) otherwise.
The loaded theme manager must be released by calling UnloadTheme routine.
*)
function LoadTheme(const FileName: PWideChar): TThemeManagerHandle; stdcall;
(*
Unloads the given theme manager and returns S_OK if successfull or
E_FAIL otherwise. If the given theme manager is active at the moment,
it will be deactivated automatically.
*)
function UnloadTheme(ThemeManager: TThemeManagerHandle): HResult; stdcall;
(*
Sets the given theme manager as active and loads the given color scheme.
If color scheme is not specified, the routine loads a default color scheme
for this theme manager. The activated theme manager must be deactivated
by calling DeactivateTheme routine.
The function returns S_OK if succeeded and E_FAIL otherwise.
Note: if ActivateTheme is called while another theme manager is active,
the previous theme manager will be deactivated automatically (but not
unloaded!), so it's no need to call DeactivateTheme before calling
ActivateTheme, but it's still needed to call UnloadTheme for each
theme manager returned by LoadTheme functions.
*)
function ActivateTheme(ThemeManager: TThemeManagerHandle;
ColorScheme: PWideChar): HResult; stdcall;
(*
Deactivates currently active theme manager.
*)
procedure DeactivateTheme; stdcall;
(*
This function retrives display name for the given theme manager.
The function returns S_OK if succeeded or E_FAIL otherwise.
*)
function GetThemeDisplayName(ThemeManager: TThemeManagerHandle;
DisplayName: PWideChar; MaxNameChars: integer): HResult; stdcall;
(*
This function returns a list of all color schemes supported by
the given theme manager. Color schemes' names in the list are
separated by zero-char. The list is terminated by two zero-chars.
The function returns S_OK if succeeded or E_FAIL otherwise.
*)
function EnumThemeColorSchemes(ThemeManager: TThemeManagerHandle;
Schemes: PWideChar; MaxSchemesChars: integer): HResult; stdcall;
(*
This function returns display name for the given theme manager
and color scheme.
The function returns S_OK if succeeded or E_FAIL otherwise.
*)
function GetThemeColorSchemeDisplayName(ThemeManager: TThemeManagerHandle;
SchemeName: PWideChar; DisplayName: PWideChar;
MaxNameChars: integer): HResult; stdcall;
(*
This function returns the handle of currently active theme manager
or 0(NULL) if there is no active theme manager.
*)
function GetCurrentTheme: TThemeManagerHandle; stdcall;
{$ENDIF}
implementation
{$IFDEF ELPACK_THEME_ENGINE}
uses
ElStrUtils,
ElThemesGeneral,
ElThemesWindowsXP,
ElThemeSysColorHook;
{var
CurrentTheme: TThemeManager = nil;}
// Standard Visual Styles API
function CloseThemeData(Theme: TThemeHandle): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
if Theme = 0 then
Result := E_FAIL
else
try
if IsValidTheme(Theme) then
begin
if (CurrentTheme = nil) or (TTheme(Theme).Manager <> CurrentTheme) then
TTheme(Theme).Free
else
CurrentTheme.CloseThemeData(Theme);
Result := S_OK;
end
else
Result := E_FAIL;
except
Result := E_FAIL;
end;
end;
function DrawThemeBackground(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const Rect: TRect; ClipRect: PRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.DrawThemeBackground(Theme, DC, PartID, StateID, Rect, ClipRect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function DrawThemeEdge(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const DestRect: TRect; Edge: cardinal; Flags: cardinal;
ContentRect: PRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.DrawThemeEdge(Theme, DC, PartID, StateID, DestRect, Edge,
Flags, ContentRect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function DrawThemeIcon(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Rect: PRect; ImageList: THandle;
ImageIndex: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.DrawThemeIcon(Theme, DC, PartID, StateID, Rect^, ImageList,
ImageIndex);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function DrawThemeParentBackground(Wnd: HWnd; DC: HDC; const Rect: TRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.DrawThemeParentBackground(Wnd, DC, @Rect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function DrawThemeText(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID: integer;
Text: PWideChar; CharCount: integer; TextFlags: cardinal; TextFlags2: cardinal;
var Rect: TRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.DrawThemeText(Theme, DC, PartID, StateID, Text, CharCount,
TextFlags, TextFlags2, Rect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function EnableThemeDialogTexture(Wnd: HWnd; Flags: cardinal): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.EnableThemeDialogTexture(Wnd, Flags);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function EnableTheming(Enable: boolean): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.EnableTheming(Enable);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetCurrentThemeName(ThemeFileName: PWideChar; MaxNameChars: integer;
ColorName: PWideChar; MaxColorChars: integer; FontSize: PWideChar;
MaxSizeChars: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetCurrentThemeName(ThemeFileName, MaxNameChars, ColorName,
MaxColorChars, FontSize, MaxSizeChars);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeAppProperties: cardinal;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := 0
else
try
Result := CurrentTheme.GetThemeAppProperties;
except
Result := 0;
end;
end;
function GetThemeBackgroundContentRect(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const BoundingRect: TRect; var ContentRect: TRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeBackgroundContentRect(Theme, DC, PartID, StateID,
BoundingRect, ContentRect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeBackgroundExtent(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; const ContentRect: PRect; var ExtentRect: TRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeBackgroundExtent(Theme, DC, PartID, StateID,
ContentRect^, ExtentRect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeBackgroundRegion(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Rect: PRect; var Region: HRgn): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeBackgroundRegion(Theme, DC, PartID, StateID, Rect^,
Region);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeBool(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Value: BOOL): HResult;
var
V: boolean;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
V := Value;
CurrentTheme.GetThemeBool(Theme, PartID, StateID, PropID, V);
Value := V;
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeColor(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Color: ColorRef): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeColor(Theme, PartID, StateID, PropID, Color);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeDocumentationProperty(ThemeName: PWideChar;
PropertyName: PWideChar; Value: PWideChar; MaxValueChars: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeDocumentationProperty(ThemeName, PropertyName, Value,
MaxValueChars);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeEnumValue(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Value: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeEnumValue(Theme, PartID, StateID, PropID, Value);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeFilename(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; ThemeFileName: PWideChar; MaxNameChars: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeFilename(Theme, PartID, StateID, PropID, ThemeFileName,
MaxNameChars);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeFont(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID: integer;
PropID: integer; var Font: LogFontW): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeFont(Theme, DC, PartID, StateID, PropID, Font);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeInt(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Value: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeInt(Theme, PartID, StateID, PropID, Value);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeIntList(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; out List: TThemeIntList): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeIntList(Theme, PartID, StateID, PropID, List);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeMargins(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID: integer;
PropID: integer; Rect: PRect; var Margins: TThemeMargins): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeMargins(Theme, DC, PartID, StateID, PropID, Rect,
Margins);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeMetric(Theme: TThemeHandle; DC: HDC; PartID: integer; StateID: integer;
PropID: integer; var Value: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeMetric(Theme, DC, PartID, StateID, PropID, Value);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemePartSize(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer;
Rect: PRect; SizeType: integer; var Size: Windows.TSize): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemePartSize(Theme, DC, PartID, StateID, Rect, SizeType,
TSize(Size));
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemePosition(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Point: TPoint): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemePosition(Theme, PartID, StateID, PropID, Point);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemePropertyOrigin(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; out Origin: TPropertyOrigin): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemePropertyOrigin(Theme, PartID, StateID, PropID, Origin);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeRect(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; var Rect: TRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeRect(Theme, PartID, StateID, PropID, Rect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeString(Theme: TThemeHandle; PartID: integer; StateID: integer;
PropID: integer; Buffer: PWideChar; MaxBufferChars: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeString(Theme, PartID, StateID, PropID, Buffer,
MaxBufferChars);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeSysBool(Theme: TThemeHandle; BoolID: integer): BOOL;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := False
else
try
Result := CurrentTheme.GetThemeSysBool(Theme, BoolID);
except
Result := False;
end;
end;
function GetThemeSysColor(Theme: TThemeHandle; ColorID: integer): ColorRef;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := $FFFFFFFF
else
try
Result := CurrentTheme.GetThemeSysColor(Theme, ColorID);
except
Result := $FFFFFFFF;
end;
end;
function GetThemeSysColorBrush(Theme: TThemeHandle; ColorID: integer): HBrush;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := 0
else
try
Result := CurrentTheme.GetThemeSysColorBrush(Theme, ColorID);
except
Result := 0;
end;
end;
function GetThemeSysFont(Theme: TThemeHandle; FontID: integer;
var Font: LogFontW): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeSysFont(Theme, FontID, Font);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeSysInt(Theme: TThemeHandle; IntID: integer;
var Value: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeSysInt(Theme, IntID, Value);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeSysSize(Theme: TThemeHandle; SizeID: integer): integer;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
Result := CurrentTheme.GetThemeSysSize(Theme, SizeID);
except
Result := 0;
end;
end;
function GetThemeSysString(Theme: TThemeHandle; StringID: integer;
Value: PWideChar; MaxStringChars: integer): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeSysString(Theme, StringID, Value, MaxStringChars);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeTextExtent(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Text: PWideChar; CharCount: integer; TextFlags: cardinal;
BoundingRect: PRect; var ExtentRect: TRect): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeTextExtent(Theme, DC, PartID, StateID, Text, CharCount,
TextFlags, BoundingRect, ExtentRect);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetThemeTextMetrics(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; var Metrics: TTextMetricW): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.GetThemeTextMetrics(Theme, DC, PartID, StateID, Metrics);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function GetWindowTheme(Wnd: HWnd): TThemeHandle;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := 0
else
try
Result := CurrentTheme.GetWindowTheme(Wnd);
except
Result := 0;
end;
end;
function HitTestThemeBackground(Theme: TThemeHandle; DC: HDC; PartID: integer;
StateID: integer; Options: cardinal; Rect: PRect; Region: HRgn;
Test: TPoint; var HitTestCode: word): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.HitTestThemeBackground(Theme, DC, PartID, StateID, Options,
Rect^, Region, Test, HitTestCode);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function IsAppThemed: boolean;
begin
Result := True;
end;
function IsThemeActive: boolean;
begin
//Result := (CurrentTheme <> nil);
Result := (GetGlobalCurrentTheme <> 0);
end;
function IsThemeBackgroundPartiallyTransparent(Theme: TThemeHandle; PartID: integer;
StateID: integer): boolean;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := False
else
try
Result := CurrentTheme.IsThemeBackgroundPartiallyTransparent(Theme, PartID,
StateID);
except
Result := False;
end;
end;
function IsThemeDialogTextureEnabled: BOOL;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := False
else
try
Result := CurrentTheme.IsThemeDialogTextureEnabled;
except
Result := False;
end;
end;
function IsThemePartDefined(Theme: TThemeHandle; PartID: integer;
StateID: integer): boolean;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := False
else
try
Result := CurrentTheme.IsThemePartDefined(Theme, PartID, StateID);
except
Result := False;
end;
end;
function OpenThemeData(Wnd: HWnd; ClassList: PWideChar): TThemeHandle;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := 0
else
try
Result := CurrentTheme.OpenThemeData(Wnd, ClassList);
except
Result := 0;
end;
end;
procedure SetThemeAppProperties(Flags: cardinal);
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme <> nil then
try
CurrentTheme.SetThemeAppProperties(Flags);
except
end;
end;
function SetWindowTheme(Wnd: HWnd; SubAppName: PWideChar; SubIDList: PWideChar): HResult;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := E_FAIL
else
try
CurrentTheme.SetWindowTheme(Wnd, SubAppName, SubIDList);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
// Advanced Visual Styles API
function LoadTheme(const FileName: PWideChar): TThemeManagerHandle;
var
Manager: TWindowsXPThemeManager;
begin
try
Manager := TWindowsXPThemeManager.Create;
try
Manager.Open(FileName);
Result := TThemeManagerHandle(Manager);
except
Manager.Free;
Result := 0;
end;
except
Result := 0;
end;
end;
function UnloadTheme(ThemeManager: TThemeManagerHandle): HResult;
var
Manager: TThemeManager;
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
try
Manager := TThemeManager(ThemeManager);
if Manager = CurrentTheme then
DeactivateTheme;
Manager.Free;
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function ActivateTheme(ThemeManager: TThemeManagerHandle; ColorScheme:
PWideChar): HResult;
var
Manager, OldManager: TThemeManager;
Scheme: WideString;
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
try
if ColorScheme = nil then
Scheme := ''
else
Scheme := ColorScheme;
Manager := TThemeManager(ThemeManager);
if CurrentTheme <> nil then
begin
if Manager = CurrentTheme then
begin
Manager.ChangeColorScheme(Scheme);
end
else
begin
OldManager := CurrentTheme;
Manager.Activate(Scheme);
SetGlobalCurrentTheme(THandle(Manager));
//CurrentTheme := Manager;
OldManager.Deactivate;
end;
end
else
begin
Manager.Activate(Scheme);
SetGlobalCurrentTheme(THandle(Manager));
//CurrentTheme := Manager;
end;
Result := S_OK;
except
Result := E_FAIL;
end;
end;
procedure DeactivateTheme;
var
OldManager: TThemeManager;
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
try
if CurrentTheme <> nil then
begin
OldManager := CurrentTheme;
SetGlobalCurrentTheme(0);
//CurrentTheme := nil;
OldManager.Deactivate;
end;
except
end;
end;
function GetThemeDisplayName(ThemeManager: TThemeManagerHandle;
DisplayName: PWideChar; MaxNameChars: integer): HResult;
var
Manager: TThemeManager;
Name: WideString;
begin
if DisplayName = nil then
Result := E_FAIL
else
try
Manager := TThemeManager(ThemeManager);
Name := Manager.DisplayName;
WideStrLCopy(DisplayName, PWideChar(Name), MaxNameChars);
Result := S_OK;
except
Result := E_FAIL;
end;
end;
function EnumThemeColorSchemes(ThemeManager: TThemeManagerHandle;
Schemes: PWideChar; MaxSchemesChars: integer): HResult;
var
Manager: TThemeManager;
Names: WideString;
I: integer;
begin
if Schemes = nil then
Result := E_FAIL
else
try
Manager := TThemeManager(ThemeManager);
Names := '';
if Manager.ColorSchemeCount > 0 then
begin
for I := 0 to Manager.ColorSchemeCount - 1 do
Names := Names + Manager.ColorSchemes[I] + WideChar(#0);
end;
Names := Names + WideChar(#0);
if Length(Names) <= MaxSchemesChars then
begin
Move(Names[1], Schemes^, Length(Names) * 2);
Result := S_OK;
end
else
Result := E_FAIL;
except
Result := E_FAIL;
end;
end;
function GetThemeColorSchemeDisplayName(ThemeManager: TThemeManagerHandle;
SchemeName: PWideChar; DisplayName: PWideChar;
MaxNameChars: integer): HResult;
var
Manager: TThemeManager;
Name: WideString;
begin
if (SchemeName = nil) or (DisplayName = nil) then
Result := E_FAIL
else
try
Manager := TThemeManager(ThemeManager);
Name := Manager.GetColorSchemeDisplayName(SchemeName);
if Length(Name) = 0 then
Result := E_FAIL
else
begin
WideStrLCopy(DisplayName, PWideChar(Name), MaxNameChars);
Result := S_OK;
end;
except
Result := E_FAIL;
end;
end;
function GetCurrentTheme: TThemeManagerHandle;
var
CurrentTheme: TThemeManager;
begin
CurrentTheme := TThemeManager(GetGlobalCurrentTheme);
if CurrentTheme = nil then
Result := 0
else
Result := TThemeManagerHandle(CurrentTheme);
end;
{$ENDIF}
end.
|
program piValue;
(* Computes pi from series pi / 4 = 1/1 - 1/3 + 1/5 - 1/7 + 1/9 + ... *)
const
TINY = 0.00000002;
var
n : integer;
pi, term : real;
begin
writeln('Computation of pi:');
writeln();
pi := 0.0;
n := 1;
repeat
term := 4/n - 4/(n + 2);
pi := pi + term;
n := n + 4;
until term < TINY;
writeln('After ', n div 4 : 7, ' cycles,');
writeln('Pi: ', pi:12:7);
end. |
{******************************************************************************}
{ }
{ Delphi FB4D Library }
{ Copyright (c) 2018-2022 Christoph Schneider }
{ Schneider Infosystems AG, Switzerland }
{ https://github.com/SchneiderInfosystems/FB4D }
{ }
{******************************************************************************}
{ }
{ 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 RealTimeDB;
interface
uses
System.Classes, System.SysUtils, System.JSON,
DUnitX.TestFramework,
FB4D.Interfaces;
{$M+}
type
[TestFixture]
UT_RealTimeDB = class(TObject)
private
fConfig: IFirebaseConfiguration;
fErrMsg: string;
fReqID: string;
fInfo: string;
fData: TJSONObject;
fCallBack: boolean;
fRes: TJSONValue;
fFirebaseEvent: IFirebaseEvent;
procedure OnPutGet(ResourceParams: TRequestResourceParam; Val: TJSONValue);
procedure OnError(const RequestID, ErrMsg: string);
procedure OnReceive(const Event: string; Params: TRequestResourceParam; JSONObj: TJSONObject);
procedure OnStop(Sender: TObject);
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
published
[TestCase]
procedure PutGetSynchronous;
procedure PutGet;
procedure GetResourceParamListener;
end;
implementation
uses
VCL.Forms,
FB4D.Configuration,
Consts;
{$I FBConfig.inc}
const
cDBPath: TRequestResourceParam = ['TestNode', '1234'];
{ UT_RealTimeDB }
procedure UT_RealTimeDB.Setup;
begin
fConfig := TFirebaseConfiguration.Create(cApiKey, cProjectID, cBucket);
fConfig.Auth.SignUpWithEmailAndPasswordSynchronous(cEmail, cPassword);
fErrMsg := '';
fReqID := '';
fInfo := '';
fData := TJSONObject.Create;
fCallBack := false;
end;
procedure UT_RealTimeDB.TearDown;
begin
if Assigned(fFirebaseEvent) and (not fFirebaseEvent.IsStopped) then
fFirebaseEvent.StopListening;
fConfig.RealTimeDB.DeleteSynchronous(cDBPath);
fData.Free;
fConfig.Auth.DeleteCurrentUserSynchronous;
fConfig := nil;
end;
procedure UT_RealTimeDB.GetResourceParamListener;
var
Res: TJSONValue;
DBPath: string;
ResourcePath: string;
begin
Status('Put single value');
fData.AddPair('Item1', 'TestVal1');
Res := fConfig.RealTimeDB.PutSynchronous(cDBPath, fData);
Assert.IsNotNull(res, 'Result of Put is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON,
'result JSON is different from put');
Res.Free;
Status('Listen value');
fFirebaseEvent := fConfig.RealTimeDB.ListenForValueEvents(cDBPath,
OnReceive, OnStop, OnError);
sleep(1); //give time to the thread create fAsyncResult object
Assert.IsNotNull(fFirebaseEvent.GetResourceParams);
ResourcePath := string.Join('/', fFirebaseEvent.GetResourceParams);
DbPath := string.Join('/', cDBPath);
Assert.AreEqual(DBPath, ResourcePath,
'ResourceParams is different from the listened');
end;
procedure UT_RealTimeDB.OnReceive(const Event: string; Params:
TRequestResourceParam; JSONObj: TJSONObject);
begin
fCallBack := true;
end;
procedure UT_RealTimeDB.OnStop(Sender: TObject);
begin
end;
procedure UT_RealTimeDB.OnError(const RequestID, ErrMsg: string);
begin
fReqID := RequestID;
fErrMsg := ErrMsg;
fCallBack := true;
end;
procedure UT_RealTimeDB.OnPutGet(ResourceParams: TRequestResourceParam;
Val: TJSONValue);
begin
fRes := Val.Clone as TJSONValue;
fCallBack := true;
end;
procedure UT_RealTimeDB.PutGetSynchronous;
var
Res: TJSONValue;
begin
Status('Put single value');
fData.AddPair('Item1', 'TestVal1');
Res := fConfig.RealTimeDB.PutSynchronous(cDBPath, fData);
Assert.IsNotNull(res, 'Result of Put is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON, 'result JSON is different from put');
Res.Free;
Status('Get single value');
Res := fConfig.RealTimeDB.GetSynchronous(cDBPath);
Assert.IsNotNull(res, 'Result of Get is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON,
'result JSON is different between get and put');
Res.Free;
Status('Put simple object value');
fData.AddPair('Item2', TJSONNumber.Create(3.14));
Res := fConfig.RealTimeDB.PutSynchronous(cDBPath, fData);
Assert.IsNotNull(res, 'Result is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON, 'resul JSON is different from put');
Res.Free;
Status('Get single object value');
Res := fConfig.RealTimeDB.GetSynchronous(cDBPath);
Assert.IsNotNull(res, 'Result of Get is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON,
'result JSON is different between get and put');
Res.Free;
Status('Put complex object value');
fData.AddPair('Item3', TJSONObject.Create(TJSONPair.Create('SubItem',
'TestSubItem')));
Res := fConfig.RealTimeDB.PutSynchronous(cDBPath, fData);
Assert.IsNotNull(res, 'Result is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON, 'result JSON is different from put');
Res.Free;
Status('Get complex object value');
Res := fConfig.RealTimeDB.GetSynchronous(cDBPath);
Assert.IsNotNull(res, 'Result of Get is nil');
Assert.AreEqual(fData.ToJSON, Res.ToJSON,
'result JSON is different between get and put');
Res.Free;
end;
procedure UT_RealTimeDB.PutGet;
begin
Status('Put single value');
fData.AddPair('Item1', 'TestVal1');
fConfig.RealTimeDB.Put(cDBPath, fData, OnPutGet, OnError);
while not fCallBack do
Application.ProcessMessages;
Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg);
Assert.IsNotNull(fRes, 'Result of Put is nil');
Assert.AreEqual(fData.ToJSON, fRes.ToJSON, 'result JSON is different from put');
FreeAndNil(fRes);
Status('Get single value');
fCallBack := false;
fConfig.RealTimeDB.Get(cDBPath, OnPutGet, OnError);
while not fCallBack do
Application.ProcessMessages;
Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg);
Assert.IsNotNull(fRes, 'Result of Get is nil');
Assert.AreEqual(fData.ToJSON, fRes.ToJSON,
'result JSON is different between get and put');
FreeAndNil(fRes);
Status('Put simple object value');
fData.AddPair('Item2', TJSONNumber.Create(3.14));
fCallBack := false;
fConfig.RealTimeDB.Put(cDBPath, fData, OnPutGet, OnError);
while not fCallBack do
Application.ProcessMessages;
Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg);
Assert.IsNotNull(fRes, 'Result of Put is nil');
Assert.AreEqual(fData.ToJSON, fRes.ToJSON, 'resul JSON is different from put');
FreeAndNil(fRes);
Status('Get single object value');
fCallBack := false;
fConfig.RealTimeDB.Get(cDBPath, OnPutGet, OnError);
while not fCallBack do
Application.ProcessMessages;
Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg);
Assert.IsNotNull(fRes, 'Result of Get is nil');
Assert.AreEqual(fData.ToJSON, fRes.ToJSON,
'result JSON is different between get and put');
FreeAndNil(fRes);
Status('Put complex object value');
fData.AddPair('Item3', TJSONObject.Create(TJSONPair.Create('SubItem',
'TestSubItem')));
fCallBack := false;
fConfig.RealTimeDB.Put(cDBPath, fData, OnPutGet, OnError);
while not fCallBack do
Application.ProcessMessages;
Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg);
Assert.IsNotNull(fRes, 'Result is nil');
Assert.AreEqual(fData.ToJSON, fRes.ToJSON,
'result JSON is different from put');
FreeAndNil(fRes);
Status('Get complex object value');
fCallBack := false;
fConfig.RealTimeDB.Get(cDBPath, OnPutGet, OnError);
while not fCallBack do
Application.ProcessMessages;
Assert.IsEmpty(fErrMsg, 'Error: ' + fErrMsg);
Assert.IsNotNull(fRes, 'Result of Get is nil');
Assert.AreEqual(fData.ToJSON, fRes.ToJSON,
'result JSON is different between get and put');
FreeAndNil(fRes);
end;
initialization
TDUnitX.RegisterTestFixture(UT_RealTimeDB);
end.
|
unit ItfwKeywordFinderWordsPack;
// Модуль: "w:\common\components\rtl\Garant\ScriptEngine\ItfwKeywordFinderWordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ItfwKeywordFinderWordsPack" MUID: (559BCED301F0)
{$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc}
interface
{$If NOT Defined(NoScripts)}
uses
l3IntfUses
, tfwScriptingInterfaces
;
{$IfEnd} // NOT Defined(NoScripts)
implementation
{$If NOT Defined(NoScripts)}
uses
l3ImplUses
, tfwClassLike
, l3Interfaces
, TypInfo
, tfwPropertyLike
, tfwTypeInfo
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
//#UC START# *559BCED301F0impl_uses*
//#UC END# *559BCED301F0impl_uses*
;
type
TkwPopKeywordFinderKeywordByName = {final} class(TtfwClassLike)
{* Слово скрипта pop:KeywordFinder:KeywordByName }
private
function KeywordByName(const aCtx: TtfwContext;
aKeywordFinder: TtfwKeywordFinder;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:KeywordFinder:KeywordByName }
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;
end;//TkwPopKeywordFinderKeywordByName
TkwPopKeywordFinderParentFinder = {final} class(TtfwPropertyLike)
{* Слово скрипта pop:KeywordFinder:ParentFinder }
private
function ParentFinder(const aCtx: TtfwContext;
aKeywordFinder: TtfwKeywordFinder): TtfwKeywordFinder;
{* Реализация слова скрипта pop:KeywordFinder:ParentFinder }
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;//TkwPopKeywordFinderParentFinder
function TkwPopKeywordFinderKeywordByName.KeywordByName(const aCtx: TtfwContext;
aKeywordFinder: TtfwKeywordFinder;
const aName: Il3CString): TtfwKeyWord;
{* Реализация слова скрипта pop:KeywordFinder:KeywordByName }
//#UC START# *559BCEFC0315_559BCEFC0315_559D5D4400D3_Word_var*
//#UC END# *559BCEFC0315_559BCEFC0315_559D5D4400D3_Word_var*
begin
//#UC START# *559BCEFC0315_559BCEFC0315_559D5D4400D3_Word_impl*
Result := TtfwKeyWord(aKeywordFinder.KeywordByName(aName));
//#UC END# *559BCEFC0315_559BCEFC0315_559D5D4400D3_Word_impl*
end;//TkwPopKeywordFinderKeywordByName.KeywordByName
class function TkwPopKeywordFinderKeywordByName.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:KeywordFinder:KeywordByName';
end;//TkwPopKeywordFinderKeywordByName.GetWordNameForRegister
function TkwPopKeywordFinderKeywordByName.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwKeyWord);
end;//TkwPopKeywordFinderKeywordByName.GetResultTypeInfo
function TkwPopKeywordFinderKeywordByName.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 2;
end;//TkwPopKeywordFinderKeywordByName.GetAllParamsCount
function TkwPopKeywordFinderKeywordByName.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwKeywordFinder), @tfw_tiString]);
end;//TkwPopKeywordFinderKeywordByName.ParamsTypes
procedure TkwPopKeywordFinderKeywordByName.DoDoIt(const aCtx: TtfwContext);
var l_aKeywordFinder: TtfwKeywordFinder;
var l_aName: Il3CString;
begin
try
l_aKeywordFinder := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aKeywordFinder: TtfwKeywordFinder : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
try
l_aName := Il3CString(aCtx.rEngine.PopString);
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aName: Il3CString : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(KeywordByName(aCtx, l_aKeywordFinder, l_aName));
end;//TkwPopKeywordFinderKeywordByName.DoDoIt
function TkwPopKeywordFinderParentFinder.ParentFinder(const aCtx: TtfwContext;
aKeywordFinder: TtfwKeywordFinder): TtfwKeywordFinder;
{* Реализация слова скрипта pop:KeywordFinder:ParentFinder }
//#UC START# *559BCF500182_559BCF500182_559D5D4400D3_Word_var*
//#UC END# *559BCF500182_559BCF500182_559D5D4400D3_Word_var*
begin
//#UC START# *559BCF500182_559BCF500182_559D5D4400D3_Word_impl*
Result := aKeywordFinder.ParentFinder;
//#UC END# *559BCF500182_559BCF500182_559D5D4400D3_Word_impl*
end;//TkwPopKeywordFinderParentFinder.ParentFinder
class function TkwPopKeywordFinderParentFinder.GetWordNameForRegister: AnsiString;
begin
Result := 'pop:KeywordFinder:ParentFinder';
end;//TkwPopKeywordFinderParentFinder.GetWordNameForRegister
function TkwPopKeywordFinderParentFinder.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TtfwKeywordFinder);
end;//TkwPopKeywordFinderParentFinder.GetResultTypeInfo
function TkwPopKeywordFinderParentFinder.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwPopKeywordFinderParentFinder.GetAllParamsCount
function TkwPopKeywordFinderParentFinder.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TtfwKeywordFinder)]);
end;//TkwPopKeywordFinderParentFinder.ParamsTypes
procedure TkwPopKeywordFinderParentFinder.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ParentFinder', aCtx);
end;//TkwPopKeywordFinderParentFinder.SetValuePrim
procedure TkwPopKeywordFinderParentFinder.DoDoIt(const aCtx: TtfwContext);
var l_aKeywordFinder: TtfwKeywordFinder;
begin
try
l_aKeywordFinder := TtfwWord(aCtx.rEngine.PopObjAs(TtfwWord));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aKeywordFinder: TtfwKeywordFinder : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(ParentFinder(aCtx, l_aKeywordFinder));
end;//TkwPopKeywordFinderParentFinder.DoDoIt
initialization
TkwPopKeywordFinderKeywordByName.RegisterInEngine;
{* Регистрация pop_KeywordFinder_KeywordByName }
TkwPopKeywordFinderParentFinder.RegisterInEngine;
{* Регистрация pop_KeywordFinder_ParentFinder }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeywordFinder));
{* Регистрация типа TtfwKeywordFinder }
TtfwTypeRegistrator.RegisterType(TypeInfo(TtfwKeyWord));
{* Регистрация типа TtfwKeyWord }
TtfwTypeRegistrator.RegisterType(@tfw_tiString);
{* Регистрация типа Il3CString }
{$IfEnd} // NOT Defined(NoScripts)
end.
|
program enteros;
type
vector = array[1..100] of integer;
function posicion(v:vector; x:integer):integer;
begin
if ((x >= 1) and (x <= 100)) then
obtenerX := v[x]
else
obtenerX := -1;
end;
procedure intercambio(v:vector; x,y:integer);
var
aux :integer;
begin
aux := v[x];
v[x] := v[y];
v[y] := aux;
end;
function sumarVector(v:vector):integer;
var
suma :integer;
begin
for i:= 1 to 100 do
suma := suma + v[i];
sumarVector := suma;
end;
function promedio(v:vector):real;
begin
promedio := sumarVector(v) / 100;
end;
function elementoMaximo(v:vector):integer;
var
maximo :integer;
begin
maximo := 0;
for i:=1 to 100 do
if (v[i] > maximo) then
maximo := v[i];
elementoMaximo := maximo;
end;
function elementoMinimo(v:vector):integer;
var
minimo :integer;
begin
minimo := 0;
for i := 1 to 100 do
if (v[i] < minimo) then
minimo := v[i];
elementoMinimo := minimo;
end;
begin
//
end. |
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
jc.IniFile, jc.Libs.Interfaces;
type
TMain_Form = class(TForm)
Button1: TButton;
Edt_Host: TEdit;
Edt_UserName: TEdit;
Edt_Password: TEdit;
Edt_Port: TEdit;
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
jcIniFIle: IJcIniFile;
teste: TStrings;
end;
var
Main_Form: TMain_Form;
implementation
{$R *.dfm}
function getApplicationPath: String;
var
Path: array[0..MAX_PATH - 1] of Char;
PathStr: string;
begin
SetString(PathStr, Path, GetModuleFileName(HInstance, Path, SizeOf(Path)));
result := ExtractFilePath(PathStr);
end;
procedure TMain_Form.Button1Click(Sender: TObject);
begin
jcIniFIle := TJcIniFile.New(getApplicationPath + 'config.ini');
jcIniFIle
.AddString('database', 'host', Edt_Host.Text)
.AddString('database', 'user', Edt_UserName.Text)
.AddString('database', 'password', Edt_Password.Text)
.AddString('database', 'port', Edt_Port.Text)
end;
procedure TMain_Form.FormCreate(Sender: TObject);
begin
jcIniFIle := TJcIniFile.Get(getApplicationPath + 'config.ini');
Edt_Host.Text := jcIniFIle.GetString('database', 'host', '');
Edt_UserName.Text := jcIniFIle.GetString('database', 'user', '');
Edt_Password.Text := jcIniFIle.GetString('database', 'password', '');
Edt_Port.Text := jcIniFIle.GetString('database', 'port', '');
end;
procedure TMain_Form.Button2Click(Sender: TObject);
begin
Close;
end;
end.
|
unit ContactListKeywordsPack;
{* Набор слов словаря для доступа к экземплярам контролов формы ContactList }
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Chat\ContactListKeywordsPack.pas"
// Стереотип: "ScriptKeywordsPack"
// Элемент модели: "ContactListKeywordsPack" MUID: (B87F040AE285)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, vtPanel
{$If Defined(Nemesis)}
, nscContextFilter
{$IfEnd} // Defined(Nemesis)
, eeTreeView
;
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, ContactList_Form
, tfwControlString
{$If NOT Defined(NoVCL)}
, kwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
, tfwScriptingInterfaces
, tfwPropertyLike
, TypInfo
, tfwTypeInfo
, TtfwClassRef_Proxy
, SysUtils
, TtfwTypeRegistrator_Proxy
, tfwScriptingTypes
;
type
Tkw_Form_ContactList = {final} class(TtfwControlString)
{* Слово словаря для идентификатора формы ContactList
----
*Пример использования*:
[code]
'aControl' форма::ContactList TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_Form_ContactList
Tkw_ContactList_Control_BackgroundPanel = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола BackgroundPanel
----
*Пример использования*:
[code]
контрол::BackgroundPanel TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_ContactList_Control_BackgroundPanel
Tkw_ContactList_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола BackgroundPanel
----
*Пример использования*:
[code]
контрол::BackgroundPanel:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_ContactList_Control_BackgroundPanel_Push
Tkw_ContactList_Control_ContextFilter = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола ContextFilter
----
*Пример использования*:
[code]
контрол::ContextFilter TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_ContactList_Control_ContextFilter
Tkw_ContactList_Control_ContextFilter_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола ContextFilter
----
*Пример использования*:
[code]
контрол::ContextFilter:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_ContactList_Control_ContextFilter_Push
Tkw_ContactList_Control_trContactList = {final} class(TtfwControlString)
{* Слово словаря для идентификатора контрола trContactList
----
*Пример использования*:
[code]
контрол::trContactList TryFocus ASSERT
[code] }
protected
function GetString: AnsiString; override;
class procedure RegisterInEngine; override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_ContactList_Control_trContactList
Tkw_ContactList_Control_trContactList_Push = {final} class({$If NOT Defined(NoVCL)}
TkwBynameControlPush
{$IfEnd} // NOT Defined(NoVCL)
)
{* Слово словаря для контрола trContactList
----
*Пример использования*:
[code]
контрол::trContactList:push pop:control:SetFocus ASSERT
[code] }
protected
procedure DoDoIt(const aCtx: TtfwContext); override;
class function GetWordNameForRegister: AnsiString; override;
end;//Tkw_ContactList_Control_trContactList_Push
TkwContactListFormBackgroundPanel = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContactListForm.BackgroundPanel }
private
function BackgroundPanel(const aCtx: TtfwContext;
aContactListForm: TContactListForm): TvtPanel;
{* Реализация слова скрипта .TContactListForm.BackgroundPanel }
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;//TkwContactListFormBackgroundPanel
TkwContactListFormContextFilter = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContactListForm.ContextFilter }
private
function ContextFilter(const aCtx: TtfwContext;
aContactListForm: TContactListForm): TnscContextFilter;
{* Реализация слова скрипта .TContactListForm.ContextFilter }
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;//TkwContactListFormContextFilter
TkwContactListFormTrContactList = {final} class(TtfwPropertyLike)
{* Слово скрипта .TContactListForm.trContactList }
private
function trContactList(const aCtx: TtfwContext;
aContactListForm: TContactListForm): TeeTreeView;
{* Реализация слова скрипта .TContactListForm.trContactList }
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;//TkwContactListFormTrContactList
function Tkw_Form_ContactList.GetString: AnsiString;
begin
Result := 'ContactListForm';
end;//Tkw_Form_ContactList.GetString
class function Tkw_Form_ContactList.GetWordNameForRegister: AnsiString;
begin
Result := 'форма::ContactList';
end;//Tkw_Form_ContactList.GetWordNameForRegister
function Tkw_ContactList_Control_BackgroundPanel.GetString: AnsiString;
begin
Result := 'BackgroundPanel';
end;//Tkw_ContactList_Control_BackgroundPanel.GetString
class procedure Tkw_ContactList_Control_BackgroundPanel.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TvtPanel);
end;//Tkw_ContactList_Control_BackgroundPanel.RegisterInEngine
class function Tkw_ContactList_Control_BackgroundPanel.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::BackgroundPanel';
end;//Tkw_ContactList_Control_BackgroundPanel.GetWordNameForRegister
procedure Tkw_ContactList_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('BackgroundPanel');
inherited;
end;//Tkw_ContactList_Control_BackgroundPanel_Push.DoDoIt
class function Tkw_ContactList_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::BackgroundPanel:push';
end;//Tkw_ContactList_Control_BackgroundPanel_Push.GetWordNameForRegister
function Tkw_ContactList_Control_ContextFilter.GetString: AnsiString;
begin
Result := 'ContextFilter';
end;//Tkw_ContactList_Control_ContextFilter.GetString
class procedure Tkw_ContactList_Control_ContextFilter.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TnscContextFilter);
end;//Tkw_ContactList_Control_ContextFilter.RegisterInEngine
class function Tkw_ContactList_Control_ContextFilter.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContextFilter';
end;//Tkw_ContactList_Control_ContextFilter.GetWordNameForRegister
procedure Tkw_ContactList_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('ContextFilter');
inherited;
end;//Tkw_ContactList_Control_ContextFilter_Push.DoDoIt
class function Tkw_ContactList_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::ContextFilter:push';
end;//Tkw_ContactList_Control_ContextFilter_Push.GetWordNameForRegister
function Tkw_ContactList_Control_trContactList.GetString: AnsiString;
begin
Result := 'trContactList';
end;//Tkw_ContactList_Control_trContactList.GetString
class procedure Tkw_ContactList_Control_trContactList.RegisterInEngine;
begin
inherited;
TtfwClassRef.Register(TeeTreeView);
end;//Tkw_ContactList_Control_trContactList.RegisterInEngine
class function Tkw_ContactList_Control_trContactList.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::trContactList';
end;//Tkw_ContactList_Control_trContactList.GetWordNameForRegister
procedure Tkw_ContactList_Control_trContactList_Push.DoDoIt(const aCtx: TtfwContext);
begin
aCtx.rEngine.PushString('trContactList');
inherited;
end;//Tkw_ContactList_Control_trContactList_Push.DoDoIt
class function Tkw_ContactList_Control_trContactList_Push.GetWordNameForRegister: AnsiString;
begin
Result := 'контрол::trContactList:push';
end;//Tkw_ContactList_Control_trContactList_Push.GetWordNameForRegister
function TkwContactListFormBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext;
aContactListForm: TContactListForm): TvtPanel;
{* Реализация слова скрипта .TContactListForm.BackgroundPanel }
begin
Result := aContactListForm.BackgroundPanel;
end;//TkwContactListFormBackgroundPanel.BackgroundPanel
class function TkwContactListFormBackgroundPanel.GetWordNameForRegister: AnsiString;
begin
Result := '.TContactListForm.BackgroundPanel';
end;//TkwContactListFormBackgroundPanel.GetWordNameForRegister
function TkwContactListFormBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TvtPanel);
end;//TkwContactListFormBackgroundPanel.GetResultTypeInfo
function TkwContactListFormBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContactListFormBackgroundPanel.GetAllParamsCount
function TkwContactListFormBackgroundPanel.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContactListForm)]);
end;//TkwContactListFormBackgroundPanel.ParamsTypes
procedure TkwContactListFormBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx);
end;//TkwContactListFormBackgroundPanel.SetValuePrim
procedure TkwContactListFormBackgroundPanel.DoDoIt(const aCtx: TtfwContext);
var l_aContactListForm: TContactListForm;
begin
try
l_aContactListForm := TContactListForm(aCtx.rEngine.PopObjAs(TContactListForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContactListForm: TContactListForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aContactListForm));
end;//TkwContactListFormBackgroundPanel.DoDoIt
function TkwContactListFormContextFilter.ContextFilter(const aCtx: TtfwContext;
aContactListForm: TContactListForm): TnscContextFilter;
{* Реализация слова скрипта .TContactListForm.ContextFilter }
begin
Result := aContactListForm.ContextFilter;
end;//TkwContactListFormContextFilter.ContextFilter
class function TkwContactListFormContextFilter.GetWordNameForRegister: AnsiString;
begin
Result := '.TContactListForm.ContextFilter';
end;//TkwContactListFormContextFilter.GetWordNameForRegister
function TkwContactListFormContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TnscContextFilter);
end;//TkwContactListFormContextFilter.GetResultTypeInfo
function TkwContactListFormContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContactListFormContextFilter.GetAllParamsCount
function TkwContactListFormContextFilter.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContactListForm)]);
end;//TkwContactListFormContextFilter.ParamsTypes
procedure TkwContactListFormContextFilter.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx);
end;//TkwContactListFormContextFilter.SetValuePrim
procedure TkwContactListFormContextFilter.DoDoIt(const aCtx: TtfwContext);
var l_aContactListForm: TContactListForm;
begin
try
l_aContactListForm := TContactListForm(aCtx.rEngine.PopObjAs(TContactListForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContactListForm: TContactListForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aContactListForm));
end;//TkwContactListFormContextFilter.DoDoIt
function TkwContactListFormTrContactList.trContactList(const aCtx: TtfwContext;
aContactListForm: TContactListForm): TeeTreeView;
{* Реализация слова скрипта .TContactListForm.trContactList }
begin
Result := aContactListForm.trContactList;
end;//TkwContactListFormTrContactList.trContactList
class function TkwContactListFormTrContactList.GetWordNameForRegister: AnsiString;
begin
Result := '.TContactListForm.trContactList';
end;//TkwContactListFormTrContactList.GetWordNameForRegister
function TkwContactListFormTrContactList.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo;
begin
Result := TypeInfo(TeeTreeView);
end;//TkwContactListFormTrContactList.GetResultTypeInfo
function TkwContactListFormTrContactList.GetAllParamsCount(const aCtx: TtfwContext): Integer;
begin
Result := 1;
end;//TkwContactListFormTrContactList.GetAllParamsCount
function TkwContactListFormTrContactList.ParamsTypes: PTypeInfoArray;
begin
Result := OpenTypesToTypes([TypeInfo(TContactListForm)]);
end;//TkwContactListFormTrContactList.ParamsTypes
procedure TkwContactListFormTrContactList.SetValuePrim(const aValue: TtfwStackValue;
const aCtx: TtfwContext);
begin
RunnerError('Нельзя присваивать значение readonly свойству trContactList', aCtx);
end;//TkwContactListFormTrContactList.SetValuePrim
procedure TkwContactListFormTrContactList.DoDoIt(const aCtx: TtfwContext);
var l_aContactListForm: TContactListForm;
begin
try
l_aContactListForm := TContactListForm(aCtx.rEngine.PopObjAs(TContactListForm));
except
on E: Exception do
begin
RunnerError('Ошибка при получении параметра aContactListForm: TContactListForm : ' + E.Message, aCtx);
Exit;
end;//on E: Exception
end;//try..except
aCtx.rEngine.PushObj(trContactList(aCtx, l_aContactListForm));
end;//TkwContactListFormTrContactList.DoDoIt
initialization
Tkw_Form_ContactList.RegisterInEngine;
{* Регистрация Tkw_Form_ContactList }
Tkw_ContactList_Control_BackgroundPanel.RegisterInEngine;
{* Регистрация Tkw_ContactList_Control_BackgroundPanel }
Tkw_ContactList_Control_BackgroundPanel_Push.RegisterInEngine;
{* Регистрация Tkw_ContactList_Control_BackgroundPanel_Push }
Tkw_ContactList_Control_ContextFilter.RegisterInEngine;
{* Регистрация Tkw_ContactList_Control_ContextFilter }
Tkw_ContactList_Control_ContextFilter_Push.RegisterInEngine;
{* Регистрация Tkw_ContactList_Control_ContextFilter_Push }
Tkw_ContactList_Control_trContactList.RegisterInEngine;
{* Регистрация Tkw_ContactList_Control_trContactList }
Tkw_ContactList_Control_trContactList_Push.RegisterInEngine;
{* Регистрация Tkw_ContactList_Control_trContactList_Push }
TkwContactListFormBackgroundPanel.RegisterInEngine;
{* Регистрация ContactListForm_BackgroundPanel }
TkwContactListFormContextFilter.RegisterInEngine;
{* Регистрация ContactListForm_ContextFilter }
TkwContactListFormTrContactList.RegisterInEngine;
{* Регистрация ContactListForm_trContactList }
TtfwTypeRegistrator.RegisterType(TypeInfo(TContactListForm));
{* Регистрация типа TContactListForm }
TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel));
{* Регистрация типа TvtPanel }
TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter));
{* Регистрация типа TnscContextFilter }
TtfwTypeRegistrator.RegisterType(TypeInfo(TeeTreeView));
{* Регистрация типа TeeTreeView }
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)
end.
|
unit xn.grid.Register;
interface
uses ToolsAPI, System.Classes;
type
TxnGridAbout = class(TNotifierObject, IOTAWizard, IOTAMenuWizard)
function GetIDString: string;
function GetName: string;
function GetState: TWizardState;
procedure Execute;
function GetMenuText: string;
end;
procedure Register;
implementation
uses Vcl.Menus, Vcl.Dialogs, Vcl.Graphics,
xn.grid;
// *****************************************************************************
// *****************************************************************************
procedure SplashTextAdd;
var
b: TBitmap;
begin
b := TBitmap.Create;
try
b.LoadFromResourceName(HInstance, 'LOGO');
SplashScreenServices.AddPluginBitmap('xnGrid', b.Handle, false, '', '');
finally
b.Free;
end;
end;
// *****************************************************************************
// *****************************************************************************
procedure Register;
begin
RegisterComponents('Data Controls', [TxnGrid]);
RegisterPackageWizard(TxnGridAbout.Create);
end;
{ TxnGridAbout }
procedure TxnGridAbout.Execute;
begin
ShowMessage('stefano.busetto@gmail.com')
end;
function TxnGridAbout.GetIDString: string;
begin
Result := 'xn.grid.about';
end;
function TxnGridAbout.GetMenuText: string;
begin
Result := 'About xnGrid'
end;
function TxnGridAbout.GetName: string;
begin
Result := 'About xnGrid'
end;
function TxnGridAbout.GetState: TWizardState;
begin
Result := [wsEnabled];
end;
initialization
SplashTextAdd;
finalization
end.
|
unit uInterfaceFactory;
interface
uses
SysUtils, Classes;
type
TInterfacedObjectClass = class of TInterfacedObject;
TInterfaceFactory = class(TObject)
private
FGuildList: TStringList;
public
constructor Create;
destructor Destroy; override;
function CreateInterface(GUID: TGUID; AName: string = ''): IInterface; overload;
function CreateInterface(GUID: TGUID; out ARetval; AName: string = ''):
Boolean; overload;
procedure RegisterImplementation(GUID: TGUID; ImplementorClass:
TInterfacedObjectClass; AName: string = '');
procedure UnRegisterImplementation(GUID: TGUID; AName: string = '');
end;
ImplementorNotRegisteredException = class(Exception)
private
FGUID: TGUID;
procedure SetGUID(const Value: TGUID);
public
property GUID: TGUID read FGUID write SetGUID;
end;
//function InterfaceFactory: TInterfaceFactory;
implementation
var
FInterfaceFactory: TInterfaceFactory;
function InterfaceFactory: TInterfaceFactory;
begin
Result := FInterfaceFactory;
end;
constructor TInterfaceFactory.Create;
begin
inherited Create;
FGuildList := TStringList.Create();
end;
destructor TInterfaceFactory.Destroy;
begin
FreeAndNil(FGuildList);
inherited Destroy;
end;
{
****************************** TInterfaceFactory *******************************
}
function TInterfaceFactory.CreateInterface(GUID: TGUID; AName: string = ''):
IInterface;
var
ItemIndex: Integer;
ItemName: string;
Obj: TObject;
E: ImplementorNotRegisteredException;
begin
ItemName := GUIDToString(GUID) + AName;
ItemIndex := FGuildList.IndexOf(ItemName);
if ItemIndex > -1 then
begin
Obj := FGuildList.Objects[ItemIndex];
Result := TInterfacedObjectClass(Pointer(Obj)).Create;
end
else
begin
E := ImplementorNotRegisteredException.Create('Класс реализующий интерфейс '
+ GUIDToString(GUID) + ' не зарегистрирован в реестре реализаций');
E.GUID := GUID;
raise E;
end;
end;
function TInterfaceFactory.CreateInterface(GUID: TGUID; out ARetval; AName:
string = ''): Boolean;
var
Instance: IInterface;
begin
Instance := CreateInterface(GUID);
Result := Supports(Instance, GUID, ARetval);
end;
procedure TInterfaceFactory.RegisterImplementation(GUID: TGUID;
ImplementorClass: TInterfacedObjectClass; AName: string = '');
var
ItemIndex: Integer;
ItemName: string;
Obj: TObject;
begin
ItemName := GUIDToString(GUID) + AName;
ItemIndex := FGuildList.IndexOf(ItemName);
Obj := TObject(Pointer(ImplementorClass));
if ItemIndex = -1 then
FGuildList.AddObject(ItemName, Obj)
else
FGuildList.Objects[ItemIndex] := Obj;
end;
procedure TInterfaceFactory.UnRegisterImplementation(GUID: TGUID; AName: string
= '');
var
ItemIndex: Integer;
ItemName: string;
begin
ItemName := GUIDToString(GUID) + AName;
ItemIndex := FGuildList.IndexOf(ItemName);
if ItemIndex >= 0 then
FGuildList.Delete(ItemIndex);
end;
procedure ImplementorNotRegisteredException.SetGUID(const Value: TGUID);
begin
if not IsEqualGUID(FGUID, Value) then
begin
FGUID := Value;
end;
end;
initialization
FInterfaceFactory := TInterfaceFactory.Create;
finalization
FInterfaceFactory.Free;
end.
|
unit ServerMethodsUnit1;
interface
uses System.SysUtils, System.Classes, System.Json,
Data.FireDACJSONReflect,
Datasnap.DSServer, Datasnap.DSAuth, Datasnap.DSProviderDataModuleAdapter,
FireDAC.Stan.StorageJSON, FireDAC.Stan.StorageBin;
type
{$METHODINFO ON}
TServerMethods1 = class(TDataModule)
FDStanStorageJSONLink1: TFDStanStorageJSONLink;
FDStanStorageBinLink1: TFDStanStorageBinLink;
private
Pre_unit_balanca:double;
procedure DOACBrPrecoUnitarioEvento(const Codigo: string;
var PrecoUnitario: Double);
{ Private declarations }
public
{ Public declarations }
// original criado pelo DELPHI
function EchoString(Value: string): string;
function ReverseString(Value: string): string;
// passa o codigo do cliente e retorna os dados do cliente
function GetCliente(codigo: int64): TJsonObject;
// exemplo retornando um JSONObject
function GetCliente2(codigo: int64): TFDJSONDataSets; // usando Reflection
// retorna na mesma resposta CLIENTE + ITENS
function GetNotaFiscal(ANumero: integer): TFDJSONDataSets;
function EAN_balanca(EAN: string; preco_unit: Double): string;
end;
{$METHODINFO OFF}
implementation
{$R *.dfm}
uses System.StrUtils, FireDAC.ObjectDataSet, Data.db.helper,
ACBrBase, ACBrInStore;
function TServerMethods1.EchoString(Value: string): string;
begin
Result := Value;
end;
function TServerMethods1.ReverseString(Value: string): string;
begin
Result := System.StrUtils.ReverseString(Value);
end;
type
TClientes = class
private
FCodigo: int64;
FNome: string;
FCidade: string;
FDebitos: Double;
FEndereco: string;
FEstado: String;
procedure SetCidade(const Value: string);
procedure SetCodigo(const Value: int64);
procedure SetDebitos(const Value: Double);
procedure SetEndereco(const Value: string);
procedure SetEstado(const Value: String);
procedure SetNome(const Value: string);
public
property codigo: int64 read FCodigo write SetCodigo;
property Nome: string read FNome write SetNome;
property Cidade: string read FCidade write SetCidade;
property Estado: String read FEstado write SetEstado;
property Endereco: string read FEndereco write SetEndereco;
property Debitos: Double read FDebitos write SetDebitos;
end;
TNotaFiscalItens = class
private
FPreco: Double;
FCodigo: string;
FQtde: Double;
FNome: string;
procedure SetCodigo(const Value: string);
procedure SetNome(const Value: string);
procedure SetPreco(const Value: Double);
procedure SetQtde(const Value: Double);
public
property codigo: string read FCodigo write SetCodigo;
property Nome: string read FNome write SetNome;
property Qtde: Double read FQtde write SetQtde;
property Preco: Double read FPreco write SetPreco;
end;
function TServerMethods1.GetCliente(codigo: int64): TJsonObject;
// TFDJSONDataSets;
var
ds: TObjectDataSet;
cli: TClientes;
v : TJSonValue;
begin
// buscar os dados no banco de dados com codigo passado pelo cliente...
// resposta para o cliente;
// meus dados no firedac
// usei um ObjectDataset somento para não precisar criar uma conexão e um query
ds := TObjectDataSet.Create(self, TClientes);
// usa RTTI para mapear coluna do TDataset
try
ds.Open;
ds.append;
with ds do
begin
FieldByName('codigo').Value := 1;
FieldByName('nome').Value := 'Embarcadero SA';
FieldByName('Endereco').Value := 'Rua...xxxx...,10';
FieldByName('Cidade').Value := 'Sao Paulo';
FieldByName('Estado').Value := 'SP';
FieldByName('Debitos').Value := 100000.12;
end;
ds.Post;
ds.append;
with ds do
begin
FieldByName('codigo').Value := 2;
FieldByName('nome').Value := 'Embarcadero SA2';
FieldByName('Endereco').Value := 'Rua...xxxx...,10';
FieldByName('Cidade').Value := 'Sao Paulo';
FieldByName('Estado').Value := 'SP';
FieldByName('Debitos').Value := 100000.12;
end;
ds.Post;
// retorna um JsonObject
Result := ds.ToJsonObject('cliente');
v := TJSONObject.ParseJSONValue('[{"codigo":1,"nome":"Exemplo 2"}]');
result.addpair('adicional', v);
finally
ds.Free;
end;
end;
// retorna um objeto FireDAC JSON Reflection
// isto estabelece uma boa integração entre aplicativos que usam FireDAC nos clientes.
// se o cliente não for FireDAC... talves seja interessante pensar em retornar um
// formato mais generico
function TServerMethods1.GetCliente2(codigo: int64): TFDJSONDataSets;
var
ds: TObjectDataSet;
cli: TClientes;
begin
// buscar os dados no banco de dados com codigo passado pelo cliente...
// resposta para o cliente;
Result := TFDJSONDataSets.Create;
// meus dados no firedac
// usei um ObjectDataset somento para não precisar criar uma conexão e um query
ds := TObjectDataSet.Create(nil, TClientes);
try
ds.Open;
ds.append;
with ds do
begin
FieldByName('codigo').Value := 1;
FieldByName('nome').Value := 'Embarcadero SA';
FieldByName('Endereco').Value := 'Rua...xxxx...,10';
FieldByName('Cidade').Value := 'Sao Paulo';
FieldByName('Estado').Value := 'SP';
FieldByName('Debitos').Value := 100000.12;
end;
ds.Post;
TFDJSONDataSetsWriter.ListAdd(Result, 'CLIENTE', ds);
finally
// ds.Free; -- eh destruido pelo Writer
end;
end;
// retornando mais de uma tabala na mesma consulta
// retorna CLIENTE e ITENS da nota fiscal
function TServerMethods1.GetNotaFiscal(ANumero: integer): TFDJSONDataSets;
var
ds: TObjectDataSet;
cli: TClientes;
dsItens: TObjectDataSet;
itens: TNotaFiscalItens;
begin
// buscar os dados no banco de dados com codigo passado pelo cliente...
// resposta para o cliente;
Result := TFDJSONDataSets.Create;
// meus dados no firedac
// usei um ObjectDataset somento para não precisar criar uma conexão e um query
ds := TObjectDataSet.Create(nil, TClientes);
try
ds.Open;
ds.append;
with ds do
begin
FieldByName('codigo').Value := 1;
FieldByName('nome').Value := 'Embarcadero SA';
FieldByName('Endereco').Value := 'Rua...xxxx...,10';
FieldByName('Cidade').Value := 'Sao Paulo';
FieldByName('Estado').Value := 'SP';
FieldByName('Debitos').Value := 100000.12;
end;
ds.Post;
TFDJSONDataSetsWriter.ListAdd(Result, 'CLIENTE', ds);
// usa RTTI para mapear o objeto para TFDMemTable
dsItens := TObjectDataSet.Create(nil, TNotaFiscalItens);
dsItens.Open;
itens := TNotaFiscalItens.Create;
with itens do
begin
codigo := '000001';
Nome := 'Margarina';
Qtde := 2;
Preco := 8.5;
end;
dsItens.ObjectList.Add(itens); // adiciona o objeto ao ObjectDataSet
with itens do
begin
codigo := '000002';
Nome := 'Pao Frances';
Qtde := 1;
Preco := 15;
end;
dsItens.ObjectList.Add(itens);
TFDJSONDataSetsWriter.ListAdd(Result, 'ITENS', dsItens);
finally
// ds.Free; -- eh destruido pelo Writer
end;
end;
{ TClientes }
procedure TClientes.SetCidade(const Value: string);
begin
FCidade := Value;
end;
procedure TClientes.SetCodigo(const Value: int64);
begin
FCodigo := Value;
end;
procedure TClientes.SetDebitos(const Value: Double);
begin
FDebitos := Value;
end;
procedure TClientes.SetEndereco(const Value: string);
begin
FEndereco := Value;
end;
procedure TClientes.SetEstado(const Value: String);
begin
FEstado := Value;
end;
procedure TClientes.SetNome(const Value: string);
begin
FNome := Value;
end;
{ TNotaFiscalItens }
procedure TNotaFiscalItens.SetCodigo(const Value: string);
begin
FCodigo := Value;
end;
procedure TNotaFiscalItens.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TNotaFiscalItens.SetPreco(const Value: Double);
begin
FPreco := Value;
end;
procedure TNotaFiscalItens.SetQtde(const Value: Double);
begin
FQtde := Value;
end;
Procedure TServerMethods1.DOACBrPrecoUnitarioEvento(const Codigo: string;
var PrecoUnitario: Double) ;
begin
// retornar o preco de venda;
PrecoUnitario := Pre_unit_balanca;
end;
function TServerMethods1.EAN_balanca(EAN: string; preco_unit: Double): string;
var
edtPrefixo, edtCodigo, edtPeso, edtDV: String;
edtTotal: Double;
ACBrInStore1: TACBrInStore;
begin
Pre_unit_balanca := preco_unit;
ACBrInStore1 := TACBrInStore.Create(nil);
try
ACBrInStore1.OnGetPrecoUnitario :=DOACBrPrecoUnitarioEvento;
ACBrInStore1.Codificacao := '2CCCC0TTTTTTDV';
if Length(EAN) = 13 then
begin
if ACBrInStore1.Prefixo = Copy(EAN, 1, Length(ACBrInStore1.Prefixo)) then
begin
ACBrInStore1.Desmembrar(EAN);
edtPrefixo := ACBrInStore1.Prefixo;
edtCodigo := ACBrInStore1.codigo;
edtTotal := ACBrInStore1.Total;
edtDV := ACBrInStore1.DV;
//edtPeso := FormatFloat('0.000', ACBrInStore1.Total / preco_unit);
edtPeso := formatFloat('0.000',ACBrInStore1.peso);
end;
end;
{ Result := Result + ' ' + edtCodigo + ' ' + edtPeso + ' ' +
FloatToJson(edtTotal);
}
with TJSONObject.create do
try
AddPair('codigo',edtCodigo);
AddPair('peso',TJSONNumber.Create(ACBrInStore1.Peso));
AddPair('preco',TJSONNumber.Create(preco_unit));
AddPair('total', TJSONNumber.Create(ACBrInStore1.Total) );
result := ToString;
finally
free;
end;
finally
ACBrInStore1.Free;
end;
end;
end.
|
unit xpr.parser;
{
Author: Jarl K. Holta
License: GNU Lesser GPL (http://www.gnu.org/licenses/lgpl.html)
A parser... Or, that's what it's ment to be :P
}
{$I express.inc}
interface
uses
SysUtils,
xpr.express,
xpr.lexer,
xpr.AST,
xpr.errors;
const
ATOM = [tk_ident, tk_int, tk_float, tk_bool, tk_char, tk_string, tk_none];
EXPRESSION = ATOM + [tk_sum, tk_bitwise, tk_paren, tk_square];
SEPARATORS = [tk_newline, tk_semicolon];
type
TParser = class(TObject)
private
FPos: Int32;
FTokenizer: TTokenizer;
FLooping:Int32;
{flags}
OldLineInsenstive, FLineInsenstive: Boolean;
public
constructor Create(T:TTokenizer);
function Parse(): TBaseNode; inline;
function DocPos: TDocPos; inline;
function Current: TToken; inline;
function Peek(n:Int32=1): TToken; inline;
procedure SkipTokens(tokens:TTokenKindSet); inline;
procedure SkipNewline; inline;
function Next(IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken; inline;
function NextIf(Value:String; IncOrder:EIncOrder=PostInc; Increment:Int32=1): Boolean; inline; overload;
function NextIf(Token:TTokenKind; IncOrder:EIncOrder=PostInc; Increment:Int32=1): Boolean; inline; overload;
function NextIf(Token:TToken; IncOrder:EIncOrder=PostInc; Increment:Int32=1): Boolean; inline; overload;
procedure RaiseException(msg:string); inline;
procedure RaiseExceptionFmt(msg:string; fmt:array of const); {inline;}
procedure Expect(Token:TToken); inline; overload;
procedure Expect(Token:TTokenKind); inline; overload;
procedure Expect(Value:String); inline; overload;
procedure Expect(Values:array of String); overload;
function ExpectAndInc(Token:TToken; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken; inline; overload;
function ExpectAndInc(Token:TTokenKind; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken; inline; overload;
function ExpectAndInc(Value:String; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken; inline; overload;
function ExpectAndInc(Values:array of String; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken; overload;
function OperatorPrecedence(): Int8; inline;
function OperatorAssoc(): Int8; inline;
function IS_UNARY(): Boolean; inline;
function IS_ENCLOSURE(): Boolean; inline;
function ParseReturn(): TReturn; inline;
function ParseContinue(): TContinue; inline;
function ParseBreak(): TBreak; inline;
function ParseFunction(): TFunction;
function ParseCall(callable: TBaseNode): TCall;
function ParseIndex(indexable:TBaseNode): TIndex;
function ParseIf(): TIf;
function ParseWhile(): TWhile;
function ParseRepeat(): TRepeat;
function ParseFor(): TFor;
function ParsePrint(): TPrint;
function ParseVardecl: TVarDecl;
function ParseListEnclosure(): TBaseNode;
function ParsePostPrimary(PrimExpr:TBaseNode): TBaseNode; inline;
function ParseAtom(): TBaseNode; inline;
function ParsePrimary(): TBaseNode; inline;
function RHSExpr(Left:TBaseNode; leftPrecedence:Int8=0): TBaseNode;
function ParseExpression(ExpectSeparator:Boolean=True): TBaseNode;
function ParseExpressionList(Insensitive:Boolean; AllowEmpty:Boolean=False): TNodeArray;
function ParseVarList(Insensitive:Boolean): TVarArray;
function ParseStatement: TBaseNode;
function ParseStatements(EndKeywords:array of string; Increase:Boolean=False): TNodeArray;
end;
function Parse(Tokenizer:TTokenizer): TBaseNode;
implementation
uses
xpr.utils;
function Parse(Tokenizer:TTokenizer): TBaseNode;
var
Parser:TParser;
begin
Parser := TParser.Create(Tokenizer);
Result := Parser.Parse();
Parser.Free();
end;
constructor TParser.Create(T:TTokenizer);
begin
FTokenizer := T;
FPos := 0;
FLooping := 0;
FLineInsenstive := False;
end;
function TParser.Parse(): TBaseNode;
begin
Result := TBlock.Create(ParseStatements([]), DocPos);
end;
{==============================================================================]
The basics
[==============================================================================}
function TParser.DocPos: TDocPos;
begin
if FPos = 0 then
Result := FTokenizer.Tokens[0].DocPos
else
Result := FTokenizer.Tokens[FPos-1].DocPos;
end;
function TParser.Current: TToken;
begin
Result := FTokenizer.Tokens[FPos];
end;
function TParser.Peek(n:Int32=1): TToken;
begin
Result := FTokenizer.Tokens[FPos+n];
end;
procedure TParser.SkipTokens(tokens:TTokenKindSet);
begin
while(Current.Token in Tokens) do Inc(FPos);
end;
procedure TParser.SkipNewline;
begin
while(Current.Token = tk_newline) do Inc(FPos);
end;
function TParser.Next(IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
if IncOrder = PostInc then
begin
Result := FTokenizer.Tokens[FPos];
Inc(FPos, Increment);
end else
begin
Inc(FPos, Increment);
Result := FTokenizer.Tokens[FPos];
end;
end;
function TParser.NextIf(Value:String; IncOrder:EIncOrder=PostInc; Increment:Int32=1): Boolean;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Peek(Ord(IncOrder)).value = Value;
if Result then Inc(FPos, Increment);
end;
function TParser.NextIf(Token:TTokenKind; IncOrder:EIncOrder=PostInc; Increment:Int32=1): Boolean;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Peek(Ord(IncOrder)).token = Token;
if Result then Inc(FPos, Increment);
end;
function TParser.NextIf(Token:TToken; IncOrder:EIncOrder=PostInc; Increment:Int32=1): Boolean;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Peek(Ord(IncOrder)) = Token;
if Result then Inc(FPos, Increment);
end;
{==============================================================================]
Error handling rutines
[==============================================================================}
procedure TParser.RaiseException(msg:string);
begin
xpr.errors.RaiseException(eSyntaxError, msg, DocPos);
end;
procedure TParser.RaiseExceptionFmt(msg:string; fmt:array of const);
begin
try
xpr.errors.RaiseExceptionFmt(eSyntaxError, msg, fmt, DocPos);
except
on e:SyntaxError do
raise SyntaxError.Create(e.Message) at get_caller_addr(get_frame);
end;
end;
procedure TParser.Expect(Token:TToken);
begin
if Token <> Current then
RaiseExceptionFmt(eExpectedButFound, [Token.ToString(), Current.ToString]);
end;
procedure TParser.Expect(Token:TTokenKind);
begin
if Token <> Current.Token then
RaiseExceptionFmt(eExpectedButFound, [TkToString(Token), Current.ToString]);
end;
procedure TParser.Expect(Value:String);
begin
if (Current.Token = tk_string) or (Value <> Current.Value) then
RaiseExceptionFmt(eExpectedButFound, [Value, Current.ToString]);
end;
procedure TParser.Expect(Values:array of String);
begin
if (Current.Token = tk_string) or (not StringContains(Values, Current.Value)) then
RaiseExceptionFmt(eExpectedButFound, [Values[0], Current.ToString]);
end;
function TParser.ExpectAndInc(Token:TToken; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Next(IncOrder, Increment);
if Token <> Result then
RaiseExceptionFmt(eExpectedButFound, [Token.ToString(), Result.ToString]);
end;
function TParser.ExpectAndInc(Token:TTokenKind; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Next(IncOrder, Increment);
if Token <> Result.Token then
RaiseExceptionFmt(eExpectedButFound, [TkToString(Token), Result.ToString]);
end;
function TParser.ExpectAndInc(Value:String; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Next(IncOrder, Increment);
if (Result.Token = tk_string) or (Value <> Result.Value) then
RaiseExceptionFmt(eExpectedButFound, [Value, Result.ToString]);
end;
function TParser.ExpectAndInc(Values:array of String; IncOrder:EIncOrder=PostInc; Increment:Int32=1): TToken;
begin
{$IFDEF loose_semicolon}if FLineInsenstive then SkipNewline;{$ENDIF}
Result := Next(IncOrder, Increment);
if (Result.Token = tk_string) or (not StringContains(Values, Result.Value)) then
RaiseExceptionFmt(eExpectedButFound, [Values[0], Result.ToString]);
end;
{==============================================================================]
Operator information
[==============================================================================}
function TParser.OperatorPrecedence(): Int8;
var
def:TOperatorPrecedence = (prec:-1; assoc:0);
begin
Result := PrecedenceMap.GetDef(Current.Value, def).prec;
end;
function TParser.OperatorAssoc(): Int8;
var
def:TOperatorPrecedence = (prec:0; assoc:1);
begin
Result := PrecedenceMap.GetDef(Current.Value, def).assoc;
end;
function TParser.IS_UNARY: Boolean;
var
def:TOperatorPrecedence = (prec:-1; assoc:0);
begin
Result := UnaryPrecedenceMap.GetDef(Current.Value, def).prec <> -1;
end;
function TParser.IS_ENCLOSURE: Boolean;
begin
Result := (Current.Token = tk_square) and (Current.Value = '[');
end;
{==============================================================================]
Here starts the actual parsing.. :)
[==============================================================================}
function TParser.ParseReturn(): TReturn;
begin
ExpectAndInc('return');
Result := TReturn.Create(ParseExpression(True), DocPos);
end;
function TParser.ParseContinue(): TContinue;
begin
ExpectAndInc('continue');
SkipTokens(SEPARATORS);
Result := TContinue.Create(DocPos);
end;
function TParser.ParseBreak(): TBreak;
begin
ExpectAndInc('break');
SkipTokens(SEPARATORS);
Result := TBreak.Create(DocPos);
end;
//print ...
function TParser.ParsePrint(): TPrint;
var exprs:TNodeArray;
begin
ExpectAndInc('print');
exprs := ParseExpressionList(False,False);
Result := TPrint.Create(exprs, DocPos);
SkipTokens(SEPARATORS);
end;
function TParser.ParseFunction(): TFunction;
var
Name:TToken;
Params:TVarArray = nil;
Prog:TBlock;
begin
ExpectAndInc('func');
Name := ExpectAndInc(tk_ident);
ExpectAndInc(lparen);
Params := ParseVarList(True);
ExpectAndInc(rparen);
if Current = Token(tk_assign, '=>') then
begin
Next;
Prog := TBlock.Create(TReturn.Create(ParseExpression(True), DocPos), DocPos);
end
else
begin
SkipTokens(SEPARATORS);
Prog := TBlock.Create(ParseStatements(['end'], True), DocPos);
end;
Result := TFunction.Create(Name.Value, Params, Prog, DocPos);
end;
function TParser.ParseCall(callable:TBaseNode): TCall;
var
args:TNodeArray=nil;
begin
ExpectAndInc(lparen);
Args := ParseExpressionList(True, True);
ExpectAndInc(rparen);
Result := TCall.Create(callable, args, DocPos);
end;
function TParser.ParseIndex(indexable:TBaseNode): TIndex;
var
args:TNodeArray;
begin
ExpectAndInc(lsquare);
OldLineInsenstive := FLineInsenstive;
FLineInsenstive := True;
while not NextIf(rsquare) do
begin
SetLength(args, Length(args) + 1);
Args[high(args)] := ParseExpression(False);
if NextIf(rsquare) then Break;
ExpectAndInc(tk_comma);
end;
FLineInsenstive := OldLineInsenstive;
Result := TIndex.Create(indexable, args, DocPos);
end;
(*IF STATEMENT:
> if condition then <stmts> [end | else <stmts> end]
> if (condition) <stmt> [else <stmt>]
*)
function TParser.ParseIf(): TIf;
var
Condition: TBaseNode;
Body, ElseBody: TBlock;
has_parenthesis:Boolean;
begin
ExpectAndInc('if');
has_parenthesis := NextIf(lparen, PostInc);
Condition := ParseExpression(False);
if has_parenthesis then
ExpectAndInc(rparen)
else
Expect(keyword('then'));
ElseBody := nil;
if NextIf(keyword('then')) then
begin
Body := TBlock.Create(ParseStatements(['end','else'], False), DocPos);
if Next() = keyword('else') then
ElseBody := TBlock.Create(ParseStatements(['end'], True), DocPos);
end
else
begin
Body := TBlock.Create(self.ParseStatement(), DocPos);
if NextIf(keyword('else')) then
ElseBody := TBlock.Create(self.ParseStatement(), DocPos);
end;
Result := TIf.Create(Condition, Body, ElseBody, DocPos);
end;
(*WHILE LOOP:
> while condition do <stmts> end
> while (condition) <stmt>
*)
function TParser.ParseWhile(): TWhile;
var
Condition:TBaseNode;
body:TBlock;
has_parenthesis:Boolean;
begin
ExpectAndInc('while');
has_parenthesis := NextIf(lparen, PostInc);
Condition := ParseExpression(False);
if has_parenthesis then
ExpectAndInc(rparen)
else
Expect(keyword('do'));
Inc(FLooping);
if NextIf(keyword('do')) then
body := TBlock.Create(ParseStatements(['end'], True), DocPos)
else
body := TBlock.Create(self.ParseStatement(), DocPos);
Result := TWhile.Create(Condition, body, DocPos);
Dec(FLooping);
end;
(*REPEAT LOOP:
> repeat <stmts> until(<condition>)
*)
function TParser.ParseRepeat(): TRepeat;
var
condition:TBaseNode;
body:TBlock;
begin
ExpectAndInc('repeat');
Inc(FLooping);
body := TBlock.Create(ParseStatements(['until'], True), DocPos);
Dec(FLooping);
ExpectAndInc(lparen, PostInc);
Condition := ParseExpression(False);
ExpectAndInc(rparen, PostInc);
Result := TRepeat.Create(condition, body, DocPos);
end;
(*FOR LOOP:
> for <expr>; <condition>; <expr> do <stmts> end
> for(<expr>; <condition>; <expr>) <stmt>
*)
function TParser.ParseFor(): TFor;
var
stmt1,stmt2,stmt3,body:TBaseNode;
has_parenthesis:Boolean;
begin
ExpectAndInc('for');
has_parenthesis := NextIf(lparen, PostInc);
if current = Keyword('var') then
begin
stmt1 := ParseVardecl;
ExpectAndInc(tk_semicolon);
end
else
stmt1 := ParseExpression(True);
stmt2 := ParseExpression(True);
stmt3 := ParseExpression(False);
if stmt3 <> nil then stmt3 := TStatement.Create(stmt3, DocPos);
if has_parenthesis then
ExpectAndInc(rparen)
else
Expect(Keyword('do'));
Inc(FLooping);
if NextIf(keyword('do')) then
body := TBlock.Create(ParseStatements(['end'], True), DocPos)
else
body := TBlock.Create(ParseStatement(), DocPos);
Result := TFor.Create(stmt1,stmt2,stmt3, body as TBlock, DocPos);
Dec(FLooping);
end;
//meh
function TParser.ParseVardecl: TVarDecl;
var
Right:TBaseNode;
Left:TVarArray;
begin
ExpectAndInc('var');
Left := ParseVarList(False);
Right := nil;
if Current = Token(tk_assign, ':=') then
begin
Next;
Right := ParseExpression(False);
end;
Result := TVarDecl.Create(left, right, DocPos)
end;
function TParser.ParseListEnclosure(): TBaseNode;
var
args:TNodeArray;
begin
ExpectAndInc(lsquare);
args := ParseExpressionList(True,True);
ExpectAndInc(rsquare);
Result := TListExpr.Create(args, docpos);
end;
function TParser.ParseAtom(): TBaseNode;
begin
Result := nil;
case Current.token of
tk_ident:
Result := TVariable.Create(Current.value, DocPos);
tk_none:
Result := TConstNone.Create(DocPos);
tk_bool:
Result := TConstBool.Create(Current.value, DocPos);
tk_char:
Result := TConstChar.Create(Current.value, DocPos);
tk_int:
Result := TConstInt.Create(Current.value, DocPos);
tk_float:
Result := TConstFloat.Create(Current.value, DocPos);
tk_string:
Result := TConstString.Create(Current.value, DocPos);
tk_square:
Exit(ParseListEnclosure());
else
RaiseException(eUnexpected);
end;
Next();
end;
function TParser.ParsePostPrimary(PrimExpr:TBaseNode): TBaseNode;
begin
while ((Current = lparen) or (Current = lsquare)) do
begin
while (Current = lparen) do PrimExpr := ParseCall(PrimExpr);
while (Current = lsquare) do PrimExpr := ParseIndex(PrimExpr);
end;
if Current.Token = tk_sum then
if Current.Value = '++' then
PrimExpr := TUnaryOp.Create(Next(PostInc), PrimExpr, True, DocPos)
else if Current.Value = '--' then
PrimExpr := TUnaryOp.Create(Next(PostInc), PrimExpr, True, DocPos);
Result := PrimExpr;
end;
function TParser.ParsePrimary: TBaseNode;
var op:TToken;
begin
if IS_UNARY then
begin
op := Next(PostInc);
Result := TUnaryOp.Create(op, ParsePrimary(), False, DocPos)
end
else if Current = keyword('time') then
begin
Next();
Result := TTimeNow.Create(DocPos);
end
else if (Current.Token in ATOM) or IS_ENCLOSURE then
begin
Result := ParseAtom();
end
else if Current = lparen then
begin
Next();
OldLineInsenstive := FLineInsenstive;
FLineInsenstive := True;
Result := ParseExpression(False);
ExpectAndInc(rparen, PostInc);
FLineInsenstive := OldLineInsenstive;
end
else
Result := nil;
if Result <> nil then
Result := ParsePostPrimary(Result);
end;
function TParser.RHSExpr(Left:TBaseNode; leftPrecedence:Int8=0): TBaseNode;
var
precedence,nextPrecedence,assoc:Int8;
Right: TBaseNode;
op:TToken;
function IfExpr(Left,Right:TBaseNode): TIfExpression; inline;
var Condition:TBaseNode;
begin
Condition := Right;
ExpectAndInc(Keyword('else'));
Right := ParseExpression(False);
Result := TIfExpression.Create(Condition,Left,Right, DocPos);
end;
function Operation(op:TToken; Left,Right:TBaseNode): TBaseNode; inline;
begin
if op.token = tk_assign then
Result := TAssignment.Create(op, Left, Right, DocPos)
else if op = Keyword('if') then
Result := IfExpr(Left, Right)
else
Result := TBinOp.Create(op, left, right, DocPos);
end;
begin
while True do
begin
precedence := OperatorPrecedence;
if precedence < leftPrecedence then
Exit(Left);
op := Next(PostInc);
right := ParsePrimary();
if right = nil then RaiseException(eInvalidExpression);
nextPrecedence := OperatorPrecedence;
if precedence < nextPrecedence then
Right := RHSExpr(right, precedence+1)
else if precedence = nextPrecedence then
begin
assoc := precedence + OperatorAssoc;
Right := RHSExpr(right, assoc);
end;
Left := Operation(op, left, right);
end;
Result := Left;
end;
function TParser.ParseExpression(ExpectSeparator:Boolean=True): TBaseNode;
begin
Result := ParsePrimary();
if (Result <> nil) then
Result := RHSExpr(Result);
{$IFDEF loose_semicolon}
OldLineInsenstive := FLineInsenstive;
FLineInsenstive := False;
if NextIf(tk_newline) then Exit;
FLineInsenstive := OldLineInsenstive;
{$ENDIF}
if (ExpectSeparator) then
ExpectAndInc(tk_semicolon, PostInc);
end;
function TParser.ParseExpressionList(Insensitive:Boolean; AllowEmpty:Boolean=False): TNodeArray;
var
expr: TBaseNode;
top: Int32;
begin
if Insensitive then
begin
OldLineInsenstive := FLineInsenstive;
FLineInsenstive := True;
end;
top := 0;
while True do
begin
expr := ParseExpression(False);
if (expr = nil) then
begin
if (not AllowEmpty) then RaiseException(eInvalidExpression);
break;
end;
SetLength(Result, top + 1);
Result[top] := expr;
Inc(top);
if not NextIf(tk_comma) then
break;
end;
if Insensitive then
FLineInsenstive := OldLineInsenstive;
end;
function TParser.ParseVarList(Insensitive:Boolean): TVarArray;
var top: Int32;
begin
if Insensitive then
begin
OldLineInsenstive := FLineInsenstive;
FLineInsenstive := True;
end;
top := 0;
while Current.token = tk_ident do
begin
SetLength(Result, top + 1);
Result[top] := TVariable.Create(Current.Value, DocPos);
Inc(top);
if (Next(PreInc).Token = tk_comma) then Next() else break;
end;
if Insensitive then
FLineInsenstive := OldLineInsenstive;
end;
function TParser.ParseStatement: TBaseNode;
begin
Result := nil;
{$IFDEF loose_semicolon}SkipNewline;{$ENDIF}
if Current.token in EXPRESSION then
begin
Result := ParseExpression(True);
if not(Result is TAssignment) then
Result := TStatement.Create(Result, DocPos);
end
else if(Current.token = tk_keyword) then
begin
if (Current.value = 'var') then
Result := ParseVardecl()
else if (Current.value = 'if') then
Result := ParseIf()
else if (Current.value = 'while') then
Result := ParseWhile()
else if (Current.value = 'repeat') then
Result := ParseRepeat()
else if (Current.value = 'for') then
Result := ParseFor()
//else if (Current.value = 'repeat') then
// result := ParseRepeat()
else if (Current.value = 'continue') then
if FLooping = 0 then
RaiseExceptionFmt(eNotAllowedOutsideLoop, ['`continue`'])
else
Result := ParseContinue()
else if (Current.value = 'break') then
if FLooping = 0 then
RaiseExceptionFmt(eNotAllowedOutsideLoop, ['`break`'])
else
Result := ParseBreak()
(*
else if (Current.value = 'pass') then
Result := ParsePass() *)
else if (Current.value = 'return') then
Result := ParseReturn()
else if (Current.value = 'func') then
Result := ParseFunction()
else if (Current.value = 'print') then
Result := ParsePrint()
else
RaiseExceptionFmt(eUnexpectedKeyword, [current.Value]);
end
else if not(Current.token in SEPARATORS) then
RaiseExceptionFmt(eUnexpectedOperation, [current.ToString]);
{$IFDEF loose_semicolon}
SkipTokens(SEPARATORS);
{$ELSE}
NextIf(tk_semicolon);
{$ENDIF}
end;
function TParser.ParseStatements(EndKeywords:array of string; Increase:Boolean=False): TNodeArray;
var
prim:TBaseNode;
begin
SetLength(Result, 0);
while (Current.Token <> tk_unknown) and (not StringContains(EndKeywords, Current.value)) do
begin
prim := self.ParseStatement();
{$IFDEF loose_semicolon}SkipNewline;{$ENDIF}
if prim <> nil then
begin
SetLength(Result, Length(Result)+1);
Result[High(Result)] := prim;
end;
end;
if Length(EndKeywords) <> 0 then
Expect(EndKeywords);
if Increase then
Next;
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 Plugin.Forms;
interface
uses WinApi.windows, {$IFDEF FMX} FMX.Forms, FMX.Controls, {$ELSE} VCL.Forms,
VCL.Controls, {$ENDIF} System.classes, System.SysUtils,
Plugin.Service, Plugin.Interf;
type
TPluginExecuteService = class(TPluginService, IPluginExecute)
protected
FSubTypeID: Int64;
FParams: String;
FConnectionString: string;
FUser, FPass: string;
FFilial: integer;
FAppUser: string;
private
procedure SetSubTypeID(const Value: Int64);
protected
destructor Destroy; override;
procedure SetForm(const Value: TForm); virtual;
function GetForm(AParent: THandle): TForm; virtual;
function GetCaption: string; virtual;
function GetSubTypeID: Int64; virtual;
{ function GetHandle:THandle;
procedure SetHandle(AHandle:THandle);
}
procedure Connection(const AConnectionString: string); virtual;
procedure User(const AFilial: integer; const AAppUser: string); virtual;
procedure Sync(const AJson: string); virtual;
procedure Execute(const AModal: boolean); virtual;
procedure SetParams(AJsonParams: String);
function GetAuthor: string; virtual;
function GetName: string; virtual;
function GetVersion: string; virtual;
function GetDescription: string; virtual;
public
property SubTypeID: Int64 read GetSubTypeID write SetSubTypeID;
end;
{$IFDEF FMX}
TFormClass = class of TForm;
{$ENDIF}
TPluginFormService = class(TPluginExecuteService)
protected
FCaption: string;
FFormClass: TFormClass;
procedure Init; virtual;
public
constructor Create(AFormClass: TFormClass; ACaption: String); virtual;
function GetCaption: string; override;
procedure Execute(const AModal: boolean); override;
procedure Embedded(const AParent: THandle); override;
procedure DoStart; override;
end;
procedure Register;
implementation
uses System.classes.Helper, System.Rtti;
procedure Register;
begin
// RegisterComponents('Store',[TPluginFormService]);
end;
procedure TPluginExecuteService.Connection(const AConnectionString: string);
begin
FConnectionString := AConnectionString;
if not assigned(FForm) then
exit;
if Supports(FForm, IPluginExecuteBase) then
(FForm as IPluginExecuteBase).Connection(AConnectionString)
else
begin
// DO NOT CHANGE NAMES
FForm.ContextProperties['ConnectionString'] := AConnectionString;
end;
end;
destructor TPluginExecuteService.Destroy;
begin
if FOwned then
FreeAndNil(FForm);
inherited;
end;
procedure TPluginExecuteService.Execute(const AModal: boolean);
begin
if not assigned(FForm) then
exit;
if AModal then
try
FForm.ShowModal
finally
FForm.Release
end
else
FForm.Show;
end;
function TPluginExecuteService.GetAuthor: string;
begin
result := 'Storeware';
end;
function TPluginExecuteService.GetCaption: string;
begin
if assigned(FForm) then
result := FForm.Caption
else
result := '';
end;
function TPluginExecuteService.GetDescription: string;
begin
result := 'Plugin';
end;
function TPluginExecuteService.GetForm(AParent: THandle): TForm;
begin
result := FForm;
if AParent > 0 then
begin
{$IFDEF FMX}
{$ELSE}
WinApi.windows.SetParent(FForm.Handle, AParent);
{$ENDIF}
end;
end;
{
function TPluginExecuteService.GetHandle: THandle;
begin
result := FHandle;
end;
}
function TPluginExecuteService.GetName: string;
begin
result := 'Storeware';
end;
function TPluginExecuteService.GetVersion: string;
begin
result := '01.00';
end;
function TPluginExecuteService.GetSubTypeID: Int64;
begin
result := FSubTypeID;
end;
procedure TPluginExecuteService.SetForm(const Value: TForm);
begin
FOwned := false;
if assigned(FForm) then
FreeAndNil(FForm);
FForm := Value;
Connection(FConnectionString);
User(FFilial, FAppUser);
end;
procedure TPluginExecuteService.SetParams(AJsonParams: String);
begin
FParams := AJsonParams;
end;
procedure TPluginExecuteService.SetSubTypeID(const Value: Int64);
begin
FSubTypeID := Value;
end;
{ procedure TPluginExecuteService.SetHandle(AHandle: THandle);
begin
FHandle := AHandle;
end;
}
procedure TPluginExecuteService.Sync(const AJson: string);
begin
if not assigned(FForm) then
exit;
if Supports(FForm, IPluginExecuteBase) then
(FForm as IPluginExecuteBase).Sync(AJson)
else
begin
FForm.ContextInvokeMethod('Sync', [AJson]);
end;
end;
procedure TPluginExecuteService.User(const AFilial: integer;
const AAppUser: string);
begin
FFilial := AFilial;
FAppUser := AAppUser;
if not assigned(FForm) then
exit;
if Supports(FForm, IPluginExecuteBase) then
(FForm as IPluginExecuteBase).User(AFilial, AAppUser)
else
begin
FForm.ContextProperties['Filial'] := AFilial;
FForm.ContextProperties['Usuario'] := AAppUser;
end;
end;
{ TPluginFormService }
constructor TPluginFormService.Create(AFormClass: TFormClass; ACaption: String);
begin
inherited Create;
FFormClass := AFormClass;
FCaption := ACaption;
end;
procedure TPluginFormService.DoStart;
begin
inherited;
end;
procedure TPluginFormService.Embedded(const AParent: THandle);
begin
Init;
inherited;
end;
procedure TPluginFormService.Execute(const AModal: boolean);
begin
Init;
inherited;
end;
function TPluginFormService.GetCaption: string;
begin
if FCaption <> '' then
result := FCaption
else
result := inherited GetCaption;
end;
procedure TPluginFormService.Init;
begin
FreeAndNil(FForm);
SetForm(FFormClass.Create(nil));
FForm.Caption := FCaption;
FOwned := true;
end;
end.
|
unit Model.Interceptor.Button;
interface
uses
StdCtrls,
Controls,
System.Classes;
type
TButton = class(StdCtrls.TButton)
private
State: Boolean;
Toogle: Boolean;
procedure SwitchState (Value : Boolean);
public
property Checked : Boolean read State write SwitchState;
property ToogleButton : Boolean read Toogle write Toogle;
procedure Click; override;
constructor Create(AOwner : TComponent); override;
end;
implementation
{ TButton }
procedure TButton.Click;
begin
if Toogle then
SwitchState(Not State);
inherited;
end;
constructor TButton.Create(AOwner: TComponent);
begin
inherited;
end;
procedure TButton.SwitchState(Value: Boolean);
begin
State := Not State;
if State then
begin
BevelKind := bkFlat;
BevelInner := bvLowered;
end
else
begin
BevelKind := bkNone;
BevelInner := bvRaised;
end;
end;
end.
|
unit Solid.Samples.DIP.Books.Step3;
interface
uses
System.IOUtils;
type
{ IBook }
IBook = interface
['{59A3B142-73C3-4BF5-AC7D-CEB422591DA2}']
function Read: TArray<Byte>;
end;
{ TPdfBook }
TPdfBook = class(TInterfacedObject, IBook)
private
FPath: string;
public
constructor Create(const APath: string);
function Read: TArray<Byte>;
end;
{ TKoboBook }
TKoboBook = class(TInterfacedObject, IBook)
private
FPath: string;
public
constructor Create(const APath: string);
function Read: TArray<Byte>;
end;
{ TMobiBook }
TMobiBook = class(TInterfacedObject, IBook)
private
FPath: string;
public
constructor Create(const APath: string);
function Read: TArray<Byte>;
end;
{ TBookReader }
TBookReader = class
private
FBook: IBook;
public
constructor Create(ABook: IBook);
procedure Display;
end;
implementation
{ TPdfBook }
constructor TPdfBook.Create(const APath: string);
begin
inherited Create;
FPath := APath;
end;
function TPdfBook.Read: TArray<Byte>;
begin
Result := TFile.ReadAllBytes(FPath);
end;
{ TKoboBook }
constructor TKoboBook.Create(const APath: string);
begin
inherited Create;
FPath := APath;
end;
function TKoboBook.Read: TArray<Byte>;
begin
Result := TFile.ReadAllBytes(FPath);
end;
{ TMobiBook }
constructor TMobiBook.Create(const APath: string);
begin
inherited Create;
FPath := APath;
end;
function TMobiBook.Read: TArray<Byte>;
begin
Result := TFile.ReadAllBytes(FPath);
end;
{ TBookReader }
constructor TBookReader.Create(ABook: IBook);
begin
inherited Create;
FBook := ABook;
end;
procedure TBookReader.Display;
var
LData: TArray<Byte>;
begin
LData := FBook.Read;
// TODO
end;
end.
|
unit pgFreeIDHelper;
// Модуль: "w:\common\components\rtl\Garant\PG\pgFreeIDHelper.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TpgFreeIDHelper" MUID: (56556EF3017C)
{$Include w:\common\components\rtl\Garant\PG\pgDefine.inc}
interface
{$If Defined(UsePostgres)}
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, daTypes
, pgConnection
, pgFunctionFactory
;
type
TpgFreeIDHelper = class(Tl3ProtoObject)
private
f_IntervalQuery: IdaTabledQuery;
f_FamilyID: TdaFamilyID;
f_GetFreeFunction: IdaFunction;
f_Connection: TpgConnection;
f_RegisterAllocFunction: IdaFunction;
f_Factory: IdaTableQueryFactory;
f_ExclusiveUse: Boolean;
private
function KeyPrefix(const aKey: AnsiString): AnsiString;
function RepairInterval(const aKey: AnsiString): Boolean;
function GetFreeFromTable(const aKey: AnsiString;
out theNumber: TdaDocID): Boolean;
function GetFreeFromReplica(const aKey: AnsiString;
out theNumber: TdaDocID): Boolean;
function TableKind: TdaTables;
function ExcludeFreeInReplica(const aKey: AnsiString;
anID: TdaDocID): Boolean;
procedure ExcludeFreeInTable(const aKey: AnsiString;
anID: TdaDocID);
protected
procedure pm_SetExclusiveUse(aValue: Boolean); virtual;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(aConnection: TpgConnection;
const aQueryFactory: IdaTableQueryFactory;
aFunctionFactory: TpgFunctionFactory;
aFamilyID: TdaFamilyID); reintroduce;
procedure ExcludeFree(const aKey: AnsiString;
anID: TdaDocID);
function GetFree(const aKey: AnsiString): TdaDocID;
function AnyRangesPresent(const aKey: AnsiString): Boolean;
procedure PutFree(const aKey: AnsiString;
anID: TdaDocID);
public
property ExclusiveUse: Boolean
read f_ExclusiveUse
write pm_SetExclusiveUse;
end;//TpgFreeIDHelper
{$IfEnd} // Defined(UsePostgres)
implementation
{$If Defined(UsePostgres)}
uses
l3ImplUses
, daScheme
, daSchemeConsts
, SysUtils
, pgInterfaces
, pgTableModifier
//#UC START# *56556EF3017Cimpl_uses*
//#UC END# *56556EF3017Cimpl_uses*
;
const
cFreeTblErr = 'Ошибка получения свободного номера';
ATTEMPT_AMOUNT = 20;
PAUSE_SIZE = 500;
{* 0,5 сек }
procedure TpgFreeIDHelper.pm_SetExclusiveUse(aValue: Boolean);
//#UC START# *565ECB810377_56556EF3017Cset_var*
//#UC END# *565ECB810377_56556EF3017Cset_var*
begin
//#UC START# *565ECB810377_56556EF3017Cset_impl*
if f_ExclusiveUse <> aValue then
begin
f_ExclusiveUse := aValue;
Assert(False);
//!! !!! Needs to be implemented !!!
end;
//#UC END# *565ECB810377_56556EF3017Cset_impl*
end;//TpgFreeIDHelper.pm_SetExclusiveUse
constructor TpgFreeIDHelper.Create(aConnection: TpgConnection;
const aQueryFactory: IdaTableQueryFactory;
aFunctionFactory: TpgFunctionFactory;
aFamilyID: TdaFamilyID);
//#UC START# *5656EF8D0161_56556EF3017C_var*
const
cGetFreeMap: array [MainTblsFamily..CurrentFamily] of AnsiString = (
'get_admin_free_num',
'get_free_num'
);
cRegisterAllocMap: array [MainTblsFamily..CurrentFamily] of AnsiString = (
'register_admin_alloc_num',
'register_alloc_num'
);
var
l_Description: IdaTableDescription;
l_FieldToSort: IdaSelectField;
//#UC END# *5656EF8D0161_56556EF3017C_var*
begin
//#UC START# *5656EF8D0161_56556EF3017C_impl*
inherited Create;
Assert(aFamilyID in [MainTblsFamily, CurrentFamily]);
f_FamilyID := aFamilyID;
f_Factory := aQueryFactory;
l_Description := TdaScheme.Instance.Table(TableKind);
try
f_IntervalQuery := f_Factory.MakeTabledQuery(f_Factory.MakeSimpleFromClause(l_Description));
f_IntervalQuery.AddSelectField(f_Factory.MakeSelectField('', l_Description.Field['start_num']));
l_FieldToSort := f_Factory.MakeSelectField('', l_Description.Field['last_num']);
f_IntervalQuery.AddSelectField(l_FieldToSort);
f_IntervalQuery.WhereCondition := f_Factory.MakeParamsCondition('', l_Description.Field['table_name'], da_copEqual, 'p_Key');
f_IntervalQuery.AddOrderBy(f_Factory.MakeSortField(l_FieldToSort));
f_IntervalQuery.Prepare;
finally
l_Description := nil;
end;
aConnection.SetRefTo(f_Connection);
f_GetFreeFunction := aFunctionFactory.MakeFunction(cGetFreeMap[aFamilyID]);
f_RegisterAllocFunction := aFunctionFactory.MakeFunction(cRegisterAllocMap[aFamilyID]);
//#UC END# *5656EF8D0161_56556EF3017C_impl*
end;//TpgFreeIDHelper.Create
function TpgFreeIDHelper.KeyPrefix(const aKey: AnsiString): AnsiString;
//#UC START# *565703DA0330_56556EF3017C_var*
const
c_BadFamily = -1;
//#UC END# *565703DA0330_56556EF3017C_var*
begin
//#UC START# *565703DA0330_56556EF3017C_impl*
Result := aKey;
If (f_FamilyID <> MainTblsFamily)
and (f_FamilyID = StrToIntDef(Copy(aKey, Length(aKey) - 2, 3), c_BadFamily)) // последние 3 символа являются номером семейства
then
SetLength(Result, Length(Result) - 3);
//#UC END# *565703DA0330_56556EF3017C_impl*
end;//TpgFreeIDHelper.KeyPrefix
function TpgFreeIDHelper.RepairInterval(const aKey: AnsiString): Boolean;
//#UC START# *5658228C0267_56556EF3017C_var*
//#UC END# *5658228C0267_56556EF3017C_var*
begin
//#UC START# *5658228C0267_56556EF3017C_impl*
Result := False;
Assert(False);
//!! !!! Needs to be implemented !!!
//#UC END# *5658228C0267_56556EF3017C_impl*
end;//TpgFreeIDHelper.RepairInterval
function TpgFreeIDHelper.GetFreeFromTable(const aKey: AnsiString;
out theNumber: TdaDocID): Boolean;
//#UC START# *5658229402A8_56556EF3017C_var*
var
l_AttemptNo: Integer;
l_Search: AnsiString;
l_ResultSet: IdaResultSet;
//#UC END# *5658229402A8_56556EF3017C_var*
begin
//#UC START# *5658229402A8_56556EF3017C_impl*
l_Search := KeyPrefix(aKey);
theNumber := -1;
for l_AttemptNo := 1 to ATTEMPT_AMOUNT + 1 do
begin
if l_AttemptNo > ATTEMPT_AMOUNT then
raise EpgError.Create('Не удалось получить свободный номер из таблицы FREE.');
if f_Connection.BeginTransaction([TableKind]) then
try
f_GetFreeFunction.Param['p_table_name'].AsString := aKey;
f_GetFreeFunction.Execute;
theNumber := f_GetFreeFunction.Param[f_GetFreeFunction.Name+'.Result'].AsLargeInt;
f_Connection.CommitTransaction;
Break; // пора прекращать крутить цикл
except
theNumber := -1;
f_Connection.RollbackTransaction;
Sleep(PAUSE_SIZE);
end;
end; // for
Result := theNumber <> -1;
//#UC END# *5658229402A8_56556EF3017C_impl*
end;//TpgFreeIDHelper.GetFreeFromTable
function TpgFreeIDHelper.GetFreeFromReplica(const aKey: AnsiString;
out theNumber: TdaDocID): Boolean;
//#UC START# *565822B40312_56556EF3017C_var*
//#UC END# *565822B40312_56556EF3017C_var*
begin
//#UC START# *565822B40312_56556EF3017C_impl*
Result := False;
if ExclusiveUse then
begin
Result := False;
Assert(False);
//!! !!! Needs to be implemented !!!
end;
//#UC END# *565822B40312_56556EF3017C_impl*
end;//TpgFreeIDHelper.GetFreeFromReplica
function TpgFreeIDHelper.TableKind: TdaTables;
//#UC START# *56A7208C003C_56556EF3017C_var*
const cTableKindMap: array [MainTblsFamily..CurrentFamily] of TdaTables = (
da_mtFree,
da_ftFree
);
//#UC END# *56A7208C003C_56556EF3017C_var*
begin
//#UC START# *56A7208C003C_56556EF3017C_impl*
Result := cTableKindMap[f_FamilyID];
//#UC END# *56A7208C003C_56556EF3017C_impl*
end;//TpgFreeIDHelper.TableKind
procedure TpgFreeIDHelper.ExcludeFree(const aKey: AnsiString;
anID: TdaDocID);
//#UC START# *5770DA7C004B_56556EF3017C_var*
//#UC END# *5770DA7C004B_56556EF3017C_var*
begin
//#UC START# *5770DA7C004B_56556EF3017C_impl*
if not ExcludeFreeInReplica(aKey, anID) then
ExcludeFreeInTable(aKey, anID);
//#UC END# *5770DA7C004B_56556EF3017C_impl*
end;//TpgFreeIDHelper.ExcludeFree
function TpgFreeIDHelper.ExcludeFreeInReplica(const aKey: AnsiString;
anID: TdaDocID): Boolean;
//#UC START# *57739A99016D_56556EF3017C_var*
//#UC END# *57739A99016D_56556EF3017C_var*
begin
//#UC START# *57739A99016D_56556EF3017C_impl*
Result := False;
if ExclusiveUse then
begin
Result := False;
Assert(False);
//!! !!! Needs to be implemented !!!
end;
//#UC END# *57739A99016D_56556EF3017C_impl*
end;//TpgFreeIDHelper.ExcludeFreeInReplica
procedure TpgFreeIDHelper.ExcludeFreeInTable(const aKey: AnsiString;
anID: TdaDocID);
//#UC START# *57739AA9019C_56556EF3017C_var*
var
l_AttemptNo: Integer;
l_Search: AnsiString;
//#UC END# *57739AA9019C_56556EF3017C_var*
begin
//#UC START# *57739AA9019C_56556EF3017C_impl*
l_Search := KeyPrefix(aKey);
for l_AttemptNo := 1 to ATTEMPT_AMOUNT + 1 do
begin
if l_AttemptNo > ATTEMPT_AMOUNT then
raise EpgError.Create('Не удалось получить свободный номер из таблицы FREE.');
if f_Connection.BeginTransaction([TableKind]) then
try
f_RegisterAllocFunction.Param['p_table_name'].AsString := aKey;
f_RegisterAllocFunction.Param['p_alloc_id'].AsLargeInt := anID;
f_RegisterAllocFunction.Execute;
f_Connection.CommitTransaction;
Break; // пора прекращать крутить цикл
except
f_Connection.RollbackTransaction;
Sleep(PAUSE_SIZE);
end;
end; // for
//#UC END# *57739AA9019C_56556EF3017C_impl*
end;//TpgFreeIDHelper.ExcludeFreeInTable
function TpgFreeIDHelper.GetFree(const aKey: AnsiString): TdaDocID;
//#UC START# *565589E102C3_56556EF3017C_var*
//#UC END# *565589E102C3_56556EF3017C_var*
begin
//#UC START# *565589E102C3_56556EF3017C_impl*
if not GetFreeFromReplica(aKey, Result) then
if not GetFreeFromTable(aKey, Result) then
// поиск и попытка освобождения залоченных интервалов
if not RepairInterval(aKey) then
raise EpgError.Create(cFreeTblErr)
else // вторая попытка
begin
if not GetFreeFromReplica(aKey, Result) then
if not GetFreeFromTable(aKey, Result) then
// выстрел в голову
raise EpgError.Create(cFreeTblErr);
end;
//#UC END# *565589E102C3_56556EF3017C_impl*
end;//TpgFreeIDHelper.GetFree
function TpgFreeIDHelper.AnyRangesPresent(const aKey: AnsiString): Boolean;
//#UC START# *56558EF30265_56556EF3017C_var*
var
l_ResultSet: IdaResultSet;
//#UC END# *56558EF30265_56556EF3017C_var*
begin
//#UC START# *56558EF30265_56556EF3017C_impl*
f_IntervalQuery.Param['p_Key'].AsString := KeyPrefix(aKey);
l_ResultSet := f_IntervalQuery.OpenResultSet;
try
Result := not l_ResultSet.IsEmpty;
finally
l_ResultSet := nil;
end;
//#UC END# *56558EF30265_56556EF3017C_impl*
end;//TpgFreeIDHelper.AnyRangesPresent
procedure TpgFreeIDHelper.PutFree(const aKey: AnsiString;
anID: TdaDocID);
//#UC START# *577CC0A10277_56556EF3017C_var*
{$IfNDef ReUseNumberOff} // запрещение возврата свободных номеров
var
l_Modifier: TpgTableModifier;
{$EndIf}
//#UC END# *577CC0A10277_56556EF3017C_var*
begin
//#UC START# *577CC0A10277_56556EF3017C_impl*
{$IfNDef ReUseNumberOff} // запрещение возврата свободных номеров
l_Modifier := TpgTableModifier.Create(TableKind, f_Connection, f_Factory.DataConverter);
try
l_Modifier.BeginTransaction;
try
l_Modifier.Params['table_name'].AsString := aKey;
l_Modifier.Params['start_num'].AsLargeInt := anID;
l_Modifier.Params['last_num'].AsLargeInt := 0;
l_Modifier.Insert;
l_Modifier.CommitTransaction;
except
l_Modifier.RollBackTransaction;
raise;
end;
finally
FreeAndNil(l_Modifier)
end;
{$EndIf}
//#UC END# *577CC0A10277_56556EF3017C_impl*
end;//TpgFreeIDHelper.PutFree
procedure TpgFreeIDHelper.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_56556EF3017C_var*
//#UC END# *479731C50290_56556EF3017C_var*
begin
//#UC START# *479731C50290_56556EF3017C_impl*
f_GetFreeFunction := nil;
f_RegisterAllocFunction := nil;
FreeAndNil(f_Connection);
f_IntervalQuery := nil;
f_Factory := nil;
inherited;
//#UC END# *479731C50290_56556EF3017C_impl*
end;//TpgFreeIDHelper.Cleanup
{$IfEnd} // Defined(UsePostgres)
end.
|
unit pgTableQueryFactory;
// Модуль: "w:\common\components\rtl\Garant\PG\pgTableQueryFactory.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TpgTableQueryFactory" MUID: (55F81B3F024D)
{$Include w:\common\components\rtl\Garant\PG\pgDefine.inc}
interface
{$If Defined(UsePostgres)}
uses
l3IntfUses
, l3ProtoObject
, daInterfaces
, pgInterfaces
, pgConnection
, daTypes
;
type
TpgTableQueryFactory = class(Tl3ProtoObject, IdaTableQueryFactory)
private
f_DataConverter: IpgDataConverter;
f_Connection: TpgConnection;
f_UserNameQuery: IdaTabledQuery;
private
function UserNameQuery: IdaTabledQuery;
protected
function MakeTabledQuery(const aFromClause: IdaFromClause): IdaTabledQuery;
function MakeSelectField(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
const anAlias: AnsiString = ''): IdaSelectField;
function MakeParamsCondition(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaCompareOperation;
const aParamName: AnsiString): IdaCondition;
function Get_DataConverter: IdaDataConverter;
function MakeLogicCondition(const aLeft: IdaCondition;
anOperation: TdaLogicOperation;
const aRight: IdaCondition): IdaCondition;
function MakeSubQueryCondition(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
const aQuery: IdaTabledQuery): IdaCondition;
function MakeSortField(const aSelectField: IdaSelectField;
aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField;
function MakeJoin(const aLeft: IdaFromClause;
const aRight: IdaFromClause;
aKind: TdaJoinKind): IdaJoin;
function MakeJoinCondition(const aLeftTableAlias: AnsiString;
const aLeftField: IdaFieldDescription;
const aRightTableAlias: AnsiString;
const aRightField: IdaFieldDescription): IdaCondition;
function MakeSimpleFromClause(const aTable: IdaTableDescription;
const anAlias: AnsiString = ''): IdaFromClause;
function MakeAggregateField(anOperation: TdaAggregateOperation;
const aField: IdaSelectField;
const anAlias: AnsiString): IdaSelectField;
function MakeBitwiseCondition(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaBitwiseOperator;
aValue: Int64): IdaCondition;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create(const aDataConverter: IpgDataConverter;
aConnection: TpgConnection); reintroduce;
class function Make(const aDataConverter: IpgDataConverter;
aConnection: TpgConnection): IdaTableQueryFactory; reintroduce;
end;//TpgTableQueryFactory
{$IfEnd} // Defined(UsePostgres)
implementation
{$If Defined(UsePostgres)}
uses
l3ImplUses
, daSelectField
, daParamsCondition
, pgTabledQuery
, daScheme
, SysUtils
, daLogicCondition
, daSubQueryCondition
, daSortField
, daJoin
, daJoinCondition
, daFromTable
, daAggregateField
, daBitwiseCondition
//#UC START# *55F81B3F024Dimpl_uses*
//#UC END# *55F81B3F024Dimpl_uses*
;
constructor TpgTableQueryFactory.Create(const aDataConverter: IpgDataConverter;
aConnection: TpgConnection);
//#UC START# *55F81B5C029C_55F81B3F024D_var*
//#UC END# *55F81B5C029C_55F81B3F024D_var*
begin
//#UC START# *55F81B5C029C_55F81B3F024D_impl*
inherited Create;
f_DataConverter := aDataConverter;
aConnection.SetRefTo(f_Connection);
//#UC END# *55F81B5C029C_55F81B3F024D_impl*
end;//TpgTableQueryFactory.Create
class function TpgTableQueryFactory.Make(const aDataConverter: IpgDataConverter;
aConnection: TpgConnection): IdaTableQueryFactory;
var
l_Inst : TpgTableQueryFactory;
begin
l_Inst := Create(aDataConverter, aConnection);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TpgTableQueryFactory.Make
function TpgTableQueryFactory.UserNameQuery: IdaTabledQuery;
//#UC START# *56F11DEF037F_55F81B3F024D_var*
//#UC END# *56F11DEF037F_55F81B3F024D_var*
begin
//#UC START# *56F11DEF037F_55F81B3F024D_impl*
if f_UserNameQuery = nil then
begin
f_UserNameQuery := MakeTabledQuery(MakeSimpleFromClause(TdaScheme.Instance.Table(da_mtUsers)));
f_UserNameQuery.AddSelectField(MakeSelectField('', TdaScheme.Instance.Table(da_mtUsers)['user_name']));
f_UserNameQuery.WhereCondition := MakeParamsCondition('', TdaScheme.Instance.Table(da_mtUsers)['ID'], da_copEqual, 'p_UserID');
f_UserNameQuery.Prepare;
end;
Result := f_UserNameQuery;
//#UC END# *56F11DEF037F_55F81B3F024D_impl*
end;//TpgTableQueryFactory.UserNameQuery
function TpgTableQueryFactory.MakeTabledQuery(const aFromClause: IdaFromClause): IdaTabledQuery;
//#UC START# *5549C65D038D_55F81B3F024D_var*
//#UC END# *5549C65D038D_55F81B3F024D_var*
begin
//#UC START# *5549C65D038D_55F81B3F024D_impl*
Result := TpgTabledQuery.Make(Self, f_DataConverter, aFromClause, f_Connection);
//#UC END# *5549C65D038D_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeTabledQuery
function TpgTableQueryFactory.MakeSelectField(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
const anAlias: AnsiString = ''): IdaSelectField;
//#UC START# *559B80BD00A8_55F81B3F024D_var*
//#UC END# *559B80BD00A8_55F81B3F024D_var*
begin
//#UC START# *559B80BD00A8_55F81B3F024D_impl*
Result := TdaSelectField.Make(aTableAlias, aField, anAlias);
//#UC END# *559B80BD00A8_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeSelectField
function TpgTableQueryFactory.MakeParamsCondition(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaCompareOperation;
const aParamName: AnsiString): IdaCondition;
//#UC START# *559B810003CF_55F81B3F024D_var*
//#UC END# *559B810003CF_55F81B3F024D_var*
begin
//#UC START# *559B810003CF_55F81B3F024D_impl*
Result := TdaParamsCondition.Make(aTableAlias, aField, anOperation, aParamName);
//#UC END# *559B810003CF_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeParamsCondition
function TpgTableQueryFactory.Get_DataConverter: IdaDataConverter;
//#UC START# *55C1BFA402E3_55F81B3F024Dget_var*
//#UC END# *55C1BFA402E3_55F81B3F024Dget_var*
begin
//#UC START# *55C1BFA402E3_55F81B3F024Dget_impl*
Result := f_DataConverter;
//#UC END# *55C1BFA402E3_55F81B3F024Dget_impl*
end;//TpgTableQueryFactory.Get_DataConverter
function TpgTableQueryFactory.MakeLogicCondition(const aLeft: IdaCondition;
anOperation: TdaLogicOperation;
const aRight: IdaCondition): IdaCondition;
//#UC START# *56405475021D_55F81B3F024D_var*
//#UC END# *56405475021D_55F81B3F024D_var*
begin
//#UC START# *56405475021D_55F81B3F024D_impl*
Result := TdaLogicCondition.Make(aLeft, anOperation, aRight);
//#UC END# *56405475021D_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeLogicCondition
function TpgTableQueryFactory.MakeSubQueryCondition(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
const aQuery: IdaTabledQuery): IdaCondition;
//#UC START# *5641E5DB02C3_55F81B3F024D_var*
//#UC END# *5641E5DB02C3_55F81B3F024D_var*
begin
//#UC START# *5641E5DB02C3_55F81B3F024D_impl*
Result := TdaSubQueryCondition.Make(aTableALias, aField, aQuery);
//#UC END# *5641E5DB02C3_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeSubQueryCondition
function TpgTableQueryFactory.MakeSortField(const aSelectField: IdaSelectField;
aSortOrder: TdaSortOrder = daTypes.da_soAscending): IdaSortField;
//#UC START# *56811844032C_55F81B3F024D_var*
//#UC END# *56811844032C_55F81B3F024D_var*
begin
//#UC START# *56811844032C_55F81B3F024D_impl*
Result := TdaSortField.Make(aSelectField, aSortOrder);
//#UC END# *56811844032C_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeSortField
function TpgTableQueryFactory.MakeJoin(const aLeft: IdaFromClause;
const aRight: IdaFromClause;
aKind: TdaJoinKind): IdaJoin;
//#UC START# *574584D802F6_55F81B3F024D_var*
//#UC END# *574584D802F6_55F81B3F024D_var*
begin
//#UC START# *574584D802F6_55F81B3F024D_impl*
Result := TdaJoin.Make(Self, aLeft, aRight, aKind);
//#UC END# *574584D802F6_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeJoin
function TpgTableQueryFactory.MakeJoinCondition(const aLeftTableAlias: AnsiString;
const aLeftField: IdaFieldDescription;
const aRightTableAlias: AnsiString;
const aRightField: IdaFieldDescription): IdaCondition;
//#UC START# *574BF2B20123_55F81B3F024D_var*
//#UC END# *574BF2B20123_55F81B3F024D_var*
begin
//#UC START# *574BF2B20123_55F81B3F024D_impl*
Result := TdaJoinCondition.Make(aLeftTableAlias, aLeftField, aRightTableAlias, aRightField);
//#UC END# *574BF2B20123_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeJoinCondition
function TpgTableQueryFactory.MakeSimpleFromClause(const aTable: IdaTableDescription;
const anAlias: AnsiString = ''): IdaFromClause;
//#UC START# *574C32760314_55F81B3F024D_var*
//#UC END# *574C32760314_55F81B3F024D_var*
begin
//#UC START# *574C32760314_55F81B3F024D_impl*
Result := TdaFromTable.Make(Self, aTable, anAlias);
//#UC END# *574C32760314_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeSimpleFromClause
function TpgTableQueryFactory.MakeAggregateField(anOperation: TdaAggregateOperation;
const aField: IdaSelectField;
const anAlias: AnsiString): IdaSelectField;
//#UC START# *5755313E0083_55F81B3F024D_var*
//#UC END# *5755313E0083_55F81B3F024D_var*
begin
//#UC START# *5755313E0083_55F81B3F024D_impl*
Result := TdaAggregateField.Make(anOperation, aField, anAlias);
//#UC END# *5755313E0083_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeAggregateField
function TpgTableQueryFactory.MakeBitwiseCondition(const aTableAlias: AnsiString;
const aField: IdaFieldDescription;
anOperation: TdaBitwiseOperator;
aValue: Int64): IdaCondition;
//#UC START# *57A9A66C00A7_55F81B3F024D_var*
//#UC END# *57A9A66C00A7_55F81B3F024D_var*
begin
//#UC START# *57A9A66C00A7_55F81B3F024D_impl*
Result := TdaBitwiseCondition.Make(aTableAlias, aField, anOperation, aValue);
//#UC END# *57A9A66C00A7_55F81B3F024D_impl*
end;//TpgTableQueryFactory.MakeBitwiseCondition
procedure TpgTableQueryFactory.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_55F81B3F024D_var*
//#UC END# *479731C50290_55F81B3F024D_var*
begin
//#UC START# *479731C50290_55F81B3F024D_impl*
f_UserNameQuery := nil;
f_DataConverter := nil;
FreeAndNil(f_Connection);
inherited;
//#UC END# *479731C50290_55F81B3F024D_impl*
end;//TpgTableQueryFactory.Cleanup
{$IfEnd} // Defined(UsePostgres)
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 6.0 for Delphi and C++Builder ::
:: ::
:: QRGraphcon TQRGraphicCanvas ::
:: ::
:: Copyright (c) 2013 QBS Software ::
:: All Rights Reserved ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::}
unit QRGraphcon;
interface
uses Messages, Windows, Classes, Controls, StdCtrls, SysUtils, Graphics,
Forms, ExtCtrls, Dialogs, Printers, ComCtrls,qrxdocument,
QRPrntr, QuickRpt, QR6Const, qrctrls;
type
TQRGraphicCanvas = class;
TQRGraphicOnPrintEvent = procedure (sender : TQRGraphicCanvas; grect : TRect) of object;
TQRGraphicOnCommandEvent = procedure (sender : TQRGraphicCanvas) of object;
TQRGraphicCanvas = class(TQRPrintable)
private
FBeforePrint : TQRGraphicOnPrintEvent;
commlist : TStringList;
procedure SetBeforePrint( value : TQRGraphicOnPrintEvent);
protected
procedure Paint; override;
procedure Print(OfsX, OfsY : integer); override;
procedure RenderComms( acanvas : TCanvas; OffX, OffY : extended);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetCanvas: TCanvas;
// graphic methods
procedure TextOut( x,y : integer; s : string);
procedure MoveTo( x,y : integer);
procedure LinetoTo( x,y : integer);
procedure Ellipse( x,y,w,h : integer);
procedure rectangle( x,y,w,h : integer);
procedure setPenWidth(w : extended);
procedure setPenColor( pencolor : TColor);
procedure setBrushColor( brushcolor : TColor);
procedure setPenStyle( pstyle : TPenstyle);
procedure setBrushStyle( bstyle : TBrushstyle);
procedure setFont( s : string);
procedure setFontSize( h : integer);
published
property BeforePrint: TQRGraphicOnPrintEvent read FBeforePrint write SetBeforePrint;
property Visible;
property XLColumn;
property Font;
property Transparent;
property color;
end;
implementation
uses qrxmlsfilt;
constructor TQRGraphicCanvas.Create(AOwner: TComponent);
begin
commlist := TStringList.create;
inherited create(AOwner);
end;
destructor TQRGraphicCanvas.Destroy;
begin
commlist.Free;
inherited Destroy;
end;
procedure TQRGraphicCanvas.SetBeforePrint( value : TQRGraphicOnPrintEvent);
begin
FBeforePrint := value;
end;
function TQRGraphicCanvas.GetCanvas: TCanvas;
begin
result := TQuickrep(parentreport).QRPrinter.Canvas;
end;
// graphic methods
procedure TQRGraphicCanvas.TextOut( x,y : integer; s : string);
begin
commlist.Add(inttostr(integer(TVecComm.textout))+'?'+inttostr(x)+'?'+inttostr(y)+'?'''+ s + '''');
end;
procedure TQRGraphicCanvas.MoveTo( x,y : integer);
begin
commlist.Add(inttostr(integer(TVecComm.moveto))+'?'+inttostr(x)+'?'+inttostr(y));
end;
procedure TQRGraphicCanvas.LinetoTo( x,y : integer);
begin
commlist.Add(inttostr(integer(TVecComm.lineto))+'?'+inttostr(x)+'?'+inttostr(y));
end;
procedure TQRGraphicCanvas.Ellipse( x,y,w,h : integer);
begin
commlist.Add(inttostr(integer(TVecComm.ellipse))+'?'+inttostr(x)+'?'+inttostr(y)+'?'+inttostr(w)+'?'+inttostr(h));
end;
procedure TQRGraphicCanvas.rectangle( x,y,w,h : integer);
begin
commlist.Add(inttostr(integer(TVecComm.rectangle))+'?'+inttostr(x)+'?'+inttostr(y)+'?'+inttostr(w)+'?'+inttostr(h));
end;
procedure TQRGraphicCanvas.setPenWidth(w : extended);
begin
commlist.Add(inttostr(integer(TVecComm.penwidth))+'?'+floattostr(w));
end;
procedure TQRGraphicCanvas.setPenColor( pencolor : TColor);
begin
commlist.Add(inttostr(integer(TVecComm.pencolor))+'?'+inttostr(integer(pencolor)));
end;
procedure TQRGraphicCanvas.setBrushColor( brushcolor : TColor);
begin
commlist.Add(inttostr(integer(TVecComm.brushcolor))+'?'+inttostr(integer(brushcolor)));
end;
procedure TQRGraphicCanvas.setPenStyle( pstyle : TPenstyle);
begin
commlist.Add(inttostr(integer(TVecComm.penstyle))+'?'+inttostr(integer(pstyle)));
end;
procedure TQRGraphicCanvas.setBrushStyle( bstyle : TBrushstyle);
begin
commlist.Add(inttostr(integer(TVecComm.brushstyle))+'?'+inttostr(integer(bstyle)));
end;
procedure TQRGraphicCanvas.setFont( s : string);
begin
commlist.Add(inttostr(integer(TVecComm.setFont))+'?'+s+'''');
end;
procedure TQRGraphicCanvas.setFontSize( h : integer);
begin
commlist.Add(inttostr(integer(TVecComm.setFontSize))+'?'+inttostr(h));
end;
procedure TQRGraphicCanvas.Paint;
begin
if csDesigning in ComponentState then
with inherited Canvas do
begin
Pen.Style := psSolid;
Brush.Style := bsClear;
Rectangle(0, 0, Width, Height);
end;
end;
function randomName : string;
var
k : integer;
begin
result := '';
for k := 1 to 10 do result := result + chr(random(22)+ord('a'));
end;
procedure SplitString( ss : string; sep : char; var aList : TStringlist );
const
MAX_STRING = 65000;
var
k : integer;
defstr : string;
begin
defstr := ss;
aList.Clear;
while length( defstr) > 0 do
begin
k := pos( sep, defstr );
if k = 0 then
begin
if length( defstr) > 0 then
alist.add(defstr);
defstr := '';
end
else if trim(copy( defstr, 1, k-1)) <> '' then
alist.add(trim(copy( defstr, 1, k-1)));
defstr := trim(copy( defstr, k+1, MAX_STRING ));
end;
end;
procedure TQRGraphicCanvas.RenderComms( acanvas : TCanvas; OffX, OffY : extended);
var
combits : TStringlist;
FZoomFactor : double;
k : integer;
function ScaleNumber( ns : string) : integer;
begin
result := round(FZoomFactor*strtoint(ns)/100.0);
end;
function ScaleXNumber( ns : string) : integer;
begin
result := round(FZoomFactor*(strtoint(ns)-OffX)/100.0);
end;
function ScaleYNumber( ns : string) : integer;
begin
result := round(FZoomFactor*(strtoint(ns)-OffY)/100.0);
end;
begin
combits := TStringlist.Create;
FZoomFactor := 100.0;
try
for k := 0 to commlist.Count-1 do
begin
splitstring(commlist[k],'?',combits);
if combits.Count=0 then continue;
case TVecComm(strtoint(combits[0])) of
TVecComm.moveto: acanvas.Moveto( ScalexNumber(combits[1]),ScaleyNumber(combits[2]));
TVecComm.lineto: acanvas.Lineto( ScalexNumber(combits[1]),ScaleyNumber(combits[2]));
TVecComm.rectangle: acanvas.rectangle( ScalexNumber(combits[1]),ScaleyNumber(combits[2]),ScalexNumber(combits[3]),ScaleyNumber(combits[4]));
TVecComm.ellipse: acanvas.Ellipse( ScalexNumber(combits[1]),ScaleyNumber(combits[2]),ScalexNumber(combits[3]),ScaleyNumber(combits[4]));
TVecComm.pencolor: acanvas.pen.Color := strtoint(combits[1]);
TVecComm.brushcolor: acanvas.brush.Color := strtoint(combits[1]);
TVecComm.penstyle: acanvas.pen.Style := TPenstyle(strtoint(combits[1]));
TVecComm.brushstyle: acanvas.brush.Style := TBrushstyle(strtoint(combits[1]));
TVecComm.penwidth: acanvas.pen.width := ScaleNumber(combits[1]);
TVecComm.textout: acanvas.textout(ScaleNumber(combits[1]),ScaleNumber(combits[2]),combits[3]);
TVecComm.setFont: acanvas.Font.Name := combits[1];
TVecComm.setFontSize: acanvas.Font.Size := ScaleNumber(combits[1]);
else ;
end;
end;
finally
combits.Free;
end;
end;
procedure TQRGraphicCanvas.Print(OfsX, OfsY : integer);
var
gcanvas : TCanvas;
CanvasRect : TRect ;
cRgn : HRGN ;
expimg : TQRImage;
begin
// determine the rectangle of the canvas of this control:
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;
commlist.Clear;
if not transparent then
begin
// load up commlist with background painting instructions
self.setPenStyle(psSolid);
self.setBrushStyle(bsSolid);
self.setBrushColor(color);
self.setPenColor(color);
self.Rectangle(CanvasRect.left, CanvasRect.top, CanvasRect.right, CanvasRect.bottom);
end;
gcanvas.Font.Assign(self.Font);
if assigned( FBeforePrint) then
FBeforePrint( self, canvasRect );
RenderComms( gcanvas,0,0);
SelectClipRgn(QRPrinter.Canvas.Handle,0);
deleteObject(cRgn);
// exporting
if not parentreport.Exporting then exit;
if parentreport.ExportFilter is TQRXDocumentfilter then
begin
TQRXDocumentfilter( parentreport.ExportFilter).AcceptVector(commlist);
exit;
end;
expimg := TQRImage.Create(parentreport);
expimg.Top := top;
expimg.Left := left;
expimg.width := width;
expimg.height := height;
expimg.Name := randomName;
expimg.Picture.Bitmap.Width := self.Width;
expimg.Picture.Bitmap.Height := Height;
expimg.Name := 'Graphcon';
self.setPenStyle(psSolid);
self.setPenColor(Font.Color);
RenderComms( expimg.Picture.Bitmap.Canvas, CanvasRect.left, CanvasRect.top);
parentreport.ExportFilter.AcceptGraphic(CanvasRect.left,CanvasRect.top, expimg);
expimg.Free;
end;
end.
|
unit DW.iOSapi.Helpers;
{*******************************************************}
{ }
{ Kastri }
{ }
{ Delphi Worlds Cross-Platform Library }
{ }
{ Copyright 2020-2021 Dave Nottage under MIT license }
{ which is located in the root folder of this library }
{ }
{*******************************************************}
{$I DW.GlobalDefines.inc}
interface
uses
// RTL
System.Sensors,
// macOS
Macapi.ObjectiveC,
// iOS
iOSapi.Foundation, iOSapi.UIKit;
type
UIApplication = interface(iOSapi.UIKit.UIApplication)
['{7228BEAE-1B3A-4EBC-A87C-03982C8EC742}']
function isRegisteredForRemoteNotifications: Boolean; cdecl;
end;
TUIApplication = class(TOCGenericImport<UIApplicationClass, UIApplication>) end;
TiOSHelperEx = record
public
class procedure AddObserver(const AObserver: Pointer; const AMethod: MarshaledAString; const AName: NSString;
const AObject: NSObject = nil); overload; static;
class procedure AddObserver(const AObserver: Pointer; const AMethod: MarshaledAString; const AName: string;
const AObject: NSObject = nil); overload; static;
class function GetLocationManagerAuthorization: TAuthorizationType; static;
class function HasBackgroundMode(const AMode: string): Boolean; static;
class function IsBackground: Boolean; static;
class function IsIPhoneX: Boolean; static;
//!!! ADictionary must be a JSON dictionary!!
class function NSDictionaryToJSON(const ADictionary: NSDictionary): string; static;
class function NSDictionaryToString(const ADictionary: NSDictionary): string; static;
class function SharedApplication: UIApplication; static;
class function StandardUserDefaults: NSUserDefaults; static;
end;
implementation
uses
// RTL
System.SysUtils,
// iOS
iOSapi.CoreLocation, iOSapi.Helpers,
// macOS
Macapi.ObjCRuntime, Macapi.Helpers;
class procedure TiOSHelperEx.AddObserver(const AObserver: Pointer; const AMethod: MarshaledAString; const AName: NSString; const AObject: NSObject = nil);
var
LObject: Pointer;
begin
if AObject <> nil then
LObject := NSObjectToID(AObject)
else
LObject := nil;
TiOSHelper.DefaultNotificationCenter.addObserver(AObserver, sel_getUid(AMethod), NSObjectToID(AName), LObject);
end;
class procedure TiOSHelperEx.AddObserver(const AObserver: Pointer; const AMethod: MarshaledAString; const AName: string; const AObject: NSObject = nil);
begin
AddObserver(AObserver, AMethod, StrToNSStr(AName), AObject);
end;
class function TiOSHelperEx.GetLocationManagerAuthorization: TAuthorizationType;
begin
case TCLLocationManager.OCClass.authorizationStatus of
kCLAuthorizationStatusNotDetermined:
Result := TAuthorizationType.atNotSpecified;
kCLAuthorizationStatusDenied,
kCLAuthorizationStatusRestricted:
Result := TAuthorizationType.atUnauthorized;
kCLAuthorizationStatusAuthorizedWhenInUse,
kCLAuthorizationStatusAuthorized:
Result := TAuthorizationType.atAuthorized;
else
Result := TAuthorizationType.atNotSpecified;
end;
end;
class function TiOSHelperEx.HasBackgroundMode(const AMode: string): Boolean;
var
LBundle: NSBundle;
LPointer: Pointer;
LModesArray: NSArray;
LModeString: string;
I: Integer;
begin
Result := False;
LBundle := TiOSHelper.MainBundle;
LPointer := LBundle.infoDictionary.valueForKey(StrToNSStr('UIBackgroundModes')); // Do not localise
if LPointer = nil then
Exit; // <======
LModesArray := TNSArray.Wrap(LPointer);
for I := 0 to LModesArray.count - 1 do
begin
LModeString := NSStrToStr(TNSString.Wrap(LModesArray.objectAtIndex(I)));
if AMode.Equals(LModeString) then
Exit(True); // <======
end;
end;
class function TiOSHelperEx.IsBackground: Boolean;
begin
Result := SharedApplication.applicationState = UIApplicationStateBackground;
end;
class function TiOSHelperEx.IsIPhoneX: Boolean;
const
cIPhoneXHeight = 812;
var
LOrientation: UIInterfaceOrientation;
begin
Result := False;
// Might be safe enough to just use statusBarOrientation
if SharedApplication.keyWindow = nil then
LOrientation := SharedApplication.statusBarOrientation
else
LOrientation := SharedApplication.keyWindow.rootViewController.interfaceOrientation;
case LOrientation of
UIInterfaceOrientationPortrait, UIInterfaceOrientationPortraitUpsideDown:
Result := TiOSHelper.MainScreen.bounds.size.height = cIPhoneXHeight;
UIInterfaceOrientationLandscapeLeft, UIInterfaceOrientationLandscapeRight:
Result := TiOSHelper.MainScreen.bounds.size.width = cIPhoneXHeight;
end;
end;
class function TiOSHelperEx.NSDictionaryToJSON(const ADictionary: NSDictionary): string;
var
LData: NSData;
LString: NSString;
LError: NSError;
begin
LData := TNSJSONSerialization.OCClass.dataWithJSONObject(NSObjectToID(ADictionary), 0, Addr(LError));
if (LData <> nil) and (LError = nil) then
begin
LString := TNSString.Wrap(TNSString.Alloc.initWithData(LData, NSUTF8StringEncoding));
Result := NSStrToStr(LString);
end
else
Result := '';
end;
class function TiOSHelperEx.NSDictionaryToString(const ADictionary: NSDictionary): string;
var
I: Integer;
begin
// Just dumps the keys for now
Result := '';
for I := 0 to ADictionary.allKeys.count - 1 do
begin
if I > 0 then
Result := Result + #13#10;
Result := Result + NSStrToStr(TNSString.Wrap(ADictionary.allKeys.objectAtIndex(I)));
end;
end;
class function TiOSHelperEx.SharedApplication: UIApplication;
begin
Result := TUIApplication.Wrap(TUIApplication.OCClass.sharedApplication);
end;
class function TiOSHelperEx.StandardUserDefaults: NSUserDefaults;
begin
Result := TNSUserDefaults.Wrap(TNSUserDefaults.OCClass.standardUserDefaults);
end;
end.
|
unit TiledPanel;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TTiledPanel =
class(TPanel)
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
private
fTileImage : TBitMap;
protected
procedure Paint; override;
procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND;
private
function GetTileImage : TBitmap;
procedure SetTileImage(aImage : TBitmap);
published
property TileImage : TBitmap read GetTileImage write SetTileImage;
end;
procedure Register;
implementation
// TTiledPanel
constructor TTiledPanel.Create(AOwner : TComponent);
begin
inherited;
fTileImage := TBitMap.Create;
end;
destructor TTiledPanel.Destroy;
begin
fTileImage.Free;
inherited;
end;
procedure TTiledPanel.Paint;
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
var
xPixels : word;
yPixels : word;
Rect : TRect;
FontHeight : integer;
Buffer : TBitmap;
tmpCanvas : TCanvas;
begin
if Caption <> ''
then
begin
Buffer := TBitmap.Create;
Buffer.Width := Width;
Buffer.Height := Height;
tmpCanvas := Buffer.Canvas;
end
else
begin
Buffer := nil;
tmpCanvas := Canvas;
end;
if (fTileImage.Width > 0) and (fTileImage.Height > 0)
then
begin
yPixels := 0;
repeat
xPixels := 0;
repeat
tmpCanvas.Draw(xPixels, yPixels, fTileImage);
inc(xPixels, fTileImage.Width);
until xPixels >= Width;
inc(yPixels, fTileImage.Height);
until yPixels >= Height
end;
Rect := GetClientRect;
inc( Rect.Left, BorderWidth );
dec( Rect.Right, BorderWidth );
with tmpCanvas do
begin
Brush.Color := Color;
Brush.Style := bsClear;
Font := Self.Font;
FontHeight := TextHeight('W');
with Rect do
begin
Top := ((Bottom + Top) - FontHeight) div 2;
Bottom := Top + FontHeight;
end;
DrawText(Handle, PChar(Caption), -1, Rect, (DT_EXPANDTABS or
DT_VCENTER) or Alignments[Alignment]);
end;
if Buffer <> nil
then
begin
Rect := Bounds( 0, 0, Width, Height );
Canvas.CopyRect( Rect, tmpCanvas, Rect );
Buffer.Free;
end;
end;
procedure TTiledPanel.WMEraseBkgnd(var Message: TMessage);
begin
Message.Result := 1;
end;
function TTiledPanel.GetTileImage : TBitmap;
begin
result := fTileImage;
end;
procedure TTiledPanel.SetTileImage(aImage : TBitmap);
begin
fTileImage.Assign(aImage);
end;
// Register component
procedure Register;
begin
RegisterComponents('Five', [TTiledPanel]);
end;
end.
|
unit XMLFiles;
interface
uses SysUtils, Classes, Windows, Forms, Dialogs;
type
{ XML Attrs }
TXMLAttrs = class
public
dataWideString : WideString;
end;
function GetAttrs(Name: WideString; Attrs: TStringList): WideString;
procedure LoadXMLStations(sFileName : String; DATA : TStringList);
implementation
uses LibXmlParser, General, Convs;
(*
===============================================================================================
TElementNode
===============================================================================================
*)
TYPE
TElementNode = CLASS
Content : AnsiString;
Attr : TStringList;
CONSTRUCTOR Create (TheContent : RawByteString; TheAttr : TNvpList);
DESTRUCTOR Destroy; OVERRIDE;
END;
CONSTRUCTOR TElementNode.Create (TheContent : RawByteString; TheAttr : TNvpList);
VAR
I : INTEGER;
BEGIN
INHERITED Create;
Content := TheContent;
Attr := TStringList.Create;
IF TheAttr <> NIL THEN
FOR I := 0 TO TheAttr.Count-1 DO
Attr.Add (TNvpNode (TheAttr [I]).Name + '=' + TNvpNode (TheAttr [I]).Value);
END;
DESTRUCTOR TElementNode.Destroy;
BEGIN
Attr.Free;
INHERITED Destroy;
END;
////////////////////////////////////////////////////////////////////////////////
function GetAttrs(Name: WideString; Attrs: TStringList): WideString;
var
idx : Integer;
begin
idx := Attrs.IndexOf(name);
if idx <> -1 then
Result := TXMLAttrs(Attrs.Objects[idx]).dataWideString;
end;
////////////////////////////////////////////////////////////////////////////////
procedure LoadXMLStations(sFileName : String; DATA : TStringList);
var
XmlParser : TXmlParser;
sn : RawByteString;
EN : TElementNode;
idxItem, idxStream : Integer;
// F, F2: TextFile;
bNewFormat : Boolean;
procedure CommandXML(sCommand: RawByteString; sValue: RawByteString; Attrs: TStringList; bAttrs: Boolean);
var
ix : Integer;
begin
//showmessage(sCommand + #13 + sValue);
application.ProcessMessages;
{
writeln(F,sCommand + ' >>> ' + sValue);
for ix := 0 to Attrs.Count - 1 do
begin
writeln(F, '>' + Attrs.Strings[ix] + ' >>> ' + TXMLAttrs(Attrs.Objects[ix]).dataWideString );
end;
}
if (sCommand = 'CODEPAGE') and (sValue = 'UTF-8') then
begin
bNewFormat := True;
end;
if bNewFormat=True then
begin
if sCommand = '/stationslist/station' then
begin
DATA.Add('ITEM');
idxItem:= DATA.Count - 1;
DATA.Objects[idxItem] := TStation.Create;
TStation(DATA.Objects[idxItem]).Name := UTF82WideString({MIMEBase64Decode(}GetAttrs('name', Attrs){)});
TStation(DATA.Objects[idxItem]).Genre := UTF82WideString({MIMEBase64Decode(}GetAttrs('genre', Attrs){)});
TStation(DATA.Objects[idxItem]).Language := UTF82WideString({MIMEBase64Decode(}GetAttrs('language', Attrs){)});
TStation(DATA.Objects[idxItem]).URL := UTF82WideString({MIMEBase64Decode(}GetAttrs('url', Attrs){)});
TStation(DATA.Objects[idxItem]).Group := UTF82WideString({MIMEBase64Decode(}GetAttrs('group', Attrs){)});
TStation(DATA.Objects[idxItem]).Streams := TStringList.Create;
TStation(DATA.Objects[idxItem]).Streams.Clear;
{ writeln(F2,'--- station ---');
writeln(F2,UTF82WideString(GetAttrs('name', Attrs)));
writeln(F2,UTF82WideString(GetAttrs('genre', Attrs)));
writeln(F2,UTF82WideString(GetAttrs('language', Attrs)));
writeln(F2,UTF82WideString(GetAttrs('url', Attrs)));
writeln(F2,UTF82WideString(GetAttrs('group', Attrs))); }
end;
if sCommand = '/stationslist/station/streams' then
begin
TStation(DATA.Objects[idxItem]).DefaultStream := ConvStrToInt( GetAttrs('default', Attrs) );
{ writeln(F2,GetAttrs('default', Attrs));}
end;
if sCommand = '/stationslist/station/streams/stream' then
begin
TStation(DATA.Objects[idxItem]).Streams.Add('STREAM');
idxStream:= TStation(DATA.Objects[idxItem]).Streams.Count - 1;
TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream] := TStream.Create;
TStream(TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream]).Format := UTF82WideString({MIMEBase64Decode(}GetAttrs('format', Attrs){)});
TStream(TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream]).URL := UTF82WideString({MIMEBase64Decode(}GetAttrs('url', Attrs){)});
{ writeln(F2,'--- stream ---');
writeln(F2,UTF82WideString(GetAttrs('format', Attrs)));
writeln(F2,UTF82WideString( sValue ));}
end;
end
else
begin
if (sCommand = 'BEGIN') and (sValue = '/Station') then
begin
DATA.Add('ITEM');
idxItem:= DATA.Count - 1;
DATA.Objects[idxItem] := TStation.Create;
TStation(DATA.Objects[idxItem]).Name := '';
TStation(DATA.Objects[idxItem]).Genre := '';
TStation(DATA.Objects[idxItem]).Language := '';
TStation(DATA.Objects[idxItem]).URL := '';
TStation(DATA.Objects[idxItem]).Streams := TStringList.Create;
TStation(DATA.Objects[idxItem]).Streams.Clear;
// writeln(F2,'--- station ---');
end;
if (sCommand = 'BEGIN') and (sValue = '/Station/Stream') then
begin
TStation(DATA.Objects[idxItem]).Streams.Add('STREAM');
idxStream:= TStation(DATA.Objects[idxItem]).Streams.Count - 1;
TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream] := TStream.Create;
TStream(TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream]).Format := '';
TStream(TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream]).URL := '';
// writeln(F2,'--- stream ---');
end;
if sCommand = '/Station/Name' then
begin
TStation(DATA.Objects[idxItem]).Name := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/Genre' then
begin
TStation(DATA.Objects[idxItem]).Genre := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/Language' then
begin
TStation(DATA.Objects[idxItem]).Language := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/URL' then
begin
TStation(DATA.Objects[idxItem]).URL := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/Group' then
begin
TStation(DATA.Objects[idxItem]).Group := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/DefaultStream' then
begin
TStation(DATA.Objects[idxItem]).DefaultStream := ConvStrToInt( UTF82WideString( sValue ) );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/Stream/Format' then
begin
TStream(TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream]).Format := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end
else if sCommand = '/Station/Stream/URL' then
begin
TStream(TStation(DATA.Objects[idxItem]).Streams.Objects[idxStream]).URL := UTF82WideString( sValue );
// writeln(F2,UTF82WideString( sValue ));
end;
;
end;
Attrs.Clear;
end;
procedure ReadItemXML(s: RawByteString);
var ii: Integer;
sAttrs : TStringList;
hIndex1: Integer;
begin
sAttrs := TStringList.Create;
sAttrs.Clear;
while XmlParser.Scan do
begin
case XmlParser.CurPartType of
ptXmlProlog : begin
CommandXML( 'CODEPAGE' ,XmlParser.CurEncoding, sAttrs, False);
end;
ptDtdc : begin
end;
ptStartTag,
ptEmptyTag : begin
if XmlParser.CurAttr.Count > 0 then
begin
sn:= s + '/' + XmlParser.CurName ;
EN := TElementNode.Create ('', XmlParser.CurAttr);
sAttrs.Clear;
for Ii := 0 TO EN.Attr.Count-1 do
begin
sAttrs.Add( Trim( EN.Attr.Names [Ii] ) );
hIndex1:= sAttrs.Count - 1;
sAttrs.Objects[hIndex1] := TXMLAttrs.Create;
TXMLAttrs(sAttrs.Objects[hIndex1]).dataWideString := Trim( EN.Attr.Values [EN.Attr.Names [Ii]]);
end;
CommandXML( sn, '', sAttrs, True );
sAttrs.Clear;
end;
if XmlParser.CurPartType = ptStartTag then // Recursion
begin
sn:= s + '/' + XmlParser.CurName ;
CommandXML('BEGIN' , sn, sAttrs, False );
ReadItemXML (sn);
end
end;
ptEndTag : begin
CommandXML('END' , s, sAttrs, False );
BREAK;
end;
ptContent,
ptCData : begin
if Trim( XmlParser.CurContent)='' then
else
begin
CommandXML( s , Trim( XmlParser.CurContent ), sAttrs, False );
end;
end;
ptComment : begin
end;
ptPI : begin
end;
end;
end;
end;
begin
(*
if Copy(sXMLText,1,3) = '´╗┐' then
sXMLText := Copy(sXMLText,4);
if (Copy(sXMLText,1,5) <> '<?xml') then // neplatny XML soubor
begin
ShowMessage('Neplatnř XML soubor');
Exit;
end; *)
{ AssignFile(F2, ExtractFilePath( PluginDllPath) + '\stanice.txt');
Rewrite(F2);}
{ AssignFile(F, ExtractFilePath( PluginDllPath) + '\xml.txt');
Rewrite(F);}
bNewFormat := False;
XmlParser := TXmlParser.Create;
XmlParser.LoadFromFile(sFileName);
// XmlParser.LoadFromBuffer( PAnsiChar( sXMLText ) );
XmlParser.StartScan;
XmlParser.Normalize := FALSE;
ReadItemXML('');
XmlParser.Free;
{
CloseFile(F);}
{ CloseFile(F2);}
end;
end.
|
{$I ATViewerDef.inc}
unit REProc;
interface
uses Windows, ComCtrls;
function RE_CurrentLine(Edit: TRichEdit): integer;
function RE_LineFromPos(Edit: TRichEdit; Pos: integer): integer;
function RE_PosFromLine(Edit: TRichEdit; Line: integer): integer;
procedure RE_ScrollToStart(Edit: TRichEdit);
procedure RE_ScrollToEnd(Edit: TRichEdit);
procedure RE_ScrollToLine(Edit: TRichEdit; Line, Indent: integer);
procedure RE_ScrollToPercent(Edit: TRichEdit; N: integer);
procedure RE_LimitSize(Edit: TRichEdit; Size: DWORD);
procedure RE_LoadFile(Edit: TRichEdit; const AFileName: WideString;
IsOEM: boolean; ASelStart, ASelLength: integer);
procedure RE_Print(Edit: TRichEdit; OnlySel: boolean; Copies: integer);
implementation
uses
SysUtils, Messages, Classes,
{$ifdef TNT}TntClasses,{$endif}
Printers, RichEdit, SProc;
function RE_CurrentLine(Edit: TRichEdit): integer;
begin
Result:= Edit.Perform(EM_GETFIRSTVISIBLELINE, 0, 0);
end;
function RE_LineFromPos(Edit: TRichEdit; Pos: integer): integer;
begin
Result:= Edit.Perform(EM_EXLINEFROMCHAR, 0, Pos);
end;
function RE_PosFromLine(Edit: TRichEdit; Line: integer): integer;
begin
Result:= Edit.Perform(EM_LINEINDEX, Line, 0);
end;
procedure RE_ScrollToStart(Edit: TRichEdit);
var
n: DWORD;
begin
repeat
n:= Edit.Perform(EM_SCROLL, SB_PAGEUP, 0);
until (n and $FFFF)=0;
end;
procedure RE_ScrollToEnd(Edit: TRichEdit);
var
n: DWORD;
begin
repeat
n:= Edit.Perform(EM_SCROLL, SB_PAGEDOWN, 0);
until (n and $FFFF)=0;
end;
procedure RE_ScrollToLine(Edit: TRichEdit; Line, Indent: integer);
begin
RE_ScrollToStart(Edit);
Dec(Line, Indent);
if Line<0 then Line:= 0;
Edit.Perform(EM_LINESCROLL, 0, Line);
end;
procedure RE_ScrollToPercent(Edit: TRichEdit; N: integer);
var
Num: integer;
begin
if N<=0 then
begin
RE_ScrollToStart(Edit);
Edit.SelStart:= 0;
Edit.SelLength:= 0;
end
else
if N>=100 then
begin
RE_ScrollToEnd(Edit);
Edit.SelStart:= RE_PosFromLine(Edit, Edit.Lines.Count-1);
Edit.SelLength:= 0;
end
else
begin
Num:= (Edit.Lines.Count-1) * N div 100;
if Num>0 then
begin
RE_ScrollToLine(Edit, Num, 0);
Edit.SelStart:= RE_PosFromLine(Edit, Num);
Edit.SelLength:= 0;
end;
end;
end;
procedure RE_LimitSize(Edit: TRichEdit; Size: DWORD);
begin
Edit.Perform(EM_EXLIMITTEXT, 0, Size);
end;
procedure RE_LoadFile(Edit: TRichEdit; const AFileName: WideString;
IsOEM: boolean; ASelStart, ASelLength: integer);
var
Stream: TStream;
i: integer;
begin
with Edit do
begin
Lines.Clear;
Stream:= {$ifdef TNT}TTntFileStream{$else}TFileStream{$endif}.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
Lines.LoadFromStream(Stream);
finally
Stream.Free;
end;
if IsOEM then
for i:= 0 to Lines.Count-1 do
Lines[i]:= ToANSI(Lines[i]);
end;
RE_ScrollToStart(Edit);
Edit.SelStart:= ASelStart;
Edit.SelLength:= ASelLength;
end;
procedure RE_Print(Edit: TRichEdit; OnlySel: boolean; Copies: integer);
var
ASelStart, ASelLength: integer;
begin
if Copies=0 then Inc(Copies);
Printer.Copies:= Copies;
Printer.Canvas.Font:= Edit.Font;
if OnlySel then
begin
ASelStart:= Edit.SelStart;
ASelLength:= Edit.SelLength;
Edit.SelStart:= ASelStart+ASelLength;
Edit.SelLength:= MaxInt;
Edit.SelText:= '';
Edit.SelStart:= 0;
Edit.SelLength:= ASelStart;
Edit.SelText:= '';
end;
Edit.Print('');
end;
end.
|
unit dsMainList;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Библиотека "List"
// Автор: Морозов М.А.
// Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/List/dsMainList.pas"
// Начат: 2007/04/06 13:04:11
// Родные Delphi интерфейсы (.pas)
// Generated from UML model, root element: <<ViewAreaControllerImp::Class>> F1 Работа с документом и списком документов::WorkWithList::List::List::TdsMainList
//
// Список документов прецедента "Список". Списков в системе много, а сообщать о смене текущего
// прецеденту должен только один - список документов прецедента "Cписок". Для этой цели создан
// dsMainList с перекрытым NotifyAboutChangeCurrent
//
//
// Все права принадлежат ООО НПП "Гарант-Сервис".
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ! Полностью генерируется с модели. Править руками - нельзя. !
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If not defined(Admin) AND not defined(Monitorings)}
uses
dsDocumentList,
l3TreeInterfaces
;
{$IfEnd} //not Admin AND not Monitorings
{$If not defined(Admin) AND not defined(Monitorings)}
type
TdsMainList = {vac} class(TdsDocumentList)
{* Список документов прецедента "Список". Списков в системе много, а сообщать о смене текущего прецеденту должен только один - список документов прецедента "Cписок". Для этой цели создан dsMainList с перекрытым NotifyAboutChangeCurrent }
protected
// overridden protected methods
function NotifyAboutChangeCurrent: Boolean; override;
{* уведомлять бизнес объект прецедента о смене текущего. }
function DoIsMain: Boolean; override;
{* - определяет список в основной зоне приложения. }
function DoGetIsShortList: Boolean; override;
procedure DoSetupNewSimpleTree(const aTree: Il3SimpleTree); override;
function DoGetIsSnippet: Boolean; override;
function DoCanAnalize: Boolean; override;
end;//TdsMainList
{$IfEnd} //not Admin AND not Monitorings
implementation
{$If not defined(Admin) AND not defined(Monitorings)}
// start class TdsMainList
function TdsMainList.NotifyAboutChangeCurrent: Boolean;
//#UC START# *47F0D913030D_4926C0970020_var*
//#UC END# *47F0D913030D_4926C0970020_var*
begin
//#UC START# *47F0D913030D_4926C0970020_impl*
Result := true;
//#UC END# *47F0D913030D_4926C0970020_impl*
end;//TdsMainList.NotifyAboutChangeCurrent
function TdsMainList.DoIsMain: Boolean;
//#UC START# *47FB00640212_4926C0970020_var*
//#UC END# *47FB00640212_4926C0970020_var*
begin
//#UC START# *47FB00640212_4926C0970020_impl*
Result := true;
//#UC END# *47FB00640212_4926C0970020_impl*
end;//TdsMainList.DoIsMain
function TdsMainList.DoGetIsShortList: Boolean;
//#UC START# *4A2D0838019C_4926C0970020_var*
//#UC END# *4A2D0838019C_4926C0970020_var*
begin
//#UC START# *4A2D0838019C_4926C0970020_impl*
Result := Assigned(ImpList) and ImpList.GetIsShort;
//#UC END# *4A2D0838019C_4926C0970020_impl*
end;//TdsMainList.DoGetIsShortList
procedure TdsMainList.DoSetupNewSimpleTree(const aTree: Il3SimpleTree);
//#UC START# *4A4074FB0192_4926C0970020_var*
//#UC END# *4A4074FB0192_4926C0970020_var*
begin
//#UC START# *4A4074FB0192_4926C0970020_impl*
if DoGetIsSnippet then
aTree.ExpandSubDir(nil, True, 0);
//#UC END# *4A4074FB0192_4926C0970020_impl*
end;//TdsMainList.DoSetupNewSimpleTree
function TdsMainList.DoGetIsSnippet: Boolean;
//#UC START# *4A796F46039D_4926C0970020_var*
//#UC END# *4A796F46039D_4926C0970020_var*
begin
//#UC START# *4A796F46039D_4926C0970020_impl*
Result := Assigned(ImpList) and ImpList.GetIsSnippet;
//#UC END# *4A796F46039D_4926C0970020_impl*
end;//TdsMainList.DoGetIsSnippet
function TdsMainList.DoCanAnalize: Boolean;
//#UC START# *4AA0F2E70398_4926C0970020_var*
//#UC END# *4AA0F2E70398_4926C0970020_var*
begin
//#UC START# *4AA0F2E70398_4926C0970020_impl*
Result := true;
//#UC END# *4AA0F2E70398_4926C0970020_impl*
end;//TdsMainList.DoCanAnalize
{$IfEnd} //not Admin AND not Monitorings
end. |
unit nsMainMenu2011Node;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Common\nsMainMenu2011Node.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TnsMainMenu2011Node" MUID: (4E730AE6014C)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3IntfUses
, nsNewCachableNode
, MainMenuUnit
, l3Interfaces
, l3Tree_TLB
, l3IID
;
type
TnsMainMenu2011Node = class(TnsNewCachableNode)
private
f_SectionItem: ISectionItem;
f_Caption: Il3CString;
protected
function GetAsPCharLen: Tl3WString; override;
function COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult; override;
{* Реализация запроса интерфейса }
procedure ClearFields; override;
public
constructor Create(const aSectionItem: ISectionItem); reintroduce;
class function Make(const aSectionItem: ISectionItem): Il3Node; reintroduce;
end;//TnsMainMenu2011Node
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
implementation
{$If NOT Defined(Admin) AND NOT Defined(Monitorings)}
uses
l3ImplUses
, l3Base
, SysUtils
, l3String
, nsTypes
, IOUnit
{$If NOT Defined(NoScripts)}
, InterfacedNodeWords
{$IfEnd} // NOT Defined(NoScripts)
//#UC START# *4E730AE6014Cimpl_uses*
//#UC END# *4E730AE6014Cimpl_uses*
;
constructor TnsMainMenu2011Node.Create(const aSectionItem: ISectionItem);
//#UC START# *4E730CD20352_4E730AE6014C_var*
//#UC END# *4E730CD20352_4E730AE6014C_var*
begin
//#UC START# *4E730CD20352_4E730AE6014C_impl*
inherited Create(nil);
Assert(aSectionItem <> nil);
f_SectionItem := aSectionItem;
//#UC END# *4E730CD20352_4E730AE6014C_impl*
end;//TnsMainMenu2011Node.Create
class function TnsMainMenu2011Node.Make(const aSectionItem: ISectionItem): Il3Node;
var
l_Inst : TnsMainMenu2011Node;
begin
l_Inst := Create(aSectionItem);
try
Result := l_Inst;
finally
l_Inst.Free;
end;//try..finally
end;//TnsMainMenu2011Node.Make
function TnsMainMenu2011Node.GetAsPCharLen: Tl3WString;
//#UC START# *47A869BB02DE_4E730AE6014C_var*
var
l_S : IString;
//#UC END# *47A869BB02DE_4E730AE6014C_var*
begin
//#UC START# *47A869BB02DE_4E730AE6014C_impl*
if (f_Caption = nil) then
begin
f_SectionItem.GetCaption(l_S);
if (l_S = nil) then
f_Caption := l3CStr('')
else
f_Caption := nsCStr(l_S);
end;//f_Caption = nil
Result := l3PCharLen(f_Caption);
//#UC END# *47A869BB02DE_4E730AE6014C_impl*
end;//TnsMainMenu2011Node.GetAsPCharLen
function TnsMainMenu2011Node.COMQueryInterface(const IID: Tl3GUID;
out Obj): Tl3HResult;
{* Реализация запроса интерфейса }
//#UC START# *4A60B23E00C3_4E730AE6014C_var*
//#UC END# *4A60B23E00C3_4E730AE6014C_var*
begin
//#UC START# *4A60B23E00C3_4E730AE6014C_impl*
Result.SetOk;
if IID.EQ(ISectionItem) then
ISectionItem(Obj) := f_SectionItem
else
Result := inherited COMQueryInterface(IID, Obj);
//#UC END# *4A60B23E00C3_4E730AE6014C_impl*
end;//TnsMainMenu2011Node.COMQueryInterface
procedure TnsMainMenu2011Node.ClearFields;
begin
f_SectionItem := nil;
f_Caption := nil;
inherited;
end;//TnsMainMenu2011Node.ClearFields
{$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings)
end.
|
{
Copyright (C) 2013-2019 Tim Sinaeve tim.sinaeve@gmail.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
unit LogViewer.Settings.Dialog;
{ Application settings dialog. }
interface
uses
System.SysUtils, System.Variants, System.Classes, System.ImageList,
System.Actions,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls,
Vcl.ComCtrls, Vcl.ActnList, Vcl.StdCtrls, Vcl.ImgList,
VirtualTrees,
SynEditHighlighter, SynEditCodeFolding, SynHighlighterJScript, SynEdit,
DDuce.Editor.Interfaces, DDuce.Components.VirtualTrees.Node,
LogViewer.Settings, LogViewer.Settings.Dialog.Data,
LogViewer.Comport.Settings.View, LogViewer.WinIPC.Settings.View,
LogViewer.Watches.Settings.View, LogViewer.WinODS.Settings.View,
LogViewer.ZeroMQ.Settings.View, LogViewer.DisplayValues.Settings.View;
type
TConfigNode = TVTNode<TConfigData>;
type
TfrmLogViewerSettings = class(TForm)
{$REGION 'designer controls'}
aclMain : TActionList;
actApply : TAction;
actCancel : TAction;
actClose : TAction;
btnCancel : TButton;
btnClose : TButton;
btnClose1 : TButton;
imlMain : TImageList;
pgcMain : TPageControl;
pnlBottom : TPanel;
pnlConfigTree : TPanel;
splVertical : TSplitter;
tsAdvanced : TTabSheet;
tsCallstack : TTabSheet;
tsComport : TTabSheet;
tsDisplayValuesSettings : TTabSheet;
tsWatches : TTabSheet;
tsWinIPC : TTabSheet;
tsWinODS : TTabSheet;
tsZeroMQ : TTabSheet;
seSettings : TSynEdit;
synJScript : TSynJScriptSyn;
{$ENDREGION}
procedure actCloseExecute(Sender: TObject);
procedure actApplyExecute(Sender: TObject);
procedure actCancelExecute(Sender: TObject);
private
FConfigTree : TVirtualStringTree;
FSettings : TLogViewerSettings;
FComportSettingsForm : TfrmComPortSettings;
FWatchSettingsForm : TfrmWatchSettings;
FWinIPCSettingsForm : TfrmWinIPCSettings;
FWinODSSettingsForm : TfrmWinODSSettings;
FZeroMQSettingsForm : TfrmZeroMQSettings;
FDisplayValuesSettingsForm : TfrmDisplayValuesSettings;
procedure FConfigTreeGetText(
Sender : TBaseVirtualTree;
Node : PVirtualNode;
Column : TColumnIndex;
TextType : TVSTTextType;
var CellText : string
);
procedure FConfigTreeFocusChanged(
Sender : TBaseVirtualTree;
Node : PVirtualNode;
Column : TColumnIndex
);
procedure FConfigTreeFreeNode(
Sender: TBaseVirtualTree;
Node: PVirtualNode
);
protected
procedure BuildTree;
function AddNode(
AParentNode : TConfigNode;
const AText : string;
ATabSheet : TTabSheet
): TConfigNode;
procedure CreateSettingsForms;
public
procedure AfterConstruction; override;
procedure BeforeDestruction; override;
constructor Create(
AOwner : TComponent;
ASettings : TLogViewerSettings
); reintroduce;
end;
implementation
{$R *.dfm}
uses
DDuce.Editor.Factories, DDuce.Factories.VirtualTrees,
LogViewer.Resources;
{$REGION 'construction and destruction'}
constructor TfrmLogViewerSettings.Create(AOwner: TComponent;
ASettings: TLogViewerSettings);
begin
inherited Create(AOwner);
FSettings := ASettings;
end;
procedure TfrmLogViewerSettings.AfterConstruction;
var
I : Integer;
begin
inherited AfterConstruction;
CreateSettingsForms;
FConfigTree := TVirtualStringTreeFactory.CreateTreeList(Self, pnlConfigTree);
FConfigTree.OnGetText := FConfigTreeGetText;
FConfigTree.OnFreeNode := FConfigTreeFreeNode;
FConfigTree.OnFocusChanged := FConfigTreeFocusChanged;
FConfigTree.Header.Options := FConfigTree.Header.Options - [hoVisible];
FConfigTree.TreeOptions.PaintOptions :=
FConfigTree.TreeOptions.PaintOptions + [toShowTreeLines];
FConfigTree.Margins.Right := 0;
FConfigTree.NodeDataSize := SizeOf(TConfigNode);
BuildTree;
for I := 0 to pgcMain.PageCount - 1 do
begin
pgcMain.Pages[I].TabVisible := False;
end;
pgcMain.ActivePage := tsDisplayValuesSettings;
seSettings.Lines.LoadFromFile(FSettings.FileName);
end;
procedure TfrmLogViewerSettings.BeforeDestruction;
begin
FConfigTree.Free;
inherited BeforeDestruction;
end;
{$ENDREGION}
{$REGION 'event handlers'}
procedure TfrmLogViewerSettings.FConfigTreeFocusChanged(
Sender: TBaseVirtualTree; Node: PVirtualNode; Column: TColumnIndex);
var
CN: TConfigNode;
begin
CN := Sender.GetNodeData<TConfigNode>(Node);
if Assigned(CN.Data.TabSheet) then
pgcMain.ActivePage := CN.Data.TabSheet;
end;
procedure TfrmLogViewerSettings.FConfigTreeFreeNode(Sender: TBaseVirtualTree;
Node: PVirtualNode);
var
CN : TConfigNode;
begin
CN := Sender.GetNodeData<TConfigNode>(Node);
FreeAndNil(CN);
end;
procedure TfrmLogViewerSettings.FConfigTreeGetText(Sender: TBaseVirtualTree;
Node: PVirtualNode; Column: TColumnIndex; TextType: TVSTTextType;
var CellText: string);
var
CN : TConfigNode;
begin
CN := Sender.GetNodeData<TConfigNode>(Node);
CellText := CN.Text;
end;
{$ENDREGION}
{$REGION 'action handlers'}
procedure TfrmLogViewerSettings.actApplyExecute(Sender: TObject);
begin
FSettings.Save;
seSettings.Lines.LoadFromFile(FSettings.FileName);
end;
procedure TfrmLogViewerSettings.actCancelExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmLogViewerSettings.actCloseExecute(Sender: TObject);
begin
FSettings.Save;
Close;
end;
{$ENDREGION}
{$REGION 'protected methods'}
function TfrmLogViewerSettings.AddNode(AParentNode: TConfigNode; const AText:
string; ATabSheet: TTabSheet): TConfigNode;
begin
if Assigned(AParentNode) then
begin
Result := AParentNode.Add(TConfigData.Create(AText, ATabSheet));
end
else
begin
Result := TConfigNode.Create(
FConfigTree,
TConfigData.Create(AText, ATabSheet)
);
end;
Result.Text := AText;
end;
procedure TfrmLogViewerSettings.BuildTree;
var
LNode : TConfigNode;
begin
LNode := AddNode(nil, SViewSettings, nil);
AddNode(LNode, SDisplaySettings, tsDisplayValuesSettings);
AddNode(LNode, SWatches, tsWatches);
AddNode(LNode, SCallStack, tsCallstack);
LNode := AddNode(nil, SChannelSettings, nil);
AddNode(LNode, SWinIPC, tsWinIPC);
AddNode(LNode, SWinODS, tsWinODS);
AddNode(LNode, SComPort, tsComport);
AddNode(LNode, SZeroMQ, tsZeroMQ);
AddNode(nil, SGeneralSettings, nil);
AddNode(nil, SAdvanced, tsAdvanced);
FConfigTree.FullExpand;
end;
procedure TfrmLogViewerSettings.CreateSettingsForms;
begin
FComportSettingsForm := TfrmComPortSettings.Create(Self, FSettings.ComPortSettings);
FComportSettingsForm.Parent := tsComport;
FComportSettingsForm.Align := alClient;
FComportSettingsForm.BorderStyle := bsNone;
FComportSettingsForm.Visible := True;
FWatchSettingsForm := TfrmWatchSettings.Create(Self, FSettings.WatchSettings);
FWatchSettingsForm.Parent := tsWatches;
FWatchSettingsForm.Align := alClient;
FWatchSettingsForm.BorderStyle := bsNone;
FWatchSettingsForm.Visible := True;
FWinIPCSettingsForm := TfrmWinIPCSettings.Create(Self, FSettings.WinIPCSettings);
FWinIPCSettingsForm.Parent := tsWinIPC;
FWinIPCSettingsForm.Align := alClient;
FWinIPCSettingsForm.BorderStyle := bsNone;
FWinIPCSettingsForm.Visible := True;
FWinODSSettingsForm := TfrmWinODSSettings.Create(Self, FSettings.WinODSSettings);
FWinODSSettingsForm.Parent := tsWinODS;
FWinODSSettingsForm.Align := alClient;
FWinODSSettingsForm.BorderStyle := bsNone;
FWinODSSettingsForm.Visible := True;
FZeroMQSettingsForm := TfrmZeroMQSettings.Create(Self, FSettings.ZeroMQSettings);
FZeroMQSettingsForm.Parent := tsZeroMQ;
FZeroMQSettingsForm.Align := alClient;
FZeroMQSettingsForm.BorderStyle := bsNone;
FZeroMQSettingsForm.Visible := True;
FDisplayValuesSettingsForm := TfrmDisplayValuesSettings.Create(
Self, FSettings.DisplayValuesSettings
);
FDisplayValuesSettingsForm.Parent := tsDisplayValuesSettings;
FDisplayValuesSettingsForm.Align := alClient;
FDisplayValuesSettingsForm.BorderStyle := bsNone;
FDisplayValuesSettingsForm.Visible := True;
end;
{$ENDREGION}
end.
|
{
*****************************************************************************
* *
* This file is part of the iPhone Laz Extension *
* *
* See the file COPYING.modifiedLGPL.txt, included in this distribution, *
* for details about the copyright. *
* *
* 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. *
* *
*****************************************************************************
}
unit LazFilesUtils;
{$mode objfpc}{$H+}
interface
uses
{$ifdef Unix}BaseUnix,{$endif}
Classes, SysUtils, FileUtil, Masks,
LazIDEIntf, ProjectIntf, process;
function ResolveProjectPath(const path: string; project: TLazProject = nil): string;
function BreakPathsStringToOption(const Paths, Switch: String; const Quotes: string = '"'; project: TLazProject = nil): String;
function RelativeToFullPath(const BasePath, Relative: string): String;
function NeedQuotes(const path: string): Boolean;
function CopySymLinks(const SrcDir, DstDir, FilterMask: string): Boolean;
procedure EnumFilesAtDir(const PathUtf8 : AnsiString; Dst: TStrings);
procedure EnumFilesAtDir(const PathUtf8, AMask : AnsiString; Dst: TStrings);
procedure ExecCmdLineNoWait(const CmdLineUtf8: AnsiString);
function ExecCmdLineStdOut(const CmdLineUtf8: AnsiString; var StdOut: string; var ErrCode: LongWord): Boolean;
implementation
{$ifdef Unix}
function CopySymLinks(const SrcDir, DstDir, FilterMask: string): Boolean;
var
allfiles : TStringList;
i : Integer;
pth : string;
MaskList : TMaskList;
curdir : string;
linkdir : string;
linkname : string;
begin
Result:=DirectoryExistsUTF8(SrcDir) and ForceDirectoriesUTF8(DstDir);
if not Result then Exit;
//todo: don't use FindAllFiles(), use sub dir search
allfiles:=FindAllFiles(SrcDir, AllFilesMask, False);
Result:=Assigned(allfiles);
if not Result then Exit;
MaskList := TMaskList.Create(FilterMask);
curdir:=IncludeTrailingPathDelimiter(SrcDir);
linkdir:=IncludeTrailingPathDelimiter(DstDir);
for i:=0 to allfiles.Count-1 do begin
pth:=allfiles[i];
if (FilterMask='') or (not MaskList.Matches(pth)) then begin
linkname:=linkdir+Copy(pth, length(curdir), length(pth));
fpSymlink(PAnsiChar(pth), PAnsiChar(linkname));
end;
end;
allfiles.Free;
end;
{$else}
function CopySymLinks(const SrcDir, DstDir, FilterMask: string): Boolean;
begin
Result:=false;
end;
{$endif}
function GetNextDir(const Path: string; var index: integer; var Name: string): Boolean;
var
i : Integer;
begin
Result:=index<=length(Path);
if not Result then Exit;
if Path[index]=PathDelim then inc(index);
Result:=index<=length(Path);
if not Result then Exit;
for i:=index to length(Path) do
if Path[i]=PathDelim then begin
Name:=Copy(Path, index, i - index);
index:=i+1;
Exit;
end;
Name:=Copy(Path, index, length(Path) - index+1);
index:=length(Path)+1;
end;
function RelativeToFullPath(const BasePath, Relative: string): String;
var
i : integer;
nm : string;
begin
Result:=ExcludeTrailingPathDelimiter(BasePath);
i:=1;
while GetNextDir(Relative, i, nm) do
if nm = '..' then
Result:=ExtractFileDir(Result)
else if nm <> '.' then
Result:=IncludeTrailingPathDelimiter(Result)+nm;
end;
function NeedQuotes(const path: string): Boolean;
var
i : integer;
const
SpaceChars = [#32,#9];
begin
for i:=1 to length(path) do
if path[i] in SpaceChars then begin
Result:=true;
Exit;
end;
Result:=false;
end;
function QuoteStrIfNeeded(const path: string; const quotes: String): String;
begin
if NeedQuotes(path) then
Result:=quotes+path+quotes
else
Result:=path;
end;
function ResolveProjectPath(const path: string; project: TLazProject): string;
var
base : string;
begin
if project=nil then project:=LazarusIDE.ActiveProject;
if FilenameIsAbsolute(Path) then
Result:=Path
else begin
base:='';
base:=ExtractFilePath(project.ProjectInfoFile);
Result:=RelativeToFullPath(base, Path);
end;
end;
function BreakPathsStringToOption(const Paths, Switch, Quotes: String; project: TLazProject): String;
var
i, j : Integer;
fixed : String;
begin
Result:='';
if not Assigned(project) then
project:=LazarusIDE.ActiveProject;
if not Assigned(project) then Exit;
j:=1;
for i:=1 to length(paths)-1 do
if Paths[i]=';' then begin
fixed:=Trim(Copy(paths,j, i-j) );
if fixed<>'' then begin
fixed:=ResolveProjectPath(fixed, project);
Result:=Result+' ' + Switch + QuoteStrIfNeeded(fixed, quotes);
end;
j:=i+1;
end;
fixed:=Trim(Copy(paths,j, length(paths)-j+1) );
if fixed<>'' then begin
fixed:=ResolveProjectPath(fixed, project);
Result:=Result+' ' + Switch + QuoteStrIfNeeded(fixed, quotes);
end;
end;
procedure EnumFilesAtDir(const PathUtf8, AMask : AnsiString; Dst: TStrings);
var
mask : TMask;
sr : TSearchRec;
path : AnsiString;
begin
if (AMask='') or (trim(AMask)='*') then mask:=nil else mask:=TMask.Create(AMask);
try
path:=IncludeTrailingPathDelimiter(PathUtf8);
if FindFirstUTF8(path+AllFilesMask, faAnyFile, sr) = 0 then begin
repeat
if (sr.Name<>'.') and (sr.Name<>'..') then
if not Assigned(mask) or mask.Matches(sr.Name) then
Dst.Add(path+sr.Name);
until FindNextUTF8(sr)<>0;
FindCloseUTF8(sr);
end;
finally
mask.Free;
end;
end;
procedure EnumFilesAtDir(const PathUtf8 : AnsiString; Dst: TStrings);
begin
EnumFilesAtDir(PathUTF8, AllFilesMask, Dst);
end;
procedure ExecCmdLineNoWait(const CmdLineUtf8: AnsiString);
var
proc : TProcess;
begin
proc:=TProcess.Create(nil);
try
proc.CommandLine:=CmdLineUtf8;
proc.Options := [poUsePipes,poNoConsole,poStderrToOutPut];
proc.Execute;
finally
proc.Free;
end;
end;
function ExecCmdLineStdOut(const CmdLineUtf8: AnsiString; var StdOut: string; var ErrCode: LongWord): Boolean;
var
OurCommand : String;
OutputLines : TStringList;
MemStream : TStringStream;
OurProcess : TProcess;
NumBytes : LongInt;
begin
// A temp Memorystream is used to buffer the output
MemStream := TStringStream.Create('');
OurProcess := TProcess.Create(nil);
try
OurProcess.CommandLine := CmdLineUtf8;
//OurProcess.Executable := CmdLineUtf8;
//OurProcess.Parameters.Add(OurCommand);
// We cannot use poWaitOnExit here since we don't
// know the size of the output. On Linux the size of the
// output pipe is 2 kB; if the output data is more, we
// need to read the data. This isn't possible since we are
// waiting. So we get a deadlock here if we use poWaitOnExit.
OurProcess.Options := [poUsePipes];
OurProcess.Execute;
while True do
begin
// make sure we have room
//MemStream.SetSize(BytesRead + READ_BYTES);
// try reading it
if OurProcess.Output.NumBytesAvailable > 0 then
MemStream.CopyFrom(OurProcess.Output, OurProcess.Output.NumBytesAvailable)
else begin
if not OurProcess.Active then
Break; // Program has finished execution.
end;
end;
//MemStream.SetSize(BytesRead);
//OutputLines := TStringList.Create;
//OutputLines.LoadFromStream(MemStream);
//OutputLines.Free;
StdOut:=MemStream.DataString;
Result:=true;
finally
OurProcess.Free;
MemStream.Free;
end;
end;
end.
|
unit db_dealitem_loadIni;
interface
uses
BaseApp, db_dealItem, Define_DealMarket;
procedure LoadDBStockItemIni(App: TBaseApp; ADB: TDBDealItem);
procedure LoadDBStockItemIniFromFile(App: TBaseApp; ADB: TDBDealItem; AFileUrl: string);
procedure SaveDBStockItemIniToFile(App: TBaseApp; ADB: TDBDealItem; AFileUrl: string);
implementation
uses
define_dealItem,
define_dealstore_file,
Windows,
Classes,
SysUtils,
IniFiles;
procedure LoadDBStockItemIni(App: TBaseApp; ADB: TDBDealItem);
var
tmpFilePath: string;
tmpFileUrl: string;
tmpFileName: string;
tmpDicIni: TIniFile;
tmpCnt: integer;
idxFile: integer;
begin
tmpFilePath := App.Path.DataBasePath[ADB.DBType, DataType_Item, 0] + 'sdic\';
tmpFileUrl := tmpFilePath + 'items.ini';
if App.Path.IsFileExists(tmpFileUrl) then
begin
tmpDicIni := TIniFile.Create(tmpFileUrl);
try
tmpCnt := tmpDicIni.ReadInteger('items', 'count', 0);
for idxFile := 0 to tmpCnt - 1 do
begin
tmpFileName := tmpDicIni.ReadString('items', 'item' + IntToStr(idxFile + 1), '');
tmpFileUrl := tmpFilePath + tmpFileName;
if App.Path.IsFileExists(tmpFileUrl) then
begin
LoadDBStockItemIniFromFile(App, ADB, tmpFileUrl);
end;
end;
finally
tmpDicIni.Free;
end;
end;
end;
procedure LoadDBStockItemIniFromFile(App: TBaseApp; ADB: TDBDealItem; AFileUrl: string);
var
i: integer;
tmpSections: TStringList;
tmpStockItem: PRT_DealItem;
tmpItemsIni: TIniFile;
tmpStockCode: string;
tmpMarket: string;
begin
if not App.Path.IsFileExists(AFileUrl) then
exit;
tmpSections := TStringList.Create;
tmpItemsIni := TIniFile.Create(AFileUrl);
try
tmpItemsIni.ReadSections(tmpSections);
for i := 0 to tmpSections.Count - 1 do
begin
tmpStockCode := Trim(LowerCase(tmpSections[i]));
tmpMarket := '';
if '' <> tmpStockCode then
begin
if Pos(Market_SH, tmpStockCode) > 0 then
begin
tmpMarket := Market_SH;
tmpStockCode := Trim(Copy(tmpStockCode, 3, maxint));
end;
if Pos(Market_SZ, tmpStockCode) > 0 then
begin
tmpMarket := Market_SZ;
tmpStockCode := Trim(Copy(tmpStockCode, 3, maxint));
end;
if Length(tmpStockCode) = 6 then
begin
if '6' = tmpStockCode[1] then
begin
tmpMarket := Market_SH
end else
begin
tmpMarket := Market_SZ;
end;
end;
if ('' <> tmpMarket) and (6 > Length(tmpStockCode)) then
begin
tmpStockCode := Copy('000000', 1, 6 - Length(tmpStockCode)) + tmpStockCode;
end;
if ('' <> tmpMarket) and (6 = Length(tmpStockCode)) then
begin
tmpStockItem := ADB.AddDealItem(tmpMarket, tmpStockCode);
if nil <> tmpStockItem then
begin
tmpStockItem.FirstDealDate := tmpItemsIni.ReadInteger(tmpSections[i], 'FirstDeal', 0);
if 0 = tmpStockItem.FirstDealDate then
begin
tmpStockItem.FirstDealDate := tmpItemsIni.ReadInteger(tmpSections[i], 'f', 0);
end;
tmpStockItem.EndDealDate := tmpItemsIni.ReadInteger(tmpSections[i], 'e', 0);
if 0 = tmpStockItem.EndDealDate then
begin
tmpStockItem.EndDealDate := tmpItemsIni.ReadInteger(tmpSections[i], 'EndDeal', 0);
end;
tmpStockItem.Name := Trim(tmpItemsIni.ReadString(tmpSections[i], 'n', ''));
if '' = tmpStockItem.Name then
begin
tmpStockItem.Name := Trim(tmpItemsIni.ReadString(tmpSections[i], 'name', ''));
end;
end;
end;
end;
end;
finally
tmpItemsIni.Free;
tmpSections.Free;
end;
end;
procedure SaveDBStockItemIniToFile(App: TBaseApp; ADB: TDBDealItem; AFileUrl: string);
var
i: integer;
tmpStockItem: PRT_DealItem;
tmpItemsIni: TIniFile;
tmpSection: string;
begin
tmpItemsIni := TIniFile.Create(AFileUrl);
try
for i := 0 to ADB.RecordCount - 1 do
begin
tmpStockItem := ADB.RecordItem[i];
if '' <> tmpStockItem.Name then
begin
tmpSection := tmpStockItem.sMarketCode + tmpStockItem.sCode;
tmpItemsIni.WriteString(tmpSection, 'n', tmpStockItem.Name);
if 0 < tmpStockItem.FirstDealDate then
tmpItemsIni.WriteInteger(tmpSection, 'f', tmpStockItem.FirstDealDate);
end;
end;
finally
tmpItemsIni.Free;
end;
end;
end.
|
unit untOutgoingData;
interface
uses DateUtils, sysutils, untUtils;
type
OutgoingDataErrors = (ERROR_NoError = 0);
PByte = ^Byte;
type
TOutgoingData = class
private
bPilotSymbol: Byte;
bCommandLength: Byte;
wSubstationAddress: Word;
bCommandType: Byte;
dtDateTime: TDateTime;
wYear, wMonth, wDay, wHour, wMinute, wSecond, wMs: Word;
bolClearCommEquipment: boolean;
bolClearIntterupt: boolean;
bolOutgoingData: boolean;
bolClearLastRecord: boolean;
bMaxNumberPeople: Byte;
bAlarm: Byte;
bWarning: Byte;
bOtherCommands: Byte;
bHighRandomCode, bLowRandomCode: Byte;
bCRC16H: Byte;
bCRC16L: Byte;
bolTakeDateFromMe: boolean;
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;
property DateTime: TDateTime read dtDateTime write dtDateTime;
property TakeDateTimeFromMe: boolean read bolTakeDateFromMe
write bolTakeDateFromMe;
constructor Create;
function CreateFrame(var Buffer: ByteArray): OutgoingDataErrors;
end;
implementation
{ TOutgoingData }
constructor TOutgoingData.Create;
begin
bPilotSymbol := $7E;
bCommandType := $46;
bCommandLength := 0;
wSubstationAddress := 1;
dtDateTime := Now;
bolClearCommEquipment := false;
bolClearIntterupt := false;
bolOutgoingData := false;
bolClearLastRecord := false;
bMaxNumberPeople := 15;
bAlarm := 0;
bWarning := 0;
bOtherCommands := 0;
bHighRandomCode := 0;
bLowRandomCode := 0;
bCRC16H := 0;
bCRC16L := 0;
bolTakeDateFromMe := false;
end;
function TOutgoingData.CreateFrame(var Buffer: ByteArray): OutgoingDataErrors;
var
bDeviceSettings: Byte;
begin
if (bCommandType = $46) then
begin
if (bolTakeDateFromMe) then
DecodeDateTime(dtDateTime, wYear, wMonth, wDay, wHour, wMinute,
wSecond, wMs)
else
DecodeDateTime(Now, wYear, wMonth, wDay, wHour, wMinute, wSecond, wMs);
bDeviceSettings := 0;
if (bolClearCommEquipment) then
bDeviceSettings := bDeviceSettings or $01;
if (bolClearIntterupt) then
bDeviceSettings := bDeviceSettings or $02;
if (bolOutgoingData) then
bDeviceSettings := bDeviceSettings or $04;
if (bolClearLastRecord) then
bDeviceSettings := bDeviceSettings or $80;
SetLength(Buffer, 19);
Buffer[0] := bPilotSymbol;
Buffer[1] := $13; //Command Length
Buffer[2] := wSubstationAddress div 256;
Buffer[3] := wSubstationAddress mod 256;
Buffer[4] := bCommandType;
Buffer[5] := wYear - 2000;
Buffer[6] := wMonth;
Buffer[7] := wDay;
Buffer[8] := wHour;
Buffer[9] := wMinute;
Buffer[10] := wSecond;
Buffer[11] := bDeviceSettings;
Buffer[12] := bMaxNumberPeople;
Buffer[13] := bAlarm;
Buffer[14] := bWarning;
Buffer[15] := $00; //Random code
Buffer[16] := $00; //Random code
Crc16_ver(Buffer);
end;
end;
end.
|
unit linux_explicit_synchronization_unstable_v1_protocol;
{$mode objfpc} {$H+}
{$interfaces corba}
interface
uses
Classes, Sysutils, ctypes, wayland_util, wayland_client_core, wayland_protocol;
type
Pzwp_linux_explicit_synchronization_v1 = Pointer;
Pzwp_linux_surface_synchronization_v1 = Pointer;
Pzwp_linux_buffer_release_v1 = Pointer;
const
ZWP_LINUX_EXPLICIT_SYNCHRONIZATION_V1_ERROR_SYNCHRONIZATION_EXISTS = 0; // the surface already has a synchronization object associated
type
Pzwp_linux_explicit_synchronization_v1_listener = ^Tzwp_linux_explicit_synchronization_v1_listener;
Tzwp_linux_explicit_synchronization_v1_listener = record
end;
const
ZWP_LINUX_SURFACE_SYNCHRONIZATION_V1_ERROR_INVALID_FENCE = 0; // the fence specified by the client could not be imported
ZWP_LINUX_SURFACE_SYNCHRONIZATION_V1_ERROR_DUPLICATE_FENCE = 1; // multiple fences added for a single surface commit
ZWP_LINUX_SURFACE_SYNCHRONIZATION_V1_ERROR_DUPLICATE_RELEASE = 2; // multiple releases added for a single surface commit
ZWP_LINUX_SURFACE_SYNCHRONIZATION_V1_ERROR_NO_SURFACE = 3; // the associated wl_surface was destroyed
ZWP_LINUX_SURFACE_SYNCHRONIZATION_V1_ERROR_UNSUPPORTED_BUFFER = 4; // the buffer does not support explicit synchronization
ZWP_LINUX_SURFACE_SYNCHRONIZATION_V1_ERROR_NO_BUFFER = 5; // no buffer was attached
type
Pzwp_linux_surface_synchronization_v1_listener = ^Tzwp_linux_surface_synchronization_v1_listener;
Tzwp_linux_surface_synchronization_v1_listener = record
end;
Pzwp_linux_buffer_release_v1_listener = ^Tzwp_linux_buffer_release_v1_listener;
Tzwp_linux_buffer_release_v1_listener = record
fenced_release : procedure(data: Pointer; AZwpLinuxBufferReleaseV1: Pzwp_linux_buffer_release_v1; AFence: LongInt{fd}); cdecl;
immediate_release : procedure(data: Pointer; AZwpLinuxBufferReleaseV1: Pzwp_linux_buffer_release_v1); cdecl;
end;
TZwpLinuxExplicitSynchronizationV1 = class;
TZwpLinuxSurfaceSynchronizationV1 = class;
TZwpLinuxBufferReleaseV1 = class;
IZwpLinuxExplicitSynchronizationV1Listener = interface
['IZwpLinuxExplicitSynchronizationV1Listener']
end;
IZwpLinuxSurfaceSynchronizationV1Listener = interface
['IZwpLinuxSurfaceSynchronizationV1Listener']
end;
IZwpLinuxBufferReleaseV1Listener = interface
['IZwpLinuxBufferReleaseV1Listener']
procedure zwp_linux_buffer_release_v1_fenced_release(AZwpLinuxBufferReleaseV1: TZwpLinuxBufferReleaseV1; AFence: LongInt{fd});
procedure zwp_linux_buffer_release_v1_immediate_release(AZwpLinuxBufferReleaseV1: TZwpLinuxBufferReleaseV1);
end;
TZwpLinuxExplicitSynchronizationV1 = class(TWLProxyObject)
private
const _DESTROY = 0;
const _GET_SYNCHRONIZATION = 1;
public
destructor Destroy; override;
function GetSynchronization(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZwpLinuxSurfaceSynchronizationV1}): TZwpLinuxSurfaceSynchronizationV1;
function AddListener(AIntf: IZwpLinuxExplicitSynchronizationV1Listener): LongInt;
end;
TZwpLinuxSurfaceSynchronizationV1 = class(TWLProxyObject)
private
const _DESTROY = 0;
const _SET_ACQUIRE_FENCE = 1;
const _GET_RELEASE = 2;
public
destructor Destroy; override;
procedure SetAcquireFence(AFd: LongInt{fd});
function GetRelease(AProxyClass: TWLProxyObjectClass = nil {TZwpLinuxBufferReleaseV1}): TZwpLinuxBufferReleaseV1;
function AddListener(AIntf: IZwpLinuxSurfaceSynchronizationV1Listener): LongInt;
end;
TZwpLinuxBufferReleaseV1 = class(TWLProxyObject)
function AddListener(AIntf: IZwpLinuxBufferReleaseV1Listener): LongInt;
end;
var
zwp_linux_explicit_synchronization_v1_interface: Twl_interface;
zwp_linux_surface_synchronization_v1_interface: Twl_interface;
zwp_linux_buffer_release_v1_interface: Twl_interface;
implementation
var
vIntf_zwp_linux_explicit_synchronization_v1_Listener: Tzwp_linux_explicit_synchronization_v1_listener;
vIntf_zwp_linux_surface_synchronization_v1_Listener: Tzwp_linux_surface_synchronization_v1_listener;
vIntf_zwp_linux_buffer_release_v1_Listener: Tzwp_linux_buffer_release_v1_listener;
destructor TZwpLinuxExplicitSynchronizationV1.Destroy;
begin
wl_proxy_marshal(FProxy, _DESTROY);
inherited Destroy;
end;
function TZwpLinuxExplicitSynchronizationV1.GetSynchronization(ASurface: TWlSurface; AProxyClass: TWLProxyObjectClass = nil {TZwpLinuxSurfaceSynchronizationV1}): TZwpLinuxSurfaceSynchronizationV1;
var
id: Pwl_proxy;
begin
id := wl_proxy_marshal_constructor(FProxy,
_GET_SYNCHRONIZATION, @zwp_linux_surface_synchronization_v1_interface, nil, ASurface.Proxy);
if AProxyClass = nil then
AProxyClass := TZwpLinuxSurfaceSynchronizationV1;
Result := TZwpLinuxSurfaceSynchronizationV1(AProxyClass.Create(id));
if not AProxyClass.InheritsFrom(TZwpLinuxSurfaceSynchronizationV1) then
Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZwpLinuxSurfaceSynchronizationV1]);
end;
function TZwpLinuxExplicitSynchronizationV1.AddListener(AIntf: IZwpLinuxExplicitSynchronizationV1Listener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_linux_explicit_synchronization_v1_Listener, @FUserDataRec);
end;
destructor TZwpLinuxSurfaceSynchronizationV1.Destroy;
begin
wl_proxy_marshal(FProxy, _DESTROY);
inherited Destroy;
end;
procedure TZwpLinuxSurfaceSynchronizationV1.SetAcquireFence(AFd: LongInt{fd});
begin
wl_proxy_marshal(FProxy, _SET_ACQUIRE_FENCE, AFd);
end;
function TZwpLinuxSurfaceSynchronizationV1.GetRelease(AProxyClass: TWLProxyObjectClass = nil {TZwpLinuxBufferReleaseV1}): TZwpLinuxBufferReleaseV1;
var
release: Pwl_proxy;
begin
release := wl_proxy_marshal_constructor(FProxy,
_GET_RELEASE, @zwp_linux_buffer_release_v1_interface, nil);
if AProxyClass = nil then
AProxyClass := TZwpLinuxBufferReleaseV1;
Result := TZwpLinuxBufferReleaseV1(AProxyClass.Create(release));
if not AProxyClass.InheritsFrom(TZwpLinuxBufferReleaseV1) then
Raise Exception.CreateFmt('%s does not inherit from %s', [AProxyClass.ClassName, TZwpLinuxBufferReleaseV1]);
end;
function TZwpLinuxSurfaceSynchronizationV1.AddListener(AIntf: IZwpLinuxSurfaceSynchronizationV1Listener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_linux_surface_synchronization_v1_Listener, @FUserDataRec);
end;
function TZwpLinuxBufferReleaseV1.AddListener(AIntf: IZwpLinuxBufferReleaseV1Listener): LongInt;
begin
FUserDataRec.ListenerUserData := Pointer(AIntf);
Result := wl_proxy_add_listener(FProxy, @vIntf_zwp_linux_buffer_release_v1_Listener, @FUserDataRec);
end;
procedure zwp_linux_buffer_release_v1_fenced_release_Intf(AData: PWLUserData; Azwp_linux_buffer_release_v1: Pzwp_linux_buffer_release_v1; AFence: LongInt{fd}); cdecl;
var
AIntf: IZwpLinuxBufferReleaseV1Listener;
begin
if AData = nil then Exit;
AIntf := IZwpLinuxBufferReleaseV1Listener(AData^.ListenerUserData);
AIntf.zwp_linux_buffer_release_v1_fenced_release(TZwpLinuxBufferReleaseV1(AData^.PascalObject), AFence);
end;
procedure zwp_linux_buffer_release_v1_immediate_release_Intf(AData: PWLUserData; Azwp_linux_buffer_release_v1: Pzwp_linux_buffer_release_v1); cdecl;
var
AIntf: IZwpLinuxBufferReleaseV1Listener;
begin
if AData = nil then Exit;
AIntf := IZwpLinuxBufferReleaseV1Listener(AData^.ListenerUserData);
AIntf.zwp_linux_buffer_release_v1_immediate_release(TZwpLinuxBufferReleaseV1(AData^.PascalObject));
end;
const
pInterfaces: array[0..10] of Pwl_interface = (
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(nil),
(@zwp_linux_surface_synchronization_v1_interface),
(@wl_surface_interface),
(@zwp_linux_buffer_release_v1_interface)
);
zwp_linux_explicit_synchronization_v1_requests: array[0..1] of Twl_message = (
(name: 'destroy'; signature: ''; types: @pInterfaces[0]),
(name: 'get_synchronization'; signature: 'no'; types: @pInterfaces[8])
);
zwp_linux_surface_synchronization_v1_requests: array[0..2] of Twl_message = (
(name: 'destroy'; signature: ''; types: @pInterfaces[0]),
(name: 'set_acquire_fence'; signature: 'h'; types: @pInterfaces[0]),
(name: 'get_release'; signature: 'n'; types: @pInterfaces[10])
);
zwp_linux_buffer_release_v1_events: array[0..1] of Twl_message = (
(name: 'fenced_release'; signature: 'h'; types: @pInterfaces[0]),
(name: 'immediate_release'; signature: ''; types: @pInterfaces[0])
);
initialization
Pointer(vIntf_zwp_linux_buffer_release_v1_Listener.fenced_release) := @zwp_linux_buffer_release_v1_fenced_release_Intf;
Pointer(vIntf_zwp_linux_buffer_release_v1_Listener.immediate_release) := @zwp_linux_buffer_release_v1_immediate_release_Intf;
zwp_linux_explicit_synchronization_v1_interface.name := 'zwp_linux_explicit_synchronization_v1';
zwp_linux_explicit_synchronization_v1_interface.version := 2;
zwp_linux_explicit_synchronization_v1_interface.method_count := 2;
zwp_linux_explicit_synchronization_v1_interface.methods := @zwp_linux_explicit_synchronization_v1_requests;
zwp_linux_explicit_synchronization_v1_interface.event_count := 0;
zwp_linux_explicit_synchronization_v1_interface.events := nil;
zwp_linux_surface_synchronization_v1_interface.name := 'zwp_linux_surface_synchronization_v1';
zwp_linux_surface_synchronization_v1_interface.version := 2;
zwp_linux_surface_synchronization_v1_interface.method_count := 3;
zwp_linux_surface_synchronization_v1_interface.methods := @zwp_linux_surface_synchronization_v1_requests;
zwp_linux_surface_synchronization_v1_interface.event_count := 0;
zwp_linux_surface_synchronization_v1_interface.events := nil;
zwp_linux_buffer_release_v1_interface.name := 'zwp_linux_buffer_release_v1';
zwp_linux_buffer_release_v1_interface.version := 1;
zwp_linux_buffer_release_v1_interface.method_count := 0;
zwp_linux_buffer_release_v1_interface.methods := nil;
zwp_linux_buffer_release_v1_interface.event_count := 2;
zwp_linux_buffer_release_v1_interface.events := @zwp_linux_buffer_release_v1_events;
end.
|
unit tanque;
interface
uses
SysUtils, DateUtils;
type
T_Tanque = class(TObject)
private
F_Id: Integer;
F_Capacidade_Litros: Double;
F_Quantidade_Litros: Double;
F_TipoCombustivel_Id: Integer;
// F_Id
procedure setId(pId: Integer);
function getId(): Integer;
// F_Capacidade_Litros
procedure setCapacidade_Litros(pCapacidade_Litros: Double);
function getCapacidade_Litros(): Double;
// F_Quantidade_Litros
procedure setQuantidade_Litros(pQuantidade_Litros: Double);
function getQuantidade_Litros(): Double;
// F_TipoCombustivel_Id
procedure setTipoCombustivel_Id(pTipoCombustivel_Id: Integer);
function getTipoCombustivel_Id(): Integer;
public
constructor Create(
pId: Integer;
pCapacidade_Litros: Double;
pQuantidade_Litros: Double;
pTipoCombustivel_Id: Integer); overload;
constructor Create(); overload;
published
property Id: Integer read getId write setId;
property Capacidade_Litros: Double read getCapacidade_Litros write setCapacidade_Litros;
property Quantidade_Litros: Double read getQuantidade_Litros write setQuantidade_Litros;
property TipoCombustivel_Id: Integer read getTipoCombustivel_Id write setTipoCombustivel_Id;
end;
implementation
constructor T_Tanque.Create(
pId: Integer;
pCapacidade_Litros: Double;
pQuantidade_Litros: Double;
pTipoCombustivel_Id: Integer);
begin
F_Id := pId;
F_Capacidade_Litros := pCapacidade_Litros;
F_Quantidade_Litros := pQuantidade_Litros;
F_TipoCombustivel_Id := pTipoCombustivel_Id;
end;
constructor T_Tanque.Create();
begin
end;
// F_Id
procedure T_Tanque.setId(pId: Integer);
begin
F_Id := pId;
end;
function T_Tanque.getId(): Integer;
begin
result := F_Id;
end;
// F_Capacidade_Litros
procedure T_Tanque.setCapacidade_Litros(pCapacidade_Litros: Double);
begin
F_Capacidade_Litros := pCapacidade_Litros;
end;
function T_Tanque.getCapacidade_Litros(): Double;
begin
result := F_Capacidade_Litros;
end;
// F_Quantidade_Litros
procedure T_Tanque.setQuantidade_Litros(pQuantidade_Litros: Double);
begin
F_Quantidade_Litros := pQuantidade_Litros;
end;
function T_Tanque.getQuantidade_Litros(): Double;
begin
result := F_Quantidade_Litros;
end;
// F_TipoCombustivel_Id
procedure T_Tanque.setTipoCombustivel_Id(pTipoCombustivel_Id: Integer);
begin
F_TipoCombustivel_Id := pTipoCombustivel_Id;
end;
function T_Tanque.getTipoCombustivel_Id(): Integer;
begin
result := F_TipoCombustivel_Id;
end;
end.
|
unit uRamalItensVO;
interface
uses
System.SysUtils, uTableName, uKeyField, System.Generics.Collections;
type
[TableName('Ramal_Itens')]
TRamalItensVO = class
private
FIdRamal: Integer;
FId: Integer;
FNumero: Integer;
FNome: string;
procedure SetId(const Value: Integer);
procedure SetIdRamal(const Value: Integer);
procedure SetNome(const Value: string);
procedure SetNumero(const Value: Integer);
public
[KeyField('RamIt_Id')]
property Id: Integer read FId write SetId;
[FieldName('RamIt_Ramal')]
property IdRamal: Integer read FIdRamal write SetIdRamal;
[FieldName('RamIt_Nome')]
property Nome: string read FNome write SetNome;
[FieldName('RamIt_Numero')]
property Numero: Integer read FNumero write SetNumero;
end;
TListaRamalItens = TObjectList<TRamalItensVO>;
implementation
{ TRamalItensVO }
procedure TRamalItensVO.SetId(const Value: Integer);
begin
FId := Value;
end;
procedure TRamalItensVO.SetIdRamal(const Value: Integer);
begin
FIdRamal := Value;
end;
procedure TRamalItensVO.SetNome(const Value: string);
begin
FNome := Value;
end;
procedure TRamalItensVO.SetNumero(const Value: Integer);
begin
FNumero := Value;
end;
end.
|
unit MVCBr.PersistentModel;
interface
uses System.Classes, System.SysUtils, MVCBr.Interf, MVCBr.Model,
MVCBr.Controller;
Type
TPersistentModelFactory = class(TModelFactory, IPersistentModel)
protected
FController:IController;
public
function Controller(const AController: IController): IPersistentModel;
end;
implementation
{ TPersistentModelFactory }
function TPersistentModelFactory.Controller(const AController: IController)
: IPersistentModel;
begin
FController := AController;
end;
end.
|
unit ulimitedstringlist;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
TLimitedStringList = class(TObject)
private
FIndexOfInsert: integer;
FList: TStringList;
function Get(Index: integer): string;
function GetCount: integer;
public
constructor Create(AMaxCount: integer);
destructor Destroy; override;
procedure Append(const S: string);
procedure LoadFromFile(const FileName: string);
procedure SaveToFile(const FileName: string);
property Count: integer read GetCount;
property Strings[Index: integer]: string read Get; default;
end;
implementation
constructor TLimitedStringList.Create(AMaxCount: integer);
begin
inherited Create;
if AMaxCount <= 0 then
AMaxCount := 1;
FList := TStringList.Create;
FList.Capacity := AMaxCount;
// FIndexOfInsert := 0;
end;
procedure TLimitedStringList.Append(const S: string);
begin
if FList.Count < FList.Capacity then
FList.Append(S)
else
begin
FList[FIndexOfInsert] := S;
Inc(FIndexOfInsert);
if FIndexOfInsert >= FList.Count then
FIndexOfInsert := 0;
end;
end;
destructor TLimitedStringList.Destroy;
begin
FList.Free;
inherited;
end;
function TLimitedStringList.Get(Index: integer): string;
begin
Inc(Index, FIndexOfInsert);
if Index >= FList.Count then
Dec(Index, FList.Count);
Result := FList[Index];
end;
function TLimitedStringList.GetCount: integer;
begin
Result := FList.Count;
end;
procedure TLimitedStringList.LoadFromFile(const FileName: string);
var
TempList: TStringList;
i: integer;
Start: integer;
begin
TempList := TStringList.Create;
try
TempList.LoadFromFile(FileName, TEncoding.UTF8);
FList.Clear;
FIndexOfInsert := 0;
Start := TempList.Count - FList.Capacity;
if Start < 0 then
Start := 0;
for i := Start to TempList.Count - 1 do
Append(TempList[i]);
finally
TempList.Free;
end;
end;
procedure TLimitedStringList.SaveToFile(const FileName: string);
var
TempList: TStringList;
i: integer;
begin
TempList := TStringList.Create;
try
TempList.Capacity := FList.Capacity;
for i := 0 to FList.Count - 1 do
TempList.Append(Get(i));
try
TempList.SaveToFile(FileName);
except
on E: EFCreateError do
begin
// no hacer nada, no se pudo guardar el log
end;
end;
finally
TempList.Free;
end;
end;
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 frmAlarmHistory;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Menus, cxLookAndFeelPainters, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData,
cxGridLevel, cxClasses, cxControls, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid,
StdCtrls, cxButtons, ExtCtrls, MemDS, VirtualTable, DBAccess, Ora,
OraBarConn, cxSpinEdit, cxTimeEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, cxCalendar, cxContainer, cxLabel;
type
TAlarmHistoryFrm = class(TForm)
Panel2: TPanel;
btnRefresh: TcxButton;
GridDB: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
vtAlertHistory: TVirtualTable;
dsAlertHistory: TDataSource;
GridDBALARM_DATE: TcxGridDBColumn;
GridDBALARM_TYPE: TcxGridDBColumn;
GridDBEVENT_NAME: TcxGridDBColumn;
GridDBEVENT_STATUS: TcxGridDBColumn;
GridDBEVENT_VALUE: TcxGridDBColumn;
GridDBDATA_SOURCE: TcxGridDBColumn;
Timer: TTimer;
qAlert: TOraQuery;
btnExport: TcxButton;
btnClose: TcxButton;
Panel1: TPanel;
cxLabel1: TcxLabel;
dedtFromDate: TcxDateEdit;
tedtFromTime: TcxTimeEdit;
cxLabel2: TcxLabel;
dedtToDate: TcxDateEdit;
tedtToTime: TcxTimeEdit;
GridDBALERT_TIME: TcxGridDBColumn;
vtAlerts: TVirtualTable;
vtAlertsTYPE: TStringField;
vtAlertsNAME: TStringField;
vtAlertsDESCRIPTION: TStringField;
vtAlertsCRITICAL_STATUS: TSmallintField;
vtAlertsCRITICAL_IF: TStringField;
vtAlertsCRITICAL_VALUE: TIntegerField;
vtAlertsWARNING_STATUS: TSmallintField;
vtAlertsWARNING_IF: TStringField;
vtAlertsWARNING_VALUE: TIntegerField;
vtAlertsINFO_STATUS: TSmallintField;
vtAlertsINFO_IF: TStringField;
vtAlertsINFO_VALUE: TIntegerField;
vtAlertsSQL: TStringField;
vtAlertHistoryALERT_DATE: TDateField;
vtAlertHistoryALERT_TIME: TTimeField;
vtAlertHistoryALERT_TYPE: TStringField;
vtAlertHistoryEVENT_NAME: TStringField;
vtAlertHistoryEVENT_STATUS: TStringField;
vtAlertHistoryEVENT_VALUE: TStringField;
vtAlertHistoryDATA_SOURCE: TStringField;
lblLastRefreshTime: TcxLabel;
procedure btnCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnRefreshClick(Sender: TObject);
procedure GridDBCustomDrawCell(Sender: TcxCustomGridTableView;
ACanvas: TcxCanvas; AViewInfo: TcxGridTableDataCellViewInfo;
var ADone: Boolean);
procedure TimerTimer(Sender: TObject);
private
{ Private declarations }
FOraSession: TOraSession;
FBarConnection : TBarConnection;
procedure ControlAlertEvents;
procedure ControlEvent(sql, AlertType, EventName, EventStatus, EventIf: string; EventValue: integer);
procedure AddEvent(AlertType, EventName, EventValue, EventStatus: string);
public
{ Public declarations }
procedure Init(ABarConnection : TBarConnection);
end;
var
AlarmHistoryFrm: TAlarmHistoryFrm;
implementation
{$R *.dfm}
uses frmMain, DBQuery, OraSessions, util, AlarmOptions, VisualOptions,
GenelDM;
procedure TAlarmHistoryFrm.Init(ABarConnection : TBarConnection);
begin
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
FBarConnection := ABarConnection;
FOraSession := ABarConnection.Session;
Caption := 'Alert History for '+ FBarConnection.Session.Server;
MainFrm.dxBarListWindows.Items.AddObject(Caption, Self);
dedtFromDate.Date := Now; tedtFromTime.Time := StrToTime('00:00:00');
dedtToDate.Date := Now; tedtToTime.Time := now;
AlertOptionsLoadFromIni;
vtAlertHistory.Open;
AlertLogLoadFromFile(vtAlertHistory);
Timer.Interval := AlertRefreshInterval * 1000;
Timer.Enabled := True;
qAlert.Session := FOraSession;
btnRefresh.Click;
end;
procedure TAlarmHistoryFrm.TimerTimer(Sender: TObject);
begin
ControlAlertEvents;
lblLastRefreshTime.Caption := 'Last refresh at : '+DateTimeToStr(now);
end;
procedure TAlarmHistoryFrm.btnCloseClick(Sender: TObject);
begin
AlertLogSaveToFile(vtAlertHistory);
close;
end;
procedure TAlarmHistoryFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
qAlert.close;
with MainFrm.dxBarListWindows.Items do
Delete(IndexOfObject(Self));
Action := caFree;
end;
procedure TAlarmHistoryFrm.ControlAlertEvents;
begin
vtAlerts.Open;
if FileExists(ExtractFilePath(Application.ExeName)+'AlertEvents.vtd') then
vtAlerts.LoadFromFile(ExtractFilePath(Application.ExeName)+'AlertEvents.vtd');
vtAlerts.First;
while not vtAlerts.Eof do
begin
if vtAlerts.FieldByName('CRITICAL_STATUS').AsString = '1' then
begin
ControlEvent(vtAlerts.FieldByName('SQL').AsString,
vtAlerts.FieldByName('TYPE').AsString,
vtAlerts.FieldByName('NAME').AsString,
'Critical',
vtAlerts.FieldByName('CRITICAL_IF').AsString,
vtAlerts.FieldByName('CRITICAL_VALUE').AsInteger);
end;
if vtAlerts.FieldByName('WARNING_STATUS').AsString = '1' then
begin
ControlEvent(vtAlerts.FieldByName('SQL').AsString,
vtAlerts.FieldByName('TYPE').AsString,
vtAlerts.FieldByName('NAME').AsString,
'Warning',
vtAlerts.FieldByName('WARNING_IF').AsString,
vtAlerts.FieldByName('WARNING_VALUE').AsInteger);
end;
if vtAlerts.FieldByName('INFO_STATUS').AsString = '1' then
begin
ControlEvent(vtAlerts.FieldByName('SQL').AsString,
vtAlerts.FieldByName('TYPE').AsString,
vtAlerts.FieldByName('NAME').AsString,
'Info',
vtAlerts.FieldByName('INFO_IF').AsString,
vtAlerts.FieldByName('INFO_VALUE').AsInteger);
end;
vtAlerts.next;
end; //while
end;
procedure TAlarmHistoryFrm.ControlEvent(sql, AlertType, EventName, EventStatus, EventIf: string; EventValue: integer);
var
ShowAlert: boolean;
begin
ShowAlert := False;
qAlert.close;
qAlert.SQL.Text := SQL;
try
qAlert.Open;
if EventIf = '>' then
if qAlert.Fields[0].Value > EventValue then ShowAlert := True;
if EventIf = '<' then
if qAlert.Fields[0].Value < EventValue then ShowAlert := True;
if EventIf = '>=' then
if qAlert.Fields[0].Value >= EventValue then ShowAlert := True;
if EventIf = '<=' then
if qAlert.Fields[0].Value <= EventValue then ShowAlert := True;
if EventIf = '=' then
if qAlert.Fields[0].Value = EventValue then ShowAlert := True;
if EventIf = '<>' then
if qAlert.Fields[0].Value <> EventValue then ShowAlert := True;
except
end;
if ShowAlert then
AddEvent(AlertType,
EventName +' '+EventIf+' '+IntToStr(EventValue),
IntToStr(qAlert.Fields[0].Value),
EventStatus);
qAlert.Close;
end;
procedure TAlarmHistoryFrm.AddEvent(AlertType, EventName, EventValue, EventStatus: string);
begin
if vtAlertHistory.Locate('EVENT_NAME;EVENT_VALUE',VarArrayOf([EventName,EventValue]), []) then exit;
vtAlertHistory.Append;
vtAlertHistory.FieldByName('ALERT_DATE').AsDateTime := Now;
vtAlertHistory.FieldByName('ALERT_TIME').AsDateTime := Now;
vtAlertHistory.FieldByName('ALERT_TYPE').AsString := AlertType; //System, User
vtAlertHistory.FieldByName('EVENT_NAME').AsString := EventName;
vtAlertHistory.FieldByName('EVENT_STATUS').AsString := EventStatus; //Critical, Warning, Info
vtAlertHistory.FieldByName('EVENT_VALUE').AsString := EventValue;
vtAlertHistory.FieldByName('DATA_SOURCE').AsString := FBarConnection.Session.Server;
vtAlertHistory.Post;
Beep;
end;
procedure TAlarmHistoryFrm.btnRefreshClick(Sender: TObject);
begin
vtAlertHistory.Filtered := false;
vtAlertHistory.Filter := '(ALERT_DATE >= '+QuotedStr(dedtFromDate.Text)+') and (ALERT_TIME >= '+QuotedStr(tedtFromTime.Text)
+') and (ALERT_DATE <= '+QuotedStr(dedtToDate.Text)+') and (ALERT_TIME <= '+QuotedStr(tedtToTime.Text)+')';
vtAlertHistory.Filtered := True;
end;
procedure TAlarmHistoryFrm.GridDBCustomDrawCell(
Sender: TcxCustomGridTableView; ACanvas: TcxCanvas;
AViewInfo: TcxGridTableDataCellViewInfo; var ADone: Boolean);
begin
if AViewInfo.GridRecord.Values[0] = 'Critical' then
ACanvas.Canvas.Brush.Color := clRed;
if AViewInfo.GridRecord.Values[0] = 'Warning' then
ACanvas.Canvas.Brush.Color := clYellow;
if AViewInfo.GridRecord.Values[0] = 'Info' then
ACanvas.Canvas.Brush.Color := clGreen;
ACanvas.Canvas.FillRect(AViewInfo.Bounds);
end;
end.
|
{*******************************************************************************
作者: dmzn@163.com 2011-11-30
描述: 商品订单确认
*******************************************************************************}
unit UFormReturnConfirm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, USkinFormBase, ExtCtrls, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, StdCtrls,
UImageButton, Grids, UGridPainter, cxCheckBox, cxMaskEdit,
cxDropDownEdit, UGridExPainter, Menus, cxButtons;
type
TfFormReturnConfirm = class(TSkinFormBase)
LabelHint: TLabel;
GridList: TDrawGridEx;
Panel1: TPanel;
Panel2: TPanel;
BtnOK: TImageButton;
BtnCancel: TImageButton;
Label1: TLabel;
EditID: TcxTextEdit;
Label2: TLabel;
EditMan: TcxTextEdit;
Label3: TLabel;
EditTime: TcxTextEdit;
procedure FormCreate(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Panel1Resize(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
private
{ Private declarations }
FID,FMan,FTime: string;
FPainter: TGridPainter;
//绘制对象
procedure LoadReturnInfo(const nReturn: string);
//退货信息
public
{ Public declarations }
class function FormSkinID: string; override;
end;
function ShowReturnConfirmForm(const nReturn: string): Boolean;
//退货确认
implementation
{$R *.dfm}
uses
ULibFun, DB, UFormCtrl, USysDB, USysConst, USysFun, UDataModule, FZSale_Intf;
function ShowReturnConfirmForm(const nReturn: string): Boolean;
begin
with TfFormReturnConfirm.Create(Application) do
begin
LoadReturnInfo(nReturn);
Result := ShowModal = mrOk;
Free;
end;
end;
class function TfFormReturnConfirm.FormSkinID: string;
begin
Result := 'FormDialog';
end;
procedure TfFormReturnConfirm.FormCreate(Sender: TObject);
var nIdx: Integer;
begin
for nIdx:=ComponentCount-1 downto 0 do
if Components[nIdx] is TImageButton then
LoadFixImageButton(TImageButton(Components[nIdx]));
//xxxxx
FPainter := TGridPainter.Create(GridList);
with FPainter do
begin
HeaderFont.Style := HeaderFont.Style + [fsBold];
//粗体
AddHeader('序号', 50);
AddHeader('商品名称', 50);
AddHeader('当前进货价', 50);
AddHeader('当前库存', 50);
AddHeader('退货量', 50);
end;
LoadFormConfig(Self);
LoadDrawGridConfig(Name, GridList);
end;
procedure TfFormReturnConfirm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
SaveFormConfig(Self);
SaveDrawGridConfig(Name, GridList);
FPainter.Free;
end;
procedure TfFormReturnConfirm.BtnExitClick(Sender: TObject);
begin
Close;
end;
//Desc: 调整按钮位置
procedure TfFormReturnConfirm.Panel1Resize(Sender: TObject);
var nW,nL: Integer;
begin
nW := BtnOK.Width + 65 + BtnCancel.Width;
nL := Trunc((Panel1.Width - nW) / 2);
BtnOk.Left := nL;
BtnCancel.Left := nL + BtnOK.Width + 65;
end;
//------------------------------------------------------------------------------
//Desc: 载入退货信息
procedure TfFormReturnConfirm.LoadReturnInfo(const nReturn: string);
var nStr,nHint: string;
nDS: TDataSet;
nIdx,nInt: Integer;
nData: TGridDataArray;
begin
if nReturn = '' then
begin
nStr := 'Select Top 1 * From %s Where T_Status=''%s'' And ' +
'T_TerminalId=''%s'' Order By R_ID DESC';
nStr := Format(nStr, [sTable_Return, sFlag_BillLock, gSysParam.FTerminalID]);
end else
begin
nStr := 'Select * From %s Where T_ID=''%s'' And ' +
'(T_Status=''%s'' or T_Status=''%s'') ';
nStr := Format(nStr, [sTable_Return, nReturn, sFlag_BillLock, sFlag_BillNew]);
end;
nDS := FDM.LockDataSet(nStr, nHint);
try
if not Assigned(nDS) then
begin
ShowDlg(nHint, sWarn); Exit;
end;
if nDS.RecordCount > 0 then
begin
FID := nDS.FieldByName('T_ID').AsString;
FMan := nDS.FieldByName('T_Man').AsString;
FTime := DateTime2Str(nDS.FieldByName('T_Date').AsDateTime);
end;
finally
FDM.ReleaseDataSet(nDS);
end;
if FID = '' then
begin
ShowMsg('没有待确认的退货单', sHint);
Exit;
end;
EditID.Text := FID;
EditMan.Text := FMan;
EditTime.Text := FTime;
nStr := 'Select rd.*,StyleName,SizeName,ColorName,P_Price,P_Number From $RD rd ' +
' Left Join $PT pt On pt.ProductID=rd.D_Product ' +
' Left Join $SZ sz On sz.SizeID=pt.SizeID ' +
' Left Join $CR cr On cr.ColorID=pt.ColorID ' +
' Left Join $ST st On st.StyleID=pt.StyleID ' +
' Left Join $TP tp On tp.P_ID=rd.D_Product ' +
'Where D_Return=''$ID'' Order by rd.R_ID';
//xxxxx
nStr := MacroValue(nStr, [MI('$RD', sTable_ReturnDtl),
MI('$TP', sTable_Product), MI('$PT', sTable_DL_Product),
MI('$SZ', sTable_DL_Size), MI('$CR', sTable_DL_Color),
MI('$ST', sTable_DL_Style), MI('$ID', FID)]);
//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
nInt := 1;
First;
nStr := FieldByName('StyleName').AsString;
LabelHint.Caption := Format('%s款式退货单确认', [nStr]);
while not Eof do
begin
SetLength(nData, 6);
for nIdx:=Low(nData) to High(nData) do
begin
nData[nIdx].FCtrls := nil;
nData[nIdx].FAlign := taCenter;
end;
nStr := Format('%s_%s_%s', [FieldByName('StyleName').AsString,
FieldByName('ColorName').AsString,
FieldByName('SizeName').AsString]);
//xxxxx
nData[0].FText := IntToStr(nInt);
Inc(nInt);
nData[1].FText := nStr;
nData[2].FText := Format('%.2f', [FieldByName('P_Price').AsFloat]);
nData[3].FText := FieldByName('P_Number').AsString;
nData[4].FText := FieldByName('D_Number').AsString;
nData[5].FText := FieldByName('D_Product').AsString;
FPainter.AddData(nData);
Next;
end;
end;
finally
FDM.ReleaseDataSet(nDS);
end;
end;
//Desc: 确定
procedure TfFormReturnConfirm.BtnOKClick(Sender: TObject);
var nStr,nHint: string;
nIdx: Integer;
nSQLList: SQLItems;
begin
nStr := '要确认编号为[ %s ]的退货单吗?';
nStr := Format(nStr, [FID]);
if not QueryDlg(nStr, sAsk, Handle) then Exit;
nSQLList := SQLItems.Create;
try
nStr := 'Update %s Set T_Status=''%s'',T_ActMan=''%s'',T_ActDate=%s ' +
'Where T_ID=''%s''';
nStr := Format(nStr, [sTable_Return, sFlag_BillNew, gSysParam.FUserID,
sField_SQLServer_Now, FID]);
//xxxxx
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
for nIdx:=0 to FPainter.DataCount - 1 do
begin
nStr := 'Update %s Set P_Number=P_Number-(%s) ' +
'Where P_TerminalId=''%s'' And P_ID=''%s''';
nStr := Format(nStr, [sTable_Product, FPainter.Data[nIdx][4].FText,
gSysParam.FTerminalID, FPainter.Data[nIdx][5].FText]);
//xxxxx
with nSQLList.Add do
begin
SQL := nStr;
IfRun := '';
IfType := 0;
end;
end;
if FDM.SQLUpdates(nSQLList, True, nHint) > 0 then
begin
ShowMsg('退货单确认成功', sHint);
ModalResult := mrOk;
end else ShowDlg(nHint, sWarn, Handle);
finally
//nSQLList.Free;
end;
end;
//Desc: 取消订单
procedure TfFormReturnConfirm.BtnCancelClick(Sender: TObject);
var nStr,nHint: string;
begin
nStr := '要取消编号为[ %s ]的退货单吗?' + #32#32#13#10#13#10 +
'取消后退货单将作废.';
nStr := Format(nStr, [FID]);
if not QueryDlg(nStr, sAsk, Handle) then Exit;
nStr := 'Update %s Set T_Status=''%s'',T_ActMan=''%s'',T_ActDate=%s ' +
'Where T_ID=''%s''';
nStr := Format(nStr, [sTable_Return, sFlag_BillCancel, gSysParam.FUserID,
sField_SQLServer_Now, FID]);
//xxxxx
if FDM.SQLExecute(nStr, nHint) > 0 then
begin
ShowMsg('退货单已经取消', sHint);
ModalResult := mrOk;
end else ShowDlg(nHint, sWarn, Handle);
end;
end.
|
unit EVDtoNSRCPlusWriterTest;
{* Тест записи в NSRC+ }
// Модуль: "w:\common\components\rtl\Garant\Daily\EVDtoNSRCPlusWriterTest.pas"
// Стереотип: "TestCase"
// Элемент модели: "TEVDtoNSRCPlusWriterTest" MUID: (4B853E7501DF)
{$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas}
interface
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3IntfUses
, EVDtoNSRCWriterTest
;
type
TEVDtoNSRCPlusWriterTest = {abstract} class(TEVDtoNSRCWriterTest)
{* Тест записи в NSRC+ }
protected
function IsNSRCPlus: Boolean; override;
function GetFolder: AnsiString; override;
{* Папка в которую входит тест }
function GetModelElementGUID: AnsiString; override;
{* Идентификатор элемента модели, который описывает тест }
end;//TEVDtoNSRCPlusWriterTest
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
implementation
{$If Defined(nsTest) AND NOT Defined(NoScripts)}
uses
l3ImplUses
, TestFrameWork
//#UC START# *4B853E7501DFimpl_uses*
//#UC END# *4B853E7501DFimpl_uses*
;
function TEVDtoNSRCPlusWriterTest.IsNSRCPlus: Boolean;
//#UC START# *4B8545CC03D2_4B853E7501DF_var*
//#UC END# *4B8545CC03D2_4B853E7501DF_var*
begin
//#UC START# *4B8545CC03D2_4B853E7501DF_impl*
Result := true;
//#UC END# *4B8545CC03D2_4B853E7501DF_impl*
end;//TEVDtoNSRCPlusWriterTest.IsNSRCPlus
function TEVDtoNSRCPlusWriterTest.GetFolder: AnsiString;
{* Папка в которую входит тест }
begin
Result := 'NSRCTests';
end;//TEVDtoNSRCPlusWriterTest.GetFolder
function TEVDtoNSRCPlusWriterTest.GetModelElementGUID: AnsiString;
{* Идентификатор элемента модели, который описывает тест }
begin
Result := '4B853E7501DF';
end;//TEVDtoNSRCPlusWriterTest.GetModelElementGUID
{$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts)
end.
|
{***************************************************************************}
{ }
{ VCL.Menus.Helpers }
{ }
{ 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 VCL.Menus.Helpers;
interface
uses VCL.Menus, System.SysUtils, System.Classes;
Type
TMenuItemAnonimous = class(TMenuItem)
private
FProc: TProc;
procedure DoClick(Sender: TObject);
public
constructor create(AOwner: TComponent; AProc: TProc);
end;
TMenuItemHelper = class helper for TMenuItem
public
function CreateAnonimous(ACaption: string; AProc: TProc)
: TMenuItemAnonimous; overload;
function CreateAnonimous(AProc: TProc): TMenuItemAnonimous; overload;
end;
implementation
function TMenuItemHelper.CreateAnonimous(AProc: TProc): TMenuItemAnonimous;
begin
result := TMenuItemAnonimous.create(self, AProc);
Add(result);
end;
function TMenuItemHelper.CreateAnonimous(ACaption: string; AProc: TProc)
: TMenuItemAnonimous;
begin
result := CreateAnonimous(AProc);
result.Caption := ACaption;
end;
procedure TMenuItemAnonimous.DoClick(Sender: TObject);
begin
if assigned(FProc) then
FProc;
end;
constructor TMenuItemAnonimous.create(AOwner: TComponent; AProc: TProc);
begin
inherited create(AOwner);
OnClick := DoClick;
FProc := AProc;
end;
end.
|
unit SiteMan;
interface
uses ElVCLUtils, ElTools, ElGraphs, ElPgCtl, ExtCtrls, Classes, Forms, SysUtils, ElTimers;
type TSite = class
private
FInterval: integer;
procedure SetInterval(Value : integer);
procedure SetRepCount(Value : integer);
//procedure SetRepFile (Value : string);
public
Shutdown : boolean;
Address : string;
HostName : string;
Timeout : integer;
Graph : TElGraph;
Sheet : TElTabSheet;
StartTime : string;
ThreadList : TList;
Timer : TElTimerPoolItem;
FRepFile : string;
F : TextFile;
FRepCount,
RepNow : integer;
procedure SaveValue;
procedure Start;
destructor Destroy; override;
procedure TimerProc(Sender:TObject);
procedure OnThreadFinish(Sender:TObject);
property RepFile : string read FRepFile write FRepFile;
property RepCount : integer read FRepCount write SetRepCount;
property Interval : integer read FInterval write SetInterval;
end;
implementation
uses PingThread, Main;
procedure TSite.SetRepCount(Value : integer);
begin
if (FRepFile <> '') and (Value >0) and (Value <>FRepCount) then
begin
if (FRepCount = 0) then
begin
try
if not FileExists(FRepFile) then
begin
AssignFile(F, FRepFile);
Rewrite(F);
end else
begin
AssignFile(F, FRepFile);
Append(F);
end;
Writeln(F, '');
Write(F, 'Time: ', DateTimeToStr(Now));
WriteLn(F, ' EldoS Pinger started logging.');
CloseFile(F);
except
end;
end;
end;
FRepCount := Value;
end;
procedure TSite.SetInterval;
begin
if (Value <> FInterval) and (Value >=500) then
begin
FInterval := Value;
Timer.Interval := Value;
end;
end;
procedure TSite.Start;
begin
ThreadList:=TList.Create;
if Interval = 0 then
FInterval := 1000;
Timer := MainForm.TimerList.Items.Add;
Timer.Interval := FInterval;
Timer.OnTimer := Self.TimerProc;
Timer.Enabled := true;
end;
destructor TSite.Destroy;
begin
FreeAndNil(Timer);
while ThreadList.Count > 0 do Application.ProcessMessages;
ThreadList.Free;
inherited;
end;
procedure TSite.OnThreadFinish(Sender:TObject);
begin
ThreadList.Remove(Sender);
end;
procedure TSite.TimerProc;
var Thread : TPingThread;
begin
if Shutdown then exit;
Thread := TPingThread.Create(true);
Thread.Address:=Address;
Thread.Graph:=Graph;
Thread.Site := Self;
Thread.Timeout := Timeout;
Thread.FreeOnTerminate:=true;
Thread.OnTerminate:=OnThreadFinish;
ThreadList.Add(Thread);
Thread.Resume;
end;
procedure TSite.SaveValue; { public }
var Min,
Max,
Avg : integer;
begin
if (RepCount = 0) or (RepFile = '') then exit;
inc (RepNow);
if RepNow >= RepCount then
begin
RepNow := 0;
try
AssignFile(F, RepFile);
Append(F);
Write(F, 'Time: ', DateTimeToStr(Now));
Write(F, ' Faults: ', Graph.DataList[0].Faults);
Graph.DataList[0].CalcMinMax(Min, Max, Avg);
Write(F, ' Average: ', Avg);
WriteLn(F, ' Last: ', Graph.DataList[0].Value[Graph.DataList[0].ValueCount-1]);
CloseFile(F);
except
on E: Exception do ;
end;
end;
end; { SaveValue }
end.
|
{ Version 1.0 - Author jasc2v8 at yahoo dot com
This is free and unencumbered software released into the public domain.
For more information, please refer to <http://unlicense.org> }
unit threadunit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TThreadUnit }
TThreadUnit = class(TThread)
private
FActive: boolean;
FStatus: string;
FName: string;
procedure Update;
procedure OnTerminate;
protected
procedure Execute; override;
public
property Active: boolean Read FActive Write FActive;
property Status: string Read FStatus Write FStatus;
property Name: string Read FName Write FName;
constructor Create(CreateSuspended: Boolean);
end;
implementation
uses Unit1;
{ TThreadUnit }
procedure TThreadUnit.OnTerminate;
begin
Form1.Memo1.Append('Terminate : '+Name);
end;
procedure TThreadUnit.Update;
begin
Form1.Memo1.Append(Status);
end;
procedure TThreadUnit.Execute;
var
i: integer;
begin
{ simulate some work }
while true do begin
if Terminated then break;
Sleep(Random(500)+500);
Status:=Name+' count: '+i.ToString;
if FActive then begin
Inc(i);
Synchronize(@Update);
end;
end;
Synchronize(@OnTerminate);
end;
constructor TThreadUnit.Create(CreateSuspended: Boolean);
begin
inherited Create(CreateSuspended);
FActive:=True;
FreeOnTerminate:=True;
end;
end.
|
{*********************************************}
{ }
{ ATImageMap component }
{ Copyright (c) 2008 Alexey Torgashin }
{ http://atorg.net.ru }
{ }
{*********************************************}
{$BOOLEVAL OFF} //Short bool evaluation
//Note: define "TEST" will draw test grid
unit ATImageMap;
interface
uses
Windows, Messages, Classes, Controls, Graphics,
StdCtrls, ExtCtrls, Dialogs,
Forms, FBits, ATImage;
{ Constants }
const
cATMaxImagesX = 10 * 1000; //Max parts on X, Y
cATMaxImages = 100 * 1000; //Max parts total
cATMinScale = 0.0; //Min scale
cATMaxScale = 1000.0; //Max scale
type
PATImageRec = ^TATImageRec;
TATImageRec = record
Image: TATImageEx;
Shown: Boolean;
end;
PATImageArray = ^TATImageArray;
TATImageArray = array[0 .. Pred(cATMaxImages)] of TATImageRec;
type
TImageBoxIndexShow = procedure(Sender: TObject; AI, AJ: Integer; AValue: Boolean) of object;
type
TATImageMap = class(TScrollBox)
private
FImageW: Integer; //Tested with 250x190
FImageH: Integer;
FImage: PATImageArray;
FPanel: TPaintBox;
FFocusable: Boolean;
FImageWidth: Integer;
FImageHeight: Integer;
FImageScale: Extended;
FImageKeepPosition: Boolean;
FImageDrag: Boolean;
FImageDragCursor: TCursor;
FImageDragging: Boolean;
FImageDraggingPoint: TPoint;
FOnScroll: TNotifyEvent;
FOnOptionsChange: TNotifyEvent;
FOnIndexShow: TImageBoxIndexShow;
FBitsObject: TBitsObject;
//FX: Integer;
//FY: Integer;
//procedure SavePosition;
//procedure RestorePosition;
procedure DoScroll;
procedure DoOptionsChange;
procedure DoIndexShow(AI, AJ: Integer; AValue: Boolean);
procedure MouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure MouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
procedure UpdateImage(I, J: Integer);
procedure UpdateImagePosition(AKeep: Boolean = False);
procedure UpdateImageShown;
procedure SetImageScale(AValue: Extended);
procedure ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateParts(APartsX, APartsY: Integer);
procedure CreateImage(I, J: Integer);
function GetImage(X, Y: Integer): PATImageRec;
procedure IncreaseImageScale(AIncrement: Boolean);
property ImageWidth: Integer read FImageWidth;
property ImageHeight: Integer read FImageHeight;
property ImageScale: Extended read FImageScale write SetImageScale;
property Panel: TPaintBox read FPanel;
//Bits code
function AddBit(const Info: TBitInfo; Redraw: Boolean = True): Integer;
function GetBit(Id: Integer; var Info: TBitInfo; Scaled: Boolean = True): Boolean;
function DeleteBit(Id: Integer; Redraw: Boolean = True): Boolean;
function SetBit(Id: Integer; const Info: TBitInfo; InfoSet: TBitInfoSet; Redraw: Boolean = True): Boolean;
function AddTrackItem(Id: Integer; P: TPoint; Redraw: Boolean = True): Boolean;
function BitsCount: Integer;
property BitsObject: TBitsObject read FBitsObject;
//Indexes code
procedure PanelPaint(Sender: TObject);
function ShowRect(I, J: Integer): TRect;
function IndexRect(I, J: Integer): TRect;
procedure PaintIndexes(LastOnly: Boolean = False);
procedure LoadIndexFromFile(I, J: Integer; const FN: string);
procedure FreeIndex(I, J: Integer);
procedure PositionToIndex(I, J: Integer; center: boolean = false);
function IsIndexLoaded(I, J: Integer): Boolean;
function IsIndexShown(I, J: Integer): Boolean;
protected
procedure WMHScroll(var Msg: TMessage); message WM_HSCROLL;
procedure WMVScroll(var Msg: TMessage); message WM_VSCROLL;
procedure WMGetDlgCode(var Message: TMessage); message WM_GETDLGCODE;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Resize; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
published
property Focusable: Boolean read FFocusable write FFocusable default True;
property ImageKeepPosition: Boolean read FImageKeepPosition write FImageKeepPosition default True;
property ImageDrag: Boolean read FImageDrag write FImageDrag default True;
property ImageDragCursor: TCursor read FImageDragCursor write FImageDragCursor default crSizeAll;
property OnScroll: TNotifyEvent read FOnScroll write FOnScroll;
property OnOptionsChange: TNotifyEvent read FOnOptionsChange write FOnOptionsChange;
property OnIndexShow: TImageBoxIndexShow read FOnIndexShow write FOnIndexShow;
end;
procedure FixIcon(AIcon: TIcon);
function FixPictureFormat(APicture: TPicture; ABackColor: TColor): Boolean;
procedure Register;
//-----------------------------------------------------------------
implementation
uses
SysUtils, FTrack;
{ Constants }
const
cImageLineSize = 50; //Line size: pixels to scroll by arrows and mouse sheel
cImageGapSize = 20; //Gap size: PgUp/PgDn/Home/End scroll by control size minus gap size
{ Helper functions }
procedure FixIcon(AIcon: TIcon);
var
Bmp: TBitmap;
begin
try
Bmp := TBitmap.Create;
try
Bmp.PixelFormat := pf24bit;
Bmp.Canvas.Draw(0, 0, AIcon);
finally
Bmp.Free;
end;
except
end;
end;
{
Scaling doesn't work with icons. So, we need to convert icon to a bitmap,
preferrably with PixelFormat = pf24bit.
}
function FixPictureFormat(APicture: TPicture; ABackColor: TColor): Boolean;
var
bmp: TBitmap;
begin
Result := True;
with APicture do
if (not (Graphic is TBitmap)) or ((TBitmap(Graphic).PixelFormat <> pf24Bit)) then
try
bmp := TBitmap.Create;
try
bmp.PixelFormat := pf24bit;
bmp.Width := Graphic.Width;
bmp.Height := Graphic.Height;
bmp.Canvas.Brush.Color:= ABackColor;
bmp.Canvas.FillRect(Rect(0, 0, bmp.Width, bmp.Height));
bmp.Canvas.Draw(0, 0, Graphic);
APicture.Graphic := bmp;
finally
bmp.Free;
end;
except
Result := False;
end;
end;
{ TATImageMap }
constructor TATImageMap.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
//Create initial parts
FImage := nil;
FImageW := 0;
FImageH := 0;
CreateParts(2, 2);
//Init inherited properties
AutoScroll := False;
DoubleBuffered := True; //To remove flicker when new image is loaded
HorzScrollBar.Tracking := True;
VertScrollBar.Tracking := True;
//Init fields
FFocusable := True;
FImageWidth := 0;
FImageHeight := 0;
FImageScale := 100;
FImageKeepPosition := True;
FImageDrag := True;
FImageDragCursor := crSizeAll;
FImageDragging := False;
FImageDraggingPoint := Point(0, 0);
//Init objects
FBitsObject := TBitsObject.Create;
FPanel := TPaintBox.Create(Self);
with FPanel do
begin
Parent := Self;
SetBounds(0, 0, 200, 200);
OnMouseDown := ImageMouseDown;
OnMouseUp := ImageMouseUp;
OnMouseMove := ImageMouseMove;
{$ifdef Test}
OnPaint := PanelPaint;
{$endif}
end;
//Init event handlers
OnMouseWheelUp := MouseWheelUp;
OnMouseWheelDown := MouseWheelDown;
end;
destructor TATImageMap.Destroy;
var
i, j: Integer;
begin
for i := 1 to FImageW do
for j := 1 to FImageH do
with GetImage(i, j)^ do
if Assigned(Image) then
FreeAndNil(Image);
FreeMem(FImage);
FreeAndNil(FBitsObject);
inherited;
end;
procedure TATImageMap.CreateImage(I, J: Integer);
begin
with GetImage(I, J)^ do
if not Assigned(Image) then
begin
Image := TATImageEx.CreateObj(Self, FBitsObject);
with Image do
begin
Parent := Self;
Align := alNone;
OnMouseDown := ImageMouseDown;
OnMouseUp := ImageMouseUp;
OnMouseMove := ImageMouseMove;
end;
end;
end;
//---------------------------
procedure TATImageMap.DoScroll;
begin
UpdateImageShown;
if Assigned(FOnScroll) then
FOnScroll(Self);
end;
procedure TATImageMap.DoOptionsChange;
begin
if Assigned(FOnOptionsChange) then
FOnOptionsChange(Self);
end;
procedure TATImageMap.DoIndexShow;
begin
if Assigned(FOnIndexShow) then
FOnIndexShow(Self, AI, AJ, AValue);
end;
//---------------------------
procedure TATImageMap.WMHScroll(var Msg: TMessage);
begin
inherited;
DoScroll;
end;
procedure TATImageMap.WMVScroll(var Msg: TMessage);
begin
inherited;
DoScroll;
end;
procedure TATImageMap.MouseWheelUp(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if (Shift = []) then
begin
IncreaseImageScale(True);
FImageDragging := False;
end;
Handled := True;
end;
procedure TATImageMap.MouseWheelDown(Sender: TObject; Shift: TShiftState;
MousePos: TPoint; var Handled: Boolean);
begin
if (Shift = []) then
begin
IncreaseImageScale(False);
FImageDragging := False;
end;
Handled := True;
end;
procedure TATImageMap.WMGetDlgCode(var Message: TMessage);
begin
Message.Result := DLGC_WANTARROWS;
end;
//---------------------------
procedure TATImageMap.KeyDown(var Key: Word; Shift: TShiftState);
function PageSize(AClientSize: Integer): Integer;
begin
Result := IMax(AClientSize - cImageGapSize, AClientSize div 3 * 2);
end;
begin
case Key of
VK_LEFT:
begin
if Shift = [] then
begin
with HorzScrollBar do
Position := Position - cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with HorzScrollBar do
Position := 0;
DoScroll;
Key := 0;
end;
end;
VK_RIGHT:
begin
if Shift = [] then
begin
with HorzScrollBar do
Position := Position + cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with HorzScrollBar do
Position := Range;
DoScroll;
Key := 0;
end;
end;
VK_HOME:
if Shift = [] then
begin
with HorzScrollBar do
Position := Position - PageSize(ClientWidth);
DoScroll;
Key := 0;
end;
VK_END:
if Shift = [] then
begin
with HorzScrollBar do
Position := Position + PageSize(ClientWidth);
DoScroll;
Key := 0;
end;
VK_UP:
begin
if Shift = [] then
begin
with VertScrollBar do
Position := Position - cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with VertScrollBar do
Position := 0;
DoScroll;
Key := 0;
end;
end;
VK_DOWN:
begin
if Shift = [] then
begin
with VertScrollBar do
Position := Position + cImageLineSize;
DoScroll;
Key := 0;
end
else
if Shift = [ssCtrl] then
begin
with VertScrollBar do
Position := Range;
DoScroll;
Key := 0;
end;
end;
VK_PRIOR:
if Shift = [] then
begin
with VertScrollBar do
Position := Position - PageSize(ClientHeight);
DoScroll;
Key := 0;
end;
VK_NEXT:
if Shift = [] then
begin
with VertScrollBar do
Position := Position + PageSize(ClientHeight);
DoScroll;
Key := 0;
end;
end;
end;
//---------------------------
function TATImageMap.IndexRect(I, J: Integer): TRect;
var
ANewWidth, ANewHeight,
ANewLeft, ANewTop: Integer;
begin
ANewWidth := Trunc(FImageWidth * FImageScale / 100);
ANewHeight := Trunc(FImageHeight * FImageScale / 100);
ANewLeft := Trunc((i - 1) * FImageWidth * FImageScale / 100);
ANewTop := Trunc((j - 1) * FImageHeight * FImageScale / 100);
Result := Bounds(
ANewLeft,
ANewTop,
ANewWidth,
ANewHeight);
end;
function TATImageMap.ShowRect(I, J: Integer): TRect;
begin
Result := IndexRect(i, j);
OffsetRect(Result, FPanel.Left, FPanel.Top);
end;
//---------------------------
procedure TATImageMap.UpdateImage(I, J: Integer);
begin
with GetImage(i, j)^ do
if Assigned(Image) then
begin
Image.XOffset := IndexRect(i, j).Left;
Image.YOffset := IndexRect(i, j).Top;
Image.Scale := FImageScale / 100;
Image.BoundsRect := ShowRect(i, j);
Image.Invalidate;
end;
end;
//---------------------------
procedure TATImageMap.UpdateImagePosition;
var
i, j: Integer;
SW, SH: Integer;
begin
if not AKeep then
begin
HorzScrollBar.Position := 0;
VertScrollBar.Position := 0;
end;
SW := Round(FImageWidth * FImageW * FImageScale / 100);
SH := Round(FImageHeight * FImageH * FImageScale / 100);
FPanel.Width:= SW;
FPanel.Height:= SH;
HorzScrollBar.Range := SW;
VertScrollBar.Range := SH;
UpdateImageShown;
for i := 1 to FImageW do
for j := 1 to FImageH do
begin
UpdateImage(i, j);
end;
end;
//---------------------------
{
procedure TATImageMap.SavePosition;
var
p: TPoint;
begin
p := FPanel.ScreenToClient(Mouse.CursorPos);
FX := Trunc(p.x *100 / FImageScale / FImageWidth) + 1;
FY := Trunc(p.y *100 / FImageScale / FImageHeight) + 1;
end;
procedure TATImageMap.RestorePosition;
begin
PositionToIndex(FX, FY, True);
end;
}
procedure TATImageMap.Resize;
begin
inherited;
DoScroll;
end;
//---------------------------
procedure TATImageMap.SetImageScale(AValue: Extended);
begin
Assert((AValue >= cATMinScale) and (AValue <= cATMaxScale), 'Invalid scale value');
if FImageScale <> AValue then
begin
FImageScale := AValue;
UpdateImagePosition(True);
DoOptionsChange;
end;
end;
//---------------------------
procedure TATImageMap.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
if FFocusable then
SetFocus;
end;
//---------------------------
procedure TATImageMap.ImageMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if FFocusable then
SetFocus;
if (Button = mbLeft) then
begin
if FImageDrag then
begin
FImageDragging := True;
FImageDraggingPoint := Point(X, Y);
Screen.Cursor := FImageDragCursor;
FMapImagesStop := True; //Don't redraw on dragging!
end;
end;
end;
procedure TATImageMap.ImageMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
if (Button = mbLeft) then
begin
FImageDragging := False;
Screen.Cursor := crDefault;
FMapImagesStop := False; //Can redraw again
Repaint;
DoScroll;
end;
end;
procedure TATImageMap.ImageMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if FImageDrag and FImageDragging then
begin
HorzScrollBar.Position := HorzScrollBar.Position + (FImageDraggingPoint.X - X);
VertScrollBar.Position := VertScrollBar.Position + (FImageDraggingPoint.Y - Y);
//Repaint; //To draw on mouse move
//DoScroll;
end;
end;
//---------------------------
procedure TATImageMap.IncreaseImageScale(AIncrement: Boolean);
const
cViewerImageScales: array[1 .. 34] of Integer = (
1, 2, 4, 7, 10, 15, 20, 25, 30,
40, 50, 60, 70, 80, 90, 100, 110,
125, 150, 175, 200, 250, 300, 350, 400, 450, 500,
600, 700, 800, 1000, 1200, 1400, 1600);
var
i: Integer;
begin
if AIncrement then
begin
for i := Low(cViewerImageScales) to High(cViewerImageScales) do
if cViewerImageScales[i] > ImageScale then
begin
ImageScale := cViewerImageScales[i];
Break;
end;
end
else
begin
for i := High(cViewerImageScales) downto Low(cViewerImageScales) do
if cViewerImageScales[i] < ImageScale then
begin
ImageScale := cViewerImageScales[i];
Break;
end;
end;
end;
//---------------------------
function TATImageMap.GetBit;
var
AScale: Extended;
begin
Result := fBitsObject.GetBit(Id, Info);
if Scaled and (FImageWidth > 0) then
AScale := Width / FImageWidth
else
AScale := 1.0;
Info.X1 := Trunc(Info.X1 * AScale);
Info.Y1 := Trunc(Info.Y1 * AScale);
Info.X2 := Trunc(Info.X2 * AScale);
Info.Y2 := Trunc(Info.Y2 * AScale);
end;
function TATImageMap.AddBit(const Info: TBitInfo; Redraw: Boolean = True): Integer;
begin
Result := fBitsObject.AddBit(Info);
if Redraw then
PaintIndexes(True);
end;
function TATImageMap.DeleteBit;
begin
Result := fBitsObject.DeleteBit(Id);
if Redraw then
PaintIndexes;
end;
function TATImageMap.SetBit;
begin
Result := fBitsObject.SetBit(Id, Info, InfoSet);
if Redraw then
PaintIndexes;
end;
function TATImageMap.AddTrackItem;
begin
Result := fBitsobject.AddTrackItem(Id, P);
if Redraw then
PaintIndexes;
end;
procedure TATImageMap.PaintIndexes;
var
i, j: Integer;
begin
for i := 1 to FImageW do
for j := 1 to FImageH do
with GetImage(i, j)^ do
if Assigned(Image) then
begin
if LastOnly then
Image.PaintLast
else
Image.Invalidate;
end;
end;
//-----------------------------
procedure TATImageMap.FreeIndex(I, J: Integer);
begin
with GetImage(i, j)^ do
if Assigned(Image) then
FreeAndNil(Image);
end;
//-----------------------------
procedure TATImageMap.LoadIndexFromFile(I, J: Integer; const FN: string);
begin
Assert((i > 0) and (i <= FImageW), Format('Wrong index X: %d', [I]));
Assert((j > 0) and (j <= FImageH), Format('Wrong index Y: %d', [J]));
CreateImage(i, j);
with GetImage(i, j)^ do
begin
Assert(Assigned(Image), 'Image not assigned after CreateImage');
Image.Visible := False;
Image.LoadFromFile(FN);
FImageWidth := Image.ImageWidth;
FImageHeight := Image.ImageHeight;
UpdateImage(i, j);
Image.Visible := True;
Application.ProcessMessages;
end;
end;
//-----------------------------
procedure TATImageMap.PositionToIndex;
var
X, Y: Integer;
begin
X := 0;
Y := 0;
if Center then X := Trunc(FImageWidth / 2 * FImageScale / 100) - ClientWidth div 2;
if Center then Y := Trunc(FImageheight / 2 * FImageScale / 100) - ClientHeight div 2;
HorzScrollBar.Range := Trunc(FImageWidth * FImageW * FImageScale / 100);
VertScrollBar.Range := Trunc(FImageHeight * FImageH * FImageScale / 100);
HorzScrollBar.Position := Trunc(FImageWidth * (I - 1) * FImageScale / 100) + X;
VertScrollBar.Position := Trunc(FImageHeight * (J - 1) * FImageScale / 100) + Y;
DoScroll;
end;
//-----------------------------
function TATImageMap.IsIndexLoaded(I, J: Integer): Boolean;
begin
Assert((i > 0) and (i <= FImageW), Format('Wrong index X: %d', [I]));
Assert((j > 0) and (j <= FImageH), Format('Wrong index Y: %d', [J]));
with GetImage(i, j)^ do
Result := Assigned(Image) and
(Image.ImageWidth > 0) and (Image.ImageHeight > 0);
end;
function TATImageMap.IsIndexShown(I, J: Integer): Boolean;
begin
with GetImage(i, j)^ do
Result := Shown;
end;
//-----------------------------
//Check which images are shown on screen, which not
//(saved in Shown flags)
procedure TATImageMap.UpdateImageShown;
var
i, j: Integer;
R: TRect;
i0, i01, j0, j01: Integer;
type
PShArray = ^TShArray;
TShArray = array[0 .. Pred(cATMaxImages)] of Bool;
var
sh: PShArray;
Size: Integer;
ImgPtr: PATImageRec;
ShPtr: PBool;
function GetSh(X, Y: Integer): PBool;
begin
//Must work the same as GetImage
Result:= @(sh^[(X - 1) * FImageH + (Y - 1)]);
end;
begin
Size:= FImageW * FImageH * SizeOf(Bool);
GetMem(sh, Size);
FillChar(sh^, Size, 0);
try
R := Bounds(
HorzScrollbar.Position,
VertScrollbar.Position,
ClientWidth,
ClientHeight);
//Images are visible with indexes:
// I = I0 .. I01,
// J = J0 .. Y01
I0 := 1;
J0 := 1;
I01 := 1;
J01 := 1;
for i := 1 to FImageW do
if (FImageWidth * i * FImageScale / 100) > R.Left then begin I0 := i; Break end;
for i := FImageW downto 1 do
if (FImageWidth * (i - 1) * FImageScale / 100) < R.Right then begin I01 := i; Break end;
for j := 1 to FImageH do
if (FImageHeight * j * FImageScale / 100) > R.Top then begin J0 := j; Break end;
for j := FImageH downto 1 do
if (FImageHeight * (j - 1) * FImageScale / 100) < R.Bottom then begin J01 := j; Break end;
//d
//ShowMessage(Format('Shown: %d %d %d %d', [i0, i01, j0, j01]));
for i := i0 to i01 do
for j := j0 to j01 do
GetSh(i, j)^ := True;
for j := 1 to FImageH do
for i := 1 to FImageW do
begin
ImgPtr := GetImage(i, j);
ShPtr := GetSh(i, j);
if Assigned(ImgPtr) and Assigned(ShPtr) then
if (ImgPtr^.Shown <> ShPtr^) then
begin
ImgPtr^.Shown := ShPtr^;
DoIndexShow(i, j, ShPtr^);
end;
end;
finally
FreeMem(sh);
end;
end;
//----------------------------
function TATImageMap.BitsCount: Integer;
begin
Result := FBitsObject.BitsCount;
end;
//----------------------------
//Debug procedure
procedure TATImageMap.PanelPaint(Sender: TObject);
var
i,j : Integer;
s: string;
begin
if FImageScale >=5 then
for i := 1 to FImageW do
for j := 1 to FImageH do
with FPanel.Canvas do
begin
if Assigned(GetImage(i, j)^.Image) then
Brush.Style := bsSolid
else
Brush.Style := bsClear;
Rectangle(
Trunc((i - 1) * FImageWidth * FImageScale / 100),
Trunc((j - 1) * FImageHeight * FImageScale / 100),
Trunc(i * FImageWidth * FImageScale / 100),
Trunc(j * FImageHeight * FImageScale /100));
s := Format('%d,%d', [i, j]);
if Assigned(GetImage(i, j)^.Image) then
s := '(loaded)';
TextOut(
Trunc((i-1)*FImageWidth * FImageScale / 100),
Trunc((j-1)*FImageHeight * FImageScale / 100), s);
end;
end;
//-------------------------------
procedure TATImageMap.CreateParts(APartsX, APartsY: Integer);
var
Size: Integer;
begin
Assert((APartsX > 0) and (APartsX <= cATMaxImagesX), 'Invalid parts number X');
Assert((APartsY > 0) and (APartsY <= cATMaxImagesX), 'Invalid parts number Y');
Assert((APartsX * APartsY) <= cATMaxImages, 'Too many parts X * Y');
if Assigned(FImage) then
begin
FreeMem(FImage);
FImage := nil;
end;
try
FImageW := APartsX;
FImageH := APartsY;
Size := FImageW * FImageH * SizeOf(TATImageRec);
GetMem(FImage, Size);
FillChar(FImage^, Size, 0);
except
FImage := nil;
FImageW := 0;
FImageH := 0;
end;
end;
//----------------------------
function TATImageMap.GetImage(X, Y: Integer): PATImageRec;
begin
Assert((X > 0) and (X <= FImageW), 'Invalid image index X');
Assert((Y > 0) and (Y <= FImageH), 'Invalid image index Y');
Result := @(FImage^[(X - 1) * FImageH + (Y - 1)]);
end;
//----------------------------
{ Registration }
procedure Register;
begin
RegisterComponents('Samples', [TATImageMap]);
end;
end.
|
unit uPlayer;
interface
uses
glr_core,
glr_render2d,
glr_math,
glr_utils,
uUnit;
type
{ TArenaPlayer }
TArenaPlayer = class (TArenaUnit)
private
fMeleeAttackInProgress: Boolean;
// procedure MeleeAttack1(const dt: Double);
// procedure MeleeAttack2(const dt: Double);
// procedure MeleeAttack3();
protected
fAnimator: TglrActionManager;
procedure DoRender(SpriteBatch: TglrSpriteBatch; FontBatch: TglrFontBatch=nil); override;
procedure Control(const dt: Double); override;
procedure MeleeAttack();
public
Sword: TglrSprite;
Sword2: TglrSprite;
constructor Create; override;
destructor Destroy; override;
procedure Spawn(Position: TglrVec3f); override;
procedure OnInputReceived(Event: PglrInputEvent);
end;
implementation
uses
uColors,
uAssets;
{ TArenaPlayer }
(*
procedure TArenaPlayer.MeleeAttack1(const dt: Double);
begin
fMeleeAttackInProgress := true;
Sword.Rotation := Sword.Rotation + dt * 720;
end;
procedure TArenaPlayer.MeleeAttack2(const dt: Double);
begin
Sword.Rotation := Sword.Rotation + dt * 720;
Sprite.Rotation := Sprite.Rotation + dt * 720;
end;
procedure TArenaPlayer.MeleeAttack3;
begin
fMeleeAttackInProgress := False;
Sword.Rotation := -45;
end;
*)
procedure TArenaPlayer.DoRender(SpriteBatch: TglrSpriteBatch;
FontBatch: TglrFontBatch);
begin
inherited DoRender(SpriteBatch, FontBatch);
SpriteBatch.Draw(Sword);
end;
procedure TArenaPlayer.Control(const dt: Double);
begin
inherited Control(dt);
// Moving
fControlVector.Reset();
if (Core.Input.KeyDown[kW] or Core.Input.KeyDown[kUp]) then
fControlVector.y := -1
else if (Core.Input.KeyDown[kS] or Core.Input.KeyDown[kDown]) then
fControlVector.y := 1;
if (Core.Input.KeyDown[kA] or Core.Input.KeyDown[kLeft]) then
fControlVector.x := -1
else if (Core.Input.KeyDown[kD] or Core.Input.KeyDown[kRight]) then
fControlVector.x := 1;
if (fControlVector.LengthQ > cEPS) then
fControlVector.Normalize();
// Rotating
if not fMeleeAttackInProgress then
fDirection := (Assets.MainCamera.ScreenToWorld(Core.Input.MousePos) - Vec2f(Sprite.Position)).Normal;
fAnimator.Update(dt);
end;
procedure TArenaPlayer.MeleeAttack;
begin
(*
if fMeleeAttackInProgress then
Exit();
fAnimator.AddToQueue(MeleeAttack1, 0.25);
fAnimator.AddToQueue(MeleeAttack2, 0.5);
fAnimator.AddToQueue(MeleeAttack3);
*)
end;
constructor TArenaPlayer.Create;
begin
inherited Create;
Sprite.SetVerticesColor(Color4f(1, 1, 1, 1));
Sword := TglrSprite.Create(50, 5, Vec2f(0, 0.5));
Sword.Parent := Sprite;
Sword.SetVerticesColor(Colors.Green);
fAnimator := TglrActionManager.Create();
end;
destructor TArenaPlayer.Destroy;
begin
fAnimator.Free();
Sword.Free();
inherited Destroy;
end;
procedure TArenaPlayer.Spawn(Position: TglrVec3f);
begin
inherited Spawn(Position);
Sprite.SetSize(25, 45);
DirectSpeed := 190;
Sword.Position := Vec3f(10, 10, 4);
Sword.Rotation := -45;
end;
procedure TArenaPlayer.OnInputReceived(Event: PglrInputEvent);
begin
if (Event^.InputType = itTouchDown) then
MeleeAttack();
end;
end.
|
unit TTSUSERTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TTTSUSERRecord = record
PUserName: String[10];
PModCount: Integer;
PPassword: String[50];
PRealName: String[30];
PLoggedInFlag: Boolean;
PLoggedInStamp: String[17];
PLoggedOutStamp: String[17];
PLastLender: String[50];
PLenderGroup: String[240];
PUserGroup: String[20];
PUserTable: Boolean;
PAccessGroups: Boolean;
PLenderGroups: Boolean;
PSingleLender: String[4];
PBranch: String[8];
PGUISkin :string[30];
PGUISkinDir:string[40];
PWinUser:string[20];
End;
TTTSUSERBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TTTSUSERRecord;
function FieldNameToIndex(s:string):integer;override;
function FieldType(index:integer):TFieldType;override;
end;
TEITTSUSER = (TTSUSERPrimaryKey, TTSUSERByRights, TTSUSERByLenderGroup);
TTTSUSERTable = class( TDBISAMTableAU )
private
FDFUserName: TStringField;
FDFModCount: TIntegerField;
FDFPassword: TStringField;
FDFRealName: TStringField;
FDFLoggedInFlag: TBooleanField;
FDFLoggedInStamp: TStringField;
FDFLoggedOutStamp: TStringField;
FDFLastLender: TStringField;
FDFLenderGroup: TStringField;
FDFUserGroup: TStringField;
FDFUserTable: TBooleanField;
FDFAccessGroups: TBooleanField;
FDFLenderGroups: TBooleanField;
FDFSingleLender: TStringField;
FDFBranch: TStringField;
FDFGUISkin :TStringField;
FDFGUISkinDir:TStringField;
FDFWinUser:TStringField;
procedure SetPUserName(const Value: String);
function GetPUserName:String;
procedure SetPModCount(const Value: Integer);
function GetPModCount:Integer;
procedure SetPPassword(const Value: String);
function GetPPassword:String;
procedure SetPRealName(const Value: String);
function GetPRealName:String;
procedure SetPLoggedInFlag(const Value: Boolean);
function GetPLoggedInFlag:Boolean;
procedure SetPLoggedInStamp(const Value: String);
function GetPLoggedInStamp:String;
procedure SetPLoggedOutStamp(const Value: String);
function GetPLoggedOutStamp:String;
procedure SetPLastLender(const Value: String);
function GetPLastLender:String;
procedure SetPLenderGroup(const Value: String);
function GetPLenderGroup:String;
procedure SetPUserGroup(const Value: String);
function GetPUserGroup:String;
procedure SetPUserTable(const Value: Boolean);
function GetPUserTable:Boolean;
procedure SetPAccessGroups(const Value: Boolean);
function GetPAccessGroups:Boolean;
procedure SetPLenderGroups(const Value: Boolean);
function GetPLenderGroups:Boolean;
procedure SetPSingleLender(const Value: String);
function GetPSingleLender:String;
procedure SetPBranch(const Value: String);
function GetPBranch:String;
procedure SetPGUISkin(const Value: String);
function GetPGUISkin:String;
procedure SetPGUISkinDir(const Value: String);
function GetPGUISkinDir:String;
procedure SetPWinUser(const Value: String);
function GetPWinUser:String;
function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
procedure SetEnumIndex(Value: TEITTSUSER);
function GetEnumIndex: TEITTSUSER;
protected
function CreateField( const FieldName : string ): TField;
procedure CreateFields; reintroduce;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TTTSUSERRecord;
procedure StoreDataBuffer(ABuffer:TTTSUSERRecord);
property DFUserName: TStringField read FDFUserName;
property DFModCount: TIntegerField read FDFModCount;
property DFPassword: TStringField read FDFPassword;
property DFRealName: TStringField read FDFRealName;
property DFLoggedInFlag: TBooleanField read FDFLoggedInFlag;
property DFLoggedInStamp: TStringField read FDFLoggedInStamp;
property DFLoggedOutStamp: TStringField read FDFLoggedOutStamp;
property DFLastLender: TStringField read FDFLastLender;
property DFLenderGroup: TStringField read FDFLenderGroup;
property DFUserGroup: TStringField read FDFUserGroup;
property DFUserTable: TBooleanField read FDFUserTable;
property DFAccessGroups: TBooleanField read FDFAccessGroups;
property DFLenderGroups: TBooleanField read FDFLenderGroups;
property DFSingleLender: TStringField read FDFSingleLender;
property DFBranch: TStringField read FDFBranch;
property DFGUISkin: TStringField read FDFGUISkin;
property DFGUISkinDir: TStringField read FDFGUISkinDir;
property DFWinUser: TStringField read FDFWinUser;
property PUserName: String read GetPUserName write SetPUserName;
property PModCount: Integer read GetPModCount write SetPModCount;
property PPassword: String read GetPPassword write SetPPassword;
property PRealName: String read GetPRealName write SetPRealName;
property PLoggedInFlag: Boolean read GetPLoggedInFlag write SetPLoggedInFlag;
property PLoggedInStamp: String read GetPLoggedInStamp write SetPLoggedInStamp;
property PLoggedOutStamp: String read GetPLoggedOutStamp write SetPLoggedOutStamp;
property PLastLender: String read GetPLastLender write SetPLastLender;
property PLenderGroup: String read GetPLenderGroup write SetPLenderGroup;
property PUserGroup: String read GetPUserGroup write SetPUserGroup;
property PUserTable: Boolean read GetPUserTable write SetPUserTable;
property PAccessGroups: Boolean read GetPAccessGroups write SetPAccessGroups;
property PLenderGroups: Boolean read GetPLenderGroups write SetPLenderGroups;
property PSingleLender: String read GetPSingleLender write SetPSingleLender;
property PBranch: String read GetPBranch write SetPBranch;
property PGUISkin : String read GetPGUISkin write SetPGUISkin;
property PGUISkinDir: String read GetPGUISkinDir write SetPGUISkinDir;
property PWinUser : String read GetPWinUser write SetPWinUser;
published
property Active write SetActive;
property EnumIndex: TEITTSUSER read GetEnumIndex write SetEnumIndex;
end; { TTTSUSERTable }
procedure Register;
implementation
function TTTSUSERTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string;
var
I: Integer;
NewName: string;
Done: Boolean;
function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean;
var
I: Integer;
begin
Result := False;
for I := 0 To AOwner.ComponentCount - 1 do
begin
if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then
begin
Result := True;
Break;
end;
end;
end; { ComponentExists }
begin { TTTSUSERTable.GenerateNewFieldName }
NewName := DatasetName;
for I := 1 to Length( FieldName ) do
begin
if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then
NewName := NewName + FieldName[ I ];
end;
if ComponentExists( Owner, NewName ) then
begin
I := 1;
Done := False;
repeat
Inc( I );
if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then
begin
Result := NewName + IntToStr( I );
Done := True;
end;
until Done;
end
else
Result := NewName;
end; { TTTSUSERTable.GenerateNewFieldName }
function TTTSUSERTable.CreateField( const FieldName : string ): TField;
begin
{ First, try to find an existing field object. FindField is the same }
{ as FieldByName, but does not raise an exception if the field object }
{ cannot be found. }
Result := FindField( FieldName );
if Result = nil then
begin
{ If an existing field object cannot be found... }
{ Instruct the FieldDefs object to create a new field object }
Result := FieldDefs.Find( FieldName ).CreateField( Owner );
{ The new field object must be given a name so that it may appear in }
{ the Object Inspector. The Delphi default naming convention is used.}
Result.Name := GenerateNewFieldName( Owner, Name, FieldName);
end;
end; { TTTSUSERTable.CreateField }
procedure TTTSUSERTable.CreateFields;
begin
FDFUserName := CreateField( 'UserName' ) as TStringField;
FDFModCount := CreateField( 'ModCount' ) as TIntegerField;
FDFPassword := CreateField( 'Password' ) as TStringField;
FDFRealName := CreateField( 'RealName' ) as TStringField;
FDFLoggedInFlag := CreateField( 'LoggedInFlag' ) as TBooleanField;
FDFLoggedInStamp := CreateField( 'LoggedInStamp' ) as TStringField;
FDFLoggedOutStamp := CreateField( 'LoggedOutStamp' ) as TStringField;
FDFLastLender := CreateField( 'LastLender' ) as TStringField;
FDFLenderGroup := CreateField( 'LenderGroup' ) as TStringField;
FDFUserGroup := CreateField( 'UserGroup' ) as TStringField;
FDFUserTable := CreateField( 'UserTable' ) as TBooleanField;
FDFAccessGroups := CreateField( 'AccessGroups' ) as TBooleanField;
FDFLenderGroups := CreateField( 'LenderGroups' ) as TBooleanField;
FDFSingleLender := CreateField( 'SingleLender' ) as TStringField;
FDFBranch := CreateField( 'Branch' ) as TStringField;
FDFGUISkin := CreateField( 'GUISkin' ) as TStringField;
FDFGUISkinDir := CreateField( 'GUISkinDir' ) as TStringField;
FDFBranch := CreateField( 'WinUser' ) as TStringField;
end; { TTTSUSERTable.CreateFields }
procedure TTTSUSERTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TTTSUSERTable.SetActive }
procedure TTTSUSERTable.SetPUserName(const Value: String);
begin
DFUserName.Value := Value;
end;
function TTTSUSERTable.GetPUserName:String;
begin
result := DFUserName.Value;
end;
procedure TTTSUSERTable.SetPModCount(const Value: Integer);
begin
DFModCount.Value := Value;
end;
function TTTSUSERTable.GetPModCount:Integer;
begin
result := DFModCount.Value;
end;
procedure TTTSUSERTable.SetPPassword(const Value: String);
begin
DFPassword.Value := Value;
end;
function TTTSUSERTable.GetPPassword:String;
begin
result := DFPassword.Value;
end;
procedure TTTSUSERTable.SetPRealName(const Value: String);
begin
DFRealName.Value := Value;
end;
function TTTSUSERTable.GetPRealName:String;
begin
result := DFRealName.Value;
end;
procedure TTTSUSERTable.SetPLoggedInFlag(const Value: Boolean);
begin
DFLoggedInFlag.Value := Value;
end;
function TTTSUSERTable.GetPLoggedInFlag:Boolean;
begin
result := DFLoggedInFlag.Value;
end;
procedure TTTSUSERTable.SetPLoggedInStamp(const Value: String);
begin
DFLoggedInStamp.Value := Value;
end;
function TTTSUSERTable.GetPLoggedInStamp:String;
begin
result := DFLoggedInStamp.Value;
end;
procedure TTTSUSERTable.SetPLoggedOutStamp(const Value: String);
begin
DFLoggedOutStamp.Value := Value;
end;
function TTTSUSERTable.GetPLoggedOutStamp:String;
begin
result := DFLoggedOutStamp.Value;
end;
procedure TTTSUSERTable.SetPLastLender(const Value: String);
begin
DFLastLender.Value := Value;
end;
function TTTSUSERTable.GetPLastLender:String;
begin
result := DFLastLender.Value;
end;
procedure TTTSUSERTable.SetPLenderGroup(const Value: String);
begin
DFLenderGroup.Value := Value;
end;
function TTTSUSERTable.GetPLenderGroup:String;
begin
result := DFLenderGroup.Value;
end;
procedure TTTSUSERTable.SetPUserGroup(const Value: String);
begin
DFUserGroup.Value := Value;
end;
function TTTSUSERTable.GetPUserGroup:String;
begin
result := DFUserGroup.Value;
end;
procedure TTTSUSERTable.SetPUserTable(const Value: Boolean);
begin
DFUserTable.Value := Value;
end;
function TTTSUSERTable.GetPUserTable:Boolean;
begin
result := DFUserTable.Value;
end;
procedure TTTSUSERTable.SetPAccessGroups(const Value: Boolean);
begin
DFAccessGroups.Value := Value;
end;
function TTTSUSERTable.GetPAccessGroups:Boolean;
begin
result := DFAccessGroups.Value;
end;
procedure TTTSUSERTable.SetPLenderGroups(const Value: Boolean);
begin
DFLenderGroups.Value := Value;
end;
function TTTSUSERTable.GetPLenderGroups:Boolean;
begin
result := DFLenderGroups.Value;
end;
procedure TTTSUSERTable.SetPSingleLender(const Value: String);
begin
DFSingleLender.Value := Value;
end;
function TTTSUSERTable.GetPSingleLender:String;
begin
result := DFSingleLender.Value;
end;
procedure TTTSUSERTable.SetPBranch(const Value: String);
begin
DFBranch.Value := Value;
end;
function TTTSUSERTable.GetPBranch:String;
begin
result := DFBranch.Value;
end;
procedure TTTSUSERTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('UserName, String, 10, N');
Add('ModCount, Integer, 0, N');
Add('Password, String, 50, N');
Add('RealName, String, 30, N');
Add('LoggedInFlag, Boolean, 0, N');
Add('LoggedInStamp, String, 17, N');
Add('LoggedOutStamp, String, 17, N');
Add('LastLender, String, 50, N');
Add('LenderGroup, String, 240, N');
Add('UserGroup, String, 20, N');
Add('UserTable, Boolean, 0, N');
Add('AccessGroups, Boolean, 0, N');
Add('LenderGroups, Boolean, 0, N');
Add('SingleLender, String, 4, N');
Add('Branch, String, 8, N');
Add('GUISkin, String, 30, N');
Add('GUISkinDir, String, 40, N');
Add('WinUser, String, 20, N');
end;
end;
procedure TTTSUSERTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, UserName, Y, Y, N, N');
Add('ByRights, UserGroup;UserName, N, N, N, N');
Add('ByLenderGroup, LenderGroup;UserName, N, N, N, N');
end;
end;
procedure TTTSUSERTable.SetEnumIndex(Value: TEITTSUSER);
begin
case Value of
TTSUSERPrimaryKey : IndexName := '';
TTSUSERByRights : IndexName := 'ByRights';
TTSUSERByLenderGroup : IndexName := 'ByLenderGroup';
end;
end;
function TTTSUSERTable.GetDataBuffer:TTTSUSERRecord;
var buf: TTTSUSERRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PUserName := DFUserName.Value;
buf.PModCount := DFModCount.Value;
buf.PPassword := DFPassword.Value;
buf.PRealName := DFRealName.Value;
buf.PLoggedInFlag := DFLoggedInFlag.Value;
buf.PLoggedInStamp := DFLoggedInStamp.Value;
buf.PLoggedOutStamp := DFLoggedOutStamp.Value;
buf.PLastLender := DFLastLender.Value;
buf.PLenderGroup := DFLenderGroup.Value;
buf.PUserGroup := DFUserGroup.Value;
buf.PUserTable := DFUserTable.Value;
buf.PAccessGroups := DFAccessGroups.Value;
buf.PLenderGroups := DFLenderGroups.Value;
buf.PSingleLender := DFSingleLender.Value;
buf.PBranch := DFBranch.Value;
buf.PGUISkin := DFGUISkin.Value;
buf.PGUISkinDir := DFGUISkinDir.Value;
buf.PWinUser := DFWinUser.Value;
result := buf;
end;
procedure TTTSUSERTable.StoreDataBuffer(ABuffer:TTTSUSERRecord);
begin
DFUserName.Value := ABuffer.PUserName;
DFModCount.Value := ABuffer.PModCount;
DFPassword.Value := ABuffer.PPassword;
DFRealName.Value := ABuffer.PRealName;
DFLoggedInFlag.Value := ABuffer.PLoggedInFlag;
DFLoggedInStamp.Value := ABuffer.PLoggedInStamp;
DFLoggedOutStamp.Value := ABuffer.PLoggedOutStamp;
DFLastLender.Value := ABuffer.PLastLender;
DFLenderGroup.Value := ABuffer.PLenderGroup;
DFUserGroup.Value := ABuffer.PUserGroup;
DFUserTable.Value := ABuffer.PUserTable;
DFAccessGroups.Value := ABuffer.PAccessGroups;
DFLenderGroups.Value := ABuffer.PLenderGroups;
DFSingleLender.Value := ABuffer.PSingleLender;
DFBranch.Value := ABuffer.PBranch;
DFGUISkin.Value := ABuffer.PGUISkin;
DFGUISkinDir.Value := ABuffer.PGUISkinDir;
DFWinUser.Value := ABuffer.PWinUser;
end;
function TTTSUSERTable.GetEnumIndex: TEITTSUSER;
var iname : string;
begin
result := TTSUSERPrimaryKey;
iname := uppercase(indexname);
if iname = '' then result := TTSUSERPrimaryKey;
if iname = 'BYRIGHTS' then result := TTSUSERByRights;
if iname = 'BYLENDERGROUP' then result := TTSUSERByLenderGroup;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'TTS Tables', [ TTTSUSERTable, TTTSUSERBuffer ] );
end; { Register }
function TTTSUSERBuffer.FieldNameToIndex(s:string):integer;
const flist:array[1..18] of string = ('USERNAME','MODCOUNT','PASSWORD','REALNAME','LOGGEDINFLAG','LOGGEDINSTAMP'
,'LOGGEDOUTSTAMP','LASTLENDER','LENDERGROUP','USERGROUP','USERTABLE'
,'ACCESSGROUPS','LENDERGROUPS','SINGLELENDER','BRANCH','GUISKIN','GUISKINDIR', 'WINUSER' );
var x : integer;
begin
s := uppercase(s);
x := 1;
while (x <= 18) and (flist[x] <> s) do inc(x);
if x <= 18 then result := x else result := 0;
end;
function TTTSUSERBuffer.FieldType(index:integer):TFieldType;
begin
result := ftUnknown;
case index of
1 : result := ftString;
2 : result := ftInteger;
3 : result := ftString;
4 : result := ftString;
5 : result := ftBoolean;
6 : result := ftString;
7 : result := ftString;
8 : result := ftString;
9 : result := ftString;
10 : result := ftString;
11 : result := ftBoolean;
12 : result := ftBoolean;
13 : result := ftBoolean;
14 : result := ftString;
15 : result := ftString;
16 : result := ftString;
17 : result := ftString;
end;
end;
function TTTSUSERBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PUserName;
2 : result := @Data.PModCount;
3 : result := @Data.PPassword;
4 : result := @Data.PRealName;
5 : result := @Data.PLoggedInFlag;
6 : result := @Data.PLoggedInStamp;
7 : result := @Data.PLoggedOutStamp;
8 : result := @Data.PLastLender;
9 : result := @Data.PLenderGroup;
10 : result := @Data.PUserGroup;
11 : result := @Data.PUserTable;
12 : result := @Data.PAccessGroups;
13 : result := @Data.PLenderGroups;
14 : result := @Data.PSingleLender;
15 : result := @Data.PBranch;
16 : result := @Data.PGUISkin;
17 : result := @Data.PGUISkinDir;
18 : Result := @Data.PWinUser;
end;
end;
function TTTSUSERTable.GetPGUISkin: String;
begin
result := DFGUISkin.Value;
end;
function TTTSUSERTable.GetPGUISkinDir: String;
begin
result := DFGUISkinDir.Value;
end;
procedure TTTSUSERTable.SetPGUISkin(const Value: String);
begin
DFGUISkin.Value := Value;
end;
procedure TTTSUSERTable.SetPGUISkinDir(const Value: String);
begin
DFGUISkinDir.Value := Value;
end;
function TTTSUSERTable.GetPWinUser: String;
begin
Result := DFWinUser.Value;
end;
procedure TTTSUSERTable.SetPWinUser(const Value: String);
begin
DFWinUser.Value := Value;
end;
end.
|
unit MFichas.Model.Produto.Interfaces;
interface
uses
System.Generics.Collections,
MFichas.Model.Entidade.PRODUTO,
ORMBR.Container.ObjectSet.Interfaces,
ORMBR.Container.DataSet.interfaces,
FireDAC.Comp.Client;
type
iModelProduto = interface;
iModelProdutoMetodos = interface;
iModelProdutoMetodosCadastrar = interface;
iModelProdutoMetodosEditar = interface;
iModelProdutoMetodosBuscar = interface;
iModelProdutoMetodosBuscarModel = interface;
iModelProduto = interface
['{61661537-0B52-412D-ADBF-07AD0CE4B36A}']
function Metodos: iModelProdutoMetodos;
function Entidade: TPRODUTO; overload;
function Entidade(AEntidade: TPRODUTO): iModelProduto; overload;
function DAO : iContainerObjectSet<TPRODUTO>;
function DAODataSet: iContainerDataSet<TPRODUTO>;
end;
iModelProdutoMetodos = interface
['{F0085DB7-902C-4F16-9EE4-FD46FDC51B48}']
function CadastrarView: iModelProdutoMetodosCadastrar;
function EditarView : iModelProdutoMetodosEditar;
function BuscarView : iModelProdutoMetodosBuscar;
function BuscarModel : iModelProdutoMetodosBuscarModel;
function &End : iModelProduto;
end;
iModelProdutoMetodosCadastrar = interface
['{6F017D50-9B06-43DA-8EFB-2C96818DF053}']
function Descricao(ADescricao: String): iModelProdutoMetodosCadastrar;
function Valor(AValor: Currency) : iModelProdutoMetodosCadastrar;
function Grupo(AGrupo: String) : iModelProdutoMetodosCadastrar;
function &End : iModelProdutoMetodos;
end;
iModelProdutoMetodosBuscar = interface
['{53805661-F48B-47DF-9CFF-84DC595B3C01}']
function FDMemTable(AFDMemTable: TFDMemTable): iModelProdutoMetodosBuscar;
function BuscarTodos : iModelProdutoMetodosBuscar;
function BuscarTodosAtivos : iModelProdutoMetodosBuscar;
function BuscarPorCodigo(ACodigo: String): iModelProdutoMetodosBuscar;
function BuscarPorGrupo(AGrupo: String) : iModelProdutoMetodosBuscar;
function &End : iModelProdutoMetodos;
end;
iModelProdutoMetodosBuscarModel = interface
['{93C38D5A-83DE-4B9E-A5AB-D7058E113F90}']
function BuscarPorCodigo(AGUUID: String): TObjectList<TPRODUTO>;
function &End : iModelProdutoMetodos;
end;
iModelProdutoMetodosEditar = interface
['{C9AAD284-8E20-4162-8762-C5C8B09E1B95}']
function GUUID(AGUUID: String) : iModelProdutoMetodosEditar;
function Descricao(ADescricao: String): iModelProdutoMetodosEditar;
function Valor(AValor: Currency) : iModelProdutoMetodosEditar;
function Grupo(AGrupo: String) : iModelProdutoMetodosEditar;
function AtivoInativo(AValue: Integer): iModelProdutoMetodosEditar;
function &End : iModelProdutoMetodos;
end;
implementation
end.
|
{
This file is part of the Free Pascal run time library.
Copyright (c) 2008 by the Free Pascal development team
Common stuff for Tiff image format.
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
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.
**********************************************************************
}
unit FPTiffCmn;
{$mode objfpc}{$H+}
interface
uses
Classes, sysutils, FPimage;
type
TTiffRational = packed record
Numerator, Denominator: DWord;
end;
const
TiffRational0: TTiffRational = (Numerator: 0; Denominator: 0);
TiffRational72: TTiffRational = (Numerator: 72; Denominator: 1);
// TFPCustomImage.Extra properties used by TFPReaderTiff and TFPWriterTiff
TiffExtraPrefix = 'Tiff';
TiffPhotoMetric = TiffExtraPrefix+'PhotoMetricInterpretation';
TiffGrayBits = TiffExtraPrefix+'GrayBits'; // CMYK: key plate
TiffRedBits = TiffExtraPrefix+'RedBits'; // CMYK: cyan
TiffGreenBits = TiffExtraPrefix+'GreenBits'; // CMYK: magenta
TiffBlueBits = TiffExtraPrefix+'BlueBits'; // CMYK: yellow
TiffAlphaBits = TiffExtraPrefix+'AlphaBits';
TiffArtist = TiffExtraPrefix+'Artist';
TiffCopyright = TiffExtraPrefix+'Copyright';
TiffDocumentName = TiffExtraPrefix+'DocumentName';
TiffDateTime = TiffExtraPrefix+'DateTime';
TiffImageDescription = TiffExtraPrefix+'ImageDescription';
TiffOrientation = TiffExtraPrefix+'Orientation';
TiffResolutionUnit = TiffExtraPrefix+'ResolutionUnit';
TiffXResolution = TiffExtraPrefix+'XResolution';
TiffYResolution = TiffExtraPrefix+'YResolution';
type
{ TTiffIDF }
TTiffIDF = class
public
Artist: String;
BitsPerSample: DWord; // tiff position of entry
BitsPerSampleArray: array of Word;
CellLength: DWord;
CellWidth: DWord;
ColorMap: DWord;// tiff position of entry
Compression: DWord;
Predictor: Word;
Copyright: string;
DateAndTime: string;
DocumentName: string;
ExtraSamples: DWord;// tiff position of entry
FillOrder: DWord;
HostComputer: string;
ImageDescription: string;
ImageHeight: DWord;
ImageIsMask: Boolean;
ImageIsPage: Boolean;
ImageIsThumbNail: Boolean;
ImageWidth: DWord;
Make_ScannerManufacturer: string;
Model_Scanner: string;
Orientation: DWord;
PhotoMetricInterpretation: DWord;
PlanarConfiguration: DWord;
ResolutionUnit: DWord;
RowsPerStrip: DWord;
SamplesPerPixel: DWord;
Software: string;
StripByteCounts: DWord;// tiff position of entry
StripOffsets: DWord; // tiff position of entry
Treshholding: DWord;
XResolution: TTiffRational;
YResolution: TTiffRational;
// image
Img: TFPCustomImage;
RedBits: word;
GreenBits: word;
BlueBits: word;
GrayBits: word;
AlphaBits: word;
BytesPerPixel: Word;
procedure Clear;
procedure Assign(IDF: TTiffIDF);
end;
function TiffRationalToStr(const r: TTiffRational): string;
function StrToTiffRationalDef(const s: string; const Def: TTiffRational): TTiffRational;
procedure ClearTiffExtras(Img: TFPCustomImage);
procedure CopyTiffExtras(SrcImg, DestImg: TFPCustomImage);
procedure WriteTiffExtras(Msg: string; Img: TFPCustomImage);
implementation
function TiffRationalToStr(const r: TTiffRational): string;
begin
Result:=IntToStr(r.Numerator)+'/'+IntToStr(r.Denominator);
end;
function StrToTiffRationalDef(const s: string; const Def: TTiffRational
): TTiffRational;
var
p: LongInt;
begin
Result:=Def;
p:=System.Pos('/',s);
if p<1 then exit;
Result.Numerator:=StrToIntDef(copy(s,1,p-1),TiffRational0.Numerator);
Result.Denominator:=StrToIntDef(copy(s,p+1,length(s)),TiffRational0.Denominator);
end;
procedure ClearTiffExtras(Img: TFPCustomImage);
var
i: Integer;
begin
for i:=Img.ExtraCount-1 downto 0 do
if SysUtils.CompareText(copy(Img.ExtraKey[i],1,4),'Tiff')=0 then
Img.RemoveExtra(Img.ExtraKey[i]);
end;
procedure CopyTiffExtras(SrcImg, DestImg: TFPCustomImage);
var
i: Integer;
begin
ClearTiffExtras(DestImg);
for i:=SrcImg.ExtraCount-1 downto 0 do
if SysUtils.CompareText(copy(SrcImg.ExtraKey[i],1,4),'Tiff')=0 then
DestImg.Extra[SrcImg.ExtraKey[i]]:=SrcImg.ExtraValue[i];
end;
procedure WriteTiffExtras(Msg: string; Img: TFPCustomImage);
var
i: Integer;
begin
{$ifdef FPC_Debug_Image}
writeln('WriteTiffExtras ',Msg);
for i:=Img.ExtraCount-1 downto 0 do
//if SysUtils.CompareText(copy(Img.ExtraKey[i],1,4),'Tiff')=0 then
writeln(' ',i,' ',Img.ExtraKey[i],'=',Img.ExtraValue[i]);
{$endif}
end;
{ TTiffIDF }
procedure TTiffIDF.Clear;
begin
PhotoMetricInterpretation:=High(PhotoMetricInterpretation);
PlanarConfiguration:=0;
Compression:=0;
Predictor:=1;
ImageHeight:=0;
ImageWidth:=0;
ImageIsThumbNail:=false;
ImageIsPage:=false;
ImageIsMask:=false;
BitsPerSample:=0;
SetLength(BitsPerSampleArray,0);
ResolutionUnit:=0;
XResolution:=TiffRational0;
YResolution:=TiffRational0;
RowsPerStrip:=0;
StripOffsets:=0;
StripByteCounts:=0;
SamplesPerPixel:=0;
Artist:='';
HostComputer:='';
ImageDescription:='';
Make_ScannerManufacturer:='';
Model_Scanner:='';
Copyright:='';
DateAndTime:='';
Software:='';
CellWidth:=0;
CellLength:=0;
FillOrder:=0;
Orientation:=0;
Treshholding:=0;
RedBits:=0;
GreenBits:=0;
BlueBits:=0;
GrayBits:=0;
AlphaBits:=0;
BytesPerPixel:=0;
end;
procedure TTiffIDF.Assign(IDF: TTiffIDF);
begin
PhotoMetricInterpretation:=IDF.PhotoMetricInterpretation;
PlanarConfiguration:=IDF.PlanarConfiguration;
Compression:=IDF.Compression;
Predictor:=IDF.Predictor;
ImageHeight:=IDF.ImageHeight;
ImageWidth:=IDF.ImageWidth;
ImageIsThumbNail:=IDF.ImageIsThumbNail;
ImageIsPage:=IDF.ImageIsPage;
ImageIsMask:=IDF.ImageIsMask;
BitsPerSample:=IDF.BitsPerSample;
BitsPerSampleArray:=IDF.BitsPerSampleArray;
ResolutionUnit:=IDF.ResolutionUnit;
XResolution:=IDF.XResolution;
YResolution:=IDF.YResolution;
RowsPerStrip:=IDF.RowsPerStrip;
StripOffsets:=IDF.StripOffsets;
StripByteCounts:=IDF.StripByteCounts;
SamplesPerPixel:=IDF.SamplesPerPixel;
Artist:=IDF.Artist;
HostComputer:=IDF.HostComputer;
ImageDescription:=IDF.ImageDescription;
Make_ScannerManufacturer:=IDF.Make_ScannerManufacturer;
Model_Scanner:=IDF.Model_Scanner;
Copyright:=IDF.Copyright;
DateAndTime:=IDF.DateAndTime;
Software:=IDF.Software;
CellWidth:=IDF.CellWidth;
CellLength:=IDF.CellLength;
FillOrder:=IDF.FillOrder;
Orientation:=IDF.Orientation;
Treshholding:=IDF.Treshholding;
RedBits:=IDF.RedBits;
GreenBits:=IDF.GreenBits;
BlueBits:=IDF.BlueBits;
GrayBits:=IDF.GrayBits;
AlphaBits:=IDF.AlphaBits;
if (Img<>nil) and (IDF.Img<>nil) then
Img.Assign(IDF.Img);
end;
end.
|
unit NewStaticText;
{
TNewStaticText - similar to TStaticText on D3+ but with multi-line AutoSize
support and a WordWrap property
}
interface
{$IFNDEF VER90}
{$IFNDEF VER100}
{$IFNDEF VER120}
{$IFNDEF VER130}
{$DEFINE Delphi6OrHigher}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
uses
Windows, Messages, SysUtils, Classes, Controls, Forms;
type
TNewStaticText = class(TWinControl)
private
FAutoSize: Boolean;
FFocusControl: TWinControl;
FForceLTRReading: Boolean;
FLastAdjustBoundsRTL: Boolean;
FShowAccelChar: Boolean;
FWordWrap: Boolean;
procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure CMParentFontChanged(var Message: TMessage); message CM_PARENTFONTCHANGED;
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
procedure AdjustBounds;
function CalcBounds: TPoint;
function GetDrawTextFlags: UINT;
procedure SetFocusControl(Value: TWinControl);
procedure SetForceLTRReading(Value: Boolean);
procedure SetShowAccelChar(Value: Boolean);
procedure SetWordWrap(Value: Boolean);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure Loaded; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetAutoSize(Value: Boolean); {$IFDEF Delphi6OrHigher}override;{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
function AdjustHeight: Integer;
published
property Align;
property AutoSize: Boolean read FAutoSize write SetAutoSize default True;
property Caption;
property Color;
property DragCursor;
property DragMode;
property Enabled;
property FocusControl: TWinControl read FFocusControl write SetFocusControl;
property Font;
property ForceLTRReading: Boolean read FForceLTRReading write SetForceLTRReading
default False;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowAccelChar: Boolean read FShowAccelChar write SetShowAccelChar
default True;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property WordWrap: Boolean read FWordWrap write SetWordWrap default False;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnStartDrag;
end;
procedure Register;
implementation
uses
BidiUtils;
procedure Register;
begin
RegisterComponents('JR', [TNewStaticText]);
end;
procedure DrawTextACP(const DC: HDC; const S: String; var R: TRect;
const AFormat: UINT);
{ Draws an ANSI string using the system's code page (CP_ACP), unlike DrawTextA
which uses the code page defined by the selected font. }
{$IFDEF UNICODE}
begin
DrawText(DC, PChar(S), Length(S), R, AFormat);
end;
{$ELSE}
var
SLen, WideLen: Integer;
WideStr: PWideChar;
begin
SLen := Length(S);
if SLen = 0 then
Exit;
if Win32Platform = VER_PLATFORM_WIN32_NT then begin
if SLen > High(Integer) div SizeOf(WideChar) then
Exit;
GetMem(WideStr, SLen * SizeOf(WideChar));
try
WideLen := MultiByteToWideChar(CP_ACP, 0, PChar(S), SLen, WideStr, SLen);
DrawTextW(DC, WideStr, WideLen, R, AFormat);
finally
FreeMem(WideStr);
end;
end
else
DrawText(DC, PChar(S), SLen, R, AFormat);
end;
{$ENDIF}
{ TNewStaticText }
constructor TNewStaticText.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
ControlStyle := [csCaptureMouse, csClickEvents, csSetCaption,
csOpaque, csReplicatable, csDoubleClicks];
Width := 65;
Height := 17;
FAutoSize := True;
FShowAccelChar := True;
AdjustBounds;
end;
procedure TNewStaticText.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
CreateSubClass(Params, 'STATIC');
with Params do
begin
Style := Style or SS_NOTIFY;
if not SetBiDiStyles(Self, Params) then begin
{ Quirk: No style is set for WordWrap=False in RTL mode; WS_EX_RIGHT
overrides SS_LEFTNOWORDWRAP, and there is no SS_RIGHTNOWORDWRAP style.
WordWrap=False still affects AdjustBounds, though. }
if not FWordWrap then Style := Style or SS_LEFTNOWORDWRAP;
end;
if not FShowAccelChar then Style := Style or SS_NOPREFIX;
if FForceLTRReading then ExStyle := ExStyle and not WS_EX_RTLREADING;
end;
end;
procedure TNewStaticText.CMDialogChar(var Message: TCMDialogChar);
begin
if (FFocusControl <> nil) and Enabled and ShowAccelChar and
IsAccel(Message.CharCode, Caption) then
with FFocusControl do
if CanFocus then
begin
SetFocus;
Message.Result := 1;
end;
end;
procedure TNewStaticText.CMFontChanged(var Message: TMessage);
begin
inherited;
AdjustBounds;
end;
procedure TNewStaticText.CMParentFontChanged(var Message: TMessage);
begin
inherited;
{ What we're really trapping here is changes to Parent. Recalculate size
if the new Parent's RTL setting is different. }
if IsParentRightToLeft(Self) <> FLastAdjustBoundsRTL then
AdjustBounds;
end;
procedure TNewStaticText.CMTextChanged(var Message: TMessage);
begin
inherited;
Invalidate;
AdjustBounds;
end;
procedure TNewStaticText.Loaded;
begin
inherited Loaded;
AdjustBounds;
end;
function TNewStaticText.GetDrawTextFlags: UINT;
begin
Result := DT_EXPANDTABS or DT_NOCLIP;
if FWordWrap then Result := Result or DT_WORDBREAK;
if not FShowAccelChar then Result := Result or DT_NOPREFIX;
if IsParentRightToLeft(Self) then begin
{ Note: DT_RTLREADING must be included even when just calculating the
size, since on certain fonts it can affect the width of characters.
(Consider the Hebrew string: 'a '#$F9' b'. On 2000 with Lucida Console
as the font, the spaces aren't drawn as wide with RTLREADING.) }
Result := Result or DT_RIGHT;
if not FForceLTRReading then
Result := Result or DT_RTLREADING;
end;
end;
function TNewStaticText.CalcBounds: TPoint;
var
R: TRect;
S: String;
DC: HDC;
begin
{ Note: The calculated width/height is actually one pixel wider/taller
than the size of the text, so that when Enabled=False the white shadow
does not get clipped }
R := Rect(0, 0, Width, 0);
if R.Right > 0 then Dec(R.Right);
S := Caption;
if (S = '') or (FShowAccelChar and (S[1] = '&') and (S[2] = #0)) then
S := S + ' ';
DC := GetDC(0);
try
SelectObject(DC, Font.Handle);
{ On NT platforms, static controls are Unicode-based internally; when
ANSI text is assigned to them, it is converted to Unicode using the
system code page (ACP). We must be sure to use the ACP here, too,
otherwise the calculated size could be incorrect. The code page used
by DrawTextA is defined by the font, and not necessarily equal to the
ACP, so we can't use it. (To reproduce: with the ACP set to Hebrew
(1255), try passing Hebrew text to DrawTextA with the font set to
"Lucida Console". It appears to use CP 1252, not 1255.) }
DrawTextACP(DC, S, R, DT_CALCRECT or GetDrawTextFlags);
finally
ReleaseDC(0, DC);
end;
Result.X := R.Right + 1;
Result.Y := R.Bottom + 1;
end;
procedure TNewStaticText.AdjustBounds;
var
NewBounds: TPoint;
NewLeft, NewWidth: Integer;
begin
if not (csLoading in ComponentState) and FAutoSize then
begin
FLastAdjustBoundsRTL := IsParentRightToLeft(Self);
NewBounds := CalcBounds;
NewLeft := Left;
NewWidth := Width;
if not FWordWrap then begin
NewWidth := NewBounds.X;
if IsParentFlipped(Self) then
Inc(NewLeft, Width - NewWidth);
end;
SetBounds(NewLeft, Top, NewWidth, NewBounds.Y);
end;
end;
function TNewStaticText.AdjustHeight: Integer;
var
OldHeight: Integer;
begin
OldHeight := Height;
Height := CalcBounds.Y;
Result := Height - OldHeight;
end;
procedure TNewStaticText.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FFocusControl) then
FFocusControl := nil;
end;
procedure TNewStaticText.SetAutoSize(Value: Boolean);
begin
if FAutoSize <> Value then
begin
FAutoSize := Value;
if Value then AdjustBounds;
end;
end;
procedure TNewStaticText.SetFocusControl(Value: TWinControl);
begin
FFocusControl := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
procedure TNewStaticText.SetForceLTRReading(Value: Boolean);
begin
if FForceLTRReading <> Value then begin
FForceLTRReading := Value;
RecreateWnd;
AdjustBounds;
end;
end;
procedure TNewStaticText.SetShowAccelChar(Value: Boolean);
begin
if FShowAccelChar <> Value then
begin
FShowAccelChar := Value;
RecreateWnd;
AdjustBounds;
end;
end;
procedure TNewStaticText.SetWordWrap(Value: Boolean);
begin
if FWordWrap <> Value then
begin
FWordWrap := Value;
RecreateWnd;
AdjustBounds;
end;
end;
end.
|
unit uTAGRequests;
interface
uses
SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs,
uModel, System.Generics.Collections;
type
TTAGRequestItem = class;
TTAGRequest = class(TAppObject)
private
FCabang: TCabang;
FKeterangan: string;
FNoBukti: string;
FPetugas: string;
FStatus: string;
FTAGRequestItems: tobjectlist<TTAGRequestItem>;
FTglBukti: TDateTime;
FToCabang: TCabang;
function GetTAGRequestItems: tobjectlist<TTAGRequestItem>;
public
constructor Create;
destructor Destroy; override;
published
property TAGRequestItems: tobjectlist<TTAGRequestItem> read GetTAGRequestItems
write FTAGRequestItems;
property Cabang: TCabang read FCabang write FCabang;
property Keterangan: string read FKeterangan write FKeterangan;
property NoBukti: string read FNoBukti write FNoBukti;
property Petugas: string read FPetugas write FPetugas;
property Status: string read FStatus write FStatus;
property TglBukti: TDateTime read FTglBukti write FTglBukti;
property ToCabang: TCabang read FToCabang write FToCabang;
end;
TTAGRequestItem = class(TAppObjectItem)
private
FBarang: TBarang;
FBarangSatuangItemID: string;
FKeterangan: string;
FQtyRequest: Double;
FTAGRequest: TTAGRequest;
FUOM: TUOM;
public
destructor Destroy; override;
function GetHeaderField: string; override;
procedure SetHeaderProperty(AHeaderProperty : TAppObject); override;
property BarangSatuangItemID: string read FBarangSatuangItemID write
FBarangSatuangItemID;
published
property Barang: TBarang read FBarang write FBarang;
property Keterangan: string read FKeterangan write FKeterangan;
property QtyRequest: Double read FQtyRequest write FQtyRequest;
property TAGRequest: TTAGRequest read FTAGRequest write FTAGRequest;
property UOM: TUOM read FUOM write FUOM;
end;
implementation
destructor TTAGRequestItem.Destroy;
begin
inherited;
FreeAndNil(FBarang);
FreeAndNil(FUOM);
end;
function TTAGRequestItem.GetHeaderField: string;
begin
Result := 'TAGRequest';
end;
procedure TTAGRequestItem.SetHeaderProperty(AHeaderProperty : TAppObject);
begin
Self.TAGRequest := TTAGRequest(AHeaderProperty);
end;
constructor TTAGRequest.Create;
begin
inherited;
Status := 'MINTA'
end;
destructor TTAGRequest.Destroy;
var
I: Integer;
begin
inherited;
FreeAndNil(FCabang);
FreeAndNil(FToCabang);
for I := 0 to TAGRequestItems.Count - 1 do
begin
TAGRequestItems[i].Free;
end;
FreeAndNil(FTAGRequestItems);
end;
function TTAGRequest.GetTAGRequestItems: tobjectlist<TTAGRequestItem>;
begin
if FTAGRequestItems = nil then
FTAGRequestItems := TObjectList<TTAGRequestItem>.Create(False);
Result := FTAGRequestItems;
end;
end.
|
unit Model.PlanilhaBaixasDIRECT;
interface
uses Generics.Collections, System.Classes, System.SysUtils;
type
TPlanilhaBaixasDIRECT = class
private
FRegiao: String;
FDataRegistro: TDate;
FOperacao: String;
FMotorista: String;
FDataAtualizacao: TDate;
FPesoNominal: Double;
FValor: Double;
FPedido: String;
FPesoCubado: Double;
FSiglaBase: String;
FVolumes: Integer;
FNF: String;
FCEP: String;
FDocumento: String;
FPesoAferido: Double;
FMunicipio: String;
FRemessa: String;
FPesoCTE: Double;
FNumeroViagem: Integer;
FTipo: String;
FMensagemProcesso: string;
FPlanilha: TObjectList<TPlanilhaBaixasDIRECT>;
FLoja: String;
public
property NumeroViagem: Integer read FNumeroViagem write FNumeroViagem;
property DataAtualizacao: TDate read FDataAtualizacao write FDataAtualizacao;
property Documento: String read FDocumento write FDocumento;
property Motorista: String read FMotorista write FMotorista;
property SiglaBase: String read FSiglaBase write FSiglaBase;
property Pedido: String read FPedido write FPedido;
property Remessa: String read FRemessa write FRemessa;
property NF: String read FNF write FNF;
property Municipio: String read FMunicipio write FMunicipio;
property CEP: String read FCEP write FCEP;
property Volumes: Integer read FVolumes write FVolumes;
property Tipo: String read FTipo write FTipo;
property DataRegistro: TDate read FDataRegistro write FDataRegistro;
property Valor: Double read FValor write FValor;
property PesoAferido: Double read FPesoAferido write FPesoAferido;
property PesoCubado: Double read FPesoCubado write FPesoCubado;
property PesoNominal: Double read FPesoNominal write FPesoNominal;
property PesoCTE: Double read FPesoCTE write FPesoCTE;
property Operacao: String read FOperacao write FOperacao;
property Regiao: String read FRegiao write FRegiao;
property Loja: String read FLoja write FLoja;
property MensagemProcesso: string read FMensagemProcesso;
property Planilha: TObjectList<TPlanilhaBaixasDIRECT> read FPlanilha;
function GetPlanilha(sFile: String): boolean;
end;
implementation
{ TPlanilhaBaixasDIRECT }
uses Common.Utils;
function TPlanilhaBaixasDIRECT.GetPlanilha(sFile: String): boolean;
var
ArquivoCSV: TextFile;
sLinha: String;
sDetalhe: TStringList;
i : Integer;
sValor: String;
begin
FPlanilha := TObjectList<TPlanilhaBaixasDIRECT>.Create;
if not FileExists(sFile) then
begin
FMensagemProcesso := 'Arquivo ' + sFile + ' não foi encontrado!';
Exit;
end;
AssignFile(ArquivoCSV, sFile);
if sFile.IsEmpty then Exit;
sDetalhe := TStringList.Create;
sDetalhe.StrictDelimiter := True;
sDetalhe.Delimiter := ';';
Reset(ArquivoCSV);
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha;
if Pos('Numero Viagem',sLinha) = 0 then
begin
FMensagemProcesso := 'Arquivo ' + sFile + ' não é planilha de baixas!';
CloseFile(ArquivoCSV);
Exit;
end;
sDetalhe.DelimitedText := sLinha;
i := 0;
while not Eoln(ArquivoCSV) do
begin
Readln(ArquivoCSV, sLinha);
sDetalhe.DelimitedText := sLinha + ';';
sValor := '0';
if TUtils.ENumero(sDetalhe[6]) then
begin
FPlanilha.Add(TPlanilhaBaixasDIRECT.Create);
i := FPlanilha.Count - 1;
FPlanilha[i].NumeroViagem := StrToIntDef(sDetalhe[0], 0);
FPlanilha[i].DataAtualizacao := StrToDateDef(sDetalhe[1], 0);
FPlanilha[i].Documento := sDetalhe[2];
FPlanilha[i].Motorista := sDetalhe[3];
FPlanilha[i].SiglaBase := sDetalhe[4];
FPlanilha[i].Pedido := sDetalhe[5];
FPlanilha[i].Remessa := sDetalhe[6];
FPlanilha[i].NF := Trim(sDetalhe[7]);
FPlanilha[i].Municipio := sDetalhe[8];
FPlanilha[i].CEP := sDetalhe[9];
FPlanilha[i].Volumes := StrToIntDef(sDetalhe[10], 1);
FPlanilha[i].Tipo := sDetalhe[11];
FPlanilha[i].DataRegistro := StrToDateDef(sDetalhe[12], 0);
sValor := StringReplace(sDetalhe[13], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].Valor := StrToFloatDef(sValor, 0);
sValor := StringReplace(sDetalhe[14], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].PesoAferido := StrToFloatDef(sValor, 0);
sValor := StringReplace(sDetalhe[15], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].PesoCubado := StrToFloatDef(sValor, 0);
sValor := StringReplace(sDetalhe[16], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].PesoNominal := StrToFloatDef(sValor, 0);
sValor := StringReplace(sDetalhe[17], '.', ',', [rfReplaceAll, rfIgnoreCase]);
FPlanilha[i].PesoCTE := StrToFloatDef(sValor, 0);
FPlanilha[i].Operacao := sDetalhe[18];
FPlanilha[i].Regiao := sDetalhe[19];
if sDetalhe.Count >= 21 then
begin
FPLanilha[i].Loja := sDetalhe[20];
end
else
begin
FPLanilha[i].Loja := 'N';
end;
end;
end;
CloseFile(ArquivoCSV);
if FPlanilha.Count = 0 then
begin
FMensagemProcesso := 'Nenhuma informação foi importada da planilha!';
Exit;
end;
Result := True;
end;
end.
|
unit UMazeHandler; //Fully annotated
interface
uses
Classes, SysUtils, UInterface;
type
TCell = record // Properties of each square
Wall: boolean;
Passed: boolean;
Solution: boolean;
end;
TMaze = Array of Array of TCell; //All squares in the maze
TMazeHandler = class
private
MazeLength, LastIndex, startX, startY, endX, endY, positionX,
positionY: integer;
Maze: TMaze;
public
constructor Create;
procedure SetEmpty(x, y: integer);
function GetMazeLength: integer;
function GetWall(x, y: integer): boolean;
function GetLastIndex: integer;
function GetStartX: integer;
function GetStartY: integer;
function GetEndX: integer;
function GetEndY: integer;
function GetPositionX: integer;
function GetPositionY: integer;
procedure MoveForward;
procedure MoveBackward;
procedure MoveLeft;
procedure MoveRight;
function GetPassed(x, y: integer): boolean;
function GetNumberOfAir: integer;
procedure SetPassed(x, y: integer);
procedure AddExternalWalls;
procedure SetSolution(x, y: integer);
function GetSolution(x, y: integer): boolean;
procedure SetStartAndFinish(nstartX, nstartY, nendX, nendY: integer);
procedure UnsetStartAndFinish(nstartX: integer; nstartY: integer;
nendX: integer; nendY: integer);
procedure ResetMaze;
end;
implementation
// Creates the Maze Class
constructor TMazeHandler.Create;
var
x, y: integer;
begin
MazeLength := 50;
setLength(Maze, MazeLength, MazeLength);
LastIndex := MazeLength - 1;
//Sets all attributes to each cell in the maze to their default value
for x := 0 to LastIndex do
begin
for y := 0 to LastIndex do
begin
Maze[x, y].Wall := true;
Maze[x, y].Passed := false;
Maze[x, y].Solution := false;
end;
end;
end;
// Sets a cell to be air (have no wall)
procedure TMazeHandler.SetEmpty(x, y: integer);
begin
Maze[x, y].Wall := false;
end;
// Returns the width/height of the maze
function TMazeHandler.GetMazeLength: integer;
begin
result := MazeLength;
end;
// Returns whether a cell has a wall or not
function TMazeHandler.GetWall(x, y: integer): boolean;
begin
result := Maze[x, y].Wall;
end;
// Returns the position of the last index in the list
function TMazeHandler.GetLastIndex: integer;
begin
result := LastIndex;
end;
// Returns the x coordinate of the start position
function TMazeHandler.GetStartX: integer;
begin
result := startX;
end;
// Returns the y coordinate of the start position
function TMazeHandler.GetStartY: integer;
begin
result := startY;
end;
// Returns the x coordinate of the end position
function TMazeHandler.GetEndX: integer;
begin
result := endX;
end;
// Returns the y coordinate of the end position
function TMazeHandler.GetEndY: integer;
begin
result := endY;
end;
// Returns the x coordinate of the character position
function TMazeHandler.GetPositionX: integer;
begin
result := positionX;
end;
// Returns the y coordinate of the character position
function TMazeHandler.GetPositionY: integer;
begin
result := positionY;
end;
// Move the character forward one square
procedure TMazeHandler.MoveForward;
begin
dec(positionY);
end;
// Move the character backward one square
procedure TMazeHandler.MoveBackward;
begin
inc(positionY);
end;
// Move the character one square to the left
procedure TMazeHandler.MoveLeft;
begin
dec(positionX);
end;
// Move the character one square to the right
procedure TMazeHandler.MoveRight;
begin
inc(positionX);
end;
// Returns whether the chracter has passed a specified cell
function TMazeHandler.GetPassed(x, y: integer): boolean;
begin
result := Maze[x, y].Passed;
end;
// Sets that the character has passed a specified cell
procedure TMazeHandler.SetPassed(x, y: integer);
begin
Maze[x, y].Passed := true;
end;
// Returns the number of the spaces in the maze (cells with wall set to false)
function TMazeHandler.GetNumberOfAir: integer;
var
x, y: integer;
begin
result := 0;
for x := 0 to LastIndex do
begin
for y := 0 to LastIndex do
begin
if not(Maze[x, y].Wall) then
inc(result);
end;
end;
end;
// Adds the external walls to the maze
procedure TMazeHandler.AddExternalWalls;
var
NewMaze: TMaze;
newMazeLength, x, y: integer;
begin
// Creates a temporary new maze with an extra collumn on each vertical side,
// and an extra row on each horizontle side
newMazeLength := MazeLength + 2;
setLength(NewMaze, newMazeLength, newMazeLength);
// Sets the passed value of all cells to false
for x := 0 to newMazeLength - 1 do
begin
for y := 0 to newMazeLength - 1 do
begin
NewMaze[x, y].Passed := false;
end;
end;
// Copies the values of the walls of the old maze into the new one
for x := 0 to (MazeLength - 1) do
begin
for y := 0 to (MazeLength - 1) do
begin
NewMaze[x + 1, y + 1].Wall := Maze[x, y].Wall;
end;
end;
// Adds the horizontle exterior walls
for x := 0 to (newMazeLength - 1) do
begin
NewMaze[x, 0].Wall := true;
NewMaze[x, newMazeLength - 1].Wall := true;
end;
// Adds the vertical exterior walls
for y := 1 to (newMazeLength - 2) do
begin
NewMaze[0, y].Wall := true;
NewMaze[newMazeLength - 1, y].Wall := true;
end;
// Sets the old maze equal to the new maze
setLength(Maze, newMazeLength, newMazeLength);
Maze := NewMaze;
MazeLength := newMazeLength;
LastIndex := MazeLength - 1;
end;
// Sets a cell to be a part of the solution to the maze
procedure TMazeHandler.SetSolution(x: integer; y: integer);
begin
Maze[x, y].Solution := true;
end;
// Returns whether a cell is part of the solution to the maze
function TMazeHandler.GetSolution(x: integer; y: integer): boolean;
begin
result := Maze[x, y].Solution;
end;
// Sets the start cell and finish cell for the maze, and updates the default
// character position to reflect the change in start position
procedure TMazeHandler.SetStartAndFinish(nstartX: integer; nstartY: integer;
nendX: integer; nendY: integer);
begin
startX := nstartX;
startY := nstartY;
Maze[startX, startY].Wall := false;
positionX := startX;
positionY := startY;
endX := nendX;
endY := nendY;
Maze[endX, endY].Wall := false;
end;
// Fills in the spaces created by the old start and finish cells
procedure TMazeHandler.UnsetStartAndFinish(nstartX: integer;
nstartY: integer; nendX: integer; nendY: integer);
begin
Maze[nstartX, nstartY].Wall := true;
Maze[nendX, nendY].Wall := true;
end;
// Resets the maze to its state after being generated
procedure TMazeHandler.ResetMaze;
var
x,y:integer;
begin
// Resets the chracter position back to the start
positionX:=startX;
positionY:=startY;
// Sets that no cells have been passed by the character
for x := 0 to LastIndex do
begin
for y := 0 to LastIndex do
begin
Maze[x,y].Passed:=false;
end;
end;
end;
end.
|
unit UHistory;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, UDraw, Math;
type
THistoryItem = record
Figures: TFigureArray;
Saved: boolean;
end;
{ THistory }
THistory = class
private
FItems: array of THistoryItem;
FIndex: SizeInt;
public
constructor Create;
procedure Push(AState: THistoryItem);
procedure Push;
procedure PushToClipboard;
procedure GetFromClipBoard;
procedure Undo;
procedure Redo;
function CanUndo: boolean;
function CanRedo: boolean;
procedure Clear;
function GetCurrState: THistoryItem;
end;
function HistoryItem(AFigures: TFigureArray): THistoryItem;
var
History: THistory;
ClipBoardFigures: TFigureArray;
implementation
function HistoryItem(AFigures: TFigureArray): THistoryItem;
begin
Result.Figures := AFigures;
end;
{ THistory }
constructor THistory.Create;
begin
FIndex := -1;
end;
procedure THistory.Push(AState: THistoryItem);
var
i: SizeInt;
begin
Inc(FIndex);
SetLength(FItems, FIndex + 1);
FItems[FIndex] := AState;
end;
procedure THistory.Push;
begin
Push(HistoryItem(CloneFigures(FiguresData)));
end;
procedure THistory.PushToClipboard;
var
i, j: SizeInt;
AClipBoardFigures: TFigureArray;
begin
j := 0;
for i := 0 to high(FiguresData) do
begin
if GetFigure(i).selected then
begin
SetLength(AClipBoardFigures, Length(AClipBoardFigures) + 1);
AClipboardFigures[j] := GetFigure(i).Clone;
Inc(j);
end;
end;
ClipBoardFigures:= AClipBoardFigures;
end;
procedure THistory.GetFromClipBoard;
var
i, j: SizeInt;
len: SizeInt;
begin
Len := Length(FiguresData);
j := 0;
SetLength(FiguresData, Length(FiguresData) + Length(ClipBoardFigures));
for i := Len to High(FiguresData) do
begin
FiguresData[i] := ClipBoardFigures[j].Clone;
GetFigure(i).selected := True;
Inc(j);
end;
end;
procedure THistory.Undo;
begin
PSelectAll();
DeleteSelected();
FIndex := max(0, FIndex - 1);
FiguresData := CloneFigures(GetCurrState.Figures);
end;
procedure THistory.Redo;
begin
PSelectAll();
DeleteSelected();
FIndex := min(FIndex + 1, High(FItems));
FiguresData := CloneFigures(GetCurrState.Figures);
end;
function THistory.CanUndo: boolean;
begin
Result := FIndex > 0;
end;
function THistory.CanRedo: boolean;
begin
Result := (FIndex >= 0) and (FIndex < High(FItems));
end;
procedure THistory.Clear;
begin
SetLength(FItems, 0);
FIndex := -1;
Push;
end;
function THistory.GetCurrState: THistoryItem;
begin
Result := FItems[FIndex];
end;
begin
History := THistory.Create;
end.
|
unit DDUtils;
interface
uses
Windows, SysUtils, Classes,
DDraw ;
{ DDCopyBitmap
- Draw a bitmap into a DirectDrawSurface }
procedure DDCopyBitmap( Surface : IDirectDrawSurface ;
Bitmap : HBITMAP ;
x, y, Width, Height : integer ) ;
{ DDLoadBitmap
- Create a DirectDrawSurface from a bitmap resource or file. }
function DDLoadBitmap( DirectDraw : IDirectDraw ;
const BitmapName : string ;
Width : integer ;
Height : integer ) : IDirectDrawSurface ;
{ DDReLoadBitmap
- Load a bitmap from a file or resource into a directdraw surface.
- Normally used to re-load a surface after a restore. }
procedure DDReLoadBitmap( Surface : IDirectDrawSurface ;
const BitmapName : string ) ;
{ DDLoadPalette
- Create a DirectDraw palette object from a bitmap resource or file.
- If the resource doesn't exist or '' is passed create a default 332 palette. }
function DDLoadPalette( DirectDraw : IDirectDraw ;
const BitmapName : string ) : IDirectDrawPalette ;
{ DDColorMatch
- Convert an RGB color to a pysical color.
- Works by letting GDI SetPixel() do the color matching
then we lock the memory and see what it got mapped to. }
function DDColorMatch( Surface : IDirectDrawSurface ;
RGB : TColorRef ) : integer ;
{ DDSetColorKey
- Set a color key for a surface, given an RGB.
- If you pass CLR_INVALID as the color key, the pixel
in the upper-left corner will be used. }
function DDSetColorKey( Surface : IDirectDrawSurface ;
RGB : TColorRef ) : HResult ;
implementation
procedure DDCopyBitmap( Surface : IDirectDrawSurface ;
Bitmap : HBITMAP ;
x, y, Width, Height : integer ) ;
var ImageDC : HDC ;
DC : HDC ;
BM : Windows.TBitmap ;
SurfaceDesc : TDDSurfaceDesc ;
OldBitmap: HBitmap;
begin
if ( Surface = NIL ) or ( Bitmap = 0 ) then
Raise Exception.Create( 'Invalid parameters for DDCopyBitmap' ) ;
// make sure this surface is restored.
Surface.Restore ;
// select bitmap into a memoryDC so we can use it.
ImageDC := CreateCompatibleDC( 0 ) ;
try
OldBitmap := SelectObject( ImageDC, Bitmap ) ;
// get size of the bitmap
GetObject( Bitmap, SizeOf( BM ), @BM ) ;
if Width = 0 then Width := BM.bmWidth ;
if Height = 0 then Height := BM.bmHeight ;
// get size of surface.
SurfaceDesc.dwSize := SizeOf( SurfaceDesc ) ;
SurfaceDesc.dwFlags := DDSD_HEIGHT or DDSD_WIDTH ;
Surface.GetSurfaceDesc(SurfaceDesc);
if Surface.GetDC( DC ) <> DD_OK then
Raise Exception.Create( 'GetDC failed for DirectDraw surface' ) ;
try
StretchBlt( DC, 0, 0, SurfaceDesc.dwWidth, SurfaceDesc.dwHeight,
ImageDC, x, y, Width, Height, SRCCOPY ) ;
finally
Surface.ReleaseDC( DC ) ;
if OldBitmap <> 0 then
SelectObject(ImageDC, OldBitmap);
end ;
finally
DeleteDC( ImageDC ) ;
end ;
end ;
function DDLoadBitmap( DirectDraw : IDirectDraw ;
const BitmapName : string ;
Width : integer ;
Height : integer ) : IDirectDrawSurface ;
var Bitmap : HBitmap ;
BM : Windows.TBitmap ;
SurfaceDesc : TDDSurfaceDesc ;
begin
// try to load the bitmap as a resource, if that fails, try it as a file
Bitmap := LoadImage( GetModuleHandle( NIL ), PChar( BitmapName ),
IMAGE_BITMAP, Width, Height, LR_CREATEDIBSECTION ) ;
try
if Bitmap = 0 then
Bitmap := LoadImage( 0, PChar( BitmapName ), IMAGE_BITMAP, Width, Height,
LR_LOADFROMFILE or LR_CREATEDIBSECTION ) ;
if Bitmap = 0 then
Raise Exception.CreateFmt( 'Unable to load bitmap %s', [ BitmapName ] ) ;
// get size of the bitmap
GetObject( Bitmap, SizeOf( BM ), @BM ) ;
// create a DirectDrawSurface for this bitmap
FillChar( SurfaceDesc, SizeOf( SurfaceDesc ), 0 ) ;
with SurfaceDesc do begin
dwSize := SizeOf( SurfaceDesc ) ;
dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH ;
ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN ;
dwWidth := BM.bmWidth ;
dwHeight := BM.bmHeight ;
end ;
if DirectDraw.CreateSurface( SurfaceDesc, Result, NIL ) <> DD_OK then
Raise Exception.Create( 'CreateSurface failed' ) ;
DDCopyBitmap( Result, Bitmap, 0, 0, 0, 0 ) ;
finally
if Bitmap <> 0 then DeleteObject( Bitmap ) ;
end ;
end ;
procedure DDReLoadBitmap( Surface : IDirectDrawSurface ;
const BitmapName : string ) ;
var Bitmap : HBitmap ;
begin
// try to load the bitmap as a resource, if that fails, try it as a file
Bitmap := LoadImage( GetModuleHandle( NIL ), PChar( BitmapName ),
IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION ) ;
try
if Bitmap = 0 then
Bitmap := LoadImage( 0, PChar( BitmapName ), IMAGE_BITMAP,
0, 0, LR_LOADFROMFILE or LR_CREATEDIBSECTION ) ;
if Bitmap = 0 then
Raise Exception.CreateFmt( 'Unable to load bitmap %s', [ BitmapName ] ) ;
DDCopyBitmap( Surface, Bitmap, 0, 0, 0, 0 ) ;
finally
DeleteObject( Bitmap ) ;
end ;
end ;
function DDLoadPalette( DirectDraw : IDirectDraw ;
const BitmapName : string ) : IDirectDrawPalette ;
type TRGB = array[ 0..255 ] of TRGBQuad ;
PRGB = ^TRGB ;
var i, n : integer ;
h : HRsrc ;
BitmapInfo : PBitmapInfo ;
APE : array[ 0..255 ] of TPaletteEntry ;
RGB : PRGB ;
bfHeader : TBitmapFileHeader ;
biHeader : TBitmapInfoHeader ;
Temp : byte ;
begin
// build a 332 palette as the default.
for i := 0 to 255 do with APE[ i ] do begin
peRed := ( ( ( i SHR 5 ) and $07 ) * 255 div 7 ) ;
peGreen := ( ( ( i SHR 2 ) and $07 ) * 255 div 7 ) ;
peBlue := ( ( i and $03 ) * 255 div 3 ) ;
peFlags := 0 ;
end ;
// get a pointer to the bitmap resource.
if BitmapName <> '' then begin
h := FindResource( 0, PChar( BitmapName ), RT_BITMAP ) ;
if h <> 0 then begin
BitmapInfo := PBitmapInfo( LockResource( LoadResource( 0, h ) ) ) ;
RGB := PRGB( @BitmapInfo^.bmiColors ) ;
if ( BitmapInfo = NIL ) or
( BitmapInfo^.bmiHeader.biSize < sizeof( TBITMAPINFOHEADER ) ) then n := 0
else
if ( BitmapInfo^.bmiHeader.biBitCount > 8 ) then n := 0
else
if ( BitmapInfo^.bmiHeader.biClrUsed = 0 ) then
n := 1 SHL BitmapInfo^.bmiHeader.biBitCount
else
n := BitmapInfo^.bmiHeader.biClrUsed ;
// a DIB color table has its colors stored BGR not RGB
// so flip them around.
for i := 0 to n - 1 do with APE[ i ], RGB^[ i ] do begin
peRed := rgbRed ;
peGreen := rgbGreen ;
peBlue := rgbBlue ;
peFlags := 0 ;
end ;
end else begin
with TFileStream.Create( BitmapName, fmOpenRead ) do try
Read( bfHeader, SizeOf( bfHeader ) ) ;
Read( biHeader, SizeOf( biHeader ) ) ;
Read( APE, SizeOf( APE ) ) ;
finally
Free ;
end ;
// get the number of colors in the color table
if biHeader.biSize <> SizeOf( TBitmapInfoHeader ) then n := 0
else
if biHeader.biBitCount > 8 then n := 0
else
if biHeader.biClrUsed = 0 then n := 1 SHL biHeader.biBitCount else
n := biHeader.biClrUsed ;
// a DIB color table has its colors stored BGR not RGB
// so flip them around.
for i := 0 to n - 1 do with APE[ i ] do begin
Temp := peRed ;
peRed := peBlue ;
peBlue := Temp ;
end ;
end ;
end ;
// create the DD palette
if DirectDraw.CreatePalette( DDPCAPS_8BIT, @APE[ 0 ], Result, NIL ) <> DD_OK then
Raise Exception.Create( 'DirectDraw.CreatePalette failed' ) ;
end ;
function DDColorMatch( Surface : IDirectDrawSurface ;
RGB : TColorRef ) : integer ;
var TempValue : TColorRef ;
DC : HDC ;
SurfaceDesc : TDDSurfaceDesc ;
DDResult : HResult ;
begin
TempValue := 0;
Result := CLR_INVALID ;
// use GDI SetPixel to color match for us
if ( RGB <> CLR_INVALID ) and ( Surface.GetDC( DC ) = DD_OK ) then
try
TempValue := GetPixel( DC, 0, 0 ) ; // save current pixel value
SetPixel( DC, 0, 0, RGB ) ; // set our value
finally
Surface.ReleaseDC( DC ) ;
end ;
// now lock the surface so we can read back the converted color
SurfaceDesc.dwSize := sizeof( SurfaceDesc ) ;
try
repeat
DDResult := Surface.Lock( NIL, @SurfaceDesc, 0, 0 ) ;
until DDResult <> DDERR_WASSTILLDRAWING ;
if DDResult = DD_OK then begin
// get value and mask it to bpp
Result := PInteger( SurfaceDesc.lpSurface )^ and
( 1 SHL SurfaceDesc.ddpfPixelFormat.dwRGBBitCount ) - 1 ;
end ;
finally
Surface.Unlock( NIL ) ;
end ;
// now put the color that was there back.
if ( RGB <> CLR_INVALID ) and ( Surface.GetDC( DC ) = DD_OK ) then
try
SetPixel( DC, 0, 0, TempValue ) ;
finally
Surface.ReleaseDC( DC ) ;
end ;
end ;
function DDSetColorKey( Surface : IDirectDrawSurface ;
RGB : TColorRef ) : HResult ;
var ColorKey : TDDColorKey ;
begin
ColorKey.dwColorSpaceLowValue := DDColorMatch( Surface, RGB ) ;
ColorKey.dwColorSpaceHighValue := ColorKey.dwColorSpaceLowValue ;
Result := Surface.SetColorKey( DDCKEY_SRCBLT, ColorKey ) ;
end ;
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfArrays;
{$I TFL.inc}
interface
uses SysUtils, tfTypes, tfConsts, tfExceptions,
{$IFDEF TFL_DLL} tfImport {$ELSE} tfByteVectors {$ENDIF};
type
ByteArray = record
private
FBytes: IBytes;
function GetByte(Index: Integer): Byte;
procedure SetByte(Index: Integer; const Value: Byte);
public
function IsAssigned: Boolean;
procedure Free;
function GetEnumerator: IBytesEnumerator;
function GetHashCode: Integer;
property HashCode: Integer read GetHashCode;
function GetLen: Integer;
procedure SetLen(Value: Integer);
procedure SetInstanceLen(Value: Integer);
function GetRawData: PByte;
class function Allocate(ASize: Cardinal): ByteArray; overload; static;
class function Allocate(ASize: Cardinal; Filler: Byte): ByteArray; overload; static;
class function AllocateRand(ASize: Cardinal): ByteArray; static;
procedure ReAllocate(ASize: Cardinal);
class function FromBytes(const A: array of Byte): ByteArray; static;
class function FromText(const S: string): ByteArray; static;
class function FromAnsiText(const S: RawByteString): ByteArray; static;
class function FromMem(P: Pointer; Count: Cardinal): ByteArray; static;
class function Parse(const S: string; Delimiter: Char = #0): ByteArray; static;
class function TryParse(const S: string; var R: ByteArray): Boolean; overload; static;
class function TryParse(const S: string; Delimiter: Char; var R: ByteArray): Boolean; overload; static;
class function ParseHex(const S: string): ByteArray; overload; static;
class function ParseHex(const S: string; Delimiter: Char): ByteArray; overload; static;
class function TryParseHex(const S: string; var R: ByteArray): Boolean; overload; static;
class function TryParseHex(const S: string; Delimiter: Char; var R: ByteArray): Boolean; overload; static;
class function ParseBitString(const S: string; ABitLen: Integer): ByteArray; static;
class function FromInt(const Data; DataLen: Cardinal;
Reversed: Boolean): ByteArray; static;
function ToText: string;
function ToString: string;
function ToHex: string;
procedure ToInt(var Data; DataLen: Cardinal; Reversed: Boolean);
procedure Incr;
procedure Decr;
procedure IncrLE;
procedure DecrLE;
procedure Burn;
procedure Fill(AValue: Byte);
function Copy: ByteArray; overload;
function Copy(I: Cardinal): ByteArray; overload;
function Copy(I, L: Cardinal): ByteArray; overload;
function Insert(I: Cardinal; B: Byte): ByteArray; overload;
function Insert(I: Cardinal; const B: ByteArray): ByteArray; overload;
function Insert(I: Cardinal; const B: TBytes): ByteArray; overload;
function Remove(I: Cardinal): ByteArray; overload;
function Remove(I, L: Cardinal): ByteArray; overload;
function Reverse: ByteArray; overload;
function TestBit(BitNo: Cardinal): Boolean;
function SeniorBit: Integer;
class function Concat(const A, B: ByteArray): ByteArray; static;
class function AddBytes(const A, B: ByteArray): ByteArray; static;
class function SubBytes(const A, B: ByteArray): ByteArray; static;
class function AndBytes(const A, B: ByteArray): ByteArray; static;
class function OrBytes(const A, B: ByteArray): ByteArray; static;
class function XorBytes(const A, B: ByteArray): ByteArray; static;
class function ShlBytes(const A: ByteArray; Shift: Cardinal): ByteArray; static;
class function ShrBytes(const A: ByteArray; Shift: Cardinal): ByteArray; static;
class operator Explicit(const Value: ByteArray): Byte;
class operator Explicit(const Value: ByteArray): Word;
class operator Explicit(const Value: ByteArray): LongWord;
class operator Explicit(const Value: ByteArray): UInt64;
class operator Explicit(const Value: Byte): ByteArray;
class operator Explicit(const Value: Word): ByteArray;
class operator Explicit(const Value: LongWord): ByteArray;
class operator Explicit(const Value: UInt64): ByteArray;
class operator Implicit(const Value: ByteArray): TBytes;
class operator Implicit(const Value: TBytes): ByteArray;
class operator Equal(const A, B: ByteArray): Boolean;
class operator Equal(const A: ByteArray; const B: TBytes): Boolean;
class operator Equal(const A: TBytes; const B: ByteArray): Boolean;
class operator Equal(const A: ByteArray; const B: Byte): Boolean;
class operator Equal(const A: Byte; const B: ByteArray): Boolean;
class operator NotEqual(const A, B: ByteArray): Boolean;
class operator NotEqual(const A: ByteArray; const B: TBytes): Boolean;
class operator NotEqual(const A: TBytes; const B: ByteArray): Boolean;
class operator NotEqual(const A: ByteArray; const B: Byte): Boolean;
class operator NotEqual(const A: Byte; const B: ByteArray): Boolean;
class operator Add(const A, B: ByteArray): ByteArray;
class operator Add(const A: ByteArray; const B: TBytes): ByteArray;
class operator Add(const A: ByteArray; const B: Byte): ByteArray;
class operator Add(const A: TBytes; const B: ByteArray): ByteArray;
class operator Add(const A: Byte; const B: ByteArray): ByteArray;
class operator BitwiseAnd(const A, B: ByteArray): ByteArray;
class operator BitwiseOr(const A, B: ByteArray): ByteArray;
class operator BitwiseXor(const A, B: ByteArray): ByteArray;
class operator LeftShift(const A: ByteArray; Shift: Cardinal): ByteArray;
class operator RightShift(const A: ByteArray; Shift: Cardinal): ByteArray;
property InstanceLen: Integer read GetLen write SetInstanceLen;
property Len: Integer read GetLen write SetLen;
property Raw: PByte read GetRawData;
property RawData: PByte read GetRawData;
property Bytes[Index: Integer]: Byte read GetByte write SetByte; default;
end;
implementation
type
PByteArrayRec = ^TByteArrayRec;
PPByteArrayRec = ^PByteArrayRec;
TByteArrayRec = record
FVTable: Pointer;
FRefCount: Integer;
FCapacity: Integer; // number of bytes allocated
FUsed: Integer; // number of bytes used
FData: array[0..0] of Byte;
end;
procedure ByteArrayError(ACode: TF_RESULT; const Msg: string = '');
begin
raise EByteArrayError.Create(ACode, Msg);
end;
procedure HResCheck(ACode: TF_RESULT); inline;
begin
if ACode <> TF_S_OK then
raise EByteArrayError.Create(ACode, '');
end;
{ ByteArray }
function ByteArray.GetByte(Index: Integer): Byte;
begin
if Cardinal(Index) < Cardinal(GetLen) then
Result:= GetRawData[Index]
else
raise EArgumentOutOfRangeException.CreateResFmt(@SIndexOutOfRange, [Index]);
end;
procedure ByteArray.SetByte(Index: Integer; const Value: Byte);
begin
if Cardinal(Index) < Cardinal(GetLen) then
GetRawData[Index]:= Value
else
raise EArgumentOutOfRangeException.CreateResFmt(@SIndexOutOfRange, [Index]);
end;
function ByteArray.IsAssigned: Boolean;
begin
Result:= FBytes <> nil;
end;
procedure ByteArray.Free;
begin
FBytes:= nil;
end;
function ByteArray.GetEnumerator: IBytesEnumerator;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.GetEnum(Result));
{$ELSE}
HResCheck(TByteVector.GetEnum(PByteVector(FBytes), PByteVectorEnum(Result)));
{$ENDIF}
end;
function ByteArray.GetHashCode: Integer;
begin
{$IFDEF TFL_INTFCALL}
Result:= FBytes.GetHashCode;
{$ELSE}
Result:= TByteVector.GetHashCode(PByteVector(FBytes));
{$ENDIF}
end;
function ByteArray.GetLen: Integer;
begin
{$IFDEF TFL_HACK}
Result:= PPByteArrayRec(@Self)^^.FUsed;
{$ELSE}
{$IFDEF TFL_INTFCALL}
Result:= FBytes.GetLen;
{$ELSE}
Result:= TByteVector.GetLen(PByteVector(FBytes));
{$ENDIF}
{$ENDIF}
end;
procedure ByteArray.SetLen(Value: Integer);
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorSetLen(FBytes, Value));
{$ELSE}
HResCheck(ByteVectorSetLen(PByteVector(FBytes), Value));
{$ENDIF}
end;
procedure ByteArray.SetInstanceLen(Value: Integer);
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.SetLen(Value));
{$ELSE}
HResCheck(TByteVector.SetLen(PByteVector(FBytes), Value));
{$ENDIF}
end;
function ByteArray.GetRawData: PByte;
begin
{$IFDEF TFL_HACK}
Result:= @PPByteArrayRec(@Self)^^.FData;
{$ELSE}
{$IFDEF TFL_INTFCALL}
Result:= FBytes.GetRawData;
{$ELSE}
Result:= TByteVector.GetRawData(PByteVector(FBytes));
{$ENDIF}
{$ENDIF}
end;
function ByteArray.TestBit(BitNo: Cardinal): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= FBytes.GetBitSet(BitNo);
{$ELSE}
Result:= TByteVector.GetBitSet(PByteVector(FBytes), BitNo);
{$ENDIF}
end;
function ByteArray.SeniorBit: Integer;
begin
{$IFDEF TFL_INTFCALL}
Result:= FBytes.GetSeniorBit;
{$ELSE}
Result:= TByteVector.GetSeniorBit(PByteVector(FBytes));
{$ENDIF}
end;
class function ByteArray.Allocate(ASize: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorAlloc(Result.FBytes, ASize));
{$ELSE}
HResCheck(ByteVectorAlloc(PByteVector(Result.FBytes), ASize));
{$ENDIF}
end;
class function ByteArray.Allocate(ASize: Cardinal; Filler: Byte): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorAllocEx(Result.FBytes, ASize, Filler));
{$ELSE}
HResCheck(ByteVectorAllocEx(PByteVector(Result.FBytes), ASize, Filler));
{$ENDIF}
end;
class function ByteArray.AllocateRand(ASize: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorAllocRand(Result.FBytes, ASize));
{$ELSE}
HResCheck(ByteVectorAllocRand(PByteVector(Result.FBytes), ASize));
{$ENDIF}
end;
procedure ByteArray.ReAllocate(ASize: Cardinal);
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorReAlloc(FBytes, ASize));
{$ELSE}
HResCheck(ByteVectorReAlloc(PByteVector(FBytes), ASize));
{$ENDIF}
end;
class function ByteArray.FromText(const S: string): ByteArray;
var
S8: UTF8String;
begin
S8:= UTF8String(S);
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromPByte(Result.FBytes, Pointer(S8), Length(S8)));
{$ELSE}
HResCheck(ByteVectorFromPByte(PByteVector(Result.FBytes), Pointer(S8), Length(S8)));
{$ENDIF}
if Pointer(S8) <> Pointer(S) then begin
FillChar(Pointer(S8)^, Length(S8), 32);
end;
end;
class function ByteArray.FromAnsiText(const S: RawByteString): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromPByte(Result.FBytes, Pointer(S), Length(S)));
{$ELSE}
HResCheck(ByteVectorFromPByte(PByteVector(Result.FBytes), Pointer(S), Length(S)));
{$ENDIF}
end;
class function ByteArray.FromBytes(const A: array of Byte): ByteArray;
var
I: Integer;
P: PByte;
begin
Result:= ByteArray.Allocate(Length(A));
P:= Result.RawData;
for I:= 0 to Length(A) - 1 do begin
P^:= A[I];
Inc(P);
end;
end;
class function ByteArray.FromInt(const Data; DataLen: Cardinal;
Reversed: Boolean): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromPByteEx(Result.FBytes, @Data, DataLen, Reversed));
{$ELSE}
HResCheck(ByteVectorFromPByteEx(PByteVector(Result.FBytes), @Data, DataLen, Reversed));
{$ENDIF}
end;
class function ByteArray.FromMem(P: Pointer; Count: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromPByte(Result.FBytes, P, Count));
{$ELSE}
HResCheck(ByteVectorFromPByte(PByteVector(Result.FBytes), P, Count));
{$ENDIF}
end;
class function ByteArray.Parse(const S: string; Delimiter: Char): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorParse(Result.FBytes, Pointer(S), Length(S),
SizeOf(Char), Byte(Delimiter)));
{$ELSE}
HResCheck(ByteVectorParse(PByteVector(Result.FBytes),
Pointer(S), Length(S), SizeOf(Char), Byte(Delimiter)));
{$ENDIF}
end;
class function ByteArray.ParseHex(const S: string): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromPCharHex(Result.FBytes, Pointer(S), Length(S), SizeOf(Char)));
{$ELSE}
HResCheck(ByteVectorFromPCharHex(PByteVector(Result.FBytes),
Pointer(S), Length(S), SizeOf(Char)));
{$ENDIF}
end;
class function ByteArray.ParseHex(const S: string; Delimiter: Char): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorParseHex(Result.FBytes, Pointer(S), Length(S),
SizeOf(Char), Byte(Delimiter)));
{$ELSE}
HResCheck(ByteVectorParseHex(PByteVector(Result.FBytes),
Pointer(S), Length(S), SizeOf(Char), Byte(Delimiter)));
{$ENDIF}
end;
class function ByteArray.TryParseHex(const S: string; var R: ByteArray): Boolean;
begin
Result:= (
{$IFDEF TFL_INTFCALL}
ByteVectorFromPCharHex(R.FBytes, Pointer(S), Length(S), SizeOf(Char))
{$ELSE}
ByteVectorFromPCharHex(PByteVector(R.FBytes),
Pointer(S), Length(S), SizeOf(Char))
{$ENDIF}
= TF_S_OK);
end;
class function ByteArray.TryParse(const S: string; var R: ByteArray): Boolean;
begin
Result:= (
{$IFDEF TFL_INTFCALL}
ByteVectorParse(R.FBytes, Pointer(S), Length(S),
SizeOf(Char), 0)
{$ELSE}
ByteVectorParse(PByteVector(R.FBytes), Pointer(S), Length(S),
SizeOf(Char), 0)
{$ENDIF}
= TF_S_OK);
end;
class function ByteArray.TryParse(const S: string; Delimiter: Char;
var R: ByteArray): Boolean;
begin
Result:= (
{$IFDEF TFL_INTFCALL}
ByteVectorParse(R.FBytes, Pointer(S), Length(S),
SizeOf(Char), Byte(Delimiter))
{$ELSE}
ByteVectorParse(PByteVector(R.FBytes), Pointer(S), Length(S),
SizeOf(Char), Byte(Delimiter))
{$ENDIF}
= TF_S_OK);
end;
class function ByteArray.TryParseHex(const S: string; Delimiter: Char;
var R: ByteArray): Boolean;
begin
Result:= (
{$IFDEF TFL_INTFCALL}
ByteVectorParseHex(R.FBytes, Pointer(S), Length(S),
SizeOf(Char), Byte(Delimiter))
{$ELSE}
ByteVectorParseHex(PByteVector(R.FBytes), Pointer(S), Length(S),
SizeOf(Char), Byte(Delimiter))
{$ENDIF}
= TF_S_OK);
end;
class function ByteArray.ParseBitString(const S: string; ABitLen: Integer): ByteArray;
var
Ch: Char;
I: Integer;
Tmp: Cardinal;
P: PByte;
begin
if (ABitLen <= 0) or (ABitLen > 8) or (Length(S) mod ABitLen <> 0) then
raise Exception.Create('Wrong string length');
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorAlloc(Result.FBytes, Length(S) div ABitLen));
{$ELSE}
HResCheck(ByteVectorAlloc(PByteVector(Result.FBytes), Length(S) div ABitLen));
{$ENDIF}
// SetLength(Result.FBytes, Length(S) div 7);
P:= Result.FBytes.GetRawData;
I:= 0;
Tmp:= 0;
for Ch in S do begin
Tmp:= Tmp shl 1;
if Ch = '1' then Tmp:= Tmp or 1
else if Ch <> '0' then
raise Exception.Create('Wrong string char');
Inc(I);
if I mod 7 = 0 then begin
// Result.FBytes[I div 7 - 1]:= Tmp;
P^:= Tmp;
Inc(P);
Tmp:= 0;
end;
end;
end;
class operator ByteArray.Implicit(const Value: ByteArray): TBytes;
var
L: Integer;
begin
Result:= nil;
{$IFDEF TFL_HACK}
L:= PPByteArrayRec(@Value)^^.FUsed;
if L > 0 then begin
SetLength(Result, L);
Move(PPByteArrayRec(@Value)^^.FData, Pointer(Result)^, L);
end;
{$ELSE}
{$IFDEF TFL_INTFCALL}
L:= Value.FBytes.GetLen;
if L > 0 then begin
SetLength(Result, L);
Move(Value.FBytes.GetRawData^, Pointer(Result)^, L);
end;
{$ELSE}
L:= TByteVector.GetLen(PByteVector(Value.FBytes));
if L > 0 then begin
SetLength(Result, L);
Move(TByteVector.GetRawData(PByteVector(Value.FBytes))^, Pointer(Result)^, L);
end;
{$ENDIF}
{$ENDIF}
end;
class operator ByteArray.Implicit(const Value: TBytes): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromPByte(Result.FBytes, Pointer(Value), Length(Value)));
{$ELSE}
HResCheck(ByteVectorFromPByte(PByteVector(Result.FBytes), Pointer(Value), Length(Value)));
{$ENDIF}
end;
(*
class function ByteArray.Insert(const A: ByteArray; I: Cardinal; B: Byte): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.InsertByte(I, B, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertByte(PByteVector(A.FBytes), I, B, PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.Insert(const A: ByteArray; I: Cardinal; B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.InsertBytes(I, B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertBytes(PByteVector(A.FBytes), I, PByteVector(B.FBytes),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.Insert(const A: ByteArray; I: Cardinal; B: TBytes): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.InsertPByte(I, Pointer(B), Length(B), Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertPByte(PByteVector(A.FBytes), I, Pointer(B), Length(B),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
*)
function ByteArray.Insert(I: Cardinal; B: Byte): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.InsertByte(I, B, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertByte(PByteVector(FBytes), I, B, PByteVector(Result.FBytes)));
{$ENDIF}
end;
function ByteArray.Insert(I: Cardinal; const B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.InsertBytes(I, B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertBytes(PByteVector(FBytes), I, PByteVector(B.FBytes),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
function ByteArray.Insert(I: Cardinal; const B: TBytes): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.InsertPByte(I, Pointer(B), Length(B), Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertPByte(PByteVector(FBytes), I, Pointer(B), Length(B),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
procedure ByteArray.Burn;
begin
{$IFDEF TFL_INTFCALL}
FBytes.Burn;
{$ELSE}
TByteVector.Burn(PByteVector(FBytes));
{$ENDIF}
end;
procedure ByteArray.Fill(AValue: Byte);
begin
{$IFDEF TFL_INTFCALL}
FBytes.Fill(AValue);
{$ELSE}
TByteVector.Fill(PByteVector(FBytes), AValue);
{$ENDIF}
end;
procedure ByteArray.Incr;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.Incr);
{$ELSE}
HResCheck(TByteVector.Incr(PByteVector(FBytes)));
{$ENDIF}
end;
procedure ByteArray.IncrLE;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.IncrLE);
{$ELSE}
HResCheck(TByteVector.IncrLE(PByteVector(FBytes)));
{$ENDIF}
end;
procedure ByteArray.Decr;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.Decr);
{$ELSE}
HResCheck(TByteVector.Decr(PByteVector(FBytes)));
{$ENDIF}
end;
procedure ByteArray.DecrLE;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.DecrLE);
{$ELSE}
HResCheck(TByteVector.DecrLE(PByteVector(FBytes)));
{$ENDIF}
end;
function ByteArray.Remove(I: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.RemoveBytes1(Result.FBytes), I);
{$ELSE}
HResCheck(TByteVector.RemoveBytes1(PByteVector(FBytes),
PByteVector(Result.FBytes), I));
{$ENDIF}
end;
function ByteArray.Remove(I, L: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.RemoveBytes2(Result.FBytes, I, L));
{$ELSE}
HResCheck(TByteVector.RemoveBytes2(PByteVector(FBytes),
PByteVector(Result.FBytes), I, L));
{$ENDIF}
end;
function ByteArray.Reverse: ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.ReverseBytes(Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ReverseBytes(PByteVector(FBytes),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
{$WARNINGS OFF}
class operator ByteArray.Explicit(const Value: ByteArray): Byte;
var
L: Integer;
begin
L:= Value.GetLen;
if L >= 1 then
Result:= PByte(Value.GetRawData)[L-1]
else
ByteArrayError(TF_E_INVALIDARG);
end;
{$WARNINGS ON}
class operator ByteArray.Explicit(const Value: ByteArray): Word;
var
L: Integer;
P: PByte;
begin
L:= Value.GetLen;
if L = 1 then begin
Result:= 0;
WordRec(Result).Lo:= PByte(Value.GetRawData)^;
end
else if L >= 2 then begin
P:= Value.GetRawData;
WordRec(Result).Lo:= P[L-1];
WordRec(Result).Hi:= P[L-2];
end
else
ByteArrayError(TF_E_INVALIDARG);
end;
class operator ByteArray.Explicit(const Value: ByteArray): LongWord;
var
L: Integer;
P, PR: PByte;
begin
L:= Value.GetLen;
if (L > 0) then begin
Result:= 0;
P:= Value.GetRawData;
Inc(P, L);
if (L > SizeOf(LongWord)) then L:= SizeOf(LongWord);
PR:= @Result;
repeat
Dec(P);
PR^:= P^;
Inc(PR);
Dec(L);
until L = 0;
end
else
ByteArrayError(TF_E_INVALIDARG);
end;
class operator ByteArray.Explicit(const Value: ByteArray): UInt64;
var
L: Integer;
P, PR: PByte;
begin
L:= Value.GetLen;
if (L > 0) then begin
Result:= 0;
P:= Value.GetRawData;
Inc(P, L);
if (L > SizeOf(UInt64)) then L:= SizeOf(UInt64);
PR:= @Result;
repeat
Dec(P);
PR^:= P^;
Inc(PR);
Dec(L);
until L = 0;
end
else
ByteArrayError(TF_E_INVALIDARG);
end;
class operator ByteArray.Explicit(const Value: Byte): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(ByteVectorFromByte(Result.FBytes, Value));
{$ELSE}
HResCheck(ByteVectorFromByte(PByteVector(Result.FBytes), Value));
{$ENDIF}
end;
class operator ByteArray.Explicit(const Value: Word): ByteArray;
var
P: PByte;
begin
if Value >= 256 then begin
Result:= ByteArray.Allocate(SizeOf(Word));
P:= Result.RawData;
P[0]:= WordRec(Value).Hi;
P[1]:= WordRec(Value).Lo;
end
else begin
Result:= ByteArray.Allocate(SizeOf(Byte));
P:= Result.RawData;
P[0]:= WordRec(Value).Lo;
end;
end;
class operator ByteArray.Explicit(const Value: LongWord): ByteArray;
var
P, P1: PByte;
L: Integer;
begin
L:= SizeOf(LongWord);
P1:= @Value;
Inc(P1, SizeOf(LongWord) - 1);
while (P1^ = 0) do begin
Dec(L);
Dec(P1);
if L = 1 then Break;
end;
Result:= ByteArray.Allocate(L);
P:= Result.RawData;
repeat
P^:= P1^;
Inc(P);
Dec(P1);
Dec(L);
until L = 0;
end;
class operator ByteArray.Explicit(const Value: UInt64): ByteArray;
var
P, P1: PByte;
L: Integer;
begin
L:= SizeOf(UInt64);
P1:= @Value;
Inc(P1, SizeOf(UInt64) - 1);
while (P1^ = 0) do begin
Dec(L);
Dec(P1);
if L = 1 then Break;
end;
Result:= ByteArray.Allocate(L);
P:= Result.RawData;
repeat
P^:= P1^;
Inc(P);
Dec(P1);
Dec(L);
until L = 0;
end;
procedure ByteArray.ToInt(var Data; DataLen: Cardinal; Reversed: Boolean);
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.ToInt(@Data, DataLen, Reversed));
{$ELSE}
HResCheck(TByteVector.ToInt(PByteVector(FBytes), @Data, DataLen, Reversed));
{$ENDIF}
end;
function ByteArray.ToHex: string;
const
ASCII_0 = Ord('0');
ASCII_A = Ord('A');
var
L: Integer;
P: PByte;
B: Byte;
PS: PChar;
begin
L:= GetLen;
SetLength(Result, 2 * L);
P:= GetRawData;
PS:= PChar(Result);
while L > 0 do begin
B:= P^ shr 4;
if B < 10 then
PS^:= Char(B + ASCII_0)
else
PS^:= Char(B - 10 + ASCII_A);
Inc(PS);
B:= P^ and $0F;
if B < 10 then
PS^:= Char(B + ASCII_0)
else
PS^:= Char(B - 10 + ASCII_A);
Inc(PS);
Inc(P);
Dec(L);
end;
end;
function ByteArray.ToString: string;
var
Tmp: IBytes;
L, N: Integer;
P: PByte;
P1: PChar;
begin
Result:= '';
L:= GetLen;
if L = 0 then Exit;
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.ToDec(Tmp));
{$ELSE}
HResCheck(TByteVector.ToDec(PByteVector(FBytes), PByteVector(Tmp)));
{$ENDIF}
P:= Tmp.GetRawData;
N:= Tmp.GetLen;
SetLength(Result, N);
P1:= PChar(Result);
repeat
if P^ <> 0 then begin
P1^:= Char(P^);
end
else begin
P1^:= Char($20); // space
end;
Inc(P);
Inc(P1);
Dec(N);
until N = 0;
end;
function ByteArray.ToText: string;
var
S8: UTF8String;
L: Integer;
begin
if FBytes = nil then Result:= ''
else begin
L:= FBytes.GetLen;
SetLength(S8, L);
Move(FBytes.GetRawData^, Pointer(S8)^, L);
Result:= string(S8);
if Pointer(S8) <> Pointer(Result) then
FillChar(Pointer(S8)^, Length(S8), 32);
end;
end;
class operator ByteArray.Add(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.ConcatBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ConcatBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.Add(const A: ByteArray; const B: TBytes): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.AppendPByte(Pointer(B), Length(B), Result.FBytes));
{$ELSE}
HResCheck(TByteVector.AppendPByte(PByteVector(A.FBytes),
Pointer(B), Length(B), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.Add(const A: TBytes; const B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(B.FBytes.InsertPByte(0, Pointer(A), Length(A), Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertPByte(PByteVector(B.FBytes), 0,
Pointer(A), Length(A), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.Add(const A: ByteArray; const B: Byte): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.AppendByte(B, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.AppendByte(PByteVector(A.FBytes),
B, PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.Add(const A: Byte; const B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(B.FBytes.InsertByte(0, A, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.InsertByte(PByteVector(B.FBytes), 0,
A, PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.AddBytes(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.AddBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.AddBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.SubBytes(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.SubBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.SubBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.AndBytes(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.AndBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.AndBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.OrBytes(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.OrBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.OrBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.XorBytes(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.XorBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.XorBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.BitwiseAnd(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.AndBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.AndBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.BitwiseOr(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.OrBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.OrBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.BitwiseXor(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.XorBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.XorBytes(PByteVector(A.FBytes),
PByteVector(B.FBytes), PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.ShlBytes(const A: ByteArray;
Shift: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.ShiftLeft(Shift, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ShiftLeft(PByteVector(A.FBytes), Shift,
PByteVector(Result.FBytes)));
{$ENDIF}
end;
class function ByteArray.ShrBytes(const A: ByteArray;
Shift: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.ShiftRight(Shift, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ShiftRight(PByteVector(A.FBytes), Shift,
PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.LeftShift(const A: ByteArray;
Shift: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.ShiftLeft(Shift, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ShiftLeft(PByteVector(A.FBytes), Shift,
PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.RightShift(const A: ByteArray;
Shift: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.ShiftRight(Shift, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ShiftRight(PByteVector(A.FBytes), Shift,
PByteVector(Result.FBytes)));
{$ENDIF}
end;
class operator ByteArray.Equal(const A, B: ByteArray): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= A.FBytes.EqualBytes(B.FBytes);
{$ELSE}
Result:= TByteVector.EqualBytes(PByteVector(A.FBytes), PByteVector(B.FBytes));
{$ENDIF}
end;
class operator ByteArray.Equal(const A: ByteArray; const B: TBytes): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= A.FBytes.EqualToPByte(Pointer(B), Length(B));
{$ELSE}
Result:= TByteVector.EqualToPByte(PByteVector(A.FBytes), Pointer(B), Length(B));
{$ENDIF}
end;
class operator ByteArray.Equal(const A: TBytes; const B: ByteArray): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= B.FBytes.EqualToPByte(Pointer(A), Length(A));
{$ELSE}
Result:= TByteVector.EqualToPByte(PByteVector(B.FBytes), Pointer(A), Length(A));
{$ENDIF}
end;
class operator ByteArray.Equal(const A: ByteArray; const B: Byte): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= A.FBytes.EqualToByte(B);
{$ELSE}
Result:= TByteVector.EqualToByte(PByteVector(A.FBytes), B);
{$ENDIF}
end;
class operator ByteArray.Equal(const A: Byte; const B: ByteArray): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= B.FBytes.EqualToByte(A);
{$ELSE}
Result:= TByteVector.EqualToByte(PByteVector(B.FBytes), A);
{$ENDIF}
end;
class operator ByteArray.NotEqual(const A, B: ByteArray): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= not A.FBytes.EqualBytes(B.FBytes);
{$ELSE}
Result:= not TByteVector.EqualBytes(PByteVector(A.FBytes), PByteVector(B.FBytes));
{$ENDIF}
end;
class operator ByteArray.NotEqual(const A: ByteArray; const B: TBytes): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= not A.FBytes.EqualToPByte(Pointer(B), Length(B));
{$ELSE}
Result:= not TByteVector.EqualToPByte(PByteVector(A.FBytes), Pointer(B), Length(B));
{$ENDIF}
end;
class operator ByteArray.NotEqual(const A: TBytes; const B: ByteArray): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= not B.FBytes.EqualToPByte(Pointer(A), Length(A));
{$ELSE}
Result:= not TByteVector.EqualToPByte(PByteVector(B.FBytes), Pointer(A), Length(A));
{$ENDIF}
end;
class operator ByteArray.NotEqual(const A: ByteArray; const B: Byte): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= not A.FBytes.EqualToByte(B);
{$ELSE}
Result:= not TByteVector.EqualToByte(PByteVector(A.FBytes), B);
{$ENDIF}
end;
class operator ByteArray.NotEqual(const A: Byte; const B: ByteArray): Boolean;
begin
{$IFDEF TFL_INTFCALL}
Result:= not B.FBytes.EqualToByte(A);
{$ELSE}
Result:= not TByteVector.EqualToByte(PByteVector(B.FBytes), A);
{$ENDIF}
end;
class function ByteArray.Concat(const A, B: ByteArray): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(A.FBytes.ConcatBytes(B.FBytes, Result.FBytes));
{$ELSE}
HResCheck(TByteVector.ConcatBytes(PByteVector(A.FBytes), PByteVector(B.FBytes),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
function ByteArray.Copy: ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.CopyBytes(Result.FBytes));
{$ELSE}
HResCheck(TByteVector.CopyBytes(PByteVector(FBytes),
PByteVector(Result.FBytes)));
{$ENDIF}
end;
function ByteArray.Copy(I: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.CopyBytes1(Result.FBytes), I);
{$ELSE}
HResCheck(TByteVector.CopyBytes1(PByteVector(FBytes),
PByteVector(Result.FBytes), I));
{$ENDIF}
end;
function ByteArray.Copy(I, L: Cardinal): ByteArray;
begin
{$IFDEF TFL_INTFCALL}
HResCheck(FBytes.CopyBytes2(Result.FBytes, I, L));
{$ELSE}
HResCheck(TByteVector.CopyBytes2(PByteVector(FBytes),
PByteVector(Result.FBytes), I, L));
{$ENDIF}
end;
end.
|
unit fmuWriteSerial;
interface
uses
// VCL
ComCtrls, Controls, StdCtrls, ExtCtrls, Classes, SysUtils,
Buttons, Graphics,
// This
untPages, untUtil, untDriver;
type
{ TfmWriteSerial }
TfmWriteSerial = class(TPage)
gbSerialNumber: TGroupBox;
edtSerialNumber: TEdit;
gbLicense: TGroupBox;
edtLicense: TEdit;
btnSetSerialNumber: TBitBtn;
btnReadLicense: TBitBtn;
btnWriteLicense: TBitBtn;
gbPointPosition: TGroupBox;
btnSetPointPosition: TBitBtn;
cbPointPosition: TComboBox;
lblPointPosition: TLabel;
grpServiceNumber: TGroupBox;
lblSCPassword: TLabel;
lblNewSCPassword: TLabel;
Label2: TLabel;
edtSCPassword: TEdit;
edtNewSCPassword: TEdit;
btnSetSCPassword: TBitBtn;
procedure btnSetSerialNumberClick(Sender: TObject);
procedure btnReadLicenseClick(Sender: TObject);
procedure btnWriteLicenseClick(Sender: TObject);
procedure btnSetPointPositionClick(Sender: TObject);
procedure btnSetSCPasswordClick(Sender: TObject);
end;
implementation
{$R *.DFM}
{ TfmWriteSerial }
procedure TfmWriteSerial.btnSetSerialNumberClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.SerialNumber := edtSerialNumber.Text;
Driver.SetSerialNumber;
finally
EnableButtons(True);
end;
end;
procedure TfmWriteSerial.btnReadLicenseClick(Sender: TObject);
begin
EnableButtons(False);
try
if Driver.ReadLicense = 0 then
edtLicense.Text := GetLicense(Driver.License)
else
edtLicense.Clear;
finally
EnableButtons(True);
end;
end;
procedure TfmWriteSerial.btnWriteLicenseClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.License := edtLicense.Text;
Driver.WriteLicense;
finally
EnableButtons(True);
end;
end;
procedure TfmWriteSerial.btnSetPointPositionClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.PointPosition := cbPointPosition.ItemIndex > 0;
Driver.SetPointPosition;
finally
EnableButtons(True);
end;
end;
procedure TfmWriteSerial.btnSetSCPasswordClick(Sender: TObject);
begin
EnableButtons(False);
try
Driver.SCPassword := StrToInt(edtSCPassword.Text);
Driver.NewSCPassword := StrToInt(edtNewSCPassword.Text);
Driver.SetSCPassword;
finally
EnableButtons(True);
end;
end;
end.
|
unit mainform;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls,
ExtCtrls, DateUtils,
clock_control;
type
{ TForm1 }
TForm1 = class(TForm)
btnCronometer: TButton;
btnStart: TButton;
btnStop: TButton;
btnReset: TButton;
btnClock: TButton;
labelCronometer: TLabel;
Notebook: TNotebook;
Page1: TPage;
pageCronometer: TPage;
timerCronometer: TTimer;
timerClock: TTimer;
procedure HandleChangePage(Sender: TObject);
procedure btnResetClick(Sender: TObject);
procedure btnStartClick(Sender: TObject);
procedure btnStopClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure timerClockTimer(Sender: TObject);
procedure timerCronometerTimer(Sender: TObject);
private
{ private declarations }
LazClockControl: TLazClockControl;
public
{ public declarations }
CronometerStarted: Boolean;
CronometerTime, CronometerLastUpdate: TTime;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
procedure TForm1.timerClockTimer(Sender: TObject);
begin
LazClockControl.Invalidate;
end;
procedure TForm1.timerCronometerTimer(Sender: TObject);
var
lNow: TDateTime;
lFormatSettings: TFormatSettings;
begin
lNow := Now();
CronometerTime := CronometerTime + CronometerLastUpdate - lNow;
CronometerLastUpdate := lNow;
lFormatSettings := SysUtils.FormatSettings;
lFormatSettings.LongTimeFormat := 'hh:nn:ss:zzz';
labelCronometer.Caption := SysUtils.TimeToStr(CronometerTime, lFormatSettings);
end;
procedure TForm1.HandleChangePage(Sender: TObject);
begin
Notebook.PageIndex := (Sender as TButton).Tag;
end;
procedure TForm1.btnResetClick(Sender: TObject);
begin
CronometerTime := DateUtils.EncodeTimeInterval(0, 0, 0, 0);
end;
procedure TForm1.btnStartClick(Sender: TObject);
begin
CronometerStarted := True;
timerCronometer.Enabled := True;
CronometerLastUpdate := Now();
end;
procedure TForm1.btnStopClick(Sender: TObject);
begin
CronometerStarted := False;
timerCronometer.Enabled := False;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
LazClockControl := TLazClockControl.Create(Self);
LazClockControl.Height := 400;
LazClockControl.Width := 400;
LazClockControl.Top := 0;
LazClockControl.Left := 0;
LazClockControl.Parent := Notebook.Page[0];
LazClockControl.DoubleBuffered := True;
end;
end.
|
{$MODE OBJFPC}
program DIGIT;
const
InputFile = 'DIGIT.INP';
OutputFile = 'DIGIT.OUT';
nbit = 32;
radix = QWord(1) shl nbit;
mask = radix - 1;
maxd = 3;
type
TNumber = array[0..maxd] of Int64;
var
a, b, k: QWord;
res: Integer;
procedure Enter;
var
f: TextFile;
begin
AssignFile(f, InputFile); Reset(f);
try
ReadLn(f, a, b, k);
finally
CloseFile(f);
end;
end;
function MulMod(x, y, z: QWord): QWord; //x * y mod z
var
temp: QWord;
begin
if y = 0 then Exit(0);
temp := MulMod(x, y shr 1, z);
Result := temp shl 1 mod z;
if Odd(y) then
Result := (Result + x) mod z;
end;
function Power10(n, z: QWord): QWord; //10^n mod z
var
temp: QWord;
begin
if n = 0 then Result := 1 mod z
else
begin
temp := Power10(n shr 1, z);
Result := MulMod(temp, temp, z);
if Odd(n) then Result := Result * 10 mod z;
end;
end;
procedure Solve;
begin
res := MulMod(a, Power10(k - 1, b), b) * 10 div b;
end;
procedure PrintResult;
var
f: TextFile;
begin
AssignFile(f, OutputFile); Rewrite(f);
try
Write(f, res);
finally
CloseFile(f);
end;
end;
begin
Enter;
Solve;
PrintResult;
end.
|
{ Classes for interpreting the output of svn commands
Copyright (C) 2007 Vincent Snijders vincents@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 SvnClasses;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, strutils, dateutils,
contnrs,
DOM, XMLRead,
SvnCommand;
type
TEntryKind = (ekUnknown, ekFile, ekDirectory);
TCommitAction = (caUnknown, caModify, caAdd, caDelete);
{ TSvnBase }
TSvnBase = class
private
procedure LoadFromXml(ADoc: TXMLDocument); virtual; abstract;
public
procedure LoadFromStream(s: TStream);
procedure LoadFromFile(FileName: string);
procedure LoadFromCommand(command: string);
end;
{ TCommit }
TCommit = class
private
FAuthor: string;
FDate: string;
FRevision: integer;
procedure LoadFromNode(ANode: TDomNode);
public
procedure Clear;
property Author: string read FAuthor write FAuthor;
property Date: string read FDate write FDate;
property Revision: integer read FRevision write FRevision;
end;
{ TLock }
TLock = class
private
FOwner : string;
FToken : string;
FComment : string;
FCreated : string;
procedure LoadFromNode(ANode: TDomNode);
public
property Owner: string read FOwner write FOwner;
property Token: string read FToken write FToken;
property Comment: string read FComment write FComment;
property Created: string read FCreated write FCreated;
end;
{ TRepository }
TRepository = class
private
FRoot: string;
FUUID: string;
procedure LoadFromNode(ANode: TDomNode);
public
procedure Clear;
property Root: string read FRoot write FRoot;
property UUID: string read FUUID write FUUID;
end;
{ TEntry }
TEntry = class
private
FCommit: TCommit;
FKind: TEntryKind;
FPath: string;
FRepository: TRepository;
FRevision: integer;
FUrl: string;
procedure LoadFromNode(ANode: TDomNode);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
property Commit: TCommit read FCommit;
property Kind: TEntryKind read FKind write FKind;
property Path: string read FPath write FPath;
property URL: string read FUrl write FUrl;
property Repository: TRepository read FRepository;
property Revision: integer read FRevision write FRevision;
end;
{ TSvnInfo }
TSvnInfo = class(TSvnBase)
private
FEntry: TEntry;
procedure LoadFromXml(ADoc: TXMLDocument); override;
public
constructor Create;
constructor Create(const Uri: string);
destructor Destroy; override;
procedure Clear;
property Entry: TEntry read FEntry;
end;
{ TLogPath }
TLogPath = class
private
FAction: TCommitAction;
FCopyFromPath: string;
FCopyFromRevision: integer;
FPath: string;
procedure LoadFromNode(ANode: TDomElement);
public
property Action : TCommitAction read FAction write FAction;
property CopyFromRevision: integer read FCopyFromRevision write FCopyFromRevision;
property CopyFromPath: string read FCopyFromPath write FCopyFromPath;
property Path: string read FPath write FPath;
end;
{ TLogEntry }
TLogEntry = class
private
FAuthor: string;
FDate: string;
FLogPaths: TFPObjectList;
FMessage: string;
FRevision: integer;
function GetCommonPath: string;
function GetDateTime: TDateTime;
function GetDisplayDate: string;
function GetLogPath(index: integer): TLogPath;
function GetLogPathCount: integer;
procedure LoadFromNode(ANode: TDOMElement);
public
constructor Create;
destructor Destroy; override;
function GetFileList(const BaseDir: string = ''): TStrings;
procedure SortPaths;
property Author: string read FAuthor write FAuthor;
property CommonPath: string read GetCommonPath;
property Date: string read FDate write FDate;
property DateTime: TDateTime read GetDateTime;
property DisplayDate: string read GetDisplayDate;
property Message: string read FMessage write FMessage;
property Path[index: integer] :TLogPath read GetLogPath;
property PathCount: integer read GetLogPathCount;
property Revision: integer read FRevision write FRevision;
end;
{ TSvnLog }
TSvnLog = class(TSvnBase)
private
FLogEntries: TFPObjectList;
function GetLogEntry(index: integer): TLogEntry;
function GetLogEntryCount: integer;
procedure LoadFromXml(ADoc: TXMLDocument); override;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
property LogEntry[index: integer] :TLogEntry read GetLogEntry;
property LogEntryCount: integer read GetLogEntryCount;
end;
{ TSvnFileProp }
TSvnFileProp = class
private
FFileName: string;
FProperties: TStrings;
public
constructor Create;
constructor Create(const AFileName: string);
destructor Destroy; override;
property FileName: string read FFileName;
property Properties: TStrings read FProperties;
end;
{ TSvnPropInfo }
TSvnPropInfo = class
private
FFiles: TFPHashObjectList;
function GetFile(index: integer): TSvnFileProp;
function GetFileCount: integer;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromStream(s: TStream); virtual;
procedure LoadFromFile(FileName: string);
procedure LoadForFiles(FileNames: TStrings); virtual;
function GetFileItem(const s: string): TSvnFileProp;
property FileItem[index: integer]: TSvnFileProp read GetFile; default;
property FileCount: integer read GetFileCount;
end;
{ TSvnPropInfoXML }
TSvnPropInfoXML = class(TSvnPropInfo)
public
procedure LoadFromStream(s: TStream); override;
procedure LoadForFiles(FileNames: TStrings); override;
end;
{ TStatusEntry }
TStatusEntry = class
private
FCommit : TCommit;
FPath : String;
FWorkLock : TLock;
FWorkProps : String;
FWorkStatus : String;
FWorkRevision : Integer;
FRepoLock : TLock;
FRepoProps : String;
FRepoStatus : String;
procedure LoadFromNode(ANode: TDOMElement);
public
constructor Create;
destructor Destroy; override;
property Commit : TCommit read FCommit;
property Path: String read FPath write FPath;
property WorkLock: TLock read FWorkLock;
property WorkProps: String read FWorkProps write FWorkProps;
property WorkStatus: String read FWorkStatus write FWorkStatus;
property WorkRevision: Integer read FWorkRevision write FWorkRevision;
property RepoLock: TLock read FRepoLock;
property RepoProps: String read FRepoProps write FRepoProps;
property RepoStatus: String read FRepoStatus write FRepoStatus;
end;
{ TSvnStatusList }
TSvnStatusList = class
private
FTargetPath : String;
FChangeListName : String;
FAgainstRevision : Integer;
FStatusEntries : TFPObjectList;
function GetStatusEntry(index: integer): TStatusEntry;
function GetStatusEntryCount: integer;
procedure LoadFromNode(ANode: TDOMElement);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
property StatusEntry[index: integer] :TStatusEntry read GetStatusEntry; default;
property StatusEntryCount: integer read GetStatusEntryCount;
property TargetPath: String read FTargetPath;
property AgainstRevision: Integer read FAgainstRevision;
property ChangeListName: String read FChangeListName;
end;
TSvnStatus = class(TSVNBase)
private
FLists : TFPObjectList;
protected
function GetStatusList(index: Integer): TSVNStatusList;
function GetListsCount: Integer;
procedure LoadFromXml(ADoc: TXMLDocument); override;
public
constructor Create;
destructor Destroy; override;
property Lists[index: Integer]: TSVNStatusList read GetStatusList;
property ListsCount: Integer read GetListsCount;
end;
implementation
const
ActionStrings : array[TCommitAction] of char =
(' ','M','A','D');
function DomToSvn(const ds: DOMString): String;
begin
Result := UTF8Encode(ds);
end;
function GetChildTextContent(ANode: TDomNode; const AName: string) : string;
var
ChildNode: TDOMNode;
begin
Result := '';
ChildNode := ANode.FindNode(AName);
if assigned(ChildNode) then
Result := DomToSvn(ChildNode.TextContent);
end;
{ TSvnBase }
procedure TSvnBase.LoadFromStream(s: TStream);
var
ADoc: TXMLDocument;
begin
ReadXMLFile(ADoc, s);
try
LoadFromXml(ADoc);
finally
ADoc.Free;
end;
end;
procedure TSvnBase.LoadFromFile(FileName: string);
var
ADoc: TXMLDocument;
begin
ReadXMLFile(ADoc, FileName);
try
LoadFromXml(ADoc);
finally
ADoc.Free;
end;
end;
procedure TSvnBase.LoadFromCommand(command: string);
var
XmlOutput: TMemoryStream;
begin
XmlOutput := TMemoryStream.Create;
try
ExecuteSvnCommand(command, XmlOutput);
//DumpStream(XmlOutput);
XmlOutput.Position := 0;
LoadFromStream(XmlOutput);
finally
XmlOutput.Free;
end;
end;
{ TSvnInfo }
procedure TSvnInfo.LoadFromXml(ADoc: TXMLDocument);
begin
Clear;
Entry.LoadFromNode(ADoc.DocumentElement.FindNode('entry'));
end;
constructor TSvnInfo.Create;
begin
inherited Create;
FEntry := TEntry.Create;
end;
constructor TSvnInfo.Create(const Uri: string);
begin
Create;
LoadFromCommand('info --xml '+Uri);
end;
destructor TSvnInfo.Destroy;
begin
FEntry.Free;
inherited Destroy;
end;
procedure TSvnInfo.Clear;
begin
FEntry.Clear;
end;
{ TEntry }
procedure TEntry.LoadFromNode(ANode: TDomNode);
var
EntryNode: TDomElement;
KindString: string;
UrlNode: TDomNode;
begin
if ANode=nil then exit;
if ANode.NodeType = ELEMENT_NODE then begin
EntryNode := TDomElement(ANode);
FRevision := StrToIntDef(EntryNode.GetAttribute('revision'),0);
FPath := DomToSvn(EntryNode.GetAttribute('path'));
KindString := DomToSvn(EntryNode.GetAttribute('kind'));
if KindString = 'file' then
FKind := ekFile
else if KindString = 'dir' then
FKind := ekDirectory
else
FKind := ekUnknown;
UrlNode := EntryNode.FindNode('url');
if assigned(UrlNode) then
FUrl := DomToSvn(UrlNode.TextContent);
FRepository.LoadFromNode(EntryNode.FindNode('repository'));
FCommit.LoadFromNode(EntryNode.FindNode('commit'));
end;
end;
constructor TEntry.Create;
begin
inherited Create;
FCommit := TCommit.Create;
FRepository := TRepository.Create;
end;
destructor TEntry.Destroy;
begin
FCommit.Free;
FRepository.Free;
inherited Destroy;
end;
procedure TEntry.Clear;
begin
FPath := '';
FKind := ekUnknown;
FUrl := '';
FRevision := 0;
FCommit.Clear;
FRepository.Clear;
end;
{ TRepository }
procedure TRepository.LoadFromNode(ANode: TDomNode);
begin
if ANode=nil then exit;
FRoot := GetChildTextContent(ANode, 'root');
FUUID := GetChildTextContent(ANode, 'uuid');
end;
procedure TRepository.Clear;
begin
FRoot := '';
FUUID := '';
end;
{ TCommit }
procedure TCommit.LoadFromNode(ANode: TDomNode);
begin
if ANode=nil then exit;
if ANode.NodeType = ELEMENT_NODE then begin
FRevision := StrToIntDef(TDomElement(ANode).GetAttribute('revision'),0);
FAuthor := GetChildTextContent(ANode, 'author');
FDate := GetChildTextContent(ANode, 'date');
end;
end;
procedure TCommit.Clear;
begin
FAuthor := '';
FDate := '';
FRevision := 0;
end;
{ TSvnLog }
function TSvnLog.GetLogEntry(index: integer): TLogEntry;
begin
Result := TLogEntry(FLogEntries[index]);
end;
function TSvnLog.GetLogEntryCount: integer;
begin
Result := FLogEntries.Count;
end;
procedure TSvnLog.LoadFromXml(ADoc: TXMLDocument);
var
LogEntryElement: TDomNode;
NewLogEntry: TLogEntry;
begin
Clear;
LogEntryElement := ADoc.FindNode('log').FirstChild;
while assigned(LogEntryElement) do begin
if (LogEntryElement.NodeType=ELEMENT_NODE)
and (LogEntryElement.NodeName='logentry') then
begin
NewLogEntry := TLogEntry.Create;
NewLogEntry.LoadFromNode(TDomElement(LogEntryElement));
FLogEntries.Add(NewLogEntry);
end;
LogEntryElement := LogEntryElement.NextSibling;
end;
end;
constructor TSvnLog.Create;
begin
inherited Create;
FLogEntries := TFPObjectList.Create(true);
end;
destructor TSvnLog.Destroy;
begin
FLogEntries.Free;
inherited Destroy;
end;
procedure TSvnLog.Clear;
begin
FLogEntries.Clear;
end;
{ TLogEntry }
function TLogEntry.GetLogPath(index: integer): TLogPath;
begin
Result := TLogPath(FLogPaths[index]);
end;
function TLogEntry.GetCommonPath: string;
var
i: integer;
NextPath: string;
begin
if FLogPaths.Count = 0 then exit('');
Result := ExtractFilePath(Path[0].Path);
i := 1;
while i<FLogPaths.Count do begin
NextPath := Path[i].Path;
while (Copy(NextPath,1,length(Result))<>Result) do
Result := ExtractFilePath(ExtractFileDir(Result));
inc(i);
end;
end;
function TLogEntry.GetDateTime: TDateTime;
begin
Result := ScanDateTime('yyyy-mm-dd"T"hh:nn:ss.zzz',FDate);
end;
function TLogEntry.GetDisplayDate: string;
begin
Result := Copy(FDate, 1, 10) + ' ' + Copy(FDate,12,8);
end;
function TLogEntry.GetFileList(const BaseDir: string = ''): TStrings;
var
i: integer;
begin
Result := TStringList.Create;
for i:= 0 to PathCount -1 do
if Path[i].Action in [caModify, caAdd] then
Result.Add(SetDirSeparators(BaseDir + Path[i].Path));
end;
function TLogEntry.GetLogPathCount: integer;
begin
Result := FLogPaths.Count;
end;
procedure TLogEntry.LoadFromNode(ANode: TDOMElement);
var
PathsElement: TDomNode;
PathElement: TDomNode;
NewLogPath: TLogPath;
begin
FRevision := StrToIntDef(ANode.GetAttribute('revision'),0);
FAuthor := GetChildTextContent(ANode, 'author');
FDate := GetChildTextContent(ANode, 'date');
FMessage := GetChildTextContent(ANode, 'msg');
PathsElement := ANode.FindNode('paths');
if assigned(PathsELement) then begin
PathElement := PathsElement.FirstChild;
while assigned(PathElement) do begin
if (PathElement.NodeType=ELEMENT_NODE)
and (PathElement.NodeName='path') then
begin
NewLogPath := TLogPath.Create;
NewLogPath.LoadFromNode(TDomElement(PathElement));
FLogPaths.Add(NewLogPath);
end;
PathElement := PathElement.NextSibling;
end;
end;
end;
function PathCompare(Item1, Item2: Pointer): Integer;
var
Path1, Path2: TLogPath;
begin
Path1 := TLogPath(Item1);
Path2 := TLogPath(Item2);
Result := CompareStr(Path1.Path, Path2.Path);
end;
procedure TLogEntry.SortPaths;
begin
FLogPaths.Sort(@PathCompare);
end;
constructor TLogEntry.Create;
begin
inherited Create;
FLogPaths := TFPObjectList.Create(true);
end;
destructor TLogEntry.Destroy;
begin
FLogPaths.Free;
inherited Destroy;
end;
{ TLogPath }
procedure TLogPath.LoadFromNode(ANode: TDomElement);
var
ActionStr: string;
i: TCommitAction;
begin
FPath := DomToSvn(ANode.TextContent);
FCopyFromRevision := StrToIntDef(ANode.GetAttribute('copyfrom-rev'),0);
FCopyFromPath := DomToSvn(ANode.GetAttribute('copyfrom-path'));
ActionStr := ANode.GetAttribute('action');
FAction := caUnknown;
for i := low(TCommitAction) to high(TCommitAction) do
if ActionStrings[i]=ActionStr then begin
FAction := i;
break;
end;
end;
{ TSvnFileProp }
constructor TSvnFileProp.Create;
begin
FProperties := TStringList.Create;
end;
constructor TSvnFileProp.Create(const AFileName: string);
begin
Create;
FFileName := AFileName;
end;
destructor TSvnFileProp.Destroy;
begin
FProperties.Free;
inherited Destroy;
end;
{ TSvnPropInfo }
function TSvnPropInfo.GetFile(index: integer): TSvnFileProp;
begin
Result := TSvnFileProp(FFiles[index]);
end;
function TSvnPropInfo.GetFileCount: integer;
begin
Result := FFiles.Count;
end;
constructor TSvnPropInfo.Create;
begin
FFiles := TFPHashObjectList.Create(true);
end;
destructor TSvnPropInfo.Destroy;
begin
FFiles.Free;
inherited Destroy;
end;
procedure TSvnPropInfo.LoadFromStream(s: TStream);
var
Lines: TStrings;
Line: string;
FileProp: TSvnFileProp;
i: Integer;
QuotePos, ColonPos: integer;
PropName, PropValue: String;
const
PropertiesOn = 'Properties on ';
begin
Lines := TStringList.Create;
try
Lines.LoadFromStream(s);
i := 0;
while (i<Lines.Count) do begin
Line := Lines[i];
if copy(Line, 1, length(PropertiesOn))=PropertiesOn then begin
QuotePos := PosEx('''', Line, Length(PropertiesOn)+2);
FileProp := TSvnFileProp.Create(
Copy(Line, Length(PropertiesOn)+2, QuotePos - Length(PropertiesOn)-2));
FFiles.Add(FileProp.FileName, FileProp);
inc(i);
while (i<Lines.Count) do begin
Line := Lines[i];
if (Length(Line)<2) or (Line[1]<>' ') then begin
// new file, so unget line
dec(i);
break;
end;
ColonPos := Pos(' : ', Line);
PropName := Copy(Line, 3, ColonPos - 3);
PropValue := Copy(Line, ColonPos + 3, Length(Line)-ColonPos-2);
// try for a multiline property
inc(i);
while (i<Lines.Count) do begin
if ((length(Lines[i])>=2) and (copy(Lines[i],1,2)=' '))
or (copy(Lines[i], 1, length(PropertiesOn))=PropertiesOn) then begin
// new property, unget line
dec(i);
break;
end;
PropValue := PropValue + LineEnding + Lines[i];
inc(i);
end;
FileProp.Properties.Values[PropName] := PropValue;
inc(i);
end;
end
else
inc(i);
end;
finally
Lines.Free;
end;
end;
procedure TSvnPropInfo.LoadFromFile(FileName: string);
var
FileStream: TFileStream;
begin
FileStream := TFileStream.Create(FileName, fmOpenRead);
try
LoadFromStream(FileStream);
finally
FileStream.Free;
end;
end;
procedure TSvnPropInfo.LoadForFiles(FileNames: TStrings);
var
Output: TMemoryStream;
Files: string;
i: integer;
begin
Output := TMemoryStream.Create;
try
if FileNames.Count>0 then begin
Files := '';
for i := 0 to FileNames.Count-1 do
Files := Files + format(' "%s"', [FileNames[i]]);
ExecuteSvnCommand('proplist -v' + Files, Output);
Output.Position := 0;
end;
LoadFromStream(Output);
for i := 0 to FileNames.Count -1 do begin
if FFiles.FindIndexOf(FileNames[i])<0 then begin
FFiles.Add(FileNames[i], TSvnFileProp.Create(FileNames[i]));
end;
end;
finally
Output.Free;
end;
end;
function TSvnPropInfo.GetFileItem(const s: string): TSvnFileProp;
begin
Result := TSvnFileProp(FFiles.Find(s));
end;
{ TSvnStatusList }
function TSvnStatusList.GetStatusEntry(index: integer): TStatusEntry;
begin
Result := TStatusEntry(FStatusEntries[index]);
end;
function TSvnStatusList.GetStatusEntryCount: integer;
begin
Result := FStatusEntries.Count;
end;
procedure TSvnStatusList.LoadFromNode(ANode: TDOMElement);
var
EntryNode : TDOMNode;
StatEntry : TStatusEntry;
begin
Clear;
FAgainstRevision := 0;
FTargetPath := '';
if not Assigned(ANode) then Exit;
EntryNode := ANode as TDOMNode;
if EntryNode.NodeName = 'target' then
FTargetPath := DomToSvn((EntryNode as TDOMElement).GetAttribute('path'))
else if EntryNode.NodeName = 'changelist' then
FChangeListName := DomToSvn((EntryNode as TDOMElement).GetAttribute('name'));
EntryNode := ANode.FirstChild;
while assigned(EntryNode) do begin
if (EntryNode.NodeType=ELEMENT_NODE)
and (EntryNode.NodeName='entry') then
begin
StatEntry := TStatusEntry.Create;
StatEntry.LoadFromNode(TDomElement(EntryNode));
FStatusEntries.Add(StatEntry);
end else if (EntryNode.NodeName='against') then
begin
FAgainstRevision := StrToIntDef(TDOMElement(EntryNode).GetAttribute('revision'), 0);
end;
EntryNode := EntryNode.NextSibling;
end;
end;
constructor TSvnStatusList.Create;
begin
inherited Create;
FStatusEntries:=TFPObjectList.Create(true);
end;
destructor TSvnStatusList.Destroy;
begin
FStatusEntries.Free;
inherited Destroy;
end;
procedure TSvnStatusList.Clear;
begin
FStatusEntries.Clear;
end;
{ TStatusEntry }
procedure TStatusEntry.LoadFromNode(ANode: TDOMElement);
var
StatusNode: TDOMNode;
SubNode : TDOMNode;
begin
if not Assigned(ANode) then Exit;
FPath := DomToSvn(ANode.GetAttribute('path'));
StatusNode := ANode.FindNode('wc-status');
if Assigned(StatusNode) and (StatusNode is TDOMElement) then begin
FWorkProps := DomToSvn(TDomElement(StatusNode).GetAttribute('props'));
FWorkStatus := DomToSvn(TDomElement(StatusNode).GetAttribute('item'));
FWorkRevision := StrToIntDef(TDomElement(StatusNode).GetAttribute('revision'),0);
SubNode := StatusNode.FindNode('commit');
if Assigned(subNode) then FCommit.LoadFromNode(subNode);
SubNode := StatusNode.FindNode('lock');
if Assigned(SubNode) then begin
if not Assigned(FWorkLock) then FWorkLock := TLock.Create;
FWorkLock.LoadFromNode(SubNode);
end;
end;
StatusNode := ANode.FindNode('repos-status');
if Assigned(StatusNode) and (StatusNode is TDOMElement) then begin
FRepoProps := DomToSvn(TDomElement(StatusNode).GetAttribute('props'));
FRepoStatus := DomToSvn(TDomElement(StatusNode).GetAttribute('item'));
SubNode := StatusNode.FindNode('lock');
if Assigned(SubNode) then begin
if not Assigned(FRepoLock) then FRepoLock := TLock.Create;
FRepoLock.LoadFromNode(SubNode);
end;
end;
end;
constructor TStatusEntry.Create;
begin
FCommit := TCommit.Create;
end;
destructor TStatusEntry.Destroy;
begin
FCommit.Free;
FRepoLock.Free;
FWorkLock.Free;
inherited Destroy;
end;
{ TLock }
procedure TLock.LoadFromNode(ANode: TDomNode);
begin
if ANode=nil then exit;
if ANode.NodeType = ELEMENT_NODE then begin
FToken := GetChildTextContent(ANode, 'token');
FOwner := GetChildTextContent(ANode, 'owner');
fComment := GetChildTextContent(ANode, 'comment');
fCreated := GetChildTextContent(ANode, 'created');
end;
end;
{ TSvnStatus }
function TSvnStatus.GetStatusList(index: Integer): TSVNStatusList;
begin
Result := FLists[Index] as TSVNStatusList;
end;
function TSvnStatus.GetListsCount: Integer;
begin
Result := FLists.Count;
end;
procedure TSvnStatus.LoadFromXml(ADoc: TXMLDocument);
var
ListNode : TDOMNode;
NodeName : String;
StatList : TSvnStatusList;
begin
ListNode := ADoc.FindNode('status').FirstChild;
while Assigned(ListNode) do begin
NodeName := ListNode.NodeName;
if (ListNode.NodeType=ELEMENT_NODE) and
((NodeName='target') or (NodeName='changelist')) then begin
StatList := TSvnStatusList.Create;
FLists.Add(StatList);
StatList.LoadFromNode(ListNode as TDomElement);
end;
ListNode := ListNode.NextSibling;
end;
end;
constructor TSvnStatus.Create;
begin
inherited Create;
FLists := TFPObjectList.Create(true);
end;
destructor TSvnStatus.Destroy;
begin
FLists.Free;
inherited Destroy;
end;
{ TSvnPropInfoXML }
procedure TSvnPropInfoXML.LoadFromStream(s: TStream);
var
doc : TXMLDocument;
proplist : TDOMNode;
prop : TDomNode;
target : TDOMNode;
fileName : String;
FileProp : TSvnFileProp;
pName : String;
begin
ReadXMLFile(doc, s);
try
proplist := doc.FindNode('properties');
if not Assigned(proplist) then Exit;
target := proplist.FirstChild;
while Assigned(target) do begin
if target.NodeName = 'target' then begin
fileName := DomToSvn(TDomElement(target).GetAttribute('path'));
FileProp := TSvnFileProp.Create(fileName);
prop := target.FirstChild;
while Assigned(prop) do begin
if prop.NodeName = 'property' then begin
pName := DomToSvn(TDomElement(prop).GetAttribute('name'));
FileProp.Properties.Values[pName] := DomToSvn(prop.TextContent);
end;
prop := prop.NextSibling;
end;
FFiles.Add(FileProp.FileName, FileProp);
end;
target := target.NextSibling;
end;
finally
doc.Free;
end;
end;
procedure TSvnPropInfoXML.LoadForFiles(FileNames: TStrings);
var
Output: TMemoryStream;
Files: string;
i: integer;
begin
Output := TMemoryStream.Create;
try
if FileNames.Count>0 then begin
Files := '';
for i := 0 to FileNames.Count-1 do
Files := Files + format(' "%s"', [FileNames[i]]);
ExecuteSvnCommand('proplist --xml -v' + Files, Output);
Output.Position := 0;
end;
LoadFromStream(Output);
for i := 0 to FileNames.Count -1 do begin
if FFiles.FindIndexOf(FileNames[i])<0 then begin
FFiles.Add(FileNames[i], TSvnFileProp.Create(FileNames[i]));
end;
end;
finally
Output.Free;
end;
end;
end.
|
unit uPengeluaranKas;
interface
uses
uModel, uRekBank, uAR, uAccount, System.Generics.Collections,
System.SysUtils, uSupplier, uPenerimaanKas;
type
TPengeluaranKasAPNew = class;
TPengeluaranKasAP = class;
TPengeluaranKasNonAP = class;
TPengeluaranKas = class(TAppObject)
private
FCabang: TCabang;
FJenisTransaksi: string;
FJthTempoBG: TDatetime;
FKeterangan: string;
FNoBG: string;
FNoBukti: string;
FNominal: Double;
FPenerima: TSupplier;
FPengeluaranKasAPs: TobjectList<TPengeluaranKasAP>;
FPengeluaranKasAPNews: TobjectList<TPengeluaranKasAPNew>;
FPengeluaranKasNonAPs: TobjectList<TPengeluaranKasNonAP>;
FPetugas: string;
FRekBank: TRekBank;
FTglBukti: TDatetime;
function GetPengeluaranKasAPs: TobjectList<TPengeluaranKasAP>;
function GetPengeluaranKasAPNews: TobjectList<TPengeluaranKasAPNew>;
function GetPengeluaranKasNonAPs: TobjectList<TPengeluaranKasNonAP>;
procedure SetCabang(const Value: TCabang);
published
property Cabang: TCabang read FCabang write SetCabang;
property JenisTransaksi: string read FJenisTransaksi write FJenisTransaksi;
property JthTempoBG: TDatetime read FJthTempoBG write FJthTempoBG;
property Keterangan: string read FKeterangan write FKeterangan;
property NoBG: string read FNoBG write FNoBG;
property NoBukti: string read FNoBukti write FNoBukti;
property Nominal: Double read FNominal write FNominal;
property Penerima: TSupplier read FPenerima write FPenerima;
property PengeluaranKasAPs: TobjectList<TPengeluaranKasAP> read
GetPengeluaranKasAPs write FPengeluaranKasAPs;
property PengeluaranKasAPNews: TobjectList<TPengeluaranKasAPNew> read
GetPengeluaranKasAPNews write FPengeluaranKasAPNews;
property PengeluaranKasNonAPs: TobjectList<TPengeluaranKasNonAP> read
GetPengeluaranKasNonAPs write FPengeluaranKasNonAPs;
property Petugas: string read FPetugas write FPetugas;
property RekBank: TRekBank read FRekBank write FRekBank;
property TglBukti: TDatetime read FTglBukti write FTglBukti;
end;
TPengeluaranKasAP = class(TAppObjectItem)
private
FAP: TAP;
FKeterangan: string;
FNominal: Double;
FPengeluaranKas: TPengeluaranKas;
public
function GetHeaderField: string; override;
procedure SetHeaderProperty(AHeaderProperty : TAppObject); override;
published
property AP: TAP read FAP write FAP;
property Keterangan: string read FKeterangan write FKeterangan;
property Nominal: Double read FNominal write FNominal;
property PengeluaranKas: TPengeluaranKas read FPengeluaranKas write
FPengeluaranKas;
end;
TPengeluaranKasNonAP = class(TAppObjectItem)
private
FAccount: TAccount;
FKeterangan: string;
FNominal: Double;
FPengeluaranKas: TPengeluaranKas;
public
function GetHeaderField: string; override;
procedure SetHeaderProperty(AHeaderProperty : TAppObject); override;
published
property Account: TAccount read FAccount write FAccount;
property Keterangan: string read FKeterangan write FKeterangan;
property Nominal: Double read FNominal write FNominal;
property PengeluaranKas: TPengeluaranKas read FPengeluaranKas write
FPengeluaranKas;
end;
TPengeluaranKasAPNew = class(TAppObjectItem)
private
FAccount: TAccount;
FAP: TAP;
FKeterangan: string;
FNominal: Double;
FPengeluaranKas: TPengeluaranKas;
public
function GetHeaderField: string; override;
procedure SetHeaderProperty(AHeaderProperty : TAppObject); override;
published
property Account: TAccount read FAccount write FAccount;
property AP: TAP read FAP write FAP;
property Keterangan: string read FKeterangan write FKeterangan;
property Nominal: Double read FNominal write FNominal;
property PengeluaranKas: TPengeluaranKas read FPengeluaranKas write
FPengeluaranKas;
end;
implementation
function TPengeluaranKas.GetPengeluaranKasAPs: TobjectList<TPengeluaranKasAP>;
begin
if FPengeluaranKasAPs = nil then
FPengeluaranKasAPs := TObjectList<TPengeluaranKasAP>.Create();
Result := FPengeluaranKasAPs;
end;
function TPengeluaranKas.GetPengeluaranKasAPNews:
TobjectList<TPengeluaranKasAPNew>;
begin
if FPengeluaranKasAPNews = nil then
FPengeluaranKasAPNews := TObjectList<TPengeluaranKasAPNew>.Create();
Result := FPengeluaranKasAPNews;
end;
function TPengeluaranKas.GetPengeluaranKasNonAPs:
TobjectList<TPengeluaranKasNonAP>;
begin
if FPengeluaranKasNonAPs = nil then
FPengeluaranKasNonAPs := TObjectList<TPengeluaranKasNonAP>.Create();
Result := FPengeluaranKasNonAPs;
end;
procedure TPengeluaranKas.SetCabang(const Value: TCabang);
begin
if FCabang <> Value then
begin
FreeAndNil(FCabang);
FCabang := Value;
end;
FCabang := Value;
end;
function TPengeluaranKasAP.GetHeaderField: string;
begin
Result := 'PengeluaranKas';
end;
procedure TPengeluaranKasAP.SetHeaderProperty(AHeaderProperty : TAppObject);
begin
Self.PengeluaranKas := TPengeluaranKas(AHeaderProperty);
end;
function TPengeluaranKasNonAP.GetHeaderField: string;
begin
Result := 'PengeluaranKas';
end;
procedure TPengeluaranKasNonAP.SetHeaderProperty(AHeaderProperty : TAppObject);
begin
Self.PengeluaranKas := TPengeluaranKas(AHeaderProperty);
end;
function TPengeluaranKasAPNew.GetHeaderField: string;
begin
Result := 'PengeluaranKas';
end;
procedure TPengeluaranKasAPNew.SetHeaderProperty(AHeaderProperty : TAppObject);
begin
Self.PengeluaranKas := TPengeluaranKas(AHeaderProperty);
end;
end.
|
unit ConstantsTypes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Station, way;
const r=5; // radius of stations
mincr=1;
maxcr=5;
minway=1;
maxway=30;
type
PItem = ^SItem;
SItem = record
Value:Tstation;
next:PItem;
end;
type
WPitem = ^WayItem;
WayItem = record
Value:TWay;
next:WPitem;
end;
implementation
end.
|
program ManageArrays;
{$Mode delphi}
uses
SysUtils,
Quick.Commons,
Quick.Console,
Quick.Arrays;
type
TUser = record
Name : string;
Age : Integer;
end;
TUserArray = TXArray<TUser>;
var
userarray : TUserArray;
user : TUser;
normalarray : TArray<TUser>;
begin
try
user.Name := 'Joe';
user.Age := 30;
userarray.Add(user);
user.Name := 'Peter';
user.Age := 32;
userarray.Add(user);
user.Name := 'James';
user.Age := 40;
userarray.Add(user);
if userarray.Contains(user) then cout('found user in array',etInfo);
cout('List users:',ccYellow);
for user in userarray do
begin
coutFmt('User: %s',[user.Name],etInfo);
end;
normalarray := userarray;
coutFmt('Copied array value 1: %s',[normalarray[1].Name],etInfo);
cout('Press <Enter> to Exit',ccYellow);
ConsoleWaitForEnterKey;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
|
program MultiTask_PreCompiler;
uses
sysutils,
classes,
strutils,
typinfo,
fileutil,
ucmdline,
uMultiTask,
uMultiTaskQueue,
StringUtils,
uIOFile_v4,
regexpr,
SuperObject;
type
tParam =
record
Name : string;
Typ : string;
end;
tMethod =
record
Name : string;
Params : array of tParam;
end;
tMethods = array of tMethod;
var
InputFileName : string; // defaults to ''
OnNewWorkMethodFileName : string; // name of OnNewWork filename (could be .inc or '', when '' then ) - defaults to On_New_Work
MethodDefinitionFile : string; // where to place md. when '' then in source file on place MT_def
MethodImplementationFile : string; // where to place mi. when '' then in source file on place MT_impl
Type_Definition_File : string;
Type_Definition : tStringList;
Class_Name : string; // name of class for which we generate, or class can be selected as class_MT flag
MethodFlagName : string; // defaults to MT - so then method should be flaged as gen_MT (when more than one object, could be other for second objects)
MultiTaskerObjectname : string; // defaults to MultiTask
Default_Priority : tMultitaskEnQueueFlag;
OnNewWorkMethodName : string; // name of OnNewWork method - defaults to On_New_Work
Default_Method_Suffix : string;
// Switches
GenerateUniqueMethods : boolean;
Generate_Main_Methods : boolean;
Generate_Last_Priority_Methods : boolean;
Generate_Low_Priority_Methods : boolean;
Generate_Normal_Priority_Methods : boolean;
Generate_High_Priority_Methods : boolean;
Generate_ASAP_Priority_Methods : boolean;
Methods : tMethods;
procedure InitParameters;
begin
MethodFlagName := getOptionS('mfn','Method-Flag-Name','compile methods tag with {gen_<Method-Flag-Name>}','MT');
Class_Name := getOptionS('cn','Class-Name','to which class generated methods belongs, or class can be selected as class_<Method-Flag-Name> flag','');
if Class_Name <> '' then Class_Name := Class_Name + '.';
MultiTaskerObjectname := getOptionS('mto','Multi-Task-Object','name of MultiTask object variable','MultiTask');
MethodDefinitionFile := getOptionS('mdf','Method-Definition-File','when use .inc file for generated interface, this is filename for it, default <InputFileName>+_<Method-Flag-Name>_def.inc','');
MethodImplementationFile := getOptionS('mif','Method-Implementation-File','when use .inc file for implementation, this is filename for it, default <InputFileName>+_<Method-Flag-Name>_impl.inc','');
OnNewWorkMethodFileName := getOptionS('onwf','On-New-Work-Method-FileName','Name of main worker method file - default <InputFileName>+_onNewWork.inc','');
OnNewWorkMethodName := getOptionS('onw','On-New-Work-Method-Name','Name of main worker method - this method is generated and runs adequate method','On_New_Work');
Default_Method_Suffix := getOptionS('dms','Default-Method-Suffix','default suffix for generated multi task methods f.e.: Write->Write_<Default-Method-Suffix>','_MT');
Type_Definition_File := getOptionS('tdf','Type-Definition-File','file with info about object and interfaces','MultiTask_Type_Definition.cfg');
Type_Definition := tStringList.Create;
if FileExists(Type_Definition_File) then
Type_Definition.LoadFromFile(Type_Definition_File);
Generate_Main_Methods := getOptionB('dgmm','Disable-Main-Methods','generate main multitask invoke methods', true);
GenerateUniqueMethods := getOptionB('gum','Unique-Methods','generate unique multitask invoke methods', false);
case lowercase(getOptionS('dp','Default-Priority','default priority for enqueuing','NORMAL')) of
'asap' : Default_Priority := teFirst;
'high' : Default_Priority := teHighPriority;
'last' : Default_Priority := teLast;
'low' : Default_Priority := teLowPriority;
else Default_Priority := teNormalPriority;
end;
Generate_Last_Priority_Methods := getOptionB('lapm','Last-Priority-Methods','generation of f.e.: Write->Write_<Default-Method-Suffix>_Last_Priority', false);
Generate_Low_Priority_Methods := getOptionB('lopm','Low-Priority-Methods','generation of f.e.: Write->Write_<Default-Method-Suffix>_Low_Priority', false);
Generate_Normal_Priority_Methods := getOptionB('npm','Normal-Priority-Methods','generation of f.e.: Write->Write_<Default-Method-Suffix>_Normal_Priority', false);
Generate_High_Priority_Methods := getOptionB('hpm','High-Priority-Methods','generation of f.e.: Write->Write_<Default-Method-Suffix>_HIGH_Priority', false);
Generate_ASAP_Priority_Methods := getOptionB('apm','ASAP-Priority-Methods','generation of f.e.: Write->Write_<Default-Method-Suffix>_ASAP_Priority', false);
InputFileName := getFinalS('filename','input file for compilation','');
if getOptionB('h','help','print help string - this list',false) then
begin
Writeln();
Writeln(getHelpString);
Halt();
end;
OnNewWorkMethodFileName := getOptionS('onwf','On-New-Work-Method-FileName','Name of main worker method file - default <InputFileName>+_onNewWork.inc',ChangeFileExt(InputFileName,'_onNewWork.inc'));
MethodDefinitionFile := getOptionS('mdf','Method-Definition-File','when use .inc file for generated interface, this is filename for it, default <InputFileName>+_<Method-Flag-Name>_def',ChangeFileExt(InputFileName,'_'+MethodFlagName+'_def.inc'));
MethodImplementationFile := getOptionS('mif','Method-Implementation-File','when use .inc file for implementation, this is filename for it, default <InputFileName>+_<Method-Flag-Name>_impl',ChangeFileExt(InputFileName,'_'+MethodFlagName+'_impl.inc'));
end;
procedure WriteParameters;
var tp : string;
begin
Writeln('Input file : ' + InputFileName);
Writeln('Type definition file : ' + ifthen(FileExists(Type_Definition_File),Type_Definition_File,''));
Writeln('Method definition .inc file : ' + MethodDefinitionFile);
Writeln('Method implementation .inc file : ' + MethodImplementationFile);
Writeln;
Writeln('Method selection flag : ' + MethodFlagName);
Writeln('Name of class : ' + Class_Name);
Writeln('Name of on_new_work_method : ' + OnNewWorkMethodName);
Writeln('Default method suffix : ' + Default_Method_Suffix);
Writeln;
Writeln(' Main Method generation : ' + ifThen(Generate_Main_Methods,' YES ','no'));
Writeln(' Unique Method generation : ' + ifThen(GenerateUniqueMethods,' YES ','no'));
tp := 'LAST';
case Default_Priority of
teFirst : tp := 'ASAP';
teHighPriority : tp := 'HIGH';
teNormalPriority : tp := 'NORMAL';
teLowPriority : tp := 'LOW';
teLast : tp := 'LAST';
end;
Writeln(' Default task priority : ' + tp);
Writeln(' generate ASAP priority : ' + ifThen(Generate_ASAP_Priority_Methods,' YES ','no'));
Writeln(' Generate High priority : ' + ifThen(Generate_High_Priority_Methods,' YES ','no'));
Writeln(' Generate Normal priority : ' + ifThen(Generate_Normal_Priority_Methods,' YES ','no'));
Writeln(' Generate Low priority : ' + ifThen(Generate_Low_Priority_Methods,' YES ','no'));
Writeln(' Generate Last priority : ' + ifThen(Generate_Last_Priority_Methods,' YES ','no'));
end;
var input : string;
output : string;
inter : string;
impl : string;
procedure LoadDataFromSource(const filename : string);
var input : string;
procedure FindIncludes(const str : string);
var
RE: TRegExpr;
fn : string;
newfn : string;
begin
RE := TRegExpr.Create;
try
RE.Expression := '{\$(I|INCLUDE)[ ]+([\w\.\\]+)}';
RE.ModifierG := false;
RE.ModifierI := true;
// Writeln('Running RE on string('+IntToStr(length(str))+')');
if RE.Exec(str) then
begin
repeat
fn := RE.Match[2];
newfn := ExpandFileName(IncludeTrailingPathDelimiter(ExtractFilePath(filename)) + fn);
// Writeln('Found $I : ' + fn + ' which should be ' + newfn);
LoadDataFromSource(newfn);
until not RE.ExecNext;
end;
finally
RE.Free;
end;
end;
procedure FindClassName(const str : string);
var
RE: TRegExpr;
cn : string;
begin
if Class_Name <> '' then Exit;
RE := TRegExpr.Create;
try
RE.Expression := '([a-z_1-90]+)[ ]*=[ ]*class\([a-z_1-90]+\)[ ]+\{class_'+MethodFlagName+'\}';
RE.ModifierG := false;
RE.ModifierI := true;
// Writeln('Running RE on string('+IntToStr(length(str))+')');
if RE.Exec(str) then
begin
repeat
cn := RE.Match[1];
Writeln('Found class name : ' + cn);
Class_Name := cn + '.';
until not RE.ExecNext;
end;
finally
RE.Free;
end;
end;
procedure FindMethods(const str : string);
var
RE, REp: TRegExpr;
fn, params, param : string;
mn : string;
method : string;
par : tParam;
meth : tMethod;
procedure AddParam(par : tParam);
begin
setLength(meth.Params,length(meth.Params)+1);
meth.Params[high(meth.Params)] := par;
end;
procedure AddMethod(meth : tMethod);
begin
setLength(methods,length(methods)+1);
methods[high(methods)] := meth;
end;
begin
RE := TRegExpr.Create;
RE.Expression := 'procedure ([a-z_1-90]*)[ ]*(\((.*)\)){0,1}[ ]*;[ ]*\{gen_MT\}';
REp := TRegExpr.Create;
REp.Expression:='((const|var)[ ]){0,1}[ ]*([a-z_]+)[ ]*:[ ]*([a-z_]+);';
try
RE.ModifierG := false;
RE.ModifierI := true;
REp.ModifierG := false;
REp.ModifierI := true;
if RE.Exec(str) then
begin
repeat
method := '';
SetLength(meth.Params,0);
mn := RE.Match[1];
params := RE.Match[3];
params := ReplaceStr(params,#13,'');
params := ReplaceStr(params,#10,'');
params := ReplaceStr(params,' ',' ');
if params <> '' then params += ';';
meth.Name:=mn;
method += mn + '(';
if REp.Exec(params) then
begin
repeat
method += REp.Match[4] + ',';
par.Name:=REp.Match[3];
par.Typ:= REp.Match[4];
AddParam(par);
until not REp.ExecNext;
method := copy(method,1,length(method)-1);
end;
method += ');';
writeln('Found method : '+method);
AddMethod(Meth);
until not RE.ExecNext;
end;
finally
REp.Free;
RE.Free;
end;
end;
begin
Writeln('Loading ' + filename);
input := getFile(filename);
if input = '' then
begin
Writeln('Input file ' + filename + ' not found or empty, halt..');
Halt;
end;
FindClassName(input);
FindMethods(input);
FindIncludes(input);
end;
procedure Generate_On_New_Work();
var i : integer;
meth : tMethod;
p : integer;
par : tParam;
par_str : string;
res : string;
fn : string;
typ : string;
begin
res := 'procedure ' + Class_Name + OnNewWorkMethodName + '(const method_name: string; const task: tMultiTaskItem);' + LineEnding;
res += 'begin' + LineEnding;
res += ' case method_name of' + LineEnding + LineEnding;
for i := low(methods) to high(methods) do
begin
meth := methods[i];
par_str := '';
if length(meth.Params) > 0 then
begin
for p := low(meth.Params) to high(meth.Params) do
begin
par := meth.Params[p];
typ := Type_Definition.Values[par.typ];
if typ <> '' then
begin
par_str += ' '+par.typ+'(task.'+typ+'['+IntToStr(p+1)+']), ';
end else
begin
case lowercase(par.typ) of
{
property I[const id: integer]: integer read getInteger;
property int[const id: integer]: pointer read getinterface;
property ParBoolean[const id: integer]: boolean read getboolean;
property ParChar[const id: integer]: char read getchar;
property ParExtended[const id: integer]: extended read getExtended;
property S[const id: integer]: string read getString;
property ParPChar[const id: integer]: PChar read getPChar;
property O[const id: integer]: TObject read gettObject;
property ParClass[const id: integer]: tClass read gettClass;
property ParAnsiString[const id: integer]: ansistring read getAnsiString;
property ParCurrency[const id: integer]: currency read getCurrency;
property ParVariant[const id: integer]: variant read getVariant;
property I64[const id: integer]: int64 read getInt64;
}
'string' : par_str += ' task.S['+IntToStr(p+1)+'], ';
'integer',
'byte',
'word' : par_str += ' task.I['+IntToStr(p+1)+'], ';
else
if lowercase(copy(par.typ,1,1)) = 'i' then
par_str += ' '+par.typ+'(task.int['+IntToStr(p+1)+']), ' else
par_str += ' '+par.typ+'(task.O['+IntToStr(p+1)+']), ';
end;
end;
end;
par_str := copy(par_str,1,length(par_str)-2);
end;
res += ' ''' + lowercase(meth.Name) + ''' : ' + meth.Name + '(' + par_str + ');' + LineEnding;
res += LineEnding;
end;
res += ' else' + LineEnding;
res += ' Log(''!!!ERROR!!! Method "'' + method_name + ''" is not defined in On_New_Work method. !!!ERROR!!!'' );' + LineEnding;
res += ' end;' + LineEnding;
res += 'end;' + LineEnding;
fn := ExpandFileName(IncludeTrailingPathDelimiter(ExtractFilePath(InputFileName)) + OnNewWorkMethodFileName);
Writeln('Saving ' + fn);
SetFile(fn,res);
end;
procedure Generate_Method_Definition();
var i : integer;
meth : tMethod;
p : integer;
par : tParam;
par_str : string;
res : string;
fn : string;
begin
res := '';
for i := low(methods) to high(methods) do
begin
meth := methods[i];
par_str := '';
if length(meth.Params) > 0 then
begin
for p := low(meth.Params) to high(meth.Params) do
begin
par := meth.Params[p];
par_str += ' const ' + par.Name + ' : ' + par.Typ + '; ';
end;
par_str := copy(par_str,1,length(par_str)-2);
end;
res += ' procedure ' + meth.Name + Default_Method_Suffix + '(' + par_str + ');' + LineEnding;
if Generate_Last_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Last(' + par_str + ');' + LineEnding;
if Generate_Low_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Low(' + par_str + ');' + LineEnding;
if Generate_Normal_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Normal(' + par_str + ');' + LineEnding;
if Generate_High_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_High(' + par_str + ');' + LineEnding;
if Generate_ASAP_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_ASAP(' + par_str + ');' + LineEnding;
if GenerateUniqueMethods then
begin
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Unique(' + par_str + ');' + LineEnding;
if Generate_Last_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Unique_Last(' + par_str + ');' + LineEnding;
if Generate_Low_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Unique_Low(' + par_str + ');' + LineEnding;
if Generate_Normal_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Unique_Normal(' + par_str + ');' + LineEnding;
if Generate_High_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Unique_High(' + par_str + ');' + LineEnding;
if Generate_ASAP_Priority_Methods then
res += ' procedure ' + meth.Name + Default_Method_Suffix + '_Unique_ASAP(' + par_str + ');' + LineEnding;
end;
res += LineEnding;
end;
res += LineEnding;
fn := ExpandFileName(IncludeTrailingPathDelimiter(ExtractFilePath(InputFileName)) + MethodDefinitionFile);
Writeln('Saving ' + fn);
SetFile(fn,res);
end;
procedure Generate_Method_Implementation();
var i : integer;
meth : tMethod;
p : integer;
par : tParam;
par_str, par_str2 : string;
res : string;
fn : string;
procedure AddMethods(const unique : boolean);
begin
res += ' procedure ' + Class_Name + meth.Name + Default_Method_Suffix + ifThen(unique,'_Unique','') + '(' + par_str2 + ');' + LineEnding;
res += ' begin' + LineEnding;
res += ' ' + MultiTaskerObjectname+'.Enqueue(tTaskMethod(@' + meth.Name + '), [' + par_str + '], ['+GetEnumName(TypeInfo(tMultitaskEnQueueFlag),Ord(Default_Priority))+''+ifThen(unique,',teUnique','')+']);' + LineEnding;
res += ' end;' + LineEnding;
if Generate_Last_Priority_Methods then
begin
res += ' procedure ' + Class_Name + meth.Name + Default_Method_Suffix + ifThen(unique,'_Unique','') + '_Last(' + par_str2 + ');' + LineEnding;
res += ' begin' + LineEnding;
res += ' ' + MultiTaskerObjectname+'.Enqueue(tTaskMethod(@' + meth.Name + '), [' + par_str + '], [teLast'+ifThen(unique,',teUnique','')+']);' + LineEnding;
res += ' end;' + LineEnding;
end;
if Generate_Low_Priority_Methods then
begin
res += ' procedure ' + Class_Name + meth.Name + Default_Method_Suffix + ifThen(unique,'_Unique','') + '_Low(' + par_str2 + ');' + LineEnding;
res += ' begin' + LineEnding;
res += ' ' + MultiTaskerObjectname+'.Enqueue(tTaskMethod(@' + meth.Name + '), [' + par_str + '], [teLowPriority'+ifThen(unique,',teUnique','')+']);' + LineEnding;
res += ' end;' + LineEnding;
end;
if Generate_Normal_Priority_Methods then
begin
res += ' procedure ' + Class_Name + meth.Name + Default_Method_Suffix + ifThen(unique,'_Unique','') + '_Normal(' + par_str2 + ');' + LineEnding;
res += ' begin' + LineEnding;
res += ' ' + MultiTaskerObjectname+'.Enqueue(tTaskMethod(@' + meth.Name + '), [' + par_str + '], [teNormalPriority'+ifThen(unique,',teUnique','')+']);' + LineEnding;
res += ' end;' + LineEnding;
end;
if Generate_High_Priority_Methods then
begin
res += ' procedure ' + Class_Name + meth.Name + Default_Method_Suffix + ifThen(unique,'_Unique','') + '_High(' + par_str2 + ');' + LineEnding;
res += ' begin' + LineEnding;
res += ' ' + MultiTaskerObjectname+'.Enqueue(tTaskMethod(@' + meth.Name + '), [' + par_str + '], [teHighPriority'+ifThen(unique,',teUnique','')+']);' + LineEnding;
res += ' end;' + LineEnding;
end;
if Generate_ASAP_Priority_Methods then
begin
res += ' procedure ' + Class_Name + meth.Name + Default_Method_Suffix + ifThen(unique,'_Unique','') + '_ASAP(' + par_str2 + ');' + LineEnding;
res += ' begin' + LineEnding;
res += ' ' + MultiTaskerObjectname+'.Enqueue(tTaskMethod(@' + meth.Name + '), [' + par_str + '], [teFirst'+ifThen(unique,',teUnique','')+']);' + LineEnding;
res += ' end;' + LineEnding;
end;
end;
begin
res := '';
for i := low(methods) to high(methods) do
begin
meth := methods[i];
par_str := '';
par_str2 := '';
if length(meth.Params) > 0 then
begin
for p := low(meth.Params) to high(meth.Params) do
begin
par := meth.Params[p];
par_str += ' ' + par.Name + ',';
par_str2 += ' const ' + par.Name + ' : ' + par.Typ + ';';
end;
par_str := copy(par_str,1,length(par_str)-1);
par_str2 := copy(par_str2,1,length(par_str2)-1);
end;
AddMethods(false);
if GenerateUniqueMethods then
Addmethods(true);
res += LineEnding;
res += LineEnding;
end;
res += LineEnding;
fn := ExpandFileName(IncludeTrailingPathDelimiter(ExtractFilePath(InputFileName)) + MethodImplementationFile);
Writeln('Saving ' + fn);
SetFile(fn,res);
end;
begin
Writeln('MultiTask_PreCompiler - v0.1 - build on ' + {$I %DATE%} + ' ' + {$I %TIME%});
InitParameters();
WriteParameters();
output := ''; inter := ''; impl := '';
LoadDataFromSource(InputFileName);
Writeln('Data loaded..');
Writeln('Found ' + IntToStr(length(methods)) + ' methods');
if length(methods) = 0 then
begin
Writeln('Halt');
Halt;
end;
Generate_On_New_Work();
Generate_Method_Definition();
Generate_Method_Implementation();
Writeln('All work done ok');
// Readln();
end.
|
{ Date Created: 5/22/00 11:17:33 AM }
unit InfoPULLLISTLOOKUPTable;
interface
uses
Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf;
type
TInfoPULLLISTLOOKUPRecord = record
PItemNumber: String[1];
PSI: String[2];
PDescription: String[20];
PAbbreviation: String[12];
End;
TInfoPULLLISTLOOKUPBuffer = class(TDataBuf)
protected
function PtrIndex(Index:integer):Pointer;override;
public
Data: TInfoPULLLISTLOOKUPRecord
end;
TEIInfoPULLLISTLOOKUP = (InfoPULLLISTLOOKUPPrimaryKey);
TInfoPULLLISTLOOKUPTable = class( TDBISAMTableAU )
private
FDFItemNumber: TStringField;
FDFSI: TStringField;
FDFDescription: TStringField;
FDFAbbreviation: TStringField;
procedure SetPItemNumber(const Value: String);
function GetPItemNumber:String;
procedure SetPSI(const Value: String);
function GetPSI:String;
procedure SetPDescription(const Value: String);
function GetPDescription:String;
procedure SetPAbbreviation(const Value: String);
function GetPAbbreviation:String;
procedure SetEnumIndex(Value: TEIInfoPULLLISTLOOKUP);
function GetEnumIndex: TEIInfoPULLLISTLOOKUP;
protected
procedure CreateFields; virtual;
procedure SetActive(Value: Boolean); override;
procedure LoadFieldDefs(AStringList:TStringList);override;
procedure LoadIndexDefs(AStringList:TStringList);override;
public
function GetDataBuffer:TInfoPULLLISTLOOKUPRecord;
procedure StoreDataBuffer(ABuffer:TInfoPULLLISTLOOKUPRecord);
property DFItemNumber: TStringField read FDFItemNumber;
property DFSI: TStringField read FDFSI;
property DFDescription: TStringField read FDFDescription;
property DFAbbreviation: TStringField read FDFAbbreviation;
property PItemNumber: String read GetPItemNumber write SetPItemNumber;
property PSI: String read GetPSI write SetPSI;
property PDescription: String read GetPDescription write SetPDescription;
property PAbbreviation: String read GetPAbbreviation write SetPAbbreviation;
procedure Validate; virtual;
published
property Active write SetActive;
property EnumIndex: TEIInfoPULLLISTLOOKUP read GetEnumIndex write SetEnumIndex;
end; { TInfoPULLLISTLOOKUPTable }
procedure Register;
implementation
procedure TInfoPULLLISTLOOKUPTable.CreateFields;
begin
FDFItemNumber := CreateField( 'ItemNumber' ) as TStringField;
FDFSI := CreateField( 'SI' ) as TStringField;
FDFDescription := CreateField( 'Description' ) as TStringField;
FDFAbbreviation := CreateField( 'Abbreviation' ) as TStringField;
end; { TInfoPULLLISTLOOKUPTable.CreateFields }
procedure TInfoPULLLISTLOOKUPTable.SetActive(Value: Boolean);
begin
inherited SetActive(Value);
if Active then
CreateFields;
end; { TInfoPULLLISTLOOKUPTable.SetActive }
procedure TInfoPULLLISTLOOKUPTable.Validate;
begin
{ Enter Validation Code Here }
end; { TInfoPULLLISTLOOKUPTable.Validate }
procedure TInfoPULLLISTLOOKUPTable.SetPItemNumber(const Value: String);
begin
DFItemNumber.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPItemNumber:String;
begin
result := DFItemNumber.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.SetPSI(const Value: String);
begin
DFSI.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPSI:String;
begin
result := DFSI.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.SetPDescription(const Value: String);
begin
DFDescription.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPDescription:String;
begin
result := DFDescription.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.SetPAbbreviation(const Value: String);
begin
DFAbbreviation.Value := Value;
end;
function TInfoPULLLISTLOOKUPTable.GetPAbbreviation:String;
begin
result := DFAbbreviation.Value;
end;
procedure TInfoPULLLISTLOOKUPTable.LoadFieldDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('ItemNumber, String, 1, N');
Add('SI, String, 2, N');
Add('Description, String, 20, N');
Add('Abbreviation, String, 12, N');
end;
end;
procedure TInfoPULLLISTLOOKUPTable.LoadIndexDefs(AStringList: TStringList);
begin
inherited;
with AstringList do
begin
Add('PrimaryKey, ItemNumber;SI, Y, Y, N, N');
end;
end;
procedure TInfoPULLLISTLOOKUPTable.SetEnumIndex(Value: TEIInfoPULLLISTLOOKUP);
begin
case Value of
InfoPULLLISTLOOKUPPrimaryKey : IndexName := '';
end;
end;
function TInfoPULLLISTLOOKUPTable.GetDataBuffer:TInfoPULLLISTLOOKUPRecord;
var buf: TInfoPULLLISTLOOKUPRecord;
begin
fillchar(buf, sizeof(buf), 0);
buf.PItemNumber := DFItemNumber.Value;
buf.PSI := DFSI.Value;
buf.PDescription := DFDescription.Value;
buf.PAbbreviation := DFAbbreviation.Value;
result := buf;
end;
procedure TInfoPULLLISTLOOKUPTable.StoreDataBuffer(ABuffer:TInfoPULLLISTLOOKUPRecord);
begin
DFItemNumber.Value := ABuffer.PItemNumber;
DFSI.Value := ABuffer.PSI;
DFDescription.Value := ABuffer.PDescription;
DFAbbreviation.Value := ABuffer.PAbbreviation;
end;
function TInfoPULLLISTLOOKUPTable.GetEnumIndex: TEIInfoPULLLISTLOOKUP;
var iname : string;
begin
iname := uppercase(indexname);
if iname = '' then result := InfoPULLLISTLOOKUPPrimaryKey;
end;
(********************************************)
(************ Register Component ************)
(********************************************)
procedure Register;
begin
RegisterComponents( 'Info Tables', [ TInfoPULLLISTLOOKUPTable, TInfoPULLLISTLOOKUPBuffer ] );
end; { Register }
function TInfoPULLLISTLOOKUPBuffer.PtrIndex(index:integer):Pointer;
begin
result := nil;
case index of
1 : result := @Data.PItemNumber;
2 : result := @Data.PSI;
3 : result := @Data.PDescription;
4 : result := @Data.PAbbreviation;
end;
end;
end. { InfoPULLLISTLOOKUPTable }
|
unit uvMain;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, ComCtrls;
type
TFormMain = class(TForm)
StatusBar1: TStatusBar;
pnlTool: TPanel;
btnAdd: TBitBtn;
scrlTiles: TScrollBox;
pnlTiles: TPanel;
lblTilesCount: TLabel;
edTileName: TEdit;
btnSave: TBitBtn;
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
fIsTilesRepositionEnabled : boolean;
public
procedure tailsReposition;
property IsTilesRepositionEnabled : boolean read fIsTilesRepositionEnabled write fIsTilesRepositionEnabled;
end;
var
FormMain: TFormMain;
implementation
uses uvITileView;
{$R *.dfm}
const
FrameTileMinWidth = 200;
FrameTileHeight = 70;
countColumn = 3;
procedure TFormMain.FormCreate(Sender: TObject);
begin
scrlTiles.Constraints.MinWidth := 3 * FrameTileMinWidth + 20;
scrlTiles.Constraints.MinHeight := FrameTileHeight + 1;
fIsTilesRepositionEnabled := true;
end;
procedure TFormMain.FormResize(Sender: TObject);
begin
pnlTiles.Hide;
tailsReposition;
pnlTiles.Show;
end;
procedure TFormMain.tailsReposition;
var
i, maxNum, curPosX, curPosY, tileWidth, tileHeight : integer;
curTile : ITileView;
begin
if fIsTilesRepositionEnabled then
begin
maxNum := pnlTiles.ControlCount - 1;
if maxNum >= 0 then
begin
//pnlTiles.Hide;
curTile := (pnlTiles.Controls[0]) as ITileView;
tileWidth := pnlTiles.ClientWidth div countColumn;
tileHeight := curTile.getHeight;
curPosX := 0;
curPosY := 0;
for i := 0 to maxNum do
begin
curTile := (pnlTiles.Controls[i]) as ITileView;
(ITileView(curTile)).setPosition(curPosX * tileWidth, curPosY * tileHeight, tileWidth);
inc(curPosX);
if curPosX = countColumn then
begin
curPosX := 0;
inc(curPosY);
end;
end;
pnlTiles.SetBounds(0, 0, scrlTiles.ClientWidth, (curPosY+1) * tileHeight);
//pnlTiles.Show;
end;
end;
end;
end.
|
{*_* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Author: Arno Garrels <arno.garrels@gmx.de>
Description: Delphi 2009 and 2010 do not update old projects correctly.
This IDE plugin reads OutputDir, UnitOutputDir, SearchPath and
Conditionals from the .dof file on project updates from .dpr if
no .dproj file already exists and sets these in new project's
Base configuration.
Creation: June 2011
Version: 1.00
EMail: francois.piette@overbyte.be http://www.overbyte.be
Support: Use the mailing list twsocket@elists.org
Follow "support" link at http://www.overbyte.be for subscription.
Legal issues: Copyright (C) 2011 by Arno Garrels
Berlin, Germany <arno.garrels@gmx.de>
This software is provided 'as-is', without any express or
implied warranty. In no event will the author be held liable
for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it
and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented,
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
4. You must register this software by sending a picture postcard
to François PIETTE. Use a nice stamp and mention your name,
street address, EMail address and any comment you like to say.
History:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
unit OverbyteIcsDprUpdFix;
{.$DEFINE DEBUGLOG}
{$I OverbyteIcsDefs.inc}
{$IFDEF COMPILER12_UP}
{$IFNDEF COMPILER15_UP}
{$DEFINE DPRFIX2009}
{$ENDIF}
{$IFDEF COMPILER16_UP}
{$DEFINE DPRFIXXE2}
{$ENDIF}
{$ENDIF}
interface
uses
SysUtils, Classes, Forms, IniFiles, TypInfo,
{$IFDEF DPRFIXXE2}
PlatformAPI,
CommonOptionStrs,
{$ENDIF}
ToolsApi;
type
TIdeNotifier = class(TNotifierObject, IOTAIDENotifier)
private
FLastDpr : string;
protected
procedure AfterCompile(Succeeded: Boolean);
procedure BeforeCompile(const Project: IOTAProject; var Cancel: Boolean);
procedure FileNotification(NotifyCode: TOTAFileNotification;
const FileName: string; var Cancel: Boolean);
end;
procedure Register;
implementation
uses
DCCStrs;
const
sDofSectDir = 'Directories';
sDofSectCustom = 'IcsCustom';
var
IDENotifierIndex : Integer = -1;
GMessageService: IOTAMessageServices = nil;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure DebugLog(const Msg: string);
begin
GMessageService.AddTitleMessage(Msg);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure Register;
var
Services : IOTAServices;
begin
{$IF DEFINED(DPRFIX2009) or DEFINED(DPRFIXXE2)}
Services := BorlandIDEServices as IOTAServices;
GMessageService := (BorlandIDEServices as IOTAMessageServices);
if (IDENotifierIndex = -1) then begin
IDENotifierIndex := Services.AddNotifier(TIdeNotifier.Create);
{$IFDEF DEBUGLOG}
DebugLog('OverbyteIcsDprUpdFix Installed NotifierIndex: #' + IntToStr(IDENotifierIndex));
{$ENDIF}
end;
{$IFEND}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
function IsProjectFile(const FileName: string;
var Project : IOTAProject): Boolean;
var
Module : IOTAModule;
ProjectGroup : IOTAProjectGroup;
begin
Module := (BorlandIDEServices as IOTAModuleServices).FindModule(FileName);
Result := Supports(Module, IOTAProject, Project) and
not Supports(Module, IOTAProjectGroup, ProjectGroup);
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIdeNotifier.AfterCompile(Succeeded: Boolean);
begin
{$IFDEF DEBUGLOG}
DebugLog('After Compile');
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIdeNotifier.BeforeCompile(const Project: IOTAProject;
var Cancel: Boolean);
begin
{$IFDEF DEBUGLOG}
DebugLog('Before Compile');
{$ENDIF}
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure TIdeNotifier.FileNotification(NotifyCode: TOTAFileNotification;
const FileName: string; var Cancel: Boolean);
var
Project : IOTAProject;
OptionsConfigurations : IOTAProjectOptionsConfigurations;
BaseConfig : IOTABuildConfiguration;
IniValues : TStringList;
Values : TStringList;
Ini : TIniFile;
I : Integer;
{$IFDEF DPRFIX2009}
RS : array of string;
S1 : string;
S2 : string;
{$ENDIF}
Dirty : Boolean;
DofFile : string;
{$IFDEF DPRFIXXE2}
RS : array of string;
ProjectPlatforms : IOTAProjectPlatforms;
DebugConfig : IOTABuildConfiguration;
bFlag : Boolean;
{$ENDIF}
begin
try
{$IFDEF DEBUGLOG}
DebugLog(Format('%s: %s',
[GetEnumName(TypeInfo(TOTAFileNotification), Ord(NotifyCode)), FileName]));
{$ENDIF}
case NotifyCode of
ofnFileOpening :
if ExtractFileExt(FileName) = '.dpr' then
begin
FLastDpr := ChangeFileExt(FileName, '.dproj');
if FileExists(FLastDpr) then
FLastDpr := '';
end;
ofnFileOpened :
if FLastDpr = FileName then
begin
FLastDpr := '';
DofFile := ChangeFileExt(FileName, '.dof');
Dirty := False;
Values := nil;
IniValues := nil;
Ini := nil;
if FileExists(DofFile) and IsProjectFile(FileName, Project) and
Supports(Project.ProjectOptions,
IOTAProjectOptionsConfigurations,
OptionsConfigurations) then
try
BaseConfig := OptionsConfigurations.BaseConfiguration;
if BaseConfig = nil then // Should never happen on UPD from .dpr
Exit;
{$IFDEF DPRFIX2009} // And D2010
Ini := TIniFile.Create(DofFile);
IniValues := TStringList.Create;
IniValues.Delimiter := ';';
IniValues.StrictDelimiter := True;
Values := TStringList.Create;
//-----------------------------------
IniValues.DelimitedText := Ini.ReadString(sDofSectDir, 'SearchPath', '');
if IniValues.Count > 0 then
begin
BaseConfig.GetValues(sUnitSearchPath, Values, False);
for I := IniValues.Count - 1 downto 0 do
begin
if Values.IndexOf(Trim(IniValues[I])) >= 0 then
IniValues.Delete(I);
end;
if IniValues.Count > 0 then
begin
SetLength(RS, IniValues.Count);
for I := 0 to IniValues.Count - 1 do
RS[I] := Trim(IniValues[I]);
BaseConfig.InsertValues(sUnitSearchPath, RS);
Dirty := True;
DebugLog('ICS UpdateFix from .dof: Base SearchPath');
end;
end;
//-----------------------------------
IniValues.DelimitedText := Ini.ReadString(sDofSectDir, 'Conditionals', '');
if IniValues.Count > 0 then
begin
Values.Clear;
BaseConfig.GetValues(sDefine, Values, False);
for I := IniValues.Count - 1 downto 0 do
begin
if Values.IndexOf(Trim(IniValues[I])) >= 0 then
IniValues.Delete(I);
end;
if IniValues.Count > 0 then
begin
SetLength(RS, IniValues.Count);
for I := 0 to IniValues.Count - 1 do
RS[I] := Trim(IniValues[I]);
BaseConfig.InsertValues(sDefine, RS);
Dirty := True;
DebugLog('ICS UpdateFix from .dof: Base Conditionals');
end;
end;
//-----------------------------------
S2 := Trim(Ini.ReadString(sDofSectDir, 'OutputDir', ''));
if S2 <> '' then
begin
S1 := BaseConfig.GetValue(sExeOutput, False);
if S1 <> S2 then
begin
BaseConfig.Value[sExeOutput] := S2;
Dirty := True;
DebugLog('ICS UpdateFix from .dof: Base OutputDir');
end;
end;
//-----------------------------------
S2 := Trim(Ini.ReadString(sDofSectDir, 'UnitOutputDir', ''));
if S2 <> '' then
begin
S1 := BaseConfig.GetValue(sDcuOutput, False);
if S1 <> S2 then
begin
BaseConfig.Value[sDcuOutput] := S2;
Dirty := True;
DebugLog('ICS UpdateFix from .dof: Base UnitOutputDir');
end;
end;
//-----------------------------------
{$ENDIF}
{$IFDEF DPRFIXXE2}
{ Read values from our custom ini-section added to .dof files }
{ This is just the bare minimum to update the ICS samples }
{ from .dpr / .dof with the platforms and framework type we }
{ want reliable. }
if not Assigned(Ini) then
Ini := TIniFile.Create(DofFile);
if Supports(Project, IOTAProjectPlatforms, ProjectPlatforms) and
Ini.SectionExists(sDofSectCustom) then // It's an ICS demo .dpr
begin
if (UpperCase(Trim(Ini.ReadString(sDofSectCustom, 'FrameworkType', ''))) = sFrameworkTypeVCL) and
(Project.FrameworkType <> sFrameworkTypeVCL) then
begin
Project.ProjectOptions.Values['FrameworkType'] := sFrameworkTypeVCL;
Dirty := True;
end;
bFlag := Ini.ReadBool(sDofSectCustom, 'Win32Supported', TRUE);
if ProjectPlatforms.Supported[cWin32Platform] <> bFlag then
begin
ProjectPlatforms.Supported[cWin32Platform] := bFlag;
Dirty := True;
end;
bFlag := Ini.ReadBool(sDofSectCustom, 'Win32Enabled', TRUE);
if ProjectPlatforms.Enabled[cWin32Platform] <> bFlag then
begin
if bFlag and not ProjectPlatforms.Supported[cWin32Platform] then
ProjectPlatforms.Supported[cWin32Platform] := TRUE;
ProjectPlatforms.Enabled[cWin32Platform] := bFlag;
Dirty := True;
end;
bFlag := Ini.ReadBool(sDofSectCustom, 'Win64Supported', TRUE);
if ProjectPlatforms.Supported[cWin64Platform] <> bFlag then
begin
ProjectPlatforms.Supported[cWin64Platform] := bFlag;
Dirty := True;
end;
bFlag := Ini.ReadBool(sDofSectCustom, 'Win64Enabled', FALSE);
if ProjectPlatforms.Enabled[cWin64Platform] <> bFlag then
begin
if bFlag and not ProjectPlatforms.Supported[cWin64Platform] then
ProjectPlatforms.Supported[cWin64Platform] := TRUE;
ProjectPlatforms.Enabled[cWin64Platform] := bFlag;
if bFlag then
begin
{ Enable remote debug symbols for Win64 }
for I := 0 to OptionsConfigurations.ConfigurationCount -1 do
begin
if OptionsConfigurations.Configurations[I].Name = 'Debug' then
begin
DebugConfig :=
OptionsConfigurations.Configurations[I].PlatformConfiguration[cWin64Platform];
if Assigned(DebugConfig) then
DebugConfig.Value[sRemoteDebug] := 'true';
Break;
end;
end;
end;
Dirty := True;
end;
bFlag := Ini.ReadBool(sDofSectCustom, 'OSX32Supported', FALSE);
if ProjectPlatforms.Supported[cOSX32Platform] <> bFlag then
begin
ProjectPlatforms.Supported[cOSX32Platform] := bFlag;
Dirty := True;
end;
bFlag := Ini.ReadBool(sDofSectCustom, 'OSX32Enabled', FALSE);
if ProjectPlatforms.Enabled[cOSX32Platform] <> bFlag then
begin
if bFlag and not ProjectPlatforms.Supported[cOSX32Platform] then
ProjectPlatforms.Supported[cOSX32Platform] := TRUE;
ProjectPlatforms.Enabled[cOSX32Platform] := bFlag;
Dirty := True;
end;
if Dirty then
DebugLog('ICS project updated from custom .dof section');
end;
{ No internal manifest in 32-bit }
for I := 0 to OptionsConfigurations.ConfigurationCount -1 do
begin
DebugConfig :=
OptionsConfigurations.Configurations[I].PlatformConfiguration[cWin32Platform];
if Assigned(DebugConfig) then
begin
if LowerCase(DebugConfig.Value[sManifest_File]) <> 'none' then
begin
DebugConfig.Value[sManifest_File] := 'None';
Dirty := True;
end;
end;
end;
{ No version info in 32-bit }
DebugConfig := BaseConfig.PlatformConfiguration[cWin32Platform];
if Assigned(DebugConfig) then
begin
if LowerCase(DebugConfig.Value[sVerInfo_IncludeVerInfo]) <> 'false' then
begin
DebugConfig.Value[sVerInfo_IncludeVerInfo] := 'false';
Dirty := True;
end;
end;
{ Fix namespace prefixes }
if not Assigned(IniValues) then
IniValues := TStringList.Create;
IniValues.Delimiter := ';';
IniValues.StrictDelimiter := True;
if not Assigned(Values) then
Values := TStringList.Create;
{ Check if Winapi is set in Base config, if not add it }
IniValues.DelimitedText := 'Winapi;System.Win';
BaseConfig.GetValues(sNamespace, Values, False);
for I := IniValues.Count - 1 downto 0 do
begin
if Values.IndexOf(IniValues[I]) >= 0 then
IniValues.Delete(I);
end;
if IniValues.Count > 0 then
begin
SetLength(RS, IniValues.Count);
for I := 0 to IniValues.Count - 1 do
RS[I] := IniValues[I];
BaseConfig.InsertValues(sNamespace, RS);
Dirty := True;
end;
{$ENDIF}
if Dirty then
Project.Save(False, True);
finally
Ini.Free;
Values.Free;
IniValues.Free;
end;
end;
end;
except
FLastDpr := '';
Application.HandleException(Self);
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
procedure RemoveIDENotifier;
var
Services : IOTAServices;
begin
if IDENotifierIndex > -1 then
begin
Services := BorlandIDEServices as IOTAServices;
if Services <> nil then
Services.RemoveNotifier(IDENotifierIndex);
IDENotifierIndex := -1;
end;
end;
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *}
initialization
finalization
RemoveIDENotifier;
end.
|
unit languajecontrol;
interface
implementation
uses
Windows, Consts;
// Assign new value to a resource string
procedure HookResourceString(ResStringRec: pResStringRec; NewStr: pChar) ;
var
OldProtect: DWORD;
begin
VirtualProtect(ResStringRec, SizeOf(ResStringRec^), PAGE_EXECUTE_READWRITE, @OldProtect) ;
ResStringRec^.Identifier := Integer(NewStr) ;
VirtualProtect(ResStringRec, SizeOf(ResStringRec^), OldProtect, @OldProtect) ;
end;
initialization
HookResourceString(@SCannotOpenClipboard, 'No se puede abrir porta-papeles') ;
HookResourceString(@SMsgDlgWarning, 'Atencion') ;
HookResourceString(@SMsgDlgError, 'Error') ;
HookResourceString(@SMsgDlgInformation, 'Informacion') ;
HookResourceString(@SMsgDlgConfirm, 'Confirmar') ;
HookResourceString(@SMsgDlgYes, 'Si') ;
HookResourceString(@SMsgDlgNo, 'No') ;
HookResourceString(@SMsgDlgOK, 'OK') ;
HookResourceString(@SMsgDlgCancel, 'Anula') ;
HookResourceString(@SMsgDlgHelp, 'Ayuda') ;
HookResourceString(@SMsgDlgHelpNone, 'No hay ayuda') ;
HookResourceString(@SMsgDlgHelpHelp, 'Ayuda') ;
HookResourceString(@SMsgDlgAbort, 'Abortar') ;
HookResourceString(@SMsgDlgRetry, 'Reintentar') ;
HookResourceString(@SMsgDlgIgnore, 'Ignorar') ;
HookResourceString(@SMsgDlgAll, 'Todos') ;
HookResourceString(@SMsgDlgNoToAll, 'No a todos') ;
HookResourceString(@SMsgDlgYesToAll, 'Si a todos') ;
end.
|
{ Subroutine SST_R_SYO_UTITEM (TARG, SYM_MFLAG)
*
* Process UNTAGGED_ITEM syntax.
}
module sst_r_syo_utitem;
define sst_r_syo_utitem;
%include 'sst_r_syo.ins.pas';
procedure sst_r_syo_utitem ( {process UTITEM syntax}
in out jtarg: jump_targets_t; {execution block jump targets info}
in sym_mflag: sst_symbol_t); {desc of parent MFLAG variable symbol}
val_param;
const
max_msg_parms = 1; {max parameters we can pass to a message}
var
tag: sys_int_machine_t; {tag from syntax tree}
str_h: syo_string_t; {handle to string from input file}
sym_p, sym2_p: sst_symbol_p_t; {scratch pointers to symbol descriptors}
name_p: string_var_p_t; {pointer to name in hash table entry}
data_p: symbol_data_p_t; {points to data in hash table entry}
jt, jt2: jump_targets_t; {scratch jump targets for lower routines}
token: string_var8192_t; {scratch token or string}
i, j, k: sys_int_machine_t; {scratch integers}
var_p: sst_var_p_t; {scratch pointer to var descriptor}
exp_p, exp2_p, exp3_p: sst_exp_p_t; {scratch pointers to exp descriptors}
term_p: sst_exp_term_p_t; {scratch pointer to term in expression}
call_p: call_p_t; {pointer to data about called syntax}
call_pp: ^call_p_t; {points to end of called syntaxes chain pnt}
msg_parm: {parameter references for messages}
array[1..max_msg_parms] of sys_parm_msg_t;
stat: sys_err_t;
label
comp_char_sym2, in_list, done_occurs, always_match, optional;
begin
token.max := sizeof(token.str); {init local var string}
syo_level_down; {down into UNTAGGED_ITEM syntax}
syo_get_tag_msg ( {get tag to identify type of item}
tag, str_h, 'sst_syo_read', 'syerr_define', nil, 0);
case tag of
{
**************************************
*
* Item is .EOL
}
1: begin
sym2_p := sym_ichar_eol_p; {symbol to compare character value to}
comp_char_sym2: {compare char value to SYM2_P^}
sst_call (sym_cpos_push_p^); {write call to SYO_P_CPOS_PUSH}
sst_call (sym_get_ichar_p^); {write call to SYO_P_GET_ICHAR}
sst_r_syo_int (sym_p); {make temporary integer variable}
sst_call_arg_var (sst_opc_p^, sym_p^); {add integer variable call argument}
sst_r_syo_set_mflag ( {set MFLAG based on comparison}
sym_p^, {first term of comparison}
sym2_p^, {second term of comparison}
sst_op2_eq_k, {comparison operator}
true, {indicate to take error flag into account}
sym_mflag); {handle to MFLAG variable to set}
{
* Pop parsing state saved earlier.
}
sst_call (sym_cpos_pop_p^); {write call to SYO_P_CPOS_POP}
sst_call_arg_var (sst_opc_p^, sym_mflag); {add MFLAG variable as call argument}
{
* Handle the jump targets.
}
sst_r_syo_goto ( {goto, as needed, to jump targets}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is .EOF
}
2: begin
sym2_p := sym_ichar_eof_p; {symbol to compare character value to}
goto comp_char_sym2; {to common code}
end;
{
**************************************
*
* Item is symbol reference
}
3: begin
syo_get_tag_string (str_h, token); {get name of SYN file symbol}
string_upcase (token);
string_hash_ent_lookup (table_sym, token, name_p, data_p); {look up name in table}
if data_p = nil then begin {no such entry in table ?}
sys_msg_parm_vstr (msg_parm[1], token);
syo_error (str_h, 'sst_syo_read', 'symbol_not_declared', msg_parm, 1);
end;
{
* Add called syntax to list of syntaxes called by this parent, if not
* already in list.
}
call_pp := addr(def_syo_p^.call_p); {init end of called syntaxes chain pointer}
call_p := call_pp^; {init to first called syntax in chain}
while call_p <> nil do begin {loop thru called syntaxes chain}
if call_p^.data_p = data_p then begin {this called syntax already in list ?}
goto in_list;
end;
call_pp := addr(call_p^.next_p); {update pointer to end of chain}
call_p := call_pp^; {advance to next called syntax entry}
end; {back to process next called syntax entry}
string_hash_mem_alloc_ndel ( {allocate memory for new called syntax entry}
table_sym, sizeof(call_p^), call_p);
call_pp^ := call_p; {add new entry to end of chain}
call_p^.next_p := nil; {this is now new end of chain}
call_p^.data_p := data_p; {save pointer to data about called syntax}
in_list: {jump here if called syntax already in list}
sst_call (data_p^.sym_p^); {create call to syntax subroutine}
sst_call_arg_var (sst_opc_p^, sym_mflag); {pass MFLAG variable as call argument}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is string constant
}
4: begin
syo_level_down; {down into STRING syntax}
syo_get_tag_msg ( {get tag for string contents}
tag, str_h, 'sst_syo_read', 'syerr_string', nil, 0);
syo_get_tag_string (str_h, token); {get string value}
syo_level_up; {back up from STRING syntax}
sst_call (sym_test_string_p^); {create call to SYM_P_TEST_STRING}
sst_call_arg_var (sst_opc_p^, sym_mflag); {MFLAG variable is argument 1}
sst_call_arg_str ( {string characters are argument 2}
sst_opc_p^, {opcode to add call argument to}
token.str, {string value}
token.len); {number of characters in string}
sst_call_arg_int (sst_opc_p^, token.len); {number of characters is argument 3}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is .RANGE
}
5: begin
syo_get_tag_msg ( {get tag for range start character}
tag, str_h, 'sst_syo_read', 'syerr_string', nil, 0);
if tag <> 1 then begin
syo_error_tag_unexp (tag, str_h);
end;
syo_get_tag_string (str_h, token); {get string value}
i := ord(token.str[2]) & 127; {get character value for start of range}
syo_get_tag_msg ( {get tag for range start character}
tag, str_h, 'sst_syo_read', 'syerr_string', nil, 0);
if tag <> 1 then begin
syo_error_tag_unexp (tag, str_h);
end;
syo_get_tag_string (str_h, token); {get string value}
j := ord(token.str[2]) & 127; {get character value for start of range}
{
* I contains the 0-127 character value for the start of the range, and
* J contains the 0-127 character value for the end of the range.
}
sst_call (sym_cpos_push_p^); {write call to SYO_P_CPOS_PUSH}
sst_call (sym_get_ichar_p^); {write call to SYO_P_GET_ICHAR}
sst_r_syo_int (sym_p); {make temporary integer variable}
sst_call_arg_var (sst_opc_p^, sym_p^); {add integer variable call argument}
{
* Code has been written so that the integer variable at SYM_P contains
* the character code of the character to check the range of. The MFLAG
* variable will be set as the result of a comparison. Our local pointers
* to handle the comparison expression will be:
*
* EXP_P - Pointer to top level expression. First term will be the
* range check, second term will be ERROR test.
* EXP2_P - Pointer to first term of EXP_P expression. First term
* will be low end of range check, second term high end of
* range check.
* EXP3_P - Pointers to nested expression for each term in range check.
* TERM_P - Temporarily used to point to second terms of various
* expressions.
* VAR_P - Var descriptor referencing ERROR variable in common block.
}
sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {alloc mem for top expression desc}
sst_mem_alloc_scope (sizeof(exp2_p^), exp2_p); {alloc mem for range check exp desc}
sst_r_syo_comp_var_int ( {make exp comparing var to integer value}
sym_p^, {variable for first term of comparison}
i, {integer value for second term}
sst_op2_ge_k, {comparison operator}
exp3_p); {returned pointer to new expression}
sst_opcode_new; {create comparison opcode}
sst_opc_p^.opcode := sst_opc_if_k;
sst_opc_p^.if_exp_p := exp_p; {set pointer to top level decision expression}
sst_mem_alloc_scope (sizeof(var_p^), var_p); {alloc mem for var desc to ERROR}
sst_mem_alloc_scope (sizeof(term_p^), term_p); {alloc mem for second EXP_P term}
var_p^.dtype_p := sym_error_p^.var_dtype_p; {fill in var desc referencing ERROR}
var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
var_p^.vtype := sst_vtype_var_k;
var_p^.mod1.next_p := nil;
var_p^.mod1.modtyp := sst_var_modtyp_top_k;
var_p^.mod1.top_str_h := sst_opc_p^.str_h;
var_p^.mod1.top_sym_p := sym_error_p;
exp_p^.str_h := sst_opc_p^.str_h; {top level expression descriptor}
exp_p^.dtype_p := nil;
exp_p^.dtype_hard := false;
exp_p^.val_eval := false;
exp_p^.val_fnd := false;
exp_p^.rwflag := [sst_rwflag_read_k];
exp_p^.term1.next_p := term_p; {first term of top level expression}
exp_p^.term1.op2 := sst_op2_none_k;
exp_p^.term1.op1 := sst_op1_none_k;
exp_p^.term1.ttype := sst_term_exp_k;
exp_p^.term1.str_h := sst_opc_p^.str_h;
exp_p^.term1.dtype_p := nil;
exp_p^.term1.dtype_hard := false;
exp_p^.term1.val_eval := false;
exp_p^.term1.val_fnd := false;
exp_p^.term1.rwflag := [sst_rwflag_read_k];
exp_p^.term1.exp_exp_p := exp2_p;
term_p^.next_p := nil; {second term of top level expression}
term_p^.op2 := sst_op2_or_k;
term_p^.op1 := sst_op1_none_k;
term_p^.ttype := sst_term_var_k;
term_p^.str_h := sst_opc_p^.str_h;
term_p^.dtype_p := nil;
term_p^.dtype_hard := true;
term_p^.val_eval := false;
term_p^.val_fnd := false;
term_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
term_p^.var_var_p := var_p;
sst_mem_alloc_scope (sizeof(term_p^), term_p); {alloc mem for second EXP2_P term}
exp2_p^.str_h := sst_opc_p^.str_h; {range check expression descriptor}
exp2_p^.dtype_p := nil;
exp2_p^.dtype_hard := false;
exp2_p^.val_eval := false;
exp2_p^.val_fnd := false;
exp2_p^.rwflag := [sst_rwflag_read_k];
exp2_p^.term1.next_p := term_p; {low end of range check term}
exp2_p^.term1.op2 := sst_op2_none_k;
exp2_p^.term1.op1 := sst_op1_none_k;
exp2_p^.term1.ttype := sst_term_exp_k;
exp2_p^.term1.str_h := sst_opc_p^.str_h;
exp2_p^.term1.dtype_p := nil;
exp2_p^.term1.dtype_hard := false;
exp2_p^.term1.val_eval := false;
exp2_p^.term1.val_fnd := false;
exp2_p^.term1.rwflag := [sst_rwflag_read_k];
exp2_p^.term1.exp_exp_p := exp3_p;
sst_r_syo_comp_var_int ( {make exp comparing var to integer value}
sym_p^, {variable for first term of comparison}
j, {integer value for second term}
sst_op2_le_k, {comparison operator}
exp3_p); {returned pointer to new expression}
term_p^.next_p := nil; {high end of range check term}
term_p^.op2 := sst_op2_and_k;
term_p^.op1 := sst_op1_none_k;
term_p^.ttype := sst_term_exp_k;
term_p^.str_h := sst_opc_p^.str_h;
term_p^.dtype_p := nil;
term_p^.dtype_hard := false;
term_p^.val_eval := false;
term_p^.val_fnd := false;
term_p^.rwflag := [sst_rwflag_read_k];
term_p^.exp_exp_p := exp3_p;
sst_exp_eval (exp_p^, false); {fully evaluate top level expression}
{
* Write code for YES case.
}
sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code}
sst_r_syo_opc_assign (sym_mflag, sym_mflag_yes_p^);
sst_opcode_pos_pop; {pop back to parent opcode chain}
{
* Write code for NO case.
}
sst_opcode_pos_push (sst_opc_p^.if_false_p); {set up for writing FALSE code}
sst_r_syo_opc_assign (sym_mflag, sym_mflag_no_p^);
sst_opcode_pos_pop; {pop back to parent opcode chain}
{
* Pop parsing state saved earlier.
}
sst_call (sym_cpos_pop_p^); {write call to SYO_P_CPOS_POP}
sst_call_arg_var (sst_opc_p^, sym_mflag); {add MFLAG variable as call argument}
{
* Handle the jump targets.
}
sst_r_syo_goto ( {goto, as needed, to jump targets}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is .OCCURS
}
6: begin
syo_get_tag_msg ( {get tag for min occurrence number}
tag, str_h, 'sst_syo_read', 'syerr_string', nil, 0);
if tag <> 1 then begin
syo_error_tag_unexp (tag, str_h);
end;
syo_get_tag_string (str_h, token); {get string value}
string_t_int (token, i, stat); {get min occurrence number}
syo_error_abort (stat, str_h, '', '', nil, 0);
if i < 0 then begin {negative min occurrence limit not allowed}
syo_error (str_h, 'sst_syo_read', 'occurs_limit_low_bad', nil, 0);
end;
syo_level_down; {down into END_RANGE syntax}
syo_get_tag_msg ( {get tag for min occurrence number}
tag, str_h, 'sst_syo_read', 'syerr_string', nil, 0);
case tag of
1: begin {tag was for max occurrence integer value}
syo_get_tag_string (str_h, token); {get string value}
string_t_int (token, j, stat); {get max occurrence number}
syo_error_abort (stat, str_h, '', '', nil, 0);
if j < i then begin
syo_error (str_h, 'sst_syo_read', 'occurs_limit_high_below', nil, 0);
end;
end;
2: begin {tag was for infinite occurrences}
j := -1; {flag that infinite occurrences allowed}
end;
otherwise
syo_error_tag_unexp (tag, str_h);
end;
syo_level_up; {back up from END_RANGE syntax}
{
* I is set to the minimum allowable occurrence count and J is the maximum
* allowable occurrence count. J is negative to indicate that no upper
* occurrence limit is being imposed. Some special cases will be handled
* separately. K will be set to indicate which combinations of upper/lower
* limits need to be checked. K will have the following values:
*
* 0 - No limits need checking
* 1 - Lower limit needs checking
* 2 - Upper limit needs checking
* 3 - Both limits need checking
}
k := 0; {init limit checks flag}
if i > 0 then k := k + 1; {lower limit needs checking ?}
if j >= 0 then k := k + 2; {upper limit needs checking ?}
{
* Handle special case where upper and lower limits are both 1. This means
* there is really nothing to do.
}
if (i = 1) and (j = 1) then begin {OCCURS is really a NOP ?}
sst_r_syo_item (jtarg, sym_mflag); {process subject item directly}
goto done_occurs;
end;
{
* Handle special case where item is allowed 0 or one times. This
* is the same logic as handled by the OPTIONAL item.
}
if (i = 0) and (j = 1) then begin {item allowed 0 or 1 times ?}
goto optional;
end;
{
*******************
*
* The min and max limits don't match any special case. Handle in general
* way by counting the number of occurrences, then checking against the
* limits at the end.
}
sst_r_syo_int (sym_p); {get handle to occurrence counting variable}
{
* Make opcode to initialize the occurrence counter variable to 0.
}
if k <> 0 then begin {some occurrence limit needs checking ?}
sst_opcode_new; {create initial assignment opcode}
sst_opc_p^.opcode := sst_opc_assign_k;
sst_mem_alloc_scope (sizeof(var_p^), var_p); {grab mem for assignment var desc}
sst_opc_p^.assign_var_p := var_p; {point opcode to assignment var desc}
sst_exp_const_int (-1, sst_opc_p^.assign_exp_p); {assignment value is -1}
var_p^.mod1.next_p := nil;
var_p^.mod1.modtyp := sst_var_modtyp_top_k;
var_p^.mod1.top_str_h := sst_opc_p^.str_h;
var_p^.mod1.top_sym_p := sym_p;
var_p^.dtype_p := sym_p^.var_dtype_p;
var_p^.rwflag := [sst_rwflag_read_k, sst_rwflag_write_k];
var_p^.vtype := sst_vtype_var_k;
end;
{
* Insert call to SYO_P_CPOS_PUSH if there is any chance the final
* syntax matched answer might be NO.
}
if k <> 0 then begin {some limit will have to be checked ?}
sst_call (sym_cpos_push_p^); {create call to SYO_P_CPOS_PUSH}
end;
{
* Make opcode for counted loop with decision at the bottom. We will
* exit the loop after the first time the item fails.
}
sst_opcode_new; {make loop with decision at bottom opcode}
sst_opc_p^.opcode := sst_opc_loop_tbot_k;
sst_r_syo_comp_var_sym ( {create loop continuation expression}
sym_mflag, {variable for first term in expression}
sym_mflag_no_p^, {symbol to compare variable to}
sst_op2_eq_k, {comparison operator}
sst_opc_p^.lpbt_exp_p); {returned pointer to expression descriptor}
{
* Write opcodes for loop body.
}
sst_opcode_pos_push (sst_opc_p^.lpbt_code_p); {set up for writing loop body code}
{
* Increment the occurrence counter. This was initialized to -1, so it will
* be the number of successful occurrences upon loop exit.
}
if k <> 0 then begin {some occurrence limit needs checking ?}
sst_opcode_new; {create counter increment opcode}
sst_opc_p^.opcode := sst_opc_assign_k;
sst_opc_p^.assign_var_p := var_p; {point opcode to assignment var desc}
sst_mem_alloc_scope (sizeof(exp_p^), exp_p); {alloc mem for expression desc}
sst_opc_p^.assign_exp_p := exp_p; {point opcode to assignment value expression}
sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term}
exp_p^.term1.next_p := term_p;
exp_p^.term1.op2 := sst_op2_none_k;
exp_p^.term1.op1 := sst_op1_none_k;
exp_p^.term1.ttype := sst_term_var_k;
exp_p^.term1.str_h := sst_opc_p^.str_h;
exp_p^.term1.dtype_p := var_p^.dtype_p;
exp_p^.term1.dtype_hard := true;
exp_p^.term1.val_eval := false;
exp_p^.term1.val_fnd := false;
exp_p^.term1.rwflag := var_p^.rwflag;
exp_p^.term1.var_var_p := var_p;
exp_p^.str_h := sst_opc_p^.str_h;
exp_p^.dtype_p := exp_p^.term1.dtype_p;
exp_p^.dtype_hard := false;
exp_p^.val_eval := false;
exp_p^.val_fnd := false;
exp_p^.rwflag := [sst_rwflag_read_k];
term_p^.next_p := nil;
term_p^.op2 := sst_op2_add_k;
term_p^.op1 := sst_op1_none_k;
term_p^.str_h := sst_opc_p^.str_h;
term_p^.val_eval := false;
term_p^.val_fnd := false;
term_p^.rwflag := [sst_rwflag_read_k];
term_p^.ttype := sst_term_const_k;
term_p^.dtype_p := sym_int_machine_t_p^.dtype_dtype_p;
term_p^.dtype_hard := false;
term_p^.val_eval := true;
term_p^.val_fnd := true;
term_p^.val.dtype := sst_dtype_int_k;
term_p^.val.int_val := 1;
sst_exp_eval (exp_p^, false);
end;
{
* Write code to process the item.
*
* An additional layer of jump targets is used if we must always
* do a SYO_P_CPOS_POP before passing back to the parent.
}
if k = 0
then begin {OK to go directly to parent on error}
sst_r_syo_jtargets_make ( {create jump targets for nested item}
jtarg, {template jump targets}
jt, {output jump targets}
lab_fall_k, {fall thru on YES}
lab_fall_k, {fall thru on NO}
lab_same_k); {go to parent target on ERROR}
end
else begin {must always do call to SYO_P_CPOS_POP}
sst_r_syo_jtargets_make ( {create private jump targets layer}
jtarg, {template jump targets}
jt2, {output jump targets}
lab_fall_k, {fall thru on YES}
lab_fall_k, {fall thru on NO}
lab_fall_k); {fall thru on ERROR}
sst_r_syo_jtargets_make ( {create nested jump targets for ITEM}
jt2, {template jump targets}
jt, {output jump targets}
lab_fall_k, {fall thru on YES}
lab_fall_k, {fall thru on NO}
lab_same_k); {go to parent target on ERROR}
end
;
sst_r_syo_item (jt, sym_mflag); {process nested item syntax}
sst_r_syo_jtargets_done (jt); {tag implicit labels as being here}
{
****************
*
* All done with loop body code.
}
sst_opcode_pos_pop; {pop opcode position back to after loop}
case k of
{
****************
*
* Neither upper nor lower loop limit need checking.
}
0: begin
goto always_match;
end;
{
****************
*
* Only lower limit needs to be checked.
}
1: begin
sst_mem_alloc_scope (sizeof(exp_p^), exp_p);
sst_mem_alloc_scope (sizeof(term_p^), term_p);
sst_opcode_new; {create opcode for IF}
sst_opc_p^.opcode := sst_opc_if_k;
sst_r_syo_comp_var_int ( {make exp to compare var with int value}
sym_p^, {variable for first term in compare}
i, {value for second term of compare}
sst_op2_ge_k, {comparison operator}
sst_opc_p^.if_exp_p); {returned pointer to decision expression}
end;
{
****************
*
* Only upper limit needs to be checked.
}
2: begin
sst_mem_alloc_scope (sizeof(exp_p^), exp_p);
sst_mem_alloc_scope (sizeof(term_p^), term_p);
sst_opcode_new; {create opcode for IF}
sst_opc_p^.opcode := sst_opc_if_k;
sst_r_syo_comp_var_int ( {make exp to compare var with int value}
sym_p^, {variable for first term in compare}
j, {value for second term of compare}
sst_op2_le_k, {comparison operator}
sst_opc_p^.if_exp_p); {returned pointer to decision expression}
end;
{
****************
*
* Both upper and lower limit need to be checked.
}
3: begin
sst_opcode_new; {create opcode for IF}
sst_opc_p^.opcode := sst_opc_if_k;
sst_mem_alloc_scope (sizeof(exp_p^), exp_p);
sst_opc_p^.if_exp_p := exp_p; {point to boolean expression for decision}
sst_r_syo_comp_var_int ( {make compare exp for lower limit}
sym_p^, {variable for first term in compare}
i, {value for second term of compare}
sst_op2_ge_k, {comparison operator}
exp2_p); {returned pointer to decision expression}
sst_r_syo_comp_var_int ( {make compare exp for upper limit}
sym_p^, {variable for first term in compare}
j, {value for second term of compare}
sst_op2_le_k, {comparison operator}
exp3_p); {returned pointer to decision expression}
sst_mem_alloc_scope (sizeof(term_p^), term_p); {get mem for second term}
exp_p^.term1.next_p := term_p; {fill in first term in top expression}
exp_p^.term1.op2 := sst_op2_none_k;
exp_p^.term1.op1 := sst_op1_none_k;
exp_p^.term1.ttype := sst_term_exp_k;
exp_p^.term1.str_h := sst_opc_p^.str_h;
exp_p^.term1.dtype_p := nil;
exp_p^.term1.dtype_hard := false;
exp_p^.term1.val_eval := false;
exp_p^.term1.val_fnd := false;
exp_p^.term1.rwflag := [sst_rwflag_read_k];
exp_p^.term1.exp_exp_p := exp2_p;
term_p^.next_p := nil; {fill in second term in top expression}
term_p^.op2 := sst_op2_and_k; {operator between the two terms}
term_p^.op1 := sst_op1_none_k;
term_p^.ttype := sst_term_exp_k;
term_p^.str_h := sst_opc_p^.str_h;
term_p^.dtype_p := nil;
term_p^.dtype_hard := false;
term_p^.val_eval := false;
term_p^.val_fnd := false;
term_p^.rwflag := [sst_rwflag_read_k];
term_p^.exp_exp_p := exp3_p;
exp_p^.str_h := sst_opc_p^.str_h; {fill in top expression descriptor}
exp_p^.dtype_p := nil;
exp_p^.dtype_hard := false;
exp_p^.val_eval := false;
exp_p^.val_fnd := false;
exp_p^.rwflag := [sst_rwflag_read_k];
sst_exp_eval (exp_p^, false); {evaluate whole expression}
end;
end; {end of limits check cases}
{
* Write code for YES case.
}
sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE code}
sst_r_syo_opc_assign (sym_mflag, sym_mflag_yes_p^);
sst_opcode_pos_pop; {pop back to parent opcode chain}
{
* Write code for NO case.
}
sst_opcode_pos_push (sst_opc_p^.if_false_p); {set up for writing FALSE code}
sst_r_syo_opc_assign (sym_mflag, sym_mflag_no_p^);
sst_opcode_pos_pop; {pop back to parent opcode chain}
sst_r_syo_jtargets_done (jt2); {ITEM ERROR case comes here}
sst_call (sym_cpos_pop_p^); {create call to SYO_P_CPOS_POP}
sst_call_arg_var (sst_opc_p^, sym_mflag); {add MFLAG variable as call argument}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
done_occurs: {all done processing OCCURS item}
end;
{
**************************************
*
* Item is nested expression in parenthesis.
}
7: begin
sst_call (sym_cpos_push_p^); {save parse state before expression}
sst_r_syo_jtargets_make ( {make new jump targets for nested ITEM}
jtarg, jt, {input and output jump targets}
lab_fall_k, lab_fall_k, lab_fall_k); {fall thru in all cases}
sst_r_syo_expression (jt, sym_mflag); {process nested expression}
sst_r_syo_jtargets_done (jt); {tag implicit labels as being here}
sst_call (sym_cpos_pop_p^); {conditionally restore parse state after exp}
sst_call_arg_var (sst_opc_p^, sym_mflag); {add MFLAG variable as call argument}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is .CHARCASE
}
8: begin
syo_get_tag_msg ( {get tag for character case select}
tag, str_h, 'sst_syo_read', 'syerr_string', nil, 0);
case tag of
1: begin {upper case}
sym_p := sym_charcase_up_p;
end;
2: begin {lower case}
sym_p := sym_charcase_down_p;
end;
3: begin {off}
sym_p := sym_charcase_asis_p;
end;
end; {end of character case cases}
sst_call (sym_charcase_p^); {create call to SYO_P_CHARCASE}
sst_call_arg_enum (sst_opc_p^, sym_p^); {pass new character case as argument 1}
goto always_match; {make sure MFLAG is set to YES}
end;
{
**************************************
*
* Item is .NULL
}
9: begin
always_match: {jump here to set MFLAG to YES}
sst_r_syo_opc_assign (sym_mflag, sym_mflag_yes_p^); {set MFLAG to YES}
if {need to jump somewhere ?}
(not (jflag_fall_k in jtarg.yes.flags)) or {not fall thru ?}
(jflag_indir_k in jtarg.yes.flags) {indirect reference ?}
then begin
sst_opcode_new; {create GOTO opcode}
sst_opc_p^.opcode := sst_opc_goto_k;
sst_opc_p^.str_h.first_char.crange_p := nil;
sst_opc_p^.str_h.first_char.ofs := 0;
sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char;
sst_r_syo_jtarget_sym ( {get or make jump target symbol}
jtarg.yes, {jump target descriptor}
sst_opc_p^.goto_sym_p); {returned pointer to label symbol}
end;
end;
{
**************************************
*
* Item is .UPTO
}
10: begin
sst_call (sym_cpos_push_p^); {create call to SYO_P_CPOS_PUSH}
sst_r_syo_jtargets_make ( {make new jump targets for nested ITEM}
jtarg, jt, {input and output jump targets}
lab_fall_k, lab_fall_k, lab_fall_k); {fall thru in all cases}
sst_r_syo_item (jt, sym_mflag); {process nested ITEM}
sst_r_syo_jtargets_done (jt); {tag implicit labels as being here}
sst_call (sym_cpos_pop_p^); {create call to SYO_P_CPOS_POP}
sst_call_arg_enum (sst_opc_p^, sym_mflag_no_p^); {always restores state}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is .NOT
}
11: begin
sst_r_syo_jtargets_make ( {make new jump targets for nested ITEM}
jtarg, jt, {input and output jump targets}
lab_fall_k, lab_fall_k, lab_fall_k); {fall thru in all cases}
sst_r_syo_item (jt, sym_mflag); {process nested ITEM}
sst_r_syo_jtargets_done (jt); {tag implicit labels as being here}
sst_r_syo_set_mflag ( {write code to flip sense of MFLAG}
sym_mflag, {variable for first term in comparison}
sym_mflag_yes_p^, {value to compare against}
sst_op2_ne_k, {comparision operator}
true, {always set to YES on error condition}
sym_mflag); {handle to MFLAG variable to set}
sst_r_syo_goto ( {go to jump targets, as required}
jtarg, {jump targets data}
[jtarg_yes_k, jtarg_no_k, jtarg_err_k], {which targets to process}
sym_mflag); {handle to MFLAG variable}
end;
{
**************************************
*
* Item is .EOD
}
12: begin
sym2_p := sym_ichar_eod_p; {symbol to compare character value to}
goto comp_char_sym2; {to common code}
end;
{
**************************************
*
* Item is .OPTIONAL
}
13: begin
optional: {jump here from .OCCURS [0 TO 1]}
sst_r_syo_jtargets_make ( {make new jump targets for nested ITEM}
jtarg, jt, {input and output jump targets}
lab_fall_k, lab_fall_k, lab_fall_k); {fall thru in all cases}
sst_r_syo_item (jt, sym_mflag); {process nested ITEM}
sst_r_syo_jtargets_done (jt); {tag implicit labels as being here}
goto always_match; {.OPTIONAL always returns YES}
end;
{
**************************************
*
* Unexpected expression format tag value.
}
otherwise
syo_error_tag_unexp (tag, str_h);
end; {end of item format cases}
syo_level_up; {back up from ITEM syntax}
end;
|
unit SmartThreadRegistry;
interface
uses
Windows, Classes, Collection;
procedure InitThreadRegistry;
procedure DoneThreadRegistry;
procedure RegisterThread( Thread : TThread );
procedure UnregisterThread( Thread : TThread );
function FindThread( ThreadId : dword ) : TThread;
implementation
var
ThreadList : TLockableCollection = nil;
procedure InitThreadRegistry;
begin
ThreadList := TLockableCollection.Create( 0, rkUse );
end;
procedure DoneThreadRegistry;
begin
ThreadList.Free;
ThreadList := nil;
end;
procedure RegisterThread( Thread : TThread );
begin
if ThreadList<>nil
then ThreadList.Insert( Thread );
end;
procedure UnregisterThread( Thread : TThread );
begin
if ThreadList<>nil
then ThreadList.Delete( Thread );
end;
function FindThread( ThreadId : dword ) : TThread;
var
i : integer;
begin
result := nil;
if ThreadList<>nil
then
begin
ThreadList.Lock;
try
i := 0;
while (i < ThreadList.Count) and (TThread(ThreadList[i]).ThreadId <> ThreadId) do
inc( i );
if i < ThreadList.Count
then result := TThread(ThreadList[i]);
finally
ThreadList.Unlock;
end;
end;
end;
initialization
InitThreadRegistry;
finalization
DoneThreadRegistry;
end.
|
unit ddCharacterProperty;
interface
uses
Classes,
ddTypes,
ddPropertyObject,
k2Prim,
k2Interfaces,
l3Interfaces,
RTfTypes,
l3Types,
l3Base
;
type
TddCharacterProperty = class(TddPropertyObject)
private
f_FontName: AnsiString;
f_LongProperties: Array[TddCharProperties] of Longint;
private
function IsDefaultValue(anIndex: TddCharProperties; aValue: LongInt): Boolean;
function GetParam(Index: TddCharProperties): LongInt;
procedure SetParam(Index: TddCharProperties; Value: LongInt);
protected
function GetBoolProperty(Index: TddCharProperties): Boolean;
function GetCaps: TddCharCapsType;
function GetFontName: AnsiString;
function GetLongProperty(Index: TddCharProperties): LongInt;
function GetPos: TCharPosition;
function GetUnderline: TUnderline;
procedure SetBoolProperty(Index: TddCharProperties; Value: Boolean);
procedure SetCaps(Value: TddCharCapsType);
procedure SetFontName(Value: AnsiString);
procedure SetLongProperty(Index: TddCharProperties; Value: Longint);
procedure SetPos(Value: TCharPosition);
procedure SetUnderline(Value: TUnderline);
property Param[Index: TddCharProperties]: LongInt read GetParam write
SetParam;
public
constructor Create; override;
procedure AssignFrom(ACHP: TddPropertyObject); override;
procedure Clear; override;
function SymbolFont: Boolean;
function MonoTypeFont: Boolean;
function OCompare(anObject: Tl3Base): Long; override;
function Diff(P: TddPropertyObject; aForReader: Boolean): TddPropertyObject; override;
function JoinWith(P: TObject): Long; override;
procedure MergeWith(P: TddPropertyObject); override;
procedure InheriteFrom(P: TddPropertyObject); override;
procedure Reset; override;
function HasDefaultValue(aProperty: TddCharProperties): Boolean;
procedure Write2Generator(const Generator: Ik2TagGenerator); override;
procedure ClearProp(aPropID: TddCharProperties);
function IsFontColorWhite: Boolean;
function IsHighlightColorWhite: Boolean;
property BColor: LongInt index ddBColor read GetLongProperty write
SetLongProperty;
property BIndexColor: LongInt index ddBackColor read GetLongProperty write
SetLongProperty;
property Bold: Boolean index ddBold read GetBoolProperty write
SetBoolProperty;
property Caps: TddCharCapsType read GetCaps write SetCaps;
property CharScale: LongInt index ddCharScale read GetLongProperty write
SetLongProperty;
property Deleted: Boolean index ddDeleted read GetBoolProperty write
SetBoolProperty;
property EvdStyle: LongInt index ddEvdStyle read GetLongProperty write
SetLongProperty;
property FColor: LongInt index ddFColor read GetLongProperty write
SetLongProperty;
property FIndexColor: LongInt index ddForeColor read GetLongProperty write
SetLongProperty;
property FontName: AnsiString read GetFontName write SetFontName;
property FontNumber: LongInt index ddFontNumber read GetLongProperty write
SetLongProperty;
property FontCharSet: LongInt
index ddFontCharSet
read GetLongProperty
write SetLongProperty;
property FontSize: LongInt index ddFontSize read GetLongProperty write
SetLongProperty;
property PrintFontSize: LongInt index ddPrintFontSize read GetLongProperty write
SetLongProperty;
property Hidden: Boolean index ddHidden read GetBoolProperty write
SetBoolProperty;
property Highlight: LongInt index ddHighlight read GetLongProperty write
SetLongProperty;
property Italic: Boolean index ddItalic read GetBoolProperty write
SetBoolProperty;
property Language: LongInt index ddLanguage read GetLongProperty write
SetLongProperty;
property Pos: TCharPosition read GetPos write SetPos;
property Strikeout: Boolean index ddStrikeout read GetBoolProperty write
SetBoolProperty;
property Style: LongInt index ddStyle read GetLongProperty write
SetLongProperty;
property Subpos: LongInt index ddSubPos read GetLongProperty write
SetLongProperty;
property Underline: TUnderline read GetUnderline write SetUnderline;
end;
implementation
uses
Graphics,
StrUtils,
SysUtils,
k2Tags,
l3String,
l3FontManager,
ddRTFConst,
Windows;
{ start class TddCharacterProperty }
{
***************************** TddCharacterProperty *****************************
}
constructor TddCharacterProperty.Create;
begin
inherited Create;
Clear;
end;
procedure TddCharacterProperty.AssignFrom(aCHP: TddPropertyObject);
var
l_CHP : TddCharacterProperty absolute aCHP;
l_Index: TddCharProperties;
begin
if (aCHP Is TddCharacterProperty) then
begin
for l_Index := Low(TddCharProperties) to High(TddCharProperties) do
f_LongProperties[l_Index]:= l_CHP.Param[l_Index];
f_FontName := l_CHP.FontName;
IsDefault := l_CHP.IsDefault;
end // if (aCHP Is TddCharacterProperty) then
else
inherited AssignFrom(aCHP);
end;
procedure TddCharacterProperty.Clear;
var
l_Index: TddCharProperties;
begin
inherited;
for l_Index := Low(TddCharProperties) to High(TddCharProperties) do
Param[l_Index] := propUndefined;
FontName := '';
IsDefault := True;
end;
function TddCharacterProperty.OCompare(anObject: Tl3Base): Long;
var
l_Index: TddCharProperties;
begin
if (anObject Is TddCharacterProperty) then
begin
Result := 1;
if not AnsiSameText(FontName, TddCharacterProperty(anObject).FontName) then
Exit;
for l_Index := Low(TddCharProperties) to High(TDdCharProperties) do
if TddCharacterProperty(anObject).Param[l_Index] <> Param[l_Index] then
Exit;
Result := 0;
end
else
Result := inherited OCompare(anObject);
end;
function TddCharacterProperty.Diff(P: TddPropertyObject; aForReader: Boolean): TddPropertyObject;
var
aCHP: TddCharacterProperty absolute P;
index: TddCharProperties;
l_IsDefault: Boolean;
begin
if P = nil then
Result := nil
else
if OCompare(p) = 0 then
Result := nil
else
begin
l_IsDefault := True;
Result := TddCharacterProperty.Create;
try
if (P Is TddCharacterProperty) then
begin
for index := Low(TddCharProperties) to High(TddCharProperties) do
begin
if aCHP.Param[index] = Param[Index] then
TddCharacterProperty(Result).Param[index] := propUndefined
else
if Param[index] = propUndefined then
TddCharacterProperty(Result).Param[index] := aCHP.Param[index]
else
if aCHP.Param[index] <> propUndefined then
TddCharacterProperty(Result).Param[index] := aCHP.Param[index]
else
if (index = ddBold) and (aCHP.Param[index] = propUndefined) and (Param[index] <> propUndefined) then // http://mdp.garant.ru/pages/viewpage.action?pageId=512253629
TddCharacterProperty(Result).Param[index] := Param[index];
if not TddCharacterProperty(Result).HasDefaultValue(index) then
l_IsDefault := False;
end; // for index
// Имя шрифта
if aCHP.Param[ddFontNumber] = Param[ddFontNumber] then
TddCharacterProperty(Result).FontName := ''
else
if Param[ddFontNumber] = propUndefined then
TddCharacterProperty(Result).FontName := aCHP.FontName
else
if aForReader and (aCHP.Param[ddFontNumber] = propUndefined) and (Param[ddFontNumber] <> propUndefined) then
begin
TddCharacterProperty(Result).FontNumber := FontNumber;
TddCharacterProperty(Result).FontName := FontName;
l_IsDefault := False;
end // if (aCHP.Param[ddFontNumber] = propUndefined) and (Param[ddFontNumber] <> propUndefined) then
else
if aCHP.Param[ddFontNumber] <> propUndefined then
TddCharacterProperty(Result).FontName := aCHP.FontName;
end; // P Is TddCharacterProperty
if l_IsDefault then
FreeAndNil(Result)
else
Result.IsDefault := False;
except
FreeAndNil(Result);
end;
end;
end;
function TddCharacterProperty.GetBoolProperty(Index: TddCharProperties):
Boolean;
begin
if f_LongProperties[Index] <> propUndefined then
Result:= LongBool(f_LongProperties[Index])
else
Result:= False;
end;
function TddCharacterProperty.GetCaps: TddCharCapsType;
begin
if f_LongProperties[ddCaps] <> propUndefined then
Result:= TddCharCapsType(f_LongProperties[ddCaps])
else
Result:= ccNone;
end;
function TddCharacterProperty.GetFontName: AnsiString;
begin
Result:= f_FontName;
end;
function TddCharacterProperty.GetLongProperty(Index: TddCharProperties):
LongInt;
begin
Result:= f_LongProperties[Index];
end;
function TddCharacterProperty.GetParam(Index: TddCharProperties): LongInt;
begin
Result:= f_LongProperties[Index];
end;
function TddCharacterProperty.GetPos: TCharPosition;
begin
if f_LongProperties[ddCharPosition] <> propUndefined then
Result:= TCharPosition(f_LongProperties[ddCharPosition])
else
Result:= cpNotDefined;
end;
function TddCharacterProperty.GetUnderline: TUnderline;
begin
if f_LongProperties[ddUnderline] <> propUndefined then
Result:= TUnderline(f_LongProperties[ddUnderline])
else
Result:= utNotDefined;
end;
function TddCharacterProperty.JoinWith(P: TObject): Long;
var
aCHP : TddCharacterProperty absolute P;
index : TddCharProperties;
begin
if (P Is TddCharacterProperty) then
begin
Result := 0;
IsDefault := IsDefault and aCHP.IsDefault;
if FontName = '' then
FontName := aCHP.FontName;
for index := Low(TddCharProperties) to High(TddCharProperties) do
if Param[Index] = propUndefined then // transparent
Param[index] := aCHP.Param[Index]
end // if (P Is TddCharacterProperty) then
else
Result := -1;
end;
procedure TddCharacterProperty.MergeWith(P: TddPropertyObject);
var
aCHP: TddCharacterProperty absolute P;
Index: TddCharProperties;
begin
if (P Is TddCharacterProperty) then
begin
IsDefault := False;
for index := Low(TddCharProperties) to High(TddCharProperties) do
if (aCHP.Param[Index] <> propUndefined) and (Param[Index] = propUndefined) then
Param[index] := aCHP.Param[Index];
end;
end;
procedure TddCharacterProperty.InheriteFrom(P: TddPropertyObject);
var
aCHP : TddCharacterProperty absolute P;
l_Index : TddCharProperties;
begin
if (P Is TddCharacterProperty) then
begin
IsDefault := False;
for l_Index := Low(TddCharProperties) to High(TddCharProperties) do
if (aCHP.Param[l_Index] <> propUndefined) and (Param[l_Index] <> propUndefined) then
Param[l_Index] := aCHP.Param[l_Index];
end;
end;
procedure TddCharacterProperty.Reset;
begin
Clear;
f_FontName:= '';
end;
procedure TddCharacterProperty.SetBoolProperty(Index: TddCharProperties; Value:
Boolean);
begin
if (f_LongProperties[Index] = propUndefined) or
((f_LongProperties[Index] <> propUndefined) and
LongBool(f_LongProperties[Index]) <> Value) then
begin
f_LongProperties[Index]:= Ord(Value);
IsDefault:= False;
end;
end;
procedure TddCharacterProperty.SetCaps(Value: TddCharCapsType);
begin
if Value <> Caps then
begin
IsDefault:= False;
f_LongProperties[ddCaps]:= Ord(Value);
end;
end;
procedure TddCharacterProperty.SetFontName(Value: AnsiString);
begin
if f_FontName <> Value then
begin
f_FontName:= Value;
IsDefault:= False;
end;
end;
procedure TddCharacterProperty.SetLongProperty(Index: TddCharProperties; Value:
Longint);
begin
if (f_LongProperties[Index] <> Value) and not IsDefaultValue(Index, Value) then
begin
f_LongProperties[Index] := Value;
if Index <> ddStyle then
IsDefault := False;
end // if f_LongProperties[Index] <> Value then
else
if IsDefaultValue(Index, Value) and not IsDefaultValue(Index, f_LongProperties[Index]) then
ClearProp(Index)
end;
procedure TddCharacterProperty.SetParam(Index: TddCharProperties; Value:
LongInt);
begin
f_LongProperties[Index] := Value;
end;
procedure TddCharacterProperty.SetPos(Value: TCharPosition);
begin
if Value <> Pos then
begin
if IsDefaultValue(ddCharPosition, Ord(Value)) then
f_LongProperties[ddCharPosition] := propUndefined
else
begin
f_LongProperties[ddCharPosition] := Ord(Value);
IsDefault := False;
end;
end;
end;
procedure TddCharacterProperty.SetUnderline(Value: TUnderline);
begin
if Value <> Underline then
begin
IsDefault:= False;
f_LongProperties[ddUnderline]:= Ord(Value);
end;
end;
procedure TddCharacterProperty.Write2Generator(const Generator: Ik2TagGenerator);
var
l_CharSet : Long;
l_LogFont : Tl3LogFont;
l_Underline: Boolean;
begin
// пока не учитывается переданное оформление
if Hidden then
Generator.AddBoolAtom(k2_tiVisible, ByteBool(False));
Generator.StartTag(k2_tiFont);
try
if Bold then
Generator.AddBoolAtom(k2_tiBold, ByteBool(Bold));
if Italic then
Generator.AddBoolAtom(k2_tiItalic, ByteBool(Italic));
if StrikeOut then
Generator.AddBoolAtom(k2_tiStrikeout, ByteBool(Strikeout));
if (Language = langRussian) and (FontName <> '') and
((Length(FontName) < 4) OR (l3Compare(PAnsiChar(FontName) + Length(FontName) - 4,
' CYR', l3_siCaseUnsensitive) <> 0)) then
begin
l_LogFont := l3FontManager.Fonts.DRByName[FontName];
if (l_LogFont <> nil) then
l_CharSet := l_LogFont.LogFont.elfLogFont.lfCharSet
else
l_CharSet := DEFAULT_CHARSET;
if not (l_CharSet in [SYMBOL_CHARSET, RUSSIAN_CHARSET]) then
FontName := FontName + ' CYR';
end;
if FontName <> '' then
Generator.AddStringAtom(k2_tiName, FontName);
if (FontSize <> propUndefined) then
Generator.AddIntegerAtom(k2_tiSize, FontSize div 2);
if fColor <> propUndefined then
Generator.AddIntegerAtom(k2_tiForeColor, FColor);
if bColor <> propUndefined then
Generator.AddIntegerAtom(k2_tiBackColor, BColor);
if Highlight <> propUndefined then
Generator.AddIntegerAtom(k2_tiBackColor, Highlight);
case Pos of
cpSuperScript: Generator.AddIntegerAtom(k2_tiIndex, ord(l3_fiSuper));
cpSubScript: Generator.AddIntegerAtom(k2_tiIndex, ord(l3_fiSub));
end; // pos
if (Underline <> utNotDefined) then
begin
l_Underline := (Underline <> utNone) and (Underline <> utNotDefined);
if l_Underline then
Generator.AddBoolAtom(k2_tiUnderline, l_Underline);
end;
finally
Generator.Finish;
end;
end;
procedure TddCharacterProperty.ClearProp(aPropID: TddCharProperties);
begin
Param[aPropID] := propUndefined;
end;
function TddCharacterProperty.IsDefaultValue(anIndex: TddCharProperties;
aValue: Integer): Boolean;
begin
Result := aValue = propUndefined;
if not Result then
case anIndex of
ddFColor: Result := (aValue = clBlack);
ddCharPosition: Result := (aValue = Ord(cpNone)) or (aValue = Ord(cpNotDefined));
end;
end;
function TddCharacterProperty.SymbolFont: Boolean;
var
l_CharSet: Long;
l_LogFont: Tl3LogFont;
begin
Result := False;
if (FontName <> '') then
begin
l_LogFont := l3FontManager.Fonts.DRByName[FontName];
if (l_LogFont <> nil) then
begin
l_CharSet := l_LogFont.LogFont.elfLogFont.lfCharSet;
Result := l_CharSet = SYMBOL_CHARSET;
end; // if (l_LogFont <> nil) then
end; // if (FontName <> '') then
end;
function TddCharacterProperty.MonoTypeFont: Boolean;
var
l_CharSet: Long;
l_LogFont: Tl3LogFont;
begin
Result := False;
if (FontName <> '') then
begin
l_LogFont := l3FontManager.Fonts.DRByName[FontName];
if (l_LogFont <> nil) then
Result := l_LogFont.IsFixed;
end; // if (FontName <> '') then
end;
function TddCharacterProperty.HasDefaultValue(
aProperty: TddCharProperties): Boolean;
begin
Result := IsDefaultValue(aProperty, f_LongProperties[aProperty]);
end;
function TddCharacterProperty.IsFontColorWhite: Boolean;
begin
Result := FColor = clWhite
end;
function TddCharacterProperty.IsHighlightColorWhite: Boolean;
begin
Result := Highlight = clWhite
end;
end.
|
unit D3Math;
interface
function Min(a, b : integer) : integer;
function Max(a, b : integer) : integer;
implementation
function Min(a, b : integer) : integer;
begin
if a < b
then Result := a
else Result := b;
end;
function Max(a, b : integer) : integer;
begin
if a > b
then Result := a
else Result := b;
end;
end.
|
unit CircuitEquivalences;
interface
uses
Collection, Circuits;
type
TEquivalence = class;
TEquivalences = class;
TEquivalence =
class
public
constructor Create(aRep : TCircuit);
destructor Destroy; override;
private
fCircuits : TCollection;
public
property Circuits : TCollection read fCircuits;
public
function Belongs(aCircuit : TCircuit) : boolean;
function Include(aCircuit : TCircuit) : boolean;
function Merge(anEqv : TEquivalence) : boolean;
end;
TEquivalences =
class
public
constructor Create;
destructor Destroy; override;
private
fEquivalences : TCollection;
public
function FindEquivalence(Circuit : TCircuit) : TEquivalence;
procedure AddEquivalence(Circuit1, Circuit2 : TCircuit);
procedure Clear;
public
property Equivalences : TCollection read fEquivalences;
end;
implementation
// TEquivalence
constructor TEquivalence.Create(aRep : TCircuit);
begin
inherited Create;
fCircuits := TCollection.Create(0, rkUse);
fCircuits.Insert(aRep);
end;
destructor TEquivalence.Destroy;
begin
fCircuits.Free;
inherited;
end;
function TEquivalence.Belongs(aCircuit : TCircuit) : boolean;
begin
result := fCircuits.IndexOf(aCircuit) <> noIndex;
end;
function TEquivalence.Include(aCircuit : TCircuit) : boolean;
begin
if not Belongs(aCircuit)
then
begin
fCircuits.Insert(aCircuit);
result := true;
end
else result := false;
end;
function TEquivalence.Merge(anEqv : TEquivalence) : boolean;
var
i : integer;
begin
if anEqv <> nil
then
begin
for i := 0 to pred(anEqv.fCircuits.Count) do
Include(TCircuit(anEqv.fCircuits[i]));
result := true;
end
else result := false;
end;
// TEquivalences
constructor TEquivalences.Create;
begin
inherited Create;
fEquivalences := TCollection.Create(0, rkBelonguer);
end;
destructor TEquivalences.Destroy;
begin
fEquivalences.Free;
inherited;
end;
function TEquivalences.FindEquivalence(Circuit : TCircuit) : TEquivalence;
var
i : integer;
begin
i := 0;
while (i < fEquivalences.Count) and not TEquivalence(fEquivalences[i]).Belongs(Circuit) do
inc(i);
if i < fEquivalences.Count
then result := TEquivalence(fEquivalences[i])
else result := nil;
end;
procedure TEquivalences.AddEquivalence(Circuit1, Circuit2 : TCircuit);
var
Eq1, Eq2 : TEquivalence;
begin
Eq1 := FindEquivalence(Circuit1);
Eq2 := FindEquivalence(Circuit2);
if (Eq1 = nil) or (Eq1 <> Eq2)
then
if Eq1 <> nil
then
if Eq2 <> nil
then
begin
Eq1.Merge(Eq2);
fEquivalences.Delete(Eq2);
end
else Eq1.Include(Circuit2)
else
if Eq2 <> nil
then
begin
Eq2.Include(Circuit1);
Eq2.Include(Circuit2);
end
else
begin
Eq1 := TEquivalence.Create(Circuit1);
Eq1.Include(Circuit2);
fEquivalences.Insert(Eq1);
end;
end;
procedure TEquivalences.Clear;
begin
fEquivalences.DeleteAll;
end;
end.
|
unit FeatureErrorIntf;
interface
uses
ErrorIntf;
type
IFeatureError = interface(IError)
['{0BA0638C-53C1-41A8-9EB2-6DC94244E2E6}']
function GetLine: Integer;
function GetSugestedAction: string;
procedure SetLine(const Value: Integer);
procedure SetSugestedAction(const Value: string);
property Line: Integer read GetLine write SetLine;
property SugestedAction: string read GetSugestedAction write SetSugestedAction;
end;
implementation
end.
|
(*
This source code is Copyright (C) 2000 Kyley Harris
This software is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone who has received permission from the author
in writing, or purchased a licence to use from the author to use this
software for any purpose, including commercial applications, and to alter it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
4. The source codes may not be redistributed without permission.
5. This header must not be removed or altered.
Any changes to the code would be appreciated to be emailed to the author
for consideration to any improvements.
Kyley Harris, Auckland, New Zealand
Kyley@HarrisSoftware.com
*)
unit uTemplate;
interface
uses
sysutils,
classes;
const BLANK_PARAM='_INSERTBLANK_';
type
TCodeStackItem = class(TObject)
private
FReplaceValue: string;
FParamName: string;
procedure SetParamName(const Value: string);
procedure SetReplaceValue(const Value: string);
public
property ParamName:string read FParamName write SetParamName;
property ReplaceValue:string read FReplaceValue write SetReplaceValue;
end;
TCodeStackReplace = class(TObject)
private
FParamPos: integer;
FParam: TCodeStackItem;
procedure SetParam(const Value: TCodeStackItem);
procedure SetParamPos(const Value: integer);
public
property Param:TCodeStackItem read FParam write SetParam;
property ParamPos:integer read FParamPos write SetParamPos;
end;
TStackReplace = class(TComponent)
protected
FParams:TStringList;
FStack:TList;
public
constructor Create(AOwner:TComponent);override;
procedure AddParam(AName,AValue:string);
function Process(AValue:string):string;
destructor Destroy;override;
end;
implementation
uses
StrUtils,
Math;
type
TLongestFirst = class(TStringList)
public
procedure LongestFirst;
end;
{ TTemplate }
function HssStringReplace(const s:string; AFind, AReplace: string): string;
var
i:integer;
ASourceLen,AFindLen,AReplaceLen:integer;
LenDif:integer;
AMatchPos:integer;
begin
AFind := UpperCase(AFind);
AFindLen := Length(AFind);
AReplaceLen := Length(AReplace);
ASourceLen := Length(s);
LenDif := AReplaceLen-AFindLen;
result := s;
if AFind = '' then
begin
exit;
end else
if ASourceLen > 0 then
begin
i := 1;
AMatchPos := 1;
repeat
if UpCase(Result[i]) = AFind[AMatchPos] then
Inc(AMatchPos) else
AMatchPos := 1;
if AMatchPos = AFindLen+1 then
begin
AMatchPos := 1;
Delete(result,i-AFindLen+1,AFindLen);
Insert(AReplace,result,i-AFindLen+1);
Inc(i,LenDif+1);
end else
Inc(i);
until i > Length(result);
end;
end;
{ TLongestFirst }
function SortLongestFirst(List: TStringList; Index1, Index2: Integer): Integer;
begin
if Length(List.Names[Index1]) > Length(List.Names[Index2]) then
result := -1 else
if Length(List.Names[Index1]) < Length(List.Names[Index2]) then
result := 1 else
result := 0;
end;
procedure TLongestFirst.LongestFirst;
begin
CustomSort(SortLongestFirst);
end;
{ TStackReplace }
procedure TStackReplace.AddParam(AName, AValue: string);
var
O:TCodeStackItem;
begin
o := TCodeStackItem.Create;
o.ParamName := AName;
o.ReplaceValue := AValue;
FParams.AddObject(UpperCase(AName), o);
end;
constructor TStackReplace.Create(AOwner: TComponent);
begin
inherited;
FParams := TStringList.Create;
FParams.sorted := True;
FStack := TList.Create;
end;
destructor TStackReplace.Destroy;
var
i:integer;
begin
for i := 0 to FStack.count - 1 do tobject(FStack[i]).Free;
while FParams.Count > 0 do
begin
FParams.Objects[0].free;
FParams.Delete(0);
end;
FreeAndNil(FParams);
FreeAndNil(FStack);
inherited;
end;
function SortStack(Item1, Item2: Pointer): Integer;
begin
result := CompareValue(TCodeStackReplace(Item1).ParamPos,TCodeStackReplace(Item2).ParamPos);
end;
function TStackReplace.Process(AValue: string): string;
var
CSR:TCodeStackReplace;
i:integer;
s:string;
i1:integer;
i2:integer;
function GetChar(APos:integer):Char;
begin
if APos < 1 then
result := #32 else
if APos > Length(AValue) then
result := #32 else
result := AValue[APos];
end;
function WhiteSpace(APos:integer):boolean;
const
WHITE_SPACE_CHARS = [#0..#32,',','/','+','.','-','*','(',')','='];
begin
{$IF DEFINED(FPC) or (CompilerVersion > 19)}
result := CharInSet(GetChar(APos),WHITE_SPACE_CHARS);
{$ELSE}
result := GetChar(APos) in WHITE_SPACE_CHARS;
{$IFEND}
end;
var
p:string;
pl:integer;
LengthValue:integer;
begin
LengthValue := length(AValue);
s := uppercase(Avalue);
for i1 := FParams.Count -1 downto 0 do
begin
p := uppercase(FParams[i1]);
pl := length(p);
i := 1;
repeat
i := PosEx(p,s,i);
if (i > 0) then
if (WhiteSpace(i-1) and WhiteSpace(i+pl)) then
begin
CSR := TCodeStackReplace.Create;
CSR.Param := FParams.Objects[i1] as TCodeStackItem;
CSR.FParamPos := i;
for i2 := i to i + Length(FParams[i1]) -1 do
s[i2] := ' ';
FStack.add(CSR);
i := i + pl -1;
end else
inc(i);
until (i = 0) or (i > LengthValue);
end;
FStack.Sort(SortStack);
while FStack.Count > 0 do
begin
CSR := TCodeStackReplace(FStack[FStack.count-1]);
FStack.Delete(FStack.count-1);
try
Delete(AValue,CSR.ParamPos,Length(CSR.Param.FParamName));
Insert(CSR.Param.ReplaceValue,AValue,CSR.ParamPos);
finally
FreeAndNil(CSR);
end;
end;
result := AValue;
end;
{ TCodeStackItem }
procedure TCodeStackItem.SetParamName(const Value: string);
begin
FParamName := Value;
end;
procedure TCodeStackItem.SetReplaceValue(const Value: string);
begin
FReplaceValue := Value;
end;
{ TCodeStackReplace }
procedure TCodeStackReplace.SetParam(const Value: TCodeStackItem);
begin
FParam := Value;
end;
procedure TCodeStackReplace.SetParamPos(const Value: integer);
begin
FParamPos := Value;
end;
end.
|
unit SQLite3Constants;
{ *******************************************************
SQLite 3 Dynamic Library wrapper for Delphi
2012 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
*******************************************************
Files: SQLite3Constants, SQLite3Lib
*******************************************************
CHANGE LOG:
- 2012-03-22: First implementation
******************************************************* }
interface
const
// Result codes
SQLITE_OK = 0; // Successful result
SQLITE_ERROR = 1; // SQL error or missing database
SQLITE_INTERNAL = 2; // An internal logic error in SQLite
SQLITE_PERM = 3; // Access permission denied
SQLITE_ABORT = 4; // Callback routine requested an abort
SQLITE_BUSY = 5; // The database file is locked
SQLITE_LOCKED = 6; // A table in the database is locked
SQLITE_NOMEM = 7; // A malloc() failed
SQLITE_READONLY = 8; // Attempt to write a readonly database
SQLITE_INTERRUPT = 9; // Operation terminated by sqlite3_interrupt()
SQLITE_IOERR = 10; // Some kind of disk I/O error occurred
SQLITE_CORRUPT = 11; // The database disk image is malformed
SQLITE_NOTFOUND = 12; // (Internal Only) Table or record not found
SQLITE_FULL = 13; // Insertion failed because database is full
SQLITE_CANTOPEN = 14; // Unable to open the database file
SQLITE_PROTOCOL = 15; // Database lock protocol error
SQLITE_EMPTY = 16; // Database is empty
SQLITE_SCHEMA = 17; // The database schema changed
SQLITE_TOOBIG = 18; // Too much data for one row of a table
SQLITE_CONSTRAINT = 19; // Abort due to contraint violation
SQLITE_MISMATCH = 20; // Data type mismatch
SQLITE_MISUSE = 21; // Library used incorrectly
SQLITE_NOLFS = 22; // Uses OS features not supported on host
SQLITE_AUTH = 23; // Authorization denied
SQLITE_FORMAT = 24; // Auxiliary database format error
SQLITE_RANGE = 25; // 2nd parameter to sqlite3_bind out of range
SQLITE_NOTADB = 26; // File opened that is not a database file
SQLITE_ROW = 100; // sqlite3_step() has another row ready
SQLITE_DONE = 101; // sqlite3_step() has finished executing
// Flags for the xAccess VFS method
SQLITE_ACCESS_EXISTS = 0;
SQLITE_ACCESS_READWRITE = 1;
SQLITE_ACCESS_READ = 2;
// Authorizer Action Codes
SQLITE_CREATE_INDEX = 1;
SQLITE_CREATE_TABLE = 2;
SQLITE_CREATE_TEMP_INDEX = 3;
SQLITE_CREATE_TEMP_TABLE = 4;
SQLITE_CREATE_TEMP_TRIGGER = 5;
SQLITE_CREATE_TEMP_VIEW = 6;
SQLITE_CREATE_TRIGGER = 7;
SQLITE_CREATE_VIEW = 8;
SQLITE_DELETE = 9;
SQLITE_DROP_INDEX = 10;
SQLITE_DROP_TABLE = 11;
SQLITE_DROP_TEMP_INDEX = 12;
SQLITE_DROP_TEMP_TABLE = 13;
SQLITE_DROP_TEMP_TRIGGER = 14;
SQLITE_DROP_TEMP_VIEW = 15;
SQLITE_DROP_TRIGGER = 16;
SQLITE_DROP_VIEW = 17;
SQLITE_INSERT = 18;
SQLITE_PRAGMA = 19;
SQLITE_READ = 20;
SQLITE_SELECT = 21;
SQLITE_TRANSACTION = 22;
SQLITE_UPDATE = 23;
SQLITE_ATTACH = 24;
SQLITE_DETACH = 25;
SQLITE_ALTER_TABLE = 26;
SQLITE_REINDEX = 27;
SQLITE_ANALYZE = 28;
SQLITE_CREATE_VTABLE = 29;
SQLITE_DROP_VTABLE = 30;
SQLITE_FUNCTION = 31;
SQLITE_SAVEPOINT = 32;
SQLITE_COPY = 0;
// Fundamental Data types
SQLITE_INTEGER = 1;
SQLITE_FLOAT = 2;
SQLITE_TEXT = 3;
SQLITE_BLOB = 4;
SQLITE_NULL = 5;
// Text encodings
SQLITE_UTF8 = 1;
SQLITE_UTF16 = 2;
SQLITE_UTF16BE = 3;
SQLITE_UTF16LE = 4;
SQLITE_ANY = 5;
// Constants Defining Special Destructor Behavior
SQLITE_STATIC = Pointer(0);
SQLITE_TRANSIENT = Pointer(-1);
// Checkpoint operation parameters
SQLITE_CHECKPOINT_PASSIVE = 0;
SQLITE_CHECKPOINT_FULL = 1;
SQLITE_CHECKPOINT_RESTART = 2;
// Configuration options
SQLITE_CONFIG_SINGLETHREAD = 1;
SQLITE_CONFIG_MULTITHREAD = 2;
SQLITE_CONFIG_SERIALIZED = 3;
SQLITE_CONFIG_MALLOC = 4;
SQLITE_CONFIG_GETMALLOC = 5;
SQLITE_CONFIG_SCRATCH = 6;
SQLITE_CONFIG_PAGECACHE = 7;
SQLITE_CONFIG_HEAP = 8;
SQLITE_CONFIG_MEMSTATUS = 9;
SQLITE_CONFIG_MUTEX = 10;
SQLITE_CONFIG_GETMUTEX = 11;
SQLITE_CONFIG_LOOKASIDE = 13;
SQLITE_CONFIG_PCACHE = 14;
SQLITE_CONFIG_GETPCACHE = 15;
SQLITE_CONFIG_LOG = 16;
SQLITE_CONFIG_URI = 17;
// Status Parameters for database connections
SQLITE_DBSTATUS_LOOKASIDE_USED = 0;
SQLITE_DBSTATUS_CACHE_USED = 1;
SQLITE_DBSTATUS_SCHEMA_USED = 2;
SQLITE_DBSTATUS_STMT_USED = 3;
SQLITE_DBSTATUS_LOOKASIDE_HIT = 4;
SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE = 5;
SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL = 6;
SQLITE_DBSTATUS_MAX = 6;
// Standard File Control Opcodes
SQLITE_FCNTL_LOCKSTATE = 1;
SQLITE_GET_LOCKPROXYFILE = 2;
SQLITE_SET_LOCKPROXYFILE = 3;
SQLITE_LAST_ERRNO = 4;
SQLITE_FCNTL_SIZE_HINT = 5;
SQLITE_FCNTL_CHUNK_SIZE = 6;
SQLITE_FCNTL_FILE_POINTER = 7;
SQLITE_FCNTL_SYNC_OMITTED = 8;
// Authorizer Return Codes
SQLITE_DENY = 1;
SQLITE_IGNORE = 2;
// Virtual Table Constraint Operator Codes
SQLITE_INDEX_CONSTRAINT_EQ = 2;
SQLITE_INDEX_CONSTRAINT_GT = 4;
SQLITE_INDEX_CONSTRAINT_LE = 8;
SQLITE_INDEX_CONSTRAINT_LT = 16;
SQLITE_INDEX_CONSTRAINT_GE = 32;
SQLITE_INDEX_CONSTRAINT_MATCH = 64;
// Device Characteristics
SQLITE_IOCAP_ATOMIC = $00000001;
SQLITE_IOCAP_ATOMIC512 = $00000002;
SQLITE_IOCAP_ATOMIC1K = $00000004;
SQLITE_IOCAP_ATOMIC2K = $00000008;
SQLITE_IOCAP_ATOMIC4K = $00000010;
SQLITE_IOCAP_ATOMIC8K = $00000020;
SQLITE_IOCAP_ATOMIC16K = $00000040;
SQLITE_IOCAP_ATOMIC32K = $00000080;
SQLITE_IOCAP_ATOMIC64K = $00000100;
SQLITE_IOCAP_SAFE_APPEND = $00000200;
SQLITE_IOCAP_SEQUENTIAL = $00000400;
SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN = $00000800;
// Extended result codes
SQLITE_IOERR_READ = (SQLITE_IOERR or (1 shl 8));
SQLITE_IOERR_SHORT_READ = (SQLITE_IOERR or (2 shl 8));
SQLITE_IOERR_WRITE = (SQLITE_IOERR or (3 shl 8));
SQLITE_IOERR_FSYNC = (SQLITE_IOERR or (4 shl 8));
SQLITE_IOERR_DIR_FSYNC = (SQLITE_IOERR or (5 shl 8));
SQLITE_IOERR_TRUNCATE = (SQLITE_IOERR or (6 shl 8));
SQLITE_IOERR_FSTAT = (SQLITE_IOERR or (7 shl 8));
SQLITE_IOERR_UNLOCK = (SQLITE_IOERR or (8 shl 8));
SQLITE_IOERR_RDLOCK = (SQLITE_IOERR or (9 shl 8));
SQLITE_IOERR_DELETE = (SQLITE_IOERR or (10 shl 8));
SQLITE_IOERR_BLOCKED = (SQLITE_IOERR or (11 shl 8));
SQLITE_IOERR_NOMEM = (SQLITE_IOERR or (12 shl 8));
SQLITE_IOERR_ACCESS = (SQLITE_IOERR or (13 shl 8));
SQLITE_IOERR_CHECKRESERVEDLOCK = (SQLITE_IOERR or (14 shl 8));
SQLITE_IOERR_LOCK = (SQLITE_IOERR or (15 shl 8));
SQLITE_IOERR_CLOSE = (SQLITE_IOERR or (16 shl 8));
SQLITE_IOERR_DIR_CLOSE = (SQLITE_IOERR or (17 shl 8));
SQLITE_IOERR_SHMOPEN = (SQLITE_IOERR or (18 shl 8));
SQLITE_IOERR_SHMSIZE = (SQLITE_IOERR or (19 shl 8));
SQLITE_IOERR_SHMLOCK = (SQLITE_IOERR or (20 shl 8));
SQLITE_IOERR_SHMMAP = (SQLITE_IOERR or (21 shl 8));
SQLITE_IOERR_SEEK = (SQLITE_IOERR or (22 shl 8));
SQLITE_LOCKED_SHAREDCACHE = (SQLITE_LOCKED or (1 shl 8));
SQLITE_BUSY_RECOVERY = (SQLITE_BUSY or (1 shl 8));
SQLITE_CANTOPEN_NOTEMPDIR = (SQLITE_CANTOPEN or (1 shl 8));
SQLITE_CORRUPT_VTAB = (SQLITE_CORRUPT or (1 shl 8));
SQLITE_READONLY_RECOVERY = (SQLITE_READONLY or (1 shl 8));
SQLITE_READONLY_CANTLOCK = (SQLITE_READONLY or (2 shl 8));
// Run-Time Limit Categories
SQLITE_LIMIT_LENGTH = 0;
SQLITE_LIMIT_SQL_LENGTH = 1;
SQLITE_LIMIT_COLUMN = 2;
SQLITE_LIMIT_EXPR_DEPTH = 3;
SQLITE_LIMIT_COMPOUND_SELECT = 4;
SQLITE_LIMIT_VDBE_OP = 5;
SQLITE_LIMIT_FUNCTION_ARG = 6;
SQLITE_LIMIT_ATTACHED = 7;
SQLITE_LIMIT_LIKE_PATTERN_LENGTH = 8;
SQLITE_LIMIT_VARIABLE_NUMBER = 9;
SQLITE_LIMIT_TRIGGER_DEPTH = 10;
// File Locking Levels
SQLITE_LOCK_NONE = 0;
SQLITE_LOCK_SHARED = 1;
SQLITE_LOCK_RESERVED = 2;
SQLITE_LOCK_PENDING = 3;
SQLITE_LOCK_EXCLUSIVE = 4;
// Mutex Types
SQLITE_MUTEX_FAST = 0;
SQLITE_MUTEX_RECURSIVE = 1;
SQLITE_MUTEX_STATIC_MASTER = 2;
SQLITE_MUTEX_STATIC_MEM = 3;
SQLITE_MUTEX_STATIC_MEM2 = 4;
SQLITE_MUTEX_STATIC_OPEN = 4;
SQLITE_MUTEX_STATIC_PRNG = 5;
SQLITE_MUTEX_STATIC_LRU = 6;
SQLITE_MUTEX_STATIC_LRU2 = 7;
SQLITE_MUTEX_STATIC_PMEM = 7;
// Flags For File Open Operations
SQLITE_OPEN_READONLY = $00000001;
SQLITE_OPEN_READWRITE = $00000002;
SQLITE_OPEN_CREATE = $00000004;
SQLITE_OPEN_DELETEONCLOSE = $00000008;
SQLITE_OPEN_EXCLUSIVE = $00000010;
SQLITE_OPEN_AUTOPROXY = $00000020;
SQLITE_OPEN_URI = $00000040;
SQLITE_OPEN_MAIN_DB = $00000100;
SQLITE_OPEN_TEMP_DB = $00000200;
SQLITE_OPEN_TRANSIENT_DB = $00000400;
SQLITE_OPEN_MAIN_JOURNAL = $00000800;
SQLITE_OPEN_TEMP_JOURNAL = $00001000;
SQLITE_OPEN_SUBJOURNAL = $00002000;
SQLITE_OPEN_MASTER_JOURNAL = $00004000;
SQLITE_OPEN_NOMUTEX = $00008000;
SQLITE_OPEN_FULLMUTEX = $00010000;
SQLITE_OPEN_SHAREDCACHE = $00020000;
SQLITE_OPEN_PRIVATECACHE = $00040000;
SQLITE_OPEN_WAL = $00080000;
// Flags for the xShmLock VFS method
SQLITE_SHM_UNLOCK = 1;
SQLITE_SHM_LOCK = 2;
SQLITE_SHM_SHARED = 4;
SQLITE_SHM_EXCLUSIVE = 8;
// Status Parameters
SQLITE_STATUS_MEMORY_USED = 0;
SQLITE_STATUS_PAGECACHE_USED = 1;
SQLITE_STATUS_PAGECACHE_OVERFLOW = 2;
SQLITE_STATUS_SCRATCH_USED = 3;
SQLITE_STATUS_SCRATCH_OVERFLOW = 4;
SQLITE_STATUS_MALLOC_SIZE = 5;
SQLITE_STATUS_PARSER_STACK = 6;
SQLITE_STATUS_PAGECACHE_SIZE = 7;
SQLITE_STATUS_SCRATCH_SIZE = 8;
SQLITE_STATUS_MALLOC_COUNT = 9;
// Status Parameters for prepared statements
SQLITE_STMTSTATUS_FULLSCAN_STEP = 1;
SQLITE_STMTSTATUS_SORT = 2;
SQLITE_STMTSTATUS_AUTOINDEX = 3;
// Synchronization Type Flags
SQLITE_SYNC_NORMAL = $00002;
SQLITE_SYNC_FULL = $00003;
SQLITE_SYNC_DATAONLY = $00010;
// T esting Interface Operation Codes
SQLITE_TESTCTRL_FIRST = 5;
SQLITE_TESTCTRL_PRNG_SAVE = 5;
SQLITE_TESTCTRL_PRNG_RESTORE = 6;
SQLITE_TESTCTRL_PRNG_RESET = 7;
SQLITE_TESTCTRL_BITVEC_TEST = 8;
SQLITE_TESTCTRL_FAULT_INSTALL = 9;
SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS = 10;
SQLITE_TESTCTRL_PENDING_BYTE = 11;
SQLITE_TESTCTRL_ASSERT = 12;
SQLITE_TESTCTRL_ALWAYS = 13;
SQLITE_TESTCTRL_RESERVE = 14;
SQLITE_TESTCTRL_OPTIMIZATIONS = 15;
SQLITE_TESTCTRL_ISKEYWORD = 16;
SQLITE_TESTCTRL_PGHDRSZ = 17;
SQLITE_TESTCTRL_SCRATCHMALLOC = 18;
SQLITE_TESTCTRL_LOCALTIME_FAULT = 19;
SQLITE_TESTCTRL_LAST = 19;
// Virtual Table Configuration Options
SQLITE_VTAB_CONSTRAINT_SUPPORT = 1;
implementation
end.
|
unit FMX.Grid.DataManager;
interface
uses
System.Classes,
System.SysUtils,
System.Rtti,
FMX.Grid;
type
TGridDataManager = Class(System.Classes.TComponent)
private
FData: array of array of TValue; // Col and Row
FMyGrid: TCustomGrid; //
protected
Procedure SetColLength(Const Value: Integer); Virtual;
Procedure SetRowLength(Const Value: Integer); Virtual;
procedure SetColRowLength(Const Col, Row: Integer); Virtual;
public
function ReadRowAsSingle(Const Row: Integer): TArray<Single>;
/// <summary>Получить значение</summary>
Function Read(Const Col, Row: Integer): TValue; overload;
Function ReadAsSingle(Const Col, Row: Integer): Single; overload;
Function ReadAsInteger(Const Col, Row: Integer): Integer; overload;
/// <summary>Записать значение</summary>
Procedure Write(Const Col, Row: Integer; Const Value: TValue);
//
procedure Clear; overload;
procedure Clear(Const Col, Row: Integer); overload;
function ColumnCount: Integer;
function RowCount: Integer;
published
property MyGrid: TCustomGrid read FMyGrid write FMyGrid;
End;
procedure Register;
implementation
procedure Register;
Begin
RegisterComponents('Grids', [TGridDataManager]);
End;
{ TGridDataManager }
procedure TGridDataManager.Clear(const Col, Row: Integer);
begin
Write(Col, Row, TValue.Empty);
end;
procedure TGridDataManager.Clear;
var
I: Integer;
J: Integer;
begin
for I := Low(FData) to High(FData) do
for J := Low(FData[I]) to High(FData[I]) do
Clear(I, J);
end;
function TGridDataManager.ColumnCount: Integer;
begin
Result := Length(FData);
end;
function TGridDataManager.Read(const Col, Row: Integer): TValue;
begin
if NOT Assigned(FMyGrid) then
Exit;
SetColRowLength(FMyGrid.ColumnCount, FMyGrid.RowCount);
Result := FData[Col][Row];
end;
function TGridDataManager.ReadAsInteger(const Col, Row: Integer): Integer;
begin
if NOT Result.TryParse(Read(Col, Row).AsString, Result) then
Result := 0;
end;
function TGridDataManager.ReadAsSingle(const Col, Row: Integer): Single;
begin
Result.TryParse(Read(Col, Row).ToString, Result)
end;
function TGridDataManager.ReadRowAsSingle(const Row: Integer): TArray<Single>;
var
I: Integer;
begin
SetLength(Result, RowCount);
for I := Low(Result) to High(Result) do
Result[I] := ReadAsSingle(I, Row);
end;
function TGridDataManager.RowCount: Integer;
begin
Result := 0;
if ColumnCount > 0 then
Result := Length(FData[Low(FData)]);
end;
procedure TGridDataManager.SetColLength(const Value: Integer);
begin
SetLength(FData, Value);
end;
procedure TGridDataManager.SetRowLength(const Value: Integer);
var
I: Integer;
begin
for I := Low(FData) to High(FData) do
SetLength(FData[I], Value);
end;
procedure TGridDataManager.SetColRowLength(const Col, Row: Integer);
begin
SetColLength(Col);
SetRowLength(Row);
end;
procedure TGridDataManager.Write(const Col, Row: Integer; const Value: TValue);
begin
if NOT Assigned(FMyGrid) then
Exit;
SetColRowLength(FMyGrid.ColumnCount, FMyGrid.RowCount);
FData[Col][Row] := Value;
MyGrid.Repaint;
end;
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 frmProcedureEditor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, cxGraphics, dxStatusBar, cxSplitter, cxListView,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMemo, cxRichEdit, dxBar,
ExtCtrls, OraProcSource, OraBarConn, frmProcedureDetail, StdCtrls,RichEdit,
ora, oraStorage, cxPC;
type
TProcedureEditorFrm = class(TForm)
bottomPanel: TPanel;
lviewError: TcxListView;
cxSplitter2: TcxSplitter;
dxBarManager1: TdxBarManager;
btnSaveQuery: TdxBarButton;
btnCompile: TdxBarButton;
btnNewQuery: TdxBarButton;
btnOpenQuery: TdxBarButton;
btnUndo: TdxBarButton;
btnRedo: TdxBarButton;
btnFindText: TdxBarButton;
btnAlignLeft: TdxBarButton;
btnAlignCenter: TdxBarButton;
btnAlignRight: TdxBarButton;
btnCut: TdxBarButton;
btnCopy: TdxBarButton;
btnPaste: TdxBarButton;
btnClear: TdxBarButton;
btnSelectAll: TdxBarButton;
btnReplace: TdxBarButton;
dxBarDockControl1: TdxBarDockControl;
OpenDialog: TOpenDialog;
editorStatusBar: TdxStatusBar;
SaveDialog: TSaveDialog;
ReplaceDialog: TReplaceDialog;
FindDialog: TFindDialog;
bbtnRun: TdxBarButton;
pc: TcxPageControl;
tsSource: TcxTabSheet;
tsBody: TcxTabSheet;
SQLEditorSource: TRichEdit;
SQLEditorBody: TRichEdit;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnNewQueryClick(Sender: TObject);
procedure btnOpenQueryClick(Sender: TObject);
procedure btnSaveQueryClick(Sender: TObject);
procedure SQLEditorSourceChange(Sender: TObject);
procedure SQLEditorSourceSelectionChange(Sender: TObject);
procedure btnUndoClick(Sender: TObject);
procedure btnRedoClick(Sender: TObject);
procedure btnCutClick(Sender: TObject);
procedure btnCopyClick(Sender: TObject);
procedure btnPasteClick(Sender: TObject);
procedure btnClearClick(Sender: TObject);
procedure btnSelectAllClick(Sender: TObject);
procedure btnFindTextClick(Sender: TObject);
procedure btnReplaceClick(Sender: TObject);
procedure btnAlignLeftClick(Sender: TObject);
procedure FindDialogFind(Sender: TObject);
procedure ReplaceDialogFind(Sender: TObject);
procedure btnCompileClick(Sender: TObject);
procedure bbtnRunClick(Sender: TObject);
procedure pcChange(Sender: TObject);
private
{ Private declarations }
FProcSource: TProcSource;
procedure NewProcSource;
procedure SetErrorStatus;
function GetSQLEditor: TRichEdit;
function GetSQLEditorCol: Integer;
function GetSQLEditorRow: Integer;
property SQLEditorCol: Integer read GetSQLEditorCol;
property SQLEditorRow: Integer read GetSQLEditorRow;
property SQLEditor: TRichEdit read GetSQLEditor;
public
{ Public declarations }
procedure Init(ProcSource : TProcSource);
end;
var
ProcedureEditorFrm: TProcedureEditorFrm;
implementation
uses frmMain, util, frmProcedureRun, VisualOptions, GenelDM;
{$R *.dfm}
procedure TProcedureEditorFrm.Init(ProcSource : TProcSource);
begin
DMGenel.ChangeLanguage(self);
ChangeVisualGUI(self);
Caption := ProcSource.OraSession.Server+'/'+ProcSource.OraSession.UserName+' - '+'Procedure Editor' +' ('+ProcSource.SOURCE_NAME+')';
editorStatusBar.Panels[0].Text := ProcSource.OraSession.Server+'/'+ProcSource.OraSession.UserName;
MainFrm.dxBarListWindows.Items.AddObject(Caption, Self);
FProcSource := TProcSource.Create;
FProcSource := ProcSource;
tsBody.TabVisible := FProcSource.SOURCE_TYPE = stPackage;
if FProcSource.Mode = InsertMode then
begin
SQLEditorSource.Text := FProcSource.GetDefaultDDL;
if FProcSource.SOURCE_TYPE = stPackage then
SQLEditorBody.Text := FProcSource.GetDefaultBodyDDL;
SQLEditor.Modified := True;
end else
begin
FProcSource.SetDDL;
SQLEditorSource.Text := FProcSource.GetDDL;
if FProcSource.SOURCE_TYPE = stPackage then
SQLEditorBody.Text := FProcSource.GetBodyDDL;
SQLEditor.Modified := false;
end;
SetErrorStatus;
Show;
end;
procedure TProcedureEditorFrm.FormClose(Sender: TObject;
var Action: TCloseAction);
var
answer: word;
begin
if SQLEditor.Modified then
begin
answer := MessageDlg('Would you like to save your changes to '+FProcSource.OWNER+'.'+FProcSource.SOURCE_NAME+' ?', mtConfirmation, [mbYes, mbNo, mbCancel], 0);
if answer = mrYes then btnCompile.Click;
//if answer = mrNo then
if answer = mrCancel then abort;
end;
with MainFrm.dxBarListWindows.Items do
Delete(IndexOfObject(Self));
action := caFree;
end;
{**************************** PROCEDURE EVENT *********************************}
procedure TProcedureEditorFrm.btnNewQueryClick(Sender: TObject);
var
answer: word;
begin
if SQLEditor.Modified then
begin
answer := MessageDlg('Would you like to save your changes to '+FProcSource.OWNER+'.'+FProcSource.SOURCE_NAME+' ?', mtConfirmation, [mbYes, mbNo, mbCancel], 0);
if answer = mrYes then btnCompile.Click;
if answer = mrNo then NewProcSource;
if answer = mrCancel then abort;
end;
end;
procedure TProcedureEditorFrm.NewProcSource;
begin
FProcSource := ProcedureDetailFrm.Init(FProcSource);
SQLEditorSource.Text := FProcSource.GetDDL;
if FProcSource.SOURCE_TYPE = stPackage then
SQLEditorBody.Text := FProcSource.GetDefaultBodyDDL;
end;
procedure TProcedureEditorFrm.btnOpenQueryClick(Sender: TObject);
begin
OpenDialog.FileName := '';
if OpenDialog.Execute then
begin
btnNewQuery.Click;
SQLEditor.Lines.LoadFromFile(OpenDialog.FileName);
Caption := FProcSource.OraSession.Server+'/'+FProcSource.OraSession.UserName+' - '+'Procedure Editor' +' ('+OpenDialog.FileName+')';
with MainFrm.dxBarListWindows do
Items[Items.IndexOfObject(Self)] := Self.Caption ;
editorStatusBar.Panels[2].Text := 'Modified';
end;
end;
procedure TProcedureEditorFrm.btnSaveQueryClick(Sender: TObject);
begin
if SaveDialog.Execute then
begin
SQLEditor.Lines.SaveToFile(SaveDialog.FileName);
Caption := FProcSource.OraSession.Server+'/'+FProcSource.OraSession.Username+' - '+'Procedure Editor' +' ('+SaveDialog.FileName+')';
with MainFrm.dxBarListWindows do
Items[Items.IndexOfObject(Self)] := Self.Caption ;
editorStatusBar.Panels[2].Text := '';
end;
end;
function TProcedureEditorFrm.GetSQLEditor: TRichEdit;
begin
if pc.ActivePage = tsSource then
result := SQLEditorSource
else
result := SQLEditorBody;
end;
function TProcedureEditorFrm.GetSQLEditorCol: Integer;
begin
with SQLEditor do
Result := SelStart - SendMessage(Handle, EM_LINEINDEX, SQLEditorRow, 0);
end;
function TProcedureEditorFrm.GetSQLEditorRow: Integer;
begin
with SQLEditor do
Result := SendMessage(Handle, EM_LINEFROMCHAR, SelStart, 0);
end;
procedure TProcedureEditorFrm.SQLEditorSourceChange(Sender: TObject);
begin
if FProcSource = nil then exit;
SQLEditor.OnSelectionChange(SQLEditor);
TdxStatusBarTextPanelStyle(editorStatusBar.Panels[1].PanelStyle).ImageIndex := 0;
TdxStatusBarTextPanelStyle(editorStatusBar.Panels[0].PanelStyle).ImageIndex := 2;
btnUndo.Enabled := SendMessage(SQLEditor.Handle, EM_CANUNDO, 0, 0) <> 0;
btnRedo.Enabled := SendMessage(SQLEditor.Handle, EM_CANREDO, 0, 0) <> 0;
if SQLEditor.Text = FProcSource.CODE then
editorStatusBar.Panels[2].Text := ''
else
editorStatusBar.Panels[2].Text := 'Modified';
end;
procedure TProcedureEditorFrm.SQLEditorSourceSelectionChange(Sender: TObject);
begin
with SQLEditor do
begin
//FEditorUpdating := True;
try
editorStatusBar.Panels[1].Text := Format('Line: %3d Col: %3d', [1 + SQLEditorRow, 1 + SQLEditorCol]);
btnCopy.Enabled := SelLength > 0;
btnCut.Enabled := btnCopy.Enabled;
btnPaste.Enabled := SendMessage(SQLEditor.Handle, EM_CANPASTE, 0, 0) <> 0;
btnClear.Enabled := btnCopy.Enabled;
btnCompile.Enabled := Lines.Text <> '';
case Ord(Paragraph.Alignment) of
0: btnAlignLeft.Down := True;
1: btnAlignRight.Down := True;
2: btnAlignCenter.Down := True;
end;
finally
//FEditorUpdating := False;
end;
end;
end;
procedure TProcedureEditorFrm.btnUndoClick(Sender: TObject);
begin
SendMessage(SQLEditor.Handle, EM_UNDO, 0, 0);
end;
procedure TProcedureEditorFrm.btnRedoClick(Sender: TObject);
begin
SendMessage(SQLEditor.Handle, EM_REDO, 0, 0);
end;
procedure TProcedureEditorFrm.btnCutClick(Sender: TObject);
begin
SQLEditor.CutToClipboard;
end;
procedure TProcedureEditorFrm.btnCopyClick(Sender: TObject);
begin
SQLEditor.CopyToClipboard;
end;
procedure TProcedureEditorFrm.btnPasteClick(Sender: TObject);
begin
SQLEditor.PasteFromClipboard;
end;
procedure TProcedureEditorFrm.btnClearClick(Sender: TObject);
begin
SQLEditor.ClearSelection;
end;
procedure TProcedureEditorFrm.btnSelectAllClick(Sender: TObject);
begin
SQLEditor.SelectAll;
end;
procedure TProcedureEditorFrm.btnFindTextClick(Sender: TObject);
begin
SQLEditor.SelLength := 0;
FindDialog.Execute;
end;
procedure TProcedureEditorFrm.btnReplaceClick(Sender: TObject);
begin
SQLEditor.SelLength := 0;
ReplaceDialog.Execute;
end;
procedure TProcedureEditorFrm.btnAlignLeftClick(Sender: TObject);
begin
if TdxBarButton(Sender).Down then
SQLEditor.Paragraph.Alignment := TAlignment(TdxBarButton(Sender).Tag)
else
SQLEditor.Paragraph.Alignment := taLeftJustify;
end;
procedure TProcedureEditorFrm.FindDialogFind(Sender: TObject);
var
StartPos, FindLength, FoundAt: Integer;
Flags: TSearchTypes;
P: TPoint;
CaretR, R, IntersectR: TRect;
begin
with SQLEditor, TFindDialog(Sender) do
begin
if frDown in Options then
begin
if SelLength = 0 then StartPos := SelStart
else StartPos := SelStart + SelLength;
FindLength := Length(Text) - StartPos;
end
else
begin
StartPos := SelStart;
FindLength := -StartPos;
end;
Flags := [];
if frMatchCase in Options then Include(Flags, stMatchCase);
if frWholeWord in Options then Include(Flags, stWholeWord);
Screen.Cursor := crHourglass;
FoundAt := SQLEditor.FindText(FindText, StartPos, FindLength, Flags);
if not (frReplaceAll in Options) then Screen.Cursor := crDefault;
if FoundAt > -1 then
if frReplaceAll in Options then
begin
SelStart := FoundAt;
SelLength := Length(FindText);
end
else
begin
SetFocus;
SelStart := FoundAt;
SelLength := Length(FindText);
GetCaretPos(P);
P := ClientToScreen(P);
CaretR := Rect(P.X, P.Y, P.X + 2, P.Y + 20);
GetWindowRect(Handle, R);
if IntersectRect(IntersectR, CaretR, R) then
if P.Y < Screen.Height div 2 then
Top := P.Y + 40
else
Top := P.Y - (R.Bottom - R.Top + 20);
end
else
if not (frReplaceAll in Options) then
Application.MessageBox('The search text is not found.',
'Information', MB_ICONINFORMATION);
end;
end;
procedure TProcedureEditorFrm.ReplaceDialogFind(Sender: TObject);
var
ReplacedCount, OldSelStart, PrevSelStart: Integer;
S: string;
begin
with SQLEditor, TReplaceDialog(Sender) do
begin
ReplacedCount := 0;
OldSelStart := SelStart;
if frReplaceAll in Options then
Screen.Cursor := crHourglass;
repeat
if (SelLength > 0) and ((SelText = FindText) or
(not (frMatchCase in Options) and
(AnsiUpperCase(SelText) = AnsiUpperCase(FindText)))) then
begin
SelText := ReplaceText;
Inc(ReplacedCount);
end;
PrevSelStart := SelStart;
FindDialogFind(Sender);
until not (frReplaceAll in Options) or (SelStart = PrevSelStart);
if frReplaceAll in Options then
begin
Screen.Cursor := crDefault;
if ReplacedCount = 0 then S := 'The search text is not found.'
else
begin
SelStart := OldSelStart;
S := Format('Replaced %d occurances.', [ReplacedCount]);
end;
Application.MessageBox(PChar(S), 'Information',
MB_ICONINFORMATION);
end;
end;
end;
{**************************** PROCEDURE EVENT *********************************}
procedure TProcedureEditorFrm.btnCompileClick(Sender: TObject);
var
isValid: boolean;
begin
if SQLEditor.Text = '' then exit;
FProcSource.CODE := SQLEditorSource.Text;
if FProcSource.SOURCE_TYPE = stPackage then
FProcSource.BODY_CODE := SQLEditorBody.Text;
isValid := FProcSource.AlterSource(FProcSource.CODE);
if (isValid) and (FProcSource.SOURCE_TYPE = stPackage) then
isValid := FProcSource.AlterSource(FProcSource.BODY_CODE);
SetErrorStatus;
SQLEditor.Modified := false;
editorStatusBar.Panels[2].Text := '';
if not isValid then editorStatusBar.Panels[3].Text := 'Invalid';
end;
procedure TProcedureEditorFrm.SetErrorStatus;
begin
lviewError.Items.Clear;
if pc.ActivePage = tsSource then
begin
FillViewHorizontal(FProcSource.SourceErrors, lviewError);
if FProcSource.SourceErrors.RecordCount = 0 then
editorStatusBar.Panels[3].Text := 'Valid'
else
editorStatusBar.Panels[3].Text := 'Invalid';
end;
if pc.ActivePage = tsBody then
begin
FillViewHorizontal(FProcSource.SourceBodyErrors, lviewError);
if FProcSource.SourceBodyErrors.RecordCount = 0 then
editorStatusBar.Panels[3].Text := 'Valid'
else
editorStatusBar.Panels[3].Text := 'Invalid';
end;
end;
procedure TProcedureEditorFrm.bbtnRunClick(Sender: TObject);
begin
ProcedureRunFrm.Init(FProcSource);
end;
procedure TProcedureEditorFrm.pcChange(Sender: TObject);
begin
SetErrorStatus;
end;
end.
|
unit QRColorBox;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Buttons, system.UITypes;
type
TQRColorBox = class(TCustomControl)
protected
FColorval : TColor;
FColor : TColor;
FBackgroundColor : TColor;
procedure setColor( acolor : TColor);
function getColor : TColor;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer);override;
procedure Paint; override;
private
srect1, srect2, srect3 : TRect;
rv, gv, bv : byte;
thumb1, thumb2, thumb3 : TRect;
drag1, drag2, drag3 : boolean;
thumbextra, thumbwidth, tmouseoffset : integer;
button1 : TRect;
joinThumbs : boolean;
procedure drawSlider( srect, thumb : TRect);
function makeThumb( srect : TRect; thumbpos : integer): TRect;
function hit( hrect : TRect; x,y : integer) : boolean;
public
constructor Create(Owner : TComponent); override;
published
property Color : TColor read getColor write setColor;
property BackgroundColor : TColor read FBackgroundColor write FBackgroundColor;
end;
implementation
procedure GetRGB(Col: TColor; var R, G, B: Byte);
var
Color: $0..$FFFFFFFF;
begin
Color := ColorToRGB(Col);
R := ($000000FF and Color);
G := ($0000FF00 and Color) Shr 8;
B := ($00FF0000 and Color) Shr 16;
end;
procedure DrawButton( dbutton : TRect; canvas : TCanvas; btnTxt : string; highlight : boolean );
var
h1, h2 : integer;
begin
h1 := (dbutton.Height div 2) -1; // 13
h2 := h1-1;// 12
canvas.Pen.Style := psClear;
canvas.Brush.Color := rgb(240,240,240);
canvas.Rectangle(dbutton.Left, dbutton.top, dbutton.right, dbutton.bottom-h1);
canvas.Brush.Color := rgb(214,214,214);
canvas.Rectangle(dbutton.Left, dbutton.top+h1, dbutton.right, dbutton.bottom);
canvas.Pen.Style := psSolid;
canvas.Pen.Color := rgb(235,235,235);
canvas.MoveTo(dbutton.Left,dbutton.top+h2);
canvas.LineTo(dbutton.Right,dbutton.top+h2);
canvas.Brush.Style := bsClear;;
canvas.Pen.Color := rgb(112,112,112);
canvas.Rectangle(dbutton);
canvas.Pen.Color := rgb(251,251,251);
canvas.Rectangle(dbutton.Left+1, dbutton.top+1, dbutton.right-1, dbutton.bottom-1);
canvas.TextOut(dbutton.Left + 5,dbutton.top+canvas.Font.Size, btntxt);
end;
constructor TQRColorBox.Create(Owner : TComponent);
begin
inherited Create(Owner);
srect1 := rect( 10, 30, 400, 50);
thumb1 := makeThumb(srect1, 0);
srect2 := rect( 10, 70, 400, 90);
thumb2 := makeThumb(srect2, 0);
srect3 := rect( 10, 110, 400, 130);
thumb3 := makeThumb(srect3, 0);
rv := 0;
gv := 0;
bv := 0;
width := 420;
height := 420;
FColor := clWhite;
FBackgroundColor := clBtnFace;
end;
procedure TQRColorBox.Paint;
begin
canvas.Brush.Color := FBackgroundColor;
canvas.Rectangle(clientrect);
canvas.TextOut(10, 180, format('RED %3.3d',[ rv]));
canvas.TextOut(10, 200, format('GREEN %3.3d',[ gv]));
canvas.TextOut(10, 220, format('BLUE %3.3d',[ bv]));
drawSlider(srect1, thumb1);
drawSlider(srect2, thumb2);
drawSlider(srect3, thumb3);
//savecolor := canvas.Brush.Color;
canvas.Brush.Color := FColor;
canvas.Rectangle(200, 140, 400, 260);
//canvas.Brush.Color := savecolor;
button1 := rect(10, 140, 105, 168);
DrawButton( button1, canvas, 'Thumbs are free', false);
end;
function TQRColorBox.hit( hrect : TRect; x,y : integer) : boolean;
begin
result := (x > hrect.Left) and ( x < hrect.Right) and (Y>hrect.top) and (y<hrect.Bottom);
if result then tmouseoffset := x - hrect.Left;
end;
function TQRColorBox.makeThumb( srect : TRect; thumbpos : integer): TRect;
begin
thumbextra := 5;
thumbwidth := 12;
result := rect(srect.Left+thumbpos,srect.Top-thumbextra, srect.Left+thumbpos+thumbwidth,srect.Top+srect.Height + thumbextra);
end;
procedure TQRColorBox.drawSlider( srect, thumb : TRect);
begin
canvas.brush.Style := bsSolid;
canvas.Pen.Style := psClear;
canvas.brush.Color := FBackgroundColor;
canvas.Rectangle(rect(srect.Left, srect.Top-thumbextra, srect.Right+2, srect.Bottom + thumbextra+2));
canvas.Pen.Style := psSolid;
canvas.Pen.Color := clblack;
canvas.brush.Color := clScrollbar;
canvas.Rectangle(srect);
canvas.Brush.Color := rgb(220,220,220);
canvas.Rectangle(thumb);
canvas.Pen.Color := clsilver;
canvas.MoveTo(thumb.Left, thumb.top);
canvas.LineTo(thumb.Left+thumb.width, thumb.top);
canvas.MoveTo(thumb.Left, thumb.top);
canvas.LineTo(thumb.Left, thumb.top+thumb.height);
end;
function TQRColorBox.getColor : TColor;
begin
result := rgb(rv,gv,bv);
end;
procedure TQRColorBox.setColor( acolor : TColor);
var
thumbpos : integer;
savecolor : TColor;
begin
FColorval := acolor;
FColor := acolor;
GetRGB(acolor, rv,gv,bv);
thumbpos := trunc((rv*(srect1.Width-thumbwidth))/255.0);
thumb1 := self.makeThumb(srect1, thumbpos);
drawSlider( srect1, thumb1);
thumbpos := trunc((gv*(srect1.Width-thumbwidth))/255.0);
thumb2 := self.makeThumb(srect2, thumbpos);
drawSlider( srect2, thumb2);
thumbpos := trunc((bv*(srect1.Width-thumbwidth))/255.0);
thumb3 := self.makeThumb(srect3, thumbpos);
drawSlider( srect3, thumb3);
canvas.Brush.Color := FBackgroundColor;
canvas.TextOut(10, 180, format('RED %3.3d',[ rv]));
canvas.TextOut(10, 200, format('GREEN %3.3d',[ gv]));
canvas.TextOut(10, 220, format('BLUE %3.3d',[ bv]));
savecolor := canvas.Brush.Color;
canvas.Brush.Color := FColor;
canvas.Rectangle(200, 140, 400, 260);
canvas.Brush.Color := savecolor;
end;
procedure TQRColorBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown( button, shift, x, y);
drag1 := hit( thumb1,x,y);
drag2 := hit( thumb2,x,y);
drag3 := hit( thumb3,x,y);
end;
procedure TQRColorBox.MouseMove(Shift: TShiftState; X, Y: Integer);
var
thumbpos, dthumb : integer;
savecolor : TColor;
function MoveSlider( slider : TRect; var thumb : TRect; tpos : integer; var cval : byte) : boolean;
begin
result := not((thumbpos<0) or ((thumbpos+thumbwidth)> slider.Width));
if result then
begin
thumb := self.makeThumb(slider, tpos);
drawSlider( slider, thumb);
cval := trunc(255.0*tpos/(slider.Width-(thumbwidth)));
end;
end;
begin
inherited MouseMove( shift, x, y );
if drag1 then
begin
thumbpos := x-srect1.Left - tmouseoffset;
dthumb := thumbpos - thumb1.Left;
if not MoveSlider( srect1,thumb1,thumbpos,rv) then exit;
if joinThumbs then
begin
thumbpos := thumb2.Left + dthumb;
MoveSlider( srect2,thumb2,thumbpos,gv);
thumbpos := thumb3.Left + dthumb;
MoveSlider( srect3,thumb3,thumbpos,bv);
end;
end
else if drag2 then
begin
thumbpos := x-srect2.Left - tmouseoffset;
dthumb := thumbpos - thumb2.Left;
if not MoveSlider( srect2,thumb2,thumbpos,gv) then exit;
if joinThumbs then
begin
thumbpos := thumb1.Left + dthumb;
MoveSlider( srect1,thumb1,thumbpos,rv);
thumbpos := thumb3.Left + dthumb;
MoveSlider( srect3,thumb3,thumbpos,bv);
end;
end
else if drag3 then
begin
thumbpos := x-srect3.Left - tmouseoffset;
dthumb := thumbpos - thumb3.Left;
if not MoveSlider( srect3,thumb3,thumbpos,bv) then exit;
if joinThumbs then
begin
thumbpos := thumb1.Left + dthumb;
MoveSlider( srect1,thumb1,thumbpos,rv);
thumbpos := thumb2.Left + dthumb;
MoveSlider( srect2,thumb2,thumbpos,gv);
end;
end
else
exit;
canvas.Brush.Color := FBackgroundColor;
canvas.TextOut(10, 200, format('GREEN %3.3d',[ gv]));
canvas.TextOut(10, 180, format('RED %3.3d',[ rv]));
canvas.TextOut(10, 220, format('BLUE %3.3d',[ bv]));
FColorVal := rgb(rv, gv, bv);
savecolor := canvas.Brush.Color;
canvas.Brush.Color := FColorVal;
canvas.Rectangle(200, 140, 400, 260);
canvas.Brush.Color := savecolor;
end;
procedure TQRColorBox.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
thumbpos : integer;
savecolor : TColor;
begin
inherited MouseUp(button, shift, x, y );
if drag1 then drag1 := false;
if drag2 then drag2 := false;
if drag3 then drag3 := false;
if hit(srect1, x,y) and not hit(thumb1, x, y) and not joinThumbs then
begin
thumbpos := x-srect1.Left;
if (thumbpos<0) or ((thumbpos+thumbwidth)> srect1.Width) then exit;
thumb1 := self.makeThumb(srect1, thumbpos);
drawSlider( srect1, thumb1);
rv := trunc(255.0*thumbpos/(srect1.Width-(thumbwidth)));
end
else if hit(srect2, x,y) and not hit(thumb2, x, y) and not joinThumbs then
begin
thumbpos := x-srect1.Left;
if (thumbpos<0) or ((thumbpos+thumbwidth)> srect2.Width) then exit;
thumb2 := self.makeThumb(srect2, thumbpos);
drawSlider( srect2, thumb2);
gv := trunc(255.0*thumbpos/(srect2.Width-(thumbwidth)));
end
else if hit(srect3, x,y) and not hit(thumb3, x, y) and not joinThumbs then
begin
thumbpos := x-srect1.Left;
if (thumbpos<0) or ((thumbpos+thumbwidth)> srect3.Width) then exit;
thumb3 := self.makeThumb(srect3, thumbpos);
drawSlider( srect3, thumb3);
bv := trunc(255.0*thumbpos/(srect3.Width-(thumbwidth)));
end
else
begin
if hit(button1, x, y) then
begin
joinThumbs := not joinThumbs;
if joinThumbs then
drawButton( button1, canvas,'Thumbs are joined',false)
else
drawButton( button1, canvas,'Thumbs are free',false)
end;
exit;
end;
canvas.Brush.Color := FBackgroundColor;
canvas.TextOut(10, 180, format('RED %3.3d',[ rv]));
canvas.TextOut(10, 200, format('GREEN %3.3d',[ gv]));
canvas.TextOut(10, 220, format('BLUE %3.3d',[ bv]));
FColorVal := rgb(rv, gv, bv);
savecolor := canvas.Brush.Color;
canvas.Brush.Color := FColorVal;
canvas.Rectangle(200, 140, 400, 260);
canvas.Brush.Color := savecolor;
end;
end.
|
{*********************************************************}
{* VPTASKEDITDLG.PAS 1.03 *}
{*********************************************************}
{* ***** 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 Visual PlanIt *}
{* *}
{* The Initial Developer of the Original Code is TurboPower Software *}
{* *}
{* Portions created by TurboPower Software Inc. are Copyright (C) 2002 *}
{* TurboPower Software Inc. All Rights Reserved. *}
{* *}
{* Contributor(s): *}
{* *}
{* ***** END LICENSE BLOCK ***** *}
{$I Vp.INC}
unit VpTaskEditDlg;
{ default task editing dialog }
interface
uses
{$IFDEF LCL}
LMessages,LCLProc,LCLType,LCLIntf,LResources,
{$ELSE}
Windows,
{$ENDIF}
Messages, SysUtils,
{$IFDEF VERSION6} Variants, {$ENDIF}
Classes, Graphics, Controls, Forms, Dialogs, VpData, StdCtrls, ExtCtrls,
VpEdPop, VpDateEdit, VpBase, VpSR, VpDlg, ComCtrls;
type
{ forward declarations }
TVpTaskEditDialog = class;
TTaskEditForm = class(TForm)
Panel2: TPanel;
OKBtn: TButton;
CancelBtn: TButton;
PageControl1: TPageControl;
tabTask: TTabSheet;
DescriptionEdit: TEdit;
DueDateLbl: TLabel;
DueDateEdit: TVpDateEdit;
CompleteCB: TCheckBox;
CreatedOnLbl: TLabel;
CompletedOnLbl: TLabel;
DetailsMemo: TMemo;
ResourceNameLbl: TLabel;
Bevel1: TBevel;
Bevel2: TBevel;
imgCalendar: TImage;
imgCompleted: TImage;
procedure FormCreate(Sender: TObject);
procedure OnChange(Sender: TObject);
procedure OKBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
FReturnCode: TVpEditorReturnCode;
FTask: TVpTask;
FResource: TVpResource;
public
procedure PopulateSelf;
procedure DePopulateSelf;
property Task: TVpTask
read FTask write FTask;
property Resource: TVpResource
read FResource write FResource;
property ReturnCode: TVpEditorReturnCode
read FReturnCode;
end;
TVpTaskEditDialog = class(TVpBaseDialog)
protected {private}
teEditDlg : TTaskEditForm;
teTask : TVpTask;
public
constructor Create(AOwner : TComponent); override;
function Execute(Task: TVpTask): Boolean; reintroduce;
function AddNewTask: Boolean;
published
{properties}
property DataStore;
property Options;
property Placement;
end;
implementation
{$IFNDEF LCL}
{$R *.dfm}
{$ENDIF}
{ TTaskEditForm }
procedure TTaskEditForm.FormCreate(Sender: TObject);
begin
FReturnCode := rtAbandon;
end;
{=====}
procedure TTaskEditForm.DePopulateSelf;
begin
Task.Description := DescriptionEdit.Text;
Task.DueDate := DueDateEdit.Date;
Task.Details := DetailsMemo.Text;
Task.Complete := CompleteCB.Checked;
DueDateLbl.Caption := RSDueDate;
end;
{=====}
procedure TTaskEditForm.PopulateSelf;
begin
ResourceNameLbl.Caption := Resource.Description;
DueDateLbl.Caption := RSDueDate;
OKBtn.Caption := RSOKBtn;
CancelBtn.Caption := RSCancelBtn;
DescriptionEdit.Text := Task.Description;
DueDateEdit.Date := Task.DueDate;
DetailsMemo.Text := Task.Details;
CompleteCB.Checked := Task.Complete;
if Task.CompletedOn <> 0 then
CompletedOnLbl.Caption := RSCompletedOn + ' ' +
FormatDateTime(ShortDateFormat, Task.CompletedOn)
else
CompletedOnLbl.Visible := False;
CompletedOnLbl.Visible := CompleteCB.Checked;
CreatedOnLbl.Caption := RSCreatedOn + ' ' +
FormatDateTime(ShortDateFormat, Task.CreatedOn);
end;
{=====}
procedure TTaskEditForm.OnChange(Sender: TObject);
begin
Task.Changed := true;
end;
{=====}
procedure TTaskEditForm.OKBtnClick(Sender: TObject);
begin
FReturnCode := rtCommit;
Close;
end;
{=====}
procedure TTaskEditForm.CancelBtnClick(Sender: TObject);
begin
Close;
end;
{=====}
procedure TTaskEditForm.FormShow(Sender: TObject);
begin
DescriptionEdit.SetFocus;
end;
{=====}
{ TVpTaskEditDialog }
constructor TVpTaskEditDialog.Create(AOwner : TComponent);
begin
inherited Create(AOwner);
FPlacement.Height := 340;
FPlacement.Width := 545;
end;
function TVpTaskEditDialog.Execute(Task: TVpTask): Boolean;
var
TaskEditForm: TTaskEditForm;
begin
Result := false;
teTask := Task;
if (teTask <> nil) and (DataStore <> nil) and
(DataStore.Resource <> nil) then begin
Application.CreateForm(TTaskEditForm, TaskEditForm);
try
DoFormPlacement(TaskEditForm);
SetFormCaption(TaskEditForm, Task.Description, RSDlgTaskEdit);
TaskEditForm.Task := Task;
TaskEditForm.Resource := DataStore.Resource;
TaskEditForm.PopulateSelf;
TaskEditForm.ShowModal;
Result := (TaskEditForm.ReturnCode = rtCommit);
Task.Changed := Result;
if Result then begin
TaskEditForm.DePopulateSelf;
DataStore.PostTasks;
DataStore.NotifyDependents;
end;
finally
TaskEditForm.Release;
end;
end;
end;
{=====}
function TVpTaskEditDialog.AddNewTask: Boolean;
begin
result := false;
if DataStore <> nil then begin
teTask := DataStore.Resource.Tasks.AddTask(DataStore.GetNextID('Tasks'));
if teTask <> nil then begin
Result := Execute(teTask);
if not Result then
teTask.Free;
end;
end;
end;
{=====}
initialization
{$IFDEF LCL}
{$I vptaskeditdlg.lrs}
{$ENDIF}
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.1 1/25/2004 2:17:52 PM JPMugaas
Should work better. Removed one GPF in S/Key.
Rev 1.0 11/13/2002 08:00:36 AM JPMugaas
PLAIN mechanism
This is of type TIdSASLUserPass because it needs a username/password,
additionally it has a LoginAs property - this is the "effective username"
after connecting, which could be different as your "real" username
(eg. root logging in as someone else on a unix system)
}
unit IdSASLPlain;
interface
{$i IdCompilerDefines.inc}
uses
IdSASL,
IdSASLUserPass;
type
TIdSASLPlain = class(TIdSASLUserPass)
protected
FLoginAs: String;
public
function IsReadyToStart: Boolean; override;
class function ServiceName: TIdSASLServiceName; override;
function StartAuthenticate(const AChallenge, AHost, AProtocolName : string) : String; override;
published
property LoginAs : String read FLoginAs write FLoginAs;
end;
implementation
{ TIdSASLPlain }
function TIdSASLPlain.IsReadyToStart: Boolean;
begin
Result := inherited IsReadyToStart;
if not Result then begin
Result := (LoginAs <> '');
end;
end;
class function TIdSASLPlain.ServiceName: TIdSASLServiceName;
begin
Result := 'PLAIN'; {Do not translate}
end;
function TIdSASLPlain.StartAuthenticate(const AChallenge, AHost, AProtocolName : string): String;
var
LUser, LUserAs: string;
begin
LUser := GetUsername;
LUserAs := LoginAs;
if LUser = '' then begin
LUser := LUserAs;
end;
Result := LUserAs+#0+LUser+#0+GetPassword; {Do not translate}
end;
end.
|
// **********************************************************************
//
// Copyright (c) 2001 MT Tools.
//
// All Rights Reserved
//
// MT_DORB is based in part on the product DORB,
// written by Shadrin Victor
//
// See Readme.txt for contact information
//
// **********************************************************************
unit osprocess;
interface
{$I dorb.inc}
uses SysUtils, Classes, process_int, osthread, orbtypes,{$IFDEF LINUX}Libc{$ENDIF}
{$IFDEF MSWINDOWS}Windows{$ENDIF};
type
TProcessFactory = class(TInterfacedObject, IProcessFactory)
private
{$IFDEF MSWINDOWS}
FWatcher: IORBThread;
{$ENDIF}
protected
function CreateProcess(const ACommand: string; const ACallback: IProcessCallback): IProcess;
public
constructor Create;
destructor Destroy; override;
end;
TProcess = class(TInterfacedObject, IProcess)
private
FCallback: IProcessCallback;
{$IFDEF MSWINDOWS}
FPid: DWORD;
FRequestExitEvent: THandle;
FProcess: THandle;
{$ENDIF}
{$IFDEF LINUX}
FPid: __pid_t;
{$ENDIF}
FExitStatus: long;
FCommand: string;
FDetached: boolean;
{$IFDEF LINUX}
//procedure SignalHandler(Sig: Longint); cdecl;
{$ENDIF}
protected
procedure Detach;
procedure Terminate;
function Run: boolean;
{$IFDEF MSWINDOWS}
function PId: DWORD;
function PHandle: THandle;
{$ENDIF}
{$IFDEF LINUX}
function PId: __pid_t;
{$ENDIF}
function Callback: IProcessCallback;
public
constructor Create(const ACommand: string; const ACallback: IProcessCallback);
destructor Destroy; override;
class procedure ProcessDied(APid: DWORD);
class procedure Init();
class procedure Shutdown();
end;
TProcessReaper = class(TORBThread)
protected
procedure Run(); override;
end;
TProcessExitEventListener = class(TORBThread)
private
protected
procedure Run(); override;
end;
function ProcessFactory: IProcessFactory;
implementation
uses orb;
var
{$IFDEF MSWINDOWS}
SignalMutex: THandle;
ProcessExitEvent: THandle;
ExitEventThread: IORBThread;
NumOfChildren: integer;
ChildProcs: TWOHandleArray;
ChildPids: array [0..MAXIMUM_WAIT_OBJECTS - 1] of DWORD;
{$ENDIF}
{$IFDEF LINUX}
SigActionRec: TSigAction;
{$ENDIF}
ProcessFactoryVar: IProcessFactory;
ProcessList: IInterfaceList;
function ProcessFactory: IProcessFactory;
begin
if ProcessFactoryVar = nil then
ProcessFactoryVar := TProcessFactory.Create;
result := ProcessFactoryVar;
end;
{ TProcess }
function TProcess.Callback: IProcessCallback;
begin
result := FCallback;
end;
constructor TProcess.Create(const ACommand: string; const ACallback: IProcessCallback);
begin
inherited Create;
{$IFDEF MSWINDOWS}
WaitForSingleObject(SignalMutex, INFINITE);
try
FCommand := ACommand;
FCallback := ACallback;
FExitStatus := -1;
ProcessList.Add(Self as IProcess);
finally
ReleaseMutex(SignalMutex);
end; { try/finally }
{$ENDIF}
{$IFDEF LINUX}
FCommand := ACommand;
FCallback := ACallback;
FExitStatus := -1;
ProcessList.Add(Self as IProcess);
{$ENDIF}
end;
destructor TProcess.Destroy;
begin
{$IFDEF MSWINDOWS}
WaitForSingleObject(SignalMutex, INFINITE);
try
if ProcessList <> nil then
repeat
until ProcessList.Remove(Self) = -1;
finally
CloseHandle(FRequestExitEvent);
ReleaseMutex(SignalMutex);
end; { try/finally }
{$ENDIF}
{$IFDEF LINUX}
if ProcessList <> nil then
repeat
until ProcessList.Remove(Self) = -1;
{$ENDIF}
{ TODO -oOVS : exited }
inherited;
end;
procedure TProcess.Detach;
begin
FDetached := true;
FCallback := nil;
end;
class procedure TProcess.Init;
{$IFDEF MSWINDOWS}
var
ProcessExitEvent: THandle;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
ProcessExitEvent := OpenEvent(SYNCHRONIZE, true, PChar(Format('Process%8x', [GetCurrentProcessId()])));
if ProcessExitEvent <> 0 then begin
// we have been started by TProcess.run()
CloseHandle(ProcessExitEvent);
ExitEventThread := TProcessExitEventListener.Create();
ExitEventThread.Start();
end;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
function TProcess.PHandle: THandle;
begin
result := FProcess;
end;
{$ENDIF}
function TProcess.PId: {$IFDEF MSWINDOWS}DWORD{$ENDIF}{$IFDEF LINUX}__pid_t{$ENDIF};
begin
result := FPId;
end;
class procedure TProcess.ProcessDied(APId: DWORD);
{$IFDEF MSWINDOWS}
var
i: integer;
proc: IProcess;
exitcode: DWORD;
procList: IInterfaceList;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
procList := TInterfaceList.Create;
ProcessList.Lock;
try
for i := 0 to ProcessList.Count - 1 do begin
proc := IProcess(ProcessList.Items[i]);
if APId = proc.PId then begin
GetExitCodeProcess(proc.PHandle, exitcode);
// cannot be set to exitcode which could be -1, if mains returns with -1
// Avoid zombies
CloseHandle(proc.PHandle);
if proc.Callback <> nil then
proc.Callback.ProcessCallback(proc, pceExited);
procList.Add(proc);
end;
end;
finally
ProcessList.Unlock;
end; { try/finally }
for i := 0 to procList.Count - 1 do
repeat
until ProcessList.Remove(procList[i]) = -1;
{$ENDIF}
end;
{$IFDEF LINUX}
procedure SignalHandler(Sig: Longint); cdecl;
var
pid: __pid_t;
status: Integer;
i: integer;
proc: IProcess;
procList: IInterfaceList;
begin
while True do begin
pid := waitpid(WAIT_ANY, @status, WNOHANG);
if (pid < 0) and (errno() = EINTR) then
Continue;
if (pid < 0) then
Break;
procList := TInterfaceList.Create;
ProcessList.Lock;
try
for i := 0 to ProcessList.Count - 1 do begin
proc := IProcess(ProcessList.Items[i]);
if pid = proc.PId then begin
if proc.Callback <> nil then
proc.Callback.ProcessCallback(proc, pceExited);
procList.Add(proc);
end;
end;
finally
ProcessList.Unlock;
end; { try/finally }
for i := 0 to procList.Count - 1 do
repeat
until ProcessList.Remove(procList[i]) = -1;
end;
end;
{$ENDIF}
function TProcess.Run: boolean;
var
{$IFDEF MSWINDOWS}
startupInfo: TStartupInfo;
processInfo: TProcessInformation;
{$ENDIF}
path: string;
begin
{$IFDEF MSWINDOWS}
StartupInfo.cb := SizeOf(TStartupInfo);
GetStartupInfo(StartupInfo);
StartupInfo.lpReserved := nil;
StartupInfo.lpTitle := nil;
path := ExtractFilePath(Copy(FCommand, 1, Pos(' ', FCommand) - 1));
result := CreateProcess(nil, PChar(FCommand), nil, nil, false, CREATE_NEW_CONSOLE, nil, PChar(path),
StartupInfo, processInfo);
CloseHandle(processInfo.hThread); // must be closed and we don't need it
FProcess := processInfo.hProcess;
FPid := processInfo.dwProcessId;
if result then begin
// Synchronization with waiting thread,
WaitForSingleObject(SignalMutex,INFINITE);
try
InterlockedIncrement(NumOfChildren);
// Insert new Process at the end
ChildProcs[NumOfChildren] := FProcess;
ChildPids[NumOfChildren] := FPid;
// Wake Up the thread
SetEvent(ChildProcs[0]);
if (FRequestExitEvent = 0) then
FRequestExitEvent := CreateEvent(nil, true, false, PChar(Format('Process%8x', [FPid])));
finally
ReleaseMutex(SignalMutex);
end; { try/finally }
result := FPid <> 0;
end
else
result := false;
{$ENDIF}
{$IFDEF LINUX}
FillChar(SigActionRec, SizeOf(TSigAction), 0);
SigActionRec.__sigaction_handler := SignalHandler;
sigaction(SIGCHLD, @SigActionRec, nil);
result := false;
FPid := fork();
if FPid = -1 then
Exit
else if FPid = 0 then begin
path := ExtractFileDir(FCommand);
chdir(path);
execl('/bin/sh', '/bin/sh', '-c', PChar('exec ' + FCommand + ' > /dev/null'), nil);
Halt(1);
end
else
result := true;
{$ENDIF}
end;
class procedure TProcess.Shutdown;
begin
{$IFDEF MSWINDOWS}
if ProcessExitEvent <> 0 then begin
SetEvent(ProcessExitEvent);
end;
{$ENDIF}
end;
{$IFDEF LINUX}
{procedure TProcess.SignalHandler(Sig: Integer);
begin
end;}
{$ENDIF}
procedure TProcess.Terminate;
begin
{$IFDEF MSWINDOWS}
SetEvent(FRequestExitEvent);
{$ENDIF}
{$IFDEF LINUX}
kill(FPid, SIGTERM);
{$ENDIF}
//FCallback := nil;
end;
{ TProcessFactory }
constructor TProcessFactory.Create;
begin
ProcessList := TInterfaceList.Create;
{$IFDEF MSWINDOWS}
SignalMutex := CreateMutex(nil, false, nil);
NumOfChildren := 0;
FillChar(ChildProcs, SizeOf(ChildProcs), 0);
FillChar(ChildPids, SizeOf(ChildPids), 0);
ChildProcs[0] := CreateEvent(nil, false, false, nil);
FWatcher := TProcessReaper.Create();
FWatcher.Start();
{$ENDIF}
end;
function TProcessFactory.CreateProcess(const ACommand: string;
const ACallback: IProcessCallback): IProcess;
begin
result := TProcess.Create(ACommand, ACallback);
end;
destructor TProcessFactory.Destroy;
begin
{$IFDEF MSWINDOWS}
FWatcher.Finish();
SetEvent(ChildProcs[0]);
ReleaseMutex(SignalMutex);
{$ENDIF}
inherited;
end;
{ TProcessReaper }
procedure TProcessReaper.Run;
{$IFDEF MSWINDOWS}
var
rc: DWORD;
pid: integer;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
while true do begin
rc := WaitForMultipleObjects(NumOfChildren + 1, @ChildProcs, false, INFINITE);
if FFinished or (rc = WAIT_TIMEOUT) then
Break;
rc := rc - WAIT_OBJECT_0;
if rc <> 0 then begin
Dec(rc);
// move last proc to the position of terminated proc
// could be the same
WaitForSingleObject(SignalMutex, INFINITE);
try
pid := ChildPids[rc + 1];
ChildProcs[rc + 1] := ChildProcs[NumOfChildren];
ChildPids[rc + 1] := ChildPids[NumOfChildren];
InterlockedDecrement(NumOfChildren);
// Call the "signal_handler"
TProcess.ProcessDied(pid);
finally
ReleaseMutex(SignalMutex);
end; { try/finally }
end;
end; { while }
{$ENDIF}
end;
{ TProcessExitEventListener }
procedure TProcessExitEventListener.Run;
begin
{$IFDEF MSWINDOWS}
ProcessExitEvent := OpenEvent(SYNCHRONIZE, true, PChar(Format('Process%8x', [GetCurrentProcessId()])));
if ProcessExitEvent <> 0 then begin
WaitForSingleObject(ProcessExitEvent, INFINITE);
ResetEvent(ProcessExitEvent);
ORB_Instance.shutdown(false);
ORB_Instance.perform_work();
end;
{$ENDIF}
end;
initialization
finalization
ProcessFactoryVar := nil;
{$IFDEF MSWINDOWS}
ProcessList := nil;
{$ENDIF}
end.
|
unit ParserBaseTestCase;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
FpcUnit, TestRegistry,
WpcScriptParser,
WpcScript,
WpcStatements,
WpcExceptions,
WpcWallpaperStyles;
const
PARSER_TEST_SUITE_NAME = 'Parser';
DEFAULT_PROBABILITY = 100;
DEFAULT_TIMES = 1;
TEST_DEFAULT_DELAY_STRING = '5m';
TEST_DEFAULT_DELAY_VALUE = 5 * 60 * 1000;
TEST_DEFAULT_PROBABILITY_STRING = '50';
TEST_DEFAULT_PROBABILITY_VALUE = 50;
TEST_DEFAULT_TIMES_STRING = '4';
TEST_DEFAULT_TIMES_VALUE = 4;
TEST_DEFAULT_STYLE_STRING = 'STRETCH';
TEST_DEFAULT_STYLE_VALUE = STRETCH;
// Spaces are added for future concatanation of the items.
DELAY_FOR_PROPERTY = ' ' + FOR_KEYWORD + ' ' + TEST_DEFAULT_DELAY_STRING + ' ';
X_TIMES_PROPERTY = ' ' + TEST_DEFAULT_TIMES_STRING + ' ' + TIMES_KEYWORD + ' ';
WITH_PROBABILITY_PROPERTY = ' ' + WITH_KEYWORD + ' ' + PROBABILITY_KEYWORD + ' ' + TEST_DEFAULT_PROBABILITY_STRING + ' ';
STYLE_PROPERTY = ' ' + STYLE_KEYWORD + ' ' + TEST_DEFAULT_STYLE_STRING + ' ';
// Fail test error messages
WRONG_NUMBER_OF_BRANCHES = 'Script has wrong number of branches';
WRONG_NUMBER_OF_SATEMENTS = 'Branch has wrong number of statements';
WRONG_STATEMENT = 'Wrong statement type';
WRONG_STATEMENT_PROPRTY_VALUE = 'Wrong statement property value';
WRONG_SELECTOR_VALUE = 'Wrong selector value';
type
{ TParserBaseTestCase }
TParserBaseTestCase = class(TTestCase)
protected
ScriptLines : TStringList;
Script : TWpcScript;
Parser : TWpcScriptParser;
MainBranchStatements : TListOfBranchStatements;
protected
procedure SetUp(); override;
procedure TearDown(); override;
protected
procedure WrapInMainBranch(Statements : TStringList);
procedure AddEmptyBranch(Statements : TStringList; BranchName : String);
procedure ParseScriptLines();
function GetBranchStatemntsList(BranchName : String) : TListOfBranchStatements;
procedure ReadMainBranchStatementsList();
public
procedure AssertScriptParseExceptionOnParse();
procedure AssertScriptParseExceptionOnParse(Line : Integer);
procedure AssertScriptParseExceptionOnParse(Line : Integer; WordNumber : Integer);
end;
implementation
{ TParserBaseTestCase }
procedure TParserBaseTestCase.SetUp();
begin
ScriptLines := TStringList.Create();
Script := nil;
Parser := nil;
// Shouldn't be freed because it is part of main branch. Will be freed with its script.
MainBranchStatements := nil;
end;
procedure TParserBaseTestCase.TearDown();
begin
if (ScriptLines <> nil) then FreeAndNil(ScriptLines);
if (Script <> nil) then FreeAndNil(Script);
if (Parser <> nil) then FreeAndNil(Parser);
end;
procedure TParserBaseTestCase.WrapInMainBranch(Statements : TStringList);
begin
Statements.Insert(0, BRANCH_KEYWORD + ' ' + MAIN_BARNCH);
Statements.Add(END_KEYWORD + ' ' + BRANCH_KEYWORD);
end;
procedure TParserBaseTestCase.AddEmptyBranch(Statements: TStringList; BranchName: String);
begin
Statements.Add(BRANCH_KEYWORD + ' ' + BranchName);
Statements.Add(END_KEYWORD + ' ' + BRANCH_KEYWORD);
end;
procedure TParserBaseTestCase.ParseScriptLines();
begin
Parser := TWpcScriptParser.Create(ScriptLines);
Parser.CheckScriptResources := False;
Script := Parser.Parse();
end;
{
Returns list of the given branch statements.
Returned list shouldn't be modified or freed by invoker.
}
function TParserBaseTestCase.GetBranchStatemntsList(BranchName : String) : TListOfBranchStatements;
var
Branch : TWpcBranchStatement;
begin
if (Script = nil) then
Fail('Parse script before getting a branch statements.');
Branch := Script.GetBranch(BranchName);
if (Branch = nil) then
Fail('Script does not contain branch: ' + BranchName);
Result := Branch.GetBranchStatements();
end;
{
Sets MainBranchStatements field. It shouldn't be modified or freed by invoker.
}
procedure TParserBaseTestCase.ReadMainBranchStatementsList();
begin
MainBranchStatements := GetBranchStatemntsList(MAIN_BARNCH);
end;
procedure TParserBaseTestCase.AssertScriptParseExceptionOnParse();
begin
AssertScriptParseExceptionOnParse(TWpcScriptParseException.UNKNOWN_LINE, TWpcScriptParseException.UNKNOWN_WORD_NUMBER);
end;
procedure TParserBaseTestCase.AssertScriptParseExceptionOnParse(Line: Integer);
begin
AssertScriptParseExceptionOnParse(Line, TWpcScriptParseException.UNKNOWN_WORD_NUMBER);
end;
{
Performs script parsing and checks that TWpcScriptParseException was thrown at given line and word numbers.
Note, line and word numbers is counted from 0
}
procedure TParserBaseTestCase.AssertScriptParseExceptionOnParse(Line: Integer; WordNumber: Integer);
begin
try
ParseScriptLines();
Fail('An TWpcScriptParseException is expected but nothing was thrown.');
except
on ScriptParsingException : TWpcScriptParseException do begin
if ((Line <> TWpcScriptParseException.UNKNOWN_LINE) and (Line <> ScriptParsingException.Line)) then begin
Fail('The Script parse exception is expected at line ' + IntToStr(Line) + ' of script, ' +
'but occured at line ' + IntToStr(ScriptParsingException.Line) + '. Message: ' + ScriptParsingException.Message);
end;
if ((WordNumber <> TWpcScriptParseException.UNKNOWN_WORD_NUMBER) and (WordNumber <> ScriptParsingException.WordNumer)) then begin
Fail('The Script parse exception is expected at line ' + IntToStr(Line) + ' word ' + IntToStr(WordNumber) + ', ' +
'but occured at line ' + IntToStr(ScriptParsingException.Line) + ' word ' + IntToStr(ScriptParsingException.WordNumer) + '. Message: ' + ScriptParsingException.Message);
end;
end;
on UnexpectedException : Exception do begin
Fail('Unexpected exception: ' + UnexpectedException.ToString());
end;
end;
end;
end.
|
unit BitmapForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FormOperations, ExtDlgs, ExtCtrls, SaveStatusForms;
type
TFormBitmap = class(TSaveStatusForm, IFormOperations)
Image1: TImage;
OpenPictureDialog1: TOpenPictureDialog;
SavePictureDialog1: TSavePictureDialog;
private
{ Private declarations }
public
procedure Load;
procedure Save;
end;
var
FormBitmap: TFormBitmap;
implementation
{$R *.DFM}
{ TFormBitmap }
procedure TFormBitmap.Load;
begin
if OpenPictureDialog1.Execute then
Image1.Picture.LoadFromFile(OpenPictureDialog1.FileName);
end;
procedure TFormBitmap.Save;
begin
if SavePictureDialog1.Execute then
Image1.Picture.SaveToFile(SavePictureDialog1.FileName);
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: StAstroP.pas 4.04 *}
{*********************************************************}
{* SysTools: Astronomical Routines (general Planetary) *}
{*********************************************************}
{$I StDefine.inc}
{ ************************************************************** }
{ Sources: }
{ 1. Astronomical Algorithms, Jean Meeus, Willmann-Bell, 1991. }
{ }
{ 2. Planetary and Lunar Coordinates (1984-2000), U.S. Govt, }
{ 1983. }
{ }
{ 3. Supplement to the American Ephemeris and Nautical Almanac,}
{ U.S. Govt, 1964. }
{ }
{ 4. MPO96-MPO98 source files, Brian D. Warner, 1995-2000. }
{ }
{ ************************************************************** }
unit StAstroP;
interface
const
StdDate = 2451545.0; {Ast. Julian Date for J2000 Epoch}
OB2000 = 0.409092804; {J2000 obliquity of the ecliptic (radians)}
type
TStEclipticalCord = packed record
L0,
B0,
R0 : Double;
end;
TStRectangularCord = packed record
X,
Y,
Z : Double;
end;
TStPlanetsRec = packed record
RA,
DC,
Elong : Double;
end;
TStPlanetsArray = array[1..8] of TStPlanetsRec;
procedure PlanetsPos(JD : Double; var PA : TStPlanetsArray);
implementation
uses
Windows,
StDate, StMerc, StVenus, StMars, StJup, StSaturn, StUranus, StNeptun,
StPluto, StMath;
var
PlanEC : TStEclipticalCord;
PlanRC,
SunRC : TStRectangularCord;
SunEQ : TStPlanetsRec;
{--------------------------------------------------------------------------}
function RealAngle(Value2, Value1, Start : Double) : Double;
begin
Result := Start;
if (Value1 = 0) then begin
if Value2 > 0 then
Result := Pi / 2.0
else
Result := 3.0 * Pi / 2.0;
end else begin
if (Value2 > 0.0) then begin
if (Value1 < 0.0) then
Result := Start + Pi
else
Result := Start;
end else begin
if (Value2 = 0) then begin
if Value1 > 0 then
Result := 0
else
Result := Pi;
end else begin
if (Value2 < 0) then begin
if (Value1 < 0) then
Result := Start + Pi
else
Result := Start + (2.0 * Pi)
end;
end;
end;
end;
end;
{--------------------------------------------------------------------------}
function SunOfDate(JD : Double) : TStRectangularCord;
{-compute J2000 XYZ coordinates of the Sun}
var
T0,
A,
L,
B,
RV,
TX,
TY,
TZ : Double;
begin
T0 := (JD - StdDate) / 365250;
{solar longitude}
L := 175347046
+ 3341656 * cos(4.6692568 + 6283.07585*T0)
+ 34894 * cos(4.6261000 + 12566.1517*T0)
+ 3497 * cos(2.7441000 + 5753.3849*T0)
+ 3418 * cos(2.8289000 + 3.5231*T0)
+ 3136 * cos(3.6277000 + 77713.7715*T0)
+ 2676 * cos(4.4181000 + 7860.4194*T0)
+ 2343 * cos(6.1352000 + 3930.2097*T0)
+ 1324 * cos(0.7425000 + 11506.7698*T0)
+ 1273 * cos(2.0371000 + 529.6910*T0)
+ 1199 * cos(1.1096000 + 1577.3435*T0)
+ 990 * cos(5.2330000 + 5884.9270*T0)
+ 902 * cos(2.0450000 + 26.1490*T0)
+ 857 * cos(3.5080000 + 398.149*T0)
+ 780 * cos(1.1790000 + 5223.694*T0)
+ 753 * cos(2.5330000 + 5507.553*T0)
+ 505 * cos(4.5830000 + 18849.228*T0)
+ 492 * cos(4.2050000 + 775.523*T0)
+ 357 * cos(2.9200000 + 0.067*T0)
+ 317 * cos(5.8490000 + 11790.626*T0)
+ 284 * cos(1.8990000 + 796.298*T0)
+ 271 * cos(0.3150000 + 10977.079*T0)
+ 243 * cos(0.3450000 + 5486.778*T0)
+ 206 * cos(4.8060000 + 2544.314*T0)
+ 205 * cos(1.8690000 + 5573.143*T0)
+ 202 * cos(2.4580000 + 6069.777*T0)
+ 156 * cos(0.8330000 + 213.299*T0)
+ 132 * cos(3.4110000 + 2942.463*T0)
+ 126 * cos(1.0830000 + 20.775*T0)
+ 115 * cos(0.6450000 + 0.980*T0)
+ 103 * cos(0.6360000 + 4694.003*T0)
+ 102 * cos(0.9760000 + 15720.839*T0)
+ 102 * cos(4.2670000 + 7.114*T0)
+ 99 * cos(6.2100000 + 2146.170*T0)
+ 98 * cos(0.6800000 + 155.420*T0)
+ 86 * cos(5.9800000 +161000.690*T0)
+ 85 * cos(1.3000000 + 6275.960*T0)
+ 85 * cos(3.6700000 + 71430.700*T0)
+ 80 * cos(1.8100000 + 17260.150*T0);
A := 628307584999.0
+ 206059 * cos(2.678235 + 6283.07585*T0)
+ 4303 * cos(2.635100 + 12566.1517*T0)
+ 425 * cos(1.590000 + 3.523*T0)
+ 119 * cos(5.796000 + 26.298*T0)
+ 109 * cos(2.966000 + 1577.344*T0)
+ 93 * cos(2.590000 + 18849.23*T0)
+ 72 * cos(1.140000 + 529.69*T0)
+ 68 * cos(1.870000 + 398.15*T0)
+ 67 * cos(4.410000 + 5507.55*T0)
+ 59 * cos(2.890000 + 5223.69*T0)
+ 56 * cos(2.170000 + 155.42*T0)
+ 45 * cos(0.400000 + 796.30*T0)
+ 36 * cos(0.470000 + 775.52*T0)
+ 29 * cos(2.650000 + 7.11*T0)
+ 21 * cos(5.340000 + 0.98*T0)
+ 19 * cos(1.850000 + 5486.78*T0)
+ 19 * cos(4.970000 + 213.30*T0)
+ 17 * cos(2.990000 + 6275.96*T0)
+ 16 * cos(0.030000 + 2544.31*T0);
L := L + (A * T0);
A := 8722 * cos(1.0725 + 6283.0758*T0)
+ 991 * cos(3.1416)
+ 295 * cos(0.437 + 12566.1520*T0)
+ 27 * cos(0.050 + 3.52*T0)
+ 16 * cos(5.190 + 26.30*T0)
+ 16 * cos(3.69 + 155.42*T0)
+ 9 * cos(0.30 + 18849.23*T0)
+ 9 * cos(2.06 + 77713.77*T0);
L := L + (A * sqr(T0));
A := 289 * cos(5.842 + 6283.076*T0)
+ 21 * cos(6.05 + 12566.15*T0)
+ 3 * cos(5.20 + 155.42*T0)
+ 3 * cos(3.14);
L := L + (A * sqr(T0) * T0);
L := L / 1.0E+8;
{solar latitude}
B := 280 * cos(3.199 + 84334.662*T0)
+ 102 * cos(5.422 + 5507.553*T0)
+ 80 * cos(3.88 + 5223.69*T0)
+ 44 * cos(3.70 + 2352.87*T0)
+ 32 * cos(4.00 + 1577.34*T0);
B := B / 1.0E+8;
A := 227778 * cos(3.413766 + 6283.07585*T0)
+ 3806 * cos(3.3706 + 12566.1517*T0)
+ 3620
+ 72 * cos(3.33 + 18849.23*T0)
+ 8 * cos(3.89 + 5507.55*T0)
+ 8 * cos(1.79 + 5223.69*T0)
+ 6 * cos(5.20 + 2352.87*T0);
B := B + (A * T0 / 1.0E+8);
A := 9721 * cos(5.1519 + 6283.07585*T0)
+ 233 * cos(3.1416)
+ 134 * cos(0.644 + 12566.152*T0)
+ 7 * cos(1.07 + 18849.23*T0);
B := B + (A * sqr(T0) / 1.0E+8);
A := 276 * cos(0.595 + 6283.076*T0)
+ 17 * cos(3.14)
+ 4 * cos(0.12 + 12566.15*T0);
B := B + (A * sqr(T0) * T0 / 1.0E+8);
{solar radius vector (astronomical units)}
RV := 100013989
+ 1670700 * cos(3.0984635 + 6283.07585*T0)
+ 13956 * cos(3.05525 + 12566.15170*T0)
+ 3084 * cos(5.1985 + 77713.7715*T0)
+ 1628 * cos(1.1739 + 5753.3849*T0)
+ 1576 * cos(2.8649 + 7860.4194*T0)
+ 925 * cos(5.453 + 11506.770*T0)
+ 542 * cos(4.564 + 3930.210*T0)
+ 472 * cos(3.661 + 5884.927*T0)
+ 346 * cos(0.964 + 5507.553*T0)
+ 329 * cos(5.900 + 5223.694*T0)
+ 307 * cos(0.299 + 5573.143*T0)
+ 243 * cos(4.273 + 11790.629*T0)
+ 212 * cos(5.847 + 1577.344*T0)
+ 186 * cos(5.022 + 10977.079*T0)
+ 175 * cos(3.012 + 18849.228*T0)
+ 110 * cos(5.055 + 5486.778*T0)
+ 98 * cos(0.89 + 6069.78*T0)
+ 86 * cos(5.69 + 15720.84*T0)
+ 86 * cos(1.27 +161000.69*T0)
+ 65 * cos(0.27 + 17260.15*T0)
+ 63 * cos(0.92 + 529.69*T0)
+ 57 * cos(2.01 + 83996.85*T0)
+ 56 * cos(5.24 + 71430.70*T0)
+ 49 * cos(3.25 + 2544.31*T0)
+ 47 * cos(2.58 + 775.52*T0)
+ 45 * cos(5.54 + 9437.76*T0)
+ 43 * cos(6.01 + 6275.96*T0)
+ 39 * cos(5.36 + 4694.00*T0)
+ 38 * cos(2.39 + 8827.39*T0)
+ 37 * cos(0.83 + 19651.05*T0)
+ 37 * cos(4.90 + 12139.55*T0)
+ 36 * cos(1.67 + 12036.46*T0)
+ 35 * cos(1.84 + 2942.46*T0)
+ 33 * cos(0.24 + 7084.90*T0)
+ 32 * cos(0.18 + 5088.63*T0)
+ 32 * cos(1.78 + 398.15*T0)
+ 28 * cos(1.21 + 6286.60*T0)
+ 28 * cos(1.90 + 6279.55*T0)
+ 26 * cos(4.59 + 10447.39*T0);
RV := RV / 1.0E+8;
A := 103019 * cos(1.107490 + 6283.075850*T0)
+ 1721 * cos(1.0644 + 12566.1517*T0)
+ 702 * cos(3.142)
+ 32 * cos(1.02 + 18849.23*T0)
+ 31 * cos(2.84 + 5507.55*T0)
+ 25 * cos(1.32 + 5223.69*T0)
+ 18 * cos(1.42 + 1577.34*T0)
+ 10 * cos(5.91 + 10977.08*T0)
+ 9 * cos(1.42 + 6275.96*T0)
+ 9 * cos(0.27 + 5486.78*T0);
RV := RV + (A * T0 / 1.0E+8);
A := 4359 * cos(5.7846 + 6283.0758*T0)
+ 124 * cos(5.579 + 12566.152*T0)
+ 12 * cos(3.14)
+ 9 * cos(3.63 + 77713.77*T0)
+ 6 * cos(1.87 + 5573.14*T0)
+ 3 * cos(5.47 + 18849.23*T0);
RV := RV + (A * sqr(T0) / 1.0E+8);
L := (L + PI);
L := Frac(L / 2.0 / PI) * 2.0 * Pi;
if L < 0 then
L := L + (2.0*PI);
B := -B;
TX := RV * cos(B) * cos(L);
TY := RV * cos(B) * sin(L);
TZ := RV * sin(B);
Result.X := TX + 4.40360E-7 * TY - 1.90919E-7 * TZ;
Result.Y := -4.79966E-7 * TX + 0.917482137087 * TY - 0.397776982902 * TZ;
Result.Z := 0.397776982902 * TY + 0.917482137087 * TZ;
end;
{--------------------------------------------------------------------------}
function EclipticToRectangular(Longitude, Latitude,
RadiusVector : Double) : TStRectangularCord;
var
var1,
var2,
var3 : Double;
begin
var1 := RadiusVector * cos(Longitude) * cos(Latitude);
var2 := RadiusVector * sin(Longitude) * cos(Latitude);
var3 := RadiusVector * sin(Latitude);
Result.X := var1;
Result.Y := var2 * cos(OB2000) - var3 * sin(OB2000);
Result.Z := var2 * sin(OB2000) + var3 * cos(OB2000);
end;
{--------------------------------------------------------------------------}
function RADec(Planet, Sun : TStRectangularCord;
ComputeElong : Boolean) : TStPlanetsRec;
var
var1,
var2,
var3,
var4,
var5 : Double;
begin
FillChar(Result, SizeOf(TStPlanetsRec), #0);
var1 := Sun.X + Planet.X;
var2 := Sun.Y + Planet.Y;
var3 := Sun.Z + Planet.Z;
var4 := arctan(var2/var1);
var4 := RealAngle(var2, var1, var4) * radcor;
var5 := sqrt(sqr(var1) + sqr(var2) + sqr(var3));
var3 := StInvsin(var3/var5) * radcor;
Result.RA := var4;
Result.DC := var3;
var4 := Result.RA / radcor;
var3 := Result.DC / radcor;
if (ComputeElong) then begin
var1 := sin(SunEQ.DC/radcor) * sin(var3);
var2 := cos(SunEQ.DC/radcor) * cos(var3) * cos(SunEQ.RA/radcor - var4);
Result.Elong := StInvcos(var1+var2) * radcor;
end;
end;
{--------------------------------------------------------------------------}
function MercuryPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeMercury(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function VenusPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeVenus(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function MarsPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeMars(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function JupiterPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeJupiter(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function SaturnPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeSaturn(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function UranusPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeUranus(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function NeptunePosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputeNeptune(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
function PlutoPosition(JD : Double) : TStPlanetsRec;
begin
PlanEC := ComputePluto(JD);
PlanRC := EclipticToRectangular(PlanEC.L0, PlanEC.B0, PlanEC.R0);
Result := RADec(PlanRC, SunRC, True);
end;
{--------------------------------------------------------------------------}
procedure PlanetsPos(JD : Double; var PA : TStPlanetsArray);
var
I : Integer;
Sun : TStRectangularCord;
begin
{find Sun's Rectangular Coordinates}
SunRC := SunofDate(JD);
FillChar(SunEQ, SizeOf(TStPlanetsRec), #0);
FillChar(Sun, SizeOf(TStRectangularCord), #0);
{find Sun's RA/Dec}
SunEQ := RADec(SunRC, Sun, False);
PA[1] := PlutoPosition(JD);
{find RA/Dec of each planet}
for I := 1 to 8 do begin
case I of
1 : PA[I] := MercuryPosition(JD);
2 : PA[I] := VenusPosition(JD);
3 : PA[I] := MarsPosition(JD);
4 : PA[I] := JupiterPosition(JD);
5 : PA[I] := SaturnPosition(JD);
6 : PA[I] := UranusPosition(JD);
7 : PA[I] := NeptunePosition(JD);
8 : PA[I] := PlutoPosition(JD);
end;
end;
end;
end.
|
unit MdiChilds.ComponentCreate;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, MDIChilds.CustomDialog,
System.ImageList, Vcl.ImgList, System.Actions, Vcl.ActnList,
Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnMan, Vcl.ToolWin, Vcl.ActnCtrls,
Vcl.ExtCtrls, Vcl.StdCtrls, JvBaseDlg, JvSelectDirectory, MdiChilds.ProgressForm, FWZipWriter, GlobalData, MdiChilds.Reg;
type
TFmComponentCreate = class(TFmProcess)
rgOptions: TRadioGroup;
edtFullCaption: TLabeledEdit;
edtGroup: TLabeledEdit;
lbItems: TListBox;
Panel1: TPanel;
tbMain: TActionToolBar;
amMain: TActionManager;
acAddFolder: TAction;
acAddFile: TAction;
ilMain: TImageList;
acDeleteItem: TAction;
acClear: TAction;
JvSelectDirectory: TJvSelectDirectory;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
procedure acAddFolderExecute(Sender: TObject);
procedure acAddFileExecute(Sender: TObject);
procedure acDeleteItemExecute(Sender: TObject);
procedure acClearExecute(Sender: TObject);
private
{ Private declarations }
protected
procedure DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean); override;
public
{ Public declarations }
end;
var
FmComponentCreate: TFmComponentCreate;
implementation
{$R *.dfm}
procedure TFmComponentCreate.acAddFileExecute(Sender: TObject);
begin
if OpenDialog.Execute then
if lbItems.Items.IndexOf(OpenDialog.FileName) = -1 then
lbItems.Items.Add(OpenDialog.FileName);
end;
procedure TFmComponentCreate.acAddFolderExecute(Sender: TObject);
begin
if JvSelectDirectory.Execute then
if lbItems.Items.IndexOf(JvSelectDirectory.Directory) = -1 then
lbItems.Items.Add(JvSelectDirectory.Directory);
end;
procedure TFmComponentCreate.acClearExecute(Sender: TObject);
begin
lbItems.Clear;
end;
procedure TFmComponentCreate.acDeleteItemExecute(Sender: TObject);
begin
lbItems.DeleteSelected;
end;
procedure TFmComponentCreate.DoOk(Sender: TObject; ProgressForm: TFmProgress;
var ShowMessage: Boolean);
var
TargetDir, ZipFolder: string;
Zip: TFWZipWriter;
I: Integer;
SR: TSearchRec;
begin
Assert(edtFullCaption.Text <> '','Не заполнено наименование компонента');
case rgOptions.ItemIndex of
0: begin TargetDir := TempDir + 'Plugins\'; ZipFolder := TargetDir; end;
1: begin TargetDir := TempDir; ZipFolder := ''; end;
2:
begin
Assert(edtGroup.Text <> '', 'Не заполнена группа');
TargetDir := TempDir+ 'Components\'+edtGroup.Text+'\'+edtFullCaption.Text+'\';
ZipFolder := TempDir +'Components\';
end;
end;
Assert(lbItems.Count <> 0, 'Нет данных для создания компонента');
ForceDirectories(TargetDir);
for I := 0 to lbItems.Count - 1 do
begin
if not FileExists(lbItems.Items[I]) then
FullDirectoryCopy(lbItems.Items[I], TargetDir, False, True)
else
CopyFile(PChar(lbItems.Items[I]), PChar(TargetDir + ExtractFileName(lbItems.Items[I])), False);
end;
Zip := TFWZipWriter.Create;
try
Zip.AlwaysAddEmptyFolder := True;
if ZipFolder <> '' then
Zip.AddFolder(ZipFolder)
else
begin
if FindFirst(TempDir + '*', faAnyFile, SR) = 0 then
begin
repeat
Zip.AddFile(TempDir+SR.Name);
until FindNext(SR) <> 0;
FindClose(SR);
end;
end;
if SaveDialog.Execute then
Zip.BuildZip(SaveDialog.FileName);
finally
Zip.Free;
end;
//FullRemoveDir(TempDir, True, False, False);
ShowMessage := FullRemoveDir(TempDir, True, False, False);
end;
begin
FormsRegistrator.RegisterForm(TFmComponentCreate, 'Создать компонент','Системные утилиты', False, dpkTools, '/CREATECOMPONENT');
end.
|
unit evEmptyTableEliminator;
{* Фильтр, выкидывающий пустые таблицы }
// Модуль: "w:\common\components\gui\Garant\EverestCommon\evEmptyTableEliminator.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TevEmptyTableEliminator" MUID: (4CF7B733015E)
{$Include w:\common\components\gui\Garant\EverestCommon\evDefine.inc}
interface
uses
l3IntfUses
, evdBufferedFilter
, l3Variant
, k2Base
;
type
TevEmptyTableEliminator = class(TevdBufferedFilter)
{* Фильтр, выкидывающий пустые таблицы }
private
f_WasSomeLeaf: Boolean;
protected
procedure StartChild(TypeID: Tl3Type); override;
procedure OpenStream; override;
{* вызывается один раз при начале генерации. Для перекрытия в потомках. }
procedure DoStartChild(TypeID: Tk2Type); override;
function NeedStartBuffering(aID: Integer): Boolean; override;
function NeedFlushBuffer(aLeaf: Tl3Variant;
aTagId: Integer): Boolean; override;
procedure DoFlushBuffer(aLeaf: Tl3Variant;
aTagId: Integer;
aNeedCloseBracket: Boolean); override;
end;//TevEmptyTableEliminator
implementation
uses
l3ImplUses
, LeafPara_Const
, Table_Const
, SBS_Const
, k2Facade
, ParaList_Const
, TableCell_Const
//#UC START# *4CF7B733015Eimpl_uses*
//#UC END# *4CF7B733015Eimpl_uses*
;
procedure TevEmptyTableEliminator.StartChild(TypeID: Tl3Type);
//#UC START# *4836D4650177_4CF7B733015E_var*
//#UC END# *4836D4650177_4CF7B733015E_var*
begin
//#UC START# *4836D4650177_4CF7B733015E_impl*
if (SkipLevel > 0) then
begin
if not f_WasSomeLeaf then
begin
if TypeID.IsKindOf(k2_typLeafPara) then
f_WasSomeLeaf := true;
end//not f_WasSomeLeaf
else
if (SkipLevel = 2) then
begin
StopBufferingAndFlush(False, TopObject[0], False);
f_WasSomeLeaf := false;
end;//SkipLevel = 2
end;//SkipLevel > 0
inherited;
//#UC END# *4836D4650177_4CF7B733015E_impl*
end;//TevEmptyTableEliminator.StartChild
procedure TevEmptyTableEliminator.OpenStream;
{* вызывается один раз при начале генерации. Для перекрытия в потомках. }
//#UC START# *4836D49800CA_4CF7B733015E_var*
//#UC END# *4836D49800CA_4CF7B733015E_var*
begin
//#UC START# *4836D49800CA_4CF7B733015E_impl*
inherited;
f_WasSomeLeaf := false;
//#UC END# *4836D49800CA_4CF7B733015E_impl*
end;//TevEmptyTableEliminator.OpenStream
procedure TevEmptyTableEliminator.DoStartChild(TypeID: Tk2Type);
//#UC START# *4A2D1217037A_4CF7B733015E_var*
//#UC END# *4A2D1217037A_4CF7B733015E_var*
begin
//#UC START# *4A2D1217037A_4CF7B733015E_impl*
inherited;
//#UC END# *4A2D1217037A_4CF7B733015E_impl*
end;//TevEmptyTableEliminator.DoStartChild
function TevEmptyTableEliminator.NeedStartBuffering(aID: Integer): Boolean;
//#UC START# *4C56D54B002A_4CF7B733015E_var*
//#UC END# *4C56D54B002A_4CF7B733015E_var*
begin
//#UC START# *4C56D54B002A_4CF7B733015E_impl*
Result := (aID = -k2_idTable) OR (aID = -k2_idSBS);
if Result then
f_WasSomeLeaf := false;
//#UC END# *4C56D54B002A_4CF7B733015E_impl*
end;//TevEmptyTableEliminator.NeedStartBuffering
function TevEmptyTableEliminator.NeedFlushBuffer(aLeaf: Tl3Variant;
aTagId: Integer): Boolean;
//#UC START# *4CF7BC520161_4CF7B733015E_var*
procedure CheckEmptyLists(aList : Tl3Variant);
var
l_Index : Integer;
l_Child : Tl3Variant;
begin//CheckEmptyLists
l_Index := 0;
while (l_Index < aList.ChildrenCount) do
begin
l_Child := aList.Child[l_Index];
if l_Child.IsKindOf(k2_typParaList) then
begin
CheckEmptyLists(l_Child);
if (l_Child.ChildrenCount = 0) then
begin
if not l_Child.IsKindOf(k2_typTableCell) then
begin
aList.DeleteChild(l_Index);
continue;
end;//not l_Child.IsKindOf(k2_typTableCell)
end;//l_Child.ChildrenCount = 0
end;//l_Child.IsKindOf(k2_typParaList)
Inc(l_Index);
end;//l_Index < aList.ChildrenCount
end;//CheckEmptyLists
//#UC END# *4CF7BC520161_4CF7B733015E_var*
begin
//#UC START# *4CF7BC520161_4CF7B733015E_impl*
Result := f_WasSomeLeaf;
if Result then
CheckEmptyLists(aLeaf);
//#UC END# *4CF7BC520161_4CF7B733015E_impl*
end;//TevEmptyTableEliminator.NeedFlushBuffer
procedure TevEmptyTableEliminator.DoFlushBuffer(aLeaf: Tl3Variant;
aTagId: Integer;
aNeedCloseBracket: Boolean);
//#UC START# *4CF7BEC40130_4CF7B733015E_var*
//#UC END# *4CF7BEC40130_4CF7B733015E_var*
begin
//#UC START# *4CF7BEC40130_4CF7B733015E_impl*
inherited;
f_WasSomeLeaf := false;
//#UC END# *4CF7BEC40130_4CF7B733015E_impl*
end;//TevEmptyTableEliminator.DoFlushBuffer
end.
|
PROGRAM Complex;
TYPE
complex = RECORD
re, im : real
END;
mystring = ARRAY[1..3] OF char;
VAR
x, y, z : complex;
PROCEDURE print(name : mystring; VAR z : complex);
BEGIN
write(name, ' = (', z.re:0:5, ', ', z.im:0:5, ') ');
END;
PROCEDURE add(VAR x, y, z : complex);
BEGIN
z.re := x.re + y.re;
z.im := x.im + y.im;
END;
PROCEDURE subtract(VAR x, y, z : complex);
BEGIN
z.re := x.re - y.re;
z.im := x.im - y.im;
END;
PROCEDURE multiply(VAR x, y, z: complex);
BEGIN
z.re := x.re*y.re - x.im*y.im;
z.im := x.re*y.im + x.im*y.re;
END;
PROCEDURE divide(VAR x, y, z : complex);
VAR
denom : real;
BEGIN
denom := sqr(y.re) + sqr(y.im);
z.re := (x.re*y.re + x.im*y.im)/denom;
z.im := (x.im*y.re - x.re*y.im)/denom;
END;
BEGIN {ComplexTest}
x.re := 3; x.im := 2; print(' x', x);
y.re := 8; y.im := -5; print(' y', y);
add(x, y, z); print('x+y', z);
writeln;
print(' x', x);
print(' y', y);
subtract(x, y, z); print('x-y', z);
writeln;
x.re := 4; x.im := -2; print(' x', x);
y.re := 1; y.im := -5; print(' y', y);
multiply(x, y, z); print('x*y', z);
writeln;
x.re := -3; x.im := 2; print(' x', x);
y.re := 3; y.im := -6; print(' y', y);
divide(x, y, z); print('x/y', z);
writeln;
x.re := 5; x.im := 0; print(' x', x);
y.re := 3; y.im := 2; print(' y', y);
add(x, y, z); print('x+y', z);
writeln;
x.re := 5; x.im := 4; print(' x', x);
y.re := 2; y.im := 0; print(' y', y);
multiply(x, y, z); print('x*y', z);
writeln;
x.re := -2; x.im := -4; print(' x', x);
y.re := 0; y.im := 1; print(' y', y);
divide(x, y, z); print('x/y', z);
writeln;
END {ComplexTest}.
|
{
ICS TWSocket descendant that performs TLS communication by means of
Windows SChannel.
Automatically processes SChannel connection bug.
Supports establishing and finishing TLS channel over existing connection.
Requires at least **ICS V8.66 - Part 10** for HTTP tunnel support. For older
versions either:
- Comment out usage of `HttpTunnelState`
- Modify ICS `TCustomHttpTunnelWSocket` class to have public `HttpTunnelState` property:
`property HttpTunnelState : THttpTunnelState read FHttpTunnelState;`
(c) Fr0sT-Brutal
License MIT
}
unit SChannel.IcsWSocket;
interface
uses
SysUtils, Classes, Windows, WinSock,
SChannel.JwaWinError, SChannel.JwaSspi,
OverbyteIcsWSocket, OverbyteIcsWSockBuf, OverbyteIcsLogger, OverbyteIcsUtils,
SChannel.Utils;
const
WS_OK = 0; // WinSock success code
type
// ICS TWSocket descendant supporting TLS
TSChannelWSocket = class(TWSocket)
strict protected
FSecure: Boolean;
FChannelState: TChannelState;
FSessionData: TSessionData;
FHandShakeData: THandShakeData;
FhContext: CtxtHandle;
FHandshakeBug: Boolean;
FPrevFlags: TSessionFlags; // previous state of session flags
FAddrIsIP: Boolean;
FSendBuffer: TBytes; // buffer that receives encrypted data to be sent
FRecvBuffer: TBuffer; // buffer that receives encrypted data from server
FDecrBuffer: TBuffer; // buffer that receives decrypted data from server
FSizes: SecPkgContext_StreamSizes;
FPayloadReadCount : Int64; // counters of unencrypted (payload) traffic
FPayloadWriteCount: Int64;
// event handlers
FOnTLSDone: TNotifyEvent;
FOnTLSShutdown: TNotifyEvent;
// overrides
procedure AssignDefaultValue; override;
procedure TriggerSessionConnectedSpecial(Error : Word); override;
function TriggerDataAvailable(Error : Word) : Boolean; override;
procedure TriggerSessionClosed(Error: Word); override;
function GetRcvdCount : LongInt; override;
function DoRecv(var Buffer : TWSocketData;
BufferSize : Integer;
Flags : Integer) : Integer; override;
function RealSend(var Data : TWSocketData; Len : Integer) : Integer; override;
// new methods
procedure SChannelHandshakeLog(const Msg: string);
procedure SChannelLog(LogOption : TLogOption; const Msg: string);
procedure DoHandshakeStart;
procedure DoHandshakeProcess;
procedure DoHandshakeSuccess;
procedure StartTLS;
procedure ShutdownTLS;
procedure SetSecure(const Value: Boolean);
procedure SetSessionData(const SessionData: TSessionData);
public
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure Listen; override;
procedure Shutdown(How : Integer); override;
procedure PostFD_EVENT(Event: Cardinal);
published
// Indicates whether TLS is currently used. Effect of setting the property
// depends on current state. @br
// Socket is **not** connected:
// - Setting @name to @True: TLS handshake will be established
// automatically as soon as socket is connected.
// - Setting @name to @False: work as usual (no TLS)
//
// Socket **is** connected:
// - Setting @name to @True: TLS handshake will be started immediately
// over existing connection
// - Setting @name to @False: TLS shutdown will be executed immediately
// without closing the connection
property Secure: Boolean read FSecure write SetSecure;
// Traffic counter for incoming payload.
// `TWSocket.ReadCount` property reflects encrypted traffic
property PayloadReadCount: Int64 read FPayloadReadCount;
// Traffic counter for outgoing payload.
// `TWSocket.WriteCount` property reflects encrypted traffic
property PayloadWriteCount: Int64 read FPayloadWriteCount;
// TLS Session data that allows fine tuning of TLS handshake. Also it could
// contain shared credentials used by multiple sockets. Fields must be
// assigned before starting TLS handshake (otherwise exception is raised).
// Note that some fields are assigned internally based on other values
// (f.ex., `sfNoServerVerify` flag is enabled if connecting to IP).
// Initial values are returned when secure connection is finished.
// ! Session data is finalized in destructor, closing and zeroing any
// non-shared handles.
property SessionData: TSessionData read FSessionData write SetSessionData;
// Event is called when TLS handshake is established successfully
property OnTLSDone: TNotifyEvent read FOnTLSDone write FOnTLSDone;
// Event is called when TLS handshake is shut down
property OnTLSShutdown: TNotifyEvent read FOnTLSShutdown write FOnTLSShutdown;
end;
implementation
const
S_E_HandshakeTDAErr = 'Handshake - ! error [%d] in TriggerDataAvailable';
S_E_SettingSessionDataChannelActive = 'Setting SessionData is prohibited when secure channel is active';
S_E_SettingSessionDataHostsDiffer = 'Error setting SessionData: socket is connected and hosts differ (%s and %s)';
// Check if address is a dotted numeric address like 192.161.124.32
function AddrIsIP(const Addr: string): Boolean;
var
IPAddr : u_long;
begin
IPAddr := WSocket_inet_addr(PAnsiChar(AnsiString(Addr)));
Result := (IPAddr <> u_long(INADDR_NONE));
end;
constructor TSChannelWSocket.Create(AOwner: TComponent);
begin
SChannel.Utils.Init;
inherited Create(AOwner);
end;
destructor TSChannelWSocket.Destroy;
begin
inherited;
FinSession(FSessionData);
end;
// Cleanup on creation and before connection
procedure TSChannelWSocket.AssignDefaultValue;
begin
inherited;
FChannelState := chsNotStarted;
FHandShakeData := Default(THandShakeData);
DeleteContext(FhContext);
FHandshakeBug := False;
FSendBuffer := nil;
FRecvBuffer := Default(TBuffer);
FDecrBuffer := Default(TBuffer);
FSizes := Default(SecPkgContext_StreamSizes);
FPayloadReadCount := 0;
FPayloadWriteCount := 0;
FPrevFlags := [];
FAddrIsIP := False;
end;
// Get the number of bytes received, decrypted and waiting to be read
function TSChannelWSocket.GetRcvdCount: LongInt;
begin
if FChannelState = chsEstablished then
Result := FRecvBuffer.DataLen
else
Result := inherited GetRcvdCount;
end;
// Actual receive data
function TSChannelWSocket.DoRecv(var Buffer: TWSocketData; BufferSize,
Flags: Integer): Integer;
// Copies already decrypted data from FDecrBuffer to Buffer
// Uses external variables: Buffer, BufferSize
function RecvFromBuffer: Integer;
begin
if Integer(FDecrBuffer.DataLen) < BufferSize then
Result := FDecrBuffer.DataLen
else
Result := BufferSize;
Move(FDecrBuffer.Data[FDecrBuffer.DataStartIdx], Buffer^, Result);
Inc(FDecrBuffer.DataStartIdx, Result);
Dec(FDecrBuffer.DataLen, Result);
Inc(FPayloadReadCount, Result);
end;
var
res: Integer;
pFreeSpace: TWSocketData;
scRet: SECURITY_STATUS;
cbWritten: DWORD;
begin
// SChannel not used or not established yet - call inherited to receive raw
if FChannelState <> chsEstablished then
begin
Result := inherited;
Exit;
end;
// There's already decrypted data in buffer - copy from it and imitate FD_READ event
if FDecrBuffer.DataLen > 0 then
begin
Result := RecvFromBuffer;
if FState = wsConnected then
PostFD_EVENT(FD_READ);
Exit;
end;
// Handshake established - receive and decrypt
// Here we're sure that FDecrBuffer is empty
FDecrBuffer.DataStartIdx := 0;
// For some mysterious reason DoRecv requires "var"...
// In FRecvBuffer data always starts from the beginning
pFreeSpace := Pointer(@FRecvBuffer.Data[FRecvBuffer.DataLen]);
res := inherited DoRecv(pFreeSpace, Length(FRecvBuffer.Data) - Integer(FRecvBuffer.DataLen), Flags);
if res <= 0 then
Exit(res);
Inc(FRecvBuffer.DataLen, res);
scRet := DecryptData(
FhContext, FSizes, Pointer(FRecvBuffer.Data), FRecvBuffer.DataLen,
Pointer(FDecrBuffer.Data), Length(FDecrBuffer.Data), cbWritten);
case scRet of
SEC_E_OK, SEC_E_INCOMPLETE_MESSAGE, SEC_I_CONTEXT_EXPIRED:
begin
SChannelLog(loSslDump, Format(S_Msg_Received, [res, cbWritten]));
if scRet = SEC_I_CONTEXT_EXPIRED then
SChannelLog(loSslInfo, S_Msg_SessionClosed);
FDecrBuffer.DataLen := cbWritten;
Result := RecvFromBuffer;
end;
SEC_I_RENEGOTIATE:
begin
SChannelLog(loSslInfo, S_Msg_Renegotiate);
DoHandshakeStart;
Result := 0;
end;
else
Result := SOCKET_ERROR; // shouldn't happen
end; // case
end;
// Actual send data
function TSChannelWSocket.RealSend(var Data : TWSocketData; Len : Integer) : Integer;
var
EncryptedLen: Cardinal;
Sent: Integer;
begin
// SChannel not used or not established yet - call inherited to send raw
if FChannelState <> chsEstablished then
begin
Result := inherited;
Exit;
end;
// Handshake established - encrypt and send
EncryptData(FhContext, FSizes, Data, Len, PByte(FSendBuffer), Length(FSendBuffer), EncryptedLen);
SChannelLog(loSslDump, Format(S_Msg_Sending, [Len, EncryptedLen]));
Sent := inherited RealSend(TWSocketData(FSendBuffer), EncryptedLen);
if Sent <= 0 then
begin
raise ESSPIError.CreateWinAPI('sending payload to server', 'Send', WSocket_WSAGetLastError);
Result := Sent;
Exit;
end;
Inc(FPayloadWriteCount, Sent);
// ! Return length of payload
Result := Len;
end;
// Socket connected - internal event. Start handshake
procedure TSChannelWSocket.TriggerSessionConnectedSpecial(Error: Word);
begin
{ Error occured / no SChannel used / HTTP tunnel or Socks isn't ready yet, signal connect as usual }
if not FSecure or (Error <> WS_OK) or (FSocksState <> socksData) or (HttpTunnelState <> htsData) then
begin
inherited;
Exit;
end;
SChannelLog(loSslInfo, S_Msg_StartingTLS);
StartTLS;
end;
// Data incoming. Handle handshake or ensure decrypted data is received
function TSChannelWSocket.TriggerDataAvailable(Error: Word): Boolean;
begin
case FChannelState of
// No secure channel / Channel established - default
chsNotStarted,
chsEstablished, chsShutdown:
begin
Result := inherited;
end;
// Handshaking in progress - special handling
chsHandshake:
begin
if (Error <> WS_OK) then
begin
SChannelLog(loSslErr, Format(S_E_HandshakeTDAErr, [Error]));
TriggerSessionConnected(Error);
InternalClose(TRUE, Error);
Result := False;
Exit;
end;
Result := True;
DoHandshakeProcess;
end;
else
Result := False; // compiler happy
end; // case
end;
// TWSocket.ASyncReceive finishes when there's no data in socket but we could
// still have something already decrypted in internal buffer. Make sure we
// consume it all
procedure TSChannelWSocket.TriggerSessionClosed(Error: Word);
begin
try
if FChannelState = chsEstablished then
while FDecrBuffer.DataLen > 0 do
if not TriggerDataAvailable(WS_OK) then
Break;
{$IFNDEF NO_DEBUG_LOG}
if CheckLogOptions(loWsockInfo) then
if FSecure then
DebugLog(loWsockInfo, Format('TriggerSessionClosed. Payload R %d, W %d, total R %d, W %d',
[FPayloadReadCount, FPayloadWriteCount, FReadCount, FWriteCount]))
else
DebugLog(loWsockInfo, Format('TriggerSessionClosed. Total R %d, W %d',
[FReadCount, FWriteCount]));
{$ENDIF}
inherited;
except
on E:Exception do
HandleBackGroundException(E, 'TriggerSessionClosed');
end;
end;
// SChannel-specific output
procedure TSChannelWSocket.SChannelLog(LogOption: TLogOption; const Msg: string);
begin
{$IFNDEF NO_DEBUG_LOG}
if CheckLogOptions(LogOption) then
DebugLog(LogOption, SChannel.Utils.LogPrefix + Msg);
{$ENDIF}
end;
// SChannel-specific output that is called from functions during handshake
procedure TSChannelWSocket.SChannelHandshakeLog(const Msg: string);
begin
{$IFNDEF NO_DEBUG_LOG}
SChannelLog(loSslDevel, Msg);
{$ENDIF}
end;
// Start handshake process
procedure TSChannelWSocket.DoHandshakeStart;
var
BytesSent: Integer;
begin
FChannelState := chsHandshake;
FHandShakeData.Stage := hssNotStarted;
try
// Generate hello
DoClientHandshake(FSessionData, FHandShakeData, SChannelHandshakeLog);
Assert(FHandShakeData.Stage = hssSendCliHello);
// Send hello to server
BytesSent := Send(FHandShakeData.OutBuffers[0].pvBuffer, FHandShakeData.OutBuffers[0].cbBuffer);
if BytesSent > 0 then
SChannelLog(loSslDevel, Format(S_Msg_HShStageW1Success, [BytesSent]))
else
SChannelLog(loSslErr, Format(S_Msg_HShStageW1Fail, [WSocket_WSAGetLastError, WSocketErrorMsgFromErrorCode(WSocket_WSAGetLastError)]));
// Prepare to read hello from server
SetLength(FHandShakeData.IoBuffer, IO_BUFFER_SIZE);
FHandShakeData.cbIoBuffer := 0;
FHandShakeData.Stage := hssReadSrvHello;
finally
if Length(FHandShakeData.OutBuffers) > 0 then
g_pSSPI.FreeContextBuffer(FHandShakeData.OutBuffers[0].pvBuffer); // Free output buffer
SetLength(FHandShakeData.OutBuffers, 0);
end;
end;
// Handshake in process
procedure TSChannelWSocket.DoHandshakeProcess;
var
cbData: Integer;
begin
// Read next chunk from server
if FHandShakeData.Stage = hssReadSrvHello then
begin
cbData := Receive((PByte(FHandShakeData.IoBuffer) + FHandShakeData.cbIoBuffer),
Length(FHandShakeData.IoBuffer) - Integer(FHandShakeData.cbIoBuffer));
// ! Although this function is called from TriggerDataAvailable,
// WSAEWOULDBLOCK could happen so we just ignore it.
if (cbData = SOCKET_ERROR) and (WSocket_WSAGetLastError = WSAEWOULDBLOCK) then
Exit;
// Report other errors
if cbData <= 0 then
begin
SChannelLog(loSslErr, Format(S_Msg_HShStageRFail, [WSocket_WSAGetLastError, WSocketErrorMsgFromErrorCode(WSocket_WSAGetLastError)]));
Exit;
end;
SChannelLog(loSslDevel, Format(S_Msg_HShStageRSuccess, [cbData]));
Inc(FHandShakeData.cbIoBuffer, cbData);
end;
// Decode hello
try
try
DoClientHandshake(FSessionData, FHandShakeData, SChannelHandshakeLog);
except on E: ESSPIError do
// Hide Windows handshake bug and restart the process for the first time
if (FHandShakeData.Stage = hssReadSrvHello) and IsWinHandshakeBug(E.SecStatus)
and not FHandshakeBug then
begin
SChannelLog(loSslErr, Format(S_Msg_HandshakeBug, [E.Message]));
FHandshakeBug := True;
DeleteContext(FHandShakeData.hContext);
DoHandshakeStart;
Exit;
end
else
raise;
end;
// Send token if needed
if FHandShakeData.Stage in [hssReadSrvHelloContNeed, hssReadSrvHelloOK] then
begin
if (FHandShakeData.OutBuffers[0].cbBuffer > 0) and (FHandShakeData.OutBuffers[0].pvBuffer <> nil) then
begin
cbData := Send(FHandShakeData.OutBuffers[0].pvBuffer, FHandShakeData.OutBuffers[0].cbBuffer);
if cbData = Integer(FHandShakeData.OutBuffers[0].cbBuffer) then
SChannelLog(loSslDevel, Format(S_Msg_HShStageW2Success, [cbData]))
else
SChannelLog(loSslErr, Format(S_Msg_HShStageW2Fail, [WSocket_WSAGetLastError, WSocketErrorMsgFromErrorCode(WSocket_WSAGetLastError)]));
g_pSSPI.FreeContextBuffer(FHandShakeData.OutBuffers[0].pvBuffer); // Free output buffer
SetLength(FHandShakeData.OutBuffers, 0);
end;
if FHandShakeData.Stage = hssReadSrvHelloContNeed then
begin
FHandShakeData.Stage := hssReadSrvHello;
Exit;
end;
if FHandShakeData.Stage = hssReadSrvHelloOK then
begin
DoHandshakeSuccess;
TriggerSessionConnected(WS_OK);
Exit;
end;
end;
finally
if Length(FHandShakeData.OutBuffers) > 0 then
g_pSSPI.FreeContextBuffer(FHandShakeData.OutBuffers[0].pvBuffer); // Free output buffer
SetLength(FHandShakeData.OutBuffers, 0);
end;
end;
// Perform actions on successful handshake.
// Helper method, called from TriggerDataAvailable only, extracted for simplicity
procedure TSChannelWSocket.DoHandshakeSuccess;
var
CertCheckRes: TCertCheckResult;
begin
FhContext := FHandShakeData.hContext;
FHandShakeData.Stage := hssDone;
FChannelState := chsEstablished;
SChannelLog(loSslInfo, S_Msg_Established);
if FHandShakeData.cbIoBuffer > 0 then
SChannelLog(loSslInfo, Format(S_Msg_HShExtraData, [FHandShakeData.cbIoBuffer]));
try
// Don't pass host addr if it's IP otherwise verification would fail
if FAddrIsIP then
CertCheckRes := CheckServerCert(FhContext, '', SessionData.TrustedCerts, SessionData.CertCheckIgnoreFlags)
else
CertCheckRes := CheckServerCert(FhContext, Addr, SessionData.TrustedCerts, SessionData.CertCheckIgnoreFlags);
// Print debug messages why the cert appeared valid
case CertCheckRes of
ccrTrusted: SChannelLog(loSslInfo, S_Msg_CertIsTrusted);
ccrValidWithFlags: SChannelLog(loSslInfo, S_Msg_CertIsValidWithFlags);
end;
except on E: ESSPIError do
begin
// Report error to TLS channel
SChannelLog(loSslErr, E.Message);
raise;
end;
end;
SChannelLog(loSslInfo, S_Msg_SrvCredsAuth);
InitBuffers(FhContext, FSendBuffer, FSizes);
SetLength(FRecvBuffer.Data, Length(FSendBuffer));
SetLength(FDecrBuffer.Data, FSizes.cbMaximumMessage);
// Copy received extra data (0 length will work too)
Move(Pointer(FHandShakeData.IoBuffer)^, Pointer(FRecvBuffer.Data)^, FHandShakeData.cbIoBuffer);
Inc(FRecvBuffer.DataLen, FHandShakeData.cbIoBuffer);
FHandShakeData := Default(THandShakeData);
if Assigned(FOnTLSDone) then
FOnTLSDone(Self);
end;
// Change internal FSecure field and, if connected, run StartTLS/ShutdownTLS
procedure TSChannelWSocket.SetSecure(const Value: Boolean);
begin
if FSecure = Value then Exit; // no change
if Value then
begin
// already connected - start handshake
if FState = wsConnected then
StartTLS;
end
else
begin
// already connected - shutdown TLS
if FState = wsConnected then
ShutdownTLS;
end;
// Only set field if no exceptions happened
FSecure := Value;
end;
// Imitate FD_* event on a socket. Mostly useful with FD_READ to have DataAvailable
// with buffering socket implementations
procedure TSChannelWSocket.PostFD_EVENT(Event: Cardinal);
begin
PostMessage(Handle, FMsg_WM_ASYNCSELECT, WPARAM(FHSocket), IcsMakeLong(Event, 0));
end;
// Start TLS handshake process
procedure TSChannelWSocket.StartTLS;
var pCreds: PSessionCreds;
begin
FSessionData.ServerName := Addr;
// Create and init session data if not inited yet or finished (unlikely)
pCreds := GetSessionCredsPtr(FSessionData);
if SecIsNullHandle(pCreds.hCreds) then
begin
CreateSessionCreds(pCreds^);
SChannelLog(loSslInfo, S_Msg_CredsInited);
end;
// Save initial flags
FPrevFlags := FSessionData.Flags;
// Check if Addr is IP and set flag if yes
FAddrIsIP := AddrIsIP(Addr);
if FAddrIsIP then
begin
SChannelLog(loSslInfo, Format(S_Msg_AddrIsIP, [Addr]));
Include(FSessionData.Flags, sfNoServerVerify);
end;
DeleteContext(FhContext); // It should not contain any value but delete it for sure
DoHandshakeStart;
end;
// Shutdown TLS channel without closing the socket connection
procedure TSChannelWSocket.ShutdownTLS;
var
OutBuffer: SecBuffer;
begin
SChannelLog(loSslInfo, S_Msg_ShuttingDownTLS);
// Restore previous value of flags that could've been auto-set by
// current connect to an IP
FSessionData.Flags := FPrevFlags;
// Send a close_notify alert to the server and close down the connection.
GetShutdownData(FSessionData, FhContext, OutBuffer);
if OutBuffer.cbBuffer > 0 then
begin
SChannelLog(loSslDevel, Format(S_Msg_SendingShutdown, [OutBuffer.cbBuffer]));
FChannelState := chsShutdown;
Send(OutBuffer.pvBuffer, OutBuffer.cbBuffer);
g_pSSPI.FreeContextBuffer(OutBuffer.pvBuffer);
end;
DeleteContext(FhContext);
if Assigned(FOnTLSShutdown) then
FOnTLSShutdown(Self);
FChannelState := chsNotStarted;
end;
// Override for inherited method - deny listening in secure mode
procedure TSChannelWSocket.Listen;
begin
{ Check if we really want to use SChannel in server }
if FSecure then
raise ESocketException.Create(S_Err_ListeningNotSupported);
{ No SChannel used, Listen as usual }
inherited;
end;
// Override for inherited method - shutdown TLS channel before closing the connection
// (ignoring exceptions and don't waiting for peer response)
procedure TSChannelWSocket.Shutdown(How: Integer);
begin
// Secure channel not established - run default
if FChannelState <> chsEstablished then begin
inherited ShutDown(How);
Exit;
end;
// Send a close_notify alert to the server and close the connection.
try
ShutdownTLS;
// Currently we don't wait for data to be sent or server replies, just shutdown
inherited ShutDown(How);
// Just log an exception, don't let it go
except on E: Exception do
SChannelLog(loSslErr, E.Message);
end;
end;
procedure TSChannelWSocket.SetSessionData(const SessionData: TSessionData);
begin
// Allow setting only when channel is not established
if FChannelState <> chsNotStarted then
raise ESocketException.Create(S_E_SettingSessionDataChannelActive);
// If connected, check if socket host is the same as Session host
if FState = wsConnected then
if (SessionData.ServerName <> '') and (Addr <> SessionData.ServerName) then
raise ESocketException.CreateFmt(S_E_SettingSessionDataHostsDiffer, [Addr, SessionData.ServerName]);
FSessionData := SessionData; // we'll assign ServerName later in StartTLS
end;
end.
|
unit tmsUFlxStack;
{$INCLUDE ..\FLXCOMPILER.INC}
interface
uses Classes, SysUtils, tmsUFlxMessages;
type
TStringStack=class
private
FList: array of UTF16String;
FListCount: integer;
public
constructor Create;
destructor Destroy; override;
function Count: Integer;
function AtLeast(ACount: Integer): Boolean;
procedure Push(const s: UTF16String); virtual;
procedure Pop(out s: UTF16String);
procedure Peek(out s: UTF16String);
end;
TFormulaStack=class (TStringStack)
public
FmSpaces, FmPreSpaces, FmPostSpaces: UTF16String;
procedure Push(const s: UTF16String); override;
end;
TWhiteSpace=record
Count: byte;
Kind: byte;
end;
TWhiteSpaceStack=class
private
FList: array of TWhiteSpace;
FListCount: integer;
public
constructor Create;
destructor Destroy; override;
function Count: Integer;
function AtLeast(ACount: Integer): Boolean;
procedure Push(const s: TWhiteSpace); virtual;
procedure Pop(out s: TWhiteSpace);
procedure Peek(out s: TWhiteSpace);
end;
implementation
resourcestring
ErrEmptyStack='String Stack is empty';
ErrEmptyWsStack='WhiteSpace Stack is empty';
{ TStringStack }
function TStringStack.AtLeast(ACount: Integer): Boolean;
begin
Result := FListCount >= ACount;
end;
function TStringStack.Count: Integer;
begin
Result := FListCount;
end;
constructor TStringStack.Create;
begin
inherited Create;
FListCount:=0;
end;
destructor TStringStack.Destroy;
begin
inherited Destroy;
end;
procedure TStringStack.Peek(out s: UTF16String);
begin
if (FListCount-1<0) or (FListCount-1>=Length(FList)) then raise Exception.Create(ErrEmptyStack);
s := FList[FListCount-1];
end;
procedure TStringStack.Pop(out s: UTF16String);
begin
Peek(s);
if FListCount<=0 then raise Exception.Create(ErrEmptyStack);
Dec(FListCount);
end;
procedure TStringStack.Push(const s: UTF16String);
begin
if FListCount>=Length(FList) then SetLength(FList, Length(FList)+10);
FList[FListCount]:=s;
inc(FListCount);
end;
{ TFormulaStack }
procedure TFormulaStack.Push(const s: UTF16String);
begin
inherited;
FmSpaces:='';
FmPreSpaces:='';
FmPostSpaces:='';
end;
{ TWhiteSpaceStack }
function TWhiteSpaceStack.AtLeast(ACount: Integer): Boolean;
begin
Result := FListCount >= ACount;
end;
function TWhiteSpaceStack.Count: Integer;
begin
Result := FListCount;
end;
constructor TWhiteSpaceStack.Create;
begin
inherited Create;
FListCount:=0;
end;
destructor TWhiteSpaceStack.Destroy;
begin
inherited Destroy;
end;
procedure TWhiteSpaceStack.Peek(out s: TWhiteSpace);
begin
if (FListCount-1<0) or (FListCount-1>=Length(FList)) then raise Exception.Create(ErrEmptyWsStack);
s := FList[FListCount-1];
end;
procedure TWhiteSpaceStack.Pop(out s: TWhiteSpace);
begin
Peek(s);
if FListCount<=0 then raise Exception.Create(ErrEmptyStack);
Dec(FListCount);
end;
procedure TWhiteSpaceStack.Push(const s: TWhiteSpace);
begin
if FListCount>=Length(FList) then SetLength(FList, Length(FList)+10);
FList[FListCount]:=s;
inc(FListCount);
end;
end.
|
unit nsUnderControlNotificationManager;
// Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\Data\Common\nsUnderControlNotificationManager.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TnsUnderControlNotificationManager" MUID: (55D429A70008)
{$Include w:\garant6x\implementation\Garant\nsDefine.inc}
interface
uses
l3IntfUses
, l3ProtoObject
, l3ProtoDataContainer
, l3Memory
, l3Types
, l3Interfaces
, l3Core
, l3Except
, Classes
;
type
InsUnderControlNotificationListener = interface
['{08AD2F57-9D63-48F2-9D1D-6B7873FD8DBF}']
procedure UnderControlNotificationChanged;
end;//InsUnderControlNotificationListener
_ItemType_ = InsUnderControlNotificationListener;
_l3InterfacePtrList_Parent_ = Tl3ProtoDataContainer;
{$Define l3Items_IsProto}
{$Include w:\common\components\rtl\Garant\L3\l3InterfacePtrList.imp.pas}
TnsUnderControlNotificationListenersList = class(_l3InterfacePtrList_)
end;//TnsUnderControlNotificationListenersList
TnsUnderControlNotificationManager = {final} class(Tl3ProtoObject)
private
f_Listeners: TnsUnderControlNotificationListenersList;
f_HasChanged: Boolean;
private
procedure NotifyListeners;
protected
function pm_GetHasChanged: Boolean; virtual;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
procedure InitFields; override;
public
procedure ResetChangedNotification;
procedure Subscribe(const aListener: InsUnderControlNotificationListener);
procedure Unsubscribe(const aListener: InsUnderControlNotificationListener);
procedure SetChangedNotification;
class function Instance: TnsUnderControlNotificationManager;
{* Метод получения экземпляра синглетона TnsUnderControlNotificationManager }
class function Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
public
property HasChanged: Boolean
read pm_GetHasChanged;
end;//TnsUnderControlNotificationManager
implementation
uses
l3ImplUses
, SysUtils
, l3Base
, l3MinMax
, RTLConsts
//#UC START# *55D429A70008impl_uses*
//#UC END# *55D429A70008impl_uses*
;
var g_TnsUnderControlNotificationManager: TnsUnderControlNotificationManager = nil;
{* Экземпляр синглетона TnsUnderControlNotificationManager }
procedure TnsUnderControlNotificationManagerFree;
{* Метод освобождения экземпляра синглетона TnsUnderControlNotificationManager }
begin
l3Free(g_TnsUnderControlNotificationManager);
end;//TnsUnderControlNotificationManagerFree
type _Instance_R_ = TnsUnderControlNotificationListenersList;
{$Include w:\common\components\rtl\Garant\L3\l3InterfacePtrList.imp.pas}
function TnsUnderControlNotificationManager.pm_GetHasChanged: Boolean;
//#UC START# *55D4325E03DF_55D429A70008get_var*
//#UC END# *55D4325E03DF_55D429A70008get_var*
begin
//#UC START# *55D4325E03DF_55D429A70008get_impl*
Result := f_HasChanged;
//#UC END# *55D4325E03DF_55D429A70008get_impl*
end;//TnsUnderControlNotificationManager.pm_GetHasChanged
procedure TnsUnderControlNotificationManager.ResetChangedNotification;
//#UC START# *55D4315E001F_55D429A70008_var*
//#UC END# *55D4315E001F_55D429A70008_var*
begin
//#UC START# *55D4315E001F_55D429A70008_impl*
f_HasChanged := False;
NotifyListeners;
//#UC END# *55D4315E001F_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.ResetChangedNotification
procedure TnsUnderControlNotificationManager.Subscribe(const aListener: InsUnderControlNotificationListener);
//#UC START# *55D43170011B_55D429A70008_var*
//#UC END# *55D43170011B_55D429A70008_var*
begin
//#UC START# *55D43170011B_55D429A70008_impl*
Assert(f_Listeners.IndexOf(aListener) = -1);
f_Listeners.Add(aListener);
//#UC END# *55D43170011B_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.Subscribe
procedure TnsUnderControlNotificationManager.Unsubscribe(const aListener: InsUnderControlNotificationListener);
//#UC START# *55D4317E026C_55D429A70008_var*
//#UC END# *55D4317E026C_55D429A70008_var*
begin
//#UC START# *55D4317E026C_55D429A70008_impl*
Assert(f_Listeners.IndexOf(aListener) <> -1);
f_Listeners.Remove(aListener);
//#UC END# *55D4317E026C_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.Unsubscribe
procedure TnsUnderControlNotificationManager.NotifyListeners;
//#UC START# *55D438CC0369_55D429A70008_var*
var
l_Index: Integer;
//#UC END# *55D438CC0369_55D429A70008_var*
begin
//#UC START# *55D438CC0369_55D429A70008_impl*
for l_Index := 0 to Pred(f_Listeners.Count) do
f_Listeners[l_Index].UnderControlNotificationChanged;
//#UC END# *55D438CC0369_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.NotifyListeners
procedure TnsUnderControlNotificationManager.SetChangedNotification;
//#UC START# *55D43E670378_55D429A70008_var*
//#UC END# *55D43E670378_55D429A70008_var*
begin
//#UC START# *55D43E670378_55D429A70008_impl*
f_HasChanged := True;
NotifyListeners;
//#UC END# *55D43E670378_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.SetChangedNotification
class function TnsUnderControlNotificationManager.Instance: TnsUnderControlNotificationManager;
{* Метод получения экземпляра синглетона TnsUnderControlNotificationManager }
begin
if (g_TnsUnderControlNotificationManager = nil) then
begin
l3System.AddExitProc(TnsUnderControlNotificationManagerFree);
g_TnsUnderControlNotificationManager := Create;
end;
Result := g_TnsUnderControlNotificationManager;
end;//TnsUnderControlNotificationManager.Instance
class function TnsUnderControlNotificationManager.Exists: Boolean;
{* Проверяет создан экземпляр синглетона или нет }
begin
Result := g_TnsUnderControlNotificationManager <> nil;
end;//TnsUnderControlNotificationManager.Exists
procedure TnsUnderControlNotificationManager.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_55D429A70008_var*
//#UC END# *479731C50290_55D429A70008_var*
begin
//#UC START# *479731C50290_55D429A70008_impl*
FreeAndNil(f_Listeners);
inherited;
//#UC END# *479731C50290_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.Cleanup
procedure TnsUnderControlNotificationManager.InitFields;
//#UC START# *47A042E100E2_55D429A70008_var*
//#UC END# *47A042E100E2_55D429A70008_var*
begin
//#UC START# *47A042E100E2_55D429A70008_impl*
inherited;
f_Listeners := TnsUnderControlNotificationListenersList.Create;
//#UC END# *47A042E100E2_55D429A70008_impl*
end;//TnsUnderControlNotificationManager.InitFields
end.
|
unit PIImpl;
interface
uses orbtypes, orb, exceptions, PIDemo_int, PIDemo, LoggerPolicy_int, LoggerPolicy,
pi, code_int, orb_int, policy_int, poa, poa_int, req_int;
type
TPIDemo_impl = class(TPIDemo_serv)
private
FOtherObj: IPIDemo;
protected
procedure noargs; override;
procedure noargs_oneway; override;
function noargs_return: AnsiString; override;
procedure withargs(const param1: AnsiString; var param2: AnsiString; out param3: AnsiString); override;
procedure systemexception; override;
procedure userexception; override;
procedure switch_to_static_impl; override;
procedure switch_to_dynamic_impl; override;
procedure call_other_impl(const level: short); override;
procedure deactivate; override;
public
//constructor Create();
procedure SetOtherObj(AObj: IPIDemo);
end;
TPIDemoDSI_impl = class(TPOADynamicImplementation)
private
FOtherObj: IPIDemo;
protected
function _primary_interface(const objid: ObjectID; const poa: IPOA): AnsiString; override;
function _is_a(const repoid: RepositoryID): Boolean; override;
procedure invoke(const req: IServerRequest); override;
public
procedure SetOtherObj(AObj: IPIDemo);
end;
TLoggerPolicyImpl = class(TLoggerPolicy)
private
FLevel: short;
protected
function _get_level: short; override;
public
constructor CreateLoggerPolicy(level: short);
end;
TLoggerPolicyFactory = class(TPolicyFactory)
protected
function create_policy(const _type: TPolicyType; const value: IAny): IPolicy; override;
end;
implementation
uses policy, env_int, any, tcode, except_int;
{ TPIDemo_impl }
procedure TPIDemo_impl.call_other_impl(const level: short);
begin
if (FOtherObj <> nil) and (level > 0) then
FOtherObj.call_other_impl(Pred(level));
end;
procedure TPIDemo_impl.deactivate;
begin
ORB_Instance.shutdown(false);
end;
procedure TPIDemo_impl.noargs;
begin
end;
procedure TPIDemo_impl.noargs_oneway;
begin
writeln('noargs_oneway');
end;
function TPIDemo_impl.noargs_return: AnsiString;
begin
Result := 'PIDemo';
end;
procedure TPIDemo_impl.SetOtherObj(AObj: IPIDemo);
begin
FOtherObj := AObj;
end;
procedure TPIDemo_impl.switch_to_dynamic_impl;
begin
end;
procedure TPIDemo_impl.switch_to_static_impl;
begin
end;
procedure TPIDemo_impl.systemexception;
begin
raise NO_IMPLEMENT.Create();
end;
procedure TPIDemo_impl.userexception;
begin
raise TPIDemo_User.Create;
end;
procedure TPIDemo_impl.withargs(const param1: AnsiString; var param2: AnsiString;
out param3: AnsiString);
begin
param2 := 'PIDemo';
param3 := 'PIDemo';
end;
{ TLoggerPolicyImpl }
constructor TLoggerPolicyImpl.CreateLoggerPolicy(level: short);
begin
inherited Create(LOGGER_POLICY_ID);
FLevel := level;
end;
function TLoggerPolicyImpl._get_level: short;
begin
Result := FLevel;
end;
{ TLoggerPolicyFactory }
function TLoggerPolicyFactory.create_policy(const _type: TPolicyType;
const value: IAny): IPolicy;
var
level: short;
begin
if _type = LOGGER_POLICY_ID then begin
if value.to_short(level) then begin
Result := TLoggerPolicyImpl.CreateLoggerPolicy(level);
Exit;
end;
raise TPolicyError.Create();
end;
raise TPolicyError.Create(BAD_POLICY);
end;
{ TPIDemoDSI_impl }
function TPIDemoDSI_impl._is_a(const repoid: RepositoryID): Boolean;
begin
Result := repoid = 'IDL:PIDemo:1.0';
if not Result then
Result := inherited _is_a(repoid);
end;
function TPIDemoDSI_impl._primary_interface(const objid: ObjectID;
const poa: IPOA): AnsiString;
begin
Result := 'IDL:PIDemo:1.0';
end;
procedure TPIDemoDSI_impl.invoke(const req: IServerRequest);
var
name: AnsiString;
nvList: INVList;
orb: IORB;
res, any: IAny;
//sysEx: ISystemException;
level: short;
begin
name := req.operation();
orb := ORB_Instance();
if name = 'noargs' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
end
else if name = 'noargs_oneway' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
end
else if name = 'noargs_return' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
res := CreateAny();
res.put_string('PIDemoDSI');
req.set_result(res);
end
else if name = 'withargs' then begin
orb.create_list(0, nvList);
nvList.add(ARG_IN).argument.replace(_tc_string, nil);
nvList.add(ARG_INOUT).argument.replace(_tc_string, nil);
nvList.add(ARG_OUT).argument.replace(_tc_string, nil);
req.arguments(nvList);
any := nvList.item(1).argument;
any.put_string('PIDemoDSI');
any := nvList.item(2).argument;
any.put_string('PIDemoDSI');
end
else if name = 'systemexception' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
{sysEx := NO_IMPLEMENT.Create();
res := CreateAny();
sysEx.encode_any(res);}
req.set_exception(NO_IMPLEMENT.Create());
end
else if name = 'userexception' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
//res := PIDemo_User_to_any(TPIDemo_User.Create());
//result <<= PIDemo::User();
req.set_exception(TPIDemo_User.Create());
end
else if name = 'switch_to_static_impl' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
end
else if name = 'switch_to_dynamic_impl' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
end
else if name = 'call_other_impl' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
nvList.add(ARG_IN).argument.replace(_tc_short, nil);
req.arguments(nvList);
any := nvList.item(0).argument;
if not any.to_short(level) then begin
req.set_exception(BAD_PARAM.Create);
Exit;
end;
if (FOtherObj <> nil) and (level > 0) then
FOtherObj.call_other_impl(Pred(level));
end
else if name = 'deactivate' then begin
orb.create_list(0, nvList);
req.arguments(nvList);
orb.shutdown(false);
end
else begin
orb.create_list(0, nvList);
req.arguments(nvList);
req.set_exception(BAD_OPERATION.Create());
end;
end;
procedure TPIDemoDSI_impl.SetOtherObj(AObj: IPIDemo);
begin
FOtherObj := AObj;
end;
end.
|
unit blacktiger_hw;
interface
uses {$IFDEF WINDOWS}windows,{$ENDIF}
nz80,mcs51,main_engine,controls_engine,ym_2203,gfx_engine,timer_engine,
rom_engine,file_engine,pal_engine,sound_engine,qsnapshot;
// {$define speed_debug}
function iniciar_blktiger:boolean;
implementation
{$ifdef speed_debug}uses principal,sysutils;{$endif}
const
blktiger_rom:array[0..4] of tipo_roms=(
(n:'bdu-01a.5e';l:$8000;p:0;crc:$a8f98f22),(n:'bdu-02a.6e';l:$10000;p:$8000;crc:$7bef96e8),
(n:'bdu-03a.8e';l:$10000;p:$18000;crc:$4089e157),(n:'bd-04.9e';l:$10000;p:$28000;crc:$ed6af6ec),
(n:'bd-05.10e';l:$10000;p:$38000;crc:$ae59b72e));
blktiger_char:tipo_roms=(n:'bd-15.2n';l:$8000;p:0;crc:$70175d78);
blktiger_sprites:array[0..3] of tipo_roms=(
(n:'bd-08.5a';l:$10000;p:0;crc:$e2f17438),(n:'bd-07.4a';l:$10000;p:$10000;crc:$5fccbd27),
(n:'bd-10.9a';l:$10000;p:$20000;crc:$fc33ccc6),(n:'bd-09.8a';l:$10000;p:$30000;crc:$f449de01));
blktiger_tiles:array[0..3] of tipo_roms=(
(n:'bd-12.5b';l:$10000;p:0;crc:$c4524993),(n:'bd-11.4b';l:$10000;p:$10000;crc:$7932c86f),
(n:'bd-14.9b';l:$10000;p:$20000;crc:$dc49593a),(n:'bd-13.8b';l:$10000;p:$30000;crc:$7ed7a122));
blktiger_snd:tipo_roms=(n:'bd-06.1l';l:$8000;p:0;crc:$2cf54274);
blktiger_mcu:tipo_roms=(n:'bd.6k';l:$1000;p:0;crc:$ac7d14f1);
//Dip
blktiger_dip_a:array [0..4] of def_dip=(
(mask:$7;name:'Coin A';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$1;dip_name:'3C 1C'),(dip_val:$2;dip_name:'2C 1C'),(dip_val:$7;dip_name:'1C 1C'),(dip_val:$6;dip_name:'1C 2C'),(dip_val:$5;dip_name:'1C 3C'),(dip_val:$4;dip_name:'1C 4C'),(dip_val:$3;dip_name:'1C 5C'),(),(),(),(),(),(),(),())),
(mask:$38;name:'Coin B';number:8;dip:((dip_val:$0;dip_name:'4C 1C'),(dip_val:$8;dip_name:'3C 1C'),(dip_val:$10;dip_name:'2C 1C'),(dip_val:$38;dip_name:'1C 1C'),(dip_val:$30;dip_name:'1C 2C'),(dip_val:$28;dip_name:'1C 3C'),(dip_val:$20;dip_name:'1C 4C'),(dip_val:$18;dip_name:'1C 5C'),(),(),(),(),(),(),(),())),
(mask:$40;name:'Flip Screen';number:2;dip:((dip_val:$40;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Test';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
blktiger_dip_b:array [0..5] of def_dip=(
(mask:$3;name:'Lives';number:4;dip:((dip_val:$2;dip_name:'2'),(dip_val:$3;dip_name:'3'),(dip_val:$1;dip_name:'5'),(dip_val:$0;dip_name:'7'),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$1c;name:'Difficulty';number:8;dip:((dip_val:$1c;dip_name:'Very Easy'),(dip_val:$18;dip_name:'Easy 3'),(dip_val:$14;dip_name:'Easy 2'),(dip_val:$10;dip_name:'Easy 1'),(dip_val:$c;dip_name:'Normal'),(dip_val:$8;dip_name:'Difficult 1'),(dip_val:$4;dip_name:'Difficult 2'),(dip_val:$0;dip_name:'Very Difficult'),(),(),(),(),(),(),(),())),
(mask:$20;name:'Demo Sounds';number:2;dip:((dip_val:$0;dip_name:'Off'),(dip_val:$20;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$40;name:'Allow Continue';number:2;dip:((dip_val:$0;dip_name:'No'),(dip_val:$40;dip_name:'Yes'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),
(mask:$80;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$80;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),());
var
scroll_ram:array[0..$3fff] of byte;
memoria_rom:array[0..$f,$0..$3fff] of byte;
banco_rom,soundlatch,i8751_latch,z80_latch,timer_hs,mask_x,mask_y,shl_row:byte;
mask_sx,mask_sy,scroll_x,scroll_y,scroll_bank:word;
bg_on,ch_on,spr_on:boolean;
procedure update_video_blktiger;
const
split_table:array[0..15] of byte=(3,3,2,2,1,1,0,0,0,0,0,0,0,0,0,0);
var
f,x,y,nchar,pos_x,pos_y,color:word;
sx,sy,pos,atrib:word;
flip_x:boolean;
begin
//Para que el fondo de la pantalla 4 se vea negro, tengo que hacerlo asi... Rellenar
//la pantalla final y todo el fondo con transparencias...
fill_full_screen(4,$400);
if bg_on then begin
pos_x:=(scroll_x and mask_sx) shr 4;
pos_y:=(scroll_y and mask_sy) shr 4;
for f:=0 to $120 do begin
x:=f mod 17;
y:=f div 17;
sx:=x+pos_x;
sy:=y+pos_y;
pos:=((sx and $0f)+((sy and $0f) shl 4)+((sx and mask_x) shl 4)+((sy and mask_y) shl shl_row)) shl 1;
atrib:=scroll_ram[pos+1];
color:=(atrib and $78) shr 3;
if (gfx[2].buffer[pos shr 1] or buffer_color[color+$20]) then begin
nchar:=scroll_ram[pos]+((atrib and $7) shl 8);
flip_x:=(atrib and $80)<>0;
put_gfx_trans_flip(x*16,y*16,nchar,color shl 4,1,2,flip_x,false);
if split_table[color]<>0 then put_gfx_trans_flip_alt(x*16,y*16,nchar,color shl 4,2,2,flip_x,false,split_table[color])
else put_gfx_block_trans(x*16,y*16,2,16,16);
gfx[2].buffer[pos shr 1]:=false;
end;
end;
scroll_x_y(1,4,scroll_x and $f,scroll_y and $f);
end;
if spr_on then begin
for f:=$7f downto 0 do begin
atrib:=buffer_sprites[$1+(f*4)];
nchar:=buffer_sprites[f*4]+(atrib and $e0) shl 3;
color:=(atrib and $7) shl 4;
x:=buffer_sprites[$3+(f*4)]+(atrib and $10) shl 4;
y:=buffer_sprites[$2+(f*4)];
put_gfx_sprite(nchar,color+$200,(atrib and 8)<>0,false,1);
actualiza_gfx_sprite(x,y,4,1);
end;
end;
if bg_on then scroll_x_y(2,4,scroll_x and $f,scroll_y and $f);
if ch_on then begin
for f:=$0 to $3ff do begin
atrib:=memoria[$d400+f];
color:=atrib and $1f;
if (gfx[0].buffer[f] or buffer_color[color]) then begin
y:=f shr 5;
x:=f and $1f;
nchar:=memoria[$d000+f]+(atrib and $e0) shl 3;
put_gfx_trans(x*8,y*8,nchar,(color shl 2)+$300,3,0);
gfx[0].buffer[f]:=false;
end;
end;
actualiza_trozo(0,0,256,256,3,0,0,256,256,4);
end;
actualiza_trozo_final(0,16,256,224,4);
fillchar(buffer_color,MAX_COLOR_BUFFER,0);
end;
procedure eventos_blktiger;
begin
if event.arcade then begin
//SYS
if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1);
if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2);
if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40);
if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80);
//P1
if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8);
if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4);
if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2);
if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1);
if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20);
if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10);
//P2
if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8);
if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4);
if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2);
if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1);
if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20);
if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10);
end;
end;
procedure blktiger_principal;
var
frame_m,frame_s,frame_mcu:single;
f:word;
{$ifdef speed_debug}cont1,cont2:int64;{$endif}
begin
init_controls(false,false,false,true);
frame_m:=z80_0.tframes;
frame_s:=z80_1.tframes;
frame_mcu:=mcs51_0.tframes;
while EmuStatus=EsRuning do begin
{$ifdef speed_debug}
QueryPerformanceCounter(cont1);
{$endif}
for f:=0 to 261 do begin
//Main CPU
z80_0.run(frame_m);
frame_m:=frame_m+z80_0.tframes-z80_0.contador;
//Sound CPU
z80_1.run(frame_s);
frame_s:=frame_s+z80_1.tframes-z80_1.contador;
//MCU
mcs51_0.run(frame_mcu);
frame_mcu:=frame_mcu+mcs51_0.tframes-mcs51_0.contador;
if f=245 then begin
z80_0.change_irq(HOLD_LINE);
copymemory(@buffer_sprites,@memoria[$fe00],$200);
update_video_blktiger;
end;
end;
eventos_blktiger;
{$ifdef speed_debug}
QueryPerformanceCounter(cont2);
principal1.statusbar1.panels[2].text:=inttostr(cont2-cont1);
{$endif}
video_sync;
end;
end;
function blktiger_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff,$d000..$d7ff,$e000..$ffff:blktiger_getbyte:=memoria[direccion];
$8000..$bfff:blktiger_getbyte:=memoria_rom[banco_rom,(direccion and $3fff)];
$c000..$cfff:blktiger_getbyte:=scroll_ram[scroll_bank+(direccion and $fff)];
$d800..$dfff:blktiger_getbyte:=buffer_paleta[direccion and $7ff];
//$f3a1:blktiger_getbyte:=4;
end;
end;
procedure cambiar_color(dir:word);
var
tmp_color:byte;
color:tcolor;
begin
tmp_color:=buffer_paleta[dir];
color.r:=pal4bit(tmp_color shr 4);
color.g:=pal4bit(tmp_color);
tmp_color:=buffer_paleta[dir+$400];
color.b:=pal4bit(tmp_color);
set_pal_color(color,dir);
case dir of
$0..$ff:buffer_color[(dir shr 4)+$20]:=true;
$300..$37f:buffer_color[(dir shr 2) and $1f]:=true;
end;
end;
procedure blktiger_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$bfff:; //ROM
$c000..$cfff:if scroll_ram[scroll_bank+(direccion and $fff)]<>valor then begin
scroll_ram[scroll_bank+(direccion and $fff)]:=valor;
gfx[2].buffer[(scroll_bank+(direccion and $fff)) shr 1]:=true;
memoria[direccion]:=valor;
end;
$d000..$d7ff:if memoria[direccion]<>valor then begin
gfx[0].buffer[direccion and $3ff]:=true;
memoria[direccion]:=valor;
end;
$d800..$dfff:if buffer_paleta[direccion and $7ff]<>valor then begin
buffer_paleta[direccion and $7ff]:=valor;
cambiar_color(direccion and $3ff);
end;
$e000..$ffff:memoria[direccion]:=valor;
end;
end;
function blktiger_inbyte(puerto:word):byte;
begin
case (puerto and $ff) of
0:blktiger_inbyte:=marcade.in0;
1:blktiger_inbyte:=marcade.in1;
2:blktiger_inbyte:=marcade.in2;
3:blktiger_inbyte:=marcade.dswa;
4:blktiger_inbyte:=marcade.dswb;
5:blktiger_inbyte:=$1; //Freeze?
7:blktiger_inbyte:=i8751_latch; //Proteccion
else blktiger_inbyte:=$ff;
end;
end;
procedure blktiger_outbyte(puerto:word;valor:byte);
begin
case (puerto and $ff) of
0:soundlatch:=valor;
1:banco_rom:=valor and $f;
4:begin
if ch_on<>((valor and $80)=0) then begin
ch_on:=(valor and $80)=0;
if ch_on then fillchar(gfx[0].buffer,$400,1);
end;
main_screen.flip_main_screen:=(valor and $40)<>0;
z80_1.change_reset((valor and $20) shr 5);
end;
7:begin
z80_latch:=valor;
mcs51_0.change_irq1(ASSERT_LINE);
end;
8:if ((scroll_x and $ff)<>valor) then begin
if abs((scroll_x and mask_sx)-(valor and mask_sx))>15 then fillchar(gfx[2].buffer,$2000,1);
scroll_x:=(scroll_x and $ff00) or valor;
end;
9:if ((scroll_x shr 8)<>valor) then begin
if abs((scroll_x and mask_sx)-(valor and mask_sx))>15 then fillchar(gfx[2].buffer,$2000,1);
scroll_x:=(scroll_x and $ff) or (valor shl 8);
end;
$a:if ((scroll_y and $ff)<>valor) then begin
if abs((scroll_y and mask_sy)-(valor and mask_sy))>15 then fillchar(gfx[2].buffer,$2000,1);
scroll_y:=(scroll_y and $ff00) or valor;
end;
$b:if ((scroll_y shr 8)<>valor) then begin
if abs((scroll_y and mask_sy)-(valor and mask_sy))>15 then fillchar(gfx[2].buffer,$2000,1);
scroll_y:=(scroll_y and $ff) or (valor shl 8);
end;
$c:begin
if bg_on<>((valor and $2)=0) then begin
bg_on:=(valor and $2)=0;
if bg_on then fillchar(gfx[2].buffer,$2000,1);
end;
spr_on:=(valor and $4)=0;
end;
$d:scroll_bank:=(valor and 3) shl 12;
$e:if ((valor and 1)<>0) then begin
mask_x:=$70;
mask_y:=$30;
shl_row:=7;
mask_sx:=$1ff0;
mask_sy:=$ff0;
end else begin
mask_x:=$30;
mask_y:=$70;
shl_row:=6;
mask_sx:=$ff0;
mask_sy:=$1ff0;
end
end;
end;
function blksnd_getbyte(direccion:word):byte;
begin
case direccion of
0..$7fff,$c000..$c7ff:blksnd_getbyte:=mem_snd[direccion];
$c800:blksnd_getbyte:=soundlatch;
$e000:blksnd_getbyte:=ym2203_0.status;
$e002:blksnd_getbyte:=ym2203_1.status;
end;
end;
procedure blksnd_putbyte(direccion:word;valor:byte);
begin
case direccion of
0..$7fff:; //ROM
$c000..$c7ff:mem_snd[direccion]:=valor;
$e000:ym2203_0.Control(valor);
$e001:ym2203_0.write(valor);
$e002:ym2203_1.Control(valor);
$e003:ym2203_1.write(valor);
end;
end;
procedure out_port0(valor:byte);
begin
i8751_latch:=valor;
end;
function in_port0:byte;
begin
mcs51_0.change_irq1(CLEAR_LINE);
in_port0:=z80_latch;
end;
procedure blktiger_sound_update;
begin
ym2203_0.update;
ym2203_1.update;
end;
procedure snd_irq(irqstate:byte);
begin
z80_1.change_irq(irqstate);
end;
procedure blk_hi_score;
begin
if ((memoria[$e204]=2) and (memoria[$e205]=0) and (memoria[$e206]=0)) then begin
load_hi('blktiger.hi',@memoria[$e200],80);
copymemory(@memoria[$e1e0],@memoria[$e200],8);
timers.enabled(timer_hs,false);
end;
end;
procedure blktiger_qsave(nombre:string);
var
data:pbyte;
buffer:array[0..19] of byte;
size:word;
begin
open_qsnapshot_save('blacktiger'+nombre);
getmem(data,20000);
//CPU
size:=z80_0.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=z80_1.save_snapshot(data);
savedata_qsnapshot(data,size);
size:=mcs51_0.save_snapshot(data);
savedata_qsnapshot(data,size);
//SND
size:=ym2203_0.save_snapshot(data);
savedata_com_qsnapshot(data,size);
size:=ym2203_1.save_snapshot(data);
savedata_com_qsnapshot(data,size);
//MEM
savedata_com_qsnapshot(@memoria[$c000],$4000);
savedata_com_qsnapshot(@mem_snd[$8000],$8000);
//MISC
savedata_com_qsnapshot(@scroll_ram,$4000);
buffer[0]:=banco_rom;
buffer[1]:=soundlatch;
buffer[2]:=scroll_x and $ff;
buffer[3]:=scroll_x shr 8;
buffer[4]:=scroll_y and $ff;
buffer[5]:=scroll_y shr 8;
buffer[6]:=scroll_bank and $ff;
buffer[7]:=scroll_bank shr 8;
buffer[8]:=mask_x;
buffer[9]:=mask_y;
buffer[10]:=shl_row;
buffer[11]:=mask_sx and $ff;
buffer[12]:=mask_sx shr 8;
buffer[13]:=mask_sy and $ff;
buffer[14]:=mask_sy shr 8;
buffer[15]:=i8751_latch;
buffer[16]:=z80_latch;
buffer[17]:=byte(bg_on);
buffer[18]:=byte(ch_on);
buffer[19]:=byte(spr_on);
savedata_qsnapshot(@buffer,20);
savedata_com_qsnapshot(@buffer_paleta,$800*2);
savedata_com_qsnapshot(@buffer_sprites,$200);
freemem(data);
close_qsnapshot;
end;
procedure blktiger_qload(nombre:string);
var
data:pbyte;
buffer:array[0..19] of byte;
f:word;
begin
if not(open_qsnapshot_load('blacktiger'+nombre)) then exit;
getmem(data,20000);
//CPU
loaddata_qsnapshot(data);
z80_0.load_snapshot(data);
loaddata_qsnapshot(data);
z80_1.load_snapshot(data);
loaddata_qsnapshot(data);
mcs51_0.load_snapshot(data);
//SND
loaddata_qsnapshot(data);
ym2203_0.load_snapshot(data);
loaddata_qsnapshot(data);
ym2203_1.load_snapshot(data);
//MEM
loaddata_qsnapshot(@memoria[$c000]);
loaddata_qsnapshot(@mem_snd[$8000]);
//MISC
loaddata_qsnapshot(@scroll_ram);
loaddata_qsnapshot(@buffer);
banco_rom:=buffer[0];
soundlatch:=buffer[1];
scroll_x:=buffer[2] or (buffer[3] shl 8);
scroll_y:=buffer[4] or (buffer[5] shl 8);
scroll_bank:=buffer[6] or (buffer[7] shl 8);
mask_x:=buffer[8];
mask_y:=buffer[9];
shl_row:=buffer[10];
mask_sx:=buffer[11] or (buffer[12] shl 8);
mask_sy:=buffer[13] or (buffer[14] shl 8);
i8751_latch:=buffer[15];
z80_latch:=buffer[16];
bg_on:=buffer[17]<>0;
ch_on:=buffer[18]<>0;
spr_on:=buffer[19]<>0;
loaddata_qsnapshot(@buffer_paleta);
loaddata_qsnapshot(@buffer_sprites);
freemem(data);
close_qsnapshot;
//END
for f:=0 to $3ff do cambiar_color(f);
fillchar(buffer_color,$400,1);
fillchar(gfx[0].buffer,$400,1);
fillchar(gfx[2].buffer,$4000,1);
end;
//Main
procedure reset_blktiger;
begin
z80_0.reset;
z80_1.reset;
mcs51_0.reset;
ym2203_0.reset;
ym2203_1.reset;
reset_audio;
banco_rom:=0;
soundlatch:=0;
scroll_bank:=0;
scroll_x:=0;
scroll_y:=0;
marcade.in0:=$ff;
marcade.in1:=$ff;
marcade.in2:=$ff;
mask_x:=$70;
mask_y:=$30;
shl_row:=7;
i8751_latch:=0;
z80_latch:=0;
bg_on:=true;
ch_on:=true;
spr_on:=true;
end;
procedure cerrar_blktiger;
begin
save_hi('blktiger.hi',@memoria[$e200],80);
end;
function iniciar_blktiger:boolean;
var
f:word;
memoria_temp:array[0..$47fff] of byte;
const
ps_x:array[0..15] of dword=(0, 1, 2, 3, 8+0, 8+1, 8+2, 8+3,
16*16+0, 16*16+1, 16*16+2, 16*16+3, 16*16+8+0, 16*16+8+1, 16*16+8+2, 16*16+8+3);
ps_y:array[0..15] of dword=(0*16, 1*16, 2*16, 3*16, 4*16, 5*16, 6*16, 7*16,
8*16, 9*16, 10*16, 11*16, 12*16, 13*16, 14*16, 15*16);
begin
llamadas_maquina.bucle_general:=blktiger_principal;
llamadas_maquina.close:=cerrar_blktiger;
llamadas_maquina.reset:=reset_blktiger;
llamadas_maquina.save_qsnap:=blktiger_qsave;
llamadas_maquina.load_qsnap:=blktiger_qload;
llamadas_maquina.fps_max:=24000000/4/384/262;
iniciar_blktiger:=false;
iniciar_audio(false);
//Background
screen_init(1,272,272,true);
screen_mod_scroll(1,272,256,255,272,256,255);
//Foreground
screen_init(2,272,272,true);
screen_mod_scroll(2,272,256,255,272,256,255);
screen_init(3,256,256,true); //Chars
screen_init(4,512,256,false,true); //Final
iniciar_video(256,224);
//Main CPU
z80_0:=cpu_z80.create(6000000,262);
z80_0.change_ram_calls(blktiger_getbyte,blktiger_putbyte);
z80_0.change_io_calls(blktiger_inbyte,blktiger_outbyte);
//Sound CPU
z80_1:=cpu_z80.create(3579545,262);
z80_1.change_ram_calls(blksnd_getbyte,blksnd_putbyte);
z80_1.init_sound(blktiger_sound_update);
//MCU
mcs51_0:=cpu_mcs51.create(24000000 div 3,262);
mcs51_0.change_io_calls(in_port0,nil,nil,nil,out_port0,nil,nil,nil);
//Sound Chip
ym2203_0:=ym2203_chip.create(3579545,0.15,0.15);
ym2203_0.change_irq_calls(snd_irq);
ym2203_1:=ym2203_chip.create(3579545,0.15,0.15);
//Timers
timer_hs:=timers.init(z80_0.numero_cpu,10000,blk_hi_score,nil,true);
//cargar roms
if not(roms_load(@memoria_temp,blktiger_rom)) then exit;
//poner las roms y los bancos de rom
copymemory(@memoria,@memoria_temp,$8000);
for f:=0 to 15 do copymemory(@memoria_rom[f,0],@memoria_temp[$8000+(f*$4000)],$4000);
//sonido
if not(roms_load(@mem_snd,blktiger_snd)) then exit;
//MCU ROM
if not(roms_load(mcs51_0.get_rom_addr,blktiger_mcu)) then exit;
//convertir chars
if not(roms_load(@memoria_temp,blktiger_char)) then exit;
init_gfx(0,8,8,2048);
gfx[0].trans[3]:=true;
gfx_set_desc_data(2,0,16*8,4,0);
convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false);
//convertir sprites
if not(roms_load(@memoria_temp,blktiger_sprites)) then exit;
init_gfx(1,16,16,$800);
gfx[1].trans[15]:=true;
gfx_set_desc_data(4,0,32*16,$800*32*16+4,$800*32*16+0,4,0);
convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false);
//tiles
if not(roms_load(@memoria_temp,blktiger_tiles)) then exit;
init_gfx(2,16,16,$800);
gfx[2].trans[15]:=true;
gfx[2].trans_alt[0,15]:=true;
for f:=4 to 15 do gfx[2].trans_alt[1,f]:=true;
for f:=8 to 15 do gfx[2].trans_alt[2,f]:=true;
for f:=12 to 15 do gfx[2].trans_alt[3,f]:=true;
gfx_set_desc_data(4,0,32*16,$800*32*16+4,$800*32*16+0,4,0);
convert_gfx(2,0,@memoria_temp,@ps_x,@ps_y,false,false);
//DIP
marcade.dswa:=$ff;
marcade.dswb:=$6f;
marcade.dswa_val:=@blktiger_dip_a;
marcade.dswb_val:=@blktiger_dip_b;
//final
reset_blktiger;
iniciar_blktiger:=true;
end;
end.
|
unit CsReplyProceduresPrim;
{* Класс для регистрации "ответных процедур" сервера для запросов от клиента }
// Модуль: "w:\common\components\rtl\Garant\cs\CsReplyProceduresPrim.pas"
// Стереотип: "SimpleClass"
// Элемент модели: "TCsReplyProceduresPrim" MUID: (537F645C01D1)
{$Include w:\common\components\rtl\Garant\cs\CsDefine.inc}
interface
{$If Defined(AppServerSide) AND NOT Defined(Nemesis)}
uses
l3IntfUses
, CsObject
, CsProcWithIdList
, SysUtils
, CsProcWithId
, CsQueryTypes
;
type
TCsReplyProceduresPrim = {abstract} class(TCsObject)
{* Класс для регистрации "ответных процедур" сервера для запросов от клиента }
protected
f_List: TCsProcWithIdList;
f_Synchronizer: TMultiReadExclusiveWriteSynchronizer;
protected
function ListItemBy(aQueryId: TCsQueryId): TCsProcWithId;
procedure Cleanup; override;
{* Функция очистки полей объекта. }
public
constructor Create; reintroduce;
function ProcBy(aQueryId: TCsQueryId): TCsReplyProc;
end;//TCsReplyProceduresPrim
{$IfEnd} // Defined(AppServerSide) AND NOT Defined(Nemesis)
implementation
{$If Defined(AppServerSide) AND NOT Defined(Nemesis)}
uses
l3ImplUses
, TypInfo
, l3Base
//#UC START# *537F645C01D1impl_uses*
//#UC END# *537F645C01D1impl_uses*
;
constructor TCsReplyProceduresPrim.Create;
//#UC START# *53959A720000_537F645C01D1_var*
//#UC END# *53959A720000_537F645C01D1_var*
begin
//#UC START# *53959A720000_537F645C01D1_impl*
inherited;
f_List := TCsProcWithIdList.Create;
f_Synchronizer := TMultiReadExclusiveWriteSynchronizer.Create;
//#UC END# *53959A720000_537F645C01D1_impl*
end;//TCsReplyProceduresPrim.Create
function TCsReplyProceduresPrim.ListItemBy(aQueryId: TCsQueryId): TCsProcWithId;
//#UC START# *53959ABC03D4_537F645C01D1_var*
var
I: Integer;
//#UC END# *53959ABC03D4_537F645C01D1_var*
begin
//#UC START# *53959ABC03D4_537F645C01D1_impl*
Result := nil;
for I := 0 to f_List.Count - 1 do
if (f_List[I].QueryId = aQueryId) then
begin
Result := f_List[I];
Break;
end;//f_List[I].QueryId = aQueryId
//#UC END# *53959ABC03D4_537F645C01D1_impl*
end;//TCsReplyProceduresPrim.ListItemBy
function TCsReplyProceduresPrim.ProcBy(aQueryId: TCsQueryId): TCsReplyProc;
//#UC START# *53959B1400E0_537F645C01D1_var*
var
l_ProcWithId: TCsProcWithId;
//#UC END# *53959B1400E0_537F645C01D1_var*
begin
//#UC START# *53959B1400E0_537F645C01D1_impl*
f_Synchronizer.BeginRead;
try
l_ProcWithId := ListItemBy(aQueryId);
if l_ProcWithId <> nil then
Result := l_ProcWithId.Proc
else
Result := nil;
finally
f_Synchronizer.EndRead;
end;//try..finally
//#UC END# *53959B1400E0_537F645C01D1_impl*
end;//TCsReplyProceduresPrim.ProcBy
procedure TCsReplyProceduresPrim.Cleanup;
{* Функция очистки полей объекта. }
//#UC START# *479731C50290_537F645C01D1_var*
//#UC END# *479731C50290_537F645C01D1_var*
begin
//#UC START# *479731C50290_537F645C01D1_impl*
FreeAndNil(f_Synchronizer);
FreeAndNil(f_List);
inherited;
//#UC END# *479731C50290_537F645C01D1_impl*
end;//TCsReplyProceduresPrim.Cleanup
{$IfEnd} // Defined(AppServerSide) AND NOT Defined(Nemesis)
end.
|
{$I ok_sklad.inc}
unit WaybillOutClass;
interface
uses
XMLDoc, XMLIntf,
WayBillClass, WBMetaItem, MetaClass;
type
TWaybillOutClass = class(TWayBillClass)
private
FWarehouseID: Integer; // common WH if all positions are from/to the same place
function LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean;
public
constructor Create(const AParent: TMetaClass); overload;
constructor Create(AID: Integer); overload;
//destructor Destroy;
procedure Clear;
function Load(const AID: integer): Boolean;
function Save: Boolean;
procedure loadXMLcallback(const topNode, cbNode: IXMLNode);
function LoadXML(var AFile: String): Boolean; overload;
function LoadXML(var Node: IXMLNode): Boolean; overload;
function SaveXML(out AOutStr: String): Integer; overload;
function SaveXML(var AFile: TextFile): Integer; overload;
end; // TWaybillOutClass
//==============================================================================================
//==============================================================================================
//==============================================================================================
//==============================================================================================
implementation
uses
Types, Forms, Controls, SysUtils, DB, Variants,
//prConst, ShellAPI, StdConvs, ssRegUtils, ssStrUtil, okMoneyFun
WebReq, MetaTax, prConst, prTypes, ssFun, ClientData, prFun, udebug;
var
DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = '';
//==============================================================================================
procedure TWaybillOutClass.Clear;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWaybillOutClass.Clear') else _udebug := nil;{$ENDIF}
inherited;
FWarehouseID := -1;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
constructor TWaybillOutClass.Create(const AParent: TMetaClass);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWaybillOutClass.Create') else _udebug := nil;{$ENDIF}
inherited;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
constructor TWaybillOutClass.Create(AID: Integer);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWaybillOutClass.Create(' + IntToStr(AID) + ')') else _udebug := nil;{$ENDIF}
Create(nil);
Load(AID);
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
(*
procedure TWaybillOutClass.ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
begin
aOk.Enabled := (Trim(edNum1.Text) <> '')
and (edDate.Text <> '')
and (edKAgent.KAID > 0)
and (cbCurr.KeyValue > 0)
and (not mdDet.IsEmpty);
aApply.Enabled := aOk.Enabled and (FModified or FPosModified or FPayDocModified)
and (FOrderID = 0);
aCIns.Enabled := (FOrderID = 0);
itmAdd.Enabled := (FOrderID = 0);
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.aCDelExecute(Sender: TObject);
var
FItem: TListItem;
i: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.aCDelExecute') else _udebug := nil;{$ENDIF}
Screen.Cursor := crSQLWait;
mdDet.DisableControls;
try
for i := 0 to dbgWaybillDet.SelectedCount - 1 do begin
if mdDet.Locate('posid', dbgWaybillDet.SelectedNodes[i].Values[colPosID.Index], []) then
if ((mdDet.FindField('locked') <> nil) and (mdDet.FieldByName('locked').AsInteger <> 1))
or (mdDet.FindField('locked') = nil)
then mdDet.Delete;
end;
LocateAfterDel;
RecalcSvc;
FGridRefresh := True;
finally
Screen.Cursor := crDefault;
mdDet.EnableControls;
SelectFocusedNode;
RealignGrid;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.aCUpdExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.aCUpdExecute') else _udebug := nil;{$ENDIF}
Screen.Cursor := crSQLWait;
case mdDet.FieldByName('postype').AsInteger of
0: with TfrmEditPosition.Create(frmEditPosition) do
try
ParentNameEx := Self.ParentNameEx;
OnDate := Self.OnDate;
WID := lcbWH.WID;
dbgWaybillDet.SetFocus;
PosNDS := FVAT;
NDSPayer := CurrEnt.NDSPayer;
ParentHandle := Self.Handle;
CurrID := cbCurr.KeyValue;
Kurs := CurKurs;
parentMdDet := mdDet; //Tag := integer(mdDet);
CurrName := cdsCurr.fieldbyname('shortname').AsString;
CurrDefName := BaseCurrName;
CurrShortName := defCurrShortName;
ByOrder := FOrderID > 0;
id := mdDet.FieldByName('posid').AsInteger;
ShowModal;
finally
Free;
Screen.Cursor := crDefault;
end;//try
1: with TfrmEditPositionSvc.Create(nil) do
try
ParentHandle := Self.Handle;
ParentNameEx := Self.ParentNameEx;
OnDate := Int(edDate.Date) + Frac(edTime.Time);
FRateValue := Self.edRate.Value;
CurrID := Self.cbCurr.KeyValue;
mdDet := Self.mdDet;
chbSvcToPrice.Enabled := True;
PosNDS := StrToFloat(mdDet.fieldbyname('NDS').AsString);
ID := Self.mdDet.FieldByName('posid').AsInteger;
ShowModal;
finally
Free;
Screen.Cursor := crDefault;
end;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//Запись в mdDet NDS и Currid
//==============================================================================================
(*
function TWaybillOutClass.ChangeMats: boolean;
var
BM:TBookmark;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.ChangeMats') else _udebug := nil;{$ENDIF}
Result := True;
with mdDet do begin
BM := GetBookmark;
DisableControls;
try
try
First;
while not Eof do begin
Edit;
FieldByName('NDS').AsFloat := FVAT;
FieldByName('CurrId').AsFloat := cbCurr.KeyValue;
Post;
Next;
end;//while
except
Result := False;
end;
finally
GotoBookmark(BM);
FreeBookmark(BM);
EnableControls;
end;
end;//while
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.aAddKAExecute(Sender: TObject);
var
aid: integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.aAddKAExecute') else _udebug := nil;{$ENDIF}
if edContr.Editor.Focused
then edContr.ShowRef
else if lcbWH.Combo.Focused
then lcbWH.ShowRef
else if FCurrCtrl = lcbPersonName then begin
try aid := lcbPersonName.KeyValue; except aid := 0; end;
lcbPersonName.SetFocus;
lcbPersonName.Tag := 1;
ShowModalRef(Self, rtPersons, vtKAgent, 'TfmKAgent', Self.OnDate, aid);
lcbPersonName.Tag := 0;
end
else if FCurrCtrl = lcbPayType then begin
ShowFinance(Self, Date, 1);
end
else if FCurrCtrl = lcbCashDesks then begin
try aid := lcbCashDesks.KeyValue; except aid := 0; end;
lcbCashDesks.SetFocus;
ShowModalRef(Self, rtCashDesks, vtCashDesks, 'TfmCashDesks', Self.OnDate, aid);
end
else if FCurrCtrl = lcbPayMPerson then begin
try aid := lcbPayMPerson.KeyValue; except aid := 0; end;
lcbPayMPerson.SetFocus;
lcbPayMPerson.Tag := 1;
ShowModalRef(Self, rtPersons, vtKAgent, 'TfmKAgent', Self.OnDate, aid);
lcbPayMPerson.Tag := 0;
end
else if edKAgent.Editor.Focused then edKAgent.ShowRef;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.chbPayPropertiesChange(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.chbPayPropertiesChange') else _udebug := nil;{$ENDIF}
// Заполнение полей
if chbPay.Enabled then begin
if (chbPay.Checked)then begin
if PDOutAutoNum and (OldPayDocID = 0) then begin
FCurrPayNum := GetDocNum(dmData.SConnection,dtPDOut,1);
edPayNum.Text := PDOutPrefix+IntToStr(FCurrPayNum)+PDOutSuffix;
end
else edPayNum.Text := FPayNum;
edPaySumm.Tag := 1;
edPaySumm.Value := roundtoa(AllSummCurr, -2);
edPaySumm.Tag := 0;
end//if (chbPay.Checked)
else begin
if PDOutAutoNum and (OldPayDocID = 0) then begin
if GetDocNum(dmData.SConnection, dtPDOut, 0) = FCurrPayNum
then GetDocNum(dmData.SConnection, dtPDOut, -1);
end;
edPayNum.Text := '';
edPaySumm.Tag := 1;
edPaySumm.Value := 0;
edPaySumm.EditText := '';
edPaySumm.Tag := 0;
FPaySummChange := false;
end;//else
FPayDocModified := true;
end;//if chbPay.Enabled
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.aAddMatExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.aAddMatExecute') else _udebug := nil;{$ENDIF}
Screen.Cursor := crSQLWait;
with TfrmEditPosition.Create(frmEditPosition) do
try
ParentNameEx := Self.ParentNameEx;
OnDate := edDate.Date + edTime.Time;
WID := lcbWH.WID;
PosNDS := FVAT;
NDSPayer := CurrEnt.NDSPayer;
ParentHandle := Self.Handle;
CurrID := Self.cbCurr.KeyValue;
Kurs := CurKurs;
parentMdDet := mdDet; //Tag := integer(mdDet);
ByOrder := FOrderID > 0;
id := 0;
CurrDefName := BaseCurrName;
CurrShortName := defCurrShortName;
CurrName := cdsCurr.fieldbyname('shortname').AsString;
ShowModal;
finally
if not mdDet.IsEmpty then begin
dbgWaybillDet.SetFocus;
end;
Free;
Screen.Cursor := crDefault;
end;//try
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.aAddSvcExecute(Sender: TObject);
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.aAddSvcExecute') else _udebug := nil;{$ENDIF}
with TfrmEditPositionSvc.Create(nil) do
try
ParentHandle := Self.Handle;
ParentNameEx := Self.ParentNameEx;
OnDate := Int(edDate.Date) + Frac(edTime.Time);
FRateValue := Self.edRate.Value;
CurrID := Self.cbCurr.KeyValue;
mdDet := Self.mdDet;
PosNDS := NDS;
chbSvcToPrice.Enabled := True;
ShowModal;
dbgWaybillDet.SetFocus;
finally
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.FillMatsFromRef(DS: TssMemoryData);
var
FPosID: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.FillMatsFromRef') else _udebug := nil;{$ENDIF}
with mdDet do begin
if not mdDet.Active then mdDet.Open;
DS.First;
mdDet.DisableControls;
while not DS.Eof do begin
FPosID := dsNextPosID(mdDet);
Append;
FieldByName('posid').AsInteger := FPosID;
FieldByName('matid').AsInteger := DS.FieldByName('matid').AsInteger;
FieldByName('postype').AsInteger := DS.Tag;
if DS.Tag = 1 then FieldByName('norm').AsFloat := 1;
FieldByName('discount').AsFloat := 0;
FieldByName('matname').AsString := DS.FieldByName('name').AsString;
FieldByName('msrname').AsString := DS.FieldByName('msrname').AsString;
FieldByName('artikul').AsString := DS.FieldByName('artikul').AsString;
FieldByName('amount').AsFloat := DS.FieldByName('amount').AsFloat;
FieldByName('price').AsFloat := DS.FieldByName('price').AsFloat;
FieldByName('fullprice').AsFloat := DS.FieldByName('price').AsFloat;
if CurrEnt.NDSPayer
then FieldByName('nds').AsFloat := FVAT
else FieldByName('nds').AsFloat := 0;
FieldByName('currid').AsInteger := cbCurr.KeyValue;
FieldByName('wid').AsInteger := lcbWH.WID;
FieldByName('whname').AsString := lcbWH.Combo.Text;
FieldByName('currname').AsString := cbCurr.Text;
FieldByName('onvalue').AsFloat := edRate.Value;
FieldByName('producer').AsString := DS.FieldByName('producer').AsString;
FieldByName('barcode').AsString := DS.FieldByName('barcode').AsString;
Post;
UpdatePos;
DS.Next;
end;
end;
RecalcSvc;
mdDet.EnableControls;
FGridRefresh := True;
dbgWaybillDet.Adjust(nil, [colPosType, colRecNo]);
dbgWaybillDet.ClearSelection;
if dbgWaybillDet.FocusedNode <> nil
then dbgWaybillDet.FocusedNode.Selected := True;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
function TWaybillOutClass.CreateByOrder(AID: Integer): Integer;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.CreateByOrder') else _udebug := nil;{$ENDIF}
Result := 0;
with newDataSet do
try
mdDet.Close;
mdDet.Open;
FOrderID := AID;
ProviderName := 'pWaybill_Get';
FetchParams;
Params.ParamByName('wbillid').AsInteger := AID;
Open;
edKAgent.OnChange := nil;
edKAgent.KAID := FieldByName('kaid').AsInteger;
edKAgent.OnChange := edKAgentChange;
edKAgent.Enabled := False;
edContr.Enabled := False;
edReason.Text := rs('fmWaybill', 'ByOrder',1) + amountPrefix + FieldByName('num').AsString;
edDate.Date := Self.OnDate;
cbCurr.KeyValue := FieldByName('currid').AsInteger;
if FieldByName('attnum').AsString <> '' then lcbWH.WID := FieldByName('attnum').AsInteger;
edRate.Value := FieldByName('onvalue').AsFloat;
Close;
ProviderName := 'pDocsRel_WB_Contr_Get';
FetchParams;
Params.ParamByName('wbillid').AsInteger := AID;
Params.ParamByName('doctype').AsInteger := 8;
Open;
if not IsEmpty then begin
edContr.DocID := FieldByName('rdocid').AsInteger;
end;
Close;
ProviderName := prvDet;
FetchParams;
Params.ParamByName('wbillid').AsInteger := AID;
Open;
mdDet.LoadFromDataSet(Fields[0].DataSet);
mdDet.First;
while not mdDet.Eof do begin
mdDet.Edit;
mdDet.FieldByName('fullprice').AsFloat := mdDet.FieldByName('price').AsFloat;
mdDet.Post;
UpdatePos;
mdDet.Next;
end;
mdDet.First;
if not mdDet.IsEmpty then begin
if dbgWaybillDet.FocusedNode = nil
then dbgWaybillDet.FocusedAbsoluteIndex := 0;
dbgWaybillDet.FocusedNode.Selected := True;
end;
Close;
finally
Free;
end;
cbCurr.Enabled := False;
FRateChanged := True;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.UpdatePos;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.UpdatePos') else _udebug := nil;{$ENDIF}
inherited;
with mdDet do begin
if FieldByName('postype').AsInteger = 1 then begin
if mdSvc.Locate('posid', FieldByName('posid').AsInteger, [])
then mdSvc.Edit
else mdSvc.Append;
mdSvc.FieldByName('posid').AsInteger := FieldByName('posid').AsInteger;
mdSvc.FieldByName('amount').AsFloat := FieldByName('amount').AsFloat;
mdSvc.FieldByName('norm').AsFloat := FieldByName('norm').AsFloat;
mdSvc.FieldByName('svctoprice').AsInteger := FieldByName('svctoprice').AsInteger;
mdSvc.FieldByName('price').AsFloat := FieldByName('price').AsFloat;
mdSvc.FieldByName('total').AsFloat := FieldByName('sumcurr').AsFloat;
mdSvc.FieldByName('totalwithnds').AsFloat := FieldByName('sumwithnds').AsFloat;
mdSvc.Post;
RecalcSvc;
end;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
(*
procedure TWaybillOutClass.RecalcSvc;
var
FTotAmount, FSvcSum: Extended;
BM: TBookmark;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.RecalcSvc') else _udebug := nil;{$ENDIF}
FTotAmount := 0;
with mdDet do
try
DisableControls;
BM := mdDet.GetBookmark;
First;
while not Eof do begin
if FieldByName('postype').AsInteger = 0
then FTotAmount := FTotAmount + FieldByName('amount').AsFloat * FieldByName('fullprice').AsFloat;
Next;
end;
if FTotAmount = 0 then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
FSvcSum := GetDSSummCurr(mdSvc, 'total', 'svctoprice', 1);
First;
while not Eof do begin
if FieldByName('postype').AsInteger = 0 then begin
Edit;
FieldByName('price').AsFloat := FieldByName('fullprice').AsFloat + FSvcSum * FieldByName('fullprice').AsFloat / FTotAmount;
Post;
UpdatePos;
end;
Next;
end;
finally
GotoBookmark(BM);
FreeBookmark(BM);
EnableControls;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
*)
//==============================================================================================
function TWaybillOutClass.Load(const AID: integer): Boolean;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWaybillOutClass.Load') else _udebug := nil;{$ENDIF}
Screen.Cursor := crSQLWait;
Result := False;
Clear;
isCorrupted := True; // pre-marking in case of disaster
with newDataSet do
try
ProviderName := 'pWaybill_Get';
FetchParams;
Params.ParamByName('wbillid').AsInteger := AID;
Open;
if IsEmpty then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end;
FNumber := fieldbyname('num').AsString;
FWBSeqNumber := fieldbyname('defnum').AsInteger;
FDate := fieldbyname('ondate').AsDateTime;
FBusinessPartner.Clear;
FBusinessPartner.loadData(fieldbyname('kaid').AsInteger);
if not fieldbyname('personid').IsNull
then FPersonID := fieldbyname('personid').AsInteger;
FReason := fieldbyname('REASON').asstring;
FNotes := FieldByName('notes').AsString;
FCurrencyID := fieldbyname('CURRID').AsInteger;
FCurrencyRate := FieldByName('onvalue').AsFloat;
FPosted := (fieldbyname('CHECKED').AsInteger = 1);
FVAT := fieldbyname('NDS').AsFloat;
if FieldByName('attnum').AsString = ''
then FWarehouseID := 0
else
try
FWarehouseID := StrToInt(FieldByName('attnum').AsString);
except
end;
Close; // pWaybill_Get
(*// if based on order
ProviderName := 'pDocsRel_WB_WB_Get';
FetchParams;
Params.ParamByName('wbillid').AsInteger := FID;
Params.ParamByName('doctype').AsInteger := 16;
Open;
if not IsEmpty
then FOrderID := FieldByName('wbillid').AsInteger
else FOrderID := 0;
Close;
// getting binded contract if any
ProviderName := 'pDocsRel_WB_Contr_Get';
FetchParams;
Params.ParamByName('wbillid').AsInteger := FID;
Params.ParamByName('doctype').AsInteger := 8;
Open;
if not IsEmpty then begin
edContr.DocID := FieldByName('rdocid').AsInteger;
FContrDocID := edContr.DocID;
end
else edContr.DocID := 0;
Close;
*)
FItems.Load(AID, True); // generate exception on error
Fid := AID;
FNew := False;
FModified := false;
isCorrupted := False;
Result := True;
finally
Free;
end;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
//==============================================================================================
//==============================================================================================
function TWaybillOutClass.Save: Boolean;
var
NewRecord: Boolean;
tmpid, FPosID, intTmp: Integer;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TWaybillOutClass.Save') else _udebug := nil;{$ENDIF}
Result := False;
with newDataSet do begin
try
Screen.Cursor := crSQLWait;
NewRecord := (ID = 0);
if NewRecord then FID := GetMaxID(dmData.SConnection, 'waybilllist', 'wbillid');
TrStart;
try
if NewRecord
then ProviderName := 'pWaybill_InsEx'
else ProviderName := 'pWaybill_UpdEx';
FetchParams;
Params.ParamByName('WBILLID').AsInteger := FID;
Params.ParamByName('NUM').AsString := FNumber;
if FWBSeqNumber > 0
then Params.ParamByName('DEFNUM').AsInteger := FWBSeqNumber
else Params.ParamByName('DEFNUM').AsInteger := GetNextDefNum(dmData.SConnection, 1);
Params.ParamByName('ONDATE').AsDateTime := FDate;
Params.ParamByName('KAID').AsInteger := FBusinessPartner.ID;
Params.ParamByName('CURRID').AsInteger := FCurrencyID;
Params.ParamByName('ONVALUE').AsFloat := FCurrencyRate;
Params.ParamByName('ATTNUM').AsString := ''; // warehouse for entire doc
Params.ParamByName('ATTDATE').AsDate := 0;
Params.ParamByName('REASON').AsString := FReason;
Params.ParamByName('notes').AsString := FNotes;
Params.ParamByName('PERSONID').AsInteger := FPersonID;
Params.ParamByName('CHECKED').AsInteger := integer(FPosted);
Params.ParamByName('WTYPE').AsInteger := wbtWaybillOut;
Params.ParamByName('DELETED').AsInteger := 0;
Params.ParamByName('SUMMALL').AsFloat := RoundToA(FItems.Total, -2);
Params.ParamByName('SUMMINCURR').AsFloat := FItems.TotalInDefCurr;
Params.ParamByName('NDS').AsFloat := roundtoa(FVAT, -2);
Params.ParamByName('RECEIVED').AsString := '';
Params.ParamByName('TODATE').DataType := ftDateTime;
Params.ParamByName('TODATE').Clear;
Params.ParamByName('entid').DataType := ftInteger;
Params.ParamByName('entid').Clear;
Execute;//Записали в waybilllist
if not FItems.Save then raise Exception.Create('Positions saving problem');
(*
then begin // Запись позиций в накладную
ProviderName := 'pWaybillDet_Del';
FetchParams;
Params.ParamByName('WBILLID').AsInteger := ID;
Execute; //Удалили позиции
ProviderName := 'pWaybillSvc_Del';
FetchParams;
Params.ParamByName('wbillid').AsInteger := FID;
Execute;
BM := mdDet.GetBookmark;
mdDet.DisableControls;
mdDet.First; // Запись позиций из mdDet в waybilldet
while not mdDet.Eof do begin
if mdDet.FieldByName('postype').AsInteger = 0 then begin
if (FOrderID > 0) and NewRecord then begin
FPosID := GetMaxID(dmData.SConnection, 'waybilldet', 'posid');
ProviderName := 'pWaybillDet_CopyPos';
FetchParams;
Params.ParamByName('posid').AsInteger := FPosID;
Params.ParamByName('oldposid').AsInteger := mdDet.FieldByName('posid').AsInteger;
Execute;
ProviderName := 'pPosRel_Ins';
FetchParams;
Params.ParamByName('posid').AsInteger := FPosID;
Params.ParamByName('cposid').AsInteger := mdDet.FieldByName('posid').AsInteger;
Execute;
ProviderName := 'pWaybillDet_UpdExIn';
end
else ProviderName := 'pWaybillDet_InsIn';
FetchParams;
if (FOrderID > 0) and NewRecord
then FPosID := mdDet.FieldByName('posid').AsInteger
else FPosID := GetMaxID(dmData.SConnection, 'waybilldet', 'posid');
Params.ParamByName('posid').AsInteger := FPosID;
if FPosID < 0 then raise Exception.Create(rs('fmWaybill', 'ErrorAddPos'));
tmpid := Params.ParamByName('POSID').AsInteger;
Params.ParamByName('wbillid').AsInteger := FID;
Params.ParamByName('MATID').AsInteger := mdDet.fieldbyname('MATID').AsInteger;
Params.ParamByName('WID').AsInteger := mdDet.fieldbyname('WID').AsInteger;
Params.ParamByName('AMOUNT').AsFloat := RoundToA(strtofloat(mdDet.fieldbyname('AMOUNT').AsString), MatDisplayDigits);
Params.ParamByName('onvalue').AsFloat := StrToFloat(mdDet.fieldbyname('onvalue').AsString);
Params.ParamByName('PRICE').AsFloat := RoundToA(strtofloat(mdDet.fieldbyname('PRICE').AsString), -6);
Params.ParamByName('baseprice').AsFloat := RoundToA(strtofloat(mdDet.fieldbyname('fullprice').AsString), -6);
Params.ParamByName('DISCOUNT').DataType := ftFloat;
Params.ParamByName('DISCOUNT').Clear;
Params.ParamByName('NDS').AsFloat := StrToFloat(mdDet.FieldByName('nds').AsString);
Params.ParamByName('CurrId').AsInteger := cbCurr.KeyValue;
Params.ParamByName('OnDate').AsDateTime := edDate.Date + edTime.Time;
Params.ParamByName('PTypeID').DataType := ftInteger;
Params.ParamByName('PTypeID').Clear;
Params.ParamByName('NUM').AsInteger := mdDet.RecNo;
Params.ParamByName('total').AsFloat := 0;
Execute;//Записываем очередную позицию
//write s/n
if not mdDet.fieldbyname('sn').IsNull then begin
ProviderName := 'rSN_Ins';
FetchParams;
Params.ParamByName('sid').AsInteger := GetMaxID(dmData.SConnection, 'serials', 'sid');
Params.ParamByName('posid').AsInteger := FPosID;
Params.ParamByName('serialno').AsString := mdDet.fieldbyname('sn').AsString;
Execute;
end;//if
ProviderName := 'pWaybillDetAP_Del'; // clear old positions in waybilldetaddprops
FetchParams;
Params.ParamByName('posid').AsInteger := FPosID;
Execute;
if (mdDet.FieldByName('producer').AsString <> '') or (mdDet.FieldByName('certnum').AsString <> '')
or (mdDet.FieldByName('gtd').AsString <> '') or (mdDet.FieldByName('certdate').AsDateTime <> 0)
then begin
ProviderName := 'pWaybillDetAP_Ins';
FetchParams;
Params.ParamByName('posid').AsInteger := FPosID;
Params.ParamByName('producer').AsString := mdDet.FieldByName('producer').AsString;
Params.ParamByName('certnum').AsString := mdDet.FieldByName('certnum').AsString;
Params.ParamByName('gtd').AsString := mdDet.FieldByName('gtd').AsString;
if mdDet.FieldByName('certdate').AsDateTime = 0 then begin
Params.ParamByName('certdate').DataType := ftDateTime;
Params.ParamByName('certdate').Clear;
end
else Params.ParamByName('certdate').AsDateTime := mdDet.FieldByName('certdate').AsDateTime;
Params.ParamByName('cardid').DataType := ftInteger;
Params.ParamByName('cardid').Clear;
Execute;
end;
end // if mdDet.FieldByName('postype').AsInteger = 0
else begin
ProviderName := 'pWaybillSvc_InsIn';
FetchParams;
FPosID := GetMaxID(dmData.SConnection, 'waybillsvc', 'posid');
Params.ParamByName('posid').AsInteger := FPosID;
Params.ParamByName('wbillid').AsInteger := FID;
Params.ParamByName('svcid').AsInteger := mdDet.fieldbyname('matid').AsInteger;
Params.ParamByName('amount').AsFloat := RoundToA(StrToFloat(mdDet.fieldbyname('amount').AsString), MatDisplayDigits);
Params.ParamByName('price').AsFloat := StrToFloat(mdDet.fieldbyname('price').AsString);
Params.ParamByName('norm').AsFloat := StrToFloat(mdDet.fieldbyname('norm').AsString);
Params.ParamByName('discount').AsFloat := StrToFloat(mdDet.fieldbyname('discount').AsString);
Params.ParamByName('nds').AsFloat := StrToFloat(mdDet.fieldbyname('NDS').AsString);
Params.ParamByName('currid').AsInteger := cbCurr.KeyValue;
Params.ParamByName('num').AsInteger := mdDet.RecNo;
Params.ParamByName('svctoprice').AsInteger := mdDet.FieldByName('svctoprice').AsInteger;
if not mdDet.FieldByName('personid').IsNull
then Params.ParamByName('personid').AsInteger := mdDet.FieldByName('personid').AsInteger
else begin
Params.ParamByName('personid').DataType := ftInteger;
Params.ParamByName('personid').Clear;
end;
Execute;
end;
mdDet.Next;
end;//while not mdDet.Eof
mdDet.GotoBookmark(BM);
FreeBookmark(BM);
mdDet.EnableControls;
FPosModified := False;
end; //if FPosModified
if (FOrderID > 0) and NewRecord then begin
ProviderName := 'pDocsRel_WB_Acc_Ins';
FetchParams;
Params.ParamByName('wbillid').AsInteger := FID;
Params.ParamByName('accid').AsInteger := FOrderID;
Execute;
ProviderName := 'pOrder_UpdStatus';
FetchParams;
Params.ParamByName('wbillid').AsInteger := FOrderID;
if chbPosting.Checked
then Params.ParamByName('checked').AsInteger := 1
else Params.ParamByName('checked').AsInteger := 2;
Execute;
end;
if FOrderID = 0 then begin
if chbPosting.Checked then begin //Если документ проведён то
//1)Удаление из оборотов //записываем позиции на склад
ProviderName := 'pWMatTurn_Del';
FetchParams;
Params.ParamByName('WBILLID').AsInteger := FID;
Execute;
//4)Запись в обороты
ProviderName := 'pWMatTurn_Ins';
FetchParams;
Params.ParamByName('WBILLID').AsInteger := FID;
Execute;
end // if chbPosting.Checked
else begin //Если документ не проведён, то удаляем позиции со склада
//1)Удаление из оборотов
ProviderName := 'pWMatTurn_Del';
FetchParams;
Params.ParamByName('WBILLID').AsInteger := FID;
Execute;
end;//else if chbPosting.Checked
end // if FOrderID = 0 (no related order)
else begin // have related order
ProviderName := 'pWMatTurn_Upd';
FetchParams;
Params.ParamByName('wbillid').AsInteger := FID;
if chbPosting.Checked
then Params.ParamByName('turntype').AsInteger := matTurnIn
else Params.ParamByName('turntype').AsInteger := matTurnOrdered;
Execute;
end;
FModified := False;
*)
TrCommit;
setModified(False);
FNew := False;
except
on e:exception do begin
TrRollback;
raise;
end;
end;
DoRecalcKASaldo(dmData.SConnection, FBusinessPartner.ID, FDate, rs('fmWaybill', 'RecalcBallance'));
RefreshFun('TfmWMat', 0);
RefreshFun('TfmPayDoc', 0);
RefreshFun('TfmFinance', 0);
{if RefreshAllClients then begin
dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_WBIN);
dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_WMAT);
dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_KAGENTS);
end;
}
finally
Free;
Screen.Cursor := crDefault;
end;
end;// with newDataSet
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;//FormCloseQuery
//==============================================================================================
function TWayBillOutClass.LoadXMLNode(var topNode, Node: IXMLNode; paramIndex: Integer = -1): Boolean;
{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.loadXMLNode') else _udebug := nil;{$ENDIF}
//stub
Result := True;
Ferror := 0;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TWaybillOutClass.LoadXML(var Node: IXMLNode): Boolean;
var
propNode: IXMLNode;
listNode: IXMLNode;
pos: TWBMetaItem;
name, data, FLastGen, docPrefix, docSuffix: String;
i, defWarehouse, FnewNum: Integer;
datefmt: TFormatSettings;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.loadXML(Node)') else _udebug := nil;{$ENDIF}
Result := False;
if (Node = nil) or (Node.ChildNodes.Count = 0) then begin
Ferror := ap_err_XML_badData;
Exit;
end;
//GetLocaleFormatSettings(..., datefmt);
datefmt.DateSeparator := '-';
datefmt.TimeSeparator := ':';
datefmt.ShortDateFormat := 'yyyy-mm-dd';
with newDataSet do begin
ProviderName := 'pWHouse_GetDef';
Open;
defWarehouse := Fields[0].asInteger;
Close;
Free;
end;
Node.OwnerDocument.Options := Node.OwnerDocument.Options + [doAttrNull];
propNode := Node.ChildNodes.First;
try //finally
repeat // for each prop
name := AnsiLowerCase(propNode.NodeName);
data := trim(propNode.Text);
if name = 'waybillout' then begin
try
if VarIsNull(propNode.Attributes[Name]) then begin
// getting new local ID for this doc
docPrefix := wbOutPrefix;
docSuffix := wbOutSuffix;
FLastGen := '';
FnewNum := GetDocNumEx(dmData.SConnection, dtwbOut, 1, docPrefix, docSuffix, FLastGen, currEnt.kaid);
FNumber := docPrefix + IntToStr(FnewNum) + docSuffix;
end
else FNumber := propNode.Attributes[Name];
except
Ferror := ap_err_XML_badID;
Exit;
end;
end
//..................................................
else if name = 'date' then begin
try
FDate := strToDateTime(data, datefmt);
except
Ferror := ap_err_XML_badDate;
Exit;
end;
end
//..................................................
else if name = 'notes' then begin
FNotes := data;
end
//..................................................
else if name = 'totaltaxes' then begin
try
FTaxes.Add(TaxMethodValue, XMLStrToFloat(data));
except
Ferror := ap_err_XML_badTaxes;
Exit;
end;
end
//..................................................
else if name = 'total' then begin
try
FSummAll := XMLStrToFloat(data);
except
Ferror := ap_err_XML_badTotal;
Exit;
end;
end
//..................................................
else if name = 'customer' then begin
FBusinessPartner.LoadXML(Node);
end
//..................................................
else if name = 'items' then begin
if not FItems.loadXML(Node) then Exit;
end; // items
Result := inherited loadXMLNode(propNode, Node); // maybe some base-class stuff
try
propNode := propNode.NextSibling;
except
Break;
end;
until propNode = nil;
Result := True;
setModified(True);
finally
isCorrupted := not Result;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
end;
//==============================================================================================
function TWaybillOutClass.LoadXML(var AFile: String): Boolean;
var
xdoc: iXMLDocument;
Node: IXMLNode;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.LoadXML('+AFile+')') else _udebug := nil;{$ENDIF}
xdoc := LoadXMLDocument(AFile);
try
Node := xdoc.DocumentElement.ChildNodes.First;
except
Node := nil;
end;
if node <> nil
then Result := LoadXML(Node)
else begin
Result := False;
Ferror := ap_err_XML_emptyDoc;
end;
xdoc := nil;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
procedure TWaybillOutClass.loadXMLcallback(const topNode, cbNode: IXMLNode);
begin
{if AnsiLowerCase(topNode.NodeName) = 'address' then begin
if AnsiLowerCase(cbNode.NodeName) = 'phone' then begin
//FPhone := trim(data);
end
//..................................................
else if AnsiLowerCase(cbNode.NodeName) = 'fax' then begin
//FFax := trim(data);
end
//..................................................
end;
}
end;
//==============================================================================================
function TWaybillOutClass.SaveXML(out AOutStr: String): Integer;
var
s: String;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.SaveXML(OutStr)') else _udebug := nil;{$ENDIF}
Result := 0;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
function TWaybillOutClass.SaveXML(var AFile: TextFile): Integer;
var
s: String;
{$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF}
begin
{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TWaybillOutClass.SaveXML(TextFile)') else _udebug := nil;{$ENDIF}
Result := 0;
{$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF}
end;
//==============================================================================================
initialization
{$IFDEF UDEBUG}
Debugging := False;
DEBUG_unit_ID := debugRegisterUnit('WaybillOutClass', @Debugging, DEBUG_group_ID);
{$ENDIF}
//==============================================================================================
finalization
//{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF}
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.