text stringlengths 14 6.51M |
|---|
Ejercicio 3 (40 puntos)
Dadas las siguientes declaraciones:
Se pide:
a) (25 puntos)
Implementar un procedimiento que cargue los datos de un arreglo de tipo
TArregloTope en una lista de tipo TListaInt. La lista debe quedar ordenada de forma
creciente. Observar que la lista puede contener elementos (ya ordenados en forma
creciente) al ser invocado el procedimiento.
procedure CargaArr (a : TArregloTope; var lis : TlistaInt);
Ejemplo:
Para
a = [205, 314, 522, 112, 709, 421]
y
lis = <100, 345>
CargaArr(a, lis) devuelve lis = <100, 112, 205, 314, 345, 421, 522, 709>
b) (15 puntos) Implementar una función que, dados un entero y una lista ordenada
creciente de tipo TListaInt, indique si ese entero se encuentra o no en la lista.
function esMiembro (i : Integer; lis : TListaInt) : Boolean;
Const Max = ... ; (* valor mayor que 0 *)
Type
TListaInt = ^Celda;
Celda = Record
elem : Integer;
sig : TListaInt;
end;
TArregloTope = Record
valores : Array[1..Max] of Integer;
tope : 0..Max;
end;
procedure CargaArr (a : TArregloTope; var lis : TlistaInt);
procedure InsertarOrdenLista(elem:integer;var lista:TlistaInt);
var celda, aux: TlistaInt;
begin
new(celda)
celda^.elem := elem;
if (lista = nil) or (elem <= lista^.elem) then
begin
celda^.sig := lista;
lista := celda;
end
else
begin
aux:= lista;
while (aux^.sig <> nil) and (aux^.sig^.elem < elem) do
aux := aux^.sig;
celda^.sig := aux^.sig;
aux^.sig := celda;
end;
var i: integer;
begin
for i:=1 to a.tope do
InsertarOrdenLista(a.valores[i],lis);
end;
function esMiembro (i : Integer; lis : TListaInt) : Boolean;
begin
if (lis = nil) then
esMiembro := false
else
begin
while (lis <> nil) and (lis^.elem <> i) do
lis := lis^.sig;
esMiembro := (lis^.elem = i);
end;
end; |
unit DaoDumper;
(*
Dedicated to dumping DAO structures.
Every object which has "Properties" can be queried through these.
They contain all the individual fields and more.
*)
interface
uses SysUtils, ComObj, DAO_TLB, JetCommon;
procedure PrintDaoSchema(dao: Database);
implementation
//Prints the contents of DAO recordset (all records and fields)
procedure DumpDaoRecordset(rs: Recordset);
var i: integer;
begin
while not rs.EOF do begin
for i := 0 to rs.Fields.Count - 1 do
writeln(rs.Fields[i].Name+'='+str(rs.Fields[i].Value));
writeln('');
rs.MoveNext();
end;
end;
procedure PrintDaoTable(dao: Database; TableName: string);
begin
SubSection('Table: '+TableName);
DumpDaoRecordset(dao.ListFields(TableName));
end;
procedure PrintDaoTables(dao: Database);
var rs: Recordset;
begin
rs := dao.ListTables;
DumpDaoRecordset(rs);
rs.MoveFirst;
while not rs.EOF do begin
try
PrintDaoTable(dao, rs.Fields['Name'].Value);
except
//Sometimes we don't have sufficient rights
on E: EOleException do
writeln(E.Classname + ': '+ E.Message);
end;
rs.MoveNext;
end;
end;
type
TPropertyNames = array of WideString;
//Handy function for inplace array initialization
function PropNames(Names: array of WideString): TPropertyNames;
var i: integer;
begin
SetLength(Result, Length(Names));
for i := 0 to Length(Names) - 1 do
Result[i] := Names[i];
end;
function IsBanned(Banned: TPropertyNames; PropName: WideString): boolean;
var i: integer;
begin
Result := false;
for i := 0 to Length(Banned) - 1 do
if WideSameText(Banned[i], PropName) then begin
Result := true;
exit;
end;
end;
//Many DAO objects have Properties
// Prop1=Value1
// Prop2=Value2 (inherited)
procedure DumpDaoProperties(Props: Properties; Banned: TPropertyNames);
var i: integer;
prop: Property_;
proptype: integer;
propname: WideString;
propval: WideString;
propflags: WideString;
procedure AddPropFlag(flag: WideString);
begin
if propflags='' then
propflags := flag
else
propflags := ', ' + flag;
end;
begin
for i := 0 to Props.Count-1 do begin
prop := Props[i];
propname := prop.Name;
proptype := prop.type_;
//Some properties are unsupported in some objects, or take too long to query
if IsBanned(Banned, PropName) then begin
// writeln(PropName+'=[skipping]');
continue;
end;
propflags := '';
// AddPropFlag('type='+IntToStr(proptype)); //we mostly don't care about types
if prop.Inherited_ then
AddPropFlag('inherited');
if propflags <> '' then
propflags := ' (' + propflags + ')';
try
if proptype=0 then
propval := 'Unsupported type'
else
propval := str(prop.Value);
except
on E: EOleException do begin
propval := E.Classname + ': ' + E.Message;
end;
end;
writeln(
propname + '=',
propval,
propflags
);
end;
end;
type
TFieldKind = (fkRecordset, fkDefinition, fkParameter, fkRelation);
procedure PrintDaoField(f: _Field; FieldKind: TFieldKind);
var Banned: TPropertyNames;
begin
case FieldKind of
fkRecordset: Banned := PropNames(['ForeignName', 'Relation']);
fkDefinition: Banned := PropNames(['Value', 'ValidateOnSet', 'ForeignName', 'FieldSize', 'OriginalValue', 'VisibleValue']);
fkParameter: Banned := PropNames(['Value', 'ValidateOnSet', 'ForeignName', 'FieldSize', 'OriginalValue', 'VisibleValue']);
fkRelation: Banned := PropNames(['Value', 'ValidateOnSet', 'FieldSize', 'OriginalValue', 'VisibleValue'])
else
Banned := nil;
end;
DumpDaoProperties(f.Properties, Banned);
end;
//Many DAO objects have Fields collections
procedure PrintDaoFields(f: Fields; FieldKind: TFieldKind);
var i: integer;
begin
for i := 0 to f.Count - 1 do begin
PrintDaoField(f[i], FieldKind);
writeln('');
end;
end;
procedure PrintDaoIndex(f: Index);
begin
DumpDaoProperties(f.Properties, PropNames([]));
end;
procedure PrintDaoIndexes(f: Indexes);
var i: integer;
begin
for i := 0 to f.Count - 1 do begin
PrintDaoIndex(f[i]);
writeln('');
end;
end;
procedure PrintDaoParameter(f: Parameter);
begin
writeln(
f.Name + ': ',
f.type_,
' = ' + str(f.Value) + ' (dir:',
f.Direction,
')'
);
writeln('Properties:');
DumpDaoProperties(f.Properties, PropNames([]));
end;
procedure PrintDaoParameters(f: Parameters);
var i: integer;
begin
for i := 0 to f.Count - 1 do begin
PrintDaoParameter(f[i]);
writeln('');
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure PrintDaoTableDef(def: TableDef);
begin
DumpDaoProperties(def.Properties,
PropNames(['ConflictTable', 'ReplicaFilter', 'Connect']));
writeln('');
Subsection('Fields: ');
try
PrintDaoFields(def.Fields, fkDefinition);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
Subsection('Indexes:');
try
PrintDaoIndexes(def.Indexes);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
end;
procedure PrintDaoQueryDef(def: QueryDef);
begin
DumpDaoProperties(def.Properties,
PropNames(['StillExecuting', 'CacheSize', 'Prepare']));
writeln('');
Subsection('Fields:');
try
PrintDaoFields(def.Fields, fkParameter);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
Subsection('ListParameters:');
try
DumpDaoRecordset(def.ListParameters);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
Subsection('Parameters:');
try
PrintDaoParameters(def.Parameters);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
end;
procedure PrintDaoRelation(def: Relation);
begin
DumpDaoProperties(def.Properties, PropNames([]));
writeln('');
Subsection('Fields:');
try
PrintDaoFields(def.Fields, fkRelation);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
end;
////////////////////////////////////////////////////////////////////////////////
procedure PrintDaoSchema(dao: Database);
var i: integer;
begin
Section('Table Properties');
DumpDaoProperties(dao.Properties,
PropNames(['ReplicaID', 'DesignMasterID']));
Section('Tables (basic definitions)');
PrintDaoTables(dao);
for i := 0 to dao.TableDefs.Count-1 do try
Section('TableDef: '+dao.TableDefs[i].Name);
PrintDaoTableDef(dao.TableDefs[i]);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
for i := 0 to dao.QueryDefs.Count-1 do try
Section('QueryDef: '+dao.QueryDefs[i].Name);
PrintDaoQueryDef(dao.QueryDefs[i]);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
for i := 0 to dao.Relations.Count-1 do try
Section('Relation: '+dao.Relations[i].Name);
PrintDaoRelation(dao.Relations[i]);
except
on E: EOleException do
writeln(E.Classname + ': ' + E.Message);
end;
end;
end.
|
unit NPCompiler.ExpressionContext;
interface
uses System.SysUtils, NPCompiler.Classes, NPCompiler.Operators, NPCompiler.Contexts,
IL.Instructions, IL.Types;
type
PBoolExprNode = ^TBoolExprNode;
TBoolExprNode = record
type
TNodeOrientation = (NodeRoot, NodeLeft, NodeRight);
TNodeType = (
ntCmp, // любое сравнение
ntAnd, // логическое AND
ntOr // логическое OR
);
var
NodeType: TNodeType; // Тип нода
Parent: PBoolExprNode; // Parent в дереве
Orientation: TNodeOrientation; // Ориентация нода относительно Parent-а
Instruction: TILInstruction; // это последняя инструкция выражения; для типа ntNode это JMP инструкция
// для типов ntAnd, ntOr это IL последняя инструкциия правого выражения
LeftChild: PBoolExprNode; // Левый child
RightChild: PBoolExprNode; // Правый child
Condition: TILCondition; // Условия сравнения (только для типа ntNode)
LeftNode: PBoolExprNode; // Левый нод (по исходному коду)
RightNode: PBoolExprNode; // Правый нод (по исходному коду)
PrevNode: PBoolExprNode; // Предыдущий нод (в стеке)
end;
TExpessionPosition = (ExprNested, ExprLValue, ExprRValue, ExprNestedGeneric);
{expression context - use RPN (Reverse Polish Notation) stack}
TEContext = record
type
TRPNItems = array of TOperatorID;
TRPNStatus = (rprOk, rpOperand, rpOperation);
TRPNError = (reDublicateOperation, reUnnecessaryClosedBracket, reUnclosedOpenBracket);
TRPNPocessProc = function (var EContext: TEContext; OpID: TOperatorID): TIDExpression of object;
private
fRPNOArray: TRPNItems; // Operations array
fRPNEArray: TIDExpressions; // Operands array
fRPNOArrayLen: Integer; // пердвычисленный размер входного списка
fRPNOpCount: Integer; // указывает на следющий свободный элемент входного списка
fRPNEArrayLen: Integer; // пердвычисленный размер выходного списка
fRPNExprCount: Integer; // указывает на следющий свободный элемент выходного списка
fRPNLastOp: TOperatorID;
fRPNPrevPriority: Integer;
fProcessProc: TRPNPocessProc;
fPosition: TExpessionPosition; // позиция выражения (Nested, LValue, RValue...);
procedure RPNCheckInputSize;
function GetExpression: TIDExpression;
public
SContext: PSContext; // statement контекст
LastBoolNode: PBoolExprNode; // содерижт Root узел boolean выражений
LastInstruction: TILInstruction; // последняя инструкция на момент начала выражения
procedure Initialize(const ProcessProc: TRPNPocessProc);
procedure Reset; // clear RPN stack and reinit
procedure RPNPushExpression(Expr: TIDExpression);
procedure RPNError(Status: TRPNError);
procedure RPNPushOpenRaund;
procedure RPNPushCloseRaund;
procedure RPNEraiseTopOperator;
procedure RPNFinish;
property RPNExprCount: Integer read fRPNExprCount;
property RPNLastOp: TOperatorID read fRPNLastOp;
property Result: TIDExpression read GetExpression;
property EPosition: TExpessionPosition read fPosition write fPosition;
function RPNPopOperator: TIDExpression;
function RPNPushOperator(OpID: TOperatorID): TRPNStatus;
function RPNReadExpression(Index: Integer): TIDExpression; inline;
function RPNLastOperator: TOperatorID;
function RPNPopExpression: TIDExpression;
end;
PEContext = ^TEContext;
implementation
uses
NPCompiler, NPCompiler.Errors;
{ TRPN }
procedure TEContext.RPNCheckInputSize;
begin
if fRPNOpCount >= fRPNOArrayLen then begin
Inc(fRPNOArrayLen, 8);
SetLength(fRPNOArray, fRPNOArrayLen);
end;
end;
procedure TEContext.RPNPushExpression(Expr: TIDExpression);
begin
fRPNEArray[fRPNExprCount] := Expr;
Inc(fRPNExprCount);
if fRPNExprCount >= fRPNEArrayLen then begin
Inc(fRPNEArrayLen, 8);
SetLength(fRPNEArray, fRPNEArrayLen);
end;
fRPNLastOp := opNone;
end;
procedure TEContext.RPNError(Status: TRPNError);
begin
case Status of
reUnclosedOpenBracket: AbortWork(sUnclosedOpenBracket);
reDublicateOperation: AbortWork(sDublicateOperationFmt);
end;
end;
procedure TEContext.RPNPushOpenRaund;
begin
fRPNOArray[fRPNOpCount] := opOpenRound;
Inc(fRPNOpCount);
RPNCheckInputSize;
fRPNLastOp := opOpenRound;
end;
procedure TEContext.RPNPushCloseRaund;
var
op: TOperatorID;
begin
fRPNLastOp := opCloseRound;
while fRPNOpCount > 0 do begin
Dec(fRPNOpCount);
op := fRPNOArray[fRPNOpCount];
if op <> opOpenRound then begin
fRPNEArray[fRPNExprCount] := fProcessProc(Self, Op);
Inc(fRPNExprCount);
end else
Exit;
end;
RPNError(reUnnecessaryClosedBracket);
end;
function TEContext.RPNPopOperator: TIDExpression;
var
Op: TOperatorID;
begin
if fRPNOpCount > 0 then
begin
Dec(fRPNOpCount);
Op := fRPNOArray[fRPNOpCount];
Result := fProcessProc(Self, op);
end else
Result := nil;
end;
procedure TEContext.RPNFinish;
var
op: TOperatorID;
Expr: TIDExpression;
begin
while fRPNOpCount > 0 do
begin
Dec(fRPNOpCount);
op := fRPNOArray[fRPNOpCount];
if op <> opOpenRound then
begin
Expr := fProcessProc(Self, op);
fRPNEArray[fRPNExprCount] := Expr;
if Assigned(Expr) then
Inc(fRPNExprCount);
if fRPNOpCount > 0 then
fRPNLastOp := fRPNOArray[fRPNOpCount - 1]
else
fRPNLastOp := opNone;
fRPNPrevPriority := cOperatorPriorities[fRPNLastOp];
end else
RPNError(reUnclosedOpenBracket);
end;
end;
function TEContext.RPNPushOperator(OpID: TOperatorID): TRPNStatus;
var
Priority: Integer;
Op: TOperatorID;
begin
if OpID = fRPNLastOp then
RPNError(reDublicateOperation);
fRPNLastOp := OpID;
Priority := cOperatorPriorities[OpID];
if cOperatorTypes[OpID] <> opUnarPrefix then
begin
if (Priority <= fRPNPrevPriority) then
begin
while fRPNOpCount > 0 do begin
Op := fRPNOArray[fRPNOpCount - 1];
if (cOperatorPriorities[Op] >= Priority) and (Op <> opOpenRound) then
begin
Dec(fRPNOpCount);
fRPNEArray[fRPNExprCount] := fProcessProc(Self, Op);
Inc(fRPNExprCount);
end else
Break;
end;
end;
end;
fRPNPrevPriority := Priority;
fRPNOArray[fRPNOpCount] := OpID;
Inc(fRPNOpCount);
RPNCheckInputSize;
Result := rpOperation;
end;
function TEContext.RPNReadExpression(Index: Integer): TIDExpression;
begin
Result := fRPNEArray[Index];
end;
function TEContext.RPNLastOperator: TOperatorID;
begin
if fRPNOpCount > 0 then
Result := fRPNOArray[fRPNOpCount - 1]
else
Result := TOperatorID.opNone;
end;
function TEContext.RPNPopExpression: TIDExpression;
begin
Dec(fRPNExprCount);
if fRPNExprCount >= 0 then begin
Result := fRPNEArray[fRPNExprCount];
if Assigned(Result) then
Exit;
end;
AbortWorkInternal('Empty Expression');
Result := nil; // for prevent compiler warning
end;
procedure TEContext.Initialize(const ProcessProc: TRPNPocessProc);
begin
SetLength(fRPNOArray, 4);
fRPNOArrayLen := 4;
SetLength(fRPNEArray, 8);
fRPNEArrayLen := 8;
fRPNOpCount := 0;
fRPNExprCount := 0;
fRPNLastOp := opNone;
fRPNPrevPriority := 0;
LastBoolNode := nil;
LastInstruction := nil;
fProcessProc := ProcessProc;
end;
procedure TEContext.RPNEraiseTopOperator;
begin
Dec(fRPNOpCount);
end;
procedure TEContext.Reset;
begin
fRPNLastOp := opNone;
fRPNPrevPriority := 0;
fRPNOpCount := 0;
fRPNExprCount := 0;
if Assigned(SContext) then
LastInstruction := SContext.ILLast;
end;
function TEContext.GetExpression: TIDExpression;
begin
if fRPNExprCount > 0 then
Result := fRPNEArray[fRPNExprCount - 1]
else
Result := nil;
end;
end.
|
unit USaleOrder;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TFormSaleOrder = class(TForm)
LOrder: TLabel;
edtSaleNum: TEdit;
LSalerName: TLabel;
edtSalerName: TEdit;
edtSaleValue: TEdit;
edtClienteName: TEdit;
LOrderValue: TLabel;
LClienteName: TLabel;
btnSave: TButton;
procedure btnSaveClick(Sender: TObject);
protected
SQL: array of array of string;
function Check: boolean; virtual;
function Save: boolean; virtual;
function clear: boolean; virtual;
function Alert: boolean;
private
{ Private declarations }
public
{ Public declarations }
end;
var
FormSaleOrder: TFormSaleOrder;
implementation
{$R *.dfm}
{ TFormSaleOrder }
procedure TFormSaleOrder.btnSaveClick(Sender: TObject);
begin
if Check then
begin
Save;
Alert;
end
else
begin
Showmessage('Dados inválidos !');
end;
end;
function TFormSaleOrder.Check: boolean;
begin
if ((edtSaleNum.Text <> '') AND (edtSalerName.Text <> '') AND
(((Length(edtSalerName.Text)) <= 100)) AND (edtSaleValue.Text <> '') AND
(edtClienteName.Text <> '') AND ((Length(edtClienteName.Text)) <= 100)) then
begin
Result := True;
end
else
begin
Result := False;
end;
end;
function TFormSaleOrder.clear: boolean;
begin
Result := False;
edtSaleNum.clear;
edtSalerName.clear;
edtSaleValue.clear;
edtClienteName.clear;
Result := True;
end;
function TFormSaleOrder.Save: boolean;
begin
if Check then
begin
setLength(SQL, Length(SQL) + 1);
setLength(SQL[Length(SQL) - 1], 4);
SQL[Length(SQL) - 1, 0] := edtSaleNum.Text;
SQL[Length(SQL) - 1, 1] := edtSalerName.Text;
SQL[Length(SQL) - 1, 2] := edtSaleValue.Text;
SQL[Length(SQL) - 1, 3] := edtClienteName.Text;
Result := True;
end
else
begin
Showmessage('Could not save sale ' + edtSaleNum.Text + '.');
Result := False;
end;
end;
function TFormSaleOrder.alert: boolean;
begin
Result := False;
Showmessage('Sale ' + edtSaleNum.Text + ' saved with success.');
Result := True;
clear;
end;
end.
|
unit UConsoleConfig;
interface
uses
windows,IniFiles,SysUtils;
const
C_ROOT = 'system';
C_GAME = 'game';
C_NGPLUGS = 'NgPlugin';
type
TConsoleConfig = class
private
mActive:BOOL;
mDir:String; //模块所在目录
mCfgPath:String; //配置文件完整路径
mFileName:String;
mIni:TIniFile;
function GetAuthUrl: String;
function GetGameBin: string;
function GetGameId: Integer;
function GetPort: Integer;
public
constructor Create(Handle:Cardinal;FileName:String);
destructor Destroy;override;
//是否加载成功
property Active:Bool read mActive;
//模块目录
property ModuleDir:String read mDir;
//版本验证地址
property AuthUrl:String read GetAuthUrl;
//
property GameBin:string read GetGameBin;
property GameId:Integer read GetGameId;
property ConsolePort:Integer read GetPort;
end;
var
g_ConsoleConfig:TConsoleConfig;
implementation
uses
GD_Utils;
{ TConfig }
constructor TConsoleConfig.Create(Handle:Cardinal;FileName:String);
var
ModuleName:Array [0..MAX_PATH] of Char;
begin
mActive:=False;
try
if GetModuleFileName(Handle,ModuleName,MAX_PATH) > 0 then
begin
mFileName:=FileName;
mDir:=ExtractFileDir(ModuleName);
mCfgPath:=Format('%s\%s',[mDir,FileName]);
mActive:=FileExists(mCfgPath);
if mActive then
mIni:=TIniFile.Create(mCfgPath);
end;
except
LogPrintf('Config Load Error',[]);
end;
end;
destructor TConsoleConfig.Destroy;
begin
mIni.Free;
end;
function TConsoleConfig.GetAuthUrl: String;
begin
Result:= mIni.ReadString(C_ROOT,'ServerUrl','');
end;
function TConsoleConfig.GetGameBin: string;
begin
Result:= mIni.ReadString(C_GAME,'GameBin','');
end;
function TConsoleConfig.GetGameId: Integer;
begin
Result:= mIni.ReadInteger(C_GAME,'GameId',0);
end;
function TConsoleConfig.GetPort: Integer;
begin
Result:= mIni.ReadInteger(C_NGPLUGS,'Port',0);
end;
end.
|
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ 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 JclWin32.pas. }
{ }
{ The Initial Developer of the Original Code is documented in the accompanying }
{ help file JCL.chm. Portions created by these individuals are Copyright (C) of these individuals. }
{ }
{**************************************************************************************************}
{ }
{ This unit defines various Win32 API declarations which are either missing or incorrect in one or }
{ more of the supported Delphi versions. This unit is not intended for regular code, only API }
{ declarations. }
{ }
{ Unit owner: Peter Friese }
{ Last modified: February 21, 2002 }
{ }
{**************************************************************************************************}
unit JclWin32;
{$I jcl.inc}
{$WEAKPACKAGEUNIT ON}
interface
uses
Windows, ActiveX, ImageHlp, WinSvc,
{$IFDEF COMPILER5_UP}
AccCtrl, AclApi,
{$ENDIF COMPILER5_UP}
ShlObj;
//--------------------------------------------------------------------------------------------------
// Locales related
//--------------------------------------------------------------------------------------------------
function LANGIDFROMLCID(const lcid: LCID): Word;
function MAKELANGID(const usPrimaryLanguage, usSubLanguage: Byte): Word;
function PRIMARYLANGID(const lgid: Word): Word;
function SUBLANGID(const lgid: Word): Word;
function MAKELCID(const wLanguageID, wSortID: Word): LCID;
function SORTIDFROMLCID(const lcid: LCID): Word;
const
KLF_SETFORPROCESS = $00000100;
DATE_YEARMONTH = $00000008;
//--------------------------------------------------------------------------------------------------
// Various Base Services declarations
//--------------------------------------------------------------------------------------------------
function InterlockedExchangePointer(var Target: Pointer; Value: Pointer): Pointer;
stdcall; external kernel32 name 'InterlockedExchangePointer';
function SignalObjectAndWait(hObjectToSignal: THandle; hObjectToWaitOn: THandle;
dwMilliseconds: DWORD; bAlertable: BOOL): DWORD; stdcall; external kernel32
name 'SignalObjectAndWait';
const
// ProductType
VER_NT_WORKSTATION = $0000001;
VER_NT_DOMAIN_CONTROLLER = $0000002;
VER_NT_SERVER = $0000003;
// SuiteMask
VER_SUITE_SMALLBUSINESS = $00000001;
VER_SUITE_ENTERPRISE = $00000002;
VER_SUITE_BACKOFFICE = $00000004;
VER_SUITE_COMMUNICATIONS = $00000008;
VER_SUITE_TERMINAL = $00000010;
VER_SUITE_SMALLBUSINESS_RESTRICTED = $00000020;
VER_SUITE_EMBEDDEDNT = $00000040;
VER_SUITE_DATACENTER = $00000080;
VER_SUITE_SINGLEUSERTS = $00000100;
VER_SUITE_PERSONAL = $00000200;
VER_SUITE_SERVERAPPLIANCE = $00000400;
type
POSVersionInfoEx = ^TOSVersionInfoEx;
TOSVersionInfoEx = record
dwOSVersionInfoSize: DWORD;
dwMajorVersion: DWORD;
dwMinorVersion: DWORD;
dwBuildNumber: DWORD;
dwPlatformId: DWORD;
szCSDVersion: array [0..127] of Char; // Maintenance string for PSS usage
wServicePackMajor: Word;
wServicePackMinor: Word;
wSuiteMask: Word;
wProductType: Byte;
wReserved: Byte;
end;
function GetVersionEx(lpVersionInformation: POSVersionInfoEx): BOOL; stdcall;
function CreateMutex(lpMutexAttributes: PSecurityAttributes; bInitialOwner: DWORD;
lpName: PChar): THandle; stdcall; external kernel32 name 'CreateMutexA';
//==================================================================================================
// COM related declarations
//==================================================================================================
type
TCoCreateInstanceExProc = function (const clsid: TGUID;
unkOuter: IUnknown; dwClsCtx: Longint; ServerInfo: Pointer{PCoServerInfo};
dwCount: Longint; rgmqResults: Pointer{PMultiQIArray}): HResult stdcall;
//==================================================================================================
// Security related declarations from winnt.h
//==================================================================================================
/////////////////////////////////////////////////////////////////////////////
// //
// Universal well-known SIDs //
// //
// Null SID S-1-0-0 //
// World S-1-1-0 //
// Local S-1-2-0 //
// Creator Owner ID S-1-3-0 //
// Creator Group ID S-1-3-1 //
// Creator Owner Server ID S-1-3-2 //
// Creator Group Server ID S-1-3-3 //
// //
// (Non-unique IDs) S-1-4 //
// //
/////////////////////////////////////////////////////////////////////////////
const
SECURITY_NULL_SID_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 0));
SECURITY_WORLD_SID_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 1));
SECURITY_LOCAL_SID_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 2));
SECURITY_CREATOR_SID_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 3));
SECURITY_NON_UNIQUE_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 4));
SECURITY_NULL_RID = ($00000000);
SECURITY_WORLD_RID = ($00000000);
SECURITY_LOCAL_RID = ($00000000);
SECURITY_CREATOR_OWNER_RID = ($00000000);
SECURITY_CREATOR_GROUP_RID = ($00000001);
SECURITY_CREATOR_OWNER_SERVER_RID = ($00000002);
SECURITY_CREATOR_GROUP_SERVER_RID = ($00000003);
/////////////////////////////////////////////////////////////////////////////
// //
// NT well-known SIDs //
// //
// NT Authority S-1-5 //
// Dialup S-1-5-1 //
// //
// Network S-1-5-2 //
// Batch S-1-5-3 //
// Interactive S-1-5-4 //
// Service S-1-5-6 //
// AnonymousLogon S-1-5-7 (aka null logon session) //
// Proxy S-1-5-8 //
// ServerLogon S-1-5-9 (aka domain controller account) //
// Self S-1-5-10 (self RID) //
// Authenticated User S-1-5-11 (Authenticated user somewhere) //
// Restricted Code S-1-5-12 (Running restricted code) //
// Terminal Server S-1-5-13 (Running on Terminal Server) //
// //
// (Logon IDs) S-1-5-5-X-Y //
// //
// (NT non-unique IDs) S-1-5-0x15-... //
// //
// (Built-in domain) s-1-5-0x20 //
// //
/////////////////////////////////////////////////////////////////////////////
const
SECURITY_NT_AUTHORITY: TSidIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
SECURITY_DIALUP_RID = ($00000001);
SECURITY_NETWORK_RID = ($00000002);
SECURITY_BATCH_RID = ($00000003);
SECURITY_INTERACTIVE_RID = ($00000004);
SECURITY_SERVICE_RID = ($00000006);
SECURITY_ANONYMOUS_LOGON_RID = ($00000007);
SECURITY_PROXY_RID = ($00000008);
SECURITY_ENTERPRISE_CONTROLLERS_RID = ($00000009);
SECURITY_SERVER_LOGON_RID = SECURITY_ENTERPRISE_CONTROLLERS_RID;
SECURITY_PRINCIPAL_SELF_RID = ($0000000A);
SECURITY_AUTHENTICATED_USER_RID = ($0000000B);
SECURITY_RESTRICTED_CODE_RID = ($0000000C);
SECURITY_TERMINAL_SERVER_RID = ($0000000D);
SECURITY_LOGON_IDS_RID = ($00000005);
SECURITY_LOGON_IDS_RID_COUNT = (3);
SECURITY_LOCAL_SYSTEM_RID = ($00000012);
SECURITY_NT_NON_UNIQUE = ($00000015);
SECURITY_BUILTIN_DOMAIN_RID = ($00000020);
/////////////////////////////////////////////////////////////////////////////
// //
// well-known domain relative sub-authority values (RIDs)... //
// //
/////////////////////////////////////////////////////////////////////////////
// Well-known users ...
DOMAIN_USER_RID_ADMIN = ($000001F4);
DOMAIN_USER_RID_GUEST = ($000001F5);
DOMAIN_USER_RID_KRBTGT = ($000001F6);
// well-known groups ...
DOMAIN_GROUP_RID_ADMINS = ($00000200);
DOMAIN_GROUP_RID_USERS = ($00000201);
DOMAIN_GROUP_RID_GUESTS = ($00000202);
DOMAIN_GROUP_RID_COMPUTERS = ($00000203);
DOMAIN_GROUP_RID_CONTROLLERS = ($00000204);
DOMAIN_GROUP_RID_CERT_ADMINS = ($00000205);
DOMAIN_GROUP_RID_SCHEMA_ADMINS = ($00000206);
DOMAIN_GROUP_RID_ENTERPRISE_ADMINS = ($00000207);
DOMAIN_GROUP_RID_POLICY_ADMINS = ($00000208);
// well-known aliases ...
DOMAIN_ALIAS_RID_ADMINS = ($00000220);
DOMAIN_ALIAS_RID_USERS = ($00000221);
DOMAIN_ALIAS_RID_GUESTS = ($00000222);
DOMAIN_ALIAS_RID_POWER_USERS = ($00000223);
DOMAIN_ALIAS_RID_ACCOUNT_OPS = ($00000224);
DOMAIN_ALIAS_RID_SYSTEM_OPS = ($00000225);
DOMAIN_ALIAS_RID_PRINT_OPS = ($00000226);
DOMAIN_ALIAS_RID_BACKUP_OPS = ($00000227);
DOMAIN_ALIAS_RID_REPLICATOR = ($00000228);
DOMAIN_ALIAS_RID_RAS_SERVERS = ($00000229);
DOMAIN_ALIAS_RID_PREW2KCOMPACCESS = ($0000022A);
SE_CREATE_TOKEN_NAME = 'SeCreateTokenPrivilege';
SE_ASSIGNPRIMARYTOKEN_NAME = 'SeAssignPrimaryTokenPrivilege';
SE_LOCK_MEMORY_NAME = 'SeLockMemoryPrivilege';
SE_INCREASE_QUOTA_NAME = 'SeIncreaseQuotaPrivilege';
SE_UNSOLICITED_INPUT_NAME = 'SeUnsolicitedInputPrivilege';
SE_MACHINE_ACCOUNT_NAME = 'SeMachineAccountPrivilege';
SE_TCB_NAME = 'SeTcbPrivilege';
SE_SECURITY_NAME = 'SeSecurityPrivilege';
SE_TAKE_OWNERSHIP_NAME = 'SeTakeOwnershipPrivilege';
SE_LOAD_DRIVER_NAME = 'SeLoadDriverPrivilege';
SE_SYSTEM_PROFILE_NAME = 'SeSystemProfilePrivilege';
SE_SYSTEMTIME_NAME = 'SeSystemtimePrivilege';
SE_PROF_SINGLE_PROCESS_NAME = 'SeProfileSingleProcessPrivilege';
SE_INC_BASE_PRIORITY_NAME = 'SeIncreaseBasePriorityPrivilege';
SE_CREATE_PAGEFILE_NAME = 'SeCreatePagefilePrivilege';
SE_CREATE_PERMANENT_NAME = 'SeCreatePermanentPrivilege';
SE_BACKUP_NAME = 'SeBackupPrivilege';
SE_RESTORE_NAME = 'SeRestorePrivilege';
SE_SHUTDOWN_NAME = 'SeShutdownPrivilege';
SE_DEBUG_NAME = 'SeDebugPrivilege';
SE_AUDIT_NAME = 'SeAuditPrivilege';
SE_SYSTEM_ENVIRONMENT_NAME = 'SeSystemEnvironmentPrivilege';
SE_CHANGE_NOTIFY_NAME = 'SeChangeNotifyPrivilege';
SE_REMOTE_SHUTDOWN_NAME = 'SeRemoteShutdownPrivilege';
SE_UNDOCK_NAME = 'SeUndockPrivilege';
SE_SYNC_AGENT_NAME = 'SeSyncAgentPrivilege';
SE_ENABLE_DELEGATION_NAME = 'SeEnableDelegationPrivilege';
{$IFNDEF COMPILER5_UP}
type
SE_OBJECT_TYPE = (
SE_UNKNOWN_OBJECT_TYPE,
SE_FILE_OBJECT,
SE_SERVICE,
SE_PRINTER,
SE_REGISTRY_KEY,
SE_LMSHARE,
SE_KERNEL_OBJECT,
SE_WINDOW_OBJECT,
SE_DS_OBJECT,
SE_DS_OBJECT_ALL,
SE_PROVIDER_DEFINED_OBJECT,
SE_WMIGUID_OBJECT
);
{$ENDIF COMPILER5_UP}
// TODO SetNamedSecurityInfo is incorrectly declared, at least for Windows 2000
// it is. D5 unit tries to import from aclapi.dll but it is located in advapi3.dll
// Have to check whether this is also true for Windows NT 4.
type
PPSID = ^PSID;
_TOKEN_USER = record
User: SID_AND_ATTRIBUTES;
end;
TOKEN_USER = _TOKEN_USER;
TTokenUser = TOKEN_USER;
PTokenUser = ^TOKEN_USER;
function SetNamedSecurityInfoW(pObjectName: PWideChar; ObjectType: SE_OBJECT_TYPE;
SecurityInfo: SECURITY_INFORMATION; ppsidOwner, ppsidGroup: PPSID; ppDacl,
ppSacl: PACL): DWORD; stdcall; external 'advapi32.dll' name 'SetNamedSecurityInfoW';
function AdjustTokenPrivileges(TokenHandle: THandle; DisableAllPrivileges: BOOL;
const NewState: TTokenPrivileges; BufferLength: DWORD;
PreviousState: PTokenPrivileges; ReturnLength: PDWORD): BOOL; stdcall;
external 'advapi32.dll' name 'AdjustTokenPrivileges'
//==================================================================================================
// NTFS related I/O control codes, types and constants from winnt.h, winioctl.h
//==================================================================================================
type
PFileAllocatedRangeBuffer = ^TFileAllocatedRangeBuffer;
_FILE_ALLOCATED_RANGE_BUFFER = record
FileOffset: TLargeInteger;
Length: TLargeInteger;
end;
TFileAllocatedRangeBuffer = _FILE_ALLOCATED_RANGE_BUFFER;
PFileZeroDataInformation = ^TFileZeroDataInformation;
_FILE_ZERO_DATA_INFORMATION = record
FileOffset: TLargeInteger;
BeyondFinalZero: TLargeInteger;
end;
TFileZeroDataInformation = _FILE_ZERO_DATA_INFORMATION;
const
COMPRESSION_FORMAT_NONE = $0000;
COMPRESSION_FORMAT_DEFAULT = $0001;
COMPRESSION_FORMAT_LZNT1 = $0002;
FILE_SUPPORTS_SPARSE_FILES = $00000040;
FILE_SUPPORTS_REPARSE_POINTS = $00000080;
IO_REPARSE_TAG_MOUNT_POINT = DWORD($A0000003);
IO_REPARSE_TAG_HSM = DWORD($C0000004);
IO_REPARSE_TAG_SIS = DWORD($80000007);
FILE_ATTRIBUTE_DEVICE = $00000040;
FILE_ATTRIBUTE_SPARSE_FILE = $00000200;
FILE_ATTRIBUTE_REPARSE_POINT = $00000400;
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = $00002000;
FILE_ATTRIBUTE_ENCRYPTED = $00004000;
FILE_DEVICE_FILE_SYSTEM = $00000009;
METHOD_BUFFERED = 0;
METHOD_IN_DIRECT = 1;
METHOD_OUT_DIRECT = 2;
METHOD_NEITHER = 3;
FILE_ANY_ACCESS = 0;
FILE_SPECIAL_ACCESS = FILE_ANY_ACCESS;
FILE_READ_ACCESS = $0001;
FILE_WRITE_ACCESS = $0002;
FILE_WRITE_DATA = $0002;
FILE_READ_DATA = $0001;
FSCTL_GET_COMPRESSION = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(15 shl 2) or METHOD_BUFFERED;
FSCTL_SET_COMPRESSION = (FILE_DEVICE_FILE_SYSTEM shl 16) or
((FILE_READ_DATA or FILE_WRITE_DATA) shl 14) or
(16 shl 2) or METHOD_BUFFERED;
FSCTL_LOCK_VOLUME = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(6 shl 2) or METHOD_BUFFERED;
FSCTL_UNLOCK_VOLUME = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(7 shl 2) or METHOD_BUFFERED;
FSCTL_SET_SPARSE = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_SPECIAL_ACCESS shl 14) or
(49 shl 2) or METHOD_BUFFERED;
FSCTL_SET_ZERO_DATA = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_WRITE_DATA shl 14) or
(50 shl 2) or METHOD_BUFFERED;
FSCTL_QUERY_ALLOCATED_RANGES =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_READ_DATA shl 14) or
(51 shl 2) or METHOD_NEITHER;
FSCTL_SET_REPARSE_POINT = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_SPECIAL_ACCESS shl 14) or
(41 shl 2) or METHOD_BUFFERED;
FSCTL_GET_REPARSE_POINT = (FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(42 shl 2) or METHOD_BUFFERED;
FSCTL_DELETE_REPARSE_POINT =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_SPECIAL_ACCESS shl 14) or
(43 shl 2) or METHOD_BUFFERED;
FSCTL_REQUEST_OPLOCK_LEVEL_1 =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(0 shl 2) or METHOD_BUFFERED;
FSCTL_REQUEST_OPLOCK_LEVEL_2 =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(1 shl 2) or METHOD_BUFFERED;
FSCTL_REQUEST_BATCH_OPLOCK =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(2 shl 2) or METHOD_BUFFERED;
FSCTL_REQUEST_FILTER_OPLOCK =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(23 shl 2) or METHOD_BUFFERED;
FSCTL_OPLOCK_BREAK_ACKNOWLEDGE =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(3 shl 2) or METHOD_BUFFERED;
FSCTL_OPBATCH_ACK_CLOSE_PENDING =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(4 shl 2) or METHOD_BUFFERED;
FSCTL_OPLOCK_BREAK_NOTIFY =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(5 shl 2) or METHOD_BUFFERED;
FSCTL_OPLOCK_BREAK_ACK_NO_2 =
(FILE_DEVICE_FILE_SYSTEM shl 16) or
(FILE_ANY_ACCESS shl 14) or
(20 shl 2) or METHOD_BUFFERED;
function GetVolumeNameForVolumeMountPoint(lpszVolumeMountPoint: LPCSTR; lpszVolumeName: LPSTR; cchBufferLength: DWORD): BOOL;
function SetVolumeMountPoint(lpszVolumeMountPoint: LPCSTR; lpszVolumeName: LPCSTR): BOOL;
function DeleteVolumeMountPoint(lpszVolumeMountPoint: LPCSTR): BOOL;
//--------------------------------------------------------------------------------------------------
// NTFS Reparse Points
//--------------------------------------------------------------------------------------------------
//
// The reparse structure is used by layered drivers to store data in a
// reparse point. The constraints on reparse tags are defined below.
// This version of the reparse data buffer is only for Microsoft tags.
//
type
PReparseDataBuffer = ^TReparseDataBuffer;
_REPARSE_DATA_BUFFER = record
ReparseTag: DWORD;
ReparseDataLength: Word;
Reserved: Word;
case Integer of
0: ( // SymbolicLinkReparseBuffer and MountPointReparseBuffer
SubstituteNameOffset: Word;
SubstituteNameLength: Word;
PrintNameOffset: Word;
PrintNameLength: Word;
PathBuffer: array [0..0] of WCHAR);
1: ( // GenericReparseBuffer
DataBuffer: array [0..0] of Byte);
end;
TReparseDataBuffer = _REPARSE_DATA_BUFFER;
const
REPARSE_DATA_BUFFER_HEADER_SIZE = 8;
REPARSE_GUID_DATA_BUFFER_HEADER_SIZE = 24;
type
PReparsePointInformation = ^TReparsePointInformation;
_REPARSE_POINT_INFORMATION = record
ReparseDataLength: Word;
UnparsedNameLength: Word;
end;
TReparsePointInformation = _REPARSE_POINT_INFORMATION;
const
MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 16 * 1024;
IO_REPARSE_TAG_RESERVED_ZERO = (0);
IO_REPARSE_TAG_RESERVED_ONE = (1);
IO_REPARSE_TAG_RESERVED_RANGE = IO_REPARSE_TAG_RESERVED_ONE;
IO_REPARSE_TAG_VALID_VALUES = DWORD($E000FFFF);
type
PReparseGuidDataBuffer = ^TReparseGuidDataBuffer;
_REPARSE_GUID_DATA_BUFFER = record
ReparseTag: DWORD;
ReparseDataLength: Word;
Reserved: WORD;
ReparseGuid: TGUID;
DataBuffer: array [0..0] of Byte;
end;
TReparseGuidDataBuffer = _REPARSE_GUID_DATA_BUFFER;
const
FILE_FLAG_OPEN_REPARSE_POINT = $00200000;
//--------------------------------------------------------------------------------------------------
// Junction Points
//--------------------------------------------------------------------------------------------------
const
CP_THREAD_ACP = 3; // current thread's ANSI code page
//--------------------------------------------------------------------------------------------------
// Streams
//--------------------------------------------------------------------------------------------------
function BackupSeek(hFile: THandle; dwLowBytesToSeek, dwHighBytesToSeek: DWORD;
var lpdwLowByteSeeked, lpdwHighByteSeeked: DWORD; var lpContext: Pointer): BOOL; stdcall;
external kernel32 name 'BackupSeek';
//==================================================================================================
// Netbios (incorrect/inconvenient declarations in rtl)
//==================================================================================================
const
NCBNAMSZ = 16; // absolute length of a net name
MAX_LANA = 254; // lana's in range 0 to MAX_LANA inclusive
NRC_GOODRET = $00; // good return
NCBASTAT = $33; // NCB ADAPTER STATUS
NCBRESET = $32; // NCB RESET
NCBENUM = $37; // NCB ENUMERATE LANA NUMBERS
type
PNCB = ^TNCB;
TNCBPostProc = procedure (P: PNCB); stdcall;
TNCB = record
ncb_command: Byte;
ncb_retcode: Byte;
ncb_lsn: Byte;
ncb_num: Byte;
ncb_buffer: PChar;
ncb_length: Word;
ncb_callname: array [0..NCBNAMSZ - 1] of Char;
ncb_name: array [0..NCBNAMSZ - 1] of Char;
ncb_rto: Byte;
ncb_sto: Byte;
ncb_post: TNCBPostProc;
ncb_lana_num: Byte;
ncb_cmd_cplt: Byte;
ncb_reserve: array [0..9] of Char;
ncb_event: THandle;
end;
PAdapterStatus = ^TAdapterStatus;
TAdapterStatus = record
adapter_address: array [0..5] of Char;
// Remaining fields are unused so let's not declare them and save space
filler: array [1..4*SizeOf(Char)+19*SizeOf(Word)+3*SizeOf(DWORD)] of Byte;
end;
PNameBuffer = ^TNameBuffer;
TNameBuffer = record
name: array [0..NCBNAMSZ - 1] of Char;
name_num: Byte;
name_flags: Byte;
end;
ASTAT = record
adapt: TAdapterStatus;
namebuf: array [0..29] of TNameBuffer;
end;
PLanaEnum = ^TLanaEnum;
TLanaEnum = record
length: Byte;
lana: array [0..MAX_LANA] of Byte;
end;
procedure ExitNetbios;
function InitNetbios: Boolean;
function NetBios(P: PNCB): Byte;
//==================================================================================================
// JclPeImage
//==================================================================================================
//--------------------------------------------------------------------------------------------------
// Missing WinNT.h translations
//--------------------------------------------------------------------------------------------------
const
IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT = 13; // Delay load import descriptors
IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR = 14; // COM run-time descriptor -> .NET
IMAGE_DLLCHARACTERISTICS_NO_BIND = $0800;
IMAGE_DLLCHARACTERISTICS_WDM_DRIVER = $2000;
IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE = $8000;
type
{$IFNDEF DELPHI5_UP}
PImageExportDirectory = ^TImageExportDirectory;
_IMAGE_EXPORT_DIRECTORY = packed record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
Name: DWORD;
Base: DWORD;
NumberOfFunctions: DWORD;
NumberOfNames: DWORD;
AddressOfFunctions: DWORD; // RVA from base of image
AddressOfNames: DWORD; // RVA from base of image
AddressOfNameOrdinals: DWORD; // RVA from base of image
end;
TImageExportDirectory = _IMAGE_EXPORT_DIRECTORY;
IMAGE_EXPORT_DIRECTORY = _IMAGE_EXPORT_DIRECTORY;
{$ENDIF DELPHI5_UP}
{ Non-COFF Object file header }
PANonObjectHeader = ^TANonObjectHeader;
ANON_OBJECT_HEADER = record
Sig1: Word; // Must be IMAGE_FILE_MACHINE_UNKNOWN
Sig2: Word; // Must be 0xffff
Version: Word; // >= 1 (implies the CLSID field is present)
Machine: Word;
TimeDateStamp: DWORD;
ClassID: TCLSID; // Used to invoke CoCreateInstance
SizeOfData: DWORD; // Size of data that follows the header
end;
TANonObjectHeader = ANON_OBJECT_HEADER;
{ Import format }
PImageImportByName = ^TImageImportByName;
_IMAGE_IMPORT_BY_NAME = packed record
Hint: Word;
Name: array [0..0] of Char;
end;
TImageImportByName = _IMAGE_IMPORT_BY_NAME;
IMAGE_IMPORT_BY_NAME = _IMAGE_IMPORT_BY_NAME;
PImageThunkData = ^TImageThunkData;
_IMAGE_THUNK_DATA = packed record
case Integer of
0: (ForwarderString: DWORD;); // PBYTE
1: (Function_: DWORD;); // PDWORD
2: (Ordinal: DWORD;);
3: (AddressOfData: DWORD;); // PIMAGE_IMPORT_BY_NAME
end;
TImageThunkData = _IMAGE_THUNK_DATA;
IMAGE_THUNK_DATA = _IMAGE_THUNK_DATA;
const
IMAGE_ORDINAL_FLAG = $80000000;
function IMAGE_ORDINAL(Ordinal: DWORD): Word;
type
PImageTlsDirectory = ^TImageTlsDirectory;
_IMAGE_TLS_DIRECTORY = packed record
StartAddressOfRawData: DWORD;
EndAddressOfRawData: DWORD;
AddressOfIndex: DWORD; // PDWORD
AddressOfCallBacks: DWORD; // PIMAGE_TLS_CALLBACK *
SizeOfZeroFill: DWORD;
Characteristics: DWORD;
end;
TImageTlsDirectory = _IMAGE_TLS_DIRECTORY;
IMAGE_TLS_DIRECTORY = _IMAGE_TLS_DIRECTORY;
PImageImportDescriptor = ^TImageImportDescriptor;
_IMAGE_IMPORT_DESCRIPTOR = record
Characteristics: DWORD; // 0 for terminating null import descriptor
// RVA to original unbound IAT (PIMAGE_THUNK_DATA)
TimeDateStamp: DWORD; // 0 if not bound,
// -1 if bound, and real date\time stamp
// in IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT (new BIND)
// O.W. date/time stamp of DLL bound to (Old BIND)
ForwarderChain: DWORD; // -1 if no forwarders
Name: DWORD;
FirstThunk: DWORD; // RVA to IAT (if bound this IAT has actual addresses)
end;
TImageImportDescriptor = _IMAGE_IMPORT_DESCRIPTOR;
IMAGE_IMPORT_DESCRIPTOR = _IMAGE_IMPORT_DESCRIPTOR;
{ New format import descriptors pointed to by DataDirectory[ IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT ] }
PImageBoundImportDescriptor = ^TImageBoundImportDescriptor;
_IMAGE_BOUND_IMPORT_DESCRIPTOR = record
TimeDateStamp: DWORD;
OffsetModuleName: Word;
NumberOfModuleForwarderRefs: Word;
// Array of zero or more IMAGE_BOUND_FORWARDER_REF follows
end;
TImageBoundImportDescriptor = _IMAGE_BOUND_IMPORT_DESCRIPTOR;
IMAGE_BOUND_IMPORT_DESCRIPTOR = _IMAGE_BOUND_IMPORT_DESCRIPTOR;
PImageBoundForwarderRef = ^TImageBoundForwarderRef;
_IMAGE_BOUND_FORWARDER_REF = record
TimeDateStamp: DWORD;
OffsetModuleName: Word;
Reserved: Word;
end;
TImageBoundForwarderRef = _IMAGE_BOUND_FORWARDER_REF;
IMAGE_BOUND_FORWARDER_REF = _IMAGE_BOUND_FORWARDER_REF;
{ Resource Format }
const
IMAGE_RESOURCE_NAME_IS_STRING = $80000000;
IMAGE_RESOURCE_DATA_IS_DIRECTORY = $80000000;
type
PImageResourceDirectory = ^TImageResourceDirectory;
_IMAGE_RESOURCE_DIRECTORY = packed record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
NumberOfNamedEntries: Word;
NumberOfIdEntries: Word;
end;
TImageResourceDirectory = _IMAGE_RESOURCE_DIRECTORY;
IMAGE_RESOURCE_DIRECTORY = _IMAGE_RESOURCE_DIRECTORY;
PImageResourceDirectoryEntry = ^TImageResourceDirectoryEntry;
_IMAGE_RESOURCE_DIRECTORY_ENTRY = packed record
Name: DWORD; // Or ID: Word (Union)
OffsetToData: DWORD;
end;
TImageResourceDirectoryEntry = _IMAGE_RESOURCE_DIRECTORY_ENTRY;
IMAGE_RESOURCE_DIRECTORY_ENTRY = _IMAGE_RESOURCE_DIRECTORY_ENTRY;
PImageResourceDataEntry = ^TImageResourceDataEntry;
_IMAGE_RESOURCE_DATA_ENTRY = packed record
OffsetToData: DWORD;
Size: DWORD;
CodePage: DWORD;
Reserved: DWORD;
end;
TImageResourceDataEntry = _IMAGE_RESOURCE_DATA_ENTRY;
IMAGE_RESOURCE_DATA_ENTRY = _IMAGE_RESOURCE_DATA_ENTRY;
PImageResourceDirStringU = ^TImageResourceDirStringU;
_IMAGE_RESOURCE_DIR_STRING_U = packed record
Length: Word;
NameString: array [0..0] of WCHAR;
end;
TImageResourceDirStringU = _IMAGE_RESOURCE_DIR_STRING_U;
IMAGE_RESOURCE_DIR_STRING_U = _IMAGE_RESOURCE_DIR_STRING_U;
{ Load Configuration Directory Entry }
PImageLoadConfigDirectory = ^TImageLoadConfigDirectory;
IMAGE_LOAD_CONFIG_DIRECTORY = packed record
Characteristics: DWORD;
TimeDateStamp: DWORD;
MajorVersion: Word;
MinorVersion: Word;
GlobalFlagsClear: DWORD;
GlobalFlagsSet: DWORD;
CriticalSectionDefaultTimeout: DWORD;
DeCommitFreeBlockThreshold: DWORD;
DeCommitTotalFreeThreshold: DWORD;
LockPrefixTable: DWORD; // VA
MaximumAllocationSize: DWORD;
VirtualMemoryThreshold: DWORD;
ProcessHeapFlags: DWORD;
ProcessAffinityMask: DWORD;
CSDVersion: Word;
Reserved1: Word;
EditList: DWORD; // VA
Reserved: array [0..0] of DWORD;
end;
TImageLoadConfigDirectory = IMAGE_LOAD_CONFIG_DIRECTORY;
PImgDelayDescr = ^TImgDelayDescr;
ImgDelayDescr = packed record
grAttrs: DWORD; // attributes
szName: DWORD; // pointer to dll name
phmod: PDWORD; // address of module handle
pIAT: TImageThunkData; // address of the IAT
pINT: TImageThunkData; // address of the INT
pBoundIAT: TImageThunkData; // address of the optional bound IAT
pUnloadIAT: TImageThunkData; // address of optional copy of original IAT
dwTimeStamp: DWORD; // 0 if not bound,
// O.W. date/time stamp of DLL bound to (Old BIND)
end;
TImgDelayDescr = ImgDelayDescr;
{ Relocation }
PImageBaseRelocation = ^TImageBaseRelocation;
_IMAGE_BASE_RELOCATION = packed record
VirtualAddress: DWORD;
SizeOfBlock: DWORD;
end;
TImageBaseRelocation = _IMAGE_BASE_RELOCATION;
IMAGE_BASE_RELOCATION =_IMAGE_BASE_RELOCATION;
const
IMAGE_SIZEOF_BASE_RELOCATION = 8;
IMAGE_REL_BASED_ABSOLUTE = 0;
IMAGE_REL_BASED_HIGH = 1;
IMAGE_REL_BASED_LOW = 2;
IMAGE_REL_BASED_HIGHLOW = 3;
IMAGE_REL_BASED_HIGHADJ = 4;
IMAGE_REL_BASED_MIPS_JMPADDR = 5;
IMAGE_REL_BASED_SECTION = 6;
IMAGE_REL_BASED_REL32 = 7;
IMAGE_REL_BASED_MIPS_JMPADDR16 = 9;
IMAGE_REL_BASED_IA64_IMM64 = 9;
IMAGE_REL_BASED_DIR64 = 10;
IMAGE_REL_BASED_HIGH3ADJ = 11;
{ Debug format }
IMAGE_DEBUG_TYPE_BORLAND = 9;
//--------------------------------------------------------------------------------------------------
// Missing WinUser.h translations
//--------------------------------------------------------------------------------------------------
const
RT_HTML = MakeIntResource(23);
RT_MANIFEST = MakeIntResource(24);
CREATEPROCESS_MANIFEST_RESOURCE_ID = MakeIntResource(1);
ISOLATIONAWARE_MANIFEST_RESOURCE_ID = MakeIntResource(2);
ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID = MakeIntResource(3);
MINIMUM_RESERVED_MANIFEST_RESOURCE_ID = MakeIntResource(1);
MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID = MakeIntResource(16);
//--------------------------------------------------------------------------------------------------
// CorHdr.h translations (part of CLR)
//--------------------------------------------------------------------------------------------------
const
COMIMAGE_FLAGS_ILONLY = $00000001;
COMIMAGE_FLAGS_32BITREQUIRED = $00000002;
COMIMAGE_FLAGS_IL_LIBRARY = $00000004;
COMIMAGE_FLAGS_STRONGNAMESIGNED = $00000008;
COMIMAGE_FLAGS_TRACKDEBUGDATA = $00010000;
type
PImageCor20Header = ^TImageCor20Header;
IMAGE_COR20_HEADER = record
cb: Cardinal;
MajorRuntimeVersion: Word;
MinorRuntimeVersion: Word;
MetaData: TImageDataDirectory;
Flags: Cardinal;
EntryPointToken: Cardinal;
Resources: TImageDataDirectory;
StrongNameSignature: TImageDataDirectory;
CodeManagerTable: TImageDataDirectory;
VTableFixups: TImageDataDirectory;
ExportAddressTableJumps: TImageDataDirectory;
ManagedNativeHeader: TImageDataDirectory;
end;
TImageCor20Header = IMAGE_COR20_HEADER;
//--------------------------------------------------------------------------------------------------
// Incorrect translations
//--------------------------------------------------------------------------------------------------
type
{$IFNDEF DELPHI6_UP}
// possibly Borland's header translation bug, fixed in Delphi 6
TLoadedImage = LoadedImage;
{$ENDIF DELPHI6_UP}
PPImageSectionHeader = ^PImageSectionHeader;
// wrong translation - LastRvaSection parameter is not var
function ImageRvaToVa(NtHeaders: PImageNtHeaders; Base: Pointer;
Rva: ULONG; LastRvaSection: PPImageSectionHeader): Pointer; stdcall;
external 'imagehlp.dll' name 'ImageRvaToVa';
// wrong translation - last parameter is incorrect
function BindImageEx(Flags: DWORD; ImageName, DllPath, SymbolPath: LPSTR;
StatusRoutine: TImagehlpStatusRoutine): Bool; stdcall;
external 'imagehlp.dll' name 'BindImageEx';
// wrong translation - last parameter is incorrect
function ImageEnumerateCertificates(FileHandle: THandle; TypeFilter: Word;
CertificateCount, Indices: PDWORD; IndexCount: DWORD): Bool; stdcall;
external 'imagehlp.dll' name 'ImageEnumerateCertificates';
{$IFNDEF DELPHI5_UP}
// lpServiceConfig can be nil
function QueryServiceConfig(hService: SC_HANDLE;
lpServiceConfig: PQueryServiceConfig; cbBufSize: DWORD;
var pcbBytesNeeded: DWORD): BOOL; stdcall;
external advapi32 name 'QueryServiceConfigA';
{$ENDIF DELPHI5_UP}
//==================================================================================================
// JclShell
//==================================================================================================
const
DLLVER_PLATFORM_WINDOWS = $00000001;
DLLVER_PLATFORM_NT = $00000002;
//==================================================================================================
// JclSysInfo
//==================================================================================================
const
CSIDL_COMMON_APPDATA = $0023; { All Users\Application Data }
//--------------------------------------------------------------------------------------------------
{$IFDEF SUPPORTS_EXTSYM}
// centralized EXTERNALSYMs to keep this Delphi 3 compatible
{$EXTERNALSYM InterlockedExchangePointer}
{$EXTERNALSYM SignalObjectAndWait}
{$EXTERNALSYM GetVersionEx}
{$EXTERNALSYM CreateMutex}
{$EXTERNALSYM VER_NT_WORKSTATION}
{$EXTERNALSYM VER_NT_DOMAIN_CONTROLLER}
{$EXTERNALSYM VER_NT_SERVER}
{$EXTERNALSYM VER_SUITE_SMALLBUSINESS}
{$EXTERNALSYM VER_SUITE_ENTERPRISE}
{$EXTERNALSYM VER_SUITE_BACKOFFICE}
{$EXTERNALSYM VER_SUITE_COMMUNICATIONS}
{$EXTERNALSYM VER_SUITE_TERMINAL}
{$EXTERNALSYM VER_SUITE_SMALLBUSINESS_RESTRICTED}
{$EXTERNALSYM VER_SUITE_EMBEDDEDNT}
{$EXTERNALSYM VER_SUITE_DATACENTER}
{$EXTERNALSYM VER_SUITE_SINGLEUSERTS}
{$EXTERNALSYM VER_SUITE_PERSONAL}
{$EXTERNALSYM VER_SUITE_SERVERAPPLIANCE}
{$EXTERNALSYM SECURITY_NULL_SID_AUTHORITY}
{$EXTERNALSYM SECURITY_WORLD_SID_AUTHORITY}
{$EXTERNALSYM SECURITY_LOCAL_SID_AUTHORITY}
{$EXTERNALSYM SECURITY_CREATOR_SID_AUTHORITY}
{$EXTERNALSYM SECURITY_NON_UNIQUE_AUTHORITY}
{$EXTERNALSYM SECURITY_NULL_RID}
{$EXTERNALSYM SECURITY_WORLD_RID}
{$EXTERNALSYM SECURITY_LOCAL_RID}
{$EXTERNALSYM SECURITY_CREATOR_OWNER_RID}
{$EXTERNALSYM SECURITY_CREATOR_GROUP_RID}
{$EXTERNALSYM SECURITY_CREATOR_OWNER_SERVER_RID}
{$EXTERNALSYM SECURITY_CREATOR_GROUP_SERVER_RID}
{$EXTERNALSYM SECURITY_NT_AUTHORITY}
{$EXTERNALSYM SECURITY_DIALUP_RID}
{$EXTERNALSYM SECURITY_NETWORK_RID}
{$EXTERNALSYM SECURITY_BATCH_RID}
{$EXTERNALSYM SECURITY_INTERACTIVE_RID}
{$EXTERNALSYM SECURITY_SERVICE_RID}
{$EXTERNALSYM SECURITY_ANONYMOUS_LOGON_RID}
{$EXTERNALSYM SECURITY_PROXY_RID}
{$EXTERNALSYM SECURITY_ENTERPRISE_CONTROLLERS_RID}
{$EXTERNALSYM SECURITY_SERVER_LOGON_RID}
{$EXTERNALSYM SECURITY_PRINCIPAL_SELF_RID}
{$EXTERNALSYM SECURITY_AUTHENTICATED_USER_RID}
{$EXTERNALSYM SECURITY_RESTRICTED_CODE_RID}
{$EXTERNALSYM SECURITY_TERMINAL_SERVER_RID}
{$EXTERNALSYM SECURITY_LOGON_IDS_RID}
{$EXTERNALSYM SECURITY_LOGON_IDS_RID_COUNT}
{$EXTERNALSYM SECURITY_LOCAL_SYSTEM_RID}
{$EXTERNALSYM SECURITY_NT_NON_UNIQUE}
{$EXTERNALSYM SECURITY_BUILTIN_DOMAIN_RID}
{$EXTERNALSYM DOMAIN_USER_RID_ADMIN}
{$EXTERNALSYM DOMAIN_USER_RID_GUEST}
{$EXTERNALSYM DOMAIN_USER_RID_KRBTGT}
{$EXTERNALSYM DOMAIN_GROUP_RID_ADMINS}
{$EXTERNALSYM DOMAIN_GROUP_RID_USERS}
{$EXTERNALSYM DOMAIN_GROUP_RID_GUESTS}
{$EXTERNALSYM DOMAIN_GROUP_RID_COMPUTERS}
{$EXTERNALSYM DOMAIN_GROUP_RID_CONTROLLERS}
{$EXTERNALSYM DOMAIN_GROUP_RID_CERT_ADMINS}
{$EXTERNALSYM DOMAIN_GROUP_RID_SCHEMA_ADMINS}
{$EXTERNALSYM DOMAIN_GROUP_RID_ENTERPRISE_ADMINS}
{$EXTERNALSYM DOMAIN_GROUP_RID_POLICY_ADMINS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_ADMINS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_USERS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_GUESTS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_POWER_USERS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_ACCOUNT_OPS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_SYSTEM_OPS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_PRINT_OPS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_BACKUP_OPS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_REPLICATOR}
{$EXTERNALSYM DOMAIN_ALIAS_RID_RAS_SERVERS}
{$EXTERNALSYM DOMAIN_ALIAS_RID_PREW2KCOMPACCESS}
{$EXTERNALSYM SE_CREATE_TOKEN_NAME}
{$EXTERNALSYM SE_ASSIGNPRIMARYTOKEN_NAME}
{$EXTERNALSYM SE_LOCK_MEMORY_NAME}
{$EXTERNALSYM SE_INCREASE_QUOTA_NAME}
{$EXTERNALSYM SE_UNSOLICITED_INPUT_NAME}
{$EXTERNALSYM SE_MACHINE_ACCOUNT_NAME}
{$EXTERNALSYM SE_TCB_NAME}
{$EXTERNALSYM SE_SECURITY_NAME}
{$EXTERNALSYM SE_TAKE_OWNERSHIP_NAME}
{$EXTERNALSYM SE_LOAD_DRIVER_NAME}
{$EXTERNALSYM SE_SYSTEM_PROFILE_NAME}
{$EXTERNALSYM SE_SYSTEMTIME_NAME}
{$EXTERNALSYM SE_PROF_SINGLE_PROCESS_NAME}
{$EXTERNALSYM SE_INC_BASE_PRIORITY_NAME}
{$EXTERNALSYM SE_CREATE_PAGEFILE_NAME}
{$EXTERNALSYM SE_CREATE_PERMANENT_NAME}
{$EXTERNALSYM SE_BACKUP_NAME}
{$EXTERNALSYM SE_RESTORE_NAME}
{$EXTERNALSYM SE_SHUTDOWN_NAME}
{$EXTERNALSYM SE_DEBUG_NAME}
{$EXTERNALSYM SE_AUDIT_NAME}
{$EXTERNALSYM SE_SYSTEM_ENVIRONMENT_NAME}
{$EXTERNALSYM SE_CHANGE_NOTIFY_NAME}
{$EXTERNALSYM SE_REMOTE_SHUTDOWN_NAME}
{$EXTERNALSYM SE_UNDOCK_NAME}
{$EXTERNALSYM SE_SYNC_AGENT_NAME}
{$EXTERNALSYM SE_ENABLE_DELEGATION_NAME}
{$IFNDEF COMPILER5_UP}
{$EXTERNALSYM SE_OBJECT_TYPE}
{$ENDIF COMPILER5_UP}
{$EXTERNALSYM PPSID}
{$EXTERNALSYM _TOKEN_USER}
{$EXTERNALSYM TOKEN_USER}
{$EXTERNALSYM SetNamedSecurityInfoW}
{$EXTERNALSYM AdjustTokenPrivileges}
{$EXTERNALSYM _FILE_ALLOCATED_RANGE_BUFFER}
{$EXTERNALSYM _FILE_ZERO_DATA_INFORMATION}
{$EXTERNALSYM COMPRESSION_FORMAT_NONE}
{$EXTERNALSYM COMPRESSION_FORMAT_DEFAULT}
{$EXTERNALSYM COMPRESSION_FORMAT_LZNT1}
{$EXTERNALSYM FILE_SUPPORTS_SPARSE_FILES}
{$EXTERNALSYM FILE_SUPPORTS_REPARSE_POINTS}
{$EXTERNALSYM REPARSE_GUID_DATA_BUFFER_HEADER_SIZE}
{$EXTERNALSYM IO_REPARSE_TAG_MOUNT_POINT}
{$EXTERNALSYM IO_REPARSE_TAG_HSM}
{$EXTERNALSYM IO_REPARSE_TAG_SIS}
{$EXTERNALSYM FILE_ATTRIBUTE_DEVICE}
{$EXTERNALSYM FILE_ATTRIBUTE_SPARSE_FILE}
{$EXTERNALSYM FILE_ATTRIBUTE_REPARSE_POINT}
{$EXTERNALSYM FILE_ATTRIBUTE_NOT_CONTENT_INDEXED}
{$EXTERNALSYM FILE_ATTRIBUTE_ENCRYPTED}
{$EXTERNALSYM FILE_DEVICE_FILE_SYSTEM}
{$EXTERNALSYM METHOD_BUFFERED}
{$EXTERNALSYM METHOD_IN_DIRECT}
{$EXTERNALSYM METHOD_OUT_DIRECT}
{$EXTERNALSYM METHOD_NEITHER}
{$EXTERNALSYM FILE_ANY_ACCESS}
{$EXTERNALSYM FILE_SPECIAL_ACCESS}
{$EXTERNALSYM FILE_READ_ACCESS}
{$EXTERNALSYM FILE_WRITE_ACCESS}
{$EXTERNALSYM FILE_WRITE_DATA}
{$EXTERNALSYM FILE_READ_DATA}
{$EXTERNALSYM FSCTL_GET_COMPRESSION}
{$EXTERNALSYM FSCTL_SET_COMPRESSION}
{$EXTERNALSYM FSCTL_LOCK_VOLUME}
{$EXTERNALSYM FSCTL_UNLOCK_VOLUME}
{$EXTERNALSYM FSCTL_SET_SPARSE}
{$EXTERNALSYM FSCTL_SET_ZERO_DATA}
{$EXTERNALSYM FSCTL_QUERY_ALLOCATED_RANGES}
{$EXTERNALSYM FSCTL_SET_REPARSE_POINT}
{$EXTERNALSYM FSCTL_GET_REPARSE_POINT}
{$EXTERNALSYM FSCTL_DELETE_REPARSE_POINT}
{$EXTERNALSYM FSCTL_REQUEST_OPLOCK_LEVEL_1}
{$EXTERNALSYM FSCTL_REQUEST_OPLOCK_LEVEL_2}
{$EXTERNALSYM FSCTL_REQUEST_BATCH_OPLOCK}
{$EXTERNALSYM FSCTL_REQUEST_FILTER_OPLOCK}
{$EXTERNALSYM FSCTL_OPLOCK_BREAK_ACKNOWLEDGE}
{$EXTERNALSYM FSCTL_OPBATCH_ACK_CLOSE_PENDING}
{$EXTERNALSYM FSCTL_OPLOCK_BREAK_NOTIFY}
{$EXTERNALSYM FSCTL_OPLOCK_BREAK_ACK_NO_2}
{$EXTERNALSYM GetVolumeNameForVolumeMountPoint}
{$EXTERNALSYM SetVolumeMountPoint}
{$EXTERNALSYM DeleteVolumeMountPoint}
{$EXTERNALSYM NCBNAMSZ}
{$EXTERNALSYM MAX_LANA}
{$EXTERNALSYM NRC_GOODRET}
{$EXTERNALSYM NCBASTAT}
{$EXTERNALSYM NCBRESET}
{$EXTERNALSYM NCBENUM}
{$EXTERNALSYM PNCB}
{$EXTERNALSYM ASTAT}
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT}
{$EXTERNALSYM IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR}
{$EXTERNALSYM IMAGE_DLLCHARACTERISTICS_NO_BIND}
{$EXTERNALSYM IMAGE_DLLCHARACTERISTICS_WDM_DRIVER}
{$EXTERNALSYM IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE}
{$IFNDEF DELPHI5_UP}
{$EXTERNALSYM _IMAGE_EXPORT_DIRECTORY}
{$EXTERNALSYM IMAGE_EXPORT_DIRECTORY}
{$ENDIF DELPHI5_UP}
{$EXTERNALSYM ANON_OBJECT_HEADER}
{$EXTERNALSYM _IMAGE_IMPORT_BY_NAME}
{$EXTERNALSYM IMAGE_IMPORT_BY_NAME}
{$EXTERNALSYM _IMAGE_THUNK_DATA}
{$EXTERNALSYM IMAGE_THUNK_DATA}
{$EXTERNALSYM IMAGE_ORDINAL_FLAG}
{$EXTERNALSYM IMAGE_ORDINAL}
{$EXTERNALSYM _IMAGE_TLS_DIRECTORY}
{$EXTERNALSYM IMAGE_TLS_DIRECTORY}
{$EXTERNALSYM _IMAGE_IMPORT_DESCRIPTOR}
{$EXTERNALSYM IMAGE_IMPORT_DESCRIPTOR}
{$EXTERNALSYM _IMAGE_BOUND_IMPORT_DESCRIPTOR}
{$EXTERNALSYM IMAGE_BOUND_IMPORT_DESCRIPTOR}
{$EXTERNALSYM _IMAGE_BOUND_FORWARDER_REF}
{$EXTERNALSYM IMAGE_BOUND_FORWARDER_REF}
{$EXTERNALSYM IMAGE_RESOURCE_NAME_IS_STRING}
{$EXTERNALSYM IMAGE_RESOURCE_DATA_IS_DIRECTORY}
{$EXTERNALSYM _IMAGE_RESOURCE_DIRECTORY}
{$EXTERNALSYM IMAGE_RESOURCE_DIRECTORY}
{$EXTERNALSYM _IMAGE_RESOURCE_DIRECTORY_ENTRY}
{$EXTERNALSYM IMAGE_RESOURCE_DIRECTORY_ENTRY}
{$EXTERNALSYM _IMAGE_RESOURCE_DATA_ENTRY}
{$EXTERNALSYM IMAGE_RESOURCE_DATA_ENTRY}
{$EXTERNALSYM _IMAGE_RESOURCE_DIR_STRING_U}
{$EXTERNALSYM IMAGE_RESOURCE_DIR_STRING_U}
{$EXTERNALSYM IMAGE_LOAD_CONFIG_DIRECTORY}
{$EXTERNALSYM ImgDelayDescr}
{$EXTERNALSYM _IMAGE_BASE_RELOCATION}
{$EXTERNALSYM IMAGE_BASE_RELOCATION}
{$EXTERNALSYM IMAGE_SIZEOF_BASE_RELOCATION}
{$EXTERNALSYM IMAGE_REL_BASED_ABSOLUTE}
{$EXTERNALSYM IMAGE_REL_BASED_HIGH}
{$EXTERNALSYM IMAGE_REL_BASED_LOW}
{$EXTERNALSYM IMAGE_REL_BASED_HIGHLOW}
{$EXTERNALSYM IMAGE_REL_BASED_HIGHADJ}
{$EXTERNALSYM IMAGE_REL_BASED_MIPS_JMPADDR}
{$EXTERNALSYM IMAGE_REL_BASED_SECTION}
{$EXTERNALSYM IMAGE_REL_BASED_REL32}
{$EXTERNALSYM IMAGE_REL_BASED_MIPS_JMPADDR16}
{$EXTERNALSYM IMAGE_REL_BASED_IA64_IMM64}
{$EXTERNALSYM IMAGE_REL_BASED_DIR64}
{$EXTERNALSYM IMAGE_REL_BASED_HIGH3ADJ}
{$EXTERNALSYM IMAGE_DEBUG_TYPE_BORLAND}
{$EXTERNALSYM RT_HTML}
{$EXTERNALSYM RT_MANIFEST}
{$EXTERNALSYM CREATEPROCESS_MANIFEST_RESOURCE_ID}
{$EXTERNALSYM ISOLATIONAWARE_MANIFEST_RESOURCE_ID}
{$EXTERNALSYM ISOLATIONAWARE_NOSTATICIMPORT_MANIFEST_RESOURCE_ID}
{$EXTERNALSYM MINIMUM_RESERVED_MANIFEST_RESOURCE_ID}
{$EXTERNALSYM MAXIMUM_RESERVED_MANIFEST_RESOURCE_ID}
{$EXTERNALSYM COMIMAGE_FLAGS_ILONLY}
{$EXTERNALSYM COMIMAGE_FLAGS_32BITREQUIRED}
{$EXTERNALSYM COMIMAGE_FLAGS_IL_LIBRARY}
{$EXTERNALSYM COMIMAGE_FLAGS_STRONGNAMESIGNED}
{$EXTERNALSYM COMIMAGE_FLAGS_TRACKDEBUGDATA}
{$EXTERNALSYM IMAGE_COR20_HEADER}
{$EXTERNALSYM ImageRvaToVa}
{$EXTERNALSYM BindImageEx}
{$EXTERNALSYM ImageEnumerateCertificates}
{$IFNDEF DELPHI5_UP}
{$EXTERNALSYM QueryServiceConfig}
{$ENDIF DELPHI5_UP}
{$EXTERNALSYM CSIDL_COMMON_APPDATA}
{$ENDIF SUPPORTS_EXTSYM}
implementation
//==================================================================================================
// Locales related
//==================================================================================================
function LANGIDFROMLCID(const lcid: LCID): Word;
begin
Result := Word(lcid);
end;
//--------------------------------------------------------------------------------------------------
function MAKELANGID(const usPrimaryLanguage, usSubLanguage: Byte): Word;
begin
Result := usPrimaryLanguage or (usSubLanguage shl 10);
end;
//--------------------------------------------------------------------------------------------------
function PRIMARYLANGID(const lgid: Word): Word;
begin
Result := (lgid and $03FF);
end;
//--------------------------------------------------------------------------------------------------
function SUBLANGID(const lgid: Word): Word;
begin
Result := (lgid shr 10);
end;
//--------------------------------------------------------------------------------------------------
function MAKELCID(const wLanguageID, wSortID: Word): LCID;
begin
Result := wLanguageID or (wSortID shl 16);
end;
//--------------------------------------------------------------------------------------------------
function SORTIDFROMLCID(const lcid: LCID): Word;
begin
Result := (lcid shr 16) and $0F;
end;
//--------------------------------------------------------------------------------------------------
var
_GetVolumeNameForVolumeMountPoint: function (lpszVolumeMountPoint: LPCSTR; lpszVolumeName: LPSTR; cchBufferLength: DWORD): BOOL; stdcall;
_SetVolumeMountPoint: function (lpszVolumeMountPoint: LPCSTR; lpszVolumeName: LPCSTR): BOOL; stdcall;
_DeleteVolumeMountPoint: function (lpszVolumeMountPoint: LPCSTR): BOOL; stdcall;
function GetVolumeNameForVolumeMountPoint(lpszVolumeMountPoint: LPCSTR; lpszVolumeName: LPSTR; cchBufferLength: DWORD): BOOL;
var
Kernel32Handle: THandle;
begin
if not Assigned(_GetVolumeNameForVolumeMountPoint) then
begin
Kernel32Handle := GetModuleHandle(kernel32);
if Kernel32Handle <> 0 then
@_GetVolumeNameForVolumeMountPoint := GetProcAddress(Kernel32Handle, PChar('GetVolumeNameForVolumeMountPointA'));
end;
if Assigned(_GetVolumeNameForVolumeMountPoint) then
Result := _GetVolumeNameForVolumeMountPoint(lpszVolumeMountPoint, lpszVolumeName, cchBufferLength)
else
Result := False;
end;
function SetVolumeMountPoint(lpszVolumeMountPoint: LPCSTR; lpszVolumeName: LPCSTR): BOOL;
var
Kernel32Handle: THandle;
begin
if not Assigned(_SetVolumeMountPoint) then
begin
Kernel32Handle := GetModuleHandle(kernel32);
if Kernel32Handle <> 0 then
@_SetVolumeMountPoint := GetProcAddress(Kernel32Handle, PChar('SetVolumeMountPointA'));
end;
if Assigned(_SetVolumeMountPoint) then
Result := _SetVolumeMountPoint(lpszVolumeMountPoint, lpszVolumeName)
else
Result := False;
end;
function DeleteVolumeMountPoint(lpszVolumeMountPoint: LPCSTR): BOOL;
var
Kernel32Handle: THandle;
begin
if not Assigned(_DeleteVolumeMountPoint) then
begin
Kernel32Handle := GetModuleHandle(kernel32);
if Kernel32Handle <> 0 then
@_DeleteVolumeMountPoint := GetProcAddress(Kernel32Handle, PChar('DeleteVolumeMountPointA'));
end;
if Assigned(_DeleteVolumeMountPoint) then
Result := _DeleteVolumeMountPoint(lpszVolumeMountPoint)
else
Result := False;
end;
function GetVersionEx; external kernel32 name 'GetVersionExA';
//==================================================================================================
// Netbios
//==================================================================================================
type
TNetBios = function (P: PNCB): Byte; stdcall;
var
NetBiosLib: HINST = 0;
_NetBios: TNetBios;
//--------------------------------------------------------------------------------------------------
procedure ExitNetbios;
begin
if NetBiosLib <> 0 then
begin
FreeLibrary(NetBiosLib);
NetBiosLib := 0;
end;
end;
//--------------------------------------------------------------------------------------------------
function InitNetbios: Boolean;
begin
Result := True;
if NetBiosLib = 0 then
begin
NetBiosLib := LoadLibrary(PChar('netapi32.dll'));
Result := NetBiosLib <> 0;
if Result then
begin
@_NetBios := GetProcAddress(NetBiosLib, PChar('Netbios'));
Result := @_NetBios <> nil;
if not Result then
ExitNetbios;
end;
end;
end;
//--------------------------------------------------------------------------------------------------
function NetBios(P: PNCB): Byte;
begin
if InitNetbios then
Result := _NetBios(P)
else
Result := 1; // anything other than NRC_GOODRET will do
end;
//==================================================================================================
// JclPeImage
//==================================================================================================
function IMAGE_ORDINAL(Ordinal: DWORD): Word;
begin
Result := Ordinal and $FFFF;
end;
end.
|
Unit Expression;
interface
uses windows, sysutils, classes, faceunit, DateUtils, dialogs;
(******************************************************************************)
type
TExpStatus = (eMore, eLess, eRavn, sNone);
TExpression = record
hh,ss,mm : integer;
dddd,mmmm,yyyy,ddmm : integer;
sthh,stss,stmm,stdddd,stmmmm,styyyy,stddmm : TExpStatus;
RND : boolean;
end;
(******************************************************************************)
function TestExpression(Exp: String) : boolean;
function ReplaseAllString(Line, Prefix, Return: String) : String;
function ReplaseString(InStr,FindStr,ReplaseStr: String) : string;
implementation
(******************************************************************************)
function ReplaseString(InStr,FindStr,ReplaseStr: String) : string;
var
id : integer;
str : string;
begin
Result := InStr;
id := pos(LowerCase(FindStr), LowerCase(InStr));
str := InStr;
Delete(str,id,length(FindStr));
Insert(ReplaseStr,str,id);
Result := str;
end;
function ReplaseAllString(Line, Prefix, Return: String) : String;
var
tmp : string;
begin
tmp := Line;
while pos(Prefix,tmp) > 0 do
tmp := ReplaseString(tmp,prefix,return);
Result := tmp;
end;
function DeleteSpaces(Line: String) : String;
var
tmp : string;
begin
tmp := Line;
while pos(' ',tmp) > 0 do
tmp := ReplaseString(tmp,' ','');
Result := tmp;
end;
procedure GetWordsList(Line: String; List : TStrings);
var
tmp : String;
begin
tmp := Line;
tmp := ReplaseAllString(tmp,' ',#13#10);
List.Text := tmp;
end;
(******************************************************************************)
procedure ClearExp(var Exp: TExpression);
begin
Exp.hh := -1;
Exp.ss := -1;
Exp.mm := -1;
Exp.dddd := -1;
Exp.mmmm := -1;
Exp.yyyy := -1;
Exp.ddmm := -1;
(* *)
Exp.sthh := sNone;
Exp.stss := sNone;
Exp.stmm := sNone;
Exp.stdddd := sNone;
Exp.stmmmm := sNone;
Exp.styyyy := sNone;
Exp.stddmm := sNone;
(* *)
Exp.RND := False;
end;
function TestExpression(Exp: String) : boolean;
var
E : TExpression;
N : TExpression;
st : TExpStatus;
Str : string;
suf : char;
List : TStringList;
i : integer;
err : boolean;
begin
ClearExp(E);
ClearExp(N);
Result := False;
(* *)
if Exp = '#RND#' then begin
Result := true;
exit;
end;
(* *)
List := TStringList.Create;
Str := DeleteSpaces(Exp);
List.Text := ReplaseAllString(Str,';',#13#10);
(* *)
try
for i := 0 to List.Count-1 do begin
if pos('=',list[i]) <> 0 then suf := '=';
if pos('>',list[i]) <> 0 then suf := '>';
if pos('<',list[i]) <> 0 then suf := '<';
//
case suf of
'>' : st := eMore;
'<' : st := eLess;
'=' : st := eRavn;
end;
//
if StrToParam(list[i],suf).pName = 'hh' then begin
E.hh := strtoint(StrToParam(list[i],suf).pParam);
E.sthh := st;
end;
if StrToParam(list[i],suf).pName = 'ss' then begin
E.ss := strtoint(StrToParam(list[i],suf).pParam);
E.stss := st;
end;
if StrToParam(list[i],suf).pName = 'mm' then begin
E.mm := strtoint(StrToParam(list[i],suf).pParam);
E.stmm := st;
end;
if StrToParam(list[i],suf).pName = 'ddmm' then begin
E.ddmm := strtoint(StrToParam(list[i],suf).pParam);
E.stddmm := st;
end;
if StrToParam(list[i],suf).pName = 'dddd' then begin
E.dddd := strtoint(StrToParam(list[i],suf).pParam);
E.stdddd := st;
end;
if StrToParam(list[i],suf).pName = 'mmmm' then begin
E.mmmm := strtoint(StrToParam(list[i],suf).pParam);
E.stmmmm := st;
end;
if StrToParam(list[i],suf).pName = 'yyyy' then begin
E.yyyy := strtoint(StrToParam(list[i],suf).pParam);
E.styyyy := st;
end;
end;
(* *)
finally
List.Free;
end;
(* *)
N.hh := HourOfTheDay(now);
N.ss := SecondOfTheMinute(now);
N.mm := MinuteOfTheHour(now);
N.dddd := DayOfTheWeek(Now);
N.ddmm := DayOfTheMonth(Now);
N.mmmm := MonthOfTheYear(Now);
N.yyyy := YearOf(Now);
(* *)
err := false;
if E.hh <> -1 then
case E.sthh of
eMore : begin
if E.hh < N.hh then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.hh > N.hh then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.hh = N.hh then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if E.ss <> -1 then
case E.stss of
eMore : begin
if E.ss < N.ss then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.ss > N.ss then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.ss = N.ss then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if E.mm <> -1 then
case E.stmm of
eMore : begin
if E.mm < N.mm then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.mm > N.mm then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.mm = N.mm then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if E.dddd <> -1 then
case E.stdddd of
eMore : begin
if E.dddd < N.dddd then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.dddd > N.dddd then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.dddd = N.dddd then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if E.ddmm <> -1 then
case E.stddmm of
eMore : begin
if E.ddmm < N.ddmm then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.ddmm > N.ddmm then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.ddmm = N.ddmm then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if E.mmmm <> -1 then
case E.stmmmm of
eMore : begin
if E.mmmm < N.mmmm then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.mmmm > N.mmmm then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.mmmm = N.mmmm then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if E.yyyy <> -1 then
case E.styyyy of
eMore : begin
if E.yyyy < N.yyyy then else
begin
err := true;
exit;
end;
end;
eLess : begin
if E.yyyy > N.yyyy then else
begin
err := true;
exit;
end;
end;
eRavn : begin
if E.yyyy = N.yyyy then else
begin
err := true;
exit;
end;
end;
end;
(* *)
if not err then Result := true else Result := false;
end;
(******************************************************************************)
end.
|
{*!
* Fano Web Framework (https://fano.juhara.id)
*
* @link https://github.com/zamronypj/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/zamronypj/fano/blob/master/LICENSE (GPL 3.0)
*}
unit FcgiAppImpl;
interface
uses
fastcgi,
AppIntf;
type
TFcgiWebApplication = class(TInterfacedObject, IWebApplication)
private
actualApp : IWebApplication;
serverHost : string;
serverPort : integer;
useUnixSocket : boolean;
serverSocketFile : string;
(*!-----------------------------------------------
* execute application and write response
*------------------------------------------------
* @return current application instance
*-----------------------------------------------
* TODO: need to think about how to execute when
* application is run as daemon.
*-----------------------------------------------*)
function acceptConnection() : IRunnable;
(*!-----------------------------------------------
* open socket
*------------------------------------------------
* @return current application instance
*-----------------------------------------------
* TODO: need to think about how to execute when
* application is run as daemon.
*-----------------------------------------------*)
function openSocket() : IRunnable;
public
constructor create(
const appInst : IWebApplication;
const port : integer
);
destructor destroy; override;
function run() : IRunnable;
end;
implementation
uses
sockets;
constructor TFcgiWebApplication.create(
const appInst : IWebApplication;
const port : integer
);
begin
actualApp := appInst;
serverPort := port;
end;
destructor TFcgiWebApplication.destroy();
begin
inherited destroy();
actualApp := nil;
end;
function TFcgiWebApplication.processRecord(const fcgiRec : PFCGI_Header) : IRunnable;
var requestId : word;
begin
env := readFastCGItoEnv(fcgiRec)
dispatcher.dispatchRequest(env);
end;
procedure TFcgiWebApplication.onConnect(const sender : TObject; const stream : TSocketStream);
var fcgiRec : PFCGI_Header;
serverSocket : TSocketServer;
status : boolean;
begin
serverSocket := TSocketServer(sender);
fcgiRec := readFCGIRecord(stream);
// If connection closed gracefully, we have nil.
if (not assigned(fcgiRec) then
begin
serverSocket.abort();
serverSocket.close();
end else
begin
try
processRecord(fcgiRec);
finally
freeMem(fcgiRec);
end;
end;
end;
function TFcgiWebApplication.run() : IRunnable;
var socketServer : TSocketServer;
begin
if (useUnixSocket) then
begin
socketServer := TUnixServer.create(serverSocketFile);
end else
begin
socketServer := TInetSocket.create(serverHost, serverPort);
end;
try
socketServer.onConnect := @onConnect;
socketServer.startAccepting();
finally
socketServer.free();
end;
end;
end.
|
{
IsZCPR3: a minimal test to see if we're running on a
ZCPR3 system.
}
FUNCTION IsZCPR3 : BOOLEAN;
FUNCTION IsZ3ENV(addr : INTEGER) : BOOLEAN;
BEGIN
IsZ3ENV :=
(Mem[addr ] = Ord('Z')) AND
(Mem[addr+1] = Ord('3')) AND
(Mem[addr+2] = Ord('E')) AND
(Mem[addr+3] = Ord('N')) AND
(Mem[addr+4] = Ord('V'));
END;
VAR
z3env : INTEGER;
isZ : BOOLEAN;
BEGIN
IF IsZ3ENV($0103) AND ((Mem[$0109] OR Mem[$010A]) <> $00) THEN BEGIN
z3env := (Mem[$010A] SHL 8) OR Mem[$0109];
IsZCPR3 := (Mem[z3env] = $C3) AND IsZ3ENV(z3env+3);
END ELSE
IsZCPR3 := FALSE;
END;
|
unit IdStrings;
interface
Uses
Classes;
{
2000-03-27 Pete Mee
- Added FindFirstOf, FindFirstNotOf and TrimAllOf functions.
2002-01-03 Andrew P.Rybin
- StrHTMLEnc/Dec,BinToHexStr,SplitColumns,IsWhiteString
2002-03-12 Andrew P.Rybin
- SplitColumns[NoTrim]
}
function FindFirstOf(AFind, AText: String): Integer;
function FindFirstNotOf(AFind, AText : String) : Integer;
function TrimAllOf(ATrim, AText : String) : String;
// Empty or contain only TAB and Space. Use it vs Length(Trim(AStr))>0
function IsWhiteString(const AStr: String): Boolean;
function BinToHexStr (AData: Pointer; ADataLen: Integer): String;
// Encode reserved html chars: < > ' & " {Do not Localize}
function StrHtmlEncode (const AStr: String): String;
function StrHtmlDecode (const AStr: String): String;
//in Integer(Strings.Objects[i]) - column position in AData
procedure SplitColumnsNoTrim (const AData: String; AStrings: TStrings; const ADelim: String=' '); {Do not Localize}
procedure SplitColumns (const AData: String; AStrings: TStrings; const ADelim: String=' '); {Do not Localize}
procedure SplitLines (AData: PChar; ADataSize: Integer; AStrings: TStrings);
// SplitString splits a string into left and right parts,
// i.e. SplitString('Namespace:tag', ':'..) will return 'Namespace' and 'Tag'
procedure SplitString(const AStr, AToken: String; var VLeft, VRight: String);
// commaadd will append AStr2 to the right of AStr1 and return the result.
// if there is any content in AStr1, a comma will be added
function CommaAdd(Const AStr1, AStr2:String):string;
implementation
uses
IdException,
IdGlobal,
SysUtils;
function StrHtmlEncode (const AStr: String): String;
begin
Result := StringReplace(AStr, '&', '&', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '<', '<', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '>', '>', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '"', '"', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '''', ''', [rfReplaceAll]); {Do not Localize}
end;
function StrHtmlDecode (const AStr: String): String;
begin
Result := StringReplace(AStr, ''', '''', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '"', '"', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '>', '>', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '<', '<', [rfReplaceAll]); {Do not Localize}
Result := StringReplace(Result, '&', '&', [rfReplaceAll]); {Do not Localize}
end;
{Function ReadTimeStampCounter: Int64;
Asm
db $0F,$31 //RDTSC
End;//Read CPU TimeStamp}
function FindFirstOf(AFind, AText: string): Integer;
var
nCount, nPos: Integer;
begin
Result := 0;
for nCount := 1 to Length(AFind) do begin
nPos := IndyPos(AFind[nCount], AText);
if nPos > 0 then begin
if Result = 0 then begin
Result := nPos;
end else if Result > nPos then begin
Result := nPos;
end;
end;
end;
end;
function FindFirstNotOf(AFind, AText : String) : Integer;
var
i : Integer;
begin
result := 0;
if length(AFind) = 0 then
begin
result := 1;
exit;
end;
if length(AText) = 0 then
begin
exit;
end;
for i := 1 to length(AText) do
begin
if IndyPos(AText[i], AFind) = 0 then
begin
result := i;
exit;
end;
end;
end;
function TrimAllOf(ATrim, AText : String) : String;
begin
while Length(AText) > 0 do
begin
if Pos(AText[1], ATrim) > 0 then
begin
System.Delete(AText, 1, 1);
end else break;
end;
while Length(AText) > 0 do begin
if Pos(AText[length(AText)], ATrim) > 0 then
begin
System.Delete(AText, Length(AText), 1);
end else break;
end;
result := AText;
End;
function BinToHexStr (AData: Pointer; ADataLen: Integer): String;
var
LSrc: PChar;
i: Integer;
Begin
LSrc:=AData;
SetString(Result,NIL,ADataLen*2);
for i:=0 to ADataLen-1 do begin
Result[i*2+1]:=IdHexDigits[ord(LSrc^) shr 4];
Result[i*2+2]:=IdHexDigits[ord(LSrc^) and $F];
inc(LSrc);
end;//for
End;
procedure SplitColumnsNoTrim(const AData: String; AStrings: TStrings; const ADelim: String=' '); {Do not Localize}
var
i: Integer;
LDelim: Integer; //delim len
LLeft: String;
LLastPos: Integer;
Begin
Assert(Assigned(AStrings));
AStrings.Clear;
LDelim := Length(ADelim);
LLastPos := 1;
i := Pos(ADelim, AData);
while I > 0 do begin
LLeft:= Copy(AData, LLastPos, I-LLastPos); //'abc d' len:=i(=4)-1 {Do not Localize}
if LLeft > '' then begin {Do not Localize}
AStrings.AddObject(LLeft,Pointer(LLastPos));
end;
LLastPos := I + LDelim; //first char after Delim
i := PosIdx (ADelim, AData, LLastPos);
end;//while found
if LLastPos <= Length(AData) then begin
AStrings.AddObject(Copy(AData,LLastPos,MaxInt), Pointer(LLastPos));
end;
End;//TIdFTPListItems.ParseColumns
procedure SplitColumns(const AData: String; AStrings: TStrings; const ADelim: String=' '); {Do not Localize}
var
i: Integer;
LData: String;
LDelim: Integer; //delim len
LLeft: String;
LLastPos: Integer;
LLeadingSpaceCnt: Integer;
Begin
Assert(Assigned(AStrings));
AStrings.Clear;
LDelim := Length(ADelim);
LLastPos := 1;
LData := Trim(AData);
LLeadingSpaceCnt := 0;
if Length(LData)>0 then begin //if Not WhiteStr
while AData[LLeadingSpaceCnt+1]<=' ' do inc(LLeadingSpaceCnt);
end
else begin
EXIT;
end;
i := Pos(ADelim, LData);
while I > 0 do begin
LLeft:= Copy(LData, LLastPos, I-LLastPos); //'abc d' len:=i(=4)-1 {Do not Localize}
if LLeft > '' then begin {Do not Localize}
AStrings.AddObject(Trim(LLeft),Pointer(LLastPos+LLeadingSpaceCnt));
end;
LLastPos := I + LDelim; //first char after Delim
i := PosIdx (ADelim, LData, LLastPos);
end;//while found
if LLastPos <= Length(LData) then begin
AStrings.AddObject(Trim( Copy(LData,LLastPos,MaxInt) ), Pointer(LLastPos+LLeadingSpaceCnt));
end;
End;//TIdFTPListItems.ParseColumns
function IsWhiteString(const AStr: String): Boolean;
const
WhiteSet = [TAB,' ']; {Do not Localize}
var
i: Integer;
LLen: Integer;
Begin
LLen := Length(AStr);
if LLen > 0 then begin
Result:=TRUE; //only white
for i:=1 to LLen do begin
if NOT (AStr[i] in WhiteSet) then begin
Result:=FALSE;
EXIT;
end;
end;
end
else begin
Result:=TRUE; //empty
end;
End;//IsWhiteString
procedure SplitString(const AStr, AToken: String; var VLeft, VRight: String);
var
i: Integer;
LLocalStr: String;
begin
{ It is possible that VLeft or VRight may be the same variable as AStr. So we copy it first }
LLocalStr := AStr;
i := Pos(AToken, LLocalStr);
if i = 0 then
begin
VLeft := LLocalStr;
VRight := '';
end
else
begin
VLeft := Copy(LLocalStr, 1, i - 1);
VRight := Copy(LLocalStr, i + Length(AToken), Length(LLocalStr));
end;
end;
function CommaAdd(Const AStr1, AStr2:String):string;
begin
if AStr1 = '' then
result := AStr2
else
result := AStr1 + ',' + AStr2;
end;
procedure SplitLines (AData: PChar; ADataSize: Integer; AStrings: TStrings);
var
P, LLast, Start: PChar;
S: string;
begin
AStrings.BeginUpdate;
try
AStrings.Clear;
P := AData;
if P <> NIL then begin
LLast := P+ADataSize;
while P < LLast do begin
Start := P;
while (P < LLast) and NOT (P^ in [CR, LF]) do Inc(P);
SetString(S, Start, P - Start);
AStrings.AddObject(S, Pointer(Start - AData +1));
if P^ = #13 then Inc(P);
if P^ = #10 then Inc(P);
end;//while
end;//if
finally
AStrings.EndUpdate;
end;
End;//SplitLines
END.
|
unit LibGraph;
interface
uses SysUtils, Graphics, Classes, Math;
const
hx=50; hy=10; hr=15; SizeStack=100;
MaxInt0=$FFFFF;
Colors: array[0..4] of TColor=($FFFFFF,clYellow,clLime,clGray,clRed);
type
TEdges=record // временная структура для ребер
n1: word; // № первой вершины
n2: word; // № второй вершины
A : integer; // вес ребра
end;
TEdge=record
A : integer; // вес дуги
NumNode : integer; // № узла
x1c,x2c,yc: integer; // геометрия
Color : TColor; // цвет дуги
end;
TNode=record
Name : string; // имя узла
Edge : array of TEdge; // массив дуг
Visit : boolean; // были
x0,y0 : integer; // центр
NumVisit: integer; // № посещения
Color : TColor;
Dist,OldDist: integer;
end;
TStack = record
Elements: array[1..SizeStack] of integer;
Top,Bottom: integer;
end;
TDist = record
S : integer;
Variabled: Boolean;
end;
var
Stack: TStack;
Path: TStack;
Node: array of TNode;
Edges: array of TEdges; // массив всех ребер
A: array of array of integer;
fl_tools: byte;
N,LL,Num: integer;
SelectNode: integer;
f: file;
Bm,Bitmap: TBitmap;
s: string;
typ_graph: byte;
procedure ReadGraph(FileName: string);
procedure AddItems(Items: TStrings);
procedure AddNode(x,y: integer);
function FindNode(x,y: integer): integer;
procedure AddEdge(n1,n2,xb,x: integer);
procedure SaveGraph(FileName: string);
procedure OpenGraph(FileName: string);
procedure SetMatr;
procedure SetSim;
procedure ClearVisit;
function DepthSearch(n: integer; NameNode: string): integer;
function DepthSearchStack(n: integer; NameNode: string): integer;
function BreadthSearch(v: integer; NameNode: string): integer;
procedure SetTreeDepth(n: integer);
procedure SortEdge;
procedure SortNumEdge(V: array of word);
procedure PathEuler;
procedure Gamilton(Items: TStrings);
function MinDist(s,v0: integer): integer;
procedure MinDist0(s: integer; Items: TStrings);
function StackToStr(Path: TStack): string;
function Dijkst(s,t: integer): integer;
procedure BellMann(from: integer);
procedure Craskal;
function SetColor: integer;
procedure TopSort;
procedure SetEdge(s: integer);
implementation
procedure Stack_Init(var S: TStack);
begin
S.top:=1; S.bottom:=1;
end;
function Stack_IsEmpty(var S: TStack): boolean;
begin
Result:=S.Top=S.bottom;
end;
function Push(var S: TStack; E: integer): boolean;
begin
Result:=S.Top<SizeStack;
if Result then
with S do begin
Top:=Top+1; Elements[Top]:=E;
end;
end;
function Stack_Pop(var S: TStack; var E: integer): boolean;
begin
Result := not Stack_IsEmpty(S);
if Result then
with S do begin
E:=Elements[Top]; Top:=(Top+SizeStack-1) mod SizeStack;
end;
end;
function Stack_Pop_End(var S: TStack; var E: integer): boolean;
begin
Result := not Stack_IsEmpty(S);
if Result then
with S do begin
E:=Elements[Bottom]; Bottom:=Bottom mod SizeStack+1;
end;
end;
procedure SetDoubleRed(m,n: integer);
var LL,i: integer; Ok: boolean;
begin
LL:=Length(Node[m].Edge); Ok:=false; i:=-1;
while (i<LL-1) and not Ok do begin
Inc(i);
Ok:=Node[m].Edge[i].NumNode=n;
end;
if Ok then Node[m].Edge[i].Color:=clBlack;
end;
procedure SetEdgeBlack(v,i: integer);
begin
Node[v].Edge[i].Color:=clBlack;
SetDoubleRed(Node[v].Edge[i].NumNode,v);
end;
procedure AddNode(x,y: integer);
begin
N:=Length(Node); N:=N+1; SetLength(Node,N);
Node[N-1].Name:='Node '+IntToStr(N);
Node[N-1].x0:=x; Node[N-1].y0:=y;
Node[N-1].Color:=clWhite;
SelectNode:=N-1;
end;
function FindNode(x,y: integer): integer;
var
i: integer;
Ok: boolean;
begin
N:=Length(Node); i:=-1; Ok:=false;
while (i<N-1) and not Ok do begin
Inc(i);
with Node[i] do
Ok:=(x0-hx<=x) and (x<=x0+hx) and (y0-hy<=y) and (y<=y0+hy);
end;
if Ok then Result:=i else Result:=-1;
end;
function TestEdge(n1,n2: integer): boolean;
var
i: integer;
begin
LL:=Length(Node[n1].Edge); i:=-1;
Result:=false;
while (i<LL-1) and not Result do begin
Inc(i); Result:=(n1=n2) or (Node[n1].Edge[i].NumNode=n2);
end;
end;
procedure AddEdge(n1,n2,xb,x: integer);
begin
if not TestEdge(n1,n2) then begin
LL:=Length(Node[n1].Edge); LL:=LL+1;
SetLength(Node[n1].Edge,LL);
with Node[n1].Edge[LL-1] do begin
NumNode:=n2;
A:=0;
x1c:=xb-Node[n1].x0; x2c:=x-Node[n2].x0;
yc:=(Node[n1].y0+Node[n2].y0) div 2;
end;
end;
end;
procedure SaveGraph(FileName: string);
var i,j: integer;
procedure WriteStr(s: string);
var L: word;
begin
L:=Length(s);
BlockWrite(f,L,SizeOf(L)); // Length Name
BlockWrite(f,s[1],L); // Name
end;
begin
AssignFile(f,FileName); Rewrite(f,1);
N:=Length(Node);
BlockWrite(f,N,SizeOf(N));
for i:=0 to N-1 do
with Node[i] do begin
BlockWrite(f,x0,SizeOf(x0));
BlockWrite(f,y0,SizeOf(y0));
BlockWrite(f,Color,SizeOf(Color));
WriteStr(Name);
LL:=Length(Edge);
BlockWrite(f,LL,SizeOf(LL));
for j:=0 to LL-1 do
with Edge[j] do begin
BlockWrite(f,A,SizeOf(A));
BlockWrite(f,NumNode,SizeOf(NumNode));
BlockWrite(f,x1c,SizeOf(x1c));
BlockWrite(f,x2c,SizeOf(x2c));
BlockWrite(f,yc,SizeOf(yc));
end;
end;
CloseFile(f);
end;
procedure OpenGraph(FileName: string);
var
i,j: integer;
function ReadStr: string;
var L: word;
begin
BlockRead(f,L,SizeOf(L)); // Length Name
SetLength(Result,L);
BlockRead(f,Result[1],L); // Name
end;
begin
AssignFile(f,FileName); Reset(f,1);
BlockRead(f,N,SizeOf(N));
SetLength(Node,N);
if N<>0 then
for i:=0 to N-1 do
with Node[i] do begin
BlockRead(f,x0,SizeOf(x0));
BlockRead(f,y0,SizeOf(y0));
BlockRead(f,Color,SizeOf(Color));
Name:=ReadStr;
BlockRead(f,LL,SizeOf(LL));
SetLength(Edge,LL);
if LL<>0 then
for j:=0 to LL-1 do
with Edge[j] do begin
BlockRead(f,A,SizeOf(A));
BlockRead(f,NumNode,SizeOf(NumNode));
BlockRead(f,x1c,SizeOf(x1c));
BlockRead(f,x2c,SizeOf(x2c));
BlockRead(f,yc,SizeOf(yc));
end;
end;
CloseFile(f);
end;
procedure SetMatr;
var
i,j: integer;
begin
N:=Length(Node);
SetLength(A,N,N);
for i:=0 to N-1 do
for j:=0 to N-1 do A[i,j]:=MaxInt0;
for i:=0 to N-1 do
with Node[i] do begin
A[i,i]:=0;
LL:=Length(Edge);
for j:=0 to LL-1 do
A[i,Edge[j].NumNode]:=Edge[j].A;
end;
end;
procedure SetSim;
var
i,j,L2,m: integer;
function IsNode(n1,n2: integer): integer;
var
i: integer; Ok: boolean;
begin
L2:=Length(Node[n2].Edge); Ok:=false; i:=-1;
while (i<L2-1) and not Ok do begin
Inc(i); Ok:=Node[n2].Edge[i].NumNode=n1;
end;
if Ok then Result:=i else Result:=-1;
end;
begin
N:=Length(Node);
for i:=0 to N-1 do
with Node[i] do begin
LL:=Length(Edge);
for j:=0 to LL-1 do
with Edge[j] do begin
m:=IsNode(i,NumNode);
if m=-1 then begin
L2:=L2+1; SetLength(Node[NumNode].Edge,L2);
Node[NumNode].Edge[L2-1].A:=A;
Node[NumNode].Edge[L2-1].NumNode:=i;
Node[NumNode].Edge[L2-1].x1c:=x2c;
Node[NumNode].Edge[L2-1].x2c:=x1c;
Node[NumNode].Edge[L2-1].yc:=yc;
end
else
if A<>0 then Node[NumNode].Edge[m].A:=A
end;
end;
end;
procedure ClearVisit;
var
i,j: integer;
begin
N:=Length(Node); Num:=0;
for i:=0 to N-1 do begin
Node[i].Visit:=false;
Node[i].NumVisit:=0;
Node[i].Color:=clWhite;
LL:=Length(Node[i].Edge);
for j:=0 to LL-1 do Node[i].Edge[j].Color:=clSilver;
end;
end;
procedure VisitTrue(n: integer);
begin
Node[n].Visit:=true;
Num:=Num+1; Node[n].NumVisit:=Num;
end;
function DepthSearch(n: integer; NameNode: string): integer;
// рекурсивный поиск в глубину
var
m: integer;
function FindDepth(n: integer): integer;
var i,LL: integer;
begin
VisitTrue(n); // отметить посещенный
if Node[n].Name=NameNode then Result:=n
else begin
LL:=Length(Node[n].Edge); i:=-1; Result:=-1;
while (i<LL-1) and (Result=-1) do
begin
Inc(i);
m:=Node[n].Edge[i].NumNode;
if not Node[m].Visit then
begin
SetEdgeBlack(n,i); // закрасить дугу
Result:=FindDepth(m)
end;
end;
end;
end;
begin
ClearVisit;
Result:=FindDepth(n);
end;
function FindNotVisit(t: integer; var i: integer): integer;
// найти непосещенный узел
var
Ok: boolean;
begin
LL:=Length(Node[t].Edge);
Ok:=false; i:=-1;
while (i<LL-1) and not Ok do begin
Inc(i);
Ok:=not Node[Node[t].Edge[i].NumNode].Visit;
end;
if Ok then Result:=Node[t].Edge[i].NumNode else Result:=-1;
end;
function DepthSearchStack(n: integer; NameNode: string): integer;
// нерекурсивный поиск в глубину
var
i,m: integer;
begin
ClearVisit;
Stack_Init(Stack);
Result:=-1;
VisitTrue(n); // отметить посещенный
repeat
if Node[n].Name=NameNode then Result:=n // узел найден
else begin
m:=FindNotVisit(n,i); // найти непосещенный узел
if m<>-1 then begin
SetEdgeBlack(n,i); // закрасить дугу
Push(Stack,n); // поместить в стек
VisitTrue(m); // отметить посещенный
n:=m;
end
else Stack_Pop(Stack,n); // взять из стекa
end;
until Stack_IsEmpty(Stack) or (Result<>-1);
end;
function BreadthSearch(v: integer; NameNode: string): integer;
// поиск в ширину
var
i,m: integer;
begin
ClearVisit; Stack_Init(Stack);
Result:=-1;
VisitTrue(v); // отметить посещенный
Push(Stack,V); // поместить в очередь
while not Stack_IsEmpty(Stack) and (Result=-1) do begin
Stack_Pop_End(Stack,v); // взять из очереди
LL:=Length(Node[v].Edge); i:=-1;
while (i<LL-1) and (Result=-1) do begin
Inc(i); m:=Node[v].Edge[i].NumNode;
if not Node[m].Visit then begin// еще не посещали
SetEdgeBlack(v,i); // закрасить дугу
Push(Stack,m); // поместить в очередь
if Node[m].Name=NameNode then Result:=m;
VisitTrue(m); // отметить посещенный
end;
end;
end;
end;
procedure SetTreeDepth(n: integer);
// построение стягивающего дерева (остов) - поиск в глубину
var
m: integer;
procedure FindDepth(n: integer);
var i,LL: integer;
begin
VisitTrue(n); // отметить посещенный
LL:=Length(Node[n].Edge); i:=-1;
while i<LL-1 do begin
Inc(i);
m:=Node[n].Edge[i].NumNode;
if not Node[m].Visit then begin
SetEdgeBlack(n,i); // закрасить дугу
FindDepth(m);
end;
end;
end;
begin
ClearVisit;
FindDepth(n);
end;
procedure SortEdge;
var
i,j,k: integer;
t: TEdge;
begin
N:=Length(Node);
for k:=0 to N-1 do
with Node[k] do begin
LL:=Length(Edge);
for i:=0 to LL-2 do
for j:=LL-1 downto i+1 do
if Edge[j].A<Edge[j-1].A then begin
t:=Edge[j]; Edge[j]:=Edge[j-1]; Edge[j-1]:=t;
end;
end;
end;
procedure SortNumEdge(V: array of word);
var
i,j: integer;
t: word;
begin
for i:=0 to N-1 do V[i]:=i;
for i:=0 to N-2 do
for j:=N-1 downto i+1 do
if Length(Node[V[j]].Edge)<Length(Node[V[j-1]].Edge) then begin
t:=V[j]; V[j]:=V[j-1]; V[j-1]:=t;
end;
end;
procedure DeleteEdge(v,u: integer);
var
i,LL,m: integer;
Ok: boolean;
begin
LL:=Length(Node[v].Edge);
if LL<>0 then begin
m:=-1; Ok:=false;
while (m<LL-1) and not Ok do begin
Inc(m); Ok:=Node[v].Edge[m].NumNode=u;
end;
if Ok then begin
for i:=m+1 to LL-1 do Node[v].Edge[i-1]:=Node[v].Edge[i];
LL:=LL-1; SetLength(Node[v].Edge,LL);
end;
end;
end;
procedure PathEuler;
// Эйлеровы пути
var
v,u,i: integer;
function FindEdge(v: integer): integer;
var
i: integer; Ok: boolean;
begin
LL:=Length(Node[v].Edge); Ok:=false; i:=-1;
while (i<LL-1) and not Ok do begin
Inc(i); Ok:=Node[v].Edge[i].Color<>clBlack;
end;
if Ok then Result:=i else Result:=-1;
end;
begin
ClearVisit;
Stack_Init(Stack); Stack_Init(Path); //Stack:=nil;
v:=0;
Push(Stack,v); // поместить в стек
while not Stack_IsEmpty(Stack) do begin
i:=FindEdge(v);
if i<>-1 then begin
u:=Node[v].Edge[i].NumNode;
Push(Stack,u); // поместить в стек
SetEdgeBlack(v,i); // закрасить дугу
v:=u;
end
else begin
Stack_Pop(Stack,v); // взять из стекa
Push(Path,v); // поместить в стек
end;
end;
end;
procedure Gamilton(Items: TStrings);
// Гамильтонов путь
var
v0: integer;
function SetPath: string;
var j: integer;
begin
Result:='';
for j:=1 to N do Result:=Result+IntToStr(Path.Elements[j])+' ';
end;
procedure Gamilt(k: integer);
var i,y,u,LL: integer;
begin
y:=Path.Elements[k-1];
LL:=Length(Node[y].Edge);
for i:=0 to LL-1 do begin
u:=Node[y].Edge[i].NumNode;
if k=N+1 then Items.Add(SetPath) // вывести путь
else
if not Node[u].Visit then begin
Path.Elements[k]:=u;
Node[u].Visit:=true; // отметить посещенный
Gamilt(k+1);
Node[u].Visit:=false; // отменить посещенный
end;
end;
end;
begin
ClearVisit;
N:=Length(Node); v0:=0;
Path.Elements[1]:=v0;
VisitTrue(v0); // отметить посещенный
Gamilt(2);
end;
function MinDist(s,v0: integer): integer;
var
D: array of integer;
v,u: integer; Ok: boolean;
begin
SetMatr;
N:=Length(Node); SetLength(D,N);
for v:=0 to N-1 do D[v]:=A[s,v]; //D[s]:=0;
Stack_Init(Stack);
Push(Stack,v0); // поместить в стек
v:=v0;
while v<>s do begin
u:=-1; Ok:=false;
while (u<N-1) and not Ok do begin
Inc(u);
Ok:=(u<>v) and (D[v]=D[u]+A[u,v]);
end;
Push(Stack,u); // поместить в стек
v:=u;
end;
Result:=D[v];
end;
procedure MinDist0(s: integer; Items: TStrings);
var
v,u,k: integer;
begin
SetMatr;
N:=Length(Node);
for v:=0 to N-1 do Node[v].Dist:=A[s,v]; Node[s].Dist:=0;
for k:=0 to N-2 do
for v:=0 to N-1 do
if v<>s then
for u:=0 to N-1 do
Node[v].Dist:=Min(Node[v].Dist,Node[u].Dist+A[u,v]);
end;
function StackToStr(Path: TStack): string;
var
i: integer;
begin
Result:='';
while not Stack_IsEmpty(Path) do begin
Stack_Pop(Path,i); // взять из стекa
Result:=Result+IntToStr(i+1)+' ';
end;
end;
function Dijkst(s,t: integer): integer;
var
i,p: integer;
function FindMinDist(p: integer): integer;
var
i,MinDist: integer;
begin
MinDist:=MaxInt0;
for i:=0 to N-1 do
with Node[i] do
if not Visit then begin
Dist:=Min(Dist,Node[p].Dist+A[p,i]);
if Dist<MinDist then begin
MinDist:=Dist; Result:=i;
end;
end;
end;
procedure PathToStack(s,p: integer);
var i: integer; Ok: boolean;
begin
Stack_Init(Stack);
while p<>s do begin
Push(Stack,p); // поместить в стек
i:=-1; Ok:=false;
while (i<N-1) and not Ok do begin
Inc(i);
Ok:=(i<>p) and (Node[p].Dist=Node[i].Dist+A[i,p]);
end;
p:=i;
end;
end;
begin
ClearVisit;
SetMatr;
// Инициализация
N:=Length(Node);
for i:=0 to N-1 do
with Node[i] do Dist:=MaxInt0;
Node[s].Dist:=0; VisitTrue(s);
p:=s;
repeat
p:=FindMinDist(p); // обновление & найти
VisitTrue(p); // пометка=false
until p=t;
Result:=Node[p].Dist;
PathToStack(s,p);
end;
procedure AddItems(Items: TStrings);
var
i: byte;
s: string;
begin
N:=Length(Node);
for i:=0 to N-1 do
with Node[i] do begin
if Dist=MaxInt0 then s:='No path' else s:=IntToStr(Dist);
s:=IntToStr(i)+' '+s;
Items.Add(s);
end;
end;
procedure ReadGraph(FileName: string);
var
i,beg,en,A,from: integer;
f: textfile;
NumEdge: integer;
begin
AssignFile(f,FileName); Reset(f);
Readln(f,N,NumEdge,from); // 5 8 1
SetLength(Node,N);
for i:=0 to N-1 do
with Node[i] do begin
x0:=Random(400); y0:=Random(400);
Color:=clWhite;
SetLength(Edge,0);
end;
for i:=1 to NumEdge do begin
Readln(f,beg,en,A);
LL:=Length(Node[en].Edge); LL:=LL+1; SetLength(Node[en].Edge,LL);
Node[en].Edge[LL-1].A:=A;
Node[en].Edge[LL-1].NumNode:=beg;
end;
CloseFile(f);
end;
procedure BellMann(from: integer);
// Алгоритм Беллмана
var
i,j : integer;
// было ли на этом шаге изменено значение кратчайшего
// пути хоть до одной вершины
Ok : boolean;
begin
N:=Length(Node);
for i:=0 to N-1 do
with Node[i] do
if i=from then Dist:=0 else Dist:=MaxInt0;
repeat
// сохраняем значение кратчайшего пути на предыдущем шаге
for i:=0 to N-1 do
with Node[i] do
OldDist:=Dist;
Ok:=false;
for i:=0 to N-1 do
with Node[i] do begin
LL:=Length(Edge);
if LL>0 then
// просматриваем ребра, входящие в текущую вершину
for j:=0 to LL-1 do
with Edge[j] do
if A+Node[NumNode].OldDist<Dist then begin// если нашли путь короче
Dist:=A+Node[NumNode].OldDist; // исправляем Dist
Ok:=true; // и ставим флаг
end;
end;
until not Ok; // если очередная итерация прошла неуспешно
end;
procedure SetColorEdge; // закраска ребер
var
i,j,t: integer;
begin
while not Stack_IsEmpty(Stack) do begin
Stack_Pop(Stack,t); // взять из стека № ребра
for i:=0 to N-1 do
with Node[i] do begin
LL:=Length(Edge);
for j:=0 to LL-1 do
if ((i=Edges[t].n1) and (Edge[j].NumNode=Edges[t].n2)) or
((i=Edges[t].n2) and (Edge[j].NumNode=Edges[t].n1)) then
SetEdgeBlack(i,j); // закрасить ребро
end;
end;
end;
procedure Craskal;
// Алгоритм Краскала
// 1. Сортируем ребра графа по возрастанию весов.
// 2. Полагаем что каждая вершина относится к своей компоненте связности.
// 3. Проходим ребра в "отсортированном" порядке. Для каждого ребра выполняем:
// а) если вершины, соединяемые данным ребром лежат в разных компонентах
// связности, то объединяем эти компоненты в одну, а рассматриваемое ребро
// добавляем к минимальному остовному дереву
// б) если вершины, соединяемые данным ребром лежат в одной компоненте связности,
// то исключаем ребро из рассмотрения.
// 4. Если есть еще нерассмотренные ребра и не все компоненты связности объединены
// в одну, то переходим к шагу 3, иначе выход.
var i,j,q,m,t: integer;
h: TEdges;
Link: array of integer;// № связности для вершин
begin
ClearVisit; Stack_Init(Stack);
N:=Length(Node); m:=0;
for i:=0 to N-1 do // формируем массив всех ребер
with Node[i] do begin
LL:=Length(Edge);
for j:=0 to LL-1 do begin
Inc(m); SetLength(Edges,m);
Edges[m-1].n1:=i; Edges[m-1].n2:=Edge[j].NumNode;
Edges[m-1].A:=Edge[j].A;
end;
end;
for i:=0 to m-2 do // Сортируем ребра графа по возрастанию весов
for j:=m-1 downto i+1 do
if Edges[j].A<Edges[j-1].A then begin
h:=Edges[j]; Edges[j]:=Edges[j-1]; Edges[j-1]:=h;
end;
SetLength(Link,N); // Вначале все ребра в разных компонента связности
for i:=0 to N-1 do Link[i]:=i;
i:=0; q:=N-1;
while (i<=m-1) and (q<>0) do begin
// если вершины в разных компонентах связности
if Link[Edges[i].n1]<>Link[Edges[i].n2] then begin
t:=Edges[i].n2; Push(Stack,i); // поместить в стек № ребра
for j:=0 to N-1 do
if Link[j]=t then Link[j]:=Link[Edges[i].n1]; // в один компонент связности
q:=q-1;
end;
Inc(i);
end;
SetColorEdge; // закраска ребер
SetLength(Edges,0);
end;
function SetColor: integer;
// переборный алгоритм раскраски
var
k,i: integer;
Ok: boolean;
V: array of word;
function IsBorder(i,k: integer): boolean;
var j: integer;
begin
j:=-1; Result:=false;
while (j<N-1) and not Result do begin
Inc(j);
Result:=Node[j].Visit and
(Node[j].Color=Colors[k]) and
(A[i,j]<>MaxInt0);
end;
end;
begin
N:=Length(Node); SetLength(V,N);
for i:=0 to N-1 do V[i]:=i;
SortNumEdge(V);
ClearVisit; SetMatr;
k:=0;
repeat
Ok:=false; i:=-1;
while (i<N-1) and not Ok do begin
Inc(i); Ok:=not Node[i].Visit;
end;
if Ok then begin // найдена не окрашенная
VisitTrue(i); // окрашено
Node[i].Color:=Colors[k];
for i:=0 to N-1 do
if not Node[i].Visit and // не окрашена
not IsBorder(i,k) then // нет соседей цвета k
begin
VisitTrue(i); // окрашено
Node[i].Color:=Colors[k];
end;
k:=k+1;
end;
until not Ok;
Result:=k;
end;
procedure TopSort;
// топологическая сортировка
var
i: integer;
procedure SetVisit(i: integer);
var j: integer;
begin
with Node[i] do
if not Visit then begin
for j:=0 to Length(Edge)-1 do begin
SetEdgeBlack(i,j); // закрасить дугу
SetVisit(Edge[j].NumNode);
end;
Push(Stack,i-1);
VisitTrue(i); // посетили узел
end;
end;
begin
N:=Length(Node); ClearVisit;
Stack_Init(Stack);
for i:=0 to N-1 do SetVisit(i);
end;
procedure SetEdge(s: integer);
// связность графа
procedure SetEdgeR(v: integer);
var i: integer;
begin
if not Node[v].Visit then begin
VisitTrue(v); // окрашено
Push(Stack,v);
LL:=Length(Node[v].Edge);
for i:=0 to LL-1 do
SetEdgeR(Node[v].Edge[i].NumNode);
end;
end;
begin
ClearVisit;
Stack_Init(Stack);
SetEdgeR(s);
end;
end.
|
{***********************************<_INFO>************************************}
{ <Проект> Компоненты медиа-преобразования }
{ }
{ <Область> Мультимедиа }
{ }
{ <Задача> Преобразователь PCM. Реализация }
{ }
{ <Автор> Фадеев Р.В. }
{ }
{ <Дата> 21.01.2011 }
{ }
{ <Примечание> Отсутствует }
{ }
{ <Атрибуты> ООО НПП "Спецстрой-Связь", ООО "Трисофт" }
{ }
{***********************************</_INFO>***********************************}
unit MediaProcessing.Transformer.Pcm.Impl;
interface
uses SysUtils,Windows,Classes, Graphics, BitmapStreamMediator,
MediaProcessing.Definitions,MediaProcessing.Global,MediaProcessing.Transformer.Pcm;
type
TMediaProcessor_Transformer_Pcm_Impl =class (TMediaProcessor_Transformer_Pcm,IMediaProcessorImpl)
private
FPcmBuffer: TBytes;
protected
procedure Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal); override;
public
constructor Create; override;
destructor Destroy; override;
end;
implementation
uses uBaseClasses;
{ TMediaProcessor_Transformer_Pcm_Impl }
constructor TMediaProcessor_Transformer_Pcm_Impl.Create;
begin
inherited;
end;
//------------------------------------------------------------------------------
destructor TMediaProcessor_Transformer_Pcm_Impl.Destroy;
begin
FPcmBuffer:=nil;
inherited;
end;
//------------------------------------------------------------------------------
procedure TMediaProcessor_Transformer_Pcm_Impl.Process(aInData: pointer; aInDataSize:cardinal; const aInFormat: TMediaStreamDataHeader; aInfo: pointer; aInfoSize: cardinal;
out aOutData: pointer; out aOutDataSize: cardinal; out aOutFormat: TMediaStreamDataHeader; out aOutInfo: pointer; out aOutInfoSize: cardinal);
var
i: Integer;
begin
TArgumentValidation.NotNil(aInData);
//Пусть по умолчанию выходные данные совпадают с входными
aOutInfo:=aInfo;
aOutInfoSize:=aInfoSize;
aOutFormat:=aInFormat; //Выходной формат у нас не меняется. Меняется только состав данных
if self.SomeSetting<>0 then
begin
//Пример использования настроек
end;
//Пример преобразования
case Random(2) of
0: begin
aOutData:=nil;
aOutDataSize:=0; //Фрейм выкидывается
end;
1: begin
//Преобразование с использованием буфера
if cardinal(Length(FPcmBuffer))<aInDataSize then
begin
FPcmBuffer:=nil; //Сначала отпустим старый буфер, чтобы был новый Allocate, а не Relocate. Это снижает фрагментацию
SetLength(FPcmBuffer,aInDataSize);
for i := 0 to aInDataSize-1 do
FPcmBuffer[i]:=(PByte(aInData)+i)^ div 2;
aOutData:=FPcmBuffer;
aOutDataSize:=aInDataSize; //Размер выходных данных не меняется
end;
end;
2: begin
//Ничего не делаем. Выходными данными будут входные
aOutData:=aInData;
aOutDataSize:=aInDataSize;
end
else begin
raise EAlgoError.Create;
end;
end;
end;
initialization
MediaProceccorFactory.RegisterMediaProcessorImplementation(TMediaProcessor_Transformer_Pcm_Impl);
end.
|
unit untEasyUtilConst;
interface
const
EASY_SYS_ERROR = '系统错误';
EASY_SYS_HINT = '系统提示';
EASY_SYS_EXCEPTION = '系统异常';
EASY_SYS_EXIT = '系统退出';
EASY_SYS_ABORT = '系统中断';
//包加载文件不存在
EASY_BPL_NOTFOUND = '加载指定的文件%s已丢失!';
//数据库连接
EASY_DB_NOTFILE = '系统文件丢失,原因:数据模块丢失!';
EASY_DB_INITERROR = '数据模块初始化失败,请检查数据连接模块!';
EASY_DB_LOADERROR = '数据模块加载失败,原因:数据模块损坏或丢失!';
//闪窗体
EASY_SPLASH_NOTFILE = '系统文件丢失,原因:闪窗体(SplashForm.dll)文件丢失!';
//登录窗体
EASY_LOGIN_NOTFILE = '系统登录文件丢失!';
//主窗体显示时
EASY_DISPLAYUSERINFO_WELCOME = '欢迎 ';
EASY_DISPLAYUSERINFO_DEPT = '部门 ';
EASY_DISPLAYUSERINFO_NULL = '此用户未有员工使用,无法登录系统!';
EASY_DISPLAYUSERINFO_MORE = '此用户有多个员工使用,系统已阻止登录!';
EASY_STATUBAR_APP = '应用程序类型 ';
EASY_STATUBAR_DBHOST = ' 数据服务器 ';
implementation
end.
|
unit MyMath;
//{$MODE Delphi}
interface
uses
SysUtils,
Nodes, TreeVisitor;
{ This unit defines subclasses of TNode for representing the following
signature:
Data = Real | BinOpKind | Funckind
Sorts = Math
Math = Const | Var | UMinus | BinOp | BinExp | Func | FuncApp
Const = D[val: Real]
Var = D[name: Char]
UMinus = S[arg: Math]
BinOp = D[kind: BinOpKind]
BinExp = S[left: Math, op: BinOp, right: Math]
Func = D[kind: FuncKind]
FuncApp = S[func: Func, arg: Math]
}
const
// math kinds
mkConst = 31;
mkVar = 32;
mkUMinus = 33; // Unary minus
mkBinop = 34; // Binary operator
mkBinExp = 35; // Binary expression
mkFunc = 36; // Function symbol
mkFuncApp = 37; // Function application
type
TMathKind = mkConst..mkFuncApp;
TBinOpKind = (boPlus, boMinus, boTimes, boDivide);
TFuncKind = (fkSin, fkCos, fkExp, fkLn);
TMath =
class(TNode)
end;
TMath_Const =
class(TMath)
private
FVal: Real;
public
constructor Create(AVal: Real);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
function GetData: String; override;
class function Hasdata: Boolean; override;
property Val: Real read FVal;
end;
TMath_Var =
class(TMath)
private
FName: Char;
public
constructor Create(AName: Char);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
function GetData: String; override;
class function HasData: Boolean; override;
end;
TMath_Uminus =
class(TMath)
private
FArg: TMath;
public
constructor Create(AArg: TMath);
destructor Destroy; override;
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
end;
TMath_BinOp =
class(TMath)
private
FOpKind: TBinOpKind;
public
constructor Create(AOpKind: TBinOpKind);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
function GetData: String; override;
class function HasData: Boolean; override;
property OpKind: TBinOpKind read FOpKind;
end;
TMath_BinExp =
class(TMath)
private
FLeft : TMath;
FOp : TMath_BinOp;
FRight: TMath;
public
constructor Create(ALeft: TMath; AOp: TMath_BinOp; ARight: TMath);
destructor Destroy; override;
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
property Left: TMath read FLeft;
property Op: TMath_BinOp read FOp;
property Right: TMath read FRight;
end;
TMath_Func =
class(TMath)
private
FFuncKind: TFuncKind;
public
constructor Create(AFuncKind: TFuncKind);
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
function GetData: String; override;
class function HasData: Boolean; override;
property FuncKind: TFuncKind read FFuncKind;
end;
TMath_FuncApp =
class(TMath)
private
FFunc : TMath_Func;
FArg: TMath;
public
constructor Create(AFunc: TMath_Func; AArg: TMath);
destructor Destroy; override;
class function GetKind: TNodeKind; override;
class function GetNrofSons: Integer; override;
function GetSon(I: Integer): TNode; override;
procedure SetSon(I: Integer; ANode: TNode); override;
class function OpName: String; override;
property Func: TMath_Func read FFunc;
property Arg: TMath read FArg;
end;
TMathVisitor =
class(TTreeVisitor)
procedure Visit(ANode: TNode); override;
procedure VisitConst (ANode: TMath_Const); virtual;
procedure VisitVar (ANode: TMath_Var); virtual;
procedure VisitUMinus (ANode: TMath_UMinus); virtual;
procedure VisitBinOp (ANode: TMath_BinOp); virtual;
procedure VisitBinExp (ANode: TMath_BinExp); virtual;
procedure VisitFunc (ANode: TMath_Func); virtual;
procedure VisitFuncApp(ANode: TMath_FuncApp); virtual;
end;
implementation{===========================================}
{ TMath_Const }
constructor TMath_Const.Create(AVal: Real);
begin
inherited Create;
FVal := AVal;
end;
class function TMath_Const.GetKind: TNodeKind;
begin
Result := mkConst;
end;
function TMath_Const.GetData: String;
begin
Result := FloatToStr(FVal);
end;
class function TMath_Const.OpName: String;
begin
Result := 'Const';
end;
function TMath_Const.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: Const.GetSon with index ' + IntToStr(I));
end;
class function TMath_Const.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_Const.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Const.SetSon with index ' + IntToStr(I));
end;
class function TMath_Const.Hasdata: Boolean;
begin
Result := true;
end;
{ TMath_Var }
constructor TMath_Var.Create(AName: Char);
begin
inherited Create;
FName := Aname;
end;
class function TMath_Var.GetKind: TNodeKind;
begin
Result := mkVar;
end;
function TMath_Var.GetData: String;
begin
Result := FName;
end;
class function TMath_Var.OpName: String;
begin
Result := 'Var';
end;
function TMath_Var.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: Var.GetSon with index ' + IntToStr(I));
end;
class function TMath_Var.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_Var.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Var.SetSon with index ' + IntToStr(I));
end;
class function TMath_Var.HasData: Boolean;
begin
Result := true;
end;
{ TMath_UMinus }
constructor TMath_UMinus.Create(AArg: TMath);
begin
inherited Create;
FArg := AArg;
end;
destructor TMath_UMinus.Destroy;
begin
FArg.Free;
inherited Destroy;
end;
class function TMath_UMinus.GetKind: TNodeKind;
begin
Result := mkUMinus;
end;
class function TMath_UMinus.GetNrofSons: Integer;
begin
Result := 1;
end;
function TMath_UMinus.GetSon(I: Integer): TNode;
begin
case I of
0: Result := FArg
else
raise EGetSonIndex('Node error: UMinus.GetSon with index ' + IntToStr(I))
end;
end;
procedure TMath_UMinus.SetSon(I: Integer; ANode: TNode);
begin
case I of
0: FArg := ANode as TMath
else
raise ESetSonIndex('Node error: UMinus.SetSon with index ' + IntToStr(I))
end;
end;
class function TMath_UMinus.OpName: String;
begin
Result := 'UMinus';
end;
{ TMath_BinOp }
constructor TMath_BinOp.Create(AOpKind: TBinOpKind);
begin
inherited Create;
FOpKind := AOpKind;
end;
class function TMath_BinOp.GetKind: TNodeKind;
begin
Result := mkBinOp;
end;
function TMath_BinOp.GetData: String;
begin
case FOpKind of
boPlus:
Result := '+';
boMinus:
Result := '-';
boTimes:
Result := '*';
boDivide:
Result := '/';
end;
end;
class function TMath_BinOp.OpName: String;
begin
Result := 'BinOp';
end;
function TMath_BinOp.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: BinOp.GetSon with index ' + IntToStr(I));
end;
class function TMath_BinOp.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_BinOp.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Const.SetSon with index ' + IntToStr(I));
end;
class function TMath_BinOp.HasData: Boolean;
begin
Result := true;
end;
{ TMath_BinExp }
constructor TMath_BinExp.Create(ALeft: TMath; AOp: TMath_BinOp; ARight: TMath);
begin
inherited Create;
FLeft := ALeft;
FOp := AOp;
FRight := ARight;
end;
destructor TMath_BinExp.Destroy;
begin
FLeft.Free;
FOp.Free;
FRight.Free;
inherited Destroy;
end;
class function TMath_BinExp.GetKind: TNodeKind;
begin
Result := mkBinExp;
end;
class function TMath_BinExp.GetNrofSons: Integer;
begin
Result := 3;
end;
function TMath_BinExp.GetSon(I: Integer): TNode;
begin
case I of
0: Result := FLeft;
1: Result := FOp;
2: Result := FRight
else
raise EGetSonIndex('Node error: BinExp.GetSon with index ' + IntToStr(I))
end;
end;
procedure TMath_BinExp.SetSon(I: Integer; ANode: TNode);
begin
case I of
0: FLeft := ANode as TMath;
1: FOp := ANode as TMath_BinOp;
2: FRight := ANode as TMath
else
raise ESetSonIndex('Node error: BinExp.SetSon with index ' + IntToStr(I))
end;
end;
class function TMath_BinExp.OpName: String;
begin
Result := 'BinExp';
end;
{ TMath_Func }
constructor TMath_Func.Create(AFuncKind: TFuncKind);
begin
inherited Create;
FFuncKind := AFuncKind;
end;
class function TMath_Func.GetKind: TNodeKind;
begin
Result := mkFunc;
end;
function TMath_Func.GetData: String;
begin
case FFuncKind of
fkSin:
Result := 'Sin';
fkCos:
Result := 'Cos';
fkExp:
Result := 'Exp';
fkLn:
Result := 'Ln';
end;
end;
class function TMath_Func.OpName: String;
begin
Result := 'Func';
end;
function TMath_Func.GetSon(I: Integer): TNode;
begin
raise EGetSonIndex('Node error: Func.GetSon with index ' + IntToStr(I));
end;
class function TMath_Func.GetNrofSons: Integer;
begin
Result := 0;
end;
procedure TMath_Func.SetSon(I: Integer; ANode: TNode);
begin
raise ESetSonIndex('Node error: Func.SetSon with index ' + IntToStr(I));
end;
class function TMath_Func.HasData: Boolean;
begin
Result := true;
end;
{ TMath_FuncApp }
constructor TMath_FuncApp.Create(AFunc: TMath_Func; AArg: TMath);
begin
inherited Create;
FFunc := AFunc;
FArg := AArg;
end;
destructor TMath_FuncApp.Destroy;
begin
FFunc.Free;
FArg.Free;
inherited Destroy;
end;
class function TMath_FuncApp.GetKind: TNodeKind;
begin
Result := mkFuncApp;
end;
class function TMath_FuncApp.GetNrofSons: Integer;
begin
Result := 2;
end;
function TMath_FuncApp.GetSon(I: Integer): TNode;
begin
case I of
0: Result := FFunc;
1: Result := FArg;
else
raise EGetSonIndex('Node error: FuncApp.GetSon with index ' + IntToStr(I))
end;
end;
class function TMath_FuncApp.OpName: String;
begin
Result := 'FuncApp';
end;
procedure TMath_FuncApp.SetSon(I: Integer; ANode: TNode);
begin
case I of
0: FFunc := ANode as TMath_Func;
1: FArg := ANode as TMath;
else
raise ESetSonIndex('Node error: FuncApp.SetSon with index ' + IntToStr(I))
end;
end;
{ TMathVisitor }
procedure TMathVisitor.Visit(ANode: TNode);
begin
// Dispatch by means of ANode.GetKind
case ANode.GetKind of
mkConst : VisitConst (ANode as TMath_Const);
mkVar : VisitVar (ANode as TMath_Var );
mkUMinus : VisitUMinus (ANode as TMath_UMinus);
mkBinOp : VisitBinOp (ANode as TMath_BinOp );
mkBinExp : VisitBinExp (ANode as TMath_BinExp );
mkFunc : VisitFunc (ANode as TMath_Func );
mkFuncApp: VisitFuncApp(ANode as TMath_FuncApp);
else
raise ENodeKind.Create('Unexpected NodeKind in TPropVisitor');
end;
end;
procedure TMathVisitor.VisitBinExp(ANode: TMath_BinExp);
begin
end;
procedure TMathVisitor.VisitBinOp(ANode: TMath_BinOp);
begin
end;
procedure TMathVisitor.VisitConst(ANode: TMath_Const);
begin
end;
procedure TMathVisitor.VisitFunc(ANode: TMath_Func);
begin
end;
procedure TMathVisitor.VisitFuncApp(ANode: TMath_FuncApp);
begin
end;
procedure TMathVisitor.VisitUMinus(ANode: TMath_UMinus);
begin
end;
procedure TMathVisitor.VisitVar(ANode: TMath_Var);
begin
end;
end.
|
{
X2Software XML Data Binding
Generated on: 22/04/2020 11:59:03
Generated from: P:\x2xmldatabinding\XSD\DataBindingHints.xsd
}
unit DataBindingHintsXML;
interface
uses
Classes,
SysUtils,
XMLDoc,
XMLIntf,
XMLDataBindingUtils;
type
{ Forward declarations for DataBindingHints }
IXMLDataBindingHints = interface;
IXMLEnumerations = interface;
IXMLEnumeration = interface;
IXMLMember = interface;
IXMLDocumentElements = interface;
IXMLDocumentElement = interface;
IXMLInterfaces = interface;
IXMLInterfaceName = interface;
IXMLProperties = interface;
IXMLPropertyName = interface;
{ Interfaces for DataBindingHints }
{
Contains hints and mappings for the data binding output
}
IXMLDataBindingHints = interface(IXMLNode)
['{8122E348-4BE1-4436-AD2A-DAFED0CFA0C4}']
procedure XSDValidateDocument(AStrict: Boolean = False);
function GetHasEnumerations: Boolean;
function GetEnumerations: IXMLEnumerations;
function GetHasDocumentElements: Boolean;
function GetDocumentElements: IXMLDocumentElements;
function GetHasInterfaces: Boolean;
function GetInterfaces: IXMLInterfaces;
function GetHasProperties: Boolean;
function GetProperties: IXMLProperties;
property HasEnumerations: Boolean read GetHasEnumerations;
property Enumerations: IXMLEnumerations read GetEnumerations;
property HasDocumentElements: Boolean read GetHasDocumentElements;
property DocumentElements: IXMLDocumentElements read GetDocumentElements;
property HasInterfaces: Boolean read GetHasInterfaces;
property Interfaces: IXMLInterfaces read GetInterfaces;
property HasProperties: Boolean read GetHasProperties;
property Properties: IXMLProperties read GetProperties;
end;
IXMLEnumerationsEnumerator = interface
['{725760E4-70A5-47A6-B91B-C240F1FADA60}']
function GetCurrent: IXMLEnumeration;
function MoveNext: Boolean;
property Current: IXMLEnumeration read GetCurrent;
end;
IXMLEnumerations = interface(IXMLNodeCollection)
['{509EAF84-A4BF-4F15-B77C-98B58792A9C3}']
function GetEnumerator: IXMLEnumerationsEnumerator;
function Get_Enumeration(Index: Integer): IXMLEnumeration;
function Add: IXMLEnumeration;
function Insert(Index: Integer): IXMLEnumeration;
property Enumeration[Index: Integer]: IXMLEnumeration read Get_Enumeration; default;
end;
IXMLEnumerationEnumerator = interface
['{8A1AF158-2AF3-49FB-9CFC-46897D8AF28C}']
function GetCurrent: IXMLMember;
function MoveNext: Boolean;
property Current: IXMLMember read GetCurrent;
end;
IXMLEnumeration = interface(IXMLNodeCollection)
['{01A5E078-6EEB-40A0-BF72-972B467AD983}']
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetEnumerator: IXMLEnumerationEnumerator;
function Get_Member(Index: Integer): IXMLMember;
function Add: IXMLMember;
function Insert(Index: Integer): IXMLMember;
property Member[Index: Integer]: IXMLMember read Get_Member; default;
function GetSchema: WideString;
function GetXPath: WideString;
function GetHasReplaceMembers: Boolean;
function GetReplaceMembers: Boolean;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
procedure SetReplaceMembers(const Value: Boolean);
property Schema: WideString read GetSchema write SetSchema;
property XPath: WideString read GetXPath write SetXPath;
property HasReplaceMembers: Boolean read GetHasReplaceMembers;
property ReplaceMembers: Boolean read GetReplaceMembers write SetReplaceMembers;
end;
IXMLMember = interface(IXMLNode)
['{C58EF7F8-E182-47A3-B591-550A51AA0751}']
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetName: WideString;
function GetValue: WideString;
procedure SetName(const Value: WideString);
procedure SetValue(const Value: WideString);
property Name: WideString read GetName write SetName;
property Value: WideString read GetValue write SetValue;
end;
IXMLDocumentElementsEnumerator = interface
['{D58F3363-3E98-4EF9-9A9E-F57B7C4639D7}']
function GetCurrent: IXMLDocumentElement;
function MoveNext: Boolean;
property Current: IXMLDocumentElement read GetCurrent;
end;
{
If present, only elements which are included in this list will be marked as
a Document Element.
}
IXMLDocumentElements = interface(IXMLNodeCollection)
['{D991E86F-3D42-4B05-BB90-10AF42324FE1}']
function GetEnumerator: IXMLDocumentElementsEnumerator;
function Get_DocumentElement(Index: Integer): IXMLDocumentElement;
function Add: IXMLDocumentElement;
function Insert(Index: Integer): IXMLDocumentElement;
property DocumentElement[Index: Integer]: IXMLDocumentElement read Get_DocumentElement; default;
end;
IXMLDocumentElement = interface(IXMLNode)
['{0FD90406-67B2-4076-870C-47DA8E8582ED}']
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetSchema: WideString;
function GetXPath: WideString;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
property Schema: WideString read GetSchema write SetSchema;
property XPath: WideString read GetXPath write SetXPath;
end;
IXMLInterfacesEnumerator = interface
['{A1433E41-A316-4DBD-ADC2-7EA490CEFCB3}']
function GetCurrent: IXMLInterfaceName;
function MoveNext: Boolean;
property Current: IXMLInterfaceName read GetCurrent;
end;
IXMLInterfaces = interface(IXMLNodeCollection)
['{6A2EDBB5-36FE-4CA6-B3B9-1AC7A016E372}']
function GetEnumerator: IXMLInterfacesEnumerator;
function Get_InterfaceName(Index: Integer): IXMLInterfaceName;
function Add: IXMLInterfaceName;
function Insert(Index: Integer): IXMLInterfaceName;
property InterfaceName[Index: Integer]: IXMLInterfaceName read Get_InterfaceName; default;
end;
IXMLInterfaceName = interface(IXMLNode)
['{F0057FA9-92D8-47C5-AC29-6A045595B7F0}']
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetSchema: WideString;
function GetXPath: WideString;
function GetValue: WideString;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
procedure SetValue(const Value: WideString);
property Schema: WideString read GetSchema write SetSchema;
property XPath: WideString read GetXPath write SetXPath;
property Value: WideString read GetValue write SetValue;
end;
IXMLPropertiesEnumerator = interface
['{4FDE9618-2177-4D53-8B14-5E81E397E084}']
function GetCurrent: IXMLPropertyName;
function MoveNext: Boolean;
property Current: IXMLPropertyName read GetCurrent;
end;
IXMLProperties = interface(IXMLNodeCollection)
['{38320F29-9D8C-4158-B0F6-8E1D1FD31EB9}']
function GetEnumerator: IXMLPropertiesEnumerator;
function Get_PropertyName(Index: Integer): IXMLPropertyName;
function Add: IXMLPropertyName;
function Insert(Index: Integer): IXMLPropertyName;
property PropertyName[Index: Integer]: IXMLPropertyName read Get_PropertyName; default;
end;
IXMLPropertyName = interface(IXMLNode)
['{F99D3125-B2DE-4A4A-88D0-DBCB50C75C59}']
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetSchema: WideString;
function GetXPath: WideString;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
property Schema: WideString read GetSchema write SetSchema;
property XPath: WideString read GetXPath write SetXPath;
end;
{ Classes for DataBindingHints }
TXMLDataBindingHints = class(TX2XMLNode, IXMLDataBindingHints)
public
procedure AfterConstruction; override;
protected
procedure XSDValidateDocument(AStrict: Boolean = False);
function GetHasEnumerations: Boolean;
function GetEnumerations: IXMLEnumerations;
function GetHasDocumentElements: Boolean;
function GetDocumentElements: IXMLDocumentElements;
function GetHasInterfaces: Boolean;
function GetInterfaces: IXMLInterfaces;
function GetHasProperties: Boolean;
function GetProperties: IXMLProperties;
end;
TXMLEnumerationsEnumerator = class(TXMLNodeCollectionEnumerator, IXMLEnumerationsEnumerator)
protected
function GetCurrent: IXMLEnumeration;
end;
TXMLEnumerations = class(TX2XMLNodeCollection, IXMLEnumerations)
public
procedure AfterConstruction; override;
protected
function GetEnumerator: IXMLEnumerationsEnumerator;
function Get_Enumeration(Index: Integer): IXMLEnumeration;
function Add: IXMLEnumeration;
function Insert(Index: Integer): IXMLEnumeration;
end;
TXMLEnumerationEnumerator = class(TXMLNodeCollectionEnumerator, IXMLEnumerationEnumerator)
protected
function GetCurrent: IXMLMember;
end;
TXMLEnumeration = class(TX2XMLNodeCollection, IXSDValidate, IXSDValidateStrict, IXMLEnumeration)
public
procedure AfterConstruction; override;
protected
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetEnumerator: IXMLEnumerationEnumerator;
function Get_Member(Index: Integer): IXMLMember;
function Add: IXMLMember;
function Insert(Index: Integer): IXMLMember;
function GetSchema: WideString;
function GetXPath: WideString;
function GetHasReplaceMembers: Boolean;
function GetReplaceMembers: Boolean;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
procedure SetReplaceMembers(const Value: Boolean);
end;
TXMLMember = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLMember)
protected
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetName: WideString;
function GetValue: WideString;
procedure SetName(const Value: WideString);
procedure SetValue(const Value: WideString);
end;
TXMLDocumentElementsEnumerator = class(TXMLNodeCollectionEnumerator, IXMLDocumentElementsEnumerator)
protected
function GetCurrent: IXMLDocumentElement;
end;
TXMLDocumentElements = class(TX2XMLNodeCollection, IXMLDocumentElements)
public
procedure AfterConstruction; override;
protected
function GetEnumerator: IXMLDocumentElementsEnumerator;
function Get_DocumentElement(Index: Integer): IXMLDocumentElement;
function Add: IXMLDocumentElement;
function Insert(Index: Integer): IXMLDocumentElement;
end;
TXMLDocumentElement = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLDocumentElement)
protected
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetSchema: WideString;
function GetXPath: WideString;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
end;
TXMLInterfacesEnumerator = class(TXMLNodeCollectionEnumerator, IXMLInterfacesEnumerator)
protected
function GetCurrent: IXMLInterfaceName;
end;
TXMLInterfaces = class(TX2XMLNodeCollection, IXMLInterfaces)
public
procedure AfterConstruction; override;
protected
function GetEnumerator: IXMLInterfacesEnumerator;
function Get_InterfaceName(Index: Integer): IXMLInterfaceName;
function Add: IXMLInterfaceName;
function Insert(Index: Integer): IXMLInterfaceName;
end;
TXMLInterfaceName = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLInterfaceName)
protected
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetSchema: WideString;
function GetXPath: WideString;
function GetValue: WideString;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
procedure SetValue(const Value: WideString);
end;
TXMLPropertiesEnumerator = class(TXMLNodeCollectionEnumerator, IXMLPropertiesEnumerator)
protected
function GetCurrent: IXMLPropertyName;
end;
TXMLProperties = class(TX2XMLNodeCollection, IXMLProperties)
public
procedure AfterConstruction; override;
protected
function GetEnumerator: IXMLPropertiesEnumerator;
function Get_PropertyName(Index: Integer): IXMLPropertyName;
function Add: IXMLPropertyName;
function Insert(Index: Integer): IXMLPropertyName;
end;
TXMLPropertyName = class(TX2XMLNode, IXSDValidate, IXSDValidateStrict, IXMLPropertyName)
protected
procedure XSDValidate;
procedure XSDValidateStrict(AResult: IXSDValidateStrictResult);
function GetSchema: WideString;
function GetXPath: WideString;
procedure SetSchema(const Value: WideString);
procedure SetXPath(const Value: WideString);
end;
{ Document functions }
function GetDataBindingHints(ADocument: XMLIntf.IXMLDocument): IXMLDataBindingHints;
function LoadDataBindingHints(const AFileName: String): IXMLDataBindingHints;
function LoadDataBindingHintsFromStream(AStream: TStream): IXMLDataBindingHints;
function LoadDataBindingHintsFromString(const AString: String{$IF CompilerVersion >= 20}; AEncoding: TEncoding = nil; AOwnsEncoding: Boolean = True{$IFEND}): IXMLDataBindingHints;
function NewDataBindingHints: IXMLDataBindingHints;
const
TargetNamespace = 'http://www.x2software.net/xsd/databinding/DataBindingHints.xsd';
implementation
uses
Variants;
{ Document functions }
function GetDataBindingHints(ADocument: XMLIntf.IXMLDocument): IXMLDataBindingHints;
begin
Result := ADocument.GetDocBinding('DataBindingHints', TXMLDataBindingHints, TargetNamespace) as IXMLDataBindingHints
end;
function LoadDataBindingHints(const AFileName: String): IXMLDataBindingHints;
begin
Result := LoadXMLDocument(AFileName).GetDocBinding('DataBindingHints', TXMLDataBindingHints, TargetNamespace) as IXMLDataBindingHints
end;
function LoadDataBindingHintsFromStream(AStream: TStream): IXMLDataBindingHints;
var
doc: XMLIntf.IXMLDocument;
begin
doc := NewXMLDocument;
doc.LoadFromStream(AStream);
Result := GetDataBindingHints(doc);
end;
function LoadDataBindingHintsFromString(const AString: String{$IF CompilerVersion >= 20}; AEncoding: TEncoding; AOwnsEncoding: Boolean{$IFEND}): IXMLDataBindingHints;
var
stream: TStringStream;
begin
{$IF CompilerVersion >= 20}
if Assigned(AEncoding) then
stream := TStringStream.Create(AString, AEncoding, AOwnsEncoding)
else
{$IFEND}
stream := TStringStream.Create(AString);
try
Result := LoadDataBindingHintsFromStream(stream);
finally
FreeAndNil(stream);
end;
end;
function NewDataBindingHints: IXMLDataBindingHints;
begin
Result := NewXMLDocument.GetDocBinding('DataBindingHints', TXMLDataBindingHints, TargetNamespace) as IXMLDataBindingHints
end;
{ Implementation for DataBindingHints }
procedure TXMLDataBindingHints.AfterConstruction;
begin
RegisterChildNode('Enumerations', TXMLEnumerations);
RegisterChildNode('DocumentElements', TXMLDocumentElements);
RegisterChildNode('Interfaces', TXMLInterfaces);
RegisterChildNode('Properties', TXMLProperties);
inherited;
end;
procedure TXMLDataBindingHints.XSDValidateDocument(AStrict: Boolean);
begin
if AStrict then
XMLDataBindingUtils.XSDValidateStrict(Self)
else
XMLDataBindingUtils.XSDValidate(Self);
end;
function TXMLDataBindingHints.GetHasEnumerations: Boolean;
begin
Result := Assigned(ChildNodes.FindNode('Enumerations'));
end;
function TXMLDataBindingHints.GetEnumerations: IXMLEnumerations;
begin
Result := (ChildNodes['Enumerations'] as IXMLEnumerations);
end;
function TXMLDataBindingHints.GetHasDocumentElements: Boolean;
begin
Result := Assigned(ChildNodes.FindNode('DocumentElements'));
end;
function TXMLDataBindingHints.GetDocumentElements: IXMLDocumentElements;
begin
Result := (ChildNodes['DocumentElements'] as IXMLDocumentElements);
end;
function TXMLDataBindingHints.GetHasInterfaces: Boolean;
begin
Result := Assigned(ChildNodes.FindNode('Interfaces'));
end;
function TXMLDataBindingHints.GetInterfaces: IXMLInterfaces;
begin
Result := (ChildNodes['Interfaces'] as IXMLInterfaces);
end;
function TXMLDataBindingHints.GetHasProperties: Boolean;
begin
Result := Assigned(ChildNodes.FindNode('Properties'));
end;
function TXMLDataBindingHints.GetProperties: IXMLProperties;
begin
Result := (ChildNodes['Properties'] as IXMLProperties);
end;
function TXMLEnumerationsEnumerator.GetCurrent: IXMLEnumeration;
begin
Result := (inherited GetCurrent as IXMLEnumeration);
end;
procedure TXMLEnumerations.AfterConstruction;
begin
RegisterChildNode('Enumeration', TXMLEnumeration);
ItemTag := 'Enumeration';
ItemInterface := IXMLEnumeration;
inherited;
end;
function TXMLEnumerations.GetEnumerator: IXMLEnumerationsEnumerator;
begin
Result := TXMLEnumerationsEnumerator.Create(Self);
end;
function TXMLEnumerations.Get_Enumeration(Index: Integer): IXMLEnumeration;
begin
Result := (List[Index] as IXMLEnumeration);
end;
function TXMLEnumerations.Add: IXMLEnumeration;
begin
Result := (AddItem(-1) as IXMLEnumeration);
end;
function TXMLEnumerations.Insert(Index: Integer): IXMLEnumeration;
begin
Result := (AddItem(Index) as IXMLEnumeration);
end;
function TXMLEnumerationEnumerator.GetCurrent: IXMLMember;
begin
Result := (inherited GetCurrent as IXMLMember);
end;
procedure TXMLEnumeration.AfterConstruction;
begin
RegisterChildNode('Member', TXMLMember);
ItemTag := 'Member';
ItemInterface := IXMLMember;
inherited;
end;
procedure TXMLEnumeration.XSDValidate;
begin
CreateRequiredAttributes(Self, ['Schema', 'XPath']);
end;
procedure TXMLEnumeration.XSDValidateStrict(AResult: IXSDValidateStrictResult);
begin
ValidateRequiredAttributes(AResult, Self, ['Schema', 'XPath']);
end;
function TXMLEnumeration.GetEnumerator: IXMLEnumerationEnumerator;
begin
Result := TXMLEnumerationEnumerator.Create(Self);
end;
function TXMLEnumeration.Get_Member(Index: Integer): IXMLMember;
begin
Result := (List[Index] as IXMLMember);
end;
function TXMLEnumeration.Add: IXMLMember;
begin
Result := (AddItem(-1) as IXMLMember);
end;
function TXMLEnumeration.Insert(Index: Integer): IXMLMember;
begin
Result := (AddItem(Index) as IXMLMember);
end;
function TXMLEnumeration.GetSchema: WideString;
begin
Result := AttributeNodes['Schema'].Text;
end;
function TXMLEnumeration.GetXPath: WideString;
begin
Result := AttributeNodes['XPath'].Text;
end;
function TXMLEnumeration.GetHasReplaceMembers: Boolean;
begin
Result := Assigned(AttributeNodes.FindNode('ReplaceMembers'));
end;
function TXMLEnumeration.GetReplaceMembers: Boolean;
begin
Result := AttributeNodes['ReplaceMembers'].NodeValue;
end;
procedure TXMLEnumeration.SetSchema(const Value: WideString);
begin
SetAttribute('Schema', GetValidXMLText(Value));
end;
procedure TXMLEnumeration.SetXPath(const Value: WideString);
begin
SetAttribute('XPath', GetValidXMLText(Value));
end;
procedure TXMLEnumeration.SetReplaceMembers(const Value: Boolean);
begin
SetAttribute('ReplaceMembers', BoolToXML(Value));
end;
procedure TXMLMember.XSDValidate;
begin
CreateRequiredAttributes(Self, ['Name']);
end;
procedure TXMLMember.XSDValidateStrict(AResult: IXSDValidateStrictResult);
begin
ValidateRequiredAttributes(AResult, Self, ['Name']);
end;
function TXMLMember.GetName: WideString;
begin
Result := AttributeNodes['Name'].Text;
end;
function TXMLMember.GetValue: WideString;
begin
Result := VarToStr(GetNodeValue);
end;
procedure TXMLMember.SetName(const Value: WideString);
begin
SetAttribute('Name', GetValidXMLText(Value));
end;
procedure TXMLMember.SetValue(const Value: WideString);
begin
SetNodeValue(GetValidXMLText(Value));
end;
function TXMLDocumentElementsEnumerator.GetCurrent: IXMLDocumentElement;
begin
Result := (inherited GetCurrent as IXMLDocumentElement);
end;
procedure TXMLDocumentElements.AfterConstruction;
begin
RegisterChildNode('DocumentElement', TXMLDocumentElement);
ItemTag := 'DocumentElement';
ItemInterface := IXMLDocumentElement;
inherited;
end;
function TXMLDocumentElements.GetEnumerator: IXMLDocumentElementsEnumerator;
begin
Result := TXMLDocumentElementsEnumerator.Create(Self);
end;
function TXMLDocumentElements.Get_DocumentElement(Index: Integer): IXMLDocumentElement;
begin
Result := (List[Index] as IXMLDocumentElement);
end;
function TXMLDocumentElements.Add: IXMLDocumentElement;
begin
Result := (AddItem(-1) as IXMLDocumentElement);
end;
function TXMLDocumentElements.Insert(Index: Integer): IXMLDocumentElement;
begin
Result := (AddItem(Index) as IXMLDocumentElement);
end;
procedure TXMLDocumentElement.XSDValidate;
begin
CreateRequiredAttributes(Self, ['Schema', 'XPath']);
end;
procedure TXMLDocumentElement.XSDValidateStrict(AResult: IXSDValidateStrictResult);
begin
ValidateRequiredAttributes(AResult, Self, ['Schema', 'XPath']);
end;
function TXMLDocumentElement.GetSchema: WideString;
begin
Result := AttributeNodes['Schema'].Text;
end;
function TXMLDocumentElement.GetXPath: WideString;
begin
Result := AttributeNodes['XPath'].Text;
end;
procedure TXMLDocumentElement.SetSchema(const Value: WideString);
begin
SetAttribute('Schema', GetValidXMLText(Value));
end;
procedure TXMLDocumentElement.SetXPath(const Value: WideString);
begin
SetAttribute('XPath', GetValidXMLText(Value));
end;
function TXMLInterfacesEnumerator.GetCurrent: IXMLInterfaceName;
begin
Result := (inherited GetCurrent as IXMLInterfaceName);
end;
procedure TXMLInterfaces.AfterConstruction;
begin
RegisterChildNode('InterfaceName', TXMLInterfaceName);
ItemTag := 'InterfaceName';
ItemInterface := IXMLInterfaceName;
inherited;
end;
function TXMLInterfaces.GetEnumerator: IXMLInterfacesEnumerator;
begin
Result := TXMLInterfacesEnumerator.Create(Self);
end;
function TXMLInterfaces.Get_InterfaceName(Index: Integer): IXMLInterfaceName;
begin
Result := (List[Index] as IXMLInterfaceName);
end;
function TXMLInterfaces.Add: IXMLInterfaceName;
begin
Result := (AddItem(-1) as IXMLInterfaceName);
end;
function TXMLInterfaces.Insert(Index: Integer): IXMLInterfaceName;
begin
Result := (AddItem(Index) as IXMLInterfaceName);
end;
procedure TXMLInterfaceName.XSDValidate;
begin
CreateRequiredAttributes(Self, ['Schema', 'XPath']);
end;
procedure TXMLInterfaceName.XSDValidateStrict(AResult: IXSDValidateStrictResult);
begin
ValidateRequiredAttributes(AResult, Self, ['Schema', 'XPath']);
end;
function TXMLInterfaceName.GetSchema: WideString;
begin
Result := AttributeNodes['Schema'].Text;
end;
function TXMLInterfaceName.GetXPath: WideString;
begin
Result := AttributeNodes['XPath'].Text;
end;
function TXMLInterfaceName.GetValue: WideString;
begin
Result := VarToStr(GetNodeValue);
end;
procedure TXMLInterfaceName.SetSchema(const Value: WideString);
begin
SetAttribute('Schema', GetValidXMLText(Value));
end;
procedure TXMLInterfaceName.SetXPath(const Value: WideString);
begin
SetAttribute('XPath', GetValidXMLText(Value));
end;
procedure TXMLInterfaceName.SetValue(const Value: WideString);
begin
SetNodeValue(GetValidXMLText(Value));
end;
function TXMLPropertiesEnumerator.GetCurrent: IXMLPropertyName;
begin
Result := (inherited GetCurrent as IXMLPropertyName);
end;
procedure TXMLProperties.AfterConstruction;
begin
RegisterChildNode('PropertyName', TXMLPropertyName);
ItemTag := 'PropertyName';
ItemInterface := IXMLPropertyName;
inherited;
end;
function TXMLProperties.GetEnumerator: IXMLPropertiesEnumerator;
begin
Result := TXMLPropertiesEnumerator.Create(Self);
end;
function TXMLProperties.Get_PropertyName(Index: Integer): IXMLPropertyName;
begin
Result := (List[Index] as IXMLPropertyName);
end;
function TXMLProperties.Add: IXMLPropertyName;
begin
Result := (AddItem(-1) as IXMLPropertyName);
end;
function TXMLProperties.Insert(Index: Integer): IXMLPropertyName;
begin
Result := (AddItem(Index) as IXMLPropertyName);
end;
procedure TXMLPropertyName.XSDValidate;
begin
CreateRequiredAttributes(Self, ['Schema', 'XPath']);
end;
procedure TXMLPropertyName.XSDValidateStrict(AResult: IXSDValidateStrictResult);
begin
ValidateRequiredAttributes(AResult, Self, ['Schema', 'XPath']);
end;
function TXMLPropertyName.GetSchema: WideString;
begin
Result := AttributeNodes['Schema'].Text;
end;
function TXMLPropertyName.GetXPath: WideString;
begin
Result := AttributeNodes['XPath'].Text;
end;
procedure TXMLPropertyName.SetSchema(const Value: WideString);
begin
SetAttribute('Schema', GetValidXMLText(Value));
end;
procedure TXMLPropertyName.SetXPath(const Value: WideString);
begin
SetAttribute('XPath', GetValidXMLText(Value));
end;
end.
|
unit plugin;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils,
System.Classes, Vcl.ComCtrls, SciSupport, Vcl.Forms,
Vcl.Controls, NppPlugin;
type
TModalResultArray = array[False..True] of TModalResult;
TBdType = (bdMSSQL, bdSybase, bdODBC);
TBdTypeStringArray = array [TBdType] of string;
TItemType = (itServerMS,itServerSYB,itODBC,itBase,itBaseRTI,itLogin);
TMenuItemCheck = (miHidden,miShown);
TdsPlugin = class(TNppPlugin)
private
{ Private declarations }
FForm: TForm;
public
constructor Create;
procedure DoNppnToolbarModification; override;
procedure FuncLog;
procedure FuncExecSQL;
end;
const
WM_USER_MESSAGE_FROM_THREAD = WM_USER + 1;
cnstSqlWaitResults = 'Waiting........';
cnstSqlNoResults = 'Command executed';
cnstSqlExec = 'Results: %s\%s (%s)';
cnstModalResultArray: TModalResultArray = (mrCancel,mrOk);
cnstShowPlan_ON = 'set showplan on';
cnstShowPlan_OFF = 'set showplan off';
cnstAseOleDB = '[ASEOLEDB]';
cnstShowPlan = 'PLAN:';
cnstShowIndx = 'INDX:';
cnstSqlplanExt = '.sqlplan';
cnstGo = 'go';
constLoginBDCaption = 'Connect to ';
constLoginBDCaptionArray: TBdTypeStringArray = ('MSSQL','Sybase','ODBC');
constDSBDCaptionArray: TBdTypeStringArray = ('Server','Server','DataSource');
cnstErroCaption = 'Error';
cnstNoBaseSelected = 'You must select Server and Base before executing SQL!';
cnstMainDlgId = 0;
var
NPlugin: TdsPlugin;
implementation
uses connectionFormUnit;
procedure _FuncLog; cdecl;
begin
NPlugin.FuncLog;
end;
procedure _FuncExecSQL; cdecl;
begin
NPlugin.FuncExecSQL;
end;
{ TdsPlugin }
constructor TdsPlugin.Create;
var
sk: TShortcutKey;
begin
inherited;
PluginName := 'npp.Connections';
AddFuncItem('Show result panel', _FuncLog);
sk.IsCtrl := true; sk.IsAlt := false; sk.IsShift := false;
sk.Key := 69; // 'E'
AddFuncItem('Execute SQL', _FuncExecSQL, sk);
Sci_Send(SCI_SETMODEVENTMASK,SC_MOD_INSERTTEXT or SC_MOD_DELETETEXT,0);
end;
procedure TdsPlugin.DoNppnToolbarModification;
var
tb: TToolbarIcons;
begin
tb.ToolbarIcon := 0;
tb.ToolbarBmp := LoadImage(Hinstance, 'TREE', IMAGE_BITMAP, 0, 0, (LR_DEFAULTSIZE));
Npp_Send(NPPM_ADDTOOLBARICON, WPARAM(self.CmdIdFromDlgId(cnstMainDlgId)), LPARAM(@tb));
tb.ToolbarBmp := LoadImage(Hinstance, 'SQL', IMAGE_BITMAP, 0, 0, (LR_DEFAULTSIZE));
Npp_Send(NPPM_ADDTOOLBARICON, WPARAM(self.CmdIdFromDlgId(cnstMainDlgId+1)), LPARAM(@tb));
end;
procedure TdsPlugin.FuncExecSQL;
var S: string;
N: integer;
begin
if not Assigned(FForm) then
begin
FuncLog;
TconnectionForm(FForm).DoConnect;
end
else
begin
S := SelectedText;
N := Length(S);
if N < 1 then
begin
S := GetText;
N := Length(S);
end;
if N > 1 then
begin
TconnectionForm(FForm).DoSql(S);
end;
end;
end;
procedure TdsPlugin.FuncLog;
begin
if not Assigned(FForm) then FForm := TconnectionForm.Create(self, cnstMainDlgId);
(FForm as TconnectionForm).Carousel;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.Types;
interface
uses System.Generics.Collections, System.Classes, REST.Client, System.JSON;
type
TDetail = TPair<string, string>;
TDetailInt = TPair<string, integer>;
TInstallDetail = record
ID: string;
Token: string;
DeviceType: string;
end;
TUserInfo = record
UserID: string;
UserName: string;
Creator: string;
Created: string;
Details: TArray<TDetail>;
Groups: TStringList;
public const
StaticFileds = 4;
cUserName = 'username';
cID = '_id';
cCreator = 'creator';
cCreated = 'created';
cUserFieldName = 'username';
cUserFieldPass = 'password';
cResource = 'Users';
end;
TGroupInfo = record
GroupName: string;
Creator: string;
Created: string;
Details: TArray<TDetail>;
Users: TStringList;
public const
StaticFileds = 3;
cGroupName = 'groupname';
cCreator = 'creator';
cCreated = 'created';
cResource = 'Groups';
cUsers = 'users';
end;
TInstallationInfo = record
InstallationID: string;
DeviceToken: string;
DeviceType: string;
Creator: string;
Created: string;
Details: TArray<TDetail>;
Channels: TArray<string>;
public const
StaticFileds = 4;
cID = '_id';
cDeviceToken = 'deviceToken';
cDeviceType = 'deviceType';
cMeta = '_meta';
cChannels = 'channels';
cResource = 'Installations';
end;
TEdgeModuleInfo = record
ModuleID: string;
ModuleName: string;
Protocol: string;
ProtocolProps: string;
Creator: string;
Created: string;
Details: TArray<TDetail>;
public const
StaticFileds = 4;
cID = '_id';
cModuleName = 'modulename';
cModuleProtocol = 'protocol';
cModuleProtocolProps = 'protocolprops';
cCreator = 'creator';
cCreated = 'created';
end;
TResourcesInfo = record
ResourceID: string;
ResourceName: string;
ModuleName: string;
ModuleID: string;
EdgePointsID: string;
Creator: string;
Created: string;
Details: TArray<TDetail>;
public const
StaticFileds = 1;
cID = '_id';
cModuleName = 'modulename';
cModuleID = 'moduleid';
cResourceName = 'resourcename';
cCreator = 'creator';
cCreated = 'created';
end;
TChannelsInfo = record
ChannelName: string;
Installations: TList<TInstallDetail>;
end;
TUsersInfoArray = TArray<TUserInfo>;
TGroupsInfoArray = TArray<TGroupInfo>;
TInstallationInfoArray = TArray<TInstallationInfo>;
TChannelsInfoArray = TArray<TChannelsInfo>;
TEdgeModulesInfoArray = TArray<TEdgeModuleInfo>;
TResourcesInfoArray = TArray<TResourcesInfo>;
TCell = record
col: integer;
row: integer;
end;
TManagerEndPoints = class
public const
cUsersEndPoint = 'Users';
cGroupsEndPoint = 'Groups';
cInstallationsEndPoint = 'Installations';
cEdgeModulessEndPoint = 'Modules';
cEdgeModulesResourcessEndPoint = 'Resources';
cPush = 'Push';
cSessionID = 'sessionid';
end;
TAdapterJSONValue = class(TInterfacedObject, IRESTResponseJSON)
private
FJSONValue: TJSONValue;
protected
{ IRESTResponseJSON }
procedure AddJSONChangedEvent(const ANotify: TNotifyEvent);
procedure RemoveJSONChangedEvent(const ANotify: TNotifyEvent);
procedure GetJSONResponse(out AJSONValue: TJSONValue;
out AHasOwner: Boolean);
function HasJSONResponse: Boolean;
function HasResponseContent: Boolean;
public
constructor Create(const AJSONValue: TJSONValue);
destructor Destroy; override;
end;
implementation
{ TAdapterJSONValue }
procedure TAdapterJSONValue.AddJSONChangedEvent(const ANotify: TNotifyEvent);
begin
// Not implemented because we pass JSON in constructor and do not change it
end;
constructor TAdapterJSONValue.Create(const AJSONValue: TJSONValue);
begin
FJSONValue := AJSONValue;
end;
destructor TAdapterJSONValue.Destroy;
begin
// We own the JSONValue, so free it.
FJSONValue.Free;
inherited;
end;
procedure TAdapterJSONValue.GetJSONResponse(out AJSONValue: TJSONValue;
out AHasOwner: Boolean);
begin
AJSONValue := FJSONValue;
AHasOwner := True; // We own this object
end;
function TAdapterJSONValue.HasJSONResponse: Boolean;
begin
Result := FJSONValue <> nil;
end;
function TAdapterJSONValue.HasResponseContent: Boolean;
begin
Result := FJSONValue <> nil;
end;
procedure TAdapterJSONValue.RemoveJSONChangedEvent(const ANotify: TNotifyEvent);
begin
// Not implemented because we pass JSON in constructor and do not change it
end;
end.
|
unit UJob;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,Uvar;
type
TFJob = class(TForm)
GroupBox1: TGroupBox;
Memo1: TMemo;
Panel3: TPanel;
Button1: TButton;
Button2: TButton;
Panel1: TPanel;
Label1: TLabel;
Edit1: TEdit;
Panel2: TPanel;
Label2: TLabel;
ComboBox1: TComboBox;
CheckBox1: TCheckBox;
CheckBox2: TCheckBox;
procedure FormShow(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure KeyPressCmdLine(Sender: TObject; var Key: Char);
procedure KeyPressCheckerr(Sender: TObject; var Key: Char);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Memo1Change(Sender: TObject);
procedure Edit1KeyPress(Sender: TObject; var Key: Char);
procedure CheckBox2Click(Sender: TObject);
private
procedure SaveStep;
{ Private declarations }
public
constructor Create(AOwner: TComponent; Job:TrecJob);
var
_Job:TrecJob;
{ Public declarations }
end;
var
FJob: TFJob;
implementation
constructor TFJob.Create(AOwner: TComponent;Job:TrecJob);
begin
inherited Create(AOwner);
_Job:=Job;
end;
{$R *.dfm}
procedure TFJob.SaveStep;
begin
_Job.JobDescription:=Edit1.Text;
_Job.JobStyle:=combobox1.ItemIndex;
_Job.is_trRW:=CheckBox1.Checked;
_Job.is_disabled:=CheckBox2.Checked;
_Job.JobScript:=memo1.Text;
end;
procedure TFJob.Button1Click(Sender: TObject);
begin
SaveStep;
Button1.Enabled:=false;
ModalResult := mrOk;
end;
procedure TFJob.Button2Click(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TFJob.CheckBox2Click(Sender: TObject);
begin
Panel1.Enabled:=not CheckBox2.Checked;
Panel2.Enabled:=not CheckBox2.Checked;
GroupBox1.Enabled:=not CheckBox2.Checked;
button1.Enabled:=true;
end;
procedure TFJob.ComboBox1Change(Sender: TObject);
begin
memo1.OnKeyDown:=nil;
memo1.ReadOnly:=false;
CheckBox1.Checked:=false;
CheckBox1.Visible:=false;
//if memo1.Text<>'' then
//if messageDlg('Очистить поле "Скрипт"?',mtConfirmation,mbOKCancel,0)=mrOk then
memo1.Clear;
case combobox1.ItemIndex of
0,6:memo1.OnKeyPress:=KeyPressCmdLine;
1,2,3:memo1.OnKeyPress:=nil;
4:memo1.OnKeyPress:=KeyPressCheckerr;
{ else
begin
memo1.ReadOnly:=true;
memo1.Text:= _job.Jobs[Integer(ComboBox1.Items.Objects[ComboBox1.ItemIndex])].Steps;
end;}
end;
if combobox1.ItemIndex in [3,4] then
CheckBox1.Visible:=true;
Memo1Change(sender);
end;
procedure TFJob.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if (Key = #13) then
begin
Key:=#0;
Perform(WM_NEXTDLGCTL,0,0);
end;
end;
procedure TFJob.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if button1.Enabled then
if messageDlg('Сохранить?',mtConfirmation,mbYesNo,0)=mrYes then
Button1.Click;
Action:=caFree;
end;
procedure TFJob.FormShow(Sender: TObject);
var
i:integer;
begin
Edit1.Text:=_job.JobDescription;
for i := 0 to length(_job.jobs)-1 do
combobox1.Items.AddObject(_job.jobs[i].Name,Tobject(i));
combobox1.ItemIndex:=_job.JobStyle;
checkbox1.Checked:=_job.is_trRW;
CheckBox2.Checked:=_job.is_disabled;
CheckBox2Click(self);
memo1.Text:=_job.JobScript;
if combobox1.ItemIndex in [3,4] then
checkbox1.Visible:=true;
button1.Enabled:=false;
end;
procedure TFJob.KeyPressCmdLine(Sender: TObject; var Key: Char);
begin
if key=#13 then
key:=#0;
end;
procedure TFJob.KeyPressCheckerr(Sender: TObject; var Key: Char);
var
keyNum:Char;
Num:integer;
begin
keyNum:=key;
if key =#13 then
key:=#0
else if not trystrtoint(keyNum,Num) then
key:=#0;
end;
procedure TFJob.Memo1Change(Sender: TObject);
begin
if (trim(Memo1.Text)<>'')
and (trim(Edit1.Text)<>'')
and (combobox1.ItemIndex>-1)then
button1.Enabled:=true
else
button1.Enabled:=false;
end;
end.
|
unit rhlSHA512Base;
interface
uses
rhlCore;
type
{ TrhlSHA512Base }
TrhlSHA512Base = class abstract(TrhlHash)
private
const s_K: array[0..79] of QWord = (
$428a2f98d728ae22, $7137449123ef65cd, $b5c0fbcfec4d3b2f, $e9b5dba58189dbbc,
$3956c25bf348b538, $59f111f1b605d019, $923f82a4af194f9b, $ab1c5ed5da6d8118,
$d807aa98a3030242, $12835b0145706fbe, $243185be4ee4b28c, $550c7dc3d5ffb4e2,
$72be5d74f27b896f, $80deb1fe3b1696b1, $9bdc06a725c71235, $c19bf174cf692694,
$e49b69c19ef14ad2, $efbe4786384f25e3, $0fc19dc68b8cd5b5, $240ca1cc77ac9c65,
$2de92c6f592b0275, $4a7484aa6ea6e483, $5cb0a9dcbd41fbd4, $76f988da831153b5,
$983e5152ee66dfab, $a831c66d2db43210, $b00327c898fb213f, $bf597fc7beef0ee4,
$c6e00bf33da88fc2, $d5a79147930aa725, $06ca6351e003826f, $142929670a0e6e70,
$27b70a8546d22ffc, $2e1b21385c26c926, $4d2c6dfc5ac42aed, $53380d139d95b3df,
$650a73548baf63de, $766a0abb3c77b2a8, $81c2c92e47edaee6, $92722c851482353b,
$a2bfe8a14cf10364, $a81a664bbc423001, $c24b8b70d0f89791, $c76c51a30654be30,
$d192e819d6ef5218, $d69906245565a910, $f40e35855771202a, $106aa07032bbd1b8,
$19a4c116b8d2d0c8, $1e376c085141ab53, $2748774cdf8eeb99, $34b0bcb5e19b48a8,
$391c0cb3c5c95a63, $4ed8aa4ae3418acb, $5b9cca4f7763e373, $682e6ff3d6b2b8a3,
$748f82ee5defb2fc, $78a5636f43172f60, $84c87814a1f0ab72, $8cc702081a6439ec,
$90befffa23631e28, $a4506cebde82bde9, $bef9a3f7b2c67915, $c67178f2e372532b,
$ca273eceea26619c, $d186b8c721c0c207, $eada7dd6cde0eb1e, $f57d4f7fee6ed178,
$06f067aa72176fba, $0a637dc5a2c898a6, $113f9804bef90dae, $1b710b35131c471b,
$28db77f523047d84, $32caab7b40c72493, $3c9ebe0a15c9bebc, $431d67c49c100d4c,
$4cc5d4becb3e42b6, $597f299cfc657e2a, $5fcb6fab3ad6faec, $6c44198c4a475817);
protected
m_state: array[0..7] of QWord;
procedure UpdateBlock(const AData); override;
public
constructor Create; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlSHA512Base }
procedure TrhlSHA512Base.UpdateBlock(const AData);
var
data: array[0..79] of QWord;
A, B, C, D, E, F, G, H, T0, T1: QWord;
i, t: Integer;
begin
ConvertBytesToQWordsSwapOrder(AData, BlockSize, {%H-}data);
for i := 16 to 79 do
begin
T0 := data[i - 15];
T1 := data[i - 2];
data[i] := (((T1 shl 45) or (T1 shr 19)) xor ((T1 shl 3) or (T1 shr 61)) xor (T1 shr 6)) + data[i - 7] +
(((T0 shl 63) or (T0 shr 1)) xor ((T0 shl 56)or (T0 shr 8)) xor (T0 shr 7)) + data[i - 16];
end;
a := m_state[0];
b := m_state[1];
c := m_state[2];
d := m_state[3];
e := m_state[4];
f := m_state[5];
g := m_state[6];
h := m_state[7];
t := 0;
for i := 0 to 9 do
begin
Inc(h, s_K[t] + data[t] + (((e shl 50) or (e shr 14)) xor ((e shl 46) or (e shr 18)) xor ((e shl 23) or (e shr 41))) + ((e and f) xor (not e and g)));
Inc(t);
Inc(d, h);
Inc(h, (((a shl 36) or (a shr 28)) xor ((a shl 30) or (a shr 34)) xor ((a shl 25) or (a shr 39))) + ((a and b) xor (a and c) xor (b and c)));
Inc(g, s_K[t] + data[t] + (((d shl 50) or (d shr 14)) xor ((d shl 46) or (d shr 18)) xor ((d shl 23) or (d shr 41))) + ((d and e) xor (not d and f)));
Inc(t);
Inc(c, g);
Inc(g, (((h shl 36) or (h shr 28)) xor ((h shl 30) or (h shr 34)) xor ((h shl 25) or (h shr 39))) + ((h and a) xor (h and b) xor (a and b)));
Inc(f, s_K[t] + data[t] + (((c shl 50) or (c shr 14)) xor ((c shl 46) or (c shr 18)) xor ((c shl 23) or (c shr 41))) + ((c and d) xor (not c and e)));
Inc(t);
Inc(b, f);
Inc(f, (((g shl 36) or (g shr 28)) xor ((g shl 30) or (g shr 34)) xor ((g shl 25) or (g shr 39))) + ((g and h) xor (g and a) xor (h and a)));
Inc(e, s_K[t] + data[t] + (((b shl 50) or (b shr 14)) xor ((b shl 46) or (b shr 18)) xor ((b shl 23) or (b shr 41))) + ((b and c) xor (not b and d)));
Inc(t);
Inc(a, e);
Inc(e, (((f shl 36) or (f shr 28)) xor ((f shl 30) or (f shr 34)) xor ((f shl 25) or (f shr 39))) + ((f and g) xor (f and h) xor (g and h)));
Inc(d, s_K[t] + data[t] + (((a shl 50) or (a shr 14)) xor ((a shl 46) or (a shr 18)) xor ((a shl 23) or (a shr 41))) + ((a and b) xor (not a and c)));
Inc(t);
Inc(h, d);
Inc(d, (((e shl 36) or (e shr 28)) xor ((e shl 30) or (e shr 34)) xor ((e shl 25) or (e shr 39))) + ((e and f) xor (e and g) xor (f and g)));
Inc(c, s_K[t] + data[t] + (((h shl 50) or (h shr 14)) xor ((h shl 46) or (h shr 18)) xor ((h shl 23) or (h shr 41))) + ((h and a) xor (not h and b)));
Inc(t);
Inc(g, c);
Inc(c, (((d shl 36) or (d shr 28)) xor ((d shl 30) or (d shr 34)) xor ((d shl 25) or (d shr 39))) + ((d and e) xor (d and f) xor (e and f)));
Inc(b, s_K[t] + data[t] + (((g shl 50) or (g shr 14)) xor ((g shl 46) or (g shr 18)) xor ((g shl 23) or (g shr 41))) + ((g and h) xor (not g and a)));
Inc(t);
Inc(f, b);
Inc(b, (((c shl 36) or (c shr 28)) xor ((c shl 30) or (c shr 34)) xor ((c shl 25) or (c shr 39))) + ((c and d) xor (c and e) xor (d and e)));
Inc(a, s_K[t] + data[t] + (((f shl 50) or (f shr 14)) xor ((f shl 46) or (f shr 18)) xor ((f shl 23) or (f shr 41))) + ((f and g) xor (not f and h)));
Inc(t);
Inc(e, a);
Inc(a, (((b shl 36) or (b shr 28)) xor ((b shl 30) or (b shr 34)) xor ((b shl 25) or (b shr 39))) + ((b and c) xor (b and d) xor (c and d)));
end;
Inc(m_state[0], a);
Inc(m_state[1], b);
Inc(m_state[2], c);
Inc(m_state[3], d);
Inc(m_state[4], e);
Inc(m_state[5], f);
Inc(m_state[6], g);
Inc(m_state[7], h);
end;
constructor TrhlSHA512Base.Create;
begin
BlockSize := 128;
end;
procedure TrhlSHA512Base.Final(var ADigest);
var
lowBits, hiBits: QWord;
pad: TBytes;
padIndex: QWord;
pdigest: PByte;
pstate: PByte;
begin
lowBits := FProcessedBytes shl 3;
hiBits := FProcessedBytes shr 61;
if FBuffer.Pos < 112 then
padIndex := 111 - FBuffer.Pos
else
padIndex := 239 - FBuffer.Pos;
Inc(padindex);
SetLength(pad, padIndex + 16);
pad[0] := $80;
lowBits := SwapEndian(lowBits);
hiBits := SwapEndian(hiBits);
Move(hiBits, pad[padIndex], SizeOf(hiBits));
Inc(padIndex, 8);
Move(lowBits, pad[padIndex], SizeOf(lowBits));
Inc(padIndex, 8);
UpdateBytes(pad[0], padIndex);
ConvertQWordsToBytesSwapOrder(m_state, HashSize div SizeOf(QWord), ADigest);
padIndex := HashSize mod SizeOf(QWord);
if padIndex = 4 then // SHA512_224 3*QWord + 1*DWord
begin
pdigest := @ADigest;
pstate := @m_state;
Inc(pdigest, HashSize - padIndex);
Inc(pstate, HashSize);
ConvertDWordsToBytesSwapOrder(pstate^, 1, pdigest^);
end;
end;
end.
|
unit untEasyDesignerPageControlReg;
{$I cxVer.inc}
interface
procedure DesignerPageControlRegister;
implementation
uses
{$IFDEF DELPHI6}
DesignEditors, DesignIntf, DesignMenus,
{$ELSE}
DsgnIntf, Menus,
{$ENDIF}
Classes, Forms, SysUtils, dxCore, cxPC, cxPCConsts, cxPCPaintersFactory,
dxCoreReg, cxLibraryReg;
const
cxPCMajorVersion = '2';
cxPCProductName = 'ExpressPageControl Suite';
cxPageControlComponentEditorVerbA: array[0 .. 3] of string = (
'New Page',
'Next Page',
'Previous Page',
'Delete Page'
);
type
{ TcxPCStyleProperty }
TcxPCStyleProperty = class(TOrdinalProperty)
private
class procedure OutError(SourceMethodName, Msg: string);
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TcxTabControlComponentEditor }
TcxTabControlComponentEditor = class(TdxComponentEditor)
protected
function GetProductMajorVersion: string; override;
function GetProductName: string; override;
end;
{ TcxPageControlActivePageProperty }
TcxPageControlActivePageProperty = class(TComponentProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValues(Proc: TGetStrProc); override;
end;
{ TcxPageControlComponentEditor }
TcxPageControlComponentEditor = class(TcxTabControlComponentEditor)
private
function GetPageControl: TcxPageControl;
protected
function InternalGetVerb(AIndex: Integer): string; override;
function InternalGetVerbCount: Integer; override;
procedure InternalExecuteVerb(AIndex: Integer); override;
procedure AddPage;
procedure NextPage(GoForward: Boolean);
property PageControl: TcxPageControl read GetPageControl;
public
procedure Edit; override;
procedure PrepareItem(Index: Integer; const AItem: TDesignMenuItem); override;
end;
{ TcxPCStyleProperty }
function TcxPCStyleProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paRevertable, paSortList, paValueList];
end;
function TcxPCStyleProperty.GetValue: string;
begin
Result := GetPCStyleName(GetOrdValue);
end;
procedure TcxPCStyleProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
begin
Proc(cxPCDefaultStyleName);
for I := 0 to PaintersFactory.PainterClassCount - 1 do
Proc(PaintersFactory.PainterClasses[I].GetStyleName);
end;
class procedure TcxPCStyleProperty.OutError(SourceMethodName, Msg: string);
begin
raise EdxException.Create('TcxPCStyleProperty.' + SourceMethodName + ': ' + Msg);
end;
procedure TcxPCStyleProperty.SetValue(const Value: string);
var
PainterClass: TcxPCPainterClass;
begin
if Value = cxPCDefaultStyleName then
SetOrdValue(cxPCDefaultStyle)
else
begin
PainterClass := PaintersFactory.GetPainterClass(Value);
if PainterClass = nil then
OutError('SetValue', Format(scxPCStyleNameError, [Value]))
else
SetOrdValue(PainterClass.GetStyleID);
end;
end;
{ TcxTabControlComponentEditor }
function TcxTabControlComponentEditor.GetProductMajorVersion: string;
begin
Result := cxPCMajorVersion;
end;
function TcxTabControlComponentEditor.GetProductName: string;
begin
Result := cxPCProductName;
end;
{ TcxPageControlActivePageProperty }
function TcxPageControlActivePageProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList];
end;
procedure TcxPageControlActivePageProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
Component: TComponent;
begin
for I := 0 to Designer.GetRoot.ComponentCount - 1 do
begin
Component := Designer.GetRoot.Components[I];
if (Component.Name <> '') and (Component is TcxTabSheet) and
(TcxTabSheet(Component).PageControl = GetComponent(0)) then
Proc(Component.Name);
end;
end;
{ TcxPageControlComponentEditor }
procedure TcxPageControlComponentEditor.Edit;
begin
end;
procedure TcxPageControlComponentEditor.PrepareItem(Index: Integer;
const AItem: TDesignMenuItem);
begin
inherited PrepareItem(Index, AItem);
if (Index > 0) and (Index < GetVerbCount - 3) then
if Index < 3 then
AItem.Enabled := PageControl.PageCount > 1
else
AItem.Enabled := Component is TcxTabSheet;
end;
function TcxPageControlComponentEditor.InternalGetVerb(AIndex: Integer): string;
begin
Result := cxPageControlComponentEditorVerbA[AIndex];
end;
function TcxPageControlComponentEditor.InternalGetVerbCount: Integer;
begin
Result := Length(cxPageControlComponentEditorVerbA);
end;
procedure TcxPageControlComponentEditor.InternalExecuteVerb(AIndex: Integer);
begin
case AIndex of
0: AddPage;
1: NextPage(True);
2: NextPage(False);
3: if (PageControl.ActivePage <> nil) then
begin
Designer.SelectComponent(PageControl);
PageControl.ActivePage.Free;
end;
end;
end;
procedure TcxPageControlComponentEditor.AddPage;
var
Page: TcxTabSheet;
begin
Page := TcxTabSheet.Create(Designer.GetRoot);
Page.Name := Designer.UniqueName(TcxTabSheet.ClassName);
Page.PageControl := PageControl;
Page.ImageIndex := Page.TabIndex;
PageControl.ActivePage := Page;
Designer.SelectComponent(Page);
end;
procedure TcxPageControlComponentEditor.NextPage(GoForward: Boolean);
var
APrevActivePage: TcxTabSheet;
begin
APrevActivePage := PageControl.ActivePage;
PageControl.SelectNextPage(GoForward, False);
if PageControl.ActivePage <> APrevActivePage then
Designer.SelectComponent(PageControl.ActivePage);
end;
function TcxPageControlComponentEditor.GetPageControl: TcxPageControl;
begin
if Component is TcxPageControl then
Result := TcxPageControl(Component)
else
Result := TcxTabSheet(Component).PageControl;
end;
procedure DesignerPageControlRegister;
begin
{$IFDEF DELPHI9}
ForceDemandLoadState(dlDisable);
{$ENDIF}
RegisterComponents('Easy LayOut', [TcxTabControl, TcxPageControl]);
RegisterComponentEditor(TcxTabControl, TcxTabControlComponentEditor);
RegisterComponentEditor(TcxPageControl, TcxPageControlComponentEditor);
RegisterComponentEditor(TcxTabSheet, TcxPageControlComponentEditor);
RegisterPropertyEditor(TypeInfo(TcxPCStyleID), nil, '', TcxPCStyleProperty);
RegisterPropertyEditor(TypeInfo(TcxTabSheet), TcxPageControl, 'ActivePage', TcxPageControlActivePageProperty);
RegisterClass(TcxTabSheet);
end;
initialization
DesignerPageControlRegister;
end.
|
unit ANU_CTR;
(*************************************************************************
DESCRIPTION : Anubis (tweaked) CTR mode functions
Because of buffering en/decrypting is associative
User can supply a custom increment function
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : B.Schneier, Applied Cryptography, 2nd ed., ch. 9.9
REMARKS : - If a predefined or user-supplied INCProc is used, it must
be set before using ANU_CTR_Seek.
- ANU_CTR_Seek may be time-consuming for user-defined
INCProcs, because this function is called many times.
See ANU_CTR_Seek how to provide user-supplied short-cuts.
WARNING : - CTR mode demands that the same key / initial CTR pair is
never reused for encryption. This requirement is especially
important for the CTR_Seek function. If different data is
written to the same position there will be leakage of
information about the plaintexts. Therefore CTR_Seek should
normally be used for random reads only.
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 05.08.08 W.Ehrhardt Initial version analog AES_CTR
0.11 24.11.08 we Uses BTypes
0.12 01.08.10 we Longint ILen in ANU_CTR_En/Decrypt
0.13 02.08.10 we ANU_CTR_Seek, ANU_CTR_Seek64 via anu_seek.inc
*************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2008-2010 Wolfgang Ehrhardt
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from
the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software in
a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
----------------------------------------------------------------------------*)
{$i STD.INC}
interface
uses
BTypes, ANU_Base;
const
DefaultIncMSBPart: boolean = false; {if true use ANU_IncMSBPart as default}
{$ifdef CONST}
function ANU_CTR_Init(const Key; KeyBits: word; const CTR: TANUBlock; var ctx: TANUContext): integer;
{-Anubis key expansion, error if inv. key size, encrypt CTR}
{$ifdef DLL} stdcall; {$endif}
{$else}
function ANU_CTR_Init(var Key; KeyBits: word; var CTR: TANUBlock; var ctx: TANUContext): integer;
{-Anubis key expansion, error if inv. key size, encrypt CTR}
{$endif}
{$ifndef DLL}
function ANU_CTR_Seek({$ifdef CONST}const{$else}var{$endif} iCTR: TANUBlock;
SOL, SOH: longint; var ctx: TANUContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in ANU_CTR_Init.}
{$ifdef HAS_INT64}
function ANU_CTR_Seek64(const iCTR: TANUBlock; SO: int64; var ctx: TANUContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SO >= 0;}
{ iCTR is the initial CTR value for offset 0, i.e. the same as in ANU_CTR_Init.}
{$endif}
{$endif}
function ANU_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
{$ifdef DLL} stdcall; {$endif}
function ANU_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
{$ifdef DLL} stdcall; {$endif}
function ANU_SetIncProc(IncP: TANUIncProc; var ctx: TANUContext): integer;
{-Set user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_IncMSBFull(var CTR: TANUBlock);
{-Increment CTR[15]..CTR[0]}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_IncLSBFull(var CTR: TANUBlock);
{-Increment CTR[0]..CTR[15]}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_IncMSBPart(var CTR: TANUBlock);
{-Increment CTR[15]..CTR[8]}
{$ifdef DLL} stdcall; {$endif}
procedure ANU_IncLSBPart(var CTR: TANUBlock);
{-Increment CTR[0]..CTR[7]}
{$ifdef DLL} stdcall; {$endif}
implementation
{---------------------------------------------------------------------------}
procedure ANU_IncMSBPart(var CTR: TANUBlock);
{-Increment CTR[15]..CTR[8]}
var
j: integer;
begin
for j:=15 downto 8 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure ANU_IncLSBPart(var CTR: TANUBlock);
{-Increment CTR[0]..CTR[7]}
var
j: integer;
begin
for j:=0 to 7 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure ANU_IncMSBFull(var CTR: TANUBlock);
{-Increment CTR[15]..CTR[0]}
var
j: integer;
begin
for j:=15 downto 0 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure ANU_IncLSBFull(var CTR: TANUBlock);
{-Increment CTR[0]..CTR[15]}
var
j: integer;
begin
for j:=0 to 15 do begin
if CTR[j]=$FF then CTR[j] := 0
else begin
inc(CTR[j]);
exit;
end;
end;
end;
{---------------------------------------------------------------------------}
function ANU_SetIncProc(IncP: TANUIncProc; var ctx: TANUContext): integer;
{-Set user supplied IncCTR proc}
begin
ANU_SetIncProc := ANU_Err_MultipleIncProcs;
with ctx do begin
{$ifdef FPC_ProcVar}
if IncProc=nil then begin
IncProc := IncP;
ANU_SetIncProc := 0;
end;
{$else}
if @IncProc=nil then begin
IncProc := IncP;
ANU_SetIncProc := 0;
end;
{$endif}
end;
end;
{---------------------------------------------------------------------------}
{$ifdef CONST}
function ANU_CTR_Init(const Key; KeyBits: word; const CTR: TANUBlock; var ctx: TANUContext): integer;
{$else}
function ANU_CTR_Init(var Key; KeyBits: word; var CTR: TANUBlock; var ctx: TANUContext): integer;
{$endif}
{-Anubis key expansion, error if inv. key size, encrypt CTR}
var
err: integer;
begin
{Anubis key expansion, error if inv. key size}
err := ANU_Init_Encr(Key, KeyBits, ctx);
if (err=0) and DefaultIncMSBPart then begin
{$ifdef FPC_ProcVar}
err := ANU_SetIncProc(@ANU_IncMSBPart, ctx);
{$else}
err := ANU_SetIncProc(ANU_IncMSBPart, ctx);
{$endif}
end;
if err=0 then begin
ctx.IV := CTR;
{encrypt CTR}
ANU_Encrypt(ctx, CTR, ctx.buf);
end;
ANU_CTR_Init := err;
end;
{---------------------------------------------------------------------------}
function ANU_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
begin
ANU_CTR_Encrypt := 0;
if ctx.Decrypt<>0 then begin
ANU_CTR_Encrypt := ANU_Err_Invalid_Mode;
exit;
end;
if (ptp=nil) or (ctp=nil) then begin
if ILen>0 then begin
ANU_CTR_Encrypt := ANU_Err_NIL_Pointer; {nil pointer to block with nonzero length}
exit;
end;
end;
{$ifdef BIT16}
if (ofs(ptp^)+ILen>$FFFF) or (ofs(ctp^)+ILen>$FFFF) then begin
ANU_CTR_Encrypt := ANU_Err_Invalid_16Bit_Length;
exit;
end;
{$endif}
if ctx.blen=0 then begin
{Handle full blocks first}
while ILen>=ANUBLKSIZE do with ctx do begin
{Cipher text = plain text xor encr(CTR), cf. [3] 6.5}
ANU_XorBlock(PANUBlock(ptp)^, buf, PANUBlock(ctp)^);
inc(Ptr2Inc(ptp), ANUBLKSIZE);
inc(Ptr2Inc(ctp), ANUBLKSIZE);
dec(ILen, ANUBLKSIZE);
{use ANU_IncMSBFull if IncProc=nil}
{$ifdef FPC_ProcVar}
if IncProc=nil then ANU_IncMSBFull(IV) else IncProc(IV);
{$else}
if @IncProc=nil then ANU_IncMSBFull(IV) else IncProc(IV);
{$endif}
ANU_Encrypt(ctx, IV, buf);
end;
end;
{Handle remaining bytes}
while ILen>0 do with ctx do begin
{Refill buffer with encrypted CTR}
if bLen>=ANUBLKSIZE then begin
{use ANU_IncMSBFull if IncProc=nil}
{$ifdef FPC_ProcVar}
if IncProc=nil then ANU_IncMSBFull(IV) else IncProc(IV);
{$else}
if @IncProc=nil then ANU_IncMSBFull(IV) else IncProc(IV);
{$endif}
ANU_Encrypt(ctx, IV, buf);
bLen := 0;
end;
{Cipher text = plain text xor encr(CTR), cf. [3] 6.5}
pByte(ctp)^ := buf[bLen] xor pByte(ptp)^;
inc(bLen);
inc(Ptr2Inc(ptp));
inc(Ptr2Inc(ctp));
dec(ILen);
end;
end;
{---------------------------------------------------------------------------}
function ANU_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TANUContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
begin
{Decrypt = encrypt for CTR mode}
ANU_CTR_Decrypt := ANU_CTR_Encrypt(ctp, ptp, ILen, ctx);
end;
{$ifndef DLL}
{$i anu_seek.inc}
{$endif}
end.
|
;----------------------------------------------------------------------
; Fontedit - Loads the current screen font and lets you modify it.
; Saves font in a COM file with integral loader. Requires EGA or VGA.
; Syntax: FONTEDIT [filespec]
; PC Magazine September 13, 1988
;----------------------------------------------------------------------
_TEXT SEGMENT PUBLIC 'CODE'
ASSUME CS:_TEXT,DS:_TEXT
ASSUME ES:_TEXT,SS:_TEXT
ORG 100H
START: JMP MAIN
; DATA AREA
; ---------
DB CR,SPACE,SPACE,SPACE,CR,LF
COPYRIGHT DB "FONTEDIT 1.0 (C) 1988 Ziff Communications Co. ",BOX
PROGRAMMER1 DB " Akira Electronic Magazine ",BOX," MuadDib & Supreme Being",0,CTRL_Z
CR EQU 13
LF EQU 10
CTRL_Z EQU 26
SPACE EQU 32
BOX EQU 254
ESC_SCAN EQU 1
ENTER_SCAN EQU 1CH
UP_ARROW EQU 48H
DN_ARROW EQU 50H
LEFT_ARROW EQU 4BH
RIGHT_ARROW EQU 4DH
Y_SCAN EQU 15H
BS_SCAN EQU 0EH
TAB_CHAR EQU 9
MAX_POINTS EQU 16
PIXEL_OFF EQU 177
PIXEL_ON EQU 219
EDIT_COL EQU 32
EDIT_ROW EQU 8
EDIT_TOP EQU EDIT_ROW SHL 8 + EDIT_COL
TEMPLATE_TOP EQU EDIT_TOP - 28
CHAR_TOP EQU EDIT_TOP + 28
BOX_TOP EQU EDIT_TOP + 1 - 400H
INTENSITY EQU 1000B
MICKEY EQU 20
BUTTONS LABEL WORD
LEFT_BUTTON DB 0
RIGHT_BUTTON DB 0
SHIFT_KEYS EQU 3
SHIFT_STATE DB ?
HORIZONTAL DW 0
VERTICAL DW 0
NORMAL EQU 07H
ATTRIBUTE DB 07H
INVERSE DB 70H
ROWS DB ?
MAX_LINES DW 16
MOUSE_FLAG DB 0
MODIFY_FLAG DB 0
BLANKS DB 0,32,255
FILE_FLAG DB 0
FILE_HANDLE DW ?
FILENAME DW ?
LAST_PIXEL DB ?
;format: reg,value SEQUENCER REGISTERS GRAPHICS CONTROLLER REGISTERS
; MAP MASK MEMORY MODE MODE REG MISC READ MAP SELECT
ACCESS_A000H DB 2,4, 4,7, 5,0, 6,4, 4,2
PROTECT_A000H DB 2,3, 4,3, 5,10H, 6,0AH, 4,0
MENU LABEL BYTE
DB "F1 Del row F2 Ins row F3 Dup row F4 Save $"
MENU1 LABEL BYTE
DB "F5 Copy template char. Tab = select edit/char box"
DB " Use: arrow keys or mouse",CR,LF
DB "Hold Shift key or mouse button to drag. Esc to exit"
DB " Rows displayed = ",CR,LF
DB "Left button = pixel on",CR,LF
DB "Right button = pixel off",CR,LF
DB "Space bar = toggle pixel$"
MENU2 LABEL BYTE
DB "Enter = select char.",0
DB "Button = select char.",0
DB "PgUp/PgDn prev./next char.",0
CAPTIONS DW TEMPLATE_TOP - 2
DB "Template Char",0
DW EDIT_TOP - 2
DB " Edit Char",0
DW CHAR_TOP - 2
DB "Character Set",0
CURRENT_BOX DB 218, 5 DUP (196), 194, 5 DUP (196), 191
DB 179, 5 DUP (SPACE), 179, 5 DUP (SPACE), 179
DB 192, 5 DUP (196), 193, 5 DUP (196), 217
NOT_ENOUGH DB "Not enough memory$"
NOT_SUPPORTED DB "Font too tall$"
NOT_EGA_VGA DB "Ega/Vga not found$"
SAVE_MSG DB CR,LF,"Save ",0
FILE_MSG DB "file",0
CREATE_MSG DB CR,LF,"Create ",0
EXIST_MSG DB CR,LF,"Write over existing ",0
YES_NO DB "? Y/N",0
FAILED_MSG DB CR,LF,"Failed$"
FILENAME_MSG DB CR,LF,"Enter filename",CR,LF,"$"
NOT_FONT_MSG DB " not font$"
COM DB ".COM",0
WARNING_MSG DB LF,"Warning! The cursor row will be deleted in"
DB " EVERY character in this font.",CR,LF,"Continue$"
DISPATCH_KEY DB 1, 4BH, 4DH, 48H, 50H, 49H
DB 51H, 0FH, 39H, 1CH, 3BH, 53H
DB 3CH, 52H, 3DH, 3EH, 3FH
DISPATCH_CNT EQU $ - DISPATCH_KEY
DISPATCH_TABLE DW EXIT, LEFT, RIGHT, UP, DOWN, PGUP
DW PGDN, TAB, SPACE_BAR, ENTER, DEL_ROW, DEL_ROW
DW INS_ROW, INS_ROW, DUP_ROW, SAVE, COPY_TEMP
DISPATCH_END EQU $ - 2
; CODE AREA
; ---------
MAIN PROC NEAR
CLD ;All string operations forward.
MOV BX,1024 ;Allocate 1024 paragraphs; 16K.
MOV AH,4AH
INT 21H
MOV DX,OFFSET NOT_ENOUGH ;Exit with message if not enough.
JC ERROR_MSG
MOV AX,500H ;Make sure zero video page.
INT 10H
MOV AX,40H ;Point to BIOS data area.
MOV ES,AX
MOV AX,1A00H ;Get display info.
INT 10H
CMP AL,1AH ;Function supported?
JNZ CK_EGA ;If no, not VGA; check EGA.
CMP BL,7 ;Else, monochrome VGA?
JZ GET_CRT_MODE ;If yes, OK.
CMP BL,8 ;Else, color VGA?
JZ GET_CRT_MODE ;If yes, OK.
CK_EGA: MOV MAX_LINES,14 ;Else, use 14 max lines for EGA.
MOV BL,10H ;Get EGA information.
MOV AH,12H
INT 10H
MOV DX,OFFSET NOT_EGA_VGA
CMP BL,10H ;Is there an EGA?
JZ ERROR_MSG ;If no, exit with message.
TEST ES:BYTE PTR [87H],8 ;Is EGA active?
JNZ ERROR_MSG ;If no, exit with message.
GET_CRT_MODE: MOV BL,ES:[49H] ;Retrieve CRT_MODE.
CALL INFORMATION ;Get font information.
MOV DX,OFFSET NOT_SUPPORTED
CMP CX,MAX_POINTS ;Font greater than 16 points?
JBE CK_MODE ;If no, OK.
ERROR_MSG: CALL PRINT_STRING ;Print error message.
ERROR_EXIT: MOV AL,1 ;ERRORLEVEL = 1
JMP TERMINATE ;Exit.
CK_MODE: CMP BL,7 ;CRT_MODE mono?
JZ SAVE_MODE ;If yes, skip.
MOV BYTE PTR PROTECT_A000H + 7,0EH ;Else, change parameter.
CMP BL,2 ;Is mode BW80?
JZ SAVE_MODE ;If yes, defaults.
MOV ATTRIBUTE,17H ;Else, use color attributes.
MOV INVERSE,71H
CMP BL,3 ;Are we in CO80?
JZ SAVE_MODE ;If yes, done here.
MOV AX,3 ;Else, change to CO80.
INT 10H
MOV BL,3
SAVE_MODE: MOV CRT_MODE,BL ;Save CRT_MODE in loader.
CALL SETUP ;Setup the display.
;************************** MAIN LOOP **************************;
; User input dispatcher. AH = ASCII character; AL = Scan Code. ;
;***************************************************************;
INPUT: CALL HIDE_CURSOR ;Park cursor off screen.
CALL GET_INPUT ;Get some input from user.
CMP BUTTONS,0 ;Was a mouse button pressed?
JZ CK_ASCII ;If no, check keyboard input.
CALL BUTTON_PRESS ;Else, process button press.
JMP SHORT INPUT ;Next input.
CK_ASCII: OR AL,AL ;Scan code zero?
JZ ALT_INPUT ;If yes, ALT keypad entry.
MOV DI,OFFSET DISPATCH_KEY ;Else, check dispatch table.
MOV CX,DISPATCH_CNT
REPNZ SCASB
JNZ ALT_INPUT ;If no match, keyboard char.
SHL CX,1 ;Else, look up subroutine
MOV DI,OFFSET DISPATCH_END
SUB DI,CX
CALL [DI] ; and process command.
JMP SHORT INPUT ;Next input.
ALT_INPUT: OR AH,AH ;ASCII zero?
JZ INPUT ;If yes, skip.
MOV EDIT_CHAR,AH ;Else, store as new character.
CALL SETUP_END ;Display new edit character.
JMP SHORT INPUT ;Next input.
;---------------------------------------------------;
; Exit. If font was modified, prompt user to save. ;
;---------------------------------------------------;
EXIT: CALL CLS ;Clear the screen.
CMP MODIFY_FLAG,1 ;Font modified?
JNZ GOOD_EXIT ;If no, return to DOS.
MOV SI,OFFSET FILE_MSG
CMP FILE_FLAG,1 ;If there a filename?
JZ DO_FILE ;If yes, display it.
MOV FILENAME,SI ;Else, display "file".
DO_FILE: MOV SI,OFFSET SAVE_MSG
CALL PROMPT ;Prompt user to save.
JNZ GOOD_EXIT ;If "Y"es not pressed, exit.
CMP FILE_FLAG,1 ;Else, is there a filename?
JZ DO_SAVE ;If yes, save it.
CALL GET_NAME ;Else, get a filename.
JC GOOD_EXIT ;If aborted, exit.
DO_SAVE: CALL SAVE_FILE ;Save the font COM file.
GOOD_EXIT: CALL CLS ;Clear the screen.
XOR AL,AL ;ERRORLEVEL zero.
TERMINATE: MOV AH,4CH ;Return to DOS.
INT 21H
MAIN ENDP
; ***************
; * SUBROUTINES *
; ***************
;-------------------------------------------------------------;
; What follows is the user input command processing routines. ;
;-------------------------------------------------------------;
BUTTON_PRESS: CALL GET_CURSOR ;Is cursor in character box?
JNZ DO_ENTER ;If yes, process as if Enter.
CMP LEFT_BUTTON,0 ;Else, left button press
JZ TURN_OFF ; will turn on pixel.
CALL GET_PIXEL ;Get the pixel.
OR [DI],AH ;Turn it on.
JMP SHORT BUTTON_END
TURN_OFF: CALL GET_PIXEL ;Right button will turn off pixel
XOR AH,0FFH ;Invert bit mask.
AND [DI],AH ;Turn it off.
BUTTON_END: CALL UPDATE_CURSOR ;Update the cursor.
CALL LOAD_CHAR ;Load the character.
RET
;--------------------------------;
ENTER: CALL GET_CURSOR ;Is cursor in character box?
JZ ENTER_END ;If no, ignore.
DO_ENTER: CALL GET_CHAR ;Else, get the highlighted char.
MOV EDIT_CHAR,AL ;Store it as new edit char.
CALL NEW_CHAR ;Display the edit character.
ENTER_END: RET
;--------------------------------;
LEFT: MOV BP,0FFH ;Movement = 0 rows; -1 cols.
JMP SHORT ARROWS
RIGHT: MOV BP,1 ;Movement = 0 rows; +1 cols.
JMP SHORT ARROWS
UP: MOV BP,0FF00H ;Movement = -1 rows; 0 cols.
JMP SHORT ARROWS
DOWN: MOV BP,100H ;Movement = +1 rows; 0 cols.
ARROWS: CALL RESTORE ;Restore current cursor position.
CALL GET_CURSOR ;Cursor in edit box?
MOV CX,BP
JNZ CHAR_ARROW ;If no, do character movement.
ADD CL,CL ;Else, double up col. movement.
CALL CK_BOUNDS ;Move cursor; check the boundary.
SUB AX,EDIT_TOP ;AX has position; make relative.
MOV EDIT_CURSOR,AX ;Store as new edit cursor.
MOV BH,LAST_PIXEL ;Retrieve the last pixel.
CALL GET_PIXEL ;Get pixel in new position.
CMP SHIFT_STATE,0 ;Button or Shift key depressed?
JZ UPDATE_PIXEL2 ;If no, update new cursor pos.
OR BH,BH ;Else, was last pixel on?
JNZ BIT_ON ;If yes, drag to new position.
XOR AH,0FFH ;Else, invert mask
AND BYTE PTR [DI],AH; ; and drag pixel off.
JMP SHORT UPDATE_PIXEL1
BIT_ON: OR BYTE PTR [DI],AH ;Turn the pixel on.
UPDATE_PIXEL1: CALL LOAD_CHAR ;Load the character.
UPDATE_PIXEL2: CALL UPDATE_CURSOR ;Update the cursor display.
RET
;--------------------------------;
CHAR_ARROW: CALL CK_BOUNDS ;Move cursor; check the boundary.
SUB AX,CHAR_TOP ;Convert to relative position.
MOV CHAR_CURSOR,AX ;Store new character box pos.
CMP SHIFT_STATE,0 ;Button or Shift key depressed?
JZ CHAR_END ;If no, done here.
NEW_CHAR: CALL GET_CHAR ;Else, get the character
MOV EDIT_CHAR,AL ; and use as new edit character.
CALL DISPLAY_FONT ;Display it.
CHAR_END: CALL UPDATE_CURSOR ;Update the cursor display.
RET
;--------------------------------;
PGUP: DEC EDIT_CHAR ;Next lower edit character.
JMP SHORT PAGE_END
PGDN: INC EDIT_CHAR ;Next higher edit character.
PAGE_END: CALL SETUP_END ;Display it.
RET
;--------------------------------;
TAB: CALL RESTORE ;Restore current cursor position.
XOR EDIT_FLAG,1 ;Toggle Edit/char active box.
CALL UPDATE_CURSOR ;Display cursor in new box.
RET
;--------------------------------;
SPACE_BAR: CALL GET_CURSOR ;Is cursor in character box?
JNZ SPACE_END ;If yes, ignore.
CALL GET_PIXEL ;Else, get the pixel.
XOR [DI],AH ;Toggle the pixel.
CALL UPDATE_PIXEL1 ;Update character and cursor.
SPACE_END: RET
;--------------------------------;
DEL_ROW: CALL GET_CURSOR ;Is cursor in character box?
JNZ DELETE_RETURN ;If yes, ignore.
MOV BP,POINTS ;Else, retrieve scan line points.
CMP BP,1 ;Is there only one scan line?
JZ DELETE_RETURN ;If yes, ignore.
MOV AL,AH ;Else, delete position equals
XOR AH,AH ; POINTS - relative ROW.
SUB BP,AX
CALL CLEAR_MENU ;Clear part of the menu and
MOV DX,OFFSET WARNING_MSG ; display warning message.
CALL PRINT_STRING
CALL QUERY ;Should we delete?
JNZ DELETE_END ;If no, done here.
MOV BX,POINTS ;Else, retrieve bytes/char.
MOV SI,OFFSET EDIT_FONT ;Delete edit font.
CALL DELETE
MOV SI,OFFSET TEMPLATE_FONT ;Do same to template font.
CALL DELETE
DEC BX ;One less byte/char.
MOV BH,BL
CMP BYTE PTR EDIT_CURSOR + 1,BL ;Was last row deleted?
JNZ LOAD_IT ;If no, OK.
DEC BL ;Else, move cursor up one
MOV BYTE PTR EDIT_CURSOR + 1,BL ; row so it's on new char.
LOAD_IT: MOV BP,OFFSET EDIT_FONT
CALL USER_LOAD ;Load the new font.
CALL INFORMATION ;Get font information.
MOV MODIFY_FLAG,1 ;Note that font's been modified.
CALL CLS ;Clear the old display.
DELETE_END: XOR DX,DX
CALL SET_CURSOR
CALL DISPLAY_COPY ;Display new font.
DELETE_RETURN: RET
;-----------------;
DELETE: MOV DI,SI ;Destination starts at source.
MOV CX,256 ;256 characters to do.
NEXT_DELETE: PUSH CX ;Save character count.
MOV CX,BX ;BX has bytes/character.
CK_SKIP: CMP CX,BP ;Is this the row to delete?
JZ SKIP_ROW ;If yes, skip it.
MOVSB ;Else, move it down.
JMP SHORT LOOP_DELETE
SKIP_ROW: INC SI ;Skip deletion row.
LOOP_DELETE: LOOP CK_SKIP ;Do all character rows.
POP CX
LOOP NEXT_DELETE ;Do all 256 characters.
RET
;--------------------------------;
INS_ROW: XOR BL,BL ;Insert a zero byte.
JMP SHORT INS_EDIT
;--------------------------------;
DUP_ROW: MOV BL,-1 ;Insert a duplicate byte.
INS_EDIT: CALL GET_CURSOR ;Is cursor in character box?
JNZ INSERT_END ;If yes, ignore.
MOV BH,AH ;Row to be inserted.
INC BH ;Adjust.
MOV BP,POINTS ;Retrieve bytes/char.
CMP BP,MAX_LINES ;Character maxed out?
JZ INSERT_END ;If yes, done here.
STD ;Else, backward moves.
MOV SI,OFFSET EDIT_FONT ;Insert a row.
CALL INSERT
MOV SI,OFFSET TEMPLATE_FONT ;Do same to template font.
CALL INSERT
CLD ;String operation back forward.
MOV BX,BP ;Increment bytes/character.
MOV BH,BL
INC BH
MOV BP,OFFSET EDIT_FONT ;Load the new font.
CALL USER_LOAD
CALL INFORMATION ;Get font information.
MOV MODIFY_FLAG,1 ;Note that font's been modified.
CALL SETUP_END ;Display new font.
INSERT_END: RET
;-----------------;
INSERT: MOV AX,BP ;Go to end of font
MOV CX,256 ; (256 * points) - 1
MUL CX
DEC AX
ADD SI,AX
MOV DI,SI
ADD DI,CX ;New font = old font + 256.
NEXT_INSERT: PUSH CX ;Save character count.
MOV CX,BP ;Retrieve bytes/char.
MOVE_BYTE: MOVSB ;Move a byte.
CMP CL,BH ;Is there an insert row?
JNZ LOOP_INSERT
MOV AL,BL ;If yes, assume zero insert.
OR BL,BL ;Is zero to be inserted?
JZ INSERT_IT ;If yes, guessed right.
MOV AL,[SI+1] ;Else, duplicate with byte below.
INSERT_IT: STOSB ;Insert it.
LOOP_INSERT: LOOP MOVE_BYTE ;Do all bytes/char.
POP CX
LOOP NEXT_INSERT ;Do all 256 characters.
RET
;--------------------------------;
COPY_TEMP: CALL GET_PIXEL ;Get index to current char.
MOV DI,SI ;Destination = Source+(16 * 256).
ADD SI,MAX_POINTS * 256
MOV CX,POINTS ;Bytes/character to copy.
REP MOVSB ;Copy them.
CALL SETUP_END ;Update the display.
CALL LOAD_CHAR ;Load the new character.
RET
;--------------------------------;
SAVE: CMP FILE_FLAG,1 ;Is there a filename?
JZ SAVE_IT ;If yes, save it.
CALL CLS ;Else, clear screen.
CALL GET_NAME ;Get a filename.
PUSHF ;Save results.
CALL DISPLAY_HEAD ;Redisplay menu.
POPF ;Retrieve results.
JC SAVE_END ;If user aborted, skip save.
SAVE_IT: CALL SAVE_FILE ;Save the file.
SAVE_END: RET
;*********** END OF COMMAND PROCESSING ROUTINES ***********;
;---------------------------;
; OUTPUT ;
; If Edit cursor, ZF = 1 ;
; If Char cursor, ZF = 0 ;
; DX = cursor position. ;
; AX = relative position. ;
;---------------------------;
GET_CURSOR: MOV AX,EDIT_CURSOR ;Assume edit cursor; retrieve it.
MOV DX,AX ;Cursor position = relative
ADD DX,EDIT_TOP ; position + top left of edit box
CMP EDIT_FLAG,1 ;Are we in edit box?
JZ CURSOR_END ;If yes, guessed right.
MOV AX,CHAR_CURSOR ;Else, retrieve char. cursor.
MOV DX,AX ;Calculate cursor position.
ADD DX,CHAR_TOP
CURSOR_END: RET
;---------------------------------------------------;
; Return highlighted cursor position to background. ;
;---------------------------------------------------;
RESTORE: MOV BL,ATTRIBUTE ;Background attribute.
CALL GET_CURSOR ;Is cursor in character box?
JNZ CHAR_RESTORE ;If yes, restore char box.
CALL GET_PIXEL ;Else, get pixel and write.
CALL WRITE_PIXEL
RET
CHAR_RESTORE: CALL GET_CHAR ;Get character and write.
CALL WRITE_CHAR
RET
;--------------------------------;
; Highlight new cursor position. ;
;--------------------------------;
UPDATE_CURSOR: MOV BL,ATTRIBUTE ;Retrieve background attribute.
OR BL,INTENSITY ;Turn on intensity bit.
CALL GET_CURSOR ;Is cursor in character box?
JNZ DO_CHAR ;If yes, do character cursor.
FONT_CURSOR: CALL GET_PIXEL ;Else, get pixel and write it.
CALL WRITE_PIXEL
RET
DO_CHAR: CALL GET_CHAR ;Retrieve character.
MOV DI,OFFSET BLANKS ;Use inverse video for invisible
MOV CX,3 ; characters 0, 32 and 255.
REPNZ SCASB
JNZ DO_CURSOR
MOV BL,INVERSE
DO_CURSOR: CALL WRITE_CHAR ;Update the character cursor.
RET
;-----------------------------------;
; INPUT ;
; AX = Relative cursor position. ;
; DX = Actual cursor position. ;
; CX = Direction. ;
; ;
; OUTPUT ;
; DX = New cursor position. ;
; AX = New cursor position. ;
; BX preserved. ;
;-----------------------------------;
CK_BOUNDS: ADD DH,CH ;Add row direction
ADD DL,CL ; and column direction.
PUSH BX ;Save BX.
MOV BL,16 ;Use 16 as bounds for char.
CMP EDIT_FLAG,1 ; box bottom.
JNZ CK_LEFT ;Use bytes/char bounds for edit
MOV BX,POINTS ; box bottom.
CK_LEFT: ADD AL,CL ;Add column to relative pos.
JGE CK_RIGHT
ADD DL,16 ;If too far left,
JMP SHORT BOUNDS_END ; wrap to right.
CK_RIGHT: CMP AL,16 ;If too far right,
JB CK_UP
SUB DL,16 ; wrap to left.
CK_UP: ADD AH,CH ;Add row to relative position.
JGE CK_DOWN
ADD DH,BL ;If too far up,
JMP SHORT BOUNDS_END ; wrap to bottom
CK_DOWN: CMP AH,BL ;If too far down,
JB BOUNDS_END ; wrap to top.
MOV DH,EDIT_ROW
BOUNDS_END: MOV AX,DX ;Return copy of cursor position.
POP BX ;Restore BX.
RET
;----------------------------------;
; INPUT ;
; AX = Relative cursor position. ;
; ;
; OUTPUT ;
; AL = character. ;
;----------------------------------;
GET_CHAR: MOV CL,4 ;Character = row * 16 + column.
SHL AH,CL
ADD AL,AH
RET
;-------------------;
; Font information. ;
;-------------------;
INFORMATION: MOV BH,2 ;Get information.
MOV AX,1130H
INT 10H
PUSH CS ;Restore extra segment.
POP ES
MOV POINTS,CX ;Store bytes/character.
MOV ROWS,DL ;Store rows on screen.
RET
;----------------------------------------------------------------;
; Filename is parsed of white space and COM extension tacked on. ;
;----------------------------------------------------------------;
PARSE_FILE: MOV SI,81H ;Point to parameter.
NEXT_PARSE: LODSB ;Get a byte.
CMP AL,SPACE ;Is it leading space?
JZ NEXT_PARSE ;If yes, ignore.
CMP AL,TAB_CHAR ;Is it leading tab?
JZ NEXT_PARSE ;If yes, ignore.
DEC SI ;Adjust pointer.
MOV FILENAME,SI ;Store start of filename.
FIND_END: LODSB ;Get a byte.
CMP AL,SPACE ;Is it space or below?
JBE PARSE_END ;If yes, end of filename.
CMP AL,"a" ;Capitalize.
JB CK_DOT
CMP AL,"z"
JA CK_DOT
AND BYTE PTR [SI-1],5FH
CK_DOT: CMP AL,"." ;Is it a dot?
JNZ FIND_END ;If no, continue.
PARSE_END: MOV DI,SI ;Else, if dot or end of filename
DEC DI ; tack on ".COM".
MOV SI,OFFSET COM
MOV CX,5
REP MOVSB
RET
;-----------------------------;
; OUTPUT ;
; If file exists, CY = 0 ;
; If file not found, CY = 1 ;
;-----------------------------;
OPEN_FILE: MOV DX,FILENAME
MOV AX,3D02H ;Open file for reading, writing.
INT 21H
SAVE_HANDLE: MOV FILE_HANDLE,AX ;Save filehandle.
MOV BX,AX
RET
;------------------------;
; OUTPUT ;
; If successful CY = 0 ;
; If failed CY = 1 ;
;------------------------;
CREATE_FILE: MOV DX,FILENAME
XOR CX,CX ;Create normal file.
MOV AH,3CH
INT 21H
JC CREATE_END
CALL SAVE_HANDLE ;If successful, save filehandle
CALL SAVE_FILE ; and save font file.
CREATE_END: RET
;-----------------------------------------------------------------------;
; Read the parsed file. Check if legitimate font file. Load the font. ;
;-----------------------------------------------------------------------;
READ_FILE: MOV BX,FILE_HANDLE ;Retrieve filehandle.
MOV DX,OFFSET LOADER ;Point to loader.
MOV CX,LOADER_LENGTH ;Bytes to read.
MOV AH,3FH ;Read from disk.
INT 21H
MOV SI,OFFSET PROGRAMMER1 ;Use name as legitimate font
MOV DI,OFFSET PROGRAMMER2 ; file signature.
MOV CX,SIGNATURE_LEN / 2
REPZ CMPSW
JZ READ_END
CALL DISP_FILENAME
MOV DX,OFFSET NOT_FONT_MSG ;If not font file, exit
JMP ERROR_MSG ; with message.
READ_END: MOV FILE_FLAG,1 ;Else, note that filename found.
PUSH BX ;Save filehandle.
MOV BP,OFFSET EDIT_FONT ;Point to font.
MOV BH,BYTE PTR POINTS ;Bytes/character.
CALL USER_LOAD ;Load the font.
CALL INFORMATION ;Get font information.
POP BX ;Retrieve filehandle.
;--------------------------------;
CLOSE_FILE: MOV AH,3EH
INT 21H
RET
;--------------------------------;
SAVE_FILE: CALL OPEN_FILE ;Open the file and write
MOV DX,OFFSET LOADER ; font image and loader to disk.
MOV CX,LOADER_LENGTH
MOV AH,40H
INT 21H
MOV MODIFY_FLAG,0 ;Reset modify flag.
MOV FILE_FLAG,1 ;Note that have a filename.
JMP SHORT CLOSE_FILE
;-------------------------------;
; INPUT ;
; SI = first string to write. ;
; ;
; OUTPUT ;
; If "Y"es pressed, ZF = 1 ;
; Else, ZF = 0 ;
;-------------------------------;
PROMPT: CALL TTY_STRING ;Write preface string.
CALL DISP_FILENAME ;Write filename.
QUERY: MOV SI,OFFSET YES_NO ;Write query string.
CALL TTY_STRING
CALL GET_KEY ;Get a response.
CMP AH,Y_SCAN ;Check if "Y" pressed.
RET
;-------------------------------;
; OUTPUT ;
; If name valid, CY = 0 ;
; If invalid or abort, CY = 1 ;
;-------------------------------;
GET_NAME: MOV DX,OFFSET FILENAME_MSG ;Ask for filename.
CALL PRINT_STRING
MOV DI,81H ;Use PSP's DTA for input.
NEXT_NAME: CALL GET_KEY ;Get a keystroke.
CMP AH,ESC_SCAN ;Esc?
STC
JZ NAME_END ;If yes, abort with CY = 1.
CMP AH,LEFT_ARROW ;Backspace with left arrow
JZ DO_BS ; or backspace key.
CMP AH,BS_SCAN
JZ DO_BS
CMP AH,ENTER_SCAN ;If Enter key, done here.
JZ STORE_BYTE
CMP AL,SPACE ;Ignore space and below.
JBE NEXT_NAME
JMP SHORT STORE_BYTE
DO_BS: DEC DI ;TTY Backspace = the characters
MOV AL,8 ; 8, space and 8.
PUSH AX
CALL WRITE_TTY
MOV AL,SPACE
CALL WRITE_TTY
POP AX
JMP SHORT DISPLAY_BYTE
STORE_BYTE: STOSB
CMP AH,ENTER_SCAN ;Done if Enter.
JZ PARSE_IT
DISPLAY_BYTE: CALL WRITE_TTY ;Echo input to screen.
JMP SHORT NEXT_NAME
PARSE_IT: CALL PARSE_FILE ;Parse the filename.
CALL OPEN_FILE ;See if it exists.
JC CREATE_IT ;If no, create it.
MOV SI,OFFSET EXIST_MSG ;Else, ask if should write
CALL PROMPT ; over existing file.
JNZ GET_NAME
CREATE_IT: CALL CREATE_FILE ;Create the file.
JNC NAME_END
MOV DX,OFFSET FAILED_MSG ;If failed, inform user
CALL PRINT_STRING ; and ask for new filename.
JMP SHORT GET_NAME
NAME_END: RET
;--------------------------------------;
; OUTPUT ;
; AH = Bit mask ;
; AL = PIXEL_ON or PIXEL_OFF ;
; SI = Pointer to start of Character ;
; DI = Pointer to start of Scan Line ;
; PIXEL = 0 or -1 ;
;--------------------------------------;
GET_PIXEL: MOV SI,OFFSET EDIT_FONT ;Point to start of edit font.
CALL CHAR_START ;Index to current character.
MOV DI,SI ;Also into DI.
MOV CX,EDIT_CURSOR ;Retrieve edit cursor.
SHR CL,1 ;Two col/bit so divide by two.
MOV AH,10000000B ;Bit starts in most significant.
SHR AH,CL ;Shift bit to column position.
MOV CL,CH ;Row in CL.
XOR CH,CH ;Zero in high half.
ADD DI,CX ;Add to character start.
MOV CL,[DI] ;Retrieve the current byte.
MOV AL,PIXEL_OFF ;Assume it is off.
MOV LAST_PIXEL,0
AND CL,AH ;AND with bit mask.
JZ END_PIXEL ;If off, guessed right.
MOV AL,PIXEL_ON ;Else, pixel is on.
MOV LAST_PIXEL,-1
END_PIXEL: RET
;--------------------------------;
WRITE_PIXEL: CALL WRITE_CHAR ;Two characters/pixel.
INC DL
CALL WRITE_CHAR
INC DL
RET
;----------------------------;
; INPUT ;
; SI = Font start. ;
; ;
; OUTPUT ;
; AX = Edit character. ;
; SI = Start of character. ;
;----------------------------;
CHAR_START: MOV CX,POINTS ;Retrieve bytes/character.
MOV AL,EDIT_CHAR ;Retrieve edit character.
XOR AH,AH ;Zero in high half.
PUSH AX ;Preserve character.
MUL CL ;Char start = bytes/char * char.
ADD SI,AX ;Add to index.
POP AX ;Retrieve character.
RET
;--------------------------------------------;
; OUTPUT ;
; AH = ASCII character. ;
; AL = Scan code. ;
; BUTTONS = button pressed. ;
; SHIFT_STATE = Shift or button depressed. ;
;--------------------------------------------;
GET_INPUT: XOR BP,BP ;Store input in BP; start with 0.
MOV SHIFT_STATE,0 ;Zero in Shift state.
MOV BUTTONS,0 ;Zero in Buttons also.
CMP MOUSE_FLAG,1 ;Is the mouse active?
JNZ CK_KEYBOARD ;If no, skip mouse poll.
XOR BX,BX ;Left button.
MOV AX,5 ;Button press information.
INT 33H
OR SHIFT_STATE,AL ;Store button depressed info.
OR LEFT_BUTTON,BL ;Store button press info.
MOV BX,1 ;Do same for right button.
MOV AX,5
INT 33H
OR RIGHT_BUTTON,BL ;Store button pressed info.
CMP BUTTONS,0 ;Any button pressed?
JNZ INPUT_END ;If yes, done here.
MOUSE_MOTION: MOV AX,0BH ;Read mouse motion.
INT 33H
ADD CX,HORIZONTAL ;Add in last horizontal motion.
ADD DX,VERTICAL ; and last vertical motion.
MOV AX,MICKEY ;Retrieve mouse unit of motion.
MOV SI,RIGHT_ARROW ;Assume right movement.
CMP CX,AX ;Is horizontal > mickey?
JG HORIZ ;If yes, guessed right.
MOV SI,DN_ARROW ;Assume down movement.
CMP DX,AX ;Is vertical > mickey?
JG VERT ;if yes, guessed right.
NEG AX ;Else, negate mickey.
MOV SI,LEFT_ARROW ;Assume left movement.
CMP CX,AX ;Is horizontal < mickey?
JL HORIZ ;If yes, guessed right.
MOV SI,UP_ARROW ;Assume up movement.
CMP DX,AX ;Is vertical < mickey?
JGE STORE_MOTION ;If yes, guessed right.
VERT: SUB DX,AX ;Subtract vertical mickey.
JMP SHORT STORE_SCAN ;Update vertical.
HORIZ: SUB CX,AX ;Subtract horizontal mickey.
STORE_SCAN: MOV BP,SI ;Store scan code in BP.
STORE_MOTION: MOV HORIZONTAL,CX ;Update movements.
MOV VERTICAL,DX
CK_KEYBOARD: MOV AH,2 ;Keyboard Shift state.
INT 16H
AND AL,SHIFT_KEYS ;Mask off all but Shift keys.
OR SHIFT_STATE,AL ;Store Shift state.
MOV AH,1 ;Keystroke status.
INT 16H
JZ STORE_INPUT ;If none available, done here.
CALL GET_KEY ;Else, get keystroke
XCHG AL,AH ;Exchange scan/ASCII code.
JMP SHORT INPUT_END
STORE_INPUT: MOV AX,BP ;Return input in AX
OR AX,AX ;Is there input?
JNZ INPUT_END ;If yes, done here.
CMP BUTTONS,0 ;Is there button pressed?
JNZ INPUT_END ;If yes, done here.
JMP GET_INPUT ;Else, wait until input.
INPUT_END: RET
;--------------------------------;
DISPLAY_FONT: MOV AL,ROWS ;Retrieve rows on screen.
INC AL ;Zero based; adjust.
MOV DX,34EH ;Display at Row 2; Col. 77.
MOV CX,3 ;Three bytes to write.
MOV BL,ATTRIBUTE ;Use background attribute.
CALL DIVIDE ;Display the number.
MOV DX,BOX_TOP + 103H ;Point to inside of info box.
MOV AL,EDIT_CHAR ;Retrieve character.
CALL WRITE_CHAR ;Display it.
ADD DL,7 ;Move to end of number col.
MOV CX,3 ;Three bytes to write.
CALL DIVIDE ;Display the number.
MOV BP,TEMPLATE_TOP ;Display template character.
MOV SI,OFFSET TEMPLATE_FONT
CALL UPDATE_FONT
MOV BP,EDIT_TOP ;Display edit character.
MOV SI,OFFSET EDIT_FONT
UPDATE_FONT: CALL CHAR_START ;Retrieve index to character.
NEXT_LINE: LODSB ;Get a byte.
MOV AH,AL ;Store in AH.
MOV DI,AX ;Store in DI.
PUSH CX ;Preserve bytes/char.
MOV CX,8 ;Eight bits/byte.
MOV DX,BP ;Top left of font display.
NEXT_PIXEL: RCL DI,1 ;Get a bit.
MOV AL,PIXEL_ON ;Assume it's on.
JC DISPLAY_IT ;Did bit end up in carry flag?
MOV AL,PIXEL_OFF ;If no, guessed wrong; pixel off.
DISPLAY_IT: CALL WRITE_PIXEL ;Display the pixel.
LOOP NEXT_PIXEL ;Do all 8 pixels.
ADD BP,100H ;Next display row.
POP CX ;Retrieve bytes/char.
LOOP NEXT_LINE ;Do all rows.
RET
;---------------------------;
; INPUT ;
; Entry point = DIVIDE. ;
; AL = Number to display. ;
; BL = Attribute. ;
; CX = Places to display. ;
; DX = Cursor position. ;
;---------------------------;
NEXT_COUNT: MOV AH,SPACE ;Assume zero.
OR AL,AL ;Is it a zero?
JZ ASCII ;If yes, display space instead.
DIVIDE: MOV BH,10 ;Divisor of ten.
XOR AH,AH ;Zero in high half.
DIV BH ;Divide by ten.
ADD AH,"0" ;Convert to ASCII.
ASCII: XCHG AL,AH ;Remainder in AL.
CALL WRITE_CHAR ;Display it.
XCHG AL,AH ;Back to AH.
DEC DL ;Move back one column.
LOOP NEXT_COUNT ;Display all three bytes.
RET
;---------------------;
; INPUT ;
; AL = Character ;
; BL = Attribute ;
; AX, CX preserved. ;
;---------------------;
WRITE_CHAR: PUSH AX
PUSH CX
CALL SET_CURSOR
MOV CX,1
MOV AH,9 ;Write attribute/character.
INT 10H
POP CX
POP AX
RET
;------------------------------------------------------------------------------;
; The Ega/Vga registers are programmed to access segment A000h where the ;
; fonts are stored. The font is retrieved and registers reset back to normal. ;
;------------------------------------------------------------------------------;
RETRIEVE_FONT: MOV SI,OFFSET ACCESS_A000H ;Point to access parameters.
CALL SET_REGISTERS ;Set the registers.
MOV BX,POINTS ;Retrieve bytes/character.
MOV AX,0A000H ;Point to font segment.
MOV DS,AX
MOV DI,OFFSET EDIT_FONT ;Point to destination.
MOV BP,256 ;256 characters.
XOR DX,DX ;Source starting offset of zero.
NEXT_CHAR: MOV SI,DX ;Point to source.
MOV CX,BX ;Bytes/character.
REP MOVSB ;Retrieve the bytes.
ADD DX,20H ;Next character two paragraphs.
DEC BP ;Do all 256 characters.
JNZ NEXT_CHAR
PUSH CS ;Restore data segment.
POP DS
MOV SI,OFFSET EDIT_FONT ;Copy the edit font to template.
MOV DI,OFFSET TEMPLATE_FONT
MOV CX,MAX_POINTS * 256 / 2
REP MOVSW
MOV SI,OFFSET PROTECT_A000H ;Point to normal parameters.
SET_REGISTERS: MOV CX,2 ;Two sequencer registers.
MOV DX,3C4H ;Indexing register.
CALL NEXT_REGISTER
MOV CX,3 ;Three graphics controller regs.
MOV DL,0CEH ;Indexing registers.
NEXT_REGISTER: LODSB ;Get index.
OUT DX,AL
INC DX
LODSB ;Get value.
OUT DX,AL
DEC DX
LOOP NEXT_REGISTER
RET
;-----------------------------------------------------;
; Similar to RETRIEVE_FONT procedure except character ;
; is uploaded instead of entire font down loaded. ;
;-----------------------------------------------------;
LOAD_CHAR: MOV SI,OFFSET ACCESS_A000H
CLI
CALL SET_REGISTERS
MOV SI,OFFSET EDIT_FONT ;Point to character
CALL CHAR_START ; to upload.
PUSH CX ;Preserve bytes/char.
MOV CL,5 ;32 bytes record for A000h font.
SHL AX,CL ;Index to appropriate character.
MOV DI,AX
POP CX
MOV AX,0A000H ;Point to font segment.
MOV ES,AX
REP MOVSB ;Upload the bytes.
PUSH CS ;Restore extra segment.
POP ES
MOV SI,OFFSET PROTECT_A000H
CALL SET_REGISTERS
STI
MOV MODIFY_FLAG,1 ;Note that font modified.
RET
;--------------------------------;
SET_CURSOR: PUSH AX
XOR BH,BH
MOV AH,2 ;Set cursor position.
INT 10H
POP AX
RET
;--------------------------------;
HIDE_CURSOR: MOV DH,ROWS
INC DH
XOR DL,DL ;Hide cursor one row below
CALL SET_CURSOR ; displayable rows.
RET
;--------------------------------;
CLEAR_MENU: MOV CX,100H ;Row 1; column zero.
MOV DX,34FH ;Row 3; column 79.
JMP SHORT SCROLL
CLS: XOR CX,CX ;Row zero; column zero.
MOV DH,ROWS ;Rows.
MOV DL,79 ;Column 79.
SCROLL: MOV BH,7 ;Attribute.
MOV AX,600H ;Scroll window of active page.
INT 10H
XOR DX,DX
CALL SET_CURSOR
RET
;--------------------------------;
GET_KEY: XOR AH,AH
INT 16H
RET
;--------------------------------;
PRINT_STRING: MOV AH,9
INT 21H
RET
;--------------------------------;
DISP_FILENAME: MOV SI,FILENAME
JMP SHORT TTY_STRING
;-----------------;
DO_WRITE: CALL WRITE_TTY
TTY_STRING: LODSB
OR AL,AL
JNZ DO_WRITE
RET
;-----------------;
WRITE_TTY: MOV AH,0EH
INT 10H
RET
;--------------------------------;
DO_CHAR_ATTR: CALL WRITE_CHAR
INC DL
CHAR_ATTRIB: LODSB
OR AL,AL
JNZ DO_CHAR_ATTR
RET
;--------------------------------;
SETUP: CLI ;No interrupts.
CALL RETRIEVE_FONT ;Retrieve font.
STI ;Interrupts back on.
CMP BYTE PTR DS:[80H],0 ;Command line parameter?
JZ CK_MOUSE ;If no, skip to mouse.
CALL PARSE_FILE ;Else, parse the parameter.
CALL OPEN_FILE ;Try to open the file.
JC CREATE_PROMPT ;If not found, ask to create.
CALL READ_FILE ;Else, read the file.
JMP SHORT CK_MOUSE ;Done here.
CREATE_PROMPT: MOV SI,OFFSET CREATE_MSG ;Display create query.
CALL PROMPT
JZ CREATE ;If got thumbs up, create it.
JMP ERROR_EXIT ;Else, exit.
CREATE: CALL CREATE_FILE ;Create the file.
MOV DX,OFFSET FAILED_MSG ;If failed, exit with message.
JNC CK_MOUSE
JMP ERROR_MSG
CK_MOUSE: XOR AX,AX ;Mouse reset and status.
INT 33H
OR AX,AX ;Is mouse active?
JZ DISPLAY_HEAD ;If no, skip.
MOV MOUSE_FLAG,1 ;Else, flag.
DISPLAY_HEAD: CALL CLS ;Clear the screen.
DISPLAY_COPY: MOV SI,OFFSET COPYRIGHT ;Display copyright in
MOV BL,INVERSE ; inverse video.
CALL CHAR_ATTRIB
MOV DX,100H ;Row 1; column 0.
CALL SET_CURSOR
MOV DX,OFFSET MENU ;Display menu.
CALL PRINT_STRING
CMP FILE_FLAG,1 ;If filename, display it.
JNZ DISPLAY_MENU
CALL DISP_FILENAME
DISPLAY_MENU: MOV DX,200H ;Row 2; column 0.
CALL SET_CURSOR
MOV DX,OFFSET MENU1 ;Display more menu.
CALL PRINT_STRING
MOV SI,OFFSET MENU2
MOV BL,NORMAL
MOV DX,436H
CALL CHAR_ATTRIB
MOV DX,536H
CALL CHAR_ATTRIB
MOV DX,636H
CALL CHAR_ATTRIB
MOV SI,OFFSET CAPTIONS ;Display three captions.
MOV CX,3
NEXT_CAPTION: LODSW
MOV DX,AX ;Caption starting cursor pos.
NEXT_CAP: LODSB
CMP AL,0 ;End of string?
JZ END_CAPTION
CALL WRITE_CHAR ;Write the caption.
INC DH ;Next row.
JMP SHORT NEXT_CAP
END_CAPTION: LOOP NEXT_CAPTION ;Do all three captions.
MOV BL,ATTRIBUTE ;Background attribute.
MOV SI,OFFSET CURRENT_BOX ;Display char/ASCII box.
MOV DX,BOX_TOP ;Starting position.
MOV BP,3 ;Three rows.
NEXT_BOX: MOV CX,13 ;13 characters/row.
NEXT_BOX_CHAR: LODSB
CALL WRITE_CHAR
INC DL ;Next column.
LOOP NEXT_BOX_CHAR
MOV DL,LOW BOX_TOP ;Starting column.
INC DH ;Next row.
DEC BP
JNZ NEXT_BOX
MOV DX,CHAR_TOP ;Display character set.
XOR AL,AL ;Start with ASCII zero.
NEXT_SET: MOV CX,16 ;16 bytes/row.
NEXT_BYTE: CALL WRITE_CHAR
INC AL ;Next character.
JZ SETUP_END
INC DL ;Next row.
LOOP NEXT_BYTE
MOV DL,LOW CHAR_TOP ;Starting column.
INC DH
JMP NEXT_SET
SETUP_END: CALL DISPLAY_FONT ;Display the edit and template.
CALL UPDATE_CURSOR ;Display the cursor.
RET
;**************** FONTLOADER ****************;
; This is the code to load the font and ;
; is followed by the edit and template font ;
;********************************************;
LOADER LABEL BYTE
LOADER_OFFSET EQU 100H - LOADER
JMP BEGINNING
; DATA AREA
; ---------
DB CR,SPACE,SPACE,SPACE,CR,LF
PROGRAMMER2 DB " PC Magazine ",BOX," Michael J. Mefford",0,CTRL_Z
SIGNATURE_LEN EQU $ - PROGRAMMER2
CRT_MODE DB ?
EDIT_CURSOR DW 102H
CHAR_CURSOR DW 401H
EDIT_CHAR DB 65
POINTS DW ?
EDIT_FLAG DB 1
; CODE AREA
; ---------
BEGINNING: MOV AX,500H ;Active page zero
INT 10H
MOV AH,0FH ;Current video state.
INT 10H
MOV DI,OFFSET CRT_MODE + LOADER_OFFSET ;Font CRT_MODE.
MOV AH,[DI]
CMP AL,AH ;Same mode?
JZ LOAD_FONT ;If yes, skip.
MOV AL,AH ;Else, change video mode.
XOR AH,AH
INT 10H
LOAD_FONT: MOV BP,OFFSET EDIT_FONT + LOADER_OFFSET
MOV DI,OFFSET POINTS + LOADER_OFFSET
MOV BH,[DI]
USER_LOAD: MOV CX,256
XOR DX,DX
XOR BL,BL
MOV AX,1110H ;User alpha load.
INT 10H
RET ;Terminate.
;--------------------------------;
EVEN
EDIT_FONT LABEL BYTE
TEMPLATE_FONT EQU EDIT_FONT + MAX_POINTS * 256
LOADER_END EQU TEMPLATE_FONT + MAX_POINTS * 256
LOADER_LENGTH EQU LOADER_END - LOADER
_TEXT ENDS
END START
|
unit UnitMainForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
OleCtrls, SHDocVw, StdCtrls;
type
TMainForm = class(TForm)
WebBrowser: TWebBrowser;
ButtonStart: TButton;
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure ButtonStartClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure WebBrowserDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
private
{ Private declarations }
LastDownloaded : integer;
List : TStringList;
procedure MakeList;
procedure DownloadNext;
public
{ Public declarations }
end;
var
MainForm: TMainForm;
implementation
{$R *.DFM}
//==============================================================================
//==============================================================================
//
// Constructor
//
//==============================================================================
//==============================================================================
procedure TMainForm.FormCreate(Sender: TObject);
begin
List := TStringList.Create;
end;
//==============================================================================
//==============================================================================
//
// Destructor
//
//==============================================================================
//==============================================================================
procedure TMainForm.FormDestroy(Sender: TObject);
begin
List.Free;
end;
//==============================================================================
//==============================================================================
//
// Downloading
//
//==============================================================================
//==============================================================================
procedure TMainForm.MakeList;
var I : integer;
begin
List.Clear;
for I := 20 to 100 do
begin
List.Add( 'on'+IntToStr(I)+'a.gif' );
List.Add( 'on'+IntToStr(I)+'b.gif' );
end;
end;
procedure TMainForm.DownloadNext;
begin
Inc( LastDownloaded );
if LastDownloaded = List.Count then exit;
Label1.Caption := 'http://www.dpb.sk/cespor/abus/'+List[ LastDownloaded ];
WebBrowser.Navigate( 'http://www.dpb.sk/cespor/abus/'+List[ LastDownloaded ] );
end;
//==============================================================================
//==============================================================================
//
// Events
//
//==============================================================================
//==============================================================================
procedure TMainForm.WebBrowserDocumentComplete(Sender: TObject;
const pDisp: IDispatch; var URL: OleVariant);
begin
DownloadNext;
end;
procedure TMainForm.ButtonStartClick(Sender: TObject);
begin
MakeList;
LastDownloaded := -1;
DownloadNext;
end;
end.
|
unit Testdjson;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, Variants, SysUtils, Classes, Dialogs, djson, windows, dateutils,
generics.collections;
type
// Test methods for class TJSON
TestTdJSON = class(TTestCase)
strict private
function loadFile(const AFilename: string): string;
public
published
procedure TestUser;
procedure TestUserList;
procedure TestListInListInList;
procedure TestEmptyList;
procedure TestMovie;
procedure TestUnEscape;
procedure TestEmptyDict;
end;
var
fmt: TFormatSettings;
implementation
uses
madexcept;
function TestTdJSON.loadFile(const AFilename: string): string;
var
jsonFile: TextFile;
text: string;
begin
result := '';
AssignFile(jsonFile, AFilename);
try
Reset(jsonFile);
while not Eof(jsonFile) do
begin
ReadLn(jsonFile, text);
result := result+text;
end;
finally
CloseFile(jsonFile);
end;
end;
procedure TestTdJSON.TestEmptyDict;
begin
try
with TdJSON.Parse(loadFile('test7.json')) do
begin
try
check(_['QueryResponse']['Item'][0]['Name'].AsString = 'Advance', 'Name is not Advance');
check(_['QueryResponse']['Item'][0]['ItemGroupDetail'].Items.Count = 0, 'items.count is not 0');
finally
Free;
end;
end;
with TdJSON.Parse(loadFile('test8.json')) do
begin
try
check(_['results'].Items.Count = 0);
finally
Free;
end;
end;
except
handleException;
raise;
end;
end;
procedure TestTdJSON.TestEmptyList;
begin
try
with TdJSON.Parse(loadFile('test4.json')) do
begin
try
check(IsList = false, 'isList is not false');
check(_['empty'].IsList = true, 'isList is not true');
check(assigned(_['empty'].ListItems) = true, 'ListItems is not assigned');
check(_['empty'].ListItems.count = 0, 'listitems.count is not 0');
finally
Free;
end;
end;
with TdJSON.Parse(loadFile('test5.json')) do
begin
try
check(IsList = true, 'isList is not true');
check(assigned(ListItems) = true, 'listItems is not assigned');
check(ListItems.count = 0, 'listitems.count is not 0');
finally
Free;
end;
end;
except
handleException;
raise;
end;
end;
procedure TestTdJSON.TestListInListInList;
begin
with TdJSON.Parse(loadFile('test3.json')) do
begin
try
check(_[0].IsList = true);
check(_[0][0][0].AsString = 'list in a list in a list');
finally
Free;
end;
end;
end;
procedure TestTdJSON.TestMovie;
begin
try
with TdJSON.Parse(loadFile('test6.json')) do
try
check(_['page'].AsInteger = 1);
check(_['results'][0]['id'].AsInteger = 262543);
check(_['results'][0]['id'].AsString = '262543');
check(_['results'][0]['original_title'].AsString = 'Automata');
check(_['results'][0]['popularity'].AsString = '6.6273989934368');
finally
free;
end;
except
handleException;
raise;
end;
end;
procedure TestTdJSON.TestUnEscape;
begin
with TdJSON.Parse('{"name": "Kurt \u00e6 bc"}') do
try
check(_['name'].AsString = 'Kurt æ bc');
finally
free;
end;
with TdJSON.Parse('{"name": "a \b b"}') do
try
check(_['name'].AsString = 'a '+#8+' b');
finally
free;
end;
with TdJSON.Parse('{"name": "a \n b"}') do
try
check(_['name'].AsString = 'a '+#10+' b');
finally
free;
end;
with TdJSON.Parse('{"name": "a \r b"}') do
try
check(_['name'].AsString = 'a '+#13+' b');
finally
free;
end;
with TdJSON.Parse('{"name": "a \t b"}') do
try
check(_['name'].AsString = 'a '+#9+' b');
finally
free;
end;
with TdJSON.Parse('{"name": "a \f b"}') do
try
check(_['name'].AsString = 'a '+#12+' b');
finally
free;
end;
with TdJSON.Parse('{"name": "\\"}') do
try
check(_['name'].AsString = '\');
finally
free;
end;
end;
procedure TestTdJSON.TestUser;
var
photo, item: TdJSON;
i: integer;
d: double;
begin
try
with TdJSON.Parse(loadFile('test1.json')) do
begin
try
Check(_['username'].AsString = 'thomas', _['username'].AsString + ' is not thomas');
for i in [1,2] do
begin
photo := _['photos'][i-1];
check(photo['title'].AsString = format('Photo %d', [i]), 'title is not '+format('Photo %d', [i]));
check(assigned(photo['urls']));
check(photo['urls']['small'].AsString = format('http://example.com/photo%d_small.jpg', [i]), 'url is not '+format('http://example.com/photo%d_small.jpg', [i]));
check(photo['urls']['large'].AsString = format('http://example.com/photo%d_large.jpg', [i]), 'url is not '+format('http://example.com/photo%d_large.jpg', [i]));
end;
for i in [1,2,3] do
begin
item := _['int_list'][i-1];
check(item.AsInteger = i, format('item value is not %d', [i]));
end;
for i in [1,2,3] do
begin
item := _['str_list'][i-1];
check(item.AsString = inttostr(i), format('item value is not %d', [i]));
end;
check(_['escape_text'].AsString = 'Some "test" \\ \u00e6=æ', format('%s is not Some "test" \\ \u00e6=æ', [_['escape_text'].AsString]));
check(_['escape_path'].AsString = 'C:\test\test.txt', format('%s is not C:\test\test.txt', [_['escape_path'].AsString]));
check(_['nullvalue'].AsString = '', 'nullvalue is not empty');
check(_['nullvalue'].IsNull, 'nullvalue value is not null');
check(_['null_list'].ListItems.Count = 1, format('null_list count is not 1: %d', [_['null_list'].ListItems.Count]));
check(_['emptyList'].ListItems.Count = 0, format('emptyList is not empty: %d', [_['null_list'].ListItems.Count]));
check(_['emptyStringList'].ListItems.Count = 1, format('emptyStringList count is not 1: %d', [_['emptyStringList'].ListItems.Count]));
check(_['list_in_list'][0][0].AsInteger = 1, '_[''list_in_list''][0][0] is not 1');
check(_['list_in_list'][0][1].AsInteger = 2, '_[''list_in_list''][0][1] is not 2');
check(_['list_in_list'][1][0].AsInteger = 3, '_[''list_in_list''][1][0] is not 3');
check(_['list_in_list'][1][1].AsInteger = 4, '_[''list_in_list''][1][1] is not 4');
check(_['bool_true'].AsBoolean, 'bool_true is not true');
check(not _['bool_false'].AsBoolean, 'bool_false is not false');
DebugStr(_['double'].AsDouble);
d := 1.337;
check(_['double'].AsDouble = d, 'double is not 1.337');
finally
Free;
end;
end;
except
handleException;
raise;
end;
end;
procedure TestTdJSON.TestUserList();
var
users: TdJSON;
user: TdJSON;
i: integer;
begin
try
users := TdJSON.Parse(loadFile('test2.json'));
try
check(users.ListItems.Count = 3, format('%d is not 3', [users.ListItems.Count]));
for i in [0,1,2] do
begin
user := users[i];
case i of
0: check(user['username'].AsString = 'thomas', user['username'].AsString+' is not thomas');
1: check(user['name'].AsString = 'Kurt', user['name'].AsString+' is not kurt');
2: check(user['username'].AsString = 'bent', user['username'].AsString+' is not bent');
end;
end;
finally
users.free;
end;
except
handleException;
raise;
end;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTdJSON.Suite);
end.
|
{*******************************************************}
{ }
{ DelphiWebMVC }
{ }
{ 版权所有 (C) 2019 苏兴迎(PRSoft) }
{ }
{*******************************************************}
unit DBBase;
interface
uses
System.SysUtils, System.Classes, 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, Data.DB, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, superobject, System.RegularExpressions;
type
TDBBase = class
private
FFields: string;
FPageKey: string;
function getJSONWhere(JSONwhere: ISuperObject): string;
procedure SetFields(const Value: string);
procedure SetPageKey(const Value: string);
{ Private declarations }
public
condb: TFDConnection;
TMP_CDS: TFDQuery;
dataset: TFDQuery;
property Fields: string read FFields write SetFields; // 用来设置查询时显示那些字段
property PageKey: string read FPageKey write SetPageKey; //分页ID设置 mssql2000 使用
{ Public declarations }
function filterSQL(sql: string): string;
procedure DBlog(msg: string);
procedure StartTransaction(); //启动事务
procedure Commit; //事务提交
procedure Rollback; //事务回滚
function FindByKey(tablename: string; key: string; value: Integer): ISuperObject; overload;
function FindByKey(tablename: string; key: string; value: string): ISuperObject; overload;
function Find(tablename: string; where: string): ISuperObject; overload;
function Find(tablename: string; JSONwhere: ISuperObject): ISuperObject; overload;
function FindFirst(tablename: string; where: string): ISuperObject; overload; virtual;
function FindFirst(tablename: string; JSONwhere: ISuperObject): ISuperObject; overload;
function FindPage(var count: Integer; tablename, order: string; pageindex, pagesize: Integer): ISuperObject; overload;
function FindPage(var count: Integer; tablename, where, order: string; pageindex, pagesize: Integer): ISuperObject; overload;
function FindPage(var count: Integer; tablename: string; JSONWhere: ISuperObject; order: string; pageindex, pagesize: Integer): ISuperObject; overload;
function CDSToJSONArray(cds: TFDQuery; isfirst: Boolean = false): ISuperObject;
function CDSToJSONObject(cds: TFDQuery): ISuperObject;
function Query(sql: string; var cds: TFDQuery): Boolean; overload;
function Query(sql: string): ISuperObject; overload;
function QueryFirst(sql: string): ISuperObject;
function QueryPage(var count: Integer; select, from, order: string; pageindex, pagesize: Integer): ISuperObject; virtual;
function ExecSQL(sql: string): Boolean;
function AddData(tablename: string): TFDQuery;
function EditData(tablename: string; key: string; value: string): TFDQuery;
function DeleteByKey(tablename: string; key: string; value: string): Boolean;
function Delete(tablename: string; JSONwhere: ISuperObject): Boolean; overload;
function Delete(tablename: string; where: string): Boolean; overload;
function TryConnDB(): Boolean;
function closeDB(): Boolean;
constructor Create(dbtype:string);
destructor Destroy; override;
end;
implementation
uses
uConfig, LogUnit;
function TDBBase.AddData(tablename: string): TFDQuery;
var
sql: string;
begin
Result := nil;
if not TryConnDB then
Exit;
if (Trim(tablename) = '') then
Exit;
try
sql := 'select * from ' + tablename + ' where 1=2';
sql := filterSQL(sql);
TMP_CDS.Open(sql);
Fields := '';
TMP_CDS.Append;
Result := TMP_CDS;
except
on e: Exception do
begin
Result := nil;
log(e.ToString);
end;
end;
end;
procedure TDBBase.Commit;
begin
condb.Commit;
end;
procedure TDBBase.Rollback;
begin
condb.Rollback;
end;
procedure TDBBase.StartTransaction;
begin
if not TryConnDB then
Exit;
condb.StartTransaction;
end;
function TDBBase.CDSToJSONArray(cds: TFDQuery; isfirst: Boolean = false): ISuperObject;
var
ja, jo: ISuperObject;
i: Integer;
ret: string;
ftype: TFieldType;
begin
ja := SA([]);
ret := '';
with cds do
begin
First;
while not Eof do
begin
jo := SO();
for i := 0 to Fields.Count - 1 do
begin
ftype := Fields[i].DataType;
if (ftype = ftAutoInc) then
jo.I[Fields[i].DisplayLabel] := Fields[i].AsInteger
else if (ftype = ftInteger) then
jo.I[Fields[i].DisplayLabel] := Fields[i].AsInteger
else if (ftype = ftBoolean) then
jo.B[Fields[i].DisplayLabel] := Fields[i].AsBoolean
else
begin
jo.S[Fields[i].DisplayLabel] := Fields[i].AsString;
end;
end;
ja.AsArray.Add(jo);
if isfirst then
break
else
Next;
end;
end;
Result := ja;
end;
function TDBBase.CDSToJSONObject(cds: TFDQuery): ISuperObject;
var
jo: ISuperObject;
begin
jo := CDSToJSONArray(cds, true);
if jo.AsArray.Length > 0 then
Result := jo.AsArray.O[0]
else
Result := nil;
end;
function TDBBase.closeDB: Boolean;
begin
try
try
condb.Connected := false;
except
on e: Exception do
begin
log(e.ToString);
end;
end;
finally
Result := condb.Connected;
end;
end;
function TDBBase.TryConnDB: Boolean;
begin
try
try
if not condb.Connected then
condb.Connected := true;
except
on e: Exception do
begin
log('数据库连接失败:' + e.ToString);
condb.Connected := False
end;
end;
finally
Result := condb.Connected;
end;
end;
constructor TDBBase.Create(dbtype:string);
begin
condb := TFDConnection.Create(nil);
condb.ConnectionDefName := dbtype;
TMP_CDS := TFDQuery.Create(nil);
TMP_CDS.Connection := condb;
end;
function TDBBase.Delete(tablename: string; JSONwhere: ISuperObject): Boolean;
var
sql: string;
begin
Result := false;
sql := getJSONWhere(JSONwhere);
if (sql <> '') then
begin
sql := 'delete from ' + tablename + ' where 1=1 ' + sql;
Result := ExecSQL(sql);
end;
end;
procedure TDBBase.DBlog(msg: string);
begin
log(msg);
end;
function TDBBase.Delete(tablename, where: string): Boolean;
var
sql: string;
begin
Result := false;
if (where <> '') then
begin
sql := 'delete from ' + tablename + ' where 1=1 ' + where;
Result := ExecSQL(sql);
end;
end;
function TDBBase.DeleteByKey(tablename, key: string; value: string): Boolean;
var
sql: string;
begin
Result := False;
if not TryConnDB then
Exit;
if (Trim(tablename) = '') then
Exit;
if (Trim(key) = '') then
Exit;
if (Trim(value) = '') then
Exit;
try
sql := 'delete from ' + tablename + ' where ' + key + '=' + value;
Result := ExecSQL(sql);
except
on e: Exception do
begin
log(e.ToString);
Result := False;
end;
end;
end;
destructor TDBBase.Destroy;
begin
try
if condb.Connected then
begin
if condb.InTransaction then
condb.Rollback;
condb.Connected := False;
end;
finally
TMP_CDS.SQL.Clear;
TMP_CDS.Close;
FreeAndNil(TMP_CDS);
FreeAndNil(condb);
end;
inherited;
end;
function TDBBase.EditData(tablename, key: string; value: string): TFDQuery;
var
sql: string;
begin
Result := nil;
if not TryConnDB then
Exit;
if (Trim(tablename) = '') then
Exit;
if (Trim(key) = '') then
Exit;
try
sql := 'select * from ' + tablename + ' where ' + key + ' = ' + value;
sql := filterSQL(sql);
TMP_CDS.Open(sql);
Fields := '';
if (not TMP_CDS.IsEmpty) then
begin
TMP_CDS.First;
TMP_CDS.Edit;
Result := TMP_CDS;
end
else
Result := nil;
except
Result := nil;
end;
end;
function TDBBase.ExecSQL(sql: string): Boolean;
begin
Result := False;
if not TryConnDB then
Exit;
try
try
sql := filterSQL(sql);
TMP_CDS.sql.Text := sql;
TMP_CDS.ExecSQL;
Result := true;
except
on e: Exception do
begin
log(e.ToString);
Result := False;
end;
end;
finally
end;
end;
function TDBBase.filterSQL(sql: string): string;
begin
if show_sql then
log(sql);
Result := sql.Replace(';', '').Replace('-', '');
end;
function TDBBase.Query(sql: string): ISuperObject;
var
ja: ISuperObject;
CDS1: TFDQuery;
begin
Result := nil;
if not TryConnDB then
Exit;
try
try
sql := filterSQL(sql);
TMP_CDS.Open(sql);
Fields := '';
ja := CDSToJSONArray(TMP_CDS);
TMP_CDS.Close();
Result := ja;
except
on e: Exception do
begin
log(e.ToString);
end;
end;
finally
// FreeAndNil(CDS1);
end;
end;
function TDBBase.Query(sql: string; var cds: TFDQuery): Boolean;
begin
Result := false;
if not TryConnDB then
Exit;
try
cds.Connection := condb;
sql := filterSQL(sql);
cds.Open(sql);
Fields := '';
Result := true;
except
on e: Exception do
begin
log(e.ToString);
end;
end;
end;
function TDBBase.QueryFirst(sql: string): ISuperObject;
var
CDS: TFDQuery;
begin
Result := nil;
if not TryConnDB then
Exit;
try
try
sql := filterSQL(sql);
TMP_CDS.Open(sql);
Fields := '';
result := CDSToJSONObject(TMP_CDS);
TMP_CDS.Close();
except
on e: Exception do
begin
log(e.ToString);
end;
end;
finally
// FreeAndNil(CDS);
end;
end;
function TDBBase.QueryPage(var count: Integer; select, from, order: string; pageindex, pagesize: Integer): ISuperObject;
begin
end;
procedure TDBBase.SetFields(const Value: string);
begin
FFields := Value;
end;
procedure TDBBase.SetPageKey(const Value: string);
begin
FPageKey := Value;
end;
function TDBBase.Find(tablename, where: string): ISuperObject;
var
sql: string;
begin
Result := nil;
if (Trim(tablename) = '') then
Exit;
if Fields = '' then
Fields := '*';
sql := 'select ' + Fields + ' from ' + tablename + ' where 1=1 ' + where;
Result := Query(sql);
end;
function TDBBase.Find(tablename: string; JSONwhere: ISuperObject): ISuperObject;
var
sql: string;
begin
Result := nil;
sql := getJSONWhere(JSONwhere);
if (sql <> '') then
begin
Result := Find(tablename, sql);
end;
end;
function TDBBase.FindByKey(tablename, key: string; value: Integer): ISuperObject;
begin
Result := FindFirst(tablename, 'and ' + key + ' = ' + IntToStr(value));
end;
function TDBBase.FindByKey(tablename, key, value: string): ISuperObject;
begin
Result := FindFirst(tablename, 'and ' + key + ' = ' + QuotedStr(value));
end;
function TDBBase.FindFirst(tablename, where: string): ISuperObject;
begin
end;
function TDBBase.FindFirst(tablename: string; JSONwhere: ISuperObject): ISuperObject;
var
sql: string;
begin
Result := nil;
sql := getJSONWhere(JSONwhere);
if (sql <> '') then
begin
Result := FindFirst(tablename, sql);
end;
end;
function TDBBase.FindPage(var count: Integer; tablename: string; JSONWhere: ISuperObject; order: string; pageindex, pagesize: Integer): ISuperObject;
var
sql: string;
begin
Result := nil;
sql := getJSONWhere(JSONWhere);
if sql <> '' then
begin
Result := FindPage(count, tablename, sql, order, pageindex, pagesize);
end;
end;
function TDBBase.getJSONWhere(JSONwhere: ISuperObject): string;
var
sql: string;
item: TSuperAvlEntry;
wh: string;
begin
sql := '';
for item in JSONwhere.AsObject do
begin
if item.Value.DataType = stInt then
wh := item.Value.AsString
else
wh := QuotedStr(item.Value.AsString);
sql := sql + ' and ' + item.Name + ' = ' + wh;
end;
Result := sql;
end;
function TDBBase.FindPage(var count: Integer; tablename, where, order: string; pageindex, pagesize: Integer): ISuperObject;
begin
Result := nil;
if (Trim(tablename) = '') then
Exit;
if Fields = '' then
Fields := '*';
Result := QueryPage(count, Fields, tablename + ' where 1=1 ' + where, order, pageindex, pagesize);
end;
function TDBBase.FindPage(var count: Integer; tablename, order: string; pageindex, pagesize: Integer): ISuperObject;
begin
Result := nil;
if (Trim(tablename) = '') then
Exit;
if Fields = '' then
Fields := '*';
Result := QueryPage(count, Fields, tablename, order, pageindex, pagesize);
end;
end.
|
{
Double Commander
-------------------------------------------------------------------------
Terminal options page
Copyright (C) 2006-2016 Alexander Koblov (alexx2000@mail.ru)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
}
unit fOptionsTerminal;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
fOptionsFrame, StdCtrls, ExtCtrls, Buttons, Menus;
type
{ TfrmOptionsTerminal }
TfrmOptionsTerminal = class(TOptionsEditor)
gbRunInTerminalStayOpen: TGroupBox;
lbRunInTermStayOpenCmd: TLabel;
edRunInTermStayOpenCmd: TEdit;
lbRunInTermStayOpenParams: TLabel;
edRunInTermStayOpenParams: TEdit;
gbRunInTerminalClose: TGroupBox;
lbRunInTermCloseCmd: TLabel;
edRunInTermCloseCmd: TEdit;
lbRunInTermCloseParams: TLabel;
edRunInTermCloseParams: TEdit;
gbJustRunTerminal: TGroupBox;
lbRunTermCmd: TLabel;
edRunTermCmd: TEdit;
lbRunTermParams: TLabel;
edRunTermParams: TEdit;
protected
procedure Load; override;
function Save: TOptionsEditorSaveFlags; override;
public
class function GetIconIndex: Integer; override;
class function GetTitle: String; override;
end;
implementation
{$R *.lfm}
uses
uGlobs, uLng;
{ TfrmOptionsTerminal }
procedure TfrmOptionsTerminal.Load;
begin
edRunInTermStayOpenCmd.Text := gRunInTermStayOpenCmd;
edRunInTermStayOpenParams.Text := gRunInTermStayOpenParams;
edRunInTermCloseCmd.Text := gRunInTermCloseCmd;
edRunInTermCloseParams.Text := gRunInTermCloseParams;
edRunTermCmd.Text := gRunTermCmd;
edRunTermParams.Text := gRunTermParams;
end;
function TfrmOptionsTerminal.Save: TOptionsEditorSaveFlags;
begin
gRunInTermStayOpenCmd := edRunInTermStayOpenCmd.Text;
gRunInTermStayOpenParams := edRunInTermStayOpenParams.Text;
gRunInTermCloseCmd := edRunInTermCloseCmd.Text;
gRunInTermCloseParams := edRunInTermCloseParams.Text;
gRunTermCmd := edRunTermCmd.Text;
gRunTermParams := edRunTermParams.Text;
Result := [];
end;
class function TfrmOptionsTerminal.GetIconIndex: Integer;
begin
Result := 24;
end;
class function TfrmOptionsTerminal.GetTitle: String;
begin
Result := rsOptionsEditorTerminal;
end;
end.
|
unit adot.Collections.Maps;
interface
{
Unordered containers:
TMapClass<TKey,TValue> Slightly extended TDictionary<TKey,TValues>
TMap<TKey,TValue> Managed analog of TDictionary<TKey,TValues>
TMultimapClass<TKey,TValue> Multimap implementation based on TDictionary<TKey,TValues>
Ordered containers:
TAATree<TKey,TValue> Implementation of AA-tree
TBinarySearchTree<TKey,TValue> Binary search tree based on TAATree<TKey,TValue>
TOrderedMapClass<TKey,TValue> Ordered map implementation based on TDictionary<TKey,TValues>
}
uses
adot.Types,
adot.Strings,
adot.Collections.Types,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils,
System.Character,
System.StrUtils,
System.Math;
type
{ Class for map. Based on TDictionary and extends it with some features. }
TMapClass<TKey,TValue> = class(TDictionary<TKey,TValue>)
private
protected
FComparerCopy: IEqualityComparer<TKey>; { FDictionary.Comparer is hidden in private section, so we keep copy }
FOwnerships: TDictionaryOwnerships;
procedure KeyNotify(const Key: TKey; Action: TCollectionNotification); override;
procedure ValueNotify(const Value: TValue; Action: TCollectionNotification); override;
function GetOwnsKeys: boolean;
function GetOwnsValues: boolean;
procedure SetOwnsKeys(const Value: boolean);
procedure SetOwnsValues(const Value: boolean);
class function EscapeStrVal(const S: string): string; static;
public
constructor Create(ACapacity: integer = 0; AComparer: IEqualityComparer<TKey> = nil); overload;
constructor Create(const AValues: array of TPair<TKey,TValue>; AComparer: IEqualityComparer<TKey> = nil); overload;
constructor Create(const AValues: TEnumerable<TPair<TKey,TValue>>; AComparer: IEqualityComparer<TKey> = nil); overload;
procedure Add(const AValues: array of TPair<TKey,TValue>); overload;
procedure Add(const AValues: TEnumerable<TPair<TKey,TValue>>); overload;
procedure AddOrSetValue(const AValues: array of TPair<TKey,TValue>); overload;
procedure AddOrSetValue(const AValues: TEnumerable<TPair<TKey,TValue>>); overload;
procedure Remove(const AKeys: array of TKey); overload;
procedure Remove(const AKeys: TEnumerable<TKey>); overload;
function Empty: boolean;
function ToText(const Delimiter: string = #13#10): string;
function ToString: string; override;
property Comparer: IEqualityComparer<TKey> read FComparerCopy;
property OwnsKeys: boolean read GetOwnsKeys write SetOwnsKeys;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
end;
{ Class for map. Based on TDictionary and extends it with some features. }
TMap<TKey,TValue> = record
public
{ Delphi 10.1 Seattle has issues with code generation for overloaded
operators if they are inlined. The issue reported here:
https://quality.embarcadero.com/browse/RSP-15196
For now we have to avoid of using _inline_ methods here. }
type
TPairEnumerator = TMapClass<TKey,TValue>.TPairEnumerator;
TKeyEnumerator = TMapClass<TKey,TValue>.TKeyEnumerator;
TValueEnumerator = TMapClass<TKey,TValue>.TValueEnumerator;
TKeyCollection = TMapClass<TKey,TValue>.TKeyCollection;
TValueCollection = TMapClass<TKey,TValue>.TValueCollection;
private
FMapInt: IInterfacedObject<TMapClass<TKey,TValue>>;
procedure CreateMap(ACapacity: integer = 0; AComparer: IEqualityComparer<TKey> = nil);
function GetReadonly: TMapClass<TKey,TValue>;
function GetReadWrite: TMapClass<TKey,TValue>;
function GetOwnsKeys: boolean;
function GetOwnsValues: boolean;
procedure SetOwnsKeys(const Value: boolean);
procedure SetOwnsValues(const Value: boolean);
function GetCollection: TEnumerable<TPair<TKey, TValue>>;
property ReadOnly: TMapClass<TKey,TValue> read GetReadonly;
property ReadWrite: TMapClass<TKey,TValue> read GetReadWrite;
function GetKeys: TKeyCollection;
function GetValues: TValueCollection;
function GetItem(const Key: TKey): TValue;
procedure SetItem(const Key: TKey; const Value: TValue);
function GetCount: integer;
function GetEmpty: Boolean;
public
procedure Init; overload;
procedure Init(ACapacity: integer; AComparer: IEqualityComparer<TKey> = nil); overload;
procedure Init(const V: array of TPair<TKey,TValue>; ACapacity: integer = 0; AComparer: IEqualityComparer<TKey> = nil); overload;
procedure Init(const V: TEnumerable<TPair<TKey,TValue>>; ACapacity: integer = 0; AComparer: IEqualityComparer<TKey> = nil); overload;
procedure Init(V: TMap<TKey,TValue>; ACapacity: integer = 0; AComparer: IEqualityComparer<TKey> = nil); overload;
function Copy: TMap<TKey,TValue>;
function GetEnumerator: TPairEnumerator;
procedure Add(const Key: TKey; Value: TValue); overload;
procedure Add(const Pair: TPair<TKey, TValue>); overload;
procedure Add(const V: TEnumerable<TPair<TKey, TValue>>); overload;
procedure Add(V: TMap<TKey,TValue>); overload;
procedure Add(const V: array of TPair<TKey, TValue>); overload;
procedure AddOrSetValue(const Key: TKey; Value: TValue); overload;
procedure AddOrSetValue(const Pair: TPair<TKey, TValue>); overload;
procedure AddOrSetValue(const V: TEnumerable<TPair<TKey, TValue>>); overload;
procedure AddOrSetValue(V: TMap<TKey,TValue>); overload;
procedure AddOrSetValue(const V: array of TPair<TKey, TValue>); overload;
procedure Remove(const V: TKey); overload;
procedure Remove(const V: TEnumerable<TKey>); overload;
procedure Remove(const V: array of TKey); overload;
function TryGetValue(const Key: TKey; out Value: TValue): Boolean;
function GetValue(const Key: TKey): TValue;
function GetValueDef(const Key: TKey): TValue;
function ExtractPair(const Key: TKey): TPair<TKey,TValue>;
procedure Clear;
procedure Release; { release underlying object }
procedure TrimExcess;
function ContainsKey(const Key: TKey): Boolean;
function ToArray: TArray<TPair<TKey,TValue>>;
function ToString: string;
function ToText(const Delimiter: string = #13#10): string;
class operator Equal(A,B: TMap<TKey,TValue>): Boolean;
class operator NotEqual(A,B: TMap<TKey,TValue>): Boolean;
property Items[const Key: TKey]: TValue read GetItem write SetItem; default;
property Count: Integer read GetCount;
property Empty: Boolean read GetEmpty;
property Keys: TKeyCollection read GetKeys;
property Values: TValueCollection read GetValues;
property OwnsKeys: boolean read GetOwnsKeys write SetOwnsKeys;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
property Collection: TEnumerable<TPair<TKey, TValue>> read GetCollection;
end;
TContainsCheckType = (cctAll, cctAnyOf);
{ Multimap class. Supports multiple items sharing same key. Keeps items in efficient way.}
TMultimapClass<TKey,TValue> = class(TEnumerableExt<TPair<TKey,TValue>>)
protected
type
TMultimapKey = record
Key: TKey;
Number: integer;
end;
{# TKey can be String for example, so we can't use default comparer for
TMultimapKey record type, we have to implement specific one. }
TMultimapKeyEqualityComparer = class(TEqualityComparer<TMultimapKey>)
private
FKeyComparer: IEqualityComparer<TKey>;
public
constructor Create(AKeyComparer: IEqualityComparer<TKey>);
function Equals(const Left, Right: TMultimapKey): Boolean; overload; override;
function GetHashCode(const Value: TMultimapKey): Integer; overload; override;
end;
public
type
{# Standard containers in Delphi use classes for enumerators.
It is ok when we keep single instance of the class inside, but for multimap we
will have to keep lot of instances (for every key where items enumerator has requested).
To avoid of this we use record type instead of class type. }
TValueEnumerator = record
private
FMultimap: TMultimapClass<TKey,TValue>;
FMultimapKey: TMultimapKey;
function GetCurrent: TValue;
function GetKey: TKey;
public
procedure Init(AMultimap: TMultimapClass<TKey,TValue>; const AKey: TKey);
function MoveNext: Boolean;
property Current: TValue read GetCurrent;
property Key: TKey read GetKey;
{ Returns copy. It allows us to use both syntaxes:
Example 1.
Enum := Multimap.Values['key1'];
while Enum.MoveNext do
Fun(Enum.Current);
Example 2.
for v in Multimap['key1'] do
Fun(v); }
function GetEnumerator: TValueEnumerator;
end;
{# Usually we don't need to use it directly. Use default enumerator for TMultimapClass<> instead.
We have to use class (not record) because we want TMultimapClass to be compatible with TEnumerable
and TEnumerable.DoGetEnumerator returns class TEnumerator<TPair<TKey,TValue>>. }
TPairEnumerator = class(TEnumerator<TPair<TKey, TValue>>)
protected
FCurrentValue: TValueEnumerator;
FInEnumKey: boolean;
FMultimap: TMultimapClass<TKey,TValue>;
FCurrentKey: TDictionary<TKey, integer>.TKeyEnumerator;
function DoGetCurrent: TPair<TKey,TValue>; override;
function DoMoveNext: Boolean; override;
public
constructor Create(const AMultimap: TMultimapClass<TKey,TValue>);
end;
TKeyEnumerator = TDictionary<TKey, integer>.TKeyEnumerator;
TKeyCollection = TDictionary<TKey, integer>.TKeyCollection;
protected
FCount: TDictionary<TKey, integer>;
FValues: TDictionary<TMultimapKey, TValue>;
{ Single instance created by request.
Provides TEnumerable interface to keys (Multimap.Keys.ToArray etc). }
FKeyCollection: TKeyCollection;
function GetTotalValuesCount: integer;
function GetValuesCount(const AKey: TKey):Integer;
function DoGetEnumerator: TEnumerator<TPair<TKey,TValue>>; override;
function GetValuesEnumerator(const AKey: TKey): TValueEnumerator;
function GetKeys: TKeyCollection;
public
constructor Create; overload;
constructor Create(AComparer: IEqualityComparer<TKey>); overload;
constructor Create(const ACollection: TEnumerable<TPair<TKey,TValue>>; AComparer: IEqualityComparer<TKey> = nil); overload;
destructor Destroy; override;
procedure Clear;
procedure Add(const AKey: TKey; const AValue: TValue); overload;
procedure Add(const AKey: TKey; const AValues: TArray<TValue>); overload;
procedure Add(const AKey: TKey; const AValues: TEnumerable<TValue>); overload;
procedure Add(const ACollection: TEnumerable<TPair<TKey,TValue>>); overload;
{ e := m.Values[Key];
while e.MoveNext do
if m.Current=10 then m.RemoveValue(e); }
function Remove(const AKey: TKey):Boolean;
procedure RemoveValue(const AEnum: TValueEnumerator);
procedure RemoveValues(const AKey: TKey; const AValues: TArray<TValue>); overload;
procedure RemoveValues(const AKey: TKey; const AValues: TEnumerable<TValue>); overload;
function ContainsKey(const AKey: TKey): Boolean;
function ContainsKeys(const AKeys: array of TKey; AContainsCheckType: TContainsCheckType = cctAnyOf): Boolean; overload;
function ContainsKeys(const AKeys: TEnumerable<TKey>; AContainsCheckType: TContainsCheckType = cctAnyOf): Boolean; overload;
function ContainsValue(const AKey: TKey; const AValue: TValue; AComparer: IEqualityComparer<TValue> = nil): Boolean;
function ContainsValues(const AKey: TKey; const AValues: TArray<TValue>; AContainsCheckType: TContainsCheckType = cctAnyOf;
AComparer: IEqualityComparer<TValue> = nil): Boolean; overload;
function ContainsValues(const AKey: TKey; const AValues: TEnumerable<TValue>; AContainsCheckType: TContainsCheckType = cctAnyOf;
AComparer: IEqualityComparer<TValue> = nil): Boolean; overload;
{ Enumerator. Example:
p: TPair<string, integer>;
for p in m do
[do something] p.Key / p.Value; }
function GetEnumerator: TPairEnumerator; reintroduce;
function Empty: boolean;
property TotalValuesCount: integer read GetTotalValuesCount;
property ValuesCount[const AKey: TKey]:integer read GetValuesCount;
{ Enumerator of values for specific Key. Returns records, ne need to destroy.
Example 1:
Enum := m.Values['test'];
While Enum.MoveNext do
if Enum.Current=314 then m.RemoveValue(Enum);
Example 2:
for s in m.Values['test'] do
<do something with s> }
property Values[const AKey: TKey]: TValueEnumerator read GetValuesEnumerator; default;
{ Enumerator of the keys. For example we can enumerate all values this way
(alternative to default enumerator):
for Key in m.Keys do
for Value in m.Values[Key] do }
property Keys: TKeyCollection read GetKeys;
end;
{# Balanced binary search tree (BST). The performance of an AA tree is equivalent to the performance of a red-black tree.
http://en.wikipedia.org/wiki/AA_tree }
TSearchType = (stAll, stAny);
TItemHandle = NativeInt;
TAATree<TKey,TValue> = class(TEnumerableExt<TPair<TKey,TValue>>)
private
protected
type
{ We use allocation of items by AllocMem, no extra initialization is needed }
P_AATreeItem = ^T_AATreeItem;
T_AATreeItem = record
Parent, Left, Right: P_AATreeItem;
Level: integer;
Data: TPair<TKey, TValue>;
end;
TPairEnumerator = class(TEnumerator<TPair<TKey,TValue>>)
protected
[Weak] FTree: TAATree<TKey,TValue>;
FCurrentItem: TItemHandle;
function DoMoveNext: Boolean; override;
function DoGetCurrent: TPair<TKey,TValue>; override;
public
constructor Create(const ATree: TAATree<TKey,TValue>);
end;
TKeyEnumerator = class(TEnumerator<TKey>)
protected
[Weak] FTree: TAATree<TKey,TValue>;
FCurrentItem: TItemHandle;
function DoMoveNext: Boolean; override;
function DoGetCurrent: TKey; override;
public
constructor Create(const ATree: TAATree<TKey,TValue>);
end;
TValueEnumerator = class(TEnumerator<TValue>)
protected
[Weak] FTree: TAATree<TKey,TValue>;
FCurrentItem: TItemHandle;
function DoMoveNext: Boolean; override;
function DoGetCurrent: TValue; override;
public
constructor Create(const ATree: TAATree<TKey,TValue>);
end;
TKeyCollection = class(TEnumerableExt<TKey>)
protected
[Weak] FTree: TAATree<TKey,TValue>;
function DoGetEnumerator: TEnumerator<TKey>; override;
public
constructor Create(const ATree: TAATree<TKey,TValue>);
end;
TValueCollection = class(TEnumerableExt<TValue>)
protected
[Weak] FTree: TAATree<TKey,TValue>;
function DoGetEnumerator: TEnumerator<TValue>; override;
public
constructor Create(const ATree: TAATree<TKey,TValue>);
end;
var
FCount: integer;
FRoot, FBottom, FDeleted, FLast: P_AATreeItem;
FComparer: IComparer<TKey>;
FKeyCollection: TKeyCollection;
FValueCollection: TValueCollection;
FOnKeyNotify: TCollectionNotifyEvent<TKey>;
FOnValueNotify: TCollectionNotifyEvent<TValue>;
function AllocNewItem: P_AATreeItem;
procedure ReleaseItem(p: P_AATreeItem);
function PtrToHandle(p: P_AATreeItem): TItemHandle;
function HandleToPtr(p: TItemHandle): P_AATreeItem;
function DoGetEnumerator: TEnumerator<TPair<TKey,TValue>>; override;
function GetKeyCollection: TKeyCollection;
function GetValueCollection: TValueCollection;
procedure KeyNotify(const Key: TKey; Action: TCollectionNotification); virtual;
procedure ValueNotify(const Value: TValue; Action: TCollectionNotification); virtual;
procedure treeSkew(var p: P_AATreeItem);
procedure treeSplit(var p: P_AATreeItem);
function treeAdd(p,aparent: P_AATreeItem; var Dst: P_AATreeItem): Boolean;
function treeGetHeight(p: P_AATreeItem): integer;
function treeFullHeight: integer;
function treeMin(p: P_AATreeItem): P_AATreeItem;
function treeMax(p: P_AATreeItem): P_AATreeItem;
function treeSuccessor(p: P_AATreeItem): P_AATreeItem;
function treePredecessor(p: P_AATreeItem): P_AATreeItem;
procedure treeClear(p: P_AATreeItem);
function treeDelete(x: P_AATreeItem; var t: P_AATreeItem): boolean;
function treeFind(const AKey: TKey): P_AATreeItem;
procedure treeMove(Src, Dst: P_AATreeItem);
procedure treeReplace(Src, Dst: P_AATreeItem);
function GetKey(AHandle: TItemHandle): TKey;
function GetValue(AHandle: TItemHandle): TValue;
procedure SetValue(AHandle: TItemHandle; const AValue: TValue);
function GetValueByKey(const AKey: TKey): TValue;
procedure SetValueByKey(const AKey: TKey; const AValue: TValue);
function GetPair(AHandle: TItemHandle): TPair<TKEy,TValue>;
public
constructor Create; overload;
constructor Create(AComparer: IComparer<TKey>); overload;
constructor Create(const ACollection: TEnumerable<TPair<TKey,TValue>>; AComparer: IComparer<TKey> = nil); overload;
destructor Destroy; override;
function GetEnumerator: TPairEnumerator;
procedure Clear;
function Add(const AKey: TKey; const AValue: TValue): TItemHandle; overload;
procedure Add(const ACollection: TEnumerable<TPair<TKey,TValue>>); overload;
function AddOrSetValue(const AKey: TKey; const AValue: TValue): TItemHandle;
function TryGetValue(const Key: TKey; out Value: TValue): Boolean;
procedure Delete(AHandle: TItemHandle);
procedure Remove(const AKey: TKey); overload;
procedure Remove(const AKeys: TArray<TKey>); overload;
procedure Remove(const AKeys: TEnumerable<TKey>); overload;
function ContainsKey(const Key: TKey): Boolean; overload;
function ContainsKeys(const AKeys: array of TKey; ASearchType: TSearchType = stAll): Boolean; overload;
function ContainsKeys(const AKeys: TEnumerable<TKey>; ASearchType: TSearchType = stAll): Boolean; overload;
function ContainsValue(const Value: TValue; AEqualityComparer: IEqualityComparer<TValue> = nil): Boolean;
function MinKey: TKey;
function MaxKey: TKey;
{ navigate over the tree }
function GetRoot(var ARoot: TItemHandle): Boolean;
function GetLeftChild(AItem: TItemHandle; var AChild: TItemHandle): Boolean;
function GetRightChild(AItem: TItemHandle; var AChild: TItemHandle): Boolean;
function GetParent(AItem: TItemHandle; var AParent: TItemHandle): Boolean;
{ Enumeration of all items from min to max and in reverse order. }
function FindMin: TItemHandle;
function FindMax: TItemHandle;
function Find(const AKey: TKey): TItemHandle;
function First(var AHandle: TItemHandle): Boolean;
function Last(var AHandle: TItemHandle): Boolean;
function Prev(var AHandle: TItemHandle): Boolean;
function Next(var AHandle: TItemHandle): Boolean;
property TreeHeight: integer read treeFullHeight;
property Keys[AHandle: TItemHandle]: TKey read GetKey;
property Values[AHandle: TItemHandle]: TValue read GetValue write SetValue;
property Pairs[AHandle: TItemHandle]: TPair<TKey,TValue> read GetPair;
property Items[const AKey: TKey]: TValue read GetValueByKey write SetValueByKey; default;
property Count: integer read FCount;
property KeyCollection: TKeyCollection read GetKeyCollection;
property ValueCollection: TValueCollection read GetValueCollection;
property OnKeyNotify: TCollectionNotifyEvent<TKey> read FOnKeyNotify write FOnKeyNotify;
property OnValueNotify: TCollectionNotifyEvent<TValue> read FOnValueNotify write FOnValueNotify;
end;
{ Binary search tree. }
TBinarySearchTree<TKey,TValue> = Class(TAATree<TKey,TValue>);
{ We do not expose handle-related functions here. That is why TAATree is slightly
faster, but TOrderedMapClass has interface similar to TDictionary.
Usually TMap is preferred over direct access to TAATree. }
{ Ordered map. }
TOrderedMapClass<TKey,TValue> = class(TEnumerableExt<TPair<TKey,TValue>>)
private
protected
type
TPairEnumerator = TAATree<TKey,TValue>.TPairEnumerator;
TKeyEnumerator = TAATree<TKey,TValue>.TKeyEnumerator;
TValueEnumerator = TAATree<TKey,TValue>.TValueEnumerator;
TKeyCollection = TAATree<TKey,TValue>.TKeyCollection;
TValueCollection = TAATree<TKey,TValue>.TValueCollection;
var
FTree: TAATree<TKey,TValue>;
FOwnerships: TDictionaryOwnerships;
FOnKeyNotify: TCollectionNotifyEvent<TKey>;
FOnValueNotify: TCollectionNotifyEvent<TValue>;
function DoGetEnumerator: TEnumerator<TPair<TKey,TValue>>; override;
function GetKeyCollection: TKeyCollection;
function GetValueCollection: TValueCollection;
function GetCount: integer;
function GetItem(const AKey: TKey): TValue;
function GetTreeHeight: integer;
procedure SetItem(const AKey: TKey; const Value: TValue);
function GetOwnsKeys: boolean;
function GetOwnsValues: boolean;
procedure SetOwnsKeys(const Value: boolean);
procedure SetOwnsValues(const Value: boolean);
procedure treeOnKeyNotify(Sender: TObject; const Key: TKey; Action: TCollectionNotification);
procedure treeOnValueNotify(Sender: TObject; const Value: TValue; Action: TCollectionNotification);
public
constructor Create; overload;
constructor Create(AComparer: IComparer<TKey>); overload;
constructor Create(const ACollection: TEnumerable<TPair<TKey,TValue>>; AComparer: IComparer<TKey> = nil); overload;
destructor Destroy; override;
procedure Clear;
procedure Add(const AKey: TKey; const AValue: TValue); overload;
procedure Add(const ACollection: TEnumerable<TPair<TKey,TValue>>); overload;
procedure AddOrSetValue(const AKey: TKey; const AValue: TValue);
function TryGetValue(const Key: TKey; out Value: TValue): Boolean;
procedure Remove(const AKey: TKey); overload;
procedure Remove(const AKeys: TArray<TKey>); overload;
procedure Remove(const AKeys: TEnumerable<TKey>); overload;
function ContainsKey(const Key: TKey): Boolean; overload;
function ContainsKeys(const AKeys: array of TKey; ASearchType: TSearchType = stAll): Boolean; overload;
function ContainsKeys(const AKeys: TEnumerable<TKey>; ASearchType: TSearchType = stAll): Boolean; overload;
function ContainsValue(const Value: TValue; AEqualityComparer: IEqualityComparer<TValue> = nil): Boolean;
function Min: TPair<TKey, TValue>;
function Max: TPair<TKey, TValue>;
function FindKeyByIndex(Index: integer): TKey;
{ navigate over the tree }
function GetRoot(var Key: TKey): Boolean;
function GetLeftChild(const AKey: TKey; var AChild: TKey): Boolean;
function GetRightChild(const AKey: TKey; var AChild: TKey): Boolean;
function GetParent(const AKey: TKey; var AParent: TKey): Boolean;
{ navigate all items from min to max (in both directions) }
function First(var AKey: TKey): Boolean;
function Last(var AKey: TKey): Boolean;
function Next(const AKey: TKey; var ANewKey: TKey): Boolean;
function Prev(const AKey: TKey; var ANewKey: TKey): Boolean;
property Count: integer read GetCount;
property Items[const AKey: TKey]: TValue read GetItem write SetItem ; default;
property KeyCollection: TKeyCollection read GetKeyCollection;
property ValueCollection: TValueCollection read GetValueCollection;
property TreeHeight: integer read GetTreeHeight;
property OwnsKeys: boolean read GetOwnsKeys write SetOwnsKeys;
property OwnsValues: boolean read GetOwnsValues write SetOwnsValues;
property OnKeyNotify: TCollectionNotifyEvent<TKey> read FOnKeyNotify write FOnKeyNotify;
property OnValueNotify: TCollectionNotifyEvent<TValue> read FOnValueNotify write FOnValueNotify;
end;
implementation
uses
adot.Hash,
adot.Collections,
adot.Tools,
adot.Tools.RTTI,
adot.Collections.Sets;
{ TMapClass<TKey, TValue> }
constructor TMapClass<TKey, TValue>.Create(ACapacity: integer; AComparer: IEqualityComparer<TKey>);
begin
inherited Create(ACapacity, AComparer);
FComparerCopy := AComparer;
end;
constructor TMapClass<TKey, TValue>.Create(const AValues: array of TPair<TKey, TValue>; AComparer: IEqualityComparer<TKey>);
begin
inherited Create(AComparer);
FComparerCopy := AComparer;
Add(AValues);
end;
constructor TMapClass<TKey, TValue>.Create(const AValues: TEnumerable<TPair<TKey, TValue>>; AComparer: IEqualityComparer<TKey>);
begin
inherited Create(AComparer);
FComparerCopy := AComparer;
Add(AValues);
end;
function TMapClass<TKey, TValue>.Empty: boolean;
begin
result := Count=0;
end;
class function TMapClass<TKey, TValue>.EscapeStrVal(const S: string): string;
var
i: Integer;
begin
for i := Low(S) to High(S) do
if S[i].IsLetter or (S[i]=',') then
Exit('"' + s + '"');
result := S;
end;
function TMapClass<TKey, TValue>.ToText(const Delimiter: string = #13#10): string;
var
Arr: TArray<TPair<TKey, TValue>>;
KeyComparer: IComparer<TKey>;
ValueComparer: IComparer<TValue>;
PairComparer: IComparer<TPair<TKey, TValue>>;
Pair: TPair<TKey, TValue>;
i: Integer;
Buf: TStringBuilder;
begin
Arr := ToArray;
KeyComparer := TComparerUtils.DefaultComparer<TKey>;
ValueComparer := TComparerUtils.DefaultComparer<TValue>;
PairComparer := TDelegatedComparer<TPair<TKey, TValue>>.Create(
function (const L,R: TPair<TKey, TValue>): integer
begin
result := KeyComparer.Compare(L.Key, R.Key);
if result=0 then
result := ValueComparer.Compare(L.Value, R.Value);
end);
TArray.Sort<TPair<TKey, TValue>>(Arr, PairComparer);
Buf := TStringBuilder.Create;
for Pair in Arr do
begin
if Buf.Length>0 then Buf.Append(Delimiter);
Buf.Append('(');
Buf.Append( EscapeStrVal(TRttiUtils.ValueAsString<TKey>(Pair.Key)));
Buf.Append(', ');
Buf.Append(TRttiUtils.ValueAsString<TValue>(Pair.Value));
Buf.Append(')');
end;
Result := Buf.ToString;
end;
function TMapClass<TKey, TValue>.ToString: string;
begin
result := ToText(' ');
end;
function TMapClass<TKey, TValue>.GetOwnsKeys: boolean;
begin
result := doOwnsKeys in FOwnerships;
end;
function TMapClass<TKey, TValue>.GetOwnsValues: boolean;
begin
result := doOwnsValues in FOwnerships;
end;
procedure TMapClass<TKey, TValue>.SetOwnsKeys(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<TKey> then
raise Exception.Create('Generic type is not a class.');
if Value
then include(FOwnerships, doOwnsKeys)
else exclude(FOwnerships, doOwnsKeys);
end;
procedure TMapClass<TKey, TValue>.SetOwnsValues(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<TValue> then
raise Exception.Create('Generic type is not a class.');
if Value
then include(FOwnerships, doOwnsValues)
else exclude(FOwnerships, doOwnsValues);
end;
procedure TMapClass<TKey, TValue>.KeyNotify(const Key: TKey; Action: TCollectionNotification);
begin
inherited;
if (Action = TCollectionNotification.cnRemoved) and (doOwnsKeys in FOwnerships) then
PObject(@Key)^.DisposeOf;
end;
procedure TMapClass<TKey, TValue>.ValueNotify(const Value: TValue; Action: TCollectionNotification);
begin
inherited;
if (Action = TCollectionNotification.cnRemoved) and (doOwnsValues in FOwnerships) then
PObject(@Value)^.DisposeOf;
end;
procedure TMapClass<TKey, TValue>.Remove(const AKeys: array of TKey);
var
i: Integer;
begin
for i := Low(AKeys) to High(AKeys) do
Remove(AKeys[i]);
end;
procedure TMapClass<TKey, TValue>.Remove(const AKeys: TEnumerable<TKey>);
var
Key: TKey;
begin
for Key in AKeys do
Remove(Key);
end;
procedure TMapClass<TKey, TValue>.Add(const AValues: array of TPair<TKey, TValue>);
var
i: Integer;
begin
for i := Low(AValues) to High(AValues) do
Add(AValues[i].Key, AValues[i].Value);
end;
procedure TMapClass<TKey, TValue>.Add(const AValues: TEnumerable<TPair<TKey, TValue>>);
var
Pair: TPair<TKey,TValue>;
begin
for Pair in AValues do
Add(Pair.Key, Pair.Value);
end;
procedure TMapClass<TKey, TValue>.AddOrSetValue(const AValues: array of TPair<TKey, TValue>);
var
i: Integer;
begin
for i := Low(AValues) to High(AValues) do
AddOrSetValue(AValues[i].Key, AValues[i].Value);
end;
procedure TMapClass<TKey, TValue>.AddOrSetValue(const AValues: TEnumerable<TPair<TKey, TValue>>);
var
Pair: TPair<TKey,TValue>;
begin
for Pair in AValues do
AddOrSetValue(Pair.Key, Pair.Value);
end;
{ TMultimapClass<TKey, TValue> }
constructor TMultimapClass<TKey, TValue>.Create;
begin
Create(IEqualityComparer<TKey>(nil));
end;
constructor TMultimapClass<TKey, TValue>.Create(AComparer: IEqualityComparer<TKey>);
begin
inherited Create;
if AComparer = nil then
AComparer := TComparerUtils.DefaultEqualityComparer<TKey>;
FCount := TDictionary<TKey, integer>.Create(AComparer);
FValues := TDictionary<TMultimapKey, TValue>.Create(TMultimapKeyEqualityComparer.Create(AComparer));
end;
constructor TMultimapClass<TKey, TValue>.Create(const ACollection: TEnumerable<TPair<TKey,TValue>>; AComparer: IEqualityComparer<TKey> = nil);
begin
Create(AComparer);
Add(ACollection);
end;
destructor TMultimapClass<TKey, TValue>.Destroy;
begin
FreeAndNil(FCount);
FreeAndNil(FValues);
FreeAndNil(FKeyCollection);
inherited;
end;
function TMultimapClass<TKey, TValue>.DoGetEnumerator: TEnumerator<TPair<TKey, TValue>>;
begin
result := GetEnumerator;
end;
function TMultimapClass<TKey, TValue>.Empty: boolean;
begin
result := FValues.Count=0;
end;
function TMultimapClass<TKey, TValue>.GetEnumerator: TPairEnumerator;
begin
Result := TPairEnumerator.Create(Self);
end;
function TMultimapClass<TKey, TValue>.GetKeys: TKeyCollection;
begin
if FKeyCollection = nil then
FKeyCollection := TKeyCollection.Create(FCount);
Result := FKeyCollection;
end;
function TMultimapClass<TKey, TValue>.GetTotalValuesCount: integer;
begin
result := FValues.Count;
end;
procedure TMultimapClass<TKey, TValue>.Clear;
begin
FCount.Clear;
FValues.Clear;
end;
function TMultimapClass<TKey, TValue>.ContainsKey(const AKey: TKey): Boolean;
begin
result := GetValuesCount(AKey)>0;
end;
function TMultimapClass<TKey, TValue>.ContainsKeys(const AKeys: array of TKey; AContainsCheckType: TContainsCheckType): Boolean;
var
i: Integer;
begin
case AContainsCheckType of
cctAll:
begin
for i := Low(AKeys) to High(AKeys) do
if not ContainsKey(AKeys[i]) then
Exit(False);
result := True;
end;
cctAnyOf:
begin
for i := Low(AKeys) to High(AKeys) do
if ContainsKey(AKeys[i]) then
Exit(True);
result := False;
end;
else
raise exception.Create('');
end;
end;
function TMultimapClass<TKey, TValue>.ContainsKeys(const AKeys: TEnumerable<TKey>; AContainsCheckType: TContainsCheckType): Boolean;
var
Key: TKey;
begin
case AContainsCheckType of
cctAll:
begin
for Key in AKeys do
if not ContainsKey(Key) then
Exit(False);
result := True;
end;
cctAnyOf:
begin
for Key in AKeys do
if ContainsKey(Key) then
Exit(True);
result := False;
end;
else
raise exception.Create('');
end;
end;
function TMultimapClass<TKey, TValue>.ContainsValue(const AKey: TKey; const AValue: TValue; AComparer: IEqualityComparer<TValue> = nil): Boolean;
var
V: TValue;
begin
if AComparer=nil then
AComparer := TComparerUtils.DefaultEqualityComparer<TValue>;
for V in Values[AKey] do
if AComparer.Equals(AValue, V) then
Exit(True);
result := False;
end;
function TMultimapClass<TKey, TValue>.ContainsValues(const AKey: TKey; const AValues: TArray<TValue>; AContainsCheckType: TContainsCheckType;
AComparer: IEqualityComparer<TValue>): Boolean;
var
ValueSet: TSetClass<TValue>;
i: Integer;
begin
if AComparer=nil then
AComparer := TComparerUtils.DefaultEqualityComparer<TValue>;
ValueSet := TSetClass<TValue>.Create(0, AComparer);
try
case AContainsCheckType of
cctAll:
begin
for i := Low(AValues) to High(AValues) do
if not ValueSet.Contains(AValues[i]) then
Exit(False);
result := True;
end;
cctAnyOf:
begin
for i := Low(AValues) to High(AValues) do
if ValueSet.Contains(AValues[i]) then
Exit(True);
result := False;
end;
else
raise exception.Create('');
end;
finally
FreeAndNil(ValueSet);
end;
end;
function TMultimapClass<TKey, TValue>.ContainsValues(const AKey: TKey; const AValues: TEnumerable<TValue>; AContainsCheckType: TContainsCheckType;
AComparer: IEqualityComparer<TValue>): Boolean;
var
ValueSet: TSetClass<TValue>;
V: TValue;
begin
if AComparer=nil then
AComparer := TComparerUtils.DefaultEqualityComparer<TValue>;
ValueSet := TSetClass<TValue>.Create(0, AComparer);
try
case AContainsCheckType of
cctAll:
begin
for V in AValues do
if not ValueSet.Contains(V) then
Exit(False);
result := True;
end;
cctAnyOf:
begin
for V in AValues do
if ValueSet.Contains(V) then
Exit(True);
result := False;
end;
else
raise exception.Create('');
end;
finally
FreeAndNil(ValueSet);
end;
end;
function TMultimapClass<TKey, TValue>.GetValuesCount(const AKey: TKey): Integer;
begin
if not FCount.TryGetValue(AKey, result) then
result := 0;
end;
procedure TMultimapClass<TKey, TValue>.Add(const AKey: TKey; const AValue: TValue);
var
MKey: TMultimapKey;
begin
MKey := Default(TMultimapKey);
MKey.Key := AKey;
if not FCount.TryGetValue(AKey, MKey.Number) then
MKey.Number := 0;
FValues.Add(MKey, AValue);
inc(MKey.Number);
FCount.AddOrSetValue(AKey, MKey.Number);
end;
procedure TMultimapClass<TKey, TValue>.Add(const AKey: TKey; const AValues: TArray<TValue>);
var
MKey: TMultimapKey;
i: Integer;
begin
MKey := Default(TMultimapKey);
MKey.Key := AKey;
if not FCount.TryGetValue(AKey, MKey.Number) then
MKey.Number := 0;
for i := Low(AValues) to High(AValues) do
begin
FValues.Add(MKey, AValues[i]);
inc(MKey.Number);
end;
FCount.AddOrSetValue(AKey, MKey.Number);
end;
procedure TMultimapClass<TKey, TValue>.Add(const AKey: TKey; const AValues: TEnumerable<TValue>);
var
item: TValue;
begin
for item in AValues do
Add(AKey, item);
end;
procedure TMultimapClass<TKey, TValue>.Add(const ACollection: TEnumerable<TPair<TKey,TValue>>);
var
item: TPair<TKey,TValue>;
begin
for item in ACollection do
Add(item.Key, item.Value);
end;
function TMultimapClass<TKey, TValue>.Remove(const AKey: TKey): Boolean;
var
MKey: TMultimapKey;
begin
MKey := Default(TMultimapKey);
result := FCount.TryGetValue(AKey, MKey.Number);
if not result then
Exit;
FCount.Remove(AKey);
MKey.Key := AKey;
while MKey.Number>0 do
begin
dec(MKey.Number);
FValues.Remove(MKey);
end;
end;
procedure TMultimapClass<TKey, TValue>.RemoveValue(const AEnum: TValueEnumerator);
var
LastKey: TMultimapKey;
LastValue: TValue;
begin
LastKey := Default(TMultimapKey);
if not FValues.ContainsKey(AEnum.FMultimapKey) or not FCount.TryGetValue(AEnum.Key, LastKey.Number) then
raise Exception.Create('Error');
dec(LastKey.Number);
LastKey.Key := AEnum.Key;
if not FValues.TryGetValue(LastKey, LastValue) then
raise Exception.Create('Error');
FValues.AddOrSetValue(AEnum.FMultimapKey, LastValue);
FValues.Remove(LastKey);
if LastKey.Number=0 then
FCount.Remove(AEnum.Key)
else
FCount.AddOrSetValue(AEnum.Key, LastKey.Number);
end;
procedure TMultimapClass<TKey, TValue>.RemoveValues(const AKey: TKey; const AValues: TArray<TValue>);
var
S: TSetClass<TValue>;
E: TValueEnumerator;
begin
S := TSetClass<TValue>.Create(AValues);
try
E := Values[AKey];
while E.MoveNext do
if S.Contains(E.Current) then
RemoveValue(E);
finally
FReeAndNil(S);
end;
end;
procedure TMultimapClass<TKey, TValue>.RemoveValues(const AKey: TKey; const AValues: TEnumerable<TValue>);
var
s: TSetClass<TValue>;
begin
s := TSetClass<TValue>.Create(AValues);
try
RemoveValues(AKey, s);
finally
FReeAndNil(s);
end;
end;
function TMultimapClass<TKey, TValue>.GetValuesEnumerator(const AKey: TKey): TValueEnumerator;
begin
result.Init(Self, AKey);
end;
{ TMultimapClass<TKey, TValue>.TValueEnumerator }
procedure TMultimapClass<TKey, TValue>.TValueEnumerator.Init(AMultimap: TMultimapClass<TKey, TValue>; const AKey: TKey);
begin
Self := Default(TValueEnumerator);
FMultimap := AMultimap;
FMultimapKey := Default(TMultimapKey);
FMultimapKey.Key := AKey;
if not FMultimap.FCount.TryGetValue(AKey, FMultimapKey.Number) then
FMultimapKey.Number := -1;
end;
function TMultimapClass<TKey, TValue>.TValueEnumerator.MoveNext: Boolean;
begin
result := FMultimapKey.Number>0;
if result then
dec(FMultimapKey.Number);
end;
function TMultimapClass<TKey, TValue>.TValueEnumerator.GetCurrent: TValue;
begin
if not FMultimap.FValues.TryGetValue(FMultimapKey, result) then
raise Exception.Create('Error');
end;
function TMultimapClass<TKey, TValue>.TValueEnumerator.GetEnumerator: TValueEnumerator;
begin
result.FMultimap := FMultimap;
result.FMultimapKey := FMultimapKey;
end;
function TMultimapClass<TKey, TValue>.TValueEnumerator.GetKey: TKey;
begin
result := FMultimapKey.Key;
end;
{ TMultimapClass<TKey, TValue>.TMultimapKeyEqualityComparer }
constructor TMultimapClass<TKey, TValue>.TMultimapKeyEqualityComparer.Create(AKeyComparer: IEqualityComparer<TKey>);
begin
FKeyComparer := AKeyComparer;
if FKeyComparer=nil then
FKeyComparer := TComparerUtils.DefaultEqualityComparer<TKey>;
end;
function TMultimapClass<TKey, TValue>.TMultimapKeyEqualityComparer.Equals(const Left,
Right: TMultimapKey): Boolean;
begin
result := (Left.Number=Right.Number) and FKeyComparer.Equals(Left.Key, Right.Key);
end;
function TMultimapClass<TKey, TValue>.TMultimapKeyEqualityComparer.GetHashCode(
const Value: TMultimapKey): Integer;
begin
result := TDigests.Mix(FKeyComparer.GetHashCode(Value.Key), Value.Number);
end;
{ TMultimapClass<TKey, TValue>.TPairEnumerator }
constructor TMultimapClass<TKey, TValue>.TPairEnumerator.Create(
const AMultimap: TMultimapClass<TKey, TValue>);
begin
inherited Create;
FMultimap := AMultimap;
FCurrentKey := FMultimap.FCount.Keys.GetEnumerator;
end;
function TMultimapClass<TKey, TValue>.TPairEnumerator.DoMoveNext: Boolean;
begin
if not FInEnumKey then
begin
result := FCurrentKey.MoveNext;
if not result then
Exit;
FCurrentValue := FMultimap.Values[FCurrentKey.Current];
result := FCurrentValue.MoveNext;
Assert(result); // if key is here, then there must be at least one value
FInEnumKey := True;
Exit;
end;
result := FCurrentValue.MoveNext;
if not result then
begin
FInEnumKey := False;
result := MoveNext;
end;
end;
function TMultimapClass<TKey, TValue>.TPairEnumerator.DoGetCurrent: TPair<TKey, TValue>;
begin
result.Key := FCurrentKey.Current;
result.Value := FCurrentValue.Current;
end;
{ TMap<TKey, TValue> }
procedure TMap<TKey, TValue>.Init;
begin
Self := Default(TMap<TKey, TValue>);
end;
procedure TMap<TKey, TValue>.Init(ACapacity: integer; AComparer: IEqualityComparer<TKey>);
begin
Self := Default(TMap<TKey, TValue>);
CreateMap(ACapacity, AComparer);
end;
procedure TMap<TKey, TValue>.Init(const V: array of TPair<TKey, TValue>; ACapacity: integer; AComparer: IEqualityComparer<TKey>);
begin
Self := Default(TMap<TKey, TValue>);
CreateMap(ACapacity, AComparer);
Add(V);
end;
procedure TMap<TKey, TValue>.Init(const V: TEnumerable<TPair<TKey, TValue>>; ACapacity: integer; AComparer: IEqualityComparer<TKey>);
begin
Self := Default(TMap<TKey, TValue>);
CreateMap(ACapacity, AComparer);
Add(V);
end;
procedure TMap<TKey, TValue>.Init(V: TMap<TKey, TValue>; ACapacity: integer; AComparer: IEqualityComparer<TKey>);
begin
Self := Default(TMap<TKey, TValue>);
CreateMap(ACapacity, AComparer);
Add(V);
end;
procedure TMap<TKey, TValue>.CreateMap(ACapacity: integer; AComparer: IEqualityComparer<TKey>);
var
C: IEqualityComparer<TKey>;
begin
if AComparer=nil
then C := TComparerUtils.DefaultEqualityComparer<TKey>
else C := AComparer;
FMapInt := TInterfacedObject<TMapClass<TKey,TValue>>.Create( TMapClass<TKey,TValue>.Create(ACapacity, C) );
end;
function TMap<TKey, TValue>.GetReadonly: TMapClass<TKey, TValue>;
begin
if FMapInt=nil then
CreateMap;
result := FMapInt.Data;
end;
function TMap<TKey, TValue>.GetReadWrite: TMapClass<TKey, TValue>;
var
SrcMapInt: IInterfacedObject<TMapClass<TKey,TValue>>;
begin
if FMapInt=nil then
CreateMap
else
if FMapInt.GetRefCount<>1 then
begin
{ Copy on write }
SrcMapInt := FMapInt;
CreateMap(SrcMapInt.Data.Count, SrcMapInt.Data.Comparer);
FMapInt.Data.Add(SrcMapInt.Data);
FMapInt.Data.OwnsKeys := FMapInt.Data.OwnsKeys;
FMapInt.Data.OwnsValues := FMapInt.Data.OwnsValues;
end;
result := FMapInt.Data;
end;
function TMap<TKey, TValue>.GetEmpty: Boolean;
begin
Result := Count = 0;
end;
function TMap<TKey, TValue>.GetEnumerator: TPairEnumerator;
begin
result := Readonly.GetEnumerator;
end;
function TMap<TKey, TValue>.GetKeys: TKeyCollection;
begin
result := ReadOnly.Keys;
end;
function TMap<TKey, TValue>.GetValues: TValueCollection;
begin
result := ReadOnly.Values;
end;
procedure TMap<TKey, TValue>.Remove(const V: TKey);
begin
ReadWrite.Remove(V);
end;
procedure TMap<TKey, TValue>.Remove(const V: TEnumerable<TKey>);
begin
ReadWrite.Remove(V);
end;
procedure TMap<TKey, TValue>.Remove(const V: array of TKey);
begin
ReadWrite.Remove(V);
end;
procedure TMap<TKey, TValue>.Add(const V: array of TPair<TKey, TValue>);
begin
ReadWrite.Add(V);
end;
procedure TMap<TKey, TValue>.Add(const Pair: TPair<TKey, TValue>);
begin
ReadWrite.Add(Pair.Key, Pair.Value);
end;
procedure TMap<TKey, TValue>.Add(const Key: TKey; Value: TValue);
begin
ReadWrite.Add(Key, Value);
end;
procedure TMap<TKey, TValue>.Add(const V: TEnumerable<TPair<TKey, TValue>>);
begin
ReadWrite.Add(V);
end;
procedure TMap<TKey, TValue>.Add(V: TMap<TKey, TValue>);
begin
ReadWrite.Add(V.ReadOnly);
end;
procedure TMap<TKey, TValue>.AddOrSetValue(const V: array of TPair<TKey, TValue>);
begin
ReadWrite.AddOrSetValue(V);
end;
procedure TMap<TKey, TValue>.AddOrSetValue(const Pair: TPair<TKey, TValue>);
begin
ReadWrite.AddOrSetValue(Pair.Key, Pair.Value);
end;
procedure TMap<TKey, TValue>.AddOrSetValue(const Key: TKey; Value: TValue);
begin
ReadWrite.AddOrSetValue(Key, Value);
end;
procedure TMap<TKey, TValue>.AddOrSetValue(const V: TEnumerable<TPair<TKey, TValue>>);
begin
ReadWrite.AddOrSetValue(V);
end;
procedure TMap<TKey, TValue>.AddOrSetValue(V: TMap<TKey, TValue>);
begin
ReadWrite.AddOrSetValue(V.ReadOnly);
end;
procedure TMap<TKey, TValue>.TrimExcess;
begin
ReadWrite.TrimExcess;
end;
function TMap<TKey, TValue>.TryGetValue(const Key: TKey; out Value: TValue): Boolean;
begin
result := ReadOnly.TryGetValue(Key, Value);
end;
function TMap<TKey, TValue>.GetValue(const Key: TKey): TValue;
begin
if not ReadOnly.TryGetValue(Key, Result) then
raise Exception.Create('Error');
end;
function TMap<TKey, TValue>.GetValueDef(const Key: TKey): TValue;
begin
if not ReadOnly.TryGetValue(Key, Result) then
result := default(TValue);
end;
class operator TMap<TKey, TValue>.Equal(A, B: TMap<TKey, TValue>): Boolean;
var
Pair: TPair<TKey, TValue>;
Value: TValue;
ValueComparer: IComparer<TValue>;
begin
if A.Count<>B.Count then
Exit(False);
ValueComparer := TComparerUtils.DefaultComparer<TValue>;
for Pair in A do
if not B.TryGetValue(Pair.Key, Value) or (ValueComparer.Compare(Pair.Value, Value) <> 0) then
Exit(False);
Result := True;
end;
class operator TMap<TKey, TValue>.NotEqual(A, B: TMap<TKey, TValue>): Boolean;
begin
result := not (A=B);
end;
function TMap<TKey, TValue>.ExtractPair(const Key: TKey): TPair<TKey, TValue>;
begin
result := ReadWrite.ExtractPair(Key);
end;
procedure TMap<TKey, TValue>.Clear;
begin
ReadWrite.Clear;
end;
procedure TMap<TKey, TValue>.Release;
begin
FMapInt := nil;
end;
function TMap<TKey, TValue>.ContainsKey(const Key: TKey): Boolean;
begin
result := ReadOnly.ContainsKey(Key);
end;
function TMap<TKey, TValue>.Copy: TMap<TKey, TValue>;
begin
if FMapInt=nil then
result.Init
else
begin
result.Init(Count, FMapInt.Data.Comparer);
result.Add(Self);
end;
end;
function TMap<TKey, TValue>.ToArray: TArray<TPair<TKey, TValue>>;
begin
result := ReadOnly.ToArray;
end;
function TMap<TKey, TValue>.ToString: string;
begin
result := ReadOnly.ToString;
end;
function TMap<TKey, TValue>.ToText(const Delimiter: string = #13#10): string;
begin
result := ReadOnly.ToText(Delimiter);
end;
function TMap<TKey, TValue>.GetCollection: TEnumerable<TPair<TKey, TValue>>;
begin
result := Readonly;
end;
function TMap<TKey, TValue>.GetCount: integer;
begin
result := ReadOnly.Count;
end;
function TMap<TKey, TValue>.GetItem(const Key: TKey): TValue;
begin
result := ReadOnly[Key];
end;
procedure TMap<TKey, TValue>.SetItem(const Key: TKey; const Value: TValue);
begin
ReadWrite[Key] := Value;
end;
function TMap<TKey, TValue>.GetOwnsKeys: boolean;
begin
result := ReadOnly.OwnsKeys;
end;
function TMap<TKey, TValue>.GetOwnsValues: boolean;
begin
result := ReadOnly.OwnsValues;
end;
procedure TMap<TKey, TValue>.SetOwnsKeys(const Value: boolean);
begin
if Value<>ReadOnly.OwnsKeys then
ReadWrite.OwnsKeys := Value;
end;
procedure TMap<TKey, TValue>.SetOwnsValues(const Value: boolean);
begin
if Value<>ReadOnly.OwnsValues then
ReadWrite.OwnsValues := Value;
end;
{ TAATree<TKey, TValue> }
constructor TAATree<TKey, TValue>.Create;
begin
Create(IComparer<TKey>(nil));
end;
constructor TAATree<TKey, TValue>.Create(AComparer: IComparer<TKey>);
begin
inherited Create;
FComparer := AComparer;
if FComparer=nil then
FComparer := TComparerUtils.DefaultComparer<TKey>;
FBottom := AllocNewItem;
FBottom.Level := 0;
FBottom.Left := FBottom;
FBottom.Right := FBottom;
FDeleted := FBottom;
FRoot := FBottom;
FLast := FBottom;
end;
constructor TAATree<TKey, TValue>.Create(const ACollection: TEnumerable<TPair<TKey,TValue>>; AComparer: IComparer<TKey> = nil);
begin
Create(AComparer);
Add(ACollection);
end;
destructor TAATree<TKey, TValue>.Destroy;
begin
Clear;
ReleaseItem(FBottom);
FBottom := nil;
FDeleted := nil;
FRoot := nil;
FreeAndNil(FKeyCollection);
FreeAndNil(FValueCollection);
inherited;
end;
function TAATree<TKey, TValue>.DoGetEnumerator: TEnumerator<TPair<TKey, TValue>>;
begin
result := TPairEnumerator.Create(Self);
end;
function TAATree<TKey, TValue>.AllocNewItem: P_AATreeItem;
begin
result := AllocMem(SizeOf(T_AATreeItem));
end;
procedure TAATree<TKey, TValue>.ReleaseItem(p: P_AATreeItem);
begin
if p=nil then
Exit;
p.Data.Key := Default(TKey);
p.Data.Value := Default(TValue);
FreeMem(p);
end;
procedure TAATree<TKey, TValue>.KeyNotify(const Key: TKey; Action: TCollectionNotification);
begin
if Assigned(FOnKeyNotify) then
FOnKeyNotify(Self, Key, Action);
end;
procedure TAATree<TKey, TValue>.ValueNotify(const Value: TValue; Action: TCollectionNotification);
begin
if Assigned(FOnValueNotify) then
FOnValueNotify(Self, Value, Action);
end;
function TAATree<TKey, TValue>.PtrToHandle(p: P_AATreeItem): TItemHandle;
begin
if (p=FBottom) or (p=nil) then
Result := -1
else
Result := TItemHandle(p);
end;
function TAATree<TKey, TValue>.HandleToPtr(p: TItemHandle): P_AATreeItem;
begin
if p=-1 then
result := nil
else
result := P_AATreeItem(p);
end;
procedure TAATree<TKey, TValue>.Clear;
begin
if FCount=0 then
exit;
treeClear(FRoot);
FBottom.Level := 0;
FBottom.Left := FBottom;
FBottom.Right := FBottom;
FDeleted := FBottom;
FRoot := FBottom;
FCount := 0;
end;
function TAATree<TKey, TValue>.treeAdd(p, aparent: P_AATreeItem; var Dst: P_AATreeItem): Boolean;
var
r: integer;
begin
if Dst = FBottom then
with p^ do
begin
Parent := AParent;
Left := FBottom;
Right := FBottom;
Level := 1;
Dst := p;
result := true;
exit;
end;
r := FComparer.Compare(p.Data.Key, Dst.Data.Key);
if r>0 then
result := treeAdd(p, Dst, Dst.right)
else
if r<0 then
result := treeAdd(p, Dst, Dst.left)
else
result := false;
if not result then
exit;
treeSkew(Dst);
treeSplit(Dst);
end;
procedure TAATree<TKey, TValue>.treeClear(p: P_AATreeItem);
begin
if (p=nil) or (p=FBottom) then
exit;
KeyNotify(p.Data.Key, TCollectionNotification.cnRemoved);
ValueNotify(p.Data.Value, TCollectionNotification.cnRemoved);
treeClear(p.Left);
treeClear(p.Right);
releaseItem(p);
end;
function TAATree<TKey, TValue>.treeDelete(x: P_AATreeItem; var t: P_AATreeItem): boolean;
begin
result := false;
if (t=nil) or (t=FBottom) then
exit;
// search down the tree and set pointers last and deleted
Flast := t;
if FComparer.Compare(x.Data.Key, t.Data.Key) < 0 then
result := treeDelete(x, t.Left)
else
begin
FDeleted := t;
result := treeDelete(x, t.Right);
end;
// At the bottom of the tree we remove the element (if it exists)
if (t = FLast) and (FDeleted <> FBottom) and (FComparer.Compare(x.Data.Key, FDeleted.Data.Key)=0) then
begin
// We copy key, because it is necessary to rebalance the tree and move
// FDeleted into right position (position for FLast).
if FLast<>FDeleted then
FDeleted.Data.Key := FLast.Data.Key;
t.Right.Parent := t.Parent;
t := t.Right;
result := true;
end
else
// On the way back, we rebalance
if (t.Left.Level < t.Level-1) or (t.Right.Level < t.Level-1) then
begin
dec(t.Level);
if t.Right.Level > t.Level then
t.right.level := t.level;
treeSkew(t);
treeSkew(t.right);
treeSkew(t.right.right);
treeSplit(t);
treeSplit(t.right);
end;
end;
function TAATree<TKey, TValue>.treeFind(const AKey: TKey): P_AATreeItem;
var n: integer;
begin
result := FRoot;
while result<>FBottom do
begin
n := FComparer.Compare(AKey, result.Data.Key);
if n<0 then
result := result.Left
else
if n>0 then
result := result.Right
else
exit;
end;
end;
function TAATree<TKey, TValue>.treeFullHeight: integer;
begin
result := treeGetHeight(FRoot);
end;
function TAATree<TKey, TValue>.treeGetHeight(p: P_AATreeItem): integer;
begin
if p=FBottom then
result := 0
else
result := Max(treeGetHeight(p.Left), treeGetHeight(p.Right)) + 1;
end;
function TAATree<TKey, TValue>.treeMax(p: P_AATreeItem): P_AATreeItem;
begin
if (p=nil) or (p=FBottom) then
result := nil
else
begin
result := p;
while result.Right <> FBottom do
result := result.Right;
end;
end;
function TAATree<TKey, TValue>.treeMin(p: P_AATreeItem): P_AATreeItem;
begin
if (p=nil) or (p=FBottom) then
result := nil
else
begin
result := p;
while result.Left <> FBottom do
result := result.Left;
end;
end;
procedure TAATree<TKey, TValue>.treeMove(Src, Dst: P_AATreeItem);
begin
Dst.Data := Src.Data;
end;
function TAATree<TKey, TValue>.treePredecessor(p: P_AATreeItem): P_AATreeItem;
begin
if (p=nil) or (p=FBottom) then
result := nil
else
if p.Left <> FBottom then
result := treeMax(p.Left)
else
begin
result := p.Parent;
while (result<>FBottom) and (p=result.Left) do
begin
p := result;
result := result.Parent;
end;
end;
end;
function TAATree<TKey, TValue>.treeSuccessor(p: P_AATreeItem): P_AATreeItem;
begin
if (p=nil) or (p=FBottom) then
result := nil
else
if p.Right <> FBottom then
result := treeMin(p.Right)
else
begin
result := p.Parent;
while (result<>FBottom) and (p=result.Right) do
begin
p := result;
result := result.Parent;
end;
end;
end;
function TAATree<TKey, TValue>.TryGetValue(const Key: TKey; out Value: TValue): Boolean;
var
h: TItemHandle;
begin
h := Find(Key);
result := h<>-1;
if result then
Value := Values[h];
end;
// replace position of Dst item in the tree with Src item
procedure TAATree<TKey, TValue>.treeReplace(Src, Dst: P_AATreeItem);
begin
Src.Parent := Dst.Parent;
Src.Left := Dst.Left;
Src.Right := Dst.Right;
Src.Level := Dst.Level;
// root item has "parent=FBottom"
// but FBottom.left/right MUST refer to FBottom
if Src.Parent<>FBottom then
if Src.Parent.Left=Dst then
Src.Parent.Left := Src
else
Src.Parent.Right := Src;
Src.Left.Parent := Src;
Src.Right.Parent := Src;
if FRoot=Dst then
FRoot := Src;
end;
{
Src: 1(p) Dst: 2(p)
/ \ / \
2(t) X Y 1(t)
/ \ / \
Y Z Z X
}
procedure TAATree<TKey, TValue>.treeSkew(var p: P_AATreeItem);
var
t: P_AATreeItem;
begin
if (p.Left.Level = p.Level) then
begin
// change Right&Left links
t := p;
p := p.left;
t.left := p.right;
p.right := t;
// change Parent links
p.Parent := t.Parent;
t.Parent := p;
t.Left.Parent := t;
end;
end;
{
Src: 1(p) Dst: 2(p)
/ \ / \
X 2(t) 1(t) Z
/ \ / \
Y Z X Y
}
procedure TAATree<TKey, TValue>.treeSplit(var p: P_AATreeItem);
var
t: P_AATreeItem;
begin
if (p.Right.Right.Level = p.Level) then
begin
// change Right&Left links
t := p;
p := p.Right;
t.Right := p.Left;
p.Left := t;
inc(p.Level);
// change Parent links
p.Parent := t.Parent;
t.Parent := p;
t.Right.Parent := t;
end;
end;
function TAATree<TKey, TValue>.Add(const AKey: TKey; const AValue: TValue): TItemHandle;
var
p: P_AATreeItem;
begin
p := AllocNewItem;
p.Data.Key := AKey;
p.Data.Value := AValue;
if treeAdd(p, FBottom, FRoot) then
begin
result := TItemHandle(p);
inc(FCount);
KeyNotify(AKey, TCollectionNotification.cnAdded);
ValueNotify(AValue, TCollectionNotification.cnAdded);
end
else
begin
ReleaseItem(p);
result := -1;
end;
end;
procedure TAATree<TKey, TValue>.Add(const ACollection: TEnumerable<TPair<TKey,TValue>>);
var
Pair: TPair<TKey,TValue>;
begin
for Pair in ACollection do
Add(Pair.Key, Pair.Value);
end;
function TAATree<TKey, TValue>.AddOrSetValue(const AKey: TKey; const AValue: TValue): TItemHandle;
begin
result := Find(AKey);
if result=-1 then
result := Add(AKey, AValue)
else
Values[result] := AValue;
end;
procedure TAATree<TKey, TValue>.Delete(AHandle: TItemHandle);
begin
if AHandle=-1 then
raise Exception.Create('Error');
if (P_AATreeItem(AHandle)<>nil) and (P_AATreeItem(AHandle)<>FBottom) then
begin
KeyNotify(P_AATreeItem(AHandle).Data.Key, TCollectionNotification.cnRemoved);
ValueNotify(P_AATreeItem(AHandle).Data.Value, TCollectionNotification.cnRemoved);
end;
if not treeDelete(P_AATreeItem(AHandle), FRoot) then
exit;
// content of FDeleted has cleaned & replaced with key from FLast
// now we move FLast into position of FDeleted
if FLast<>FDeleted then
begin
treeMove(FLast, FDeleted);
treeReplace(FLast, FDeleted);
end;
// ItemDeleted for deleted item has called from treeDelete
// so we must not call it again
ReleaseItem(FDeleted);
FDeleted := FBottom;
FLast := FBottom;
dec(FCount);
end;
function TAATree<TKey, TValue>.Find(const AKey: TKey): TItemHandle;
begin
result := PtrToHandle( treeFind(AKey) );
end;
function TAATree<TKey, TValue>.FindMax: TItemHandle;
begin
result := PtrToHandle( treeMax(FRoot) );
end;
function TAATree<TKey, TValue>.GetRoot(var ARoot: TItemHandle): Boolean;
begin
ARoot := PtrToHandle(FRoot);
result := ARoot<>-1
end;
function TAATree<TKey, TValue>.GetLeftChild(AItem: TItemHandle; var AChild: TItemHandle): Boolean;
begin
result := AItem<>-1;
if result then
begin
AChild := PtrToHandle(HandleToPtr(AItem).Left);
result := AChild<>-1;
end;
end;
function TAATree<TKey, TValue>.GetRightChild(AItem: TItemHandle; var AChild: TItemHandle): Boolean;
begin
result := AItem<>-1;
if result then
begin
AChild := PtrToHandle(HandleToPtr(AItem).Right);
result := AChild<>-1;
end;
end;
function TAATree<TKey, TValue>.GetParent(AItem: TItemHandle; var AParent: TItemHandle): Boolean;
begin
result := AItem<>-1;
if result then
begin
AParent := PtrToHandle(HandleToPtr(AItem).Parent);
result := AParent<>-1;
end;
end;
function TAATree<TKey, TValue>.FindMin: TItemHandle;
begin
result := PtrToHandle( treeMin(FRoot) );
end;
function TAATree<TKey, TValue>.First(var AHandle: TItemHandle): Boolean;
begin
AHandle := PtrToHandle( treeMin(FRoot) );
result := AHandle<>-1;
end;
function TAATree<TKey, TValue>.Last(var AHandle: TItemHandle): Boolean;
begin
AHandle := PtrToHandle( treeMax(FRoot) );
result := AHandle<>-1;
end;
function TAATree<TKey, TValue>.Prev(var AHandle: TItemHandle): Boolean;
begin
AHandle := PtrToHandle( treePredecessor(P_AATreeItem(AHandle)) );
result := AHandle<>-1;
end;
function TAATree<TKey, TValue>.Next(var AHandle: TItemHandle): Boolean;
begin
AHandle := PtrToHandle( treeSuccessor(P_AATreeItem(AHandle)) );
result := AHandle<>-1;
end;
function TAATree<TKey, TValue>.GetEnumerator: TPairEnumerator;
begin
result := TPairEnumerator.Create(Self);
end;
function TAATree<TKey, TValue>.GetKey(AHandle: TItemHandle): TKey;
begin
result := P_AATreeItem(AHandle).Data.Key;
end;
function TAATree<TKey, TValue>.GetKeyCollection: TKeyCollection;
begin
if FKeyCollection = nil then
FKeyCollection := TKeyCollection.Create(Self);
result := FKeyCollection;
end;
function TAATree<TKey, TValue>.GetValue(AHandle: TItemHandle): TValue;
begin
if AHandle<>-1 then
result := P_AATreeItem(AHandle).Data.Value
else
raise Exception.Create('Error');
end;
procedure TAATree<TKey, TValue>.SetValue(AHandle: TItemHandle; const AValue: TValue);
begin
if AHandle<>-1 then
P_AATreeItem(AHandle).Data.Value := AValue
else
raise Exception.Create('Error');
end;
function TAATree<TKey, TValue>.GetPair(AHandle: TItemHandle): TPair<TKEy,TValue>;
begin
if AHandle<>-1 then
result := P_AATreeItem(AHandle).Data
else
raise Exception.Create('Error');
end;
function TAATree<TKey, TValue>.GetValueByKey(const AKey: TKey): TValue;
begin
result := Values[Find(AKey)];
end;
function TAATree<TKey, TValue>.GetValueCollection: TValueCollection;
begin
if FValueCollection = nil then
FValueCollection := TValueCollection.Create(Self);
result := FValueCollection;
end;
procedure TAATree<TKey, TValue>.SetValueByKey(const AKey: TKey; const AValue: TValue);
var
h: TItemHandle;
begin
h := Find(AKey);
if h=-1 then
Add(AKey, AValue)
else
Values[h] := AValue;
end;
function TAATree<TKey, TValue>.ContainsKey(const Key: TKey): Boolean;
begin
result := Find(Key)<>-1;
end;
function TAATree<TKey, TValue>.ContainsKeys(const AKeys: array of TKey;
ASearchType: TSearchType): Boolean;
var
i: Integer;
begin
case ASearchType of
stAll:
begin
for i := Low(AKeys) to High(AKeys) do
if not ContainsKey(AKeys[i]) then
Exit(False);
Exit(True);
end;
stAny:
begin
for i := Low(AKeys) to High(AKeys) do
if ContainsKey(AKeys[i]) then
Exit(True);
Exit(False);
end;
end;
end;
function TAATree<TKey, TValue>.ContainsKeys(const AKeys: TEnumerable<TKey>;
ASearchType: TSearchType): Boolean;
var
Key: TKey;
begin
case ASearchType of
stAll:
begin
for Key in AKeys do
if not ContainsKey(Key) then
Exit(False);
Exit(True);
end;
stAny:
begin
for Key in AKeys do
if ContainsKey(Key) then
Exit(True);
Exit(False);
end;
end;
end;
function TAATree<TKey, TValue>.ContainsValue(const Value: TValue; AEqualityComparer: IEqualityComparer<TValue> = nil): Boolean;
var
h: TItemHandle;
begin
if AEqualityComparer=nil then
AEqualityComparer := TComparerUtils.DefaultEqualityComparer<TValue>;
if not First(h) then
result := False
else
repeat
result := AEqualityComparer.Equals(Value, Values[h]);
until result or not Next(h);
end;
function TAATree<TKey, TValue>.MinKey: TKey;
begin
result := Keys[FindMin];
end;
function TAATree<TKey, TValue>.MaxKey: TKey;
begin
result := Keys[FindMax];
end;
procedure TAATree<TKey, TValue>.Remove(const AKey: TKey);
begin
Delete(Find(AKey));
end;
procedure TAATree<TKey, TValue>.Remove(const AKeys: TArray<TKey>);
var
i: Integer;
begin
for i := Low(AKeys) to High(AKeys) do
Remove(AKeys[i]);
end;
procedure TAATree<TKey, TValue>.Remove(const AKeys: TEnumerable<TKey>);
var
Key: TKey;
begin
for Key in AKeys do
Remove(Key);
end;
{ TAATree<TKey, TValue>.TPairEnumerator }
constructor TAATree<TKey, TValue>.TPairEnumerator.Create(const ATree: TAATree<TKey, TValue>);
begin
FTree := ATree;
FCurrentItem := 0;
end;
function TAATree<TKey, TValue>.TPairEnumerator.DoMoveNext: Boolean;
begin
if FCurrentItem=0 then
result := FTree.First(FCurrentItem)
else
result := (FCurrentItem<>-1) and FTree.Next(FCurrentItem);
end;
function TAATree<TKey, TValue>.TPairEnumerator.DoGetCurrent: TPair<TKey, TValue>;
begin
result := FTree.Pairs[FCurrentItem];
end;
{ TAATree<TKey, TValue>.TKeyEnumerator }
constructor TAATree<TKey, TValue>.TKeyEnumerator.Create(const ATree: TAATree<TKey, TValue>);
begin
FTree := ATree;
FCurrentItem := 0;
end;
function TAATree<TKey, TValue>.TKeyEnumerator.DoGetCurrent: TKey;
begin
result := FTree.Keys[FCurrentItem];
end;
function TAATree<TKey, TValue>.TKeyEnumerator.DoMoveNext: Boolean;
begin
if FCurrentItem=0 then
result := FTree.First(FCurrentItem)
else
result := (FCurrentItem<>-1) and FTree.Next(FCurrentItem);
end;
{ TAATree<TKey, TValue>.TValueEnumerator }
constructor TAATree<TKey, TValue>.TValueEnumerator.Create(const ATree: TAATree<TKey, TValue>);
begin
FTree := ATree;
FCurrentItem := 0;
end;
function TAATree<TKey, TValue>.TValueEnumerator.DoGetCurrent: TValue;
begin
result := FTree.Values[FCurrentItem];
end;
function TAATree<TKey, TValue>.TValueEnumerator.DoMoveNext: Boolean;
begin
if FCurrentItem=0 then
result := FTree.First(FCurrentItem)
else
result := (FCurrentItem<>-1) and FTree.Next(FCurrentItem);
end;
{ TAATree<TKey, TValue>.TKeyCollection }
constructor TAATree<TKey, TValue>.TKeyCollection.Create(const ATree: TAATree<TKey, TValue>);
begin
inherited Create;
FTree := ATree;
end;
function TAATree<TKey, TValue>.TKeyCollection.DoGetEnumerator: TEnumerator<TKey>;
begin
result := TKeyEnumerator.Create(FTree);
end;
{ TAATree<TKey, TValue>.TValueCollection }
constructor TAATree<TKey, TValue>.TValueCollection.Create(const ATree: TAATree<TKey, TValue>);
begin
inherited Create;
FTree := ATree;
end;
function TAATree<TKey, TValue>.TValueCollection.DoGetEnumerator: TEnumerator<TValue>;
begin
result := TValueEnumerator.Create(FTree);
end;
{ TOrderedMapClass<TKey, TValue> }
procedure TOrderedMapClass<TKey, TValue>.Add(const AKey: TKey; const AValue: TValue);
begin
FTree.Add(AKey, AValue);
end;
procedure TOrderedMapClass<TKey, TValue>.Add(const ACollection: TEnumerable<TPair<TKey, TValue>>);
begin
FTree.Add(ACollection);
end;
procedure TOrderedMapClass<TKey, TValue>.AddOrSetValue(const AKey: TKey; const AValue: TValue);
begin
FTree.AddOrSetValue(AKey, AValue);
end;
procedure TOrderedMapClass<TKey, TValue>.Clear;
begin
FTree.Clear;
end;
function TOrderedMapClass<TKey, TValue>.ContainsKey(const Key: TKey): Boolean;
begin
result := FTree.ContainsKey(Key);
end;
function TOrderedMapClass<TKey, TValue>.ContainsKeys(const AKeys: array of TKey; ASearchType: TSearchType): Boolean;
begin
result := FTree.ContainsKeys(AKeys, ASearchType);
end;
function TOrderedMapClass<TKey, TValue>.ContainsKeys(const AKeys: TEnumerable<TKey>; ASearchType: TSearchType): Boolean;
begin
result := FTree.ContainsKeys(AKeys, ASearchType);
end;
function TOrderedMapClass<TKey, TValue>.ContainsValue(const Value: TValue; AEqualityComparer: IEqualityComparer<TValue>): Boolean;
begin
result := FTree.ContainsValue(Value, AEqualityComparer);
end;
constructor TOrderedMapClass<TKey, TValue>.Create;
begin
Create(IComparer<TKey>(nil));
end;
constructor TOrderedMapClass<TKey, TValue>.Create(AComparer: IComparer<TKey>);
begin
inherited Create;
FTree := TAATree<TKey,TValue>.Create(AComparer);
FTree.OnKeyNotify := treeOnKeyNotify;
FTree.OnValueNotify := treeOnValueNotify;
end;
constructor TOrderedMapClass<TKey, TValue>.Create(
const ACollection: TEnumerable<TPair<TKey, TValue>>;
AComparer: IComparer<TKey>);
begin
inherited Create;
FTree := TAATree<TKey,TValue>.Create(ACollection, AComparer);
FTree.OnKeyNotify := treeOnKeyNotify;
FTree.OnValueNotify := treeOnValueNotify;
end;
destructor TOrderedMapClass<TKey, TValue>.Destroy;
begin
FreeAndNil(FTree);
inherited;
end;
function TOrderedMapClass<TKey, TValue>.DoGetEnumerator: TEnumerator<TPair<TKey, TValue>>;
begin
result := FTree.DoGetEnumerator;
end;
function TOrderedMapClass<TKey, TValue>.First(var AKey: TKey): Boolean;
var
h: TItemHandle;
begin
result := FTree.First(h);
if result then
AKey := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.GetCount: integer;
begin
result := FTree.Count;
end;
function TOrderedMapClass<TKey, TValue>.GetItem(const AKey: TKey): TValue;
begin
result := FTree.Items[AKey];
end;
function TOrderedMapClass<TKey, TValue>.GetKeyCollection: TKeyCollection;
begin
result := FTree.GetKeyCollection;
end;
function TOrderedMapClass<TKey, TValue>.GetRoot(var Key: TKey): Boolean;
var
h: TItemHandle;
begin
result := FTree.GetRoot(h);
if result then
Key := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.GetTreeHeight: integer;
begin
result := FTree.TreeHeight;
end;
function TOrderedMapClass<TKey, TValue>.GetValueCollection: TValueCollection;
begin
result := FTree.GetValueCollection;
end;
function TOrderedMapClass<TKey, TValue>.Last(var AKey: TKey): Boolean;
var
h: TItemHandle;
begin
result := FTree.Last(h);
if result then
AKey := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.GetLeftChild(const AKey: TKey; var AChild: TKey): Boolean;
var
h: TItemHandle;
begin
result := FTree.GetLeftChild(FTree.Find(AKey), h);
if result then
AChild := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.Max: TPair<TKey, TValue>;
begin
result := FTree.Pairs[FTree.FindMax];
end;
function TOrderedMapClass<TKey, TValue>.Min: TPair<TKey, TValue>;
begin
result := FTree.Pairs[FTree.FindMin];
end;
function TOrderedMapClass<TKey, TValue>.FindKeyByIndex(Index: integer): TKey;
var
h: TItemHandle;
begin
h := FTree.FindMin;
while Index > 0 do
begin
FTree.Next(h);
dec(Index);
end;
result := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.Next(const AKey: TKey; var ANewKey: TKey): Boolean;
var
h: TItemHandle;
begin
h := FTree.Find(AKey);
result := FTree.Next(h);
if result then
ANewKey := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.GetParent(const AKey: TKey; var AParent: TKey): Boolean;
var
h: TItemHandle;
begin
result := FTree.GetParent(FTree.Find(AKey), h);
if result then
AParent := FTree.Keys[h];
end;
function TOrderedMapClass<TKey, TValue>.Prev(const AKey: TKey; var ANewKey: TKey): Boolean;
var
h: TItemHandle;
begin
h := FTree.Find(AKey);
result := FTree.Prev(h);
if result then
ANewKey := FTree.Keys[h];
end;
procedure TOrderedMapClass<TKey, TValue>.Remove(const AKeys: TArray<TKey>);
begin
FTree.Remove(AKeys);
end;
procedure TOrderedMapClass<TKey, TValue>.Remove(const AKeys: TEnumerable<TKey>);
begin
FTree.Remove(AKeys);
end;
procedure TOrderedMapClass<TKey, TValue>.Remove(const AKey: TKey);
begin
FTree.Remove(AKey);
end;
function TOrderedMapClass<TKey, TValue>.GetRightChild(const AKey: TKey; var AChild: TKey): Boolean;
var
h: TItemHandle;
begin
result := FTree.GetRightChild(FTree.Find(AKey), h);
if result then
AChild := FTree.Keys[h];
end;
procedure TOrderedMapClass<TKey, TValue>.SetItem(const AKey: TKey; const Value: TValue);
begin
FTree.Values[FTree.Find(AKey)] := Value;
end;
function TOrderedMapClass<TKey, TValue>.TryGetValue(const Key: TKey; out Value: TValue): Boolean;
begin
result := FTree.TryGetValue(Key, Value);
end;
function TOrderedMapClass<TKey, TValue>.GetOwnsKeys: boolean;
begin
result := doOwnsKeys in FOwnerships;
end;
function TOrderedMapClass<TKey, TValue>.GetOwnsValues: boolean;
begin
result := doOwnsValues in FOwnerships;
end;
procedure TOrderedMapClass<TKey, TValue>.SetOwnsKeys(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<TKey> then
raise Exception.Create('Generic type is not a class.');
if Value
then include(FOwnerships, doOwnsKeys)
else exclude(FOwnerships, doOwnsKeys);
end;
procedure TOrderedMapClass<TKey, TValue>.SetOwnsValues(const Value: boolean);
begin
if Value and not TRttiUtils.IsInstance<TValue> then
raise Exception.Create('Generic type is not a class.');
if Value
then include(FOwnerships, doOwnsValues)
else exclude(FOwnerships, doOwnsValues);
end;
procedure TOrderedMapClass<TKey, TValue>.treeOnKeyNotify(Sender: TObject; const Key: TKey; Action: TCollectionNotification);
begin
if Assigned(FOnKeyNotify) then
FOnKeyNotify(Self, Key, Action);
if (Action = TCollectionNotification.cnRemoved) and (doOwnsKeys in FOwnerships) then
PObject(@Key)^.DisposeOf;
end;
procedure TOrderedMapClass<TKey, TValue>.treeOnValueNotify(Sender: TObject; const Value: TValue; Action: TCollectionNotification);
begin
if Assigned(FOnValueNotify) then
FOnValueNotify(Self, Value, Action);
if (Action = TCollectionNotification.cnRemoved) and (doOwnsValues in FOwnerships) then
PObject(@Value)^.DisposeOf;
end;
end.
|
{ Canonicalize an xml document
The acronym for canonicalization is "C14N"
An xml document after C14N must be:
- encoded in UTF-8 only
- xml declaration removed
- entities expanded to their character equivalent
- CDATA sections replaced by character equivalent
- special < > and " entities encoded
- attributes normalized as if by validating parser
- empty elements opened with start and end tags
- namespace declarations and attributes sorted
Experimental!
Author: Nils Haeck M.Sc.
Copyright (c) 2010 - 2011 Simdesign B.V. (www.simdesign.nl)
It is NOT allowed under ANY circumstances to publish, alter or copy this code
without accepting the license conditions in accompanying LICENSE.txt
first!
This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied.
Please visit http://www.simdesign.nl/xml.html for more information.
}
unit NativeXmlC14n;
interface
uses
SysUtils, NativeXml, sdDebug;
type
TNativeXmlC14N = class(TsdDebugComponent)
public
class procedure Canonicalize(AXml: TNativeXml);
end;
implementation
{ TNativeXmlC14N }
class procedure TNativeXmlC14N.Canonicalize(AXml: TNativeXml);
var
Decl: TXmlNode;
DTD: TsdDocType;
DtdEntityNodes: array of TXmlNode;
i, j, TotalNodeCount, CharDataCount, ReferencesCount: integer;
Node: TXmlNode;
CharData: TsdCharData;
SubstituteText: Utf8String;
begin
TotalNodeCount := 0;
CharDataCount := 0;
ReferencesCount := 0;
// encode in UTF-8 only - this is already achieved by the parser
// xml compacted
//AXml.XmlFormat := xfCompact;
// remove xml declaration
Decl := AXml.RootNodes[0];
if Decl is TsdDeclaration then
begin
AXml.RootNodes.Delete(0);
end;
// recursively expand entities to their character equivalent:
// find dtdentity nodes in the dtd
DTD := TsdDocType(AXml.RootNodes.ByType(xeDocType));
if assigned(DTD) then
begin
j := 0;
SetLength(DtdEntityNodes, j);
for i := 0 to DTD.NodeCount - 1 do
if DTD.Nodes[i] is TsdDtdEntity then
begin
inc(j);
SetLength(DtdEntityNodes, j);
DtdEntityNodes[j - 1] := TsdDtdEntity(DTD.Nodes[i]);
end;
end;
// find references
Node := AXml.FindFirst;
while assigned(Node) do
begin
inc(TotalNodeCount);
// check for entity references
if Node is TsdCharData then
begin
inc(CharDataCount);
// non-standard references usually come from entity references in the dtd
if TsdCharData(Node).HasNonStandardReferences then
begin
inc(ReferencesCount);
CharData := TsdCharData(Node);
// substitute chardata value using the references
SubstituteText := AnsiDequotedStr(CharData.GetValueUsingReferences(DtdEntityNodes), '"');
Node := AXml.ParseSubstituteContentFromNode(Chardata, SubstituteText);
end;
end;
Node := AXml.FindNext(Node);
end;
// replace CDATA sections by character equivalent
// encode special < > and " entities
// normalize attributes as if by validating parser
// open empty elements with start and end tags
// sort namespace declarations and attributes
AXml.DoDebugOut(AXml, wsInfo, format('total node count: %d, chardata count: %d, references count: %d',
[TotalNodeCount, CharDataCount, ReferencesCount]));
AXml.DoDebugOut(AXml, wsInfo, 'C14N created');
end;
end.
|
unit ReadMeVar;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, StdCtrls;
type
TReadMeForm = class(TForm)
Memo1: TMemo;
StatusBar1: TStatusBar;
private
{ Private declarations }
public
{ Public declarations }
procedure Perform;
end;
var
ReadMeForm: TReadMeForm;
ReadMeName : string = 'readme.txt';
implementation
{$R *.dfm}
procedure TReadMeForm.Perform;
begin
Memo1.Clear;
if FileExists(ReadMeName) then
begin
Memo1.Lines.LoadFromFile(ReadMeName);
Show;
end;
end;
end.
|
unit suminfo;
interface
type
TSumInformation = class
protected
private
fname : WideString;
fsize : UInt64;
function GetSizeHumanReadable(): WideString;
public
constructor Create(Name : WideString);
destructor Destroy; override;
property Size: UInt64 read FSize write FSize;
property SizeHumanReadable: WideString read GetSizeHumanReadable;
property Name: WideString read FName;
function AddSize(Value : Cardinal): UInt64;
end;
implementation
uses
IniMangt,
SysUtils,
InternalTypes;
constructor TSumInformation.Create(Name : WideString);
begin
fname := Name;
fsize := 0;
end;
destructor TSumInformation.Destroy;
begin
inherited Destroy;
end;
function TSumInformation.AddSize(Value : Cardinal): UInt64;
begin
fsize := fsize + Value div 1024;
Result := fsize;
end;
function TSumInformation.GetSizeHumanReadable(): WideString;
begin
Result := GetSizeHRk(fSize);
end;
end. |
unit PictureOrDocumentLoadDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, TMultiP, ExtCtrls, Buttons, Types, MemoDialog;
type
TLoadPicturesOrDocumentsDialog = class(TForm)
InstructionLabel: TLabel;
OK: TBitBtn;
CancelButton: TBitBtn;
ScrollBox: TScrollBox;
ItemPanel4: TPanel;
Panel8: TPanel;
PMultiImage4: TPMultiImage;
CheckBox4: TCheckBox;
Memo4: TMemo;
Button4: TButton;
ItemPanel5: TPanel;
Panel10: TPanel;
PMultiImage5: TPMultiImage;
CheckBox5: TCheckBox;
Memo5: TMemo;
Button5: TButton;
ItemPanel6: TPanel;
Panel12: TPanel;
PMultiImage6: TPMultiImage;
CheckBox6: TCheckBox;
Memo6: TMemo;
Button6: TButton;
ItemPanel1: TPanel;
Panel7: TPanel;
PMultiImage1: TPMultiImage;
CheckBox1: TCheckBox;
Memo1: TMemo;
Button1: TButton;
ItemPanel2: TPanel;
Panel3: TPanel;
PMultiImage2: TPMultiImage;
CheckBox2: TCheckBox;
Memo2: TMemo;
Button2: TButton;
ItemPanel3: TPanel;
Panel5: TPanel;
PMultiImage3: TPMultiImage;
CheckBox3: TCheckBox;
Memo3: TMemo;
Button3: TButton;
ItemLabel1: TLabel;
ItemLabel2: TLabel;
ItemLabel3: TLabel;
ItemLabel4: TLabel;
ItemLabel5: TLabel;
ItemLabel6: TLabel;
MemoDialogBox: TMemoDialogBox;
DirectoryLabel1: TLabel;
DirectoryLabel2: TLabel;
DirectoryLabel3: TLabel;
DirectoryLabel4: TLabel;
DirectoryLabel5: TLabel;
DirectoryLabel6: TLabel;
ItemPanel8: TPanel;
ItemLabel8: TLabel;
DirectoryLabel8: TLabel;
Panel2: TPanel;
PMultiImage8: TPMultiImage;
CheckBox8: TCheckBox;
Memo8: TMemo;
Button8: TButton;
ItemPanel7: TPanel;
ItemLabel7: TLabel;
DirectoryLabel7: TLabel;
Panel6: TPanel;
PMultiImage7: TPMultiImage;
CheckBox7: TCheckBox;
Memo7: TMemo;
Button7: TButton;
ItemPanel9: TPanel;
ItemLabel9: TLabel;
DirectoryLabel9: TLabel;
Panel11: TPanel;
PMultiImage9: TPMultiImage;
CheckBox9: TCheckBox;
Memo9: TMemo;
Button9: TButton;
ItemPanel10: TPanel;
ItemLabel10: TLabel;
DirectoryLabel10: TLabel;
Panel14: TPanel;
PMultiImage10: TPMultiImage;
CheckBox10: TCheckBox;
Memo10: TMemo;
Button10: TButton;
ItemPanel11: TPanel;
ItemLabel11: TLabel;
DirectoryLabel11: TLabel;
Panel16: TPanel;
PMultiImage11: TPMultiImage;
CheckBox11: TCheckBox;
Memo11: TMemo;
Button11: TButton;
ItemPanel12: TPanel;
ItemLabel12: TLabel;
DirectoryLabel12: TLabel;
Panel18: TPanel;
PMultiImage12: TPMultiImage;
CheckBox12: TCheckBox;
Memo12: TMemo;
Button12: TButton;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ExpandMemoDialogBox(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
OriginalItemList : TStringList;
SwisSBLKey : String;
ItemType : Integer;
ItemTypeStr : String; {Document or picture}
Procedure InitializeForm;
Procedure AddItem(ItemName : String);
Procedure GetSelectedItems(SelectedItems : TList);
end;
var
LoadPicturesOrDocumentsDialog: TLoadPicturesOrDocumentsDialog;
implementation
{$R *.DFM}
uses Utilitys, DataModule, PASUtils, PASTypes;
{===================================================}
Procedure TLoadPicturesOrDocumentsDialog.FormCreate(Sender: TObject);
begin
OriginalItemList := TStringList.Create;
end;
{===================================================}
Procedure TLoadPicturesOrDocumentsDialog.AddItem(ItemName : String);
begin
OriginalItemList.Add(ItemName);
end;
{===================================================}
Procedure TLoadPicturesOrDocumentsDialog.InitializeForm;
var
I : Integer;
TempComponentName : String;
begin
If (OriginalItemList.Count = 1)
then
begin
Caption := 'The following ' + ItemTypeStr + ' is new for ' +
ConvertSwisSBLToDashDot(SwisSBLKey);
InstructionLabel.Caption := 'The following new ' + ItemTypeStr +
' has been found for this parcel.' +
' Please click OK to add it to the ' +
ItemTypeStr + 's page or click Cancel to not add it.' +
' You may enter notes right under the selected ' +
ItemTypeStr + '.';
end
else
begin
Caption := 'The following ' + ItemTypeStr + 's are new for ' +
ConvertSwisSBLToDashDot(SwisSBLKey);
InstructionLabel.Caption := 'The following new ' + ItemTypeStr +
's have been found for this parcel.' +
' Please select which ones you would like to be ' +
'automatically added for you.' +
' You may enter notes right under each of the selected ' +
ItemTypeStr + 's.';
end; {else of If (OriginalItemList.Count = 1)}
ScrollBox.VertScrollBar.Visible := (OriginalItemList.Count > 3);
{FXX08182002-1: Make sure they don't go past the number of available pictures.
Also, put it in a try...except.}
For I := 0 to (OriginalItemList.Count - 1) do
If (I <= 11)
then
try
TempComponentName := 'ItemPanel' + IntToStr(I + 1);
TPanel(FindComponent(TempComponentName)).Visible := True;
TempComponentName := 'PMultiImage' + IntToStr(I + 1);
try
TPMultiImage(FindComponent(TempComponentName)).ImageName := OriginalItemList[I];
except
TPMultiImage(FindComponent(TempComponentName)).ImageName := '';
end;
TempComponentName := 'ItemLabel' + IntToStr(I + 1);
TLabel(FindComponent(TempComponentName)).Caption := StripPath(OriginalItemList[I]);
{CHG07132001-1: Allow searching subdirectories and picture masks.}
TempComponentName := 'DirectoryLabel' + IntToStr(I + 1);
TLabel(FindComponent(TempComponentName)).Caption := ReturnPath(OriginalItemList[I]);
{Default the check box to selected.}
TempComponentName := 'CheckBox' + IntToStr(I + 1);
TCheckBox(FindComponent(TempComponentName)).Checked := True;
except
end; {For I := 0 to (OriginalItemList.Count - 1) do}
If (OriginalItemList.Count > 12)
then MessageDlg('There are more than 12 new ' + ItemTypeStr + 's for this parcel.' + #13 +
'After loading these ' + ItemTypeStr + 's, please exit the parcel and come back to it to load the rest.',
mtWarning, [mbOK], 0);
end; {InitializeForm}
{===========================================================}
Procedure TLoadPicturesOrDocumentsDialog.ExpandMemoDialogBox(Sender: TObject);
{FXX04252001-1: Make the expansion of the memo box work.}
var
TempComponentName, ComponentNumber : String;
TempMemo : TMemo;
I : Integer;
begin
TempComponentName := TButton(Sender).Name;
ComponentNumber := TempComponentName[Length(TempComponentName)];
TempComponentName := 'Memo' + ComponentNumber;
TempMemo := TMemo(FindComponent(TempComponentName));
MemoDialogBox.SetMemoLines(TempMemo.Lines);
If MemoDialogBox.Execute
then
begin
TempMemo.Lines.Clear;
For I := 0 to (MemoDialogBox.MemoLines.Count - 1) do
TempMemo.Lines.Add(MemoDialogBox.MemoLines[I]);
{By default the cursor was appearing at the end of
the memo and the text was not visible. So,
this tricks Windows into putting the cursor at the
front.}
TempMemo.SelStart := 0;
TempMemo.SelLength := 0;
end; {If MemoDialogBox.Execute}
end; {ExpandMemoDialogBox}
{===================================================}
Procedure TLoadPicturesOrDocumentsDialog.GetSelectedItems(SelectedItems : TList);
var
I : Integer;
TempComponentName : String;
SelectedPicsOrDocsPtr : SelectedPicsOrDocsPointer;
begin
{Find the items that are selected.}
{CHG08182002-1: Allow for up to 12 pictures per parcel.}
For I := 1 to 12 do
begin
TempComponentName := 'CheckBox' + IntToStr(I);
If TCheckBox(FindComponent(TempComponentName)).Checked
then
begin
New(SelectedPicsOrDocsPtr);
with SelectedPicsOrDocsPtr^ do
begin
TempComponentName := 'DirectoryLabel' + IntToStr(I);
DirectoryName := TLabel(FindComponent(TempComponentName)).Caption;
{FXX11052002-1: Add the directory name to the file name.}
TempComponentName := 'ItemLabel' + IntToStr(I);
FileName := AddDirectorySlashes(DirectoryName) +
TLabel(FindComponent(TempComponentName)).Caption;
TempComponentName := 'Memo' + IntToStr(I);
Notes := TMemo(FindComponent(TempComponentName)).Text;
end; {with SelectedPicsOrDocsPtr^ do}
SelectedItems.Add(SelectedPicsOrDocsPtr);
end; {If TCheckBox(FindComponent(TempComponentName)).Checked}
end; {For I := 1 to 12 do}
end; {GetSelectedItems}
{===========================================================}
Procedure TLoadPicturesOrDocumentsDialog.FormClose( Sender: TObject;
var Action: TCloseAction);
begin
OriginalItemList.Free;
end;
end. |
{Вычисление собственных чисел и собственных векторов}
{Программа написана для компиляторов Turbo Pascal/Borland Pascal фирмы Borland inc.}
uses Crt;
type
MatrType = array[1..3, 1..3] of Real; {Тип, описывающий матрицу [3x3]}
VectorType = array[1..3] of Real; {Вектор из 3-х элементов}
const
{исходная матрица}
MyMatr:MatrType =
((1, 2, -1),
(3, 0, 2),
(4, -2, 5));
{единичная матрица}
EM:MatrType =
((1, 0, 0),
(0, 1, 0),
(0, 0, 1));
{размерность заданной матрицы}
N : integer = 3;
{вычисление характеристического полинома в точке X
(используется в решении уравнения P(lambda)=0 методом Ньютона)}
Function F(X : Real; P : VectorType) : Real;
{Входные параметры:
X - значение X,
P - коэффициенты p1,..,pn (элементы матрицы Фробениуса).
Выходной параметр:
F - значение характеристического полинома в точке X.}
begin
F := (-1) * (Sqr(X) * X - P[1] * Sqr(X) - P[2] * X - P[3]);
end;
{вычисление значения производной первого порядка
от характеристического полинома в точке X
(используется в решении уравнения D(lambda)=0 методом Ньютона)}
Function dF(X : Real; P : VectorType) : Real;
{Входные параметры:
X - значение X,
P - коэффициенты p1,..,pn (элементы матрицы Фробениуса).
Выходной параметр:
dF - значение производной первого порядка от
характеристического полинома в точке X.}
begin
dF := (-1) * (3 * Sqr(X) - 2 * P[1] * X - P[2]);
end;
{умножение матрицы на матрицу}
Procedure MxM(A, B : MatrType; var X : MatrType);
{Входные параметры:
A,B - перемножаемые матрицы.
Выходной параметр:
X - матрица - результат операции умножения.}
var
i, j, k : integer;
s : real;
begin
for i := 1 to N do
for j := 1 to N do
begin
S := 0;
for k := 1 to N do
s := s + A[i, k] * B[k, j];
X[i, j] := s;
end;
end;
{умножение матрицы на вектор}
Procedure MxV(A: MatrType; V: VectorType; var X: VectorType);
{Входные параметры:
A - матрица (первый множитель),
V - вектор (второй множитель),
X - вектор, в котором хранятся результаты вычислений}
var
i, j : integer;
s : real;
begin
for i := 1 to N do
begin
s := 0;
for j := 1 to N do
s := s + A[i, j] * v[j];
X[i] := s;
end;
end;
Procedure Lab3(Matr : MatrType; var L : VectorType; var X, Ax, Lx : MatrType);
(*Входные параметры:
Matr:MatrType - квадратная матрица, для которой
находятся собственные значения;
Выходные параметры:
L:VectorType - массив [1..N] собственных чисел;
X:MatrType - двумерный массив, строки которого содержат
собственные векторы
Ax,Lx:MatrType - матрицы, строки которых содержат результаты проверки
A*x(i) и L(i)*x(i) соответственно*)
var
i, j, k, h : integer; {вспомогательные переменные}
P : MatrType; {матрица Фробениуса}
Pvec : VectorType; {вектор коэффициентов (p1,p2,p3)}
A, B, A1, B1 : real; {границы интервалов (метод Ньютона)}
E : real; {точность вычисления (метод Ньютона)}
lam0, lam1 : real; {вспомогательные переменные (метод Ньютона)}
S : MatrType; {неособенная матрица S=M(n-1)*...*M1}
M, M1 : MatrType; {матрицы, используемые в преобразовании подобия}
Yi : VectorType; {собственный вектор матрицы Фробениуса,
соответствующий i-му собственному числу}
Xi : VectorType; {i-й собственный вектор исходной матрицы}
Axi, Lxi : VectorType; {векторы с результатами проверки правильности вычисления
i-го собственного вектора исходной матрицы}
{рекурсивная процедура вычисления
матрицы Фробениуса и неособенной матрицы S}
procedure Frob(A : MatrType; Num : integer);
var i, j : integer;
begin
if Num - 1 > 0 then
begin
M := EM;
M1 := EM;
for i := 1 to N do
begin
{Вычисление матриц M(n-1),...,M1}
if i = Num - 1 then
M[Num - 1, i] := 1 / A[Num, Num - 1]
else
M[Num - 1, i] := -A[Num, i] / A[Num, Num - 1];
{Вычисление матриц M(n-1)^-1,...,M1^-1}
M1[Num - 1, i] := A[Num, i];
end;
{Вычисление неособенной матрицы S}
MxM(S, M, S);
{Преобразование подобия}
MxM(A, M, A);
MxM(M1, A, A);
P := A;
Frob(A, Num - 1);
end;
end;
Begin
clrscr;
{нахождение матрицы Фробениуса}
S := EM;
Frob(Matr, N);
{выделение вектора p=(p1,p2,p3)}
for i := 1 to N do
Pvec[i] := P[1, i];
{решение уравнения P(lambda)=0 с использованием метода Ньютона
для нахождения собственных чисел}
A := -5; B := 5; {интервал для поиска корней}
h := 10; {количество узлов}
E := 0.0001; {точность решения}
j := 1;
for i := 0 to h do
{отделение корней}
if F((A + i * (B - A) / h), Pvec) *
F((A + (i + 1) * (B - A) / h), Pvec) < 0 then
begin
{[A1, B1] - интервал, на котором находится корень}
A1 := A + i * (B - A) / h;
B1 := A + (i + 1) * (B - A) / h;
{метод Ньютона}
lam1 := (A1 + B1) / 2;
repeat
lam0 := lam1;
lam1 := lam0 - F(lam0, Pvec) / dF(lam0, Pvec);
until Abs(lam1 - lam0) < E;
{внесение найденного i-го собственного
числа в массив собственных чисел}
L[j] := lam1;
j := j + 1;
end;
{нахождение собственных векторов}
for i := 1 to N do
begin
{нахождение i-го собственного вектора матрицы Фробениуса}
Yi[N] := 1;
for j := N - 1 downto 1 do
Yi[j] := L[i] * Yi[j + 1];
{нахождение i-го собственного вектора исходной матрицы
путем умножения неособенной матрицы S=M(n-1) * ... * M1
на соответствующий собственный вектор матрицы Фробениуса}
MxV(S, Yi, Xi);
for j := 1 to N do
X[i, j] := Xi[j];
{Проверка правильности вычисления собственных векторов}
MxV(Matr, Xi, Axi);
for j := 1 to N do
begin
Ax[i, j] := Axi[j];
Lx[i, j] := L[i] * Xi[j];
end;
end;
End;
var
(* Выходные данные: *)
X : MatrType; {Матрица собственных векторов}
L : VectorType; {Вектор собственных чисел}
Ax, Lx : MatrType;
(* Вспомогательные переменные *)
{N:Integer; {Размерность матрицы}
i, j : Integer;
Begin
N := 3;
Lab3(MyMatr, L, X, Ax, Lx); {вычисление собственных чисел и векторов}
{Вывод результатов}
WriteLn('Собственные числа:');
for i := 1 to N do
WriteLn('L(', i, ') = ', L[i]:1:5);
Writeln;
WriteLn('Собственные векторы:');
for i := 1 to N do
begin
write('x(', i, ') = ');
for j := 1 to N do
Write(X[i, j]:1:5, ' ');
writeln;
end;
Writeln;
Writeln('Проверка A * x(i)=L(i) * x(i):');
for i := 1 to N do
begin
write('A * x(', i, ') = ');
for j := 1 to N do
write(Ax[i, j]:2:4, ' ');
writeln;
write('L(', i, ') * x(', i, ') = ');
for j := 1 to N do
write(Lx[i, j]:2:4, ' ');
writeln;
end;
readln;
End.
|
unit adot.Types;
{ Definition of classes/record types:
TCustomCachable = class
Basic class with support ICachable interface.
TEmptyRec = record
types.
}
interface
uses
System.Generics.Defaults,
System.SysUtils;
const
NullGuid: TGUID = '{00000000-0000-0000-0000-000000000000}';
RecordTypes = [tkInteger, tkChar, tkEnumeration, tkFloat, tkSet, tkMethod, tkWChar, tkRecord, tkInt64, tkPointer, tkProcedure];
type
{ types }
TBoolean = (BoolTrue, BoolFalse, BoolAny);
TCycleAction = (caContinue, caBreak);
TIEMode = (iemIE7, iemIE8, iemIE9, iemIE10, iemIE11, iemIEInstalled);
TEmptyRec = record end;
const
EmptyRec : TEmptyRec = ();
type
TSetOfByte = set of Byte;
TProcConst<T> = reference to procedure (const Arg1: T);
TProcConst<T1,T2> = reference to procedure (const Arg1: T1; const Arg2: T2);
TProcConst<T1,T2,T3> = reference to procedure (const Arg1: T1; const Arg2: T2; const Arg3: T3);
TProcVar<T> = reference to procedure (var Arg1: T);
TProcVar<T1,T2> = reference to procedure (var Arg1: T1; var Arg2: T2);
TProcVar<T1,T2,T3> = reference to procedure (var Arg1: T1; var Arg2: T2; var Arg3: T3);
TProcVar1<T> = reference to procedure (var Arg1: T);
TProcVar1<T1,T2> = reference to procedure (Arg1: T1; var Arg2: T2);
TProcVar1<T1,T2,T3> = reference to procedure (Arg1: T1; Arg2: T2; var Arg3: T3);
TFuncCompareValues<T> = reference to function(const Left,Right: T): integer;
TFuncFilterValueIndex<T> = reference to function(const Value: T; ValueIndex: integer): boolean; { True = Accepts item }
EForbiddenOperation = class(Exception);
{ interfaces }
IInterfacedObject<T> = interface(IInterface)
['{A6E4E6FF-DE6E-41E8-9B30-69365C0C397C}']
function GetData: T;
procedure SetData(const AData: T);
function GetRefCount: integer;
function Extract: T;
property Data: T read GetData write SetData;
property ReferenceCount: integer read GetRefCount;
end;
IArithmetic<T> = interface(IInterface)
['{EA1E0AFC-90E4-4497-9194-ACCDF3012E08}']
function Add(Left: T; Right: T): T;
function Subtract(Left: T; Right: T): T;
function Multiply(Left: T; Right: T): T;
function Divide(Left: T; Right: T): T;
function Negative(Value: T): T;
end;
{ classes }
TCustomArithmetic<T> = class(TSingletonImplementation, IArithmetic<T>)
public
function Add(Left: T; Right: T): T; virtual; abstract;
function Subtract(Left: T; Right: T): T; virtual; abstract;
function Multiply(Left: T; Right: T): T; virtual; abstract;
function Divide(Left: T; Right: T): T; virtual; abstract;
function Negative(Value: T): T; virtual; abstract;
end;
{ A non-reference-counted IInterface implementation. }
TNRCInterfacedObject = TSingletonImplementation;
TCopyFileInfo = record
FileSize : int64;
Copied : int64;
SrcFileName : string;
DstFileName : string;
end;
TCopyFileProgressProc = reference to procedure(const Info: TCopyFileInfo; var Cancel: boolean);
TCopyStreamProgressProc = reference to procedure(const Transferred: int64; var Cancel: boolean);
implementation
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Tether.Comm;
interface
{$IFNDEF IOS}
{$DEFINE BT_PLATFORM}
{$ENDIF}
uses
System.SysUtils, System.Classes, System.Generics.Collections, System.Types,
{$IFDEF BT_PLATFORM}
System.SyncObjs, System.Bluetooth,
{$ENDIF}
IPPeerAPI;
type
ETetheringCommException = class(Exception);
/// <summary>Enumeration for IP Version values</summary>
TCommIPVersion = TIPVersionPeer;
/// <summary> Event to pre-process and post-process the buffered data.</summary>
/// <remarks> This function when defined should process the DataBuffer, and put it's equivalent data into the Result.</remarks>
TTetheringDataEvent = function(const Sender: TObject; const ADataBuffer: TByteDynArray): TByteDynArray of object;
/// <summary> Event to pre-process and post-process the stream data.</summary>
/// <remarks> This function when defined should process the InputStream, and put it's equivalent data into the OutputStream.</remarks>
TTetheringStreamEvent = procedure(const Sender: TObject; const AInputStream, AOutputStream: TStream) of object;
TTetheringCustomComm = class
private
FOnAfterReceiveData: TTetheringDataEvent;
FOnBeforeSendData: TTetheringDataEvent;
FOnAfterReceiveStream: TTetheringStreamEvent;
FOnBeforeSendStream: TTetheringStreamEvent;
protected
FSecured: Boolean;
/// <summary>Last used Target for a connection</summary>
FTarget: string;
function DoConnect(const ATarget: string): Boolean; virtual; abstract;
procedure DoDisconnect; virtual; abstract;
function GetConnected: Boolean; virtual; abstract;
function DoReadData: TBytes; virtual; abstract;
procedure DoWriteData(const AData: TBytes); virtual; abstract;
procedure DoReadStream(const AStream: TStream); virtual; abstract;
procedure DoWriteStream(const AStream: TStream); virtual; abstract;
public
function Connect(const ATarget: string): Boolean; // Only valid when is used as a client
/// <summary>Closes a connection and opens it again.</summary>
function ReConnect: Boolean;
procedure Disconnect;
function ReadData: TBytes;
procedure WriteData(const AData: TBytes);
procedure ReadStream(const AStream: TStream);
procedure WriteStream(const AStream: TStream);
property Connected: Boolean read GetConnected;
property Secured: Boolean read FSecured write FSecured default False;
/// <summary> Event to post-process the buffered data.</summary>
/// <remarks> This function when defined should process the DataBuffer, and put it's equivalent data into the Result.</remarks>
property OnBeforeSendData: TTetheringDataEvent read FOnBeforeSendData write FOnBeforeSendData;
/// <summary> Event to pre-process the buffered data.</summary>
/// <remarks> This function when defined should process the DataBuffer, and put it's equivalent data into the Result.</remarks>
property OnAfterReceiveData: TTetheringDataEvent read FOnAfterReceiveData write FOnAfterReceiveData;
/// <summary> Event to post-process the stream data.</summary>
/// <remarks> This function when defined should process the InputStream, and put it's equivalent data into the OutputStream.</remarks>
property OnBeforeSendStream: TTetheringStreamEvent read FOnBeforeSendStream write FOnBeforeSendStream;
/// <summary> Event to pre-process the stream data.</summary>
/// <remarks> This function when defined should process the InputStream, and put it's equivalent data into the OutputStream.</remarks>
property OnAfterReceiveStream: TTetheringStreamEvent read FOnAfterReceiveStream write FOnAfterReceiveStream;
end;
// Server side
TServerCommExecuteEvent = procedure(const AConnection: TTetheringCustomComm) of object;
TServerCommConnectEvent = procedure(const AConnection: TTetheringCustomComm) of object;
TServerCommDisconnectEvent = procedure(const AConnection: TTetheringCustomComm) of object;
TTetheringCustomServerComm = class
private
FOnAfterReceiveData: TTetheringDataEvent;
FOnBeforeSendData: TTetheringDataEvent;
FOnAfterReceiveStream: TTetheringStreamEvent;
FOnBeforeSendStream: TTetheringStreamEvent;
protected
FTarget: string; // In network is a port, in bluetooth is a GUID
FActive: Boolean;
FSecured: Boolean;
FOnExecute: TServerCommExecuteEvent;
FOnConnect: TServerCommConnectEvent;
FOnDisconnect: TServerCommDisconnectEvent;
function DoStartServer: Boolean; virtual; abstract;
procedure DoStopServer; virtual; abstract;
procedure SetTarget(const Value: string); virtual;
procedure DoOnExecute(const AConnection: TTetheringCustomComm); virtual;
procedure DoOnConnect(const AConnection: TTetheringCustomComm); virtual;
procedure DoOnDisconnect(const AConnection: TTetheringCustomComm); virtual;
public
function StartServer: Boolean;
procedure StopServer;
property Target: string read FTarget write SetTarget;
property Active: Boolean read FActive;
property Secured: Boolean read FSecured write FSecured default False;
property OnExecute: TServerCommExecuteEvent read FOnExecute write FOnExecute;
property OnConnect: TServerCommConnectEvent read FOnConnect write FOnConnect;
property OnDisconnect: TServerCommDisconnectEvent read FOnDisconnect write FOnDisconnect;
/// <summary> Event to post-process the buffered data.</summary>
/// <remarks> This function when defined should process the DataBuffer, and put it's equivalent data into the Result.</remarks>
property OnBeforeSendData: TTetheringDataEvent read FOnBeforeSendData write FOnBeforeSendData;
/// <summary> Event to pre-process the buffered data.</summary>
/// <remarks> This function when defined should process the DataBuffer, and put it's equivalent data into the Result.</remarks>
property OnAfterReceiveData: TTetheringDataEvent read FOnAfterReceiveData write FOnAfterReceiveData;
/// <summary> Event to post-process the stream data.</summary>
/// <remarks> This function when defined should process the InputStream, and put it's equivalent data into the OutputStream.</remarks>
property OnBeforeSendStream: TTetheringStreamEvent read FOnBeforeSendStream write FOnBeforeSendStream;
/// <summary> Event to pre-process the stream data.</summary>
/// <remarks> This function when defined should process the InputStream, and put it's equivalent data into the OutputStream.</remarks>
property OnAfterReceiveStream: TTetheringStreamEvent read FOnAfterReceiveStream write FOnAfterReceiveStream;
end;
{ Network classes }
TNetworkCommUDPData = procedure(const AConnectionString: string; const AData: TBytes) of object;
TNetworkCommMulticastData = procedure(const AConnectionString: string; const AData: TBytes) of object;
TTetheringNetworkComm = class(TTetheringCustomComm)
private const
ReadTimeout = 200;
protected
/// <summary>IP Version that is going to be used by the NetworkComm</summary>
FIPVersion: TCommIPVersion;
FTCPClient: IIPTCPClient;
[Weak] FIOHandler: IIPIOHandler;
/// <summary>Remote connection string that identifies connection parameters of NetworkComm</summary>
FRemoteConnectionString: string;
function DoConnect(const ATarget: string): Boolean; override;
procedure DoDisconnect; override;
function GetConnected: Boolean; override;
function DoReadData: TBytes; override;
procedure DoWriteData(const AData: TBytes); override;
procedure DoReadStream(const AStream: TStream); override;
procedure DoWriteStream(const AStream: TStream); override;
public
constructor Create(const AIOHandler: IIPIOHandler; const ARemoteConnectionString: string; AIPVersion: TCommIPVersion);
destructor Destroy; override;
/// <summary>Property to retrieve the connection string of NetworkComm</summary>
property RemoteConnectionString: string read FRemoteConnectionString;
end;
TTetheringNetworkServerComm = class(TTetheringCustomServerComm)
private
FIPVersion: TCommIPVersion;
// TCP Server
FTCPServer: IIPTCPServer;
FContexts: TObjectDictionary<IIPContext, TTetheringNetworkComm>;
FSocket: IIPSocketHandle;
function GetComm(const AContext: IIPContext): TTetheringNetworkComm;
procedure DoOnExecuteServer(AContext: IIPContext);
procedure DoOnConnectServer(AContext: IIPContext);
procedure DoOnDisconnectServer(AContext: IIPContext);
protected
procedure SetTarget(const Value: string); override;
function DoStartServer: Boolean; override;
procedure DoStopServer; override;
public
constructor Create(AIPVersion: TCommIPVersion);
destructor Destroy; override;
end;
/// <summary>Class to manage the UDP communications in Tethering</summary>
TTetheringNetworkServerCommUDP = class(TTetheringCustomServerComm)
private
FIPVersion: TCommIPVersion;
// UDP Server
FUDPServer: IIPUDPServer;
FSocketUDP: IIPSocketHandle;
FOnUDPData: TNetworkCommUDPData;
procedure DoUDPRead(AThread: IIPUDPListenerThread; const AData: TIPBytesPeer; ABinding: IIPSocketHandle);
function GetUDPPort: Integer;
protected
procedure SetTarget(const Value: string); override;
function DoStartServer: Boolean; override;
procedure DoStopServer; override;
public
/// <summary>Function to broadcast the given data.</summary>
/// <param name="AData">Data to be broadcasted</param>
/// <param name="AHost">A specific host to broadcast the data</param>
/// <param name="InitialPort">Initial port to send the data</param>
/// <param name="FinalPort">Final port to send the data</param>
procedure BroadcastData(const AData: TBytes; const AHost: string; InitialPort, FinalPort: Integer);
constructor Create(AIPVersion: TCommIPVersion);
destructor Destroy; override;
/// <summary>UDP Port used to send and receive data</summary>
property UDPPort: Integer read GetUDPPort;
/// <summary>Property to specify a procedure that is executed when data is received from the UDP Port </summary>
property OnUDPData: TNetworkCommUDPData read FOnUDPData write FOnUDPData;
end;
/// <summary>Class to manage the Multicast communications in Tethering</summary>
TTetheringNetworkServerCommMulticast = class(TTetheringCustomServerComm)
private const
TetheringMulticastGroup: array [TCommIPVersion] of string = (
// '239.192.000.000'; Organization-Local Scope. [Meyer,RFC2365] {Do not Localize}
'239.192.2.204', // Organization-Local Scope. Ends with 2CC - 2.204 {Do not Localize}
'FF08:0:0:0:0:0:0:2CC' // All Organization Hosts... {Do not Localize}
);
private
FIPVersion: TCommIPVersion;
// Multicast Server
FMulticastServer: IIPMulticastServer;
FMulticastClient: IIPMulticastClient;
FOnMulticastData: TNetworkCommMulticastData;
procedure DoMulticastRead(Sender: TObject; const AData: TIPBytesPeer; const ABinding: IIPSocketHandle);
function GetMulticastPort: Integer;
protected
procedure SetTarget(const Value: string); override;
function DoStartServer: Boolean; override;
procedure DoStopServer; override;
public
/// <summary>Function to broadcast the given data.</summary>
/// <param name="AData">Data to be broadcasted</param>
/// <param name="AHost">A specific host to broadcast the data</param>
/// <param name="InitialPort">Initial port to send the data</param>
/// <param name="FinalPort">Final port to send the data</param>
procedure MulticastData(const AData: TBytes; const AHost: string; InitialPort, FinalPort: Integer);
constructor Create(AIPVersion: TCommIPVersion);
destructor Destroy; override;
/// <summary>Multicast Port used to send and receive data</summary>
property MulticastPort: Integer read GetMulticastPort;
/// <summary>Property to specify a procedure that is executed when data is received from the Multicast Port </summary>
property OnMulticastData: TNetworkCommMulticastData read FOnMulticastData write FOnMulticastData;
end;
{$IFDEF BT_PLATFORM}
{ Bluetooth classes }
TTetheringBTComm = class(TTetheringCustomComm)
private const
ReadTimeout = 600;
private
FBufferLock: TObject;
FInternalBuffer: TBytes;
FInternalSocket: TBluetoothSocket;
function AvailableData: Boolean;
function InternalReadData: TBytes;
protected
[Weak] FSocket: TBluetoothSocket;
function DoConnect(const ATarget: string): Boolean; override;
procedure DoDisconnect; override;
function GetConnected: Boolean; override;
function DoReadData: TBytes; override;
procedure DoWriteData(const AData: TBytes); override;
procedure DoReadStream(const AStream: TStream); override;
procedure DoWriteStream(const AStream: TStream); override;
public
constructor Create(const ASocket: TBluetoothSocket = nil; ASecured: Boolean = False);
destructor Destroy; override;
end;
TTetheringBTServerComm = class(TTetheringCustomServerComm)
private const
AcceptTimeout = 1000;
public const
/// <summary>A GUID mask to find main server socket.</summary>
BTServerBaseUUID: TGUID = '{00000000-62AA-0000-BBBF-BF3E3BBB1374}';
protected
type
TRegisteredServer = record
FGUID: TGUID;
FOnExecute: TServerCommExecuteEvent;
FOnConnect: TServerCommConnectEvent;
FOnDisconnect: TServerCommDisconnectEvent;
FOnAfterReceiveData: TTetheringDataEvent;
FOnBeforeSendData: TTetheringDataEvent;
FOnAfterReceiveStream: TTetheringStreamEvent;
FOnBeforeSendStream: TTetheringStreamEvent;
end;
/// <summary>A list with all registered servers.</summary>
class var FRegisteredServers: TList<TRegisteredServer>;
private type
TBTCommThread = class(TThread)
private
FEvent: TEvent;
protected
[Weak] FServerComm: TTetheringBTServerComm;
[Weak] FSocket: TBluetoothSocket;
procedure Execute; override;
public
constructor Create(const AServerComm: TTetheringBTServerComm; const ASocket: TBluetoothSocket);
destructor Destroy; override;
End;
TBTListenerThread = class(TThread)
protected
[Weak] FServerSocket: TBluetoothServerSocket;
[Weak] FServerComm: TTetheringBTServerComm;
procedure Execute; override;
public
constructor Create(const AServerComm: TTetheringBTServerComm; const AServerSocket: TBluetoothServerSocket);
destructor Destroy; override;
End;
private
function FindRegisteredServer(const AGUID: TGUID): Integer;
procedure RegisterServer(const AGUID: TGUID);
procedure UnRegisterServer(const AGUID: TGUID);
class destructor Destroy;
class constructor Create;
protected
class var FServerSocket: TBluetoothServerSocket;
/// <summary>GUID of the bluetooth server socket.</summary>
class var FGUIDServer: TGUID;
class var FListener: TBTListenerThread;
FGUID: TGUID;
procedure SetTarget(const Value: string); override;
function DoStartServer: Boolean; override;
procedure DoStopServer; override;
public
constructor Create;
destructor Destroy; override;
end;
{$ENDIF BT_PLATFORM}
implementation
uses
System.Tether.Consts, System.Tether.Manager, System.RegularExpressions;
type
TLogAdapter = class(TTetheringAdapter);
function CheckExceptionName(const E: Exception; const AName: string): Boolean;
var
LClass: TClass;
begin
LClass := E.ClassType;
while LClass <> nil do
begin
if LClass.ClassNameIs(AName) then
Break;
LClass := LClass.ClassParent;
end;
Result := LClass <> nil;
end;
{ TTetheringCustomComm }
function TTetheringCustomComm.Connect(const ATarget: string): Boolean;
var
Res: Boolean;
begin
if (FTarget <> ATarget) or not Connected then
begin
if Connected then
Disconnect;
FTarget := ATarget;
try
Res := DoConnect(ATarget);
except
Res := False;
end;
Result := Res;
end
else
Result := True;
end;
procedure TTetheringCustomComm.Disconnect;
begin
try
DoDisconnect;
except
end;
end;
function TTetheringCustomComm.ReadData: TBytes;
begin
if Assigned(FOnAfterReceiveData) then
Result := TBytes(FOnAfterReceiveData(Self, TByteDynArray(DoReadData)))
else
Result := DoReadData;
if (Result <> nil) and TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('TTetheringCustomComm.ReadData: "' + TEncoding.UTF8.GetString(Result) + '"');
end;
procedure TTetheringCustomComm.ReadStream(const AStream: TStream);
var
LStream: TStream;
begin
if Assigned(FOnAfterReceiveStream) then
begin
LStream := TMemoryStream.Create;
try
DoReadStream(LStream);
FOnAfterReceiveStream(Self, LStream, AStream);
finally
LStream.Free;
end;
end
else
DoReadStream(AStream);
end;
function TTetheringCustomComm.ReConnect: Boolean;
begin
if Connected then
Disconnect;
Result := Connect(FTarget);
end;
procedure TTetheringCustomComm.WriteData(const AData: TBytes);
begin
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('TTetheringCustomComm.WriteData: "' + TEncoding.UTF8.GetString(AData) + '"');
if Assigned(FOnBeforeSendData) then
DoWriteData(TBytes(FOnBeforeSendData(Self, TByteDynArray(AData))))
else
DoWriteData(AData);
end;
procedure TTetheringCustomComm.WriteStream(const AStream: TStream);
var
LStream: TStream;
begin
if Assigned(FOnBeforeSendStream) then
begin
LStream := TMemoryStream.Create;
try
FOnBeforeSendStream(Self, AStream, LStream);
DoWriteStream(LStream);
finally
LStream.Free;
end;
end
else
DoWriteStream(AStream);
end;
{ TTetheringNetworkComm }
constructor TTetheringNetworkComm.Create(const AIOHandler: IIPIOHandler; const ARemoteConnectionString: string; AIPVersion: TCommIPVersion);
begin
inherited Create;
FIPVersion := AIPVersion;
FIOHandler := AIOHandler;
FRemoteConnectionString := ARemoteConnectionString;
end;
destructor TTetheringNetworkComm.Destroy;
begin
DoDisconnect;
FTCPClient := nil;
FIOHandler := nil;
inherited;
end;
procedure TTetheringNetworkComm.DoDisconnect;
begin
try
if (FTCPClient <> nil) {and GetConnected} then
FTCPClient.Disconnect;
except
end;
end;
function TTetheringNetworkComm.DoConnect(const ATarget: string): Boolean;
var
Pos: Integer;
LHost: string;
LPort: Integer;
begin
inherited;
if FTCPClient = nil then
begin
FTCPClient := PeerFactory.CreatePeer('', IIPTCPClient, nil) as IIPTCPClient;
FTCPClient.IPVersion := FIPVersion;
end;
FTCPClient.ConnectTimeout := 5000;
Pos := ATarget.IndexOf(TetheringConnectionSeparator);
if Pos < 0 then
raise ETetheringCommException.CreateFmt(SInvalidNetworkTargetFormat, [ATarget]);
LHost := ATarget.Substring(0, Pos);
LPort := ATarget.Substring(Pos + 1, Length(ATarget)).ToInteger;
try
if (FTCPClient.Host <> LHost) or (FTCPClient.Port <> LPort) then
begin
if GetConnected then
FTCPClient.Disconnect;
FTCPClient.Host := LHost;
FTCPClient.Port := LPort;
FTCPClient.Connect;
end
else
begin
if not GetConnected then
FTCPClient.Connect;
end;
Result := GetConnected;
FIOHandler := FTCPClient.IOHandler;
except
Result := False;
end;
end;
function TTetheringNetworkComm.DoReadData: TBytes;
var
BuffSize: Integer;
MaxTimes: Integer;
begin
MaxTimes := 0;
while (FIOHandler <> nil) and (MaxTimes < ReadTimeout) and (FIOHandler.InputBuffer.Size = 0) do
begin
if FIOHandler.InputBuffer.Size = 0 then
FIOHandler.CheckForDataOnSource(10);
Inc(MaxTimes);
end;
if (FIOHandler <> nil) and (FIOHandler.InputBuffer.Size > 0) then
begin
BuffSize := FIOHandler.InputBuffer.Size;
SetLength(Result, BuffSize);
FIOHandler.ReadBytes(Result, BuffSize, False);
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('DoReadData(' + FRemoteConnectionString + '): "' + TEncoding.UTF8.GetString(Result) + '"');
end
else
SetLength(Result, 0);
end;
procedure TTetheringNetworkComm.DoReadStream(const AStream: TStream);
begin
if FIOHandler <> nil then
FIOHandler.ReadStream(AStream);
end;
procedure TTetheringNetworkComm.DoWriteData(const AData: TBytes);
begin
if FIOHandler <> nil then
begin
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('DoWriteData(' + FRemoteConnectionString + '): "' + TEncoding.UTF8.GetString(AData) + '"');
FIOHandler.Write(AData);
end;
end;
procedure TTetheringNetworkComm.DoWriteStream(const AStream: TStream);
begin
if FIOHandler <> nil then
FIOHandler.Write(AStream, 0, True);
end;
function TTetheringNetworkComm.GetConnected: Boolean;
begin
try
if FTCPClient <> nil then
Result := FTCPClient.Connected
else if FIOHandler <> nil then
Result := FIOHandler.Connected
else
Result := False;
except
DoDisconnect;
Result := False;
end;
end;
{ TTetheringCustomServerComm }
procedure TTetheringCustomServerComm.DoOnConnect(const AConnection: TTetheringCustomComm);
begin
if Assigned(FOnConnect) then
FOnConnect(AConnection);
end;
procedure TTetheringCustomServerComm.DoOnDisconnect(const AConnection: TTetheringCustomComm);
begin
if Assigned(FOnDisconnect) then
FOnDisconnect(AConnection);
end;
procedure TTetheringCustomServerComm.DoOnExecute(const AConnection: TTetheringCustomComm);
begin
if Assigned(FOnExecute) then
FOnExecute(AConnection);
end;
procedure TTetheringCustomServerComm.SetTarget(const Value: string);
begin
FTarget := Value;
end;
procedure TTetheringCustomServerComm.StopServer;
begin
if FActive then
begin
DoStopServer;
FActive := False;
end;
end;
function TTetheringCustomServerComm.StartServer: Boolean;
begin
if not FActive then
FActive := DoStartServer;
Result := FActive;
end;
{ TTetheringNetworkServerComm }
constructor TTetheringNetworkServerComm.Create(AIPVersion: TCommIPVersion);
begin
inherited Create;
FIPVersion := AIPVersion;
FContexts := TObjectDictionary<IIPContext, TTetheringNetworkComm>.Create([doOwnsValues]);
FTCPServer := PeerFactory.CreatePeer('', IIPTCPServer, nil) as IIPTCPServer;
FTCPServer.OnExecute := DoOnExecuteServer;
FTCPServer.OnDisconnect := DoOnDisconnectServer;
FTCPServer.OnConnect := DoOnConnectServer;
FSocket := FTCPServer.Bindings.Add;
FSocket.IPVersion := FIPVersion;
end;
destructor TTetheringNetworkServerComm.Destroy;
begin
StopServer;
inherited;
FContexts.Free;
FSocket := nil;
FTCPServer := nil;
end;
function TTetheringNetworkServerComm.GetComm(const AContext: IIPContext): TTetheringNetworkComm;
var
LConnectionString: string;
begin
TMonitor.Enter(FContexts);
try
if not FContexts.TryGetValue(AContext, Result) then
begin
LConnectionString := AContext.Connection.Socket.Binding.PeerIP + TetheringConnectionSeparator +
AContext.Connection.Socket.Binding.PeerPort.ToString;
Result := TTetheringNetworkComm.Create(AContext.Connection.IOHandler, LConnectionString, FIPVersion);
Result.OnAfterReceiveData := OnAfterReceiveData;
Result.OnBeforeSendData := OnBeforeSendData;
Result.OnAfterReceiveStream := OnAfterReceiveStream;
Result.OnBeforeSendStream := OnBeforeSendStream;
FContexts.Add(AContext, Result);
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('** -> TTetheringNetworkServerComm.GetComm(' + LConnectionString + ')');
end;
finally
TMonitor.Exit(FContexts);
end;
end;
procedure TTetheringNetworkServerComm.SetTarget(const Value: string);
begin
inherited;
FSocket.Port := Value.ToInteger;
end;
procedure TTetheringNetworkServerComm.DoOnConnectServer(AContext: IIPContext);
begin
DoOnConnect(GetComm(AContext));
end;
procedure TTetheringNetworkServerComm.DoOnDisconnectServer(AContext: IIPContext);
begin
DoOnDisconnect(GetComm(AContext));
end;
procedure TTetheringNetworkServerComm.DoOnExecuteServer(AContext: IIPContext);
begin
DoOnExecute(GetComm(AContext));
end;
procedure TTetheringNetworkServerComm.DoStopServer;
begin
if FTCPServer <> nil then
FTCPServer.Active := False;
end;
function TTetheringNetworkServerComm.DoStartServer: Boolean;
begin
Result := True;
try
FTCPServer.Active := True;
except
// This is a non conventional method to catch an exception that is in a library that we do not want to have a dependency.
// This is considered a HACK and not a good sample of programming techniques.
// We are going to let this code handle the exceptions until we add a proper mechanism to propagate the
// Indy exceptions through the IPPeerAPI in an ordered and safe manner.
on E: Exception do
begin
Result := False;
if not (CheckExceptionName(E, 'EIdCouldNotBindSocket') or CheckExceptionName(E, 'EIdSocketError')) then // Do not translate
raise;
end;
end;
end;
{ TTetheringNetworkServerCommUDP }
constructor TTetheringNetworkServerCommUDP.Create(AIPVersion: TCommIPVersion);
begin
inherited Create;
FIPVersion := AIPVersion;
FUDPServer := PeerFactory.CreatePeer('', IIPUDPServer, nil) as IIPUDPServer;
FUDPServer.ThreadedEvent := True;
FUDPServer.OnRead := DoUDPRead;
FUDPServer.IPVersion := FIPVersion;
FSocketUDP := FUDPServer.Bindings.Add;
FSocketUDP.IPVersion := FIPVersion;
end;
destructor TTetheringNetworkServerCommUDP.Destroy;
begin
StopServer;
inherited;
FSocketUDP := nil;
FUDPServer := nil;
end;
procedure TTetheringNetworkServerCommUDP.BroadcastData(const AData: TBytes; const AHost: string;
InitialPort, FinalPort: Integer);
var
I: Integer;
LHost: string;
begin
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('** UDP ** BroadcastData to "' + AHost + '": "' + TEncoding.UTF8.GetString(AData) + '"');
if AHost = '' then
begin
if FIPVersion = TCommIPVersion.IP_IPv4 then
LHost := '255.255.255.255'
else
LHost := '0:0:0:0:0:0:255.255.255.255';
for I := InitialPort to FinalPort do
FUDPServer.Broadcast(AData, I, LHost)
end
else
for I := InitialPort to FinalPort do
FUDPServer.SendBuffer(AHost, I, AData);
end;
function TTetheringNetworkServerCommUDP.DoStartServer: Boolean;
begin
Result := True;
try
FUDPServer.Active := True;
except
// This is a non conventional method to catch an exception that is in a library that we do not want to have a dependency.
// This is considered a HACK and not a good sample of programming techniques.
// We are going to let this code handle the exceptions until we add a proper mechanism to propagate the
// Indy exceptions through the IPPeerAPI in an ordered and safe manner.
on E: Exception do
begin
Result := False;
if not (CheckExceptionName(E, 'EIdCouldNotBindSocket') or CheckExceptionName(E, 'EIdSocketError')) then // Do not translate
raise;
end;
end;
end;
procedure TTetheringNetworkServerCommUDP.DoStopServer;
begin
if FUDPServer <> nil then
FUDPServer.Active := False;
end;
procedure TTetheringNetworkServerCommUDP.DoUDPRead(AThread: IIPUDPListenerThread; const AData: TIPBytesPeer;
ABinding: IIPSocketHandle);
var
LConnection: string;
begin
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('IN -> DoUDPRead "' + ABinding.PeerIP + '": "' + TEncoding.UTF8.GetString(AData) + '"');
if Assigned(FOnUDPData) and (Length(AData) > 0) then
begin
LConnection := ABinding.PeerIP + TetheringConnectionSeparator + ABinding.PeerPort.ToString;
FOnUDPData(LConnection, AData);
end;
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('OUT -> DoUDPRead "' + LConnection + '": "' + TEncoding.UTF8.GetString(AData) + '"');
end;
function TTetheringNetworkServerCommUDP.GetUDPPort: Integer;
begin
Result := FSocketUDP.Port;
end;
procedure TTetheringNetworkServerCommUDP.SetTarget(const Value: string);
begin
inherited;
FSocketUDP.Port := Value.ToInteger;
end;
{ TTetheringNetworkServerCommMulticast }
constructor TTetheringNetworkServerCommMulticast.Create(AIPVersion: TCommIPVersion);
begin
inherited Create;
FIPVersion := AIPVersion;
FMulticastServer := PeerFactory.CreatePeer('', IIPMulticastServer, nil) as IIPMulticastServer;
FMulticastServer.IPVersion := FIPVersion;
FMulticastClient := PeerFactory.CreatePeer('', IIPMulticastClient, nil) as IIPMulticastClient;
FMulticastClient.IPVersion := FIPVersion;
FMulticastClient.ThreadedEvent := True;
FMulticastClient.OnMulticast := DoMulticastRead;
FMulticastServer.MulticastGroup := TetheringMulticastGroup[FIPVersion];
FMulticastClient.MulticastGroup := TetheringMulticastGroup[FIPVersion];
end;
destructor TTetheringNetworkServerCommMulticast.Destroy;
begin
FMulticastClient := nil;
FMulticastServer := nil;
inherited;
end;
procedure TTetheringNetworkServerCommMulticast.DoMulticastRead(Sender: TObject; const AData: TIPBytesPeer;
const ABinding: IIPSocketHandle);
var
LConnection: string;
begin
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('IN -> DoMulticastRead "' + ABinding.PeerIP + TetheringConnectionSeparator +
ABinding.PeerPort.ToString + '": "' + TEncoding.UTF8.GetString(AData) + '"');
if Assigned(FOnMulticastData) and (Length(AData) > 0) then
begin
LConnection := ABinding.PeerIP + TetheringConnectionSeparator + ABinding.PeerPort.ToString;
FOnMulticastData(LConnection, AData);
end;
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('OUT -> DoMulticastRead "' + LConnection + '": "' + TEncoding.UTF8.GetString(AData) + '"');
end;
function TTetheringNetworkServerCommMulticast.DoStartServer: Boolean;
begin
Result := True;
try
FMulticastServer.Active := True;
FMulticastClient.Active := True;
except
// This is a non conventional method to catch an exception that is in a library that we do not want to have a dependency.
// This is considered a HACK and not a good sample of programming techniques.
// We are going to let this code handle the exceptions until we add a proper mechanism to propagate the
// Indy exceptions through the IPPeerAPI in an ordered and safe manner.
on E: Exception do
begin
Result := False;
FMulticastClient.Active := False;
FMulticastServer.Active := False;
if not (CheckExceptionName(E, 'EIdCouldNotBindSocket') or CheckExceptionName(E, 'EIdSocketError')) then // Do not translate
raise;
end;
end;
end;
procedure TTetheringNetworkServerCommMulticast.DoStopServer;
begin
if FMulticastServer <> nil then
FMulticastServer.Active := False;
if FMulticastClient <> nil then
FMulticastClient.Active := False;
end;
function TTetheringNetworkServerCommMulticast.GetMulticastPort: Integer;
begin
Result := FMulticastServer.Port;
end;
procedure TTetheringNetworkServerCommMulticast.MulticastData(const AData: TBytes; const AHost: string; InitialPort,
FinalPort: Integer);
var
I: Integer;
begin
if TTetheringAdapter.IsLoggingItem(TTetheringAdapter.TTetheringLogItem.Comm) then
TLogAdapter.Log('MulticastData to "' + AHost + '": "' + TEncoding.UTF8.GetString(AData) + '"');
if AHost = '' then
begin
if FMulticastServer.MulticastGroup <> TetheringMulticastGroup[FIPVersion] then
FMulticastServer.MulticastGroup := TetheringMulticastGroup[FIPVersion];
end
else
FMulticastServer.MulticastGroup := AHost;
for I := InitialPort to FinalPort do
FMulticastServer.Send(TIPBytesPeer(AData), I);
end;
procedure TTetheringNetworkServerCommMulticast.SetTarget(const Value: string);
begin
inherited;
FMulticastServer.Port := Value.ToInteger;
FMulticastClient.DefaultPort := Value.ToInteger;
end;
{$IFDEF BT_PLATFORM}
type
TRedirectedServer = class(TThread)
private
FSecured: Boolean;
FGUID: TGUID;
FThreadComm: TTetheringBTServerComm.TBTCommThread;
[Weak] FServerComm: TTetheringBTServerComm;
FSyncEvent: TEvent;
FServerSocket: TBluetoothServerSocket;
protected
procedure Execute; override;
procedure TerminatedSet; override;
public
constructor Create(const AServerComm: TTetheringBTServerComm; const AGUID: TGUID; Secured: Boolean);
destructor Destroy; override;
function WaitInitialization: Boolean;
End;
{ TTetheringBTComm }
function TTetheringBTComm.AvailableData: Boolean;
begin
if Length(FInternalBuffer) > 0 then
Exit(True);
if FSocket <> nil then
begin
TMonitor.Enter(FBufferLock);
try
try
FInternalBuffer := FSocket.ReceiveData(ReadTimeout);
except
ReConnect;
if FSocket <> nil then
FInternalBuffer := FSocket.ReceiveData(ReadTimeout)
else
raise ETetheringCommException.CreateFmt(SNoConnections, [FTarget]);
end;
finally
TMonitor.Exit(FBufferLock);
end;
end;
Result := Length(FInternalBuffer) > 0;
end;
constructor TTetheringBTComm.Create(const ASocket: TBluetoothSocket; ASecured: Boolean);
begin
FSocket := ASocket;
FSecured := ASecured;
FBufferLock := TObject.Create;
end;
destructor TTetheringBTComm.Destroy;
begin
if FInternalSocket <> nil then
FInternalSocket.Free;
FBufferLock.Free;
inherited;
end;
function TTetheringBTComm.DoConnect(const ATarget: string): Boolean;
type
TConnectState = (Ok, Error, NotFound);
var
LResult: Boolean;
begin
TThread.Synchronize(nil, procedure
function IsTTetheringBTBase(AGUID: TGUID): Boolean;
const
TTetheringBTBaseUUID: TGUID = '{00000000-62AA-0000-BBBF-BF3E3BBB1374}';
begin
AGUID.D1 := 0;
AGUID.D3 := 0;
Result := AGUID = TTetheringBTBaseUUID;
if not Result then
begin
AGUID.D2 := AGUID.D2 - $11;
Result := AGUID = TTetheringBTBaseUUID;
end;
if not Result then
begin
AGUID.D2 := AGUID.D2 - $11;
Result := AGUID = TTetheringBTBaseUUID;
end;
if not Result then
begin
AGUID.D2 := AGUID.D2 - $11;
Result := AGUID = TTetheringBTBaseUUID;
end;
end;
function ConnectToService(const AGUIDService: TGUID; const AGUIDDestination: TGUID; var ASocket: TBluetoothSocket;
const ADevice:TBluetoothDevice): TConnectState;
var
I: Integer;
LBuffer: TBytes;
Response: string;
begin
for I := 0 to 1 do // 2 retries
begin
try // Create socket to BT Server
ASocket := ADevice.CreateClientSocket(AGUIDService, FSecured);
ASocket.Connect;
Break;
except
on E: Exception do
begin
if ASocket <> nil then
ASocket.Close;
Exit(Error);
end;
end;
Sleep(15);
end;
// Send to which virtual server I want to connect
ASocket.SendData(TEncoding.UTF8.GetBytes(AGUIDDestination.ToString));
for I := 0 to 1 do // 2 retries
begin
try
LBuffer := ASocket.ReceiveData(ReadTimeout);
except
end;
if Length(LBuffer) > 0 then
Break;
end;
if (Length(LBuffer) > 0) then
Response := TEncoding.UTF8.GetString(LBuffer);
if (Length(LBuffer) = 0) or (Response <> 'ok') then
begin
ASocket.Close;
ASocket := nil;
if Response = 'not found' then
Result := NotFound
else
Result := Error;
end
else
Result := Ok;
end;
var
Pos: Integer;
LDeviceName: string;
LService: TBluetoothService;
LGUID: TGUID;
LGUIDService: TGUID;
LGUIDTranslated: TGUID;
LBuffer: TBytes;
LSocket: TBluetoothSocket;
I: Integer;
LText: string;
LState: TConnectState;
LDevice: TBluetoothDevice;
begin
inherited;
Pos := ATarget.IndexOf(TetheringConnectionSeparator);
if Pos < 0 then
raise ETetheringCommException.CreateFmt(SInvalidBluetoothTargetFormat, [ATarget]);
LDeviceName := ATarget.Substring(0, Pos);
LGUIDService := LGUID.Create(ATarget.Substring(Pos + 1, Length(ATarget)));
LResult := False;
FSocket := nil;
for LDevice in TBluetoothManager.Current.LastPairedDevices do
if SameText(LDevice.Address, LDeviceName) or SameText(LDevice.DeviceName, LDeviceName) then
begin
if IsTTetheringBTBase(LGUIDService) then
begin
if LGUIDService.D2 = $62AA then // It's a main Server GUID
begin
for I := 0 to 2 do // 3 retries
begin
LState := ConnectToService(LGUIDService, LGUIDService, FInternalSocket, LDevice);
if LState = Error then
Sleep(30)
else if LState = NotFound then
Break
else
begin
FSocket := FInternalSocket;
LResult := True;
Break;
end;
end;
Break;
end
else
begin
// Search main Server GUID
for LService in LDevice.GetServices do
begin
LGUID := LService.UUID;
LGUID.D1 := 0;
LGUID.D3 := 0;
if LGUID = TTetheringBTServerComm.BTServerBaseUUID then
begin
LSocket := nil;
for I := 0 to 2 do // 3 retries
begin
LState := ConnectToService(LService.UUID, LGUIDService, LSocket, LDevice);
if LState = Error then
Sleep(30)
else
Break;
end;
if LSocket <> nil then
begin
for I := 0 to 2 do // 3 retries
begin
try
LBuffer := LSocket.ReceiveData(ReadTimeout);
except
end;
if Length(LBuffer) > 0 then
Break;
end;
LText:= TEncoding.UTF8.GetString(LBuffer);
if LText <> 'error' then
begin
try
LSocket.SendData(TEncoding.UTF8.GetBytes('ok, redirected readed'));
except
end;
LSocket.Close;
LSocket.Free;
LGUIDTranslated := TGUID.Create(TEncoding.UTF8.GetString(LBuffer));
if FInternalSocket <> nil then
FInternalSocket.Free;
FInternalSocket := LDevice.CreateClientSocket(LGUIDTranslated, FSecured);
FSocket := FInternalSocket;
Break;
end;
end;
end;
end;
// Now try to read redirected server and connect to it
if FSocket <> nil then
begin
try
FSocket.Connect;
LResult := True;
except
LResult := False;
end;
end
else
LResult := False;
end;
end
else
begin // direct cConnect(not used)
if FInternalSocket <> nil then
FInternalSocket.Free;
FInternalSocket := LDevice.CreateClientSocket(LGUID, FSecured);
FSocket := FInternalSocket;
if FSocket <> nil then
begin
try
FSocket.Connect;
LResult := True;
except
LResult := False;
end;
end
else
LResult := False;
end;
Break;
end;
end);
Result := LResult;
end;
procedure TTetheringBTComm.DoDisconnect;
begin
if FSocket <> nil then
begin
FSocket.Close;
FSocket := nil;
end;
if FInternalSocket <> nil then
FreeAndNil(FInternalSocket);
end;
function TTetheringBTComm.DoReadData: TBytes;
begin
TMonitor.Enter(FBufferLock);
try
if (Length(FInternalBuffer) = 0) and (FSocket <> nil) then
try
FInternalBuffer := FSocket.ReceiveData(ReadTimeout);
except
ReConnect;
if FSocket <> nil then
FInternalBuffer := FSocket.ReceiveData(ReadTimeout)
else
raise ETetheringCommException.CreateFmt(SNoConnections, [FTarget]);
end;
Result := InternalReadData;
finally
TMonitor.Exit(FBufferLock);
end;
end;
function TTetheringBTComm.InternalReadData: TBytes;
var
BufferLength: Integer;
TempBuff: TBytes;
begin
if Length(FInternalBuffer) > 0 then
begin
BufferLength := PInteger(@FInternalBuffer[0])^;
if BufferLength <= 0 then
begin
SetLength(FInternalBuffer, 0);
SetLength(Result, 0);
end
else
begin
while Length(FInternalBuffer) - SizeOf(Integer) < BufferLength do // Need more data from socket
begin
try
TempBuff := FSocket.ReceiveData(ReadTimeout);
except
ReConnect;
if FSocket <> nil then
TempBuff := FSocket.ReceiveData(ReadTimeout)
else
raise ETetheringCommException.CreateFmt(SNoConnections, [FTarget]);
end;
FInternalBuffer := FInternalBuffer + TempBuff;
end;
Result := Copy(FInternalBuffer, SizeOf(Integer), BufferLength);
if Length(FInternalBuffer) - (BufferLength + SizeOf(Integer)) <= 0 then
SetLength(FInternalBuffer, 0)
else
FInternalBuffer := Copy(FInternalBuffer, BufferLength + SizeOf(Integer),
Length(FInternalBuffer) - (BufferLength + SizeOf(Integer)));
end;
end
else
SetLength(Result, 0);
end;
procedure TTetheringBTComm.DoReadStream(const AStream: TStream);
var
Buffer: TBytes;
begin
Buffer := DoReadData;
AStream.Write(Buffer, 0, Length(Buffer));
end;
procedure TTetheringBTComm.DoWriteData(const AData: TBytes);
var
B: TBytes;
L: Integer;
begin
if FSocket <> nil then
begin
L := Length(AData);
if L >= 0 then
begin
SetLength(B, SizeOf(Integer));
PInteger(@B[0])^ := L;
try
FSocket.SendData(B + AData);
except
ReConnect;
if FSocket <> nil then
FSocket.SendData(B + AData)
else
raise ETetheringCommException.CreateFmt(SNoConnections, [FTarget]);
end;
end;
end;
end;
procedure TTetheringBTComm.DoWriteStream(const AStream: TStream);
const
BuffSize = 8192;
var
Buffer: TBytes;
Readed: Integer;
L: Integer;
begin
L := AStream.Size;
if L >= 0 then
begin
SetLength(Buffer, BuffSize);
Buffer[0] := LongRec(L).Bytes[0];
Buffer[1] := LongRec(L).Bytes[1];
Buffer[2] := LongRec(L).Bytes[2];
Buffer[3] := LongRec(L).Bytes[3];
Readed := AStream.Read(Buffer, SizeOf(Integer), Length(Buffer) - SizeOf(Integer));
try
FSocket.SendData(Buffer);
except
ReConnect;
if FSocket <> nil then
FSocket.SendData(Buffer)
else
raise ETetheringCommException.CreateFmt(SNoConnections, [FTarget]);
end;
if Readed = Length(Buffer) - SizeOf(Integer) then
repeat
Readed := AStream.Read(Buffer, 0, Length(Buffer));
SetLength(Buffer, Readed);
try
FSocket.SendData(Buffer);
except
ReConnect;
if FSocket <> nil then
FSocket.SendData(Buffer)
else
raise ETetheringCommException.CreateFmt(SNoConnections, [FTarget]);
end;
until Readed < BuffSize;
end;
end;
function TTetheringBTComm.GetConnected: Boolean;
begin
if FSocket <> nil then
Result := FSocket.Connected
else
Result := False;
end;
{ TTetheringBTServerComm }
constructor TTetheringBTServerComm.Create;
begin
inherited;
end;
class constructor TTetheringBTServerComm.Create;
begin
FRegisteredServers := TList<TRegisteredServer>.Create;
end;
destructor TTetheringBTServerComm.Destroy;
begin
inherited;
end;
class destructor TTetheringBTServerComm.Destroy;
begin
FRegisteredServers.Free;
if FServerSocket <> nil then
FServerSocket.Close;
if FListener <> nil then
FListener.Free;
if FServerSocket <> nil then
FServerSocket.Free;
end;
function TTetheringBTServerComm.DoStartServer: Boolean;
begin
Result := True;
// Create a Unique Server to manage connections
if FListener = nil then
begin
try
FGUIDServer := BTServerBaseUUID;
FGUIDServer.D1 := Cardinal(Pointer(Self));
FGUIDServer.D3 := Random(65535);
FServerSocket := TBluetoothManager.Current.CreateServerSocket('BTServer_' + FGUIDServer.ToString, FGUIDServer, FSecured);
if FServerSocket <> nil then
begin
FListener := TBTListenerThread.Create(Self, FServerSocket);
FListener.Start;
end
else
Result := False;
except
Result := False;
end;
end;
if Result then
RegisterServer(FGUID);
end;
procedure TTetheringBTServerComm.DoStopServer;
begin
UnRegisterServer(FGUID);
end;
function TTetheringBTServerComm.FindRegisteredServer(const AGUID: TGUID): Integer;
var
I: Integer;
begin
Result := -1;
if FRegisteredServers <> nil then
for I := 0 to FRegisteredServers.Count - 1 do
if FRegisteredServers[I].FGUID = AGUID then
Exit(I);
end;
procedure TTetheringBTServerComm.RegisterServer(const AGUID: TGUID);
var
LRegisteredServer: TRegisteredServer;
begin
if FindRegisteredServer(AGUID) < 0 then
begin
LRegisteredServer.FGUID := AGUID;
LRegisteredServer.FOnExecute := FOnExecute;
LRegisteredServer.FOnConnect := FOnConnect;
LRegisteredServer.FOnDisconnect := FOnDisconnect;
LRegisteredServer.FOnAfterReceiveData := FOnAfterReceiveData;
LRegisteredServer.FOnBeforeSendData := FOnBeforeSendData;
LRegisteredServer.FOnAfterReceiveStream := FOnAfterReceiveStream;
LRegisteredServer.FOnBeforeSendStream := FOnBeforeSendStream;
FRegisteredServers.Add(LRegisteredServer);
end;
end;
procedure TTetheringBTServerComm.SetTarget(const Value: string);
begin
inherited;
FGUID := FGUID.Create(Value);
end;
procedure TTetheringBTServerComm.UnRegisterServer(const AGUID: TGUID);
var
LIndex: Integer;
begin
LIndex := FindRegisteredServer(AGUID);
if LIndex >= 0 then
FRegisteredServers.Delete(LIndex);
end;
{ TTetheringBTServerComm.TBTListenerThread }
constructor TTetheringBTServerComm.TBTListenerThread.Create(const AServerComm: TTetheringBTServerComm;
const AServerSocket: TBluetoothServerSocket);
begin
inherited Create(True);
FServerSocket := AServerSocket;
FServerComm := AServerComm;
end;
destructor TTetheringBTServerComm.TBTListenerThread.Destroy;
begin
inherited;
// FServerSocket.Close;
end;
procedure TTetheringBTServerComm.TBTListenerThread.Execute;
var
LSocket: TBluetoothSocket;
LGUID: TGUID;
LGUIDToConnect: TGUID;
LNewServer: TRedirectedServer;
LServerList: TObjectList<TRedirectedServer>;
LBuff: TBytes;
RegisteredServers: string;
I: Integer;
LTempClient: TTetheringBTComm;
procedure CleanRedirectedServers;
var
I: Integer;
begin
for I := LServerList.Count - 1 downto 0 do
if LServerList[I].Finished then
LServerList.Delete(I);
if LServerList.Count > 2 then //Only 2 servers working at same time
LServerList.Delete(0);
end;
begin
inherited;
LServerList := TObjectList<TRedirectedServer>.Create;
try
while not Terminated and (FServerSocket <> nil) do
begin
LSocket := FServerSocket.Accept(AcceptTimeout);
if (not Terminated) and (LSocket <> nil) then
begin
try
// Read the server that the client wants to connect
try
LBuff := LSocket.ReceiveData(TTetheringBTComm.ReadTimeout);
except
end;
if Length(LBuff)> 0 then
begin
try
LGUIDToConnect := FGUID.Create(TEncoding.UTF8.GetString(LBuff));
except
end;
if LGUIDToConnect = FServerComm.FGUIDServer then // Connect to BT Server (self), so returns registered servers
begin
try
LSocket.SendData(TEncoding.UTF8.GetBytes('ok'));
except
end;
RegisteredServers := '';
for I := 0 to FServerComm.FRegisteredServers.Count - 1 do
RegisteredServers := RegisteredServers + FServerComm.FRegisteredServers.Items[I].FGUID.ToString + TetheringConnectionSeparator;
try
LTempClient := TTetheringBTComm.Create(LSocket);
LTempClient.WriteData(TEncoding.UTF8.GetBytes(RegisteredServers));
LTempClient.Free;
//LSocket.SendData(TEncoding.UTF8.GetBytes(RegisteredServers));
except
end;
try
LSocket.ReceiveData(TTetheringBTComm.ReadTimeout); //wait until data is readed in the other end
except
end;
end
else if FServerComm.FindRegisteredServer(LGUIDToConnect) >= 0 then
begin
try
LSocket.SendData(TEncoding.UTF8.GetBytes('ok'));
except
end;
LGUID := TGUID.NewGuid;
LGUID.D2 := $62FF;
I := FServerComm.FindRegisteredServer(LGUIDToConnect);
FServerComm.FOnExecute := FServerComm.FRegisteredServers[I].FOnExecute;
FServerComm.FOnConnect := FServerComm.FRegisteredServers[I].FOnConnect;
FServerComm.FOnDisconnect := FServerComm.FRegisteredServers[I].FOnDisconnect;
FServerComm.FOnAfterReceiveData := FServerComm.FRegisteredServers[I].FOnAfterReceiveData;
FServerComm.FOnBeforeSendData := FServerComm.FRegisteredServers[I].FOnBeforeSendData;
FServerComm.FOnAfterReceiveStream := FServerComm.FRegisteredServers[I].FOnAfterReceiveStream;
FServerComm.FOnBeforeSendStream := FServerComm.FRegisteredServers[I].FOnBeforeSendStream;
try
LNewServer := TRedirectedServer.Create(FServerComm, LGUID, FServerComm.FSecured);
if LNewServer <> nil then
begin
LNewServer.Start;
LServerList.Add(LNewServer);
if LNewServer.WaitInitialization then
LSocket.SendData(TEncoding.UTF8.GetBytes(LGUID.ToString))
else
LSocket.SendData(TEncoding.UTF8.GetBytes('error'));
end
else
LSocket.SendData(TEncoding.UTF8.GetBytes('error'));
except
LSocket.SendData(TEncoding.UTF8.GetBytes('error'));
end;
end
else
begin
LSocket.SendData(TEncoding.UTF8.GetBytes('not found'));
try
LSocket.ReceiveData(TTetheringBTComm.ReadTimeout); //wait until socket is closed in the other end
except
end;
end;
end;
finally
LSocket.Close;
LSocket.Free;
end;
end
else
CleanRedirectedServers;
end;
finally
LServerList.Free;
end;
end;
{ TTetheringBTServerComm.TBTCommThread }
constructor TTetheringBTServerComm.TBTCommThread.Create(const AServerComm: TTetheringBTServerComm; const ASocket: TBluetoothSocket);
begin
inherited Create(True);
FServerComm := AServerComm;
FSocket := ASocket;
FEvent := TEvent.Create;
end;
destructor TTetheringBTServerComm.TBTCommThread.Destroy;
begin
inherited;
FEvent.Free;
end;
procedure TTetheringBTServerComm.TBTCommThread.Execute;
var
LConnection: TTetheringBTComm;
begin
inherited;
LConnection := TTetheringBTComm.Create(FSocket, FServerComm.FSecured);
try
LConnection.OnAfterReceiveData := FServerComm.OnAfterReceiveData;
LConnection.OnBeforeSendData := FServerComm.OnBeforeSendData;
LConnection.OnAfterReceiveStream := FServerComm.OnAfterReceiveStream;
LConnection.OnBeforeSendStream := FServerComm.OnBeforeSendStream;
FServerComm.DoOnConnect(LConnection);
try
while not Terminated and (FSocket <> nil) do
begin
if LConnection.AvailableData and not Terminated then
FServerComm.DoOnExecute(LConnection);
end;
except
end;
if not Terminated then
FServerComm.DoOnDisconnect(LConnection);
finally
LConnection.Free;
end;
FEvent.SetEvent;
end;
{ TRedirectedServer }
constructor TRedirectedServer.Create(const AServerComm: TTetheringBTServerComm; const AGUID: TGUID; Secured: Boolean);
begin
inherited Create(True);
FGUID := AGUID;
FSecured := Secured;
FServerComm := AServerComm;
FSyncEvent := TEvent.Create;
end;
destructor TRedirectedServer.Destroy;
begin
FSyncEvent.Free;
if FThreadComm <> nil then
FThreadComm.Terminate;
inherited;
FServerSocket.Free;
end;
procedure TRedirectedServer.Execute;
const
CountTimeOut = 10000 div TTetheringBTServerComm.AcceptTimeout; // 10 secs timeout
var
LoopCount: Integer;
LSocket: TBluetoothSocket;
I: Integer;
begin
inherited;
for I := 0 to 2 do
begin
try
FServerSocket := TBluetoothManager.Current.CreateServerSocket('Redirected_' + FGUID.ToString, FGUID, FSecured);
if FServerSocket <> nil then
Break;
except
FServerSocket := nil;
end;
end;
if FServerSocket <> nil then
begin
LoopCount := 0;
FSyncEvent.SetEvent;
while not Terminated do
begin
LSocket := FServerSocket.Accept(TTetheringBTServerComm.AcceptTimeout);
if not Terminated and (LSocket <> nil) then
begin
FThreadComm := TTetheringBTServerComm.TBTCommThread.Create(FServerComm, LSocket);
FThreadComm.Start;
FThreadComm.FEvent.WaitFor(INFINITE);
LSocket.Close;
LSocket.Free;
FThreadComm.DisposeOf;
FThreadComm := nil;
Break;
end
else
begin
if LoopCount > CountTimeOut then //It's a RedirectedServer so if no one connect in 10 secs I close it to release the channel
Break;
Inc(LoopCount);
end;
end;
end;
end;
procedure TRedirectedServer.TerminatedSet;
begin
inherited;
if FServerSocket <> nil then
FServerSocket.Close;
end;
function TRedirectedServer.WaitInitialization: Boolean;
begin
Result := FSyncEvent.WaitFor(1500) = wrSignaled;
end;
{$ENDIF BT_PLATFORM}
end.
|
unit frVisibleColumns;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, StdCtrls, uCfgStorage;
type
{ TfraVisibleColumns }
TfraVisibleColumns = class(TFrame)
chkExchange1: TCheckBox;
chkCallSign: TCheckBox;
chkCont: TCheckBox;
chkDate: TCheckBox;
chkDXCC: TCheckBox;
chkExchange2: TCheckBox;
chkFreq: TCheckBox;
chkIOTA: TCheckBox;
chkITU: TCheckBox;
chkLoc: TCheckBox;
chkMode: TCheckBox;
chkMyLoc: TCheckBox;
chkName: TCheckBox;
chkPower: TCheckBox;
chkQTH: TCheckBox;
chkRST_R: TCheckBox;
chkRST_S: TCheckBox;
chkState: TCheckBox;
chkTimeOn: TCheckBox;
chkWAZ: TCheckBox;
private
{ private declarations }
public
procedure LoadSettings(ini : TCfgStorage);
procedure SaveSettings(ini : TCfgStorage);
end;
implementation
{$R *.lfm}
procedure TfraVisibleColumns.LoadSettings(ini : TCfgStorage);
begin
chkDate.Checked := ini.ReadBool('Columns','Date',True);
chkTimeOn.Checked := ini.ReadBool('Columns','Time',True);
chkCallSign.Checked := ini.ReadBool('Columns','Call',True);
chkMode.Checked := ini.ReadBool('Columns','Mode',True);
chkFreq.Checked := ini.ReadBool('Columns','Freq',True);
chkRST_S.Checked := ini.ReadBool('Columns','RST_S',True);
chkRST_R.Checked := ini.ReadBool('Columns','RST_R',True);
chkName.Checked := ini.ReadBool('Columns','Name',False);
chkQTH.Checked := ini.ReadBool('Columns','QTH',False);
chkMyLoc.Checked := ini.ReadBool('Columns','MyLoc',False);
chkLoc.Checked := ini.ReadBool('Columns','Loc',False);
chkIOTA.Checked := ini.ReadBool('Columns','IOTA',False);
chkPower.Checked := ini.ReadBool('Columns','Power',False);
chkDXCC.Checked := ini.ReadBool('Columns','DXCC',False);
chkWAZ.Checked := ini.ReadBool('Columns','WAZ',False);
chkITU.Checked := ini.ReadBool('Columns','ITU',False);
chkState.Checked := ini.ReadBool('Columns','State',False);
chkCont.Checked := ini.ReadBool('Columns','Continent',False);
chkExchange1.Checked := ini.ReadBool('Columns','Exchange1',True);
chkExchange2.Checked := ini.ReadBool('Columns','Exchange2',False)
end;
procedure TfraVisibleColumns.SaveSettings(ini : TCfgStorage);
begin
ini.WriteBool('Columns','Date',chkDate.Checked);
ini.WriteBool('Columns','Time',chkTimeOn.Checked);
ini.WriteBool('Columns','Call',chkCallSign.Checked);
ini.WriteBool('Columns','Mode',chkMode.Checked);
ini.WriteBool('Columns','Freq',chkFreq.Checked);
ini.WriteBool('Columns','RST_S',chkRST_S.Checked);
ini.WriteBool('Columns','RST_R',chkRST_R.Checked);
ini.WriteBool('Columns','Name',chkName.Checked);
ini.WriteBool('Columns','QTH',chkQTH.Checked);
ini.WriteBool('Columns','MyLoc',chkMyLoc.Checked);
ini.WriteBool('Columns','Loc',chkLoc.Checked);
ini.WriteBool('Columns','IOTA',chkIOTA.Checked);
ini.WriteBool('Columns','Power',chkPower.Checked);
ini.WriteBool('Columns','DXCC',chkDXCC.Checked);
ini.WriteBool('Columns','WAZ',chkWAZ.Checked);
ini.WriteBool('Columns','ITU',chkITU.Checked);
ini.WriteBool('Columns','State',chkState.Checked);
ini.WriteBool('Columns','Continent',chkCont.Checked);
ini.WriteBool('Columns','Exchange1',chkExchange1.Checked);
ini.WriteBool('Columns','Exchange2',chkExchange2.Checked)
end;
end.
|
unit ncDebTempo;
{
ResourceString: Dario 12/03/13
Nada para fazer
}
interface
uses
SysUtils,
DB,
Classes,
Windows,
ClasseCS,
ncClassesBase;
type
TncDebTempo = class (TClasseCS)
private
FID : Integer;
FDataHora : TDateTime;
FFunc : String;
FCliente : Integer;
FTotal : Currency;
FDesconto : Currency;
FPago : Currency;
FObs : String;
FCancelado : Boolean;
FCanceladoPor: String;
FCanceladoEm : TDateTime;
FCaixa : Integer;
FRecibo : Boolean;
FQtdTempo : Double;
FCredValor : Boolean;
function GetTipo: Integer;
procedure SetTipo(const Value: Integer);
protected
function GetChave: Variant; override;
public
constructor Create;
procedure Limpa;
published
property ID : Integer
read FID write FID;
property DataHora : TDateTime
read FDataHora write FDataHora;
property Tipo : Integer
read GetTipo write SetTipo;
property Func : String
read FFunc write FFunc;
property Obs : String
read FObs write FObs;
property Cancelado : Boolean
read FCancelado write FCancelado;
property CanceladoPor : String
read FCanceladoPor write FCanceladoPor;
property CanceladoEm : TDateTime
read FCanceladoEm write FCanceladoEm;
property Caixa : Integer
read FCaixa write FCaixa;
property QtdTempo: Double
read FQtdTempo write FQtdTempo;
property CredValor: Boolean
read FCredValor write FCredValor;
property Cliente: Integer
read FCliente write FCliente;
property Recibo : Boolean
read FRecibo write FRecibo;
end;
implementation
{ TncLancExtra }
constructor TncDebTempo.Create;
begin
inherited;
Limpa;
end;
function TncDebTempo.GetChave: Variant;
begin
Result := FID;
end;
function TncDebTempo.GetTipo: Integer;
begin
Result := trDebTempo;
end;
procedure TncDebTempo.Limpa;
begin
FID := -1;
FDataHora := Now;
FFunc := '';
FObs := '';
FCancelado := False;
FCanceladoPor:= '';
FCanceladoEm := 0;
FCaixa := 0;
FQtdTempo := 0;
FCredValor := False;
FRecibo := False;
end;
procedure TncDebTempo.SetTipo(const Value: Integer);
begin
//
end;
end.
|
unit Dialogs4D.Input.Intf;
interface
type
IDialogInput = interface
['{213F3C9D-3CED-4407-82ED-4B0A143391DE}']
/// <summary>
/// Displays a dialog box for the user with an input box.
/// </summary>
/// <param name="Description">
/// Input box description.
/// </param>
/// <param name="Default">
/// Default value for the input box.
/// </param>
/// <returns>
/// User defined value.
/// </returns>
function Show(const Description, Default: string): string;
end;
implementation
end.
|
UNIT TurtleO;
{ OOP turtle routines }
{$N+}
interface
TYPE
{ ================================================================== }
TurtleObj = OBJECT
{ Don't touch these things }
X,
Y : SINGLE;
StepSize,
Theta : SINGLE;
Draw : BOOLEAN;
{ Use these procedures }
CONSTRUCTOR Init(StartX,StartY : SINGLE);
PROCEDURE Turn(angle : SINGLE);
PROCEDURE ChangeStep(PixelsPerStep : SINGLE);
PROCEDURE StartDrawing;
PROCEDURE StopDrawing;
PROCEDURE Step;
{ Move Turtle One Step according to step size and angle }
PROCEDURE Point(X1,Y1,X2,Y2 : SINGLE);
{point turtle parallel to line described by x1,y1-x2,y2}
DESTRUCTOR Done;
END {TurtleObj };
{ ================================================================== }
implementation
USES
GraphPrm {LineDraw};
VAR
HaPiRadian : SINGLE;
{ ------------------------------------------------------------ }
CONSTRUCTOR TurtleObj.Init(StartX,StartY : SINGLE);
BEGIN
x := StartX;
y := StartY;
StepSize := 1;
Theta := 0;
Draw := FALSE;
END;
{ ------------------------------------------------------------ }
PROCEDURE TurtleObj.Turn(angle : SINGLE);
BEGIN
Theta := (Theta + angle);
{ ensure a valid angle }
REPEAT
IF Theta >= 360.0 THEN
Theta := Theta - 360.0
ELSE IF Theta < 0.0 THEN
Theta := 360.0 + Theta;
UNTIL (Theta < 360.0) AND NOT (Theta < 0.0)
END;
{ ------------------------------------------------------------ }
PROCEDURE TurtleObj.ChangeStep(PixelsPerStep : SINGLE);
BEGIN
StepSize := PixelsPerStep;
END;
{ ------------------------------------------------------------ }
PROCEDURE TurtleObj.StartDrawing;
BEGIN
Draw := TRUE;
END;
{ ------------------------------------------------------------ }
PROCEDURE TurtleObj.StopDrawing;
BEGIN
Draw := FALSE;
END;
{ ------------------------------------------------------------ }
PROCEDURE TurtleObj.Step;
VAR
OldX, OldY : SINGLE;
BEGIN
OldX := x;
OldY := y;
X := X + StepSize * cos(Theta*HaPiRadian);
Y := Y + StepSize * sin(Theta*HaPiRadian);
IF Draw THEN
DrawLine(TRUNC(OldX),TRUNC(OldY),TRUNC(x),TRUNC(y),15);
END;
{ ------------------------------------------------------------ }
PROCEDURE TurtleObj.Point(X1,Y1,X2,Y2 : SINGLE);
BEGIN
IF (x2-x1) = 0 THEN
IF y2 > y1 THEN
theta := 90.0
ELSE
theta := 270.0
ELSE
theta := ArcTan((y2-y1)/(x2-x1)) / HaPiRadian;
IF x1 > x2 THEN
theta := theta + 180;
END;
DESTRUCTOR TurtleObj.Done;
BEGIN
END;
{ ------------------------------------------------------------ }
BEGIN
HaPiRadian := Pi / 180.0;
END. |
unit trees;
{$T-}
(************************************************************************
trees.c -- output deflated data using Huffman coding
Copyright (C) 1995-1998 Jean-loup Gailly
------------------------------------------------------------------------
ALGORITHM
The "deflation" process uses several Huffman trees. The more common source
values are represented by shorter bit sequences.
Each code tree is stored in a compressed form which is itself
a Huffman encoding of the lengths of all the code strings (in
ascending order by source values). The actual code strings are
reconstructed from the lengths in the inflate process, as described
in the deflate specification.
REFERENCES
Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
Storer, James A.
Data Compression: Methods and Theory, pp. 49-50.
Computer Science Press, 1988. ISBN 0-7167-8156-5.
Sedgewick, R.
Algorithms, p290.
Addison-Wesley, 1983. ISBN 0-201-06672-6.
------------------------------------------------------------------------
Pascal translation
Copyright (C) 1998 by Jacques Nomssi Nzali
For conditions of distribution and use, see copyright notice in readme.txt
------------------------------------------------------------------------
Modifications by W.Ehrhardt:
Aug 2000
- ZLIB 113 changes
Feb 2002
- Source code reformating/reordering
- $ifdefs ORG_DEBUG, GEN_TREES_H, DUMP_BL_TREE,
FORCE_STORED, FORCE_STATIC removed
- Replaced printf fragments in trace call by IntToStr
Mar 2005
- Code cleanup for WWW upload
Apr 2005
- uses zutil if debug
May 2005
- Trace: use #13#10 like C original
- Debug: removed MAX_DIST in _tr_tally
- Debug: Long type cast in compress_block
Dec 2006
- Debug: fixed old paszlib bug in copy_block
Jul 2009
- D12 fixes
------------------------------------------------------------------------
*************************************************************************)
interface
{$I zconf.inc}
uses
zlibh;
const
LENGTH_CODES = 29; {number of length codes, not counting the special END_BLOCK code}
LITERALS = 256; {number of literal bytes 0..255}
D_CODES = 30; {number of distance codes}
BL_CODES = 19; {number of codes used to transfer the bit lengths}
MAX_BITS = 15; {All codes must not exceed MAX_BITS bits}
L_CODES = (LITERALS+1+LENGTH_CODES); {number of Literal or Length codes, including the END_BLOCK code}
HEAP_SIZE = (2*L_CODES+1); {maximum heap size}
const
INIT_STATE = 42; {Stream status}
BUSY_STATE = 113;
FINISH_STATE = 666;
{Data structure describing a single value and its code string.}
type
ct_data = record
fc: record
case byte of
0: (freq: ush); {frequency count}
1: (code: ush); {bit string}
end;
dl: record
case byte of
0: (dad: ush); {father node in Huffman tree}
1: (len: ush); {length of bit string}
end;
end;
type
ltree_type = array[0..HEAP_SIZE-1] of ct_data; {literal and length tree}
dtree_type = array[0..2*D_CODES+1-1] of ct_data; {distance tree}
htree_type = array[0..2*BL_CODES+1-1] of ct_data; {Huffman tree for bit lengths}
{generic tree type}
tree_type = array[0..(MaxMemBlock div sizeof(ct_data))-1] of ct_data;
tree_ptr = ^tree_type;
type
static_tree_desc_ptr = ^static_tree_desc;
static_tree_desc = record
static_tree: tree_ptr; {static tree or nil}
extra_bits : pzIntfArray; {extra bits for each code or nil}
extra_base : int; {base index for extra_bits}
elems : int; {max number of elements in the tree}
max_length : int; {max bit length for the codes}
end;
tree_desc = record
dyn_tree : tree_ptr; {the dynamic tree}
max_code : int; {largest code with non zero frequency}
stat_desc: static_tree_desc_ptr; {the corresponding static tree}
end;
{A Pos is an index in the character window. We use short instead of int to
save space in the various tables. IPos is used only for parameter passing.}
type
Pos = ush;
Posf = Pos; {far}
IPos = uInt;
pPosf = ^Posf;
zPosfArray = array[0..(MaxMemBlock div sizeof(Posf))-1] of Posf;
pzPosfArray = ^zPosfArray;
type
zuchfArray = zByteArray;
puchfArray = ^zuchfArray;
type
zushfArray = array[0..(MaxMemBlock div sizeof(ushf))-1] of ushf;
pushfArray = ^zushfArray;
type
deflate_state_ptr = ^deflate_state;
deflate_state = record
strm: z_streamp; {pointer back to this zlib stream}
status: int; {as the name implies}
pending_buf: pzByteArray; {output still pending}
pending_buf_size: ulg; {size of pending_buf}
pending_out: pBytef; {next pending byte to output to the stream}
pending: int; {nb of bytes in the pending buffer}
noheader: int; {suppress zlib header and adler32}
data_type: byte; {UNKNOWN, BINARY or ASCII}
method: byte; {STORED (for zip only) or DEFLATED}
last_flush: int; {value of flush param for previous deflate call}
{used by deflate.pas:}
w_size: uInt; {LZ77 window size (32K by default)}
w_bits: uInt; {log2(w_size) (8..16)}
w_mask: uInt; {w_size - 1}
window: pzByteArray;
{Sliding window. Input bytes are read into the second half of the window,
and move to the first half later to keep a dictionary of at least wSize
bytes. With this organization, matches are limited to a distance of
wSize-MAX_MATCH bytes, but this ensures that IO is always
performed with a length multiple of the block size. Also, it limits
the window size to 64K, which is quite useful on MSDOS.
To do: use the user input buffer as sliding window.}
window_size: ulg;
{Actual size of window: 2*wSize, except when the user input buffer
is directly used as sliding window.}
prev: pzPosfArray;
{Link to older string with same hash index. To limit the size of this
array to 64K, this link is maintained only for the last 32K strings.
An index in this array is thus a window index modulo 32K.}
head: pzPosfArray; {Heads of the hash chains or nil.}
ins_h: uInt; {hash index of string to be inserted}
hash_size: uInt; {number of elements in hash table}
hash_bits: uInt; {log2(hash_size)}
hash_mask: uInt; {hash_size-1}
hash_shift: uInt;
{Number of bits by which ins_h must be shifted at each input
step. It must be such that after MIN_MATCH steps, the oldest
byte no longer takes part in the hash key, that is:
hash_shift * MIN_MATCH >= hash_bits }
block_start: long;
{Window position at the beginning of the current output block. Gets
negative when the window is moved backwards.}
match_length: uInt; {length of best match}
prev_match: IPos; {previous match}
match_available: boolean; {set if previous match exists}
strstart: uInt; {start of string to insert}
match_start: uInt; {start of matching string}
lookahead: uInt; {number of valid bytes ahead in window}
prev_length: uInt;
{Length of the best match at previous step. Matches not greater than this
are discarded. This is used in the lazy match evaluation.}
max_chain_length: uInt;
{To speed up deflation, hash chains are never searched beyond this
length. A higher limit improves compression ratio but degrades the
speed.}
{moved to the end because Borland Pascal won't accept the following:
max_lazy_match: uInt;
max_insert_length: uInt absolute max_lazy_match;}
level: int; {compression level (1..9)}
strategy: int; {favor or force Huffman coding}
good_match: uInt;
{Use a faster search when the previous match is longer than this}
nice_match: int; {Stop searching when current match exceeds this}
{used by trees.pas:}
{Didn't use ct_data typedef below to supress compiler warning}
dyn_ltree: ltree_type; {literal and length tree}
dyn_dtree: dtree_type; {distance tree}
bl_tree: htree_type; {Huffman tree for bit lengths}
l_desc: tree_desc; {desc. for literal tree}
d_desc: tree_desc; {desc. for distance tree}
bl_desc: tree_desc; {desc. for bit length tree}
bl_count: array[0..MAX_BITS+1-1] of ush;
{number of codes at each bit length for an optimal tree}
heap: array[0..2*L_CODES+1-1] of int; {heap used to build the Huffman trees}
heap_len: int; {number of elements in the heap}
heap_max: int; {element of largest frequency}
{The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
The same heap array is used to build all trees.}
depth: array[0..2*L_CODES+1-1] of uch;
{Depth of each subtree used as tie breaker for trees of equal frequency}
l_buf: puchfArray; {buffer for literals or lengths}
lit_bufsize: uInt;
{Size of match buffer for literals/lengths. There are 4 reasons for
limiting lit_bufsize to 64K:
- frequencies can be kept in 16 bit counters
- if compression is not successful for the first block, all input
data is still in the window so we can still emit a stored block even
when input comes from standard input. (This can also be done for
all blocks if lit_bufsize is not greater than 32K.)
- if compression is not successful for a file smaller than 64K, we can
even emit a stored file instead of a stored block (saving 5 bytes).
This is applicable only for zip (not gzip or zlib).
- creating new Huffman trees less frequently may not provide fast
adaptation to changes in the input data statistics. (Take for
example a binary file with poorly compressible code followed by
a highly compressible string table.) Smaller buffer sizes give
fast adaptation but have of course the overhead of transmitting
trees more frequently.
- I can't count above 4}
last_lit: uInt; {running index in l_buf}
d_buf: pushfArray;
{Buffer for distances. To simplify the code, d_buf and l_buf have
the same number of elements. To use different lengths, an extra flag
array would be necessary.}
opt_len: ulg; {bit length of current block with optimal trees}
static_len: ulg; {bit length of current block with static trees}
matches: uInt; {number of string matches in current block}
last_eob_len: int; {bit length of EOB code for last block}
{$ifdef DEBUG}
compressed_len: ulg; {total bit length of compressed file} {*we 113}
bits_sent: ulg; {bit length of the compressed data}
{$endif}
bi_buf: ush;
{Output buffer. bits are inserted starting at the bottom (least
significant bits).}
bi_valid: int;
{Number of valid bits in bi_buf. All bits above the last valid bit
are always zero.}
case byte of
0:(max_lazy_match: uInt);
{Attempt to find a better match only when the current match is strictly
smaller than this value. This mechanism is used only for compression
levels >= 4.}
1:(max_insert_length: uInt);
{Insert new strings in the hash table only if the match length is not
greater than this length. This saves time but degrades compression.
max_insert_length is used only for compression levels <= 3.}
end;
procedure _tr_init(var s: deflate_state);
function _tr_tally(var s: deflate_state; dist: unsigned; lc: unsigned): boolean;
procedure _tr_flush_block(var s: deflate_state; buf: pcharf; stored_len: ulg; eof: boolean); {*we 113}
procedure _tr_stored_block(var s: deflate_state; buf: pcharf; stored_len: ulg; eof: boolean);
procedure _tr_align(var s: deflate_state);
implementation
{$ifdef debug}
uses zutil;
{$endif}
const
DIST_CODE_LEN = 512; {see definition of array dist_code below}
{The static literal tree. Since the bit lengths are imposed, there is no
need for the L_CODES extra codes used during heap construction. However
The codes 286 and 287 are needed to build a canonical tree (see _tr_init
below).}
const
static_ltree: array[0..L_CODES+2-1] of ct_data = (
{fc:(freq cod) dl:(dad,len)}
(fc:(freq: 12);dl:(len: 8)), (fc:(freq:140);dl:(len: 8)),
(fc:(freq: 76);dl:(len: 8)), (fc:(freq:204);dl:(len: 8)),
(fc:(freq: 44);dl:(len: 8)), (fc:(freq:172);dl:(len: 8)),
(fc:(freq:108);dl:(len: 8)), (fc:(freq:236);dl:(len: 8)),
(fc:(freq: 28);dl:(len: 8)), (fc:(freq:156);dl:(len: 8)),
(fc:(freq: 92);dl:(len: 8)), (fc:(freq:220);dl:(len: 8)),
(fc:(freq: 60);dl:(len: 8)), (fc:(freq:188);dl:(len: 8)),
(fc:(freq:124);dl:(len: 8)), (fc:(freq:252);dl:(len: 8)),
(fc:(freq: 2);dl:(len: 8)), (fc:(freq:130);dl:(len: 8)),
(fc:(freq: 66);dl:(len: 8)), (fc:(freq:194);dl:(len: 8)),
(fc:(freq: 34);dl:(len: 8)), (fc:(freq:162);dl:(len: 8)),
(fc:(freq: 98);dl:(len: 8)), (fc:(freq:226);dl:(len: 8)),
(fc:(freq: 18);dl:(len: 8)), (fc:(freq:146);dl:(len: 8)),
(fc:(freq: 82);dl:(len: 8)), (fc:(freq:210);dl:(len: 8)),
(fc:(freq: 50);dl:(len: 8)), (fc:(freq:178);dl:(len: 8)),
(fc:(freq:114);dl:(len: 8)), (fc:(freq:242);dl:(len: 8)),
(fc:(freq: 10);dl:(len: 8)), (fc:(freq:138);dl:(len: 8)),
(fc:(freq: 74);dl:(len: 8)), (fc:(freq:202);dl:(len: 8)),
(fc:(freq: 42);dl:(len: 8)), (fc:(freq:170);dl:(len: 8)),
(fc:(freq:106);dl:(len: 8)), (fc:(freq:234);dl:(len: 8)),
(fc:(freq: 26);dl:(len: 8)), (fc:(freq:154);dl:(len: 8)),
(fc:(freq: 90);dl:(len: 8)), (fc:(freq:218);dl:(len: 8)),
(fc:(freq: 58);dl:(len: 8)), (fc:(freq:186);dl:(len: 8)),
(fc:(freq:122);dl:(len: 8)), (fc:(freq:250);dl:(len: 8)),
(fc:(freq: 6);dl:(len: 8)), (fc:(freq:134);dl:(len: 8)),
(fc:(freq: 70);dl:(len: 8)), (fc:(freq:198);dl:(len: 8)),
(fc:(freq: 38);dl:(len: 8)), (fc:(freq:166);dl:(len: 8)),
(fc:(freq:102);dl:(len: 8)), (fc:(freq:230);dl:(len: 8)),
(fc:(freq: 22);dl:(len: 8)), (fc:(freq:150);dl:(len: 8)),
(fc:(freq: 86);dl:(len: 8)), (fc:(freq:214);dl:(len: 8)),
(fc:(freq: 54);dl:(len: 8)), (fc:(freq:182);dl:(len: 8)),
(fc:(freq:118);dl:(len: 8)), (fc:(freq:246);dl:(len: 8)),
(fc:(freq: 14);dl:(len: 8)), (fc:(freq:142);dl:(len: 8)),
(fc:(freq: 78);dl:(len: 8)), (fc:(freq:206);dl:(len: 8)),
(fc:(freq: 46);dl:(len: 8)), (fc:(freq:174);dl:(len: 8)),
(fc:(freq:110);dl:(len: 8)), (fc:(freq:238);dl:(len: 8)),
(fc:(freq: 30);dl:(len: 8)), (fc:(freq:158);dl:(len: 8)),
(fc:(freq: 94);dl:(len: 8)), (fc:(freq:222);dl:(len: 8)),
(fc:(freq: 62);dl:(len: 8)), (fc:(freq:190);dl:(len: 8)),
(fc:(freq:126);dl:(len: 8)), (fc:(freq:254);dl:(len: 8)),
(fc:(freq: 1);dl:(len: 8)), (fc:(freq:129);dl:(len: 8)),
(fc:(freq: 65);dl:(len: 8)), (fc:(freq:193);dl:(len: 8)),
(fc:(freq: 33);dl:(len: 8)), (fc:(freq:161);dl:(len: 8)),
(fc:(freq: 97);dl:(len: 8)), (fc:(freq:225);dl:(len: 8)),
(fc:(freq: 17);dl:(len: 8)), (fc:(freq:145);dl:(len: 8)),
(fc:(freq: 81);dl:(len: 8)), (fc:(freq:209);dl:(len: 8)),
(fc:(freq: 49);dl:(len: 8)), (fc:(freq:177);dl:(len: 8)),
(fc:(freq:113);dl:(len: 8)), (fc:(freq:241);dl:(len: 8)),
(fc:(freq: 9);dl:(len: 8)), (fc:(freq:137);dl:(len: 8)),
(fc:(freq: 73);dl:(len: 8)), (fc:(freq:201);dl:(len: 8)),
(fc:(freq: 41);dl:(len: 8)), (fc:(freq:169);dl:(len: 8)),
(fc:(freq:105);dl:(len: 8)), (fc:(freq:233);dl:(len: 8)),
(fc:(freq: 25);dl:(len: 8)), (fc:(freq:153);dl:(len: 8)),
(fc:(freq: 89);dl:(len: 8)), (fc:(freq:217);dl:(len: 8)),
(fc:(freq: 57);dl:(len: 8)), (fc:(freq:185);dl:(len: 8)),
(fc:(freq:121);dl:(len: 8)), (fc:(freq:249);dl:(len: 8)),
(fc:(freq: 5);dl:(len: 8)), (fc:(freq:133);dl:(len: 8)),
(fc:(freq: 69);dl:(len: 8)), (fc:(freq:197);dl:(len: 8)),
(fc:(freq: 37);dl:(len: 8)), (fc:(freq:165);dl:(len: 8)),
(fc:(freq:101);dl:(len: 8)), (fc:(freq:229);dl:(len: 8)),
(fc:(freq: 21);dl:(len: 8)), (fc:(freq:149);dl:(len: 8)),
(fc:(freq: 85);dl:(len: 8)), (fc:(freq:213);dl:(len: 8)),
(fc:(freq: 53);dl:(len: 8)), (fc:(freq:181);dl:(len: 8)),
(fc:(freq:117);dl:(len: 8)), (fc:(freq:245);dl:(len: 8)),
(fc:(freq: 13);dl:(len: 8)), (fc:(freq:141);dl:(len: 8)),
(fc:(freq: 77);dl:(len: 8)), (fc:(freq:205);dl:(len: 8)),
(fc:(freq: 45);dl:(len: 8)), (fc:(freq:173);dl:(len: 8)),
(fc:(freq:109);dl:(len: 8)), (fc:(freq:237);dl:(len: 8)),
(fc:(freq: 29);dl:(len: 8)), (fc:(freq:157);dl:(len: 8)),
(fc:(freq: 93);dl:(len: 8)), (fc:(freq:221);dl:(len: 8)),
(fc:(freq: 61);dl:(len: 8)), (fc:(freq:189);dl:(len: 8)),
(fc:(freq:125);dl:(len: 8)), (fc:(freq:253);dl:(len: 8)),
(fc:(freq: 19);dl:(len: 9)), (fc:(freq:275);dl:(len: 9)),
(fc:(freq:147);dl:(len: 9)), (fc:(freq:403);dl:(len: 9)),
(fc:(freq: 83);dl:(len: 9)), (fc:(freq:339);dl:(len: 9)),
(fc:(freq:211);dl:(len: 9)), (fc:(freq:467);dl:(len: 9)),
(fc:(freq: 51);dl:(len: 9)), (fc:(freq:307);dl:(len: 9)),
(fc:(freq:179);dl:(len: 9)), (fc:(freq:435);dl:(len: 9)),
(fc:(freq:115);dl:(len: 9)), (fc:(freq:371);dl:(len: 9)),
(fc:(freq:243);dl:(len: 9)), (fc:(freq:499);dl:(len: 9)),
(fc:(freq: 11);dl:(len: 9)), (fc:(freq:267);dl:(len: 9)),
(fc:(freq:139);dl:(len: 9)), (fc:(freq:395);dl:(len: 9)),
(fc:(freq: 75);dl:(len: 9)), (fc:(freq:331);dl:(len: 9)),
(fc:(freq:203);dl:(len: 9)), (fc:(freq:459);dl:(len: 9)),
(fc:(freq: 43);dl:(len: 9)), (fc:(freq:299);dl:(len: 9)),
(fc:(freq:171);dl:(len: 9)), (fc:(freq:427);dl:(len: 9)),
(fc:(freq:107);dl:(len: 9)), (fc:(freq:363);dl:(len: 9)),
(fc:(freq:235);dl:(len: 9)), (fc:(freq:491);dl:(len: 9)),
(fc:(freq: 27);dl:(len: 9)), (fc:(freq:283);dl:(len: 9)),
(fc:(freq:155);dl:(len: 9)), (fc:(freq:411);dl:(len: 9)),
(fc:(freq: 91);dl:(len: 9)), (fc:(freq:347);dl:(len: 9)),
(fc:(freq:219);dl:(len: 9)), (fc:(freq:475);dl:(len: 9)),
(fc:(freq: 59);dl:(len: 9)), (fc:(freq:315);dl:(len: 9)),
(fc:(freq:187);dl:(len: 9)), (fc:(freq:443);dl:(len: 9)),
(fc:(freq:123);dl:(len: 9)), (fc:(freq:379);dl:(len: 9)),
(fc:(freq:251);dl:(len: 9)), (fc:(freq:507);dl:(len: 9)),
(fc:(freq: 7);dl:(len: 9)), (fc:(freq:263);dl:(len: 9)),
(fc:(freq:135);dl:(len: 9)), (fc:(freq:391);dl:(len: 9)),
(fc:(freq: 71);dl:(len: 9)), (fc:(freq:327);dl:(len: 9)),
(fc:(freq:199);dl:(len: 9)), (fc:(freq:455);dl:(len: 9)),
(fc:(freq: 39);dl:(len: 9)), (fc:(freq:295);dl:(len: 9)),
(fc:(freq:167);dl:(len: 9)), (fc:(freq:423);dl:(len: 9)),
(fc:(freq:103);dl:(len: 9)), (fc:(freq:359);dl:(len: 9)),
(fc:(freq:231);dl:(len: 9)), (fc:(freq:487);dl:(len: 9)),
(fc:(freq: 23);dl:(len: 9)), (fc:(freq:279);dl:(len: 9)),
(fc:(freq:151);dl:(len: 9)), (fc:(freq:407);dl:(len: 9)),
(fc:(freq: 87);dl:(len: 9)), (fc:(freq:343);dl:(len: 9)),
(fc:(freq:215);dl:(len: 9)), (fc:(freq:471);dl:(len: 9)),
(fc:(freq: 55);dl:(len: 9)), (fc:(freq:311);dl:(len: 9)),
(fc:(freq:183);dl:(len: 9)), (fc:(freq:439);dl:(len: 9)),
(fc:(freq:119);dl:(len: 9)), (fc:(freq:375);dl:(len: 9)),
(fc:(freq:247);dl:(len: 9)), (fc:(freq:503);dl:(len: 9)),
(fc:(freq: 15);dl:(len: 9)), (fc:(freq:271);dl:(len: 9)),
(fc:(freq:143);dl:(len: 9)), (fc:(freq:399);dl:(len: 9)),
(fc:(freq: 79);dl:(len: 9)), (fc:(freq:335);dl:(len: 9)),
(fc:(freq:207);dl:(len: 9)), (fc:(freq:463);dl:(len: 9)),
(fc:(freq: 47);dl:(len: 9)), (fc:(freq:303);dl:(len: 9)),
(fc:(freq:175);dl:(len: 9)), (fc:(freq:431);dl:(len: 9)),
(fc:(freq:111);dl:(len: 9)), (fc:(freq:367);dl:(len: 9)),
(fc:(freq:239);dl:(len: 9)), (fc:(freq:495);dl:(len: 9)),
(fc:(freq: 31);dl:(len: 9)), (fc:(freq:287);dl:(len: 9)),
(fc:(freq:159);dl:(len: 9)), (fc:(freq:415);dl:(len: 9)),
(fc:(freq: 95);dl:(len: 9)), (fc:(freq:351);dl:(len: 9)),
(fc:(freq:223);dl:(len: 9)), (fc:(freq:479);dl:(len: 9)),
(fc:(freq: 63);dl:(len: 9)), (fc:(freq:319);dl:(len: 9)),
(fc:(freq:191);dl:(len: 9)), (fc:(freq:447);dl:(len: 9)),
(fc:(freq:127);dl:(len: 9)), (fc:(freq:383);dl:(len: 9)),
(fc:(freq:255);dl:(len: 9)), (fc:(freq:511);dl:(len: 9)),
(fc:(freq: 0);dl:(len: 7)), (fc:(freq: 64);dl:(len: 7)),
(fc:(freq: 32);dl:(len: 7)), (fc:(freq: 96);dl:(len: 7)),
(fc:(freq: 16);dl:(len: 7)), (fc:(freq: 80);dl:(len: 7)),
(fc:(freq: 48);dl:(len: 7)), (fc:(freq:112);dl:(len: 7)),
(fc:(freq: 8);dl:(len: 7)), (fc:(freq: 72);dl:(len: 7)),
(fc:(freq: 40);dl:(len: 7)), (fc:(freq:104);dl:(len: 7)),
(fc:(freq: 24);dl:(len: 7)), (fc:(freq: 88);dl:(len: 7)),
(fc:(freq: 56);dl:(len: 7)), (fc:(freq:120);dl:(len: 7)),
(fc:(freq: 4);dl:(len: 7)), (fc:(freq: 68);dl:(len: 7)),
(fc:(freq: 36);dl:(len: 7)), (fc:(freq:100);dl:(len: 7)),
(fc:(freq: 20);dl:(len: 7)), (fc:(freq: 84);dl:(len: 7)),
(fc:(freq: 52);dl:(len: 7)), (fc:(freq:116);dl:(len: 7)),
(fc:(freq: 3);dl:(len: 8)), (fc:(freq:131);dl:(len: 8)),
(fc:(freq: 67);dl:(len: 8)), (fc:(freq:195);dl:(len: 8)),
(fc:(freq: 35);dl:(len: 8)), (fc:(freq:163);dl:(len: 8)),
(fc:(freq: 99);dl:(len: 8)), (fc:(freq:227);dl:(len: 8)) );
{The static distance tree. (Actually a trivial tree since all lens use 5 bits.)}
static_dtree: array[0..D_CODES-1] of ct_data = (
(fc:(freq: 0); dl:(len:5)), (fc:(freq:16); dl:(len:5)),
(fc:(freq: 8); dl:(len:5)), (fc:(freq:24); dl:(len:5)),
(fc:(freq: 4); dl:(len:5)), (fc:(freq:20); dl:(len:5)),
(fc:(freq:12); dl:(len:5)), (fc:(freq:28); dl:(len:5)),
(fc:(freq: 2); dl:(len:5)), (fc:(freq:18); dl:(len:5)),
(fc:(freq:10); dl:(len:5)), (fc:(freq:26); dl:(len:5)),
(fc:(freq: 6); dl:(len:5)), (fc:(freq:22); dl:(len:5)),
(fc:(freq:14); dl:(len:5)), (fc:(freq:30); dl:(len:5)),
(fc:(freq: 1); dl:(len:5)), (fc:(freq:17); dl:(len:5)),
(fc:(freq: 9); dl:(len:5)), (fc:(freq:25); dl:(len:5)),
(fc:(freq: 5); dl:(len:5)), (fc:(freq:21); dl:(len:5)),
(fc:(freq:13); dl:(len:5)), (fc:(freq:29); dl:(len:5)),
(fc:(freq: 3); dl:(len:5)), (fc:(freq:19); dl:(len:5)),
(fc:(freq:11); dl:(len:5)), (fc:(freq:27); dl:(len:5)),
(fc:(freq: 7); dl:(len:5)), (fc:(freq:23); dl:(len:5)) );
{Distance codes. The first 256 values correspond to the distances
3 .. 258, the last 256 values correspond to the top 8 bits of
the 15 bit distances.}
_dist_code: array[0..DIST_CODE_LEN-1] of uch = (
0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21,
22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 );
{length code for each normalized match length (0 == MIN_MATCH)}
_length_code: array[0..MAX_MATCH-MIN_MATCH+1-1] of uch = (
0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10,
11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14,
15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17,
17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18,
19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20,
20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23,
23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 28 );
{First normalized length for each code (0 = MIN_MATCH)}
base_length: array[0..LENGTH_CODES-1] of int = (
0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28,
32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0);
{First normalized distance for each code (0 = distance of 1)}
base_dist: array[0..D_CODES-1] of int = (
0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 );
const
MAX_BL_BITS = 7; {Bit length codes must not exceed MAX_BL_BITS bits}
END_BLOCK = 256; {end of block literal code}
REP_3_6 = 16; {repeat previous bit length 3-6 times (2 bits of repeat count)}
REPZ_3_10 = 17; {repeat a zero length 3-10 times (3 bits of repeat count)}
REPZ_11_138 = 18; {repeat a zero length 11-138 times (7 bits of repeat count)}
const
extra_lbits : array[0..LENGTH_CODES-1] of int = {extra bits for each length code}
(0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0);
const
extra_dbits : array[0..D_CODES-1] of int = {extra bits for each distance code}
(0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13);
const
extra_blbits: array[0..BL_CODES-1] of int = {extra bits for each bit length code}
(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7);
const
bl_order: array[0..BL_CODES-1] of uch =
(16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
{The lengths of the bit length codes are sent in order of decreasing
probability, to avoid transmitting the lengths for unused bit length codes.
}
const
Buf_size = (8 * 2*sizeof(char8)); {Number of bits used within bi_buf. (bi_buf might be implemented on
more than 16 bits on some systems.)}
const
static_l_desc: static_tree_desc =
(static_tree: @static_ltree; {pointer to array of ct_data}
extra_bits: @extra_lbits; {pointer to array of int}
extra_base: LITERALS+1;
elems: L_CODES;
max_length: MAX_BITS);
const
static_d_desc: static_tree_desc =
(static_tree: @static_dtree;
extra_bits: @extra_dbits;
extra_base: 0;
elems: D_CODES;
max_length: MAX_BITS);
const
static_bl_desc: static_tree_desc =
(static_tree: nil;
extra_bits: @extra_blbits;
extra_base: 0;
elems: BL_CODES;
max_length: MAX_BL_BITS);
{---------------------------------------------------------------------------}
procedure send_bits(var s: deflate_state;
value: int; {value to send}
length: int); {number of bits}
{-Send a value on a given number of bits.
IN assertion: length <= 16 and value fits in length bits.}
begin
{$ifdef DEBUG}
Tracevv(' l '+IntToStr(length)+ ' v '+IntToStr(value));
Assert((length > 0) and (length <= 15), 'invalid length');
inc(s.bits_sent, ulg(length));
{$endif}
{If not enough room in bi_buf, use (valid) bits from bi_buf and
(16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
unused bits in value.}
{$ifopt Q+} {$Q-} {$define NoOverflowCheck} {$endif}
{$ifopt R+} {$R-} {$define NoRangeCheck} {$endif}
if s.bi_valid > int(Buf_size) - length then begin
s.bi_buf := s.bi_buf or int(value shl s.bi_valid);
{put_short(s, s.bi_buf);}
s.pending_buf^[s.pending] := uch(s.bi_buf and $ff);
inc(s.pending);
s.pending_buf^[s.pending] := uch(ush(s.bi_buf) shr 8);;
inc(s.pending);
s.bi_buf := ush(value) shr (Buf_size - s.bi_valid);
inc(s.bi_valid, length - Buf_size);
end
else begin
s.bi_buf := s.bi_buf or int(value shl s.bi_valid);
inc(s.bi_valid, length);
end;
{$ifdef NoOverflowCheck} {$Q+} {$undef NoOverflowCheck} {$endif}
{$ifdef NoRangeCheck} {$Q+} {$undef NoRangeCheck} {$endif}
end;
{---------------------------------------------------------------------------}
function bi_reverse(code: unsigned; len: int): unsigned;
{-Reverse the first len bits of a code}
{ using straightforward code (a faster method would use a table)
IN assertion: 1 <= len <= 15}
var
res: unsigned; {register}
begin
res := 0;
repeat
res := res or (code and 1);
code := code shr 1;
res := res shl 1;
dec(len);
until len<=0;
bi_reverse := res shr 1;
end;
{---------------------------------------------------------------------------}
procedure gen_codes( tree: tree_ptr; {the tree to decorate}
max_code: int; {largest code with non zero frequency}
var bl_count: array of ushf); {number of codes at each bit length}
{-Generate the codes for a given tree and bit counts (which need not be optimal).}
{ IN assertion: the array bl_count contains the bit length statistics for
the given tree and the field len is set for all tree elements.
OUT assertion: the field code is set for all tree elements of non
zero code length.}
var
code: ush; {running code value}
bits: int; {bit index}
n: int; {code index}
len: int;
next_code: array[0..MAX_BITS+1-1] of ush; {next code value for each bit length}
begin
code := 0;
{The distribution counts are first used to generate the code values
without bit reversal.}
for bits := 1 to MAX_BITS do begin
code := (code + bl_count[bits-1]) shl 1;
next_code[bits] := code;
end;
{Check that the bit counts in bl_count are consistent. The last code
must be all ones.}
{$ifdef DEBUG}
Assert(code + bl_count[MAX_BITS]-1 = (1 shl MAX_BITS)-1, 'inconsistent bit counts');
Tracev(#13#10'gen_codes: max_code '+IntToStr(max_code));
{$endif}
for n := 0 to max_code do begin
len := tree^[n].dl.Len;
if len=0 then continue;
{Now reverse the bits}
tree^[n].fc.Code := bi_reverse(next_code[len], len);
inc(next_code[len]);
{$ifdef DEBUG}
if (n>31) and (n<128) then begin
Tracecv(tree <> tree_ptr(@static_ltree),
(#13#10'n #'+IntToStr(n)+' '+char8(n)+' l '+IntToStr(len)+' c '+
IntToStr(tree^[n].fc.Code)+' ('+IntToStr(next_code[len]-1)+')'))
end
else begin
Tracecv(tree <> tree_ptr(@static_ltree),
(#13#10'n #'+IntToStr(n)+' l '+IntToStr(len)+' c '+
IntToStr(tree^[n].fc.Code)+' ('+IntToStr(next_code[len]-1)+')'));
end;
{$endif}
end;
end;
{---------------------------------------------------------------------------}
procedure init_block(var s: deflate_state);
{-Initialize a new block.}
var
n: int; {iterates over tree elements}
begin
{Initialize the trees.}
for n := 0 to L_CODES-1 do s.dyn_ltree[n].fc.Freq := 0;
for n := 0 to D_CODES-1 do s.dyn_dtree[n].fc.Freq := 0;
for n := 0 to BL_CODES-1 do s.bl_tree[n].fc.Freq := 0;
s.dyn_ltree[END_BLOCK].fc.Freq := 1;
s.static_len := Long(0);
s.opt_len := Long(0);
s.matches := 0;
s.last_lit := 0;
end;
{---------------------------------------------------------------------------}
procedure _tr_init(var s: deflate_state);
{-Initialize the tree data structures for a new zlib stream.}
begin
s.l_desc.dyn_tree := tree_ptr(@s.dyn_ltree);
s.l_desc.stat_desc := @static_l_desc;
s.d_desc.dyn_tree := tree_ptr(@s.dyn_dtree);
s.d_desc.stat_desc := @static_d_desc;
s.bl_desc.dyn_tree := tree_ptr(@s.bl_tree);
s.bl_desc.stat_desc := @static_bl_desc;
s.bi_buf := 0;
s.bi_valid := 0;
s.last_eob_len := 8; {enough lookahead for inflate}
{$ifdef DEBUG}
s.compressed_len := Long(0); {*we 113}
s.bits_sent := Long(0);
{$endif}
{Initialize the first block of the first file:}
init_block(s);
end;
{---------------------------------------------------------------------------}
procedure pqdownheap( var s: deflate_state;
var tree: tree_type; {the tree to restore}
k: int); {node to move down}
{-Restore the heap property by moving down the tree starting at node k,
exchanging a node with the smallest of its two sons if necessary, stopping
when the heap property is re-established (each father smaller than its
two sons).}
var
v: int;
j: int;
begin
v := s.heap[k];
j := k shl 1; {left son of k}
while j<=s.heap_len do begin
{Set j to the smallest of the two sons:}
if (j < s.heap_len) and
{smaller(tree, s.heap[j+1], s.heap[j], s.depth)}
((tree[s.heap[j+1]].fc.Freq < tree[s.heap[j]].fc.Freq) or
((tree[s.heap[j+1]].fc.Freq = tree[s.heap[j]].fc.Freq) and
(s.depth[s.heap[j+1]] <= s.depth[s.heap[j]]))) then
begin
inc(j);
end;
{Exit if v is smaller than both sons}
if {(smaller(tree, v, s.heap[j], s.depth))}
((tree[v].fc.Freq < tree[s.heap[j]].fc.Freq) or
((tree[v].fc.Freq = tree[s.heap[j]].fc.Freq) and
(s.depth[v] <= s.depth[s.heap[j]]))) then
begin
break;
end;
{Exchange v with the smallest son}
s.heap[k] := s.heap[j];
k := j;
{And continue down the tree, setting j to the left son of k}
j := j shl 1;
end;
s.heap[k] := v;
end;
{---------------------------------------------------------------------------}
procedure gen_bitlen(var s: deflate_state; var desc: tree_desc);
{-Compute the optimal bit lengths for a tree and update the total bit length
for the current block.
IN assertion: the fields freq and dad are set, heap[heap_max] and
above are the tree nodes sorted by increasing frequency.
OUT assertions: the field len is set to the optimal bit length, the
array bl_count contains the frequencies for each bit length.
The length opt_len is updated; static_len is also updated if stree is
not null.}
var
tree: tree_ptr;
max_code: int;
stree: tree_ptr; {const}
extra: pzIntfArray; {const}
base: int;
max_length: int;
h: int; {heap index}
n, m: int; {iterate over the tree elements}
bits: int; {bit length}
xbits: int; {extra bits}
f: ush; {frequency}
overflow: int; {number of elements with bit length too large}
begin
tree := desc.dyn_tree;
max_code := desc.max_code;
stree := desc.stat_desc^.static_tree;
extra := desc.stat_desc^.extra_bits;
base := desc.stat_desc^.extra_base;
max_length := desc.stat_desc^.max_length;
overflow := 0;
for bits := 0 to MAX_BITS do s.bl_count[bits] := 0;
{In a first pass, compute the optimal bit lengths (which may
overflow in the case of the bit length tree).}
tree^[s.heap[s.heap_max]].dl.Len := 0; {root of the heap}
for h := s.heap_max+1 to HEAP_SIZE-1 do begin
n := s.heap[h];
bits := tree^[tree^[n].dl.Dad].dl.Len + 1;
if bits>max_length then begin
bits := max_length;
inc(overflow);
end;
tree^[n].dl.Len := ush(bits);
{We overwrite tree[n].dl.Dad which is no longer needed}
if n>max_code then continue; {not a leaf node}
inc(s.bl_count[bits]);
xbits := 0;
if n>=base then xbits := extra^[n-base];
f := tree^[n].fc.Freq;
inc(s.opt_len, ulg(f) * (bits + xbits));
if (stree <> nil) then
inc(s.static_len, ulg(f) * (stree^[n].dl.Len + xbits));
end;
if overflow=0 then exit;
{$ifdef DEBUG}
Tracev(#13#10'bit length overflow');
{$endif}
{This happens for example on obj2 and pic of the Calgary corpus}
{Find the first bit length which could increase:}
repeat
bits := max_length-1;
while s.bl_count[bits]=0 do dec(bits);
dec(s.bl_count[bits]); {move one leaf down the tree}
inc(s.bl_count[bits+1], 2); {move one overflow item as its brother}
dec(s.bl_count[max_length]);
{The brother of the overflow item also moves one step up,
but this does not affect bl_count[max_length]}
dec(overflow, 2);
until overflow<=0;
{Now recompute all bit lengths, scanning in increasing frequency.
h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
lengths instead of fixing only the wrong ones. This idea is taken
from 'ar' written by Haruhiko Okumura.)}
h := HEAP_SIZE; {Delphi3: compiler warning w/o this}
for bits := max_length downto 1 do begin
n := s.bl_count[bits];
while n<>0 do begin
dec(h);
m := s.heap[h];
if m>max_code then continue;
if tree^[m].dl.Len <> unsigned(bits) then begin
{$ifdef DEBUG}
Trace('code '+IntToStr(m)+' bits '+IntToStr(tree^[m].dl.Len) +'.'+IntToStr(bits)+#13#10);
{$endif}
inc(s.opt_len, (long(bits) - long(tree^[m].dl.Len)) * long(tree^[m].fc.Freq));
tree^[m].dl.Len := ush(bits);
end;
dec(n);
end;
end;
end;
{---------------------------------------------------------------------------}
procedure build_tree(var s: deflate_state; var desc: tree_desc);
{-Construct one Huffman tree and assigns the code bit strings and lengths.
Update the total bit length for the current block.
IN assertion: the field freq is set for all tree elements.
OUT assertions: the fields len and code are set to the optimal bit length
and corresponding code. The length opt_len is updated; static_len is
also updated if stree is not null. The field max_code is set.}
const
SMALLEST = 1; {Index within the heap array of least frequent node in the Huffman tree}
var
tree: tree_ptr;
stree: tree_ptr; {const}
elems: int;
n, m: int; {iterate over heap elements}
max_code: int; {largest code with non zero frequency}
node: int; {new node being created}
begin
tree := desc.dyn_tree;
stree := desc.stat_desc^.static_tree;
elems := desc.stat_desc^.elems;
max_code := -1;
{Construct the initial heap, with least frequent element in
heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
heap[0] is not used.}
s.heap_len := 0;
s.heap_max := HEAP_SIZE;
for n := 0 to elems-1 do begin
if tree^[n].fc.Freq<>0 then begin
max_code := n;
inc(s.heap_len);
s.heap[s.heap_len] := n;
s.depth[n] := 0;
end
else tree^[n].dl.Len := 0;
end;
{The pkzip format requires that at least one distance code exists,
and that at least one bit should be sent even if there is only one
possible code. So to avoid special checks later on we force at least
two codes of non zero frequency.}
while s.heap_len<2 do begin
inc(s.heap_len);
if max_code<2 then begin
inc(max_code);
s.heap[s.heap_len] := max_code;
node := max_code;
end
else begin
s.heap[s.heap_len] := 0;
node := 0;
end;
tree^[node].fc.Freq := 1;
s.depth[node] := 0;
dec(s.opt_len);
if stree<>nil then dec(s.static_len, stree^[node].dl.Len);
{node is 0 or 1 so it does not have extra bits}
end;
desc.max_code := max_code;
{The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
establish sub-heaps of increasing lengths:}
for n := s.heap_len div 2 downto 1 do pqdownheap(s, tree^, n);
{Construct the Huffman tree by repeatedly combining the least two
frequent nodes.}
node := elems; {next internal node of the tree}
repeat
{pqremove(s, tree, n);} {n := node of least frequency}
n := s.heap[SMALLEST];
s.heap[SMALLEST] := s.heap[s.heap_len];
dec(s.heap_len);
pqdownheap(s, tree^, SMALLEST);
m := s.heap[SMALLEST]; {m := node of next least frequency}
dec(s.heap_max);
s.heap[s.heap_max] := n; {keep the nodes sorted by frequency}
dec(s.heap_max);
s.heap[s.heap_max] := m;
{Create a new node father of n and m}
tree^[node].fc.Freq := tree^[n].fc.Freq + tree^[m].fc.Freq;
{maximum}
if s.depth[n] >= s.depth[m] then s.depth[node] := uch(s.depth[n] + 1)
else s.depth[node] := uch(s.depth[m] + 1);
tree^[m].dl.Dad := ush(node);
tree^[n].dl.Dad := ush(node);
{and insert the new node in the heap}
s.heap[SMALLEST] := node;
inc(node);
pqdownheap(s, tree^, SMALLEST);
until s.heap_len<2;
dec(s.heap_max);
s.heap[s.heap_max] := s.heap[SMALLEST];
{At this point, the fields freq and dad are set. We can now
generate the bit lengths.}
gen_bitlen(s, desc);
{The field len is now set, we can generate the bit codes}
gen_codes (tree, max_code, s.bl_count);
end;
{---------------------------------------------------------------------------}
procedure scan_tree( var s: deflate_state;
var tree: array of ct_data; {the tree to be scanned}
max_code: int); {and its largest code of non zero frequency}
{-Scan a literal or distance tree to determine the frequencies of the codes
in the bit length tree.}
var
n: int; {iterates over all tree elements}
prevlen: int; {last emitted length}
curlen: int; {length of current code}
nextlen: int; {length of next code}
count: int; {repeat count of the current code}
max_count: int; {max repeat count}
min_count: int; {min repeat count}
begin
prevlen := -1;
nextlen := tree[0].dl.Len;
count := 0;
max_count := 7;
min_count := 4;
if nextlen=0 then begin
max_count := 138;
min_count := 3;
end;
tree[max_code+1].dl.Len := ush($ffff); {guard}
for n := 0 to max_code do begin
curlen := nextlen;
nextlen := tree[n+1].dl.Len;
inc(count);
if (count < max_count) and (curlen = nextlen) then continue
else if count<min_count then inc(s.bl_tree[curlen].fc.Freq, count)
else if curlen<>0 then begin
if curlen<>prevlen then inc(s.bl_tree[curlen].fc.Freq);
inc(s.bl_tree[REP_3_6].fc.Freq);
end
else if count<=10 then inc(s.bl_tree[REPZ_3_10].fc.Freq)
else inc(s.bl_tree[REPZ_11_138].fc.Freq);
count := 0;
prevlen := curlen;
if nextlen=0 then begin
max_count := 138;
min_count := 3;
end
else if curlen=nextlen then begin
max_count := 6;
min_count := 3;
end
else begin
max_count := 7;
min_count := 4;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure send_tree( var s: deflate_state;
var tree: array of ct_data; {the tree to be scanned}
max_code: int); {and its largest code of non zero frequency}
{-Send a literal or distance tree in compressed form, using the codes in bl_tree.}
var
n: int; {iterates over all tree elements}
prevlen: int; {last emitted length}
curlen: int; {length of current code}
nextlen: int; {length of next code}
count: int; {repeat count of the current code}
max_count: int; {max repeat count}
min_count: int; {min repeat count}
begin
prevlen := -1;
nextlen := tree[0].dl.Len;
count := 0;
max_count := 7;
min_count := 4;
{tree[max_code+1].dl.Len := -1;} {guard already set}
if nextlen=0 then begin
max_count := 138;
min_count := 3;
end;
for n := 0 to max_code do begin
curlen := nextlen;
nextlen := tree[n+1].dl.Len;
inc(count);
if (count < max_count) and (curlen = nextlen) then continue
else if count<min_count then begin
repeat
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(curlen));
{$endif}
send_bits(s, s.bl_tree[curlen].fc.Code, s.bl_tree[curlen].dl.Len);
dec(count);
until (count = 0);
end
else if curlen<>0 then begin
if curlen<>prevlen then begin
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(curlen));
{$endif}
send_bits(s, s.bl_tree[curlen].fc.Code, s.bl_tree[curlen].dl.Len);
dec(count);
end;
{$ifdef DEBUG}
Assert((count >= 3) and (count <= 6), ' 3_6?');
Tracevvv(#13#10'cd '+IntToStr(REP_3_6));
{$endif}
send_bits(s, s.bl_tree[REP_3_6].fc.Code, s.bl_tree[REP_3_6].dl.Len);
send_bits(s, count-3, 2);
end
else if count<=10 then begin
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(REPZ_3_10));
{$endif}
send_bits(s, s.bl_tree[REPZ_3_10].fc.Code, s.bl_tree[REPZ_3_10].dl.Len);
send_bits(s, count-3, 3);
end
else begin
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(REPZ_11_138));
{$endif}
send_bits(s, s.bl_tree[REPZ_11_138].fc.Code, s.bl_tree[REPZ_11_138].dl.Len);
send_bits(s, count-11, 7);
end;
count := 0;
prevlen := curlen;
if nextlen=0 then begin
max_count := 138;
min_count := 3;
end
else if curlen=nextlen then begin
max_count := 6;
min_count := 3;
end
else begin
max_count := 7;
min_count := 4;
end;
end;
end;
{---------------------------------------------------------------------------}
function build_bl_tree(var s: deflate_state): int;
{-Construct the Huffman tree for the bit lengths and return the index in
bl_order of the last bit length code to send.}
var
max_blindex: int; {index of last bit length code of non zero freq}
begin
{Determine the bit length frequencies for literal and distance trees}
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
{Build the bit length tree:}
build_tree(s, s.bl_desc);
{opt_len now includes the length of the tree representations, except
the lengths of the bit lengths codes and the 5+5+4 bits for the counts.}
{Determine the number of bit length codes to send. The pkzip format
requires that at least 4 bit length codes be sent. (appnote.txt says
3 but the actual value used is 4.)}
for max_blindex := BL_CODES-1 downto 3 do begin
if s.bl_tree[bl_order[max_blindex]].dl.Len <> 0 then break;
end;
{Update opt_len to include the bit length tree and counts}
inc(s.opt_len, 3*(max_blindex+1) + 5+5+4);
{$ifdef DEBUG}
Tracev(#13#10'dyn trees: dyn '+IntToStr(s.opt_len)+', stat '+IntToStr(s.static_len));
{$endif}
build_bl_tree := max_blindex;
end;
{---------------------------------------------------------------------------}
procedure send_all_trees(var s: deflate_state; lcodes, dcodes, blcodes: int);
{-Send the header for a block using dynamic Huffman trees: the counts, the
lengths of the bit length codes, the literal tree and the distance tree.
IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.}
var
rank: int; {index in bl_order}
begin
{$ifdef DEBUG}
Assert((lcodes >= 257) and (dcodes >= 1) and (blcodes >= 4), 'not enough codes');
Assert((lcodes <= L_CODES) and (dcodes <= D_CODES) and (blcodes <= BL_CODES), 'too many codes');
Tracev(#13#10'bl counts: ');
{$endif}
send_bits(s, lcodes-257, 5); {not +255 as stated in appnote.txt}
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); {not -3 as stated in appnote.txt}
for rank := 0 to blcodes-1 do begin
{$ifdef DEBUG}
Tracev(#13#10'bl code '+IntToStr(bl_order[rank]));
{$endif}
send_bits(s, s.bl_tree[bl_order[rank]].dl.Len, 3);
end;
{$ifdef DEBUG}
Tracev(#13#10'bl tree: sent '+IntToStr(s.bits_sent));
{$endif}
send_tree(s, s.dyn_ltree, lcodes-1); {literal tree}
{$ifdef DEBUG}
Tracev(#13#10'lit tree: sent '+IntToStr(s.bits_sent));
{$endif}
send_tree(s, s.dyn_dtree, dcodes-1); {distance tree}
{$ifdef DEBUG}
Tracev(#13#10'dist tree: sent '+IntToStr(s.bits_sent));
{$endif}
end;
{---------------------------------------------------------------------------}
procedure bi_windup(var s: deflate_state);
{-Flush the bit buffer and align the output on a byte boundary}
begin
if s.bi_valid>8 then begin
{put_short(s, s.bi_buf);}
s.pending_buf^[s.pending] := uch(s.bi_buf and $ff);
inc(s.pending);
s.pending_buf^[s.pending] := uch(ush(s.bi_buf) shr 8);;
inc(s.pending);
end
else if s.bi_valid>0 then begin
{put_byte(s, (byte)s^.bi_buf);}
s.pending_buf^[s.pending] := byte(s.bi_buf);
inc(s.pending);
end;
s.bi_buf := 0;
s.bi_valid := 0;
{$ifdef DEBUG}
s.bits_sent := (s.bits_sent+7) and (not 7);
{$endif}
end;
{---------------------------------------------------------------------------}
procedure copy_block( var s: deflate_state;
buf: pcharf; {the input data}
len: unsigned; {its length}
header: boolean); {true if block header must be written}
{-Copy a stored block, storing first the length and its one's complement if requested.}
begin
bi_windup(s); {align on byte boundary}
s.last_eob_len := 8; {enough lookahead for inflate}
if header then begin
{put_short(s, (ush)len);}
s.pending_buf^[s.pending] := uch(ush(len) and $ff);
inc(s.pending);
s.pending_buf^[s.pending] := uch(ush(len) shr 8);;
inc(s.pending);
{put_short(s, (ush)~len);}
s.pending_buf^[s.pending] := uch(ush(not len) and $ff);
inc(s.pending);
s.pending_buf^[s.pending] := uch(ush(not len) shr 8);;
inc(s.pending);
{$ifdef DEBUG}
inc(s.bits_sent, 2*16);
{$endif}
end;
{$ifdef DEBUG}
{*we 2006-12-09, fixed old paszlib bug: ulg(len) shl 3}
{replaces buggy expression ulg(len shl 3)}
inc(s.bits_sent, ulg(len) shl 3);
{$endif}
while len<>0 do begin
dec(len);
{put_byte(s, *buf++);}
s.pending_buf^[s.pending] := buf^;
inc(buf);
inc(s.pending);
end;
end;
{---------------------------------------------------------------------------}
procedure _tr_stored_block( var s: deflate_state;
buf: pcharf; {input block}
stored_len: ulg; {length of input block}
eof: boolean); {true if this is the last block for a file}
{-Send a stored block}
begin
send_bits(s, (STORED_BLOCK shl 1)+ord(eof), 3); {send block type}
{$ifdef DEBUG} {*we 113}
s.compressed_len := (s.compressed_len + 3 + 7) and ulg(not Long(7));
inc(s.compressed_len, (stored_len + 4) shl 3);
{$endif}
copy_block(s, buf, unsigned(stored_len), true); {with header}
end;
{---------------------------------------------------------------------------}
procedure bi_flush(var s: deflate_state);
{-Flush the bit buffer, keeping at most 7 bits in it.}
begin
if s.bi_valid=16 then begin
{put_short(s, s.bi_buf);}
s.pending_buf^[s.pending] := uch(s.bi_buf and $ff);
inc(s.pending);
s.pending_buf^[s.pending] := uch(ush(s.bi_buf) shr 8);;
inc(s.pending);
s.bi_buf := 0;
s.bi_valid := 0;
end
else if s.bi_valid >= 8 then begin
{put_byte(s, (byte)s^.bi_buf);}
s.pending_buf^[s.pending] := byte(s.bi_buf);
inc(s.pending);
s.bi_buf := s.bi_buf shr 8;
dec(s.bi_valid, 8);
end;
end;
{---------------------------------------------------------------------------}
procedure _tr_align(var s: deflate_state);
{-Send one empty static block to give enough lookahead for inflate.}
{This takes 10 bits, of which 7 may remain in the bit buffer.
The current inflate code requires 9 bits of lookahead. If the
last two codes for the previous block (real code plus EOB) were coded
on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
the last real code. In this case we send two empty static blocks instead
of one. (There are no problems if the previous block is stored or fixed.)
To simplify the code, we assume the worst case of last real code encoded
on one bit only.}
begin
send_bits(s, STATIC_TREES shl 1, 3);
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(END_BLOCK));
{$endif}
send_bits(s, static_ltree[END_BLOCK].fc.Code, static_ltree[END_BLOCK].dl.Len);
{$ifdef DEBUG} {*we 113}
inc(s.compressed_len, Long(10)); {3 for block type, 7 for EOB}
{$endif}
bi_flush(s);
{Of the 10 bits for the empty block, we have already sent
(10 - bi_valid) bits. The lookahead for the last real code (before
the EOB of the previous block) was thus at least one plus the length
of the EOB plus what we have just sent of the empty static block.}
if 1 + s.last_eob_len + 10 - s.bi_valid < 9 then begin
send_bits(s, STATIC_TREES shl 1, 3);
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(END_BLOCK));
{$endif}
send_bits(s, static_ltree[END_BLOCK].fc.Code, static_ltree[END_BLOCK].dl.Len);
{$ifdef DEBUG} {*we 113}
inc(s.compressed_len, Long(10));
{$endif}
bi_flush(s);
end;
s.last_eob_len := 7;
end;
{---------------------------------------------------------------------------}
procedure set_data_type(var s: deflate_state);
{-Set the data type to ASCII or BINARY, using a crude approximation:
binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
IN assertion: the fields freq of dyn_ltree are set and the total of all
frequencies does not exceed 64K (to fit in an int on 16 bit machines).}
var
n: int;
ascii_freq: unsigned;
bin_freq: unsigned;
begin
n := 0;
ascii_freq := 0;
bin_freq := 0;
while n<7 do begin
inc(bin_freq, s.dyn_ltree[n].fc.Freq);
inc(n);
end;
while n<128 do begin
inc(ascii_freq, s.dyn_ltree[n].fc.Freq);
inc(n);
end;
while n<LITERALS do begin
inc(bin_freq, s.dyn_ltree[n].fc.Freq);
inc(n);
end;
if bin_freq>(ascii_freq shr 2) then s.data_type := byte(Z_BINARY)
else s.data_type := byte(Z_ASCII);
end;
{---------------------------------------------------------------------------}
procedure compress_block( var s: deflate_state;
const ltree: array of ct_data; {literal tree} {*we var -> const}
const dtree: array of ct_data); {distance tree} {*we var -> const}
{-Send the block data compressed using the given Huffman trees}
var
dist: unsigned; {distance of matched string}
lc: int; {match length or unmatched char (if dist == 0)}
lx: unsigned; {running index in l_buf}
code: unsigned; {the code to send}
extra: int; {number of extra bits to send}
begin
lx := 0;
if s.last_lit<>0 then repeat
dist := s.d_buf^[lx];
lc := s.l_buf^[lx];
inc(lx);
if dist=0 then begin
{send a literal byte}
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(lc));
Tracecv((lc > 31) and (lc < 128),{$ifdef unicode}str255{$endif} (' '+char8(lc)+' '#13#10));
{$endif}
send_bits(s, ltree[lc].fc.Code, ltree[lc].dl.Len);
end
else begin
{Here, lc is the match length - MIN_MATCH}
code := _length_code[lc];
{send the length code}
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(code+LITERALS+1));
{$endif}
send_bits(s, ltree[code+LITERALS+1].fc.Code, ltree[code+LITERALS+1].dl.Len);
extra := extra_lbits[code];
if extra<>0 then begin
dec(lc, base_length[code]);
send_bits(s, lc, extra); {send the extra length bits}
end;
dec(dist); {dist is now the match distance - 1}
{code := d_code(dist);}
if dist<256 then code := _dist_code[dist]
else code := _dist_code[256+(dist shr 7)];
{$ifdef DEBUG}
Assert (code < D_CODES, 'bad d_code');
Tracevvv(#13#10'cd '+IntToStr(code));
{$endif}
{send the distance code}
send_bits(s, dtree[code].fc.Code, dtree[code].dl.Len);
extra := extra_dbits[code];
if extra<>0 then begin
dec(dist, base_dist[code]);
send_bits(s, dist, extra); {send the extra distance bits}
end;
end; {literal or match pair ?}
{Check that the overlay between pending_buf and d_buf+l_buf is ok:}
{$ifdef DEBUG}
Assert(s.pending < Long(s.lit_bufsize + 2*lx), 'pendingBuf overflow');
{$endif}
until lx >= s.last_lit;
{$ifdef DEBUG}
Tracevvv(#13#10'cd '+IntToStr(END_BLOCK));
{$endif}
send_bits(s, ltree[END_BLOCK].fc.Code, ltree[END_BLOCK].dl.Len);
s.last_eob_len := ltree[END_BLOCK].dl.Len;
end;
{---------------------------------------------------------------------------}
procedure _tr_flush_block( var s: deflate_state; {*we 113}
buf: pcharf; {input block, or NULL if too old}
stored_len: ulg; {length of input block}
eof: boolean); {true if this is the last block for a file}
{-Determine the best encoding for the current block: dynamic trees, static
trees or store, and output the encoded block to the zip file.} {*we 113}
var
opt_lenb, static_lenb: ulg; {opt_len and static_len in bytes}
max_blindex: int; {index of last bit length code of non zero freq}
begin
max_blindex := 0;
{Build the Huffman trees unless a stored block is forced}
if s.level>0 then begin
{Check if the file is ascii or binary}
if s.data_type=Z_UNKNOWN then set_data_type(s);
{Construct the literal and distance trees}
build_tree(s, s.l_desc);
{$ifdef DEBUG}
Tracev(#13#10'lit data: dyn '+IntToStr(s.opt_len)+', stat '+IntToStr(s.static_len));
{$endif}
build_tree(s, s.d_desc);
{$ifdef DEBUG}
Tracev(#13#10'dist data: dyn '+IntToStr(s.opt_len)+', stat '+IntToStr(s.static_len));
{$endif}
{At this point, opt_len and static_len are the total bit lengths of
the compressed block data, excluding the tree representations.}
{Build the bit length tree for the above two trees, and get the index
in bl_order of the last bit length code to send.}
max_blindex := build_bl_tree(s);
{Determine the best encoding. Compute first the block length in bytes}
opt_lenb := (s.opt_len+3+7) shr 3;
static_lenb := (s.static_len+3+7) shr 3;
{$ifdef DEBUG}
Tracev(#13#10'opt ' +IntToStr(opt_lenb)+'('+IntToStr(s.opt_len)+') '+
'stat ' +IntToStr(static_lenb)+'('+IntToStr(s.static_len)+') '+
'stored '+IntToStr(stored_len)+' lit '+IntToStr(s.last_lit));
{$endif}
if static_lenb<=opt_lenb then opt_lenb := static_lenb;
end
else begin
{$ifdef DEBUG}
Assert(buf <> pcharf(nil), 'lost buf');
{$endif}
static_lenb := stored_len + 5;
opt_lenb := static_lenb; {force a stored block}
end;
{*we 113: Parts deleted}
if (stored_len+4 <= opt_lenb) and (buf<>pcharf(Z_NULL)) then begin {*we 0202: 0 -> Z_NULL}
_tr_stored_block(s, buf, stored_len, eof);
end
else if static_lenb=opt_lenb then begin
send_bits(s, (STATIC_TREES shl 1)+ord(eof), 3);
compress_block(s, static_ltree, static_dtree);
{$ifdef DEBUG} {*we 113}
inc(s.compressed_len, 3 + s.static_len);
{$endif}
end
else begin
send_bits(s, (DYN_TREES shl 1)+ord(eof), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
{$ifdef DEBUG} {*we 113}
inc(s.compressed_len, 3 + s.opt_len);
{$endif}
end;
{$ifdef DEBUG}
Assert (s.compressed_len = s.bits_sent, 'bad compressed size');
(*
if s.compressed_len <> s.bits_sent then
Tracev(#13#10'Bad compressed size: compressed_len='+IntToStr(s.compressed_len)
+', bits_sent'+IntToStr(s.bits_sent));
*)
{$else}
{$endif}
init_block(s);
if eof then begin
bi_windup(s);
{$ifdef DEBUG} {*we 113}
inc(s.compressed_len, 7); {align on byte boundary}
{$endif}
end;
{$ifdef DEBUG}
Tracev(#13#10'comprlen '+IntToStr(s.compressed_len shr 3)+'('+IntToStr(s.compressed_len-7*ord(eof))+')');
{$endif}
{ _tr_flush_block := s.compressed_len shr 3;} {*we 113}
end;
{---------------------------------------------------------------------------}
function _tr_tally(var s: deflate_state; dist: unsigned; lc: unsigned): boolean;
{-Save the match info and tally the frequency counts. Return true if
the current block must be flushed, dist: distance of matched string}
var
code: ush;
{$ifdef TRUNCATE_BLOCK}
out_length: ulg;
in_length: ulg;
dcode: int;
{$endif}
begin
s.d_buf^[s.last_lit] := ush(dist);
s.l_buf^[s.last_lit] := uch(lc);
inc(s.last_lit);
if dist=0 then begin
{lc is the unmatched char}
inc(s.dyn_ltree[lc].fc.Freq);
end
else begin
inc(s.matches);
{Here, lc is the match length - MIN_MATCH}
dec(dist); {dist := match distance - 1}
{macro d_code(dist)}
if dist<256 then code := _dist_code[dist]
else code := _dist_code[256+(dist shr 7)];
{$ifdef DEBUG}
{macro MAX_DIST(s) <=> ((s)^.w_size-MIN_LOOKAHEAD)
In order to simplify the code, particularly on 16 bit machines, match
distances are limited to MAX_DIST instead of WSIZE.}
Assert((dist < ush(s.w_size-(MAX_MATCH+MIN_MATCH+1))) and
(ush(lc) <= ush(MAX_MATCH-MIN_MATCH)) and
(ush(code) < ush(D_CODES)), '_tr_tally: bad match');
{$endif}
inc(s.dyn_ltree[_length_code[lc]+LITERALS+1].fc.Freq);
{s.dyn_dtree[d_code(dist)].Freq++;}
inc(s.dyn_dtree[code].fc.Freq);
end;
{$ifdef TRUNCATE_BLOCK}
{Try to guess if it is profitable to stop the current block here}
if (s.last_lit and $1fff = 0) and (s.level > 2) then begin
{Compute an upper bound for the compressed length}
out_length := ulg(s.last_lit)*Long(8);
in_length := ulg(long(s.strstart) - s.block_start);
for dcode := 0 to D_CODES-1 do begin
inc(out_length, ulg(s.dyn_dtree[dcode].fc.Freq * (Long(5)+extra_dbits[dcode])));
end;
out_length := out_length shr 3;
{$ifdef DEBUG}
Tracev(#13#10'last_lit '+IntToStr(s.last_lit)+', in '+IntToStr(in_length)+
', out ~'+IntToStr(out_length)+'('+IntToStr(100 - long(100)*out_length div in_length)+'%)');
{$endif}
if (s.matches<s.last_lit div 2) and (out_length<in_length div 2) then begin
_tr_tally := true;
exit;
end;
end;
{$endif}
_tr_tally := (s.last_lit = s.lit_bufsize-1);
{We avoid equality with lit_bufsize because of wraparound at 64K on
16 bit machines and because stored blocks are restricted to 64K-1 bytes.}
end;
end.
|
unit u_indy_enumerators;
{$mode objfpc}
interface
uses Classes
, IdSocketHandle
;
type { TIdSocketHandleEnumerator }
TIdSocketHandleEnumerator = class
private
fHandles : TIdSocketHandles;
fCurrent : integer;
function GetCurrent: TIdSocketHandle;
public
constructor Create(const A: TIdSocketHandles);
property Current: TIdSocketHandle read GetCurrent;
function MoveNext: Boolean;
end;
operator Enumerator(const a : TIdSocketHandles) : TIdSocketHandleEnumerator;
implementation
{ TIdSocketHandleEnumerator }
operator Enumerator(const a : TIdSocketHandles) : TIdSocketHandleEnumerator;
begin
Result := TIdSocketHandleEnumerator.Create(a);
end;
function TIdSocketHandleEnumerator.GetCurrent: TIdSocketHandle;
begin
result := fHandles.Items[fCurrent];
end;
constructor TIdSocketHandleEnumerator.Create(const A: TIdSocketHandles);
begin
fHandles := a;
fCurrent := -1;
end;
function TIdSocketHandleEnumerator.MoveNext: Boolean;
begin
inc(fCurrent);
result := fCurrent<fHandles.Count;
end;
end.
|
type
TMercatorProjection = class
constructor TMercatorProjection.Create
XMercator: Double;
YMercator: Double;
paramHoriz: Double;
paramVert: Double;
canvas: TCanvas;
latMin: Double;
latMax: Double;
longMin: Double;
longMax: Double;
procedure DrawMercator();
procedure DrawPoint();
procedure DrawParalels();
procedure DrawMeridians();
end;
implementation
uses SysUtils;
constructor TMercatorProjection.Create();
begin
end;
procedure DrawMercator(XMercator, YMercator: Double; latMin, latMax, longMin,
longMax: Double; step: Integer; canvas: TCanvas);
var XMaxPaint, YMaxPaint, Lat, Long: Integer;
pointStart, pointStop: TPointF; Xmin, Ymin, Xmax, Ymax, horiz, vert,
paramMercatorHoriz, paramMercatorVert, _x, _y: Double; _temp: string;
rect: TRectF; rectText: TRectF; pointText : TPointF;
begin
// Clear Bitmap to get empty Canvas to draw
imgMercator.Bitmap.Clear(TAlphaColors.White);
if (latMin < latMax) and (longMin < longMax) then
begin
// Set borders for paint
YMaxPaint := Round(imgMercator.Height-40);
XMaxPaint := Round(imgMercator.Width-40);
// Find Min and Max Coords for visualization
GeographicToMercator(DegToRad(latMin), DegToRad(longMin), Xmin, Ymin);
GeographicToMercator(DegToRad(latMax), DegToRad(longMax), Xmax, Ymax);
horiz := Xmax - Xmin;
vert := Ymax - Ymin;
// Params of convertation to screen coords
paramMercatorVert := YMaxPaint/vert;
paramMercatorHoriz := XMaxPaint/horiz;
Lat := Round(latMin);
Long := Round(longMin);
with canvas do
begin
if Lat < -80 then
begin
Lat := -80;
end;
canvas.BeginScene();
canvas.Stroke.Color := TAlphaColors.Blue;
// Draw meridians
while Long <= longMax do
begin
GeographicToMercator(DegToRad(latMin), DegToRad(Long), _x, _y);
pointStart := TPointF.Create(Round((_x - Xmin)*paramMercatorHoriz) + 20,
Round((vert - (_y - Ymin))*paramMercatorVert) + 20);
GeographicTOMercator(DegToRad(latMax), DegToRad(Long), _x, _y);
pointStop := TPointF.Create(Round((_x - Xmin)*paramMercatorHoriz + 20),
Round((vert - (_y - Ymin))*paramMercatorVert) + 20);
canvas.DrawLine(pointStart, pointStop, 100);
// Draw numeration of Longitudes ... -20, 0, 20, 40, 60 ...
if (Long mod 20) = 0 then
begin
canvas.Fill.Color := TAlphaColors.Black;
pointText := TPointF.Create(pointStart.X - 10, pointStart.Y + 2);
rectText := TRectF.Create(pointText, 20, 18);
canvas.FillText(rectText, IntToStr(Abs(Long)), False, 100,
[TFillTextFlag.ftRightToLeft], TTextAlign.taCenter, TTextAlign.taCenter);
pointText := TPointF.Create(pointStop.X - 10, pointStop.Y - 16);
rectText := TRectF.Create(pointText, 20, 14);
canvas.FillText(rectText, IntToStr(Abs(Long)), False, 100,
[TFillTextFlag.ftRightToLeft], TTextAlign.taCenter, TTextAlign.taCenter);
end;
Long := Long + step;
end;
// Draw parallels
while Lat <= latMax do
begin
GeographicToMercator(DegToRad(Lat), DegToRad(longMin), _x, _y);
pointStart := TPointF.Create(Round((_x - Xmin)*paramMercatorHoriz) + 20,
Round((vert - (_y - Ymin))*paramMercatorVert) + 20);
GeographicTOMercator(DegToRad(Lat), DegToRad(longMax), _x, _y);
pointStop := TPointF.Create(Round((_x - Xmin)*paramMercatorHoriz + 20),
Round((vert - (_y - Ymin))*paramMercatorVert) + 20);
canvas.DrawLine(pointStart, pointStop, 100);
// Draw numeration of Latitudes ... 0, 20, 40 ...
if (Lat mod 20) = 0 then
begin
pointText := TPointF.Create(pointStart.X - 18, pointStart.Y -6);
rectText := TRectF.Create(pointText, 16, 12);
canvas.FillText(rectText, IntToStr(Abs(Lat)), False, 100,
[TFillTextFlag.ftRightToLeft], TTextAlign.taCenter, TTextAlign.taCenter);
pointText := TPointF.Create(pointStop.X + 2, pointStop.Y - 6);
rectText := TRectF.Create(pointText, 16, 12);
canvas.FillText(rectText, IntToStr(Abs(Lat)), False, 100,
[TFillTextFlag.ftRightToLeft], TTextAlign.taCenter, TTextAlign.taCenter);
end;
Lat := Lat + step;
end;
// Draw point that has input geographic coords
pointStart := TPointF.Create(Round((X - Xmin)*paramMercatorHoriz) + 20,
Round((vert - (Y - Ymin))*paramMercatorVert) + 20);
rect := TRectF.Create(pointStart.X - 3, pointStart.Y - 3,
pointStart.X + 3, pointStart.Y + 3);
Canvas.Fill.Color := TAlphaColors.Red;
canvas.FillEllipse(rect, 100);
Canvas.Fill.Color := TAlphaColors.Black;
canvas.EndScene();
end;
end;
imgMercator.Repaint();
end; |
unit InitialRemains;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Mask, DBCtrlsEh, ExtCtrls, DBLookupEh, Grids, DBGridEh,
DB, RpCon, RpConDS, RpBase, RpSystem, RpDefine, RpRave, ComCtrls, ToolWin;
type
TInitialRemainsForm = class(TForm)
Panel2: TPanel;
DBGridEh1: TDBGridEh;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
InsertButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
Panel1: TPanel;
Label2: TLabel;
DBDateTimeEditEh1: TDBDateTimeEditEh;
Panel3: TPanel;
OKButton: TButton;
CancelButton: TButton;
Label1: TLabel;
DBEditEh1: TDBEditEh;
DBEditEh3: TDBEditEh;
Label3: TLabel;
Label3a: TLabel;
procedure EnabledButtons;
procedure HomeOrderPost;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure OKButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure InsertButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure DBEditEh3EditButtons0Click(Sender: TObject;
var Handled: Boolean);
procedure DBEditEh3KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridEh1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridEh1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
InitialRemainsForm: TInitialRemainsForm;
implementation
uses StoreDM, HomeStructure, HomeTypeSelect, DivisionSelect;
{$R *.dfm}
procedure TInitialRemainsForm.EnabledButtons;
begin
// Если записей нету, то Деактивируем кнопки "Редактировать" и "Удалить",
// а если есть, Активируем.
if StoreDataModule.HomeStructureDataSet.IsEmpty then
begin
EditButton.Enabled := False;
EditButton.ShowHint := False;
DeleteButton.Enabled := False;
DeleteButton.ShowHint := False;
end
else
begin
EditButton.Enabled := True;
EditButton.ShowHint := True;
DeleteButton.Enabled := True;
DeleteButton.ShowHint := True;
end;
end;
procedure TInitialRemainsForm.HomeOrderPost;
begin
with StoreDataModule do
begin
if HomeOrderDataSet.Modified then
try
HomeOrderDataSet.Post;
HomeOrderDataSet.Close;
HomeOrderDataSet.Open;
HomeOrderDataSet.Last;
except
Application.MessageBox('Недопустимые значения данных'+#10#13+
'(TInitialRemainsForm.HomeOrderPost)',
'Ошибка ввода', mb_IconStop);
Abort;
end
else
HomeOrderDataSet.Cancel;
end;
end;
procedure TInitialRemainsForm.FormCreate(Sender: TObject);
begin
// OKButton.Visible := False;
// CancelButton.Caption := 'Закрыть';
StoreDataModule.HomeOrderDataSet.Open;
StoreDataModule.HomeOrderDataSet.Locate('ProperID', 5, []);
// Если не находим "Документ", то создаем и вводим Данные в заголовок
if StoreDataModule.HomeOrderDataSet['ProperID'] <> 5 then
begin
StoreDataModule.HomeOrderDataSet.Append;
StoreDataModule.HomeOrderDataSet['FirmID'] := MainFirm;
StoreDataModule.HomeOrderDataSet['Date'] := Now;
StoreDataModule.HomeOrderDataSet['CustomerID'] := MainFirm;
StoreDataModule.HomeOrderDataSet['PriceID'] := 1;//"Цена Закупа"
StoreDataModule.HomeOrderDataSet['ProperID'] := 5;//"Ввод остатков"
StoreDataModule.HomeOrderDataSet['InDivisionID'] := MainDivision;
StoreDataModule.HomeOrderDataSet.Post;
end;
// Открываем "Строки Документа"
StoreDataModule.HomeStructureDataSet.Open;
StoreDataModule.HomeStructureDataSet.Last;
EnabledButtons;
// Запоминаем положение Курсора, чтобы вернуться на прежнее место
CurOrderID := StoreDataModule.HomeOrderDataSet['OrderID'];
StoreDataModule.TypePriceDataSet.Open;
Caption := 'Ввод начальных остатков';
StoreDataModule.DivisionSelectQuery.Open;
if StoreDataModule.HomeOrderDataSet['InDivisionID'] <> Null then
begin
StoreDataModule.DivisionSelectQuery.Locate('DivisionID', StoreDataModule.HomeOrderDataSet['InDivisionID'], []);
Label3a.Caption := StoreDataModule.DivisionSelectQuery.FieldByName('DivisionName').AsString;
end;
StoreDataModule.DivisionSelectQuery.Close;
end;
procedure TInitialRemainsForm.FormShow(Sender: TObject);
begin
{ if StoreDataModule.HomeOrderDataSet.State = dsInsert then
begin
OKButton.Visible := True;
CancelButton.Caption := 'Cancel';
end;{}
end;
procedure TInitialRemainsForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
with StoreDataModule do
try
try
if ModalResult = mrOk then
begin
if HomeOrderDataSet.Modified then
HomeOrderDataSet.Post;
HomeTransaction.Commit;
end
else
HomeTransaction.Rollback;
except
Application.MessageBox('Недопустимые значения данных'+#10#13+'(HomeOrderDataSet)',
'Ошибка ввода', mb_IconStop);
Abort;
end; {try except}
finally
if TypePriceDataSet.Active then
TypePriceDataSet.Close;
end; {try finally}
Release;
end;
procedure TInitialRemainsForm.OKButtonClick(Sender: TObject);
begin
ModalResult := mrOk;
end;
procedure TInitialRemainsForm.CancelButtonClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TInitialRemainsForm.InsertButtonClick(Sender: TObject);
begin
StoreDataModule.HomeStructureDataSet.Append;
StoreDataModule.HomeStructureDataSet['OrderID'] := StoreDataModule.HomeOrderDataSet['OrderID'];
StoreDataModule.HomeStructureDataSet['Type'] := -1;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end;
procedure TInitialRemainsForm.EditButtonClick(Sender: TObject);
begin
StoreDataModule.HomeStructureDataSet.Edit;
HomeStructureForm := THomeStructureForm.Create(Self);
HomeStructureForm.ShowModal;
end;
procedure TInitialRemainsForm.DeleteButtonClick(Sender: TObject);
var
HomeStrucStr : String;
begin
HomeStrucStr := StoreDataModule.HomeStructureDataSet.FieldByName('ProductFullName').AsString;
if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' +
HomeStrucStr + '"?'),
'Удаление записи',
mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then
try
StoreDataModule.HomeStructureDataSet.Delete;
except
Application.MessageBox(PChar('Запись "' + HomeStrucStr + '" удалять нельзя.'),
'Ошибка удаления', mb_IconStop);
end;
end;
procedure TInitialRemainsForm.DBEditEh3EditButtons0Click(Sender: TObject;
var Handled: Boolean);
begin
with StoreDataModule do
begin
if HomeOrderDataSet.State = dsBrowse then
HomeOrderDataSet.Edit;
DivisionSelectForm := TDivisionSelectForm.Create(Self);
DivisionSelectForm.ShowModal;
if DivisionSelectForm.ModalResult = mrOk then
begin
HomeOrderDataSet['InDivisionID'] := CurDivisionID;
HomeOrderPost;
Label3a.Caption := CurDivisionName;
end
else
HomeOrderDataSet.Cancel;
end;
DBGridEh1.SetFocus;
end;
procedure TInitialRemainsForm.DBEditEh3KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
var
h: Boolean;
begin
if Key = VK_F3 then
DBEditEh3EditButtons0Click(Self, h);
end;
procedure TInitialRemainsForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = VK_RETURN then
OKButton.Click;
end;
procedure TInitialRemainsForm.DBGridEh1KeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
case Key of
VK_F2 : InsertButton.Click;
VK_F3 : EditButton.Click;
VK_F8 : DeleteButton.Click;
end;
end;
procedure TInitialRemainsForm.DBGridEh1DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumnEh;
State: TGridDrawState);
var
ItemNo: String;
begin
//Проставляем номера по порядку в строках Документа
with DBGridEh1.Canvas do
begin
if StoreDataModule.HomeStructureDataSet.RecNo <> 0 then
ItemNo := IntToStr(StoreDataModule.HomeStructureDataSet.RecNo)
else
ItemNo := '';
if Column.Index = 0 then
begin
FillRect(Rect);
TextOut(Rect.Right - 3 - TextWidth(ItemNo), Rect.Top, ItemNo);
end
else
DBGridEh1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
end.
|
unit SFU_boot;
interface
type
tSFUboot_CommandSend = function(code:byte; cmd_body:pointer = nil; size:word = 0):cardinal of object;
tSFUboot_EventLog = procedure(sender:tobject; msg:string) of object;
tSFUboot_tx_free_func = function:integer of object;
tSFUboot_tx_reset_func = procedure of object;
tSFUboot_Event = procedure of object;
tSFUboot = class
private
CommandSend : tSFUboot_CommandSend;
firmware_buf : array[0.. $400000 - 1] of byte;
firmware_size : cardinal;
firmware_crc : cardinal;
firmware_addr : cardinal;
firmware_start : cardinal;
firmware_end_addr : cardinal;
firmware_last_block : cardinal;
info_done : boolean;
load_done : boolean;
erase_done : boolean;
write_done : boolean;
start_done : boolean;
write_restart : boolean;
send_timeout : cardinal;
rewrite_countout : cardinal;
info_chip_id : array[0..11] of byte;
info_dev_type : word;
info_dev_rev : word;
info_flash_size : cardinal;
info_boot_ver : word;
info_addr_from : cardinal;
info_addr_run : cardinal;
info_rx_size : cardinal;
start_time : cardinal;
last_sended_addr : cardinal;
last_writed_addr : cardinal;
last_corrected_addr : cardinal;
write_block_packet_size : cardinal;
prewrite_bytes_free : cardinal;
prewrite_bytes_writed : cardinal;
procedure log(msg:string);
procedure log_block_hex(msg:string; block:pbyte; count:integer);
procedure log_block_ascii(msg:string; block:pbyte; count:integer);
procedure recive_info(body:pbyte; count:word);
procedure recive_erase_done(body:pbyte; count:word);
procedure recive_erase_page(body:pbyte; count:word);
procedure recive_write(body:pbyte; count:word);
procedure recive_start(body:pbyte; count:word);
procedure recive_hw_reset(msg:string);
procedure error_stop(msg:string);
procedure send_info;
procedure send_erase;
procedure send_start;
function send_write:cardinal;
procedure send_write_restart;
procedure send_write_multi(count:integer);
procedure firmware_load;
procedure RESET;
public
onLog : tSFUboot_EventLog;
onERROR: tSFUboot_Event;
onDone: tSFUboot_Event;
tx_free_func : tSFUboot_tx_free_func;
tx_reset_func : tSFUboot_tx_reset_func;
firmware_fname : string;
progress_max : cardinal;
progress_pos : cardinal;
task_done : boolean;
task_error : boolean;
task_info : string[255];
opt_fast_erase : boolean;
opt_prewrite : boolean;
constructor create(send: tSFUboot_CommandSend);
procedure recive_command(code:byte; body:pbyte; count:word);
procedure next_send;
procedure start;
procedure abort;
end;
implementation
uses
SysUtils, windows, math,
crcunit,
SFU_other;
const
SFU_CMD_INFO = $97;
SFU_CMD_ERASE = $C5;
SFU_CMD_PAGE = $B3;
SFU_CMD_WRITE = $38;
SFU_CMD_START = $26;
SFU_CMD_TIMEOUT = $AA;
SFU_CMD_WRERROR = $55;
SFU_CMD_HWRESET = $11;
const
WRITE_BLOCK_SIZE = 2048;
const
TIMEOUT_ERASE = 2000;
TIMEOUT_WRITE = 300;
TIMEOUT_RESTART = 500;
TIMEOUT_DEFAULT = 200;
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////
constructor tSFUboot.create(send: tSFUboot_CommandSend);
begin
CommandSend := send;
RESET();
end;
////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUboot.firmware_load;
var
readed : cardinal;
begin
firmware_size := 0;
FillChar(firmware_buf[0], sizeof(firmware_buf), $FF);
readed := 0;
if not stm32_load_file(firmware_fname, @firmware_buf[0], sizeof(firmware_buf), @readed) then
begin
error_stop('ERROR: firmware_load(' + firmware_fname + '), not loaded');
exit;
end;
if readed = 0 then
begin
error_stop('ERROR: firmware_load(' + firmware_fname + '), file empty');
exit;
end;
if readed > info_flash_size then
begin
error_stop('ERROR: firmware_load(' + firmware_fname + '), too big');
exit;
end;
readed := (readed + 3) and $FFFFFFFC;
firmware_size := readed;
firmware_crc := crc_stm32(pcardinal(@firmware_buf[0]), firmware_size div 4);
firmware_end_addr := info_addr_from + firmware_size;
firmware_last_block := ((firmware_end_addr - 1) div WRITE_BLOCK_SIZE) * WRITE_BLOCK_SIZE;
log('firmware_load(''' + firmware_fname + ''') OK');
log('firmware_size: ' + IntToStr(firmware_size));
log('firmware_from: 0x' + IntToHex(firmware_start, 8));
log('firmware_to : 0x' + IntToHex(firmware_end_addr, 8));
log('firmware_last: 0x' + IntToHex(firmware_last_block, 8));
log('firmware_crc : 0x' + IntToHex(firmware_crc, 8));
log(' ');
load_done := true;
send_timeout := GetTickCount;
end;
////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUboot.log(msg:string);
begin
if @onlog<>nil then
onLog(self, msg);
task_info := msg;
end;
procedure tSFUboot.log_block_hex(msg:string; block:pbyte; count:integer);
var
str : string;
begin
if @onlog = nil then exit;
str := msg;
while count > 0 do
begin
str := str + inttohex(block^, 2) + ' ';
inc(block);
dec(count);
end;
onLog(self, str);
end;
procedure tSFUboot.log_block_ascii(msg:string; block:pbyte; count:integer);
var
str : string;
begin
if @onlog = nil then exit;
str := msg;
while count > 0 do
begin
if block^ in [9, 32..127] then
str := str + ansichar(block^)
else
str := str + '<' + inttohex(block^, 2) + '>';
inc(block);
dec(count);
end;
onLog(self, str);
end;
//////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUboot.recive_start(body:pbyte; count:word);
var
crc_from : cardinal;
crc_size : cardinal;
crc_value : cardinal;
begin
if count <> 12 then
begin
error_stop('ERROR: recive_start: count <> 12');
exit;
end;
crc_from := body_get_cardinal(body, count);
crc_size := body_get_cardinal(body, count);
crc_value := body_get_cardinal(body, count);
log('Command: Check and START');
log('crc_from : 0x' + inttohex(crc_from, 8));
log('crc_to : 0x' + inttohex(crc_from + crc_size, 8));
log('crc_value : 0x' + inttohex(crc_value, 8));
if crc_value = firmware_crc then
log('CRC OK')
else
begin
error_stop('ERROR: Firmware CRC wrong');
exit;
end;
log(' ');
start_done := true;
send_timeout := GetTickCount;
end;
procedure tSFUboot.recive_info(body:pbyte; count:word);
begin
if count <> 32 then
begin
error_stop('ERROR: recive_info: count <> 32');
exit;
end;
body_get_block(body, count, @info_chip_id[0], sizeof(info_chip_id));
info_dev_type := body_get_word(body, count);
info_dev_rev := body_get_word(body, count);
info_flash_size := body_get_word(body, count);
info_boot_ver := body_get_word(body, count);
info_flash_size := info_flash_size * 1024;
info_rx_size := body_get_cardinal(body, count);
info_addr_from := body_get_cardinal(body, count);
info_addr_run := body_get_cardinal(body, count);
log('Command: INFO');
log_block_hex('ChipID: ', @info_chip_id[0], sizeof(info_chip_id));
log_block_ascii('ChipID: ', @info_chip_id[0], sizeof(info_chip_id));
log('Dev type : 0x' + inttohex(info_dev_type, 4));
log('Dev rev : 0x' + inttohex(info_dev_rev, 4));
log('FlashSize : ' + inttostr(info_flash_size));
log('Boot ver : 0x' + inttohex(info_boot_ver, 4));
log('RX fifo : 0x' + inttohex(info_rx_size, 8));
log('Addr from : 0x' + inttohex(info_addr_from, 8));
log('Addr run : 0x' + inttohex(info_addr_run, 8));
log(' ');
firmware_start := info_addr_from;
firmware_addr := info_addr_from;
prewrite_bytes_free := info_rx_size - WRITE_BLOCK_SIZE*2;
prewrite_bytes_writed := 0;
info_done := true;
send_timeout := GetTickCount;
end;
procedure tSFUboot.recive_erase_page(body:pbyte; count:word);
var
log_str : string;
sended_count : integer;
writed : cardinal;
begin
log_str := 'Erase sector #' + inttostr(body_get_cardinal(body, count) + 1);
if opt_prewrite then
if @tx_free_func <> nil then
begin
sended_count := 0;
while (tx_free_func() >= write_block_packet_size) and
(sended_count < 64) and
(prewrite_bytes_free >= write_block_packet_size) and
(prewrite_bytes_writed < firmware_size) do
begin
writed := send_write();
inc(prewrite_bytes_writed, writed);
inc(sended_count);
dec(prewrite_bytes_free, write_block_packet_size);
end;
if sended_count > 0 then
log_str := log_str + '. Prewrite packets: ' + inttostr(sended_count) + ', free : ' + inttostr(prewrite_bytes_free);
end;
log(log_str);
send_timeout := GetTickCount + TIMEOUT_ERASE;
end;
procedure tSFUboot.recive_erase_done(body:pbyte; count:word);
begin
if (count <> 4) then
begin
error_stop('ERROR: Erase command');
exit;
end
else
log('Erase DONE');
log(' ');
if opt_prewrite then
begin
if prewrite_bytes_writed < firmware_size then
send_write_multi((firmware_size - prewrite_bytes_writed) div WRITE_BLOCK_SIZE);
end
else
send_write_multi(64);
erase_done := true;
send_timeout := GetTickCount + TIMEOUT_WRITE;
send_timeout := send_timeout + 100; //for 115200 bod: after erase additional start delay 100ms
send_timeout := send_timeout + 2000; //for STM32H7 first write after erase delay ~1000ms
end;
procedure tSFUboot.recive_write(body:pbyte; count:word);
var
addr : cardinal;
rxed : cardinal;
begin
if count <> 8 then
begin
log('ERROR: write command recive count <> 8');
exit;
end;
addr := body_get_cardinal(body, count);
rxed := body_get_cardinal(body, count);
log('WR: 0x'+inttohex(addr, 8) + #9 + inttostr(rxed));
if not write_done then
begin
if addr >= firmware_end_addr then
begin
if @tx_reset_func <> nil then
tx_reset_func();
write_done := true;
progress_max := firmware_size;
progress_pos := progress_max;
log('Write Done');
log(' ');
send_timeout := GetTickCount;
exit;
end;
if write_restart then
begin
write_restart := false;
firmware_addr := addr;
send_write_multi(64);
end
else
begin
if (last_writed_addr = addr) and (last_corrected_addr < addr) then
begin
firmware_addr := addr;
last_corrected_addr := addr;
log('WR address corrected to 0x' + inttohex(last_corrected_addr, 8));
if @tx_reset_func <> nil then
begin
tx_reset_func();
send_write_multi(4);
end;
end;
if last_sended_addr < firmware_last_block then
send_write;
end;
end;
progress_max := firmware_size;
progress_pos := addr - firmware_start;
if last_writed_addr < addr then
rewrite_countout := 0;
last_writed_addr := addr;
send_timeout := GetTickCount + TIMEOUT_WRITE;
end;
procedure tSFUboot.error_stop(msg:string);
begin
RESET();
task_error := true;
log(msg);
if @onError <> nil then
onError();
end;
procedure tSFUboot.recive_hw_reset(msg:string);
begin
if erase_done then
error_stop(msg)
else
log(msg);
end;
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUboot.recive_command(code:byte; body:pbyte; count:word);
begin
if code = SFU_CMD_INFO then recive_info(body, count) else
if code = SFU_CMD_ERASE then recive_erase_done(body, count) else
if code = SFU_CMD_PAGE then recive_erase_page(body, count) else
if code = SFU_CMD_WRITE then recive_write(body, count) else
if code = SFU_CMD_START then recive_start(body, count) else
if code = SFU_CMD_TIMEOUT then error_stop('ERROR command: TIMEOUT') else
if code = SFU_CMD_HWRESET then recive_hw_reset('ERROR command: H/W RESET') else
if code = SFU_CMD_WRERROR then error_stop('ERROR command: Flash write') else
log_block_hex('Error unknow command (' + inttohex(code, 2) + ')', body, count);
end;
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUboot.send_info;
begin
log('Send command: INFO');
CommandSend(SFU_CMD_INFO);
end;
procedure tSFUboot.send_erase;
var
info : array[0..3] of byte;
begin
if opt_fast_erase then
begin
info[0] := (firmware_size shr 0) and $FF;
info[1] := (firmware_size shr 8) and $FF;
info[2] := (firmware_size shr 16) and $FF;
info[3] := (firmware_size shr 24) and $FF;
end
else
begin
info[0] := $FF;
info[1] := $FF;
info[2] := $FF;
info[3] := $FF;
end;
log('Send command: Erase');
CommandSend(SFU_CMD_ERASE, @info, sizeof(info));
send_timeout := GetTickCount + TIMEOUT_ERASE;
end;
function tSFUboot.send_write;
var
body : array[0 .. WRITE_BLOCK_SIZE + 4 - 1] of byte;
count : integer;
pos : integer;
begin
result := 0;
if @tx_free_func <> nil then
if tx_free_func() < write_block_packet_size then
exit;
body[0] := (firmware_addr shr 0) and $FF;
body[1] := (firmware_addr shr 8) and $FF;
body[2] := (firmware_addr shr 16) and $FF;
body[3] := (firmware_addr shr 24) and $FF;
pos := firmware_addr - firmware_start;
if (pos < 0) or (pos > (Length(firmware_buf) - WRITE_BLOCK_SIZE)) then
begin
error_stop('ERROR: tSFUboot.send_write: pos = ' + inttostr(pos));
exit;
end;
if WRITE_BLOCK_SIZE > (firmware_size - pos) then
count := firmware_size - pos
else
count := WRITE_BLOCK_SIZE;
//log('Send: 0x' + inttohex(firmware_addr, 8) + ' ' + inttostr(count)); //log('');
if count <= 0 then
exit;
move(firmware_buf[pos], body[4], count);
result := CommandSend(SFU_CMD_WRITE, @body[0], count + 4);
write_block_packet_size := result;
last_sended_addr := firmware_addr;
if (firmware_addr - firmware_start) + count < firmware_size then
firmware_addr := firmware_addr + count;
end;
procedure tSFUboot.send_write_multi(count:integer);
var
pos : integer;
begin
for pos := 0 to count-1 do
begin
if @tx_free_func <> nil then
if tx_free_func() < write_block_packet_size then
break;
send_write;
end;
end;
procedure tSFUboot.send_write_restart;
begin
inc(rewrite_countout);
if rewrite_countout > 10 then
begin
error_stop('ERROR: Write restart timeout');
exit;
end;
log('Send command: Write(RESART)');
write_restart := true;
CommandSend(SFU_CMD_WRITE);
send_timeout := GetTickCount + TIMEOUT_RESTART;
end;
procedure tSFUboot.send_start;
begin
log('Send command: Check and START');
CommandSend(SFU_CMD_START, @firmware_crc, sizeof(firmware_crc));
end;
////////////////////////////////////////////////////////////////////////////////////////////
procedure tSFUboot.RESET();
begin
if start_time <> 0 then
begin
if @onLog <> nil then
onLog(self, 'Total time : ' + inttostr(GetTickCount - start_time));
start_time := 0;
end;
task_done := true;
task_error := false;
info_done := false;
load_done := false;
erase_done := false;
write_done := false;
start_done := false;
write_restart := false;
progress_pos := 0;
progress_max := 0;
firmware_size := 0;
firmware_addr := 0;
firmware_start := 0;
send_timeout := 0;
rewrite_countout := 0;
last_writed_addr := 0;
last_sended_addr := 0;
last_corrected_addr := 0;
FillChar(firmware_buf[0], sizeof(firmware_buf), $FF);
FillChar(info_chip_id, sizeof(info_chip_id), 0);
info_dev_type := 0;
info_dev_rev := 0;
info_flash_size := 0;
info_boot_ver := 0;
info_addr_from := 0;
info_addr_run := 0;
write_block_packet_size := WRITE_BLOCK_SIZE * 2;
prewrite_bytes_free := 0;
prewrite_bytes_writed := 0;
end;
procedure tSFUboot.start;
begin
if firmware_fname = '' then
begin
error_stop('ERROR: firmware_fname =''''');
exit;
end;
if not FileExists(firmware_fname) then
begin
error_stop('ERROR: firmware not exist: ' + firmware_fname);
exit;
end;
log(' ');
log('New TASK');
log('Firmware: ' + firmware_fname);
log('opt_fast_erase: ' + BoolToStr(opt_fast_erase, true));
log('opt_prewrite: ' + BoolToStr(opt_prewrite, true));
log('WRITE_BLOCK_SIZE: '+IntToStr(WRITE_BLOCK_SIZE));
log('tx_free_func: 0x' + inttohex(cardinal(TMethod(tx_free_func).code), 8));
log('tx_reset_func: 0x' + inttohex(cardinal(TMethod(tx_reset_func).code), 8));
log(' ');
self.RESET();
start_time := GetTickCount;
task_info := '';
task_done := false;
task_error := false;
end;
procedure tSFUboot.abort;
begin
log(' ');
error_stop('Task ABORTED ['+datetostr(date)+' '+TimeToStr(time)+']');
end;
procedure tSFUboot.next_send;
begin
if task_done then exit;
if GetTickCount < send_timeout then exit;
send_timeout := GetTickCount + TIMEOUT_DEFAULT;
if info_done = false then send_info() else
if load_done = false then firmware_load() else
if erase_done = false then send_erase() else
if write_done = false then send_write_restart() else
if start_done = false then send_start() else
begin
RESET;
progress_max := 1;
progress_pos := 1;
log('Task DONE ['+datetostr(date)+' '+TimeToStr(time)+']');
task_done := true;
if @onDone <> nil then
onDone();
end;
end;
end.
|
// Copyright 2021 Darian Miller, Licensed under Apache-2.0
// SPDX-License-Identifier: Apache-2.0
// More info: www.radprogrammer.com
unit radRTL.BitUtils;
interface
// given decimal 49 ('00110001') if you want the last 2 bits '01' then ExtractLastBits(49, 2) = 1
function ExtractLastBits(const pValue:Integer; const pBitsToExtract:Integer):Integer;
implementation
function ExtractLastBits(const pValue:Integer; const pBitsToExtract:Integer):Integer;
var
vMask:Int64; //Int64 to overcome "1 shl 31"
begin
if pBitsToExtract > 0 then
begin
vMask := (Int64(1) shl pBitsToExtract) - 1;
Result := pValue and (vMask and $FFFFFFFF);
end
else
begin
Result := 0;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi LiveBindings Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit System.Bindings.Factories;
interface
uses
System.SysUtils, System.Generics.Collections, System.Rtti, System.RTLConsts, System.Bindings.Consts,
System.Bindings.NotifierContracts, System.Bindings.Expression, System.Bindings.Manager, System.Bindings.CustomScope;
type
{ TBindingExpressionFactory
Creates instances of binding expressions that are used the binding manager.
Do not use the factory to create standalone instances. Use a manager instead.
Creating instances using the factory will make the manager unaware of the
existance of the expression and therefore the expression will not be
recompiled and reevaluated in case a script property changes. }
TBindingExpressionFactory = class(TObject)
public
class function CreateExpression(Manager: TBindingManager = nil): TBindingExpression;
end;
{ TBindingManagerFactory
Creates instances of binding managers that are used to handle binding expressions. }
TBindingManagerFactory = class(TObject)
private
class var
FAppManager: TBindingManager;
// creates an instance of the default implementation for TBindingManager
class function CreateManagerInstance(Owner: TBindingManager): TBindingManager;
public
class constructor Create;
class destructor Destroy;
// creates a new manager that is owner by the Owner manager;
// if Owner is Nil, the new manager will be owned by the
// application wide manager
class function CreateManager(Owner: TBindingManager = nil): TBindingManager;
// the instance of the application wide binding manager
class property AppManager: TBindingManager read FAppManager;
end;
// Exception for errors that are raised when managing custom scopes.
EBindingScopeFactoryError = class(Exception);
/// <summary>Instantiates custom scope objects based on the registred associations
/// between a scope class and an object class for which the scope is created.</summary>
TBindingScopeFactory = class(TObject)
public
type
TScopeTuple = TPair<TClass, TScopeClass>;
private
type
TScopeTuples = TDictionary<TClass, TScopeClass>;
class var
FScopeTuples: TScopeTuples;
class function GetScopeTuples: TScopeTuples; static;
class function GetScopeClassCount: Integer; static; inline;
class function GetScopeClasses(const ObjectType: TClass): TScopeClass; static; inline;
public
class destructor Destroy;
/// <summary>Registers the specified scope class for the specified object class.</summary>
/// <param name="ObjectType">Class reference for the object to which the scope type is attached.</param>
/// <param name="ScopeClass">Scope class reference registered for the given object type.</param>
class procedure RegisterScope(ObjectType: TClass; ScopeClass: TScopeClass);
/// <summary>Unregisters the scope class associated with the given object type.</summary>
/// <param name="ObjectType">Class reference for the object to which the scope type is associated.</param>
class procedure UnregisterObjectType(ObjectType: TClass);
// Unregisters all the associations that have the given scope class.
class procedure UnregisterScope(ScopeClass: TScopeClass);
/// <summary>Unregisters all the scopes in the factory.</summary>
class procedure UnregisterScopes; inline;
// returns True if the given object type has a scope class registered with it
class function IsObjectTypeRegistered(ObjectType: TClass; InheritOkay: Boolean = False): Boolean; inline;
// returns True if the given scope class is registered with an object type
class function IsScopeClassRegistered(ScopeClass: TScopeClass): Boolean; inline;
// returns the scope class associated with the given object type that object type
// is registered; if not, it returns the scope class for the closest registered
// ancestor for the given object type; if no ancestor is found, it returns nil
class function GetBestFitScope(ObjectType: TClass): TScopeClass;
class function GetEnumerator: TScopeTuples.TPairEnumerator; inline;
/// <summary>Instantiates a custom scope associated to either the type of the passed object,
/// either to the passed class reference.</summary>
/// <param name="AObject">The object which the custom scope will be able to use
/// to create custom wrappers.</param>
/// <param name="MetaClass">The class reference to be used in case the object is nil.
/// This parameter cannot be nil if the passed object is nil.</param>
/// <returns>The custom scope instance.</returns>
class function CreateScope(const AObject: TObject; MetaClass: TClass): TCustomScope; overload;
/// <param name="AObject">The object which the custom scope will be able to use
/// to create custom wrappers.</param>
/// <param name="MetaClass">The class reference to be used in case the object is nil.
/// This parameter cannot be nil if the passed object is nil.</param>
/// <param name="AObject"></param>
/// <param name="MetaClass"></param>
/// <param name="CustomScope">If the function succeeds, it contains a reference
/// to the custom scope instance. If no association is found for the passed class references,
/// this parameter contains nil.</param>
/// <returns>True if it succeeds and False if it doesn't.</returns>
class function CreateScope(const AObject: TObject; MetaClass: TClass;
out CustomScope: TCustomScope): Boolean; overload; inline;
/// <summary>Instantiates a custom scope associated to the type of the passed object.</summary>
/// <param name="AObject">The object which the custom scope will be able to use
/// to create custom wrappers. It cannot be nil.</param>
/// <returns>The custom scope instance.</returns>
class function CreateScope(const AObject: TObject): TCustomScope; overload;
class function CreateScope(const AObject: TObject; out CustomScope: TCustomScope): Boolean; overload; inline;
// access to the registered custom scope classes
class property ScopeClasses[const ObjectType: TClass]: TScopeClass read GetScopeClasses;
// the total number of registered custom scope classes
class property ScopeClassCount: Integer read GetScopeClassCount;
end;
implementation
uses
System.Bindings.NotifierDefaults, System.Bindings.ExpressionDefaults,
System.Bindings.ManagerDefaults, System.SyncObjs;
{ TBindingExpressionFactory }
class function TBindingExpressionFactory.CreateExpression(
Manager: TBindingManager): TBindingExpression;
begin
if not Assigned(Manager) then
Manager := TBindingManagerFactory.AppManager;
Result := TBindingExpressionDefault.Create(Manager);
end;
{ TBindingManagerFactory }
class constructor TBindingManagerFactory.Create;
begin
inherited;
FAppManager := CreateManagerInstance(nil);
end;
class function TBindingManagerFactory.CreateManager(Owner: TBindingManager): TBindingManager;
begin
if not Assigned(Owner) then
Owner := AppManager;
Result := CreateManagerInstance(Owner);
end;
class function TBindingManagerFactory.CreateManagerInstance(
Owner: TBindingManager): TBindingManager;
begin
Result := TBindingManagerDefault.Create(Owner);
end;
class destructor TBindingManagerFactory.Destroy;
begin
FAppManager.Free;
inherited;
end;
{ TBindingScopeFactory }
class function TBindingScopeFactory.CreateScope(
const AObject: TObject; MetaClass: TClass): TCustomScope;
var
ScopeClass: TScopeClass;
begin
if not Assigned(AObject) and not Assigned(MetaClass) then
raise EBindingScopeFactoryError.CreateFmt(sParamIsNil, ['MetaClass']);
Result := nil;
if AObject = nil then
ScopeClass := GetBestFitScope(MetaClass)
else
ScopeClass := GetBestFitScope(AObject.ClassType);
if Assigned(ScopeClass) then
Result := ScopeClass.Create(AObject, MetaClass);
end;
class function TBindingScopeFactory.CreateScope(
const AObject: TObject): TCustomScope;
begin
if not Assigned(AObject) then
raise EBindingScopeFactoryError.CreateFmt(SParamIsNil, ['AObject']);
Result := CreateScope(AObject, AObject.ClassType);
end;
class function TBindingScopeFactory.CreateScope(const AObject: TObject;
MetaClass: TClass; out CustomScope: TCustomScope): Boolean;
begin
CustomScope := CreateScope(AObject, MetaClass);
Result := Assigned(CustomScope);
end;
class destructor TBindingScopeFactory.Destroy;
begin
FreeAndNil(FScopeTuples);
end;
class function TBindingScopeFactory.GetBestFitScope(
ObjectType: TClass): TScopeClass;
var
ScopeTuple: TScopeTuple;
BestObjType: TClass;
Found: Boolean;
LScopeTuples: TScopeTuples;
begin
LScopeTuples := GetScopeTuples;
// try to find an exact match
if not LScopeTuples.TryGetValue(ObjectType, Result) then
begin
// determine the best fit by cycling among all the registered types
// and select the closest existing ancestor for ObjectType
BestObjType := TObject;
Found := False;
for ScopeTuple in LScopeTuples do
begin
if ObjectType.InheritsFrom(ScopeTuple.Key) and ScopeTuple.Key.InheritsFrom(BestObjType) then
begin
BestObjType := ScopeTuple.Key;
Found := True;
end;
end;
// get the scope class associated with the closest existing ancestor for object type
if Found then
Result := LScopeTuples.Items[BestObjType]
else
Result := nil;
end;
end;
class function TBindingScopeFactory.GetEnumerator: TScopeTuples.TPairEnumerator;
begin
Result := GetScopeTuples.GetEnumerator;
end;
class function TBindingScopeFactory.GetScopeClassCount: Integer;
begin
Result := GetScopeTuples.Count
end;
class function TBindingScopeFactory.GetScopeClasses(
const ObjectType: TClass): TScopeClass;
begin
Result := GetScopeTuples[ObjectType]
end;
class function TBindingScopeFactory.IsObjectTypeRegistered(
ObjectType: TClass; InheritOkay: Boolean = False): Boolean;
begin
if InheritOkay then
Result := GetBestFitScope(ObjectType) <> nil
else
Result := GetScopeTuples.ContainsKey(ObjectType);
end;
class function TBindingScopeFactory.IsScopeClassRegistered(
ScopeClass: TScopeClass): Boolean;
begin
Result := GetScopeTuples.ContainsValue(ScopeClass);
end;
class procedure TBindingScopeFactory.RegisterScope(ObjectType: TClass;
ScopeClass: TScopeClass);
begin
if IsScopeClassRegistered(ScopeClass) then
raise EBindingScopeFactoryError.CreateFmt(sScopeClassAlreadyRegistered, [ScopeClass.ClassName]);
GetScopeTuples.Add(ObjectType, ScopeClass);
end;
class procedure TBindingScopeFactory.UnregisterObjectType(ObjectType: TClass);
begin
if not IsObjectTypeRegistered(ObjectType) then
raise EBindingScopeFactoryError.CreateFmt(sObjectTypeNotRegistered, [ObjectType.ClassName]);
GetScopeTuples.Remove(ObjectType);
end;
class procedure TBindingScopeFactory.UnregisterScope(ScopeClass: TScopeClass);
var
ScopeTuple: TScopeTuple;
TupleList: TList<TScopeTuple>;
LScopeTuples: TScopeTuples;
begin
LScopeTuples := GetScopeTuples;
if not IsScopeClassRegistered(ScopeClass) then
raise EBindingScopeFactoryError.CreateFmt(sScopeClassNotRegistered, [ScopeClass.ClassName]);
TupleList := nil;
try
// generate a list that stores the tuples containing the given scope class
TupleList := TList<TScopeTuple>.Create;
for ScopeTuple in LScopeTuples do
if ScopeTuple.Value = ScopeClass then
TupleList.Add(ScopeTuple);
// delete the associations that reference the given scope class
for ScopeTuple in TupleList do
LScopeTuples.Remove(ScopeTuple.Key);
finally
TupleList.Free;
end;
end;
class procedure TBindingScopeFactory.UnregisterScopes;
begin
GetScopeTuples.Clear;
end;
class function TBindingScopeFactory.CreateScope(const AObject: TObject;
out CustomScope: TCustomScope): Boolean;
begin
CustomScope := CreateScope(AObject);
Result := Assigned(CustomScope);
end;
class function TBindingScopeFactory.GetScopeTuples: TScopeTuples;
var
LScopeTuples: TScopeTuples;
begin
if FScopeTuples = nil then
begin
LScopeTuples := TScopeTuples.Create;
if TInterlocked.CompareExchange(Pointer(FScopeTuples), Pointer(LScopeTuples), nil) <> nil then
LScopeTuples.Free;
end;
Result := FScopeTuples;
end;
end.
|
unit ncPrintFile;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls,
Dialogs, StdCtrls, DateUtils, ExtCtrls, ComCtrls, Mask, Printers, Winspool,
FileCtrl, ncDebug;
procedure PrintFile(const sPrinter, sFileName: string; aDataType: String = 'TEXT');
implementation
{procedure PrintFile(const sPrinter, sFileName: string);
var
I: Integer;
P: TextFile;
SL: TStrings;
begin
Printer.PrinterIndex := Printer.Printers.IndexOf(sPrinter);
AssignPrn(P);
Rewrite(P);
Printer.Canvas.Font.Name := 'Courier New';
SL := TStringList.Create;
try
SL.LoadFromFile(sFileName);
for I := 0 to sl.Count - 1 do
Writeln(P, sl[I]);
finally
CloseFile(P);
end;
end;}
procedure PrintFile(const sPrinter, sFileName: string; aDataType: String = 'TEXT');
const
iBufferSize = 32768;
var
Count, BytesWritten: Cardinal;
hPrinter, hDeviceMode: THandle;
sDevice : array[0..255] of char;
sDriver : array[0..255] of char;
sPort : array[0..255] of char;
DocInfo: TDocInfo1;
f: File;
pBuffer: Pointer;
begin
DebugMsg('PrintFile - sPrinter: ' + sPrinter + ' - sFileName: ' + sFileName + ' - aDataType: ' + aDataType);
Printer.PrinterIndex := Printer.Printers.IndexOf(sPrinter);
Printer.GetPrinter(sDevice, sDriver, sPort, hDeviceMode);
if not WinSpool.OpenPrinter(@sDevice, hPrinter, nil) then begin
DebugMsg('PrintFile - Falhou OpenPrinter: '+IntToStr(GetLastError));
exit;
end;
DocInfo.pDocName := PChar(sFileName);
DocInfo.pDatatype := PChar(aDataType);
DocInfo.pOutputFile := nil;
if StartDocPrinter(hPrinter, 1, @DocInfo) = 0 then
begin
DebugMsg('PrintFile - Falhou StartDocPrinter: '+IntToStr(GetLastError));
if SameText(aDataType, 'TEXT') then
aDataType := 'RAW' else
aDataType := 'TEXT';
DocInfo.pDatatype := PChar(aDataType);
if StartDocPrinter(hPrinter, 1, @DocInfo) = 0 then begin
DebugMsg('PrintFile - Falhou StartDocPrinter: '+IntToStr(GetLastError));
WinSpool.ClosePrinter(hPrinter);
exit;
end else
DebugMsg('PrintFile - StartDocPrinter OK !');
end;
if not StartPagePrinter(hPrinter) then
begin
DebugMsg('PrintFile - Falhou StartPagePrinter: '+IntToStr(GetLastError));
EndDocPrinter(hPrinter);
WinSpool.ClosePrinter(hPrinter);
exit;
end;
System.Assign(f, sFileName);
try
Reset(f, 1);
GetMem(pBuffer, iBufferSize);
while not eof(f) do
begin
Blockread(f, pBuffer^, iBufferSize, Count);
if Count>0 then
begin
if not WritePrinter(hPrinter, pBuffer, Count, BytesWritten) then
begin
DebugMsg('PrintFile - Falhou WritePrinter: '+IntToStr(GetLastError));
EndPagePrinter(hPrinter);
EndDocPrinter(hPrinter);
WinSpool.ClosePrinter(hPrinter);
FreeMem(pBuffer, iBufferSize);
exit;
end;
end;
end;
FreeMem(pBuffer, iBufferSize);
EndDocPrinter(hPrinter);
WinSpool.ClosePrinter(hPrinter);
finally
System.Closefile(f);
end;
end;
end.
|
unit report;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, dialogs, configuration, DOM, XMLRead, dateutils, utils;
type
TReport = class
Name : String;
Author : String;
Version: String;
Bin : String;
Params : String;
Output: String;
Summary: String;
DirPath: String;
CFG: TOTConfig;
constructor Create(FilePath: string; mCFG: TOTConfig);
function CmdLine(StartDate, EndDate: string):string;
end;
implementation
constructor TReport.Create(FilePath: string; mCFG: TOTConfig);
var
Node: TDOMNode;
Doc: TXMLDocument;
begin
self.Name := '';
self.Author := '';
self.Version:= '';
self.Bin := '';
self.Params := '';
self.Output:= '';
self.Summary:= '';
self.CFG := mCFG;
self.DirPath := ExtractFilePath(FilePath);
IF FileExists(FilePath) THEN BEGIN
ReadXMLFile(Doc, FilePath);
Node := Doc.DocumentElement.FindNode('name');
self.Name := OTFormatString(Node.TextContent);
Node := Doc.DocumentElement.FindNode('author');
self.Author := OTFormatString(Node.TextContent);
Node := Doc.DocumentElement.FindNode('version');
self.Version := OTFormatString(Node.TextContent);
Node := Doc.DocumentElement.FindNode('bin');
self.Bin := OTFormatString(Node.TextContent);
Node := Doc.DocumentElement.FindNode('params');
self.Params := OTFormatString(Node.TextContent);
Node := Doc.DocumentElement.FindNode('output');
self.Output := OTFormatString(Node.TextContent);
Node := Doc.DocumentElement.FindNode('summary');
self.Summary := OTFormatString(Node.TextContent);
Doc.Free;
END
end;
function TReport.CmdLine(StartDate, EndDate: string): string;
var
cmline, mparams: string;
starttime, endtime: integer;
begin
//Binary script
{$IFDEF Windows}
cmline := CFG.PHPBin;
cmline := cmline+' -c '+CFG.PHPPath;
{$ENDIF}
{$IFDEF unix}
cmline := CFG.PHPBin;
{$ENDIF}
starttime := 0;
endtime := 0;
IF StartDate <> '' THEN
starttime := DateTimeToUnix(StrToDate(StartDate));
IF EndDate <> '' THEN BEGIN
endtime := DateTimeToUnix(StrToDate(EndDate));
endtime := endtime + 86399;
END;
mparams := self.Params;
mparams := StringReplace(mparams, '{dirpath}', self.DirPath, [rfReplaceAll, rfIgnoreCase]);
mparams := StringReplace(mparams, '{dbpath}', CFG.DBPath, [rfReplaceAll, rfIgnoreCase]);
mparams := StringReplace(mparams, '{reporthtmldir}', CFG.ReportsHtmlDir, [rfReplaceAll, rfIgnoreCase]);
mparams := StringReplace(mparams, '{startdate}', StartDate, [rfReplaceAll, rfIgnoreCase]);
mparams := StringReplace(mparams, '{enddate}', EndDate, [rfReplaceAll, rfIgnoreCase]);
mparams := StringReplace(mparams, '{starttime}', IntToStr(starttime), [rfReplaceAll, rfIgnoreCase]);
mparams := StringReplace(mparams, '{endtime}', IntToStr(endtime), [rfReplaceAll, rfIgnoreCase]);
cmline := cmline+' '+mparams;
result := cmline;
end;
end.
|
unit CuentaDebito;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, UnitUsuario, UnitCuentaDebito;
type
TFormCuentaDebito = class(TForm)
Label1: TLabel;
txtNombre: TEdit;
txtNumCuenta: TEdit;
txtSaldo: TEdit;
btnRetirar: TButton;
btnAbonar: TButton;
txtMonto: TEdit;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Label5: TLabel;
btnAtras: TButton;
procedure FormShow(Sender: TObject);
procedure FillTextBoxes;
procedure btnRetirarClick(Sender: TObject);
function validarMonto () : boolean;
procedure btnAbonarClick(Sender: TObject);
procedure updateTextBoxes;
procedure crearMovimiento (tipoMovimiento : string);
procedure btnAtrasClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
monto : integer;
currentDate : TDateTime;
procedure updateSaldo;
public
usuario : TUsuario;
cuentaDebito : TCuentaDebito;
end;
var
FormCuentaDebito: TFormCuentaDebito;
implementation
{$R *.dfm}
uses ElegirCuenta, DataModuleDani;
procedure TFormCuentaDebito.FormShow(Sender: TObject);
begin
usuario := ElegirCuenta.FormElegirCuenta.usuario;
cuentaDebito := ElegirCuenta.FormElegirCuenta.cuentaDebito;
FillTextBoxes;
end;
procedure TFormCuentaDebito.btnAbonarClick(Sender: TObject);
begin
monto := Strtoint(txtMonto.Text);
cuentaDebito.saldo := cuentaDebito.saldo + monto;
updateSaldo;
crearMovimiento('abono');
end;
procedure TFormCuentaDebito.btnRetirarClick(Sender: TObject);
begin
monto := Strtoint(txtMonto.Text);
if validarMonto then
begin
cuentaDebito.saldo := cuentaDebito.saldo - monto;
updateSaldo;
crearMovimiento('retiro');
end
Else
begin
showmessage('La cantidad que se desea retirar es mayor que el saldo');
end;
end;
procedure TFormCuentaDebito.updateSaldo;
begin
with DataModuleDaniBD.CRUDCuentaDebito do
begin
Open;
Refresh;
if FindKey([cuentaDebito.idCuentaDebito]) then
begin
Edit;
FieldByName('saldo').AsCurrency := cuentaDebito.saldo;
Post;
end;
end;
updateTextBoxes;
end;
procedure TFormCuentaDebito.FillTextBoxes;
begin
txtNombre.Text := usuario.getNombreCompleto;
txtNumCuenta.Text := cuentaDebito.numeroDeCuenta;
txtSaldo.Text := CurrToStrF(cuentaDebito.saldo, ffCurrency, 2);
end;
procedure TFormCuentaDebito.updateTextBoxes;
begin
txtSaldo.Text := CurrToStrF(cuentaDebito.saldo, ffCurrency, 2);
txtMonto.Clear;
end;
function TFormCuentaDebito.validarMonto: boolean;
begin
if monto <= cuentaDebito.saldo then
begin
Result := true;
end
Else
begin
Result := false;
end;
end;
procedure TFormCuentaDebito.crearMovimiento(tipoMovimiento: string);
begin
currentDate := Now;
with DataModuleDaniBD.createMovimiento do
begin
Open;
Refresh;
Insert;
FieldByName('tipo_movimiento').AsString := tipoMovimiento;
FieldByName('monto').AsCurrency := monto;
FieldByName('id_cuenta_movimiento').AsInteger := cuentaDebito.idCuentaDebito;
FieldByName('fecha').AsDateTime := currentDate;
Post;
end;
showmessage('El '+tipoMovimiento+' se realizó con éxito');
end;
procedure TFormCuentaDebito.btnAtrasClick(Sender: TObject);
begin
elegirCuenta.FormElegirCuenta.cuentaDebito := cuentaDebito;
FormCuentaDebito.Visible := False;
FormElegirCuenta.Show;
end;
procedure TFormCuentaDebito.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Application.Terminate;
end;
end.
|
{ Chokyi Ozer 16518269 }
unit udatajual;
{ KAMUS }
interface
const
Nmax = 100;
type
dataJual = record
KdKategori : String;
KdProduk : String;
Hasil : Integer;
end;
tabPenjualan = record
TJual : array [1..Nmax] of dataJual;
Neff : Integer; {0..100}
end;
function EOP (rek : dataJual) : Boolean;
{ Menghasilkan true jika rek = mark }
procedure LoadDataJual (filename : String; var T : tabPenjualan);
{ I.S. : filename terdefinisi, T sembarang }
{ F.S. : Tabel T terisi data penjualan dengan data yang dibaca dari file dengan nama = filename.
T.Neff = 0 jika tidak ada file kosong;
T diisi dengan seluruh isi file atau sampai T penuh. }
procedure UrutKategoriAsc (var T : tabPenjualan);
{ I.S. : T terdefinisi; T mungkin kosong }
{ F.S. : Isi tabel T terurut membesar menurut KdKategoriProduk. T tetap jika T kosong. }
{ Proses : Gunakan salah satu algoritma sorting yang diajarkan di kelas.
Tuliskan nama algoritmanya dalam bentuk komentar. }
procedure HitungRataRata (T : tabPenjualan);
{ I.S. : T terdefinisi; T mungkin kosong. T terurut berdasarkan KdKategori. }
{ F.S. : Menampilkan KdKategori dan hasil penjualan rata-rata per KdKategori
yang ada dalam tabel dengan format: <KdKategori>=<rata-rata>
Nilai rata-rata dibulatkan ke integer terdekat. Gunakan fungsi round.
Jika tabel kosong, tuliskan "Data kosong" }
{ Proses : Menggunakan ide algoritma konsolidasi tanpa separator pada
file eksternal, hanya saja diberlakukan pada tabel. }
procedure SaveDataJual (filename : string; T : tabPenjualan);
{ I.S. : T dan filename terdefinisi, T mungkin kosong }
{ F.S. : Isi tabel T dituliskan pada file dg nama = filename }
implementation
function EOP (rek : dataJual) : Boolean;
begin
EOP := (rek.KdKategori = '99999999') and
(rek.KdProduk = 'XX9999') and
(rek.Hasil = -999);
end;
procedure LoadDataJual (filename : String; var T : tabPenjualan);
var
f : File of dataJual;
dat : dataJual;
begin
Assign(f, filename);
Reset(f);
T.Neff := 0;
Read(f, dat);
while (not EOP(dat)) do
begin
T.Neff := T.Neff + 1;
T.TJual[T.Neff] := dat;
Read(f, dat);
end;
Close(f);
end;
procedure UrutKategoriAsc (var T : tabPenjualan);
var
temp : dataJual;
i, j : Integer;
done : Boolean;
begin
if (T.Neff > 0) then
{ Bubble Sort }
i := 0;
done := False;
while (i < T.Neff) and (not done) do
begin
done := True;
for j := T.Neff downto 2 do
if (T.TJual[j].KdKategori < T.TJual[j-1].KdKategori) then
begin
temp := T.TJual[j-1];
T.TJual[j-1] := T.TJual[j];
T.TJual[j] := temp;
done := False;
end;
i := i + 1;
end;
end;
procedure HitungRataRata (T : tabPenjualan);
var
current : String;
sum, count : Integer;
i : Integer;
begin
if (T.Neff > 0) then
begin
current := T.TJual[1].KdKategori;
sum := T.TJual[1].Hasil; count := 1;
for i := 2 to T.Neff do
begin
if (T.TJual[i].KdKategori <> current) then // Section Baru
begin
Write(current);
Write('=');
WriteLn(Round(sum/count));
current := T.TJual[i].KdKategori;
sum := T.TJual[i].Hasil; count := 1;
end
else
begin
sum := sum + T.TJual[i].Hasil;
count := count + 1;
end;
end;
Write(current);
Write('=');
WriteLn(Round(sum/count));
end
else
WriteLn('Data kosong');
end;
procedure SaveDataJual (filename : string; T : tabPenjualan);
const
mark : dataJual = (
KdKategori : '99999999';
KdProduk : 'XX9999';
Hasil : -999;
);
var
f : File of dataJual;
i : Integer;
begin
Assign(f, filename);
Rewrite(f);
if (T.Neff > 0) then
for i := 1 to T.Neff do
begin
Write(f, T.TJual[i]);
end;
Write(f, mark);
Close(f);
end;
end. |
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000 Inprise Corporation }
{ }
{*******************************************************}
unit DispHandlers;
interface
uses Classes, Messages, HTTPApp, HTTPProd, WebCntxt,
Masks, WebComp, Contnrs, SysUtils, SiteComp, WebDisp;
type
TCustomWebDispatchHandler = class;
{ Keeps a list of dispatch components rather than a collection
of dispatch actions }
TDispatchHandlersContainer = class(TWebContainerComponent,
IWebComponentEditor)
protected
function GetDefaultWebComponents: TWebComponentList; override;
procedure SetDefaultWebComponents(AList: TWebComponentList); override;
{ IWebComponentEditor }
function CanAddClass(AParent: TComponent; AClass: TClass): Boolean;
function ImplCanAddClass(AParent: TComponent; AClass: TClass): Boolean; virtual;
public
property DispatchHandlers: TWebComponentList read GetWebComponents;
end;
TCustomDispatchHandlers = class(TDispatchHandlersContainer,
IMultiModuleSupport, IWebRequestHandler, IWebDispatchActions, ITopLevelWebComponent)
private
FRequest: TWebRequest;
FResponse: TWebResponse;
FDispatchList: TComponentList;
FBeforeDispatch: THTTPMethodEvent;
FAfterDispatch: THTTPMethodEvent;
protected
function DoAfterDispatch(Request: TWebRequest;
Response: TWebResponse): Boolean;
function DoBeforeDispatch(Request: TWebRequest;
Response: TWebResponse): Boolean;
function DispatchDefaultHandler(Request: TWebRequest;
Response: TWebResponse): Boolean;
{ IWebRequestHandler }
function HandleRequest(Request: TWebRequest;
Response: TWebResponse): Boolean;
function ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse): Boolean; virtual;
{ IMultiModuleSupport }
procedure InitContext(Request: TWebRequest; Response: TWebResponse);
procedure InitModule(AModule: TComponent);
procedure FinishContext;
function GetRequest: TWebRequest;
function GetResponse: TWebResponse;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Request: TWebRequest read GetRequest;
property Response: TWebResponse read GetResponse;
property BeforeDispatch: THTTPMethodEvent read FBeforeDispatch write FBeforeDispatch;
property AfterDispatch: THTTPMethodEvent read FAfterDispatch write FAfterDispatch;
end;
TDispatchHandlers = class(TCustomDispatchHandlers)
published
property DispatchHandlers;
property BeforeDispatch;
property AfterDispatch;
end;
TAbstractWebDispatchHandler = class(TWebContainedComponent)
end;
IWebDispatchHandler = interface
['{711D78E7-EB03-11D3-A41F-00C04F6BB853}']
function HandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
procedure SetDefault(AValue: Boolean);
function GetDefault: Boolean;
property Default: Boolean read GetDefault write SetDefault;
end;
TBaseWebDispatchHandler = class(TAbstractWebDispatchHandler, IWebDispatchHandler,
ISetAppDispatcher)
private
FDefault: Boolean;
FEnabled: Boolean;
FMethodType: TMethodType;
FAppDispatcher: TComponent;
protected
{ ISetAppDispatcher }
procedure SetAppDispatcher(const Value: TComponent);
{ IWebDispatchHandler }
function HandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
procedure SetDefault(AValue: Boolean);
function GetDefault: Boolean;
function ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean; virtual;
procedure ImplSetDefault(AValue: Boolean); virtual;
function ImplGetDefault: Boolean; virtual;
procedure SetEnabled(Value: Boolean);
procedure SetMethodType(Value: TMethodType);
public
constructor Create(AOwner: TComponent); override;
property Default: Boolean read ImplGetDefault write ImplSetDefault default False;
property Enabled: Boolean read FEnabled write SetEnabled default True;
property MethodType: TMethodType read FMethodType write SetMethodType default mtAny;
property AppDispatcher: TComponent read FAppDispatcher;
end;
TCustomPathInfoDispatchHandler = class(TBaseWebDispatchHandler)
private
FPathInfo: string;
FMaskPathInfo: string;
FMask: TMask;
protected
function HandlesRequest(Request: TWebRequest; const RootPath: string; DoDefault: Boolean): Boolean;
function FixupPathInfo(const Value: string): string; virtual;
function GetPathInfo: string; virtual;
procedure SetPathInfo(const Value: string); virtual;
function GetMask(const RootPath: string): TMask;
public
destructor Destroy; override;
property PathInfo: string read GetPathInfo write SetPathInfo;
end;
TCustomWebDispatchHandler = class(TCustomPathInfoDispatchHandler)
private
FOnAction: THTTPMethodEvent;
FProducer: TComponent;
FProducerContent: TComponent;
procedure SetProducerContent(const Value: TComponent);
procedure SetProducer(const Value: TComponent);
procedure SetOnAction(Value: THTTPMethodEvent);
protected
function ProducerPathInfo: string;
function FixupPathInfo(const Value: string): string; override;
function GetMask(const RootPath: string): TMask;
function GetPathInfo: string; override;
{ IWebDispatchHandler }
function ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
property Producer: TComponent read FProducer write SetProducer;
property ProducerContent: TComponent read FProducerContent write SetProducerContent;
property OnAction: THTTPMethodEvent read FOnAction write SetOnAction;
end;
TWebDispatchHandler = class(TCustomWebDispatchHandler)
published
property Default;
property Enabled;
property MethodType;
property PathInfo;
property Producer;
property ProducerContent;
property OnAction;
end;
TCustomFileDispatchHandler = class(TCustomPathInfoDispatchHandler)
private
FHTMLFile: TFileName;
public
function ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean; override;
property HTMLFile: TFileName read FHTMLFile write FHTMLFile;
end;
TFileDispatchHandler = class(TCustomFileDispatchHandler)
published
property HTMLFile;
property Default;
property Enabled;
property MethodType;
property PathInfo;
end;
TCustomPageDispatchHandler = class(TCustomPathInfoDispatchHandler)
private
FPage: string;
FOnAfterDispatchPage: TDispatchPageEvent;
FOnBeforeDispatchPage: TDispatchPageHandledEvent;
public
function ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean; override;
property Page: string read FPage write FPage;
property OnBeforeDispatchPage: TDispatchPageHandledEvent read FOnBeforeDispatchPage write FOnBeforeDispatchPage;
property OnAfterDispatchPage: TDispatchPageEvent read FOnAfterDispatchPage write FOnAfterDispatchPage;
end;
TPageDispatchHandler = class(TCustomPageDispatchHandler)
published
property Page;
property Default;
property Enabled;
property MethodType;
property PathInfo;
property OnBeforeDispatchPage;
property OnAfterDispatchPage;
end;
implementation
uses WebConst, Windows,
WebScript, WebSess, Variants, AdaptReq, WebAdapt;
{ TDispatchHandlersContainer }
function TDispatchHandlersContainer.CanAddClass(AParent: TComponent; AClass: TClass): Boolean;
begin
Result := ImplCanAddClass(AParent, AClass);
end;
function TDispatchHandlersContainer.GetDefaultWebComponents: TWebComponentList;
begin
Result := nil;
end;
function TDispatchHandlersContainer.ImplCanAddClass(AParent: TComponent; AClass: TClass): Boolean;
begin
Result := AClass.InheritsFrom(TAbstractWebDispatchHandler);
end;
{ Copied from httpapp }
function DispatchHandler(Sender: TObject; Dispatch: IWebDispatch; Request: TWebRequest; Response: TWebResponse;
DoDefault: Boolean): Boolean;
begin
Result := False;
if (Dispatch.Enabled and ((Dispatch.MethodType = mtAny) or
(Dispatch.MethodType = Dispatch.MethodType)) and
Dispatch.Mask.Matches(Request.InternalPathInfo)) then
begin
Result := Dispatch.DispatchRequest(Sender, Request, Response);
end;
end;
procedure TDispatchHandlersContainer.SetDefaultWebComponents(
AList: TWebComponentList);
begin
Assert(False);
// Unexpected call
end;
{ TBaseWebDispatchHandler }
function TBaseWebDispatchHandler.GetDefault: Boolean;
begin
Result := ImplGetDefault;
end;
function TBaseWebDispatchHandler.HandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
begin
Result := ImplHandleRequest(Request, Response, RootPath, DoDefault);
end;
function TBaseWebDispatchHandler.ImplGetDefault: Boolean;
begin
Result := FDefault;
end;
function TBaseWebDispatchHandler.ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
begin
Result := False;
end;
procedure TBaseWebDispatchHandler.SetDefault(AValue: Boolean);
begin
ImplSetDefault(AValue);
end;
constructor TBaseWebDispatchHandler.Create(AOwner: TComponent);
begin
inherited;
FEnabled := True;
end;
procedure TBaseWebDispatchHandler.SetEnabled(Value: Boolean);
begin
FEnabled := Value;
end;
procedure TBaseWebDispatchHandler.SetMethodType(Value: TMethodType);
begin
FMethodType := Value;
end;
procedure TBaseWebDispatchHandler.ImplSetDefault(AValue: Boolean);
var
I: Integer;
Handler: TComponent;
WebDispatchHandler: IWebDispatchHandler;
begin
if AValue <> FDefault then
begin
if AValue and (GetContainerList <> nil) and not (csLoading in ComponentState) then
begin
for I := 0 to GetContainerList.Count - 1 do
begin
Handler := GetContainerList[I];
if (Handler <> Self) and Supports(IInterface(Handler), IWebDispatchHandler, WebDispatchHandler) then
WebDispatchHandler.Default := False;
end;
end;
end;
FDefault := AValue;
end;
procedure TBaseWebDispatchHandler.SetAppDispatcher(
const Value: TComponent);
begin
FAppDispatcher := Value;
end;
{ TCustomWebDispatchHandler }
procedure TCustomWebDispatchHandler.SetOnAction(Value: THTTPMethodEvent);
begin
FOnAction := Value;
end;
function TCustomWebDispatchHandler.FixupPathInfo(const Value: string): string;
begin
Result := inherited FixupPathInfo(Value);
if Assigned(FProducer) and (Result = ProducerPathInfo) then
Result := '';
end;
procedure TCustomWebDispatchHandler.SetProducer(const Value: TComponent);
begin
if Assigned(Value) then
begin
Value.FreeNotification(Self);
FProducerContent := nil;
end;
FProducer := Value;
end;
procedure TCustomWebDispatchHandler.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FProducer) then
FProducer := nil;
if (Operation = opRemove) and (AComponent = FProducerContent) then
FProducerContent := nil;
end;
function TCustomWebDispatchHandler.ProducerPathInfo: string;
begin
Assert(Assigned(FProducer));
Result := '/' + FProducer.Name
end;
function TCustomWebDispatchHandler.GetPathInfo: string;
begin
if (FPathInfo = '') and Assigned(FProducer) then
Result := ProducerPathInfo
else
Result := FPathInfo;
end;
function TCustomWebDispatchHandler.GetMask(const RootPath: string): TMask;
var
Mask: TMask;
MaskPathInfo: string;
begin
MaskPathInfo := GetPathInfo;
if RootPath <> '' then
MaskPathInfo := RootPath + MaskPathInfo;
if (not Assigned(FMask)) or
(AnsiCompareText(FMaskPathInfo, MaskPathInfo) <> 0) then
begin
Mask := TMask.Create(MaskPathInfo);
try
FMaskPathInfo := MaskPathInfo;
if Assigned(FMask) then
begin
FMask.Free;
FMask := nil;
end;
except
Mask.Free;
raise;
end;
FMask := Mask;
end;
Result := FMask;
end;
function TCustomWebDispatchHandler.ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
var
ProduceContent: IProduceContent;
begin
Result := False;
if HandlesRequest(Request, RootPath, DoDefault) then
begin
Result := True;
if Supports(IUnknown(FProducer), IProduceContent, ProduceContent) then
begin
Response.Content := ProduceContent.ProduceContent;
end;
if Assigned(FOnAction) then
begin
FOnAction(Self, Request, Response, Result);
end
end;
end;
{ TCustomFileDispatchHandler }
// Extract a file name from the path and use the file as an HTML template
function TCustomFileDispatchHandler.ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
var
Producer: TPageProducer;
S: string;
P: Integer;
SetAppDispatcher: ISetAppDispatcher;
begin
Result := False;
if HandlesRequest(Request, RootPath, DoDefault) then
begin
S := Request.PathInfo;
P := Pos('/', S);
while P <> 0 do
begin
Delete(S, 1, P);
P := Pos('/', S);
end;
S := QualifyFileName(S);
if FileExists(S) then
begin
Producer := TPageProducer.Create(nil);
try
if Supports(IInterface(Producer), ISetAppDispatcher, SetAppDispatcher) then
SetAppDispatcher.SetAppDispatcher(AppDispatcher);
Producer.HTMLFile := S;
Response.Content := Producer.Content;
Result := True;
finally
Producer.Free;
end;
end;
end;
end;
procedure TCustomWebDispatchHandler.SetProducerContent(
const Value: TComponent);
begin
if Assigned(Value) then
begin
Value.FreeNotification(Self);
FProducer := nil;
end;
FProducerContent := Value;
end;
{ TCustomPageDispatchHandler }
function TCustomPageDispatchHandler.ImplHandleRequest(Request: TWebRequest;
Response: TWebResponse; const RootPath: string; DoDefault: Boolean): Boolean;
begin
Result := False;
if HandlesRequest(Request, RootPath, DoDefault) then
begin
if Assigned(OnBeforeDispatchPage) then
OnBeforeDispatchPage(Self, Page, Result);
if not Result then
begin
Result := DispatchPageName(Page, Response, [dpPublished]);
if Assigned(OnAfterDispatchPage) then
OnAfterDispatchPage(Self, Page);
end;
end;
end;
{ TCustomDispatchHandlers }
function TCustomDispatchHandlers.HandleRequest(
Request: TWebRequest; Response: TWebResponse): Boolean;
begin
Result := ImplHandleRequest(Request, Response);
end;
function TCustomDispatchHandlers.DoAfterDispatch(Request: TWebRequest; Response: TWebResponse): Boolean;
begin
Result := True;
if Assigned(FAfterDispatch) then
FAfterDispatch(Self, Request, Response, Result);
end;
function TCustomDispatchHandlers.DoBeforeDispatch(Request: TWebRequest; Response: TWebResponse): Boolean;
begin
Result := False;
if Assigned(FBeforeDispatch) then
FBeforeDispatch(Self, Request, Response, Result);
end;
function TCustomDispatchHandlers.ImplHandleRequest(
Request: TWebRequest; Response: TWebResponse): Boolean;
var
I: Integer;
Handler, Default: TComponent;
Dispatch: IWebDispatch;
WebDispatchHandler: IWebDispatchHandler;
begin
FRequest := Request;
FResponse := Response;
Default := nil;
if Response.Sent then
begin
Result := True;
Exit;
end;
Result := DoBeforeDispatch(Request, Response) or Response.Sent;
I := 0;
while not Result and (I < DispatchHandlers.Count) do
begin
Handler := DispatchHandlers.WebComponents[I];
if Supports(IInterface(Handler), IWebDispatchHandler, WebDispatchHandler) then
begin
Result := WebDispatchHandler.HandleRequest(Request, Response, '', False);
if WebDispatchHandler.Default then Default := Handler;
end;
Inc(I);
end;
// Dispatch to self registering components
I := 0;
while not Result and (I < FDispatchList.Count) do
begin
if Supports(IInterface(FDispatchList.Items[I]), IWebDispatch, Dispatch) then
begin
Result := DispatchHandler(Self, Dispatch,
Request, Response, False);
end;
Inc(I);
end;
if not Result and Assigned(Default) then
begin
if Supports(IInterface(Default), IWebDispatchHandler, WebDispatchHandler) then
Result := WebDispatchHandler.HandleRequest(Request, Response, '', True);
end;
if Result and not Response.Sent then
Result := DoAfterDispatch(Request, Response);
end;
function TCustomDispatchHandlers.DispatchDefaultHandler(
Request: TWebRequest; Response: TWebResponse): Boolean;
var
I: Integer;
Handler, Default: TComponent;
WebDispatchHandler: IWebDispatchHandler;
begin
Result := False;
I := 0;
Default := nil;
while not Assigned(Default) and (I < DispatchHandlers.Count) do
begin
Handler := DispatchHandlers.WebComponents[I];
if Supports(IInterface(Handler), IWebDispatchHandler, WebDispatchHandler) then
if WebDispatchHandler.Default then Default := Handler;
Inc(I);
end;
if Assigned(Default) then
begin
Supports(IInterface(Default), IWebDispatchHandler, WebDispatchHandler);
Result := WebDispatchHandler.HandleRequest(Request, Response, '', True);
end;
end;
procedure TCustomDispatchHandlers.InitModule(AModule: TComponent);
var
I: Integer;
Component: TComponent;
DispatchIntf: IWebDispatch;
begin
for I := 0 to AModule.ComponentCount - 1 do
begin
Component := AModule.Components[I];
if Supports(IInterface(Component), IWebDispatch, DispatchIntf) then
FDispatchList.Add(Component)
end;
end;
function TCustomDispatchHandlers.GetRequest: TWebRequest;
begin
Result := FRequest;
end;
function TCustomDispatchHandlers.GetResponse: TWebResponse;
begin
Result := FResponse;
end;
constructor TCustomDispatchHandlers.Create(AOwner: TComponent);
begin
FDispatchList := TComponentList.Create;
FDispatchList.OwnsObjects := False;
inherited Create(AOwner);
end;
destructor TCustomDispatchHandlers.Destroy;
begin
inherited;
FDispatchList.Free;
end;
procedure TCustomDispatchHandlers.FinishContext;
begin
//
end;
procedure TCustomDispatchHandlers.InitContext(Request: TWebRequest;
Response: TWebResponse);
begin
FRequest := Request;
FResponse := Response;
FDispatchList.Clear;
end;
{ TCustomPathInfoDispatchHandler }
destructor TCustomPathInfoDispatchHandler.Destroy;
begin
FMask.Free;
inherited Destroy;
end;
procedure TCustomPathInfoDispatchHandler.SetPathInfo(const Value: string);
var
NewValue: string;
begin
NewValue := FixupPathInfo(Value);
FPathInfo := NewValue;
end;
function TCustomPathInfoDispatchHandler.GetPathInfo: string;
begin
Result := FPathInfo;
end;
function TCustomPathInfoDispatchHandler.GetMask(const RootPath: string): TMask;
var
Mask: TMask;
MaskPathInfo: string;
begin
MaskPathInfo := GetPathInfo;
if RootPath <> '' then
MaskPathInfo := RootPath + MaskPathInfo;
if (not Assigned(FMask)) or
(AnsiCompareText(FMaskPathInfo, MaskPathInfo) <> 0) then
begin
Mask := TMask.Create(MaskPathInfo);
try
FMaskPathInfo := MaskPathInfo;
if Assigned(FMask) then
begin
FMask.Free;
FMask := nil;
end;
except
Mask.Free;
raise;
end;
FMask := Mask;
end;
Result := FMask;
end;
function TCustomPathInfoDispatchHandler.FixupPathInfo(
const Value: string): string;
begin
Result := Value;
if Value <> '' then Result := DosPathToUnixPath(Value);
if (Result <> '') and (Result[1] <> '/') then Insert('/', Result, 1);
end;
{ TCustomPathInfoDispatchHandler }
function TCustomPathInfoDispatchHandler.HandlesRequest(Request: TWebRequest; const RootPath: string; DoDefault: Boolean): Boolean;
begin
Result := (FDefault and DoDefault) or (FEnabled and ((FMethodType = mtAny) or
(FMethodType = Request.MethodType)) and
GetMask(RootPath).Matches(Request.InternalPathInfo));
end;
end.
|
unit UComponentTray;
interface
uses
Winapi.Windows, System.SysUtils, System.Classes, System.Generics.Collections,
System.Generics.Defaults, System.Rtti, System.TypInfo, FMX.Types,
FMX.Controls, FMX.Forms, ToolsAPI, ComponentDesigner, EmbeddedFormDesigner,
DesignIntf, Events, PaletteAPI, DesignMenus, DesignEditors, VCLMenus,
FMXFormContainer, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls,
Vcl.ComCtrls, Vcl.Menus, Vcl.Dialogs, Vcl.Tabs, Vcl.ImgList, System.IniFiles,
Winapi.ActiveX;
procedure Register;
implementation
uses
UComponentTray.SettingsDlg;
type
TDesignNotification = class(TInterfacedObject, IDesignNotification)
public
procedure ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent);
procedure ItemInserted(const ADesigner: IDesigner; AItem: TPersistent);
procedure ItemsModified(const ADesigner: IDesigner);
procedure SelectionChanged(const ADesigner: IDesigner;
const ASelection: IDesignerSelections);
procedure DesignerOpened(const ADesigner: IDesigner; AResurrecting: Boolean);
procedure DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean);
end;
TComponentEditorMenuItem = class(TMenuItem)
private
FComponentEditor: IComponentEditor;
FVerbIndex: Integer;
public
constructor Create(AOwner: TComponent; AComponentEditor: IComponentEditor;
AVerbIndex: Integer); reintroduce;
procedure Click; override;
property ComponentEditor: IComponentEditor read FComponentEditor;
end;
TSelectionEditorMenuItem = class(TMenuItem)
private
FSelectionEditor: ISelectionEditor;
FVerbIndex: Integer;
FSelections: IDesignerSelections;
public
constructor Create(AOwner: TComponent; ASelectionEditor: ISelectionEditor;
AVerbIndex: Integer; ASelections: IDesignerSelections); reintroduce;
procedure Click; override;
property SelectionEditor: ISelectionEditor read FSelectionEditor;
end;
TTypeData = record
&Type: TClass;
Count: Integer;
Visible: Boolean;
end;
TComponentTray = class;
TOTAPaletteDragAcceptor = class(TInterfacedObject, IOTAPaletteDragAcceptor, IOTADesignerDragAcceptor)
private
FControl: TComponentTray;
{ IOTAPaletteDragAcceptor }
function GetHandle: THandle;
public
constructor Create(AControl: TComponentTray);
end;
TComponentTray = class(TPanel, IDropTarget)
private
FListView: TListView;
FSplitter: TSplitter;
FSortType: Integer;
FAcceptor: IOTAPaletteDragAcceptor;
FAcceptorIndex: Integer;
FDragAllowed: Boolean;
FTypes: TDictionary<TClass,TTypeData>;
procedure ListViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure ListViewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure ListViewDblClick(Sender: TObject);
procedure ListViewSelect(Sender: TObject; Item: TListItem; Selected: Boolean);
procedure ListViewContextPopup(Sender: TObject; MousePos: TPoint; var Handled: Boolean);
procedure ListViewCompareCreationOrder(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure ListViewCompareName(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure ListViewCompareType(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
procedure SplitterMoved(Sender: TObject);
procedure LoadSettings;
procedure SaveSettings;
class procedure UpdateTrays(Style, Position: Integer;
SplitterEnabled: Boolean; SplitterColor: TColor); static;
{ IDropTarget }
function DropTarget_DragEnter(const dataObj: IDataObject; grfKeyState: Longint;
pt: TPoint; var dwEffect: Longint): HResult; stdcall;
function DropTarget_DragOver(grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult; stdcall;
function DropTarget_DragLeave: HResult; stdcall;
function DropTarget_Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult; stdcall;
function IDropTarget.DragEnter = DropTarget_DragEnter;
function IDropTarget.DragOver = DropTarget_DragOver;
function IDropTarget.DragLeave = DropTarget_DragLeave;
function IDropTarget.Drop = DropTarget_Drop;
protected
procedure CreateWnd; override;
procedure DestroyWnd; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure AddItem(AItem: TPersistent);
procedure RemoveItem(AItem: TPersistent);
procedure UpdateCaptions;
procedure UpdateItems(DoReplace: Boolean = False);
procedure UpdateSelection(const ASelection: IDesignerSelections);
procedure ChangeAlign(AValue: TAlign);
procedure Sort(SortType: Integer = -1);
end;
TComponentPopupMenu = class(TPopupMenu)
mnuNVCBFilter: TMenuItem;
mnuNVCBSort: TMenuItem;
private
FMenuLine: TMenuItem;
{$IFDEF DEBUG}
procedure TestClick(Sender: TObject);
{$ENDIF}
procedure FilterClick(Sender: TObject);
procedure FilterCheckAllClick(Sender: TObject);
procedure FilterUncheckAllClick(Sender: TObject);
procedure SortClick(Sender: TObject);
procedure SettingsClick(Sender: TObject);
public
constructor Create(AOwner: TComponent); override;
procedure BuildContextMenu;
end;
TPropFieldNotifyEvent = procedure(Sender: TObject{TPropField}) of object;
TComponentImageList = class
private
FImageList: TImageList;
FImageDict: TDictionary<TClass,Integer>;
public
constructor Create;
destructor Destroy; override;
function AddOrGet(AClass: TClass): Integer;
property ImageList: TImageList read FImageList;
end;
var
FOrgTEditorFormDesignerAfterConstruction: procedure(Self: TObject);
FTrays: TObjectList<TComponentTray>;
FCompImageList: TComponentImageList;
FShowNonVisualComponentsChange: TPropFieldNotifyEvent;
FShowNonVisualComponentsValueProp: PPropInfo;
FShowNonVisualComponentsOnChangeProp: PPropInfo;
FEditorViewsChangedEvent: ^TEvent;
FDesignNotification: IDesignNotification;
FComponentDeleting: Boolean;
FComponentSelecting: Boolean;
function IsNonVisualComponent(AClass: TClass): Boolean; overload;
begin
Result := (AClass <> nil)
and AClass.InheritsFrom(TComponent)
and not AClass.InheritsFrom(Vcl.Controls.TControl)
and not AClass.InheritsFrom(FMX.Controls.TControl)
and not AClass.InheritsFrom(FMX.Forms.TCommonCustomForm);
end;
function IsNonVisualComponent(Instance: TPersistent): Boolean; overload;
begin
Result := (Instance <> nil) and IsNonVisualComponent(Instance.ClassType);
end;
procedure HideNonVisualComponents;
begin
if ActiveRoot = nil then Exit;
if ActiveRoot.Root is TDataModule then Exit;
(BorlandIDEServices as IOTAServices).GetEnvironmentOptions.Values['ShowNonVisualComponents'] := False;
end;
function GetComponentTray(AControl: TWinControl): TComponentTray;
var
i: Integer;
begin
if AControl is TComponentTray then
Exit(TComponentTray(AControl));
for i := 0 to AControl.ControlCount-1 do
if AControl.Controls[i] is TWinControl then
begin
Result := GetComponentTray(TWinControl(AControl.Controls[i]));
if Result <> nil then Exit;
end;
Result := nil;
end;
function GetEditWindow(Control: TWinControl): TWinControl;
begin
Result := Control;
while Result <> nil do
begin
if Result.ClassName = 'TEditWindow' then
Exit;
Result := Result.Parent;
end;
end;
function ViewStyleToInt(Value: TViewStyle): Integer;
begin
Result := Ord(Value);
end;
function IntToViewStyle(Value: Integer): TViewStyle;
begin
if (Value >= Ord(vsIcon)) and (Value <= Ord(vsList)) then
Result := TViewStyle(Value)
else
Result := vsSmallIcon;
end;
function AlignToInt(Value: TAlign): Integer;
begin
case Value of
alLeft: Result := 0;
alTop: Result := 1;
alRight: Result := 2;
alBottom: Result := 3;
else
Result := 0;
end;
end;
function IntToAlign(Value: Integer): TAlign;
begin
case Value of
0: Result := alLeft;
1: Result := alTop;
2: Result := alRight;
3: Result := alBottom;
else
Result := alLeft;
end;
end;
{ TDesignNotification }
function GetFmxVclHost(Obj: TFmxObject): TWinControl;
var
ctx: TRttiContext;
typ: TRttiType;
fld: TRttiField;
begin
Result := nil;
if Obj = nil then Exit;
while Obj.Parent <> nil do
Obj := Obj.Parent;
if not (Obj is FMXFormContainer.TFormContainerForm) then Exit;
typ := ctx.GetType(FMXFormContainer.TFormContainerForm);
if typ = nil then Exit;
fld := typ.GetField('FVclHost');
if fld = nil then Exit;
Result := TWinControl(fld.GetValue(Obj).AsObject);
end;
function GetComponentTrayByItem(AItem: TPersistent): TComponentTray;
var
editWindow: TWinControl;
vclhost: TWinControl;
begin
Result := nil;
if not IsNonVisualComponent(AItem) then Exit;
if TComponent(AItem).Owner = nil then Exit;
if TComponent(AItem).Owner is TWinControl then
begin
editWindow := GetEditWindow(TWinControl(TComponent(AItem).Owner));
if editWindow = nil then Exit;
Result := GetComponentTray(editWindow);
end
else if TComponent(AItem).Owner is TFmxObject then
begin
vclhost := GetFmxVclHost(TFmxObject(TComponent(AItem).Owner));
if vclhost <> nil then
begin
editWindow := GetEditWindow(vclhost);
if editWindow <> nil then
Result := GetComponentTray(editWindow);
end;
end;
end;
function GetComponentTrayByDesigner(ADesigner: IDesigner): TComponentTray;
var
comp: TComponent;
editWindow: TWinControl;
vclhost: TWinControl;
begin
Result := nil;
if not Assigned(ADesigner) then Exit;
comp := ADesigner.Root;
if not Assigned(comp) then Exit;
if comp is TWinControl then
begin
editWindow := GetEditWindow(TWinControl(comp));
if editWindow <> nil then
Result := GetComponentTray(editWindow);
end
else if comp is TFmxObject then
begin
vclhost := GetFmxVclHost(TFmxObject(comp));
if vclhost <> nil then
begin
editWindow := GetEditWindow(vclhost);
if editWindow <> nil then
Result := GetComponentTray(editWindow);
end;
end;
end;
procedure TDesignNotification.ItemDeleted(const ADesigner: IDesigner; AItem: TPersistent);
var
componentTray: TComponentTray;
begin
if FComponentDeleting then Exit;
if not IsNonVisualComponent(AItem) then Exit;
componentTray := GetComponentTrayByItem(AItem);
if componentTray = nil then Exit;
componentTray.RemoveItem(AItem);
end;
procedure TDesignNotification.ItemInserted(const ADesigner: IDesigner; AItem: TPersistent);
var
componentTray: TComponentTray;
begin
if not IsNonVisualComponent(AItem) then Exit;
componentTray := GetComponentTrayByItem(AItem);
if componentTray = nil then Exit;
componentTray.AddItem(AItem);
HideNonVisualComponents;
end;
procedure TDesignNotification.ItemsModified(const ADesigner: IDesigner);
var
componentTray: TComponentTray;
begin
componentTray := GetComponentTrayByDesigner(ADesigner);
if componentTray = nil then Exit;
componentTray.UpdateCaptions;
HideNonVisualComponents;
end;
procedure TDesignNotification.SelectionChanged(const ADesigner: IDesigner;
const ASelection: IDesignerSelections);
var
tray: TComponentTray;
begin
if FComponentDeleting or FComponentSelecting then Exit;
tray := GetComponentTrayByDesigner(ADesigner);
if tray = nil then Exit;
tray.UpdateSelection(ASelection);
end;
procedure TDesignNotification.DesignerOpened(const ADesigner: IDesigner; AResurrecting: Boolean);
begin
{ Do nothing }
end;
procedure TDesignNotification.DesignerClosed(const ADesigner: IDesigner; AGoingDormant: Boolean);
begin
{ Do nothing }
end;
{ TComponentEditorMenuItem }
constructor TComponentEditorMenuItem.Create(AOwner: TComponent;
AComponentEditor: IComponentEditor; AVerbIndex: Integer);
var
wrapper: IMenuItem;
begin
inherited Create(AOwner);
FComponentEditor := AComponentEditor;
FVerbIndex := AVerbIndex;
Caption := FComponentEditor.GetVerb(FVerbIndex);
wrapper := TMenuItemWrapper.Create(Self);
FComponentEditor.PrepareItem(FVerbIndex, wrapper);
end;
procedure TComponentEditorMenuItem.Click;
begin
inherited;
if Enabled then
begin
if not Assigned(FComponentEditor) then Exit;
if (FVerbIndex < 0) or (FVerbIndex >= FComponentEditor.GetVerbCount) then Exit;
FComponentEditor.ExecuteVerb(FVerbIndex);
FComponentEditor := nil;
FVerbIndex := -1;
end;
end;
{ TSelectionEditorMenuItem }
constructor TSelectionEditorMenuItem.Create(AOwner: TComponent;
ASelectionEditor: ISelectionEditor; AVerbIndex: Integer;
ASelections: IDesignerSelections);
var
wrapper: IMenuItem;
begin
inherited Create(AOwner);
FSelectionEditor := ASelectionEditor;
FVerbIndex := AVerbIndex;
FSelections := ASelections;
Caption := FSelectionEditor.GetVerb(FVerbIndex);
wrapper := TMenuItemWrapper.Create(Self);
FSelectionEditor.PrepareItem(FVerbIndex, wrapper);
end;
procedure TSelectionEditorMenuItem.Click;
begin
if Enabled then
begin
if not Assigned(FSelectionEditor) then Exit;
if (FVerbIndex < 0) or (FVerbIndex >= FSelectionEditor.GetVerbCount) then Exit;
if not Assigned(FSelections) then Exit;
FSelectionEditor.ExecuteVerb(FVerbIndex, FSelections);
FSelectionEditor := nil;
FVerbIndex := -1;
FSelections := nil;
end;
end;
{ TOTAPaletteDragAcceptor }
constructor TOTAPaletteDragAcceptor.Create(AControl: TComponentTray);
begin
inherited Create;
FControl := AControl;
end;
function TOTAPaletteDragAcceptor.GetHandle: THandle;
begin
RevokeDragDrop(FControl.Handle);
Result := FControl.Handle;
RegisterDragDrop(FControl.Handle, FControl);
end;
{ TComponentTray }
constructor TComponentTray.Create(AOwner: TComponent);
begin
inherited;
Align := alLeft;
Height := 80;
Width := 120;
Parent := TWinControl(AOwner);
FTypes := TDictionary<TClass,TTypeData>.Create;
FListView := TListView.Create(Self);
FListView.BorderStyle := bsNone;
FListView.IconOptions.AutoArrange := True;
FListView.IconOptions.Arrangement := iaTop;
FListView.PopupMenu := TComponentPopupMenu.Create(Self);
FListView.ViewStyle := vsSmallIcon;
FListView.ReadOnly := True;
FListView.MultiSelect := True;
FListView.Parent := Self;
FListView.Align := alClient;
FListView.LargeImages := FCompImageList.ImageList;
FListView.SmallImages := FCompImageList.ImageList;
FListView.OnKeyDown := ListViewKeyDown;
FListView.OnMouseDown := ListViewMouseDown;
FListView.OnDblClick := ListViewDblClick;
FListView.OnSelectItem := ListViewSelect;
FListView.OnContextPopup := ListViewContextPopup;
FListView.SortType := stData;
FListView.OnCompare := ListViewCompareCreationOrder;
FSortType := 0;
FSplitter := TSplitter.Create(Self);
FSplitter.Align := alLeft;
FSplitter.ResizeStyle := rsPattern;
FSplitter.Color := clBackground;
FSplitter.Parent := Parent;
FSplitter.OnMoved := SplitterMoved;
FAcceptor := TOTAPaletteDragAcceptor.Create(Self);
FAcceptorIndex := (BorlandIDEServices as IOTAPaletteServices).RegisterDragAcceptor(FAcceptor);
LoadSettings;
end;
destructor TComponentTray.Destroy;
begin
if FAcceptorIndex >= 0 then
(BorlandIDEServices as IOTAPaletteServices).UnRegisterDragAcceptor(FAcceptorIndex);
FAcceptor := nil;
FTypes.Free;
inherited;
end;
procedure TComponentTray.LoadSettings;
var
ini: TIniFile;
begin
ini := TIniFile.Create(ChangeFileExt(GetModuleName(HInstance), '.ini'));
try
FListView.ViewStyle := IntToViewStyle(ini.ReadInteger('Settings', 'Style', 1));
ChangeAlign(IntToAlign(ini.ReadInteger('Settings', 'Position', 0)));
FSplitter.Enabled := ini.ReadBool('Settings', 'SplitterEnabled', FSplitter.Enabled);
FSplitter.Color := ini.ReadInteger('Settings', 'SplitterColor', Integer(FSplitter.Color));
FSortType := ini.ReadInteger('Settings', 'SortType', FSortType);
if (FSortType < 0) or (FSortType > 2) then
FSortType := 0;
Width := ini.ReadInteger('Settings', 'Width', 120);
Height := ini.ReadInteger('Settings', 'Height', 80);
finally
ini.Free;
end;
end;
procedure TComponentTray.SaveSettings;
var
ini: TIniFile;
begin
ini := TIniFile.Create(ChangeFileExt(GetModuleName(HInstance), '.ini'));
try
ini.WriteInteger('Settings', 'Style', ViewStyleToInt(FListView.ViewStyle));
ini.WriteInteger('Settings', 'Position', AlignToInt(Align));
ini.WriteBool('Settings', 'SplitterEnabled', FSplitter.Enabled);
ini.WriteInteger('Settings', 'SplitterColor', Integer(FSplitter.Color));
ini.WriteInteger('Settings', 'SortType', FSortType);
ini.WriteInteger('Settings', 'Width', Width);
ini.WriteInteger('Settings', 'Height', Height);
finally
ini.Free;
end;
end;
class procedure TComponentTray.UpdateTrays(Style, Position: Integer;
SplitterEnabled: Boolean; SplitterColor: TColor);
var
i: Integer;
begin
for i := 0 to FTrays.Count-1 do
begin
FTrays[i].FListView.ViewStyle := IntToViewStyle(Style);
FTrays[i].ChangeAlign(IntToAlign(Position));
FTrays[i].FSplitter.Enabled := SplitterEnabled;
FTrays[i].FSplitter.Color := SplitterColor;
end;
end;
procedure TComponentTray.AddItem(AItem: TPersistent);
var
li: TListItem;
data: TTypeData;
begin
if not IsNonVisualComponent(AItem) then Exit;
if TComponent(AItem).Owner = nil then Exit;
if TComponent(AItem).HasParent then
begin
if ActiveRoot = nil then Exit;
if TComponent(AItem).GetParentComponent = nil then Exit;
if ActiveRoot.Root <> TComponent(AItem).GetParentComponent then Exit;
end;
// Ignore item that is not on current view
if ActiveRoot.Root <> TComponent(AItem).Owner then Exit;
if not FTypes.TryGetValue(AItem.ClassType, data) then
begin
data.&Type := AItem.ClassType;
data.Count := 0;
data.Visible := True;
end;
Inc(data.Count);
FTypes.AddOrSetValue(AItem.ClassType, data);
// Filter
if FTypes.TryGetValue(AItem.ClassType, data) then
if not data.Visible then Exit;
li := FListView.Items.Add;
li.Caption := TComponent(AItem).Name;
li.ImageIndex := FCompImageList.AddOrGet(AItem.ClassType);
li.Data := AItem;
end;
procedure TComponentTray.RemoveItem(AItem: TPersistent);
var
i: Integer;
data: TTypeData;
begin
if not IsNonVisualComponent(AItem) then Exit;
if TComponent(AItem).HasParent then Exit;
for i := 0 to FListView.Items.Count-1 do
begin
if FListView.Items[i].Data = AItem then
begin
FListView.Items[i].Delete;
Break;
end;
end;
if FTypes.TryGetValue(AItem.ClassType, data) then
begin
Dec(data.Count);
if data.Count = 0 then
FTypes.Remove(AItem.ClassType)
else
FTypes[AItem.ClassType] := data;
end;
end;
procedure TComponentTray.UpdateCaptions;
var
i: Integer;
begin
for i := 0 to FListView.Items.Count-1 do
FListView.Items[i].Caption := TComponent(FListView.Items[i].Data).Name;
Sort;
end;
procedure TComponentTray.UpdateItems(DoReplace: Boolean = False);
var
root: IRoot;
i: Integer;
comp: TComponent;
tmp: TWinControl;
cls: TClass;
data: TTypeData;
begin
FListView.Clear;
if not DoReplace then
begin
for cls in FTypes.Keys do
begin
data := FTypes[cls];
data.Count := 0;
FTypes[cls] := data;
end;
end
else
FTypes.Clear;
root := ActiveRoot;
if root = nil then Exit;
// Disable when container is TDataModule
if root.Root is TDataModule then
begin
Hide;
Exit;
end;
if DoReplace then
begin
// Insert after ViewSelector at FMX environment
tmp := Parent;
Parent := nil;
Parent := tmp;
FSplitter.Parent := nil;
FSplitter.Parent := tmp;
ChangeAlign(Align);
end;
HideNonVisualComponents;
Show;
for i := 0 to root.Root.ComponentCount-1 do
begin
comp := root.Root.Components[i];
AddItem(comp);
end;
for cls in FTypes.Keys do
begin
if FTypes[cls].Count = 0 then
FTypes.Remove(cls);
end;
Sort;
end;
procedure TComponentTray.UpdateSelection(const ASelection: IDesignerSelections);
function Contains(AObj: TObject): Boolean;
var
i: Integer;
begin
for i := 0 to ASelection.Count-1 do
if ASelection[i] = AObj then Exit(True);
Result := False;
end;
var
i: Integer;
begin
if ASelection.Count = 0 then
begin
FListView.ClearSelection;
Exit;
end;
FListView.OnSelectItem := nil;
try
for i := 0 to FListView.Items.Count-1 do
FListView.Items[i].Selected := Contains(TObject(FListView.Items[i].Data));
finally
FListView.OnSelectItem := ListViewSelect;
end;
end;
procedure TComponentTray.ChangeAlign(AValue: TAlign);
var
oldAlign: TAlign;
begin
oldAlign := Align;
Align := AValue;
FSplitter.Align := AValue;
if ((oldAlign in [alLeft, alRight]) and (Align in [alTop, alBottom]))
or ((oldAlign in [alTop, alBottom]) and (Align in [alLeft, alRight])) then
begin
case Align of
alLeft, alRight:
begin
Width := 120;
FSplitter.Width := 3;
end;
alTop, alBottom:
begin
Height := 80;
FSplitter.Height := 3;
end;
end;
end;
case FSplitter.Align of
alLeft: FSplitter.Left := Self.Left + Self.Width;
alTop: FSplitter.Top := Self.Top + Self.Height;
alRight: FSplitter.Left := Self.Left;
alBottom: FSplitter.Top := Self.Top;
end;
FListView.Align := alNone;
FListView.Align := alClient;
end;
procedure TComponentTray.Sort(SortType: Integer = -1);
begin
if (SortType >= 0) and (SortType <= 2) then
begin
FSortType := SortType;
case FSortType of
0: FListView.OnCompare := ListViewCompareCreationOrder;
1: FListView.OnCompare := ListViewCompareName;
2: FListView.OnCompare := ListViewCompareType;
end;
end;
FListView.AlphaSort;
end;
procedure TComponentTray.CreateWnd;
begin
inherited;
RegisterDragDrop(Handle, Self);
end;
procedure TComponentTray.DestroyWnd;
begin
RevokeDragDrop(Handle);
inherited;
end;
procedure TComponentTray.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent is TComponentTray) then
begin
FTrays.Extract(TComponentTray(AComponent));
end;
end;
procedure TComponentTray.ListViewKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
// Enable shortcuts
TComponentPopupMenu(FListView.PopupMenu).BuildContextMenu;
if (Key = VK_DELETE) and (Shift = []) then
begin
if ActiveRoot = nil then Exit;
if FListView.SelCount = 0 then Exit;
Key := 0;
FListView.OnSelectItem := nil;
try
(ActiveRoot as IEditHandler).EditAction(eaDelete);
finally
FListView.OnSelectItem := ListViewSelect;
end;
end;
end;
procedure TComponentTray.ListViewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
paletteServices: IOTAPaletteServices;
begin
if Button <> mbLeft then Exit;
paletteServices := BorlandIDEServices as IOTAPaletteServices;
if paletteServices.SelectedTool = nil then Exit;
FListView.OnSelectItem := nil;
try
paletteServices.SelectedTool.Execute;
paletteServices.SelectedTool := nil;
HideNonVisualComponents;
finally
FListView.OnSelectItem := ListViewSelect;
end;
end;
procedure TComponentTray.ListViewDblClick(Sender: TObject);
begin
if FListView.ItemIndex = -1 then Exit;
if ActiveRoot = nil then Exit;
(ActiveRoot as IInternalRoot).Edit(TComponent(FListView.Items[FListView.ItemIndex].Data));
end;
procedure TComponentTray.ListViewSelect(Sender: TObject; Item: TListItem;
Selected: Boolean);
var
designer: IDesigner;
selections: IDesignerSelections;
i: Integer;
begin
designer := ActiveRoot as IDesigner;
if designer = nil then Exit;
selections := CreateSelectionList;
for i := 0 to FListView.Items.Count-1 do
if FListView.Items[i].Selected then
selections.Add(TPersistent(FListView.Items[i].Data));
FComponentSelecting := True;
try
designer.SetSelections(selections);
finally
FComponentSelecting := False;
end;
end;
procedure TComponentTray.ListViewContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
begin
TComponentPopupMenu(FListView.PopupMenu).BuildContextMenu;
end;
procedure TComponentTray.ListViewCompareCreationOrder(Sender: TObject;
Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
var
idx1, idx2: Integer;
begin
idx1 := TComponent(Item1.Data).ComponentIndex;
idx2 := TComponent(Item2.Data).ComponentIndex;
Compare := idx1 - idx2;
end;
procedure TComponentTray.ListViewCompareName(Sender: TObject;
Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
begin
Compare := CompareText(TComponent(Item1.Data).Name, TComponent(Item2.Data).Name);
end;
procedure TComponentTray.ListViewCompareType(Sender: TObject;
Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
begin
Compare := CompareText(TComponent(Item1.Data).ClassName, TComponent(Item2.Data).ClassName);
if Compare = 0 then
Compare := CompareText(TComponent(Item1.Data).Name, TComponent(Item2.Data).Name);
end;
procedure TComponentTray.SplitterMoved(Sender: TObject);
begin
SaveSettings;
end;
function TComponentTray.DropTarget_DragEnter(const dataObj: IDataObject;
grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult;
var
getPaletteItem: IOTAGetPaletteItem;
paletteDragDropOp: IOTAPaletteDragDropOp;
componentPaletteItem: IOTAComponentPaletteItem;
ctx: TRttiContext;
typ: TRttiType;
begin
FDragAllowed := False;
Result := S_OK;
dwEffect := DROPEFFECT_NONE;
if not Supports(dataObj, IOTAGetPaletteItem, getPaletteItem) then Exit;
if not Supports(getPaletteItem.GetPaletteItem, IOTAPaletteDragDropOp, paletteDragDropOp) then Exit;
if not Supports(getPaletteItem.GetPaletteItem, IOTAComponentPaletteItem, componentPaletteItem) then Exit;
typ := ctx.FindType(componentPaletteItem.UnitName + '.' + componentPaletteItem.ClassName);
if typ = nil then Exit;
if not (typ is TRttiInstanceType) then Exit;
if not IsNonVisualComponent(TRttiInstanceType(typ).MetaclassType) then Exit;
dwEffect := DROPEFFECT_COPY;
FDragAllowed := True;
end;
function TComponentTray.DropTarget_DragOver(grfKeyState: Longint; pt: TPoint;
var dwEffect: Longint): HResult;
begin
Result := S_OK;
if FDragAllowed then
dwEffect := DROPEFFECT_COPY
else
dwEffect := DROPEFFECT_NONE;
end;
function TComponentTray.DropTarget_DragLeave: HResult;
begin
Result := S_OK;
FDragAllowed := False;
end;
function TComponentTray.DropTarget_Drop(const dataObj: IDataObject; grfKeyState: Longint;
pt: TPoint; var dwEffect: Longint): HResult;
var
getPaletteItem: IOTAGetPaletteItem;
begin
Result := S_OK;
dwEffect := DROPEFFECT_NONE;
try
if not FDragAllowed then Exit;
if Supports(dataObj, IOTAGetPaletteItem, getPaletteItem) then
begin
getPaletteItem.GetPaletteItem.Execute;
dwEffect := DROPEFFECT_COPY;
end;
ActiveDesigner.Environment.ResetCompClass;
finally
FDragAllowed := False;
end;
end;
{ TComponentPopupMenu }
constructor TComponentPopupMenu.Create(AOwner: TComponent);
function NewRadioItem(const ACaption: string; AChecked: Boolean;
AOnClick: TNotifyEvent; const AName: string): TMenuItem;
begin
Result := NewItem(ACaption, 0, AChecked, True, AOnClick, 0, AName);
Result.RadioItem := True;
Result.AutoCheck := True;
end;
begin
inherited;
FMenuLine := NewLine;
Items.Add(FMenuLine);
{$IFDEF DEBUG}
Items.Add(NewItem('&Test', 0, False, True, TestClick, 0, 'mnuNVCBTest'));
{$ENDIF}
mnuNVCBFilter := NewItem('&Filter', 0, False, True, nil, 0, 'mnuNVCBFilter');
Items.Add(mnuNVCBFilter);
mnuNVCBSort := NewItem('S&ort', 0, False, True, nil, 0, 'mnuNVCBSort');
Items.Add(mnuNVCBSort);
mnuNVCBSort.Add(NewRadioItem('Sort by &Creation Order', True, SortClick, 'mnuNVCBSortByCreationOrder'));
mnuNVCBSort.Add(NewRadioItem('Sort by &Name', False, SortClick, 'mnuNVCBSortByName'));
mnuNVCBSort.Add(NewRadioItem('Sort by &Type', False, SortClick, 'mnuNVCBSortByType'));
Items.Add(NewLine);
Items.Add(NewItem('&Settings', 0, False, True, SettingsClick, 0, 'mnuNVCBSettings'));
end;
procedure TComponentPopupMenu.BuildContextMenu;
var
selections: IDesignerSelections;
selectionEditorList: ISelectionEditorList;
i, j, insertPos: Integer;
componentEditor: IComponentEditor;
menuitem: TMenuItem;
data: TTypeData;
types: TList<TTypeData>;
begin
// Remove menus that were added dynamicaly
while FMenuLine.MenuIndex > 0 do
Items.Delete(0);
if ActiveRoot = nil then Exit;
insertPos := 0;
selections := CreateSelectionList;
(ActiveRoot as IDesigner).GetSelections(selections);
// Component menu
if selections.Count = 1 then
begin
componentEditor := GetComponentEditor(TComponent(selections[0]), ActiveRoot as IDesigner);
for i := 0 to componentEditor.GetVerbCount-1 do
begin
menuitem := TComponentEditorMenuItem.Create(Self, componentEditor, i);
Items.Insert(insertPos, menuitem);
Inc(insertPos);
end;
Items.Insert(insertPos, Vcl.Menus.NewLine);
Inc(insertPos);
end;
// Selection menus
selectionEditorList := GetSelectionEditors(ActiveRoot as IDesigner, selections);
if selectionEditorList = nil then Exit;
for i := 0 to selectionEditorList.Count-1 do
begin
for j := 0 to selectionEditorList[i].GetVerbCount-1 do
begin
menuitem := TSelectionEditorMenuItem.Create(Self, selectionEditorList[i], j, selections);
Items.Insert(insertPos, menuitem);
Inc(insertPos);
end;
end;
mnuNVCBFilter.Clear;
mnuNVCBFilter.Visible := TComponentTray(Owner).FTypes.Count > 0;
if mnuNVCBFilter.Visible then
begin
types := TList<TTypeData>.Create;
try
for data in TComponentTray(Owner).FTypes.Values do
types.Add(data);
types.Sort(TComparer<TTypeData>.Construct(
function(const Left, Right: TTypeData): Integer
begin
Result := CompareText(Left.&Type.ClassName, Right.&Type.ClassName);
end));
for i := 0 to types.Count-1 do
begin
menuitem := NewItem(types[i].&Type.ClassName, 0, types[i].Visible, True, FilterClick, 0, '');
menuitem.Tag := NativeInt(types[i].&Type);
mnuNVCBFilter.Add(menuitem);
end;
finally
types.Free;
end;
mnuNVCBFilter.Add(NewLine);
mnuNVCBFilter.Add(NewItem('&Check All', 0, False, True, FilterCheckAllClick, 0, 'mnuNVCBFilterCheckAll'));
mnuNVCBFilter.Add(NewItem('&Uncheck All', 0, False, True, FilterUncheckAllClick, 0, 'mnuNVCBFilterUncheckAll'));
end;
mnuNVCBSort[TComponentTray(Owner).FSortType].Checked := True;
end;
{$IFDEF DEBUG}
procedure TComponentPopupMenu.TestClick(Sender: TObject);
begin
end;
{$ENDIF}
procedure TComponentPopupMenu.FilterClick(Sender: TObject);
var
cls: TClass;
data: TTypeData;
begin
cls := TClass(TMenuItem(Sender).Tag);
if TComponentTray(Owner).FTypes.TryGetValue(cls, data) then
begin
data.Visible := not data.Visible;
TComponentTray(Owner).FTypes[cls] := data;
TComponentTray(Owner).UpdateItems(False);
end;
end;
procedure TComponentPopupMenu.FilterCheckAllClick(Sender: TObject);
var
cls: TClass;
data: TTypeData;
begin
for cls in TComponentTray(Owner).FTypes.Keys do
begin
data := TComponentTray(Owner).FTypes[cls];
data.Visible := True;
TComponentTray(Owner).FTypes[cls] := data;
end;
TComponentTray(Owner).UpdateItems(False);
end;
procedure TComponentPopupMenu.FilterUncheckAllClick(Sender: TObject);
var
cls: TClass;
data: TTypeData;
begin
for cls in TComponentTray(Owner).FTypes.Keys do
begin
data := TComponentTray(Owner).FTypes[cls];
data.Visible := False;
TComponentTray(Owner).FTypes[cls] := data;
end;
TComponentTray(Owner).UpdateItems(False);
end;
procedure TComponentPopupMenu.SortClick(Sender: TObject);
begin
TComponentTray(Owner).Sort(TMenuItem(Sender).MenuIndex);
TComponentTray(Owner).SaveSettings;
end;
procedure TComponentPopupMenu.SettingsClick(Sender: TObject);
var
style, position: Integer;
splitterEnabled: Boolean;
splitterColor: TColor;
begin
style := ViewStyleToInt(TComponentTray(Owner).FListView.ViewStyle);
position := AlignToInt(TComponentTray(Owner).Align);
splitterEnabled := TComponentTray(Owner).FSplitter.Enabled;
splitterColor := TComponentTray(Owner).FSplitter.Color;
if ShowSettingsDlg(style, position, splitterEnabled, splitterColor) then
begin
TComponentTray.UpdateTrays(style, position, splitterEnabled, splitterColor);
TComponentTray(Owner).SaveSettings;
end;
end;
{ TComponentImageList }
constructor TComponentImageList.Create;
begin
FImageList := TImageList.Create(nil);
FImageList.Width := 24;
FImageList.Height := 24;
FImageList.DrawingStyle := dsTransparent;
FImageDict := TDictionary<TClass,Integer>.Create;
end;
destructor TComponentImageList.Destroy;
begin
FImageList.Free;
FImageDict.Free;
inherited;
end;
function TComponentImageList.AddOrGet(AClass: TClass): Integer;
const
DEFAULT_ICON_NAME = 'DEFAULT24';
type
TData = record
Name: string;
HInstance: THandle;
end;
PData = ^TData;
var
cls: TClass;
function EnumModuleProc(HInstance: NativeInt; Data: PData): Boolean;
begin
Result := True;
if FindResource(HInstance, PChar(Data^.Name), RT_BITMAP) <> 0 then
begin
Data^.HInstance := HInstance;
Result := False;
end;
end;
procedure SmoothResize(aBmp: TBitmap; NuWidth, NuHeight: Integer);
type
TRGBArray = array[Word] of TRGBTriple;
pRGBArray = ^TRGBArray;
var
X, Y: Integer;
xP, yP: Integer;
xP2, yP2: Integer;
SrcLine1, SrcLine2: pRGBArray;
t3: Integer;
z, z2, iz2: Integer;
DstLine: pRGBArray;
DstGap: Integer;
w1, w2, w3, w4: Integer;
Dst: TBitmap;
begin
if (aBmp.Width = NuWidth) and (aBmp.Height = NuHeight) then
Exit;
aBmp.PixelFormat := pf24Bit;
Dst := TBitmap.Create;
Dst.PixelFormat := pf24Bit;
Dst.Width := NuWidth;
Dst.Height := NuHeight;
DstLine := Dst.ScanLine[0];
DstGap := Integer(Dst.ScanLine[1]) - Integer(DstLine);
xP2 := MulDiv(aBmp.Width - 1, $10000, Dst.Width);
yP2 := MulDiv(aBmp.Height - 1, $10000, Dst.Height);
yP := 0;
for Y := 0 to Dst.Height - 1 do
begin
xP := 0;
SrcLine1 := aBmp.ScanLine[yP shr 16];
if (yP shr 16 < aBmp.Height - 1) then
SrcLine2 := aBmp.ScanLine[Succ(yP shr 16)]
else
SrcLine2 := aBmp.ScanLine[yP shr 16];
z2 := Succ(yP and $FFFF);
iz2 := Succ((not yP) and $FFFF);
for X := 0 to Dst.Width - 1 do
begin
t3 := xP shr 16;
z := xP and $FFFF;
w2 := MulDiv(z, iz2, $10000);
w1 := iz2 - w2;
w4 := MulDiv(z, z2, $10000);
w3 := z2 - w4;
DstLine[X].rgbtRed :=
(SrcLine1[t3].rgbtRed * w1 + SrcLine1[t3 + 1].rgbtRed * w2 +
SrcLine2[t3].rgbtRed * w3 + SrcLine2[t3 + 1].rgbtRed * w4) shr 16;
DstLine[X].rgbtGreen :=
(SrcLine1[t3].rgbtGreen * w1 + SrcLine1[t3 + 1].rgbtGreen * w2 +
SrcLine2[t3].rgbtGreen * w3 + SrcLine2[t3 + 1].rgbtGreen * w4) shr 16;
DstLine[X].rgbtBlue :=
(SrcLine1[t3].rgbtBlue * w1 + SrcLine1[t3 + 1].rgbtBlue * w2 +
SrcLine2[t3].rgbtBlue * w3 + SrcLine2[t3 + 1].rgbtBlue * w4) shr 16;
Inc(xP, xP2);
end;
Inc(yP, yP2);
DstLine := pRGBArray(Integer(DstLine) + DstGap);
end;
aBmp.Width := Dst.Width;
aBmp.Height := Dst.Height;
aBmp.Canvas.Draw(0, 0, Dst);
Dst.Free;
end;
function LoadIconImage(const Name: string): Integer;
var
bmp: TBitmap;
data: TData;
begin
data.Name := Name;
data.HInstance := 0;
EnumModules(TEnumModuleFunc(@EnumModuleProc), @data);
if data.HInstance <> 0 then
begin
bmp := TBitmap.Create;
try
bmp.LoadFromResourceName(data.HInstance, Name);
bmp.Transparent := True;
try
if (bmp.Width <> 24) or (bmp.Height <> 24) then
SmoothResize(bmp, 24, 24);
Result := FImageList.AddMasked(bmp, bmp.Canvas.Pixels[0, bmp.Height-1]);
except
Result := -1;
end;
Exit;
finally
bmp.Free;
end;
end;
Result := -1;
end;
begin
Result := -1;
cls := AClass;
while cls <> nil do
begin
if FImageDict.TryGetValue(cls, Result) then
begin
if cls <> AClass then
FImageDict.Add(AClass, Result);
Exit;
end;
Result := LoadIconImage(cls.ClassName);
if Result <> -1 then
begin
FImageDict.Add(cls, Result);
if cls <> AClass then
FImageDict.Add(AClass, Result);
Exit;
end;
cls := cls.ClassParent;
end;
// Load default icon
if not FImageDict.TryGetValue(nil, Result) then
begin
Result := LoadIconImage(DEFAULT_ICON_NAME);
FImageDict.Add(nil, Result);
end;
FImageDict.Add(AClass, Result);
end;
{ Functions }
procedure EditorViewsChanged(Self, Sender: TObject; NewTabIndex: Integer; NewViewIndex: Integer);
var
viewBar: TTabSet;
componentTray: TComponentTray;
begin
if not (Sender is TComponent) then Exit;
viewBar := TTabSet(TComponent(Sender).FindComponent('ViewBar'));
if viewBar = nil then Exit;
if viewBar.TabIndex = -1 then Exit;
if NativeInt(viewBar.Tabs.Objects[viewBar.TabIndex]) <> 2 then Exit;
componentTray := GetComponentTray(TWinControl(Sender));
if componentTray = nil then Exit;
componentTray.UpdateItems(True);
end;
procedure AddTray(EditorFormDesigner: TEditorFormDesigner);
begin
FTrays.Add(TComponentTray.Create(EditorFormDesigner));
end;
procedure NewAfterConstruction(Self: TEditorFormDesigner);
begin
if Assigned(FOrgTEditorFormDesignerAfterConstruction) then
FOrgTEditorFormDesignerAfterConstruction(Self);
AddTray(Self);
end;
function CreateMethod(Code, Data: Pointer): TMethod;
begin
Result.Code := Code;
Result.Data := Data;
end;
function Patch(Addr: Pointer; Value: Pointer): Pointer;
var
oldProtect: DWORD;
begin
Result := PPointer(Addr)^;
VirtualProtect(Addr, SizeOf(Value), PAGE_READWRITE, oldProtect);
PPointer(Addr)^ := Value;
VirtualProtect(Addr, SizeOf(Value), oldProtect, nil);
FlushInstructionCache(GetCurrentProcess, Addr, SizeOf(Value));
end;
procedure NewShowNonVisualComponentsChange(Self: TObject; Sender: TObject{TPropField});
var
value: Variant;
begin
if Assigned(FShowNonVisualComponentsValueProp) then
begin
value := GetVariantProp(Sender, FShowNonVisualComponentsValueProp);
if value = True then
begin
// Force to hide non visual components
SetVariantProp(Sender, FShowNonVisualComponentsValueProp, False);
Exit;
end;
end;
if Assigned(FShowNonVisualComponentsChange) then
try
FShowNonVisualComponentsChange(Sender);
except
end;
end;
procedure Register;
const
sEditWindowList = '@Editorform@EditWindowList';
sEditorViewsChangedEvent = '@Editorform@evEditorViewsChangedEvent';
sTEditControlQualifiedName = 'EditorControl.TEditControl';
var
ctx: TRttiContext;
typ: TRttiType;
prop: TRttiProperty;
coreIdeName: string;
editWindowList: ^TList;
i: Integer;
editorFormDesigner: TEditorFormDesigner;
envOptions: TComponent;
propShowNonVisualComponents: TComponent;
method: TMethod;
function FindEditorFormDesigner(AControl: TWinControl): TEditorFormDesigner;
var
i: Integer;
begin
if AControl.ClassType = TEditorFormDesigner then
Exit(TEditorFormDesigner(AControl));
for i := 0 to AControl.ControlCount-1 do
if AControl.Controls[i] is TWinControl then
begin
Result := FindEditorFormDesigner(TWinControl(AControl.Controls[i]));
if Assigned(Result) then Exit;
end;
Result := nil;
end;
begin
FTrays := TObjectList<TComponentTray>.Create;
FCompImageList := TComponentImageList.Create;
{$WARN SYMBOL_DEPRECATED OFF}
@FOrgTEditorFormDesignerAfterConstruction := Patch(Pointer(PByte(TEditorFormDesigner) + vmtAfterConstruction), @NewAfterConstruction);
{$WARN SYMBOL_DEPRECATED ON}
coreIdeName := ExtractFileName(ctx.FindType(sTEditControlQualifiedName).Package.Name);
editWindowList := GetProcAddress(GetModuleHandle(PChar(coreIdeName)), sEditWindowList);
if editWindowList = nil then Exit;
if editWindowList^ = nil then Exit;
for i := 0 to editWindowList^.Count-1 do
begin
editorFormDesigner := FindEditorFormDesigner(TWinControl(editWindowList^[i]));
if Assigned(editorFormDesigner) then
AddTray(editorFormDesigner);
end;
FEditorViewsChangedEvent := GetProcAddress(GetModuleHandle(PChar(coreIdeName)), sEditorViewsChangedEvent);
if FEditorViewsChangedEvent = nil then Exit;
FEditorViewsChangedEvent^.Add(TNotifyEvent(CreateMethod(@EditorViewsChanged, nil)));
FDesignNotification := TDesignNotification.Create;
RegisterDesignNotification(FDesignNotification);
envOptions := Application.FindComponent('EnvironmentOptions');
if envOptions = nil then Exit;
propShowNonVisualComponents := envOptions.FindComponent('ShowNonVisualComponents');
if propShowNonVisualComponents = nil then Exit;
typ := ctx.GetType(propShowNonVisualComponents.ClassType);
if typ = nil then Exit;
prop := typ.GetProperty('Value');
if prop = nil then Exit;
FShowNonVisualComponentsValueProp := TRttiInstanceProperty(prop).PropInfo;
prop := typ.GetProperty('OnChange');
if prop = nil then Exit;
FShowNonVisualComponentsOnChangeProp := TRttiInstanceProperty(prop).PropInfo;
TMethod(FShowNonVisualComponentsChange) := GetMethodProp(propShowNonVisualComponents, FShowNonVisualComponentsOnChangeProp);
method := CreateMethod(@NewShowNonVisualComponentsChange, nil);
SetMethodProp(propShowNonVisualComponents, FShowNonVisualComponentsOnChangeProp, method);
{$IFDEF DEBUG}
OutputDebugString('Installed!');
{$ENDIF}
end;
procedure Unregister;
var
envOptions: TComponent;
propShowNonVisualComponents: TComponent;
method: TMethod;
begin
{$WARN SYMBOL_DEPRECATED OFF}
if Assigned(FOrgTEditorFormDesignerAfterConstruction) then
Patch(Pointer(PByte(TEditorFormDesigner) + vmtAfterConstruction), @FOrgTEditorFormDesignerAfterConstruction);
{$WARN SYMBOL_DEPRECATED ON}
if FEditorViewsChangedEvent <> nil then
begin
FEditorViewsChangedEvent^.Remove(TNotifyEvent(CreateMethod(@EditorViewsChanged, nil)));
end;
UnregisterDesignNotification(FDesignNotification);
if Assigned(FShowNonVisualComponentsChange) then
begin
envOptions := Application.FindComponent('EnvironmentOptions');
if envOptions <> nil then
begin
propShowNonVisualComponents := envOptions.FindComponent('ShowNonVisualComponents');
if (propShowNonVisualComponents <> nil) and (FShowNonVisualComponentsOnChangeProp <> nil) then
begin
method := TMethod(FShowNonVisualComponentsChange);
SetMethodProp(propShowNonVisualComponents, FShowNonVisualComponentsOnChangeProp, method);
end;
end;
end;
FTrays.Free;
FCompImageList.Free;
{$IFDEF DEBUG}
OutputDebugString('Uninstalled!');
{$ENDIF}
end;
initialization
finalization
Unregister;
end. |
unit UnitSettings;
{
OSS Mail Server v1.0.0 - Settings Form
The MIT License (MIT)
Copyright (c) 2012 Guangzhou Cloudstrust Software Development Co., Ltd
http://cloudstrust.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.
}
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.Layouts,
FMX.Objects, FMX.ListBox,
FMX.Gestures, FMX.TabControl, FMX.Ani, FMX.Edit, FMX.Menus;
type
TfrmSettings = class(TForm)
styleSettings: TStyleBook;
loToolbar: TLayout;
ppToolbar: TPopup;
ppToolbarAnimation: TFloatAnimation;
loSettings: TLayout;
loMenu: TLayout;
lbSettings: TListBox;
lbiOssSettings: TMetropolisUIListBoxItem;
lbiMailSettings: TMetropolisUIListBoxItem;
loMenuHeader: TLayout;
laMenuTitle: TLabel;
loBack: TLayout;
btnBack: TButton;
loParameters: TLayout;
tbSettings: TToolBar;
ToolbarApplyButton: TButton;
ToolbarCloseButton: TButton;
ToolbarAddButton: TButton;
tcSettings: TTabControl;
tiOss: TTabItem;
tiMail: TTabItem;
sbOss: TVertScrollBox;
loOssHeader: TLayout;
imgOssIcon: TImageControl;
loOssTitles: TLayout;
laOssTitle: TLabel;
laOssSubTitle: TLabel;
sbMail: TVertScrollBox;
loMailHeader: TLayout;
imgMailIcon: TImageControl;
loMailTitles: TLayout;
laMailTitle: TLabel;
laMailSubTitle: TLabel;
laOssHostname: TLabel;
laOssAccessId: TLabel;
edOssAccessId: TEdit;
laOssAccessKey: TLabel;
edOssAccessKey: TEdit;
ClearEditButton1: TClearEditButton;
ClearEditButton2: TClearEditButton;
pnOssValidate: TPanel;
btnOssValidate: TButton;
laMailHostname: TLabel;
edMailHostname: TEdit;
ClearEditButton3: TClearEditButton;
laMailBucket: TLabel;
laSMTPLogin: TLabel;
pnSMTPLogin: TPanel;
rbSMTPLoginOn: TRadioButton;
rbSMTPLoginOff: TRadioButton;
pnMailSave: TPanel;
btnMailSave: TButton;
cbOssHost: TComboBox;
pnOssValidateInfo: TPanel;
pnValidateError: TCalloutPanel;
lbValidateError: TLabel;
pnValidateProgress: TPanel;
aniValidateProgress: TAniIndicator;
lbValidateProgress: TLabel;
sbSettings: THorzScrollBox;
pnMailSaveSuccess: TCalloutPanel;
lbMailSaveSuccess: TLabel;
pnValidateSuccess: TCalloutPanel;
laValidateSuccess: TLabel;
cbMailBucket: TComboEdit;
ListBoxItem2: TListBoxItem;
ListBoxItem3: TListBoxItem;
procedure btnBackClick(Sender: TObject);
procedure FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
procedure FormGesture(Sender: TObject; const EventInfo: TGestureEventInfo;
var Handled: Boolean);
procedure FormKeyDown(Sender: TObject; var Key: Word; var KeyChar: Char;
Shift: TShiftState);
procedure FormActivate(Sender: TObject);
procedure ToolbarCloseButtonClick(Sender: TObject);
procedure lbiOssSettingsClick(Sender: TObject);
procedure btnOssValidateClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnMailSaveClick(Sender: TObject);
private
FGestureOrigin: TPointF;
FGestureInProgress: Boolean;
{ Private declarations }
procedure ShowToolbar(AShow: Boolean);
procedure ReadOss;
procedure WriteOss;
procedure ReadMail;
function ValidateMail: boolean;
procedure WriteMail;
procedure SyncBucketList;
procedure FlashAndDismiss(pn: TCalloutPanel);
public
{ Public declarations }
end;
var
frmSettings: TfrmSettings;
implementation
{$R *.fmx}
uses ALIOSS, UnitMain, Winapi.ShellAPI, Winapi.Windows, UnitMessage;
procedure SelectItem(cb: TComboEdit; item: string); overload;
var
idx: integer;
begin
if item = '' then
exit;
idx := cb.Items.IndexOf(item);
if idx = -1 then
begin
//item not found, set text
cb.Text := item;
end
else
cb.ItemIndex := idx;
end;
procedure SelectItem(cb: TComboBox; item: string); overload;
var
idx: integer;
begin
if item = '' then
exit;
idx := cb.Items.IndexOf(item);
if idx = -1 then
begin
//item not found, append and select it
cb.Items.Add(item);
cb.ItemIndex := cb.Items.Count - 1;
end
else
cb.ItemIndex := idx;
end;
procedure TfrmSettings.btnBackClick(Sender: TObject);
begin
Close;
end;
procedure TfrmSettings.lbiOssSettingsClick(Sender: TObject);
var
lb: TMetropolisUIListBoxItem;
begin
self.tcSettings.TabIndex := TFmxObject(Sender).Tag;
frmMain.SwitchIcon(lbiOssSettings, 'imgOssOff');
frmMain.SwitchIcon(lbiMailSettings, 'imgMailOff');
lb := Sender as TMetropolisUIListBoxItem;
if lb = self.lbiOssSettings then
frmMain.SwitchIcon(lb, 'imgOssOn')
else if lb = self.lbiMailSettings then
frmMain.SwitchIcon(lb, 'imgMailOn');
end;
procedure TfrmSettings.ReadMail;
begin
try
self.edMailHostname.Text := frmMain.IniData.MailHostname;
self.rbSMTPLoginOn.IsChecked := frmMain.IniData.MailSMTPLogin;
self.rbSMTPLoginOff.IsChecked := not frmMain.IniData.MailSMTPLogin;
SelectItem(self.cbMailBucket, frmMain.IniData.MailBucket);
except
end;
end;
procedure TfrmSettings.ReadOss;
begin
try
SelectItem(self.cbOssHost, frmMain.IniData.OssHostname);
self.edOssAccessId.Text := frmMain.IniData.AccessId;
self.edOssAccessKey.Text := frmMain.IniData.AccessKey;
except
end;
end;
procedure TfrmSettings.btnMailSaveClick(Sender: TObject);
var
ossfs: TAliOssFileSystem;
begin
if not self.ValidateMail then
begin
MessageDlg('提示', '保存邮件服务器配置失败,请检查配置。', '确定');
exit;
end;
if frmMain.CachedBuckets.IndexOf(self.cbMailBucket.Text) = -1 then
begin
if MessageDlg('提示', '指定的bucket“'+self.cbMailBucket.Text+'”不在列表中,是否在服务器创建?', '是', '否') = ID_YES then
begin
ossfs := TAliOssFileSystem.Create(frmMain.IniData.AccessId, frmMain.IniData.AccessKey, frmMain.IniData.OssHostname);
if ossfs.CreateVolumn(self.cbMailBucket.Text) then
MessageDlg('提示', '成功创建bucket“'+self.cbMailBucket.Text+'”。', '确定')
else
MessageDlg('提示', '创建bucket“'+self.cbMailBucket.Text+'”失败,请换个名字重试。', '确定')
end;
end;
self.WriteMail;
frmMain.SaveIniFile;
frmMain.LoadCachedBuckets;
self.SyncBucketList;
FlashAndDismiss(self.pnMailSaveSuccess);
if frmMain.pop3.Active or frmMain.smtp.Active then
begin
MessageDlg('提示', '检测到邮件服务器正在运行中,新的配置将在重新启动邮件服务器后生效。', '确定');
end;
end;
procedure TfrmSettings.btnOssValidateClick(Sender: TObject);
var
ossfs: TAliOssFileSystem;
success: boolean;
volumns: TAliOssVolumnInfoList;
begin
self.pnValidateSuccess.Opacity := 0.0;
self.pnValidateError.Opacity := 0.0;
self.pnValidateProgress.Opacity := 1.0;
success := true;
try
ossfs := TAliOssFileSystem.Create(self.edOssAccessId.Text, self.edOssAccessKey.Text, self.cbOssHost.Selected.Text);
if not ossfs.ListVolumns(volumns) then
success := false;
ossfs.Destroy;
except
success := false;
end;
self.pnValidateProgress.Opacity := 0.0;
if not success then
begin
FlashAndDismiss(self.pnValidateError);
end
else
begin
FlashAndDismiss(self.pnValidateSuccess);
self.WriteOss;
frmMain.SaveIniFile;
frmMain.LoadCachedBuckets(@volumns);
self.SyncBucketList;
end;
end;
procedure TfrmSettings.FlashAndDismiss(pn: TCalloutPanel);
begin
pn.AnimateFloat('Opacity', 1.0, 0.3);
pn.AnimateFloatDelay('Opacity', 0.0, 0.7, 3.0);
end;
procedure TfrmSettings.FormActivate(Sender: TObject);
begin
WindowState := TWindowState.wsMaximized;
tbSettings.BringToFront;
end;
procedure TfrmSettings.FormCreate(Sender: TObject);
begin
//general init
self.SyncBucketList;
//init oss settings
CopyBitmap(self.lbiOssSettings.Icon, frmMain.imgOssOn.Bitmap); //selected by default
self.pnValidateProgress.Opacity := 0.0;
self.pnValidateSuccess.Opacity := 0.0;
self.pnValidateError.Opacity := 0.0;
self.ReadOss;
//init mail settings
CopyBitmap(self.lbiMailSettings.Icon, frmMain.imgMailOff.Bitmap);
self.pnMailSaveSuccess.Opacity := 0.0;
self.rbSMTPLoginOn.IsChecked := true;
self.ReadMail;
end;
procedure TfrmSettings.FormGesture(Sender: TObject;
const EventInfo: TGestureEventInfo; var Handled: Boolean);
var
DX, DY : Single;
begin
if EventInfo.GestureID = igiPan then
begin
if (TInteractiveGestureFlag.gfBegin in EventInfo.Flags)
and ((Sender = ppToolbar)
or (EventInfo.Location.Y > (ClientHeight - 70))) then
begin
FGestureOrigin := EventInfo.Location;
FGestureInProgress := True;
end;
if FGestureInProgress and (TInteractiveGestureFlag.gfEnd in EventInfo.Flags) then
begin
FGestureInProgress := False;
DX := EventInfo.Location.X - FGestureOrigin.X;
DY := EventInfo.Location.Y - FGestureOrigin.Y;
if (Abs(DY) > Abs(DX)) then
ShowToolbar(DY < 0);
end;
end
end;
procedure TfrmSettings.FormKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkEscape then
Close;
end;
procedure TfrmSettings.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if Button = TMouseButton.mbRight then
ShowToolbar(True)
else
ShowToolbar(False);
end;
procedure TfrmSettings.WriteMail;
begin
try
frmMain.IniData.MailHostname := self.edMailHostname.Text;
frmMain.IniData.MailSMTPLogin := self.rbSMTPLoginOn.IsChecked;
frmMain.IniData.MailBucket := self.cbMailBucket.Text;
frmMain.AddLog('保存邮件服务器配置');
except
end;
end;
procedure TfrmSettings.WriteOss;
begin
try
frmMain.IniData.OssHostname := self.cbOssHost.Selected.Text;
frmMain.IniData.AccessId := self.edOssAccessId.Text;
frmMain.IniData.AccessKey := self.edOssAccessKey.Text;
frmMain.AddLog('保存阿里云OSS服务配置');
except
end;
end;
procedure TfrmSettings.ShowToolbar(AShow: Boolean);
begin
ppToolbar.Width := ClientWidth;
ppToolbar.PlacementRectangle.Rect := TRectF.Create(0, ClientHeight-ppToolbar.Height, ClientWidth-1, ClientHeight-1);
ppToolbarAnimation.StartValue := ppToolbar.Height;
ppToolbarAnimation.StopValue := 0;
ppToolbar.IsOpen := AShow;
end;
procedure TfrmSettings.SyncBucketList;
begin
self.cbMailBucket.Items.Clear;
self.cbMailBucket.Items.AddStrings(frmMain.CachedBuckets);
end;
procedure TfrmSettings.ToolbarCloseButtonClick(Sender: TObject);
begin
Close;
end;
function TfrmSettings.ValidateMail: boolean;
begin
result :=
(self.edMailHostname.Text <> '') and
(self.cbMailBucket.Text <> '')
end;
end.
|
unit diocp_ex_strObjectCoder;
interface
uses
diocp.coder.baseObject, diocp.tcp.server, Classes, SysUtils, utils.buffer;
type
TMessageHead = packed record
HEAD_FLAG : Word;
DATA_LEN : Integer;
RESERVE : array[0..7] of Byte; // 保留位
end;
PMessageHead = ^TMessageHead;
const
HEAD_SIZE = SizeOf(TMessageHead);
PACK_FLAG = $D10;
MAX_OBJECT_SIZE = 1024 * 1024 * 50; //最大对象大小 50M , 超过则会认为错误的包。
type
TStringObject = class(TObject)
private
FDataString: String;
public
property DataString: String read FDataString write FDataString;
end;
type
TDiocpStrObjectDecoder = class(TIOCPDecoder)
public
/// <summary>
/// 解码收到的数据,如果有接收到数据,调用该方法,进行解码
/// </summary>
/// <returns>
/// 返回解码好的对象
/// </returns>
/// <param name="inBuf"> 接收到的流数据 </param>
function Decode(const inBuf: TBufferLink; pvContext: TObject): TObject;
override;
end;
TDiocpStrObjectEncoder = class(TIOCPEncoder)
public
/// <summary>
/// 编码要发生的对象
/// </summary>
/// <param name="pvDataObject"> 要进行编码的对象 </param>
/// <param name="ouBuf"> 编码好的数据 </param>
procedure Encode(pvDataObject:TObject; const ouBuf: TBufferLink); override;
end;
function verifyData(const buf; len:Cardinal): Cardinal;
implementation
uses
utils.byteTools;
function verifyData(const buf; len: Cardinal): Cardinal;
var
i:Cardinal;
p:PByte;
begin
i := 0;
Result := 0;
p := PByte(@buf);
while i < len do
begin
Result := Result + p^;
Inc(p);
Inc(i);
end;
end;
function TDiocpStrObjectDecoder.Decode(const inBuf: TBufferLink; pvContext:
TObject): TObject;
var
lvValidCount, lvReadL:Integer;
lvHead :TMessageHead;
lvVerifyValue, lvVerifyDataValue:Cardinal;
lvBytes:TBytes;
begin
Result := nil;
//如果缓存中的数据长度不够包头长度,
lvValidCount := inBuf.validCount; //pack_flag + reserve(4) + len
if (lvValidCount < HEAD_SIZE) then
begin
Exit;
end;
//记录读取位置
inBuf.markReaderIndex;
inBuf.readBuffer(@lvHead, HEAD_SIZE);
if lvHead.HEAD_FLAG <> PACK_FLAG then
begin
//错误的包数据
Result := TObject(-1);
exit;
end;
if lvHead.DATA_LEN > 0 then
begin
//文件头不能过大
if lvHead.DATA_LEN > MAX_OBJECT_SIZE then
begin
Result := TObject(-1);
exit;
end;
if inBuf.validCount < lvHead.DATA_LEN then
begin
//返回buf的读取位置
inBuf.restoreReaderIndex;
exit;
end;
SetLength(lvBytes, lvHead.DATA_LEN + 1); // 留一个结束符
inBuf.readBuffer(@lvBytes[0], lvHead.DATA_LEN);
Result := TStringObject.Create;
TStringObject(Result).FDataString := Utf8ToAnsi(PAnsiChar(@lvBytes[0]));
end else
begin
Result := nil;
end;
end;
{ TDiocpStrObjectEncoder }
procedure TDiocpStrObjectEncoder.Encode(pvDataObject: TObject;
const ouBuf: TBufferLink);
var
lvDataLen:Integer;
lvHead :TMessageHead;
lvRawString:AnsiString;
begin
lvHead.HEAD_FLAG := PACK_FLAG;
lvRawString :=UTF8Encode(TStringObject(pvDataObject).FDataString);
lvDataLen := Length(lvRawString);
lvHead.DATA_LEN := lvDataLen;
if lvDataLen > MAX_OBJECT_SIZE then
begin
raise Exception.CreateFmt('数据包太大,请在业务层分拆发送,最大数据包[%d]!', [MAX_OBJECT_SIZE]);
end;
// HEAD
ouBuf.AddBuffer(@lvHead, HEAD_SIZE);
ouBuf.AddBuffer(PAnsiChar(lvRawString), lvDataLen);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ Copyright(c) 2014-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Datasnap.DSProviderDataModuleAdapter;
interface
uses
System.Types, Data.DBXCommon, Datasnap.DataBkr, Datasnap.DSReflect,
Datasnap.DSServer, System.Classes;
type
{ TDSProviderDataModuleAdapter }
TDSProviderDataModuleAdapter = class(TDSDataModuleAdapterClass)
private
FProviderDataModule: TProviderDataModule;
protected
function ExtractDataModule: TDataModule; override;
public
constructor Create(AdapteeInstance: TObject); override;
destructor Destroy; override;
// IAppServerFastCall interface methods.
//
function AS_ApplyUpdates(const ProviderName: OleStr; DeltaStream: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer; OwnerDataStream: TDBXStreamValue): OleVariant;
function AS_GetRecords(const ProviderName: OleStr; Count: Integer;
out RecsOut: Integer; Options: Integer; const CommandText: OleStr;
ParamReader: TDBXStreamValue; OwnerDataStream: TDBXStreamValue): OleVariant;
function AS_DataRequest(const ProviderName: OleStr;
DataStream: OleVariant): OleVariant;
function AS_GetParams(const ProviderName: OleStr;
OwnerDataStream: TDBXStreamValue): OleVariant;
function AS_RowRequest(const ProviderName: OleStr; RowStream: OleVariant;
RequestType: Integer; OwnerDataStream: TDBXStreamValue): OleVariant;
procedure AS_Execute(const ProviderName, CommandText: OleStr;
ParamReader: TDBXStreamValue; OwnerDataStream: TDBXStreamValue);
function AS_GetProviderNames: string;
property ProviderDataModule: TProviderDataModule read FProviderDataModule write FProviderDataModule;
end;
TDSServerModuleBase = class(TProviderDataModule)
public
procedure BeforeDestruction; override;
destructor Destroy; override;
end;
{$MethodInfo ON}
TDSServerModule = class(TDSServerModuleBase)
end;
{$MethodInfo OFF}
TDSProviderServerClassAdapter = class(TServerClassAdapter)
function CreateInstance(const Instance: TObject): TObject; override;
function IsSupportedAdapterType(const AObj: TObject): Boolean; override;
function IsSupportedType(const AObj: TObject): Boolean; overload; override;
function IsSupportedType(const AClass: TClass): Boolean; overload; override;
function GetType: TPersistentClass; override;
function GetDataModule(const AObj: TObject): TDataModule; override;
procedure ClearDataModule(const AObj: TObject); override;
end;
implementation
uses
Data.DSUtil, Datasnap.DSServerResStrs, System.SysUtils, System.Variants;
{ TDSProviderDataModuleAdapter }
constructor TDSProviderDataModuleAdapter.Create(AdapteeInstance: TObject);
begin
inherited Create(AdapteeInstance);
FProviderDataModule := AdapteeInstance as TProviderDataModule;
end;
destructor TDSProviderDataModuleAdapter.Destroy;
begin
FreeAndNil(FProviderDataModule);
inherited;
end;
function TDSProviderDataModuleAdapter.ExtractDataModule: TDataModule;
begin
Result := FProviderDataModule;
FProviderDataModule := nil;
end;
function TDSProviderDataModuleAdapter.AS_ApplyUpdates(
const ProviderName: OleStr; DeltaStream: OleVariant; MaxErrors: Integer;
out ErrorCount: Integer; OwnerDataStream: TDBXStreamValue): OleVariant;
var
Delta: OleVariant;
OwnerData: OleVariant;
begin
// Setup input parameters
OwnerData := OwnerDataStream.AsVariant;
Delta := DeltaStream;
Result := Unassigned;
// Invoke the IAppServer method
Result := FProviderDataModule.Providers[ProviderName].ApplyUpdates(
Delta, MaxErrors, ErrorCount, OwnerData);
// Assign output parameters
OwnerDataStream.AsVariant := OwnerData;
end;
function TDSProviderDataModuleAdapter.AS_DataRequest(
const ProviderName: OleStr; DataStream: OleVariant): OleVariant;
begin
// Invoke the IAppServer method
Result := FProviderDataModule.Providers[ProviderName].DataRequest(DataStream);
end;
procedure TDSProviderDataModuleAdapter.AS_Execute(const ProviderName,
CommandText: OleStr; ParamReader: TDBXStreamValue; OwnerDataStream: TDBXStreamValue);
var
Params: OleVariant;
OwnerData: OleVariant;
begin
// Setup input parameters
Params := ParamReader.AsVariant;
OwnerData := OwnerDataStream.AsVariant;
// Invoke the IAppServer method
FProviderDataModule.Providers[ProviderName].Execute(CommandText, Params, OwnerData);
// Assign output parameters
ParamReader.AsVariant := Params;
OwnerDataStream.AsVariant := OwnerData;
end;
function TDSProviderDataModuleAdapter.AS_GetParams(const ProviderName: OleStr;
OwnerDataStream: TDBXStreamValue): OleVariant;
var
Params: OleVariant;
OwnerData: OleVariant;
begin
// Setup input parameters
OwnerData := OwnerDataStream.AsVariant;
// Invoke the IAppServer method
Params := FProviderDataModule.Providers[ProviderName].GetParams(OwnerData);
// Assign output parameters
Result := Params;
OwnerDataStream.AsVariant := OwnerData;
end;
function TDSProviderDataModuleAdapter.AS_GetProviderNames: string;
var
List: TStringList;
Names: OleVariant;
begin
// Invoke the IAppServer method
Names := FProviderDataModule.ProviderNamesToVariant;
// Convert the OleVariant list of names into a comma delimited string
List := TStringList.Create;
try
List.StrictDelimiter := True;
VarArrayToStrings(Names, List);
Result := List.CommaText;
finally
List.Free;
end;
end;
function TDSProviderDataModuleAdapter.AS_GetRecords(const ProviderName: OleStr; Count: Integer;
out RecsOut: Integer; Options: Integer; const CommandText: OleStr;
ParamReader: TDBXStreamValue; OwnerDataStream: TDBXStreamValue): OleVariant;
var
Params: OleVariant;
OwnerData: OleVariant;
begin
// Setup input parameters
Params := ParamReader.AsVariant;
OwnerData := OwnerDataStream.AsVariant;
Result := Null;
// Invoke the IAppServer method
Result := FProviderDataModule.Providers[ProviderName].GetRecords(
Count, RecsOut, Options, CommandText, Params, OwnerData);
// Assign output parameters
ParamReader.AsVariant := Params;
OwnerDataStream.AsVariant := OwnerData;
end;
function TDSProviderDataModuleAdapter.AS_RowRequest(
const ProviderName: OleStr; RowStream: OleVariant; RequestType: Integer;
OwnerDataStream: TDBXStreamValue): OleVariant;
var
Row: OleVariant;
OwnerData: OleVariant;
begin
// Setup input parameters
Row := RowStream;
OwnerData := OwnerDataStream.AsVariant;
// Invoke the IAppServer method
Result := FProviderDataModule.Providers[ProviderName]
.RowRequest(Row, RequestType, OwnerData);
// Assign output parameters
OwnerDataStream.AsVariant := OwnerData;
end;
{ TDSServerModuleBase }
procedure TDSServerModuleBase.BeforeDestruction;
begin
inherited;
end;
destructor TDSServerModuleBase.Destroy;
begin
inherited;
end;
{ TDSProviderServerClassAdapter }
procedure TDSProviderServerClassAdapter.ClearDataModule(const AObj: TObject);
begin
TDSProviderDataModuleAdapter(AObj).FProviderDataModule := nil;
end;
function TDSProviderServerClassAdapter.CreateInstance(const Instance: TObject): TObject;
begin
Result := TDSProviderDataModuleAdapter.Create(Instance);
end;
function TDSProviderServerClassAdapter.GetDataModule(const AObj: TObject): TDataModule;
begin
if IsSupportedAdapterType(AObj) then
Result := TDSProviderDataModuleAdapter(AObj).ProviderDataModule
else
Result := nil;
end;
function TDSProviderServerClassAdapter.GetType: TPersistentClass;
begin
Result := TDSProviderDataModuleAdapter;
end;
function TDSProviderServerClassAdapter.IsSupportedType(const AObj: TObject): Boolean;
begin
Result := AObj.InheritsFrom(TProviderDataModule);
end;
function TDSProviderServerClassAdapter.IsSupportedType(const AClass: TClass): Boolean;
begin
Result := AClass.InheritsFrom(TProviderDataModule);
end;
function TDSProviderServerClassAdapter.IsSupportedAdapterType(const AObj: TObject): Boolean;
begin
Result := AObj is TDSProviderDataModuleAdapter;
end;
initialization
TServerClassAdapterFactory.RegisterAdapterClass(sProviderServerAdapter, TDSProviderServerClassAdapter);
end.
|
unit g_rockets;
interface
uses
OpenGL, g_class_gameobject, g_game_objects, u_math, u_sound, g_sounds;
type
TTrail = class (TGameObject)
Scale : Single;
procedure Move; override;
procedure Render; override;
procedure Death; override;
constructor Create;
end;
TSimpleRocket = class (TGameObject)
LockOn : TGameObject;
FiredBy : TGameObject;
TrailTime : Integer;
procedure Move; override;
procedure Render; Override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
TExtraRocket = class (TSimpleRocket)
procedure Move; override;
procedure Render; Override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
TStraightRocket = class (TSimpleRocket)
procedure Move; override;
procedure Render; Override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
end;
TBullet = class (TGameObject)
FiredBy : TGameObject;
procedure Move; override;
procedure Render; override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
TAIMBullet = class (TBullet)
LockOn : TGameObject;
procedure Move; override;
procedure Render; override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
TWeb = class (TGameObject)
LockOn : TGameObject;
procedure Move; override;
procedure Render; override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create(Target : TGameObject);
end;
TWebRocket = class (TSimpleRocket)
procedure Move; override;
procedure Render; Override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
TExplosion = class (TGameObject)
procedure Move; override;
procedure Render; override;
procedure Death; override;
procedure DoCollision(Vector : TGamePos; CoObject : TObject); override;
constructor Create;
end;
implementation
{ TSimpleRocket }
constructor TSimpleRocket.Create;
begin
Health := 100;
Radius := 0.25;
Collision := True;
TrailTime := 5;
Speed := 0.16;
Sound_PlayStream(Rocket_Sound);
end;
procedure TSimpleRocket.Death;
begin
inherited;
//
end;
procedure TSimpleRocket.DoCollision(Vector: TGamePos; CoObject: TObject);
var
Expl : TExplosion;
begin
inherited;
if not (CoObject is TSimpleRocket) and not (CoObject is TTrail) and not (CoObject = FiredBy) then
begin
(CoObject as TGameObject).Health := (CoObject as TGameObject).Health - 10;
Health := 0;
Expl := TExplosion.Create;
Expl.Pos := Pos;
ObjectsEngine.AddObject(Expl);
end;
end;
procedure TSimpleRocket.Move;
var
Trail : TTrail;
DVector : TGamePos;
ToAng : Single;
begin
inherited;
ToAng := AngleTo(Pos.x, Pos.z, LockOn.Pos.x, LockOn.Pos.z);
if Angle < ToAng then
Angle := Angle + 5 else
Angle := Angle - 5;
if TrailTime <= 0 then
begin
Trail := TTrail.Create;
Trail.Pos := Pos;
ObjectsEngine.AddObject(Trail);
TrailTime := 5;
end;
dec(TrailTime);
if TrailTime < 0 then TrailTime := 0;
DVector := MakeNormalVector(Cosinus(Angle), 0.0, Sinus(Angle));
Pos := AddVector(Pos, MultiplyVectorScalar(DVector, Speed));
Health := Health - 0.01;
end;
procedure TSimpleRocket.Render;
begin
inherited;
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glRotatef(90-Angle, 0.0, 1.0, 0.0);
glColor3f(1.0, 0.0, 0.0);
glBegin(GL_LINE_LOOP);
glVertex3f(0, 0, 0.25);
glVertex3f(0.1, 0, -0.25);
glVertex3f(-0.1, 0, -0.25);
glEnd;
glPopMatrix;
end;
{ TTrail }
constructor TTrail.Create;
begin
Collision := False;
Health := 100;
Scale := 1;
end;
procedure TTrail.Death;
begin
inherited;
//
end;
procedure TTrail.Move;
begin
Health := Health - 0.5;
end;
procedure TTrail.Render;
begin
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glColor3f(0.5, 0.5, 0.5);
glRotatef(Random(360), 0.0, 1.0, 0.0);
glScalef(Scale, Scale, Scale);
glBegin(GL_QUADS);
glVertex3f(-0.1, 0.0, -0.1);
glVertex3f( 0.1, 0.0, -0.1);
glVertex3f( 0.1, 0.0, 0.1);
glVertex3f(-0.1, 0.0, 0.1);
glEnd;
glPopMatrix;
end;
{ TBullet }
constructor TBullet.Create;
begin
Health := 100;
Collision := True;
Radius := 0.1;
end;
procedure TBullet.Death;
begin
inherited;
end;
procedure TBullet.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
inherited;
if CoObject <> FiredBy then
begin
Health := 0;
(CoObject as TGameObject).Health := (CoObject as TGameObject).Health - 25;
end;
end;
procedure TBullet.Move;
begin
inherited;
Pos := AddVector(Pos, MultiplyVectorScalar(MVector, 2));
Health := Health - 0.5;
end;
procedure TBullet.Render;
begin
inherited;
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glColor3f(1.0, 1.0, 0.0);
glPointSize(3);
glBegin(GL_POINTS);
glVertex3f(0.0, 0.0, 0.0);
glEnd;
glPointSize(1);
glPopMatrix;
end;
{ TExplosion }
constructor TExplosion.Create;
begin
Health := 10;
Collision := False;
Sound_PlayStream(Explod_Sound);
end;
procedure TExplosion.Death;
begin
inherited;
end;
procedure TExplosion.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
inherited;
end;
procedure TExplosion.Move;
begin
inherited;
Health := Health - 0.5;
end;
procedure TExplosion.Render;
var
a:Integer;
begin
inherited;
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glRotatef(Random(360), 0.0, 1.0, 0.0);
glColor3f(1-(Health / 10), 1, 0);
glBegin(GL_POLYGON);
for a := 0 to 5 do
begin
glVertex3f(Cosinus(a * 72), 0, Sinus(a * 72));
end;
glEnd;
glPopMatrix;
end;
{ TExtraRocket }
constructor TExtraRocket.Create;
begin
Health := 100;
Collision := False;
end;
procedure TExtraRocket.Death;
begin
inherited;
//
end;
procedure TExtraRocket.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
//inherited;
end;
procedure TExtraRocket.Move;
var
Rock : TSimpleRocket;
Expl : TExplosion;
i:Integer;
Trail : TTrail;
DVector : TGamePos;
begin
{if LockOn = nil then Health := 0;
if LockOn.Fake <> nil then LockOn := LockOn.Fake as TGameObject;}
Angle := AngleTo(Pos.x, Pos.z, LockOn.Pos.x, LockOn.Pos.z);
if Distance(Pos, LockOn.Pos) < 5 then
begin
Health := 0;
for i := 1 to 3 do
begin
Rock := TSimpleRocket.Create;
Rock.Pos := AddVector(Pos, MakeVector(Cosinus(Angle + (i * 90 - 180)), 0, Sinus(Angle + (i * 90 - 180))));
Rock.LockOn := LockOn;
Rock.Angle := Angle + (i * 90 - 180);
Rock.FiredBy := FiredBy;
ObjectsEngine.AddObject(Rock);
end;
Expl := TExplosion.Create;
Expl.Pos := Pos;
ObjectsEngine.AddObject(Expl);
end else
begin
if TrailTime <= 0 then
begin
Trail := TTrail.Create;
Trail.Pos := Pos;
ObjectsEngine.AddObject(Trail);
TrailTime := 5;
end;
dec(TrailTime);
if TrailTime < 0 then TrailTime := 0;
DVector := MakeNormalVector(Cosinus(Angle), 0.0, Sinus(Angle));
Pos := AddVector(Pos, MultiplyVectorScalar(DVector, 0.2));
Health := Health - 0.01;
end;
end;
procedure TExtraRocket.Render;
var
a : Integer;
begin
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glColor3f(1.0, 1.0, 0.0);
glBegin(GL_LINE_LOOP);
for a := 0 to 5 do
begin
glVertex3f(Cosinus(a * 72) * 0.3, 0, Sinus(a * 72) * 0.3);
end;
glEnd;
glPopMatrix;
end;
{ TAIMBullet }
constructor TAIMBullet.Create;
begin
Health := 100;
Collision := True;
Radius := 0.1;
Sound_PlayStream(Shot_2);
end;
procedure TAIMBullet.Death;
begin
inherited;
end;
procedure TAIMBullet.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
if CoObject <> FiredBy then
begin
(CoObject as TGameObject).Health := (CoObject as TGameObject).Health - 5;
Health := 0;
end;
end;
procedure TAIMBullet.Move;
begin
Angle := AngleTo(Pos.x, Pos.z, LockOn.Pos.x, LockOn.Pos.z);
MVector := MultiplyVectorScalar(MakeVector(Cosinus(Angle), 0, Sinus(Angle)), 0.12);
Pos := AddVector(Pos, MVector);
Health := Health - 0.3;
end;
procedure TAIMBullet.Render;
begin
inherited;
end;
{ TWeb }
constructor TWeb.Create;
begin
Collision := False;
Health := 100;
LockOn := Target;
LockOn.Freeze := True;
end;
procedure TWeb.Death;
begin
inherited;
LockOn.Freeze := False;
end;
procedure TWeb.DoCollision(Vector: TGamePos; CoObject: TObject);
begin
inherited;
end;
procedure TWeb.Move;
begin
Health := Health - 0.25;
end;
procedure TWeb.Render;
var
a : Integer;
begin
glPushMatrix;
glTranslatef(LockOn.Pos.x, LockOn.Pos.y, LockOn.Pos.z);
glColor3f(0.8, 0.8, 0.8);
glBegin(GL_LINE_LOOP);
for a := 0 to 5 do
begin
glVertex3f(Cosinus(a * 60), 0, Sinus(a * 60));
end;
glEnd;
glBegin(GL_LINE_LOOP);
for a := 0 to 5 do
begin
glVertex3f(Cosinus(a * 60) * 2, 0, Sinus(a * 60) * 2);
end;
glEnd;
glBegin(GL_LINES);
for a := 0 to 5 do
begin
glVertex3f(Cosinus(a * 60), 0, Sinus(a * 60));
glVertex3f(Cosinus(a * 60)*3, 0, Sinus(a * 60)*3);
end;
glEnd;
glPopMatrix;
end;
{ TWebRocket }
constructor TWebRocket.Create;
begin
Health := 100;
Radius := 0.25;
Collision := True;
end;
procedure TWebRocket.Death;
var
Expl : TExplosion;
begin
Expl := TExplosion.Create;
Expl.Pos := Pos;
ObjectsEngine.AddObject(Expl);
end;
procedure TWebRocket.DoCollision(Vector: TGamePos; CoObject: TObject);
var
Web : TWeb;
begin
if CoObject = LockOn then
begin
Web := TWeb.Create(LockOn);
ObjectsEngine.AddObject(Web);
Health := 0;
end;
end;
procedure TWebRocket.Move;
var
Trail : TTrail;
begin
Angle := AngleTo(Pos.x, Pos.z, LockOn.Pos.x, LockOn.Pos.z);
MVector := MultiplyVectorScalar(MakeVector(Cosinus(Angle), 0, Sinus(Angle)), 0.13);
Pos := AddVector(Pos, MVector) ;
if (TrailTime <= 0) then
begin
Trail := TTrail.Create;
Trail.Pos := Pos;
ObjectsEngine.AddObject(Trail);
TrailTime := 5;
end;
dec(TrailTime);
if TrailTime < 0 then TrailTime := 0;
Health := Health - 0.1;
end;
procedure TWebRocket.Render;
var
a : Integer;
begin
glPushMatrix;
glTranslatef(Pos.x, Pos.y, Pos.z);
glColor3f(1.0, 1.0, 1.0);
glBegin(GL_LINE_LOOP);
for a := 0 to 5 do
begin
glVertex3f(Cosinus(a * 72) * 0.3, 0, Sinus(a * 72) * 0.3);
end;
glEnd;
glPopMatrix;
end;
{ TStraightRocket }
procedure TStraightRocket.Death;
begin
inherited;
end;
procedure TStraightRocket.DoCollision(Vector: TGamePos; CoObject: TObject);
var
Expl : TExplosion;
begin
inherited;
if not (CoObject is TSimpleRocket) and not (CoObject is TTrail) and not (CoObject = FiredBy) then
begin
(CoObject as TGameObject).Health := (CoObject as TGameObject).Health - 50;
Health := 0;
Expl := TExplosion.Create;
Expl.Pos := Pos;
ObjectsEngine.AddObject(Expl);
end;
end;
procedure TStraightRocket.Move;
var
Trail : TTrail;
begin
if TrailTime <= 0 then
begin
Trail := TTrail.Create;
Trail.Pos := Pos;
ObjectsEngine.AddObject(Trail);
TrailTime := 5;
end;
dec(TrailTime);
if TrailTime < 0 then TrailTime := 0;
Pos := AddVector(Pos, MultiplyVectorScalar(MVector, Speed));
end;
procedure TStraightRocket.Render;
begin
inherited;
end;
end.
|
unit Vigilante.Infra.Build.Builder;
interface
uses
Vigilante.Build.Model;
type
IBuildBuilder = interface(IInterface)
['{63082ACF-E23B-432B-B501-000430300CF2}']
function PegarBuild: IBuildModel;
end;
implementation
end.
|
//******************************************************************************
//*** SCRIPT VCL FUNCTIONS ***
//*** ***
//*** (c) Massimo Magnano 2006 ***
//*** ***
//*** ***
//******************************************************************************
// File : Script_DB.pas (rev. 2.0)
//
// Description : Access from scripts to Classes declared in "DB.pas"
//
//******************************************************************************
//
// TComponent <- TDataset
// <- TField
// -------------------------------------------------------------
// TScriptComponent <- TScriptDataset
// <- TScriptField
//==============================================================================
unit Script_DB;
interface
uses Classes, DB, TypInfo, Script_Classes;
type
TScriptDataset = class (TScriptComponent)
protected
class function GetPublicPropertyAccessClass :TClass; override;
public
function GetArrayPropType(Name :String; index :Variant) :PTypeInfo; override;
function GetArrayProp(Name :String; index :Variant) :Variant; override;
function ActiveBuffer: String;
procedure Append;
procedure AppendRecord(const Values: array of const);
function BookmarkValid(Bookmark: TBookmark): Boolean;
procedure Cancel;
procedure CheckBrowseMode;
procedure ClearFields;
procedure Close;
function ControlsDisabled: Boolean;
function CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer;
function CreateBlobStream(Field: TField; Mode: TBlobStreamMode): TStream;
procedure CursorPosChanged;
procedure Delete;
procedure DisableControls;
procedure Edit;
procedure EnableControls;
function FieldByName(const FieldName: string): TField;
function FindField(const FieldName: string): TField;
function FindFirst: Boolean;
function FindLast: Boolean;
function FindNext: Boolean;
function FindPrior: Boolean;
procedure First;
procedure FreeBookmark(Bookmark: TBookmark);
function GetBookmark: TBookmark;
function GetCurrentRecord(Buffer: String): Boolean;
procedure GetDetailDataSets(List: TList);
procedure GetDetailLinkFields(MasterFields, DetailFields: TList);
function GetBlobFieldData(FieldNo: Integer; var Buffer: TBlobByteData): Integer;
function GetFieldData(Field: TField; Buffer: Pointer): Boolean; overload;
function GetFieldData(FieldNo: Integer; Buffer: Pointer): Boolean; overload;
function GetFieldData(Field: TField; Buffer: Pointer; NativeFormat: Boolean): Boolean; overload;
procedure GetFieldList(List: TList; const FieldNames: string);
procedure GetFieldNames(List: TStrings);
procedure GotoBookmark(Bookmark: TBookmark);
procedure Insert;
procedure InsertRecord(const Values: array of const);
function IsEmpty: Boolean;
function IsLinkedTo(DataSource: TDataSource): Boolean;
function IsSequenced: Boolean;
procedure Last;
function Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean;
function Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;
function MoveBy(Distance: Integer): Integer;
procedure Next;
procedure Open;
procedure Post;
procedure Prior;
procedure Refresh;
procedure Resync(Mode: TResyncMode);
procedure SetFields(const Values: array of const);
function Translate(Src, Dest: String; ToOem: Boolean): Integer;
procedure UpdateCursorPos;
procedure UpdateRecord;
function UpdateStatus: TUpdateStatus;
end;
//==============================================================================
TScriptField = class (TScriptComponent)
protected
class function GetPublicPropertyAccessClass :TClass; override;
public
procedure AssignValue(const Value: TVarRec);
procedure Clear;
procedure FocusControl;
function GetData(Buffer: Pointer; NativeFormat: Boolean = True): Boolean;
class function IsBlob: Boolean;
function IsValidChar(InputChar: Char): Boolean;
procedure RefreshLookupList;
procedure SetData(Buffer: Pointer; NativeFormat: Boolean = True);
procedure SetFieldType(Value: TFieldType);
procedure Validate(Buffer: Pointer);
end;
implementation
uses Script_System, SysUtils, Variants;
type
TDatasetAccess = class(TDataset)
published
property AggFields;
property Bof;
property Bookmark;
property CanModify;
property DataSetField;
property DataSource;
property DefaultFields;
property Designer;
property Eof;
property BlockReadSize;
property FieldCount;
property FieldDefs;
property FieldDefList;
property Fields;
property FieldList;
//property FieldValues[const FieldName: string]: Variant
property Found;
property IsUniDirectional;
property Modified;
property ObjectView;
property RecordCount;
property RecNo;
property RecordSize;
property SparseArrays;
property State;
property Filter;
property Filtered;
property FilterOptions;
property Active;
property AutoCalcFields;
end;
//==============================================================================
TFieldAccess = class(TField)
published
property AsBCD;
property AsBoolean;
property AsCurrency;
property AsDateTime;
property AsSQLTimeStamp;
property AsFloat;
property AsInteger;
property AsString;
property AsVariant;
property AttributeSet;
property Calculated;
property CanModify;
property CurValue;
property DataSet;
property DataSize;
property DataType;
property DisplayName;
property DisplayText;
property EditMask;
property EditMaskPtr;
property FieldNo;
property FullName;
property IsIndexField;
property IsNull;
property Lookup;
property LookupList;
property NewValue;
property Offset;
property OldValue;
property ParentField;
property Size;
property Text;
//property ValidChars; Size of published set 'ValidChars' is >4 bytes
property Value;
end;
{ TScriptDataset }
function TScriptDataset.GetArrayPropType(Name: String; index: Variant): PTypeInfo;
begin
Name :=Uppercase(Name);
Result :=nil;
if (Name='FIELDVALUES')
then begin
if (TDataset(InstanceObj).FieldValues[index]<>NULL)
then Result :=TypeInfo(Variant);
end
else
Result :=inherited GetArrayPropType(Name, index);
end;
function TScriptDataset.GetArrayProp(Name: String; index: Variant): Variant;
begin
if (Name='FIELDVALUES')
then begin
Result :=TDataset(InstanceObj).FieldValues[index]
end
else
Result := inherited GetArrayProp(name, index)
end;
class function TScriptDataset.GetPublicPropertyAccessClass: TClass;
begin
Result :=TDatasetAccess;
end;
function TScriptDataset.FindLast: Boolean;
begin
Result :=TDataset(InstanceObj).FindLast;
end;
function TScriptDataset.FieldByName(const FieldName: string): TField;
begin
Result :=TDataset(InstanceObj).FieldByName(FieldName);
end;
function TScriptDataset.FindPrior: Boolean;
begin
Result :=TDataset(InstanceObj).FindPrior;
end;
function TScriptDataset.FindField(const FieldName: string): TField;
begin
Result :=TDataset(InstanceObj).FindField(FieldName);
end;
function TScriptDataset.FindFirst: Boolean;
begin
Result :=TDataset(InstanceObj).FindFirst;
end;
procedure TScriptDataset.First;
begin
TDataset(InstanceObj).First;
end;
function TScriptDataset.FindNext: Boolean;
begin
Result :=TDataset(InstanceObj).FindNext;
end;
function TScriptDataset.IsLinkedTo(DataSource: TDataSource): Boolean;
begin
Result :=TDataset(InstanceObj).IsLinkedTo(DataSource);
end;
procedure TScriptDataset.ClearFields;
begin
TDataset(InstanceObj).ClearFields;
end;
procedure TScriptDataset.CursorPosChanged;
begin
TDataset(InstanceObj).CursorPosChanged;
end;
function TScriptDataset.Lookup(const KeyFields: string; const KeyValues: Variant;
const ResultFields: string): Variant;
begin
Result :=TDataset(InstanceObj).Lookup(KeyFields, KeyValues, ResultFields);
end;
procedure TScriptDataset.Last;
begin
TDataset(InstanceObj).Last;
end;
function TScriptDataset.Locate(const KeyFields: string; const KeyValues: Variant;
Options: TLocateOptions): Boolean;
begin
Result :=TDataset(InstanceObj).Locate(KeyFields, KeyValues, Options);
end;
procedure TScriptDataset.SetFields(const Values: array of const);
begin
TDataset(InstanceObj).SetFields(Values);
end;
procedure TScriptDataset.CheckBrowseMode;
begin
TDataset(InstanceObj).CheckBrowseMode;
end;
function TScriptDataset.UpdateStatus: TUpdateStatus;
begin
Result :=TDataset(InstanceObj).UpdateStatus;
end;
function TScriptDataset.MoveBy(Distance: Integer): Integer;
begin
Result :=TDataset(InstanceObj).MoveBy(Distance);
end;
function TScriptDataset.IsSequenced: Boolean;
begin
Result :=TDataset(InstanceObj).IsSequenced;
end;
procedure TScriptDataset.Prior;
begin
TDataset(InstanceObj).Prior;
end;
procedure TScriptDataset.UpdateRecord;
begin
TDataset(InstanceObj).UpdateRecord;
end;
procedure TScriptDataset.Refresh;
begin
TDataset(InstanceObj).Refresh;
end;
procedure TScriptDataset.Open;
begin
TDataset(InstanceObj).Open;
end;
procedure TScriptDataset.DisableControls;
begin
TDataset(InstanceObj).DisableControls;
end;
procedure TScriptDataset.AppendRecord(const Values: array of const);
begin
TDataset(InstanceObj).AppendRecord(Values);
end;
procedure TScriptDataset.Cancel;
begin
TDataset(InstanceObj).Cancel;
end;
procedure TScriptDataset.Post;
begin
TDataset(InstanceObj).Post;
end;
procedure TScriptDataset.InsertRecord(const Values: array of const);
begin
TDataset(InstanceObj).InsertRecord(Values);
end;
function TScriptDataset.IsEmpty: Boolean;
begin
Result :=TDataset(InstanceObj).IsEmpty;
end;
procedure TScriptDataset.Close;
begin
TDataset(InstanceObj).Close;
end;
procedure TScriptDataset.EnableControls;
begin
TDataset(InstanceObj).EnableControls;
end;
procedure TScriptDataset.Delete;
begin
TDataset(InstanceObj).Delete;
end;
procedure TScriptDataset.Resync(Mode: TResyncMode);
begin
TDataset(InstanceObj).Resync(Mode);
end;
procedure TScriptDataset.Edit;
begin
TDataset(InstanceObj).Edit;
end;
procedure TScriptDataset.Append;
begin
TDataset(InstanceObj).Append;
end;
function TScriptDataset.ControlsDisabled: Boolean;
begin
Result :=TDataset(InstanceObj).ControlsDisabled;
end;
procedure TScriptDataset.UpdateCursorPos;
begin
TDataset(InstanceObj).UpdateCursorPos;
end;
procedure TScriptDataset.Next;
begin
TDataset(InstanceObj).Next;
end;
procedure TScriptDataset.Insert;
begin
TDataset(InstanceObj).Insert;
end;
procedure TScriptDataset.GetFieldList(List: TList; const FieldNames: string);
begin
TDataset(InstanceObj).GetFieldList(List, FieldNames);
end;
function TScriptDataset.GetFieldData(Field: TField; Buffer: Pointer;
NativeFormat: Boolean): Boolean;
begin
Result :=TDataset(InstanceObj).GetFieldData(Field, Buffer, NativeFormat);
end;
function TScriptDataset.GetFieldData(FieldNo: Integer; Buffer: Pointer): Boolean;
begin
Result :=TDataset(InstanceObj).GetFieldData(FieldNo, Buffer);
end;
function TScriptDataset.GetFieldData(Field: TField; Buffer: Pointer): Boolean;
begin
Result :=TDataset(InstanceObj).GetFieldData(Field, Buffer);
end;
function TScriptDataset.CreateBlobStream(Field: TField;
Mode: TBlobStreamMode): TStream;
begin
Result :=TDataset(InstanceObj).CreateBlobStream(Field, Mode);
end;
procedure TScriptDataset.GotoBookmark(Bookmark: TBookmark);
begin
TDataset(InstanceObj).GotoBookmark(Bookmark);
end;
function TScriptDataset.CompareBookmarks(Bookmark1, Bookmark2: TBookmark): Integer;
begin
Result :=TDataset(InstanceObj).CompareBookmarks(Bookmark1, Bookmark2);
end;
function TScriptDataset.GetBookmark: TBookmark;
begin
Result :=TDataset(InstanceObj).GetBookmark;
end;
function TScriptDataset.GetCurrentRecord(Buffer: String): Boolean;
begin
Result :=TDataset(InstanceObj).GetCurrentRecord(PChar(Buffer));
end;
procedure TScriptDataset.GetDetailLinkFields(MasterFields, DetailFields: TList);
begin
TDataset(InstanceObj).GetDetailLinkFields(MasterFields, DetailFields);
end;
function TScriptDataset.BookmarkValid(Bookmark: TBookmark): Boolean;
begin
Result :=TDataset(InstanceObj).BookmarkValid(Bookmark);
end;
function TScriptDataset.Translate(Src, Dest: String; ToOem: Boolean): Integer;
begin
Result :=TDataset(InstanceObj).Translate(PChar(Src), PChar(Dest), ToOem);
end;
procedure TScriptDataset.FreeBookmark(Bookmark: TBookmark);
begin
TDataset(InstanceObj).FreeBookmark(Bookmark);
end;
function TScriptDataset.GetBlobFieldData(FieldNo: Integer;
var Buffer: TBlobByteData): Integer;
begin
Result :=TDataset(InstanceObj).GetBlobFieldData(FieldNo, Buffer);
end;
procedure TScriptDataset.GetDetailDataSets(List: TList);
begin
TDataset(InstanceObj).GetDetailDataSets(List);
end;
function TScriptDataset.ActiveBuffer: String;
begin
Result :=TDataset(InstanceObj).ActiveBuffer;
end;
procedure TScriptDataset.GetFieldNames(List: TStrings);
begin
TDataset(InstanceObj).GetFieldNames(List);
end;
{ TScriptField }
class function TScriptField.GetPublicPropertyAccessClass: TClass;
begin
Result :=TFieldAccess;
end;
procedure TScriptField.AssignValue(const Value: TVarRec);
begin
TField(InstanceObj).AssignValue(Value);
end;
function TScriptField.GetData(Buffer: Pointer; NativeFormat: Boolean): Boolean;
begin
Result :=TField(InstanceObj).GetData(Buffer, NativeFormat);
end;
procedure TScriptField.FocusControl;
begin
TField(InstanceObj).FocusControl;
end;
procedure TScriptField.Clear;
begin
TField(InstanceObj).Clear;
end;
procedure TScriptField.SetData(Buffer: Pointer; NativeFormat: Boolean);
begin
TField(InstanceObj).SetData(Buffer, NativeFormat);
end;
procedure TScriptField.SetFieldType(Value: TFieldType);
begin
TField(InstanceObj).SetFieldType(Value);
end;
procedure TScriptField.Validate(Buffer: Pointer);
begin
TField(InstanceObj).Validate(Buffer);
end;
procedure TScriptField.RefreshLookupList;
begin
TField(InstanceObj).RefreshLookupList;
end;
class function TScriptField.IsBlob: Boolean;
begin
Result := False;
end;
function TScriptField.IsValidChar(InputChar: Char): Boolean;
begin
Result :=TField(InstanceObj).IsValidChar(InputChar);
end;
initialization
Script_System.RegisterClass(TDataset, TScriptDataset);
Script_System.RegisterClass(TField, TScriptField);
end.
|
unit FazerPedidoEdmoto;
interface
uses
System.SysUtils, InterfacePizzaStore, PizzariaJamal, EsfihariaEdmoto;
type
TPedidoEsfiha = class
class var ListaDoPedidoEsfihasEdmoto: TArray<TEsfiha>;
procedure PedirEsfihaEdmoto(Qtd: Integer; Tipo: string);
function RegistarPedidoDeEsfihaEdmoto(Esfiha: string): TEsfiha;
procedure MostrarPedidoDeEsfihaEdmoto;
destructor Destroy; override;
end;
TPedidoPizza = class
class var ListaDoPedidoPizzasEdmoto: TArray<TPizza>;
procedure PedirPizzaEdmoto(Qtd: Integer; Tipo: string);
function RegistrarPedidoDePizzaEdmoto(Pizza: string): TPizza;
procedure MostrarPedidoDePizzaEdmoto;
destructor Destroy; override;
end;
implementation
destructor TPedidoEsfiha.Destroy;
var
Esfihas: TEsfiha;
begin
for Esfihas in ListaDoPedidoEsfihasEdmoto do
Esfihas.Free;
inherited;
end;
procedure TPedidoEsfiha.MostrarPedidoDeEsfihaEdmoto;
var
Esfihas: TEsfiha;
begin
for Esfihas in ListaDoPedidoEsfihasEdmoto do
Writeln(Esfihas.SaborDaEsfiha + ' ' + Format('%m', [ESfihas.ValorDaEsfiha]));
end;
procedure TPedidoEsfiha.PedirEsfihaEdmoto(Qtd: Integer; Tipo: string);
var
I: Integer;
begin
for I := 0 to Qtd - 1 do
ListaDoPedidoEsfihasEdmoto := ListaDoPedidoEsfihasEdmoto + [RegistarPedidoDeEsfihaEdmoto(Tipo)];
end;
function TPedidoEsfiha.RegistarPedidoDeEsfihaEdmoto(Esfiha: string): TEsfiha;
var
EsfihaClass: TTipoDeEsfiha;
begin
Result := nil;
for EsfihaClass in TEsfihariaEdmoto.EsfihasEdmoto do
if EsfihaClass.ClassName = Esfiha then
Result := (EsfihaClass.Create);
end;
{ TPedidoPizza }
destructor TPedidoPizza.Destroy;
var
Pizzas: TPizza;
begin
for Pizzas in ListaDoPedidoPizzasEdmoto do
Pizzas.Free;
inherited;
end;
procedure TPedidoPizza.MostrarPedidoDePizzaEdmoto;
var
Pizzas: TPizza;
begin
for Pizzas in ListaDoPedidoPizzasEdmoto do
Writeln(Pizzas.SaborDaPizza+ '' + Format('%m', [Pizzas.ValorDaPizza]));
end;
procedure TPedidoPizza.PedirPizzaEdmoto(Qtd: Integer; Tipo: string);
var
I: Integer;
begin
for I := 0 to Qtd - 1 do
ListaDoPedidoPizzasEdmoto := ListaDoPedidoPizzasEdmoto + [RegistrarPedidoDePizzaEdmoto(Tipo)];
end;
function TPedidoPizza.RegistrarPedidoDePizzaEdmoto(Pizza: string): TPizza;
var
PizzaClass: TTipoDePizza;
begin
Result := nil;
for PizzaClass in TEsfihariaEdmoto.PizzasEdmoto do
if PizzaClass.ClassName = Pizza then
Result := (PizzaClass.Create);
end;
end.
|
unit uMyClientContext;
interface
uses
diocp.coder.tcpServer, Classes, SysUtils, uZipTools, SimpleMsgPack;
type
TMyClientContext = class(TIOCPCoderClientContext)
protected
procedure OnDisconnected; override;
procedure OnConnected;override;
protected
/// <summary>
/// on received a object
/// </summary>
/// <param name="pvDataObject"> (TObject) </param>
procedure DoContextAction(const pvDataObject:TObject); override;
public
end;
implementation
uses
uFileOperaHandler;
{ TMyClientContext }
procedure TMyClientContext.DoContextAction(const pvDataObject:TObject);
var
lvMsgPack:TSimpleMsgPack;
lvStream :TStream;
begin
lvStream := TStream(pvDataObject);
lvMsgPack := TSimpleMsgPack.Create;
try
try
lvStream.Position := 0;
// unpack
lvMsgPack.DecodeFromStream(lvStream);
TFileOperaHandler.Execute(lvMsgPack);
lvMsgPack.ForcePathObject('__result.result').AsBoolean := true;
except
on E:Exception do
begin
lvMsgPack.Clear;
lvMsgPack.ForcePathObject('__result.result').AsBoolean := false;
lvMsgPack.ForcePathObject('__result.msg').AsString := e.Message;
end;
end;
lvStream.Size := 0;
lvMsgPack.EncodeToStream(lvStream);
lvStream.Position := 0;
// send to client
self.writeObject(lvStream);
finally
lvMsgPack.Free;
end;
end;
procedure TMyClientContext.OnConnected;
begin
inherited;
end;
procedure TMyClientContext.OnDisconnected;
begin
inherited;
end;
end.
|
////////////////////////////////////////////
// Поток опроса приборов через GPRS-модемы Ancom
////////////////////////////////////////////
unit Threads.AncomGPRS;
interface
uses Windows, Threads.ReqSpecDevTemplate, ScktComp, GMGlobals, SysUtils, GMSocket, GM485;
type
TRequestAncomGPRS = class(TRequestSpecDevices)
private
FSocket: TGeomerSocket;
protected
function ConfigurePort(ri: TSpecDevReqListItem): bool; override;
procedure FreePort; override;
public
constructor Create(id_obj: int; socket: TGeomerSocket);
end;
implementation
uses GMConst, ProgramLogFile, Math, Connection.TCP;
type
TConnectionObjectTCP_IncomingSocketForAncom = class(TConnectionObjectTCP_IncomingSocket)
protected
function DefaultWaitFirst: int; override;
function DefaultWaitNext: int; override;
end;
function TConnectionObjectTCP_IncomingSocketForAncom.DefaultWaitFirst: int;
begin
Result := Max(inherited DefaultWaitFirst(), 5000);
end;
function TConnectionObjectTCP_IncomingSocketForAncom.DefaultWaitNext: int;
begin
Result := Max(inherited DefaultWaitNext(), 2000);
end;
{ TRequestAncomGPRS }
function TRequestAncomGPRS.ConfigurePort(ri: TSpecDevReqListItem): bool;
begin
if FSocket = nil then
Exit(false);
Result := inherited ConfigurePort(ri);
FSocket.Lock(ThreadId);
end;
constructor TRequestAncomGPRS.Create(id_obj: int; socket: TGeomerSocket);
begin
inherited Create(OBJ_TYPE_ANCOM, id_obj);
FSocket := socket;
CreateConnectionObject(TConnectionObjectTCP_IncomingSocketForAncom);
TConnectionObjectTCP_IncomingSocketForAncom(ConnectionObject).Socket := FSocket.Socket;
ConnectionObject.LogPrefix := 'Ancom_' + IntToStr(FSocket.N_Car);
end;
procedure TRequestAncomGPRS.FreePort;
begin
inherited;
FSocket.Unlock();
end;
end.
|
UNIT pixMaps;
INTERFACE
USES math,types, myGenerics,myColors;
TYPE
T_imageDimensions=object
width,height:longint;
FUNCTION fitsInto(CONST containedIn:T_imageDimensions):boolean;
FUNCTION max(CONST other:T_imageDimensions):T_imageDimensions;
FUNCTION min(CONST other:T_imageDimensions):T_imageDimensions;
FUNCTION getFittingRectangle(CONST aspectRatio:double):T_imageDimensions;
FUNCTION toRect:TRect;
end;
CONST
MAX_HEIGHT_OR_WIDTH=9999;
C_maxImageDimensions:T_imageDimensions=(width:MAX_HEIGHT_OR_WIDTH;height:MAX_HEIGHT_OR_WIDTH);
TYPE
GENERIC G_pixelMap<PIXEL_TYPE>=object
TYPE PIXEL_POINTER=^PIXEL_TYPE;
SELF_TYPE=specialize G_pixelMap<PIXEL_TYPE>;
P_SELF_TYPE=^SELF_TYPE;
protected
dim:T_imageDimensions;
data:PIXEL_POINTER;
FUNCTION getPixel(CONST x,y:longint):PIXEL_TYPE;
PROCEDURE setPixel(CONST x,y:longint; CONST value:PIXEL_TYPE);
PROCEDURE resize(CONST newSize:T_imageDimensions);
FUNCTION dataSize:longint;
FUNCTION dataSize(CONST width,height:longint):longint;
public
CONSTRUCTOR create(CONST initialWidth:longint=1; CONST initialHeight:longint=1);
DESTRUCTOR destroy;
PROPERTY pixel[x,y:longint]:PIXEL_TYPE read getPixel write setPixel; default;
PROPERTY rawData:PIXEL_POINTER read data;
FUNCTION linePtr(CONST y:longint):PIXEL_POINTER;
PROPERTY dimensions:T_imageDimensions read dim write resize;
FUNCTION pixelCount:longint;
FUNCTION diagonal:double;
FUNCTION getClone:P_SELF_TYPE;
PROCEDURE blur(CONST relativeXBlur:double; CONST relativeYBlur:double);
PROCEDURE boxBlur(CONST relativeXBlur:double; CONST relativeYBlur:double);
PROCEDURE flip;
PROCEDURE flop;
PROCEDURE rotRight;
PROCEDURE rotLeft;
PROCEDURE crop(CONST rx0,rx1,ry0,ry1:double);
PROCEDURE cropAbsolute(CONST x0,x1,y0,y1:longint);
PROCEDURE clear;
PROCEDURE copyFromPixMap(VAR srcImage: G_pixelMap);
PROCEDURE simpleScaleDown(powerOfTwo:byte);
end;
FUNCTION transpose(CONST dim:T_imageDimensions):T_imageDimensions;
FUNCTION crop(CONST dim:T_imageDimensions; CONST rx0,rx1,ry0,ry1:double):T_imageDimensions;
FUNCTION getSmoothingKernel(CONST sigma:double):T_arrayOfDouble;
OPERATOR =(CONST d1,d2:T_imageDimensions):boolean;
FUNCTION imageDimensions(CONST width,height:longint):T_imageDimensions;
//FUNCTION getFittingRectangle(CONST availableWidth,availableHeight:longint; CONST aspectRatio:double):TRect;
IMPLEMENTATION
OPERATOR =(CONST d1,d2:T_imageDimensions):boolean;
begin
result:=(d1.width=d2.width) and (d1.height=d2.height);
end;
FUNCTION imageDimensions(CONST width, height: longint): T_imageDimensions;
begin
result.width:=width;
result.height:=height;
end;
FUNCTION T_imageDimensions.fitsInto(CONST containedIn: T_imageDimensions): boolean;
begin
result:=(width <=containedIn.width ) and
(height<=containedIn.height);
end;
FUNCTION T_imageDimensions.max(CONST other: T_imageDimensions): T_imageDimensions;
begin
result.width :=math.max(width ,other.width );
result.height:=math.max(height,other.height);
end;
FUNCTION T_imageDimensions.min(CONST other: T_imageDimensions): T_imageDimensions;
begin
result.width :=math.min(width ,other.width );
result.height:=math.min(height,other.height);
end;
FUNCTION T_imageDimensions.getFittingRectangle(CONST aspectRatio: double): T_imageDimensions;
begin
if height*aspectRatio<width
then result:=imageDimensions(round(height*aspectRatio),height)
else result:=imageDimensions(width,round(width/aspectRatio));
end;
FUNCTION T_imageDimensions.toRect: TRect;
begin
result:=rect(0,0,width,height);
end;
FUNCTION getSmoothingKernel(CONST sigma:double):T_arrayOfDouble;
VAR radius,i:longint;
sum:double=-1;
factor:double;
begin
if sigma<=1E-3 then begin
setLength(result,1);
result[0]:=1;
exit(result);
end;
radius:=round(3*sigma);
if radius<2 then radius:=2;
setLength(result,radius+1);
for i:=0 to radius do begin
result[i]:=exp(-0.5*sqr(i/sigma));
sum:=sum+2*result[i];
end;
factor:=1/sum;
for i:=0 to radius do result[i]:=result[i]*factor;
end;
FUNCTION G_pixelMap.getPixel(CONST x, y: longint): PIXEL_TYPE; begin result:=data[x+y*dim.width]; end;
PROCEDURE G_pixelMap.setPixel(CONST x, y: longint; CONST value: PIXEL_TYPE); begin data[x+y*dim.width]:=value; end;
CONSTRUCTOR G_pixelMap.create(CONST initialWidth: longint;
CONST initialHeight: longint);
begin
dim.width:=initialWidth;
dim.height:=initialHeight;
getMem(data,dim.width*dim.height*sizeOf(PIXEL_TYPE));
end;
DESTRUCTOR G_pixelMap.destroy;
begin
freeMem(data,dim.width*dim.height*sizeOf(PIXEL_TYPE));
end;
PROCEDURE G_pixelMap.resize(CONST newSize: T_imageDimensions);
begin
if (newSize.width=dim.width) and (newSize.height=dim.height) then exit;
freeMem(data,dataSize);
dim:=newSize;
getMem(data,dataSize);
end;
FUNCTION G_pixelMap.dataSize: longint;
begin
result:=pixelCount*sizeOf(PIXEL_TYPE);
end;
FUNCTION G_pixelMap.dataSize(CONST width, height: longint): longint;
begin
result:=width*height*sizeOf(PIXEL_TYPE);
end;
FUNCTION G_pixelMap.linePtr(CONST y: longint): PIXEL_POINTER;
begin
result:=@(data[dim.width*y]);
end;
FUNCTION G_pixelMap.pixelCount: longint;
begin
result:=dim.width*dim.height;
end;
FUNCTION G_pixelMap.diagonal: double;
begin
result:=sqrt(sqr(double(dim. width))+
sqr(double(dim.height)));
end;
FUNCTION G_pixelMap.getClone: P_SELF_TYPE;
begin
new(result,create(dim.width,dim.height));
move(data^,result^.data^,dataSize);
end;
PROCEDURE G_pixelMap.blur(CONST relativeXBlur: double; CONST relativeYBlur: double);
VAR kernel:T_arrayOfDouble;
temp:SELF_TYPE;
ptmp:PIXEL_POINTER;
x,y,z:longint;
sum:PIXEL_TYPE;
weight:double;
begin
temp.create(dim.width,dim.height);
ptmp:=temp.data;
kernel:=getSmoothingKernel(relativeXBlur/100*diagonal);
//blur in x-direction:-----------------------------------------------
for y:=0 to dim.height-1 do for x:=0 to dim.width-1 do begin
sum:=BLACK; weight:=0;
for z:=max(-x,1-length(kernel)) to min(dim.width-x,length(kernel))-1 do begin
sum :=sum +data[x+z+y*dim.width]*kernel[abs(z)];
weight:=weight+ kernel[abs(z)];
end;
if (x<length(kernel)) or (x>dim.width-1-length(kernel))
then ptmp[x+y*dim.width]:=sum*(1/weight)
else ptmp[x+y*dim.width]:=sum;
end;
//-------------------------------------------------:blur in x-direction
setLength(kernel,0);
kernel:=getSmoothingKernel(relativeYBlur/100*diagonal);
//blur in y-direction:---------------------------------------------------
for x:=0 to dim.width-1 do for y:=0 to dim.height-1 do begin
sum:=BLACK; weight:=0;
for z:=max(-y,1-length(kernel)) to min(dim.height-y,length(kernel))-1 do begin
sum :=sum +ptmp[x+(z+y)*dim.width]*kernel[abs(z)];
weight:=weight+ kernel[abs(z)];
end;
if (y<length(kernel)) or (y>dim.height-1-length(kernel))
then data[x+y*dim.width]:=sum*(1/weight)
else data[x+y*dim.width]:=sum;
end;
//-----------------------------------------------------:blur in y-direction
temp.destroy;
setLength(kernel,0);
end;
PROCEDURE G_pixelMap.boxBlur(CONST relativeXBlur:double; CONST relativeYBlur:double);
VAR radX,radY:longint;
temp:SELF_TYPE;
ptmp:PIXEL_POINTER;
x,y,z:longint;
sum:PIXEL_TYPE;
sampleCount:longint;
begin
radX:=round(relativeXBlur*diagonal*0.01*sqrt(3)); if radX<0 then radX:=0;
radY:=round(relativeYBlur*diagonal*0.01*sqrt(3)); if radY<0 then radY:=0;
if (radX<=0) and (radY<=0) then exit;
temp.create(dim.width,dim.height);
ptmp:=temp.data;
//blur in x-direction:-----------------------------------------------
for y:=0 to dim.height-1 do for x:=0 to dim.width-1 do begin
sum:=BLACK;
sampleCount:=0;
for z:=max(-x,-radX) to min(dim.width-x-1,radX) do begin
sum:=sum+data[x+z+y*dim.width];
inc(sampleCount);
end;
ptmp[x+y*dim.width]:=sum*(1/sampleCount);
end;
//-------------------------------------------------:blur in x-direction
//blur in y-direction:---------------------------------------------------
for x:=0 to dim.width-1 do for y:=0 to dim.height-1 do begin
sum:=BLACK;
sampleCount:=0;
for z:=max(-y,-radY) to min(dim.height-y-1,radY) do begin
sum:=sum+ptmp[x+(z+y)*dim.width];
inc(sampleCount);
end;
data[x+y*dim.width]:=sum*(1/sampleCount);
end;
//-----------------------------------------------------:blur in y-direction
temp.destroy;
end;
PROCEDURE G_pixelMap.flip;
VAR x,y,y1,i0,i1:longint;
tempCol:PIXEL_TYPE;
begin
for y:=0 to dim.height shr 1 do begin
y1:=dim.height-1-y;
if y1>y then for x:=0 to dim.width-1 do begin
i0:=x+y *dim.width;
i1:=x+y1*dim.width;
tempCol :=data[i0];
data[i0]:=data[i1];
data[i1]:=tempCol;
end;
end;
end;
PROCEDURE G_pixelMap.flop;
VAR x,y,x1,i0,i1:longint;
tempCol:PIXEL_TYPE;
begin
for y:=0 to dim.height-1 do
for x:=0 to dim.width shr 1 do begin
x1:=dim.width-1-x;
if x1>x then begin
i0:=x +y*dim.width;
i1:=x1+y*dim.width;
tempCol :=data[i0];
data[i0]:=data[i1];
data[i1]:=tempCol;
end;
end;
end;
FUNCTION transpose(CONST dim:T_imageDimensions):T_imageDimensions;
begin
result.width :=dim.height;
result.height:=dim.width;
end;
PROCEDURE G_pixelMap.rotRight;
VAR x,y:longint;
temp:P_SELF_TYPE;
tempDat:PIXEL_POINTER;
begin
temp:=getClone;
tempDat:=temp^.data;
x :=dim.width;
dim.width :=dim.height;
dim.height:=x;
for y:=0 to dim.height-1 do for x:=0 to dim.width -1 do
data[x+y*dim.width]:=tempDat[(dim.height-1-y)+x*dim.height];
dispose(temp,destroy);
end;
PROCEDURE G_pixelMap.rotLeft;
VAR x,y:longint;
temp:P_SELF_TYPE;
tempDat:PIXEL_POINTER;
begin
temp:=getClone;
tempDat:=temp^.data;
x :=dim.width;
dim.width :=dim.height;
dim.height:=x;
for y:=0 to dim.height-1 do for x:=0 to dim.width -1 do
data[x+y*dim.width]:=tempDat[y+(dim.width-1-x)*dim.height];
dispose(temp,destroy);
end;
FUNCTION crop(CONST dim:T_imageDimensions; CONST rx0,rx1,ry0,ry1:double):T_imageDimensions;
begin
result.width :=round(rx1*dim.width )-round(rx0*dim.width );
result.height:=round(ry1*dim.height)-round(ry0*dim.height);
end;
PROCEDURE G_pixelMap.crop(CONST rx0, rx1, ry0, ry1: double);
begin
cropAbsolute(round(rx0*dim.width),
round(rx1*dim.width),
round(ry0*dim.height),
round(ry1*dim.height));
end;
PROCEDURE G_pixelMap.cropAbsolute(CONST x0,x1,y0,y1:longint);
VAR newData:PIXEL_POINTER;
newXRes,newYRes,x,y:longint;
begin
if (x1<=x0) or (y1<=y0) then exit;
newXRes:=x1-x0;
newYRes:=y1-y0;
getMem(newData,dataSize(newXRes,newYRes));
for y:=y0 to y1-1 do for x:=x0 to x1-1 do
if (x>=0) and (x<dim.width) and (y>=0) and (y<dim.height)
then newData[(x-x0)+(y-y0)*newXRes]:=pixel[x,y]
else newData[(x-x0)+(y-y0)*newXRes]:=BLACK;
freeMem(data,dataSize);
dim.width:=newXRes;
dim.height:=newYRes;
data:=newData;
end;
PROCEDURE G_pixelMap.clear;
begin
if pixelCount>1 then freeMem(data,dataSize);
dim.width:=1;
dim.height:=1;
getMem(data,dataSize);
end;
PROCEDURE G_pixelMap.copyFromPixMap(VAR srcImage: G_pixelMap);
VAR i:longint;
begin
resize(srcImage.dim);
for i:=0 to pixelCount-1 do data[i]:=srcImage.data[i];
end;
PROCEDURE G_pixelMap.simpleScaleDown(powerOfTwo: byte);
VAR nx,ny,nw,nh:longint;
newDat:PIXEL_POINTER;
l1,l2:PIXEL_POINTER;
begin
while powerOfTwo>1 do begin
nw:=dim.width shr 1;
nh:=dim.height shr 1;
getMem(newDat,dataSize(nw,nh));
for ny:=0 to nh-1 do begin
l1:=data+((ny+ny )*dim.height);
l2:=data+((ny+ny+1)*dim.height);
for nx:=0 to nw-1 do
newDat[nx+ny*nw]:=(l1[nx+nx]+l1[nx+nx+1]
+l2[nx+nx]+l2[nx+nx+1])*0.25;
end;
freeMem(data,dataSize);
data:=newDat; newDat:=nil;
dim.width :=nw;
dim.height:=nh;
powerOfTwo:=powerOfTwo shr 1;
end;
end;
{FUNCTION FastBitmapToBitmap(FastBitmap: TFastBitmap; Bitmap: TBitmap);
VAR
X, Y: integer;
tempIntfImage: TLazIntfImage;
begin
try
tempIntfImage := Bitmap.CreateIntfImage; // Temp image could be pre-created and help by owner class to avoid new creation in each frame
for Y := 0 to FastBitmap.size.Y - 1 do
for X := 0 to FastBitmap.size.X - 1 do begin
tempIntfImage.colors[X, Y] := TColorToFPColor(FastPixelToTColor(FastBitmap.Pixels[X, Y]));
end;
Bitmap.LoadFromIntfImage(tempIntfImage);
finally
tempIntfImage.free;
end;
end;}
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 2018-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.VirtualImageList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes,
System.Messaging, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.ImgList,
Vcl.BaseImageCollection;
type
TVirtualImageList = class;
/// <summary>
/// Item to define image for TVirtualImageList.
/// </summary>
TVirtualImageListItem = class(TCollectionItem)
private
FName: String;
FCollectionIndex: Integer;
FCollectionName: String;
FDisabled: Boolean;
FDisabledBitmap: TBitmap;
procedure SetDisabled(AValue: Boolean);
procedure SetCollectionIndex(AValue: Integer);
procedure SetCollectionName(const AValue: String);
procedure SetName(const AValue: String);
function GetImageList: TVirtualImageList;
function GetDisabledBitmap: TBitmap;
protected
function CheckCollectionItem: Boolean;
procedure UpdateDisabledBitmap;
property ImageList: TVirtualImageList read GetImageList;
property DisabledBitmap: TBitmap read GetDisabledBitmap;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
/// <summary>
/// Use Update method to mannual update image list bitmaps for current item.
/// </summary>
procedure Update;
published
/// <summary>
/// Index of linked item from image collection.
/// </summary>
property CollectionIndex: Integer
read FCollectionIndex write SetCollectionIndex;
/// <summary>
/// Name of linked item from image collection.
/// </summary>
property CollectionName: String
read FCollectionName write SetCollectionName;
/// <summary>
/// Defines disabled copy of item from image collection.
/// </summary>
property Disabled: Boolean
read FDisabled write SetDisabled;
/// <summary>
/// Item name, which can includes Category.
/// Category name placed at the beginning of the name and separated by the symbol "\".
/// </summary>
property Name: String read FName write SetName;
end;
/// <summary>
/// Collection of items, whcih defines list of images
/// </summary>
TVirtualImageListItems = class(TOwnedCollection)
private
function GetItem(Index: Integer): TVirtualImageListItem;
procedure SetItem(Index: Integer; Value: TVirtualImageListItem);
protected
function GetImageList: TVirtualImageList;
property ImageList: TVirtualImageList read GetImageList;
public
function Add: TVirtualImageListItem;
function Insert(Index: Integer): TVirtualImageListItem;
procedure Delete(Index: Integer);
property Items[Index: Integer]: TVirtualImageListItem read GetItem write SetItem; default;
end;
/// <summary>
/// Type, which defines auto fill mode for TVirtualImageList
/// </summary>
TImageListAutoFillMode = (afmNormal, afmDisabled);
/// <summary>
/// TVirtualImageList component, which
/// inherited from TCustomImageList and use TCustomImageCollection to dynamicly create list of internal images.
/// It has collection of items, in which each item linked by index and name with TCustomImageCollection.
/// </summary>
TVirtualImageList = class(TCustomImageList)
private
FDPIChangedMessageID: Integer;
FCollectionChangedMessageID: Integer;
FImageCollection: TCustomImageCollection;
FImages: TVirtualImageListItems;
FDisabledGrayscale: Boolean;
FDisabledOpacity: Byte;
FDisabledSuffix: String;
FImageListUpdating: Boolean;
FScaled: Boolean;
FPreserveItems: Boolean;
FAutoFill: Boolean;
FAutoFillMode: TImageListAutoFillMode;
procedure SetAutoFill(Value: Boolean);
procedure SetAutoFillMode(Value: TImageListAutoFillMode);
procedure SetPreserveItems(Value: Boolean);
procedure SetDisabledSuffix(Value: String);
procedure SetDisabledGrayscale(Value: Boolean);
procedure SetDisabledOpacity(Value: Byte);
procedure SetImageCollection(Value: TCustomImageCollection);
procedure DPIChangedMessageHandler(const Sender: TObject; const Msg: System.Messaging.TMessage);
procedure CollectionChangedMessageHandler(const Sender: TObject; const Msg: System.Messaging.TMessage);
protected
procedure Loaded; override;
procedure DoChange; override;
procedure DoAutoFill;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
function CreateBlankBitmap: TBitmap; virtual;
procedure UpdateDisabledBitmaps;
procedure CreateDisabledBitmap(ABitmap: TBitmap);
function IsImageCollectionAvailable: Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
/// <summary>
/// Get item index from specific name.
/// </summary>
function GetIndexByName(const AName: String): Integer; virtual;
/// <summary>
/// Call UpdateImageList to mannual recreate internal image list from item colleciton (Images property).
/// </summary>
procedure UpdateImageList;
/// <summary>
/// Delete all items from Images property.
/// </summary>
procedure Clear;
/// <summary>
/// Delete item with specific index from Images property.
/// </summary>
procedure Delete(AIndex: Integer); overload;
/// <summary>
/// Delete item with specific name from Images property.
/// </summary>
procedure Delete(const AName: String); overload;
/// <summary>
/// Add items from image colleciton using start and end item indexes.
/// if ACategory set then items will be added only with this category.
/// if AddDisabledCopies then disabled copies will be added also.
/// </summary>
procedure Add(const ACategory: String; AStartIndex, AEndIndex: Integer; AddDisabledCopies: Boolean = False); overload;
/// <summary>
/// Add item from image collection with specifc name and image collection item index.
/// if AddDisabledCopies then disabled copy will be added also.
/// </summary>
procedure Add(AName: String; ACollectionIndex: Integer; AddDisabledCopy: Boolean = False); overload;
/// <summary>
/// Add item from image collection with specifc name and image collection item name.
/// if AddDisabledCopies then disabled copy will be added also.
/// </summary>
procedure Add(AName: String; const ACollectionName: String; AddDisabledCopy: Boolean = False); overload;
/// <summary>
/// Add items as disabled copies from image colleciton using start and end item indexes.
/// if ACategory set then items will be added only with this category.
/// </summary>
procedure AddDisabled(const ACategory: String; AStartIndex, AEndIndex: Integer); overload;
/// <summary>
/// Add item as disabled copy from image colleciton using specifc name and image collection item index.
/// </summary>
procedure AddDisabled(AName: String; ACollectionIndex: Integer); overload;
/// <summary>
/// Add item as disabled copy from image colleciton using specifc name and image collection item name.
/// </summary>
procedure AddDisabled(AName: String; const ACollectionName: String); overload;
/// <summary>
/// Insert item from image collection with specifc index, name and image collection item index.
/// if AddDisabledCopies then disabled copy will be added also.
/// </summary>
procedure Insert(AIndex: Integer; AName: String; ACollectionIndex: Integer; AddDisabledCopy: Boolean = False); overload;
/// <summary>
/// Insert item from image collection with specifc index, name and image collection item name.
/// if AddDisabledCopies then disabled copy will be added also.
/// </summary>
procedure Insert(AIndex: Integer; AName: String; const ACollectionName: String; AddDisabledCopy: Boolean = False); overload;
/// <summary>
/// Insert item as disabled copy from image collection with specifc index, name and image collection item index.
/// </summary>
procedure InsertDisabled(AIndex: Integer; AName: String; ACollectionIndex: Integer); overload;
/// <summary>
/// Insert item as disabled copy from image collection with specifc index, name and image collection item name.
/// </summary>
procedure InsertDisabled(AIndex: Integer; AName: String; const ACollectionName: String); overload;
procedure DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer;
Style: Cardinal; Enabled: Boolean = True); override;
/// <summary>
/// Draw image from image list with specific item name.
/// </summary>
procedure Draw(Canvas: TCanvas; X, Y: Integer; Name: String;
Enabled: Boolean = True); overload;
published
/// <summary>
/// Auto fill all items from collection
/// </summary>
property AutoFill: Boolean
read FAutoFill write SetAutoFill default False;
/// <summary>
/// Auto fill mode to load normal or disabled images from collection
/// </summary>
property AutoFillMode: TImageListAutoFillMode
read FAutoFillMode write SetAutoFillMode default afmNormal;
/// <summary>
/// Defines opacity of image if Item.Disabled
/// </summary>
property DisabledOpacity: Byte read FDisabledOpacity write SetDisabledOpacity default 125;
/// <summary>
/// Defines grayscale of image if Item.Disabled
/// </summary>
property DisabledGrayscale: Boolean
read FDisabledGrayScale write SetDisabledGrayscale;
/// <summary>
/// Defines suffix for Item name if Item.Disabled
/// </summary>
property DisabledSuffix: String
read FDisabledSuffix write SetDisabledSuffix;
/// <summary>
/// Collection of items, which defines image list.
/// </summary>
property Images: TVirtualImageListItems
read FImages write FImages;
/// <summary>
/// Image collection component, which uses as source for images.
/// </summary>
property ImageCollection: TCustomImageCollection
read FImageCollection write SetImageCollection;
/// <summary>
/// Preserve items when collection changed
/// </summary>
property PreserveItems: Boolean
read FPreserveItems write SetPreserveItems default False;
/// <summary>
/// Enable and disable scaling with form
/// </summary>
property Scaled: Boolean read FScaled write FScaled default True;
property Width;
property Height;
end;
implementation
Uses System.UITypes, Winapi.CommCtrl;
const
DefaultDisabledSuffix = '_Disabled';
type
PColorRecArray = ^TColorRecArray;
TColorRecArray = array [0..0] of TColorRec;
constructor TVirtualImageListItem.Create(Collection: TCollection);
var
B: TBitmap;
begin
inherited Create(Collection);
FCollectionIndex := -1;
FName := '';
if (ImageList <> nil) and not (csLoading in ImageList.ComponentState) then
begin
B := ImageList.CreateBlankBitmap;
try
ImageList_Add(ImageList.Handle, B.Handle, 0);
finally
B.Free;
end;
end;
end;
destructor TVirtualImageListItem.Destroy;
begin
if FDisabledBitmap <> nil then
FDisabledBitmap.Free;
if (ImageList <> nil) and not (csDestroying in ImageList.ComponentState) and
(Index >= 0) and (Index < ImageList.Count) then
ImageList_Remove(ImageList.Handle, Index);
inherited;
end;
function TVirtualImageList.CreateBlankBitmap: TBitmap;
begin
Result := TBitmap.Create;
Result.PixelFormat := pf32bit;
Result.SetSize(Width, Height);
end;
function TVirtualImageListItem.GetDisabledBitmap: TBitmap;
begin
if (FDisabledBitmap = nil) and (ImageList.ImageCollection <> nil) then
begin
FDisabledBitmap := ImageList.ImageCollection.GetBitmap(FCollectionIndex,
ImageList.Width, ImageList.Height);
ImageList.CreateDisabledBitmap(FDisabledBitmap);
end;
Result := FDisabledBitmap;
end;
procedure TVirtualImageListItem.UpdateDisabledBitmap;
begin
if FDisabledBitmap <> nil then
begin
FreeAndNil(FDisabledBitmap);
GetDisabledBitmap;
end;
end;
function TVirtualImageListItem.CheckCollectionItem: Boolean;
var
FItemIndex: Integer;
begin
Result := False;
if (FCollectionName <> '') and (ImageList.ImageCollection <> nil) then
if (not ImageList.ImageCollection.IsIndexAvailable(FCollectionIndex)) or
(ImageList.ImageCollection.IsIndexAvailable(FCollectionIndex) and
(FCollectionName <> ImageList.ImageCollection.GetNameByIndex(FCollectionIndex)))
then
begin
FItemIndex := ImageList.ImageCollection.GetIndexByName(FCollectionName);
if FItemIndex >= 0 then
FCollectionIndex := FItemIndex
else
FCollectionName := ImageList.ImageCollection.GetNameByIndex(FCollectionIndex);
Result := True;
end;
end;
function TVirtualImageListItem.GetImageList: TVirtualImageList;
begin
Result := TVirtualImageListItems(Collection).ImageList;
end;
procedure TVirtualImageListItem.Update;
var
B: TBitmap;
begin
if (ImageList.ImageCollection <> nil) and
ImageList.ImageCollection.IsIndexAvailable(FCollectionIndex) then
begin
B := ImageList.ImageCollection.GetBitmap(FCollectionIndex,
ImageList.Width, ImageList.Height);
if B <> nil then
begin
if FDisabled then
ImageList.CreateDisabledBitmap(B);
ImageList_Replace(ImageList.Handle, Index, B.Handle, 0);
B.Free;
end;
UpdateDisabledBitmap;
end;
end;
procedure TVirtualImageListItem.SetDisabled(AValue: Boolean);
var
I: Integer;
begin
if FDisabled <> AValue then
begin
FDisabled := AValue;
Update;
if FName <> '' then
begin
I := Pos(ImageList.DisabledSuffix, FName);
if Disabled and (I < 1) then
FName := FName + ImageList.DisabledSuffix
else
if not Disabled and (I > 1) then
Delete(FName, I, Length(ImageList.DisabledSuffix));
end;
end;
end;
procedure TVirtualImageListItem.SetName(const AValue: String);
begin
FName := AValue;
end;
procedure TVirtualImageListItem.SetCollectionIndex(AValue: Integer);
begin
if AValue <> FCollectionIndex then
begin
FCollectionIndex := AValue;
if ImageList.ImageCollection <> nil then
begin
FCollectionName := ImageList.ImageCollection.GetNameByIndex(FCollectionIndex);
FName := FCollectionName;
if FDisabled then
FName := FName + ImageList.DisabledSuffix;
end;
Update;
end;
end;
procedure TVirtualImageListItem.SetCollectionName(const AValue: String);
begin
if FCollectionName <> AValue then
begin
FCollectionName := AValue;
FName := AValue;
if FDisabled then
FName := FName + ImageList.DisabledSuffix;
if (AValue <> '') and (ImageList.ImageCollection <> nil) then
FCollectionIndex := ImageList.ImageCollection.GetIndexByName(FCollectionName);
Update;
end;
end;
function TVirtualImageListItems.GetImageList: TVirtualImageList;
begin
Result := TVirtualImageList(Owner);
end;
function TVirtualImageListItems.GetItem(Index: Integer): TVirtualImageListItem;
begin
Result := TVirtualImageListItem(inherited GetItem(Index));
end;
procedure TVirtualImageListItems.SetItem(Index: Integer; Value: TVirtualImageListItem);
begin
inherited SetItem(Index, Value);
end;
function TVirtualImageListItems.Add: TVirtualImageListItem;
begin
Result := TVirtualImageListItem(inherited Add);
end;
function TVirtualImageListItems.Insert(Index: Integer): TVirtualImageListItem;
var
I: Integer;
begin
Result := TVirtualImageListItem(inherited Insert(Index));
if ImageList.Count > 1 then
for I := ImageList.Count - 2 downto Index do
ImageList_Copy(ImageList.Handle, I, ImageList.Handle, I + 1, ILCF_SWAP);
end;
procedure TVirtualImageListItems.Delete(Index: Integer);
begin
inherited Delete(Index);
end;
constructor TVirtualImageList.Create(AOwner: TComponent);
begin
inherited;
FDisabledSuffix := DefaultDisabledSuffix;
StoreBitmap := False;
FPreserveItems := False;
FAutoFill := False;
FAutoFillMode := afmNormal;
FDisabledOpacity := 125;
FScaled := True;
ColorDepth := cd32bit;
FImages := TVirtualImageListItems.Create(Self, TVirtualImageListItem);
FDPIChangedMessageID := TMessageManager.DefaultManager.SubscribeToMessage(TChangeScaleMessage, DPIChangedMessageHandler);
FCollectionChangedMessageID := TMessageManager.DefaultManager.SubscribeToMessage(TImageCollectionChangedMessage, CollectionChangedMessageHandler);
end;
destructor TVirtualImageList.Destroy;
begin
TMessageManager.DefaultManager.Unsubscribe(TChangeScaleMessage, FDPIChangedMessageID);
TMessageManager.DefaultManager.Unsubscribe(TImageCollectionChangedMessage, FCollectionChangedMessageID);
FImages.Free;
inherited;
end;
procedure TVirtualImageList.Assign(Source: TPersistent);
var
I: Integer;
IL: TVirtualImageList;
Item: TVirtualImageListItem;
begin
if Source is TVirtualImageList then
begin
IL := TVirtualImageList(Source);
FImageCollection := IL.ImageCollection;
FDisabledOpacity := IL.DisabledOpacity;
FDisabledGrayscale := IL.DisabledGrayscale;
FDisabledSuffix := IL.DisabledSuffix;
FAutoFill := IL.AutoFill;
FAutoFillMode := IL.AutoFillMode;
FImageListUpdating := True;
try
FImages.Clear;
for I := 0 to IL.Images.Count - 1 do
begin
Item := FImages.Add;
Item.FDisabled := IL.Images[I].Disabled;
Item.CollectionIndex := IL.Images[I].CollectionIndex;
Item.Name := IL.Images[I].Name;
end;
finally
Change;
FImageListUpdating := False;
end;
end
else
inherited;
end;
procedure TVirtualImageList.Clear;
begin
FImageListUpdating := True;
try
FImages.Clear;
Change;
finally
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.Delete(AIndex: Integer);
begin
if (AIndex < 0) or (AIndex > FImages.Count - 1) then
Exit;
FImageListUpdating := True;
try
FImages.Delete(AIndex);
finally
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.Delete(const AName: String);
begin
FImages.Delete(GetIndexByName(AName));
end;
function TVirtualImageList.IsImageCollectionAvailable: Boolean;
begin
Result := (FImageCollection <> nil) and (FImageCollection.Count > 0);
end;
procedure TVirtualImageList.DoAutoFill;
begin
case FAutoFillMode of
afmNormal:
Add('', -1, -1, False);
afmDisabled:
AddDisabled('', -1, -1);
end;
end;
procedure TVirtualImageList.Add(const ACategory: String; AStartIndex, AEndIndex: Integer; AddDisabledCopies: Boolean = False);
var
I: Integer;
Item: TVirtualImageListItem;
S: String;
begin
if not IsImageCollectionAvailable then
Exit;
if (ACategory = '') and ( AStartIndex < 0) and (AEndIndex < 0) and (FImages.Count > 0) then
begin
FImages.Clear;
ImageList_Remove(Handle, -1);
end;
if AStartIndex < 0 then
AStartIndex := 0;
if (AEndIndex < 0) or (AEndIndex > FImageCollection.Count - 1) then
AEndIndex := FImageCollection.Count - 1;
FImageListUpdating := True;
BeginUpdate;
try
for I := AStartIndex to AEndIndex do
begin
S := FImageCollection.GetNameByIndex(I);
if (ACategory = '') or
(LowerCase(ACategory) = LowerCase(ExtractImageCollectionCategory(S))) then
begin
Item := FImages.Add;
Item.FName := S;
Item.CollectionIndex := I;
if AddDisabledCopies then
begin
Item := FImages.Add;
Item.FName := S + FDisabledSuffix;
Item.FDisabled := True;
Item.CollectionIndex := I;
end;
end;
end;
finally
EndUpdate;
Change;
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.Add(AName: String; ACollectionIndex: Integer; AddDisabledCopy: Boolean = False);
var
Item: TVirtualImageListItem;
begin
if not IsImageCollectionAvailable or not FImageCollection.IsIndexAvailable(ACollectionIndex) then
Exit;
FImageListUpdating := True;
BeginUpdate;
try
if AName = '' then
AName := ExtractImageCollectionName(FImageCollection.GetNameByIndex(ACollectionIndex));
Item := FImages.Add;
Item.CollectionIndex := ACollectionIndex;
Item.FName := AName;
if AddDisabledCopy then
begin
Item := FImages.Add;
Item.CollectionIndex := ACollectionIndex;
Item.FName := AName + FDisabledSuffix;
Item.FDisabled := True;
end;
finally
EndUpdate;
Change;
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.Add(AName: String; const ACollectionName: String; AddDisabledCopy: Boolean = False);
begin
Add(AName, FImageCollection.GetIndexByName(ACollectionName), AddDisabledCopy);
end;
procedure TVirtualImageList.Insert(AIndex: Integer; AName: String; ACollectionIndex: Integer; AddDisabledCopy: Boolean = False);
var
Item: TVirtualImageListItem;
begin
if not IsImageCollectionAvailable or not FImageCollection.IsIndexAvailable(ACollectionIndex) or
(AIndex < 0) or (AIndex > FImages.Count - 1) then
Exit;
FImageListUpdating := True;
BeginUpdate;
try
if AName = '' then
AName := ExtractImageCollectionName(FImageCollection.GetNameByIndex(ACollectionIndex));
if AddDisabledCopy then
begin
Item := FImages.Insert(AIndex);
Item.CollectionIndex := ACollectionIndex;
Item.FName := AName + FDisabledSuffix;
Item.FDisabled := True;
end;
Item := FImages.Insert(AIndex);
Item.CollectionIndex := ACollectionIndex;
Item.FName := AName;
finally
EndUpdate;
Change;
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.Insert(AIndex: Integer; AName: String; const ACollectionName: String; AddDisabledCopy: Boolean = False);
begin
Insert(AIndex, AName, FImageCollection.GetIndexByName(ACollectionName), AddDisabledCopy);
end;
procedure TVirtualImageList.AddDisabled(const ACategory: String; AStartIndex, AEndIndex: Integer);
var
I: Integer;
Item: TVirtualImageListItem;
S: String;
begin
if not IsImageCollectionAvailable then
Exit;
if (ACategory = '') and (AStartIndex < 0) and (AEndIndex < 0) and (FImages.Count > 0) then
begin
FImages.Clear;
ImageList_Remove(Handle, -1);
end;
if AStartIndex < 0 then
AStartIndex := 0;
if (AEndIndex < 0) or (AEndIndex > FImageCollection.Count - 1) then
AEndIndex := FImageCollection.Count - 1;
FImageListUpdating := True;
BeginUpdate;
try
for I := AStartIndex to AEndIndex do
begin
S := FImageCollection.GetNameByIndex(I);
if (ACategory = '') or
(LowerCase(ACategory) = LowerCase(ExtractImageCollectionCategory(S))) then
begin
Item := FImages.Add;
Item.CollectionIndex := I;
Item.FName := S;
Item.FDisabled := True;
end;
end;
finally
EndUpdate;
Change;
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.AddDisabled(AName: String; ACollectionIndex: Integer);
var
Item: TVirtualImageListItem;
begin
if not IsImageCollectionAvailable or not FImageCollection.IsIndexAvailable(ACollectionIndex) then
Exit;
FImageListUpdating := True;
BeginUpdate;
try
if AName = '' then
AName := ExtractImageCollectionName(FImageCollection.GetNameByIndex(ACollectionIndex));
Item := FImages.Add;
Item.CollectionIndex := ACollectionIndex;
Item.FName := AName + FDisabledSuffix;
Item.FDisabled := True;
finally
EndUpdate;
Change;
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.AddDisabled(AName: String; const ACollectionName: String);
begin
AddDisabled(AName, FImageCollection.GetIndexByName(ACollectionName));
end;
procedure TVirtualImageList.InsertDisabled(AIndex: Integer; AName: String; ACollectionIndex: Integer);
var
Item: TVirtualImageListItem;
begin
if not IsImageCollectionAvailable or not FImageCollection.IsIndexAvailable(ACollectionIndex) or
(AIndex < 0) or (AIndex > FImages.Count - 1) then
Exit;
FImageListUpdating := True;
BeginUpdate;
try
if AName = '' then
AName := ExtractImageCollectionName(FImageCollection.GetNameByIndex(ACollectionIndex));
Item := FImages.Insert(AIndex);
Item.CollectionIndex := ACollectionIndex;
Item.FName := AName + FDisabledSuffix;
Item.FDisabled := True;
finally
EndUpdate;
Change;
FImageListUpdating := False;
end;
end;
procedure TVirtualImageList.InsertDisabled(AIndex: Integer; AName: String; const ACollectionName: String);
begin
InsertDisabled(AIndex, AName, FImageCollection.GetIndexByName(ACollectionName));
end;
procedure TVirtualImageList.DPIChangedMessageHandler(const Sender: TObject; const Msg: System.Messaging.TMessage);
var
W, H: Integer;
begin
if FScaled and (TChangeScaleMessage(Msg).Sender = Owner) then
begin
W := MulDiv(Width, TChangeScaleMessage(Msg).M, TChangeScaleMessage(Msg).D);
H := MulDiv(Height, TChangeScaleMessage(Msg).M, TChangeScaleMessage(Msg).D);
FScaling := True;
try
SetSize(W, H);
finally
FScaling := False;
end;
end;
end;
procedure TVirtualImageList.CollectionChangedMessageHandler(const Sender: TObject; const Msg: System.Messaging.TMessage);
var
I: Integer;
ColIndex, IndexFromCol: Integer;
ColName: String;
begin
if TImageCollectionChangedMessage(Msg).Collection = FImageCollection then
begin
if FAutoFill then
DoAutoFill
else
if TImageCollectionChangedMessage(Msg).Index < 0 then
Change
else
begin
ColIndex := TImageCollectionChangedMessage(Msg).Index;
ColName := TImageCollectionChangedMessage(Msg).Name;
FImageListUpdating := True;
try
for I := 0 to FImages.Count - 1 do
if FImages[I].CollectionIndex = ColIndex then
if FImages[I].CollectionName = ColName then
FImages[I].Update
else
if ColName <> '' then
begin
IndexFromCol := TImageCollectionChangedMessage(Msg).Collection.GetIndexByName(ColName);
if IndexFromCol = FImages[I].CollectionIndex then
begin
FImages[I].CollectionName := ColName;
FImages[I].Update
end
else
begin
FImageListUpdating := False;
Break;
end;
end;
finally
Change;
FImageListUpdating := False;
end;
end;
end;
end;
procedure TVirtualImageList.SetDisabledSuffix(Value: String);
var
I, P: Integer;
begin
if Value = '' then
Value := DefaultDisabledSuffix;
if FDisabledSuffix <> Value then
begin
for I := 0 to FImages.Count - 1 do
if FImages[I].Disabled then
begin
P := Pos(FDisabledSuffix, FImages[I].Name);
if P > 0 then
begin
System.Delete(FImages[I].FName, P, Length(FDisabledSuffix));
FImages[I].FName := FImages[I].FName + Value;
end;
end;
FDisabledSuffix := Value;
end;
end;
procedure TVirtualImageList.SetDisabledGrayscale(Value: Boolean);
begin
if FDisabledGrayscale <> Value then
begin
FDisabledGrayscale := Value;
UpdateDisabledBitmaps;
end;
end;
procedure TVirtualImageList.SetDisabledOpacity(Value: Byte);
begin
if (Value > 0) and (FDisabledOpacity <> Value) then
begin
FDisabledOpacity := Value;
UpdateDisabledBitmaps;
end;
end;
procedure TVirtualImageList.Loaded;
begin
inherited;
if FAutoFill then
DoAutoFill
else
UpdateImageList;
end;
procedure TVirtualImageList.SetAutoFill(Value: Boolean);
begin
if FAutoFill <> Value then
begin
FAutoFill := Value;
if not (csLoading in ComponentState) and FAutoFill then
DoAutoFill;
end;
end;
procedure TVirtualImageList.SetAutoFillMode(Value: TImageListAutoFillMode);
begin
if FAutoFillMode <> Value then
begin
FAutoFillMode := Value;
if not (csLoading in ComponentState) and FAutoFill then
DoAutoFill;
end;
end;
procedure TVirtualImageList.SetPreserveItems(Value: Boolean);
begin
if FPreserveItems <> Value then
begin
FPreserveItems := Value;
if not FPreserveItems and (FImageCollection = nil) and (Images.Count > 0) then
Clear;
end;
end;
procedure TVirtualImageList.SetImageCollection(Value: TCustomImageCollection);
var
CanClear: Boolean;
begin
if FImageCollection <> Value then
begin
CanClear := not FPreserveItems and ((FImageCollection <> nil) or (Value = nil));
FImageCollection := Value;
if not (csLoading in ComponentState) then
begin
if CanClear then
Images.Clear;
if FAutoFill then
DoAutoFill
else
UpdateImageList;
end;
end;
end;
procedure TVirtualImageList.CreateDisabledBitmap(ABitmap: TBitmap);
var
I: Integer;
Src: Pointer;
Gray: Byte;
begin
{$RANGECHECKS OFF}
Src := ABitmap.Scanline[ABitmap.Height - 1];
for I := 0 to ABitmap.Width * ABitmap.Height - 1 do
begin
if FDisabledOpacity < 255 then
PColorRecArray(Src)[I].A := Round(PColorRecArray(Src)[I].A * FDisabledOpacity / 255);
if FDisabledGrayscale then
begin
Gray := Round(
(0.299 * PColorRecArray(Src)[I].R) +
(0.587 * PColorRecArray(Src)[I].G) +
(0.114 * PColorRecArray(Src)[I].B));
PColorRecArray(Src)[I].R := Gray;
PColorRecArray(Src)[I].G := Gray;
PColorRecArray(Src)[I].B := Gray;
end;
end;
{$RANGECHECKS ON}
end;
procedure TVirtualImageList.UpdateDisabledBitmaps;
var
I: Integer;
begin
for I := 0 to FImages.Count - 1 do
if FImages[I].Disabled then
FImages[I].Update
else
FImages[I].UpdateDisabledBitmap;
end;
procedure TVirtualImageList.UpdateImageList;
var
I: Integer;
B: TBitmap;
begin
ImageList_Remove(Handle, -1);
if FImageCollection = nil then
Exit;
for I := 0 to FImages.Count - 1 do
begin
FImages[I].CheckCollectionItem;
B := FImageCollection.GetBitmap(FImages[I].CollectionIndex,
Width, Height);
if B = nil then
B := CreateBlankBitmap
else
if (B <> nil) and FImages[I].Disabled then
CreateDisabledBitmap(B);
try
ImageList_Add(Handle, B.Handle, 0);
finally
B.Free;
end;
FImages[I].UpdateDisabledBitmap;
end;
end;
function TVirtualImageList.GetIndexByName(const AName: String): Integer;
var
I: Integer;
S: String;
begin
Result := -1;
S := LowerCase(AName);
for I := 0 to FImages.Count - 1 do
if LowerCase(FImages[I].Name) = S then
Exit(I);
end;
procedure TVirtualImageList.DoChange;
begin
if not FImageListUpdating then
UpdateImageList;
inherited;
end;
procedure TVirtualImageList.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FImageCollection) then
ImageCollection := nil;
end;
procedure TVirtualImageList.DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer;
Style: Cardinal; Enabled: Boolean = True);
var
B: TBitmap;
BF: TBlendFunction;
begin
if (Index < 0) or (Index >= Count) or (Index >= Images.Count) then
Exit;
if Enabled then
ImageList_Draw(Handle, Index, Canvas.Handle, X, Y, ILD_NORMAL)
else
begin
B := Images[Index].DisabledBitmap;
if B <> nil then
begin
B.AlphaFormat := afPremultiplied;
BF.BlendOp := AC_SRC_OVER;
BF.BlendFlags := 0;
BF.SourceConstantAlpha := 255;
BF.AlphaFormat := AC_SRC_ALPHA;
Winapi.Windows.AlphaBlend(Canvas.Handle, X, Y, B.Width, B.Height,
B.Canvas.Handle, 0, 0, B.Width, B.Height, BF);
end
else
ImageList_Draw(Handle, Index, Canvas.Handle, X, Y, ILD_NORMAL);
end;
end;
procedure TVirtualImageList.Draw(Canvas: TCanvas; X, Y: Integer; Name: String;
Enabled: Boolean = True);
begin
if HandleAllocated then
DoDraw(GetIndexByName(Name), Canvas, X, Y, ILD_NORMAL, Enabled);
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.DBXSybaseASEMetaDataReader;
interface
uses
Data.DBXCommon,
Data.DBXCommonTable,
Data.DBXMetaDataNames,
Data.DBXMetaDataReader,
Data.DBXPlatform;
type
/// <summary> TDBXAseCustomMetaDataReader contains custom code for Adaptive Server Enterprise.
/// </summary>
TDBXSybaseASECustomMetaDataReader = class abstract(TDBXBaseMetaDataReader)
public
type
/// <summary> TDBXSybaseASEForeignKeyColumnsCursor is a filter for a cursor providing foreign key columns.
/// </summary>
/// <remarks> In Adaptive Server Enterprise all the columns of a foreign key relation are given in one row
/// of the sysreferences system table.
/// This filter will extract them into a separate rows as expected by the foreign key metadata collection.
/// Also note: there is a hard limit of 16 sub queries in this database. That is why the foreign key
/// columns and the primary key columns are split into 2 queries.
/// </remarks>
TDBXSybaseASEForeignKeyColumnsCursor = class(TDBXCustomMetaDataTable)
public
destructor Destroy; override;
function Next: Boolean; override;
protected
constructor Create(const Provider: TDBXSybaseASECustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor1: TDBXTable; const Cursor2: TDBXTable);
function GetWritableValue(const Ordinal: Integer): TDBXWritableValue; override;
private
FCursor2: TDBXTable;
FKeyIndex: Integer;
FKeyColumnCount: Integer;
FRow: TDBXSingleValueRow;
private
const OrdinalKeyColumnCount = TDBXForeignKeyColumnsIndex.Ordinal;
const OrdinalFirstColumn = TDBXForeignKeyColumnsIndex.Last + 1;
end;
public
/// <summary> Overrides the implementation in TDBXBaseMetaDataProvider.
/// </summary>
/// <remarks> A custom filter is added to extract the column names into separate rows.
/// </remarks>
/// <seealso cref="TDBXSybaseAseForeignKeyColumnsCursor"/>
function FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable; override;
protected
/// <summary> Second part of the foreign key column SQL query.
/// </summary>
/// <remarks> A concrete super class of TDBXSybaseASECustomMetaDataReader must implement this
/// property and supply a query that includes the column names of the table being referenced.
/// </remarks>
function GetSqlForForeignKeyColumnsPart2: string; virtual; abstract;
protected
/// <summary> Second part of the foreign key column SQL query.
/// </summary>
/// <remarks> A concrete super class of TDBXSybaseASECustomMetaDataReader must implement this
/// property and supply a query that includes the column names of the table being referenced.
/// </remarks>
property SqlForForeignKeyColumnsPart2: string read GetSqlForForeignKeyColumnsPart2;
end;
TDBXSybaseASEMetaDataReader = class(TDBXSybaseASECustomMetaDataReader)
public
function FetchCatalogs: TDBXTable; override;
function FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable; override;
function FetchSynonyms(const CatalogName: string; const SchemaName: string; const SynonymName: string): TDBXTable; override;
function FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override;
function FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable; override;
function FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable; override;
function FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable; override;
protected
function AreSchemasSupported: Boolean; override;
function GetProductName: string; override;
function GetTableType: string; override;
function GetViewType: string; override;
function GetSystemTableType: string; override;
function IsLowerCaseIdentifiersSupported: Boolean; override;
function IsUpperCaseIdentifiersSupported: Boolean; override;
function IsNestedTransactionsSupported: Boolean; override;
function GetSqlIdentifierQuoteChar: string; override;
function GetSqlProcedureQuoteChar: string; override;
function GetSqlIdentifierQuotePrefix: string; override;
function GetSqlIdentifierQuoteSuffix: string; override;
function IsSetRowSizeSupported: Boolean; override;
function IsParameterMetadataSupported: Boolean; override;
function GetSqlForSchemas: string; override;
function GetSqlForTables: string; override;
function GetSqlForViews: string; override;
function GetSqlForColumns: string; override;
function GetSqlForIndexes: string; override;
function GetSqlForIndexColumns: string; override;
function GetSqlForForeignKeys: string; override;
function GetSqlForForeignKeyColumns: string; override;
function GetSqlForForeignKeyColumnsPart2: string; override;
function GetSqlForProcedures: string; override;
function GetSqlForProcedureSources: string; override;
function GetSqlForProcedureParameters: string; override;
function GetSqlForUsers: string; override;
function GetSqlForRoles: string; override;
function GetDataTypeDescriptions: TDBXDataTypeDescriptionArray; override;
function GetReservedWords: TDBXStringArray; override;
end;
implementation
uses
System.SysUtils;
function TDBXSybaseASECustomMetaDataReader.FetchForeignKeyColumns(const Catalog: string; const Schema: string; const Table: string; const ForeignKeyName: string; const PrimaryCatalog: string; const PrimarySchema: string; const PrimaryTable: string; const PrimaryKeyName: string): TDBXTable;
var
ParameterNames, ParameterValues: TDBXStringArray;
Cursor1, Cursor2: TDBXTable;
Columns: TDBXValueTypeArray;
begin
SetLength(ParameterNames,8);
ParameterNames[0] := TDBXParameterName.CatalogName;
ParameterNames[1] := TDBXParameterName.SchemaName;
ParameterNames[2] := TDBXParameterName.TableName;
ParameterNames[3] := TDBXParameterName.ForeignKeyName;
ParameterNames[4] := TDBXParameterName.PrimaryCatalogName;
ParameterNames[5] := TDBXParameterName.PrimarySchemaName;
ParameterNames[6] := TDBXParameterName.PrimaryTableName;
ParameterNames[7] := TDBXParameterName.PrimaryKeyName;
SetLength(ParameterValues,8);
ParameterValues[0] := Catalog;
ParameterValues[1] := Schema;
ParameterValues[2] := Table;
ParameterValues[3] := ForeignKeyName;
ParameterValues[4] := PrimaryCatalog;
ParameterValues[5] := PrimarySchema;
ParameterValues[6] := PrimaryTable;
ParameterValues[7] := PrimaryKeyName;
Cursor1 := Context.ExecuteQuery(SqlForForeignKeyColumns, ParameterNames, ParameterValues);
Cursor2 := Context.ExecuteQuery(SqlForForeignKeyColumnsPart2, ParameterNames, ParameterValues);
Columns := TDBXMetaDataCollectionColumns.CreateForeignKeyColumnsColumns;
Result := TDBXSybaseASECustomMetaDataReader.TDBXSybaseASEForeignKeyColumnsCursor.Create(self, Columns, Cursor1, Cursor2);
end;
constructor TDBXSybaseASECustomMetaDataReader.TDBXSybaseASEForeignKeyColumnsCursor.Create(const Provider: TDBXSybaseASECustomMetaDataReader; const Columns: TDBXValueTypeArray; const Cursor1: TDBXTable; const Cursor2: TDBXTable);
begin
inherited Create(Provider.Context, TDBXMetaDataCollectionName.ForeignKeyColumns, Columns, Cursor1);
self.FCursor2 := Cursor2;
FRow := TDBXSingleValueRow.Create;
FRow.Columns := CopyColumns;
end;
destructor TDBXSybaseASECustomMetaDataReader.TDBXSybaseASEForeignKeyColumnsCursor.Destroy;
begin
FreeAndNil(FRow);
FreeAndNil(FCursor2);
inherited Destroy;
end;
function TDBXSybaseASECustomMetaDataReader.TDBXSybaseASEForeignKeyColumnsCursor.Next: Boolean;
begin
repeat
IncrAfter(FKeyIndex);
if FKeyIndex >= FKeyColumnCount then
begin
if not inherited Next then
Exit(False);
if not FCursor2.Next then
Exit(False);
FKeyIndex := 0;
FKeyColumnCount := FCursor.Value[OrdinalKeyColumnCount].AsInt32;
end;
until FKeyIndex < FKeyColumnCount;
if FCursor.Value[OrdinalFirstColumn + FKeyIndex].IsNull then
FRow.Value[TDBXForeignKeyColumnsIndex.ColumnName].SetNull
else
FRow.Value[TDBXForeignKeyColumnsIndex.ColumnName].AsString := FCursor.Value[OrdinalFirstColumn + FKeyIndex].AsString;
if FCursor2.Value[OrdinalFirstColumn + FKeyIndex].IsNull then
FRow.Value[TDBXForeignKeyColumnsIndex.PrimaryColumnName].SetNull
else
FRow.Value[TDBXForeignKeyColumnsIndex.PrimaryColumnName].AsString := FCursor2.Value[OrdinalFirstColumn + FKeyIndex].AsString;
FRow.Value[TDBXForeignKeyColumnsIndex.Ordinal].AsInt32 := FKeyIndex + 1;
Result := True;
end;
function TDBXSybaseASECustomMetaDataReader.TDBXSybaseASEForeignKeyColumnsCursor.GetWritableValue(const Ordinal: Integer): TDBXWritableValue;
begin
case Ordinal of
TDBXForeignKeyColumnsIndex.ColumnName,
TDBXForeignKeyColumnsIndex.PrimaryColumnName,
TDBXForeignKeyColumnsIndex.Ordinal:
Exit(FRow.Value[Ordinal]);
end;
Result := inherited GetWritableValue(Ordinal);
end;
function TDBXSybaseASEMetaDataReader.AreSchemasSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASEMetaDataReader.GetProductName: string;
begin
Result := 'Sybase SQL Server';
end;
function TDBXSybaseASEMetaDataReader.GetTableType: string;
begin
Result := 'U';
end;
function TDBXSybaseASEMetaDataReader.GetViewType: string;
begin
Result := 'V';
end;
function TDBXSybaseASEMetaDataReader.GetSystemTableType: string;
begin
Result := 'S';
end;
function TDBXSybaseASEMetaDataReader.IsLowerCaseIdentifiersSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASEMetaDataReader.IsUpperCaseIdentifiersSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASEMetaDataReader.IsNestedTransactionsSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASEMetaDataReader.GetSqlIdentifierQuoteChar: string;
begin
Result := '';
end;
function TDBXSybaseASEMetaDataReader.GetSqlProcedureQuoteChar: string;
begin
Result := '';
end;
function TDBXSybaseASEMetaDataReader.GetSqlIdentifierQuotePrefix: string;
begin
Result := '';
end;
function TDBXSybaseASEMetaDataReader.GetSqlIdentifierQuoteSuffix: string;
begin
Result := '';
end;
function TDBXSybaseASEMetaDataReader.IsSetRowSizeSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASEMetaDataReader.IsParameterMetadataSupported: Boolean;
begin
Result := True;
end;
function TDBXSybaseASEMetaDataReader.FetchCatalogs: TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateCatalogsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Catalogs, Columns);
end;
function TDBXSybaseASEMetaDataReader.GetSqlForSchemas: string;
begin
Result := 'SELECT DISTINCT DB_NAME(), USER_NAME(uid) ' +
'FROM dbo.sysobjects ' +
'WHERE type IN (''U'', ''V'', ''S'', ''P'', ''FN'', ''IF'', ''TF'') ' +
'ORDER BY 1, 2';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForTables: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(uid), name, CASE WHEN type=''U'' THEN ''TABLE'' WHEN type=''V'' THEN ''VIEW'' ELSE ''SYSTEM TABLE'' END ' +
'FROM dbo.sysobjects ' +
'WHERE type IN (''U'', ''V'', ''S'') ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
' AND (type = :TABLES OR type = :VIEWS OR type = :SYSTEM_TABLES) ' +
'ORDER BY 1, 2, 3';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForViews: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(uid), name, text, colid AS SOURCE_LINE_NUMBER ' +
'FROM dbo.sysobjects o, dbo.syscomments c ' +
'WHERE o.id = c.id AND type = ''V'' ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (name = :VIEW_NAME OR (:VIEW_NAME IS NULL)) ' +
'ORDER BY 1,2,3,5';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForColumns: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(o.uid), o.name, c.name, CASE WHEN t.name=''float'' THEN ''double precision'' ELSE t.name END, COALESCE(c.prec,c.length), c.scale, c.colid, CASE WHEN com.text LIKE ''DEFAULT %'' THEN SUBSTRING(com.text,10,CHAR_LENGTH(com.text)-9) ELS' + 'E com.text END, c.status & 8, c.status & 128, NULL ' +
'FROM dbo.sysobjects o INNER JOIN dbo.syscolumns c ON o.id=c.id INNER JOIN dbo.systypes t ON c.usertype = t.usertype LEFT OUTER JOIN dbo.syscomments com ON cdefault=com.id ' +
'WHERE o.type IN (''U'',''V'',''S'') ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(o.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (o.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, c.colid';
end;
function TDBXSybaseASEMetaDataReader.FetchColumnConstraints(const CatalogName: string; const SchemaName: string; const TableName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateColumnConstraintsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.ColumnConstraints, Columns);
end;
function TDBXSybaseASEMetaDataReader.GetSqlForIndexes: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(o.uid), o.name, i.name, CASE WHEN status&2 > 0 THEN i.name ELSE NULL END, status&2048, status&2, 1 ' +
'FROM dbo.sysobjects o, dbo.sysindexes i ' +
'WHERE o.type IN (''U'',''S'') AND i.id = o.id and keycnt <> 0 ' +
' AND (DB_NAME() = :CATALOG_NAME or (:CATALOG_NAME IS NULL)) AND (USER_NAME(o.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (o.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, 4';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForIndexColumns: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(o.uid), o.name, i.name, index_col(o.name, i.indid, cn.id, o.uid), cn.id, CASE WHEN index_colorder(o.name, i.indid, cn.id, o.uid) = ''ASC'' THEN 1 ELSE 0 END ' +
'FROM dbo.sysobjects o, dbo.sysindexes i, dbo.sysobjects cn ' +
'WHERE o.type IN (''U'',''S'') AND i.id = o.id AND cn.id > 0 AND cn.id <= i.keycnt - CASE WHEN i.indid=1 THEN 0 ELSE 1 END ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(o.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (o.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (i.name = :INDEX_NAME OR (:INDEX_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, 4, 6';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForForeignKeys: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(ft.uid), ft.name, fk.name ' +
'FROM dbo.sysreferences r, dbo.sysobjects fk, dbo.sysobjects ft ' +
'WHERE r.tableid=ft.id AND r.constrid=fk.id ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(ft.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (ft.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, 4';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForForeignKeyColumns: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(ft.uid), ft.name, fk.name, NULL, DB_NAME(), USER_NAME(pt.uid), pt.name, pi.name, NULL, r.keycnt, ' +
' CASE WHEN r.fokey1=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey1) END, ' +
' CASE WHEN r.fokey2=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey2) END, ' +
' CASE WHEN r.fokey3=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey3) END, ' +
' CASE WHEN r.fokey4=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey4) END, ' +
' CASE WHEN r.fokey5=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey5) END, ' +
' CASE WHEN r.fokey6=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey6) END, ' +
' CASE WHEN r.fokey7=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey7) END, ' +
' CASE WHEN r.fokey8=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey8) END, ' +
' CASE WHEN r.fokey9=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey9) END, ' +
' CASE WHEN r.fokey10=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey10) END, ' +
' CASE WHEN r.fokey11=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey11) END, ' +
' CASE WHEN r.fokey12=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey12) END, ' +
' CASE WHEN r.fokey13=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey13) END, ' +
' CASE WHEN r.fokey14=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey14) END, ' +
' CASE WHEN r.fokey15=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey15) END, ' +
' CASE WHEN r.fokey16=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=ft.id AND c.colid=r.fokey16) END ' +
'FROM dbo.sysreferences r, dbo.sysobjects fk, dbo.sysobjects ft, dbo.sysobjects pt, dbo.sysindexes pi ' +
'WHERE r.tableid=ft.id AND r.constrid=fk.id AND r.reftabid=pt.id AND r.reftabid=pi.id AND r.indexid=pi.indid ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(ft.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (ft.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (fk.name = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' +
' AND (DB_NAME() = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (USER_NAME(pt.uid) = :PRIMARY_SCHEMA_NAME OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (pt.name = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (pi.name = :PRIMARY_KEY_N' + 'AME OR (:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, 4';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForForeignKeyColumnsPart2: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(ft.uid), ft.name, fk.name, NULL, DB_NAME(), USER_NAME(pt.uid), pt.name, pi.name, NULL, r.keycnt, ' +
' CASE WHEN r.refkey1=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey1) END, ' +
' CASE WHEN r.refkey2=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey2) END, ' +
' CASE WHEN r.refkey3=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey3) END, ' +
' CASE WHEN r.refkey4=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey4) END, ' +
' CASE WHEN r.refkey5=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey5) END, ' +
' CASE WHEN r.refkey6=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey6) END, ' +
' CASE WHEN r.refkey7=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey7) END, ' +
' CASE WHEN r.refkey8=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey8) END, ' +
' CASE WHEN r.refkey9=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey9) END, ' +
' CASE WHEN r.refkey10=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey10) END, ' +
' CASE WHEN r.refkey11=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey11) END, ' +
' CASE WHEN r.refkey12=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey12) END, ' +
' CASE WHEN r.refkey13=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey13) END, ' +
' CASE WHEN r.refkey14=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey14) END, ' +
' CASE WHEN r.refkey15=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey15) END, ' +
' CASE WHEN r.refkey16=0 THEN NULL ELSE (SELECT c.name from dbo.syscolumns c where c.id=pt.id AND c.colid=r.refkey16) END ' +
'FROM dbo.sysreferences r, dbo.sysobjects fk, dbo.sysobjects ft, dbo.sysobjects pt, dbo.sysindexes pi ' +
'WHERE r.tableid=ft.id AND r.constrid=fk.id AND r.reftabid=pt.id AND r.reftabid=pi.id AND r.indexid=pi.indid ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(ft.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (ft.name = :TABLE_NAME OR (:TABLE_NAME IS NULL)) AND (fk.name = :FOREIGN_KEY_NAME OR (:FOREIGN_KEY_NAME IS NULL)) ' +
' AND (DB_NAME() = :PRIMARY_CATALOG_NAME OR (:PRIMARY_CATALOG_NAME IS NULL)) AND (USER_NAME(pt.uid) = :PRIMARY_SCHEMA_NAME OR (:PRIMARY_SCHEMA_NAME IS NULL)) AND (pt.name = :PRIMARY_TABLE_NAME OR (:PRIMARY_TABLE_NAME IS NULL)) AND (pi.name = :PRIMARY_KEY_N' + 'AME OR (:PRIMARY_KEY_NAME IS NULL)) ' +
'ORDER BY 1, 2, 3, 4';
end;
function TDBXSybaseASEMetaDataReader.FetchSynonyms(const CatalogName: string; const SchemaName: string; const SynonymName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreateSynonymsColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Synonyms, Columns);
end;
function TDBXSybaseASEMetaDataReader.GetSqlForProcedures: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(uid), name, CASE WHEN type=''F'' THEN ''FUNCTION'' ELSE ''PROCEDURE'' END ' +
'FROM dbo.sysobjects ' +
'WHERE type in (''P'', ''F'', ''XP'') ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (name = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (CASE WHEN type=''F'' THEN ''FUNCTION'' ELSE ''PROCEDURE'' END = :PROCEDURE_T' + 'YPE OR (:PROCEDURE_TYPE IS NULL)) ' +
'ORDER BY 1,2,3';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForProcedureSources: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(uid), name, CASE WHEN type=''F'' THEN ''FUNCTION'' ELSE ''PROCEDURE'' END, text, NULL, colid AS SOURCE_LINE_NUMBER ' +
'FROM dbo.sysobjects o, dbo.syscomments c ' +
'WHERE o.id = c.id AND type IN (''P'',''F'',''XP'') ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(o.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (o.name = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) ' +
'ORDER BY 1,2,3,colid';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForProcedureParameters: string;
begin
Result := 'SELECT DB_NAME(), USER_NAME(o.uid), o.name, c.name, case c.status2 when 2 then ''OUT'' else ''IN'' end, CASE WHEN t.name=''float'' THEN ''double precision'' ELSE t.name END, COALESCE(c.prec,c.length), c.scale, c.colid, 1 ' +
'FROM dbo.sysobjects o, dbo.syscolumns c, dbo.systypes t ' +
'WHERE o.id = c.id AND o.type IN (''P'',''F'',''XP'') AND t.usertype = c.usertype ' +
' AND (DB_NAME() = :CATALOG_NAME OR (:CATALOG_NAME IS NULL)) AND (USER_NAME(o.uid) = :SCHEMA_NAME OR (:SCHEMA_NAME IS NULL)) AND (o.name = :PROCEDURE_NAME OR (:PROCEDURE_NAME IS NULL)) AND (c.name = :PARAMETER_NAME OR (:PARAMETER_NAME IS NULL)) ' +
'ORDER BY 1,2,3,c.colid';
end;
function TDBXSybaseASEMetaDataReader.FetchPackages(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackagesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.Packages, Columns);
end;
function TDBXSybaseASEMetaDataReader.FetchPackageProcedures(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ProcedureType: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProceduresColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedures, Columns);
end;
function TDBXSybaseASEMetaDataReader.FetchPackageProcedureParameters(const CatalogName: string; const SchemaName: string; const PackageName: string; const ProcedureName: string; const ParameterName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageProcedureParametersColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageProcedureParameters, Columns);
end;
function TDBXSybaseASEMetaDataReader.FetchPackageSources(const CatalogName: string; const SchemaName: string; const PackageName: string): TDBXTable;
var
Columns: TDBXValueTypeArray;
begin
Columns := TDBXMetaDataCollectionColumns.CreatePackageSourcesColumns;
Result := TDBXEmptyTableCursor.Create(TDBXMetaDataCollectionName.PackageSources, Columns);
end;
function TDBXSybaseASEMetaDataReader.GetSqlForUsers: string;
begin
Result := 'SELECT name FROM dbo.sysusers WHERE uid > 0 AND suid >= -1';
end;
function TDBXSybaseASEMetaDataReader.GetSqlForRoles: string;
begin
Result := 'SELECT name FROM dbo.sysusers WHERE suid < -10';
end;
function TDBXSybaseASEMetaDataReader.GetDataTypeDescriptions: TDBXDataTypeDescriptionArray;
var
Types: TDBXDataTypeDescriptionArray;
begin
SetLength(Types,29);
Types[0] := TDBXDataTypeDescription.Create('binary', TDBXDataTypes.BytesType, 1960, 'binary({0})', 'Precision', -1, -1, '0x', NullString, '12.04.9999', NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[1] := TDBXDataTypeDescription.Create('binary', TDBXDataTypes.BytesType, 7960, 'binary({0})', 'Precision', -1, -1, '0x', NullString, NullString, '12.05.0000', TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[2] := TDBXDataTypeDescription.Create('bit', TDBXDataTypes.BooleanType, 1, 'bit', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Searchable);
Types[3] := TDBXDataTypeDescription.Create('char', TDBXDataTypes.AnsiStringType, 1960, 'char({0})', 'Precision', -1, -1, '''', '''', '12.04.9999', NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[4] := TDBXDataTypeDescription.Create('char', TDBXDataTypes.AnsiStringType, 7960, 'char({0})', 'Precision', -1, -1, '''', '''', NullString, '12.05.0000', TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[5] := TDBXDataTypeDescription.Create('datetime', TDBXDataTypes.TimeStampType, 23, 'datetime', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[6] := TDBXDataTypeDescription.Create('decimal', TDBXDataTypes.BcdType, 38, 'decimal({0}, {1})', 'Precision,Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[7] := TDBXDataTypeDescription.Create('double precision', TDBXDataTypes.DoubleType, 53, 'double precision', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[8] := TDBXDataTypeDescription.Create('image', TDBXDataTypes.BlobType, 2147483647, 'image', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[9] := TDBXDataTypeDescription.Create('int', TDBXDataTypes.Int32Type, 10, 'int', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[10] := TDBXDataTypeDescription.Create('money', TDBXDataTypes.BcdType, 19, 'money', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[11] := TDBXDataTypeDescription.Create('numeric', TDBXDataTypes.BcdType, 38, 'numeric({0}, {1})', 'Precision,Scale', 38, 0, NullString, NullString, NullString, NullString, TDBXTypeFlag.AutoIncrementable or TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[12] := TDBXDataTypeDescription.Create('unichar', TDBXDataTypes.WideStringType, 960, 'unichar({0})', 'Precision', -1, -1, 'N''', '''', '12.04.9999', NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[13] := TDBXDataTypeDescription.Create('unichar', TDBXDataTypes.WideStringType, 3960, 'unichar({0})', 'Precision', -1, -1, 'N''', '''', NullString, '12.05.0000', TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[14] := TDBXDataTypeDescription.Create('univarchar', TDBXDataTypes.WideStringType, 960, 'univarchar({0})', 'Precision', -1, -1, 'N''', '''', '12.04.9999', NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[15] := TDBXDataTypeDescription.Create('univarchar', TDBXDataTypes.WideStringType, 3960, 'univarchar({0})', 'Precision', -1, -1, 'N''', '''', NullString, '12.05.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike or TDBXTypeFlag.Unicode);
Types[16] := TDBXDataTypeDescription.Create('real', TDBXDataTypes.SingleType, 7, 'real', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[17] := TDBXDataTypeDescription.Create('smalldatetime', TDBXDataTypes.TimeStampType, 16, 'smalldatetime', NullString, -1, -1, '{ts ''', '''}', NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[18] := TDBXDataTypeDescription.Create('smallint', TDBXDataTypes.Int16Type, 5, 'smallint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[19] := TDBXDataTypeDescription.Create('smallmoney', TDBXDataTypes.BcdType, 10, 'smallmoney', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[20] := TDBXDataTypeDescription.Create('sysname', TDBXDataTypes.AnsiStringType, 30, 'sysname', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.CaseSensitive or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[21] := TDBXDataTypeDescription.Create('text', TDBXDataTypes.AnsiStringType, 2147483647, 'text', NullString, -1, -1, '''', '''', NullString, NullString, TDBXTypeFlag.Long or TDBXTypeFlag.Nullable);
Types[22] := TDBXDataTypeDescription.Create('unitext', TDBXDataTypes.WideStringType, 1073741823, 'unitext', NullString, -1, -1, '''', '''', NullString, '15.00.0000', TDBXTypeFlag.Long or TDBXTypeFlag.Nullable or TDBXTypeFlag.Unicode);
Types[23] := TDBXDataTypeDescription.Create('timestamp', TDBXDataTypes.BytesType, 8, 'timestamp', NullString, -1, -1, '0x', NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.Searchable);
Types[24] := TDBXDataTypeDescription.Create('tinyint', TDBXDataTypes.UInt8Type, 3, 'tinyint', NullString, -1, -1, NullString, NullString, NullString, NullString, TDBXTypeFlag.FixedLength or TDBXTypeFlag.FixedPrecisionScale or TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.Unsigned);
Types[25] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 1960, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, '12.04.9999', NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[26] := TDBXDataTypeDescription.Create('varbinary', TDBXDataTypes.VarBytesType, 7960, 'varbinary({0})', 'Precision', -1, -1, '0x', NullString, NullString, '12.05.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable);
Types[27] := TDBXDataTypeDescription.Create('varchar', TDBXDataTypes.AnsiStringType, 1960, 'varchar({0})', 'Precision', -1, -1, '''', '''', '12.04.9999', NullString, TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Types[28] := TDBXDataTypeDescription.Create('varchar', TDBXDataTypes.AnsiStringType, 7960, 'varchar({0})', 'Precision', -1, -1, '''', '''', NullString, '12.05.0000', TDBXTypeFlag.Nullable or TDBXTypeFlag.Searchable or TDBXTypeFlag.SearchableWithLike);
Result := Types;
end;
function TDBXSybaseASEMetaDataReader.GetReservedWords: TDBXStringArray;
var
Words: TDBXStringArray;
begin
SetLength(Words,322);
Words[0] := 'absolute';
Words[1] := 'action';
Words[2] := 'add';
Words[3] := 'all';
Words[4] := 'allocate';
Words[5] := 'alter';
Words[6] := 'and';
Words[7] := 'any';
Words[8] := 'are';
Words[9] := 'arith_overflow';
Words[10] := 'as';
Words[11] := 'asc';
Words[12] := 'assertion';
Words[13] := 'at';
Words[14] := 'authorization';
Words[15] := 'avg';
Words[16] := 'begin';
Words[17] := 'between';
Words[18] := 'bit';
Words[19] := 'bit_length';
Words[20] := 'both';
Words[21] := 'break';
Words[22] := 'browse';
Words[23] := 'bulk';
Words[24] := 'by';
Words[25] := 'cascade';
Words[26] := 'cascaded';
Words[27] := 'case';
Words[28] := 'cast';
Words[29] := 'catalog';
Words[30] := 'char';
Words[31] := 'char_convert';
Words[32] := 'char_length';
Words[33] := 'character';
Words[34] := 'character_length';
Words[35] := 'check';
Words[36] := 'checkpoint';
Words[37] := 'close';
Words[38] := 'clustered';
Words[39] := 'coalesce';
Words[40] := 'collate';
Words[41] := 'collation';
Words[42] := 'column';
Words[43] := 'commit';
Words[44] := 'compute';
Words[45] := 'confirm';
Words[46] := 'connect';
Words[47] := 'connection';
Words[48] := 'constraint';
Words[49] := 'constraints';
Words[50] := 'continue';
Words[51] := 'controlrow';
Words[52] := 'convert';
Words[53] := 'corresponding';
Words[54] := 'count';
Words[55] := 'create';
Words[56] := 'cross';
Words[57] := 'current';
Words[58] := 'current_date';
Words[59] := 'current_time';
Words[60] := 'current_timestamp';
Words[61] := 'current_user';
Words[62] := 'cursor';
Words[63] := 'database';
Words[64] := 'date';
Words[65] := 'day';
Words[66] := 'dbcc';
Words[67] := 'deallocate';
Words[68] := 'dec';
Words[69] := 'decimal';
Words[70] := 'declare';
Words[71] := 'default';
Words[72] := 'deferrable';
Words[73] := 'deferred';
Words[74] := 'delete';
Words[75] := 'desc';
Words[76] := 'describe';
Words[77] := 'descriptor';
Words[78] := 'deterministic';
Words[79] := 'diagnostics';
Words[80] := 'disconnect';
Words[81] := 'disk';
Words[82] := 'distinct';
Words[83] := 'domain';
Words[84] := 'double';
Words[85] := 'drop';
Words[86] := 'dummy';
Words[87] := 'dump';
Words[88] := 'else';
Words[89] := 'end';
Words[90] := 'end-exec';
Words[91] := 'endtran';
Words[92] := 'errlvl';
Words[93] := 'errordata';
Words[94] := 'errorexit';
Words[95] := 'escape';
Words[96] := 'except';
Words[97] := 'exception';
Words[98] := 'exclusive';
Words[99] := 'exec';
Words[100] := 'execute';
Words[101] := 'exists';
Words[102] := 'exit';
Words[103] := 'exp_row_size';
Words[104] := 'external';
Words[105] := 'extract';
Words[106] := 'false';
Words[107] := 'fetch';
Words[108] := 'fillfactor';
Words[109] := 'first';
Words[110] := 'float';
Words[111] := 'for';
Words[112] := 'foreign';
Words[113] := 'found';
Words[114] := 'from';
Words[115] := 'full';
Words[116] := 'func';
Words[117] := 'get';
Words[118] := 'global';
Words[119] := 'go';
Words[120] := 'goto';
Words[121] := 'grant';
Words[122] := 'group';
Words[123] := 'having';
Words[124] := 'holdlock';
Words[125] := 'hour';
Words[126] := 'identity';
Words[127] := 'identity_gap';
Words[128] := 'identity_insert';
Words[129] := 'identity_start';
Words[130] := 'if';
Words[131] := 'immediate';
Words[132] := 'in';
Words[133] := 'index';
Words[134] := 'indicator';
Words[135] := 'initially';
Words[136] := 'inner';
Words[137] := 'inout';
Words[138] := 'input';
Words[139] := 'insensitive';
Words[140] := 'insert';
Words[141] := 'install';
Words[142] := 'int';
Words[143] := 'integer';
Words[144] := 'intersect';
Words[145] := 'interval';
Words[146] := 'into';
Words[147] := 'is';
Words[148] := 'isolation';
Words[149] := 'jar';
Words[150] := 'join';
Words[151] := 'key';
Words[152] := 'kill';
Words[153] := 'language';
Words[154] := 'last';
Words[155] := 'leading';
Words[156] := 'left';
Words[157] := 'level';
Words[158] := 'like';
Words[159] := 'lineno';
Words[160] := 'load';
Words[161] := 'local';
Words[162] := 'lock';
Words[163] := 'lower';
Words[164] := 'match';
Words[165] := 'max';
Words[166] := 'max_rows_per_page';
Words[167] := 'min';
Words[168] := 'minute';
Words[169] := 'mirror';
Words[170] := 'mirrorexit';
Words[171] := 'modify';
Words[172] := 'module';
Words[173] := 'month';
Words[174] := 'names';
Words[175] := 'national';
Words[176] := 'natural';
Words[177] := 'nchar';
Words[178] := 'new';
Words[179] := 'next';
Words[180] := 'no';
Words[181] := 'noholdlock';
Words[182] := 'nonclustered';
Words[183] := 'not';
Words[184] := 'null';
Words[185] := 'nullif';
Words[186] := 'numeric';
Words[187] := 'numeric_truncation';
Words[188] := 'octet_length';
Words[189] := 'of';
Words[190] := 'off';
Words[191] := 'offsets';
Words[192] := 'on';
Words[193] := 'once';
Words[194] := 'online';
Words[195] := 'only';
Words[196] := 'open';
Words[197] := 'option';
Words[198] := 'or';
Words[199] := 'order';
Words[200] := 'out';
Words[201] := 'outer';
Words[202] := 'output';
Words[203] := 'over';
Words[204] := 'overlaps';
Words[205] := 'pad';
Words[206] := 'partial';
Words[207] := 'partition';
Words[208] := 'perm';
Words[209] := 'permanent';
Words[210] := 'plan';
Words[211] := 'position';
Words[212] := 'precision';
Words[213] := 'prepare';
Words[214] := 'preserve';
Words[215] := 'primary';
Words[216] := 'print';
Words[217] := 'prior';
Words[218] := 'privileges';
Words[219] := 'proc';
Words[220] := 'procedure';
Words[221] := 'processexit';
Words[222] := 'proxy_table';
Words[223] := 'public';
Words[224] := 'quiesce';
Words[225] := 'raiserror';
Words[226] := 'read';
Words[227] := 'readpast';
Words[228] := 'readtext';
Words[229] := 'real';
Words[230] := 'reconfigure';
Words[231] := 'references remove';
Words[232] := 'relative';
Words[233] := 'reorg';
Words[234] := 'replace';
Words[235] := 'replication';
Words[236] := 'reservepagegap';
Words[237] := 'restrict';
Words[238] := 'return';
Words[239] := 'returns';
Words[240] := 'revoke';
Words[241] := 'right';
Words[242] := 'role';
Words[243] := 'rollback';
Words[244] := 'rowcount';
Words[245] := 'rows';
Words[246] := 'rule';
Words[247] := 'save';
Words[248] := 'schema';
Words[249] := 'scroll';
Words[250] := 'second';
Words[251] := 'section';
Words[252] := 'select';
Words[253] := 'session_user';
Words[254] := 'set';
Words[255] := 'setuser';
Words[256] := 'shared';
Words[257] := 'shutdown';
Words[258] := 'size';
Words[259] := 'smallint';
Words[260] := 'some';
Words[261] := 'space';
Words[262] := 'sql';
Words[263] := 'sqlcode';
Words[264] := 'sqlerror';
Words[265] := 'sqlstate';
Words[266] := 'statistics';
Words[267] := 'stringsize';
Words[268] := 'stripe';
Words[269] := 'substring';
Words[270] := 'sum';
Words[271] := 'syb_identity';
Words[272] := 'syb_restree';
Words[273] := 'syb_terminate';
Words[274] := 'system_user';
Words[275] := 'table';
Words[276] := 'temp';
Words[277] := 'temporary';
Words[278] := 'textsize';
Words[279] := 'then';
Words[280] := 'time';
Words[281] := 'timestamp';
Words[282] := 'timezone_hour';
Words[283] := 'timezone_minute';
Words[284] := 'to';
Words[285] := 'trailing';
Words[286] := 'tran';
Words[287] := 'transaction';
Words[288] := 'translate';
Words[289] := 'translation';
Words[290] := 'trigger';
Words[291] := 'trim';
Words[292] := 'true';
Words[293] := 'truncate';
Words[294] := 'tsequal';
Words[295] := 'union';
Words[296] := 'unique';
Words[297] := 'unknown';
Words[298] := 'unpartition';
Words[299] := 'update';
Words[300] := 'upper';
Words[301] := 'usage';
Words[302] := 'use';
Words[303] := 'user';
Words[304] := 'user_option';
Words[305] := 'using';
Words[306] := 'value';
Words[307] := 'values';
Words[308] := 'varchar';
Words[309] := 'varying';
Words[310] := 'view';
Words[311] := 'waitfor';
Words[312] := 'when';
Words[313] := 'whenever';
Words[314] := 'where';
Words[315] := 'while';
Words[316] := 'with';
Words[317] := 'work';
Words[318] := 'write';
Words[319] := 'writetext';
Words[320] := 'year';
Words[321] := 'zone';
Result := Words;
end;
end.
|
unit classe.MakeSpend;
interface
uses classe.Spend, System.SysUtils;
type
TMakeSpend = class
private
//
public
procedure createSpend(valName : String; valCurr : Currency; valDate : TDateTime);
end;
implementation
{ TMakeSpend }
// METHODS
procedure TMakeSpend.createSpend(valName: String; valCurr: Currency; valDate : TDateTime);
var
MySpend : TSpend;
begin
MySpend := TSpend.Create;
try
MySpend.Name := valName;
MySpend.Spend := valCurr;
MySpend.Date := valDate;
MySpend.SaveInDatabase;
finally
MySpend.Free;
end;
end;
end.
|
unit Interpolation;
interface
uses IntervalArithmetic;
type TExtendedArray = array of Extended;
type TIntervalArray = array of interval;
function Lagrange( degree : Integer;
nodes : TExtendedArray;
values : TExtendedArray;
point : Extended;
var status : Integer) : Extended; overload;
function LagrangeCoefficients( degree : Integer;
nodes : TExtendedArray;
values : TExtendedArray;
var status : Integer) : TExtendedArray; overload;
function Lagrange( degree : Integer;
nodes : TIntervalArray;
values : TIntervalArray;
point : Interval;
var status : Integer) : Interval; overload;
function LagrangeCoefficients( degree : Integer;
nodes : TIntervalArray;
values : TIntervalArray;
var status : Integer) : TIntervalArray; overload;
function Neville( degree : Integer;
nodes : TExtendedArray;
values : TExtendedArray;
point : Extended;
var status : Integer) : Extended; overload;
function Neville( degree : Integer;
nodes : TIntervalArray;
values : TIntervalArray;
point : Interval;
var status : Integer) : Interval; overload;
implementation
function Lagrange (degree : Integer;
nodes : TExtendedArray;
values : TExtendedArray;
point : Extended;
var status : Integer) : Extended;
var i,k : Integer;
fx,p : Extended;
begin
if degree<0
then status:=1
else begin
status:=0;
if degree>0
then begin
i:=-1;
repeat
i:=i+1;
for k:=i+1 to degree do
if nodes[i]=nodes[k]
then status:=2
until (i=degree-1) or (status=2)
end;
if status=0
then begin
fx:=0;
for i:=0 to degree do
begin
p:=1;
for k:=0 to degree do
if k<>i
then p:=p*(point-nodes[k])/(nodes[i]-nodes[k]);
fx:=fx+values[i]*p
end;
Lagrange:=fx
end
end
end;
function LagrangeCoefficients (degree : Integer;
nodes : TExtendedArray;
values : TExtendedArray;
var status : Integer) : TExtendedArray; overload;
var i,k,l: Integer;
p : Extended;
cfs : TExtendedArray;
poly : TExtendedArray;
begin
if degree<0
then status:=1
else begin
status:=0;
if degree>0
then begin
i:=-1;
repeat
i:=i+1;
for k:=i+1 to degree do
if nodes[i]=nodes[k]
then status:=2
until (i=degree-1) or (status=2)
end;
if status=0
then begin
SetLength(cfs, degree+1);
SetLength(poly, degree+1);
SetLength(result, degree+1);
for i := 0 to degree do
result[i] := 0;
for i:=0 to degree do
begin
p:=1;
for k:=0 to degree do
if k<>i
then p:=p*(nodes[i]-nodes[k]);
cfs[i] := values[i]/p;
end;
for i := 0 to degree do begin
for l := 0 to degree do
poly[l] := 0;
poly[degree] := 1;
for l := 0 to degree do
if i <> l then
for k := 0 to degree-1 do
poly[k] := poly[k] - poly[k+1]*nodes[l];
for l := 0 to degree do begin
poly[l] := poly[l]*cfs[i];;
result[l] := result[l] + poly[l];
end;
end;
end
end
end;
function LagrangeCoefficients (degree : Integer;
nodes : TIntervalArray;
values : TIntervalArray;
var status : Integer) : TIntervalArray; overload;
var i,k,l: Integer;
fx,p : Interval;
cfs : TIntervalArray;
poly : TIntervalArray;
begin
if degree<0
then status:=1
else begin
status:=0;
if degree>0
then begin
i:=-1;
repeat
i:=i+1;
for k:=i+1 to degree do
if iequal(nodes[i], nodes[k])
then status:=2
until (i=degree-1) or (status=2)
end;
if status=0
then begin
SetLength(cfs, degree+1);
SetLength(poly, degree+1);
SetLength(result, degree+1);
for i := 0 to degree do
result[i] := izero;
fx:=izero;
for i:=0 to degree do
begin
p:=ione;
for k:=0 to degree do
if k<>i
then p:=imul(p, isub(nodes[i], nodes[k]));
cfs[i] := idiv(values[i], p);
end;
for i := 0 to degree do begin
for l := 0 to degree do
poly[l] := izero;
poly[degree] := ione;
for l := 0 to degree do
if i <> l then
for k := 0 to degree-1 do
poly[k] := isub(poly[k], imul(poly[k+1],nodes[l]));
for l := 0 to degree do begin
poly[l] := imul(poly[l],cfs[i]);
result[l] := iadd(result[l], poly[l]);
end;
end;
end
end
end;
function Lagrange( degree : Integer;
nodes : TIntervalArray;
values : TIntervalArray;
point : interval;
var status : Integer) : interval;
var i,k : Integer;
fx,p : Interval;
begin
if degree<0
then status:=1
else begin
status:=0;
if degree>0
then begin
i:=-1;
repeat
i:=i+1;
for k:=i+1 to degree do
if iequal(nodes[i], nodes[k])
then status:=2
until (i=degree-1) or (status=2)
end;
if status=0
then begin
fx:=izero;
for i:=0 to degree do
begin
p:=ione;
for k:=0 to degree do
if k<>i
then p:=imul(p, idiv((isub(point, nodes[k])), (isub(nodes[i], nodes[k]))));
fx:=iadd(fx, imul(values[i], p))
end;
Lagrange:=fx
end
end
end;
function Neville (degree : Integer;
nodes : TExtendedArray;
values : TExtendedArray;
point : Extended;
var status : Integer) : Extended;
var i,k : Integer;
begin
if degree<0
then status:=1
else begin
status:=0;
if degree>0
then begin
i:=-1;
repeat
i:=i+1;
for k:=i+1 to degree do
if nodes[i]=nodes[k]
then status:=2
until (i=degree-1) or (status=2)
end;
if status=0
then begin
for k:=1 to degree do
for i:=degree downto k do
values[i]:=((point-nodes[i-k])*values[i]-(point-nodes[i])*values[i-1])
/(nodes[i]-nodes[i-k]);
Neville:=values[degree]
end
end
end;
function Neville( degree : Integer;
nodes : TIntervalArray;
values : TIntervalArray;
point : Interval;
var status : Integer) : Interval;
var i,k : Integer;
begin
if degree<0
then status:=1
else begin
status:=0;
if degree>0
then begin
i:=-1;
repeat
i:=i+1;
for k:=i+1 to degree do
if iequal(nodes[i], nodes[k])
then status:=2
until (i=degree-1) or (status=2)
end;
if status=0
then begin
for k:=1 to degree do
for i:=degree downto k do
values[i]:=idiv(isub(imul(isub(point, nodes[i-k]), values[i]), imul(isub(point,nodes[i]), values[i-1]))
,isub(nodes[i],nodes[i-k]));
Neville:=values[degree]
end
end
end;
end.
|
unit Configuracoes;
interface
uses SysUtils, Classes,
{ Fluente }
Util;
type
TConfiguracoes = class(TObject)
private
FConfiguracoes: TStringList;
public
constructor Create(const CaminhoArquivoConfiguracao: string); reintroduce;
function Gravar(const Chave, Valor: string): TConfiguracoes;
function Ler(const Key: string): string;
end;
implementation
{ TConfiguracoes }
constructor TConfiguracoes.Create(const CaminhoArquivoConfiguracao: string);
var
_i: Integer;
_arquivo: TStringList;
begin
inherited Create;
Self.FConfiguracoes := TStringList.Create;
if FileExists(CaminhoArquivoConfiguracao) then
begin
_arquivo := TStringList.Create();
try
_arquivo.LoadFromFile(CaminhoArquivoConfiguracao);
for _i := 0 to _arquivo.Count-1 do
Self.FConfiguracoes.AddObject(
Copy(_arquivo[_i], 1, Pos('=', _arquivo[_i]) -1),
TValor.Create()
.Texto(Copy(_arquivo[_i], Pos('=', _arquivo[_i])+1, 1024))) ;
finally
FreeAndNil(_arquivo);
end;
end;
end;
function TConfiguracoes.Ler(const Key: string): string;
var
_indice: Integer;
begin
_indice := Self.FConfiguracoes.IndexOf(Key);
if _indice <> -1 then
Result := (Self.FConfiguracoes.Objects[_indice] as TValor).ObterTexto()
else
Result := '';
end;
function TConfiguracoes.Gravar(const Chave, Valor: string): TConfiguracoes;
var
_indice: Integer;
begin
_indice := Self.FConfiguracoes.IndexOf(Chave);
if _indice = -1 then
Self.FConfiguracoes.AddObject(Chave, TValor.Create().Texto(Valor))
else
(Self.FConfiguracoes.Objects[_indice] as TValor).Texto(Valor);
Result := Self;
end;
end.
|
{**********************************************************************}
{ Unit archived using GP-Version }
{ GP-Version is Copyright 1997 by Quality Software Components Ltd }
{ }
{ For further information / comments, visit our WEB site at }
{ http://www.qsc.u-net.com }
{**********************************************************************}
{ $Log: 10056: kpUshrnk.pas
{
{ Rev 1.0 8/14/2005 1:10:10 PM KLB Version: VCLZip Pro 3.06
{ Initial load of VCLZip Pro on this computer
}
{
{ Rev 1.0 10/15/2002 8:15:20 PM Supervisor
}
{
{ Rev 1.0 9/3/2002 8:16:52 PM Supervisor
}
{
{ Rev 1.1 7/9/98 6:47:19 PM Supervisor
{ Version 2.13
{
{ 1) New property ResetArchiveBitOnZip causes each file's
{ archive bit to be turned off after being zipped.
{
{ 2) New Property SkipIfArchiveBitNotSet causes files
{ who's archive bit is not set to be skipped during zipping
{ operations.
{
{ 3) A few modifications were made to allow more
{ compatibility with BCB 1.
{
{ 4) Modified how directory information is used when
{ comparing filenames to be unzipped. Now it is always
{ used.
}
{ ********************************************************************************** }
{ }
{ COPYRIGHT 1997 Kevin Boylan }
{ Source File: Unshrink.pas }
{ Description: VCLUnZip component - native Delphi unzip component. }
{ Date: March 1997 }
{ Author: Kevin Boylan, CIS: boylank }
{ Internet: boylank@compuserve.com }
{ }
{ ********************************************************************************** }
procedure Unshrink;
var
codesize: WORD;
{maxcode: WORD;}
maxcodemax: WORD;
free_ent: WORD;
procedure partial_clear;
var
pr: short_int;
cd: short_int;
begin
{ mark all nodes as potentially unused }
cd := FIRST_ENT;
while (WORD(cd) < free_ent) do
begin
area^.shrink.Prefix_of[cd] := WORD(area^.shrink.Prefix_of[cd]) or $8000;
Inc(cd);
end;
cd := FIRST_ENT;
while (WORD(cd) < free_ent) do
begin
pr := area^.shrink.Prefix_of[cd] and $7fff;
if (pr >= FIRST_ENT) then
area^.shrink.Prefix_of[pr] := area^.shrink.Prefix_of[pr] and $7fff;
Inc(cd);
end;
{ clear the ones that are still marked }
cd := FIRST_ENT;
while (WORD(cd) < free_ent) do
begin
if (area^.shrink.Prefix_of[cd] and $8000) <> 0 then
area^.shrink.Prefix_of[cd] := -1;
Inc(cd);
end;
{ find first cleared node as next free_ent }
cd := FIRST_ENT;
while ((WORD(cd) < maxcodemax) and (area^.shrink.Prefix_of[cd] <> -1)) do
Inc(cd);
free_ent := cd;
end;
var
code: short_int;
stackp: short_int;
finchar: short_int;
oldcode: short_int;
incode: short_int;
begin
ZeroMemory( area, SizeOf(area));
codesize := INIT_BITS;
{maxcode := (1 shl codesize) - 1;}
maxcodemax := HSIZE;
free_ent := FIRST_ENT;
code := maxcodemax;
Repeat
area^.shrink.Prefix_of[code] := -1;
Dec(code);
Until code <= 255;
for code := 255 downto 0 do
begin
area^.shrink.Prefix_of[code] := 0;
area^.shrink.Suffix_of[code] := code;
end;
READBIT(codesize,oldcode);
if (zipeof) then
begin
xFlushOutput;
exit;
end;
finchar := oldcode;
OUTB(finchar);
stackp := HSIZE;
while not(zipeof) do
begin
READBIT(codesize,code);
if (zipeof) then
begin
xFlushOutput;
exit;
end;
while (code = CLEAR) do
begin
READBIT(codesize,code);
Case code of
1: begin
Inc(codesize);
{ if (codesize = MAX_BITS) then
maxcode := maxcodemax
else
maxcode := (1 shl codesize) - 1; }
end;
2: partial_clear;
end;
READBIT(codesize,code);
if (zipeof) then
begin
xFlushOutput;
exit;
end;
end;
{ Special case for KwKwK string }
incode := code;
if (area^.shrink.Prefix_of[code] = -1) then
begin
Dec(stackp);
area^.shrink.Stack[stackp] := Byte(finchar);
code := oldcode;
end;
{ Generate output characters in reverse order }
while (code >= FIRST_ENT) do
begin
{ Adding characters to stack }
if (area^.shrink.Prefix_of[code] = -1) then
begin
Dec(stackp);
area^.shrink.Stack[stackp] := Byte(finchar);
code := oldcode;
end
Else
begin
Dec(stackp);
area^.shrink.Stack[stackp] := area^.shrink.Suffix_of[code];
code := area^.shrink.Prefix_of[code];
end;
end;
finchar := area^.shrink.Suffix_of[code];
Dec(stackp);
area^.shrink.Stack[stackp] := Byte(finchar);
{ And put them out in forward order, block copy }
if ((HSIZE - stackp + outcnt) < 2048) then
begin
MoveMemory(outptr, @area^.shrink.Stack[stackp], HSIZE-stackp);
Inc(outptr,HSIZE-stackp);
Inc(outcnt,HSIZE-stackp);
stackp := HSIZE;
end
Else { output byte by byte if we can't go by blocks }
while (stackp < HSIZE) do
begin
OUTB(area^.shrink.Stack[stackp]);
Inc(stackp);
end;
{ Generate new entry }
code := free_ent;
if (WORD(code) < maxcodemax) then
begin
area^.shrink.Prefix_of[code] := oldcode;
area^.shrink.Suffix_of[code] := Byte(finchar);
Repeat
Inc(code);
Until (WORD(code) >= maxcodemax) or (area^.shrink.Prefix_of[code] = -1);
free_ent := code;
end;
{ remember previous code }
oldcode := incode;
end; { While not(zipeof)) }
xFlushOutput;
end;
|
{== tersMonitorU ================================================}
{: This unit implements a component that can be used to monitor print
jobs send to all installed printers.
@author Dr. Peter Below
@desc Version 1.0 created 2003-04-20<br/>
Last modified 2003-04-20<p/>
The component uses a set of background threads to monitor the installed
printers via FindFirstPrinterChangeNotification. It fires events when
a new job is added, when a job completed, or when a jobs status has
changed in some other manner. <p/>
The component does not use the Delphi Synchronize mechanism, it can be
used without problems in a DLL in D6 and above. The component is not
Kylix-compatible, since it depends completely in Windows API functions
for irs functionality. It has only been tested with Delphi 7 on
Win2K SP3.<p/>
NOTE: <br/>
Define the symbol DEBUG to allow the component to show error
messages when it cannot get information for a printer to monitor. <p/>
Define the symbol NO_MESSAGELOOP if the application using the compoent
has no message loop. In this case the internal thread synchronization
will use SendMessageTimeout instead of PostMessage. }
{======================================================================}
{$BOOLEVAL OFF}{Unit depends on shortcut boolean evaluation}
Unit ncPrintMon;
Interface
Uses
Messages, Windows, SysUtils, Classes, Printers, COntnrs, ncJob, SyncObjs;
Type
{: Prototype of an event used to pass job information to a client
if TPBPrintersMonitor.
@param aJobInformation holds the information about the job. This
object remains property of the caller, the event handler must
not free it! }
TncJobEvent = Procedure( const aJobinformation: TncJob ) of Object;
TncJobDeletedEvent = Procedure( const JobID: Cardinal) of Object;
{: This class offers job monitoring functionality to clients. As it is
now the object monitors all installed printers automatically, and there
is no way to limit this to one particular printer. The client has
to filter out the events of interest itself. Monitoring can be
suspended and resumed via the Active property and is not done at
design-time. }
TJobList = class ( TObjectList )
private
function GetJob(aIndex: Integer): TncJob;
public
function Exists(aPrinterIndex: Integer; aID: Cardinal): Boolean;
property Jobs[aIndex: Integer]: TncJob
read GetJob;
end;
TncPrintersMonitor = class(TComponent)
private
FInternalSyncHelper: HWND; // helper window used to sync to main thread
FPendingNotifications: TThreadList; // queue of notifications to process
FNotifiers: TObjectList; // list of notifier thread objects
FActive: Boolean; // monitoring state
FNewJobEvent: TncJobEvent; // atached event handlers
FJobChangeEvent: TncJobEvent;
FJobCompleteEvent: TncJobEvent;
FJobDeletedEvent: TncJobDeletedEvent;
Procedure SetActive(const Value: Boolean);
Procedure CreateNotifiers;
protected
{: Window function for the helper window, executes in the printer
monitors thread, usually the main thread. }
Procedure WndProc( Var msg: TMessage );
{: Event handler for the notifier threads, will execute in the
calling threads context.
@param aJobInformation contains the job information. The method
makes a copy of this object for the internal use of the monitor. }
Procedure JobNotification( const Jobinfo: TncJob );
{: Processes all pending notifications in the context of the
printer monitors thread. }
Procedure ProcessNotifications;
{: Fires the OnNewJob event, if a handler for it has been assigned. }
Procedure DoNewJob( const aJobinformation: TncJob ); virtual;
{: Fires the OnJobChange event, if a handler for it has been assigned. }
Procedure DoJobChange( const aJobinformation: TncJob ); virtual;
{: Fires the OnJobComplete event, if a handler for it has been assigned. }
Procedure DoJobComplete( const aJobinformation: TncJob ); virtual;
public
Constructor Create( aOwner: TComponent ); override;
Destructor Destroy; override;
function GetJobList: TJobList;
function GetPrinterIndexByName(aPrinterName: String): Integer;
procedure JobControl(aPrinterIndex: Integer; aJobID: Cardinal; aControl: Byte);
published
property Active: Boolean read FActive write SetActive;
property OnNewJob: TncJobEvent read FNewJobEvent write FNewJobEvent;
property OnJobChange: TncJobEvent read FJobChangeEvent write FJobChangeEvent;
property OnJobComplete: TncJobEvent read FJobCompleteEvent write FJobCompleteEvent;
property OnJobDeleted: TncJobDeletedEvent read FJobDeletedEvent write FJobDeletedEvent;
end;
TncNaoPausar = class
private
FItens : TStrings;
FEsteComp : String;
FPausarEsteComp: Boolean;
FCS : TCriticalSection;
procedure SetText(const aText: String);
public
constructor Create;
destructor Destroy;
procedure SetEsteComp(const AComp: String);
procedure SetPausarEsteComp(const APausarEsteComp: Boolean);
procedure SetNaoPausar(const aText: String);
function Pausar(AComp: String): Boolean;
end;
{: Exception class used to report monitor errors }
EPBPrinterMonitorError = class( Exception );
Procedure Register;
var
gNaoPausar : TncNaoPausar;
Implementation
Uses
ncClassesBase,
WinSpool,
Forms, ncDebug;
Procedure Register;
Begin
RegisterComponents('PBGoodies', [TncPrintersMonitor]);
End;
Procedure RaiseLastWin32Error;
Begin
RaiseLastOSError;
End;
Type
{: This thread class will monitor the job queue of a single printer.
On changes to a job or the queue an event is fired. The events
handler has to make sure the processing it does is thread-safe. }
TncPrintMonitor = class( TThread )
private
FJobInformation: TncJob;
// contains info on monitored printer and last job change
FPrinterHandle : THandle; // the printers API handle
FWakeupEvent : TSimpleEvent; // used to wake thread when it is destroyed
FRunning : Boolean; // flag set when thread reaches Execute
FJobChangeEvent: TncJobEvent;
procedure HandleNotification(findhandle: THandle); // attached event handler
protected
Procedure Execute; override;
Constructor InternalCreate;
Procedure DoJobChange; virtual;
Procedure Wakeup;
function GetPrinterIndex: Integer;
public
{: Do not use this constructor!
@raises EPBPrinterMonitorError when called }
Constructor Create( CreateSuspended: Boolean );
{: This class function is used to create an instance of the
class to monitor a specific printer.
@param index is the index of the printer to monitor in Printer.Printers
@param onChangeJob is the callback to receive job notifications.
@precondition 0 <= index < Printer.Printers.count
@returns the created object, or Nil, if the printer information could
not be obtained from the API. }
class Function CreateMonitor( index: Integer; onChangeJob: TncJobEvent ): TncPrintMonitor;
procedure GetJobs(aJL: TJobList);
{: Wakes the thread from the wait state, closes the printer handle. }
Destructor Destroy; override;
function SamePrinterName(aName: String): Boolean;
property PrtIndex: Integer
read GetPrinterIndex;
property PrtHandle: THandle
read FPrinterHandle;
property JInfo: TncJob
read FJobInformation;
property OnJobChange: TncJobEvent read FJobChangeEvent write FJobChangeEvent;
End;
{ TncPrintMonitor 覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧抑
Constructor TncPrintMonitor.Create(CreateSuspended: Boolean);
Begin
raise EPBPrinterMonitorError.Create(
'Do not use this constructor to create instances of '+
'TncPrintMonitor, use the CreateMonitor method instead!' );
End;
{-- GetCurrentPrinterHandle -------------------------------------------}
{: Retrieves the handle of the current printer
@Returns an API printer handle for the current printer
@Desc Uses WinSpool.OpenPrinter to get a printer handle. The caller
takes ownership of the handle and <b>must</b> call ClosePrinter on it
once the handle is no longer needed. Failing to do that creates a
serious resource leak! <P>
Requires Printers and WinSpool in the Uses clause.
@Raises EWin32Error if the OpenPrinter call fails.
}{ Created 30.9.2000 by P. Below
-----------------------------------------------------------------------}
Function GetCurrentPrinterHandle: THandle;
var
Defaults: TPrinterDefaults;
Var
Device, Driver, Port : array[0..255] of char;
hDeviceMode: THandle;
Begin { GetCurrentPrinterHandle }
Printer.GetPrinter(Device, Driver, Port, hDeviceMode);
Defaults.pDatatype := nil;
Defaults.pDevMode := nil;
if Copy(Device,1,2) = '\\' then
Defaults.DesiredAccess := SERVER_ALL_ACCESS else
Defaults.DesiredAccess := PRINTER_ACCESS_USE or PRINTER_ACCESS_ADMINISTER;
If not OpenPrinter(@Device, Result, @Defaults) Then
Result := 0;
// RaiseLastWin32Error;
End; { GetCurrentPrinterHandle }
{: Selects the printer by the passed index and tries to obtains its
API handle and a number of information items on it. If this succeeds
the thread is created, fed the obtained data, and its reference is
returned. The thread is suspended. <br/>
We trap any exceptions on the way and do not allow them to escape
the function, instead Nil is returned as result. If the symbol DEBUG
is defined a message box with the exception message will be shown,
but program flow will still continue after that. <p/>
WARNING! This function has a side effect! It will change the selected
printer! The routine calling CreateMonitor is responsible for saving
and restoring the previously selected printer, if that is required.
This is an optimization, since in typical use CreateMonitor will
be called for every printer in the list. }
class Function TncPrintMonitor.CreateMonitor(index: Integer;
onChangeJob: TncJobEvent): TncPrintMonitor;
Var
printerhandle: THandle;
pInfo: PPrinterInfo2;
bytesNeeded: DWORD;
S: String;
Begin
If (index < 0) or (index >= Printer.Printers.Count) Then
raise EPBPrinterMonitorError.CreateFmt(
'TncPrintMonitor.CreateMonitor: index %d is out of range. '+
'Valid indices are %d..%d.',
[index, 0, Printer.Printers.Count] );
Result := nil;
printerhandle := 0;
Try
Printer.PrinterIndex := index;
printerhandle := GetCurrentPrinterhandle;
if printerhandle=0 then Exit;
Winspool.GetPrinter( printerhandle, 2, Nil, 0, @bytesNeeded );
If GetLastError <> ERROR_INSUFFICIENT_BUFFER Then
RaiseLastWin32Error;
pInfo := AllocMem( bytesNeeded );
Try
If not Winspool.GetPrinter( printerhandle, 2, pInfo, bytesNeeded, @bytesNeeded )
Then
RaiseLastWin32Error;
Result := TncPrintMonitor.InternalCreate;
Try
Result.FPrinterHandle := printerhandle;
Result.FJobInformation := TncJob.Create;
with Result.FJobInformation do begin
PrtHandle := printerhandle;
PrinterIndex := index;
PrinterName := pInfo^.pPrinterName;
PrinterPort := pInfo^.pPortName;
PrinterServer := pInfo^.pServerName;
PrinterShare := pInfo^.pShareName;
end;
Result.FJobChangeEvent := OnChangeJob;
Except
Result.FPrinterHandle := 0; // prevents ClosePrinter to be called twice
FreeAndNil( Result );
raise;
End; { Except }
Finally
FreeMem( pInfo );
End;
Except
On E: Exception Do Begin
If printerhandle <> 0 Then
ClosePrinter( printerhandle );
If not (E Is EAbort) Then Begin
S:= Format(
'TncPrintMonitor.CreateMonitor raised an exception.'#13#10+
'Exception class %s'#13#10'%s',
[E.classname, E.Message] );
Windows.MessageBox( 0, Pchar(S), 'Error', MB_OK or MB_ICONSTOP );
End; { If }
End; { On }
End; { Except }
End;
Destructor TncPrintMonitor.Destroy;
Begin
If not Terminated Then Terminate;
Wakeup;
If FRunning and Suspended Then Resume;
inherited; // will wait until the thread has died
ClosePrinter( FPrinterHandle );
FJobInformation.Free;
FWakeupEvent.Free;
End;
Procedure TncPrintMonitor.DoJobChange;
Begin
If Assigned( FJobChangeEvent ) Then
FJobChangeEvent( FJobInformation );
End;
Procedure TncPrintMonitor.HandleNotification( findhandle: THandle );
Var
pni: PPrinterNotifyInfo;
ChangeReason: Cardinal;
Function ReasonWas( flag: Cardinal ): Boolean;
Begin
Result := (flag and ChangeReason) <> 0;
End; { ReasonWas }
Function FindJobStatus: Byte;
Var
i: Integer;
status: Cardinal;
Function StatusIs(flag: Cardinal): Boolean;
Begin
Result := (flag and status) <> 0;
End; { StatusIs }
Begin { FindJobStatus }
Result := jsNone;
If Assigned( pni ) Then
For i:=0 To pni^.Count-1 Do
If pni^.aData[i].Field = JOB_NOTIFY_FIELD_STATUS Then Begin
status := pni^.aData[i].NotifyData.adwData[0];
FJobInformation.Spooling := StatusIs( JOB_STATUS_SPOOLING);
FJobInformation.StatusPaused := StatusIs( JOB_STATUS_PAUSED);
If StatusIs( JOB_STATUS_PRINTED ) Then
Result := jsCompleted
Else If StatusIs( JOB_STATUS_DELETING ) Then begin
Result := jsNone;
FJobInformation.Spooling := False;
// we skip this case because we will get another notification for that
end Else If StatusIs( JOB_STATUS_SPOOLING )
Then
Result := jsProcessing
Else If StatusIs( JOB_STATUS_PRINTING )
Then
Result := jsPrinting
Else If StatusIs( JOB_STATUS_ERROR or JOB_STATUS_OFFLINE or
JOB_STATUS_PAPEROUT )
Then
Result := jsError
Else If StatusIs( JOB_STATUS_PAUSED ) Then
Result := jsPaused;
Break;
End; { If }
End; { FindJobStatus }
Procedure GetJobInformation;
Function DataString( index: Integer ): String;
Begin
Result := Pchar( pni^.aData[index].NotifyData.Data.pBuf )
End;
Function DataValue( index: Integer ): Cardinal;
Begin
Result := pni^.aData[index].NotifyData.adwData[0];
End;
Function GetPrinterNumCopies(index: Integer):Cardinal;
Begin
result:=PDeviceMode( pni^.aData[index].NotifyData.Data.pBuf)^.dmCopies;
End;
Function GetPrinterOrientation(index: Integer):TPrinterOrientation;
var Orientation: smallint;
Begin
Orientation:=
PDeviceMode(pni^.aData[index].NotifyData.Data.pBuf)^.dmOrientation;
Case orientation Of
DMORIENT_PORTRAIT : result:=poPortrait;
DMORIENT_LANDSCAPE: result:=poLandscape;
Else
result := poPortrait;
Assert( false, 'Unknown value in dmOrientation');
End;
End;
Var
i: Integer;
status: cardinal;
Begin { GetJobInformation }
If not Assigned( pni) or (pni^.Count = 0) Then Exit;
FJobInformation.JobID := pni^.aData[0].Id;
For i:=0 To pni^.Count-1 Do
Case pni^.aData[i].Field Of
JOB_NOTIFY_FIELD_STATUS: begin
status := pni^.aData[i].NotifyData.adwData[0];
FJobInformation.StatusPaused := ((JOB_STATUS_PAUSED and Status) <> 0);
end;
JOB_NOTIFY_FIELD_MACHINE_NAME:
FJobInformation.Computer := Datastring(i);
JOB_NOTIFY_FIELD_USER_NAME:
FJobInformation.User := Datastring(i);
JOB_NOTIFY_FIELD_DOCUMENT: begin
DebugMsg('TncPrintMonitor.DoJobChange - JOB_NOTIFY_FIELD_DOCUMENT - ' + Datastring(i));
FJobInformation.Document := Datastring(i);
end;
JOB_NOTIFY_FIELD_TOTAL_PAGES:
FJobInformation.TotalPages := Datavalue(i);
{ JOB_NOTIFY_FIELD_TOTAL_BYTES:
FJobInformation.Totalbytes := Datavalue(i);}
{ JOB_NOTIFY_FIELD_BYTES_PRINTED:
FJobInformation.BytesPrinted := Datavalue(i);}
JOB_NOTIFY_FIELD_PAGES_PRINTED:
FJobInformation.Pages := Datavalue(i);
JOB_NOTIFY_FIELD_DEVMODE: Begin
FJobInformation.Copies:= GetPrinterNumCopies(i);
// FJobInformation.FOrientiation := GetPrinterOrientation(i);
End;
End; { Case }
End; { GetJobInformation }
Begin { HandleNotification }
FJobInformation.Spooling := False;
If FindNextPrinterChangeNotification(
findhandle, ChangeReason, nil, Pointer(pni) )
Then Try
If ReasonWas( PRINTER_CHANGE_ADD_JOB ) Then begin
FJobInformation.Status := jsNew;
FJobInformation.Spooling := True;
end
Else If ReasonWas( PRINTER_CHANGE_DELETE_JOB ) Then
begin
FJobInformation.Status := jsCompleted;
FJobInformation.Spooling := False;
end
Else If ReasonWas( PRINTER_CHANGE_SET_JOB ) Then
FJobInformation.Status := FindJobStatus
Else If ReasonWas( PRINTER_CHANGE_WRITE_JOB ) Then
begin
FJobInformation.Status := jsProcessing;
FJobInformation.Spooling := True;
end
Else
FJobInformation.Status := jsNone;
If FJobInformation.Status <> jsNone Then Begin
GetJobInformation;
DoJobChange;
End; { If }
Finally
FreePrinterNotifyInfo( pni );
End; { Finally }
End; { TncPrintMonitor.HandleNotification }
Procedure TncPrintMonitor.Execute;
Const
jobfields : Array [1..9] of Word =
(
JOB_NOTIFY_FIELD_MACHINE_NAME,
JOB_NOTIFY_FIELD_USER_NAME,
JOB_NOTIFY_FIELD_DOCUMENT,
JOB_NOTIFY_FIELD_TOTAL_PAGES,
JOB_NOTIFY_FIELD_TOTAL_BYTES,
JOB_NOTIFY_FIELD_BYTES_PRINTED,
JOB_NOTIFY_FIELD_PAGES_PRINTED,
JOB_NOTIFY_FIELD_STATUS,
JOB_NOTIFY_FIELD_DEVMODE );
Var
handles: packed Record
findhandle, wakehandle: THandle;
end;
notifyOptions: PRINTER_NOTIFY_OPTIONS;
notifyType: PRINTER_NOTIFY_OPTIONS_TYPE;
retval: DWORD;
S: String;
Begin
FRunning := True;
If Terminated Then Exit;
notifyOptions.Version := 2;
notifyOptions.Count := 1;
notifyOptions.Flags := PRINTER_NOTIFY_OPTIONS_REFRESH;
notifyOptions.pTypes := @notifyType;
FillChar( notifyType, sizeof( notifyType ), 0 );
notifyType.wType := JOB_NOTIFY_TYPE;
notifyType.pFields := @jobfields;
notifyType.Count := High( jobfields )- Low( jobfields ) + 1;
handles.wakehandle := FWakeupEvent.Handle;
handles.findhandle :=
FindFirstPrinterChangeNotification(
Fprinterhandle,
PRINTER_CHANGE_JOB, // we are only interested in job-related changes
0, @notifyoptions );
If handles.findhandle <> INVALID_HANDLE_VALUE Then Begin
While not Terminated Do Begin
retval := WaitForMultipleObjects( 2, @handles, false, INFINITE );
If not Terminated Then
If retval = WAIT_OBJECT_0 Then
try
HandleNotification( handles.findhandle )
except
// HandleNotifiaction will only ever raise assertions,
// which the IDE debugger will trap for us
end
Else
Break;
End; { While }
FindClosePrinterChangeNotification( handles.findhandle );
End { If }
Else Begin
S:= 'FindFirstPrinterChangeNotification failed for printer '+
FJobInformation.PrinterName+', the system error is'#13#10+
SysErrorMessage( GetLastError );
Windows.MessageBox( 0, Pchar(S), 'Error', MB_OK or MB_ICONSTOP );
End; { Else }
End;
procedure TncPrintMonitor.GetJobs(aJL: TJobList);
type
TJobs = Array [0..1000] of JOB_INFO_1;
PJobs = ^TJobs;
var
hPrinter : THandle;
bytesNeeded, numJobs, i: Cardinal;
pJ: PJobs;
J : TncJob;
Status: Cardinal;
function StatusIs( flag: Cardinal ): Boolean;
Begin
Result := (flag and status) <> 0;
End; { StatusIs }
function GetStatus: Byte;
begin
Result := jsNone;
J.Spooling := StatusIs( JOB_STATUS_SPOOLING );
if StatusIs(JOB_STATUS_DELETED) then
J.Deleted := True;
If StatusIs( JOB_STATUS_PRINTED ) Then
Result := jsCompleted
Else If StatusIs( JOB_STATUS_DELETING ) Then
Result := jsNone
// we skip this case because we will get another notification for that
Else If StatusIs( JOB_STATUS_SPOOLING )
Then
Result := jsProcessing
Else If StatusIs( JOB_STATUS_PRINTING )
Then
Result := jsPrinting
Else If StatusIs( JOB_STATUS_ERROR or JOB_STATUS_OFFLINE or
JOB_STATUS_PAPEROUT )
Then
Result := jsError
Else If StatusIs( JOB_STATUS_PAUSED ) Then
Result := jsPaused;
end;
begin
EnumJobs( FPrinterHandle, 0, 1000, 1, Nil, 0, bytesNeeded, numJobs );
if bytesNeeded=0 then Exit;
GetMem( pJ, bytesNeeded );
try
if not EnumJobs( FPrinterHandle, 0, 1000, 1, pJ, bytesNeeded, bytesNeeded, numJobs ) then Exit;
for I := 0 to numJobs - 1 do begin
J := TncJob.Create;
with J do begin
PrtHandle := FPrinterHandle;
PrinterIndex := FJobInformation.PrinterIndex;
PrinterName := FJobInformation.PrinterName;
PrinterPort := FJobInformation.PrinterPort;
PrinterServer := FJobInformation.PrinterServer;
PrinterShare := FJobInformation.PrinterShare;
end;
J.Computer := pJ^[i].pMachineName;
J.User := pJ^[i].pUserName;
J.Document := pJ^[i].pDocument;
DebugMsg('TncPrintMonitor.DoJobChange - GetJobs - ' + J.Document);
J.Pages := pJ^[i].PagesPrinted;
J.TotalPages := pJ^[i].TotalPages;
J.JobID := pJ^[i].JobId;
Status := pJ^[i].Status;
aJL.Add(J);
J.Status := GetStatus;
J.StatusPaused := StatusIs(Job_Status_Paused);
end;
finally
FreeMem(pJ);
end;
end;
function TncPrintMonitor.GetPrinterIndex: Integer;
begin
Result := FJobInformation.PrinterIndex;
end;
{: Create the thread suspended, create the wakeup event. }
Constructor TncPrintMonitor.InternalCreate;
Begin
inherited Create( true );
FWakeupEvent := TSimpleEvent.Create;
End;
function TncPrintMonitor.SamePrinterName(aName: String): Boolean;
begin
with FJobInformation do begin
while Pos('\', aName)>0 do
Delete(aName, 1, Pos('\', aName));
Result := SameText(PrinterName, aName) or
SameText(PrinterShare, aName);
end;
end;
Procedure TncPrintMonitor.Wakeup;
Begin
FWakeupEvent.SetEvent;
End;
{ TncPrintersMonitor 覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧覧抑
Const
UM_JOBNOTIFICATION = WM_APP;
Constructor TncPrintersMonitor.Create(aOwner: TComponent);
Begin
inherited;
FJobDeletedEvent := nil;
If not (csDesigning In ComponentState) Then Begin
FInternalSyncHelper := Classes.AllocateHWnd( WndProc );
FPendingNotifications := TThreadList.Create;
FNotifiers := TObjectList.Create( true ); // Owns the objects
CreateNotifiers;
End; { If }
End;
Procedure TncPrintersMonitor.CreateNotifiers;
Var
aNotifier: TncPrintMonitor;
i: Integer;
oldIndex: Integer;
Begin
If Printer.Printers.Count > 0 Then
Try
oldindex := Printer.PrinterIndex;
Try
For i:= 0 To Printer.Printers.Count-1 Do Begin
aNotifier := TncPrintMonitor.CreateMonitor( i, JobNotification );
If Assigned( aNotifier ) Then
FNotifiers.Add( aNotifier );
End; { For }
Finally
Printer.PrinterIndex := oldIndex;
End; { Finally }
Except
// this is a crutch. If no default printer is defined accessing
// PrinterIndex can cause an exception
End; { Except }
End;
Destructor TncPrintersMonitor.Destroy;
Begin
FNotifiers.Free;
FPendingNotifications.Free;
Classes.DeallocateHWnd( FInternalSyncHelper );
inherited;
End;
Procedure TncPrintersMonitor.DoJobChange(
const aJobinformation: TncJob);
Begin
If Assigned( FJobChangeEvent ) Then
FJobChangeEvent( aJobinformation );
End;
Procedure TncPrintersMonitor.DoJobComplete(
const aJobinformation: TncJob);
Begin
If Assigned( FJobCompleteEvent ) Then
FJobCompleteEvent( aJobinformation );
End;
Procedure TncPrintersMonitor.DoNewJob(
const aJobinformation: TncJob);
Begin
If Assigned( FNewJobEvent ) Then
FNewJobEvent( aJobinformation );
End;
function TncPrintersMonitor.GetJobList: TJobList;
var I : Integer;
begin
Result := TJobList.Create;
for I := 0 to FNotifiers.Count-1 do
TncPrintMonitor(FNotifiers[I]).GetJobs(Result);
end;
function TncPrintersMonitor.GetPrinterIndexByName(
aPrinterName: String): Integer;
var
I: Integer;
begin
for I := 0 to FNotifiers.Count - 1 do with TncPrintMonitor(FNotifiers[I]) do
if SamePrinterName(aPrinterName) then begin
Result := PrtIndex;
Exit;
end;
Result := -1;
end;
procedure TncPrintersMonitor.JobControl(aPrinterIndex: Integer;
aJobID: Cardinal; aControl: Byte);
var I: Integer;
begin
for I := 0 to FNotifiers.Count - 1 do with TncPrintMonitor(FNotifiers[I]) do
if PrtIndex=aPrinterIndex then begin
SetJob(PrtHandle, aJobID, 0, nil, aControl);
DebugMsg('TncPrintersMonitor.JobControl - aPrinterIndex: ' +
IntToStr(aPrinterIndex) +
' - aJobID: ' + IntToStr(aJobId) +
' - aControl: ' + IntToStr(aControl) +
' - Error: ' + IntToStr(GetLastError));
Exit;
end;
DebugMsg('TncPrintersMonitor.JobControl - aPrinterIndex: ' +
IntToStr(aPrinterIndex) +
' - aJobID: ' + IntToStr(aJobId) +
' - aControl: ' + IntToStr(aControl) + ' - aPrinterIndex n縊 encontrado');
end;
Procedure TncPrintersMonitor.JobNotification(
const Jobinfo: TncJob);
var Erro: Integer;
function GetDocName: String;
var
jobInfo2:PjobInfo2;
bytesNeeded:DWORD;
Erro: Cardinal;
begin
Result := jobinfo.Document;
JobInfo2:=nil;
try
GetJob(jobinfo.PrtHandle,jobinfo.JobID,2,nil,0,@bytesNeeded);
Erro := GetLastError;
If Erro<>ERROR_INSUFFICIENT_BUFFER then begin
DebugMsg('GetDocName - A-Erro: ' + IntToStr(Erro)+' - PrtHandle: ' + IntToStr(jobinfo.PrtHandle) + ' - JobID: ' + IntToStr(Jobinfo.JobID));
Exit;
end;
jobInfo2:=AllocMem(bytesNeeded);
try
If not GetJob(jobinfo.PrtHandle, jobinfo.JobID, 2, JobInfo2,bytesNeeded, @bytesNeeded) then begin
DebugMsg('GetDocName - B-Erro: ' + IntToStr(GetLastError)+' - PrtHandle: ' + IntToStr(jobinfo.PrtHandle) + ' - JobID: ' + IntToStr(Jobinfo.JobID));
Exit;
end;
Result := jobinfo2.pDocument;
DebugMsg('GetDocName OK - ' + Result);
except
exit;
end;
finally
freeMem(JobInfo2);
end;
end;
Begin
DebugMsg('TncPrintersMonitor.JobNotification - Status: '+IntToStr(JobInfo.Status) +
' - PMPDF: ' + BoolStr[gConfig.PMPDF] +
' - PMPausaAutomatica: ' + BoolStr[gConfig.PMPausaAutomatica] +
' - gNaoPausar.PausarEsteComp: ' + BoolStr[gNaoPausar.FPausarEsteComp] +
' - gNaoPausar.EsteComp: ' + gNaoPausar.FEsteComp +
' - JobInfo.Computer: ' + JobInfo.Computer);
JobInfo.Document := GetDocName;
if gConfig.PausarJobs then
if (JobInfo.Status=jsNew) and gNaoPausar.Pausar(JobInfo.Computer) and (not JobInfo.Doc_NexCafe) then begin
JobInfo.Pausou := True;
if SetJob(JobInfo.PrtHandle, JobInfo.JobID, 0, nil, JOB_CONTROL_PAUSE) then
begin
JobInfo.Pausou := True;
DebugMsg('TncPrintersMonitor.JobNotification - SetJob - JobID: ' + IntToStr(JobInfo.JobId) + ' - JOB_CONTROL_PAUSE OK - Computer: '+JobInfo.Computer);
end else
DebugMsg('TncPrintersMonitor.JobNotification - SetJob - JobID: ' + IntToStr(JobInfo.JobId) + ' - JOB_CONTROL_PAUSE ERROR: ' + IntToStr(GetlastError));
end else begin
JobInfo.Pausou := False;
if JobInfo.Status=jsNew then
DebugMsg('TncPrintersMonitor.JobNotification - Pausa desativada');
end;
FPendingNotifications.Add( JobInfo.Clone );
PostMessage( FInternalSyncHelper, UM_JOBNOTIFICATION, 0, 0 );
End;
Procedure TncPrintersMonitor.ProcessNotifications;
Var
items: TObjectList;
list: TList;
i: Integer;
jobinfo: TncJob;
Begin
items := nil;
list:= FPendingNotifications.LockList;
Try
If list.count > 0 Then Begin
items:= TOBjectlist.Create; // owns its objects
For i:=0 To list.Count-1 Do
items.add( TObject( list[i] ));
list.Clear;
End; { If }
Finally
FPendingNotifications.UnlockList;
End; { Finally }
If Assigned( items ) Then
Try
For i:= 0 To items.count-1 Do Begin
jobinfo:= TncJob( items[i] );
Case jobinfo.Status Of
jsNew : DoNewJob( jobinfo );
jsCompleted : DoJobComplete( jobinfo );
Else
DoJobChange( jobinfo );
End; { Case }
End; { For }
Finally
items.Free
End; { Finally }
End;
Procedure TncPrintersMonitor.SetActive(const Value: Boolean);
Var
i: Integer;
Begin
If FActive <> Value Then Begin
FActive := Value;
If not (csDesigning In ComponentState) Then
For i:= 0 to FNotifiers.Count-1 Do
If Value Then
TncPrintMonitor( FNotifiers[i] ).Resume
Else
TncPrintMonitor( FNotifiers[i] ).Suspend;
End; { If }
End;
Procedure TncPrintersMonitor.WndProc(var msg: TMessage);
Begin
If msg.Msg = UM_JOBNOTIFICATION Then
ProcessNotifications
Else
msg.Result := DefWindowProc( FInternalSyncHelper,
msg.Msg,
msg.WParam,
msg.LParam );
End;
{ TJobList }
function TJobList.Exists(aPrinterIndex: Integer; aID: Cardinal): Boolean;
var i: Integer;
begin
for I := 0 to Count-1 do with Jobs[I] do
if (PrinterIndex=aPrinterIndex) and (JobID=aID) then begin
Result := True;
Exit;
end;
Result := False;
end;
function TJobList.GetJob(aIndex: Integer): TncJob;
begin
Result := TncJob(Items[aIndex]);
end;
{ TncNaoPausar }
constructor TncNaoPausar.Create;
begin
FItens := TStringList.Create;
FCS := TCriticalSection.Create;
FPausarEsteComp := False;
FEsteComp := '';
end;
destructor TncNaoPausar.Destroy;
begin
FCS.Free;
FItens.Free;
inherited;
end;
function TncNaoPausar.Pausar(AComp: String): Boolean;
begin
while Copy(AComp, 1, 1)='\' do Delete(AComp, 1, 1);
FCS.Enter;
try
if SameText(AComp, FEsteComp) then
Result := FPausarEsteComp else
Result := (FItens.IndexOf(AComp)=-1);
finally
FCS.Leave
end;
end;
procedure TncNaoPausar.SetEsteComp(const AComp: String);
begin
FCS.Enter;
try
FEsteComp := AComp;
finally
FCS.Leave;
end;
end;
procedure TncNaoPausar.SetNaoPausar(const aText: String);
begin
FCS.Enter;
try
FItens.Text := aText;
finally
FCS.Leave;
end;
end;
procedure TncNaoPausar.SetPausarEsteComp(const APausarEsteComp: Boolean);
begin
FCS.Enter;
try
FPausarEsteComp := APausarEsteComp;
finally
FCS.Leave;
end;
end;
procedure TncNaoPausar.SetText(const aText: String);
begin
FCS.Enter;
try
FItens.Text := aText;
finally
FCS.Leave;
end;
end;
initialization
gNaoPausar := TncNaoPausar.Create;
finalization
gNaoPausar.Free;
end.
|
{
Version 12
Copyright (c) 2011-2012 by Bernd Gabriel
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS
are covered by separate copyright notices located in those modules.
}
{$I htmlcons.inc}
unit HtmlStyles;
interface
uses
Windows, Classes, Contnrs, Variants, SysUtils, Graphics,
//
HtmlGlobals,
HtmlSymbols,
Parser,
StyleTypes;
//------------------------------------------------------------------------------
// style properties
//------------------------------------------------------------------------------
type
// http://www.w3.org/TR/2010/WD-CSS2-20101207/cascade.html#cascade
TPropertyOrigin = (
poDefault,// default value
poAgent, // user agent
poUser, // user preferences
poStyle, // author by style attribute
poAuthor // author resp. document
);
// http://www.w3.org/TR/2010/WD-CSS2-20101207/cascade.html#cascade
// ascending precedence:
TPropertyPrecedence = (
ppDefault, // default value of object type
ppInherited, // inherited from parent object
ppAgent, // default property by user agent
ppUserNormal, // normal user property preference
ppHtmlAttribute, // by html attribute
ppStyleNormal, // normal author resp. document property by style attribute
ppAuthorNormal, // normal author resp. document property
ppAuthorImportant, // important author propery
ppStyleImportant, // important author resp. document property by style attribute
ppUserImportant // important user property preference
);
const
CPropertyPrecedence: array [TPropertyPrecedence] of ThtString = (
'Default', // default value of object type
'Inherited', // inherited from parent object
'Agent', // default property by user agent
'User Normal', // normal user property preference
'Html Attribute', // by html attribute
'Style Normal', // normal author resp. document property by style attribute
'Author Normal', // normal author resp. document property
'Author Important', // important author propery
'Style Important', // important author resp. document property by style attribute
'User Important' // important user property preference
);
//
CPropertyPrecedenceOfOrigin: array [Boolean, TPropertyOrigin] of TPropertyPrecedence = (
(ppdefault, ppAgent, ppUserNormal, ppStyleNormal, ppAuthorNormal),
(ppdefault, ppAgent, ppUserImportant, ppStyleImportant, ppAuthorImportant)
);
// custom variant types range from $110 (272) to $7FF (2047)
const
varInherit = $123; // a value of this variant type indicates, that this value is to be inherited from parent object.
function Inherit: Variant; //{$ifdef UseInline} inline; {$endif}
function VarIsInherit(const Value: Variant): Boolean; //{$ifdef UseInline} inline; {$endif}
type
TStyleProperty = class
private
FPrev: TStyleProperty;
FNext: TStyleProperty;
FSymbol: TStylePropertySymbol;
FPrecedence: TPropertyPrecedence;
FValue: Variant;
public
constructor Create(Symbol: TStylePropertySymbol; Precedence: TPropertyPrecedence; const Value: Variant); overload;
function ToString: ThtString; {$ifdef UseToStringOverride} override; {$endif}
destructor Destroy; override;
property Symbol: TStylePropertySymbol read FSymbol;
property Precedence: TPropertyPrecedence read FPrecedence;
property Value: Variant read FValue write FValue;
property Next: TStyleProperty read FNext;
property Prev: TStyleProperty read FPrev;
end;
TStylePropertyList = {$ifdef UseEnhancedRecord} record {$else} class {$endif}
private
FFirst: TStyleProperty;
FLast: TStyleProperty;
function GetItem(Index: TStylePropertySymbol): TStyleProperty;
public
function IsEmpty: Boolean;
function ToString: ThtString; {$ifdef UseEnhancedRecord} {$else} {$ifdef UseToStringOverride} override; {$endif} {$endif}
procedure Add(Prop: TStyleProperty);
procedure Assign(const List: TStylePropertyList);
procedure Clear;
{$ifdef UseEnhancedRecord}
procedure Free;
{$endif}
procedure Init;
procedure Remove(Prop: TStyleProperty);
property First: TStyleProperty read FFirst;
property Last: TStyleProperty read FLast;
property Items[Index: TStylePropertySymbol]: TStyleProperty read GetItem; default;
end;
//------------------------------------------------------------------------------
// style selectors
//------------------------------------------------------------------------------
type
TAttributeMatchOperator = (
amoSet, // [name] : matches, if attr is set and has any value.
amoEquals, // [name=value] : matches, if attr equals value.
amoContains, // [name~=value] : matches, if attr is a white space separated list of values and value is one of these values.
amoStartsWith // [name|=value] : matches, if attr equals value or starts with value immediately followed by a hyphen.
);
const
CAttributeMatchOperator: array [TAttributeMatchOperator] of string = (
'', // [name] : matches, if attr is set and has any value.
'=', // [name=value] : matches, if attr equals value.
'~=', // [name~=value] : matches, if attr is a white space separated list of values and value is one of these values.
'|=' // [name|=value] : matches, if attr equals value or starts with value immediately followed by a hyphen.
);
type
TAttributeMatch = class
private
FAttr: THtmlAttributeSymbol;
FOper: TAttributeMatchOperator;
FValue: ThtString;
public
constructor Create(Attribute: THtmlAttributeSymbol; Oper: TAttributeMatchOperator; const Value: ThtString);
function ToString: ThtString; {$ifdef UseToStringOverride} override; {$endif}
property Attribute: THtmlAttributeSymbol read FAttr;
property Oper: TAttributeMatchOperator read FOper;
property Value: ThtString read FValue;
end;
TAttributeMatchList = class(TObjectList)
private
function GetItem(Index: Integer): TAttributeMatch;
public
function Same(List: TAttributeMatchList): Boolean; overload; {$ifdef UseInline} inline; {$endif}
function ToString: ThtString; {$ifdef UseToStringOverride} override; {$endif}
procedure Sort; overload; {$ifdef UseInline} inline; {$endif}
property Items[Index: Integer]: TAttributeMatch read GetItem; default;
end;
function CompareAttributeMatches(P1, P2: Pointer): Integer;
function TryStrToAttributeMatchOperator(Str: ThtString; out Oper: TAttributeMatchOperator): Boolean;
type
TPseudo = (
pcNone,
// pseudo classes
pcLink,
pcVisited,
pcActive,
pcHover,
pcFocus,
pcFirstChild,
//TODO: pcLanguage, requires additional data
// pseudo elements
peFirstLine,
peFirstLetter,
peBefore,
peAfter
);
TPseudos = set of TPseudo;
TPseudoClass = pcLink..pcFirstChild;
TPseudoElement = peFirstLine..peAfter;
const
CPseudo: array[TPseudo] of ThtString = (
// pseudo classes
'',
'link',
'visited',
'active',
'hover',
'focus',
'first-child',
//TODO: 'language(...)'
// pseudo elements
'first-line',
'first-letter',
'before',
'after');
PseudoClasses = [
pcLink,
pcVisited,
pcActive,
pcHover,
pcFocus,
pcFirstChild
//TODO: pcLanguage, requires additional data
];
PseudoElements = [
peFirstLine,
peFirstLetter,
peBefore,
peAfter
];
function TryStrToPseudo(const Str: ThtString; out Pseudo: TPseudo): Boolean;
type
TStyleCombinator = (
scNone, // F : matches any F
scDescendant, // E F : matches F, if it is descendant of E
scChild, // E > F : matches F, if it is child of E
scFollower // E + F : matches F, if it immediately follows sibling E
);
TStyleSelectorState = set of (
ssSorted
);
// a simple selector
TStyleSelector = class
private
FPrev: TStyleSelector;
FNext: TStyleSelector;
FTags: ThtStringArray;
FClasses: ThtStringArray;
FIds: ThtStringArray;
FPseudos: TPseudos;
FAttributeMatches: TAttributeMatchList;
FIsFromStyleAttr: Boolean;
FSelectorState: TStyleSelectorState;
FNumberOfElements: Integer;
FNumberOfNonIds: Integer;
function NumberOfIDs: Integer; {$ifdef UseInline} inline; {$endif}
procedure Sort; {$ifdef UseInline} inline; {$endif}
property NumberOfElements: Integer read FNumberOfElements;
property NumberOfNonIDs: Integer read FNumberOfNonIds;
public
destructor Destroy; override;
function AttributeMatchesCount: Integer; {$ifdef UseInline} inline; {$endif}
function Same(Selector: TStyleSelector): Boolean; virtual;
function ToString: ThtString; {$ifdef UseToStringOverride} override; {$else} virtual; {$endif}
function CompareSpecificity(ASelector: TStyleSelector): Integer;
procedure AddAttributeMatch(AAttributeMatch: TAttributeMatch); {$ifdef UseInline} inline; {$endif}
procedure AddClass(AClass: ThtString); {$ifdef UseInline} inline; {$endif}
procedure AddId(AId: ThtString); {$ifdef UseInline} inline; {$endif}
procedure AddPseudo(APseudo: TPseudo); {$ifdef UseInline} inline; {$endif}
procedure AddTag(ATag: ThtString);
property Tags: ThtStringArray read FTags;
property Classes: ThtStringArray read FClasses;
property Ids: ThtStringArray read FIds;
property Pseudos: TPseudos read FPseudos;
property AttributeMatches: TAttributeMatchList read FAttributeMatches;
property Next: TStyleSelector read FNext;
property Prev: TStyleSelector read FPrev;
end;
// a compound selector
TCombinedSelector = class(TStyleSelector)
private
FLeftHand: TStyleSelector;
FCombinator: TStyleCombinator;
public
constructor Create(LeftHand: TStyleSelector; Combinator: TStyleCombinator);
destructor Destroy; override;
function ToString: ThtString; override;
property Combinator: TStyleCombinator read FCombinator;
property LeftHand: TStyleSelector read FLeftHand;
end;
TStyleSelectorList = {$ifdef UseEnhancedRecord} record {$else} class {$endif}
private
FFirst: TStyleSelector;
FLast: TStyleSelector;
public
function IsEmpty: Boolean;
function ToString: ThtString; {$ifdef UseEnhancedRecord} {$else} {$ifdef UseToStringOverride} override; {$endif} {$endif}
procedure Init;
procedure Add(Sele: TStyleSelector);
procedure Assign(const List: TStyleSelectorList);
procedure Clear;
{$ifdef UseEnhancedRecord}
procedure Free;
{$endif}
procedure Remove(Prop: TStyleSelector);
property First: TStyleSelector read FFirst;
property Last: TStyleSelector read FLast;
end;
//------------------------------------------------------------------------------
// style rule sets
//------------------------------------------------------------------------------
type
TRuleset = class
private
FMediaTypes: TMediaTypes;
public
Properties: TStylePropertyList;
Selectors: TStyleSelectorList;
constructor Create(MediaTypes: TMediaTypes);
destructor Destroy; override;
function ToString: ThtString; {$ifdef UseToStringOverride} override; {$endif}
property MediaTypes: TMediaTypes read FMediaTypes;
end;
TRulesetList = class(TObjectList)
private
function GetItem(Index: Integer): TRuleset;
public
function ToString: ThtString; {$ifdef UseToStringOverride} override; {$endif}
procedure InsertList(Index: Integer; Rulesets: TRulesetList);
property Items[Index: Integer]: TRuleset read GetItem; default;
end;
//------------------------------------------------------------------------------
// resulting properties
//------------------------------------------------------------------------------
// A temporary collection of properties while computing the effective values.
//------------------------------------------------------------------------------
TResultingProperty = class
// references data only, does not own it.
private
FProperty: TStyleProperty;
FSelector: TStyleSelector;
public
function GetBorderStyle(Parent, Default: TBorderStyle): TBorderStyle;
function GetColor(Parent, Default: TColor): TColor;
function GetDisplay(Parent, Default: TDisplayStyle): TDisplayStyle;
function GetFloat(Parent, Default: TBoxFloatStyle): TBoxFloatStyle;
function GetFontName(Parent, Default: ThtString): ThtString;
function GetFontSize(DefaultFontSize, Parent, Default: Double): Double;
function GetFontWeight(Parent, Default: Integer): Integer;
function GetLength(Parent, Base, EmBase, Default: Double): Double;
function GetPosition(Parent, Default: TBoxPositionStyle): TBoxPositionStyle;
function GetTextDecoration(Parent, Default: TFontStyles): TFontStyles;
function GetValue(Parent, Default: Variant): Variant;
function HasValue: Boolean;
function IsItalic(Parent, Default: Boolean): Boolean;
//
function Compare(const AProperty: TStyleProperty; const ASelector: TStyleSelector): Integer; {$ifdef UseInline} inline; {$endif}
procedure Update(const AProperty: TStyleProperty; const ASelector: TStyleSelector); {$ifdef UseInline} inline; {$endif}
property Prop: TStyleProperty read FProperty;
property Sele: TStyleSelector read FSelector;
end;
TResultingProperties = array [TStylePropertySymbol] of TResultingProperty;
THtmlElementBoxingInfo = record
Display: TDisplayStyle;
Position: TBoxPositionStyle;
Float: TBoxFloatStyle;
end;
// How to compute the resulting properties:
// 1) Fill map with properties from style attribute (highest prio) using UpdateFromStyleAttribute(),
// 2) Walk through ruleset list in reverse order. If a selector of the ruleset matches,
// then call UpdateFromProperties() with the ruleset's properties and if the combination has a
// higher cascading order, this becomes the new resulting value.
// 3) Fill up missing properties with other tag attributes (like color, width, height, ...).
//
// Using reverse order minimizes comparing and update effort.
TResultingPropertyMap = class
private
FProps: TResultingProperties; // the resulting properties
procedure Update(const AProperty: TStyleProperty; const ASelector: TStyleSelector);
public
destructor Destroy; override;
function Get(Index: TStylePropertySymbol): TResultingProperty; {$ifdef UseInline} inline; {$endif}
function GetColors(Left, Top, Right, Bottom: TPropertySymbol; const Parent, Default: TRectColors): TRectColors;
function GetLengths(Left, Top, Right, Bottom: TPropertySymbol; const Parent, Default: TRectIntegers; BaseSize: Integer): TRectIntegers;
function GetStyles(Left, Top, Right, Bottom: TPropertySymbol; const Parent, Default: TRectStyles): TRectStyles;
procedure GetElementBoxingInfo(var Info: THtmlElementBoxingInfo);
procedure UpdateFromAttributes(const Properties: TStylePropertyList; IsFromStyleAttr: Boolean);
procedure UpdateFromProperties(const Properties: TStylePropertyList; const ASelector: TStyleSelector); {$ifdef UseInline} inline; {$endif}
property Properties[Index: TStylePropertySymbol]: TResultingProperty read Get; default;
end;
//------------------------------------------------------------------------------
//
//------------------------------------------------------------------------------
function GetCssDefaults: TStream;
implementation
var
StyleAttributeSelector: TStyleSelector;
StyleTagSelector: TStyleSelector;
{$R css_defaults.res}
//-- BG ---------------------------------------------------------- 20.03.2011 --
function GetCssDefaults: TStream;
begin
Result := TResourceStream.Create(hInstance, 'CSS_DEFAULTS', RT_RCDATA);
end;
//-- BG ---------------------------------------------------------- 15.03.2011 --
function TryStrToPseudo(const Str: ThtString; out Pseudo: TPseudo): Boolean;
var
I: TPseudo;
begin
for I := low(I) to high(I) do
if CPseudo[I] = Str then
begin
Result := True;
Pseudo := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 21.03.2011 --
function Inherit: Variant;
// returns a variant of type varInherit
begin
TVarData(Result).VType := varEmpty; //varInherit;
end;
//-- BG ---------------------------------------------------------- 21.03.2011 --
function VarIsInherit(const Value: Variant): Boolean;
// returns true, if Value is of type varInherit
begin
Result := VarType(Value) = varEmpty; //varInherit;
end;
{ TStyleProperty }
//-- BG ---------------------------------------------------------- 13.03.2011 --
constructor TStyleProperty.Create(Symbol: TStylePropertySymbol; Precedence: TPropertyPrecedence; const Value: Variant);
begin
inherited Create;
FSymbol := Symbol;
FPrecedence := Precedence;
FValue := Value;
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
destructor TStyleProperty.Destroy;
begin
if Prev <> nil then
Prev.FNext := Next;
if Next <> nil then
Next.FPrev := Prev;
inherited;
end;
//-- BG ---------------------------------------------------------- 19.03.2011 --
function TStyleProperty.ToString: ThtString;
function VariantToStr(Value: Variant): ThtString;
begin
if VarIsNull(Value) then
Result := ''
else if VarIsStr(Value) then
Result := '"' + Value + '"'
else if VarIsInherit(Value) then
Result := '"inherit"'
else
Result := Value;
end;
begin
Result :=
PropertySymbolToStr(FSymbol) + ': ' + VariantToStr(Value) +
' /* ' + CPropertyPrecedence[FPrecedence] + ' */';
end;
{ TStylePropertyList }
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStylePropertyList.Add(Prop: TStyleProperty);
var
Prev: TStyleProperty;
Next: TStyleProperty;
begin
assert(Prop.Next = nil, 'Don''t add chained links twice. Prop.Next is not nil.');
assert(Prop.Prev = nil, 'Don''t add chained links twice. Prop.Prev is not nil.');
// find neighbors
Prev := nil;
Next := First;
while (Next <> nil) and (Next.Symbol < Prop.Symbol) do
begin
Prev := Next;
Next := Prev.Next;
end;
// link to prev
if Prev = nil then
FFirst := Prop
else
Prev.FNext := Prop;
Prop.FPrev := Prev;
// link to next
if Next = nil then
FLast := Prop
else
Next.FPrev := Prop;
Prop.FNext := Next;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStylePropertyList.Assign(const List: TStylePropertyList);
begin
FFirst := List.FFirst;
FLast := List.FLast;
end;
//-- BG ---------------------------------------------------------- 03.04.2011 --
procedure TStylePropertyList.Clear;
var
Link: TStyleProperty;
begin
FLast := nil;
while First <> nil do
begin
Link := First;
FFirst := Link.Next;
Link.Free;
end;
end;
{$ifdef UseEnhancedRecord}
//-- BG ---------------------------------------------------------- 16.04.2011 --
procedure TStylePropertyList.Free;
begin
Clear;
end;
{$endif}
//-- BG ---------------------------------------------------------- 16.04.2011 --
function TStylePropertyList.GetItem(Index: TStylePropertySymbol): TStyleProperty;
begin
Result := First;
while Result <> nil do
begin
if Result.Symbol = Index then
exit;
if Result.Symbol > Index then
begin
Result := nil;
exit;
end;
Result := Result.Next;
end;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStylePropertyList.Init;
begin
FFirst := nil;
FLast := nil;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
function TStylePropertyList.IsEmpty: Boolean;
begin
Result := First = nil;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStylePropertyList.Remove(Prop: TStyleProperty);
begin
//TODO -1 -oBG, 02.04.2011
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
function TStylePropertyList.ToString: ThtString;
var
Prop: TStyleProperty;
begin
Result := '';
Prop := First;
if Prop <> nil then
begin
Result := CrLfTab + Prop.ToString;
Prop := Prop.Next;
while Prop <> nil do
begin
Result := Result + ';' + CrLfTab + Prop.ToString;
Prop := Prop.Next;
end;
end;
end;
{ TAttributeMatch }
//-- BG ---------------------------------------------------------- 14.03.2011 --
constructor TAttributeMatch.Create(Attribute: THtmlAttributeSymbol; Oper: TAttributeMatchOperator; const Value: ThtString);
begin
inherited Create;
FAttr := Attribute;
FOper := Oper;
FValue := Value;
end;
//-- BG ---------------------------------------------------------- 21.03.2011 --
function TAttributeMatch.ToString: ThtString;
var
Name: ThtString;
begin
Name := AttributeSymbolToStr(Attribute);
case Oper of
amoSet: Result := '[' + Name + ']';
else
Result := '[' + Name + CAttributeMatchOperator[Oper] + Value + ']';
end;
end;
{ TAttributeMatchList }
//-- BG ---------------------------------------------------------- 14.03.2011 --
function TAttributeMatchList.GetItem(Index: Integer): TAttributeMatch;
begin
Result := Get(Index);
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function CompareAttributeMatches(P1, P2: Pointer): Integer;
var
A1: TAttributeMatch absolute P1;
A2: TAttributeMatch absolute P2;
begin
Result := Ord(A1.Attribute) - Ord(A2.Attribute);
if Result <> 0 then
exit;
Result := Ord(A1.Oper) - Ord(A2.Oper);
if Result <> 0 then
exit;
Result := htCompareString(A1.Value, A2.Value);
end;
//-- BG ---------------------------------------------------------- 25.04.2011 --
function TryStrToAttributeMatchOperator(Str: ThtString; out Oper: TAttributeMatchOperator): Boolean;
var
I: TAttributeMatchOperator;
begin
for I := low(I) to high(I) do
if CAttributeMatchOperator[I] = Str then
begin
Result := True;
Oper := I;
exit;
end;
Result := False;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function TAttributeMatchList.Same(List: TAttributeMatchList): Boolean;
var
I, N: Integer;
begin
N := Count;
Result := N = List.Count;
if Result then
for I := 0 To N - 1 do
if CompareAttributeMatches(Self[I], List[I]) <> 0 then
begin
Result := False;
break;
end;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
procedure TAttributeMatchList.Sort;
begin
inherited Sort(CompareAttributeMatches);
end;
//-- BG ---------------------------------------------------------- 21.03.2011 --
function TAttributeMatchList.ToString: ThtString;
var
I: Integer;
begin
Result := '';
for I := 0 to Count - 1 do
Result := Result + Self[I].ToString;
end;
{ TStyleSelector }
//-- BG ---------------------------------------------------------- 14.03.2011 --
procedure TStyleSelector.AddAttributeMatch(AAttributeMatch: TAttributeMatch);
begin
if FAttributeMatches = nil then
FAttributeMatches := TAttributeMatchList.Create(True);
FAttributeMatches.Add(AAttributeMatch);
Inc(FNumberOfNonIds);
end;
//-- BG ---------------------------------------------------------- 14.03.2011 --
procedure TStyleSelector.AddClass(AClass: ThtString);
var
Index: Integer;
begin
Index := Length(FClasses);
SetLength(FClasses, Index + 1);
FClasses[Index] := AClass;
Inc(FNumberOfNonIds);
end;
//-- BG ---------------------------------------------------------- 14.03.2011 --
procedure TStyleSelector.AddId(AId: ThtString);
var
Index: Integer;
begin
Index := Length(FIds);
SetLength(FIds, Index + 1);
FIds[Index] := AId;
Inc(FNumberOfElements);
end;
//-- BG ---------------------------------------------------------- 14.03.2011 --
procedure TStyleSelector.AddPseudo(APseudo: TPseudo);
begin
if APseudo in FPseudos then
exit;
Include(FPseudos, APseudo);
if APseudo in PseudoElements then
Inc(FNumberOfElements)
else //if APseudo in PseudoClasses then
Inc(FNumberOfNonIds);
end;
//-- BG ---------------------------------------------------------- 14.03.2011 --
procedure TStyleSelector.AddTag(ATag: ThtString);
var
Index: Integer;
begin
Index := Length(FTags);
SetLength(FTags, Index + 1);
FTags[Index] := ATag;
Inc(FNumberOfElements);
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function TStyleSelector.AttributeMatchesCount: Integer;
begin
if FAttributeMatches <> nil then
Result := FAttributeMatches.Count
else
Result := 0;
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
function TStyleSelector.CompareSpecificity(ASelector: TStyleSelector): Integer;
// http://www.w3.org/TR/2010/WD-CSS2-20101207/cascade.html#specificity
begin
Result := Ord(FIsFromStyleAttr) - Ord(ASelector.FIsFromStyleAttr);
if Result <> 0 then
exit;
Result := NumberOfIDs - ASelector.NumberOfIDs;
if Result <> 0 then
exit;
Result := NumberOfNonIDs - ASelector.NumberOfNonIDs;
if Result <> 0 then
exit;
Result := NumberOfElements - ASelector.NumberOfElements;
end;
//-- BG ---------------------------------------------------------- 14.03.2011 --
destructor TStyleSelector.Destroy;
begin
FAttributeMatches.Free;
inherited;
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
function TStyleSelector.NumberOfIDs: Integer;
begin
Result := Length(FIds);
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function TStyleSelector.Same(Selector: TStyleSelector): Boolean;
begin
Sort;
Selector.Sort;
Result := False;
if Length(FTags) = Length(Selector.FTags) then
if Length(FClasses) = Length(Selector.FClasses) then
if Length(FIds) = Length(Selector.FIds) then
if AttributeMatchesCount = Selector.AttributeMatchesCount then
if FPseudos = Selector.FPseudos then
if SameStringArray(FClasses, Selector.FClasses) then
if SameStringArray(FTags, Selector.FTags) then
Result := FAttributeMatches.Same(Selector.FAttributeMatches);
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
procedure TStyleSelector.Sort;
begin
if not (ssSorted in FSelectorState) then
begin
SortStringArray(FTags);
SortStringArray(FClasses);
SortStringArray(FIds);
if FAttributeMatches <> nil then
FAttributeMatches.Sort;
Include(FSelectorState, ssSorted);
end;
end;
//-- BG ---------------------------------------------------------- 19.03.2011 --
function TStyleSelector.ToString: ThtString;
var
I: Integer;
P: TPseudo;
begin
if Length(FTags) = 1 then
Result := FTags[0]
else
Result := '';
for I := Low(FClasses) to High(FClasses) do
Result := Result + '.' + FClasses[I];
for I := Low(FIds) to High(FIds) do
Result := Result + '#' + FIds[I];
for P := Low(TPseudo) to High(TPseudo) do
if P in FPseudos then
Result := Result + ':' + CPseudo[P];
if Result = '' then
Result := '*';
if FAttributeMatches <> nil then
Result := Result + FAttributeMatches.ToString;
end;
{ TCombinedSelector }
//-- BG ---------------------------------------------------------- 15.03.2011 --
constructor TCombinedSelector.Create(LeftHand: TStyleSelector; Combinator: TStyleCombinator);
begin
inherited Create;
FLeftHand := LeftHand;
FCombinator := Combinator;
end;
//-- BG ---------------------------------------------------------- 14.03.2011 --
destructor TCombinedSelector.Destroy;
begin
FLeftHand.Free;
inherited;
end;
//-- BG ---------------------------------------------------------- 20.03.2011 --
function TCombinedSelector.ToString: ThtString;
var
CmbStr: ThtString;
begin
case FCombinator of
scDescendant: CmbStr := ' ';
scChild: CmbStr := ' > ';
scFollower: CmbStr := ' + ';
else
CmbStr := ' ? ';
end;
Result := FLeftHand.ToString + CmbStr + inherited ToString;
end;
{ TStyleSelectorList }
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStyleSelectorList.Add(Sele: TStyleSelector);
var
Prev: TStyleSelector;
begin
assert(Sele.Next = nil, 'Don''t add chained links twice. Sele.Next is not nil.');
assert(Sele.Prev = nil, 'Don''t add chained links twice. Sele.Prev is not nil.');
Prev := Last;
// link to prev
if Prev = nil then
FFirst := Sele
else
Prev.FNext := Sele;
Sele.FPrev := Prev;
// link to next
FLast := Sele;
Sele.FNext := nil;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStyleSelectorList.Assign(const List: TStyleSelectorList);
begin
FFirst := List.FFirst;
FLast := List.FLast;
end;
//-- BG ---------------------------------------------------------- 03.04.2011 --
procedure TStyleSelectorList.Clear;
var
Link: TStyleSelector;
begin
FLast := nil;
while First <> nil do
begin
Link := First;
FFirst := Link.Next;
Link.Free;
end;
end;
{$ifdef UseEnhancedRecord}
//-- BG ---------------------------------------------------------- 16.04.2011 --
procedure TStyleSelectorList.Free;
begin
Clear;
end;
{$endif}
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStyleSelectorList.Init;
begin
FFirst := nil;
FLast := nil;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
function TStyleSelectorList.IsEmpty: Boolean;
begin
Result := First = nil;
end;
//-- BG ---------------------------------------------------------- 02.04.2011 --
procedure TStyleSelectorList.Remove(Prop: TStyleSelector);
begin
//TODO -1 -oBG, 02.04.2011
end;
//-- BG ---------------------------------------------------------- 19.03.2011 --
function TStyleSelectorList.ToString: ThtString;
var
Sele: TStyleSelector;
begin
Result := '';
Sele := First;
if Sele <> nil then
begin
Result := Sele.ToString;
Sele := Sele.Next;
while Sele <> nil do
begin
Result := Result + ', ' + Sele.ToString;
Sele := Sele.Next;
end;
end;
end;
{ TRuleset }
//-- BG ---------------------------------------------------------- 15.03.2011 --
constructor TRuleset.Create(MediaTypes: TMediaTypes);
begin
inherited Create;
FMediaTypes := MediaTypes;
{$ifdef UseEnhancedRecord}
{$else}
Selectors := TStyleSelectorList.Create;
Properties := TStylePropertyList.Create;
{$endif}
end;
//-- BG ---------------------------------------------------------- 16.04.2011 --
destructor TRuleset.Destroy;
begin
Properties.Free;
Selectors.Free;
inherited;
end;
//-- BG ---------------------------------------------------------- 19.03.2011 --
function TRuleset.ToString: ThtString;
var
Strings: ThtStringList;
Indent: ThtString;
Sele: TStyleSelector;
Prop: TStyleProperty;
begin
Strings := ThtStringList.Create;
Indent := '';
try
if FMediaTypes = [] then
Strings.Add('@media none {')
else if not ((mtAll in FMediaTypes) or (FMediaTypes = AllMediaTypes)) then
Strings.Add('@media ' + MediaTypesToStr(FMediaTypes) + ' {');
if Strings.Count > 0 then
Indent := TabChar;
if Selectors.First <> nil then
begin
Sele := Selectors.First;
while Sele.Next <> nil do
begin
Strings.Add(Indent + Sele.ToString + ',');
Sele := Sele.Next;
end;
Strings.Add(Indent + Sele.ToString + ' {');
if Properties.First <> nil then
begin
Indent := Indent + TabChar;
Prop := Properties.First;
while Prop.Next <> nil do
begin
Strings.Add(Indent + Prop.ToString + ';');
Prop := Prop.Next;
end;
Strings.Add(Indent + Prop.ToString);
SetLength(Indent, Length(Indent) - 1);
end;
Strings.Add(Indent + '}');
end;
if Indent <> '' then
Strings.Add('}');
Result := Strings.Text;
finally
Strings.Free;
end;
end;
{ TRulesetList }
//-- BG ---------------------------------------------------------- 15.03.2011 --
function TRulesetList.GetItem(Index: Integer): TRuleset;
begin
Result := Get(Index);
end;
//-- BG ---------------------------------------------------------- 17.03.2011 --
procedure TRulesetList.InsertList(Index: Integer; Rulesets: TRulesetList);
var
InsCount: Integer;
NewCount: Integer;
begin
InsCount := Rulesets.Count;
if InsCount > 0 then
begin
NewCount := Count + InsCount;
if Capacity < NewCount then
Capacity := NewCount;
if Index < Count then
System.Move(List[Index], List[Index + InsCount], (Count - Index) * SizeOf(Pointer));
// Make sure that Rulesets no longer owns the objects:
Rulesets.OwnsObjects := False;
System.Move(Rulesets.List[0], List[Index], InsCount * SizeOf(Pointer));
end;
end;
//-- BG ---------------------------------------------------------- 19.03.2011 --
function TRulesetList.ToString: ThtString;
var
Strings: TStrings;
I: Integer;
begin
Strings := TStringList.Create;
try
for I := 0 to Count - 1 do
Strings.Add(Self[I].ToString);
Result := Strings.Text;
{$ifdef DEBUG}
if Length(Result) > 0 then
Strings.SaveToFile('C:\Temp\Rulesets.css');
{$endif}
finally
Strings.Free;
end;
end;
{ TResultingProperty }
//-- BG ---------------------------------------------------------- 22.03.2011 --
function TResultingProperty.Compare(const AProperty: TStyleProperty; const ASelector: TStyleSelector): Integer;
begin
Result := Ord(FProperty.Precedence) - Ord(AProperty.Precedence);
if Result <> 0 then
exit;
Result := FSelector.CompareSpecificity(ASelector);
end;
//-- BG ---------------------------------------------------------- 30.04.2011 --
function TResultingProperty.GetBorderStyle(Parent, Default: TBorderStyle): TBorderStyle;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsOrdinal(Prop.Value) then
Result := TBorderStyle(Prop.Value)
else if VarIsStr(Prop.Value) then
if TryStrToBorderStyle(Prop.Value, Result) then
Prop.Value := Integer(Result);
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingProperty.GetColor(Parent, Default: TColor): TColor;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsOrdinal(Prop.Value) then
Result := TColor(Prop.Value)
else if VarIsStr(Prop.Value) then
if TryStrToColor(Prop.Value, False, Result) then
Prop.Value := Integer(Result);
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingProperty.GetDisplay(Parent, Default: TDisplayStyle): TDisplayStyle;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsOrdinal(Prop.Value) then
Result := TDisplayStyle(Prop.Value)
else if VarIsStr(Prop.Value) then
if TryStrToDisplayStyle(Prop.Value, Result) then
Prop.Value := Integer(Result);
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingProperty.GetFloat(Parent, Default: TBoxFloatStyle): TBoxFloatStyle;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsOrdinal(Prop.Value) then
Result := TBoxFloatStyle(Prop.Value)
else if VarIsStr(Prop.Value) then
if TryStrToBoxFloatStyle(Prop.Value, Result) then
Prop.Value := Integer(Result);
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
function TResultingProperty.GetFontName(Parent, Default: ThtString): ThtString;
function FontFamilyToFontName(Family: ThtString): ThtString;
begin
//TODO -oBG, 03.05.2011: translate font famliy to font name
Result := Family;
end;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsStr(Prop.Value) then
begin
Result := FontFamilyToFontName(Prop.Value);
Prop.Value := Result;
end;
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
function TResultingProperty.GetFontSize(DefaultFontSize, Parent, Default: Double): Double;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsNumeric(Prop.Value) then
Result := Prop.Value
else if VarIsStr(Prop.Value) then
begin
Result := StrToFontSize(Prop.Value, FontConvBase, DefaultFontSize, Parent, Default);
Prop.Value := Result;
end;
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
function TResultingProperty.GetFontWeight(Parent, Default: Integer): Integer;
// CSS 2.1:
// Parent | 100 200 300 400 500 600 700 800 900
// --------+------------------------------------
// bolder | 400 400 400 700 700 900 900 900 900
// lighter | 100 100 100 100 100 400 400 700 700
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsNumeric(Prop.Value) then
Result := Prop.Value
else if VarIsStr(Prop.Value) then
begin
if htCompareString(Prop.Value, 'normal') = 0 then
Result := 400
else if htCompareString(Prop.Value, 'bold') = 0 then
Result := 700
else if htCompareString(Prop.Value, 'bolder') = 0 then
if Parent <= 300 then
Result := 400
else if Parent < 600 then
Result := 700
else
Result := 900
else if htCompareString(Prop.Value, 'lighter') = 0 then
if Parent <= 500 then
Result := 100
else if Parent < 800 then
Result := 400
else
Result := 700
else if htCompareString(Prop.Value, 'light') = 0 then
Result := 100;
Prop.Value := Result;
end;
end;
//-- BG ---------------------------------------------------------- 30.04.2011 --
function TResultingProperty.GetLength(Parent, Base, EmBase, Default: Double): Double;
{
Return the calculated length.
if Relative is true,
}
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsNumeric(Prop.Value) then
Result := Prop.Value
else if VarIsStr(Prop.Value) then
begin
Result := StrToLength(Prop.Value, False, Parent, EmBase, Default);
Prop.Value := Result;
end;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingProperty.GetPosition(Parent, Default: TBoxPositionStyle): TBoxPositionStyle;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsOrdinal(Prop.Value) then
Result := TBoxPositionStyle(Prop.Value)
else if VarIsStr(Prop.Value) then
if TryStrToBoxPositionStyle(Prop.Value, Result) then
Prop.Value := Integer(Result);
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
function TResultingProperty.GetTextDecoration(Parent, Default: TFontStyles): TFontStyles;
var
ResultAsByte: Byte absolute Result;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsOrdinal(Prop.Value) then
ResultAsByte := Prop.Value
else if VarIsStr(Prop.Value) then
begin
if htCompareString(Prop.Value, 'underline') = 0 then
Result := [fsUnderline]
else if htCompareString(Prop.Value, 'line-through') = 0 then
Result := [fsStrikeOut]
else
Result := [];
Prop.Value := ResultAsByte;
end;
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
function TResultingProperty.GetValue(Parent, Default: Variant): Variant;
begin
if Self = nil then
Result := Default
else
begin
Result := Prop.Value;
if Result = Inherit then
Result := Parent;
end;
end;
//-- BG ---------------------------------------------------------- 14.12.2011 --
function TResultingProperty.HasValue: Boolean;
begin
Result := (Self <> nil) and (Prop.Value <> Unassigned);
end;
//-- BG ---------------------------------------------------------- 03.05.2011 --
function TResultingProperty.IsItalic(Parent, Default: Boolean): Boolean;
begin
Result := Default;
if Self <> nil then
if Prop.Value = Inherit then
Result := Parent
else if VarIsType(Prop.Value, varBoolean) then
Result := Prop.Value
else if VarIsStr(Prop.Value) then
begin
if htCompareString(Prop.Value, 'italic') = 0 then
Result := True
else if htCompareString(Prop.Value, 'oblique') = 0 then
Result := True
else
Result := False;
Prop.Value := Result;
end;
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
procedure TResultingProperty.Update(const AProperty: TStyleProperty; const ASelector: TStyleSelector);
begin
FProperty := AProperty;
FSelector := ASelector;
end;
{ TResultingPropertyMap }
destructor TResultingPropertyMap.Destroy;
var
I: TStylePropertySymbol;
begin
for I := Low(I) to High(I) do
FProps[I].Free;
inherited;
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
function TResultingPropertyMap.Get(Index: TStylePropertySymbol): TResultingProperty;
begin
Result := FProps[Index];
end;
//-- BG ---------------------------------------------------------- 03.09.2011 --
procedure TResultingPropertyMap.GetElementBoxingInfo(var Info: THtmlElementBoxingInfo);
{
Get the calculated values of the boxing properties.
On enter Info must contain the parent's properties.
On exit Info returns the calculated values of this property map.
}
begin
Info.Display := Properties[psDisplay].GetDisplay(Info.Display, pdInline);
case Info.Display of
pdNone:
begin
Info.Position := posAbsolute;
Info.Float := flNone;
end;
else
Info.Position := Properties[psPosition].GetPosition(Info.Position, posStatic);
case Info.Position of
posAbsolute,
posFixed:
begin
Info.Float := flNone;
Info.Display := ToRootDisplayStyle(Info.Display);
end;
else
Info.Float := Properties[psFloat].GetFloat(Info.Float, flNone);
case Info.Float of
flNone:;
else
Info.Display := ToRootDisplayStyle(Info.Display);
end;
end;
end;
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingPropertyMap.GetLengths(Left, Top, Right, Bottom: TPropertySymbol;
const Parent, Default: TRectIntegers; BaseSize: Integer): TRectIntegers;
var
PercentBase: Double;
begin
PercentBase := Parent[reRight] - Parent[reLeft];
Result[reLeft] := Round(Properties[Left]. GetLength(Parent[reLeft], PercentBase, BaseSize, Default[reLeft] ));
Result[reRight] := Round(Properties[Right]. GetLength(Parent[reRight], PercentBase, BaseSize, Default[reRight] ));
PercentBase := Parent[reBottom] - Parent[reTop];
Result[reTop] := Round(Properties[Top]. GetLength(Parent[reTop], PercentBase, BaseSize, Default[reTop] ));
Result[reBottom] := Round(Properties[Bottom].GetLength(Parent[reBottom], PercentBase, BaseSize, Default[reBottom]));
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingPropertyMap.GetColors(Left, Top, Right, Bottom: TPropertySymbol; const Parent, Default: TRectColors): TRectColors;
begin
Result[reLeft] := Properties[Left]. GetColor(Parent[reLeft], Default[reLeft] );
Result[reTop] := Properties[Top]. GetColor(Parent[reTop], Default[reTop] );
Result[reRight] := Properties[Right]. GetColor(Parent[reRight], Default[reRight] );
Result[reBottom] := Properties[Bottom].GetColor(Parent[reBottom], Default[reBottom]);
end;
//-- BG ---------------------------------------------------------- 01.05.2011 --
function TResultingPropertyMap.GetStyles(Left, Top, Right, Bottom: TPropertySymbol; const Parent, Default: TRectStyles): TRectStyles;
begin
Result[reLeft] := Properties[Left]. GetBorderStyle(Parent[reLeft], Default[reLeft]);
Result[reTop] := Properties[Top]. GetBorderStyle(Parent[reTop], Default[reTop]);
Result[reRight] := Properties[Right]. GetBorderStyle(Parent[reRight], Default[reRight]);
Result[reBottom] := Properties[Bottom].GetBorderStyle(Parent[reBottom], Default[reBottom]);
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
procedure TResultingPropertyMap.Update(const AProperty: TStyleProperty; const ASelector: TStyleSelector);
begin
if FProps[AProperty.Symbol] = nil then
begin
FProps[AProperty.Symbol] := TResultingProperty.Create;
FProps[AProperty.Symbol].Update(AProperty, ASelector);
end
else if FProps[AProperty.Symbol].Compare(AProperty, ASelector) < 0 then
FProps[AProperty.Symbol].Update(AProperty, ASelector);
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
procedure TResultingPropertyMap.UpdateFromProperties(const Properties: TStylePropertyList; const ASelector: TStyleSelector);
var
Prop: TStyleProperty;
begin
Prop := Properties.First;
while Prop <> nil do
begin
Update(Prop, ASelector);
Prop := Prop.Next;
end;
end;
//-- BG ---------------------------------------------------------- 22.03.2011 --
procedure TResultingPropertyMap.UpdateFromAttributes(const Properties: TStylePropertyList; IsFromStyleAttr: Boolean);
begin
if IsFromStyleAttr then
UpdateFromProperties(Properties, StyleAttributeSelector)
else
UpdateFromProperties(Properties, StyleTagSelector);
end;
initialization
StyleAttributeSelector := TStyleSelector.Create;
StyleAttributeSelector.FIsFromStyleAttr := True;
StyleTagSelector := TStyleSelector.Create;
finalization
FreeAndNil(StyleAttributeSelector);
FreeAndNil(StyleTagSelector);
end.
|
{-----------------------------------------------------------------------------
Author: Roman Fadeyev
Purpose: Специальный клас-переходник между библиотечным интерфейсом
предоставления данных для чарта (IStockDataSource) и
DataSet
History:
-----------------------------------------------------------------------------}
unit FC.StockData.DataSourceToDataSetMediator;
{$I Compiler.inc}
interface
uses BaseUtils,SysUtils, Classes, Controls, Serialization,
StockChart.Definitions,FC.Definitions, StockChart.Obj,MemoryDS,DB;
type
TStockInputDataCollectionToDataSetMediator = class (TCustomMemoryDataSet)
private
FMemoryRecord: TCustomMemoryRecord;
FDataSource: IStockDataSource;
procedure SetDataSource(const Value: IStockDataSource);
protected
function AddMemoryRecord: TCustomMemoryRecord; override;
function InsertMemoryRecord(Index: Integer): TCustomMemoryRecord; override;
function GetMemoryRecord(Index: Integer): TCustomMemoryRecord; override;
function OnMemoryRecordAdded(aRecord:TCustomMemoryRecord): integer; override;
function OnMemoryRecordRemoved(aRecord:TCustomMemoryRecord): integer; override;
procedure ChangeMemoryRecordIndex(aOld,aNew: integer); override;
procedure ClearMemoryRecords; override;
function FindMemoryRecordByID(aID: integer): integer; override;
function GetRecordCount: Integer; override;
function GetCanModify: Boolean; override;
procedure DoAfterOpen; override;
public
function GetDataDateTime: TDateTime;
function GetDataOpen: TStockRealNumber;
function GetDataHigh: TStockRealNumber;
function GetDataLow: TStockRealNumber;
function GetDataClose: TStockRealNumber;
function GetDataVolume: integer;
constructor Create(aOwner:TComponent); override;
destructor Destroy; override;
published
property DataSource: IStockDataSource read FDataSource write SetDataSource;
property BeforeOpen;
property AfterOpen;
property BeforeClose;
property AfterClose;
property BeforeInsert;
property AfterInsert;
property BeforeEdit;
property AfterEdit;
property BeforePost;
property AfterPost;
property BeforeCancel;
property AfterCancel;
property BeforeDelete;
property AfterDelete;
property BeforeScroll;
property AfterScroll;
property OnCalcFields;
property OnDeleteError;
property OnEditError;
property OnFilterRecord;
property OnNewRecord;
property OnPostError;
end;
implementation
type
TBuffer = packed record
a_0: byte;
a_Index: integer;
a_1: byte;
a_Time: TDateTimeRec;
a_2: byte;
a_Open: Double;
a_3: byte;
a_High: Double;
a_4: byte;
a_Low: Double;
a_5: byte;
a_Close: Double;
a_6: byte;
a_Volume: integer;
end;
PBuffer = ^TBuffer;
TMemoryRecordEx = class (TCustomMemoryRecord)
protected
procedure CleanupMemory; override;
procedure AllocateMemory; override;
function GetBlobData(index: integer): TMemBlobData; override;
procedure SetBlobData(index: integer; const Value: TMemBlobData); override;
public
procedure GetData(Buffer: TRecordBuffer); override;
procedure SetData(Buffer: TRecordBuffer); override;
end;
{ TStockInputDataCollectionToDataSetMediator }
constructor TStockInputDataCollectionToDataSetMediator.Create(aOwner: TComponent);
begin
inherited;
FieldDefs.Add('No', ftInteger);
FieldDefs.Add('DateTime', ftDateTime);
FieldDefs.Add('Open', ftCurrency);
FieldDefs.Add('High', ftCurrency);
FieldDefs.Add('Low', ftCurrency);
FieldDefs.Add('Close', ftCurrency);
FieldDefs.Add('Volume', ftInteger);
FMemoryRecord:=TMemoryRecordEx.Create(self);
end;
destructor TStockInputDataCollectionToDataSetMediator.Destroy;
begin
FreeAndNil(FMemoryRecord);
inherited;
end;
procedure TStockInputDataCollectionToDataSetMediator.DoAfterOpen;
begin
inherited;
FieldByName('No').DisplayWidth:=7;
// FieldByName('No').ReadOnly:=true;
(FieldByName('Open') as TNumericField).DisplayFormat:='0.0000';
FieldByName('Open').DisplayWidth:=7;
// FieldByName('Open').ReadOnly:=true;
(FieldByName('High') as TNumericField).DisplayFormat:='0.0000';
FieldByName('High').DisplayWidth:=7;
// FieldByName('High').ReadOnly:=true;
(FieldByName('Low') as TNumericField).DisplayFormat:='0.0000';
FieldByName('Low').DisplayWidth:=7;
// FieldByName('Low').ReadOnly:=true;
(FieldByName('Close') as TNumericField).DisplayFormat:='0.0000';
FieldByName('Close').DisplayWidth:=7;
// FieldByName('Close').ReadOnly:=true;
end;
function TStockInputDataCollectionToDataSetMediator.FindMemoryRecordByID(aID: integer): integer;
begin
result:=aID; //Индекс и ID должны совпадать
end;
function TStockInputDataCollectionToDataSetMediator.AddMemoryRecord: TCustomMemoryRecord;
begin
result:=FMemoryRecord;
end;
procedure TStockInputDataCollectionToDataSetMediator.ChangeMemoryRecordIndex(aOld, aNew: integer);
begin
end;
procedure TStockInputDataCollectionToDataSetMediator.ClearMemoryRecords;
begin
end;
function TStockInputDataCollectionToDataSetMediator.GetCanModify: Boolean;
begin
result:=false;
end;
function TStockInputDataCollectionToDataSetMediator.GetDataClose: TStockRealNumber;
begin
result:=FieldByName('Close').AsFloat;
end;
function TStockInputDataCollectionToDataSetMediator.GetDataDateTime: TDateTime;
begin
result:=FieldByName('DateTime').AsDateTime;
end;
function TStockInputDataCollectionToDataSetMediator.GetDataHigh: TStockRealNumber;
begin
result:=FieldByName('High').AsFloat;
end;
function TStockInputDataCollectionToDataSetMediator.GetDataLow: TStockRealNumber;
begin
result:=FieldByName('Low').AsFloat;
end;
function TStockInputDataCollectionToDataSetMediator.GetDataOpen: TStockRealNumber;
begin
result:=FieldByName('Open').AsFloat;
end;
function TStockInputDataCollectionToDataSetMediator.GetDataVolume: integer;
begin
result:=FieldByName('Volume').AsInteger;
end;
function TStockInputDataCollectionToDataSetMediator.GetMemoryRecord(Index: Integer): TCustomMemoryRecord;
begin
//Можно ли в качестве ID использовать индекс???
FMemoryRecord.ID:=index;
result:=FMemoryRecord;
end;
function TStockInputDataCollectionToDataSetMediator.GetRecordCount: Integer;
begin
if FDataSource=nil then
result:=0
else
result:=FDataSource.RecordCount;
end;
function TStockInputDataCollectionToDataSetMediator.InsertMemoryRecord(Index: Integer): TCustomMemoryRecord;
begin
result:=AddMemoryRecord;
end;
function TStockInputDataCollectionToDataSetMediator.OnMemoryRecordAdded(aRecord: TCustomMemoryRecord): integer;
begin
result:=RecordCount-1;
end;
function TStockInputDataCollectionToDataSetMediator.OnMemoryRecordRemoved(aRecord: TCustomMemoryRecord): integer;
begin
result:=RecordCount-1;
end;
procedure TStockInputDataCollectionToDataSetMediator.SetDataSource(const Value: IStockDataSource);
begin
FDataSource := Value;
Close;
if FDataSource<>nil then
begin
Open;
end;
end;
{ TMemoryRecordEx }
procedure TMemoryRecordEx.AllocateMemory;
begin
inherited;
end;
procedure TMemoryRecordEx.CleanupMemory;
begin
inherited;
end;
function TMemoryRecordEx.GetBlobData(index: integer): TMemBlobData;
begin
result:='';
end;
procedure TMemoryRecordEx.GetData(Buffer: TRecordBuffer);
var
aCollection: IStockDataSource;
begin
aCollection:=TStockInputDataCollectionToDataSetMediator(Owner).DataSource;
if aCollection<>nil then
begin
PBuffer(Buffer).a_0:=1;
PBuffer(Buffer).a_1:=1;
PBuffer(Buffer).a_2:=1;
PBuffer(Buffer).a_3:=1;
PBuffer(Buffer).a_4:=1;
PBuffer(Buffer).a_5:=1;
PBuffer(Buffer).a_6:=1;
PBuffer(Buffer).a_Index:=ID; //Индекс и ID у нас совпадают
PBuffer(Buffer).a_Time.DateTime:=TimeStampToMSecs(DateTimeToTimeStamp(aCollection.GetDataDateTime(ID)));
PBuffer(Buffer).a_Open:=aCollection.GetDataOpen(ID);
PBuffer(Buffer).a_High:=aCollection.GetDataHigh(ID);
PBuffer(Buffer).a_Low:=aCollection.GetDataLow(ID);
PBuffer(Buffer).a_Close:=aCollection.GetDataClose(ID);
PBuffer(Buffer).a_Volume:=aCollection.GetDataVolume(ID);
end
else
FillChar(Buffer^,Owner.RecordSize,0);
end;
procedure TMemoryRecordEx.SetBlobData(index: integer; const Value: TMemBlobData);
begin
end;
procedure TMemoryRecordEx.SetData(Buffer: TRecordBuffer);
//var
// aCollection: IStockDataSource;
begin
(* aCollection:=TStockInputDataCollectionToDataSetMediator(Owner).InputDataCollection;
if aCollection<>nil then
begin
if PBuffer(Buffer).a_1=1 then
if PBuffer(Buffer).a_2=1 then
aCollection.
if PBuffer(Buffer).a_3=1 then
if PBuffer(Buffer).a_4=1 then
if PBuffer(Buffer).a_5=1 then
if PBuffer(Buffer).a_6=1 then
PBuffer(Buffer).a_Time.DateTime:=TimeStampToMSecs(DateTimeToTimeStamp(aCollection.DirectGetItem_DataDateTime(Index)));
PBuffer(Buffer).a_Open:=aCollection.DirectGetItem_DataOpen(Index);
PBuffer(Buffer).a_High:=aCollection.DirectGetItem_DataHigh(Index);
PBuffer(Buffer).a_Low:=aCollection.DirectGetItem_DataLow(Index);
PBuffer(Buffer).a_Close:=aCollection.DirectGetItem_DataClose(Index);
PBuffer(Buffer).a_Volume:=aCollection.DirectGetItem_DataVolume(Index);
end
*)
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 1995-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit DBReg;
interface
uses SysUtils, Classes, DesignIntf, DesignEditors,
{$IFDEF MSWINDOWS}DSDesign{$ENDIF}{$IFDEF LINUX}DSDesignLin{$ENDIF};
type
TDBStringProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetValueList(List: TStrings); virtual;
procedure GetValues(Proc: TGetStrProc); override;
end;
TDataFieldProperty = class(TDBStringProperty)
public
function GetDataSourcePropName: string; virtual;
procedure GetValueList(List: TStrings); override;
end;
TDataFieldAggProperty = class(TDBStringProperty)
public
function GetDataSourcePropName: string; virtual;
procedure GetValueList(List: TStrings); override;
end;
TDataSetEditor = class(TComponentEditor{$IFDEF LINUX}, IDesignerThreadAffinity{$ENDIF})
protected
function GetDSDesignerClass: TDSDesignerClass; virtual;
public
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
{$IFDEF LINUX}
procedure Edit; override;
{IDesignerThreadAffinity}
function GetThreadAffinity: TThreadAffinity;
{$ENDIF}
end;
TIndexFieldNamesProperty = class(TDBStringProperty)
public
procedure GetValueList(List: TStrings); override;
end;
TIndexNameProperty = class(TDBStringProperty)
public
procedure GetValueList(List: TStrings); override;
end;
{ TListFieldProperty }
type
TListFieldProperty = class(TDataFieldProperty)
public
function GetDataSourcePropName: string; override;
end;
procedure Register;
implementation
uses
Windows, Controls, Forms, Mask, TypInfo, DsnDBCst, DB,
ColnEdit, ActnList, DBActRes, {$IFDEF MSWINDOWS}DBColnEd;{$ENDIF}
{$IFDEF LINUX}ClxDBColnEd, TConnect;{$ENDIF}
{ TDataSetEditor }
function TDataSetEditor.GetDSDesignerClass: TDSDesignerClass;
begin
Result := TDSDesigner;
end;
procedure TDataSetEditor.ExecuteVerb(Index: Integer);
begin
if Index = 0 then
ShowFieldsEditor(Designer, TDataSet(Component), GetDSDesignerClass);
end;
function TDataSetEditor.GetVerb(Index: Integer): string;
begin
Result := SDatasetDesigner;
end;
function TDataSetEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{$IFDEF LINUX}
function TDataSetEditor.GetThreadAffinity: TThreadAffinity;
begin
Result := taQT;
end;
procedure TDataSetEditor.Edit;
begin
ShowFieldsEditor(Designer, TDataSet(Component), GetDSDesignerClass);
end;
{$ENDIF}
{ TDataSetProperty }
type
TDataSetProperty = class(TComponentProperty)
private
FCheckProc: TGetStrProc;
procedure CheckComponent(const Value: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure TDataSetProperty.CheckComponent(const Value: string);
var
J: Integer;
Dataset: TDataset;
begin
Dataset := TDataset(Designer.GetComponent(Value));
for J := 0 to PropCount - 1 do
if TDataSource(GetComponent(J)).IsLinkedTo(Dataset) then
Exit;
FCheckProc(Value);
end;
procedure TDataSetProperty.GetValues(Proc: TGetStrProc);
begin
FCheckProc := Proc;
inherited GetValues(CheckComponent);
end;
{ TDataSourceProperty }
type
TDataSourceProperty = class(TComponentProperty)
private
FCheckProc: TGetStrProc;
procedure CheckComponent(const Value: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure TDataSourceProperty.CheckComponent(const Value: string);
var
J: Integer;
DataSource: TDataSource;
begin
DataSource := TDataSource(Designer.GetComponent(Value));
for J := 0 to PropCount - 1 do
if TDataSet(GetComponent(J)).IsLinkedTo(DataSource) then
Exit;
FCheckProc(Value);
end;
procedure TDataSourceProperty.GetValues(Proc: TGetStrProc);
begin
FCheckProc := Proc;
inherited GetValues(CheckComponent);
end;
{ TNestedDataSetProperty }
type
TNestedDataSetProperty = class(TComponentProperty)
private
FCheckProc: TGetStrProc;
procedure CheckComponent(const Value: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure TNestedDataSetProperty.CheckComponent(const Value: string);
var
DataSet: TDataset;
begin
DataSet := (GetComponent(0) as TDataSetField).DataSet;
if TDataset(Designer.GetComponent(Value)) <> DataSet then
FCheckProc(Value);
end;
procedure TNestedDataSetProperty.GetValues(Proc: TGetStrProc);
begin
FCheckProc := Proc;
inherited GetValues(CheckComponent);
end;
{ TDBStringProperty }
function TDBStringProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paValueList, paSortList, paMultiSelect];
end;
procedure TDBStringProperty.GetValueList(List: TStrings);
begin
end;
procedure TDBStringProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
Values: TStringList;
begin
Values := TStringList.Create;
try
GetValueList(Values);
for I := 0 to Values.Count - 1 do Proc(Values[I]);
finally
Values.Free;
end;
end;
function GetIndexDefs(Component: TPersistent): TIndexDefs;
var
DataSet: TDataSet;
begin
DataSet := Component as TDataSet;
Result := GetObjectProp(DataSet, 'IndexDefs') as TIndexDefs;
if Assigned(Result) then
begin
Result.Updated := False;
Result.Update;
end;
end;
{ TIndexNameProperty }
procedure TIndexNameProperty.GetValueList(List: TStrings);
begin
GetIndexDefs(GetComponent(0)).GetItemNames(List);
end;
{ TIndexFieldNamesProperty }
procedure TIndexFieldNamesProperty.GetValueList(List: TStrings);
var
I: Integer;
IndexDefs: TIndexDefs;
begin
IndexDefs := GetIndexDefs(GetComponent(0));
for I := 0 to IndexDefs.Count - 1 do
with IndexDefs[I] do
if (Options * [ixExpression, ixDescending] = []) and (Fields <> '') then
List.Add(Fields);
end;
{ TDataFieldProperty }
function TDataFieldProperty.GetDataSourcePropName: string;
begin
Result := 'DataSource';
end;
procedure TDataFieldProperty.GetValueList(List: TStrings);
var
DataSource: TDataSource;
begin
DataSource := GetObjectProp(GetComponent(0), GetDataSourcePropName) as TDataSource;
if (DataSource <> nil) and (DataSource.DataSet <> nil) then
DataSource.DataSet.GetFieldNames(List);
end;
{ TDataFieldAggProperty }
function TDataFieldAggProperty.GetDataSourcePropName: string;
begin
Result := 'DataSource';
end;
procedure TDataFieldAggProperty.GetValueList(List: TStrings);
var
DataSource: TDataSource;
AggList: TStringList;
begin
DataSource := GetObjectProp(GetComponent(0), GetDataSourcePropName) as TDataSource;
if (DataSource <> nil) and (DataSource.DataSet <> nil) then
begin
DataSource.DataSet.GetFieldNames(List);
if DataSource.DataSet.AggFields.Count > 0 then
begin
AggList := TStringList.Create;
try
DataSource.DataSet.AggFields.GetFieldNames(AggList);
List.AddStrings(AggList);
finally
AggList.Free;
end;
end;
end;
end;
{ TLookupSourceProperty }
type
TLookupSourceProperty = class(TDBStringProperty)
public
procedure GetValueList(List: TStrings); override;
end;
procedure TLookupSourceProperty.GetValueList(List: TStrings);
begin
with GetComponent(0) as TField do
if DataSet <> nil then DataSet.GetFieldNames(List);
end;
{ TLookupDestProperty }
type
TLookupDestProperty = class(TDBStringProperty)
public
procedure GetValueList(List: TStrings); override;
end;
procedure TLookupDestProperty.GetValueList(List: TStrings);
begin
with GetComponent(0) as TField do
if LookupDataSet <> nil then LookupDataSet.GetFieldNames(List);
end;
function TListFieldProperty.GetDataSourcePropName: string;
begin
Result := 'ListSource';
end;
{ TLookupFieldProperty }
type
TLookupFieldProperty = class(TDataFieldProperty)
public
function GetDataSourcePropName: string; override;
end;
function TLookupFieldProperty.GetDataSourcePropName: string;
begin
Result := 'LookupSource';
end;
{ TLookupIndexProperty }
type
TLookupIndexProperty = class(TLookupFieldProperty)
public
procedure GetValueList(List: TStrings); override;
end;
procedure TLookupIndexProperty.GetValueList(List: TStrings);
var
DataSource: TDataSource;
begin
DataSource := GetObjectProp(GetComponent(0), GetDataSourcePropName) as TDataSource;
if (DataSource <> nil) and (DataSource.DataSet <> nil) then
DataSource.DataSet.GetFieldNames(List);
end;
{ Registration }
procedure Register;
begin
{ Database Components are excluded from the STD SKU }
if GDAL <> LongWord(-16) then
begin
RegisterComponents(srDAccess, [TDataSource]);
{$IFDEF LINUX}
RegisterComponents(srDAccess, [TLocalConnection]);
{$ENDIF}
RegisterNoIcon([TField]);
RegisterFields([TStringField, TIntegerField, TSmallintField, TWordField,
TFloatField, TCurrencyField, TBCDField, TFMTBcdField, TBooleanField, TDateField,
TVarBytesField, TBytesField, TTimeField, TDateTimeField, TSQLTimeStampField,
TBlobField, TMemoField, TGraphicField, TAutoIncField, TLargeIntField,
TADTField, TArrayField, TDataSetField, TReferenceField, TAggregateField,
TWideStringField, TVariantField, TGuidField, TInterfaceField, TIDispatchField]);
RegisterPropertyEditor(TypeInfo(TDataSet), TDataSource, 'DataSet', TDataSetProperty);
RegisterPropertyEditor(TypeInfo(TDataSet), TDataSetField, 'NestedDataSet', TNestedDataSetProperty);
RegisterPropertyEditor(TypeInfo(TDataSource), TDataSet, 'MasterSource', TDataSourceProperty);
RegisterPropertyEditor(TypeInfo(TDataSource), TDataSet, 'DataSource', TDataSourceProperty);
RegisterPropertyEditor(TypeInfo(string), TField, 'KeyFields', TLookupSourceProperty);
RegisterPropertyEditor(TypeInfo(string), TField, 'LookupKeyFields', TLookupDestProperty);
RegisterPropertyEditor(TypeInfo(string), TField, 'LookupResultField', TLookupDestProperty);
RegisterPropertyEditor(TypeInfo(string), TComponent, 'DataField', TDataFieldProperty);
RegisterPropertyEditor(TypeInfo(string), TWinControl, 'LookupField', TLookupIndexProperty);
RegisterPropertyEditor(TypeInfo(string), TWinControl, 'LookupDisplay', TLookupFieldProperty);
RegisterComponentEditor(TDataset, TDataSetEditor);
{ Property Category registration }
RegisterPropertiesInCategory(sDatabaseCategoryName, TDataSet,
['*Field', '*Fields', 'Index*', 'Lookup*', '*Defs', 'ObjectView', 'Table*',
'Param*', 'Cache*', 'Lock*', 'Cursor*']);
RegisterPropertiesInCategory(sDatabaseCategoryName, TField,
['*Field', '*Fields']);
RegisterPropertyInCategory(sDatabaseCategoryName, TComponent, 'DataField');
end;
end;
end.
|
unit BD.Handler;
interface
uses System.Classes, System.Generics.Defaults, Generics.Collections, OXmlPDOM, Data.DB,
Spring.Collections, System.TypInfo;
type
TMapList = TDictionary<String, String>;
THandler = class(TObject)
class procedure SetDatabaseFields(AObject: TObject; ADataSet: TDataSet;
const Mapping: TMapList); static;
class procedure MergeIntoDatabase(AObject: TObject; ADataSet: TDataSet;
const Mapping: TMapList; KeyField: String); static;
class function LoadFromXML<T: class, constructor>(ANode: PXMLNode; const Mapping: TMapList): T;
end;
implementation
{ THandler }
class procedure THandler.SetDatabaseFields(AObject: TObject; ADataSet: TDataSet;
const Mapping: TMapList);
var
Key, SubKey: String;
Obj: TObject;
Found: Boolean;
begin
// Notasjon for å støtte sub-objecter
for Key in Mapping.Keys do begin
if Pos('.', Mapping.Items[Key]) = 0 then
ADataSet.FieldByName(Key).AsVariant :=
GetPropValue(AObject, Mapping.Items[Key])
else begin
// Drilldown to sub-object
SubKey := Mapping.Items[Key];
Obj := AObject;
Found := True;
while (Pos('.', SubKey) > 0) and (Found) do begin
Obj := GetObjectProp(Obj, Copy(SubKey, 1, Pos('.', SubKey) - 1));
Delete(SubKey, 1, Pos('.', SubKey));
Found := (Obj <> nil);
end;
if Found then
ADataSet.FieldByName(Key).AsVariant := GetPropValue(Obj, SubKey);
end;
end;
end;
class function THandler.LoadFromXML<T>(ANode: PXMLNode;
const Mapping: TMapList): T;
var
Obj: T;
TmpNode: PXMLNode;
Sub, Key: String;
begin
Result := nil;
Obj := T.Create;
// Notasjon for å støtte attributter
for Key in Mapping.Keys do
if Pos('.', Mapping.Items[Key]) = 0 then begin
if ANode.SelectNode(Mapping.Items[Key], TmpNode) then
SetPropValue(Obj, Key, TmpNode.Text);
end
else begin
Sub := Mapping.Items[Key];
if ANode.SelectNode(Copy(Sub, 1, Pos('.', Sub) -1), TmpNode) then begin
Delete(Sub, 1, Pos('.', Sub));
SetPropValue(Obj, Key, TmpNode.Attributes[Sub]);
end;
end;
Result := Obj;
end;
class procedure THandler.MergeIntoDatabase(AObject: TObject; ADataSet: TDataSet;
const Mapping: TMapList; KeyField: String);
begin
if ADataSet.Locate(KeyField, GetPropValue(AObject, Mapping.Items[KeyField]),
[]) then
ADataSet.Edit
else
ADataSet.Insert;
SetDatabaseFields(AObject, ADataSet, Mapping);
ADataSet.Post;
end;
end.
|
PROGRAM WishListAnalyzer;
USES WishListUnit;
var wl: WishList;
PROCEDURE AddPresentToList(s: string);
var childName, present: string;
BEGIN (* AddPresentToList *)
childName := s;
Delete(childName, Pos(':', childName), Length(s) - Pos(':', childName) + 1);
present := s;
Delete(present, 1, Pos(' ', present));
AddPresent(wl, childName, present);
END; (* AddPresentToList *)
var s: string;
BEGIN (* WishListAnalyzer *)
NewWishList(wl);
Write('Please enter "<Child>: <Present>": ');
ReadLn(s);
while s <> '' do begin
AddPresentToList(s);
Write('Please enter "<Child>: <Present>": ');
ReadLn(s);
end; (* WHILE *)
WriteWishList(wl);
END. (* WishListAnalyzer *) |
unit NumPlanPreviewFrame;
interface
uses
Types, Windows, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, NxColumns, NxColumnClasses, NxScrollControl,
NxCustomGridControl, NxCustomGrid, NxGrid, ComCtrls, StdCtrls, ItemsDef,
Contnrs, Core, ActnList, ToolWin, DateUtils, Math;
type
TfrmNumPlanPreview = class(TFrame)
pan2: TPanel;
pbPreview: TPaintBox;
tlbNumPlanPreview: TToolBar;
actlstNumPlanPreview: TActionList;
actModeNames: TAction;
actModeValues: TAction;
actModeActions: TAction;
actPageFirst: TAction;
actPagePrev: TAction;
actPageNext: TAction;
actPageLast: TAction;
actEditPageTpl: TAction;
actEditTicketTpl: TAction;
actZoomFit: TAction;
actZoomPlus: TAction;
actZoomMinus: TAction;
actClose: TAction;
actDummy: TAction;
btnModeValues: TToolButton;
btnModeNames: TToolButton;
btnModeActions: TToolButton;
btn1: TToolButton;
btnEditPageTpl: TToolButton;
btnEditTicketTpl: TToolButton;
btn2: TToolButton;
btnPageFirst: TToolButton;
btnPagePrev: TToolButton;
btnPageNext: TToolButton;
btnPageLast: TToolButton;
btn3: TToolButton;
btnZoomFit: TToolButton;
btnZoomPlus: TToolButton;
btnZoomMinus: TToolButton;
btn4: TToolButton;
btnClose: TToolButton;
pan1: TPanel;
ngPagesList: TNextGrid;
spl1: TSplitter;
ntcOrder: TNxNumberColumn;
ncbNumPageTpl: TNxListColumn;
actHelp: TAction;
btnHelp: TToolButton;
procedure rgViewModeClick(Sender: TObject);
procedure imgPreviewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pan2Resize(Sender: TObject);
procedure actDummyExecute(Sender: TObject);
procedure actlstNumPlanPreviewExecute(Action: TBasicAction;
var Handled: Boolean);
procedure ngPagesListSelectCell(Sender: TObject; ACol, ARow: Integer);
private
{ Private declarations }
ViewMode: AnsiChar;
CurNumPlanItem: TNumPlanItem;
NumPage: TNumPage;
NumPageTpl: TNumPageTpl;
NpiList: TObjectList;
PreviewParams: TPreviewParams;
slPageTpl: TStringList;
LockPagesList: Boolean;
Scale: Real;
function GetCurItems(): boolean;
procedure SetPreviewParams();
procedure FillPagesList();
procedure UpdatePreview();
procedure ActivatePageByOrder(AOrder: Integer);
function GetItemAtXY(X, Y: Integer): TNumPlanItem;
public
{ Public declarations }
NumProject: TNumProject;
PageID: Integer;
Form: TForm;
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function Start(): boolean;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Refresh();
procedure ChangeLanguage();
end;
var
PlanPrevCreated: Boolean = False;
sColNumPageTpl: string = 'Макет листа';
sColOrder: string = '№';
const
ciPosOrder = 0;
ciPosNumPageTpl = 1;
implementation
uses MainForm;
{$R *.dfm}
constructor TfrmNumPlanPreview.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
NpiList:=TObjectList.Create(false);
slPageTpl:=TStringList.Create();
LockPagesList:=False;
Scale:=1;
pan2.DoubleBuffered:=True;
//
PlanPrevCreated:= True;
ChangeLanguage();
end;
destructor TfrmNumPlanPreview.Destroy();
begin
FreeAndNil(slPageTpl);
FreeAndNil(NpiList);
PlanPrevCreated:= False;
inherited Destroy();
end;
procedure TfrmNumPlanPreview.ChangeLanguage();
var
Part: string;
begin
if not Assigned(LangFile) then Exit;
if PlanPrevCreated then
begin
Part:= 'NumPlanPreview';
Self.btnClose.Caption:= LangFile.ReadString(Part, 'sbtnClose', Self.btnClose.Caption);
Self.btnClose.Hint:= LangFile.ReadString(Part, 'hbtnClose', Self.btnClose.Hint);
Self.btnEditPageTpl.Caption:= LangFile.ReadString(Part, 'sbtnEditPageTpl', Self.btnEditPageTpl.Caption);
Self.btnEditPageTpl.Hint:= LangFile.ReadString(Part, 'hbtnEditPageTpl', Self.btnEditPageTpl.Hint);
Self.btnEditTicketTpl.Caption:= LangFile.ReadString(Part, 'sbtnEditTicketTpl', Self.btnEditTicketTpl.Caption);
Self.btnEditTicketTpl.Hint:= LangFile.ReadString(Part, 'hbtnEditTicketTpl', Self.btnEditTicketTpl.Hint);
Self.btnModeActions.Caption:= LangFile.ReadString(Part, 'sbtnModeActions', Self.btnModeActions.Caption);
Self.btnModeActions.Hint:= LangFile.ReadString(Part, 'hbtnModeActions', Self.btnModeActions.Hint);
Self.btnModeNames.Caption:= LangFile.ReadString(Part, 'sbtnModeNames', Self.btnModeNames.Caption);
Self.btnModeNames.Hint:= LangFile.ReadString(Part, 'hbtnModeNames', Self.btnModeNames.Hint);
Self.btnModeValues.Caption:= LangFile.ReadString(Part, 'sbtnModeValues', Self.btnModeValues.Caption);
Self.btnModeValues.Hint:= LangFile.ReadString(Part, 'hbtnModeValues', Self.btnModeValues.Hint);
Self.btnPageFirst.Caption:= LangFile.ReadString(Part, 'sbtnPageFirst', Self.btnPageFirst.Caption);
Self.btnPageFirst.Hint:= LangFile.ReadString(Part, 'hbtnPageFirst', Self.btnPageFirst.Hint);
Self.btnPageLast.Caption:= LangFile.ReadString(Part, 'sbtnPageLast', Self.btnPageLast.Caption);
Self.btnPageLast.Hint:= LangFile.ReadString(Part, 'hbtnPageLast', Self.btnPageLast.Hint);
Self.btnPageNext.Caption:= LangFile.ReadString(Part, 'sbtnPageNext', Self.btnPageNext.Caption);
Self.btnPageNext.Hint:= LangFile.ReadString(Part, 'hbtnPageNext', Self.btnPageNext.Hint);
Self.btnPagePrev.Caption:= LangFile.ReadString(Part, 'sbtnPagePrev', Self.btnPagePrev.Caption);
Self.btnPagePrev.Hint:= LangFile.ReadString(Part, 'hbtnPagePrev', Self.btnPagePrev.Hint);
Self.btnZoomFit.Caption:= LangFile.ReadString(Part, 'sbtnZoomFit', Self.btnZoomFit.Caption);
Self.btnZoomFit.Hint:= LangFile.ReadString(Part, 'hbtnZoomFit', Self.btnZoomFit.Hint);
Self.btnZoomMinus.Caption:= LangFile.ReadString(Part, 'sbtnZoomMinus', Self.btnZoomMinus.Caption);
Self.btnZoomMinus.Hint:= LangFile.ReadString(Part, 'hbtnZoomMinus', Self.btnZoomMinus.Hint);
Self.btnZoomPlus.Caption:= LangFile.ReadString(Part, 'sbtnZoomPlus', Self.btnZoomPlus.Caption);
Self.btnZoomPlus.Hint:= LangFile.ReadString(Part, 'hbtnZoomPlus', Self.btnZoomPlus.Hint);
Self.btnHelp.Caption:= LangFile.ReadString(Part, 'sbtnHelp', Self.btnHelp.Caption);
Self.btnHelp.Hint:= LangFile.ReadString(Part, 'hbtnHelp', Self.btnHelp.Hint);
end;
end;
function TfrmNumPlanPreview.GetCurItems(): boolean;
var
i, n: Integer;
TmpNumPage: TNumPage;
begin
Result:=False;
if not Assigned(NumProject) then Exit;
CurNumPlanItem:=NumProject.CurNumPlanItem;
try
if not Assigned(CurNumPlanItem) then Exit;
//CurNumPlanItem.Read(true);
if not Assigned(CurNumPlanItem.NumPage) then Exit;
if not Assigned(CurNumPlanItem.Ticket) then Exit;
if not Assigned(CurNumPlanItem.Ticket.NumPageTpl) then Exit;
NumPage:=CurNumPlanItem.NumPage;
NumPageTpl:=CurNumPlanItem.Ticket.NumPageTpl;
except
//Core.ShowWarning('Ошибка в элементе '+IntToStr(CurNumPlanItem.ID),'!');
DebugMsg('Error in CurNumPlanItem, ID='+IntToStr(CurNumPlanItem.ID), 'NUMPLAN');
Exit;
end;
// Change page from pages list
for i:=0 to ngPagesList.RowCount-1 do
begin
if ngPagesList.Cell[ciPosOrder, i].ObjectReference = NumPage then
begin
//if ngPagesList.SelectedRow <> i then
if not ngPagesList.Selected[i] then
begin
LockPagesList:=True;
//Core.AddCmd('STATUS i='+IntToStr(i)+' selected_row='+IntToStr(ngPagesList.SelectedRow)+' addr1='+IntToStr(Integer(NumPage))+' addr2='+IntToStr(Integer(TmpNumPage))+' npi='+IntToStr(CurNumPlanItem.ID));
//ngPagesList.SelectCell(ciPosOrder, i);
//Core.AddCmd('STATUS row='+IntToStr(i)+' selected_row='+IntToStr(ngPagesList.SelectedRow)+' addr1='+IntToStr(Integer(NumPage))+' addr2='+IntToStr(Integer(ngPagesList.Cell[ciPosOrder, i].ObjectReference)));
ngPagesList.SelectedRow:=i;
ngPagesList.ScrollToRow(i);
LockPagesList:=False;
Break;
end;
end;
end;
// Get NumPlanItems for current NumPage
NpiList.Clear();
n:=NumProject.NumPlanItems.Count-1;
for i:=0 to n do
begin
if NumProject.NumPlanItems[i].NumPage = NumPage then
begin
NpiList.Add(NumProject.NumPlanItems[i]);
end;
end;
Result:=True;
end;
procedure TfrmNumPlanPreview.SetPreviewParams();
var
//Canvas: TCanvas;
kx, ky: Real;
PreviewSize: TSize;
begin
// imgPreview.Picture.Bitmap.Height:=imgPreview.Height;
// imgPreview.Picture.Bitmap.Width:=imgPreview.Width;
// Canvas:=imgPreview.Canvas;
// Canvas:=pbPreview.Canvas;
// Compute preview size in pixels
with PreviewParams do
begin
SizeMm.cx:=NumPageTpl.Size.X;
SizeMm.cy:=NumPageTpl.Size.Y;
//CanvasSize.cx:=Canvas.ClipRect.Right-Canvas.ClipRect.Left;
//CanvasSize.cy:=Canvas.ClipRect.Bottom-Canvas.ClipRect.Top;
CanvasSize.cx:=pbPreview.Width;
CanvasSize.cy:=pbPreview.Height;
PreviewSize.cx:=CanvasSize.cx-8;
PreviewSize.cy:=CanvasSize.cy-8;
kx:=0; if SizeMm.cx<>0 then kx:=PreviewSize.cx/SizeMm.cx;
ky:=0; if SizeMm.cy<>0 then ky:=PreviewSize.cy/SizeMm.cy;
if kx<ky then
begin
k:=kx*Scale;
PreviewSize.cy:=Round(SizeMm.cy*k);
end
else
begin
k:=ky*Scale;
PreviewSize.cx:=Round(SizeMm.cx*k);
end;
BordersRect.Left:=(CanvasSize.cx-PreviewSize.cx) div 2;
BordersRect.Top:=(CanvasSize.cy-PreviewSize.cy) div 2;
BordersRect.Right:=BordersRect.Left+PreviewSize.cx;
BordersRect.Bottom:=BordersRect.Top+PreviewSize.cy;
end;
end;
procedure TfrmNumPlanPreview.UpdatePreview();
var
r: TRect;
x,y,sx,sy, i, ic, n, nc, m: Integer;
Ticket: TTicket;
NumLabel: TNumLabel;
NumLabelData: TNumLabelData;
TicketTpl: TTicketTpl;
Canvas: TCanvas;
s: string;
TempNpi, Npi2: TNumPlanItem;
LogFont: TLogFont;
bmp: TBitmap;
begin
if not GetCurItems() then Exit;
SetPreviewParams();
bmp:=TBitmap.Create();
bmp.Width:=pbPreview.Width;
bmp.Height:=pbPreview.Height;
//Canvas:=imgPreview.Canvas;
//Canvas:=pbPreview.Canvas;
Canvas:=bmp.Canvas;
Canvas.Lock();
// Clear canvas
Canvas.Brush.Color:=clWhite;
Canvas.FillRect(Canvas.ClipRect);
with PreviewParams do
begin
Canvas.Pen.Color:=clBlack;
Canvas.Pen.Width:=1;
Canvas.Brush.Style:=bsSolid;
//Canvas.Brush.Color:=clInfoBk; //clYellow;
//Canvas.FillRect(tr);
Canvas.Rectangle(PreviewParams.BordersRect);
// Draw tickets
ic:=NumPageTpl.Tickets.Count-1;
for i:=0 to ic do
begin
Ticket:=NumPageTpl.Tickets[i];
TicketTpl:=Ticket.Tpl;
if not Assigned(TicketTpl) then Continue;
TempNpi:=nil;
for m:=0 to NpiList.Count-1 do
begin
TempNpi:=TNumPlanItem(NpiList[m]);
if TempNpi.Ticket.ID=Ticket.ID then Break;
end;
if not Assigned (TempNpi) then Continue;
x:=BordersRect.Left+Round(Ticket.Position.X*k);
y:=BordersRect.Top+Round(Ticket.Position.Y*k);
sx:=Round(TicketTpl.Size.X*k);
sy:=Round(TicketTpl.Size.Y*k);
r:=Bounds(x, y, sx, sy);
Canvas.Pen.Color:=clBlack;
Canvas.Pen.Width:=1;
if CurNumPlanItem.Ticket.ID = Ticket.ID then
begin
Canvas.Pen.Width:=3;
end;
Canvas.Brush.Color:=clInfoBk; //clYellow;
Canvas.Brush.Style:=bsSolid;
//Canvas.FillRect(r);
Canvas.Rectangle(r);
// Draw numlabels
Canvas.Brush.Style:=bsClear;
nc:=TicketTpl.NumLabels.Count-1;
for n:=0 to nc do
begin
NumLabel:=TicketTpl.NumLabels[n];
if not Assigned(NumLabel.Font) then Continue;
x:=r.Left+Round(NumLabel.Position.X*k);
y:=r.Top+Round(NumLabel.Position.Y*k);
s:='';
if ViewMode = 'n' then s:=NumLabel.Name
else
begin
NumLabelData:=nil;
for m:=0 to TempNpi.NumLabelDataList.Count-1 do
begin
NumLabelData:=TempNpi.NumLabelDataList[m];
if NumLabelData.NumLabelTpl.ID = NumLabel.NumLabelTpl.ID then Break;
end;
if Assigned(NumLabelData) then
begin
if ViewMode = 'v' then s:=NumLabelData.Value;
if ViewMode = 'a' then s:=NumLabelData.Action;
end;
end;
Canvas.Pen.Color:=clBlack;
Canvas.Font.Assign(NumLabel.Font);
// Пересчет размера шрифта
Canvas.Font.Height:=-Round(NumLabel.Size * k);
GetObject(Canvas.Font.Handle, SizeOf(TLogFont), @LogFont);
{ Вывести текст 1/10 градуса против часовой стрелки }
LogFont.lfEscapement := NumLabel.Angle*10;
Canvas.Font.Handle := CreateFontIndirect(LogFont);
Canvas.TextOut(x, y, s);
end;
end;
// Draw arrows
for m:=0 to NpiList.Count-1 do
begin
TempNpi:=TNumPlanItem(NpiList[m]);
if not Assigned(TempNpi.Ticket) then Continue;
if not Assigned(TempNpi.Ticket.Tpl) then Continue;
for n:=0 to NpiList.Count-1 do
begin
if NpiList[n]=TempNpi then Continue;
Npi2:=(NpiList[n] as TNumPlanItem);
if not Assigned(Npi2.Ticket) then Continue;
if not Assigned(Npi2.Ticket.Tpl) then Continue;
if Npi2.Order = TempNpi.Order+1 then
begin
x:=BordersRect.Left+Round((TempNpi.Ticket.Position.X+(TempNpi.Ticket.Tpl.Size.X/2))*k);
y:=BordersRect.Top+Round((TempNpi.Ticket.Position.Y+(TempNpi.Ticket.Tpl.Size.Y/2))*k);
sx:=BordersRect.Left+Round((Npi2.Ticket.Position.X+(Npi2.Ticket.Tpl.Size.X/2))*k);
sy:=BordersRect.Top+Round((Npi2.Ticket.Position.Y+(Npi2.Ticket.Tpl.Size.Y/2))*k);
DrawArrowLine(Canvas, Point(x, y), Point(sx, sy), k);
end;
end;
end;
end;
Canvas.Unlock();
BitBlt(pbPreview.Canvas.Handle, 0, 0, bmp.Width, bmp.Height, bmp.Canvas.Handle, 0, 0, SRCCOPY );
FreeAndNil(bmp);
end;
function TfrmNumPlanPreview.Start(): boolean;
begin
Result:=False;
if not Assigned(NumProject) then Exit;
// Set view mode
ViewMode:='v';
// Fill pages list
FillPagesList();
// Update preview
UpdatePreview();
Result:=True;
end;
procedure TfrmNumPlanPreview.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if Assigned(Form) then Form.Release();
end;
procedure TfrmNumPlanPreview.pan2Resize(Sender: TObject);
begin
UpdatePreview();
end;
procedure TfrmNumPlanPreview.rgViewModeClick(Sender: TObject);
begin
UpdatePreview();
end;
procedure TfrmNumPlanPreview.Refresh();
begin
UpdatePreview();
end;
function TfrmNumPlanPreview.GetItemAtXY(X, Y: Integer): TNumPlanItem;
var
i, nx, ny, sx, sy: integer;
LocPoint: TPoint;
r: TRect;
NpiTicket: TTicket;
begin
Result:=nil;
with PreviewParams do
begin
if k = 0 then Exit;
LocPoint.X:=X;
LocPoint.Y:=Y;
for i:=0 to NpiList.Count-1 do
begin
NpiTicket:=(NpiList[i] as TNumPlanItem).Ticket;
nx:=Round(BordersRect.Left + (NpiTicket.Position.X * k));
ny:=Round(BordersRect.Top + (NpiTicket.Position.Y * k));
sx:=Round(NpiTicket.Tpl.Size.X * k);
sy:=Round(NpiTicket.Tpl.Size.Y * k);
r:=Bounds(nx, ny, sx, sy);
if PtInRect(r, LocPoint) then
begin
Result:=(NpiList[i] as TNumPlanItem);
Break;
end;
end;
end;
end;
procedure TfrmNumPlanPreview.imgPreviewMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
Npi: TNumPlanItem;
begin
Npi:=GetItemAtXY(X, Y);
if not Assigned(Npi) then Exit;
if Npi = CurNumPlanItem then Exit;
Core.AddCmd('NUMPLAN_ITEM_SEL '+IntToStr(npi.ID));
end;
procedure TfrmNumPlanPreview.actDummyExecute(Sender: TObject);
begin
//
end;
procedure TfrmNumPlanPreview.actlstNumPlanPreviewExecute(
Action: TBasicAction; var Handled: Boolean);
begin
if Action = actClose then
begin
if (Parent is TSomePage) then
begin
Core.AddCmd('CLOSE '+IntToStr((Parent as TSomePage).PageID));
end;
Exit;
end
else if Action = actModeNames then
begin
ViewMode:='n';
end
else if Action = actModeValues then
begin
ViewMode:='v';
end
else if Action = actHelp then
begin
Application.HelpCommand(HELP_CONTEXT, 12);
end
else if Action = actModeActions then
begin
ViewMode:='a';
end
else if Action = actPageFirst then
begin
ActivatePageByOrder(1);
end
else if Action = actPagePrev then
begin
ActivatePageByOrder(NumPage.Order-1);
end
else if Action = actPageNext then
begin
ActivatePageByOrder(NumPage.Order+1);
end
else if Action = actPageLast then
begin
ActivatePageByOrder(MaxInt);
end
else if Action = actEditPageTpl then
begin
if not Assigned(CurNumPlanItem) then Exit;
Core.ShowNumPageTplEdit(CurNumPlanItem.NumPage.NumPageTpl);
end
else if Action = actEditTicketTpl then
begin
if not Assigned(CurNumPlanItem) then Exit;
Core.ShowTicketTplEdit(CurNumPlanItem.Ticket.Tpl);
end
else if Action = actZoomFit then
begin
Scale:=1;
end
else if Action = actZoomPlus then
begin
Scale:=Scale+0.2;
end
else if Action = actZoomMinus then
begin
Scale:=Scale-0.2;
end
else if Action = actClose then
begin
end;
UpdatePreview();
end;
// === Pages list ===
procedure TfrmNumPlanPreview.FillPagesList();
var
i, n: Integer;
TmpPage: TNumPage;
TmpPageTpl: TNumPageTpl;
begin
if not Assigned(NumProject) then Exit;
{#IFDEF DEBUG}
DebugMsg('Preprocessing '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'NumPlanPreview');
{#ENDIF}
// PageTpl combo box items
slPageTpl.Clear();
for i:=0 to NumProject.PagesTpl.Count-1 do
begin
TmpPageTpl:=NumProject.PagesTpl[i];
slPageTpl.AddObject(TmpPageTpl.Name, TmpPageTpl);
end;
ngPagesList.BeginUpdate();
ngPagesList.ClearRows();
// NumPageTpl column settings
ngPagesList.Columns.Item[ciPosNumPageTpl].Header.Caption:=sColNumPageTpl;
ngPagesList.Columns.Item[ciPosNumPageTpl].Options:=ngPagesList.Columns.Item[ciPosNumPageTpl].Options+[coEditing];
ngPagesList.Columns.Item[ciPosNumPageTpl].Options:=ngPagesList.Columns.Item[ciPosNumPageTpl].Options-[coCanSort];
(ngPagesList.Columns.Item[ciPosNumPageTpl] as TNxListColumn).Items:=slPageTpl;
n:=NumProject.Pages.Count;
ngPagesList.AddRow(n);
NumProject.Pages.SortByOrder();
for i:=0 to n-1 do
begin
TmpPage:=NumProject.Pages[i];
ngPagesList.Cell[ciPosOrder, i].ObjectReference:=TmpPage;
//ngPagesList.Cell[ciPosOrder, i].AsString:=IntToStr(TmpPage.Order);
ngPagesList.Cell[ciPosOrder, i].AsInteger:=TmpPage.Order;
ngPagesList.Cell[ciPosNumPageTpl, i].ObjectReference:=nil;
//ngPagesList.Cell[ciPosNumPageTpl, i].AsString:=TmpPage.NumPageTpl.Name;
ngPagesList.Cell[ciPosNumPageTpl, i].AsInteger:=slPageTpl.IndexOf(TmpPage.NumPageTpl.Name);
end;
ngPagesList.EndUpdate();
{#IFDEF DEBUG}
DebugMsg('Created '+IntToStr(ngPagesList.RowCount)+' rows in '+IntToStr(MilliSecondsBetween(DT, Now))+' ms', 'NumPlanPreview');
{#ENDIF}
end;
procedure TfrmNumPlanPreview.ActivatePageByOrder(AOrder: Integer);
var
i: Integer;
TmpNumPlanItems: TNumPlan;
TmpNumPageList: TNumPageList;
npi: TNumPlanItem;
begin
if not Assigned(NumProject) then Exit;
// Check order range
TmpNumPageList:=NumProject.Pages;
if AOrder < 1 then AOrder:=1;
if AOrder > TmpNumPageList.Count then AOrder:=TmpNumPageList.Count;
if AOrder = 0 then Exit;
// Find first ticket from selected page
TmpNumPlanItems:=NumProject.NumPlanItems;
for i:=0 to TmpNumPlanItems.Count-1 do
begin
npi:=TmpNumPlanItems[i];
if npi.NumPage.Order = AOrder then
begin
Core.AddCmd('NUMPLAN_ITEM_SEL '+IntToStr(npi.ID));
Break;
end;
end;
end;
procedure TfrmNumPlanPreview.ngPagesListSelectCell(Sender: TObject; ACol,
ARow: Integer);
var
TmpPage: TNumPage;
begin
if LockPagesList then Exit;
if not Assigned(ngPagesList.Cell[ciPosOrder, ARow].ObjectReference) then Exit;
TmpPage:=(ngPagesList.Cell[ciPosOrder, ARow].ObjectReference as TNumPage);
//if not Assigned(TmpPage) then Exit;
//Core.AddCmd('STATUS Page='+IntToStr(TmpPage.Order)+' row='+IntToStr(ngPagesList.SelectedRow));
ActivatePageByOrder(TmpPage.Order);
end;
end.
|
{ *************************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Visual Component Library }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{ *************************************************************************** }
unit VarConv;
interface
uses
SysUtils, Variants, ConvUtils;
function VarConvertCreate(const AValue: Double; const AType: TConvType): Variant; overload;
function VarConvertCreate(const AValue: string): Variant; overload;
function VarConvert: TVarType;
function VarIsConvert(const AValue: Variant): Boolean;
function VarAsConvert(const AValue: Variant): Variant; overload;
function VarAsConvert(const AValue: Variant; const AType: TConvType): Variant; overload;
implementation
uses
Math, Types;
type
TConvertVariantType = class(TInvokeableVariantType)
protected
function RightPromotion(const V: TVarData; const Operator: TVarOp;
out RequiredVarType: TVarType): Boolean; override;
public
procedure Clear(var V: TVarData); override;
function IsClear(const V: TVarData): Boolean; override;
procedure Copy(var Dest: TVarData; const Source: TVarData;
const Indirect: Boolean); override;
procedure UnaryOp(var Right: TVarData; const Operator: TVarOp);
override;
procedure BinaryOp(var Left: TVarData; const Right: TVarData;
const Operator: TVarOp); override;
procedure Compare(const Left: TVarData; const Right: TVarData;
var Relationship: TVarCompareResult); override;
procedure Cast(var Dest: TVarData; const Source: TVarData); override;
procedure CastTo(var Dest: TVarData; const Source: TVarData;
const AVarType: Word); override;
function GetProperty(var Dest: TVarData; const V: TVarData;
const Name: String): Boolean; override;
function SetProperty(const V: TVarData; const Name: String;
const Value: TVarData): Boolean; override;
end;
TConvertVarData = packed record
VType: TVarType;
VConvType: TConvType;
Reserved1, Reserved2: Word;
VValue: Double;
end;
var
ConvertVariantType: TConvertVariantType;
procedure VarConvertCreateInto(var ADest: Variant; const AValue: Double; const AType: TConvType);
begin
VarClear(ADest);
TConvertVarData(ADest).VType := VarConvert;
TConvertVarData(ADest).VConvType := AType;
TConvertVarData(ADest).VValue := AValue;
end;
function VarConvertCreate(const AValue: Double; const AType: TConvType): Variant;
begin
VarConvertCreateInto(Result, AValue, AType);
end;
function VarConvertCreate(const AValue: string): Variant;
var
LValue: Double;
LType: TConvType;
begin
if not TryStrToConvUnit(AValue, LValue, LType) then
ConvertVariantType.RaiseCastError;
VarConvertCreateInto(Result, LValue, LType);
end;
function VarConvert: TVarType;
begin
Result := ConvertVariantType.VarType;
end;
function VarIsConvert(const AValue: Variant): Boolean;
begin
Result := (TVarData(AValue).VType and varTypeMask) = VarConvert;
end;
function VarAsConvert(const AValue: Variant): Variant; overload;
begin
if not VarIsConvert(AValue) then
VarCast(Result, AValue, VarConvert)
else
Result := AValue;
end;
function VarAsConvert(const AValue: Variant; const AType: TConvType): Variant;
begin
if not VarIsConvert(AValue) then
Result := VarConvertCreate(AValue, AType)
else
Result := AValue;
end;
{ TConvertVariantType }
procedure TConvertVariantType.BinaryOp(var Left: TVarData;
const Right: TVarData; const Operator: TVarOp);
var
LValue: Double;
LType: TConvType;
begin
// supports...
// convvar + number = convvar
// convvar - number = convvar
// convvar * number = convvar
// convvar / number = convvar
// convvar div number = convvar
// Add (subtract, etc) the number to the value contained in convvar
// convvar's type does not change
// convvar1 + convvar2 = convvar1
// convvar1 - convvar2 = convvar1
// convvar1 * convvar2 = !ERROR!
// convvar1 / convvar2 = double
// convvar1 div convvar2 = integer
// Add (subtract, etc) convvar2 and convvar1 after converting convvar2
// to convvar1's unit type. Result's unit type will equal convvar1's type
// Please note that you currently cannot multiply two varConvert variants
// the right can also be a string, if it has unit info then it is treated
// like a varConvert else it is treated as a double
{$RANGECHECKS ON}
case Right.VType of
varString:
case Operator of
opAdd:
if TryStrToConvUnit(Variant(Right), LValue, LType) then
if LType = CIllegalConvType then
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue + LValue
else
Variant(Left) := Variant(Left) + VarConvertCreate(LValue, LType)
else
RaiseCastError;
opSubtract:
if TryStrToConvUnit(Variant(Right), LValue, LType) then
if LType = CIllegalConvType then
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue + LValue
else
Variant(Left) := Variant(Left) - VarConvertCreate(LValue, LType)
else
RaiseCastError;
opMultiply:
if TryStrToConvUnit(Variant(Right), LValue, LType) then
if LType = CIllegalConvType then
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue * LValue
else
RaiseInvalidOp
else
RaiseCastError;
opDivide:
if TryStrToConvUnit(Variant(Right), LValue, LType) then
if LType = CIllegalConvType then
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue / LValue
else
Variant(Left) := Variant(Left) / VarConvertCreate(LValue, LType)
else
RaiseCastError;
opIntDivide:
if TryStrToConvUnit(Variant(Right), LValue, LType) then
if LType = CIllegalConvType then
TConvertVarData(Left).VValue := Int(TConvertVarData(Left).VValue / LValue)
else
Variant(Left) := Variant(Left) div VarConvertCreate(LValue, LType)
else
RaiseCastError;
else
RaiseInvalidOp;
end;
varDouble:
case Operator of
opAdd:
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue +
TVarData(Right).VDouble;
opSubtract:
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue -
TVarData(Right).VDouble;
opMultiply:
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue *
TVarData(Right).VDouble;
opDivide:
TConvertVarData(Left).VValue := TConvertVarData(Left).VValue /
TVarData(Right).VDouble;
opIntDivide:
TConvertVarData(Left).VValue := Int(TConvertVarData(Left).VValue /
TVarData(Right).VDouble);
else
RaiseInvalidOp;
end;
else
if Left.VType = VarType then
case Operator of
opAdd:
TConvertVarData(Left).VValue := ConvUnitInc(TConvertVarData(Left).VValue,
TConvertVarData(Left).VConvType,
TConvertVarData(Right).VValue,
TConvertVarData(Right).VConvType);
opSubtract:
TConvertVarData(Left).VValue := ConvUnitDec(TConvertVarData(Left).VValue,
TConvertVarData(Left).VConvType,
TConvertVarData(Right).VValue,
TConvertVarData(Right).VConvType);
opDivide:
Variant(Left) := TConvertVarData(Left).VValue /
Convert(TConvertVarData(Right).VValue,
TConvertVarData(Right).VConvType,
TConvertVarData(Left).VConvType);
opIntDivide:
Variant(Left) := Int(TConvertVarData(Left).VValue /
Convert(TConvertVarData(Right).VValue,
TConvertVarData(Right).VConvType,
TConvertVarData(Left).VConvType));
else
RaiseInvalidOp;
end
else
RaiseInvalidOp;
end;
{$RANGECHECKS OFF}
end;
procedure TConvertVariantType.Cast(var Dest: TVarData; const Source: TVarData);
var
LValue: Double;
LType: TConvType;
begin
if TryStrToConvUnit(VarDataToStr(Source), LValue, LType) then
begin
VarDataClear(Dest);
TConvertVarData(Dest).VValue := LValue;
TConvertVarData(Dest).VConvType := LType;
Dest.VType := VarType;
end
else
RaiseCastError;
end;
procedure TConvertVariantType.CastTo(var Dest: TVarData;
const Source: TVarData; const AVarType: Word);
var
LTemp: TVarData;
begin
if Source.VType = VarType then
case AVarType of
varOleStr:
VarDataFromOleStr(Dest, ConvUnitToStr(TConvertVarData(Source).VValue,
TConvertVarData(Source).VConvType));
varString:
VarDataFromStr(Dest, ConvUnitToStr(TConvertVarData(Source).VValue,
TConvertVarData(Source).VConvType));
else
VarDataInit(LTemp);
try
LTemp.VType := varDouble;
LTemp.VDouble := TConvertVarData(Source).VValue;
VarDataCastTo(Dest, LTemp, AVarType);
finally
VarDataClear(LTemp);
end;
end
else
RaiseCastError;
end;
procedure TConvertVariantType.Clear(var V: TVarData);
begin
SimplisticClear(V);
end;
procedure TConvertVariantType.Compare(const Left, Right: TVarData;
var Relationship: TVarCompareResult);
const
CRelationshipToRelationship: array [TValueRelationship] of TVarCompareResult =
(crLessThan, crEqual, crGreaterThan);
var
LValue: Double;
LType: TConvType;
LRelationship: TValueRelationship;
begin
// supports...
// convvar cmp number
// Compare the value of convvar and the given number
// convvar1 cmp convvar2
// Compare after converting convvar2 to convvar1's unit type
// The right can also be a string. If the string has unit info then it is
// treated like a varConvert else it is treated as a double
LRelationship := EqualsValue;
case Right.VType of
varString:
if TryStrToConvUnit(Variant(Right), LValue, LType) then
if LType = CIllegalConvType then
LRelationship := CompareValue(TConvertVarData(Left).VValue, LValue)
else
LRelationship := ConvUnitCompareValue(TConvertVarData(Left).VValue,
TConvertVarData(Left).VConvType,
LValue, LType)
else
RaiseCastError;
varDouble:
LRelationship := CompareValue(TConvertVarData(Left).VValue,
TVarData(Right).VDouble);
else
if Left.VType = VarType then
LRelationship := ConvUnitCompareValue(TConvertVarData(Left).VValue,
TConvertVarData(Left).VConvType,
TConvertVarData(Right).VValue,
TConvertVarData(Right).VConvType)
else
RaiseInvalidOp;
end;
Relationship := CRelationshipToRelationship[LRelationship];
end;
procedure TConvertVariantType.Copy(var Dest: TVarData;
const Source: TVarData; const Indirect: Boolean);
begin
SimplisticCopy(Dest, Source, Indirect);
end;
function TConvertVariantType.GetProperty(var Dest: TVarData;
const V: TVarData; const Name: String): Boolean;
var
LType: TConvType;
begin
// supports...
// 'Value'
// 'Type'
// 'TypeName'
// 'Family'
// 'FamilyName'
// 'As[Type]'
Result := True;
if Name = 'VALUE' then
Variant(Dest) := TConvertVarData(V).VValue
else if Name = 'TYPE' then
Variant(Dest) := TConvertVarData(V).VConvType
else if Name = 'TYPENAME' then
Variant(Dest) := ConvTypeToDescription(TConvertVarData(V).VConvType)
else if Name = 'FAMILY' then
Variant(Dest) := ConvTypeToFamily(TConvertVarData(V).VConvType)
else if Name = 'FAMILYNAME' then
Variant(Dest) := ConvFamilyToDescription(ConvTypeToFamily(TConvertVarData(V).VConvType))
else if System.Copy(Name, 1, 2) = 'AS' then
begin
if DescriptionToConvType(ConvTypeToFamily(TConvertVarData(V).VConvType),
System.Copy(Name, 3, MaxInt), LType) then
VarConvertCreateInto(Variant(Dest),
Convert(TConvertVarData(V).VValue,
TConvertVarData(V).VConvType, LType),
LType)
else
Result := False;
end
else
Result := False;
end;
function TConvertVariantType.IsClear(const V: TVarData): Boolean;
begin
Result := TConvertVarData(V).VConvType = CIllegalConvType;
end;
function TConvertVariantType.RightPromotion(const V: TVarData;
const Operator: TVarOp; out RequiredVarType: TVarType): Boolean;
begin
// supports...
// Add, Subtract, Divide, IntDivide and Compare
// Ordinals (used as is), strings (converted to either an ordinal or
// another varConvert) and other varConvert (used as is) variants.
// Multiply
// Ordinals (used as is) and strings (converted to an ordinal).
Result := True;
case Operator of
opAdd, opSubtract, opDivide, opIntDivide, opCompare:
if VarDataIsNumeric(V) then
RequiredVarType := varDouble
else if VarDataIsStr(V) then
RequiredVarType := varString
else
RequiredVarType := VarType;
opMultiply:
if VarDataIsNumeric(V) or VarDataIsStr(V) then
RequiredVarType := varDouble
else
RaiseCastError;
else
RaiseInvalidOp;
end;
end;
function TConvertVariantType.SetProperty(const V: TVarData;
const Name: String; const Value: TVarData): Boolean;
begin
// supports...
// 'Value'
Result := True;
if Name = 'VALUE' then
TConvertVarData(PVarData(@V)^).VValue := Variant(Value)
else
Result := False;
end;
procedure TConvertVariantType.UnaryOp(var Right: TVarData;
const Operator: TVarOp);
begin
// supports...
// '-'
case Operator of
opNegate:
TConvertVarData(Right).VValue := -TConvertVarData(Right).VValue;
else
RaiseInvalidOp;
end;
end;
initialization
ConvertVariantType := TConvertVariantType.Create;
finalization
FreeAndNil(ConvertVariantType);
end.
|
unit uMultaModel;
interface
uses
uEnumerado, FireDAC.Comp.Client, System.SysUtils;
type
TMultaModel = class
private
FAcao: TAcao;
FIdEmprestimo: string;
FIdUsuario: string;
FValor: Double;
procedure SetAcao(const Value: TAcao);
procedure setEmprestimo(const Value: string);
procedure setUsuario(const Value: string);
procedure setValor(const Value: Double);
public
function Obter: TFDQuery;
function Salvar: Boolean;
procedure AplicarMultas;
function BuscarMultas(Cpf: string): TFDQuery;
property IdEmprestimo: string read FIdEmprestimo write setEmprestimo;
property IdUsuario: string read FIdUsuario write setUsuario;
property Valor: Double read FValor write setValor;
property Acao: TAcao read FAcao write SetAcao;
end;
implementation
{ TEmprestimo }
uses uMultaDao, uEmprestimoDao;
procedure TMultaModel.AplicarMultas;
var
VQryEmprestimos: TFDQuery;
VQryMulta: TFDQuery;
DaoEmprestimo: TEmprestimoDao;
DaoMulta: TMultaDao;
Hoje: TDateTime;
Vencimento: TDateTime;
begin
DaoEmprestimo := TEmprestimoDao.Create;
DaoMulta := TMultaDao.Create;
try
Hoje := date;
VQryEmprestimos := DaoEmprestimo.Obter;
VQryEmprestimos.First;
while not VQryEmprestimos.Eof do
begin
Vencimento := StrToDate(VQryEmprestimos.FieldByName('Vencimento').AsString);
if Vencimento < Hoje then
begin
Self.IdEmprestimo := VQryEmprestimos.FieldByName('Id_Emprestimo').AsString;
Self.IdUsuario := VQryEmprestimos.FieldByName('Id_Usuario').AsString;
Self.Valor := (Hoje - Vencimento) * 2.0;
Self.Acao := tacIncluir;
VQryMulta := DaoMulta.Buscar(Self);
if VQryMulta.RecordCount > 0 then
begin
Self.Valor := VQryMulta.FieldByName('Valor').AsFloat + (Hoje - Vencimento) * 2.0;
Self.Acao := tacAlterar;
end;
Self.Salvar;
end;
VQryEmprestimos.Next;
end;
VQryEmprestimos.Close;
VQryMulta.Close;
finally
DaoEmprestimo.Free;
DaoMulta.Free;
end;
end;
function TMultaModel.BuscarMultas(Cpf: string): TFDQuery;
var
Dao: TMultaDao;
begin
Dao := TMultaDao.Create;
try
Result := Dao.ObterSelecionadas(Cpf);
finally
Dao.Free;
end;
end;
function TMultaModel.Obter: TFDQuery;
var
Dao: TMultaDao;
begin
Dao := TMultaDao.Create;
try
Result := Dao.Obter;
finally
Dao.Free;
end;
end;
function TMultaModel.Salvar: Boolean;
var
Dao: TMultaDao;
begin
Result := False;
Dao := TMultaDao.Create;
try
case FAcao of
uEnumerado.tacIncluir:
Result := Dao.Incluir(Self);
uEnumerado.tacAlterar:
Result := Dao.AtualizarValor(Self);
uEnumerado.tacExcluir:
Result := Dao.Excluir(Self);
end;
finally
Dao.Free;
end;
end;
procedure TMultaModel.SetAcao(const Value: TAcao);
begin
FAcao := Value;
end;
procedure TMultaModel.setEmprestimo(const Value: string);
begin
FIdEmprestimo := Value;
end;
procedure TMultaModel.setUsuario(const Value: string);
begin
FIdUsuario := Value;
end;
procedure TMultaModel.setValor(const Value: Double);
begin
FValor := Value;
end;
end.
|
unit BCEditor.Editor.SpecialChars;
interface
uses
Classes, Graphics,
BCEditor.Editor.SpecialChars.Selection, BCEditor.Editor.SpecialChars.EndOfLine,
BCEditor.Types;
type
TBCEditorSpecialChars = class(TPersistent)
strict private
FColor: TColor;
FEndOfLine: TBCEditorSpecialCharsEndOfLine;
FOnChange: TNotifyEvent;
FOptions: TBCEditorSpecialCharsOptions;
FSelection: TBCEditorSpecialCharsSelection;
FStyle: TBCEditorSpecialCharsStyle;
FVisible: Boolean;
procedure DoChange;
procedure SetColor(const Value: TColor);
procedure SetEndOfLine(const Value: TBCEditorSpecialCharsEndOfLine);
procedure SetOnChange(const Value: TNotifyEvent);
procedure SetOptions(const Value: TBCEditorSpecialCharsOptions);
procedure SetSelection(const Value: TBCEditorSpecialCharsSelection);
procedure SetStyle(const Value: TBCEditorSpecialCharsStyle);
procedure SetVisible(const Value: Boolean);
public
constructor Create;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
published
property Color: TColor read FColor write SetColor default clBlack;
property EndOfLine: TBCEditorSpecialCharsEndOfLine read FEndOfLine write SetEndOfLine;
property OnChange: TNotifyEvent read FOnChange write SetOnChange;
property Options: TBCEditorSpecialCharsOptions read FOptions write SetOptions default [scoUseTextColor];
property Selection: TBCEditorSpecialCharsSelection read FSelection write SetSelection;
property Style: TBCEditorSpecialCharsStyle read FStyle write SetStyle;
property Visible: Boolean read FVisible write SetVisible default False;
end;
implementation
{ TBCEditorSpecialChars }
constructor TBCEditorSpecialChars.Create;
begin
inherited;
FColor := clBlack;
FEndOfLine := TBCEditorSpecialCharsEndOfLine.Create;
FSelection := TBCEditorSpecialCharsSelection.Create;
FVisible := False;
FOptions := [scoUseTextColor];
end;
destructor TBCEditorSpecialChars.Destroy;
begin
FEndOfLine.Free;
FSelection.Free;
inherited Destroy;
end;
procedure TBCEditorSpecialChars.SetOnChange(const Value: TNotifyEvent);
begin
FOnChange := Value;
FEndOfLine.OnChange := FOnChange;
FSelection.OnChange := FOnChange;
end;
procedure TBCEditorSpecialChars.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorSpecialChars) then
with Source as TBCEditorSpecialChars do
begin
Self.FColor := FColor;
Self.FEndOfLine.Assign(FEndOfLine);
Self.FOptions := FOptions;
Self.FSelection.Assign(FSelection);
Self.FVisible := FVisible;
Self.DoChange;
end
else
inherited Assign(Source);
end;
procedure TBCEditorSpecialChars.DoChange;
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TBCEditorSpecialChars.SetColor(const Value: TColor);
begin
if Value <> FColor then
begin
FColor := Value;
DoChange;
end;
end;
procedure TBCEditorSpecialChars.SetEndOfLine(const Value: TBCEditorSpecialCharsEndOfLine);
begin
FEndOfLine.Assign(Value);
end;
procedure TBCEditorSpecialChars.SetSelection(const Value: TBCEditorSpecialCharsSelection);
begin
FSelection.Assign(Value);
end;
procedure TBCEditorSpecialChars.SetVisible(const Value: Boolean);
begin
if Value <> FVisible then
begin
FVisible := Value;
DoChange;
end;
end;
procedure TBCEditorSpecialChars.SetStyle(const Value: TBCEditorSpecialCharsStyle);
begin
if Value <> FStyle then
begin
FStyle := Value;
DoChange;
end;
end;
procedure TBCEditorSpecialChars.SetOptions(const Value: TBCEditorSpecialCharsOptions);
begin
if Value <> FOptions then
begin
FOptions := Value;
DoChange;
end;
end;
end.
|
{
"Bitmap Utils"
- Copyright 2013-2017 (c) RealThinClient.com (http://www.realthinclient.com)
@exclude
}
unit rtcXBmpUtils;
interface
{$INCLUDE rtcDefs.inc}
uses
SysUtils,
rtcTypes,
rtcSystem,
rtcInfo,
rtcXJPEGConst;
type
BufferType=(btBGR24,btBGRA32,
btRGB24,btRGBA32);
TRtcBitmapInfo=record
Data:Pointer;
TopData:^Byte;
Width,Height:integer;
Reverse:boolean;
BuffType:BufferType;
BytesTotal,
BytesPerPixel,
BytesPerLine,
PixelsToNextLine,
TopLine,
NextLine:integer;
end;
TRtcCursorRect=record
Left,Top,
Right,Bottom:integer;
end;
TRtcMouseCursorInfo=class(TObject)
protected
FCS:TRtcCritSec;
FCursorVisible: boolean;
FCursorHotX: integer;
FCursorHotY: integer;
FCursorX: integer;
FCursorY: integer;
FCursorImageW: integer;
FCursorImageH: integer;
FCursorMaskW: integer;
FCursorMaskH: integer;
FCursorOldY: integer;
FCursorOldX: integer;
FCursorUser: cardinal;
FCursorImageData: RtcByteArray;
FCursorMaskData: RtcByteArray;
FData: TObject;
procedure RealUpdate(const rec:TRtcRecord);
public
constructor Create; virtual;
destructor Destroy; override;
procedure Lock;
procedure UnLock;
procedure ClearImageData;
procedure ClearMaskData;
procedure Update(const MouseCursorData:RtcByteArray);
function GetRect(NowMouseX, NowMouseY: integer; inControl: boolean): TRtcCursorRect;
property Visible:boolean read FCursorVisible;
property HotX:integer read FCursorHotX;
property HotY:integer read FCursorHotY;
property X:integer read FCursorX;
property Y:integer read FCursorY;
property ImageW:integer read FCursorImageW;
property ImageH:integer read FCursorImageH;
property MaskW:integer read FCursorMaskW;
property MaskH:integer read FCursorMaskH;
property OldX:integer read FCursorOldX;
property OldY:integer read FCursorOldY;
property User:cardinal read FCursorUser;
property ImageData:RtcByteArray read FCursorImageData;
property MaskData:RtcByteArray read FCursorMaskData;
property Data:TObject read FData write FData;
end;
// Map BitmapInfo for internal usage
function MapBitmapInfo(const OldBmp:TRtcBitmapInfo):TRtcBitmapInfo;
// Unmap BitmapInfo
procedure UnMapBitmapInfo(var NewBmp:TRtcBitmapInfo);
procedure CompleteBitmapInfo(var Result:TRtcBitmapInfo);
// Reset Bitmap Info image
procedure ResetBitmapInfo(var NewBmp:TRtcBitmapInfo);
// Make an exact duplicate of OldBmp, copying image contents
function DuplicateBitmapInfo(const OldBmp:TRtcBitmapInfo):TRtcBitmapInfo;
// Copy image with all info from OldBmp to Result
procedure CopyBitmapInfo(const OldBmp:TRtcBitmapInfo; var Result:TRtcBitmapInfo);
// Resize the memory occupied by the image
procedure ResizeBitmapInfo(var BmpInfo:TRtcBitmapInfo; SizeX,SizeY:integer; Clear:boolean);
// Release the memory occupied by the image copy created with DuplicateBitmapInfo
procedure ReleaseBitmapInfo(var NewBmp:TRtcBitmapInfo);
implementation
procedure CompleteBitmapInfo(var Result:TRtcBitmapInfo);
begin
if Result.Reverse then
begin
Result.TopLine:=Result.BytesPerLine*(Result.Height-1);
Result.NextLine:=-Result.BytesPerLine;
end
else
begin
Result.TopLine:=0;
Result.NextLine:=Result.BytesPerLine;
end;
Result.TopData:=Result.Data;
if assigned(Result.TopData) then
Inc(Result.TopData,Result.TopLine);
Result.BytesTotal:=Result.BytesPerPixel*Result.Width;
if Result.Height>1 then
Inc(Result.BytesTotal,Result.BytesPerLine*(Result.Height-1));
if Result.BytesPerPixel>0 then
begin
Result.PixelsToNextLine:=Result.BytesPerLine div Result.BytesPerPixel;
if Result.Reverse then
Result.PixelsToNextLine:=-Result.PixelsToNextLine;
end
else
Result.PixelsToNextLine:=0;
end;
function DuplicateBitmapInfo(const OldBmp:TRtcBitmapInfo):TRtcBitmapInfo;
begin
FillChar(Result, SizeOf(Result), 0);
Result.Width:=OldBmp.Width;
Result.Height:=OldBmp.Height;
Result.Reverse:=OldBmp.Reverse;
Result.BuffType:=OldBmp.BuffType;
Result.BytesPerPixel:=OldBmp.BytesPerPixel;
Result.BytesPerLine:=OldBmp.BytesPerLine;
Result.TopLine:=OldBmp.TopLine;
Result.NextLine:=OldBmp.NextLine;
Result.BytesTotal:=Result.BytesPerPixel*Result.Width;
if Result.Height>1 then
Inc(Result.BytesTotal,Result.BytesPerLine*(Result.Height-1));
if Result.BytesPerPixel>0 then
begin
Result.PixelsToNextLine:=Result.BytesPerLine div Result.BytesPerPixel;
if Result.Reverse then
Result.PixelsToNextLine:=-Result.PixelsToNextLine;
end
else
Result.PixelsToNextLine:=0;
Result.PixelsToNextLine:=Result.BytesPerLine div Result.BytesPerPixel;
if Result.Reverse then
Result.PixelsToNextLine:=-Result.PixelsToNextLine;
if Result.BytesTotal>0 then
begin
GetMem(Result.Data, Result.BytesTotal);
Move(OldBmp.Data^, Result.Data^, Result.BytesTotal);
Result.TopData:=Result.Data;
Inc(Result.TopData,Result.TopLine);
end;
end;
procedure CopyBitmapInfo(const OldBmp:TRtcBitmapInfo; var Result:TRtcBitmapInfo);
begin
if assigned(Result.Data) then
begin
if Result.BytesTotal<>OldBmp.BytesTotal then
begin
if OldBmp.BytesTotal>0 then
ReallocMem(Result.Data,OldBmp.BytesTotal)
else
begin
FreeMem(Result.Data);
Result.Data:=nil;
end;
end;
end
else if OldBmp.BytesTotal>0 then
GetMem(Result.Data,OldBmp.BytesTotal);
Result.Width:=OldBmp.Width;
Result.Height:=OldBmp.Height;
Result.Reverse:=OldBmp.Reverse;
Result.BuffType:=OldBmp.BuffType;
Result.BytesPerPixel:=OldBmp.BytesPerPixel;
Result.BytesPerLine:=OldBmp.BytesPerLine;
Result.TopLine:=OldBmp.TopLine;
Result.NextLine:=OldBmp.NextLine;
Result.BytesTotal:=OldBmp.BytesTotal;
Result.PixelsToNextLine:=OldBmp.PixelsToNextLine;
if Result.BytesTotal>0 then
begin
Move(OldBmp.Data^, Result.Data^, Result.BytesTotal);
Result.TopData:=Result.Data;
Inc(Result.TopData,Result.TopLine);
end;
end;
procedure ReleaseBitmapInfo(var NewBmp:TRtcBitmapInfo);
begin
if assigned(NewBmp.Data) then
begin
FreeMem(NewBmp.Data);
FillChar(NewBmp,SizeOf(NewBmp),0);
end;
end;
function MapBitmapInfo(const OldBmp:TRtcBitmapInfo):TRtcBitmapInfo;
begin
FillChar(Result, SizeOf(Result), 0);
Result.Data:=OldBmp.Data;
Result.Width:=OldBmp.Width;
Result.Height:=OldBmp.Height;
Result.Reverse:=OldBmp.Reverse;
Result.BuffType:=OldBmp.BuffType;
Result.BytesPerPixel:=OldBmp.BytesPerPixel;
Result.BytesPerLine:=OldBmp.BytesPerLine;
Result.TopLine:=OldBmp.TopLine;
Result.NextLine:=OldBmp.NextLine;
Result.BytesTotal:=OldBmp.BytesTotal;
Result.TopData:=OldBmp.TopData;
Result.PixelsToNextLine:=OldBmp.PixelsToNextLine;
end;
procedure UnMapBitmapInfo(var NewBmp:TRtcBitmapInfo);
begin
FillChar(NewBmp, SizeOf(NewBmp), 0);
end;
procedure ClearBitmapInfo(var BmpInfo:TRtcBitmapInfo);
var
pix:LongWord;
data:PLongWord;
cnt,i:integer;
crgb:colorRGB32;
cbgr:colorBGR32;
begin
if not assigned(BmpInfo.Data) then Exit;
if (BmpInfo.Width=0) or (BmpInfo.Height=0) then Exit;
cnt:=BmpInfo.Width*BmpInfo.Height;
crgb.R:=0;crgb.B:=0;crgb.G:=0;crgb.A:=255;
cbgr.R:=0;cbgr.B:=0;cbgr.G:=0;cbgr.A:=255;
case BmpInfo.BuffType of
btBGRA32: pix:=LongWord(cbgr);
btRGBA32: pix:=LongWord(crgb);
else pix:=0;
end;
data:=PLongWord(BmpInfo.Data);
for i := 1 to cnt do
begin
data^:=pix;
Inc(data);
end;
end;
procedure ResizeBitmapInfo(var BmpInfo:TRtcBitmapInfo; SizeX,SizeY:integer; Clear:boolean);
var
OldData:pointer;
Src,Dst:^Byte;
OldSX,OldSY,
SX,SY,BPL,BPLS,BPLD,Line:integer;
begin
if (SizeX<>BmpInfo.Width) or (SizeY<>BmpInfo.Height) then
begin
if (SizeX>0) and (SizeY>0) then
begin
OldData:=BmpInfo.Data;
OldSX:=BmpInfo.Width;
OldSY:=BmpInfo.Height;
GetMem(BmpInfo.Data,SizeX*SizeY*BmpInfo.BytesPerPixel);
BmpInfo.TopData:=BmpInfo.Data;
BmpInfo.Width:=SizeX;
BmpInfo.Height:=SizeY;
ClearBitmapInfo(BmpInfo);
if SizeX>OldSX then SX:=OldSX else SX:=SizeX;
if SizeY>OldSY then SY:=OldSY else SY:=SizeY;
if assigned(OldData) then
begin
if not Clear and (SX>0) and (SY>0) then
begin
Src:=OldData;
Dst:=BmpInfo.Data;
BPL :=BmpInfo.BytesPerPixel * SX;
BPLS:=BmpInfo.BytesPerPixel * OldSX;
BPLD:=BmpInfo.BytesPerPixel * SizeX;
if BmpInfo.Reverse then
begin
Inc(Src,BPLS*(OldSY-1));
Inc(Dst,BPLD*(SizeY-1));
for Line:=1 to SY do
begin
Move(Src^,Dst^,BPL);
Dec(Src,BPLS);
Dec(Dst,BPLD);
end;
end
else
begin
for Line:=1 to SY do
begin
Move(Src^,Dst^,BPL);
Inc(Src,BPLS);
Inc(Dst,BPLD);
end;
end;
end;
FreeMem(OldData);
end;
end
else if assigned(BmpInfo.Data) then
begin
FreeMem(BmpInfo.Data);
BmpInfo.Data:=nil;
BmpInfo.TopData:=nil;
BmpInfo.Width:=0;
BmpInfo.Height:=0;
end;
BmpInfo.BytesPerLine:=BmpInfo.BytesPerPixel*BmpInfo.Width;
CompleteBitmapInfo(BmpInfo);
end
else if Clear and assigned(BmpInfo.Data) and (BmpInfo.BytesTotal>0) then
ClearBitmapInfo(BmpInfo);
end;
procedure ResetBitmapInfo(var NewBmp:TRtcBitmapInfo);
begin
if assigned(NewBmp.Data) then
begin
FreeMem(NewBmp.Data);
NewBmp.Data:=nil;
NewBmp.TopData:=nil;
NewBmp.Width:=0;
NewBmp.Height:=0;
NewBmp.BytesPerLine:=0;
CompleteBitmapInfo(NewBmp);
end;
end;
{ TRtcMouseCursorInfo }
constructor TRtcMouseCursorInfo.Create;
begin
FCS:=TRtcCritSec.Create;
FCursorVisible:=False;
SetLength(FCursorImageData,0);
SetLength(FCursorMaskData,0);
FData:=nil;
end;
destructor TRtcMouseCursorInfo.Destroy;
begin
SetLength(FCursorImageData,0);
SetLength(FCursorMaskData,0);
FreeAndNil(FCS);
FreeAndNil(FData);
inherited;
end;
procedure TRtcMouseCursorInfo.Update(const MouseCursorData: RtcByteArray);
var
rec: TRtcRecord;
begin
if length(MouseCursorData)=0 then Exit;
rec := TRtcRecord.FromCode(RtcBytesToString(MouseCursorData));
FCS.Acquire;
try
RealUpdate(rec);
finally
FCS.Release;
rec.Free;
end;
end;
procedure TRtcMouseCursorInfo.RealUpdate(const rec:TRtcRecord);
begin
if (rec.isType['X'] <> rtc_Null) or (rec.isType['Y'] <> rtc_Null) then
begin
if FCursorVisible then
begin
FCursorOldX := FCursorX;
FCursorOldY := FCursorY;
end
else
begin
FCursorOldX := rec.asInteger['X'];
FCursorOldY := rec.asInteger['Y'];
end;
FCursorX := rec.asInteger['X'];
FCursorY := rec.asInteger['Y'];
FCursorUser := rec.asCardinal['A'];
end;
if (rec.isType['V'] <> rtc_Null) and (rec.asBoolean['V'] <> FCursorVisible) then
FCursorVisible := rec.asBoolean['V'];
if rec.isType['HX'] <> rtc_Null then
begin
FCursorHotX := rec.asInteger['HX'];
FCursorHotY := rec.asInteger['HY'];
if rec.isType['IW']<>rtc_Null then
begin
FCursorImageW:=rec.asInteger['IW'];
FCursorImageH:=rec.asInteger['IH'];
end
else
begin
FCursorImageW:=0;
FCursorImageH:=0;
end;
if rec.isType['MW']<>rtc_Null then
begin
FCursorMaskW:=rec.asInteger['MW'];
FCursorMaskH:=rec.asInteger['MH'];
end
else
begin
FCursorMaskW:=0;
FCursorMaskH:=0;
end;
if (rec.isType['I']=rtc_ByteArray) or
(rec.isType['M']=rtc_ByteArray) then
begin
SetLength(FCursorImageData,0);
SetLength(FCursorMaskData,0);
if rec.isType['I']=rtc_ByteArray then
if (length(rec.asByteArray['I'])>0) and
(length(rec.asByteArray['I'])=FCursorImageW*FCursorImageH*4) then
FCursorImageData:=rec.asByteArray['I'];
if rec.isType['M']=rtc_ByteArray then
if (length(rec.asByteArray['M'])>0) and
(length(rec.asByteArray['M'])=FCursorMaskW*FCursorMaskH*4) then
FCursorMaskData:=rec.asByteArray['M'];
end;
end;
end;
function TRtcMouseCursorInfo.GetRect(NowMouseX, NowMouseY: integer; inControl: boolean): TRtcCursorRect;
var
cX,cY:integer;
cW,cH:integer;
begin
FCS.Acquire;
try
if FCursorVisible and ((FCursorImageW+FCursorImageH>0) or (FCursorMaskW+FCursorMaskH>0)) then
begin
if inControl then
begin
cX:=NowMouseX-FCursorHotX;
cY:=NowMouseY-FCursorHotY;
end
else
begin
cX:=FCursorX-FCursorHotX;
cY:=FCursorY-FCursorHotY;
end;
cW:=0;
cH:=0;
if (FCursorMaskH+FCursorMaskW>0) then
begin
if (FCursorImageH+FCursorImageW>0) and (FCursorMaskH = FCursorImageH) then
begin
cW:=FCursorMaskW;
cH:=FCursorMaskH;
end
else if FCursorMaskH > 1 then
begin
cW:=FCursorMaskW;
cH:=FCursorMaskH div 2;
end;
end;
if (FCursorImageH+FCursorImageW>0) then
begin
if FCursorImageW>cW then cW:=FCursorImageW;
if FCursorImageH>cH then cH:=FCursorImageH;
end;
end
else
begin
cX:=0;cY:=0;
cW:=0;cH:=0;
end;
finally
FCS.Release;
end;
Result.Left:=cX;
Result.Top:=cY;
Result.Right:=cX+cW;
Result.Bottom:=cY+cH;
end;
procedure TRtcMouseCursorInfo.Lock;
begin
FCS.Acquire;
end;
procedure TRtcMouseCursorInfo.UnLock;
begin
FCS.Release;
end;
procedure TRtcMouseCursorInfo.ClearImageData;
begin
SetLength(FCursorImageData,0);
end;
procedure TRtcMouseCursorInfo.ClearMaskData;
begin
SetLength(FCursorMaskData,0);
end;
end.
|
unit uWeatherDLLTestMain;
interface
uses
Winapi.Windows, Winapi.Messages, Winapi.ShellAPI,
System.SysUtils, System.Variants, System.Classes, System.TypInfo,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.ExtCtrls, Vcl.ComCtrls,
JD.Weather.Intf, JD.Weather.SuperObject, System.ImageList, Vcl.ImgList,
Vcl.Menus;
type
TfrmMain = class(TForm)
Panel4: TPanel;
lstServices: TListView;
lstURLs: TListView;
GP: TGridPanel;
Panel1: TPanel;
Panel2: TPanel;
Panel5: TPanel;
Panel3: TPanel;
Panel6: TPanel;
Panel7: TPanel;
Panel8: TPanel;
Panel9: TPanel;
Panel10: TPanel;
imgLogo: TImage;
Panel11: TPanel;
Panel12: TPanel;
imgList: TImageList;
lstSupportedInfo: TListView;
lstSupportedLocationTypes: TListView;
lstSupportedConditionProps: TListView;
lstSupportedAlertTypes: TListView;
lstSupportedForecastSummaryProps: TListView;
lstSupportedAlertProps: TListView;
lstSupportedForecastHourlyProps: TListView;
lstSupportedForecastDailyProps: TListView;
lstSupportedMaps: TListView;
lstSupportedUnits: TListView;
MM: TMainMenu;
File1: TMenuItem;
Service1: TMenuItem;
Refresh1: TMenuItem;
N1: TMenuItem;
Exit1: TMenuItem;
EditSettings1: TMenuItem;
N2: TMenuItem;
estData1: TMenuItem;
View1: TMenuItem;
LogoType1: TMenuItem;
SquareLight1: TMenuItem;
SquareDark1: TMenuItem;
WideLight1: TMenuItem;
WideDark1: TMenuItem;
Help1: TMenuItem;
ShowHelp1: TMenuItem;
N3: TMenuItem;
About1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure lstServicesSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure lstURLsClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Refresh1Click(Sender: TObject);
private
FCreateLib: TCreateJDWeather;
FLib: HMODULE;
FWeather: IJDWeather;
procedure ClearInfo;
procedure WeatherImageToPicture(const G: IWeatherGraphic;
const P: TPicture);
procedure DisplayService(const S: IWeatherService);
public
procedure LoadServices;
end;
var
frmMain: TfrmMain;
implementation
{$R *.dfm}
{ TfrmMain }
procedure TfrmMain.FormCreate(Sender: TObject);
var
E: Integer;
begin
{$IFDEF DEBUG}
ReportMemoryLeaksOnShutdown:= True;
{$ENDIF}
Width:= 1200;
Height:= 800;
GP.Align:= alClient;
imgLogo.Align:= alClient;
lstURLs.Align:= alClient;
lstServices.Width:= lstServices.Width + 1;
GP.Width:= GP.Width + 1;
lstSupportedInfo.Align:= alClient;
lstSupportedLocationTypes.Align:= alClient;
lstSupportedConditionProps.Align:= alClient;
lstSupportedAlertTypes.Align:= alClient;
lstSupportedAlertProps.Align:= alClient;
lstSupportedForecastSummaryProps.Align:= alClient;
lstSupportedForecastHourlyProps.Align:= alClient;
lstSupportedForecastDailyProps.Align:= alClient;
lstSupportedMaps.Align:= alClient;
lstSupportedUnits.Align:= alClient;
Show;
BringToFront;
Application.ProcessMessages;
//Load weather library
FLib:= LoadLibrary('JDWeather.dll');
if FLib <> 0 then begin
FCreateLib:= GetProcAddress(FLib, 'CreateJDWeather');
if Assigned(FCreateLib) then begin
try
FWeather:= FCreateLib(ExtractFilePath(ParamStr(0)));
LoadServices;
except
on E: Exception do begin
raise Exception.Create('Failed to create new instance of "IJDWeather": '+E.Message);
end;
end;
end else begin
raise Exception.Create('Function "CreateJDWeather" not found!');
end;
end else begin
E:= GetLastError;
raise Exception.Create('Failed to load library "JDWeather.dll" with error code '+IntToStr(E));
end;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
//
end;
procedure TfrmMain.LoadServices;
var
X: Integer;
S: IWeatherService;
I: TListItem;
begin
//Displays a list of supported services
lstServices.Items.Clear;
for X := 0 to FWeather.Services.Count-1 do begin
S:= FWeather.Services.Items[X];
I:= lstServices.Items.Add;
I.Caption:= S.Info.Caption;
I.Data:= Pointer(S);
end;
end;
procedure TfrmMain.WeatherImageToPicture(const G: IWeatherGraphic; const P: TPicture);
var
S: TStringStream;
I: TWicImage;
begin
//Converts an `IWeatherGraphic` interface to a `TPicture`
S:= TStringStream.Create;
try
S.WriteString(G.Base64);
S.Position:= 0;
I:= TWicImage.Create;
try
I.LoadFromStream(S);
P.Assign(I);
finally
FreeAndNil(I);
end;
finally
FreeAndNil(S);
end;
end;
procedure TfrmMain.ClearInfo;
begin
//Clear all service information
lstURLs.Items.Clear;
lstSupportedInfo.Items.Clear;
lstSupportedLocationTypes.Items.Clear;
lstSupportedConditionProps.Items.Clear;
lstSupportedAlertTypes.Items.Clear;
lstSupportedAlertProps.Items.Clear;
lstSupportedForecastSummaryProps.Items.Clear;
lstSupportedForecastHourlyProps.Items.Clear;
lstSupportedForecastDailyProps.Items.Clear;
lstSupportedMaps.Items.Clear;
lstSupportedUnits.Items.Clear;
imgLogo.Picture.Assign(nil);
end;
procedure TfrmMain.lstURLsClick(Sender: TObject);
var
U: String;
begin
//Launch url in browser
if lstURLs.ItemIndex >= 0 then begin
U:= lstURLs.Selected.SubItems[0];
ShellExecute(0, 'open', PChar(U), nil, nil, SW_SHOWNORMAL);
end;
end;
procedure TfrmMain.Refresh1Click(Sender: TObject);
begin
if lstServices.ItemIndex >= 0 then begin
DisplayService(IWeatherService(lstServices.Selected.Data));
end else begin
DisplayService(nil);
end;
end;
procedure TfrmMain.DisplayService(const S: IWeatherService);
const
IMG_CHECK = 1;
IMG_UNCHECK = -1;
var
TInfo, TCond, TLoc, TAlert, TAlertProp, TForSum, TForHour, TForDay, TMaps, TUnits: Integer;
PInfo, PCond, PLoc, PAlert, PAlertProp, PForSum, PForHour, PForDay, PMaps, PUnits: Single;
TP: Single;
WInfo: TWeatherInfoType;
WLoc: TWeatherLocationType;
WCond: TWeatherPropType;
WAlt: TWeatherAlertType;
WAlp: TWeatherAlertProp;
WMap: TWeatherMapType;
WMaf: TWeatherMapFormat;
WUni: TWeatherUnits;
I: TListItem;
X: Integer;
procedure ChkUrl(const N, V: String);
var
I: TListItem;
begin
if V <> '' then begin
I:= lstURLs.Items.Add;
I.Caption:= N;
I.SubItems.Add(V);
end;
end;
begin
Screen.Cursor:= crHourglass;
try
ClearInfo;
if Assigned(S) then begin
//Reset Defaults
TInfo:= 0;
TCond:= 0;
TLoc:= 0;
TAlert:= 0;
TAlertProp:= 0;
TForSum:= 0;
TForHour:= 0;
TForDay:= 0;
TMaps:= 0;
TUnits:= 0;
//Display URLs for Service
ChkUrl('Website', S.Info.URLs.MainURL);
ChkUrl('API Docs', S.Info.URLs.ApiURL);
ChkUrl('Register', S.Info.URLs.RegisterURL);
ChkUrl('Login', S.Info.URLs.LoginURL);
ChkUrl('Legal', S.Info.URLs.LegalURL);
//Show supported information types
lstSupportedInfo.Items.BeginUpdate;
try
for WInfo := Low(TWeatherInfoType) to High(TWeatherInfoType) do begin
I:= lstSupportedInfo.Items.Add;
I.Caption:= WeatherInfoTypeToStr(WInfo);
if WInfo in S.Info.Support.SupportedInfo then begin
Inc(TInfo);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedInfo.Items.EndUpdate;
end;
//Show supported location lookup types
lstSupportedLocationTypes.Items.BeginUpdate;
try
for WLoc := Low(TWeatherLocationType) to High(TWeatherLocationType) do begin
I:= lstSupportedLocationTypes.Items.Add;
I.Caption:= WeatherLocationTypeToStr(WLoc);
if WLoc in S.Info.Support.SupportedLocations then begin
Inc(TLoc);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedLocationTypes.Items.EndUpdate;
end;
//Show supported condition properties
lstSupportedConditionProps.Items.BeginUpdate;
try
for WCond := Low(TWeatherPropType) to High(TWeatherPropType) do begin
I:= lstSupportedConditionProps.Items.Add;
I.Caption:= WeatherPropToStr(WCond);
if WCond in S.Info.Support.SupportedConditionProps then begin
Inc(TCond);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedConditionProps.Items.EndUpdate;
end;
//Display supported forecast summary properties
lstSupportedForecastSummaryProps.Items.BeginUpdate;
try
for WCond := Low(TWeatherPropType) to High(TWeatherPropType) do begin
I:= lstSupportedForecastSummaryProps.Items.Add;
I.Caption:= WeatherPropToStr(WCond);
if WCond in S.Info.Support.SupportedForecastSummaryProps then begin
Inc(TForSum);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedForecastSummaryProps.Items.EndUpdate;
end;
//Display supported forecast hourly properties
lstSupportedForecastHourlyProps.Items.BeginUpdate;
try
for WCond := Low(TWeatherPropType) to High(TWeatherPropType) do begin
I:= lstSupportedForecastHourlyProps.Items.Add;
I.Caption:= WeatherPropToStr(WCond);
if WCond in S.Info.Support.SupportedForecastHourlyProps then begin
Inc(TForHour);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedForecastHourlyProps.Items.EndUpdate;
end;
//Display supported forecast daily properties
lstSupportedForecastDailyProps.Items.BeginUpdate;
try
for WCond := Low(TWeatherPropType) to High(TWeatherPropType) do begin
I:= lstSupportedForecastDailyProps.Items.Add;
I.Caption:= WeatherPropToStr(WCond);
if WCond in S.Info.Support.SupportedForecastDailyProps then begin
Inc(TForDay);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedForecastDailyProps.Items.EndUpdate;
end;
//Display supported alert types
lstSupportedAlertTypes.Items.BeginUpdate;
try
for WAlt := Low(TWeatherAlertType) to High(TWeatherAlertType) do begin
I:= lstSupportedAlertTypes.Items.Add;
I.Caption:= WeatherAlertTypeToStr(WAlt);
if WAlt in S.Info.Support.SupportedAlerts then begin
Inc(TAlert);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedAlertTypes.Items.EndUpdate;
end;
//Display supported alert properties
lstSupportedAlertProps.Items.BeginUpdate;
try
for WAlp := Low(TWeatherAlertProp) to High(TWeatherAlertProp) do begin
I:= lstSupportedAlertProps.Items.Add;
I.Caption:= WeatherAlertPropToStr(WAlp);
if WAlp in S.Info.Support.SupportedAlertProps then begin
Inc(TAlertProp);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedAlertProps.Items.EndUpdate;
end;
//Display supported map types
lstSupportedMaps.Items.BeginUpdate;
try
for WMap := Low(TWeatherMapType) to High(TWeatherMapType) do begin
I:= lstSupportedMaps.Items.Add;
I.Caption:= WeatherMapTypeToStr(WMap);
if WMap in S.Info.Support.SupportedMaps then begin
Inc(TMaps);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedMaps.Items.EndUpdate;
end;
//Display supported map formats
lstSupportedMaps.Items.BeginUpdate;
try
for WMaf := Low(TWeatherMapFormat) to High(TWeatherMapFormat) do begin
I:= lstSupportedMaps.Items.Add;
I.Caption:= WeatherMapFormatToStr(WMaf);
if WMaf in S.Info.Support.SupportedMapFormats then begin
Inc(TMaps);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedMaps.Items.EndUpdate;
end;
//Display supported units of measurement
lstSupportedUnits.Items.BeginUpdate;
try
for WUni := Low(TWeatherUnits) to High(TWeatherUnits) do begin
I:= lstSupportedUnits.Items.Add;
I.Caption:= WeatherUnitsToStr(WUni);
if WUni in S.Info.Support.SupportedUnits then begin
Inc(TUnits);
I.ImageIndex:= IMG_CHECK;
end else begin
I.ImageIndex:= IMG_UNCHECK;
end;
end;
finally
lstSupportedUnits.Items.EndUpdate;
end;
//Calculate percentage of support for each type of info
PInfo:= TInfo / (Integer(High(TWeatherInfoType))+1);
PLoc:= TLoc / (Integer(High(TWeatherLocationType))+1);
PCond:= TCond / (Integer(High(TWeatherPropType))+1);
PAlert:= TAlert / (Integer(High(TWeatherAlertType))+1);
PAlertProp:= TAlertProp / (Integer(High(TWeatherAlertProp))+1);
PForSum:= TForSum / (Integer(High(TWeatherPropType))+1);
PForHour:= TForHour / (Integer(High(TWeatherPropType))+1);
PForDay:= TForDay / (Integer(High(TWeatherPropType))+1);
PMaps:= TMaps / ((Integer(High(TWeatherMapType))+1) + (Integer(High(TWeatherMapFormat))+1));
PUnits:= TUnits / (Integer(High(TWeatherUnits))+1);
//Calculate overall average of support percentage for selected service
TP:=(PInfo + PLoc + PCond + PAlert + PAlertProp + PForSum +
PForHour + PForDay + PMaps + PUnits) / 10;
Caption:= 'JD Weather DLL Test - '+S.Info.Caption+' - '+FormatFloat('0.00%', TP*100);
//Display service company logo
try
WeatherImageToPicture(S.Info.GetLogo(ltColor), imgLogo.Picture);
except
on E: Exception do begin
//TODO
end;
end;
end else begin
Caption:= 'JD Weather DLL Test';
end;
for X := 0 to GP.ControlCount-1 do begin
if GP.Controls[X] is TListView then begin
TListView(GP.Controls[X]).Columns[0].Width:= (GP.ClientWidth div 5) - 6;
//GP.Controls[X].Width:= GP.Controls[X].Width - 1;
end;
end;
finally
Screen.Cursor:= crDefault;
end;
end;
procedure TfrmMain.lstServicesSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
begin
if Selected then begin
DisplayService(IWeatherService(Item.Data));
end else begin
DisplayService(nil);
end;
end;
end.
|
unit UUtilitarios;
interface
type
TUtilitarios = class
public
class function IfThen<T>(const cbValor: Boolean;
const coVerdadeiro: T;
const coFalso: T): T;
end;
implementation
{ TUtilitarios }
class function TUtilitarios.IfThen<T>(const cbValor: Boolean;
const coVerdadeiro, coFalso: T): T;
begin
if cbValor then
Result := coVerdadeiro
else
Result := coFalso
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ File: msxml.h }
{ Copyright (c) Microsoft Corporation, 1997-1998 }
{ }
{ Translator: Embarcadero Technologies, Inc. }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ Win32 API Interface Unit }
{*******************************************************}
unit Winapi.msxml;
// ************************************************************************ //
// WARNING
// -------
// The types declared in this file were generated from data read from a
// Type Library. If this type library is explicitly or indirectly (via
// another type library referring to this type library) re-imported, or the
// 'Refresh' command of the Type Library Editor activated while editing the
// Type Library, the contents of this file will be regenerated and all
// manual modifications will be lost.
// ************************************************************************ //
// $Rev: 17244 $
// File generated on 5/21/2009 8:41:50 PM from Type Library described below.
// ************************************************************************ //
// Type Lib: C:\WINDOWS\system32\msxml6.dll (1)
// LIBID: {F5078F18-C551-11D3-89B9-0000F81FE221}
// LCID: 0
// Helpfile:
// HelpString: Microsoft XML, v6.0
// DepndLst:
// (1) v2.0 stdole, (C:\WINDOWS\system32\stdole2.tlb)
// Errors:
// Hint: Parameter 'type' of IXMLDOMNode.nodeType changed to 'type_'
// Hint: Member 'implementation' of 'IXMLDOMDocument' changed to 'implementation_'
// Hint: Parameter 'type' of IXMLDOMDocument.createNode changed to 'type_'
// Hint: Parameter 'var' of IXMLDOMSchemaCollection.add changed to 'var_'
// Hint: Member 'type' of 'ISchemaElement' changed to 'type_'
// Hint: Parameter 'type' of ISchemaElement.type changed to 'type_'
// Hint: Member 'type' of 'ISchemaAttribute' changed to 'type_'
// Hint: Parameter 'type' of ISchemaAttribute.type changed to 'type_'
// ************************************************************************ //
{$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers.
{$WARN SYMBOL_PLATFORM OFF}
{$WRITEABLECONST ON}
{$VARPROPSETTER ON}
{$ALIGN 4}
{$MINENUMSIZE 4}
interface
uses Winapi.Windows, Winapi.ActiveX, Winapi.MSXMLIntf;
{$HPPEMIT '#include <msxml.h>'}
// *********************************************************************//
// GUIDS declared in the TypeLibrary. Following prefixes are used:
// Type Libraries : LIBID_xxxx
// CoClasses : CLASS_xxxx
// DISPInterfaces : DIID_xxxx
// Non-DISP interfaces: IID_xxxx
// *********************************************************************//
const
// TypeLibrary Major and minor versions
MSXML2MajorVersion = 6;
{$EXTERNALSYM MSXML2MajorVersion}
MSXML2MinorVersion = 0;
{$EXTERNALSYM MSXML2MinorVersion}
LIBID_MSXML2: TGUID = '{F5078F18-C551-11D3-89B9-0000F81FE221}';
IID_IXMLDOMImplementation: TGUID = '{2933BF8F-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMNode: TGUID = '{2933BF80-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMNodeList: TGUID = '{2933BF82-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMNamedNodeMap: TGUID = '{2933BF83-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMDocument: TGUID = '{2933BF81-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMDocumentType: TGUID = '{2933BF8B-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMElement: TGUID = '{2933BF86-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMAttribute: TGUID = '{2933BF85-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMDocumentFragment: TGUID = '{3EFAA413-272F-11D2-836F-0000F87A7782}';
IID_IXMLDOMCharacterData: TGUID = '{2933BF84-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMText: TGUID = '{2933BF87-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMComment: TGUID = '{2933BF88-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMCDATASection: TGUID = '{2933BF8A-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMProcessingInstruction: TGUID = '{2933BF89-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMEntityReference: TGUID = '{2933BF8E-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMParseError: TGUID = '{3EFAA426-272F-11D2-836F-0000F87A7782}';
IID_IXMLDOMDocument2: TGUID = '{2933BF95-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMSchemaCollection: TGUID = '{373984C8-B845-449B-91E7-45AC83036ADE}';
IID_IXMLDOMDocument3: TGUID = '{2933BF96-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMNotation: TGUID = '{2933BF8C-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMEntity: TGUID = '{2933BF8D-7B36-11D2-B20E-00C04F983E60}';
IID_IXMLDOMParseError2: TGUID = '{3EFAA428-272F-11D2-836F-0000F87A7782}';
IID_IXMLDOMParseErrorCollection: TGUID = '{3EFAA429-272F-11D2-836F-0000F87A7782}';
IID_IXTLRuntime: TGUID = '{3EFAA425-272F-11D2-836F-0000F87A7782}';
IID_IXSLTemplate: TGUID = '{2933BF93-7B36-11D2-B20E-00C04F983E60}';
IID_IXSLProcessor: TGUID = '{2933BF92-7B36-11D2-B20E-00C04F983E60}';
IID_ISAXXMLReader: TGUID = '{A4F96ED0-F829-476E-81C0-CDC7BD2A0802}';
IID_ISAXEntityResolver: TGUID = '{99BCA7BD-E8C4-4D5F-A0CF-6D907901FF07}';
IID_ISAXContentHandler: TGUID = '{1545CDFA-9E4E-4497-A8A4-2BF7D0112C44}';
IID_ISAXLocator: TGUID = '{9B7E472A-0DE4-4640-BFF3-84D38A051C31}';
IID_ISAXAttributes: TGUID = '{F078ABE1-45D2-4832-91EA-4466CE2F25C9}';
IID_ISAXDTDHandler: TGUID = '{E15C1BAF-AFB3-4D60-8C36-19A8C45DEFED}';
IID_ISAXErrorHandler: TGUID = '{A60511C4-CCF5-479E-98A3-DC8DC545B7D0}';
IID_ISAXXMLFilter: TGUID = '{70409222-CA09-4475-ACB8-40312FE8D145}';
IID_ISAXLexicalHandler: TGUID = '{7F85D5F5-47A8-4497-BDA5-84BA04819EA6}';
IID_ISAXDeclHandler: TGUID = '{862629AC-771A-47B2-8337-4E6843C1BE90}';
IID_IVBSAXXMLReader: TGUID = '{8C033CAA-6CD6-4F73-B728-4531AF74945F}';
IID_IVBSAXEntityResolver: TGUID = '{0C05D096-F45B-4ACA-AD1A-AA0BC25518DC}';
IID_IVBSAXContentHandler: TGUID = '{2ED7290A-4DD5-4B46-BB26-4E4155E77FAA}';
IID_IVBSAXLocator: TGUID = '{796E7AC5-5AA2-4EFF-ACAD-3FAAF01A3288}';
IID_IVBSAXAttributes: TGUID = '{10DC0586-132B-4CAC-8BB3-DB00AC8B7EE0}';
IID_IVBSAXDTDHandler: TGUID = '{24FB3297-302D-4620-BA39-3A732D850558}';
IID_IVBSAXErrorHandler: TGUID = '{D963D3FE-173C-4862-9095-B92F66995F52}';
IID_IVBSAXXMLFilter: TGUID = '{1299EB1B-5B88-433E-82DE-82CA75AD4E04}';
IID_IVBSAXLexicalHandler: TGUID = '{032AAC35-8C0E-4D9D-979F-E3B702935576}';
IID_IVBSAXDeclHandler: TGUID = '{E8917260-7579-4BE1-B5DD-7AFBFA6F077B}';
IID_IMXWriter: TGUID = '{4D7FF4BA-1565-4EA8-94E1-6E724A46F98D}';
IID_IMXAttributes: TGUID = '{F10D27CC-3EC0-415C-8ED8-77AB1C5E7262}';
IID_IMXReaderControl: TGUID = '{808F4E35-8D5A-4FBE-8466-33A41279ED30}';
IID_IMXSchemaDeclHandler: TGUID = '{FA4BB38C-FAF9-4CCA-9302-D1DD0FE520DB}';
IID_ISchemaItem: TGUID = '{50EA08B3-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaParticle: TGUID = '{50EA08B5-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaElement: TGUID = '{50EA08B7-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchema: TGUID = '{50EA08B4-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaItemCollection: TGUID = '{50EA08B2-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaStringCollection: TGUID = '{50EA08B1-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaType: TGUID = '{50EA08B8-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaComplexType: TGUID = '{50EA08B9-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaAny: TGUID = '{50EA08BC-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaModelGroup: TGUID = '{50EA08BB-DD1B-4664-9A50-C2F40F4BD79A}';
IID_IMXXMLFilter: TGUID = '{C90352F7-643C-4FBC-BB23-E996EB2D51FD}';
IID_IXMLDOMSchemaCollection2: TGUID = '{50EA08B0-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaAttribute: TGUID = '{50EA08B6-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaAttributeGroup: TGUID = '{50EA08BA-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaIdentityConstraint: TGUID = '{50EA08BD-DD1B-4664-9A50-C2F40F4BD79A}';
IID_ISchemaNotation: TGUID = '{50EA08BE-DD1B-4664-9A50-C2F40F4BD79A}';
IID_IXMLDOMSelection: TGUID = '{AA634FC7-5888-44A7-A257-3A47150D3A0E}';
DIID_XMLDOMDocumentEvents: TGUID = '{3EFAA427-272F-11D2-836F-0000F87A7782}';
IID_IDSOControl: TGUID = '{310AFA62-0575-11D2-9CA9-0060B0EC3D39}';
IID_IXMLHTTPRequest: TGUID = '{ED8C108D-4349-11D2-91A4-00C04F7969E8}';
IID_IServerXMLHTTPRequest: TGUID = '{2E9196BF-13BA-4DD4-91CA-6C571F281495}';
IID_IServerXMLHTTPRequest2: TGUID = '{2E01311B-C322-4B0A-BD77-B90CFDC8DCE7}';
IID_IMXNamespacePrefixes: TGUID = '{C90352F4-643C-4FBC-BB23-E996EB2D51FD}';
IID_IVBMXNamespaceManager: TGUID = '{C90352F5-643C-4FBC-BB23-E996EB2D51FD}';
IID_IMXNamespaceManager: TGUID = '{C90352F6-643C-4FBC-BB23-E996EB2D51FD}';
CLASS_DOMDocument: TGUID = '{F6D90F11-9C73-11D3-B32E-00C04F990BB4}';
CLASS_DOMDocument26: TGUID = '{F5078F1B-C551-11D3-89B9-0000F81FE221}';
CLASS_DOMDocument30: TGUID = '{F5078F32-C551-11D3-89B9-0000F81FE221}';
CLASS_DOMDocument40: TGUID = '{88D969C0-F192-11D4-A65F-0040963251E5}';
CLASS_DOMDocument60: TGUID = '{88D96A05-F192-11D4-A65F-0040963251E5}';
CLASS_FreeThreadedDOMDocument: TGUID = '{F6D90F12-9C73-11D3-B32E-00C04F990BB4}';
CLASS_FreeThreadedDOMDocument26: TGUID = '{F5078F1C-C551-11D3-89B9-0000F81FE221}';
CLASS_FreeThreadedDOMDocument30: TGUID = '{F5078F33-C551-11D3-89B9-0000F81FE221}';
CLASS_FreeThreadedDOMDocument40: TGUID = '{88D969C1-F192-11D4-A65F-0040963251E5}';
CLASS_FreeThreadedDOMDocument60: TGUID = '{88D96A06-F192-11D4-A65F-0040963251E5}';
CLASS_XMLSchemaCache: TGUID = '{373984C9-B845-449B-91E7-45AC83036ADE}';
CLASS_XMLSchemaCache26: TGUID = '{F5078F1D-C551-11D3-89B9-0000F81FE221}';
CLASS_XMLSchemaCache30: TGUID = '{F5078F34-C551-11D3-89B9-0000F81FE221}';
CLASS_XMLSchemaCache40: TGUID = '{88D969C2-F192-11D4-A65F-0040963251E5}';
CLASS_XMLSchemaCache60: TGUID = '{88D96A07-F192-11D4-A65F-0040963251E5}';
CLASS_XSLTemplate: TGUID = '{2933BF94-7B36-11D2-B20E-00C04F983E60}';
CLASS_XSLTemplate26: TGUID = '{F5078F21-C551-11D3-89B9-0000F81FE221}';
CLASS_XSLTemplate30: TGUID = '{F5078F36-C551-11D3-89B9-0000F81FE221}';
CLASS_XSLTemplate40: TGUID = '{88D969C3-F192-11D4-A65F-0040963251E5}';
CLASS_XSLTemplate60: TGUID = '{88D96A08-F192-11D4-A65F-0040963251E5}';
CLASS_DSOControl: TGUID = '{F6D90F14-9C73-11D3-B32E-00C04F990BB4}';
CLASS_DSOControl26: TGUID = '{F5078F1F-C551-11D3-89B9-0000F81FE221}';
CLASS_DSOControl30: TGUID = '{F5078F39-C551-11D3-89B9-0000F81FE221}';
CLASS_DSOControl40: TGUID = '{88D969C4-F192-11D4-A65F-0040963251E5}';
CLASS_XMLHTTP: TGUID = '{F6D90F16-9C73-11D3-B32E-00C04F990BB4}';
CLASS_XMLHTTP26: TGUID = '{F5078F1E-C551-11D3-89B9-0000F81FE221}';
CLASS_XMLHTTP30: TGUID = '{F5078F35-C551-11D3-89B9-0000F81FE221}';
CLASS_XMLHTTP40: TGUID = '{88D969C5-F192-11D4-A65F-0040963251E5}';
CLASS_XMLHTTP60: TGUID = '{88D96A0A-F192-11D4-A65F-0040963251E5}';
CLASS_ServerXMLHTTP: TGUID = '{AFBA6B42-5692-48EA-8141-DC517DCF0EF1}';
CLASS_ServerXMLHTTP30: TGUID = '{AFB40FFD-B609-40A3-9828-F88BBE11E4E3}';
CLASS_ServerXMLHTTP40: TGUID = '{88D969C6-F192-11D4-A65F-0040963251E5}';
CLASS_ServerXMLHTTP60: TGUID = '{88D96A0B-F192-11D4-A65F-0040963251E5}';
CLASS_SAXXMLReader: TGUID = '{079AA557-4A18-424A-8EEE-E39F0A8D41B9}';
CLASS_SAXXMLReader30: TGUID = '{3124C396-FB13-4836-A6AD-1317F1713688}';
CLASS_SAXXMLReader40: TGUID = '{7C6E29BC-8B8B-4C3D-859E-AF6CD158BE0F}';
CLASS_SAXXMLReader60: TGUID = '{88D96A0C-F192-11D4-A65F-0040963251E5}';
CLASS_MXXMLWriter: TGUID = '{FC220AD8-A72A-4EE8-926E-0B7AD152A020}';
CLASS_MXXMLWriter30: TGUID = '{3D813DFE-6C91-4A4E-8F41-04346A841D9C}';
CLASS_MXXMLWriter40: TGUID = '{88D969C8-F192-11D4-A65F-0040963251E5}';
CLASS_MXXMLWriter60: TGUID = '{88D96A0F-F192-11D4-A65F-0040963251E5}';
CLASS_MXHTMLWriter: TGUID = '{A4C23EC3-6B70-4466-9127-550077239978}';
CLASS_MXHTMLWriter30: TGUID = '{853D1540-C1A7-4AA9-A226-4D3BD301146D}';
CLASS_MXHTMLWriter40: TGUID = '{88D969C9-F192-11D4-A65F-0040963251E5}';
CLASS_MXHTMLWriter60: TGUID = '{88D96A10-F192-11D4-A65F-0040963251E5}';
CLASS_SAXAttributes: TGUID = '{4DD441AD-526D-4A77-9F1B-9841ED802FB0}';
CLASS_SAXAttributes30: TGUID = '{3E784A01-F3AE-4DC0-9354-9526B9370EBA}';
CLASS_SAXAttributes40: TGUID = '{88D969CA-F192-11D4-A65F-0040963251E5}';
CLASS_SAXAttributes60: TGUID = '{88D96A0E-F192-11D4-A65F-0040963251E5}';
CLASS_MXNamespaceManager: TGUID = '{88D969D5-F192-11D4-A65F-0040963251E5}';
CLASS_MXNamespaceManager40: TGUID = '{88D969D6-F192-11D4-A65F-0040963251E5}';
CLASS_MXNamespaceManager60: TGUID = '{88D96A11-F192-11D4-A65F-0040963251E5}';
// *********************************************************************//
// Declaration of Enumerations defined in Type Library
// *********************************************************************//
// Constants for enum tagDOMNodeType
type
tagDOMNodeType = Winapi.MSXMLIntf.tagDOMNodeType;
{$EXTERNALSYM tagDOMNodeType}
const
NODE_INVALID = $00000000;
{$EXTERNALSYM NODE_INVALID}
NODE_ELEMENT = $00000001;
{$EXTERNALSYM NODE_ELEMENT}
NODE_ATTRIBUTE = $00000002;
{$EXTERNALSYM NODE_ATTRIBUTE}
NODE_TEXT = $00000003;
{$EXTERNALSYM NODE_TEXT}
NODE_CDATA_SECTION = $00000004;
{$EXTERNALSYM NODE_CDATA_SECTION}
NODE_ENTITY_REFERENCE = $00000005;
{$EXTERNALSYM NODE_ENTITY_REFERENCE}
NODE_ENTITY = $00000006;
{$EXTERNALSYM NODE_ENTITY}
NODE_PROCESSING_INSTRUCTION = $00000007;
{$EXTERNALSYM NODE_PROCESSING_INSTRUCTION}
NODE_COMMENT = $00000008;
{$EXTERNALSYM NODE_COMMENT}
NODE_DOCUMENT = $00000009;
{$EXTERNALSYM NODE_DOCUMENT}
NODE_DOCUMENT_TYPE = $0000000A;
{$EXTERNALSYM NODE_DOCUMENT_TYPE}
NODE_DOCUMENT_FRAGMENT = $0000000B;
{$EXTERNALSYM NODE_DOCUMENT_FRAGMENT}
NODE_NOTATION = $0000000C;
{$EXTERNALSYM NODE_NOTATION}
// Constants for enum _SOMITEMTYPE
type
_SOMITEMTYPE = Winapi.MSXMLIntf._SOMITEMTYPE;
{$EXTERNALSYM _SOMITEMTYPE}
const
SOMITEM_SCHEMA = $00001000;
{$EXTERNALSYM SOMITEM_SCHEMA}
SOMITEM_ATTRIBUTE = $00001001;
{$EXTERNALSYM SOMITEM_ATTRIBUTE}
SOMITEM_ATTRIBUTEGROUP = $00001002;
{$EXTERNALSYM SOMITEM_ATTRIBUTEGROUP}
SOMITEM_NOTATION = $00001003;
{$EXTERNALSYM SOMITEM_NOTATION}
SOMITEM_ANNOTATION = $00001004;
{$EXTERNALSYM SOMITEM_ANNOTATION}
SOMITEM_IDENTITYCONSTRAINT = $00001100;
{$EXTERNALSYM SOMITEM_IDENTITYCONSTRAINT}
SOMITEM_KEY = $00001101;
{$EXTERNALSYM SOMITEM_KEY}
SOMITEM_KEYREF = $00001102;
{$EXTERNALSYM SOMITEM_KEYREF}
SOMITEM_UNIQUE = $00001103;
{$EXTERNALSYM SOMITEM_UNIQUE}
SOMITEM_ANYTYPE = $00002000;
{$EXTERNALSYM SOMITEM_ANYTYPE}
SOMITEM_DATATYPE = $00002100;
{$EXTERNALSYM SOMITEM_DATATYPE}
SOMITEM_DATATYPE_ANYTYPE = $00002101;
{$EXTERNALSYM SOMITEM_DATATYPE_ANYTYPE}
SOMITEM_DATATYPE_ANYURI = $00002102;
{$EXTERNALSYM SOMITEM_DATATYPE_ANYURI}
SOMITEM_DATATYPE_BASE64BINARY = $00002103;
{$EXTERNALSYM SOMITEM_DATATYPE_BASE64BINARY}
SOMITEM_DATATYPE_BOOLEAN = $00002104;
{$EXTERNALSYM SOMITEM_DATATYPE_BOOLEAN}
SOMITEM_DATATYPE_BYTE = $00002105;
{$EXTERNALSYM SOMITEM_DATATYPE_BYTE}
SOMITEM_DATATYPE_DATE = $00002106;
{$EXTERNALSYM SOMITEM_DATATYPE_DATE}
SOMITEM_DATATYPE_DATETIME = $00002107;
{$EXTERNALSYM SOMITEM_DATATYPE_DATETIME}
SOMITEM_DATATYPE_DAY = $00002108;
{$EXTERNALSYM SOMITEM_DATATYPE_DAY}
SOMITEM_DATATYPE_DECIMAL = $00002109;
{$EXTERNALSYM SOMITEM_DATATYPE_DECIMAL}
SOMITEM_DATATYPE_DOUBLE = $0000210A;
{$EXTERNALSYM SOMITEM_DATATYPE_DOUBLE}
SOMITEM_DATATYPE_DURATION = $0000210B;
{$EXTERNALSYM SOMITEM_DATATYPE_DURATION}
SOMITEM_DATATYPE_ENTITIES = $0000210C;
{$EXTERNALSYM SOMITEM_DATATYPE_ENTITIES}
SOMITEM_DATATYPE_ENTITY = $0000210D;
{$EXTERNALSYM SOMITEM_DATATYPE_ENTITY}
SOMITEM_DATATYPE_FLOAT = $0000210E;
{$EXTERNALSYM SOMITEM_DATATYPE_FLOAT}
SOMITEM_DATATYPE_HEXBINARY = $0000210F;
{$EXTERNALSYM SOMITEM_DATATYPE_HEXBINARY}
SOMITEM_DATATYPE_ID = $00002110;
{$EXTERNALSYM SOMITEM_DATATYPE_ID}
SOMITEM_DATATYPE_IDREF = $00002111;
{$EXTERNALSYM SOMITEM_DATATYPE_IDREF}
SOMITEM_DATATYPE_IDREFS = $00002112;
{$EXTERNALSYM SOMITEM_DATATYPE_IDREFS}
SOMITEM_DATATYPE_INT = $00002113;
{$EXTERNALSYM SOMITEM_DATATYPE_INT}
SOMITEM_DATATYPE_INTEGER = $00002114;
{$EXTERNALSYM SOMITEM_DATATYPE_INTEGER}
SOMITEM_DATATYPE_LANGUAGE = $00002115;
{$EXTERNALSYM SOMITEM_DATATYPE_LANGUAGE}
SOMITEM_DATATYPE_LONG = $00002116;
{$EXTERNALSYM SOMITEM_DATATYPE_LONG}
SOMITEM_DATATYPE_MONTH = $00002117;
{$EXTERNALSYM SOMITEM_DATATYPE_MONTH}
SOMITEM_DATATYPE_MONTHDAY = $00002118;
{$EXTERNALSYM SOMITEM_DATATYPE_MONTHDAY}
SOMITEM_DATATYPE_NAME = $00002119;
{$EXTERNALSYM SOMITEM_DATATYPE_NAME}
SOMITEM_DATATYPE_NCNAME = $0000211A;
{$EXTERNALSYM SOMITEM_DATATYPE_NCNAME}
SOMITEM_DATATYPE_NEGATIVEINTEGER = $0000211B;
{$EXTERNALSYM SOMITEM_DATATYPE_NEGATIVEINTEGER}
SOMITEM_DATATYPE_NMTOKEN = $0000211C;
{$EXTERNALSYM SOMITEM_DATATYPE_NMTOKEN}
SOMITEM_DATATYPE_NMTOKENS = $0000211D;
{$EXTERNALSYM SOMITEM_DATATYPE_NMTOKENS}
SOMITEM_DATATYPE_NONNEGATIVEINTEGER = $0000211E;
{$EXTERNALSYM SOMITEM_DATATYPE_NONNEGATIVEINTEGER}
SOMITEM_DATATYPE_NONPOSITIVEINTEGER = $0000211F;
{$EXTERNALSYM SOMITEM_DATATYPE_NONPOSITIVEINTEGER}
SOMITEM_DATATYPE_NORMALIZEDSTRING = $00002120;
{$EXTERNALSYM SOMITEM_DATATYPE_NORMALIZEDSTRING}
SOMITEM_DATATYPE_NOTATION = $00002121;
{$EXTERNALSYM SOMITEM_DATATYPE_NOTATION}
SOMITEM_DATATYPE_POSITIVEINTEGER = $00002122;
{$EXTERNALSYM SOMITEM_DATATYPE_POSITIVEINTEGER}
SOMITEM_DATATYPE_QNAME = $00002123;
{$EXTERNALSYM SOMITEM_DATATYPE_QNAME}
SOMITEM_DATATYPE_SHORT = $00002124;
{$EXTERNALSYM SOMITEM_DATATYPE_SHORT}
SOMITEM_DATATYPE_STRING = $00002125;
{$EXTERNALSYM SOMITEM_DATATYPE_STRING}
SOMITEM_DATATYPE_TIME = $00002126;
{$EXTERNALSYM SOMITEM_DATATYPE_TIME}
SOMITEM_DATATYPE_TOKEN = $00002127;
{$EXTERNALSYM SOMITEM_DATATYPE_TOKEN}
SOMITEM_DATATYPE_UNSIGNEDBYTE = $00002128;
{$EXTERNALSYM SOMITEM_DATATYPE_UNSIGNEDBYTE}
SOMITEM_DATATYPE_UNSIGNEDINT = $00002129;
{$EXTERNALSYM SOMITEM_DATATYPE_UNSIGNEDINT}
SOMITEM_DATATYPE_UNSIGNEDLONG = $0000212A;
{$EXTERNALSYM SOMITEM_DATATYPE_UNSIGNEDLONG}
SOMITEM_DATATYPE_UNSIGNEDSHORT = $0000212B;
{$EXTERNALSYM SOMITEM_DATATYPE_UNSIGNEDSHORT}
SOMITEM_DATATYPE_YEAR = $0000212C;
{$EXTERNALSYM SOMITEM_DATATYPE_YEAR}
SOMITEM_DATATYPE_YEARMONTH = $0000212D;
{$EXTERNALSYM SOMITEM_DATATYPE_YEARMONTH}
SOMITEM_DATATYPE_ANYSIMPLETYPE = $000021FF;
{$EXTERNALSYM SOMITEM_DATATYPE_ANYSIMPLETYPE}
SOMITEM_SIMPLETYPE = $00002200;
{$EXTERNALSYM SOMITEM_SIMPLETYPE}
SOMITEM_COMPLEXTYPE = $00002400;
{$EXTERNALSYM SOMITEM_COMPLEXTYPE}
SOMITEM_PARTICLE = $00004000;
{$EXTERNALSYM SOMITEM_PARTICLE}
SOMITEM_ANY = $00004001;
{$EXTERNALSYM SOMITEM_ANY}
SOMITEM_ANYATTRIBUTE = $00004002;
{$EXTERNALSYM SOMITEM_ANYATTRIBUTE}
SOMITEM_ELEMENT = $00004003;
{$EXTERNALSYM SOMITEM_ELEMENT}
SOMITEM_GROUP = $00004100;
{$EXTERNALSYM SOMITEM_GROUP}
SOMITEM_ALL = $00004101;
{$EXTERNALSYM SOMITEM_ALL}
SOMITEM_CHOICE = $00004102;
{$EXTERNALSYM SOMITEM_CHOICE}
SOMITEM_SEQUENCE = $00004103;
{$EXTERNALSYM SOMITEM_SEQUENCE}
SOMITEM_EMPTYPARTICLE = $00004104;
{$EXTERNALSYM SOMITEM_EMPTYPARTICLE}
SOMITEM_NULL = $00000800;
{$EXTERNALSYM SOMITEM_NULL}
SOMITEM_NULL_TYPE = $00002800;
{$EXTERNALSYM SOMITEM_NULL_TYPE}
SOMITEM_NULL_ANY = $00004801;
{$EXTERNALSYM SOMITEM_NULL_ANY}
SOMITEM_NULL_ANYATTRIBUTE = $00004802;
{$EXTERNALSYM SOMITEM_NULL_ANYATTRIBUTE}
SOMITEM_NULL_ELEMENT = $00004803;
{$EXTERNALSYM SOMITEM_NULL_ELEMENT}
// Constants for enum _SCHEMADERIVATIONMETHOD
type
_SCHEMADERIVATIONMETHOD = Winapi.MSXMLIntf._SCHEMADERIVATIONMETHOD;
{$EXTERNALSYM _SCHEMADERIVATIONMETHOD}
const
SCHEMADERIVATIONMETHOD_EMPTY = $00000000;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_EMPTY}
SCHEMADERIVATIONMETHOD_SUBSTITUTION = $00000001;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_SUBSTITUTION}
SCHEMADERIVATIONMETHOD_EXTENSION = $00000002;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_EXTENSION}
SCHEMADERIVATIONMETHOD_RESTRICTION = $00000004;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_RESTRICTION}
SCHEMADERIVATIONMETHOD_LIST = $00000008;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_LIST}
SCHEMADERIVATIONMETHOD_UNION = $00000010;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_UNION}
SCHEMADERIVATIONMETHOD_ALL = $000000FF;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_ALL}
SCHEMADERIVATIONMETHOD_NONE = $00000100;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD_NONE}
// Constants for enum _SCHEMATYPEVARIETY
type
_SCHEMATYPEVARIETY = Winapi.MSXMLIntf._SCHEMATYPEVARIETY;
{$EXTERNALSYM _SCHEMATYPEVARIETY}
const
SCHEMATYPEVARIETY_NONE = $FFFFFFFF;
{$EXTERNALSYM SCHEMATYPEVARIETY_NONE}
SCHEMATYPEVARIETY_ATOMIC = $00000000;
{$EXTERNALSYM SCHEMATYPEVARIETY_ATOMIC}
SCHEMATYPEVARIETY_LIST = $00000001;
{$EXTERNALSYM SCHEMATYPEVARIETY_LIST}
SCHEMATYPEVARIETY_UNION = $00000002;
{$EXTERNALSYM SCHEMATYPEVARIETY_UNION}
// Constants for enum _SCHEMAWHITESPACE
type
_SCHEMAWHITESPACE = Winapi.MSXMLIntf._SCHEMAWHITESPACE;
{$EXTERNALSYM _SCHEMAWHITESPACE}
const
SCHEMAWHITESPACE_NONE = $FFFFFFFF;
{$EXTERNALSYM SCHEMAWHITESPACE_NONE}
SCHEMAWHITESPACE_PRESERVE = $00000000;
{$EXTERNALSYM SCHEMAWHITESPACE_PRESERVE}
SCHEMAWHITESPACE_REPLACE = $00000001;
{$EXTERNALSYM SCHEMAWHITESPACE_REPLACE}
SCHEMAWHITESPACE_COLLAPSE = $00000002;
{$EXTERNALSYM SCHEMAWHITESPACE_COLLAPSE}
// Constants for enum _SCHEMAPROCESSCONTENTS
type
_SCHEMAPROCESSCONTENTS = Winapi.MSXMLIntf._SCHEMAPROCESSCONTENTS;
{$EXTERNALSYM _SCHEMAPROCESSCONTENTS}
const
SCHEMAPROCESSCONTENTS_NONE = $00000000;
{$EXTERNALSYM SCHEMAPROCESSCONTENTS_NONE}
SCHEMAPROCESSCONTENTS_SKIP = $00000001;
{$EXTERNALSYM SCHEMAPROCESSCONTENTS_SKIP}
SCHEMAPROCESSCONTENTS_LAX = $00000002;
{$EXTERNALSYM SCHEMAPROCESSCONTENTS_LAX}
SCHEMAPROCESSCONTENTS_STRICT = $00000003;
{$EXTERNALSYM SCHEMAPROCESSCONTENTS_STRICT}
// Constants for enum _SCHEMACONTENTTYPE
type
_SCHEMACONTENTTYPE = Winapi.MSXMLIntf._SCHEMACONTENTTYPE;
{$EXTERNALSYM _SCHEMACONTENTTYPE}
const
SCHEMACONTENTTYPE_EMPTY = $00000000;
{$EXTERNALSYM SCHEMACONTENTTYPE_EMPTY}
SCHEMACONTENTTYPE_TEXTONLY = $00000001;
{$EXTERNALSYM SCHEMACONTENTTYPE_TEXTONLY}
SCHEMACONTENTTYPE_ELEMENTONLY = $00000002;
{$EXTERNALSYM SCHEMACONTENTTYPE_ELEMENTONLY}
SCHEMACONTENTTYPE_MIXED = $00000003;
{$EXTERNALSYM SCHEMACONTENTTYPE_MIXED}
// Constants for enum _SCHEMAUSE
type
_SCHEMAUSE = Winapi.MSXMLIntf._SCHEMAUSE;
{$EXTERNALSYM _SCHEMAUSE}
const
SCHEMAUSE_OPTIONAL = $00000000;
{$EXTERNALSYM SCHEMAUSE_OPTIONAL}
SCHEMAUSE_PROHIBITED = $00000001;
{$EXTERNALSYM SCHEMAUSE_PROHIBITED}
SCHEMAUSE_REQUIRED = $00000002;
{$EXTERNALSYM SCHEMAUSE_REQUIRED}
// Constants for enum _SERVERXMLHTTP_OPTION
type
_SERVERXMLHTTP_OPTION = Winapi.MSXMLIntf._SERVERXMLHTTP_OPTION;
{$EXTERNALSYM _SERVERXMLHTTP_OPTION}
const
SXH_OPTION_URL = $FFFFFFFF;
{$EXTERNALSYM SXH_OPTION_URL}
SXH_OPTION_URL_CODEPAGE = $00000000;
{$EXTERNALSYM SXH_OPTION_URL_CODEPAGE}
SXH_OPTION_ESCAPE_PERCENT_IN_URL = $00000001;
{$EXTERNALSYM SXH_OPTION_ESCAPE_PERCENT_IN_URL}
SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS = $00000002;
{$EXTERNALSYM SXH_OPTION_IGNORE_SERVER_SSL_CERT_ERROR_FLAGS}
SXH_OPTION_SELECT_CLIENT_SSL_CERT = $00000003;
{$EXTERNALSYM SXH_OPTION_SELECT_CLIENT_SSL_CERT}
// Constants for enum _SXH_SERVER_CERT_OPTION
type
_SXH_SERVER_CERT_OPTION = TOleEnum;
{$EXTERNALSYM _SXH_SERVER_CERT_OPTION}
const
SXH_SERVER_CERT_IGNORE_UNKNOWN_CA = $00000100;
{$EXTERNALSYM SXH_SERVER_CERT_IGNORE_UNKNOWN_CA}
SXH_SERVER_CERT_IGNORE_WRONG_USAGE = $00000200;
{$EXTERNALSYM SXH_SERVER_CERT_IGNORE_WRONG_USAGE}
SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID = $00001000;
{$EXTERNALSYM SXH_SERVER_CERT_IGNORE_CERT_CN_INVALID}
SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID = $00002000;
{$EXTERNALSYM SXH_SERVER_CERT_IGNORE_CERT_DATE_INVALID}
SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = $00003300;
{$EXTERNALSYM SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS}
// Constants for enum _SXH_PROXY_SETTING
type
_SXH_PROXY_SETTING = Winapi.MSXMLIntf._SXH_PROXY_SETTING;
{$EXTERNALSYM _SXH_PROXY_SETTING}
const
SXH_PROXY_SET_DEFAULT = $00000000;
{$EXTERNALSYM SXH_PROXY_SET_DEFAULT}
SXH_PROXY_SET_PRECONFIG = $00000000;
{$EXTERNALSYM SXH_PROXY_SET_PRECONFIG}
SXH_PROXY_SET_DIRECT = $00000001;
{$EXTERNALSYM SXH_PROXY_SET_DIRECT}
SXH_PROXY_SET_PROXY = $00000002;
{$EXTERNALSYM SXH_PROXY_SET_PROXY}
type
// *********************************************************************//
// Forward declaration of types defined in TypeLibrary
// *********************************************************************//
IXMLDOMImplementation = Winapi.MSXMLIntf.IXMLDOMImplementation;
{$EXTERNALSYM IXMLDOMImplementation}
IXMLDOMImplementationDisp = Winapi.MSXMLIntf.IXMLDOMImplementationDisp;
{$EXTERNALSYM IXMLDOMImplementationDisp}
IXMLDOMNode = Winapi.MSXMLIntf.IXMLDOMNode;
{$EXTERNALSYM IXMLDOMNode}
IXMLDOMNodeDisp = Winapi.MSXMLIntf.IXMLDOMNodeDisp;
{$EXTERNALSYM IXMLDOMNodeDisp}
IXMLDOMNodeList = Winapi.MSXMLIntf.IXMLDOMNodeList;
{$EXTERNALSYM IXMLDOMNodeList}
IXMLDOMNodeListDisp = Winapi.MSXMLIntf.IXMLDOMNodeListDisp;
{$EXTERNALSYM IXMLDOMNodeListDisp}
IXMLDOMNamedNodeMap = Winapi.MSXMLIntf.IXMLDOMNamedNodeMap;
{$EXTERNALSYM IXMLDOMNamedNodeMap}
IXMLDOMNamedNodeMapDisp = Winapi.MSXMLIntf.IXMLDOMNamedNodeMapDisp;
{$EXTERNALSYM IXMLDOMNamedNodeMapDisp}
IXMLDOMDocument = Winapi.MSXMLIntf.IXMLDOMDocument;
{$EXTERNALSYM IXMLDOMDocument}
IXMLDOMDocumentDisp = Winapi.MSXMLIntf.IXMLDOMDocumentDisp;
{$EXTERNALSYM IXMLDOMDocumentDisp}
IXMLDOMDocumentType = Winapi.MSXMLIntf.IXMLDOMDocumentType;
{$EXTERNALSYM IXMLDOMDocumentType}
IXMLDOMDocumentTypeDisp = Winapi.MSXMLIntf.IXMLDOMDocumentTypeDisp;
{$EXTERNALSYM IXMLDOMDocumentTypeDisp}
IXMLDOMElement = Winapi.MSXMLIntf.IXMLDOMElement;
{$EXTERNALSYM IXMLDOMElement}
IXMLDOMElementDisp = Winapi.MSXMLIntf.IXMLDOMElementDisp;
{$EXTERNALSYM IXMLDOMElementDisp}
IXMLDOMAttribute = Winapi.MSXMLIntf.IXMLDOMAttribute;
{$EXTERNALSYM IXMLDOMAttribute}
IXMLDOMAttributeDisp = Winapi.MSXMLIntf.IXMLDOMAttributeDisp;
{$EXTERNALSYM IXMLDOMAttributeDisp}
IXMLDOMDocumentFragment = Winapi.MSXMLIntf.IXMLDOMDocumentFragment;
{$EXTERNALSYM IXMLDOMDocumentFragment}
IXMLDOMDocumentFragmentDisp = Winapi.MSXMLIntf.IXMLDOMDocumentFragmentDisp;
{$EXTERNALSYM IXMLDOMDocumentFragmentDisp}
IXMLDOMCharacterData = Winapi.MSXMLIntf.IXMLDOMCharacterData;
{$EXTERNALSYM IXMLDOMCharacterData}
IXMLDOMCharacterDataDisp = Winapi.MSXMLIntf.IXMLDOMCharacterDataDisp;
{$EXTERNALSYM IXMLDOMCharacterDataDisp}
IXMLDOMText = Winapi.MSXMLIntf.IXMLDOMText;
{$EXTERNALSYM IXMLDOMText}
IXMLDOMTextDisp = Winapi.MSXMLIntf.IXMLDOMTextDisp;
{$EXTERNALSYM IXMLDOMTextDisp}
IXMLDOMComment = Winapi.MSXMLIntf.IXMLDOMComment;
{$EXTERNALSYM IXMLDOMComment}
IXMLDOMCommentDisp = Winapi.MSXMLIntf.IXMLDOMCommentDisp;
{$EXTERNALSYM IXMLDOMCommentDisp}
IXMLDOMCDATASection = Winapi.MSXMLIntf.IXMLDOMCDATASection;
{$EXTERNALSYM IXMLDOMCDATASection}
IXMLDOMCDATASectionDisp = Winapi.MSXMLIntf.IXMLDOMCDATASectionDisp;
{$EXTERNALSYM IXMLDOMCDATASectionDisp}
IXMLDOMProcessingInstruction = Winapi.MSXMLIntf.IXMLDOMProcessingInstruction;
{$EXTERNALSYM IXMLDOMProcessingInstruction}
IXMLDOMProcessingInstructionDisp = Winapi.MSXMLIntf.IXMLDOMProcessingInstructionDisp;
{$EXTERNALSYM IXMLDOMProcessingInstructionDisp}
IXMLDOMEntityReference = Winapi.MSXMLIntf.IXMLDOMEntityReference;
{$EXTERNALSYM IXMLDOMEntityReference}
IXMLDOMEntityReferenceDisp = Winapi.MSXMLIntf.IXMLDOMEntityReferenceDisp;
{$EXTERNALSYM IXMLDOMEntityReferenceDisp}
IXMLDOMParseError = Winapi.MSXMLIntf.IXMLDOMParseError;
{$EXTERNALSYM IXMLDOMParseError}
IXMLDOMParseErrorDisp = Winapi.MSXMLIntf.IXMLDOMParseErrorDisp;
{$EXTERNALSYM IXMLDOMParseErrorDisp}
IXMLDOMDocument2 = Winapi.MSXMLIntf.IXMLDOMDocument2;
{$EXTERNALSYM IXMLDOMDocument2}
IXMLDOMDocument2Disp = Winapi.MSXMLIntf.IXMLDOMDocument2Disp;
{$EXTERNALSYM IXMLDOMDocument2Disp}
IXMLDOMSchemaCollection = Winapi.MSXMLIntf.IXMLDOMSchemaCollection;
{$EXTERNALSYM IXMLDOMSchemaCollection}
IXMLDOMSchemaCollectionDisp = Winapi.MSXMLIntf.IXMLDOMSchemaCollectionDisp;
{$EXTERNALSYM IXMLDOMSchemaCollectionDisp}
IXMLDOMDocument3 = Winapi.MSXMLIntf.IXMLDOMDocument3;
{$EXTERNALSYM IXMLDOMDocument3}
IXMLDOMDocument3Disp = Winapi.MSXMLIntf.IXMLDOMDocument3Disp;
{$EXTERNALSYM IXMLDOMDocument3Disp}
IXMLDOMNotation = Winapi.MSXMLIntf.IXMLDOMNotation;
{$EXTERNALSYM IXMLDOMNotation}
IXMLDOMNotationDisp = Winapi.MSXMLIntf.IXMLDOMNotationDisp;
{$EXTERNALSYM IXMLDOMNotationDisp}
IXMLDOMEntity = Winapi.MSXMLIntf.IXMLDOMEntity;
{$EXTERNALSYM IXMLDOMEntity}
IXMLDOMEntityDisp = Winapi.MSXMLIntf.IXMLDOMEntityDisp;
{$EXTERNALSYM IXMLDOMEntityDisp}
IXMLDOMParseError2 = Winapi.MSXMLIntf.IXMLDOMParseError2;
{$EXTERNALSYM IXMLDOMParseError2}
IXMLDOMParseError2Disp = Winapi.MSXMLIntf.IXMLDOMParseError2Disp;
{$EXTERNALSYM IXMLDOMParseError2Disp}
IXMLDOMParseErrorCollection = Winapi.MSXMLIntf.IXMLDOMParseErrorCollection;
{$EXTERNALSYM IXMLDOMParseErrorCollection}
IXMLDOMParseErrorCollectionDisp = Winapi.MSXMLIntf.IXMLDOMParseErrorCollectionDisp;
{$EXTERNALSYM IXMLDOMParseErrorCollectionDisp}
IXTLRuntime = Winapi.MSXMLIntf.IXTLRuntime;
{$EXTERNALSYM IXTLRuntime}
IXTLRuntimeDisp = Winapi.MSXMLIntf.IXTLRuntimeDisp;
{$EXTERNALSYM IXTLRuntimeDisp}
IXSLTemplate = Winapi.MSXMLIntf.IXSLTemplate;
{$EXTERNALSYM IXSLTemplate}
IXSLTemplateDisp = Winapi.MSXMLIntf.IXSLTemplateDisp;
{$EXTERNALSYM IXSLTemplateDisp}
IXSLProcessor = Winapi.MSXMLIntf.IXSLProcessor;
{$EXTERNALSYM IXSLProcessor}
IXSLProcessorDisp = Winapi.MSXMLIntf.IXSLProcessorDisp;
{$EXTERNALSYM IXSLProcessorDisp}
ISAXXMLReader = Winapi.MSXMLIntf.ISAXXMLReader;
{$EXTERNALSYM ISAXXMLReader}
ISAXEntityResolver = Winapi.MSXMLIntf.ISAXEntityResolver;
{$EXTERNALSYM ISAXEntityResolver}
ISAXContentHandler = Winapi.MSXMLIntf.ISAXContentHandler;
{$EXTERNALSYM ISAXContentHandler}
ISAXLocator = Winapi.MSXMLIntf.ISAXLocator;
{$EXTERNALSYM ISAXLocator}
ISAXAttributes = Winapi.MSXMLIntf.ISAXAttributes;
{$EXTERNALSYM ISAXAttributes}
ISAXDTDHandler = Winapi.MSXMLIntf.ISAXDTDHandler;
{$EXTERNALSYM ISAXDTDHandler}
ISAXErrorHandler = Winapi.MSXMLIntf.ISAXErrorHandler;
{$EXTERNALSYM ISAXErrorHandler}
ISAXXMLFilter = Winapi.MSXMLIntf.ISAXXMLFilter;
{$EXTERNALSYM ISAXXMLFilter}
ISAXLexicalHandler = Winapi.MSXMLIntf.ISAXLexicalHandler;
{$EXTERNALSYM ISAXLexicalHandler}
ISAXDeclHandler = Winapi.MSXMLIntf.ISAXDeclHandler;
{$EXTERNALSYM ISAXDeclHandler}
IVBSAXXMLReader = Winapi.MSXMLIntf.IVBSAXXMLReader;
{$EXTERNALSYM IVBSAXXMLReader}
IVBSAXXMLReaderDisp = Winapi.MSXMLIntf.IVBSAXXMLReaderDisp;
{$EXTERNALSYM IVBSAXXMLReaderDisp}
IVBSAXEntityResolver = Winapi.MSXMLIntf.IVBSAXEntityResolver;
{$EXTERNALSYM IVBSAXEntityResolver}
IVBSAXEntityResolverDisp = Winapi.MSXMLIntf.IVBSAXEntityResolverDisp;
{$EXTERNALSYM IVBSAXEntityResolverDisp}
IVBSAXContentHandler = Winapi.MSXMLIntf.IVBSAXContentHandler;
{$EXTERNALSYM IVBSAXContentHandler}
IVBSAXContentHandlerDisp = Winapi.MSXMLIntf.IVBSAXContentHandlerDisp;
{$EXTERNALSYM IVBSAXContentHandlerDisp}
IVBSAXLocator = Winapi.MSXMLIntf.IVBSAXLocator;
{$EXTERNALSYM IVBSAXLocator}
IVBSAXLocatorDisp = Winapi.MSXMLIntf.IVBSAXLocatorDisp;
{$EXTERNALSYM IVBSAXLocatorDisp}
IVBSAXAttributes = Winapi.MSXMLIntf.IVBSAXAttributes;
{$EXTERNALSYM IVBSAXAttributes}
IVBSAXAttributesDisp = Winapi.MSXMLIntf.IVBSAXAttributesDisp;
{$EXTERNALSYM IVBSAXAttributesDisp}
IVBSAXDTDHandler = Winapi.MSXMLIntf.IVBSAXDTDHandler;
{$EXTERNALSYM IVBSAXDTDHandler}
IVBSAXDTDHandlerDisp = Winapi.MSXMLIntf.IVBSAXDTDHandlerDisp;
{$EXTERNALSYM IVBSAXDTDHandlerDisp}
IVBSAXErrorHandler = Winapi.MSXMLIntf.IVBSAXErrorHandler;
{$EXTERNALSYM IVBSAXErrorHandler}
IVBSAXErrorHandlerDisp = Winapi.MSXMLIntf.IVBSAXErrorHandlerDisp;
{$EXTERNALSYM IVBSAXErrorHandlerDisp}
IVBSAXXMLFilter = Winapi.MSXMLIntf.IVBSAXXMLFilter;
{$EXTERNALSYM IVBSAXXMLFilter}
IVBSAXXMLFilterDisp = Winapi.MSXMLIntf.IVBSAXXMLFilterDisp;
{$EXTERNALSYM IVBSAXXMLFilterDisp}
IVBSAXLexicalHandler = Winapi.MSXMLIntf.IVBSAXLexicalHandler;
{$EXTERNALSYM IVBSAXLexicalHandler}
IVBSAXLexicalHandlerDisp = Winapi.MSXMLIntf.IVBSAXLexicalHandlerDisp;
{$EXTERNALSYM IVBSAXLexicalHandlerDisp}
IVBSAXDeclHandler = Winapi.MSXMLIntf.IVBSAXDeclHandler;
{$EXTERNALSYM IVBSAXDeclHandler}
IVBSAXDeclHandlerDisp = Winapi.MSXMLIntf.IVBSAXDeclHandlerDisp;
{$EXTERNALSYM IVBSAXDeclHandlerDisp}
IMXWriter = Winapi.MSXMLIntf.IMXWriter;
{$EXTERNALSYM IMXWriter}
IMXWriterDisp = Winapi.MSXMLIntf.IMXWriterDisp;
{$EXTERNALSYM IMXWriterDisp}
IMXAttributes = Winapi.MSXMLIntf.IMXAttributes;
{$EXTERNALSYM IMXAttributes}
IMXAttributesDisp = Winapi.MSXMLIntf.IMXAttributesDisp;
{$EXTERNALSYM IMXAttributesDisp}
IMXReaderControl = Winapi.MSXMLIntf.IMXReaderControl;
{$EXTERNALSYM IMXReaderControl}
IMXReaderControlDisp = Winapi.MSXMLIntf.IMXReaderControlDisp;
{$EXTERNALSYM IMXReaderControlDisp}
IMXSchemaDeclHandler = Winapi.MSXMLIntf.IMXSchemaDeclHandler;
{$EXTERNALSYM IMXSchemaDeclHandler}
IMXSchemaDeclHandlerDisp = Winapi.MSXMLIntf.IMXSchemaDeclHandlerDisp;
{$EXTERNALSYM IMXSchemaDeclHandlerDisp}
ISchemaItem = Winapi.MSXMLIntf.ISchemaItem;
{$EXTERNALSYM ISchemaItem}
ISchemaItemDisp = Winapi.MSXMLIntf.ISchemaItemDisp;
{$EXTERNALSYM ISchemaItemDisp}
ISchemaParticle = Winapi.MSXMLIntf.ISchemaParticle;
{$EXTERNALSYM ISchemaParticle}
ISchemaParticleDisp = Winapi.MSXMLIntf.ISchemaParticleDisp;
{$EXTERNALSYM ISchemaParticleDisp}
ISchemaElement = Winapi.MSXMLIntf.ISchemaElement;
{$EXTERNALSYM ISchemaElement}
ISchemaElementDisp = Winapi.MSXMLIntf.ISchemaElementDisp;
{$EXTERNALSYM ISchemaElementDisp}
ISchema = Winapi.MSXMLIntf.ISchema;
{$EXTERNALSYM ISchema}
ISchemaDisp = Winapi.MSXMLIntf.ISchemaDisp;
{$EXTERNALSYM ISchemaDisp}
ISchemaItemCollection = Winapi.MSXMLIntf.ISchemaItemCollection;
{$EXTERNALSYM ISchemaItemCollection}
ISchemaItemCollectionDisp = Winapi.MSXMLIntf.ISchemaItemCollectionDisp;
{$EXTERNALSYM ISchemaItemCollectionDisp}
ISchemaStringCollection = Winapi.MSXMLIntf.ISchemaStringCollection;
{$EXTERNALSYM ISchemaStringCollection}
ISchemaStringCollectionDisp = Winapi.MSXMLIntf.ISchemaStringCollectionDisp;
{$EXTERNALSYM ISchemaStringCollectionDisp}
ISchemaType = Winapi.MSXMLIntf.ISchemaType;
{$EXTERNALSYM ISchemaType}
ISchemaTypeDisp = Winapi.MSXMLIntf.ISchemaTypeDisp;
{$EXTERNALSYM ISchemaTypeDisp}
ISchemaComplexType = Winapi.MSXMLIntf.ISchemaComplexType;
{$EXTERNALSYM ISchemaComplexType}
ISchemaComplexTypeDisp = Winapi.MSXMLIntf.ISchemaComplexTypeDisp;
{$EXTERNALSYM ISchemaComplexTypeDisp}
ISchemaAny = Winapi.MSXMLIntf.ISchemaAny;
{$EXTERNALSYM ISchemaAny}
ISchemaAnyDisp = Winapi.MSXMLIntf.ISchemaAnyDisp;
{$EXTERNALSYM ISchemaAnyDisp}
ISchemaModelGroup = Winapi.MSXMLIntf.ISchemaModelGroup;
{$EXTERNALSYM ISchemaModelGroup}
ISchemaModelGroupDisp = Winapi.MSXMLIntf.ISchemaModelGroupDisp;
{$EXTERNALSYM ISchemaModelGroupDisp}
IMXXMLFilter = Winapi.MSXMLIntf.IMXXMLFilter;
{$EXTERNALSYM IMXXMLFilter}
IMXXMLFilterDisp = Winapi.MSXMLIntf.IMXXMLFilterDisp;
{$EXTERNALSYM IMXXMLFilterDisp}
IXMLDOMSchemaCollection2 = Winapi.MSXMLIntf.IXMLDOMSchemaCollection2;
{$EXTERNALSYM IXMLDOMSchemaCollection2}
IXMLDOMSchemaCollection2Disp = Winapi.MSXMLIntf.IXMLDOMSchemaCollection2Disp;
{$EXTERNALSYM IXMLDOMSchemaCollection2Disp}
ISchemaAttribute = Winapi.MSXMLIntf.ISchemaAttribute;
{$EXTERNALSYM ISchemaAttribute}
ISchemaAttributeDisp = Winapi.MSXMLIntf.ISchemaAttributeDisp;
{$EXTERNALSYM ISchemaAttributeDisp}
ISchemaAttributeGroup = Winapi.MSXMLIntf.ISchemaAttributeGroup;
{$EXTERNALSYM ISchemaAttributeGroup}
ISchemaAttributeGroupDisp = Winapi.MSXMLIntf.ISchemaAttributeGroupDisp;
{$EXTERNALSYM ISchemaAttributeGroupDisp}
ISchemaIdentityConstraint = Winapi.MSXMLIntf.ISchemaIdentityConstraint;
{$EXTERNALSYM ISchemaIdentityConstraint}
ISchemaIdentityConstraintDisp = Winapi.MSXMLIntf.ISchemaIdentityConstraintDisp;
{$EXTERNALSYM ISchemaIdentityConstraintDisp}
ISchemaNotation = Winapi.MSXMLIntf.ISchemaNotation;
{$EXTERNALSYM ISchemaNotation}
ISchemaNotationDisp = Winapi.MSXMLIntf.ISchemaNotationDisp;
{$EXTERNALSYM ISchemaNotationDisp}
IXMLDOMSelection = Winapi.MSXMLIntf.IXMLDOMSelection;
{$EXTERNALSYM IXMLDOMSelection}
IXMLDOMSelectionDisp = Winapi.MSXMLIntf.IXMLDOMSelectionDisp;
{$EXTERNALSYM IXMLDOMSelectionDisp}
XMLDOMDocumentEvents = Winapi.MSXMLIntf.XMLDOMDocumentEvents;
{$EXTERNALSYM XMLDOMDocumentEvents}
IDSOControl = Winapi.MSXMLIntf.IDSOControl;
{$EXTERNALSYM IDSOControl}
IDSOControlDisp = Winapi.MSXMLIntf.IDSOControlDisp;
{$EXTERNALSYM IDSOControlDisp}
IXMLHTTPRequest = Winapi.MSXMLIntf.IXMLHTTPRequest;
{$EXTERNALSYM IXMLHTTPRequest}
IXMLHTTPRequestDisp = Winapi.MSXMLIntf.IXMLHTTPRequestDisp;
{$EXTERNALSYM IXMLHTTPRequestDisp}
IServerXMLHTTPRequest = Winapi.MSXMLIntf.IServerXMLHTTPRequest;
{$EXTERNALSYM IServerXMLHTTPRequest}
IServerXMLHTTPRequestDisp = Winapi.MSXMLIntf.IServerXMLHTTPRequestDisp;
{$EXTERNALSYM IServerXMLHTTPRequestDisp}
IServerXMLHTTPRequest2 = Winapi.MSXMLIntf.IServerXMLHTTPRequest2;
{$EXTERNALSYM IServerXMLHTTPRequest2}
IServerXMLHTTPRequest2Disp = Winapi.MSXMLIntf.IServerXMLHTTPRequest2Disp;
{$EXTERNALSYM IServerXMLHTTPRequest2Disp}
IMXNamespacePrefixes = Winapi.MSXMLIntf.IMXNamespacePrefixes;
{$EXTERNALSYM IMXNamespacePrefixes}
IMXNamespacePrefixesDisp = Winapi.MSXMLIntf.IMXNamespacePrefixesDisp;
{$EXTERNALSYM IMXNamespacePrefixesDisp}
IVBMXNamespaceManager = Winapi.MSXMLIntf.IVBMXNamespaceManager;
{$EXTERNALSYM IVBMXNamespaceManager}
IVBMXNamespaceManagerDisp = Winapi.MSXMLIntf.IVBMXNamespaceManagerDisp;
{$EXTERNALSYM IVBMXNamespaceManagerDisp}
IMXNamespaceManager = Winapi.MSXMLIntf.IMXNamespaceManager;
{$EXTERNALSYM IMXNamespaceManager}
// *********************************************************************//
// Declaration of CoClasses defined in Type Library
// (NOTE: Here we map each CoClass to its Default Interface)
// *********************************************************************//
DOMDocument = IXMLDOMDocument2;
{$EXTERNALSYM DOMDocument}
DOMDocument26 = IXMLDOMDocument2;
{$EXTERNALSYM DOMDocument26}
DOMDocument30 = IXMLDOMDocument2;
{$EXTERNALSYM DOMDocument30}
DOMDocument40 = IXMLDOMDocument2;
{$EXTERNALSYM DOMDocument40}
DOMDocument60 = IXMLDOMDocument3;
{$EXTERNALSYM DOMDocument60}
FreeThreadedDOMDocument = IXMLDOMDocument2;
{$EXTERNALSYM FreeThreadedDOMDocument}
FreeThreadedDOMDocument26 = IXMLDOMDocument2;
{$EXTERNALSYM FreeThreadedDOMDocument26}
FreeThreadedDOMDocument30 = IXMLDOMDocument2;
{$EXTERNALSYM FreeThreadedDOMDocument30}
FreeThreadedDOMDocument40 = IXMLDOMDocument2;
{$EXTERNALSYM FreeThreadedDOMDocument40}
FreeThreadedDOMDocument60 = IXMLDOMDocument3;
{$EXTERNALSYM FreeThreadedDOMDocument60}
XMLSchemaCache = IXMLDOMSchemaCollection;
{$EXTERNALSYM XMLSchemaCache}
XMLSchemaCache26 = IXMLDOMSchemaCollection;
{$EXTERNALSYM XMLSchemaCache26}
XMLSchemaCache30 = IXMLDOMSchemaCollection;
{$EXTERNALSYM XMLSchemaCache30}
XMLSchemaCache40 = IXMLDOMSchemaCollection2;
{$EXTERNALSYM XMLSchemaCache40}
XMLSchemaCache60 = IXMLDOMSchemaCollection2;
{$EXTERNALSYM XMLSchemaCache60}
XSLTemplate = IXSLTemplate;
{$EXTERNALSYM XSLTemplate}
XSLTemplate26 = IXSLTemplate;
{$EXTERNALSYM XSLTemplate26}
XSLTemplate30 = IXSLTemplate;
{$EXTERNALSYM XSLTemplate30}
XSLTemplate40 = IXSLTemplate;
{$EXTERNALSYM XSLTemplate40}
XSLTemplate60 = IXSLTemplate;
{$EXTERNALSYM XSLTemplate60}
DSOControl = IDSOControl;
{$EXTERNALSYM DSOControl}
DSOControl26 = IDSOControl;
{$EXTERNALSYM DSOControl26}
DSOControl30 = IDSOControl;
{$EXTERNALSYM DSOControl30}
DSOControl40 = IDSOControl;
{$EXTERNALSYM DSOControl40}
XMLHTTP = IXMLHTTPRequest;
{$EXTERNALSYM XMLHTTP}
XMLHTTP26 = IXMLHTTPRequest;
{$EXTERNALSYM XMLHTTP26}
XMLHTTP30 = IXMLHTTPRequest;
{$EXTERNALSYM XMLHTTP30}
XMLHTTP40 = IXMLHTTPRequest;
{$EXTERNALSYM XMLHTTP40}
XMLHTTP60 = IXMLHTTPRequest;
{$EXTERNALSYM XMLHTTP60}
ServerXMLHTTP = IServerXMLHTTPRequest;
{$EXTERNALSYM ServerXMLHTTP}
ServerXMLHTTP30 = IServerXMLHTTPRequest;
{$EXTERNALSYM ServerXMLHTTP30}
ServerXMLHTTP40 = IServerXMLHTTPRequest2;
{$EXTERNALSYM ServerXMLHTTP40}
ServerXMLHTTP60 = IServerXMLHTTPRequest2;
{$EXTERNALSYM ServerXMLHTTP60}
SAXXMLReader = IVBSAXXMLReader;
{$EXTERNALSYM SAXXMLReader}
SAXXMLReader30 = IVBSAXXMLReader;
{$EXTERNALSYM SAXXMLReader30}
SAXXMLReader40 = IVBSAXXMLReader;
{$EXTERNALSYM SAXXMLReader40}
SAXXMLReader60 = IVBSAXXMLReader;
{$EXTERNALSYM SAXXMLReader60}
MXXMLWriter = IMXWriter;
{$EXTERNALSYM MXXMLWriter}
MXXMLWriter30 = IMXWriter;
{$EXTERNALSYM MXXMLWriter30}
MXXMLWriter40 = IMXWriter;
{$EXTERNALSYM MXXMLWriter40}
MXXMLWriter60 = IMXWriter;
{$EXTERNALSYM MXXMLWriter60}
MXHTMLWriter = IMXWriter;
{$EXTERNALSYM MXHTMLWriter}
MXHTMLWriter30 = IMXWriter;
{$EXTERNALSYM MXHTMLWriter30}
MXHTMLWriter40 = IMXWriter;
{$EXTERNALSYM MXHTMLWriter40}
MXHTMLWriter60 = IMXWriter;
{$EXTERNALSYM MXHTMLWriter60}
SAXAttributes = IMXAttributes;
{$EXTERNALSYM SAXAttributes}
SAXAttributes30 = IMXAttributes;
{$EXTERNALSYM SAXAttributes30}
SAXAttributes40 = IMXAttributes;
{$EXTERNALSYM SAXAttributes40}
SAXAttributes60 = IMXAttributes;
{$EXTERNALSYM SAXAttributes60}
MXNamespaceManager = IVBMXNamespaceManager;
{$EXTERNALSYM MXNamespaceManager}
MXNamespaceManager40 = IVBMXNamespaceManager;
{$EXTERNALSYM MXNamespaceManager40}
MXNamespaceManager60 = IVBMXNamespaceManager;
{$EXTERNALSYM MXNamespaceManager60}
// *********************************************************************//
// Declaration of structures, unions and aliases.
// *********************************************************************//
PWord1 = Winapi.MSXMLIntf.PWord1;
{$EXTERNALSYM PWord1}
DOMNodeType = Winapi.MSXMLIntf.DOMNodeType;
{$EXTERNALSYM DOMNodeType}
SOMITEMTYPE = Winapi.MSXMLIntf.SOMITEMTYPE;
{$EXTERNALSYM SOMITEMTYPE}
SCHEMADERIVATIONMETHOD = Winapi.MSXMLIntf.SCHEMADERIVATIONMETHOD;
{$EXTERNALSYM SCHEMADERIVATIONMETHOD}
SCHEMATYPEVARIETY = Winapi.MSXMLIntf.SCHEMATYPEVARIETY;
{$EXTERNALSYM SCHEMATYPEVARIETY}
SCHEMAWHITESPACE = Winapi.MSXMLIntf.SCHEMAWHITESPACE;
{$EXTERNALSYM SCHEMAWHITESPACE}
SCHEMAPROCESSCONTENTS = Winapi.MSXMLIntf.SCHEMAPROCESSCONTENTS;
{$EXTERNALSYM SCHEMAPROCESSCONTENTS}
SCHEMACONTENTTYPE = Winapi.MSXMLIntf.SCHEMACONTENTTYPE;
{$EXTERNALSYM SCHEMACONTENTTYPE}
SCHEMAUSE = Winapi.MSXMLIntf.SCHEMAUSE;
{$EXTERNALSYM SCHEMAUSE}
SERVERXMLHTTP_OPTION = Winapi.MSXMLIntf.SERVERXMLHTTP_OPTION;
{$EXTERNALSYM SERVERXMLHTTP_OPTION}
SXH_SERVER_CERT_OPTION = _SXH_SERVER_CERT_OPTION;
{$EXTERNALSYM SXH_SERVER_CERT_OPTION}
SXH_PROXY_SETTING = Winapi.MSXMLIntf.SXH_PROXY_SETTING;
{$EXTERNALSYM SXH_PROXY_SETTING}
// *********************************************************************//
// The Class CoDOMDocument provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass DOMDocument. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDOMDocument = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoDOMDocument26 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass DOMDocument26. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDOMDocument26 = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoDOMDocument30 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass DOMDocument30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDOMDocument30 = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoDOMDocument40 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass DOMDocument40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDOMDocument40 = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoDOMDocument60 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument3 exposed by
// the CoClass DOMDocument60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDOMDocument60 = class
class function Create: IXMLDOMDocument3;
class function CreateRemote(const MachineName: string): IXMLDOMDocument3;
end;
// *********************************************************************//
// The Class CoFreeThreadedDOMDocument provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass FreeThreadedDOMDocument. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoFreeThreadedDOMDocument = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoFreeThreadedDOMDocument26 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass FreeThreadedDOMDocument26. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoFreeThreadedDOMDocument26 = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoFreeThreadedDOMDocument30 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass FreeThreadedDOMDocument30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoFreeThreadedDOMDocument30 = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoFreeThreadedDOMDocument40 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument2 exposed by
// the CoClass FreeThreadedDOMDocument40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoFreeThreadedDOMDocument40 = class
class function Create: IXMLDOMDocument2;
class function CreateRemote(const MachineName: string): IXMLDOMDocument2;
end;
// *********************************************************************//
// The Class CoFreeThreadedDOMDocument60 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMDocument3 exposed by
// the CoClass FreeThreadedDOMDocument60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoFreeThreadedDOMDocument60 = class
class function Create: IXMLDOMDocument3;
class function CreateRemote(const MachineName: string): IXMLDOMDocument3;
end;
// *********************************************************************//
// The Class CoXMLSchemaCache provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMSchemaCollection exposed by
// the CoClass XMLSchemaCache. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLSchemaCache = class
class function Create: IXMLDOMSchemaCollection;
class function CreateRemote(const MachineName: string): IXMLDOMSchemaCollection;
end;
// *********************************************************************//
// The Class CoXMLSchemaCache26 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMSchemaCollection exposed by
// the CoClass XMLSchemaCache26. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLSchemaCache26 = class
class function Create: IXMLDOMSchemaCollection;
class function CreateRemote(const MachineName: string): IXMLDOMSchemaCollection;
end;
// *********************************************************************//
// The Class CoXMLSchemaCache30 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMSchemaCollection exposed by
// the CoClass XMLSchemaCache30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLSchemaCache30 = class
class function Create: IXMLDOMSchemaCollection;
class function CreateRemote(const MachineName: string): IXMLDOMSchemaCollection;
end;
// *********************************************************************//
// The Class CoXMLSchemaCache40 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMSchemaCollection2 exposed by
// the CoClass XMLSchemaCache40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLSchemaCache40 = class
class function Create: IXMLDOMSchemaCollection2;
class function CreateRemote(const MachineName: string): IXMLDOMSchemaCollection2;
end;
// *********************************************************************//
// The Class CoXMLSchemaCache60 provides a Create and CreateRemote method to
// create instances of the default interface IXMLDOMSchemaCollection2 exposed by
// the CoClass XMLSchemaCache60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLSchemaCache60 = class
class function Create: IXMLDOMSchemaCollection2;
class function CreateRemote(const MachineName: string): IXMLDOMSchemaCollection2;
end;
// *********************************************************************//
// The Class CoXSLTemplate provides a Create and CreateRemote method to
// create instances of the default interface IXSLTemplate exposed by
// the CoClass XSLTemplate. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXSLTemplate = class
class function Create: IXSLTemplate;
class function CreateRemote(const MachineName: string): IXSLTemplate;
end;
// *********************************************************************//
// The Class CoXSLTemplate26 provides a Create and CreateRemote method to
// create instances of the default interface IXSLTemplate exposed by
// the CoClass XSLTemplate26. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXSLTemplate26 = class
class function Create: IXSLTemplate;
class function CreateRemote(const MachineName: string): IXSLTemplate;
end;
// *********************************************************************//
// The Class CoXSLTemplate30 provides a Create and CreateRemote method to
// create instances of the default interface IXSLTemplate exposed by
// the CoClass XSLTemplate30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXSLTemplate30 = class
class function Create: IXSLTemplate;
class function CreateRemote(const MachineName: string): IXSLTemplate;
end;
// *********************************************************************//
// The Class CoXSLTemplate40 provides a Create and CreateRemote method to
// create instances of the default interface IXSLTemplate exposed by
// the CoClass XSLTemplate40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXSLTemplate40 = class
class function Create: IXSLTemplate;
class function CreateRemote(const MachineName: string): IXSLTemplate;
end;
// *********************************************************************//
// The Class CoXSLTemplate60 provides a Create and CreateRemote method to
// create instances of the default interface IXSLTemplate exposed by
// the CoClass XSLTemplate60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXSLTemplate60 = class
class function Create: IXSLTemplate;
class function CreateRemote(const MachineName: string): IXSLTemplate;
end;
// *********************************************************************//
// The Class CoDSOControl provides a Create and CreateRemote method to
// create instances of the default interface IDSOControl exposed by
// the CoClass DSOControl. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDSOControl = class
class function Create: IDSOControl;
class function CreateRemote(const MachineName: string): IDSOControl;
end;
// *********************************************************************//
// The Class CoDSOControl26 provides a Create and CreateRemote method to
// create instances of the default interface IDSOControl exposed by
// the CoClass DSOControl26. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDSOControl26 = class
class function Create: IDSOControl;
class function CreateRemote(const MachineName: string): IDSOControl;
end;
// *********************************************************************//
// The Class CoDSOControl30 provides a Create and CreateRemote method to
// create instances of the default interface IDSOControl exposed by
// the CoClass DSOControl30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDSOControl30 = class
class function Create: IDSOControl;
class function CreateRemote(const MachineName: string): IDSOControl;
end;
// *********************************************************************//
// The Class CoDSOControl40 provides a Create and CreateRemote method to
// create instances of the default interface IDSOControl exposed by
// the CoClass DSOControl40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoDSOControl40 = class
class function Create: IDSOControl;
class function CreateRemote(const MachineName: string): IDSOControl;
end;
// *********************************************************************//
// The Class CoXMLHTTP provides a Create and CreateRemote method to
// create instances of the default interface IXMLHTTPRequest exposed by
// the CoClass XMLHTTP. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLHTTP = class
class function Create: IXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoXMLHTTP26 provides a Create and CreateRemote method to
// create instances of the default interface IXMLHTTPRequest exposed by
// the CoClass XMLHTTP26. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLHTTP26 = class
class function Create: IXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoXMLHTTP30 provides a Create and CreateRemote method to
// create instances of the default interface IXMLHTTPRequest exposed by
// the CoClass XMLHTTP30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLHTTP30 = class
class function Create: IXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoXMLHTTP40 provides a Create and CreateRemote method to
// create instances of the default interface IXMLHTTPRequest exposed by
// the CoClass XMLHTTP40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLHTTP40 = class
class function Create: IXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoXMLHTTP60 provides a Create and CreateRemote method to
// create instances of the default interface IXMLHTTPRequest exposed by
// the CoClass XMLHTTP60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoXMLHTTP60 = class
class function Create: IXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoServerXMLHTTP provides a Create and CreateRemote method to
// create instances of the default interface IServerXMLHTTPRequest exposed by
// the CoClass ServerXMLHTTP. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoServerXMLHTTP = class
class function Create: IServerXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IServerXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoServerXMLHTTP30 provides a Create and CreateRemote method to
// create instances of the default interface IServerXMLHTTPRequest exposed by
// the CoClass ServerXMLHTTP30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoServerXMLHTTP30 = class
class function Create: IServerXMLHTTPRequest;
class function CreateRemote(const MachineName: string): IServerXMLHTTPRequest;
end;
// *********************************************************************//
// The Class CoServerXMLHTTP40 provides a Create and CreateRemote method to
// create instances of the default interface IServerXMLHTTPRequest2 exposed by
// the CoClass ServerXMLHTTP40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoServerXMLHTTP40 = class
class function Create: IServerXMLHTTPRequest2;
class function CreateRemote(const MachineName: string): IServerXMLHTTPRequest2;
end;
// *********************************************************************//
// The Class CoServerXMLHTTP60 provides a Create and CreateRemote method to
// create instances of the default interface IServerXMLHTTPRequest2 exposed by
// the CoClass ServerXMLHTTP60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoServerXMLHTTP60 = class
class function Create: IServerXMLHTTPRequest2;
class function CreateRemote(const MachineName: string): IServerXMLHTTPRequest2;
end;
// *********************************************************************//
// The Class CoSAXXMLReader provides a Create and CreateRemote method to
// create instances of the default interface IVBSAXXMLReader exposed by
// the CoClass SAXXMLReader. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXXMLReader = class
class function Create: IVBSAXXMLReader;
class function CreateRemote(const MachineName: string): IVBSAXXMLReader;
end;
// *********************************************************************//
// The Class CoSAXXMLReader30 provides a Create and CreateRemote method to
// create instances of the default interface IVBSAXXMLReader exposed by
// the CoClass SAXXMLReader30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXXMLReader30 = class
class function Create: IVBSAXXMLReader;
class function CreateRemote(const MachineName: string): IVBSAXXMLReader;
end;
// *********************************************************************//
// The Class CoSAXXMLReader40 provides a Create and CreateRemote method to
// create instances of the default interface IVBSAXXMLReader exposed by
// the CoClass SAXXMLReader40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXXMLReader40 = class
class function Create: IVBSAXXMLReader;
class function CreateRemote(const MachineName: string): IVBSAXXMLReader;
end;
// *********************************************************************//
// The Class CoSAXXMLReader60 provides a Create and CreateRemote method to
// create instances of the default interface IVBSAXXMLReader exposed by
// the CoClass SAXXMLReader60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXXMLReader60 = class
class function Create: IVBSAXXMLReader;
class function CreateRemote(const MachineName: string): IVBSAXXMLReader;
end;
// *********************************************************************//
// The Class CoMXXMLWriter provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXXMLWriter. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXXMLWriter = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXXMLWriter30 provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXXMLWriter30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXXMLWriter30 = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXXMLWriter40 provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXXMLWriter40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXXMLWriter40 = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXXMLWriter60 provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXXMLWriter60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXXMLWriter60 = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXHTMLWriter provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXHTMLWriter. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXHTMLWriter = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXHTMLWriter30 provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXHTMLWriter30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXHTMLWriter30 = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXHTMLWriter40 provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXHTMLWriter40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXHTMLWriter40 = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoMXHTMLWriter60 provides a Create and CreateRemote method to
// create instances of the default interface IMXWriter exposed by
// the CoClass MXHTMLWriter60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXHTMLWriter60 = class
class function Create: IMXWriter;
class function CreateRemote(const MachineName: string): IMXWriter;
end;
// *********************************************************************//
// The Class CoSAXAttributes provides a Create and CreateRemote method to
// create instances of the default interface IMXAttributes exposed by
// the CoClass SAXAttributes. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXAttributes = class
class function Create: IMXAttributes;
class function CreateRemote(const MachineName: string): IMXAttributes;
end;
// *********************************************************************//
// The Class CoSAXAttributes30 provides a Create and CreateRemote method to
// create instances of the default interface IMXAttributes exposed by
// the CoClass SAXAttributes30. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXAttributes30 = class
class function Create: IMXAttributes;
class function CreateRemote(const MachineName: string): IMXAttributes;
end;
// *********************************************************************//
// The Class CoSAXAttributes40 provides a Create and CreateRemote method to
// create instances of the default interface IMXAttributes exposed by
// the CoClass SAXAttributes40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXAttributes40 = class
class function Create: IMXAttributes;
class function CreateRemote(const MachineName: string): IMXAttributes;
end;
// *********************************************************************//
// The Class CoSAXAttributes60 provides a Create and CreateRemote method to
// create instances of the default interface IMXAttributes exposed by
// the CoClass SAXAttributes60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoSAXAttributes60 = class
class function Create: IMXAttributes;
class function CreateRemote(const MachineName: string): IMXAttributes;
end;
// *********************************************************************//
// The Class CoMXNamespaceManager provides a Create and CreateRemote method to
// create instances of the default interface IVBMXNamespaceManager exposed by
// the CoClass MXNamespaceManager. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXNamespaceManager = class
class function Create: IVBMXNamespaceManager;
class function CreateRemote(const MachineName: string): IVBMXNamespaceManager;
end;
// *********************************************************************//
// The Class CoMXNamespaceManager40 provides a Create and CreateRemote method to
// create instances of the default interface IVBMXNamespaceManager exposed by
// the CoClass MXNamespaceManager40. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXNamespaceManager40 = class
class function Create: IVBMXNamespaceManager;
class function CreateRemote(const MachineName: string): IVBMXNamespaceManager;
end;
// *********************************************************************//
// The Class CoMXNamespaceManager60 provides a Create and CreateRemote method to
// create instances of the default interface IVBMXNamespaceManager exposed by
// the CoClass MXNamespaceManager60. The functions are intended to be used by
// clients wishing to automate the CoClass objects exposed by the
// server of this typelibrary.
// *********************************************************************//
CoMXNamespaceManager60 = class
class function Create: IVBMXNamespaceManager;
class function CreateRemote(const MachineName: string): IVBMXNamespaceManager;
end;
implementation
uses System.Win.ComObj;
class function CoDOMDocument.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_DOMDocument) as IXMLDOMDocument2;
end;
class function CoDOMDocument.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DOMDocument) as IXMLDOMDocument2;
end;
class function CoDOMDocument26.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_DOMDocument26) as IXMLDOMDocument2;
end;
class function CoDOMDocument26.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DOMDocument26) as IXMLDOMDocument2;
end;
class function CoDOMDocument30.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_DOMDocument30) as IXMLDOMDocument2;
end;
class function CoDOMDocument30.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DOMDocument30) as IXMLDOMDocument2;
end;
class function CoDOMDocument40.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_DOMDocument40) as IXMLDOMDocument2;
end;
class function CoDOMDocument40.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DOMDocument40) as IXMLDOMDocument2;
end;
class function CoDOMDocument60.Create: IXMLDOMDocument3;
begin
Result := CreateComObject(CLASS_DOMDocument60) as IXMLDOMDocument3;
end;
class function CoDOMDocument60.CreateRemote(const MachineName: string): IXMLDOMDocument3;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DOMDocument60) as IXMLDOMDocument3;
end;
class function CoFreeThreadedDOMDocument.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_FreeThreadedDOMDocument) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_FreeThreadedDOMDocument) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument26.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_FreeThreadedDOMDocument26) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument26.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_FreeThreadedDOMDocument26) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument30.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_FreeThreadedDOMDocument30) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument30.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_FreeThreadedDOMDocument30) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument40.Create: IXMLDOMDocument2;
begin
Result := CreateComObject(CLASS_FreeThreadedDOMDocument40) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument40.CreateRemote(const MachineName: string): IXMLDOMDocument2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_FreeThreadedDOMDocument40) as IXMLDOMDocument2;
end;
class function CoFreeThreadedDOMDocument60.Create: IXMLDOMDocument3;
begin
Result := CreateComObject(CLASS_FreeThreadedDOMDocument60) as IXMLDOMDocument3;
end;
class function CoFreeThreadedDOMDocument60.CreateRemote(const MachineName: string): IXMLDOMDocument3;
begin
Result := CreateRemoteComObject(MachineName, CLASS_FreeThreadedDOMDocument60) as IXMLDOMDocument3;
end;
class function CoXMLSchemaCache.Create: IXMLDOMSchemaCollection;
begin
Result := CreateComObject(CLASS_XMLSchemaCache) as IXMLDOMSchemaCollection;
end;
class function CoXMLSchemaCache.CreateRemote(const MachineName: string): IXMLDOMSchemaCollection;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLSchemaCache) as IXMLDOMSchemaCollection;
end;
class function CoXMLSchemaCache26.Create: IXMLDOMSchemaCollection;
begin
Result := CreateComObject(CLASS_XMLSchemaCache26) as IXMLDOMSchemaCollection;
end;
class function CoXMLSchemaCache26.CreateRemote(const MachineName: string): IXMLDOMSchemaCollection;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLSchemaCache26) as IXMLDOMSchemaCollection;
end;
class function CoXMLSchemaCache30.Create: IXMLDOMSchemaCollection;
begin
Result := CreateComObject(CLASS_XMLSchemaCache30) as IXMLDOMSchemaCollection;
end;
class function CoXMLSchemaCache30.CreateRemote(const MachineName: string): IXMLDOMSchemaCollection;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLSchemaCache30) as IXMLDOMSchemaCollection;
end;
class function CoXMLSchemaCache40.Create: IXMLDOMSchemaCollection2;
begin
Result := CreateComObject(CLASS_XMLSchemaCache40) as IXMLDOMSchemaCollection2;
end;
class function CoXMLSchemaCache40.CreateRemote(const MachineName: string): IXMLDOMSchemaCollection2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLSchemaCache40) as IXMLDOMSchemaCollection2;
end;
class function CoXMLSchemaCache60.Create: IXMLDOMSchemaCollection2;
begin
Result := CreateComObject(CLASS_XMLSchemaCache60) as IXMLDOMSchemaCollection2;
end;
class function CoXMLSchemaCache60.CreateRemote(const MachineName: string): IXMLDOMSchemaCollection2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLSchemaCache60) as IXMLDOMSchemaCollection2;
end;
class function CoXSLTemplate.Create: IXSLTemplate;
begin
Result := CreateComObject(CLASS_XSLTemplate) as IXSLTemplate;
end;
class function CoXSLTemplate.CreateRemote(const MachineName: string): IXSLTemplate;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XSLTemplate) as IXSLTemplate;
end;
class function CoXSLTemplate26.Create: IXSLTemplate;
begin
Result := CreateComObject(CLASS_XSLTemplate26) as IXSLTemplate;
end;
class function CoXSLTemplate26.CreateRemote(const MachineName: string): IXSLTemplate;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XSLTemplate26) as IXSLTemplate;
end;
class function CoXSLTemplate30.Create: IXSLTemplate;
begin
Result := CreateComObject(CLASS_XSLTemplate30) as IXSLTemplate;
end;
class function CoXSLTemplate30.CreateRemote(const MachineName: string): IXSLTemplate;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XSLTemplate30) as IXSLTemplate;
end;
class function CoXSLTemplate40.Create: IXSLTemplate;
begin
Result := CreateComObject(CLASS_XSLTemplate40) as IXSLTemplate;
end;
class function CoXSLTemplate40.CreateRemote(const MachineName: string): IXSLTemplate;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XSLTemplate40) as IXSLTemplate;
end;
class function CoXSLTemplate60.Create: IXSLTemplate;
begin
Result := CreateComObject(CLASS_XSLTemplate60) as IXSLTemplate;
end;
class function CoXSLTemplate60.CreateRemote(const MachineName: string): IXSLTemplate;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XSLTemplate60) as IXSLTemplate;
end;
class function CoDSOControl.Create: IDSOControl;
begin
Result := CreateComObject(CLASS_DSOControl) as IDSOControl;
end;
class function CoDSOControl.CreateRemote(const MachineName: string): IDSOControl;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DSOControl) as IDSOControl;
end;
class function CoDSOControl26.Create: IDSOControl;
begin
Result := CreateComObject(CLASS_DSOControl26) as IDSOControl;
end;
class function CoDSOControl26.CreateRemote(const MachineName: string): IDSOControl;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DSOControl26) as IDSOControl;
end;
class function CoDSOControl30.Create: IDSOControl;
begin
Result := CreateComObject(CLASS_DSOControl30) as IDSOControl;
end;
class function CoDSOControl30.CreateRemote(const MachineName: string): IDSOControl;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DSOControl30) as IDSOControl;
end;
class function CoDSOControl40.Create: IDSOControl;
begin
Result := CreateComObject(CLASS_DSOControl40) as IDSOControl;
end;
class function CoDSOControl40.CreateRemote(const MachineName: string): IDSOControl;
begin
Result := CreateRemoteComObject(MachineName, CLASS_DSOControl40) as IDSOControl;
end;
class function CoXMLHTTP.Create: IXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_XMLHTTP) as IXMLHTTPRequest;
end;
class function CoXMLHTTP.CreateRemote(const MachineName: string): IXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLHTTP) as IXMLHTTPRequest;
end;
class function CoXMLHTTP26.Create: IXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_XMLHTTP26) as IXMLHTTPRequest;
end;
class function CoXMLHTTP26.CreateRemote(const MachineName: string): IXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLHTTP26) as IXMLHTTPRequest;
end;
class function CoXMLHTTP30.Create: IXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_XMLHTTP30) as IXMLHTTPRequest;
end;
class function CoXMLHTTP30.CreateRemote(const MachineName: string): IXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLHTTP30) as IXMLHTTPRequest;
end;
class function CoXMLHTTP40.Create: IXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_XMLHTTP40) as IXMLHTTPRequest;
end;
class function CoXMLHTTP40.CreateRemote(const MachineName: string): IXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLHTTP40) as IXMLHTTPRequest;
end;
class function CoXMLHTTP60.Create: IXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_XMLHTTP60) as IXMLHTTPRequest;
end;
class function CoXMLHTTP60.CreateRemote(const MachineName: string): IXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_XMLHTTP60) as IXMLHTTPRequest;
end;
class function CoServerXMLHTTP.Create: IServerXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_ServerXMLHTTP) as IServerXMLHTTPRequest;
end;
class function CoServerXMLHTTP.CreateRemote(const MachineName: string): IServerXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_ServerXMLHTTP) as IServerXMLHTTPRequest;
end;
class function CoServerXMLHTTP30.Create: IServerXMLHTTPRequest;
begin
Result := CreateComObject(CLASS_ServerXMLHTTP30) as IServerXMLHTTPRequest;
end;
class function CoServerXMLHTTP30.CreateRemote(const MachineName: string): IServerXMLHTTPRequest;
begin
Result := CreateRemoteComObject(MachineName, CLASS_ServerXMLHTTP30) as IServerXMLHTTPRequest;
end;
class function CoServerXMLHTTP40.Create: IServerXMLHTTPRequest2;
begin
Result := CreateComObject(CLASS_ServerXMLHTTP40) as IServerXMLHTTPRequest2;
end;
class function CoServerXMLHTTP40.CreateRemote(const MachineName: string): IServerXMLHTTPRequest2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_ServerXMLHTTP40) as IServerXMLHTTPRequest2;
end;
class function CoServerXMLHTTP60.Create: IServerXMLHTTPRequest2;
begin
Result := CreateComObject(CLASS_ServerXMLHTTP60) as IServerXMLHTTPRequest2;
end;
class function CoServerXMLHTTP60.CreateRemote(const MachineName: string): IServerXMLHTTPRequest2;
begin
Result := CreateRemoteComObject(MachineName, CLASS_ServerXMLHTTP60) as IServerXMLHTTPRequest2;
end;
class function CoSAXXMLReader.Create: IVBSAXXMLReader;
begin
Result := CreateComObject(CLASS_SAXXMLReader) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader.CreateRemote(const MachineName: string): IVBSAXXMLReader;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXXMLReader) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader30.Create: IVBSAXXMLReader;
begin
Result := CreateComObject(CLASS_SAXXMLReader30) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader30.CreateRemote(const MachineName: string): IVBSAXXMLReader;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXXMLReader30) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader40.Create: IVBSAXXMLReader;
begin
Result := CreateComObject(CLASS_SAXXMLReader40) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader40.CreateRemote(const MachineName: string): IVBSAXXMLReader;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXXMLReader40) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader60.Create: IVBSAXXMLReader;
begin
Result := CreateComObject(CLASS_SAXXMLReader60) as IVBSAXXMLReader;
end;
class function CoSAXXMLReader60.CreateRemote(const MachineName: string): IVBSAXXMLReader;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXXMLReader60) as IVBSAXXMLReader;
end;
class function CoMXXMLWriter.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXXMLWriter) as IMXWriter;
end;
class function CoMXXMLWriter.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXXMLWriter) as IMXWriter;
end;
class function CoMXXMLWriter30.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXXMLWriter30) as IMXWriter;
end;
class function CoMXXMLWriter30.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXXMLWriter30) as IMXWriter;
end;
class function CoMXXMLWriter40.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXXMLWriter40) as IMXWriter;
end;
class function CoMXXMLWriter40.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXXMLWriter40) as IMXWriter;
end;
class function CoMXXMLWriter60.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXXMLWriter60) as IMXWriter;
end;
class function CoMXXMLWriter60.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXXMLWriter60) as IMXWriter;
end;
class function CoMXHTMLWriter.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXHTMLWriter) as IMXWriter;
end;
class function CoMXHTMLWriter.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXHTMLWriter) as IMXWriter;
end;
class function CoMXHTMLWriter30.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXHTMLWriter30) as IMXWriter;
end;
class function CoMXHTMLWriter30.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXHTMLWriter30) as IMXWriter;
end;
class function CoMXHTMLWriter40.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXHTMLWriter40) as IMXWriter;
end;
class function CoMXHTMLWriter40.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXHTMLWriter40) as IMXWriter;
end;
class function CoMXHTMLWriter60.Create: IMXWriter;
begin
Result := CreateComObject(CLASS_MXHTMLWriter60) as IMXWriter;
end;
class function CoMXHTMLWriter60.CreateRemote(const MachineName: string): IMXWriter;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXHTMLWriter60) as IMXWriter;
end;
class function CoSAXAttributes.Create: IMXAttributes;
begin
Result := CreateComObject(CLASS_SAXAttributes) as IMXAttributes;
end;
class function CoSAXAttributes.CreateRemote(const MachineName: string): IMXAttributes;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXAttributes) as IMXAttributes;
end;
class function CoSAXAttributes30.Create: IMXAttributes;
begin
Result := CreateComObject(CLASS_SAXAttributes30) as IMXAttributes;
end;
class function CoSAXAttributes30.CreateRemote(const MachineName: string): IMXAttributes;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXAttributes30) as IMXAttributes;
end;
class function CoSAXAttributes40.Create: IMXAttributes;
begin
Result := CreateComObject(CLASS_SAXAttributes40) as IMXAttributes;
end;
class function CoSAXAttributes40.CreateRemote(const MachineName: string): IMXAttributes;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXAttributes40) as IMXAttributes;
end;
class function CoSAXAttributes60.Create: IMXAttributes;
begin
Result := CreateComObject(CLASS_SAXAttributes60) as IMXAttributes;
end;
class function CoSAXAttributes60.CreateRemote(const MachineName: string): IMXAttributes;
begin
Result := CreateRemoteComObject(MachineName, CLASS_SAXAttributes60) as IMXAttributes;
end;
class function CoMXNamespaceManager.Create: IVBMXNamespaceManager;
begin
Result := CreateComObject(CLASS_MXNamespaceManager) as IVBMXNamespaceManager;
end;
class function CoMXNamespaceManager.CreateRemote(const MachineName: string): IVBMXNamespaceManager;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXNamespaceManager) as IVBMXNamespaceManager;
end;
class function CoMXNamespaceManager40.Create: IVBMXNamespaceManager;
begin
Result := CreateComObject(CLASS_MXNamespaceManager40) as IVBMXNamespaceManager;
end;
class function CoMXNamespaceManager40.CreateRemote(const MachineName: string): IVBMXNamespaceManager;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXNamespaceManager40) as IVBMXNamespaceManager;
end;
class function CoMXNamespaceManager60.Create: IVBMXNamespaceManager;
begin
Result := CreateComObject(CLASS_MXNamespaceManager60) as IVBMXNamespaceManager;
end;
class function CoMXNamespaceManager60.CreateRemote(const MachineName: string): IVBMXNamespaceManager;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MXNamespaceManager60) as IVBMXNamespaceManager;
end;
end.
|
program strMatching;
Type
OperType = (UNDEFINED, MATCH, INSERT, DELETE);
cell = record
cost:integer;
parent: OperType;
end;
var str1, str2, str3, str4: String;
dist: integer;
m: Array [0..MAXLEN, 0..MAXLEN] of cell;
function indel (c: char):integer;
begin
indel:= 1;
end;
function char_match (c:char; d: char): integer;
begin
if (c <> d) then char_match:= 1
else char_match := 0;
end;
function string_compare (s: string; t: string; i: integer; j: integer): integer;
var
k: OperType;
opt: Array [OperType] of integer;
lowest_cost: integer;
begin
if (i = 0) then
begin
string_compare:= j*indel(' ');
exit
end;
if(j = 0) then
begin
string_compare := i*indel(' ');
exit
end;
opt[MATCH] := string_compare(s, t, i-1, j-1) + char_match(s[i],t[j]);
opt[INSERT] := string_compare (s, t, i, j-1) + indel(t[j]);
opt[DELETE] := string_compare (s, t, i-1, j) + indel(s[i]);
lowest_cost := opt[MATCH];
for k:= INSERT to DELETE do begin
if (opt[k] < lowest_cost) then lowest_cost := opt[k]
end;
string_compare := lowest_cost;
end;
begin
str1:= 'GAATTCAGTTA';
str2:= 'GGATCGA';
str3:= 'thou-shalt-not';
str4:= 'you-shoud-not';
dist:= string_compare (str1, str2, length(str1),length(str2));
writeln (dist, 'moves');
end. |
unit UTablaSim;
interface
uses crt, Utipos;
procedure crearTS (var tabla:TS);
procedure insertarenTS (var tabla:TS; lex:string[80]; comp:simbolos);
procedure busquedaenTS (tabla:TS; lexema:string[80]; var complex:simbolos ; var pos:byte);
implementation
procedure crearTS (var tabla:TS);
begin
tabla.cantidad:=0;
insertarenTS (tabla, 'rest', rest);
insertarenTS (tabla, 'cons', cons);
insertarenTS (tabla, 'first', first);
insertarenTS (tabla, 'leerEntero', leerEntero);
insertarenTS (tabla, 'leerLista', leerLista);
insertarenTS (tabla, 'escribir', escribir);
insertarenTS (tabla, 'si', si);
insertarenTS (tabla, 'entonces', entonces);
insertarenTS (tabla, 'fin', fin);
insertarenTS (tabla, 'sino', sino);
insertarenTS (tabla, 'null', null);
insertarenTS (tabla, 'mientras', mientras);
insertarenTS (tabla, 'hacer', hacer);
end;
procedure insertarenTS (var tabla:TS; lex:string[80]; comp:simbolos);
begin
if tabla.cantidad<100 then
begin
inc(tabla.cantidad);
with tabla.lista[tabla.cantidad] do
begin
lexema:=lex;
complex:=comp;
newTResultado(val);
end;
end;
end;
procedure busquedaenTS (tabla:TS; lexema:string[80]; var complex:simbolos; var pos:byte);
var
i:byte;
begin
i:=0;
repeat
inc(i);
if tabla.lista[i].lexema=lexema then
begin
complex:=tabla.lista[i].complex;
pos:=i
end
until (i=tabla.cantidad) or (tabla.lista[i].lexema=lexema);
if tabla.lista[i].lexema=lexema then
begin
complex:=tabla.lista[i].complex;
pos:=i;
end
else
pos:=0;
end;
end.
|
unit PascalCoin.RawOp.Interfaces;
interface
uses PascalCoin.Wallet.Interfaces;
type
IRawOperation = interface
['{24258076-FBD4-4AB0-BE47-458F7AD00CE7}']
function GetRawData: string;
property RawData: string read GetRawData;
end;
IRawOperations = interface
['{3850F193-355D-402E-8F69-21D35B636DA4}']
function GetRawOperation(const Index: integer): IRawOperation;
function GetRawData: string;
function AddRawOperation(Value: IRawOperation): integer;
property RawData: string read GetRawData;
property RawOperation[const Index: integer]: IRawOperation
read GetRawOperation;
end;
IRawTransactionOp = interface(IRawOperation)
['{0E4967FF-BB2D-4749-ABE0-B810204455DE}']
function GetSendFrom: Cardinal;
function GetNOp: integer;
function GetSendTo: Cardinal;
function GetAmount: Currency;
function GetFee: Currency;
function GetPayload: string;
procedure SetSendFrom(const Value: Cardinal);
procedure SetNOp(const Value: integer);
procedure SetSendTo(const Value: Cardinal);
procedure SetAmount(const Value: Currency);
procedure SetFee(const Value: Currency);
procedure SetPayload(const Value: string);
procedure SetKey(Value: IPrivateKey);
{$IFDEF UNITTEST}
function GetKRandom: string;
procedure SetKRandom(const Value: string);
function TestValue(const AKey: string): string;
{$ENDIF}
property SendFrom: Cardinal read GetSendFrom write SetSendFrom;
property NOp: integer read GetNOp write SetNOp;
property SendTo: Cardinal read GetSendTo write SetSendTo;
property Amount: Currency read GetAmount write SetAmount;
property Fee: Currency read GetFee write SetFee;
property Payload: string read GetPayload write SetPayload;
property Key: IPrivateKey write SetKey;
{$IFDEF UNITTEST}
property KRandom: string read GetKRandom write SetKRandom;
{$ENDIF}
end;
implementation
end.
|
unit MediaProcessing.ProcessorListForAllMediaTypesFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls,MediaProcessing.Definitions, MediaProcessing.ProcessorListFrame;
type
TfrmMediaProcessorListForAllMediaTypes = class(TFrame)
pcMediaTypes: TPageControl;
private
FProcessorListFrames: array [TMediaType] of TfrmMediaProcessorList;
FOnDataChanged: TNotifyEvent;
procedure OnProcessorListDataChanged(aSender: TObject);
function GetProcessorList(aIndex: TMediaType): TfrmMediaProcessorList;
function GetOriginalStreamType(aIndex: TMediaType): TStreamType;
function GetOutputStreamType(aIndex: TMediaType): TStreamType;
procedure SetOriginalStreamType(aIndex: TMediaType;
const Value: TStreamType);
function GetPageVisible(aIndex: TMediaType): boolean;
procedure SetPageVisible(aIndex: TMediaType; const Value: boolean);
public
constructor Create(aOwner: TComponent); override;
property ProcessorList[aIndex: TMediaType]: TfrmMediaProcessorList read GetProcessorList;
property OriginalStreamType[aIndex: TMediaType]: TStreamType read GetOriginalStreamType write SetOriginalStreamType;
property OutputStreamType[aIndex: TMediaType]: TStreamType read GetOutputStreamType;
property PageVisible[aIndex: TMediaType]: boolean read GetPageVisible write SetPageVisible;
property OnDataChanged: TNotifyEvent read FOnDataChanged write FOnDataChanged;
end;
implementation
{$R *.dfm}
{ TFrame1 }
constructor TfrmMediaProcessorListForAllMediaTypes.Create(aOwner: TComponent);
var
aMediaType: TMediaType;
aPage:TTabSheet;
i,j: Integer;
begin
inherited Create(aOwner);
for aMediaType:=Low(TMediaType) to High(TMediaType) do
begin
aPage:=TTabSheet.Create(pcMediaTypes);
aPage.PageControl:=pcMediaTypes;
aPage.Caption:=MediaTypeNames[aMediaType];
FProcessorListFrames[aMediaType]:=TfrmMediaProcessorList.Create(self);
FProcessorListFrames[aMediaType].Name:='MediaType'+IntToStr(integer(aMediaType));
FProcessorListFrames[aMediaType].Parent:=aPage;
FProcessorListFrames[aMediaType].Align:=alClient;
FProcessorListFrames[aMediaType].OnDataChanged:=OnProcessorListDataChanged;
FProcessorListFrames[aMediaType].ParentBackground:=true;
FProcessorListFrames[aMediaType].FillOriginalStreamTypeList(aMediaType);
FProcessorListFrames[aMediaType].AcceptableMediaTypes:=[aMediaType];
with FProcessorListFrames[aMediaType] do
begin
for j:= 0 to OriginalStreamTypeListCount-1 do
for i := 0 to OriginalStreamTypeListCount-1 do
begin
if not IsAppropriateToMediaType(OriginalStreamTypeList[i],aMediaType) then
begin
FProcessorListFrames[aMediaType].RemoveFromOriginalStreamTypeList(OriginalStreamTypeList[i]);
break;
end;
end;
end;
pcMediaTypes.ActivePageIndex:=0;
end;
end;
function TfrmMediaProcessorListForAllMediaTypes.GetOriginalStreamType(aIndex: TMediaType): TStreamType;
begin
result:=FProcessorListFrames[aIndex].OriginalStreamType;
end;
function TfrmMediaProcessorListForAllMediaTypes.GetOutputStreamType(aIndex: TMediaType): TStreamType;
begin
result:=FProcessorListFrames[aIndex].OutputStreamType;
end;
function TfrmMediaProcessorListForAllMediaTypes.GetPageVisible(
aIndex: TMediaType): boolean;
begin
result:=pcMediaTypes.Pages[integer(aIndex)].TabVisible;
end;
function TfrmMediaProcessorListForAllMediaTypes.GetProcessorList(aIndex: TMediaType): TfrmMediaProcessorList;
begin
result:=FProcessorListFrames[aIndex];
end;
procedure TfrmMediaProcessorListForAllMediaTypes.OnProcessorListDataChanged(aSender: TObject);
begin
if Assigned(FOnDataChanged) then
FOnDataChanged(self);
end;
procedure TfrmMediaProcessorListForAllMediaTypes.SetOriginalStreamType(aIndex: TMediaType; const Value: TStreamType);
begin
FProcessorListFrames[aIndex].OriginalStreamType:=Value;
end;
procedure TfrmMediaProcessorListForAllMediaTypes.SetPageVisible(
aIndex: TMediaType; const Value: boolean);
begin
pcMediaTypes.Pages[integer(aIndex)].TabVisible:=Value;
end;
end.
|
{
:: X2UtNamedFormat implements Format-style functionality using named
:: instead of indexed parameters.
::
:: Last changed: $Date$
:: Revision: $Rev$
:: Author: $Author$
}
unit X2UtNamedFormat;
interface
uses
Classes,
SysUtils;
type
TNamedFormatStringList = class(TStringList)
public
procedure AddLn();
function Format(AParams: array of const): String;
end;
{
AFormat uses the same format strings as SysUtils.Format, where each
format specifier may use a named instead of a numeric index, surrounded by
<>, eg:
%<Value1>:s %<Value2>:.2d
AParams contains alternating the parameter name and it's value.
Note: NamedFormat works by mapping names to indices and passing the result
to SysUtils.Format. Unnamed or existing indexed specifiers will therefore
be affected by named specifiers! It is strongly recommended to name all
specifiers.
}
function NamedFormat(const AFormat: String; AParams: array of const; AFormatSettings: TFormatSettings): String; overload;
function NamedFormat(const AFormat: String; AParams: array of const): String; overload;
implementation
uses
Windows;
type
TProtectedMemoryStream = class(TMemoryStream);
const
SpecifierChar = '%';
SpecifierNameStart = '<';
SpecifierNameEnd = '>';
ValidNameChars = ['A'..'Z', 'a'..'z', '0'..'9', '_'];
procedure StreamWriteChar(const AStream: TStream; const AValue: Char);
begin
AStream.WriteBuffer(AValue, SizeOf(Char));
end;
procedure StreamWriteString(const AStream: TStream; const AValue: String);
begin
AStream.WriteBuffer(PChar(AValue)^, Length(AValue) * SizeOf(Char));
end;
function FindNameEnd(const APosition: PChar; const AEnd: PChar): PChar;
var
position: PChar;
begin
Result := nil;
position := APosition;
while position < AEnd do
begin
if position^ = SpecifierNameEnd then
begin
Result := position;
break;
end;
if not CharInSet(position^, ValidNameChars) then
break;
Inc(position);
end;
end;
function NamedFormat(const AFormat: String; AParams: array of const): String; overload;
var
formatSettings: TFormatSettings;
begin
formatSettings := TFormatSettings.Create;
Result := NamedFormat(AFormat, AParams, formatSettings);
end;
function NamedFormat(const AFormat: string; AParams: array of const; AFormatSettings: TFormatSettings): String;
var
currentPos: PChar;
formatEnd: PChar;
formatStream: TMemoryStream;
formatString: String;
name: String;
nameEnd: PChar;
nameStart: PChar;
param: TVarRec;
paramIndex: Integer;
paramNames: TStringList;
paramValues: array of TVarRec;
specifierIndex: Integer;
errorMsg: String;
begin
if Length(AParams) mod 2 = 1 then
raise Exception.Create('AParams must contains a multiple of 2 number of items');
currentPos := PChar(AFormat);
SetLength(paramValues, 0);
formatEnd := currentPos;
Inc(formatEnd, Length(AFormat));
paramNames := TStringList.Create();
try
paramNames.CaseSensitive := False;
formatStream := TMemoryStream.Create();
try
{ Most likely scenario; the names are longer than the replacement
indexes. }
TProtectedMemoryStream(formatStream).Capacity := Length(AFormat) * SizeOf(Char);
while currentPos < formatEnd do
begin
{ Search for % }
if currentPos^ = SpecifierChar then
begin
StreamWriteChar(formatStream, currentPos^);
Inc(currentPos);
{ Check if this is indeed a named specifier }
if (currentPos < formatEnd) and (currentPos^ = SpecifierNameStart) then
begin
Inc(currentPos);
nameStart := currentPos;
nameEnd := FindNameEnd(currentPos, formatEnd);
if Assigned(nameEnd) then
begin
SetString(name, nameStart, nameEnd - nameStart);
specifierIndex := paramNames.IndexOf(name);
if specifierIndex = -1 then
specifierIndex := paramNames.Add(name);
StreamWriteString(formatStream, IntToStr(specifierIndex));
currentPos := nameEnd;
end;
end else
StreamWriteChar(formatStream, currentPos^);
end else
StreamWriteChar(formatStream, currentPos^);
Inc(currentPos);
end;
SetString(formatString, PChar(formatStream.Memory), formatStream.Size div SizeOf(Char));
finally
FreeAndNil(formatStream);
end;
SetLength(paramValues, paramNames.Count);
paramIndex := 0;
while paramIndex < High(AParams) do
begin
param := AParams[paramIndex];
case param.VType of
vtChar: name := string(param.VChar);
vtString: name := string(param.VString^);
vtPChar: name := string(param.VPChar);
vtAnsiString: name := string(PChar(param.VAnsiString));
vtWideChar: name := string(param.VWideChar);
vtWideString: name := string(WideString(param.VWideString));
vtUnicodeString: name := string(UnicodeString(param.VUnicodeString));
else
raise Exception.CreateFmt('Parameter name at index %d is not a string value',
[paramIndex div 2]);
end;
Inc(paramIndex);
specifierIndex := paramNames.IndexOf(name);
if specifierIndex > -1 then
paramValues[specifierIndex] := AParams[paramIndex];
Inc(paramIndex);
end;
try
Result := Format(formatString, paramValues, AFormatSettings);
except
on E:EConvertError do
begin
errorMsg := E.Message;
{ Translate specifiers in error messages back to names }
for paramIndex := 0 to Pred(paramNames.Count) do
errorMsg := StringReplace(errorMsg, SpecifierChar + IntToStr(paramIndex) + ':',
SpecifierChar + SpecifierNameStart +
paramNames[paramIndex] + SpecifierNameEnd + ':',
[rfReplaceAll]);
raise EConvertError.Create(errorMsg);
end;
end;
finally
FreeAndNil(paramNames);
end;
end;
{ TNamedFormatStringList }
procedure TNamedFormatStringList.AddLn;
begin
Add('');
end;
function TNamedFormatStringList.Format(AParams: array of const): String;
begin
Result := NamedFormat(Text, AParams);
end;
end.
|
{*******************************************************}
{ }
{ Delphi YouTubeApi Library }
{ }
{ Copyright(c) 2010-2018 Ali Zairov }
{ }
{*******************************************************}
unit azYouTubeApi;
interface
uses
System.SysUtils,
System.Classes,
IdHTTP;
type
TazInfo = record
url,
title,
thumbnailUrl,
description,
channelId,
videoId,
duration,
datePublished,
genre,
embedUrl: string;
width,
height: Integer;
keywords,
author: string;
length_seconds: Integer;
subscriber,
view,
like,
unlike: string;
end;
type
TazYouTubeApi = class(TComponent)
private
FAuthor, FSite, FVersion: string;
FHTTP: TIdHTTP;
function Parse(Source, L, R: string): string;
function SReplace(Source, Old, New: string): string;
function TagClear(Source: string): string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Get(v: string): TazInfo;
published
property Author: string Read FAuthor;
property Site: string Read FSite;
property Version: string Read FVersion;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('AliZairov', [TazYouTubeApi]);
end;
{ TazYouTubeApi }
constructor TazYouTubeApi.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FAuthor := 'Ali Zairov';
FSite := 'http://delphidx.blogspot.com';
FVersion := '1.4';
FHTTP := TIdHTTP.Create(nil);
FHTTP.Request.AcceptLanguage := 'en';
FHTTP.Request.UserAgent := 'Mozilla/5.0';
end;
destructor TazYouTubeApi.Destroy;
begin
FHTTP.Free;
inherited Destroy;
end;
function TazYouTubeApi.Parse(Source, L, R: string): string;
begin
Delete(Source, 1, Pos(L, Source) + Length(L) - 1);
Result := Copy(Source, 1, Pos(R, Source) - 1);
end;
function TazYouTubeApi.SReplace(Source, Old, New: string): string;
begin
Result := StringReplace(Source, Old, New, [rfReplaceAll, rfIgnoreCase]);
end;
function TazYouTubeApi.TagClear(Source: string): string;
var
S: string;
begin
S := Source;
S := SReplace(S, '"', '"');
S := SReplace(S, '&', '&');
S := SReplace(S, '<', '<');
S := SReplace(S, '>', '>');
S := SReplace(S, ' ', ' ');
S := SReplace(S, '©', '©');
S := SReplace(S, ''', '”');
Result := S;
end;
function TazYouTubeApi.Get(v: string): TazInfo;
var
Source, Source2: string;
begin
Source := FHTTP.Get('https://www.youtube.com/watch?v=' + v);
Source2 := Parse(Source, 'ytplayer.config =', ';ytplayer.load');
with Result do
begin
url := Parse(Source, 'og:url" content="', '"');
title := Parse(Source, 'og:title" content="', '"');
thumbnailUrl := Parse(Source, 'og:image" content="', '"');
description := TagClear(Parse(Source, 'og:description" content="', '"'));
channelId := Parse(Source, 'channelId" content="', '"');
videoId := Parse(Source, 'videoId" content="', '"');
duration := Parse(Source, 'duration" content="', '"');
datePublished := Parse(Source, 'datePublished" content="', '"');
genre := Parse(Source, 'genre" content="', '"');
embedUrl := Parse(Source, 'og:video:url" content="', '"');
width := Parse(Source, 'og:video:width" content="', '"').ToInteger;
height := Parse(Source, 'og:video:height" content="', '"').ToInteger;
keywords := Parse(Source2, '"keywords":"', '"');
author := Parse(Source2, 'author":"', '"');
length_seconds := Parse(Source2, 'length_seconds":"', '"').ToInteger;
subscriber := Parse(Source, 'subscriber-count" title="', '"');
view := Trim(Parse(Source, 'watch-view-count">', 'views'));
like := Trim(Parse(Source, 'like this video along with', 'other'));
unlike := Trim(Parse(Source, 'dislike this video along with', 'other'))
end;
end;
end.
|
unit HKSelfUpdater;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LResources, Forms, Controls, Graphics, Dialogs;
type
THKUpdaterProtocol=(UPHTTP, UPHTTPS, UPFTP);
TOnUpdateFound=procedure(aSender:TObject; aChecksum, aVersion:String;
var DoDownload:Boolean)of object;
{ THKSelfUpdater }
THKSelfUpdater = class(TComponent)
private
FArchiveFolder: String;
FAuthToken: String;
FAuthTokenHeaderName: String;
FHost: String;
FOnUpdateFound: TOnUpdateFound;
FPassword: String;
FPath: String;
FPort: Integer;
FProtocol: THKUpdaterProtocol;
FUsername: String;
FVersion: String;
procedure SetArchiveFolder(AValue: String);
procedure SetAuthToken(AValue: String);
procedure SetAuthTokenHeaderName(AValue: String);
procedure SetHost(AValue: String);
procedure SetOnUpdateFound(AValue: TOnUpdateFound);
procedure SetPassword(AValue: String);
procedure SetPath(AValue: String);
procedure SetPort(AValue: Integer);
procedure SetProtocol(AValue: THKUpdaterProtocol);
procedure SetUsername(AValue: String);
protected
procedure DoFoundUpdate(aChecksum, aVersion:String);
procedure DoDownload;
procedure HTTPCheckUpdate;
procedure FTPCheckUpdate;
Function CompareVersion(CloudVersion:String):Boolean;
Procedure CheckVersion;
public
constructor Create(AOwner: TComponent); override;
procedure CheckUpdate;
published
property Host:String read FHost write SetHost;
property Port:Integer read FPort write SetPort;
property Protocol:THKUpdaterProtocol read FProtocol write SetProtocol default UPHTTP;
property Path:String read FPath write SetPath;
property Username:String read FUsername write SetUsername;
property Password:String read FPassword write SetPassword;
property AuthToken:String read FAuthToken write SetAuthToken;
property AuthTokenHeaderName:String read FAuthTokenHeaderName write SetAuthTokenHeaderName;
property OnUpdateFound:TOnUpdateFound read FOnUpdateFound write SetOnUpdateFound;
property ArchiveFolder:String read FArchiveFolder write SetArchiveFolder;
property AppVersion:String read FVersion;
end;
procedure Register;
implementation
uses FileInfo;
procedure Register;
begin
{$I hkselfupdater_icon.lrs}
RegisterComponents('HKCompPacks',[THKSelfUpdater]);
end;
{ THKSelfUpdater }
procedure THKSelfUpdater.SetAuthToken(AValue: String);
begin
if FAuthToken=AValue then Exit;
FAuthToken:=AValue;
end;
procedure THKSelfUpdater.SetArchiveFolder(AValue: String);
begin
if FArchiveFolder=AValue then Exit;
FArchiveFolder:=AValue;
end;
procedure THKSelfUpdater.SetAuthTokenHeaderName(AValue: String);
begin
if FAuthTokenHeaderName=AValue then Exit;
FAuthTokenHeaderName:=AValue;
end;
procedure THKSelfUpdater.SetHost(AValue: String);
begin
if FHost=AValue then Exit;
FHost:=AValue;
end;
procedure THKSelfUpdater.SetOnUpdateFound(AValue: TOnUpdateFound);
begin
if FOnUpdateFound=AValue then Exit;
FOnUpdateFound:=AValue;
end;
procedure THKSelfUpdater.SetPassword(AValue: String);
begin
if FPassword=AValue then Exit;
FPassword:=AValue;
end;
procedure THKSelfUpdater.SetPath(AValue: String);
begin
if FPath=AValue then Exit;
FPath:=AValue;
end;
procedure THKSelfUpdater.SetPort(AValue: Integer);
begin
if FPort=AValue then Exit;
FPort:=AValue;
end;
procedure THKSelfUpdater.SetProtocol(AValue: THKUpdaterProtocol);
begin
if FProtocol=AValue then Exit;
FProtocol:=AValue;
end;
procedure THKSelfUpdater.SetUsername(AValue: String);
begin
if FUsername=AValue then Exit;
FUsername:=AValue;
end;
procedure THKSelfUpdater.DoFoundUpdate(aChecksum, aVersion: String);
var
doContinue: Boolean;
begin
doContinue:=False;
if Assigned(OnUpdateFound) then OnUpdateFound(Self, aChecksum, aVersion, doContinue);
if doContinue then DoDownload;
end;
procedure THKSelfUpdater.DoDownload;
begin
end;
procedure THKSelfUpdater.HTTPCheckUpdate;
begin
end;
procedure THKSelfUpdater.FTPCheckUpdate;
begin
end;
function THKSelfUpdater.CompareVersion(CloudVersion: String): Boolean;
begin
end;
procedure THKSelfUpdater.CheckVersion;
var ver:TFileVersionInfo;
begin
ver:=TFileVersionInfo.Create(Self);
with ver do
begin
try
ReadFileInfo;
FVersion:=VersionStrings.Values['FileVersion'];
finally
Free;
end;
end;
end;
constructor THKSelfUpdater.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Host:='localhost';
Port:=80;
Path:='/';
end;
procedure THKSelfUpdater.CheckUpdate;
begin
case Protocol of
UPHTTPS,
UPHTTP:HTTPCheckUpdate;
UPFTP:FTPCheckUpdate;
end;
end;
end.
|
unit UFrmCadCargo;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrmCadastro, Mask, sMaskEdit, sCustomComboEdit, sTooledit, StdCtrls,
sEdit, sLabel, Buttons, sBitBtn, sGroupBox, UCargo, UCtrlCargo;
type
TFrmCadCargo = class(TFrmCadastro)
lbl_Codigo: TsLabel;
lbl_Cargo: TsLabel;
lbl_DataCadastro: TsLabel;
lbl_DataAlteracao: TsLabel;
edt_IdCargo: TsEdit;
edt_Cargo: TsEdit;
edt_DataCadastro: TsDateEdit;
edt_DataAlteracao: TsDateEdit;
procedure btn_SalvarClick(Sender: TObject);
procedure btn_SairClick(Sender: TObject);
private
{ Private declarations }
UmCargo : Cargo;
umaCtrlCargo : CtrlCargo;
public
{ Public declarations }
procedure ConhecaObjeto(vCargo: Cargo; vCtrlCargo : CtrlCargo);
procedure HabilitaCampos;
procedure LimpaCampos;
procedure CarregaObj;
end;
var
FrmCadCargo: TFrmCadCargo;
implementation
{$R *.dfm}
{ TFrmCadCargo }
procedure TFrmCadCargo.btn_SairClick(Sender: TObject);
begin
inherited;
self.HabilitaCampos;
end;
procedure TFrmCadCargo.btn_SalvarClick(Sender: TObject);
var
dataAtual : TDateTime;
msg: string;
begin
inherited;
dataAtual := Date;
if edt_Cargo.Text = '' then
begin
ShowMessage('Campo País não pode estar em branco!');
edt_Cargo.SetFocus;
end
else
if self.btn_Salvar.Caption = 'Salvar' then
begin
UmCargo.setDescricao(edt_Cargo.Text);
UmCargo.setDataCadastro(edt_DataCadastro.Date);
if self.edt_DataAlteracao.Date <> dataAtual then
UmCargo.setDataAlteracao(dataAtual);
msg := umaCtrlCargo.Salvar(UmCargo);
if Copy(msg,0,16) = 'Ocorreu um erro!' then
Application.MessageBox(PChar(msg), 'Erro!', MB_OK + MB_ICONSTOP)
else
ShowMessage(msg);
Close;
end
else
if self.btn_Salvar.Caption = 'Excluir' then
begin
msg := umaCtrlCargo.Excluir(umCargo);
showmessage(msg);
self.HabilitaCampos;
self.btn_Salvar.Caption := 'Salvar';
close;
end;
UmCargo.CrieObjeto;
end;
procedure TFrmCadCargo.CarregaObj;
begin
Self.edt_IdCargo.Text := IntToStr(umCargo.getId);
Self.edt_Cargo.Text := UmCargo.getDescricao;
Self.edt_DataCadastro.Date := umCargo.getDataCadastro;
Self.edt_DataAlteracao.Date := umCargo.getDataAlteracao;
end;
procedure TFrmCadCargo.ConhecaObjeto(vCargo: Cargo; vCtrlCargo: CtrlCargo);
begin
umCargo := vCargo;
umaCtrlCargo := vCtrlCargo;
Self.HabilitaCampos;
Self.LimpaCampos;
end;
procedure TFrmCadCargo.HabilitaCampos;
begin
Self.btn_Salvar.Caption := 'Salvar';
self.edt_Cargo.Enabled := True;
end;
procedure TFrmCadCargo.LimpaCampos;
var dataAtual : TDateTime;
begin
dataAtual := Date;
Self.edt_IdCargo.Clear;
Self.edt_Cargo.Clear;
Self.edt_DataCadastro.Date := dataAtual;
Self.edt_DataAlteracao.Date := dataAtual;
end;
end.
|
unit BCEditor.Editor.Search.Map.Colors;
interface
uses
Classes, Graphics, BCEditor.Consts, BCEditor.Types;
type
TBCEditorSearchMapColors = class(TPersistent)
strict private
FActiveLine: TColor;
FBackground: TColor;
FForeground: TColor;
FOnChange: TBCEditorSearchChangeEvent;
procedure SetActiveLine(Value: TColor);
procedure SetBackground(Value: TColor);
procedure SetForeground(Value: TColor);
public
constructor Create;
procedure Assign(Source: TPersistent); override;
published
property ActiveLine: TColor read FActiveLine write SetActiveLine default clLeftMarginBookmarkBackground;
property Background: TColor read FBackground write SetBackground default clLeftMarginBackground;
property Foreground: TColor read FForeground write SetForeground default clSearchHighlighter;
property OnChange: TBCEditorSearchChangeEvent read FOnChange write FOnChange;
end;
implementation
{ TBCEditorSelectedColor }
constructor TBCEditorSearchMapColors.Create;
begin
inherited;
FActiveLine := clLeftMarginBookmarkBackground;
FBackground := clLeftMarginBackground;
FForeground := clSearchHighlighter;
end;
procedure TBCEditorSearchMapColors.Assign(Source: TPersistent);
begin
if Assigned(Source) and (Source is TBCEditorSearchMapColors) then
with Source as TBCEditorSearchMapColors do
begin
Self.FBackground := FBackground;
Self.FForeground := FForeground;
Self.FActiveLine := FActiveLine;
if Assigned(Self.FOnChange) then
Self.FOnChange(scRefresh);
end
else
inherited Assign(Source);
end;
procedure TBCEditorSearchMapColors.SetActiveLine(Value: TColor);
begin
if FActiveLine <> Value then
begin
FActiveLine := Value;
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
end;
procedure TBCEditorSearchMapColors.SetBackground(Value: TColor);
begin
if FBackground <> Value then
begin
FBackground := Value;
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
end;
procedure TBCEditorSearchMapColors.SetForeground(Value: TColor);
begin
if FForeground <> Value then
begin
FForeground := Value;
if Assigned(FOnChange) then
FOnChange(scRefresh);
end;
end;
end.
|
unit typename_6;
interface
implementation
function GetTypeName<T>: string;
begin
result := typename(T);
end;
var S: string;
procedure Test;
begin
S := GetTypeName<Int32>();
end;
initialization
Test();
finalization
Assert(S = 'Int32');
end. |
unit ComponentsBaseView;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, GridFrame,
cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles,
cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator, Data.DB,
cxDBData, System.Actions, Vcl.ActnList, dxBar, cxClasses, Vcl.ComCtrls,
cxGridLevel, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridBandedTableView, cxGridDBBandedTableView, cxGrid, NotifyEvents,
cxEditRepositoryItems, cxExtEditRepositoryItems, SubGroupsQuery,
SubGroupListPopupForm, cxLabel, cxDBLookupComboBox, cxDropDownEdit,
cxButtonEdit, cxGridCustomPopupMenu, cxGridPopupMenu, Vcl.Menus,
System.Generics.Collections, dxSkinsCore, dxSkinBlack,
dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom,
dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy,
dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian,
dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMetropolis,
dxSkinMetropolisDark, dxSkinMoneyTwins, dxSkinOffice2007Black,
dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink,
dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue,
dxSkinOffice2010Silver, dxSkinOffice2013DarkGray, dxSkinOffice2013LightGray,
dxSkinOffice2013White, dxSkinOffice2016Colorful, dxSkinOffice2016Dark,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine,
dxSkinVisualStudio2013Blue, dxSkinVisualStudio2013Dark,
dxSkinVisualStudio2013Light, dxSkinVS2010, dxSkinWhiteprint,
dxSkinXmas2008Blue, dxSkinscxPCPainter, dxSkinsdxBarPainter,
CustomComponentsQuery, cxTextEdit, cxBlobEdit, cxRichEdit,
DescriptionPopupForm, DocFieldInfo, OpenDocumentUnit, ProjectConst,
cxDataControllerConditionalFormattingRulesManagerDialog, dxBarBuiltInMenu,
System.Contnrs, BaseComponentsGroupUnit2, DSWrap, dxDateRanges, ColInfo;
const
// WM_ON_DETAIL_EXPANDED = WM_USER + 57;
WM_UPDATE_DETAIL_COLUMNS_WIDTH = WM_USER + 58;
WM_FOCUS_TOP_LEFT = WM_USER + 59;
type
TColBtn = class(TObject)
private
FCol: TcxGridDBBandedColumn;
FLoadAction: TAction;
FOpenAction: TAction;
public
constructor Create(ACol: TcxGridDBBandedColumn;
AOpenAction, ALoadAction: TAction);
property Col: TcxGridDBBandedColumn read FCol;
property LoadAction: TAction read FLoadAction;
property OpenAction: TAction read FOpenAction;
end;
TViewComponentsBase = class(TfrmGrid)
cxerlSubGroup: TcxEditRepositoryLabel;
cxerpiSubGroup: TcxEditRepositoryPopupItem;
actSettings: TAction;
actPasteComponents: TAction;
N3: TMenuItem;
actPasteProducer: TAction;
N4: TMenuItem;
actPastePackagePins: TAction;
N5: TMenuItem;
actPasteFamily: TAction;
N2: TMenuItem;
actOpenDatasheet: TAction;
actLoadDatasheet: TAction;
actOpenDiagram: TAction;
actLoadDiagram: TAction;
actOpenImage: TAction;
actLoadImage: TAction;
actOpenDrawing: TAction;
actLoadDrawing: TAction;
cxGridLevel2: TcxGridLevel;
cxGridDBBandedTableView2: TcxGridDBBandedTableView;
actCommit: TAction;
actRollback: TAction;
cxertiValue: TcxEditRepositoryTextItem;
cxertiValueRO: TcxEditRepositoryTextItem;
cxFieldValueWithExpand: TcxEditRepositoryButtonItem;
cxFieldValueWithExpandRO: TcxEditRepositoryButtonItem;
actDeleteFromAllCategories: TAction;
cxEditRepository1: TcxEditRepository;
actAddFamily: TAction;
actAddComponent: TAction;
actFocusTopLeft: TAction;
procedure actAddComponentExecute(Sender: TObject);
procedure actAddFamilyExecute(Sender: TObject);
procedure actCommitExecute(Sender: TObject);
procedure actDeleteFromAllCategoriesExecute(Sender: TObject);
procedure actFocusTopLeftExecute(Sender: TObject);
procedure actLoadDatasheetExecute(Sender: TObject);
procedure actLoadDiagramExecute(Sender: TObject);
procedure actLoadDrawingExecute(Sender: TObject);
procedure actLoadImageExecute(Sender: TObject);
procedure actOpenDatasheetExecute(Sender: TObject);
procedure actOpenDiagramExecute(Sender: TObject);
procedure actOpenDrawingExecute(Sender: TObject);
procedure actOpenImageExecute(Sender: TObject);
procedure actPasteComponentsExecute(Sender: TObject);
procedure actPastePackagePinsExecute(Sender: TObject);
procedure actPasteFamilyExecute(Sender: TObject);
procedure actPasteProducerExecute(Sender: TObject);
procedure actRollbackExecute(Sender: TObject);
procedure actSettingsExecute(Sender: TObject);
procedure clSubGroup2GetProperties(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AProperties: TcxCustomEditProperties);
procedure clSubGroupGetProperties(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AProperties: TcxCustomEditProperties);
procedure cxerpiSubGroup_PropertiesCloseUp(Sender: TObject);
procedure cxerpiSubGroup_PropertiesInitPopup(Sender: TObject);
procedure clBodyIdPropertiesNewLookupDisplayText(Sender: TObject;
const AText: TCaption);
procedure clDatasheetGetDataText(Sender: TcxCustomGridTableItem;
ARecordIndex: Integer; var AText: string);
procedure cxGridDBBandedTableViewColumnHeaderClick(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure clDescriptionPropertiesInitPopup(Sender: TObject);
procedure clValue2GetProperties(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AProperties: TcxCustomEditProperties);
procedure clValue2GetPropertiesForEdit(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AProperties: TcxCustomEditProperties);
procedure clValueGetProperties(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AProperties: TcxCustomEditProperties);
procedure clValueGetPropertiesForEdit(Sender: TcxCustomGridTableItem;
ARecord: TcxCustomGridRecord; var AProperties: TcxCustomEditProperties);
procedure cxGridDBBandedTableViewSelectionChanged
(Sender: TcxCustomGridTableView);
procedure cxFieldValueWithExpandPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure cxGridDBBandedTableView2CellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxGridDBBandedTableView2EditKeyDown
(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState);
procedure cxGridDBBandedTableView2LeftPosChanged(Sender: TObject);
procedure cxGridDBBandedTableViewBandSizeChanged
(Sender: TcxGridBandedTableView; ABand: TcxGridBand);
procedure cxGridDBBandedTableViewCellClick(Sender: TcxCustomGridTableView;
ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton;
AShift: TShiftState; var AHandled: Boolean);
procedure cxGridDBBandedTableViewColumnSizeChanged(Sender: TcxGridTableView;
AColumn: TcxGridColumn);
procedure cxGridDBBandedTableViewEditKeyUp(Sender: TcxCustomGridTableView;
AItem: TcxCustomGridTableItem; AEdit: TcxCustomEdit; var Key: Word;
Shift: TShiftState);
procedure cxGridDBBandedTableViewEditValueChanged
(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
procedure cxGridDBBandedTableViewLeftPosChanged(Sender: TObject);
procedure cxGridDBBandedTableViewDataControllerDetailExpanded
(ADataController: TcxCustomDataController; ARecordIndex: Integer);
private
FBaseCompGrp: TBaseComponentsGroup2;
FCountEvents: TObjectList;
FDeleteFromAllCategories: Boolean;
FEditingValue: Variant;
FfrmDescriptionPopup: TfrmDescriptionPopup;
FfrmSubgroupListPopup: TfrmSubgroupListPopup;
FIsSyncScrollbars: Boolean;
FMessageUpdateDetailColumnsPosted: Boolean;
FNeedApplyBestFit: Boolean;
FqSubGroups: TfrmQuerySubGroups;
procedure DoAfterCommit(Sender: TObject);
procedure DoOnDescriptionPopupHide(Sender: TObject);
procedure DoOnUpdateComponentsCount(Sender: TObject);
procedure DoOnUpdateFamilyCount(Sender: TObject);
function GetclID: TcxGridDBBandedColumn;
function GetclID2: TcxGridDBBandedColumn;
function GetclValue: TcxGridDBBandedColumn;
function GetclProducer: TcxGridDBBandedColumn;
function GetclSubGroup: TcxGridDBBandedColumn;
function GetclDescription: TcxGridDBBandedColumn;
function GetclDatasheet: TcxGridDBBandedColumn;
function GetclImage: TcxGridDBBandedColumn;
function GetclDiagram: TcxGridDBBandedColumn;
function GetclDrawing: TcxGridDBBandedColumn;
function GetclPackagePins: TcxGridDBBandedColumn;
function GetclValue2: TcxGridDBBandedColumn;
function GetFocusedQuery: TQueryCustomComponents;
function GetfrmSubgroupListPopup: TfrmSubgroupListPopup;
function GetProducerDisplayText: string;
function GetqSubGroups: TfrmQuerySubGroups;
procedure SetBaseCompGrp(const Value: TBaseComponentsGroup2);
procedure SyncScrollbarPositions;
procedure UpdateSelectedCount;
procedure UpdateSelectedValues(AView: TcxGridDBBandedTableView);
procedure UpdateTotalComponentCount;
{ Private declarations }
protected
procedure CreateCountEvents;
procedure ClearCountEvents;
function CreateColInfoArray: TArray<TColInfo>; virtual;
procedure CreateColumnsBarButtons; override;
function CreateViewArr: TArray<TcxGridDBBandedTableView>; override;
procedure Create_Columns;
procedure DoAfterLoadData; virtual;
procedure DoAfterOpenOrRefresh(Sender: TObject);
procedure DoBeforeOpenOrRefresh(Sender: TObject);
procedure DoOnFocusTopLeft(var Message: TMessage);
message WM_FOCUS_TOP_LEFT;
procedure DoOnHaveAnyChanges(Sender: TObject);
procedure DoOnMasterDetailChange; virtual;
procedure DoOnUpdateColumnsWidth(var Message: TMessage);
message WM_UPDATE_DETAIL_COLUMNS_WIDTH;
function ExpandDetail: TcxGridDBBandedTableView;
procedure InitBands;
procedure InitComponentsColumns; virtual;
procedure InitView(AView: TcxGridDBBandedTableView); override;
procedure InternalRefreshData; override;
procedure MyDelete; override;
procedure MyInitializeComboBoxColumn;
procedure OnGridRecordCellPopupMenu(AColumn: TcxGridDBBandedColumn;
var AllowPopup: Boolean); override;
procedure OpenDoc(ADocFieldInfo: TDocFieldInfo);
procedure PostMessageUpdateDetailColumnsWidth;
procedure UpdateDetailColumnsWidth;
procedure UploadDoc(ADocFieldInfo: TDocFieldInfo);
property FocusedQuery: TQueryCustomComponents read GetFocusedQuery;
property frmSubgroupListPopup: TfrmSubgroupListPopup
read GetfrmSubgroupListPopup;
property qSubGroups: TfrmQuerySubGroups read GetqSubGroups;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BeginUpdate; override;
function CheckAndSaveChanges: Integer;
procedure EndUpdate; override;
procedure FocusTopLeftEx;
procedure TryApplyBestFit;
procedure UpdateView; override;
property BaseCompGrp: TBaseComponentsGroup2 read FBaseCompGrp
write SetBaseCompGrp;
property clID: TcxGridDBBandedColumn read GetclID;
property clID2: TcxGridDBBandedColumn read GetclID2;
property clValue: TcxGridDBBandedColumn read GetclValue;
property clProducer: TcxGridDBBandedColumn read GetclProducer;
property clSubGroup: TcxGridDBBandedColumn read GetclSubGroup;
property clDescription: TcxGridDBBandedColumn read GetclDescription;
property clDatasheet: TcxGridDBBandedColumn read GetclDatasheet;
property clImage: TcxGridDBBandedColumn read GetclImage;
property clDiagram: TcxGridDBBandedColumn read GetclDiagram;
property clDrawing: TcxGridDBBandedColumn read GetclDrawing;
property clPackagePins: TcxGridDBBandedColumn read GetclPackagePins;
property clValue2: TcxGridDBBandedColumn read GetclValue2;
property ProducerDisplayText: string read GetProducerDisplayText;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses GridExtension, dxCore, System.Math, System.StrUtils, cxDataUtils,
System.IOUtils, Winapi.ShellAPI, RepositoryDataModule, System.UITypes,
ColumnsBarButtonsHelper, DialogUnit, Vcl.Clipbrd, PathSettingsForm,
ClipboardUnit, DefaultParameters, ProducersQuery, cxGridDBDataDefinitions,
GridSort;
constructor TViewComponentsBase.Create(AOwner: TComponent);
var
AView: TcxGridDBBandedTableView;
begin
inherited;
// Форма с кодами категорий
cxerpiSubGroup.Properties.PopupControl := frmSubgroupListPopup;
FCountEvents := TObjectList.Create;
StatusBarEmptyPanelIndex := 3;
DeleteMessages.Add(cxGridLevel, sDoYouWantToDeleteFamily);
DeleteMessages.Add(cxGridLevel2, sDoYouWantToDeleteComponent);
ApplyBestFitForDetail := False;
// Чтобы убрать значки своравчивания/разворачивания слева от записи грида
// Создаём новое представление своего типа
AView := cxGrid.CreateView(TcxGridDBBandedTableViewWithoutExpand)
as TcxGridDBBandedTableView;
// Копируем в новое представление все события
AView.Assign(cxGridDBBandedTableView);
// Новое представление будет отображаться на первом уровне
cxGridLevel.GridView := AView;
cxGridDBBandedTableView.Free;
end;
destructor TViewComponentsBase.Destroy;
begin
FreeAndNil(FCountEvents);
inherited;
end;
procedure TViewComponentsBase.actAddComponentExecute(Sender: TObject);
var
AView: TcxGridDBBandedTableView;
begin
// Сначала сохраняем семейство компонентов
BaseCompGrp.qBaseFamily.W.TryPost;
// Разворачиваем представление 2-го уровня
AView := ExpandDetail;
// Сначала добавляем запись, потом разворачиваем
AView.DataController.Append;
FocusColumnEditor(AView, BaseCompGrp.qBaseComponents.W.Value.FieldName);
UpdateView;
end;
procedure TViewComponentsBase.actAddFamilyExecute(Sender: TObject);
var
AView: TcxGridDBBandedTableView;
begin
AView := GetDBBandedTableView(0);
AView.Focused := True;
AView.DataController.Append;
FocusColumnEditor(AView, BaseCompGrp.qBaseFamily.W.Value.FieldName);
UpdateView;
end;
procedure TViewComponentsBase.actCommitExecute(Sender: TObject);
begin
inherited;
BaseCompGrp.Commit;
UpdateView;
end;
procedure TViewComponentsBase.actDeleteFromAllCategoriesExecute
(Sender: TObject);
begin
inherited;
FDeleteFromAllCategories := True;
try
MyDelete;
finally
FDeleteFromAllCategories := False;
end;
end;
procedure TViewComponentsBase.actFocusTopLeftExecute(Sender: TObject);
begin
inherited;
FocusTopLeft;
end;
procedure TViewComponentsBase.actLoadDatasheetExecute(Sender: TObject);
begin
UploadDoc(TComponentDatasheetDoc.Create);
end;
procedure TViewComponentsBase.actLoadDiagramExecute(Sender: TObject);
begin
UploadDoc(TComponentDiagramDoc.Create);
end;
procedure TViewComponentsBase.actLoadDrawingExecute(Sender: TObject);
begin
UploadDoc(TComponentDrawingDoc.Create);
end;
procedure TViewComponentsBase.actLoadImageExecute(Sender: TObject);
begin
UploadDoc(TComponentImageDoc.Create);
end;
procedure TViewComponentsBase.actOpenDatasheetExecute(Sender: TObject);
begin
OpenDoc(TComponentDatasheetDoc.Create);
end;
procedure TViewComponentsBase.actOpenDiagramExecute(Sender: TObject);
begin
OpenDoc(TComponentDiagramDoc.Create);
end;
procedure TViewComponentsBase.actOpenDrawingExecute(Sender: TObject);
begin
OpenDoc(TComponentDrawingDoc.Create);
end;
procedure TViewComponentsBase.actOpenImageExecute(Sender: TObject);
begin
OpenDoc(TComponentImageDoc.Create);
end;
procedure TViewComponentsBase.actPasteComponentsExecute(Sender: TObject);
var
// AColumn: TcxGridDBBandedColumn;
ARow: TcxMyGridMasterDataRow;
AView: TcxGridDBBandedTableView;
m: TArray<String>;
begin
m := TClb.Create.GetRowsAsArray;
if Length(m) = 0 then
Exit;
// Сначала сохраняем семейство компонентов
BaseCompGrp.qBaseFamily.W.TryPost;
ARow := GetRow(0) as TcxMyGridMasterDataRow;
Assert(ARow <> nil);
AView := GetDBBandedTableView(1);
ARow.MyExpand(False);
AView.Focused := True;
// Просим добавить дочерние компоненты
BaseCompGrp.qBaseComponents.W.AppendRows
(BaseCompGrp.qBaseComponents.W.Value.FieldName, m);
UpdateView;
end;
procedure TViewComponentsBase.actPastePackagePinsExecute(Sender: TObject);
var
AID: Integer;
AIDList: TArray<Integer>;
m: TArray<String>;
begin
m := TClb.Create.GetRowsAsArray;
if (Length(m) = 0) or (GetFocusedQuery = nil) then
Exit;
AIDList := GetSelectedIntValues(FocusedTableView, clID.Index);
for AID in AIDList do
GetFocusedQuery.W.SetPackagePins(AID, m[0]);
UpdateView;
end;
procedure TViewComponentsBase.actPasteFamilyExecute(Sender: TObject);
begin
// Если в буфере обмена ничего нет
if Clipboard.AsText.Trim.IsEmpty then
Exit;
MainView.BeginUpdate();
try
// Просим добавить родительские компоненты
BaseCompGrp.qBaseFamily.W.AppendRows
(BaseCompGrp.qBaseFamily.W.Value.FieldName, TClb.Create.GetRowsAsArray);
finally
MainView.EndUpdate;
end;
PostMyApplyBestFitEvent;
PutInTheCenterFocusedRecord(MainView);
UpdateView;
end;
procedure TViewComponentsBase.actPasteProducerExecute(Sender: TObject);
var
AID: Integer;
AIDList: TArray<Integer>;
AProducer: string;
m: TArray<String>;
begin
m := TClb.Create.GetRowsAsArray;
if (Length(m) = 0) or (GetFocusedQuery = nil) then
Exit;
AProducer := m[0].Trim;
Assert(BaseCompGrp.Producers <> nil);
Assert(BaseCompGrp.Producers.FDQuery.Active);
// Вставлять можно только то, что есть в справочнике
if not BaseCompGrp.Producers.Locate(AProducer) then
begin
TDialog.Create.ProducerNotFound(AProducer);
Exit;
end;
Assert(clID.Index = clID2.Index);
AIDList := GetSelectedIntValues(FocusedTableView, clID.Index);
BeginUpdate;
try
for AID in AIDList do
GetFocusedQuery.W.SetProducer(AID, AProducer);
finally
EndUpdate;
end;
UpdateView;
end;
procedure TViewComponentsBase.actRollbackExecute(Sender: TObject);
begin
inherited;
BeginUpdate();
try
BaseCompGrp.Rollback;
finally
EndUpdate;
end;
UpdateView;
end;
procedure TViewComponentsBase.actSettingsExecute(Sender: TObject);
var
frmPathSettings: TfrmPathSettings;
begin
frmPathSettings := TfrmPathSettings.Create(Self);
try
frmPathSettings.cxPageControl.ActivePage := frmPathSettings.cxtshComponents;
frmPathSettings.ShowModal;
finally
FreeAndNil(frmPathSettings);
end;
end;
procedure TViewComponentsBase.BeginUpdate;
begin
// Отписываемся от событий о смене кол-ва
if UpdateCount = 0 then
ClearCountEvents;
inherited;
end;
function TViewComponentsBase.CheckAndSaveChanges: Integer;
begin
Result := 0;
if FBaseCompGrp = nil then
Exit;
UpdateView;
// Если есть несохранённые изменения
if BaseCompGrp.HaveAnyChanges then
begin
Result := TDialog.Create.SaveDataDialog;
case Result of
IDYes:
actCommit.Execute;
IDNO:
actRollback.Execute;
end;
end;
end;
procedure TViewComponentsBase.clBodyIdPropertiesNewLookupDisplayText
(Sender: TObject; const AText: TCaption);
begin
inherited;
// DM.BodyTypesMasterDetail.qBodyTypes2.AddNewValue(AText);
end;
procedure TViewComponentsBase.clDatasheetGetDataText
(Sender: TcxCustomGridTableItem; ARecordIndex: Integer; var AText: string);
begin
inherited;
if not AText.IsEmpty then
AText := TPath.GetFileNameWithoutExtension(AText);
end;
procedure TViewComponentsBase.clDescriptionPropertiesInitPopup(Sender: TObject);
begin
inherited;
Assert(FfrmDescriptionPopup <> nil);
// Привязываем выпадающую форму к данным
FfrmDescriptionPopup.DescriptionW := BaseCompGrp.qBaseFamily.W;
end;
procedure TViewComponentsBase.clSubGroup2GetProperties
(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AProperties: TcxCustomEditProperties);
begin
AProperties := cxerlSubGroup.Properties;
end;
procedure TViewComponentsBase.clSubGroupGetProperties
(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AProperties: TcxCustomEditProperties);
begin
if ARecord = nil then
Exit;
AProperties := cxerpiSubGroup.Properties;
end;
procedure TViewComponentsBase.CreateCountEvents;
begin
// Подписываемся на события чтобы отслеживать кол-во
Assert(FCountEvents.Count = 0);
TNotifyEventWrap.Create(BaseCompGrp.qBaseFamily.W.AfterPostM,
DoOnUpdateFamilyCount, FCountEvents);
TNotifyEventWrap.Create(BaseCompGrp.qBaseFamily.W.AfterOpen,
DoOnUpdateFamilyCount, FCountEvents);
TNotifyEventWrap.Create(BaseCompGrp.qBaseFamily.W.AfterDelete,
DoOnUpdateFamilyCount, FCountEvents);
TNotifyEventWrap.Create(BaseCompGrp.qBaseComponents.W.AfterPostM,
DoOnUpdateComponentsCount, FCountEvents);
TNotifyEventWrap.Create(BaseCompGrp.qBaseComponents.W.AfterOpen,
DoOnUpdateComponentsCount, FEventList);
TNotifyEventWrap.Create(BaseCompGrp.qBaseComponents.W.AfterDelete,
DoOnUpdateComponentsCount, FCountEvents);
DoOnUpdateComponentsCount(nil);
DoOnUpdateFamilyCount(nil);
UpdateTotalComponentCount;
end;
procedure TViewComponentsBase.ClearCountEvents;
begin
// Отписываемся от событий чтобы отслеживать кол-во
FCountEvents.Clear;
end;
procedure TViewComponentsBase.clValue2GetProperties
(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AProperties: TcxCustomEditProperties);
begin
if ARecord = nil then
Exit;
// В режиме просмотра - доступ только для чтения
AProperties := cxertiValueRO.Properties
end;
procedure TViewComponentsBase.clValue2GetPropertiesForEdit
(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AProperties: TcxCustomEditProperties);
var
AReadOnly: Boolean;
V: Variant;
begin
if ARecord = nil then
Exit;
V := ARecord.Values[clID2.Index];
// В режиме редактирования - доступ в зависимости от состояния
AReadOnly := (not VarIsNull(V)) and
(not BaseCompGrp.qBaseComponents.W.IsRecordModifed(V));
if AReadOnly then
AProperties := cxertiValueRO.Properties
else
AProperties := cxertiValue.Properties
end;
procedure TViewComponentsBase.clValueGetProperties
(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AProperties: TcxCustomEditProperties);
var
AID: Integer;
HavDetails: Boolean;
V: Variant;
begin
if ARecord = nil then
Exit;
HavDetails := False;
if BaseCompGrp <> nil then
begin
V := ARecord.Values[clID.Index];
if not VarIsNull(V) then
begin
AID := V;
HavDetails := BaseCompGrp.qBaseComponents.Exists(AID);
end;
end;
if HavDetails then
begin
AProperties := cxFieldValueWithExpandRO.Properties
end
else
begin
AProperties := cxertiValueRO.Properties
end;
end;
procedure TViewComponentsBase.clValueGetPropertiesForEdit
(Sender: TcxCustomGridTableItem; ARecord: TcxCustomGridRecord;
var AProperties: TcxCustomEditProperties);
var
AID: Integer;
AReadOnly: Boolean;
HavDetails: Boolean;
V: Variant;
begin
if ARecord = nil then
Exit;
AReadOnly := False;
HavDetails := False;
// Получаем значение первичного ключа
V := ARecord.Values[clID.Index];
if not VarIsNull(V) then
begin
AID := V;
// Смотрим, есть ли у семейства компоненты
HavDetails := BaseCompGrp.qBaseComponents.Exists(AID);
// Только для чтения те записи, которые не модифицировались
AReadOnly := not BaseCompGrp.qBaseFamily.W.IsRecordModifed(AID);
end;
if HavDetails then
begin
if AReadOnly then
AProperties := cxFieldValueWithExpandRO.Properties
else
AProperties := cxFieldValueWithExpand.Properties
end
else
begin
if AReadOnly then
AProperties := cxertiValueRO.Properties
else
AProperties := cxertiValue.Properties;
end;
end;
function TViewComponentsBase.CreateColInfoArray: TArray<TColInfo>;
Var
W: TCustomComponentsW;
begin
W := BaseCompGrp.qBaseFamily.W;
Result := [TColInfo.Create(W.ID, 0), TColInfo.Create(W.Value, 0),
TColInfo.Create(W.Producer, 1), TColInfo.Create(W.SubGroup, 1),
TColInfo.Create(W.DescriptionComponentName, 1), TColInfo.Create(W.Datasheet,
1), TColInfo.Create(W.Diagram, 1), TColInfo.Create(W.Drawing, 1),
TColInfo.Create(W.Image, 1), TColInfo.Create(W.PackagePins, 1)]
end;
procedure TViewComponentsBase.CreateColumnsBarButtons;
begin
// Меню будем создавать только после создания всех колонок
end;
function TViewComponentsBase.CreateViewArr: TArray<TcxGridDBBandedTableView>;
begin
Result := [MainView, cxGridDBBandedTableView2];
end;
procedure TViewComponentsBase.Create_Columns;
var
// ABand: TcxGridBand;
ACol: TcxGridDBBandedColumn;
AColInfo: TColInfo;
Arr: TArray<TColInfo>;
AView: TcxGridDBBandedTableView;
begin
if (MainView.ColumnCount > 1) then
Exit;
Arr := CreateColInfoArray;
for AColInfo in Arr do
begin
for AView in ViewArr do
begin
ACol := AView.CreateColumn;
ACol.Visible := AColInfo.FieldWrap.DisplayLabel <> '';
ACol.VisibleForCustomization := ACol.Visible;
ACol.Caption := AColInfo.FieldWrap.DisplayLabel;
ACol.DataBinding.FieldName := AColInfo.FieldWrap.FieldName;
// Если такого бэнда не существует
while AView.Bands.Count <= AColInfo.BandIndex do
{ ABand := } AView.Bands.Add;
if AColInfo.BandCaption <> '' then
AView.Bands[AColInfo.BandIndex].Caption := AColInfo.BandCaption;
ACol.Position.BandIndex := AColInfo.BandIndex;
end;
end;
InitComponentsColumns;
InitBands;
end;
procedure TViewComponentsBase.cxerpiSubGroup_PropertiesCloseUp(Sender: TObject);
var
ParamValue: string;
begin
Assert(qSubGroups.FDQuery.Active);
ParamValue := qSubGroups.W.ExternalID.AllValues(',');
if BaseCompGrp.qBaseFamily.W.SubGroup.F.AsString = ParamValue then
Exit;
BaseCompGrp.qBaseFamily.FDQuery.DisableControls;
try
BaseCompGrp.qBaseFamily.W.TryEdit;
BaseCompGrp.qBaseFamily.W.SubGroup.F.AsString := ParamValue;
BaseCompGrp.qBaseFamily.W.TryPost;
finally
BaseCompGrp.qBaseFamily.FDQuery.EnableControls;
end;
UpdateView;
end;
procedure TViewComponentsBase.cxerpiSubGroup_PropertiesInitPopup
(Sender: TObject);
var
AMainExternalID: string;
S: string;
begin
S := BaseCompGrp.qBaseFamily.W.SubGroup.F.AsString;
// Удаляем все пробелы из строки. Должны остаться только цифры и запятые
S := S.Replace(' ', '', [rfReplaceAll]);
Assert(S.Length > 0);
AMainExternalID := BaseCompGrp.qBaseFamily.CategoryExternalID;
qSubGroups.Search(AMainExternalID, Format(',%s,', [S]));
frmSubgroupListPopup.QuerySubGroups := qSubGroups;
end;
procedure TViewComponentsBase.cxFieldValueWithExpandPropertiesButtonClick
(Sender: TObject; AButtonIndex: Integer);
var
ASender, AParent: TComponent;
AGridSite: TcxGridSite;
ACustomGridView: TcxCustomGridView;
begin
ASender := Sender as TComponent;
AParent := ASender.GetParentComponent;
AGridSite := AParent as TcxGridSite;
if AGridSite <> nil then
begin
ACustomGridView := AGridSite.GridView;
with (ACustomGridView as TcxGridTableView).Controller do
begin
if (FocusedRow as TcxMyGridMasterDataRow).Expanded then
// если уже был развёрнут - свернуть
begin
(FocusedRow as TcxMyGridMasterDataRow).MyCollapse(True);
end
else // иначе - развернуть
begin
(FocusedRow as TcxMyGridMasterDataRow).MyExpand(True);
end;
end;
end;
end;
procedure TViewComponentsBase.cxGridDBBandedTableView2CellClick
(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
UpdateDetailColumnsWidth;
end;
procedure TViewComponentsBase.cxGridDBBandedTableView2EditKeyDown
(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState);
begin
inherited;
DoOnEditKeyDown(Sender, AItem, AEdit, Key, Shift);
end;
procedure TViewComponentsBase.cxGridDBBandedTableView2LeftPosChanged
(Sender: TObject);
begin
inherited;
SyncScrollbarPositions;
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewBandSizeChanged
(Sender: TcxGridBandedTableView; ABand: TcxGridBand);
begin
inherited;
PostMessageUpdateDetailColumnsWidth;
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewCellClick
(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo;
AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean);
begin
inherited;
UpdateDetailColumnsWidth;
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewColumnHeaderClick
(Sender: TcxGridTableView; AColumn: TcxGridColumn);
begin
inherited;
ApplySort(Sender, AColumn);
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewColumnSizeChanged
(Sender: TcxGridTableView; AColumn: TcxGridColumn);
begin
inherited;
PostMessageUpdateDetailColumnsWidth;
end;
procedure TViewComponentsBase.
cxGridDBBandedTableViewDataControllerDetailExpanded(ADataController
: TcxCustomDataController; ARecordIndex: Integer);
begin
inherited;
UpdateDetailColumnsWidth;
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewEditKeyUp
(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem;
AEdit: TcxCustomEdit; var Key: Word; Shift: TShiftState);
begin
inherited;
FEditingValue := AEdit.EditingValue;
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewEditValueChanged
(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem);
var
AView: TcxGridDBBandedTableView;
begin
inherited;
AView := Sender as TcxGridDBBandedTableView;
if AView.Controller.SelectedRecordCount <= 1 then
Exit;
if AView.DataController.DataSet.State <> dsEdit then
Exit;
// Это для того чтобы редактируемое в ячейке значение распространить на несколько выделенных записей
UpdateSelectedValues(AView);
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewLeftPosChanged
(Sender: TObject);
begin
inherited;
SyncScrollbarPositions;
end;
procedure TViewComponentsBase.cxGridDBBandedTableViewSelectionChanged
(Sender: TcxCustomGridTableView);
begin
inherited;
UpdateSelectedCount;
end;
procedure TViewComponentsBase.DoAfterCommit(Sender: TObject);
begin
// Инициализируем выпадающие столбцы
MyInitializeComboBoxColumn;
end;
procedure TViewComponentsBase.DoAfterLoadData;
begin
PostMyApplyBestFitEvent;
UpdateView;
PostMessage(Handle, WM_FOCUS_TOP_LEFT, 0, 0);
end;
procedure TViewComponentsBase.DoAfterOpenOrRefresh(Sender: TObject);
begin
EndUpdate;
FIsSyncScrollbars := False;
DoAfterLoadData;
FNeedApplyBestFit := True;
end;
procedure TViewComponentsBase.DoBeforeOpenOrRefresh(Sender: TObject);
begin
BeginUpdate;
end;
procedure TViewComponentsBase.DoOnDescriptionPopupHide(Sender: TObject);
begin
UpdateView;
end;
procedure TViewComponentsBase.DoOnFocusTopLeft(var Message: TMessage);
begin
inherited;
FocusTopLeft;
end;
procedure TViewComponentsBase.DoOnHaveAnyChanges(Sender: TObject);
begin
UpdateView;
end;
procedure TViewComponentsBase.DoOnMasterDetailChange;
begin
FNeedApplyBestFit := FBaseCompGrp <> nil;
if FBaseCompGrp <> nil then
begin
// Привязываем представление к данным
with MainView do
begin
DataController.DataSource := BaseCompGrp.qBaseFamily.W.DataSource;
// DataController.CreateAllItems();
OptionsView.ColumnAutoWidth := False;
end;
with cxGridDBBandedTableView2.DataController do
begin
DataSource := FBaseCompGrp.qBaseComponents.W.DataSource;
KeyFieldNames := FBaseCompGrp.qBaseComponents.W.ID.FieldName;
MasterKeyFieldNames := FBaseCompGrp.qBaseFamily.W.ID.FieldName;
DetailKeyFieldNames := FBaseCompGrp.qBaseComponents.W.
ParentProductID.FieldName;
end;
with cxGridDBBandedTableView2 do
begin
// DataController.CreateAllItems();
OptionsBehavior.CopyCaptionsToClipboard := False;
OptionsSelection.MultiSelect := True;
OptionsSelection.CellMultiSelect := True;
OptionsSelection.InvertSelect := False;
OptionsView.ColumnAutoWidth := False;
OptionsView.ScrollBars := TScrollStyle.ssVertical;
OptionsView.GroupByBox := False;
OptionsView.Header := False;
OptionsView.BandHeaders := False;
end;
// Подписываемся на события
if FBaseCompGrp.qBaseComponents.Master <> nil then
begin
// Компоненты у нас загружаются первыми
TNotifyEventWrap.Create(FBaseCompGrp.qBaseComponents.W.BeforeOpen,
DoBeforeOpenOrRefresh, FEventList);
// Компоненты у нас загружаются первыми
TNotifyEventWrap.Create(FBaseCompGrp.qBaseComponents.W.BeforeRefresh,
DoBeforeOpenOrRefresh, FEventList);
// Семейства у нас загружаются последними !!!
TNotifyEventWrap.Create(FBaseCompGrp.qBaseFamily.W.AfterRefresh,
DoAfterOpenOrRefresh, FEventList);
// Семейства у нас загружаются последними !!!
TNotifyEventWrap.Create(FBaseCompGrp.qBaseFamily.W.AfterOpen,
DoAfterOpenOrRefresh, FEventList);
end;
Create_Columns;
// Пусть нам монитор сообщает об изменениях в БД
TNotifyEventWrap.Create
(FBaseCompGrp.qBaseComponents.Monitor.OnHaveAnyChanges,
DoOnHaveAnyChanges, FEventList);
// Подписываемся на событие о коммите
TNotifyEventWrap.Create(DMRepository.AfterCommit, DoAfterCommit,
FEventList);
MyInitializeComboBoxColumn;
if GridSort.Count = 0 then
begin
// Настраиваем сортировку
GridSort.Add(TSortVariant.Create(clValue, [clValue]));
GridSort.Add(TSortVariant.Create(clProducer, [clProducer, clValue]));
// Применяем сортировку по производителю
ApplySort(MainView, clValue);
end;
// Подписываемся на сообщения об изменении кол-ва
if UpdateCount = 0 then
CreateCountEvents;
// После того, как колоки созданы - создаём соответствующие пункты в меню
FColumnsBarButtons := TGVColumnsBarButtonsEx.Create(Self, dxbsColumns,
MainView, cxGridDBBandedTableView2);
end;
UpdateView;
cxGridPopupMenu.PopupMenus.Items[0].GridView := MainView;
end;
procedure TViewComponentsBase.DoOnUpdateColumnsWidth(var Message: TMessage);
begin
try
UpdateDetailColumnsWidth;
finally
FMessageUpdateDetailColumnsPosted := False;
end;
end;
procedure TViewComponentsBase.DoOnUpdateComponentsCount(Sender: TObject);
begin
// Выводим кол-во компонентов
StatusBar.Panels[1].Text :=
Format('%d', [BaseCompGrp.qBaseComponents.FDQuery.RecordCount]);
end;
procedure TViewComponentsBase.DoOnUpdateFamilyCount(Sender: TObject);
begin
Assert(BaseCompGrp <> nil);
(*
// Событие может прийти позже, после того как набор данных будет разрушен
if BaseCompGrp = nil then
begin
beep;
Exit;
end;
*)
if BaseCompGrp.qBaseFamily.FDQuery.State = dsBrowse then
begin
// Выводим кол-во родительских наименований
StatusBar.Panels[0].Text :=
Format('%d', [BaseCompGrp.qBaseFamily.FDQuery.RecordCount]);
UpdateTotalComponentCount;
end;
end;
procedure TViewComponentsBase.EndUpdate;
begin
inherited;
if UpdateCount = 0 then
CreateCountEvents;
end;
function TViewComponentsBase.ExpandDetail: TcxGridDBBandedTableView;
var
ARow: TcxMyGridMasterDataRow;
begin
ARow := MainView.Controller.FocusedRow as TcxMyGridMasterDataRow;
Assert(ARow <> nil);
Result := ARow.ActiveDetailGridView as TcxGridDBBandedTableView;
ARow.MyExpand(False);
Result.Focused := True;
end;
procedure TViewComponentsBase.FocusTopLeftEx;
begin
MainView.ViewData.Collapse(True);
FocusTopLeft;
end;
function TViewComponentsBase.GetclID: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.ID.FieldName);
end;
function TViewComponentsBase.GetclID2: TcxGridDBBandedColumn;
begin
Result := cxGridDBBandedTableView2.GetColumnByFieldName
(FBaseCompGrp.qBaseComponents.W.ID.FieldName);
end;
function TViewComponentsBase.GetclValue: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.Value.FieldName);
end;
function TViewComponentsBase.GetclProducer: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.Producer.FieldName);
end;
function TViewComponentsBase.GetclSubGroup: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.SubGroup.FieldName);
end;
function TViewComponentsBase.GetclDescription: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.DescriptionComponentName.FieldName);
end;
function TViewComponentsBase.GetclDatasheet: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.Datasheet.FieldName);
end;
function TViewComponentsBase.GetclImage: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.Image.FieldName);
end;
function TViewComponentsBase.GetclDiagram: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.Diagram.FieldName);
end;
function TViewComponentsBase.GetclDrawing: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.Drawing.FieldName);
end;
function TViewComponentsBase.GetclPackagePins: TcxGridDBBandedColumn;
begin
Result := MainView.GetColumnByFieldName
(FBaseCompGrp.qBaseFamily.W.PackagePins.FieldName);
end;
function TViewComponentsBase.GetclValue2: TcxGridDBBandedColumn;
begin
Result := cxGridDBBandedTableView2.GetColumnByFieldName
(FBaseCompGrp.qBaseComponents.W.Value.FieldName);
end;
function TViewComponentsBase.GetFocusedQuery: TQueryCustomComponents;
var
AView: TcxGridDBBandedTableView;
begin
Result := nil;
AView := GetFocusedTableView;
if AView <> nil then
begin
if AView.Level = cxGridLevel then
Result := BaseCompGrp.qBaseFamily;
if AView.Level = cxGridLevel2 then
Result := BaseCompGrp.qBaseComponents;
end;
end;
function TViewComponentsBase.GetfrmSubgroupListPopup: TfrmSubgroupListPopup;
begin
if FfrmSubgroupListPopup = nil then
FfrmSubgroupListPopup := TfrmSubgroupListPopup.Create(Self);
Result := FfrmSubgroupListPopup;
end;
function TViewComponentsBase.GetProducerDisplayText: string;
var
AColumn: TcxGridDBBandedColumn;
AView: TcxGridDBBandedTableView;
begin
Result := '';
AView := FocusedTableView;
if AView = nil then
Exit;
AColumn := AView.GetColumnByFieldName(FocusedQuery.W.Producer.FieldName);
Assert(AColumn <> nil);
Result := AView.Controller.FocusedRecord.DisplayTexts[AColumn.Index];
end;
function TViewComponentsBase.GetqSubGroups: TfrmQuerySubGroups;
begin
if FqSubGroups = nil then
begin
FqSubGroups := TfrmQuerySubGroups.Create(Self);
FqSubGroups.FDQuery.Connection := BaseCompGrp.Connection;
end;
Result := FqSubGroups;
end;
procedure TViewComponentsBase.InitBands;
var
ABand: TcxGridBand;
AView: TcxGridDBBandedTableView;
i: Integer;
begin
Assert(Length(ViewArr) > 0);
for AView in ViewArr do
begin
for i := 0 to AView.Bands.Count - 1 do
begin
ABand := AView.Bands[i];
with ABand do
begin
Options.HoldOwnColumnsOnly := True;
Options.Moving := False;
end;
end;
AView.Bands[0].FixedKind := fkLeft;
end;
end;
procedure TViewComponentsBase.InitComponentsColumns;
var
ACol: TcxGridDBBandedColumn;
AColBtn: TColBtn;
AcxButtonEditProperties: TcxButtonEditProperties;
Arr: TArray<TColBtn>;
i: Integer;
begin
with clValue do
begin
OnGetProperties := clValueGetProperties;
OnGetPropertiesForEdit := clValueGetPropertiesForEdit;
Options.ShowEditButtons := isebAlways;
VisibleForCustomization := False;
end;
// Производитель
clProducer.Position.BandIndex := 1;
MyInitializeComboBoxColumn;
if clSubGroup <> nil then
// группа компонентов
with clSubGroup do
begin
// Position.BandIndex := 1;
PropertiesClass := TcxPopupEditproperties;
OnGetProperties := clSubGroupGetProperties;
Options.Sorting := False;
Width := 100;
end;
// краткое описание
with clDescription do
begin
// Всплывающая форма с кратким описанием
if FfrmDescriptionPopup = nil then
FfrmDescriptionPopup := TfrmDescriptionPopup.Create(Self);
TNotifyEventWrap.Create(FfrmDescriptionPopup.OnHide,
DoOnDescriptionPopupHide, FEventList);
Assert(FfrmDescriptionPopup <> nil);
// Position.BandIndex := 1;
PropertiesClass := TcxPopupEditproperties;
(Properties as TcxPopupEditproperties).OnInitPopup :=
clDescriptionPropertiesInitPopup;
(Properties as TcxPopupEditproperties).PopupControl := FfrmDescriptionPopup;
MinWidth := 50;
Options.Sorting := False;
end;
// спецификация, схема, чертёж, изображение
Arr := [TColBtn.Create(clDatasheet, actOpenDatasheet, actLoadDatasheet),
TColBtn.Create(clDiagram, actOpenDiagram, actLoadDiagram),
TColBtn.Create(clDrawing, actOpenDrawing, actLoadDrawing),
TColBtn.Create(clImage, actOpenImage, actLoadImage)];
for AColBtn in Arr do
begin
with AColBtn.Col do
begin
// Position.BandIndex := 1;
PropertiesClass := TcxButtonEditProperties;
AcxButtonEditProperties := Properties as TcxButtonEditProperties;
AcxButtonEditProperties.Buttons.Add;
Assert(AcxButtonEditProperties.Buttons.Count = 2);
AcxButtonEditProperties.Buttons[0].Action := AColBtn.OpenAction;
AcxButtonEditProperties.Buttons[0].Kind := bkText;
AcxButtonEditProperties.Buttons[1].Action := AColBtn.LoadAction;
AcxButtonEditProperties.Buttons[1].Default := True;
AcxButtonEditProperties.Buttons[1].Kind := bkEllipsis;
OnGetDataText := clDatasheetGetDataText;
Options.Sorting := False;
Width := 100;
end;
end;
if clPackagePins <> nil then
with clPackagePins do
begin
// Position.BandIndex := 1;
MinWidth := 120;
Options.Sorting := False;
end;
with clValue2 do
begin
OnGetProperties := clValue2GetProperties;
OnGetPropertiesForEdit := clValue2GetPropertiesForEdit;
VisibleForCustomization := False;
end;
// Все колонки дочернего представления
for i := 0 to cxGridDBBandedTableView2.ColumnCount - 1 do
begin
ACol := cxGridDBBandedTableView2.Columns[i];
if ACol = clValue2 then
Continue;
// ACol.Position.BandIndex := 1;
ACol.PropertiesClass := TcxTextEditProperties;
(ACol.Properties as TcxTextEditProperties).ReadOnly := True;
end;
end;
procedure TViewComponentsBase.InitView(AView: TcxGridDBBandedTableView);
begin
inherited;
AView.OptionsData.Deleting := False;
AView.OptionsData.DeletingConfirmation := False;
// AView.OptionsView.ExpandButtonsForEmptyDetails := False;
end;
procedure TViewComponentsBase.InternalRefreshData;
begin
Assert(BaseCompGrp <> nil);
BaseCompGrp.RefreshData;
MainView.ViewData.Collapse(True);
end;
procedure TViewComponentsBase.MyDelete;
var
AController: TcxGridBandedTableController;
AView: TcxGridDBBandedTableView;
fri: Integer;
i: Integer;
S: string;
t: Integer;
X: Integer;
begin
AView := FocusedTableView;
if AView = nil then
Exit;
if FDeleteFromAllCategories then
S := sDoYouWantToDeleteFamilyFromAll
else
S := DeleteMessages[AView.Level as TcxGridLevel];
if not TDialog.Create.DeleteRecordsDialog(S) then
Exit;
AController := AView.Controller;
// если удалить всё
if FDeleteFromAllCategories then
begin
if AController.SelectedRowCount > 0 then
begin
for i := 0 to AController.SelectedRowCount - 1 do
begin
X := AController.SelectedRows[i].Values[clID.Index];
BaseCompGrp.FullDeleted.Add(X);
end;
end
else
begin
X := AController.FocusedRecord.Values[clID.Index];
BaseCompGrp.FullDeleted.Add(X);
end;
end;
t := MainView.Controller.TopRecordIndex;
fri := MainView.Controller.FocusedRowIndex;
DisableCollapsingAndExpanding;
try
AController.DeleteSelection;
// если удалили последнюю "дочернюю" запись
if (AView.DataController.RecordCount = 0) and (AView.MasterGridRecord <> nil)
then
begin
// Сворачиваем дочернее представление
(AView.MasterGridRecord as TcxMyGridMasterDataRow).MyCollapse(False);
MainView.Controller.TopRowIndex := t;
MainView.Controller.FocusedRowIndex := fri;
end;
finally
EnableCollapsingAndExpanding;
end;
UpdateView;
end;
procedure TViewComponentsBase.MyInitializeComboBoxColumn;
begin
Assert(BaseCompGrp.Producers <> nil);
BaseCompGrp.Producers.W.TryOpen;
// Производителя выбираем ТОЛЬКО из списка
InitializeComboBoxColumn(MainView, clProducer.DataBinding.FieldName,
lsEditFixedList, BaseCompGrp.Producers.W.Name.F);
end;
procedure TViewComponentsBase.OnGridRecordCellPopupMenu
(AColumn: TcxGridDBBandedColumn; var AllowPopup: Boolean);
Var
AColumnIsValue: Boolean;
IsText: Boolean;
begin
IsText := Clipboard.HasFormat(CF_TEXT);
AColumnIsValue := (AColumn <> nil) and
(AColumn.DataBinding.FieldName = clValue.DataBinding.FieldName);
actPasteFamily.Visible :=
(AColumnIsValue and (AColumn.GridView.Level = cxGridLevel)) or
(AColumn = nil);
actPasteFamily.Enabled := actPasteFamily.Visible and IsText;
actPasteComponents.Visible := AColumnIsValue;
actPasteComponents.Enabled := actPasteComponents.Visible and IsText;
actPasteProducer.Visible := (AColumn <> nil) and
(AColumn.DataBinding.FieldName = clProducer.DataBinding.FieldName);
actPasteProducer.Enabled := actPasteProducer.Visible and IsText;
actPastePackagePins.Visible := (AColumn <> nil) and (clPackagePins <> nil) and
(AColumn.DataBinding.FieldName = clPackagePins.DataBinding.FieldName);
actPastePackagePins.Enabled := actPastePackagePins.Visible and IsText;
actCopyToClipboard.Visible := AColumn <> nil;
actCopyToClipboard.Enabled := actCopyToClipboard.Visible
end;
procedure TViewComponentsBase.OpenDoc(ADocFieldInfo: TDocFieldInfo);
begin
Application.Hint := '';
TDocument.Open(Handle, ADocFieldInfo.Folder,
BaseCompGrp.qBaseFamily.FDQuery.FieldByName(ADocFieldInfo.FieldName)
.AsString, ADocFieldInfo.ErrorMessage, ADocFieldInfo.EmptyErrorMessage,
sBodyTypesFilesExt);
end;
procedure TViewComponentsBase.PostMessageUpdateDetailColumnsWidth;
begin
if FMessageUpdateDetailColumnsPosted then
Exit;
FMessageUpdateDetailColumnsPosted := True;
PostMessage(Handle, WM_UPDATE_DETAIL_COLUMNS_WIDTH, 0, 0)
end;
procedure TViewComponentsBase.SetBaseCompGrp(const Value
: TBaseComponentsGroup2);
begin
if FBaseCompGrp = Value then
Exit;
FBaseCompGrp := Value;
FEventList.Clear; // Отписываемся от старых событий
DoOnMasterDetailChange;
end;
{ Синхронизировать положение скроллбаров }
procedure TViewComponentsBase.SyncScrollbarPositions;
var
AcxGridDBBandedTableView: TcxGridDBBandedTableView;
AcxGridMasterDataRow: TcxGridMasterDataRow;
i, ALeftPos: Integer;
AView: TcxGridBandedTableView;
begin
// Если находимся в состоянии BeginUpdate
if UpdateCount > 0 then
Exit;
if FIsSyncScrollbars then
Exit;
try
FIsSyncScrollbars := True;
AView := MainView;
ALeftPos := AView.Controller.LeftPos;
for i := 0 to AView.ViewData.RowCount - 1 do
begin
AcxGridMasterDataRow := GetRow(0, i) as TcxGridMasterDataRow;
if AcxGridMasterDataRow.Expanded then
begin
AcxGridDBBandedTableView := AcxGridMasterDataRow.ActiveDetailGridView as
TcxGridDBBandedTableView;
if (AcxGridDBBandedTableView.Controller <> nil) and
(AcxGridDBBandedTableView.Controller.LeftPos <> ALeftPos) then
AcxGridDBBandedTableView.Controller.LeftPos := ALeftPos;
end;
end;
finally
FIsSyncScrollbars := False;
end;
end;
procedure TViewComponentsBase.TryApplyBestFit;
begin
if not FNeedApplyBestFit then
Exit;
FNeedApplyBestFit := False;
MyApplyBestFit;
end;
procedure TViewComponentsBase.UpdateDetailColumnsWidth;
var
ABand: TcxGridBand;
ADetailColumn: TcxGridDBBandedColumn;
AMainColumn: TcxGridDBBandedColumn;
// dx: Integer;
i: Integer;
RealBandWidth: Integer;
RealColumnWidth: Integer;
begin
// Предполагаем, что количество видимых главных и дочерних колонок одинаковое
Assert(MainView.VisibleColumnCount = cxGridDBBandedTableView2.
VisibleColumnCount);
cxGrid.BeginUpdate();
// cxGridDBBandedTableView2.BeginBestFitUpdate;
try
// Большинство бэндов имеют ширину 0
// Тогда их ширина подстроится под ширину колонок
// Но есть и те, у которых задана минимальная ширина, чтобы влез их заголовок
Assert(MainView.Bands.Count = cxGridDBBandedTableView2.Bands.Count);
// Сначала выравниваем длину всех бэндов
for i := 0 to MainView.Bands.Count - 1 do
begin
ABand := MainView.Bands[i];
if (not ABand.Visible) or (ABand.VisibleIndex = 0)
{ or (ABand.Width = 0) }
then
Continue;
// Если информация о том, сколько бэнд занимает на экране не доступна!
if MainView.ViewInfo.HeaderViewInfo.BandsViewInfo.Count <= ABand.VisibleIndex
then
Continue;
RealBandWidth := MainView.ViewInfo.HeaderViewInfo.BandsViewInfo.Items
[ABand.VisibleIndex].Width;
{
if ABand.VisibleIndex = 0 then
begin
dx := ABand.Width - RealBandWidth;
Dec(RealBandWidth, MainView.ViewInfo.FirstItemAdditionalWidth - dx);
end;
}
cxGridDBBandedTableView2.Bands[i].Width := RealBandWidth;
// cxGridDBBandedTableView2.Bands[i].Width := ABand.Width;
end;
// Потом изменяем размеры всех дочерних колонок
for i := 0 to cxGridDBBandedTableView2.VisibleColumnCount - 1 do
begin
AMainColumn := MainView.VisibleColumns[i] as TcxGridDBBandedColumn;
ADetailColumn := cxGridDBBandedTableView2.VisibleColumns[i]
as TcxGridDBBandedColumn;
Assert(AMainColumn.DataBinding.FieldName = ADetailColumn.DataBinding.
FieldName);
Assert(AMainColumn.VisibleIndex < MainView.ViewInfo.HeaderViewInfo.Count);
RealColumnWidth := MainView.ViewInfo.HeaderViewInfo.Items
[AMainColumn.VisibleIndex].Width;
if AMainColumn.VisibleIndex = 0 then
Dec(RealColumnWidth, MainView.ViewInfo.FirstItemAdditionalWidth);
ADetailColumn.Width := RealColumnWidth;
end;
finally
// cxGridDBBandedTableView2.EndBestFitUpdate;
cxGrid.EndUpdate;
end;
end;
procedure TViewComponentsBase.UpdateSelectedCount;
begin
if UpdateCount = 0 then
StatusBar.Panels[2].Text :=
Format('%d', [MainView.DataController.GetSelectedCount]);
end;
procedure TViewComponentsBase.UpdateSelectedValues
(AView: TcxGridDBBandedTableView);
var
i: Integer;
Index: Integer;
J: Integer;
RowIndex: Integer;
begin
AView.Controller.BeginUpdate();
try
for i := 0 to AView.Controller.SelectedRecordCount - 1 do
// для каждой строки
begin
RowIndex := AView.Controller.SelectedRecords[i].Index;
// Цикл по выделенным столбцам
for J := 0 to AView.Controller.SelectedColumnCount - 1 do
// для каждого столбца
begin
Index := AView.Controller.SelectedColumns[J].Index;
AView.Controller.FocusRecord(RowIndex, False);
if FEditingValue = null then
begin
AView.DataController.SetEditValue(Index, null, evsValue)
end
else
begin
try
AView.DataController.SetEditValue(Index, FEditingValue, evsValue);
except
AView.DataController.SetEditValue(Index, null, evsValue);
end;
end;
end;
end;
finally
AView.Controller.EndUpdate;
end;
end;
procedure TViewComponentsBase.UpdateTotalComponentCount;
begin
// Общее число компонентов на в БД
StatusBar.Panels[4].Text := Format('Всего: %d', [BaseCompGrp.TotalCount]);
end;
procedure TViewComponentsBase.UpdateView;
var
AView: TcxGridDBBandedTableView;
Ok: Boolean;
S: string;
begin
Ok := BaseCompGrp <> nil;
AView := FocusedTableView;
// Удалить из всех категорий можно только родительский компонент
actDeleteFromAllCategories.Enabled := Ok and (AView <> nil) and
(AView.Level = cxGridLevel) and (AView.Controller.SelectedRowCount > 0);
actDeleteFromAllCategories.Visible := actDeleteFromAllCategories.Enabled;
// Удалять разрешаем только если что-то выделено
actDeleteEx.Enabled := Ok and (AView <> nil) and
(AView.Controller.SelectedRowCount > 0);
actDeleteFromAllCategories.Enabled := actDeleteEx.Enabled;
if Ok and (AView <> nil) and (AView.Level = cxGridLevel) then
begin
if (BaseCompGrp.qBaseFamily.Master <> nil) and
((BaseCompGrp.qBaseFamily.Master.FDQuery.Active)) then
begin
S := BaseCompGrp.qBaseFamily.Master.FDQuery.FieldByName('Value').AsString;
actDeleteEx.Caption := Format('Удалить семейство из категории «%s»', [S]);
end;
end;
if Ok and (AView <> nil) and (AView.Level = cxGridLevel2) then
begin
actDeleteEx.Caption := 'Удалить компонент из семейства';
end;
actAddFamily.Enabled := Ok and (AView <> nil);
actAddComponent.Enabled := Ok and (AView <> nil);
// and (AView.Level = tlComponentsDetails);
actCommit.Enabled := Ok and BaseCompGrp.HaveAnyChanges;
actRollback.Enabled := actCommit.Enabled;
end;
procedure TViewComponentsBase.UploadDoc(ADocFieldInfo: TDocFieldInfo);
var
AProducer: string;
APath: String;
AFileName: string;
begin
Application.Hint := '';
// Файл должен лежать в каталоге = производителю
AProducer := ProducerDisplayText;
APath := BaseCompGrp.qBaseFamily.W.Field(ADocFieldInfo.FieldName).AsString;
// Если файл документации ранее был уже задан
if APath <> '' then
begin
// Получаем полный путь до файла
APath := TPath.Combine(ADocFieldInfo.Folder, APath);
// Получаем папку в которой лежит ранее заданный файл документации
APath := TPath.GetDirectoryName(APath);
// если такого пути уже не существует
end
else
APath := TPath.Combine(ADocFieldInfo.Folder, AProducer);
if not TDirectory.Exists(APath) then
APath := ADocFieldInfo.Folder;
// Открываем диалог выбора файла для загрузки
if not TDialog.Create.ShowDialog(TMyOpenPictureDialog, APath, '', AFileName)
then
Exit;
BaseCompGrp.LoadDocFile(AFileName, ADocFieldInfo);
MyApplyBestFit;
end;
constructor TColBtn.Create(ACol: TcxGridDBBandedColumn;
AOpenAction, ALoadAction: TAction);
begin
FCol := ACol;
FOpenAction := AOpenAction;
FLoadAction := ALoadAction;
end;
end.
|
unit simpleaudio;
//------------------------------------------------------------------------------
// A simple audio unit for Ultibo modelled after SDL audio API
// v.0.91 beta - 20170218
// pik33@o2.pl
// gpl 2.0 or higher
//------------------------------------------------------------------------------
//
// beta changelog
//
// 0.91 - fixed the bug which caused 1-channel sound play badly distorted
//
//------------------------------------------------------------------------------
{$mode objfpc}{$H+}
interface
uses Classes, SysUtils, Platform, HeapManager, Threads, GlobalConst, math;
type
// ---- I decided to use SDL-like API so this fragment is copied from SDL unit
// ----- and modified somewhat
TAudioSpecCallback = procedure(userdata: Pointer; stream: PUInt8; len:Integer );
PAudioSpec = ^TAudioSpec;
TAudioSpec = record
freq: Integer; // DSP frequency -- samples per second
format: UInt16; // Audio data format
channels: UInt8; // Number of channels: 1 mono, 2 stereo
silence: UInt8; // Audio buffer silence value (calculated)
samples: UInt16; // Audio buffer size in samples
padding: UInt16; // Necessary for some compile environments
size: UInt32; // Audio buffer size in bytes (calculated)
// This function is called when the audio device needs more data.
// 'stream' is a pointer to the audio data buffer
// 'len' is the length of that buffer in bytes.
// Once the callback returns, the buffer will no longer be valid.
// Stereo samples are stored in a LRLRLR ordering.
callback: TAudioSpecCallback;
userdata: Pointer;
// 3 fields added, not in SDL
oversample: UInt8; // oversampling value
range: UInt16; // PWM range
oversampled_size: integer; // oversampled buffer size
end;
const
// ---------- Error codes
freq_too_low= -$11;
freq_too_high= -$12;
format_not_supported= -$21;
invalid_channel_number= -$41;
size_too_low = -$81;
size_too_high= -$81;
callback_not_specified= -$101;
// ---------- Audio formats. Subset of SDL formats
// ---------- These are 99.99% of wave file formats:
AUDIO_U8 = $0008; // Unsigned 8-bit samples
AUDIO_S16 = $8010; // Signed 16-bit samples
AUDIO_F32 = $8120; // Float 32 bit
// SDL based functions
function OpenAudio(desired, obtained: PAudioSpec): Integer;
procedure CloseAudio;
procedure PauseAudio(p:integer);
// Functions not in SDL API
function ChangeAudioParams(desired, obtained: PAudioSpec): Integer;
procedure SetVolume(vol:single);
procedure SetVolume(vol:integer);
procedure setDBVolume(vol:single);
// Simplified functions
function SA_OpenAudio(freq,bits,channels,samples:integer; callback: TAudioSpecCallback):integer;
function SA_ChangeParams(freq,bits,channels,samples:integer): Integer;
function SA_GetCurrentFreq:integer;
function SA_GetCurrentRange:integer;
//------------------ End of Interface ------------------------------------------
implementation
type
PLongBuffer=^TLongBuffer;
TLongBuffer=array[0..65535] of integer; // 64K DMA buffer
TCtrlBlock=array[0..7] of cardinal;
PCtrlBlock=^TCtrlBlock;
TAudioThread= class(TThread)
private
protected
procedure Execute; override;
public
Constructor Create(CreateSuspended : boolean);
end;
const nocache=$C0000000; // constant to disable GPU L2 Cache
pll_freq=500000000; // base PLL freq=500 MHz
pwm_base_freq=1920000;
divider=2;
base_freq=pll_freq div divider;
max_pwm_freq=pwm_base_freq div divider;
dma_buffer_size=65536; // max size for simplified channel
// TODO: make the sample buffer size dynamic (?)
sample_buffer_size=8192; // max size for sample buffer.
// The max allowed by dma_buffer_size is 1536 for 44100/16/2 wave
sample_buffer_32_size=16384; // 8x sample_buffer_size for 8-bit mono samples
// ------- Hardware registers addresses --------------------------------------
_pwm_fif1_ph= $7E20C018; // PWM FIFO input reg physical address
_pwm_ctl= $3F20C000; // PWM Control Register MMU address
_pwm_dmac= $3F20C008; // PWM DMA Configuration MMU address
_pwm_rng1= $3F20C010; // PWM Range channel #1 MMU address
_pwm_rng2= $3F20C020; // PWM Range channel #2 MMU address
_gpfsel4= $3F200010; // GPIO Function Select 4 MMU address
_pwmclk= $3F1010a0; // PWM Clock ctrl reg MMU address
_pwmclk_div= $3F1010a4; // PWM clock divisor MMU address
_dma_enable= $3F007ff0; // DMA enable register
_dma_cs= $3F007000; // DMA control and status
_dma_conblk= $3F007004; // DMA ctrl block address
_dma_nextcb= $3F00701C; // DMA next control block
// ------- Hardware initialization constants
transfer_info=$00050140; // DMA transfer information
// 5 - DMA peripheral code (5 -> PWM)
// 1 - src address increment after read
// 4 - DREQ controls write
and_mask_40_45= %11111111111111000111111111111000; // AND mask for gpio 40 and 45
or_mask_40_45_4= %00000000000000100000000000000100; // OR mask for set Alt Function #0 @ GPIO 40 and 45
clk_plld= $5a000016; // set clock to PLL D
clk_div= $5a000000 + divider shl 12; //002000; // set clock divisor to 2.0
pwm_ctl_val= $0000a1e1; // value for PWM init:
// bit 15: chn#2 set M/S mode=1. Use PWM mode for non-noiseshaped audio and M/S mode for oversampled noiseshaped audio
// bit 13: enable fifo for chn #2
// bit 8: enable chn #2
// bit 7: chn #1 M/S mode on
// bit 6: clear FIFO
// bit 5: enable fifo for chn #1
// bit 0: enable chn #1
pwm_dmac_val= $80000707; // PWM DMA ctrl value:
// bit 31: enable DMA
// bits 15..8: PANIC value
// bits 7..0: DREQ value
dma_chn= 14; // use DMA channel 14 (the last)
var gpfsel4:cardinal absolute _gpfsel4; // GPIO Function Select 4
pwmclk:cardinal absolute _pwmclk; // PWM Clock ctrl
pwmclk_div: cardinal absolute _pwmclk_div; // PWM Clock divisor
pwm_ctl:cardinal absolute _pwm_ctl; // PWM Control Register
pwm_dmac:cardinal absolute _pwm_dmac; // PWM DMA Configuration MMU address
pwm_rng1:cardinal absolute _pwm_rng1; // PWM Range channel #1 MMU address
pwm_rng2:cardinal absolute _pwm_rng2; // PWM Range channel #2 MMU address
dma_enable:cardinal absolute _dma_enable; // DMA Enable register
dma_cs:cardinal absolute _dma_cs+($100*dma_chn); // DMA ctrl/status
dma_conblk:cardinal absolute _dma_conblk+($100*dma_chn); // DMA ctrl block addr
dma_nextcb:cardinal absolute _dma_nextcb+($100*dma_chn); // DMA next ctrl block addr
dmactrl_ptr:PCardinal=nil; // DMA ctrl block pointer
dmactrl_adr:cardinal absolute dmactrl_ptr; // DMA ctrl block address
dmabuf1_ptr:PCardinal=nil; // DMA data buffer #1 pointer
dmabuf1_adr:cardinal absolute dmabuf1_ptr; // DMA data buffer #1 address
dmabuf2_ptr:PCardinal=nil; // DMA data buffer #2 pointer
dmabuf2_adr:cardinal absolute dmabuf2_ptr; // DMA data buffer #2 address
ctrl1_ptr,ctrl2_ptr:PCtrlBlock; // DMA ctrl block array pointers
ctrl1_adr:cardinal absolute ctrl1_ptr; // DMA ctrl block #1 array address
ctrl2_adr:cardinal absolute ctrl2_ptr; // DMA ctrl block #2 array address
// CurrentAudioSpec:TAudioSpec;
SampleBuffer_ptr:pointer;
SampleBuffer_ptr_b:PByte absolute SampleBuffer_ptr;
SampleBuffer_ptr_si:PSmallint absolute SampleBuffer_ptr;
SampleBuffer_ptr_f:PSingle absolute SampleBuffer_ptr;
SampleBuffer_adr:cardinal absolute SampleBuffer_ptr;
SampleBuffer_32_ptr:PCardinal;
SampleBuffer_32_adr:cardinal absolute SampleBuffer_32_ptr;
AudioThread:TAudioThread;
AudioOn:integer=0; // 1 - audio worker thread is running
volume:integer=4096; // audio volume; 4096 -> 0 dB
pauseA:integer=1; // 1 - audio is paused
nc:cardinal;
working:integer;
CurrentAudioSpec:TAudioSpec;
s_desired, s_obtained: TAudioSpec;
procedure InitAudioEx(range,t_length:integer); forward;
function noiseshaper8(bufaddr,outbuf,oversample,len:integer):integer; forward;
function noiseshaper9(bufaddr,outbuf,oversample,len:integer):integer; forward;
// ------------------------------------------------
// A helper procedure which removes RAM RO limit
// used here to speed up the noise shaper
//-------------------------------------------------
procedure removeramlimits(addr:integer);
var Entry:TPageTableEntry;
begin
Entry:=PageTableGetEntry(addr);
Entry.Flags:=$3b2; //executable, shareable, rw, cacheable, writeback
PageTableSetEntry(Entry);
end;
//------------------------------------------------------------------------------
// Procedure initaudio - init the GPIO, PWM and DMA for audio subsystem.
//------------------------------------------------------------------------------
procedure InitAudioEx(range,t_length:integer); //TODO don't init second time!!!
var i:integer;
begin
dmactrl_ptr:=GetAlignedMem(64,32); // get 64 bytes for 2 DMA ctrl blocks
ctrl1_ptr:=PCtrlBlock(dmactrl_ptr); // set pointers so the ctrl blocks can be accessed as array
ctrl2_ptr:=PCtrlBlock(dmactrl_ptr+8); // second ctrl block is 8 longs further
dmabuf1_ptr:=getmem(65536); // allocate 64k for DMA buffer
dmabuf2_ptr:=getmem(65536); // .. and the second one
ctrl1_ptr^[0]:=transfer_info; // transfer info
ctrl1_ptr^[1]:=nocache+dmabuf1_adr; // source address -> buffer #1
ctrl1_ptr^[2]:=_pwm_fif1_ph; // destination address
ctrl1_ptr^[3]:=t_length; // transfer length
ctrl1_ptr^[4]:=$0; // 2D length, unused
ctrl1_ptr^[5]:=nocache+ctrl2_adr; // next ctrl block -> ctrl block #2
ctrl1_ptr^[6]:=$0; // unused
ctrl1_ptr^[7]:=$0; // unused
ctrl2_ptr^:=ctrl1_ptr^; // copy first block to second
ctrl2_ptr^[5]:=nocache+ctrl1_adr; // next ctrl block -> ctrl block #1
ctrl2_ptr^[1]:=nocache+dmabuf2_adr; // source address -> buffer #2
CleanDataCacheRange(dmactrl_adr,64); // now push this into RAM
sleep(1);
// Init the hardware
gpfsel4:=(gpfsel4 and and_mask_40_45) or or_mask_40_45_4; // gpio 40/45 as alt#0 -> PWM Out
pwmclk:=clk_plld; // set PWM clock src=PLLD (500 MHz)
pwmclk_div:=clk_div; // set PWM clock divisor=2 (250 MHz)
pwm_rng1:=range; // minimum range for 8-bit noise shaper to avoid overflows
pwm_rng2:=range; //
pwm_ctl:=pwm_ctl_val; // pwm contr0l - enable pwm, clear fifo, use fifo
pwm_dmac:=pwm_dmac_val; // pwm dma enable
dma_enable:=dma_enable or (1 shl dma_chn); // enable dma channel # dma_chn
dma_conblk:=nocache+ctrl1_adr; // init DMA ctr block to ctrl block # 1
dma_cs:=$00FF0003; // start DMA
end;
function SA_OpenAudio(freq,bits,channels,samples:integer; callback: TAudioSpecCallback):integer;
begin
s_desired.freq:=freq;
s_desired.samples:=samples;
s_desired.channels:=channels;
s_desired.samples:=samples;
s_desired.callback:=callback;
case bits of
8:s_desired.format:= AUDIO_U8;
16:s_desired.format:=AUDIO_S16;
32:s_desired.format:=AUDIO_F32;
else
begin
result:=format_not_supported;
exit;
end;
end;
result:=OpenAudio(@s_desired,@s_obtained);
end;
function SA_ChangeParams(freq,bits,channels,samples:integer): Integer;
begin
s_desired.freq:=freq;
s_desired.samples:=samples;
s_desired.channels:=channels;
s_desired.samples:=samples;
s_desired.callback:=nil;
case bits of
0:s_desired.format:=0;
8:s_desired.format:= AUDIO_U8;
16:s_desired.format:=AUDIO_S16;
32:s_desired.format:=AUDIO_F32;
else
begin
result:=format_not_supported;
exit;
end;
end;
result:=ChangeAudioParams(@s_desired,@s_obtained);
end;
// ----------------------------------------------------------------------
// OpenAudio
// Inits the audio according to specifications in 'desired' record
// The values which in reality had been set are in 'obtained' record
// Returns 0 or the error code, in this case 'obtained' is invalid
//
// You have to set the fields:
//
// freq: samples per second, 8..960 kHz
// format: audio data format
// channels: number of channels: 1 mono, 2 stereo
// samples: audio buffer size in samples. >32, not too long (<384 for stereo 44100 Hz)
// callback: a callback function you have to write in your program
//
// The rest of fields in 'desire' will be ignored. They will be filled in 'obtained'
// ------------------------------------------------------------------------
function OpenAudio(desired, obtained: PAudioSpec): Integer;
var maxsize:double;
over_freq:integer;
begin
result:=0;
// ----------- check if params can be used
// ----------- the frequency should be between 8 and 960 kHz
if desired^.freq<8000 then
begin
result:=freq_too_low;
exit;
end;
if desired^.freq>max_pwm_freq then
begin
result:=freq_too_high;
exit;
end;
//----------- check if the format is supported
if (desired^.format <> AUDIO_U8) and (desired^.format <> AUDIO_S16) and (desired^.format <> AUDIO_F32) then
begin
result:=format_not_supported;
exit;
end;
//----------- check the channel number
if (desired^.channels < 1) or (desired^.channels>2) then
begin
result:=invalid_channel_number;
exit;
end;
//----------- check the buffer size in samples
//----------- combined with the noise shaper should not exceed 64k
// It is ~384 for 44 kHz S16 samples
if (desired^.samples<32) then
begin
result:=size_too_low;
exit;
end;
maxsize:=65528/max_pwm_freq*desired^.freq/desired^.channels;
if (desired^.samples>maxsize) then
begin
result:=size_too_high;
exit;
end;
if (desired^.callback=nil) then
begin
result:=callback_not_specified;
exit;
end;
// now compute the obtained parameters
obtained^:=desired^;
obtained^.oversample:=max_pwm_freq div desired^.freq;
// the workaround for simply making 432 Hz tuned sound
// the problem is: when going 44100->43298
// the computed oversample changes from 21 to 22
// and this causes the resulting DMA buffer exceed 64K
// Also if I init the 43298 Hz soud, I will want to change it to 44100
// without changing anything else
if obtained^.oversample=22 then obtained^.oversample:=21;
over_freq:=desired^.freq*obtained^.oversample;
obtained^.range:=round(base_freq/over_freq);
obtained^.freq:=round(base_freq/(obtained^.range*obtained^.oversample));
if (desired^.format = AUDIO_U8) then obtained^.silence:=128 else obtained^.silence:=0;
obtained^.padding:=0;
obtained^.size:=obtained^.samples*obtained^.channels;
if obtained^.size>sample_buffer_size then
begin
result:=size_too_high;
exit;
end;
if obtained^.channels=2 then obtained^.oversampled_size:=obtained^.size*4*obtained^.oversample
else obtained^.oversampled_size:=obtained^.size*8*obtained^.oversample; //output is always 2 channels
if obtained^.format=AUDIO_U8 then obtained^.size:=obtained^.size;
if obtained^.format=AUDIO_S16 then obtained^.size:=obtained^.size*2;
if obtained^.format=AUDIO_F32 then obtained^.size:=obtained^.size*4;
InitAudioEx(obtained^.range,obtained^.oversampled_size);
CurrentAudioSpec:=obtained^;
samplebuffer_ptr:=getmem(sample_buffer_size);
samplebuffer_32_ptr:=getmem(sample_buffer_32_size);
removeramlimits(integer(@noiseshaper8)); // noise shaper uses local vars or it will be slower
removeramlimits(integer(@noiseshaper9)); // noise shaper uses local vars or it will be slower
// now create and start the audio thread
pauseA:=1;
AudioThread:=TAudioThread.Create(true);
AudioThread.start;
end;
// ---------- ChangeAudioParams -----------------------------------------
//
// This function will try to change audio parameters
// without closing and reopening the audio system (=loud click)
// The usage is the same as OpenAudio
//
// -----------------------------------------------------------------------
function ChangeAudioParams(desired, obtained: PAudioSpec): Integer;
var maxsize:double;
over_freq:integer;
begin
// -------------- Do all things as in OpenAudio
// -------------- TODO: what is common, should go to one place
result:=0;
if desired^.freq=0 then desired^.freq:=CurrentAudioSpec.freq;
if desired^.freq<8000 then
begin
result:=freq_too_low;
exit;
end;
if desired^.freq>max_pwm_freq then
begin
result:=freq_too_high;
exit;
end;
if desired^.format=0 then desired^.format:=CurrentAudioSpec.format;
if (desired^.format <> AUDIO_U8) and (desired^.format <> AUDIO_S16) and (desired^.format <> AUDIO_F32) then
begin
result:=format_not_supported;
exit;
end;
if desired^.channels=0 then desired^.channels:=CurrentAudioSpec.channels;
if (desired^.channels < 1) or (desired^.channels>2) then
begin
result:=invalid_channel_number;
exit;
end;
if desired^.samples=0 then desired^.samples:=CurrentAudioSpec.samples ;
if (desired^.samples<32) then
begin
result:=size_too_low;
exit;
end;
maxsize:=65528/max_pwm_freq*desired^.freq/desired^.channels;
if (desired^.samples>maxsize) then
begin
result:=size_too_high;
exit;
end;
if (desired^.callback=nil) then desired^.callback:=CurrentAudioSpec.callback;
obtained^:=desired^;
obtained^.oversample:=max_pwm_freq div desired^.freq;
// the workaround for simply making 432 Hz tuned sound
// the problem is: when going 44100->43298
// the computed oversample changes from 21 to 22
// and this causes the resulting DMA buffer exceed 64K
if obtained^.oversample=22 then obtained^.oversample:=21;
over_freq:=desired^.freq*obtained^.oversample;
obtained^.range:=round(base_freq/over_freq);
obtained^.freq:=round(base_freq/(obtained^.range*obtained^.oversample));
if (desired^.format = AUDIO_U8) then obtained^.silence:=128 else obtained^.silence:=0;
obtained^.padding:=0;
obtained^.size:=obtained^.samples*obtained^.channels;
if obtained^.size>sample_buffer_size then
begin
result:=size_too_high;
exit;
end;
if obtained^.channels=2 then obtained^.oversampled_size:=obtained^.size*4*obtained^.oversample
else obtained^.oversampled_size:=obtained^.size*8*obtained^.oversample; //output is always 2 channels
if obtained^.format=AUDIO_S16 then obtained^.size:=obtained^.size * 2;
if obtained^.format=AUDIO_F32 then obtained^.size:=obtained^.size * 4;
// Here the common part ends.
//
// Now we cannot "InitAudio" as it is already init and running
// Instead we will change - only when needed:
//
// - PWM range
// - DMA transfer length
if obtained^.range<>CurrentAudioSpec.range then
begin
pwm_ctl:=0; // stop PWM
pwm_rng1:=obtained^.range; // set a new range
pwm_rng2:=obtained^.range;
pwm_ctl:=pwm_ctl_val; // start PWM
end;
if obtained^.oversampled_size<>CurrentAudioSpec.oversampled_size then
begin
repeat sleep(0) until dma_nextcb=nocache+ctrl2_adr;
ctrl1_ptr^[3]:=obtained^.oversampled_size;
repeat sleep(0) until dma_nextcb=nocache+ctrl1_adr;
ctrl2_ptr^[3]:=obtained^.oversampled_size;
end;
repeat until working=1;
repeat until working=0;
CurrentAudioSpec:=obtained^;
end;
procedure CloseAudio;
begin
// Stop audio worker thread
//PauseAudio(1);
AudioThread.terminate;
repeat sleep(1) until AudioOn=1;
// ...then switch off DMA...
ctrl1_ptr^[5]:=0;
ctrl2_ptr^[5]:=0;
// up to 8 ms of audio can still reside in the buffer
sleep(20);
// Now disable PWM...
pwm_ctl:=0;
//... and return the memory to the system
dispose(dmabuf1_ptr);
dispose(dmabuf2_ptr);
freemem(dmactrl_ptr);
freemem(samplebuffer_ptr);
end;
procedure pauseaudio(p:integer);
begin
if p=1 then pauseA:=1;
if p=0 then pausea:=0;
end;
procedure SetVolume(vol:single);
// Setting the volume as float in range 0..1
begin
if (vol>=0) and (vol<=1) then volume:=round(vol*4096);
end;
procedure SetVolume(vol:integer);
// Setting the volume as integer in range 0..4096
begin
if (vol>=0) and (vol<=4096) then volume:=vol;
end;
procedure setDBVolume(vol:single);
// Setting decibel volume. This has to be negative number in range ~-72..0)
begin
if (vol<0) and (vol>=-72) then volume:=round(4096*power(10,vol/20));
if vol<-72 then volume:=0;
if vol>=0 then volume:=4096;
end;
function noiseshaper9(bufaddr,outbuf,oversample,len:integer):integer;
label p101,p102,p999,i1l,i1r,i2l,i2r;
// -- rev 20170126
begin
asm
push {r0-r10,r12,r14}
ldr r3,i1l // init integerators
ldr r4,i1r
ldr r7,i2l
ldr r8,i2r
ldr r5,bufaddr // init buffers addresses
ldr r2,outbuf
ldr r14,oversample // yes, lr used here, I am short of regs :(
ldr r0,len // outer loop counter
p102: mov r1,r14 // inner loop counter
ldr r6,[r5],#4 // new input value left
ldr r12,[r5],#4 // new input value right
p101: add r3,r6 // inner loop: do oversampling
add r4,r12
add r7,r3
add r8,r4
mov r9,r7,asr #19
mov r10,r9,lsl #19
sub r3,r10
sub r7,r10
add r9,#1 // kill the negative bug :) :)
str r9,[r2],#4
mov r9,r8,asr #19
mov r10,r9,lsl #19
sub r4,r10
sub r8,r10
add r9,#1
str r9,[r2],#4
subs r1,#1
bne p101
subs r0,#1
bne p102
str r3,i1l
str r4,i1r
str r7,i2l
str r8,i2r
str r2,result
b p999
i1l: .long 0
i1r: .long 0
i2l: .long 0
i2r: .long 0
p999: pop {r0-r10,r12,r14}
end;
CleanDataCacheRange(outbuf,$10000);
end;
function noiseshaper8(bufaddr,outbuf,oversample,len:integer):integer;
label p101,p102,p999,i1l,i1r,i2l,i2r;
// -- rev 20170126
begin
asm
push {r0-r10,r12,r14}
ldr r3,i1l // init integerators
ldr r4,i1r
ldr r7,i2l
ldr r8,i2r
ldr r5,bufaddr // init buffers addresses
ldr r2,outbuf
ldr r14,oversample // yes, lr used here, I am short of regs :(
ldr r0,len // outer loop counter
p102: mov r1,r14 // inner loop counter
ldr r12,[r5],#4 // new input value left
ldr r6,[r5],#4 // new input value right
p101: add r3,r6 // inner loop: do oversampling
add r4,r12
add r7,r3
add r8,r4
mov r9,r7,asr #20
mov r10,r9,lsl #20
sub r3,r10
sub r7,r10
add r9,#1 // kill the negative bug :) :)
str r9,[r2],#4
mov r9,r8,asr #20
mov r10,r9,lsl #20
sub r4,r10
sub r8,r10
add r9,#1
str r9,[r2],#4
subs r1,#1
bne p101
subs r0,#1
bne p102
str r3,i1l
str r4,i1r
str r7,i2l
str r8,i2r
str r2,result
b p999
i1l: .long 0
i1r: .long 0
i2l: .long 0
i2r: .long 0
p999: pop {r0-r10,r12,r14}
end;
CleanDataCacheRange(outbuf,$10000);
end;
// Audio thread
// After the audio is opened it calls audiocallback when needed
constructor TAudioThread.Create(CreateSuspended : boolean);
begin
FreeOnTerminate := True;
inherited Create(CreateSuspended);
end;
procedure TAudioThread.Execute;
var
i:integer;
ns_size:integer;
begin
AudioOn:=1;
ThreadSetCPU(ThreadGetCurrent,CPU_ID_1);
ThreadSetPriority(ThreadGetCurrent,7);
threadsleep(1);
repeat
repeat threadsleep(1) until (dma_cs and 2) <>0 ;
working:=1;
nc:=dma_nextcb;
if pauseA>0 then // clean the buffers
begin
if nc=nocache+ctrl1_adr then for i:=0 to 16383 do dmabuf1_ptr[i]:=CurrentAudioSpec.range div 2;
if nc=nocache+ctrl2_adr then for i:=0 to 16383 do dmabuf2_ptr[i]:=CurrentAudioSpec.range div 2;
if nc=nocache+ctrl1_adr then CleanDataCacheRange(dmabuf1_adr,$10000);
if nc=nocache+ctrl2_adr then CleanDataCacheRange(dmabuf2_adr,$10000);
end
else
begin
// if not pause then we should call audiocallback to fill the buffer
if CurrentAudioSpec.callback<>nil then CurrentAudioSpec.callback(CurrentAudioSpec.userdata, samplebuffer_ptr, CurrentAudioSpec.size);
// the buffer has to be converted to 2 chn 32bit integer
if CurrentAudioSpec.channels=2 then // stereo
begin
case CurrentAudioSpec.format of
AUDIO_U8: for i:=0 to 2*CurrentAudioSpec.samples-1 do samplebuffer_32_ptr[i]:= volume*256*samplebuffer_ptr_b[i];
AUDIO_S16: for i:=0 to 2*CurrentAudioSpec.samples-1 do samplebuffer_32_ptr[i]:= volume*samplebuffer_ptr_si[i]+$8000000;
AUDIO_F32: for i:=0 to 2*CurrentAudioSpec.samples-1 do samplebuffer_32_ptr[i]:= round(volume*32768*samplebuffer_ptr_f[i])+$8000000;
end;
end
else
begin
case CurrentAudioSpec.format of
AUDIO_U8: for i:=0 to CurrentAudioSpec.samples-1 do begin samplebuffer_32_ptr[2*i]:= volume*256*samplebuffer_ptr_b[i]; samplebuffer_32_ptr[2*i+1]:= samplebuffer_32_ptr[2*i]; end;
AUDIO_S16: for i:=0 to CurrentAudioSpec.samples-1 do begin samplebuffer_32_ptr[2*i]:= volume*samplebuffer_ptr_si[i]+$8000000; samplebuffer_32_ptr[2*i+1]:= samplebuffer_32_ptr[2*i]; end;
AUDIO_F32: for i:=0 to CurrentAudioSpec.samples-1 do begin samplebuffer_32_ptr[2*i]:= round(volume*32768*samplebuffer_ptr_f[i])+$8000000; samplebuffer_32_ptr[2*i+1]:= samplebuffer_32_ptr[2*i]; end;
end;
end;
if nc=nocache+ctrl1_adr then noiseshaper8(samplebuffer_32_adr,dmabuf1_adr,CurrentAudioSpec.oversample,CurrentAudioSpec.samples)
else noiseshaper8(samplebuffer_32_adr,dmabuf2_adr,CurrentAudioSpec.oversample,CurrentAudioSpec.samples);
if nc=nocache+ctrl1_adr then CleanDataCacheRange(dmabuf1_adr,$10000) else CleanDataCacheRange(dmabuf2_adr,$10000);
end;
dma_cs:=$00FF0003;
working:=0;
until terminated;
AudioOn:=0;
end;
function SA_GetCurrentFreq:integer;
begin
result:=CurrentAudioSpec.freq;
end;
function SA_GetCurrentRange:integer;
begin
result:=CurrentAudioSpec.range;
end;
end.
|
unit ncBaseWebApi;
{
ResourceString: Dario 12/03/13
}
interface
uses Dialogs, SysUtils, Winsock, Windows, ExtActns, ActiveX, UrlMon, Automation, uMyBrowser, SHFolder, Classes, Forms, idHttp;
type
TncBaseWebApi = class ( TMyWebApi )
published
function DotNetInstalled(const aVer: OleVariant): OleVariant;
function FileVersion(const aFileName: OleVariant): OleVariant;
function LogInfo(const aString: OleVariant): OleVariant; override;
function Conta: OleVariant;
function ContaFree: OleVariant;
function ContaPremium: OleVariant;
function AppVer: OleVariant;
function FullAppVer: OleVariant;
function ShellStart(const aCmd, aParams, aDir: OleVariant): OleVariant; override;
function ServerIP: OleVariant; virtual;
function UsernameFunc: OleVariant; virtual;
function UserAdmin: OleVariant; virtual;
function PopupUrl(const aURL: OleVariant): OleVariant; virtual;
end;
implementation
uses
ncShellStart, ncClassesBase, ncVersionInfo, ncDebug,
ncFrmWebPopup, uLicEXECryptor;
{ TncBaseWebApi }
function TncBaseWebApi.UserAdmin: OleVariant;
begin
Result := 0;
end;
function TncBaseWebApi.AppVer: OleVariant;
begin
Result := Trim(Copy(SelfVersion, 7, 20));
end;
function TncBaseWebApi.Conta: OleVariant;
begin
Result := gConfig.Conta;
end;
function TncBaseWebApi.ContaFree: OleVariant;
begin
Result := gConfig.FreePremium and (gConfig.StatusConta<>scPremium);
end;
function TncBaseWebApi.ContaPremium: OleVariant;
begin
Result := gConfig.FreePremium and (gConfig.StatusConta=scPremium);
end;
function GetSysFolder(csidl: integer): String;
const
TOKEN_DEFAULTUSER = $FFFF; // -1
var
szBuffer: AnsiString; // <-- here
ResultCode: Integer;
begin
Result := ''; // avoid function might return undefined warning
SetLength(szBuffer, 255);
ResultCode := SHGetFolderPathA(0, CSIDL, TOKEN_DEFAULTUSER,
0, PAnsiChar(szBuffer));
if ResultCode = 0 then
Result := String(PAnsiChar(szBuffer));
end;
function TncBaseWebApi.DotNetInstalled(const aVer: OleVariant): OleVariant;
var
s: String;
sr : TSearchRec;
begin
Result := 0;
s := GetSysFolder(CSIDL_WINDOWS) + '\Microsoft.NET\Framework'; // do not localize
if not DirectoryExists(s) then Exit;
if FindFirst(s+'\*.*', faDirectory, sr)=0 then
try
repeat
s := aVer;
if Pos(s, sr.Name)=1 then begin
Result := 1;
Exit;
end;
until (FindNext(sr)<>0);
finally
SysUtils.FindClose(sr);
end;
end;
function TncBaseWebApi.FileVersion(const aFileName: OleVariant): OleVariant;
begin
ncVersionInfo.GetVersionInfo(aFileName);
end;
function TncBaseWebApi.FullAppVer: OleVariant;
begin
Result := SelfVersion;
end;
function TncBaseWebApi.LogInfo(const aString: OleVariant): OleVariant;
begin
DebugMsg('TncBaseWebApi.LogInfo: ' + aString); // do not localize
end;
function TncBaseWebApi.PopupUrl(const aURL: OleVariant): OleVariant;
var F: TFrmWebPopup;
begin
if FrmWebPopupClass<>nil then begin
F := FrmWebPopupClass.Create(nil);
F.URL := aURL;
F.Show;
Result := 1;
end else
Result := 0;
end;
function TncBaseWebApi.ServerIP: OleVariant;
begin
Result := '127.0.0.1'; // do not localize
end;
function TncBaseWebApi.ShellStart(const aCmd, aParams,
aDir: OleVariant): OleVariant;
var
sCmd, sParams, sDir: String;
begin
sCmd := aCmd;
sParams := aParams;
sDir := aDir;
DebugMsg('TncBaseWebApi.ShellStart - aCmd: ' + aCmd + ' - aParams: ' + aParams + ' - aDir: ' + aDir); // do not localize
ncShellStart.ShellStart(sCmd, sParams, sDir);
Result := 1;
end;
function TncBaseWebApi.UsernameFunc: OleVariant;
begin
Result := ncClassesBase.UsernameAtual;
end;
{ ThreadRenameExec }
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.SettingsList;
interface
uses
System.Generics.Collections;
const
SETTINGSDBFILE = 'settings.dat'; // do not localize
type
TSettingsList = class(TObject)
private const
cWidth = 'width';
cWidthKey = 'widthkey';
private
FWidths: TDictionary<string, Integer>;
FFilename: string;
public
constructor Create(const AFilename: string = ''); overload;
destructor Destroy; override;
procedure Clear;
procedure AddWidth(const AKey: string; AWidth: Integer);
function GetWidth(const AKey: string; out AWidth: Integer): Boolean;
procedure SaveToFile(const AFilename: string = '');
procedure LoadFromFile(const AFilename: string = '');
end;
implementation
uses
System.JSON, System.SysUtils, System.Classes;
{ TSettingsList }
constructor TSettingsList.Create(const AFilename: string = '');
begin
inherited Create;
FWidths := TDictionary<string, Integer>.Create;
FFilename := AFilename;
if (FFilename <> '') and FileExists(FFilename) then
LoadFromFile(FFilename);
end;
destructor TSettingsList.Destroy;
begin
FWidths.Free;
inherited;
end;
procedure TSettingsList.Clear;
begin
FWidths.Clear;
end;
procedure TSettingsList.AddWidth(const AKey: string; AWidth: Integer);
begin
FWidths.AddOrSetValue(AKey, AWidth);
end;
function TSettingsList.GetWidth(const AKey: string;
out AWidth: Integer): Boolean;
begin
Result := FWidths.TryGetValue(AKey, AWidth)
end;
procedure TSettingsList.LoadFromFile(const AFilename: string);
var
LStream: TStringStream;
LRoot: TJSONArray;
LFilename: string;
i: Integer;
LValue: TJSONValue;
LWidth: Integer;
LKey: string;
begin
Clear;
if (AFilename <> '') then
LFilename := AFilename
else
LFilename := FFilename;
if (LFilename = '') or not FileExists(LFilename) then
Exit;
LStream := TStringStream.Create;
try
LStream.LoadFromFile(LFilename);
LRoot := TJSONObject.ParseJSONValue(LStream.DataString) as TJSONArray;
try
for i := 0 to LRoot.Count - 1 do
begin
LValue := LRoot.Items[i] as TJSONObject;
if LValue.TryGetValue<string>(cWidthKey, LKey) and
LValue.TryGetValue<Integer>(cWidth, LWidth) then
FWidths.AddOrSetValue(LKey, LWidth);
end;
finally
LRoot.Free;
end;
finally
LStream.Free;
end;
end;
procedure TSettingsList.SaveToFile(const AFilename: string = '');
var
LStream: TStringStream;
LRoot: TJSONArray;
LFilename: string;
LPair: TPair<string, Integer>;
LJSONObject: TJSONObject;
begin
if (AFilename <> '') then
LFilename := AFilename
else
LFilename := FFilename;
if (LFilename = '') then
Exit;
LRoot := TJSONArray.Create;
try
for LPair in FWidths do
begin
LJSONObject := TJSONObject.Create;
LJSONObject.AddPair(cWidthKey, TJSONString.Create(LPair.Key));
LJSONObject.AddPair(cWidth, TJSONNumber.Create(LPair.Value));
LRoot.AddElement(LJSONObject);
end;
LStream := TStringStream.Create(LRoot.ToString);
try
LStream.SaveToFile(LFilename);
finally
LStream.Free;
end;
finally
LRoot.Free;
end;
end;
end.
|
unit UnitFolha;
interface
type
TFolha = class(TObject)
SB: Double;
INSS:Double;
FGTS:Double;
IR:Double;
SL:Double;
Function Calcula_INSS(X:Double):Double;
Function Calcula_FGTS(X:Double):Double;
Function Calcula_IR(X:Double):Double;
Function Calcula_SL(X:Double):Double;
end;
var
Folha:TFolha;
implementation
function TFolha.Calcula_FGTS(X:Double):Double;
begin
FGTS:= X * 0.08;
Result:=FGTS;
end;
function TFolha.Calcula_INSS (X:Double):Double;
begin
if X <= 752.62 then
INSS:=X * 0.0765
else
if X <= 780.00 then
INSS:= X * 0.0865
else
if X <= 1254.36 then
INSS:= X * 0.09
else
if X <= 2508.72 then
INSS:= X * 0.11
else
INSS:= 275.95;
Result:=INSS;
end;
function TFolha.Calcula_IR (X:Double):Double;
begin
if X <= 1164.00 then
IR:= X * 0.00-0.00
else
if X <= 2326.00 then
IR:= (X * 0.15) - 174.60
else
IR:= (X * 0.275) - 465.35;
Result:=IR;
end;
function TFolha.Calcula_SL(X:Double):Double;
begin
SB:= X;
SL:=(SB - (Calcula_INSS(X) + Calcula_IR(X-INSS)));
Result:=SL;
end;
end.
|
unit IdCoderText;
interface
uses
Classes,
IdCoder;
type
TIdQuotedPrintableEncoder = class(TIdCoder)
protected
FQPOutputString: string;
procedure QPOutput(const sOut: string); virtual;
function ToQuotedPrintable(const b: Byte): string;
procedure Coder; override;
procedure CompleteCoding; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Reset; override;
end;
TIdQuotedPrintableDecoder = class(TIdCoder)
protected
fQPTriple: string;
fInTriple: Byte;
procedure Coder; override;
procedure CompleteCoding; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Reset; override;
end;
implementation
uses
IdGlobal,
SysUtils;
const
QPLowBound = 32;
QPMidBound = 61;
QPHighBound = 126;
QPEDBDIC = '!"#$@[\]^`{|}~';
constructor TIdQuotedPrintableEncoder.Create;
begin
inherited Create(AOwner);
fAddCRLF := False;
FQPOutputString := '';
end;
destructor TIdQuotedPrintableEncoder.Destroy;
begin
inherited;
end;
procedure TIdQuotedPrintableEncoder.Reset;
begin
FQPOutputString := '';
end;
procedure TIdQuotedPrintableEncoder.Coder;
var
i: LongWord;
b: Byte;
s: string;
begin
s := '';
i := 1;
while i <= FCBufferSize do
begin
b := Byte(FCBuffer[i]);
if (b >= QPLowBound) and (b <= QPHighBound) then
begin
if b = QPMidBound then
begin
s := s + ToQuotedPrintable(QPMidBound);
end
else
if IndyPos(Char(b), QPEDBDIC) > 0 then
begin
s := s + ToQuotedPrintable(b);
end
else
begin
s := s + Char(b);
end;
end
else
begin
if b = Byte(CR) then
begin
if i < FCBufferSize then
begin
if FCBuffer[i + 1] = LF then
begin
s := s + EOL;
Inc(i);
end
else
begin
s := s + ToQuotedPrintable(b);
end;
end
else
begin
FCBufferedData := 1;
FCBuffer[1] := Char(b);
QPOutput(s);
Exit;
end;
end
else
begin
s := s + ToQuotedPrintable(b);
end;
end;
Inc(i);
end;
QPOutput(s);
FCBufferedData := 0;
end;
procedure TIdQuotedPrintableEncoder.QPOutput;
var
s: string;
i: LongWord;
begin
FQPOutputString := FQPOutputString + sOut;
i := IndyPos(EOL, FQPOutputString);
while i > 0 do
begin
s := Copy(FQPOutputString, 1, i - 1);
FQPOutputString := Copy(FQPOutputString, i + 2, length(FQPOutputString));
i := length(s);
if i > 0 then
begin
case s[i] of
' ', TAB:
begin
s := s + Copy(ToQuotedPrintable(Byte(s[i])), 2, 2);
s[i] := '=';
end;
else
s := s + CR + LF;
end;
end
else
begin
s := CR + LF;
end;
OutputString(s);
i := IndyPos(EOL, FQPOutputString);
end;
while length(FQPOutputString) > 75 do
begin
if FQPOutputString[73] = '=' then
begin
i := 72;
end
else
if FQPOutputString[74] = '=' then
begin
i := 73;
end
else
if FQPOutputString[75] = '=' then
begin
i := 74;
end
else
begin
i := 75;
end;
OutputString(Copy(FQPOutputString, 1, i) + '=');
FQPOutputString := Copy(FQPOutputString, i + 1, length(FQPOutputString));
end;
end;
procedure TIdQuotedPrintableEncoder.CompleteCoding;
var
i, j: LongWord;
begin
fInCompletion := True;
i := FCBufferSize;
InternSetBufferSize(FCBufferedData);
FCBufferedData := FCBufferSize;
if FCBufferedData > 0 then
begin
Coder;
end;
if FCBufferedData > 0 then
begin
QPOutput(ToQuotedPrintable(13));
end;
j := Length(FQPOutputString);
if j > 0 then
begin
case FQPOutputString[j] of
' ', TAB:
begin
FQPOutputString := FQPOutputString + Copy(ToQuotedPrintable(
Byte(FQPOutputString[j])), 2, 2);
FQPOutputString[j] := '=';
end;
end;
while length(FQPOutputString) > 75 do
begin
if FQPOutputString[73] = '=' then
begin
i := 72;
end
else
if FQPOutputString[74] = '=' then
begin
i := 73;
end
else
if FQPOutputString[75] = '=' then
begin
i := 74;
end
else
begin
i := 75;
end;
OutputString(Copy(FQPOutputString, 1, i) + '=');
FQPOutputString := Copy(FQPOutputString, i + 1, length(FQPOutputString));
end;
OutputString(FQPOutputString);
end;
InternSetBufferSize(i);
FCBufferedData := 0;
end;
function TIdQuotedPrintableEncoder.ToQuotedPrintable;
begin
result := '=' + UpperCase(IntToHex(b, 2));
end;
constructor TIdQuotedPrintableDecoder.Create;
begin
inherited Create(AOwner);
fQPTriple := '';
SetLength(fQPTriple, 2);
UniqueString(fQPTriple);
fAddCRLF := False;
fInTriple := 0;
end;
destructor TIdQuotedPrintableDecoder.Destroy;
begin
inherited;
end;
procedure TIdQuotedPrintableDecoder.Reset;
begin
fAddCRLF := False;
fInTriple := 0;
end;
procedure TIdQuotedPrintableDecoder.Coder;
var
i: LongWord;
s: string;
c: Char;
function IsHex(c: Char): Boolean;
begin
case c of
'0'..'9', 'a'..'f', 'A'..'F':
begin
result := true;
end;
else
result := False;
end;
end;
begin
i := 1;
s := '';
while i <= FCBufferedData do
begin
c := FCBuffer[i];
if fInTriple > 0 then
begin
fQPTriple[fInTriple] := c;
Inc(fInTriple);
if fInTriple >= 3 then
begin
if IsHex(fQPTriple[1]) and IsHex(fQPTriple[2]) then
begin
s := s + Chr(StrToInt('$' + fQPTriple));
end
else
if (fQPTriple[1] = CR) and (fQPTriple[2] = LF) then
begin
end
else
begin
s := s + '=' + fQPTriple;
end;
fInTriple := 0;
end;
end
else
if c = '=' then
begin
Inc(fInTriple);
end
else
begin
s := s + c;
end;
Inc(i);
end;
OutputString(s);
FCBufferedData := 0;
end;
procedure TIdQuotedPrintableDecoder.CompleteCoding;
begin
fInCompletion := True;
Coder;
if fInTriple > 0 then
begin
OutputString(Copy(fQPTriple, 1, fInTriple - 1));
FCBufferedData := 0;
end;
end;
initialization
RegisterCoderClass(TIdQuotedPrintableEncoder, CT_CREATION, CP_STANDARD,
'', 'quoted-printable');
RegisterCoderClass(TIdQuotedPrintableDecoder, CT_REALISATION, CP_STANDARD,
'', 'quoted-printable');
end.
|
unit adot.Tools.Rtti;
{ Definition of classes/record types:
TEnumeration<T: record> = record
Conversion between enumeration type, ordinal value and string value.
TRttiUtils = class
IsInstance<T>, ValueAsString<T>, CreateInstance<T: class> etc.
}
interface
uses
System.Rtti,
System.TypInfo,
System.Math,
System.Classes,
System.SysUtils;
type
TConvOption = (
coReadable,
coStreamAsString
);
TConvOptions = set of TConvOption;
const
defConvOptions = [coReadable, coStreamAsString];
type
TConvSettings = record
Options: TConvOptions;
MaxArrayCount: integer;
MaxDepth: integer;
procedure Init;
end;
{ IsInstance<T>, ValueAsString<T>, CreateInstance<T: class> etc }
TRttiUtils = class
private
public
{ Returns True if T is class (instance can be created) }
class function IsInstance<T>: boolean; static;
class function IsOrdinal<T>: boolean; static;
{ Convert value of type T to string }
class function ValueAsString<T>(const Value: T): string; static;
{ Find latest public constructor in hierarchy and create instance/object of the class. Supports:
Create()
Create(ACapacity: integer)
Create(Capacity: integer)
Create(AOwner: TComponent)
Create(Owner: TComponent) }
class function CreateInstance<T: class>: T; static;
class function FromVariant<T>(const Src: Variant): T; static;
{ can be used for access to private fields }
class function GetFieldValue<T>(Obj: TObject; const AFieldName: string): T; static;
class procedure SetFieldValue<T>(Obj: TObject; const AFieldName: string; const Value: T); static;
{ returns object details in readable JSON (for log etc) }
class function ObjectAsJson(Src: TObject): string; overload; static;
class function ObjectAsJson(Src: TObject; const Settings: TConvSettings): string; overload; static;
end;
{ Simple convertion EnumType->string->EnumType etc.
http://stackoverflow.com/questions/31601707/generic-functions-for-converting-an-enumeration-to-string-and-back#31604647 }
{ Conversion between enumeration type, ordinal value and string value }
TEnumeration<T: record> = record
strict private
class function TypeInfo: PTypeInfo; static;
class function TypeData: PTypeData; static;
public
class function IsEnumeration: Boolean; static;
class function ToOrdinal(Enum: T): Integer; static;
class function FromOrdinal(Value: Integer): T; static;
class function ToString(Enum: T): string; static;
class function FromString(const S: string): T; static;
class function MinValue: Integer; static;
class function MaxValue: Integer; static;
class function InRange(Value: Integer): Boolean; static;
class function EnsureRange(Value: Integer): Integer; static;
end;
implementation
uses
adot.Tools,
adot.Strings,
adot.JSON.JBuilder;
type
TObjectToJson = class
private
Settings: TConvSettings;
Dst: TJBuilder;
procedure ObjectToJson(const PropName: string; Src: TObject; Depth: integer);
procedure ValueToJson(const PropName: string; var Value: TValue; Depth: integer);
procedure StreamToJson(const PropName: string; Stream: TStream);
public
constructor Create(const ASettings: TConvSettings); overload;
constructor Create; overload;
function Get(Src: TObject): string;
end;
{ TObjectToJson }
constructor TObjectToJson.Create(const ASettings: TConvSettings);
begin
Settings := ASettings;
end;
constructor TObjectToJson.Create;
var Settings: TConvSettings;
begin
Settings.Init;
Create(Settings);
end;
procedure TObjectToJson.StreamToJson(const PropName: string; Stream: TStream);
var
P: Int64;
B: TArray<byte>;
S: string;
I: Integer;
AsText: Boolean;
begin
{ read as bytes }
P := Stream.Position;
Stream.Position := 0;
SetLength(B, Stream.Size);
Stream.ReadBuffer(B, Stream.Size);
Stream.Position := P;
{ convert to text }
AsText := (coStreamAsString in Settings.Options);
if AsText and TEnc.IsValidUtf8(B) then
try
S := TEncoding.UTF8.GetString(B);
except
AsText := False;
end;
{ write to dst }
if AsText then
begin
if PropName=''
then Dst.Add(S)
else Dst.Add(PropName, S)
end
else
begin
if PropName=''
then Dst.BeginArray
else Dst.BeginArray(PropName);
for I := 0 to Min(Length(B), Settings.MaxArrayCount)-1 do
Dst.Add(B[I]);
if Length(B) > Settings.MaxArrayCount then
Dst.Add('<...>');
Dst.EndArray;
end;
end;
procedure TObjectToJson.ValueToJson(const PropName: string; var Value: TValue; Depth: integer);
var
I: Integer;
V: TValue;
Obj: TObject;
begin
case Value.Kind of
tkClass:
begin
Obj := Value.AsObject;
if Obj is TStream then
begin
if PropName <> '' then
Dst.BeginObject(PropName);
StreamToJson(Value.ToString, TStream(Obj));
if PropName <> '' then
Dst.EndObject;
Exit;
end
else
if Depth > 1 then
begin
ObjectToJson(PropName, Obj, Depth-1);
Exit;
end;
end;
tkDynArray:
begin
if PropName = ''
then Dst.BeginArray
else Dst.BeginArray(PropName);
for I := 0 to Min(Value.GetArrayLength, Settings.MaxArrayCount)-1 do
begin
V := Value.GetArrayElement(I);
ValueToJson('', V, Depth-1);
end;
if Value.GetArrayLength > Settings.MaxArrayCount then
Dst.Add('<...>');
Dst.EndArray;
Exit;
end;
end;
if PropName = ''
then Dst.Add(Value.ToString)
else Dst.Add(PropName, Value.ToString)
end;
procedure TObjectToJson.ObjectToJson(const PropName: string; Src: TObject; Depth: integer);
var
RttiType: TRttiType;
RttiContext: TRttiContext;
RttiProp: TRttiProperty;
RttiValue: TValue;
S: string;
begin
S := TRttiUtils.ValueAsString<TObject>(Src);
if Src = nil
then S := 'nil'
else S := TRttiUtils.ValueAsString<TObject>(Src);
if (Depth <= 0) or (Src = nil) then
begin
if PropName = ''
then Dst.Add(S)
else Dst.Add(PropName, S);
Exit;
end;
if PropName = '' then
Dst.BeginObject(S)
else
begin
Dst.BeginObject(PropName);
Dst.BeginObject(S);
end;
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(Src.ClassType);
for RttiProp in RttiType.GetProperties do
begin
if not RttiProp.IsReadable then
Continue;
RttiType := RttiProp.PropertyType;
if not RttiType.IsPublicType then
Continue;
RttiValue := RttiProp.GetValue(Src);
ValueToJson(RttiProp.Name, RttiValue, Depth-1);
end;
Dst.EndObject;
if PropName <> '' then
Dst.EndObject;
end;
function TObjectToJson.Get(Src: TObject): string;
begin
Dst.Init;
ObjectToJson('', Src, Settings.MaxDepth);
result := Dst.ToString;
end;
{ TConvSettings }
procedure TConvSettings.Init;
begin
Self := Default(TConvSettings);
Options := defConvOptions;
MaxArrayCount := High(MaxArrayCount);
MaxDepth := 10*1024*1024;
end;
{ TRttiUtils }
class function TRttiUtils.CreateInstance<T>: T;
var
TypInf: PTypeInfo;
Value: TValue;
RttiContext: TRttiContext;
RttiType: TRttiType;
RttiInstanceType: TRttiInstanceType;
Method: TRttiMethod;
Params: TArray<TRttiParameter>;
begin
TypInf := TypeInfo(T);
{ We use more general solution for "Create(AOwner: TComponent)", but
for descendants of TComponent we can avoid extra checks. }
if TypInf.TypeData.ClassType.InheritsFrom(TComponent) then
result := T(TComponentClass(TypInf.TypeData.ClassType).Create(nil));
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(TypeInfo(T));
if not RttiType.IsInstance then
Exit;
for Method in RttiType.GetMethods do
if Method.IsConstructor and SameText(Method.Name, 'Create') then
begin
Params := Method.GetParameters;
{ "Create()". }
if Length(Params)=0 then
begin
RttiInstanceType := RttiType.AsInstance;
Value := Method.Invoke(RttiInstanceType.MetaclassType, []);
Result := Value.AsType<T>;
Exit;
end;
// "Create(ACapacity: integer = 0)".
// There is no way to check default value, but usually such constructor
// hides "Create()", for example:
// "TDictionary<byte,byte>.Create" means "Create(ACapacity = 0)".
if (Length(Params)=1) and
((Params[0].Flags=[]) or (Params[0].Flags=[TParamFlag.pfConst])) and
(Params[0].ParamType<>nil) and (Params[0].ParamType.TypeKind in [tkInteger, tkInt64]) and
(AnsiSameText(Params[0].Name, 'ACapacity') or AnsiSameText(Params[0].Name, 'Capacity'))
then
begin
RttiInstanceType := RttiType.AsInstance;
Value := Method.Invoke(RttiInstanceType.MetaclassType, [0]);
Result := Value.AsType<T>;
Exit;
end;
// "Create(AOwner: TComponent)".
if (Length(Params)=1) and
(Params[0].Flags=[TParamFlag.pfAddress]) and
(Params[0].ParamType<>nil) and (Params[0].ParamType.TypeKind in [tkClass]) and
(AnsiSameText(Params[0].Name, 'AOwner') or AnsiSameText(Params[0].Name, 'Owner'))
then
begin
RttiInstanceType := RttiType.AsInstance;
Value := Method.Invoke(RttiInstanceType.MetaclassType, [nil]);
Result := Value.AsType<T>;
Exit;
end;
end; // For Method in RttiType.GetMethods
end; // If
// Should never happend, because TObject has "Create()".
raise Exception.Create('Default constructor is not found');
end;
class function TRttiUtils.FromVariant<T>(const Src: Variant): T;
begin
result := TValue.FromVariant(Src).AsType<T>;
end;
class function TRttiUtils.GetFieldValue<T>(Obj: TObject; const AFieldName: string): T;
var
RttiType : TRttiType;
RttiContext : TRttiContext;
RttiField : TRttiField;
Ptr : ^T;
begin
RttiType := RttiContext.GetType(Obj.ClassType);
Assert(Assigned(RttiType));
for RttiField in RttiType.GetFields do
if AnsiLowerCase(AFieldName)=AnsiLowerCase(RttiField.Name) then
begin
Ptr := Pointer(PByte(Obj) + RttiField.Offset);
result := Ptr^;
Exit;
end;
raise Exception.Create(format('Field "%s" is not found (%s)', [AFieldName, Obj.ClassName]));
end;
class procedure TRttiUtils.SetFieldValue<T>(Obj: TObject; const AFieldName: string; const Value: T);
var
RttiType : TRttiType;
RttiContext : TRttiContext;
RttiField : TRttiField;
Ptr : ^T;
begin
RttiType := RttiContext.GetType(Obj.ClassType);
Assert(Assigned(RttiType));
for RttiField in RttiType.GetFields do
if AnsiLowerCase(AFieldName)=AnsiLowerCase(RttiField.Name) then
begin
Ptr := Pointer(PByte(Obj) + RttiField.Offset);
Ptr^ := Value;
Exit;
end;
raise Exception.Create(format('Field "%s" is not found (%s)', [AFieldName, Obj.ClassName]));
end;
class function TRttiUtils.IsInstance<T>: boolean;
var
RttiContext: TRttiContext;
RttiType: TRttiType;
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(TypeInfo(T));
result := (RttiType<>nil) and RttiType.IsInstance;
end;
class function TRttiUtils.IsOrdinal<T>: boolean;
var
RttiContext: TRttiContext;
RttiType: TRttiType;
begin
RttiContext := TRttiContext.Create;
RttiType := RttiContext.GetType(TypeInfo(T));
result := (RttiType<>nil) and RttiType.IsOrdinal;
end;
class function TRttiUtils.ObjectAsJson(Src: TObject; const Settings: TConvSettings): string;
var
C: TObjectToJson;
begin
C := TObjectToJson.Create(Settings);
try
result := C.Get(Src);
finally
C.Free;
end;
end;
class function TRttiUtils.ObjectAsJson(Src: TObject): string;
var
Settings: TConvSettings;
begin
Settings.Init;
result := ObjectAsJson(Src, Settings);
end;
class function TRttiUtils.ValueAsString<T>(const Value: T): string;
begin
result := TValue.From<T>(Value).ToString;
end;
{ TEnumeration<T> }
class function TEnumeration<T>.TypeInfo: PTypeInfo;
begin
Result := System.TypeInfo(T);
end;
class function TEnumeration<T>.TypeData: PTypeData;
begin
Result := System.TypInfo.GetTypeData(TypeInfo);
end;
class function TEnumeration<T>.IsEnumeration: Boolean;
begin
Result := TypeInfo.Kind=tkEnumeration;
end;
class function TEnumeration<T>.ToOrdinal(Enum: T): Integer;
begin
Assert(IsEnumeration);
Assert(SizeOf(Enum)<=SizeOf(Result));
Result := 0; // needed when SizeOf(Enum) < SizeOf(Result)
Move(Enum, Result, SizeOf(Enum));
Assert(InRange(Result));
end;
class function TEnumeration<T>.FromOrdinal(Value: Integer): T;
begin
Assert(IsEnumeration);
Assert(InRange(Value));
Assert(SizeOf(Result)<=SizeOf(Value));
Move(Value, Result, SizeOf(Result));
end;
class function TEnumeration<T>.ToString(Enum: T): string;
begin
Result := GetEnumName(TypeInfo, ToOrdinal(Enum));
end;
class function TEnumeration<T>.FromString(const S: string): T;
begin
Result := FromOrdinal(GetEnumValue(TypeInfo, S));
end;
class function TEnumeration<T>.MinValue: Integer;
begin
Assert(IsEnumeration);
Result := TypeData.MinValue;
end;
class function TEnumeration<T>.MaxValue: Integer;
begin
Assert(IsEnumeration);
Result := TypeData.MaxValue;
end;
class function TEnumeration<T>.InRange(Value: Integer): Boolean;
var
ptd: PTypeData;
begin
Assert(IsEnumeration);
ptd := TypeData;
Result := System.Math.InRange(Value, ptd.MinValue, ptd.MaxValue);
end;
class function TEnumeration<T>.EnsureRange(Value: Integer): Integer;
var
ptd: PTypeData;
begin
Assert(IsEnumeration);
ptd := TypeData;
Result := System.Math.EnsureRange(Value, ptd.MinValue, ptd.MaxValue);
end;
end.
|
{***************************************************************
*
* Project : TimeDemo
* Unit Name: Main
* Purpose : Demonstrates a DateTime client getting current date and time from remote DateTimeServer
* Date : 21/01/2001 - 12:55:37
* History :
*
****************************************************************}
unit Main;
// A list of time servers is available at:
// http://www.eecis.udel.edu/~mills/ntp/servers.html
interface
uses
{$IFDEF Linux}
QGraphics, QControls, QForms, QDialogs, QStdCtrls,
{$ELSE}
windows, messages, graphics, controls, forms, dialogs, stdctrls,
{$ENDIF}
SysUtils, Classes, IdComponent, IdTCPConnection, IdTCPClient, IdTime,
IdBaseComponent;
type
TfrmTimeDemo = class(TForm)
lblTimeServer: TLabel;
IdDemoTime: TIdTime;
edtTimeResult: TEdit;
Label1: TLabel;
btnGetTime: TButton;
cmboTimeServer: TComboBox;
procedure btnGetTimeClick(Sender: TObject);
private
public
end;
var
frmTimeDemo: TfrmTimeDemo;
implementation
{$IFDEF MSWINDOWS}{$R *.dfm}{$ELSE}{$R *.xfm}{$ENDIF}
// No real code required - all functionality built into component !
procedure TfrmTimeDemo.btnGetTimeClick(Sender: TObject);
begin
IdDemoTime.Host := cmboTimeServer.Text;
{ After setting Host, this is all you have to get the time from a time
server. We do the rest. }
edtTimeResult.Text := DateTimeToStr ( IdDemoTime.DateTime );
end;
end.
|
unit multiLangMainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TMultiLangMainForm = class(TForm)
cbLanguage: TComboBox;
memoMessages: TMemo;
btnOK: TButton;
procedure FormShow(Sender: TObject);
procedure cbLanguageChange(Sender: TObject);
private
{ Private declarations }
procedure LoadMessages;
public
{ Public declarations }
end;
var
frmMultiLangMainForm: TMultiLangMainForm;
implementation
uses
mORMoti18n,
ResMessages;
{$R *.dfm}
procedure TMultiLangMainForm.cbLanguageChange(Sender: TObject);
var
lang: TLanguages;
begin
lang := LanguageAbrToIndex(cbLanguage.Text);
SetCurrentLanguage(lang);
Language.FormTranslateOne(frmMultiLangMainForm);
LoadMessages;
end;
procedure TMultiLangMainForm.FormShow(Sender: TObject);
begin
{$IFDEF EXTRACTALLRESOURCES}
ExtractAllResources(
// first, all enumerations to be translated
[], // TypeInfo(TFileEvent),TypeInfo(TFileAction),TypeInfo(TPreviewAction)],
// then some class instances (including the TSQLModel will handle all TSQLRecord)
[], // Client.Model],
// some custom classes or captions
[], []);
Close;
{$ELSE}
// i18nLanguageToRegistry(lngFrench);
SetCurrentLanguage(lngPolish);
Language.FormTranslateOne(self);
LoadMessages;
{$ENDIF}
end;
procedure TMultiLangMainForm.LoadMessages;
begin
memoMessages.Lines.Clear;
memoMessages.Lines.Add(msg1);
memoMessages.Lines.Add(msg2);
memoMessages.Lines.Add(msg3);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.