text stringlengths 14 6.51M |
|---|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ XML Transform Components }
{ }
{ Copyright (c) 2000-2001 Borland Software Corporation }
{ }
{*******************************************************}
unit Xmlxform;
interface
uses
Variants, SysUtils, Classes, Provider, DB, DBClient, DSIntf,
xmldom, xmlutil;
type
TranslateException = class(Exception);
{ TXMLTransform }
TTranslateEvent = procedure(Sender: TObject; Id: string;
SrcNode: IDOMNode; var Value: string; DestNode: IDOMNode) of object;
TRowEvent = procedure(Sender: TObject; Id: string;
SrcNode: IDOMNode; DestNode: IDOMNode) of object;
TXMLTransform = class(TComponent)
private
FEncoding: string;
FEncodingTrans: string;
FDirectionToCds: Boolean;
FVersion: string;
FSourceXmlFile: string;
FSourceXmlDocument: IDOMDocument;
FSourceXml: string;
FTransformationFile: string;
FTransformationDocument: IDOMDocument;
FEmptyDestinationDocument: IDOMDocument; //Insert into this, if present
FResultDocument: IDOMDocument;
FResultString: string;
FOnTranslate: TTranslateEvent;
FBeforeEachRow: TRowEvent;
FAfterEachRow: TRowEvent;
FBeforeEachRowSet: TRowEvent;
FAfterEachRowSet: TRowEvent;
protected
procedure Translate(const Id: string; const SrcNode: IDOMNode;
var SrcValue: string; const DestNode: IDOMNode); dynamic;
function DoTransform(const XMLSrc, XMLExtract, XMLOut: IDOMDocument): string;
procedure Transform(TransNode, SrcNode, DestNode: IDOMNode;
Count: Integer; InFromList, InDestList, InIdStrList, InValueList,
InOptionalList, InDateFormatList, InDateFormatTypeList,
InMapValuesList: TStringList);
function GetData: string;
function GetResultString: string;
public
function TransformXML(const SourceXml: string;
const ATransformationFile: string = ''): string;
property Data: string read GetData ;
property SourceXmlDocument: IDOMDocument read FSourceXmlDocument write FSourceXmlDocument;
property SourceXmlFile: string read FSourceXmlFile write FSourceXmlFile;
property SourceXml: string read FSourceXml write FSourceXml;
property TransformationDocument: IDOMDocument read FTransformationDocument write FTransformationDocument;
property EmptyDestinationDocument: IDOMDocument read FEmptyDestinationDocument write FEmptyDestinationDocument;
property ResultDocument: IDOMDocument read FResultDocument;
property ResultString: string read GetResultString;
published
property TransformationFile: string read FTransformationFile write FTransformationFile;
property OnTranslate: TTranslateEvent read FOnTranslate write FOnTranslate;
property BeforeEachRow: TRowEvent read FBeforeEachRow write FBeforeEachRow;
property AfterEachRow: TRowEvent read FAfterEachRow write FAfterEachRow;
property BeforeEachRowSet: TRowEvent read FBeforeEachRowSet write FBeforeEachRowSet;
property AfterEachRowSet: TRowEvent read FAfterEachRowSet write FAfterEachRowSet;
end;
{ TXMLTransformProvider }
{ This component takes data in an arbitrary XML data file and provides it to a
DataSnap client. It also takes updates to the data from the DataSnap client and
modifies the original XML data file.
Properties:
CacheData
Indicates if data is cached by the provider after the GetRecords
method is called by the client. Caching the data will speed
the update process, but will consume additional resources.
XMLDataFile
XML File containing data to be returned to the client. This can be
in any format that can be transformed into a DataSnap compatible format.
Updates are written back to this file.
TransformRead.TransformationFile
Transform file for for converting from XMLDataFile format into a
DataSnap format. This file must be created using the XMLMapper program.
TransformWrite.TransformationFile
Transform file for for converting from a DataSnap format into the
XMLDataFile format. This file must be created using the XMLMapper
program.
}
TXMLTransformProvider = class(TCustomProvider)
private
FDataCache: TClientDataSet;
FResolver: TDataSetProvider;
FTransformRead: TXMLTransform;
FTransformWrite: TXMLTransform;
FCacheData: Boolean;
function GetXMLDataFile: string;
procedure SetXMLDataFile(const Value: string);
protected
function InternalApplyUpdates(const Delta: OleVariant; MaxErrors: Integer;
out ErrorCount: Integer): OleVariant; override;
function InternalGetRecords(Count: Integer; out RecsOut: Integer;
Options: TGetRecordOptions; const CommandText: WideString;
var Params: OleVariant): OleVariant; override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property TransformRead: TXMLTransform read FTransformRead ;
property TransformWrite: TXMLTransform read FTransformWrite ;
property XMLDataFile: string read GetXMLDataFile write SetXMLDataFile;
property CacheData: Boolean read FCacheData write FCacheData default False;
property BeforeApplyUpdates;
property AfterApplyUpdates;
property BeforeGetRecords;
property AfterGetRecords;
property BeforeRowRequest;
property AfterRowRequest;
property OnDataRequest;
end;
{ Transform Client }
{ This component takes data returned from a DataSnap AppServer and transforms
it into an external XML data file (GetXML method). The format of the XML is
determined by the TransformGetData TransformationFile.
It also allows inserting and deleting data on the AppServer by calling the
calling ApplyUpdates method, passing an XML file with the data to
insert/delete, and also a reference to a file containing the
relavant transformation info. }
TXMLTransformClient = class(TComponent)
private
FDataCache: TClientDataSet;
FSetParamsDataCache: TClientDataSet;
FLocalAppServer: TLocalAppServer;
FTransformGetData: TXMLTransform;
FTransformApplyUpdates: TXMLTransform;
FTransformSetParams: TXMLTransform;
function GetProviderName: string;
function GetRemoteServer: TCustomRemoteServer;
procedure SetProviderName(const Value: string);
procedure SetRemoteServer(const Value: TCustomRemoteServer);
protected
procedure SetupAppServer;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function GetDataAsXml(const PublishTransformFile: string): string; virtual;
function ApplyUpdates(const UpdateXML, UpdateTransformFile: string; MaxErrors: Integer): Integer; virtual;
procedure SetParams(const ParamsXml, ParamsTransformFile: string);
published
property RemoteServer: TCustomRemoteServer read GetRemoteServer write SetRemoteServer;
property ProviderName: string read GetProviderName write SetProviderName;
property TransformGetData: TXMLTransform read FTransformGetData ;
property TransformApplyUpdates: TXMLTransform read FTransformApplyUpdates;
property TransformSetParams: TXMLTransform read FTransformSetParams ;
end;
implementation
{ Utility Functions }
procedure TransformError(const Msg: string);
begin
raise TranslateException.Create(Msg);
end;
procedure StringToFile(const S, FileName: string);
begin
with TStringList.Create do
try
Text := S;
SaveToFile(FileName);
finally
Free;
end;
end;
function GetXMLData(DataSet: TClientDataSet): string;
var
Stream: TStringStream;
begin
Stream := TStringStream.Create('');
try
DataSet.SaveToStream(Stream, dfXML);
Result := Stream.DataString;
finally
Stream.Free;
end;
end;
function CreateNestedTransform(Owner: TComponent; const Name: string): TXMLTransform;
begin
Result := TXMLTransform.Create(Owner);
Result.SetSubComponent(True);
Result.Name := Name;
end;
{ TXMLTransform }
procedure TXMLTransform.Translate(const Id: string; const SrcNode: IDOMNode;
var SrcValue: string; const DestNode: IDOMNode);
begin
if Assigned(FOnTranslate) then
FOnTranslate(Self, Id, SrcNode, SrcValue, DestNode);
end;
function TXMLTransform.GetData: string;
var
FSrcDom: IDOMDocument;
FTransDom: IDOMDocument;
begin
if FSourceXMLFile = '' then
begin
if FSourceXml <> '' then
FSrcDom := LoadDocFromString(FSourceXml)
else if FSourceXmlDocument = nil then
TransformError(SMissingSourceFile)
else
FSrcDom := FSourceXmlDocument;
end
else
FSrcDom := LoadDocFromFile(FSourceXMLFile);
if FTransformationFile = '' then
begin
if FTransformationDocument = nil then
TransformError(SMissingTransform)
else
FTransDom := FTransformationDocument;
end
else
FTransDom := LoadDocFromFile(FTransformationFile);
Result := DoTransform(FSrcDom, FTransDom, FEmptyDestinationDocument);
end;
function TXMLTransform.GetResultString: string;
begin
if (FResultString = '') and (FResultDocument <> nil) then
FResultString := (FResultDocument as IDOMPersist).xml;
Result := FResultString;
end;
function TXMLTransform.TransformXML (const SourceXML: string;
const ATransformationFile: string = ''): string;
var
SrcDom: IDOMDocument;
TransDom: IDOMDocument;
begin
Result := '';
TransDom := nil;
SrcDom := nil;
if SourceXml <> '' then
SrcDom := LoadDocFromString(SourceXML);
if ATransformationFile <> '' then
TransDom := LoadDocFromFile(ATransformationFile)
else
if FTransformationFile <> '' then
TransDom := LoadDocFromFile(FTransformationFile)
else
TransformError(SMissingTransform);
if (TransDom <> nil) and (SrcDom <> nil) then
Result := DoTransForm(SrcDom, TransDom, FEmptyDestinationDocument);
end;
function TXMLTransform.DoTransform(const XMLSrc, XMLExtract, XMLOut: IDOMDocument): string;
var
TransRoot: IDOMNode;
SrcRoot, DestRoot, DestRootClone, Node, TransformNode: IDOMNode;
I: Integer;
cdata_skeleton: string;
Skeleton: IDOMDocument;
Direction: string;
MajorVersion, MinorVersion: string;
begin
FResultDocument := nil;
FResultString := '';
FEncoding := GetEncoding(XMLSrc);
TransRoot := XMLExtract.documentElement;
SrcRoot := XMLSrc.documentElement;
if XMLOut <> nil then
DestRootClone := XMLOut.documentElement
else
begin
FVersion := GetAttribute(TransRoot, mx_Version);
if FVersion <> '' then
begin
MajorVersion := Head(FVersion, '.', MinorVersion);
if StrToInt(MajorVersion) < 1 then
TransformError(SOldVersion);
end;
TransformNode := SelectNode(TransRoot, mx_Root + '\'+ mx_Transform);
FEncodingTrans := GetAttribute(TransformNode, mx_DataEncoding);
Direction := GetAttribute(TransformNode, mx_Direction);
FDirectionToCds := (Direction = mx_ToCds);
DestRoot := SelectNode(TransRoot,mx_Root+'\'+mx_Skeleton);
if DestRoot.ChildNodes.item[0].nodeType = ELEMENT_NODE then
DestRootClone := DestRoot.CloneNode(True)
else if DestRoot.ChildNodes.item[0].nodeType = CDATA_SECTION_NODE then
begin
cdata_skeleton := DestRoot.ChildNodes.item[0].nodeValue;
Skeleton := LoadDocFromString(cdata_skeleton);
DestRootClone := Skeleton.documentElement;
end;
end;
Node := SelectNode(TransRoot, mx_Root + '\' + mx_Transform);
if Node <> nil then
for I := 0 to Node.childNodes.length-1 do
Transform(Node.childNodes.item[I], SrcRoot, DestRootClone,
0, nil, nil, nil, nil, nil, nil, nil, nil);
if XmlOut <> nil then
begin
FResultDocument := XMLOut;
Result := (DestRootClone as IDOMNodeEx).xml;
end
else
begin
if Skeleton = nil then
Result := (DestRootClone.childNodes.item[0] as IDOMPersist).xml
else
begin
FResultDocument := Skeleton;
Result := (Skeleton as IDOMPersist).xml;
end;
end;
FResultString := Result;
end;
procedure TXMLTransform.Transform(TransNode, SrcNode, DestNode: IDOMNode;
Count: Integer; InFromList, InDestList, InIdStrList, InValueList,
InOptionalList, InDateFormatList, InDateFormatTypeList,
InMapValuesList: TStringList);
var
I, J: Integer;
From, Dest: string;
Value, AttrName: string;
IdStr, RepeatName: string;
Optional, Map_Values: string;
DefaultValue, DateFormat, DateFormatType: string;
More, BeforeEachRowSet: Boolean;
RepeatDestNode, AttrNode, TmpNode: IDOMNode;
FromList, DestList, IdStrList, ValueList, OptionalList: TStringList;
DateFormatList, DateFormatTypeList, MapValuesList: TStringList;
begin
if TransNode.NodeName = mx_TranslateEach then
begin
AttrNode := TransNode.attributes.getNamedItem(mx_FROM);
if AttrNode <> nil then From := AttrNode.nodeValue else From := '';
AttrNode := TransNode.attributes.getNamedItem(mx_DEST);
if AttrNode <> nil then Dest := AttrNode.nodeValue else Dest := '';
AttrNode := TransNode.attributes.getNamedItem(mx_ID);
if AttrNode <> nil then IdStr := AttrNode.nodeValue else IdStr := '';
SrcNode := SelectNode(SrcNode, From);
if SrcNode <> nil then
begin
RepeatName := SrcNode.nodeName;
DestNode := SelectCreateNode(DestNode, Dest, AttrName);
end
else
begin
RepeatName := '';
DestNode := SelectCreateNode(DestNode, Dest, AttrName);
if (DestNode <> nil) and (DestNode.parentNode <> nil) then
begin
TmpNode := DestNode;
DestNode := DestNode.parentNode;
DestNode.removeChild(TmpNode);
end;
end;
if (SrcNode <> nil) and (DestNode <> nil) then
begin
More := True;
BeforeEachRowSet := True;
RepeatDestNode := DestNode.cloneNode(True);
end
else
begin
More := False;
BeforeEachRowSet := False;
RepeatDestNode := nil;
end;
if More and Assigned(FBeforeEachRowSet) then
FBeforeEachRowSet(Self, IdStr, SrcNode, DestNode);
FromList := TStringList.Create;
DestList := TStringList.Create;
IdStrList := TStringList.Create;
ValueList := TStringList.Create;
OptionalList := TStringList.Create;
DateFormatList := TStringList.Create;
DateFormatTypeList := TStringList.Create;
MapValuesList := TStringList.Create;
try
while More do
begin
if Assigned(FBeforeEachRow) then
FBeforeEachRow(Self, IdStr, SrcNode, DestNode);
for I := 0 to TransNode.childNodes.length-1 do
TransForm(TransNode.childNodes.item[i], SrcNode, DestNode,
I, FromList, DestList, IdStrList, ValueList, OptionalList,
DateFormatList, DateFormatTypeList, MapValuesList);
if Assigned(FAfterEachRow) then
FAfterEachRow(Self, IdStr, SrcNode, DestNode);
while More do
begin
SrcNode := SrcNode.nextSibling;
if SrcNode = nil then
More := False
else
begin
if SrcNode.nodeName = RepeatName then
begin //found next\
DestNode := SelectCreateSibling(DestNode, RepeatDestNode);
if DestNode = nil then More := False;
Break;
end;
end;
end;
end; //while More
if BeforeEachRowSet and Assigned(FAfterEachRowSet) then
FAfterEachRowSet(Self, IdStr, SrcNode, DestNode);
finally
FromList.Free;
DestList.Free;
IdStrList.Free;
ValueList.Free ;
OptionalList.Free;
DateFormatList.Free;
DateFormatTypeList.Free;
MapValuesList.Free;
end;
end // TransNode.NodeName = mx_TranslateEach
else if TransNode.NodeName = mx_Translate then //Field-translation
begin
if (InFromList = nil) or (Count >= InFromList.Count) then
begin
From := ''; Dest := ''; IdStr := ''; Value := ''; Optional := '';
DateFormat := ''; DateFormatType := ''; Map_Values := '';
for J := 0 to TransNode.attributes.length-1 do
begin
TmpNode := TransNode.attributes.item[J];
if TmpNode.NodeName = mx_FROM then
From := TmpNode.nodeValue
else if TmpNode.NodeName = mx_DEST then
Dest := TmpNode.nodeValue
else if TmpNode.NodeName = mx_VALUE then
Value := TmpNode.nodeValue
else if TmpNode.NodeName = mx_OPTIONAL then
Optional := TmpNode.nodeValue
else if TmpNode.NodeName = mx_ID then
Idstr := TmpNode.nodeValue
else if TmpNode.NodeName = mx_DEFAULT then
DefaultValue := TmpNode.nodeValue
else if (TmpNode.NodeName = mx_DATETIMEFORMAT) or
(TmpNode.NodeName = mx_DATEFORMAT) or
(TmpNode.NodeName = mx_TIMEFORMAT) then
begin
DateFormat := TmpNode.NodeValue;
DateFormatType := TmpNode.NodeName;
end
else if TmpNode.NodeName = mx_MAPVALUES then
Map_Values := TmpNode.NodeValue;
end; // for
if InFromList <> nil then
begin
InFromList.Add(From);
InDestList.Add(Dest);
InIdStrList.Add(IdStr);
InValueList.Add(Value);
InOptionalList.Add(Optional);
InDateFormatList.Add(DateFormat);
InDateFormatTypeList.Add(DateFormatType);
InMapValuesList.Add(Map_Values);
end;
end // if (InFromList = nil) ...
else
begin
From := InFromList[Count];
Dest := InDestList[Count];
IdStr := InIdStrList[Count];
Value := InValueList[Count];
Optional := InOptionalList[Count];
DateFormat := InDateFormatList[Count];
DateFormatType := InDateFormatTypeList[Count];
Map_Values := InMapValuesList[Count];
end;
SrcNode := SelectNode(SrcNode, From);
if SrcNode <> nil then
begin
if Value = '' then
begin
if SrcNode.nodeType = ELEMENT_NODE then
Value := (SrcNode as IDOMNodeEx).Text
else
Value := SrcNode.nodeValue;
end;
if (IdStr <> '') and Assigned(FOnTranslate) then
FOnTranslate(Self, IdStr, SrcNode, Value, DestNode);
end;
if Value = '' then
if DefaultValue <> '' then
Value := DefaultValue;
if Value <> '' then
begin
if Map_Values <> '' then
Value := MapValues(Map_Values, Value);
if Value = '' then
if DefaultValue <> '' then
Value := DefaultValue;
if DateFormatType <> '' then
Value := MapDateTime(DateFormatType, DateFormat, Value, FDirectionToCds);
if (Optional = '') or (Value <> '') then
PutValue(DestNode, Dest, Value);
end
else if Optional = '' then // = '1'
PutValue(DestNode, Dest, '');
if (Optional <> '') and (Value = '') and
(Dest <> '') and (Dest[1] <> '@') then
begin
TmpNode := SelectNode(DestNode, Dest);
if TmpNode <> nil then
TmpNode.parentNode.removeChild(TmpNode);
end;
end; // else if TransNode.NodeName = mx_Translate
end;
{ TXMLTransformProvider }
constructor TXMLTransformProvider.Create(AOwner: TComponent);
begin
FTransformRead := CreateNestedTransform(Self, 'DataTransformRead'); // Do not localize
FTransformWrite := CreateNestedTransform(Self, 'DataTransformWrite'); // Do not localize
FDataCache := TClientDataSet.Create(Self);
inherited;
end;
destructor TXMLTransformProvider.Destroy;
begin
inherited;
end;
function TXMLTransformProvider.InternalGetRecords(Count: Integer;
out RecsOut: Integer; Options: TGetRecordOptions;
const CommandText: WideString; var Params: OleVariant): OleVariant;
begin
Result := StringtoVariantArray(FTransformRead.Data);
if CacheData then
FDataCache.Data := Result;
end;
function TXMLTransformProvider.InternalApplyUpdates(const Delta: OleVariant;
MaxErrors: Integer; out ErrorCount: Integer): OleVariant;
var
S: string;
begin
if not Assigned(FResolver) then
begin
FResolver := TDataSetProvider.Create(Self);
FResolver.DataSet := FDataCache;
FResolver.ResolveToDataSet := True;
FResolver.UpdateMode := upWhereAll; //upWhereKeyOnly;
end;
if not FCacheData or not FDataCache.Active then
FDataCache.Data := StringToVariantArray(FTransformRead.Data);
Result := FResolver.ApplyUpdates(Delta, MaxErrors, ErrorCount);
FDataCache.MergeChangeLog;
S := FTransformWrite.TransformXML(GetXMLData(FDataCache));
if FTransformWrite.ResultDocument <> nil then
begin
SetEncoding(FTransformWrite.ResultDocument, FTRansformRead.FEncoding, False);
if FTransformRead.SourceXmlFile <> '' then
(FTransformWrite.ResultDocument as IDOMPersist).save(FTransformRead.SourceXmlFile);
end
else if S <> '' then
StringToFile(S, FTransformRead.SourceXmlFile);
if not FCacheData then
FDataCache.Data := Null;
end;
function TXMLTransformProvider.GetXMLDataFile: string;
begin
Result := FTransformRead.SourceXMLFile
end;
procedure TXMLTransformProvider.SetXMLDataFile(const Value: string);
begin
FTransformRead.SourceXMLFile := Value;
end;
{ TXMLTransformClient }
constructor TXMLTransformClient.Create(AOwner: TComponent);
begin
FTransformGetData := CreateNestedTransform(Self, 'TransformGetData'); // Do not localize
FTransformApplyUpdates := CreateNestedTransform(Self, 'TransformApplyUpdates'); // Do not localize
FTransformSetParams := CreateNestedTransform(Self, 'TransformSetParams'); // Do not localize
FDataCache := TClientDataSet.Create(Self);
inherited;
end;
destructor TXMLTransformClient.Destroy;
begin
inherited;
FLocalAppServer.Free;
end;
procedure TXMLTransformClient.SetupAppServer;
var
ProvComp: TComponent;
begin
if not Assigned(FDataCache.RemoteServer) or not FDataCache.HasAppServer then
begin
ProvComp := Owner.FindComponent(ProviderName);
if Assigned(ProvComp) and (ProvComp is TCustomProvider) then
FDataCache.AppServer := TLocalAppServer.Create(TCustomProvider(ProvComp));
end;
end;
function TXMLTransformClient.GetDataAsXml(const PublishTransformFile: string): string;
var
RecsOut: Integer;
Params, OwnerData, VarPacket: OleVariant;
TransFileName, XmlData: string;
Options: TGetRecordOptions;
begin
SetupAppServer;
if FDataCache.Params.Count > 0 then
Params := PackageParams(FDataCache.Params);
Options := [grMetaData, grXML];
VarPacket := FDataCache.AppServer.AS_GetRecords(GetProviderName, -1,
RecsOut, Byte(Options), '', Params, OwnerData);
XmlData := VariantArrayToString(VarPacket);
if PublishTransformFile <> '' then
TransFileName := PublishTransformFile else
TransFileName := FTransformGetData.FTransformationFile;
Result := FTransformGetData.TransformXML(XMLData, TransFileName);
if (Result <> '') and (FTransformGetData.ResultDocument <> nil) and
(FTransformGetData.FEncodingTrans <> '') then
SetEncoding(FTransformGetData.ResultDocument,
FTransformGetData.FEncodingTrans, True);
end;
function TXMLTransformClient.ApplyUpdates(const UpdateXML, UpdateTransformFile: string;
MaxErrors: Integer): Integer;
var
Delta: Variant;
OwnerData: OleVariant;
TransFileName: string;
begin
SetupAppServer;
if UpdateTransformFile <> '' then
TransFileName := UpdateTransformFile else
TransFileName := FTransformApplyUpdates.TransformationFile;
Delta := FTransformApplyUpdates.TransformXML(UpdateXML, TransFileName);
try
FDataCache.AppServer.AS_ApplyUpdates(GetProviderName,
StringToVariantArray(Delta), MaxErrors, Result, OwnerData);
except
end;
end;
function TXMLTransformClient.GetProviderName: string;
begin
Result := FDataCache.ProviderName;
end;
procedure TXMLTransformClient.SetProviderName(const Value: string);
begin
FDataCache.ProviderName := Value;
end;
function TXMLTransformClient.GetRemoteServer: TCustomRemoteServer;
begin
Result := FDataCache.RemoteServer;
end;
procedure TXMLTransformClient.SetRemoteServer(const Value: TCustomRemoteServer);
begin
FDataCache.RemoteServer := Value;
end;
procedure TXMLTransformClient.SetParams(const ParamsXml, ParamsTransformFile: string);
var
I: Integer;
Field: TField;
Param: TParam;
S: string;
begin
if FSetParamsdataCache = nil then
FSetParamsdataCache := TClientDataSet.Create(Self);
with FSetParamsdataCache do
begin
Active := False;
S := FTransformSetParams.TransformXML(ParamsXML, ParamsTransformFile);
Data := StringToVariantArray(S);
if (Active) and (Fields.Count > 0) then
begin
First;
if not EOF then
for I := 0 to Fields.Count -1 do
begin
Field := Fields[I];
Param := FDataCache.Params.FindParam(Field.FieldName);
if Param = nil then
Param := FDataCache.Params.CreateParam(Field.DataType, Field.FieldName, ptInput);
Param.Value := Field.Value;
end;
end;
end;
end;
end.
|
unit Memo_TLB;
// ************************************************************************ //
// 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. //
// ************************************************************************ //
// PASTLWTR : $Revision: 1.11.1.62 $
// File generated on 6/12/98 11:21:03 AM from Type Library described below.
// ************************************************************************ //
// Type Lib: C:\Delphi4\Demos\Activex\Oleauto\Autoserv\memoedit.tlb
// IID\LCID: {55E49D30-9FFE-11D0-8095-0020AF74DE39}\0
// Helpfile:
// HelpString: Memo Editor Application
// Version: 1.0
// ************************************************************************ //
interface
uses Windows, ActiveX, Classes, Graphics, OleCtrls, StdVCL;
// *********************************************************************//
// 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
LIBID_Memo: TGUID = '{55E49D30-9FFE-11D0-8095-0020AF74DE39}';
IID_IMemoApp: TGUID = '{55E49D31-9FFE-11D0-8095-0020AF74DE39}';
CLASS_MemoApp: TGUID = '{F7FF4880-200D-11CF-BD2F-0020AF0E5B81}';
IID_IMemoDoc: TGUID = '{55E49D34-9FFE-11D0-8095-0020AF74DE39}';
CLASS_MemoDoc: TGUID = '{55E49D35-9FFE-11D0-8095-0020AF74DE39}';
type
// *********************************************************************//
// Forward declaration of interfaces defined in Type Library //
// *********************************************************************//
IMemoApp = interface;
IMemoAppDisp = dispinterface;
IMemoDoc = interface;
IMemoDocDisp = dispinterface;
// *********************************************************************//
// Declaration of CoClasses defined in Type Library //
// (NOTE: Here we map each CoClass to its Default Interface) //
// *********************************************************************//
MemoApp = IMemoApp;
MemoDoc = IMemoDoc;
// *********************************************************************//
// Interface: IMemoApp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {55E49D31-9FFE-11D0-8095-0020AF74DE39}
// *********************************************************************//
IMemoApp = interface(IDispatch)
['{55E49D31-9FFE-11D0-8095-0020AF74DE39}']
function NewMemo: OleVariant; safecall;
function OpenMemo(const MemoFileName: WideString): OleVariant; safecall;
procedure TileWindows; safecall;
procedure CascadeWindows; safecall;
function Get_MemoCount: Integer; safecall;
function Get_Memos(MemoIndex: Integer): OleVariant; safecall;
property MemoCount: Integer read Get_MemoCount;
property Memos[MemoIndex: Integer]: OleVariant read Get_Memos;
end;
// *********************************************************************//
// DispIntf: IMemoAppDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {55E49D31-9FFE-11D0-8095-0020AF74DE39}
// *********************************************************************//
IMemoAppDisp = dispinterface
['{55E49D31-9FFE-11D0-8095-0020AF74DE39}']
function NewMemo: OleVariant; dispid 1;
function OpenMemo(const MemoFileName: WideString): OleVariant; dispid 2;
procedure TileWindows; dispid 3;
procedure CascadeWindows; dispid 4;
property MemoCount: Integer readonly dispid 5;
property Memos[MemoIndex: Integer]: OleVariant readonly dispid 6;
end;
// *********************************************************************//
// Interface: IMemoDoc
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {55E49D34-9FFE-11D0-8095-0020AF74DE39}
// *********************************************************************//
IMemoDoc = interface(IDispatch)
['{55E49D34-9FFE-11D0-8095-0020AF74DE39}']
procedure Clear; safecall;
procedure Insert(const Text: WideString); safecall;
procedure Save; safecall;
procedure Close; safecall;
function Get_FileName: WideString; safecall;
procedure Set_FileName(const Value: WideString); safecall;
function Get_Modified: WordBool; safecall;
property FileName: WideString read Get_FileName write Set_FileName;
property Modified: WordBool read Get_Modified;
end;
// *********************************************************************//
// DispIntf: IMemoDocDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {55E49D34-9FFE-11D0-8095-0020AF74DE39}
// *********************************************************************//
IMemoDocDisp = dispinterface
['{55E49D34-9FFE-11D0-8095-0020AF74DE39}']
procedure Clear; dispid 1;
procedure Insert(const Text: WideString); dispid 2;
procedure Save; dispid 3;
procedure Close; dispid 4;
property FileName: WideString dispid 5;
property Modified: WordBool readonly dispid 6;
end;
CoMemoApp = class
class function Create: IMemoApp;
class function CreateRemote(const MachineName: string): IMemoApp;
end;
CoMemoDoc = class
class function Create: IMemoDoc;
class function CreateRemote(const MachineName: string): IMemoDoc;
end;
implementation
uses ComObj;
class function CoMemoApp.Create: IMemoApp;
begin
Result := CreateComObject(CLASS_MemoApp) as IMemoApp;
end;
class function CoMemoApp.CreateRemote(const MachineName: string): IMemoApp;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MemoApp) as IMemoApp;
end;
class function CoMemoDoc.Create: IMemoDoc;
begin
Result := CreateComObject(CLASS_MemoDoc) as IMemoDoc;
end;
class function CoMemoDoc.CreateRemote(const MachineName: string): IMemoDoc;
begin
Result := CreateRemoteComObject(MachineName, CLASS_MemoDoc) as IMemoDoc;
end;
end.
|
unit TConnectionManager;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type TOconnectionManager = class
const maxConnections = 1;
private
connections: Integer;
public
function newConnection: boolean;
procedure disconnectConnection;
end;
var ConnectionManager: TOconnectionManager;
implementation
procedure TOconnectionManager.disconnectConnection;
begin
self.connections:=self.connections - 1;
writeln('Connection disconnected. New connections count: '+inttostr(self.connections) +'. ');
end;
function TOconnectionManager.newConnection: boolean;
begin
Result := True;
self.connections:=self.connections+1;
writeln('Connection count: ' + inttostr(self.connections));
if (self.connections > self.maxConnections) then begin
Result := False;
writeln('Max connections reached! Not accepting new ones.');
end;
end;
begin
ConnectionManager := TOconnectionManager.Create;
end.
|
unit HGM.GraphQL.Query;
interface
uses
HGM.GraphQL.Types, HGM.GraphQL.Fields, HGM.GraphQL.Method;
type
TGraphQuery = class
private
FMethods: TGraphMethods;
FName: string;
FType: string;
procedure SetMethods(const Value: TGraphMethods);
public
procedure AddMethod(const Name: string; Args: TGraphArgList; Fields: TGraphFields);
property Methods: TGraphMethods read FMethods write SetMethods;
property Name: string read FName;
constructor Create(const AType, AName: string); reintroduce;
destructor Destroy; override;
function ToString: string; reintroduce;
function Query: TGraphQuery;
end;
implementation
{ TGraphQuery }
procedure TGraphQuery.AddMethod(const Name: string; Args: TGraphArgList; Fields: TGraphFields);
var
Item: TGraphMethod;
begin
Item := TGraphMethod.Create;
Item.Name := Name;
Item.Args := Args;
Item.Fields := Fields;
Methods.Add(Item);
end;
constructor TGraphQuery.Create(const AType, AName: string);
begin
FMethods := TGraphMethods.Create;
FType := AType;
FName := AName;
end;
destructor TGraphQuery.Destroy;
begin
FMethods.Free;
FMethods := nil;
inherited;
end;
function TGraphQuery.Query: TGraphQuery;
begin
Result := Self;
end;
procedure TGraphQuery.SetMethods(const Value: TGraphMethods);
begin
FMethods := Value;
end;
function TGraphQuery.ToString: string;
begin
Result := FType + ' ' + FName + ' ' + FMethods.ToString;
end;
end.
|
unit EmerAPIServerTasksUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, EmerAPIMain, emerapitypes, EmerAPIBlockchainUnit, fpjson;
type
tEmerAPIServerTaskValid=(eptvUnknown,eptvValid,eptvInvalid,eptvPart); //part for a group means some tasks are valid
tEmerAPIServerTaskList=class;
tBaseEmerAPIServerTask=class(tObject)
protected
fEmerAPI:tEmerAPI;
fExecuted:boolean; //sent to BC. Will be removed by parent
fExecutionDatetime:tDatetime;
fSuccessful:boolean; //set together with fExecuted
fOwner:tEmerAPIServerTaskList;
fOnDone:tNotifyEvent; //called if the task is done (sent to BC, for example, even not successeful)
fLastError:string;
fTaskValid:boolean; //is the task CAN be applied?
fTaskValidAt:tDateTime; //0 if not checked; etherwise time
function execute(onDone:tNotifyEvent=nil):boolean; virtual;
function getExecuted:boolean; virtual; abstract; //for task: it was send. for group: all the tasks were sent
public
fUpdated:boolean; //set true on data loaded. One time.
userObj1:tObject;
Comment:string; //comment: String
id:ansistring; //id: ID
NVSName:ansistring; //name: String
NVSValue:ansistring; //value
NVSDays:qword;
amount:qword; //amount: Float
ownerAddress:ansistring; //address
time:dword;
LockTime:dword;
// dpo: String
// time: Int
TaskType: String; //type
onTaskUpdated:tNotifyEvent;
//
function getDescription:string; virtual; abstract;
function fIsKnownName:boolean; virtual; abstract; //рекурсивно вызывает всех детей, если есть. Возвращает типировано ли имя
function getTitle:string; virtual; abstract;
function getNameType:ansistring; virtual; abstract;//Возвращает имя с сигнатурой, например 'dns' или 'af:brand'
procedure validateTask(); virtual; abstract;
//stat
function getCost:qWord; virtual; abstract;
function getValid:tEmerAPIServerTaskValid; virtual; abstract;
// group: ссылка на группу, при запросе можно получать поля, например id
property Executed:boolean read getExecuted;
property Successful:boolean read fSuccessful;
property LastError:string read fLastError;
constructor create(mOwner:tEmerAPIServerTaskList);
end;
tEmerAPIServerTask=class(tBaseEmerAPIServerTask)
private
procedure SendingError(Sender: TObject);
procedure Sent(Sender: TObject);
//procedure onAsyncQueryDoneHandler(sender:TEmerAPIBlockchainThread;result:tJsonData);
procedure onAsyncQueryDoneHandler(sender:TEmerAPIBlockchainThread;result:tJsonData);
public
function getEmerAPI:tEmerAPI;
function getValid:tEmerAPIServerTaskValid; override;
procedure validateTask(); override;
procedure updateDataByParent(); //updates fields by parent task
function execute(onDone:tNotifyEvent=nil):boolean; override;
function getExecuted:boolean; override;
function getCost:qWord; override;
end;
tEmerAPIServerTaskGroup=class(tBaseEmerAPIServerTask)
private
function getCount:integer;
function getItem(Index: integer):tBaseEmerAPIServerTask;
procedure taskExecuted(sender: tObject);
protected
Tasks:tEmerAPIServerTaskList;
public
property Count:integer read getCount;
property Items[Index: integer]:tBaseEmerAPIServerTask read getItem; default;
property getTasks:tEmerAPIServerTaskList read Tasks;
function execute(onDone:tNotifyEvent=nil):boolean; override;
function getExecuted:boolean; override;
constructor create(mOwner:tEmerAPIServerTaskList);
destructor destroy; override;
function getValid:tEmerAPIServerTaskValid; override;
procedure validateTask(); override;
//stat
function getCost:qWord; override;
function getUniOwnerCount:integer;
function getOwnerByCount(address:ansistring='undefined'):integer;
end;
//update
//error
//newtask
//taskremoved
//taskUpdated : single task has new information
tEmerAPIServerTaskList=class(tEmerApiNotified)
private
fOwnerTask:tBaseEmerAPIServerTask;
fEmerAPI:tEmerAPI;
fLastUpdateTime:tDatetime;
fItems:tList;
fValidateAfterCreate:boolean;
function getItem(Index: integer):tBaseEmerAPIServerTask;
function getCount:integer;
procedure clearList;
procedure onAsyncQueryDoneHandler(sender:TEmerAPIBlockchainThread;result:tJsonData);
procedure myUpdate(sender:tObject);
procedure myError(sender:tObject);
procedure myNewTask(sender:tObject);
procedure myTaskRemoved(sender:tObject);
procedure mytaskUpdated(sender:tObject);
public
property Count:integer read getCount;
property Items[Index: integer]:tBaseEmerAPIServerTask read getItem; default;
property ValidateAfterCreate:boolean read fValidateAfterCreate write fValidateAfterCreate;
procedure delete(Index: integer);
procedure validateTask(Index:integer=-1); //-1 for all
procedure updateFromServer(groupID:ansistring='');
constructor create(mEmerAPI:tEmerAPI; setValidateAfterCreate:boolean=true);
destructor destroy; override;
end;
implementation
uses HelperUnit, EmerAPITransactionUnit, MainUnit{for getprivkey}, crypto, EmerTX, LazUTF8SysUtils;
{tBaseEmerAPIServerTask}
constructor tBaseEmerAPIServerTask.create(mOwner:tEmerAPIServerTaskList);
begin
inherited create;
fOwner:=mOwner;
fLastError:='';
end;
function tBaseEmerAPIServerTask.execute(onDone:tNotifyEvent=nil):boolean;
begin
fonDone:=onDone;
fLastError:='';
result:=true;
end;
{tEmerAPIServerTask}
function tEmerAPIServerTask.getCost:qWord;
begin
result:=0;
end;
function tEmerAPIServerTask.getExecuted:boolean;
begin
result:=fExecuted;
end;
function tEmerAPIServerTask.getValid:tEmerAPIServerTaskValid;
begin
//eptvUnknown,eptvValid,eptvInvalid,eptvPart
if fTaskValidAt>0 then
if fTaskValid then
result:=eptvValid
else
result:=eptvInvalid
else begin
result:=eptvUnknown;
end;
end;
procedure tEmerAPIServerTask.onAsyncQueryDoneHandler(sender:TEmerAPIBlockchainThread;result:tJsonData);
var e:tJsonData;
{s:string;
val,x:double;
nc,i,n:integer;
st:ansistring;
vR,vY,vS:double;
nameScript:tNameScript;
amount:integer;
}
begin
if result=nil then //requery? failed?
exit; //ok. now just do nothing
if sender.id=('checkname:'+trim(NVSName)) then begin
e:=result.FindPath('result');
if e<>nil then
if e.IsNull then begin
//name is free
fTaskValidAt:=now;
fTaskValid:=true;
if assigned(fOwner) then fOwner.callNotify('taskUpdated');
end else begin
fTaskValidAt:=now;
fTaskValid:=false;
if assigned(fOwner) then fOwner.callNotify('taskUpdated');
end
else exit; //can't check //lNameExits.Caption:='Error: can''t find result in: '+result.AsJSON;
end;
end;
procedure tEmerAPIServerTask.validateTask();
var nt:ansistring;
begin
//check if the task is valid.
//set fTaskValidAt and fTaskValid
{ if (NVSName='')
or (NVSValue='')
or (length(NVSName)>512)
or (length(NVSValue)>20480)
or (NVSDays<1)
or (ownerAddress='')
or ((time>1000000) and ((time<()) or (time>())))
or ((LockTime>1000000) and ((LockTime<()) or (LockTime>())))
}
if (ownerAddress='')
or ((time>1000000) and ((time<(winTimeToUnixTime(nowUTC()))) or (time>(winTimeToUnixTime(nowUTC())+3000))))
or ((LockTime>1000000) and ({(LockTime<(winTimeToUnixTime(nowUTC())-3000)) or} (LockTime>(winTimeToUnixTime(nowUTC())+3000*100))))
then begin
fTaskValidAt:=now;
fTaskValid:=false;
if assigned(fOwner) then fOwner.callNotify('taskUpdated');
exit;
end;
if TaskType='NEW_NAME' then begin
//create name. We must check if the name is not exists
updateDataByParent;
if (NVSName='')
or (NVSValue='')
or (length(NVSName)>512)
or (length(NVSValue)>20480)
or (NVSDays<1)
then begin
fTaskValidAt:=now;
fTaskValid:=false;
if assigned(fOwner) then fOwner.callNotify('taskUpdated');
exit;
end;
//check
getEmerAPI.EmerAPIConnetor.sendWalletQueryAsync('name_show',getJSON('{name:"'+NVSName+'"}'),@onAsyncQueryDoneHandler,'checkname:'+NVSName);
end else begin//unknown task
fTaskValidAt:=0;
fTaskValid:=false;
end;
end;
procedure tEmerAPIServerTask.SendingError(Sender: TObject);
begin
//if Sender is tEmerTransaction
// then ShowMessageSafe('Sending error: '+tEmerTransaction(sender).lastError)
// else ShowMessageSafe('Sending error');
fSuccessful:=false;
fExecuted:=true;
if Sender is tEmerTransaction
then fLastError:=tEmerTransaction(sender).lastError
else fLastError:='unknown sending error';
if assigned(fonDone) then fonDone(self);
end;
procedure tEmerAPIServerTask.Sent(Sender: TObject);
begin
//ShowMessageSafe('Successfully sent');
fSuccessful:=true;
fExecuted:=true;
fLastError:='';
if assigned(fonDone) then fonDone(self);
end;
procedure tEmerAPIServerTask.updateDataByParent();
begin
{
nName:=NVSName;
nValue:=NVSValue;
nDays:=NVSDays;
nAmount:=amount;
nOwnerAddress:=ownerAddress;
nTime:=time;
nLockTime:=LockTime;
}
if (fOwner<>nil) and (fOwner.fOwnerTask<>nil) then begin
if fOwner.fOwnerTask.NVSName<>'' then NVSName:=fOwner.fOwnerTask.NVSName;
if fOwner.fOwnerTask.NVSValue<>'' then NVSValue:=fOwner.fOwnerTask.NVSValue;
if fOwner.fOwnerTask.NVSDays>0 then NVSDays:=fOwner.fOwnerTask.NVSDays;
if fOwner.fOwnerTask.amount>0 then amount:=fOwner.fOwnerTask.amount;
if fOwner.fOwnerTask.time<>-1 then time:=fOwner.fOwnerTask.time;
if fOwner.fOwnerTask.LockTime<>-1 then LockTime:=fOwner.fOwnerTask.LockTime;
end;
end;
function tEmerAPIServerTask.getEmerAPI:tEmerAPI;
begin
result:=fEmerAPI;
if result=nil then
if (fOwner<>nil) then result:=fOwner.fEmerAPI;
if result=nil then
if (fOwner<>nil) and (fOwner.fOwnerTask<>nil) then
result:=fOwner.fOwnerTask.fEmerAPI;
if result=nil then raise exception.Create('tEmerAPIServerTask.execute: EmerAPI is nil');
end;
function tEmerAPIServerTask.execute(onDone:tNotifyEvent=nil):boolean;
var
//nName,nValue:ansistring;
//nDays,nAmount:qword;
//nOwnerAddress:ansistring;
//nTime:dWord;
//nLockTime:dWord;
tx:tEmerTransaction;
EmerAPI:tEmerAPI;
begin
inherited;//fonDone:=onDone;
result:=false;
EmerAPI:=getEmerAPI;
{
data:
NVSName:ansistring; - only for NAME_NEW, NAME_UPDATE, NAME_DELETE
NVSValue:ansistring; - only for NAME_NEW, NAME_UPDATE
NVSDays:qword; - only for NAME_NEW, NAME_UPDATE
amount:qword; - only for payments.
ownerAddress:ansistring; //address
time:dword;
LockTime:dword;
}
updateDataByParent;
if TaskType='NEW_NAME' then begin
if length(NVSName)>512 then exit;
if length(NVSValue)>20480 then exit;
tx:=tEmerTransaction.create(EmerAPI,true);
if not( (time=-1) or (time=0)) then tx.Time:=time;
if not( (LockTime=-1) or (LockTime=0)) then tx.LockTime:= LockTime;
try
tx.addOutput(tx.createNameScript(addressto21(ownerAddress),NVSName,NVSValue,NVSDays,True),EmerAPI.blockChain.MIN_TX_FEE);
//EmerAPI.blockChain.getNameOpFee(seDays.Value,opNum('OP_NAME_NEW'),length(nName)+length(nValue))
if tx.makeComplete then begin
if tx.signAllInputs(MainForm.PrivKey) then begin
tx.sendToBlockchain(EmerAPINotification(@Sent,'sent'));
tx.addNotify(EmerAPINotification(@SendingError,'error'));
end else begin fLastError:=('Can''t sign all transaction inputs using current key: '+tx.LastError); freeandnil(tx); exit; end;//else showMessageSafe('Can''t sign all transaction inputs using current key: '+tx.LastError);
end else begin fLastError:=('Can''t create transaction: '+tx.LastError); freeandnil(tx); exit; end; //showMessageSafe('Can''t create transaction: '+tx.LastError);
except
freeandnil(tx);
exit;
end;
result:=true;
end;
end;
{tEmerAPIServerTaskGroup}
function tEmerAPIServerTaskGroup.getCount:integer;
begin
result:=0;
if Tasks=nil then exit;
result:=Tasks.Count;
end;
function tEmerAPIServerTaskGroup.getItem(Index: integer):tBaseEmerAPIServerTask;
begin
result:=nil;
if Tasks=nil then exit;
result:=Tasks[Index];
end;
procedure tEmerAPIServerTaskGroup.taskExecuted(sender: tObject);
var i:integer;
mySuccessful:boolean;
begin
fSuccessful:=false;
mySuccessful:=true;
for i:=0 to Tasks.Count-1 do begin
if not tBaseEmerAPIServerTask(Tasks[i]).Executed then exit;
mySuccessful:= mySuccessful and tBaseEmerAPIServerTask(Tasks[i]).Successful;
if not tBaseEmerAPIServerTask(Tasks[i]).Successful then
fLastError:= fLastError + tBaseEmerAPIServerTask(Tasks[i]).LastError+'; ';
end;
fSuccessful:=mySuccessful;
if not assigned(fOnDone) then exit;
fOnDone(self);
end;
function tEmerAPIServerTaskGroup.execute(onDone:tNotifyEvent=nil):boolean;
var i:integer;
begin
inherited;
result:=true;
for i:=0 to Tasks.Count-1 do
if tBaseEmerAPIServerTask(Tasks[i]).getValid in [eptvValid,eptvPart] then
if not tBaseEmerAPIServerTask(Tasks[i]).Execute(@taskExecuted)
then result:=false;
end;
procedure tEmerAPIServerTaskGroup.validateTask();
begin
Tasks.validateTask(-1);
end;
function tEmerAPIServerTaskGroup.getValid:tEmerAPIServerTaskValid;
var i:integer;
ceptvValid,ceptvInvalid:integer;
begin
result:=eptvUnknown;
//eptvUnknown,eptvValid,eptvInvalid,eptvPart
ceptvValid:=0;
ceptvInvalid:=0;
for i:=0 to Tasks.Count-1 do
case tBaseEmerAPIServerTask(Tasks[i]).getValid of
eptvUnknown:exit;
eptvValid:inc(ceptvValid);
eptvInvalid:inc(ceptvInvalid);
end;
if ceptvValid*ceptvInvalid>0 then result:=eptvPart
else if ceptvValid>0 then result:=eptvValid
else if ceptvInvalid>0 then result:=eptvInvalid;
//else just unknown or erroneous state
end;
function tEmerAPIServerTaskGroup.getExecuted:boolean;
var i:integer;
begin
result:=false;
for i:=0 to Tasks.Count-1 do
if not tBaseEmerAPIServerTask(Tasks[i]).Executed
then exit;
result:=true;
end;
function tEmerAPIServerTaskGroup.getCost:qWord;
var i:integer;
begin
result:=0;
for i:=0 to Tasks.Count-1 do
result:=result + tBaseEmerAPIServerTask(Tasks[i]).getCost;
end;
function tEmerAPIServerTaskGroup.getUniOwnerCount:integer;
var i:integer;
nl:tStringList;
begin
result:=0;
if Tasks.Count=1 then begin
result:=1;
exit;
end;
nl:=tStringList.Create;
try
for i:=0 to Tasks.Count-1 do
if nl.IndexOf(tBaseEmerAPIServerTask(Tasks[i]).ownerAddress)<0 then begin
nl.Add(tBaseEmerAPIServerTask(Tasks[i]).ownerAddress);
result:=result + 1;
end;
finally
nl.free;
end;
end;
function tEmerAPIServerTaskGroup.getOwnerByCount(address:ansistring='undefined'):integer;
var i:integer;
begin
result:=0;
for i:=0 to Tasks.Count-1 do
if tBaseEmerAPIServerTask(Tasks[i]).ownerAddress=address then
result:=result + 1;
end;
constructor tEmerAPIServerTaskGroup.create(mOwner:tEmerAPIServerTaskList);
begin
inherited create(mOwner);
Tasks:=tEmerAPIServerTaskList.create(fOwner.fEmerApi);
Tasks.fOwnerTask:=self;
//update
//error
//newtask
//taskremoved
//taskUpdated
Tasks.addNotify(EmerAPINotification(@(fOwner.myUpdate),'update',true));
Tasks.addNotify(EmerAPINotification(@(fOwner.myError),'error',true));
Tasks.addNotify(EmerAPINotification(@(fOwner.myNewTask),'newtask',true));
Tasks.addNotify(EmerAPINotification(@(fOwner.myTaskRemoved),'taskremoved',true));
Tasks.addNotify(EmerAPINotification(@(fOwner.mytaskUpdated),'taskUpdated',true));
end;
destructor tEmerAPIServerTaskGroup.destroy;
begin
freeandnil(Tasks);
inherited;
end;
{tEmerAPIServerTaskList}
procedure tEmerAPIServerTaskList.myUpdate(sender:tObject);
var i:integer;
begin
//if ALL tasks are updated, call Update notify
for i:=0 to Count-1 do
if not Items[i].fUpdated then exit;;
//set parent group task updated = true
if fOwnerTask<>nil then
fOwnerTask.fUpdated:=true;
//call notification
callNotify('update');
end;
procedure tEmerAPIServerTaskList.myError(sender:tObject);
begin
callNotify('error');
end;
procedure tEmerAPIServerTaskList.myNewTask(sender:tObject);
begin
callNotify('newtask')
end;
procedure tEmerAPIServerTaskList.myTaskRemoved(sender:tObject);
begin
callNotify('taskremoved')
end;
procedure tEmerAPIServerTaskList.mytaskUpdated(sender:tObject);
begin
callNotify('taskUpdated')
end;
procedure tEmerAPIServerTaskList.onAsyncQueryDoneHandler(sender:TEmerAPIBlockchainThread;result:tJsonData);
var js,e:tJsonData;
ja:tJSONArray;
s:string;
x:double;
i,j:integer;
st:ansistring;
groupID:ansistring;
taskID:ansistring;
task:tEmerAPIServerTask;
group:tEmerAPIServerTaskGroup;
q:qword;
taskidx:integer;
function safeString(e:tJsonData):string;
begin
if e<>nil then
if e.IsNull
then result:=''
else result:=e.asString
else result:='';
end;
begin
if result=nil then begin
fEmerAPI.EmerAPIConnetor.checkConnection();
exit;
end;
js:=result;
if pos('transactiongrouplist_',sender.id+'_')=1 then begin
//this is a main list
//{ "data" : { "transactiongrouplist" : [{ "address" : "address", "amount" : 1. ......
if js<>nil then begin
e:=js.FindPath('data.transactiongrouplist');
if (e<>nil) and (e is tJSONArray) then begin
ja:=tJSONArray(e);
for i:=0 to ja.Count-1 do begin
//group. Do we have it?
groupID:=ja[i].FindPath('id').AsString;
group:=nil;
for j:=0 to Count-1 do
if items[j] is tEmerAPIServerTaskGroup then
if uppercase(tEmerAPIServerTaskGroup(items[j]).id) =uppercase(groupID) then begin
group:=tEmerAPIServerTaskGroup(items[j]);
break;
end;
if group = nil then begin
group:=tEmerAPIServerTaskGroup.create(self);
fItems.add(group);
//Comment:string; //comment: String
group.Comment:=safeString(ja[i].FindPath('comment'));
//id:ansistring; //id: ID
group.id:=groupID;
//NVSName:ansistring; //name: String
group.NVSName:=safeString(ja[i].FindPath('name'));
//NVSValue:ansistring; //value
group.NVSValue:=safeString(ja[i].FindPath('value'));
try
q:=365;
s:=safeString(ja[i].FindPath('days'));
if s<>'' then q:=myStrToInt(s) else q:=365;
except
q:=365;
end;
group.NVSDays:=q;
//amount:dword; //amount: Float
s:=safeString(ja[i].FindPath('amount'));
if s<>'' then group.amount:=trunc(1000000*myStrToFloat(s))
else group.amount:=0;
//ownerAddress:ansistring; //address
group.ownerAddress:=safeString(ja[i].FindPath('address'));
//time:dword;
//LockTime:dword;
// dpo: String
// time: Int
//TaskType: String; //type
group.TaskType:=safeString(ja[i].FindPath('type'));
// group: ссылка на группу, при запросе можно получать поля, например id
group.Tasks.updateFromServer(groupID);
group.fUpdated:=false;
callNotify('newtask');
end;
end;
end;
//fLastUpdateTimeTX:=now;
//callNotify
myUpdate(self);
end;
end else
if pos('transactionlist_',sender.id+'_')=1 then begin
//this is a tasks list
//{ "data" : { "transactionlist" : [{ "address" : "address", "amount" : 1.000
// ... , "group" : { "id" : "5bd87ebef3a6087e32ee70b6" }
if js<>nil then begin
e:=js.FindPath('data.transactionlist');
if (e<>nil) and (e is tJSONArray) then begin
ja:=tJSONArray(e);
for i:=0 to ja.Count-1 do begin
//Task. Do we have it?
taskID:=ja[i].FindPath('id').AsString;
task:=nil;
for j:=0 to Count-1 do
if items[j] is tEmerAPIServerTask then
if uppercase(tEmerAPIServerTask(items[j]).id) =uppercase(taskID) then begin
task:=tEmerAPIServerTask(items[j]);
break;
end;
groupID:='';
e:=ja[i].FindPath('group.id');
if e<>nil then groupID:=e.AsString;
if task = nil then begin
task:=tEmerAPIServerTask.create(self);
taskidx:=fItems.add(task);
//Comment:string; //comment: String
task.Comment:=safeString(ja[i].FindPath('comment'));
//id:ansistring; //id: ID
//task.id:=groupID;
//NVSName:ansistring; //name: String
task.NVSName:=safeString(ja[i].FindPath('name'));
//NVSValue:ansistring; //value
task.NVSValue:=safeString(ja[i].FindPath('value'));
try
q:=365;
s:=safeString(ja[i].FindPath('days'));
if s<>'' then q:=myStrToInt(s) else q:=365;
except
q:=365;
end;
task.NVSDays:=q;
//amount:dword; //amount: Float
s:=safeString(ja[i].FindPath('amount'));
if s<>'' then task.amount:=trunc(1000000*myStrToFloat(s))
else task.amount:=0;
//ownerAddress:ansistring; //address
task.ownerAddress:=safeString(ja[i].FindPath('address'));
//time:dword;
//LockTime:dword;
// dpo: String
// time: Int
//TaskType: String; //type
task.TaskType:=safeString(ja[i].FindPath('type'));
task.fUpdated:=true;
if fValidateAfterCreate then validateTask(taskidx);
callNotify('newtask');
end;
end;
end;
myUpdate(self);
end;
end;
fLastUpdateTime:=now;
end;
procedure tEmerAPIServerTaskList.updateFromServer(groupID:ansistring='');
begin
//read tasks
if fEmerAPI=nil then raise exception.Create('tEmerAPIServerTaskList.updateFromServer: fEmerAPI=nil');
// if fEmerAPI.EmerAPIConnetor.sendQueryAsync();
if groupID='' then
//this is a main list
fEmerAPI.EmerAPIConnetor.sendQueryAsync(
'query { transactiongrouplist {'#13#10+
' address'#13#10+
' amount'#13#10+
' comment'#13#10+
' id'#13#10+
' name'#13#10+
' time'#13#10+
' type'#13#10+
' value'#13#10+
'}}'
, nil //GetJSON('{"action":"start",scanobjects:['+s+']}')
,@onAsyncQueryDoneHandler,'transactiongrouplist_'+fEmerAPI.EmerAPIConnetor.getNextID)
else
//this is a task list for a group groupID
fEmerAPI.EmerAPIConnetor.sendQueryAsync(
'query {transactionlist (group:"'+groupID+'") {'#13#10+
' address'#13#10+
' amount'#13#10+
' comment'#13#10+
// ' dpo'#13#10+
' id'#13#10+
' name'#13#10+
' time'#13#10+
' type'#13#10+
' value'#13#10+
' group {'#13#10+
' id'#13#10+
' }'#13#10+
' }}'
, nil //GetJSON('{"action":"start",scanobjects:['+s+']}')
,@onAsyncQueryDoneHandler,'transactionlist_'+groupID+'_'+fEmerAPI.EmerAPIConnetor.getNextID)
;
end;
procedure tEmerAPIServerTaskList.validateTask(Index:integer=-1); //-1 for all
var i:integer;
begin
if (index<-1) or (index>=fItems.count) then raise exception.Create('tEmerAPIServerTaskList.validateTask: index out of bounds');
if index<0 then
for i:=0 to fItems.count-1 do
tBaseEmerAPIServerTask(fItems[i]).validateTask()
else
tBaseEmerAPIServerTask(fItems[index]).validateTask();
end;
constructor tEmerAPIServerTaskList.create(mEmerAPI:tEmerAPI; setValidateAfterCreate:boolean=true);
begin
inherited create();
fEmerAPI:=mEmerAPI;
fItems:=tList.Create;
fvalidateAfterCreate:=setValidateAfterCreate;
end;
procedure tEmerAPIServerTaskList.clearList;
var i:integer;
begin
for i:=0 to fItems.Count-1 do
tBaseEmerAPIServerTask(fItems[i]).Free;
fItems.Clear;
end;
procedure tEmerAPIServerTaskList.delete(Index: integer);
begin
if (index<0) or (index>=fItems.count) then raise exception.Create('tEmerAPIServerTaskList.delete: index out of bounds');
tBaseEmerAPIServerTask(fItems[index]).Free;
fItems.Delete(index);
end;
destructor tEmerAPIServerTaskList.destroy;
begin
clearList;
fItems.Free;
inherited;
end;
function tEmerAPIServerTaskList.getItem(Index: integer):tBaseEmerAPIServerTask;
begin
if (Index<0) or (Index>=Count) then raise exception.Create('tEmerAPIServerTaskList.getItem: index out of bounds');
result:=tBaseEmerAPIServerTask(fItems[Index]);
end;
function tEmerAPIServerTaskList.getCount:integer;
begin
result:=fItems.Count;
end;
end.
|
unit rhlSipHash;
interface
uses
rhlCore, sysutils, Dialogs;
type
{ TrhlSipHash }
TrhlSipHash = class(TrhlHashWithKey)
private
const
V0: QWord = $736f6d6570736575;
V1: QWord = $646f72616e646f6d;
V2: QWord = $6c7967656e657261;
V3: QWord = $7465646279746573;
KEY0: QWord = $0706050403020100;
KEY1: QWord = $0F0E0D0C0B0A0908;
var
m_v0,
m_v1,
m_v2,
m_v3,
m_key0,
m_key1: QWord;
procedure m_round;
protected
procedure UpdateBlock(const AData); override;
function GetKey: TBytes; override;
procedure SetKey(AValue: TBytes); override;
public
constructor Create; override;
procedure Init; override;
procedure Final(var ADigest); override;
end;
implementation
{ TrhlSipHash }
procedure TrhlSipHash.m_round;
begin
m_v0 += m_v1;
m_v1 := RolQWord(m_v1, 13);
m_v1 := m_v1 xor m_v0;
m_v0 := RolQWord(m_v0, 32);
m_v2 += m_v3;
m_v3 := RolQWord(m_v3, 16);
m_v3 := m_v3 xor m_v2;
m_v0 += m_v3;
m_v3 := RolQWord(m_v3, 21);
m_v3 := m_v3 xor m_v0;
m_v2 += m_v1;
m_v1 := RolQWord(m_v1, 17);
m_v1 := m_v1 xor m_v2;
m_v2 := RolQWord(m_v2, 32);
end;
procedure TrhlSipHash.UpdateBlock(const AData);
var
m: QWord absolute AData;
begin
m_v3 := m_v3 xor m;
m_round;
m_round;
m_v0 := m_v0 xor m;
end;
function TrhlSipHash.GetKey: TBytes;
begin
SetLength(Result, SizeOf(QWord)*2);
Move(m_key0, Result[0], SizeOf(QWord));
Move(m_key1, Result[8], SizeOf(QWord));
end;
procedure TrhlSipHash.SetKey(AValue: TBytes);
begin
if Length(AValue) = SizeOf(m_key0)*2 then
begin
Move(AValue[0], m_key0, SizeOf(m_key0));
Move(AValue[8], m_key1, SizeOf(m_key1));
end;
end;
constructor TrhlSipHash.Create;
begin
HashSize := 8;
BlockSize := 8;
m_key0 := KEY0;
m_key1 := KEY1;
end;
procedure TrhlSipHash.Init;
begin
inherited Init;
m_v0 := V0;
m_v1 := V1;
m_v2 := V2;
m_v3 := V3;
m_v3 := m_v3 xor m_key1;
m_v2 := m_v2 xor m_key0;
m_v1 := m_v1 xor m_key1;
m_v0 := m_v0 xor m_key0;
end;
procedure TrhlSipHash.Final(var ADigest);
var
b: QWord;
left: QWord;
i: Integer;
begin
b := QWord(FProcessedBytes) shl 56;
FBuffer.SetZeroPadded;
Move(FBuffer.Bytes[0], left, SizeOf(QWord));
b := b or left;
UpdateBlock(b);
m_v2 := m_v2 xor $ff;
for i := 0 to 3 do
m_round;
m_v0 := m_v0 xor m_v1 xor m_v2 xor m_v3;
Move(m_v0, ADigest, SizeOf(QWord));
end;
end.
|
unit PlayerLogger;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
{ TPlayerLogger }
TPlayerLogger = class
private class var
FCriticalSection: TRTLCriticalSection;
FFile: TextFile;
FPrepared: Boolean;
private
class procedure Prepare;
public
class constructor ClassCreate;
class destructor ClassDestroy;
class procedure Log(const AMsg: String); overload;
class procedure Log(const AMsg: String; const Values: array of const);
overload;
end;
logger = TPlayerLogger;
implementation
uses
PlayerSessionStorage, PlayerOptions;
{ TPlayerLogger }
class procedure TPlayerLogger.Prepare;
var
LogFile: String;
begin
LogFile:=opts.TempDir + 'player.log';
AssignFile(FFile, LogFile);
if FileExists(LogFile) then Append(FFile) else Rewrite(FFile);
FPrepared:=True;
end;
class constructor TPlayerLogger.ClassCreate;
begin
inherited;
FPrepared:=False;
InitCriticalSection(FCriticalSection);
end;
class destructor TPlayerLogger.ClassDestroy;
begin
DoneCriticalsection(FCriticalSection);
if FPrepared then CloseFile(FFile);
inherited;
end;
class procedure TPlayerLogger.Log(const AMsg: String);
begin
if not (ploExtractor in opts.LogOptions) then Exit;
EnterCriticalsection(FCriticalSection);
try
if not FPrepared then Prepare;
WriteLn(FFile, '[', FormatDateTime(PLAYER_DATE_FORMAT, Now), ']: ',
AMsg);
finally
LeaveCriticalsection(FCriticalSection);
end;
end;
class procedure TPlayerLogger.Log(const AMsg: String;
const Values: array of const);
begin
Log(Format(AMsg, Values));
end;
end.
|
Program PATTERNS; {-*- Mode: Pascal -*-}
{
This program is designed for demo purposes only. It doesn't really do
anything; it's just here for display. Enjoy the concept of programming
in Pascal (Yecchh!) using AMACS, the EMACS for the Apple.
}
Uses TURTLEGRAPHICS, APPLESTUFF; {we USE these Units}
Const maxx =280; {x coordinates available on screen}
maxy =191; {y coordinates available on screen}
radius =95; {maximum radius of figure to be drawn}
Type point =record {stupid Pascal has MOVETO, but not Point.}
y: 0..maxy
x: 0..maxx;
end;
Var cycles: 0..2;
theta: 3..15;
trgl: array [1..3] of point;
c: 1..3;
corner: point;
Function Arbitrary(Low, High: integer) :integer;
{
Returns a pseudo-random integer in the rage of Low through High. This
function should only be called with a constant as parameters. High must be
strictly greater than Low; it must not be equal to Low. Also, the difference
between High and Low must not exceed MAXINT.
}
Var mx,z,d: integer;
Begin {arbitrary}
z := High-Low+1;
mx := (MAXINT-High+Low) div (z+1);
mx := mx * (High-Low) + (mx-1);
Repeat d := random Until (d <= mx);
Arbitrary := :Low+d mod z;
End; {arbitrary}
Procedure Rotate(angle: integer); Forward; {Maybe in some other file?}
Begin {main progam}
Repeat
theta := (ramdom);
cycles := 0;
repeat
rotate (theta);
pencolor (reverse);
for c := 1 tp 3 do moveto (trgl[c].x, trgl[c].y);
if trgl[3] = corner then cycles := cycles +1;
until cycles =2
Until KeyPress
End. {main program}
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DBAdaptImg;
interface
{$IFDEF MSWINDOWS}
uses System.Classes, Winapi.Messages, Web.HTTPApp, WebComp, Data.DB, SiteComp, System.SysUtils,
WebContnrs, WebAdapt, DBAdapt, AdaptReq;
{$ENDIF}
{$IFDEF LINUX}
uses Classes, HTTPApp, WebComp, DB, SiteComp, SysUtils,
WebContnrs, WebAdapt, DBAdapt, AdaptReq;
{$ENDIF}
type
TImageDataSetFieldGetImageEvent = procedure(Sender: TObject;
var MimeType: string; var Image: TStream; var Owned: Boolean) of object;
TCustomDataSetAdapterImageField = class(TBaseDataSetAdapterImageField,
IGetAdapterImage, IGetAdapterItemRequestParams,
IAdapterRequestHandler, IWebImageHREF)
private
FOnGetHREF: TImageFieldGetHREFEvent;
FOnGetImage: TImageDataSetFieldGetImageEvent;
protected
function CheckOrUpdateValue(AActionRequest: IActionRequest;
AFieldIndex: Integer; AUpdate: Boolean): Boolean;
function GetDataSetFieldValue(Field: TField): Variant; override;
{ IWebImageHREF }
function ImplWebImageHREF(var AHREF: string): Boolean; virtual;
function WebImageHREF(var AHREF: string): Boolean;
{ IAdapterRequestHandler }
procedure CreateRequestContext(DispatchParams: IAdapterDispatchParams);
procedure ImplCreateRequestContext(DispatchParams: IAdapterDispatchParams);
function HandleRequest(DispatchParams: IAdapterDispatchParams): Boolean;
function ImplHandleRequest(DispatchParams: IAdapterDispatchParams): Boolean; virtual;
{ ICheckValueChange }
function ImplCheckValueChange(AActionRequest: IActionRequest;
AFieldIndex: Integer): Boolean; override;
{ IUpdateValue }
procedure ImplUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer); override;
{ IGetHTMLStyle }
function GetDisplayStyleType(const AAdapterMode: string): TAdapterDisplayHTMLElementType; override;
function GetInputStyleType(const AAdapterMode: string): TAdapterInputHTMLElementType; override;
{ IGetAdapterImage }
function GetAdapterImage: TComponent;
{ IRenderAdapterImage }
procedure RenderAdapterImage(ARequest: IImageRequest; AResponse: IImageResponse);
{ IGetAdapterItemRequestParams }
procedure GetAdapterItemRequestParams(
var AIdentifier: string; AParams: IAdapterItemRequestParams);
public
constructor Create(AOwner: TComponent); override;
property OnGetImage: TImageDataSetFieldGetImageEvent read FOnGetImage write FOnGetImage;
property OnGetHREF: TImageFieldGetHREFEvent read FOnGetHREF write FOnGetHREF;
end;
TDataSetAdapterImageField = class(TCustomDataSetAdapterImageField)
published
property DataSetField;
property ViewAccess;
property ModifyAccess;
property OnGetImage;
property OnGetHREF;
property FieldModes;
end;
implementation
uses System.Variants, Web.WebCntxt,
AutoAdap,
{$IFDEF MSWINDOWS}
Vcl.Graphics, Vcl.Imaging.jpeg,
{$ENDIF}
SiteConst;
{ TCustomDataSetAdapterImageField }
function TCustomDataSetAdapterImageField.GetAdapterImage: TComponent;
begin
case Adapter.Mode of
amInsert, amQuery: Result := nil
else
Result := Self;
end;
end;
function TCustomDataSetAdapterImageField.GetDisplayStyleType(const AAdapterMode: string): TAdapterDisplayHTMLElementType;
begin
Result := htmldImage;
end;
function TCustomDataSetAdapterImageField.GetInputStyleType(const AAdapterMode: string): TAdapterInputHTMLElementType;
begin
Result := htmliFile;
end;
procedure TCustomDataSetAdapterImageField.RenderAdapterImage(
ARequest: IImageRequest; AResponse: IImageResponse);
var
S: TStream;
Bytes: array[0..7] of Byte; // Used for reading in the image header
Response: TWebResponse;
Field: TField;
ContentType: string;
ContentStream: TStream;
MimeType: string;
Image: TStream;
Owned: Boolean;
{$IFDEF MSWINDOWS}
procedure ConvertBitmapToJpeg;
var
Bmp: TBitmap;
JPEG: TJPEGImage;
begin
// Convert the bitmap to a jpeg
Bmp := TBitmap.Create;
try
Bmp.LoadFromStream(ContentStream);
JPEG := TJPEGImage.Create;
try
JPEG.Assign(Bmp);
S := TMemoryStream.Create;
JPEG.SaveToStream(S);
S.Seek(0, soFromBeginning);
ContentStream.Free; // Since, it already contained the blob
ContentStream := S;
finally
JPEG.Free;
end;
ContentType := 'image/jpeg';
finally
Bmp.Free;
end
end;
{$ENDIF}
begin
CheckViewAccess;
Response := WebContext.Response;
Response.ContentType := 'text/html'; // for any exceptions that may happen
ContentStream := nil;
Adapter.ExtractRequestParams(ARequest);
if Adapter.SilentLocate(Adapter.LocateParamsList, True) then
begin
if Assigned(FOnGetImage) then
begin
Image := nil;
Owned := True;
S := nil;
FOnGetImage(Self, MimeType, Image, Owned);
if Image <> nil then
begin
try
if not Owned then
begin
S := TMemoryStream.Create;
S.CopyFrom(Image, 0);
end
else
S := Image;
S.Seek(0, soFromBeginning);
except
if Owned then
Image.Free;
if Image <> S then
S.Free;
raise;
end;
Assert(MimeType <> '');
ContentType := MimeType;
ContentStream := S;
end;
end;
if ContentStream = nil then
begin
Field := Adapter.DataSet.FindField(DataSetField);
if Assigned(Field) then
begin
ContentType := '';
ContentStream := Field.DataSet.CreateBlobStream(Field, bmRead);
// Try reading the first few (8 to be exact) bytes of the content
// stream to see what type of image it is.
try
if ContentStream.Size < SizeOf(Bytes) then
raise EAdapterFieldException.CreateFmt(sInvalidImageSize, [SizeOf(Bytes)]);
ContentStream.Read(Bytes[0], SizeOf(Bytes));
// 0xFFD8 is the starting marker for a JPEG
if (Bytes[0] = $FF) and (Bytes[1] = $D8) then
ContentType := 'image/jpeg' { Do not localize}
// 'GIF' (as in the string literal) is the starting marker
// for a GIF
else if (Bytes[0] = Ord('G')) and { Do not localize}
(Bytes[1] = Ord('I')) and { Do not localize}
(Bytes[2] = Ord('F')) then { Do not localize}
ContentType := 'image/gif' { Do not localize}
// For ping, the first 8 bytes header is:
// (HEX) 89 50 4e 47 0d 0a 1a 0a
// (ASCII C notation) \211 P N G \r \n \032 \n
else if (Bytes[0] = $89) and
(Bytes[1] = $50) and
(Bytes[2] = $4e) and
(Bytes[3] = $47) and
(Bytes[4] = $0d) and
(Bytes[5] = $0a) and
(Bytes[6] = $1a) and
(Bytes[7] = $0a) then
ContentType := 'image/png' { Do not localize}
{$IFDEF MSWINDOWS}
// Paradox graphic header (bitmaps)
// TGraphicHeader = record
// Count: Word; { Fixed at 1 }
// HType: Word; { Fixed at $0100 }
// Size: Longint; { Size not including header }
// end;
// This looks strange below due to the byte order
else if (Bytes[0] = $01) and
(Bytes[1] = $00) and
(Bytes[2] = $00) and
(Bytes[3] = $01) then // Ignore the Size:Longint
begin
// Remove the TGraphicHeader
// SizeOf(TGraphicHeader) = 8 bytes, but TGraphicHeaderis not public
ContentStream.Seek(8, soFromBeginning);
ConvertBitmapToJpeg;
end
{$ENDIF}
else if (Bytes[0] = Ord('B')) and { Do not localize}
(Bytes[1] = Ord('M')) then // Windows bitmap { Do not localize}
{$IFDEF MSWINDOWS}
begin
ContentStream.Seek(0, soFromBeginning); // Return to the start of the file
ConvertBitmapToJpeg
end
{$ENDIF MSWINDOWS}
{$IFDEF LINUX}
raise EAdapterFieldException.Create(Format(sIncorrectImageFormat,
['image/bmp', FieldName]), FieldName) { Do not localize }
{$ENDIF LINUX}
else
raise EAdapterFieldException.Create(Format(sIncorrectImageFormat,
[sUnknownImageType, FieldName]), FieldName)
except
FreeAndNil(ContentStream);
raise;
end;
// Go back to the start of the file.
ContentStream.Position := 0;
end;
end;
end;
Response.ContentType := AnsiString(ContentType);
Response.ContentStream := ContentStream;
end;
function GetActionFieldValues(AActionRequest: IActionRequest): IActionFieldValues;
begin
if not Supports(AActionRequest, IActionFieldValues, Result) then
Assert(False);
end;
function TCustomDataSetAdapterImageField.CheckOrUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer;
AUpdate: Boolean): Boolean;
var
Field: TField;
FieldValue: IActionFieldValue;
{$IFDEF MSWINDOWS}
Bmp: TBitmap;
{$ENDIF}
begin
Result := False;
Assert(Adapter <> nil);
Assert(Adapter.DataSet <> nil);
with GetActionFieldValues(AActionRequest) do
FieldValue := Values[AFieldIndex];
if FieldValue.FileCount > 0 then
begin
Field := Adapter.DataSet.FindField(DataSetField);
if Field = nil then
Adapter.RaiseFieldNotFound(DataSetField);
if FieldValue.FileCount = 1 then
begin
if AUpdate then
begin
{$IFDEF MSWINDOWS}
if FieldValue.Files[0].ContentType = 'image/bmp' then
begin
Bmp := TBitmap.Create;
try
Bmp.LoadFromStream(FieldValue.Files[0].Stream);
Field.Assign(Bmp);
finally
Bmp.Free;
end;
end
else
{$ENDIF MSWINDOWS}
// Only support jpeg and gif on Kylix. pjpeg is sent by IE, and is "progressive" jpeg
if (FieldValue.Files[0].ContentType = 'image/jpeg') or
(FieldValue.Files[0].ContentType = 'image/pjpeg') or
(FieldValue.Files[0].ContentType = 'image/gif') or
(FieldValue.Files[0].ContentType = 'image/png') or
(FieldValue.Files[0].ContentType = 'image/x-png') then
(Field as TBlobField).LoadFromStream(FieldValue.Files[0].Stream)
else
raise EAdapterFieldException.Create(Format(sIncorrectImageFormat, [FieldValue.Files[0].ContentType, FieldName]),
FieldName);
end
else
Result := True;
end
else
RaiseMultipleFilesException(FieldName);
end
else if (FieldValue.ValueCount > 0) and (FieldValue.Values[0] <> '') then
raise EAdapterFieldException.Create(sFileExpected,
FieldName);
end;
procedure TCustomDataSetAdapterImageField.ImplUpdateValue(AActionRequest: IActionRequest; AFieldIndex: Integer);
begin
CheckModifyAccess;
CheckOrUpdateValue(AActionRequest, AFieldIndex, True);
end;
function TCustomDataSetAdapterImageField.GetDataSetFieldValue(
Field: TField): Variant;
begin
// Field.Value will return binary data. Use DisplayText instead.
Result := Field.DisplayText;
end;
function TCustomDataSetAdapterImageField.ImplCheckValueChange(
AActionRequest: IActionRequest; AFieldIndex: Integer): Boolean;
begin
Result := CheckOrUpdateValue(AActionRequest, AFieldIndex, False);
end;
function TCustomDataSetAdapterImageField.ImplWebImageHREF(var AHREF: string): Boolean;
begin
if DesigningComponent(Self) and Assigned(GetHTMLSampleImage) then
AHREF := GetHTMLSampleImage
else
begin
AHREF := '';
if Assigned(FOnGetHREF) then
FOnGetHREF(Self, AHREF);
end;
Result := AHREF <> '';
end;
function TCustomDataSetAdapterImageField.WebImageHREF(var AHREF: string): Boolean;
begin
Result := ImplWebImageHREF(AHREF);
end;
procedure TCustomDataSetAdapterImageField.CreateRequestContext(
DispatchParams: IAdapterDispatchParams);
begin
ImplCreateRequestContext(DispatchParams);
end;
function TCustomDataSetAdapterImageField.HandleRequest(
DispatchParams: IAdapterDispatchParams): Boolean;
begin
Result := ImplHandleRequest(DispatchParams);
end;
procedure TCustomDataSetAdapterImageField.ImplCreateRequestContext(
DispatchParams: IAdapterDispatchParams);
var
Obj: TBasicImageRequestImpl;
begin
Obj := TBasicImageRequestImpl.Create(DispatchParams);
TBasicImageResponseImpl.Create(Obj);
end;
function TCustomDataSetAdapterImageField.ImplHandleRequest(
DispatchParams: IAdapterDispatchParams): Boolean;
var
ImageRequest: IImageRequest;
ImageResponse: IImageResponse;
begin
Result := Supports(WebContext.AdapterRequest, IImageRequest, ImageRequest) and
Supports(WebContext.AdapterResponse, IImageResponse, ImageResponse);
Assert(Result);
if Result then
RenderAdapterImage(ImageRequest, ImageResponse);
end;
procedure TCustomDataSetAdapterImageField.GetAdapterItemRequestParams(
var AIdentifier: string; AParams: IAdapterItemRequestParams);
begin
AIdentifier := MakeAdapterRequestIdentifier(Self);
Adapter.EncodeActionParamsFlags(AParams, [poLocateParams]);
end;
constructor TCustomDataSetAdapterImageField.Create(AOwner: TComponent);
begin
inherited;
FieldModes := [amInsert, amEdit, amBrowse {, amQuery}];
end;
initialization
DataSetAdapterImageFieldClass := TDataSetAdapterImageField;
end.
|
{ ********************************************************************** }
{ }
{ Delphi and Kylix Cross-Platform Open Tools API }
{ }
{ Copyright (C) 1995, 2001 Borland Software Corporation }
{ }
{ All Rights Reserved. }
{ }
{ ********************************************************************** }
unit DesignEditors;
interface
uses
Types, SysUtils, Classes, TypInfo, Variants, DesignIntf, DesignMenus;
{ Property Editors }
type
TInstProp = record
Instance: TPersistent;
PropInfo: PPropInfo;
end;
PInstPropList = ^TInstPropList;
TInstPropList = array[0..1023] of TInstProp;
TPropertyEditor = class(TBasePropertyEditor, IProperty)
private
FDesigner: IDesigner;
FPropList: PInstPropList;
FPropCount: Integer;
function GetPrivateDirectory: string;
protected
procedure SetPropEntry(Index: Integer; AInstance: TPersistent;
APropInfo: PPropInfo); override;
protected
function GetFloatValue: Extended;
function GetFloatValueAt(Index: Integer): Extended;
function GetInt64Value: Int64;
function GetInt64ValueAt(Index: Integer): Int64;
function GetMethodValue: TMethod;
function GetMethodValueAt(Index: Integer): TMethod;
function GetOrdValue: Longint;
function GetOrdValueAt(Index: Integer): Longint;
function GetStrValue: string;
function GetStrValueAt(Index: Integer): string;
function GetVarValue: Variant;
function GetVarValueAt(Index: Integer): Variant;
function GetIntfValue: IInterface;
function GetIntfValueAt(Index: Integer): IInterface;
procedure Modified;
procedure SetFloatValue(Value: Extended);
procedure SetMethodValue(const Value: TMethod);
procedure SetInt64Value(Value: Int64);
procedure SetOrdValue(Value: Longint);
procedure SetStrValue(const Value: string);
procedure SetVarValue(const Value: Variant);
procedure SetIntfValue(const Value: IInterface);
protected
{ IProperty }
function GetEditValue(out Value: string): Boolean;
function HasInstance(Instance: TPersistent): Boolean;
public
constructor Create(const ADesigner: IDesigner; APropCount: Integer); override;
destructor Destroy; override;
procedure Activate; virtual;
function AllEqual: Boolean; virtual;
function AutoFill: Boolean; virtual;
procedure Edit; virtual;
function GetAttributes: TPropertyAttributes; virtual;
function GetComponent(Index: Integer): TPersistent;
function GetEditLimit: Integer; virtual;
function GetName: string; virtual;
procedure GetProperties(Proc: TGetPropProc); virtual;
function GetPropInfo: PPropInfo; virtual;
function GetPropType: PTypeInfo;
function GetValue: string; virtual;
function GetVisualValue: string;
procedure GetValues(Proc: TGetStrProc); virtual;
procedure Initialize; override;
procedure Revert;
procedure SetValue(const Value: string); virtual;
function ValueAvailable: Boolean;
property Designer: IDesigner read FDesigner;
property PrivateDirectory: string read GetPrivateDirectory;
property PropCount: Integer read FPropCount;
property Value: string read GetValue write SetValue;
end;
{ TOrdinalProperty
The base class of all ordinal property editors. It established that ordinal
properties are all equal if the GetOrdValue all return the same value. }
TOrdinalProperty = class(TPropertyEditor)
function AllEqual: Boolean; override;
function GetEditLimit: Integer; override;
end;
{ TIntegerProperty
Default editor for all Longint properties and all subtypes of the Longint
type (i.e. Integer, Word, 1..10, etc.). Restricts the value entered into
the property to the range of the sub-type. }
TIntegerProperty = class(TOrdinalProperty)
public
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TCharProperty
Default editor for all Char properties and sub-types of Char (i.e. Char,
'A'..'Z', etc.). }
TCharProperty = class(TOrdinalProperty)
public
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TEnumProperty
The default property editor for all enumerated properties (e.g. TShape =
(sCircle, sTriangle, sSquare), etc.). }
TEnumProperty = class(TOrdinalProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TBoolProperty is now obsolete. TEnumProperty handles bool types. }
TBoolProperty = class(TEnumProperty)
end deprecated;
{ TInt64Property
Default editor for all Int64 properties and all subtypes of Int64. }
TInt64Property = class(TPropertyEditor)
public
function AllEqual: Boolean; override;
function GetEditLimit: Integer; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TFloatProperty
The default property editor for all floating point types (e.g. Float,
Single, Double, etc.) }
TFloatProperty = class(TPropertyEditor)
public
function AllEqual: Boolean; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TStringProperty
The default property editor for all strings and sub types (e.g. string,
string[20], etc.). }
TStringProperty = class(TPropertyEditor)
public
function AllEqual: Boolean; override;
function GetEditLimit: Integer; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TNestedProperty
A property editor that uses the parent's Designer, PropList and PropCount.
The constructor and destructor do not call inherited, but all derived classes
should. This is useful for properties like the TSetElementProperty. }
TNestedProperty = class(TPropertyEditor)
public
constructor Create(Parent: TPropertyEditor); reintroduce;
destructor Destroy; override;
end;
{ TSetElementProperty
A property editor that edits an individual set element. GetName is
changed to display the set element name instead of the property name and
Get/SetValue is changed to reflect the individual element state. This
editor is created by the TSetProperty editor. }
TSetElementProperty = class(TNestedProperty)
private
FElement: Integer;
protected
constructor Create(Parent: TPropertyEditor; AElement: Integer); reintroduce;
property Element: Integer read FElement;
public
function AllEqual: Boolean; override;
function GetAttributes: TPropertyAttributes; override;
function GetName: string; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TSetProperty
Default property editor for all set properties. This editor does not edit
the set directly but will display sub-properties for each element of the
set. GetValue displays the value of the set in standard set syntax. }
TSetProperty = class(TOrdinalProperty)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetProperties(Proc: TGetPropProc); override;
function GetValue: string; override;
end;
{ TClassProperty
Default property editor for all objects. Does not allow modifying the
property but does display the class name of the object and will allow the
editing of the object's properties as sub-properties of the property. }
TClassProperty = class(TPropertyEditor)
public
function GetAttributes: TPropertyAttributes; override;
procedure GetProperties(Proc: TGetPropProc); override;
function GetValue: string; override;
end;
{ TMethodProperty
Property editor for all method properties. }
TMethodProperty = class(TPropertyEditor, IMethodProperty)
public
function AllNamed: Boolean; virtual;
function AllEqual: Boolean; override;
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetEditLimit: Integer; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const AValue: string); override;
function GetFormMethodName: string; virtual;
function GetTrimmedEventName: string;
end;
{ TComponentProperty
The default editor for TComponents. It does not allow editing of the
properties of the component. It allow the user to set the value of this
property to point to a component in the same form that is type compatible
with the property being edited (e.g. the ActiveControl property). }
TComponentProperty = class(TPropertyEditor, IReferenceProperty)
protected
function FilterFunc(const ATestEditor: IProperty): Boolean;
function GetComponentReference: TComponent; virtual;
function GetSelections: IDesignerSelections; virtual;
public
function AllEqual: Boolean; override;
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
procedure GetProperties(Proc: TGetPropProc); override;
function GetEditLimit: Integer; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TInterfaceProperty
The default editor for interface references. It allows the user to set
the value of this property to refer to an interface implemented by
a component on the form (or via form linking) that is type compatible
with the property being edited. }
TInterfaceProperty = class(TComponentProperty)
private
FGetValuesStrProc: TGetStrProc;
protected
procedure ReceiveComponentNames(const S: string);
function GetComponent(const AInterface: IInterface): TComponent;
function GetComponentReference: TComponent; override;
function GetSelections: IDesignerSelections; override;
public
function AllEqual: Boolean; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
{ TComponentNameProperty
Property editor for the Name property. It restricts the name property
from being displayed when more than one component is selected. }
TComponentNameProperty = class(TStringProperty)
public
function GetAttributes: TPropertyAttributes; override;
function GetEditLimit: Integer; override;
end;
{ TDateProperty
Property editor for date portion of TDateTime type. }
TDateProperty = class(TPropertyEditor)
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TTimeProperty
Property editor for time portion of TDateTime type. }
TTimeProperty = class(TPropertyEditor)
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TDateTimeProperty
Edits both date and time data simultaneously }
TDateTimeProperty = class(TPropertyEditor)
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TVariantProperty }
TVariantProperty = class(TPropertyEditor)
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
procedure GetProperties(Proc: TGetPropProc); override;
end;
procedure GetComponentProperties(const Components: IDesignerSelections;
Filter: TTypeKinds; const Designer: IDesigner; Proc: TGetPropProc;
EditorFilterFunc: TPropertyEditorFilterFunc = nil);
{ Component Editors }
type
{ TComponentEditor
This class provides a default implementation for the IComponentEditor
interface. There is no assumption by the designer that you use this class
only that your class derive from TBaseComponentEditor and implement
IComponentEditor. This class is provided to help you implement a class
that meets those requirements. }
TComponentEditor = class(TBaseComponentEditor, IComponentEditor)
private
FComponent: TComponent;
FDesigner: IDesigner;
public
constructor Create(AComponent: TComponent; ADesigner: IDesigner); override;
procedure Edit; virtual;
procedure ExecuteVerb(Index: Integer); virtual;
function GetComponent: TComponent;
function GetDesigner: IDesigner;
function GetVerb(Index: Integer): string; virtual;
function GetVerbCount: Integer; virtual;
function IsInInlined: Boolean;
procedure Copy; virtual;
procedure PrepareItem(Index: Integer; const AItem: IMenuItem); virtual;
property Component: TComponent read FComponent;
property Designer: IDesigner read GetDesigner;
end;
{ TDefaultEditor
An editor that provides default behavior for the double-click that will
iterate through the properties looking the the most appropriate method
property to edit }
TDefaultEditor = class(TComponentEditor, IDefaultEditor)
private
FFirst: IProperty;
FBest: IProperty;
FContinue: Boolean;
procedure CheckEdit(const Prop: IProperty);
protected
procedure EditProperty(const Prop: IProperty; var Continue: Boolean); virtual;
public
procedure Edit; override;
end;
function GetComponentEditor(Component: TComponent;
const Designer: IDesigner): IComponentEditor;
{ Selection Editors }
type
{ TSelectionEditor
This provides a default implementation of the ISelectionEditor interface.
There is no assumption by the designer that you use this class only that
you have a class derived from TBaseSelectionEditor and implements the
ISelectionEdtior interface. This class is provided to help you implement a
class the meets those requirements. This class is also the selection editor
that will be created if no other selection editor is registered for a class. }
TSelectionEditor = class(TBaseSelectionEditor, ISelectionEditor)
private
FDesigner: IDesigner;
public
constructor Create(const ADesigner: IDesigner); override;
procedure ExecuteVerb(Index: Integer; const List: IDesignerSelections); virtual;
function GetVerb(Index: Integer): string; virtual;
function GetVerbCount: Integer; virtual;
procedure RequiresUnits(Proc: TGetStrProc); virtual;
procedure PrepareItem(Index: Integer; const AItem: IMenuItem); virtual;
property Designer: IDesigner read FDesigner;
end;
function GetSelectionEditors(const Designer: IDesigner): ISelectionEditorList; overload;
function GetSelectionEditors(const Designer: IDesigner;
const Selections: IDesignerSelections): ISelectionEditorList; overload;
function GetSelectionEditors(const Designer: IDesigner;
Component: TComponent): ISelectionEditorList; overload;
type
{ TEditActionSelectionEditor }
TEditActionSelectionEditor = class(TSelectionEditor)
private
procedure HandleToBack(Sender: TObject);
procedure HandleToFront(Sender: TObject);
protected
function GetEditState: TEditState;
procedure EditAction(Action: TEditAction);
procedure HandleCopy(Sender: TObject);
procedure HandleCut(Sender: TObject);
procedure HandleDelete(Sender: TObject);
procedure HandlePaste(Sender: TObject);
procedure HandleSelectAll(Sender: TObject);
procedure HandleUndo(Sender: TObject);
public
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure PrepareItem(Index: Integer; const AItem: IMenuItem); override;
end;
{ Custom Modules }
type
{ TCustomModule
This class provides a default implementation of the ICustomModule interface.
There is no assumption by the designer that a custom module derives form
this class only that it derive from TBaseCustomModule and implement the
ICustomModule interface. This class is provided to help you implement a
class that meets those requirements. }
TCustomModule = class(TBaseCustomModule, ICustomModule)
private
FRoot: TComponent;
FDesigner: IDesigner;
FFinder: TClassFinder;
public
constructor Create(ARoot: TComponent; const ADesigner: IDesigner); override;
destructor Destroy; override;
procedure ExecuteVerb(Index: Integer); virtual;
function GetAttributes: TCustomModuleAttributes; virtual;
function GetVerb(Index: Integer): string; virtual;
function GetVerbCount: Integer; virtual;
procedure Saving; virtual;
procedure PrepareItem(Index: Integer; const AItem: IMenuItem); virtual;
procedure ValidateComponent(Component: TComponent); virtual;
function ValidateComponentClass(ComponentClass: TComponentClass): Boolean; virtual;
function Nestable: Boolean; virtual;
property Root: TComponent read FRoot;
property Designer: IDesigner read FDesigner;
end;
{ ClassInheritsFrom
Returns true if ClassType, or one of its ancestors, name matches
ClassName. This allows checking ancestor by name instead of by class
reference. }
function ClassInheritsFrom(ClassType: TClass; const ClassName: string): Boolean;
{ AncestorNameMatches
Returns true if either ClassType descends from AncestorClass or doesn't
contain an ancestor class by the same name as AncestorClass. This ensures that
if ClassType has an ancestor by the same name it is AncestorClass. }
function AncestorNameMatches(ClassType: TClass; AncestorClass: TClass): Boolean;
{ Find the top level component (form, module, etc) }
type
TGetTopLevelComponentFunc = function(Ignoring: TComponent = nil): TComponent;
var
GetTopLevelComponentFunc: TGetTopLevelComponentFunc;
resourcestring
sClassNotApplicable = 'Class %s is not applicable to this module';
sNotAvailable = '(Not available)';
function PossibleStream(const S: string): Boolean;
{ Routines used by the form designer for package management }
type
TGroupChangeProc = procedure(AGroup: Integer);
IDesignGroupChange = interface
['{8B5614E7-A726-4622-B2A7-F79340B1B78E}']
procedure FreeEditorGroup(Group: Integer);
end;
function NewEditorGroup: Integer;
procedure FreeEditorGroup(Group: Integer);
procedure NotifyGroupChange(AProc: TGroupChangeProc);
procedure UnnotifyGroupChange(AProc: TGroupChangeProc);
var
GReferenceExpandable: Boolean = True;
GShowReadOnlyProps: Boolean = True;
implementation
uses DesignConst, Consts, RTLConsts, Contnrs, Proxies;
function PossibleStream(const S: string): Boolean;
var
I: Integer;
begin
Result := True;
for I := 1 to Length(S) - 6 do
begin
if (S[I] in ['O','o']) and (CompareText(Copy(S, I, 6), 'OBJECT') = 0) then Exit;
if not (S[I] in [' ',#9, #13, #10]) then Break;
end;
Result := False;
end;
{ TPropertyEditor }
constructor TPropertyEditor.Create(const ADesigner: IDesigner;
APropCount: Integer);
begin
inherited Create(ADesigner, APropCount);
FDesigner := ADesigner;
GetMem(FPropList, APropCount * SizeOf(TInstProp));
FPropCount := APropCount;
end;
destructor TPropertyEditor.Destroy;
begin
if FPropList <> nil then
FreeMem(FPropList, FPropCount * SizeOf(TInstProp));
end;
procedure TPropertyEditor.Activate;
begin
end;
function TPropertyEditor.AllEqual: Boolean;
begin
Result := FPropCount = 1;
end;
procedure TPropertyEditor.Edit;
type
TGetStrFunc = function(const Value: string): Integer of object;
var
I: Integer;
Values: TStringList;
AddValue: TGetStrFunc;
begin
if not AutoFill then Exit;
Values := TStringList.Create;
Values.Sorted := paSortList in GetAttributes;
try
AddValue := Values.Add;
GetValues(TGetStrProc(AddValue));
if Values.Count > 0 then
begin
I := Values.IndexOf(Value) + 1;
if I = Values.Count then I := 0;
Value := Values[I];
end;
finally
Values.Free;
end;
end;
function TPropertyEditor.AutoFill: Boolean;
begin
Result := Assigned(GetPropInfo^.SetProc);
end;
function TPropertyEditor.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paRevertable];
end;
function TPropertyEditor.GetComponent(Index: Integer): TPersistent;
begin
Result := FPropList^[Index].Instance;
end;
function TPropertyEditor.GetFloatValue: Extended;
begin
Result := GetFloatValueAt(0);
end;
function TPropertyEditor.GetFloatValueAt(Index: Integer): Extended;
begin
with FPropList^[Index] do Result := GetFloatProp(Instance, PropInfo);
end;
function TPropertyEditor.GetMethodValue: TMethod;
begin
Result := GetMethodValueAt(0);
end;
function TPropertyEditor.GetMethodValueAt(Index: Integer): TMethod;
begin
with FPropList^[Index] do Result := GetMethodProp(Instance, PropInfo);
end;
function TPropertyEditor.GetEditLimit: Integer;
begin
Result := 255;
end;
function TPropertyEditor.GetName: string;
begin
Result := FPropList^[0].PropInfo^.Name;
end;
function TPropertyEditor.GetOrdValue: Longint;
begin
Result := GetOrdValueAt(0);
end;
function TPropertyEditor.GetOrdValueAt(Index: Integer): Longint;
begin
with FPropList^[Index] do Result := GetOrdProp(Instance, PropInfo);
end;
function TPropertyEditor.GetPrivateDirectory: string;
begin
Result := '';
if Designer <> nil then
Result := Designer.GetPrivateDirectory;
end;
procedure TPropertyEditor.GetProperties(Proc: TGetPropProc);
begin
end;
function TPropertyEditor.GetPropInfo: PPropInfo;
begin
Result := FPropList^[0].PropInfo;
end;
function TPropertyEditor.GetPropType: PTypeInfo;
begin
Result := FPropList^[0].PropInfo^.PropType^;
end;
function TPropertyEditor.GetStrValue: string;
begin
Result := GetStrValueAt(0);
end;
function TPropertyEditor.GetStrValueAt(Index: Integer): string;
begin
with FPropList^[Index] do Result := GetStrProp(Instance, PropInfo);
end;
function TPropertyEditor.GetVarValue: Variant;
begin
Result := GetVarValueAt(0);
end;
function TPropertyEditor.GetVarValueAt(Index: Integer): Variant;
begin
with FPropList^[Index] do Result := GetVariantProp(Instance, PropInfo);
end;
function TPropertyEditor.GetValue: string;
begin
Result := srUnknown;
end;
function TPropertyEditor.GetVisualValue: string;
begin
if AllEqual then
Result := GetValue
else
Result := '';
end;
procedure TPropertyEditor.GetValues(Proc: TGetStrProc);
begin
end;
procedure TPropertyEditor.Initialize;
begin
end;
procedure TPropertyEditor.Modified;
begin
if Designer <> nil then
Designer.Modified;
end;
procedure TPropertyEditor.SetFloatValue(Value: Extended);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetFloatProp(Instance, PropInfo, Value);
Modified;
end;
procedure TPropertyEditor.SetMethodValue(const Value: TMethod);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetMethodProp(Instance, PropInfo, Value);
Modified;
end;
procedure TPropertyEditor.SetOrdValue(Value: Longint);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetOrdProp(Instance, PropInfo, Value);
Modified;
end;
procedure TPropertyEditor.SetPropEntry(Index: Integer;
AInstance: TPersistent; APropInfo: PPropInfo);
begin
with FPropList^[Index] do
begin
Instance := AInstance;
PropInfo := APropInfo;
end;
end;
procedure TPropertyEditor.SetStrValue(const Value: string);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetStrProp(Instance, PropInfo, Value);
Modified;
end;
procedure TPropertyEditor.SetVarValue(const Value: Variant);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetVariantProp(Instance, PropInfo, Value);
Modified;
end;
procedure TPropertyEditor.Revert;
var
I: Integer;
begin
if Designer <> nil then
for I := 0 to FPropCount - 1 do
with FPropList^[I] do Designer.Revert(Instance, PropInfo);
end;
procedure TPropertyEditor.SetValue(const Value: string);
begin
end;
function TPropertyEditor.ValueAvailable: Boolean;
var
I: Integer;
S: string;
begin
Result := True;
for I := 0 to FPropCount - 1 do
begin
if (FPropList^[I].Instance is TComponent) and
(csCheckPropAvail in TComponent(FPropList^[I].Instance).ComponentStyle) then
begin
try
S := GetValue;
AllEqual;
except
Result := False;
end;
Exit;
end;
end;
end;
function TPropertyEditor.GetInt64Value: Int64;
begin
Result := GetInt64ValueAt(0);
end;
function TPropertyEditor.GetInt64ValueAt(Index: Integer): Int64;
begin
with FPropList^[Index] do Result := GetInt64Prop(Instance, PropInfo);
end;
procedure TPropertyEditor.SetInt64Value(Value: Int64);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetInt64Prop(Instance, PropInfo, Value);
Modified;
end;
function TPropertyEditor.GetIntfValue: IInterface;
begin
Result := GetIntfValueAt(0);
end;
function TPropertyEditor.GetIntfValueAt(Index: Integer): IInterface;
begin
with FPropList^[Index] do Result := GetInterfaceProp(Instance, PropInfo);
end;
procedure TPropertyEditor.SetIntfValue(const Value: IInterface);
var
I: Integer;
begin
for I := 0 to FPropCount - 1 do
with FPropList^[I] do SetInterfaceProp(Instance, PropInfo, Value);
Modified;
end;
function TPropertyEditor.GetEditValue(out Value: string): Boolean;
begin
Result := False;
try
Value := GetValue;
Result := True;
except
on E: EPropWriteOnly do Value := sNotAvailable;
on E: Exception do Value := Format('(%s)', [E.Message]);
end;
end;
function TPropertyEditor.HasInstance(Instance: TPersistent): Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to FPropCount - 1 do
if FPropList^[I].Instance = Instance then Exit;
Result := False;
end;
{ TOrdinalProperty }
function TOrdinalProperty.AllEqual: Boolean;
var
I: Integer;
V: Longint;
begin
Result := False;
if PropCount > 1 then
begin
V := GetOrdValue;
for I := 1 to PropCount - 1 do
if GetOrdValueAt(I) <> V then Exit;
end;
Result := True;
end;
function TOrdinalProperty.GetEditLimit: Integer;
begin
Result := 63;
end;
{ TIntegerProperty }
function TIntegerProperty.GetValue: string;
begin
with GetTypeData(GetPropType)^ do
if OrdType = otULong then // unsigned
Result := IntToStr(Cardinal(GetOrdValue))
else
Result := IntToStr(GetOrdValue);
end;
procedure TIntegerProperty.SetValue(const Value: String);
procedure Error(const Args: array of const);
begin
raise EPropertyError.CreateResFmt(@SOutOfRange, Args);
end;
var
L: Int64;
begin
L := StrToInt64(Value);
with GetTypeData(GetPropType)^ do
if OrdType = otULong then
begin // unsigned compare and reporting needed
if (L < Cardinal(MinValue)) or (L > Cardinal(MaxValue)) then
// bump up to Int64 to get past the %d in the format string
Error([Int64(Cardinal(MinValue)), Int64(Cardinal(MaxValue))]);
end
else if (L < MinValue) or (L > MaxValue) then
Error([MinValue, MaxValue]);
SetOrdValue(L);
end;
{ TCharProperty }
function TCharProperty.GetValue: string;
var
Ch: Char;
begin
Ch := Chr(GetOrdValue);
if Ch in [#33..#127] then
Result := Ch else
FmtStr(Result, '#%d', [Ord(Ch)]);
end;
procedure TCharProperty.SetValue(const Value: string);
var
L: Longint;
begin
if Length(Value) = 0 then L := 0 else
if Length(Value) = 1 then L := Ord(Value[1]) else
if Value[1] = '#' then L := StrToInt(Copy(Value, 2, Maxint)) else
raise EPropertyError.CreateRes(@SInvalidPropertyValue);
with GetTypeData(GetPropType)^ do
if (L < MinValue) or (L > MaxValue) then
raise EPropertyError.CreateResFmt(@SOutOfRange, [MinValue, MaxValue]);
SetOrdValue(L);
end;
{ TEnumProperty }
function TEnumProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList, paRevertable];
end;
function TEnumProperty.GetValue: string;
var
L: Longint;
begin
L := GetOrdValue;
with GetTypeData(GetPropType)^ do
if (L < MinValue) or (L > MaxValue) then L := MaxValue;
Result := GetEnumName(GetPropType, L);
end;
procedure TEnumProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
EnumType: PTypeInfo;
begin
EnumType := GetPropType;
with GetTypeData(EnumType)^ do
begin
if MinValue < 0 then // longbool/wordbool/bytebool
begin
Proc(GetEnumName(EnumType, 0));
Proc(GetEnumName(EnumType, 1));
end
else
for I := MinValue to MaxValue do Proc(GetEnumName(EnumType, I));
end;
end;
procedure TEnumProperty.SetValue(const Value: string);
var
I: Integer;
begin
I := GetEnumValue(GetPropType, Value);
with GetTypeData(GetPropType)^ do
if (I < MinValue) or (I > MaxValue) then
raise EPropertyError.CreateRes(@SInvalidPropertyValue);
SetOrdValue(I);
end;
{ TBoolProperty }
{!!
function TBoolProperty.GetValue: string;
begin
Result := BooleanIdents[GetOrdValue <> 0];
end;
procedure TBoolProperty.GetValues(Proc: TGetStrProc);
begin
Proc(BooleanIdents[False]);
Proc(BooleanIdents[True]);
end;
procedure TBoolProperty.SetValue(const Value: string);
var
I: Integer;
begin
if SameText(Value, BooleanIdents[False]) then
I := 0
else if SameText(Value, BooleanIdents[True]) then
I := -1
else
I := StrToInt(Value);
SetOrdValue(I);
end;
}
{ TInt64Property }
function TInt64Property.AllEqual: Boolean;
var
I: Integer;
V: Int64;
begin
Result := False;
if PropCount > 1 then
begin
V := GetInt64Value;
for I := 1 to PropCount - 1 do
if GetInt64ValueAt(I) <> V then Exit;
end;
Result := True;
end;
function TInt64Property.GetEditLimit: Integer;
begin
Result := 63;
end;
function TInt64Property.GetValue: string;
begin
Result := IntToStr(GetInt64Value);
end;
procedure TInt64Property.SetValue(const Value: string);
begin
SetInt64Value(StrToInt64(Value));
end;
{ TFloatProperty }
function TFloatProperty.AllEqual: Boolean;
var
I: Integer;
V: Extended;
begin
Result := False;
if PropCount > 1 then
begin
V := GetFloatValue;
for I := 1 to PropCount - 1 do
if GetFloatValueAt(I) <> V then Exit;
end;
Result := True;
end;
function TFloatProperty.GetValue: string;
const
Precisions: array[TFloatType] of Integer = (7, 15, 18, 18, 18);
begin
Result := FloatToStrF(GetFloatValue, ffGeneral,
Precisions[GetTypeData(GetPropType)^.FloatType], 0);
end;
procedure TFloatProperty.SetValue(const Value: string);
begin
SetFloatValue(StrToFloat(Value));
end;
{ TStringProperty }
function TStringProperty.AllEqual: Boolean;
var
I: Integer;
V: string;
begin
Result := False;
if PropCount > 1 then
begin
V := GetStrValue;
for I := 1 to PropCount - 1 do
if GetStrValueAt(I) <> V then Exit;
end;
Result := True;
end;
function TStringProperty.GetEditLimit: Integer;
begin
if GetPropType^.Kind = tkString then
Result := GetTypeData(GetPropType)^.MaxLength
else
Result := 255;
end;
function TStringProperty.GetValue: string;
begin
Result := GetStrValue;
end;
procedure TStringProperty.SetValue(const Value: string);
begin
SetStrValue(Value);
end;
{ TComponentNameProperty }
function TComponentNameProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paNotNestable];
end;
function TComponentNameProperty.GetEditLimit: Integer;
begin
Result := MaxIdentLength;
end;
{ TNestedProperty }
constructor TNestedProperty.Create(Parent: TPropertyEditor);
begin
FDesigner := Parent.Designer;
FPropList := Parent.FPropList;
FPropCount := Parent.PropCount;
end;
destructor TNestedProperty.Destroy;
begin
end;
{ TSetElementProperty }
constructor TSetElementProperty.Create(Parent: TPropertyEditor; AElement: Integer);
begin
inherited Create(Parent);
FElement := AElement;
end;
function TSetElementProperty.AllEqual: Boolean;
var
I: Integer;
S: TIntegerSet;
V: Boolean;
begin
Result := False;
if PropCount > 1 then
begin
Integer(S) := GetOrdValue;
V := FElement in S;
for I := 1 to PropCount - 1 do
begin
Integer(S) := GetOrdValueAt(I);
if (FElement in S) <> V then Exit;
end;
end;
Result := True;
end;
function TSetElementProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList];
end;
function TSetElementProperty.GetName: string;
begin
Result := GetEnumName(GetTypeData(GetPropType)^.CompType^, FElement);
end;
function TSetElementProperty.GetValue: string;
var
S: TIntegerSet;
begin
Integer(S) := GetOrdValue;
Result := BooleanIdents[FElement in S];
end;
procedure TSetElementProperty.GetValues(Proc: TGetStrProc);
begin
Proc(BooleanIdents[False]);
Proc(BooleanIdents[True]);
end;
procedure TSetElementProperty.SetValue(const Value: string);
var
S: TIntegerSet;
begin
Integer(S) := GetOrdValue;
if CompareText(Value, BooleanIdents[True]) = 0 then
Include(S, FElement)
else
Exclude(S, FElement);
SetOrdValue(Integer(S));
end;
{ TSetProperty }
function TSetProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paSubProperties, paReadOnly, paRevertable];
end;
procedure TSetProperty.GetProperties(Proc: TGetPropProc);
var
I: Integer;
begin
with GetTypeData(GetTypeData(GetPropType)^.CompType^)^ do
for I := MinValue to MaxValue do
Proc(TSetElementProperty.Create(Self, I));
end;
function TSetProperty.GetValue: string;
var
S: TIntegerSet;
TypeInfo: PTypeInfo;
I: Integer;
begin
Integer(S) := GetOrdValue;
TypeInfo := GetTypeData(GetPropType)^.CompType^;
Result := '[';
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Length(Result) <> 1 then Result := Result + ',';
Result := Result + GetEnumName(TypeInfo, I);
end;
Result := Result + ']';
end;
{ TClassProperty }
function TClassProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paSubProperties, paReadOnly];
end;
procedure TClassProperty.GetProperties(Proc: TGetPropProc);
var
I: Integer;
J: Integer;
Components: IDesignerSelections;
begin
Components := TDesignerSelections.Create;
for I := 0 to PropCount - 1 do
begin
J := GetOrdValueAt(I);
if J <> 0 then
Components.Add(TComponent(GetOrdValueAt(I)));
end;
if Components.Count > 0 then
GetComponentProperties(Components, tkProperties, Designer, Proc);
end;
function TClassProperty.GetValue: string;
begin
FmtStr(Result, '(%s)', [GetPropType^.Name]);
end;
{ TComponentProperty }
procedure TComponentProperty.Edit;
var
Temp: TComponent;
begin
if (Designer.GetShiftState * [ssCtrl, ssLeft] = [ssCtrl, ssLeft]) then
begin
Temp := GetComponentReference;
if Temp <> nil then
Designer.SelectComponent(Temp)
else
inherited Edit;
end
else
inherited Edit;
end;
function TComponentProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect];
if Assigned(GetPropInfo^.SetProc) then
Result := Result + [paValueList, paSortList, paRevertable]
else
Result := Result + [paReadOnly];
if GReferenceExpandable and (GetComponentReference <> nil) and AllEqual then
Result := Result + [paSubProperties, paVolatileSubProperties];
end;
function TComponentProperty.GetSelections: IDesignerSelections;
var
I: Integer;
begin
Result := nil;
if (GetComponentReference <> nil) and AllEqual then
begin
Result := TDesignerSelections.Create;
for I := 0 to PropCount - 1 do
Result.Add(TComponent(GetOrdValueAt(I)));
end;
end;
procedure TComponentProperty.GetProperties(Proc: TGetPropProc);
var
LComponents: IDesignerSelections;
LDesigner: IDesigner;
begin
LComponents := GetSelections;
if LComponents <> nil then
begin
if not Supports(FindRootDesigner(LComponents[0]), IDesigner, LDesigner) then
LDesigner := Designer;
GetComponentProperties(LComponents, tkAny, LDesigner, Proc, FilterFunc);
end;
end;
function TComponentProperty.GetEditLimit: Integer;
begin
Result := 127;
end;
function TComponentProperty.GetValue: string;
begin
Result := Designer.GetComponentName(GetComponentReference);
end;
procedure TComponentProperty.GetValues(Proc: TGetStrProc);
begin
Designer.GetComponentNames(GetTypeData(GetPropType), Proc);
end;
procedure TComponentProperty.SetValue(const Value: string);
var
Component: TComponent;
begin
if Value = '' then
Component := nil
else
begin
Component := Designer.GetComponent(Value);
if not (Component is GetTypeData(GetPropType)^.ClassType) then
raise EPropertyError.CreateRes(@SInvalidPropertyValue);
end;
SetOrdValue(LongInt(Component));
end;
function TComponentProperty.AllEqual: Boolean;
var
I: Integer;
LInstance: TComponent;
begin
Result := False;
LInstance := TComponent(GetOrdValue);
if PropCount > 1 then
for I := 1 to PropCount - 1 do
if TComponent(GetOrdValueAt(I)) <> LInstance then
Exit;
Result := Supports(FindRootDesigner(LInstance), IDesigner);
end;
function TComponentProperty.GetComponentReference: TComponent;
begin
Result := TComponent(GetOrdValue);
end;
function TComponentProperty.FilterFunc(const ATestEditor: IProperty): Boolean;
begin
Result := not (paNotNestable in ATestEditor.GetAttributes);
end;
{ TInterfaceProperty }
function TInterfaceProperty.AllEqual: Boolean;
var
I: Integer;
LInterface: IInterface;
begin
Result := False;
LInterface := GetIntfValue;
if PropCount > 1 then
for I := 1 to PropCount - 1 do
if GetIntfValueAt(I) <> LInterface then
Exit;
Result := Supports(FindRootDesigner(GetComponent(LInterface)), IDesigner);
end;
function TInterfaceProperty.GetComponent(const AInterface: IInterface): TComponent;
var
ICR: IInterfaceComponentReference;
begin
if (AInterface <> nil) and
Supports(AInterface, IInterfaceComponentReference, ICR) then
Result := ICR.GetComponent
else
Result := nil;
end;
function TInterfaceProperty.GetComponentReference: TComponent;
begin
Result := GetComponent(GetIntfValue);
end;
function TInterfaceProperty.GetSelections: IDesignerSelections;
var
I: Integer;
begin
Result := nil;
if (GetIntfValue <> nil) and AllEqual then
begin
Result := TDesignerSelections.Create;
for I := 0 to PropCount - 1 do
Result.Add(GetComponent(GetIntfValueAt(I)));
end;
end;
procedure TInterfaceProperty.ReceiveComponentNames(const S: string);
var
Temp: TComponent;
Intf: IInterface;
begin
Temp := Designer.GetComponent(S);
if Assigned(FGetValuesStrProc) and
Assigned(Temp) and
Supports(TObject(Temp), GetTypeData(GetPropType)^.Guid, Intf) then
FGetValuesStrProc(S);
end;
procedure TInterfaceProperty.GetValues(Proc: TGetStrProc);
begin
FGetValuesStrProc := Proc;
try
Designer.GetComponentNames(GetTypeData(TypeInfo(TComponent)), ReceiveComponentNames);
finally
FGetValuesStrProc := nil;
end;
end;
procedure TInterfaceProperty.SetValue(const Value: string);
var
Intf: IInterface;
Component: TComponent;
begin
if Value = '' then
Intf := nil
else
begin
Component := Designer.GetComponent(Value);
if (Component = nil) or
not Supports(TObject(Component), GetTypeData(GetPropType)^.Guid, Intf) then
raise EPropertyError.CreateRes(@SInvalidPropertyValue);
end;
SetIntfValue(Intf);
end;
{ TMethodProperty }
function TMethodProperty.AllEqual: Boolean;
var
I: Integer;
V, T: TMethod;
begin
Result := False;
if PropCount > 1 then
begin
V := GetMethodValue;
for I := 1 to PropCount - 1 do
begin
T := GetMethodValueAt(I);
if (T.Code <> V.Code) or (T.Data <> V.Data) then Exit;
end;
end;
Result := True;
end;
function TMethodProperty.AllNamed: Boolean;
var
I: Integer;
begin
Result := True;
for I := 0 to PropCount - 1 do
if GetComponent(I).GetNamePath = '' then
begin
Result := False;
Break;
end;
end;
procedure TMethodProperty.Edit;
var
FormMethodName: string;
begin
if not AllNamed then
raise EPropertyError.CreateRes(@SCannotCreateName);
FormMethodName := GetValue;
if (FormMethodName = '') or
Designer.MethodFromAncestor(GetMethodValue) then
begin
if FormMethodName = '' then
FormMethodName := GetFormMethodName;
if FormMethodName = '' then
raise EPropertyError.CreateRes(@SCannotCreateName);
SetValue(FormMethodName);
end;
Designer.ShowMethod(FormMethodName);
end;
function TMethodProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList, paRevertable];
end;
function TMethodProperty.GetEditLimit: Integer;
begin
Result := MaxIdentLength;
end;
function TMethodProperty.GetFormMethodName: string;
var
I: Integer;
begin
if GetComponent(0) = Designer.GetRoot then
begin
Result := Designer.GetRootClassName;
if (Result <> '') and (Result[1] = 'T') then
Delete(Result, 1, 1);
end
else
begin
Result := Designer.GetObjectName(GetComponent(0));
for I := Length(Result) downto 1 do
if Result[I] in ['.', '[', ']', '-', '>'] then
Delete(Result, I, 1);
end;
if Result = '' then
raise EPropertyError.CreateRes(@SCannotCreateName);
Result := Result + GetTrimmedEventName;
end;
function TMethodProperty.GetTrimmedEventName: string;
begin
Result := GetName;
if (Length(Result) >= 2) and
(Result[1] in ['O', 'o']) and (Result[2] in ['N', 'n']) then
Delete(Result,1,2);
end;
function TMethodProperty.GetValue: string;
begin
Result := Designer.GetMethodName(GetMethodValue);
end;
procedure TMethodProperty.GetValues(Proc: TGetStrProc);
begin
Designer.GetMethods(GetTypeData(GetPropType), Proc);
end;
procedure TMethodProperty.SetValue(const AValue: string);
procedure CheckChainCall(const MethodName: string; Method: TMethod);
var
Persistent: TPersistent;
Component: TComponent;
InstanceMethod: string;
Instance: TComponent;
begin
Persistent := GetComponent(0);
if Persistent is TComponent then
begin
Component := TComponent(Persistent);
if (Component.Name <> '') and (Method.Data <> Designer.GetRoot) and
(TObject(Method.Data) is TComponent) then
begin
Instance := TComponent(Method.Data);
InstanceMethod := Instance.MethodName(Method.Code);
if InstanceMethod <> '' then
Designer.ChainCall(MethodName, Instance.Name, InstanceMethod,
GetTypeData(GetPropType));
end;
end;
end;
var
NewMethod: Boolean;
CurValue: string;
OldMethod: TMethod;
begin
if not AllNamed then
raise EPropertyError.CreateRes(@SCannotCreateName);
CurValue:= GetValue;
if (CurValue <> '') and (AValue <> '') and (SameText(CurValue, AValue) or
not Designer.MethodExists(AValue)) and not Designer.MethodFromAncestor(GetMethodValue) then
Designer.RenameMethod(CurValue, AValue)
else
begin
NewMethod := (AValue <> '') and not Designer.MethodExists(AValue);
OldMethod := GetMethodValue;
SetMethodValue(Designer.CreateMethod(AValue, GetTypeData(GetPropType)));
if NewMethod then
begin
if (PropCount = 1) and (OldMethod.Data <> nil) and (OldMethod.Code <> nil) then
CheckChainCall(AValue, OldMethod);
Designer.ShowMethod(AValue);
end;
end;
end;
{ TDateProperty }
function TDateProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paRevertable];
end;
function TDateProperty.GetValue: string;
var
DT: TDateTime;
begin
DT := GetFloatValue;
if DT = 0.0 then Result := '' else
Result := DateToStr(DT);
end;
procedure TDateProperty.SetValue(const Value: string);
var
DT: TDateTime;
begin
if Value = '' then DT := 0.0
else DT := StrToDate(Value);
SetFloatValue(DT);
end;
{ TTimeProperty }
function TTimeProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paRevertable];
end;
function TTimeProperty.GetValue: string;
var
DT: TDateTime;
begin
DT := GetFloatValue;
if DT = 0.0 then Result := '' else
Result := TimeToStr(DT);
end;
procedure TTimeProperty.SetValue(const Value: string);
var
DT: TDateTime;
begin
if Value = '' then DT := 0.0
else DT := StrToTime(Value);
SetFloatValue(DT);
end;
{ TDateTimeProperty }
function TDateTimeProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paRevertable];
end;
function TDateTimeProperty.GetValue: string;
var
DT: TDateTime;
begin
DT := GetFloatValue;
if DT = 0.0 then Result := '' else
Result := DateTimeToStr(DT);
end;
procedure TDateTimeProperty.SetValue(const Value: string);
var
DT: TDateTime;
begin
if Value = '' then DT := 0.0
else DT := StrToDateTime(Value);
SetFloatValue(DT);
end;
{ TPropInfoList }
type
TPropInfoList = class
private
FList: PPropList;
FCount: Integer;
FSize: Integer;
function Get(Index: Integer): PPropInfo;
public
constructor Create(Instance: TPersistent; Filter: TTypeKinds);
destructor Destroy; override;
function Contains(P: PPropInfo): Boolean;
procedure Delete(Index: Integer);
procedure Intersect(List: TPropInfoList);
property Count: Integer read FCount;
property Items[Index: Integer]: PPropInfo read Get; default;
end;
constructor TPropInfoList.Create(Instance: TPersistent; Filter: TTypeKinds);
begin
FCount := GetPropList(Instance.ClassInfo, Filter, nil);
FSize := FCount * SizeOf(Pointer);
GetMem(FList, FSize);
GetPropList(Instance.ClassInfo, Filter, FList);
end;
destructor TPropInfoList.Destroy;
begin
if FList <> nil then FreeMem(FList, FSize);
end;
function TPropInfoList.Contains(P: PPropInfo): Boolean;
var
I: Integer;
begin
for I := 0 to FCount - 1 do
with FList^[I]^ do
if (PropType^ = P^.PropType^) and (CompareText(Name, P^.Name) = 0) then
begin
Result := True;
Exit;
end;
Result := False;
end;
procedure TPropInfoList.Delete(Index: Integer);
begin
Dec(FCount);
if Index < FCount then
Move(FList^[Index + 1], FList^[Index],
(FCount - Index) * SizeOf(Pointer));
end;
function TPropInfoList.Get(Index: Integer): PPropInfo;
begin
Result := FList^[Index];
end;
procedure TPropInfoList.Intersect(List: TPropInfoList);
var
I: Integer;
begin
for I := FCount - 1 downto 0 do
if not List.Contains(FList^[I]) then Delete(I);
end;
function InterfaceInheritsFrom(Child, Parent: PTypeData): Boolean;
begin
while (Child <> nil) and (Child <> Parent) and (Child^.IntfParent <> nil) do
Child := GetTypeData(Child^.IntfParent^);
Result := (Child <> nil) and (Child = Parent);
end;
{ Property Editor registration }
type
PPropertyClassRec = ^TPropertyClassRec;
TPropertyClassRec = record
Group: Integer;
PropertyType: PTypeInfo;
PropertyName: string;
ComponentClass: TClass;
ClassGroup: TPersistentClass;
EditorClass: TPropertyEditorClass;
end;
PPropertyMapperRec = ^TPropertyMapperRec;
TPropertyMapperRec = record
Group: Integer;
Mapper: TPropertyMapperFunc;
end;
const
PropClassMap: array[TypInfo.TTypeKind] of TPropertyEditorClass = (
nil, // tkUnknown
TIntegerProperty, // tkInteger
TCharProperty, // tkChar
TEnumProperty, // tkEnumeration
TFloatProperty, // tkFloat
TStringProperty, // tkString
TSetProperty, // tkSet
TClassProperty, // tkClass
TMethodProperty, // tkMethod
TPropertyEditor, // tkWChar
TStringProperty, // tkLString
TStringProperty, // tkWString
TVariantProperty, // tkVariant
nil, // tkArray
nil, // tkRecord
TInterfaceProperty, // tkInterface
TInt64Property, // tkInt64
nil); // tkDynArray
var
PropertyClassList: TList;
PropertyMapperList: TList = nil;
procedure RegisterPropertyEditor(PropertyType: PTypeInfo; ComponentClass: TClass;
const PropertyName: string; EditorClass: TPropertyEditorClass);
var
P: PPropertyClassRec;
begin
if PropertyClassList = nil then
PropertyClassList := TList.Create;
New(P);
P.Group := CurrentGroup;
P.PropertyType := PropertyType;
P.ComponentClass := ComponentClass;
P.PropertyName := '';
P.ClassGroup := nil;
if Assigned(ComponentClass) then P^.PropertyName := PropertyName;
P.EditorClass := EditorClass;
PropertyClassList.Insert(0, P);
end;
procedure SetPropertyEditorGroup(EditorClass: TPropertyEditorClass;
GroupClass: TPersistentClass);
var
P: PPropertyClassRec;
I: Integer;
begin
for I := 0 to PropertyClassList.Count - 1 do
begin
P := PropertyClassList[I];
if P^.EditorClass = EditorClass then
begin
P^.ClassGroup := ClassGroupOf(GroupClass);
Exit;
end;
end;
// Ignore it if the EditorClass is not found.
end;
function GetEditorClass(PropInfo: PPropInfo;
Obj: TPersistent): TPropertyEditorClass;
var
PropType: PTypeInfo;
P, C: PPropertyClassRec;
I: Integer;
begin
if PropertyMapperList <> nil then
begin
for I := 0 to PropertyMapperList.Count -1 do
with PPropertyMapperRec(PropertyMapperList[I])^ do
begin
Result := Mapper(Obj, PropInfo);
if Result <> nil then Exit;
end;
end;
PropType := PropInfo^.PropType^;
I := 0;
C := nil;
while I < PropertyClassList.Count do
begin
P := PropertyClassList[I];
if ( (P^.PropertyType = PropType) {or
((P^.PropertyType^.Kind = PropType.Kind) and
(P^.PropertyType^.Name = PropType.Name)
)}
) or // compatible class type
( (PropType^.Kind = tkClass) and
(P^.PropertyType^.Kind = tkClass) and
GetTypeData(PropType)^.ClassType.InheritsFrom(GetTypeData(P^.PropertyType)^.ClassType)
) or // compatible interface type
( (PropType^.Kind = tkInterface) and
(P^.PropertyType^.Kind = tkInterface) and
InterfaceInheritsFrom(GetTypeData(PropType), GetTypeData(P^.PropertyType))
) then
if ((P^.ComponentClass = nil) or (Obj.InheritsFrom(P^.ComponentClass))) and
((P^.ClassGroup = nil) or (P^.ClassGroup = ClassGroupOf(Obj))) and
((P^.PropertyName = '') or (CompareText(PropInfo^.Name, P^.PropertyName) = 0)) then
if (C = nil) or // see if P is better match than C
((C^.ComponentClass = nil) and (P^.ComponentClass <> nil)) or
((C^.PropertyName = '') and (P^.PropertyName <> ''))
or // P's proptype match is exact, but C's isn't
((C^.PropertyType <> PropType) and (P^.PropertyType = PropType))
or // P's proptype is more specific than C's proptype
( (P^.PropertyType <> C^.PropertyType) and
( ( // P has a more specific class type than C.
(P^.PropertyType^.Kind = tkClass) and
(C^.PropertyType^.Kind = tkClass) and
GetTypeData(P^.PropertyType)^.ClassType.InheritsFrom(
GetTypeData(C^.PropertyType)^.ClassType)
) or // P has a more specific interface type than C.
( (P^.PropertyType^.Kind = tkInterface) and
(C^.PropertyType^.Kind = tkInterface) and
InterfaceInheritsFrom(GetTypeData(P^.PropertyType), GetTypeData(C^.PropertyType))
)
)
) or // P's component class is more specific than C's component class
( (P^.ComponentClass <> nil) and (C^.ComponentClass <> nil) and
(P^.ComponentClass <> C^.ComponentClass) and
(P^.ComponentClass.InheritsFrom(C^.ComponentClass))
) then
C := P;
Inc(I);
end;
if C <> nil then
Result := C^.EditorClass else
Result := PropClassMap[PropType^.Kind];
end;
procedure GetComponentProperties(const Components: IDesignerSelections;
Filter: TTypeKinds; const Designer: IDesigner; Proc: TGetPropProc;
EditorFilterFunc: TPropertyEditorFilterFunc);
var
I, J, CompCount: Integer;
CompType: TClass;
Candidates: TPropInfoList;
PropLists: TList;
EditorInstance: TBasePropertyEditor;
Editor: IProperty;
EdClass: TPropertyEditorClass;
PropInfo: PPropInfo;
AddEditor: Boolean;
Obj: TPersistent;
begin
if (Components = nil) or (Components.Count = 0) then Exit;
CompCount := Components.Count;
Obj := Components[0];
CompType := Components[0].ClassType;
// Create a property candidate list
Candidates := TPropInfoList.Create(Components[0], Filter);
try
for I := Candidates.Count - 1 downto 0 do
begin
PropInfo := Candidates[I];
EdClass := GetEditorClass(PropInfo, Obj);
if EdClass = nil then
Candidates.Delete(I)
else
begin
EditorInstance := EdClass.Create(Designer, 1);
Editor := EditorInstance as IProperty;
TPropertyEditor(EditorInstance).SetPropEntry(0, Components[0], PropInfo);
TPropertyEditor(EditorInstance).Initialize;
with PropInfo^ do
if (GetProc = nil) or
(not GShowReadOnlyProps and
((PropType^.Kind <> tkClass) and
(SetProc = nil))) or
((CompCount > 1) and
not (paMultiSelect in Editor.GetAttributes)) or
not Editor.ValueAvailable or
(Assigned(EditorFilterFunc) and not EditorFilterFunc(Editor)) then
Candidates.Delete(I);
end;
end;
PropLists := TList.Create;
try
PropLists.Capacity := CompCount;
// Create a property list for each component in the selection
for I := 0 to CompCount - 1 do
PropLists.Add(TPropInfoList.Create(Components[I], Filter));
// Eliminate each property in Candidates that is not in all property list
for I := 0 to CompCount - 1 do
Candidates.Intersect(TPropInfoList(PropLists[I]));
// Eliminate each property in the property list that are not in Candidates
for I := 0 to CompCount - 1 do
TPropInfoList(PropLists[I]).Intersect(Candidates);
// PropList now has a matrix of PropInfo's, create property editors for
// each property with given each the array of PropInfos
for I := 0 to Candidates.Count - 1 do
begin
EdClass := GetEditorClass(Candidates[I], Obj);
if EdClass = nil then Continue;
EditorInstance := EdClass.Create(Designer, CompCount);
Editor := EditorInstance as IProperty;
AddEditor := True;
for J := 0 to CompCount - 1 do
begin
if (Components[J].ClassType <> CompType) and
(GetEditorClass(TPropInfoList(PropLists[J])[I],
Components[J]) <> EdClass) then
begin
AddEditor := False;
Break;
end;
TPropertyEditor(EditorInstance).SetPropEntry(J, Components[J],
TPropInfoList(PropLists[J])[I]);
end;
if AddEditor then
begin
TPropertyEditor(EditorInstance).Initialize;
if Editor.ValueAvailable then Proc(Editor);
end;
end;
finally
for I := 0 to PropLists.Count - 1 do TPropInfoList(PropLists[I]).Free;
PropLists.Free;
end;
finally
Candidates.Free;
end;
end;
procedure RegisterPropertyMapper(Mapper: TPropertyMapperFunc);
var
P: PPropertyMapperRec;
begin
if PropertyMapperList = nil then
PropertyMapperList := TList.Create;
New(P);
P^.Group := CurrentGroup;
P^.Mapper := Mapper;
PropertyMapperList.Insert(0, P);
end;
{ Component Editors }
{ TComponentEditor }
constructor TComponentEditor.Create(AComponent: TComponent; ADesigner: IDesigner);
begin
inherited Create(AComponent, ADesigner);
FComponent := AComponent;
FDesigner := ADesigner;
end;
procedure TComponentEditor.Edit;
begin
if GetVerbCount > 0 then ExecuteVerb(0);
end;
function TComponentEditor.GetComponent: TComponent;
begin
Result := FComponent;
end;
function TComponentEditor.GetDesigner: IDesigner;
begin
Result := FDesigner;
end;
function TComponentEditor.GetVerbCount: Integer;
begin
// Intended for descendents to implement
Result := 0;
end;
function TComponentEditor.GetVerb(Index: Integer): string;
begin
// Intended for descendents to implement
end;
procedure TComponentEditor.ExecuteVerb(Index: Integer);
begin
// Intended for descendents to implement
end;
procedure TComponentEditor.Copy;
begin
// Intended for descendents to implement
end;
function TComponentEditor.IsInInlined: Boolean;
begin
Result := csInline in Component.Owner.ComponentState;
end;
procedure TComponentEditor.PrepareItem(Index: Integer;
const AItem: IMenuItem);
begin
// Intended for descendents to implement
end;
{ TDefaultEditor }
procedure TDefaultEditor.CheckEdit(const Prop: IProperty);
begin
if FContinue then
EditProperty(Prop, FContinue);
end;
procedure TDefaultEditor.EditProperty(const Prop: IProperty;
var Continue: Boolean);
var
PropName: string;
BestName: string;
MethodProperty: IMethodProperty;
procedure ReplaceBest;
begin
FBest := Prop;
if FFirst = FBest then FFirst := nil;
end;
begin
if not Assigned(FFirst) and
Supports(Prop, IMethodProperty, MethodProperty) then
FFirst := Prop;
PropName := Prop.GetName;
BestName := '';
if Assigned(FBest) then BestName := FBest.GetName;
if CompareText(PropName, 'ONCREATE') = 0 then
ReplaceBest
else if CompareText(BestName, 'ONCREATE') <> 0 then
if CompareText(PropName, 'ONCHANGE') = 0 then
ReplaceBest
else if CompareText(BestName, 'ONCHANGE') <> 0 then
if CompareText(PropName, 'ONCLICK') = 0 then
ReplaceBest;
end;
procedure TDefaultEditor.Edit;
var
Components: IDesignerSelections;
begin
Components := TDesignerSelections.Create;
FContinue := True;
Components.Add(Component);
FFirst := nil;
FBest := nil;
try
GetComponentProperties(Components, tkAny, Designer, CheckEdit);
if FContinue then
if Assigned(FBest) then
FBest.Edit
else if Assigned(FFirst) then
FFirst.Edit;
finally
FFirst := nil;
FBest := nil;
end;
end;
{ RegisterComponentEditor }
type
PComponentClassRec = ^TComponentClassRec;
TComponentClassRec = record
Group: Integer;
ComponentClass: TComponentClass;
EditorClass: TComponentEditorClass;
end;
var
ComponentClassList: TList = nil;
procedure RegisterComponentEditor(ComponentClass: TComponentClass;
ComponentEditor: TComponentEditorClass);
var
P: PComponentClassRec;
begin
if ComponentClassList = nil then
ComponentClassList := TList.Create;
New(P);
P.Group := CurrentGroup;
P.ComponentClass := ComponentClass;
P.EditorClass := ComponentEditor;
ComponentClassList.Insert(0, P);
end;
{ GetComponentEditor }
function GetComponentEditor(Component: TComponent;
const Designer: IDesigner): IComponentEditor;
var
P: PComponentClassRec;
I: Integer;
ComponentClass: TComponentClass;
EditorClass: TComponentEditorClass;
begin
ComponentClass := TComponentClass(TPersistent);
EditorClass := TDefaultEditor;
if ComponentClassList <> nil then
for I := 0 to ComponentClassList.Count-1 do
begin
P := ComponentClassList[I];
if (Component is P^.ComponentClass) and
(P^.ComponentClass <> ComponentClass) and
(P^.ComponentClass.InheritsFrom(ComponentClass)) then
begin
EditorClass := P^.EditorClass;
ComponentClass := P^.ComponentClass;
end;
end;
Result := EditorClass.Create(Component, Designer) as IComponentEditor;
end;
{ TSelectionEditor }
constructor TSelectionEditor.Create(const ADesigner: IDesigner);
begin
inherited Create(ADesigner);
FDesigner := ADesigner;
end;
procedure TSelectionEditor.ExecuteVerb(Index: Integer; const List: IDesignerSelections);
begin
// Intended for descendents to implement
end;
function TSelectionEditor.GetVerb(Index: Integer): string;
begin
// Intended for descendents to implement
Result := '';
end;
function TSelectionEditor.GetVerbCount: Integer;
begin
// Intended for descendents to implement
Result := 0;
end;
procedure TSelectionEditor.RequiresUnits(Proc: TGetStrProc);
begin
// No implementation needed (see description in DesignIntf)
end;
procedure TSelectionEditor.PrepareItem(Index: Integer;
const AItem: IMenuItem);
begin
// Intended for descendents to implement
end;
type
TSelectionEditorList = class(TInterfacedObject, ISelectionEditorList)
private
FList: IInterfaceList;
protected
procedure Add(AEditor: ISelectionEditor);
public
constructor Create;
function Get(Index: Integer): ISelectionEditor;
function GetCount: Integer;
property Count: Integer read GetCount;
property Items[Index: Integer]: ISelectionEditor read Get; default;
end;
{ TSelectionEditorList }
procedure TSelectionEditorList.Add(AEditor: ISelectionEditor);
begin
FList.Add(AEditor);
end;
constructor TSelectionEditorList.Create;
begin
inherited;
FList := TInterfaceList.Create;
end;
function TSelectionEditorList.Get(Index: Integer): ISelectionEditor;
begin
Result := FList[Index] as ISelectionEditor;
end;
function TSelectionEditorList.GetCount: Integer;
begin
Result := FList.Count;
end;
type
TSelectionEditorDefinition = class(TObject)
private
FGroup: Integer;
FClass: TClass;
FEditor: TSelectionEditorClass;
public
constructor Create(AClass: TClass; AEditor: TSelectionEditorClass);
function Matches(AClass: TClass): Boolean;
property Editor: TSelectionEditorClass read FEditor;
end;
TSelectionEditorDefinitionList = class(TObjectList)
protected
function GetItem(Index: Integer): TSelectionEditorDefinition;
procedure SetItem(Index: Integer; AObject: TSelectionEditorDefinition);
procedure FreeEditorGroup(AGroup: Integer);
public
property Items[Index: Integer]: TSelectionEditorDefinition read GetItem write SetItem; default;
end;
{ TSelectionEditorDefinition }
constructor TSelectionEditorDefinition.Create(AClass: TClass;
AEditor: TSelectionEditorClass);
begin
inherited Create;
FGroup := CurrentGroup;
FClass := AClass;
FEditor := AEditor;
end;
function TSelectionEditorDefinition.Matches(AClass: TClass): Boolean;
begin
Result := AClass.InheritsFrom(FClass);
end;
{ TSelectionEditorDefinitionList }
procedure TSelectionEditorDefinitionList.FreeEditorGroup(AGroup: Integer);
var
I: Integer;
begin
for I := Count - 1 downto 0 do
if Items[I].FGroup = AGroup then
Delete(I);
end;
function TSelectionEditorDefinitionList.GetItem(Index: Integer): TSelectionEditorDefinition;
begin
Result := TSelectionEditorDefinition(inherited Items[Index]);
end;
procedure TSelectionEditorDefinitionList.SetItem(Index: Integer;
AObject: TSelectionEditorDefinition);
begin
inherited Items[Index] := AObject;
end;
var
SelectionEditorDefinitionList: TSelectionEditorDefinitionList;
procedure RegisterSelectionEditor(AClass: TClass; AEditor: TSelectionEditorClass);
begin
if not Assigned(SelectionEditorDefinitionList) then
SelectionEditorDefinitionList := TSelectionEditorDefinitionList.Create;
SelectionEditorDefinitionList.Add(TSelectionEditorDefinition.Create(AClass, AEditor));
end;
function GetSelectionEditors(const Designer: IDesigner;
const Selections: IDesignerSelections): ISelectionEditorList; overload;
var
LList: TSelectionEditorList;
I: Integer;
LCommonClass, LClass: TClass;
begin
// either way we return this
LList := TSelectionEditorList.Create;
Result := LList as ISelectionEditorList;
// find out who qualifies
if Selections.Count > 0 then
begin
// grab the first class
LCommonClass := Selections[0].ClassType;
// now look for the common class
for I := 1 to Selections.Count - 1 do
begin
LClass := Selections[I].ClassType;
while LCommonClass <> TObject do
if not LClass.InheritsFrom(LCommonClass) then
LCommonClass := LCommonClass.ClassParent
else
Break;
end;
// now which selection editors qualify?
for I := 0 to SelectionEditorDefinitionList.Count - 1 do
if SelectionEditorDefinitionList[I].Matches(LCommonClass) then
LList.Add(SelectionEditorDefinitionList[I].Editor.Create(Designer) as ISelectionEditor);
end;
end;
function GetSelectionEditors(const Designer: IDesigner): ISelectionEditorList;
var
LSelections: IDesignerSelections;
begin
// what is selected?
LSelections := TDesignerSelections.Create;
Designer.GetSelections(LSelections);
Result := GetSelectionEditors(Designer, LSelections);
end;
function GetSelectionEditors(const Designer: IDesigner;
Component: TComponent): ISelectionEditorList;
var
LSelections: IDesignerSelections;
begin
LSelections := TDesignerSelections.Create;
LSelections.Add(Component);
Result := GetSelectionEditors(Designer, LSelections);
end;
{ TCustomModule }
constructor TCustomModule.Create(ARoot: TComponent; const ADesigner: IDesigner);
begin
inherited Create(ARoot, ADesigner);
FRoot := ARoot;
FDesigner := ADesigner;
end;
destructor TCustomModule.Destroy;
begin
FFinder.Free;
inherited;
end;
procedure TCustomModule.ExecuteVerb(Index: Integer);
begin
// Intended for descendents to implement
end;
function TCustomModule.GetAttributes: TCustomModuleAttributes;
begin
Result := [];
end;
function TCustomModule.GetVerb(Index: Integer): string;
begin
// Intended for descendents to implement
Result := '';
end;
function TCustomModule.GetVerbCount: Integer;
begin
// Intended for descendents to implement
Result := 0;
end;
function TCustomModule.Nestable: Boolean;
begin
Result := False;
end;
procedure TCustomModule.PrepareItem(Index: Integer;
const AItem: IMenuItem);
begin
// Intended for descendents to implement
end;
procedure TCustomModule.Saving;
begin
// Intended for descendents to implement
end;
procedure TCustomModule.ValidateComponent(Component: TComponent);
begin
if not ValidateComponentClass(TComponentClass(Component.ClassType)) then
raise Exception.CreateResFmt(@sClassNotApplicable, [Component.ClassName]);
end;
function TCustomModule.ValidateComponentClass(ComponentClass: TComponentClass): Boolean;
var
Base: TComponent;
begin
if FFinder = nil then
begin
Base := Root;
if Base.Owner <> nil then
// If the root has an owner then we want to find classes in the owners
// class group not just the root's. This represents what will be active
// when the class is loaded at runtime.
Base := Base.Owner;
FFinder := TClassFinder.Create(TPersistentClass(Base.ClassType));
end;
while IsProxyClass(ComponentClass) do
ComponentClass := TComponentClass(ComponentClass.ClassParent);
// We should only accept classes that are the same as the streaming system
// will see.
Result := FFinder.GetClass(ComponentClass.ClassName) = ComponentClass;
end;
function ClassInheritsFrom(ClassType: TClass; const ClassName: string): Boolean;
begin
Result := True;
while ClassType <> nil do
if ClassType.ClassNameIs(ClassName) then
Exit
else
ClassType := ClassType.ClassParent;
Result := False;
end;
function AncestorNameMatches(ClassType: TClass; AncestorClass: TClass): Boolean;
begin
Result := ClassType.InheritsFrom(AncestorClass) or
not ClassInheritsFrom(ClassType, AncestorClass.ClassName);
end;
{ package management }
var
GroupNotifyList: TList;
EditorGroupList: TBits;
function NewEditorGroup: Integer;
begin
if EditorGroupList = nil then
EditorGroupList := TBits.Create;
CurrentGroup := EditorGroupList.OpenBit;
EditorGroupList[CurrentGroup] := True;
Result := CurrentGroup;
end;
procedure NotifyGroupChange(AProc: TGroupChangeProc);
begin
UnnotifyGroupChange(AProc);
if not Assigned(GroupNotifyList) then
GroupNotifyList := TList.Create;
GroupNotifyList.Add(@AProc);
end;
procedure UnnotifyGroupChange(AProc: TGroupChangeProc);
begin
if Assigned(GroupNotifyList) then
GroupNotifyList.Remove(@AProc);
end;
procedure FreeEditorGroup(Group: Integer);
var
I: Integer;
P: PPropertyClassRec;
C: PComponentClassRec;
M: PPropertyMapperRec;
SelectionDef: TSelectionEditorDefinition;
begin
// Release all property editors associated with the group
I := PropertyClassList.Count - 1;
while I > -1 do
begin
P := PropertyClassList[I];
if P.Group = Group then
begin
PropertyClassList.Delete(I);
Dispose(P);
end;
Dec(I);
end;
// Release all component editors associated with the group
I := ComponentClassList.Count - 1;
while I > -1 do
begin
C := ComponentClassList[I];
if C.Group = Group then
begin
ComponentClassList.Delete(I);
Dispose(C);
end;
Dec(I);
end;
// Release all property mappers associated with the group
if PropertyMapperList <> nil then
for I := PropertyMapperList.Count-1 downto 0 do
begin
M := PropertyMapperList[I];
if M.Group = Group then
begin
PropertyMapperList.Delete(I);
Dispose(M);
end;
end;
// Release all selection editors associated with the group
if SelectionEditorDefinitionList <> nil then
for I := SelectionEditorDefinitionList.Count-1 downto 0 do
begin
SelectionDef := SelectionEditorDefinitionList[I];
if SelectionDef.FGroup = Group then
SelectionEditorDefinitionList.Delete(I);
end;
// Notify everyone else that have similar registration lists that the group
// is being unloaded.
if Assigned(GroupNotifyList) then
for I := GroupNotifyList.Count - 1 downto 0 do
TGroupChangeProc(GroupNotifyList[I])(Group);
// Free the group ID for use by another group
if (Group >= 0) and (Group < EditorGroupList.Size) then
EditorGroupList[Group] := False;
end;
{ TVariantTypeProperty }
var
VarTypeNames: array[varEmpty..varInt64] of string = (
'Unassigned', // varEmpty
'Null', // varNull
'Smallint', // varSmallint
'Integer', // varInteger
'Single', // varSingle
'Double', // varDouble
'Currency', // varCurrency
'Date', // varDate
'OleStr', // varOleStr
'', // varDispatch
'', // varError
'Boolean', // varBoolean
'', // varVariant
'', // varUnknown
'', // [varDecimal]
'', // [undefined]
'Shortint', // varShortInt
'Byte', // varByte
'Word', // varWord
'LongWord', // varLongWord
'Int64'); // varInt64
type
TVariantTypeProperty = class(TNestedProperty)
public
function AllEqual: Boolean; override;
function GetAttributes: TPropertyAttributes; override;
function GetName: string; override;
function GetValue: string; override;
procedure GetValues(Proc: TGetStrProc); override;
procedure SetValue(const Value: string); override;
end;
function TVariantTypeProperty.AllEqual: Boolean;
var
i: Integer;
V1, V2: Variant;
begin
Result := False;
if PropCount > 1 then
begin
V1 := GetVarValue;
for i := 1 to PropCount - 1 do
begin
V2 := GetVarValueAt(i);
if VarType(V1) <> VarType(V2) then Exit;
end;
end;
Result := True;
end;
function TVariantTypeProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paValueList, paSortList];
end;
function TVariantTypeProperty.GetName: string;
begin
Result := 'Type';
end;
function TVariantTypeProperty.GetValue: string;
begin
case VarType(GetVarValue) and varTypeMask of
Low(VarTypeNames)..High(VarTypeNames):
Result := VarTypeNames[VarType(GetVarValue)];
varString:
Result := SString;
else
Result := SUnknown;
end;
end;
procedure TVariantTypeProperty.GetValues(Proc: TGetStrProc);
var
i: Integer;
begin
for i := 0 to High(VarTypeNames) do
if VarTypeNames[i] <> '' then
Proc(VarTypeNames[i]);
Proc(SString);
end;
procedure TVariantTypeProperty.SetValue(const Value: string);
function GetSelectedType: Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to High(VarTypeNames) do
if VarTypeNames[i] = Value then
begin
Result := i;
break;
end;
if (Result = -1) and (Value = SString) then
Result := varString;
end;
var
NewType: Integer;
V: Variant;
begin
V := GetVarValue;
NewType := GetSelectedType;
case NewType of
varEmpty: VarClear(V);
varNull: V := NULL;
-1: raise Exception.CreateRes(@SUnknownType);
else
try
VarCast(V, V, NewType);
except
{ If it cannot cast, clear it and then cast again. }
VarClear(V);
VarCast(V, V, NewType);
end;
end;
SetVarValue(V);
end;
{ TVariantProperty }
function TVariantProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paMultiSelect, paSubProperties];
end;
procedure TVariantProperty.GetProperties(Proc: TGetPropProc);
begin
Proc(TVariantTypeProperty.Create(Self));
end;
function TVariantProperty.GetValue: string;
function GetVariantStr(const Value: Variant): string;
begin
case VarType(Value) of
varBoolean:
Result := BooleanIdents[Value = True];
varCurrency:
Result := CurrToStr(Value);
else
Result := VarToStrDef(Value, SNull);
end;
end;
var
Value: Variant;
begin
Value := GetVarValue;
if VarType(Value) <> varDispatch then
Result := GetVariantStr(Value)
else
Result := 'ERROR';
end;
procedure TVariantProperty.SetValue(const Value: string);
function Cast(var Value: Variant; NewType: Integer): Boolean;
var
V2: Variant;
begin
Result := True;
if NewType = varCurrency then
Result := AnsiPos(CurrencyString, Value) > 0;
if Result then
try
VarCast(V2, Value, NewType);
Result := (NewType = varDate) or (VarToStr(V2) = VarToStr(Value));
if Result then Value := V2;
except
Result := False;
end;
end;
var
V: Variant;
OldType: Integer;
begin
OldType := VarType(GetVarValue);
V := Value;
if Value = '' then
VarClear(V) else
if (CompareText(Value, SNull) = 0) then
V := NULL else
if not Cast(V, OldType) then
V := Value;
SetVarValue(V);
end;
{ TEditActionSelectionEditor }
resourcestring
sEditSubmenu = 'Edit';
sUndoComponent = 'Undo';
sCutComponent = 'Cut';
sCopyComponent = 'Copy';
sPasteComponent = 'Paste';
sDeleteComponent = 'Delete';
sSelectAllComponent = 'Select All';
sControlSubmenu = 'Control';
sToFrontControl = 'Bring to Front';
sToBackControl = 'Send to Back';
function TEditActionSelectionEditor.GetVerb(Index: Integer): string;
begin
case Index of
0: Result := sEditSubmenu;
1: Result := sControlSubmenu;
end;
end;
function TEditActionSelectionEditor.GetVerbCount: Integer;
begin
Result := 2;
end;
procedure TEditActionSelectionEditor.PrepareItem(Index: Integer; const AItem: IMenuItem);
var
LEditState: TEditState;
begin
case Index of
0: // edit
with AItem do
begin
LEditState := GetEditState;
Enabled := ([esCanUndo, esCanCut, esCanCopy, esCanPaste, esCanDelete, esCanSelectAll] * LEditState) <> [];
AddItem(sUndoComponent, 0, False, esCanUndo in LEditState, HandleUndo);
AddLine;
AddItem(sCutComponent, 0, False, esCanCut in LEditState, HandleCut);
AddItem(sCopyComponent, 0, False, esCanCopy in LEditState, HandleCopy);
AddItem(sPasteComponent, 0, False, esCanPaste in LEditState, HandlePaste);
AddItem(sDeleteComponent, 0, False, esCanDelete in LEditState, HandleDelete);
AddLine;
AddItem(sSelectAllComponent, 0, False, esCanSelectAll in LEditState, HandleSelectAll);
end;
1: // control
with AItem do
begin
LEditState := GetEditState;
Visible := esCanZOrder in LEditState;
AddItem(sToFrontControl, 0, False, True, HandleToFront);
AddItem(sToBackControl, 0, False, True, HandleToBack);
end;
end;
end;
procedure TEditActionSelectionEditor.HandleToFront(Sender: TObject);
begin
EditAction(eaBringToFront);
end;
procedure TEditActionSelectionEditor.HandleToBack(Sender: TObject);
begin
EditAction(eaSendToBack);
end;
procedure TEditActionSelectionEditor.HandleUndo(Sender: TObject);
begin
EditAction(eaUndo);
end;
procedure TEditActionSelectionEditor.HandleCut(Sender: TObject);
begin
EditAction(eaCut);
end;
procedure TEditActionSelectionEditor.HandleCopy(Sender: TObject);
begin
EditAction(eaCopy);
end;
procedure TEditActionSelectionEditor.HandlePaste(Sender: TObject);
begin
EditAction(eaPaste);
end;
procedure TEditActionSelectionEditor.HandleDelete(Sender: TObject);
begin
EditAction(eaDelete);
end;
procedure TEditActionSelectionEditor.HandleSelectAll(Sender: TObject);
begin
EditAction(eaSelectAll);
end;
procedure TEditActionSelectionEditor.EditAction(Action: TEditAction);
var
LTopComponent: TComponent;
LEditHandler: IEditHandler;
begin
LTopComponent := nil;
if Assigned(GetTopLevelComponentFunc) then
LTopComponent := GetTopLevelComponentFunc;
if Supports(LTopComponent, IEditHandler, LEditHandler) or
Supports(Designer, IEditHandler, LEditHandler) then
LEditHandler.EditAction(Action);
end;
function TEditActionSelectionEditor.GetEditState: TEditState;
var
LTopComponent: TComponent;
LEditHandler: IEditHandler;
begin
Result := [];
LTopComponent := nil;
if Assigned(GetTopLevelComponentFunc) then
LTopComponent := GetTopLevelComponentFunc;
if Supports(LTopComponent, IEditHandler, LEditHandler) or
Supports(Designer, IEditHandler, LEditHandler) then
Result := LEditHandler.GetEditState;
end;
initialization
{ Hook the DesignIntf registration routines }
DesignIntf.RegisterPropertyEditorProc := RegisterPropertyEditor;
DesignIntf.RegisterPropertyMapperProc := RegisterPropertyMapper;
DesignIntf.RegisterComponentEditorProc := RegisterComponentEditor;
DesignIntf.RegisterSelectionEditorProc := RegisterSelectionEditor;
DesignIntf.SetPropertyEditorGroupProc := SetPropertyEditorGroup;
finalization
{ Unhook DesignIntf registration routines }
DesignIntf.RegisterPropertyEditorProc := nil;
DesignIntf.RegisterPropertyMapperProc := nil;
DesignIntf.RegisterComponentEditorProc := nil;
DesignIntf.RegisterSelectionEditorProc := nil;
DesignIntf.SetPropertyEditorGroupProc := nil;
end.
|
{$mode objfpc}
{$m+}
program TreeTraversalBFS;
type
Nd = ^Node;
Node = record
data : char;
L, R, P : Nd; { Left, right, parent }
end;
StackNode = record
val : Nd;
prev : ^StackNode;
end;
LinkedListQueue = class
private
first : ^StackNode;
last : ^StackNode;
public
function pop(): Nd;
procedure push(i : Nd);
end;
function LinkedListQueue.pop() : Nd;
begin
if first <> nil then
begin
pop := first^.val;
first := first^.prev;
end
else
begin
pop := nil;
end;
end;
procedure LinkedListQueue.push(i : Nd);
var
A : ^StackNode;
begin
new(A);
A^.val := i;
if first = nil then
first := A
else
last^.prev := A;
last := A;
end;
procedure TraverseBFSRight(Root: Nd);
var
LQueue : LinkedListQueue;
L : Nd;
begin
LQueue := LinkedListQueue.Create();
L := Root;
while L <> nil do
begin
writeln(L^.data);
if L^.R <> nil then
LQueue.push(L^.R);
if L^.L <> nil then
LQueue.push(L^.L);
L := LQueue.pop();
end;
end;
procedure TraverseBFSLeft(Root: Nd);
var
LQueue : LinkedListQueue;
L : Nd;
begin
LQueue := LinkedListQueue.Create();
L := Root;
while L <> nil do
begin
writeln(L^.data);
if L^.L <> nil then
LQueue.push(L^.L);
if L^.R <> nil then
LQueue.push(L^.R);
L := LQueue.pop();
end;
end;
var
A, B, C, D, E, F, G, H, I, J : Nd;
begin
new(A); A^.data := 'A';
new(B); B^.data := 'B';
new(C); C^.data := 'C';
new(D); D^.data := 'D';
new(E); E^.data := 'E';
new(F); F^.data := 'F';
new(G); G^.data := 'G';
new(H); H^.data := 'H';
new(I); I^.data := 'I';
new(J); J^.data := 'J';
A^.L := B;
A^.R := C;
B^.L := D;
B^.R := E;
C^.L := H;
D^.L := J;
D^.R := F;
H^.R := I;
{* tree structure:
A
B C
D E H
J F I *}
writeln('bfs traverse right');
TraverseBFSRight(A);
writeln('bfs traverse left');
TraverseBFSLeft(A);
end.
|
unit VisualHallFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls;
type
//для отрисовки элементов
IDrawItems = interface
['{168B0326-DBE9-4406-8FD0-BE5CA476FB98}']
function Draw(aCanvas: TCanvas):HRESULT;
end;
ISelectedItems = interface
['{2872B58B-EBA3-4959-AE9D-A390C9FD8B11}']
function IsUnderMouse(x: Integer; y: Integer; var resVal : Boolean):HRESULT;
function SelectedRect(aRect: TRect):HRESULT;
function SelectedPoint(x: Integer; y: Integer):HRESULT;
function Reset():HRESULT;
end;
IPosition = interface
['{3FFFC999-746F-44A4-94AB-BE8459D24CDC}']
function Shift(dx: Integer; dy: Integer):HRESULT;
end;
//резиновая рамка
TSelectedArea = class
public
StartPoint : TPoint;
SelRect : TRect;
Selecting : Boolean;
constructor Create();
procedure DrawRect(const canvs:TCanvas);
procedure NormalRect(const p: TPoint);
// procedure ItemsIntersectRect(var items : THallPlan);
private
end;
//для перемещения
TMoveItems = record
PosMDown : TPoint;
Selecting : Boolean;
end;
TfrmVisualHall = class(TFrame)
pbDisplay: TPaintBox;
procedure pbDisplayPaint(Sender: TObject);
procedure pbDisplayMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure pbDisplayMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure pbDisplayMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
FBkscrn: TBitmap;
FGridStep: Integer;
FItems: TInterfaceList;
FMoveItems: TMoveItems;
FSelectedArea: TSelectedArea;
FSelectSingle: Boolean;
FSelectRegion: Boolean;
FDrawGrid: Boolean;
procedure NoBkGnd(var Msg: TWMEraseBkGnd); message WM_ERASEBKGND;
procedure RefreshSize();
procedure SetSelectSingle(val: Boolean);
procedure SetSelectRegion(val: Boolean);
procedure SetDrawGrid(val: Boolean);
procedure GridDraw(cnvs: TCanvas);
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function AddItem(itm : IUnknown):HRESULT;
procedure InvalidateCanvas();
property SelectSingle: Boolean read FSelectSingle write SetSelectSingle;
property SelectRegion: Boolean read FSelectRegion write SetSelectRegion;
property DrawGrid: Boolean read FDrawGrid write SetDrawGrid;
end;
const
SEAT_SIZE : Integer = 16; //размер квадрата ячейки (места)
implementation
{$R *.dfm}
procedure TfrmVisualHall.NoBkGnd(var Msg: TWMEraseBkgnd);
begin
Msg.Result :=1;
end;
//==============================================================================
constructor TSelectedArea.Create();
begin
end;
procedure TSelectedArea.DrawRect(const canvs:TCanvas);
begin
with canvs do begin
Pen.Style := psDot;
Pen.Color := clGray;
Pen.Mode := pmXor;
Brush.Style := bsClear;
Rectangle(SelRect.Left, SelRect.Top, SelRect.Right, SelRect.Bottom);
end;
end;
procedure TSelectedArea.NormalRect(const p: TPoint);
begin
if StartPoint.X < p.X then
begin
SelRect.Left := StartPoint.X;
SelRect.Right := p.X;
end
else begin
SelRect.Left := p.X;
SelRect.Right := StartPoint.X;
end;
if StartPoint.Y < p.Y then
begin
SelRect.Top := StartPoint.Y;
SelRect.Bottom := p.Y;
end
else begin
SelRect.Top := p.Y;
SelRect.Bottom := StartPoint.Y;
end;
end;
(*
procedure TSelectedArea.ItemsIntersectRect(var items : THallPlan);
var
i, n: integer;
rct: TRect;
res: TRect;
begin
with items do begin
n := Count-1;
for i:=0 to n do
begin
rct := Rect(Items[i].Position.X, Items[i].Position.Y,
Items[i].Position.X+SEAT_SIZE, Items[i].Position.Y+SEAT_SIZE);
Items[i].Selected := IntersectRect(res, rct, SelRect);
end;
end;
end;
(**)
//==============================================================================
procedure TfrmVisualHall.RefreshSize();
begin
if (FBkscrn.Height <> pbDisplay.Height)
or (FBkscrn.Width <> pbDisplay.Width)
then
begin
FBkscrn.Height:=pbDisplay.Height;
FBkscrn.Width:=pbDisplay.Width;
end;
end;
procedure TfrmVisualHall.SetSelectSingle(val: Boolean);
begin
if val <> FSelectSingle then
begin
FSelectSingle := val;
FSelectRegion := not FSelectSingle;
end;
end;
procedure TfrmVisualHall.SetSelectRegion(val: Boolean);
begin
if val <> FSelectRegion then
begin
FSelectRegion := val;
FSelectSingle := not FSelectRegion;
end;
end;
procedure TfrmVisualHall.SetDrawGrid(val: Boolean);
begin
if val <> FDrawGrid then
begin
FDrawGrid := val;
pbDisplay.Invalidate;
end;
end;
procedure TfrmVisualHall.GridDraw(cnvs: TCanvas);
var
n, nn:integer;
i, ii:integer;
tr: TRect;
begin
if not FDrawGrid then Exit;
tr:=cnvs.ClipRect;
cnvs.Pen.Color:=clBlack;
cnvs.Pen.Width:=1;
nn := (tr.Right div FGridStep);
ii := (tr.Bottom div FGridStep);
for n:=0 to nn do
begin
for i:=0 to ii do
begin
cnvs.Pixels[n*FGridStep, i*FGridStep]:= cnvs.Pen.Color;
end;
end;
end;
procedure TfrmVisualHall.pbDisplayPaint(Sender: TObject);
var
indx : Integer;
cnt : Integer;
itms : IUnknown;
cnvs : TCanvas;
begin
cnvs:=FBkscrn.Canvas;
try
cnvs.Lock();
RefreshSize();
cnvs.Brush.Color:=clWhite;
cnvs.FillRect(cnvs.ClipRect);
GridDraw(cnvs);
cnt := FItems.Count - 1;
for indx:=0 to cnt do begin
itms := IUnknown(FItems[indx]);
(itms as IDrawItems).Draw(cnvs);
end;
finally
cnvs.Unlock();
pbDisplay.Canvas.Draw(0, 0, FBkscrn);
end;
end;
constructor TfrmVisualHall.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FBkscrn:=TBitmap.Create();
FSelectedArea:= TSelectedArea.Create();
FItems := TInterfaceList.Create();
FGridStep := SEAT_SIZE;
end;
destructor TfrmVisualHall.Destroy();
begin
FItems.Clear;
FItems.Free();
FSelectedArea.Free;
FBkscrn.Free();
inherited Destroy();
end;
function TfrmVisualHall.AddItem(itm : IUnknown):HRESULT;
begin
FItems.Add(itm);
pbDisplay.Invalidate;
Result := S_OK;
end;
procedure TfrmVisualHall.InvalidateCanvas();
begin
pbDisplay.Invalidate;
end;
procedure TfrmVisualHall.pbDisplayMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
itms : IUnknown;
function IsSelectingItems():Boolean;
var
i : Integer;
n : Integer;
isSelected : Boolean;
hrRes: HRESULT;
begin
isSelected := False;
n := FItems.Count - 1;
for i:=0 to n do begin
itms := IUnknown(FItems[i]);
hrRes := (itms as ISelectedItems).IsUnderMouse(X, Y, isSelected);
if (isSelected) and (hrRes = S_OK)
then Break;
end;
Result := isSelected;
end;
procedure ResetSelectItem();
var
i : Integer;
n : Integer;
begin
n := FItems.Count - 1;
for i:=0 to n do begin
itms := IUnknown(FItems[i]);
(itms as ISelectedItems).Reset();
end;
end;
procedure SelectingItem();
var
i : Integer;
n : Integer;
begin
n := FItems.Count - 1;
for i:=0 to n do begin
itms := IUnknown(FItems[i]);
(itms as ISelectedItems).SelectedPoint(X, Y);
end;
end;
begin
if IsSelectingItems then
begin //установка курсора на один из элементов
if ((ssShift in Shift) and (ssCtrl in Shift))
then begin//при одновременном нажатии Ctrl и Shift и - начинаем смещение
FMoveItems.PosMDown := Point(X, Y);
FMoveItems.Selecting := True;
end
else if FSelectSingle
then begin
if not(ssCtrl in Shift)
then ResetSelectItem();
SelectingItem;
//ReadHallItemProps(Item);
end;
end
else begin
if FSelectRegion and not(FSelectedArea.Selecting or (Button <> mbLeft))
then begin
FSelectedArea.Selecting := True;
FSelectedArea.StartPoint := Point(X, Y);
FSelectedArea.SelRect := Bounds(X, Y, 0, 0);
end
else begin
if not(ssCtrl in Shift)
then ResetSelectItem();
end;
end;
pbDisplay.Invalidate;
end;
procedure TfrmVisualHall.pbDisplayMouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
var
itms : IUnknown;
procedure ShiftSelectItem(const dx: Integer; const dy: Integer);
var
i : Integer;
n : Integer;
begin
n := FItems.Count - 1;
for i:=0 to n do begin
itms := IUnknown(FItems[i]);
(itms as IPosition).Shift(dx, dy);
end;
end;
procedure SelectingItems();
var
i : Integer;
n : Integer;
begin
n := FItems.Count - 1;
for i:=0 to n do begin
itms := IUnknown(FItems[i]);
(itms as ISelectedItems).SelectedRect(FSelectedArea.SelRect);
end;
end;
begin
if FMoveItems.Selecting then
begin
//CurHallItem.Position:=GetSnapPoint(X, Y);
ShiftSelectItem(X - FMoveItems.posMDown.X, Y - FMoveItems.posMDown.Y);
FMoveItems.posMDown := Point(X, Y);
pbDisplay.Invalidate;
end
else
begin
(*
HallItem:=GetItemAtXY(X, Y);
if Assigned(HallItem) then
begin
ReadHallItemProps(HallItem);
end;
(**)
end;
if not FSelectedArea.Selecting
then Exit;
FSelectedArea.DrawRect(pbDisplay.Canvas);
FSelectedArea.NormalRect(Point(X, Y));
SelectingItems();
pbDisplay.Invalidate;
FSelectedArea.DrawRect(pbDisplay.Canvas);
end;
procedure TfrmVisualHall.pbDisplayMouseUp(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
// if Assigned(CurHallItem) then CurHallItem.Selected:=False;
FMoveItems.Selecting := False;
if (not FSelectedArea.Selecting or (Button <> mbLeft))
then Exit;
FSelectedArea.NormalRect( Point(X, Y) );
FSelectedArea.DrawRect( pbDisplay.Canvas );
FSelectedArea.Selecting := False;
end;
end.
|
unit AssignRoles;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, BasePopupDetail, RzButton, RzTabs,
Vcl.StdCtrls, RzLabel, Vcl.Imaging.pngimage, Vcl.ExtCtrls, RzPanel, LocalUser, Role,
RzLstBox, RzChkLst;
type
TfrmAssignRoles = class(TfrmBasePopupDetail)
chlRoles: TRzCheckList;
procedure chlRolesChange(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
private
{ Private declarations }
FUser: TLocalUser;
procedure PopulateRolesList;
protected
procedure Save; override;
procedure Cancel; override;
procedure BindToObject; override;
function ValidEntry: boolean; override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); overload; override;
constructor Create(AOwner: TComponent; var AUser: TLocalUser); reintroduce; overload;
end;
implementation
{$R *.dfm}
uses
SecurityData;
{ TfrmAssignRoles }
procedure TfrmAssignRoles.BindToObject;
begin
inherited;
end;
procedure TfrmAssignRoles.Cancel;
begin
inherited;
end;
procedure TfrmAssignRoles.chlRolesChange(Sender: TObject; Index: Integer;
NewState: TCheckBoxState);
begin
inherited;
(chlRoles.Items.Objects[Index] as TRole).AssignedNewValue := NewState = cbChecked;
end;
constructor TfrmAssignRoles.Create(AOwner: TComponent; var AUser: TLocalUser);
begin
inherited Create(AOwner);
FUser := AUser;
// caption
lblCaption.Caption := 'Assigned roles to ' + AUser.Name;
PopulateRolesList;
end;
procedure TfrmAssignRoles.PopulateRolesList;
var
LRole: TRole;
begin
with dmSecurity.dstUserRoles, chlRoles do
begin
try
// open the datasource
Parameters.ParamByName('@id_num').Value := FUser.UserId;
Open;
while not Eof do
begin
LRole := TRole.Create;
LRole.Code := FieldByName('role_code_master').AsString;
LRole.Name := FieldByName('role_name').AsString;
LRole.AssignedOldValue := FieldByName('id_num').AsString <> '';
LRole.AssignedNewValue := FieldByName('id_num').AsString <> '';
AddItem(LRole.Name,LRole);
ItemChecked[Items.Count-1] := LRole.AssignedOldValue;
Next;
end;
finally
Close;
end;
end;
end;
constructor TfrmAssignRoles.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
procedure TfrmAssignRoles.Save;
var
i, cnt: integer;
begin
cnt := chlRoles.Count - 1;
for i := 0 to cnt do FUser.Roles[i] := chlRoles.Items.Objects[i] as TRole;
end;
function TfrmAssignRoles.ValidEntry: boolean;
begin
Result := true;
end;
end.
|
unit IdVCLPosixSupplemental;
interface
{$I IdCompilerDefines.inc}
{$WARN SYMBOL_PLATFORM OFF}
uses
{$IFDEF DARWIN}
CoreFoundation,
CoreServices,
{$ENDIF}
IdCTypes;
//tcp.hh
type
{Supplemental stuff from netinet/tcp.h}
{$EXTERNALSYM tcp_seq}
tcp_seq = TIdC_UINT32;
{$EXTERNALSYM tcp_cc}
tcp_cc = TIdC_UINT32; //* connection count per rfc1644 */
{$EXTERNALSYM tcp6_seq}
tcp6_seq = tcp_seq; //* for KAME src sync over BSD*'s */' +
{stuff that may be needed for various socket functions. Much of this may be
platform specific. Defined in netinet/tcp.h}
const
{$IFDEF BSD}
//for BSD-based operating systems such as FreeBSD and Mac OS X
{$EXTERNALSYM TCP_MAXSEG}
TCP_MAXSEG = $02; //* set maximum segment size */
{$EXTERNALSYM TCP_NOPUSH}
TCP_NOPUSH = $04 platform; //* don't push last block of write */
{$EXTERNALSYM TCP_NOOPT}
TCP_NOOPT = $08; //* don't use TCP options */
{$ENDIF}
{$IFDEF FREEBSD}
//specific to FreeBSD
{$EXTERNALSYM TCP_MD5SIG}
TCP_MD5SIG = $10 platform; //* use MD5 digests (RFC2385) */
{$EXTERNALSYM TCP_INFO}
TCP_INFO = $20 platform; //* retrieve tcp_info structure */
{$EXTERNALSYM TCP_CONGESTION}
TCP_CONGESTION = $40 platform; //* get/set congestion control algorithm */
{$ENDIF}
{$IFDEF DARWIN}
//specific to Mac OS X
{$EXTERNALSYM TCP_KEEPALIVE}
TCP_KEEPALIVE = $10 platform; //* idle time used when SO_KEEPALIVE is enabled */
{$EXTERNALSYM TCP_CONNECTIONTIMEOUT}
TCP_CONNECTIONTIMEOUT = $20 platform; //* connection timeout */
{$EXTERNALSYM TCPOPT_EOL}
TCPOPT_EOL = 0 platform;
{$EXTERNALSYM TCPOPT_NOP}
TCPOPT_NOP = 1 platform;
{$EXTERNALSYM TCPOPT_MAXSEG}
TCPOPT_MAXSEG = 2 platform;
{$EXTERNALSYM TCPOLEN_MAXSEG}
TCPOLEN_MAXSEG = 4 platform;
{$EXTERNALSYM TCPOPT_WINDOW}
TCPOPT_WINDOW = 3 platform;
{$EXTERNALSYM TCPOLEN_WINDOW}
TCPOLEN_WINDOW = 3 platform;
{$EXTERNALSYM TCPOPT_SACK_PERMITTED}
TCPOPT_SACK_PERMITTED = 4 platform; //* Experimental */
{$EXTERNALSYM TCPOLEN_SACK_PERMITTED}
TCPOLEN_SACK_PERMITTED = 2 platform;
{$EXTERNALSYM TCPOPT_SACK}
TCPOPT_SACK = 5 platform; //* Experimental */
{$EXTERNALSYM TCPOLEN_SACK}
TCPOLEN_SACK = 8 platform; //* len of sack block */
{$EXTERNALSYM TCPOPT_TIMESTAMP}
TCPOPT_TIMESTAMP = 8 platform;
{$EXTERNALSYM TCPOLEN_TIMESTAMP}
TCPOLEN_TIMESTAMP = 10 platform;
{$EXTERNALSYM TCPOLEN_TSTAMP_APPA}
TCPOLEN_TSTAMP_APPA = (TCPOLEN_TIMESTAMP+2) platform; //* appendix A */
{$EXTERNALSYM TCPOPT_TSTAMP_HDR}
TCPOPT_TSTAMP_HDR =
((TCPOPT_NOP shl 24) or
(TCPOPT_NOP shl 16) or
(TCPOPT_TIMESTAMP shl 8) or
(TCPOLEN_TIMESTAMP)) platform;
{$EXTERNALSYM MAX_TCPOPTLEN}
MAX_TCPOPTLEN = 40 platform; //* Absolute maximum TCP options len */
{$EXTERNALSYM TCPOPT_CC}
TCPOPT_CC = 11 platform; //* CC options: RFC-1644 */
{$EXTERNALSYM TCPOPT_CCNEW}
TCPOPT_CCNEW = 12 platform;
{$EXTERNALSYM TCPOPT_CCECHO}
TCPOPT_CCECHO = 13 platform;
{$EXTERNALSYM TCPOLEN_CC}
TCPOLEN_CC = 6 platform;
{$EXTERNALSYM TCPOLEN_CC_APPA}
TCPOLEN_CC_APPA = (TCPOLEN_CC+2);
{$EXTERNALSYM TCPOPT_CC_HDR}
function TCPOPT_CC_HDR(const ccopt : Integer) : Integer; inline;
const
{$EXTERNALSYM TCPOPT_SIGNATURE}
TCPOPT_SIGNATURE = 19 platform; //* Keyed MD5: RFC 2385 */
{$EXTERNALSYM TCPOLEN_SIGNATURE}
TCPOLEN_SIGNATURE = 18 platform;
//* Option definitions */
{$EXTERNALSYM TCPOPT_SACK_PERMIT_HDR}
TCPOPT_SACK_PERMIT_HDR =
((TCPOPT_NOP shl 24) or
(TCPOPT_NOP shl 16) or
(TCPOPT_SACK_PERMITTED shl 8) or
TCPOLEN_SACK_PERMITTED) platform;
{$EXTERNALSYM TCPOPT_SACK_HDR}
TCPOPT_SACK_HDR = ((TCPOPT_NOP shl 24) or (TCPOPT_NOP shl 16) or (TCPOPT_SACK shl 8)) platform;
//* Miscellaneous constants */
{$EXTERNALSYM MAX_SACK_BLKS}
MAX_SACK_BLKS = 6 platform; //* Max # SACK blocks stored at sender side */
{$EXTERNALSYM TCP_MAX_SACK}
TCP_MAX_SACK = 3 platform; //* MAX # SACKs sent in any segment */
// /*
// * Default maximum segment size for TCP.
// * With an IP MTU of 576, this is 536,
// * but 512 is probably more convenient.
// * This should be defined as MIN(512, IP_MSS - sizeof (struct tcpiphdr)).
// */
{$EXTERNALSYM TCP_MSS}
TCP_MSS = 512 platform;
// /*
// * TCP_MINMSS is defined to be 216 which is fine for the smallest
// * link MTU (256 bytes, SLIP interface) in the Internet.
// * However it is very unlikely to come across such low MTU interfaces
// * these days (anno dato 2004).
// * Probably it can be set to 512 without ill effects. But we play safe.
// * See tcp_subr.c tcp_minmss SYSCTL declaration for more comments.
// * Setting this to "0" disables the minmss check.
// */
{$EXTERNALSYM TCP_MINMSS}
TCP_MINMSS = 216 platform;
// /*
// * TCP_MINMSSOVERLOAD is defined to be 1000 which should cover any type
// * of interactive TCP session.
// * See tcp_subr.c tcp_minmssoverload SYSCTL declaration and tcp_input.c
// * for more comments.
// * Setting this to "0" disables the minmssoverload check.
// */
{$EXTERNALSYM TCP_MINMSSOVERLOAD}
TCP_MINMSSOVERLOAD = 1000 platform;
// *
// * Default maximum segment size for TCP6.
// * With an IP6 MSS of 1280, this is 1220,
// * but 1024 is probably more convenient. (xxx kazu in doubt)
// * This should be defined as MIN(1024, IP6_MSS - sizeof (struct tcpip6hdr))
// */
{$EXTERNALSYM TCP6_MSS}
TCP6_MSS = 1024 platform;
{$EXTERNALSYM TCP_MAXWIN}
TCP_MAXWIN = 65535 platform; //* largest value for (unscaled) window */
{$EXTERNALSYM TTCP_CLIENT_SND_WND}
TTCP_CLIENT_SND_WND = 4096 platform; //* dflt send window for T/TCP client */
{$EXTERNALSYM TCP_MAX_WINSHIFT}
TCP_MAX_WINSHIFT = 14 platform; //* maximum window shift */
{$EXTERNALSYM TCP_MAXBURST}
TCP_MAXBURST = 4 platform; //* maximum segments in a burst */
{$EXTERNALSYM TCP_MAXHLEN}
TCP_MAXHLEN = ($f shl 2) platform; //* max length of header in bytes */
{$ENDIF}
{$IFDEF LINUX}
//specific to Linux
{$EXTERNALSYM TCP_MAXSEG}
TCP_MAXSEG = 2; //* Limit MSS */
{$EXTERNALSYM TCP_CORK}
TCP_CORK = 3 platform; //* Never send partially complete segments */
{$EXTERNALSYM TCP_KEEPIDLE}
TCP_KEEPIDLE = 4 platform //* Start keeplives after this period */
{$EXTERNALSYM TCP_KEEPINTVL}
TCP_KEEPINTVL = 5 platform; //* Interval between keepalives */
{$EXTERNALSYM TCP_KEEPCNT}
TCP_KEEPCNT = 6 platform; //* Number of keepalives before death */
{$EXTERNALSYM TCP_SYNCNT}
TCP_SYNCNT = 7 platform; //* Number of SYN retransmits */
{$EXTERNALSYM TCP_LINGER2}
TCP_LINGER2 = 8 platform; //* Life time of orphaned FIN-WAIT-2 state */
{$EXTERNALSYM TCP_DEFER_ACCEPT}
TCP_DEFER_ACCEPT = 9 platform; //* Wake up listener only when data arrive */
{$EXTERNALSYM TCP_WINDOW_CLAMP}
TCP_WINDOW_CLAMP = 10 platform; //* Bound advertised window */
{$EXTERNALSYM TCP_WINDOW_CLAMP}
TCP_INFO = 11 platform; //* Information about this connection. */
{$EXTERNALSYM TCP_QUICKACK}
TCP_QUICKACK = 12 platform; //* Block/reenable quick acks */
{$EXTERNALSYM TCP_CONGESTION}
TCP_CONGESTION = 13 platform; //* Congestion control algorithm */
{$EXTERNALSYM TCP_MD5SIG}
TCP_MD5SIG = 14 platform; //* TCP MD5 Signature (RFC2385) */
{$EXTERNALSYM TCP_COOKIE_TRANSACTIONS}
TCP_COOKIE_TRANSACTIONS = 15 platform; //* TCP Cookie Transactions */
{$EXTERNALSYM TCP_THIN_LINEAR_TIMEOUTS}
TCP_THIN_LINEAR_TIMEOUTS = 16 platform; //* Use linear timeouts for thin streams*/
{$EXTERNALSYM TCP_THIN_DUPACK}
TCP_THIN_DUPACK = 17 platform; //* Fast retrans. after 1 dupack */
{$EXTERNALSYM TCPI_OPT_TIMESTAMPS}
TCPI_OPT_TIMESTAMPS = 1;
{$EXTERNALSYM TCPI_OPT_SACK}
TCPI_OPT_SACK = 2;
{$EXTERNALSYM TCPI_OPT_WSCALE}
TCPI_OPT_WSCALE = 4;
{$EXTERNALSYM TCPI_OPT_ECN}
TCPI_OPT_ECN = 8;
{$ENDIF}
//udp.h
{$IFDEF DARWIN}
{$EXTERNALSYM UDP_NOCKSUM}
UDP_NOCKSUM = $01; //* don't checksum outbound payloads */
{$ENDIF}
{$IFDEF DARWIN}
///Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks/CarbonCore.framework/Versions/A/Headers/MacErrors.h
//enum {
{$EXTERNALSYM paramErr}
paramErr = -50; //*error in user parameter list*/
{$EXTERNALSYM noHardwareErr}
noHardwareErr = -200; //*Sound Manager Error Returns*/
{$EXTERNALSYM notEnoughHardwareErr}
notEnoughHardwareErr = -201; //*Sound Manager Error Returns*/
{$EXTERNALSYM userCanceledErr}
userCanceledErr = -128;
{$EXTERNALSYM qErr}
qErr = -1; //*queue element not found during deletion*/
{$EXTERNALSYM vTypErr}
vTypErr = -2; //*invalid queue element*/
{$EXTERNALSYM corErr}
corErr = -3; //*core routine number out of range*/
{$EXTERNALSYM unimpErr}
unimpErr = -4; //*unimplemented core routine*/
{$EXTERNALSYM SlpTypeErr}
SlpTypeErr = -5; //*invalid queue element*/
{$EXTERNALSYM seNoDB}
seNoDB = -8; //*no debugger installed to handle debugger command*/
{$EXTERNALSYM controlErr}
controlErr = -17; //*I/O System Errors*/
{$EXTERNALSYM statusErr}
statusErr = -18; //*I/O System Errors*/
{$EXTERNALSYM readErr}
readErr = -19; //*I/O System Errors*/
{$EXTERNALSYM writErr}
writErr = -20; //*I/O System Errors*/
{$EXTERNALSYM badUnitErr}
badUnitErr = -21; //*I/O System Errors*/
{$EXTERNALSYM unitEmptyErr}
unitEmptyErr = -22; //*I/O System Errors*/
{$EXTERNALSYM openErr}
openErr = -23; //*I/O System Errors*/
{$EXTERNALSYM closErr}
closErr = -24; //*I/O System Errors*/
{$EXTERNALSYM dRemovErr}
dRemovErr = -25; //*tried to remove an open driver*/
{$EXTERNALSYM dInstErr}
dInstErr = -26; //*DrvrInstall couldn't find driver in resources*/
//};
//enum {
{$EXTERNALSYM abortErr}
abortErr = -27; //*IO call aborted by KillIO*/
{$EXTERNALSYM iIOAbortErr}
iIOAbortErr = -27; //*IO abort error (Printing Manager)*/
{$EXTERNALSYM notOpenErr}
notOpenErr = -28; //*Couldn't rd/wr/ctl/sts cause driver not opened*/
{$EXTERNALSYM unitTblFullErr}
unitTblFullErr = -29; //*unit table has no more entries*/
{$EXTERNALSYM dceExtErr}
dceExtErr = -30; //*dce extension error*/
{$EXTERNALSYM slotNumErr}
slotNumErr = -360; //*invalid slot # error*/
{$EXTERNALSYM gcrOnMFMErr}
gcrOnMFMErr = -400; //*gcr format on high density media error*/
{$EXTERNALSYM dirFulErr}
dirFulErr = -33; //*Directory full*/
{$EXTERNALSYM dskFulErr}
dskFulErr = -34; //*disk full*/
{$EXTERNALSYM nsvErr}
nsvErr = -35; //*no such volume*/
{$EXTERNALSYM ioErr}
ioErr = -36; //*I/O error (bummers)*/
{$EXTERNALSYM bdNamErr}
bdNamErr = -37; //* bad file name passed to routine; there may be no bad names in the final system!*/
{$EXTERNALSYM fnOpnErr}
fnOpnErr = -38; //*File not open*/
{$EXTERNALSYM eofErr}
eofErr = -39; //*End of file*/
{$EXTERNALSYM posErr}
posErr = -40; //*tried to position to before start of file (r/w)*/
{$EXTERNALSYM mFulErr}
mFulErr = -41; //*memory full (open) or file won't fit (load)*/
{$EXTERNALSYM tmfoErr}
tmfoErr = -42; //*too many files open*/
{$EXTERNALSYM fnfErr}
fnfErr = -43; //*File not found*/
{$EXTERNALSYM wPrErr}
wPrErr = -44; //*diskette is write protected.*/
{$EXTERNALSYM fLckdErr}
fLckdErr = -45; //*file is locked*/
//};
//enum {
{$EXTERNALSYM vLckdErr}
vLckdErr = -46; //*volume is locked*/
{$EXTERNALSYM fBsyErr}
fBsyErr = -47; //*File is busy (delete)*/
{$EXTERNALSYM dupFNErr}
dupFNErr = -48; //*duplicate filename (rename)*/
{$EXTERNALSYM opWrErr}
opWrErr = -49; //*file already open with with write permission*/
{$EXTERNALSYM rfNumErr}
rfNumErr = -51; //*refnum error*/
{$EXTERNALSYM gfpErr}
gfpErr = -52; //*get file position error*/
{$EXTERNALSYM volOffLinErr}
volOffLinErr = -53; //*volume not on line error (was Ejected)*/
{$EXTERNALSYM permErr}
permErr = -54; //*permissions error (on file open)*/
{$EXTERNALSYM volOnLinErr}
volOnLinErr = -55; //*drive volume already on-line at MountVol*/
{$EXTERNALSYM nsDrvErr}
nsDrvErr = -56; //*no such drive (tried to mount a bad drive num)*/
{$EXTERNALSYM noMacDskErr}
noMacDskErr = -57; //*not a mac diskette (sig bytes are wrong)*/
{$EXTERNALSYM extFSErr}
extFSErr = -58; //*volume in question belongs to an external fs*/
{$EXTERNALSYM fsRnErr}
fsRnErr = -59; //*file system internal error:during rename the old entry was deleted but could not be restored.*/
{$EXTERNALSYM badMDBErr}
badMDBErr = -60; //*bad master directory block*/
{$EXTERNALSYM wrPermErr}
wrPermErr = -61; //*write permissions error*/
{$EXTERNALSYM dirNFErr}
dirNFErr = -120; //*Directory not found*/
{$EXTERNALSYM tmwdoErr}
tmwdoErr = -121; //*No free WDCB available*/
{$EXTERNALSYM badMovErr}
badMovErr = -122; //*Move into offspring error*/
{$EXTERNALSYM wrgVolTypErr}
wrgVolTypErr = -123; //*Wrong volume type error [operation not supported for MFS]*/
{$EXTERNALSYM volGoneErr}
volGoneErr = -124; //*Server volume has been disconnected.*/
//};
//enum {
{$EXTERNALSYM fidNotFound}
fidNotFound = -1300; //*no file thread exists.*/
{$EXTERNALSYM fidExists}
fidExists = -1301; //*file id already exists*/
{$EXTERNALSYM notAFileErr}
notAFileErr = -1302; //*directory specified*/
{$EXTERNALSYM diffVolErr}
diffVolErr = -1303; //*files on different volumes*/
{$EXTERNALSYM catChangedErr}
catChangedErr = -1304; //*the catalog has been modified*/
{$EXTERNALSYM desktopDamagedErr}
desktopDamagedErr = -1305; //*desktop database files are corrupted*/
{$EXTERNALSYM sameFileErr}
sameFileErr = -1306; //*can't exchange a file with itself*/
{$EXTERNALSYM badFidErr}
badFidErr = -1307; //*file id is dangling or doesn't match with the file number*/
{$EXTERNALSYM notARemountErr}
notARemountErr = -1308; //*when _Mount allows only remounts and doesn't get one*/
{$EXTERNALSYM fileBoundsErr}
fileBoundsErr = -1309; //*file's EOF, offset, mark or size is too big*/
{$EXTERNALSYM fsDataTooBigErr}
fsDataTooBigErr = -1310; //*file or volume is too big for system*/
{$EXTERNALSYM volVMBusyErr}
volVMBusyErr = -1311; //*can't eject because volume is in use by VM*/
{$EXTERNALSYM badFCBErr}
badFCBErr = -1327; //*FCBRecPtr is not valid*/
{$EXTERNALSYM errFSUnknownCall}
errFSUnknownCall = -1400; //* selector is not recognized by this filesystem */
{$EXTERNALSYM errFSBadFSRef}
errFSBadFSRef = -1401; //* FSRef parameter is bad */
{$EXTERNALSYM errFSBadForkName}
errFSBadForkName = -1402; //* Fork name parameter is bad */
{$EXTERNALSYM errFSBadBuffer}
errFSBadBuffer = -1403; //* A buffer parameter was bad */
{$EXTERNALSYM errFSBadForkRef}
errFSBadForkRef = -1404; //* A ForkRefNum parameter was bad */
{$EXTERNALSYM errFSBadInfoBitmap}
errFSBadInfoBitmap = -1405; //* A CatalogInfoBitmap or VolumeInfoBitmap has reserved or invalid bits set */
{$EXTERNALSYM errFSMissingCatInfo}
errFSMissingCatInfo = -1406; //* A CatalogInfo parameter was NULL */
{$EXTERNALSYM errFSNotAFolder}
errFSNotAFolder = -1407; //* Expected a folder, got a file */
{$EXTERNALSYM errFSForkNotFound}
errFSForkNotFound = -1409; //* Named fork does not exist */
{$EXTERNALSYM errFSNameTooLong}
errFSNameTooLong = -1410; //* File/fork name is too long to create/rename */
{$EXTERNALSYM errFSMissingName}
errFSMissingName = -1411; //* A Unicode name parameter was NULL or nameLength parameter was zero */
{$EXTERNALSYM errFSBadPosMode}
errFSBadPosMode = -1412; //* Newline bits set in positionMode */
{$EXTERNALSYM errFSBadAllocFlags}
errFSBadAllocFlags = -1413; //* Invalid bits set in allocationFlags */
{$EXTERNALSYM errFSNoMoreItems}
errFSNoMoreItems = -1417; //* Iteration ran out of items to return */
{$EXTERNALSYM errFSBadItemCount}
errFSBadItemCount = -1418; //* maximumItems was zero */
{$EXTERNALSYM errFSBadSearchParams}
errFSBadSearchParams = -1419; //* Something wrong with CatalogSearch searchParams */
{$EXTERNALSYM errFSRefsDifferent}
errFSRefsDifferent = -1420; //* FSCompareFSRefs; refs are for different objects */
{$EXTERNALSYM errFSForkExists}
errFSForkExists = -1421; //* Named fork already exists. */
{$EXTERNALSYM errFSBadIteratorFlags}
errFSBadIteratorFlags = -1422; //* Flags passed to FSOpenIterator are bad */
{$EXTERNALSYM errFSIteratorNotFound}
errFSIteratorNotFound = -1423; //* Passed FSIterator is not an open iterator */
{$EXTERNALSYM errFSIteratorNotSupported}
errFSIteratorNotSupported = -1424; //* The iterator's flags or container are not supported by this call */
{$EXTERNALSYM errFSQuotaExceeded}
errFSQuotaExceeded = -1425; //* The user's quota of disk blocks has been exhausted. */
{$EXTERNALSYM errFSOperationNotSupported}
errFSOperationNotSupported = -1426; //* The attempted operation is not supported */
{$EXTERNALSYM errFSAttributeNotFound}
errFSAttributeNotFound = -1427; //* The requested attribute does not exist */
{$EXTERNALSYM errFSPropertyNotValid}
errFSPropertyNotValid = -1428; //* The requested property is not valid (has not been set yet) */
{$EXTERNALSYM errFSNotEnoughSpaceForOperation}
errFSNotEnoughSpaceForOperation = -1429; //* There is not enough disk space to perform the requested operation */
{$EXTERNALSYM envNotPresent}
envNotPresent = -5500; //*returned by glue.*/
{$EXTERNALSYM envBadVers}
envBadVers = -5501; //*Version non-positive*/
{$EXTERNALSYM envVersTooBig}
envVersTooBig = -5502; //*Version bigger than call can handle*/
{$EXTERNALSYM fontDecError}
fontDecError = -64; //*error during font declaration*/
{$EXTERNALSYM fontNotDeclared}
fontNotDeclared = -65; //*font not declared*/
{$EXTERNALSYM fontSubErr}
fontSubErr = -66; //*font substitution occurred*/
{$EXTERNALSYM fontNotOutlineErr}
fontNotOutlineErr = -32615; //*bitmap font passed to routine that does outlines only*/
{$EXTERNALSYM firstDskErr}
firstDskErr = -84; //*I/O System Errors*/
{$EXTERNALSYM lastDskErr}
lastDskErr = -64; //*I/O System Errors*/
{$EXTERNALSYM noDriveErr}
noDriveErr = -64; //*drive not installed*/
{$EXTERNALSYM offLinErr}
offLinErr = -65; //*r/w requested for an off-line drive*/
{$EXTERNALSYM noNybErr}
noNybErr = -66; //*couldn't find 5 nybbles in 200 tries*/
//};
//enum {
{$EXTERNALSYM noAdrMkErr}
noAdrMkErr = -67; //*couldn't find valid addr mark*/
{$EXTERNALSYM dataVerErr}
dataVerErr = -68; //*read verify compare failed*/
{$EXTERNALSYM badCksmErr}
badCksmErr = -69; //*addr mark checksum didn't check*/
{$EXTERNALSYM badBtSlpErr}
badBtSlpErr = -70; //*bad addr mark bit slip nibbles*/
{$EXTERNALSYM noDtaMkErr}
noDtaMkErr = -71; //*couldn't find a data mark header*/
{$EXTERNALSYM badDCksum}
badDCksum = -72; //*bad data mark checksum*/
{$EXTERNALSYM badDBtSlp}
badDBtSlp = -73; //*bad data mark bit slip nibbles*/
{$EXTERNALSYM wrUnderrun}
wrUnderrun = -74; //*write underrun occurred*/
{$EXTERNALSYM cantStepErr}
cantStepErr = -75; //*step handshake failed*/
{$EXTERNALSYM tk0BadErr}
tk0BadErr = -76; //*track 0 detect doesn't change*/
{$EXTERNALSYM initIWMErr}
initIWMErr = -77; //*unable to initialize IWM*/
{$EXTERNALSYM twoSideErr}
twoSideErr = -78; //*tried to read 2nd side on a 1-sided drive*/
{$EXTERNALSYM spdAdjErr}
spdAdjErr = -79; //*unable to correctly adjust disk speed*/
{$EXTERNALSYM seekErr}
seekErr = -80; //*track number wrong on address mark*/
{$EXTERNALSYM sectNFErr}
sectNFErr = -81; //*sector number never found on a track*/
{$EXTERNALSYM fmt1Err}
fmt1Err = -82; //*can't find sector 0 after track format*/
{$EXTERNALSYM fmt2Err}
fmt2Err = -83; //*can't get enough sync*/
{$EXTERNALSYM verErr}
verErr = -84; //*track failed to verify*/
{$EXTERNALSYM clkRdErr}
clkRdErr = -85; //*unable to read same clock value twice*/
{$EXTERNALSYM clkWrErr}
clkWrErr = -86; //*time written did not verify*/
{$EXTERNALSYM prWrErr}
prWrErr = -87; //*parameter ram written didn't read-verify*/
{$EXTERNALSYM prInitErr}
prInitErr = -88; //*InitUtil found the parameter ram uninitialized*/
{$EXTERNALSYM rcvrErr}
rcvrErr = -89; //*SCC receiver error (framing; parity; OR)*/
{$EXTERNALSYM breakRecd}
breakRecd = -90; //*Break received (SCC)*/
//};
//enum {
//*Scrap Manager errors*/
{$EXTERNALSYM noScrapErr}
noScrapErr = -100; //*No scrap exists error*/
{$EXTERNALSYM noTypeErr}
noTypeErr = -102; //*No object of that type in scrap*/
//};
//enum {
//* ENET error codes */
{$EXTERNALSYM eLenErr}
eLenErr = -92; //*Length error ddpLenErr*/
{$EXTERNALSYM eMultiErr}
eMultiErr = -91; //*Multicast address error ddpSktErr*/
//};
//enum {
{$EXTERNALSYM ddpSktErr}
ddpSktErr = -91; //*error in soket number*/
{$EXTERNALSYM ddpLenErr}
ddpLenErr = -92; //*data length too big*/
{$EXTERNALSYM noBridgeErr}
noBridgeErr = -93; //*no network bridge for non-local send*/
{$EXTERNALSYM lapProtErr}
lapProtErr = -94; //*error in attaching/detaching protocol*/
{$EXTERNALSYM excessCollsns}
excessCollsns = -95; //*excessive collisions on write*/
{$EXTERNALSYM portNotPwr}
portNotPwr = -96; //*serial port not currently powered*/
{$EXTERNALSYM portInUse}
portInUse = -97; //*driver Open error code (port is in use)*/
{$EXTERNALSYM portNotCf}
portNotCf = -98; //*driver Open error code (parameter RAM not configured for this connection)*/
//};
//enum {
//* Memory Manager errors*/
{$EXTERNALSYM memROZWarn}
memROZWarn = -99; //*soft error in ROZ*/
{$EXTERNALSYM memROZError}
memROZError = -99; //*hard error in ROZ*/
{$EXTERNALSYM memROZErr}
memROZErr = -99; //*hard error in ROZ*/
{$EXTERNALSYM memFullErr}
memFullErr = -108; //*Not enough room in heap zone*/
{$EXTERNALSYM nilHandleErr}
nilHandleErr = -109; //*Master Pointer was NIL in HandleZone or other*/
{$EXTERNALSYM memWZErr}
memWZErr = -111; //*WhichZone failed (applied to free block)*/
{$EXTERNALSYM memPurErr}
memPurErr = -112; //*trying to purge a locked or non-purgeable block*/
{$EXTERNALSYM memAdrErr}
memAdrErr = -110; //*address was odd; or out of range*/
{$EXTERNALSYM memAZErr}
memAZErr = -113; //*Address in zone check failed*/
{$EXTERNALSYM memPCErr}
memPCErr = -114; //*Pointer Check failed*/
{$EXTERNALSYM memBCErr}
memBCErr = -115; //*Block Check failed*/
{$EXTERNALSYM memSCErr}
memSCErr = -116; //*Size Check failed*/
{$EXTERNALSYM memLockedErr}
memLockedErr = -117; //*trying to move a locked block (MoveHHi)*/
//};
//enum {
//* Printing Errors */
{$EXTERNALSYM iMemFullErr}
iMemFullErr = -108;
{$EXTERNALSYM iIOAbort}
iIOAbort = -27;
//};
//enum {
{$EXTERNALSYM resourceInMemory}
resourceInMemory = -188; //*Resource already in memory*/
{$EXTERNALSYM writingPastEnd}
writingPastEnd = -189; //*Writing past end of file*/
{$EXTERNALSYM inputOutOfBounds}
inputOutOfBounds = -190; //*Offset of Count out of bounds*/
{$EXTERNALSYM resNotFound}
resNotFound = -192; //*Resource not found*/
{$EXTERNALSYM resFNotFound}
resFNotFound = -193; //*Resource file not found*/
{$EXTERNALSYM addResFailed}
addResFailed = -194; //*AddResource failed*/
{$EXTERNALSYM addRefFailed}
addRefFailed = -195; //*AddReference failed*/
{$EXTERNALSYM rmvResFailed}
rmvResFailed = -196; //*RmveResource failed*/
{$EXTERNALSYM rmvRefFailed}
rmvRefFailed = -197; //*RmveReference failed*/
{$EXTERNALSYM resAttrErr}
resAttrErr = -198; //*attribute inconsistent with operation*/
{$EXTERNALSYM mapReadErr}
mapReadErr = -199; //*map inconsistent with operation*/
{$EXTERNALSYM CantDecompress}
CantDecompress = -186; //*resource bent ("the bends") - can't decompress a compressed resource*/
{$EXTERNALSYM badExtResource}
badExtResource = -185; //*extended resource has a bad format.*/
{$EXTERNALSYM noMemForPictPlaybackErr}
noMemForPictPlaybackErr = -145;
{$EXTERNALSYM rgnOverflowErr}
rgnOverflowErr = -147;
{$EXTERNALSYM rgnTooBigError}
rgnTooBigError = -147;
{$EXTERNALSYM pixMapTooDeepErr}
pixMapTooDeepErr = -148;
{$EXTERNALSYM insufficientStackErr}
insufficientStackErr = -149;
{$EXTERNALSYM nsStackErr}
nsStackErr = -149;
//};
//enum {
{$EXTERNALSYM evtNotEnb}
evtNotEnb = 1; //*event not enabled at PostEvent*/
//};
//* OffScreen QuickDraw Errors */
//enum {
{$EXTERNALSYM cMatchErr}
cMatchErr = -150; //*Color2Index failed to find an index*/
{$EXTERNALSYM cTempMemErr}
cTempMemErr = -151; //*failed to allocate memory for temporary structures*/
{$EXTERNALSYM cNoMemErr}
cNoMemErr = -152; //*failed to allocate memory for structure*/
{$EXTERNALSYM cRangeErr}
cRangeErr = -153; //*range error on colorTable request*/
{$EXTERNALSYM cProtectErr}
cProtectErr = -154; //*colorTable entry protection violation*/
{$EXTERNALSYM cDevErr}
cDevErr = -155; //*invalid type of graphics device*/
{$EXTERNALSYM cResErr}
cResErr = -156; //*invalid resolution for MakeITable*/
{$EXTERNALSYM cDepthErr}
cDepthErr = -157; //*invalid pixel depth */
{$EXTERNALSYM rgnTooBigErr}
rgnTooBigErr = -500; //* should have never been added! (cf. rgnTooBigError = 147) */
{$EXTERNALSYM updPixMemErr}
updPixMemErr = -125; //*insufficient memory to update a pixmap*/
{$EXTERNALSYM pictInfoVersionErr}
pictInfoVersionErr = -11000; //*wrong version of the PictInfo structure*/
{$EXTERNALSYM pictInfoIDErr}
pictInfoIDErr = -11001; //*the internal consistancy check for the PictInfoID is wrong*/
{$EXTERNALSYM pictInfoVerbErr}
pictInfoVerbErr = -11002; //*the passed verb was invalid*/
{$EXTERNALSYM cantLoadPickMethodErr}
cantLoadPickMethodErr = -11003; //*unable to load the custom pick proc*/
{$EXTERNALSYM colorsRequestedErr}
colorsRequestedErr = -11004; //*the number of colors requested was illegal*/
{$EXTERNALSYM pictureDataErr}
pictureDataErr = -11005; //*the picture data was invalid*/
//};
//* ColorSync Result codes */
//enum {
//* General Errors */
{$EXTERNALSYM cmProfileError}
cmProfileError = -170;
{$EXTERNALSYM cmMethodError}
cmMethodError = -171;
{$EXTERNALSYM cmMethodNotFound}
cmMethodNotFound = -175; //* CMM not present */
{$EXTERNALSYM cmProfileNotFound}
cmProfileNotFound = -176; //* Responder error */
{$EXTERNALSYM cmProfilesIdentical}
cmProfilesIdentical = -177; //* Profiles the same */
{$EXTERNALSYM cmCantConcatenateError}
cmCantConcatenateError = -178; //* Profile can't be concatenated */
{$EXTERNALSYM cmCantXYZ}
cmCantXYZ = -179; //* CMM cant handle XYZ space */
{$EXTERNALSYM cmCantDeleteProfile}
cmCantDeleteProfile = -180; //* Responder error */
{$EXTERNALSYM cmUnsupportedDataType}
cmUnsupportedDataType = -181; //* Responder error */
{$EXTERNALSYM cmNoCurrentProfile}
cmNoCurrentProfile = -182; //* Responder error */
//};
//enum {
//*Sound Manager errors*/
{$EXTERNALSYM noHardware}
noHardware = noHardwareErr; //*obsolete spelling*/
{$EXTERNALSYM notEnoughHardware}
notEnoughHardware = notEnoughHardwareErr; //*obsolete spelling*/
{$EXTERNALSYM queueFull}
queueFull = -203; //*Sound Manager Error Returns*/
{$EXTERNALSYM resProblem}
resProblem = -204; //*Sound Manager Error Returns*/
{$EXTERNALSYM badChannel}
badChannel = -205; //*Sound Manager Error Returns*/
{$EXTERNALSYM badFormat}
badFormat = -206; //*Sound Manager Error Returns*/
{$EXTERNALSYM notEnoughBufferSpace}
notEnoughBufferSpace = -207; //*could not allocate enough memory*/
{$EXTERNALSYM badFileFormat}
badFileFormat = -208; //*was not type AIFF or was of bad format,corrupt*/
{$EXTERNALSYM channelBusy}
channelBusy = -209; //*the Channel is being used for a PFD already*/
{$EXTERNALSYM buffersTooSmall}
buffersTooSmall = -210; //*can not operate in the memory allowed*/
{$EXTERNALSYM channelNotBusy}
channelNotBusy = -211;
{$EXTERNALSYM noMoreRealTime}
noMoreRealTime = -212; //*not enough CPU cycles left to add another task*/
{$EXTERNALSYM siVBRCompressionNotSupported}
siVBRCompressionNotSupported = -213; //*vbr audio compression not supported for this operation*/
{$EXTERNALSYM siNoSoundInHardware}
siNoSoundInHardware = -220; //*no Sound Input hardware*/
{$EXTERNALSYM siBadSoundInDevice}
siBadSoundInDevice = -221; //*invalid index passed to SoundInGetIndexedDevice*/
{$EXTERNALSYM siNoBufferSpecified}
siNoBufferSpecified = -222; //*returned by synchronous SPBRecord if nil buffer passed*/
{$EXTERNALSYM siInvalidCompression}
siInvalidCompression = -223; //*invalid compression type*/
{$EXTERNALSYM siHardDriveTooSlow}
siHardDriveTooSlow = -224; //*hard drive too slow to record to disk*/
{$EXTERNALSYM siInvalidSampleRate}
siInvalidSampleRate = -225; //*invalid sample rate*/
{$EXTERNALSYM siInvalidSampleSize}
siInvalidSampleSize = -226; //*invalid sample size*/
{$EXTERNALSYM siDeviceBusyErr}
siDeviceBusyErr = -227; //*input device already in use*/
{$EXTERNALSYM siBadDeviceName}
siBadDeviceName = -228; //*input device could not be opened*/
{$EXTERNALSYM siBadRefNum}
siBadRefNum = -229; //*invalid input device reference number*/
{$EXTERNALSYM siInputDeviceErr}
siInputDeviceErr = -230; //*input device hardware failure*/
{$EXTERNALSYM siUnknownInfoType}
siUnknownInfoType = -231; //*invalid info type selector (returned by driver)*/
{$EXTERNALSYM siUnknownQuality}
siUnknownQuality = -232; //*invalid quality selector (returned by driver)*/
//};
///*Speech Manager errors*/
//enum {
{$EXTERNALSYM noSynthFound}
noSynthFound = -240;
{$EXTERNALSYM synthOpenFailed}
synthOpenFailed = -241;
{$EXTERNALSYM synthNotReady}
synthNotReady = -242;
{$EXTERNALSYM bufTooSmall}
bufTooSmall = -243;
{$EXTERNALSYM voiceNotFound}
voiceNotFound = -244;
{$EXTERNALSYM incompatibleVoice}
incompatibleVoice = -245;
{$EXTERNALSYM badDictFormat}
badDictFormat = -246;
{$EXTERNALSYM badInputText}
badInputText = -247;
//};
//* Midi Manager Errors: */
//enum {
{$EXTERNALSYM midiNoClientErr}
midiNoClientErr = -250; //*no client with that ID found*/
{$EXTERNALSYM midiNoPortErr}
midiNoPortErr = -251; //*no port with that ID found*/
{$EXTERNALSYM midiTooManyPortsErr}
midiTooManyPortsErr = -252; //*too many ports already installed in the system*/
{$EXTERNALSYM midiTooManyConsErr}
midiTooManyConsErr = -253; //*too many connections made*/
{$EXTERNALSYM midiVConnectErr}
midiVConnectErr = -254; //*pending virtual connection created*/
{$EXTERNALSYM midiVConnectMade}
midiVConnectMade = -255; //*pending virtual connection resolved*/
{$EXTERNALSYM midiVConnectRmvd}
midiVConnectRmvd = -256; //*pending virtual connection removed*/
{$EXTERNALSYM midiNoConErr}
midiNoConErr = -257; //*no connection exists between specified ports*/
{$EXTERNALSYM midiWriteErr}
midiWriteErr = -258; //*MIDIWritePacket couldn't write to all connected ports*/
{$EXTERNALSYM midiNameLenErr}
midiNameLenErr = -259; //*name supplied is longer than 31 characters*/
{$EXTERNALSYM midiDupIDErr}
midiDupIDErr = -260; //*duplicate client ID*/
{$EXTERNALSYM midiInvalidCmdErr}
midiInvalidCmdErr = -261; //*command not supported for port type*/
//};
//enum {
{$EXTERNALSYM nmTypErr}
nmTypErr = -299; //*Notification Manager:wrong queue type*/
//};
//enum {
{$EXTERNALSYM siInitSDTblErr}
siInitSDTblErr = 1; //*slot int dispatch table could not be initialized.*/
{$EXTERNALSYM siInitVBLQsErr}
siInitVBLQsErr = 2; //*VBLqueues for all slots could not be initialized.*/
{$EXTERNALSYM siInitSPTblErr}
siInitSPTblErr = 3; //*slot priority table could not be initialized.*/
{$EXTERNALSYM sdmJTInitErr}
sdmJTInitErr = 10; //*SDM Jump Table could not be initialized.*/
{$EXTERNALSYM sdmInitErr}
sdmInitErr = 11; //*SDM could not be initialized.*/
{$EXTERNALSYM sdmSRTInitErr}
sdmSRTInitErr = 12; //*Slot Resource Table could not be initialized.*/
{$EXTERNALSYM sdmPRAMInitErr}
sdmPRAMInitErr = 13; //*Slot PRAM could not be initialized.*/
{$EXTERNALSYM sdmPriInitErr}
sdmPriInitErr = 14; //*Cards could not be initialized.*/
//};
//enum {
{$EXTERNALSYM smSDMInitErr}
smSDMInitErr = -290; //*Error; SDM could not be initialized.*/
{$EXTERNALSYM smSRTInitErr}
smSRTInitErr = -291; //*Error; Slot Resource Table could not be initialized.*/
{$EXTERNALSYM smPRAMInitErr}
smPRAMInitErr = -292; //*Error; Slot Resource Table could not be initialized.*/
{$EXTERNALSYM smPriInitErr}
smPriInitErr = -293; //*Error; Cards could not be initialized.*/
{$EXTERNALSYM smEmptySlot}
smEmptySlot = -300; //*No card in slot*/
{$EXTERNALSYM smCRCFail}
smCRCFail = -301; //*CRC check failed for declaration data*/
{$EXTERNALSYM smFormatErr}
smFormatErr = -302; //*FHeader Format is not Apple's*/
{$EXTERNALSYM smRevisionErr}
smRevisionErr = -303; //*Wrong revison level*/
{$EXTERNALSYM smNoDir}
smNoDir = -304; //*Directory offset is Nil*/
{$EXTERNALSYM smDisabledSlot}
smDisabledSlot = -305; //*This slot is disabled (-305 use to be smLWTstBad)*/
{$EXTERNALSYM smNosInfoArray}
smNosInfoArray = -306; //*No sInfoArray. Memory Mgr error.*/
//};
//enum {
{$EXTERNALSYM smResrvErr}
smResrvErr = -307; //*Fatal reserved error. Resreved field <> 0.*/
{$EXTERNALSYM smUnExBusErr}
smUnExBusErr = -308; //*Unexpected BusError*/
{$EXTERNALSYM smBLFieldBad}
smBLFieldBad = -309; //*ByteLanes field was bad.*/
{$EXTERNALSYM smFHBlockRdErr}
smFHBlockRdErr = -310; //*Error occurred during _sGetFHeader.*/
{$EXTERNALSYM smFHBlkDispErr}
smFHBlkDispErr = -311; //*Error occurred during _sDisposePtr (Dispose of FHeader block).*/
{$EXTERNALSYM smDisposePErr}
smDisposePErr = -312; //*_DisposePointer error*/
{$EXTERNALSYM smNoBoardSRsrc}
smNoBoardSRsrc = -313; //*No Board sResource.*/
{$EXTERNALSYM smGetPRErr}
smGetPRErr = -314; //*Error occurred during _sGetPRAMRec (See SIMStatus).*/
{$EXTERNALSYM smNoBoardId}
smNoBoardId = -315; //*No Board Id.*/
{$EXTERNALSYM smInitStatVErr}
smInitStatVErr = -316; //*The InitStatusV field was negative after primary or secondary init.*/
{$EXTERNALSYM smInitTblVErr}
smInitTblVErr = -317; //*An error occurred while trying to initialize the Slot Resource Table.*/
{$EXTERNALSYM smNoJmpTbl}
smNoJmpTbl = -318; //*SDM jump table could not be created.*/
{$EXTERNALSYM smReservedSlot}
smReservedSlot = -318; //*slot is reserved, VM should not use this address space.*/
{$EXTERNALSYM smBadBoardId}
smBadBoardId = -319; //*BoardId was wrong; re-init the PRAM record.*/
{$EXTERNALSYM smBusErrTO}
smBusErrTO = -320; //*BusError time out.*/
//* These errors are logged in the vendor status field of the sInfo record. */
{$EXTERNALSYM svTempDisable}
svTempDisable = -32768; //*Temporarily disable card but run primary init.*/
{$EXTERNALSYM svDisabled}
svDisabled = -32640; //*Reserve range -32640 to -32768 for Apple temp disables.*/
{$EXTERNALSYM smBadRefId}
smBadRefId = -330; //*Reference Id not found in List*/
{$EXTERNALSYM smBadsList}
smBadsList = -331; //*Bad sList: Id1 < Id2 < Id3 ...format is not followed.*/
{$EXTERNALSYM smReservedErr}
smReservedErr = -332; //*Reserved field not zero*/
{$EXTERNALSYM smCodeRevErr}
smCodeRevErr = -333; //*Code revision is wrong*/
//};
//enum {
{$EXTERNALSYM smCPUErr}
smCPUErr = -334; //*Code revision is wrong*/
{$EXTERNALSYM smsPointerNil}
smsPointerNil = -335; //*LPointer is nil From sOffsetData. If this error occurs; check sInfo rec for more information.*/
{$EXTERNALSYM smNilsBlockErr}
smNilsBlockErr = -336; //*Nil sBlock error (Don't allocate and try to use a nil sBlock)*/
{$EXTERNALSYM smSlotOOBErr}
smSlotOOBErr = -337; //*Slot out of bounds error*/
{$EXTERNALSYM smSelOOBErr}
smSelOOBErr = -338; //*Selector out of bounds error*/
{$EXTERNALSYM smNewPErr}
smNewPErr = -339; //*_NewPtr error*/
{$EXTERNALSYM smBlkMoveErr}
smBlkMoveErr = -340; //*_BlockMove error*/
{$EXTERNALSYM smCkStatusErr}
smCkStatusErr = -341; //*Status of slot = fail.*/
{$EXTERNALSYM smGetDrvrNamErr}
smGetDrvrNamErr = -342; //*Error occurred during _sGetDrvrName.*/
{$EXTERNALSYM smDisDrvrNamErr}
smDisDrvrNamErr = -343; //*Error occurred during _sDisDrvrName.*/
{$EXTERNALSYM smNoMoresRsrcs}
smNoMoresRsrcs = -344; //*No more sResources*/
{$EXTERNALSYM smsGetDrvrErr}
smsGetDrvrErr = -345; //*Error occurred during _sGetDriver.*/
{$EXTERNALSYM smBadsPtrErr}
smBadsPtrErr = -346; //*Bad pointer was passed to sCalcsPointer*/
{$EXTERNALSYM smByteLanesErr}
smByteLanesErr = -347; //*NumByteLanes was determined to be zero.*/
{$EXTERNALSYM smOffsetErr}
smOffsetErr = -348; //*Offset was too big (temporary error*/
{$EXTERNALSYM smNoGoodOpens}
smNoGoodOpens = -349; //*No opens were successfull in the loop.*/
{$EXTERNALSYM smSRTOvrFlErr}
smSRTOvrFlErr = -350; //*SRT over flow.*/
{$EXTERNALSYM smRecNotFnd}
smRecNotFnd = -351; //*Record not found in the SRT.*/
//};
//enum {
//*Dictionary Manager errors*/
{$EXTERNALSYM notBTree}
notBTree = -410; //*The file is not a dictionary.*/
{$EXTERNALSYM btNoSpace}
btNoSpace = -413; //*Can't allocate disk space.*/
{$EXTERNALSYM btDupRecErr}
btDupRecErr = -414; //*Record already exists.*/
{$EXTERNALSYM btRecNotFnd}
btRecNotFnd = -415; //*Record cannot be found.*/
{$EXTERNALSYM btKeyLenErr}
btKeyLenErr = -416; //*Maximum key length is too long or equal to zero.*/
{$EXTERNALSYM btKeyAttrErr}
btKeyAttrErr = -417; //*There is no such a key attribute.*/
{$EXTERNALSYM unknownInsertModeErr}
unknownInsertModeErr = -20000; //*There is no such an insert mode.*/
{$EXTERNALSYM recordDataTooBigErr}
recordDataTooBigErr = -20001; //*The record data is bigger than buffer size (1024 bytes).*/
{$EXTERNALSYM invalidIndexErr}
invalidIndexErr = -20002; //*The recordIndex parameter is not valid.*/
//};
{*
* Error codes from FSM functions
*}
//enum {
{$EXTERNALSYM fsmFFSNotFoundErr}
fsmFFSNotFoundErr = -431; //* Foreign File system does not exist - new Pack2 could return this error too */
{$EXTERNALSYM fsmBusyFFSErr}
fsmBusyFFSErr = -432; //* File system is busy, cannot be removed */
{$EXTERNALSYM fsmBadFFSNameErr}
fsmBadFFSNameErr = -433; //* Name length not 1 <= length <= 31 */
{$EXTERNALSYM fsmBadFSDLenErr}
fsmBadFSDLenErr = -434; //* FSD size incompatible with current FSM vers */
{$EXTERNALSYM fsmDuplicateFSIDErr}
fsmDuplicateFSIDErr = -435; //* FSID already exists on InstallFS */
{$EXTERNALSYM fsmBadFSDVersionErr}
fsmBadFSDVersionErr = -436; //* FSM version incompatible with FSD */
{$EXTERNALSYM fsmNoAlternateStackErr}
fsmNoAlternateStackErr = -437; //* no alternate stack for HFS CI */
{$EXTERNALSYM fsmUnknownFSMMessageErr}
fsmUnknownFSMMessageErr = -438; //* unknown message passed to FSM */
//};
//enum {
//* Edition Mgr errors*/
{$EXTERNALSYM editionMgrInitErr}
editionMgrInitErr = -450; //*edition manager not inited by this app*/
{$EXTERNALSYM badSectionErr}
badSectionErr = -451; //*not a valid SectionRecord*/
{$EXTERNALSYM notRegisteredSectionErr}
notRegisteredSectionErr = -452; //*not a registered SectionRecord*/
{$EXTERNALSYM badEditionFileErr}
badEditionFileErr = -453; //*edition file is corrupt*/
{$EXTERNALSYM badSubPartErr}
badSubPartErr = -454; //*can not use sub parts in this release*/
{$EXTERNALSYM multiplePublisherWrn}
multiplePublisherWrn = -460; //*A Publisher is already registered for that container*/
{$EXTERNALSYM containerNotFoundWrn}
containerNotFoundWrn = -461; //*could not find editionContainer at this time*/
{$EXTERNALSYM containerAlreadyOpenWrn}
containerAlreadyOpenWrn = -462; //*container already opened by this section*/
{$EXTERNALSYM notThePublisherWrn}
notThePublisherWrn = -463; //*not the first registered publisher for that container*/
//};
//enum {
{$EXTERNALSYM teScrapSizeErr}
teScrapSizeErr = -501; //*scrap item too big for text edit record*/
{$EXTERNALSYM hwParamErr}
hwParamErr = -502; //*bad selector for _HWPriv*/
{$EXTERNALSYM driverHardwareGoneErr}
driverHardwareGoneErr = -503; //*disk driver's hardware was disconnected*/
//};
//enum {
//*Process Manager errors*/
{$EXTERNALSYM procNotFound}
procNotFound = -600; //*no eligible process with specified descriptor*/
{$EXTERNALSYM memFragErr}
memFragErr = -601; //*not enough room to launch app w/special requirements*/
{$EXTERNALSYM appModeErr}
appModeErr = -602; //*memory mode is 32-bit, but app not 32-bit clean*/
{$EXTERNALSYM protocolErr}
protocolErr = -603; //*app made module calls in improper order*/
{$EXTERNALSYM hardwareConfigErr}
hardwareConfigErr = -604; //*hardware configuration not correct for call*/
{$EXTERNALSYM appMemFullErr}
appMemFullErr = -605; //*application SIZE not big enough for launch*/
{$EXTERNALSYM appIsDaemon}
appIsDaemon = -606; //*app is BG-only, and launch flags disallow this*/
{$EXTERNALSYM bufferIsSmall}
bufferIsSmall = -607; //*error returns from Post and Accept */
{$EXTERNALSYM noOutstandingHLE}
noOutstandingHLE = -608;
{$EXTERNALSYM connectionInvalid}
connectionInvalid = -609;
{$EXTERNALSYM noUserInteractionAllowed}
noUserInteractionAllowed = -610; //* no user interaction allowed */
//};
//enum {
//* More Process Manager errors */
{$EXTERNALSYM wrongApplicationPlatform}
wrongApplicationPlatform = -875; //* The application could not launch because the required platform is not available */
{$EXTERNALSYM appVersionTooOld}
appVersionTooOld = -876; //* The application's creator and version are incompatible with the current version of Mac OS. */
{$EXTERNALSYM notAppropriateForClassic}
notAppropriateForClassic = -877; //* This application won't or shouldn't run on Classic (Problem 2481058). */
//};
//* Thread Manager Error Codes */
//enum {
{$EXTERNALSYM threadTooManyReqsErr}
threadTooManyReqsErr = -617;
{$EXTERNALSYM threadNotFoundErr}
threadNotFoundErr = -618;
{$EXTERNALSYM threadProtocolErr}
threadProtocolErr = -619;
//};
//enum {
{$EXTERNALSYM threadBadAppContextErr}
threadBadAppContextErr = -616;
//};
//*MemoryDispatch errors*/
//enum {
{$EXTERNALSYM notEnoughMemoryErr}
notEnoughMemoryErr = -620; //*insufficient physical memory*/
{$EXTERNALSYM notHeldErr}
notHeldErr = -621; //*specified range of memory is not held*/
{$EXTERNALSYM cannotMakeContiguousErr}
cannotMakeContiguousErr = -622; //*cannot make specified range contiguous*/
{$EXTERNALSYM notLockedErr}
notLockedErr = -623; //*specified range of memory is not locked*/
{$EXTERNALSYM interruptsMaskedErr}
interruptsMaskedErr = -624; //*don’t call with interrupts masked*/
{$EXTERNALSYM cannotDeferErr}
cannotDeferErr = -625; //*unable to defer additional functions*/
{$EXTERNALSYM noMMUErr}
noMMUErr = -626; //*no MMU present*/
//};
//* Internal VM error codes returned in pVMGLobals (b78) if VM doesn't load */
//enum {
{$EXTERNALSYM vmMorePhysicalThanVirtualErr}
vmMorePhysicalThanVirtualErr = -628; //*VM could not start because there was more physical memory than virtual memory (bad setting in VM config resource)*/
{$EXTERNALSYM vmKernelMMUInitErr}
vmKernelMMUInitErr = -629; //*VM could not start because VM_MMUInit kernel call failed*/
{$EXTERNALSYM vmOffErr}
vmOffErr = -630; //*VM was configured off, or command key was held down at boot*/
{$EXTERNALSYM vmMemLckdErr}
vmMemLckdErr = -631; //*VM could not start because of a lock table conflict (only on non-SuperMario ROMs)*/
{$EXTERNALSYM vmBadDriver}
vmBadDriver = -632; //*VM could not start because the driver was incompatible*/
{$EXTERNALSYM vmNoVectorErr}
vmNoVectorErr = -633; //*VM could not start because the vector code could not load*/
//};
///* FileMapping errors */
//enum {
{$EXTERNALSYM vmInvalidBackingFileIDErr}
vmInvalidBackingFileIDErr = -640; //* invalid BackingFileID */
{$EXTERNALSYM vmMappingPrivilegesErr}
vmMappingPrivilegesErr = -641; //* requested MappingPrivileges cannot be obtained */
{$EXTERNALSYM vmBusyBackingFileErr}
vmBusyBackingFileErr = -642; //* open views found on BackingFile */
{$EXTERNALSYM vmNoMoreBackingFilesErr}
vmNoMoreBackingFilesErr = -643; //* no more BackingFiles were found */
{$EXTERNALSYM vmInvalidFileViewIDErr}
vmInvalidFileViewIDErr = -644; //*invalid FileViewID */
{$EXTERNALSYM vmFileViewAccessErr}
vmFileViewAccessErr = -645; //* requested FileViewAccess cannot be obtained */
{$EXTERNALSYM vmNoMoreFileViewsErr}
vmNoMoreFileViewsErr = -646; //* no more FileViews were found */
{$EXTERNALSYM vmAddressNotInFileViewErr}
vmAddressNotInFileViewErr = -647; //* address is not in a FileView */
{$EXTERNALSYM vmInvalidOwningProcessErr}
vmInvalidOwningProcessErr = -648; //* current process does not own the BackingFileID or FileViewID */
//};
//* Database access error codes */
//enum {
{$EXTERNALSYM rcDBNull}
rcDBNull = -800;
{$EXTERNALSYM rcDBValue}
rcDBValue = -801;
{$EXTERNALSYM rcDBError}
rcDBError = -802;
{$EXTERNALSYM rcDBBadType}
rcDBBadType = -803;
{$EXTERNALSYM rcDBBreak}
rcDBBreak = -804;
{$EXTERNALSYM rcDBExec}
rcDBExec = -805;
{$EXTERNALSYM rcDBBadSessID}
rcDBBadSessID = -806;
{$EXTERNALSYM rcDBBadSessNum}
rcDBBadSessNum = -807; //* bad session number for DBGetConnInfo */
{$EXTERNALSYM rcDBBadDDEV}
rcDBBadDDEV = -808; //* bad ddev specified on DBInit */
{$EXTERNALSYM rcDBAsyncNotSupp}
rcDBAsyncNotSupp = -809; //* ddev does not support async calls */
{$EXTERNALSYM rcDBBadAsyncPB}
rcDBBadAsyncPB = -810; //* tried to kill a bad pb */
{$EXTERNALSYM rcDBNoHandler}
rcDBNoHandler = -811; //* no app handler for specified data type */
{$EXTERNALSYM rcDBWrongVersion}
rcDBWrongVersion = -812; //* incompatible versions */
{$EXTERNALSYM rcDBPackNotInited}
rcDBPackNotInited = -813; //* attempt to call other routine before InitDBPack */
//};
//*Help Mgr error range: -850 to -874*/
//enum {
{$EXTERNALSYM hmHelpDisabled}
hmHelpDisabled = -850; //* Show Balloons mode was off, call to routine ignored */
{$EXTERNALSYM hmBalloonAborted}
hmBalloonAborted = -853; //* Returned if mouse was moving or mouse wasn't in window port rect */
{$EXTERNALSYM hmSameAsLastBalloon}
hmSameAsLastBalloon = -854; //* Returned from HMShowMenuBalloon if menu & item is same as last time */
{$EXTERNALSYM hmHelpManagerNotInited}
hmHelpManagerNotInited = -855; //* Returned from HMGetHelpMenuHandle if help menu not setup */
{$EXTERNALSYM hmSkippedBalloon}
hmSkippedBalloon = -857; //* Returned from calls if helpmsg specified a skip balloon */
{$EXTERNALSYM hmWrongVersion}
hmWrongVersion = -858; //* Returned if help mgr resource was the wrong version */
{$EXTERNALSYM hmUnknownHelpType}
hmUnknownHelpType = -859; //* Returned if help msg record contained a bad type */
{$EXTERNALSYM hmOperationUnsupported}
hmOperationUnsupported = -861; //* Returned from HMShowBalloon call if bad method passed to routine */
{$EXTERNALSYM hmNoBalloonUp}
hmNoBalloonUp = -862; //* Returned from HMRemoveBalloon if no balloon was visible when call was made */
{$EXTERNALSYM hmCloseViewActive}
hmCloseViewActive = -863; //* Returned from HMRemoveBalloon if CloseView was active */
//};
//enum {
//*PPC errors*/
{$EXTERNALSYM notInitErr}
notInitErr = -900; //*PPCToolBox not initialized*/
{$EXTERNALSYM nameTypeErr}
nameTypeErr = -902; //*Invalid or inappropriate locationKindSelector in locationName*/
{$EXTERNALSYM noPortErr}
noPortErr = -903; //*Unable to open port or bad portRefNum. If you're calling */
//* AESend, this is because your application does not have */
//* the isHighLevelEventAware bit set in your SIZE resource. */
{$EXTERNALSYM noGlobalsErr}
noGlobalsErr = -904; //*The system is hosed, better re-boot*/
{$EXTERNALSYM localOnlyErr}
localOnlyErr = -905; //*Network activity is currently disabled*/
{$EXTERNALSYM destPortErr}
destPortErr = -906; //*Port does not exist at destination*/
{$EXTERNALSYM sessTableErr}
sessTableErr = -907; //*Out of session tables, try again later*/
{$EXTERNALSYM noSessionErr}
noSessionErr = -908; //*Invalid session reference number*/
{$EXTERNALSYM badReqErr}
badReqErr = -909; //*bad parameter or invalid state for operation*/
{$EXTERNALSYM portNameExistsErr}
portNameExistsErr = -910; //*port is already open (perhaps in another app)*/
{$EXTERNALSYM noUserNameErr}
noUserNameErr = -911; //*user name unknown on destination machine*/
{$EXTERNALSYM userRejectErr}
userRejectErr = -912; //*Destination rejected the session request*/
{$EXTERNALSYM noMachineNameErr}
noMachineNameErr = -913; //*user hasn't named his Macintosh in the Network Setup Control Panel*/
{$EXTERNALSYM noToolboxNameErr}
noToolboxNameErr = -914; //*A system resource is missing, not too likely*/
{$EXTERNALSYM noResponseErr}
noResponseErr = -915; //*unable to contact destination*/
{$EXTERNALSYM portClosedErr}
portClosedErr = -916; //*port was closed*/
{$EXTERNALSYM sessClosedErr}
sessClosedErr = -917; //*session was closed*/
{$EXTERNALSYM badPortNameErr}
badPortNameErr = -919; //*PPCPortRec malformed*/
{$EXTERNALSYM noDefaultUserErr}
noDefaultUserErr = -922; //*user hasn't typed in owners name in Network Setup Control Pannel*/
{$EXTERNALSYM notLoggedInErr}
notLoggedInErr = -923; //*The default userRefNum does not yet exist*/
{$EXTERNALSYM noUserRefErr}
noUserRefErr = -924; //*unable to create a new userRefNum*/
{$EXTERNALSYM networkErr}
networkErr = -925; //*An error has occurred in the network, not too likely*/
{$EXTERNALSYM noInformErr}
noInformErr = -926; //*PPCStart failed because destination did not have inform pending*/
{$EXTERNALSYM authFailErr}
authFailErr = -927; //*unable to authenticate user at destination*/
{$EXTERNALSYM noUserRecErr}
noUserRecErr = -928; //*Invalid user reference number*/
{$EXTERNALSYM badServiceMethodErr}
badServiceMethodErr = -930; //*illegal service type, or not supported*/
{$EXTERNALSYM badLocNameErr}
badLocNameErr = -931; //*location name malformed*/
{$EXTERNALSYM guestNotAllowedErr}
guestNotAllowedErr = -932; //*destination port requires authentication*/
//};
//* Font Mgr errors*/
//enum {
{$EXTERNALSYM kFMIterationCompleted}
kFMIterationCompleted = -980;
{$EXTERNALSYM kFMInvalidFontFamilyErr}
kFMInvalidFontFamilyErr = -981;
{$EXTERNALSYM kFMInvalidFontErr}
kFMInvalidFontErr = -982;
{$EXTERNALSYM kFMIterationScopeModifiedErr}
kFMIterationScopeModifiedErr = -983;
{$EXTERNALSYM kFMFontTableAccessErr}
kFMFontTableAccessErr = -984;
{$EXTERNALSYM kFMFontContainerAccessErr}
kFMFontContainerAccessErr = -985;
//};
//enum {
{$EXTERNALSYM noMaskFoundErr}
noMaskFoundErr = -1000; //*Icon Utilties Error*/
//};
//enum {
{$EXTERNALSYM nbpBuffOvr}
nbpBuffOvr = -1024; //*Buffer overflow in LookupName*/
{$EXTERNALSYM nbpNoConfirm}
nbpNoConfirm = -1025;
{$EXTERNALSYM nbpConfDiff}
nbpConfDiff = -1026; //*Name confirmed at different socket*/
{$EXTERNALSYM nbpDuplicate}
nbpDuplicate = -1027; //*Duplicate name exists already*/
{$EXTERNALSYM nbpNotFound}
nbpNotFound = -1028; //*Name not found on remove*/
{$EXTERNALSYM nbpNISErr}
nbpNISErr = -1029; //*Error trying to open the NIS*/
//};
//enum {
{$EXTERNALSYM aspBadVersNum}
aspBadVersNum = -1066; //*Server cannot support this ASP version*/
{$EXTERNALSYM aspBufTooSmall}
aspBufTooSmall = -1067; //*Buffer too small*/
{$EXTERNALSYM aspNoMoreSess}
aspNoMoreSess = -1068; //*No more sessions on server*/
{$EXTERNALSYM aspNoServers}
aspNoServers = -1069; //*No servers at that address*/
{$EXTERNALSYM aspParamErr}
aspParamErr = -1070; //*Parameter error*/
{$EXTERNALSYM aspServerBusy}
aspServerBusy = -1071; //*Server cannot open another session*/
{$EXTERNALSYM aspSessClosed}
aspSessClosed = -1072; //*Session closed*/
{$EXTERNALSYM aspSizeErr}
aspSizeErr = -1073; //*Command block too big*/
{$EXTERNALSYM aspTooMany}
aspTooMany = -1074; //*Too many clients (server error)*/
{$EXTERNALSYM aspNoAck}
aspNoAck = -1075; //*No ack on attention request (server err)*/
//};
//enum {
{$EXTERNALSYM reqFailed}
reqFailed = -1096;
{$EXTERNALSYM tooManyReqs}
tooManyReqs = -1097;
{$EXTERNALSYM tooManySkts}
tooManySkts = -1098;
{$EXTERNALSYM badATPSkt}
badATPSkt = -1099;
{$EXTERNALSYM badBuffNum}
badBuffNum = -1100;
{$EXTERNALSYM noRelErr}
noRelErr = -1101;
{$EXTERNALSYM cbNotFound}
cbNotFound = -1102;
{$EXTERNALSYM noSendResp}
noSendResp = -1103;
{$EXTERNALSYM noDataArea}
noDataArea = -1104;
{$EXTERNALSYM reqAborted}
reqAborted = -1105;
//};
//* ADSP Error Codes */
//enum {
//* driver control ioResults */
{$EXTERNALSYM errRefNum}
errRefNum = -1280; //* bad connection refNum */
{$EXTERNALSYM errAborted}
errAborted = -1279; //* control call was aborted */
{$EXTERNALSYM errState}
errState = -1278; //* bad connection state for this operation */
{$EXTERNALSYM errOpening}
errOpening = -1277; //* open connection request failed */
{$EXTERNALSYM errAttention}
errAttention = -1276; //* attention message too long */
{$EXTERNALSYM errFwdReset}
errFwdReset = -1275; //* read terminated by forward reset */
{$EXTERNALSYM errDSPQueueSize}
errDSPQueueSize = -1274; //* DSP Read/Write Queue Too small */
{$EXTERNALSYM errOpenDenied}
errOpenDenied = -1273; //* open connection request was denied */
//};
{*--------------------------------------------------------------
Apple event manager error messages
--------------------------------------------------------------*}
//enum {
{$EXTERNALSYM errAECoercionFail}
errAECoercionFail = -1700; //* bad parameter data or unable to coerce the data supplied */
{$EXTERNALSYM errAEDescNotFound}
errAEDescNotFound = -1701;
{$EXTERNALSYM errAECorruptData}
errAECorruptData = -1702;
{$EXTERNALSYM errAEWrongDataType}
errAEWrongDataType = -1703;
{$EXTERNALSYM errAENotAEDesc}
errAENotAEDesc = -1704;
{$EXTERNALSYM errAEBadListItem}
errAEBadListItem = -1705; //* the specified list item does not exist */
{$EXTERNALSYM errAENewerVersion}
errAENewerVersion = -1706; //* need newer version of the AppleEvent manager */
{$EXTERNALSYM errAENotAppleEvent}
errAENotAppleEvent = -1707; //* the event is not in AppleEvent format */
{$EXTERNALSYM errAEEventNotHandled}
errAEEventNotHandled = -1708; //* the AppleEvent was not handled by any handler */
{$EXTERNALSYM errAEReplyNotValid}
errAEReplyNotValid = -1709; //* AEResetTimer was passed an invalid reply parameter */
{$EXTERNALSYM errAEUnknownSendMode}
errAEUnknownSendMode = -1710; //* mode wasn't NoReply, WaitReply, or QueueReply or Interaction level is unknown */
{$EXTERNALSYM errAEWaitCanceled}
errAEWaitCanceled = -1711; //* in AESend, the user cancelled out of wait loop for reply or receipt */
{$EXTERNALSYM errAETimeout}
errAETimeout = -1712; //* the AppleEvent timed out */
{$EXTERNALSYM errAENoUserInteraction}
errAENoUserInteraction = -1713; //* no user interaction is allowed */
{$EXTERNALSYM errAENotASpecialFunction}
errAENotASpecialFunction = -1714; //* there is no special function for/with this keyword */
{$EXTERNALSYM errAEParamMissed}
errAEParamMissed = -1715; //* a required parameter was not accessed */
{$EXTERNALSYM errAEUnknownAddressType}
errAEUnknownAddressType = -1716; //* the target address type is not known */
{$EXTERNALSYM errAEHandlerNotFound}
errAEHandlerNotFound = -1717; //* no handler in the dispatch tables fits the parameters to AEGetEventHandler or AEGetCoercionHandler */
{$EXTERNALSYM errAEReplyNotArrived}
errAEReplyNotArrived = -1718; //* the contents of the reply you are accessing have not arrived yet */
{$EXTERNALSYM errAEIllegalIndex}
errAEIllegalIndex = -1719; //* index is out of range in a put operation */
{$EXTERNALSYM errAEImpossibleRange}
errAEImpossibleRange = -1720; //* A range like 3rd to 2nd, or 1st to all. */
{$EXTERNALSYM errAEWrongNumberArgs}
errAEWrongNumberArgs = -1721; //* Logical op kAENOT used with other than 1 term */
{$EXTERNALSYM errAEAccessorNotFound}
errAEAccessorNotFound = -1723; //* Accessor proc matching wantClass and containerType or wildcards not found */
{$EXTERNALSYM errAENoSuchLogical}
errAENoSuchLogical = -1725; //* Something other than AND, OR, or NOT */
{$EXTERNALSYM errAEBadTestKey}
errAEBadTestKey = -1726; //* Test is neither typeLogicalDescriptor nor typeCompDescriptor */
{$EXTERNALSYM errAENotAnObjSpec}
errAENotAnObjSpec = -1727; //* Param to AEResolve not of type 'obj ' */
{$EXTERNALSYM errAENoSuchObject}
errAENoSuchObject = -1728; //* e.g.,: specifier asked for the 3rd, but there are only 2. Basically, this indicates a run-time resolution error. */
{$EXTERNALSYM errAENegativeCount}
errAENegativeCount = -1729; //* CountProc returned negative value */
{$EXTERNALSYM errAEEmptyListContainer}
errAEEmptyListContainer = -1730; //* Attempt to pass empty list as container to accessor */
{$EXTERNALSYM errAEUnknownObjectType}
errAEUnknownObjectType = -1731; //* available only in version 1.0.1 or greater */
{$EXTERNALSYM errAERecordingIsAlreadyOn}
errAERecordingIsAlreadyOn = -1732; //* available only in version 1.0.1 or greater */
{$EXTERNALSYM errAEReceiveTerminate}
errAEReceiveTerminate = -1733; //* break out of all levels of AEReceive to the topmost (1.1 or greater) */
{$EXTERNALSYM errAEReceiveEscapeCurrent}
errAEReceiveEscapeCurrent = -1734; //* break out of only lowest level of AEReceive (1.1 or greater) */
{$EXTERNALSYM errAEEventFiltered}
errAEEventFiltered = -1735; //* event has been filtered, and should not be propogated (1.1 or greater) */
{$EXTERNALSYM errAEDuplicateHandler}
errAEDuplicateHandler = -1736; //* attempt to install handler in table for identical class and id (1.1 or greater) */
{$EXTERNALSYM errAEStreamBadNesting}
errAEStreamBadNesting = -1737; //* nesting violation while streaming */
{$EXTERNALSYM errAEStreamAlreadyConverted}
errAEStreamAlreadyConverted = -1738; //* attempt to convert a stream that has already been converted */
{$EXTERNALSYM errAEDescIsNull}
errAEDescIsNull = -1739; //* attempting to perform an invalid operation on a null descriptor */
{$EXTERNALSYM errAEBuildSyntaxError}
errAEBuildSyntaxError = -1740; //* AEBuildDesc and friends detected a syntax error */
{$EXTERNALSYM errAEBufferTooSmall}
errAEBufferTooSmall = -1741; //* buffer for AEFlattenDesc too small */
//};
//enum {
{$EXTERNALSYM errOSASystemError}
errOSASystemError = -1750;
{$EXTERNALSYM errOSAInvalidID}
errOSAInvalidID = -1751;
{$EXTERNALSYM errOSABadStorageType}
errOSABadStorageType = -1752;
{$EXTERNALSYM errOSAScriptError}
errOSAScriptError = -1753;
{$EXTERNALSYM errOSABadSelector}
errOSABadSelector = -1754;
{$EXTERNALSYM errOSASourceNotAvailable}
errOSASourceNotAvailable = -1756;
{$EXTERNALSYM errOSANoSuchDialect}
errOSANoSuchDialect = -1757;
{$EXTERNALSYM errOSADataFormatObsolete}
errOSADataFormatObsolete = -1758;
{$EXTERNALSYM errOSADataFormatTooNew}
errOSADataFormatTooNew = -1759;
{$EXTERNALSYM errOSACorruptData}
errOSACorruptData = errAECorruptData;
{$EXTERNALSYM errOSARecordingIsAlreadyOn}
errOSARecordingIsAlreadyOn = errAERecordingIsAlreadyOn;
{$EXTERNALSYM errOSAComponentMismatch}
errOSAComponentMismatch = -1761; //* Parameters are from 2 different components */
{$EXTERNALSYM errOSACantOpenComponent}
errOSACantOpenComponent = -1762; //* Can't connect to scripting system with that ID */
//};
//* AppleEvent error definitions */
//enum {
{$EXTERNALSYM errOffsetInvalid}
errOffsetInvalid = -1800;
{$EXTERNALSYM errOffsetIsOutsideOfView}
errOffsetIsOutsideOfView = -1801;
{$EXTERNALSYM errTopOfDocument}
errTopOfDocument = -1810;
{$EXTERNALSYM errTopOfBody}
errTopOfBody = -1811;
{$EXTERNALSYM errEndOfDocument}
errEndOfDocument = -1812;
{$EXTERNALSYM errEndOfBody}
errEndOfBody = -1813;
//};
//enum {
//* Drag Manager error codes */
{$EXTERNALSYM badDragRefErr}
badDragRefErr = -1850; //* unknown drag reference */
{$EXTERNALSYM badDragItemErr}
badDragItemErr = -1851; //* unknown drag item reference */
{$EXTERNALSYM badDragFlavorErr}
badDragFlavorErr = -1852; //* unknown flavor type */
{$EXTERNALSYM duplicateFlavorErr}
duplicateFlavorErr = -1853; //* flavor type already exists */
{$EXTERNALSYM cantGetFlavorErr}
cantGetFlavorErr = -1854; //* error while trying to get flavor data */
{$EXTERNALSYM duplicateHandlerErr}
duplicateHandlerErr = -1855; //* handler already exists */
{$EXTERNALSYM handlerNotFoundErr}
handlerNotFoundErr = -1856; //* handler not found */
{$EXTERNALSYM dragNotAcceptedErr}
dragNotAcceptedErr = -1857; //* drag was not accepted by receiver */
{$EXTERNALSYM unsupportedForPlatformErr}
unsupportedForPlatformErr = -1858; //* call is for PowerPC only */
{$EXTERNALSYM noSuitableDisplaysErr}
noSuitableDisplaysErr = -1859; //* no displays support translucency */
{$EXTERNALSYM badImageRgnErr}
badImageRgnErr = -1860; //* bad translucent image region */
{$EXTERNALSYM badImageErr}
badImageErr = -1861; //* bad translucent image PixMap */
{$EXTERNALSYM nonDragOriginatorErr}
nonDragOriginatorErr = -1862; //* illegal attempt at originator only data */
//};
//*QuickTime errors*/
//enum {
{$EXTERNALSYM couldNotResolveDataRef}
couldNotResolveDataRef = -2000;
{$EXTERNALSYM badImageDescription}
badImageDescription = -2001;
{$EXTERNALSYM badPublicMovieAtom}
badPublicMovieAtom = -2002;
{$EXTERNALSYM cantFindHandler}
cantFindHandler = -2003;
{$EXTERNALSYM cantOpenHandler}
cantOpenHandler = -2004;
{$EXTERNALSYM badComponentType}
badComponentType = -2005;
{$EXTERNALSYM noMediaHandler}
noMediaHandler = -2006;
{$EXTERNALSYM noDataHandler}
noDataHandler = -2007;
{$EXTERNALSYM invalidMedia}
invalidMedia = -2008;
{$EXTERNALSYM invalidTrack}
invalidTrack = -2009;
{$EXTERNALSYM invalidMovie}
invalidMovie = -2010;
{$EXTERNALSYM invalidSampleTable}
invalidSampleTable = -2011;
{$EXTERNALSYM invalidDataRef}
invalidDataRef = -2012;
{$EXTERNALSYM invalidHandler}
invalidHandler = -2013;
{$EXTERNALSYM invalidDuration}
invalidDuration = -2014;
{$EXTERNALSYM invalidTime}
invalidTime = -2015;
{$EXTERNALSYM cantPutPublicMovieAtom}
cantPutPublicMovieAtom = -2016;
{$EXTERNALSYM badEditList}
badEditList = -2017;
{$EXTERNALSYM mediaTypesDontMatch}
mediaTypesDontMatch = -2018;
{$EXTERNALSYM progressProcAborted}
progressProcAborted = -2019;
{$EXTERNALSYM movieToolboxUninitialized}
movieToolboxUninitialized = -2020;
{$EXTERNALSYM noRecordOfApp}
noRecordOfApp = movieToolboxUninitialized; //* replica */
{$EXTERNALSYM wfFileNotFound}
wfFileNotFound = -2021;
{$EXTERNALSYM cantCreateSingleForkFile}
cantCreateSingleForkFile = -2022; //* happens when file already exists */
{$EXTERNALSYM invalidEditState}
invalidEditState = -2023;
{$EXTERNALSYM nonMatchingEditState}
nonMatchingEditState = -2024;
{$EXTERNALSYM staleEditState}
staleEditState = -2025;
{$EXTERNALSYM userDataItemNotFound}
userDataItemNotFound = -2026;
{$EXTERNALSYM maxSizeToGrowTooSmall}
maxSizeToGrowTooSmall = -2027;
{$EXTERNALSYM badTrackIndex}
badTrackIndex = -2028;
{$EXTERNALSYM trackIDNotFound}
trackIDNotFound = -2029;
{$EXTERNALSYM trackNotInMovie}
trackNotInMovie = -2030;
{$EXTERNALSYM timeNotInTrack}
timeNotInTrack = -2031;
{$EXTERNALSYM timeNotInMedia}
timeNotInMedia = -2032;
{$EXTERNALSYM badEditIndex}
badEditIndex = -2033;
{$EXTERNALSYM internalQuickTimeError}
internalQuickTimeError = -2034;
{$EXTERNALSYM cantEnableTrack}
cantEnableTrack = -2035;
{$EXTERNALSYM invalidRect}
invalidRect = -2036;
{$EXTERNALSYM invalidSampleNum}
invalidSampleNum = -2037;
{$EXTERNALSYM invalidChunkNum}
invalidChunkNum = -2038;
{$EXTERNALSYM invalidSampleDescIndex}
invalidSampleDescIndex = -2039;
{$EXTERNALSYM invalidChunkCache}
invalidChunkCache = -2040;
{$EXTERNALSYM invalidSampleDescription}
invalidSampleDescription = -2041;
{$EXTERNALSYM dataNotOpenForRead}
dataNotOpenForRead = -2042;
{$EXTERNALSYM dataNotOpenForWrite}
dataNotOpenForWrite = -2043;
{$EXTERNALSYM dataAlreadyOpenForWrite}
dataAlreadyOpenForWrite = -2044;
{$EXTERNALSYM dataAlreadyClosed}
dataAlreadyClosed = -2045;
{$EXTERNALSYM endOfDataReached}
endOfDataReached = -2046;
{$EXTERNALSYM dataNoDataRef}
dataNoDataRef = -2047;
{$EXTERNALSYM noMovieFound}
noMovieFound = -2048;
{$EXTERNALSYM invalidDataRefContainer}
invalidDataRefContainer = -2049;
{$EXTERNALSYM badDataRefIndex}
badDataRefIndex = -2050;
{$EXTERNALSYM noDefaultDataRef}
noDefaultDataRef = -2051;
{$EXTERNALSYM couldNotUseAnExistingSample}
couldNotUseAnExistingSample = -2052;
{$EXTERNALSYM featureUnsupported}
featureUnsupported = -2053;
{$EXTERNALSYM noVideoTrackInMovieErr}
noVideoTrackInMovieErr = -2054; //* QT for Windows error */
{$EXTERNALSYM noSoundTrackInMovieErr}
noSoundTrackInMovieErr = -2055; //* QT for Windows error */
{$EXTERNALSYM soundSupportNotAvailableErr}
soundSupportNotAvailableErr = -2056; //* QT for Windows error */
{$EXTERNALSYM unsupportedAuxiliaryImportData}
unsupportedAuxiliaryImportData = -2057;
{$EXTERNALSYM auxiliaryExportDataUnavailable}
auxiliaryExportDataUnavailable = -2058;
{$EXTERNALSYM samplesAlreadyInMediaErr}
samplesAlreadyInMediaErr = -2059;
{$EXTERNALSYM noSourceTreeFoundErr}
noSourceTreeFoundErr = -2060;
{$EXTERNALSYM sourceNotFoundErr}
sourceNotFoundErr = -2061;
{$EXTERNALSYM movieTextNotFoundErr}
movieTextNotFoundErr = -2062;
{$EXTERNALSYM missingRequiredParameterErr}
missingRequiredParameterErr = -2063;
{$EXTERNALSYM invalidSpriteWorldPropertyErr}
invalidSpriteWorldPropertyErr = -2064;
{$EXTERNALSYM invalidSpritePropertyErr}
invalidSpritePropertyErr = -2065;
{$EXTERNALSYM gWorldsNotSameDepthAndSizeErr}
gWorldsNotSameDepthAndSizeErr = -2066;
{$EXTERNALSYM invalidSpriteIndexErr}
invalidSpriteIndexErr = -2067;
{$EXTERNALSYM invalidImageIndexErr}
invalidImageIndexErr = -2068;
{$EXTERNALSYM invalidSpriteIDErr}
invalidSpriteIDErr = -2069;
//};
//enum {
{$EXTERNALSYM internalComponentErr}
internalComponentErr = -2070;
{$EXTERNALSYM notImplementedMusicOSErr}
notImplementedMusicOSErr = -2071;
{$EXTERNALSYM cantSendToSynthesizerOSErr}
cantSendToSynthesizerOSErr = -2072;
{$EXTERNALSYM cantReceiveFromSynthesizerOSErr}
cantReceiveFromSynthesizerOSErr = -2073;
{$EXTERNALSYM illegalVoiceAllocationOSErr}
illegalVoiceAllocationOSErr = -2074;
{$EXTERNALSYM illegalPartOSErr}
illegalPartOSErr = -2075;
{$EXTERNALSYM illegalChannelOSErr}
illegalChannelOSErr = -2076;
{$EXTERNALSYM illegalKnobOSErr}
illegalKnobOSErr = -2077;
{$EXTERNALSYM illegalKnobValueOSErr}
illegalKnobValueOSErr = -2078;
{$EXTERNALSYM illegalInstrumentOSErr}
illegalInstrumentOSErr = -2079;
{$EXTERNALSYM illegalControllerOSErr}
illegalControllerOSErr = -2080;
{$EXTERNALSYM midiManagerAbsentOSErr}
midiManagerAbsentOSErr = -2081;
{$EXTERNALSYM synthesizerNotRespondingOSErr}
synthesizerNotRespondingOSErr = -2082;
{$EXTERNALSYM synthesizerOSErr}
synthesizerOSErr = -2083;
{$EXTERNALSYM illegalNoteChannelOSErr}
illegalNoteChannelOSErr = -2084;
{$EXTERNALSYM noteChannelNotAllocatedOSErr}
noteChannelNotAllocatedOSErr = -2085;
{$EXTERNALSYM tunePlayerFullOSErr}
tunePlayerFullOSErr = -2086;
{$EXTERNALSYM tuneParseOSErr}
tuneParseOSErr = -2087;
{$EXTERNALSYM noExportProcAvailableErr}
noExportProcAvailableErr = -2089;
{$EXTERNALSYM videoOutputInUseErr}
videoOutputInUseErr = -2090;
//};
//enum {
{$EXTERNALSYM componentDllLoadErr}
componentDllLoadErr = -2091; //* Windows specific errors (when component is loading)*/
{$EXTERNALSYM componentDllEntryNotFoundErr}
componentDllEntryNotFoundErr = -2092; //* Windows specific errors (when component is loading)*/
{$EXTERNALSYM qtmlDllLoadErr}
qtmlDllLoadErr = -2093; //* Windows specific errors (when qtml is loading)*/
{$EXTERNALSYM qtmlDllEntryNotFoundErr}
qtmlDllEntryNotFoundErr = -2094; //* Windows specific errors (when qtml is loading)*/
{$EXTERNALSYM qtmlUninitialized}
qtmlUninitialized = -2095;
{$EXTERNALSYM unsupportedOSErr}
unsupportedOSErr = -2096;
{$EXTERNALSYM unsupportedProcessorErr}
unsupportedProcessorErr = -2097;
{$EXTERNALSYM componentNotThreadSafeErr}
componentNotThreadSafeErr = -2098; //* component is not thread-safe*/
//};
//enum {
{$EXTERNALSYM cannotFindAtomErr}
cannotFindAtomErr = -2101;
{$EXTERNALSYM notLeafAtomErr}
notLeafAtomErr = -2102;
{$EXTERNALSYM atomsNotOfSameTypeErr}
atomsNotOfSameTypeErr = -2103;
{$EXTERNALSYM atomIndexInvalidErr}
atomIndexInvalidErr = -2104;
{$EXTERNALSYM duplicateAtomTypeAndIDErr}
duplicateAtomTypeAndIDErr = -2105;
{$EXTERNALSYM invalidAtomErr}
invalidAtomErr = -2106;
{$EXTERNALSYM invalidAtomContainerErr}
invalidAtomContainerErr = -2107;
{$EXTERNALSYM invalidAtomTypeErr}
invalidAtomTypeErr = -2108;
{$EXTERNALSYM cannotBeLeafAtomErr}
cannotBeLeafAtomErr = -2109;
{$EXTERNALSYM pathTooLongErr}
pathTooLongErr = -2110;
{$EXTERNALSYM emptyPathErr}
emptyPathErr = -2111;
{$EXTERNALSYM noPathMappingErr}
noPathMappingErr = -2112;
{$EXTERNALSYM pathNotVerifiedErr}
pathNotVerifiedErr = -2113;
{$EXTERNALSYM unknownFormatErr}
unknownFormatErr = -2114;
{$EXTERNALSYM wackBadFileErr}
wackBadFileErr = -2115;
{$EXTERNALSYM wackForkNotFoundErr}
wackForkNotFoundErr = -2116;
{$EXTERNALSYM wackBadMetaDataErr}
wackBadMetaDataErr = -2117;
{$EXTERNALSYM qfcbNotFoundErr}
qfcbNotFoundErr = -2118;
{$EXTERNALSYM qfcbNotCreatedErr}
qfcbNotCreatedErr = -2119;
{$EXTERNALSYM AAPNotCreatedErr}
AAPNotCreatedErr = -2120;
{$EXTERNALSYM AAPNotFoundErr}
AAPNotFoundErr = -2121;
{$EXTERNALSYM ASDBadHeaderErr}
ASDBadHeaderErr = -2122;
{$EXTERNALSYM ASDBadForkErr}
ASDBadForkErr = -2123;
{$EXTERNALSYM ASDEntryNotFoundErr}
ASDEntryNotFoundErr = -2124;
{$EXTERNALSYM fileOffsetTooBigErr}
fileOffsetTooBigErr = -2125;
{$EXTERNALSYM notAllowedToSaveMovieErr}
notAllowedToSaveMovieErr = -2126;
{$EXTERNALSYM qtNetworkAlreadyAllocatedErr}
qtNetworkAlreadyAllocatedErr = -2127;
{$EXTERNALSYM urlDataHHTTPProtocolErr}
urlDataHHTTPProtocolErr = -2129;
{$EXTERNALSYM urlDataHHTTPNoNetDriverErr}
urlDataHHTTPNoNetDriverErr = -2130;
{$EXTERNALSYM urlDataHHTTPURLErr}
urlDataHHTTPURLErr = -2131;
{$EXTERNALSYM urlDataHHTTPRedirectErr}
urlDataHHTTPRedirectErr = -2132;
{$EXTERNALSYM urlDataHFTPProtocolErr}
urlDataHFTPProtocolErr = -2133;
{$EXTERNALSYM urlDataHFTPShutdownErr}
urlDataHFTPShutdownErr = -2134;
{$EXTERNALSYM urlDataHFTPBadUserErr}
urlDataHFTPBadUserErr = -2135;
{$EXTERNALSYM urlDataHFTPBadPasswordErr}
urlDataHFTPBadPasswordErr = -2136;
{$EXTERNALSYM urlDataHFTPServerErr}
urlDataHFTPServerErr = -2137;
{$EXTERNALSYM urlDataHFTPDataConnectionErr}
urlDataHFTPDataConnectionErr = -2138;
{$EXTERNALSYM urlDataHFTPNoDirectoryErr}
urlDataHFTPNoDirectoryErr = -2139;
{$EXTERNALSYM urlDataHFTPQuotaErr}
urlDataHFTPQuotaErr = -2140;
{$EXTERNALSYM urlDataHFTPPermissionsErr}
urlDataHFTPPermissionsErr = -2141;
{$EXTERNALSYM urlDataHFTPFilenameErr}
urlDataHFTPFilenameErr = -2142;
{$EXTERNALSYM urlDataHFTPNoNetDriverErr}
urlDataHFTPNoNetDriverErr = -2143;
{$EXTERNALSYM urlDataHFTPBadNameListErr}
urlDataHFTPBadNameListErr = -2144;
{$EXTERNALSYM urlDataHFTPNeedPasswordErr}
urlDataHFTPNeedPasswordErr = -2145;
{$EXTERNALSYM urlDataHFTPNoPasswordErr}
urlDataHFTPNoPasswordErr = -2146;
{$EXTERNALSYM urlDataHFTPServerDisconnectedErr}
urlDataHFTPServerDisconnectedErr = -2147;
{$EXTERNALSYM urlDataHFTPURLErr}
urlDataHFTPURLErr = -2148;
{$EXTERNALSYM notEnoughDataErr}
notEnoughDataErr = -2149;
{$EXTERNALSYM qtActionNotHandledErr}
qtActionNotHandledErr = -2157;
{$EXTERNALSYM qtXMLParseErr}
qtXMLParseErr = -2158;
{$EXTERNALSYM qtXMLApplicationErr}
qtXMLApplicationErr = -2159;
//};
//enum {
{$EXTERNALSYM digiUnimpErr}
digiUnimpErr = -2201; //* feature unimplemented */
{$EXTERNALSYM qtParamErr}
qtParamErr = -2202; //* bad input parameter (out of range, etc) */
{$EXTERNALSYM matrixErr}
matrixErr = -2203; //* bad matrix, digitizer did nothing */
{$EXTERNALSYM notExactMatrixErr}
notExactMatrixErr = -2204; //* warning of bad matrix, digitizer did its best */
{$EXTERNALSYM noMoreKeyColorsErr}
noMoreKeyColorsErr = -2205; //* all key indexes in use */
{$EXTERNALSYM notExactSizeErr}
notExactSizeErr = -2206; //* Can’t do exact size requested */
{$EXTERNALSYM badDepthErr}
badDepthErr = -2207; //* Can’t digitize into this depth */
{$EXTERNALSYM noDMAErr}
noDMAErr = -2208; //* Can’t do DMA digitizing (i.e. can't go to requested dest */
{$EXTERNALSYM badCallOrderErr}
badCallOrderErr = -2209; //* Usually due to a status call being called prior to being setup first */
//};
//* Kernel Error Codes */
//enum {
{$EXTERNALSYM kernelIncompleteErr}
kernelIncompleteErr = -2401;
{$EXTERNALSYM kernelCanceledErr}
kernelCanceledErr = -2402;
{$EXTERNALSYM kernelOptionsErr}
kernelOptionsErr = -2403;
{$EXTERNALSYM kernelPrivilegeErr}
kernelPrivilegeErr = -2404;
{$EXTERNALSYM kernelUnsupportedErr}
kernelUnsupportedErr = -2405;
{$EXTERNALSYM kernelObjectExistsErr}
kernelObjectExistsErr = -2406;
{$EXTERNALSYM kernelWritePermissionErr}
kernelWritePermissionErr = -2407;
{$EXTERNALSYM kernelReadPermissionErr}
kernelReadPermissionErr = -2408;
{$EXTERNALSYM kernelExecutePermissionErr}
kernelExecutePermissionErr = -2409;
{$EXTERNALSYM kernelDeletePermissionErr}
kernelDeletePermissionErr = -2410;
{$EXTERNALSYM kernelExecutionLevelErr}
kernelExecutionLevelErr = -2411;
{$EXTERNALSYM kernelAttributeErr}
kernelAttributeErr = -2412;
{$EXTERNALSYM kernelAsyncSendLimitErr}
kernelAsyncSendLimitErr = -2413;
{$EXTERNALSYM kernelAsyncReceiveLimitErr}
kernelAsyncReceiveLimitErr = -2414;
{$EXTERNALSYM kernelTimeoutErr}
kernelTimeoutErr = -2415;
{$EXTERNALSYM kernelInUseErr}
kernelInUseErr = -2416;
{$EXTERNALSYM kernelTerminatedErr}
kernelTerminatedErr = -2417;
{$EXTERNALSYM kernelExceptionErr}
kernelExceptionErr = -2418;
{$EXTERNALSYM kernelIDErr}
kernelIDErr = -2419;
{$EXTERNALSYM kernelAlreadyFreeErr}
kernelAlreadyFreeErr = -2421;
{$EXTERNALSYM kernelReturnValueErr}
kernelReturnValueErr = -2422;
{$EXTERNALSYM kernelUnrecoverableErr}
kernelUnrecoverableErr = -2499;
//};
//enum {
//* Text Services Mgr error codes */
{$EXTERNALSYM tsmComponentNoErr}
tsmComponentNoErr = 0; //* component result = no error */
{$EXTERNALSYM tsmUnsupScriptLanguageErr}
tsmUnsupScriptLanguageErr = -2500;
{$EXTERNALSYM tsmInputMethodNotFoundErr}
tsmInputMethodNotFoundErr = -2501;
{$EXTERNALSYM tsmNotAnAppErr}
tsmNotAnAppErr = -2502; //* not an application error */
{$EXTERNALSYM tsmAlreadyRegisteredErr}
tsmAlreadyRegisteredErr = -2503; //* want to register again error */
{$EXTERNALSYM tsmNeverRegisteredErr}
tsmNeverRegisteredErr = -2504; //* app never registered error (not TSM aware) */
{$EXTERNALSYM tsmInvalidDocIDErr}
tsmInvalidDocIDErr = -2505; //* invalid TSM documentation id */
{$EXTERNALSYM tsmTSMDocBusyErr}
tsmTSMDocBusyErr = -2506; //* document is still active */
{$EXTERNALSYM tsmDocNotActiveErr}
tsmDocNotActiveErr = -2507; //* document is NOT active */
{$EXTERNALSYM tsmNoOpenTSErr}
tsmNoOpenTSErr = -2508; //* no open text service */
{$EXTERNALSYM tsmCantOpenComponentErr}
tsmCantOpenComponentErr = -2509; //* can’t open the component */
{$EXTERNALSYM tsmTextServiceNotFoundErr}
tsmTextServiceNotFoundErr = -2510; //* no text service found */
{$EXTERNALSYM tsmDocumentOpenErr}
tsmDocumentOpenErr = -2511; //* there are open documents */
{$EXTERNALSYM tsmUseInputWindowErr}
tsmUseInputWindowErr = -2512; //* not TSM aware because we are using input window */
{$EXTERNALSYM tsmTSHasNoMenuErr}
tsmTSHasNoMenuErr = -2513; //* the text service has no menu */
{$EXTERNALSYM tsmTSNotOpenErr}
tsmTSNotOpenErr = -2514; //* text service is not open */
{$EXTERNALSYM tsmComponentAlreadyOpenErr}
tsmComponentAlreadyOpenErr = -2515; //* text service already opened for the document */
{$EXTERNALSYM tsmInputMethodIsOldErr}
tsmInputMethodIsOldErr = -2516; //* returned by GetDefaultInputMethod */
{$EXTERNALSYM tsmScriptHasNoIMErr}
tsmScriptHasNoIMErr = -2517; //* script has no imput method or is using old IM */
{$EXTERNALSYM tsmUnsupportedTypeErr}
tsmUnsupportedTypeErr = -2518; //* unSupported interface type error */
{$EXTERNALSYM tsmUnknownErr}
tsmUnknownErr = -2519; //* any other errors */
{$EXTERNALSYM tsmInvalidContext}
tsmInvalidContext = -2520; //* Invalid TSMContext specified in call */
{$EXTERNALSYM tsmNoHandler}
tsmNoHandler = -2521; //* No Callback Handler exists for callback */
{$EXTERNALSYM tsmNoMoreTokens}
tsmNoMoreTokens = -2522; //* No more tokens are available for the source text */
{$EXTERNALSYM tsmNoStem}
tsmNoStem = -2523; //* No stem exists for the token */
{$EXTERNALSYM tsmDefaultIsNotInputMethodErr}
tsmDefaultIsNotInputMethodErr = -2524; //* Current Input source is KCHR or uchr, not Input Method (GetDefaultInputMethod) */
{$EXTERNALSYM tsmDocPropertyNotFoundErr}
tsmDocPropertyNotFoundErr = -2528; //* Requested TSM Document property not found */
{$EXTERNALSYM tsmDocPropertyBufferTooSmallErr}
tsmDocPropertyBufferTooSmallErr = -2529; //* Buffer passed in for property value is too small */
{$EXTERNALSYM tsmCantChangeForcedClassStateErr}
tsmCantChangeForcedClassStateErr = -2530; //* Enabled state of a TextService class has been forced and cannot be changed */
{$EXTERNALSYM tsmComponentPropertyUnsupportedErr}
tsmComponentPropertyUnsupportedErr = -2531; //* Component property unsupported (or failed to be set) */
{$EXTERNALSYM tsmComponentPropertyNotFoundErr}
tsmComponentPropertyNotFoundErr = -2532; //* Component property not found */
{$EXTERNALSYM tsmInputModeChangeFailedErr}
tsmInputModeChangeFailedErr = -2533; //* Input Mode not changed */
//};
//enum {
//* Mixed Mode error codes */
{$EXTERNALSYM mmInternalError}
mmInternalError = -2526;
//};
//* NameRegistry error codes */
//enum {
{$EXTERNALSYM nrLockedErr}
nrLockedErr = -2536;
{$EXTERNALSYM nrNotEnoughMemoryErr}
nrNotEnoughMemoryErr = -2537;
{$EXTERNALSYM nrInvalidNodeErr}
nrInvalidNodeErr = -2538;
{$EXTERNALSYM nrNotFoundErr}
nrNotFoundErr = -2539;
{$EXTERNALSYM nrNotCreatedErr}
nrNotCreatedErr = -2540;
{$EXTERNALSYM nrNameErr}
nrNameErr = -2541;
{$EXTERNALSYM nrNotSlotDeviceErr}
nrNotSlotDeviceErr = -2542;
{$EXTERNALSYM nrDataTruncatedErr}
nrDataTruncatedErr = -2543;
{$EXTERNALSYM nrPowerErr}
nrPowerErr = -2544;
{$EXTERNALSYM nrPowerSwitchAbortErr}
nrPowerSwitchAbortErr = -2545;
{$EXTERNALSYM nrTypeMismatchErr}
nrTypeMismatchErr = -2546;
{$EXTERNALSYM nrNotModifiedErr}
nrNotModifiedErr = -2547;
{$EXTERNALSYM nrOverrunErr}
nrOverrunErr = -2548;
{$EXTERNALSYM nrResultCodeBase}
nrResultCodeBase = -2549;
{$EXTERNALSYM nrPathNotFound}
nrPathNotFound = -2550; //* a path component lookup failed */
{$EXTERNALSYM nrPathBufferTooSmall}
nrPathBufferTooSmall = -2551; //* buffer for path is too small */
{$EXTERNALSYM nrInvalidEntryIterationOp}
nrInvalidEntryIterationOp = -2552; //* invalid entry iteration operation */
{$EXTERNALSYM nrPropertyAlreadyExists}
nrPropertyAlreadyExists = -2553; //* property already exists */
{$EXTERNALSYM nrIterationDone}
nrIterationDone = -2554; //* iteration operation is done */
{$EXTERNALSYM nrExitedIteratorScope}
nrExitedIteratorScope = -2555; //* outer scope of iterator was exited */
{$EXTERNALSYM nrTransactionAborted}
nrTransactionAborted = -2556; //* transaction was aborted */
{$EXTERNALSYM nrCallNotSupported}
nrCallNotSupported = -2557; //* This call is not available or supported on this machine */
//};
//* Icon Services error codes */
//enum {
{$EXTERNALSYM invalidIconRefErr}
invalidIconRefErr = -2580; //* The icon ref is not valid */
{$EXTERNALSYM noSuchIconErr}
noSuchIconErr = -2581; //* The requested icon could not be found */
{$EXTERNALSYM noIconDataAvailableErr}
noIconDataAvailableErr = -2582; //* The necessary icon data is not available */
//};
{*
Dynamic AppleScript errors:
These errors result from data-dependent conditions and are typically
signaled at runtime.
*}
//enum {
{$EXTERNALSYM errOSACantCoerce}
errOSACantCoerce = errAECoercionFail; //* Signaled when a value can't be coerced to the desired type. */
{$EXTERNALSYM errOSACantAccess}
errOSACantAccess = errAENoSuchObject; //* Signaled when an object is not found in a container*/
{$EXTERNALSYM errOSACantAssign}
errOSACantAssign = -10006; //* Signaled when an object cannot be set in a container.*/
{$EXTERNALSYM errOSAGeneralError}
errOSAGeneralError = -2700; //* Signaled by user scripts or applications when no actual error code is to be returned.*/
{$EXTERNALSYM errOSADivideByZero}
errOSADivideByZero = -2701; //* Signaled when there is an attempt to divide by zero*/
{$EXTERNALSYM errOSANumericOverflow}
errOSANumericOverflow = -2702; //* Signaled when integer or real value is too large to be represented*/
{$EXTERNALSYM errOSACantLaunch}
errOSACantLaunch = -2703; //* Signaled when application can't be launched or when it is remote and program linking is not enabled*/
{$EXTERNALSYM errOSAAppNotHighLevelEventAware}
errOSAAppNotHighLevelEventAware = -2704; //* Signaled when an application can't respond to AppleEvents*/
{$EXTERNALSYM errOSACorruptTerminology}
errOSACorruptTerminology = -2705; //* Signaled when an application's terminology resource is not readable*/
{$EXTERNALSYM errOSAStackOverflow}
errOSAStackOverflow = -2706; //* Signaled when the runtime stack overflows*/
{$EXTERNALSYM errOSAInternalTableOverflow}
errOSAInternalTableOverflow = -2707; //* Signaled when a runtime internal data structure overflows*/
{$EXTERNALSYM errOSADataBlockTooLarge}
errOSADataBlockTooLarge = -2708; //* Signaled when an intrinsic limitation is exceeded for the size of a value or data structure.*/
{$EXTERNALSYM errOSACantGetTerminology}
errOSACantGetTerminology = -2709;
{$EXTERNALSYM errOSACantCreate}
errOSACantCreate = -2710;
//};
{*
Component-specific dynamic script errors:
The range -2720 thru -2739 is reserved for component-specific runtime errors.
(Note that error codes from different scripting components in this range will
overlap.)
*}
{*
Static AppleScript errors:
These errors comprise what are commonly thought of as parse and compile-
time errors. However, in a dynamic system (e.g. AppleScript) any or all
of these may also occur at runtime.
*}
//enum {
{$EXTERNALSYM errOSATypeError}
errOSATypeError = errAEWrongDataType;
{$EXTERNALSYM OSAMessageNotUnderstood}
OSAMessageNotUnderstood = errAEEventNotHandled; //* Signaled when a message was sent to an object that didn't handle it*/
{$EXTERNALSYM OSAUndefinedHandler}
OSAUndefinedHandler = errAEHandlerNotFound; //* Signaled when a function to be returned doesn't exist. */
{$EXTERNALSYM OSAIllegalAccess}
OSAIllegalAccess = errAEAccessorNotFound; //* Signaled when a container can never have the requested object*/
{$EXTERNALSYM OSAIllegalIndex}
OSAIllegalIndex = errAEIllegalIndex; //* Signaled when index was out of range. Specialization of errOSACantAccess*/
{$EXTERNALSYM OSAIllegalRange}
OSAIllegalRange = errAEImpossibleRange; //* Signaled when a range is screwy. Specialization of errOSACantAccess*/
{$EXTERNALSYM OSAIllegalAssign}
OSAIllegalAssign = -10003; //* Signaled when an object can never be set in a container*/
{$EXTERNALSYM OSASyntaxError}
OSASyntaxError = -2740; //* Signaled when a syntax error occurs. (e.g. "Syntax error" or "<this> can't go after <that>")*/
{$EXTERNALSYM OSASyntaxTypeError}
OSASyntaxTypeError = -2741; //* Signaled when another form of syntax was expected. (e.g. "expected a <type> but found <this>")*/
{$EXTERNALSYM OSATokenTooLong}
OSATokenTooLong = -2742; //* Signaled when a name or number is too long to be parsed*/
{$EXTERNALSYM OSAMissingParameter}
OSAMissingParameter = errAEDescNotFound; //* Signaled when a parameter is missing for a function invocation*/
{$EXTERNALSYM OSAParameterMismatch}
OSAParameterMismatch = errAEWrongNumberArgs; //* Signaled when function is called with the wrong number of parameters, or a parameter pattern cannot be matched*/
{$EXTERNALSYM OSADuplicateParameter}
OSADuplicateParameter = -2750; //* Signaled when a formal parameter, local variable, or instance variable is specified more than once*/
{$EXTERNALSYM OSADuplicateProperty}
OSADuplicateProperty = -2751; //* Signaled when a formal parameter, local variable, or instance variable is specified more than once.*/
{$EXTERNALSYM OSADuplicateHandler}
OSADuplicateHandler = -2752; //* Signaled when more than one handler is defined with the same name in a scope where the language doesn't allow it*/
{$EXTERNALSYM OSAUndefinedVariable}
OSAUndefinedVariable = -2753; //* Signaled when a variable is accessed that has no value*/
{$EXTERNALSYM OSAInconsistentDeclarations}
OSAInconsistentDeclarations = -2754; //* Signaled when a variable is declared inconsistently in the same scope, such as both local and global*/
{$EXTERNALSYM OSAControlFlowError}
OSAControlFlowError = -2755; //* Signaled when illegal control flow occurs in an application (no catcher for throw, non-lexical loop exit, etc.)*/
//};
{*
Component-specific AppleScript static errors:
The range -2760 thru -2779 is reserved for component-specific parsing and
compile-time errors. (Note that error codes from different scripting
components in this range will overlap.)
*}
{*
Dialect-specific AppleScript errors:
The range -2780 thru -2799 is reserved for dialect specific error codes for
scripting components that support dialects. (Note that error codes from
different scripting components in this range will overlap, as well as error
codes from different dialects in the same scripting component.)
*}
//**************************************************************************
// Apple Script Error Codes
//**************************************************************************/
//* Runtime errors: */
//enum {
{$EXTERNALSYM errASCantConsiderAndIgnore}
errASCantConsiderAndIgnore = -2720;
{$EXTERNALSYM errASCantCompareMoreThan32k}
errASCantCompareMoreThan32k = -2721; //* Parser/Compiler errors: */
{$EXTERNALSYM errASTerminologyNestingTooDeep}
errASTerminologyNestingTooDeep = -2760;
{$EXTERNALSYM errASIllegalFormalParameter}
errASIllegalFormalParameter = -2761;
{$EXTERNALSYM errASParameterNotForEvent}
errASParameterNotForEvent = -2762;
{$EXTERNALSYM errASNoResultReturned}
errASNoResultReturned = -2763; //* The range -2780 thru -2799 is reserved for dialect specific error codes. (Error codes from different dialects may overlap.) */
{$EXTERNALSYM errASInconsistentNames}
errASInconsistentNames = -2780; //* English errors: */
//};
//* The preferred spelling for Code Fragment Manager errors:*/
//enum {
{$EXTERNALSYM cfragFirstErrCode}
cfragFirstErrCode = -2800; //* The first value in the range of CFM errors.*/
{$EXTERNALSYM cfragContextIDErr}
cfragContextIDErr = -2800; //* The context ID was not valid.*/
{$EXTERNALSYM cfragConnectionIDErr}
cfragConnectionIDErr = -2801; //* The connection ID was not valid.*/
{$EXTERNALSYM cfragNoSymbolErr}
cfragNoSymbolErr = -2802; //* The specified symbol was not found.*/
{$EXTERNALSYM cfragNoSectionErr}
cfragNoSectionErr = -2803; //* The specified section was not found.*/
{$EXTERNALSYM cfragNoLibraryErr}
cfragNoLibraryErr = -2804; //* The named library was not found.*/
{$EXTERNALSYM cfragDupRegistrationErr}
cfragDupRegistrationErr = -2805; //* The registration name was already in use.*/
{$EXTERNALSYM cfragFragmentFormatErr}
cfragFragmentFormatErr = -2806; //* A fragment's container format is unknown.*/
{$EXTERNALSYM cfragUnresolvedErr}
cfragUnresolvedErr = -2807; //* A fragment had "hard" unresolved imports.*/
{$EXTERNALSYM cfragNoPositionErr}
cfragNoPositionErr = -2808; //* The registration insertion point was not found.*/
{$EXTERNALSYM cfragNoPrivateMemErr}
cfragNoPrivateMemErr = -2809; //* Out of memory for internal bookkeeping.*/
{$EXTERNALSYM cfragNoClientMemErr}
cfragNoClientMemErr = -2810; //* Out of memory for fragment mapping or section instances.*/
{$EXTERNALSYM cfragNoIDsErr}
cfragNoIDsErr = -2811; //* No more CFM IDs for contexts, connections, etc.*/
{$EXTERNALSYM cfragInitOrderErr}
cfragInitOrderErr = -2812; //* */
{$EXTERNALSYM cfragImportTooOldErr}
cfragImportTooOldErr = -2813; //* An import library was too old for a client.*/
{$EXTERNALSYM cfragImportTooNewErr}
cfragImportTooNewErr = -2814; //* An import library was too new for a client.*/
{$EXTERNALSYM cfragInitLoopErr}
cfragInitLoopErr = -2815; //* Circularity in required initialization order.*/
{$EXTERNALSYM cfragInitAtBootErr}
cfragInitAtBootErr = -2816; //* A boot library has an initialization function. (System 7 only)*/
{$EXTERNALSYM cfragLibConnErr}
cfragLibConnErr = -2817; //* */
{$EXTERNALSYM cfragCFMStartupErr}
cfragCFMStartupErr = -2818; //* Internal error during CFM initialization.*/
{$EXTERNALSYM cfragCFMInternalErr}
cfragCFMInternalErr = -2819; //* An internal inconstistancy has been detected.*/
{$EXTERNALSYM cfragFragmentCorruptErr}
cfragFragmentCorruptErr = -2820; //* A fragment's container was corrupt (known format).*/
{$EXTERNALSYM cfragInitFunctionErr}
cfragInitFunctionErr = -2821; //* A fragment's initialization routine returned an error.*/
{$EXTERNALSYM cfragNoApplicationErr}
cfragNoApplicationErr = -2822; //* No application member found in the cfrg resource.*/
{$EXTERNALSYM cfragArchitectureErr}
cfragArchitectureErr = -2823; //* A fragment has an unacceptable architecture.*/
{$EXTERNALSYM cfragFragmentUsageErr}
cfragFragmentUsageErr = -2824; //* A semantic error in usage of the fragment.*/
{$EXTERNALSYM cfragFileSizeErr}
cfragFileSizeErr = -2825; //* A file was too large to be mapped.*/
{$EXTERNALSYM cfragNotClosureErr}
cfragNotClosureErr = -2826; //* The closure ID was actually a connection ID.*/
{$EXTERNALSYM cfragNoRegistrationErr}
cfragNoRegistrationErr = -2827; //* The registration name was not found.*/
{$EXTERNALSYM cfragContainerIDErr}
cfragContainerIDErr = -2828; //* The fragment container ID was not valid.*/
{$EXTERNALSYM cfragClosureIDErr}
cfragClosureIDErr = -2829; //* The closure ID was not valid.*/
{$EXTERNALSYM cfragAbortClosureErr}
cfragAbortClosureErr = -2830; //* Used by notification handlers to abort a closure.*/
{$EXTERNALSYM cfragOutputLengthErr}
cfragOutputLengthErr = -2831; //* An output parameter is too small to hold the value.*/
{$EXTERNALSYM cfragMapFileErr}
cfragMapFileErr = -2851; //* A file could not be mapped.*/
{$EXTERNALSYM cfragExecFileRefErr}
cfragExecFileRefErr = -2854; //* Bundle does not have valid executable file.*/
{$EXTERNALSYM cfragStdFolderErr}
cfragStdFolderErr = -2855; //* Could not find standard CFM folder.*/
{$EXTERNALSYM cfragRsrcForkErr}
cfragRsrcForkErr = -2856; //* Resource fork could not be opened.*/
{$EXTERNALSYM cfragCFragRsrcErr}
cfragCFragRsrcErr = -2857; //* 'cfrg' resource could not be loaded.*/
{$EXTERNALSYM cfragLastErrCode}
cfragLastErrCode = -2899; //* The last value in the range of CFM errors.*/
//};
//enum {
//* Reserved values for internal "warnings".*/
{$EXTERNALSYM cfragFirstReservedCode}
cfragFirstReservedCode = -2897;
{$EXTERNALSYM cfragReservedCode_3}
cfragReservedCode_3 = -2897;
{$EXTERNALSYM cfragReservedCode_2}
cfragReservedCode_2 = -2898;
{$EXTERNALSYM cfragReservedCode_1}
cfragReservedCode_1 = -2899;
//};
//#if OLDROUTINENAMES
//* The old spelling for Code Fragment Manager errors, kept for compatibility:*/
//enum {
{$EXTERNALSYM fragContextNotFound}
fragContextNotFound = cfragContextIDErr;
{$EXTERNALSYM fragConnectionIDNotFound}
fragConnectionIDNotFound = cfragConnectionIDErr;
{$EXTERNALSYM fragSymbolNotFound}
fragSymbolNotFound = cfragNoSymbolErr;
{$EXTERNALSYM fragSectionNotFound}
fragSectionNotFound = cfragNoSectionErr;
{$EXTERNALSYM fragLibNotFound}
fragLibNotFound = cfragNoLibraryErr;
{$EXTERNALSYM fragDupRegLibName}
fragDupRegLibName = cfragDupRegistrationErr;
{$EXTERNALSYM fragFormatUnknown}
fragFormatUnknown = cfragFragmentFormatErr;
{$EXTERNALSYM fragHadUnresolveds}
fragHadUnresolveds = cfragUnresolvedErr;
{$EXTERNALSYM fragNoMem}
fragNoMem = cfragNoPrivateMemErr;
{$EXTERNALSYM fragNoAddrSpace}
fragNoAddrSpace = cfragNoClientMemErr;
{$EXTERNALSYM fragNoContextIDs}
fragNoContextIDs = cfragNoIDsErr;
{$EXTERNALSYM fragObjectInitSeqErr}
fragObjectInitSeqErr = cfragInitOrderErr;
{$EXTERNALSYM fragImportTooOld}
fragImportTooOld = cfragImportTooOldErr;
{$EXTERNALSYM fragImportTooNew}
fragImportTooNew = cfragImportTooNewErr;
{$EXTERNALSYM fragInitLoop}
fragInitLoop = cfragInitLoopErr;
{$EXTERNALSYM fragInitRtnUsageErr}
fragInitRtnUsageErr = cfragInitAtBootErr;
{$EXTERNALSYM fragLibConnErr}
fragLibConnErr = cfragLibConnErr;
{$EXTERNALSYM fragMgrInitErr}
fragMgrInitErr = cfragCFMStartupErr;
{$EXTERNALSYM fragConstErr}
fragConstErr = cfragCFMInternalErr;
{$EXTERNALSYM fragCorruptErr}
fragCorruptErr = cfragFragmentCorruptErr;
{$EXTERNALSYM fragUserInitProcErr}
fragUserInitProcErr = cfragInitFunctionErr;
{$EXTERNALSYM fragAppNotFound}
fragAppNotFound = cfragNoApplicationErr;
{$EXTERNALSYM fragArchError}
fragArchError = cfragArchitectureErr;
{$EXTERNALSYM fragInvalidFragmentUsage}
fragInvalidFragmentUsage = cfragFragmentUsageErr;
{$EXTERNALSYM fragLastErrCode}
fragLastErrCode = cfragLastErrCode;
//};
//#endif /* OLDROUTINENAMES */
//*Component Manager & component errors*/
//enum {
{$EXTERNALSYM invalidComponentID}
invalidComponentID = -3000;
{$EXTERNALSYM validInstancesExist}
validInstancesExist = -3001;
{$EXTERNALSYM componentNotCaptured}
componentNotCaptured = -3002;
{$EXTERNALSYM componentDontRegister}
componentDontRegister = -3003;
{$EXTERNALSYM unresolvedComponentDLLErr}
unresolvedComponentDLLErr = -3004;
{$EXTERNALSYM retryComponentRegistrationErr}
retryComponentRegistrationErr = -3005;
//};
//*Translation manager & Translation components*/
//enum {
{$EXTERNALSYM invalidTranslationPathErr}
invalidTranslationPathErr = -3025; //*Source type to destination type not a valid path*/
{$EXTERNALSYM couldNotParseSourceFileErr}
couldNotParseSourceFileErr = -3026; //*Source document does not contain source type*/
{$EXTERNALSYM noTranslationPathErr}
noTranslationPathErr = -3030;
{$EXTERNALSYM badTranslationSpecErr}
badTranslationSpecErr = -3031;
{$EXTERNALSYM noPrefAppErr}
noPrefAppErr = -3032;
//};
//enum {
{$EXTERNALSYM buf2SmallErr}
buf2SmallErr = -3101;
{$EXTERNALSYM noMPPErr}
noMPPErr = -3102;
{$EXTERNALSYM ckSumErr}
ckSumErr = -3103;
{$EXTERNALSYM extractErr}
extractErr = -3104;
{$EXTERNALSYM readQErr}
readQErr = -3105;
{$EXTERNALSYM atpLenErr}
atpLenErr = -3106;
{$EXTERNALSYM atpBadRsp}
atpBadRsp = -3107;
{$EXTERNALSYM recNotFnd}
recNotFnd = -3108;
{$EXTERNALSYM sktClosedErr}
sktClosedErr = -3109;
//};
//* OpenTransport errors*/
//enum {
{$EXTERNALSYM kOTNoError}
kOTNoError = 0; //* No Error occurred */
{$EXTERNALSYM kOTOutOfMemoryErr}
kOTOutOfMemoryErr = -3211; //* OT ran out of memory, may be a temporary */
{$EXTERNALSYM kOTNotFoundErr}
kOTNotFoundErr = -3201; //* OT generic not found error */
{$EXTERNALSYM kOTDuplicateFoundErr}
kOTDuplicateFoundErr = -3216; //* OT generic duplicate found error */
{$EXTERNALSYM kOTBadAddressErr}
kOTBadAddressErr = -3150; //* XTI2OSStatus(TBADADDR) A Bad address was specified */
{$EXTERNALSYM kOTBadOptionErr}
kOTBadOptionErr = -3151; //* XTI2OSStatus(TBADOPT) A Bad option was specified */
{$EXTERNALSYM kOTAccessErr}
kOTAccessErr = -3152; //* XTI2OSStatus(TACCES) Missing access permission */
{$EXTERNALSYM kOTBadReferenceErr}
kOTBadReferenceErr = -3153; //* XTI2OSStatus(TBADF) Bad provider reference */
{$EXTERNALSYM kOTNoAddressErr}
kOTNoAddressErr = -3154; //* XTI2OSStatus(TNOADDR) No address was specified */
{$EXTERNALSYM kOTOutStateErr}
kOTOutStateErr = -3155; //* XTI2OSStatus(TOUTSTATE) Call issued in wrong state */
{$EXTERNALSYM kOTBadSequenceErr}
kOTBadSequenceErr = -3156; //* XTI2OSStatus(TBADSEQ) Sequence specified does not exist */
{$EXTERNALSYM kOTSysErrorErr}
kOTSysErrorErr = -3157; //* XTI2OSStatus(TSYSERR) A system error occurred */
{$EXTERNALSYM kOTLookErr}
kOTLookErr = -3158; //* XTI2OSStatus(TLOOK) An event occurred - call Look() */
{$EXTERNALSYM kOTBadDataErr}
kOTBadDataErr = -3159; //* XTI2OSStatus(TBADDATA) An illegal amount of data was specified */
{$EXTERNALSYM kOTBufferOverflowErr}
kOTBufferOverflowErr = -3160; //* XTI2OSStatus(TBUFOVFLW) Passed buffer not big enough */
{$EXTERNALSYM kOTFlowErr}
kOTFlowErr = -3161; //* XTI2OSStatus(TFLOW) Provider is flow-controlled */
{$EXTERNALSYM kOTNoDataErr}
kOTNoDataErr = -3162; //* XTI2OSStatus(TNODATA) No data available for reading */
{$EXTERNALSYM kOTNoDisconnectErr}
kOTNoDisconnectErr = -3163; //* XTI2OSStatus(TNODIS) No disconnect indication available */
{$EXTERNALSYM kOTNoUDErrErr}
kOTNoUDErrErr = -3164; //* XTI2OSStatus(TNOUDERR) No Unit Data Error indication available */
{$EXTERNALSYM kOTBadFlagErr}
kOTBadFlagErr = -3165; //* XTI2OSStatus(TBADFLAG) A Bad flag value was supplied */
{$EXTERNALSYM kOTNoReleaseErr}
kOTNoReleaseErr = -3166; //* XTI2OSStatus(TNOREL) No orderly release indication available */
{$EXTERNALSYM kOTNotSupportedErr}
kOTNotSupportedErr = -3167; //* XTI2OSStatus(TNOTSUPPORT) Command is not supported */
{$EXTERNALSYM kOTStateChangeErr}
kOTStateChangeErr = -3168; //* XTI2OSStatus(TSTATECHNG) State is changing - try again later */
{$EXTERNALSYM kOTNoStructureTypeErr}
kOTNoStructureTypeErr = -3169; //* XTI2OSStatus(TNOSTRUCTYPE) Bad structure type requested for OTAlloc */
{$EXTERNALSYM kOTBadNameErr}
kOTBadNameErr = -3170; //* XTI2OSStatus(TBADNAME) A bad endpoint name was supplied */
{$EXTERNALSYM kOTBadQLenErr}
kOTBadQLenErr = -3171; //* XTI2OSStatus(TBADQLEN) A Bind to an in-use addr with qlen > 0 */
{$EXTERNALSYM kOTAddressBusyErr}
kOTAddressBusyErr = -3172; //* XTI2OSStatus(TADDRBUSY) Address requested is already in use */
{$EXTERNALSYM kOTIndOutErr}
kOTIndOutErr = -3173; //* XTI2OSStatus(TINDOUT) Accept failed because of pending listen */
{$EXTERNALSYM kOTProviderMismatchErr}
kOTProviderMismatchErr = -3174; //* XTI2OSStatus(TPROVMISMATCH) Tried to accept on incompatible endpoint */
{$EXTERNALSYM kOTResQLenErr}
kOTResQLenErr = -3175; //* XTI2OSStatus(TRESQLEN) */
{$EXTERNALSYM kOTResAddressErr}
kOTResAddressErr = -3176; //* XTI2OSStatus(TRESADDR) */
{$EXTERNALSYM kOTQFullErr}
kOTQFullErr = -3177; //* XTI2OSStatus(TQFULL) */
{$EXTERNALSYM kOTProtocolErr}
kOTProtocolErr = -3178; //* XTI2OSStatus(TPROTO) An unspecified provider error occurred */
{$EXTERNALSYM kOTBadSyncErr}
kOTBadSyncErr = -3179; //* XTI2OSStatus(TBADSYNC) A synchronous call at interrupt time */
{$EXTERNALSYM kOTCanceledErr}
kOTCanceledErr = -3180; //* XTI2OSStatus(TCANCELED) The command was cancelled */
{$EXTERNALSYM kEPERMErr}
kEPERMErr = -3200; //* Permission denied */
{$EXTERNALSYM kENOENTErr}
kENOENTErr = -3201; //* No such file or directory */
{$EXTERNALSYM kENORSRCErr}
kENORSRCErr = -3202; //* No such resource */
{$EXTERNALSYM kEINTRErr}
kEINTRErr = -3203; //* Interrupted system service */
{$EXTERNALSYM kEIOErr}
kEIOErr = -3204; //* I/O error */
{$EXTERNALSYM kENXIOErr}
kENXIOErr = -3205; //* No such device or address */
{$EXTERNALSYM kEBADFErr}
kEBADFErr = -3208; //* Bad file number */
{$EXTERNALSYM kEAGAINErr}
kEAGAINErr = -3210; //* Try operation again later */
{$EXTERNALSYM kENOMEMErr}
kENOMEMErr = -3211; //* Not enough space */
{$EXTERNALSYM kEACCESErr}
kEACCESErr = -3212; //* Permission denied */
{$EXTERNALSYM kEFAULTErr}
kEFAULTErr = -3213; //* Bad address */
{$EXTERNALSYM kEBUSYErr}
kEBUSYErr = -3215; //* Device or resource busy */
{$EXTERNALSYM kEEXISTErr}
kEEXISTErr = -3216; //* File exists */
{$EXTERNALSYM kENODEVErr}
kENODEVErr = -3218; //* No such device */
{$EXTERNALSYM kEINVALErr}
kEINVALErr = -3221; //* Invalid argument */
{$EXTERNALSYM kENOTTYErr}
kENOTTYErr = -3224; //* Not a character device */
{$EXTERNALSYM kEPIPEErr}
kEPIPEErr = -3231; //* Broken pipe */
{$EXTERNALSYM kERANGEErr}
kERANGEErr = -3233; //* Message size too large for STREAM */
{$EXTERNALSYM kEWOULDBLOCKErr}
kEWOULDBLOCKErr = -3234; //* Call would block, so was aborted */
{$EXTERNALSYM kEDEADLKErr}
kEDEADLKErr = -3234; //* or a deadlock would occur */
{$EXTERNALSYM kEALREADYErr}
kEALREADYErr = -3236; //* */
{$EXTERNALSYM kENOTSOCKErr}
kENOTSOCKErr = -3237; //* Socket operation on non-socket */
{$EXTERNALSYM kEDESTADDRREQErr}
kEDESTADDRREQErr = -3238; //* Destination address required */
{$EXTERNALSYM kEMSGSIZEErr}
kEMSGSIZEErr = -3239; //* Message too long */
{$EXTERNALSYM kEPROTOTYPEErr}
kEPROTOTYPEErr = -3240; //* Protocol wrong type for socket */
{$EXTERNALSYM kENOPROTOOPTErr}
kENOPROTOOPTErr = -3241; //* Protocol not available */
{$EXTERNALSYM kEPROTONOSUPPORTErr}
kEPROTONOSUPPORTErr = -3242; //* Protocol not supported */
{$EXTERNALSYM kESOCKTNOSUPPORTErr}
kESOCKTNOSUPPORTErr = -3243; //* Socket type not supported */
{$EXTERNALSYM kEOPNOTSUPPErr}
kEOPNOTSUPPErr = -3244; //* Operation not supported on socket */
{$EXTERNALSYM kEADDRINUSEErr}
kEADDRINUSEErr = -3247; //* Address already in use */
{$EXTERNALSYM kEADDRNOTAVAILErr}
kEADDRNOTAVAILErr = -3248; //* Can't assign requested address */
{$EXTERNALSYM kENETDOWNErr}
kENETDOWNErr = -3249; //* Network is down */
{$EXTERNALSYM kENETUNREACHErr}
kENETUNREACHErr = -3250; //* Network is unreachable */
{$EXTERNALSYM kENETRESETErr}
kENETRESETErr = -3251; //* Network dropped connection on reset */
{$EXTERNALSYM kECONNABORTEDErr}
kECONNABORTEDErr = -3252; //* Software caused connection abort */
{$EXTERNALSYM kECONNRESETErr}
kECONNRESETErr = -3253; //* Connection reset by peer */
{$EXTERNALSYM kENOBUFSErr}
kENOBUFSErr = -3254; //* No buffer space available */
{$EXTERNALSYM kEISCONNErr}
kEISCONNErr = -3255; //* Socket is already connected */
{$EXTERNALSYM kENOTCONNErr}
kENOTCONNErr = -3256; //* Socket is not connected */
{$EXTERNALSYM kESHUTDOWNErr}
kESHUTDOWNErr = -3257; //* Can't send after socket shutdown */
{$EXTERNALSYM kETOOMANYREFSErr}
kETOOMANYREFSErr = -3258; //* Too many references: can't splice */
{$EXTERNALSYM kETIMEDOUTErr}
kETIMEDOUTErr = -3259; //* Connection timed out */
{$EXTERNALSYM kECONNREFUSEDErr}
kECONNREFUSEDErr = -3260; //* Connection refused */
{$EXTERNALSYM kEHOSTDOWNErr}
kEHOSTDOWNErr = -3263; //* Host is down */
{$EXTERNALSYM kEHOSTUNREACHErr}
kEHOSTUNREACHErr = -3264; //* No route to host */
{$EXTERNALSYM kEPROTOErr}
kEPROTOErr = -3269; //* ••• fill out missing codes ••• */
{$EXTERNALSYM kETIMEErr}
kETIMEErr = -3270; //* */
{$EXTERNALSYM kENOSRErr}
kENOSRErr = -3271; //* */
{$EXTERNALSYM kEBADMSGErr}
kEBADMSGErr = -3272; //* */
{$EXTERNALSYM kECANCELErr}
kECANCELErr = -3273; //* */
{$EXTERNALSYM kENOSTRErr}
kENOSTRErr = -3274; //* */
{$EXTERNALSYM kENODATAErr}
kENODATAErr = -3275; //* */
{$EXTERNALSYM kEINPROGRESSErr}
kEINPROGRESSErr = -3276; //* */
{$EXTERNALSYM kESRCHErr}
kESRCHErr = -3277; //* */
{$EXTERNALSYM kENOMSGErr}
kENOMSGErr = -3278; //* */
{$EXTERNALSYM kOTClientNotInittedErr}
kOTClientNotInittedErr = -3279; //* */
{$EXTERNALSYM kOTPortHasDiedErr}
kOTPortHasDiedErr = -3280; //* */
{$EXTERNALSYM kOTPortWasEjectedErr}
kOTPortWasEjectedErr = -3281; //* */
{$EXTERNALSYM kOTBadConfigurationErr}
kOTBadConfigurationErr = -3282; //* */
{$EXTERNALSYM kOTConfigurationChangedErr}
kOTConfigurationChangedErr = -3283; //* */
{$EXTERNALSYM kOTUserRequestedErr}
kOTUserRequestedErr = -3284; //* */
{$EXTERNALSYM kOTPortLostConnection}
kOTPortLostConnection = -3285; //* */
//};
//* Additional Quickdraw errors in the assigned range -3950 .. -3999*/
//enum {
{$EXTERNALSYM kQDNoPalette}
kQDNoPalette = -3950; //* PaletteHandle is NULL*/
{$EXTERNALSYM kQDNoColorHWCursorSupport}
kQDNoColorHWCursorSupport = -3951; //* CGSSystemSupportsColorHardwareCursors() returned false*/
{$EXTERNALSYM kQDCursorAlreadyRegistered}
kQDCursorAlreadyRegistered = -3952; //* can be returned from QDRegisterNamedPixMapCursor()*/
{$EXTERNALSYM kQDCursorNotRegistered}
kQDCursorNotRegistered = -3953; //* can be returned from QDSetNamedPixMapCursor()*/
{$EXTERNALSYM kQDCorruptPICTDataErr}
kQDCorruptPICTDataErr = -3954;
//};
//* Color Picker errors*/
//enum {
{$EXTERNALSYM firstPickerError}
firstPickerError = -4000;
{$EXTERNALSYM invalidPickerType}
invalidPickerType = firstPickerError;
{$EXTERNALSYM requiredFlagsDontMatch}
requiredFlagsDontMatch = -4001;
{$EXTERNALSYM pickerResourceError}
pickerResourceError = -4002;
{$EXTERNALSYM cantLoadPicker}
cantLoadPicker = -4003;
{$EXTERNALSYM cantCreatePickerWindow}
cantCreatePickerWindow = -4004;
{$EXTERNALSYM cantLoadPackage}
cantLoadPackage = -4005;
{$EXTERNALSYM pickerCantLive}
pickerCantLive = -4006;
{$EXTERNALSYM colorSyncNotInstalled}
colorSyncNotInstalled = -4007;
{$EXTERNALSYM badProfileError}
badProfileError = -4008;
{$EXTERNALSYM noHelpForItem}
noHelpForItem = -4009;
//};
//* NSL error codes*/
//enum {
{$EXTERNALSYM kNSL68kContextNotSupported}
kNSL68kContextNotSupported = -4170; //* no 68k allowed*/
{$EXTERNALSYM kNSLSchedulerError}
kNSLSchedulerError = -4171; //* A custom thread routine encountered an error*/
{$EXTERNALSYM kNSLBadURLSyntax}
kNSLBadURLSyntax = -4172; //* URL contains illegal characters*/
{$EXTERNALSYM kNSLNoCarbonLib}
kNSLNoCarbonLib = -4173;
{$EXTERNALSYM kNSLUILibraryNotAvailable}
kNSLUILibraryNotAvailable = -4174; //* The NSL UI Library needs to be in the Extensions Folder*/
{$EXTERNALSYM kNSLNotImplementedYet}
kNSLNotImplementedYet = -4175;
{$EXTERNALSYM kNSLErrNullPtrError}
kNSLErrNullPtrError = -4176;
{$EXTERNALSYM kNSLSomePluginsFailedToLoad}
kNSLSomePluginsFailedToLoad = -4177; //* (one or more plugins failed to load, but at least one did load; this error isn't fatal)*/
{$EXTERNALSYM kNSLNullNeighborhoodPtr}
kNSLNullNeighborhoodPtr = -4178; //* (client passed a null neighborhood ptr)*/
{$EXTERNALSYM kNSLNoPluginsForSearch}
kNSLNoPluginsForSearch = -4179; //* (no plugins will respond to search request; bad protocol(s)?)*/
{$EXTERNALSYM kNSLSearchAlreadyInProgress}
kNSLSearchAlreadyInProgress = -4180; //* (you can only have one ongoing search per clientRef)*/
{$EXTERNALSYM kNSLNoPluginsFound}
kNSLNoPluginsFound = -4181; //* (manager didn't find any valid plugins to load)*/
{$EXTERNALSYM kNSLPluginLoadFailed}
kNSLPluginLoadFailed = -4182; //* (manager unable to load one of the plugins)*/
{$EXTERNALSYM kNSLBadProtocolTypeErr}
kNSLBadProtocolTypeErr = -4183; //* (client is trying to add a null protocol type)*/
{$EXTERNALSYM kNSLNullListPtr}
kNSLNullListPtr = -4184; //* (client is trying to add items to a nil list)*/
{$EXTERNALSYM kNSLBadClientInfoPtr}
kNSLBadClientInfoPtr = -4185; //* (nil ClientAsyncInfoPtr; no reference available)*/
{$EXTERNALSYM kNSLCannotContinueLookup}
kNSLCannotContinueLookup = -4186; //* (Can't continue lookup; error or bad state)*/
{$EXTERNALSYM kNSLBufferTooSmallForData}
kNSLBufferTooSmallForData = -4187; //* (Client buffer too small for data from plugin)*/
{$EXTERNALSYM kNSLNoContextAvailable}
kNSLNoContextAvailable = -4188; //* (ContinueLookup function ptr invalid)*/
{$EXTERNALSYM kNSLRequestBufferAlreadyInList}
kNSLRequestBufferAlreadyInList = -4189;
{$EXTERNALSYM kNSLInvalidPluginSpec}
kNSLInvalidPluginSpec = -4190;
{$EXTERNALSYM kNSLNoSupportForService}
kNSLNoSupportForService = -4191;
{$EXTERNALSYM kNSLBadNetConnection}
kNSLBadNetConnection = -4192;
{$EXTERNALSYM kNSLBadDataTypeErr}
kNSLBadDataTypeErr = -4193;
{$EXTERNALSYM kNSLBadServiceTypeErr}
kNSLBadServiceTypeErr = -4194;
{$EXTERNALSYM kNSLBadReferenceErr}
kNSLBadReferenceErr = -4195;
{$EXTERNALSYM kNSLNoElementsInList}
kNSLNoElementsInList = -4196;
{$EXTERNALSYM kNSLInsufficientOTVer}
kNSLInsufficientOTVer = -4197;
{$EXTERNALSYM kNSLInsufficientSysVer}
kNSLInsufficientSysVer = -4198;
{$EXTERNALSYM kNSLNotInitialized}
kNSLNotInitialized = -4199;
{$EXTERNALSYM kNSLInitializationFailed}
kNSLInitializationFailed = -4200; //* UNABLE TO INITIALIZE THE MANAGER!!!!! DO NOT CONTINUE!!!!*/
//};
//* desktop printing error codes*/
//enum {
{$EXTERNALSYM kDTPHoldJobErr}
kDTPHoldJobErr = -4200;
{$EXTERNALSYM kDTPStopQueueErr}
kDTPStopQueueErr = -4201;
{$EXTERNALSYM kDTPTryAgainErr}
kDTPTryAgainErr = -4202;
{$EXTERNALSYM kDTPAbortJobErr}
kDTPAbortJobErr = 128;
//};
//* ColorSync Result codes */
//enum {
//* Profile Access Errors */
{$EXTERNALSYM cmElementTagNotFound}
cmElementTagNotFound = -4200;
{$EXTERNALSYM cmIndexRangeErr}
cmIndexRangeErr = -4201; //* Tag index out of range */
{$EXTERNALSYM cmCantDeleteElement}
cmCantDeleteElement = -4202;
{$EXTERNALSYM cmFatalProfileErr}
cmFatalProfileErr = -4203;
{$EXTERNALSYM cmInvalidProfile}
cmInvalidProfile = -4204; //* A Profile must contain a 'cs1 ' tag to be valid */
{$EXTERNALSYM cmInvalidProfileLocation}
cmInvalidProfileLocation = -4205; //* Operation not supported for this profile location */
{$EXTERNALSYM cmCantCopyModifiedV1Profile}
cmCantCopyModifiedV1Profile = -4215; //* Illegal to copy version 1 profiles that have been modified */
//* Profile Search Errors */
{$EXTERNALSYM cmInvalidSearch}
cmInvalidSearch = -4206; //* Bad Search Handle */
{$EXTERNALSYM cmSearchError}
cmSearchError = -4207;
{$EXTERNALSYM cmErrIncompatibleProfile}
cmErrIncompatibleProfile = -4208; //* Other ColorSync Errors */
{$EXTERNALSYM cmInvalidColorSpace}
cmInvalidColorSpace = -4209; //* Profile colorspace does not match bitmap type */
{$EXTERNALSYM cmInvalidSrcMap}
cmInvalidSrcMap = -4210; //* Source pix/bit map was invalid */
{$EXTERNALSYM cmInvalidDstMap}
cmInvalidDstMap = -4211; //* Destination pix/bit map was invalid */
{$EXTERNALSYM cmNoGDevicesError}
cmNoGDevicesError = -4212; //* Begin/End Matching -- no gdevices available */
{$EXTERNALSYM cmInvalidProfileComment}
cmInvalidProfileComment = -4213; //* Bad Profile comment during drawpicture */
{$EXTERNALSYM cmRangeOverFlow}
cmRangeOverFlow = -4214; //* Color conversion warning that some output color values over/underflowed and were clipped */
{$EXTERNALSYM cmNamedColorNotFound}
cmNamedColorNotFound = -4216; //* NamedColor not found */
{$EXTERNALSYM cmCantGamutCheckError}
cmCantGamutCheckError = -4217; //* Gammut checking not supported by this ColorWorld */
//};
//* new Folder Manager error codes */
//enum {
{$EXTERNALSYM badFolderDescErr}
badFolderDescErr = -4270;
{$EXTERNALSYM duplicateFolderDescErr}
duplicateFolderDescErr = -4271;
{$EXTERNALSYM noMoreFolderDescErr}
noMoreFolderDescErr = -4272;
{$EXTERNALSYM invalidFolderTypeErr}
invalidFolderTypeErr = -4273;
{$EXTERNALSYM duplicateRoutingErr}
duplicateRoutingErr = -4274;
{$EXTERNALSYM routingNotFoundErr}
routingNotFoundErr = -4275;
{$EXTERNALSYM badRoutingSizeErr}
badRoutingSizeErr = -4276;
//};
//* Core Foundation errors*/
//enum {
{$EXTERNALSYM coreFoundationUnknownErr}
coreFoundationUnknownErr = -4960;
//};
//* CoreEndian error codes. These can be returned by Flippers. */
//enum {
{$EXTERNALSYM errCoreEndianDataTooShortForFormat}
errCoreEndianDataTooShortForFormat = -4940;
{$EXTERNALSYM errCoreEndianDataTooLongForFormat}
errCoreEndianDataTooLongForFormat = -4941;
{$EXTERNALSYM errCoreEndianDataDoesNotMatchFormat}
errCoreEndianDataDoesNotMatchFormat = -4942;
//};
//* ScrapMgr error codes (CarbonLib 1.0 and later)*/
//enum {
{$EXTERNALSYM internalScrapErr}
internalScrapErr = -4988;
{$EXTERNALSYM duplicateScrapFlavorErr}
duplicateScrapFlavorErr = -4989;
{$EXTERNALSYM badScrapRefErr}
badScrapRefErr = -4990;
{$EXTERNALSYM processStateIncorrectErr}
processStateIncorrectErr = -4991;
{$EXTERNALSYM scrapPromiseNotKeptErr}
scrapPromiseNotKeptErr = -4992;
{$EXTERNALSYM noScrapPromiseKeeperErr}
noScrapPromiseKeeperErr = -4993;
{$EXTERNALSYM nilScrapFlavorDataErr}
nilScrapFlavorDataErr = -4994;
{$EXTERNALSYM scrapFlavorFlagsMismatchErr}
scrapFlavorFlagsMismatchErr = -4995;
{$EXTERNALSYM scrapFlavorSizeMismatchErr}
scrapFlavorSizeMismatchErr = -4996;
{$EXTERNALSYM illegalScrapFlavorFlagsErr}
illegalScrapFlavorFlagsErr = -4997;
{$EXTERNALSYM illegalScrapFlavorTypeErr}
illegalScrapFlavorTypeErr = -4998;
{$EXTERNALSYM illegalScrapFlavorSizeErr}
illegalScrapFlavorSizeErr = -4999;
{$EXTERNALSYM scrapFlavorNotFoundErr}
scrapFlavorNotFoundErr = -102; //* == noTypeErr*/
{$EXTERNALSYM needClearScrapErr}
needClearScrapErr = -100; //* == noScrapErr*/
//};
//enum {
//* AFP Protocol Errors */
{$EXTERNALSYM afpAccessDenied}
afpAccessDenied = -5000; //* Insufficient access privileges for operation */
{$EXTERNALSYM afpAuthContinue}
afpAuthContinue = -5001; //* Further information required to complete AFPLogin call */
{$EXTERNALSYM afpBadUAM}
afpBadUAM = -5002; //* Unknown user authentication method specified */
{$EXTERNALSYM afpBadVersNum}
afpBadVersNum = -5003; //* Unknown AFP protocol version number specified */
{$EXTERNALSYM afpBitmapErr}
afpBitmapErr = -5004; //* Bitmap contained bits undefined for call */
{$EXTERNALSYM afpCantMove}
afpCantMove = -5005; //* Move destination is offspring of source, or root was specified */
{$EXTERNALSYM afpDenyConflict}
afpDenyConflict = -5006; //* Specified open/deny modes conflict with current open modes */
{$EXTERNALSYM afpDirNotEmpty}
afpDirNotEmpty = -5007; //* Cannot delete non-empty directory */
{$EXTERNALSYM afpDiskFull}
afpDiskFull = -5008; //* Insufficient free space on volume for operation */
{$EXTERNALSYM afpEofError}
afpEofError = -5009; //* Read beyond logical end-of-file */
{$EXTERNALSYM afpFileBusy}
afpFileBusy = -5010; //* Cannot delete an open file */
{$EXTERNALSYM afpFlatVol}
afpFlatVol = -5011; //* Cannot create directory on specified volume */
{$EXTERNALSYM afpItemNotFound}
afpItemNotFound = -5012; //* Unknown UserName/UserID or missing comment/APPL entry */
{$EXTERNALSYM afpLockErr}
afpLockErr = -5013; //* Some or all of requested range is locked by another user */
{$EXTERNALSYM afpMiscErr}
afpMiscErr = -5014; //* Unexpected error encountered during execution */
{$EXTERNALSYM afpNoMoreLocks}
afpNoMoreLocks = -5015; //* Maximum lock limit reached */
{$EXTERNALSYM afpNoServer}
afpNoServer = -5016; //* Server not responding */
{$EXTERNALSYM afpObjectExists}
afpObjectExists = -5017; //* Specified destination file or directory already exists */
{$EXTERNALSYM afpObjectNotFound}
afpObjectNotFound = -5018; //* Specified file or directory does not exist */
{$EXTERNALSYM afpParmErr}
afpParmErr = -5019; //* A specified parameter was out of allowable range */
{$EXTERNALSYM afpRangeNotLocked}
afpRangeNotLocked = -5020; //* Tried to unlock range that was not locked by user */
{$EXTERNALSYM afpRangeOverlap}
afpRangeOverlap = -5021; //* Some or all of range already locked by same user */
{$EXTERNALSYM afpSessClosed}
afpSessClosed = -5022; //* Session closed*/
{$EXTERNALSYM afpUserNotAuth}
afpUserNotAuth = -5023; //* No AFPLogin call has successfully been made for this session */
{$EXTERNALSYM afpCallNotSupported}
afpCallNotSupported = -5024; //* Unsupported AFP call was made */
{$EXTERNALSYM afpObjectTypeErr}
afpObjectTypeErr = -5025; //* File/Directory specified where Directory/File expected */
{$EXTERNALSYM afpTooManyFilesOpen}
afpTooManyFilesOpen = -5026; //* Maximum open file count reached */
{$EXTERNALSYM afpServerGoingDown}
afpServerGoingDown = -5027; //* Server is shutting down */
{$EXTERNALSYM afpCantRename}
afpCantRename = -5028; //* AFPRename cannot rename volume */
{$EXTERNALSYM afpDirNotFound}
afpDirNotFound = -5029; //* Unknown directory specified */
{$EXTERNALSYM afpIconTypeError}
afpIconTypeError = -5030; //* Icon size specified different from existing icon size */
{$EXTERNALSYM afpVolLocked}
afpVolLocked = -5031; //* Volume is Read-Only */
{$EXTERNALSYM afpObjectLocked}
afpObjectLocked = -5032; //* Object is M/R/D/W inhibited*/
{$EXTERNALSYM afpContainsSharedErr}
afpContainsSharedErr = -5033; //* the folder being shared contains a shared folder*/
{$EXTERNALSYM afpIDNotFound}
afpIDNotFound = -5034;
{$EXTERNALSYM afpIDExists}
afpIDExists = -5035;
{$EXTERNALSYM afpDiffVolErr}
afpDiffVolErr = -5036;
{$EXTERNALSYM afpCatalogChanged}
afpCatalogChanged = -5037;
{$EXTERNALSYM afpSameObjectErr}
afpSameObjectErr = -5038;
{$EXTERNALSYM afpBadIDErr}
afpBadIDErr = -5039;
{$EXTERNALSYM afpPwdSameErr}
afpPwdSameErr = -5040; //* Someone tried to change their password to the same password on a mantadory password change */
{$EXTERNALSYM afpPwdTooShortErr}
afpPwdTooShortErr = -5041; //* The password being set is too short: there is a minimum length that must be met or exceeded */
{$EXTERNALSYM afpPwdExpiredErr}
afpPwdExpiredErr = -5042; //* The password being used is too old: this requires the user to change the password before log-in can continue */
{$EXTERNALSYM afpInsideSharedErr}
afpInsideSharedErr = -5043; //* The folder being shared is inside a shared folder OR the folder contains a shared folder and is being moved into a shared folder */
//* OR the folder contains a shared folder and is being moved into the descendent of a shared folder.*/
{$EXTERNALSYM afpInsideTrashErr}
afpInsideTrashErr = -5044; //* The folder being shared is inside the trash folder OR the shared folder is being moved into the trash folder */
//* OR the folder is being moved to the trash and it contains a shared folder */
{$EXTERNALSYM afpPwdNeedsChangeErr}
afpPwdNeedsChangeErr = -5045; //* The password needs to be changed*/
{$EXTERNALSYM afpPwdPolicyErr}
afpPwdPolicyErr = -5046; //* Password does not conform to servers password policy */
{$EXTERNALSYM afpAlreadyLoggedInErr}
afpAlreadyLoggedInErr = -5047; //* User has been authenticated but is already logged in from another machine (and that's not allowed on this server) */
{$EXTERNALSYM afpCallNotAllowed}
afpCallNotAllowed = -5048; //* The server knows what you wanted to do, but won't let you do it just now */
//};
//enum {
//* AppleShare Client Errors */
{$EXTERNALSYM afpBadDirIDType}
afpBadDirIDType = -5060;
{$EXTERNALSYM afpCantMountMoreSrvre}
afpCantMountMoreSrvre = -5061; //* The Maximum number of server connections has been reached */
{$EXTERNALSYM afpAlreadyMounted}
afpAlreadyMounted = -5062; //* The volume is already mounted */
{$EXTERNALSYM afpSameNodeErr}
afpSameNodeErr = -5063; //* An Attempt was made to connect to a file server running on the same machine */
//};
//*Text Engines, TSystemTextEngines, HIEditText error coded*/
//* NumberFormatting error codes*/
//enum {
{$EXTERNALSYM numberFormattingNotANumberErr}
numberFormattingNotANumberErr = -5200;
{$EXTERNALSYM numberFormattingOverflowInDestinationErr}
numberFormattingOverflowInDestinationErr = -5201;
{$EXTERNALSYM numberFormattingBadNumberFormattingObjectErr}
numberFormattingBadNumberFormattingObjectErr = -5202;
{$EXTERNALSYM numberFormattingSpuriousCharErr}
numberFormattingSpuriousCharErr = -5203;
{$EXTERNALSYM numberFormattingLiteralMissingErr}
numberFormattingLiteralMissingErr = -5204;
{$EXTERNALSYM numberFormattingDelimiterMissingErr}
numberFormattingDelimiterMissingErr = -5205;
{$EXTERNALSYM numberFormattingEmptyFormatErr}
numberFormattingEmptyFormatErr = -5206;
{$EXTERNALSYM numberFormattingBadFormatErr}
numberFormattingBadFormatErr = -5207;
{$EXTERNALSYM numberFormattingBadOptionsErr}
numberFormattingBadOptionsErr = -5208;
{$EXTERNALSYM numberFormattingBadTokenErr}
numberFormattingBadTokenErr = -5209;
{$EXTERNALSYM numberFormattingUnOrderedCurrencyRangeErr}
numberFormattingUnOrderedCurrencyRangeErr = -5210;
{$EXTERNALSYM numberFormattingBadCurrencyPositionErr}
numberFormattingBadCurrencyPositionErr = -5211;
{$EXTERNALSYM numberFormattingNotADigitErr}
numberFormattingNotADigitErr = -5212; //* deprecated misspelled versions:*/
{$EXTERNALSYM numberFormattingUnOrdredCurrencyRangeErr}
numberFormattingUnOrdredCurrencyRangeErr = -5210;
{$EXTERNALSYM numberFortmattingNotADigitErr}
numberFortmattingNotADigitErr = -5212;
//};
//* TextParser error codes*/
//enum {
{$EXTERNALSYM textParserBadParamErr}
textParserBadParamErr = -5220;
{$EXTERNALSYM textParserObjectNotFoundErr}
textParserObjectNotFoundErr = -5221;
{$EXTERNALSYM textParserBadTokenValueErr}
textParserBadTokenValueErr = -5222;
{$EXTERNALSYM textParserBadParserObjectErr}
textParserBadParserObjectErr = -5223;
{$EXTERNALSYM textParserParamErr}
textParserParamErr = -5224;
{$EXTERNALSYM textParserNoMoreTextErr}
textParserNoMoreTextErr = -5225;
{$EXTERNALSYM textParserBadTextLanguageErr}
textParserBadTextLanguageErr = -5226;
{$EXTERNALSYM textParserBadTextEncodingErr}
textParserBadTextEncodingErr = -5227;
{$EXTERNALSYM textParserNoSuchTokenFoundErr}
textParserNoSuchTokenFoundErr = -5228;
{$EXTERNALSYM textParserNoMoreTokensErr}
textParserNoMoreTokensErr = -5229;
//};
//enum {
{$EXTERNALSYM errUnknownAttributeTag}
errUnknownAttributeTag = -5240;
{$EXTERNALSYM errMarginWilllNotFit}
errMarginWilllNotFit = -5241;
{$EXTERNALSYM errNotInImagingMode}
errNotInImagingMode = -5242;
{$EXTERNALSYM errAlreadyInImagingMode}
errAlreadyInImagingMode = -5243;
{$EXTERNALSYM errEngineNotFound}
errEngineNotFound = -5244;
{$EXTERNALSYM errIteratorReachedEnd}
errIteratorReachedEnd = -5245;
{$EXTERNALSYM errInvalidRange}
errInvalidRange = -5246;
{$EXTERNALSYM errOffsetNotOnElementBounday}
errOffsetNotOnElementBounday = -5247;
{$EXTERNALSYM errNoHiliteText}
errNoHiliteText = -5248;
{$EXTERNALSYM errEmptyScrap}
errEmptyScrap = -5249;
{$EXTERNALSYM errReadOnlyText}
errReadOnlyText = -5250;
{$EXTERNALSYM errUnknownElement}
errUnknownElement = -5251;
{$EXTERNALSYM errNonContiuousAttribute}
errNonContiuousAttribute = -5252;
{$EXTERNALSYM errCannotUndo}
errCannotUndo = -5253;
//};
//* HTMLRendering OSStaus codes*/
//enum {
{$EXTERNALSYM hrHTMLRenderingLibNotInstalledErr}
hrHTMLRenderingLibNotInstalledErr = -5360;
{$EXTERNALSYM hrMiscellaneousExceptionErr}
hrMiscellaneousExceptionErr = -5361;
{$EXTERNALSYM hrUnableToResizeHandleErr}
hrUnableToResizeHandleErr = -5362;
{$EXTERNALSYM hrURLNotHandledErr}
hrURLNotHandledErr = -5363;
//};
//* IAExtractor result codes */
//enum {
{$EXTERNALSYM errIANoErr}
errIANoErr = 0;
{$EXTERNALSYM errIAUnknownErr}
errIAUnknownErr = -5380;
{$EXTERNALSYM errIAAllocationErr}
errIAAllocationErr = -5381;
{$EXTERNALSYM errIAParamErr}
errIAParamErr = -5382;
{$EXTERNALSYM errIANoMoreItems}
errIANoMoreItems = -5383;
{$EXTERNALSYM errIABufferTooSmall}
errIABufferTooSmall = -5384;
{$EXTERNALSYM errIACanceled}
errIACanceled = -5385;
{$EXTERNALSYM errIAInvalidDocument}
errIAInvalidDocument = -5386;
{$EXTERNALSYM errIATextExtractionErr}
errIATextExtractionErr = -5387;
{$EXTERNALSYM errIAEndOfTextRun}
errIAEndOfTextRun = -5388;
//};
//* QuickTime Streaming Errors */
//enum {
{$EXTERNALSYM qtsBadSelectorErr}
qtsBadSelectorErr = -5400;
{$EXTERNALSYM qtsBadStateErr}
qtsBadStateErr = -5401;
{$EXTERNALSYM qtsBadDataErr}
qtsBadDataErr = -5402; //* something is wrong with the data */
{$EXTERNALSYM qtsUnsupportedDataTypeErr}
qtsUnsupportedDataTypeErr = -5403;
{$EXTERNALSYM qtsUnsupportedRateErr}
qtsUnsupportedRateErr = -5404;
{$EXTERNALSYM qtsUnsupportedFeatureErr}
qtsUnsupportedFeatureErr = -5405;
{$EXTERNALSYM qtsTooMuchDataErr}
qtsTooMuchDataErr = -5406;
{$EXTERNALSYM qtsUnknownValueErr}
qtsUnknownValueErr = -5407;
{$EXTERNALSYM qtsTimeoutErr}
qtsTimeoutErr = -5408;
{$EXTERNALSYM qtsConnectionFailedErr}
qtsConnectionFailedErr = -5420;
{$EXTERNALSYM qtsAddressBusyErr}
qtsAddressBusyErr = -5421;
//};
//enum {
//*Gestalt error codes*/
{$EXTERNALSYM gestaltUnknownErr}
gestaltUnknownErr = -5550; //*value returned if Gestalt doesn't know the answer*/
{$EXTERNALSYM gestaltUndefSelectorErr}
gestaltUndefSelectorErr = -5551; //*undefined selector was passed to Gestalt*/
{$EXTERNALSYM gestaltDupSelectorErr}
gestaltDupSelectorErr = -5552; //*tried to add an entry that already existed*/
{$EXTERNALSYM gestaltLocationErr}
gestaltLocationErr = -5553; //*gestalt function ptr wasn't in sysheap*/
//};
//* Menu Manager error codes*/
//enum {
{$EXTERNALSYM menuPropertyInvalidErr}
menuPropertyInvalidErr = -5603; //* invalid property creator */
{$EXTERNALSYM menuPropertyInvalid}
menuPropertyInvalid = menuPropertyInvalidErr; //* "menuPropertyInvalid" is deprecated */
{$EXTERNALSYM menuPropertyNotFoundErr}
menuPropertyNotFoundErr = -5604; //* specified property wasn't found */
{$EXTERNALSYM menuNotFoundErr}
menuNotFoundErr = -5620; //* specified menu or menu ID wasn't found */
{$EXTERNALSYM menuUsesSystemDefErr}
menuUsesSystemDefErr = -5621; //* GetMenuDefinition failed because the menu uses the system MDEF */
{$EXTERNALSYM menuItemNotFoundErr}
menuItemNotFoundErr = -5622; //* specified menu item wasn't found*/
{$EXTERNALSYM menuInvalidErr}
menuInvalidErr = -5623; //* menu is invalid*/
//};
//* Window Manager error codes*/
//enum {
{$EXTERNALSYM errInvalidWindowPtr}
errInvalidWindowPtr = -5600; //* tried to pass a bad WindowRef argument*/
{$EXTERNALSYM errInvalidWindowRef}
errInvalidWindowRef = -5600; //* tried to pass a bad WindowRef argument*/
{$EXTERNALSYM errUnsupportedWindowAttributesForClass}
errUnsupportedWindowAttributesForClass = -5601; //* tried to create a window with WindowAttributes not supported by the WindowClass*/
{$EXTERNALSYM errWindowDoesNotHaveProxy}
errWindowDoesNotHaveProxy = -5602; //* tried to do something requiring a proxy to a window which doesn’t have a proxy*/
{$EXTERNALSYM errInvalidWindowProperty}
errInvalidWindowProperty = -5603; //* tried to access a property tag with private creator*/
{$EXTERNALSYM errWindowPropertyNotFound}
errWindowPropertyNotFound = -5604; //* tried to get a nonexistent property*/
{$EXTERNALSYM errUnrecognizedWindowClass}
errUnrecognizedWindowClass = -5605; //* tried to create a window with a bad WindowClass*/
{$EXTERNALSYM errCorruptWindowDescription}
errCorruptWindowDescription = -5606; //* tried to load a corrupt window description (size or version fields incorrect)*/
{$EXTERNALSYM errUserWantsToDragWindow}
errUserWantsToDragWindow = -5607; //* if returned from TrackWindowProxyDrag, you should call DragWindow on the window*/
{$EXTERNALSYM errWindowsAlreadyInitialized}
errWindowsAlreadyInitialized = -5608; //* tried to call InitFloatingWindows twice, or called InitWindows and then floating windows*/
{$EXTERNALSYM errFloatingWindowsNotInitialized}
errFloatingWindowsNotInitialized = -5609; //* called HideFloatingWindows or ShowFloatingWindows without calling InitFloatingWindows*/
{$EXTERNALSYM errWindowNotFound}
errWindowNotFound = -5610; //* returned from FindWindowOfClass*/
{$EXTERNALSYM errWindowDoesNotFitOnscreen}
errWindowDoesNotFitOnscreen = -5611; //* ConstrainWindowToScreen could not make the window fit onscreen*/
{$EXTERNALSYM windowAttributeImmutableErr}
windowAttributeImmutableErr = -5612; //* tried to change attributes which can't be changed*/
{$EXTERNALSYM windowAttributesConflictErr}
windowAttributesConflictErr = -5613; //* passed some attributes that are mutually exclusive*/
{$EXTERNALSYM windowManagerInternalErr}
windowManagerInternalErr = -5614; //* something really weird happened inside the window manager*/
{$EXTERNALSYM windowWrongStateErr}
windowWrongStateErr = -5615; //* window is not in a state that is valid for the current action*/
{$EXTERNALSYM windowGroupInvalidErr}
windowGroupInvalidErr = -5616; //* WindowGroup is invalid*/
{$EXTERNALSYM windowAppModalStateAlreadyExistsErr}
windowAppModalStateAlreadyExistsErr = -5617; //* we're already running this window modally*/
{$EXTERNALSYM windowNoAppModalStateErr}
windowNoAppModalStateErr = -5618; //* there's no app modal state for the window*/
{$EXTERNALSYM errWindowDoesntSupportFocus}
errWindowDoesntSupportFocus = -30583;
{$EXTERNALSYM errWindowRegionCodeInvalid}
errWindowRegionCodeInvalid = -30593;
//};
//* Dialog Mgr error codes*/
//enum {
{$EXTERNALSYM dialogNoTimeoutErr}
dialogNoTimeoutErr = -5640;
//};
//* NavigationLib error codes*/
//enum {
{$EXTERNALSYM kNavWrongDialogStateErr}
kNavWrongDialogStateErr = -5694;
{$EXTERNALSYM kNavWrongDialogClassErr}
kNavWrongDialogClassErr = -5695;
{$EXTERNALSYM kNavInvalidSystemConfigErr}
kNavInvalidSystemConfigErr = -5696;
{$EXTERNALSYM kNavCustomControlMessageFailedErr}
kNavCustomControlMessageFailedErr = -5697;
{$EXTERNALSYM kNavInvalidCustomControlMessageErr}
kNavInvalidCustomControlMessageErr = -5698;
{$EXTERNALSYM kNavMissingKindStringErr}
kNavMissingKindStringErr = -5699;
//};
//* Collection Manager errors */
//enum {
{$EXTERNALSYM collectionItemLockedErr}
collectionItemLockedErr = -5750;
{$EXTERNALSYM collectionItemNotFoundErr}
collectionItemNotFoundErr = -5751;
{$EXTERNALSYM collectionIndexRangeErr}
collectionIndexRangeErr = -5752;
{$EXTERNALSYM collectionVersionErr}
collectionVersionErr = -5753;
//};
//* QuickTime Streaming Server Errors */
//enum {
{$EXTERNALSYM kQTSSUnknownErr}
kQTSSUnknownErr = -6150;
//};
//enum {
//* Display Manager error codes (-6220...-6269)*/
{$EXTERNALSYM kDMGenErr}
kDMGenErr = -6220; //*Unexpected Error*/
//* Mirroring-Specific Errors */
{$EXTERNALSYM kDMMirroringOnAlready}
kDMMirroringOnAlready = -6221; //*Returned by all calls that need mirroring to be off to do their thing.*/
{$EXTERNALSYM kDMWrongNumberOfDisplays}
kDMWrongNumberOfDisplays = -6222; //*Can only handle 2 displays for now.*/
{$EXTERNALSYM kDMMirroringBlocked}
kDMMirroringBlocked = -6223; //*DMBlockMirroring() has been called.*/
{$EXTERNALSYM kDMCantBlock}
kDMCantBlock = -6224; //*Mirroring is already on, can’t Block now (call DMUnMirror() first).*/
{$EXTERNALSYM kDMMirroringNotOn}
kDMMirroringNotOn = -6225; //*Returned by all calls that need mirroring to be on to do their thing.*/
//* Other Display Manager Errors */
{$EXTERNALSYM kSysSWTooOld}
kSysSWTooOld = -6226; //*Missing critical pieces of System Software.*/
{$EXTERNALSYM kDMSWNotInitializedErr}
kDMSWNotInitializedErr = -6227; //*Required software not initialized (eg windowmanager or display mgr).*/
{$EXTERNALSYM kDMDriverNotDisplayMgrAwareErr}
kDMDriverNotDisplayMgrAwareErr = -6228; //*Video Driver does not support display manager.*/
{$EXTERNALSYM kDMDisplayNotFoundErr}
kDMDisplayNotFoundErr = -6229; //*Could not find item (will someday remove).*/
{$EXTERNALSYM kDMNotFoundErr}
kDMNotFoundErr = -6229; //*Could not find item.*/
{$EXTERNALSYM kDMDisplayAlreadyInstalledErr}
kDMDisplayAlreadyInstalledErr = -6230; //*Attempt to add an already installed display.*/
{$EXTERNALSYM kDMMainDisplayCannotMoveErr}
kDMMainDisplayCannotMoveErr = -6231; //*Trying to move main display (or a display mirrored to it) */
{$EXTERNALSYM kDMNoDeviceTableclothErr}
kDMNoDeviceTableclothErr = -6231; //*obsolete*/
{$EXTERNALSYM kDMFoundErr}
kDMFoundErr = -6232; //*Did not proceed because we found an item*/
//};
{*
Language Analysis error codes
*}
//enum {
{$EXTERNALSYM laTooSmallBufferErr}
laTooSmallBufferErr = -6984; //* output buffer is too small to store any result */
{$EXTERNALSYM laEnvironmentBusyErr}
laEnvironmentBusyErr = -6985; //* specified environment is used */
{$EXTERNALSYM laEnvironmentNotFoundErr}
laEnvironmentNotFoundErr = -6986; //* can't fint the specified environment */
{$EXTERNALSYM laEnvironmentExistErr}
laEnvironmentExistErr = -6987; //* same name environment is already exists */
{$EXTERNALSYM laInvalidPathErr}
laInvalidPathErr = -6988; //* path is not correct */
{$EXTERNALSYM laNoMoreMorphemeErr}
laNoMoreMorphemeErr = -6989; //* nothing to read*/
{$EXTERNALSYM laFailAnalysisErr}
laFailAnalysisErr = -6990; //* analysis failed*/
{$EXTERNALSYM laTextOverFlowErr}
laTextOverFlowErr = -6991; //* text is too long*/
{$EXTERNALSYM laDictionaryNotOpenedErr}
laDictionaryNotOpenedErr = -6992; //* the dictionary is not opened*/
{$EXTERNALSYM laDictionaryUnknownErr}
laDictionaryUnknownErr = -6993; //* can't use this dictionary with this environment*/
{$EXTERNALSYM laDictionaryTooManyErr}
laDictionaryTooManyErr = -6994; //* too many dictionaries*/
{$EXTERNALSYM laPropertyValueErr}
laPropertyValueErr = -6995; //* Invalid property value*/
{$EXTERNALSYM laPropertyUnknownErr}
laPropertyUnknownErr = -6996; //* the property is unknown to this environment*/
{$EXTERNALSYM laPropertyIsReadOnlyErr}
laPropertyIsReadOnlyErr = -6997; //* the property is read only*/
{$EXTERNALSYM laPropertyNotFoundErr}
laPropertyNotFoundErr = -6998; //* can't find the property*/
{$EXTERNALSYM laPropertyErr}
laPropertyErr = -6999; //* Error in properties*/
{$EXTERNALSYM laEngineNotFoundErr}
laEngineNotFoundErr = -7000; //* can't find the engine*/
//};
//enum {
{$EXTERNALSYM kUSBNoErr}
kUSBNoErr = 0;
{$EXTERNALSYM kUSBNoTran}
kUSBNoTran = 0;
{$EXTERNALSYM kUSBNoDelay}
kUSBNoDelay = 0;
{$EXTERNALSYM kUSBPending}
kUSBPending = 1;
//};
{*
USB Hardware Errors
Note pipe stalls are communication
errors. The affected pipe can not
be used until USBClearPipeStallByReference
is used.
kUSBEndpointStallErr is returned in
response to a stall handshake
from a device. The device has to be
cleared before a USBClearPipeStallByReference
can be used.
*}
//enum {
{$EXTERNALSYM kUSBNotSent2Err}
kUSBNotSent2Err = -6901; //* Transaction not sent */
{$EXTERNALSYM kUSBNotSent1Err}
kUSBNotSent1Err = -6902; //* Transaction not sent */
{$EXTERNALSYM kUSBBufUnderRunErr}
kUSBBufUnderRunErr = -6903; //* Host hardware failure on data out, PCI busy? */
{$EXTERNALSYM kUSBBufOvrRunErr}
kUSBBufOvrRunErr = -6904; //* Host hardware failure on data in, PCI busy? */
{$EXTERNALSYM kUSBRes2Err}
kUSBRes2Err = -6905;
{$EXTERNALSYM kUSBRes1Err}
kUSBRes1Err = -6906;
{$EXTERNALSYM kUSBUnderRunErr}
kUSBUnderRunErr = -6907; //* Less data than buffer */
{$EXTERNALSYM kUSBOverRunErr}
kUSBOverRunErr = -6908; //* Packet too large or more data than buffer */
{$EXTERNALSYM kUSBWrongPIDErr}
kUSBWrongPIDErr = -6909; //* Pipe stall, Bad or wrong PID */
{$EXTERNALSYM kUSBPIDCheckErr}
kUSBPIDCheckErr = -6910; //* Pipe stall, PID CRC error */
{$EXTERNALSYM kUSBNotRespondingErr}
kUSBNotRespondingErr = -6911; //* Pipe stall, No device, device hung */
{$EXTERNALSYM kUSBEndpointStallErr}
kUSBEndpointStallErr = -6912; //* Device didn't understand */
{$EXTERNALSYM kUSBDataToggleErr}
kUSBDataToggleErr = -6913; //* Pipe stall, Bad data toggle */
{$EXTERNALSYM kUSBBitstufErr}
kUSBBitstufErr = -6914; //* Pipe stall, bitstuffing */
{$EXTERNALSYM kUSBCRCErr}
kUSBCRCErr = -6915; //* Pipe stall, bad CRC */
{$EXTERNALSYM kUSBLinkErr}
kUSBLinkErr = -6916;
//};
{*
USB Manager Errors
*}
//enum {
{$EXTERNALSYM kUSBQueueFull}
kUSBQueueFull = -6948; //* Internal queue maxxed */
{$EXTERNALSYM kUSBNotHandled}
kUSBNotHandled = -6987; //* Notification was not handled (same as NotFound)*/
{$EXTERNALSYM kUSBUnknownNotification}
kUSBUnknownNotification = -6949; //* Notification type not defined */
{$EXTERNALSYM kUSBBadDispatchTable}
kUSBBadDispatchTable = -6950; //* Improper driver dispatch table */
//};
{*
USB internal errors are in range -6960 to -6951
please do not use this range
*}
//enum {
{$EXTERNALSYM kUSBInternalReserved10}
kUSBInternalReserved10 = -6951;
{$EXTERNALSYM kUSBInternalReserved9}
kUSBInternalReserved9 = -6952;
{$EXTERNALSYM kUSBInternalReserved8}
kUSBInternalReserved8 = -6953;
{$EXTERNALSYM kUSBInternalReserved7}
kUSBInternalReserved7 = -6954;
{$EXTERNALSYM kUSBInternalReserved6}
kUSBInternalReserved6 = -6955;
{$EXTERNALSYM kUSBInternalReserved5}
kUSBInternalReserved5 = -6956;
{$EXTERNALSYM kUSBInternalReserved4}
kUSBInternalReserved4 = -6957;
{$EXTERNALSYM kUSBInternalReserved3}
kUSBInternalReserved3 = -6958;
{$EXTERNALSYM kUSBInternalReserved2}
kUSBInternalReserved2 = -6959;
{$EXTERNALSYM kUSBInternalReserved1}
kUSBInternalReserved1 = -6960; //* reserved*/
//};
//* USB Services Errors */
//enum {
{$EXTERNALSYM kUSBPortDisabled}
kUSBPortDisabled = -6969; //* The port you are attached to is disabled, use USBDeviceReset.*/
{$EXTERNALSYM kUSBQueueAborted}
kUSBQueueAborted = -6970; //* Pipe zero stall cleared.*/
{$EXTERNALSYM kUSBTimedOut}
kUSBTimedOut = -6971; //* Transaction timed out. */
{$EXTERNALSYM kUSBDeviceDisconnected}
kUSBDeviceDisconnected = -6972; //* Disconnected during suspend or reset */
{$EXTERNALSYM kUSBDeviceNotSuspended}
kUSBDeviceNotSuspended = -6973; //* device is not suspended for resume */
{$EXTERNALSYM kUSBDeviceSuspended}
kUSBDeviceSuspended = -6974; //* Device is suspended */
{$EXTERNALSYM kUSBInvalidBuffer}
kUSBInvalidBuffer = -6975; //* bad buffer, usually nil */
{$EXTERNALSYM kUSBDevicePowerProblem}
kUSBDevicePowerProblem = -6976; //* Device has a power problem */
{$EXTERNALSYM kUSBDeviceBusy}
kUSBDeviceBusy = -6977; //* Device is already being configured */
{$EXTERNALSYM kUSBUnknownInterfaceErr}
kUSBUnknownInterfaceErr = -6978; //* Interface ref not recognised */
{$EXTERNALSYM kUSBPipeStalledError}
kUSBPipeStalledError = -6979; //* Pipe has stalled, error needs to be cleared */
{$EXTERNALSYM kUSBPipeIdleError}
kUSBPipeIdleError = -6980; //* Pipe is Idle, it will not accept transactions */
{$EXTERNALSYM kUSBNoBandwidthError}
kUSBNoBandwidthError = -6981; //* Not enough bandwidth available */
{$EXTERNALSYM kUSBAbortedError}
kUSBAbortedError = -6982; //* Pipe aborted */
{$EXTERNALSYM kUSBFlagsError}
kUSBFlagsError = -6983; //* Unused flags not zeroed */
{$EXTERNALSYM kUSBCompletionError}
kUSBCompletionError = -6984; //* no completion routine specified */
{$EXTERNALSYM kUSBPBLengthError}
kUSBPBLengthError = -6985; //* pbLength too small */
{$EXTERNALSYM kUSBPBVersionError}
kUSBPBVersionError = -6986; //* Wrong pbVersion */
{$EXTERNALSYM kUSBNotFound}
kUSBNotFound = -6987; //* Not found */
{$EXTERNALSYM kUSBOutOfMemoryErr}
kUSBOutOfMemoryErr = -6988; //* Out of memory */
{$EXTERNALSYM kUSBDeviceErr}
kUSBDeviceErr = -6989; //* Device error */
{$EXTERNALSYM kUSBNoDeviceErr}
kUSBNoDeviceErr = -6990; //* No device*/
{$EXTERNALSYM kUSBAlreadyOpenErr}
kUSBAlreadyOpenErr = -6991; //* Already open */
{$EXTERNALSYM kUSBTooManyTransactionsErr}
kUSBTooManyTransactionsErr = -6992; //* Too many transactions */
{$EXTERNALSYM kUSBUnknownRequestErr}
kUSBUnknownRequestErr = -6993; //* Unknown request */
{$EXTERNALSYM kUSBRqErr}
kUSBRqErr = -6994; //* Request error */
{$EXTERNALSYM kUSBIncorrectTypeErr}
kUSBIncorrectTypeErr = -6995; //* Incorrect type */
{$EXTERNALSYM kUSBTooManyPipesErr}
kUSBTooManyPipesErr = -6996; //* Too many pipes */
{$EXTERNALSYM kUSBUnknownPipeErr}
kUSBUnknownPipeErr = -6997; //* Pipe ref not recognised */
{$EXTERNALSYM kUSBUnknownDeviceErr}
kUSBUnknownDeviceErr = -6998; //* device ref not recognised */
{$EXTERNALSYM kUSBInternalErr}
kUSBInternalErr = -6999; //* Internal error */
//};
{*
DictionaryMgr error codes
*}
//enum {
{$EXTERNALSYM dcmParamErr}
dcmParamErr = -7100; //* bad parameter*/
{$EXTERNALSYM dcmNotDictionaryErr}
dcmNotDictionaryErr = -7101; //* not dictionary*/
{$EXTERNALSYM dcmBadDictionaryErr}
dcmBadDictionaryErr = -7102; //* invalid dictionary*/
{$EXTERNALSYM dcmPermissionErr}
dcmPermissionErr = -7103; //* invalid permission*/
{$EXTERNALSYM dcmDictionaryNotOpenErr}
dcmDictionaryNotOpenErr = -7104; //* dictionary not opened*/
{$EXTERNALSYM dcmDictionaryBusyErr}
dcmDictionaryBusyErr = -7105; //* dictionary is busy*/
{$EXTERNALSYM dcmBlockFullErr}
dcmBlockFullErr = -7107; //* dictionary block full*/
{$EXTERNALSYM dcmNoRecordErr}
dcmNoRecordErr = -7108; //* no such record*/
{$EXTERNALSYM dcmDupRecordErr}
dcmDupRecordErr = -7109; //* same record already exist*/
{$EXTERNALSYM dcmNecessaryFieldErr}
dcmNecessaryFieldErr = -7110; //* lack required/identify field*/
{$EXTERNALSYM dcmBadFieldInfoErr}
dcmBadFieldInfoErr = -7111; //* incomplete information*/
{$EXTERNALSYM dcmBadFieldTypeErr}
dcmBadFieldTypeErr = -7112; //* no such field type supported*/
{$EXTERNALSYM dcmNoFieldErr}
dcmNoFieldErr = -7113; //* no such field exist*/
{$EXTERNALSYM dcmBadKeyErr}
dcmBadKeyErr = -7115; //* bad key information*/
{$EXTERNALSYM dcmTooManyKeyErr}
dcmTooManyKeyErr = -7116; //* too many key field*/
{$EXTERNALSYM dcmBadDataSizeErr}
dcmBadDataSizeErr = -7117; //* too big data size*/
{$EXTERNALSYM dcmBadFindMethodErr}
dcmBadFindMethodErr = -7118; //* no such find method supported*/
{$EXTERNALSYM dcmBadPropertyErr}
dcmBadPropertyErr = -7119; //* no such property exist*/
{$EXTERNALSYM dcmProtectedErr}
dcmProtectedErr = -7121; //* need keyword to use dictionary*/
{$EXTERNALSYM dcmNoAccessMethodErr}
dcmNoAccessMethodErr = -7122; //* no such AccessMethod*/
{$EXTERNALSYM dcmBadFeatureErr}
dcmBadFeatureErr = -7124; //* invalid AccessMethod feature*/
{$EXTERNALSYM dcmIterationCompleteErr}
dcmIterationCompleteErr = -7126; //* no more item in iterator*/
{$EXTERNALSYM dcmBufferOverflowErr}
dcmBufferOverflowErr = -7127; //* data is larger than buffer size*/
//};
//* Apple Remote Access error codes*/
//enum {
{$EXTERNALSYM kRAInvalidParameter}
kRAInvalidParameter = -7100;
{$EXTERNALSYM kRAInvalidPort}
kRAInvalidPort = -7101;
{$EXTERNALSYM kRAStartupFailed}
kRAStartupFailed = -7102;
{$EXTERNALSYM kRAPortSetupFailed}
kRAPortSetupFailed = -7103;
{$EXTERNALSYM kRAOutOfMemory}
kRAOutOfMemory = -7104;
{$EXTERNALSYM kRANotSupported}
kRANotSupported = -7105;
{$EXTERNALSYM kRAMissingResources}
kRAMissingResources = -7106;
{$EXTERNALSYM kRAIncompatiblePrefs}
kRAIncompatiblePrefs = -7107;
{$EXTERNALSYM kRANotConnected}
kRANotConnected = -7108;
{$EXTERNALSYM kRAConnectionCanceled}
kRAConnectionCanceled = -7109;
{$EXTERNALSYM kRAUnknownUser}
kRAUnknownUser = -7110;
{$EXTERNALSYM kRAInvalidPassword}
kRAInvalidPassword = -7111;
{$EXTERNALSYM kRAInternalError}
kRAInternalError = -7112;
{$EXTERNALSYM kRAInstallationDamaged}
kRAInstallationDamaged = -7113;
{$EXTERNALSYM kRAPortBusy}
kRAPortBusy = -7114;
{$EXTERNALSYM kRAUnknownPortState}
kRAUnknownPortState = -7115;
{$EXTERNALSYM kRAInvalidPortState}
kRAInvalidPortState = -7116;
{$EXTERNALSYM kRAInvalidSerialProtocol}
kRAInvalidSerialProtocol = -7117;
{$EXTERNALSYM kRAUserLoginDisabled}
kRAUserLoginDisabled = -7118;
{$EXTERNALSYM kRAUserPwdChangeRequired}
kRAUserPwdChangeRequired = -7119;
{$EXTERNALSYM kRAUserPwdEntryRequired}
kRAUserPwdEntryRequired = -7120;
{$EXTERNALSYM kRAUserInteractionRequired}
kRAUserInteractionRequired = -7121;
{$EXTERNALSYM kRAInitOpenTransportFailed}
kRAInitOpenTransportFailed = -7122;
{$EXTERNALSYM kRARemoteAccessNotReady}
kRARemoteAccessNotReady = -7123;
{$EXTERNALSYM kRATCPIPInactive}
kRATCPIPInactive = -7124; //* TCP/IP inactive, cannot be loaded*/
{$EXTERNALSYM kRATCPIPNotConfigured}
kRATCPIPNotConfigured = -7125; //* TCP/IP not configured, could be loaded*/
{$EXTERNALSYM kRANotPrimaryInterface}
kRANotPrimaryInterface = -7126; //* when IPCP is not primary TCP/IP intf.*/
{$EXTERNALSYM kRAConfigurationDBInitErr}
kRAConfigurationDBInitErr = -7127;
{$EXTERNALSYM kRAPPPProtocolRejected}
kRAPPPProtocolRejected = -7128;
{$EXTERNALSYM kRAPPPAuthenticationFailed}
kRAPPPAuthenticationFailed = -7129;
{$EXTERNALSYM kRAPPPNegotiationFailed}
kRAPPPNegotiationFailed = -7130;
{$EXTERNALSYM kRAPPPUserDisconnected}
kRAPPPUserDisconnected = -7131;
{$EXTERNALSYM kRAPPPPeerDisconnected}
kRAPPPPeerDisconnected = -7132;
{$EXTERNALSYM kRAPeerNotResponding}
kRAPeerNotResponding = -7133;
{$EXTERNALSYM kRAATalkInactive}
kRAATalkInactive = -7134;
{$EXTERNALSYM kRAExtAuthenticationFailed}
kRAExtAuthenticationFailed = -7135;
{$EXTERNALSYM kRANCPRejectedbyPeer}
kRANCPRejectedbyPeer = -7136;
{$EXTERNALSYM kRADuplicateIPAddr}
kRADuplicateIPAddr = -7137;
{$EXTERNALSYM kRACallBackFailed}
kRACallBackFailed = -7138;
{$EXTERNALSYM kRANotEnabled}
kRANotEnabled = -7139;
//};
//* ATSUI Error Codes - Range 1 of 2*/
//enum {
{$EXTERNALSYM kATSUInvalidTextLayoutErr}
kATSUInvalidTextLayoutErr = -8790; //* An attempt was made to use a ATSUTextLayout */
//* which hadn't been initialized or is otherwise */
//* in an invalid state. */
{$EXTERNALSYM kATSUInvalidStyleErr}
kATSUInvalidStyleErr = -8791; //* An attempt was made to use a ATSUStyle which */
//* hadn't been properly allocated or is otherwise */
//* in an invalid state. */
{$EXTERNALSYM kATSUInvalidTextRangeErr}
kATSUInvalidTextRangeErr = -8792; //* An attempt was made to extract information */
//* from or perform an operation on a ATSUTextLayout */
//* for a range of text not covered by the ATSUTextLayout. */
{$EXTERNALSYM kATSUFontsMatched}
kATSUFontsMatched = -8793; //* This is not an error code but is returned by */
//* ATSUMatchFontsToText() when changes need to */
//* be made to the fonts associated with the text. */
{$EXTERNALSYM kATSUFontsNotMatched}
kATSUFontsNotMatched = -8794; //* This value is returned by ATSUMatchFontsToText() */
//* when the text contains Unicode characters which */
//* cannot be represented by any installed font. */
{$EXTERNALSYM kATSUNoCorrespondingFontErr}
kATSUNoCorrespondingFontErr = -8795; //* This value is retrned by font ID conversion */
//* routines ATSUFONDtoFontID() and ATSUFontIDtoFOND() */
//* to indicate that the input font ID is valid but */
//* there is no conversion possible. For example, */
//* data-fork fonts can only be used with ATSUI not */
//* the FontManager, and so converting an ATSUIFontID */
//* for such a font will fail. */
{$EXTERNALSYM kATSUInvalidFontErr}
kATSUInvalidFontErr = -8796; //* Used when an attempt was made to use an invalid font ID.*/
{$EXTERNALSYM kATSUInvalidAttributeValueErr}
kATSUInvalidAttributeValueErr = -8797; //* Used when an attempt was made to use an attribute with */
//* a bad or undefined value. */
{$EXTERNALSYM kATSUInvalidAttributeSizeErr}
kATSUInvalidAttributeSizeErr = -8798; //* Used when an attempt was made to use an attribute with a */
//* bad size. */
{$EXTERNALSYM kATSUInvalidAttributeTagErr}
kATSUInvalidAttributeTagErr = -8799; //* Used when an attempt was made to use a tag value that*/
//* was not appropriate for the function call it was used. */
{$EXTERNALSYM kATSUInvalidCacheErr}
kATSUInvalidCacheErr = -8800; //* Used when an attempt was made to read in style data */
//* from an invalid cache. Either the format of the */
//* cached data doesn't match that used by Apple Type */
//* Services for Unicode™ Imaging, or the cached data */
//* is corrupt. */
{$EXTERNALSYM kATSUNotSetErr}
kATSUNotSetErr = -8801; //* Used when the client attempts to retrieve an attribute, */
//* font feature, or font variation from a style when it */
//* hadn't been set. In such a case, the default value will*/
//* be returned for the attribute's value.*/
{$EXTERNALSYM kATSUNoStyleRunsAssignedErr}
kATSUNoStyleRunsAssignedErr = -8802; //* Used when an attempt was made to measure, highlight or draw*/
//* a ATSUTextLayout object that has no styleRuns associated with it.*/
{$EXTERNALSYM kATSUQuickDrawTextErr}
kATSUQuickDrawTextErr = -8803; //* Used when QuickDraw Text encounters an error rendering or measuring*/
//* a line of ATSUI text.*/
{$EXTERNALSYM kATSULowLevelErr}
kATSULowLevelErr = -8804; //* Used when an error was encountered within the low level ATS */
//* mechanism performing an operation requested by ATSUI.*/
{$EXTERNALSYM kATSUNoFontCmapAvailableErr}
kATSUNoFontCmapAvailableErr = -8805; //* Used when no CMAP table can be accessed or synthesized for the */
//* font passed into a SetAttributes Font call.*/
{$EXTERNALSYM kATSUNoFontScalerAvailableErr}
kATSUNoFontScalerAvailableErr = -8806; //* Used when no font scaler is available for the font passed*/
//* into a SetAttributes Font call.*/
{$EXTERNALSYM kATSUCoordinateOverflowErr}
kATSUCoordinateOverflowErr = -8807; //* Used to indicate the coordinates provided to an ATSUI routine caused*/
//* a coordinate overflow (i.e. > 32K).*/
{$EXTERNALSYM kATSULineBreakInWord}
kATSULineBreakInWord = -8808; //* This is not an error code but is returned by ATSUBreakLine to */
//* indicate that the returned offset is within a word since there was*/
//* only less than one word that could fit the requested width.*/
{$EXTERNALSYM kATSUBusyObjectErr}
kATSUBusyObjectErr = -8809; //* An ATSUI object is being used by another thread */
//};
{*
kATSUInvalidFontFallbacksErr, which had formerly occupied -8810 has been relocated to error code -8900. See
below in this range for additional error codes.
*}
//* Error & status codes for general text and text encoding conversion*/
//enum {
//* general text errors*/
{$EXTERNALSYM kTextUnsupportedEncodingErr}
kTextUnsupportedEncodingErr = -8738; //* specified encoding not supported for this operation*/
{$EXTERNALSYM kTextMalformedInputErr}
kTextMalformedInputErr = -8739; //* in DBCS, for example, high byte followed by invalid low byte*/
{$EXTERNALSYM kTextUndefinedElementErr}
kTextUndefinedElementErr = -8740; //* text conversion errors*/
{$EXTERNALSYM kTECMissingTableErr}
kTECMissingTableErr = -8745;
{$EXTERNALSYM kTECTableChecksumErr}
kTECTableChecksumErr = -8746;
{$EXTERNALSYM kTECTableFormatErr}
kTECTableFormatErr = -8747;
{$EXTERNALSYM kTECCorruptConverterErr}
kTECCorruptConverterErr = -8748; //* invalid converter object reference*/
{$EXTERNALSYM kTECNoConversionPathErr}
kTECNoConversionPathErr = -8749;
{$EXTERNALSYM kTECBufferBelowMinimumSizeErr}
kTECBufferBelowMinimumSizeErr = -8750; //* output buffer too small to allow processing of first input text element*/
{$EXTERNALSYM kTECArrayFullErr}
kTECArrayFullErr = -8751; //* supplied name buffer or TextRun, TextEncoding, or UnicodeMapping array is too small*/
{$EXTERNALSYM kTECBadTextRunErr}
kTECBadTextRunErr = -8752;
{$EXTERNALSYM kTECPartialCharErr}
kTECPartialCharErr = -8753; //* input buffer ends in the middle of a multibyte character, conversion stopped*/
{$EXTERNALSYM kTECUnmappableElementErr}
kTECUnmappableElementErr = -8754;
{$EXTERNALSYM kTECIncompleteElementErr}
kTECIncompleteElementErr = -8755; //* text element may be incomplete or is too long for internal buffers*/
{$EXTERNALSYM kTECDirectionErr}
kTECDirectionErr = -8756; //* direction stack overflow, etc.*/
{$EXTERNALSYM kTECGlobalsUnavailableErr}
kTECGlobalsUnavailableErr = -8770; //* globals have already been deallocated (premature TERM)*/
{$EXTERNALSYM kTECItemUnavailableErr}
kTECItemUnavailableErr = -8771; //* item (e.g. name) not available for specified region (& encoding if relevant)*/
//* text conversion status codes*/
{$EXTERNALSYM kTECUsedFallbacksStatus}
kTECUsedFallbacksStatus = -8783;
{$EXTERNALSYM kTECNeedFlushStatus}
kTECNeedFlushStatus = -8784;
{$EXTERNALSYM kTECOutputBufferFullStatus}
kTECOutputBufferFullStatus = -8785; //* output buffer has no room for conversion of next input text element (partial conversion)*/
//* deprecated error & status codes for low-level converter*/
{$EXTERNALSYM unicodeChecksumErr}
unicodeChecksumErr = -8769;
{$EXTERNALSYM unicodeNoTableErr}
unicodeNoTableErr = -8768;
{$EXTERNALSYM unicodeVariantErr}
unicodeVariantErr = -8767;
{$EXTERNALSYM unicodeFallbacksErr}
unicodeFallbacksErr = -8766;
{$EXTERNALSYM unicodePartConvertErr}
unicodePartConvertErr = -8765;
{$EXTERNALSYM unicodeBufErr}
unicodeBufErr = -8764;
{$EXTERNALSYM unicodeCharErr}
unicodeCharErr = -8763;
{$EXTERNALSYM unicodeElementErr}
unicodeElementErr = -8762;
{$EXTERNALSYM unicodeNotFoundErr}
unicodeNotFoundErr = -8761;
{$EXTERNALSYM unicodeTableFormatErr}
unicodeTableFormatErr = -8760;
{$EXTERNALSYM unicodeDirectionErr}
unicodeDirectionErr = -8759;
{$EXTERNALSYM unicodeContextualErr}
unicodeContextualErr = -8758;
{$EXTERNALSYM unicodeTextEncodingDataErr}
unicodeTextEncodingDataErr = -8757;
//};
//* UTCUtils Status Codes */
//enum {
{$EXTERNALSYM kUTCUnderflowErr}
kUTCUnderflowErr = -8850;
{$EXTERNALSYM kUTCOverflowErr}
kUTCOverflowErr = -8851;
{$EXTERNALSYM kIllegalClockValueErr}
kIllegalClockValueErr = -8852;
//};
//* ATSUI Error Codes - Range 2 of 2*/
//enum {
{$EXTERNALSYM kATSUInvalidFontFallbacksErr}
kATSUInvalidFontFallbacksErr = -8900; //* An attempt was made to use a ATSUFontFallbacks which hadn't */
//* been initialized or is otherwise in an invalid state. */
{$EXTERNALSYM kATSUUnsupportedStreamFormatErr}
kATSUUnsupportedStreamFormatErr = -8901; //* An attempt was made to use a ATSUFlattenedDataStreamFormat*/
//* which is invalid is not compatible with this version of ATSUI.*/
{$EXTERNALSYM kATSUBadStreamErr}
kATSUBadStreamErr = -8902; //* An attempt was made to use a stream which is incorrectly*/
//* structured, contains bad or out of range values or is*/
//* missing required information.*/
{$EXTERNALSYM kATSUOutputBufferTooSmallErr}
kATSUOutputBufferTooSmallErr = -8903; //* An attempt was made to use an output buffer which was too small*/
//* for the requested operation.*/
{$EXTERNALSYM kATSUInvalidCallInsideCallbackErr}
kATSUInvalidCallInsideCallbackErr = -8904; //* A call was made within the context of a callback that could*/
//* potetially cause an infinite recursion*/
{$EXTERNALSYM kATSUNoFontNameErr}
kATSUNoFontNameErr = -8905; //* This error is returned when either ATSUFindFontName() or ATSUGetIndFontName() */
//* function cannot find a corresponding font name given the input parameters*/
{$EXTERNALSYM kATSULastErr}
kATSULastErr = -8959; //* The last ATSUI error code.*/
//};
//* QuickTime errors (Image Compression Manager) */
//enum {
{$EXTERNALSYM codecErr}
codecErr = -8960;
{$EXTERNALSYM noCodecErr}
noCodecErr = -8961;
{$EXTERNALSYM codecUnimpErr}
codecUnimpErr = -8962;
{$EXTERNALSYM codecSizeErr}
codecSizeErr = -8963;
{$EXTERNALSYM codecScreenBufErr}
codecScreenBufErr = -8964;
{$EXTERNALSYM codecImageBufErr}
codecImageBufErr = -8965;
{$EXTERNALSYM codecSpoolErr}
codecSpoolErr = -8966;
{$EXTERNALSYM codecAbortErr}
codecAbortErr = -8967;
{$EXTERNALSYM codecWouldOffscreenErr}
codecWouldOffscreenErr = -8968;
{$EXTERNALSYM codecBadDataErr}
codecBadDataErr = -8969;
{$EXTERNALSYM codecDataVersErr}
codecDataVersErr = -8970;
{$EXTERNALSYM codecExtensionNotFoundErr}
codecExtensionNotFoundErr = -8971;
{$EXTERNALSYM scTypeNotFoundErr}
scTypeNotFoundErr = codecExtensionNotFoundErr;
{$EXTERNALSYM codecConditionErr}
codecConditionErr = -8972;
{$EXTERNALSYM codecOpenErr}
codecOpenErr = -8973;
{$EXTERNALSYM codecCantWhenErr}
codecCantWhenErr = -8974;
{$EXTERNALSYM codecCantQueueErr}
codecCantQueueErr = -8975;
{$EXTERNALSYM codecNothingToBlitErr}
codecNothingToBlitErr = -8976;
{$EXTERNALSYM codecNoMemoryPleaseWaitErr}
codecNoMemoryPleaseWaitErr = -8977;
{$EXTERNALSYM codecDisabledErr}
codecDisabledErr = -8978; //* codec disabled itself -- pass codecFlagReenable to reset*/
{$EXTERNALSYM codecNeedToFlushChainErr}
codecNeedToFlushChainErr = -8979;
{$EXTERNALSYM lockPortBitsBadSurfaceErr}
lockPortBitsBadSurfaceErr = -8980;
{$EXTERNALSYM lockPortBitsWindowMovedErr}
lockPortBitsWindowMovedErr = -8981;
{$EXTERNALSYM lockPortBitsWindowResizedErr}
lockPortBitsWindowResizedErr = -8982;
{$EXTERNALSYM lockPortBitsWindowClippedErr}
lockPortBitsWindowClippedErr = -8983;
{$EXTERNALSYM lockPortBitsBadPortErr}
lockPortBitsBadPortErr = -8984;
{$EXTERNALSYM lockPortBitsSurfaceLostErr}
lockPortBitsSurfaceLostErr = -8985;
{$EXTERNALSYM codecParameterDialogConfirm}
codecParameterDialogConfirm = -8986;
{$EXTERNALSYM codecNeedAccessKeyErr}
codecNeedAccessKeyErr = -8987; //* codec needs password in order to decompress*/
{$EXTERNALSYM codecOffscreenFailedErr}
codecOffscreenFailedErr = -8988;
{$EXTERNALSYM codecDroppedFrameErr}
codecDroppedFrameErr = -8989; //* returned from ImageCodecDrawBand */
{$EXTERNALSYM directXObjectAlreadyExists}
directXObjectAlreadyExists = -8990;
{$EXTERNALSYM lockPortBitsWrongGDeviceErr}
lockPortBitsWrongGDeviceErr = -8991;
{$EXTERNALSYM codecOffscreenFailedPleaseRetryErr}
codecOffscreenFailedPleaseRetryErr = -8992;
{$EXTERNALSYM badCodecCharacterizationErr}
badCodecCharacterizationErr = -8993;
{$EXTERNALSYM noThumbnailFoundErr}
noThumbnailFoundErr = -8994;
//};
//* PCCard error codes */
//enum {
{$EXTERNALSYM kBadAdapterErr}
kBadAdapterErr = -9050; //* invalid adapter number*/
{$EXTERNALSYM kBadAttributeErr}
kBadAttributeErr = -9051; //* specified attributes field value is invalid*/
{$EXTERNALSYM kBadBaseErr}
kBadBaseErr = -9052; //* specified base system memory address is invalid*/
{$EXTERNALSYM kBadEDCErr}
kBadEDCErr = -9053; //* specified EDC generator specified is invalid*/
{$EXTERNALSYM kBadIRQErr}
kBadIRQErr = -9054; //* specified IRQ level is invalid*/
{$EXTERNALSYM kBadOffsetErr}
kBadOffsetErr = -9055; //* specified PC card memory array offset is invalid*/
{$EXTERNALSYM kBadPageErr}
kBadPageErr = -9056; //* specified page is invalid*/
{$EXTERNALSYM kBadSizeErr}
kBadSizeErr = -9057; //* specified size is invalid*/
{$EXTERNALSYM kBadSocketErr}
kBadSocketErr = -9058; //* specified logical or physical socket number is invalid*/
{$EXTERNALSYM kBadTypeErr}
kBadTypeErr = -9059; //* specified window or interface type is invalid*/
{$EXTERNALSYM kBadVccErr}
kBadVccErr = -9060; //* specified Vcc power level index is invalid*/
{$EXTERNALSYM kBadVppErr}
kBadVppErr = -9061; //* specified Vpp1 or Vpp2 power level index is invalid*/
{$EXTERNALSYM kBadWindowErr}
kBadWindowErr = -9062; //* specified window is invalid*/
{$EXTERNALSYM kBadArgLengthErr}
kBadArgLengthErr = -9063; //* ArgLength argument is invalid*/
{$EXTERNALSYM kBadArgsErr}
kBadArgsErr = -9064; //* values in argument packet are invalid*/
{$EXTERNALSYM kBadHandleErr}
kBadHandleErr = -9065; //* clientHandle is invalid*/
{$EXTERNALSYM kBadCISErr}
kBadCISErr = -9066; //* CIS on card is invalid*/
{$EXTERNALSYM kBadSpeedErr}
kBadSpeedErr = -9067; //* specified speed is unavailable*/
{$EXTERNALSYM kReadFailureErr}
kReadFailureErr = -9068; //* unable to complete read request*/
{$EXTERNALSYM kWriteFailureErr}
kWriteFailureErr = -9069; //* unable to complete write request*/
{$EXTERNALSYM kGeneralFailureErr}
kGeneralFailureErr = -9070; //* an undefined error has occurred*/
{$EXTERNALSYM kNoCardErr}
kNoCardErr = -9071; //* no PC card in the socket*/
{$EXTERNALSYM kUnsupportedFunctionErr}
kUnsupportedFunctionErr = -9072; //* function is not supported by this implementation*/
{$EXTERNALSYM kUnsupportedModeErr}
kUnsupportedModeErr = -9073; //* mode is not supported*/
{$EXTERNALSYM kBusyErr}
kBusyErr = -9074; //* unable to process request at this time - try later*/
{$EXTERNALSYM kWriteProtectedErr}
kWriteProtectedErr = -9075; //* media is write-protected*/
{$EXTERNALSYM kConfigurationLockedErr}
kConfigurationLockedErr = -9076; //* a configuration has already been locked*/
{$EXTERNALSYM kInUseErr}
kInUseErr = -9077; //* requested resource is being used by a client*/
{$EXTERNALSYM kNoMoreItemsErr}
kNoMoreItemsErr = -9078; //* there are no more of the requested item*/
{$EXTERNALSYM kOutOfResourceErr}
kOutOfResourceErr = -9079; //* Card Services has exhausted the resource*/
{$EXTERNALSYM kNoCardSevicesSocketsErr}
kNoCardSevicesSocketsErr = -9080;
{$EXTERNALSYM kInvalidRegEntryErr}
kInvalidRegEntryErr = -9081;
{$EXTERNALSYM kBadLinkErr}
kBadLinkErr = -9082;
{$EXTERNALSYM kBadDeviceErr}
kBadDeviceErr = -9083;
{$EXTERNALSYM k16BitCardErr}
k16BitCardErr = -9084;
{$EXTERNALSYM kCardBusCardErr}
kCardBusCardErr = -9085;
{$EXTERNALSYM kPassCallToChainErr}
kPassCallToChainErr = -9086;
{$EXTERNALSYM kCantConfigureCardErr}
kCantConfigureCardErr = -9087;
{$EXTERNALSYM kPostCardEventErr}
kPostCardEventErr = -9088; //* _PCCSLPostCardEvent failed and dropped an event */
{$EXTERNALSYM kInvalidDeviceNumber}
kInvalidDeviceNumber = -9089;
{$EXTERNALSYM kUnsupportedVsErr}
kUnsupportedVsErr = -9090; //* Unsupported Voltage Sense */
{$EXTERNALSYM kInvalidCSClientErr}
kInvalidCSClientErr = -9091; //* Card Services ClientID is not registered */
{$EXTERNALSYM kBadTupleDataErr}
kBadTupleDataErr = -9092; //* Data in tuple is invalid */
{$EXTERNALSYM kBadCustomIFIDErr}
kBadCustomIFIDErr = -9093; //* Custom interface ID is invalid */
{$EXTERNALSYM kNoIOWindowRequestedErr}
kNoIOWindowRequestedErr = -9094; //* Request I/O window before calling configuration */
{$EXTERNALSYM kNoMoreTimerClientsErr}
kNoMoreTimerClientsErr = -9095; //* All timer callbacks are in use */
{$EXTERNALSYM kNoMoreInterruptSlotsErr}
kNoMoreInterruptSlotsErr = -9096; //* All internal Interrupt slots are in use */
{$EXTERNALSYM kNoClientTableErr}
kNoClientTableErr = -9097; //* The client table has not be initialized yet */
{$EXTERNALSYM kUnsupportedCardErr}
kUnsupportedCardErr = -9098; //* Card not supported by generic enabler*/
{$EXTERNALSYM kNoCardEnablersFoundErr}
kNoCardEnablersFoundErr = -9099; //* No Enablers were found*/
{$EXTERNALSYM kNoEnablerForCardErr}
kNoEnablerForCardErr = -9100; //* No Enablers were found that can support the card*/
{$EXTERNALSYM kNoCompatibleNameErr}
kNoCompatibleNameErr = -9101; //* There is no compatible driver name for this device*/
{$EXTERNALSYM kClientRequestDenied}
kClientRequestDenied = -9102; //* CS Clients should return this code inorder to */
//* deny a request-type CS Event */
{$EXTERNALSYM kNotReadyErr}
kNotReadyErr = -9103; //* PC Card failed to go ready */
{$EXTERNALSYM kTooManyIOWindowsErr}
kTooManyIOWindowsErr = -9104; //* device requested more than one I/O window */
{$EXTERNALSYM kAlreadySavedStateErr}
kAlreadySavedStateErr = -9105; //* The state has been saved on previous call */
{$EXTERNALSYM kAttemptDupCardEntryErr}
kAttemptDupCardEntryErr = -9106; //* The Enabler was asked to create a duplicate card entry */
{$EXTERNALSYM kCardPowerOffErr}
kCardPowerOffErr = -9107; //* Power to the card has been turned off */
{$EXTERNALSYM kNotZVCapableErr}
kNotZVCapableErr = -9108; //* This socket does not support Zoomed Video */
{$EXTERNALSYM kNoCardBusCISErr}
kNoCardBusCISErr = -9109; //* No valid CIS exists for this CardBus card */
//};
//enum {
{$EXTERNALSYM noDeviceForChannel}
noDeviceForChannel = -9400;
{$EXTERNALSYM grabTimeComplete}
grabTimeComplete = -9401;
{$EXTERNALSYM cantDoThatInCurrentMode}
cantDoThatInCurrentMode = -9402;
{$EXTERNALSYM notEnoughMemoryToGrab}
notEnoughMemoryToGrab = -9403;
{$EXTERNALSYM notEnoughDiskSpaceToGrab}
notEnoughDiskSpaceToGrab = -9404;
{$EXTERNALSYM couldntGetRequiredComponent}
couldntGetRequiredComponent = -9405;
{$EXTERNALSYM badSGChannel}
badSGChannel = -9406;
{$EXTERNALSYM seqGrabInfoNotAvailable}
seqGrabInfoNotAvailable = -9407;
{$EXTERNALSYM deviceCantMeetRequest}
deviceCantMeetRequest = -9408;
{$EXTERNALSYM badControllerHeight}
badControllerHeight = -9994;
{$EXTERNALSYM editingNotAllowed}
editingNotAllowed = -9995;
{$EXTERNALSYM controllerBoundsNotExact}
controllerBoundsNotExact = -9996;
{$EXTERNALSYM cannotSetWidthOfAttachedController}
cannotSetWidthOfAttachedController = -9997;
{$EXTERNALSYM controllerHasFixedHeight}
controllerHasFixedHeight = -9998;
{$EXTERNALSYM cannotMoveAttachedController}
cannotMoveAttachedController = -9999;
//};
//* AERegistry Errors */
//enum {
{$EXTERNALSYM errAEBadKeyForm}
errAEBadKeyForm = -10002;
{$EXTERNALSYM errAECantHandleClass}
errAECantHandleClass = -10010;
{$EXTERNALSYM errAECantSupplyType}
errAECantSupplyType = -10009;
{$EXTERNALSYM errAECantUndo}
errAECantUndo = -10015;
{$EXTERNALSYM errAEEventFailed}
errAEEventFailed = -10000;
{$EXTERNALSYM errAEIndexTooLarge}
errAEIndexTooLarge = -10007;
{$EXTERNALSYM errAEInTransaction}
errAEInTransaction = -10011;
{$EXTERNALSYM errAELocalOnly}
errAELocalOnly = -10016;
{$EXTERNALSYM errAENoSuchTransaction}
errAENoSuchTransaction = -10012;
{$EXTERNALSYM errAENotAnElement}
errAENotAnElement = -10008;
{$EXTERNALSYM errAENotASingleObject}
errAENotASingleObject = -10014;
{$EXTERNALSYM errAENotModifiable}
errAENotModifiable = -10003;
{$EXTERNALSYM errAENoUserSelection}
errAENoUserSelection = -10013;
{$EXTERNALSYM errAEPrivilegeError}
errAEPrivilegeError = -10004;
{$EXTERNALSYM errAEReadDenied}
errAEReadDenied = -10005;
{$EXTERNALSYM errAETypeError}
errAETypeError = -10001;
{$EXTERNALSYM errAEWriteDenied}
errAEWriteDenied = -10006;
{$EXTERNALSYM errAENotAnEnumMember}
errAENotAnEnumMember = -10023; //* enumerated value in SetData is not allowed for this property */
{$EXTERNALSYM errAECantPutThatThere}
errAECantPutThatThere = -10024; //* in make new, duplicate, etc. class can't be an element of container */
{$EXTERNALSYM errAEPropertiesClash}
errAEPropertiesClash = -10025; //* illegal combination of properties settings for Set Data, make new, or duplicate */
//};
//* TELErr */
//enum {
{$EXTERNALSYM telGenericError}
telGenericError = -1;
{$EXTERNALSYM telNoErr}
telNoErr = 0;
{$EXTERNALSYM telNoTools}
telNoTools = 8; //* no telephone tools found in extension folder */
{$EXTERNALSYM telBadTermErr}
telBadTermErr = -10001; //* invalid TELHandle or handle not found*/
{$EXTERNALSYM telBadDNErr}
telBadDNErr = -10002; //* TELDNHandle not found or invalid */
{$EXTERNALSYM telBadCAErr}
telBadCAErr = -10003; //* TELCAHandle not found or invalid */
{$EXTERNALSYM telBadHandErr}
telBadHandErr = -10004; //* bad handle specified */
{$EXTERNALSYM telBadProcErr}
telBadProcErr = -10005; //* bad msgProc specified */
{$EXTERNALSYM telCAUnavail}
telCAUnavail = -10006; //* a CA is not available */
{$EXTERNALSYM telNoMemErr}
telNoMemErr = -10007; //* no memory to allocate handle */
{$EXTERNALSYM telNoOpenErr}
telNoOpenErr = -10008; //* unable to open terminal */
{$EXTERNALSYM telBadHTypeErr}
telBadHTypeErr = -10010; //* bad hook type specified */
{$EXTERNALSYM telHTypeNotSupp}
telHTypeNotSupp = -10011; //* hook type not supported by this tool */
{$EXTERNALSYM telBadLevelErr}
telBadLevelErr = -10012; //* bad volume level setting */
{$EXTERNALSYM telBadVTypeErr}
telBadVTypeErr = -10013; //* bad volume type error */
{$EXTERNALSYM telVTypeNotSupp}
telVTypeNotSupp = -10014; //* volume type not supported by this tool*/
{$EXTERNALSYM telBadAPattErr}
telBadAPattErr = -10015; //* bad alerting pattern specified */
{$EXTERNALSYM telAPattNotSupp}
telAPattNotSupp = -10016; //* alerting pattern not supported by tool*/
{$EXTERNALSYM telBadIndex}
telBadIndex = -10017; //* bad index specified */
{$EXTERNALSYM telIndexNotSupp}
telIndexNotSupp = -10018; //* index not supported by this tool */
{$EXTERNALSYM telBadStateErr}
telBadStateErr = -10019; //* bad device state specified */
{$EXTERNALSYM telStateNotSupp}
telStateNotSupp = -10020; //* device state not supported by tool */
{$EXTERNALSYM telBadIntExt}
telBadIntExt = -10021; //* bad internal external error */
{$EXTERNALSYM telIntExtNotSupp}
telIntExtNotSupp = -10022; //* internal external type not supported by this tool */
{$EXTERNALSYM telBadDNDType}
telBadDNDType = -10023; //* bad DND type specified */
{$EXTERNALSYM telDNDTypeNotSupp}
telDNDTypeNotSupp = -10024; //* DND type is not supported by this tool */
{$EXTERNALSYM telFeatNotSub}
telFeatNotSub = -10030; //* feature not subscribed */
{$EXTERNALSYM telFeatNotAvail}
telFeatNotAvail = -10031; //* feature subscribed but not available */
{$EXTERNALSYM telFeatActive}
telFeatActive = -10032; //* feature already active */
{$EXTERNALSYM telFeatNotSupp}
telFeatNotSupp = -10033; //* feature program call not supported by this tool */
{$EXTERNALSYM telConfLimitErr}
telConfLimitErr = -10040; //* limit specified is too high for this configuration */
{$EXTERNALSYM telConfNoLimit}
telConfNoLimit = -10041; //* no limit was specified but required*/
{$EXTERNALSYM telConfErr}
telConfErr = -10042; //* conference was not prepared */
{$EXTERNALSYM telConfRej}
telConfRej = -10043; //* conference request was rejected */
{$EXTERNALSYM telTransferErr}
telTransferErr = -10044; //* transfer not prepared */
{$EXTERNALSYM telTransferRej}
telTransferRej = -10045; //* transfer request rejected */
{$EXTERNALSYM telCBErr}
telCBErr = -10046; //* call back feature not set previously */
{$EXTERNALSYM telConfLimitExceeded}
telConfLimitExceeded = -10047; //* attempt to exceed switch conference limits */
{$EXTERNALSYM telBadDNType}
telBadDNType = -10050; //* DN type invalid */
{$EXTERNALSYM telBadPageID}
telBadPageID = -10051; //* bad page ID specified*/
{$EXTERNALSYM telBadIntercomID}
telBadIntercomID = -10052; //* bad intercom ID specified */
{$EXTERNALSYM telBadFeatureID}
telBadFeatureID = -10053; //* bad feature ID specified */
{$EXTERNALSYM telBadFwdType}
telBadFwdType = -10054; //* bad fwdType specified */
{$EXTERNALSYM telBadPickupGroupID}
telBadPickupGroupID = -10055; //* bad pickup group ID specified */
{$EXTERNALSYM telBadParkID}
telBadParkID = -10056; //* bad park id specified */
{$EXTERNALSYM telBadSelect}
telBadSelect = -10057; //* unable to select or deselect DN */
{$EXTERNALSYM telBadBearerType}
telBadBearerType = -10058; //* bad bearerType specified */
{$EXTERNALSYM telBadRate}
telBadRate = -10059; //* bad rate specified */
{$EXTERNALSYM telDNTypeNotSupp}
telDNTypeNotSupp = -10060; //* DN type not supported by tool */
{$EXTERNALSYM telFwdTypeNotSupp}
telFwdTypeNotSupp = -10061; //* forward type not supported by tool */
{$EXTERNALSYM telBadDisplayMode}
telBadDisplayMode = -10062; //* bad display mode specified */
{$EXTERNALSYM telDisplayModeNotSupp}
telDisplayModeNotSupp = -10063; //* display mode not supported by tool */
{$EXTERNALSYM telNoCallbackRef}
telNoCallbackRef = -10064; //* no call back reference was specified, but is required */
{$EXTERNALSYM telAlreadyOpen}
telAlreadyOpen = -10070; //* terminal already open */
{$EXTERNALSYM telStillNeeded}
telStillNeeded = -10071; //* terminal driver still needed by someone else */
{$EXTERNALSYM telTermNotOpen}
telTermNotOpen = -10072; //* terminal not opened via TELOpenTerm */
{$EXTERNALSYM telCANotAcceptable}
telCANotAcceptable = -10080; //* CA not "acceptable" */
{$EXTERNALSYM telCANotRejectable}
telCANotRejectable = -10081; //* CA not "rejectable" */
{$EXTERNALSYM telCANotDeflectable}
telCANotDeflectable = -10082; //* CA not "deflectable" */
{$EXTERNALSYM telPBErr}
telPBErr = -10090; //* parameter block error, bad format */
{$EXTERNALSYM telBadFunction}
telBadFunction = -10091; //* bad msgCode specified */
//* telNoTools = -10101, unable to find any telephone tools */
{$EXTERNALSYM telNoSuchTool}
telNoSuchTool = -10102; //* unable to find tool with name specified */
{$EXTERNALSYM telUnknownErr}
telUnknownErr = -10103; //* unable to set config */
{$EXTERNALSYM telNoCommFolder}
telNoCommFolder = -10106; //* Communications/Extensions ƒ not found */
{$EXTERNALSYM telInitFailed}
telInitFailed = -10107; //* initialization failed */
{$EXTERNALSYM telBadCodeResource}
telBadCodeResource = -10108; //* code resource not found */
{$EXTERNALSYM telDeviceNotFound}
telDeviceNotFound = -10109; //* device not found */
{$EXTERNALSYM telBadProcID}
telBadProcID = -10110; //* invalid procID */
{$EXTERNALSYM telValidateFailed}
telValidateFailed = -10111; //* telValidate failed */
{$EXTERNALSYM telAutoAnsNotOn}
telAutoAnsNotOn = -10112; //* autoAnswer in not turned on */
{$EXTERNALSYM telDetAlreadyOn}
telDetAlreadyOn = -10113; //* detection is already turned on */
{$EXTERNALSYM telBadSWErr}
telBadSWErr = -10114; //* Software not installed properly */
{$EXTERNALSYM telBadSampleRate}
telBadSampleRate = -10115; //* incompatible sample rate */
{$EXTERNALSYM telNotEnoughdspBW}
telNotEnoughdspBW = -10116; //* not enough real-time for allocation */
//};
//enum {
{$EXTERNALSYM errTaskNotFound}
errTaskNotFound = -10780; //* no task with that task id exists */
//};
//* Video driver Errorrs -10930 to -10959 */
//* Defined in video.h. */
//enum {
//*Power Manager Errors*/
{$EXTERNALSYM pmBusyErr}
pmBusyErr = -13000; //*Power Mgr never ready to start handshake*/
{$EXTERNALSYM pmReplyTOErr}
pmReplyTOErr = -13001; //*Timed out waiting for reply*/
{$EXTERNALSYM pmSendStartErr}
pmSendStartErr = -13002; //*during send, pmgr did not start hs*/
{$EXTERNALSYM pmSendEndErr}
pmSendEndErr = -13003; //*during send, pmgr did not finish hs*/
{$EXTERNALSYM pmRecvStartErr}
pmRecvStartErr = -13004; //*during receive, pmgr did not start hs*/
{$EXTERNALSYM pmRecvEndErr}
pmRecvEndErr = -13005; //*during receive, pmgr did not finish hs configured for this connection*/
//};
//*Power Manager 2.0 Errors*/
//enum {
{$EXTERNALSYM kPowerHandlerExistsForDeviceErr}
kPowerHandlerExistsForDeviceErr = -13006;
{$EXTERNALSYM kPowerHandlerNotFoundForDeviceErr}
kPowerHandlerNotFoundForDeviceErr = -13007;
{$EXTERNALSYM kPowerHandlerNotFoundForProcErr}
kPowerHandlerNotFoundForProcErr = -13008;
{$EXTERNALSYM kPowerMgtMessageNotHandled}
kPowerMgtMessageNotHandled = -13009;
{$EXTERNALSYM kPowerMgtRequestDenied}
kPowerMgtRequestDenied = -13010;
{$EXTERNALSYM kCantReportProcessorTemperatureErr}
kCantReportProcessorTemperatureErr = -13013;
{$EXTERNALSYM kProcessorTempRoutineRequiresMPLib2}
kProcessorTempRoutineRequiresMPLib2 = -13014;
{$EXTERNALSYM kNoSuchPowerSource}
kNoSuchPowerSource = -13020;
{$EXTERNALSYM kBridgeSoftwareRunningCantSleep}
kBridgeSoftwareRunningCantSleep = -13038;
//};
//* Debugging library errors */
//enum {
{$EXTERNALSYM debuggingExecutionContextErr}
debuggingExecutionContextErr = -13880; //* routine cannot be called at this time */
{$EXTERNALSYM debuggingDuplicateSignatureErr}
debuggingDuplicateSignatureErr = -13881; //* componentSignature already registered */
{$EXTERNALSYM debuggingDuplicateOptionErr}
debuggingDuplicateOptionErr = -13882; //* optionSelectorNum already registered */
{$EXTERNALSYM debuggingInvalidSignatureErr}
debuggingInvalidSignatureErr = -13883; //* componentSignature not registered */
{$EXTERNALSYM debuggingInvalidOptionErr}
debuggingInvalidOptionErr = -13884; //* optionSelectorNum is not registered */
{$EXTERNALSYM debuggingInvalidNameErr}
debuggingInvalidNameErr = -13885; //* componentName or optionName is invalid (NULL) */
{$EXTERNALSYM debuggingNoCallbackErr}
debuggingNoCallbackErr = -13886; //* debugging component has no callback */
{$EXTERNALSYM debuggingNoMatchErr}
debuggingNoMatchErr = -13887; //* debugging component or option not found at this index */
//};
//* HID device driver error codes */
//enum {
{$EXTERNALSYM kHIDVersionIncompatibleErr}
kHIDVersionIncompatibleErr = -13909;
{$EXTERNALSYM kHIDDeviceNotReady}
kHIDDeviceNotReady = -13910; //* The device is still initializing, try again later*/
//};
//* HID error codes */
//enum {
{$EXTERNALSYM kHIDSuccess}
kHIDSuccess = 0;
{$EXTERNALSYM kHIDInvalidRangePageErr}
kHIDInvalidRangePageErr = -13923;
{$EXTERNALSYM kHIDReportIDZeroErr}
kHIDReportIDZeroErr = -13924;
{$EXTERNALSYM kHIDReportCountZeroErr}
kHIDReportCountZeroErr = -13925;
{$EXTERNALSYM kHIDReportSizeZeroErr}
kHIDReportSizeZeroErr = -13926;
{$EXTERNALSYM kHIDUnmatchedDesignatorRangeErr}
kHIDUnmatchedDesignatorRangeErr = -13927;
{$EXTERNALSYM kHIDUnmatchedStringRangeErr}
kHIDUnmatchedStringRangeErr = -13928;
{$EXTERNALSYM kHIDInvertedUsageRangeErr}
kHIDInvertedUsageRangeErr = -13929;
{$EXTERNALSYM kHIDUnmatchedUsageRangeErr}
kHIDUnmatchedUsageRangeErr = -13930;
{$EXTERNALSYM kHIDInvertedPhysicalRangeErr}
kHIDInvertedPhysicalRangeErr = -13931;
{$EXTERNALSYM kHIDInvertedLogicalRangeErr}
kHIDInvertedLogicalRangeErr = -13932;
{$EXTERNALSYM kHIDBadLogicalMaximumErr}
kHIDBadLogicalMaximumErr = -13933;
{$EXTERNALSYM kHIDBadLogicalMinimumErr}
kHIDBadLogicalMinimumErr = -13934;
{$EXTERNALSYM kHIDUsagePageZeroErr}
kHIDUsagePageZeroErr = -13935;
{$EXTERNALSYM kHIDEndOfDescriptorErr}
kHIDEndOfDescriptorErr = -13936;
{$EXTERNALSYM kHIDNotEnoughMemoryErr}
kHIDNotEnoughMemoryErr = -13937;
{$EXTERNALSYM kHIDBadParameterErr}
kHIDBadParameterErr = -13938;
{$EXTERNALSYM kHIDNullPointerErr}
kHIDNullPointerErr = -13939;
{$EXTERNALSYM kHIDInvalidReportLengthErr}
kHIDInvalidReportLengthErr = -13940;
{$EXTERNALSYM kHIDInvalidReportTypeErr}
kHIDInvalidReportTypeErr = -13941;
{$EXTERNALSYM kHIDBadLogPhysValuesErr}
kHIDBadLogPhysValuesErr = -13942;
{$EXTERNALSYM kHIDIncompatibleReportErr}
kHIDIncompatibleReportErr = -13943;
{$EXTERNALSYM kHIDInvalidPreparsedDataErr}
kHIDInvalidPreparsedDataErr = -13944;
{$EXTERNALSYM kHIDNotValueArrayErr}
kHIDNotValueArrayErr = -13945;
{$EXTERNALSYM kHIDUsageNotFoundErr}
kHIDUsageNotFoundErr = -13946;
{$EXTERNALSYM kHIDValueOutOfRangeErr}
kHIDValueOutOfRangeErr = -13947;
{$EXTERNALSYM kHIDBufferTooSmallErr}
kHIDBufferTooSmallErr = -13948;
{$EXTERNALSYM kHIDNullStateErr}
kHIDNullStateErr = -13949;
{$EXTERNALSYM kHIDBaseError}
kHIDBaseError = -13950;
//};
//* the OT modem module may return the following error codes:*/
//enum {
{$EXTERNALSYM kModemOutOfMemory}
kModemOutOfMemory = -14000;
{$EXTERNALSYM kModemPreferencesMissing}
kModemPreferencesMissing = -14001;
{$EXTERNALSYM kModemScriptMissing}
kModemScriptMissing = -14002;
//};
//* Multilingual Text Engine (MLTE) error codes */
//enum {
{$EXTERNALSYM kTXNEndIterationErr}
kTXNEndIterationErr = -22000; //* Function was not able to iterate through the data contained by a text object*/
{$EXTERNALSYM kTXNCannotAddFrameErr}
kTXNCannotAddFrameErr = -22001; //* Multiple frames are not currently supported in MLTE*/
{$EXTERNALSYM kTXNInvalidFrameIDErr}
kTXNInvalidFrameIDErr = -22002; //* The frame ID is invalid*/
{$EXTERNALSYM kTXNIllegalToCrossDataBoundariesErr}
kTXNIllegalToCrossDataBoundariesErr = -22003; //* Offsets specify a range that crosses a data type boundary*/
{$EXTERNALSYM kTXNUserCanceledOperationErr}
kTXNUserCanceledOperationErr = -22004; //* A user canceled an operation before your application completed processing it*/
{$EXTERNALSYM kTXNBadDefaultFileTypeWarning}
kTXNBadDefaultFileTypeWarning = -22005; //* The text file is not in the format you specified*/
{$EXTERNALSYM kTXNCannotSetAutoIndentErr}
kTXNCannotSetAutoIndentErr = -22006; //* Auto indentation is not available when word wrapping is enabled*/
{$EXTERNALSYM kTXNRunIndexOutofBoundsErr}
kTXNRunIndexOutofBoundsErr = -22007; //* An index you supplied to a function is out of bounds*/
{$EXTERNALSYM kTXNNoMatchErr}
kTXNNoMatchErr = -22008; //* Returned by TXNFind when a match is not found*/
{$EXTERNALSYM kTXNAttributeTagInvalidForRunErr}
kTXNAttributeTagInvalidForRunErr = -22009; //* Tag for a specific run is not valid (the tag's dataValue is set to this)*/
{$EXTERNALSYM kTXNSomeOrAllTagsInvalidForRunErr}
kTXNSomeOrAllTagsInvalidForRunErr = -22010; //* At least one of the tags given is invalid*/
{$EXTERNALSYM kTXNInvalidRunIndex}
kTXNInvalidRunIndex = -22011; //* Index is out of range for that run*/
{$EXTERNALSYM kTXNAlreadyInitializedErr}
kTXNAlreadyInitializedErr = -22012; //* You already called the TXNInitTextension function*/
{$EXTERNALSYM kTXNCannotTurnTSMOffWhenUsingUnicodeErr}
kTXNCannotTurnTSMOffWhenUsingUnicodeErr = -22013; //* Your application tried to turn off the Text Services Manager when using Unicode*/
{$EXTERNALSYM kTXNCopyNotAllowedInEchoModeErr}
kTXNCopyNotAllowedInEchoModeErr = -22014; //* Your application tried to copy text that was in echo mode*/
{$EXTERNALSYM kTXNDataTypeNotAllowedErr}
kTXNDataTypeNotAllowedErr = -22015; //* Your application specified a data type that MLTE does not allow*/
{$EXTERNALSYM kTXNATSUIIsNotInstalledErr}
kTXNATSUIIsNotInstalledErr = -22016; //* Indicates that ATSUI is not installed on the system*/
{$EXTERNALSYM kTXNOutsideOfLineErr}
kTXNOutsideOfLineErr = -22017; //* Indicates a value that is beyond the length of the line*/
{$EXTERNALSYM kTXNOutsideOfFrameErr}
kTXNOutsideOfFrameErr = -22018; //* Indicates a value that is outside of the text object's frame*/
//};
//*Possible errors from the PrinterStatus bottleneck*/
//enum {
{$EXTERNALSYM printerStatusOpCodeNotSupportedErr}
printerStatusOpCodeNotSupportedErr = -25280;
//};
//* Keychain Manager error codes */
//enum {
{$EXTERNALSYM errKCNotAvailable}
errKCNotAvailable = -25291;
{$EXTERNALSYM errKCReadOnly}
errKCReadOnly = -25292;
{$EXTERNALSYM errKCAuthFailed}
errKCAuthFailed = -25293;
{$EXTERNALSYM errKCNoSuchKeychain}
errKCNoSuchKeychain = -25294;
{$EXTERNALSYM errKCInvalidKeychain}
errKCInvalidKeychain = -25295;
{$EXTERNALSYM errKCDuplicateKeychain}
errKCDuplicateKeychain = -25296;
{$EXTERNALSYM errKCDuplicateCallback}
errKCDuplicateCallback = -25297;
{$EXTERNALSYM errKCInvalidCallback}
errKCInvalidCallback = -25298;
{$EXTERNALSYM errKCDuplicateItem}
errKCDuplicateItem = -25299;
{$EXTERNALSYM errKCItemNotFound}
errKCItemNotFound = -25300;
{$EXTERNALSYM errKCBufferTooSmall}
errKCBufferTooSmall = -25301;
{$EXTERNALSYM errKCDataTooLarge}
errKCDataTooLarge = -25302;
{$EXTERNALSYM errKCNoSuchAttr}
errKCNoSuchAttr = -25303;
{$EXTERNALSYM errKCInvalidItemRef}
errKCInvalidItemRef = -25304;
{$EXTERNALSYM errKCInvalidSearchRef}
errKCInvalidSearchRef = -25305;
{$EXTERNALSYM errKCNoSuchClass}
errKCNoSuchClass = -25306;
{$EXTERNALSYM errKCNoDefaultKeychain}
errKCNoDefaultKeychain = -25307;
{$EXTERNALSYM errKCInteractionNotAllowed}
errKCInteractionNotAllowed = -25308;
{$EXTERNALSYM errKCReadOnlyAttr}
errKCReadOnlyAttr = -25309;
{$EXTERNALSYM errKCWrongKCVersion}
errKCWrongKCVersion = -25310;
{$EXTERNALSYM errKCKeySizeNotAllowed}
errKCKeySizeNotAllowed = -25311;
{$EXTERNALSYM errKCNoStorageModule}
errKCNoStorageModule = -25312;
{$EXTERNALSYM errKCNoCertificateModule}
errKCNoCertificateModule = -25313;
{$EXTERNALSYM errKCNoPolicyModule}
errKCNoPolicyModule = -25314;
{$EXTERNALSYM errKCInteractionRequired}
errKCInteractionRequired = -25315;
{$EXTERNALSYM errKCDataNotAvailable}
errKCDataNotAvailable = -25316;
{$EXTERNALSYM errKCDataNotModifiable}
errKCDataNotModifiable = -25317;
{$EXTERNALSYM errKCCreateChainFailed}
errKCCreateChainFailed = -25318;
//};
//* UnicodeUtilities error & status codes*/
//enum {
{$EXTERNALSYM kUCOutputBufferTooSmall}
kUCOutputBufferTooSmall = -25340; //* Output buffer too small for Unicode string result*/
{$EXTERNALSYM kUCTextBreakLocatorMissingType}
kUCTextBreakLocatorMissingType = -25341; //* Unicode text break error*/
//};
//enum {
{$EXTERNALSYM kUCTSNoKeysAddedToObjectErr}
kUCTSNoKeysAddedToObjectErr = -25342;
{$EXTERNALSYM kUCTSSearchListErr}
kUCTSSearchListErr = -25343;
//};
//enum {
{$EXTERNALSYM kUCTokenizerIterationFinished}
kUCTokenizerIterationFinished = -25344;
{$EXTERNALSYM kUCTokenizerUnknownLang}
kUCTokenizerUnknownLang = -25345;
{$EXTERNALSYM kUCTokenNotFound}
kUCTokenNotFound = -25346;
//};
//* Multiprocessing API error codes*/
//enum {
{$EXTERNALSYM kMPIterationEndErr}
kMPIterationEndErr = -29275;
{$EXTERNALSYM kMPPrivilegedErr}
kMPPrivilegedErr = -29276;
{$EXTERNALSYM kMPProcessCreatedErr}
kMPProcessCreatedErr = -29288;
{$EXTERNALSYM kMPProcessTerminatedErr}
kMPProcessTerminatedErr = -29289;
{$EXTERNALSYM kMPTaskCreatedErr}
kMPTaskCreatedErr = -29290;
{$EXTERNALSYM kMPTaskBlockedErr}
kMPTaskBlockedErr = -29291;
{$EXTERNALSYM kMPTaskStoppedErr}
kMPTaskStoppedErr = -29292; //* A convention used with MPThrowException.*/
{$EXTERNALSYM kMPBlueBlockingErr}
kMPBlueBlockingErr = -29293;
{$EXTERNALSYM kMPDeletedErr}
kMPDeletedErr = -29295;
{$EXTERNALSYM kMPTimeoutErr}
kMPTimeoutErr = -29296;
{$EXTERNALSYM kMPTaskAbortedErr}
kMPTaskAbortedErr = -29297;
{$EXTERNALSYM kMPInsufficientResourcesErr}
kMPInsufficientResourcesErr = -29298;
{$EXTERNALSYM kMPInvalidIDErr}
kMPInvalidIDErr = -29299;
//};
//enum {
{$EXTERNALSYM kMPNanokernelNeedsMemoryErr}
kMPNanokernelNeedsMemoryErr = -29294;
//};
//* StringCompare error codes (in TextUtils range)*/
//enum {
{$EXTERNALSYM kCollateAttributesNotFoundErr}
kCollateAttributesNotFoundErr = -29500;
{$EXTERNALSYM kCollateInvalidOptions}
kCollateInvalidOptions = -29501;
{$EXTERNALSYM kCollateMissingUnicodeTableErr}
kCollateMissingUnicodeTableErr = -29502;
{$EXTERNALSYM kCollateUnicodeConvertFailedErr}
kCollateUnicodeConvertFailedErr = -29503;
{$EXTERNALSYM kCollatePatternNotFoundErr}
kCollatePatternNotFoundErr = -29504;
{$EXTERNALSYM kCollateInvalidChar}
kCollateInvalidChar = -29505;
{$EXTERNALSYM kCollateBufferTooSmall}
kCollateBufferTooSmall = -29506;
{$EXTERNALSYM kCollateInvalidCollationRef}
kCollateInvalidCollationRef = -29507;
//};
//* FontSync OSStatus Codes */
//enum {
{$EXTERNALSYM kFNSInvalidReferenceErr}
kFNSInvalidReferenceErr = -29580; //* ref. was NULL or otherwise bad */
{$EXTERNALSYM kFNSBadReferenceVersionErr}
kFNSBadReferenceVersionErr = -29581; //* ref. version is out of known range */
{$EXTERNALSYM kFNSInvalidProfileErr}
kFNSInvalidProfileErr = -29582; //* profile is NULL or otherwise bad */
{$EXTERNALSYM kFNSBadProfileVersionErr}
kFNSBadProfileVersionErr = -29583; //* profile version is out of known range */
{$EXTERNALSYM kFNSDuplicateReferenceErr}
kFNSDuplicateReferenceErr = -29584; //* the ref. being added is already in the profile */
{$EXTERNALSYM kFNSMismatchErr}
kFNSMismatchErr = -29585; //* reference didn't match or wasn't found in profile */
{$EXTERNALSYM kFNSInsufficientDataErr}
kFNSInsufficientDataErr = -29586; //* insufficient data for the operation */
{$EXTERNALSYM kFNSBadFlattenedSizeErr}
kFNSBadFlattenedSizeErr = -29587; //* flattened size didn't match input or was too small */
{$EXTERNALSYM kFNSNameNotFoundErr}
kFNSNameNotFoundErr = -29589; //* The name with the requested paramters was not found */
//};
//* MacLocales error codes*/
//enum {
{$EXTERNALSYM kLocalesBufferTooSmallErr}
kLocalesBufferTooSmallErr = -30001;
{$EXTERNALSYM kLocalesTableFormatErr}
kLocalesTableFormatErr = -30002;
{$EXTERNALSYM kLocalesDefaultDisplayStatus}
kLocalesDefaultDisplayStatus = -30029; //* Requested display locale unavailable, used default*/
//};
//* Settings Manager (formerly known as Location Manager) Errors */
//enum {
{$EXTERNALSYM kALMInternalErr}
kALMInternalErr = -30049;
{$EXTERNALSYM kALMGroupNotFoundErr}
kALMGroupNotFoundErr = -30048;
{$EXTERNALSYM kALMNoSuchModuleErr}
kALMNoSuchModuleErr = -30047;
{$EXTERNALSYM kALMModuleCommunicationErr}
kALMModuleCommunicationErr = -30046;
{$EXTERNALSYM kALMDuplicateModuleErr}
kALMDuplicateModuleErr = -30045;
{$EXTERNALSYM kALMInstallationErr}
kALMInstallationErr = -30044;
{$EXTERNALSYM kALMDeferSwitchErr}
kALMDeferSwitchErr = -30043;
{$EXTERNALSYM kALMRebootFlagsLevelErr}
kALMRebootFlagsLevelErr = -30042;
//};
//enum {
{$EXTERNALSYM kALMLocationNotFoundErr}
kALMLocationNotFoundErr = kALMGroupNotFoundErr; //* Old name */
//};
//* SoundSprocket Error Codes */
//enum {
{$EXTERNALSYM kSSpInternalErr}
kSSpInternalErr = -30340;
{$EXTERNALSYM kSSpVersionErr}
kSSpVersionErr = -30341;
{$EXTERNALSYM kSSpCantInstallErr}
kSSpCantInstallErr = -30342;
{$EXTERNALSYM kSSpParallelUpVectorErr}
kSSpParallelUpVectorErr = -30343;
{$EXTERNALSYM kSSpScaleToZeroErr}
kSSpScaleToZeroErr = -30344;
//};
//* NetSprocket Error Codes */
//enum {
{$EXTERNALSYM kNSpInitializationFailedErr}
kNSpInitializationFailedErr = -30360;
{$EXTERNALSYM kNSpAlreadyInitializedErr}
kNSpAlreadyInitializedErr = -30361;
{$EXTERNALSYM kNSpTopologyNotSupportedErr}
kNSpTopologyNotSupportedErr = -30362;
{$EXTERNALSYM kNSpPipeFullErr}
kNSpPipeFullErr = -30364;
{$EXTERNALSYM kNSpHostFailedErr}
kNSpHostFailedErr = -30365;
{$EXTERNALSYM kNSpProtocolNotAvailableErr}
kNSpProtocolNotAvailableErr = -30366;
{$EXTERNALSYM kNSpInvalidGameRefErr}
kNSpInvalidGameRefErr = -30367;
{$EXTERNALSYM kNSpInvalidParameterErr}
kNSpInvalidParameterErr = -30369;
{$EXTERNALSYM kNSpOTNotPresentErr}
kNSpOTNotPresentErr = -30370;
{$EXTERNALSYM kNSpOTVersionTooOldErr}
kNSpOTVersionTooOldErr = -30371;
{$EXTERNALSYM kNSpMemAllocationErr}
kNSpMemAllocationErr = -30373;
{$EXTERNALSYM kNSpAlreadyAdvertisingErr}
kNSpAlreadyAdvertisingErr = -30374;
{$EXTERNALSYM kNSpNotAdvertisingErr}
kNSpNotAdvertisingErr = -30376;
{$EXTERNALSYM kNSpInvalidAddressErr}
kNSpInvalidAddressErr = -30377;
{$EXTERNALSYM kNSpFreeQExhaustedErr}
kNSpFreeQExhaustedErr = -30378;
{$EXTERNALSYM kNSpRemovePlayerFailedErr}
kNSpRemovePlayerFailedErr = -30379;
{$EXTERNALSYM kNSpAddressInUseErr}
kNSpAddressInUseErr = -30380;
{$EXTERNALSYM kNSpFeatureNotImplementedErr}
kNSpFeatureNotImplementedErr = -30381;
{$EXTERNALSYM kNSpNameRequiredErr}
kNSpNameRequiredErr = -30382;
{$EXTERNALSYM kNSpInvalidPlayerIDErr}
kNSpInvalidPlayerIDErr = -30383;
{$EXTERNALSYM kNSpInvalidGroupIDErr}
kNSpInvalidGroupIDErr = -30384;
{$EXTERNALSYM kNSpNoPlayersErr}
kNSpNoPlayersErr = -30385;
{$EXTERNALSYM kNSpNoGroupsErr}
kNSpNoGroupsErr = -30386;
{$EXTERNALSYM kNSpNoHostVolunteersErr}
kNSpNoHostVolunteersErr = -30387;
{$EXTERNALSYM kNSpCreateGroupFailedErr}
kNSpCreateGroupFailedErr = -30388;
{$EXTERNALSYM kNSpAddPlayerFailedErr}
kNSpAddPlayerFailedErr = -30389;
{$EXTERNALSYM kNSpInvalidDefinitionErr}
kNSpInvalidDefinitionErr = -30390;
{$EXTERNALSYM kNSpInvalidProtocolRefErr}
kNSpInvalidProtocolRefErr = -30391;
{$EXTERNALSYM kNSpInvalidProtocolListErr}
kNSpInvalidProtocolListErr = -30392;
{$EXTERNALSYM kNSpTimeoutErr}
kNSpTimeoutErr = -30393;
{$EXTERNALSYM kNSpGameTerminatedErr}
kNSpGameTerminatedErr = -30394;
{$EXTERNALSYM kNSpConnectFailedErr}
kNSpConnectFailedErr = -30395;
{$EXTERNALSYM kNSpSendFailedErr}
kNSpSendFailedErr = -30396;
{$EXTERNALSYM kNSpMessageTooBigErr}
kNSpMessageTooBigErr = -30397;
{$EXTERNALSYM kNSpCantBlockErr}
kNSpCantBlockErr = -30398;
{$EXTERNALSYM kNSpJoinFailedErr}
kNSpJoinFailedErr = -30399;
//};
//* InputSprockets error codes */
//enum {
{$EXTERNALSYM kISpInternalErr}
kISpInternalErr = -30420;
{$EXTERNALSYM kISpSystemListErr}
kISpSystemListErr = -30421;
{$EXTERNALSYM kISpBufferToSmallErr}
kISpBufferToSmallErr = -30422;
{$EXTERNALSYM kISpElementInListErr}
kISpElementInListErr = -30423;
{$EXTERNALSYM kISpElementNotInListErr}
kISpElementNotInListErr = -30424;
{$EXTERNALSYM kISpSystemInactiveErr}
kISpSystemInactiveErr = -30425;
{$EXTERNALSYM kISpDeviceInactiveErr}
kISpDeviceInactiveErr = -30426;
{$EXTERNALSYM kISpSystemActiveErr}
kISpSystemActiveErr = -30427;
{$EXTERNALSYM kISpDeviceActiveErr}
kISpDeviceActiveErr = -30428;
{$EXTERNALSYM kISpListBusyErr}
kISpListBusyErr = -30429;
//};
//* DrawSprockets error/warning codes */
//enum {
{$EXTERNALSYM kDSpNotInitializedErr}
kDSpNotInitializedErr = -30440;
{$EXTERNALSYM kDSpSystemSWTooOldErr}
kDSpSystemSWTooOldErr = -30441;
{$EXTERNALSYM kDSpInvalidContextErr}
kDSpInvalidContextErr = -30442;
{$EXTERNALSYM kDSpInvalidAttributesErr}
kDSpInvalidAttributesErr = -30443;
{$EXTERNALSYM kDSpContextAlreadyReservedErr}
kDSpContextAlreadyReservedErr = -30444;
{$EXTERNALSYM kDSpContextNotReservedErr}
kDSpContextNotReservedErr = -30445;
{$EXTERNALSYM kDSpContextNotFoundErr}
kDSpContextNotFoundErr = -30446;
{$EXTERNALSYM kDSpFrameRateNotReadyErr}
kDSpFrameRateNotReadyErr = -30447;
{$EXTERNALSYM kDSpConfirmSwitchWarning}
kDSpConfirmSwitchWarning = -30448;
{$EXTERNALSYM kDSpInternalErr}
kDSpInternalErr = -30449;
{$EXTERNALSYM kDSpStereoContextErr}
kDSpStereoContextErr = -30450;
//};
{*
***************************************************************************
Find By Content errors are assigned in the range -30500 to -30539, inclusive.
***************************************************************************
*}
//enum {
{$EXTERNALSYM kFBCvTwinExceptionErr}
kFBCvTwinExceptionErr = -30500; //*no telling what it was*/
{$EXTERNALSYM kFBCnoIndexesFound}
kFBCnoIndexesFound = -30501;
{$EXTERNALSYM kFBCallocFailed}
kFBCallocFailed = -30502; //*probably low memory*/
{$EXTERNALSYM kFBCbadParam}
kFBCbadParam = -30503;
{$EXTERNALSYM kFBCfileNotIndexed}
kFBCfileNotIndexed = -30504;
{$EXTERNALSYM kFBCbadIndexFile}
kFBCbadIndexFile = -30505; //*bad FSSpec, or bad data in file*/
{$EXTERNALSYM kFBCcompactionFailed}
kFBCcompactionFailed = -30506; //*V-Twin exception caught*/
{$EXTERNALSYM kFBCvalidationFailed}
kFBCvalidationFailed = -30507; //*V-Twin exception caught*/
{$EXTERNALSYM kFBCindexingFailed}
kFBCindexingFailed = -30508; //*V-Twin exception caught*/
{$EXTERNALSYM kFBCcommitFailed}
kFBCcommitFailed = -30509; //*V-Twin exception caught*/
{$EXTERNALSYM kFBCdeletionFailed}
kFBCdeletionFailed = -30510; //*V-Twin exception caught*/
{$EXTERNALSYM kFBCmoveFailed}
kFBCmoveFailed = -30511; //*V-Twin exception caught*/
{$EXTERNALSYM kFBCtokenizationFailed}
kFBCtokenizationFailed = -30512; //*couldn't read from document or query*/
{$EXTERNALSYM kFBCmergingFailed}
kFBCmergingFailed = -30513; //*couldn't merge index files*/
{$EXTERNALSYM kFBCindexCreationFailed}
kFBCindexCreationFailed = -30514; //*couldn't create index*/
{$EXTERNALSYM kFBCaccessorStoreFailed}
kFBCaccessorStoreFailed = -30515;
{$EXTERNALSYM kFBCaddDocFailed}
kFBCaddDocFailed = -30516;
{$EXTERNALSYM kFBCflushFailed}
kFBCflushFailed = -30517;
{$EXTERNALSYM kFBCindexNotFound}
kFBCindexNotFound = -30518;
{$EXTERNALSYM kFBCnoSearchSession}
kFBCnoSearchSession = -30519;
{$EXTERNALSYM kFBCindexingCanceled}
kFBCindexingCanceled = -30520;
{$EXTERNALSYM kFBCaccessCanceled}
kFBCaccessCanceled = -30521;
{$EXTERNALSYM kFBCindexFileDestroyed}
kFBCindexFileDestroyed = -30522;
{$EXTERNALSYM kFBCindexNotAvailable}
kFBCindexNotAvailable = -30523;
{$EXTERNALSYM kFBCsearchFailed}
kFBCsearchFailed = -30524;
{$EXTERNALSYM kFBCsomeFilesNotIndexed}
kFBCsomeFilesNotIndexed = -30525;
{$EXTERNALSYM kFBCillegalSessionChange}
kFBCillegalSessionChange = -30526; //*tried to add/remove vols to a session*/
//*that has hits*/
{$EXTERNALSYM kFBCanalysisNotAvailable}
kFBCanalysisNotAvailable = -30527;
{$EXTERNALSYM kFBCbadIndexFileVersion}
kFBCbadIndexFileVersion = -30528;
{$EXTERNALSYM kFBCsummarizationCanceled}
kFBCsummarizationCanceled = -30529;
{$EXTERNALSYM kFBCindexDiskIOFailed}
kFBCindexDiskIOFailed = -30530;
{$EXTERNALSYM kFBCbadSearchSession}
kFBCbadSearchSession = -30531;
{$EXTERNALSYM kFBCnoSuchHit}
kFBCnoSuchHit = -30532;
//};
//* QuickTime VR Errors */
//enum {
{$EXTERNALSYM notAQTVRMovieErr}
notAQTVRMovieErr = -30540;
constraintReachedErr = -30541;
{$EXTERNALSYM callNotSupportedByNodeErr}
callNotSupportedByNodeErr = -30542;
{$EXTERNALSYM selectorNotSupportedByNodeErr}
selectorNotSupportedByNodeErr = -30543;
{$EXTERNALSYM invalidNodeIDErr}
invalidNodeIDErr = -30544;
{$EXTERNALSYM invalidViewStateErr}
invalidViewStateErr = -30545;
{$EXTERNALSYM timeNotInViewErr}
timeNotInViewErr = -30546;
{$EXTERNALSYM propertyNotSupportedByNodeErr}
propertyNotSupportedByNodeErr = -30547;
{$EXTERNALSYM settingNotSupportedByNodeErr}
settingNotSupportedByNodeErr = -30548;
{$EXTERNALSYM limitReachedErr}
limitReachedErr = -30549;
{$EXTERNALSYM invalidNodeFormatErr}
invalidNodeFormatErr = -30550;
{$EXTERNALSYM invalidHotSpotIDErr}
invalidHotSpotIDErr = -30551;
{$EXTERNALSYM noMemoryNodeFailedInitialize}
noMemoryNodeFailedInitialize = -30552;
{$EXTERNALSYM streamingNodeNotReadyErr}
streamingNodeNotReadyErr = -30553;
{$EXTERNALSYM qtvrLibraryLoadErr}
qtvrLibraryLoadErr = -30554;
{$EXTERNALSYM qtvrUninitialized}
qtvrUninitialized = -30555;
//};
//* Appearance Manager Error Codes */
//enum {
{$EXTERNALSYM themeInvalidBrushErr}
themeInvalidBrushErr = -30560; //* pattern index invalid */
{$EXTERNALSYM themeProcessRegisteredErr}
themeProcessRegisteredErr = -30561;
{$EXTERNALSYM themeProcessNotRegisteredErr}
themeProcessNotRegisteredErr = -30562;
{$EXTERNALSYM themeBadTextColorErr}
themeBadTextColorErr = -30563;
{$EXTERNALSYM themeHasNoAccentsErr}
themeHasNoAccentsErr = -30564;
{$EXTERNALSYM themeBadCursorIndexErr}
themeBadCursorIndexErr = -30565;
{$EXTERNALSYM themeScriptFontNotFoundErr}
themeScriptFontNotFoundErr = -30566; //* theme font requested for uninstalled script system */
{$EXTERNALSYM themeMonitorDepthNotSupportedErr}
themeMonitorDepthNotSupportedErr = -30567; //* theme not supported at monitor depth */
{$EXTERNALSYM themeNoAppropriateBrushErr}
themeNoAppropriateBrushErr = -30568; //* theme brush has no corresponding theme text color */
//};
{*
* Discussion:
* Control Manager Error Codes
*}
//enum {
{*
* Not exclusively a Control Manager error code. In general, this
* return value means a control, window, or menu definition does not
* support the message/event that underlies an API call.
*}
{$EXTERNALSYM errMessageNotSupported}
errMessageNotSupported = -30580;
{*
* This is returned from GetControlData and SetControlData if the
* control doesn't support the tag name and/or part code that is
* passed in. It can also be returned from other APIs - like
* SetControlFontStyle - which are wrappers around Get/SetControlData.
*}
{$EXTERNALSYM errDataNotSupported}
errDataNotSupported = -30581;
{*
* The control you passed to a focusing API doesn't support focusing.
* This error isn't sent on Mac OS X; instead, you're likely to
* receive errCouldntSetFocus or eventNotHandledErr.
*}
{$EXTERNALSYM errControlDoesntSupportFocus}
errControlDoesntSupportFocus = -30582;
{*
* This is a variant of and serves the same purpose as
* controlHandleInvalidErr. Various Control Manager APIs will return
* this error if one of the passed-in controls is NULL or otherwise
* invalid.
*}
{$EXTERNALSYM errUnknownControl}
errUnknownControl = -30584;
{*
* The focus couldn't be set to a given control or advanced through a
* hierarchy of controls. This could be because the control doesn't
* support focusing, the control isn't currently embedded in a
* window, or there are no focusable controls in the window when you
* try to advance the focus.
*}
{$EXTERNALSYM errCouldntSetFocus}
errCouldntSetFocus = -30585;
{*
* This is returned by GetRootControl before a root control was
* created for a given non-compositing window. Alternatively, you
* called a Control Manager API such as ClearKeyboardFocus or
* AutoEmbedControl that requires a root control, but there is no
* root control on the window.
*}
{$EXTERNALSYM errNoRootControl}
errNoRootControl = -30586;
{*
* This is returned by CreateRootControl on the second and successive
* calls for a given window.
*}
{$EXTERNALSYM errRootAlreadyExists}
errRootAlreadyExists = -30587;
{*
* The ControlPartCode you passed to a Control Manager API is out of
* range, invalid, or otherwise unsupported.
*}
{$EXTERNALSYM errInvalidPartCode}
errInvalidPartCode = -30588;
{*
* You called CreateRootControl after creating one or more non-root
* controls in a window, which is illegal; if you want an embedding
* hierarchy on a given window, you must call CreateRootControl
* before creating any other controls for a given window. This will
* never be returned on Mac OS X, because a root control is created
* automatically if it doesn't already exist the first time any
* non-root control is created in a window.
*}
{$EXTERNALSYM errControlsAlreadyExist}
errControlsAlreadyExist = -30589;
{*
* You passed a control that doesn't support embedding to a Control
* Manager API which requires the control to support embedding.
*}
{$EXTERNALSYM errControlIsNotEmbedder}
errControlIsNotEmbedder = -30590;
{*
* You called GetControlData or SetControlData with a buffer whose
* size does not match the size of the data you are attempting to get
* or set.
*}
{$EXTERNALSYM errDataSizeMismatch}
errDataSizeMismatch = -30591;
{*
* You called TrackControl, HandleControlClick or a similar mouse
* tracking API on a control that is invisible or disabled. You
* cannot track controls that are invisible or disabled.
*}
{$EXTERNALSYM errControlHiddenOrDisabled}
errControlHiddenOrDisabled = -30592;
{*
* You called EmbedControl or a similar API with the same control in
* the parent and child parameters. You cannot embed a control into
* itself.
*}
{$EXTERNALSYM errCantEmbedIntoSelf}
errCantEmbedIntoSelf = -30594;
{*
* You called EmbedControl or a similiar API to embed the root
* control in another control. You cannot embed the root control in
* any other control.
*}
{$EXTERNALSYM errCantEmbedRoot}
errCantEmbedRoot = -30595;
{*
* You called GetDialogItemAsControl on a dialog item such as a
* kHelpDialogItem that is not represented by a control.
*}
{$EXTERNALSYM errItemNotControl}
errItemNotControl = -30596;
{*
* You called GetControlData or SetControlData with a buffer that
* represents a versioned structure, but the version is unsupported
* by the control definition. This can happen with the Tabs control
* and the kControlTabInfoTag.
*}
{$EXTERNALSYM controlInvalidDataVersionErr}
controlInvalidDataVersionErr = -30597;
{*
* You called SetControlProperty, GetControlProperty, or a similar
* API with an illegal property creator OSType.
*}
{$EXTERNALSYM controlPropertyInvalid}
controlPropertyInvalid = -5603;
{*
* You called GetControlProperty or a similar API with a property
* creator and property tag that does not currently exist on the
* given control.
*}
{$EXTERNALSYM controlPropertyNotFoundErr}
controlPropertyNotFoundErr = -5604;
{*
* You passed an invalid ControlRef to a Control Manager API.
*}
{$EXTERNALSYM controlHandleInvalidErr}
controlHandleInvalidErr = -30599;
//};
//* URLAccess Error Codes */
//enum {
{$EXTERNALSYM kURLInvalidURLReferenceError}
kURLInvalidURLReferenceError = -30770;
{$EXTERNALSYM kURLProgressAlreadyDisplayedError}
kURLProgressAlreadyDisplayedError = -30771;
{$EXTERNALSYM kURLDestinationExistsError}
kURLDestinationExistsError = -30772;
{$EXTERNALSYM kURLInvalidURLError}
kURLInvalidURLError = -30773;
{$EXTERNALSYM kURLUnsupportedSchemeError}
kURLUnsupportedSchemeError = -30774;
{$EXTERNALSYM kURLServerBusyError}
kURLServerBusyError = -30775;
{$EXTERNALSYM kURLAuthenticationError}
kURLAuthenticationError = -30776;
{$EXTERNALSYM kURLPropertyNotYetKnownError}
kURLPropertyNotYetKnownError = -30777;
{$EXTERNALSYM kURLUnknownPropertyError}
kURLUnknownPropertyError = -30778;
{$EXTERNALSYM kURLPropertyBufferTooSmallError}
kURLPropertyBufferTooSmallError = -30779;
{$EXTERNALSYM kURLUnsettablePropertyError}
kURLUnsettablePropertyError = -30780;
{$EXTERNALSYM kURLInvalidCallError}
kURLInvalidCallError = -30781;
{$EXTERNALSYM kURLFileEmptyError}
kURLFileEmptyError = -30783;
{$EXTERNALSYM kURLExtensionFailureError}
kURLExtensionFailureError = -30785;
{$EXTERNALSYM kURLInvalidConfigurationError}
kURLInvalidConfigurationError = -30786;
{$EXTERNALSYM kURLAccessNotAvailableError}
kURLAccessNotAvailableError = -30787;
{$EXTERNALSYM kURL68kNotSupportedError}
kURL68kNotSupportedError = -30788;
//};
{*
Error Codes for C++ Exceptions
C++ exceptions cannot be thrown across certain boundaries, for example,
from an event handler back to the main application. You may use these
error codes to communicate an exception through an API that only supports
OSStatus error codes. Mac OS APIs will never generate these error codes;
they are reserved for developer convenience only.
*}
//enum {
{$EXTERNALSYM errCppGeneral}
errCppGeneral = -32000;
{$EXTERNALSYM errCppbad_alloc}
errCppbad_alloc = -32001; //* thrown by new */
{$EXTERNALSYM errCppbad_cast}
errCppbad_cast = -32002; //* thrown by dynamic_cast when fails with a referenced type */
{$EXTERNALSYM errCppbad_exception}
errCppbad_exception = -32003; //* thrown when an exception doesn't match any catch */
{$EXTERNALSYM errCppbad_typeid}
errCppbad_typeid = -32004; //* thrown by typeid */
{$EXTERNALSYM errCpplogic_error}
errCpplogic_error = -32005;
{$EXTERNALSYM errCppdomain_error}
errCppdomain_error = -32006;
{$EXTERNALSYM errCppinvalid_argument}
errCppinvalid_argument = -32007;
{$EXTERNALSYM errCpplength_error}
errCpplength_error = -32008;
{$EXTERNALSYM errCppout_of_range}
errCppout_of_range = -32009;
{$EXTERNALSYM errCppruntime_error}
errCppruntime_error = -32010;
{$EXTERNALSYM errCppoverflow_error}
errCppoverflow_error = -32011;
{$EXTERNALSYM errCpprange_error}
errCpprange_error = -32012;
{$EXTERNALSYM errCppunderflow_error}
errCppunderflow_error = -32013;
{$EXTERNALSYM errCppios_base_failure}
errCppios_base_failure = -32014;
{$EXTERNALSYM errCppLastSystemDefinedError}
errCppLastSystemDefinedError = -32020;
{$EXTERNALSYM errCppLastUserDefinedError}
errCppLastUserDefinedError = -32049; //* -32021 through -32049 are free for developer-defined exceptions*/
//};
//* ComponentError codes*/
//enum {
{$EXTERNALSYM badComponentInstance}
badComponentInstance = TIdC_INT($80008001); //* when cast to an OSErr this is -32767*/
{$EXTERNALSYM badComponentSelector}
badComponentSelector = TIdC_INT($80008002); //* when cast to an OSErr this is -32766*/
//};
//enum {
{$EXTERNALSYM dsBusError}
dsBusError = 1; //*bus error*/
{$EXTERNALSYM dsAddressErr}
dsAddressErr = 2; //*address error*/
{$EXTERNALSYM dsIllInstErr}
dsIllInstErr = 3; //*illegal instruction error*/
{$EXTERNALSYM dsZeroDivErr}
dsZeroDivErr = 4; //*zero divide error*/
{$EXTERNALSYM dsChkErr}
dsChkErr = 5; //*check trap error*/
{$EXTERNALSYM dsOvflowErr}
dsOvflowErr = 6; //*overflow trap error*/
{$EXTERNALSYM dsPrivErr}
dsPrivErr = 7; //*privilege violation error*/
{$EXTERNALSYM dsTraceErr}
dsTraceErr = 8; //*trace mode error*/
{$EXTERNALSYM dsLineAErr}
dsLineAErr = 9; //*line 1010 trap error*/
{$EXTERNALSYM dsLineFErr}
dsLineFErr = 10; //*line 1111 trap error*/
{$EXTERNALSYM dsMiscErr}
dsMiscErr = 11; //*miscellaneous hardware exception error*/
{$EXTERNALSYM dsCoreErr}
dsCoreErr = 12; //*unimplemented core routine error*/
{$EXTERNALSYM dsIrqErr}
dsIrqErr = 13; //*uninstalled interrupt error*/
{$EXTERNALSYM dsIOCoreErr}
dsIOCoreErr = 14; //*IO Core Error*/
{$EXTERNALSYM dsLoadErr}
dsLoadErr = 15; //*Segment Loader Error*/
{$EXTERNALSYM dsFPErr}
dsFPErr = 16; //*Floating point error*/
{$EXTERNALSYM dsNoPackErr}
dsNoPackErr = 17; //*package 0 not present*/
{$EXTERNALSYM dsNoPk1}
dsNoPk1 = 18; //*package 1 not present*/
{$EXTERNALSYM dsNoPk2}
dsNoPk2 = 19; //*package 2 not present*/
//};
//enum {
{$EXTERNALSYM dsNoPk3}
dsNoPk3 = 20; //*package 3 not present*/
{$EXTERNALSYM dsNoPk4}
dsNoPk4 = 21; //*package 4 not present*/
{$EXTERNALSYM dsNoPk5}
dsNoPk5 = 22; //*package 5 not present*/
{$EXTERNALSYM dsNoPk6}
dsNoPk6 = 23; //*package 6 not present*/
{$EXTERNALSYM dsNoPk7}
dsNoPk7 = 24; //*package 7 not present*/
{$EXTERNALSYM dsMemFullErr}
dsMemFullErr = 25; //*out of memory!*/
{$EXTERNALSYM dsBadLaunch}
dsBadLaunch = 26; //*can't launch file*/
{$EXTERNALSYM dsFSErr}
dsFSErr = 27; //*file system map has been trashed*/
{$EXTERNALSYM dsStknHeap}
dsStknHeap = 28; //*stack has moved into application heap*/
{$EXTERNALSYM negZcbFreeErr}
negZcbFreeErr = 33; //*ZcbFree has gone negative*/
{$EXTERNALSYM dsFinderErr}
dsFinderErr = 41; //*can't load the Finder error*/
{$EXTERNALSYM dsBadSlotInt}
dsBadSlotInt = 51; //*unserviceable slot interrupt*/
{$EXTERNALSYM dsBadSANEOpcode}
dsBadSANEOpcode = 81; //*bad opcode given to SANE Pack4*/
{$EXTERNALSYM dsBadPatchHeader}
dsBadPatchHeader = 83; //*SetTrapAddress saw the “come-from” header*/
{$EXTERNALSYM menuPrgErr}
menuPrgErr = 84; //*happens when a menu is purged*/
{$EXTERNALSYM dsMBarNFnd}
dsMBarNFnd = 85; //*Menu Manager Errors*/
{$EXTERNALSYM dsHMenuFindErr}
dsHMenuFindErr = 86; //*Menu Manager Errors*/
{$EXTERNALSYM dsWDEFNotFound}
dsWDEFNotFound = 87; //*could not load WDEF*/
{$EXTERNALSYM dsCDEFNotFound}
dsCDEFNotFound = 88; //*could not load CDEF*/
{$EXTERNALSYM dsMDEFNotFound}
dsMDEFNotFound = 89; //*could not load MDEF*/
//};
//enum {
{$EXTERNALSYM dsNoFPU}
dsNoFPU = 90; //*an FPU instruction was executed and the machine doesn’t have one*/
{$EXTERNALSYM dsNoPatch}
dsNoPatch = 98; //*Can't patch for particular Model Mac*/
{$EXTERNALSYM dsBadPatch}
dsBadPatch = 99; //*Can't load patch resource*/
{$EXTERNALSYM dsParityErr}
dsParityErr = 101; //*memory parity error*/
{$EXTERNALSYM dsOldSystem}
dsOldSystem = 102; //*System is too old for this ROM*/
{$EXTERNALSYM ds32BitMode}
ds32BitMode = 103; //*booting in 32-bit on a 24-bit sys*/
{$EXTERNALSYM dsNeedToWriteBootBlocks}
dsNeedToWriteBootBlocks = 104; //*need to write new boot blocks*/
{$EXTERNALSYM dsNotEnoughRAMToBoot}
dsNotEnoughRAMToBoot = 105; //*must have at least 1.5MB of RAM to boot 7.0*/
{$EXTERNALSYM dsBufPtrTooLow}
dsBufPtrTooLow = 106; //*bufPtr moved too far during boot*/
{$EXTERNALSYM dsVMDeferredFuncTableFull}
dsVMDeferredFuncTableFull = 112; //*VM's DeferUserFn table is full*/
{$EXTERNALSYM dsVMBadBackingStore}
dsVMBadBackingStore = 113; //*Error occurred while reading or writing the VM backing-store file*/
{$EXTERNALSYM dsCantHoldSystemHeap}
dsCantHoldSystemHeap = 114; //*Unable to hold the system heap during boot*/
{$EXTERNALSYM dsSystemRequiresPowerPC}
dsSystemRequiresPowerPC = 116; //*Startup disk requires PowerPC*/
{$EXTERNALSYM dsGibblyMovedToDisabledFolder}
dsGibblyMovedToDisabledFolder = 117; //* For debug builds only, signals that active gibbly was disabled during boot. */
{$EXTERNALSYM dsUnBootableSystem}
dsUnBootableSystem = 118; //* Active system file will not boot on this system because it was designed only to boot from a CD. */
{$EXTERNALSYM dsMustUseFCBAccessors}
dsMustUseFCBAccessors = 119; //* FCBSPtr and FSFCBLen are invalid - must use FSM FCB accessor functions */
{$EXTERNALSYM dsMacOSROMVersionTooOld}
dsMacOSROMVersionTooOld = 120; //* The version of the "Mac OS ROM" file is too old to be used with the installed version of system software */
{$EXTERNALSYM dsLostConnectionToNetworkDisk}
dsLostConnectionToNetworkDisk = 121; //* Lost communication with Netboot server */
{$EXTERNALSYM dsRAMDiskTooBig}
dsRAMDiskTooBig = 122; //* The RAM disk is too big to boot safely; will be turned off */
{$EXTERNALSYM dsWriteToSupervisorStackGuardPage}
dsWriteToSupervisorStackGuardPage = 128; //*the supervisor stack overflowed into its guard page */
{$EXTERNALSYM dsReinsert}
dsReinsert = 30; //*request user to reinsert off-line volume*/
{$EXTERNALSYM shutDownAlert}
shutDownAlert = 42; //*handled like a shutdown error*/
{$EXTERNALSYM dsShutDownOrRestart}
dsShutDownOrRestart = 20000; //*user choice between ShutDown and Restart*/
{$EXTERNALSYM dsSwitchOffOrRestart}
dsSwitchOffOrRestart = 20001; //*user choice between switching off and Restart*/
{$EXTERNALSYM dsForcedQuit}
dsForcedQuit = 20002; //*allow the user to ExitToShell, return if Cancel*/
{$EXTERNALSYM dsRemoveDisk}
dsRemoveDisk = 20003; //*request user to remove disk from manual eject drive*/
{$EXTERNALSYM dsDirtyDisk}
dsDirtyDisk = 20004; //*request user to return a manually-ejected dirty disk*/
{$EXTERNALSYM dsShutDownOrResume}
dsShutDownOrResume = 20109; //*allow user to return to Finder or ShutDown*/
{$EXTERNALSYM dsSCSIWarn}
dsSCSIWarn = 20010; //*Portable SCSI adapter warning.*/
{$EXTERNALSYM dsMBSysError}
dsMBSysError = 29200; //*Media Bay replace warning.*/
{$EXTERNALSYM dsMBFlpySysError}
dsMBFlpySysError = 29201; //*Media Bay, floppy replace warning.*/
{$EXTERNALSYM dsMBATASysError}
dsMBATASysError = 29202; //*Media Bay, ATA replace warning.*/
{$EXTERNALSYM dsMBATAPISysError}
dsMBATAPISysError = 29203; //*Media Bay, ATAPI replace warning...*/
{$EXTERNALSYM dsMBExternFlpySysError}
dsMBExternFlpySysError = 29204; //*Media Bay, external floppy drive reconnect warning*/
{$EXTERNALSYM dsPCCardATASysError}
dsPCCardATASysError = 29205; //*PCCard has been ejected while still in use. */
//};
{*
System Errors that are used after MacsBug is loaded to put up dialogs since these should not
cause MacsBug to stop, they must be in the range (30, 42, 16384-32767) negative numbers add
to an existing dialog without putting up a whole new dialog
*}
//enum {
{$EXTERNALSYM dsNoExtsMacsBug}
dsNoExtsMacsBug = -1; //*not a SysErr, just a placeholder */
{$EXTERNALSYM dsNoExtsDisassembler}
dsNoExtsDisassembler = -2; //*not a SysErr, just a placeholder */
{$EXTERNALSYM dsMacsBugInstalled}
dsMacsBugInstalled = -10; //*say “MacsBug Installed”*/
{$EXTERNALSYM dsDisassemblerInstalled}
dsDisassemblerInstalled = -11; //*say “Disassembler Installed”*/
{$EXTERNALSYM dsExtensionsDisabled}
dsExtensionsDisabled = -13; //*say “Extensions Disabled”*/
{$EXTERNALSYM dsGreeting}
dsGreeting = 40; //*welcome to Macintosh greeting*/
{$EXTERNALSYM dsSysErr}
dsSysErr = 32767; //*general system error*/
//*old names here for compatibility’s sake*/
{$EXTERNALSYM WDEFNFnd}
WDEFNFnd = dsWDEFNotFound;
//};
//enum {
{$EXTERNALSYM CDEFNFnd}
CDEFNFnd = dsCDEFNotFound;
{$EXTERNALSYM dsNotThe1}
dsNotThe1 = 31; //*not the disk I wanted*/
{$EXTERNALSYM dsBadStartupDisk}
dsBadStartupDisk = 42; //*unable to mount boot volume (sad Mac only)*/
{$EXTERNALSYM dsSystemFileErr}
dsSystemFileErr = 43; //*can’t find System file to open (sad Mac only)*/
{$EXTERNALSYM dsHD20Installed}
dsHD20Installed = -12; //*say “HD20 Startup”*/
{$EXTERNALSYM mBarNFnd}
mBarNFnd = -126; //*system error code for MBDF not found*/
{$EXTERNALSYM fsDSIntErr}
fsDSIntErr = -127; //*non-hardware Internal file system error*/
{$EXTERNALSYM hMenuFindErr}
hMenuFindErr = -127; //*could not find HMenu's parent in MenuKey (wrong error code - obsolete)*/
{$EXTERNALSYM userBreak}
userBreak = -490; //*user debugger break*/
{$EXTERNALSYM strUserBreak}
strUserBreak = -491; //*user debugger break; display string on stack*/
{$EXTERNALSYM exUserBreak}
exUserBreak = -492; //*user debugger break; execute debugger commands on stack*/
//};
//enum {
//* DS Errors which are specific to the new runtime model introduced with PowerPC */
{$EXTERNALSYM dsBadLibrary}
dsBadLibrary = 1010; //* Bad shared library */
{$EXTERNALSYM dsMixedModeFailure}
dsMixedModeFailure = 1011; //* Internal Mixed Mode Failure */
//};
{*
On Mac OS X, the range from 100,000 to 100,999 has been reserved for returning POSIX errno error values.
Every POSIX errno value can be converted into a Mac OS X OSStatus value by adding kPOSIXErrorBase to the
value of errno. They can't be returned by anything which just returns OSErr since kPOSIXErrorBase is
larger than the highest OSErr value.
*}
//enum {
{$EXTERNALSYM kPOSIXErrorBase}
kPOSIXErrorBase = 100000;
{$EXTERNALSYM kPOSIXErrorEPERM}
kPOSIXErrorEPERM = 100001; //* Operation not permitted */
{$EXTERNALSYM kPOSIXErrorENOENT}
kPOSIXErrorENOENT = 100002; //* No such file or directory */
{$EXTERNALSYM kPOSIXErrorESRCH}
kPOSIXErrorESRCH = 100003; //* No such process */
{$EXTERNALSYM kPOSIXErrorEINTR}
kPOSIXErrorEINTR = 100004; //* Interrupted system call */
{$EXTERNALSYM kPOSIXErrorEIO}
kPOSIXErrorEIO = 100005; //* Input/output error */
{$EXTERNALSYM kPOSIXErrorENXIO}
kPOSIXErrorENXIO = 100006; //* Device not configured */
{$EXTERNALSYM kPOSIXErrorE2BIG}
kPOSIXErrorE2BIG = 100007; //* Argument list too long */
{$EXTERNALSYM kPOSIXErrorENOEXEC}
kPOSIXErrorENOEXEC = 100008; //* Exec format error */
{$EXTERNALSYM kPOSIXErrorEBADF}
kPOSIXErrorEBADF = 100009; //* Bad file descriptor */
{$EXTERNALSYM kPOSIXErrorECHILD}
kPOSIXErrorECHILD = 100010; //* No child processes */
{$EXTERNALSYM kPOSIXErrorEDEADLK}
kPOSIXErrorEDEADLK = 100011; //* Resource deadlock avoided */
{$EXTERNALSYM kPOSIXErrorENOMEM}
kPOSIXErrorENOMEM = 100012; //* Cannot allocate memory */
{$EXTERNALSYM kPOSIXErrorEACCES}
kPOSIXErrorEACCES = 100013; //* Permission denied */
{$EXTERNALSYM kPOSIXErrorEFAULT}
kPOSIXErrorEFAULT = 100014; //* Bad address */
{$EXTERNALSYM kPOSIXErrorENOTBLK}
kPOSIXErrorENOTBLK = 100015; //* Block device required */
{$EXTERNALSYM kPOSIXErrorEBUSY}
kPOSIXErrorEBUSY = 100016; //* Device busy */
{$EXTERNALSYM kPOSIXErrorEEXIST}
kPOSIXErrorEEXIST = 100017; //* File exists */
{$EXTERNALSYM kPOSIXErrorEXDEV}
kPOSIXErrorEXDEV = 100018; //* Cross-device link */
{$EXTERNALSYM kPOSIXErrorENODEV}
kPOSIXErrorENODEV = 100019; //* Operation not supported by device */
{$EXTERNALSYM kPOSIXErrorENOTDIR}
kPOSIXErrorENOTDIR = 100020; //* Not a directory */
{$EXTERNALSYM kPOSIXErrorEISDIR}
kPOSIXErrorEISDIR = 100021; //* Is a directory */
{$EXTERNALSYM kPOSIXErrorEINVAL}
kPOSIXErrorEINVAL = 100022; //* Invalid argument */
{$EXTERNALSYM kPOSIXErrorENFILE}
kPOSIXErrorENFILE = 100023; //* Too many open files in system */
{$EXTERNALSYM kPOSIXErrorEMFILE}
kPOSIXErrorEMFILE = 100024; //* Too many open files */
{$EXTERNALSYM kPOSIXErrorENOTTY}
kPOSIXErrorENOTTY = 100025; //* Inappropriate ioctl for device */
{$EXTERNALSYM kPOSIXErrorETXTBSY}
kPOSIXErrorETXTBSY = 100026; //* Text file busy */
{$EXTERNALSYM kPOSIXErrorEFBIG}
kPOSIXErrorEFBIG = 100027; //* File too large */
{$EXTERNALSYM kPOSIXErrorENOSPC}
kPOSIXErrorENOSPC = 100028; //* No space left on device */
{$EXTERNALSYM kPOSIXErrorESPIPE}
kPOSIXErrorESPIPE = 100029; //* Illegal seek */
{$EXTERNALSYM kPOSIXErrorEROFS}
kPOSIXErrorEROFS = 100030; //* Read-only file system */
{$EXTERNALSYM kPOSIXErrorEMLINK}
kPOSIXErrorEMLINK = 100031; //* Too many links */
{$EXTERNALSYM kPOSIXErrorEPIPE}
kPOSIXErrorEPIPE = 100032; //* Broken pipe */
{$EXTERNALSYM kPOSIXErrorEDOM}
kPOSIXErrorEDOM = 100033; //* Numerical argument out of domain */
{$EXTERNALSYM kPOSIXErrorERANGE}
kPOSIXErrorERANGE = 100034; //* Result too large */
{$EXTERNALSYM kPOSIXErrorEAGAIN}
kPOSIXErrorEAGAIN = 100035; //* Resource temporarily unavailable */
{$EXTERNALSYM kPOSIXErrorEINPROGRESS}
kPOSIXErrorEINPROGRESS = 100036; //* Operation now in progress */
{$EXTERNALSYM kPOSIXErrorEALREADY}
kPOSIXErrorEALREADY = 100037; //* Operation already in progress */
{$EXTERNALSYM kPOSIXErrorENOTSOCK}
kPOSIXErrorENOTSOCK = 100038; //* Socket operation on non-socket */
{$EXTERNALSYM kPOSIXErrorEDESTADDRREQ}
kPOSIXErrorEDESTADDRREQ = 100039; //* Destination address required */
{$EXTERNALSYM kPOSIXErrorEMSGSIZE}
kPOSIXErrorEMSGSIZE = 100040; //* Message too long */
{$EXTERNALSYM kPOSIXErrorEPROTOTYPE}
kPOSIXErrorEPROTOTYPE = 100041; //* Protocol wrong type for socket */
{$EXTERNALSYM kPOSIXErrorENOPROTOOPT}
kPOSIXErrorENOPROTOOPT = 100042; //* Protocol not available */
{$EXTERNALSYM kPOSIXErrorEPROTONOSUPPORT}
kPOSIXErrorEPROTONOSUPPORT = 100043; //* Protocol not supported */
{$EXTERNALSYM kPOSIXErrorESOCKTNOSUPPORT}
kPOSIXErrorESOCKTNOSUPPORT = 100044; //* Socket type not supported */
{$EXTERNALSYM kPOSIXErrorENOTSUP}
kPOSIXErrorENOTSUP = 100045; //* Operation not supported */
{$EXTERNALSYM kPOSIXErrorEPFNOSUPPORT}
kPOSIXErrorEPFNOSUPPORT = 100046; //* Protocol family not supported */
{$EXTERNALSYM kPOSIXErrorEAFNOSUPPORT}
kPOSIXErrorEAFNOSUPPORT = 100047; //* Address family not supported by protocol family */
{$EXTERNALSYM kPOSIXErrorEADDRINUSE}
kPOSIXErrorEADDRINUSE = 100048; //* Address already in use */
{$EXTERNALSYM kPOSIXErrorEADDRNOTAVAIL}
kPOSIXErrorEADDRNOTAVAIL = 100049; //* Can't assign requested address */
{$EXTERNALSYM kPOSIXErrorENETDOWN}
kPOSIXErrorENETDOWN = 100050; //* Network is down */
{$EXTERNALSYM kPOSIXErrorENETUNREACH}
kPOSIXErrorENETUNREACH = 100051; //* Network is unreachable */
{$EXTERNALSYM kPOSIXErrorENETRESET}
kPOSIXErrorENETRESET = 100052; //* Network dropped connection on reset */
{$EXTERNALSYM kPOSIXErrorECONNABORTED}
kPOSIXErrorECONNABORTED = 100053; //* Software caused connection abort */
{$EXTERNALSYM kPOSIXErrorECONNRESET}
kPOSIXErrorECONNRESET = 100054; //* Connection reset by peer */
{$EXTERNALSYM kPOSIXErrorENOBUFS}
kPOSIXErrorENOBUFS = 100055; //* No buffer space available */
{$EXTERNALSYM kPOSIXErrorEISCONN}
kPOSIXErrorEISCONN = 100056; //* Socket is already connected */
{$EXTERNALSYM kPOSIXErrorENOTCONN}
kPOSIXErrorENOTCONN = 100057; //* Socket is not connected */
{$EXTERNALSYM kPOSIXErrorESHUTDOWN}
kPOSIXErrorESHUTDOWN = 100058; //* Can't send after socket shutdown */
{$EXTERNALSYM kPOSIXErrorETOOMANYREFS}
kPOSIXErrorETOOMANYREFS = 100059; //* Too many references: can't splice */
{$EXTERNALSYM kPOSIXErrorETIMEDOUT}
kPOSIXErrorETIMEDOUT = 100060; //* Operation timed out */
{$EXTERNALSYM kPOSIXErrorECONNREFUSED}
kPOSIXErrorECONNREFUSED = 100061; //* Connection refused */
{$EXTERNALSYM kPOSIXErrorELOOP}
kPOSIXErrorELOOP = 100062; //* Too many levels of symbolic links */
{$EXTERNALSYM kPOSIXErrorENAMETOOLONG}
kPOSIXErrorENAMETOOLONG = 100063; //* File name too long */
{$EXTERNALSYM kPOSIXErrorEHOSTDOWN}
kPOSIXErrorEHOSTDOWN = 100064; //* Host is down */
{$EXTERNALSYM kPOSIXErrorEHOSTUNREACH}
kPOSIXErrorEHOSTUNREACH = 100065; //* No route to host */
{$EXTERNALSYM kPOSIXErrorENOTEMPTY}
kPOSIXErrorENOTEMPTY = 100066; //* Directory not empty */
{$EXTERNALSYM kPOSIXErrorEPROCLIM}
kPOSIXErrorEPROCLIM = 100067; //* Too many processes */
{$EXTERNALSYM kPOSIXErrorEUSERS}
kPOSIXErrorEUSERS = 100068; //* Too many users */
{$EXTERNALSYM kPOSIXErrorEDQUOT}
kPOSIXErrorEDQUOT = 100069; //* Disc quota exceeded */
{$EXTERNALSYM kPOSIXErrorESTALE}
kPOSIXErrorESTALE = 100070; //* Stale NFS file handle */
{$EXTERNALSYM kPOSIXErrorEREMOTE}
kPOSIXErrorEREMOTE = 100071; //* Too many levels of remote in path */
{$EXTERNALSYM kPOSIXErrorEBADRPC}
kPOSIXErrorEBADRPC = 100072; //* RPC struct is bad */
{$EXTERNALSYM kPOSIXErrorERPCMISMATCH}
kPOSIXErrorERPCMISMATCH = 100073; //* RPC version wrong */
{$EXTERNALSYM kPOSIXErrorEPROGUNAVAIL}
kPOSIXErrorEPROGUNAVAIL = 100074; //* RPC prog. not avail */
{$EXTERNALSYM kPOSIXErrorEPROGMISMATCH}
kPOSIXErrorEPROGMISMATCH = 100075; //* Program version wrong */
{$EXTERNALSYM kPOSIXErrorEPROCUNAVAIL}
kPOSIXErrorEPROCUNAVAIL = 100076; //* Bad procedure for program */
{$EXTERNALSYM kPOSIXErrorENOLCK}
kPOSIXErrorENOLCK = 100077; //* No locks available */
{$EXTERNALSYM kPOSIXErrorENOSYS}
kPOSIXErrorENOSYS = 100078; //* Function not implemented */
{$EXTERNALSYM kPOSIXErrorEFTYPE}
kPOSIXErrorEFTYPE = 100079; //* Inappropriate file type or format */
{$EXTERNALSYM kPOSIXErrorEAUTH}
kPOSIXErrorEAUTH = 100080; //* Authentication error */
{$EXTERNALSYM kPOSIXErrorENEEDAUTH}
kPOSIXErrorENEEDAUTH = 100081; //* Need authenticator */
{$EXTERNALSYM kPOSIXErrorEPWROFF}
kPOSIXErrorEPWROFF = 100082; //* Device power is off */
{$EXTERNALSYM kPOSIXErrorEDEVERR}
kPOSIXErrorEDEVERR = 100083; //* Device error, e.g. paper out */
{$EXTERNALSYM kPOSIXErrorEOVERFLOW}
kPOSIXErrorEOVERFLOW = 100084; //* Value too large to be stored in data type */
{$EXTERNALSYM kPOSIXErrorEBADEXEC}
kPOSIXErrorEBADEXEC = 100085; //* Bad executable */
{$EXTERNALSYM kPOSIXErrorEBADARCH}
kPOSIXErrorEBADARCH = 100086; //* Bad CPU type in executable */
{$EXTERNALSYM kPOSIXErrorESHLIBVERS}
kPOSIXErrorESHLIBVERS = 100087; //* Shared library version mismatch */
{$EXTERNALSYM kPOSIXErrorEBADMACHO}
kPOSIXErrorEBADMACHO = 100088; //* Malformed Macho file */
{$EXTERNALSYM kPOSIXErrorECANCELED}
kPOSIXErrorECANCELED = 100089; //* Operation canceled */
{$EXTERNALSYM kPOSIXErrorEIDRM}
kPOSIXErrorEIDRM = 100090; //* Identifier removed */
{$EXTERNALSYM kPOSIXErrorENOMSG}
kPOSIXErrorENOMSG = 100091; //* No message of desired type */
{$EXTERNALSYM kPOSIXErrorEILSEQ}
kPOSIXErrorEILSEQ = 100092; //* Illegal byte sequence */
{$EXTERNALSYM kPOSIXErrorENOATTR}
kPOSIXErrorENOATTR = 100093; //* Attribute not found */
{$EXTERNALSYM kPOSIXErrorEBADMSG}
kPOSIXErrorEBADMSG = 100094; //* Bad message */
{$EXTERNALSYM kPOSIXErrorEMULTIHOP}
kPOSIXErrorEMULTIHOP = 100095; //* Reserved */
{$EXTERNALSYM kPOSIXErrorENODATA}
kPOSIXErrorENODATA = 100096; //* No message available on STREAM */
{$EXTERNALSYM kPOSIXErrorENOLINK}
kPOSIXErrorENOLINK = 100097; //* Reserved */
{$EXTERNALSYM kPOSIXErrorENOSR}
kPOSIXErrorENOSR = 100098; //* No STREAM resources */
{$EXTERNALSYM kPOSIXErrorENOSTR}
kPOSIXErrorENOSTR = 100099; //* Not a STREAM */
{$EXTERNALSYM kPOSIXErrorEPROTO}
kPOSIXErrorEPROTO = 100100; //* Protocol error */
{$EXTERNALSYM kPOSIXErrorETIME}
kPOSIXErrorETIME = 100101; //* STREAM ioctl timeout */
{$EXTERNALSYM kPOSIXErrorEOPNOTSUPP}
kPOSIXErrorEOPNOTSUPP = 100102; //* Operation not supported on socket */
//};
///Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/Gestalt.h
//* Environment Selectors */
//enum {
{$EXTERNALSYM gestaltAddressingModeAttr}
gestaltAddressingModeAttr = $61646472; //'addr', /* addressing mode attributes */
{$EXTERNALSYM gestalt32BitAddressing}
gestalt32BitAddressing = 0; //* using 32-bit addressing mode */
{$EXTERNALSYM gestalt32BitSysZone}
gestalt32BitSysZone = 1; //* 32-bit compatible system zone */
{$EXTERNALSYM gestalt32BitCapable}
gestalt32BitCapable = 2; //* Machine is 32-bit capable */
//};
//enum {
{$EXTERNALSYM gestaltAFPClient}
gestaltAFPClient = $61667073; //'afps',
{$EXTERNALSYM gestaltAFPClientVersionMask}
gestaltAFPClientVersionMask = $0000FFFF; //* low word of SInt32 is the */
//* client version 0x0001 -> 0x0007*/
{$EXTERNALSYM gestaltAFPClient3_5}
gestaltAFPClient3_5 = $0001;
{$EXTERNALSYM gestaltAFPClient3_6}
gestaltAFPClient3_6 = $0002;
{$EXTERNALSYM gestaltAFPClient3_6_1}
gestaltAFPClient3_6_1 = $0003;
{$EXTERNALSYM gestaltAFPClient3_6_2}
gestaltAFPClient3_6_2 = $0004;
{$EXTERNALSYM gestaltAFPClient3_6_3}
gestaltAFPClient3_6_3 = $0005; //* including 3.6.4, 3.6.5*/
{$EXTERNALSYM gestaltAFPClient3_7}
gestaltAFPClient3_7 = $0006; //* including 3.7.1*/
{$EXTERNALSYM gestaltAFPClient3_7_2}
gestaltAFPClient3_7_2 = $0007; //* including 3.7.3, 3.7.4*/
{$EXTERNALSYM gestaltAFPClient3_8}
gestaltAFPClient3_8 = $0008;
{$EXTERNALSYM gestaltAFPClient3_8_1}
gestaltAFPClient3_8_1 = $0009; //* including 3.8.2 */
{$EXTERNALSYM gestaltAFPClient3_8_3}
gestaltAFPClient3_8_3 = $000A;
{$EXTERNALSYM gestaltAFPClient3_8_4}
gestaltAFPClient3_8_4 = $000B; //* including 3.8.5, 3.8.6 */
{$EXTERNALSYM gestaltAFPClientAttributeMask}
gestaltAFPClientAttributeMask = TIdC_INT($FFFF0000); //* high word of response is a */
//* set of attribute bits*/
{$EXTERNALSYM gestaltAFPClientCfgRsrc}
gestaltAFPClientCfgRsrc = 16; //* Client uses config resources*/
{$EXTERNALSYM gestaltAFPClientSupportsIP}
gestaltAFPClientSupportsIP = 29; //* Client supports AFP over TCP/IP*/
{$EXTERNALSYM gestaltAFPClientVMUI}
gestaltAFPClientVMUI = 30; //* Client can put up UI from the PBVolMount trap*/
{$EXTERNALSYM gestaltAFPClientMultiReq}
gestaltAFPClientMultiReq = 31; //* Client supports multiple outstanding requests*/
//};
//enum {
{$EXTERNALSYM gestaltAliasMgrAttr}
gestaltAliasMgrAttr = $616c6973; //'alis', /* Alias Mgr Attributes */
{$EXTERNALSYM gestaltAliasMgrPresent}
gestaltAliasMgrPresent = 0; //* True if the Alias Mgr is present */
{$EXTERNALSYM gestaltAliasMgrSupportsRemoteAppletalk}
gestaltAliasMgrSupportsRemoteAppletalk = 1; //* True if the Alias Mgr knows about Remote Appletalk */
{$EXTERNALSYM gestaltAliasMgrSupportsAOCEKeychain}
gestaltAliasMgrSupportsAOCEKeychain = 2; //* True if the Alias Mgr knows about the AOCE Keychain */
{$EXTERNALSYM gestaltAliasMgrResolveAliasFileWithMountOptions}
gestaltAliasMgrResolveAliasFileWithMountOptions = 3; //* True if the Alias Mgr implements gestaltAliasMgrResolveAliasFileWithMountOptions() and IsAliasFile() */
{$EXTERNALSYM gestaltAliasMgrFollowsAliasesWhenResolving}
gestaltAliasMgrFollowsAliasesWhenResolving = 4;
{$EXTERNALSYM gestaltAliasMgrSupportsExtendedCalls}
gestaltAliasMgrSupportsExtendedCalls = 5;
{$EXTERNALSYM gestaltAliasMgrSupportsFSCalls}
gestaltAliasMgrSupportsFSCalls = 6; //* true if Alias Mgr supports HFS+ Calls */
{$EXTERNALSYM gestaltAliasMgrPrefersPath}
gestaltAliasMgrPrefersPath = 7; //* True if the Alias Mgr prioritizes the path over file id during resolution by default */
{$EXTERNALSYM gestaltAliasMgrRequiresAccessors}
gestaltAliasMgrRequiresAccessors = 8; //* Set if Alias Manager requires accessors for size and usertype */
//};
//* Gestalt selector and values for the Appearance Manager */
//enum {
{$EXTERNALSYM gestaltAppearanceAttr}
gestaltAppearanceAttr = $61707072; //'appr',
{$EXTERNALSYM gestaltAppearanceExists}
gestaltAppearanceExists = 0;
{$EXTERNALSYM gestaltAppearanceCompatMode}
gestaltAppearanceCompatMode = 1;
//};
//* Gestalt selector for determining Appearance Manager version */
//* If this selector does not exist, but gestaltAppearanceAttr */
//* does, it indicates that the 1.0 version is installed. This */
//* gestalt returns a BCD number representing the version of the */
//* Appearance Manager that is currently running, e.g. 0x0101 for */
//* version 1.0.1. */
//enum {
{$EXTERNALSYM gestaltAppearanceVersion}
gestaltAppearanceVersion = $61707672; //'apvr'
//};
//enum {
{$EXTERNALSYM gestaltArbitorAttr}
gestaltArbitorAttr = $61726220;//'arb ',
{$EXTERNALSYM gestaltSerialArbitrationExists}
gestaltSerialArbitrationExists = 0; //* this bit if the serial port arbitrator exists*/
//};
//enum {
{$EXTERNALSYM gestaltAppleScriptVersion}
gestaltAppleScriptVersion = $61736376; //'ascv' /* AppleScript version*/
//};
//enum {
{$EXTERNALSYM gestaltAppleScriptAttr}
gestaltAppleScriptAttr = $61736372; //'ascr', /* AppleScript attributes*/
{$EXTERNALSYM gestaltAppleScriptPresent}
gestaltAppleScriptPresent = 0;
{$EXTERNALSYM gestaltAppleScriptPowerPCSupport}
gestaltAppleScriptPowerPCSupport = 1;
//};
//enum {
{$EXTERNALSYM gestaltATAAttr}
gestaltATAAttr = $61746120; //'ata ', /* ATA is the driver to support IDE hard disks */
{$EXTERNALSYM gestaltATAPresent}
gestaltATAPresent = 0; //* if set, ATA Manager is present */
//};
//enum {
{$EXTERNALSYM gestaltATalkVersion}
gestaltATalkVersion = $61746b76; //'atkv' /* Detailed AppleTalk version; see comment above for format */
//};
//enum {
{$EXTERNALSYM gestaltAppleTalkVersion}
gestaltAppleTalkVersion = $61746c6b; //'atlk' /* appletalk version */
//};
{*
FORMAT OF gestaltATalkVersion RESPONSE
--------------------------------------
The version is stored in the high three bytes of the response value. Let us number
the bytes in the response value from 0 to 3, where 0 is the least-significant byte.
Byte#: 3 2 1 0
Value: 0xMMNNRR00
Byte 3 (MM) contains the major revision number, byte 2 (NN) contains the minor
revision number, and byte 1 (RR) contains a constant that represents the release
stage. Byte 0 always contains 0x00. The constants for the release stages are:
development = 0x20
alpha = 0x40
beta = 0x60
final = 0x80
release = 0x80
For example, if you call Gestalt with the 'atkv' selector when AppleTalk version 57
is loaded, you receive the integer response value 0x39008000.
*}
//enum {
{$EXTERNALSYM gestaltAUXVersion}
gestaltAUXVersion = $612f7578; //'a/ux' /* a/ux version, if present */
//};
//enum {
{$EXTERNALSYM gestaltMacOSCompatibilityBoxAttr}
gestaltMacOSCompatibilityBoxAttr = $62626f78; //'bbox', //* Classic presence and features */
{$EXTERNALSYM gestaltMacOSCompatibilityBoxPresent}
gestaltMacOSCompatibilityBoxPresent = 0; //* True if running under the Classic */
{$EXTERNALSYM gestaltMacOSCompatibilityBoxHasSerial}
gestaltMacOSCompatibilityBoxHasSerial = 1; //* True if Classic serial support is implemented. */
{$EXTERNALSYM gestaltMacOSCompatibilityBoxless}
gestaltMacOSCompatibilityBoxless = 2; //* True if we're Boxless (screen shared with Carbon/Cocoa) */
//};
//enum {
{$EXTERNALSYM gestaltBusClkSpeed}
gestaltBusClkSpeed = $62636c6b; //'bclk' /* main I/O bus clock speed in hertz */
//};
//enum {
{$EXTERNALSYM gestaltBusClkSpeedMHz}
gestaltBusClkSpeedMHz = $62636c6d; //'bclm' /* main I/O bus clock speed in megahertz ( a UInt32 ) */
//};
//enum {
{$EXTERNALSYM gestaltCloseViewAttr}
gestaltCloseViewAttr = $42534461; //'BSDa', /* CloseView attributes */
{$EXTERNALSYM gestaltCloseViewEnabled}
gestaltCloseViewEnabled = 0; //* Closeview enabled (dynamic bit - returns current state) */
{$EXTERNALSYM gestaltCloseViewDisplayMgrFriendly}
gestaltCloseViewDisplayMgrFriendly = 1; //* Closeview compatible with Display Manager (FUTURE) */
//};
//enum {
{$EXTERNALSYM gestaltCarbonVersion}
gestaltCarbonVersion = $63626f6e; //'cbon' /* version of Carbon API present in system */
//};
//enum {
{$EXTERNALSYM gestaltCFMAttr}
gestaltCFMAttr = $63667267; //'cfrg', /* Selector for information about the Code Fragment Manager */
{$EXTERNALSYM gestaltCFMPresent}
gestaltCFMPresent = 0; //* True if the Code Fragment Manager is present */
{$EXTERNALSYM gestaltCFMPresentMask}
gestaltCFMPresentMask = $0001;
{$EXTERNALSYM gestaltCFM99Present}
gestaltCFM99Present = 2; //* True if the CFM-99 features are present. */
{$EXTERNALSYM gestaltCFM99PresentMask}
gestaltCFM99PresentMask = $0004;
//};
//enum {
{$EXTERNALSYM gestaltProcessorCacheLineSize}
gestaltProcessorCacheLineSize = $6373697a; //'csiz' /* The size, in bytes, of the processor cache line. */
//};
//enum {
{$EXTERNALSYM gestaltCollectionMgrVersion}
gestaltCollectionMgrVersion = $636c746e; // 'cltn' /* Collection Manager version */
//};
//enum {
{$EXTERNALSYM gestaltColorMatchingAttr}
gestaltColorMatchingAttr = $636d7461; //'cmta', /* ColorSync attributes */
{$EXTERNALSYM gestaltHighLevelMatching}
gestaltHighLevelMatching = 0;
{$EXTERNALSYM gestaltColorMatchingLibLoaded}
gestaltColorMatchingLibLoaded = 1;
//};
//enum {
{$EXTERNALSYM gestaltColorMatchingVersion}
gestaltColorMatchingVersion = $636d7463; // 'cmtc',
{$EXTERNALSYM gestaltColorSync10}
gestaltColorSync10 = $0100; //* 0x0100 & 0x0110 _Gestalt versions for 1.0-1.0.3 product */
{$EXTERNALSYM gestaltColorSync11}
gestaltColorSync11 = $0110; //* 0x0100 == low-level matching only */
{$EXTERNALSYM gestaltColorSync104}
gestaltColorSync104 = $0104; //* Real version, by popular demand */
{$EXTERNALSYM gestaltColorSync105}
gestaltColorSync105 = $0105;
{$EXTERNALSYM gestaltColorSync20}
gestaltColorSync20 = $0200; //* ColorSync 2.0 */
{$EXTERNALSYM gestaltColorSync21}
gestaltColorSync21 = $0210;
{$EXTERNALSYM gestaltColorSync211}
gestaltColorSync211 = $0211;
{$EXTERNALSYM gestaltColorSync212}
gestaltColorSync212 = $0212;
{$EXTERNALSYM gestaltColorSync213}
gestaltColorSync213 = $0213;
{$EXTERNALSYM gestaltColorSync25}
gestaltColorSync25 = $0250;
{$EXTERNALSYM gestaltColorSync26}
gestaltColorSync26 = $0260;
{$EXTERNALSYM gestaltColorSync261}
gestaltColorSync261 = $0261;
{$EXTERNALSYM gestaltColorSync30}
gestaltColorSync30 = $0300;
//};
//enum {
// gestaltControlMgrVersion = 'cmvr' /* NOTE: The first version we return is 3.0.1, on Mac OS X plus update 2*/
{$EXTERNALSYM gestaltControlMgrVersion}
gestaltControlMgrVersion = $636d7672;
//};
//enum {
// gestaltControlMgrAttr = 'cntl', /* Control Mgr*/
{$EXTERNALSYM gestaltControlMgrAttr}
gestaltControlMgrAttr = $636e746c;
{$EXTERNALSYM gestaltControlMgrPresent}
gestaltControlMgrPresent = (1 shl 0); //* NOTE: this is a bit mask, whereas all other Gestalt constants of*/
//* this type are bit index values. Universal Interfaces 3.2 slipped*/
//* out the door with this mistake.*/
{$EXTERNALSYM gestaltControlMgrPresentBit}
gestaltControlMgrPresentBit = 0; //* bit number*/
{$EXTERNALSYM gestaltControlMsgPresentMask}
gestaltControlMsgPresentMask = (1 shl gestaltControlMgrPresentBit);
//};
//enum {
{$EXTERNALSYM gestaltConnMgrAttr}
gestaltConnMgrAttr = $636f6e6e; //'conn', /* connection mgr attributes */
{$EXTERNALSYM gestaltConnMgrPresent}
gestaltConnMgrPresent = 0;
{$EXTERNALSYM gestaltConnMgrCMSearchFix}
gestaltConnMgrCMSearchFix = 1; //* Fix to CMAddSearch? */
{$EXTERNALSYM gestaltConnMgrErrorString}
gestaltConnMgrErrorString = 2; //* has CMGetErrorString() */
{$EXTERNALSYM gestaltConnMgrMultiAsyncIO}
gestaltConnMgrMultiAsyncIO = 3; //* CMNewIOPB, CMDisposeIOPB, CMPBRead, CMPBWrite, CMPBIOKill */
//};
//enum {
{$EXTERNALSYM gestaltColorPickerVersion}
gestaltColorPickerVersion = $63706b72; //'cpkr', /* returns version of ColorPicker */
{$EXTERNALSYM gestaltColorPicker}
gestaltColorPicker = $63706b72; //'cpkr' /* gestaltColorPicker is old name for gestaltColorPickerVersion */
//};
//enum {
{$EXTERNALSYM gestaltComponentMgr}
gestaltComponentMgr = $63706e74; //'cpnt', /* Component Mgr version */
{$EXTERNALSYM gestaltComponentPlatform}
gestaltComponentPlatform = $636f706c; //'copl' /* Component Platform number */
//};
{*
The gestaltNativeCPUtype ('cput') selector can be used to determine the
native CPU type for all Macs running System 7.5 or later.
However, the use of these selectors for pretty much anything is discouraged.
If you are trying to determine if you can use a particular processor or
operating system feature, it would be much better to check directly for that
feature using one of the apis for doing so -- like, sysctl() or sysctlbyname().
Those apis return information directly from the operating system and kernel. By
using those apis you may be able to avoid linking against Frameworks which you
otherwise don't need, and may lessen the memory and code footprint of your
applications.
The gestaltNativeCPUfamily ('cpuf') selector can be used to determine the
general family the native CPU is in.
gestaltNativeCPUfamily uses the same results as gestaltNativeCPUtype, but
will only return certain CPU values.
IMPORTANT NOTE: gestaltNativeCPUFamily may no longer be updated for any new
processor families introduced after the 970. If there are
processor specific features you need to be checking for in
your code, use one of the appropriate apis to get for those
exact features instead of assuming that all members of a given
cpu family exhibit the same behaviour. The most appropriate api
to look at is sysctl() and sysctlbyname(), which return information
direct from the kernel about the system.
*}
//enum {
{$EXTERNALSYM gestaltNativeCPUtype}
gestaltNativeCPUtype = $63707574; // 'cput', /* Native CPU type */
{$EXTERNALSYM gestaltNativeCPUfamily}
gestaltNativeCPUfamily = $63707566; //'cpuf', /* Native CPU family */
{$EXTERNALSYM gestaltCPU68000}
gestaltCPU68000 = 0; //* Various 68k CPUs... */
{$EXTERNALSYM gestaltCPU68010}
gestaltCPU68010 = 1;
{$EXTERNALSYM gestaltCPU68020}
gestaltCPU68020 = 2;
{$EXTERNALSYM gestaltCPU68030}
gestaltCPU68030 = 3;
{$EXTERNALSYM gestaltCPU68040}
gestaltCPU68040 = 4;
{$EXTERNALSYM gestaltCPU601}
gestaltCPU601 = $0101; //* IBM 601 */
{$EXTERNALSYM gestaltCPU603}
gestaltCPU603 = $0103;
{$EXTERNALSYM gestaltCPU604}
gestaltCPU604 = $0104;
{$EXTERNALSYM gestaltCPU603e}
gestaltCPU603e = $0106;
{$EXTERNALSYM gestaltCPU603ev}
gestaltCPU603ev = $0107;
{$EXTERNALSYM gestaltCPU750}
gestaltCPU750 = $0108; //* Also 740 - "G3" */
{$EXTERNALSYM gestaltCPU604e}
gestaltCPU604e = $0109;
{$EXTERNALSYM gestaltCPU604ev}
gestaltCPU604ev = $010A; //* Mach 5, 250Mhz and up */
{$EXTERNALSYM gestaltCPUG4}
gestaltCPUG4 = $010C; //* Max */
{$EXTERNALSYM gestaltCPUG47450}
gestaltCPUG47450 = $0110; //* Vger , Altivec */
//};
//enum {
{$EXTERNALSYM gestaltCPUApollo}
gestaltCPUApollo = $0111; //* Apollo , Altivec, G4 7455 */
{$EXTERNALSYM gestaltCPUG47447}
gestaltCPUG47447 = $0112;
{$EXTERNALSYM gestaltCPU750FX}
gestaltCPU750FX = $0120; //* Sahara,G3 like thing */
{$EXTERNALSYM gestaltCPU970}
gestaltCPU970 = $0139; //* G5 */
{$EXTERNALSYM gestaltCPU970FX}
gestaltCPU970FX = $013C; //* another G5 */
{$EXTERNALSYM gestaltCPU970MP}
gestaltCPU970MP = $0144;
//};
//enum {
//* x86 CPUs all start with 'i' in the high nybble */
{$EXTERNALSYM gestaltCPU486}
gestaltCPU486 = $69343836; //'i486',
{$EXTERNALSYM gestaltCPUPentium}
gestaltCPUPentium = $69353836; //'i586',
{$EXTERNALSYM gestaltCPUPentiumPro}
gestaltCPUPentiumPro = $69357072; //'i5pr',
{$EXTERNALSYM gestaltCPUPentiumII}
gestaltCPUPentiumII = $69356969; //'i5ii',
{$EXTERNALSYM gestaltCPUX86}
gestaltCPUX86 = $69787878; //'ixxx',
{$EXTERNALSYM gestaltCPUPentium4}
gestaltCPUPentium4 = $69356976; //'i5iv'
//};
//enum {
{$EXTERNALSYM gestaltCRMAttr}
gestaltCRMAttr = $63726d20; //'crm ', /* comm resource mgr attributes */
{$EXTERNALSYM gestaltCRMPresent}
gestaltCRMPresent = 0;
{$EXTERNALSYM gestaltCRMPersistentFix}
gestaltCRMPersistentFix = 1; //* fix for persistent tools */
{$EXTERNALSYM gestaltCRMToolRsrcCalls}
gestaltCRMToolRsrcCalls = 2; //* has CRMGetToolResource/ReleaseToolResource */
//};
//enum {
{$EXTERNALSYM gestaltControlStripVersion}
gestaltControlStripVersion = $63737672; //'csvr' /* Control Strip version (was 'sdvr') */
//};
//enum {
{$EXTERNALSYM gestaltCountOfCPUs}
gestaltCountOfCPUs = $63707573; //'cpus' /* the number of CPUs on the computer, Mac OS X 10.4 and later */
//};
//enum {
{$EXTERNALSYM gestaltCTBVersion}
gestaltCTBVersion = $63746276; //'ctbv' /* CommToolbox version */
//};
//enum {
{$EXTERNALSYM gestaltDBAccessMgrAttr}
gestaltDBAccessMgrAttr = $64626163; // 'dbac', /* Database Access Mgr attributes */
{$EXTERNALSYM gestaltDBAccessMgrPresent}
gestaltDBAccessMgrPresent = 0; //* True if Database Access Mgr present */
//};
//enum {
{$EXTERNALSYM gestaltDiskCacheSize}
gestaltDiskCacheSize = $6463737a; //'dcsz' /* Size of disk cache's buffers, in bytes */
//};
//enum {
{$EXTERNALSYM gestaltSDPFindVersion}
gestaltSDPFindVersion = $64666e64; // 'dfnd' /* OCE Standard Directory Panel*/
//};
//enum {
{$EXTERNALSYM gestaltDictionaryMgrAttr}
gestaltDictionaryMgrAttr = $64696374; // 'dict', /* Dictionary Manager attributes */
{$EXTERNALSYM gestaltDictionaryMgrPresent}
gestaltDictionaryMgrPresent = 0; //* Dictionary Manager attributes */
//};
//enum {
{$EXTERNALSYM gestaltDITLExtAttr}
gestaltDITLExtAttr = $6469746c; //'ditl', /* AppenDITL, etc. calls from CTB */
{$EXTERNALSYM gestaltDITLExtPresent}
gestaltDITLExtPresent = 0; //* True if calls are present */
{$EXTERNALSYM gestaltDITLExtSupportsIctb}
gestaltDITLExtSupportsIctb = 1; //* True if AppendDITL, ShortenDITL support 'ictb's */
//};
//enum {
{$EXTERNALSYM gestaltDialogMgrAttr}
gestaltDialogMgrAttr = $646c6f67; // 'dlog', /* Dialog Mgr*/
{$EXTERNALSYM gestaltDialogMgrPresent}
gestaltDialogMgrPresent = (1 shl 0); //* NOTE: this is a bit mask, whereas all other Gestalt constants of*/
//* this type are bit index values. Universal Interfaces 3.2 slipped*/
//* out the door with this mistake.*/
{$EXTERNALSYM gestaltDialogMgrPresentBit}
gestaltDialogMgrPresentBit = 0; //* bit number*/
{$EXTERNALSYM gestaltDialogMgrHasAquaAlertBit}
gestaltDialogMgrHasAquaAlertBit = 2; //* bit number*/
{$EXTERNALSYM gestaltDialogMgrPresentMask}
gestaltDialogMgrPresentMask = (1 shl gestaltDialogMgrPresentBit);
{$EXTERNALSYM gestaltDialogMgrHasAquaAlertMask}
gestaltDialogMgrHasAquaAlertMask = (1 shl gestaltDialogMgrHasAquaAlertBit);
{$EXTERNALSYM gestaltDialogMsgPresentMask}
gestaltDialogMsgPresentMask = gestaltDialogMgrPresentMask; //* compatibility mask*/
//};
//enum {
{$EXTERNALSYM gestaltDesktopPicturesAttr}
gestaltDesktopPicturesAttr = $646b7078; //'dkpx', /* Desktop Pictures attributes */
{$EXTERNALSYM gestaltDesktopPicturesInstalled}
gestaltDesktopPicturesInstalled = 0; //* True if control panel is installed */
{$EXTERNALSYM gestaltDesktopPicturesDisplayed}
gestaltDesktopPicturesDisplayed = 1; //* True if a picture is currently displayed */
//};
//enum {
{$EXTERNALSYM gestaltDisplayMgrVers}
gestaltDisplayMgrVers = $64706c76; //'dplv' /* Display Manager version */
//};
//enum {
{$EXTERNALSYM gestaltDisplayMgrAttr}
gestaltDisplayMgrAttr = $64706c79; //'dply', /* Display Manager attributes */
{$EXTERNALSYM gestaltDisplayMgrPresent}
gestaltDisplayMgrPresent = 0; //* True if Display Mgr is present */
{$EXTERNALSYM gestaltDisplayMgrCanSwitchMirrored}
gestaltDisplayMgrCanSwitchMirrored = 2; //* True if Display Mgr can switch modes on mirrored displays */
{$EXTERNALSYM gestaltDisplayMgrSetDepthNotifies}
gestaltDisplayMgrSetDepthNotifies = 3; //* True SetDepth generates displays mgr notification */
{$EXTERNALSYM gestaltDisplayMgrCanConfirm}
gestaltDisplayMgrCanConfirm = 4; //* True Display Manager supports DMConfirmConfiguration */
{$EXTERNALSYM gestaltDisplayMgrColorSyncAware}
gestaltDisplayMgrColorSyncAware = 5; //* True if Display Manager supports profiles for displays */
{$EXTERNALSYM gestaltDisplayMgrGeneratesProfiles}
gestaltDisplayMgrGeneratesProfiles = 6; //* True if Display Manager will automatically generate profiles for displays */
{$EXTERNALSYM gestaltDisplayMgrSleepNotifies}
gestaltDisplayMgrSleepNotifies = 7; //* True if Display Mgr generates "displayWillSleep", "displayDidWake" notifications */
//};
//enum {
{$EXTERNALSYM gestaltDragMgrAttr}
gestaltDragMgrAttr = $64726167; // 'drag', /* Drag Manager attributes */
{$EXTERNALSYM gestaltDragMgrPresent}
gestaltDragMgrPresent = 0; //* Drag Manager is present */
{$EXTERNALSYM gestaltDragMgrFloatingWind}
gestaltDragMgrFloatingWind = 1; //* Drag Manager supports floating windows */
{$EXTERNALSYM gestaltPPCDragLibPresent}
gestaltPPCDragLibPresent = 2; //* Drag Manager PPC DragLib is present */
{$EXTERNALSYM gestaltDragMgrHasImageSupport}
gestaltDragMgrHasImageSupport = 3; //* Drag Manager allows SetDragImage call */
{$EXTERNALSYM gestaltCanStartDragInFloatWindow}
gestaltCanStartDragInFloatWindow = 4; //* Drag Manager supports starting a drag in a floating window */
{$EXTERNALSYM gestaltSetDragImageUpdates}
gestaltSetDragImageUpdates = 5; //* Drag Manager supports drag image updating via SetDragImage */
//};
//enum {
{$EXTERNALSYM gestaltDrawSprocketVersion}
gestaltDrawSprocketVersion = $64737076; // 'dspv' /* Draw Sprocket version (as a NumVersion) */
//};
//enum {
{$EXTERNALSYM gestaltDigitalSignatureVersion}
gestaltDigitalSignatureVersion = $64736967; //'dsig' /* returns Digital Signature Toolbox version in low-order word*/
//};
{*
Desktop Printing Feature Gestalt
Use this gestalt to check if third-party printer driver support is available
*}
//enum {
{$EXTERNALSYM gestaltDTPFeatures}
gestaltDTPFeatures = $64747066; // 'dtpf',
{$EXTERNALSYM kDTPThirdPartySupported}
kDTPThirdPartySupported = $00000004; //* mask for checking if third-party drivers are supported*/
//};
{*
Desktop Printer Info Gestalt
Use this gestalt to get a hold of information for all of the active desktop printers
*}
//enum {
{$EXTERNALSYM gestaltDTPInfo}
gestaltDTPInfo = $64747078; //'dtpx' /* returns GestaltDTPInfoHdle*/
//};
//enum {
{$EXTERNALSYM gestaltEasyAccessAttr}
gestaltEasyAccessAttr = $65617379; // 'easy', /* Easy Access attributes */
{$EXTERNALSYM gestaltEasyAccessOff}
gestaltEasyAccessOff = 0; //* if Easy Access present, but off (no icon) */
{$EXTERNALSYM gestaltEasyAccessOn}
gestaltEasyAccessOn = 1; //* if Easy Access "On" */
{$EXTERNALSYM gestaltEasyAccessSticky}
gestaltEasyAccessSticky = 2; //* if Easy Access "Sticky" */
{$EXTERNALSYM gestaltEasyAccessLocked}
gestaltEasyAccessLocked = 3; //* if Easy Access "Locked" */
//};
//enum {
{$EXTERNALSYM gestaltEditionMgrAttr}
gestaltEditionMgrAttr = $6564746e; //'edtn', /* Edition Mgr attributes */
{$EXTERNALSYM gestaltEditionMgrPresent}
gestaltEditionMgrPresent = 0; //* True if Edition Mgr present */
{$EXTERNALSYM gestaltEditionMgrTranslationAware}
gestaltEditionMgrTranslationAware = 1; //* True if edition manager is translation manager aware */
//};
//enum {
{$EXTERNALSYM gestaltAppleEventsAttr}
gestaltAppleEventsAttr = $65766e74; //'evnt', /* Apple Events attributes */
{$EXTERNALSYM gestaltAppleEventsPresent}
gestaltAppleEventsPresent = 0; //* True if Apple Events present */
{$EXTERNALSYM gestaltScriptingSupport}
gestaltScriptingSupport = 1;
{$EXTERNALSYM gestaltOSLInSystem}
gestaltOSLInSystem = 2; //* OSL is in system so don’t use the one linked in to app */
{$EXTERNALSYM gestaltSupportsApplicationURL}
gestaltSupportsApplicationURL = 4; //* Supports the typeApplicationURL addressing mode */
//};
//enum {
{$EXTERNALSYM gestaltExtensionTableVersion}
gestaltExtensionTableVersion = $6574626c; // 'etbl' /* ExtensionTable version */
//};
//enum {
{$EXTERNALSYM gestaltFBCIndexingState}
gestaltFBCIndexingState = $66626369;// 'fbci', /* Find By Content indexing state*/
{$EXTERNALSYM gestaltFBCindexingSafe}
gestaltFBCindexingSafe = 0; //* any search will result in synchronous wait*/
{$EXTERNALSYM gestaltFBCindexingCritical}
gestaltFBCindexingCritical = 1; //* any search will execute immediately*/
//};
//enum {
{$EXTERNALSYM gestaltFBCVersion}
gestaltFBCVersion = $66626376;// 'fbcv', /* Find By Content version*/
{$EXTERNALSYM gestaltFBCCurrentVersion}
gestaltFBCCurrentVersion = $0011; //* First release for OS 8/9*/
{$EXTERNALSYM gestaltOSXFBCCurrentVersion}
gestaltOSXFBCCurrentVersion = $0100; //* First release for OS X*/
//};
//enum {
{$EXTERNALSYM gestaltFileMappingAttr}
gestaltFileMappingAttr = $666c6d70; //'flmp', /* File mapping attributes*/
{$EXTERNALSYM gestaltFileMappingPresent}
gestaltFileMappingPresent = 0; //* bit is set if file mapping APIs are present*/
{$EXTERNALSYM gestaltFileMappingMultipleFilesFix}
gestaltFileMappingMultipleFilesFix = 1; //* bit is set if multiple files per volume can be mapped*/
//};
//enum {
{$EXTERNALSYM gestaltFloppyAttr}
gestaltFloppyAttr = $666c7079; //'flpy', /* Floppy disk drive/driver attributes */
{$EXTERNALSYM gestaltFloppyIsMFMOnly}
gestaltFloppyIsMFMOnly = 0; //* Floppy driver only supports MFM disk formats */
{$EXTERNALSYM gestaltFloppyIsManualEject}
gestaltFloppyIsManualEject = 1; //* Floppy drive, driver, and file system are in manual-eject mode */
{$EXTERNALSYM gestaltFloppyUsesDiskInPlace}
gestaltFloppyUsesDiskInPlace = 2; //* Floppy drive must have special DISK-IN-PLACE output; standard DISK-CHANGED not used */
//};
//enum {
{$EXTERNALSYM gestaltFinderAttr}
gestaltFinderAttr = $666e6472;// 'fndr', //* Finder attributes */
{$EXTERNALSYM gestaltFinderDropEvent}
gestaltFinderDropEvent = 0; //* Finder recognizes drop event */
{$EXTERNALSYM gestaltFinderMagicPlacement}
gestaltFinderMagicPlacement = 1; //* Finder supports magic icon placement */
{$EXTERNALSYM gestaltFinderCallsAEProcess}
gestaltFinderCallsAEProcess = 2; //* Finder calls AEProcessAppleEvent */
{$EXTERNALSYM gestaltOSLCompliantFinder}
gestaltOSLCompliantFinder = 3; //* Finder is scriptable and recordable */
{$EXTERNALSYM gestaltFinderSupports4GBVolumes}
gestaltFinderSupports4GBVolumes = 4; //* Finder correctly handles 4GB volumes */
{$EXTERNALSYM gestaltFinderHasClippings}
gestaltFinderHasClippings = 6; //* Finder supports Drag Manager clipping files */
{$EXTERNALSYM gestaltFinderFullDragManagerSupport}
gestaltFinderFullDragManagerSupport = 7; //* Finder accepts 'hfs ' flavors properly */
{$EXTERNALSYM gestaltFinderFloppyRootComments}
gestaltFinderFloppyRootComments = 8; //* in MacOS 8 and later, will be set if Finder ever supports comments on Floppy icons */
{$EXTERNALSYM gestaltFinderLargeAndNotSavedFlavorsOK}
gestaltFinderLargeAndNotSavedFlavorsOK = 9; //* in MacOS 8 and later, this bit is set if drags with >1024-byte flavors and flavorNotSaved flavors work reliably */
{$EXTERNALSYM gestaltFinderUsesExtensibleFolderManager}
gestaltFinderUsesExtensibleFolderManager = 10; //* Finder uses Extensible Folder Manager (for example, for Magic Routing) */
{$EXTERNALSYM gestaltFinderUnderstandsRedirectedDesktopFolder}
gestaltFinderUnderstandsRedirectedDesktopFolder = 11; //* Finder deals with startup disk's desktop folder residing on another disk */
//};
//enum {
{$EXTERNALSYM gestaltFindFolderAttr}
gestaltFindFolderAttr = $666f6c64; // 'fold', /* Folder Mgr attributes */
{$EXTERNALSYM gestaltFindFolderPresent}
gestaltFindFolderPresent = 0; //* True if Folder Mgr present */
{$EXTERNALSYM gestaltFolderDescSupport}
gestaltFolderDescSupport = 1; //* True if Folder Mgr has FolderDesc calls */
{$EXTERNALSYM gestaltFolderMgrFollowsAliasesWhenResolving}
gestaltFolderMgrFollowsAliasesWhenResolving = 2; //* True if Folder Mgr follows folder aliases */
{$EXTERNALSYM gestaltFolderMgrSupportsExtendedCalls}
gestaltFolderMgrSupportsExtendedCalls = 3; //* True if Folder Mgr supports the Extended calls */
{$EXTERNALSYM gestaltFolderMgrSupportsDomains}
gestaltFolderMgrSupportsDomains = 4; //* True if Folder Mgr supports domains for the first parameter to FindFolder */
{$EXTERNALSYM gestaltFolderMgrSupportsFSCalls}
gestaltFolderMgrSupportsFSCalls = 5; //* True if FOlder manager supports __FindFolderFSRef & __FindFolderExtendedFSRef */
//};
//enum {
{$EXTERNALSYM gestaltFindFolderRedirectionAttr}
gestaltFindFolderRedirectionAttr = $666f6c65; //'fole'
//};
//enum {
{$EXTERNALSYM gestaltFontMgrAttr}
gestaltFontMgrAttr = $666f6e74;//'font', /* Font Mgr attributes */
{$EXTERNALSYM gestaltOutlineFonts}
gestaltOutlineFonts = 0; //* True if Outline Fonts supported */
//};
//enum {
{$EXTERNALSYM gestaltFPUType}
gestaltFPUType = $66707520; //'fpu ', /* fpu type */
{$EXTERNALSYM gestaltNoFPU}
gestaltNoFPU = 0; //* no FPU */
{$EXTERNALSYM gestalt68881}
gestalt68881 = 1; //* 68881 FPU */
{$EXTERNALSYM gestalt68882}
gestalt68882 = 2; //* 68882 FPU */
{$EXTERNALSYM gestalt68040FPU}
gestalt68040FPU = 3; //* 68040 built-in FPU */
//};
//enum {
{$EXTERNALSYM gestaltFSAttr}
gestaltFSAttr = $66732020; //'fs ', /* file system attributes */
{$EXTERNALSYM gestaltFullExtFSDispatching}
gestaltFullExtFSDispatching = 0; //* has really cool new HFSDispatch dispatcher */
{$EXTERNALSYM gestaltHasFSSpecCalls}
gestaltHasFSSpecCalls = 1; //* has FSSpec calls */
{$EXTERNALSYM gestaltHasFileSystemManager}
gestaltHasFileSystemManager = 2; //* has a file system manager */
{$EXTERNALSYM gestaltFSMDoesDynamicLoad}
gestaltFSMDoesDynamicLoad = 3; //* file system manager supports dynamic loading */
{$EXTERNALSYM gestaltFSSupports4GBVols}
gestaltFSSupports4GBVols = 4; //* file system supports 4 gigabyte volumes */
{$EXTERNALSYM gestaltFSSupports2TBVols}
gestaltFSSupports2TBVols = 5; //* file system supports 2 terabyte volumes */
{$EXTERNALSYM gestaltHasExtendedDiskInit}
gestaltHasExtendedDiskInit = 6; //* has extended Disk Initialization calls */
{$EXTERNALSYM gestaltDTMgrSupportsFSM}
gestaltDTMgrSupportsFSM = 7; //* Desktop Manager support FSM-based foreign file systems */
{$EXTERNALSYM gestaltFSNoMFSVols}
gestaltFSNoMFSVols = 8; //* file system doesn't supports MFS volumes */
{$EXTERNALSYM gestaltFSSupportsHFSPlusVols}
gestaltFSSupportsHFSPlusVols = 9; //* file system supports HFS Plus volumes */
{$EXTERNALSYM gestaltFSIncompatibleDFA82}
gestaltFSIncompatibleDFA82 = 10; //* VCB and FCB structures changed; DFA 8.2 is incompatible */
//};
//enum {
{$EXTERNALSYM gestaltFSSupportsDirectIO}
gestaltFSSupportsDirectIO = 11; //* file system supports DirectIO */
//};
//enum {
{$EXTERNALSYM gestaltHasHFSPlusAPIs}
gestaltHasHFSPlusAPIs = 12; //* file system supports HFS Plus APIs */
{$EXTERNALSYM gestaltMustUseFCBAccessors}
gestaltMustUseFCBAccessors = 13; //* FCBSPtr and FSFCBLen are invalid - must use FSM FCB accessor functions*/
{$EXTERNALSYM gestaltFSUsesPOSIXPathsForConversion}
gestaltFSUsesPOSIXPathsForConversion = 14; //* The path interchange routines operate on POSIX paths instead of HFS paths */
{$EXTERNALSYM gestaltFSSupportsExclusiveLocks}
gestaltFSSupportsExclusiveLocks = 15; //* File system uses POSIX O_EXLOCK for opens */
{$EXTERNALSYM gestaltFSSupportsHardLinkDetection}
gestaltFSSupportsHardLinkDetection = 16; //* File system returns if an item is a hard link */
{$EXTERNALSYM gestaltFSAllowsConcurrentAsyncIO}
gestaltFSAllowsConcurrentAsyncIO = 17; //* File Manager supports concurrent async reads and writes */
//};
//enum {
{$EXTERNALSYM gestaltAdminFeaturesFlagsAttr}
gestaltAdminFeaturesFlagsAttr = $66726564; // 'fred', /* a set of admin flags, mostly useful internally. */
{$EXTERNALSYM gestaltFinderUsesSpecialOpenFoldersFile}
gestaltFinderUsesSpecialOpenFoldersFile = 0; //* the Finder uses a special file to store the list of open folders */
//};
//enum {
{$EXTERNALSYM gestaltFSMVersion}
gestaltFSMVersion = $66736d20; //'fsm ' /* returns version of HFS External File Systems Manager (FSM) */
//};
//enum {
{$EXTERNALSYM gestaltFXfrMgrAttr}
gestaltFXfrMgrAttr = $66786672; // 'fxfr', /* file transfer manager attributes */
{$EXTERNALSYM gestaltFXfrMgrPresent}
gestaltFXfrMgrPresent = 0;
{$EXTERNALSYM gestaltFXfrMgrMultiFile}
gestaltFXfrMgrMultiFile = 1; //* supports FTSend and FTReceive */
{$EXTERNALSYM gestaltFXfrMgrErrorString}
gestaltFXfrMgrErrorString = 2; //* supports FTGetErrorString */
{$EXTERNALSYM gestaltFXfrMgrAsync}
gestaltFXfrMgrAsync = 3; //*supports FTSendAsync, FTReceiveAsync, FTCompletionAsync*/
//};
//enum {
{$EXTERNALSYM gestaltGraphicsAttr}
gestaltGraphicsAttr = $67667861; // 'gfxa', /* Quickdraw GX attributes selector */
{$EXTERNALSYM gestaltGraphicsIsDebugging}
gestaltGraphicsIsDebugging = $00000001;
{$EXTERNALSYM gestaltGraphicsIsLoaded}
gestaltGraphicsIsLoaded = $00000002;
{$EXTERNALSYM gestaltGraphicsIsPowerPC}
gestaltGraphicsIsPowerPC = $00000004;
//};
//enum {
{$EXTERNALSYM gestaltGraphicsVersion}
gestaltGraphicsVersion = $67726678; //'grfx', /* Quickdraw GX version selector */
{$EXTERNALSYM gestaltCurrentGraphicsVersion}
gestaltCurrentGraphicsVersion = $00010200; //* the version described in this set of headers */
//};
//enum {
{$EXTERNALSYM gestaltHardwareAttr}
gestaltHardwareAttr = $68647772; //'hdwr', /* hardware attributes */
{$EXTERNALSYM gestaltHasVIA1}
gestaltHasVIA1 = 0; //* VIA1 exists */
{$EXTERNALSYM gestaltHasVIA2}
gestaltHasVIA2 = 1; //* VIA2 exists */
{$EXTERNALSYM gestaltHasASC}
gestaltHasASC = 3; //* Apple Sound Chip exists */
{$EXTERNALSYM gestaltHasSCC}
gestaltHasSCC = 4; //* SCC exists */
{$EXTERNALSYM gestaltHasSCSI}
gestaltHasSCSI = 7; //* SCSI exists */
{$EXTERNALSYM gestaltHasSoftPowerOff}
gestaltHasSoftPowerOff = 19; //* Capable of software power off */
{$EXTERNALSYM gestaltHasSCSI961}
gestaltHasSCSI961 = 21; //* 53C96 SCSI controller on internal bus */
{$EXTERNALSYM gestaltHasSCSI962}
gestaltHasSCSI962 = 22; //* 53C96 SCSI controller on external bus */
{$EXTERNALSYM gestaltHasUniversalROM}
gestaltHasUniversalROM = 24; //* Do we have a Universal ROM? */
{$EXTERNALSYM gestaltHasEnhancedLtalk}
gestaltHasEnhancedLtalk = 30; //* Do we have Enhanced LocalTalk? */
//};
//enum {
{$EXTERNALSYM gestaltHelpMgrAttr}
gestaltHelpMgrAttr = $68656c70;//'help', /* Help Mgr Attributes */
{$EXTERNALSYM gestaltHelpMgrPresent}
gestaltHelpMgrPresent = 0; //* true if help mgr is present */
{$EXTERNALSYM gestaltHelpMgrExtensions}
gestaltHelpMgrExtensions = 1; //* true if help mgr extensions are installed */
{$EXTERNALSYM gestaltAppleGuideIsDebug}
gestaltAppleGuideIsDebug = 30;
{$EXTERNALSYM gestaltAppleGuidePresent}
gestaltAppleGuidePresent = 31; //* true if AppleGuide is installed */
//};
//enum {
{$EXTERNALSYM gestaltHardwareVendorCode}
gestaltHardwareVendorCode = $68726164; //'hrad', /* Returns hardware vendor information */
{$EXTERNALSYM gestaltHardwareVendorApple}
gestaltHardwareVendorApple = $4170706c; //'Appl' /* Hardware built by Apple */
//};
//enum {
{$EXTERNALSYM gestaltCompressionMgr}
gestaltCompressionMgr = $69636d70; //'icmp' /* returns version of the Image Compression Manager */
//};
//enum {
{$EXTERNALSYM gestaltIconUtilitiesAttr}
gestaltIconUtilitiesAttr = $69636f6e; //'icon', /* Icon Utilities attributes (Note: available in System 7.0, despite gestalt) */
{$EXTERNALSYM gestaltIconUtilitiesPresent}
gestaltIconUtilitiesPresent = 0; //* true if icon utilities are present */
{$EXTERNALSYM gestaltIconUtilitiesHas48PixelIcons}
gestaltIconUtilitiesHas48PixelIcons = 1; //* true if 48x48 icons are supported by IconUtilities */
{$EXTERNALSYM gestaltIconUtilitiesHas32BitIcons}
gestaltIconUtilitiesHas32BitIcons = 2; //* true if 32-bit deep icons are supported */
{$EXTERNALSYM gestaltIconUtilitiesHas8BitDeepMasks}
gestaltIconUtilitiesHas8BitDeepMasks = 3; //* true if 8-bit deep masks are supported */
{$EXTERNALSYM gestaltIconUtilitiesHasIconServices}
gestaltIconUtilitiesHasIconServices = 4; //* true if IconServices is present */
//};
//enum {
{$EXTERNALSYM gestaltInternalDisplay}
gestaltInternalDisplay = $69647370; //'idsp' //* slot number of internal display location */
//};
{*
To obtain information about the connected keyboard(s), one should
use the ADB Manager API. See Technical Note OV16 for details.
*}
//enum {
{$EXTERNALSYM gestaltKeyboardType}
gestaltKeyboardType = $6b626420; //'kbd ', /* keyboard type */
{$EXTERNALSYM gestaltMacKbd}
gestaltMacKbd = 1;
{$EXTERNALSYM gestaltMacAndPad}
gestaltMacAndPad = 2;
{$EXTERNALSYM gestaltMacPlusKbd}
gestaltMacPlusKbd = 3; //* OBSOLETE: This pre-ADB keyboard is not supported by any Mac OS X hardware and this value now means gestaltUnknownThirdPartyKbd */
{$EXTERNALSYM gestaltUnknownThirdPartyKbd}
gestaltUnknownThirdPartyKbd = 3; //* Unknown 3rd party keyboard. */
{$EXTERNALSYM gestaltExtADBKbd}
gestaltExtADBKbd = 4;
{$EXTERNALSYM gestaltStdADBKbd}
gestaltStdADBKbd = 5;
{$EXTERNALSYM gestaltPrtblADBKbd}
gestaltPrtblADBKbd = 6;
{$EXTERNALSYM gestaltPrtblISOKbd}
gestaltPrtblISOKbd = 7;
{$EXTERNALSYM gestaltStdISOADBKbd}
gestaltStdISOADBKbd = 8;
{$EXTERNALSYM gestaltExtISOADBKbd}
gestaltExtISOADBKbd = 9;
{$EXTERNALSYM gestaltADBKbdII}
gestaltADBKbdII = 10;
{$EXTERNALSYM gestaltADBISOKbdII}
gestaltADBISOKbdII = 11;
{$EXTERNALSYM gestaltPwrBookADBKbd}
gestaltPwrBookADBKbd = 12;
{$EXTERNALSYM gestaltPwrBookISOADBKbd}
gestaltPwrBookISOADBKbd = 13;
{$EXTERNALSYM gestaltAppleAdjustKeypad}
gestaltAppleAdjustKeypad = 14;
{$EXTERNALSYM gestaltAppleAdjustADBKbd}
gestaltAppleAdjustADBKbd = 15;
{$EXTERNALSYM gestaltAppleAdjustISOKbd}
gestaltAppleAdjustISOKbd = 16;
{$EXTERNALSYM gestaltJapanAdjustADBKbd}
gestaltJapanAdjustADBKbd = 17; //* Japan Adjustable Keyboard */
{$EXTERNALSYM gestaltPwrBkExtISOKbd}
gestaltPwrBkExtISOKbd = 20; //* PowerBook Extended International Keyboard with function keys */
{$EXTERNALSYM gestaltPwrBkExtJISKbd}
gestaltPwrBkExtJISKbd = 21; //* PowerBook Extended Japanese Keyboard with function keys */
{$EXTERNALSYM gestaltPwrBkExtADBKbd}
gestaltPwrBkExtADBKbd = 24; //* PowerBook Extended Domestic Keyboard with function keys */
{$EXTERNALSYM gestaltPS2Keyboard}
gestaltPS2Keyboard = 27; //* PS2 keyboard */
{$EXTERNALSYM gestaltPwrBkSubDomKbd}
gestaltPwrBkSubDomKbd = 28; //* PowerBook Subnote Domestic Keyboard with function keys w/ inverted T */
{$EXTERNALSYM gestaltPwrBkSubISOKbd}
gestaltPwrBkSubISOKbd = 29; //* PowerBook Subnote International Keyboard with function keys w/ inverted T */
{$EXTERNALSYM gestaltPwrBkSubJISKbd}
gestaltPwrBkSubJISKbd = 30; //* PowerBook Subnote Japanese Keyboard with function keys w/ inverted T */
{$EXTERNALSYM gestaltPortableUSBANSIKbd}
gestaltPortableUSBANSIKbd = 37; //* Powerbook USB-based internal keyboard, ANSI layout */
{$EXTERNALSYM gestaltPortableUSBISOKbd}
gestaltPortableUSBISOKbd = 38; //* Powerbook USB-based internal keyboard, ISO layout */
{$EXTERNALSYM gestaltPortableUSBJISKbd}
gestaltPortableUSBJISKbd = 39; //* Powerbook USB-based internal keyboard, JIS layout */
{$EXTERNALSYM gestaltThirdPartyANSIKbd}
gestaltThirdPartyANSIKbd = 40; //* Third party keyboard, ANSI layout. Returned in Mac OS X Tiger and later. */
{$EXTERNALSYM gestaltThirdPartyISOKbd}
gestaltThirdPartyISOKbd = 41; //* Third party keyboard, ISO layout. Returned in Mac OS X Tiger and later. */
{$EXTERNALSYM gestaltThirdPartyJISKbd}
gestaltThirdPartyJISKbd = 42; //* Third party keyboard, JIS layout. Returned in Mac OS X Tiger and later. */
{$EXTERNALSYM gestaltPwrBkEKDomKbd}
gestaltPwrBkEKDomKbd = 195; //* (0xC3) PowerBook Domestic Keyboard with Embedded Keypad, function keys & inverted T */
{$EXTERNALSYM gestaltPwrBkEKISOKbd}
gestaltPwrBkEKISOKbd = 196; //* (0xC4) PowerBook International Keyboard with Embedded Keypad, function keys & inverted T */
{$EXTERNALSYM gestaltPwrBkEKJISKbd}
gestaltPwrBkEKJISKbd = 197; //* (0xC5) PowerBook Japanese Keyboard with Embedded Keypad, function keys & inverted T */
{$EXTERNALSYM gestaltUSBCosmoANSIKbd}
gestaltUSBCosmoANSIKbd = 198; //* (0xC6) original USB Domestic (ANSI) Keyboard */
{$EXTERNALSYM gestaltUSBCosmoISOKbd}
gestaltUSBCosmoISOKbd = 199; //* (0xC7) original USB International (ISO) Keyboard */
{$EXTERNALSYM gestaltUSBCosmoJISKbd}
gestaltUSBCosmoJISKbd = 200; //* (0xC8) original USB Japanese (JIS) Keyboard */
{$EXTERNALSYM gestaltPwrBk99JISKbd}
gestaltPwrBk99JISKbd = 201; //* (0xC9) '99 PowerBook JIS Keyboard with Embedded Keypad, function keys & inverted T */
{$EXTERNALSYM gestaltUSBAndyANSIKbd}
gestaltUSBAndyANSIKbd = 204; //* (0xCC) USB Pro Keyboard Domestic (ANSI) Keyboard */
{$EXTERNALSYM gestaltUSBAndyISOKbd}
gestaltUSBAndyISOKbd = 205; //* (0xCD) USB Pro Keyboard International (ISO) Keyboard */
{$EXTERNALSYM gestaltUSBAndyJISKbd}
gestaltUSBAndyJISKbd = 206; //* (0xCE) USB Pro Keyboard Japanese (JIS) Keyboard */
//};
//enum {
{$EXTERNALSYM gestaltPortable2001ANSIKbd}
gestaltPortable2001ANSIKbd = 202; //* (0xCA) PowerBook and iBook Domestic (ANSI) Keyboard with 2nd cmd key right & function key moves. */
{$EXTERNALSYM gestaltPortable2001ISOKbd}
gestaltPortable2001ISOKbd = 203; //* (0xCB) PowerBook and iBook International (ISO) Keyboard with 2nd cmd key right & function key moves. */
{$EXTERNALSYM gestaltPortable2001JISKbd}
gestaltPortable2001JISKbd = 207; //* (0xCF) PowerBook and iBook Japanese (JIS) Keyboard with function key moves. */
//};
//enum {
{$EXTERNALSYM gestaltUSBProF16ANSIKbd}
gestaltUSBProF16ANSIKbd = 34; //* (0x22) USB Pro Keyboard w/ F16 key Domestic (ANSI) Keyboard */
{$EXTERNALSYM gestaltUSBProF16ISOKbd}
gestaltUSBProF16ISOKbd = 35; //* (0x23) USB Pro Keyboard w/ F16 key International (ISO) Keyboard */
{$EXTERNALSYM gestaltUSBProF16JISKbd}
gestaltUSBProF16JISKbd = 36; //* (0x24) USB Pro Keyboard w/ F16 key Japanese (JIS) Keyboard */
{$EXTERNALSYM gestaltProF16ANSIKbd}
gestaltProF16ANSIKbd = 31; //* (0x1F) Pro Keyboard w/F16 key Domestic (ANSI) Keyboard */
{$EXTERNALSYM gestaltProF16ISOKbd}
gestaltProF16ISOKbd = 32; //* (0x20) Pro Keyboard w/F16 key International (ISO) Keyboard */
{$EXTERNALSYM gestaltProF16JISKbd}
gestaltProF16JISKbd = 33; //* (0x21) Pro Keyboard w/F16 key Japanese (JIS) Keyboard */
//};
{*
This gestalt indicates the highest UDF version that the active UDF implementation supports.
The value should be assembled from a read version (upper word) and a write version (lower word)
*}
//enum {
{$EXTERNALSYM gestaltUDFSupport}
gestaltUDFSupport = $6b756466; //'kudf' /* Used for communication between UDF implementations*/
//};
//enum {
{$EXTERNALSYM gestaltLowMemorySize}
gestaltLowMemorySize = $6c6d656d; //'lmem' /* size of low memory area */
//};
//enum {
{$EXTERNALSYM gestaltLogicalRAMSize}
gestaltLogicalRAMSize = $6c72616d; //'lram' /* logical ram size */
//};
{
MACHINE TYPE CONSTANTS NAMING CONVENTION
All future machine type constant names take the following form:
gestalt<lineName><modelNumber>
Line Names
The following table contains the lines currently produced by Apple and the
lineName substrings associated with them:
Line lineName
------------------------- ------------
Macintosh LC "MacLC"
Macintosh Performa "Performa"
Macintosh PowerBook "PowerBook"
Macintosh PowerBook Duo "PowerBookDuo"
Power Macintosh "PowerMac"
Apple Workgroup Server "AWS"
The following table contains lineNames for some discontinued lines:
Line lineName
------------------------- ------------
Macintosh Quadra "MacQuadra" (preferred)
"Quadra" (also used, but not preferred)
Macintosh Centris "MacCentris"
Model Numbers
The modelNumber is a string representing the specific model of the machine
within its particular line. For example, for the Power Macintosh 8100/80,
the modelNumber is "8100".
Some Performa & LC model numbers contain variations in the rightmost 1 or 2
digits to indicate different RAM and Hard Disk configurations. A single
machine type is assigned for all variations of a specific model number. In
this case, the modelNumber string consists of the constant leftmost part
of the model number with 0s for the variant digits. For example, the
Performa 6115 and Performa 6116 are both return the same machine type
constant: gestaltPerforma6100.
OLD NAMING CONVENTIONS
The "Underscore Speed" suffix
In the past, Apple differentiated between machines that had the same model
number but different speeds. For example, the Power Macintosh 8100/80 and
Power Macintosh 8100/100 return different machine type constants. This is
why some existing machine type constant names take the form:
gestalt<lineName><modelNumber>_<speed>
e.g.
gestaltPowerMac8100_110
gestaltPowerMac7100_80
gestaltPowerMac7100_66
It is no longer necessary to use the "underscore speed" suffix. Starting with
the Power Surge machines (Power Macintosh 7200, 7500, 8500 and 9500), speed is
no longer used to differentiate between machine types. This is why a Power
Macintosh 7200/75 and a Power Macintosh 7200/90 return the same machine type
constant: gestaltPowerMac7200.
The "Screen Type" suffix
All PowerBook models prior to the PowerBook 190, and all PowerBook Duo models
before the PowerBook Duo 2300 take the form:
gestalt<lineName><modelNumber><screenType>
Where <screenType> is "c" or the empty string.
e.g.
gestaltPowerBook100
gestaltPowerBookDuo280
gestaltPowerBookDuo280c
gestaltPowerBook180
gestaltPowerBook180c
Starting with the PowerBook 190 series and the PowerBook Duo 2300 series, machine
types are no longer differentiated based on screen type. This is why a PowerBook
5300cs/100 and a PowerBook 5300c/100 both return the same machine type constant:
gestaltPowerBook5300.
Macintosh LC 630 gestaltMacLC630
Macintosh Performa 6200 gestaltPerforma6200
Macintosh Quadra 700 gestaltQuadra700
Macintosh PowerBook 5300 gestaltPowerBook5300
Macintosh PowerBook Duo 2300 gestaltPowerBookDuo2300
Power Macintosh 8500 gestaltPowerMac8500
*}
//enum {
{$EXTERNALSYM gestaltMachineType}
gestaltMachineType = $6d616368; //'mach', /* machine type */
{$EXTERNALSYM gestaltClassic}
gestaltClassic = 1;
{$EXTERNALSYM gestaltMacXL}
gestaltMacXL = 2;
{$EXTERNALSYM gestaltMac512KE}
gestaltMac512KE = 3;
{$EXTERNALSYM gestaltMacPlus}
gestaltMacPlus = 4;
{$EXTERNALSYM gestaltMacSE}
gestaltMacSE = 5;
{$EXTERNALSYM gestaltMacII}
gestaltMacII = 6;
{$EXTERNALSYM gestaltMacIIx}
gestaltMacIIx = 7;
{$EXTERNALSYM gestaltMacIIcx}
gestaltMacIIcx = 8;
{$EXTERNALSYM gestaltMacSE030}
gestaltMacSE030 = 9;
{$EXTERNALSYM gestaltPortable}
gestaltPortable = 10;
{$EXTERNALSYM gestaltMacIIci}
gestaltMacIIci = 11;
{$EXTERNALSYM gestaltPowerMac8100_120}
gestaltPowerMac8100_120 = 12;
{$EXTERNALSYM gestaltMacIIfx}
gestaltMacIIfx = 13;
{$EXTERNALSYM gestaltMacClassic}
gestaltMacClassic = 17;
{$EXTERNALSYM gestaltMacIIsi}
gestaltMacIIsi = 18;
{$EXTERNALSYM gestaltMacLC}
gestaltMacLC = 19;
{$EXTERNALSYM gestaltMacQuadra900}
gestaltMacQuadra900 = 20;
{$EXTERNALSYM gestaltPowerBook170}
gestaltPowerBook170 = 21;
{$EXTERNALSYM gestaltMacQuadra700}
gestaltMacQuadra700 = 22;
{$EXTERNALSYM gestaltClassicII}
gestaltClassicII = 23;
{$EXTERNALSYM gestaltPowerBook100}
gestaltPowerBook100 = 24;
{$EXTERNALSYM gestaltPowerBook140}
gestaltPowerBook140 = 25;
{$EXTERNALSYM gestaltMacQuadra950}
gestaltMacQuadra950 = 26;
{$EXTERNALSYM gestaltMacLCIII}
gestaltMacLCIII = 27;
{$EXTERNALSYM gestaltPerforma450}
gestaltPerforma450 = gestaltMacLCIII;
{$EXTERNALSYM gestaltPowerBookDuo210}
gestaltPowerBookDuo210 = 29;
{$EXTERNALSYM gestaltMacCentris650}
gestaltMacCentris650 = 30;
{$EXTERNALSYM gestaltPowerBookDuo230}
gestaltPowerBookDuo230 = 32;
{$EXTERNALSYM gestaltPowerBook180}
gestaltPowerBook180 = 33;
{$EXTERNALSYM gestaltPowerBook160}
gestaltPowerBook160 = 34;
{$EXTERNALSYM gestaltMacQuadra800}
gestaltMacQuadra800 = 35;
{$EXTERNALSYM gestaltMacQuadra650}
gestaltMacQuadra650 = 36;
{$EXTERNALSYM gestaltMacLCII}
gestaltMacLCII = 37;
{$EXTERNALSYM gestaltPowerBookDuo250}
gestaltPowerBookDuo250 = 38;
{$EXTERNALSYM gestaltAWS9150_80}
gestaltAWS9150_80 = 39;
{$EXTERNALSYM gestaltPowerMac8100_110}
gestaltPowerMac8100_110 = 40;
{$EXTERNALSYM gestaltAWS8150_110}
gestaltAWS8150_110 = gestaltPowerMac8100_110;
{$EXTERNALSYM gestaltPowerMac5200}
gestaltPowerMac5200 = 41;
{$EXTERNALSYM gestaltPowerMac5260}
gestaltPowerMac5260 = gestaltPowerMac5200;
{$EXTERNALSYM gestaltPerforma5300}
gestaltPerforma5300 = gestaltPowerMac5200;
{$EXTERNALSYM gestaltPowerMac6200}
gestaltPowerMac6200 = 42;
{$EXTERNALSYM gestaltPerforma6300}
gestaltPerforma6300 = gestaltPowerMac6200;
{$EXTERNALSYM gestaltMacIIvi}
gestaltMacIIvi = 44;
{$EXTERNALSYM gestaltMacIIvm}
gestaltMacIIvm = 45;
{$EXTERNALSYM gestaltPerforma600}
gestaltPerforma600 = gestaltMacIIvm;
{$EXTERNALSYM gestaltPowerMac7100_80}
gestaltPowerMac7100_80 = 47;
{$EXTERNALSYM gestaltMacIIvx}
gestaltMacIIvx = 48;
{$EXTERNALSYM gestaltMacColorClassic}
gestaltMacColorClassic = 49;
{$EXTERNALSYM gestaltPerforma250}
gestaltPerforma250 = gestaltMacColorClassic;
{$EXTERNALSYM gestaltPowerBook165c}
gestaltPowerBook165c = 50;
{$EXTERNALSYM gestaltMacCentris610}
gestaltMacCentris610 = 52;
{$EXTERNALSYM gestaltMacQuadra610}
gestaltMacQuadra610 = 53;
{$EXTERNALSYM gestaltPowerBook145}
gestaltPowerBook145 = 54;
{$EXTERNALSYM gestaltPowerMac8100_100}
gestaltPowerMac8100_100 = 55;
{$EXTERNALSYM gestaltMacLC520}
gestaltMacLC520 = 56;
{$EXTERNALSYM gestaltAWS9150_120}
gestaltAWS9150_120 = 57;
{$EXTERNALSYM gestaltPowerMac6400}
gestaltPowerMac6400 = 58;
{$EXTERNALSYM gestaltPerforma6400}
gestaltPerforma6400 = gestaltPowerMac6400;
{$EXTERNALSYM gestaltPerforma6360}
gestaltPerforma6360 = gestaltPerforma6400;
{$EXTERNALSYM gestaltMacCentris660AV}
gestaltMacCentris660AV = 60;
{$EXTERNALSYM gestaltMacQuadra660AV}
gestaltMacQuadra660AV = gestaltMacCentris660AV;
{$EXTERNALSYM gestaltPerforma46x}
gestaltPerforma46x = 62;
{$EXTERNALSYM gestaltPowerMac8100_80}
gestaltPowerMac8100_80 = 65;
{$EXTERNALSYM gestaltAWS8150_80}
gestaltAWS8150_80 = gestaltPowerMac8100_80;
{$EXTERNALSYM gestaltPowerMac9500}
gestaltPowerMac9500 = 67;
{$EXTERNALSYM gestaltPowerMac9600}
gestaltPowerMac9600 = gestaltPowerMac9500;
{$EXTERNALSYM gestaltPowerMac7500}
gestaltPowerMac7500 = 68;
{$EXTERNALSYM gestaltPowerMac7600}
gestaltPowerMac7600 = gestaltPowerMac7500;
{$EXTERNALSYM gestaltPowerMac8500}
gestaltPowerMac8500 = 69;
{$EXTERNALSYM gestaltPowerMac8600}
gestaltPowerMac8600 = gestaltPowerMac8500;
{$EXTERNALSYM gestaltAWS8550}
gestaltAWS8550 = gestaltPowerMac7500;
{$EXTERNALSYM gestaltPowerBook180c}
gestaltPowerBook180c = 71;
{$EXTERNALSYM gestaltPowerBook520}
gestaltPowerBook520 = 72;
{$EXTERNALSYM gestaltPowerBook520c}
gestaltPowerBook520c = gestaltPowerBook520;
{$EXTERNALSYM gestaltPowerBook540}
gestaltPowerBook540 = gestaltPowerBook520;
{$EXTERNALSYM gestaltPowerBook540c}
gestaltPowerBook540c = gestaltPowerBook520;
{$EXTERNALSYM gestaltPowerMac5400}
gestaltPowerMac5400 = 74;
{$EXTERNALSYM gestaltPowerMac6100_60}
gestaltPowerMac6100_60 = 75;
{$EXTERNALSYM gestaltAWS6150_60}
gestaltAWS6150_60 = gestaltPowerMac6100_60;
{$EXTERNALSYM gestaltPowerBookDuo270c}
gestaltPowerBookDuo270c = 77;
{$EXTERNALSYM gestaltMacQuadra840AV}
gestaltMacQuadra840AV = 78;
{$EXTERNALSYM gestaltPerforma550}
gestaltPerforma550 = 80;
{$EXTERNALSYM gestaltPowerBook165}
gestaltPowerBook165 = 84;
{$EXTERNALSYM gestaltPowerBook190}
gestaltPowerBook190 = 85;
{$EXTERNALSYM gestaltMacTV}
gestaltMacTV = 88;
{$EXTERNALSYM gestaltMacLC475}
gestaltMacLC475 = 89;
{$EXTERNALSYM gestaltPerforma47x}
gestaltPerforma47x = gestaltMacLC475;
{$EXTERNALSYM gestaltMacLC575}
gestaltMacLC575 = 92;
{$EXTERNALSYM gestaltMacQuadra605}
gestaltMacQuadra605 = 94;
{$EXTERNALSYM gestaltMacQuadra630}
gestaltMacQuadra630 = 98;
{$EXTERNALSYM gestaltMacLC580}
gestaltMacLC580 = 99;
{$EXTERNALSYM gestaltPerforma580}
gestaltPerforma580 = gestaltMacLC580;
{$EXTERNALSYM gestaltPowerMac6100_66}
gestaltPowerMac6100_66 = 100;
{$EXTERNALSYM gestaltAWS6150_66}
gestaltAWS6150_66 = gestaltPowerMac6100_66;
{$EXTERNALSYM gestaltPowerBookDuo280}
gestaltPowerBookDuo280 = 102;
{$EXTERNALSYM gestaltPowerBookDuo280c}
gestaltPowerBookDuo280c = 103;
{$EXTERNALSYM gestaltPowerMacLC475}
gestaltPowerMacLC475 = 104; //* Mac LC 475 & PPC Processor Upgrade Card*/
{$EXTERNALSYM gestaltPowerMacPerforma47x}
gestaltPowerMacPerforma47x = gestaltPowerMacLC475;
{$EXTERNALSYM gestaltPowerMacLC575}
gestaltPowerMacLC575 = 105; //* Mac LC 575 & PPC Processor Upgrade Card */
{$EXTERNALSYM gestaltPowerMacPerforma57x}
gestaltPowerMacPerforma57x = gestaltPowerMacLC575;
{$EXTERNALSYM gestaltPowerMacQuadra630}
gestaltPowerMacQuadra630 = 106; //* Quadra 630 & PPC Processor Upgrade Card*/
{$EXTERNALSYM gestaltPowerMacLC630}
gestaltPowerMacLC630 = gestaltPowerMacQuadra630; //* Mac LC 630 & PPC Processor Upgrade Card*/
{$EXTERNALSYM gestaltPowerMacPerforma63x}
gestaltPowerMacPerforma63x = gestaltPowerMacQuadra630; //* Performa 63x & PPC Processor Upgrade Card*/
{$EXTERNALSYM gestaltPowerMac7200}
gestaltPowerMac7200 = 108;
{$EXTERNALSYM gestaltPowerMac7300}
gestaltPowerMac7300 = 109;
{$EXTERNALSYM gestaltPowerMac7100_66}
gestaltPowerMac7100_66 = 112;
{$EXTERNALSYM gestaltPowerBook150}
gestaltPowerBook150 = 115;
{$EXTERNALSYM gestaltPowerMacQuadra700}
gestaltPowerMacQuadra700 = 116; //* Quadra 700 & Power PC Upgrade Card*/
{$EXTERNALSYM gestaltPowerMacQuadra900}
gestaltPowerMacQuadra900 = 117; //* Quadra 900 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerMacQuadra950}
gestaltPowerMacQuadra950 = 118; //* Quadra 950 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerMacCentris610}
gestaltPowerMacCentris610 = 119; //* Centris 610 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerMacCentris650}
gestaltPowerMacCentris650 = 120; //* Centris 650 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerMacQuadra610}
gestaltPowerMacQuadra610 = 121; //* Quadra 610 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerMacQuadra650}
gestaltPowerMacQuadra650 = 122; //* Quadra 650 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerMacQuadra800}
gestaltPowerMacQuadra800 = 123; //* Quadra 800 & Power PC Upgrade Card */
{$EXTERNALSYM gestaltPowerBookDuo2300}
gestaltPowerBookDuo2300 = 124;
{$EXTERNALSYM gestaltPowerBook500PPCUpgrade}
gestaltPowerBook500PPCUpgrade = 126;
{$EXTERNALSYM gestaltPowerBook5300}
gestaltPowerBook5300 = 128;
{$EXTERNALSYM gestaltPowerBook1400}
gestaltPowerBook1400 = 310;
{$EXTERNALSYM gestaltPowerBook3400}
gestaltPowerBook3400 = 306;
{$EXTERNALSYM gestaltPowerBook2400}
gestaltPowerBook2400 = 307;
{$EXTERNALSYM gestaltPowerBookG3Series}
gestaltPowerBookG3Series = 312;
{$EXTERNALSYM gestaltPowerBookG3}
gestaltPowerBookG3 = 313;
{$EXTERNALSYM gestaltPowerBookG3Series2}
gestaltPowerBookG3Series2 = 314;
{$EXTERNALSYM gestaltPowerMacNewWorld}
gestaltPowerMacNewWorld = 406; //* All NewWorld architecture Macs (iMac, blue G3, etc.)*/
{$EXTERNALSYM gestaltPowerMacG3}
gestaltPowerMacG3 = 510;
{$EXTERNALSYM gestaltPowerMac5500}
gestaltPowerMac5500 = 512;
{$EXTERNALSYM gestalt20thAnniversary}
gestalt20thAnniversary = gestaltPowerMac5500;
{$EXTERNALSYM gestaltPowerMac6500}
gestaltPowerMac6500 = 513;
{$EXTERNALSYM gestaltPowerMac4400_160}
gestaltPowerMac4400_160 = 514; //* slower machine has different machine ID*/
{$EXTERNALSYM gestaltPowerMac4400}
gestaltPowerMac4400 = 515;
{$EXTERNALSYM gestaltMacOSCompatibility}
gestaltMacOSCompatibility = 1206; //* Mac OS Compatibility on Mac OS X (Classic)*/
//};
//enum {
{$EXTERNALSYM gestaltQuadra605}
gestaltQuadra605 = gestaltMacQuadra605;
{$EXTERNALSYM gestaltQuadra610}
gestaltQuadra610 = gestaltMacQuadra610;
{$EXTERNALSYM gestaltQuadra630}
gestaltQuadra630 = gestaltMacQuadra630;
{$EXTERNALSYM gestaltQuadra650}
gestaltQuadra650 = gestaltMacQuadra650;
{$EXTERNALSYM gestaltQuadra660AV}
gestaltQuadra660AV = gestaltMacQuadra660AV;
{$EXTERNALSYM gestaltQuadra700}
gestaltQuadra700 = gestaltMacQuadra700;
{$EXTERNALSYM gestaltQuadra800}
gestaltQuadra800 = gestaltMacQuadra800;
{$EXTERNALSYM gestaltQuadra840AV}
gestaltQuadra840AV = gestaltMacQuadra840AV;
{$EXTERNALSYM gestaltQuadra900}
gestaltQuadra900 = gestaltMacQuadra900;
{$EXTERNALSYM gestaltQuadra950}
gestaltQuadra950 = gestaltMacQuadra950;
//};
//enum {
{$EXTERNALSYM kMachineNameStrID}
kMachineNameStrID = -16395;
//};
//enum {
{$EXTERNALSYM gestaltSMPMailerVersion}
gestaltSMPMailerVersion = $6d616c72; //'malr' /* OCE StandardMail*/
//};
//enum {
{$EXTERNALSYM gestaltMediaBay}
gestaltMediaBay = $6d626568; //'mbeh', /* media bay driver type */
{$EXTERNALSYM gestaltMBLegacy}
gestaltMBLegacy = 0; //* media bay support in PCCard 2.0 */
{$EXTERNALSYM gestaltMBSingleBay}
gestaltMBSingleBay = 1; //* single bay media bay driver */
{$EXTERNALSYM gestaltMBMultipleBays}
gestaltMBMultipleBays = 2; //* multi-bay media bay driver */
//};
//enum {
{$EXTERNALSYM gestaltMessageMgrVersion}
gestaltMessageMgrVersion = $6d657373; //'mess' //* GX Printing Message Manager Gestalt Selector */
//};
//* Menu Manager Gestalt (Mac OS 8.5 and later)*/
//enum {
{$EXTERNALSYM gestaltMenuMgrAttr}
gestaltMenuMgrAttr = $6d656e75; //'menu', /* If this Gestalt exists, the Mac OS 8.5 Menu Manager is installed */
{$EXTERNALSYM gestaltMenuMgrPresent}
gestaltMenuMgrPresent = (1 shl 0); //* NOTE: this is a bit mask, whereas all other Gestalt constants of this nature */
//* are bit index values. 3.2 interfaces slipped out with this mistake unnoticed. */
//* Sincere apologies for any inconvenience.*/
{$EXTERNALSYM gestaltMenuMgrPresentBit}
gestaltMenuMgrPresentBit = 0; //* bit number */
{$EXTERNALSYM gestaltMenuMgrAquaLayoutBit}
gestaltMenuMgrAquaLayoutBit = 1; //* menus have the Aqua 1.0 layout*/
{$EXTERNALSYM gestaltMenuMgrMultipleItemsWithCommandIDBit}
gestaltMenuMgrMultipleItemsWithCommandIDBit = 2; //* CountMenuItemsWithCommandID/GetIndMenuItemWithCommandID support multiple items with the same command ID*/
{$EXTERNALSYM gestaltMenuMgrRetainsIconRefBit}
gestaltMenuMgrRetainsIconRefBit = 3; //* SetMenuItemIconHandle, when passed an IconRef, calls AcquireIconRef*/
{$EXTERNALSYM gestaltMenuMgrSendsMenuBoundsToDefProcBit}
gestaltMenuMgrSendsMenuBoundsToDefProcBit = 4; //* kMenuSizeMsg and kMenuPopUpMsg have menu bounding rect information*/
{$EXTERNALSYM gestaltMenuMgrMoreThanFiveMenusDeepBit}
gestaltMenuMgrMoreThanFiveMenusDeepBit = 5; //* the Menu Manager supports hierarchical menus more than five deep*/
{$EXTERNALSYM gestaltMenuMgrCGImageMenuTitleBit}
gestaltMenuMgrCGImageMenuTitleBit = 6; //* SetMenuTitleIcon supports CGImageRefs*/
//* masks for the above bits*/
{$EXTERNALSYM gestaltMenuMgrPresentMask}
gestaltMenuMgrPresentMask = (1 shl gestaltMenuMgrPresentBit);
{$EXTERNALSYM gestaltMenuMgrAquaLayoutMask}
gestaltMenuMgrAquaLayoutMask = (1 shl gestaltMenuMgrAquaLayoutBit);
{$EXTERNALSYM gestaltMenuMgrMultipleItemsWithCommandIDMask}
gestaltMenuMgrMultipleItemsWithCommandIDMask = (1 shl gestaltMenuMgrMultipleItemsWithCommandIDBit);
{$EXTERNALSYM gestaltMenuMgrRetainsIconRefMask}
gestaltMenuMgrRetainsIconRefMask = (1 shl gestaltMenuMgrRetainsIconRefBit);
{$EXTERNALSYM gestaltMenuMgrSendsMenuBoundsToDefProcMask}
gestaltMenuMgrSendsMenuBoundsToDefProcMask = (1 shl gestaltMenuMgrSendsMenuBoundsToDefProcBit);
{$EXTERNALSYM gestaltMenuMgrMoreThanFiveMenusDeepMask}
gestaltMenuMgrMoreThanFiveMenusDeepMask = (1 shl gestaltMenuMgrMoreThanFiveMenusDeepBit);
{$EXTERNALSYM gestaltMenuMgrCGImageMenuTitleMask}
gestaltMenuMgrCGImageMenuTitleMask = (1 shl gestaltMenuMgrCGImageMenuTitleBit);
//};
//enum {
{$EXTERNALSYM gestaltMultipleUsersState}
gestaltMultipleUsersState = $6d666472; //'mfdr' //* Gestalt selector returns MultiUserGestaltHandle (in Folders.h)*/
//};
//enum {
{$EXTERNALSYM gestaltMachineIcon}
gestaltMachineIcon = $6d69636e; //'micn' /* machine icon */
//};
//enum {
{$EXTERNALSYM gestaltMiscAttr}
gestaltMiscAttr = $6d697363; //'misc', /* miscellaneous attributes */
{$EXTERNALSYM gestaltScrollingThrottle}
gestaltScrollingThrottle = 0; //* true if scrolling throttle on */
{$EXTERNALSYM gestaltSquareMenuBar}
gestaltSquareMenuBar = 2; //* true if menu bar is square */
//};
{*
The name gestaltMixedModeVersion for the 'mixd' selector is semantically incorrect.
The same selector has been renamed gestaltMixedModeAttr to properly reflect the
Inside Mac: PowerPC System Software documentation. The gestaltMixedModeVersion
symbol has been preserved only for backwards compatibility.
Developers are forewarned that gestaltMixedModeVersion has a limited lifespan and
will be removed in a future release of the Interfaces.
For the first version of Mixed Mode, both meanings of the 'mixd' selector are
functionally identical. They both return 0x00000001. In subsequent versions
of Mixed Mode, however, the 'mixd' selector will not respond with an increasing
version number, but rather, with 32 attribute bits with various meanings.
*}
//enum {
{$EXTERNALSYM gestaltMixedModeVersion}
gestaltMixedModeVersion = $6d697864; //'mixd' /* returns version of Mixed Mode */
//};
//enum {
{$EXTERNALSYM gestaltMixedModeAttr}
gestaltMixedModeAttr = $6d697864; //'mixd', /* returns Mixed Mode attributes */
{$EXTERNALSYM gestaltMixedModePowerPC}
gestaltMixedModePowerPC = 0; //* true if Mixed Mode supports PowerPC ABI calling conventions */
{$EXTERNALSYM gestaltPowerPCAware}
gestaltPowerPCAware = 0; //* old name for gestaltMixedModePowerPC */
{$EXTERNALSYM gestaltMixedModeCFM68K}
gestaltMixedModeCFM68K = 1; //* true if Mixed Mode supports CFM-68K calling conventions */
{$EXTERNALSYM gestaltMixedModeCFM68KHasTrap}
gestaltMixedModeCFM68KHasTrap = 2; //* true if CFM-68K Mixed Mode implements _MixedModeDispatch (versions 1.0.1 and prior did not) */
{$EXTERNALSYM gestaltMixedModeCFM68KHasState}
gestaltMixedModeCFM68KHasState = 3; //* true if CFM-68K Mixed Mode exports Save/RestoreMixedModeState */
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeConferencing}
gestaltQuickTimeConferencing = $6d746c6b;// 'mtlk' /* returns QuickTime Conferencing version */
//};
//enum {
{$EXTERNALSYM gestaltMemoryMapAttr}
gestaltMemoryMapAttr = $6d6d6170; //'mmap', /* Memory map type */
{$EXTERNALSYM gestaltMemoryMapSparse}
gestaltMemoryMapSparse = 0; //* Sparse memory is on */
//};
//enum {
{$EXTERNALSYM gestaltMMUType}
gestaltMMUType = $6d6d7520; // 'mmu ', /* mmu type */
{$EXTERNALSYM gestaltNoMMU}
gestaltNoMMU = 0; //* no MMU */
{$EXTERNALSYM gestaltAMU}
gestaltAMU = 1; //* address management unit */
{$EXTERNALSYM gestalt68851}
gestalt68851 = 2; //* 68851 PMMU */
{$EXTERNALSYM gestalt68030MMU}
gestalt68030MMU = 3; //* 68030 built-in MMU */
{$EXTERNALSYM gestalt68040MMU}
gestalt68040MMU = 4; //* 68040 built-in MMU */
{$EXTERNALSYM gestaltEMMU1}
gestaltEMMU1 = 5; //* Emulated MMU type 1 */
//};
//enum {
//* On Mac OS X, the user visible machine name may something like "PowerMac3,4", which is*/
//* a unique string for each signifigant Macintosh computer which Apple creates, but is*/
//* not terribly useful as a user visible string.*/
{$EXTERNALSYM gestaltUserVisibleMachineName}
gestaltUserVisibleMachineName = $6d6e616d;//'mnam' /* Coerce response into a StringPtr to get a user visible machine name */
//};
//enum {
{$EXTERNALSYM gestaltMPCallableAPIsAttr}
gestaltMPCallableAPIsAttr = $6d707363; //'mpsc', /* Bitmap of toolbox/OS managers that can be called from MPLibrary MPTasks */
{$EXTERNALSYM gestaltMPFileManager}
gestaltMPFileManager = 0; //* True if File Manager calls can be made from MPTasks */
{$EXTERNALSYM gestaltMPDeviceManager}
gestaltMPDeviceManager = 1; //* True if synchronous Device Manager calls can be made from MPTasks */
{$EXTERNALSYM gestaltMPTrapCalls}
gestaltMPTrapCalls = 2; //* True if most trap-based calls can be made from MPTasks */
//};
//enum {
{$EXTERNALSYM gestaltStdNBPAttr}
gestaltStdNBPAttr = $6e6c7570; //'nlup', /* standard nbp attributes */
{$EXTERNALSYM gestaltStdNBPPresent}
gestaltStdNBPPresent = 0;
{$EXTERNALSYM gestaltStdNBPSupportsAutoPosition}
gestaltStdNBPSupportsAutoPosition = 1; //* StandardNBP takes (-1,-1) to mean alert position main screen */
//};
//enum {
{$EXTERNALSYM gestaltNotificationMgrAttr}
gestaltNotificationMgrAttr = $6e6d6772; //'nmgr', /* notification manager attributes */
{$EXTERNALSYM gestaltNotificationPresent}
gestaltNotificationPresent = 0; //* notification manager exists */
//};
//enum {
{$EXTERNALSYM gestaltNameRegistryVersion}
gestaltNameRegistryVersion = $6e726567; //'nreg' /* NameRegistryLib version number, for System 7.5.2+ usage */
//};
//enum {
{$EXTERNALSYM gestaltNuBusSlotCount}
gestaltNuBusSlotCount = $6e756273; // 'nubs' /* count of logical NuBus slots present */
//};
//enum {
{$EXTERNALSYM gestaltOCEToolboxVersion}
gestaltOCEToolboxVersion = $6f636574; //'ocet', /* OCE Toolbox version */
{$EXTERNALSYM gestaltOCETB}
gestaltOCETB = $0102; //* OCE Toolbox version 1.02 */
{$EXTERNALSYM gestaltSFServer}
gestaltSFServer = $0100; //* S&F Server version 1.0 */
//};
//enum {
{$EXTERNALSYM gestaltOCEToolboxAttr}
gestaltOCEToolboxAttr = $6f636575; //'oceu', /* OCE Toolbox attributes */
{$EXTERNALSYM gestaltOCETBPresent}
gestaltOCETBPresent = $01; //* OCE toolbox is present, not running */
{$EXTERNALSYM gestaltOCETBAvailable}
gestaltOCETBAvailable = $02; //* OCE toolbox is running and available */
{$EXTERNALSYM gestaltOCESFServerAvailable}
gestaltOCESFServerAvailable = $04; //* S&F Server is running and available */
{$EXTERNALSYM gestaltOCETBNativeGlueAvailable}
gestaltOCETBNativeGlueAvailable = $10; //* Native PowerPC Glue routines are availible */
//};
//enum {
{$EXTERNALSYM gestaltOpenFirmwareInfo}
gestaltOpenFirmwareInfo = $6f706677; //'opfw' /* Open Firmware info */
//};
//enum {
{$EXTERNALSYM gestaltOSAttr}
gestaltOSAttr = $6f732020;//'os ', /* o/s attributes */
{$EXTERNALSYM gestaltSysZoneGrowable}
gestaltSysZoneGrowable = 0; //* system heap is growable */
{$EXTERNALSYM gestaltLaunchCanReturn}
gestaltLaunchCanReturn = 1; //* can return from launch */
{$EXTERNALSYM gestaltLaunchFullFileSpec}
gestaltLaunchFullFileSpec = 2; //* can launch from full file spec */
{$EXTERNALSYM gestaltLaunchControl}
gestaltLaunchControl = 3; //* launch control support available */
{$EXTERNALSYM gestaltTempMemSupport}
gestaltTempMemSupport = 4; //* temp memory support */
{$EXTERNALSYM gestaltRealTempMemory}
gestaltRealTempMemory = 5; //* temp memory handles are real */
{$EXTERNALSYM gestaltTempMemTracked}
gestaltTempMemTracked = 6; //* temporary memory handles are tracked */
{$EXTERNALSYM gestaltIPCSupport}
gestaltIPCSupport = 7; //* IPC support is present */
{$EXTERNALSYM gestaltSysDebuggerSupport}
gestaltSysDebuggerSupport = 8; //* system debugger support is present */
{$EXTERNALSYM gestaltNativeProcessMgrBit}
gestaltNativeProcessMgrBit = 19; //* the process manager itself is native */
{$EXTERNALSYM gestaltAltivecRegistersSwappedCorrectlyBit}
gestaltAltivecRegistersSwappedCorrectlyBit = 20; //* Altivec registers are saved correctly on process switches */
//};
//enum {
{$EXTERNALSYM gestaltOSTable}
gestaltOSTable = $6f737474;//'ostt' /* OS trap table base */
//};
{*******************************************************************************
* Gestalt Selectors for Open Transport Network Setup
*
* Note: possible values for the version "stage" byte are:
* development = 0x20, alpha = 0x40, beta = 0x60, final & release = 0x80
********************************************************************************}
//enum {
{$EXTERNALSYM gestaltOpenTptNetworkSetup}
gestaltOpenTptNetworkSetup = $6f746366;//'otcf',
{$EXTERNALSYM gestaltOpenTptNetworkSetupLegacyImport}
gestaltOpenTptNetworkSetupLegacyImport = 0;
{$EXTERNALSYM gestaltOpenTptNetworkSetupLegacyExport}
gestaltOpenTptNetworkSetupLegacyExport = 1;
{$EXTERNALSYM gestaltOpenTptNetworkSetupSupportsMultihoming}
gestaltOpenTptNetworkSetupSupportsMultihoming = 2;
//};
//enum {
{$EXTERNALSYM gestaltOpenTptNetworkSetupVersion}
gestaltOpenTptNetworkSetupVersion = $6f746376; //'otcv'
//};
{*******************************************************************************
* Gestalt Selectors for Open Transport-based Remote Access/PPP
*
* Note: possible values for the version "stage" byte are:
* development = 0x20, alpha = 0x40, beta = 0x60, final & release = 0x80
********************************************************************************}
//enum {
{$EXTERNALSYM gestaltOpenTptRemoteAccess}
gestaltOpenTptRemoteAccess = $6f747261; //'otra',
{$EXTERNALSYM gestaltOpenTptRemoteAccessPresent}
gestaltOpenTptRemoteAccessPresent = 0;
{$EXTERNALSYM gestaltOpenTptRemoteAccessLoaded}
gestaltOpenTptRemoteAccessLoaded = 1;
{$EXTERNALSYM gestaltOpenTptRemoteAccessClientOnly}
gestaltOpenTptRemoteAccessClientOnly = 2;
{$EXTERNALSYM gestaltOpenTptRemoteAccessPServer}
gestaltOpenTptRemoteAccessPServer = 3;
{$EXTERNALSYM gestaltOpenTptRemoteAccessMPServer}
gestaltOpenTptRemoteAccessMPServer = 4;
{$EXTERNALSYM gestaltOpenTptPPPPresent}
gestaltOpenTptPPPPresent = 5;
{$EXTERNALSYM gestaltOpenTptARAPPresent}
gestaltOpenTptARAPPresent = 6;
//};
//enum {
{$EXTERNALSYM gestaltOpenTptRemoteAccessVersion}
gestaltOpenTptRemoteAccessVersion = $6f747276;// 'otrv'
//};
//* ***** Open Transport Gestalt ******/
//enum {
{$EXTERNALSYM gestaltOpenTptVersions}
gestaltOpenTptVersions = $6f747672; // 'otvr' /* Defined by OT 1.1 and higher, response is NumVersion.*/
//};
//enum {
{$EXTERNALSYM gestaltOpenTpt}
gestaltOpenTpt = $6f74616e; //'otan', /* Defined by all versions, response is defined below.*/
{$EXTERNALSYM gestaltOpenTptPresentMask}
gestaltOpenTptPresentMask = $00000001;
{$EXTERNALSYM gestaltOpenTptLoadedMask}
gestaltOpenTptLoadedMask = $00000002;
{$EXTERNALSYM gestaltOpenTptAppleTalkPresentMask}
gestaltOpenTptAppleTalkPresentMask = $00000004;
{$EXTERNALSYM gestaltOpenTptAppleTalkLoadedMask}
gestaltOpenTptAppleTalkLoadedMask = $00000008;
{$EXTERNALSYM gestaltOpenTptTCPPresentMask}
gestaltOpenTptTCPPresentMask = $00000010;
{$EXTERNALSYM gestaltOpenTptTCPLoadedMask}
gestaltOpenTptTCPLoadedMask = $00000020;
{$EXTERNALSYM gestaltOpenTptIPXSPXPresentMask}
gestaltOpenTptIPXSPXPresentMask = $00000040;
{$EXTERNALSYM gestaltOpenTptIPXSPXLoadedMask}
gestaltOpenTptIPXSPXLoadedMask = $00000080;
{$EXTERNALSYM gestaltOpenTptPresentBit}
gestaltOpenTptPresentBit = 0;
{$EXTERNALSYM gestaltOpenTptLoadedBit}
gestaltOpenTptLoadedBit = 1;
{$EXTERNALSYM gestaltOpenTptAppleTalkPresentBit}
gestaltOpenTptAppleTalkPresentBit = 2;
{$EXTERNALSYM gestaltOpenTptAppleTalkLoadedBit}
gestaltOpenTptAppleTalkLoadedBit = 3;
{$EXTERNALSYM gestaltOpenTptTCPPresentBit}
gestaltOpenTptTCPPresentBit = 4;
{$EXTERNALSYM gestaltOpenTptTCPLoadedBit}
gestaltOpenTptTCPLoadedBit = 5;
{$EXTERNALSYM gestaltOpenTptIPXSPXPresentBit}
gestaltOpenTptIPXSPXPresentBit = 6;
{$EXTERNALSYM gestaltOpenTptIPXSPXLoadedBit}
gestaltOpenTptIPXSPXLoadedBit = 7;
//};
//enum {
{$EXTERNALSYM gestaltPCCard}
gestaltPCCard = $70636364; // 'pccd', /* PC Card attributes*/
{$EXTERNALSYM gestaltCardServicesPresent}
gestaltCardServicesPresent = 0; //* PC Card 2.0 (68K) API is present*/
{$EXTERNALSYM gestaltPCCardFamilyPresent}
gestaltPCCardFamilyPresent = 1; //* PC Card 3.x (PowerPC) API is present*/
{$EXTERNALSYM gestaltPCCardHasPowerControl}
gestaltPCCardHasPowerControl = 2; //* PCCardSetPowerLevel is supported*/
{$EXTERNALSYM gestaltPCCardSupportsCardBus}
gestaltPCCardSupportsCardBus = 3; //* CardBus is supported*/
//};
//enum {
{$EXTERNALSYM gestaltProcClkSpeed}
gestaltProcClkSpeed = $70636c6b; //'pclk' /* processor clock speed in hertz (a UInt32) */
//};
//enum {
{$EXTERNALSYM gestaltProcClkSpeedMHz}
gestaltProcClkSpeedMHz = $6d636c6b;// 'mclk' /* processor clock speed in megahertz (a UInt32) */
//};
//enum {
{$EXTERNALSYM gestaltPCXAttr}
gestaltPCXAttr = $70637867; //'pcxg', /* PC Exchange attributes */
{$EXTERNALSYM gestaltPCXHas8and16BitFAT}
gestaltPCXHas8and16BitFAT = 0; //* PC Exchange supports both 8 and 16 bit FATs */
{$EXTERNALSYM gestaltPCXHasProDOS}
gestaltPCXHasProDOS = 1; //* PC Exchange supports ProDOS */
{$EXTERNALSYM gestaltPCXNewUI}
gestaltPCXNewUI = 2;
{$EXTERNALSYM gestaltPCXUseICMapping}
gestaltPCXUseICMapping = 3; //* PC Exchange uses InternetConfig for file mappings */
//};
//enum {
{$EXTERNALSYM gestaltLogicalPageSize}
gestaltLogicalPageSize = $7067737a; // 'pgsz' /* logical page size */
//};
{* System 7.6 and later. If gestaltScreenCaptureMain is not implemented,
PictWhap proceeds with screen capture in the usual way.
The high word of gestaltScreenCaptureMain is reserved (use 0).
To disable screen capture to disk, put zero in the low word. To
specify a folder for captured pictures, put the vRefNum in the
low word of gestaltScreenCaptureMain, and put the directory ID in
gestaltScreenCaptureDir.
*}
//enum {
{$EXTERNALSYM gestaltScreenCaptureMain}
gestaltScreenCaptureMain = $70696331; //'pic1', /* Zero, or vRefNum of disk to hold picture */
{$EXTERNALSYM gestaltScreenCaptureDir}
gestaltScreenCaptureDir = $70696332; //'pic2' /* Directory ID of folder to hold picture */
//};
//enum {
{$EXTERNALSYM gestaltGXPrintingMgrVersion}
gestaltGXPrintingMgrVersion = $706d6772; // 'pmgr' /* QuickDraw GX Printing Manager Version*/
//};
//enum {
{$EXTERNALSYM gestaltPopupAttr}
gestaltPopupAttr = $706f7021;//'pop!', /* popup cdef attributes */
{$EXTERNALSYM gestaltPopupPresent}
gestaltPopupPresent = 0;
//};
//enum {
{$EXTERNALSYM gestaltPowerMgrAttr}
gestaltPowerMgrAttr = $706f7772; //'powr', /* power manager attributes */
{$EXTERNALSYM gestaltPMgrExists}
gestaltPMgrExists = 0;
{$EXTERNALSYM gestaltPMgrCPUIdle}
gestaltPMgrCPUIdle = 1;
{$EXTERNALSYM gestaltPMgrSCC}
gestaltPMgrSCC = 2;
{$EXTERNALSYM gestaltPMgrSound}
gestaltPMgrSound = 3;
{$EXTERNALSYM gestaltPMgrDispatchExists}
gestaltPMgrDispatchExists = 4;
{$EXTERNALSYM gestaltPMgrSupportsAVPowerStateAtSleepWake}
gestaltPMgrSupportsAVPowerStateAtSleepWake = 5;
//};
//enum {
{$EXTERNALSYM gestaltPowerMgrVers}
gestaltPowerMgrVers = $70777276; //'pwrv' /* power manager version */
//};
{*
* PPC will return the combination of following bit fields.
* e.g. gestaltPPCSupportsRealTime +gestaltPPCSupportsIncoming + gestaltPPCSupportsOutGoing
* indicates PPC is cuurently is only supports real time delivery
* and both incoming and outgoing network sessions are allowed.
* By default local real time delivery is supported as long as PPCInit has been called.*}
//enum {
{$EXTERNALSYM gestaltPPCToolboxAttr}
gestaltPPCToolboxAttr = $70706320;// 'ppc ', /* PPC toolbox attributes */
{$EXTERNALSYM gestaltPPCToolboxPresent}
gestaltPPCToolboxPresent = $0000; //* PPC Toolbox is present Requires PPCInit to be called */
{$EXTERNALSYM gestaltPPCSupportsRealTime}
gestaltPPCSupportsRealTime = $1000; //* PPC Supports real-time delivery */
{$EXTERNALSYM gestaltPPCSupportsIncoming}
gestaltPPCSupportsIncoming = $0001; //* PPC will allow incoming network requests */
{$EXTERNALSYM gestaltPPCSupportsOutGoing}
gestaltPPCSupportsOutGoing = $0002; //* PPC will allow outgoing network requests */
{$EXTERNALSYM gestaltPPCSupportsTCP_IP}
gestaltPPCSupportsTCP_IP = $0004; //* PPC supports TCP/IP transport */
{$EXTERNALSYM gestaltPPCSupportsIncomingAppleTalk}
gestaltPPCSupportsIncomingAppleTalk = $0010;
{$EXTERNALSYM gestaltPPCSupportsIncomingTCP_IP}
gestaltPPCSupportsIncomingTCP_IP = $0020;
{$EXTERNALSYM gestaltPPCSupportsOutgoingAppleTalk}
gestaltPPCSupportsOutgoingAppleTalk = $0100;
{$EXTERNALSYM gestaltPPCSupportsOutgoingTCP_IP}
gestaltPPCSupportsOutgoingTCP_IP = $0200;
//};
{*
Programs which need to know information about particular features of the processor should
migrate to using sysctl() and sysctlbyname() to get this kind of information. No new
information will be added to the 'ppcf' selector going forward.
*}
//enum {
{$EXTERNALSYM gestaltPowerPCProcessorFeatures}
gestaltPowerPCProcessorFeatures = $70706366;// 'ppcf', //* Optional PowerPC processor features */
{$EXTERNALSYM gestaltPowerPCHasGraphicsInstructions}
gestaltPowerPCHasGraphicsInstructions = 0; //* has fres, frsqrte, and fsel instructions */
{$EXTERNALSYM gestaltPowerPCHasSTFIWXInstruction}
gestaltPowerPCHasSTFIWXInstruction = 1; //* has stfiwx instruction */
{$EXTERNALSYM gestaltPowerPCHasSquareRootInstructions}
gestaltPowerPCHasSquareRootInstructions = 2; //* has fsqrt and fsqrts instructions */
{$EXTERNALSYM gestaltPowerPCHasDCBAInstruction}
gestaltPowerPCHasDCBAInstruction = 3; //* has dcba instruction */
{$EXTERNALSYM gestaltPowerPCHasVectorInstructions}
gestaltPowerPCHasVectorInstructions = 4; //* has vector instructions */
{$EXTERNALSYM gestaltPowerPCHasDataStreams}
gestaltPowerPCHasDataStreams = 5; //* has dst, dstt, dstst, dss, and dssall instructions */
{$EXTERNALSYM gestaltPowerPCHas64BitSupport}
gestaltPowerPCHas64BitSupport = 6; //* double word LSU/ALU, etc. */
{$EXTERNALSYM gestaltPowerPCHasDCBTStreams}
gestaltPowerPCHasDCBTStreams = 7; //* TH field of DCBT recognized */
{$EXTERNALSYM gestaltPowerPCASArchitecture}
gestaltPowerPCASArchitecture = 8; //* chip uses new 'A/S' architecture */
{$EXTERNALSYM gestaltPowerPCIgnoresDCBST}
gestaltPowerPCIgnoresDCBST = 9; //* */
//};
//enum {
{$EXTERNALSYM gestaltProcessorType}
gestaltProcessorType = $70726f63; //'proc', /* processor type */
{$EXTERNALSYM gestalt68000}
gestalt68000 = 1;
{$EXTERNALSYM gestalt68010}
gestalt68010 = 2;
{$EXTERNALSYM gestalt68020}
gestalt68020 = 3;
{$EXTERNALSYM gestalt68030}
gestalt68030 = 4;
{$EXTERNALSYM gestalt68040}
gestalt68040 = 5;
//};
//enum {
{$EXTERNALSYM gestaltSDPPromptVersion}
gestaltSDPPromptVersion = $70727076; //'prpv' /* OCE Standard Directory Panel*/
//};
//enum {
{$EXTERNALSYM gestaltParityAttr}
gestaltParityAttr = $70727479; //'prty', /* parity attributes */
{$EXTERNALSYM gestaltHasParityCapability}
gestaltHasParityCapability = 0; //* has ability to check parity */
{$EXTERNALSYM gestaltParityEnabled}
gestaltParityEnabled = 1; //* parity checking enabled */
//};
//enum {
{$EXTERNALSYM gestaltQD3DVersion}
gestaltQD3DVersion = $71337620; //'q3v ' /* Quickdraw 3D version in pack BCD*/
//};
//enum {
{$EXTERNALSYM gestaltQD3DViewer}
gestaltQD3DViewer = $71337663; //'q3vc', /* Quickdraw 3D viewer attributes*/
{$EXTERNALSYM gestaltQD3DViewerPresent}
gestaltQD3DViewerPresent = 0; //* bit 0 set if QD3D Viewer is available*/
//};
//#if OLDROUTINENAMES
//enum {
{$EXTERNALSYM gestaltQD3DViewerNotPresent}
gestaltQD3DViewerNotPresent = (0 shl gestaltQD3DViewerPresent);
{$EXTERNALSYM gestaltQD3DViewerAvailable}
gestaltQD3DViewerAvailable = (1 shl gestaltQD3DViewerPresent);
//};
//#endif /* OLDROUTINENAMES */
//enum {
{$EXTERNALSYM gestaltQuickdrawVersion}
gestaltQuickdrawVersion = $71642020; //'qd ', /* quickdraw version */
{$EXTERNALSYM gestaltOriginalQD}
gestaltOriginalQD = $0000; //* original 1-bit QD */
{$EXTERNALSYM gestalt8BitQD}
gestalt8BitQD = $0100; //* 8-bit color QD */
{$EXTERNALSYM gestalt32BitQD}
gestalt32BitQD = $0200; //* 32-bit color QD */
{$EXTERNALSYM gestalt32BitQD11}
gestalt32BitQD11 = $0201; //* 32-bit color QDv1.1 */
{$EXTERNALSYM gestalt32BitQD12}
gestalt32BitQD12 = $0220; //* 32-bit color QDv1.2 */
{$EXTERNALSYM gestalt32BitQD13}
gestalt32BitQD13 = $0230; //* 32-bit color QDv1.3 */
{$EXTERNALSYM gestaltAllegroQD}
gestaltAllegroQD = $0250; //* Allegro QD OS 8.5 */
{$EXTERNALSYM gestaltMacOSXQD}
gestaltMacOSXQD = $0300; //* 0x310, 0x320 etc. for 10.x.y */
//};
//enum {
{$EXTERNALSYM gestaltQD3D}
gestaltQD3D = $71643364; //'qd3d', /* Quickdraw 3D attributes*/
{$EXTERNALSYM gestaltQD3DPresent}
gestaltQD3DPresent = 0; //* bit 0 set if QD3D available*/
//};
//#if OLDROUTINENAMES
//enum {
{$EXTERNALSYM gestaltQD3DNotPresent}
gestaltQD3DNotPresent = (0 shl gestaltQD3DPresent);
{$EXTERNALSYM gestaltQD3DAvailable}
gestaltQD3DAvailable = (1 shl gestaltQD3DPresent);
//};
//#endif /* OLDROUTINENAMES */
//enum {
{$EXTERNALSYM gestaltGXVersion}
gestaltGXVersion = $71646778; //'qdgx' /* Overall QuickDraw GX Version*/
//};
//enum {
{$EXTERNALSYM gestaltQuickdrawFeatures}
gestaltQuickdrawFeatures = $71647277;//'qdrw', /* quickdraw features */
{$EXTERNALSYM gestaltHasColor}
gestaltHasColor = 0; //* color quickdraw present */
{$EXTERNALSYM gestaltHasDeepGWorlds}
gestaltHasDeepGWorlds = 1; //* GWorlds can be deeper than 1-bit */
{$EXTERNALSYM gestaltHasDirectPixMaps}
gestaltHasDirectPixMaps = 2; //* PixMaps can be direct (16 or 32 bit) */
{$EXTERNALSYM gestaltHasGrayishTextOr}
gestaltHasGrayishTextOr = 3; //* supports text mode grayishTextOr */
{$EXTERNALSYM gestaltSupportsMirroring}
gestaltSupportsMirroring = 4; //* Supports video mirroring via the Display Manager. */
{$EXTERNALSYM gestaltQDHasLongRowBytes}
gestaltQDHasLongRowBytes = 5; //* Long rowBytes supported in GWorlds */
//};
//enum {
{$EXTERNALSYM gestaltQDTextVersion}
gestaltQDTextVersion = $71647478;//'qdtx', /* QuickdrawText version */
{$EXTERNALSYM gestaltOriginalQDText}
gestaltOriginalQDText = $0000; //* up to and including 8.1 */
{$EXTERNALSYM gestaltAllegroQDText}
gestaltAllegroQDText = $0100; //* starting with 8.5 */
{$EXTERNALSYM gestaltMacOSXQDText}
gestaltMacOSXQDText = $0200; //* we are in Mac OS X */
//};
//enum {
{$EXTERNALSYM gestaltQDTextFeatures}
gestaltQDTextFeatures = $71647466; //'qdtf', /* QuickdrawText features */
{$EXTERNALSYM gestaltWSIISupport}
gestaltWSIISupport = 0; //* bit 0: WSII support included */
{$EXTERNALSYM gestaltSbitFontSupport}
gestaltSbitFontSupport = 1; //* sbit-only fonts supported */
{$EXTERNALSYM gestaltAntiAliasedTextAvailable}
gestaltAntiAliasedTextAvailable = 2; //* capable of antialiased text */
{$EXTERNALSYM gestaltOFA2available}
gestaltOFA2available = 3; //* OFA2 available */
{$EXTERNALSYM gestaltCreatesAliasFontRsrc}
gestaltCreatesAliasFontRsrc = 4; //* "real" datafork font support */
{$EXTERNALSYM gestaltNativeType1FontSupport}
gestaltNativeType1FontSupport = 5; //* we have scaler for Type1 fonts */
{$EXTERNALSYM gestaltCanUseCGTextRendering}
gestaltCanUseCGTextRendering = 6;
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeConferencingInfo}
gestaltQuickTimeConferencingInfo = $71746369;//'qtci' /* returns pointer to QuickTime Conferencing information */
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeVersion}
gestaltQuickTimeVersion = $7174696d; //'qtim', /* returns version of QuickTime */
{$EXTERNALSYM gestaltQuickTime}
gestaltQuickTime = $7174696d; //'qtim' /* gestaltQuickTime is old name for gestaltQuickTimeVersion */
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeFeatures}
gestaltQuickTimeFeatures = $71747273;// 'qtrs',
{$EXTERNALSYM gestaltPPCQuickTimeLibPresent}
gestaltPPCQuickTimeLibPresent = 0; //* PowerPC QuickTime glue library is present */
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeStreamingFeatures}
gestaltQuickTimeStreamingFeatures = $71747366; // 'qtsf'
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeStreamingVersion}
gestaltQuickTimeStreamingVersion = $71747374; // 'qtst'
//};
//enum {
{$EXTERNALSYM gestaltQuickTimeThreadSafeFeaturesAttr}
gestaltQuickTimeThreadSafeFeaturesAttr = $71747468;//'qtth', /* Quicktime thread safety attributes */
{$EXTERNALSYM gestaltQuickTimeThreadSafeICM}
gestaltQuickTimeThreadSafeICM = 0;
{$EXTERNALSYM gestaltQuickTimeThreadSafeMovieToolbox}
gestaltQuickTimeThreadSafeMovieToolbox = 1;
{$EXTERNALSYM gestaltQuickTimeThreadSafeMovieImport}
gestaltQuickTimeThreadSafeMovieImport = 2;
{$EXTERNALSYM gestaltQuickTimeThreadSafeMovieExport}
gestaltQuickTimeThreadSafeMovieExport = 3;
{$EXTERNALSYM gestaltQuickTimeThreadSafeGraphicsImport}
gestaltQuickTimeThreadSafeGraphicsImport = 4;
{$EXTERNALSYM gestaltQuickTimeThreadSafeGraphicsExport}
gestaltQuickTimeThreadSafeGraphicsExport = 5;
{$EXTERNALSYM gestaltQuickTimeThreadSafeMoviePlayback}
gestaltQuickTimeThreadSafeMoviePlayback = 6;
//};
//enum {
{$EXTERNALSYM gestaltQTVRMgrAttr}
gestaltQTVRMgrAttr = $71747672; //'qtvr', /* QuickTime VR attributes */
{$EXTERNALSYM gestaltQTVRMgrPresent}
gestaltQTVRMgrPresent = 0; //* QTVR API is present */
{$EXTERNALSYM gestaltQTVRObjMoviesPresent}
gestaltQTVRObjMoviesPresent = 1; //* QTVR runtime knows about object movies */
{$EXTERNALSYM gestaltQTVRCylinderPanosPresent}
gestaltQTVRCylinderPanosPresent = 2; //* QTVR runtime knows about cylindrical panoramic movies */
{$EXTERNALSYM gestaltQTVRCubicPanosPresent}
gestaltQTVRCubicPanosPresent = 3; //* QTVR runtime knows about cubic panoramic movies */
//};
//enum {
{$EXTERNALSYM gestaltQTVRMgrVers}
gestaltQTVRMgrVers = $71747676; //'qtvv' /* QuickTime VR version */
//};
{*
Because some PowerPC machines now support very large physical memory capacities, including
some above the maximum value which can held in a 32 bit quantity, there is now a new selector,
gestaltPhysicalRAMSizeInMegabytes, which returns the size of physical memory scaled
in megabytes. It is recommended that code transition to using this new selector if
it wants to get a useful value for the amount of physical memory on the system. Code can
also use the sysctl() and sysctlbyname() BSD calls to get these kinds of values.
For compatability with code which assumed that the value in returned by the
gestaltPhysicalRAMSize selector would be a signed quantity of bytes, this selector will
now return 2 gigabytes-1 ( INT_MAX ) if the system has 2 gigabytes of physical memory or more.
*}
//enum {
{$EXTERNALSYM gestaltPhysicalRAMSize}
gestaltPhysicalRAMSize = $72616d20; //'ram ' /* physical RAM size, in bytes */
//};
//enum {
{$EXTERNALSYM gestaltPhysicalRAMSizeInMegabytes}
gestaltPhysicalRAMSizeInMegabytes = $72616d6d; // 'ramm' /* physical RAM size, scaled in megabytes */
//};
//enum {
{$EXTERNALSYM gestaltRBVAddr}
gestaltRBVAddr = $72627620; // 'rbv ' /* RBV base address */
//};
//enum {
{$EXTERNALSYM gestaltROMSize}
gestaltROMSize = $726f6d20; //'rom ' /* rom size */
//};
//enum {
// gestaltROMVersion = 'romv' /* rom version */
{$EXTERNALSYM gestaltROMVersion}
gestaltROMVersion = $726f6d76;
//};
//enum {
{$EXTERNALSYM gestaltResourceMgrAttr}
gestaltResourceMgrAttr = $72737263;// 'rsrc', /* Resource Mgr attributes */
{$EXTERNALSYM gestaltPartialRsrcs}
gestaltPartialRsrcs = 0; //* True if partial resources exist */
{$EXTERNALSYM gestaltHasResourceOverrides}
gestaltHasResourceOverrides = 1; //* Appears in the ROM; so put it here. */
//};
//enum {
{$EXTERNALSYM gestaltResourceMgrBugFixesAttrs}
gestaltResourceMgrBugFixesAttrs = $726d6267; //'rmbg', /* Resource Mgr bug fixes */
{$EXTERNALSYM gestaltRMForceSysHeapRolledIn}
gestaltRMForceSysHeapRolledIn = 0;
{$EXTERNALSYM gestaltRMFakeAppleMenuItemsRolledIn}
gestaltRMFakeAppleMenuItemsRolledIn = 1;
{$EXTERNALSYM gestaltSanityCheckResourceFiles}
gestaltSanityCheckResourceFiles = 2; //* Resource manager does sanity checking on resource files before opening them */
{$EXTERNALSYM gestaltSupportsFSpResourceFileAlreadyOpenBit}
gestaltSupportsFSpResourceFileAlreadyOpenBit = 3; //* The resource manager supports GetResFileRefNum and FSpGetResFileRefNum and FSpResourceFileAlreadyOpen */
{$EXTERNALSYM gestaltRMSupportsFSCalls}
gestaltRMSupportsFSCalls = 4; //* The resource manager supports OpenResFileFSRef, CreateResFileFSRef and ResourceFileAlreadyOpenFSRef */
{$EXTERNALSYM gestaltRMTypeIndexOrderingReverse}
gestaltRMTypeIndexOrderingReverse = 8; //* GetIndType() calls return resource types in opposite order to original 68k resource manager */
//};
//enum {
{$EXTERNALSYM gestaltRealtimeMgrAttr}
gestaltRealtimeMgrAttr = $72746d72;//'rtmr', /* Realtime manager attributes */
{$EXTERNALSYM gestaltRealtimeMgrPresent}
gestaltRealtimeMgrPresent = 0; //* true if the Realtime manager is present */
//};
//enum {
{$EXTERNALSYM gestaltSafeOFAttr}
gestaltSafeOFAttr = $73616665;//'safe',
{$EXTERNALSYM gestaltVMZerosPagesBit}
gestaltVMZerosPagesBit = 0;
{$EXTERNALSYM gestaltInitHeapZerosOutHeapsBit}
gestaltInitHeapZerosOutHeapsBit = 1;
{$EXTERNALSYM gestaltNewHandleReturnsZeroedMemoryBit}
gestaltNewHandleReturnsZeroedMemoryBit = 2;
{$EXTERNALSYM gestaltNewPtrReturnsZeroedMemoryBit}
gestaltNewPtrReturnsZeroedMemoryBit = 3;
{$EXTERNALSYM gestaltFileAllocationZeroedBlocksBit}
gestaltFileAllocationZeroedBlocksBit = 4;
//};
//enum {
{$EXTERNALSYM gestaltSCCReadAddr}
gestaltSCCReadAddr = $73636372; //'sccr' /* scc read base address */
//};
//enum {
{$EXTERNALSYM gestaltSCCWriteAddr}
gestaltSCCWriteAddr = $73636377; //'sccw' /* scc read base address */
//};
//enum {
{$EXTERNALSYM gestaltScrapMgrAttr}
gestaltScrapMgrAttr = $73637261;//'scra', /* Scrap Manager attributes */
{$EXTERNALSYM gestaltScrapMgrTranslationAware}
gestaltScrapMgrTranslationAware = 0; //* True if scrap manager is translation aware */
//};
//enum {
{$EXTERNALSYM gestaltScriptMgrVersion}
gestaltScriptMgrVersion = $73637269;// 'scri' /* Script Manager version number */
//};
//enum {
{$EXTERNALSYM gestaltScriptCount}
gestaltScriptCount = $73637223;// 'scr#' /* number of active script systems */
//};
//enum {
{$EXTERNALSYM gestaltSCSI}
gestaltSCSI = $73637369;//'scsi', /* SCSI Manager attributes */
{$EXTERNALSYM gestaltAsyncSCSI}
gestaltAsyncSCSI = 0; //* Supports Asynchronous SCSI */
{$EXTERNALSYM gestaltAsyncSCSIINROM}
gestaltAsyncSCSIINROM = 1; //* Async scsi is in ROM (available for booting) */
{$EXTERNALSYM gestaltSCSISlotBoot}
gestaltSCSISlotBoot = 2; //* ROM supports Slot-style PRAM for SCSI boots (PDM and later) */
{$EXTERNALSYM gestaltSCSIPollSIH}
gestaltSCSIPollSIH = 3; //* SCSI Manager will poll for interrupts if Secondary Interrupts are busy. */
//};
//enum {
{$EXTERNALSYM gestaltControlStripAttr}
gestaltControlStripAttr = $73646576;//'sdev', /* Control Strip attributes */
{$EXTERNALSYM gestaltControlStripExists}
gestaltControlStripExists = 0; //* Control Strip is installed */
{$EXTERNALSYM gestaltControlStripVersionFixed}
gestaltControlStripVersionFixed = 1; //* Control Strip version Gestalt selector was fixed */
{$EXTERNALSYM gestaltControlStripUserFont}
gestaltControlStripUserFont = 2; //* supports user-selectable font/size */
{$EXTERNALSYM gestaltControlStripUserHotKey}
gestaltControlStripUserHotKey = 3; //* support user-selectable hot key to show/hide the window */
//};
//enum {
{$EXTERNALSYM gestaltSDPStandardDirectoryVersion}
gestaltSDPStandardDirectoryVersion = $73647672;//'sdvr' /* OCE Standard Directory Panel*/
//};
//enum {
{$EXTERNALSYM gestaltSerialAttr}
gestaltSerialAttr = $73657220; //'ser ', /* Serial attributes */
{$EXTERNALSYM gestaltHasGPIaToDCDa}
gestaltHasGPIaToDCDa = 0; //* GPIa connected to DCDa*/
{$EXTERNALSYM gestaltHasGPIaToRTxCa}
gestaltHasGPIaToRTxCa = 1; //* GPIa connected to RTxCa clock input*/
{$EXTERNALSYM gestaltHasGPIbToDCDb}
gestaltHasGPIbToDCDb = 2; //* GPIb connected to DCDb */
{$EXTERNALSYM gestaltHidePortA}
gestaltHidePortA = 3; //* Modem port (A) should be hidden from users */
{$EXTERNALSYM gestaltHidePortB}
gestaltHidePortB = 4; //* Printer port (B) should be hidden from users */
{$EXTERNALSYM gestaltPortADisabled}
gestaltPortADisabled = 5; //* Modem port (A) disabled and should not be used by SW */
{$EXTERNALSYM gestaltPortBDisabled}
gestaltPortBDisabled = 6; //* Printer port (B) disabled and should not be used by SW */
//};
//enum {
{$EXTERNALSYM gestaltShutdownAttributes}
gestaltShutdownAttributes = $73687574; //'shut', /* ShutDown Manager Attributes */
{$EXTERNALSYM gestaltShutdownHassdOnBootVolUnmount}
gestaltShutdownHassdOnBootVolUnmount = 0; //* True if ShutDown Manager unmounts boot & VM volume at shutdown time. */
//};
//enum {
{$EXTERNALSYM gestaltNuBusConnectors}
gestaltNuBusConnectors = $736c7463; //'sltc' /* bitmap of NuBus connectors*/
//};
//enum {
{$EXTERNALSYM gestaltSlotAttr}
gestaltSlotAttr = $736c6f74; //'slot', /* slot attributes */
{$EXTERNALSYM gestaltSlotMgrExists}
gestaltSlotMgrExists = 0; //* true is slot mgr exists */
{$EXTERNALSYM gestaltNuBusPresent}
gestaltNuBusPresent = 1; //* NuBus slots are present */
{$EXTERNALSYM gestaltSESlotPresent}
gestaltSESlotPresent = 2; //* SE PDS slot present */
{$EXTERNALSYM gestaltSE30SlotPresent}
gestaltSE30SlotPresent = 3; //* SE/30 slot present */
{$EXTERNALSYM gestaltPortableSlotPresent}
gestaltPortableSlotPresent = 4; //* Portable’s slot present */
//};
//enum {
// gestaltFirstSlotNumber = 'slt1' /* returns first physical slot */
{$EXTERNALSYM gestaltFirstSlotNumber}
gestaltFirstSlotNumber = $736c7431;
//};
//enum {
{$EXTERNALSYM gestaltSoundAttr}
gestaltSoundAttr = $736e6420; //'snd ', /* sound attributes */
{$EXTERNALSYM gestaltStereoCapability}
gestaltStereoCapability = 0; //* sound hardware has stereo capability */
{$EXTERNALSYM gestaltStereoMixing}
gestaltStereoMixing = 1; //* stereo mixing on external speaker */
{$EXTERNALSYM gestaltSoundIOMgrPresent}
gestaltSoundIOMgrPresent = 3; //* The Sound I/O Manager is present */
{$EXTERNALSYM gestaltBuiltInSoundInput}
gestaltBuiltInSoundInput = 4; //* built-in Sound Input hardware is present */
{$EXTERNALSYM gestaltHasSoundInputDevice}
gestaltHasSoundInputDevice = 5; //* Sound Input device available */
{$EXTERNALSYM gestaltPlayAndRecord}
gestaltPlayAndRecord = 6; //* built-in hardware can play and record simultaneously */
{$EXTERNALSYM gestalt16BitSoundIO}
gestalt16BitSoundIO = 7; //* sound hardware can play and record 16-bit samples */
{$EXTERNALSYM gestaltStereoInput}
gestaltStereoInput = 8; //* sound hardware can record stereo */
{$EXTERNALSYM gestaltLineLevelInput}
gestaltLineLevelInput = 9; //* sound input port requires line level */
//* the following bits are not defined prior to Sound Mgr 3.0 */
{$EXTERNALSYM gestaltSndPlayDoubleBuffer}
gestaltSndPlayDoubleBuffer = 10; //* SndPlayDoubleBuffer available, set by Sound Mgr 3.0 and later */
{$EXTERNALSYM gestaltMultiChannels}
gestaltMultiChannels = 11; //* multiple channel support, set by Sound Mgr 3.0 and later */
{$EXTERNALSYM gestalt16BitAudioSupport}
gestalt16BitAudioSupport = 12; //* 16 bit audio data supported, set by Sound Mgr 3.0 and later */
//};
//enum {
{$EXTERNALSYM gestaltSplitOSAttr}
gestaltSplitOSAttr = $73706f73;// 'spos',
{$EXTERNALSYM gestaltSplitOSBootDriveIsNetworkVolume}
gestaltSplitOSBootDriveIsNetworkVolume = 0; //* the boot disk is a network 'disk', from the .LANDisk drive. */
{$EXTERNALSYM gestaltSplitOSAware}
gestaltSplitOSAware = 1; //* the system includes the code to deal with a split os situation. */
{$EXTERNALSYM gestaltSplitOSEnablerVolumeIsDifferentFromBootVolume}
gestaltSplitOSEnablerVolumeIsDifferentFromBootVolume = 2; //* the active enabler is on a different volume than the system file. */
{$EXTERNALSYM gestaltSplitOSMachineNameSetToNetworkNameTemp}
gestaltSplitOSMachineNameSetToNetworkNameTemp = 3; //* The machine name was set to the value given us from the BootP server */
{$EXTERNALSYM gestaltSplitOSMachineNameStartupDiskIsNonPersistent}
gestaltSplitOSMachineNameStartupDiskIsNonPersistent = 5; //* The startup disk ( vRefNum == -1 ) is non-persistent, meaning changes won't persist across a restart. */
//};
//enum {
{$EXTERNALSYM gestaltSMPSPSendLetterVersion}
gestaltSMPSPSendLetterVersion = $7370736c;// 'spsl' /* OCE StandardMail*/
//};
//enum {
{$EXTERNALSYM gestaltSpeechRecognitionAttr}
gestaltSpeechRecognitionAttr = $73727461; //'srta', /* speech recognition attributes */
{$EXTERNALSYM gestaltDesktopSpeechRecognition}
gestaltDesktopSpeechRecognition = 1; //* recognition thru the desktop microphone is available */
{$EXTERNALSYM gestaltTelephoneSpeechRecognition}
gestaltTelephoneSpeechRecognition = 2; //* recognition thru the telephone is available */
//};
//enum {
{$EXTERNALSYM gestaltSpeechRecognitionVersion}
gestaltSpeechRecognitionVersion = $73727462;//'srtb' /* speech recognition version (0x0150 is the first version that fully supports the API) */
//};
//enum {
{$EXTERNALSYM gestaltSoftwareVendorCode}
gestaltSoftwareVendorCode = $73726164; //'srad', /* Returns system software vendor information */
{$EXTERNALSYM gestaltSoftwareVendorApple}
gestaltSoftwareVendorApple = $4170706c; //'Appl', /* System software sold by Apple */
// gestaltSoftwareVendorLicensee = 'Lcns' /* System software sold by licensee */
{$EXTERNALSYM gestaltSoftwareVendorLicensee}
gestaltSoftwareVendorLicensee = $4c636e73;
//};
//enum {
{$EXTERNALSYM gestaltSysArchitecture}
gestaltSysArchitecture = $73797361;//'sysa', /* Native System Architecture */
{$EXTERNALSYM gestalt68k}
gestalt68k = 1; //* Motorola MC68k architecture */
{$EXTERNALSYM gestaltPowerPC}
gestaltPowerPC = 2; //* IBM PowerPC architecture */
{$EXTERNALSYM gestaltIntel}
gestaltIntel = 10; //* Intel x86 architecture */
//};
//enum {
{$EXTERNALSYM gestaltSystemUpdateVersion}
gestaltSystemUpdateVersion = $73797375; //'sysu' /* System Update version */
//};
//enum {
{$EXTERNALSYM gestaltSystemVersion}
gestaltSystemVersion = $73797376; //'sysv', /* system version*/
{$EXTERNALSYM gestaltSystemVersionMajor}
gestaltSystemVersionMajor = $73797331; //'sys1', /* The major system version number; in 10.4.17 this would be the decimal value 10 */
{$EXTERNALSYM gestaltSystemVersionMinor}
gestaltSystemVersionMinor = $73797332; //'sys2', /* The minor system version number; in 10.4.17 this would be the decimal value 4 */
{$EXTERNALSYM gestaltSystemVersionBugFix}
gestaltSystemVersionBugFix = $73797333; //'sys3' /* The bug fix system version number; in 10.4.17 this would be the decimal value 17 */
//};
//enum {
{$EXTERNALSYM gestaltToolboxTable}
gestaltToolboxTable = $74627474; //'tbtt' /* OS trap table base */
//};
//enum {
{$EXTERNALSYM gestaltTextEditVersion}
gestaltTextEditVersion = $74652020; //'te ', /* TextEdit version number */
{$EXTERNALSYM gestaltTE1}
gestaltTE1 = 1; //* TextEdit in MacIIci ROM */
{$EXTERNALSYM gestaltTE2}
gestaltTE2 = 2; //* TextEdit with 6.0.4 Script Systems on MacIIci (Script bug fixes for MacIIci) */
{$EXTERNALSYM gestaltTE3}
gestaltTE3 = 3; //* TextEdit with 6.0.4 Script Systems all but MacIIci */
{$EXTERNALSYM gestaltTE4}
gestaltTE4 = 4; //* TextEdit in System 7.0 */
{$EXTERNALSYM gestaltTE5}
gestaltTE5 = 5; //* TextWidthHook available in TextEdit */
//};
//enum {
{$EXTERNALSYM gestaltTE6}
gestaltTE6 = 6; //* TextEdit with integrated TSMTE and improved UI */
//};
//enum {
{$EXTERNALSYM gestaltTEAttr}
gestaltTEAttr = $74656174; //'teat'; /* TextEdit attributes */
{$EXTERNALSYM gestaltTEHasGetHiliteRgn}
gestaltTEHasGetHiliteRgn = 0; //* TextEdit has TEGetHiliteRgn */
{$EXTERNALSYM gestaltTESupportsInlineInput}
gestaltTESupportsInlineInput = 1; //* TextEdit does Inline Input */
{$EXTERNALSYM gestaltTESupportsTextObjects}
gestaltTESupportsTextObjects = 2; //* TextEdit does Text Objects */
{$EXTERNALSYM gestaltTEHasWhiteBackground}
gestaltTEHasWhiteBackground = 3; //* TextEdit supports overriding the TERec's background to white */
//};
//enum {
{$EXTERNALSYM gestaltTeleMgrAttr}
gestaltTeleMgrAttr = $74656c65; //'tele', /* Telephone manager attributes */
{$EXTERNALSYM gestaltTeleMgrPresent}
gestaltTeleMgrPresent = 0;
{$EXTERNALSYM gestaltTeleMgrPowerPCSupport}
gestaltTeleMgrPowerPCSupport = 1;
{$EXTERNALSYM gestaltTeleMgrSoundStreams}
gestaltTeleMgrSoundStreams = 2;
{$EXTERNALSYM gestaltTeleMgrAutoAnswer}
gestaltTeleMgrAutoAnswer = 3;
{$EXTERNALSYM gestaltTeleMgrIndHandset}
gestaltTeleMgrIndHandset = 4;
{$EXTERNALSYM gestaltTeleMgrSilenceDetect}
gestaltTeleMgrSilenceDetect = 5;
{$EXTERNALSYM gestaltTeleMgrNewTELNewSupport}
gestaltTeleMgrNewTELNewSupport = 6;
//};
//enum {
{$EXTERNALSYM gestaltTermMgrAttr}
gestaltTermMgrAttr = $7465726d; //'term', /* terminal mgr attributes */
{$EXTERNALSYM gestaltTermMgrPresent}
gestaltTermMgrPresent = 0;
{$EXTERNALSYM gestaltTermMgrErrorString}
gestaltTermMgrErrorString = 2;
//};
//enum {
{$EXTERNALSYM gestaltThreadMgrAttr}
gestaltThreadMgrAttr = $74686473; //'thds', /* Thread Manager attributes */
{$EXTERNALSYM gestaltThreadMgrPresent}
gestaltThreadMgrPresent = 0; //* bit true if Thread Mgr is present */
{$EXTERNALSYM gestaltSpecificMatchSupport}
gestaltSpecificMatchSupport = 1; //* bit true if Thread Mgr supports exact match creation option */
{$EXTERNALSYM gestaltThreadsLibraryPresent}
gestaltThreadsLibraryPresent = 2; //* bit true if Thread Mgr shared library is present */
//};
//enum {
{$EXTERNALSYM gestaltTimeMgrVersion}
gestaltTimeMgrVersion = $746d6772; //'tmgr', /* time mgr version */
{$EXTERNALSYM gestaltStandardTimeMgr}
gestaltStandardTimeMgr = 1; //* standard time mgr is present */
{$EXTERNALSYM gestaltRevisedTimeMgr}
gestaltRevisedTimeMgr = 2; //* revised time mgr is present */
{$EXTERNALSYM gestaltExtendedTimeMgr}
gestaltExtendedTimeMgr = 3; //* extended time mgr is present */
{$EXTERNALSYM gestaltNativeTimeMgr}
gestaltNativeTimeMgr = 4; //* PowerPC native TimeMgr is present */
//};
//enum {
{$EXTERNALSYM gestaltTSMTEVersion}
gestaltTSMTEVersion = $746d5456; //'tmTV',
{$EXTERNALSYM gestaltTSMTE1}
gestaltTSMTE1 = $0100; //* Original version of TSMTE */
{$EXTERNALSYM gestaltTSMTE15}
gestaltTSMTE15 = $0150; //* System 8.0 */
{$EXTERNALSYM gestaltTSMTE152}
gestaltTSMTE152 = $0152; //* System 8.2 */
//};
//enum {
{$EXTERNALSYM gestaltTSMTEAttr}
gestaltTSMTEAttr = $746d5445; //'tmTE',
{$EXTERNALSYM gestaltTSMTEPresent}
gestaltTSMTEPresent = 0;
{$EXTERNALSYM gestaltTSMTE}
gestaltTSMTE = 0; //* gestaltTSMTE is old name for gestaltTSMTEPresent */
//};
//enum {
{$EXTERNALSYM gestaltAVLTreeAttr}
gestaltAVLTreeAttr = $74726565; //'tree', /* AVLTree utility routines attributes. */
{$EXTERNALSYM gestaltAVLTreePresentBit}
gestaltAVLTreePresentBit = 0; //* if set, then the AVL Tree routines are available. */
{$EXTERNALSYM gestaltAVLTreeSupportsHandleBasedTreeBit}
gestaltAVLTreeSupportsHandleBasedTreeBit = 1; //* if set, then the AVL Tree routines can store tree data in a single handle */
{$EXTERNALSYM gestaltAVLTreeSupportsTreeLockingBit}
gestaltAVLTreeSupportsTreeLockingBit = 2; //* if set, the AVLLockTree() and AVLUnlockTree() routines are available. */
//};
//enum {
{$EXTERNALSYM gestaltALMAttr}
gestaltALMAttr = $74726970; //'trip', /* Settings Manager attributes (see also gestaltALMVers) */
{$EXTERNALSYM gestaltALMPresent}
gestaltALMPresent = 0; //* bit true if ALM is available */
{$EXTERNALSYM gestaltALMHasSFGroup}
gestaltALMHasSFGroup = 1; //* bit true if Put/Get/Merge Group calls are implmented */
{$EXTERNALSYM gestaltALMHasCFMSupport}
gestaltALMHasCFMSupport = 2; //* bit true if CFM-based modules are supported */
{$EXTERNALSYM gestaltALMHasRescanNotifiers}
gestaltALMHasRescanNotifiers = 3; //* bit true if Rescan notifications/events will be sent to clients */
//};
//enum {
{$EXTERNALSYM gestaltALMHasSFLocation}
gestaltALMHasSFLocation = gestaltALMHasSFGroup;
//};
//enum {
{$EXTERNALSYM gestaltTSMgrVersion}
gestaltTSMgrVersion = $74736d76; //'tsmv', /* Text Services Mgr version, if present */
{$EXTERNALSYM gestaltTSMgr15}
gestaltTSMgr15 = $0150;
{$EXTERNALSYM gestaltTSMgr20}
gestaltTSMgr20 = $0200; //* Version 2.0 as of MacOSX 10.0 */
{$EXTERNALSYM gestaltTSMgr22}
gestaltTSMgr22 = $0220; //* Version 2.2 as of MacOSX 10.3 */
{$EXTERNALSYM gestaltTSMgr23}
gestaltTSMgr23 = $0230; //* Version 2.3 as of MacOSX 10.4 */
//};
//enum {
{$EXTERNALSYM gestaltTSMgrAttr}
gestaltTSMgrAttr = $74736d61; //'tsma', /* Text Services Mgr attributes, if present */
{$EXTERNALSYM gestaltTSMDisplayMgrAwareBit}
gestaltTSMDisplayMgrAwareBit = 0; //* TSM knows about display manager */
{$EXTERNALSYM gestaltTSMdoesTSMTEBit}
gestaltTSMdoesTSMTEBit = 1; //* TSM has integrated TSMTE */
//};
//enum {
{$EXTERNALSYM gestaltSpeechAttr}
gestaltSpeechAttr = $74747363; //'ttsc', /* Speech Manager attributes */
{$EXTERNALSYM gestaltSpeechMgrPresent}
gestaltSpeechMgrPresent = 0; //* bit set indicates that Speech Manager exists */
{$EXTERNALSYM gestaltSpeechHasPPCGlue}
gestaltSpeechHasPPCGlue = 1; //* bit set indicates that native PPC glue for Speech Manager API exists */
//};
//enum {
{$EXTERNALSYM gestaltTVAttr}
gestaltTVAttr = $74762020; //'tv ', /* TV version */
{$EXTERNALSYM gestaltHasTVTuner}
gestaltHasTVTuner = 0; //* supports Philips FL1236F video tuner */
{$EXTERNALSYM gestaltHasSoundFader}
gestaltHasSoundFader = 1; //* supports Philips TEA6330 Sound Fader chip */
{$EXTERNALSYM gestaltHasHWClosedCaptioning}
gestaltHasHWClosedCaptioning = 2; //* supports Philips SAA5252 Closed Captioning */
{$EXTERNALSYM gestaltHasIRRemote}
gestaltHasIRRemote = 3; //* supports CyclopsII Infra Red Remote control */
{$EXTERNALSYM gestaltHasVidDecoderScaler}
gestaltHasVidDecoderScaler = 4; //* supports Philips SAA7194 Video Decoder/Scaler */
{$EXTERNALSYM gestaltHasStereoDecoder}
gestaltHasStereoDecoder = 5; //* supports Sony SBX1637A-01 stereo decoder */
{$EXTERNALSYM gestaltHasSerialFader}
gestaltHasSerialFader = 6; //* has fader audio in serial with system audio */
{$EXTERNALSYM gestaltHasFMTuner}
gestaltHasFMTuner = 7; //* has FM Tuner from donnybrook card */
{$EXTERNALSYM gestaltHasSystemIRFunction}
gestaltHasSystemIRFunction = 8; //* Infra Red button function is set up by system and not by Video Startup */
{$EXTERNALSYM gestaltIRDisabled}
gestaltIRDisabled = 9; //* Infra Red remote is not disabled. */
{$EXTERNALSYM gestaltINeedIRPowerOffConfirm}
gestaltINeedIRPowerOffConfirm = 10; //* Need IR power off confirm dialog. */
{$EXTERNALSYM gestaltHasZoomedVideo}
gestaltHasZoomedVideo = 11; //* Has Zoomed Video PC Card video input. */
//};
//enum {
{$EXTERNALSYM gestaltATSUVersion}
gestaltATSUVersion = $75697376; //'uisv',
{$EXTERNALSYM gestaltOriginalATSUVersion}
gestaltOriginalATSUVersion = (1 shl 16); //* ATSUI version 1.0 */
{$EXTERNALSYM gestaltATSUUpdate1}
gestaltATSUUpdate1 = (2 shl 16); //* ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSUUpdate2}
gestaltATSUUpdate2 = (3 shl 16); //* ATSUI version 1.2 */
{$EXTERNALSYM gestaltATSUUpdate3}
gestaltATSUUpdate3 = (4 shl 16); //* ATSUI version 2.0 */
{$EXTERNALSYM gestaltATSUUpdate4}
gestaltATSUUpdate4 = (5 shl 16); //* ATSUI version in Mac OS X - SoftwareUpdate 1-4 for Mac OS 10.0.1 - 10.0.4 */
{$EXTERNALSYM gestaltATSUUpdate5}
gestaltATSUUpdate5 = (6 shl 16); //* ATSUI version 2.3 in MacOS 10.1 */
{$EXTERNALSYM gestaltATSUUpdate6}
gestaltATSUUpdate6 = (7 shl 16); //* ATSUI version 2.4 in MacOS 10.2 */
{$EXTERNALSYM gestaltATSUUpdate7}
gestaltATSUUpdate7 = (8 shl 16); //* ATSUI version 2.5 in MacOS 10.3 */
//};
//enum {
{$EXTERNALSYM gestaltATSUFeatures}
gestaltATSUFeatures = $75697366; //'uisf',
{$EXTERNALSYM gestaltATSUTrackingFeature}
gestaltATSUTrackingFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSUMemoryFeature}
gestaltATSUMemoryFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSUFallbacksFeature}
gestaltATSUFallbacksFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSUGlyphBoundsFeature}
gestaltATSUGlyphBoundsFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSULineControlFeature}
gestaltATSULineControlFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSULayoutCreateAndCopyFeature}
gestaltATSULayoutCreateAndCopyFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSULayoutCacheClearFeature}
gestaltATSULayoutCacheClearFeature = $00000001; //* feature introduced in ATSUI version 1.1 */
{$EXTERNALSYM gestaltATSUTextLocatorUsageFeature}
gestaltATSUTextLocatorUsageFeature = $00000002; //* feature introduced in ATSUI version 1.2 */
{$EXTERNALSYM gestaltATSULowLevelOrigFeatures}
gestaltATSULowLevelOrigFeatures = $00000004; //* first low-level features introduced in ATSUI version 2.0 */
{$EXTERNALSYM gestaltATSUFallbacksObjFeatures}
gestaltATSUFallbacksObjFeatures = $00000008; //* feature introduced - ATSUFontFallbacks objects introduced in ATSUI version 2.3 */
{$EXTERNALSYM gestaltATSUIgnoreLeadingFeature}
gestaltATSUIgnoreLeadingFeature = $00000008; //* feature introduced - kATSLineIgnoreFontLeading LineLayoutOption introduced in ATSUI version 2.3 */
{$EXTERNALSYM gestaltATSUByCharacterClusterFeature}
gestaltATSUByCharacterClusterFeature = $00000010; //* ATSUCursorMovementTypes introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUAscentDescentControlsFeature}
gestaltATSUAscentDescentControlsFeature = $00000010; //* attributes introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUHighlightInactiveTextFeature}
gestaltATSUHighlightInactiveTextFeature = $00000010; //* feature introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUPositionToCursorFeature}
gestaltATSUPositionToCursorFeature = $00000010; //* features introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUBatchBreakLinesFeature}
gestaltATSUBatchBreakLinesFeature = $00000010; //* feature introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUTabSupportFeature}
gestaltATSUTabSupportFeature = $00000010; //* features introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUDirectAccess}
gestaltATSUDirectAccess = $00000010; //* features introduced in ATSUI version 2.4 */
{$EXTERNALSYM gestaltATSUDecimalTabFeature}
gestaltATSUDecimalTabFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
{$EXTERNALSYM gestaltATSUBiDiCursorPositionFeature}
gestaltATSUBiDiCursorPositionFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
{$EXTERNALSYM gestaltATSUNearestCharLineBreakFeature}
gestaltATSUNearestCharLineBreakFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
{$EXTERNALSYM gestaltATSUHighlightColorControlFeature}
gestaltATSUHighlightColorControlFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
{$EXTERNALSYM gestaltATSUUnderlineOptionsStyleFeature}
gestaltATSUUnderlineOptionsStyleFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
{$EXTERNALSYM gestaltATSUStrikeThroughStyleFeature}
gestaltATSUStrikeThroughStyleFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
{$EXTERNALSYM gestaltATSUDropShadowStyleFeature}
gestaltATSUDropShadowStyleFeature = $00000020; //* feature introduced in ATSUI version 2.5 */
//};
//enum {
{$EXTERNALSYM gestaltUSBAttr}
gestaltUSBAttr = $75736220; // 'usb ', /* USB Attributes */
{$EXTERNALSYM gestaltUSBPresent}
gestaltUSBPresent = 0; //* USB Support available */
{$EXTERNALSYM gestaltUSBHasIsoch}
gestaltUSBHasIsoch = 1; //* USB Isochronous features available */
//};
//enum {
{$EXTERNALSYM gestaltUSBVersion}
gestaltUSBVersion = $75736276; //'usbv' /* USB version */
//};
//enum {
{$EXTERNALSYM gestaltVersion}
gestaltVersion = $76657273; //'vers', /* gestalt version */
{$EXTERNALSYM gestaltValueImplementedVers}
gestaltValueImplementedVers = 5; //* version of gestalt where gestaltValue is implemented. */
//};
//enum {
{$EXTERNALSYM gestaltVIA1Addr}
gestaltVIA1Addr = $76696131; //'via1' /* via 1 base address */
//};
//enum {
{$EXTERNALSYM gestaltVIA2Addr}
gestaltVIA2Addr = $76696132; //'via2' /* via 2 base address */
//};
//enum {
{$EXTERNALSYM gestaltVMAttr}
gestaltVMAttr = $766d2020; //'vm ', /* virtual memory attributes */
{$EXTERNALSYM gestaltVMPresent}
gestaltVMPresent = 0; //* true if virtual memory is present */
{$EXTERNALSYM gestaltVMHasLockMemoryForOutput}
gestaltVMHasLockMemoryForOutput = 1; //* true if LockMemoryForOutput is available */
{$EXTERNALSYM gestaltVMFilemappingOn}
gestaltVMFilemappingOn = 3; //* true if filemapping is available */
{$EXTERNALSYM gestaltVMHasPagingControl}
gestaltVMHasPagingControl = 4; //* true if MakeMemoryResident, MakeMemoryNonResident, FlushMemory, and ReleaseMemoryData are available */
//};
//enum {
{$EXTERNALSYM gestaltVMInfoType}
gestaltVMInfoType = $766d696e; // 'vmin', /* Indicates how the Finder should display information about VM in */
//* the Finder about box. */
{$EXTERNALSYM gestaltVMInfoSizeStorageType}
gestaltVMInfoSizeStorageType = 0; //* Display VM on/off, backing store size and name */
{$EXTERNALSYM gestaltVMInfoSizeType}
gestaltVMInfoSizeType = 1; //* Display whether VM is on or off and the size of the backing store */
{$EXTERNALSYM gestaltVMInfoSimpleType}
gestaltVMInfoSimpleType = 2; //* Display whether VM is on or off */
{$EXTERNALSYM gestaltVMInfoNoneType}
gestaltVMInfoNoneType = 3; //* Display no VM information */
//};
//enum {
{$EXTERNALSYM gestaltVMBackingStoreFileRefNum}
gestaltVMBackingStoreFileRefNum = $766d6273; //'vmbs'; //* file refNum of virtual memory's main backing store file (returned in low word of result) */
//};
//enum {
{$EXTERNALSYM gestaltALMVers}
gestaltALMVers = $77616c6b; //'walk' /* Settings Manager version (see also gestaltALMAttr) */
//};
//enum {
{$EXTERNALSYM gestaltWindowMgrAttr}
gestaltWindowMgrAttr = $77696e64; //'wind', /* If this Gestalt exists, the Mac OS 8.5 Window Manager is installed*/
{$EXTERNALSYM gestaltWindowMgrPresent}
gestaltWindowMgrPresent = (1 shl 0); //* NOTE: this is a bit mask, whereas all other Gestalt constants of*/
//* this type are bit index values. Universal Interfaces 3.2 slipped*/
//* out the door with this mistake.*/
{$EXTERNALSYM gestaltWindowMgrPresentBit}
gestaltWindowMgrPresentBit = 0; //* bit number*/
{$EXTERNALSYM gestaltExtendedWindowAttributes}
gestaltExtendedWindowAttributes = 1; //* Has ChangeWindowAttributes; GetWindowAttributes works for all windows*/
{$EXTERNALSYM gestaltExtendedWindowAttributesBit}
gestaltExtendedWindowAttributesBit = 1; //* Has ChangeWindowAttributes; GetWindowAttributes works for all windows*/
{$EXTERNALSYM gestaltHasFloatingWindows}
gestaltHasFloatingWindows = 2; //* Floating window APIs work*/
{$EXTERNALSYM gestaltHasFloatingWindowsBit}
gestaltHasFloatingWindowsBit = 2; //* Floating window APIs work*/
{$EXTERNALSYM gestaltHasWindowBuffering}
gestaltHasWindowBuffering = 3; //* This system has buffering available*/
{$EXTERNALSYM gestaltHasWindowBufferingBit}
gestaltHasWindowBufferingBit = 3; //* This system has buffering available*/
{$EXTERNALSYM gestaltWindowLiveResizeBit}
gestaltWindowLiveResizeBit = 4; //* live resizing of windows is available*/
{$EXTERNALSYM gestaltWindowMinimizeToDockBit}
gestaltWindowMinimizeToDockBit = 5; //* windows minimize to the dock and do not windowshade (Mac OS X)*/
{$EXTERNALSYM gestaltHasWindowShadowsBit}
gestaltHasWindowShadowsBit = 6; //* windows have shadows*/
{$EXTERNALSYM gestaltSheetsAreWindowModalBit}
gestaltSheetsAreWindowModalBit = 7; //* sheet windows are modal only to their parent window*/
{$EXTERNALSYM gestaltFrontWindowMayBeHiddenBit}
gestaltFrontWindowMayBeHiddenBit = 8; //* FrontWindow and related APIs will return the front window even when the app is hidden*/
//* masks for the above bits*/
{$EXTERNALSYM gestaltWindowMgrPresentMask}
gestaltWindowMgrPresentMask = (1 shl gestaltWindowMgrPresentBit);
{$EXTERNALSYM gestaltExtendedWindowAttributesMask}
gestaltExtendedWindowAttributesMask = (1 shl gestaltExtendedWindowAttributesBit);
{$EXTERNALSYM gestaltHasFloatingWindowsMask}
gestaltHasFloatingWindowsMask = (1 shl gestaltHasFloatingWindowsBit);
{$EXTERNALSYM gestaltHasWindowBufferingMask}
gestaltHasWindowBufferingMask = (1 shl gestaltHasWindowBufferingBit);
{$EXTERNALSYM gestaltWindowLiveResizeMask}
gestaltWindowLiveResizeMask = (1 shl gestaltWindowLiveResizeBit);
{$EXTERNALSYM gestaltWindowMinimizeToDockMask}
gestaltWindowMinimizeToDockMask = (1 shl gestaltWindowMinimizeToDockBit);
{$EXTERNALSYM gestaltHasWindowShadowsMask}
gestaltHasWindowShadowsMask = (1 shl gestaltHasWindowShadowsBit);
{$EXTERNALSYM gestaltSheetsAreWindowModalMask}
gestaltSheetsAreWindowModalMask = (1 shl gestaltSheetsAreWindowModalBit);
{$EXTERNALSYM gestaltFrontWindowMayBeHiddenMask}
gestaltFrontWindowMayBeHiddenMask = (1 shl gestaltFrontWindowMayBeHiddenBit);
//};
//enum {
{$EXTERNALSYM gestaltHasSingleWindowModeBit}
gestaltHasSingleWindowModeBit = 8; //* This system supports single window mode*/
{$EXTERNALSYM gestaltHasSingleWindowModeMask}
gestaltHasSingleWindowModeMask = (1 shl gestaltHasSingleWindowModeBit);
//};
{* gestaltX86Features is a convenience for 'cpuid' instruction. Note
that even though the processor may support a specific feature, the
OS may not support all of these features. These bitfields
correspond directly to the bits returned by cpuid *}
//enum {
{$EXTERNALSYM gestaltX86Features}
gestaltX86Features = $78383666; //'x86f',
{$EXTERNALSYM gestaltX86HasFPU}
gestaltX86HasFPU = 0; //* has an FPU that supports the 387 instructions*/
{$EXTERNALSYM gestaltX86HasVME}
gestaltX86HasVME = 1; //* supports Virtual-8086 Mode Extensions*/
{$EXTERNALSYM gestaltX86HasDE}
gestaltX86HasDE = 2; //* supports I/O breakpoints (Debug Extensions)*/
{$EXTERNALSYM gestaltX86HasPSE}
gestaltX86HasPSE = 3; //* supports 4-Mbyte pages (Page Size Extension)*/
{$EXTERNALSYM gestaltX86HasTSC}
gestaltX86HasTSC = 4; //* supports RTDSC instruction (Time Stamp Counter)*/
{$EXTERNALSYM gestaltX86HasMSR}
gestaltX86HasMSR = 5; //* supports Model Specific Registers*/
{$EXTERNALSYM gestaltX86HasPAE}
gestaltX86HasPAE = 6; //* supports physical addresses > 32 bits (Physical Address Extension)*/
{$EXTERNALSYM gestaltX86HasMCE}
gestaltX86HasMCE = 7; //* supports Machine Check Exception*/
{$EXTERNALSYM gestaltX86HasCX8}
gestaltX86HasCX8 = 8; //* supports CMPXCHG8 instructions (Compare Exchange 8 bytes)*/
{$EXTERNALSYM gestaltX86HasAPIC}
gestaltX86HasAPIC = 9; //* contains local APIC*/
{$EXTERNALSYM gestaltX86HasSEP}
gestaltX86HasSEP = 11; //* supports fast system call (SysEnter Present)*/
{$EXTERNALSYM gestaltX86HasMTRR}
gestaltX86HasMTRR = 12; //* supports Memory Type Range Registers*/
{$EXTERNALSYM gestaltX86HasPGE}
gestaltX86HasPGE = 13; //* supports Page Global Enable*/
{$EXTERNALSYM gestaltX86HasMCA}
gestaltX86HasMCA = 14; //* supports Machine Check Architecture*/
{$EXTERNALSYM gestaltX86HasCMOV}
gestaltX86HasCMOV = 15; //* supports CMOVcc instruction (Conditional Move).*/
//* If FPU bit is also set, supports FCMOVcc and FCOMI, too*/
{$EXTERNALSYM gestaltX86HasPAT}
gestaltX86HasPAT = 16; //* supports Page Attribute Table*/
{$EXTERNALSYM gestaltX86HasPSE36}
gestaltX86HasPSE36 = 17; //* supports 36-bit Page Size Extension*/
{$EXTERNALSYM gestaltX86HasPSN}
gestaltX86HasPSN = 18; //* Processor Serial Number*/
{$EXTERNALSYM gestaltX86HasCLFSH}
gestaltX86HasCLFSH = 19; //* CLFLUSH Instruction supported*/
{$EXTERNALSYM gestaltX86Serviced20}
gestaltX86Serviced20 = 20; //* do not count on this bit value*/
{$EXTERNALSYM gestaltX86HasDS}
gestaltX86HasDS = 21; //* Debug Store*/
{$EXTERNALSYM gestaltX86ResACPI}
gestaltX86ResACPI = 22; //* Thermal Monitor, SW-controlled clock*/
{$EXTERNALSYM gestaltX86HasMMX}
gestaltX86HasMMX = 23; //* supports MMX instructions*/
{$EXTERNALSYM gestaltX86HasFXSR}
gestaltX86HasFXSR = 24; //* Supports FXSAVE and FXRSTOR instructions (fast FP save/restore)*/
{$EXTERNALSYM gestaltX86HasSSE}
gestaltX86HasSSE = 25; //* Streaming SIMD extensions*/
{$EXTERNALSYM gestaltX86HasSSE2}
gestaltX86HasSSE2 = 26; //* Streaming SIMD extensions 2*/
{$EXTERNALSYM gestaltX86HasSS}
gestaltX86HasSS = 27; //* Self-Snoop*/
{$EXTERNALSYM gestaltX86HasHTT}
gestaltX86HasHTT = 28; //* Hyper-Threading Technology*/
{$EXTERNALSYM gestaltX86HasTM}
gestaltX86HasTM = 29; //* Thermal Monitor*/
//};
{* 'cpuid' now returns a 64 bit value, and the following
gestalt selector and field definitions apply
to the extended form of this instruction *}
//enum {
{$EXTERNALSYM gestaltX86AdditionalFeatures}
gestaltX86AdditionalFeatures = $78383661; //'x86a',
{$EXTERNALSYM gestaltX86HasSSE3}
gestaltX86HasSSE3 = 0; //* Prescott New Inst.*/
{$EXTERNALSYM gestaltX86HasMONITOR}
gestaltX86HasMONITOR = 3; //* Monitor/mwait*/
{$EXTERNALSYM gestaltX86HasDSCPL}
gestaltX86HasDSCPL = 4; //* Debug Store CPL*/
{$EXTERNALSYM gestaltX86HasVMX}
gestaltX86HasVMX = 5; //* VMX*/
{$EXTERNALSYM gestaltX86HasSMX}
gestaltX86HasSMX = 6; //* SMX*/
{$EXTERNALSYM gestaltX86HasEST}
gestaltX86HasEST = 7; //* Enhanced SpeedsTep (GV3)*/
{$EXTERNALSYM gestaltX86HasTM2}
gestaltX86HasTM2 = 8; //* Thermal Monitor 2*/
{$EXTERNALSYM gestaltX86HasSupplementalSSE3}
gestaltX86HasSupplementalSSE3 = 9; //* Supplemental SSE3 instructions*/
{$EXTERNALSYM gestaltX86HasCID}
gestaltX86HasCID = 10; //* L1 Context ID*/
{$EXTERNALSYM gestaltX86HasCX16}
gestaltX86HasCX16 = 13; //* CmpXchg16b instruction*/
{$EXTERNALSYM gestaltX86HasxTPR}
gestaltX86HasxTPR = 14; //* Send Task PRiority msgs*/
//};
//enum {
{$EXTERNALSYM gestaltTranslationAttr}
gestaltTranslationAttr = $786c6174; //'xlat', /* Translation Manager attributes */
{$EXTERNALSYM gestaltTranslationMgrExists}
gestaltTranslationMgrExists = 0; //* True if translation manager exists */
{$EXTERNALSYM gestaltTranslationMgrHintOrder}
gestaltTranslationMgrHintOrder = 1; //* True if hint order reversal in effect */
{$EXTERNALSYM gestaltTranslationPPCAvail}
gestaltTranslationPPCAvail = 2;
{$EXTERNALSYM gestaltTranslationGetPathAPIAvail}
gestaltTranslationGetPathAPIAvail = 3;
//};
//enum {
{$EXTERNALSYM gestaltExtToolboxTable}
gestaltExtToolboxTable = $78747474; //'xttt' /* Extended Toolbox trap table base */
//};
//enum {
{$EXTERNALSYM gestaltUSBPrinterSharingVersion}
gestaltUSBPrinterSharingVersion = $7a616b20; //'zak ', /* USB Printer Sharing Version*/
{$EXTERNALSYM gestaltUSBPrinterSharingVersionMask}
gestaltUSBPrinterSharingVersionMask = $0000FFFF; //* mask for bits in version*/
{$EXTERNALSYM gestaltUSBPrinterSharingAttr}
gestaltUSBPrinterSharingAttr = $7a616b20; //'zak ', /* USB Printer Sharing Attributes*/
{$EXTERNALSYM gestaltUSBPrinterSharingAttrMask}
gestaltUSBPrinterSharingAttrMask = TIdC_INT($FFFF0000); //* mask for attribute bits*/
{$EXTERNALSYM gestaltUSBPrinterSharingAttrRunning}
gestaltUSBPrinterSharingAttrRunning = TIdC_INT($80000000); //* printer sharing is running*/
{$EXTERNALSYM gestaltUSBPrinterSharingAttrBooted}
gestaltUSBPrinterSharingAttrBooted = $40000000; //* printer sharing was installed at boot time*/
//};
//*WorldScript settings;*/
//enum {
{$EXTERNALSYM gestaltWorldScriptIIVersion}
gestaltWorldScriptIIVersion = $646f7562; //'doub',
{$EXTERNALSYM gestaltWorldScriptIIAttr}
gestaltWorldScriptIIAttr = $77736174; //'wsat',
{$EXTERNALSYM gestaltWSIICanPrintWithoutPrGeneralBit}
gestaltWSIICanPrintWithoutPrGeneralBit = 0; //* bit 0 is on if WS II knows about PrinterStatus callback */
//};
type
//may very depeanding on CPU architecture.
{$EXTERNALSYM SelectorFunctionProcPtr}
SelectorFunctionProcPtr = function (selector : OSType; var response : SInt32 ): OSErr cdecl;
{$EXTERNALSYM SelectorFunctionUPP}
SelectorFunctionUPP = SelectorFunctionProcPtr;
//MacErrors.h
{*
* SysError()
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.1 and later
*}
{$EXTERNALSYM SysError}
procedure SysError(errorCode : TIdC_SHORT) {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
//gestalt.h
{*
* Gestalt()
*
* Summary:
* Gestalt returns information about the operating environment.
*
* Discussion:
* The Gestalt function places the information requested by the
* selector parameter in the variable parameter response . Note that
* Gestalt returns the response from all selectors in an SInt32,
* which occupies 4 bytes. When not all 4 bytes are needed, the
* significant information appears in the low-order byte or bytes.
* Although the response parameter is declared as a variable
* parameter, you cannot use it to pass information to Gestalt or to
* a Gestalt selector function. Gestalt interprets the response
* parameter as an address at which it is to place the result
* returned by the selector function specified by the selector
* parameter. Gestalt ignores any information already at that
* address.
*
* The Apple-defined selector codes fall into two categories:
* environmental selectors, which supply specific environmental
* information you can use to control the behavior of your
* application, and informational selectors, which supply
* information you can't use to determine what hardware or software
* features are available. You can use one of the selector codes
* defined by Apple (listed in the "Constants" section beginning on
* page 1-14 ) or a selector code defined by a third-party
* product.
*
* The meaning of the value that Gestalt returns in the response
* parameter depends on the selector code with which it was called.
* For example, if you call Gestalt using the gestaltTimeMgrVersion
* selector, it returns a version code in the response parameter. In
* this case, a returned value of 3 indicates that the extended Time
* Manager is available.
*
* In most cases, the last few characters in the selector's symbolic
* name form a suffix that indicates what type of value you can
* expect Gestalt to place in the response parameter. For example,
* if the suffix in a Gestalt selector is Size , then Gestalt
* returns a size in the response parameter.
*
* Attr: A range of 32 bits, the meanings of which are defined by a
* list of constants. Bit 0 is the least significant bit of the
* SInt32.
* Count: A number indicating how many of the indicated type of item
* exist.
* Size: A size, usually in bytes.
* Table: The base address of a table.
* Type: An index to a list of feature descriptions.
* Version: A version number, which can be either a constant with a
* defined meaning or an actual version number, usually stored as
* four hexadecimal digits in the low-order word of the return
* value. Implied decimal points may separate digits. The value
* $0701, for example, returned in response to the
* gestaltSystemVersion selector, represents system software version
* 7.0.1.
*
* Selectors that have the suffix Attr deserve special attention.
* They cause Gestalt to return a bit field that your application
* must interpret to determine whether a desired feature is present.
* For example, the application-defined sample function
* MyGetSoundAttr , defined in Listing 1-2 on page 1-6 , returns a
* LongInt that contains the Sound Manager attributes field
* retrieved from Gestalt . To determine whether a particular
* feature is available, you need to look at the designated bit.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* The selector to return information for
*
* response:
* On exit, the requested information whose format depends on the
* selector specified.
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.1 and later
*}
{$EXTERNALSYM Gestalt}
function Gestalt(selector : OSType; var response : SInt32 ) : OSErr {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{$IFNDEF CPU64}
{*
* ReplaceGestalt() *** DEPRECATED ***
*
* Deprecated:
* Use NewGestaltValue instead wherever possible.
*
* Summary:
* Replaces the gestalt function associated with a selector.
*
* Discussion:
* The ReplaceGestalt function replaces the selector function
* associated with an existing selector code.
*
* So that your function can call the function previously associated
* with the selector, ReplaceGestalt places the address of the old
* selector function in the oldGestaltFunction parameter. If
* ReplaceGestalt returns an error of any type, then the value of
* oldGestaltFunction is undefined.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* the selector to replace
*
* gestaltFunction:
* a UPP for the new selector function
*
* oldGestaltFunction:
* on exit, a pointer to the UPP of the previously associated with
* the specified selector
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework [32-bit only] but deprecated in 10.3
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.1 and later
*}
{$EXTERNALSYM ReplaceGestalt}
function ReplaceGestalt(selector : OSType;
gestaltFunction : SelectorFunctionUPP;
oldGestaltFunction : SelectorFunctionUPP) : OSErr
{AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_3}; cdecl;
{*
* NewGestalt() *** DEPRECATED ***
*
* Deprecated:
* Use NewGestaltValue instead wherever possible.
*
* Summary:
* Adds a selector code to those already recognized by Gestalt.
*
* Discussion:
* The NewGestalt function registers a specified selector code with
* the Gestalt Manager so that when the Gestalt function is called
* with that selector code, the specified selector function is
* executed. Before calling NewGestalt, you must define a selector
* function callback. See SelectorFunctionProcPtr for a description
* of how to define your selector function.
*
* Registering with the Gestalt Manager is a way for software such
* as system extensions to make their presence known to potential
* users of their services.
*
* In Mac OS X, the selector and replacement value are on a
* per-context basis. That means they are available only to the
* application or other code that installs them. You cannot use this
* function to make information available to another process.
*
* A Gestalt selector registered with NewGestalt() can not be
* deleted.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* the selector to create
*
* gestaltFunction:
* a UPP for the new selector function, which Gestalt executes
* when it receives the new selector code. See
* SelectorFunctionProcPtr for more information on the callback
* you need to provide.
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework [32-bit only] but deprecated in 10.3
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.1 and later
*}
{$EXTERNALSYM NewGestalt}
function NewGestalt(selector : OSType;
gestaltFunction : SelectorFunctionUPP) : OSErr
{AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER_BUT_DEPRECATED_IN_MAC_OS_X_VERSION_10_3}; cdecl;
{$ENDIF}
{*
* NewGestaltValue()
*
* Summary:
* Adds a selector code to those already recognized by Gestalt.
*
* Discussion:
* The NewGestalt function registers a specified selector code with
* the Gestalt Manager so that when the Gestalt function is called
* with that selector code, the specified selector function is
* executed. Before calling NewGestalt, you must define a selector
* function callback. See SelectorFunctionProcPtr for a description
* of how to define your selector function.
*
* Registering with the Gestalt Manager is a way for software such
* as system extensions to make their presence known to potential
* users of their services.
*
* In Mac OS X, the selector and replacement value are on a
* per-context basis. That means they are available only to the
* application or other code that installs them. You cannot use this
* function to make information available to another process.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* the selector to create
*
* newValue:
* the value to return for the new selector code.
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.5 and later
*}
{$EXTERNALSYM NewGestaltValue}
function NewGestaltValue(selector : OSType; const newValue : SInt32) : OSErr {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{*
* ReplaceGestaltValue()
*
* Summary:
* Replaces the value that the function Gestalt returns for a
* specified selector code with the value provided to the function.
*
* Discussion:
* You use the function ReplaceGestaltValue to replace an existing
* value. You should not call this function to introduce a value
* that doesn't already exist; instead call the function
* NewGestaltValue.
*
* In Mac OS X, the selector and replacement value are on a
* per-context basis. That means they are available only to the
* application or other code that installs them. You cannot use this
* function to make information available to another process.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* the selector to create
*
* replacementValue:
* the new value to return for the new selector code.
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.5 and later
*}
{$EXTERNALSYM ReplaceGestaltValue}
function ReplaceGestaltValue(selector : OSType; const replacementValue : SInt32 ) : OSErr {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{*
* SetGestaltValue()
*
* Summary:
* Sets the value the function Gestalt will return for a specified
* selector code, installing the selector if it was not already
* installed.
*
* Discussion:
* You use SetGestaltValue to establish a value for a selector,
* without regard to whether the selector was already installed.
*
* In Mac OS X, the selector and replacement value are on a
* per-context basis. That means they are available only to the
* application or other code that installs them. You cannot use this
* function to make information available to another process.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* the selector to create
*
* newValue:
* the new value to return for the new selector code.
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.5 and later
*}
{$EXTERNALSYM SetGestaltValue}
function SetGestaltValue(selector : OSType; const newValue : SInt32) : OSErr {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{*
* DeleteGestaltValue()
*
* Summary:
* Deletes a Gestalt selector code so that it is no longer
* recognized by Gestalt.
*
* Discussion:
* After calling this function, subsequent query or replacement
* calls for the selector code will fail as if the selector had
* never been installed
*
* In Mac OS X, the selector and replacement value are on a
* per-context basis. That means they are available only to the
* application or other code that installs them.
*
* Mac OS X threading:
* Thread safe since version 10.3
*
* Parameters:
*
* selector:
* the selector to delete
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: in InterfaceLib 7.5 and later
*}
{$EXTERNALSYM DeleteGestaltValue}
function DeleteGestaltValue(selector : OSType) : OSErr {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{*
* NewSelectorFunctionUPP()
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: available as macro/inline
*}
{$EXTERNALSYM NewSelectorFunctionUPP}
function NewSelectorFunctionUPP(userRoutine : SelectorFunctionProcPtr) : SelectorFunctionUPP {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{*
* DisposeSelectorFunctionUPP()
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: available as macro/inline
*}
{$EXTERNALSYM DisposeSelectorFunctionUPP}
procedure DisposeSelectorFunctionUPP(userUPP : SelectorFunctionUPP) {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{*
* InvokeSelectorFunctionUPP()
*
* Availability:
* Mac OS X: in version 10.0 and later in CoreServices.framework
* CarbonLib: in CarbonLib 1.0 and later
* Non-Carbon CFM: available as macro/inline
*}
{$EXTERNALSYM InvokeSelectorFunctionUPP}
function InvokeSelectorFunctionUPP(selector : OSType; var response : SInt32; userUPP : SelectorFunctionUPP) : OSErr {AVAILABLE_MAC_OS_X_VERSION_10_0_AND_LATER}; cdecl;
{$ENDIF}
{$IFDEF LINUX}
//* UDP socket options */
{$EXTERNALSYM UDP_CORK}
UDP_CORK = 1; //* Never send partially complete segments */
{$EXTERNALSYM UDP_ENCAP}
UDP_ENCAP = 100; //* Set the socket to accept encapsulated packets */
//* UDP encapsulation types */
{$EXTERNALSYM UDP_ENCAP_ESPINUDP_NON_IKE}
UDP_ENCAP_ESPINUDP_NON_IKE = 1; //* draft-ietf-ipsec-nat-t-ike-00/01 */
{$EXTERNALSYM UDP_ENCAP_ESPINUDP}
UDP_ENCAP_ESPINUDP = 2; //* draft-ietf-ipsec-udp-encaps-06 */
{$ENDIF}
implementation
{$IFDEF DARWIN}
{$DEFINE USE_CARBONCORELIB}
{/$DEFINE USE_CORESERVICESLIB}
{$IFDEF USE_CARBONCORELIB}
{$UNDEF USE_CORESERVICESLIB}
{$ENDIF}
function TCPOPT_CC_HDR(const ccopt : Integer) : Integer; inline;
begin
Result := (TCPOPT_NOP shl 24) or
(TCPOPT_NOP shl 16) or
(ccopt shl 8) or
TCPOLEN_CC;
end;
procedure SysError; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib{$ENDIF} name '_SysError';
function Gestalt; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_Gestalt';
{$IFNDEF CPU64}
function ReplaceGestalt; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_ReplaceGestalt';
function NewGestalt; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_NewGestalt';
{$ENDIF}
function NewGestaltValue; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_NewGestaltValue';
function ReplaceGestaltValue; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_ReplaceGestaltValue';
function SetGestaltValue; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_SetGestaltValue';
function DeleteGestaltValue; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_DeleteGestaltValue';
function NewSelectorFunctionUPP; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_NewSelectorFunctionUPP';
procedure DisposeSelectorFunctionUPP; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_DisposeSelectorFunctionUPP';
function InvokeSelectorFunctionUPP; external {$IFDEF USE_CORESERVICESLIB}CoreServices{$ENDIF}
{$IFDEF USE_CARBONCORELIB}CarbonCoreLib {$ENDIF} name '_InvokeSelectorFunctionUPP';
{$ENDIF}
end.
|
inherited fClarifySpaces: TfClarifySpaces
Width = 472
Height = 463
Font.Charset = ANSI_CHARSET
Font.Height = -15
Font.Name = 'Segoe UI'
ParentFont = False
object cbFixSpacing: TCheckBox
Left = 8
Top = 6
Width = 241
Height = 17
Caption = 'Fix &spacing'
TabOrder = 0
end
object cbSpaceClassHeritage: TCheckBox
Left = 8
Top = 29
Width = 241
Height = 17
Caption = 'Space before class &heritage'
TabOrder = 1
end
object gbColon: TGroupBox
Left = 8
Top = 50
Width = 246
Height = 292
Caption = 'Spaces &before colon in'
TabOrder = 2
object lblSpaceBeforeColonVar: TLabel
Left = 8
Top = 22
Width = 107
Height = 20
Caption = '&Var declarations'
FocusControl = eSpaceBeforeColonVar
end
object lblSpacesBeforeColonClassVar: TLabel
Left = 8
Top = 142
Width = 96
Height = 20
Caption = '&Class variables'
FocusControl = eSpacesBeforeColonClassVar
end
object lblSpaceBeforeColonFn: TLabel
Left = 8
Top = 112
Width = 138
Height = 20
Caption = '&Function return types'
FocusControl = eSpaceBeforeColonFn
end
object lblSpaceBeforeColonParam: TLabel
Left = 8
Top = 82
Width = 146
Height = 20
Caption = '&Procedure parameters'
FocusControl = eSpaceBeforeColonParam
end
object lblSpacesBeforeCaseLabel: TLabel
Left = 5
Top = 202
Width = 68
Height = 20
Caption = 'Case l&abel'
FocusControl = eSpacesBeforeCaseLabel
end
object lbSpacesBeforeLabel: TLabel
Left = 5
Top = 232
Width = 36
Height = 20
Caption = '&Label'
FocusControl = eSpacesBeforeLabel
end
object lblSpacesBeforeColonGeneric: TLabel
Left = 5
Top = 262
Width = 65
Height = 20
Caption = 'In &generic'
FocusControl = eSpacesBeforeColonGeneric
end
object lblSpaceBeforeColonConst: TLabel
Left = 7
Top = 52
Width = 122
Height = 20
Caption = 'C&onst declarations'
FocusControl = eSpaceBeforeColonConst
end
object lblSpacesBeforeColonRecordField: TLabel
Left = 8
Top = 172
Width = 87
Height = 20
Caption = '&Record fields'
FocusControl = eSpacesBeforeColonRecordField
end
object eSpaceBeforeColonVar: TJvValidateEdit
Left = 180
Top = 20
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 0
end
object eSpaceBeforeColonParam: TJvValidateEdit
Left = 180
Top = 80
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 1
end
object eSpaceBeforeColonFn: TJvValidateEdit
Left = 180
Top = 110
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 2
end
object eSpacesBeforeColonClassVar: TJvValidateEdit
Left = 180
Top = 140
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 3
end
object eSpacesBeforeCaseLabel: TJvValidateEdit
Left = 180
Top = 200
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 4
end
object eSpacesBeforeLabel: TJvValidateEdit
Left = 180
Top = 230
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 5
end
object eSpacesBeforeColonGeneric: TJvValidateEdit
Left = 180
Top = 260
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 6
end
object eSpaceBeforeColonConst: TJvValidateEdit
Left = 180
Top = 50
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 7
end
object eSpacesBeforeColonRecordField: TJvValidateEdit
Left = 180
Top = 170
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
MaxLength = 2
TabOrder = 8
end
end
object gbTabs: TGroupBox
Left = 8
Top = 344
Width = 457
Height = 78
Caption = '&Tab characters'
TabOrder = 3
object Label1: TLabel
Left = 240
Top = 22
Width = 98
Height = 20
Caption = 'Spaces per tab'
end
object Label3: TLabel
Left = 240
Top = 44
Width = 95
Height = 20
Caption = 'Spaces for tab'
end
object cbTabsToSpaces: TCheckBox
Left = 6
Top = 24
Width = 175
Height = 17
Caption = 'Turn tabs to spaces'
TabOrder = 0
OnClick = cbTabsToSpacesClick
end
object cbSpacesToTabs: TCheckBox
Left = 6
Top = 46
Width = 175
Height = 17
Caption = 'Turn spaces to tabs'
TabOrder = 2
OnClick = cbSpacesToTabsClick
end
object edtSpacesPerTab: TJvValidateEdit
Left = 356
Top = 20
Width = 49
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 2
MaxValue = 12.000000000000000000
TabOrder = 1
end
object edtSpacesForTab: TJvValidateEdit
Left = 356
Top = 44
Width = 49
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 2
MaxValue = 12.000000000000000000
TabOrder = 3
end
end
object cbMaxSpaces: TCheckBox
Left = 8
Top = 426
Width = 179
Height = 17
Caption = '&Max spaces in code'
TabOrder = 4
OnClick = cbMaxSpacesClick
end
object edtMaxSpacesInCode: TJvValidateEdit
Left = 193
Top = 424
Width = 50
Height = 28
CriticalPoints.MaxValueIncluded = False
CriticalPoints.MinValueIncluded = False
EditText = '0'
HasMaxValue = True
HasMinValue = True
MaxLength = 2
MaxValue = 99.000000000000000000
TabOrder = 5
end
object rgOperators: TRadioGroup
Left = 260
Top = 6
Width = 202
Height = 92
Caption = 'Spaces around &operators'
Items.Strings = (
'Always'
'Leave as is'
'Never')
TabOrder = 6
end
object GroupBoxInsertSpaceBeforeBracket: TGroupBox
Left = 260
Top = 98
Width = 202
Height = 95
Caption = '&Insert space before bracket'
TabOrder = 7
object cbInsertSpaceBeforeBracketinFunctionDeclaration: TCheckBox
Left = 8
Top = 26
Width = 181
Height = 17
Caption = 'In function &declaration'
TabOrder = 0
end
object cbInsertSpaceBeforeBracketinFunctionCall: TCheckBox
Left = 8
Top = 48
Width = 181
Height = 17
Caption = 'In function &call'
TabOrder = 1
end
object cbBeforeOpenSquareBracketInExpression: TCheckBox
Left = 8
Top = 68
Width = 182
Height = 17
Caption = 'Before [ in expression'
TabOrder = 2
end
end
object GroupBoxSpacesInsideBrackets: TGroupBox
Left = 260
Top = 194
Width = 202
Height = 70
Caption = 'Insert space inside brackets'
TabOrder = 8
object CheckBoxInsertSpaceBeforeEnd: TCheckBox
Left = 8
Top = 47
Width = 181
Height = 17
Caption = 'Before end'
TabOrder = 0
end
object cbInsertSpaceAfterOpen: TCheckBox
Left = 8
Top = 24
Width = 181
Height = 17
Caption = 'After open'
TabOrder = 1
end
end
object cbMoveSpacesToBeforeColon: TCheckBox
Left = 260
Top = 270
Width = 202
Height = 17
Caption = 'Move spaces to before colon'
TabOrder = 9
end
end
|
unit sNIF.control;
{ *******************************************************
sNIF
Utilidad para buscar ficheros ofimáticos con
cadenas de caracteres coincidentes con NIF/NIE.
*******************************************************
2012-2018 Ángel Fernández Pineda. Madrid. Spain.
This work is licensed under the Creative Commons
Attribution-ShareAlike 3.0 Unported License. To
view a copy of this license,
visit http://creativecommons.org/licenses/by-sa/3.0/
or send a letter to Creative Commons,
444 Castro Street, Suite 900,
Mountain View, California, 94041, USA.
******************************************************* }
interface
uses
System.Classes,
System.SysUtils,
System.Generics.Collections,
CSVUtils.ThreadSafe,
sNIF.params,
sNIF.data;
type
TsNIFControl = class
{
PROPOSITO:
Controla la concurrencia durante la exploración. Mantiene contadores
de progreso y su estado.
ALGORITMO:
El trabajo se ejecuta en hilos concurrentes llamados "trabajadores".
El trabajador "candidatos" genera los ficheros a explorar a partir de un
listado recursivo de directorios. El trabajo se almacena en una cola
concurrente denominada "ColaCandidatos".
Varios hilos trabajadores de tipo "explorador" extraen de dicha cola
cada fichero candidato y cuentan el número de ocurrencias de NIF/NIE.
El resultado de cada exploración pasa a otra cola concurrente
denominada "ColaResultados".
El trabajador "escritor" toma los resultados de dicha cola y los escribe
en el fichero de salida.
ESTADOS:
(incial y final): preparado
Método "iniciar": preparado --> trabajando.
Método "cancelar": trabajando --> cancelando.
Evento de fin de trabajo: trabajando --> preparado
Evento de fin de trabajo: cancelando --> preparado
EVENTO DE FIN DE TRABAJO:
El trabajador "candidatos" ha finalizado
Y
"ColaCandidatos" está vacía
CONTADORES DE PROGRESO:
Algunos contadores no están sincronizados porque se supone que solamente
un hilo trabajador efectuará escrituras.
Los restantes están sincronizados. La lectura no necesita sincronización.
}
public type
TEstado = (preparado, cancelando, trabajando);
EWorkerException = class(Exception);
private
FCuentaTotalFicheros: int64;
FCuentaFicherosExplorados: int64;
FCuentaCarpetas: int64;
FCuentaErroresFichero: int64;
FCuentaErroresCarpeta: int64;
FTimestampInicio: TDateTime;
FTimestampFin: TDateTime;
FEstado: TEstado;
FParametros: TsNIFParametros;
FColaCandidatos: TColaCandidatos;
FWorkers: TList<TThread>;
FCSVWriter: TSafeCSVWriter;
NumExploradores: int64;
procedure FinDelTrabajo;
function getProgreso: integer;
function getMinutosTrabajo: int64;
public
// Propiedades y métodos públicos para uso exclusivo de los hilos
// exploradores. No invocar directamente.
property ColaCandidatos: TColaCandidatos read FColaCandidatos;
property CSVWriter: TSafeCSVWriter read FCSVWriter;
public
// -- Inicialización
constructor Create;
destructor Destroy; override;
// -- Contadores de progreso
// Nota: Solo escritura para el hilo que busca ficheros candidatos
procedure incCuentaTotalFicheros;
property CuentaTotalFicheros: int64 read FCuentaTotalFicheros;
procedure incCuentaCarpetas;
property CuentaCarpetas: int64 read FCuentaCarpetas;
property Progreso: integer read getProgreso;
property MinutosDeTrabajo: int64 read getMinutosTrabajo;
procedure incCuentaErroresCarpeta;
property CuentaErroresCarpeta: int64 read FCuentaErroresCarpeta;
// Nota: propiedades/procedimientos sincronizados
procedure incCuentaFicherosExplorados;
property CuentaFicherosExplorados: int64 read FCuentaFicherosExplorados;
procedure incCuentaErroresFichero;
property CuentaErroresFichero: int64 read FCuentaErroresFichero;
// -- Control y estado
procedure Iniciar(const Parametros: TsNIFParametros);
procedure Cancelar;
property Estado: TEstado read FEstado;
// En aplicaciones CLI no funcionan los eventos, por lo que se necesita
// esta primitiva de espera en bucle. No es espera activa.
function haTerminado(const timeout: cardinal = 1000): boolean;
end;
implementation
uses
SyncObjs,
// System.SysUtils,
System.DateUtils,
ThreadUtils.Sync,
CSVUtils,
IOUtils,
IOUtilsFix,
sNIF.worker.candidatos,
sNIF.worker.explorador,
windows;
// --------------------------------------------------------------------------
// TsNIFControl
// --------------------------------------------------------------------------
// -- Inicialización
constructor TsNIFControl.Create;
begin
inherited;
FWorkers := TList<TThread>.Create;
FEstado := preparado;
FColaCandidatos := nil;
FCSVWriter := nil;
FTimestampInicio := Now;
FTimestampFin := FTimestampInicio;
end;
destructor TsNIFControl.Destroy;
begin
if (FEstado <> preparado) then
// no debería ocurrir
raise EAbort.Create
('Se ha ejecutado TsNIFControl.Destroy con la exploración en marcha');
FWorkers.Free;
inherited;
end;
// -- Contadores de progreso
procedure TsNIFControl.incCuentaTotalFicheros;
begin
inc(FCuentaTotalFicheros);
end;
procedure TsNIFControl.incCuentaCarpetas;
begin
inc(FCuentaCarpetas);
end;
procedure TsNIFControl.incCuentaErroresCarpeta;
begin
inc(FCuentaErroresCarpeta);
end;
procedure TsNIFControl.incCuentaFicherosExplorados;
begin
InterlockedIncrement64(FCuentaFicherosExplorados);
end;
procedure TsNIFControl.incCuentaErroresFichero;
begin
InterlockedIncrement64(FCuentaErroresFichero);
end;
function TsNIFControl.getProgreso: integer;
begin
if (FCuentaTotalFicheros > 0) then
Result := Trunc((FCuentaFicherosExplorados * 1.0 /
FCuentaTotalFicheros) * 100)
else
Result := 0;
end;
function TsNIFControl.getMinutosTrabajo: int64;
begin
if (FEstado = preparado) then
Result := MinutesBetween(FTimestampFin, FTimestampInicio)
else
Result := MinutesBetween(Now, FTimestampInicio);
end;
// -- Control
procedure TsNIFControl.Iniciar(const Parametros: TsNIFParametros);
var
worker: TThread;
c: integer;
csvFields: TCSVFields;
begin
if (FEstado = preparado) then
begin
FTimestampInicio := Now;
FParametros := Parametros; // Se necesita en "FinDelTrabajo"
FWorkers.Clear;
FCuentaTotalFicheros := 0;
FCuentaFicherosExplorados := 0;
FCuentaCarpetas := 0;
FCuentaErroresFichero := 0;
FCuentaErroresCarpeta := 0;
// Preparar fichero CSV de resultados
FCSVWriter := TSafeCSVWriter.Create
(TPath.SetExtendedPrefix(Parametros.FicheroSalida));
csvFields := TCSVFields.Create;
// Escribir cabecera de fichero CSV
try
csvFields.StrictSyntax := true;
csvFields.FieldCount := 4;
csvFields.Field[0] := 'Carpeta';
csvFields.Field[1] := 'Fichero';
csvFields.Field[2] := 'CuentaNIF';
csvFields.Field[3] := 'Ultimo acceso';
FCSVWriter.WriteLine(csvFields);
finally
csvFields.Free;
end;
try
FColaCandidatos := TColaCandidatos.Create;
// Crear hilo buscador de ficheros candidatos
worker := TWorkerCandidatos.Create(self, Parametros);
FWorkers.Add(worker);
// Crear hilos exploradores de cadenas NIF/NIE
NumExploradores := Parametros.NumHilos;
for c := 0 to Parametros.NumHilos - 1 do
begin
worker := TWorkerExplorador.Create(self, Parametros);
FWorkers.Add(worker);
end;
except
// Si algo falla, finalizar los hilos que se hayan podido crear
// y liberar recursos.
FColaCandidatos.Free;
TThread.TerminateAll(FWorkers);
// Todos los hilos se crean en estado suspendido. Hay que despertarlos
// para que puedan terminar.
TThread.StartAll(FWorkers);
TThread.FreeAll(FWorkers);
// Relanzar la excepción
raise;
end;
// iniciar el trabajo
FEstado := trabajando;
TThread.StartAll(FWorkers);
end;
end;
procedure TsNIFControl.Cancelar;
begin
if (FEstado = trabajando) then
begin
FEstado := cancelando;
// Solicitar la parada de todos los hilos
TThread.TerminateAll(FWorkers);
// Cancelar la cola. De lo contrario, algunos hilos quedarían
// bloqueados y no terminarían nunca.
FreeAndNil(FColaCandidatos);
end;
end;
procedure TsNIFControl.FinDelTrabajo;
var
estadoPrevio: TEstado;
csv: TCSVWriter;
I: integer;
ExcepcionEnHilo: boolean;
MensajeExcepcion: string;
begin
// Liberar recursos y cambiar estado
estadoPrevio := Estado;
FEstado := preparado;
FTimestampFin := Now;
FreeAndNil(FCSVWriter);
FreeAndNil(FColaCandidatos);
csv := nil;
// Determinar si algún hilo terminó en excepción
ExcepcionEnHilo := false;
I := 0;
while (I < FWorkers.Count) and (not ExcepcionEnHilo) do
begin
ExcepcionEnHilo := (FWorkers[I].FatalException <> nil);
inc(I);
end;
if (ExcepcionEnHilo) then
MensajeExcepcion := Exception(FWorkers[I-1].FatalException).Message;
TThread.FreeAll(FWorkers);
// Generar fichero resumen, si procede
if (FParametros.GenerarResumen) then
try
csv := TCSVWriter.Create(FParametros.FicheroResumen);
csv.FieldCount := 2;
csv.Field[0] := 'Clave';
csv.Field[1] := 'Valor';
csv.WriteLine;
csv.Field[0] := 'MARCA_TIEMPO_INICIO';
csv.Field[1] := FormatDateTime('yyyy/mm/dd hh:nn:ss', FTimestampInicio);
csv.WriteLine;
csv.Field[0] := 'MARCA_TIEMPO_FIN';
csv.Field[1] := FormatDateTime('yyyy/mm/dd hh:nn:ss', FTimestampFin);
csv.WriteLine;
csv.Field[0] := 'TIEMPO_EJECUCION';
csv.Field[1] := FormatDateTime('hh:nn:ss',
FTimestampFin - FTimestampInicio);
csv.WriteLine;
csv.Field[0] := 'CUENTA_CARPETAS_EXPLORADAS';
csv.Field[1] := FCuentaCarpetas;
csv.WriteLine;
csv.Field[0] := 'CUENTA_CARPETAS_ERROR';
csv.Field[1] := FCuentaErroresCarpeta;
csv.WriteLine;
csv.Field[0] := 'CUENTA_FICHEROS_EXPLORADOS';
csv.Field[1] := FCuentaFicherosExplorados;
csv.WriteLine;
csv.Field[0] := 'CUENTA_FICHEROS_ERROR_LECTURA';
csv.Field[1] := FCuentaErroresFichero;
csv.WriteLine;
csv.Field[0] := 'ESTADO_FINALIZACION';
if (ExcepcionEnHilo) then
csv.Field[1] := 'ABORTADO'
else if (estadoPrevio = cancelando) then
csv.Field[1] := 'CANCELADO'
else
csv.Field[1] := 'correcto';
csv.WriteLine;
if (ExcepcionEnHilo) then
begin
csv.Field[0] := 'MENSAJE_ERROR';
csv.Field[1] := MensajeExcepcion;
csv.WriteLine;
end;
for I := 0 to FParametros.Carpetas.Count - 1 do
begin
csv.Field[0] := 'CARPETA_EXPLORADA';
csv.Field[1] := FParametros.Carpetas.Strings[I];
csv.WriteLine;
end;
csv.Field[0] := 'EXTENSIONES';
csv.Field[1] := FParametros.Extensiones.DelimitedText;
csv.WriteLine;
csv.Field[0] := 'MAX_CUENTA_NIF';
csv.Field[1] := FParametros.MaxNIF;
csv.WriteLine;
csv.Field[0] := 'MAX_PORCENTAJE_SIN_NIF';
csv.Field[1] := FParametros.MaxSinNIF;
csv.WriteLine;
csv.Field[0] := 'MIN_BYTES';
csv.Field[1] := FParametros.MinBytes;
csv.WriteLine;
csv.Field[0] := 'MIN_DIAS_CREADO';
csv.Field[1] := FParametros.MinDiasCreado;
csv.WriteLine;
csv.Free;
except
// ignorar errores
csv.Free;
end;
// Si algún trabajador abortó su ejecución, lanzar la excepción
// en el hilo principal
if (ExcepcionEnHilo) then
raise EWorkerException.Create(MensajeExcepcion);
end;
function TsNIFControl.haTerminado(const timeout: cardinal = 1000): boolean;
var
wr: TWaitResult;
begin
Result := false;
if (FEstado <> preparado) then
begin
wr := TThread.WaitForAll(FWorkers, timeout);
if (wr = wrSignaled) then
begin
Result := true;
FinDelTrabajo;
end
else if (wr <> wrTimeout) then
RaiseLastOSError
end
else
Result := true;
end;
end.
|
unit MinTransfersplanner;
interface
uses
Contnrs,
MetroBase, Planner;
type
TMinTransfersPlanner =
class(TPlanner)
protected
FNetwork: TNetwork;
public
// construction/destruction
constructor Create(ANetwork: TNetwork);
// queries --------------------------------------------
function FindRoutes(A, B: TStationR; AOption: TSearchOption): TRouteSet;
override;
// pre: true
// ret: set of optimal (according to AOption) routes from A to B
function FindRoute(A, B: TStationR; AOption: TSearchOption): TRouteR;
override;
// pre: true
// ret: a route from A to B with minimal number of transfers
end;
implementation //===============================================================
// Auxiliary types
type
TLineState = (lsWhite, lsGrey, lsBlack);
TLineData =
class(TObject)
FState: TLineState;
FParent: TLineR;
FEntry: TStationR;
end;
{ TBFSPlanner }
constructor TMinTransfersPlanner.Create(ANetwork: TNetwork);
begin
inherited Create;
FNetwork := ANetwork;
end;
function TMinTransfersPlanner.FindRoute(A, B: TStationR;
AOption: TSearchOption): TRouteR;
var
VRoute: TRouteRW;
VSegment: TRouteSegmentR;
VQueue: TObjectList;
VTargetLine: TLineR;
VL, VH: TLineR;
VS, VQ, VDirection : TStationR;
I, J: Integer;
begin
// initialization
VQueue := TObjectList.Create(false);
VTargetLine := nil;
with FNetwork.GetLineSet do
for I := 0 to Count - 1 do
begin
VL := GetLine(I);
VL.Data := TLineData.Create;
with VL.Data as TLineData do
begin
FParent := nil;
if VL.HasStop(A)
then
begin
FState := lsGrey;
FEntry := A;
VQueue.Add(VL);
if VL.HasStop(B)
then VTargetLine := VL;
end
else
begin
FState := lsWhite;
FEntry := nil;
end;
end{with};
end{for};
// main loop
while (VQueue.Count > 0) and (VTargetLine = nil) do
begin
VL := VQueue.Items[0] as TLineR;
VQueue.Delete(0);
for I := 0 to VL.Count - 1 do
begin
VS := VL.Stop(I);
with FNetwork.GetLineSet do
for J := 0 to Count - 1 do
begin
VH := GetLine(J);
if VH.HasStop(VS) and ((VH.Data as TLineData).FState = lsWhite)
then
with VH.Data as TLineData do
begin
FParent := VL;
FEntry := VS;
FState := lsGrey;
VQueue.Add(VH);
if VH.HasStop(B)
then VTargetLine := VH
end{with}
end{for};
end{for};
(VL.Data as TLineData).FState := lsBlack;
end{while};
// construct route
VRoute := TRouteRW.Create;
if VTargetLine <> nil then
begin
VL := VTargetLine;
VQ := B;
while VL <> nil do
begin
VS := (VL.Data as TLineData).FEntry;
with VL do
begin
if IndexOf(VS) <= IndexOf(VQ)
then VDirection := Stop(Count - 1)
else VDirection := Stop(0);
end;
VSegment := TRouteSegmentR.Create(VS, VL, VDirection, VQ);
VRoute.Insert(0, VSegment);
VQ := VS;
VL := (VL.Data as TLineData).FParent;
end{while};
end{if};
// finalization
with FNetwork.GetLineSet do
for I := 0 to Count - 1 do
GetLine(I).Data.Free;
VQueue.Free;
Result := VRoute;
end;
function TMinTransfersPlanner.FindRoutes(A, B: TStationR;
AOption: TSearchOption): TRouteSet;
begin
Result := TRouteSet.Create;
Result.Add(FindRoute(A, B, AOption));
end;
end.
|
//+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright 1995-1998 Microsoft Corporation. All Rights Reserved.
//
// File: exdispid.h
//
//--------------------------------------------------------------------------
unit ExDispID;
interface
const
//
// Dispatch IDS for IExplorer Dispatch Events.
//
DISPID_BEFORENAVIGATE = 100; // this is sent before navigation to give a chance to abort
DISPID_NAVIGATECOMPLETE = 101; // in async, this is sent when we have enough to show
DISPID_STATUSTEXTCHANGE = 102;
DISPID_QUIT = 103;
DISPID_DOWNLOADCOMPLETE = 104;
DISPID_COMMANDSTATECHANGE = 105;
DISPID_DOWNLOADBEGIN = 106;
DISPID_NEWWINDOW = 107; // sent when a new window should be created
DISPID_PROGRESSCHANGE = 108; // sent when download progress is updated
DISPID_WINDOWMOVE = 109; // sent when main window has been moved
DISPID_WINDOWRESIZE = 110; // sent when main window has been sized
DISPID_WINDOWACTIVATE = 111; // sent when main window has been activated
DISPID_PROPERTYCHANGE = 112; // sent when the PutProperty method is called
DISPID_TITLECHANGE = 113; // sent when the document title changes
DISPID_TITLEICONCHANGE = 114; // sent when the top level window icon may have changed.
DISPID_FRAMEBEFORENAVIGATE = 200;
DISPID_FRAMENAVIGATECOMPLETE = 201;
DISPID_FRAMENEWWINDOW = 204;
DISPID_BEFORENAVIGATE2 = 250; // hyperlink clicked on
DISPID_NEWWINDOW2 = 251 ;
DISPID_NAVIGATECOMPLETE2 = 252; // UIActivate new document
DISPID_ONQUIT = 253 ;
DISPID_ONVISIBLE = 254; // sent when the window goes visible/hidden
DISPID_ONTOOLBAR = 255; // sent when the toolbar should be shown/hidden
DISPID_ONMENUBAR = 256; // sent when the menubar should be shown/hidden
DISPID_ONSTATUSBAR = 257; // sent when the statusbar should be shown/hidden
DISPID_ONFULLSCREEN = 258; // sent when kiosk mode should be on/off
DISPID_DOCUMENTCOMPLETE = 259; // new document goes ReadyState_Complete
DISPID_ONTHEATERMODE = 260; // sent when theater mode should be on/off
DISPID_ONADDRESSBAR = 261; // sent when the address bar should be shown/hidden
DISPID_WINDOWSETRESIZABLE = 262; // sent to set the style of the host window frame
DISPID_WINDOWCLOSING = 263; // sent before script window.close closes the window
DISPID_WINDOWSETLEFT = 264; // sent when the put_left method is called on the WebOC
DISPID_WINDOWSETTOP = 265; // sent when the put_top method is called on the WebOC
DISPID_WINDOWSETWIDTH = 266; // sent when the put_width method is called on the WebOC
DISPID_WINDOWSETHEIGHT = 267; // sent when the put_height method is called on the WebOC
DISPID_CLIENTTOHOSTWINDOW = 268; // sent during window.open to request conversion of dimensions
DISPID_SETSECURELOCKICON = 269; // sent to suggest the appropriate security icon to show
DISPID_FILEDOWNLOAD = 270; // Fired to indicate the File Download dialog is opening
DISPID_NAVIGATEERROR = 271; // Fired to indicate the a binding error has occured
DISPID_PRIVACYIMPACTEDSTATECHANGE = 272; // Fired when the user's browsing experience is impacted
// Printing events
DISPID_PRINTTEMPLATEINSTANTIATION = 225; // Fired to indicate that a print template is instantiated
DISPID_PRINTTEMPLATETEARDOWN = 226; // Fired to indicate that a print templete is completely gone
DISPID_UPDATEPAGESTATUS = 227; // Fired to indicate that the spooling status has changed
// define the events for the shell wiwndow list
DISPID_WINDOWREGISTERED = 200; // Window registered
DISPID_WINDOWREVOKED = 201; // Window Revoked
DISPID_RESETFIRSTBOOTMODE = 1;
DISPID_RESETSAFEMODE = 2;
DISPID_REFRESHOFFLINEDESKTOP = 3;
DISPID_ADDFAVORITE = 4;
DISPID_ADDCHANNEL = 5;
DISPID_ADDDESKTOPCOMPONENT = 6;
DISPID_ISSUBSCRIBED = 7;
DISPID_NAVIGATEANDFIND = 8;
DISPID_IMPORTEXPORTFAVORITES = 9;
DISPID_AUTOCOMPLETESAVEFORM = 10;
DISPID_AUTOSCAN = 11;
DISPID_AUTOCOMPLETEATTACH = 12;
DISPID_SHOWBROWSERUI = 13;
DISPID_SHELLUIHELPERLAST = 13;
DISPID_ADVANCEERROR = 10;
DISPID_RETREATERROR = 11;
DISPID_CANADVANCEERROR = 12;
DISPID_CANRETREATERROR = 13;
DISPID_GETERRORLINE = 14;
DISPID_GETERRORCHAR = 15;
DISPID_GETERRORCODE = 16;
DISPID_GETERRORMSG = 17;
DISPID_GETERRORURL = 18;
DISPID_GETDETAILSSTATE = 19;
DISPID_SETDETAILSSTATE = 20;
DISPID_GETPERERRSTATE = 21;
DISPID_SETPERERRSTATE = 22;
DISPID_GETALWAYSSHOWLOCKSTATE = 23;
// Dispatch IDS for ShellFavoritesNameSpace Dispatch Events.
//
DISPID_FAVSELECTIONCHANGE = 1;
DISPID_SELECTIONCHANGE = 2;
DISPID_DOUBLECLICK = 3;
DISPID_INITIALIZED = 4;
DISPID_MOVESELECTIONUP = 1;
DISPID_MOVESELECTIONDOWN = 2;
DISPID_RESETSORT = 3;
DISPID_NEWFOLDER = 4;
DISPID_SYNCHRONIZE = 5;
DISPID_IMPORT = 6;
DISPID_EXPORT = 7;
DISPID_INVOKECONTEXTMENU = 8;
DISPID_MOVESELECTIONTO = 9;
DISPID_SUBSCRIPTIONSENABLED = 10;
DISPID_CREATESUBSCRIPTION = 11;
DISPID_DELETESUBSCRIPTION = 12;
DISPID_SETROOT = 13;
DISPID_ENUMOPTIONS = 14;
DISPID_SELECTEDITEM = 15;
DISPID_ROOT = 16;
DISPID_DEPTH = 17;
DISPID_MODE = 18;
DISPID_FLAGS = 19;
DISPID_TVFLAGS = 20;
DISPID_NSCOLUMNS = 21;
DISPID_COUNTVIEWTYPES = 22;
DISPID_SETVIEWTYPE = 23;
DISPID_SELECTEDITEMS = 24;
DISPID_EXPAND = 25;
DISPID_UNSELECTALL = 26;
implementation
end.
|
{------------------------------------------------------------------------------
This file is part of the MotifMASTER project. This software is
distributed under GPL (see gpl.txt for details).
This software 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.
Copyright (C) 1999-2007 D.Morozov (dvmorozov@mail.ru)
------------------------------------------------------------------------------}
unit Runner;
{$IFDEF Lazarus}
{$MODE Delphi}
{$ENDIF}
interface
uses Classes,
{$IFNDEF Lazarus}
DsgnIntf,
{$ENDIF}
Tools;
type
TRunningProcedure = procedure of object;
TEndRunningProcedure = procedure of object;
TRunningThread = class(TThread)
public
RunningProcedure: TRunningProcedure;
EndRunningProcedure: TEndRunningProcedure;
procedure Execute; override;
end;
TRunner = class(TComponent)
protected
FOnRunningProcedure: TRunningProcedure;
FOnEndRunningProcedure: TEndRunningProcedure;
RunningThread: TRunningThread;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Run;
procedure Suspend;
procedure Resume;
procedure Synchronize(AProcedure: TThreadMethod);
published
property OnRunningProcedure: TRunningProcedure
read FOnRunningProcedure write FOnRunningProcedure;
property OnEndRunningProcedure: TEndRunningProcedure
read FOnEndRunningProcedure write FOnEndRunningProcedure;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Common',[TRunner]);
{$IFNDEF Lazarus}
RegisterPropertyEditor(TypeInfo(TRunningProcedure),TRunner,'OnRunningProcedure',TMethodProperty);
RegisterPropertyEditor(TypeInfo(TEndRunningProcedure),TRunner,'OnEndRunningProcedure',TMethodProperty);
{$ENDIF}
end;
procedure TRunningThread.Execute;
begin
if Assigned(RunningProcedure) then RunningProcedure;
if (not Terminated) and Assigned(EndRunningProcedure) then EndRunningProcedure;
end;
constructor TRunner.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
RunningThread := TRunningThread.Create(True);
end;
destructor TRunner.Destroy;
begin
UtilizeObject(RunningThread);
inherited Destroy;
end;
procedure TRunner.Run;
begin
RunningThread.RunningProcedure := OnRunningProcedure;
RunningThread.EndRunningProcedure := OnEndRunningProcedure;
RunningThread.Resume;
end;
procedure TRunner.Suspend;
begin
RunningThread.Suspend;
end;
procedure TRunner.Resume;
begin
RunningThread.Resume;
end;
procedure TRunner.Synchronize;
begin
RunningThread.Synchronize(AProcedure);
end;
end.
|
{------------------------------------------------------------------------------
TDzDirSeek component
Developed by Rodrigo Depiné Dalpiaz (digão dalpiaz)
Non visual component to search files in directories
https://github.com/digao-dalpiaz/DzDirSeek
Please, read the documentation at GitHub link.
------------------------------------------------------------------------------}
unit DzDirSeek;
interface
uses System.Classes;
type
TDSResultKind = (rkComplete, rkRelative, rkOnlyName);
TDSMaskKind = (mkExceptions, mkInclusions);
TDzDirSeek = class(TComponent)
private
FDir: String;
FSubDir: Boolean;
FSorted: Boolean;
FResultKind: TDSResultKind;
FMaskKind: TDSMaskKind;
FUseMask: Boolean;
FMasks: TStrings;
FList: TStringList;
BaseDir: String;
procedure IntSeek(const RelativeDir: String);
function CheckMask(const aFile: String; IsDir: Boolean): Boolean;
function GetName(const RelativeDir, Nome: String): String;
procedure DoSort;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Seek;
property List: TStringList read FList;
published
property Dir: String read FDir write FDir;
property SubDir: Boolean read FSubDir write FSubDir default True;
property Sorted: Boolean read FSorted write FSorted default False;
property ResultKind: TDSResultKind read FResultKind write FResultKind default rkComplete;
property MaskKind: TDSMaskKind read FMaskKind write FMaskKind default mkExceptions;
property UseMask: Boolean read FUseMask write FUseMask default True;
property Masks: TStrings read FMasks write FMasks;
end;
function BytesToMB(X: Int64): String;
function GetFileSize(const aFileName: String): Int64;
procedure Register;
implementation
uses System.SysUtils, System.Masks, System.StrUtils;
procedure Register;
begin
RegisterComponents('Digao', [TDzDirSeek]);
end;
//
constructor TDzDirSeek.Create(AOwner: TComponent);
begin
inherited;
FSubDir := True;
FResultKind := rkComplete;
FMaskKind := mkExceptions;
FUseMask := True;
FMasks := TStringList.Create;
FList := TStringList.Create;
end;
destructor TDzDirSeek.Destroy;
begin
FMasks.Free;
FList.Free;
inherited;
end;
procedure TDzDirSeek.Seek;
begin
if not DirectoryExists(FDir) then
raise Exception.CreateFmt('Path "%s" not found', [FDir]);
BaseDir := IncludeTrailingPathDelimiter(FDir);
FList.Clear;
IntSeek('');
if FSorted then DoSort;
end;
procedure TDzDirSeek.IntSeek(const RelativeDir: String);
var Sr: TSearchRec;
function IntCheckMask(IsDir: Boolean): Boolean;
begin
Result := CheckMask(RelativeDir + Sr.Name, IsDir);
end;
begin
if FindFirst(BaseDir + RelativeDir + '*', faAnyFile, Sr) = 0 then
begin
repeat
if (Sr.Name = '.') or (Sr.Name = '..') then Continue;
if (Sr.Attr and faDirectory) <> 0 then
begin //directory
if FSubDir then //include sub-directories
begin
if IntCheckMask(True{Dir}) then
IntSeek(RelativeDir + Sr.Name + '\');
end;
end else
begin //file
if IntCheckMask(False) then
FList.Add(GetName(RelativeDir, Sr.Name));
end;
until FindNext(Sr) <> 0;
FindClose(Sr);
end;
end;
function TDzDirSeek.CheckMask(const aFile: String; IsDir: Boolean): Boolean;
type
TProps = (pOnlyFile);
TPropsSet = set of TProps;
function GetProps(var Mask: String): TPropsSet;
var Props: TPropsSet;
procedure CheckProp(const aProp: String; pProp: TProps);
var aIntProp: String;
begin
aIntProp := '<'+aProp+'>';
if Mask.Contains(aIntProp) then
begin
Include(Props, pProp);
Mask := StringReplace(Mask, aIntProp, '', []); //you should type parameter just once!
end;
end;
begin
Props := [];
CheckProp('F', pOnlyFile); //only file parameter
Result := Props;
end;
var
aPreMask, aMask: String;
P: TPropsSet;
Normal: Boolean; //not OnlyFile
begin
Result := False;
if not FUseMask then Exit(True);
if IsDir and (FMaskKind=mkInclusions) then Exit(True);
for aPreMask in FMasks do
begin
aMask := aPreMask;
P := GetProps(aMask);
Normal := not (pOnlyFile in P); //not OnlyFile
if ( Normal and MatchesMask(aFile, aMask) )
or ( (Normal or not IsDir) and MatchesMask(ExtractFileName(aFile), aMask) ) then
begin
Result := True;
Break;
end;
end;
if FMaskKind = mkExceptions then Result := not Result;
end;
function TDzDirSeek.GetName(const RelativeDir, Nome: String): String;
begin
case FResultKind of
rkComplete: Result := BaseDir + RelativeDir + Nome;
rkRelative: Result := RelativeDir + Nome;
rkOnlyName: Result := Nome;
end;
end;
// ============================================================================
function SortItem(List: TStringList; Index1, Index2: Integer): Integer;
var A1, A2: String;
Dir1, Dir2: String;
Name1, Name2: String;
begin
A1 := List[Index1];
A2 := List[Index2];
Dir1 := ExtractFilePath(A1);
Dir2 := ExtractFilePath(A2);
Name1 := ExtractFileName(A1);
Name2 := ExtractFileName(A2);
if Dir1 = Dir2 then
Result := AnsiCompareText(Name1, Name2)
else
Result := AnsiCompareText(Dir1, Dir2);
end;
procedure TDzDirSeek.DoSort;
begin
FList.CustomSort(SortItem);
end;
// ============================================================================
function BytesToMB(X: Int64): String;
begin
Result := FormatFloat('0.00 MB', X / 1024 / 1024);
end;
function GetFileSize(const aFileName: String): Int64;
var Sr: TSearchRec;
begin
if FindFirst(aFileName, faAnyFile, Sr) = 0 then
begin
Result := Sr.Size;
FindClose(Sr);
end
else raise Exception.CreateFmt('Could not get file size of "%s"', [aFileName]);
end;
end.
|
unit BrickCamp.Model.IAnswer;
interface
uses
Spring;
type
IAnswer = interface(IInterface)
['{22C4E548-5FBE-47FE-9138-5A96FFE3DDE0}']
function GetId: Integer;
function GetQuestionId: Integer;
function GetUserId: Integer;
function GetText: string;
function GetRankIndex: SmallInt;
procedure SetQuestionId(const Value: Integer);
procedure SetUserId(const Value: Integer);
procedure SetText(const Value: string);
procedure SetRankIndex(const Value: SmallInt);
end;
implementation
end.
|
unit HashUnit;
{ Hash Unit }
// Hash Algorithms : MD5, SHA-1
// Copyright (c) 2015 ChrisF
// Distributed under the terms of the MIT license: see LICENSE.txt
{$IFDEF FPC}
// {$MODE OBJFPC}{$H+}
{$MODE DELPHI}
{$ENDIF}
//------------------------------------------------------------------------------
interface
const
// Exported Constants for the MD5 Algo
MD5_BLOCK = 64; // Length for MD5 Block
MD5_NBRH = 4; // Number of H Variables
MD5_DIGESTSIZE = 16; // Size of Digest for MD5 (Number of Bytes)
// Exported Constants for the SHA-1 Algo
SHA1_BLOCK = 64; // Length for SHA-1 Block
SHA1_NBRH = 5; // Number of H Variables
SHA1_DIGESTSIZE = 20; // Size of Digest for SHA-1 (Number of Bytes)
type
MD5_CTX = record // Structure for MD5 Context
Num: longword;
Len: uint64;
H: array [0..Pred(MD5_NBRH)] of longword; // Hash buffers
Data: array [0..Pred(MD5_BLOCK)] of byte; // Input buffer
end;
type
SHA1_CTX = record // Structure for SHA-1 Context
Num: integer;
Len: uint64;
Data: array [0..Pred(SHA1_BLOCK)] of byte;
H: array [0..Pred(SHA1_NBRH)] of longword;
end;
procedure MD5Digest(const Data: array of byte; const DataLen: longword;
var Digest: array of byte);
procedure MD5Init(var MD5CTX: MD5_CTX);
procedure MD5Update(var MD5CTX: MD5_CTX; const Data: array of byte;
const DataLen: longword);
procedure MD5Final(var MD5CTX: MD5_CTX; var Digest: array of byte);
procedure SHA1Digest(const Data: array of byte; const DataLen: longword;
var Digest: array of byte);
procedure SHA1Init(var SHA1CTX: SHA1_CTX);
procedure SHA1Update(var SHA1CTX: SHA1_CTX; const Data: array of byte;
const DataLen: longword);
procedure SHA1Final(var SHA1CTX: SHA1_CTX; var Digest: array of byte);
//------------------------------------------------------------------------------
implementation
procedure ArrBLongLong(var Buffer: array of byte; const Posi: integer;
const Value: uint64); forward;
procedure ArrBLongLongInv(var Buffer: array of byte; const Posi: integer;
const Value: uint64); forward;
function LongArrB(const Buffer: array of byte; const Posi: integer): longword; forward;
function LongArrBInv(const Buffer: array of byte; const Posi: integer): longword;
forward;
procedure ArrBLong(var Buffer: array of byte; const Posi: integer;
const Value: longword); forward;
procedure ArrBLongInv(var Buffer: array of byte; const Posi: integer;
const Value: longword); forward;
{$IFDEF FPC}
{$MACRO ON}
{$DEFINE ROL:=ROLDWord}
{$DEFINE ROR:=RORDWord}
// {$ASMMODE INTEL} // Intel/AMD Processors by Default
{$ELSE}
{$DEFINE ENDIAN_LITTLE}// Assumes Delphi is always for Intel/AMD processors
function ROR(const InLong: longword; const Times: byte): longword; forward;
function ROL(const InLong: longword; const Times: byte): longword; forward;
{$ENDIF}
{$IFDEF PASJS}
function ROR(const InLong: longword; const Times: byte): longword; forward;
function ROL(const InLong: longword; const Times: byte): longword; forward;
Procedure Move(const source;var dest;count:{$ifdef MOVE_HAS_SIZEUINT_COUNT}SizeUInt{$else}SizeInt{$endif});
begin
end;
procedure MD5Body(var MD5CTX: MD5_CTX; const Data:array of byte;
const DataLen: longword); forward;
procedure SHA1Body(var SHA1CTX: SHA1_CTX; const Data:array of byte;
const DataLen: longword); forward;
{$ELSE}
procedure MD5Body(var MD5CTX: MD5_CTX; const Data: array of byte;
const DataLen: longword); forward;
procedure SHA1Body(var SHA1CTX: SHA1_CTX; const Data: array of byte;
const DataLen: longword); forward;
{$ENDIF}
const
// Constants for the MD5 Algo
MD5_BLOCKP2 = 6; // Power of 2 for Length for MD5 Block
// Constants for the SHA-1 Algo
SHA1_BLOCKP2 = 6; // Power of 2 for Length for SHA-1 Block
SHA1_WSIZE = 80; // Size of W Block
//------------------------------------------------------------------------------
// MD5 : Only for Bytes Message (Not Bits) - Limited to (2^61)-1 Bytes (i.e. (2^64)-1 Bits)
// MD5 General Call : Limited to (2^32)-1 Bytes
procedure MD5Digest(const Data: array of byte; const DataLen: longword;
var Digest: array of byte);
var
LocalMD5CTX: MD5_CTX;
begin
MD5Init(LocalMD5CTX);
MD5Update(LocalMD5CTX, Data, DataLen);
MD5Final(LocalMD5CTX, Digest);
end;
// MD5 Initializations
procedure MD5Init(var MD5CTX: MD5_CTX);
const
KI: array [0..Pred(MD5_NBRH)] of longword =
($67452301, $EFCDAB89, $98BADCFE, $10325476);
// Constants defined for MD5
var
i1: integer;
begin
MD5CTX.Num := 0;
MD5CTX.Len := 0;
for i1 := 0 to Pred(MD5_NBRH) do MD5CTX.H[i1] := KI[i1];
end;
// MD5 Add Data : Limited to (2^32)-1 Bytes per Call
procedure MD5Update(var MD5CTX: MD5_CTX; const Data: array of byte;
const DataLen: longword);
var
i1, i2, i3, i4: longword;
var
j1: uint64;
begin
if DataLen = 0 then Exit; // Sanity
j1 := uint64(DataLen);
MD5CTX.Len := MD5CTX.Len + j1;
i4 := 0; // Initial Position in Data Buffer
i3 := DataLen; // Initial Data Buffer Length
i1 := MD5CTX.Num;
if i1 <> 0 then // Have Some Previous Unprocessed Data ?
begin
j1 := uint64(i1);
j1 := j1 + uint64(i3);
if j1 < uint64(MD5_BLOCK) then
// Still a Partial Block (Not Enough for a Full Block)
begin
{$IFNDEF PASJS}
Move(Data, MD5CTX.Data[i1], i3);
{$ENDIF}
MD5CTX.Num := i1 + i3;
Exit;
end
else // At Least a Full Block (or More)
begin
i2 := MD5_BLOCK - i1;
{$IFNDEF PASJS}
Move(Data, MD5CTX.Data[i1], i2);
{$ENDIF}
Dec(i3, i2);
Inc(i4, i2);
MD5CTX.Num := 0;
MD5Body(MD5CTX, MD5CTX.Data, MD5_BLOCK);
MD5Body(MD5CTX, MD5CTX.Data, MD5_BLOCK);
end;
end;
i1 := i3 and (not Pred(MD5_BLOCK));
// Number of Bytes for Full Block(s) Only (Because MD5_BLOCK is a Power of 2)
{$IFNDEF PASJS}
if i1 <> 0 then
MD5Body(MD5CTX, Data[i4], i1);
{$ENDIF}
Dec(i3, i1);
if i3 <> 0 then // Still some Data ?
{$IFNDEF PASJS}
Move(Data[i4 + i1], MD5CTX.Data[0], i3);
// Store Them for the Next Call
{$ELSE}
;
{$ENDIF}
MD5CTX.Num := i3;
end;
// MD5 Final Digest
procedure MD5Final(var MD5CTX: MD5_CTX; var Digest: array of byte);
var
i1: integer;
begin
i1 := MD5CTX.Num;
{$IFNDEF PASJS}
FillChar(MD5CTX.Data[i1], MD5_BLOCK - i1, 0);
{$ELSE}
;
{$ENDIF}
if i1 < MD5_BLOCK then MD5CTX.Data[i1] := $80;
// Bit 1 just after the Data (if possible)
if i1 > MD5_BLOCK - Succ(8) then
// Too much Previous Unprocessed Data To Add Full Data Length ?
begin
MD5Body(MD5CTX, MD5CTX.Data, MD5_BLOCK);
{$IFNDEF PASJS}
FillChar(MD5CTX.Data, MD5_BLOCK, 0);
{$ELSE}
;
{$ENDIF}
if i1 = MD5_BLOCK then MD5CTX.Data[0] := $80;
// Bit 1 just after the Data (if not possible in previous block)
end;
// Add Length
ArrBLongLongInv(MD5CTX.Data, MD5_BLOCK - 8, MD5CTX.Len shl 3); // Size in Bits
MD5Body(MD5CTX, MD5CTX.Data, MD5_BLOCK);
// Return 16 Bytes From H Buffers
for i1 := 0 to Pred(MD5_NBRH) do
ArrBLongInv(Digest, i1 shl 2, MD5CTx.H[i1]);
end;
// MD5 Main Algo (Partially Unrolled Version)
procedure MD5Body(var MD5CTX: MD5_CTX; const Data: array of byte;
const DataLen: longword);
const
MD5_TRSF: array [0..Pred(64)] of longword = ( // Array for the MD5 Transformation
$D76AA478, $E8C7B756, $242070DB, $C1BDCEEE, $F57C0FAF,
$4787C62A, $A8304613, $FD469501,
$698098D8, $8B44F7AF, $FFFF5BB1, $895CD7BE, $6B901122,
$FD987193, $A679438E, $49B40821,
$F61E2562, $C040B340, $265E5A51, $E9B6C7AA, $D62F105D,
$02441453, $D8A1E681, $E7D3FBC8,
$21E1CDE6, $C33707D6, $F4D50D87, $455A14ED, $A9E3E905,
$FCEFA3F8, $676F02D9, $8D2A4C8A,
$FFFA3942, $8771F681, $6D9D6122, $FDE5380C, $A4BEEA44,
$4BDECFA9, $F6BB4B60, $BEBFBC70,
$289B7EC6, $EAA127FA, $D4EF3085, $04881D05, $D9D4D039,
$e6DB99E5, $1fA27CF8, $C4AC5665,
$F4292244, $432AFF97, $AB9423A7, $FC93A039, $655B59C3,
$8F0CCC92, $FFEFF47D, $85845DD1,
$6FA87E4F, $FE2CE6E0, $A3014314, $4E0811A1, $F7537E82,
$BD3AF235, $2AD7D2BB, $EB86D391);
var
DataIn: array [0..Pred(16)] of longword;
var
a, b, c, d: longword;
var
i1, i2: integer;
begin
if DataLen = 0 then Exit; // Sanity
for i1 := 0 to Pred(DataLen shr MD5_BLOCKP2) do
begin
a := MD5CTX.H[0];
b := MD5CTX.H[1];
c := MD5CTX.H[2];
d := MD5CTX.H[3];
for i2 := 0 to Pred(16) do
DataIn[i2] := LongArrBInv(Data, (i1 shl MD5_BLOCKP2) + (i2 shl 2));
// MD5 Core (4 rounds)
Inc(a, DataIn[00] + MD5_TRSF[00] + (d xor (b and (c xor d))));
a := ROL(a, 07) + b;
Inc(d, DataIn[01] + MD5_TRSF[01] + (c xor (a and (b xor c))));
d := ROL(d, 12) + a;
Inc(c, DataIn[02] + MD5_TRSF[02] + (b xor (d and (a xor b))));
c := ROL(c, 17) + d;
Inc(b, DataIn[03] + MD5_TRSF[03] + (a xor (c and (d xor a))));
b := ROL(b, 22) + c;
Inc(a, DataIn[04] + MD5_TRSF[04] + (d xor (b and (c xor d))));
a := ROL(a, 07) + b;
Inc(d, DataIn[05] + MD5_TRSF[05] + (c xor (a and (b xor c))));
d := ROL(d, 12) + a;
Inc(c, DataIn[06] + MD5_TRSF[06] + (b xor (d and (a xor b))));
c := ROL(c, 17) + d;
Inc(b, DataIn[07] + MD5_TRSF[07] + (a xor (c and (d xor a))));
b := ROL(b, 22) + c;
Inc(a, DataIn[08] + MD5_TRSF[08] + (d xor (b and (c xor d))));
a := ROL(a, 07) + b;
Inc(d, DataIn[09] + MD5_TRSF[09] + (c xor (a and (b xor c))));
d := ROL(d, 12) + a;
Inc(c, DataIn[10] + MD5_TRSF[10] + (b xor (d and (a xor b))));
c := ROL(c, 17) + d;
Inc(b, DataIn[11] + MD5_TRSF[11] + (a xor (c and (d xor a))));
b := ROL(b, 22) + c;
Inc(a, DataIn[12] + MD5_TRSF[12] + (d xor (b and (c xor d))));
a := ROL(a, 07) + b;
Inc(d, DataIn[13] + MD5_TRSF[13] + (c xor (a and (b xor c))));
d := ROL(d, 12) + a;
Inc(c, DataIn[14] + MD5_TRSF[14] + (b xor (d and (a xor b))));
c := ROL(c, 17) + d;
Inc(b, DataIn[15] + MD5_TRSF[15] + (a xor (c and (d xor a))));
b := ROL(b, 22) + c;
Inc(a, DataIn[01] + MD5_TRSF[16] + (c xor (d and (b xor c))));
a := ROL(a, 05) + b;
Inc(d, DataIn[06] + MD5_TRSF[17] + (b xor (c and (a xor b))));
d := ROL(d, 09) + a;
Inc(c, DataIn[11] + MD5_TRSF[18] + (a xor (b and (d xor a))));
c := ROL(c, 14) + d;
Inc(b, DataIn[00] + MD5_TRSF[19] + (d xor (a and (c xor d))));
b := ROL(b, 20) + c;
Inc(a, DataIn[05] + MD5_TRSF[20] + (c xor (d and (b xor c))));
a := ROL(a, 05) + b;
Inc(d, DataIn[10] + MD5_TRSF[21] + (b xor (c and (a xor b))));
d := ROL(d, 09) + a;
Inc(c, DataIn[15] + MD5_TRSF[22] + (a xor (b and (d xor a))));
c := ROL(c, 14) + d;
Inc(b, DataIn[04] + MD5_TRSF[23] + (d xor (a and (c xor d))));
b := ROL(b, 20) + c;
Inc(a, DataIn[09] + MD5_TRSF[24] + (c xor (d and (b xor c))));
a := ROL(a, 05) + b;
Inc(d, DataIn[14] + MD5_TRSF[25] + (b xor (c and (a xor b))));
d := ROL(d, 09) + a;
Inc(c, DataIn[03] + MD5_TRSF[26] + (a xor (b and (d xor a))));
c := ROL(c, 14) + d;
Inc(b, DataIn[08] + MD5_TRSF[27] + (d xor (a and (c xor d))));
b := ROL(b, 20) + c;
Inc(a, DataIn[13] + MD5_TRSF[28] + (c xor (d and (b xor c))));
a := ROL(a, 05) + b;
Inc(d, DataIn[02] + MD5_TRSF[29] + (b xor (c and (a xor b))));
d := ROL(d, 09) + a;
Inc(c, DataIn[07] + MD5_TRSF[30] + (a xor (b and (d xor a))));
c := ROL(c, 14) + d;
Inc(b, DataIn[12] + MD5_TRSF[31] + (d xor (a and (c xor d))));
b := ROL(b, 20) + c;
Inc(a, DataIn[05] + MD5_TRSF[32] + (b xor c xor d));
a := ROL(a, 04) + b;
Inc(d, DataIn[08] + MD5_TRSF[33] + (a xor b xor c));
d := ROL(d, 11) + a;
Inc(c, DataIn[11] + MD5_TRSF[34] + (d xor a xor b));
c := ROL(c, 16) + d;
Inc(b, DataIn[14] + MD5_TRSF[35] + (c xor d xor a));
b := ROL(b, 23) + c;
Inc(a, DataIn[01] + MD5_TRSF[36] + (b xor c xor d));
a := ROL(a, 04) + b;
Inc(d, DataIn[04] + MD5_TRSF[37] + (a xor b xor c));
d := ROL(d, 11) + a;
Inc(c, DataIn[07] + MD5_TRSF[38] + (d xor a xor b));
c := ROL(c, 16) + d;
Inc(b, DataIn[10] + MD5_TRSF[39] + (c xor d xor a));
b := ROL(b, 23) + c;
Inc(a, DataIn[13] + MD5_TRSF[40] + (b xor c xor d));
a := ROL(a, 04) + b;
Inc(d, DataIn[00] + MD5_TRSF[41] + (a xor b xor c));
d := ROL(d, 11) + a;
Inc(c, DataIn[03] + MD5_TRSF[42] + (d xor a xor b));
c := ROL(c, 16) + d;
Inc(b, DataIn[06] + MD5_TRSF[43] + (c xor d xor a));
b := ROL(b, 23) + c;
Inc(a, DataIn[09] + MD5_TRSF[44] + (b xor c xor d));
a := ROL(a, 04) + b;
Inc(d, DataIn[12] + MD5_TRSF[45] + (a xor b xor c));
d := ROL(d, 11) + a;
Inc(c, DataIn[15] + MD5_TRSF[46] + (d xor a xor b));
c := ROL(c, 16) + d;
Inc(b, DataIn[02] + MD5_TRSF[47] + (c xor d xor a));
b := ROL(b, 23) + c;
Inc(a, DataIn[00] + MD5_TRSF[48] + (c xor (b or (not d))));
a := ROL(a, 06) + b;
Inc(d, DataIn[07] + MD5_TRSF[49] + (b xor (a or (not c))));
d := ROL(d, 10) + a;
Inc(c, DataIn[14] + MD5_TRSF[50] + (a xor (d or (not b))));
c := ROL(c, 15) + d;
Inc(b, DataIn[05] + MD5_TRSF[51] + (d xor (c or (not a))));
b := ROL(b, 21) + c;
Inc(a, DataIn[12] + MD5_TRSF[52] + (c xor (b or (not d))));
a := ROL(a, 06) + b;
Inc(d, DataIn[03] + MD5_TRSF[53] + (b xor (a or (not c))));
d := ROL(d, 10) + a;
Inc(c, DataIn[10] + MD5_TRSF[54] + (a xor (d or (not b))));
c := ROL(c, 15) + d;
Inc(b, DataIn[01] + MD5_TRSF[55] + (d xor (c or (not a))));
b := ROL(b, 21) + c;
Inc(a, DataIn[08] + MD5_TRSF[56] + (c xor (b or (not d))));
a := ROL(a, 06) + b;
Inc(d, DataIn[15] + MD5_TRSF[57] + (b xor (a or (not c))));
d := ROL(d, 10) + a;
Inc(c, DataIn[06] + MD5_TRSF[58] + (a xor (d or (not b))));
c := ROL(c, 15) + d;
Inc(b, DataIn[13] + MD5_TRSF[59] + (d xor (c or (not a))));
b := ROL(b, 21) + c;
Inc(a, DataIn[04] + MD5_TRSF[60] + (c xor (b or (not d))));
a := ROL(a, 06) + b;
Inc(d, DataIn[11] + MD5_TRSF[61] + (b xor (a or (not c))));
d := ROL(d, 10) + a;
Inc(c, DataIn[02] + MD5_TRSF[62] + (a xor (d or (not b))));
c := ROL(c, 15) + d;
Inc(b, DataIn[09] + MD5_TRSF[63] + (d xor (c or (not a))));
b := ROL(b, 21) + c;
Inc(MD5CTX.H[0], a);
Inc(MD5CTX.H[1], b);
Inc(MD5CTX.H[2], c);
Inc(MD5CTX.H[3], d);
end;
end;
//------------------------------------------------------------------------------
// SHA-1 : Only for Bytes Message (Not Bits) - Limited to (2^61)-1 Bytes (i.e. (2^64)-1 Bits)
// SHA-1 General Call : Limited to (2^32)-1 Bytes
procedure SHA1Digest(const Data: array of byte; const DataLen: longword;
var Digest: array of byte);
var
LocalSHA1CTX: SHA1_CTX;
begin
SHA1Init(LocalSHA1CTX);
SHA1Update(LocalSHA1CTX, Data, DataLen);
SHA1Final(LocalSHA1CTX, Digest);
end;
// SHA-1 Initializations
procedure SHA1Init(var SHA1CTX: SHA1_CTX);
const
KI: array [0..Pred(SHA1_NBRH)] of longword =
($67452301, $EFCDAB89, $98BADCFE, $10325476, $C3D2E1F0);
// Constants defined for SHA-1
var
i1: integer;
begin
SHA1CTX.Num := 0;
SHA1CTX.Len := 0;
for i1 := 0 to Pred(SHA1_NBRH) do SHA1CTX.H[i1] := KI[i1];
end;
// SHA-1 Add Data : Limited to (2^32)-1 Bytes per Call
procedure SHA1Update(var SHA1CTX: SHA1_CTX; const Data: array of byte;
const DataLen: longword);
var
i1, i2, i3, i4: longword;
var
j1: uint64;
begin
if DataLen = 0 then Exit; // Sanity
j1 := uint64(DataLen);
SHA1CTX.Len := SHA1CTX.Len + j1;
i4 := 0; // Initial Position in Data Buffer
i3 := DataLen; // Initial Data Buffer Length
i1 := SHA1CTX.Num;
if i1 <> 0 then // Have Some Previous Unprocessed Data ?
begin
j1 := uint64(i1);
j1 := j1 + uint64(i3);
if j1 < uint64(SHA1_BLOCK) then
// Still a Partial Block (Not Enough for a Full Block)
begin
Move(Data, SHA1CTX.Data[i1], i3);
SHA1CTX.Num := i1 + i3;
Exit;
end
else // At Least a Full Block (or More)
begin
i2 := SHA1_BLOCK - i1;
Move(Data, SHA1CTX.Data[i1], i2);
Dec(i3, i2);
Inc(i4, i2);
SHA1CTX.Num := 0;
{$IFNDEF PASJS}SHA1Body(SHA1CTX, SHA1CTX.Data, SHA1_BLOCK);{$ENDIF}
end;
end;
i1 := i3 and (not Pred(SHA1_BLOCK));
// Number of Bytes for Full Block(s) Only (Because SHA1_BLOCK is a Power of 2)
{$IFNDEF PASJS} if i1 <> 0 then // One or More Full Block(s) to Process
SHA1Body(SHA1CTX, Data[i4], i1);{$ENDIF}
Dec(i3, i1);
if i3 <> 0 then // Still some Data ?
Move(Data[i4 + i1], SHA1CTX.Data[0], i3); // Store Them for the Next Call
SHA1CTX.Num := i3;
end;
// SHA-1 Final Digest
procedure SHA1Final(var SHA1CTX: SHA1_CTX; var Digest: array of byte);
var
i1: integer;
begin
i1 := SHA1CTX.Num;
{$IFNDEF PASJS}FillChar(SHA1CTX.Data[i1], SHA1_BLOCK - i1, 0);{$ENDIF}
if i1 < SHA1_BLOCK then SHA1CTX.Data[i1] := $80;
// Bit 1 just after the Data (if possible)
if i1 > SHA1_BLOCK - Succ(8) then
// Too much Previous Unprocessed Data To Add Full Data Length ?
begin
{$IFNDEF PASJS} SHA1Body(SHA1CTX, SHA1CTX.Data, SHA1_BLOCK);
FillChar(SHA1CTX.Data, SHA1_BLOCK, 0);
{$ENDIF}
if i1 = SHA1_BLOCK then SHA1CTX.Data[0] := $80;
// Bit 1 just after the Data (if not possible in previous block)
end;
// Add Length
ArrBLongLong(SHA1CTX.Data, SHA1_BLOCK - 8, SHA1CTX.Len shl 3); // Size in Bits
{$IFNDEF PASJS} SHA1Body(SHA1CTX, SHA1CTX.Data, SHA1_BLOCK);{$ENDIF}
// Return 20 Bytes From H Buffers
for i1 := 0 to Pred(SHA1_NBRH) do
ArrBLong(Digest, i1 shl 2, SHA1CTX.H[i1]);
end;
// SHA-1 Main Algo
procedure SHA1Body(var SHA1CTX: SHA1_CTX; const Data: array of byte;
const DataLen: longword);
const
K: array [0..Pred(4)] of longword = ($5A827999, $6ED9EBA1, $8F1BBCDC, $CA62C1D6);
// Constants defined for SHA-1
var
W: array [0..Pred(SHA1_WSIZE)] of longword; // Word sequence
var
T: longword; // Temporary Word value
var
A, B, C, D, E: longword; // Word buffers
var
i1, i2: integer;
begin
if DataLen = 0 then Exit; // Sanity
// Proceed all Blocks
for i1 := 0 to Pred(DataLen shr SHA1_BLOCKP2) do
begin
// Initialize first 16 words in array W
for i2 := 0 to Pred(16) do
W[i2] := LongArrB(Data, (i1 shl SHA1_BLOCKP2) + (i2 shl 2));
// Compute others words in array W
for i2 := 16 to Pred(SHA1_WSIZE) do
begin
T := W[i2 - 3] xor W[i2 - 8] xor W[i2 - 14] xor W[i2 - 16];
W[i2] := (T shl 1) or (T shr 31);
end;
// Copy from H Buffer
A := SHA1CTX.H[0];
B := SHA1CTX.H[1];
C := SHA1CTX.H[2];
D := SHA1CTX.H[3];
E := SHA1CTX.H[4];
// Run Logical Functions
for i2 := 0 to Pred(SHA1_WSIZE) do
begin
T := (A shl 5) or (A shr 27);
case i2 of
00..19:
T := T + ((B and C) or ((not B) and D)) + E + W[i2] + K[0];
20..39:
T := T + (B xor C xor D) + E + W[i2] + K[1];
40..59:
T := T + ((B and C) or (B and D) or (C and D)) + E + W[i2] + K[2];
60..79:
T := T + (B xor C xor D) + E + W[i2] + K[3];
end;
E := D;
D := C;
C := (B shl 30) or (B shr 2);
B := A;
A := T;
end;
// Update H Buffer
Inc(SHA1CTX.H[0], A);
Inc(SHA1CTX.H[1], B);
Inc(SHA1CTX.H[2], C);
Inc(SHA1CTX.H[3], D);
Inc(SHA1CTX.H[4], E);
end;
end;
//------------------------------------------------------------------------------
procedure ArrBLongLong(var Buffer: array of byte; const Posi: integer;
const Value: uint64);
begin
Buffer[Posi] := Value shr 56;
Buffer[Posi + 1] := Value shr 48;
Buffer[Posi + 2] := Value shr 40;
Buffer[Posi + 3] := Value shr 32;
Buffer[Posi + 4] := Value shr 24;
Buffer[Posi + 5] := Value shr 16;
Buffer[Posi + 6] := Value shr 8;
Buffer[Posi + 7] := Value;
end;
procedure ArrBLongLongInv(var Buffer: array of byte; const Posi: integer;
const Value: uint64);
begin
{$IFDEF ENDIAN_LITTLE}
PLongword(@Buffer[Posi + 4])^ := Value shr 32;
PLongword(@Buffer[Posi])^ := Value;
{$ELSE}
Buffer[Posi+7]:=Value shr 56;
Buffer[Posi+6]:=Value shr 48;
Buffer[Posi+5]:=Value shr 40;
Buffer[Posi+4]:=Value shr 32;
Buffer[Posi+3]:=Value shr 24;
Buffer[Posi+2]:=Value shr 16;
Buffer[Posi+1]:=Value shr 8;
Buffer[Posi]:=Value;
{$ENDIF}
end;
function LongArrB(const Buffer: array of byte; const Posi: integer): longword;
begin
Result := (Buffer[Posi] shl 24) or (Buffer[Posi + 1] shl 16) or
(Buffer[Posi + 2] shl 8) or Buffer[Posi + 3];
end;
function LongArrBInv(const Buffer: array of byte; const Posi: integer): longword;
begin
{$IFDEF ENDIAN_LITTLE}
Result := PLongword(@Buffer[Posi])^;
{$ELSE}
Result:=(Buffer[Posi+3] shl 24) or (Buffer[Posi+2] shl 16) or (Buffer[Posi+1] shl 8) or Buffer[Posi];
{$ENDIF}
end;
procedure ArrBLong(var Buffer: array of byte; const Posi: integer;
const Value: longword);
begin
Buffer[Posi] := Value shr 24;
Buffer[Posi + 1] := Value shr 16;
Buffer[Posi + 2] := Value shr 8;
Buffer[Posi + 3] := Value;
end;
procedure ArrBLongInv(var Buffer: array of byte; const Posi: integer;
const Value: longword);
begin
{$IFDEF ENDIAN_LITTLE}
PLongword(@Buffer[Posi])^ := Value;
{$ELSE}
Buffer[Posi+3]:=Value shr 24;
Buffer[Posi+2]:=Value shr 16;
Buffer[Posi+1]:=Value shr 8;
Buffer[Posi]:=Value;
{$ENDIF}
end;
// Additional Functions
{$IFDEF FPC}
{$IFDEF PASJS}
function ROR(const InLong: longword; const Times: byte): longword;
begin
end;
function ROL(const InLong: longword; const Times: byte): longword;
begin
end;
{$ENDIF}
{$ELSE}
function ROR(const InLong: longword; const Times: byte): longword;
asm
MOV EAX, InLong
MOV CL, Times
ROR EAX, CL
end;
function ROL(const InLong: longword; const Times: byte): longword;
asm
MOV EAX, InLong
MOV CL, Times
ROL EAX, CL
end;
{$ENDIF}
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{*******************************************************}
{ DTD Translator for XML Schema }
{*******************************************************}
unit Xml.DTDSchema;
interface
uses System.SysUtils, System.Classes, Xml.XMLSchema, Xml.Xmldom;
type
{ TDTDBaseTranslator }
TDTDBaseTranslator = class(TXMLSchemaTranslator)
private
FDTDLines: TStrings;
protected
{ Data member access }
property DTDLines: TStrings read FDTDLines;
public
destructor Destroy; override;
procedure AfterConstruction; override;
end;
{ TDTDImportTranslator }
TDTDImportTranslator = class(TDTDBaseTranslator)
protected
function Expand(Dtd: string; var RootName: string; SrcPath: string): string;
procedure ExtractDtdParts(Str: string; StrBeg: string; StrEnd: string; Parts: TStrings);
procedure Parse(Dtd: string);
procedure ParseAttributeDefinitions(AttributeList: TStrings);
procedure ParseAttributeDefinition(AttrStr: string);
procedure ParseChildElements(ComplexDef: IXMLComplexTypeDef; ParentCompositors: IXMLElementCompositors; var Str: string);
procedure ParseElementDefinitions(ElementList: TStrings; ElementsWithAttributes: TStrings);
procedure ParseTokens(Str: string; Tokens: TStrings);
function PreParseChildElements(Str: string; var Suffix: string; var GroupType: string): string;
procedure PreparseAttributeDefinitions(AttributeList: TStrings; AttrDefs: TStrings);
procedure Translate(const FileName: DOMString; const SchemaDef: IXMLSchemaDef); override;
end;
const
DTDExtension = '.dtd';
implementation
uses Xml.XMLSchemaTags, Xml.XMLConst;
{ Utility Functions }
function LoadFile(const Name: string): string;
begin
with TStringList.Create do
try
LoadFromFile(Name);
Result:= Text;
finally
Free;
end;
end;
function Join(List: TStrings; Str: string): string;
var
I: Integer;
begin
if List.Count = 0 then
Result := Str
else
Result:= List[0];
for I := 1 to List.Count - 1 do
Result := Result + Str + List[I];
end;
procedure Split(Str: string; SubStr: string; List: TStrings);
var
I: Integer;
S, Tmp: string;
begin
List.Clear;
S := Str;
while Length(S) > 0 do
begin
I := Pos(SubStr, S);
if I = 0 then
begin
List.Add(S);
S := '';
end
else
begin
if I = 1 then
begin
List.Add('');
Delete(S, 1, Length(SubStr));
end
else
begin
Tmp := S;
Delete(Tmp, I, Length(Tmp));
List.Add(Tmp);
Delete(S, 1, I + Length(SubStr) - 1);
if Length(S) = 0 then
List.Add('');
end;
end;
end;
end;
function Head(Str: string; SubStr: string; var TailStr: string): string;
var
I: Integer;
begin
I := Pos(SubStr, Str);
if I = 0 then
begin
Result := Str;
TailStr := '';
end
else
begin
TailStr := Str;
Delete(TailStr, 1, I + Length(SubStr) - 1);
Delete(Str, I, Length(Str));
Result := Str;
end;
end;
function Tail(Str: string; SubStr: string): string;
var
I: Integer;
begin
I := Pos(SubStr, Str);
if I = 0 then
Result := ''
else
begin
Delete(Str, 1, I + Length(SubStr) - 1);
Result:= Str;
end;
end;
function Trim(Str: string): string;
var
Tokens: TStrings;
begin
if Length(Str) > 0 then
begin
Tokens := TStringList.Create;
try
// Replace end-of-line chars
Split(Str, #13, Tokens);
Str := Join(Tokens, ' ');
Split(Str, #10, Tokens);
Str := Join(Tokens, ' ');
Split(Str, #9, Tokens);
Str := Join(Tokens, ' ');
finally
Tokens.Free;
end;
while (Length(Str) > 0) and (Str[1] = ' ') do
Str := Tail(Str, ' '); //remove leading spaces
while (Length(Str) > 0) and (Str[Length(Str)]=' ') do
SetLength(Str, Length(Str) - 1);
while (Length(Str) > 0) and (Str[Length(Str)] = #0) do
SetLength(Str, Length(Str) - 1);
Result := Str;
end
else
Result := '';
end;
function ReadName(Str: string; var TailStr: string): string;
var
I: Integer;
Ch: Char;
begin
Str := Trim(Str);
Ch := ' ';
for I := 1 to Length(Str) do
begin
if CharInSet(Str[I], ['(','#',' ']) then
begin
Ch := Str[I];
Break;
end
end;
Str := Head(Str, Ch, TailStr);
if Ch <> ' ' then
TailStr := Ch + TailStr;
TailStr := Trim(TailStr);
Result := Trim(Str);
end;
function Replace(Str: string; FindStr: string; ReplaceStr: string): string;
begin
Result:= '';
while Pos(FindStr, Str) > 0 do
Result := Result + Head(Str, FindStr, Str) + ReplaceStr;
Result:= Result+ Str;
end;
function UnQuote(Str: string; const QuoteChar: string = '"'): string;
begin
Str:= Tail(Str, QuoteChar);
Result:= Head(Str, QuoteChar, Str);
end;
{ TDTDBaseTranslator }
procedure TDTDBaseTranslator.AfterConstruction;
begin
inherited;
FDTDLines := TStringList.Create;
end;
destructor TDTDBaseTranslator.Destroy;
begin
inherited;
FreeAndNil(FDTDLines);
end;
{ TDTDImportTranslator }
procedure TDTDImportTranslator.Translate(const FileName: DOMString;
const SchemaDef: IXMLSchemaDef);
var
Dtd: string;
Pathname, RootName: string;
Path: TStrings;
begin
inherited;
if FileName = '' then Exit;
DTDLines.LoadFromFile(FileName);
Dtd:= DTDLines.Text;
if Dtd = '' then exit;
Path := TStringList.Create;
try
Split(Filename, '\', Path);
Path[Path.count-1] := '';
PathName:= Join(Path, '\');
finally
Path.Free;
end;
Dtd:= Expand(Dtd, RootName, PathName);
Parse(Dtd);
end;
procedure TDTDImportTranslator.ExtractDtdParts(Str: string; StrBeg: string;
StrEnd: string; Parts: TStrings);
var
E, X: string;
begin
Parts.Clear;
while Length(Str) > 0 do
begin
X := Head(Str, StrBeg, Str); // s: "...<!ELEMENT xx yy > ... " -> " xx yy > ..."
if Length(Str) > 0 then
begin
E := Head(Str, StrEnd, Str); // e: " xx yy " , s: "...."
Trim(E);
if Length(E) > 0 then
Parts.Add(E);
end;
end;
end;
function TDTDImportTranslator.Expand(Dtd: string; var RootName:
string; SrcPath: string): string;
function SubstituteEntities(Str: string; EntityList: TStrings;
var IncFile: Boolean; SrcPath: string): string;
var
I: Integer;
Entity, EntityName: string;
IncludeFile, ReplaceString, Tmp: string;
begin
for I := 0 to EntityList.Count-1 do
begin
Entity := EntityList[I];
Entity := Tail(Entity, '%');
EntityName := ReadName(Entity, ReplaceString);
if Pos('SYSTEM', Entity) > 0 then
begin
Includefile := Tail(EntityList[I], 'SYSTEM');
Includefile := Tail(IncludeFile,'"');
Includefile := Head(IncludeFile,'"', Tmp);
ReplaceString := LoadFile(SrcPath + IncludeFile);
Str := Replace(Str, EntityList[I], ' ');
Incfile := True;
end
else
begin
ReplaceString := Tail(ReplaceString, '"');
ReplaceString := Head(ReplaceString, '"', Tmp);
end;
Str := Replace(Str, '%'+EntityName+';', ' '+ReplaceString+' ');
end;
Result := Str;
end;
var
EntityList, ElementList, DocList: TStrings;
Str, Tmp : string;
More : Boolean;
begin
try
Str := Dtd;
DocList := TStringList.Create;
try
ExtractDtdParts(Dtd, '<!DOCTYPE', ']>', DocList);
if (DocList.Count = 0) and (Rootname= '') then
begin
Str := Dtd;
//Assume first element is the root
ElementList := TStringList.Create;
try
ExtractDtdParts(Str, '<!ELEMENT', '>', ElementList);
if ElementList.count > 0 then
RootName :=ReadName(ElementList[0], Tmp);
finally
ElementList.Free;
end;
end
else
begin
if DocList.Count <> 0 then
begin
Str := DocList[0];
RootName := Trim(Head(Str, '[', Str));
RootName := Trim(RootName);
end;
end;
More := True;
while More do
begin
More := False;
EntityList := TStringList.Create;
try
ExtractDtdParts(Str, '<!ENTITY', '>', EntityList);
if EntityList.count > 0 then //substitute
repeat
Tmp := Str;
Str := SubstituteEntities(Str, EntityList, More, Srcpath);
until Tmp = Str;
finally
EntityList.Free;
end;
end;
Result := Str;
finally
DocList.Free;
end;
except
Result := '';
end;
end;
//parse an expanded dtd-string into a nodeinfo-list
procedure TDTDImportTranslator.Parse(Dtd: string);
var
ElementDefinitionList,
AttributeDefinitionList,
ElementsWithAttributes: TStrings;
begin
AttributeDefinitionList := nil;
ElementsWithAttributes := nil;
ElementDefinitionList := nil;
try
ElementDefinitionList := TStringList.Create;
ElementsWithAttributes := TStringList.Create;
AttributeDefinitionList := TStringList.Create;
Extractdtdparts(Dtd, '<!ELEMENT', '>', ElementDefinitionList);
Extractdtdparts(Dtd, '<!ATTLIST', '>', AttributeDefinitionList);
PreparseAttributeDefinitions(AttributeDefinitionList, ElementsWithAttributes);
ParseElementDefinitions(ElementDefinitionList, ElementsWithAttributes);
ParseAttributeDefinitions(AttributeDefinitionList);
finally
ElementDefinitionList.Free;
AttributeDefinitionList.Free;
ElementsWithAttributes.Free;
end;
end;
function TDTDImportTranslator.PreParseChildElements(Str: string; var Suffix: string; var GroupType: string ): string;
var
I: integer;
Ch: Char;
More: boolean;
Suffix1, GroupType1: string;
begin
GroupType := '';
Suffix := '';
Str := Tail(Str, '('); //Remove beginning parenthesis
More := True;
while More do
begin
for I := 1 to Length(Str) do
begin
Ch := Str[I];
if Ch = ')' then
begin //Terminating
Str := Tail(Str, Ch);
if Length(Str)> 0 then
begin
Ch := Str[1]; //Should ignore whitespaces
if CharInSet(Ch, ['?','*','+']) then
begin
Suffix := Ch;
Str := Tail(Str, Ch);
end;
end;
More := False;
break;
end else
if Ch = '(' then
begin
Str := PreParseChildElements(Str, Suffix1, GroupType1);
break;
end else
if Ch = '|' then
begin
GroupType := '|';
Str := Tail(Str, '|');
break;
end else
if Ch = ',' then
begin
GroupType := ',';
Str := Tail(Str, ',');
break;
end;
end; //for I
if Length(Str) = 0 then
More := False;
end; //while
Result := Str;
end;
procedure TDTDImportTranslator.ParseElementDefinitions(ElementList: TStrings;
ElementsWithAttributes: TStrings);
var
I: Integer;
ElementStr: string;
Name, XsdType: string;
PcData: Boolean;
ComplexType: IXMLComplexTypeDef;
HasAttributes: Boolean;
IsEmpty, IsAny: Boolean;
begin
for I := 0 to ElementList.Count-1 do
begin
ElementStr := ElementList[I];
//ElementStr := Replace(ElementStr, '(', ' (');
Name := ReadName(ElementStr, ElementStr);
if ElementsWithAttributes.IndexOf(Name) <> -1 then
HasAttributes := True else HasAttributes := False;
if Name='' then
continue
else
begin
if Pos('EMPTY', ElementStr)> 0 then IsEmpty := True else IsEmpty := False;
if Pos('ANY', ElementStr)> 0 then IsAny := True else IsAny := False;
if (Pos('(', ElementStr) > 0) or (IsEmpty) or (IsAny) then
begin
if Pos('#PCDATA', ElementStr) > 0 then PcData := True else PcData := False;
if ((PcData) or (IsEmpty)) and (not HasAttributes) then //and no attributes
begin
SchemaDef.ElementDefs.Add(Name, Name+'Type');
XsdType := xsdString;
SchemaDef.SimpleTypes.Add(Name+'Type', XsdType);
end
else
begin
SchemaDef.ElementDefs.Add(Name, Name+'Type');
ComplexType := SchemaDef.ComplexTypes.Add(Name+'Type');
ParseChildElements(ComplexType, nil, ElementStr);
end;
end
else
begin
SchemaDef.ElementDefs.Add(Name);
end;
end;
end;
end;
procedure TDTDImportTranslator.ParseTokens(Str: string; Tokens: TStrings);
var
I: Integer;
begin
Tokens.Clear;
Split(Str, ''#10, Tokens); // Replace end-of-line chars
Str := Join(Tokens, ' ');
Split(Str, ''#13, Tokens);
Str := Join(tokens, ' ');
Split(Str, ''#09, Tokens);
Str := Join(Tokens, ' ');
Split(Str, ' ', Tokens); //Divide using spaces
for I :=0 to Tokens.Count-1 do
Tokens[I] := Trim(Tokens[I]); // Trim for preceding/succeding spaces
for I := Tokens.Count-1 downto 0 do //Remove empty strings
if Tokens[I]='' then
Tokens.Delete(I);
end;
//Parse an <!ATTLIST ..> definition (including multiple definitions)
procedure TDTDImportTranslator.ParseAttributeDefinition(AttrStr: string);
var
K, I, CurToken: Integer;
ElementName, AttributeName, AttributeSample: string;
AttributeType, AttrType, AttributeDefault, AttributeFixed, AttributeOptions: string;
AttrToken, X: string;
Tokens: TStrings;
OList: TStrings;
AttributeRequired, More: Boolean;
MaxLength: Integer;
ComplexType: IXMLComplexTypeDef;
AttributeDef: IXMLAttributeDef;
begin
Tokens := TStringList.Create;
try
AttrStr := Head(AttrStr, '>', X);
AttrStr := Replace(AttrStr, '(', ' (');
ParseTokens(AttrStr, Tokens);
ElementName := Tokens[0];
ComplexType := SchemaDef.ComplexTypes.FindItem(ElementName+'Type') as IXMLComplexTypeDef;
if ComplexType = nil then Exit; ///Should not happen
CurToken := 1;
More := True;
while More do
begin
AttributeRequired := False;
AttributeFixed := '';
AttributeDefault := '';
AttributeOptions := '';
AttributeType := 'string';
if curtoken < tokens.count then
AttributeName := tokens[curtoken];
AttributeSample := '';
MaxLength := 0;
CurToken := CurToken+1;
if Tokens.Count > CurToken then
begin
AttrType := Tokens[CurToken];
CurToken := CurToken+1;
if Pos('(', AttrType)>0 then
begin
AttributeOptions := Tail(AttrType, '(');
while (Pos(')', AttrType) = 0) and (Tokens.Count> CurToken) do
begin //Reassemble options string
AttrType := Trim(Tokens[CurToken]);
AttributeOptions := AttributeOptions+ AttrType;
CurToken := CurToken+1;
end;
AttributeOptions := Head(AttributeOptions, ')', X);
OList := TStringList.Create;
try
Split(AttributeOptions, '|', OList);
for I := 0 to OList.Count-1 do
begin
AttrType := Trim(OList[I]);
if AttributeSample = '' then
AttributeSample := AttrType;
if Length(AttrType) > MaxLength then MaxLength := Length(AttrType);
OList[I] := AttrType;
end;
AttributeOptions := Join(OList,' ');
finally
OList.Free;
end;
end
else
if AttrType='CDATA' then
AttributeType := xsdString
else if AttrType='NOTATION' then
AttributeType := AttrType
else
//could be followed by options-list
AttributeType := AttrType;
end
else
AttributeType := xsdString;
if Tokens.Count > CurToken then
begin
AttrToken := Tokens[CurToken];
if AttrToken[1]= '#' then
begin
CurToken := CurToken+1;
if AttrToken= '#REQUIRED' then
AttributeRequired := True;
if AttrToken = '#FIXED' then
AttributeFixed := UnQuote(AttrToken);
if Tokens.Count > CurToken then
AttrToken := Tokens[CurToken];
end;
if CharInSet(AttrToken[1], ['"', '''']) then
begin
CurToken := CurToken+1;
AttributeDefault := UnQuote(AttrToken, AttrToken[1]);
end;
end;
if AttributeOptions <> '' then
begin
AttributeDef := ComplexType.AttributeDefs.Add(AttributeName, True, AttributeType);
OList := TStringList.Create;
try
Split(AttributeOptions, ' ', OList);
for K := 0 to OList.Count-1 do
AttributeDef.DataType.Enumerations.Add(OList[K]);
finally
OList.Free;
end;
end
else
AttributeDef := ComplexType.AttributeDefs.Add(AttributeName, AttributeType);
if AttributeDefault<> '' then
begin
AttributeDef.Default := AttributeDefault;
end;
if AttributeRequired then
AttributeDef.Use := SRequired;
if AttributeFixed <> '' then
begin
AttributeDef.Fixed := AttributeFixed;
end;
if Tokens.Count > CurToken then
begin //special case: Multiple attributes in one declaration
end
else
More := False;
end; //end while
finally
Tokens.Free;
end;
end;
procedure TDTDImportTranslator.ParseAttributeDefinitions(AttributeList: TStrings);
var
I: Integer;
begin
for I := 0 to AttributeList.Count-1 do
ParseAttributeDefinition(AttributeList[I]);
end;
procedure TDTDImportTranslator.PreparseAttributeDefinitions(AttributeList: TStrings; AttrDefs: TStrings);
var
I: Integer;
AttrStr: String;
Tokens: TStrings;
ElementName, X: String;
begin
AttrDefs.Clear;
for I := 0 to AttributeList.Count -1 do
begin
Tokens := TStringList.Create;
try
AttrStr := Head(AttributeList[I], '>', X);
ParseTokens(AttrStr, Tokens);
ElementName := Tokens[0];
if AttrDefs.IndexOf(ElementName) <> -1 then Continue;
AttrDefs.Add(ElementName);
finally
Tokens.Free;
end;
end;
end;
//Eats the string s, and generates a list of child-element names
procedure TDTDImportTranslator.ParseChildElements(ComplexDef: IXMLComplexTypeDef;
ParentCompositors: IXMLElementCompositors; var Str: string);
function RemoveSuffix(var name: string; RemoveAll: Boolean): Char;
var
X: string;
Ch: Char;
begin
if Name = '' then
begin
Result:= ' ';
exit;
end;
Ch := Name[Length(Name)];
if CharInSet(Ch, ['?','*','+','!', ')']) then
begin
if (Ch= ')') and (RemoveAll) then
Name := Trim(Head(Name, '(', X))
else
Name := Trim(Head(Name, Ch, X));
end
else if Pos('#', Name) > 0 then
Name := Trim(Head(Name, '#', X))
else if Pos('[', Name) > 0 then
Name := Trim(Head(Name, '#', X))
else
Ch := ' ';
Result := Ch;
end;
function IncStrProp(const Val: string): string;
begin
if CharInSet(Val[1], ['0'..'9']) then
Result := IntToStr(StrToInt(Val) + 1)
else
Result := Val;
end;
var
I: integer;
Name: string;
Ch: Char;
More: boolean;
ElementDefs: IXMLElementDefs;
ElementDef: IXMLElementDef;
Compositor: IXMLElementCompositor;
Suffix, GroupType: string;
NameSuffix: Char;
CompType: TCompositorType;
CountChildNames: Integer;
begin
CountChildNames := 0;
PreParseChildElements(Str, Suffix, GroupType);
if GroupType = '|' then
CompType := ctChoice else
CompType := ctSequence;
if (GroupType <> '') and ((Suffix <> '') or (GroupType = '|') or
(ComplexDef = nil)) then
begin
if ComplexDef = nil then
Compositor := ParentCompositors.Add(CompType)
else
Compositor := ComplexDef.ElementCompositors.Add(CompType);
if (Suffix <> '') and (Compositor <> nil) then
begin
if (Suffix = '?') or (Suffix = '*') then
Compositor.MinOccurs := '0';
if (Suffix = '*') or (Suffix = '+') then
Compositor.MaxOccurs := 'unbounded';
end;
ElementDefs := Compositor.ElementDefs;
end
else
begin
if ComplexDef <> nil then
begin
ElementDefs := ComplexDef.ElementDefs;
Compositor := nil;
end;
end;
Str := Tail(Str, '('); //Remove beginning parenthesis
More := True;
while More do
begin
for I := 1 to Length(Str) do
begin
Ch := Str[I];
if (Ch = ')') or (Ch = '|') or (Ch = ',') then
begin //Terminating
Name := Trim(Head(Str, Ch, Str));
NameSuffix := RemoveSuffix(Name, True);
if (Name <> '') and (Name <> '#PCDATA') and Assigned(ElementDefs) then
begin ///
ElementDef := ElementDefs.Find(Name);
if not Assigned(ElementDef) then
begin
ElementDef := ElementDefs.Add(Name);
CountChildNames := CountChildNames + 1;
if (Ch = ')') and (CountChildNames = 1) and not (CharInSet(NameSuffix, ['?','*','+'])) then
begin // (x)*
if Length(Str) > 0 then
begin
NameSuffix := Str[1];
Str := Tail(Str, NameSuffix);
end
else NameSuffix := ' ';
end;
if (CharInSet(NameSuffix, ['?','*','+'])) then
begin
if (NameSuffix = '?') or (NameSuffix = '*') then
ElementDef.MinOccurs := '0';
if (NameSuffix = '*') or (NameSuffix = '+') then
ElementDef.MaxOccurs := 'unbounded';
end;
end
else
begin
// Duplicate entries i.e. (StreetAddress, StreetAddress?, City ...
if NameSuffix = '' then
begin
ElementDef.MinOccurs := IncStrProp(ElementDef.MinOccurs);
ElementDef.MaxOccurs := IncStrProp(ElementDef.MaxOccurs);
end
else if (NameSuffix = '*') or (NameSuffix = '+') then
begin
ElementDef.MinOccurs := IncStrProp(ElementDef.MinOccurs);
ElementDef.MaxOccurs := 'unbounded';
end
else if (NameSuffix = '?') then
ElementDef.MaxOccurs := IncStrProp(ElementDef.MaxOccurs);
end;
end; ///
if Ch = ')' then
More := False;
break;
end else
if Ch = '(' then
begin
if Compositor <> nil then
ParseChildElements(nil, Compositor.Compositors, Str)
else
ParseChildElements(ComplexDef, nil, Str);
break;
end;
end; //for I
if Length(Str) = 0 then
More := False;
end; //while
end;
var
TranslatorFactory: IXMLSchemaTranslatorFactory;
initialization
TranslatorFactory := TXMLSchemaTranslatorFactory.Create(TDTDImportTranslator,
nil, DTDExtension, SDTDTransDesc);
RegisterSchemaTranslator(TranslatorFactory);
finalization
UnRegisterSchemaTranslator(TranslatorFactory);
end.
|
unit constants;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
const VERSION = '0.1';
const iniFile = 'oconfig.ini';
const INI_General = 'General';
const INI_Network = 'Network';
const INI_SWAMP = 'Swamp';
const BIND_Default_Address = '0.0.0.0';
const BIND_Default_Port = 16384;
const OPERATION_TYPE_BLOCKCHAIN_GENERAL_INFO = 1;
const OPERATION_TYPE_BLOCKCHAIN_SPECIFIC_BLOCK = 2;
const OPERATION_TYPE_NODE_DISCOVERY = 100;
const NODE_DISCOVERY_MAX_NODES = 10;
implementation
end.
|
unit ParcelAuditPrintForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Mask, RPCanvas, RPrinter, RPFiler, RPDefine, RPBase,
RPTXFilr, Db, DBTables, Wwtable;
type
TParcelAuditPrintDialog = class(TForm)
UserIDGroupBox: TGroupBox;
Label9: TLabel;
Label10: TLabel;
StartUserEdit: TEdit;
AllUsersCheckBox: TCheckBox;
ToEndOfUsersCheckBox: TCheckBox;
EndUserEdit: TEdit;
DateGroupBox: TGroupBox;
Label7: TLabel;
Label8: TLabel;
AllDatesCheckBox: TCheckBox;
ToEndofDatesCheckBox: TCheckBox;
EndDateEdit: TMaskEdit;
StartDateEdit: TMaskEdit;
HeaderLabel: TLabel;
PrintButton: TBitBtn;
CancelButton: TBitBtn;
PrintDialog: TPrintDialog;
TextFiler: TTextFiler;
ReportFiler: TReportFiler;
ReportPrinter: TReportPrinter;
AuditTrailTable: TwwTable;
AuditQuery: TQuery;
procedure PrintButtonClick(Sender: TObject);
procedure TextFilerPrintHeader(Sender: TObject);
procedure TextFilerPrint(Sender: TObject);
procedure AllDatesCheckBoxClick(Sender: TObject);
procedure AllUsersCheckBoxClick(Sender: TObject);
procedure ReportPrint(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
SwisSBLKey : String;
PrintAllUsers,
PrintToEndOfUsers,
PrintAllDates,
PrintToEndOfDates : Boolean;
StartUser,
EndUser : String;
StartDate,
EndDate : TDateTime;
Function RecordInRange(Date : TDateTime;
User : String) : Boolean;
Procedure SetHeaderLabel(SwisSBLKey : String);
end;
var
ParcelAuditPrintDialog: TParcelAuditPrintDialog;
implementation
{$R *.DFM}
uses PASUtils, Preview, GlblVars, WinUtils, PASTypes, Utilitys, GlblCnst,
DataAccessUnit;
{=============================================================}
Procedure TParcelAuditPrintDialog.FormShow(Sender: TObject);
{FXX08142002-2: This information was in FormCreate, but it should have been
in FormShow since the form is autocreated, but the
global variables are not yet set at this point.}
begin
{CHG06092010-3(2.26.1)[I7208]: Allow for supervisor equivalents.}
If ((not UserIsSupervisor(GlblUserName)) and
(not GlblAllowAuditAccessToAll))
then
begin
UserIDGroupBox.Visible := False;
{If not the supervisor, set the start and end ranges the same.}
PrintAllUsers := False;
PrintToEndOfUsers := False;
StartUser := Take(10, GlblUserName);
EndUser := Take(10, GlblUserName);
end; {If (GlblUserName <> 'SUPERVISOR')}
end; {FormShow}
{=============================================================}
Procedure TParcelAuditPrintDialog.SetHeaderLabel(SwisSBLKey : String);
begin
HeaderLabel.Caption := 'Print audit trail for ' +
ConvertSwisSBLToDashDot(SwisSBLKey);
end; {SetHeaderLabel}
{=============================================================}
Procedure TParcelAuditPrintDialog.AllDatesCheckBoxClick(Sender: TObject);
begin
If AllDatesCheckBox.Checked
then
begin
ToEndofDatesCheckBox.Checked := False;
ToEndofDatesCheckBox.Enabled := False;
StartDateEdit.Text := '';
StartDateEdit.Enabled := False;
StartDateEdit.Color := clBtnFace;
EndDateEdit.Text := '';
EndDateEdit.Enabled := False;
EndDateEdit.Color := clBtnFace;
end
else EnableSelectionsInGroupBoxOrPanel(DateGroupBox);
end; {AllDatesCheckBoxClick}
{=============================================================}
Procedure TParcelAuditPrintDialog.AllUsersCheckBoxClick(Sender: TObject);
begin
If AllUsersCheckBox.Checked
then
begin
ToEndofUsersCheckBox.Checked := False;
ToEndofUsersCheckBox.Enabled := False;
StartUserEdit.Text := '';
StartUserEdit.Enabled := False;
StartUserEdit.Color := clBtnFace;
EndUserEdit.Text := '';
EndUserEdit.Enabled := False;
EndUserEdit.Color := clBtnFace;
end
else EnableSelectionsInGroupBoxOrPanel(UserIdGroupBox);
end; {AllUsersCheckBoxClick}
{=============================================================}
Procedure TParcelAuditPrintDialog.PrintButtonClick(Sender: TObject);
var
TextFileName, NewFileName : String;
Quit, Continue : Boolean;
begin
Quit := False;
Continue := True;
StartDate := 0;
EndDate := 0;
{FXX04232003-1(2.07): Make it so that they don't have to select a date range.}
If ((StartDateEdit.Text = ' / / ') and
(EndDateEdit.Text = ' / / ') and
(not AllDatesCheckBox.Checked) and
(not ToEndOfDatesCheckBox.Checked))
then
begin
AllDatesCheckBox.Checked := True;
PrintAllDates := True;
end
else
If AllDatesCheckBox.Checked
then PrintAllDates := True
else
begin
try
StartDate := StrToDate(StartDateEdit.Text);
except
Continue := False;
MessageDlg('Sorry, ' + StartDateEdit.Text + ' is not a valid start date.' + #13 +
'Please correct and try again.', mtError, [mbOK], 0);
end;
If ToEndOfDatesCheckBox.Checked
then PrintToEndOfDates := True
else
try
EndDate := StrToDate(EndDateEdit.Text);
except
Continue := False;
MessageDlg('Sorry, ' + EndDateEdit.Text + ' is not a valid end date.' + #13 +
'Please correct and try again.', mtError, [mbOK], 0);
end;
end; {else of If PrintAllDates.Checked}
EndUser := '';
StartUser := '';
PrintAllUsers := False;
PrintToEndOfUsers := False;
If AllUsersCheckBox.Checked
then PrintAllUsers := True
else
begin
StartUser := StartUserEdit.Text;
If ToEndOfUsersCheckBox.Checked
then PrintToEndOfUsers := True
else EndUser := EndUserEdit.Text;
end; {else of If AllUsersCheckBox.Checked}
If ((Deblank(StartUser) = '') and
(Deblank(EndUser) = '') and
(not PrintAllUsers) and
(not PrintToEndOfUsers))
then
begin
AllUsersCheckBox.Checked := True;
PrintAllUsers := True;
end;
{CHG10121998-1: Add user options for default destination and show vet max msg.}
SetPrintToScreenDefault(PrintDialog);
If (Continue and
PrintDialog.Execute)
then
begin
TextFiler.SetFont('Courier New', 10);
AssignPrinterSettings(PrintDialog, ReportPrinter, ReportFiler, [ptBoth], True, Quit);
If not Quit
then
begin
{CHG02282001-1: Allow everybody to everyone elses changes.}
If GlblAllowAuditAccessToAll
then PrintAllUsers := True;
If not Quit
then
begin
GlblPreviewPrint := False;
TextFiler.SetFont('Courier New', 10);
TextFileName := GetPrintFileName(Self.Caption, True);
TextFiler.FileName := TextFileName;
{FXX01211998-1: Need to set the LastPage property so that
long rolls aren't a problem.}
TextFiler.LastPage := 30000;
TextFiler.Execute;
{If they want to see it on the screen, start the preview.}
If PrintDialog.PrintToFile
then
begin
GlblPreviewPrint := True;
NewFileName := GetPrintFileName(Self.Caption, True);
ReportFiler.FileName := NewFileName;
try
PreviewForm := TPreviewForm.Create(self);
PreviewForm.FilePrinter.FileName := NewFileName;
PreviewForm.FilePreview.FileName := NewFileName;
PreviewForm.FilePreview.ZoomFactor := 130;
ReportFiler.Execute;
PreviewForm.ShowModal;
finally
PreviewForm.Free;
end;
{Delete the report printer file.}
try
Chdir(GlblReportDir);
OldDeleteFile(NewFileName);
except
end;
end
else ReportPrinter.Execute;
end; {If not Quit}
Close;
end; {If not Quit}
end; {If PrintDialog.Execute}
end; {PrintButtonClick}
{===================================================================}
Function TParcelAuditPrintDialog.RecordInRange(Date : TDateTime;
User : String) : Boolean;
begin
Result := True;
If not PrintAllDates
then
begin
If (Date < StartDate)
then Result := False;
If ((not PrintToEndOfDates) and
(Date > EndDate))
then Result := False;
end; {If not PrintAllDates}
If not PrintAllUsers
then
begin
If (Take(10, User) < Take(10, StartUser))
then Result := False;
If ((not PrintToEndOfUsers) and
(Take(10, User) > Take(10, EndUser)))
then Result := False;
end; {If not PrintAllUsers}
end; {RecordInRange}
{===================================================================}
Procedure TParcelAuditPrintDialog.TextFilerPrintHeader(Sender: TObject);
begin
with Sender as TBaseReport do
begin
ClearTabs;
SetTab(0.3, pjLeft, 13.0, 0, BoxLineNone, 0);
{Print the date and page number.}
Println(Take(43, GetMunicipalityName) +
Center('Audit Trail Report', 43) +
RightJustify('Date: ' + DateToStr(Date) +
' Time: ' + FormatDateTime(TimeFormat, Now), 43));
Println(RightJustify('Page: ' + IntToStr(CurrentPage), 129));
Print(#9 + 'For Dates: ');
If PrintAllDates
then Println(' All')
else
begin
Println(' ' + DateToStr(StartDate));
If PrintToEndOfDates
then Println(' End')
else Println(' ' + DateToStr(EndDate));
end; {else of If AllDatesCheckBox.Checked}
Print(#9 + 'For Users: ');
If PrintAllUsers
then Println(' All')
else
begin
Print(' ' + RTrim(StartUser) + ' to ');
If PrintToEndOfUsers
then Println(' End')
else Println(' ' + EndUser);
end; {else of If PrintAllUsers}
Println('');
ClearTabs;
SetTab(10.5, pjLeft, 2.2, 0, BOXLINENONE, 0); {Old Value}
Println(#9 + 'Old Value');
ClearTabs;
SetTab(0.2, pjCenter, 2.0, 0, BOXLINEBOTTOM, 0); {SBL}
SetTab(2.3, pjCenter, 1.0, 0, BOXLINEBOTTOM, 0); {Date Entered}
SetTab(3.5, pjCenter, 0.8, 0, BOXLINEBOTTOM, 0); {Time}
SetTab(4.4, pjCenter, 1.0, 0, BOXLINEBOTTOM, 0); {User}
SetTab(5.5, pjCenter, 0.4, 0, BOXLINEBOTTOM, 0); {Year}
SetTab(6.0, pjLeft, 1.9, 0, BOXLINEBOTTOM, 0); {FormName}
SetTab(8.0, pjLeft, 2.4, 0, BOXLINEBOTTOM, 0); {Label Name}
SetTab(10.5, pjLeft, 2.5, 0, BOXLINEBOTTOM, 0); {Old Value}
Println(#9 + 'Parcel ID' +
#9 + 'Date ' +
#9 + 'Time' +
#9 + 'User' +
#9 + 'Yr' +
#9 + 'Screen' +
#9 + 'Field' +
#9 + 'New Value');
Println('');
ClearTabs;
SetTab(0.2, pjLeft, 2.0, 0, BOXLINEBOTTOM, 0); {SBL}
SetTab(2.3, pjLeft, 1.0, 0, BOXLINEBOTTOM, 0); {Date Entered}
SetTab(3.5, pjLeft, 0.8, 0, BOXLINEBOTTOM, 0); {Time}
SetTab(4.4, pjLeft, 1.0, 0, BOXLINEBOTTOM, 0); {User}
SetTab(5.5, pjLeft, 0.4, 0, BOXLINEBOTTOM, 0); {Year}
SetTab(6.0, pjLeft, 1.9, 0, BOXLINEBOTTOM, 0); {FormName}
SetTab(8.0, pjLeft, 2.4, 0, BOXLINEBOTTOM, 0); {Label Name}
SetTab(10.5, pjLeft, 2.5, 0, BOXLINEBOTTOM, 0); {Old Value}
end; {with Sender as TBaseReport do}
end; {TextFilerPrintHeader}
{===================================================================}
Procedure TParcelAuditPrintDialog.TextFilerPrint(Sender: TObject);
var
TempStr : String;
Done, FirstTimeThrough, Quit : Boolean;
NumChanged : LongInt;
PreviousDate, PreviousTime,
PreviousUser, PreviousScreen : String;
begin
Done := False;
FirstTimeThrough := True;
Quit := False;
NumChanged := 0;
{CHG07102005-1(2.8.5.5): Change the audit trail access to SQL to avoid using an index.}
with AuditQuery do
try
SQL.Clear;
SQL.Add('Select * from AuditTable where');
SQL.Add(FormatSQLConditional('SwisSBLKey', [SwisSBLKey], coEqual, []));
Open;
except
end; {with AuditQuery do}
(* AuditTrailTable.Open;
SetRangeOld(AuditTrailTable,
['SwisSBLKey', 'Date', 'Time'],
[SwisSBLKey, '1/1/1900', ''],
[SwisSBLKey, '1/1/2300', '']); *)
with Sender as TBaseReport do
begin
PreviousDate := '';
PreviousTime := '';
PreviousUser := '';
PreviousScreen := '';
{First print the individual changes.}
repeat
If FirstTimeThrough
then FirstTimeThrough := False
else AuditQuery.Next;
If AuditQuery.EOF
then Done := True;
{Print the present record.}
If not (Done or Quit)
then
begin
Application.ProcessMessages;
with AuditQuery do
If RecordInRange(FieldByName('Date').AsDateTime,
FieldByName('User').Text)
then
begin
NumChanged := NumChanged + 1;
TempStr := FieldByName('OldValue').Text;
If (Deblank(TempStr) = '')
then TempStr := '{none}';
{FXX11171997-3: The field "FormName" was being printed
out, but should be "ScreenName".}
{FXX12221998-3: If the parcel ID, user year, date and time are all the
same, then print as one change.}
If ((PreviousDate = AuditQuery.FieldByName('Date').Text) and
(PreviousTime = AuditQuery.FieldByName('Time').Text) and
(Take(30, PreviousScreen) = Take(30, AuditQuery.FieldByName('ScreenName').Text)) and
(Take(10, PreviousUser) = Take(10, AuditQuery.FieldByName('User').Text)))
then Print(#9 + #9 + #9 + #9 + #9 + #9)
else Print(#9 + ConvertSwisSBLToDashDot(FieldByName('SwisSBLKey').Text) +
#9 + FieldByName('Date').Text +
#9 + FormatDateTime(TimeFormat, FieldByName('Time').AsDateTime) +
#9 + FieldByName('User').Text +
#9 + FieldByName('TaxRollYr').Text +
#9 + FieldByName('ScreenName').Text);
Println(#9 + FieldByName('LabelName').Text +
#9 + TempStr);
TempStr := FieldByName('NewValue').Text;
If (Deblank(TempStr) = '')
then TempStr := '{none}';
Println(#9 +
#9 +
#9 +
#9 +
#9 +
#9 +
#9 +
#9 + TempStr);
Println('');
{FXX12221998-3: If the parcel ID, user year, date and time are all the
same, then print as one change.}
{FXX08061999-1: Only update the previous info if it actually changed.}
PreviousDate := AuditQuery.FieldByName('Date').Text;
PreviousTime := AuditQuery.FieldByName('Time').Text;
PreviousScreen := AuditQuery.FieldByName('ScreenName').Text;
PreviousUser := AuditQuery.FieldByName('User').Text;
end; {with AuditQuery do}
{If there is only one line left to print, then we
want to go to the next page.}
If (LinesLeft < 8)
then NewPage;
end; {If not (Done or Quit)}
until (Done or Quit);
{FXX01231998-5: Tell them if nothing in range.}
If (NumChanged = 0)
then Println('None.');
end; {with Sender as TBaseReport do}
end; {TextFilerPrint}
{==============================================================}
Procedure TParcelAuditPrintDialog.ReportPrint(Sender: TObject);
var
ReportTextFile : TextFile;
begin
AssignFile(ReportTextFile, TextFiler.FileName);
Reset(ReportTextFile);
{CHG12211998-1: Add ability to select print range.}
PrintTextReport(Sender, ReportTextFile, PrintDialog.FromPage,
PrintDialog.ToPage);
CloseFile(ReportTextFile);
end; {ReportPrint}
end. |
//
// This unit is part of the GLScene Project, http://glscene.org
//
{: GLTimeEventsMgr<p>
by GliGli
Time based events mannager using the Cadencer<p>
can be useful to make animations with GlScene<p>
<b>History : </b><font size=-1><ul>
<li>07/01/10 - DaStr - Added TGLTimeEventsMGR.Reset()
Fixed code formating
<li>25/11/09 - DanB - Changed TTimeEvent.Name from ShortString to String
<li>11/10/07 - DaStr - TTimeEvent.SetEnabled now updates StartTime to
Cadencers's current time.
(Thanks Lukasz Sokol) (BugTracker ID = 1811141)
<li>28/03/07 - DaStr - Cosmetic fix for FPC compatibility
<li>29/01/07 - DaStr - Moved registration to GLSceneRegister.pas
<li>07/02/02 - EG - Added Notification, DoEvent, ElapsedTime and changed Event type
}
unit GLTimeEventsMgr;
interface
uses
System.Classes, System.SysUtils,
GLCadencer, GLBaseClasses;
type
TTimeEvent = class;
TTimeEvents = class;
// TGLTimeEventsMGR
//
TGLTimeEventsMGR = class(TGLUpdateAbleComponent)
private
{ Déclarations privées }
FCadencer : TGLCadencer;
FEnabled : boolean;
FFreeEventOnEnd : boolean;
FEvents : TTimeEvents;
protected
{ Déclarations protégées }
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetCadencer(const val : TGLCadencer);
procedure SetEvents(const val : TTimeEvents);
public
{ Déclarations publiques }
constructor Create(aOwner : TComponent); override;
destructor Destroy; override;
procedure DoProgress(const progressTime : TProgressTimes); override;
procedure Reset();
published
{ Déclarations publiées }
property Cadencer : TGLCadencer read FCadencer write SetCadencer;
property Enabled : boolean read FEnabled write FEnabled default True;
property FreeEventOnEnd : boolean read FFreeEventOnEnd write FFreeEventOnEnd default False;
property Events : TTimeEvents read FEvents write SetEvents;
end;
// TTimeEvents
//
TTimeEvents = class (TCollection)
protected
{ Protected Declarations }
Owner : TComponent;
function GetOwner: TPersistent; override;
procedure SetItems(index : Integer; const val : TTimeEvent);
function GetItems(index : Integer) : TTimeEvent;
public
{ Public Declarations }
constructor Create(AOwner : TComponent);
function Add: TTimeEvent;
function FindItemID(ID: Integer): TTimeEvent;
function EventByName(name:String): TTimeEvent;
property Items[index : Integer] : TTimeEvent read GetItems write SetItems; default;
end;
TTimeEventType = (etOneShot, etContinuous, etPeriodic);
TTimeEventProc = procedure (event : TTimeEvent) of object;
// TTimeEvent
//
TTimeEvent = class (TCollectionItem)
private
{ Private Declarations }
FName: String;
FStartTime, FEndTime, FElapsedTime : Double;
FPeriod : Double;
FEventType: TTimeEventType;
FOnEvent:TTimeEventProc;
FEnabled: boolean;
FTickCount : Cardinal;
procedure SetEnabled(const Value: Boolean);
protected
{ Protected Declarations }
function GetDisplayName : String; override;
procedure SetName(Val : String);
procedure DoEvent(const CurTime : Double);
public
{ Public Declarations }
constructor Create(Collection : TCollection); override;
destructor Destroy; override;
//: Number of times the event was triggered since activation
property TickCount : Cardinal read FTickCount;
//: Elapsed time since the event was activated
property ElapsedTime : Double read FElapsedTime;
published
{ Published Declarations }
property Name : String read FName write SetName;
property StartTime : Double read FStartTime write FStartTime;
property EndTime : Double read FEndTime write FEndTime;
property Period : Double read FPeriod write FPeriod;
property EventType : TTimeEventType read FEventType write FEventType default etOneShot;
property OnEvent : TTimeEventProc read FOnEvent write FOnEvent;
property Enabled : Boolean read FEnabled write SetEnabled default True;
end;
implementation
// ------------------
// ------------------ TGLTimeEventsMGR ------------------
// ------------------
// Create
//
constructor TGLTimeEventsMGR.Create(aOwner : TComponent);
begin
inherited;
FEnabled:=True;
FFreeEventOnEnd:=False;
FEvents:=TTimeEvents.Create(self);
end;
// Destroy
//
destructor TGLTimeEventsMGR.Destroy;
begin
Cadencer:=nil;
FEvents.Free;
inherited Destroy;
end;
// Notification
//
procedure TGLTimeEventsMGR.Notification(AComponent: TComponent; Operation: TOperation);
begin
if (Operation=opRemove) and (AComponent=Cadencer) then
FCadencer:=nil;
inherited;
end;
// SetCadencer
//
procedure TGLTimeEventsMGR.SetCadencer(const val : TGLCadencer);
begin
if FCadencer<>val then begin
if Assigned(FCadencer) then
FCadencer.UnSubscribe(Self);
FCadencer:=val;
if Assigned(FCadencer) then
FCadencer.Subscribe(Self);
end;
end;
// SetEvents
//
procedure TGLTimeEventsMGR.SetEvents(const val : TTimeEvents);
begin
FEvents.Assign(val);
end;
// DoProgress
//
procedure TGLTimeEventsMGR.DoProgress(const progressTime : TProgressTimes);
var
i : Integer;
begin
if not Enabled then Exit;
i:=0;
with progressTime do while i<=Events.Count-1 do with Events.Items[i] do begin
if Enabled and Assigned(FOnEvent) then begin
case EventType of
etOneShot :
if (newTime>=StartTime) and (TickCount=0) then
DoEvent(newTime);
etContinuous :
if (newTime>=StartTime) and ((newTime<=EndTime) or (EndTime<=0)) then
DoEvent(newTime);
etPeriodic :
if (newTime>=StartTime+TickCount*Period) and ((newTime<=EndTime) or (EndTime<=0)) then
DoEvent(newTime);
else
Assert(False);
end;
end;
if FreeEventOnEnd and
( ((EventType<>etOneShot) and (newTime>EndTime) and (EndTime>=0)) or
((EventType=etOneShot) and (TickCount>0)) ) then
Events[i].Free
else begin
// if we delete current event, the next will have same index
// so increment only if we don't delete
Inc(i);
end;
end;
end;
// Reset
//
procedure TGLTimeEventsMGR.Reset;
var
I: Integer;
begin
if FEvents.Count <> 0 then
for I := 0 to FEvents.Count - 1 do
FEvents[I].FTickCount := 0;
end;
// ------------------
// ------------------ TTimeEvents ------------------
// ------------------
// Create
//
constructor TTimeEvents.Create(AOwner : TComponent);
begin
Owner:=AOwner;
inherited Create(TTimeEvent);
end;
// GetOwner
//
function TTimeEvents.GetOwner: TPersistent;
begin
Result:=Owner;
end;
// Setitems
//
procedure TTimeEvents.SetItems(index : Integer; const val : TTimeEvent);
begin
inherited Items[index]:=val;
end;
// GetItems
//
function TTimeEvents.GetItems(index : Integer) : TTimeEvent;
begin
Result:=TTimeEvent(inherited Items[index]);
end;
// Add
//
function TTimeEvents.Add : TTimeEvent;
begin
Result:=(inherited Add) as TTimeEvent;
end;
// FindItemID
//
function TTimeEvents.FindItemID(ID: Integer): TTimeEvent;
begin
Result:=(inherited FindItemID(ID)) as TTimeEvent;
end;
// EventByName
//
function TTimeEvents.EventByName(name:String): TTimeEvent;
var i:integer;
begin
i:=0;
while (i<Count) and (Items[i].FName<>name) do inc(i);
if i=Count then result:=nil else result:=Items[i];
end;
// ------------------
// ------------------ TTimeEvent ------------------
// ------------------
// Create
//
constructor TTimeEvent.Create(Collection : TCollection);
begin
inherited Create(Collection);
FEventType:=etOneShot;
FName:=Format('Event%d', [index]); // give a default name different for each event
FEnabled:=True;
end;
// Destroy
//
destructor TTimeEvent.Destroy;
begin
inherited Destroy;
end;
// GetDisplayName
//
function TTimeEvent.GetDisplayName : String;
begin
case EventType of
etOneShot:
Result:=Name+Format(' (OneShot ST=%g)',[StartTime]);
etContinuous:
Result:=Name+Format(' (Continuous ST=%g ET=%g)',[StartTime,EndTime]);
etPeriodic:
Result:=Name+Format(' (Periodic ST=%g ET=%g P=%g)',[StartTime,EndTime,Period]);
end;
end;
// SetName
//
procedure TTimeEvent.SetName(Val : String);
var
i : Integer;
ok : Boolean;
begin
ok := True;
with self.Collection as TTimeEvents do // we mustn't have 2 events with the same name (for EventByName)
for i:=0 to Count-1 do
if Items[i].FName = val then Ok := False;
if Ok and (Val<>'') then FName:=Val;
end;
// DoEvent
//
procedure TTimeEvent.DoEvent(const curTime : Double);
begin
if Assigned(FOnEvent) then begin
FElapsedTime:=curTime-StartTime;
FOnEvent(Self);
end;
Inc(FTickCount);
end;
// SetEnabled
//
procedure TTimeEvent.SetEnabled(const Value: Boolean);
begin
FEnabled := Value;
FStartTime := ((GetOwner as TTimeEvents).Owner as TGLTimeEventsMGR).Cadencer.CurrentTime;
end;
end.
|
unit MainPage;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Layouts, FMX.Controls.Presentation, FMX.MultiView, FMX.Objects,
FireDAC.Phys.Intf, FireDAC.Stan.Option, FireDAC.Stan.Intf, FireDAC.Comp.Client,
LyoutHeader, FMX.TabControl, BabyList, BabyEdit, FMX.ListBox,
FMX.Ani, FMX.MediaLibrary.Actions, System.Actions, FMX.ActnList, FMX.StdActns;
type
TFMainPage = class(TForm)
MultiView1: TMultiView;
MainLayout: TLayout;
ToolBar1: TToolBar;
SpeedButton1: TSpeedButton;
FlyoutMenu: TRectangle;
FMenuScrollBox: TVertScrollBox;
BtnNewBaby: TRectangle;
Image1: TImage;
Label1: TLabel;
Lang1: TLang;
MainHeader: TRectangle;
TabControl1: TTabControl;
TabItem1: TTabItem;
TabItem2: TTabItem;
TabItem3: TTabItem;
BtnBabiesList: TRectangle;
Image2: TImage;
Label2: TLabel;
Rectangle1: TRectangle;
Label3: TLabel;
StyleBook1: TStyleBook;
recBakground: TRectangle;
mActionSheet: TRectangle;
animActionSheet: TFloatAnimation;
Label4: TLabel;
ListBox1: TListBox;
btnTakePhoto: TListBoxItem;
btnTakeFromLibrary: TListBoxItem;
btnActionSheetClose: TListBoxItem;
OpDlgPicture: TOpenDialog;
// Declaration proceduren
procedure FormCreate(Sender: TObject);
procedure BtnBabiesListClick(Sender: TObject);
procedure BtnNewBabyClick(Sender: TObject);
procedure animActionSheetFinish(Sender: TObject);
procedure btnActionSheetCloseClick(Sender: TObject);
procedure btnTakePhotoClick(Sender: TObject);
procedure btnTakeFromLibraryClick(Sender: TObject);
procedure FBabyEdit1SaveClick(Sender: TObject);
procedure FBabyEdit1Rectangle2Click(Sender: TObject);
procedure FBabyEdit1SpeedButton1Click(Sender: TObject);
private
{ Private declarations }
procedure ActionSheetClose();
protected
FchoicePic: string;
public
{ Public declarations }
property choicePic: string read FchoicePic write FchoicePic;
end;
var
FMainPage: TFMainPage;
implementation
uses
PcCam, UScript;
{$R *.fmx}
procedure TFMainPage.animActionSheetFinish(Sender: TObject);
begin
animActionSheet.Enabled := false;
end;
procedure TFMainPage.BtnBabiesListClick(Sender: TObject);
begin
TabControl1.ActiveTab := TabControl1.Tabs[0];
MultiView1.HideMaster;
end;
procedure TFMainPage.BtnNewBabyClick(Sender: TObject);
begin
TabControl1.ActiveTab := TabControl1.Tabs[1];
MultiView1.HideMaster;
end;
procedure TFMainPage.btnTakeFromLibraryClick(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
OpDlgPicture.Filter := 'Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png';
OpDlgPicture.InitialDir:=ExtractFilePath(ParamStr(0));
try
OpDlgPicture.Execute;
finally
ActionSheetClose();
if (OpDlgPicture.FileName<>'') then
FBabyEdit1.btnActionSheet.Fill.Bitmap.Bitmap.LoadFromFile(OpDlgPicture.FileName);
end;
{$ENDIF}
{$IFDEF MACOS}
{$ENDIF}
end;
procedure TFMainPage.btnTakePhotoClick(Sender: TObject);
begin
{$IFDEF MSWINDOWS}
Application.CreateForm(TfrmPcCam,frmPcCam);
try
frmPcCam.ShowModal;
finally
FreeAndNil(frmPcCam);
ActionSheetClose();
if (FchoicePic<>'') then
FBabyEdit1.btnActionSheet.Fill.Bitmap.Bitmap.LoadFromFile(FchoicePic);
end;
{$ENDIF}
{$IFDEF MACOS}
{$ENDIF}
//
end;
procedure TFMainPage.btnActionSheetCloseClick(Sender: TObject);
begin
ActionSheetClose();
end;
procedure TFMainPage.ActionSheetClose();
begin
recBakground.Visible := false;
recBakground.Height := FMainPage.Height;
end;
procedure TFMainPage.FBabyEdit1Rectangle2Click(Sender: TObject);
begin
recBakground.Width := MainLayout.Width;
recBakground.Height := MainLayout.Height;
recBakground.Position.Y := 0;
recBakground.Visible := true;
animActionSheet.StartValue := FMainPage.Height;
animActionSheet.StopValue := MainLayout.Height - mActionSheet.Height;
animActionSheet.Enabled := true;
end;
procedure TFMainPage.FBabyEdit1SaveClick(Sender: TObject);
begin
FBabyEdit1.SaveClick(Sender);
end;
procedure TFMainPage.FBabyEdit1SpeedButton1Click(Sender: TObject);
begin
FBabyEdit1.SpeedButton1Click(Sender);
FBabyList1.BindSourceAdapterReload();
end;
procedure TFMainPage.FormCreate(Sender: TObject);
begin
Label3.Margins.Left:=200;
Label3.Margins.Right:=10;
FBabyEdit1.Layout1.Padding.Left := 250;
FBabyEdit1.Layout1.Padding.Right := 10;
FBabyEdit1.Layout4.Padding.Left := 250;
FBabyEdit1.Layout4.Padding.Right := 10;
FBabyEdit1.edtID.FilterChar := '0123456789';
FBabyEdit1.edtAge.FilterChar := '0123456789';
FMainPage.Position:=TFormPosition(6);
FMainPage.WindowState:=TWindowState(2);
FlyoutHeader.Loead();
Uscript.BuildTable;
FBabyList1.BindSourceAdapterReload();
end;
end.
|
{
*****************************************************************************
* *
* See the file COPYING.modifiedLGPL.txt, included in the lazarus *
* directory, for details about the license/copyright. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* *
*****************************************************************************
Author....: Raphael Zimermann
Website...: www.raphaelz.com.br
About:
KZDesktop transforms the lazarus IDE to a layout similar to that of the
Package ViewerPackage Viewer"Delphi Rad Studio" IDE.
}
unit kzdesktop;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, LCLIntf, LCLType, LResources, Forms, Controls, Graphics, Dialogs,
ExtCtrls, TypInfo, Buttons, StdCtrls, GraphType, LMessages, MenuIntf, ComCtrls, Menus,
IniFiles, IDEOptionsIntf, LazIDEIntf;
procedure Register;
procedure SaveCFG(_Section, _Ident, _Value: String);
function LoadCFG(_Section, _Ident: String; _Default: String = ''): String;
implementation
uses
KZLazDesktop, uKZConfig;
function KzDesktopCFG: String;
begin
Result := ExtractFilePath(Application.ExeName) + PathDelim + 'kzdesktop.cfg'; // LazApp
end;
procedure SaveCFG(_Section, _Ident, _Value: String);
var
cfg: TIniFile;
begin
cfg := TIniFile.Create(KzDesktopCFG);
try
cfg.WriteString(_Section, _Ident, _Value);
finally
FreeAndNil(cfg);
end;
end;
function LoadCFG(_Section, _Ident: String; _Default: String = ''): String;
var
cfg: TIniFile;
begin
cfg := TIniFile.Create(KzDesktopCFG);
try
Result := cfg.ReadString(_Section, _Ident, _Default);
finally
FreeAndNil(cfg);
end;
end;
procedure StartKzDeskTop(Sender: TObject);
begin
if Sender <> nil then
begin
SaveCFG('Initialization', 'Started', 'True');
ShowMessage('Done.' + #13#10 +
'Remember: The KZDesktop is still under development' +
'and has some bugs that are being corrected over time!' + #13#10 + #13#10 +
'Restart Lazarus for the KZDesktop take effect.');
end
else
begin
KZLazDesktopInterface := TKZLazDesktopInterface.Create(Application);
KZLazDesktopInterface.Execute;
end;
end;
procedure StopKzDeskTop(Sender: TObject);
begin
SaveCFG('Initialization', 'Started', 'False');
ShowMessage('Done.' + #13#10 + 'Restart Lazarus to disable KZDesktop.')
//if DeleteFile(KzDesktopCFG) then
// ShowMessage('Done.' + #13#10 + 'Restart Lazarus to disable KZDesktop.')
//else
// ShowMessage('Problem to disable KZDesktop!');
end;
procedure AboutKzDeskTop(Sender: TObject);
begin
ShowMessage(
'KZDesktop (2011-2012)' + #13#10 +
'This version is a alpha version. Ignore the bugs, please! ;)' + #13#10 +
'By Raphael Zimermann - http://www.raphaelz.com.br/');
end;
procedure ConfigKzDeskTop(Sender: TObject);
begin
LazarusIDE.DoOpenIDEOptions(TfmKZConfig);
{fmKZConfig := TfmKZConfig.Create(Application);
try
fmKZConfig.Enabled := True;
fmKZConfig.ShowModal;
finally
fmKZConfig.Release;
fmKZConfig := Nil;
end;}
end;
procedure StartMyTool_Teste(Sender: TObject);
var
i, a: Integer;
s: String;
begin
ShowMessage('Screen.Forms');
for i := 0 to Screen.FormCount - 1 do
begin
s := Screen.Forms[i].Name + ': ' + Screen.Forms[i].ClassName;
for a := 0 to Screen.Forms[i].ComponentCount - 1 do
begin
s := s + #13#10 + '...' + Screen.Forms[i].Components[a].Name + ': ' +
Screen.Forms[i].Components[a].ClassName;
end;
ShowMessage(s);
end;
ShowMessage('Application.Components');
for i := 0 to Application.ComponentCount - 1 do
begin
s := Application.Components[i].Name + ': ' + Application.Components[i].ClassName;
for a := 0 to Application.Components[i].ComponentCount - 1 do
begin
s := s + #13#10 + '...' + Application.Components[i].Components[a].Name + ': ' +
Application.Components[i].Components[a].ClassName;
end;
ShowMessage(s);
end;
//Screen.FindForm('fmPlayList').Parent := Screen.FindForm('fmPrincipal');
//Screen.FindForm('fmPlayList').ParentWindow := Screen.FindForm('fmPrincipal').Handle;
end;
procedure Register;
var
mm: TIDEMenuSection;
begin
mm := itmSecondaryTools;
RegisterIDEMenuCommand(mm, 'mmKZDesktopSep', '-', nil, nil);
if (not FileExists(KzDesktopCFG)) or (LoadCFG('Initialization', 'Started', 'False') = 'False') then
begin
RegisterIDEMenuCommand(mm, 'mmKZDesktopStart', 'KZ Desktop - Start', nil, @StartKzDeskTop);
end
else
begin
RegisterIDEMenuCommand(mm, 'mmKZDesktopStop', 'KZ Desktop - Stop', nil, @StopKzDeskTop);
RegisterIDEOptionsEditor(GroupEnvironment, TfmKZConfig, 1000);
StartKzDeskTop(Nil);
end;
RegisterIDEMenuCommand(mm, 'mmConfigKzDeskTop', 'KZ Desktop - Options', nil, @ConfigKzDeskTop);
RegisterIDEMenuCommand(mm, 'mmKZDesktopAbout', 'KZ Desktop - About', nil, @AboutKzDeskTop);
end;
end.
///
|
unit uefattura;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils
, fgl // used for generics
;
const
DOMEL_FatturaElettronicaHeader = 'FatturaElettronicaHeader';
DOMEL_DatiTrasmissione = 'DatiTrasmissione';
DOMEL_IdTrasmittente = 'IdTrasmittente';
DOMEL_IdPaese = 'IdPaese';
DOMEL_IdCodice = 'IdCodice';
DOMEL_ProgressivoInvio = 'ProgressivoInvio';
DOMEL_FormatoTrasmissione = 'FormatoTrasmissione';
DOMEL_CodiceDestinatario = 'CodiceDestinatario';
DOMEL_PECDestinatario = 'PECDestinatario';
DOMEL_ContattiTrasmittente = 'ContattiTrasmittente';
DOMEL_Contatti = 'Contatti';
DOMEL_Telefono = 'Telefono';
DOMEL_Fax = 'Fax';
DOMEL_Email = 'Email';
DOMEL_CedentePrestatore = 'CedentePrestatore';
DOMEL_DatiAnagrafici = 'DatiAnagrafici';
DOMEL_IdFiscaleIVA = 'IdFiscaleIVA';
DOMEL_CodiceFiscale = 'CodiceFiscale';
DOMEL_Anagrafica = 'Anagrafica';
DOMEL_Denominazione = 'Denominazione';
DOMEL_Nome = 'Nome';
DOMEL_Cognome = 'Cognome';
DOMEL_RegimeFiscale = 'RegimeFiscale';
DOMEL_Indirizzo = 'Indirizzo';
DOMEL_NumeroCivico = 'NumeroCivico';
DOMEL_CAP = 'CAP';
DOMEL_Comune = 'Comune';
DOMEL_Provincia = 'Provincia';
DOMEL_Nazione = 'Nazione';
DOMEL_IscrizioneREA = 'IscrizioneREA';
DOMEL_Ufficio = 'Ufficio';
DOMEL_NumeroREA = 'NumeroREA';
DOMEL_CapitaleSociale = 'CapitaleSociale';
DOMEL_SocioUnico = 'SocioUnico';
DOMEL_StatoLiquidazione = 'StatoLiquidazione';
DOMEL_CessionarioCommittente = 'CessionarioCommittente';
DOMEL_Sede = 'Sede';
DOMEL_FatturaElettronicaBody = 'FatturaElettronicaBody';
DOMEL_DatiGenerali = 'DatiGenerali';
DOMEL_DatiGeneraliDocumento = 'DatiGeneraliDocumento';
DOMEL_TipoDocumento = 'TipoDocumento';
DOMEL_Divisa = 'Divisa';
DOMEL_Data = 'Data';
DOMEL_Numero = 'Numero';
DOMEL_ImportoTotaleDocumento = 'ImportoTotaleDocumento';
DOMEL_Arrotondamento = 'Arrotondamento';
DOMEL_Causale = 'Causale';
DOMEL_Art73 = 'Art73';
DOMEL_DatiOrdineAcquisto = 'DatiOrdineAcquisto';
DOMEL_RiferimentoNumeroLinea = 'RiferimentoNumeroLinea';
DOMEL_IdDocumento = 'IdDocumento';
DOMEL_NumItem = 'NumItem';
DOMEL_CodiceCommessaConvenzione = 'CodiceCommessaConvenzione';
DOMEL_CodiceCUP = 'CodiceCUP';
DOMEL_CodiceCIG = 'CodiceCIG';
DOMEL_DatiDDT = 'DatiDDT';
DOMEL_NumeroDDT = 'NumeroDDT';
DOMEL_DataDDT = 'DataDDT';
DOMEL_DatiTrasporto = 'DatiTrasporto';
DOMEL_DatiAnagraficiVettore = 'DatiAnagraficiVettore';
DOMEL_MezzoTrasporto = 'MezzoTrasporto';
DOMEL_CausaleTrasporto = 'CausaleTrasporto';
DOMEL_NumeroColli = 'NumeroColli';
DOMEL_Descrizione = 'Descrizione';
DOMEL_UnitaMisuraPeso = 'UnitaMisuraPeso';
DOMEL_PesoLordo = 'PesoLordo';
DOMEL_PesoNetto = 'PesoNetto';
DOMEL_DataOraRitiro = 'DataOraRitiro';
DOMEL_DataInizioTrasporto = 'DataInizioTrasporto';
DOMEL_TipoResa = 'TipoResa';
DOMEL_IndirizzoResa = 'IndirizzoResa';
DOMEL_DataOraConsegna = 'DataOraConsegna';
DOMEL_DatiBeniServizi = 'DatiBeniServizi';
DOMEL_DettaglioLinee = 'DettaglioLinee';
DOMEL_NumeroLinea = 'NumeroLinea';
DOMEL_TipoCessionePrestazione = 'TipoCessionePrestazione';
DOMEL_CodiceArticolo = 'CodiceArticolo';
DOMEL_CodiceTipo = 'CodiceTipo';
DOMEL_CodiceValore = 'CodiceValore';
DOMEL_Quantita = 'Quantita';
DOMEL_UnitaMisura = 'UnitaMisura';
DOMEL_PrezzoUnitario = 'PrezzoUnitario';
DOMEL_ScontoMaggiorazione = 'ScontoMaggiorazione';
DOMEL_Tipo = 'Tipo';
DOMEL_Percentuale = 'Percentuale';
DOMEL_Importo = 'Importo';
DOMEL_PrezzoTotale = 'PrezzoTotale';
DOMEL_AliquotaIVA = 'AliquotaIVA';
DOMEL_Ritenuta = 'Ritenuta';
DOMEL_Natura = 'Natura';
DOMEL_DatiRiepilogo = 'DatiRiepilogo';
DOMEL_SpeseAccessorie = 'SpeseAccessorie';
DOMEL_ImponibileImporto = 'ImponibileImporto';
DOMEL_Imposta = 'Imposta';
DOMEL_EsigibilitaIVA = 'EsigibilitaIVA';
DOMEL_RiferimentoNormativo = 'RiferimentoNormativo';
DOMEL_AltriDatiGestionali = 'AltriDatiGestionali';
DOMEL_TipoDato = 'TipoDato';
DOMEL_RiferimentoTesto = 'RiferimentoTesto';
DOMEL_RiferimentoNumero = 'RiferimentoNumero';
DOMEL_RiferimentoData = 'RiferimentoData';
DOMEL_DatiPagamento = 'DatiPagamento';
DOMEL_CondizioniPagamento = 'CondizioniPagamento';
DOMEL_DettaglioPagamento = 'DettaglioPagamento';
DOMEL_Beneficiario = 'Beneficiario';
DOMEL_ModalitaPagamento = 'ModalitaPagamento';
DOMEL_DataScadenzaPagamento = 'DataScadenzaPagamento';
DOMEL_ImportoPagamento = 'ImportoPagamento';
DOMEL_IBAN = 'IBAN';
DOMEL_ABI = 'ABI';
DOMEL_CAB = 'CAB';
DOMEL_BIC = 'BIC';
DOMEL_ScontoPagamentoAnticipato = 'ScontoPagamentoAnticipato';
DOMEL_PenalitaPagamentiRitardati = 'PenalitaPagamentiRitardati';
type
{ TEFatturaHeader_Generico_Contatti }
TEFatturaHeader_Generico_Contatti = class(TPersistent)
private
Femail: WideString;
FFax: WideString;
FTelefono: WideString;
function GetAssigned: boolean;
public
property IsAssigned: boolean read GetAssigned;
public
constructor Create;
property Telefono: WideString read FTelefono write FTelefono;
property Fax: WideString read FFax write FFax;
property email: WideString read Femail write Femail;
end;
{ TEFatturaHeader_Generico_Anagrafica }
TEFatturaHeader_Generico_Anagrafica = class(TPersistent)
private
FCodEORI: WideString;
FCognome: WideString;
FDenominazione: WideString;
FNome: WideString;
FTitolo: WideString;
function GetIsAssigned: boolean;
public
property IsAssigned: boolean read GetIsAssigned;
public
constructor Create;
// destructor Destroy; override;
property Denominazione: WideString read FDenominazione write FDenominazione;
property Nome: WideString read FNome write FNome;
property Cognome: WideString read FCognome write FCognome;
property Titolo: WideString read FTitolo write FTitolo;
property CodEORI: WideString read FCodEORI write FCodEORI;
end;
{ TEFatturaHeader_Generico_Sede }
TEFatturaHeader_Generico_Sede = class(TPersistent)
private
FCAP: WideString;
FComune: WideString;
FIndirizzo: WideString;
FNazione: WideString;
FNumeroCivico: WideString;
FProvincia: WideString;
function GetIsAssigned: boolean;
public
property IsAssigned: boolean read GetIsAssigned;
public
constructor Create;
// destructor Destroy; override;
property Indirizzo: WideString read FIndirizzo write FIndirizzo;
property NumeroCivico: WideString read FNumeroCivico write FNumeroCivico;
property CAP: WideString read FCAP write FCAP;
property Comune: WideString read FComune write FComune;
property Provincia: WideString read FProvincia write FProvincia;
property Nazione: WideString read FNazione write FNazione;
end;
{ TEFatturaHeader_Generico_IdFiscaleIVA }
TEFatturaHeader_Generico_IdFiscaleIVA = class(TPersistent)
private
FIdCodice: WideString;
FIdPaese: WideString;
function GetAssigned: boolean;
public
property IsAssigned: boolean read GetAssigned;
public
constructor Create;
property IdPaese: WideString read FIdPaese write FIdPaese;
property IdCodice: WideString read FIdCodice write FIdCodice;
end;
{ TEFatturaBody_Generico_ScontoMaggiorazione }
TEFatturaBody_Generico_ScontoMaggiorazione = class(TPersistent)
private
FImporto: extended;
FPercentuale: extended;
FTipo: WideString;
public
constructor Create;
property Tipo: WideString read FTipo write FTipo;
property Percentuale: extended read FPercentuale write FPercentuale;
property Importo: extended read FImporto write FImporto;
end;
{ TEFatturaBody_Generico_ScontoMaggiorazione_Lista }
TEFatturaBody_Generico_ScontoMaggiorazione_Lista = specialize TFPGObjectList<TEFatturaBody_Generico_ScontoMaggiorazione>;
// DatiTrasmissione
{ TEFatturaHeader_DatiTrasmissione }
TEFatturaHeader_DatiTrasmissione = class(TPersistent)
private
FCodiceDestinatario: WideString;
FContattiTrasmittente: TEFatturaHeader_Generico_Contatti;
FFormatoTrasmissione: WideString;
FIdTrasmittente: TEFatturaHeader_Generico_IdFiscaleIVA;
FPecDestinatario: WideString;
FProgressivoInvio: WideString;
public
constructor Create;
destructor Destroy; override;
property IdTrasmittente: TEFatturaHeader_Generico_IdFiscaleIVA read FIdTrasmittente write FIdTrasmittente;
property ProgressivoInvio: WideString read FProgressivoInvio write FProgressivoInvio;
property FormatoTrasmissione: WideString read FFormatoTrasmissione write FFormatoTrasmissione;
property CodiceDestinatario: WideString read FCodiceDestinatario write FCodiceDestinatario;
property ContattiTrasmittente: TEFatturaHeader_Generico_Contatti read FContattiTrasmittente write FContattiTrasmittente;
property PecDestinatario: WideString read FPecDestinatario write FPecDestinatario;
end;
// CedentePrestatore
{ TEFatturaHeader_CedentePrestatore_DatiAnagrafici }
TEFatturaHeader_CedentePrestatore_DatiAnagrafici = class(TPersistent)
private
FAnagrafica: TEFatturaHeader_Generico_Anagrafica;
FCodiceFiscale: WideString;
FIdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA;
FRegimeFiscale: WideString;
public
constructor Create;
destructor Destroy; override;
property IdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA read FIdFiscaleIVA write FIdFiscaleIVA;
property CodiceFiscale: WideString read FCodiceFiscale write FCodiceFiscale;
property Anagrafica: TEFatturaHeader_Generico_Anagrafica read FAnagrafica write FAnagrafica;
property RegimeFiscale: WideString read FRegimeFiscale write FRegimeFiscale;
end;
{ TEFatturaHeader_CedentePrestatore_IscrizioneREA }
TEFatturaHeader_CedentePrestatore_IscrizioneREA = class(TPersistent)
private
FCapitaleSociale: WideString;
FNumeroREA: WideString;
FSocioUnico: WideString;
FStatoLiquidazione: WideString;
FUfficio: WideString;
public
constructor Create;
// destructor Destroy; override;
property Ufficio: WideString read FUfficio write FUfficio;
property NumeroREA: WideString read FNumeroREA write FNumeroREA;
property CapitaleSociale: WideString read FCapitaleSociale write FCapitaleSociale;
property SocioUnico: WideString read FSocioUnico write FSocioUnico;
property StatoLiquidazione: WideString read FStatoLiquidazione write FStatoLiquidazione;
end;
TEFatturaHeader_CedentePrestatore = class(TPersistent)
private
FContatti: TEFatturaHeader_Generico_Contatti;
FDatiAnagrafici: TEFatturaHeader_CedentePrestatore_DatiAnagrafici;
FIscrizioneREA: TEFatturaHeader_CedentePrestatore_IscrizioneREA;
FRiferimentoAmministrazione: WideString;
FSede: TEFatturaHeader_Generico_Sede;
FStabileOrganizzazione: TEFatturaHeader_Generico_Sede;
public
constructor Create;
destructor Destroy; override;
property RiferimentoAmministrazione: WideString read FRiferimentoAmministrazione write FRiferimentoAmministrazione;
property DatiAnagrafici: TEFatturaHeader_CedentePrestatore_DatiAnagrafici read FDatiAnagrafici write FDatiAnagrafici;
property Sede: TEFatturaHeader_Generico_Sede read FSede write FSede;
property StabileOrganizzazione: TEFatturaHeader_Generico_Sede read FStabileOrganizzazione write FStabileOrganizzazione;
property IscrizioneREA: TEFatturaHeader_CedentePrestatore_IscrizioneREA read FIscrizioneREA write FIscrizioneREA;
property Contatti: TEFatturaHeader_Generico_Contatti read FContatti write FContatti;
end;
// RappresentanteFiscale
{ TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici }
TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici = class(TPersistent)
private
FAnagrafica: TEFatturaHeader_Generico_Anagrafica;
FCodiceFiscale: WideString;
FIdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA;
FRegimeFiscale: WideString;
public
constructor Create;
destructor Destroy; override;
property RegimeFiscale: WideString read FRegimeFiscale write FRegimeFiscale;
property CodiceFiscale: WideString read FCodiceFiscale write FCodiceFiscale;
property IdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA read FIdFiscaleIVA write FIdFiscaleIVA;
property Anagrafica: TEFatturaHeader_Generico_Anagrafica read FAnagrafica write FAnagrafica;
end;
TEFatturaHeader_RappresentanteFiscale = class(TPersistent)
private
FDatiAnagrafici: TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici;
public
constructor Create;
destructor Destroy; override;
property DatiAnagrafici: TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici read FDatiAnagrafici write FDatiAnagrafici;
end;
// CessionarioCommittente
{ TEFatturaHeader_CessionarioCommittente_DatiAnagrafici }
TEFatturaHeader_CessionarioCommittente_DatiAnagrafici = class(TPersistent)
private
FAnagrafica: TEFatturaHeader_Generico_Anagrafica;
FCodiceFiscale: WideString;
FIdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA;
public
constructor Create;
destructor Destroy; override;
property IdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA read FIdFiscaleIVA write FIdFiscaleIVA;
property CodiceFiscale: WideString read FCodiceFiscale write FCodiceFiscale;
property Anagrafica: TEFatturaHeader_Generico_Anagrafica read FAnagrafica write FAnagrafica;
end;
{ TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale }
TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale = class(TPersistent)
private
FCognome: WideString;
FDenominazione: WideString;
FIdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA;
FNome: WideString;
public
constructor Create;
destructor Destroy; override;
property IdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA read FIdFiscaleIVA write FIdFiscaleIVA;
property Denominazione: WideString read FDenominazione write FDenominazione;
property Nome: WideString read FNome write FNome;
property Cognome: WideString read FCognome write FCognome;
end;
TEFatturaHeader_CessionarioCommittente = class(TPersistent)
private
FDatiAnagrafici: TEFatturaHeader_CessionarioCommittente_DatiAnagrafici;
FRappresentanteFiscale: TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale;
FSede: TEFatturaHeader_Generico_Sede;
FStabileOrganizzazione: TEFatturaHeader_Generico_Sede;
public
constructor Create;
destructor Destroy; override;
property DatiAnagrafici: TEFatturaHeader_CessionarioCommittente_DatiAnagrafici read FDatiAnagrafici write FDatiAnagrafici;
property Sede: TEFatturaHeader_Generico_Sede read FSede write FSede;
property StabileOrganizzazione: TEFatturaHeader_Generico_Sede read FStabileOrganizzazione write FStabileOrganizzazione;
property RappresentanteFiscale: TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale read FRappresentanteFiscale write FRappresentanteFiscale;
end;
// TerzoIntermediarioOSoggettoEmittente
{ TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici }
TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici = class(TPersistent)
private
FAnagrafica: TEFatturaHeader_Generico_Anagrafica;
FCodiceFiscale: WideString;
FIdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA;
public
constructor Create;
destructor Destroy; override;
property IdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA read FIdFiscaleIVA write FIdFiscaleIVA;
property CodiceFiscale: WideString read FCodiceFiscale write FCodiceFiscale;
property Anagrafica: TEFatturaHeader_Generico_Anagrafica read FAnagrafica write FAnagrafica;
end;
TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente = class(TPersistent)
private
FDatiAnagrafici: TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici;
public
constructor Create;
destructor Destroy; override;
property DatiAnagrafici: TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici read FDatiAnagrafici write FDatiAnagrafici;
end;
// TEFatturaHeader
TEFatturaHeader = class(TPersistent)
private
FDatiTrasmissione: TEFatturaHeader_DatiTrasmissione;
FCedentePrestatore: TEFatturaHeader_CedentePrestatore;
FCessionarioCommittente: TEFatturaHeader_CessionarioCommittente;
FTerzoIntermediarioOSoggettoEmittente: TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente;
FSoggettoEmittente: widestring;
public
constructor Create;
destructor Destroy; override;
property DatiTrasmissione: TEFatturaHeader_DatiTrasmissione read FDatiTrasmissione write FDatiTrasmissione;
property CedentePrestatore: TEFatturaHeader_CedentePrestatore read FCedentePrestatore write FCedentePrestatore;
property CessionarioCommittente: TEFatturaHeader_CessionarioCommittente read FCessionarioCommittente write FCessionarioCommittente;
property TerzoIntermediarioOSoggettoEmittente: TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente read FTerzoIntermediarioOSoggettoEmittente write FTerzoIntermediarioOSoggettoEmittente;
property SoggettoEmittente: widestring read FSoggettoEmittente write FSoggettoEmittente;
end;
// ---------------------------------------------------------------------
// TEFatturaBody
// ---------------------------------------------------------------------
{ TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta }
TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta = class(TPersistent)
private
FAliquotaRitenuta: extended;
FCausalePagamento: WideString;
FImportoRitenuta: extended;
FTipoRitenuta: WideString;
public
constructor Create;
// destructor Destroy; override;
property TipoRitenuta: WideString read FTipoRitenuta write FTipoRitenuta;
property ImportoRitenuta: extended read FImportoRitenuta write FImportoRitenuta;
property AliquotaRitenuta: extended read FAliquotaRitenuta write FAliquotaRitenuta;
property CausalePagamento: WideString read FCausalePagamento write FCausalePagamento;
end;
{ TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo }
TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo = class(TPersistent)
private
FBolloVirtuale: WideString;
FImportoBollo: extended;
public
constructor Create;
// destructor Destroy; override;
property BolloVirtuale: WideString read FBolloVirtuale write FBolloVirtuale;
property ImportoBollo: extended read FImportoBollo write FImportoBollo;
end;
{ TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiCassaPrevidenziale }
TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiCassaPrevidenziale = class(TPersistent)
public
end;
// TEFatturaBody_DatiGeneraliDocumento
TEFatturaBody_DatiGenerali_DatiGeneraliDocumento = class(TPersistent)
private
FData: TDate;
FDatiBollo: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo;
FDatiCassaPrevidenziale: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiCassaPrevidenziale;
FDatiRitenuta: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta;
FDivisa: WideString;
FImportoTotaleDocumentoAZero: boolean;
FNumero: WideString;
FTipoDocumento: WideString;
FImportoTotaleDocumento: extended;
FArrotondamento: extended;
FCausale: TStringList;
FArt73: WideString;
function GetImportoTotaleDocumentoIsAssigned: boolean;
public
ScontoMaggiorazione_Lista: TEFatturaBody_Generico_ScontoMaggiorazione_Lista;
property ImportoTotaleDocumentoIsAssegned: boolean read GetImportoTotaleDocumentoIsAssigned;
property ImportoTotaleDocumentoAZero: boolean read FImportoTotaleDocumentoAZero write FImportoTotaleDocumentoAZero;
public
constructor Create;
destructor Destroy; override;
property TipoDocumento: WideString read FTipoDocumento write FTipoDocumento;
property Divisa: WideString read FDivisa write FDivisa;
property Data: TDate read FData write FData;
property Numero: WideString read FNumero write FNumero;
property DatiRitenuta: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta read FDatiRitenuta write FDatiRitenuta;
property DatiBollo: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo read FDatiBollo write FDatiBollo;
property DatiCassaPrevidenziale: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiCassaPrevidenziale read FDatiCassaPrevidenziale write FDatiCassaPrevidenziale;
property ImportoTotaleDocumento: extended read FImportoTotaleDocumento write FImportoTotaleDocumento;
property Arrotondamento: extended read FArrotondamento write FArrotondamento;
property Causale: TStringList read FCausale write FCausale;
property Art73: WideString read FArt73 write FArt73;
end;
// TEFatturaBody_DatiOrdineAcquisto
{ TEFatturaBody_DatiGenerali_DatiOrdineAcquisto }
TEFatturaBody_DatiGenerali_DatiOrdineAcquisto = class(TPersistent)
private
FCodiceCIG: WideString;
FCodiceCommessaConvenzione: WideString;
FCodiceCUP: WideString;
FData: TDate;
FIdDocumento: WideString;
FNumItem: WideString;
FRiferimentoNumeroLinea: TStringList;
function GetAssigned: boolean;
public
constructor Create;
destructor Destroy; override;
property IsAssigned: boolean read GetAssigned;
property RiferimentoNumeroLinea: TStringList read FRiferimentoNumeroLinea write FRiferimentoNumeroLinea;
property IdDocumento: WideString read FIdDocumento write FIdDocumento;
property Data: TDate read FData write FData;
property NumItem: WideString read FNumItem write FNumItem;
property CodiceCommessaConvenzione: WideString read FCodiceCommessaConvenzione write FCodiceCommessaConvenzione;
property CodiceCUP: WideString read FCodiceCUP write FCodiceCUP;
property CodiceCIG: WideString read FCodiceCIG write FCodiceCIG;
end;
{ TEFatturaBody_DatiGenerali_DatiOrdineAcquisto_Lista }
TEFatturaBody_DatiGenerali_DatiOrdineAcquisto_Lista = specialize TFPGObjectList<TEFatturaBody_DatiGenerali_DatiOrdineAcquisto>;
// TEFatturaBody_DatiGenerali_DatiContratto (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiConvenzione (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiRicezione (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiFattureCollegate (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiSAL (opzionale)
// TEFatturaBody_DatiGenerali_DatiDDT
TEFatturaBody_DatiGenerali_DatiDDT = class(TPersistent)
private
FDataDDT: TDate;
FNumeroDDT: WideString;
FRiferimentoNumeroLinea: TStringList;
public
constructor Create;
destructor Destroy; override;
property NumeroDDT: WideString read FNumeroDDT write FNumeroDDT;
property DataDDT: TDate read FDataDDT write FDataDDT;
property RiferimentoNumeroLinea: TStringList read FRiferimentoNumeroLinea write FRiferimentoNumeroLinea;
end;
{ TEFatturaBody_DatiGenerali_DatiDDT }
TEFatturaBody_DatiGenerali_DatiDDT_Lista = specialize TFPGObjectList<TEFatturaBody_DatiGenerali_DatiDDT>;
{ TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore }
TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore = class(TPersistent)
private
FAnagrafica: TEFatturaHeader_Generico_Anagrafica;
FCodiceFiscale: WideString;
FIdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA;
FNumeroLicenzaGuida: WideString;
function GetIsAssigned: boolean;
public
property IsAssigned: boolean read GetIsAssigned;
public
constructor Create;
destructor Destroy; override;
property IdFiscaleIVA: TEFatturaHeader_Generico_IdFiscaleIVA read FIdFiscaleIVA write FIdFiscaleIVA;
property CodiceFiscale: WideString read FCodiceFiscale write FCodiceFiscale;
property Anagrafica: TEFatturaHeader_Generico_Anagrafica read FAnagrafica write FAnagrafica;
property NumeroLicenzaGuida: WideString read FNumeroLicenzaGuida write FNumeroLicenzaGuida;
end;
{ TEFatturaBody_DatiGenerali_DatiTrasporto }
TEFatturaBody_DatiGenerali_DatiTrasporto = class(TPersistent)
private
FCausaleTrasporto: WideString;
FDataInizioTrasporto: TDateTime;
FDataOraConsegna: tdatetime;
FDataOraRitiro: TDateTime;
FDatiAnagraficiVettore: TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore;
FDescrizione: WideString;
FIndirizzoResa: TEFatturaHeader_Generico_Sede;
FMezzoTrasporto: WideString;
FNumeroColli: integer;
FPesoLordo: extended;
FPesoNetto: extended;
FTipoResa: WideString;
FUnitaMisuraPeso: WideString;
function GetIsAssigned: boolean;
public
property IsAssigned: boolean read GetIsAssigned;
public
constructor Create;
destructor Destroy; override;
property DatiAnagraficiVettore: TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore read FDatiAnagraficiVettore write FDatiAnagraficiVettore;
property MezzoTrasporto: WideString read FMezzoTrasporto write FMezzoTrasporto;
property CausaleTrasporto: WideString read FCausaleTrasporto write FCausaleTrasporto;
property NumeroColli: integer read FNumeroColli write FNumeroColli;
property Descrizione: WideString read FDescrizione write FDescrizione;
property UnitaMisuraPeso: WideString read FUnitaMisuraPeso write FUnitaMisuraPeso;
property PesoLordo: extended read FPesoLordo write FPesoLordo;
property PesoNetto: extended read FPesoNetto write FPesoNetto;
property DataOraRitiro: TDateTime read FDataOraRitiro write FDataOraRitiro;
property DataInizioTrasporto: TDate read FDataInizioTrasporto write FDataInizioTrasporto;
property TipoResa: WideString read FTipoResa write FTipoResa;
property IndirizzoResa: TEFatturaHeader_Generico_Sede read FIndirizzoResa write FIndirizzoResa;
property DataOraConsegna: TDateTime read FDataOraConsegna write FDataOraConsegna;
end;
// TEFatturaBody_DatiGenerali
TEFatturaBody_DatiGenerali = class(TPersistent)
private
FDatiGeneraliDocumento: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento;
FDatiTrasporto: TEFatturaBody_DatiGenerali_DatiTrasporto;
public
DatiOrdineAcquisto_Lista: TEFatturaBody_DatiGenerali_DatiOrdineAcquisto_Lista;
DatiDDT_Lista: TEFatturaBody_DatiGenerali_DatiDDT_Lista;
public
constructor Create;
destructor Destroy; override;
property DatiGeneraliDocumento: TEFatturaBody_DatiGenerali_DatiGeneraliDocumento read FDatiGeneraliDocumento write FDatiGeneraliDocumento;
// TEFatturaBody_DatiGenerali_DatiContratto (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiConvenzione (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiRicezione (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiFattureCollegate (opzionale, ripetuto)
// TEFatturaBody_DatiGenerali_DatiSAL (opzionale)
property DatiTrasporto: TEFatturaBody_DatiGenerali_DatiTrasporto read FDatiTrasporto write FDatiTrasporto;
end;
// TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo
TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo = class(TPersistent)
private
FCodiceTipo: WideString;
FCodiceValore: WideString;
public
constructor Create;
property CodiceTipo: WideString read FCodiceTipo write FCodiceTipo;
property CodiceValore: WideString read FCodiceValore write FCodiceValore;
end;
{ TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo_Lista }
TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo_Lista = specialize TFPGObjectList<TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo>;
// TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali
TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali = class(TPersistent)
private
FRiferimentoData: TDate;
FRiferimentoNumero: integer;
FRiferimentoTesto: WideString;
FTipoDato: WideString;
public
constructor Create;
property TipoDato: WideString read FTipoDato write FTipoDato;
property RiferimentoTesto: WideString read FRiferimentoTesto write FRiferimentoTesto;
property RiferimentoNumero: integer read FRiferimentoNumero write FRiferimentoNumero;
property RiferimentoData: TDate read FRiferimentoData write FRiferimentoData;
end;
{ TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali_Lista }
TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali_Lista = specialize TFPGObjectList<TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali>;
// TEFatturaBody_DatiBeniServizi_DettaglioLinee
TEFatturaBody_DatiBeniServizi_DettaglioLinee = class(TPersistent)
private
FAliquotaIVA: extended;
FDataFinePeriodo: TDate;
FDataInizioPeriodo: TDate;
FDescrizione: WideString;
FLineaDescrittiva: boolean;
FNatura: WideString;
FNumeroLinea: integer;
FPrezzoTotale: extended;
FPrezzoUnitario: extended;
FQuantita: extended;
FRiferimentoAmministrazione: WideString;
FRitenuta: WideString;
FTipoCessionePrestazione: WideString;
FUnitaMisura: WideString;
public
CodiceArticolo: TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo_Lista;
ScontoMaggiorazione: TEFatturaBody_Generico_ScontoMaggiorazione_Lista;
AltriDatiGestionali: TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali_Lista;
property LineaDescrittiva: boolean read FLineaDescrittiva write FLineaDescrittiva;
public
constructor Create;
destructor Destroy; override;
property NumeroLinea: integer read FNumeroLinea write FNumeroLinea;
property TipoCessionePrestazione: WideString read FTipoCessionePrestazione write FTipoCessionePrestazione;
// property CodiceArticolo
property Descrizione: WideString read FDescrizione write FDescrizione;
property Quantita: extended read FQuantita write FQuantita;
property UnitaMisura: WideString read FUnitaMisura write FUnitaMisura;
property DataInizioPeriodo: TDate read FDataInizioPeriodo write FDataInizioPeriodo;
property DataFinePeriodo: TDate read FDataFinePeriodo write FDataFinePeriodo;
property PrezzoUnitario: extended read FPrezzoUnitario write FPrezzoUnitario;
// property ScontoMaggiorazione
property PrezzoTotale: extended read FPrezzoTotale write FPrezzoTotale;
property AliquotaIVA: extended read FAliquotaIVA write FAliquotaIVA;
property Ritenuta: WideString read FRitenuta write FRitenuta;
property Natura: WideString read FNatura write FNatura;
property RiferimentoAmministrazione: WideString read FRiferimentoAmministrazione write FRiferimentoAmministrazione;
// property AltriDatiGestionali
end;
{ TEFatturaBody_DatiBeniServizi_DettaglioLinee_Lista }
TEFatturaBody_DatiBeniServizi_DettaglioLinee_Lista = specialize TFPGObjectList<TEFatturaBody_DatiBeniServizi_DettaglioLinee>;
// TEFatturaBody_DatiBeniServizi_DatiRiepilogo
TEFatturaBody_DatiBeniServizi_DatiRiepilogo = class(TPersistent)
private
FAliquotaIVA: extended;
FArrotondamento: extended;
FEsigibilitaIVA: WideString;
FImponibileImporto: extended;
FImposta: extended;
FNatura: WideString;
FRiferimentoNormativo: WideString;
FSpeseAccessorie: extended;
public
constructor Create;
// destructor Destroy; override;
property AliquotaIVA: extended read FAliquotaIVA write FAliquotaIVA;
property Natura: WideString read FNatura write FNatura;
property SpeseAccessorie: extended read FSpeseAccessorie write FSpeseAccessorie;
property Arrotondamento: extended read FArrotondamento write FArrotondamento;
property ImponibileImporto: extended read FImponibileImporto write FImponibileImporto;
property Imposta: extended read FImposta write FImposta;
property EsigibilitaIVA: WideString read FEsigibilitaIVA write FEsigibilitaIVA;
property RiferimentoNormativo: WideString read FRiferimentoNormativo write FRiferimentoNormativo;
end;
{ TEFatturaBody_DatiBeniServizi_DatiRiepilogo_Lista }
TEFatturaBody_DatiBeniServizi_DatiRiepilogo_Lista = specialize TFPGObjectList<TEFatturaBody_DatiBeniServizi_DatiRiepilogo>;
// TEFatturaBody_DatiBeniServizi
TEFatturaBody_DatiBeniServizi = class(TPersistent)
private
FDatiRiepilogo: TEFatturaBody_DatiBeniServizi_DatiRiepilogo_Lista;
FDettaglioLinee: TEFatturaBody_DatiBeniServizi_DettaglioLinee_Lista;
public
property DettaglioLinee: TEFatturaBody_DatiBeniServizi_DettaglioLinee_Lista read FDettaglioLinee write FDettaglioLinee;
property DatiRiepilogo: TEFatturaBody_DatiBeniServizi_DatiRiepilogo_Lista read FDatiRiepilogo write FDatiRiepilogo;
public
constructor Create;
destructor Destroy; override;
end;
// TEFatturaBody_DatiPagamento_DettaglioPagamento
TEFatturaBody_DatiPagamento_DettaglioPagamento = class(TPersistent)
private
FABI: Widestring;
FBeneficiario: Widestring;
FBIC: Widestring;
FCAB: Widestring;
FCFQuietanzante: Widestring;
FCodicePagamento: Widestring;
FCodUfficioPostale: Widestring;
FCognomeQuietanzante: Widestring;
FDataDecorrenzaPenale: TDate;
FDataLimitePagamentoAnticipato: TDate;
FDataRiferimentoTerminiPagamento: TDate;
FDataScadenzaPagamento: TDate;
FGiorniTerminiPagamento: integer;
FIBAN: Widestring;
FImportoPagamento: extended;
FIstitutoFinanziario: Widestring;
FModalitaPagamento: Widestring;
FNomeQuietanzante: Widestring;
FPenalitaPagamentiRitardati: extended;
FScontoPagamentoAnticipato: extended;
FTitoloQuietanzante: Widestring;
public
constructor Create;
property Beneficiario: Widestring read FBeneficiario write FBeneficiario;
property ModalitaPagamento: Widestring read FModalitaPagamento write FModalitaPagamento;
property DataRiferimentoTerminiPagamento: TDate read FDataRiferimentoTerminiPagamento write FDataRiferimentoTerminiPagamento;
property GiorniTerminiPagamento:integer read FGiorniTerminiPagamento write FGiorniTerminiPagamento;
property DataScadenzaPagamento: TDate read FDataScadenzaPagamento write FDataScadenzaPagamento;
property ImportoPagamento: extended read FImportoPagamento write FImportoPagamento;
property CodUfficioPostale: Widestring read FCodUfficioPostale write FCodUfficioPostale;
property CognomeQuietanzante: Widestring read FCognomeQuietanzante write FCognomeQuietanzante;
property NomeQuietanzante: Widestring read FNomeQuietanzante write FNomeQuietanzante;
property CFQuietanzante: Widestring read FCFQuietanzante write FCFQuietanzante;
property TitoloQuietanzante: Widestring read FTitoloQuietanzante write FTitoloQuietanzante;
property IstitutoFinanziario: Widestring read FIstitutoFinanziario write FIstitutoFinanziario;
property IBAN: Widestring read FIBAN write FIBAN;
property ABI: Widestring read FABI write FABI;
property CAB: Widestring read FCAB write FCAB;
property BIC: Widestring read FBIC write FBIC;
property ScontoPagamentoAnticipato: extended read FScontoPagamentoAnticipato write FScontoPagamentoAnticipato;
property DataLimitePagamentoAnticipato: TDate read FDataLimitePagamentoAnticipato write FDataLimitePagamentoAnticipato;
property PenalitaPagamentiRitardati: extended read FPenalitaPagamentiRitardati write FPenalitaPagamentiRitardati;
property DataDecorrenzaPenale: TDate read FDataDecorrenzaPenale write FDataDecorrenzaPenale;
property CodicePagamento: Widestring read FCodicePagamento write FCodicePagamento;
end;
{ TEFatturaBody_DatiPagamento_DettaglioPagamento_Lista }
TEFatturaBody_DatiPagamento_DettaglioPagamento_Lista = specialize TFPGObjectList<TEFatturaBody_DatiPagamento_DettaglioPagamento>;
// TEFatturaBody_DatiPagamento
TEFatturaBody_DatiPagamento = class(TPersistent)
private
FCondizioniPagamento: WideString;
public
DettaglioPagamento_Lista: TEFatturaBody_DatiPagamento_DettaglioPagamento_Lista;
public
constructor Create;
destructor Destroy; override;
property CondizioniPagamento: WideString read FCondizioniPagamento write FCondizioniPagamento;
end;
{ TEFatturaBody_DatiPagamento_Lista }
TEFatturaBody_DatiPagamento_Lista = specialize TFPGObjectList<TEFatturaBody_DatiPagamento>;
// TEFatturaBody
TEFatturaBody = class(TPersistent)
private
FDatiBeniServizi: TEFatturaBody_DatiBeniServizi;
FDatiGenerali: TEFatturaBody_DatiGenerali;
public
Datipagamento: TEFatturaBody_DatiPagamento_Lista;
public
constructor Create;
destructor Destroy; override;
property DatiGenerali: TEFatturaBody_DatiGenerali read FDatiGenerali write FDatiGenerali;
property DatiBeniServizi: TEFatturaBody_DatiBeniServizi read FDatiBeniServizi write FDatiBeniServizi;
end;
{ TEFatturaBody_Lista }
TEFatturaBody_Lista = specialize TFPGObjectList<TEFatturaBody>;
// TEFattura
TEFattura=class(TPersistent)
private
FFatturaElettronicaHeader: TEFatturaHeader;
FVersione: WideString;
// FFatturaElettronicaBody: TEFatturaBody;
public
FatturaElettronicaBody_Lista: TEFatturaBody_Lista;
public
constructor Create;
destructor Destroy; override;
published
property Versione: WideString read FVersione write FVersione;
property FatturaElettronicaHeader: TEFatturaHeader read FFatturaElettronicaHeader write FFatturaElettronicaHeader;
// property FatturaElettronicaBody: TEFatturaBody read FFatturaElettronicaBody write FFatturaElettronicaBody;
end;
// functions
function eFattura_FormatDateTime(AValue: TDateTime): WideString;
function eFattura_FormatDate(AValue: TDate): WideString;
function eFattura_FormatImporto(AValue: extended): WideString;
function eFattura_FormatAliquota(AValue: extended): WideString;
function eFattura_FormatQuantita(AValue: extended): WideString;
function eFattura_FormatPrezzoUnitario(AValue: extended): WideString;
function eFattura_FormatScontoMagg(AValue: extended): WideString;
implementation
function eFattura_FormatDateTime(AValue: TDateTime): WideString;
begin
result := WideString(FormatDateTime('yyyy-mm-dd', AValue)) +
'T' +
WideString(FormatDateTime('hh:nn:ss.000', AValue)) +
'+02:00';
end;
function eFattura_FormatDate(AValue: TDate): WideString;
begin
result := WideString(FormatDateTime('yyyy-mm-dd', AValue));
end;
function eFattura_FormatImporto(AValue: extended): WideString;
var fs: TFormatSettings;
begin
fs.DecimalSeparator:='.';
fs.ThousandSeparator:=',';
result := WideString(FloatToStrF(AValue,ffFixed,999999999,2,fs));
end;
function eFattura_FormatAliquota(AValue: extended): WideString;
var fs: TFormatSettings;
begin
fs.DecimalSeparator:='.';
fs.ThousandSeparator:=',';
// result := WideString(FloatToStr(AValue));
result := WideString(FloatToStrF(AValue,ffFixed,9999,2,fs));
end;
function eFattura_FormatQuantita(AValue: extended): WideString;
var fs: TFormatSettings;
begin
fs.DecimalSeparator:='.';
fs.ThousandSeparator:=',';
// result := WideString(FloatToStrF(AValue,ffFixed,999999999,10,fs));
result:= WideString(FormatFloat('0.0000000#', AValue, fs));
end;
function eFattura_FormatPrezzoUnitario(AValue: extended): WideString;
var fs: TFormatSettings;
begin
fs.DecimalSeparator:='.';
fs.ThousandSeparator:=',';
// result := WideString(FloatToStrF(AValue,ffFixed,999999999,10,fs));
result:= WideString(FormatFloat('0.0000000#', AValue, fs));
end;
function eFattura_FormatScontoMagg(AValue: extended): WideString;
var fs: TFormatSettings;
begin
fs.DecimalSeparator:='.';
fs.ThousandSeparator:=',';
// result := WideString(FloatToStrF(AValue,ffFixed,999999999,10,fs));
result:= WideString(FormatFloat('0.00######', AValue, fs));
end;
{ TEFatturaBody_DatiPagamento }
constructor TEFatturaBody_DatiPagamento.Create;
begin
DettaglioPagamento_Lista:=TEFatturaBody_DatiPagamento_DettaglioPagamento_Lista.Create(True);
end;
destructor TEFatturaBody_DatiPagamento.Destroy;
begin
FreeAndNil(DettaglioPagamento_Lista);
inherited Destroy;
end;
{ TEFatturaBody_DatiPagamento_DettaglioPagamento }
constructor TEFatturaBody_DatiPagamento_DettaglioPagamento.Create;
begin
FABI:='';
FBeneficiario:='';
FBIC:='';
FCAB:='';
FCFQuietanzante:='';
FCodicePagamento:='';
FCodUfficioPostale:='';
FCognomeQuietanzante:='';
FDataDecorrenzaPenale:=0;
FDataLimitePagamentoAnticipato:=0;
FDataRiferimentoTerminiPagamento:=0;
FDataScadenzaPagamento:=0;
FGiorniTerminiPagamento:=0;
FIBAN:='';
FImportoPagamento:=0.0;
FIstitutoFinanziario:='';
FModalitaPagamento:='';
FNomeQuietanzante:='';
FPenalitaPagamentiRitardati:=0.0;
FScontoPagamentoAnticipato:=0.0;
FTitoloQuietanzante:='';
end;
{ TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali }
constructor TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali.Create;
begin
FRiferimentoData:=0;
FRiferimentoNumero:=0;
FRiferimentoTesto:='';
FTipoDato:='';
end;
{ TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo }
constructor TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo.Create;
begin
FCodiceTipo:='';
FCodiceValore:='';
end;
{ TEFatturaBody_DatiBeniServizi }
constructor TEFatturaBody_DatiBeniServizi.Create;
begin
FDatiRiepilogo:=TEFatturaBody_DatiBeniServizi_DatiRiepilogo_Lista.Create(True);
FDettaglioLinee:=TEFatturaBody_DatiBeniServizi_DettaglioLinee_Lista.Create(True);
end;
destructor TEFatturaBody_DatiBeniServizi.Destroy;
begin
FreeAndNil(FDatiRiepilogo);
FreeAndNil(FDettaglioLinee);
inherited Destroy;
end;
{ TEFatturaBody_DatiBeniServizi_DatiRiepilogo }
constructor TEFatturaBody_DatiBeniServizi_DatiRiepilogo.Create;
begin
FAliquotaIVA:=0.0;
FArrotondamento:=0.0;
FEsigibilitaIVA:='';
FImponibileImporto:=0.0;
FImposta:=0.0;
FNatura:='';
FRiferimentoNormativo:='';
FSpeseAccessorie:=0.0;
end;
{ TEFatturaBody_DatiBeniServizi_DettaglioLinee }
constructor TEFatturaBody_DatiBeniServizi_DettaglioLinee.Create;
begin
FAliquotaIVA:=0.0;
FDataFinePeriodo:=0;
FDataInizioPeriodo:=0;
FDescrizione:='';
FNatura:='';
FNumeroLinea:=0;
FPrezzoTotale:=0.0;
FPrezzoUnitario:=0.0;
FQuantita:=0.0;
FRiferimentoAmministrazione:='';
FRitenuta:='';
FTipoCessionePrestazione:='';
FUnitaMisura:='';
FLineaDescrittiva:=False;
CodiceArticolo:=TEFatturaBody_DatiBeniServizi_DettaglioLinee_CodiceArticolo_Lista.Create(True);
ScontoMaggiorazione:=TEFatturaBody_Generico_ScontoMaggiorazione_Lista.Create(True);
AltriDatiGestionali:=TEFatturaBody_DatiBeniServizi_DettaglioLinee_AltriDatiGestionali_Lista.Create(True);
end;
destructor TEFatturaBody_DatiBeniServizi_DettaglioLinee.Destroy;
begin
FreeAndNil(CodiceArticolo);
FreeAndNil(ScontoMaggiorazione);
FreeAndNil(AltriDatiGestionali);
inherited Destroy;
end;
{ TEFatturaBody_DatiGenerali_DatiTrasporto }
function TEFatturaBody_DatiGenerali_DatiTrasporto.GetIsAssigned: boolean;
begin
result := FDatiAnagraficiVettore.IsAssigned
or
FIndirizzoResa.IsAssigned
or
(FCausaleTrasporto<>'')
or
(FDataInizioTrasporto<>0)
or
(FDataOraConsegna<>0)
or
(FDataOraRitiro<>0)
or
(FDescrizione<>'')
or
(FMezzoTrasporto<>'')
or
(FNumeroColli<>0)
or
(FPesoLordo<>0)
or
(FPesoNetto<>0)
or
(FTipoResa<>'')
or
(FUnitaMisuraPeso<>'');
end;
constructor TEFatturaBody_DatiGenerali_DatiTrasporto.Create;
begin
FCausaleTrasporto:='';
FDataInizioTrasporto:=0;
FDataOraConsegna:=0;
FDataOraRitiro:=0;
FDescrizione:='';
FMezzoTrasporto:='';
FNumeroColli:=0;
FPesoLordo:=0;
FPesoNetto:=0;
FTipoResa:='';
FUnitaMisuraPeso:='';
FIndirizzoResa:=TEFatturaHeader_Generico_Sede.Create;
FDatiAnagraficiVettore:=TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore.Create;
end;
destructor TEFatturaBody_DatiGenerali_DatiTrasporto.Destroy;
begin
FreeAndNil(FIndirizzoResa);
FreeAndNil(FDatiAnagraficiVettore);
inherited Destroy;
end;
{ TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore }
function TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore.GetIsAssigned: boolean;
begin
result := FAnagrafica.IsAssigned
or
FIdFiscaleIVA.IsAssigned
or
(FCodiceFiscale<>'');
end;
constructor TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore.Create;
begin
FCodiceFiscale:='';
FNumeroLicenzaGuida:='';
FAnagrafica:=TEFatturaHeader_Generico_Anagrafica.Create;
FIdFiscaleIVA:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
end;
destructor TEFatturaBody_DatiGenerali_DatiTrasporto_DatiAnagraficiVettore.Destroy;
begin
FreeAndNil(FAnagrafica);
FreeAndNil(FIdFiscaleIVA);
inherited Destroy;
end;
{ TEFatturaBody_DatiGenerali_DatiDDT }
constructor TEFatturaBody_DatiGenerali_DatiDDT.Create;
begin
FDataDDT:=0;
FNumeroDDT:='';
FRiferimentoNumeroLinea:=TStringList.Create;
end;
destructor TEFatturaBody_DatiGenerali_DatiDDT.Destroy;
begin
FreeAndNil(FRiferimentoNumeroLinea);
inherited Destroy;
end;
{ TEFatturaBody_DatiGenerali }
constructor TEFatturaBody_DatiGenerali.Create;
begin
FDatiGeneraliDocumento:=TEFatturaBody_DatiGenerali_DatiGeneraliDocumento.Create;
FDatiTrasporto:=TEFatturaBody_DatiGenerali_DatiTrasporto.Create;
DatiOrdineAcquisto_Lista:=TEFatturaBody_DatiGenerali_DatiOrdineAcquisto_Lista.Create(True);
DatiDDT_Lista:=TEFatturaBody_DatiGenerali_DatiDDT_Lista.Create(True);
end;
destructor TEFatturaBody_DatiGenerali.Destroy;
begin
FreeAndNil(DatiDDT_Lista);
FreeAndNil(DatiOrdineAcquisto_Lista);
FreeAndNil(FDatiTrasporto);
FreeAndNil(FDatiGeneraliDocumento);
inherited Destroy;
end;
{ TEFatturaBody_DatiGenerali_DatiOrdineAcquisto }
function TEFatturaBody_DatiGenerali_DatiOrdineAcquisto.GetAssigned: boolean;
begin
result := (Trim(FCodiceCIG)<>'')
or
(Trim(FCodiceCommessaConvenzione)<>'')
or
(Trim(FCodiceCUP)<>'')
or
(Trim(FIdDocumento)<>'')
;
end;
constructor TEFatturaBody_DatiGenerali_DatiOrdineAcquisto.Create;
begin
FCodiceCIG:='';
FCodiceCommessaConvenzione:='';
FCodiceCUP:='';
FData:=0;
FIdDocumento:='';
FNumItem:='';
FRiferimentoNumeroLinea:=TStringList.Create;
end;
destructor TEFatturaBody_DatiGenerali_DatiOrdineAcquisto.Destroy;
begin
FreeAndNil(FRiferimentoNumeroLinea);
inherited Destroy;
end;
{ TEFatturaBody_Generico_ScontoMaggiorazione }
constructor TEFatturaBody_Generico_ScontoMaggiorazione.Create;
begin
FImporto:=0.0;
FPercentuale:=0.0;
FTipo:='';
end;
{ TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo }
constructor TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo.Create;
begin
FBolloVirtuale:='';
FImportoBollo:=0.0;
end;
{ TEFatturaBody_DatiGenerali_DatiGeneraliDocumento }
function TEFatturaBody_DatiGenerali_DatiGeneraliDocumento.GetImportoTotaleDocumentoIsAssigned: boolean;
begin
result := (FImportoTotaleDocumento <> 0.0)
or
((FImportoTotaleDocumento = 0.0) and FImportoTotaleDocumentoAZero);
end;
constructor TEFatturaBody_DatiGenerali_DatiGeneraliDocumento.Create;
begin
ScontoMaggiorazione_Lista:=TEFatturaBody_Generico_ScontoMaggiorazione_Lista.Create(True);
FData:=0.0;
FDivisa:='';
FNumero:='';
FTipoDocumento:='';
FImportoTotaleDocumento:=0.0;
FArrotondamento:=0.0;
FArt73:='';
FImportoTotaleDocumentoAZero:= False;
FDatiBollo:=TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiBollo.Create;
FDatiCassaPrevidenziale:=TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiCassaPrevidenziale.Create;
FDatiRitenuta:=TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta.Create;
FCausale:=TStringList.Create;
end;
destructor TEFatturaBody_DatiGenerali_DatiGeneraliDocumento.Destroy;
begin
FreeAndNil(ScontoMaggiorazione_Lista);
FreeAndNil(FCausale);
FreeAndNil(FDatiBollo);
FreeAndNil(FDatiCassaPrevidenziale);
FreeAndNil(FDatiRitenuta);
inherited Destroy;
end;
{ TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta }
constructor TEFatturaBody_DatiGenerali_DatiGeneraliDocumento_DatiRitenuta.Create;
begin
FAliquotaRitenuta:=0.0;
FCausalePagamento:='';
FImportoRitenuta:=0.0;
FTipoRitenuta:='';
end;
{ TEFatturaBody }
constructor TEFatturaBody.Create;
begin
FDatiGenerali:=TEFatturaBody_DatiGenerali.Create;
FDatiBeniServizi:=TEFatturaBody_DatiBeniServizi.Create;
Datipagamento:=TEFatturaBody_DatiPagamento_Lista.Create(True);
end;
destructor TEFatturaBody.Destroy;
begin
FreeAndNil(FDatiGenerali);
FreeAndNil(FDatiBeniServizi);
FreeAndNil(Datipagamento);
inherited Destroy;
end;
{ TEFatturaHeader_Generico_IdFiscaleIVA }
function TEFatturaHeader_Generico_IdFiscaleIVA.GetAssigned: boolean;
begin
result := (FIdCodice <> '') and (FIdPaese <> '');
end;
constructor TEFatturaHeader_Generico_IdFiscaleIVA.Create;
begin
FIdCodice:='';
FIdPaese:='';
end;
{ TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente }
constructor TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente.Create;
begin
FDatiAnagrafici:=TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici.Create;
end;
destructor TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente.Destroy;
begin
FreeAndNil(FDatiAnagrafici);
inherited Destroy;
end;
{ TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici }
constructor TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici.Create;
begin
FCodiceFiscale:='';
FIdFiscaleIVA:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
FAnagrafica:=TEFatturaHeader_Generico_Anagrafica.Create;
end;
destructor TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente_DatiAnagrafici.Destroy;
begin
FreeAndNil(FIdFiscaleIVA);
FreeAndNil(FAnagrafica);
inherited Destroy;
end;
{ TEFatturaHeader_CessionarioCommittente }
constructor TEFatturaHeader_CessionarioCommittente.Create;
begin
FDatiAnagrafici:=TEFatturaHeader_CessionarioCommittente_DatiAnagrafici.Create;
FRappresentanteFiscale:=TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale.Create;
FSede:=TEFatturaHeader_Generico_Sede.Create;
FStabileOrganizzazione:=TEFatturaHeader_Generico_Sede.Create;
end;
destructor TEFatturaHeader_CessionarioCommittente.Destroy;
begin
FreeAndNil(FDatiAnagrafici);
FreeAndNil(FRappresentanteFiscale);
FreeAndNil(FSede);
FreeAndNil(FStabileOrganizzazione);
inherited Destroy;
end;
{ TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale }
constructor TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale.Create;
begin
FCognome:='';
FDenominazione:='';
FNome:='';
FIdFiscaleIVA:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
end;
destructor TEFatturaHeader_CessionarioCommittente_RappresentanteFiscale.Destroy;
begin
FreeAndNil(FIdFiscaleIVA);
inherited Destroy;
end;
{ TEFatturaHeader_CessionarioCommittente_DatiAnagrafici }
constructor TEFatturaHeader_CessionarioCommittente_DatiAnagrafici.Create;
begin
FCodiceFiscale:='';
FAnagrafica:=TEFatturaHeader_Generico_Anagrafica.Create;
FIdFiscaleIVA:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
end;
destructor TEFatturaHeader_CessionarioCommittente_DatiAnagrafici.Destroy;
begin
FreeAndNil(FIdFiscaleIVA);
FreeAndNil(FAnagrafica);
inherited Destroy;
end;
{ TEFatturaHeader_RappresentanteFiscale }
constructor TEFatturaHeader_RappresentanteFiscale.Create;
begin
FDatiAnagrafici:=TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici.Create;
end;
destructor TEFatturaHeader_RappresentanteFiscale.Destroy;
begin
FreeAndNil(FDatiAnagrafici);
inherited Destroy;
end;
{ TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici }
constructor TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici.Create;
begin
FRegimeFiscale:='';
FCodiceFiscale:='';
FAnagrafica:=TEFatturaHeader_Generico_Anagrafica.Create;
FIdFiscaleIVA:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
end;
destructor TEFatturaHeader_RappresentanteFiscale_DatiAnagrafici.Destroy;
begin
FreeAndNil(FIdFiscaleIVA);
FreeAndNil(FAnagrafica);
inherited Destroy;
end;
{ TEFatturaHeader_CedentePrestatore }
constructor TEFatturaHeader_CedentePrestatore.Create;
begin
FRiferimentoAmministrazione:='';
FContatti:=TEFatturaHeader_Generico_Contatti.Create;
FDatiAnagrafici:=TEFatturaHeader_CedentePrestatore_DatiAnagrafici.Create;
FIscrizioneREA:=TEFatturaHeader_CedentePrestatore_IscrizioneREA.Create;
FSede:=TEFatturaHeader_Generico_Sede.Create;
FStabileOrganizzazione:=TEFatturaHeader_Generico_Sede.Create;
end;
destructor TEFatturaHeader_CedentePrestatore.Destroy;
begin
FreeAndNil(FContatti);
FreeAndNil(FDatiAnagrafici);
FreeAndNil(FIscrizioneREA);
FreeAndNil(FSede);
FreeAndNil(FStabileOrganizzazione);
inherited Destroy;
end;
{ TEFatturaHeader_CedentePrestatore_IscrizioneREA }
constructor TEFatturaHeader_CedentePrestatore_IscrizioneREA.Create;
begin
Ufficio:='';
NumeroREA:='';
CapitaleSociale:='';
SocioUnico:='';
StatoLiquidazione:='';
end;
{ TEFatturaHeader_CedentePrestatore_DatiAnagrafici }
constructor TEFatturaHeader_CedentePrestatore_DatiAnagrafici.Create;
begin
FRegimeFiscale:='';
FAnagrafica:=TEFatturaHeader_Generico_Anagrafica.Create;
FIdFiscaleIVA:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
end;
destructor TEFatturaHeader_CedentePrestatore_DatiAnagrafici.Destroy;
begin
FreeAndNil(FIdFiscaleIVA);
FreeAndNil(FAnagrafica);
inherited Destroy;
end;
{ TEFatturaHeader_DatiTrasmissione }
constructor TEFatturaHeader_DatiTrasmissione.Create;
begin
FCodiceDestinatario:='';
FFormatoTrasmissione:='';
FPecDestinatario:='';
FProgressivoInvio:='';
FIdTrasmittente:=TEFatturaHeader_Generico_IdFiscaleIVA.Create;
FContattiTrasmittente:=TEFatturaHeader_Generico_Contatti.Create;
end;
destructor TEFatturaHeader_DatiTrasmissione.Destroy;
begin
FreeAndNil(FIdTrasmittente);
FreeAndNil(FContattiTrasmittente);
inherited Destroy;
end;
{ TEFatturaHeader_Generico_Sede }
function TEFatturaHeader_Generico_Sede.GetIsAssigned: boolean;
begin
result := (FIndirizzo<>'')
or
(FCAP <> '')
or
(FComune<>'');
end;
constructor TEFatturaHeader_Generico_Sede.Create;
begin
FIndirizzo:='';
FNumeroCivico:='';
FCAP:='';
FComune:='';
FProvincia:='';
FNazione:='';
end;
{ TEFatturaHeader_Generico_Anagrafica }
function TEFatturaHeader_Generico_Anagrafica.GetIsAssigned: boolean;
begin
result := (FDenominazione<>'')
or
(FNome<>'')
or
(FTitolo<>'');
end;
constructor TEFatturaHeader_Generico_Anagrafica.Create;
begin
FDenominazione:='';
FNome:='';
FCognome:='';
FTitolo:='';
FCodEORI:='';
end;
{ TEFatturaHeader_Generico_Contatti }
function TEFatturaHeader_Generico_Contatti.GetAssigned: boolean;
begin
result := (Femail<>'') or (FFax<>'') or (FTelefono<>'')
end;
constructor TEFatturaHeader_Generico_Contatti.Create;
begin
Femail:='';
FFax:='';
FTelefono:='';
end;
{ TEFatturaHeader }
constructor TEFatturaHeader.Create;
begin
FDatiTrasmissione:=TEFatturaHeader_DatiTrasmissione.Create;
FCedentePrestatore:=TEFatturaHeader_CedentePrestatore.Create;
FCessionarioCommittente:=TEFatturaHeader_CessionarioCommittente.Create;
FTerzoIntermediarioOSoggettoEmittente:=TEFatturaHeader_TerzoIntermediarioOSoggettoEmittente.Create;
end;
destructor TEFatturaHeader.Destroy;
begin
FreeAndNil(FDatiTrasmissione);
FreeAndNil(FCedentePrestatore);
FreeAndNil(FCessionarioCommittente);
FreeAndNil(FTerzoIntermediarioOSoggettoEmittente);
inherited Destroy;
end;
{ TEFattura }
constructor TEFattura.Create;
begin
FFatturaElettronicaHeader:=TEFatturaHeader.Create;
FatturaElettronicaBody_Lista:=TEFatturaBody_Lista.Create(True);
end;
destructor TEFattura.Destroy;
begin
FatturaElettronicaBody_Lista.Clear;
FreeAndNil(FatturaElettronicaBody_Lista);
FreeAndNil(FFatturaElettronicaHeader);
inherited Destroy;
end;
end.
|
{ ********************************************************************* }
{ * Microsoft Windows ** }
{ * Copyright(c) Microsoft Corp., 1996-1998 ** }
{ * ** }
{ * Translator: Embarcadero Technologies, Inc. ** }
{ Copyright(c) 2012-2018 Embarcadero Technologies, Inc. }
{ * All rights reserved ** }
{ ********************************************************************* }
unit mshtmcid;
interface
uses Winapi.Windows;
{ +--------------------------------------------------------------------------- }
{ Microsoft Windows }
{ Copyright (C) Microsoft Corporation. All Rights Reserved. }
{ File: mshtmcid.h }
{ ---------------------------------------------------------------------------- }
{ MSHTML Command IDs }
{ ---------------------------------------------------------------------------- }
const
IDM_UNKNOWN = 0;
IDM_ALIGNBOTTOM = 1;
IDM_ALIGNHORIZONTALCENTERS = 2;
IDM_ALIGNLEFT = 3;
IDM_ALIGNRIGHT = 4;
IDM_ALIGNTOGRID = 5;
IDM_ALIGNTOP = 6;
IDM_ALIGNVERTICALCENTERS = 7;
IDM_ARRANGEBOTTOM = 8;
IDM_ARRANGERIGHT = 9;
IDM_BRINGFORWARD = 10;
IDM_BRINGTOFRONT = 11;
IDM_CENTERHORIZONTALLY = 12;
IDM_CENTERVERTICALLY = 13;
IDM_CODE = 14;
IDM_DELETE = 17;
IDM_FONTNAME = 18;
IDM_FONTSIZE = 19;
IDM_GROUP = 20;
IDM_HORIZSPACECONCATENATE = 21;
IDM_HORIZSPACEDECREASE = 22;
IDM_HORIZSPACEINCREASE = 23;
IDM_HORIZSPACEMAKEEQUAL = 24;
IDM_INSERTOBJECT = 25;
IDM_MULTILEVELREDO = 30;
IDM_SENDBACKWARD = 32;
IDM_SENDTOBACK = 33;
IDM_SHOWTABLE = 34;
IDM_SIZETOCONTROL = 35;
IDM_SIZETOCONTROLHEIGHT = 36;
IDM_SIZETOCONTROLWIDTH = 37;
IDM_SIZETOFIT = 38;
IDM_SIZETOGRID = 39;
IDM_SNAPTOGRID = 40;
IDM_TABORDER = 41;
IDM_TOOLBOX = 42;
IDM_MULTILEVELUNDO = 44;
IDM_UNGROUP = 45;
IDM_VERTSPACECONCATENATE = 46;
IDM_VERTSPACEDECREASE = 47;
IDM_VERTSPACEINCREASE = 48;
IDM_VERTSPACEMAKEEQUAL = 49;
IDM_JUSTIFYFULL = 50;
IDM_BACKCOLOR = 51;
IDM_BOLD = 52;
IDM_BORDERCOLOR = 53;
IDM_FLAT = 54;
IDM_FORECOLOR = 55;
IDM_ITALIC = 56;
IDM_JUSTIFYCENTER = 57;
IDM_JUSTIFYGENERAL = 58;
IDM_JUSTIFYLEFT = 59;
IDM_JUSTIFYRIGHT = 60;
IDM_RAISED = 61;
IDM_SUNKEN = 62;
IDM_UNDERLINE = 63;
IDM_CHISELED = 64;
IDM_ETCHED = 65;
IDM_SHADOWED = 66;
IDM_FIND = 67;
IDM_SHOWGRID = 69;
IDM_OBJECTVERBLIST0 = 72;
IDM_OBJECTVERBLIST1 = 73;
IDM_OBJECTVERBLIST2 = 74;
IDM_OBJECTVERBLIST3 = 75;
IDM_OBJECTVERBLIST4 = 76;
IDM_OBJECTVERBLIST5 = 77;
IDM_OBJECTVERBLIST6 = 78;
IDM_OBJECTVERBLIST7 = 79;
IDM_OBJECTVERBLIST8 = 80;
IDM_OBJECTVERBLIST9 = 81;
IDM_OBJECTVERBLISTLAST = IDM_OBJECTVERBLIST9;
IDM_CONVERTOBJECT = 82;
IDM_CUSTOMCONTROL = 83;
IDM_CUSTOMIZEITEM = 84;
IDM_RENAME = 85;
IDM_IMPORT = 86;
IDM_NEWPAGE = 87;
IDM_MOVE = 88;
IDM_CANCEL = 89;
IDM_FONT = 90;
IDM_STRIKETHROUGH = 91;
IDM_DELETEWORD = 92;
IDM_EXECPRINT = 93;
IDM_JUSTIFYNONE = 94;
IDM_TRISTATEBOLD = 95;
IDM_TRISTATEITALIC = 96;
IDM_TRISTATEUNDERLINE = 97;
IDM_FOLLOW_ANCHOR = 2008;
IDM_INSINPUTIMAGE = 2114;
IDM_INSINPUTBUTTON = 2115;
IDM_INSINPUTRESET = 2116;
IDM_INSINPUTSUBMIT = 2117;
IDM_INSINPUTUPLOAD = 2118;
IDM_INSFIELDSET = 2119;
IDM_PASTEINSERT = 2120;
IDM_REPLACE = 2121;
IDM_EDITSOURCE = 2122;
IDM_BOOKMARK = 2123;
IDM_HYPERLINK = 2124;
IDM_UNLINK = 2125;
IDM_BROWSEMODE = 2126;
IDM_EDITMODE = 2127;
IDM_UNBOOKMARK = 2128;
IDM_TOOLBARS = 2130;
IDM_STATUSBAR = 2131;
IDM_FORMATMARK = 2132;
IDM_TEXTONLY = 2133;
IDM_OPTIONS = 2135;
IDM_FOLLOWLINKC = 2136;
IDM_FOLLOWLINKN = 2137;
IDM_VIEWSOURCE = 2139;
IDM_ZOOMPOPUP = 2140;
{ IDM_BASELINEFONT1, IDM_BASELINEFONT2, IDM_BASELINEFONT3, IDM_BASELINEFONT4, }
{ and IDM_BASELINEFONT5 should be consecutive integers; }
IDM_BASELINEFONT1 = 2141;
IDM_BASELINEFONT2 = 2142;
IDM_BASELINEFONT3 = 2143;
IDM_BASELINEFONT4 = 2144;
IDM_BASELINEFONT5 = 2145;
IDM_HORIZONTALLINE = 2150;
IDM_LINEBREAKNORMAL = 2151;
IDM_LINEBREAKLEFT = 2152;
IDM_LINEBREAKRIGHT = 2153;
IDM_LINEBREAKBOTH = 2154;
IDM_NONBREAK = 2155;
IDM_SPECIALCHAR = 2156;
IDM_HTMLSOURCE = 2157;
IDM_IFRAME = 2158;
IDM_HTMLCONTAIN = 2159;
IDM_TEXTBOX = 2161;
IDM_TEXTAREA = 2162;
IDM_CHECKBOX = 2163;
IDM_RADIOBUTTON = 2164;
IDM_DROPDOWNBOX = 2165;
IDM_LISTBOX = 2166;
IDM_BUTTON = 2167;
IDM_IMAGE = 2168;
IDM_OBJECT = 2169;
IDM_1D = 2170;
IDM_IMAGEMAP = 2171;
IDM_FILE = 2172;
IDM_COMMENT = 2173;
IDM_SCRIPT = 2174;
IDM_JAVAAPPLET = 2175;
IDM_PLUGIN = 2176;
IDM_PAGEBREAK = 2177;
IDM_HTMLAREA = 2178;
IDM_PARAGRAPH = 2180;
IDM_FORM = 2181;
IDM_MARQUEE = 2182;
IDM_LIST = 2183;
IDM_ORDERLIST = 2184;
IDM_UNORDERLIST = 2185;
IDM_INDENT = 2186;
IDM_OUTDENT = 2187;
IDM_PREFORMATTED = 2188;
IDM_ADDRESS = 2189;
IDM_BLINK = 2190;
IDM_DIV = 2191;
IDM_TABLEINSERT = 2200;
IDM_RCINSERT = 2201;
IDM_CELLINSERT = 2202;
IDM_CAPTIONINSERT = 2203;
IDM_CELLMERGE = 2204;
IDM_CELLSPLIT = 2205;
IDM_CELLSELECT = 2206;
IDM_ROWSELECT = 2207;
IDM_COLUMNSELECT = 2208;
IDM_TABLESELECT = 2209;
IDM_TABLEPROPERTIES = 2210;
IDM_CELLPROPERTIES = 2211;
IDM_ROWINSERT = 2212;
IDM_COLUMNINSERT = 2213;
IDM_HELP_CONTENT = 2220;
IDM_HELP_ABOUT = 2221;
IDM_HELP_README = 2222;
IDM_REMOVEFORMAT = 2230;
IDM_PAGEINFO = 2231;
IDM_TELETYPE = 2232;
IDM_GETBLOCKFMTS = 2233;
IDM_BLOCKFMT = 2234;
IDM_SHOWHIDE_CODE = 2235;
IDM_TABLE = 2236;
IDM_COPYFORMAT = 2237;
IDM_PASTEFORMAT = 2238;
IDM_GOTO = 2239;
IDM_CHANGEFONT = 2240;
IDM_CHANGEFONTSIZE = 2241;
IDM_CHANGECASE = 2246;
IDM_SHOWSPECIALCHAR = 2249;
IDM_SUBSCRIPT = 2247;
IDM_SUPERSCRIPT = 2248;
IDM_CENTERALIGNPARA = 2250;
IDM_LEFTALIGNPARA = 2251;
IDM_RIGHTALIGNPARA = 2252;
IDM_REMOVEPARAFORMAT = 2253;
IDM_APPLYNORMAL = 2254;
IDM_APPLYHEADING1 = 2255;
IDM_APPLYHEADING2 = 2256;
IDM_APPLYHEADING3 = 2257;
IDM_DOCPROPERTIES = 2260;
IDM_ADDFAVORITES = 2261;
IDM_COPYSHORTCUT = 2262;
IDM_SAVEBACKGROUND = 2263;
IDM_SETWALLPAPER = 2264;
IDM_COPYBACKGROUND = 2265;
IDM_CREATESHORTCUT = 2266;
IDM_PAGE = 2267;
IDM_SAVETARGET = 2268;
IDM_SHOWPICTURE = 2269;
IDM_SAVEPICTURE = 2270;
IDM_DYNSRCPLAY = 2271;
IDM_DYNSRCSTOP = 2272;
IDM_PRINTTARGET = 2273;
IDM_IMGARTPLAY = 2274; { no longer in use }
IDM_IMGARTSTOP = 2275; { no longer in use }
IDM_IMGARTREWIND = 2276; { no longer in use }
IDM_PRINTQUERYJOBSPENDING = 2277;
IDM_SETDESKTOPITEM = 2278;
IDM_CONTEXTMENU = 2280;
IDM_GOBACKWARD = 2282;
IDM_GOFORWARD = 2283;
IDM_PRESTOP = 2284;
{ ;begin_internal }
IDM_GOTOCLIPBOARDADDRESS = 2285;
IDM_GOTOCLIPBOARDTEXT = 2286;
{ ;end_internal }
IDM_MP_MYPICS = 2287;
IDM_MP_EMAILPICTURE = 2288;
IDM_MP_PRINTPICTURE = 2289;
IDM_CREATELINK = 2290;
IDM_COPYCONTENT = 2291;
IDM_LANGUAGE = 2292;
IDM_GETPRINTTEMPLATE = 2295;
IDM_SETPRINTTEMPLATE = 2296;
IDM_TEMPLATE_PAGESETUP = 2298;
IDM_REFRESH = 2300;
IDM_STOPDOWNLOAD = 2301;
IDM_ENABLE_INTERACTION = 2302;
IDM_LAUNCHDEBUGGER = 2310;
IDM_BREAKATNEXT = 2311;
IDM_INSINPUTHIDDEN = 2312;
IDM_INSINPUTPASSWORD = 2313;
IDM_OVERWRITE = 2314;
IDM_PARSECOMPLETE = 2315;
IDM_HTMLEDITMODE = 2316;
IDM_REGISTRYREFRESH = 2317;
IDM_COMPOSESETTINGS = 2318;
IDM_SHOWALLTAGS = 2327;
IDM_SHOWALIGNEDSITETAGS = 2321;
IDM_SHOWSCRIPTTAGS = 2322;
IDM_SHOWSTYLETAGS = 2323;
IDM_SHOWCOMMENTTAGS = 2324;
IDM_SHOWAREATAGS = 2325;
IDM_SHOWUNKNOWNTAGS = 2326;
IDM_SHOWMISCTAGS = 2320;
IDM_SHOWZEROBORDERATDESIGNTIME = 2328;
IDM_AUTODETECT = 2329;
IDM_SCRIPTDEBUGGER = 2330;
IDM_GETBYTESDOWNLOADED = 2331;
IDM_NOACTIVATENORMALOLECONTROLS = 2332;
IDM_NOACTIVATEDESIGNTIMECONTROLS = 2333;
IDM_NOACTIVATEJAVAAPPLETS = 2334;
IDM_NOFIXUPURLSONPASTE = 2335;
IDM_EMPTYGLYPHTABLE = 2336;
IDM_ADDTOGLYPHTABLE = 2337;
IDM_REMOVEFROMGLYPHTABLE = 2338;
IDM_REPLACEGLYPHCONTENTS = 2339;
IDM_SHOWWBRTAGS = 2340;
IDM_PERSISTSTREAMSYNC = 2341;
IDM_SETDIRTY = 2342;
IDM_RUNURLSCRIPT = 2343;
{$ifdef IE5_ZOOM}
IDM_ZOOMRATIO = 2344;
IDM_GETZOOMNUMERATOR = 2345;
IDM_GETZOOMDENOMINATOR = 2346;
{$endif // IE5_ZOOM}
{ COMMANDS FOR COMPLEX TEXT }
IDM_DIRLTR = 2350;
IDM_DIRRTL = 2351;
IDM_BLOCKDIRLTR = 2352;
IDM_BLOCKDIRRTL = 2353;
IDM_INLINEDIRLTR = 2354;
IDM_INLINEDIRRTL = 2355;
{ SHDOCVW }
IDM_ISTRUSTEDDLG = 2356;
{ MSHTMLED }
IDM_INSERTSPAN = 2357;
IDM_LOCALIZEEDITOR = 2358;
{ XML MIMEVIEWER }
IDM_SAVEPRETRANSFORMSOURCE = 2370;
IDM_VIEWPRETRANSFORMSOURCE = 2371;
{ Scrollbar context menu }
IDM_SCROLL_HERE = 2380;
IDM_SCROLL_TOP = 2381;
IDM_SCROLL_BOTTOM = 2382;
IDM_SCROLL_PAGEUP = 2383;
IDM_SCROLL_PAGEDOWN = 2384;
IDM_SCROLL_UP = 2385;
IDM_SCROLL_DOWN = 2386;
IDM_SCROLL_LEFTEDGE = 2387;
IDM_SCROLL_RIGHTEDGE = 2388;
IDM_SCROLL_PAGELEFT = 2389;
IDM_SCROLL_PAGERIGHT = 2390;
IDM_SCROLL_LEFT = 2391;
IDM_SCROLL_RIGHT = 2392;
{ IE 6 Form Editing Commands }
IDM_MULTIPLESELECTION = 2393;
IDM_2D_POSITION = 2394;
IDM_2D_ELEMENT = 2395;
IDM_1D_ELEMENT = 2396;
IDM_ABSOLUTE_POSITION = 2397;
IDM_LIVERESIZE = 2398;
IDM_ATOMICSELECTION = 2399;
{ Auto URL detection mode }
IDM_AUTOURLDETECT_MODE = 2400;
{ Legacy IE50 compatible paste }
IDM_IE50_PASTE = 2401;
{ ie50 paste mode }
IDM_IE50_PASTE_MODE = 2402;
{ ;begin_internal }
IDM_GETIPRINT = 2403;
{ ;end_internal }
{ for disabling selection handles }
IDM_DISABLE_EDITFOCUS_UI = 2404;
{ for visibility/display in design }
IDM_RESPECTVISIBILITY_INDESIGN = 2405;
{ set css mode }
IDM_CSSEDITING_LEVEL = 2406;
{ New outdent }
IDM_UI_OUTDENT = 2407;
{ Printing Status }
IDM_UPDATEPAGESTATUS = 2408;
{ IME Reconversion }
IDM_IME_ENABLE_RECONVERSION = 2409;
IDM_KEEPSELECTION = 2410;
IDM_UNLOADDOCUMENT = 2411;
IDM_OVERRIDE_CURSOR = 2420;
IDM_PEERHITTESTSAMEINEDIT = 2423;
IDM_TRUSTAPPCACHE = 2425;
IDM_BACKGROUNDIMAGECACHE = 2430;
IDM_GETUSERACTIONTIME = 2431;
IDM_BEGINUSERACTION = 2432;
IDM_ENDUSERACTION = 2433;
IDM_SETCUSTOMCURSOR = 2434;
{ Open Link in New Tab }
IDM_FOLLOWLINKT = 2435;
{ Caret Browsing Mode }
IDM_CARETBROWSINGMODE = 2436;
{ Style menu }
IDM_STYLEMENU_SETNOSTYLE = 2437;
IDM_STYLEMENU_GETNOSTYLE = 2438;
IDM_STYLEMENU_GETPREFSTYLE = 2439;
IDM_STYLEMENU_CHANGESELECTEDSTYLE = 2440;
{ Media element commands (context menu/keyboard accelerators) }
IDM_MEDIA_PLAYPAUSE = 2441;
IDM_MEDIA_MUTEUNMUTE = 2442;
IDM_MEDIA_PLAY = 2443;
IDM_MEDIA_PAUSE = 2444;
IDM_MEDIA_STOP = 2445;
IDM_MEDIA_FULLSCREEN_TOGGLE = 2446;
IDM_MEDIA_FULLSCREEN_EXIT = 2447;
IDM_MEDIA_VOLUME_UP = 2448;
IDM_MEDIA_VOLUME_DOWN = 2449;
IDM_MEDIA_SEEK_TO_START = 2450;
IDM_MEDIA_SEEK_TO_END = 2451;
IDM_MEDIA_SEEK_FWD_SMALL = 2452;
IDM_MEDIA_SEEK_BACK_SMALL = 2453;
IDM_MEDIA_SEEK_FWD_LARGE = 2454;
IDM_MEDIA_SEEK_BACK_LARGE = 2455;
IDM_MEDIA_RATE_FASTER = 2456;
IDM_MEDIA_RATE_SLOWER = 2457;
IDM_MEDIA_SHOWCONTROLS_TOGGLE = 2458;
IDM_MEDIA_ZOOMMODE_TOGGLE = 2459;
IDM_MEDIA_FRAMESTEP_FWD = 2460;
IDM_MEDIA_FRAMESTEP_BACK = 2461;
IDM_MEDIA_MUTE = 2462;
IDM_MEDIA_UNMUTE = 2463;
IDM_MEDIA_SHOW_AUDIO_ACCESS = 2464;
IDM_MEDIA_SHOW_SUBTITLE_ACCESS = 2465;
{ These should be enough to reserve a block covering all playrates }
{ displayed on the context menu (must be consecutive integers) }
IDM_MEDIA_PLAYRATE0 = 2480;
IDM_MEDIA_PLAYRATE1 = 2481;
IDM_MEDIA_PLAYRATE2 = 2482;
IDM_MEDIA_PLAYRATE3 = 2483;
IDM_MEDIA_PLAYRATE4 = 2484;
IDM_MEDIA_PLAYRATE5 = 2485;
IDM_MEDIA_PLAYRATE6 = 2486;
IDM_MEDIA_PLAYRATE7 = 2487;
IDM_MEDIA_PLAYRATE8 = 2488;
IDM_MEDIA_PLAYRATE9 = 2489;
IDM_PASTECONTENTONLY = 2500;
IDM_PASTETEXTONLY = 2501;
IDM_DEFAULTBLOCK = 6046;
IDM_MIMECSET__FIRST__ = 3609;
IDM_MIMECSET__LAST__ = 3699;
IDM_MENUEXT_FIRST__ = 3700;
IDM_MENUEXT_LAST__ = 3732;
IDM_MENUEXT_COUNT = 3733;
{ New for IE10 }
IDM_ADDCONSOLEMESSAGERECEIVER = 3800;
IDM_REMOVECONSOLEMESSAGERECEIVER = 3801;
IDM_STARTDIAGNOSTICSMODE = 3802;
IDM_GETSCRIPTENGINE = 3803;
IDM_ADDDEBUGCALLBACKRECEIVER = 3804; { pvaIn: IDebugCallbackNotificationHandler*, pvaOut: cookie for unregister }
IDM_REMOVEDEBUGCALLBACKRECEIVER = 3805; { pvaIn: cookie from register, pvaOut: NULL }
{ New for IE11 }
IDM_DEFAULTPARAGRAPHSEPARATOR = 3900;
IDM_BEGINUNDOUNIT = 3901;
IDM_ENDUNDOUNIT = 3902;
IDM_CLEARUNDO = 3903;
IDM_INSPECTELEMENT = 3904;
{ Commands mapped from the standard set. We should }
{ consider deleting them from public header files. }
IDM_OPEN = 2000;
IDM_NEW = 2001;
IDM_SAVE = 70;
IDM_SAVEAS = 71;
IDM_SAVECOPYAS = 2002;
IDM_PRINTPREVIEW = 2003;
IDM_SHOWPRINT = 2010;
IDM_SHOWPAGESETUP = 2011;
IDM_PRINT = 27;
IDM_PAGESETUP = 2004;
IDM_SPELL = 2005;
IDM_PASTESPECIAL = 2006;
IDM_CLEARSELECTION = 2007;
IDM_PROPERTIES = 28;
IDM_REDO = 29;
IDM_UNDO = 43;
IDM_SELECTALL = 31;
IDM_ZOOMPERCENT = 50;
IDM_GETZOOM = 68;
IDM_STOP = 2138;
IDM_COPY = 15;
IDM_CUT = 16;
IDM_PASTE = 26;
{ Defines for IDM_ZOOMPERCENT }
CMD_ZOOM_PAGEWIDTH = -1;
CMD_ZOOM_ONEPAGE = -2;
CMD_ZOOM_TWOPAGES = -3;
CMD_ZOOM_SELECTION = -4;
CMD_ZOOM_FIT = -5;
{ IDMs for CGID_EditStateCommands group }
IDM_CONTEXT = 1;
IDM_HWND = 2;
{ Shdocvw Execs on CGID_DocHostCommandHandler }
IDM_NEW_TOPLEVELWINDOW = 7050;
{ Undo persistence comands }
IDM_PRESERVEUNDOALWAYS = 6049;
IDM_PERSISTDEFAULTVALUES = 7100;
IDM_PROTECTMETATAGS = 7101;
IDM_GETFRAMEZONE = 6037;
IDM_REFRESH_THIS = 6042;
{ placeholder for context menu extensions }
IDM_MENUEXT_PLACEHOLDER = 6047;
{ ;begin_internal }
{ <New in IE6> }
IDM_FIRE_PRINTTEMPLATEUP = 15000;
IDM_FIRE_PRINTTEMPLATEDOWN = 15001;
IDM_SETPRINTHANDLES = 15002;
IDM_CLEARAUTHENTICATIONCACHE = 15003;
IDM_GETUSERINITFLAGS = 15004;
IDM_GETDOCDLGFLAGS = 15005;
{ <New in IE7> }
IDM_OLEWINDOWSTATECHANGED = 15006;
{ <New in IE8> }
IDM_ACTIVEXINSTALLSCOPE = 15007;
IDM_SETSESSIONDOCUMENTMODE = 15008;
IDM_GETSESSIONDOCUMENTMODE = 15009;
IDM_SETPROFILINGONSTART = 15010;
IDM_GETPROFILINGONSTART = 15011;
IDM_SETSCRIPTCONSOLE = 15012; { no longer in use, use IDM_SETDEVTOOLBARCONSOLE }
IDM_SETNAVIGATEEVENTSINK = 15013;
{ <New in IE9> }
{ UNUSED : 15014 }
{ UNUSED : 15015 }
IDM_SETDEVTOOLBARCONSOLE = 15016; { no longer in use, use IDM_ADDCONSOLEMESSAGERECEIVER & IDM_REMOVECONSOLEMESSAGERECEIVER }
{ <New in IE10> }
IDM_POPSTATEEVENT = 15017;
{ UNUSED : 15018 }
{ UNUSED : 15019 }
{ UNUSED : 15020 }
IDM_SETPARTIALLAYOUTSTATUS = 15021;
IDM_GETPARTIALLAYOUTSTATUS = 15022;
IDM_ADDPARTIALTESTSTEPCOUNT = 15023;
IDM_SETL9QUIRKSEMULATIONENABLED = 15024;
IDM_GETL9QUIRKSEMULATIONENABLED = 15025;
{ UNUSED : 15026 }
IDM_GETDEFAULTZOOMLEVEL = 15027;
IDM_GETELEMENTBOUNDINGBOX = 15028;
IDM_SETGEOLOCATIONCONSENT = 15029;
IDM_ACTIVEXFILTERINGENABLED = 15030;
{ <New in WIN8> }
IDM_SHARE = 15031;
IDM_SETAPPCACHESIZECONSENT = 15032;
IDM_SHAREAPPCACHEEVENT = 15033;
IDM_SETINDEXDBSIZECONSENT = 15034;
{ Diagnostics mode commands }
{ UNUSED: 15035 }
{ UNUSED: 15036 }
{ 15037 unused. Repurpose as needed. }
{ PrintManager Printing Support }
IDM_GETPRINTMANAGERDOCSOURCE = 15038;
IDM_SETEXTRAHEADERS = 15039;
IDM_SETACCESSIBILITYNAME = 15040;
{ Dynamic setting registry update }
IDM_UPDATESETTINGSFROMREGISTRY = 15041;
{ PhoneLegacyHost only: perform edit activation }
IDM_PERFORMEDITACTIVATION = 15042;
{ Get/set default background color }
IDM_SETDEFAULTBACKGROUNDCOLOR = 15043;
IDM_GETDEFAULTBACKGROUNDCOLOR = 15044;
{ PhoneLegacyHost only: notify the end of a zoom and scroll animation }
IDM_NOTIFYZOOMANDSCROLLANIMATIONEND = 15045;
{ PhoneLegacyHost only: notify the context menu on phone has been dismissed }
IDM_NOTIFYCONTEXTMENUDISMISSED = 15046;
{ ;end_internal }
{ Security band commands }
IDM_SETPAGEACTIONALLOWEDFLAGS = 15100;
{ Flip Ahead commands }
IDM_INVOKEFLIPAHEADTARGET = 15200;
IDM_ENABLEFLIPAHEADTARGET = 15201;
{ <New in IE11> }
{ Debug w/o Refresh commands }
IDM_DEBUGGERDYNAMICATTACH = 15202;
IDM_DEBUGGERDYNAMICDETACH = 15203;
IDM_DEBUGGERDYNAMICATTACHSOURCERUNDOWN = 15204;
IDM_GETDEBUGGERSTATE = 15205;
IDM_SELECTIONSEARCH = 15206;
IDM_SHOWSHAREUI = 15207;
implementation
end.
|
unit Test.Devices.Tecon19.Parser;
interface
uses TestFrameWork, Devices.Tecon, Devices.Tecon.Common, GMGlobals, GMConst, Classes, Test.Devices.Base.ReqParser, Math;
type
TTeconReqParserTest = class(TDeviceReqParserTestBase)
private
reqParser: TTecon19AnswerParser;
protected
procedure SetUp; override;
procedure TearDown; override;
function GetDevType(): int; override;
function GetThreadClass(): TSQLWriteThreadForTestClass; override;
published
procedure Currents;
procedure Arch;
procedure K105Autorization();
end;
implementation
type TLocalSQLWriteThreadForTest = class(TResponceParserThreadForTest);
{ TLogicaReqParserTest }
procedure TTeconReqParserTest.Arch;
var buf: ArrayOfByte;
r: TRequestDetails;
i: int;
begin
buf := TextNumbersStringToArray('68 42 42 68 0F 01 FF FF FF FF FF FF FF FF FF FF FF FF 00 00 A0 40 00 00 A0 40 00 00 A0 40 00 00 A0 40 FF FF FF FF 00 00 A0 40 00 00 A0 40 00 00 A0 40 00 00 A0 40 00 00 A0 40 00 00 A0 40 00 00 A0 40 00 00 A0 40 80 16');
r.N_Car := 1;
r.ReqID := $0F;
r.UTimeArch := EncodeDateTimeUTC(2015, 01, 10, 14, 00);
r.rqtp := rqtTECON_HourArch;
Check(reqParser.Parse(buf, Length(buf), r));
Check(reqParser.Vals.Count = 12);
for i := 0 to reqParser.Vals.Count - 1 do
begin
Check(reqParser.Vals[i].Val = 5);
Check(reqParser.Vals[i].UTime = int64(r.UTimeArch) + (3 + IfThen(i >= 4, 1, 0) + i) * UTC_HOUR);
Check(reqParser.Vals[i].ValType = valueTypeHourArch);
Check(reqParser.Vals[i].Chn = nil);
end;
end;
procedure TTeconReqParserTest.Currents;
var buf: ArrayOfByte;
r: TRequestDetails;
begin
buf := TextNumbersStringToArray('68 06 06 68 08 01 00 00 C0 3F 08 16');
r.N_Car := 1;
r.ReqID := $08;
r.rqtp := rqtUSER_DEFINED;
Check(reqParser.Parse(buf, Length(buf), r));
Check(reqParser.Vals.Count = 1);
Check(reqParser.Vals[0].Val = 1.5);
Check(Abs(NowGM() - reqParser.Vals[0].UTime) < 5);
Check(reqParser.Vals[0].ValType = valueTypeCurrent);
Check(reqParser.Vals[0].Chn = nil);
end;
function TTeconReqParserTest.GetDevType: int;
begin
Result := DEVTYPE_TECON_19_01;
end;
function TTeconReqParserTest.GetThreadClass: TSQLWriteThreadForTestClass;
begin
Result := TLocalSQLWriteThreadForTest;
end;
procedure TTeconReqParserTest.K105Autorization;
var buf: ArrayOfByte;
begin
buf := TextNumbersStringToArray('68 08 08 68 41 25 1B 09 C1 06 79 24 EE 16');
Check(Tecon_CheckK105Authorization(buf, Length(buf)));
end;
procedure TTeconReqParserTest.SetUp;
begin
inherited;
reqParser := TTecon19AnswerParser.Create();
end;
procedure TTeconReqParserTest.TearDown;
begin
reqParser.Free();
inherited;
end;
initialization
RegisterTest('GMIOPSrv/Devices/Tecon', TTeconReqParserTest.Suite);
end.
|
unit Financas.Controller.Connections.Factory.DataSet;
interface
uses Financas.Controller.Connections.Interfaces, Financas.Model.Connections.Interfaces,
Financas.Model.Connections.Factory.DataSet;
Type
TControllerConnectionsFactoryDataSet = class(TInterfacedObject, iControllerFactoryDataSet)
private
public
constructor Create;
destructor Destroy; override;
class function New : iControllerFactoryDataSet;
function DataSet(Connection : iModelConnection) : iModelDataSet;
end;
implementation
{ TControllerConnectionsFactoryDataSet }
constructor TControllerConnectionsFactoryDataSet.Create;
begin
end;
function TControllerConnectionsFactoryDataSet.DataSet(Connection : iModelConnection) : iModelDataSet;
begin
Result := TModelConnectionFactoryDataSet.New.DataSetFiredac(Connection);
end;
destructor TControllerConnectionsFactoryDataSet.Destroy;
begin
inherited;
end;
class function TControllerConnectionsFactoryDataSet.New: iControllerFactoryDataSet;
begin
Result := Self.Create;
end;
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2016-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit System.Net.FileClient;
interface
{$SCOPEDENUMS ON}
uses
System.Classes, System.Types, System.Net.URLClient, System.Sysutils;
type
/// <summary>Specific Class to handle File Requests</summary>
/// <remarks></remarks>
TFileRequest = class(TURLRequest, IURLRequest)
end;
/// <summary>Specific Class to handle File Responses</summary>
TFileResponse = class(TURLResponse, IURLResponse)
protected
constructor Create(const AContext: TObject; const AProc: TProc;
const AAsyncCallback: TAsyncCallback; const AAsyncCallbackEvent: TAsyncCallbackEvent;
const ARequest: IURLRequest; const AContentStream: TStream); overload;
/// <summary>Implementation method for specific stream creation</summary>
function DoCreateInternalStream: TStream; override;
function DoCancel: Boolean; override;
public
/// <summary>Getter for the Headers property</summary>
function GetHeaders: TNetHeaders; override;
/// <summary>Getter for the MimeType property</summary>
function GetMimeType: string; override;
/// <summary>Function that transforms the ContentStream into a string</summary>
/// <remarks> If AnEncoding is omitted UTF8 encoding will be assumed.</remarks>
function ContentAsString(const AnEncoding: TEncoding = nil): string; override;
end;
/// <summary> Class that implements a File Client.</summary>
TFileClient = class(TURLClient)
protected
/// <summary>Function that obtains a Response instance</summary>
function DoGetResponseInstance(const AContext: TObject; const AProc: TProc; const AsyncCallback: TAsyncCallback;
const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream)
: IAsyncResult; override;
/// <summary>Function that obtains a Request instance</summary>
function DoGetRequestInstance(const ARequestMethod: string; const AURI: TURI): IURLRequest; override;
/// <summary>Function that asynchronusly executes a Request and obtains a response</summary>
/// <remarks> This function creates a request before calling InternalExecuteAsync</remarks>
function DoExecuteAsync(const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent;
const ARequestMethod: string; const AURI: TURI; const ASourceStream, AContentStream: TStream;
const AHeaders: TNetHeaders; AOwnsSourceStream: Boolean): IAsyncResult; override;
public
/// <summary>Create a File Client instance</summary>
class function CreateInstance: TURLClient; override;
end;
implementation
uses System.NetEncoding;
{ TFileClient }
class function TFileClient.CreateInstance: TURLClient;
begin
Result := TFileClient.Create;
end;
function TFileClient.DoExecuteAsync(const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent;
const ARequestMethod: string; const AURI: TURI; const ASourceStream, AContentStream: TStream;
const AHeaders: TNetHeaders; AOwnsSourceStream: Boolean): IAsyncResult;
var
LRequest: IURLRequest;
begin
LRequest := GetRequest(ARequestMethod, AURI);
Result := DoGetResponseInstance(Self, nil, AsyncCallback, AsyncCallbackEvent, LRequest, AContentStream);
// Invoke Async Execution.
(Result as TFileResponse).Invoke;
end;
function TFileClient.DoGetRequestInstance(const ARequestMethod: string; const AURI: TURI): IURLRequest;
begin
Result := TFileRequest.Create(Self, ARequestMethod, AURI);
end;
function TFileClient.DoGetResponseInstance(const AContext: TObject; const AProc: TProc;
const AsyncCallback: TAsyncCallback; const AsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest;
const AContentStream: TStream): IAsyncResult;
begin
Result := TFileResponse.Create(AContext, AProc, AsyncCallback, AsyncCallbackEvent, ARequest, AContentStream);
end;
{ TFileResponse }
constructor TFileResponse.Create(const AContext: TObject; const AProc: TProc; const AAsyncCallback: TAsyncCallback;
const AAsyncCallbackEvent: TAsyncCallbackEvent; const ARequest: IURLRequest; const AContentStream: TStream);
begin
inherited Create(AContext, AProc, AAsyncCallback, AAsyncCallbackEvent, ARequest, AContentStream);
end;
function TFileResponse.ContentAsString(const AnEncoding: TEncoding): string;
var
LReader: TStringStream;
begin
If AnEncoding = nil then
LReader := TStringStream.Create(string.Empty, TEncoding.UTF8, False)
else
LReader := TStringStream.Create(string.Empty, AnEncoding, False);
try
LReader.CopyFrom(GetContentStream, 0);
Result := LReader.DataString;
finally
LReader.Free;
end;
end;
function TFILEResponse.DoCancel: Boolean;
begin
Result := False; //TFile request can not be canceled.
end;
function TFileResponse.DoCreateInternalStream: TStream;
var
LPath: string;
begin
LPath := TNetEncoding.URL.URLDecode(FRequest.URL.Path);
if (Length(LPath) > 0) and (LPath.Chars[0] = '/') then
LPath := LPath.Substring(1);
{$IFDEF MSWINDOWS}
//In windows, file scheme can have ':' as a '|', so restore it to load from file.
//Info obtained from: https://en.wikipedia.org/wiki/File_URI_scheme
if (Length(LPath) > 1) and (LPath.Chars[1] = '|') then
LPath[Low(string) + 1] := ':';
{$ENDIF MSWINDOWS}
Result := TFileStream.Create(LPath, fmOpenRead or fmShareDenyWrite);
end;
function TFileResponse.GetHeaders: TNetHeaders;
begin
Result := nil;
end;
function TFileResponse.GetMimeType: string;
begin
Result := string.Empty;
end;
initialization
TURLSchemes.RegisterURLClientScheme(TFileClient, 'FILE');
finalization
TURLSchemes.UnRegisterURLClientScheme('FILE');
end.
|
unit HtmlDoc;
interface
type
IHTMLElemCollection = interface;
IHTMLElem = interface
['{348287FA-A001-49C7-966B-2B07A151D8DA}']
function TagName: string;
//function ClassName: string;
function InnerText: string;
function Children: IHTMLElemCollection;
end;
IHTMLElemCollection = interface
['{0344A65F-85BD-4F5B-BCD8-E0A19C852F02}']
function Count: Integer;
function Item(Index: Integer): IHTMLElem;
end;
IHTMLDoc = interface
['{4AB6D434-937D-4FD5-A646-E6B8B58D5C77}']
function DocumentElem: IHTMLElem;
function Body: IHTMLElem;
function GetElemById(const ID: string): IHTMLElem;
end;
function BuildHTMLDoc(const Content: string): IHTMLDoc;
implementation
uses
System.Variants, System.VarUtils,
Winapi.ActiveX,
MSHTML;
type
THTMLElem = class(TInterfacedObject, IHTMLElem)
private
HTMLElem: IHTMLElement;
FChildren: IHTMLElemCollection;
public
constructor Create(AHTMLElem: IHTMLElement);
function TagName: string;
function InnerText: string; inline;
function Children: IHTMLElemCollection; inline;
end;
THTMLElemCollection = class(TInterfacedObject, IHTMLElemCollection)
private
Children: IHTMLElementCollection; // CtorDI
public
constructor Create(AChildren: IHTMLElementCollection);
function Count: Integer; inline;
function Item(Index: Integer): IHTMLElem; inline;
end;
THtmlDoc = class(TInterfacedObject, IHTMLDoc)
private
Doc2: IHTMLDocument2;
Doc3: IHTMLDocument3;
procedure SetHtmlDoc(const HtmlDoc: string);
public
constructor Create(const Content: string);
function DocumentElem: IHTMLElem;
function Body: IHTMLElem;
function GetElemById(const ID: string): IHTMLElem; inline;
end;
{ THTMLElem }
constructor THTMLElem.Create(AHTMLElem: IHTMLElement);
begin
inherited Create;
FChildren := nil;
HTMLElem := AHTMLElem;
end;
function THTMLElem.TagName: string;
begin
Result := HTMLElem.tagName;
end;
function THTMLElem.InnerText: string;
begin
Result := HTMLElem.InnerText;
end;
function THTMLElem.Children: IHTMLElemCollection;
begin
if not Assigned(FChildren) then
FChildren := THTMLElemCollection.Create(HTMLElem.children as IHTMLElementCollection);
Result := FChildren;
end;
{ THTMLElemCollection }
constructor THTMLElemCollection.Create(AChildren: IHTMLElementCollection);
begin
inherited Create;
Children := AChildren;
end;
function THTMLElemCollection.Count: Integer;
begin
Result := Children.length;
end;
function THTMLElemCollection.Item(Index: Integer): IHTMLElem;
begin
Result := THTMLElem.Create(Children.item(Index, 0) as IHTMLElement);
end;
{ THTMLDoc }
constructor THtmlDoc.Create(const Content: string);
begin
inherited Create;
Doc2 := coHTMLDocument.Create as IHTMLDocument2;
SetHTMLDoc(Content);
Doc3 := Doc2 as IHTMLDocument3;
end;
procedure THtmlDoc.SetHtmlDoc(const HtmlDoc: string);
var
V: OleVariant;
begin
V := VarArrayCreate([0,0], varVariant);
V[0] := HtmlDoc;
Doc2.Write(PSafeArray(TVarData(v).VArray));
end;
function THtmlDoc.DocumentElem: IHTMLElem;
begin
Result := THTMLElem.Create(Doc3.documentElement);
end;
function THtmlDoc.Body: IHTMLElem;
begin
Result := THTMLElem.Create(Doc2.body);
end;
function THtmlDoc.getElemById(const ID: string): IHTMLElem;
begin
Result := THTMLElem.Create(Doc3.getElementById(ID));
end;
function BuildHTMLDoc(const Content: string): IHTMLDoc;
begin
Result := THTMLDoc.Create(Content);
end;
end.
|
{
GMEditors
ES: unit con la definición de los editores para los componentes
EN: unit with the definition of the editors for components
=========================================================================
History:
ver 0.1:
ES: primera versión
EN: first version
=========================================================================
IMPORTANTE PROGRAMADORES: Por favor, si tienes comentarios, mejoras,
ampliaciones, errores y/o cualquier otro tipo de sugerencia, envíame un correo a:
gmlib@cadetill.com
IMPORTANT PROGRAMMERS: please, if you have comments, improvements, enlargements,
errors and/or any another type of suggestion, please send me a mail to:
gmlib@cadetill.com
=========================================================================
Copyright (©) 2011, by Xavier Martinez (cadetill)
@author Xavier Martinez (cadetill)
@web http://www.cadetill.com
}
unit GMEditors;
interface
uses
DesignIntf, DesignEditors;
type
// http://delphi.about.com/library/bluc/text/uc092501c.htm
TAboutGMLib = class(TPropertyEditor)
public
procedure Edit; override;
function GetValue: string; override;
function GetAttributes: TPropertyAttributes; override;
end;
// http://delphi.about.com/library/bluc/text/uc092501b.htm
TGMBaseEditor = class(TComponentEditor)
public
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure ExecuteVerb(Index: Integer); override;
end;
TGMLinkedComponentEditor = class(TGMBaseEditor)
public
procedure Edit; override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
procedure ExecuteVerb(Index: Integer); override;
end;
implementation
uses
UAboutFrm, GMConstants, ColnEdit, GMLinkedComponents;
{ TAboutGMLib }
procedure TAboutGMLib.Edit;
begin
inherited;
with TAboutFrm.Create(nil) do
try
ShowModal;
finally
Free;
end;
end;
function TAboutGMLib.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
function TAboutGMLib.GetValue: string;
begin
Result := GMLIB_Version;
end;
{ TGMBaseEditor }
procedure TGMBaseEditor.ExecuteVerb(Index: Integer);
begin
inherited;
with TAboutFrm.Create(nil) do
try
ShowModal;
finally
Free;
end;
end;
function TGMBaseEditor.GetVerb(Index: Integer): string;
begin
Result := AboutGMLibTxt;
end;
function TGMBaseEditor.GetVerbCount: Integer;
begin
Result := 1;
end;
{ TGMLinkedComponentEditor }
procedure TGMLinkedComponentEditor.Edit;
begin
ShowCollectionEditor(Designer, Component, TGMLinkedComponent(Component).VisualObjects, 'VisualObjects');
end;
procedure TGMLinkedComponentEditor.ExecuteVerb(Index: Integer);
begin
if Index <= inherited GetVerbCount - 1 then
inherited ExecuteVerb(Index)
else
begin
Dec(Index, inherited GetVerbCount);
case Index of
0: ShowCollectionEditor(Designer, Component, TGMLinkedComponent(Component).VisualObjects, 'VisualObjects');
end;
end;
end;
function TGMLinkedComponentEditor.GetVerb(Index: Integer): string;
begin
if Index <= inherited GetVerbCount - 1 then
Result := inherited GetVerb(Index)
else
begin
Dec(Index, inherited GetVerbCount);
case Index of
0: Result := MEditor;
end;
end;
end;
function TGMLinkedComponentEditor.GetVerbCount: Integer;
begin
Result := inherited GetVerbCount + 1;
end;
end.
|
unit UShapesList;
{$mode objfpc}{$H+}
interface
uses
Graphics, UBaseShape, UShapes, math, UGeometry, UViewPort, UInspector, Classes,
sysutils, Dialogs, UShapeJSONConverter, UHistory, Clipbrd;
type
{ TShapesList }
TZOrderEvent = procedure(Enabled: Boolean) of object;
TShapesList = class
private
FOnZOrderSwitch: TZOrderEvent;
FShapes: array of TShape;
FSelectionRectangle: TRectangle;
function GetImageSize: TFloatRect;
procedure DeleteAll;
public
property SelectionRectangle: TRectangle read FSelectionRectangle
write FSelectionRectangle;
property ImageSize: TFloatRect read GetImageSize;
property OnZOrderSwitch: TZOrderEvent read FOnZOrderSwitch
write FOnZOrderSwitch;
procedure Draw(ACanvas: TCanvas);
procedure Add(AShape: TShape);
procedure Select;
procedure Select(APoint: TPoint);
procedure SwitchSelect;
procedure SwitchSelect(APoint: TPoint);
constructor Create;
function PointOnEditPoint(APoint: TPoint; var AShape: TShape;
var AIndex: Integer): Boolean;
procedure Delete;
procedure LoadSelected;
procedure UnSelect;
procedure ZUp;
procedure ZDown;
procedure ZTop;
procedure ZBottom;
function PointOnFigure(APoint: TPoint): Boolean;
procedure ShiftSelected(AShift: TPoint);
function IsEmpty: Boolean;
procedure Save(AFile: String);
function Load(AFile: String): Boolean;
procedure New;
procedure ExportToBMP(AFile: String; AWidth, AHeight: Integer);
procedure ExportToPNG(AFile: String; AWidth, AHeight: Integer);
procedure ExportToJPG(AFile: String; AWidth, AHeight: Integer);
procedure ShowAll;
procedure UpdateHistory;
procedure Copy;
procedure Paste;
procedure LoadState(AString: String);
procedure Clear;
end;
var
Figures: TShapesList;
implementation
{ TShapesList }
function TShapesList.GetImageSize: TFloatRect;
var i: integer;
begin
if Length(FShapes) > 0 then
begin
Result := FShapes[0].Rect;
for i := 1 to High(FShapes) do
begin
Result.Left := Min(Result.Left, FShapes[i].Rect.Left);
Result.Right := Max(Result.Right, FShapes[i].Rect.Right);
Result.Top := Min(Result.Top, FShapes[i].Rect.Top);
Result.Bottom := Max(Result.Bottom, FShapes[i].Rect.Bottom);
end;
end
else
Result := FloatRect(FloatPoint(0, 0), FloatPoint(0, 0));
end;
procedure TShapesList.DeleteAll;
var i: Integer;
begin
UnSelect;
for i := 0 to High(FShapes) do
FreeAndNil(FShapes[i]);
SetLength(FShapes, 0);
VP.Scale := 1;
VP.ViewPosition := VP.PortSize / 2;
end;
procedure TShapesList.Draw(ACanvas: TCanvas);
var i: integer;
begin
for i := 0 to High(FShapes) do
FShapes[i].Draw(ACanvas);
for i := 0 to High(FShapes) do
if FShapes[i].IsSelected then
FShapes[i].DrawSelection(ACanvas);
if FSelectionRectangle <> nil then
FSelectionRectangle.Draw(ACanvas);
end;
procedure TShapesList.Add(AShape: TShape);
begin
SetLength(FShapes, Length(FShapes) + 1);
FShapes[High(FShapes)] := AShape;
end;
procedure TShapesList.Select;
var i: Integer;
begin
for i := 0 to High(FShapes) do
FShapes[i].IsSelected :=
FShapes[i].RectInShape(VP.WorldToScreen(FSelectionRectangle.TrueRect));
end;
procedure TShapesList.Select(APoint: TPoint);
var i: Integer;
begin
for i := High(FShapes) downto 0 do
begin
FShapes[i].IsSelected := FShapes[i].PointInShape(APoint);
if FShapes[i].IsSelected then
Exit;
end;
end;
procedure TShapesList.SwitchSelect;
var i: Integer;
begin
for i := 0 to High(FShapes) do
FShapes[i].IsSelected :=
FShapes[i].RectInShape(VP.WorldToScreen(FSelectionRectangle.TrueRect)) xor
FShapes[i].PrevSelected;
end;
procedure TShapesList.SwitchSelect(APoint: TPoint);
var i: Integer;
begin
for i := High(FShapes) downto 0 do
begin
FShapes[i].IsSelected := FShapes[i].PointInShape(APoint) xor
FShapes[i].PrevSelected;
if FShapes[i].PointInShape(APoint) then
break;
end;
end;
constructor TShapesList.Create;
begin
History := THistory.Create(SaveJSON(FShapes));
OnUpdateEditor := @UpdateHistory;
end;
function TShapesList.PointOnEditPoint(APoint: TPoint; var AShape: TShape;
var AIndex: Integer): Boolean;
var i, j: Integer;
begin
AShape := nil;
AIndex := -1;
for i := High(FShapes) downto 0 do
begin
if not FShapes[i].IsSelected then
continue;
j := FShapes[i].PointInEditPoint(APoint);
Result := j <> -1;
if Result then
begin
AShape := FShapes[i];
AIndex := j;
Exit;
end;
end;
end;
procedure TShapesList.Delete;
var i, c: Integer;
begin
c := 0;
for i := 0 to High(FShapes) do
begin
if FShapes[i].IsSelected then
begin
c += 1;
FreeAndNil(FShapes[i]);
end
else
FShapes[i - c] := FShapes[i];
end;
SetLength(FShapes, Length(FShapes) - c);
if Length(FShapes) = 0 then
begin
VP.Scale := 1;
VP.ViewPosition := VP.PortSize / 2;
end;
Inspector.LoadNew(nil);
FOnZOrderSwitch(False);
UpdateHistory;
end;
procedure TShapesList.LoadSelected;
var
a: array of TShape;
i: Integer;
begin
SetLength(a, 0);
for i := 0 to High(FShapes) do
if FShapes[i].IsSelected then
begin
SetLength(a, Length(a) + 1);
a[High(a)] := FShapes[i];
FShapes[i].PrevSelected := True;
end
else
FShapes[i].PrevSelected := False;
Inspector.Load(a);
FOnZOrderSwitch(Length(a) > 0);
end;
procedure TShapesList.UnSelect;
var
i: Integer;
begin
for i := 0 to High(FShapes) do
if FShapes[i].IsSelected then
begin
Inspector.LoadNew(nil);
break;
end;
for i := 0 to High(FShapes) do
begin
FShapes[i].IsSelected := False;
FShapes[i].PrevSelected := False;
end;
FOnZOrderSwitch(False);
end;
procedure TShapesList.ZUp;
var
i: Integer;
s: TShape;
begin
for i := High(FShapes) downto 0 do
begin
if FShapes[i].IsSelected and (i < High(FShapes)) and
not FShapes[i + 1].IsSelected then
begin
s := FShapes[i];
FShapes[i] := FShapes[i + 1];
FShapes[i + 1] := s;
end;
end;
UpdateHistory;
end;
procedure TShapesList.ZDown;
var
i: Integer;
s: TShape;
begin
for i := 0 to High(FShapes) do
begin
if FShapes[i].IsSelected and (i > 0) and not FShapes[i - 1].IsSelected then
begin
s := FShapes[i];
FShapes[i] := FShapes[i - 1];
FShapes[i - 1] := s;
end;
end;
UpdateHistory;
end;
procedure TShapesList.ZTop;
var
i, j: Integer;
temp: array of TShape;
begin
SetLength(temp, Length(FShapes));
j := 0;
for i := 0 to High(FShapes) do
if not FShapes[i].IsSelected then
begin
temp[j] := FShapes[i];
j += 1;
end;
for i := 0 to High(FShapes) do
if FShapes[i].IsSelected then
begin
temp[j] := FShapes[i];
j += 1;
end;
FShapes := temp;
UpdateHistory;
end;
procedure TShapesList.ZBottom;
var
i, j: Integer;
temp: array of TShape;
begin
SetLength(temp, Length(FShapes));
j := 0;
for i := 0 to High(FShapes) do
if FShapes[i].IsSelected then
begin
temp[j] := FShapes[i];
j += 1;
end;
for i := 0 to High(FShapes) do
if not FShapes[i].IsSelected then
begin
temp[j] := FShapes[i];
j += 1;
end;
FShapes := temp;
UpdateHistory;
end;
function TShapesList.PointOnFigure(APoint: TPoint): Boolean;
var i: Integer;
begin
Result := False;
for i := 0 to High(FShapes) do
begin
Result := FShapes[i].IsSelected and FShapes[i].PointInShape(APoint);
if Result then
exit;
end;
end;
procedure TShapesList.ShiftSelected(AShift: TPoint);
var i: Integer;
begin
for i := 0 to High(FShapes) do
begin
if FShapes[i].IsSelected then
FShapes[i].Shift(AShift);
end;
end;
function TShapesList.IsEmpty: Boolean;
begin
Result := Length(FShapes) < 1;
end;
procedure TShapesList.Save(AFile: String);
var
f: Text;
begin
AssignFile(f, AFile);
Rewrite(f);
Write(f, SaveJSON(FShapes));
Close(f);
History.InformOfSave;
OnUpdateFileStatus;
end;
function TShapesList.Load(AFile: String): Boolean;
var
f: TStringList;
begin
Result := True;
f := TStringList.Create;
f.LoadFromFile(AFile);
New;
try
FShapes := LoadJSON(f.Text);
if not IsEmpty then
ShowAll;
History.StartNew(SaveJSON(FShapes));
except
on E: Exception do
begin
New;
MessageDlg(E.Message, mtError, [mbOK], 0);
Result := False;
end;
end;
OnUpdateFileStatus;
f.Free;
end;
procedure TShapesList.New;
begin
DeleteAll;
History.StartNew(SaveJSON(FShapes));
end;
procedure TShapesList.ExportToBMP(AFile: String; AWidth, AHeight: Integer);
var
bmp: TBitmap;
i: Integer;
t: TFloatRect;
s: Double;
begin
bmp := TBitmap.Create;
t := GetImageSize;
bmp.Height := AHeight;
bmp.Width := AWidth;
s := Min(AWidth / (t.Right - t.Left), AHeight / (t.Bottom - t.Top));
bmp.Canvas.Brush.Color := clWhite;
bmp.Canvas.FillRect(0, 0, bmp.Width, bmp.Height);
for i := 0 to High(FShapes) do
FShapes[i].DrawExport(bmp.Canvas, UGeometry.Point(
UGeometry.FloatPoint(t.Left, t.Top)), s);
bmp.SaveToFile(AFile);
bmp.Free;
end;
procedure TShapesList.ExportToPNG(AFile: String; AWidth, AHeight: Integer);
var
png: TPortableNetworkGraphic;
i: Integer;
t: TFloatRect;
s: Double;
begin
png := TPortableNetworkGraphic.Create;
t := GetImageSize;
png.Height := AHeight;
png.Width := AWidth;
s := Min(AWidth / (t.Right - t.Left), AHeight / (t.Bottom - t.Top));
png.Canvas.Brush.Color := clWhite;
png.Canvas.FillRect(0, 0, png.Width, png.Height);
for i := 0 to High(FShapes) do
FShapes[i].DrawExport(png.Canvas, UGeometry.Point(
UGeometry.FloatPoint(t.Left, t.Top)), s);
png.SaveToFile(AFile);
png.Free;
end;
procedure TShapesList.ExportToJPG(AFile: String; AWidth, AHeight: Integer);
var
jpg: TJPEGImage;
i: Integer;
t: TFloatRect;
s: Double;
begin
jpg := TJPEGImage.Create;
t := GetImageSize;
jpg.Height := AHeight;
jpg.Width := AWidth;
s := Min(AWidth / (t.Right - t.Left), AHeight / (t.Bottom - t.Top));
jpg.Canvas.Brush.Color := clWhite;
jpg.Canvas.FillRect(0, 0, jpg.Width, jpg.Height);
for i := 0 to High(FShapes) do
FShapes[i].DrawExport(jpg.Canvas, UGeometry.Point(
UGeometry.FloatPoint(t.Left, t.Top)), s);
jpg.SaveToFile(AFile);
jpg.Free;
end;
procedure TShapesList.ShowAll;
var t: TFloatRect;
begin
t := ImageSize;
VP.ViewPosition := FloatPoint((t.Left + t.Right) / 2, (t.Top + t.Bottom) / 2);
VP.ScaleTo(t);
end;
procedure TShapesList.Copy;
var
i: Integer;
t: TShapes;
begin
SetLength(t, 0);
for i := 0 to High(FShapes) do
if FShapes[i].IsSelected then
begin
SetLength(t, Length(t) + 1);
t[High(t)] := FShapes[i];
end;
if Length(t) > 0 then
Clipboard.AsText := SaveJSON(t);
end;
procedure TShapesList.Paste;
var
i: Integer;
t: TShapes;
begin
try
t := LoadJSON(Clipboard.AsText);
SetLength(FShapes, Length(FShapes) + Length(t));
for i := Length(FShapes) - Length(t) to High(FShapes) do
FShapes[i] := t[i - Length(FShapes) + Length(t)];
if Length(t) > 0 then
UpdateHistory;
except
end;
end;
procedure TShapesList.LoadState(AString: String);
begin
UnSelect;
FShapes := LoadJSON(AString);
end;
procedure TShapesList.Clear;
begin
DeleteAll;
History.AddNew(SaveJSON(FShapes));
end;
procedure TShapesList.UpdateHistory;
begin
History.AddNew(SaveJSON(FShapes));
OnUpdateFileStatus;
end;
end.
|
unit NewLawyerDialog;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, Wwdatsrc, DBTables, Wwtable, StdCtrls, Mask, DBCtrls, Buttons;
type
TNewLawyerForm = class(TForm)
LawyerDataSource: TwwDataSource;
UndoButton: TBitBtn;
GroupBox1: TGroupBox;
LawyerTable: TwwTable;
MainCodeLabel: TLabel;
Label11: TLabel;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label15: TLabel;
SwisLabel: TLabel;
Label17: TLabel;
Label3: TLabel;
Label28: TLabel;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Label5: TLabel;
MainCodeEdit: TDBEdit;
EditName: TDBEdit;
EditName2: TDBEdit;
EditAddress: TDBEdit;
EditAddress2: TDBEdit;
EditStreet: TDBEdit;
EditCity: TDBEdit;
EditState: TDBEdit;
EditZip: TDBEdit;
EditZipPlus4: TDBEdit;
EditPhoneNumber: TDBEdit;
EditFaxNumber: TDBEdit;
EditAttorneyName: TDBEdit;
EditEmail: TDBEdit;
SaveButton: TBitBtn;
LawyerCodeLookupTable: TwwTable;
procedure SaveButtonClick(Sender: TObject);
procedure UndoButtonClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
{ Private declarations }
public
{ Public declarations }
LawyerSelected : String;
Procedure InitializeForm;
end;
var
NewLawyerForm: TNewLawyerForm;
implementation
{$R *.DFM}
uses PASUtils, WinUtils, GlblVars;
{=========================================================================}
Procedure TNewLawyerForm.InitializeForm;
begin
LawyerSelected := '';
OpenTablesForForm(Self, GlblProcessingType);
try
LawyerTable.Insert;
except
end;
end; {InitializeForm}
{=========================================================================}
Procedure TNewLawyerForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
If (Key = #13)
then
begin
Key := #0;
Perform(WM_NEXTDLGCTL, 0, 0);
end;
end; {FormKeyPress}
{=========================================================================}
Procedure TNewLawyerForm.UndoButtonClick(Sender: TObject);
begin
LawyerTable.Cancel;
ModalResult := mrCancel;
end;
{=========================================================================}
Procedure TNewLawyerForm.SaveButtonClick(Sender: TObject);
begin
case LawyerTable.State of
dsEdit :
try
LawyerTable.Post;
LawyerSelected := LawyerTable.FieldByName('Code').Text;
ModalResult := mrOK;
except
end;
dsInsert :
begin
{FXX02022004-1(2.07l): Need to check for duplicates on a lookup table.}
If FindKeyOld(LawyerCodeLookupTable, ['Code'], [LawyerTable.FieldByName('Code').Text])
then
begin
MessageDlg('A representative already exists with the code ' +
LawyerTable.FieldByName('Code').Text + '.' + #13 +
'Please enter a different code.',
mtError, [mbOK], 0);
MainCodeEdit.SetFocus;
end
else
try
LawyerTable.Post;
LawyerSelected := LawyerTable.FieldByName('Code').Text;
ModalResult := mrOK;
except
end;
end; {dsInsert}
end; {case LawyerTable.State of}
end; {SaveButtonClick}
{=========================================================================}
Procedure TNewLawyerForm.FormCloseQuery( Sender: TObject;
var CanClose: Boolean);
begin
SaveButtonClick(Sender);
end;
end.
|
{Realizar un programa que cargue un vector de 800 caracteres. Finalizada la carga informar:
a) La cantidad de caracteres que son consonantes y la cantidad de vocales
b) La cantidad de caracteres que son dígitos, la cantidad de letras mayúsculas y la cantidad de letras
minúsculas.}
{digitos: desde 48 hasta el 57}
{letras mayusculas: desde 65 a 90}
{letras minusculas: desde 97 a 122}
program vectores4
type
vector = Array [] of integer;
proccedure cargarvector(v1,var dig,var mayus,var minus,var vocales)
var
i:integer
begin
for(i:=1 to 800)do begin
if(v[i]>= 48 and v[i]<= 57)then begin
dig:= dig + 1;
end else begin
if(v[i]>=65 and v[i]<=90)then begin
mayus:= mayus + 1;
if(v[i] == 'A' or 'E' or 'I' or 'O' or 'U')then begin
vocales:= vocales + 1;
end
end else begin if(v[i]>=97 to v[i]<122)then begin
minus:= minus + 1;
if(v[i] == 'a'OR'e'OR'i'OR'o'OR'u')then begin
vocales:= vocales + 1 ;
end
end
end
end
var
v1:vector;
dig,mayus,minus,vocales:integer;
Begin
dig:=0;
mayus:=o;
minus:=0;
vocales:=0;
read(v1);
cargarvector(v1,dig,mayus,minus,vocales);
wrtiteln('La cantidad de digitos dentro de los caracteres ingresados es:',dig);
wrtiteln('La cantidad de mayusculas dentro de los caracteres ingresados es:',mayus);
wrtiteln('La cantidad de minusculas dentro de los caracteres ingresados es:',minus);
writeln('El numero de vocales es:',vocales);
End
|
unit uPrintPreviewDialog;
interface
//In this example we will create a print document and print using PrintPreviewDialog.
//We will print some text on Print Page event
uses
{$IF CompilerVersion > 22}
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
{$ELSE}
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
{$IFEND}
CNClrLib.Control.EnumTypes, CNClrLib.Component.PrintDocument, CNClrLib.Control.Base,
CNClrLib.Component.PrintPreviewDialog;
type
TForm9 = class(TForm)
btnPrint: TButton;
CnPrintPreviewDialog1: TCnPrintPreviewDialog;
CnPrintDocument1: TCnPrintDocument;
procedure CnPrintDocument1PrintPage(Sender: TObject;
E: _PrintPageEventArgs);
procedure btnPrintClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form9: TForm9;
implementation
{$R *.dfm}
uses CNClrLib.Drawing, CNClrLib.EnumTypes;
procedure TForm9.btnPrintClick(Sender: TObject);
begin
CnPrintPreviewDialog1.ShowDialog;
end;
procedure TForm9.CnPrintDocument1PrintPage(Sender: TObject;
E: _PrintPageEventArgs);
var
text: String;
printFont: _Font;
brushes: _Brushes;
begin
text := 'Header';
printFont := CoFont.CreateInstance('Tahoma', 40, [TFontStyle.fsBold]);
brushes := CoBrushes.CreateInstance;
E.Graphics.DrawString(text, printFont, brushes.Blue, 0, 0);
text := 'Text';
printFont := CoFont.CreateInstance('Tahoma', 30, [TFontStyle.fsRegular]);
E.Graphics.DrawString(text, printFont, Brushes.Black , 0, 100);
end;
end.
|
unit TestDelphiNetRecordForward;
{ This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
Delphi.NEt record forward declarations
}
interface
type
TRecord1 = record;
TRecord2 = record;
TRecord3 = record;
TRecord1 = record
foo: integer;
bar: string;
fish: double;
rec: TRecord2;
end;
TRecord2 = record
foo: integer;
bar: string;
fish: double;
rec: TRecord3;
end;
TRecord3 = record
end;
implementation
end.
|
unit FC.Trade.TesterTrainReportDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogClose_B, ComCtrls, StdCtrls, ExtCtrls, ExtendControls,
Properties.Definitions,
StockChart.Definitions,
FC.Trade.TesterDialog;
type
TfmTesterTrainReportDialog = class(TfmDialogClose_B)
paWorkSpace: TPanel;
Label1: TLabel;
lvReport: TExtendListView;
buStopTrain: TButton;
procedure lvReportColumnClick(Sender: TObject; Column: TListColumn);
procedure buStopTrainClick(Sender: TObject);
private
FTesterDialog: TfmTradeTesterDialog;
FCount: integer;
FStopped: boolean;
FRunning: boolean;
FTrainingProperties: TInterfaceList;
FLastSortOrderColumn: integer;
procedure RunTrainingInternal(index: integer);
public
class procedure Run(aDialog: TfmTradeTesterDialog; aTrainingProperties : TInterfaceList);
end;
implementation
uses ufmDialog_B;
{$R *.dfm}
const
ProfitColumnName = 'Profit';
{ TfmTesterTrainReportDialog }
class procedure TfmTesterTrainReportDialog.Run(aDialog: TfmTradeTesterDialog; aTrainingProperties: TInterfaceList);
var
i: integer;
begin
with TfmTesterTrainReportDialog.Create(nil) do
try
FTesterDialog:=aDialog;
FTrainingProperties:=aTrainingProperties;
FLastSortOrderColumn:=-1;
for i:=0 to aTrainingProperties.Count-1 do
with lvReport.Columns.Add do
begin
Caption:=(aTrainingProperties[i] as IProperty).GetName;
end;
with lvReport.Columns.Add do
Caption:=ProfitColumnName;
ShowModal;
finally
Free;
end;
end;
procedure TfmTesterTrainReportDialog.RunTrainingInternal(index: integer);
var
aProperty: ISCIndicatorPropertyTrainee;
aItem: TListItem;
i: integer;
begin
aProperty:=FTrainingProperties[index] as ISCIndicatorPropertyTrainee;
buOK.Enabled:=false;
try
aProperty.StartTrain;
repeat
if index<FTrainingProperties.Count-1 then
RunTrainingInternal(index+1)
else begin
//Report
Inc(FCount);
aItem:=lvReport.Items.Add;
aItem.Caption:=IntToStr(FCount);
for i:=0 to FTrainingProperties.Count-1 do
aItem.SubItems.Add((FTrainingProperties[i] as ISCIndicatorProperty).ValueAsText);
Forms.Application.ProcessMessages;
//Run
FTesterDialog.RunTesting;
Forms.Application.ProcessMessages;
aItem.SubItems.Add(CurrToStr(FTesterDialog.frmStockTradeResult.Statictics.Balance));
end;
if FStopped then
break;
until not aProperty.DoTrainStep;
finally
buOK.Enabled:=true;
end;
end;
procedure TfmTesterTrainReportDialog.buStopTrainClick(Sender: TObject);
begin
inherited;
if FRunning then
begin
FStopped:=true
end
else begin
buStopTrain.Caption:='Stop Train';
FRunning:=true;
Forms.Application.ProcessMessages;
RunTrainingInternal(0);
buStopTrain.Caption:='Start Train';
FRunning:=false;
FStopped:=false;
end;
end;
procedure TfmTesterTrainReportDialog.lvReportColumnClick(Sender: TObject; Column: TListColumn);
begin
if Column.Caption<>ProfitColumnName then
exit;
if FLastSortOrderColumn = Column.Index then
begin
FLastSortOrderColumn := -1;
lvReport.SortColumn(Column,smCurrency,true);
end
else
begin
FLastSortOrderColumn := Column.Index;
lvReport.SortColumn(Column,smCurrency,false);
end;
end;
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// 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.
//
{$POINTERMATH ON}
unit RN_DetourNavMeshQuery;
interface
uses Classes, RN_DetourCommon, RN_DetourNavMesh, RN_DetourNavMeshHelper, RN_DetourNode, RN_DetourStatus;
type
// Define DT_VIRTUAL_QUERYFILTER if you wish to derive a custom filter from dtQueryFilter.
// On certain platforms indirect or virtual function call is expensive. The default
// setting is to use non-virtual functions, the actual implementations of the functions
// are declared as inline for maximum speed.
//#define DT_VIRTUAL_QUERYFILTER 1
/// Defines polygon filtering and traversal costs for navigation mesh query operations.
/// @ingroup detour
TdtQueryFilter = class
private
m_areaCost: array [0..DT_MAX_AREAS-1] of Single; ///< Cost per area type. (Used by default implementation.)
m_includeFlags: Word; ///< Flags for polygons that can be visited. (Used by default implementation.)
m_excludeFlags: Word; ///< Flags for polygons that should not be visted. (Used by default implementation.)
public
constructor Create;
/// Returns true if the polygon can be visited. (I.e. Is traversable.)
/// @param[in] ref The reference id of the polygon test.
/// @param[in] tile The tile containing the polygon.
/// @param[in] poly The polygon to test.
function passFilter(ref: TdtPolyRef; tile: PdtMeshTile; poly: PdtPoly): Boolean;
/// Returns cost to move from the beginning to the end of a line segment
/// that is fully contained within a polygon.
/// @param[in] pa The start position on the edge of the previous and current polygon. [(x, y, z)]
/// @param[in] pb The end position on the edge of the current and next polygon. [(x, y, z)]
/// @param[in] prevRef The reference id of the previous polygon. [opt]
/// @param[in] prevTile The tile containing the previous polygon. [opt]
/// @param[in] prevPoly The previous polygon. [opt]
/// @param[in] curRef The reference id of the current polygon.
/// @param[in] curTile The tile containing the current polygon.
/// @param[in] curPoly The current polygon.
/// @param[in] nextRef The refernece id of the next polygon. [opt]
/// @param[in] nextTile The tile containing the next polygon. [opt]
/// @param[in] nextPoly The next polygon. [opt]
function getCost(pa, pb: PSingle;
prevRef: TdtPolyRef; prevTile: PdtMeshTile; prevPoly: PdtPoly;
curRef: TdtPolyRef; curTile: PdtMeshTile; curPoly: PdtPoly;
nextRef: TdtPolyRef; nextTile: PdtMeshTile; nextPoly: PdtPoly): Single;
/// @name Getters and setters for the default implementation data.
///@{
/// Returns the traversal cost of the area.
/// @param[in] i The id of the area.
/// @returns The traversal cost of the area.
function getAreaCost(i: Integer): Single; { return m_areaCost[i]; }
/// Sets the traversal cost of the area.
/// @param[in] i The id of the area.
/// @param[in] cost The new cost of traversing the area.
procedure setAreaCost(i: Integer; cost: Single); { m_areaCost[i] = cost; }
/// Returns the include flags for the filter.
/// Any polygons that include one or more of these flags will be
/// included in the operation.
function getIncludeFlags(): Word; { return m_includeFlags; }
/// Sets the include flags for the filter.
/// @param[in] flags The new flags.
procedure setIncludeFlags(flags: Word); { m_includeFlags = flags; }
/// Returns the exclude flags for the filter.
/// Any polygons that include one ore more of these flags will be
/// excluded from the operation.
function getExcludeFlags(): Word; { return m_excludeFlags; }
/// Sets the exclude flags for the filter.
/// @param[in] flags The new flags.
procedure setExcludeFlags(flags: Word); { m_excludeFlags = flags; }
///@}
end;
/// Provides information about raycast hit
/// filled by dtNavMeshQuery::raycast
/// @ingroup detour
PdtRaycastHit = ^TdtRaycastHit;
TdtRaycastHit = record
/// The hit parameter. (FLT_MAX if no wall hit.)
t: Single;
/// hitNormal The normal of the nearest wall hit. [(x, y, z)]
hitNormal: array [0..2] of Single;
/// Pointer to an array of reference ids of the visited polygons. [opt]
path: PdtPolyRef;
/// The number of visited polygons. [opt]
pathCount: Integer;
/// The maximum number of polygons the @p path array can hold.
maxPath: Integer;
/// The cost of the path until hit.
pathCost: Single;
end;
TdtQueryData = record
status: TdtStatus;
lastBestNode: PdtNode;
lastBestNodeCost: Single;
startRef, endRef: TdtPolyRef;
startPos, endPos: array [0..2] of Single;
filter: TdtQueryFilter;
options: Cardinal;
raycastLimitSqr: Single;
end;
/// Provides the ability to perform pathfinding related queries against
/// a navigation mesh.
/// @ingroup detour
TdtNavMeshQuery = class
private
m_nav: TdtNavMesh; ///< Pointer to navmesh data.
m_tinyNodePool: TdtNodePool;///< Pointer to small node pool.
m_nodePool: TdtNodePool; ///< Pointer to node pool.
m_openList: TdtNodeQueue; ///< Pointer to open list queue.
m_query: TdtQueryData; ///< Sliced query state.
public
constructor Create;
destructor Destroy; override;
/// Initializes the query object.
/// @param[in] nav Pointer to the dtNavMesh object to use for all queries.
/// @param[in] maxNodes Maximum number of search nodes. [Limits: 0 < value <= 65536]
/// @returns The status flags for the query.
function init(nav: TdtNavMesh; maxNodes: Integer): TdtStatus;
/// @name Standard Pathfinding Functions
// /@{
/// Finds a path from the start polygon to the end polygon.
/// @param[in] startRef The refrence id of the start polygon.
/// @param[in] endRef The reference id of the end polygon.
/// @param[in] startPos A position within the start polygon. [(x, y, z)]
/// @param[in] endPos A position within the end polygon. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 1]
function findPath(startRef, endRef: TdtPolyRef;
startPos, endPos: PSingle;
filter: TdtQueryFilter;
path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
/// Finds the straight path from the start to the end position within the polygon corridor.
/// @param[in] startPos Path start position. [(x, y, z)]
/// @param[in] endPos Path end position. [(x, y, z)]
/// @param[in] path An array of polygon references that represent the path corridor.
/// @param[in] pathSize The number of polygons in the @p path array.
/// @param[out] straightPath Points describing the straight path. [(x, y, z) * @p straightPathCount].
/// @param[out] straightPathFlags Flags describing each point. (See: #dtStraightPathFlags) [opt]
/// @param[out] straightPathRefs The reference id of the polygon that is being entered at each point. [opt]
/// @param[out] straightPathCount The number of points in the straight path.
/// @param[in] maxStraightPath The maximum number of points the straight path arrays can hold. [Limit: > 0]
/// @param[in] options Query options. (see: #dtStraightPathOptions)
/// @returns The status flags for the query.
function findStraightPath(startPos, endPos: PSingle;
path: PdtPolyRef; pathSize: Integer;
straightPath: PSingle; straightPathFlags: PByte; straightPathRefs: PdtPolyRef;
straightPathCount: PInteger; maxStraightPath: Integer; options: Integer = 0): TdtStatus;
///@}
/// @name Sliced Pathfinding Functions
/// Common use case:
/// -# Call initSlicedFindPath() to initialize the sliced path query.
/// -# Call updateSlicedFindPath() until it returns complete.
/// -# Call finalizeSlicedFindPath() to get the path.
///@{
/// Intializes a sliced path query.
/// @param[in] startRef The refrence id of the start polygon.
/// @param[in] endRef The reference id of the end polygon.
/// @param[in] startPos A position within the start polygon. [(x, y, z)]
/// @param[in] endPos A position within the end polygon. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] options query options (see: #dtFindPathOptions)
/// @returns The status flags for the query.
function initSlicedFindPath(startRef, endRef: TdtPolyRef;
startPos, endPos: PSingle;
filter: TdtQueryFilter; options: Integer = 0): TdtStatus;
/// Updates an in-progress sliced path query.
/// @param[in] maxIter The maximum number of iterations to perform.
/// @param[out] doneIters The actual number of iterations completed. [opt]
/// @returns The status flags for the query.
function updateSlicedFindPath(maxIter: Integer; doneIters: PInteger): TdtStatus;
/// Finalizes and returns the results of a sliced path query.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The max number of polygons the path array can hold. [Limit: >= 1]
/// @returns The status flags for the query.
function finalizeSlicedFindPath(path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
/// Finalizes and returns the results of an incomplete sliced path query, returning the path to the furthest
/// polygon on the existing path that was visited during the search.
/// @param[in] existing An array of polygon references for the existing path.
/// @param[in] existingSize The number of polygon in the @p existing array.
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
/// [(polyRef) * @p pathCount]
/// @param[out] pathCount The number of polygons returned in the @p path array.
/// @param[in] maxPath The max number of polygons the @p path array can hold. [Limit: >= 1]
/// @returns The status flags for the query.
function finalizeSlicedFindPathPartial(existing: PdtPolyRef; existingSize: Integer;
path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
///@}
/// @name Dijkstra Search Functions
/// @{
/// Finds the polygons along the navigation graph that touch the specified circle.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
/// @param[in] radius The radius of the search circle.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultRef The reference ids of the polygons touched by the circle. [opt]
/// @param[out] resultParent The reference ids of the parent polygons for each result.
/// Zero if a result polygon has no parent. [opt]
/// @param[out] resultCost The search cost from @p centerPos to the polygon. [opt]
/// @param[out] resultCount The number of polygons found. [opt]
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
/// @returns The status flags for the query.
function findPolysAroundCircle(startRef: TdtPolyRef; centerPos: PSingle; radius: Single;
filter: TdtQueryFilter;
resultRef, resultParent: PdtPolyRef; resultCost: PSingle;
resultCount: PInteger; maxResult: Integer): TdtStatus;
/// Finds the polygons along the naviation graph that touch the specified convex polygon.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] verts The vertices describing the convex polygon. (CCW)
/// [(x, y, z) * @p nverts]
/// @param[in] nverts The number of vertices in the polygon.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultRef The reference ids of the polygons touched by the search polygon. [opt]
/// @param[out] resultParent The reference ids of the parent polygons for each result. Zero if a
/// result polygon has no parent. [opt]
/// @param[out] resultCost The search cost from the centroid point to the polygon. [opt]
/// @param[out] resultCount The number of polygons found.
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
/// @returns The status flags for the query.
function findPolysAroundShape(startRef: TdtPolyRef; verts: PSingle; nverts: Integer;
filter: TdtQueryFilter;
resultRef, resultParent: PdtPolyRef; resultCost: PSingle;
resultCount: PInteger; maxResult: Integer): TdtStatus;
/// @}
/// @name Local Query Functions
///@{
/// Finds the polygon nearest to the specified center point.
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] extents The search distance along each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] nearestRef The reference id of the nearest polygon.
/// @param[out] nearestPt The nearest point on the polygon. [opt] [(x, y, z)]
/// @returns The status flags for the query.
function findNearestPoly(center, extents: PSingle; filter: TdtQueryFilter; nearestRef: PdtPolyRef; nearestPt: PSingle): TdtStatus;
/// Finds polygons that overlap the search box.
/// @param[in] center The center of the search box. [(x, y, z)]
/// @param[in] extents The search distance along each axis. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] polys The reference ids of the polygons that overlap the query box.
/// @param[out] polyCount The number of polygons in the search result.
/// @param[in] maxPolys The maximum number of polygons the search result can hold.
/// @returns The status flags for the query.
function queryPolygons(center, extents: PSingle; filter: TdtQueryFilter; polys: PdtPolyRef; polyCount: PInteger; maxPolys: Integer): TdtStatus;
/// Finds the non-overlapping navigation polygons in the local neighbourhood around the center position.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] centerPos The center of the query circle. [(x, y, z)]
/// @param[in] radius The radius of the query circle.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultRef The reference ids of the polygons touched by the circle.
/// @param[out] resultParent The reference ids of the parent polygons for each result.
/// Zero if a result polygon has no parent. [opt]
/// @param[out] resultCount The number of polygons found.
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
/// @returns The status flags for the query.
function findLocalNeighbourhood(startRef: TdtPolyRef; centerPos: PSingle; radius: Single;
filter: TdtQueryFilter;
resultRef, resultParent: PdtPolyRef;
resultCount: PInteger; maxResult: Integer): TdtStatus;
/// Moves from the start to the end position constrained to the navigation mesh.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] startPos A position of the mover within the start polygon. [(x, y, x)]
/// @param[in] endPos The desired end position of the mover. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] resultPos The result position of the mover. [(x, y, z)]
/// @param[out] visited The reference ids of the polygons visited during the move.
/// @param[out] visitedCount The number of polygons visited during the move.
/// @param[in] maxVisitedSize The maximum number of polygons the @p visited array can hold.
/// @returns The status flags for the query.
function moveAlongSurface(startRef: TdtPolyRef; startPos, endPos: PSingle;
filter: TdtQueryFilter;
resultPos: PSingle; visited: PdtPolyRef; visitedCount: PInteger; maxVisitedSize: Integer): TdtStatus;
/// Casts a 'walkability' ray along the surface of the navigation mesh from
/// the start position toward the end position.
/// @note A wrapper around raycast(..., RaycastHit*). Retained for backward compatibility.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] startPos A position within the start polygon representing
/// the start of the ray. [(x, y, z)]
/// @param[in] endPos The position to cast the ray toward. [(x, y, z)]
/// @param[out] t The hit parameter. (FLT_MAX if no wall hit.)
/// @param[out] hitNormal The normal of the nearest wall hit. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] path The reference ids of the visited polygons. [opt]
/// @param[out] pathCount The number of visited polygons. [opt]
/// @param[in] maxPath The maximum number of polygons the @p path array can hold.
/// @returns The status flags for the query.
function raycast(startRef: TdtPolyRef; startPos, endPos: PSingle;
filter: TdtQueryFilter;
t, hitNormal: PSingle; path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus; overload;
/// Casts a 'walkability' ray along the surface of the navigation mesh from
/// the start position toward the end position.
/// @param[in] startRef The reference id of the start polygon.
/// @param[in] startPos A position within the start polygon representing
/// the start of the ray. [(x, y, z)]
/// @param[in] endPos The position to cast the ray toward. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] flags govern how the raycast behaves. See dtRaycastOptions
/// @param[out] hit Pointer to a raycast hit structure which will be filled by the results.
/// @param[in] prevRef parent of start ref. Used during for cost calculation [opt]
/// @returns The status flags for the query.
function raycast(startRef: TdtPolyRef; startPos, endPos: PSingle;
filter: TdtQueryFilter; options: Cardinal;
hit: PdtRaycastHit; prevRef: TdtPolyRef = 0): TdtStatus; overload;
/// Finds the distance from the specified position to the nearest polygon wall.
/// @param[in] startRef The reference id of the polygon containing @p centerPos.
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
/// @param[in] maxRadius The radius of the search circle.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] hitDist The distance to the nearest wall from @p centerPos.
/// @param[out] hitPos The nearest position on the wall that was hit. [(x, y, z)]
/// @param[out] hitNormal The normalized ray formed from the wall point to the
/// source point. [(x, y, z)]
/// @returns The status flags for the query.
function findDistanceToWall(startRef: TdtPolyRef; centerPos: PSingle; maxRadius: Single;
filter: TdtQueryFilter;
hitDist, hitPos, hitNormal: PSingle): TdtStatus;
/// Returns the segments for the specified polygon, optionally including portals.
/// @param[in] ref The reference id of the polygon.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[out] segmentVerts The segments. [(ax, ay, az, bx, by, bz) * segmentCount]
/// @param[out] segmentRefs The reference ids of each segment's neighbor polygon.
/// Or zero if the segment is a wall. [opt] [(parentRef) * @p segmentCount]
/// @param[out] segmentCount The number of segments returned.
/// @param[in] maxSegments The maximum number of segments the result arrays can hold.
/// @returns The status flags for the query.
function getPolyWallSegments(ref: TdtPolyRef; filter: TdtQueryFilter;
segmentVerts: PSingle; segmentRefs: PdtPolyRef; segmentCount: PInteger;
maxSegments: Integer): TdtStatus;
/// Returns random location on navmesh.
/// Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] frand Function returning a random number [0..1).
/// @param[out] randomRef The reference id of the random location.
/// @param[out] randomPt The random location.
/// @returns The status flags for the query.
function findRandomPoint(filter: TdtQueryFilter; //float ( *frand)(),
randomRef: PdtPolyRef; randomPt: PSingle): TdtStatus;
/// Returns random location on navmesh within the reach of specified location.
/// Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
/// The location is not exactly constrained by the circle, but it limits the visited polygons.
/// @param[in] startRef The reference id of the polygon where the search starts.
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
/// @param[in] filter The polygon filter to apply to the query.
/// @param[in] frand Function returning a random number [0..1).
/// @param[out] randomRef The reference id of the random location.
/// @param[out] randomPt The random location. [(x, y, z)]
/// @returns The status flags for the query.
function findRandomPointAroundCircle(startRef: TdtPolyRef; centerPos: PSingle; maxRadius: Single;
filter: TdtQueryFilter; //{float ( *frand)(),
randomRef: PdtPolyRef; randomPt: PSingle): TdtStatus;
/// Finds the closest point on the specified polygon.
/// @param[in] ref The reference id of the polygon.
/// @param[in] pos The position to check. [(x, y, z)]
/// @param[out] closest The closest point on the polygon. [(x, y, z)]
/// @param[out] posOverPoly True of the position is over the polygon.
/// @returns The status flags for the query.
function closestPointOnPoly(ref: TdtPolyRef; pos, closest: PSingle; posOverPoly: PBoolean): TdtStatus;
/// Returns a point on the boundary closest to the source point if the source point is outside the
/// polygon's xz-bounds.
/// @param[in] ref The reference id to the polygon.
/// @param[in] pos The position to check. [(x, y, z)]
/// @param[out] closest The closest point. [(x, y, z)]
/// @returns The status flags for the query.
function closestPointOnPolyBoundary(ref: TdtPolyRef; pos, closest: PSingle): TdtStatus;
/// Gets the height of the polygon at the provided position using the height detail. (Most accurate.)
/// @param[in] ref The reference id of the polygon.
/// @param[in] pos A position within the xz-bounds of the polygon. [(x, y, z)]
/// @param[out] height The height at the surface of the polygon.
/// @returns The status flags for the query.
function getPolyHeight(ref: TdtPolyRef; pos, height: PSingle): TdtStatus;
/// @}
/// @name Miscellaneous Functions
/// @{
/// Returns true if the polygon reference is valid and passes the filter restrictions.
/// @param[in] ref The polygon reference to check.
/// @param[in] filter The filter to apply.
function isValidPolyRef(ref: TdtPolyRef; filter: TdtQueryFilter): Boolean;
/// Returns true if the polygon reference is in the closed list.
/// @param[in] ref The reference id of the polygon to check.
/// @returns True if the polygon is in closed list.
function isInClosedList(ref: TdtPolyRef): Boolean;
/// Gets the node pool.
/// @returns The node pool.
property getNodePool: TdtNodePool read m_nodePool;
/// Gets the navigation mesh the query object is using.
/// @return The navigation mesh the query object is using.
property getAttachedNavMesh: TdtNavMesh read m_nav;
/// @}
private
/// Returns neighbour tile based on side.
{ function getNeighbourTileAt(x, y, side: Integer): PdtMeshTile;}
/// Queries polygons within a tile.
function queryPolygonsInTile(tile: PdtMeshTile; qmin, qmax: PSingle; filter: TdtQueryFilter;
polys: PdtPolyRef; maxPolys: Integer): Integer;
/// Returns portal points between two polygons.
function getPortalPoints(from, &to: TdtPolyRef; left, right: PSingle;
fromType, toType: PByte): TdtStatus; overload;
function getPortalPoints(from: TdtPolyRef; fromPoly: PdtPoly; fromTile: PdtMeshTile;
&to: TdtPolyRef; toPoly: PdtPoly; toTile: PdtMeshTile;
left, right: PSingle): TdtStatus; overload;
/// Returns edge mid point between two polygons.
function getEdgeMidPoint(from, &to: TdtPolyRef; mid: PSingle): TdtStatus; overload;
function getEdgeMidPoint(from: TdtPolyRef; fromPoly: PdtPoly; fromTile: PdtMeshTile;
&to: TdtPolyRef; toPoly: PdtPoly; toTile: PdtMeshTile;
mid: PSingle): TdtStatus; overload;
// Appends vertex to a straight path
function appendVertex(pos: PSingle; flags: Integer; ref: TdtPolyRef;
straightPath: PSingle; straightPathFlags: PByte; straightPathRefs: PdtPolyRef;
straightPathCount: PInteger; maxStraightPath: Integer): TdtStatus;
// Appends intermediate portal points to a straight path.
function appendPortals(startIdx, endIdx: Integer; endPos: PSingle; path: PdtPolyRef;
straightPath: PSingle; straightPathFlags: PByte; straightPathRefs: PdtPolyRef;
straightPathCount: PInteger; maxStraightPath, options: Integer): TdtStatus;
end;
/// Allocates a query object using the Detour allocator.
/// @return An allocated query object, or null on failure.
/// @ingroup detour
function dtAllocNavMeshQuery(): TdtNavMeshQuery;
/// Frees the specified query object using the Detour allocator.
/// @param[in] query A query object allocated using #dtAllocNavMeshQuery
/// @ingroup detour
procedure dtFreeNavMeshQuery(var navmesh: TdtNavMeshQuery);
implementation
uses Math;
/// @class dtQueryFilter
///
/// <b>The Default Implementation</b>
///
/// At construction: All area costs default to 1.0. All flags are included
/// and none are excluded.
///
/// If a polygon has both an include and an exclude flag, it will be excluded.
///
/// The way filtering works, a navigation mesh polygon must have at least one flag
/// set to ever be considered by a query. So a polygon with no flags will never
/// be considered.
///
/// Setting the include flags to 0 will result in all polygons being excluded.
///
/// <b>Custom Implementations</b>
///
/// DT_VIRTUAL_QUERYFILTER must be defined in order to extend this class.
///
/// Implement a custom query filter by overriding the virtual passFilter()
/// and getCost() functions. If this is done, both functions should be as
/// fast as possible. Use cached local copies of data rather than accessing
/// your own objects where possible.
///
/// Custom implementations do not need to adhere to the flags or cost logic
/// used by the default implementation.
///
/// In order for A* searches to work properly, the cost should be proportional to
/// the travel distance. Implementing a cost modifier less than 1.0 is likely
/// to lead to problems during pathfinding.
///
/// @see dtNavMeshQuery
constructor TdtQueryFilter.Create;
var i: Integer;
begin
m_includeFlags := $ffff;
m_excludeFlags := 0;
for i := 0 to DT_MAX_AREAS - 1 do
m_areaCost[i] := 1.0;
end;
function TdtQueryFilter.passFilter(ref: TdtPolyRef; tile: PdtMeshTile; poly: PdtPoly): Boolean;
begin
Result := ((poly.flags and m_includeFlags) <> 0) and ((poly.flags and m_excludeFlags) = 0);
end;
function TdtQueryFilter.getCost(pa, pb: PSingle;
prevRef: TdtPolyRef; prevTile: PdtMeshTile; prevPoly: PdtPoly;
curRef: TdtPolyRef; curTile: PdtMeshTile; curPoly: PdtPoly;
nextRef: TdtPolyRef; nextTile: PdtMeshTile; nextPoly: PdtPoly): Single;
begin
Result := dtVdist(pa, pb) * m_areaCost[curPoly.getArea()];
end;
function TdtQueryFilter.getAreaCost(i: Integer): Single; begin Result := m_areaCost[i]; end;
procedure TdtQueryFilter.setAreaCost(i: Integer; cost: Single); begin m_areaCost[i] := cost; end;
function TdtQueryFilter.getIncludeFlags(): Word; begin Result := m_includeFlags; end;
procedure TdtQueryFilter.setIncludeFlags(flags: Word); begin m_includeFlags := flags; end;
function TdtQueryFilter.getExcludeFlags(): Word; begin Result := m_excludeFlags; end;
procedure TdtQueryFilter.setExcludeFlags(flags: Word); begin m_excludeFlags := flags; end;
const H_SCALE = 0.999; // Search heuristic scale.
function dtAllocNavMeshQuery(): TdtNavMeshQuery;
begin
Result := TdtNavMeshQuery.Create;
end;
procedure dtFreeNavMeshQuery(var navmesh: TdtNavMeshQuery);
begin
if (navmesh = nil) then Exit;
navMesh.Free;
navMesh := nil;
end;
//////////////////////////////////////////////////////////////////////////////////////////
/// @class dtNavMeshQuery
///
/// For methods that support undersized buffers, if the buffer is too small
/// to hold the entire result set the return status of the method will include
/// the #DT_BUFFER_TOO_SMALL flag.
///
/// Constant member functions can be used by multiple clients without side
/// effects. (E.g. No change to the closed list. No impact on an in-progress
/// sliced path query. Etc.)
///
/// Walls and portals: A @e wall is a polygon segment that is
/// considered impassable. A @e portal is a passable segment between polygons.
/// A portal may be treated as a wall based on the dtQueryFilter used for a query.
///
/// @see dtNavMesh, dtQueryFilter, #dtAllocNavMeshQuery(), #dtAllocNavMeshQuery()
constructor TdtNavMeshQuery.Create;
begin
inherited;
end;
destructor TdtNavMeshQuery.Destroy;
begin
m_tinyNodePool.Free;
m_nodePool.Free;
m_openList.Free;
inherited;
end;
/// @par
///
/// Must be the first function called after construction, before other
/// functions are used.
///
/// This function can be used multiple times.
function TdtNavMeshQuery.init(nav: TdtNavMesh; maxNodes: Integer): TdtStatus;
begin
m_nav := nav;
if (m_nodePool = nil) or (m_nodePool.getMaxNodes < maxNodes) then
begin
if (m_nodePool <> nil) then
begin
m_nodePool.Free;
m_nodePool := nil;
end;
m_nodePool := TdtNodePool.Create(maxNodes, dtNextPow2(maxNodes div 4));
if (m_nodePool = nil) then
Exit(DT_FAILURE or DT_OUT_OF_MEMORY);
end
else
begin
m_nodePool.clear();
end;
if (m_tinyNodePool = nil) then
begin
m_tinyNodePool := TdtNodePool.Create(64, 32);
if (m_tinyNodePool = nil) then
Exit(DT_FAILURE or DT_OUT_OF_MEMORY);
end
else
begin
m_tinyNodePool.clear();
end;
// TODO: check the open list size too.
if (m_openList = nil) or (m_openList.getCapacity < maxNodes) then
begin
if (m_openList <> nil) then
begin
m_openList.Free;
m_openList := nil;
end;
m_openList := TdtNodeQueue.Create(maxNodes);
if (m_openList = nil) then
Exit(DT_FAILURE or DT_OUT_OF_MEMORY);
end
else
begin
m_openList.clear();
end;
Result := DT_SUCCESS;
end;
function TdtNavMeshQuery.findRandomPoint(filter: TdtQueryFilter; //float ( *frand)(),
randomRef: PdtPolyRef; randomPt: PSingle): TdtStatus;
var tile: PdtMeshTile; tsum,area,u,areaSum,polyArea,rs,rt,h: Single; i,j: Integer; t: PdtMeshTile; poly,p: PdtPoly;
polyRef,base,ref: TdtPolyRef; va,vb,vc,v: PSingle; verts: array [0..3*DT_VERTS_PER_POLYGON-1] of Single;
areas: array [0..DT_VERTS_PER_POLYGON-1] of Single; pt: array [0..2] of Single; status: TdtStatus;
begin
Assert(m_nav <> nil);
// Randomly pick one tile. Assume that all tiles cover roughly the same area.
tile := nil;
tsum := 0.0;
for i := 0 to m_nav.getMaxTiles - 1 do
begin
t := m_nav.getTile(i);
if (t = nil) or(t.header = nil) then continue;
// Choose random tile using reservoi sampling.
area := 1.0; // Could be tile area too.
tsum := tsum + area;
u := Random();
if (u*tsum <= area) then
tile := t;
end;
if (tile = nil) then
Exit(DT_FAILURE);
// Randomly pick one polygon weighted by polygon area.
poly := nil;
polyRef := 0;
base := m_nav.getPolyRefBase(tile);
areaSum := 0.0;
for i := 0 to tile.header.polyCount - 1 do
begin
p := @tile.polys[i];
// Do not return off-mesh connection polygons.
if (p.getType() <> DT_POLYTYPE_GROUND) then
continue;
// Must pass filter
ref := base or TdtPolyRef(i);
if (not filter.passFilter(ref, tile, p)) then
continue;
// Calc area of the polygon.
polyArea := 0.0;
for j := 2 to p.vertCount - 1 do
begin
va := @tile.verts[p.verts[0]*3];
vb := @tile.verts[p.verts[j-1]*3];
vc := @tile.verts[p.verts[j]*3];
polyArea := polyArea + dtTriArea2D(va,vb,vc);
end;
// Choose random polygon weighted by area, using reservoi sampling.
areaSum := areaSum + polyArea;
u := Random();
if (u*areaSum <= polyArea) then
begin
poly := p;
polyRef := ref;
end;
end;
if (poly = nil) then
Exit(DT_FAILURE);
// Randomly pick point on polygon.
v := @tile.verts[poly.verts[0]*3];
dtVcopy(@verts[0*3],v);
for j := 1 to poly.vertCount - 1 do
begin
v := @tile.verts[poly.verts[j]*3];
dtVcopy(@verts[j*3],v);
end;
rs := Random();
rt := Random();
dtRandomPointInConvexPoly(@verts[0], poly.vertCount, @areas[0], rs, rt, @pt[0]);
h := 0.0;
status := getPolyHeight(polyRef, @pt[0], @h);
if (dtStatusFailed(status)) then
Exit(status);
pt[1] := h;
dtVcopy(randomPt, @pt[0]);
randomRef^ := polyRef;
Result := DT_SUCCESS;
end;
function TdtNavMeshQuery.findRandomPointAroundCircle(startRef: TdtPolyRef; centerPos: PSingle; maxRadius: Single;
filter: TdtQueryFilter; //float ( *frand)(),
randomRef: PdtPolyRef; randomPt: PSingle): TdtStatus;
var startTile,randomTile,bestTile,parentTile,neighbourTile: PdtMeshTile; startPoly,randomPoly,bestPoly,parentPoly,neighbourPoly: PdtPoly;
startNode,bestNode,neighbourNode: PdtNode; status: TdtStatus; radiusSqr,areaSum: Single; randomPolyRef,bestRef,parentRef,neighbourRef: TdtPolyRef;
polyArea,u,s,t,h,tseg,distSqr,total: Single; j: Integer; va,vb,vc,v: PSingle; i: Cardinal; link: PdtLink; va3,vb3,pt: array [0..2] of Single;
verts: array [0..3*DT_VERTS_PER_POLYGON-1] of Single; areas: array [0..DT_VERTS_PER_POLYGON-1] of Single; stat: TdtStatus;
begin
Assert(m_nav <> nil);
Assert(m_nodePool <> nil);
Assert(m_openList <> nil);
// Validate input
if (startRef = 0) or (not m_nav.isValidPolyRef(startRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
startTile := nil;
startPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(startRef, @startTile, @startPoly);
if (not filter.passFilter(startRef, startTile, startPoly)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
m_nodePool.clear();
m_openList.clear();
startNode := m_nodePool.getNode(startRef);
dtVcopy(@startNode.pos, centerPos);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := 0;
startNode.id := startRef;
startNode.flags := DT_NODE_OPEN;
m_openList.push(startNode);
status := DT_SUCCESS;
radiusSqr := Sqr(maxRadius);
areaSum := 0.0;
randomTile := nil;
randomPoly := nil;
randomPolyRef := 0;
while (not m_openList.empty()) do
begin
bestNode := m_openList.pop();
bestNode.flags := bestNode.flags and not DT_NODE_OPEN;
bestNode.flags := bestNode.flags or DT_NODE_CLOSED;
// Get poly and tile.
// The API input has been cheked already, skip checking internal data.
bestRef := bestNode.id;
bestTile := nil;
bestPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(bestRef, @bestTile, @bestPoly);
// Place random locations on on ground.
if (bestPoly.getType() = DT_POLYTYPE_GROUND) then
begin
// Calc area of the polygon.
polyArea := 0.0;
for j := 2 to bestPoly.vertCount - 1 do
begin
va := @bestTile.verts[bestPoly.verts[0]*3];
vb := @bestTile.verts[bestPoly.verts[j-1]*3];
vc := @bestTile.verts[bestPoly.verts[j]*3];
polyArea := polyArea + dtTriArea2D(va,vb,vc);
end;
// Choose random polygon weighted by area, using reservoi sampling.
areaSum := areaSum + polyArea;
u := Random;
if (u*areaSum <= polyArea) then
begin
randomTile := bestTile;
randomPoly := bestPoly;
randomPolyRef := bestRef;
end;
end;
// Get parent poly and tile.
parentRef := 0;
parentTile := nil;
parentPoly := nil;
if (bestNode.pidx <> 0) then
parentRef := m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef <> 0) then
m_nav.getTileAndPolyByRefUnsafe(parentRef, @parentTile, @parentPoly);
i := bestPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
link := @bestTile.links[i];
neighbourRef := link.ref;
// Skip invalid neighbours and do not follow back to parent.
if (neighbourRef = 0) or (neighbourRef = parentRef) then
begin
i := bestTile.links[i].next;
continue;
end;
// Expand to neighbour
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
// Do not advance if the polygon is excluded by the filter.
if (not filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := bestTile.links[i].next;
continue;
end;
// Find edge and calc distance to the edge.
if (getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, @va3[0], @vb3[0]) = 0) then
begin
i := bestTile.links[i].next;
continue;
end;
// If the circle is not touching the next polygon, skip it.
distSqr := dtDistancePtSegSqr2D(centerPos, @va3[0], @vb3[0], @tseg);
if (distSqr > radiusSqr) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode := m_nodePool.getNode(neighbourRef);
if (neighbourNode = nil) then
begin
status := status or DT_OUT_OF_NODES;
i := bestTile.links[i].next;
continue;
end;
if (neighbourNode.flags and DT_NODE_CLOSED) <> 0 then
begin
i := bestTile.links[i].next;
continue;
end;
// Cost
if (neighbourNode.flags = 0) then
dtVlerp(@neighbourNode.pos, @va3[0], @vb3[0], 0.5);
total := bestNode.total + dtVdist(@bestNode.pos, @neighbourNode.pos);
// The node is already in open list and the new result is worse, skip.
if ((neighbourNode.flags and DT_NODE_OPEN) <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode.id := neighbourRef;
neighbourNode.flags := (neighbourNode.flags and not DT_NODE_CLOSED);
neighbourNode.pidx := m_nodePool.getNodeIdx(bestNode);
neighbourNode.total := total;
if (neighbourNode.flags and DT_NODE_OPEN) <> 0 then
begin
m_openList.modify(neighbourNode);
end
else
begin
neighbourNode.flags := DT_NODE_OPEN;
m_openList.push(neighbourNode);
end;
i := bestTile.links[i].next;
end;
end;
if (randomPoly = nil) then
Exit(DT_FAILURE);
// Randomly pick point on polygon.
v := @randomTile.verts[randomPoly.verts[0]*3];
dtVcopy(@verts[0*3],v);
for j := 1 to randomPoly.vertCount - 1 do
begin
v := @randomTile.verts[randomPoly.verts[j]*3];
dtVcopy(@verts[j*3],v);
end;
s := Random;
t := Random;
dtRandomPointInConvexPoly(@verts[0], randomPoly.vertCount, @areas[0], s, t, @pt[0]);
h := 0.0;
stat := getPolyHeight(randomPolyRef, @pt[0], @h);
if (dtStatusFailed(status)) then
Exit(stat);
pt[1] := h;
dtVcopy(randomPt, @pt[0]);
randomRef^ := randomPolyRef;
Result := DT_SUCCESS;
end;
//////////////////////////////////////////////////////////////////////////////////////////
/// @par
///
/// Uses the detail polygons to find the surface height. (Most accurate.)
///
/// @p pos does not have to be within the bounds of the polygon or navigation mesh.
///
/// See closestPointOnPolyBoundary() for a limited but faster option.
///
function TdtNavMeshQuery.closestPointOnPoly(ref: TdtPolyRef; pos, closest: PSingle; posOverPoly: PBoolean): TdtStatus;
var tile: PdtMeshTile; poly: PdtPoly; v0,v1: PSingle; d0,d1,u: Single; ip: Cardinal; pd: PdtPolyDetail;
verts: array [0..DT_VERTS_PER_POLYGON*3-1] of Single; edged: array [0..DT_VERTS_PER_POLYGON-1] of Single;
edget: array [0..DT_VERTS_PER_POLYGON-1] of Single; nv,i,j,k: Integer; dmin: Single; imin: Integer; va,vb: PSingle; t: PByte;
v: array [0..2] of PSingle; h: Single;
begin
//dtAssert(m_nav);
tile := nil;
poly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(ref, @tile, @poly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (tile = nil) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Off-mesh connections don't have detail polygons.
if (poly.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
v0 := @tile.verts[poly.verts[0]*3];
v1 := @tile.verts[poly.verts[1]*3];
d0 := dtVdist(pos, v0);
d1 := dtVdist(pos, v1);
u := d0 / (d0+d1);
dtVlerp(closest, v0, v1, u);
if (posOverPoly <> nil) then
posOverPoly^ := false;
Exit(DT_SUCCESS);
end;
ip := Cardinal(poly - tile.polys);
pd := @tile.detailMeshes[ip];
// Clamp point to be inside the polygon.
nv := poly.vertCount;
for i := 0 to nv - 1 do
dtVcopy(@verts[i*3], @tile.verts[poly.verts[i]*3]);
dtVcopy(closest, pos);
if (not dtDistancePtPolyEdgesSqr(pos, @verts[0], nv, @edged[0], @edget[0])) then
begin
// Point is outside the polygon, dtClamp to nearest edge.
dmin := MaxSingle;
imin := -1;
for i := 0 to nv - 1 do
begin
if (edged[i] < dmin) then
begin
dmin := edged[i];
imin := i;
end;
end;
va := @verts[imin*3];
vb := @verts[((imin+1) mod nv)*3];
dtVlerp(closest, va, vb, edget[imin]);
if (posOverPoly <> nil) then
posOverPoly^ := false;
end
else
begin
if (posOverPoly <> nil) then
posOverPoly^ := true;
end;
// Find height at the location.
for j := 0 to pd.triCount - 1 do
begin
t := @tile.detailTris[(pd.triBase+j)*4];
for k := 0 to 2 do
begin
if (t[k] < poly.vertCount) then
v[k] := @tile.verts[poly.verts[t[k]]*3]
else
v[k] := @tile.detailVerts[(pd.vertBase+(t[k]-poly.vertCount))*3];
end;
if (dtClosestHeightPointTriangle(pos, v[0], v[1], v[2], @h)) then
begin
closest[1] := h;
break;
end;
end;
Result := DT_SUCCESS;
end;
/// @par
///
/// Much faster than closestPointOnPoly().
///
/// If the provided position lies within the polygon's xz-bounds (above or below),
/// then @p pos and @p closest will be equal.
///
/// The height of @p closest will be the polygon boundary. The height detail is not used.
///
/// @p pos does not have to be within the bounds of the polybon or the navigation mesh.
///
function TdtNavMeshQuery.closestPointOnPolyBoundary(ref: TdtPolyRef; pos, closest: PSingle): TdtStatus;
var tile: PdtMeshTile; poly: PdtPoly; verts: array [0..DT_VERTS_PER_POLYGON*3-1] of Single;
edged: array [0..DT_VERTS_PER_POLYGON-1] of Single; edget: array [0..DT_VERTS_PER_POLYGON-1] of Single; nv,i: Integer;
inside: Boolean; dmin: Single; imin: Integer; va,vb: PSingle;
begin
//dtAssert(m_nav);
tile := nil;
poly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(ref, @tile, @poly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Collect vertices.
nv := 0;
for i := 0 to poly.vertCount - 1 do
begin
dtVcopy(@verts[nv*3], @tile.verts[poly.verts[i]*3]);
Inc(nv);
end;
inside := dtDistancePtPolyEdgesSqr(pos, @verts[0], nv, @edged[0], @edget[0]);
if (inside) then
begin
// Point is inside the polygon, return the point.
dtVcopy(closest, pos);
end
else
begin
// Point is outside the polygon, dtClamp to nearest edge.
dmin := MaxSingle;
imin := -1;
for i := 0 to nv - 1 do
begin
if (edged[i] < dmin) then
begin
dmin := edged[i];
imin := i;
end;
end;
va := @verts[imin*3];
vb := @verts[((imin+1) mod nv)*3];
dtVlerp(closest, va, vb, edget[imin]);
end;
Result := DT_SUCCESS;
end;
/// @par
///
/// Will return #DT_FAILURE if the provided position is outside the xz-bounds
/// of the polygon.
///
function TdtNavMeshQuery.getPolyHeight(ref: TdtPolyRef; pos, height: PSingle): TdtStatus;
var tile: PdtMeshTile; poly: PdtPoly; v0,v1: PSingle; d0,d1,u,h: Single; ip: Cardinal; pd: PdtPolyDetail; j,k: Integer; t: PByte;
v: array [0..2] of PSingle;
begin
//dtAssert(m_nav);
tile := nil;
poly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(ref, @tile, @poly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (poly.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
v0 := @tile.verts[poly.verts[0]*3];
v1 := @tile.verts[poly.verts[1]*3];
d0 := dtVdist2D(pos, v0);
d1 := dtVdist2D(pos, v1);
u := d0 / (d0+d1);
if (height <> nil) then
height^ := v0[1] + (v1[1] - v0[1]) * u;
Exit(DT_SUCCESS);
end
else
begin
ip := (poly - tile.polys);
pd := @tile.detailMeshes[ip];
for j := 0 to pd.triCount - 1 do
begin
t := @tile.detailTris[(pd.triBase+j)*4];
for k := 0 to 2 do
begin
if (t[k] < poly.vertCount) then
v[k] := @tile.verts[poly.verts[t[k]]*3]
else
v[k] := @tile.detailVerts[(pd.vertBase+(t[k]-poly.vertCount))*3];
end;
if (dtClosestHeightPointTriangle(pos, v[0], v[1], v[2], @h)) then
begin
if (height <> nil) then
height^ := h;
Exit(DT_SUCCESS);
end;
end;
end;
Result := (DT_FAILURE or DT_INVALID_PARAM);
end;
/// @par
///
/// @note If the search box does not intersect any polygons the search will
/// return #DT_SUCCESS, but @p nearestRef will be zero. So if in doubt, check
/// @p nearestRef before using @p nearestPt.
///
/// @warning This function is not suitable for large area searches. If the search
/// extents overlaps more than MAX_SEARCH (128) polygons it may return an invalid result.
///
function TdtNavMeshQuery.findNearestPoly(center, extents: PSingle; filter: TdtQueryFilter; nearestRef: PdtPolyRef; nearestPt: PSingle): TdtStatus;
const MAX_SEARCH = 128;
var polys: array [0..MAX_SEARCH-1] of TdtPolyRef; polyCount: Integer; nearest,ref: TdtPolyRef; nearestDistanceSqr: Single; i: Integer;
closestPtPoly,diff: array [0..2] of Single; posOverPoly: Boolean; d: Single; tile: PdtMeshTile; poly: PdtPoly;
begin
//dtAssert(m_nav);
nearestRef^ := 0;
// Get nearby polygons from proximity grid.
polyCount := 0;
if (dtStatusFailed(queryPolygons(center, extents, filter, @polys[0], @polyCount, MAX_SEARCH))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Find nearest polygon amongst the nearby polygons.
nearest := 0;
nearestDistanceSqr := MaxSingle;
for i := 0 to polyCount - 1 do
begin
ref := polys[i];
posOverPoly := false;
d := 0;
closestPointOnPoly(ref, center, @closestPtPoly[0], @posOverPoly);
// If a point is directly over a polygon and closer than
// climb height, favor that instead of straight line nearest point.
dtVsub(@diff[0], center, @closestPtPoly[0]);
if (posOverPoly) then
begin
tile := nil;
poly := nil;
m_nav.getTileAndPolyByRefUnsafe(polys[i], @tile, @poly);
d := Abs(diff[1]) - tile.header.walkableClimb;
d := IfThen(d > 0, d*d, 0);
end
else
begin
d := dtVlenSqr(@diff[0]);
end;
if (d < nearestDistanceSqr) then
begin
if (nearestPt <> nil) then
dtVcopy(nearestPt, @closestPtPoly[0]);
nearestDistanceSqr := d;
nearest := ref;
end;
end;
if (nearestRef <> nil) then
nearestRef^ := nearest;
Result := DT_SUCCESS;
end;
function TdtNavMeshQuery.queryPolygonsInTile(tile: PdtMeshTile; qmin, qmax: PSingle; filter: TdtQueryFilter;
polys: PdtPolyRef; maxPolys: Integer): Integer;
var node: PdtBVNode; &end: PdtBVNode; tbmin,tbmax: PSingle; qfac: Single; bmin,bmax: array [0..2] of Word; bminf,bmaxf: array [0..2] of Single;
minx,miny,minz,maxx,maxy,maxz: Single; base,ref: TdtPolyRef; i,j,n,escapeIndex: Integer; overlap,isLeafNode: Boolean; p: PdtPoly;
v: PSingle;
begin
//dtAssert(m_nav);
if (tile.bvTree <> nil) then
begin
node := @tile.bvTree[0];
&end := @tile.bvTree[tile.header.bvNodeCount];
tbmin := @tile.header.bmin[0];
tbmax := @tile.header.bmax[0];
qfac := tile.header.bvQuantFactor;
// Calculate quantized box
// dtClamp query box to world box.
minx := dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
miny := dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
minz := dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
maxx := dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
maxy := dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
maxz := dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
// Quantize
bmin[0] := Word(Trunc(qfac * minx)) and $fffe;
bmin[1] := Word(Trunc(qfac * miny)) and $fffe;
bmin[2] := Word(Trunc(qfac * minz)) and $fffe;
bmax[0] := Word(Trunc(qfac * maxx + 1)) or 1;
bmax[1] := Word(Trunc(qfac * maxy + 1)) or 1;
bmax[2] := Word(Trunc(qfac * maxz + 1)) or 1;
// Traverse tree
base := m_nav.getPolyRefBase(tile);
n := 0;
while (node < &end) do
begin
overlap := dtOverlapQuantBounds(@bmin[0], @bmax[0], @node.bmin, @node.bmax[0]);
isLeafNode := node.i >= 0;
if (isLeafNode and overlap) then
begin
ref := base or TdtPolyRef(node.i);
if (filter.passFilter(ref, tile, @tile.polys[node.i])) then
begin
if (n < maxPolys) then
begin
polys[n] := ref;
Inc(n);
end;
end;
end;
if (overlap or isLeafNode) then
Inc(node)
else
begin
escapeIndex := -node.i;
Inc(node, escapeIndex);
end;
end;
Exit(n);
end
else
begin
n := 0;
base := m_nav.getPolyRefBase(tile);
for i := 0 to tile.header.polyCount - 1 do
begin
p := @tile.polys[i];
// Do not return off-mesh connection polygons.
if (p.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
continue;
// Must pass filter
ref := base or TdtPolyRef(i);
if (not filter.passFilter(ref, tile, p)) then
continue;
// Calc polygon bounds.
v := @tile.verts[p.verts[0]*3];
dtVcopy(@bminf[0], v);
dtVcopy(@bmaxf[0], v);
for j := 1 to p.vertCount - 1 do
begin
v := @tile.verts[p.verts[j]*3];
dtVmin(@bminf[0], v);
dtVmax(@bmaxf[0], v);
end;
if (dtOverlapBounds(qmin,qmax, @bminf[0],@bmaxf[0])) then
begin
if (n < maxPolys) then
begin
polys[n] := ref;
Inc(n);
end;
end;
end;
Exit(n);
end;
end;
/// @par
///
/// If no polygons are found, the function will return #DT_SUCCESS with a
/// @p polyCount of zero.
///
/// If @p polys is too small to hold the entire result set, then the array will
/// be filled to capacity. The method of choosing which polygons from the
/// full set are included in the partial result set is undefined.
///
function TdtNavMeshQuery.queryPolygons(center, extents: PSingle; filter: TdtQueryFilter; polys: PdtPolyRef; polyCount: PInteger; maxPolys: Integer): TdtStatus;
const MAX_NEIS = 32;
var bmin,bmax: array [0..2] of Single; minx, miny, maxx, maxy: Integer; neis: array [0..MAX_NEIS-1] of PdtMeshTile; n,y,x,j,nneis: Integer;
begin
//dtAssert(m_nav);
dtVsub(@bmin[0], center, extents);
dtVadd(@bmax[0], center, extents);
// Find tiles the query touches.
m_nav.calcTileLoc(@bmin[0], @minx, @miny);
m_nav.calcTileLoc(@bmax[0], @maxx, @maxy);
n := 0;
for y := miny to maxy do
begin
for x := minx to maxx do
begin
nneis := m_nav.getTilesAt(x,y,@neis[0],MAX_NEIS);
for j := 0 to nneis - 1 do
begin
Inc(n, queryPolygonsInTile(neis[j], @bmin[0], @bmax[0], filter, polys+n, maxPolys-n));
if (n >= maxPolys) then
begin
polyCount^ := n;
Exit(DT_SUCCESS or DT_BUFFER_TOO_SMALL);
end;
end;
end;
end;
polyCount^ := n;
Result := DT_SUCCESS;
end;
/// @par
///
/// If the end polygon cannot be reached through the navigation graph,
/// the last polygon in the path will be the nearest the end polygon.
///
/// If the path array is to small to hold the full result, it will be filled as
/// far as possible from the start polygon toward the end polygon.
///
/// The start and end positions are used to calculate traversal costs.
/// (The y-values impact the result.)
///
function TdtNavMeshQuery.findPath(startRef, endRef: TdtPolyRef;
startPos, endPos: PSingle;
filter: TdtQueryFilter;
path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
var startNode,lastBestNode,bestNode: PdtNode; lastBestNodeCost: Single; status: TdtStatus; bestRef,parentRef,neighbourRef: TdtPolyRef;
bestTile,parentTile,neighbourTile: PdtMeshTile; bestPoly,parentPoly,neighbourPoly: PdtPoly; i: Cardinal; crossSide: Byte;
neighbourNode,prev,node,next: PdtNode; cost,heuristic,curCost,endCost,total: Single; n: Integer;
begin
Assert(m_nav <> nil);
Assert(m_nodePool <> nil);
Assert(m_openList <> nil);
pathCount^ := 0;
if (startRef = 0) or (endRef = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (maxPath = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Validate input
if (not m_nav.isValidPolyRef(startRef) or not m_nav.isValidPolyRef(endRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (startRef = endRef) then
begin
path[0] := startRef;
pathCount^ := 1;
Exit(DT_SUCCESS);
end;
m_nodePool.clear();
m_openList.clear();
startNode := m_nodePool.getNode(startRef);
dtVcopy(@startNode.pos, startPos);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := dtVdist(startPos, endPos) * H_SCALE;
startNode.id := startRef;
startNode.flags := DT_NODE_OPEN;
m_openList.push(startNode);
lastBestNode := startNode;
lastBestNodeCost := startNode.total;
status := DT_SUCCESS;
while (not m_openList.empty()) do
begin
// Remove node from open list and put it in closed list.
bestNode := m_openList.pop();
bestNode.flags := bestNode.flags and not DT_NODE_OPEN;
bestNode.flags := bestNode.flags or DT_NODE_CLOSED;
// Reached the goal, stop searching.
if (bestNode.id = endRef) then
begin
lastBestNode := bestNode;
break;
end;
// Get current poly and tile.
// The API input has been cheked already, skip checking internal data.
bestRef := bestNode.id;
bestTile := nil;
bestPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(bestRef, @bestTile, @bestPoly);
// Get parent poly and tile.
parentRef := 0;
parentTile := nil;
parentPoly := nil;
if (bestNode.pidx <> 0) then
parentRef := m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef <> 0) then
m_nav.getTileAndPolyByRefUnsafe(parentRef, @parentTile, @parentPoly);
i := bestPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
neighbourRef := bestTile.links[i].ref;
// Skip invalid ids and do not expand back to where we came from.
if (neighbourRef = 0) or (neighbourRef = parentRef) then
begin
i := bestTile.links[i].next;
continue;
end;
// Get neighbour poly and tile.
// The API input has been cheked already, skip checking internal data.
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
if (not filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := bestTile.links[i].next;
continue;
end;
// deal explicitly with crossing tile boundaries
crossSide := 0;
if (bestTile.links[i].side <> $ff) then
crossSide := bestTile.links[i].side shr 1;
// get the node
neighbourNode := m_nodePool.getNode(neighbourRef, crossSide);
if (neighbourNode = nil) then
begin
status := status or DT_OUT_OF_NODES;
begin
i := bestTile.links[i].next;
continue;
end;
end;
// If the node is visited the first time, calculate node position.
if (neighbourNode.flags = 0) then
begin
getEdgeMidPoint(bestRef, bestPoly, bestTile,
neighbourRef, neighbourPoly, neighbourTile,
@neighbourNode.pos);
end;
// Calculate cost and heuristic.
cost := 0;
heuristic := 0;
// Special case for last node.
if (neighbourRef = endRef) then
begin
// Cost
curCost := filter.getCost(@bestNode.pos, @neighbourNode.pos,
parentRef, parentTile, parentPoly,
bestRef, bestTile, bestPoly,
neighbourRef, neighbourTile, neighbourPoly);
endCost := filter.getCost(@neighbourNode.pos, endPos,
bestRef, bestTile, bestPoly,
neighbourRef, neighbourTile, neighbourPoly,
0, nil, nil);
cost := bestNode.cost + curCost + endCost;
heuristic := 0;
end
else
begin
// Cost
curCost := filter.getCost(@bestNode.pos, @neighbourNode.pos,
parentRef, parentTile, parentPoly,
bestRef, bestTile, bestPoly,
neighbourRef, neighbourTile, neighbourPoly);
cost := bestNode.cost + curCost;
heuristic := dtVdist(@neighbourNode.pos, endPos)*H_SCALE;
end;
total := cost + heuristic;
// The node is already in open list and the new result is worse, skip.
if (neighbourNode.flags and DT_NODE_OPEN <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
continue;
end;
// The node is already visited and process, and the new result is worse, skip.
if (neighbourNode.flags and DT_NODE_CLOSED <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
continue;
end;
// Add or update the node.
neighbourNode.pidx := m_nodePool.getNodeIdx(bestNode);
neighbourNode.id := neighbourRef;
neighbourNode.flags := (neighbourNode.flags and not DT_NODE_CLOSED);
neighbourNode.cost := cost;
neighbourNode.total := total;
if (neighbourNode.flags and DT_NODE_OPEN <> 0) then
begin
// Already in open, update node location.
m_openList.modify(neighbourNode);
end
else
begin
// Put the node in open list.
neighbourNode.flags := neighbourNode.flags or DT_NODE_OPEN;
m_openList.push(neighbourNode);
end;
// Update nearest node to target so far.
if (heuristic < lastBestNodeCost) then
begin
lastBestNodeCost := heuristic;
lastBestNode := neighbourNode;
end;
i := bestTile.links[i].next;
end;
end;
if (lastBestNode.id <> endRef) then
status := status or DT_PARTIAL_RESULT;
// Reverse the path.
prev := nil;
node := lastBestNode;
repeat
next := m_nodePool.getNodeAtIdx(node.pidx);
node.pidx := m_nodePool.getNodeIdx(prev);
prev := node;
node := next;
until (node = nil);
// Store path
node := prev;
n := 0;
repeat
path[n] := node.id;
Inc(n);
if (n >= maxPath) then
begin
status := status or DT_BUFFER_TOO_SMALL;
break;
end;
node := m_nodePool.getNodeAtIdx(node.pidx);
until (node = nil);
pathCount^ := n;
Result := status;
end;
/// @par
///
/// @warning Calling any non-slice methods before calling finalizeSlicedFindPath()
/// or finalizeSlicedFindPathPartial() may result in corrupted data!
///
/// The @p filter pointer is stored and used for the duration of the sliced
/// path query.
///
function TdtNavMeshQuery.initSlicedFindPath(startRef, endRef: TdtPolyRef;
startPos, endPos: PSingle;
filter: TdtQueryFilter; options: Integer = 0): TdtStatus;
var tile: PdtMeshTile; agentRadius: Single; startNode: PdtNode;
begin
Assert(m_nav <> nil);
Assert(m_nodePool <> nil);
Assert(m_openList <> nil);
// Init path state.
FillChar(m_query, sizeof(TdtQueryData), 0);
m_query.status := DT_FAILURE;
m_query.startRef := startRef;
m_query.endRef := endRef;
dtVcopy(@m_query.startPos[0], startPos);
dtVcopy(@m_query.endPos[0], endPos);
m_query.filter := filter;
m_query.options := options;
m_query.raycastLimitSqr := MaxSingle;
if (startRef = 0) or (endRef = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Validate input
if (not m_nav.isValidPolyRef(startRef) or not m_nav.isValidPolyRef(endRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// trade quality with performance?
if (options and Byte(DT_FINDPATH_ANY_ANGLE)) <> 0 then
begin
// limiting to several times the character radius yields nice results. It is not sensitive
// so it is enough to compute it from the first tile.
tile := m_nav.getTileByRef(startRef);
agentRadius := tile.header.walkableRadius;
m_query.raycastLimitSqr := Sqr(agentRadius * DT_RAY_CAST_LIMIT_PROPORTIONS);
end;
if (startRef = endRef) then
begin
m_query.status := DT_SUCCESS;
Exit(DT_SUCCESS);
end;
m_nodePool.clear();
m_openList.clear();
startNode := m_nodePool.getNode(startRef);
dtVcopy(@startNode.pos, startPos);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := dtVdist(startPos, endPos) * H_SCALE;
startNode.id := startRef;
startNode.flags := DT_NODE_OPEN;
m_openList.push(startNode);
m_query.status := DT_IN_PROGRESS;
m_query.lastBestNode := startNode;
m_query.lastBestNodeCost := startNode.total;
Result := m_query.status;
end;
function TdtNavMeshQuery.updateSlicedFindPath(maxIter: Integer; doneIters: PInteger): TdtStatus;
var rayHit: TdtRaycastHit; iter: Integer; bestNode: PdtNode; details: TdtStatus;
bestRef,parentRef,grandpaRef,neighbourRef: TdtPolyRef; bestTile,parentTile,neighbourTile: PdtMeshTile; bestPoly,parentPoly,neighbourPoly: PdtPoly; parentNode,neighbourNode: PdtNode;
invalidParent,tryLOS: Boolean; i: Cardinal; cost,heuristic,curCost,endCost,total: Single; foundShortCut: Boolean;
begin
if (not dtStatusInProgress(m_query.status)) then
Exit(m_query.status);
// Make sure the request is still valid.
if (not m_nav.isValidPolyRef(m_query.startRef) or not m_nav.isValidPolyRef(m_query.endRef)) then
begin
m_query.status := DT_FAILURE;
Exit(DT_FAILURE);
end;
rayHit.maxPath := 0;
iter := 0;
while (iter < maxIter) and (not m_openList.empty()) do
begin
Inc(iter);
// Remove node from open list and put it in closed list.
bestNode := m_openList.pop();
bestNode.flags := bestNode.flags and not DT_NODE_OPEN;
bestNode.flags := bestNode.flags or DT_NODE_CLOSED;
// Reached the goal, stop searching.
if (bestNode.id = m_query.endRef) then
begin
m_query.lastBestNode := bestNode;
details := m_query.status and DT_STATUS_DETAIL_MASK;
m_query.status := DT_SUCCESS or details;
if (doneIters <> nil) then
doneIters^ := iter;
Exit(m_query.status);
end;
// Get current poly and tile.
// The API input has been cheked already, skip checking internal data.
bestRef := bestNode.id;
bestTile := nil;
bestPoly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(bestRef, @bestTile, @bestPoly))) then
begin
// The polygon has disappeared during the sliced query, fail.
m_query.status := DT_FAILURE;
if (doneIters <> nil) then
doneIters^ := iter;
Exit(m_query.status);
end;
// Get parent and grand parent poly and tile.
parentRef := 0; grandpaRef := 0;
parentTile := nil;
parentPoly := nil;
parentNode := nil;
if (bestNode.pidx <> 0) then
begin
parentNode := m_nodePool.getNodeAtIdx(bestNode.pidx);
parentRef := parentNode.id;
if (parentNode.pidx <> 0) then
grandpaRef := m_nodePool.getNodeAtIdx(parentNode.pidx).id;
end;
if (parentRef <> 0) then
begin
invalidParent := dtStatusFailed(m_nav.getTileAndPolyByRef(parentRef, @parentTile, @parentPoly));
if (invalidParent or ((grandpaRef <> 0) and not m_nav.isValidPolyRef(grandpaRef)) ) then
begin
// The polygon has disappeared during the sliced query, fail.
m_query.status := DT_FAILURE;
if (doneIters <> nil) then
doneIters^ := iter;
Exit(m_query.status);
end;
end;
// decide whether to test raycast to previous nodes
tryLOS := false;
if (m_query.options and Byte(DT_FINDPATH_ANY_ANGLE)) <> 0 then
begin
if ((parentRef <> 0) and (dtVdistSqr(@parentNode.pos, @bestNode.pos) < m_query.raycastLimitSqr)) then
tryLOS := true;
end;
i := bestPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
neighbourRef := bestTile.links[i].ref;
// Skip invalid ids and do not expand back to where we came from.
if (neighbourRef = 0) or (neighbourRef = parentRef) then
begin
i := bestTile.links[i].next;
Continue;
end;
// Get neighbour poly and tile.
// The API input has been cheked already, skip checking internal data.
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
if (not m_query.filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := bestTile.links[i].next;
Continue;
end;
// get the neighbor node
neighbourNode := m_nodePool.getNode(neighbourRef, 0);
if (neighbourNode = nil) then
begin
m_query.status := m_query.status or DT_OUT_OF_NODES;
i := bestTile.links[i].next;
Continue;
end;
// do not expand to nodes that were already visited from the same parent
if (neighbourNode.pidx <> 0) and (neighbourNode.pidx = bestNode.pidx) then
begin
i := bestTile.links[i].next;
Continue;
end;
// If the node is visited the first time, calculate node position.
if (neighbourNode.flags = 0) then
begin
getEdgeMidPoint(bestRef, bestPoly, bestTile,
neighbourRef, neighbourPoly, neighbourTile,
@neighbourNode.pos);
end;
// Calculate cost and heuristic.
cost := 0;
heuristic := 0;
// raycast parent
foundShortCut := false;
rayHit.pathCost := 0; rayHit.t := 0;
if (tryLOS) then
begin
raycast(parentRef, @parentNode.pos, @neighbourNode.pos, m_query.filter, Byte(DT_RAYCAST_USE_COSTS), @rayHit, grandpaRef);
foundShortCut := rayHit.t >= 1.0;
end;
// update move cost
if (foundShortCut) then
begin
// shortcut found using raycast. Using shorter cost instead
cost := parentNode.cost + rayHit.pathCost;
end
else
begin
// No shortcut found.
curCost := m_query.filter.getCost(@bestNode.pos, @neighbourNode.pos,
parentRef, parentTile, parentPoly,
bestRef, bestTile, bestPoly,
neighbourRef, neighbourTile, neighbourPoly);
cost := bestNode.cost + curCost;
end;
// Special case for last node.
if (neighbourRef = m_query.endRef) then
begin
endCost := m_query.filter.getCost(@neighbourNode.pos, @m_query.endPos[0],
bestRef, bestTile, bestPoly,
neighbourRef, neighbourTile, neighbourPoly,
0, nil, nil);
cost := cost + endCost;
heuristic := 0;
end
else
begin
heuristic := dtVdist(@neighbourNode.pos, @m_query.endPos[0])*H_SCALE;
end;
total := cost + heuristic;
// The node is already in open list and the new result is worse, skip.
if (neighbourNode.flags and DT_NODE_OPEN <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
Continue;
end;
// The node is already visited and process, and the new result is worse, skip.
if (neighbourNode.flags and DT_NODE_CLOSED <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
Continue;
end;
// Add or update the node.
if foundShortCut then neighbourNode.pidx := bestNode.pidx else neighbourNode.pidx := m_nodePool.getNodeIdx(bestNode);
neighbourNode.id := neighbourRef;
neighbourNode.flags := (neighbourNode.flags and not (DT_NODE_CLOSED or DT_NODE_PARENT_DETACHED));
neighbourNode.cost := cost;
neighbourNode.total := total;
if (foundShortCut) then
neighbourNode.flags := (neighbourNode.flags or DT_NODE_PARENT_DETACHED);
if (neighbourNode.flags and DT_NODE_OPEN <> 0) then
begin
// Already in open, update node location.
m_openList.modify(neighbourNode);
end
else
begin
// Put the node in open list.
neighbourNode.flags := neighbourNode.flags or DT_NODE_OPEN;
m_openList.push(neighbourNode);
end;
// Update nearest node to target so far.
if (heuristic < m_query.lastBestNodeCost) then
begin
m_query.lastBestNodeCost := heuristic;
m_query.lastBestNode := neighbourNode;
end;
i := bestTile.links[i].next;
end;
end;
// Exhausted all nodes, but could not find path.
if (m_openList.empty()) then
begin
details := m_query.status and DT_STATUS_DETAIL_MASK;
m_query.status := DT_SUCCESS or details;
end;
if (doneIters <> nil) then
doneIters^ := iter;
Result := m_query.status;
end;
function TdtNavMeshQuery.finalizeSlicedFindPath(path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
var n,m: Integer; prev,node,next: PdtNode; prevRay,nextRay: Integer; status,details: TdtStatus; t: Single; normal: array [0..2] of Single;
begin
pathCount^ := 0;
if (dtStatusFailed(m_query.status)) then
begin
// Reset query.
FillChar(m_query, sizeof(TdtQueryData), 0);
Exit(DT_FAILURE);
end;
n := 0;
if (m_query.startRef = m_query.endRef) then
begin
// Special case: the search starts and ends at same poly.
path[n] := m_query.startRef;
Inc(n);
end
else
begin
// Reverse the path.
Assert(m_query.lastBestNode <> nil);
if (m_query.lastBestNode.id <> m_query.endRef) then
m_query.status := m_query.status or DT_PARTIAL_RESULT;
prev := nil;
node := m_query.lastBestNode;
prevRay := 0;
repeat
next := m_nodePool.getNodeAtIdx(node.pidx);
node.pidx := m_nodePool.getNodeIdx(prev);
prev := node;
nextRay := node.flags and DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)
node.flags := (node.flags and not DT_NODE_PARENT_DETACHED) or prevRay; // and store it in the reversed path's node
prevRay := nextRay;
node := next;
until (node = nil);
// Store path
node := prev;
repeat
next := m_nodePool.getNodeAtIdx(node.pidx);
status := 0;
if (node.flags and DT_NODE_PARENT_DETACHED) <> 0 then
begin
status := raycast(node.id, @node.pos, @next.pos, m_query.filter, @t, @normal[0], path+n, @m, maxPath-n);
Inc(n, m);
// raycast ends on poly boundary and the path might include the next poly boundary.
if (path[n-1] = next.id) then
Dec(n); // remove to avoid duplicates
end
else
begin
path[n] := node.id;
Inc(n);
if (n >= maxPath) then
status := DT_BUFFER_TOO_SMALL;
end;
if (status and DT_STATUS_DETAIL_MASK) <> 0 then
begin
m_query.status := m_query.status or (status and DT_STATUS_DETAIL_MASK);
break;
end;
node := next;
until (node = nil);
end;
details := m_query.status and DT_STATUS_DETAIL_MASK;
// Reset query.
FillChar(m_query, sizeof(TdtQueryData), 0);
pathCount^ := n;
Result := DT_SUCCESS or details;
end;
function TdtNavMeshQuery.finalizeSlicedFindPathPartial(existing: PdtPolyRef; existingSize: Integer;
path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
var
n, i, prevRay, nextRay, m: Integer; prev, node, next: PdtNode; status, details: TdtStatus; t: Single; normal: array [0..2] of Single;
begin
pathCount^ := 0;
if (existingSize = 0) then
begin
Exit(DT_FAILURE);
end;
if (dtStatusFailed(m_query.status)) then
begin
// Reset query.
FillChar(m_query, sizeof(TdtQueryData), 0);
Exit(DT_FAILURE);
end;
n := 0;
if (m_query.startRef = m_query.endRef) then
begin
// Special case: the search starts and ends at same poly.
path[n] := m_query.startRef;
Inc(n);
end
else
begin
// Find furthest existing node that was visited.
prev := nil;
node := nil;
for i := existingSize-1 downto 0 do
begin
m_nodePool.findNodes(existing[i], &node, 1);
if (node <> nil) then
break;
end;
if (node = nil) then
begin
m_query.status := m_query.status or DT_PARTIAL_RESULT;
Assert(m_query.lastBestNode <> nil);
node := m_query.lastBestNode;
end;
// Reverse the path.
prevRay := 0;
repeat
next := m_nodePool.getNodeAtIdx(node.pidx);
node.pidx := m_nodePool.getNodeIdx(prev);
prev := node;
nextRay := node.flags and DT_NODE_PARENT_DETACHED; // keep track of whether parent is not adjacent (i.e. due to raycast shortcut)
node.flags := (node.flags and not DT_NODE_PARENT_DETACHED) or prevRay; // and store it in the reversed path's node
prevRay := nextRay;
node := next;
until (node = nil);
// Store path
node := prev;
repeat
next := m_nodePool.getNodeAtIdx(node.pidx);
status := 0;
if (node.flags and DT_NODE_PARENT_DETACHED) <> 0 then
begin
status := raycast(node.id, @node.pos[0], @next.pos[0], m_query.filter, @t, @normal[0], path+n, @m, maxPath-n);
Inc(n, m);
// raycast ends on poly boundary and the path might include the next poly boundary.
if (path[n-1] = next.id) then
Dec(n); // remove to avoid duplicates
end
else
begin
path[n] := node.id;
Inc(n);
if (n >= maxPath) then
status := DT_BUFFER_TOO_SMALL;
end;
if (status and DT_STATUS_DETAIL_MASK) <> 0 then
begin
m_query.status := m_query.status or (status and DT_STATUS_DETAIL_MASK);
break;
end;
node := next;
until (node = nil);
end;
details := m_query.status and DT_STATUS_DETAIL_MASK;
// Reset query.
FillChar(m_query, sizeof(TdtQueryData), 0);
pathCount^ := n;
Result := DT_SUCCESS or details;
end;
function TdtNavMeshQuery.appendVertex(pos: PSingle; flags: Integer; ref: TdtPolyRef;
straightPath: PSingle; straightPathFlags: PByte; straightPathRefs: PdtPolyRef;
straightPathCount: PInteger; maxStraightPath: Integer): TdtStatus;
begin
if (straightPathCount^ > 0) and dtVequal(@straightPath[((straightPathCount^)-1)*3], pos) then
begin
// The vertices are equal, update flags and poly.
if (straightPathFlags <> nil) then
straightPathFlags[(straightPathCount^)-1] := flags;
if (straightPathRefs <> nil) then
straightPathRefs[(straightPathCount^)-1] := ref;
end
else
begin
// Append new vertex.
dtVcopy(@straightPath[(straightPathCount^)*3], pos);
if (straightPathFlags <> nil) then
straightPathFlags[(straightPathCount^)] := flags;
if (straightPathRefs <> nil) then
straightPathRefs[(straightPathCount^)] := ref;
Inc(straightPathCount^);
// If reached end of path or there is no space to append more vertices, return.
if (flags = Byte(DT_STRAIGHTPATH_END)) or (( straightPathCount^) >= maxStraightPath) then
begin
Exit(DT_SUCCESS or IfThen(((straightPathCount^) >= maxStraightPath), DT_BUFFER_TOO_SMALL, 0));
end;
end;
Result := DT_IN_PROGRESS;
end;
function TdtNavMeshQuery.appendPortals(startIdx, endIdx: Integer; endPos: PSingle; path: PdtPolyRef;
straightPath: PSingle; straightPathFlags: PByte; straightPathRefs: PdtPolyRef;
straightPathCount: PInteger; maxStraightPath, options: Integer): TdtStatus;
var startPos: PSingle; stat: TdtStatus; i: Integer; from,&to: TdtPolyRef; fromTile,toTile: PdtMeshTile; fromPoly,toPoly: PdtPoly;
left,right,pt: array [0..2] of Single; s,t: Single;
begin
startPos := @straightPath[(straightPathCount^-1)*3];
// Append or update last vertex
stat := 0;
for i := startIdx to endIdx - 1 do
begin
// Calculate portal
from := path[i];
fromTile := nil;
fromPoly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(from, @fromTile, @fromPoly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
&to := path[i+1];
toTile := nil;
toPoly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(&to, @toTile, @toPoly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, &to, toPoly, toTile, @left[0], @right[0]))) then
break;
if (options and Byte(DT_STRAIGHTPATH_AREA_CROSSINGS)) <> 0 then
begin
// Skip intersection if only area crossings are requested.
if (fromPoly.getArea() = toPoly.getArea()) then
continue;
end;
// Append intersection
if (dtIntersectSegSeg2D(startPos, endPos, @left[0], @right[0], @s, @t)) then
begin
dtVlerp(@pt[0], @left[0],@right[0], t);
stat := appendVertex(@pt[0], 0, path[i+1],
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
end;
end;
Result := DT_IN_PROGRESS;
end;
/// @par
///
/// This method peforms what is often called 'string pulling'.
///
/// The start position is clamped to the first polygon in the path, and the
/// end position is clamped to the last. So the start and end positions should
/// normally be within or very near the first and last polygons respectively.
///
/// The returned polygon references represent the reference id of the polygon
/// that is entered at the associated path position. The reference id associated
/// with the end point will always be zero. This allows, for example, matching
/// off-mesh link points to their representative polygons.
///
/// If the provided result buffers are too small for the entire result set,
/// they will be filled as far as possible from the start toward the end
/// position.
///
function TdtNavMeshQuery.findStraightPath(startPos, endPos: PSingle;
path: PdtPolyRef; pathSize: Integer;
straightPath: PSingle; straightPathFlags: PByte; straightPathRefs: PdtPolyRef;
straightPathCount: PInteger; maxStraightPath: Integer; options: Integer = 0): TdtStatus;
var stat: TdtStatus; closestStartPos,closestEndPos,portalApex,portalLeft,portalRight: array [0..2] of Single;
apexIndex,leftIndex,rightIndex: Integer; leftPolyType,rightPolyType: Byte; leftPolyRef,rightPolyRef: TdtPolyRef; i: Integer;
left,right: array [0..2] of Single; fromType,toType: Byte; t: Single; flags: Byte; ref: TdtPolyRef;
begin
//dtAssert(m_nav);
straightPathCount^ := 0;
if (maxStraightPath = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (path[0] = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
stat := 0;
// TODO: Should this be callers responsibility?
if (dtStatusFailed(closestPointOnPolyBoundary(path[0], startPos, @closestStartPos[0]))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (dtStatusFailed(closestPointOnPolyBoundary(path[pathSize-1], endPos, @closestEndPos[0]))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Add start point.
stat := appendVertex(@closestStartPos[0], Byte(DT_STRAIGHTPATH_START), path[0],
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
if (pathSize > 1) then
begin
dtVcopy(@portalApex[0], @closestStartPos[0]);
dtVcopy(@portalLeft[0], @portalApex[0]);
dtVcopy(@portalRight[0], @portalApex[0]);
apexIndex := 0;
leftIndex := 0;
rightIndex := 0;
leftPolyType := 0;
rightPolyType := 0;
leftPolyRef := path[0];
rightPolyRef := path[0];
i := 0;
while (i < pathSize) do
begin
if (i+1 < pathSize) then
begin
// Next portal.
if (dtStatusFailed(getPortalPoints(path[i], path[i+1], @left[0], @right[0], @fromType, @toType))) then
begin
// Failed to get portal points, in practice this means that path[i+1] is invalid polygon.
// Clamp the end point to path[i], and return the path so far.
if (dtStatusFailed(closestPointOnPolyBoundary(path[i], endPos, @closestEndPos[0]))) then
begin
// This should only happen when the first polygon is invalid.
Exit(DT_FAILURE or DT_INVALID_PARAM);
end;
// Apeend portals along the current straight path segment.
if (options and (Byte(DT_STRAIGHTPATH_AREA_CROSSINGS) or Byte(DT_STRAIGHTPATH_ALL_CROSSINGS)) <> 0) then
begin
stat := appendPortals(apexIndex, i, @closestEndPos[0], path,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath, options);
end;
stat := appendVertex(@closestEndPos[0], 0, path[i],
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath);
Exit(DT_SUCCESS or DT_PARTIAL_RESULT or IfThen((straightPathCount^ >= maxStraightPath), DT_BUFFER_TOO_SMALL, 0));
end;
// If starting really close the portal, advance.
if (i = 0) then
begin
if (dtDistancePtSegSqr2D(@portalApex[0], @left[0], @right[0], @t) < Sqr(0.001)) then
begin
Inc(i);
continue;
end;
end;
end
else
begin
// End of the path.
dtVcopy(@left[0], @closestEndPos[0]);
dtVcopy(@right[0], @closestEndPos[0]);
fromType := DT_POLYTYPE_GROUND; toType := DT_POLYTYPE_GROUND;
end;
// Right vertex.
if (dtTriArea2D(@portalApex[0], @portalRight[0], @right[0]) <= 0.0) then
begin
if (dtVequal(@portalApex[0], @portalRight[0]) or (dtTriArea2D(@portalApex[0], @portalLeft[0], @right[0]) > 0.0)) then
begin
dtVcopy(@portalRight[0], @right[0]);
if (i+1 < pathSize) then rightPolyRef := path[i+1] else rightPolyRef := 0;
rightPolyType := toType;
rightIndex := i;
end
else
begin
// Append portals along the current straight path segment.
if (options and (Byte(DT_STRAIGHTPATH_AREA_CROSSINGS) or Byte(DT_STRAIGHTPATH_ALL_CROSSINGS)) <> 0) then
begin
stat := appendPortals(apexIndex, leftIndex, @portalLeft[0], path,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath, options);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
end;
dtVcopy(@portalApex[0], @portalLeft[0]);
apexIndex := leftIndex;
flags := 0;
if (leftPolyRef = 0) then
flags := Byte(DT_STRAIGHTPATH_END)
else if (leftPolyType = DT_POLYTYPE_OFFMESH_CONNECTION) then
flags := Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION);
ref := leftPolyRef;
// Append or update vertex
stat := appendVertex(@portalApex[0], flags, ref,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
dtVcopy(@portalLeft[0], @portalApex[0]);
dtVcopy(@portalRight[0], @portalApex[0]);
leftIndex := apexIndex;
rightIndex := apexIndex;
// Restart
i := apexIndex;
Inc(i);
continue;
end;
end;
// Left vertex.
if (dtTriArea2D(@portalApex[0], @portalLeft[0], @left[0]) >= 0.0) then
begin
if (dtVequal(@portalApex[0], @portalLeft[0])) or (dtTriArea2D(@portalApex[0], @portalRight[0], @left[0]) < 0.0) then
begin
dtVcopy(@portalLeft[0], @left[0]);
if (i+1 < pathSize) then leftPolyRef := path[i+1] else leftPolyRef := 0;
leftPolyType := toType;
leftIndex := i;
end
else
begin
// Append portals along the current straight path segment.
if (options and (Byte(DT_STRAIGHTPATH_AREA_CROSSINGS) or Byte(DT_STRAIGHTPATH_ALL_CROSSINGS)) <> 0) then
begin
stat := appendPortals(apexIndex, rightIndex, @portalRight[0], path,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath, options);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
end;
dtVcopy(@portalApex[0], @portalRight[0]);
apexIndex := rightIndex;
flags := 0;
if (rightPolyRef = 0) then
flags := Byte(DT_STRAIGHTPATH_END)
else if (rightPolyType = DT_POLYTYPE_OFFMESH_CONNECTION) then
flags := Byte(DT_STRAIGHTPATH_OFFMESH_CONNECTION);
ref := rightPolyRef;
// Append or update vertex
stat := appendVertex(@portalApex[0], flags, ref,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
dtVcopy(@portalLeft[0], @portalApex[0]);
dtVcopy(@portalRight[0], @portalApex[0]);
leftIndex := apexIndex;
rightIndex := apexIndex;
// Restart
i := apexIndex;
Inc(i);
continue;
end;
end;
Inc(i);
end;
// Append portals along the current straight path segment.
if (options and (Byte(DT_STRAIGHTPATH_AREA_CROSSINGS) or Byte(DT_STRAIGHTPATH_ALL_CROSSINGS)) <> 0) then
begin
stat := appendPortals(apexIndex, pathSize-1, @closestEndPos[0], path,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath, options);
if (stat <> DT_IN_PROGRESS) then
Exit(stat);
end;
end;
stat := appendVertex(@closestEndPos[0], Byte(DT_STRAIGHTPATH_END), 0,
straightPath, straightPathFlags, straightPathRefs,
straightPathCount, maxStraightPath);
Result := DT_SUCCESS or IfThen((straightPathCount^ >= maxStraightPath), DT_BUFFER_TOO_SMALL, 0);
end;
/// @par
///
/// This method is optimized for small delta movement and a small number of
/// polygons. If used for too great a distance, the result set will form an
/// incomplete path.
///
/// @p resultPos will equal the @p endPos if the end is reached.
/// Otherwise the closest reachable position will be returned.
///
/// @p resultPos is not projected onto the surface of the navigation
/// mesh. Use #getPolyHeight if this is needed.
///
/// This method treats the end position in the same manner as
/// the #raycast method. (As a 2D point.) See that method's documentation
/// for details.
///
/// If the @p visited array is too small to hold the entire result set, it will
/// be filled as far as possible from the start position toward the end
/// position.
///
function TdtNavMeshQuery.moveAlongSurface(startRef: TdtPolyRef; startPos, endPos: PSingle;
filter: TdtQueryFilter;
resultPos: PSingle; visited: PdtPolyRef; visitedCount: PInteger; maxVisitedSize: Integer): TdtStatus;
const MAX_STACK = 48;
const MAX_NEIS = 8;
var status: TdtStatus; stack: array [0..MAX_STACK-1] of PdtNode; nstack,i,j,nverts: Integer; startNode,bestNode,curNode: PdtNode;
bestPos,searchPos: array [0..2] of Single; bestDist,searchRadSqr: Single; verts: array [0..DT_VERTS_PER_POLYGON*3-1] of Single;
curRef: TdtPolyRef; curTile,neiTile: PdtMeshTile; curPoly,neiPoly: PdtPoly; nneis: Integer; neis: array [0..MAX_NEIS-1] of TdtPolyRef; k: Cardinal;
link: PdtLink; idx: Cardinal; ref: TdtPolyRef; vj,vi: PSingle; tseg,distSqr: Single; neighbourNode: PdtNode; n: Integer;
prev,node,next: PdtNode;
begin
//dtAssert(m_nav);
//dtAssert(m_tinyNodePool);
visitedCount^ := 0;
// Validate input
if (startRef = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (not m_nav.isValidPolyRef(startRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
status := DT_SUCCESS;
nstack := 0;
m_tinyNodePool.clear();
startNode := m_tinyNodePool.getNode(startRef);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := 0;
startNode.id := startRef;
startNode.flags := DT_NODE_CLOSED;
stack[nstack] := startNode;
Inc(nstack);
bestDist := MaxSingle;
bestNode := nil;
dtVcopy(@bestPos[0], startPos);
// Search constraints F
dtVlerp(@searchPos[0], startPos, endPos, 0.5);
searchRadSqr := Sqr(dtVdist(startPos, endPos)/2.0 + 0.001);
while (nstack <> 0) do
begin
// Pop front.
curNode := stack[0];
for i := 0 to nstack-1 - 1 do
stack[i] := stack[i+1];
Dec(nstack);
// Get poly and tile.
// The API input has been cheked already, skip checking internal data.
curRef := curNode.id;
curTile := nil;
curPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(curRef, @curTile, @curPoly);
// Collect vertices.
nverts := curPoly.vertCount;
for i := 0 to nverts - 1 do
dtVcopy(@verts[i*3], @curTile.verts[curPoly.verts[i]*3]);
// If target is inside the poly, stop search.
if (dtPointInPolygon(endPos, @verts[0], nverts)) then
begin
bestNode := curNode;
dtVcopy(@bestPos[0], endPos);
break;
end;
// Find wall edges and find nearest point inside the walls.
i := 0; j := curPoly.vertCount-1;
while (i < curPoly.vertCount) do
begin
// Find links to neighbours.
nneis := 0;
if (curPoly.neis[j] and DT_EXT_LINK) <> 0 then
begin
// Tile border.
k := curPoly.firstLink;
while (k <> DT_NULL_LINK) do
begin
link := @curTile.links[k];
if (link.edge = j) then
begin
if (link.ref <> 0) then
begin
neiTile := nil;
neiPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(link.ref, @neiTile, @neiPoly);
if (filter.passFilter(link.ref, neiTile, neiPoly)) then
begin
if (nneis < MAX_NEIS) then
begin
neis[nneis] := link.ref;
Inc(nneis);
end;
end;
end;
end;
k := curTile.links[k].next;
end;
end
else if (curPoly.neis[j] <> 0) then
begin
idx := (curPoly.neis[j]-1);
ref := m_nav.getPolyRefBase(curTile) or idx;
if (filter.passFilter(ref, curTile, @curTile.polys[idx])) then
begin
// Internal edge, encode id.
neis[nneis] := ref;
Inc(nneis);
end;
end;
if (nneis = 0) then
begin
// Wall edge, calc distance.
vj := @verts[j*3];
vi := @verts[i*3];
distSqr := dtDistancePtSegSqr2D(endPos, vj, vi, @tseg);
if (distSqr < bestDist) then
begin
// Update nearest distance.
dtVlerp(@bestPos[0], vj,vi, tseg);
bestDist := distSqr;
bestNode := curNode;
end;
end
else
begin
for k := 0 to nneis - 1 do
begin
// Skip if no node can be allocated.
neighbourNode := m_tinyNodePool.getNode(neis[k]);
if (neighbourNode = nil) then
continue;
// Skip if already visited.
if (neighbourNode.flags and DT_NODE_CLOSED) <> 0 then
continue;
// Skip the link if it is too far from search constraint.
// TODO: Maybe should use getPortalPoints(), but this one is way faster.
vj := @verts[j*3];
vi := @verts[i*3];
distSqr := dtDistancePtSegSqr2D(@searchPos[0], vj, vi, @tseg);
if (distSqr > searchRadSqr) then
continue;
// Mark as the node as visited and push to queue.
if (nstack < MAX_STACK) then
begin
neighbourNode.pidx := m_tinyNodePool.getNodeIdx(curNode);
neighbourNode.flags := neighbourNode.flags or DT_NODE_CLOSED;
stack[nstack] := neighbourNode;
Inc(nstack);
end;
end;
end;
j := i;
Inc(i);
end;
end;
n := 0;
if (bestNode <> nil) then
begin
// Reverse the path.
prev := nil;
node := bestNode;
repeat
next := m_tinyNodePool.getNodeAtIdx(node.pidx);
node.pidx := m_tinyNodePool.getNodeIdx(prev);
prev := node;
node := next;
until (node = nil);
// Store result
node := prev;
repeat
visited[n] := node.id;
Inc(n);
if (n >= maxVisitedSize) then
begin
status := status or DT_BUFFER_TOO_SMALL;
break;
end;
node := m_tinyNodePool.getNodeAtIdx(node.pidx);
until (node = nil);
end;
dtVcopy(resultPos, @bestPos[0]);
visitedCount^ := n;
Result := status;
end;
function TdtNavMeshQuery.getPortalPoints(from, &to: TdtPolyRef; left, right: PSingle;
fromType, toType: PByte): TdtStatus;
var fromTile,toTile: PdtMeshTile; fromPoly,toPoly: PdtPoly;
begin
//dtAssert(m_nav);
fromTile := nil;
fromPoly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(from, @fromTile, @fromPoly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
fromType^ := fromPoly.getType;
toTile := nil;
toPoly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(&to, @toTile, @toPoly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
toType^ := toPoly.getType;
Result := getPortalPoints(from, fromPoly, fromTile, &to, toPoly, toTile, left, right);
end;
// Returns portal points between two polygons.
function TdtNavMeshQuery.getPortalPoints(from: TdtPolyRef; fromPoly: PdtPoly; fromTile: PdtMeshTile;
&to: TdtPolyRef; toPoly: PdtPoly; toTile: PdtMeshTile;
left, right: PSingle): TdtStatus;
var link: PdtLink; i: Cardinal; v,v0,v1: Integer; s,tmin,tmax: Single;
begin
// Find the link that points to the 'to' polygon.
link := nil;
i := fromPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
if (fromTile.links[i].ref = &to) then
begin
link := @fromTile.links[i];
break;
end;
i := fromTile.links[i].next;
end;
if (link = nil) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Handle off-mesh connections.
if (fromPoly.getType = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
// Find link that points to first vertex.
i := fromPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
if (fromTile.links[i].ref = &to) then
begin
v := fromTile.links[i].edge;
dtVcopy(left, @fromTile.verts[fromPoly.verts[v]*3]);
dtVcopy(right, @fromTile.verts[fromPoly.verts[v]*3]);
Exit(DT_SUCCESS);
end;
i := fromTile.links[i].next;
end;
Exit(DT_FAILURE or DT_INVALID_PARAM);
end;
if (toPoly.getType = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
i := toPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
if (toTile.links[i].ref = from) then
begin
v := toTile.links[i].edge;
dtVcopy(left, @toTile.verts[toPoly.verts[v]*3]);
dtVcopy(right, @toTile.verts[toPoly.verts[v]*3]);
Exit(DT_SUCCESS);
end;
i := toTile.links[i].next;
end;
Exit(DT_FAILURE or DT_INVALID_PARAM);
end;
// Find portal vertices.
v0 := fromPoly.verts[link.edge];
v1 := fromPoly.verts[(link.edge+1) mod fromPoly.vertCount];
dtVcopy(left, @fromTile.verts[v0*3]);
dtVcopy(right, @fromTile.verts[v1*3]);
// If the link is at tile boundary, dtClamp the vertices to
// the link width.
if (link.side <> $ff) then
begin
// Unpack portal limits.
if (link.bmin <> 0) or (link.bmax <> 255) then
begin
s := 1.0/255.0;
tmin := link.bmin*s;
tmax := link.bmax*s;
dtVlerp(left, @fromTile.verts[v0*3], @fromTile.verts[v1*3], tmin);
dtVlerp(right, @fromTile.verts[v0*3], @fromTile.verts[v1*3], tmax);
end;
end;
Result := DT_SUCCESS;
end;
// Returns edge mid point between two polygons.
function TdtNavMeshQuery.getEdgeMidPoint(from, &to: TdtPolyRef; mid: PSingle): TdtStatus;
var left, right: array [0..2] of Single; fromType, toType: Byte;
begin
if (dtStatusFailed(getPortalPoints(from, &to, @left[0],@right[0], @fromType, @toType))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
mid[0] := (left[0]+right[0])*0.5;
mid[1] := (left[1]+right[1])*0.5;
mid[2] := (left[2]+right[2])*0.5;
Result := DT_SUCCESS;
end;
function TdtNavMeshQuery.getEdgeMidPoint(from: TdtPolyRef; fromPoly: PdtPoly; fromTile: PdtMeshTile;
&to: TdtPolyRef; toPoly: PdtPoly; toTile: PdtMeshTile;
mid: PSingle): TdtStatus;
var left, right: array [0..2] of Single;
begin
if (dtStatusFailed(getPortalPoints(from, fromPoly, fromTile, &to, toPoly, toTile, @left[0], @right[0]))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
mid[0] := (left[0]+right[0])*0.5;
mid[1] := (left[1]+right[1])*0.5;
mid[2] := (left[2]+right[2])*0.5;
Result := DT_SUCCESS;
end;
/// @par
///
/// This method is meant to be used for quick, short distance checks.
///
/// If the path array is too small to hold the result, it will be filled as
/// far as possible from the start postion toward the end position.
///
/// <b>Using the Hit Parameter (t)</b>
///
/// If the hit parameter is a very high value (FLT_MAX), then the ray has hit
/// the end position. In this case the path represents a valid corridor to the
/// end position and the value of @p hitNormal is undefined.
///
/// If the hit parameter is zero, then the start position is on the wall that
/// was hit and the value of @p hitNormal is undefined.
///
/// If 0 < t < 1.0 then the following applies:
///
/// @code
/// distanceToHitBorder := distanceToEndPosition * t
/// hitPoint := startPos + (endPos - startPos) * t
/// @endcode
///
/// <b>Use Case Restriction</b>
///
/// The raycast ignores the y-value of the end position. (2D check.) This
/// places significant limits on how it can be used. For example:
///
/// Consider a scene where there is a main floor with a second floor balcony
/// that hangs over the main floor. So the first floor mesh extends below the
/// balcony mesh. The start position is somewhere on the first floor. The end
/// position is on the balcony.
///
/// The raycast will search toward the end position along the first floor mesh.
/// If it reaches the end position's xz-coordinates it will indicate FLT_MAX
/// (no wall hit), meaning it reached the end position. This is one example of why
/// this method is meant for short distance checks.
///
function TdtNavMeshQuery.raycast(startRef: TdtPolyRef; startPos, endPos: PSingle;
filter: TdtQueryFilter;
t, hitNormal: PSingle; path: PdtPolyRef; pathCount: PInteger; maxPath: Integer): TdtStatus;
var hit: TdtRaycastHit; status: TdtStatus;
begin
hit.path := path;
hit.maxPath := maxPath;
status := raycast(startRef, startPos, endPos, filter, 0, @hit);
t^ := hit.t;
if (hitNormal <> nil) then
dtVcopy(hitNormal, @hit.hitNormal[0]);
if (pathCount <> nil) then
pathCount^ := hit.pathCount;
Result := status;
end;
/// @par
///
/// This method is meant to be used for quick, short distance checks.
///
/// If the path array is too small to hold the result, it will be filled as
/// far as possible from the start postion toward the end position.
///
/// <b>Using the Hit Parameter t of RaycastHit</b>
///
/// If the hit parameter is a very high value (FLT_MAX), then the ray has hit
/// the end position. In this case the path represents a valid corridor to the
/// end position and the value of @p hitNormal is undefined.
///
/// If the hit parameter is zero, then the start position is on the wall that
/// was hit and the value of @p hitNormal is undefined.
///
/// If 0 < t < 1.0 then the following applies:
///
/// @code
/// distanceToHitBorder := distanceToEndPosition * t
/// hitPoint := startPos + (endPos - startPos) * t
/// @endcode
///
/// <b>Use Case Restriction</b>
///
/// The raycast ignores the y-value of the end position. (2D check.) This
/// places significant limits on how it can be used. For example:
///
/// Consider a scene where there is a main floor with a second floor balcony
/// that hangs over the main floor. So the first floor mesh extends below the
/// balcony mesh. The start position is somewhere on the first floor. The end
/// position is on the balcony.
///
/// The raycast will search toward the end position along the first floor mesh.
/// If it reaches the end position's xz-coordinates it will indicate FLT_MAX
/// (no wall hit), meaning it reached the end position. This is one example of why
/// this method is meant for short distance checks.
///
function TdtNavMeshQuery.raycast(startRef: TdtPolyRef; startPos, endPos: PSingle;
filter: TdtQueryFilter; options: Cardinal;
hit: PdtRaycastHit; prevRef: TdtPolyRef = 0): TdtStatus;
var dir,curPos,lastPos,eDir,diff: array [0..2] of Single; verts: array [0..DT_VERTS_PER_POLYGON*3+3-1] of Single; n: Integer; status: TdtStatus;
prevTile,tile,nextTile: PdtMeshTile; prevPoly,poly,nextPoly: PdtPoly; curRef,nextRef: TdtPolyRef; nv: Integer; i: Cardinal;
tmin, tmax: Single; segMin, segMax: Integer; link: PdtLink; v0,v1: Integer; left,right: PSingle; s,lmin,lmax,z,x: Single;
e1,e2: PSingle; a,b: Integer; va,vb: PSingle; dx,dz: Single;
begin
//dtAssert(m_nav);
hit.t := 0;
hit.pathCount := 0;
hit.pathCost := 0;
// Validate input
if (startRef = 0) or not m_nav.isValidPolyRef(startRef) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
if (prevRef <> 0) and not m_nav.isValidPolyRef(prevRef) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
n := 0;
dtVcopy(@curPos[0], startPos);
dtVsub(@dir[0], endPos, startPos);
dtVset(@hit.hitNormal[0], 0, 0, 0);
status := DT_SUCCESS;
// The API input has been checked already, skip checking internal data.
nextRef := startRef; curRef := startRef;
tile := nil;
poly := nil;
m_nav.getTileAndPolyByRefUnsafe(curRef, @tile, @poly);
nextTile := tile; prevTile := tile;
nextPoly := poly; prevPoly := poly;
if (prevRef <> 0) then
m_nav.getTileAndPolyByRefUnsafe(prevRef, @prevTile, @prevPoly);
while (curRef <> 0) do
begin
// Cast ray against current polygon.
// Collect vertices.
nv := 0;
for i := 0 to Integer(poly.vertCount) - 1 do
begin
dtVcopy(@verts[nv*3], @tile.verts[poly.verts[i]*3]);
Inc(nv);
end;
if (not dtIntersectSegmentPoly2D(startPos, endPos, @verts[0], nv, @tmin, @tmax, @segMin, @segMax)) then
begin
// Could not hit the polygon, keep the old t and report hit.
hit.pathCount := n;
Exit(status);
end;
// Keep track of furthest t so far.
if (tmax > hit.t) then
hit.t := tmax;
// Store visited polygons.
if (n < hit.maxPath) then
begin
hit.path[n] := curRef;
Inc(n);
end
else
status := status or DT_BUFFER_TOO_SMALL;
// Ray end is completely inside the polygon.
if (segMax = -1) then
begin
hit.t := MaxSingle;
hit.pathCount := n;
// add the cost
if (options and Byte(DT_RAYCAST_USE_COSTS) <> 0) then
hit.pathCost := hit.pathCost + filter.getCost(@curPos[0], endPos, prevRef, prevTile, prevPoly, curRef, tile, poly, curRef, tile, poly);
Exit(status);
end;
// Follow neighbours.
nextRef := 0;
i := poly.firstLink;
while (i <> DT_NULL_LINK) do
begin
link := @tile.links[i];
// Find link which contains this edge.
if (link.edge <> segMax) then
begin
i := tile.links[i].next;
continue;
end;
// Get pointer to the next polygon.
nextTile := nil;
nextPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(link.ref, @nextTile, @nextPoly);
// Skip off-mesh connections.
if (nextPoly.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
i := tile.links[i].next;
continue;
end;
// Skip links based on filter.
if (not filter.passFilter(link.ref, nextTile, nextPoly)) then
begin
i := tile.links[i].next;
continue;
end;
// If the link is internal, just return the ref.
if (link.side = $ff) then
begin
nextRef := link.ref;
break;
end;
// If the link is at tile boundary,
// Check if the link spans the whole edge, and accept.
if (link.bmin = 0) and (link.bmax = 255) then
begin
nextRef := link.ref;
break;
end;
// Check for partial edge links.
v0 := poly.verts[link.edge];
v1 := poly.verts[(link.edge+1) mod poly.vertCount];
left := @tile.verts[v0*3];
right := @tile.verts[v1*3];
// Check that the intersection lies inside the link portal.
if (link.side = 0) or (link.side = 4) then
begin
// Calculate link size.
s := 1.0/255.0;
lmin := left[2] + (right[2] - left[2])*(link.bmin*s);
lmax := left[2] + (right[2] - left[2])*(link.bmax*s);
if (lmin > lmax) then dtSwap(lmin, lmax);
// Find Z intersection.
z := startPos[2] + (endPos[2]-startPos[2])*tmax;
if (z >= lmin) and (z <= lmax) then
begin
nextRef := link.ref;
break;
end;
end
else if (link.side = 2) or (link.side = 6) then
begin
// Calculate link size.
s := 1.0/255.0;
lmin := left[0] + (right[0] - left[0])*(link.bmin*s);
lmax := left[0] + (right[0] - left[0])*(link.bmax*s);
if (lmin > lmax) then dtSwap(lmin, lmax);
// Find X intersection.
x := startPos[0] + (endPos[0]-startPos[0])*tmax;
if (x >= lmin) and (x <= lmax) then
begin
nextRef := link.ref;
break;
end;
end;
i := tile.links[i].next;
end;
// add the cost
if (options and Byte(DT_RAYCAST_USE_COSTS)) <> 0 then
begin
// compute the intersection point at the furthest end of the polygon
// and correct the height (since the raycast moves in 2d)
dtVcopy(@lastPos[0], @curPos[0]);
dtVmad(@curPos[0], startPos, @dir[0], hit.t);
e1 := @verts[segMax*3];
e2 := @verts[((segMax+1) mod nv)*3];
dtVsub(@eDir[0], e2, e1);
dtVsub(@diff[0], @curPos[0], e1);
if Sqr(eDir[0]) > Sqr(eDir[2]) then s := diff[0] / eDir[0] else s := diff[2] / eDir[2];
curPos[1] := e1[1] + eDir[1] * s;
hit.pathCost := hit.pathCost + filter.getCost(@lastPos[0], @curPos[0], prevRef, prevTile, prevPoly, curRef, tile, poly, nextRef, nextTile, nextPoly);
end;
if (nextRef = 0) then
begin
// No neighbour, we hit a wall.
// Calculate hit normal.
a := segMax;
b := IfThen(segMax+1 < nv, segMax+1, 0);
va := @verts[a*3];
vb := @verts[b*3];
dx := vb[0] - va[0];
dz := vb[2] - va[2];
hit.hitNormal[0] := dz;
hit.hitNormal[1] := 0;
hit.hitNormal[2] := -dx;
dtVnormalize(@hit.hitNormal[0]);
hit.pathCount := n;
Exit(status);
end;
// No hit, advance to neighbour polygon.
prevRef := curRef;
curRef := nextRef;
prevTile := tile;
tile := nextTile;
prevPoly := poly;
poly := nextPoly;
end;
hit.pathCount := n;
Result := status;
end;
/// @par
///
/// At least one result array must be provided.
///
/// The order of the result set is from least to highest cost to reach the polygon.
///
/// A common use case for this method is to perform Dijkstra searches.
/// Candidate polygons are found by searching the graph beginning at the start polygon.
///
/// If a polygon is not found via the graph search, even if it intersects the
/// search circle, it will not be included in the result set. For example:
///
/// polyA is the start polygon.
/// polyB shares an edge with polyA. (Is adjacent.)
/// polyC shares an edge with polyB, but not with polyA
/// Even if the search circle overlaps polyC, it will not be included in the
/// result set unless polyB is also in the set.
///
/// The value of the center point is used as the start position for cost
/// calculations. It is not projected onto the surface of the mesh, so its
/// y-value will effect the costs.
///
/// Intersection tests occur in 2D. All polygons and the search circle are
/// projected onto the xz-plane. So the y-value of the center point does not
/// effect intersection tests.
///
/// If the result arrays are to small to hold the entire result set, they will be
/// filled to capacity.
///
function TdtNavMeshQuery.findPolysAroundCircle(startRef: TdtPolyRef; centerPos: PSingle; radius: Single;
filter: TdtQueryFilter;
resultRef, resultParent: PdtPolyRef; resultCost: PSingle;
resultCount: PInteger; maxResult: Integer): TdtStatus;
var startNode,bestNode,neighbourNode: PdtNode; status: TdtStatus; n: Integer; radiusSqr: Single; bestRef,parentRef,neighbourRef: TdtPolyRef;
bestTile,parentTile,neighbourTile: PdtMeshTile; bestPoly,parentPoly,neighbourPoly: PdtPoly; i: Cardinal; link: PdtLink;
va,vb: array [0..2] of Single; tseg,distSqr,total: Single;
begin
Assert(m_nav <> nil);
Assert(m_nodePool <> nil);
Assert(m_openList <> nil);
resultCount^ := 0;
// Validate input
if (startRef = 0) or (not m_nav.isValidPolyRef(startRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
m_nodePool.clear();
m_openList.clear();
startNode := m_nodePool.getNode(startRef);
dtVcopy(@startNode.pos, centerPos);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := 0;
startNode.id := startRef;
startNode.flags := DT_NODE_OPEN;
m_openList.push(startNode);
status := DT_SUCCESS;
n := 0;
if (n < maxResult) then
begin
if (resultRef <> nil) then
resultRef[n] := startNode.id;
if (resultParent <> nil) then
resultParent[n] := 0;
if (resultCost <> nil) then
resultCost[n] := 0;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
radiusSqr := Sqr(radius);
while (not m_openList.empty()) do
begin
bestNode := m_openList.pop();
bestNode.flags := bestNode.flags and not DT_NODE_OPEN;
bestNode.flags := bestNode.flags or DT_NODE_CLOSED;
// Get poly and tile.
// The API input has been cheked already, skip checking internal data.
bestRef := bestNode.id;
bestTile := nil;
bestPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(bestRef, @bestTile, @bestPoly);
// Get parent poly and tile.
parentRef := 0;
parentTile := nil;
parentPoly := nil;
if (bestNode.pidx <> 0) then
parentRef := m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef <> 0) then
m_nav.getTileAndPolyByRefUnsafe(parentRef, @parentTile, @parentPoly);
i := bestPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
link := @bestTile.links[i];
neighbourRef := link.ref;
// Skip invalid neighbours and do not follow back to parent.
if (neighbourRef = 0) or (neighbourRef = parentRef) then
begin
i := bestTile.links[i].next;
continue;
end;
// Expand to neighbour
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
// Do not advance if the polygon is excluded by the filter.
if (not filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := bestTile.links[i].next;
continue;
end;
// Find edge and calc distance to the edge.
if (getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, @va[0], @vb[0]) = 0) then
begin
i := bestTile.links[i].next;
continue;
end;
// If the circle is not touching the next polygon, skip it.
distSqr := dtDistancePtSegSqr2D(centerPos, @va[0], @vb[0], @tseg);
if (distSqr > radiusSqr) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode := m_nodePool.getNode(neighbourRef);
if (neighbourNode = nil) then
begin
status := status or DT_OUT_OF_NODES;
i := bestTile.links[i].next;
continue;
end;
if (neighbourNode.flags and DT_NODE_CLOSED) <> 0 then
begin
i := bestTile.links[i].next;
continue;
end;
// Cost
if (neighbourNode.flags = 0) then
dtVlerp(@neighbourNode.pos, @va[0], @vb[0], 0.5);
total := bestNode.total + dtVdist(@bestNode.pos, @neighbourNode.pos);
// The node is already in open list and the new result is worse, skip.
if ((neighbourNode.flags and DT_NODE_OPEN) <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode.id := neighbourRef;
neighbourNode.flags := (neighbourNode.flags and not DT_NODE_CLOSED);
neighbourNode.pidx := m_nodePool.getNodeIdx(bestNode);
neighbourNode.total := total;
if (neighbourNode.flags and DT_NODE_OPEN) <> 0 then
begin
m_openList.modify(neighbourNode);
end
else
begin
if (n < maxResult) then
begin
if (resultRef <> nil) then
resultRef[n] := neighbourNode.id;
if (resultParent <> nil) then
resultParent[n] := m_nodePool.getNodeAtIdx(neighbourNode.pidx).id;
if (resultCost <> nil) then
resultCost[n] := neighbourNode.total;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
neighbourNode.flags := DT_NODE_OPEN;
m_openList.push(neighbourNode);
end;
i := bestTile.links[i].next;
end;
end;
resultCount^ := n;
Result := status;
end;
/// @par
///
/// The order of the result set is from least to highest cost.
///
/// At least one result array must be provided.
///
/// A common use case for this method is to perform Dijkstra searches.
/// Candidate polygons are found by searching the graph beginning at the start
/// polygon.
///
/// The same intersection test restrictions that apply to findPolysAroundCircle()
/// method apply to this method.
///
/// The 3D centroid of the search polygon is used as the start position for cost
/// calculations.
///
/// Intersection tests occur in 2D. All polygons are projected onto the
/// xz-plane. So the y-values of the vertices do not effect intersection tests.
///
/// If the result arrays are is too small to hold the entire result set, they will
/// be filled to capacity.
///
function TdtNavMeshQuery.findPolysAroundShape(startRef: TdtPolyRef; verts: PSingle; nverts: Integer;
filter: TdtQueryFilter;
resultRef, resultParent: PdtPolyRef; resultCost: PSingle;
resultCount: PInteger; maxResult: Integer): TdtStatus;
var centerPos: array [0..2] of Single; i: Cardinal; startNode,bestNode,neighbourNode: PdtNode; status: TdtStatus; n: Integer;
bestRef,parentRef,neighbourRef: TdtPolyRef; bestTile,parentTile,neighbourTile: PdtMeshTile; bestPoly,parentPoly,neighbourPoly: PdtPoly;
link: PdtLink; va,vb: array [0..2] of Single; tmin,tmax,distSqr,total: Single; segMin,segMax: Integer;
begin
Assert(m_nav <> nil);
Assert(m_nodePool <> nil);
Assert(m_openList <> nil);
resultCount^ := 0;
// Validate input
if (startRef = 0) or (not m_nav.isValidPolyRef(startRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
m_nodePool.clear();
m_openList.clear();
centerPos[0] := 0; centerPos[1] := 0; centerPos[2] := 0;
for i := 0 to nverts - 1 do
dtVadd(@centerPos[0],@centerPos[0],@verts[i*3]);
dtVscale(@centerPos[0],@centerPos[0],1.0/nverts);
startNode := m_nodePool.getNode(startRef);
dtVcopy(@startNode.pos, @centerPos[0]);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := 0;
startNode.id := startRef;
startNode.flags := DT_NODE_OPEN;
m_openList.push(startNode);
status := DT_SUCCESS;
n := 0;
if (n < maxResult) then
begin
if (resultRef <> nil) then
resultRef[n] := startNode.id;
if (resultParent <> nil) then
resultParent[n] := 0;
if (resultCost <> nil) then
resultCost[n] := 0;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
while (not m_openList.empty()) do
begin
bestNode := m_openList.pop();
bestNode.flags := bestNode.flags and not DT_NODE_OPEN;
bestNode.flags := bestNode.flags or DT_NODE_CLOSED;
// Get poly and tile.
// The API input has been cheked already, skip checking internal data.
bestRef := bestNode.id;
bestTile := nil;
bestPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(bestRef, @bestTile, @bestPoly);
// Get parent poly and tile.
parentRef := 0;
parentTile := nil;
parentPoly := nil;
if (bestNode.pidx <> 0) then
parentRef := m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef <> 0) then
m_nav.getTileAndPolyByRefUnsafe(parentRef, @parentTile, @parentPoly);
i := bestPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
link := @bestTile.links[i];
neighbourRef := link.ref;
// Skip invalid neighbours and do not follow back to parent.
if (neighbourRef = 0) or (neighbourRef = parentRef) then
begin
i := bestTile.links[i].next;
continue;
end;
// Expand to neighbour
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
// Do not advance if the polygon is excluded by the filter.
if (not filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := bestTile.links[i].next;
continue;
end;
// Find edge and calc distance to the edge.
if (getPortalPoints(bestRef, bestPoly, bestTile, neighbourRef, neighbourPoly, neighbourTile, @va[0], @vb[0]) = 0) then
begin
i := bestTile.links[i].next;
continue;
end;
// If the poly is not touching the edge to the next polygon, skip the connection it.
if (not dtIntersectSegmentPoly2D(@va[0], @vb[0], verts, nverts, @tmin, @tmax, @segMin, @segMax)) then
begin
i := bestTile.links[i].next;
continue;
end;
if (tmin > 1.0) or (tmax < 0.0) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode := m_nodePool.getNode(neighbourRef);
if (neighbourNode = nil) then
begin
status := status or DT_OUT_OF_NODES;
i := bestTile.links[i].next;
continue;
end;
if (neighbourNode.flags and DT_NODE_CLOSED) <> 0 then
begin
i := bestTile.links[i].next;
continue;
end;
// Cost
if (neighbourNode.flags = 0) then
dtVlerp(@neighbourNode.pos, @va[0], @vb[0], 0.5);
total := bestNode.total + dtVdist(@bestNode.pos, @neighbourNode.pos);
// The node is already in open list and the new result is worse, skip.
if ((neighbourNode.flags and DT_NODE_OPEN) <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode.id := neighbourRef;
neighbourNode.flags := (neighbourNode.flags and not DT_NODE_CLOSED);
neighbourNode.pidx := m_nodePool.getNodeIdx(bestNode);
neighbourNode.total := total;
if (neighbourNode.flags and DT_NODE_OPEN) <> 0 then
begin
m_openList.modify(neighbourNode);
end
else
begin
if (n < maxResult) then
begin
if (resultRef <> nil) then
resultRef[n] := neighbourNode.id;
if (resultParent <> nil) then
resultParent[n] := m_nodePool.getNodeAtIdx(neighbourNode.pidx).id;
if (resultCost <> nil) then
resultCost[n] := neighbourNode.total;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
neighbourNode.flags := DT_NODE_OPEN;
m_openList.push(neighbourNode);
end;
i := bestTile.links[i].next;
end;
end;
resultCount^ := n;
Result := status;
end;
/// @par
///
/// This method is optimized for a small search radius and small number of result
/// polygons.
///
/// Candidate polygons are found by searching the navigation graph beginning at
/// the start polygon.
///
/// The same intersection test restrictions that apply to the findPolysAroundCircle
/// mehtod applies to this method.
///
/// The value of the center point is used as the start point for cost calculations.
/// It is not projected onto the surface of the mesh, so its y-value will effect
/// the costs.
///
/// Intersection tests occur in 2D. All polygons and the search circle are
/// projected onto the xz-plane. So the y-value of the center point does not
/// effect intersection tests.
///
/// If the result arrays are is too small to hold the entire result set, they will
/// be filled to capacity.
///
function TdtNavMeshQuery.findLocalNeighbourhood(startRef: TdtPolyRef; centerPos: PSingle; radius: Single;
filter: TdtQueryFilter;
resultRef, resultParent: PdtPolyRef;
resultCount: PInteger; maxResult: Integer): TdtStatus;
const MAX_STACK = 48;
var stack: array [0..MAX_STACK-1] of PdtNode; i, k: Cardinal; nstack,n,j,i0,k0: Integer; startNode, curNode, neighbourNode: PdtNode; radiusSqr: Single;
pa, pb: array [0..DT_VERTS_PER_POLYGON*3-1] of Single; status: TdtStatus; curRef, neighbourRef, pastRef: TdtPolyRef;
curTile, neighbourTile, pastTile: PdtMeshTile; curPoly, neighbourPoly, pastPoly: PdtPoly;
link: PdtLink; va,vb: array [0..2] of Single; tseg, distSqr: Single; npa, npb: Integer; overlap, connected: Boolean;
begin
Assert(m_nav <> nil);
Assert(m_tinyNodePool <> nil);
resultCount^ := 0;
// Validate input
if (startRef = 0) or (not m_nav.isValidPolyRef(startRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
nstack := 0;
m_tinyNodePool.clear();
startNode := m_tinyNodePool.getNode(startRef);
startNode.pidx := 0;
startNode.id := startRef;
startNode.flags := DT_NODE_CLOSED;
stack[nstack] := startNode;
Inc(nstack);
radiusSqr := Sqr(radius);
status := DT_SUCCESS;
n := 0;
if (n < maxResult) then
begin
resultRef[n] := startNode.id;
if (resultParent <> nil) then
resultParent[n] := 0;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
while (nstack <> 0) do
begin
// Pop front.
curNode := stack[0];
for i0 := 0 to nstack-1 - 1 do
stack[i0] := stack[i0+1];
Dec(nstack);
// Get poly and tile.
// The API input has been cheked already, skip checking internal data.
curRef := curNode.id;
curTile := nil;
curPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(curRef, @curTile, @curPoly);
i := curPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
link := @curTile.links[i];
neighbourRef := link.ref;
// Skip invalid neighbours.
if (neighbourRef = 0) then
begin
i := curTile.links[i].next;
continue;
end;
// Skip if cannot alloca more nodes.
neighbourNode := m_tinyNodePool.getNode(neighbourRef);
if (neighbourNode = nil) then
begin
i := curTile.links[i].next;
continue;
end;
// Skip visited.
if (neighbourNode.flags and DT_NODE_CLOSED) <> 0 then
begin
i := curTile.links[i].next;
continue;
end;
// Expand to neighbour
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
// Skip off-mesh connections.
if (neighbourPoly.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
i := curTile.links[i].next;
continue;
end;
// Do not advance if the polygon is excluded by the filter.
if (not filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := curTile.links[i].next;
continue;
end;
// Find edge and calc distance to the edge.
if (getPortalPoints(curRef, curPoly, curTile, neighbourRef, neighbourPoly, neighbourTile, @va[0], @vb[0]) = 0) then
begin
i := curTile.links[i].next;
continue;
end;
// If the circle is not touching the next polygon, skip it.
distSqr := dtDistancePtSegSqr2D(centerPos, @va[0], @vb[0], @tseg);
if (distSqr > radiusSqr) then
begin
i := curTile.links[i].next;
continue;
end;
// Mark node visited, this is done before the overlap test so that
// we will not visit the poly again if the test fails.
neighbourNode.flags := neighbourNode.flags or DT_NODE_CLOSED;
neighbourNode.pidx := m_tinyNodePool.getNodeIdx(curNode);
// Check that the polygon does not collide with existing polygons.
// Collect vertices of the neighbour poly.
npa := neighbourPoly.vertCount;
for k := 0 to npa - 1 do
dtVcopy(@pa[k*3], @neighbourTile.verts[neighbourPoly.verts[k]*3]);
overlap := false;
for j := 0 to n - 1 do
begin
pastRef := resultRef[j];
// Connected polys do not overlap.
connected := false;
k := curPoly.firstLink;
while (k <> DT_NULL_LINK) do
begin
if (curTile.links[k].ref = pastRef) then
begin
connected := true;
break;
end;
k := curTile.links[k].next;
end;
if (connected) then
continue;
// Potentially overlapping.
pastTile := nil;
pastPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(pastRef, @pastTile, @pastPoly);
// Get vertices and test overlap
npb := pastPoly.vertCount;
for k0 := 0 to npb - 1 do
dtVcopy(@pb[k0*3], @pastTile.verts[pastPoly.verts[k0]*3]);
if (dtOverlapPolyPoly2D(@pa[0],npa, @pb[0],npb)) then
begin
overlap := true;
break;
end;
end;
if (overlap) then
begin
i := curTile.links[i].next;
continue;
end;
// This poly is fine, store and advance to the poly.
if (n < maxResult) then
begin
resultRef[n] := neighbourRef;
if (resultParent <> nil) then
resultParent[n] := curRef;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
if (nstack < MAX_STACK) then
begin
stack[nstack] := neighbourNode;
Inc(nstack);
end;
i := curTile.links[i].next;
end;
end;
resultCount^ := n;
Result := status;
end;
type
PdtSegInterval = ^TdtSegInterval;
TdtSegInterval = record
ref: TdtPolyRef;
tmin, tmax: SmallInt;
end;
procedure insertInterval(ints: PdtSegInterval; nints: PInteger; maxInts: Integer;
tmin, tmax: SmallInt; ref: TdtPolyRef);
var idx: Integer;
begin
if (nints^+1 > maxInts) then Exit;
// Find insertion point.
idx := 0;
while (idx < nints^) do
begin
if (tmax <= ints[idx].tmin) then
break;
Inc(idx);
end;
// Move current results.
if (nints^-idx) <> 0 then
Move(ints[idx], ints[idx+1], sizeof(TdtSegInterval)*(nints^-idx));
// Store
ints[idx].ref := ref;
ints[idx].tmin := tmin;
ints[idx].tmax := tmax;
Inc(nints^);
end;
/// @par
///
/// If the @p segmentRefs parameter is provided, then all polygon segments will be returned.
/// Otherwise only the wall segments are returned.
///
/// A segment that is normally a portal will be included in the result set as a
/// wall if the @p filter results in the neighbor polygon becoomming impassable.
///
/// The @p segmentVerts and @p segmentRefs buffers should normally be sized for the
/// maximum segments per polygon of the source navigation mesh.
///
function TdtNavMeshQuery.getPolyWallSegments(ref: TdtPolyRef; filter: TdtQueryFilter;
segmentVerts: PSingle; segmentRefs: PdtPolyRef; segmentCount: PInteger;
maxSegments: Integer): TdtStatus;
const MAX_INTERVAL = 16;
var tile,neiTile: PdtMeshTile; poly,neiPoly: PdtPoly; n,nints: Integer; ints: array [0..MAX_INTERVAL-1] of TdtSegInterval; storePortals: Boolean;
status: TdtStatus; i,j: Integer; k: Cardinal; link: PdtLink; neiRef: TdtPolyRef; idx: Cardinal; vj,vi,seg: PSingle; tmin,tmax: Single;
imin,imax: Integer;
begin
//dtAssert(m_nav);
segmentCount^ := 0;
tile := nil;
poly := nil;
if (dtStatusFailed(m_nav.getTileAndPolyByRef(ref, @tile, @poly))) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
n := 0;
storePortals := segmentRefs <> nil;
status := DT_SUCCESS;
i := 0;
j := poly.vertCount-1;
while (i < poly.vertCount) do
begin
// Skip non-solid edges.
nints := 0;
if (poly.neis[j] and DT_EXT_LINK) <> 0 then
begin
// Tile border.
k := poly.firstLink;
while (k <> DT_NULL_LINK) do
begin
link := @tile.links[k];
if (link.edge = j) then
begin
if (link.ref <> 0) then
begin
neiTile := nil;
neiPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(link.ref, @neiTile, @neiPoly);
if (filter.passFilter(link.ref, neiTile, neiPoly)) then
begin
insertInterval(@ints[0], @nints, MAX_INTERVAL, link.bmin, link.bmax, link.ref);
end;
end;
end;
k := tile.links[k].next;
end;
end
else
begin
// Internal edge
neiRef := 0;
if (poly.neis[j] <> 0) then
begin
idx := (poly.neis[j]-1);
neiRef := m_nav.getPolyRefBase(tile) or idx;
if (not filter.passFilter(neiRef, tile, @tile.polys[idx])) then
neiRef := 0;
end;
// If the edge leads to another polygon and portals are not stored, skip.
if (neiRef <> 0) and (not storePortals) then
begin
j := i;
Inc(i);
continue;
end;
if (n < maxSegments) then
begin
vj := @tile.verts[poly.verts[j]*3];
vi := @tile.verts[poly.verts[i]*3];
seg := @segmentVerts[n*6];
dtVcopy(seg+0, vj);
dtVcopy(seg+3, vi);
if (segmentRefs <> nil) then
segmentRefs[n] := neiRef;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
j := i;
Inc(i);
continue;
end;
// Add sentinels
insertInterval(@ints[0], @nints, MAX_INTERVAL, -1, 0, 0);
insertInterval(@ints[0], @nints, MAX_INTERVAL, 255, 256, 0);
// Store segments.
vj := @tile.verts[poly.verts[j]*3];
vi := @tile.verts[poly.verts[i]*3];
for k := 1 to nints - 1 do
begin
// Portal segment.
if storePortals and (ints[k].ref <> 0) then
begin
tmin := ints[k].tmin/255.0;
tmax := ints[k].tmax/255.0;
if (n < maxSegments) then
begin
seg := @segmentVerts[n*6];
dtVlerp(seg+0, vj,vi, tmin);
dtVlerp(seg+3, vj,vi, tmax);
if (segmentRefs <> nil) then
segmentRefs[n] := ints[k].ref;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
end;
// Wall segment.
imin := ints[k-1].tmax;
imax := ints[k].tmin;
if (imin <> imax) then
begin
tmin := imin/255.0;
tmax := imax/255.0;
if (n < maxSegments) then
begin
seg := @segmentVerts[n*6];
dtVlerp(seg+0, vj,vi, tmin);
dtVlerp(seg+3, vj,vi, tmax);
if (segmentRefs <> nil) then
segmentRefs[n] := 0;
Inc(n);
end
else
begin
status := status or DT_BUFFER_TOO_SMALL;
end;
end;
end;
j := i;
Inc(i);
end;
segmentCount^ := n;
Result := status;
end;
/// @par
///
/// @p hitPos is not adjusted using the height detail data.
///
/// @p hitDist will equal the search radius if there is no wall within the
/// radius. In this case the values of @p hitPos and @p hitNormal are
/// undefined.
///
/// The normal will become unpredicable if @p hitDist is a very small number.
///
function TdtNavMeshQuery.findDistanceToWall(startRef: TdtPolyRef; centerPos: PSingle; maxRadius: Single;
filter: TdtQueryFilter;
hitDist, hitPos, hitNormal: PSingle): TdtStatus;
var startNode,bestNode,neighbourNode: PdtNode; radiusSqr: Single; status: TdtStatus; bestRef,parentRef: TdtPolyRef;
bestTile,parentTile,neiTile,neighbourTile: PdtMeshTile; bestPoly,parentPoly,neiPoly,neighbourPoly: PdtPoly; i,k: Cardinal; j: Integer;
solid: Boolean; link: PdtLink; idx: Cardinal; ref,neighbourRef: TdtPolyRef; vj,vi,va,vb: PSingle; tseg,distSqr,total: Single;
begin
//dtAssert(m_nav);
//dtAssert(m_nodePool);
//dtAssert(m_openList);
// Validate input
if (startRef = 0) or (not m_nav.isValidPolyRef(startRef)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
m_nodePool.clear();
m_openList.clear();
startNode := m_nodePool.getNode(startRef);
dtVcopy(@startNode.pos, centerPos);
startNode.pidx := 0;
startNode.cost := 0;
startNode.total := 0;
startNode.id := startRef;
startNode.flags := DT_NODE_OPEN;
m_openList.push(startNode);
radiusSqr := Sqr(maxRadius);
status := DT_SUCCESS;
while (not m_openList.empty()) do
begin
bestNode := m_openList.pop();
bestNode.flags := bestNode.flags and not DT_NODE_OPEN;
bestNode.flags := bestNode.flags or DT_NODE_CLOSED;
// Get poly and tile.
// The API input has been cheked already, skip checking internal data.
bestRef := bestNode.id;
bestTile := nil;
bestPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(bestRef, @bestTile, @bestPoly);
// Get parent poly and tile.
parentRef := 0;
parentTile := nil;
parentPoly := nil;
if (bestNode.pidx <> 0) then
parentRef := m_nodePool.getNodeAtIdx(bestNode.pidx).id;
if (parentRef <> 0) then
m_nav.getTileAndPolyByRefUnsafe(parentRef, @parentTile, @parentPoly);
// Hit test walls.
i := 0;
j := bestPoly.vertCount-1;
while (i < bestPoly.vertCount) do
begin
// Skip non-solid edges.
if (bestPoly.neis[j] and DT_EXT_LINK) <> 0 then
begin
// Tile border.
solid := true;
k := bestPoly.firstLink;
while (k <> DT_NULL_LINK) do
begin
link := @bestTile.links[k];
if (link.edge = j) then
begin
if (link.ref <> 0) then
begin
neiTile := nil;
neiPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(link.ref, @neiTile, @neiPoly);
if (filter.passFilter(link.ref, neiTile, neiPoly)) then
solid := false;
end;
break;
end;
k := bestTile.links[k].next;
end;
if (not solid) then begin j := i; Inc(i); continue; end;
end
else if (bestPoly.neis[j] <> 0) then
begin
// Internal edge
idx := (bestPoly.neis[j]-1);
ref := m_nav.getPolyRefBase(bestTile) or idx;
if (filter.passFilter(ref, bestTile, @bestTile.polys[idx])) then
begin
j := i;
Inc(i);
continue;
end;
end;
// Calc distance to the edge.
vj := @bestTile.verts[bestPoly.verts[j]*3];
vi := @bestTile.verts[bestPoly.verts[i]*3];
distSqr := dtDistancePtSegSqr2D(centerPos, vj, vi, @tseg);
// Edge is too far, skip.
if (distSqr > radiusSqr) then
begin
j := i;
Inc(i);
continue;
end;
// Hit wall, update radius.
radiusSqr := distSqr;
// Calculate hit pos.
hitPos[0] := vj[0] + (vi[0] - vj[0])*tseg;
hitPos[1] := vj[1] + (vi[1] - vj[1])*tseg;
hitPos[2] := vj[2] + (vi[2] - vj[2])*tseg;
j := i;
Inc(i);
end;
i := bestPoly.firstLink;
while (i <> DT_NULL_LINK) do
begin
link := @bestTile.links[i];
neighbourRef := link.ref;
// Skip invalid neighbours and do not follow back to parent.
if (neighbourRef = 0) or (neighbourRef = parentRef) then
begin
i := bestTile.links[i].next;
continue;
end;
// Expand to neighbour.
neighbourTile := nil;
neighbourPoly := nil;
m_nav.getTileAndPolyByRefUnsafe(neighbourRef, @neighbourTile, @neighbourPoly);
// Skip off-mesh connections.
if (neighbourPoly.getType = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
i := bestTile.links[i].next;
continue;
end;
// Calc distance to the edge.
va := @bestTile.verts[bestPoly.verts[link.edge]*3];
vb := @bestTile.verts[bestPoly.verts[(link.edge+1) mod bestPoly.vertCount]*3];
distSqr := dtDistancePtSegSqr2D(centerPos, va, vb, @tseg);
// If the circle is not touching the next polygon, skip it.
if (distSqr > radiusSqr) then
begin
i := bestTile.links[i].next;
continue;
end;
if (not filter.passFilter(neighbourRef, neighbourTile, neighbourPoly)) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode := m_nodePool.getNode(neighbourRef);
if (neighbourNode = nil) then
begin
status := status or DT_OUT_OF_NODES;
i := bestTile.links[i].next;
continue;
end;
if (neighbourNode.flags and DT_NODE_CLOSED) <> 0 then
begin
i := bestTile.links[i].next;
continue;
end;
// Cost
if (neighbourNode.flags = 0) then
begin
getEdgeMidPoint(bestRef, bestPoly, bestTile,
neighbourRef, neighbourPoly, neighbourTile, @neighbourNode.pos);
end;
total := bestNode.total + dtVdist(@bestNode.pos, @neighbourNode.pos);
// The node is already in open list and the new result is worse, skip.
if ((neighbourNode.flags and DT_NODE_OPEN) <> 0) and (total >= neighbourNode.total) then
begin
i := bestTile.links[i].next;
continue;
end;
neighbourNode.id := neighbourRef;
neighbourNode.flags := (neighbourNode.flags and not DT_NODE_CLOSED);
neighbourNode.pidx := m_nodePool.getNodeIdx(bestNode);
neighbourNode.total := total;
if (neighbourNode.flags and DT_NODE_OPEN) <> 0 then
begin
m_openList.modify(neighbourNode);
end
else
begin
neighbourNode.flags := neighbourNode.flags or DT_NODE_OPEN;
m_openList.push(neighbourNode);
end;
i := bestTile.links[i].next;
end;
end;
// Calc hit normal.
dtVsub(hitNormal, centerPos, hitPos);
dtVnormalize(hitNormal);
hitDist^ := Sqrt(radiusSqr);
Result := status;
end;
function TdtNavMeshQuery.isValidPolyRef(ref: TdtPolyRef; filter: TdtQueryFilter): Boolean;
var tile: PdtMeshTile; poly: PdtPoly; status: TdtStatus;
begin
tile := nil;
poly := nil;
status := m_nav.getTileAndPolyByRef(ref, @tile, @poly);
// If cannot get polygon, assume it does not exists and boundary is invalid.
if (dtStatusFailed(status)) then
Exit(false);
// If cannot pass filter, assume flags has changed and boundary is invalid.
if (not filter.passFilter(ref, tile, poly)) then
Exit(false);
Result := true;
end;
/// @par
///
/// The closed list is the list of polygons that were fully evaluated during
/// the last navigation graph search. (A* or Dijkstra)
///
function TdtNavMeshQuery.isInClosedList(ref: TdtPolyRef): Boolean;
var nodes: array [0..DT_MAX_STATES_PER_NODE-1] of PdtNode; n,i: Integer;
begin
if (m_nodePool = nil) then Exit(false);
n := m_nodePool.findNodes(ref, nodes, DT_MAX_STATES_PER_NODE);
for i := 0 to n - 1 do
begin
if (nodes[i].flags and DT_NODE_CLOSED) <> 0 then
Exit(true);
end;
Result := false;
end;
end.
|
{$IFDEF SOLID}
unit Scan;
interface
function SERVICE(ServiceNumber: Longint; Buffer: Pointer): Longint;
implementation
{$ELSE}
library Scan;
{$ENDIF}
{$IFDEF VIRTUALPASCAL}
uses
Dos, Wizard,
Types,
Consts_,
Log, Video, Misc, Language, Semaphor, Plugins, Config, ScanCore;
{$IFNDEF SOLID}
{$DYNAMIC MAIN.LIB}
{$ENDIF}
{$ELSE}
uses
Macroz, Dos, Wizard,
{$IFDEF SOLID}
Log, Video, Misc, Language, Semaphor, Plugins, Config,
{$ELSE}
Decl,
{$ENDIF}
Types, Consts_, ScanCore;
{$ENDIF}
(*** Services handler ***)
function SERVICE(ServiceNumber: Longint; Buffer: Pointer): Longint; {$IFNDEF SOLID}export;{$ENDIF}
begin
Service:=srYes;
case ServiceNumber of
(*** Startup actions ***)
snQueryName: sSetSemaphore('Kernel.Plugins.Info.Name', 'SCANNER');
snQueryAuthor: sSetSemaphore('Kernel.Plugins.Info.Author', 'sergey korowkin');
snQueryVersion: Service:=ScanVersion;
snQueryReqVer: Service:=KernelVersion;
snCommandLine:
if sGetSemaphore('Kernel.CommandLine') = 'DISABLESCAN' then ScanEnabled:=False else
if sGetSemaphore('Kernel.CommandLine') = 'ENABLESCAN' then ScanEnabled:=True;
(*** Work actions ***)
snAfterStartup: __AfterStartup;
snStartup: __Startup;
snShutdown: __Shutdown;
snStart: __Start;
(*** Message actions ***)
snsPutMessage: ___PutMessage(Buffer);
snsDupeMessage: ___DupeMessage(Buffer);
snsKillMessage: ___KillMessage(Buffer);
snsCopyMessage: ___CopyMessage;
else
Service:=srNotSupported;
end;
end;
{$IFNDEF SOLID}
exports
SERVICE;
begin
{$ENDIF}
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SQL script engine }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Comp.Script;
interface
uses
{$IFDEF MSWINDOWS}
Winapi.Windows,
{$ENDIF}
System.Types, System.SysUtils, System.Classes, System.SyncObjs,
FireDAC.Stan.Param, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Util,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.Phys.SQLPreprocessor,
FireDAC.Comp.UI, FireDAC.Comp.Client;
type
IFDScriptEngineIntf = interface;
TFDScriptCommand = class;
TFDScriptCommandClass = class of TFDScriptCommand;
TFDScriptParser = class;
TFDScriptOptions = class;
TFDSQLScript = class;
TFDSQLScripts = class;
TFDScript = class;
TFDScriptEchoCommands = (ecNone, ecSQL, ecAll);
TFDScriptSpoolOutputMode = (smNone, smOnReset, smOnAppend);
TFDScriptStatus = (ssInactive, ssValidating, ssRunning, ssFinishWithErrors,
ssFinishSuccess, ssAborted);
TFDScriptTextMode = (smRead, smWriteReset, smWriteAppend);
TFDHostCommandEvent = procedure (AEngine: TFDScript;
const ACommand: String; var ADoDefault: Boolean) of object;
TFDConsolePutEvent = procedure (AEngine: TFDScript;
const AMessage: String; AKind: TFDScriptOutputKind) of object;
TFDConsoleLockUpdate = procedure (AEngine: TFDScript; ALock: Boolean) of object;
TFDConsoleGetEvent = procedure (AEngine: TFDScript;
const APrompt: String; var AResult: String) of object;
TFDGetTextEvent = procedure (AEngine: TFDScript;
const AFileName: String; AMode: TFDScriptTextMode; out AText: TFDTextFile) of object;
TFDPauseEvent = procedure (AEngine: TFDScript;
const AText: String) of object;
IFDScriptEngineIntf = interface (IUnknown)
['{FFD3BABC-CFAB-4A6E-9B1B-882E76791DF6}']
// private
function GetRDBMSKind: TFDRDBMSKind;
function GetConnectionIntf: IFDPhysConnection;
function GetCommandIntf: IFDPhysCommand;
function GetTable: TFDDatSTable;
// public
procedure CheckCommand;
procedure CheckCommit(AForce: Boolean);
procedure CheckStartTransaction;
procedure UpdateCommandSeparator;
function ExpandString(const AValue: String): String;
procedure CloseSpool;
procedure UpdateSpool;
procedure OpenConnection(const AConnectionString: String);
procedure CloseConnection;
procedure Disconnect(AAbortJob: Boolean = False);
function ExecuteAll(AParser: TFDScriptParser): Boolean; overload;
function ExecuteStep(AParser: TFDScriptParser): Boolean; overload;
function ValidateAll(AParser: TFDScriptParser): Boolean; overload;
function ValidateStep(AParser: TFDScriptParser): Boolean; overload;
procedure Progress;
procedure ConPut(const AMsg: String; AKind: TFDScriptOutputKind);
procedure ConLockUpdate;
procedure ConUnlockUpdate;
procedure ConGet(const APrompt: String; var AResult: String);
procedure ConPause(const APrompt: String);
procedure GetText(const AFileName: String; AMode: TFDScriptTextMode;
out AText: TFDTextFile);
procedure ReleaseText(const AFileName: String; AMode: TFDScriptTextMode;
var AText: TFDTextFile);
procedure ExecuteHostCommand(const ACommand: String);
property ConnectionIntf: IFDPhysConnection read GetConnectionIntf;
property CommandIntf: IFDPhysCommand read GetCommandIntf;
property RDBMSKind: TFDRDBMSKind read GetRDBMSKind;
property Table: TFDDatSTable read GetTable;
end;
TFDScriptCommand = class(TObject)
private
FParser: TFDScriptParser;
FEngine: TFDScript;
FEngineIntf: IFDScriptEngineIntf;
FPosition: TPoint;
public
constructor Create(AParser: TFDScriptParser; AEngine: TFDScript); virtual;
destructor Destroy; override;
{$IFDEF FireDAC_MONITOR}
function Dump(): String; virtual;
{$ENDIF}
class function Help(): String; virtual;
class procedure Keywords(AKwds: TStrings); virtual;
function Parse(const AKwd: String): Boolean; virtual;
procedure Execute(); virtual;
procedure Validate(); virtual;
procedure AbortJob(const AWait: Boolean = False); virtual;
property Parser: TFDScriptParser read FParser;
property Engine: TFDScript read FEngine;
property EngineIntf: IFDScriptEngineIntf read FEngineIntf;
property Position: TPoint read FPosition;
end;
TFDScriptCommandLookupRes = (ucNone, ucPartial, ucShort, ucExact);
TFDScriptCommandRegistry = class(TObject)
private
FKeywords: TFDStringList;
FCommands: TFDClassList;
FDefaultSQLCommandClass: TFDScriptCommandClass;
FDefaultPLSQLCommandClass: TFDScriptCommandClass;
function GetCommand(AIndex: Integer): TFDScriptCommandClass;
function GetCount: Integer;
public
constructor Create;
destructor Destroy; override;
procedure AddCommand(ACommand: TFDScriptCommandClass);
function LookupCommand(const AStr: String;
out ACommand: TFDScriptCommandClass): TFDScriptCommandLookupRes;
property DefaultSQLCommandClass: TFDScriptCommandClass
read FDefaultSQLCommandClass write FDefaultSQLCommandClass;
property DefaultPLSQLCommandClass: TFDScriptCommandClass
read FDefaultPLSQLCommandClass write FDefaultPLSQLCommandClass;
property Count: Integer read GetCount;
property Commands[AIndex: Integer]: TFDScriptCommandClass read GetCommand; default;
end;
TFDScriptParser = class(TObject)
private
FCh: Char;
FBeginningOfLine: Boolean;
FWasBeginningOfLine: Boolean;
FFileName: String;
FParentCommand: TFDScriptCommand;
FLineNumber: Integer;
FLineNumberPos: Int64;
FTotalSize: Integer;
FScriptOptions: TFDScriptOptions;
FText: TFDTextFile;
FLastKwd: String;
FPrep: TFDPhysPreprocessor;
function CreateScriptCommand(ACmdClass: TFDScriptCommandClass;
AEngine: TFDScript; const AKwd: String): TFDScriptCommand;
function CreateSQLCommand(var ABeginBmk, ALastBmk, AEndBmk: Integer;
AEngine: TFDScript; var ACommand: TFDScriptCommand): Boolean;
function GetPosition: TPoint;
procedure SetPosition(const AValue: TPoint);
function InternalGetString(AAllowQuote, AAllowDoubleQuote, ARequired,
AIgnoreSep: Boolean; ASet: TFDCharSet): String;
function GetEOL(AFirstCh: Char): Boolean;
protected
function InternalGetChar: Char;
function InternalGetBookmark: Integer;
procedure InternalSetBookmark(ABmk: Integer);
function InternalExtractString(ABmk1, ABmk2: Integer): String;
public
constructor Create(AFileName: String; AParentCommand: TFDScriptCommand;
AText: TFDTextFile; AOptions: TFDScriptOptions);
// low level
procedure GetChar;
procedure UnGetChar;
function GetBookmark: Integer;
procedure SetBookmark(ABmk: Integer);
function ExtractString(ABmk1, ABmk2: Integer): String;
procedure SkipWS;
procedure SkipWSLF;
function GetUCWord: String;
function GetString(ARequired: Boolean = False): String;
function GetStringInFull: String;
function GetIdentifier: String;
function GetLine: String;
function GetOnOfChar(ADef: Char): Integer;
function GetOnOff: Integer;
function GetNumber(ADef: Integer = 0): Integer;
// high level
procedure InvalidSyntax;
function ExtractCommand(AEngine: TFDScript): TFDScriptCommand;
// props
// R/O
property Ch: Char read FCh;
property FileName: String read FFileName;
property LineNumber: Integer read FLineNumber;
property ParentCommand: TFDScriptCommand read FParentCommand;
property WasBeginningOfLine: Boolean read FWasBeginningOfLine;
// R/W
property TotalSize: Integer read FTotalSize write FTotalSize;
property ScriptOptions: TFDScriptOptions read FScriptOptions write FScriptOptions;
property Position: TPoint read GetPosition write SetPosition;
end;
TFDScriptOptions = class(TPersistent)
private
FOwner: TPersistent;
FCommitEachNCommands: Integer;
FAutoPrintParams: Boolean;
FEchoCommands: TFDScriptEchoCommands;
FFeedbackCommands: Boolean;
FColumnHeadings: Boolean;
FMaxBytesToPrintLongs: Integer;
FConsoleOutput: Boolean;
FSpoolOutput: TFDScriptSpoolOutputMode;
FSpoolFileName: String;
FTiming: Boolean;
FBreakOnError: Boolean;
FDropNonexistObj: Boolean;
FCommandSeparator: String;
FParamArraySize: Integer;
FEchoCommandTrim: Integer;
FFeedbackScript: Boolean;
FActualCommandSeparator: String;
FDefaultScriptPath: String;
FMacroExpand: Boolean;
FTrimConsole: Boolean;
FTrimSpool: Boolean;
FVerify: Boolean;
FDefaultDataPath: String;
FPageSize: Integer;
FLineSize: Integer;
FFileEndOfLine: TFDTextEndOfLine;
FFileEncoding: TFDEncoding;
FIgnoreError: Boolean;
FCharacterSet: String;
FSQLDialect: Integer;
FClientLib: String;
FDriverID: String;
FRaisePLSQLErrors: Boolean;
FBlobFile: String;
procedure SetCommandSeparator(const AValue: String);
procedure SetDriverID(const AValue: String);
protected
function GetOwner: TPersistent; override;
public
property ActualCommandSeparator: String read FActualCommandSeparator;
published
constructor Create(AOwner: TPersistent);
procedure Reset;
procedure Assign(Source: TPersistent); override;
property CommitEachNCommands: Integer read FCommitEachNCommands write FCommitEachNCommands default 0;
property AutoPrintParams: Boolean read FAutoPrintParams write FAutoPrintParams default False;
property EchoCommands: TFDScriptEchoCommands read FEchoCommands write FEchoCommands default ecSQL;
property EchoCommandTrim: Integer read FEchoCommandTrim write FEchoCommandTrim default 50;
property FeedbackCommands: Boolean read FFeedbackCommands write FFeedbackCommands default True;
property FeedbackScript: Boolean read FFeedbackScript write FFeedbackScript default True;
property ColumnHeadings: Boolean read FColumnHeadings write FColumnHeadings default True;
property MaxStringWidth: Integer read FMaxBytesToPrintLongs write FMaxBytesToPrintLongs default 80;
property ConsoleOutput: Boolean read FConsoleOutput write FConsoleOutput default True;
property SpoolOutput: TFDScriptSpoolOutputMode read FSpoolOutput write FSpoolOutput default smNone;
property SpoolFileName: String read FSpoolFileName write FSpoolFileName;
property Timing: Boolean read FTiming write FTiming default True;
property BreakOnError: Boolean read FBreakOnError write FBreakOnError default False;
property IgnoreError: Boolean read FIgnoreError write FIgnoreError default False;
property DropNonexistObj: Boolean read FDropNonexistObj write FDropNonexistObj default True;
property CommandSeparator: String read FCommandSeparator write SetCommandSeparator;
property ParamArraySize: Integer read FParamArraySize write FParamArraySize default 1;
property PageSize: Integer read FPageSize write FPageSize default 24;
property LineSize: Integer read FLineSize write FLineSize default 0;
property DefaultScriptPath: String read FDefaultScriptPath write FDefaultScriptPath;
property MacroExpand: Boolean read FMacroExpand write FMacroExpand default True;
property TrimConsole: Boolean read FTrimConsole write FTrimConsole default False;
property TrimSpool: Boolean read FTrimSpool write FTrimSpool default True;
property Verify: Boolean read FVerify write FVerify default False;
property DefaultDataPath: String read FDefaultDataPath write FDefaultDataPath;
property FileEncoding: TFDEncoding read FFileEncoding write FFileEncoding default ecDefault;
property FileEndOfLine: TFDTextEndOfLine read FFileEndOfLine write FFileEndOfLine default elDefault;
property DriverID: String read FDriverID write SetDriverID;
property ClientLib: String read FClientLib write FClientLib;
property CharacterSet: String read FCharacterSet write FCharacterSet;
property SQLDialect: Integer read FSQLDialect write FSQLDialect default 0;
property RaisePLSQLErrors: Boolean read FRaisePLSQLErrors write FRaisePLSQLErrors default False;
property BlobFile: String read FBlobFile write FBlobFile;
end;
TFDSQLScript = class(TCollectionItem)
private
FName: String;
FSQL: TStrings;
procedure SetSQL(const AValue: TStrings);
protected
function GetDisplayName: string; override;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Assign(ASource: TPersistent); override;
published
property Name: String read FName write FName;
property SQL: TStrings read FSQL write SetSQL;
end;
TFDSQLScripts = class(TOwnedCollection)
private
function GetItems(AIndex: Integer): TFDSQLScript;
procedure SetItems(AIndex: Integer; const AValue: TFDSQLScript);
public
constructor Create(AScript: TFDScript);
function Add: TFDSQLScript;
function FindScript(const AName: String): TFDSQLScript;
property Items[AIndex: Integer]: TFDSQLScript read GetItems write SetItems; default;
end;
[ComponentPlatformsAttribute(pidAllPlatforms)]
TFDScript = class(TFDComponent, IFDStanOptions, IFDStanErrorHandler,
IFDStanObject, IFDGUIxScriptDialogInfoProvider, IFDScriptEngineIntf)
private
FFinished: Boolean;
FConnectionIntf: IFDPhysConnection;
FCommandIntf: IFDPhysCommand;
FTable: TFDDatSTable;
FMacros: TFDMacros;
FParams: TFDParams;
FArguments: TStrings;
FProcessedAfterCommit: Integer;
FSpool: TFDTextFile;
FLastSpoolFileName: String;
FLock: TCriticalSection;
FPrep: TFDPhysPreprocessor;
FRDBMSKind: TFDRDBMSKind;
FCurrentCommand: TFDScriptCommand;
FCallStack: TStrings;
FAllSpools: TStrings;
FTotalJobSize: Integer;
FTotalJobDone: Integer;
FTotalPct10Done: Integer;
FTotalErrors: Integer;
FStatus: TFDScriptStatus;
FOnHostCommand: TFDHostCommandEvent;
FOnConsolePut: TFDConsolePutEvent;
FOnConsoleLockUpdate: TFDConsoleLockUpdate;
FOnConsoleGet: TFDConsoleGetEvent;
FOnSpoolPut: TFDConsolePutEvent;
FOnGetText: TFDGetTextEvent;
FOnReleaseText: TFDGetTextEvent;
FOnPause: TFDPauseEvent;
FOnProgress: TNotifyEvent;
FBeforeScript: TNotifyEvent;
FAfterScript: TNotifyEvent;
FAfterExecute: TNotifyEvent;
FBeforeExecute: TNotifyEvent;
FOnError: TFDErrorEvent;
FScriptOptions: TFDScriptOptions;
FScriptDialog: TFDGUIxScriptDialog;
FScriptDialogVisible: Boolean;
FSQLScriptFileName: String;
FSQLScripts: TFDSQLScripts;
FConnection: TFDCustomConnection;
FTransaction: TFDCustomTransaction;
FOptionsIntf: IFDStanOptions;
FPosition: TPoint;
function GetScriptDialogIntf(out AIntf: IFDGUIxScriptDialog): Boolean;
procedure SetCurrentCommand(const ACommand: TFDScriptCommand);
procedure SetScriptOptions(const AValue: TFDScriptOptions);
procedure SetScriptDialog(const AValue: TFDGUIxScriptDialog);
procedure RestoreArguments(AArgs: TStrings);
function SetupArguments: TStrings;
procedure SetArguments(const AValue: TStrings);
procedure SetConnection(const AValue: TFDCustomConnection);
procedure SetTransaction(const AValue: TFDCustomTransaction);
procedure DoConnectChanged(Sender: TObject; Connecting: Boolean);
procedure SetSQLScripts(const AValue: TFDSQLScripts);
function GetFetchOptions: TFDFetchOptions;
function GetFormatOptions: TFDFormatOptions;
function GetResourceOptions: TFDResourceOptions;
procedure SetFetchOptions(const Value: TFDFetchOptions);
procedure SetFormatOptions(const Value: TFDFormatOptions);
procedure SetResourceOptions(const Value: TFDResourceOptions);
function GetEof: Boolean;
procedure SetMacros(const AValue: TFDMacros);
procedure SetParams(const AValue: TFDParams);
function GetParamsOwner: TPersistent;
function GetIsEmpty: Boolean;
protected
procedure Notification(AComponent: TComponent; AOperation: TOperation); override;
function InternalExecute(AParser: TFDScriptParser; ARealExecute: Boolean;
AAll: Boolean): Boolean; overload;
function InternalExecute(ARealExecute: Boolean; AAll: Boolean): Boolean; overload;
procedure InternalOpenConnection(const AConnectionString: String);
procedure InternalReleaseConnection;
{ IFDStanObject }
function GetName: TComponentName;
function GetParent: IFDStanObject;
procedure BeforeReuse;
procedure AfterReuse;
procedure SetOwner(const AOwner: TObject; const ARole: TComponentName);
{ IFDStanOptions }
property OptionsIntf: IFDStanOptions read FOptionsIntf implements IFDStanOptions;
procedure GetParentOptions(var AOpts: IFDStanOptions);
{ IFDStanErrorHandler }
procedure HandleException(const AInitiator: IFDStanObject;
var AException: Exception); virtual;
{ IFDGUIxScriptDialogInfoProvider }
procedure RequestStop;
function GetCallStack: TStrings;
function GetTotalJobSize: Integer;
function GetTotalJobDone: Integer;
function GetTotalPct10Done: Integer;
function GetTotalErrors: Integer;
function GetIsRunning: Boolean;
{ IFDScriptEngineIntf }
function GetRDBMSKind: TFDRDBMSKind;
function GetConnectionIntf: IFDPhysConnection;
function GetCommandIntf: IFDPhysCommand;
function GetTable: TFDDatSTable;
procedure CheckCommand;
procedure CheckCommit(AForce: Boolean);
procedure CheckStartTransaction;
procedure UpdateCommandSeparator;
function ExpandString(const AValue: String): String;
procedure CloseSpool;
procedure UpdateSpool;
procedure OpenConnection(const AConnectionString: String);
procedure CloseConnection;
procedure Disconnect(AAbortJob: Boolean = False);
function ExecuteAll(AParser: TFDScriptParser): Boolean; overload;
function ExecuteStep(AParser: TFDScriptParser): Boolean; overload;
function ValidateAll(AParser: TFDScriptParser): Boolean; overload;
function ValidateStep(AParser: TFDScriptParser): Boolean; overload;
procedure Progress;
procedure ConPut(const AMsg: String; AKind: TFDScriptOutputKind); virtual;
procedure ConLockUpdate; virtual;
procedure ConUnlockUpdate; virtual;
procedure ConGet(const APrompt: String; var AResult: String); virtual;
procedure ConPause(const APrompt: String); virtual;
procedure GetText(const AFileName: String; AMode: TFDScriptTextMode;
out AText: TFDTextFile); virtual;
procedure ReleaseText(const AFileName: String; AMode: TFDScriptTextMode;
var AText: TFDTextFile); virtual;
procedure ExecuteHostCommand(const ACommand: String); virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function ExecuteAll: Boolean; overload;
function ExecuteStep: Boolean; overload;
function ValidateAll: Boolean; overload;
function ValidateStep: Boolean; overload;
procedure ExecuteFile(const AFileName: String); overload;
procedure ExecuteFile(const AFileName: String; const AArguments: array of String); overload;
procedure ExecuteScript(const AScript: TStrings); overload;
procedure ExecuteScript(const AScript: TStrings; const AArguments: array of String); overload;
procedure AbortJob(const AWait: Boolean = False);
property CallStack: TStrings read GetCallStack;
property TotalJobSize: Integer read GetTotalJobSize;
property TotalJobDone: Integer read GetTotalJobDone;
property TotalPct10Done: Integer read GetTotalPct10Done;
property TotalErrors: Integer read GetTotalErrors;
property CurrentCommand: TFDScriptCommand read FCurrentCommand;
property AllSpools: TStrings read FAllSpools;
property LastSpoolFileName: String read FLastSpoolFileName;
property Status: TFDScriptStatus read FStatus;
property Eof: Boolean read GetEof;
property IsEmpty: Boolean read GetIsEmpty;
property Position: TPoint read FPosition write FPosition;
property Finished: Boolean read FFinished write FFinished;
property ProcessedAfterCommit: Integer read FProcessedAfterCommit write FProcessedAfterCommit;
published
property SQLScriptFileName: String read FSQLScriptFileName write FSQLScriptFileName;
property SQLScripts: TFDSQLScripts read FSQLScripts write SetSQLScripts;
property Connection: TFDCustomConnection read FConnection write SetConnection;
property Transaction: TFDCustomTransaction read FTransaction write SetTransaction;
property ScriptOptions: TFDScriptOptions read FScriptOptions write SetScriptOptions;
property ScriptDialog: TFDGUIxScriptDialog read FScriptDialog write SetScriptDialog;
property Params: TFDParams read FParams write SetParams;
property Macros: TFDMacros read FMacros write SetMacros;
property Arguments: TStrings read FArguments write SetArguments;
property FormatOptions: TFDFormatOptions read GetFormatOptions write SetFormatOptions;
property FetchOptions: TFDFetchOptions read GetFetchOptions write SetFetchOptions;
property ResourceOptions: TFDResourceOptions read GetResourceOptions write SetResourceOptions;
property OnHostCommand: TFDHostCommandEvent read FOnHostCommand write FOnHostCommand;
property OnConsolePut: TFDConsolePutEvent read FOnConsolePut write FOnConsolePut;
property OnConsoleLockUpdate: TFDConsoleLockUpdate read FOnConsoleLockUpdate write FOnConsoleLockUpdate;
property OnConsoleGet: TFDConsoleGetEvent read FOnConsoleGet write FOnConsoleGet;
property OnSpoolPut: TFDConsolePutEvent read FOnSpoolPut write FOnSpoolPut;
property OnGetText: TFDGetTextEvent read FOnGetText write FOnGetText;
property OnReleaseText: TFDGetTextEvent read FOnReleaseText write FOnReleaseText;
property OnPause: TFDPauseEvent read FOnPause write FOnPause;
property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
property BeforeScript: TNotifyEvent read FBeforeScript write FBeforeScript;
property AfterScript: TNotifyEvent read FAfterScript write FAfterScript;
property OnError: TFDErrorEvent read FOnError write FOnError;
property BeforeExecute: TNotifyEvent read FBeforeExecute write FBeforeExecute;
property AfterExecute: TNotifyEvent read FAfterExecute write FAfterExecute;
end;
function FDKeywordMatch(const AStr, AMatch: String; AOptLength: Integer): Boolean;
function FDScriptCommandRegistry(): TFDScriptCommandRegistry;
implementation
uses
FireDAC.Stan.Factory, FireDAC.Stan.Consts;
var
FScriptCommandRegistry: TFDScriptCommandRegistry = nil;
{-------------------------------------------------------------------------------}
function FDKeywordMatch(const AStr, AMatch: String; AOptLength: Integer): Boolean;
begin
if Length(AStr) > Length(AMatch) then
Result := False
else begin
Result := StrLComp(PChar(AStr), PChar(AMatch), AOptLength) = 0;
if Result and (Length(AStr) > AOptLength) then
Result := StrLComp(PChar(AStr) + AOptLength, PChar(AMatch) + AOptLength,
Length(AStr) - AOptLength) = 0;
end;
end;
{-------------------------------------------------------------------------------}
function FDScriptCommandRegistry(): TFDScriptCommandRegistry;
begin
if FScriptCommandRegistry = nil then
FScriptCommandRegistry := TFDScriptCommandRegistry.Create;
Result := FScriptCommandRegistry;
end;
{-------------------------------------------------------------------------------}
function UpperCh(const ACh: Char): Char;
begin
if FDInSet(ACh, ['a' .. 'z']) then
Result := Char(Word(ACh) xor $0020)
else
Result := ACh;
end;
{-------------------------------------------------------------------------------}
{ TFDScriptCommand }
{-------------------------------------------------------------------------------}
constructor TFDScriptCommand.Create(AParser: TFDScriptParser;
AEngine: TFDScript);
begin
inherited Create;
FParser := AParser;
FEngine := AEngine;
FEngineIntf := AEngine as IFDScriptEngineIntf;
if FEngine <> nil then
FEngine.SetCurrentCommand(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDScriptCommand.Destroy;
begin
if (FEngine <> nil) and (FEngine.CurrentCommand = Self) then
FEngine.SetCurrentCommand(nil);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
{$IFDEF FireDAC_MONITOR}
function TFDScriptCommand.Dump(): String;
begin
Result := '<incompleted>';
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
class function TFDScriptCommand.Help(): String;
begin
Result := '';
end;
{-------------------------------------------------------------------------------}
class procedure TFDScriptCommand.Keywords(AKwds: TStrings);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
function TFDScriptCommand.Parse(const AKwd: String): Boolean;
begin
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptCommand.Execute;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptCommand.Validate;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptCommand.AbortJob(const AWait: Boolean);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
{ TFDScriptCommandRegistry }
{-------------------------------------------------------------------------------}
constructor TFDScriptCommandRegistry.Create;
begin
inherited Create;
FCommands := TFDClassList.Create;
FKeywords := TFDStringList.Create;
end;
{-------------------------------------------------------------------------------}
destructor TFDScriptCommandRegistry.Destroy;
begin
FDFreeAndNil(FCommands);
FDFreeAndNil(FKeywords);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDScriptCommandRegistry.GetCount: Integer;
begin
Result := FCommands.Count;
end;
{-------------------------------------------------------------------------------}
function TFDScriptCommandRegistry.GetCommand(AIndex: Integer): TFDScriptCommandClass;
begin
Result := TFDScriptCommandClass(FCommands[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptCommandRegistry.AddCommand(ACommand: TFDScriptCommandClass);
var
i: Integer;
oKwds: TFDStringList;
begin
FCommands.Add(ACommand);
FKeywords.Sorted := False;
oKwds := TFDStringList.Create;
try
ACommand.Keywords(oKwds);
for i := 0 to oKwds.Count - 1 do
FKeywords.AddPtr(oKwds[i], ACommand);
finally
FDFree(oKwds);
end;
end;
{-------------------------------------------------------------------------------}
function TFDScriptCommandRegistry.LookupCommand(const AStr: String;
out ACommand: TFDScriptCommandClass): TFDScriptCommandLookupRes;
var
L, H, I, C, j, iStrLen: Integer;
sKwd: String;
begin
FKeywords.Sorted := True;
Result := ucNone;
ACommand := nil;
iStrLen := Length(AStr);
L := 0;
H := FKeywords.Count - 1;
while L <= H do begin
I := (L + H) shr 1;
// 1 2 3 4 5 6
// kwd: AAAA AAAA AAAA AAaa AAaa AAaa
// str: AA AAAA AAAAA AA AAA AAAA
// res: part exact none short short exact
sKwd := FKeywords[I];
C := 0;
j := 1;
Result := ucNone;
while j <= iStrLen do begin
// 3
if j > Length(sKwd) then begin
Result := ucNone;
Break;
end;
C := Ord(sKwd[j]) - Ord(AStr[j]);
if j = iStrLen then begin
if C = 0 then
if j < Length(sKwd) then
// 4
if FDInSet(sKwd[j + 1], ['a' .. 'z']) then
Result := ucShort
// 1
else begin
Result := ucPartial;
if not FDInSet(sKwd[j + 1], ['a' .. 'z', 'A' .. 'Z', '0' .. '9']) then
C := 1;
end
// 2
else
Result := ucExact
else if (C = 32) and FDInSet(sKwd[j], ['a' .. 'z']) then begin
// 5
if j < Length(sKwd) then
Result := ucShort
// 6
else
Result := ucExact;
C := 0;
end
else
Result := ucNone;
end
else
if not ((C = 0) or (C = 32) and FDInSet(sKwd[j], ['a' .. 'z'])) then begin
Result := ucNone;
Break;
end
else
C := 0;
Inc(j);
end;
if C < 0 then
L := I + 1
else begin
H := I - 1;
if C = 0 then
L := I;
end;
end;
if Result in [ucShort, ucExact] then
ACommand := TFDScriptCommandClass(FKeywords.Ptrs[L]);
end;
{-------------------------------------------------------------------------------}
{ TFDScriptParser }
{-------------------------------------------------------------------------------}
constructor TFDScriptParser.Create(AFileName: String; AParentCommand: TFDScriptCommand;
AText: TFDTextFile; AOptions: TFDScriptOptions);
begin
inherited Create;
FFileName := AFileName;
FParentCommand := AParentCommand;
FText := AText;
FBeginningOfLine := True;
FScriptOptions := AOptions;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.InternalGetBookmark: Integer;
begin
Result := Integer(FText.Position);
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.InternalSetBookmark(ABmk: Integer);
begin
FText.Position := ABmk;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.InternalGetChar: Char;
begin
if not FText.ReadChar(Result) then
Result := #0;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.InternalExtractString(ABmk1, ABmk2: Integer): String;
begin
Result := FText.ExtractString(ABmk1, ABmk2);
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.GetChar;
begin
FCh := InternalGetChar;
if FCh <> #0 then begin
Inc(FTotalSize);
if FDInSet(FCh, [#13, #10]) then
FBeginningOfLine := True
else if FBeginningOfLine then
FBeginningOfLine := False;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.UnGetChar;
begin
SetBookmark(GetBookmark - 1);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetBookmark: Integer;
begin
Result := InternalGetBookmark;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.SetBookmark(ABmk: Integer);
begin
if ABmk > 0 then begin
Inc(FTotalSize, ABmk - 1 - InternalGetBookmark);
InternalSetBookmark(ABmk - 1);
GetChar;
end
else begin
Inc(FTotalSize, ABmk - InternalGetBookmark);
InternalSetBookmark(ABmk);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.SkipWSLF;
begin
while FDInSet(FCh, [' ', #9, #13, #10]) do
GetChar;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.SkipWS;
begin
while FDInSet(FCh, [' ', #9]) do
GetChar;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.InternalGetString(AAllowQuote, AAllowDoubleQuote,
ARequired, AIgnoreSep: Boolean; ASet: TFDCharSet): String;
var
i1, i2: Integer;
iQuoted, iSep, iLen: Integer;
ucCS: String;
begin
SkipWS;
i1 := GetBookmark - 1;
iLen := 2;
if AAllowDoubleQuote and (FCh = '"') then begin
iQuoted := 1;
GetChar;
while not FDInSet(FCh, [#0, #13, #10]) do begin
if FCh = '"' then begin
GetChar;
if FCh <> '"' then
Break;
end;
GetChar;
end;
end
else if AAllowQuote and (FCh = '''') then begin
iQuoted := 2;
GetChar;
while not FDInSet(FCh, [#0, #13, #10]) do begin
if FCh = '''' then begin
GetChar;
if FCh <> '''' then
Break;
end;
GetChar;
end;
end
else begin
ucCS := UpperCase(ScriptOptions.ActualCommandSeparator);
iQuoted := 0;
iSep := 1;
while (FCh <> #0) and not FDInSet(FCh, ASet) do begin
if ARequired then
GetChar;
if not AIgnoreSep then begin
if UpperCh(FCh) = ucCS[iSep] then
Inc(iSep)
else
iSep := 1;
if iSep > Length(ucCS) then begin
iLen := Length(ucCS) + 1;
Break;
end;
end;
if not ARequired then
GetChar;
end;
end;
i2 := GetBookmark - iLen;
if iQuoted <> 0 then begin
Inc(i1);
Dec(i2);
end;
if i2 < i1 then
Result := ''
else begin
if FCh = #0 then
Inc(i2);
Result := ExtractString(i1, i2);
end;
if iQuoted = 1 then
Result := StringReplace(Result, '""', '"', [rfReplaceAll])
else if iQuoted = 2 then
Result := StringReplace(Result, '''''', '''', [rfReplaceAll]);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetUCWord: String;
begin
Result := InternalGetString(False, False, False, False, [#0..#255] -
['a'..'z', 'A'..'Z', '0'..'9', '_', '$', '#']);
Result := UpperCase(Result);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetIdentifier: String;
begin
Result := InternalGetString(False, True, False, False, [#0..#255] -
['a'..'z', 'A'..'Z', '0'..'9', '_', ':', '.', '#', '@', '$']);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetLine: String;
begin
Result := InternalGetString(True, True, False, False, [#13, #10, #0]);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetString(ARequired: Boolean = False): String;
begin
Result := InternalGetString(True, True, ARequired, False, [' ', #9, #13, #10, #0]);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetStringInFull: String;
begin
Result := InternalGetString(True, True, False, True, [' ', #9, #13, #10, #0]);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetOnOfChar(ADef: Char): Integer;
var
ucS: String;
begin
ucS := Trim(UpperCase(GetString()));
if ucS = 'OFF' then
Result := -1
else if ucS = 'ON' then
Result := Ord(ADef)
else begin
if Length(ucS) <> 1 then
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrStrSize1, []);
if FDInSet(ucS[1], ['A'..'Z', '0'..'9', ' ', #9, #13, #10]) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrStrNotAlphaNum, []);
Result := Ord(ucS[1]);
end;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetOnOff: Integer;
var
ucS: String;
begin
ucS := GetUCWord;
if ucS = 'OFF' then
Result := -1
else if ucS = 'ON' then
Result := 1
else begin
Result := 0;
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrSetArgInvalid, []);
end;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetNumber(ADef: Integer): Integer;
var
ucS: String;
begin
ucS := GetUCWord;
if ucS = 'OFF' then
Result := -1
else if ucS = 'ON' then
Result := ADef
else
try
Result := StrToInt(ucS);
except
Result := 0;
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrSetArgInvalid, []);
end;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.ExtractString(ABmk1, ABmk2: Integer): String;
begin
Result := InternalExtractString(ABmk1, ABmk2);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetEOL(AFirstCh: Char): Boolean;
begin
Result := False;
case ScriptOptions.FileEndOfLine of
{$IFDEF MSWINDOWS}
elDefault,
{$ENDIF}
elWindows:
if AFirstCh = #13 then begin
GetChar;
Result := FDInSet(FCh, [#10, #0]);
if not Result then
UnGetChar
end
else if AFirstCh = #10 then
Result := True;
{$IFDEF POSIX}
elDefault,
{$ENDIF}
elPosix:
if AFirstCh = #10 then
Result := True;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.InvalidSyntax;
begin
FDException(nil, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrInvalidSyntax,
[FLastKwd]);
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.CreateScriptCommand(ACmdClass: TFDScriptCommandClass;
AEngine: TFDScript; const AKwd: String): TFDScriptCommand;
begin
Result := ACmdClass.Create(Self, AEngine);
try
FLastKwd := AKwd;
if not Result.Parse(AKwd) then
FDFreeAndNil(Result);
except
FDFree(Result);
raise;
end;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.CreateSQLCommand(var ABeginBmk, ALastBmk, AEndBmk: Integer;
AEngine: TFDScript; var ACommand: TFDScriptCommand): Boolean;
var
lEmpty: Boolean;
sSQL: String;
i: Integer;
begin
AEndBmk := ALastBmk - 2;
// check command is empty or not
lEmpty := (AEndBmk = -1) or (ABeginBmk >= AEndBmk);
if not lEmpty then begin
sSQL := ExtractString(ABeginBmk, AEndBmk);
lEmpty := True;
for i := 1 to Length(sSQL) do
if sSQL[i] > ' ' then begin
lEmpty := False;
Break;
end;
end;
// if empty command, then continue to parse
if lEmpty then begin
FDFreeAndNil(ACommand);
ABeginBmk := GetBookmark;
AEndBmk := -1;
Result := False;
end
// ... otherwise exit from loop
else begin
if ACommand = nil then
ACommand := FScriptCommandRegistry.DefaultSQLCommandClass.Create(Self, AEngine);
ACommand.Parse(ExtractString(ABeginBmk, AEndBmk));
Result := True;
end;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.ExtractCommand(AEngine: TFDScript): TFDScriptCommand;
var
lInComment2, lInStr, lInStr2, lInName, lCmdSep, lAlpha: Boolean;
iInComment1, iBraceLevel, iLastBmk, iBeginBmk, iEndBmk, i: Integer;
ucS, ucCS, s, sPgStr2Delim: String;
oCmdClass: TFDScriptCommandClass;
rPos: TPoint;
begin
iInComment1 := 0;
lInComment2 := False;
lInStr := False;
lInStr2 := False;
lInName := False;
iBraceLevel := 0;
iBeginBmk := GetBookmark;
iEndBmk := -1;
Result := nil;
ucCS := ScriptOptions.ActualCommandSeparator;
ASSERT(ucCS <> '');
FPrep := AEngine.FPrep;
rPos.X := 0;
rPos.Y := 0;
while True do begin
FWasBeginningOfLine := FBeginningOfLine;
GetChar;
if (FCh <> #0) and (FLineNumber = 0) then begin
FLineNumber := 1;
FLineNumberPos := FText.Position - 1;
end;
if AEngine.Finished then begin
FDFreeAndNil(Result);
Exit;
end;
if (FCh > ' ') and (rPos.X = 0) and (rPos.Y = 0) then begin
rPos := Position;
Dec(rPos.X);
end;
iLastBmk := GetBookmark;
case FCh of
'(':
if (iInComment1 = 0) and not lInComment2 and not lInStr and not lInStr2 and not lInName then begin
Inc(iBraceLevel);
Continue;
end;
')':
if (iInComment1 = 0) and not lInComment2 and not lInStr and not lInStr2 and not lInName then begin
Dec(iBraceLevel);
Continue;
end;
'/':
if (iInComment1 = 0) and not lInComment2 and not lInStr and not lInStr2 and not lInName then begin
GetChar;
if FCh = '*' then begin
Inc(iInComment1);
Continue;
end
else if (ucCS = '/') or (ucCS = ';') then begin
SetBookmark(iLastBmk);
// if SQL or PL/SQL command, then extract it
if FWasBeginningOfLine and
CreateSQLCommand(iBeginBmk, iLastBmk, iEndBmk, AEngine, Result) then
Break;
end
else
SetBookmark(iLastBmk);
end;
#0:
begin
if ((Result = nil) or (Result.ClassType = FScriptCommandRegistry.DefaultSQLCommandClass) or
(Result.ClassType = FScriptCommandRegistry.DefaultPLSQLCommandClass)) then begin
// if SQL or PL/SQL command, then extract it
Inc(iLastBmk);
CreateSQLCommand(iBeginBmk, iLastBmk, iEndBmk, AEngine, Result);
end;
Break;
end;
'*':
begin
GetChar;
if not lInComment2 and not lInStr and not lInStr2 and not lInName and (FCh = '/') then begin
if iInComment1 > 0 then
Dec(iInComment1);
Continue;
end
else
SetBookmark(iLastBmk);
end;
'-':
begin
GetChar;
if (iInComment1 = 0) and not lInStr and not lInStr2 and not lInName and (FCh = '-') then begin
lInComment2 := True;
Continue;
end
else
SetBookmark(iLastBmk);
end;
'''':
if (iInComment1 = 0) and not lInComment2 and not lInName and not lInStr2 then begin
lInStr := not lInStr;
Continue;
end;
'"':
if (iInComment1 = 0) and not lInComment2 and not lInStr and not lInStr2 then begin
lInName := not lInName;
Continue;
end;
'$':
if (iInComment1 = 0) and not lInComment2 and not lInName and not lInStr and
(AEngine.GetRDBMSKind = TFDRDBMSKinds.PostgreSQL) then begin
GetChar;
if not FDInSet(FCh, ['0' .. '9']) then begin
s := InternalGetString(False, False, False, True, ['$', #13, #10]);
if FCh <> '$' then
SetBookmark(iLastBmk)
else
if not lInStr2 then begin
sPgStr2Delim := s;
lInStr2 := True;
Continue;
end
else if s = sPgStr2Delim then begin
sPgStr2Delim := '';
lInStr2 := False;
Continue;
end;
end;
end;
#13, #10:
if GetEOL(FCh) then begin
Inc(FLineNumber);
FLineNumberPos := FText.Position;
if (iInComment1 = 0) and lInComment2 then
lInComment2 := False;
Continue;
end;
'\':
if (iInComment1 = 0) and not lInComment2 and lInStr and
// only MySQL and SQL Anywhere support C-style escape sequences
// in string literals
(AEngine.GetRDBMSKind in [TFDRDBMSKinds.MySQL, TFDRDBMSKinds.SQLAnywhere]) then begin
GetChar;
Continue;
end;
end;
if (iInComment1 = 0) and not lInComment2 and not lInStr and not lInStr2 and not lInName and (iBraceLevel = 0) then begin
// check for command separator:
// 1) first char the same and
// 2) either non alpha, either it is at start of line
lCmdSep := False;
if ((FCh = ucCS[1]) or FDInSet(FCh, ['a' .. 'z']) and (Chr(Ord(FCh) - 32) = ucCS[1])) and
(not FDInSet(ucCS[1], ['A'..'Z', '0'..'9', '_']) or FWasBeginningOfLine) and (
(Result = nil) or (ucCS <> ';') or
(Result.ClassType <> FScriptCommandRegistry.DefaultPLSQLCommandClass) or
(AEngine.GetRDBMSKind = TFDRDBMSKinds.PostgreSQL)) then begin
lCmdSep := True;
for i := 1 to Length(ucCS) do begin
if ucCS[i] <> UpperCh(FCh) then begin
lCmdSep := False;
Break;
end;
GetChar;
end;
// if alpha-numeric separator, then it must end by spaces
if FDInSet(ucCS[1], ['A'..'Z', '0'..'9', '_']) and not FDInSet(FCh, [' ', #9, #13, #10, #0]) then
lCmdSep := False;
// if SQL or PL/SQL command, then extract it
if lCmdSep then begin
if FCh <> #0 then
UnGetChar;
if CreateSQLCommand(iBeginBmk, iLastBmk, iEndBmk, AEngine, Result) then
Break
end
else
SetBookmark(iLastBmk);
end;
// check for non SQL command
ucS := '';
if not lCmdSep and (Result = nil) then begin
lAlpha := FDInSet(FCh, ['A' .. 'Z', 'a' .. 'z']);
while True do begin
ucS := ucS + UpperCh(FCh);
case FScriptCommandRegistry.LookupCommand(ucS, oCmdClass) of
ucNone:
begin
if Length(ucS) > 1 then
SetBookmark(iLastBmk);
ucS := '';
Break;
end;
ucPartial:
GetChar;
ucShort,
ucExact:
begin
GetChar;
if not lAlpha or
not FDInSet(FCh, ['A'..'Z', 'a'..'z', '0'..'9', '_', '$', '#', '-']) then begin
Result := CreateScriptCommand(oCmdClass, AEngine, ucS);
if Result = nil then
UnGetChar;
Break;
end;
end;
end;
end;
if Result <> nil then
Break;
end;
// check for SQL programming language command
if not lCmdSep and (Result = nil) and ((ucS <> '') or FDInSet(FCh, ['A'..'Z', 'a'..'z'])) then begin
if ucS = '' then
ucS := GetUCWord
else
GetChar;
if (AEngine.GetRDBMSKind = TFDRDBMSKinds.Oracle) and ((ucS = 'BEGIN') or (ucS = 'DECLARE')) then
Result := FScriptCommandRegistry.DefaultPLSQLCommandClass.Create(Self, AEngine)
else if (AEngine.GetRDBMSKind = TFDRDBMSKinds.Firebird) and (ucS = 'EXECUTE') then begin
SkipWSLF;
ucS := GetUCWord;
if ucS = 'BLOCK' then
Result := FScriptCommandRegistry.DefaultPLSQLCommandClass.Create(Self, AEngine);
end
else if not (AEngine.GetRDBMSKind in [TFDRDBMSKinds.MSSQL, TFDRDBMSKinds.SQLAnywhere]) and
((ucS = 'CREATE') or (ucS = 'RECREATE')) then begin
SkipWSLF;
ucS := GetUCWord;
if (AEngine.GetRDBMSKind in [TFDRDBMSKinds.Interbase, TFDRDBMSKinds.Firebird]) and (ucS = 'DATABASE') then begin
FScriptCommandRegistry.LookupCommand('CREATE DATABASE', oCmdClass);
if oCmdClass <> nil then
Result := oCmdClass.Create(Self, AEngine)
else
Result := FScriptCommandRegistry.DefaultSQLCommandClass.Create(Self, AEngine);
end
else begin
if ucS = 'OR' then begin
SkipWSLF;
ucS := GetUCWord;
if (ucS = 'REPLACE') or (ucS = 'ALTER') then begin
SkipWSLF;
ucS := GetUCWord;
end;
end;
if (ucS = 'PROCEDURE') or (ucS = 'FUNCTION') or (ucS = 'PACKAGE') or
(ucS = 'TYPE') or (ucS = 'TRIGGER') or (ucS = 'VARIABLE') then
Result := FScriptCommandRegistry.DefaultPLSQLCommandClass.Create(Self, AEngine);
end;
end
else
Result := FScriptCommandRegistry.DefaultSQLCommandClass.Create(Self, AEngine);
if not FDInSet(FCh, [' ', #9, #0]) then
UnGetChar;
end;
end;
end;
// assign command position
if Result <> nil then
Result.FPosition := rPos;
// if echo is on, then output command
if (AEngine.Status <> ssValidating) and (
(ScriptOptions.EchoCommands = ecAll) or
(ScriptOptions.EchoCommands = ecSQL) and (Result <> nil) and
((Result.ClassType = FScriptCommandRegistry.DefaultSQLCommandClass) or
(Result.ClassType = FScriptCommandRegistry.DefaultPLSQLCommandClass))) then begin
s := ExtractString(iBeginBmk, GetBookmark);
if (ScriptOptions.EchoCommandTrim > 0) and (Length(s) > ScriptOptions.EchoCommandTrim) then
s := Copy(s, 1, ScriptOptions.EchoCommandTrim) + ' ...';
AEngine.ConPut(s, soEcho);
end;
// skip stream to the next line
GetChar;
SkipWS;
if FDInSet(FCh, [#13, #10]) and GetEOL(FCh) then begin
Inc(FLineNumber);
FLineNumberPos := FText.Position;
end
else if FCh <> #0 then
UnGetChar;
end;
{-------------------------------------------------------------------------------}
function TFDScriptParser.GetPosition: TPoint;
begin
if FLineNumber > 0 then
Result := Point(Integer(FText.Position - FLineNumberPos), FLineNumber - 1)
else
Result := Point(0, 0);
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptParser.SetPosition(const AValue: TPoint);
var
i: Integer;
p: TPoint;
begin
p := Position;
if (p.X = AValue.X) and (p.Y = AValue.Y) then
Exit;
FText.Position := 0;
FLineNumber := 0;
FLineNumberPos := 0;
FBeginningOfLine := False;
if AValue.Y >= 0 then begin
i := 0;
while i < AValue.Y do begin
GetChar;
if FCh = #0 then
Break
else begin
if FLineNumber = 0 then begin
FLineNumber := 1;
FLineNumberPos := FText.Position - 1;
end;
if FDInSet(FCh, [#13, #10]) and GetEOL(FCh) then begin
Inc(FLineNumber);
FLineNumberPos := FText.Position;
Inc(i);
end;
end;
end;
i := 0;
while i < AValue.X do begin
GetChar;
if FCh = #0 then
Break
else begin
if FLineNumber = 0 then begin
FLineNumber := 1;
FLineNumberPos := FText.Position - 1;
end;
if FDInSet(FCh, [#13, #10]) then begin
UnGetChar;
Break;
end;
end;
Inc(i);
end;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDScriptOptions }
{-------------------------------------------------------------------------------}
constructor TFDScriptOptions.Create(AOwner: TPersistent);
begin
inherited Create;
FOwner := AOwner;
Reset;
end;
{-------------------------------------------------------------------------------}
function TFDScriptOptions.GetOwner: TPersistent;
begin
Result := FOwner;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptOptions.Reset;
begin
FCommitEachNCommands := 0;
FAutoPrintParams := False;
FEchoCommands := ecSQL;
FEchoCommandTrim := 50;
FFeedbackCommands := True;
FFeedbackScript := True;
FColumnHeadings := True;
FMaxBytesToPrintLongs := 80;
FConsoleOutput := True;
FSpoolOutput := smNone;
FTiming := True;
FBreakOnError := False;
FIgnoreError := False;
FDropNonexistObj := True;
FCommandSeparator := '';
FParamArraySize := 1;
FPageSize := 24;
FDefaultScriptPath := '';
FMacroExpand := True;
FTrimConsole := False;
FTrimSpool := True;
FVerify := False;
FDefaultDataPath := '';
FLineSize := 0;
FFileEncoding := ecDefault;
FFileEndOfLine := elDefault;
FDriverID := '';
FClientLib := '';
FCharacterSet := '';
FSQLDialect := 0;
FRaisePLSQLErrors := False;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptOptions.Assign(Source: TPersistent);
begin
if Source is TFDScriptOptions then begin
FCommitEachNCommands := TFDScriptOptions(Source).FCommitEachNCommands;
FAutoPrintParams := TFDScriptOptions(Source).FAutoPrintParams;
FEchoCommands := TFDScriptOptions(Source).FEchoCommands;
FFeedbackCommands := TFDScriptOptions(Source).FFeedbackCommands;
FFeedbackScript := TFDScriptOptions(Source).FFeedbackScript;
FColumnHeadings := TFDScriptOptions(Source).FColumnHeadings;
FMaxBytesToPrintLongs := TFDScriptOptions(Source).FMaxBytesToPrintLongs;
FConsoleOutput := TFDScriptOptions(Source).FConsoleOutput;
FSpoolOutput := TFDScriptOptions(Source).FSpoolOutput;
FSpoolFileName := TFDScriptOptions(Source).FSpoolFileName;
FTiming := TFDScriptOptions(Source).FTiming;
FBreakOnError := TFDScriptOptions(Source).FBreakOnError;
FIgnoreError := TFDScriptOptions(Source).FIgnoreError;
FDropNonexistObj := TFDScriptOptions(Source).FDropNonexistObj;
FCommandSeparator := TFDScriptOptions(Source).FCommandSeparator;
FActualCommandSeparator := TFDScriptOptions(Source).FActualCommandSeparator;
FParamArraySize := TFDScriptOptions(Source).FParamArraySize;
FPageSize := TFDScriptOptions(Source).FPageSize;
FEchoCommandTrim := TFDScriptOptions(Source).FEchoCommandTrim;
FDefaultScriptPath := TFDScriptOptions(Source).FDefaultScriptPath;
FMacroExpand := TFDScriptOptions(Source).FMacroExpand;
FTrimConsole := TFDScriptOptions(Source).FTrimConsole;
FTrimSpool := TFDScriptOptions(Source).FTrimSpool;
FVerify := TFDScriptOptions(Source).FVerify;
FDefaultDataPath := TFDScriptOptions(Source).FDefaultDataPath;
FLineSize := TFDScriptOptions(Source).FLineSize;
FFileEncoding := TFDScriptOptions(Source).FFileEncoding;
FFileEndOfLine := TFDScriptOptions(Source).FFileEndOfLine;
FDriverID := TFDScriptOptions(Source).FDriverID;
FClientLib := TFDScriptOptions(Source).FClientLib;
FCharacterSet := TFDScriptOptions(Source).FCharacterSet;
FSQLDialect := TFDScriptOptions(Source).FSQLDialect;
FRaisePLSQLErrors := TFDScriptOptions(Source).FRaisePLSQLErrors;
end
else
inherited Assign(Source);
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptOptions.SetCommandSeparator(const AValue: String);
begin
if FCommandSeparator <> AValue then begin
FCommandSeparator := AValue;
FActualCommandSeparator := UpperCase(Trim(AValue));
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScriptOptions.SetDriverID(const AValue: String);
begin
if FDriverID <> AValue then begin
FDriverID := AValue;
if (FOwner <> nil) and (FOwner is TFDScript) then
TFDScript(FOwner).FRDBMSKind := TFDRDBMSKinds.Unknown;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDSQLScript }
{-------------------------------------------------------------------------------}
constructor TFDSQLScript.Create(Collection: TCollection);
begin
inherited Create(Collection);
FSQL := TFDStringList.Create;
TFDStringList(FSQL).TrailingLineBreak := False;
end;
{-------------------------------------------------------------------------------}
destructor TFDSQLScript.Destroy;
begin
FDFreeAndNil(FSQL);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDSQLScript.GetDisplayName: string;
begin
if FName <> '' then
Result := FName
else
Result := inherited GetDisplayName;
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLScript.Assign(ASource: TPersistent);
begin
if ASource is TFDSQLScript then begin
FName := TFDSQLScript(ASource).Name;
FSQL.SetStrings(TFDSQLScript(ASource).SQL);
end
else
inherited Assign(ASource);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLScript.SetSQL(const AValue: TStrings);
begin
FSQL.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
{ TFDSQLScripts }
{-------------------------------------------------------------------------------}
constructor TFDSQLScripts.Create(AScript: TFDScript);
begin
inherited Create(AScript, TFDSQLScript);
end;
{-------------------------------------------------------------------------------}
function TFDSQLScripts.GetItems(AIndex: Integer): TFDSQLScript;
begin
Result := TFDSQLScript(inherited Items[AIndex]);
end;
{-------------------------------------------------------------------------------}
procedure TFDSQLScripts.SetItems(AIndex: Integer;
const AValue: TFDSQLScript);
begin
inherited Items[AIndex] := AValue;
end;
{-------------------------------------------------------------------------------}
function TFDSQLScripts.Add: TFDSQLScript;
begin
Result := TFDSQLScript(inherited Add);
end;
{-------------------------------------------------------------------------------}
function TFDSQLScripts.FindScript(const AName: String): TFDSQLScript;
var
i: Integer;
begin
Result := nil;
for i := 0 to Count - 1 do
if AnsiCompareText(Items[i].Name, AName) = 0 then begin
Result := Items[i];
Break;
end;
end;
{-------------------------------------------------------------------------------}
{ TFDScript }
{-------------------------------------------------------------------------------}
constructor TFDScript.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCallStack := TFDStringList.Create;
FScriptOptions := TFDScriptOptions.Create(Self);
FTable := TFDDatSTable.Create;
FParams := TFDParams.CreateRefCounted(GetParamsOwner);
FMacros := TFDMacros.CreateRefCounted(GetParamsOwner);
FArguments := TFDStringList.Create;
FAllSpools := TFDStringList.Create;
FPrep := TFDPhysPreprocessor.Create;
FPrep.MacrosRead := FMacros;
FPrep.Instrs := [piExpandMacros];
FSQLScripts := TFDSQLScripts.Create(Self);
FOptionsIntf := TFDOptionsContainer.Create(Self, TFDFetchOptions,
TFDBottomUpdateOptions, TFDBottomResourceOptions, GetParentOptions);
FLock := TCriticalSection.Create;
FDScriptCommandRegistry();
if FDIsDesigning(Self) then
Connection := FDFindDefaultConnection(Self);
end;
{-------------------------------------------------------------------------------}
destructor TFDScript.Destroy;
begin
CloseSpool;
Connection := nil;
FOptionsIntf := nil;
FDFreeAndNil(FSQLScripts);
FDFreeAndNil(FCallStack);
FDFreeAndNil(FScriptOptions);
FParams.RemRef;
FParams := nil;
FMacros.RemRef;
FMacros := nil;
FDFreeAndNil(FArguments);
FDFreeAndNil(FTable);
FDFreeAndNil(FAllSpools);
FDFreeAndNil(FPrep);
FDFreeAndNil(FLock);
inherited Destroy;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetParamsOwner: TPersistent;
begin
Result := Self;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.Notification(AComponent: TComponent; AOperation: TOperation);
begin
inherited Notification(AComponent, AOperation);
if AOperation = opRemove then
if FScriptDialog = AComponent then
ScriptDialog := nil
else if FConnection = AComponent then
Connection := nil
else if FTransaction = AComponent then
Transaction := nil;
end;
{-------------------------------------------------------------------------------}
// IFDStanObject
function TFDScript.GetName: TComponentName;
begin
if Name = '' then
Result := '$' + IntToHex(Integer(Self), 8)
else
Result := Name;
Result := Result + ': ' + ClassName;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetParent: IFDStanObject;
begin
if FConnection = nil then
Result := nil
else
Result := FConnection as IFDStanObject;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.AfterReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.BeforeReuse;
begin
// nothing
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetOwner(const AOwner: TObject;
const ARole: TComponentName);
begin
// nothing
end;
{-------------------------------------------------------------------------------}
// IFDStanOptions
procedure TFDScript.GetParentOptions(var AOpts: IFDStanOptions);
begin
if FConnection <> nil then
AOpts := FConnection.OptionsIntf;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetFetchOptions: TFDFetchOptions;
begin
Result := OptionsIntf.FetchOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetFetchOptions(const Value: TFDFetchOptions);
begin
OptionsIntf.FetchOptions.Assign(Value);
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetFormatOptions: TFDFormatOptions;
begin
Result := OptionsIntf.FormatOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetFormatOptions(const Value: TFDFormatOptions);
begin
OptionsIntf.FormatOptions.Assign(Value);
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetResourceOptions: TFDResourceOptions;
begin
Result := OptionsIntf.ResourceOptions;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetResourceOptions(const Value: TFDResourceOptions);
begin
OptionsIntf.ResourceOptions.Assign(Value);
end;
{-------------------------------------------------------------------------------}
// IFDStanErrorHandler
procedure TFDScript.HandleException(const AInitiator: IFDStanObject;
var AException: Exception);
var
oInit: IFDStanObject;
begin
oInit := AInitiator;
if Status in [ssValidating, ssRunning] then begin
if AInitiator = nil then
oInit := Self as IFDStanObject;
if Assigned(FOnError) then
FOnError(Self, oInit as TObject, AException);
end;
if (Connection <> nil) and (AException <> nil) then
(Connection as IFDStanErrorHandler).HandleException(oInit, AException);
end;
{-------------------------------------------------------------------------------}
// etc
type
__TFDCustomConnection = class(TFDCustomConnection)
end;
procedure TFDScript.SetConnection(const AValue: TFDCustomConnection);
begin
if FConnection <> nil then
__TFDCustomConnection(FConnection).UnRegisterClient(Self);
InternalReleaseConnection;
FConnection := AValue;
if FConnection <> nil then begin
__TFDCustomConnection(FConnection).RegisterClient(Self, DoConnectChanged);
FConnection.FreeNotification(Self);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetTransaction(const AValue: TFDCustomTransaction);
begin
FTransaction := AValue;
if FTransaction <> nil then
FTransaction.FreeNotification(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.DoConnectChanged(Sender: TObject; Connecting: Boolean);
begin
if not Connecting then
InternalReleaseConnection;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetSQLScripts(const AValue: TFDSQLScripts);
begin
FSQLScripts.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetScriptOptions(const AValue: TFDScriptOptions);
begin
FScriptOptions.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetArguments(const AValue: TStrings);
begin
FArguments.SetStrings(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetParams(const AValue: TFDParams);
begin
FParams.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetMacros(const AValue: TFDMacros);
begin
FMacros.Assign(AValue);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetScriptDialog(const AValue: TFDGUIxScriptDialog);
begin
if FScriptDialog <> nil then
FScriptDialog.RemoveFreeNotification(Self);
FScriptDialog := AValue;
if FScriptDialog <> nil then
FScriptDialog.FreeNotification(Self);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ConGet(const APrompt: String;
var AResult: String);
var
oDlg: IFDGUIxScriptDialog;
begin
if Assigned(FOnConsoleGet) then
FOnConsoleGet(Self, APrompt, AResult)
else if GetScriptDialogIntf(oDlg) then
oDlg.Input(APrompt, AResult);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ConPause(const APrompt: String);
var
oDlg: IFDGUIxScriptDialog;
begin
if Assigned(FOnPause) then
FOnPause(Self, APrompt)
else if GetScriptDialogIntf(oDlg) then
oDlg.Pause(APrompt);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ConPut(const AMsg: String; AKind: TFDScriptOutputKind);
var
sCon: String;
sSpool: String;
oDlg: IFDGUIxScriptDialog;
begin
if ScriptOptions.ConsoleOutput then begin
if ScriptOptions.TrimConsole then
sCon := TrimRight(AMsg)
else
sCon := AMsg;
if Assigned(FOnConsolePut) then
FOnConsolePut(Self, sCon, AKind);
if GetScriptDialogIntf(oDlg) then
oDlg.Output(sCon, AKind);
end;
if ScriptOptions.SpoolOutput <> smNone then begin
if ScriptOptions.TrimSpool then
sSpool := TrimRight(AMsg)
else
sSpool := AMsg;
if Assigned(FOnSpoolPut) then
FOnSpoolPut(Self, sSpool, AKind);
if FSpool <> nil then
FSpool.WriteLine(sSpool);
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ConLockUpdate;
begin
if ScriptOptions.ConsoleOutput then
if Assigned(FOnConsoleLockUpdate) then
FOnConsoleLockUpdate(Self, True);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ConUnlockUpdate;
begin
if ScriptOptions.ConsoleOutput then
if Assigned(FOnConsoleLockUpdate) then
FOnConsoleLockUpdate(Self, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.GetText(const AFileName: String; AMode: TFDScriptTextMode;
out AText: TFDTextFile);
var
s: String;
oSQL: TFDSQLScript;
begin
AText := nil;
if Assigned(FOnGetText) then
FOnGetText(Self, AFileName, AMode, AText);
if AText = nil then begin
s := ExpandString(AFileName);
oSQL := SQLScripts.FindScript(s);
if oSQL <> nil then
AText := TFDTextFile.Create(TStringStream.Create(oSQL.SQL.Text,
TEncoding.Unicode), True, True, False, ecUTF16, elWindows)
else if AMode in [smWriteReset, smWriteAppend] then begin
if ExtractFileExt(s) = '' then
s := s + '.log';
AText := TFDTextFile.Create(s, False, AMode = smWriteAppend,
ScriptOptions.FileEncoding, ScriptOptions.FileEndOfLine);
end
else begin
if not FileExists(s) and (ExtractFileExt(s) = '') then
s := s + '.sql';
if (ExtractFilePath(s) = '') and (ScriptOptions.DefaultScriptPath <> '') then
s := FDNormPath(ScriptOptions.DefaultScriptPath) + s;
AText := TFDTextFile.Create(s, True, False,
ScriptOptions.FileEncoding, ScriptOptions.FileEndOfLine);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ReleaseText(const AFileName: String; AMode: TFDScriptTextMode;
var AText: TFDTextFile);
var
s: String;
oSQL: TFDSQLScript;
begin
if AText = nil then
Exit;
if AMode in [smWriteReset, smWriteAppend] then begin
s := ExpandString(AFileName);
oSQL := SQLScripts.FindScript(s);
if oSQL <> nil then begin
AText.Position := 0;
oSQL.SQL.LoadFromStream(AText.Stream, TEncoding.Unicode);
end;
end;
if Assigned(FOnReleaseText) then
FOnReleaseText(Self, AFileName, AMode, AText);
if AText <> nil then
FDFreeAndNil(AText);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ExecuteHostCommand(const ACommand: String);
var
lDefault: Boolean;
begin
if Assigned(FOnHostCommand) then begin
lDefault := False;
FOnHostCommand(Self, ACommand, lDefault);
end
else
lDefault := True;
if lDefault then
FDShell(ACommand, S_FD_LComp_PScr);
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetCallStack: TStrings;
var
oCmd: TFDScriptCommand;
begin
FCallStack.Clear;
FLock.Enter;
try
oCmd := FCurrentCommand;
while oCmd <> nil do begin
FCallStack.Insert(0, Format('%s (line %d)',
[oCmd.Parser.FileName, oCmd.Parser.LineNumber]));
oCmd := oCmd.Parser.ParentCommand;
end;
finally
FLock.Leave;
end;
Result := FCallStack;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetScriptDialogIntf(out AIntf: IFDGUIxScriptDialog): Boolean;
begin
Result := FScriptDialogVisible and (FScriptDialog <> nil);
if Result then
AIntf := FScriptDialog as IFDGUIxScriptDialog;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetTotalErrors: Integer;
begin
Result := FTotalErrors;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetTotalJobDone: Integer;
begin
Result := FTotalJobDone;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetTotalJobSize: Integer;
begin
Result := FTotalJobSize;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetTotalPct10Done: Integer;
begin
Result := FTotalPct10Done;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetIsRunning: Boolean;
begin
Result := FStatus in [ssValidating, ssRunning];
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.RequestStop;
begin
AbortJob();
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.SetCurrentCommand(const ACommand: TFDScriptCommand);
var
iPct10Done: Integer;
begin
FLock.Enter;
try
if (ACommand <> nil) and (ACommand.Parser <> nil) then
FTotalJobDone := ACommand.Parser.TotalSize
else if (FCurrentCommand <> nil) and (FCurrentCommand.Parser <> nil) then
FTotalJobDone := FCurrentCommand.Parser.TotalSize;
FCurrentCommand := ACommand;
finally
FLock.Leave;
end;
if FTotalJobSize = 0 then begin
if ACommand <> nil then begin
Inc(FTotalPct10Done);
Progress;
if FTotalPct10Done >= 1000 then
FTotalPct10Done := 0;
end;
end
else begin
iPct10Done := Integer((Int64(FTotalJobDone) * Int64(1000)) div Int64(FTotalJobSize));
if FTotalPct10Done <> iPct10Done then begin
FTotalPct10Done := iPct10Done;
Progress;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.UpdateCommandSeparator;
var
oConnMeta: IFDPhysConnectionMetadata;
begin
if ScriptOptions.CommandSeparator = '' then
if FConnectionIntf <> nil then begin
FConnectionIntf.CreateMetadata(oConnMeta);
ScriptOptions.FActualCommandSeparator := UpperCase(Trim(oConnMeta.CommandSeparator));
end
else
ScriptOptions.FActualCommandSeparator := ';';
end;
{-------------------------------------------------------------------------------}
{$HINTS OFF}
function TFDScript.SetupArguments: TStrings;
var
i, iName, iCode: Integer;
oMac: TFDMacro;
begin
Result := TFDStringList.Create;
i := 0;
while i <= Macros.Count - 1 do begin
Val(Macros[i].Name, iName, iCode);
if iCode = 0 then begin
Result.Add(Macros[i].Name + '=' + Macros[i].AsRaw);
FDFree(Macros[i]);
end
else
Inc(i);
end;
for i := 0 to Arguments.Count - 1 do begin
oMac := Macros.Add;
oMac.Name := IntToStr(i + 1);
oMac.AsRaw := Arguments[i];
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.RestoreArguments(AArgs: TStrings);
var
i, iName, iCode: Integer;
oMac: TFDMacro;
begin
i := 0;
while i <= Macros.Count - 1 do begin
Val(Macros[i].Name, iName, iCode);
if iCode = 0 then
FDFree(Macros[i])
else
Inc(i);
end;
for i := 0 to AArgs.Count - 1 do begin
oMac := Macros.Add;
oMac.Name := AArgs.KeyNames[i];
oMac.AsRaw := AArgs.ValueFromIndex[i];
end;
FDFree(AArgs);
end;
{$HINTS ON}
{-------------------------------------------------------------------------------}
function TFDScript.InternalExecute(AParser: TFDScriptParser;
ARealExecute: Boolean; AAll: Boolean): Boolean;
var
oCmd: TFDScriptCommand;
dwStartTime: DWORD;
dwExecTime: DWORD;
sFeedback: String;
iStartErrors: Integer;
iExecErrors: Integer;
i: Integer;
oPrevArgs: TStrings;
oDlg: IFDGUIxScriptDialog;
oSaveOpts: TFDScriptOptions;
begin
if AAll and Assigned(FBeforeScript) then
FBeforeScript(Self);
if (FDScriptCommandRegistry().FCommands.Count = 0) or
(FDScriptCommandRegistry().FDefaultSQLCommandClass = nil) or
(FDScriptCommandRegistry().FDefaultPLSQLCommandClass = nil) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrNoCmds, []);
oSaveOpts := nil;
if AParser.ParentCommand = nil then begin
Finished := False;
if ARealExecute then
FStatus := ssRunning
else
FStatus := ssValidating;
if AAll and ARealExecute then begin
FAllSpools.Clear;
ProcessedAfterCommit := 0;
end;
FTotalJobDone := 0;
if not ARealExecute then
FTotalJobSize := 0;
FTotalErrors := 0;
if (Connection <> nil) and Connection.Connected then
CheckCommand
else
UpdateCommandSeparator;
FScriptDialogVisible := False;
if AAll and (FScriptDialog <> nil) then begin
oDlg := FScriptDialog as IFDGUIxScriptDialog;
oDlg.Show;
FScriptDialogVisible := True;
end;
if AAll then begin
oSaveOpts := TFDScriptOptions.Create(Self);
oSaveOpts.Assign(ScriptOptions);
end;
end;
Progress;
oPrevArgs := SetupArguments;
if AAll and ARealExecute then
UpdateSpool;
if AAll and ARealExecute and ScriptOptions.FeedbackScript and (AParser.FileName <> '') then
ConPut('Running script [' + AParser.FileName + '] ...', soScript);
dwStartTime := TThread.GetTickCount();
iStartErrors := FTotalErrors;
try
try
while not Finished do begin
oCmd := nil;
try
try
oCmd := AParser.ExtractCommand(Self);
if oCmd = nil then
Break
else if not Finished then
if ARealExecute then
oCmd.Execute()
else
oCmd.Validate();
except
on E: Exception do begin
if not ScriptOptions.IgnoreError then begin
Inc(FTotalErrors);
if E is EFDDBEngineException then
for i := 0 to EFDDBEngineException(E).ErrorCount - 1 do
if i = 0 then
ConPut('ERROR: ' + EFDDBEngineException(E).Errors[i].Message, soError)
else
ConPut(EFDDBEngineException(E).Errors[i].Message, soError)
else
ConPut('ERROR: ' + E.Message, soError);
if ScriptOptions.BreakOnError then
Finished := True;
if not AAll or ScriptOptions.BreakOnError then
raise;
end;
end;
end;
finally
FDFree(oCmd);
end;
if not AAll then
Finished := True;
end;
except
if FStatus in [ssRunning, ssValidating] then
FStatus := ssFinishWithErrors;
raise;
end;
finally
if AAll and ARealExecute then
CheckCommit(True);
dwExecTime := TThread.GetTickCount() - dwStartTime;
iExecErrors := FTotalErrors - iStartErrors;
Result := iExecErrors = 0;
RestoreArguments(oPrevArgs);
if AAll and ARealExecute and ScriptOptions.FeedbackScript and (AParser.FileName <> '') then begin
sFeedback := 'Script [' + AParser.FileName + '] finished';
if iExecErrors = 0 then
sFeedback := sFeedback + ' without errors'
else if iExecErrors = 1 then
sFeedback := sFeedback + ' with [1] error'
else
sFeedback := sFeedback + ' with [' + IntToStr(iExecErrors) + '] errors';
if ScriptOptions.Timing then
sFeedback := sFeedback + Format(' [%.2d:%.2d:%.2d.%.3d]', [
(dwExecTime div 3600000) mod 60, (dwExecTime div 60000) mod 60,
(dwExecTime div 1000) mod 60, dwExecTime mod 1000]);
sFeedback := sFeedback + '.';
ConPut(sFeedback, soScript);
ConPut('', soSeparator);
end;
if AParser.ParentCommand = nil then begin
Finished := True;
if FStatus in [ssRunning, ssValidating] then
if FTotalErrors = 0 then
FStatus := ssFinishSuccess
else
FStatus := ssFinishWithErrors;
if not ARealExecute then begin
FTotalJobSize := AParser.TotalSize;
FTotalPct10Done := 1000;
end;
if AAll then
CloseSpool;
Progress;
if GetScriptDialogIntf(oDlg) then
oDlg.Hide;
if AAll then begin
ScriptOptions.Assign(oSaveOpts);
FDFree(oSaveOpts);
end;
if AAll and Assigned(FAfterScript) then
FAfterScript(Self);
end;
end;
end;
{-------------------------------------------------------------------------------}
function TFDScript.InternalExecute(ARealExecute: Boolean; AAll: Boolean): Boolean;
var
oText: TFDTextFile;
oParser: TFDScriptParser;
oWait: IFDGUIxWaitCursor;
sName: String;
lUsePosition: Boolean;
begin
if Assigned(FBeforeExecute) then
FBeforeExecute(Self);
if not FDGUIxSilent then begin
FDCreateInterface(IFDGUIxWaitCursor, oWait);
oWait.StartWait;
end;
try
if Connection = nil then
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ClntDbNotDefined, [Name]);
FRDBMSKind := TFDRDBMSKinds.Unknown;
lUsePosition := False;
if SQLScriptFileName <> '' then begin
sName := SQLScriptFileName;
GetText(SQLScriptFileName, smRead, oText);
end
else if SQLScripts.Count > 0 then begin
sName := SQLScripts[0].Name;
GetText(sName, smRead, oText);
lUsePosition := not AAll;
end
else
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrNoScript, [Name]);
try
oParser := TFDScriptParser.Create(sName, nil, oText, ScriptOptions);
try
if lUsePosition then
oParser.Position := FPosition;
Result := InternalExecute(oParser, ARealExecute, AAll);
finally
if lUsePosition then
FPosition := oParser.Position;
FDFree(oParser);
end;
finally
ReleaseText(sName, smRead, oText);
end;
finally
if not FDGUIxSilent then
oWait.StopWait;
if Assigned(FAfterExecute) then
FAfterExecute(Self);
end;
end;
{-------------------------------------------------------------------------------}
function TFDScript.ExecuteAll: Boolean;
begin
Result := InternalExecute(True, True);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ExecuteStep: Boolean;
begin
Result := InternalExecute(True, False);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ValidateAll: Boolean;
begin
Result := InternalExecute(False, True);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ValidateStep: Boolean;
begin
Result := InternalExecute(False, False);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ExecuteAll(AParser: TFDScriptParser): Boolean;
begin
Result := InternalExecute(AParser, True, True);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ExecuteStep(AParser: TFDScriptParser): Boolean;
begin
Result := InternalExecute(AParser, True, False);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ValidateAll(AParser: TFDScriptParser): Boolean;
begin
Result := InternalExecute(AParser, False, True);
end;
{-------------------------------------------------------------------------------}
function TFDScript.ValidateStep(AParser: TFDScriptParser): Boolean;
begin
Result := InternalExecute(AParser, False, False);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ExecuteFile(const AFileName: String);
begin
SQLScripts.Clear;
SQLScriptFileName := AFileName;
ValidateAll;
if Status = ssFinishSuccess then
ExecuteAll;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ExecuteFile(const AFileName: String; const AArguments: array of String);
var
i: Integer;
begin
Arguments.Clear;
for i := Low(AArguments) to High(AArguments) do
Arguments.Add(AArguments[i]);
ExecuteFile(AFileName);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ExecuteScript(const AScript: TStrings);
begin
SQLScripts.Clear;
SQLScripts.Add.SQL := AScript;
SQLScriptFileName := '';
ValidateAll;
if Status = ssFinishSuccess then
ExecuteAll;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.ExecuteScript(const AScript: TStrings; const AArguments: array of String);
var
i: Integer;
begin
Arguments.Clear;
for i := Low(AArguments) to High(AArguments) do
Arguments.Add(AArguments[i]);
ExecuteScript(AScript);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.AbortJob(const AWait: Boolean = False);
begin
if FStatus in [ssValidating, ssRunning] then
FStatus := ssAborted;
Finished := True;
if FCommandIntf <> nil then
FCommandIntf.AbortJob(AWait);
if CurrentCommand <> nil then
CurrentCommand.AbortJob(AWait);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.Progress;
var
oDlg: IFDGUIxScriptDialog;
begin
if Assigned(FOnProgress) then
FOnProgress(Self);
if GetScriptDialogIntf(oDlg) then
oDlg.Progress(Self as IFDGUIxScriptDialogInfoProvider);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.CloseSpool;
begin
if ScriptOptions.SpoolOutput = smOnReset then
ReleaseText(FLastSpoolFileName, smWriteReset, FSpool)
else
ReleaseText(FLastSpoolFileName, smWriteAppend, FSpool);
FLastSpoolFileName := '';
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.UpdateSpool;
begin
if ScriptOptions.SpoolOutput = smNone then
CloseSpool
else begin
if ScriptOptions.SpoolFileName <> FLastSpoolFileName then
CloseSpool;
if (FSpool = nil) and (ScriptOptions.SpoolFileName <> '') then begin
if ScriptOptions.SpoolOutput = smOnReset then
GetText(ScriptOptions.SpoolFileName, smWriteReset, FSpool)
else
GetText(ScriptOptions.SpoolFileName, smWriteAppend, FSpool);
FLastSpoolFileName := ScriptOptions.SpoolFileName;
FAllSpools.Add(FLastSpoolFileName);
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.CheckCommand;
begin
if (FConnectionIntf = nil) or (FConnectionIntf.State <> csConnected) then
OpenConnection('');
if (FConnectionIntf = nil) or (FConnectionIntf.State <> csConnected) then
FDException(Self, [S_FD_LComp, S_FD_LComp_PScr], er_FD_ScrNotLogged, []);
ASSERT(FCommandIntf <> nil);
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.CheckCommit(AForce: Boolean);
begin
if ScriptOptions.CommitEachNCommands > 0 then begin
ProcessedAfterCommit := ProcessedAfterCommit + 1;
if AForce or (ProcessedAfterCommit >= ScriptOptions.CommitEachNCommands) then begin
if Transaction <> nil then
Transaction.Commit
else
FConnectionIntf.Transaction.Commit;
ProcessedAfterCommit := 0;
end;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.CheckStartTransaction;
begin
if (ScriptOptions.CommitEachNCommands > 0) and (ProcessedAfterCommit = 0) and
((Transaction <> nil) and not Transaction.Active or
(Transaction = nil) and not FConnectionIntf.Transaction.Active) then
if Transaction <> nil then
Transaction.StartTransaction
else
FConnectionIntf.Transaction.StartTransaction;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.InternalOpenConnection(const AConnectionString: String);
var
sConnStr: String;
oObjIntf: IFDStanObject;
oConnMeta: IFDPhysConnectionMetadata;
oDef: IFDStanDefinition;
begin
if AConnectionString <> '' then begin
sConnStr := AConnectionString;
if ScriptOptions.DriverID <> '' then
sConnStr := S_FD_ConnParam_Common_DriverID + '=' +
ScriptOptions.DriverID + ';' + sConnStr;
Connection.Close;
Connection.ResultConnectionDef.Params.Clear;
Connection.ResultConnectionDef.ParseString(sConnStr);
end;
if ScriptOptions.ClientLib <> '' then begin
Connection.CheckConnectionDef;
oDef := FDPhysManager.DriverDefs.FindDefinition(Connection.Params.DriverID);
if oDef = nil then begin
oDef := FDPhysManager.DriverDefs.Add;
oDef.Name := Connection.Params.DriverID;
end;
oDef.AsString[S_FD_DrvVendorLib] := ScriptOptions.ClientLib;
end;
if ScriptOptions.CharacterSet <> '' then
Connection.ResultConnectionDef.AsString[S_FD_ConnParam_Common_CharacterSet] :=
ScriptOptions.CharacterSet;
if ScriptOptions.SQLDialect > 0 then
Connection.ResultConnectionDef.AsInteger[S_FD_ConnParam_IB_SQLDialect] :=
ScriptOptions.SQLDialect;
Connection.Open;
FConnectionIntf := FConnection.ConnectionIntf;
FConnectionIntf.ErrorHandler := Self as IFDStanErrorHandler;
FConnectionIntf.CreateCommand(FCommandIntf);
if Transaction <> nil then
FCommandIntf.Transaction := Transaction.TransactionIntf;
FCommandIntf.Options := Self as IFDStanOptions;
FCommandIntf.Macros := FMacros;
FCommandIntf.ErrorHandler := Self as IFDStanErrorHandler;
FConnectionIntf.CreateMetadata(oConnMeta);
FPrep.ConnMetadata := oConnMeta;
if Supports(FCommandIntf, IFDStanObject, oObjIntf) then begin
oObjIntf.SetOwner(Self, '');
oObjIntf := nil;
end;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.OpenConnection(const AConnectionString: String);
const
C_UROWID = '_ora_UROWID';
var
oURIMac: TFDMacro;
oCmd: IFDPhysCommand;
begin
InternalOpenConnection(AConnectionString);
// This is needed for FireDAC QA scripts. Depending on Oracle version
// in CREATE TABLE will be used either UROWID data type, either ROWID.
if GetRDBMSKind = TFDRDBMSKinds.Oracle then begin
oURIMac := Macros.FindMacro(C_UROWID);
if oURIMac = nil then begin
oURIMac := Macros.Add;
oURIMac.Name := C_UROWID;
end;
try
FConnectionIntf.CreateCommand(oCmd);
if Transaction <> nil then
oCmd.Transaction := Transaction.TransactionIntf;
oCmd.Prepare('declare r urowid; begin null; end;');
oCmd.Execute;
oURIMac.AsRaw := 'UROWID'
except
oURIMac.AsRaw := 'ROWID';
end;
end;
UpdateCommandSeparator;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.InternalReleaseConnection;
begin
if FCommandIntf <> nil then begin
FCommandIntf.AbortJob(False);
FCommandIntf.Disconnect;
FCommandIntf.Options := nil;
FCommandIntf.Params := nil;
FCommandIntf.Macros := nil;
FCommandIntf := nil;
end;
if FPrep <> nil then
FPrep.ConnMetadata := nil;
if FConnectionIntf <> nil then
if FConnection <> nil then
FConnectionIntf.ErrorHandler := FConnection as IFDStanErrorHandler
else
FConnectionIntf.ErrorHandler := nil;
FConnectionIntf := nil;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.CloseConnection;
begin
InternalReleaseConnection;
FConnection.Close;
end;
{-------------------------------------------------------------------------------}
procedure TFDScript.Disconnect(AAbortJob: Boolean = False);
begin
if AAbortJob then
AbortJob(True);
InternalReleaseConnection;
end;
{-------------------------------------------------------------------------------}
function TFDScript.ExpandString(const AValue: String): String;
begin
if ScriptOptions.MacroExpand then begin
FPrep.Source := AnsiQuotedStr(AValue, '''');
FPrep.Init;
FPrep.Execute;
Result := AnsiDequotedStr(FPrep.Destination, '''');
end
else
Result := AValue;
Result := FDExpandStr(Result);
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetRDBMSKind: TFDRDBMSKind;
begin
if FRDBMSKind = TFDRDBMSKinds.Unknown then begin
if (ScriptOptions.DriverID <> '') and ((Connection = nil) or not Connection.Connected) then
FRDBMSKind := FDManager.GetRDBMSKind(ScriptOptions.DriverID)
else if Connection <> nil then
FRDBMSKind := Connection.RDBMSKind;
end;
Result := FRDBMSKind;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetTable: TFDDatSTable;
begin
Result := FTable;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetCommandIntf: IFDPhysCommand;
begin
Result := FCommandIntf;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetConnectionIntf: IFDPhysConnection;
begin
Result := FConnectionIntf;
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetEof: Boolean;
begin
Result := (SQLScripts.Count = 0) or
(FPosition.Y > SQLScripts[0].SQL.Count - 1) or
(FPosition.Y = SQLScripts[0].SQL.Count - 1) and
(FPosition.X >= Length(SQLScripts[0].SQL[FPosition.Y]));
end;
{-------------------------------------------------------------------------------}
function TFDScript.GetIsEmpty: Boolean;
begin
Result := (SQLScripts.Count = 0) or (SQLScripts[0].SQL.Count = 0);
end;
{-------------------------------------------------------------------------------}
initialization
finalization
FDFreeAndNil(FScriptCommandRegistry);
end.
|
{ * ------------------------------------------------------------------------
* ♥ Akademia BSC © 2019 ♥
* ----------------------------------------------------------------------- * }
unit TestSortControler;
interface
uses
System.SysUtils, System.Classes, System.Diagnostics, System.TimeSpan,
TestFramework,
Model.Board,
Controler.Sort;
type
// Test methods for class TSortControler
TestTSortControler = class(TTestCase)
strict private
FBoard: TBoard;
FSortControler: TSortControler;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestExecute;
procedure TestTerminateThread;
procedure TestDispatchBoardMessage;
end;
implementation
uses
View.Board,
Mock.BoardView;
procedure TestTSortControler.SetUp;
begin
FBoard := TBoard.Create;
// TODO: Stworzyć FSortControler
// w tym celu potrzebny jest obiekt, który implementuje inteface IBoardView
// Proszę stworzyć tzw. zaślepkęm, czyki Mock, kótrzy prawie
// W mocku potrzebne będzie zwracanie liczby widocznych danych
// Mock prosze zdefinować w unit: Mock.BoardView.pas
(*
FSortControler := TSortControler.Create(FBoard, TBoardViewMock.Create);
*)
end;
procedure TestTSortControler.TearDown;
begin
(*
FSortControler.Free;
FSortControler := nil;
*)
FBoard.Free;
FBoard := nil;
end;
procedure TestTSortControler.TestExecute;
begin
// TODO: Sprawdzić metodę TSortControler.Execute
(*
Uwaga!
------
Metoda Execute generuje dane i uruchamia nowy wątek roboczy w którym
wykonywane jest sortowanie, czyli nie można od razy skończyć tego testu.
Prosze wymyśleć jak można czekać na zakończenie wątku roboczego.
Uwaga!
------
Uruchomienie testu spowoduje zawieszenie się wątku roboczego, czyli nie
można czekać w nieskończoność na jego zakończenie. Proszę ustawić timeout
w czekaniu (np. 1 sekunda)
TBorad nie jest w pełni wielowątkowy (tzw. thread-safe), ponieważ korzysta
ze wspólnej pamięci, bez dodawania sekcji bezpiecznych. Proszę zlokalizować
tą "czarną owcę" w TBoard. Prosze tutaj poniżej niapisać co to jest.
Proszę nie poprawiać błędów w TBoard.
*)
end;
procedure TestTSortControler.TestTerminateThread;
begin
// TODO: Sprawdzić działąnie metody TSortControler.TerminateThread
(*
Uwaga!!! Zadanie dla ambitnych :-)
-----
Test powinien urachamiać wątek roboczy (metoda: TSortControler.Execute), a
po odczekaniu krótkiego czasu (15ms) powinen przerywać działanie wątku
roboczego (metoda: TSortControler.TerminateThread.
*)
end;
procedure TestTSortControler.TestDispatchBoardMessage;
begin
// TODO: Sprawdzić czy po dodanu do kolejki FMessageQueue (w Model.Board.pas)
// kilku komunikatów Swap zostaną oe poprawnie obsłużone przez metodę
// DispatchBoardMessage
end;
initialization
RegisterTest(TestTSortControler.Suite);
end.
|
unit adot.VCL.Tools;
{ Definition of classes/record types:
TAppActions = class
Get all "executable" components of form (TMenu/TAction/...).
Used by automated testing framework & quick search window (available by F11).
TCanvasUtils = class
MaxFitLength / BlendRectangle and other graphic functions specific to VCL.
TControlUtils = class
ForEach, FindForm, GetShortCaption and other.
TMDIHelper<T: class> = class
FindMDIChild etc.
TVCLFileUtils = class
CopyFile without locking UI etc.
TVCLStreamUtils = class
Copy streams without locking UI etc.
}
interface
uses
adot.Types,
Winapi.ShellAPI,
Winapi.Windows,
Winapi.Messages,
Vcl.ActnList,
Vcl.ExtCtrls,
Vcl.Forms,
Vcl.Graphics,
Vcl.Menus,
Vcl.Controls,
System.Classes,
System.SysUtils,
System.Math,
System.Character,
System.Generics.Collections,
System.Generics.Defaults,
System.StrUtils,
System.Types,
System.DateUtils,
System.SyncObjs;
type
{
Screen object has event OnActiveControlChange, but it doesn't support multiple handlers.
Chaining of handlers for such event is not safe.
Objects can install handlers in one sequence and then uninstall it in different sequence, restoring
"dead" handlers as active.
To avoid of errors we use list for chaining of handlers.
}
TActiveControlListeners = class
private
class var
FList: TList<TNotifyEvent>;
FOldOnActiveControlChange: TNotifyEvent;
class property List: TList<TNotifyEvent> read FList;
class procedure ActiveControlChange(Data, Sender: TObject); static;
public
class constructor Create;
class destructor Destroy;
class function Add(AHandler: TNotifyEvent): boolean; static;
class function Exists(AHandler: TNotifyEvent): boolean; static;
class function Remove(AHandler: TNotifyEvent): boolean; static;
end;
{ Simple interface to search for MDI form of specific type. Example:
var
MVA: TMVAAvstemmingForm;
begin
MVA := TMDIHelper<TMVAAvstemmingForm>.FindMDIChild;
end; }
{ FindMDIChild etc }
TMDIHelper = class
public
class function FindMDIChild<T: TCustomForm>(ParentForm: TForm; BringToFront : Boolean = True; Sjekk: TFunc<TForm,Boolean> = nil):T; overload; static;
class function FindMDIChild<T: TCustomForm>(BringToFront: Boolean = True; Sjekk: TFunc<TForm,Boolean> = nil): T; overload; static;
class function MdiClientArea(MainForm: TForm; ScreenCoordinates: boolean): TRect; static;
end;
{ Get all "executable" components of form (TMenu/TAction/...).
Used by automated testing framework & quick search window (available by F11). }
TAppActions = class
public
type
TVerb = record
Text: string;
Obj: TComponent;
constructor Create(const AText: string; AObj: TComponent); overload;
constructor Create(const AText: string); overload;
end;
private
class function GetIntInPos(const s: string; n: integer): string; static;
class function FilterAccept(
Caption, SoekeTekst : String;
InnholdSoek : Boolean;
var Tekst : string;
var Indeks : integer;
AddedItems : TDictionary<string, boolean>
): Boolean; static;
class function IsInteger(const s: string): Boolean; static;
class function GetActionObjComparer(const ASoeketekst: string): TDelegatedComparer<TAppActions.TVerb>; static;
public
{ Both chars belong to same type (printable char, digit, space, or special char) }
class function SameCharCategory(const a, b: Char): Boolean; static;
{ TMenu, TButton, ... -> TBasicAction }
class function ComponentAction(aComponent: TComponent): TBasicAction; static;
{ Component (TMenu, TButton, ...) and/or assigned action are visible }
class function ComponentVisible(aComponent: TComponent): Boolean; static;
{ Component (TMenu, TButton, ...) and/or assigned action are enabled }
class function ComponentEnabled(aComponent: TComponent): Boolean; static;
{ Parent of TMenuItem is TMenuITem, parent of TControl is TControl, etc }
class function ComponentParent(aComponent: TComponent): TComponent; static;
{ Component (TMenu, TAction) has assigned OnClick/OnExecute }
class function ComponentExecutable(aComponent: TComponent): Boolean; static;
{ Component is enabled&visible + all parents are visible }
class function ComponentAccessible(aComponent: TComponent): Boolean; static;
{ Execute corresponding OnClick/Action.OnExecute/... for component }
class function ExecuteComponent(aComponent: TComponent): Boolean; static;
{ find all objects which can be executed (actions, menus, ...) }
class function FindFormActions(
AForm : TForm;
AExtraComponents : TStrings;
ASoeketekst : string;
AAutoAppendMenuItemsTag : integer;
AAutoAppendActionsTag : integer;
ATest : TFunc<TComponent,Boolean>
): TList<TAppActions.TVerb>;
class function MixCaptionAndHint(C: TAction): string; static;
end;
{ MaxFitLength / BlendRectangle and other graphic functions specific to VCL }
TCanvasUtils = class
public
class procedure BlendRectangle(Dst: TCanvas; const R: TRect; C: TColor; MixPercent: Byte); static;
class function MaxFitLength(const Src: string; Dst: TCanvas; WidthPixels: integer): integer; overload; static;
class function MaxFitLength(const Src: string; StartIndex,Count: integer; Dst: TCanvas; WidthPixels: integer): integer; overload; static;
end;
{ ForEach, FindForm, GetShortCaption and other }
TControlUtils = class
public
type
TControlBrkProc = reference to procedure(AControl: TControl; var ABreak: boolean);
TControlProc = reference to procedure(AControl: TControl);
class procedure SetEnabled(C: TControl; Value: Boolean; Recursive: Boolean = True); static;
class function FindParentOfClass(AControl: TControl; const AParentClass: TClass): TControl; static;
class function FindForm(C: TControl): TForm; static;
{ "file://c:\aaaa\sss\ddddddd\file.zip" -> "file://c:\aaa...\file.zip" }
class function GetShortCaption(
const Caption : string;
FixedHeadChars : integer;
FixedTailChars : integer;
Dst : TCanvas;
WidthPixels : integer;
Separator : string = '...'): string; static;
{ returns True if enumeration complete, False if canceled }
class function ForEach(AStart: TControl; ACallback: TControlBrkProc): Boolean; overload; static;
class procedure ForEach(AStart: TControl; ACallback: TControlProc); overload; static;
class function GetAll(AStart: TControl): TArray<TControl>; static;
class function FindControlAtPos(AScreenPos: TPoint): TControl; static;
class function FindControlAtMousePos: TControl; static;
class procedure HideBorder(c: TPanel); static;
end;
TWinControlUtils = class
public
class function GetReadableId(C: TWinControl): string; static;
end;
{ Copy streams without locking UI etc }
TVCLStreamUtils = class
public
{ Copy stream functions (from simple to feature-rich):
1. TStreamUtils.Copy:
uses standard Delphi streams, UI will freeze until operation is complete.
2. TVCLStreamUtils.Copy:
uses standard Delphi streams, UI will not freeze. }
class function Copy(Src,Dst: TStream; Count,BufSize: integer; ProgressProc: TCopyStreamProgressProc): int64; overload; static;
class function Copy(Src,Dst: TStream; ProgressProc: TCopyStreamProgressProc): int64; overload; static;
class function Copy(Src,Dst: TStream): int64; overload; static;
end;
{ CopyFile without locking UI etc }
TVCLFileUtils = class
public
{ Copy file functions (from simple to feature-rich):
1. TFileUtils.CopyFile:
uses standard Delphi streams, UI will freeze until operation is complete.
2. TWinFileUtils.CopyFile:
uses Windows function CopyFileEx, UI will freeze until operation is complete.
3. TVCLFileUtils.Copyfile:
uses standard Delphi streams, UI will not freeze.
4. TCopyFileProgressDlg.CopyFile:
uses either Delphi streams or CopyFileEx, UI will not freeze,
progress bar with cancel command will be available for long operations). }
class function CopyFile(
const SrcFileName,DstFileName : string;
out ErrorMessage : string;
ProgressProc : TCopyFileProgressProc): boolean; overload;
class function CopyFile(
const SrcFileName,DstFileName : string;
out ErrorMessage : string): boolean; overload;
end;
{ Debouncing of event with interval N ms means, that time between triggering of SourceEvent will at least N ms.
Most common use case: when user is editing a filter, data should not be updated too often }
TDebouncedEvent = class(TComponent)
private
class var
FInstCount: integer;
var
FSrcEvent: TNotifyEvent;
FMinInterval: integer;
FTimer: TTimer;
FSender: TObject;
FLastCallTime: TDateTime;
procedure OnTimer(Sender: TObject);
procedure EventHandler(Sender: TObject);
function GetDebouncedEvent: TNotifyEvent;
procedure CallSrcHandler(Sender: TObject);
public
constructor Create(AOwner: TComponent; AEventToDebounce: TNotifyEvent; AMinIntervalMs: integer); reintroduce;
destructor Destroy; override;
class function Debounce(AOwner: TComponent; AEventToDebounce: TNotifyEvent; AMinIntervalMs: integer): TNotifyEvent; static;
property DebouncedEvent: TNotifyEvent read GetDebouncedEvent;
property SourceEvent: TNotifyEvent read FSrcEvent;
class property InstanceCount: integer read FInstCount;
end;
TFormUtils = class
public
class procedure Activate(AForm: TForm); static;
end;
implementation
uses
adot.Collections,
adot.Tools,
adot.Tools.IO,
adot.Win.Tools;
{ MDIHelper }
class function TMDIHelper.FindMDIChild<T>(ParentForm: TForm; BringToFront: Boolean = True; Sjekk: TFunc<TForm,Boolean> = nil): T;
var
I: integer;
begin
for I := 0 to ParentForm.MDIChildcount-1 do
if (ParentForm.MDIChildren[I] is T) and (not Assigned(Sjekk) or Sjekk(ParentForm.MDIChildren[I])) then
begin
result := ParentForm.MDIChildren[I] as T;
if BringToFront then
begin
(result as TForm).Show;
(result as TForm).BringToFront;
end;
exit;
end;
result := nil;
end;
class function TMDIHelper.FindMDIChild<T>(BringToFront : Boolean = True; Sjekk: TFunc<TForm,Boolean> = nil):T;
begin
Result := FindMDIChild<T>(Application.MainForm, BringToFront, Sjekk);
end;
class function TMDIHelper.MdiClientArea(MainForm: TForm; ScreenCoordinates: boolean): TRect;
var
P1,P2: TPoint;
begin
if (MainForm = nil) or not Winapi.Windows.GetClientRect(MainForm.ClientHandle, Result) then
Exit(TRect.Empty);
P1 := TPoint.Create(0,0);
Winapi.Windows.ClientToScreen(MainForm.ClientHandle, P1);
if ScreenCoordinates then
result.Offset(P1.X, P1.Y)
else
begin
P2 := TPoint.Create(0,0);
Winapi.Windows.ClientToScreen(MainForm.Handle, P2);
result.Offset(P1.X-P2.X, P1.Y-P2.Y);
end;
end;
{ TVerb }
constructor TAppActions.TVerb.Create(const AText: string; AObj: TComponent);
begin
Text := AText;
Obj := AObj;
end;
constructor TAppActions.TVerb.Create(const AText: string);
begin
Create(AText, nil);
end;
{ TAppActions }
class function TAppActions.ComponentAction (aComponent : TComponent):TBasicAction;
begin
if aComponent is TMenuItem then
Result := TMenuItem(aComponent).Action
else if aComponent is TAction then
Result := TBasicAction(aComponent)
else if aComponent is TControl then
Result := TControl(aComponent).Action
else
Result := nil;
end;
class function TAppActions.ComponentVisible (aComponent : TComponent):Boolean;
begin
if aComponent is TMenuItem then
Result := TMenuItem(aComponent).Visible
else if aComponent is TAction then
Result := TAction(aComponent).Visible
else if aComponent is TControl then
Result := TControl(aComponent).Visible
else
Result := True;
end;
class function TAppActions.ComponentEnabled (aComponent : TComponent):Boolean;
begin
if aComponent is TMenuItem then
Result := TMenuItem(aComponent).Enabled
else if aComponent is TAction then
Result := TAction(aComponent).Enabled
else if aComponent is TControl then
Result := TControl(aComponent).Enabled
else
Result := True;
end;
class function TAppActions.ComponentParent (aComponent : TComponent):TComponent;
begin
if aComponent is TMenuItem then
Result := TMenuItem(aComponent).Parent
else if aComponent is TControl then
Result := TControl(aComponent).Parent
else
Result := nil;
end;
type
TControlHack = class (TControl);
class function TAppActions.ComponentExecutable (aComponent : TComponent) : Boolean;
begin
if aComponent is TMenuItem then
Result := Assigned (TMenuItem(aComponent).OnClick)
else if aComponent is TAction then
Result := Assigned (TAction(aComponent).OnExecute)
else if aComponent is TControl then
Result := Assigned (TControlHack(aComponent).OnClick)
else
Result := False;
end;
class function TAppActions.ComponentAccessible(aComponent: TComponent): Boolean;
var
Cmp:TComponent;
begin
Result:= False;
if aComponent = nil then
Exit;
{* Kontrollerer aComponent (enabled og visible)*}
Cmp:= aComponent;
if ComponentAction(Cmp) <> nil then
ComponentAction(Cmp).Update;
if (not ComponentEnabled(cmp)) or (not ComponentVisible(Cmp)) then
Exit;
{* Kontrollerer parents (visible) *}
Cmp:= ComponentParent (Cmp);
while Cmp <> nil do
begin
if ComponentAction(Cmp) <> nil then
ComponentAction(Cmp).Update;
if not ComponentVisible(Cmp) then
Exit;
Cmp:= ComponentParent (Cmp);
end;
Result:= True;
end;
class function TAppActions.ExecuteComponent(aComponent : TComponent): Boolean;
begin
result := Assigned(aComponent);
if result then
if (aComponent is TMenuItem) and Assigned(TMenuItem(aComponent).OnClick) then
TMenuItem(aComponent).OnClick(aComponent)
else if aComponent is TBasicAction then
TBasicAction(aComponent).Execute
else if aComponent is TControl then
TControlHack (aComponent).Click
else
result := false;
end;
class function TAppActions.SameCharCategory(const a,b: Char): Boolean;
var
f1, f2: integer;
begin
f1 :=
IfThen(a.IsWhiteSpace, 1, 0) +
IfThen(a.IsSeparator, 2, 0) +
IfThen(a.IsDigit, 4, 0) +
IfThen(a.IsLetter, 8, 0) +
IfThen(a.IsPunctuation, 16, 0) +
IfThen(a.IsSymbol, 32, 0);
f2 :=
IfThen(b.IsWhiteSpace, 1, 0) +
IfThen(b.IsSeparator, 2, 0) +
IfThen(b.IsDigit, 4, 0) +
IfThen(b.IsLetter, 8, 0) +
IfThen(b.IsPunctuation, 16, 0) +
IfThen(b.IsSymbol, 32, 0);
result := f1=f2;
end;
class function TAppActions.GetIntInPos(const s: string; n: integer): string;
var
i: Integer;
begin
for i := n to High(s) do
if not s[i].IsDigit then
begin
result := s.Substring(n, i-n);
exit;
end;
result := s.Substring(n);
end;
class function TAppActions.IsInteger(const s: string): Boolean;
var
n: integer;
begin
result := TryStrToInt(Trim(s), n);
end;
class function TAppActions.FilterAccept(
Caption, SoekeTekst : String;
InnholdSoek : Boolean;
var Tekst : string;
var Indeks : integer;
AddedItems : TDictionary<string, boolean>
): Boolean;
var
i: Integer;
RF,Num: Boolean;
b: Boolean;
begin
//Tekstlengde:= Length(Soeketekst);
Tekst:= StripHotKey(Caption);
// Sørger for at vi ikke får like elementer
if AddedItems.TryGetValue(AnsiLowerCase(Tekst), b) then
//if ListBox.Items.IndexOf(Tekst) <> -1 then
begin
Result := False;
Exit;
end;
Indeks:= Pos(AnsiLowerCase(Soeketekst), AnsiLowerCase(Tekst));
// RF:= (Indeks in [3,4]) and ErHeltall(AnsiLowercase(Soeketekst), True);
Num := IsInteger(SoekeTekst);
RF := false;
if Indeks>0 then
if Num then
RF := Pos(AnsiLowerCase('rf-'+Soeketekst), AnsiLowerCase(Tekst))>0
else
if (Pos('rf-',AnsiLowercase(Soeketekst))>0) then
RF := true;
Result :=
InnholdSoek and (Indeks <> 0) //and ((Tekstlengde > 0) or Num)
or ((not Innholdsoek) and (Indeks = 1))
or ((not Innholdsoek) and RF)
or (Indeks>1) and // example: searcrh "kost" should find "10 Kostnader"
((Tekst[Indeks-1]<'0') or (Tekst[Indeks-1]>'9')) and
TryStrToInt(Trim(Copy(Tekst,1,Indeks-1)), i)
or (Soeketekst = '');
end;
class function TAppActions.GetActionObjComparer(const ASoeketekst: string):TDelegatedComparer<TAppActions.TVerb>;
begin
// priority of items ordering:
// - items where Query and Result have same category (digit or nondigit)
// - both items starts from number - compare as numbers
// otherwise compare case insensitively as strings
result := TDelegatedComparer<TAppActions.TVerb>.Create(
function(const A,B: TAppActions.TVerb):Integer
var
c1,c2: Boolean;
n1,n2: integer;
begin
// category
c1 := (ASoeketekst<>'') and (A.Text<>'') and SameCharCategory(A.Text[Low(A.Text)], ASoeketekst[Low(ASoeketekst)]);
c2 := (ASoeketekst<>'') and (B.Text<>'') and SameCharCategory(B.Text[Low(B.Text)], ASoeketekst[Low(ASoeketekst)]);
if (c1 or c2) and (c1<>c2) then
begin
result := IfThen(c1, -1, 1);
exit;
end;
// number
if (A.Text<>'') and (B.Text<>'') and
A.Text[Low(A.Text)].IsDigit and B.Text[Low(B.Text)].IsDigit and
TryStrToInt(GetIntInPos(A.Text,Low(A.Text)), n1) and
TryStrToInt(GetIntInPos(B.Text,Low(B.Text)), n2)
then
result := n1-n2
else
result := AnsiCompareText(A.Text, B.Text);
end
);
end;
class function TAppActions.FindFormActions(
AForm : TForm;
AExtraComponents : TStrings;
ASoeketekst : string;
AAutoAppendMenuItemsTag : integer;
AAutoAppendActionsTag : integer;
ATest : TFunc<TComponent,Boolean>
): TList<TAppActions.TVerb>;
var
AutoFreeCollection: TAutoFreeCollection;
AddedItems: TDictionary<string, boolean>;
InnholdSoek: Boolean;
i: Integer;
Cmp: TComponent;
Tekst: String;
Indeks: Integer;
S: string;
begin
Assert(AForm <> nil, 'HostForm ikke satt under init.');
AddedItems := AutoFreeCollection.Add( TDictionary<string, boolean>.Create );
InnholdSoek := Trim(ASoeketekst).StartsWith('*');
while Trim(ASoeketekst).StartsWith('*') do
ASoeketekst := ASoeketekst.Replace('*', '');
result := TList<TAppActions.TVerb>.Create(GetActionObjComparer(ASoeketekst));
{ manually added components }
if AExtraComponents<>nil then
for i := 0 to AExtraComponents.Count - 1 do
if AExtraComponents.Objects[i]<>nil then
begin
Cmp := TComponent(AExtraComponents.Objects[i]);
if TAppActions.ComponentExecutable(Cmp) and
(TAppActions.ComponentAccessible(Cmp) or Assigned(ATest) and ATest(Cmp)) and
FilterAccept(AExtraComponents[i], ASoeketekst, InnholdSoek, Tekst, Indeks, AddedItems)
then
begin
result.Add(TAppActions.TVerb.Create(Tekst, AExtraComponents.Objects[i] as TComponent));
AddedItems.Add(AnsiLowerCase(Tekst), False);
end;
end;
{ components from HostForm }
if AForm<>nil then
for i:= 0 to AForm.ComponentCount-1 do
begin
Cmp := AForm.components[i];
if (AAutoAppendMenuItemsTag<>0) and (Cmp is TMenuItem) then
if (Cmp.tag = AAutoAppendMenuItemsTag) and
TAppActions.ComponentExecutable(Cmp) and
(
TAppActions.ComponentAccessible(Cmp) or
Assigned(ATest) and ATest(Cmp)
) and
FilterAccept(TMenuItem(Cmp).Caption, ASoeketekst, InnholdSoek, Tekst, Indeks, AddedItems)
then
begin
result.Add(TAppActions.TVerb.Create(Tekst, Cmp));
AddedItems.Add(AnsiLowerCase(Tekst), False);
end;
if (AAutoAppendActionsTag<>0) and (Cmp is TAction) then
if (Cmp.tag = AAutoAppendActionsTag) and
TAppActions.ComponentExecutable(Cmp) and
(
TAppActions.ComponentAccessible(Cmp) or
Assigned(ATest) and ATest(Cmp)
)
then
begin
{Hint/Caption can be modified inside of TAction.Update. That is why we call ComponentAccessible
first (it will trigger TAction.Update) and only after that we read Caption/Hint for processing }
S := MixCaptionAndHint(TAction(Cmp));
if FilterAccept(S, ASoeketekst, InnholdSoek, Tekst, Indeks, AddedItems) then
begin
result.Add(TAppActions.TVerb.Create(Tekst, AForm.components[i]));
AddedItems.Add(AnsiLowerCase(Tekst), False);
end;
end;
end;
Result.Sort;
end;
class function TAppActions.MixCaptionAndHint(C: TAction): string;
var I: integer;
begin
Result := C.Caption;
if TryStrToInt(Result, I) then
Result := Trim(Result + ' ' + C.Hint);
end;
{ TCanvasUtils }
class procedure TCanvasUtils.BlendRectangle(Dst: TCanvas; const R: TRect; C: TColor; MixPercent: Byte);
var
Bmp: TBitmap;
Blend: TBlendFunction;
begin
Bmp := TBitmap.Create;
try
Bmp.Width := 1;
Bmp.Height := 1;
Bmp.Canvas.Pixels[0,0] := C;
Blend.BlendOp := AC_SRC_OVER;
Blend.BlendFlags := 0;
Blend.SourceConstantAlpha := (50 + 255*MixPercent) Div 100;
Blend.AlphaFormat := 0;
AlphaBlend(Dst.Handle, R.Left, R.Top, R.Right-R.Left, R.Bottom-R.Top, Bmp.Canvas.Handle, 0, 0, 1, 1, Blend);
finally
Bmp.Free;
end;
end;
class function TCanvasUtils.MaxFitLength(const Src: string; StartIndex, Count: integer; Dst: TCanvas; WidthPixels: integer): integer;
var
l,r,w: integer;
begin
result := 0;
if Count <= 0 then
Exit;
l := StartIndex + 1;
r := StartIndex + Count;
while r-l>=2 do
begin
result := (r+l) shr 1;
w := Dst.TextWidth(Src.Substring(0,result));
if w=WidthPixels then
Break;
if w<WidthPixels then
l := result
else
r := result;
end;
if not (r-l>=2) then
if Dst.TextWidth(Src.Substring(0,r)) <= WidthPixels then
result := r
else
result := l;
if Dst.TextWidth(Src.Substring(0,result)) > WidthPixels then
dec(result);
if result<0 then
result := 0;
end;
class function TCanvasUtils.MaxFitLength(const Src: string; Dst: TCanvas; WidthPixels: integer): integer;
begin
result := MaxFitLength(Src, 0, Length(Src), Dst, WidthPixels);
end;
{ TControlUtils }
class procedure TControlUtils.SetEnabled(C: TControl; Value, Recursive: Boolean);
var
I: Integer;
begin
C.Enabled := Value;
if Recursive and (C is TWinControl) then
for I := 0 to TWinControl(C).ControlCount-1 do
SetEnabled(TWinControl(C).Controls[I], Value, Recursive);
end;
class function TControlUtils.ForEach(AStart: TControl; ACallback: TControlBrkProc): Boolean;
var
i: Integer;
begin
if AStart<>nil then
begin
{ check if canceled by callback function }
result := False;
ACallback(AStart, result);
if result then
Exit(False);
{ check if any subsearch canceled }
if AStart is TWinControl then
for i := TWinControl(AStart).ControlCount-1 downto 0 do
if not ForEach(TWinControl(AStart).Controls[i], ACallback) then
Exit(False);
end;
result := True;
end;
class function TControlUtils.FindControlAtMousePos: TControl;
begin
Result := FindControlAtPos(Mouse.CursorPos);
end;
function FindSubcontrolAtPos(AControl: TControl; AScreenPos, AClientPos: TPoint): TControl;
var
i: Integer;
C: TControl;
begin
Result := nil;
C := AControl;
if (C=nil) or not C.Visible or not TRect.Create(C.Left, C.Top, C.Left+C.Width, C.Top+C.Height).Contains(AClientPos) then
Exit;
Result := AControl;
if AControl is TWinControl then
for i := 0 to TWinControl(AControl).ControlCount-1 do
begin
C := FindSubcontrolAtPos(TWinControl(AControl).Controls[i], AScreenPos, AControl.ScreenToClient(AScreenPos));
if C<>nil then
Result := C;
end;
end;
class function TControlUtils.FindControlAtPos(AScreenPos: TPoint): TControl;
var
i: Integer;
f,m: TForm;
p: TPoint;
r: TRect;
begin
Result := nil;
for i := Screen.FormCount-1 downto 0 do
begin
f := Screen.Forms[i];
if f.Visible and (f.Parent=nil) and (f.FormStyle<>fsMDIChild) and
TRect.Create(f.Left, f.Top, f.Left+f.Width, f.Top+f.Height).Contains(AScreenPos)
then
Result := f;
end;
Result := FindSubcontrolAtPos(Result, AScreenPos, AScreenPos);
if (Result is TForm) and (TForm(Result).ClientHandle<>0) then
begin
WinAPI.Windows.GetWindowRect(TForm(Result).ClientHandle, r);
p := TPoint.Create(AScreenPos.X-r.Left, AScreenPos.Y-r.Top);
m := nil;
for i := TForm(Result).MDIChildCount-1 downto 0 do
begin
f := TForm(Result).MDIChildren[i];
if TRect.Create(f.Left, f.Top, f.Left+f.Width, f.Top+f.Height).Contains(p) then
m := f;
end;
if m<>nil then
Result := FindSubcontrolAtPos(m, AScreenPos, p);
end;
end;
class function TControlUtils.FindForm(C: TControl): TForm;
begin
Result := TForm(FindParentOfClass(C, TForm));
end;
class function TControlUtils.FindParentOfClass(AControl: TControl; const AParentClass: TClass): TControl;
begin
result := AControl;
while (result<>nil) and not (result is AParentClass) do
result := result.Parent;
end;
class procedure TControlUtils.ForEach(AStart: TControl; ACallback: TControlProc);
var
i: Integer;
begin
if AStart=nil then
Exit;
ACallback(AStart);
if AStart is TWinControl then
for i := TWinControl(AStart).ControlCount-1 downto 0 do
ForEach(TWinControl(AStart).Controls[i], ACallback);
end;
class function TControlUtils.GetAll(AStart: TControl): TArray<TControl>;
var
Dst: TArray<TControl>;
Count: integer;
begin
Count := 0;
SetLength(Dst, 1000);
ForEach(AStart,
procedure(C: TControl)
begin
if Count>=Length(Dst) then
SetLength(Dst, Length(Dst)*2);
Dst[Count] := C;
inc(Count);
end);
SetLength(Dst, Count);
Result := Dst;
end;
class function TControlUtils.GetShortCaption(
const Caption : string;
FixedHeadChars : integer;
FixedTailChars : integer;
Dst : TCanvas;
WidthPixels : integer;
Separator : string = '...'): string;
var
L,FixedLen: Integer;
begin
{ full caption is ok }
Result := Caption;
if Dst.TextWidth(Result) <= WidthPixels then
Exit;
{ only fixed part may fit }
Result :=
Caption.Substring(0,FixedHeadChars) +
Separator +
Caption.Substring(Length(Caption)-FixedTailChars,FixedTailChars);
FixedLen := Dst.TextWidth(Result);
if Dst.TextWidth(Result) >= WidthPixels then
Exit;
{ we have to cut some part }
Result := Caption.Substring(FixedHeadChars, Length(Caption) - FixedHeadChars - FixedTailChars);
L := TCanvasUtils.MaxFitLength(Result, Dst, WidthPixels-FixedLen);
result :=
Caption.Substring(0, FixedHeadChars+L) +
Separator +
Caption.Substring(Length(Caption)-FixedTailChars,FixedTailChars);
end;
class procedure TControlUtils.HideBorder(c: TPanel);
begin
c.BevelInner := bvNone;
c.BevelOuter := bvNone;
c.BevelKind := bkNone;
c.BorderStyle := bsNone;
end;
type
TCopyStreamsForm = class(TForm)
protected
FSrc, FDst: TStream;
FCount, FBufSize: integer;
FProgressProc: TCopyStreamProgressProc;
FLocked: boolean;
FTransferred: int64;
procedure FormShow(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure CreateParams(var Params:TCreateParams); override;
public
constructor Create(Src, Dst: TStream; Count, BufSize: integer; ProgressProc: TCopyStreamProgressProc); reintroduce;
property Transferred: int64 read FTransferred;
end;
{ TCopyStreamsForm }
constructor TCopyStreamsForm.Create(Src, Dst: TStream; Count, BufSize: integer; ProgressProc: TCopyStreamProgressProc);
begin
inherited CreateNew(nil);
{ form properties (we will try to make the form invisible/transparent) }
BorderStyle := bsNone;
Left := 0;
Top := 0;
Width := 0;
Height := 0;
OnShow := FormShow;
OnCloseQuery := FormCloseQuery;
FSrc := Src;
FDst := Dst;
FCount := Count;
FBufSize := BufSize;
FProgressProc := ProgressProc;
FLocked := True;
end;
procedure TCopyStreamsForm.CreateParams(var Params: TCreateParams);
begin
inherited;
Params.ExStyle := WS_EX_TRANSPARENT or WS_EX_TOPMOST;
end;
procedure TCopyStreamsForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
CanClose := not FLocked;
end;
procedure TCopyStreamsForm.FormShow(Sender: TObject);
begin
FLocked := True;
try
FTransferred := TStreamUtils.Copy(FSrc, FDst, FCount, FBufSize,
procedure(const Transferred: int64; var Cancel: boolean)
begin
{ user defined callback }
if Assigned(FProgressProc) then
FProgressProc(Transferred, Cancel);
{ to keep ui alive ()}
Application.ProcessMessages;
end);
finally
FLocked := False;
ModalResult := mrOk;
{ .Close mwthod will not close the form from FormShow, so we send wm_close message instead }
PostMessage(Handle, wm_close,0,0);
end;
end;
{ TVCLStreamUtils }
class function TVCLStreamUtils.Copy(Src, Dst: TStream; Count, BufSize: integer; ProgressProc: TCopyStreamProgressProc): int64;
var
LockUIForm: TCopyStreamsForm;
begin
LockUIForm := TCopyStreamsForm.Create(Src, Dst, Count, BufSize, ProgressProc);
try
LockUIForm.ShowModal;
result := LockUIForm.Transferred;
finally
LockUIForm.Free;
end;
end;
class function TVCLStreamUtils.Copy(Src, Dst: TStream; ProgressProc: TCopyStreamProgressProc): int64;
begin
result := Copy(Src, Dst, 0,0,ProgressProc);
end;
class function TVCLStreamUtils.Copy(Src, Dst: TStream): int64;
begin
result := Copy(Src, Dst, 0,0,nil);
end;
{ TVCLFileUtils }
class function TVCLFileUtils.CopyFile(
const SrcFileName, DstFileName : string;
out ErrorMessage : string;
ProgressProc : TCopyFileProgressProc): boolean;
var
AutoFreeCollection: TAutoFreeCollection;
CI: TCopyFileInfo;
Src,Dst: TStream;
begin
try
Result := True;
Src := AutoFreeCollection.Add(TFileStream.Create(SrcFileName, fmOpenRead or fmShareDenyWrite));
Dst := AutoFreeCollection.Add(TFileStream.Create(DstFileName, fmCreate));
CI.FileSize := Src.Size;
CI.SrcFileName := SrcFileName;
CI.DstFileName := DstFileName;
if not Assigned(ProgressProc) then
TVCLStreamUtils.Copy(Src, Dst)
else
begin
TVCLStreamUtils.Copy(Src, Dst,
procedure(const Transferred: int64; var Cancel: boolean)
begin
CI.Copied := Transferred;
ProgressProc(CI, Cancel);
end);
end;
except
on e: exception do
begin
Result := True;
ErrorMessage := Format('Can''t copy file "%s" to "%s": %s', [SrcFileName, DstFileName, SysErrorMessage(GetLastError)]);
end;
end;
end;
class function TVCLFileUtils.CopyFile(
const SrcFileName, DstFileName : string;
out ErrorMessage : string): boolean;
begin
result := CopyFile(SrcFileName, DstFileName, ErrorMessage, nil);
end;
{ TActiveControlListeners }
class constructor TActiveControlListeners.Create;
var
NotifyEvent: TNotifyEvent;
begin
FList := TList<TNotifyEvent>.Create;
TMethod(NotifyEvent).Code := @ActiveControlChange;
TMethod(NotifyEvent).Data := nil;
FOldOnActiveControlChange := Screen.OnActiveControlChange;
Screen.OnActiveControlChange := NotifyEvent;
end;
class destructor TActiveControlListeners.Destroy;
begin
FList.Free;
FList := nil;
Screen.OnActiveControlChange := FOldOnActiveControlChange;
FOldOnActiveControlChange := nil;
end;
class procedure TActiveControlListeners.ActiveControlChange(Data, Sender: TObject);
var
I: Integer;
begin
if Assigned(FOldOnActiveControlChange) then
FOldOnActiveControlChange(Sender);
if List <> nil then
for I := 0 to List.Count-1 do
List[I](Sender);
end;
class function TActiveControlListeners.Add(AHandler: TNotifyEvent): boolean;
begin
result := (List <> nil) and not Exists(AHandler);
if result then
List.Add(AHandler);
end;
class function TActiveControlListeners.Exists(AHandler: TNotifyEvent): boolean;
begin
result := (List <> nil) and List.Contains(AHandler);
end;
class function TActiveControlListeners.Remove(AHandler: TNotifyEvent): boolean;
begin
result := (List <> nil) and Exists(AHandler);
if result then
List.Remove(AHandler);
end;
{ TWinControlUtils }
class function TWinControlUtils.GetReadableId(C: TWinControl): string;
var
H,P: string;
begin
if C.HandleAllocated
then H := NativeUInt(C.Handle).ToString
else H := '0';
P := '$'+THex.PointerToHex(C);
result := format('%s: %s (hwnd=%s, ptr=%s)', [C.Name, C.Classname, H, P]);
end;
{ TDebouncedEvent }
constructor TDebouncedEvent.Create(AOwner: TComponent; AEventToDebounce: TNotifyEvent; AMinIntervalMs: integer);
begin
inherited Create(AOwner);
FSrcEvent := AEventToDebounce;
FMinInterval := AMinIntervalMs;
FTimer := TTimer.Create(Self);
FTimer.Interval := FMinInterval;
FTimer.OnTimer := OnTimer;
FTimer.Enabled := False;
TInterlocked.Increment(FInstCount);
end;
destructor TDebouncedEvent.Destroy;
begin
TInterlocked.Decrement(FInstCount);
Sys.FreeAndNil(FTimer);
inherited;
end;
procedure TDebouncedEvent.EventHandler(Sender: TObject);
var
ElapsedTimeMs: Int64;
begin
ElapsedTimeMs := MilliSecondsBetween(Now, FLastCallTime);
if ElapsedTimeMs >= FMinInterval then
begin
FTimer.Enabled := False;
CallSrcHandler(Sender);
end
else
begin
FSender := Sender;
if not FTimer.Enabled then
begin
FTimer.Interval := FMinInterval - ElapsedTimeMs;
FTimer.Enabled := True;
end;
end;
end;
procedure TDebouncedEvent.OnTimer(Sender: TObject);
begin
FTimer.Enabled := False;
CallSrcHandler(FSender);
end;
procedure TDebouncedEvent.CallSrcHandler(Sender: TObject);
begin
FSrcEvent(Sender);
FLastCallTime := Now;
end;
function TDebouncedEvent.GetDebouncedEvent: TNotifyEvent;
begin
result := EventHandler;
end;
class function TDebouncedEvent.Debounce(AOwner: TComponent; AEventToDebounce: TNotifyEvent; AMinIntervalMs: integer): TNotifyEvent;
begin
result := TDebouncedEvent.Create(AOwner, AEventToDebounce, AMinIntervalMs).DebouncedEvent;
end;
{ TFormUtils }
class procedure TFormUtils.Activate(AForm: TForm);
begin
if (AForm = nil) or not (AForm.Visible) then
Exit;
{ try to focus the form }
try
AForm.BringToFront;
AForm.SetFocus;
except
end;
{ BringToFront/SetFocus doesn't guarantee that control of the form gets focus.
It is possible case when two forms have Active=True/Focused=True.
We may need to focus control of active form }
if (AForm.ActiveControl <> nil) and AForm.ActiveControl.Visible and AForm.ActiveControl.Enabled then
try
AForm.ActiveControl.SetFocus;
except
end;
end;
end.
|
unit uCapturaWebcamVCL;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.Samples.Spin;
type
TForm1 = class(TForm)
btnConectar: TButton;
pnlWebcam: TPanel;
btnDesconectar: TButton;
btnGravarVideo: TButton;
btnGravarImagem: TButton;
btnConfigurar: TButton;
btnParar: TButton;
spnedtRate: TSpinEdit;
edtFileName: TEdit;
Label1: TLabel;
Label2: TLabel;
chkbPreview: TCheckBox;
SaveDialog1: TSaveDialog;
procedure btnConectarClick(Sender: TObject);
procedure btnDesconectarClick(Sender: TObject);
procedure btnConfigurarClick(Sender: TObject);
procedure chkbPreviewClick(Sender: TObject);
procedure spnedtRateChange(Sender: TObject);
procedure btnGravarImagemClick(Sender: TObject);
procedure btnGravarVideoClick(Sender: TObject);
procedure btnPararClick(Sender: TObject);
private
{ Private declarations }
HWndCaptura: HWnd;
public
{ Public declarations }
end;
function capCreateCaptureWindowA(lpszWindowName: PCHAR; dwStyle: longint;
x: integer; y: integer; nWidth: integer; nHeight: integer; ParentWin: HWnd;
nId: integer): HWnd;
stdcall external 'AVICAP32.DLL';
//function CalculaDobro(Valor: Integer): Integer;stdcall;external 'TTDLL.dll' name 'dobro';
{ Mensagem base }
const WM_CAP_START = WM_USER;
{ Conectar a WebCam }
const WM_CAP_DRIVER_CONNECT = WM_CAP_START + 10;
{ Desconectar a WebCam }
const WM_CAP_DRIVER_DISCONNECT = WM_CAP_START + 11;
{ Preview }
const WM_CAP_SET_PREVIEW = WM_CAP_START + 50;
{ Configurar frames por segundo }
const WM_CAP_SET_PREVIEWRATE = WM_CAP_START + 52;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnConectarClick(Sender: TObject);
begin
HWndCaptura := capCreateCaptureWindowA(
'Windows Video API no Delphi',
WS_CHILD or WS_VISIBLE, pnlWebCam.Left, pnlWebCam.Top,
pnlWebCam.Width, pnlWebCam.Height, pnlWebCam.Handle, 0);
if HWndCaptura <> 0 then
begin
try
SendMessage(HWndCaptura, WM_CAP_DRIVER_CONNECT, 0, 0);
SendMessage(HWndCaptura, WM_CAP_SET_PREVIEWRATE, 1000 div spnedtRate.Value , 0);
SendMessage(HWndCaptura, WM_CAP_SET_PREVIEW, Ord(chkbPreview.Checked), 0);
btnDesconectar.Enabled := True;
btnConectar.Enabled := False;
btnConfigurar.Enabled := True;
btnGravarImagem.Enabled := True;
btnGravarVideo.Enabled := True;
btnParar.Enabled := True;
except
raise;
end;
end
else
begin
MessageDlg ('Erro ao conectar ao driver da cāmera!',mtError, [mbok], 0);
btnDesconectar.Enabled := False;
btnConectar.Enabled := True;
btnGravarImagem.Enabled := False;
btnGravarVideo.Enabled := False;
btnParar.Enabled := False;
end;
end;
procedure TForm1.btnConfigurarClick(Sender: TObject);
begin
if HWndCaptura <> 0 then
SendMessage(HWndCaptura,WM_CAP_START +41, 0, 0);
end;
procedure TForm1.btnDesconectarClick(Sender: TObject);
begin
if HWndCaptura <> 0 then
begin
SendMessage(HWndCaptura, WM_CAP_DRIVER_DISCONNECT, 0, 0);
btnDesconectar.Enabled := False;
btnConectar.Enabled := True;
btnGravarImagem.Enabled := False;
btnGravarVideo.Enabled := False;
btnConfigurar.Enabled := False;
btnParar.Enabled := False;
end;
end;
procedure TForm1.btnGravarImagemClick(Sender: TObject);
begin
if HWndCaptura <> 0 then
begin
SaveDialog1.DefaultExt := 'bmp';
SaveDialog1.Filter := 'Arquivo Bitmap (*.bmp)|*.bmp';
if SaveDialog1.Execute then
SendMessage(HWndCaptura, WM_CAP_START +25, 0,
longint(pchar(SaveDialog1.FileName)));
end;
end;
procedure TForm1.btnGravarVideoClick(Sender: TObject);
begin
if HWndCaptura <> 0 then
begin
// SendMessage(HWndCaptura, WM_CAP_FILE_SET_CAPTURE_FILEA, 0,
// Longint(pchar(edtFileName.Text)));
// SendMessage(HWndCaptura, WM_CAP_SEQUENCE, 0, 0);
end;
end;
procedure TForm1.btnPararClick(Sender: TObject);
begin
// if HWndCaptura <> 0 then
// SendMessage(HWndCaptura, WM_CAP_STOP, 0, 0);
end;
procedure TForm1.chkbPreviewClick(Sender: TObject);
begin
if HWndCaptura <> 0 then
SendMessage(HWndCaptura, WM_CAP_SET_PREVIEW,
Ord(chkbPreview.Checked), 0);
end;
procedure TForm1.spnedtRateChange(Sender: TObject);
begin
if HWndCaptura <> 0 then
SendMessage(HWndCaptura, WM_CAP_SET_PREVIEWRATE, 1000 div spnedtRate.Value, 0);
end;
end.
|
unit p_draw;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, Amzi, StdCtrls, ExtCtrls;
procedure InitDrawPreds(LS: TLSEngine);
{ Function definitions for the Delphi functions that
implement the various extended predicates. }
function p_lineto(EngID: TEngID): TTFi; stdcall; export;
function p_moveto(EngID: TEngID): TTFi; stdcall; export;
function p_textout(EngID: TEngID): TTFi; stdcall; export;
function p_textheight(EngID: TEngID): TTFi; stdcall; export;
function p_textwidth(EngID: TEngID): TTFi; stdcall; export;
function p_cliprect(EngID: TEngID): TTFi; stdcall; export;
function p_rectangle(EngID: TEngID): TTFi; stdcall; export;
function p_ellipse(EngID: TEngID): TTFi; stdcall; export;
function p_pen(EngID: TEngID): TTFi; stdcall; export;
function p_font(EngID: TEngID): TTFi; stdcall; export;
function p_brush(EngID: TEngID): TTFi; stdcall; export;
var
TheCanvas: TCanvas;
LSEng: TLSEngine;
implementation
{ Logic Server initialization code that associates a Prolog
predicate with a Delphi function. For example, the first
call to AddPred associates the Delphi function p_lineto
with the predicate draw_lineto/3. }
procedure InitDrawPreds(LS: TLSEngine);
begin
LSEng := LS;
LSEng.AddPred('draw_lineto', 3, p_lineto);
LSEng.AddPred('draw_moveto', 3, p_moveto);
LSEng.AddPred('draw_textout', 4, p_textout);
LSEng.AddPred('draw_textheight', 3, p_textheight);
LSEng.AddPred('draw_textwidth', 3, p_textwidth);
LSEng.AddPred('draw_cliprect', 5, p_cliprect);
LSEng.AddPred('draw_rectangle', 5, p_rectangle);
LSEng.AddPred('draw_ellipse', 5, p_ellipse);
LSEng.AddPred('draw_pen', 3, p_pen);
LSEng.AddPred('draw_font', 4, p_font);
LSEng.AddPred('draw_brush', 3, p_brush);
end;
{ For each of the implementations, the first argument is the address
of the control that is to receive the drawing commands. The other
arguments are then specific to the operation being performed. }
{ draw_lineto/3 expects the second and third arguments to be instantiated
to integers, which are then retrieved from Prolog and passed to the
Delphi LineTo function for canvases. This same approach is used
for many of these predicates. }
function p_lineto;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
TheCanvas.LineTo(LSEng.GetIntParm(2), LSEng.GetIntParm(3));
Result := lsTrue;
end;
function p_moveto;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
TheCanvas.MoveTo(LSEng.GetIntParm(2), LSEng.GetIntParm(3));
Result := lsTrue;
end;
function p_textout;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
TheCanvas.TextOut(LSEng.GetIntParm(2), LSEng.GetIntParm(3), LSEng.GetPStrParm(4));
Result := lsTrue;
end;
{ draw_textheight/3 unifies the Prolog argument with the result
of the Delphi TextHeight function. If the Prolog argument is
an unbound variable, this function returns the value. If the
Prolog argument is bound, then the predicate succeeds or fails
depending on whether the unification succeeds or fails. }
function p_textheight;
var
N: Integer;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
N := TheCanvas.TextHeight(LSEng.GetPStrParm(2));
if LSEng.UnifyIntParm(3, N) then
Result := lstrue
else
Result := lsfalse;
end;
function p_textwidth;
var
N: Integer;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
N := TheCanvas.TextWidth(LSEng.GetPStrParm(2));
if LSEng.UnifyIntParm(3, N) then
Result := lstrue
else
Result := lsfalse;
end;
function p_cliprect;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
LSEng.UnifyIntParm(2, TheCanvas.ClipRect.Top);
LSEng.UnifyIntParm(3, TheCanvas.ClipRect.Left);
LSEng.UnifyIntParm(4, TheCanvas.ClipRect.Bottom);
LSEng.UnifyIntParm(5, TheCanvas.ClipRect.Right);
Result := lsTrue;
end;
function p_rectangle;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
TheCanvas.Rectangle(LSEng.GetIntParm(2), LSEng.GetIntParm(3), LSEng.GetIntParm(4), LSEng.GetIntParm(5));
Result := lsTrue;
end;
function p_ellipse;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
TheCanvas.Ellipse(LSEng.GetIntParm(2), LSEng.GetIntParm(3), LSEng.GetIntParm(4), LSEng.GetIntParm(5));
Result := lsTrue;
end;
function p_pen;
var
ColorNum: Longint;
ColorName: String;
PenWidth: Integer;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
Result := lsFalse;
ColorName := LSEng.GetPStrParm(2);
if (not IdentToColor(ColorName, ColorNum)) then
Exit;
PenWidth := LSEng.GetIntParm(3);
if (PenWidth < 1) then
Exit;
TheCanvas.Pen.Color := ColorNum;
TheCanvas.Pen.Width := PenWidth;
Result := lstrue;
end;
{ draw_font/4 checks each of the arguments to see if its bound
or not. If its bound, then the predicate sets the corresponding font
property. If its unbound,then it returns the current property. }
function p_font;
var
ColorNum: Longint;
ColorName: String;
Size: integer;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
if (LSEng.GetParmType(2) = pVAR) then
LSEng.UnifyAtomParm(2, TheCanvas.Font.Name)
else
TheCanvas.Font.Name := LSEng.GetPStrParm(2);
if (LSEng.GetParmType(3) = pVAR) then begin
ColorNum := TheCanvas.Font.Color;
ColorToIdent(ColorNum, ColorName);
LSEng.UnifyAtomParm(3, ColorName);
end
else begin
ColorName := LSEng.GetPStrParm(3);
if (not IdentToColor(ColorName, ColorNum)) then begin
ShowMessage('Invalid color name for font');
Result := lsFalse;
exit;
end;
TheCanvas.Font.Color := ColorNum;
end;
if (LSEng.GetParmType(4) = pVAR) then begin
Size := TheCanvas.Font.Size;
LSEng.UnifyIntParm(4, Size);
end
else begin
Size := LSEng.GetIntParm(4);
TheCanvas.Font.Size := Size;
end;
Result := lsTrue;
end;
{ draw_brush/3 maps Prolog atoms describing various styles to
Delphi brush styles. }
function p_brush;
var
ColorNum: Longint;
ColorName: String;
Style: String;
begin
LSEng.GetParm(1, dADDR, @TheCanvas);
Result := lsFalse;
ColorName := LSEng.GetPStrParm(2);
if (not IdentToColor(ColorName, ColorNum)) then
Exit;
TheCanvas.Brush.Color := ColorNum;
Style := LSEng.GetPStrParm(3);
if (Style = 'bsSolid') then TheCanvas.Brush.Style := bsSolid;
if (Style = 'bsClear') then TheCanvas.Brush.Style := bsClear;
if (Style = 'bsBDiagonal') then TheCanvas.Brush.Style := bsBDiagonal;
if (Style = 'bsFDiagonal') then TheCanvas.Brush.Style := bsFDiagonal;
if (Style = 'bsCross') then TheCanvas.Brush.Style := bsCross;
if (Style = 'bsDiagCross') then TheCanvas.Brush.Style := bsDiagCross;
if (Style = 'bsHorizontal') then TheCanvas.Brush.Style := bsHorizontal;
if (Style = 'bsVertical') then TheCanvas.Brush.Style := bsVertical;
Result := lsTrue;
end;
end.
|
unit NtUtils.Exec;
interface
uses
NtUtils.Exceptions, Winapi.ProcessThreadsApi, NtUtils.Environment,
NtUtils.Objects, Ntapi.ntdef;
type
TExecParam = (
ppParameters, ppCurrentDirectory, ppDesktop, ppToken, ppParentProcess,
ppLogonFlags, ppInheritHandles, ppCreateSuspended, ppBreakaway,
ppNewConsole, ppRequireElevation, ppShowWindowMode, ppRunAsInvoker,
ppEnvironment
);
IExecProvider = interface
function Provides(Parameter: TExecParam): Boolean;
function Application: String;
function Parameters: String;
function CurrentDircetory: String;
function Desktop: String;
function Token: IHandle;
function ParentProcess: IHandle;
function LogonFlags: Cardinal;
function InheritHandles: Boolean;
function CreateSuspended: Boolean;
function Breakaway: Boolean;
function NewConsole: Boolean;
function RequireElevation: Boolean;
function ShowWindowMode: Word;
function RunAsInvoker: Boolean;
function Environment: IEnvironment;
end;
TProcessInfo = record
ClientId: TClientId;
hxProcess, hxThread: IHandle;
end;
TExecMethod = class
class function Supports(Parameter: TExecParam): Boolean; virtual; abstract;
class function Execute(ParamSet: IExecProvider; out Info: TProcessInfo):
TNtxStatus; virtual; abstract;
end;
TExecMethodClass = class of TExecMethod;
TExecParamSet = set of TExecParam;
TDefaultExecProvider = class(TInterfacedObject, IExecProvider)
public
UseParams: TExecParamSet;
strApplication: String;
strParameters: String;
strCurrentDircetory: String;
strDesktop: String;
hxToken: IHandle;
hxParentProcess: IHandle;
dwLogonFlags: Cardinal;
bInheritHandles: Boolean;
bCreateSuspended: Boolean;
bBreakaway: Boolean;
bNewConsole: Boolean;
bRequireElevation: Boolean;
wShowWindowMode: Word;
bRunAsInvoker: Boolean;
objEnvironment: IEnvironment;
public
function Provides(Parameter: TExecParam): Boolean; virtual;
function Application: String; virtual;
function Parameters: String; virtual;
function CurrentDircetory: String; virtual;
function Desktop: String; virtual;
function Token: IHandle; virtual;
function ParentProcess: IHandle; virtual;
function LogonFlags: Cardinal; virtual;
function InheritHandles: Boolean; virtual;
function CreateSuspended: Boolean; virtual;
function Breakaway: Boolean; virtual;
function NewConsole: Boolean; virtual;
function RequireElevation: Boolean; virtual;
function ShowWindowMode: Word; virtual;
function RunAsInvoker: Boolean; virtual;
function Environment: IEnvironment; virtual;
end;
function PrepareCommandLine(ParamSet: IExecProvider): String;
implementation
uses
Winapi.WinUser;
{ TDefaultExecProvider }
function TDefaultExecProvider.Application: String;
begin
Result := strApplication;
end;
function TDefaultExecProvider.Breakaway: Boolean;
begin
if ppBreakaway in UseParams then
Result := bBreakaway
else
Result := False;
end;
function TDefaultExecProvider.CreateSuspended: Boolean;
begin
if ppCreateSuspended in UseParams then
Result := bCreateSuspended
else
Result := False;
end;
function TDefaultExecProvider.CurrentDircetory: String;
begin
if ppCurrentDirectory in UseParams then
Result := strCurrentDircetory
else
Result := '';
end;
function TDefaultExecProvider.Desktop: String;
begin
if ppDesktop in UseParams then
Result := strDesktop
else
Result := '';
end;
function TDefaultExecProvider.Environment: IEnvironment;
begin
if ppEnvironment in UseParams then
Result := objEnvironment
else
Result := TEnvironment.OpenCurrent;
end;
function TDefaultExecProvider.InheritHandles: Boolean;
begin
if ppInheritHandles in UseParams then
Result := bInheritHandles
else
Result := False;
end;
function TDefaultExecProvider.LogonFlags: Cardinal;
begin
if ppLogonFlags in UseParams then
Result := dwLogonFlags
else
Result := 0;
end;
function TDefaultExecProvider.NewConsole: Boolean;
begin
Result := bNewConsole;
end;
function TDefaultExecProvider.Parameters: String;
begin
if ppParameters in UseParams then
Result := strParameters
else
Result := '';
end;
function TDefaultExecProvider.ParentProcess: IHandle;
begin
if ppParentProcess in UseParams then
Result := hxParentProcess
else
Result := nil;
end;
function TDefaultExecProvider.Provides(Parameter: TExecParam): Boolean;
begin
Result := Parameter in UseParams;
end;
function TDefaultExecProvider.RequireElevation: Boolean;
begin
if ppRequireElevation in UseParams then
Result := bRequireElevation
else
Result := False;
end;
function TDefaultExecProvider.RunAsInvoker: Boolean;
begin
if ppRunAsInvoker in UseParams then
Result := bRunAsInvoker
else
Result := False;
end;
function TDefaultExecProvider.ShowWindowMode: Word;
begin
if ppShowWindowMode in UseParams then
Result := wShowWindowMode
else
Result := SW_SHOWNORMAL;
end;
function TDefaultExecProvider.Token: IHandle;
begin
if ppToken in UseParams then
Result := hxToken
else
Result := nil;
end;
{ Functions }
function PrepareCommandLine(ParamSet: IExecProvider): String;
begin
Result := '"' + ParamSet.Application + '"';
if ParamSet.Provides(ppParameters) and (ParamSet.Parameters <> '') then
Result := Result + ' ' + ParamSet.Parameters;
end;
end.
|
{*******************************************************}
{ }
{ Delphi DBX Framework }
{ }
{ Copyright(c) 2016 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Data.SqlConst;
interface
const
DRIVERS_KEY = 'Installed Drivers'; //TDBXPropertyNames.InstalledDrivers; { Do not localize }
CONNECTIONS_KEY = 'Installed Connections'; { Do not localize }
DRIVERNAME_KEY = 'DriverName'; { Do not localize }
HOSTNAME_KEY = 'HostName'; { Do not localize }
ROLENAME_KEY = 'RoleName'; { Do not localize }
DATABASENAME_KEY = 'Database'; //TDBXPropertyNames.Database; { Do not localize }
MAXBLOBSIZE_KEY = 'BlobSize'; { Do not localize }
VENDORLIB_KEY = 'VendorLib'; //TDBXPropertyNames.VendorLib; { Do not localize }
DLLLIB_KEY = 'LibraryName'; //TDBXPropertyNames.LibraryName; { Do not localize }
GETDRIVERFUNC_KEY = 'GetDriverFunc'; //TDBXPropertyNames.GetDriverFunc;{ Do not localize }
AUTOCOMMIT_KEY = 'AutoCommit'; { Do not localize }
BLOCKINGMODE_KEY = 'BlockingMode'; { Do not localize }
WAITONLOCKS_KEY= 'WaitOnLocks'; { Do not localize }
COMMITRETAIN_KEY = 'CommitRetain'; { Do not localize }
TRANSISOLATION_KEY = '%s TransIsolation'; { Do not localize }
SQLDIALECT_KEY = 'SqlDialect'; { Do not localize }
SQLLOCALE_CODE_KEY = 'LocaleCode'; { Do not localize }
ERROR_RESOURCE_KEY = 'ErrorResourceFile'; { Do not localize }
SQLSERVER_CHARSET_KEY = 'ServerCharSet'; { Do not localize }
CONNECTION_STRING = 'ConnectionString'; { Do not localize }
SREADCOMMITTED = 'readcommitted'; { Do not localize }
SREPEATREAD = 'repeatableread'; { Do not localize }
SDIRTYREAD = 'dirtyread'; { Do not localize }
{$EXTERNALSYM szUSERNAME}
szUSERNAME = 'USER_NAME'; { Do not localize }
szPASSWORD = 'PASSWORD'; { Do not localize }
SLocaleCode = 'LCID'; { Do not localize }
ROWSETSIZE_KEY = 'RowsetSize'; { Do not localize }
OSAUTHENTICATION = 'OS Authentication'; { Do not localize }
SERVERPORT = 'Server Port'; { Do not localize }
MULTITRANSENABLED = 'Multiple Transaction'; { Do not localize }
TRIMCHAR = 'Trim Char'; { Do not localize }
CUSTOM_INFO = 'Custom String'; { Do not localize }
CONN_TIMEOUT = 'Connection Timeout'; { Do not localize }
TDSPACKETSIZE = 'TDS Packet Size'; { Do not localize }
CLIENTHOSTNAME = 'Client HostName'; { Do not localize }
CLIENTAPPNAME = 'Client AppName'; { Do not localize }
COMPRESSED = 'Compressed'; { Do not localize }
ENCRYPTED = 'Encrypted'; { Do not localize }
PREPARESQL = 'Prepare SQL'; { Do not localize }
// DECIMALSEPARATOR = 'Decimal Separator'; { Do not localize }
resourcestring
SLoginError = 'Não é possível conectar com o banco de dados "%s"';
SMonitorActive = 'Não é possível alterar conexão no monitor ativo';
SMissingConnection = 'Faltando propriedade SQLConnection';
SDatabaseOpen = 'Não é possível executar esta operação em um Database aberto';
SDatabaseClosed = 'Não é possível executar esta operação em um Database fechado';
SMissingSQLConnection = 'Propriedade SQLConnection requerida para esta operação';
SConnectionNameMissing = 'Nome da conexão faltando ou não existe';
SEmptySQLStatement = 'Nenhuma indicação do SQL disponível';
SNoParameterValue = 'Nenhum valor para o parâmetro "%s"';
SNoParameterType = 'Nenhum tipo de parâmetro para o parâmetro "%s"';
SParameterTypes = ';Entrada;Saida;Entrada/Saída;Resultado';
SDataTypes = ';String;SmallInt;Integer;Word;Boolean;Float;Currency;BCD;Date;Time;DateTime;;;;Blob;Memo;Graphic;;;;;Cursor;';
SResultName = 'Resultado';
SNoTableName = 'Faltando propriedade TableName';
SNoSqlStatement = 'Faltando query, nome da tabela ou da procedure';
SNoDataSetField = 'Faltando propriedade DataSetField';
SNoCachedUpdates = 'Não está em modo "Cached update"';
SMissingDataBaseName = 'Database faltando propriedade';
SMissingDataSet = 'Dataset faltando propriedade';
SMissingDriverName = 'DriverName faltando propriedade';
SPrepareError = 'Erro ao executar a Query';
SObjectNameError = 'Tabela/Procedure não encontrada';
SSQLDataSetOpen = 'Incapaz de determinar nomes de campos para %s';
SNoActiveTrans = 'Não existem transações ativas';
SActiveTrans = 'Uma transação já está ativa';
SDllLoadError = 'Incapaz de Carregar %s';
SDllProcLoadError = 'Incapaz de achar Procedure %s';
SConnectionEditor = '&Editar Propriedades de Conexão';
SAddConnectionString = '&Add ConnectionString Param';
SRefreshConnectionString = 'R&efresh ConnectionString Param';
SRemoveConnectionString = '&Remove ConnectionString Param';
SCommandTextEditor = '&Editar CommandText';
SMissingDLLName = 'DLL/Shared Library Name não ajustada';
SMissingDriverRegFile = 'Arquivo de registro do Driver/Connection "%s" não encontrado';
STableNameNotFound = 'Não é possível achar TableName em CommandText';
SNoCursor = 'Cursor não retornado da Query';
SMetaDataOpenError = 'Incapaz de abrir Metadata';
SErrorMappingError = 'Erro no SQL: Mapeamento do erro falhou';
SStoredProcsNotSupported = 'Stored Procedures não suportadas pelo Servidor "%s"';
SPackagesNotSupported = 'Pacotes não são suportados pelo Servidor "%s"';
STooManyActualParam = '%s: Actual number of parameters (%d) exceeds the current number of stored procedure parameters (%d). Either uncheck the ParamCheck component property or review the parameter list content';
SDBXUNKNOWNERROR = 'Erro no DBX: Nenhum mapeamento para o Código do Erro encontrado';
//#define DBXERR_NOTSUPPORTED 0x0005
SNOTSUPPORTED = '[0x0005]: Operação Não Suportada';
SDBXError = 'Erro no dbExpress: %s';
SSQLServerError = 'Erro no Servidor de BancodeDados: %s';
SConfFileMoveError = 'Unable to move %s to %s';
SMissingConfFile = 'Arquivo de Configuração %s não encontrado';
SObjectViewNotTrue = 'ObjectView deve ser True para Tabelas com Campos Objetos';
SObjectTypenameRequired = 'Nome do tipo de Objeto requerido como valor de parâmetro';
SCannotCreateFile = 'Arquivo %s não Criado';
// used in SqlReg.pas
SDlgOpenCaption = 'Tentando abrir arquivo de log';
SDlgFilterTxt = 'Arquivo de Texto (*.txt)|*.txt|All files (*.*)|*.*';
SLogFileFilter = 'Arquivos de Log (*.log)';
SCircularProvider = 'Provedor Circular de referencias não reconhecido.';
SUnknownDataType = 'Unknown data type: %s for %s parameter';
SSaveConnectionParams = 'Save connection parameters';
SReloadConnectionParams = 'Reload connection parameters';
SGenerateClientClasses = 'Generate DataSnap client classes';
implementation
end. |
unit ORDtTmRng;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ORFn, OR2006Compatibility, ORDtTm, VA508AccessibilityManager;
type
TORfrmDateRange = class(Tfrm2006Compatibility)
lblStart: TLabel;
lblStop: TLabel;
cmdOK: TButton;
cmdCancel: TButton;
lblInstruct: TLabel;
VA508Man: TVA508AccessibilityManager;
procedure cmdOKClick(Sender: TObject);
procedure cmdCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FCalStart: TORDateBox;
FCalStop: TORDateBox;
protected
procedure Loaded; override;
end;
TORDateRangeDlg = class(TComponent)
private
FTextOfStart: string;
FTextOfStop: string;
FFMDateStart: TFMDateTime;
FFMDateStop: TFMDateTime;
FRelativeStart: string;
FRelativeStop: string;
FDateOnly: Boolean;
FRequireTime: Boolean;
FInstruction: string;
FLabelStart: string;
FLabelStop: string;
FFormat: string;
procedure SetDateOnly(Value: Boolean);
procedure SetFMDateStart(Value: TFMDateTime);
procedure SetFMDateStop(Value: TFMDateTime);
procedure SetTextOfStart(const Value: string);
procedure SetTextOfStop(const Value: string);
procedure SetRequireTime(Value: Boolean);
public
constructor Create(AOwner: TComponent); override;
function Execute: Boolean;
property RelativeStart: string read FRelativeStart;
property RelativeStop: string read FRelativeStop;
published
property DateOnly: Boolean read FDateOnly write SetDateOnly;
property FMDateStart: TFMDateTime read FFMDateStart write SetFMDateStart;
property FMDateStop: TFMDateTime read FFMDateStop write SetFMDateStop;
property Instruction: string read FInstruction write FInstruction;
property LabelStart: string read FLabelStart write FLabelStart;
property LabelStop: string read FLabelStop write FLabelStop;
property RequireTime: Boolean read FRequireTime write SetRequireTime;
property Format: string read FFormat write FFormat;
property TextOfStart: string read FTextOfStart write SetTextOfStart;
property TextOfStop: string read FTextOfStop write SetTextOfStop;
end;
procedure Register;
implementation
{$R *.DFM}
const
FMT_DATETIME = 'mmm d,yy@hh:nn';
FMT_DATEONLY = 'mmm d,yy';
{ TORDateRangeDlg --------------------------------------------------------------------------- }
constructor TORDateRangeDlg.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FInstruction := 'Enter a date range -';
FLabelStart := 'Begin Date';
FLabelStop := 'End Date';
FFormat := FMT_DATETIME;
end;
function TORDateRangeDlg.Execute: Boolean;
var
frmDateRange: TORfrmDateRange;
begin
frmDateRange := TORfrmDateRange.Create(Application);
try
with frmDateRange do
begin
FCalStart.Text := FTextOfStart;
FCalStop.Text := FTextOfStop;
if FFMDateStart > 0 then
begin
FCalStart.FMDateTime := FFMDateStart;
FCalStart.Text := FormatFMDateTime(FFormat, FFMDateStart);
end;
if FFMDateStop > 0 then
begin
FCalStop.FMDateTime := FFMDateStop;
FCalStop.Text := FormatFMDateTime(FFormat, FFMDateStop);
end;
FCalStart.DateOnly := FDateOnly;
FCalStop.DateOnly := FDateOnly;
FCalStart.RequireTime := FRequireTime;
FCalStop.RequireTime := FRequireTime;
lblInstruct.Caption := FInstruction;
lblStart.Caption := FLabelStart;
lblStop.Caption := FLabelStop;
Result := (ShowModal = IDOK);
if Result then
begin
FTextOfStart := FCalStart.Text;
FTextOfStop := FCalStop.Text;
FFMDateStart := FCalStart.FMDateTime;
FFMDateStop := FCalStop.FMDateTime;
FRelativeStart := FCalStart.RelativeTime;
FRelativeStop := FCalStop.RelativeTime;
end;
end;
finally
frmDateRange.Free;
end;
end;
procedure TORDateRangeDlg.SetDateOnly(Value: Boolean);
begin
FDateOnly := Value;
if FDateOnly then
begin
FRequireTime := False;
FMDateStart := Int(FFMDateStart);
FMDateStop := Int(FFMDateStop);
if FFormat = FMT_DATETIME then FFormat := FMT_DATEONLY;
end;
end;
procedure TORDateRangeDlg.SetRequireTime(Value: Boolean);
begin
FRequireTime := Value;
if FRequireTime then
begin
if FFormat = FMT_DATEONLY then FFormat := FMT_DATETIME;
SetDateOnly(False);
end;
end;
procedure TORDateRangeDlg.SetFMDateStart(Value: TFMDateTime);
begin
FFMDateStart := Value;
FTextOfStart := FormatFMDateTime(FFormat, FFMDateStart);
end;
procedure TORDateRangeDlg.SetFMDateStop(Value: TFMDateTime);
begin
FFMDateStop := Value;
FTextOfStop := FormatFMDateTime(FFormat, FFMDateStop);
end;
procedure TORDateRangeDlg.SetTextOfStart(const Value: string);
begin
FTextOfStart := Value;
FFMDateStart := 0;
end;
procedure TORDateRangeDlg.SetTextOfStop(const Value: string);
begin
FTextOfStop := Value;
FFMDateStop := 0;
end;
{ TORfrmDateRange --------------------------------------------------------------------------- }
procedure TORfrmDateRange.cmdOKClick(Sender: TObject);
var
ErrMsg: string;
begin
FCalStart.Validate(ErrMsg);
if ErrMsg <> '' then
begin
Application.MessageBox(PChar(ErrMsg), 'Start Date Error', MB_OK);
Exit;
end;
FCalStop.Validate(ErrMsg);
if ErrMsg <> '' then
begin
Application.MessageBox(PChar(ErrMsg), 'Stop Date Error', MB_OK);
Exit;
end;
ModalResult := mrOK;
end;
procedure TORfrmDateRange.cmdCancelClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure Register;
{ used by Delphi to put components on the Palette }
begin
RegisterComponents('CPRS', [TORDateRangeDlg]);
end;
procedure TORfrmDateRange.FormCreate(Sender: TObject);
{ Create date boxes here to avoid problem where TORDateBox is not already on component palette. }
var
item: TVA508AccessibilityItem;
id: integer;
begin
FCalStart := TORDateBox.Create(Self);
FCalStart.Parent := Self;
FCalStart.SetBounds(8, 58, 121, 21);
FCalStart.TabOrder := 0;
FCalStop := TORDateBox.Create(Self);
FCalStop.Parent := Self;
FCalStop.SetBounds(145, 58, 121, 21);
FCalStop.TabOrder := 1;
ResizeAnchoredFormToFont(self);
UpdateColorsFor508Compliance(self);
VA508Man.AccessData.Add.component := FCalStart;
item := VA508Man.AccessData.FindItem(FCalStart, False);
id:= item.INDEX;
VA508Man.AccessData[id].AccessText := 'From date/time. Press the enter key to access.';
VA508Man.AccessData.Add.component := FCalStop;
item := VA508Man.AccessData.FindItem(FCalStop, False);
id:= item.INDEX;
VA508Man.AccessData[id].AccessText := 'Through date/time. Press the enter key to access.';
end;
procedure TORfrmDateRange.FormDestroy(Sender: TObject);
begin
FCalStart.Free;
FCalStop.Free;
end;
procedure TORfrmDateRange.Loaded;
begin
inherited Loaded;
UpdateColorsFor508Compliance(Self);
end;
end.
|
unit dDXCC;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, FileUtil;
type
TExplodeArray = Array of String;
type
TDXCCRef = record
adif : Word;
pref : String[20];
name : String[100];
cont : String[6];
utc : String[12];
lat : String[10];
longit : String[10];
itu : String[20];
waz : String[20];
deleted : Word
end;
const
NotExactly = 0;
Exactly = 1;
ExNoEquals = 2;
type
TdmDXCC = class(TDataModule)
Q: TSQLQuery;
Q1: TSQLQuery;
qDXCCRef: TSQLQuery;
trQ: TSQLTransaction;
trQ1: TSQLTransaction;
trDXCCRef: TSQLTransaction;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
csDXCC : TRTLCriticalSection;
DXCCRefArray : Array of TDXCCRef;
DXCCDelArray : Array of Integer;
AmbiguousArray : Array of String;
ExceptionArray : Array of String;
function WhatSearch(call : String; date : TDateTime; var AlreadyFound : Boolean;var ADIF : Integer) : String;
function FindCountry(call : String; date : TDateTime; var ADIF : Integer; Precision : Integer = NotExactly) : Boolean; overload;
function FindCountry(call : String; date : TDateTime; var pfx, country,
cont, ITU, WAZ, offset, lat, long : String; var ADIF : Integer; Precision : Integer = NotExactly) : Boolean;
function Explode(const cSeparator, vString: String): TExplodeArray;
function DateToDDXCCDate(date : TDateTime) : String;
public
function AdifFromPfx(pfx : String) : Word;
function PfxFromADIF(adif : Word) : String;
function IsException(call : String) : Boolean;
function DXCCCount : Integer;
function IsAmbiguous(call : String) : Boolean;
function IsPrefix(pref : String; Date : TDateTime) : Boolean;
function GetCont(call : String; Date : TDateTime) : String;
function id_country(call: string; date : TDateTime; var pfx, cont, country, WAZ, offset, ITU, lat, long: string) : Word; overload;
function id_country(call : String; date : TDateTime; var pfx,country : String) : Word; overload;
function id_country(call : String; date : TDateTime) : String; overload;
function id_country(call : String; date : TDateTime; var pfx,waz,itu,cont,lat,long : String) : Word; overload;
function id_country(call : String; var lat,long : String) : Word; overload;
function CountryFromADIF(adif : Word) : String;
procedure ReloadDXCCTables;
procedure LoadDXCCRefArray;
procedure LoadAmbiguousArray;
procedure LoadExceptionArray;
end;
var
dmDXCC: TdmDXCC;
implementation
uses dData, znacmech;
type Tchyb1 = object(Tchyby) // podedim objekt a prepisu "hlaseni"
//procedure hlaseni(vzkaz,kdo:string);virtual;
end;
Pchyb1=^Tchyb1;
var
uhej : Pseznam;
sez1 : Pseznam;
chy1 : Pchyb1;
sez2 : Pseznam;
{ TdmDXCC }
procedure TdmDXCC.DataModuleCreate(Sender: TObject);
var
i : Integer;
begin
for i:=0 to ComponentCount-1 do
begin
if Components[i] is TSQLQuery then
(Components[i] as TSQLQuery).DataBase := dmData.DxccCon;
if Components[i] is TSQLTransaction then
(Components[i] as TSQLTransaction).DataBase := dmData.DxccCon
end;
InitCriticalSection(csDXCC);
chy1 := new(Pchyb1,init);
sez1 := new(Pseznam,init(dmData.AppHomeDir + 'dxcc_data/country.tab',chy1));
uhej := sez1;
sez2 := new(Pseznam,init(dmData.AppHomeDir + 'dxcc_data/country_del.tab',chy1))
end;
function TdmDXCC.id_country(call : String; Date : TDateTime) : String;
var
cont, WAZ, posun, ITU, lat, long, pfx, country: string;
begin
EnterCriticalsection(csDXCC);
try
cont := '';WAZ := '';posun := '';ITU := '';lat := '';long := '';
country := '';pfx :='';
Result := DXCCRefArray[id_country(call,date,pfx,country,cont,itu,waz,posun,lat,long)].pref
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.id_country(call : String; Date : TDateTime; var pfx,country : String) : Word;
var
cont, WAZ, posun, ITU, lat, long: string;
begin
EnterCriticalsection(csDXCC);
try
cont := '';WAZ := '';posun := '';ITU := '';lat := '';long := '';
Result := id_country(call,date,pfx,country,cont,itu,waz,posun,lat,long)
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.id_country(call : String; date : TDateTime; var pfx,waz,itu,cont,lat,long : String) : Word;
var
posun,country : string;
begin
EnterCriticalsection(csDXCC);
try
cont := '';WAZ := '';posun := '';ITU := '';lat := '';long := '';country := '';
Result := id_country(call,date,pfx,country,cont,itu,waz,posun,lat,long)
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.id_country(call : String;var lat,long : String) : Word;
var
cont, WAZ, posun, ITU, pfx, country, offset: string;
begin
EnterCriticalsection(csDXCC);
try
cont := '';WAZ := '';posun := '';ITU := ''; offset := '';
Result := id_country(call,now,pfx, cont, country, WAZ,offset, ITU, lat, long)
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.CountryFromADIF(adif : Word) : String;
begin
EnterCriticalsection(csDXCC);
try
Result := DXCCRefArray[adif].name
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.GetCont(call : String; Date : TDateTime) : String;
var
cont, WAZ, posun, ITU, lat, long, country, pfx: string;
begin
EnterCriticalsection(csDXCC);
try
cont := '';WAZ := '';posun := '';ITU := '';lat := '';long := '';
country := ''; pfx := '';
id_country(call,date,pfx,country,cont,itu,waz,posun,lat,long);
Result := Cont
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.id_country(call: string;date : TDateTime; var pfx, cont, country, WAZ,
offset, ITU, lat, long: string) : Word;
var
ADIF : Integer;
UzNasel : Boolean;
sdatum : String;
NoDXCC : Boolean;
x :longint;
sZnac : string_mdz;
sADIF : String;
begin
EnterCriticalsection(csDXCC);
try
if (length(call)=0) then
begin
exit;
end;
UzNasel := False;
ADIF := 0;
sZnac := call;
sZnac := WhatSearch(call,date,UzNasel,ADIF);
sDatum := DateToDDXCCDate(Date);// DateToStr(Datum);
x := sez2^.najdis_s2(sZnac,sDatum,NotExactly);
if x <>-1 then
begin
country := sez2^.znacka_popis_ex(x,0);
ITU := sez2^.znacka_popis_ex(x,5);
WAZ := sez2^.znacka_popis_ex(x,6);
offset := sez2^.znacka_popis_ex(x,2);
lat := sez2^.znacka_popis_ex(x,3);
long := sez2^.znacka_popis_ex(x,4);
sADIF := sez2^.znacka_popis_ex(x,11);
cont := UpperCase(sez2^.znacka_popis_ex(x,1));
NoDXCC := Pos('no DXCC',country) > 0;
if TryStrToInt(sAdif,ADIF) then
begin
if ADIF > 0 then
begin
pfx := DXCCRefArray[adif].pref;
Result := ADIF
end
else begin
if NoDXCC then
pfx := '#'
else
pfx := '!';
Result := 0
end
end
else
Result := 0;
exit
end
else begin
pfx := '!';
Result := 0
end;
x := uhej^.najdis_s2(sZnac,sDatum,NotExactly);
if x <>-1 then
begin
country := uhej^.znacka_popis_ex(x,0);
ITU := uhej^.znacka_popis_ex(x,5);
WAZ := uhej^.znacka_popis_ex(x,6);
offset := uhej^.znacka_popis_ex(x,2);
lat := uhej^.znacka_popis_ex(x,3);
long := uhej^.znacka_popis_ex(x,4);
sADIF := uhej^.znacka_popis_ex(x,11);
cont := UpperCase(uhej^.znacka_popis_ex(x,1));
NoDXCC := Pos('no DXCC',country) > 0;
if TryStrToInt(sAdif,ADIF) then
begin
if ADIF > 0 then
begin
pfx := DXCCRefArray[adif].pref;
Result := ADIF
end
else begin
if NoDXCC then
pfx := '#'
else
pfx := '!';
Result := 0
end;
exit
end
end
else begin
pfx := '!';
Result := 0
end
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.IsPrefix(pref : String; Date : TDateTime) : Boolean;
var
adif : Integer;
begin
EnterCriticalsection(csDXCC);
try
if FindCountry(pref,Date,adif,Exactly) then
Result := True
else
Result := False
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.IsAmbiguous(call : String) : Boolean;
var
i : Integer;
begin
EnterCriticalsection(csDXCC);
try
Result := False;
if Pos('/',call) < 1 then
begin
for i:=0 to Length(AmbiguousArray)-1 do
begin
if Pos(AmbiguousArray[i],call) = 1 then
begin
Result := True;
Break
end
end
end
else begin
if Length(call) < 4 then
exit;
call := call[1] + call[2] + '/' + copy(call,pos('/',call)+1,1);
for i:=0 to Length(AmbiguousArray)-1 do
begin
if AmbiguousArray[i] = call then
begin
Result := True;
Break
end
end
end
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.DXCCCount : Integer;
begin
EnterCriticalsection(csDXCC);
try
dmData.Q.Close;
if dmData.trQ.Active then
dmData.trQ.Rollback;
Q.SQL.Text := 'select count(*) from (select distinct adif from cqrtest_main where adif <> 0) as foo ';
trQ.StartTransaction;
try
Q.Open;
Result := Q.Fields[0].AsInteger
finally
Q.Close;
trQ.Rollback
end
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.IsException(call : String) : Boolean;
function IsString(call : String) : Boolean;
var
i : Integer;
begin
Result := True;
for i:=1 to Length(call) do
begin
if (call[i] in ['0'..'9']) then
begin
Result := False;
break
end
end
end;
var
y : Integer;
begin
EnterCriticalsection(csDXCC);
try
Result := False;
for y:=0 to Length(ExceptionArray)-1 do
begin
if ExceptionArray[y] = call then
begin
Result := True;
Break
end
end;
if (call = 'QRP') or (call='QRPP') or (call='P') then
Result := True;
if (IsString(call) and (Length(call) > 3)) then
Result := True
finally
LeaveCriticalsection(csDXCC)
end
end;
procedure TdmDXCC.ReloadDXCCTables;
begin
dispose(sez1,done);
dispose(sez2,done);
chy1 := new(Pchyb1,init);
sez1 := new(Pseznam,init(dmData.AppHomeDir + 'dxcc_data/country.tab',chy1));
uhej := sez1;
sez2 := new(Pseznam,init(dmData.AppHomeDir + 'dxcc_data/country_del.tab',chy1));
LoadDXCCRefArray
end;
procedure TdmDXCC.LoadDXCCRefArray;
var
adif : Integer;
begin
if trQ.Active then
trQ.Rollback;
Q.SQL.Text := 'SELECT * FROM cqrtest_common.dxcc_ref ORDER BY ADIF';
try
trQ.StartTransaction;
Q.Open;
Q.Last;
SetLength(DXCCRefArray,StrToInt(Q.FieldByName('adif').AsString)+1);
SetLength(DXCCDelArray,0);
DXCCRefArray[0].adif := 0;
DXCCRefArray[0].pref := '';
Q.First;
while not Q.Eof do
begin
adif := StrToInt(Q.FieldByName('adif').AsString);
DXCCRefArray[adif].adif := adif;
DXCCRefArray[adif].pref := Q.FieldByName('pref').AsString;
DXCCRefArray[adif].name := Q.FieldByName('name').AsString;
DXCCRefArray[adif].cont := Q.FieldByName('cont').AsString;
DXCCRefArray[adif].utc := Q.FieldByName('utc').AsString;
DXCCRefArray[adif].lat := Q.FieldByName('lat').AsString;
DXCCRefArray[adif].longit := Q.FieldByName('longit').AsString;
DXCCRefArray[adif].itu := Q.FieldByName('itu').AsString;
DXCCRefArray[adif].waz := Q.FieldByName('waz').AsString;
DXCCRefArray[adif].deleted := Q.FieldByName('deleted').AsInteger;
if DXCCRefArray[adif].deleted > 0 then
begin
SetLength(DXCCDelArray,Length(DXCCDelArray)+1);
DXCCDelArray[Length(DXCCDelArray)-1] := adif
end;
Q.Next
end;
finally
Q.Close;
trQ.Rollback
end
end;
procedure TdmDXCC.LoadAmbiguousArray;
var
f : TextFile;
s : String;
begin
SetLength(AmbiguousArray,0);
AssignFile(f,dmData.AppHomeDir+'dxcc_data'+PathDelim+'ambiguous.tab');
Reset(f);
while not Eof(f) do
begin
ReadLn(f,s);
//file has only a few lines so there is no need to SetLength in higher blocks
SetLength(AmbiguousArray,Length(AmbiguousArray)+1);
AmbiguousArray[Length(AmbiguousArray)-1]:=s
end;
CloseFile(f)
end;
procedure TdmDXCC.LoadExceptionArray;
var
f : TextFile;
s : String;
begin
SetLength(ExceptionArray,0);
AssignFile(f,dmData.AppHomeDir+'dxcc_data'+PathDelim+'exceptions.tab');
Reset(f);
while not Eof(f) do
begin
ReadLn(f,s);
//file has only a few lines so there is no need to SetLength in higher blocks
SetLength(ExceptionArray,Length(ExceptionArray)+1);
ExceptionArray[Length(ExceptionArray)-1]:=s
end;
CloseFile(f)
end;
function TdmDXCC.AdifFromPfx(pfx : String) : Word;
var
i : Integer;
begin
EnterCriticalsection(csDXCC);
try
Result := 0;
for i:=0 to Length(DXCCRefArray)-1 do
begin
if DXCCRefArray[i].pref = pfx then
begin
Result := DXCCRefArray[i].adif;
exit
end
end
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.PfxFromADIF(adif : Word) : String;
begin
EnterCriticalsection(csDXCC);
try
Result := DXCCRefArray[adif].pref
finally
LeaveCriticalsection(csDXCC)
end
end;
function TdmDXCC.Explode(const cSeparator, vString: String): TExplodeArray;
var
i: Integer;
S: String;
begin
S := vString;
SetLength(Result, 0);
i := 0;
while Pos(cSeparator, S) > 0 do
begin
SetLength(Result, Length(Result) +1);
Result[i] := Copy(S, 1, Pos(cSeparator, S) -1);
Inc(i);
S := Copy(S, Pos(cSeparator, S) + Length(cSeparator), Length(S))
end;
SetLength(Result, Length(Result) +1);
Result[i] := Copy(S, 1, Length(S))
end;
function TdmDXCC.FindCountry(call : String; date : TDateTime; var pfx, country, cont, ITU, WAZ, offset,
lat, long : String; var ADIF : Integer; Precision : Integer = NotExactly) : Boolean;
function Datumek(sdatum : String) : TDateTime;
var
tmp : TExplodeArray;
begin
tmp := Explode('.',sdatum);
Result := EncodeDate(StrToInt(tmp[2]),StrToInt(tmp[1]),strToInt(tmp[0]));
end;
var
sZnac : string_mdz;
sADIF : String;
sdatum : String;
x : LongInt;
begin
Result := False;
sZnac := call;
sDatum := DateToDDXCCDate(date);
x := sez2^.najdis_s2(sZnac,sDatum,Precision);
if x <>-1 then
begin
country := sez2^.znacka_popis_ex(x,0);
ITU := sez2^.znacka_popis_ex(x,5);
WAZ := sez2^.znacka_popis_ex(x,6);
offset := sez2^.znacka_popis_ex(x,2);
lat := sez2^.znacka_popis_ex(x,3);
long := sez2^.znacka_popis_ex(x,4);
sADIF := sez2^.znacka_popis_ex(x,11);
cont := UpperCase(sez2^.znacka_popis_ex(x,1));
Result := True;
if not TryStrToInt(sAdif,ADIF) then
ADIF := 0;
exit
end
else begin
pfx := '!'
end;
x := uhej^.najdis_s2(sZnac,sDatum,Precision);
if x <>-1 then
begin
country := uhej^.znacka_popis_ex(x,0);
ITU := uhej^.znacka_popis_ex(x,5);
WAZ := uhej^.znacka_popis_ex(x,6);
offset := uhej^.znacka_popis_ex(x,2);
lat := uhej^.znacka_popis_ex(x,3);
long := uhej^.znacka_popis_ex(x,4);
sADIF := uhej^.znacka_popis_ex(x,11);
cont := UpperCase(uhej^.znacka_popis_ex(x,1));
Result := True;
if not TryStrToInt(sAdif,ADIF) then
ADIF := 0
end
else begin
pfx := '!'
end
end;
function TdmDXCC.FindCountry(call : String; date : TDateTime; var ADIF : Integer;precision : Integer = NotExactly) : Boolean;
var
pfx,cont,country,itu,waz,posun,lat,long : String;
begin
cont := '';WAZ := '';posun := '';ITU := '';lat := '';long := '';pfx := '';
Country := '';
Result := FindCountry(call,date,pfx,cont,country,itu,waz,
posun,lat,long,adif,precision)
end;
function TdmDXCC.WhatSearch(call : String; date : TDateTime; var AlreadyFound : Boolean;var ADIF : Integer) : String;
var
Pole : TExplodeArray;
pocet : Integer;
pred_lomitkem : String;
za_lomitkem : String;
mezi_lomitky : String;
tmp : Integer;
begin
tmp := 0;
Result := call;
if pos('/',call) > 0 then
begin
if FindCountry(call,date,adif,Exactly) then
begin
Result := call;
AlreadyFound := True;
exit
end;
SetLength(pole,0);
pole := Explode('/',call);
pocet := Length(pole)-1;
case pocet of
1: begin
pred_lomitkem := pole[0];
za_lomitkem := pole[1];
if ((TryStrToInt(za_lomitkem,tmp)) and (Length(za_lomitkem)>1)) then
begin
Result := pred_lomitkem;
exit
end;
if (Length(pred_lomitkem) = 0) then
begin
Result := za_lomitkem;
exit
end;
if (Length(za_lomitkem) = 0) then
begin
Result := pred_lomitkem;
exit
end;
if (((za_lomitkem[1]='M') and (za_lomitkem[2]='M')) or (za_lomitkem='AM')) then //nevim kde je
begin
Result := '?';
exit
end;
if (length(za_lomitkem) = 1) then
begin
if (((za_lomitkem[1] = 'M') or (za_lomitkem[1] = 'P')) and (Pos('LU',pred_lomitkem) <> 1)) then
begin
Result := pred_lomitkem;
exit
end;
if (za_lomitkem[1] in ['0'..'9']) then //SP2AD/1
begin
if (((pred_lomitkem[1] = 'A') and (pred_lomitkem[2] in ['A'..'L'])) or
(pred_lomitkem[1] = 'K') or (pred_lomitkem[1] = 'W') or (pred_lomitkem[1] = 'N')) then //KL7AA/1 = W1
Result := 'W'+za_lomitkem
else begin
pred_lomitkem[3] := za_lomitkem[1];
Result := pred_lomitkem;//Result := copy(pred_lomitkem,1,3);
end;
end
else begin
if ((za_lomitkem[1] in ['A'..'D','E','H','J','L'..'V','X'..'Z'])) then //pokud je za lomitkem jen pismeno,
begin //nesmime zapomenout na chudaky Argentince
if (Pos('LU',pred_lomitkem) = 1) or (Pos('LW',pred_lomitkem) = 1) or
(Pos('AY',pred_lomitkem) = 1) or (Pos('AZ',pred_lomitkem) = 1) or
(Pos('LO',pred_lomitkem) = 1) or (Pos('LP',pred_lomitkem) = 1) or
(Pos('LQ',pred_lomitkem) = 1) or (Pos('LR',pred_lomitkem) = 1) or
(Pos('LS',pred_lomitkem) = 1) or (Pos('LT',pred_lomitkem) = 1) or
(Pos('LV',pred_lomitkem) = 1) then
begin
pred_lomitkem[4] := za_lomitkem[1];
Result := pred_lomitkem;
exit
end
else //pokud to neni chudak Argentinec, nechame znacku napokoji
Result := call
end
else begin
AlreadyFound := True;
Result := za_lomitkem
end;
if FindCountry(copy(pred_lomitkem,1,2)+'/'+za_lomitkem,date,ADIF) then
begin
AlreadyFound := True;
Result := copy(pred_lomitkem,1,2)+'/'+za_lomitkem;
exit
end
end
end
else begin //za lomitkem je vic jak jedno pismenko
if IsException(za_lomitkem) then
Result := pred_lomitkem
else begin
if Length(za_lomitkem) >= Length(pred_lomitkem) then
begin
if not FindCountry(pred_lomitkem,date,ADIF,ExNoEquals) then
begin
Result := za_lomitkem;
AlreadyFound := True;
exit
end
else begin
Result := pred_lomitkem;
exit
end
end
else begin //pred lomitkem je to delsi nebo rovno
if not FindCountry(za_lomitkem,date,ADIF,ExNoEquals) then
begin
Result := pred_lomitkem;
AlreadyFound := True;
exit
end
else begin
Result := za_lomitkem;
AlreadyFound := True;
exit
end
end
end
end
end; // 1 slash
2: begin
pred_lomitkem := pole[0];
mezi_lomitky := pole[1];
za_lomitkem := pole[2];
if Length(za_lomitkem) = 0 then
begin
Result := pred_lomitkem;
exit
end;
if (((za_lomitkem[1]='M') and (za_lomitkem[2]='M')) or (za_lomitkem='AM')) then //nevim kde je
begin
Result := '?';
exit
end;
if Length(mezi_lomitky) > 0 then
begin
if (mezi_lomitky[1] in ['0'..'9']) then
begin
if (((pred_lomitkem[1] = 'A') and (pred_lomitkem[2] in ['A'..'L'])) or
(pred_lomitkem[1] = 'K') or (pred_lomitkem[1] = 'W')) then //KL7AA/1 = W1
Result := 'W'+mezi_lomitky
else begin
if pred_lomitkem[2] in ['0'..'9'] then //RA1AAA/2/M
pred_lomitkem[2] := mezi_lomitky[1]
else
pred_lomitkem[3] := mezi_lomitky[1];
Result := pred_lomitkem;
exit;
end;
end;
end;
if ((length(za_lomitkem) = 1) and (za_lomitkem[1] in ['A'..'Z'])) then
begin
if FindCountry(pred_lomitkem + '/'+za_lomitkem,date,ADIF) then
begin
Result := pred_lomitkem + '/'+za_lomitkem;
AlreadyFound := True
end
else begin
Result := pred_lomitkem
end
end
else begin
if ((length(za_lomitkem) = 1) and (za_lomitkem[1] in ['0'..'9'])) then
begin
if FindCountry(pred_lomitkem[1]+pred_lomitkem[2]+za_lomitkem,date, ADIF) then //ZL1AMO/C
begin
Result := pred_lomitkem[1]+pred_lomitkem[2]+za_lomitkem;
AlreadyFound := True
end
else
Result := pred_lomitkem
end
else
Result := pred_lomitkem
end
end // 2 slashes
end //case
end
end;
function TdmDXCC.DateToDDXCCDate(date : TDateTime) : String;
var
d,m,y : Word;
sd,sm : String;
begin
DecodeDate(date,y,m,d);
if d < 10 then
sd := '0'+IntToStr(d)
else
sd := IntToStr(d);
if m < 10 then
sm := '0'+IntToStr(m)
else
sm := IntToStr(m);
Result := IntToStr(y) + '/' + sm + '/' + sd
end;
procedure TdmDXCC.DataModuleDestroy(Sender: TObject);
begin
dispose(sez1,done);
dispose(sez2,done);
LeaveCriticalsection(csDXCC)
end;
{$R *.lfm}
end.
|
{ Some utility routines for compatibility to some units available
for BP, like some `Turbo Power' units.
@@NOTE - SOME OF THE ROUTINES IN THIS UNIT MAY NOT WORK CORRECTLY.
TEST CAREFULLY AND USE WITH CARE!
Copyright (C) 1998-2005 Free Software Foundation, Inc.
Authors: Prof. Abimbola A. Olowofoyeku <African_Chief@bigfoot.com>
Frank Heckenbach <frank@pascal.gnu.de>
This file is part of GNU Pascal.
GNU Pascal 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, or (at your
option) any later version.
GNU Pascal 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 GNU Pascal; see the file COPYING. If not, write to the
Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA.
As a special exception, if you link this file with files compiled
with a GNU compiler to produce an executable, this does not cause
the resulting executable to be covered by the GNU General Public
License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU
General Public License. }
{$gnu-pascal,I-}
{$if __GPC_RELEASE__ < 20030412}
{$error This unit requires GPC release 20030412 or newer.}
{$endif}
module GPCUtil;
export GPCUtil = all
(
{ Return the current working directory }
GetCurrentDirectory => ThisDirectory,
{ Does a directory exist? }
DirectoryExists => IsDirectory,
{ Does file name s exist? }
FileExists => ExistFile,
{ Return just the directory path of Path. Returns
DirSelf + DirSeparator if Path contains no directory. }
DirFromPath => JustPathName,
{ Return just the file name part without extension of Path.
Empty if Path contains no file name. }
NameFromPath => JustFileName,
{ Return just the extension of Path. Empty if Path contains
no extension. }
ExtFromPath => JustExtension,
{ Return the full pathname of Path }
FExpand => FullPathName,
{ Add a DirSeparator to the end of s if there is not
already one. }
ForceAddDirSeparator => AddBackSlash,
{ Return a string stripped of leading spaces }
TrimLeftStr => TrimLead,
{ Return a string stripped of trailing spaces }
TrimRightStr => TrimTrail,
{ Return a string stripped of leading and trailing spaces }
TrimBothStr => Trim,
{ Convert a string to lowercase }
LoCaseStr => StLoCase,
{ Convert a string to uppercase }
UpCaseStr => StUpCase
);
import GPC;
{ Replace all occurences of OldC with NewC in s and return the
result }
function ReplaceChar (const s: String; OldC, NewC: Char) = Res: TString;
{ Break a string into 2 parts, using Ch as a marker }
function BreakStr (const Src: String; var Dest1, Dest2: String; ch: Char): Boolean; attribute (ignorable);
{ Convert a CString to an Integer }
function PChar2Int (s: CString) = i: Integer;
{ Convert a CString to a LongInt }
function PChar2Long (s: CString) = i: LongInt;
{ Convert a CString to a Double }
function PChar2Double (s: CString) = x: Double;
{ Search for s as an executable in the path and return its location
(full pathname) }
function PathLocate (const s: String): TString;
{ Copy file Src to Dest and return the number of bytes written }
function CopyFile (const Src, Dest: String; BufSize: Integer): LongInt; attribute (ignorable);
{ Copy file Src to Dest and return the number of bytes written;
report the number of bytes written versus total size of the source
file }
function CopyFileEx (const Src, Dest: String; BufSize: Integer;
function Report (Reached, Total: LongInt): LongInt) = BytesCopied: LongInt; attribute (ignorable);
{ Turbo Power compatibility }
{ Execute the program prog. Dummy1 and Dummy2 are for compatibility
only; they are ignored. }
function ExecDos (const Prog: String; Dummy1: Boolean; Dummy2: Pointer): Integer; attribute (ignorable);
{ Return whether Src exists in the path as an executable -- if so
return its full location in Dest }
function ExistOnPath (const Src: String; var Dest: String) = Existing: Boolean;
{ Change the extension of s to Ext (do not include the dot!) }
function ForceExtension (const s, Ext: String) = Res: TString;
{ Convert Integer to PChar; uses NewCString to allocate memory for
the result, so you must call StrDispose to free the memory later }
function Int2PChar (i: Integer): PChar;
{ Convert Integer to string }
function Int2Str (i: Integer) = s: TString;
{ Convert string to Integer }
function Str2Int (const s: String; var i: Integer): Boolean; attribute (ignorable);
{ Convert string to LongInt }
function Str2Long (const s: String; var i: LongInt): Boolean; attribute (ignorable);
{ Convert string to Double }
function Str2Real (const s: String; var i: Double): Boolean; attribute (ignorable);
{ Return a string right-padded to length Len with ch }
function PadCh (const s: String; ch: Char; Len: Integer) = Padded: TString;
{ Return a string right-padded to length Len with spaces }
function Pad (const s: String; Len: Integer): TString;
{ Return a string left-padded to length Len with ch }
function LeftPadCh (const s: String; ch: Char; Len: Byte) = Padded: TString;
{ Return a string left-padded to length Len with blanks }
function LeftPad (const s: String; Len: Integer): TString;
{ Uniform access to big memory blocks for GPC and BP. Of course, for
programs that are meant only for GPC, you can use the usual
New/Dispose routines. But for programs that should compile with
GPC and BP, you can use the following routines for GPC. In the GPC
unit for BP (gpc-bp.pas), you can find emulations for BP that try
to provide access to as much memory as possible, despite the
limitations of BP. The drawback is that this memory cannot be used
freely, but only with the following moving routines. }
type
PBigMem = ^TBigMem;
TBigMem (MaxNumber: SizeType) = record
{ Public fields }
Number, BlockSize: SizeType;
Mappable: Boolean;
{ Private fields }
Pointers: array [1 .. Max (1, MaxNumber)] of ^Byte
end;
{ Note: the number of blocks actually allocated may be smaller than
WantedNumber. Check the Number field of the result. }
function AllocateBigMem (WantedNumber, aBlockSize: SizeType; WantMappable: Boolean) = p: PBigMem;
procedure DisposeBigMem (p: PBigMem);
procedure MoveToBigMem (var Source; p: PBigMem; BlockNumber: SizeType);
procedure MoveFromBigMem (p: PBigMem; BlockNumber: SizeType; var Dest);
{ Maps a big memory block into normal addressable memory and returns
its address. The memory must have been allocated with
WantMappable = True. The mapping is only valid until the next
MapBigMem call. }
function MapBigMem (p: PBigMem; BlockNumber: SizeType): Pointer;
end;
function PathLocate (const s: String): TString;
begin
PathLocate := FSearchExecutable (s, GetEnv (PathEnvVar))
end;
function ExistOnPath (const Src: String; var Dest: String) = Existing: Boolean;
begin
Dest := PathLocate (Src);
Existing := Dest <> '';
if Existing then Dest := FExpand (Dest)
end;
function ForceExtension (const s, Ext: String) = Res: TString;
var i: Integer;
begin
i := LastPos (ExtSeparator, s);
if (i = 0) or (CharPosFrom (DirSeparators, s, i) <> 0) then
Res := s
else
Res := Copy (s, 1, i - 1);
if (Ext <> '') and (Ext[1] <> ExtSeparator) then Res := Res + ExtSeparator;
Res := Res + Ext
end;
function ExecDos (const Prog: String; Dummy1: Boolean; Dummy2: Pointer): Integer;
begin
Discard (Dummy1);
Discard (Dummy2);
ExecDos := Execute (Prog)
end;
function PadCh (const s: String; ch: Char; Len: Integer) = Padded: TString;
begin
Padded := s;
if Length (Padded) < Len then Padded := Padded + StringOfChar (ch, Len - Length (Padded))
end;
function Pad (const s: String; Len: Integer): TString;
begin
Pad := PadCh (s, ' ', Len)
end;
function LeftPadCh (const s: String; ch: Char; Len: Byte) = Padded: TString;
begin
Padded := s;
if Length (Padded) < Len then Padded := StringOfChar (ch, Len - Length (Padded)) + Padded
end;
function LeftPad (const s: String; Len: Integer): TString;
begin
LeftPad := LeftPadCh (s, ' ', Len)
end;
function Int2PChar (i: Integer): PChar;
var s: TString;
begin
Str (i, s);
SetReturnAddress (ReturnAddress (0));
Int2PChar := NewCString (s);
RestoreReturnAddress
end;
function Int2Str (i: Integer) = s: TString;
begin
Str (i, s)
end;
function Str2Int (const s: String; var i: Integer): Boolean;
var e: Integer;
begin
Val (s, i, e);
Str2Int := e = 0
end;
function Str2Long (const s: String; var i: LongInt): Boolean;
var e: Integer;
begin
Val (s, i, e);
Str2Long := e = 0
end;
function Str2Real (const s: String; var i: Double): Boolean;
var e: Integer;
begin
Val (s, i, e);
Str2Real := e = 0
end;
function CopyFile (const Src, Dest: String; BufSize: Integer): LongInt;
begin
CopyFile := CopyFileEx (Src, Dest, BufSize, nil)
end;
function CopyFileEx (const Src, Dest: String; BufSize: Integer;
function Report (Reached, Total: LongInt): LongInt) = BytesCopied: LongInt;
var
Size: LongInt;
Count: Integer;
SrcFile, DestFile: File;
Buf: ^Byte;
b: BindingType;
begin
Reset (SrcFile, Src, 1);
if IOResult <> 0 then
begin
BytesCopied := -2;
Exit
end;
Rewrite (DestFile, Dest, 1);
if IOResult <> 0 then
begin
Close (SrcFile);
BytesCopied := -3;
Exit
end;
b := Binding (SrcFile);
Size := FileSize (SrcFile);
GetMem (Buf, BufSize);
BytesCopied := 0;
repeat
BlockRead (SrcFile, Buf^, BufSize, Count);
Inc (BytesCopied, Count);
if IOResult <> 0 then
BytesCopied := -100 { Read error }
else if Count > 0 then
begin
BlockWrite (DestFile, Buf^, Count);
if IOResult <> 0 then
BytesCopied := -200 { Write error }
else if Assigned (Report) and_then (Report (BytesCopied, Size) < 0) then
BytesCopied := -300 { User Abort }
end
until (BytesCopied < 0) or (Count = 0);
FreeMem (Buf);
Close (SrcFile);
if BytesCopied >= 0 then
begin
SetFileTime (DestFile, GetUnixTime (Null), b.ModificationTime);
ChMod (DestFile, b.Mode)
end;
Close (DestFile)
end;
function BreakStr (const Src: String; var Dest1, Dest2: String; ch: Char): Boolean;
var i: Integer;
begin
i := Pos (ch, Src);
BreakStr := i <> 0;
if i = 0 then i := Length (Src) + 1;
Dest1 := Trim (Copy (Src, 1, i - 1));
Dest2 := Trim (Copy (Src, i + 1))
end;
function PChar2Int (s: CString) = i: Integer;
begin
ReadStr (CString2String (s), i)
end;
function PChar2Long (s: CString) = i: LongInt;
begin
ReadStr (CString2String (s), i)
end;
function PChar2Double (s: CString) = x: Double;
begin
ReadStr (CString2String (s), x)
end;
function ReplaceChar (const s: String; OldC, NewC: Char) = Res: TString;
var i: Integer;
begin
Res := s;
if OldC <> NewC then
for i := 1 to Length (Res) do
if Res[i] = OldC then Res[i] := NewC
end;
function AllocateBigMem (WantedNumber, aBlockSize: SizeType; WantMappable: Boolean) = p: PBigMem;
begin
SetReturnAddress (ReturnAddress (0));
New (p, WantedNumber);
RestoreReturnAddress;
with p^ do
begin
Mappable := WantMappable;
BlockSize := aBlockSize;
Number := 0;
while Number < WantedNumber do
begin
Pointers[Number + 1] := CGetMem (BlockSize);
if Pointers[Number + 1] = nil then Break;
Inc (Number)
end
end
end;
procedure DisposeBigMem (p: PBigMem);
var i: Integer;
begin
for i := 1 to p^.Number do CFreeMem (p^.Pointers[i]);
Dispose (p)
end;
procedure MoveToBigMem (var Source; p: PBigMem; BlockNumber: SizeType);
begin
Move (Source, p^.Pointers[BlockNumber]^, p^.BlockSize)
end;
procedure MoveFromBigMem (p: PBigMem; BlockNumber: SizeType; var Dest);
begin
Move (p^.Pointers[BlockNumber]^, Dest, p^.BlockSize)
end;
function MapBigMem (p: PBigMem; BlockNumber: SizeType): Pointer;
begin
if not p^.Mappable then RuntimeError (859); { attempt to map unmappable memory }
MapBigMem := p^.Pointers[BlockNumber]
end;
end.
|
unit u_workthread;
interface
uses
SysUtils,
SyncObjs,
Classes;
type
TWorkProc = procedure of object;
TWorkThread = class(TThread)
private
{ Private declarations }
Counter : Integer;
FTimeout : Integer;
FEventProc: TWorkProc;
procedure DoWork;
protected
procedure Execute; override;
public
ThreadEvent : TEvent;
constructor Create(TimeoutSeconds : Integer; EventProc: TWorkProc ); // timeout in seconds
destructor Destroy; override;
end;
implementation
procedure TWorkThread.DoWork;
begin
// put your GUI blocking code in here. Make sure you never call GUI elements from this procedure
//DoSomeLongCalculation();
end;
procedure TWorkThread.Execute;
begin
Counter := 0;
while not Terminated do
begin
if ThreadEvent.WaitFor(FTimeout) = wrTimeout then begin
DoWork;
// now inform our main Thread that we have data
Synchronize(FEventProc);
end
else
// ThreadEvent has been signaled, exit our loop
Break;
end;
end;
constructor TWorkThread.Create(TimeoutSeconds : Integer; EventProc: TWorkProc);
begin
ThreadEvent := TEvent.Create(nil, True, False, '');
// Convert to milliseconds
FTimeout := TimeoutSeconds * 1000;
FEventProc:= EventProc;
// call inherited constructor with CreateSuspended as True
inherited Create(True);
end;
destructor TWorkThread.Destroy;
begin
ThreadEvent.Free;
inherited;
end;
end.
|
unit MainForm; // allows the user to manipulate the IGame structure.
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Menus, System.Actions, Vcl.ActnList,
FrameForm, Vcl.ExtCtrls, Generics.Collections,
BowlingInt, GameUnit;
type
TfrmMain = class(TForm)
grd: TGridPanel;
fmFrame1: TfmFrame;
fmFrame2: TfmFrame;
fmFrame3: TfmFrame;
fmFrame4: TfmFrame;
fmFrame5: TfmFrame;
fmFrame6: TfmFrame;
fmFrame7: TfmFrame;
fmFrame8: TfmFrame;
fmFrame9: TfmFrame;
fmFrame10: TfmFrame;
al: TActionList;
mnu: TMainMenu;
acStart: TAction;
acRoll: TAction;
acScore: TAction;
btnRoll: TButton;
miSetup: TMenuItem;
miBowl: TMenuItem;
miScore: TMenuItem;
edtRoll: TEdit;
ttlTotalScore: TLabel;
lblTotalScore: TLabel;
acExit: TAction;
miExit: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure acRollExecute(Sender: TObject);
procedure acScoreExecute(Sender: TObject);
procedure acStartExecute(Sender: TObject);
procedure edtRollKeyPress(Sender: TObject; var Key: Char);
procedure acExitExecute(Sender: TObject);
private
Game: TGame;
BowlLine: TBowlLine;
FrameArray: TList<TfmFrame>;
function FrameCharacters(AFrame: IBowlFrame): string;
procedure Display;
public
procedure AppException(Sender: TObject; E: Exception);
procedure PopulateLine(ABowlLine: TBowlLine);
procedure PopulateFrame(var ATotal: integer; ABowlLine: TBowlLine; AFrameIdx: integer);
end;
var
frmMain: TfrmMain;
implementation
uses
BowlError;
{$R *.dfm}
{ TfrmMain }
procedure TfrmMain.acExitExecute(Sender: TObject);
begin
Close;
end;
procedure TfrmMain.acRollExecute(Sender: TObject);
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
try
sl.Delimiter := ' ';
sl.DelimitedText := edtRoll.Text;
for i := 0 to (sl.Count - 1) do begin
Game.Roll(StrToIntDef(sl[i], 0));
end;
finally
sl.Free;
end;
Display;
end;
procedure TfrmMain.acScoreExecute(Sender: TObject);
begin
Display;
end;
procedure TfrmMain.acStartExecute(Sender: TObject);
begin
Game.Start;
Display;
end;
procedure TfrmMain.AppException(Sender: TObject; E: Exception);
begin
if E is EBowlException then begin
ShowMessage(E.Message); // prep for any particular error handling regarding EBowlException
AddLogEntry(E.Message);
Display;
end else if E is EInOutError then begin
Application.ShowException(E);
end else begin
Application.ShowException(E);
AddLogEntry(E.Message);
// Application.Terminate;
end;
end;
procedure TfrmMain.Display;
begin
BowlLine := Game.ScoreByFrame;
PopulateLine(BowlLine);
lblTotalScore.Caption := IntToStr(Game.TotalScore);
end;
procedure TfrmMain.edtRollKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = #13) then begin
acRollExecute(Sender);
end;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
var
i: integer;
dt: TDateTime;
y, m, d, h, n, s, e: word;
begin
Application.OnException := AppException;
Game := TGame.Create;
Game.Start;
BowlLine := TBowlLine.Create;
FrameArray := TList<TfmFrame>.Create;
FrameArray.Add(fmFrame1);
FrameArray.Add(fmFrame2);
FrameArray.Add(fmFrame3);
FrameArray.Add(fmFrame4);
FrameArray.Add(fmFrame5);
FrameArray.Add(fmFrame6);
FrameArray.Add(fmFrame7);
FrameArray.Add(fmFrame8);
FrameArray.Add(fmFrame9);
FrameArray.Add(fmFrame10);
BowlLine.Clear;
PopulateLine(BowlLine);
lblTotalScore.Caption := '0';
for i := 1 to System.ParamCount do begin // check command line flags
if (copy(Uppercase(System.ParamStr(i)), 1, 4) = 'log=') then begin // log file name
LogFileName := copy(System.ParamStr(i), 5, length(System.ParamStr(i)));
end;
end;
if LogFileName = '' then begin
dt := now;
DecodeDate(dt, y, m, d);
DecodeTime(dt, h, n, s, e);
LogFileName := Format('Log%d%d%d%d%d%d.txt', [y, m, d, h, n, s]);
end;
LogFileName := IncludeTrailingPathDelimiter(GetEnvironmentVariable('TEMP')) + LogFileName;
end;
procedure TfrmMain.FormDestroy(Sender: TObject);
begin
FrameArray.Clear;
end;
function TfrmMain.FrameCharacters(AFrame: IBowlFrame): string; // 2 character score string in display order for regular frames; not used for last frame
var
FrameType: TBowlFrameType;
WorkStr: string;
begin
FrameType := AFrame.BowlFrameType(0); // Doesn't matter what frame in this case.
case FrameType of // uses a standard frame
frameIncomplete,
frameOpen: begin
if (AFrame.Roll[1] >= 0) then
WorkStr := IntToStr(AFrame.Roll[1])
else
WorkStr := ' ';
if (AFrame.Roll[2] >= 0) then
Result := WorkStr + IntToStr(AFrame.Roll[2])
else
Result := WorkStr + ' ';
end;
frameSpare: Result := IntToStr(AFrame.Roll[1]) + '/';
frameStrike: Result := ' X';
else
Result := ' ';
end;
end;
procedure TfrmMain.PopulateFrame(var ATotal: integer; ABowlLine: TBowlLine; AFrameIdx: integer);
var
BallDisplay: string;
Score: integer;
begin
if (AFrameIdx < ABowlLine.Count) then begin
BallDisplay := FrameCharacters(ABowlLine.Items[AFrameIdx]);
Score := ABowlLine.Items[AFrameIdx].CurrentScore(AFrameIdx + 1);
FrameArray[AFrameIdx].Populate(Score, ATotal, BallDisplay[2], BallDisplay[1], '');
if (ABowlLine.Items[AFrameIdx].BowlFrameType(AFrameIdx + 1) <> frameIncomplete) then // add in total of completed frames
ATotal := ATotal + Score;
end else begin
FrameArray[AFrameIdx].Blank;
end;
end;
procedure TfrmMain.PopulateLine(ABowlLine: TBowlLine);
var
i: integer;
BallDisplay: string;
Total: integer; // this is not the totalscore from the IGame, but the score totalled by the GUI
begin
Total := 0;
for i := 0 to 8 do begin
PopulateFrame(Total, ABowlLine, i);
end;
if ABowlLine.Count = 10 then begin // last frame needs to exist
i := ABowlLine.Items[9].CurrentScore(10);
FrameArray[9].lblScore.Caption := IntToStr(i);
Total := Total + i; // normal frames handle this in PopulateFrame
FrameArray[9].lblTotal.Caption := IntToStr(Total);
BallDisplay := FrameCharacters(ABowlLine.Items[9]);
if (ABowlLine.Items[9].BowlFrameType(10) = frameStrike) then begin
FrameArray[9].lblBall3.Caption := 'X';
if (ABowlLine.Items[9].Roll[2] < 10) then
FrameArray[9].lblBall2.Caption := IntToStr(ABowlLine.Items[9].Roll[2])
else
FrameArray[9].lblBall2.Caption := 'X';
if (ABowlLine.Items[9].Roll[3] < 10) then
FrameArray[9].lblBall1.Caption := IntToStr(ABowlLine.Items[9].Roll[3])
else
FrameArray[9].lblBall1.Caption := 'X';
end else if (ABowlLine.Items[9].BowlFrameType(10) = frameSpare) then begin
FrameArray[9].lblBall1.Caption := IntToStr(ABowlLine.Items[9].Roll[3]);
FrameArray[9].lblBall2.Caption := '/';
FrameArray[9].lblBall3.Caption := IntToStr(ABowlLine.Items[9].Roll[1]);
end else begin
FrameArray[9].lblBall1.Caption := IntToStr(ABowlLine.Items[9].Roll[1]);
FrameArray[9].lblBall2.Caption := IntToStr(ABowlLine.Items[9].Roll[2]);
FrameArray[9].lblBall3.Caption := '';
end;
end else begin
FrameArray[9].Blank;
end;
end;
end.
|
{
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.net/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HproseIdHttpClient.pas *
* *
* hprose indy http client unit for delphi. *
* *
* LastModified: Jun 5, 2010 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
}
unit HproseIdHttpClient;
{$I Hprose.inc}
interface
uses Classes, HproseCommon, HproseClient, IdURI;
type
THproseIdHttpClient = class(THproseClient)
private
FHttpPool: IList;
FIdUri: TIdURI;
FHeaders: TStringList;
FProxyHost: string;
FProxyPort: Integer;
FProxyUser: string;
FProxyPass: string;
FUserAgent: string;
protected
function GetInvokeContext: TObject; override;
function GetOutputStream(var Context: TObject): TStream; override;
procedure SendData(var Context: TObject); override;
function GetInputStream(var Context: TObject): TStream; override;
procedure EndInvoke(var Context: TObject); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure UseService(const AUri: string); override;
published
{:Before HTTP operation you may define any non-standard headers for HTTP
request, except of: 'Expect: 100-continue', 'Content-Length', 'Content-Type',
'Connection', 'Authorization', 'Proxy-Authorization' and 'Host' headers.}
property Headers: TStringList read FHeaders;
{:Address of proxy server (IP address or domain name).}
property ProxyHost: string read FProxyHost Write FProxyHost;
{:Port number for proxy connection. Default value is 8080.}
property ProxyPort: Integer read FProxyPort Write FProxyPort;
{:Username for connect to proxy server.}
property ProxyUser: string read FProxyUser Write FProxyUser;
{:Password for connect to proxy server.}
property ProxyPass: string read FProxyPass Write FProxyPass;
{:Here you can specify custom User-Agent indentification. By default is
used: 'Hprose Http Client for Delphi (Indy8)'}
property UserAgent: string read FUserAgent Write FUserAgent;
end;
procedure Register;
implementation
uses IdGlobal, IdHeaderList, IdHttp, SysUtils, Variants;
type
THproseIdHttpInvokeContext = class
IdHttp: TIdHttp;
OutStream: TStream;
InStream: TStream;
end;
var
cookieManager: IMap;
procedure SetCookie(Header: TStringList; const Host: string);
var
I, Pos: Integer;
Name, Value, CookieString, Path: string;
Cookie: IMap;
begin
for I := 0 to Header.Count - 1 do begin
Value := Header.Strings[I];
Pos := AnsiPos(':', Value);
Name := LowerCase(Copy(Value, 1, Pos - 1));
if (Name = 'set-cookie') or (Name = 'set-cookie2') then begin
Value := Trim(Copy(Value, Pos + 1, MaxInt));
Pos := AnsiPos(';', Value);
CookieString := Copy(Value, 1, Pos - 1);
Value := Copy(Value, Pos + 1, MaxInt);
Cookie := TCaseInsensitiveHashMap.Split(Value, ';', '=', 0, True, False, True);
Pos := AnsiPos('=', CookieString);
Cookie['name'] := Copy(CookieString, 1, Pos - 1);
Cookie['value'] := Copy(CookieString, Pos + 1, MaxInt);
if Cookie.ContainsKey('path') then begin
Path := Cookie['path'];
if (Length(Path) > 0) then begin
if (Path[1] = '"') then Delete(Path, 1, 1);
if (Path[Length(Path)] = '"') then SetLength(Path, Length(Path) - 1);
end;
if (Length(Path) > 0) then
Cookie['path'] := Path
else
Cookie['path'] := '/';
end
else
Cookie['path'] := '/';
if Cookie.ContainsKey('expires') then begin
// GMTToLocalDateTime of Indy 8 can't parse cookie expires directly.
// Use StringReplace to fix this bug.
Value := StringReplace(Cookie['expires'], '-', ' ', [rfReplaceAll]);
Cookie['expires'] := GMTToLocalDateTime(Value);
end;
if Cookie.ContainsKey('domain') then
Cookie['domain'] := LowerCase(Cookie['domain'])
else
Cookie['domain'] := Host;
Cookie['secure'] := Cookie.ContainsKey('secure');
CookieManager.BeginWrite;
try
if not CookieManager.ContainsKey(Cookie['domain']) then
CookieManager[Cookie['domain']] := THashMap.Create(False, True) as IMap;
VarToMap(CookieManager[Cookie['domain']])[Cookie['name']] := Cookie;
finally
CookieManager.EndWrite;
end;
end;
end;
end;
function GetCookie(const Host, Path: string; Secure: Boolean): string;
var
Cookies, CookieMap, Cookie: IMap;
Names: IList;
Domain: string;
I, J: Integer;
begin
Cookies := THashMap.Create(False);
CookieManager.BeginRead;
try
for I := 0 to CookieManager.Count - 1 do begin
Domain := VarToStr(CookieManager.Keys[I]);
if AnsiPos(Domain, Host) <> 0 then begin
CookieMap := VarToMap(CookieManager.Values[I]);
CookieMap.BeginRead;
try
Names := TArrayList.Create(False);
for J := 0 to CookieMap.Count - 1 do begin
Cookie := VarToMap(CookieMap.Values[J]);
if Cookie.ContainsKey('expires') and (Cookie['expires'] < Now) then
Names.Add(Cookie['name'])
else if AnsiPos(Cookie['path'], Path) = 1 then begin
if ((Secure and Cookie['secure']) or not Cookie['secure']) and
(Cookie['value'] <> '') then
Cookies[Cookie['name']] := Cookie['value'];
end;
end;
finally
CookieMap.EndRead;
end;
if Names.Count > 0 then begin
CookieMap.BeginWrite;
try
for J := 0 to Names.Count - 1 do CookieMap.Delete(Names[J]);
finally
CookieMap.EndWrite;
end;
end;
end;
end;
Result := Cookies.Join('; ');
finally
CookieManager.EndRead;
end;
end;
{ THproseIdHttpClient }
constructor THproseIdHttpClient.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FHttpPool := TArrayList.Create(10);
FIdUri := nil;
FHeaders := TIdHeaderList.Create;
FProxyHost := '';
FProxyPort := 8080;
FProxyUser := '';
FProxyPass := '';
FUserAgent := 'Hprose Http Client for Delphi (Indy8)';
end;
destructor THproseIdHttpClient.Destroy;
var
I: Integer;
begin
FHttpPool.Lock;
try
for I := FHttpPool.Count - 1 downto 0 do
TIdHttp(VarToObj(FHttpPool.Delete(I))).Free;
finally
FHttpPool.Unlock;
end;
FreeAndNil(FHeaders);
FreeAndNil(FIdUri);
inherited;
end;
procedure THproseIdHttpClient.UseService(const AUri: string);
begin
inherited UseService(AUri);
FreeAndNil(FIdUri);
FIdUri := TIdURI.Create(FUri);
end;
procedure THproseIdHttpClient.EndInvoke(var Context: TObject);
begin
if Context <> nil then
with THproseIdHttpInvokeContext(Context) do begin
IdHttp.Request.Clear;
IdHttp.Response.Clear;
FHttpPool.Lock;
try
FHttpPool.Add(ObjToVar(IdHttp));
finally
FHttpPool.Unlock;
end;
FreeAndNil(OutStream);
FreeAndNil(InStream);
FreeAndNil(Context);
end;
end;
function THproseIdHttpClient.GetInputStream(var Context: TObject): TStream;
begin
if Context <> nil then
Result := THproseIdHttpInvokeContext(Context).InStream
else
raise EHproseException.Create('Can''t get input stream.');
end;
function THproseIdHttpClient.GetInvokeContext: TObject;
begin
Result := THproseIdHttpInvokeContext.Create;
with THproseIdHttpInvokeContext(Result) do begin
FHttpPool.Lock;
try
if FHttpPool.Count > 0 then
IdHttp := TIdHttp(VarToObj(FHttpPool.Delete(FHttpPool.Count - 1)))
else
IdHttp := TIdHttp.Create(nil);
finally
FHttpPool.Unlock;
end;
OutStream := TMemoryStream.Create;
InStream := TMemoryStream.Create;
end;
end;
function THproseIdHttpClient.GetOutputStream(var Context: TObject): TStream;
begin
if Context <> nil then
Result := THproseIdHttpInvokeContext(Context).OutStream
else
raise EHproseException.Create('Can''t get output stream.');
end;
procedure THproseIdHttpClient.SendData(var Context: TObject);
var
Cookie: string;
begin
if Context <> nil then
with THproseIdHttpInvokeContext(Context) do begin
OutStream.Position := 0;
Cookie := GetCookie(FIdUri.Host,
FIdUri.Path,
LowerCase(FIdUri.Protocol) = 'https');
if Cookie <> '' then IdHttp.Request.ExtraHeaders.Add('Cookie: ' + Cookie);
IdHttp.Request.UserAgent := FUserAgent;
IdHttp.Request.ProxyServer := FProxyHost;
IdHttp.Request.ProxyPort := FProxyPort;
IdHttp.Request.ProxyUsername := FProxyUser;
IdHttp.Request.ProxyPassword := FProxyPass;
IdHttp.Request.Connection := 'close';
IdHttp.Request.ContentType := 'application/hprose';
IdHttp.ProtocolVersion := pv1_0;
IdHttp.DoRequest(hmPost, FUri, OutStream, InStream);
InStream.Position := 0;
SetCookie(IdHttp.Response.ExtraHeaders, FIdUri.Host);
end
else
raise EHproseException.Create('Can''t send data.');
end;
procedure Register;
begin
RegisterComponents('Hprose', [THproseIdHttpClient]);
end;
initialization
CookieManager := TCaseInsensitiveHashMap.Create(False, True);
end.
|
/////////////////////////////////////////////////////////
// //
// FlexGraphics library //
// Copyright (c) 2002-2009, FlexGraphics software. //
// //
// Flex-libraries support //
// //
/////////////////////////////////////////////////////////
unit FlexLibs;
{$I FlexDefs.inc}
interface
uses
Windows, Classes, Controls, SysUtils, Graphics,
FlexBase, FlexProps, FlexUtils;
type
TLibItemAnchorProp = class(TCustomProp)
private
function GetAsPoint: TPoint;
procedure SetAsPoint(const Value: TPoint);
procedure SetEnabled(const Value: boolean);
procedure SetPosX(const Value: integer);
procedure SetPosY(const Value: integer);
protected
FEnabled: boolean;
FPosX: integer;
FPosY: integer;
function GetDisplayValue: string; override;
public
constructor Create(AOwner: TPropList; const AName: string; const ATranslatedName: string = '');
property AsPoint: TPoint read GetAsPoint write SetAsPoint;
published
property Enabled: boolean read FEnabled write SetEnabled default False;
property PosX: integer read FPosX write SetPosX default 0;
property PosY: integer read FPosY write SetPosY default 0;
end;
TFlexLibItem = class(TFlexControl)
protected
FAnchorProp: TLibItemAnchorProp;
procedure CreateProperties; override;
procedure ControlCreate; override;
public
function CreateDragObject: TFlexDragObject;
function MakeCopy(AFlex: TFlexPanel; ALeft, ATop: integer): boolean;
property AnchorProp: TLibItemAnchorProp read FAnchorProp;
end;
TFlexLibraryClass = class of TFlexLibrary;
TFlexLibrary = class(TFlexCustomScheme)
private
FFilename: string;
FModified: boolean;
function GetByName(const Name: string): TFlexLibItem;
function GetLibItem(Index: integer): TFlexLibItem;
protected
procedure CreateProperties; override;
procedure ControlCreate; override;
public
function New: TFlexLibItem; virtual;
function NewFromFlex(AFlex: TFlexPanel): TFlexLibItem;
function Add(AControl: TFlexControl): integer; override;
procedure Delete(Index: integer); override;
procedure SaveToFiler(Filer: TFlexFiler; const Indent: string); override;
procedure LoadFromFiler(Filer: TFlexFiler); override;
property Controls[Index: integer]: TFlexLibItem read GetLibItem; default;
property ByName[const Name: string]: TFlexLibItem read GetByName;
property LibFilename: string read FFilename write FFilename;
property Modified: boolean read FModified write FModified;
end;
TFlexLibraryWithIDs = class(TFlexLibrary)
protected
procedure CreateProperties; override;
public
function Add(AControl: TFlexControl): integer; override;
end;
TFlexLibraries = class
private
FFlex: TFlexPanel;
FDragSource: TFlexPanel;
FOnChange: TNotifyEvent;
function GetCount: integer;
function GetItem(Index: integer): TFlexLibrary;
protected
procedure DoOnChange; virtual;
property DragSource: TFlexPanel read FDragSource;
public
constructor Create;
destructor Destroy; override;
function New(const Filename: string;
LibClass: TFlexLibraryClass = Nil): TFlexLibrary; virtual;
function IndexOf(ALibrary: TFlexLibrary): integer;
procedure Remove(ALibrary: TFlexLibrary);
function SaveLibrary(ALibrary: TFlexLibrary): boolean;
function LoadLibrary(ALibrary: TFlexLibrary): boolean;
property Flex: TFlexPanel read FFlex;
property Count: integer read GetCount;
property Items[Index: integer]: TFlexLibrary read GetItem; default;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
// Libraries with IDs classes ///////////////////////////////////////////////
TFlexSingleLibraries = class;
TFlexSingleLibraryClass = class of TFlexSingleLibrary;
TFlexSingleLibrary = class
private
FOwner: TFlexSingleLibraries;
FOnChange: TNotifyEvent;
protected
FId: LongWord;
FFlex: TFlexPanel;
FLibrary: TFlexLibrary;
FDragSource: TFlexPanel;
procedure DoOnChange; virtual;
property Flex: TFlexPanel read FFlex;
property DragSource: TFlexPanel read FDragSource;
public
constructor Create(AOwner: TFlexSingleLibraries;
LibClass: TFlexLibraryClass = Nil); virtual;
destructor Destroy; override;
function SaveLibrary: boolean;
function LoadLibrary: boolean;
property Owner: TFlexSingleLibraries read FOwner;
property Id: LongWord read FId;
property FlexPanel: TFlexPanel read FFlex;
property FlexLibrary: TFlexLibrary read FLibrary;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
end;
TFlexSingleLibraries = class
private
function GetCount: integer;
function GetLibrary(Index: Integer): TFlexSingleLibrary;
protected
FList: TList;
FMaxId: LongWord;
function InternalAdd(Item: TFlexSingleLibrary): integer;
procedure InternalDelete(Index: integer);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
function New(AClass: TFlexSingleLibraryClass = Nil;
LibClass: TFlexLibraryClass = Nil): TFlexSingleLibrary; virtual;
procedure Delete(Index: integer);
function IndexOf(Item: TFlexSingleLibrary): integer;
function FindByName(const FlexPanelName: string): integer;
property Count: integer read GetCount;
property Items[Index: Integer]: TFlexSingleLibrary read GetLibrary; default;
end;
var
FlexLibraries: TFlexLibraries;
implementation
// TLibItemAnchorProp /////////////////////////////////////////////////////////
constructor TLibItemAnchorProp.Create(AOwner: TPropList; const AName: string; const ATranslatedName: string = '');
begin
inherited;
FPropType := ptComplex;
end;
function TLibItemAnchorProp.GetAsPoint: TPoint;
begin
Result.X := FPosX;
Result.Y := FPosY;
end;
function TLibItemAnchorProp.GetDisplayValue: string;
begin
Result := '(Anchor)';
end;
procedure TLibItemAnchorProp.SetAsPoint(const Value: TPoint);
begin
if ((Value.X = FPosX) and (Value.Y = FPosY)) or Owner.IsReadOnly(Self) then
exit;
DoBeforeChanged;
FPosX := Value.X;
FPosY := Value.Y;
DoChanged;
end;
procedure TLibItemAnchorProp.SetEnabled(const Value: boolean);
begin
if (Value = FEnabled) or Owner.IsReadOnly(Self) then exit;
DoBeforeChanged;
FEnabled := Value;
DoChanged;
end;
procedure TLibItemAnchorProp.SetPosX(const Value: integer);
begin
if (Value = FPosX) or Owner.IsReadOnly(Self) then exit;
DoBeforeChanged;
FPosX := Value;
DoChanged;
end;
procedure TLibItemAnchorProp.SetPosY(const Value: integer);
begin
if (Value = FPosY) or Owner.IsReadOnly(Self) then exit;
DoBeforeChanged;
FPosY := Value;
DoChanged;
end;
// TFlexLibItem //////////////////////////////////////////////////////////////
procedure TFlexLibItem.ControlCreate;
begin
NonVisual := true;
ShowHintProp.Value := True;
if Assigned(Owner) then begin
Name := Owner.GetDefaultNewName(Self, Parent);
Owner.GenerateID(Self);
end;
//inherited;
Visible := true;
DoNotify(fnCreated);
end;
procedure TFlexLibItem.CreateProperties;
const HideSet: TPropStyle = [ psReadOnly, psDontStore, psNonVisual ];
begin
inherited;
LeftProp.Style := HideSet;
TopProp.Style := HideSet;
IdProp.Style := HideSet;
ShowHintProp.Style := HideSet;
LayerProp.Style := HideSet;
ReferenceProp.Style := HideSet;
FAnchorProp := TLibItemAnchorProp.Create(Props, 'Anchor');
end;
function TFlexLibItem.CreateDragObject: TFlexDragObject;
begin
Result := Owner.CreateDragObject(Self, True, False);
end;
function TFlexLibItem.MakeCopy(AFlex: TFlexPanel;
ALeft, ATop: integer): boolean;
var Drag: TFlexDragObject;
DragGroup: TFlexGroup;
begin
// Create drag group (for extract library item controls)
Drag := Owner.CreateDragObject(Self, True, False);
try
DragGroup := Drag.DragGroup;
Drag.DragGroup := Nil;
finally
Drag.Free;
end;
// Move DragGroup to fpView panel
DragGroup.Owner := AFlex;
DragGroup.Parent := AFlex.ActiveScheme;
DragGroup.Layer := AFlex.ActiveLayer;
// Set DragGroup position
DragGroup.Left := ALeft;
DragGroup.Top := ATop;
// Ungroup
AFlex.UnselectAll;
AFlex.Select(DragGroup);
AFlex.Ungroup;
// Success
Result := true;
end;
// TFlexLibrary //////////////////////////////////////////////////////////////
procedure TFlexLibrary.ControlCreate;
begin
NonVisual := true;
ShowHintProp.Value := True;
inherited;
end;
procedure TFlexLibrary.CreateProperties;
const HideSet: TPropStyle = [ psReadOnly, psDontStore, psNonVisual ];
begin
inherited;
ShowHintProp.Style := HideSet;
IdProp.Style := HideSet;
ReferenceProp.Style := HideSet;
end;
function TFlexLibrary.Add(AControl: TFlexControl): integer;
var PassRec: TPassControlRec;
begin
Result := inherited Add(AControl);
if Result >= 0 then begin
FirstControl(AControl, PassRec);
try
while Assigned(AControl) do begin
AControl.Reference := Nil;
AControl := NextControl(PassRec);
end;
finally
ClosePassRec(PassRec);
end;
FModified := true;
end;
end;
procedure TFlexLibrary.Delete(Index: integer);
begin
inherited;
FModified := true;
end;
function TFlexLibrary.GetByName(const Name: string): TFlexLibItem;
begin
Result := TFlexLibItem( inherited ByName[Name] );
end;
function TFlexLibrary.GetLibItem(Index: integer): TFlexLibItem;
begin
Result := TFlexLibItem( inherited Controls[Index] );
end;
procedure TFlexLibrary.LoadFromFiler(Filer: TFlexFiler);
var s: string;
i: integer;
begin
s := Filer.LoadStr;
if StrBeginsFrom(s, fcBinary) then s := Filer.LoadStr;
if not StrBeginsFrom(s, fcLibrary) then
raise Exception.Create('Data format error');
i := Pos(' ', s);
if i > 0 then
Name := Trim(copy(s, i+1, MaxInt));
inherited;
end;
function TFlexLibrary.New: TFlexLibItem;
begin
Result := TFlexLibItem.Create(Owner, Self, Nil);
end;
function TFlexLibrary.NewFromFlex(AFlex: TFlexPanel): TFlexLibItem;
var MS: TMemoryStream;
Filer: TFlexFiler;
s: string;
LoadOrigin: TPoint;
Control: TFlexControl;
begin
Result := New;
if not Assigned(Result) then exit;
try
MS := Nil;
Filer := Nil;
try
MS := TMemoryStream.Create;
Filer := TFlexFiler.Create(MS);
with AFlex.SelectedRange do begin
LoadOrigin.X := -Left;
LoadOrigin.Y := -Top;
Result.Width := Right - Left;
Result.Height := Bottom - Top;
end;
AFlex.SaveToFiler(Filer, True);
Filer.Rewind;
Owner.BeginLoading;
try
s := Filer.LoadStr;
if not StrBeginsFrom(s, fcClipboard) then
raise Exception.Create('Data format error');
while Filer.LoadStrCheck(s) do begin
if StrBeginsFrom(s, fcEnd) then
break
else
if StrBeginsFrom(s, fcObject) then begin
Control := Owner.LoadFlexControl(Filer, Result, s);
if Assigned(Control) then begin
Control.Left := Control.Left + LoadOrigin.X;
Control.Top := Control.Top + LoadOrigin.Y;
end;
end else
Filer.LoadSkipToEnd;
end;
finally
Owner.EndLoading;
end;
finally
Filer.Free;
MS.Free;
end;
except
Result.Free;
raise;
end;
end;
procedure TFlexLibrary.SaveToFiler(Filer: TFlexFiler; const Indent: string);
var i: integer;
begin
Filer.SaveStr(fcLibrary + ' ' + Name);
Props.SaveToFiler(Filer, IndentStep);
for i:=0 to Count-1 do
Controls[i].SaveToFiler(Filer, IndentStep);
Filer.SaveStr(fcEnd);
end;
// TFlexLibraries ////////////////////////////////////////////////////////////
constructor TFlexLibraries.Create;
begin
inherited;
FFlex := TFlexPanel.Create(Nil);
FFlex.Name := 'FlexLibraries';
FFlex.EmptyDocument;
FFlex.ShowDocFrame := False;
end;
destructor TFlexLibraries.Destroy;
begin
FFlex.Free;
inherited;
end;
procedure TFlexLibraries.DoOnChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
function TFlexLibraries.GetCount: integer;
begin
Result := FFlex.Schemes.Count;
end;
function TFlexLibraries.GetItem(Index: integer): TFlexLibrary;
begin
Result := TFlexLibrary(FFlex.Schemes[Index]);
end;
function TFlexLibraries.New(const Filename: string;
LibClass: TFlexLibraryClass = Nil): TFlexLibrary;
begin
if Assigned(LibClass)
then Result := LibClass.Create(FFlex, FFlex.Schemes, Nil)
else Result := TFlexLibrary.Create(FFlex, FFlex.Schemes, Nil);
if Filename <> '' then begin
Result.LibFilename := Filename;
if FileExists(Filename) then
try
LoadLibrary(Result);
except
Result.Free;
raise;
end
else
// Save empty library to the file
try
SaveLibrary(Result);
except
Result.Free;
raise;
end;
end;
DoOnChange;
end;
procedure TFlexLibraries.Remove(ALibrary: TFlexLibrary);
begin
FFlex.Schemes.Remove(ALibrary);
DoOnChange;
end;
function TFlexLibraries.IndexOf(ALibrary: TFlexLibrary): integer;
begin
Result := FFlex.Schemes.IndexOf(ALibrary);
end;
function TFlexLibraries.LoadLibrary(ALibrary: TFlexLibrary): boolean;
var FS: TFileStream;
Filer: TFlexFiler;
begin
Result := False;
if not Assigned(ALibrary) or (FFlex.Schemes.IndexOf(ALibrary) < 0) then exit;
FS := Nil;
Filer := Nil;
try
FS := TFileStream.Create(ALibrary.LibFilename,
fmOpenRead or fmShareDenyWrite);
Filer := TFlexFiler.Create(FS);
ALibrary.LoadFromFiler(Filer);
ALibrary.Modified := False;
Result := true;
finally
Filer.Free;
FS.Free;
end;
end;
function TFlexLibraries.SaveLibrary(ALibrary: TFlexLibrary): boolean;
var FS: TFileStream;
Filer: TFlexFiler;
begin
Result := False;
if not Assigned(ALibrary) or (FFlex.Schemes.IndexOf(ALibrary) < 0) then exit;
FS := Nil;
Filer := Nil;
try
FS := TFileStream.Create(ALibrary.LibFilename, fmCreate);
Filer := TFlexFiler.Create(FS);
ALibrary.SaveToFiler(Filer, '');
ALibrary.Modified := False;
Result := true;
finally
Filer.Free;
FS.Free;
end;
end;
// TFlexLibraryWithIDs ////////////////////////////////////////////////////////
procedure TFlexLibraryWithIDs.CreateProperties;
begin
inherited;
// Unlock ID property
IdProp.Style := IdProp.Style - [psReadOnly, psDontStore];
end;
function TFlexLibraryWithIDs.Add(AControl: TFlexControl): integer;
begin
Result := inherited Add(AControl);
if Result < 0 then exit;
// Generate ID for library item
AControl.IdProp.Style := AControl.IdProp.Style - [psReadOnly, psDontStore];
if AControl.IdProp.Value = 0 then Owner.GenerateID(AControl);
end;
// TFlexSingleLibrary /////////////////////////////////////////////////////////
constructor TFlexSingleLibrary.Create(AOwner: TFlexSingleLibraries;
LibClass: TFlexLibraryClass = Nil);
begin
FOwner := AOwner;
FFlex := TFlexPanel.Create(Nil);
FFlex.Name := 'FlexSingleLibrary';
FFlex.EmptyDocument;
FFlex.ShowDocFrame := False;
if Assigned(LibClass)
then FLibrary := LibClass.Create(FFlex, FFlex.Schemes, Nil)
else FLibrary := TFlexLibraryWithIDs.Create(FFlex, FFlex.Schemes, Nil);
if Assigned(FOwner) then FOwner.InternalAdd(Self);
end;
destructor TFlexSingleLibrary.Destroy;
begin
if Assigned(FOwner) then FOwner.InternalDelete(FOwner.IndexOf(Self));
FFlex.Free;
inherited;
end;
procedure TFlexSingleLibrary.DoOnChange;
begin
if Assigned(FOnChange) then FOnChange(Self);
end;
function TFlexSingleLibrary.LoadLibrary: boolean;
var FS: TFileStream;
Filer: TFlexFiler;
begin
FS := Nil;
Filer := Nil;
try
FS := TFileStream.Create(FLibrary.LibFilename,
fmOpenRead or fmShareDenyWrite);
Filer := TFlexFiler.Create(FS);
FLibrary.LoadFromFiler(Filer);
FLibrary.Modified := False;
Result := true;
finally
Filer.Free;
FS.Free;
end;
end;
function TFlexSingleLibrary.SaveLibrary: boolean;
var FS: TFileStream;
Filer: TFlexFiler;
begin
FS := Nil;
Filer := Nil;
try
FS := TFileStream.Create(FLibrary.LibFilename, fmCreate);
Filer := TFlexFiler.Create(FS);
FLibrary.SaveToFiler(Filer, '');
FLibrary.Modified := False;
Result := true;
finally
Filer.Free;
FS.Free;
end;
end;
///////////////////////////////////////////////////////////////////////////////
procedure RegisterControls;
begin
RegisterFlexControl(TFlexLibItem);
end;
// TFlexSingleLibraries ///////////////////////////////////////////////////////
constructor TFlexSingleLibraries.Create;
begin
FList := TList.Create;
end;
destructor TFlexSingleLibraries.Destroy;
begin
Clear;
FList.Free;
inherited;
end;
procedure TFlexSingleLibraries.Clear;
begin
while FList.Count > 0 do TFlexSingleLibrary(FList[FList.Count-1]).Free;
end;
function TFlexSingleLibraries.GetCount: integer;
begin
Result := FList.Count;
end;
function TFlexSingleLibraries.GetLibrary(Index: Integer): TFlexSingleLibrary;
begin
Result := TFlexSingleLibrary(FList[Index]);
end;
function TFlexSingleLibraries.IndexOf(Item: TFlexSingleLibrary): integer;
begin
Result := FList.IndexOf(Item);
end;
function TFlexSingleLibraries.FindByName(const FlexPanelName: string): integer;
var i: integer;
begin
Result := -1;
for i:=0 to FList.Count-1 do
if TFlexSingleLibrary(FList[i]).FFlex.Name = FlexPanelName then begin
Result := i;
break;
end;
end;
function TFlexSingleLibraries.InternalAdd(Item: TFlexSingleLibrary): integer;
begin
Result := -1;
if not Assigned(Item) or (Item.Owner <> Self) then exit;
Result := FList.IndexOf(Item);
if Result >= 0 then exit;
Result := FList.Add(Item);
inc(FMaxId);
Item.FId := FMaxId;
Item.FFlex.Name := Format('FlexSingleLibrary%d', [Item.FId]);
end;
procedure TFlexSingleLibraries.InternalDelete(Index: integer);
begin
FList.Delete(Index);
end;
function TFlexSingleLibraries.New(AClass: TFlexSingleLibraryClass = Nil;
LibClass: TFlexLibraryClass = Nil): TFlexSingleLibrary;
begin
if Assigned(AClass)
then Result := AClass.Create(Self, LibClass)
else Result := TFlexSingleLibrary.Create(Self, LibClass);
end;
procedure TFlexSingleLibraries.Delete(Index: integer);
begin
TFlexSingleLibrary(FList[Index]).Free;
end;
initialization
RegisterControls;
FlexLibraries := TFlexLibraries.Create;
finalization
FlexLibraries.Free;
FlexLibraries := Nil;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit PropInspAPI;
{ PropInspAPI. Open Tools API for the Property Inspector. }
interface
uses System.Classes, DesignIntf, ToolsAPI, System.IniFiles;
type
{ IPropInspSaveState is a hack until the OTA has a way of
saving desktop state. The OI checks to see if the selection
implements this and calls it }
IPropInspSaveState = interface
['{B4EB42CD-7616-409F-99ED-C38B40953E02}']
procedure SaveWindowState(Desktop: TCustomIniFile; isProject: Boolean);
procedure LoadWindowState(Desktop: TCustomIniFile);
end;
TInspArrangeMode = (iamByCategory, iamByName);
IPropListBoxSelection = interface
['{2C6EC290-6159-4D66-8C45-06EFA815106A}']
function GetCount: Integer;
function GetCurrentSubItem: IProperty;
function GetSubItem(const Index: Integer): IProperty;
function GetSubItemCount: Integer;
function GetItem(const Index: Integer): IProperty;
procedure SetCurrentSubItem(const Value: IProperty);
{ Items are all of the first level items to display }
property Items[const Index: Integer]: IProperty read GetItem;
{ Count is a Count of the Items }
property Count: Integer read GetCount;
{ CurrentSubItem will be set when the Property Inspector is about
to iterate through the SubItems array for that particular IProperty }
property CurrentSubItem: IProperty read GetCurrentSubItem write SetCurrentSubItem;
property SubItemCount: Integer read GetSubItemCount;
property SubItems[const Index: Integer]: IProperty read GetSubItem;
end;
{ IOTAPropInspPages }
{ Query IOTAPropInspPages from an IOTAPropInspSelection.
If returned, then the Property Inspector should display
each Item as a page. }
IOTAPropInspPages = interface(IOTAStrings)
['{A8CFD9BF-7A6C-4F99-879E-ADBA5C8FEC08}']
function GetPageIndex: Integer;
procedure SetPageIndex(const Value: Integer);
{ PageIndex: The active page index }
property PageIndex: Integer read GetPageIndex write SetPageIndex;
end;
{ IOTAPropInspInstanceList }
{ Query IOTAPropInspInstanceList from an IOTAPropInspSelection.
If returned, then the Property Inspector will enumerate through the
Count, adding all the Name/Value's to the InstanceList list when it
is dropped down. }
IOTAPropInspInstanceList = interface(IOTAStrings)
['{394C9D2B-0925-460B-8678-1B1547AEC1A1}']
function GetActiveName: string;
function GetActiveValue: string;
function GetHint: string;
function GetItemIndex: Integer;
procedure SetItemIndex(const Value: Integer);
{ ActiveName and ActiveValue are displayed in the InstanceList when
it is not dropped down. }
property ActiveName: string read GetActiveName;
property ActiveValue: string read GetActiveValue;
property Hint: string read GetHint;
{ ItemIndex will be set when a new item is selected from the InstanceList
list. You should update your list of items as needed }
property ItemIndex: Integer read GetItemIndex write SetItemIndex;
end;
IOTAWidePropInspInstanceList = interface
['{561F40D1-38D0-4f4b-8AD2-F0582E4E2AD3}']
function GetWideActiveName: Widestring;
function GetWideActiveValue: WideString;
function GetWideHint: WideString;
function GetWideItem(const Index: Integer): WideString;
procedure SetWideItem(const Index: Integer; const Value: WideString);
property WideActiveName: WideString read GetWideActiveName;
property WideActiveValue: WideString read GetWideActiveValue;
property WideHint: WideString read GetWideHint;
property WideItems[const Index: Integer]: Widestring read GetWideItem write SetWideItem;
end;
{ IOTAPropInspCategories }
{ String Name Value is the category name. String Value for a given name
should be "1" if it is On/Checked, or anything else if it isn't.
Integer Data can be whatever you want.
Implementing Assign is not required; it is not used.
Assignment of things other than Value is not done.}
IOTAPropInspCategories = interface(IOTAStrings)
['{75F38883-A97D-4687-BD14-E14D6685D9B3}']
procedure ViewAll;
procedure ToggleAll;
procedure ViewNone;
end;
{ IOTAPropInspHotCommands }
{ Query IOTAPropInspInstanceList from and IOTAPropInspSelection. If returned,
then the property inspector will display a pane at the bottom with various
hot-links associated with the current selection. This allows, for instance,
component editor verbs to be invoked directly from the property inspector.
Since this interface descends from IOTAStrings, the Count and string items
from IOTAStrings will describe what commands and their display strings to
show. }
IOTAPropInspHotCommands = interface(IOTAStrings)
['{550D14EA-78AC-4936-AC06-E084F10C1EE7}']
{ This method will be invoked when the user clicks on the indicated item
index. }
procedure CommandClicked(Index: Integer);
{ This method is called periodically in order to determine if the specified
command index should be enabled. }
function CommandEnabled(Index: Integer): Boolean;
end;
{ The programmer who wishes to interact with the Property Inspector will
implement IOTAPropInspSelection and will set IOTAPropInspManager.Selection
to change what the Property Inspector displays. }
IOTAPropInspSelection = interface(IPropListBoxSelection)
['{0078EE6B-FB6D-4082-BB8A-189FD58395F6}']
function GetActiveItem: string;
function GetExpandAll: Boolean;
function GetExpandedItems: string;
function GetArrangeMode: TInspArrangeMode;
function GetShowDescriptionPane: Boolean;
function GetShowHotCommands: Boolean;
function GetStatusText: string;
function GetCategories: IOTAPropInspCategories;
procedure SetActiveItem(const Value: string);
procedure SetArrangeMode(const Value: TInspArrangeMode);
procedure SetExpandedItems(const Value: string);
{ Show help based on the Item that we are passing to you }
procedure InvokeHelp(const Item: IProperty);
{ Return True from IsExpandable if the property can be expanded.
The IProperty must already have paSubProperties in Attributes
for this to be called. It allows you to make an item not
appear expandable for whatever reason. Default implementations
should always return True. }
function IsExpandable(const Item: IProperty): Boolean;
{ HandleActivation should be called whenever a viewer of this
PropInspSelection is activated or deactivated. This allows the selection
to perform special processing related to the user selecting a view of the
selection }
procedure HandleActivation(Activating: Boolean);
{ ExpandAll returns whether or not the the property inspector will automatically
expand all the first level items. This is generally useful to tell the
inspector to automatically expand the categories when in the iamByCategory
ArrangeMode. Once Expanded items is set for the first time, ExpandAll can
return False in order to properly preserve the expanded and collapsed
catebories. }
property ExpandAll: Boolean read GetExpandAll;
{ ExpandedItems will be used by the Property Inspector to
retrieve and write its expanded items that are associated with this
selection. You will need to persist the state. }
property ExpandedItems: string read GetExpandedItems write SetExpandedItems;
{ ActiveItem will be used by the Property Inspector to retrieve and
store the currently selected item. Again, you will need to persist
the state. }
property ActiveItem: string read GetActiveItem write SetActiveItem;
property ArrangeMode: TInspArrangeMode read GetArrangeMode write SetArrangeMode;
{ ShowDescriptionPane is used by the property inspector to indicated whether
or not it should display the description pane at the bottom of the property
list. This pane will display the name of the currently selected property
and if the current IProperty also implements IPropertyDescription, displays
the text from IPropertyDescription.GetDescription. }
property ShowDescriptionPane: Boolean read GetShowDescriptionPane;
{ ShowHotCommands is used by the property inspector to indicate whether or
not it should display the hot commands pane at the bottom of the property
list. If this property is True, the selection should implement
IOTAPropInspHotCommands in order for the property inspector to get the
content to display in that pane. }
property ShowHotCommands: Boolean read GetShowHotCommands;
property StatusText: string read GetStatusText;
{ Retrieve the categories for this selection, and if they
are visible (checked) or not }
property Categories: IOTAPropInspCategories read GetCategories;
end;
{ Notifiers can be added to "hear" when things change in the
Property Inspector. Those who wish to implement a Property Inspector
would add a IOTASelectionNotifier to the IOTAPropInspServices and
display the IProperty's retrieved from the IOTAPropInspSelection.
For IOTANotifier, the only pertinent events are Destroyed (which
happens when the references should be dropped) and Modifed (which
signals that you should refresh your view).
}
IOTASelectionNotifier = interface(IOTANotifier)
['{3C2059B2-0C44-4C4C-9C9F-F325A509D9B4}']
{ SelectionChanged: tells you when a NewSelection has happened.
You should update your display with the NewSelection at this time }
procedure SelectionChanged(const NewSelection: IOTAPropInspSelection);
{ UpdateState: called when you should save out your current state. }
procedure UpdateState;
end;
IOTASelectionNotifier160 = interface
['{157FFA94-DA86-4112-9C94-8DFAED6EAAF7}']
{ This associated item was modified in some way. Subitems of volatile
properties may need to be recalculated }
procedure VolatileModified;
{ Expand the selection if possible }
procedure Expand;
end;
IOTAPropInspServices100 = interface
['{84494824-29A8-4F78-B58D-A87A9A1333F8}']
function GetSelection: IOTAPropInspSelection;
procedure SetSelection(const Value: IOTAPropInspSelection);
property Selection: IOTAPropInspSelection read GetSelection write SetSelection;
{ Modified can be called when the selection needs to be updated to
possibly display some new information. The implementation
calls all of the IOTASelectionNotifier's Modified. }
procedure Modified;
{ UpdateState can be called whenever the current Selection should
have some of its state stored out (such as when a desktop is
loaded or saved, your OI closes, or some other state changes). }
procedure UpdateState;
{ AddNotifier returns the index of the new notifier that was added }
function AddNotifier(const Notifier: IOTASelectionNotifier): Integer;
{ RemoveNotifider removes a given index }
procedure RemoveNotifier(const Index: Integer);
{ Prevent a selection from being cleared }
procedure LockSelection;
procedure UnlockSelection;
end;
INTAPropInspServices = interface(IInterface)
['{5891E776-BAFA-4EA5-AEE6-E32F210B5326}']
procedure SelectObjects(const Objects: array of TPersistent);
function ObjectsSelected(const Objects: array of TPersistent): Boolean;
end;
IOTAPropInspServices160 = interface(IOTAPropInspServices100)
['{15D694E6-E2D8-4BBA-A1D2-D8B6F8E8CCC2}']
{ VolatileModified can be called when the selection needs to be updated to
possibly display some new information, included different child items of
volatile properties. The implementation
calls all of the IOTASelectionNotifier160 VolatileModified. }
procedure VolatileModified;
{ Expand the selection }
procedure Expand;
end;
IOTAPropInspServices = interface(IOTAPropInspServices160)
['{7EF7625C-42C0-434F-B538-76B12C3D8E7C}']
end;
implementation
end.
|
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSPortsWizardPage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, WizardAPI, StdCtrls, DSPortFrame, Generics.Collections, AppEvnts,
DSMrWizardCommon, ExpertsUIWizard;
type
TDSAvailablePort = (portNone, portHTTP, portHTTPS, portTCPIP);
TDSAvailablePorts = set of TDSAvailablePort;
TDSPortDescription = record
Port: TDSAvailablePort;
PortLabel: string;
DefaultValue: Integer;
end;
TDSPortDescriptions = array of TDSPortDescription;
TDSPortsWizardFrame = class(TFrame, IExpertsWizardPageFrame)
ApplicationEvents1: TApplicationEvents;
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
private
FFocusedPort: TDSAvailablePort;
FPortFrames: TDictionary<TDSAvailablePort, TDSPortFram>;
FPortDescriptionsDictionary: TDictionary<TDSAvailablePort, TDSPortDescription>;
FOnFocusedPortChange: TNotifyEvent;
FLeftMargin: Integer;
FPage: TCustomExpertsFrameWizardPage;
function GetPort(I: TDSAvailablePort): Integer;
procedure SetPortDescriptions(const Value: TDSPortDescriptions);
procedure ShowPortPages;
procedure SetPort(I: TDSAvailablePort; const Value: Integer);
procedure SetFocusedPort(const Value: TDSAvailablePort);
procedure SetLeftMargin(const Value: Integer);
protected
{ IExpertsWizardPageFrame }
function ExpertsFrameValidatePage(ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean;
procedure ExpertsFrameUpdateInfo(ASender: TCustomExpertsWizardPage; var AHandled: Boolean);
procedure ExpertsFrameCreated(APage: TCustomExpertsFrameWizardPage);
procedure ExpertsFrameEnterPage(APage: TCustomExpertsFrameWizardPage);
function GetWizardInfo: string;
function ValidateFields: Boolean;
property LeftMargin: Integer read FLeftMargin write SetLeftMargin;
public
{ Public declarations }
// class function CreateFrame(AOwner: TComponent): TDSPortsWizardFrame; static;
property PortDescriptions: TDSPortDescriptions write SetPortDescriptions;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Ports[I: TDSAvailablePort]: Integer read GetPort write SetPort;
property FocusedPort: TDSAvailablePort read FFocusedPort write SetFocusedPort;
property OnFocusedPortChange: TNotifyEvent read FOnFocusedPortChange write FOnFocusedPortChange;
end;
IDSPortsWizardPage = interface(IWizardPage)
['{2149E34E-3931-4EBF-9A09-B7E7D59D0E96}']
function GetFrame: TDSPortsWizardFrame;
procedure SetPortDescriptions(const Value: TDSPortDescriptions);
property Frame: TDSPortsWizardFrame read GetFrame;
property PortDescriptions: TDSPortDescriptions write SetPortDescriptions;
end;
//const
// sDSPortsWizardPage = 'DSPortsWizardPage';
// sDSWebServerPortPage = 'WebServerPortPage';
implementation
{$R *.dfm}
uses StrUtils, DSCommonDsnResStrs, DsServerDsnResStrs;
{ TDSPortsWizardFrame }
procedure TDSPortsWizardFrame.ApplicationEvents1Idle(Sender: TObject;
var Done: Boolean);
var
LFrame: TPair<TDSAvailablePort, TDSPortFram>;
begin
if not Self.Visible then
Exit;
for LFrame in FPortFrames do
if LFrame.Value.EditPort.Focused or LFrame.Value.ButtonTest.Focused
or LFrame.Value.ButtonNextAvailable.Focused then
begin
FocusedPort := LFrame.Key;
Exit;
end;
FocusedPort := portNone;
end;
function TDSPortsWizardFrame.ValidateFields: Boolean;
var
LFrame: TPair<TDSAvailablePort, TDSPortFram>;
begin
for LFrame in FPortFrames do
try
StrToInt(LFrame.Value.EditPort.Text);
except
LFrame.Value.EditPort.SetFocus;
MessageDlg(Format(sInvalidInt, [sPort]), mtError, [mbOk], 0);
Exit(False);
end;
Result := True;
end;
constructor TDSPortsWizardFrame.Create(AOwner: TComponent);
begin
inherited;
FPortDescriptionsDictionary := TDictionary<TDSAvailablePort, TDSPortDescription>.Create;
FPortFrames := TDictionary<TDSAvailablePort, TDSPortFram>.Create;
end;
destructor TDSPortsWizardFrame.Destroy;
begin
FPortFrames.Free;
FPortDescriptionsDictionary.Free;
inherited;
end;
procedure TDSPortsWizardFrame.ExpertsFrameCreated(
APage: TCustomExpertsFrameWizardPage);
begin
LeftMargin := ExpertsUIWizard.cExpertsLeftMargin;
FPage := APage;
FPage.Description := sPortsPageDescription;
FPage.Title := sPortsPageTitle;
FPage.UpdateInfo;
end;
procedure TDSPortsWizardFrame.ExpertsFrameEnterPage(
APage: TCustomExpertsFrameWizardPage);
begin
// APage.UpdateInfo;
end;
procedure TDSPortsWizardFrame.ExpertsFrameUpdateInfo(
ASender: TCustomExpertsWizardPage; var AHandled: Boolean);
begin
AHandled := True;
ASender.WizardInfo := GetWizardInfo;
end;
function TDSPortsWizardFrame.ExpertsFrameValidatePage(
ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean;
begin
AHandled := True;
Result := ValidateFields;
end;
function TDSPortsWizardFrame.GetPort(I: TDSAvailablePort): Integer;
var
LFrame: TDSPortFram;
begin
Result := 0;
if FPortFrames.TryGetValue(I, LFrame) then
Result := LFrame.Port;
end;
function TDSPortsWizardFrame.GetWizardInfo: string;
begin
case FocusedPort of
portNone: Result := sPortsPageInfo;
portHTTP: Result := sHTTPPortInfo;
portHTTPS: Result := sHTTPSPortInfo;
portTCPIP: Result := sTCPIPPortInfo;
else
Result := sPortsPageInfo;
end;
end;
procedure TDSPortsWizardFrame.ShowPortPages;
var
LTop: Integer;
LTabOrder: TTabOrder;
procedure AddFrame(APort: TDSPortDescription);
var
LFrame: TDSPortFram;
begin
if not FPortFrames.TryGetValue(APort.Port, LFrame) then
begin
LFrame := TDSPortFram.Create(Self);
LFrame.Name := LFrame.Name + IntToStr(Integer(APort.Port));
FPortFrames.Add(APort.Port, LFrame);
LFrame.Parent := Self;
LFrame.LabelPort.Caption := APort.PortLabel;
LFrame.Port := APort.DefaultValue;
end;
LFrame.Left := FLeftMargin;
LFrame.Top := LTop;
LFrame.TabOrder := LTabOrder;
LTabOrder := LTabOrder + 1;
LTop := LTop + LFrame.Height;
end;
procedure RemoveFrame(APort: TDSAvailablePort);
var
LFrame: TDSPortFram;
begin
if FPortFrames.TryGetValue(APort, LFrame) then
begin
LFrame.Free;
FPortFrames.Remove(APort);
end;
end;
procedure AddOrRemove(APort: TDSAvailablePort);
begin
if FPortDescriptionsDictionary.ContainsKey(APort) then
AddFrame(FPortDescriptionsDictionary[APort])
else
RemoveFrame(APort);
end;
begin
LTop := 0;
LTabOrder := 1;
AddOrRemove(portTCPIP);
AddOrRemove(portHTTP);
AddOrRemove(portHTTPS);
end;
procedure TDSPortsWizardFrame.SetPortDescriptions(const Value: TDSPortDescriptions);
var
LPortDescription: TDSPortDescription;
begin
FPortDescriptionsDictionary.Clear;
for LPortDescription in Value do
FPortDescriptionsDictionary.Add(LPortDescription.Port, LPortDescription);
ShowPortPages;
end;
procedure TDSPortsWizardFrame.SetFocusedPort(const Value: TDSAvailablePort);
begin
if FFocusedPort <> Value then
begin
FFocusedPort := Value;
if Assigned(OnFocusedPortChange) then
OnFocusedPortChange(Self);
if FPage <> nil then
FPage.UpdateInfo;
end;
end;
procedure TDSPortsWizardFrame.SetLeftMargin(const Value: Integer);
var
LFrame: TFrame;
begin
FLeftMargin := Value;
for LFrame in FPortFrames.Values do
LFrame.Left := FLeftMargin;
end;
procedure TDSPortsWizardFrame.SetPort(I: TDSAvailablePort;
const Value: Integer);
begin
FPortFrames[I].Port := Value;
end;
end.
|
unit uFrmTarefas;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Datasnap.DBClient, Vcl.Grids, MidasLib,
Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, uReduxStore,
System.Generics.Collections;
type
TAcoes = (INCLUIR = 0,EXCLUIR=1,CONCLUIR=2);
TTarefa = record
Tarefa : String;
Concluida : Boolean;
end;
TFrmTarefas = class(TForm)
Label1: TLabel;
EdTarefa: TEdit;
BtAdicionar: TBitBtn;
GridTarefas: TDBGrid;
DsTarefas: TDataSource;
CdsTarefas: TClientDataSet;
CdsTarefasId: TIntegerField;
CdsTarefasTarefa: TStringField;
CdsTarefasConcluida: TBooleanField;
procedure FormCreate(Sender: TObject);
procedure BtAdicionarClick(Sender: TObject);
procedure GridTarefasDblClick(Sender: TObject);
private
ReduxStore : TReduxStore<TList<TTarefa>>;
{ Private declarations }
public
{ Public declarations }
end;
var
FrmTarefas: TFrmTarefas;
implementation
{$R *.dfm}
function RealizarAcao(State : TList<TTarefa>; Action : Integer):TList<TTarefa>;
var
Tarefa : TTarefa;
IdTarefa:Integer;
begin
case Action of
Ord(TAcoes.INCLUIR): begin
Tarefa.Concluida := False;
Tarefa.Tarefa := FrmTarefas.EdTarefa.Text;
State.Add(Tarefa);
FrmTarefas.EdTarefa.Clear;
end;
Ord(TAcoes.CONCLUIR) : begin
IdTarefa := FrmTarefas.CdsTarefasId.AsInteger;
Tarefa := State.Items[IdTarefa-1];
Tarefa.Concluida := True;
State.Items[IdTarefa-1] := Tarefa;
end;
end;
Result := State;
end;
procedure AtualizarGrid(State : TList<TTarefa>);
var
I : Integer;
begin
with FrmTarefas do
begin
if not CdsTarefas.Active then
CdsTarefas.Open;
CdsTarefas.EmptyDataSet;
for I := 0 to State.Count -1 do
begin
CdsTarefas.DisableControls;
CdsTarefas.Append;
CdsTarefasId.AsInteger := I + 1;
CdsTarefasTarefa.AsString := State.Items[i].Tarefa;
CdsTarefasConcluida.AsBoolean := State.Items[i].Concluida;
CdsTarefas.Post;
CdsTarefas.EnableControls;
end;
end;
end;
procedure TFrmTarefas.BtAdicionarClick(Sender: TObject);
begin
ReduxStore.DispatchAction(Ord(TAcoes.INCLUIR));
end;
procedure TFrmTarefas.FormCreate(Sender: TObject);
var
Reducer : TReducer<TList<TTarefa>>;
Listener : TListener<TList<TTarefa>>;
begin
CdsTarefas.CreateDataSet;
Reducer := RealizarAcao;
Listener := AtualizarGrid;
ReduxStore := TReduxStore<TList<TTarefa>>.Create(TList<TTarefa>.Create,Reducer);
ReduxStore.AddListener(Listener);
end;
procedure TFrmTarefas.GridTarefasDblClick(Sender: TObject);
begin
ReduxStore.DispatchAction(Ord(TAcoes.CONCLUIR));
end;
end.
|
namespace Importer;
interface
uses
System.IO,
System.Linq,
RemObjects.CodeGen4;
type
ConsoleApp = static class
private
method WriteSyntax;
public
method Main(args: array of String);
end;
implementation
method ConsoleApp.WriteSyntax;
begin
writeLn('syntax: MZImporter.exe importsettings.xml langauge');
writeLn();
writeLn(' where');
writeLn();
writeLn(' * importsettings.xml is the path to an XML file with your import settings');
writeLn();
writeLn(' See http://docs.elementscompiler.com/Tools/Marzipan for details.');
writeLn();
writeLn(' * language is one of the following:');
writeLn();
writeLn(' - oxygene');
writeLn(' - csharp');
writeLn(' - swift');
writeLn(' - objectivec');
writeLn();
end;
method ConsoleApp.Main(args: array of String);
begin
writeLn("RemObjects Marzipan Importer 2.0");
writeLn("Built with CodeGen4");
writeLn();
if length(args) <> 2 then begin
WriteSyntax;
exit;
end;
var lSettingsFile := args[0];
var lLanguage := args[1];
var lCodeGenerator := case lLanguage:ToLower() of
'oxygene','pascal','pas': new CGOxygeneCodeGenerator();
'c#','csharp','hydrogene','cs': new CGCSharpCodeGenerator withDialect(CGCSharpCodeGeneratorDialect.Hydrogene);
'swift','silver': new CGSwiftCodeGenerator withDialect(CGSwiftCodeGeneratorDialect.Silver);
'objc','objectivec','m': new CGObjectiveCHCodeGenerator();
end;
if not assigned(lCodeGenerator) then begin
WriteSyntax;
exit;
end;
if not File.Exists(lSettingsFile) then begin
writeLn('Import settings file '+Path.GetFileName(lSettingsFile)+' does not exist');
writeLn();
exit;
end;
var x := new ImporterSettings;
x.LoadFromXml(lSettingsFile);
Environment.CurrentDirectory := Path.GetDirectoryName(args[0]);
var lWorker := new Importer(x, lCodeGenerator);
lWorker.Log += s -> Console.WriteLine(s);
lWorker.Run;
end;
end. |
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC FireMonkey Base dialog form }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.FMXUI.OptsBase;
interface
uses
System.Classes, System.IniFiles, System.UITypes,
FMX.Controls, FMX.Forms, FMX.ExtCtrls, FMX.Types, FMX.Objects, FMX.Edit,
FMX.ListBox, FMX.Dialogs, FMX.StdCtrls;
type
TfrmFDGUIxFMXOptsBase = class(TForm)
pnlTop: TPanel;
Image2: TImage;
lblPrompt: TLabel;
pnlButtons: TPanel;
btnOk: TButton;
btnCancel: TButton;
Line1: TLine;
Line2: TLine;
Line3: TLine;
Line4: TLine;
pnlAlign: TPanel;
procedure FormActivate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormCreate(Sender: TObject);
private
FShown: Boolean;
protected
FCentered: Boolean;
procedure LoadFormState(AIni: TCustomIniFile); virtual;
procedure SaveFormState(AIni: TCustomIniFile); virtual;
procedure WaitModal;
public
procedure LoadState;
procedure SaveState;
end;
procedure FDGUIxFMXCancel;
function FDGUIxFMXBeginModal(AForm: TCustomForm; ASaveActive: Boolean = True): Pointer;
procedure FDGUIxFMXEndModal(var AData: Pointer);
function FDGUIxFMXSetupEditor(ACombo: TComboBox; AEdit: TEdit;
AFileEdt: TCustomEdit; AOpenDlg: TOpenDialog; const AType: String): Integer;
implementation
{$R *.fmx}
uses
{$IFDEF MSWINDOWS}
Winapi.Messages, Winapi.Windows, System.Win.Registry,
{$ENDIF}
FireDAC.Stan.Consts, FireDAC.Stan.Util;
{$IFDEF MSWINDOWS}
type
PTaskWindow = ^TTaskWindow;
TTaskWindow = record
Next: PTaskWindow;
Window: hwnd;
end;
var
TaskActiveWindow: HWND = 0;
TaskFirstWindow: HWND = 0;
TaskFirstTopMost: HWND = 0;
TaskWindowList: PTaskWindow = nil;
{-------------------------------------------------------------------------------}
function DoDisableWindow(Window: hwnd; Data: Longint): bool; stdcall;
var
P: PTaskWindow;
begin
if (Window <> TaskActiveWindow) and IsWindowVisible(Window) and IsWindowEnabled(Window) then
begin
New(P);
P^.Next := TaskWindowList;
P^.Window := Window;
TaskWindowList := P;
EnableWindow(Window, False);
end;
Result := True;
end;
{-------------------------------------------------------------------------------}
procedure EnableTaskWindows(WindowList: Pointer);
var
P: PTaskWindow;
begin
while WindowList <> nil do
begin
P := WindowList;
if IsWindow(P^.Window) then
EnableWindow(P^.Window, True);
WindowList := P^.Next;
Dispose(P);
end;
end;
{-------------------------------------------------------------------------------}
function DisableTaskWindows(ActiveWindow: HWND): Pointer;
var
SaveActiveWindow: hwnd;
SaveWindowList: Pointer;
begin
Result := nil;
SaveActiveWindow := TaskActiveWindow;
SaveWindowList := TaskWindowList;
TaskActiveWindow := ActiveWindow;
TaskWindowList := nil;
try
try
EnumThreadWindows(GetCurrentThreadID, @DoDisableWindow, 0);
Result := TaskWindowList;
except
EnableTaskWindows(TaskWindowList);
raise;
end;
finally
TaskWindowList := SaveWindowList;
TaskActiveWindow := SaveActiveWindow;
end;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
procedure FDGUIxFMXCancel;
begin
{$IFDEF MSWINDOWS}
if GetCapture <> 0 then
SendMessage(GetCapture, WM_CANCELMODE, 0, 0);
ReleaseCapture;
{$ENDIF}
end;
{$IFDEF MSWINDOWS}
type
TFDGUIxFMXModalData = class(TObject)
private
FWindowList: Pointer;
FActiveWindow: HWnd;
end;
{$ENDIF}
{-------------------------------------------------------------------------------}
function FDGUIxFMXBeginModal(AForm: TCustomForm; ASaveActive: Boolean = True): Pointer;
{$IFDEF MSWINDOWS}
var
oData: TFDGUIxFMXModalData;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
Result := TFDGUIxFMXModalData.Create;
oData := TFDGUIxFMXModalData(Result);
oData.FWindowList := DisableTaskWindows(0);
if ASaveActive then
oData.FActiveWindow := GetActiveWindow
else
oData.FActiveWindow := 0;
{$ELSE}
Result := nil;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure FDGUIxFMXEndModal(var AData: Pointer);
{$IFDEF MSWINDOWS}
var
oData: TFDGUIxFMXModalData;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
oData := TFDGUIxFMXModalData(AData);
EnableTaskWindows(oData.FWindowList);
if oData.FActiveWindow <> 0 then
SetActiveWindow(oData.FActiveWindow);
FDFree(oData);
{$ENDIF}
AData := nil;
end;
{-------------------------------------------------------------------------------}
function FDGUIxFMXSetupEditor(ACombo: TComboBox; AEdit: TEdit;
AFileEdt: TCustomEdit; AOpenDlg: TOpenDialog; const AType: String): Integer;
var
i: Integer;
begin
Result := 1;
if AType = '@L' then begin
ACombo.Items.BeginUpdate;
try
ACombo.Items.Clear;
ACombo.Items.Add(S_FD_True);
ACombo.Items.Add(S_FD_False);
finally
ACombo.Items.EndUpdate;
end;
ACombo.ItemIndex := 1;
end
else if AType = '@Y' then begin
ACombo.Items.BeginUpdate;
try
ACombo.Items.Clear;
ACombo.Items.Add(S_FD_Yes);
ACombo.Items.Add(S_FD_No);
finally
ACombo.Items.EndUpdate;
end;
ACombo.ItemIndex := 1;
end
else if AType = '@I' then begin
AEdit.Text := '0';
Result := 0;
end
else if (AType = '') or (AType = '@S') or (AType = '@P') then begin
AEdit.Text := '';
Result := 0;
end
else if Copy(AType, 1, 2) = '@F' then begin
AFileEdt.Text := '';
AOpenDlg.Filter := Copy(AType, 4, MAXINT) + '|All Files|*.*';
AOpenDlg.FilterIndex := 0;
Result := 2;
end
else begin
i := 1;
ACombo.Items.BeginUpdate;
try
ACombo.Items.Clear;
while i <= Length(AType) do
ACombo.Items.Add(FDExtractFieldName(AType, i));
finally
ACombo.Items.EndUpdate;
end;
ACombo.ItemIndex := -1;
end;
end;
{------------------------------------------------------------------------------}
{ TfrmFDGUIxFMXOptsBase }
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.FormActivate(Sender: TObject);
var
oMainForm: TCommonCustomForm;
begin
if not FShown then
DoShow;
// In FMX setting position to poMainFormCenter doesn't work
if FCentered then begin
oMainForm := Application.MainForm;
if (oMainForm <> nil) and oMainForm.Visible then begin
Left := oMainForm.Left + (oMainForm.Width - Width) div 2;
Top := oMainForm.Top + (oMainForm.Height - Height) div 2;
end
else
Position := TFormPosition.ScreenCenter;
end;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
FShown := False;
DoHide;
end;
{-------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.FormCreate(Sender: TObject);
begin
FShown := False;
FCentered := False;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.LoadFormState(AIni: TCustomIniFile);
var
eWinState: TWindowState;
begin
eWinState := TWindowState(AIni.ReadInteger(Name, 'State', Integer(WindowState)));
if eWinState = TWindowState.wsNormal then begin
Position := TFormPosition.Designed;
Width := AIni.ReadInteger(Name, 'Width', Width);
Height := AIni.ReadInteger(Name, 'Height', Height);
Top := AIni.ReadInteger(Name, 'Top', Top);
Left := AIni.ReadInteger(Name, 'Left', Left);
end
else if eWinState = TWindowState.wsMaximized then
WindowState := TWindowState.wsMaximized;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.SaveFormState(AIni: TCustomIniFile);
begin
AIni.WriteInteger(Name, 'State', Integer(WindowState));
if WindowState = TWindowState.wsNormal then begin
AIni.WriteInteger(Name, 'Width', Width);
AIni.WriteInteger(Name, 'Height', Height);
AIni.WriteInteger(Name, 'Top', Top);
AIni.WriteInteger(Name, 'Left', Left);
end;
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.LoadState;
var
oIni: TCustomIniFile;
begin
oIni := TFDConfigFile.Create(True);
try
Position := TFormPosition.MainFormCenter;
if oIni.SectionExists(Name) then
LoadFormState(oIni);
except
end;
FDFree(oIni);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.SaveState;
var
oIni: TCustomIniFile;
begin
oIni := TFDConfigFile.Create(False);
try
SaveFormState(oIni);
except
end;
FDFree(oIni);
end;
{------------------------------------------------------------------------------}
procedure TfrmFDGUIxFMXOptsBase.WaitModal;
begin
while Visible and not Application.Terminated do
Application.ProcessMessages;
end;
end.
|
unit ChatClass;
interface
uses Dialogs, SysUtils, Uni;
Type
TChat = class(TObject)
private
Connection: TUniConnection; // Подсоединение
Query: TUniQuery; // Переменная для набора данных
ConnectStr: string;
ChatDataBasePublic: string; // Имена баз данных (Для всех)
ChatDataBasePrivate: string; // Имена баз данных (Приват)
MaxPageSizeForBasePublic: Integer; // Макс. записей для (Для всех)
MaxPageSizeForBasePrivate: Integer; // Макс. записей для (Для всех)
procedure Update; overload;
procedure Delete; overload;
procedure Update(UserID: Integer); overload;
procedure Delete(UserID: Integer); overload;
public
constructor Create;
destructor Destroy; override;
procedure SentMessagePublic(Message: string);
// Поcылаем сообщение (Для всех)
procedure SentMessagePrivate(Message: string; UserID: Integer);
// Поcылаем сообщение (Приват)
function GetMessagePublic(MaxPageSizeForUser: Integer): string;
// Получаем сообщение (Для всех)
function GetMessagePrivate(MaxPageSizeForUser: Integer; UserID: Integer)
: string; // Получаем сообщение (Приват)
procedure Open;
procedure Close;
published
property ConnectionString: string read ConnectStr write ConnectStr;
property DataBasePublic: string read ChatDataBasePublic
write ChatDataBasePublic;
property DataBasePrivate: string read ChatDataBasePrivate
write ChatDataBasePrivate;
property PageSizeForBasePublic: Integer read MaxPageSizeForBasePublic
write MaxPageSizeForBasePublic;
property PageSizeForBasePrivate: Integer read MaxPageSizeForBasePrivate
write MaxPageSizeForBasePrivate;
end;
implementation
end.
|
unit SHA1;
{SHA1 - 160 bit Secure Hash Function}
interface
(*************************************************************************
DESCRIPTION : SHA1 - 160 bit Secure Hash Function
REQUIREMENTS : TP5-7, D1-D7/D9-D10/D12/D17-D18/D25S, FPC, VP
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
REFERENCES : - Latest specification of Secure Hash Standard:
http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
- Test vectors and intermediate values:
http://csrc.nist.gov/groups/ST/toolkit/documents/Examples/SHA_All.pdf
Version Date Author Modification
------- -------- ------- ------------------------------------------
1.00 03.01.02 W.Ehrhardt BP7 implementation
1.01 14.03.02 we D1-D6, FPC, VP
1.02 14.03.02 we TP6
1.03 14.03.02 we TP6/7 386-Code
1.04 14.03.02 we TP5.5
1.10 15.03.02 we self test with 2 strings
1.11 02.01.03 we const SFA with @ for FPC 1.0.6
1.20 23.07.03 we With SHA1File, SHA1Full
1.21 26.07.03 we With SHA1Full in self test
2.00 26.07.03 we common vers., longint for word32, D4+ - warnings
2.01 03.08.03 we type TSHA1Block for HMAC
2.02 23.08.03 we SHA1Compress in interface for prng
2.10 29.08.03 we XL versions for Win32
2.20 27.09.03 we FPC/go32v2
2.30 05.10.03 we STD.INC, TP5.0
2.40 10.10.03 we common version, english comments
2.45 11.10.03 we Speedup: partial unroll, no function calls
2.50 16.11.03 we Speedup in update, don't clear W in compress
2.51 17.11.03 we BIT16: partial unroll, BIT32: inline rot
2.52 17.11.03 we ExpandMessageBlocks
2.53 18.11.03 we LRot32, RB mit inline()
2.54 20.11.03 we Full range UpdateLen
2.55 30.11.03 we BIT16: {$F-}
2.56 30.11.03 we BIT16: LRot_5, LRot_30
3.00 01.12.03 we Common version 3.0
3.01 22.12.03 we BIT16: Two INCs
3.02 22.12.03 we BASM16: asm Lrot30
3.03 22.12.03 we TP5/5.5: LRot, RA inline
3.04 22,12.03 we Changed UpdateLen: Definition and TP5/5.5 inline
3.05 05.03.04 we Update fips180-2 URL
3.06 26.02.05 we With {$ifdef StrictLong}
3.07 05.05.05 we Use longint() in SH1Init to avoid D9 errors if $R+
3.08 17.12.05 we Force $I- in SHA1File
3.09 08.01.06 we SHA1Compress removed from interface
3.10 15.01.06 we uses Hash unit and THashDesc
3.11 18.01.06 we Descriptor fields HAlgNum, HSig
3.12 22.01.06 we Removed HSelfTest from descriptor
3.13 11.02.06 we Descriptor as typed const
3.14 26.03.06 we Round constants K1..K4, code reordering
3.15 07.08.06 we $ifdef BIT32: (const fname: shortstring...)
3.16 22.02.07 we values for OID vector
3.17 30.06.07 we Use conditional define FPC_ProcVar
3.18 04.10.07 we FPC: {$asmmode intel}
3.19 02.05.08 we Bit-API: SHA1FinalBits/Ex
3.20 05.05.08 we THashDesc constant with HFinalBit field
3.21 12.11.08 we uses BTypes, Ptr2Inc and/or Str255/Str127
3.22 12.03.10 we Fix VP feature in ExpandMessageBlocks
3.23 11.03.12 we Updated references
3.24 26.12.12 we D17 and PurePascal
3.25 16.08.15 we Removed $ifdef DLL / stdcall
3.26 15.05.17 we adjust OID to new MaxOIDLen
3.27 29.11.17 we SHA1File - fname: string
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2002-2017 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.
----------------------------------------------------------------------------*)
{NOTE: FIPS Ch and May functions can be optimized. Wei Dai (Crypto++ 3.1)
credits Rich Schroeppel (rcs@cs.arizona.edu), V 5.1 does not!?}
{$i STD.INC}
{$ifdef BIT64}
{$ifndef PurePascal}
{$define PurePascal}
{$endif}
{$endif}
uses
BTypes,Hash;
procedure SHA1Init(var Context: THashContext);
{-initialize context}
procedure SHA1Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
procedure SHA1UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
procedure SHA1Final(var Context: THashContext; var Digest: TSHA1Digest);
{-finalize SHA1 calculation, clear context}
procedure SHA1FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize SHA1 calculation, clear context}
procedure SHA1FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize SHA1 calculation with bitlen bits from BData (big-endian), clear context}
procedure SHA1FinalBits(var Context: THashContext; var Digest: TSHA1Digest; BData: byte; bitlen: integer);
{-finalize SHA1 calculation with bitlen bits from BData (big-endian), clear context}
function SHA1SelfTest: boolean;
{-self test SHA1: compare with known value}
procedure SHA1Full(var Digest: TSHA1Digest; Msg: pointer; Len: word);
{-SHA1 of Msg with init/update/final}
procedure SHA1FullXL(var Digest: TSHA1Digest; Msg: pointer; Len: longint);
{-SHA1 of Msg with init/update/final}
procedure SHA1File({$ifdef CONST} const {$endif} fname: string;
var Digest: TSHA1Digest; var buf; bsize: word; var Err: word);
{-SHA1 of file, buf: buffer with at least bsize bytes}
implementation
{$ifdef BIT16}
{$F-}
{$endif}
const
SHA1_BlockLen = 64;
const {round constants}
K1 = longint($5A827999); {round 00..19}
K2 = longint($6ED9EBA1); {round 20..39}
K3 = longint($8F1BBCDC); {round 40..59}
K4 = longint($CA62C1D6); {round 60..79}
{Internal types}
type
TWorkBuf = array[0..79] of longint;
{1.3.14.3.2.26}
{iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) hashAlgorithmIdentifier(26)}
const
SHA1_OID : TOID_Vec = (1,3,14,3,2,26,-1,-1,-1,-1,-1); {Len=6}
{$ifndef VER5X}
const
SHA1_Desc: THashDesc = (
HSig : C_HashSig;
HDSize : sizeof(THashDesc);
HDVersion : C_HashVers;
HBlockLen : SHA1_BlockLen;
HDigestlen: sizeof(TSHA1Digest);
{$ifdef FPC_ProcVar}
HInit : @SHA1Init;
HFinal : @SHA1FinalEx;
HUpdateXL : @SHA1UpdateXL;
{$else}
HInit : SHA1Init;
HFinal : SHA1FinalEx;
HUpdateXL : SHA1UpdateXL;
{$endif}
HAlgNum : longint(_SHA1);
HName : 'SHA1';
HPtrOID : @SHA1_OID;
HLenOID : 6;
HFill : 0;
{$ifdef FPC_ProcVar}
HFinalBit : @SHA1FinalBitsEx;
{$else}
HFinalBit : SHA1FinalBitsEx;
{$endif}
HReserved : (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
);
{$else}
var
SHA1_Desc: THashDesc;
{$endif}
{$ifndef BIT16}
{$ifdef PurePascal}
{---------------------------------------------------------------------------}
procedure UpdateLen(var whi, wlo: longint; BLen: longint);
{-Add BLen to 64 bit value (wlo, whi)}
var
tmp: int64;
begin
tmp := int64(cardinal(wlo))+Blen;
wlo := longint(tmp and $FFFFFFFF);
inc(whi,longint(tmp shr 32));
end;
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
begin
RB := ((A and $FF) shl 24) or ((A and $FF00) shl 8) or ((A and $FF0000) shr 8) or ((A and longint($FF000000)) shr 24);
end;
{---------------------------------------------------------------------------}
procedure ExpandMessageBlocks(var W: TWorkBuf; var Buf: THashBuffer);
{-Calculate "expanded message blocks"}
var
i,T: longint;
begin
{Part 1: Transfer buffer with little -> big endian conversion}
for i:= 0 to 15 do W[i]:= RB(THashBuf32(Buf)[i]);
{Part 2: Calculate remaining "expanded message blocks"}
for i:= 16 to 79 do begin
T := W[i-3] xor W[i-8] xor W[i-14] xor W[i-16];
W[i] := (T shl 1) or (T shr 31);
end;
end;
{$else}
{---------------------------------------------------------------------------}
procedure UpdateLen(var whi, wlo: longint; BLen: longint);
{-Add BLen to 64 bit value (wlo, whi)}
begin
asm
mov edx, [wlo]
mov ecx, [whi]
mov eax, [Blen]
add [edx], eax
adc dword ptr [ecx], 0
end;
end;
{---------------------------------------------------------------------------}
function RB(A: longint): longint; assembler;
{-reverse byte order in longint}
asm
{$ifdef LoadArgs}
mov eax,[A]
{$endif}
xchg al,ah
rol eax,16
xchg al,ah
end;
{---------------------------------------------------------------------------}
procedure ExpandMessageBlocks(var W: TWorkBuf; var Buf: THashBuffer); assembler;
{-Calculate "expanded message blocks"}
asm
{$ifdef LoadArgs}
mov edx,Buf
mov ecx,W {load W before push ebx to avoid VP crash}
push ebx {if compiling with no ASM stack frames}
mov ebx,ecx
{$else}
push ebx
mov ebx,eax
{$endif}
{part1: W[i]:= RB(TW32Buf(Buf)[i])}
mov ecx,16
@@1: mov eax,[edx]
xchg al,ah
rol eax,16
xchg al,ah
mov [ebx],eax
add ebx,4
add edx,4
dec ecx
jnz @@1
{part2: W[i]:= LRot_1(W[i-3] xor W[i-8] xor W[i-14] xor W[i-16]);}
mov ecx,64
@@2: mov eax,[ebx- 3*4]
xor eax,[ebx- 8*4]
xor eax,[ebx-14*4]
xor eax,[ebx-16*4]
rol eax,1
mov [ebx],eax
add ebx,4
dec ecx
jnz @@2
pop ebx
end;
{$endif}
{---------------------------------------------------------------------------}
procedure SHA1Compress(var Data: THashContext);
{-Actual hashing function}
var
i: integer;
A, B, C, D, E: longint;
W: TWorkBuf;
begin
ExpandMessageBlocks(W, Data.Buffer);
A := Data.Hash[0];
B := Data.Hash[1];
C := Data.Hash[2];
D := Data.Hash[3];
E := Data.Hash[4];
{SHA1 compression function}
{Partial unroll for more speed, full unroll is only slightly faster}
{BIT32: rotateleft via inline}
i := 0;
while i<20 do begin
inc(E, (A shl 5 or A shr 27) + (D xor (B and (C xor D))) + W[i ] + K1); B := B shr 2 or B shl 30;
inc(D, (E shl 5 or E shr 27) + (C xor (A and (B xor C))) + W[i+1] + K1); A := A shr 2 or A shl 30;
inc(C, (D shl 5 or D shr 27) + (B xor (E and (A xor B))) + W[i+2] + K1); E := E shr 2 or E shl 30;
inc(B, (C shl 5 or C shr 27) + (A xor (D and (E xor A))) + W[i+3] + K1); D := D shr 2 or D shl 30;
inc(A, (B shl 5 or B shr 27) + (E xor (C and (D xor E))) + W[i+4] + K1); C := C shr 2 or C shl 30;
inc(i,5);
end;
while i<40 do begin
inc(E, (A shl 5 or A shr 27) + (D xor B xor C) + W[i ] + K2); B := B shr 2 or B shl 30;
inc(D, (E shl 5 or E shr 27) + (C xor A xor B) + W[i+1] + K2); A := A shr 2 or A shl 30;
inc(C, (D shl 5 or D shr 27) + (B xor E xor A) + W[i+2] + K2); E := E shr 2 or E shl 30;
inc(B, (C shl 5 or C shr 27) + (A xor D xor E) + W[i+3] + K2); D := D shr 2 or D shl 30;
inc(A, (B shl 5 or B shr 27) + (E xor C xor D) + W[i+4] + K2); C := C shr 2 or C shl 30;
inc(i,5);
end;
while i<60 do begin
inc(E, (A shl 5 or A shr 27) + ((B and C) or (D and (B or C))) + W[i ] + K3); B := B shr 2 or B shl 30;
inc(D, (E shl 5 or E shr 27) + ((A and B) or (C and (A or B))) + W[i+1] + K3); A := A shr 2 or A shl 30;
inc(C, (D shl 5 or D shr 27) + ((E and A) or (B and (E or A))) + W[i+2] + K3); E := E shr 2 or E shl 30;
inc(B, (C shl 5 or C shr 27) + ((D and E) or (A and (D or E))) + W[i+3] + K3); D := D shr 2 or D shl 30;
inc(A, (B shl 5 or B shr 27) + ((C and D) or (E and (C or D))) + W[i+4] + K3); C := C shr 2 or C shl 30;
inc(i,5);
end;
while i<80 do begin
inc(E, (A shl 5 or A shr 27) + (D xor B xor C) + W[i ] + K4); B := B shr 2 or B shl 30;
inc(D, (E shl 5 or E shr 27) + (C xor A xor B) + W[i+1] + K4); A := A shr 2 or A shl 30;
inc(C, (D shl 5 or D shr 27) + (B xor E xor A) + W[i+2] + K4); E := E shr 2 or E shl 30;
inc(B, (C shl 5 or C shr 27) + (A xor D xor E) + W[i+3] + K4); D := D shr 2 or D shl 30;
inc(A, (B shl 5 or B shr 27) + (E xor C xor D) + W[i+4] + K4); C := C shr 2 or C shl 30;
inc(i,5);
end;
{Calculate new working hash}
inc(Data.Hash[0], A);
inc(Data.Hash[1], B);
inc(Data.Hash[2], C);
inc(Data.Hash[3], D);
inc(Data.Hash[4], E);
end;
{$else}
{$ifdef BASM16}
{TP6-7/Delphi1 for 386+}
{---------------------------------------------------------------------------}
procedure UpdateLen(var whi, wlo: longint; BLen: longint); assembler;
{-Add BLen to 64 bit value (wlo, whi)}
asm
les di,[wlo]
db $66; mov ax,word ptr [BLen]
db $66; sub dx,dx
db $66; add es:[di],ax
les di,[whi]
db $66; adc es:[di],dx
end;
{---------------------------------------------------------------------------}
function LRot_5(x: longint): longint;
{-Rotate left 5}
inline(
$66/$58/ {pop eax }
$66/$C1/$C0/$05/ {rol eax,5 }
$66/$8B/$D0/ {mov edx,eax}
$66/$C1/$EA/$10); {shr edx,16 }
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$86/$C6/ {xchg dh,al }
$86/$E2); {xchg dl,ah }
{---------------------------------------------------------------------------}
procedure ExpandMessageBlocks(var W: TWorkBuf; var Buf: THashBuffer); assembler;
{-Calculate "expanded message blocks"}
asm
push ds
{part 1: W[i]:= RB(TW32Buf(Buf)[i])}
les di,[Buf]
lds si,[W]
mov cx,16
@@1: db $66; mov ax,es:[di]
xchg al,ah
db $66; rol ax,16
xchg al,ah
db $66; mov [si],ax
add si,4
add di,4
dec cx
jnz @@1
{part 2: W[i]:= LRot_1(W[i-3] xor W[i-8] xor W[i-14] xor W[i-16]);}
mov cx,64
@@2: db $66; mov ax,[si- 3*4]
db $66; xor ax,[si- 8*4]
db $66; xor ax,[si-14*4]
db $66; xor ax,[si-16*4]
db $66; rol ax,1
db $66; mov [si],ax
add si,4
dec cx
jnz @@2
pop ds
end;
{---------------------------------------------------------------------------}
procedure SHA1Compress(var Data: THashContext);
{-Actual hashing function}
var
i: integer;
A, B, C, D, E: longint;
W: TWorkBuf;
begin
ExpandMessageBlocks(W, Data.Buffer);
{Assign old working hash to variables A..E}
A := Data.Hash[0];
B := Data.Hash[1];
C := Data.Hash[2];
D := Data.Hash[3];
E := Data.Hash[4];
{SHA1 compression function}
{Partial unroll for more speed, full unroll only marginally faster}
{Two INCs, LRot_30 via BASM}
i := 0;
while i<20 do begin
inc(E,LRot_5(A)); inc(E,(D xor (B and (C xor D))) + W[i ] + K1); asm db $66; rol word[B],30 end;
inc(D,LRot_5(E)); inc(D,(C xor (A and (B xor C))) + W[i+1] + K1); asm db $66; rol word[A],30 end;
inc(C,LRot_5(D)); inc(C,(B xor (E and (A xor B))) + W[i+2] + K1); asm db $66; rol word[E],30 end;
inc(B,LRot_5(C)); inc(B,(A xor (D and (E xor A))) + W[i+3] + K1); asm db $66; rol word[D],30 end;
inc(A,LRot_5(B)); inc(A,(E xor (C and (D xor E))) + W[i+4] + K1); asm db $66; rol word[C],30 end;
inc(i,5);
end;
while i<40 do begin
inc(E,LRot_5(A)); inc(E,(B xor C xor D) + W[i ] + K2); asm db $66; rol word[B],30 end;
inc(D,LRot_5(E)); inc(D,(A xor B xor C) + W[i+1] + K2); asm db $66; rol word[A],30 end;
inc(C,LRot_5(D)); inc(C,(E xor A xor B) + W[i+2] + K2); asm db $66; rol word[E],30 end;
inc(B,LRot_5(C)); inc(B,(D xor E xor A) + W[i+3] + K2); asm db $66; rol word[D],30 end;
inc(A,LRot_5(B)); inc(A,(C xor D xor E) + W[i+4] + K2); asm db $66; rol word[C],30 end;
inc(i,5);
end;
while i<60 do begin
inc(E,LRot_5(A)); inc(E,((B and C) or (D and (B or C))) + W[i ] + K3); asm db $66; rol word[B],30 end;
inc(D,LRot_5(E)); inc(D,((A and B) or (C and (A or B))) + W[i+1] + K3); asm db $66; rol word[A],30 end;
inc(C,LRot_5(D)); inc(C,((E and A) or (B and (E or A))) + W[i+2] + K3); asm db $66; rol word[E],30 end;
inc(B,LRot_5(C)); inc(B,((D and E) or (A and (D or E))) + W[i+3] + K3); asm db $66; rol word[D],30 end;
inc(A,LRot_5(B)); inc(A,((C and D) or (E and (C or D))) + W[i+4] + K3); asm db $66; rol word[C],30 end;
inc(i,5);
end;
while i<80 do begin
inc(E,LRot_5(A)); inc(E,(B xor C xor D) + W[i ] + K4); asm db $66; rol word[B],30 end;
inc(D,LRot_5(E)); inc(D,(A xor B xor C) + W[i+1] + K4); asm db $66; rol word[A],30 end;
inc(C,LRot_5(D)); inc(C,(E xor A xor B) + W[i+2] + K4); asm db $66; rol word[E],30 end;
inc(B,LRot_5(C)); inc(B,(D xor E xor A) + W[i+3] + K4); asm db $66; rol word[D],30 end;
inc(A,LRot_5(B)); inc(A,(C xor D xor E) + W[i+4] + K4); asm db $66; rol word[C],30 end;
inc(i,5);
end;
{Calculate new working hash}
inc(Data.Hash[0], A);
inc(Data.Hash[1], B);
inc(Data.Hash[2], C);
inc(Data.Hash[3], D);
inc(Data.Hash[4], E);
end;
{$else}
{TP5/5.5}
{---------------------------------------------------------------------------}
procedure UpdateLen(var whi, wlo: longint; BLen: longint);
{-Add BLen to 64 bit value (wlo, whi)}
inline(
$58/ {pop ax }
$5A/ {pop dx }
$5B/ {pop bx }
$07/ {pop es }
$26/$01/$07/ {add es:[bx],ax }
$26/$11/$57/$02/ {adc es:[bx+02],dx}
$5B/ {pop bx }
$07/ {pop es }
$26/$83/$17/$00/ {adc es:[bx],0 }
$26/$83/$57/$02/$00);{adc es:[bx+02],0 }
{---------------------------------------------------------------------------}
function RB(A: longint): longint;
{-reverse byte order in longint}
inline(
$58/ { pop ax }
$5A/ { pop dx }
$86/$C6/ { xchg dh,al}
$86/$E2); { xchg dl,ah}
{---------------------------------------------------------------------------}
function LRot_1(x: longint): longint;
{-Rotate left 1}
inline(
$58/ { pop ax }
$5A/ { pop dx }
$2B/$C9/ { sub cx,cx}
$D1/$D0/ { rcl ax,1 }
$D1/$D2/ { rcl dx,1 }
$13/$C1); { adc ax,cx}
{---------------------------------------------------------------------------}
function LRot_5(x: longint): longint;
{-Rotate left 5}
inline(
$58/ { pop ax }
$5A/ { pop dx }
$2B/$C9/ { sub cx,cx}
$D1/$D0/ { rcl ax,1 }
$D1/$D2/ { rcl dx,1 }
$13/$C1/ { adc ax,cx}
$D1/$D0/ { rcl ax,1 }
$D1/$D2/ { rcl dx,1 }
$13/$C1/ { adc ax,cx}
$D1/$D0/ { rcl ax,1 }
$D1/$D2/ { rcl dx,1 }
$13/$C1/ { adc ax,cx}
$D1/$D0/ { rcl ax,1 }
$D1/$D2/ { rcl dx,1 }
$13/$C1/ { adc ax,cx}
$D1/$D0/ { rcl ax,1 }
$D1/$D2/ { rcl dx,1 }
$13/$C1); { adc ax,cx}
{---------------------------------------------------------------------------}
function LRot_30(x: longint): longint;
{-Rotate left 30 = rot right 2}
inline(
$58/ { pop ax }
$5A/ { pop dx }
$8B/$CA/ { mov cx,dx}
$D1/$E9/ { shr cx,1 }
$D1/$D8/ { rcr ax,1 }
$D1/$DA/ { rcr dx,1 }
$8B/$CA/ { mov cx,dx}
$D1/$E9/ { shr cx,1 }
$D1/$D8/ { rcr ax,1 }
$D1/$DA); { rcr dx,1 }
{---------------------------------------------------------------------------}
procedure ExpandMessageBlocks(var W: TWorkBuf; var Buf: THashBuffer);
{-Calculate "expanded message blocks"}
var
i: integer;
begin
{Part 1: Transfer buffer with little -> big endian conversion}
for i:= 0 to 15 do W[i]:= RB(THashBuf32(Buf)[i]);
{Part 2: Calculate remaining "expanded message blocks"}
for i:= 16 to 79 do W[i]:= LRot_1(W[i-3] xor W[i-8] xor W[i-14] xor W[i-16]);
end;
{---------------------------------------------------------------------------}
procedure SHA1Compress(var Data: THashContext);
{-Actual hashing function}
var
i: integer;
A, B, C, D, E: longint;
W: TWorkBuf;
begin
ExpandMessageBlocks(W, Data.Buffer);
{Assign old working hash to variables A..E}
A := Data.Hash[0];
B := Data.Hash[1];
C := Data.Hash[2];
D := Data.Hash[3];
E := Data.Hash[4];
{SHA1 compression function}
{Partial unroll for more speed, full unroll only marginally faster}
{BIT16: rotateleft via function call}
i := 0;
while i<20 do begin
inc(E,LRot_5(A) + (D xor (B and (C xor D))) + W[i ] + K1); B := LRot_30(B);
inc(D,LRot_5(E) + (C xor (A and (B xor C))) + W[i+1] + K1); A := LRot_30(A);
inc(C,LRot_5(D) + (B xor (E and (A xor B))) + W[i+2] + K1); E := LRot_30(E);
inc(B,LRot_5(C) + (A xor (D and (E xor A))) + W[i+3] + K1); D := LRot_30(D);
inc(A,LRot_5(B) + (E xor (C and (D xor E))) + W[i+4] + K1); C := LRot_30(C);
inc(i,5);
end;
while i<40 do begin
inc(E,LRot_5(A) + (B xor C xor D) + W[i ] + K2); B := LRot_30(B);
inc(D,LRot_5(E) + (A xor B xor C) + W[i+1] + K2); A := LRot_30(A);
inc(C,LRot_5(D) + (E xor A xor B) + W[i+2] + K2); E := LRot_30(E);
inc(B,LRot_5(C) + (D xor E xor A) + W[i+3] + K2); D := LRot_30(D);
inc(A,LRot_5(B) + (C xor D xor E) + W[i+4] + K2); C := LRot_30(C);
inc(i,5);
end;
while i<60 do begin
inc(E,LRot_5(A) + ((B and C) or (D and (B or C))) + W[i ] + K3); B := LRot_30(B);
inc(D,LRot_5(E) + ((A and B) or (C and (A or B))) + W[i+1] + K3); A := LRot_30(A);
inc(C,LRot_5(D) + ((E and A) or (B and (E or A))) + W[i+2] + K3); E := LRot_30(E);
inc(B,LRot_5(C) + ((D and E) or (A and (D or E))) + W[i+3] + K3); D := LRot_30(D);
inc(A,LRot_5(B) + ((C and D) or (E and (C or D))) + W[i+4] + K3); C := LRot_30(C);
inc(i,5);
end;
while i<80 do begin
inc(E,LRot_5(A) + (B xor C xor D) + W[i ] + K4); B := LRot_30(B);
inc(D,LRot_5(E) + (A xor B xor C) + W[i+1] + K4); A := LRot_30(A);
inc(C,LRot_5(D) + (E xor A xor B) + W[i+2] + K4); E := LRot_30(E);
inc(B,LRot_5(C) + (D xor E xor A) + W[i+3] + K4); D := LRot_30(D);
inc(A,LRot_5(B) + (C xor D xor E) + W[i+4] + K4); C := LRot_30(C);
inc(i,5);
end;
{Calculate new working hash}
inc(Data.Hash[0], A);
inc(Data.Hash[1], B);
inc(Data.Hash[2], C);
inc(Data.Hash[3], D);
inc(Data.Hash[4], E);
end;
{$endif BASM16}
{$endif BIT16}
{---------------------------------------------------------------------------}
procedure SHA1Init(var Context: THashContext);
{-initialize context}
begin
{Clear context, buffer=0!!}
fillchar(Context,sizeof(Context),0);
with Context do begin
Hash[0] := longint($67452301);
Hash[1] := longint($EFCDAB89);
Hash[2] := longint($98BADCFE);
Hash[3] := longint($10325476);
Hash[4] := longint($C3D2E1F0);
end;
end;
{---------------------------------------------------------------------------}
procedure SHA1UpdateXL(var Context: THashContext; Msg: pointer; Len: longint);
{-update context with Msg data}
var
i: integer;
begin
{Update message bit length}
if Len<=$1FFFFFFF then UpdateLen(Context.MLen[1], Context.MLen[0], Len shl 3)
else begin
for i:=1 to 8 do UpdateLen(Context.MLen[1], Context.MLen[0], Len)
end;
while Len > 0 do begin
{fill block with msg data}
Context.Buffer[Context.Index]:= pByte(Msg)^;
inc(Ptr2Inc(Msg));
inc(Context.Index);
dec(Len);
if Context.Index=SHA1_BlockLen then begin
{If 512 bit transferred, compress a block}
Context.Index:= 0;
SHA1Compress(Context);
while Len>=SHA1_BlockLen do begin
move(Msg^,Context.Buffer,SHA1_BlockLen);
SHA1Compress(Context);
inc(Ptr2Inc(Msg),SHA1_BlockLen);
dec(Len,SHA1_BlockLen);
end;
end;
end;
end;
{---------------------------------------------------------------------------}
procedure SHA1Update(var Context: THashContext; Msg: pointer; Len: word);
{-update context with Msg data}
begin
SHA1UpdateXL(Context, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA1FinalBitsEx(var Context: THashContext; var Digest: THashDigest; BData: byte; bitlen: integer);
{-finalize SHA1 calculation with bitlen bits from BData (big-endian), clear context}
var
i: integer;
begin
{Message padding}
{append bits from BData and a single '1' bit}
if (bitlen>0) and (bitlen<=7) then begin
Context.Buffer[Context.Index]:= (BData and BitAPI_Mask[bitlen]) or BitAPI_PBit[bitlen];
UpdateLen(Context.MLen[1], Context.MLen[0], bitlen);
end
else Context.Buffer[Context.Index]:= $80;
for i:=Context.Index+1 to 63 do Context.Buffer[i] := 0;
{2. Compress if more than 448 bits, (no room for 64 bit length}
if Context.Index>= 56 then begin
SHA1Compress(Context);
fillchar(Context.Buffer,56,0);
end;
{Write 64 bit msg length into the last bits of the last block}
{(in big endian format) and do a final compress}
THashBuf32(Context.Buffer)[14] := RB(Context.MLen[1]);
THashBuf32(Context.Buffer)[15] := RB(Context.MLen[0]);
SHA1Compress(Context);
{Hash->Digest to little endian format}
fillchar(Digest, sizeof(Digest), 0);
for i:=0 to 4 do THashDig32(Digest)[i]:= RB(Context.Hash[i]);
{Clear context}
fillchar(Context,sizeof(Context),0);
end;
{---------------------------------------------------------------------------}
procedure SHA1FinalBits(var Context: THashContext; var Digest: TSHA1Digest; BData: byte; bitlen: integer);
{-finalize SHA1 calculation with bitlen bits from BData (big-endian), clear context}
var
tmp: THashDigest;
begin
SHA1FinalBitsEx(Context, tmp, BData, bitlen);
move(tmp, Digest, sizeof(Digest));
end;
{---------------------------------------------------------------------------}
procedure SHA1FinalEx(var Context: THashContext; var Digest: THashDigest);
{-finalize SHA1 calculation, clear context}
begin
SHA1FinalBitsEx(Context,Digest,0,0);
end;
{---------------------------------------------------------------------------}
procedure SHA1Final(var Context: THashContext; var Digest: TSHA1Digest);
{-finalize SHA1 calculation, clear context}
var
tmp: THashDigest;
begin
SHA1FinalBitsEx(Context, tmp, 0, 0);
move(tmp, Digest, sizeof(Digest));
end;
{---------------------------------------------------------------------------}
function SHA1SelfTest: boolean;
{-self test SHA1: compare with known value}
const
s1: string[ 3] = 'abc';
s2: string[56] = 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq';
D1: TSHA1Digest= ($a9,$99,$3e,$36,$47,$06,$81,$6a,$ba,$3e,$25,$71,$78,$50,$c2,$6c,$9c,$d0,$d8,$9d);
D2: TSHA1Digest= ($84,$98,$3E,$44,$1C,$3B,$D2,$6E,$BA,$AE,$4A,$A1,$F9,$51,$29,$E5,$E5,$46,$70,$F1);
D3: TSHA1Digest= ($bb,$6b,$3e,$18,$f0,$11,$5b,$57,$92,$52,$41,$67,$6f,$5b,$1a,$e8,$87,$47,$b0,$8a);
D4: TSHA1Digest= ($98,$23,$2a,$15,$34,$53,$14,$9a,$f8,$d5,$2a,$61,$50,$3a,$50,$74,$b8,$59,$70,$e8);
var
Context: THashContext;
Digest : TSHA1Digest;
function SingleTest(s: Str127; TDig: TSHA1Digest): boolean;
{-do a single test, const not allowed for VER<7}
{ Two sub tests: 1. whole string, 2. one update per char}
var
i: integer;
begin
SingleTest := false;
{1. Hash complete string}
SHA1Full(Digest, @s[1],length(s));
{Compare with known value}
if not HashSameDigest(@SHA1_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
{2. one update call for all chars}
SHA1Init(Context);
for i:=1 to length(s) do SHA1Update(Context,@s[i],1);
SHA1Final(Context,Digest);
{Compare with known value}
if not HashSameDigest(@SHA1_Desc, PHashDigest(@Digest), PHashDigest(@TDig)) then exit;
SingleTest := true;
end;
begin
SHA1SelfTest := false;
{1 Zero bit from NESSIE test vectors}
SHA1Init(Context);
SHA1FinalBits(Context,Digest,0,1);
if not HashSameDigest(@SHA1_Desc, PHashDigest(@Digest), PHashDigest(@D3)) then exit;
{4 hightest bits of $50, D4 calculated with program shatest from RFC 4634}
SHA1Init(Context);
SHA1FinalBits(Context,Digest,$50,4);
if not HashSameDigest(@SHA1_Desc, PHashDigest(@Digest), PHashDigest(@D4)) then exit;
{strings from SHA1 document}
SHA1SelfTest := SingleTest(s1, D1) and SingleTest(s2, D2)
end;
{---------------------------------------------------------------------------}
procedure SHA1FullXL(var Digest: TSHA1Digest; Msg: pointer; Len: longint);
{-SHA1 of Msg with init/update/final}
var
Context: THashContext;
begin
SHA1Init(Context);
SHA1UpdateXL(Context, Msg, Len);
SHA1Final(Context, Digest);
end;
{---------------------------------------------------------------------------}
procedure SHA1Full(var Digest: TSHA1Digest; Msg: pointer; Len: word);
{-SHA1 of Msg with init/update/final}
begin
SHA1FullXL(Digest, Msg, Len);
end;
{---------------------------------------------------------------------------}
procedure SHA1File({$ifdef CONST} const {$endif} fname: string;
var Digest: TSHA1Digest; var buf; bsize: word; var Err: word);
{-SHA1 of file, buf: buffer with at least bsize bytes}
var
tmp: THashDigest;
begin
HashFile(fname, @SHA1_Desc, tmp, buf, bsize, Err);
move(tmp, Digest, sizeof(Digest));
end;
begin
{$ifdef VER5X}
fillchar(SHA1_Desc, sizeof(SHA1_Desc), 0);
with SHA1_Desc do begin
HSig := C_HashSig;
HDSize := sizeof(THashDesc);
HDVersion := C_HashVers;
HBlockLen := SHA1_BlockLen;
HDigestlen:= sizeof(TSHA1Digest);
HInit := SHA1Init;
HFinal := SHA1FinalEx;
HUpdateXL := SHA1UpdateXL;
HAlgNum := longint(_SHA1);
HName := 'SHA1';
HPtrOID := @SHA1_OID;
HLenOID := 6;
HFinalBit := SHA1FinalBitsEx;
end;
{$endif}
RegisterHash(_SHA1, @SHA1_Desc);
end.
|
const MAX_OUT_BUF = 4096 * 4;
var
output_buffer : array[0..MAX_OUT_BUF-1] of char;
idx_output_buffer : longint;
output_stream : TFileStream;
procedure fast_write_char(x : char);
begin
(* Write one char onto the buffer *)
output_buffer[idx_output_buffer] := x;
inc(idx_output_buffer);
if idx_output_buffer = MAX_OUT_BUF then (* I'm at the end of the buffer, flush it *)
begin
output_stream.WriteBuffer(output_buffer, sizeof(output_buffer));
idx_output_buffer := 0;
end;
end;
procedure fast_write_int(x : longint);
begin
if x < 0 then (* Write the sign, then the number *)
begin
fast_write_char('-');
fast_write_int(-x);
end
else (* Write the number recursively *)
begin
if x >= 10 then
fast_write_int(x div 10);
fast_write_char(chr(ord('0') + x mod 10));
end;
end;
procedure fast_write_longint(x : int64);
begin
if x < 0 then (* Write the sign, then the number *)
begin
fast_write_char('-');
fast_write_longint(-x);
end
else (* Write the number recursively *)
begin
if x >= 10 then
fast_write_longint(x div 10);
fast_write_char(chr(ord('0') + x mod 10));
end;
end;
procedure fast_write_real(x : double);
begin
(* TODO *)
fast_write_char('4');
fast_write_char('2');
fast_write_char('.');
fast_write_char('0');
end;
procedure init_fast_output(file_name : string);
var
open_flag: word;
begin
open_flag := fmCreate;
if FileExists(file_name) then
open_flag := fmOpenWrite;
output_stream := TFileStream.Create(file_name, open_flag);
output_stream.size := 0;
idx_output_buffer := 0;
end;
procedure close_fast_output;
begin
if idx_output_buffer > 0 then (* Gotta flush them bytez *)
begin
(* TODO: check if this is OK also when using unicode data *)
output_stream.Write(output_buffer, idx_output_buffer * sizeof(output_buffer[0]))
end;
output_stream.Free;
end;
|
unit ProducerInterface;
interface
type
IProducer = interface(IInterface)
function GetProducerID(const AProducerName: String): Integer; stdcall;
function Exist(const AProducerName: String): Boolean; stdcall;
end;
implementation
end.
|
unit HomeOrder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, Grids, DBGridEh,
DB, ComCtrls, ToolWin;
type
THomeOrderForm = class(TForm)
DBGridEh1: TDBGridEh;
Panel1: TPanel;
CloseButton: TButton;
DBGridEh2: TDBGridEh;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
InsertButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
ToolButton2: TToolButton;
Edit1: TEdit;
ToolButton3: TToolButton;
Splitter1: TSplitter;
RefreshButton: TToolButton;
procedure EnabledButtons;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure CloseButtonClick(Sender: TObject);
procedure Edit1Change(Sender: TObject);
procedure InsertButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure DBGridEh1TitleBtnClick(Sender: TObject; ACol: Integer;
Column: TColumnEh);
procedure DBGridEh2DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumnEh; State: TGridDrawState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
HomeOrderForm: THomeOrderForm;
implementation
uses StoreDM, HomeProperSelect, HomeOrderItem;
{$R *.dfm}
procedure THomeOrderForm.EnabledButtons;
begin
// Если записей нету, то Деактивируем кнопки "Редактировать" и "Удалить",
// а если есть, Активируем.
if StoreDataModule.HomeOrderDataSet.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 THomeOrderForm.FormCreate(Sender: TObject);
begin
with StoreDataModule do
begin
HomeOrderDataSet.Open;
HomeStructureDataSet.Open;
end;
CloseButton.Left := Panel1.Width - CloseButton.Width - 10;
Caption := 'Складские документы (' + TopDate + '-' + BottomDate + ')';
EnabledButtons;
end;
procedure THomeOrderForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
CurOrderID := 0;
with StoreDataModule do
begin
HomeOrderDataSet.Close;
HomeOrderDataSet.SelectSQL.Strings[HomeOrderDataSet.SelectSQL.Count - 1] := 'ORDER BY "Date", "OrderID"';
HomeStructureDataSet.Close;
end;
// Удаление формы при ее закрытии
HomeOrderForm := nil;
Action := caFree;
end;
procedure THomeOrderForm.CloseButtonClick(Sender: TObject);
begin
Close;
end;
procedure THomeOrderForm.Edit1Change(Sender: TObject);
begin
// StoreDataModule.ConvertDataSet.Locate('CategoryName', Edit1.Text, [loCaseInsensitive, loPartialKey]);
end;
procedure THomeOrderForm.InsertButtonClick(Sender: TObject);
begin
StoreDataModule.HomeOrderDataSet.Append;
StoreDataModule.HomeOrderDataSet['FirmID'] := MainFirm;
StoreDataModule.HomeOrderDataSet['Date'] := Now;
StoreDataModule.HomeOrderDataSet['CustomerID'] := MainFirm;
StoreDataModule.HomeOrderDataSet['PriceID'] := 1;//"Цена Закупа"
//Выбираем Вид Накладной
HomeProperSelectForm := THomeProperSelectForm.Create(Self);
HomeProperSelectForm.ShowModal;
if HomeProperSelectForm.ModalResult = mrOK then
begin
StoreDataModule.HomeOrderDataSet['ProperID'] := CurProperID;
if CurProperID = 6 then
StoreDataModule.HomeOrderDataSet['InDivisionID'] := MainDivision;
if CurProperID = 7 then
StoreDataModule.HomeOrderDataSet['OutDivisionID'] := MainDivision;
if CurProperID = 8 then
begin
StoreDataModule.HomeOrderDataSet['OutDivisionID'] := MainDivision;
StoreDataModule.HomeOrderDataSet['InDivisionID'] := MainDivision;
end;
if CurProperID = 9 then
begin
StoreDataModule.HomeOrderDataSet['OutDivisionID'] := MainDivision;
// StoreDataModule.HomeOrderDataSet['InDivisionID'] := MainDivision;
end;
StoreDataModule.HomeOrderDataSet.Post;
EnabledButtons;
HomeOrderItemForm := THomeOrderItemForm.Create(Self);
HomeOrderItemForm.ShowModal;
end
else
begin
StoreDataModule.HomeOrderDataSet.Cancel;
end;
end;
procedure THomeOrderForm.EditButtonClick(Sender: TObject);
begin
// StoreDataModule.HomeOrderDataSet.Edit;
HomeOrderItemForm := THomeOrderItemForm.Create(Self);
HomeOrderItemForm.ShowModal;
end;
procedure THomeOrderForm.DeleteButtonClick(Sender: TObject);
var
OrderStr: String;
begin
with StoreDataModule do
try
OrderStr := HomeOrderDataSet.FieldByName('OrderID').AsString;
if Application.MessageBox(PChar('Вы действительно хотите удалить запись"' +
OrderStr + '"?'),
'Удаление записи',
mb_YesNo + mb_IconQuestion + mb_DefButton2) = idYes then
try
HomeOrderDataSet.Delete;
HomeTransaction.Commit;
EnabledButtons;
except
Application.MessageBox(PChar('Запись "' + OrderStr + '" удалять нельзя.'),
'Ошибка удаления', mb_IconStop);
end; {try except}
finally
if HomeOrderDataSet.Active = False then
HomeOrderDataSet.Open;
end; {try finally}
end;
procedure THomeOrderForm.RefreshButtonClick(Sender: TObject);
begin
CurOrderID := StoreDataModule.HomeOrderDataSet['OrderID'];
StoreDataModule.HomeOrderDataSet.Close;
StoreDataModule.HomeOrderDataSet.Open;
Caption := 'Складские документы (' + TopDate + '-' + BottomDate + ')';
end;
procedure THomeOrderForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
case Key of
VK_F2 : InsertButton.Click;
VK_F3 : EditButton.Click;
VK_F8 : DeleteButton.Click;
VK_F5 : RefreshButton.Click;
end;
end;
procedure THomeOrderForm.DBGridEh1TitleBtnClick(Sender: TObject;
ACol: Integer; Column: TColumnEh);
var
i: Integer;
begin
//Сортировка по клику на заголовке столбца
CurOrderID := StoreDataModule.HomeOrderDataSet['OrderID'];
if Column.Title.Font.Color = clRed then
with StoreDataModule.HomeOrderDataSet do
begin
SelectSQL.Strings[SelectSQL.Count - 1] := 'ORDER BY "OrderID"';
Close;
Open;
for i := 0 to DBGridEh1.Columns.Count - 1 do
begin
DBGridEh1.Columns.Items[i].Title.Font.Color := clWindowText;
end;
end
else
with StoreDataModule.HomeOrderDataSet do
begin
SelectSQL.Strings[SelectSQL.Count - 1] := 'ORDER BY "' + Column.FieldName + '", "OrderID"';
Close;
Open;
for i := 0 to DBGridEh1.Columns.Count - 1 do
begin
DBGridEh1.Columns.Items[i].Title.Font.Color := clWindowText;
end;
Column.Title.Font.Color := clRed;
end;
end;
procedure THomeOrderForm.DBGridEh2DrawColumnCell(Sender: TObject;
const Rect: TRect; DataCol: Integer; Column: TColumnEh;
State: TGridDrawState);
var
ItemNo: String;
begin
//Проставляем номера по порядку в строках Документа
with DBGridEh2.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
DBGridEh2.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit Vcl.Touch.KeyboardTypes;
interface
uses
System.Generics.Collections, System.Classes;
type
TKeyState = (ksDown, ksUp);
TModifierState = set of (msShift, msCtrl, msAlt, msDiacritic);
TKeyImage = (kiOverride = -2, kiText = -1, kiTab = 0, kiShift = 1, kiEnter = 2,
kiBackspace = 3, kiUp = 4, kiDown = 5, kiLeft = 6, kiRight = 7, kiTallEnter = 8);
TVirtualKeyFlag = (kfStretch, kfToggle, kfRepeat);
TVirtualKeyFlags = set of TVirtualKeyFlag;
// For internal use only.
TKeyData = record
Vk: SmallInt;
ScanCode: SmallInt;
class function Create: TKeyData; static;
end;
TKeyDataArray = array of TKeyData;
// For internal use only.
TKey = record
Vk: SmallInt;
ScanCode: SmallInt;
Caption: string;
KeyImage: TKeyImage;
ComboKeys: TKeyDataArray;
class function Create: TKey; static;
function ToString(State: TModifierState = []): string;
function IsDeadKey: Boolean;
class operator Implicit(const AKey: TKey): TKeyData;
end;
// For internal use only.
TKeyLanguage = record
Vk: SmallInt;
ScanCode: SmallInt;
Caption: string;
KeyImage: TKeyImage;
ComboKeys: TKeyDataArray;
Language: string;
class function Create: TKeyLanguage; static;
end;
TKeyLanguages = array of TKeyLanguage;
// For internal use only.
TKeyModifier = record
Vk: SmallInt;
ScanCode: SmallInt;
Caption: string;
KeyImage: TKeyImage;
ModifierName: string;
Languages: TKeyLanguages;
FontSize: Word;
Language: string;
class function Create: TKeyModifier; static;
class operator Implicit(const AModifierKey: TKeyModifier): TKey;
end;
TKeyModifiers = array of TKeyModifier;
// For internal use only.
TVirtualKey = record
Vk: SmallInt;
ScanCode: SmallInt;
Caption: string;
KeyImage: TKeyImage;
ComboKeys: TKeyDataArray;
FontSize: Word;
Width: Word;
Height: Word;
Flags: TVirtualKeyFlags;
LeftMargin: Word;
RightMargin: Word;
Modifiers: TKeyModifiers;
ModifierName: string;
Languages: TKeyLanguages;
GroupIndex: Word;
PublishedName: string;
class function Create: TVirtualKey; static;
function Equals(const AVirtualKey: TVirtualKey): Boolean;
class operator Implicit(const AVirtualKey: TVirtualKey): TKey;
end;
TVirtualKeys = class
private
FKeys: TList<TVirtualKey>;
FTopMargin: Integer;
FBottomMargin: Integer;
function GetItem(Index: Integer): TVirtualKey;
procedure SetItem(Index: Integer; const Value: TVirtualKey);
public
constructor Create;
destructor Destroy; override;
procedure Add(var AKey: TVirtualKey);
function Count: Integer;
property Items[Index: Integer]: TVirtualKey read GetItem write SetItem; default;
property TopMargin: Integer read FTopMargin write FTopMargin;
property BottomMargin: Integer read FBottomMargin write FBottomMargin;
end;
// For internal use only.
TKeyboardLanguage = record
Language: string;
Name: string;
class function Create: TKeyboardLanguage; static;
end;
TVirtualKeyLayout = class
private
type
TVirtualKeyboard = class(TList<TVirtualKeys>);
TKeyboardLanguages = class(TList<TKeyboardLanguage>);
private
FLanguages: TKeyboardLanguages;
FKeyboardName: string;
FKeyboardType: string;
FMinHeight: Integer;
FWidth: Integer;
FMinWidth: Integer;
FHeight: Integer;
FMaxWidth: Integer;
FMaxHeight: Integer;
FRowHeight: Integer;
FKeys: TVirtualKeyboard;
public
constructor Create;
destructor Destroy; override;
procedure LoadFromStream(Stream: TStream);
procedure SaveToStream(Stream: TStream);
property Languages: TKeyboardLanguages read FLanguages;
property KeyboardName: string read FKeyboardName write FKeyboardName;
property KeyboardType: string read FKeyboardType write FKeyboardType;
property Width: Integer read FWidth write FWidth;
property Height: Integer read FHeight write FHeight;
property MinWidth: Integer read FMinWidth write FMinWidth;
property MinHeight: Integer read FMinHeight write FMinHeight;
property MaxWidth: Integer read FMaxWidth write FMaxWidth;
property MaxHeight: Integer read FMaxHeight write FMaxHeight;
property RowHeight: Integer read FRowHeight write FRowHeight;
property Keys: TVirtualKeyboard read FKeys;
end;
TVirtualKeyLayouts = class(TList<TVirtualKeyLayout>)
public
destructor Destroy; override;
end;
TKeyboardLayout = type string;
function VKey(Vk, ScanCode: Integer): TKeyData;
function GetVirtualKey(const Key: TKeyData): TKeyData;
procedure StringToComboKeys(const Value: string; var Keys: TKeyDataArray);
function ComboKeysToString(const Keys: TKeyDataArray): string;
implementation
uses
Winapi.Windows, System.SysUtils;
function VKey(Vk, ScanCode: Integer): TKeyData;
begin
Result.Vk := Vk;
Result.ScanCode := ScanCode;
end;
function GetVirtualKey(const Key: TKeyData): TKeyData;
begin
if (Key.Vk = -1) and (Key.ScanCode >= 0) then
begin
Result.Vk := MapVirtualKey(Key.ScanCode, MAPVK_VSC_TO_VK);
Result.ScanCode := Key.ScanCode;
end
else if (Key.Vk >= 0) and (Key.ScanCode = -1) then
begin
Result.Vk := Key.Vk;
Result.ScanCode := MapVirtualKey(Key.Vk, MAPVK_VK_TO_VSC);
end
else if (Key.Vk >= 0) and (Key.ScanCode >= 0) then
begin
Result.Vk := Key.Vk;
Result.ScanCode := Key.ScanCode;
end
else
Result := TKeyData.Create;
end;
function InternalToUnicode(const Key: TKeyData; const KeyboardState: TKeyboardState;
var DeadKey: Boolean): string; overload;
const
TempSize = 64;
var
TempStr: string;
Size: Integer;
begin
DeadKey := False;
SetLength(TempStr, TempSize);
ZeroMemory(@TempStr[1], TempSize * SizeOf(Char));
Size := ToUnicode(Key.Vk, Key.ScanCode, KeyboardState, @TempStr[1], TempSize, 0);
case Size of
-1:
begin
DeadKey := True;
// Fix painting on Windows XP.
if not(CheckWin32Version(6, 0)) and (TempStr <> '') then
Result := TempStr[1]
else
Result := TempStr;
// Call ToUnicode again to clear the dead key from the internal buffer.
ToUnicode(Key.Vk, Key.ScanCode, KeyboardState, @TempStr[1], TempSize, 0);
end;
0: ; // Do nothing when the size is zero.
else
begin
ZeroMemory(@TempStr[1], TempSize * SizeOf(Char));
// Call ToUnicode again to clear the dead key from the internal buffer.
Size := ToUnicode(Key.Vk, Key.ScanCode, KeyboardState, @TempStr[1], TempSize, 0);
begin
Result := TempStr;
SetLength(Result, Size);
end;
end;
end;
end;
function InternalToUnicode(const Key: TKeyData; const KeyboardState: TKeyboardState): string; overload;
var
DeadKey: Boolean;
begin
Result := InternalToUnicode(Key, KeyboardState, DeadKey);
end;
procedure StringToComboKeys(const Value: string; var Keys: TKeyDataArray);
function GetValue(const S, Name: string; var Value: string): Boolean;
var
P: PChar;
LName, LValue: string;
begin
Result := False;
P := @S[1];
while P^ <> #0 do
begin
if P^ = '=' then
begin
Inc(P);
Break;
end;
LName := LName + P^;
Inc(P);
end;
if LName = Name then
begin
while P^ <> #0 do
begin
LValue := LValue + P^;
Inc(P)
end;
Value := LValue;
Result := True;
end;
end;
const
cVK = 'vk';
cScanCode = 'sc';
var
Strings: TStrings;
Index, StringsIndex: Integer;
LValue: string;
begin
Strings := TStringList.Create;
try
Strings.Delimiter := ';';
Strings.DelimitedText := Value;
Index := 0;
StringsIndex := 0;
SetLength(Keys, Strings.Count div 2);
while Index < Length(Keys) do
begin
if GetValue(Strings[StringsIndex], cVk, LValue) then
Keys[Index].Vk := StrToInt(LValue);
if GetValue(Strings[StringsIndex + 1], cScanCode, LValue) then
Keys[Index].ScanCode := StrToInt(LValue);
Inc(Index);
Inc(StringsIndex, 2);
end;
finally
Strings.Free;
end;
end;
function ComboKeysToString(const Keys: TKeyDataArray): string;
var
Index: Integer;
begin
for Index := 0 to Length(Keys) - 1 do
begin
if Index > 0 then
Result := Result + ';';
Result := Result + Format('vk=%d;sc=%d', [Keys[Index].Vk, Keys[Index].ScanCode]);
end;
end;
{ TKeyModifier }
class function TKeyModifier.Create: TKeyModifier;
begin
with Result do
begin
Caption := '';
ModifierName := '';
Vk := -1;
ScanCode := -1;
KeyImage := kiText;
FontSize := 14;
Language := '';
end;
end;
class operator TKeyModifier.Implicit(const AModifierKey: TKeyModifier): TKey;
begin
Result.Caption := AModifierKey.Caption;
Result.KeyImage := AModifierKey.KeyImage;
Result.Vk := AModifierKey.Vk;
Result.ScanCode := AModifierKey.ScanCode;
SetLength(Result.ComboKeys, 0);
end;
{ TVirtualKey }
class function TVirtualKey.Create: TVirtualKey;
begin
with Result do
begin
Caption := '';
KeyImage := kiText;
Vk := -1;
ScanCode := -1;
SetLength(ComboKeys, 0);
Width := 48;
Height := 48;
LeftMargin := 2;
RightMargin := 2;
Flags := [];
SetLength(Modifiers, 0);
ModifierName := '';
GroupIndex := 0;
SetLength(Languages, 0);
PublishedName := '';
FontSize := 14;
end;
end;
function TVirtualKey.Equals(const AVirtualKey: TVirtualKey): Boolean;
begin
Result := False;
if (Length(ComboKeys) = 0) and (Length(AVirtualKey.ComboKeys) = 0) then
begin
if ((ScanCode <> -1) or (AVirtualKey.ScanCode = -1)) and
((Vk <> -1) or (AVirtualKey.Vk <> -1)) then
begin
Result := (ScanCode = AVirtualKey.ScanCode) and (Vk = AVirtualKey.Vk);
end
else if ((ScanCode = -1) or (AVirtualKey.ScanCode = -1)) then
Result := Vk = AVirtualKey.Vk
else if ((Vk = -1) or (AVirtualKey.Vk = -1)) then
Result := ScanCode = AVirtualKey.ScanCode
end;
end;
class operator TVirtualKey.Implicit(const AVirtualKey: TVirtualKey): TKey;
begin
Result.Caption := AVirtualKey.Caption;
Result.KeyImage := AVirtualKey.KeyImage;
Result.Vk := AVirtualKey.Vk;
Result.ScanCode := AVirtualKey.ScanCode;
Result.ComboKeys := AVirtualKey.ComboKeys;
if Length(Result.ComboKeys) > 0 then
begin
Result.ScanCode := -1;
Result.Vk := -1;
end;
end;
{ TKeyLanguage }
class function TKeyLanguage.Create: TKeyLanguage;
begin
with Result do
begin
Caption := '';
Vk := -1;
ScanCode := -1;
SetLength(ComboKeys, 0);
Language := '';
KeyImage := kiText;
end;
end;
{ TKey }
class function TKey.Create: TKey;
begin
with Result do
begin
Caption := '';
KeyImage := kiText;
Vk := -1;
ScanCode := -1;
SetLength(ComboKeys, 0);
end;
end;
class operator TKey.Implicit(const AKey: TKey): TKeyData;
begin
Result.Vk := AKey.Vk;
Result.ScanCode := AKey.ScanCode;
end;
function TKey.IsDeadKey: Boolean;
var
KeyboardState: TKeyboardState;
begin
GetKeyboardState(KeyboardState);
InternalToUnicode(GetVirtualKey(VKey(Vk, ScanCode)), KeyboardState, Result);
end;
function TKey.ToString(State: TModifierState = []): string;
var
KeyboardState: TKeyboardState;
begin
ZeroMemory(@KeyboardState[0], Length(KeyboardState));
if msShift in State then
KeyboardState[VK_SHIFT] := $81;
Result := InternalToUnicode(GetVirtualKey(VKey(Vk, ScanCode)), KeyboardState);
end;
{ TVirtualKeyLayout }
constructor TVirtualKeyLayout.Create;
begin
inherited;
FLanguages := TKeyboardLanguages.Create;
FMinWidth := 0;
FMinHeight := 0;
FMaxWidth := 0;
FMaxHeight := 0;
FRowHeight := 48;
FKeys := TVirtualKeyboard.Create;
end;
destructor TVirtualKeyLayout.Destroy;
var
Index: Integer;
begin
for Index := 0 to FKeys.Count - 1 do
FKeys[Index].Free;
FKeys.Free;
FLanguages.Free;
inherited;
end;
procedure TVirtualKeyLayout.LoadFromStream(Stream: TStream);
function ReadSmallInt: SmallInt;
begin
Stream.Read(Result, SizeOf(Result));
end;
function ReadBool: Boolean;
begin
Stream.Read(Result, SizeOf(Result));
end;
function ReadByte: Byte;
begin
Stream.Read(Result, SizeOf(Byte))
end;
function ReadWord: Word;
begin
Stream.Read(Result, SizeOf(Word));
end;
function ReadString: string;
var
Count: Byte;
Bytes: TBytes;
begin
Stream.Read(Count, SizeOf(Count));
if Count > 0 then
begin
SetLength(Bytes, Count);
ZeroMemory(@Bytes[0], Length(Bytes));
Stream.Read(Bytes[0], Count);
Result := TEncoding.Unicode.GetString(Bytes);
end
else
Result := '';
end;
var
Index, RowIndex, KeyIndex, ModifierIndex, ComboKeysIndex, ModifierLangIndex: Integer;
ModifierCount, ComboKeysCount, ModifierLangCount: Integer;
Key: TVirtualKey;
KeyModifier: TKeyModifier;
KeyLanguage: TKeyLanguage;
Row: TVirtualKeys;
Version: Integer;
KeyboardLanguage: TKeyboardLanguage;
begin
Version := ReadByte;
if Version = 1 then
begin
KeyboardName := ReadString;
KeyboardType := ReadString;
Width := ReadWord;
Height := ReadWord;
MinWidth := ReadWord;
MinHeight := ReadWord;
MaxWidth := ReadWord;
MaxHeight := ReadWord;
RowHeight := ReadWord;
for Index := ReadWord - 1 downto 0 do
begin
KeyboardLanguage := TKeyboardLanguage.Create;
KeyboardLanguage.Language := ReadString;
KeyboardLanguage.Name := ReadString;
Languages.Add(KeyboardLanguage);
end;
for RowIndex := ReadWord - 1 downto 0 do
begin
Row := TVirtualKeys.Create;
Keys.Add(Row);
Row.TopMargin := ReadByte;
Row.BottomMargin := ReadByte;
for KeyIndex := ReadWord - 1 downto 0 do
begin
Key := TVirtualKey.Create;
Key.Caption := ReadString;
Key.KeyImage := TKeyImage(ReadByte);
Key.Vk := ReadSmallInt;
Key.ScanCode := ReadSmallInt;
ComboKeysCount := ReadWord;
SetLength(Key.ComboKeys, ComboKeysCount);
for ComboKeysIndex := 0 to ComboKeysCount - 1 do
begin
Key.ComboKeys[ComboKeysIndex].Vk := ReadSmallInt;
Key.ComboKeys[ComboKeysIndex].ScanCode := ReadSmallInt;
end;
Key.Width := ReadWord;
Key.Height := ReadWord;
Key.LeftMargin := ReadByte;
Key.RightMargin := ReadByte;
Key.Flags := TVirtualKeyFlags(Byte(ReadByte));
Key.GroupIndex := ReadWord;
Key.ModifierName := ReadString;
Key.PublishedName := ReadString;
Key.FontSize := ReadWord;
ModifierCount := ReadWord;
SetLength(Key.Modifiers, ModifierCount);
for ModifierIndex := ModifierCount - 1 downto 0 do
begin
KeyModifier := TKeyModifier.Create;
KeyModifier.Caption := ReadString;
KeyModifier.Vk := ReadSmallInt;
KeyModifier.ScanCode := ReadSmallInt;
KeyModifier.KeyImage := TKeyImage(ReadByte);
KeyModifier.ModifierName := ReadString;
KeyModifier.FontSize := ReadWord;
KeyModifier.Language := ReadString;
ModifierLangCount := ReadWord;
SetLength(KeyModifier.Languages, ModifierLangCount);
for ModifierLangIndex := ModifierLangCount - 1 downto 0 do
begin
KeyLanguage := TKeyLanguage.Create;
KeyLanguage.Caption := ReadString;
KeyLanguage.Vk := ReadSmallInt;
KeyLanguage.ScanCode := ReadSmallInt;
KeyLanguage.KeyImage := TKeyImage(ReadByte);
KeyLanguage.Language := ReadString;
KeyModifier.Languages[ModifierLangIndex] := KeyLanguage;
end;
Key.Modifiers[ModifierIndex] := KeyModifier;
end;
ModifierLangCount := ReadWord;
SetLength(Key.Languages, ModifierLangCount);
for ModifierLangIndex := ModifierLangCount - 1 downto 0 do
begin
KeyLanguage := TKeyLanguage.Create;
KeyLanguage.Caption := ReadString;
KeyLanguage.Vk := ReadSmallInt;
KeyLanguage.ScanCode := ReadSmallInt;
ComboKeysCount := ReadWord;
SetLength(KeyLanguage.ComboKeys, ComboKeysCount);
for ComboKeysIndex := 0 to ComboKeysCount - 1 do
begin
KeyLanguage.ComboKeys[ComboKeysIndex].Vk := ReadSmallInt;
KeyLanguage.ComboKeys[ComboKeysIndex].ScanCode := ReadSmallInt;
end;
KeyLanguage.KeyImage := TKeyImage(ReadByte);
KeyLanguage.Language := ReadString;
Key.Languages[ModifierLangIndex] := KeyLanguage;
end;
Row.Add(Key);
end;
end;
end;
end;
procedure TVirtualKeyLayout.SaveToStream(Stream: TStream);
procedure WriteSmallInt(Value: SmallInt);
begin
Stream.Write(Value, SizeOf(Value));
end;
procedure WriteWord(Value: Word);
begin
Stream.Write(Value, SizeOf(Value));
end;
procedure WriteByte(Value: Byte);
begin
Stream.Write(Value, SizeOf(Value));
end;
procedure WriteBool(Value: Boolean);
begin
Stream.Write(Value, SizeOf(Value));
end;
procedure WriteString(const Value: string);
var
Bytes: TBytes;
Count: Byte;
begin
Bytes := TEncoding.Unicode.GetBytes(Value);
Count := Length(Bytes);
Stream.Write(Count, SizeOf(Count));
if Count > 0 then
Stream.Write(Bytes[0], Count);
end;
var
Index, RowIndex, KeyIndex, ModifierIndex, ComboKeysIndex, ModifierLangIndex: Integer;
Key: TVirtualKey;
KeyModifier: TKeyModifier;
KeyLanguage: TKeyLanguage;
KeyboardLanguage: TKeyboardLanguage;
begin
// Write version
WriteByte(1);
WriteString(Self.KeyboardName);
WriteString(Self.KeyboardType);
WriteWord(Self.Width);
WriteWord(Self.Height);
WriteWord(Self.MinWidth);
WriteWord(Self.MinHeight);
WriteWord(Self.MaxWidth);
WriteWord(Self.MaxHeight);
WriteWord(Self.RowHeight);
WriteWord(Self.Languages.Count);
for Index := 0 to Self.Languages.Count - 1 do
begin
KeyboardLanguage := Self.Languages[Index];
WriteString(KeyboardLanguage.Language);
WriteString(KeyboardLanguage.Name);
end;
WriteWord(Keys.Count); // write rows
for RowIndex := 0 to Keys.Count - 1 do
begin
WriteByte(Keys[RowIndex].TopMargin);
WriteByte(Keys[RowIndex].BottomMargin);
WriteWord(Keys[RowIndex].Count);
for KeyIndex := 0 to Keys[RowIndex].Count - 1 do
begin
Key := Keys[RowIndex][KeyIndex];
WriteString(Key.Caption);
WriteByte(Byte(Key.KeyImage));
WriteSmallInt(Key.Vk);
WriteSmallInt(Key.ScanCode);
WriteWord(Length(Key.ComboKeys));
for ComboKeysIndex := 0 to Length(Key.ComboKeys) - 1 do
begin
WriteSmallInt(Key.ComboKeys[ComboKeysIndex].Vk);
WriteSmallInt(Key.ComboKeys[ComboKeysIndex].ScanCode);
end;
WriteWord(Key.Width);
WriteWord(Key.Height);
WriteByte(Key.LeftMargin);
WriteByte(Key.RightMargin);
WriteByte(Byte(Key.Flags));
WriteWord(Key.GroupIndex);
WriteString(Key.ModifierName);
WriteString(Key.PublishedName);
WriteWord(Key.FontSize);
WriteWord(Length(Key.Modifiers));
for ModifierIndex := 0 to Length(Key.Modifiers) - 1 do
begin
KeyModifier := Key.Modifiers[ModifierIndex];
WriteString(KeyModifier.Caption);
WriteSmallInt(KeyModifier.Vk);
WriteSmallInt(KeyModifier.ScanCode);
WriteByte(Byte(KeyModifier.KeyImage));
WriteString(KeyModifier.ModifierName);
WriteWord(KeyModifier.FontSize);
WriteString(KeyModifier.Language);
WriteWord(Length(KeyModifier.Languages));
for ModifierLangIndex := 0 to Length(KeyModifier.Languages) - 1 do
begin
KeyLanguage := KeyModifier.Languages[ModifierLangIndex];
WriteString(KeyLanguage.Caption);
WriteSmallInt(KeyLanguage.Vk);
WriteSmallInt(KeyLanguage.ScanCode);
WriteByte(Byte(KeyLanguage.KeyImage));
WriteString(KeyLanguage.Language);
end;
end;
WriteWord(Length(Key.Languages));
for ModifierLangIndex := 0 to Length(Key.Languages) - 1 do
begin
KeyLanguage := Key.Languages[ModifierLangIndex];
WriteString(KeyLanguage.Caption);
WriteSmallInt(KeyLanguage.Vk);
WriteSmallInt(KeyLanguage.ScanCode);
WriteWord(Length(KeyLanguage.ComboKeys));
for ComboKeysIndex := 0 to Length(KeyLanguage.ComboKeys) - 1 do
begin
WriteSmallInt(KeyLanguage.ComboKeys[ComboKeysIndex].Vk);
WriteSmallInt(KeyLanguage.ComboKeys[ComboKeysIndex].ScanCode);
end;
WriteByte(Byte(KeyLanguage.KeyImage));
WriteString(KeyLanguage.Language);
end;
end;
end;
end;
{ TVirtualKeyLayouts }
destructor TVirtualKeyLayouts.Destroy;
var
Index: Integer;
begin
for Index := 0 to Count - 1 do
Items[Index].Free;
inherited;
end;
{ TVirtualKeys }
procedure TVirtualKeys.Add(var AKey: TVirtualKey);
begin
FKeys.Add(AKey);
end;
function TVirtualKeys.Count: Integer;
begin
Result := FKeys.Count;
end;
constructor TVirtualKeys.Create;
begin
FKeys := TList<TVirtualKey>.Create;
FTopMargin := 0;
FBottomMargin := 0;
end;
destructor TVirtualKeys.Destroy;
begin
FKeys.Free;
inherited;
end;
function TVirtualKeys.GetItem(Index: Integer): TVirtualKey;
begin
Result := FKeys[Index];
end;
procedure TVirtualKeys.SetItem(Index: Integer; const Value: TVirtualKey);
begin
FKeys[Index] := Value;
end;
{ TKeyboardLanguage }
class function TKeyboardLanguage.Create: TKeyboardLanguage;
begin
Result.Language := '';
Result.Name := '';
end;
{ TKeyData }
class function TKeyData.Create: TKeyData;
begin
Result.Vk := 0;
Result.ScanCode := 0;
end;
end.
|
Unit PathTree;
interface
uses AVL_tree,
pathinfo;
type
TPathTree = class
private
fTree : TAVLTree;
public
constructor Create();
destructor Destroy; override;
function AddPathInfo(Name : String) : TPathInfo;
procedure BrowseAll;
function GetMissedPaths : AnsiString;
function UnknownGetJSON : AnsiString;
end;
implementation
uses SysUtils;
function CompareNode(Item1 : Pointer; Item2 : Pointer) : Longint;
var Node1 : TPathInfo absolute Item1;
Node2 : TPathInfo absolute Item2;
begin
Result := AnsiCompareText(Node1.PathName,Node2.Pathname);
end;
constructor TPathTree.Create();
begin
ftree := TAVLTree.create(@CompareNode);
end;
destructor TPathTree.Destroy;
begin
//BrowseAll;
ftree.free;
end;
function TPathTree.GetMissedPaths : AnsiString;
var TreeEnum : TAVLTreeNodeEnumerator;
var TreeItem,Node : TAVLTreeNode;
var MyData : TPathInfo;
begin
result := '';
TreeEnum := fTree.GetEnumerator;
While TreeEnum.MoveNext do
begin
TreeItem := TreeEnum.Current;
with TPathInfo(TreeItem.Data) do
if State = tpisConfigured then
Result := Result + Pathname + '|'
end;
end;
function TPathTree.UnknownGetJSON : AnsiString;
var TreeEnum : TAVLTreeNodeEnumerator;
var TreeItem,Node : TAVLTreeNode;
var MyData : TPathInfo;
begin
Result := '"FileInfoSet" : [';
TreeEnum := fTree.GetEnumerator;
While TreeEnum.MoveNext do
begin
TreeItem := TreeEnum.Current;
with TPathInfo(TreeItem.Data) do
if (SpecificName<>'') or (GroupName<>'') then
Result := Result + DumpJSON + ',';
end;
if Result[Length(Result)]=',' then
Result[Length(Result)]:=']'
else
Result := Result + ']';
end;
procedure TPathTree.BrowseAll;
var TreeEnum : TAVLTreeNodeEnumerator;
var TreeItem,Node : TAVLTreeNode;
var MyData : TPathInfo;
begin
writeln('\nDump Sorted Tree ftree:');
TreeEnum := fTree.GetEnumerator;
While TreeEnum.MoveNext do
begin
TreeItem := TreeEnum.Current;
with TPathInfo(TreeItem.Data) do
begin
write('(Item : Prof(' + IntToStr(TreeItem.TreeDepth) + ') '+
dumpData);
end;
end;
//for Node in fTree do begin
// MyData:=TPathInfo(Node.Data);
// writeln(MyData.PathName);
//end;
end;
function TPathTree.AddPathInfo(Name : String) : TPathInfo;
var PI : TPathInfo;
var Node : TAVLTreeNode;
begin
try
PI := tPathInfo.create(Name);
Node := fTree.find(PI);
if assigned(Node) then
begin
// writeln('Find "',Name,'" give ',TPathInfo(Node.Data).PathName);
PI.free;
PI := TPathInfo(Node.Data);
// PI.State := tpisFound;
end
else
begin
// writeln('Find "',Name,'" give nothing. Create Node');
Node := fTree.Add(PI);
end;
Result := PI;
except on e: Exception do writeln('exception ',e.message);
end;
end;
end. |
unit untEasyDesignerTLReg;
{$I cxVer.inc}
interface
uses
Classes, SysUtils, TypInfo, Types, DesignIntf, DesignEditors, VCLEditors, dxCore,
cxInplaceContainer, Forms, DB, cxDesignWindows, cxPropEditors, cxClasses, cxControls,
cxEdit, cxStyles, cxTL, cxTLData, cxDBTL, cxTLStrs,
cxTLEditor, cxTLItemsEditor, cxTLPredefinedStyles, cxTLStyleSheetPreview{, cxTLExportLink};
procedure DesignerTLRegister;
implementation
uses
dxCoreReg, cxLibraryReg, cxEditPropEditors;
type
{ TcxTreeListComponentEditor }
TcxTreeListComponentEditor = class(TdxComponentEditor)
protected
FItems: TStringList;
function GetTreeList: TcxCustomTreeList;
procedure ItemsNeeded; virtual;
protected
function GetProductMajorVersion: string; override;
function GetProductName: string; override;
function InternalGetVerb(AIndex: Integer): string; override;
function InternalGetVerbCount: Integer; override;
procedure InternalExecuteVerb(AIndex: Integer); override;
public
destructor Destroy; override;
property TreeList: TcxCustomTreeList read GetTreeList;
end;
{ TcxstStylesEventsProperty }
TcxTreeListStylesEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
{ TcxTreeListPopupMenusEventsProperty }
TcxTreeListPopupMenusEventsProperty = class(TcxNestedEventProperty)
protected
function GetInstance: TPersistent; override;
end;
{ TcxDBTreeListDataBindingFieldNameProperty }
TcxDBTreeListDataBindingFieldNameProperty = class(TFieldNameProperty)
public
function GetDataSource: TDataSource; override;
end;
{ TcxDBTreeListDataControllerFieldNameProperty }
TcxDBTreeListDataControllerFieldNameProperty = class(TFieldNameProperty)
public
function GetDataSource: TDataSource; override;
end;
{ TcxTreeListColumnProperty }
TcxTreeListColumnProperty = class(TComponentProperty)
public
procedure GetValues(Proc: TGetStrProc); override;
end;
const
UnitNamePrefix = '' ;
ComponentDescription = 'ExpressQuantumTreeList';
procedure ShowItemsDesigner(
AEditor: TcxTreeListComponentEditor; APageIndex: Integer);
var
ADesigner: TcxTreeListBandColumnDesigner;
begin
ADesigner := TcxTreeListBandColumnDesigner(ShowFormEditorClass(AEditor.Designer,
AEditor.Component, TcxTreeListBandColumnDesigner));
ADesigner.SetVisiblePageIndex(APageIndex);
end;
{ TcxTreeListComponentEditor }
destructor TcxTreeListComponentEditor.Destroy;
begin
FreeAndNil(FItems);
inherited Destroy;
end;
function TcxTreeListComponentEditor.GetTreeList: TcxCustomTreeList;
begin
Result := Component as TcxCustomTreeList;
end;
procedure TcxTreeListComponentEditor.ItemsNeeded;
var
AOperations: IcxTreeListDesignTimeOperations;
begin
if FItems = nil then
FItems := TStringList.Create()
else
FItems.Clear;
if not Supports(TreeList, IcxTreeListDesignTimeOperations, AOperations) then Exit;
if AOperations.SupportBandColumnEditor then
begin
FItems.Add(scxStr(@scxColumns));
FItems.Add(scxStr(@scxBands));
end;
if AOperations.SupportItemsEditor then
FItems.Add(scxStr(@scxItems))
else
if AOperations.SupportCreateAllItems then
begin
FItems.Add(scxStr(@scxCreateAllItems));
FItems.Add(scxStr(@scxDeleteAllItems));
end;
end;
function TcxTreeListComponentEditor.GetProductMajorVersion: string;
begin
Result := cxTLMajorVersion;
end;
function TcxTreeListComponentEditor.GetProductName: string;
begin
Result := ComponentDescription;
end;
function TcxTreeListComponentEditor.InternalGetVerb(AIndex: Integer): string;
begin
Result := FItems[AIndex]
end;
function TcxTreeListComponentEditor.InternalGetVerbCount: Integer;
begin
ItemsNeeded;
Result := FItems.Count;
end;
procedure TcxTreeListComponentEditor.InternalExecuteVerb(AIndex: Integer);
var
AOperations: IcxTreeListDesignTimeOperations;
const
Invert: array[Boolean] of Byte = (1, 0);
var
ADesignerModifiedNeeded: Boolean;
begin
if not Supports(TreeList, IcxTreeListDesignTimeOperations, AOperations) then Exit;
ADesignerModifiedNeeded := False;
if AIndex in [0..1] then
begin
if AOperations.SupportBandColumnEditor then
ShowItemsDesigner(Self, Invert[AIndex = 1]);
end
else
if AOperations.SupportItemsEditor and (AIndex = 2) then
ADesignerModifiedNeeded := cxShowTreeListItemsEditor(TreeList)
else
if AOperations.SupportCreateAllItems then
begin
if AIndex = 2 then
AOperations.CreateAllItems
else
TreeList.DeleteAllColumns;
ADesignerModifiedNeeded := True;
end;
if ADesignerModifiedNeeded then
Designer.Modified;
end;
{ TcxTreeListStylesEventsProperty }
function TcxTreeListStylesEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomTreeList(GetComponent(0)).Styles;
end;
{ TcxTreeListPopupMenusEventsProperty }
function TcxTreeListPopupMenusEventsProperty.GetInstance: TPersistent;
begin
Result := TcxCustomTreeList(GetComponent(0)).PopupMenus;
end;
{ TcxDBTreeListDataBindingFieldNameProperty }
function TcxDBTreeListDataBindingFieldNameProperty.GetDataSource: TDataSource;
begin
Result := TcxDBItemDataBinding(GetComponent(0)).DataController.DataSource
end;
{ TcxDBTreeListDataControllerFieldNameProperty }
function TcxDBTreeListDataControllerFieldNameProperty.GetDataSource: TDataSource;
begin
Result := TcxDBTreeListDataController(GetComponent(0)).DataSource;
end;
{ TcxTreeListColumnProperty }
type
TPersistentAccess = class(TPersistent);
procedure TcxTreeListColumnProperty.GetValues(Proc: TGetStrProc);
var
I: Integer;
ATreeList: TcxCustomTreeList;
begin
ATreeList := TPersistentAccess(GetComponent(0)).GetOwner as TcxCustomTreeList;
for I := 0 to ATreeList.ColumnCount - 1 do
Proc(ATreeList.Columns[I].Name)
end;
type
TcxTreeListSelectionEditor = class(TSelectionEditor)
protected
ComponentsList: TStringList;
public
procedure AddComponent(const Name: string);
procedure RequiresUnits(Proc: TGetStrProc); override;
end;
procedure TcxTreeListSelectionEditor.AddComponent(const Name: string);
begin
ComponentsList.Add(Name);
end;
procedure TcxTreeListSelectionEditor.RequiresUnits(Proc: TGetStrProc);
procedure AddColumnUnitName(AProperties: TcxCustomEditProperties);
begin
if AProperties <> nil then
Proc(UnitNamePrefix + dxShortStringToString(GetTypeData(PTypeinfo(AProperties.ClassType.ClassInfo))^.UnitName));
end;
var
AComponent: TComponent;
I: Integer;
begin
inherited RequiresUnits(Proc);
Proc(UnitNamePrefix + 'cxGraphics');
Proc(UnitNamePrefix + 'cxCustomData');
Proc(UnitNamePrefix + 'cxStyles');
Proc(UnitNamePrefix + 'cxTL');
ComponentsList := TStringList.Create;
try
Designer.GetComponentNames(GetTypeData(PTypeInfo(TcxTreeListColumn.ClassInfo)), AddComponent);
for I := 0 to ComponentsList.Count - 1 do
begin
AComponent := Designer.GetComponent(ComponentsList[I]);
if AComponent is TcxTreeListColumn then
begin
AddColumnUnitName(TcxTreeListColumn(AComponent).Properties);
AddColumnUnitName(TcxTreeListColumn(AComponent).PropertiesValue);
end;
end;
finally
ComponentsList.Free;
end;
Proc(UnitNamePrefix + dxShortStringToString(GetTypeData(PTypeinfo(cxTreeListBuiltInMenuClass.ClassInfo))^.UnitName))
end;
type
TcxDesignSelectionListener = class(TcxIUnknownObject, IDesignNotification)
protected
Listeners: TList;
// IDesignNotification
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);
public
constructor Create; virtual;
destructor Destroy; override;
procedure AddListener(AListener: TObject; AddListener: Boolean);
end;
constructor TcxDesignSelectionListener.Create;
begin
Listeners := TList.Create;
RegisterDesignNotification(Self);
DesignerNavigatorProc := AddListener;
end;
destructor TcxDesignSelectionListener.Destroy;
begin
DesignerNavigatorProc := nil;
Listeners.Clear;
UnRegisterDesignNotification(Self);
FreeAndNil(Listeners);
inherited Destroy;
end;
procedure TcxDesignSelectionListener.AddListener(
AListener: TObject; AddListener: Boolean);
begin
Listeners.Remove(AListener);
if AddListener then
Listeners.Add(AListener);
end;
procedure TcxDesignSelectionListener.ItemDeleted(
const ADesigner: IDesigner; AItem: TPersistent);
begin
end;
procedure TcxDesignSelectionListener.ItemInserted(
const ADesigner: IDesigner; AItem: TPersistent);
begin
end;
procedure TcxDesignSelectionListener.ItemsModified(
const ADesigner: IDesigner);
begin
end;
procedure TcxDesignSelectionListener.SelectionChanged(
const ADesigner: IDesigner; const ASelection: IDesignerSelections);
var
I: Integer;
begin
for I := 0 to Listeners.Count - 1 do
TcxCustomTreeList(Listeners[I]).Invalidate;
end;
procedure TcxDesignSelectionListener.DesignerOpened(
const ADesigner: IDesigner; AResurrecting: Boolean);
begin
end;
procedure TcxDesignSelectionListener.DesignerClosed(
const ADesigner: IDesigner; AGoingDormant: Boolean);
begin
end;
procedure DesignerTLRegister;
begin
{$IFDEF DELPHI9}
ForceDemandLoadState(dlDisable);
{$ENDIF}
RegisterComponents('Easy TreeView', [TcxTreeList, TcxDBTreeList, TcxVirtualTreeList]);
RegisterClasses([TcxTreeListColumn, TcxDBTreeListColumn, TcxTreeListBands, TcxTreeListBand, TcxTreeListStyleSheet]);
RegisterNoIcon([TcxTreeListColumn, TcxDBTreeListColumn, TcxTreeListStyleSheet]);
RegisterComponentEditor(TcxCustomTreeList, TcxTreeListComponentEditor);
RegisterPropertyEditor(TypeInfo(TcxTreeListColumn), TcxTreeListPreview,
'Column', TcxTreeListColumnProperty);
RegisterPropertyEditor(TypeInfo(TcxTreeListColumn), TcxTreeListOptionsView,
'CategorizedColumn', TcxTreeListColumnProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomTreeList,
'StylesEvents', TcxTreeListStylesEventsProperty);
RegisterPropertyEditor(TypeInfo(TNotifyEvent), TcxCustomTreeList,
'PopupMenusEvents', TcxTreeListPopupMenusEventsProperty);
RegisterPropertyEditor(TypeInfo(TComponent),
TcxTreeListPopupMenu, 'PopupMenu', TcxControlPopupMenuProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBItemDataBinding,
'FieldName', TcxDBTreeListDataBindingFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBTreeListDataController,
'KeyField', TcxDBTreeListDataControllerFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBTreeListDataController,
'ParentField', TcxDBTreeListDataControllerFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBTreeListDataController,
'ImageIndexField', TcxDBTreeListDataControllerFieldNameProperty);
RegisterPropertyEditor(TypeInfo(string), TcxDBTreeListDataController,
'StateIndexField', TcxDBTreeListDataControllerFieldNameProperty);
RegisterSelectionEditor(TcxCustomTreeList, TcxTreeListSelectionEditor);
HideClassProperties(TcxTreeListColumn, ['SummaryFooter']);
end;
var
DesignSelectionListener: TcxDesignSelectionListener;
initialization
DesignSelectionListener := TcxDesignSelectionListener.Create;
RegisterStyleSheetClass(TcxTreeListStyleSheet);
DesignerTLRegister;
finalization
UnRegisterStyleSheetClass(TcxTreeListStyleSheet);
DesignSelectionListener.Free;
end.
|
unit UnitAccounts;
{
OSS Mail Server v1.0.0 - Accounts 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
TfrmAccounts = class(TForm)
styleSettings: TStyleBook;
loToolbar: TLayout;
ppToolbar: TPopup;
ppToolbarAnimation: TFloatAnimation;
loAccounts: TLayout;
loMenu: TLayout;
lbAccounts: TListBox;
lbiAddAccount: TMetropolisUIListBoxItem;
loMenuHeader: TLayout;
laMenuTitle: TLabel;
loBack: TLayout;
btnBack: TButton;
loParameters: TLayout;
tbSettings: TToolBar;
ToolbarApplyButton: TButton;
ToolbarCloseButton: TButton;
ToolbarAddButton: TButton;
tcAccount: TTabControl;
sbAccounts: THorzScrollBox;
tiAccount: TTabItem;
sbAccount: TVertScrollBox;
loAccountHeader: TLayout;
imgAccountIcon: TImageControl;
loAccountTitles: TLayout;
laAccountTitle: TLabel;
laAccountSubTitle: TLabel;
laUsername: TLabel;
edUsername: TEdit;
ClearEditButton3: TClearEditButton;
laPassword: TLabel;
pnPassword: TPanel;
laAccountStatus: TLabel;
pnAccountStatus: TPanel;
rbAccountLocked: TRadioButton;
rbAccountNotLocked: TRadioButton;
pnAccountOperation: TPanel;
btnAccountSave: TButton;
pnAccountSaveSuccess: TCalloutPanel;
lbAccountSaveSuccess: TLabel;
edPassword: TEdit;
PasswordEditButton1: TPasswordEditButton;
lbiAccountTemplate: TMetropolisUIListBoxItem;
btnAccountDelete: TButton;
laGuid: TLabel;
edGuid: TEdit;
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 lbiAddAccountClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure lbiAccountTemplateClick(Sender: TObject);
procedure btnAccountDeleteClick(Sender: TObject);
procedure btnAccountSaveClick(Sender: TObject);
private
FGestureOrigin: TPointF;
FGestureInProgress: Boolean;
{ Private declarations }
procedure ShowToolbar(AShow: Boolean);
procedure LoadAccountList;
procedure ReadAccount(index: integer);
function ValidateAccount: boolean;
procedure WriteAccount(index: integer);
procedure FlashAndDismiss(pn: TCalloutPanel);
procedure SwitchAccountIcon(Sender: TObject);
function GenerateGUID: string;
public
{ Public declarations }
end;
var
frmAccounts: TfrmAccounts;
implementation
{$R *.fmx}
uses ALIOSSUTIL, UnitMain, UnitMessage, ComObj;
procedure SelectItem(cb: TComboBox; item: string);
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 TfrmAccounts.btnAccountDeleteClick(Sender: TObject);
begin
//delete current user
if IdYes = MessageDlg('确认', '即将删除用户“'+self.laAccountTitle.Text+'”,确认删除吗?', '确定', '取消') then
begin
frmMain.IniData.Accounts.Delete(self.laAccountTitle.Tag);
//reload account list
self.LoadAccountList;
self.lbAccounts.ItemIndex := 0;
self.lbiAddAccountClick(self.lbiAddAccount);
end;
end;
procedure TfrmAccounts.btnAccountSaveClick(Sender: TObject);
begin
if not self.ValidateAccount then
begin
MessageDlg('提示', '保用户失败,请检查设置。', '确定');
exit;
end;
self.WriteAccount(self.laAccountTitle.Tag);
frmMain.SaveIniFile;
FlashAndDismiss(self.pnAccountSaveSuccess);
//reload account list
self.LoadAccountList;
end;
procedure TfrmAccounts.btnBackClick(Sender: TObject);
begin
Close;
end;
procedure TfrmAccounts.lbiAccountTemplateClick(Sender: TObject);
var
lb: TMetropolisUIListBoxItem;
begin
self.SwitchAccountIcon(Sender);
lb := Sender as TMetropolisUIListBoxItem;
self.laAccountTitle.Tag := lb.Tag;
self.laAccountTitle.Text := lb.Title;
self.pnAccountSaveSuccess.Opacity := 0.0;
self.btnAccountDelete.Opacity := 1.0;
//load account data
self.ReadAccount(lb.Tag);
end;
procedure TfrmAccounts.lbiAddAccountClick(Sender: TObject);
begin
self.SwitchAccountIcon(Sender);
self.laAccountTitle.Tag := -1;
self.laAccountTitle.Text := '添加用户';
self.pnAccountSaveSuccess.Opacity := 0.0;
self.btnAccountDelete.Opacity := 0.0;
//new account
self.ReadAccount(-1);
end;
procedure TfrmAccounts.LoadAccountList;
var
I: Integer;
data: string;
username: string;
lb: TMetropolisUIListBoxItem;
begin
//clear current items
for I := self.lbAccounts.Count - 1 downto 1 do
begin
self.lbAccounts.Items.Delete(I);
end;
for I := 0 to frmMain.IniData.Accounts.Count - 1 do
begin
data := frmMain.IniData.Accounts[I];
PopString(data);
username := PopString(data);
lb := self.lbiAccountTemplate.Clone(self.lbAccounts) as TMetropolisUIListBoxItem;
lb.Name := 'lbAccount'+IntToStr(i+1);
lb.Title := StringReplace(lb.Title, '{username}', username, [rfReplaceAll]);
lb.SubTitle := StringReplace(lb.SubTitle, '{username}', username, [rfReplaceAll]);
lb.Visible := true;
lb.Tag := i;
lb.OnClick := self.lbiAccountTemplateClick;
lb.Parent := self.lbAccounts;
end;
end;
procedure TfrmAccounts.ReadAccount(index: integer);
var
data: string;
guid: string;
username: string;
password: string;
locked: boolean;
begin
try
if index = -1 then
data := self.GenerateGUID
else
data := frmMain.IniData.Accounts[index];
//split data
//guid|username|password|true/false
guid := PopString(data);
username := PopString(data);
password := PopString(data);
locked := data = 'true';
self.edGuid.Text := guid;
self.edUsername.Text := username;
self.edPassword.Text := password;
self.rbAccountLocked.IsChecked := locked;
self.rbAccountNotLocked.IsChecked := not locked;
if index <> -1 then
self.laAccountTitle.Text := username;
except
end;
end;
procedure TfrmAccounts.FlashAndDismiss(pn: TCalloutPanel);
begin
pn.AnimateFloat('Opacity', 1.0, 0.3);
pn.AnimateFloatDelay('Opacity', 0.0, 0.7, 3.0);
end;
procedure TfrmAccounts.FormActivate(Sender: TObject);
begin
WindowState := TWindowState.wsMaximized;
tbSettings.BringToFront;
end;
procedure TfrmAccounts.FormCreate(Sender: TObject);
begin
//init account settings
CopyBitmap(self.lbiAddAccount.Icon, frmMain.imgAddAccountOn.Bitmap); //selected by default
CopyBitmap(self.lbiAccountTemplate.Icon, frmMain.imgAccountsOff.Bitmap);
//load account list
self.lbiAccountTemplate.Parent := self;
self.LoadAccountList;
self.lbiAddAccountClick(self.lbiAddAccount);
end;
procedure TfrmAccounts.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 TfrmAccounts.FormKeyDown(Sender: TObject; var Key: Word;
var KeyChar: Char; Shift: TShiftState);
begin
if Key = vkEscape then
Close;
end;
procedure TfrmAccounts.FormMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Single);
begin
if Button = TMouseButton.mbRight then
ShowToolbar(True)
else
ShowToolbar(False);
end;
function TfrmAccounts.GenerateGUID: string;
begin
result := CreateClassID;
result := copy(result, 2, length(result)-2); //remove {}
end;
procedure TfrmAccounts.WriteAccount(index: integer);
var
data: string;
begin
try
if self.rbAccountLocked.IsChecked then
data := 'true'
else
data := 'false';
data := self.edGuid.Text+'|'+self.edUsername.Text+'|'+self.edPassword.Text+'|'+data;
if index = -1 then
begin
//new user
frmMain.IniData.Accounts.Add(data);
end
else
begin
//save existing user
frmMain.IniData.Accounts[index] := data;
self.laAccountTitle.Text := self.edUsername.Text;
(self.lbAccounts.Selected as TMetropolisUIListBoxItem).Title := self.edUsername.Text;
end;
frmMain.AddLog('保存用户列表');
except
end;
end;
procedure TfrmAccounts.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 TfrmAccounts.SwitchAccountIcon(Sender: TObject);
var
lb: TMetropolisUIListBoxItem;
I: integer;
begin
for I := 0 to self.lbAccounts.Count - 1 do
begin
lb := self.lbAccounts.ItemByIndex(I) as TMetropolisUIListBoxItem;
if lb.TagString = 'on' then
begin
//last selected
if I = 0 then
frmMain.SwitchIcon(lb, 'imgAddAccountOff')
else
frmMain.SwitchIcon(lb, 'imgAccountsOff');
lb.TagString := '';
break;
end;
end;
//new account
lb := Sender as TMetropolisUIListBoxItem;
if lb = self.lbAccounts.ItemByIndex(0) then
frmMain.SwitchIcon(lb, 'imgAddAccountOn')
else
frmMain.SwitchIcon(lb, 'imgAccountsOn');
lb.TagString := 'on';
end;
procedure TfrmAccounts.ToolbarCloseButtonClick(Sender: TObject);
begin
Close;
end;
function TfrmAccounts.ValidateAccount: boolean;
var
I: Integer;
data: string;
guid: string;
username: string;
begin
result :=
(self.edUsername.Text <> '') and
(self.edPassword.Text <> '') and
(self.rbAccountLocked.IsChecked or self.rbAccountNotLocked.IsChecked);
if result then
begin
for I := 0 to frmMain.IniData.Accounts.Count - 1 do
begin
data := frmMain.IniData.Accounts[I];
guid := PopString(data);
username := PopString(data);
//check unique guid
if (self.laAccountTitle.Tag = -1) and (guid = self.edGuid.Text) then
begin
result := false;
break;
end;
//check unique username
if (username = self.edUsername.Text) and (guid <> self.edGuid.Text) then
begin
result := false;
break;
end;
end;
end;
end;
end.
|
(*
X-Mailer plugin.
Copyright (C) 2013 Silvio Clecio - silvioprog@gmail.com
Please see the LICENSE file.
*)
unit XMailer;
{$mode objfpc}{$H+}
//{$DEFINE OPEN_SSL}
{$DEFINE UTF_8_MIME}
interface
uses
{$IFDEF OPEN_SSL}
SSL_OpenSSL,
{$ENDIF}
{$IFDEF UTF_8_MIME}
MimeInln,
{$ENDIF}
SMTPSend, MimePart, MimeMess, SynaChar, SynaUtil, Classes, SysUtils;
type
TContentType = (ctTextPlain, ctTextHTML);
EMailer = class(Exception);
TMailerProgress = procedure(const AProgress, AMax: Integer;
const AStatus: string) of object;
{ TMimeMessEx }
TMimeMessEx = class(TMimeMess)
public
function AddPartText(const AValue: TStrings;
const APartParent: TMimePart): TMimepart;
function AddPartHTML(const AValue: TStrings;
const APartParent: TMimePart): TMimepart;
end;
{ TSmtp }
TSmtp = class(TSMTPSend)
private
function GetHost: string;
function GetPort: string;
function GetSSL: Boolean;
function GetTLS: Boolean;
procedure SetHost(AValue: string);
procedure SetPort(AValue: string);
procedure SetSSL(AValue: Boolean);
procedure SetTLS(AValue: Boolean);
public
property Host: string read GetHost write SetHost;
property Port: string read GetPort write SetPort;
property SSL: Boolean read GetSSL write SetSSL;
property TLS: Boolean read GetTLS write SetTLS;
end;
{ TSendMail }
TSendMail = class
private
FAttachments: TStrings;
FAttempts: Byte;
FBCC: TStrings;
FCC: TStrings;
FHeader: TStrings;
FOnProgress: TMailerProgress;
FReadingConfirmation: Boolean;
FMessage: TStrings;
FContentType: TContentType;
FPriority: TMessPriority;
FReceivers: TStrings;
FSender: string;
FSmtp: TSmtp;
FSubject: string;
public
constructor Create; virtual;
destructor Destroy; override;
procedure Send; virtual;
procedure Error(const AMsg: string);
procedure Progress(const APosition, AMax: Integer;
const AStatus: string); virtual;
property Smtp: TSmtp read FSmtp;
property Attempts: Byte read FAttempts write FAttempts;
property Sender: string read FSender write FSender;
property Receivers: TStrings read FReceivers;
property CC: TStrings read FCC;
property BCC: TStrings read FBCC;
property Subject: string read FSubject write FSubject;
property Header: TStrings read FHeader;
property Message: TStrings read FMessage;
property Attachments: TStrings read FAttachments;
property Priority: TMessPriority read FPriority write FPriority;
property ReadingConfirmation: Boolean read FReadingConfirmation
write FReadingConfirmation;
property ContentType: TContentType read FContentType write FContentType;
property OnProgress: TMailerProgress read FOnProgress write FOnProgress;
end;
{$IFDEF OPEN_SSL}
function IsAvailableOpenSSL: Boolean;
{$ENDIF}
procedure SendMail(
// Smtp params
const AHost, AUser, APassword: string; const ASSL, ATLS: Boolean;
// Mail params
const ASender, AReceivers, ASubject, AMessage: string; const ACC: string = '';
const ABCC: string = ''; const AAttachments: string = '';
const APriority: TMessPriority = MP_unknown;
const AReadingConfirmation: Boolean = False;
const AContentType: TContentType = ctTextPlain;
AProgress: TMailerProgress = nil);
procedure SendMail(const S: string; AArgs: array of const;
const AQuoteChar: Char = '"'; AProgress: TMailerProgress = nil);
procedure SendMail(const AParams: string; const AQuoteChar: Char = '"';
AProgress: TMailerProgress = nil);
procedure FormatEmailAddress(const S: string; out AAddr, ADesc: string);
function DequotedStr(const S: string; AQuoteChar: Char): string;
{$IFDEF UTF_8_MIME}
function UTF8InlineEncodeEmail(const AAddr, ADesc: string): string;
function UTF8InlineEncodeEmail(const AEmail: string): string;
function UTF8InlineEncode(const S: string): string;
{$ENDIF}
implementation
{$IFDEF OPEN_SSL}
function IsAvailableOpenSSL: Boolean;
var
VOpenSSL: TSSLOpenSSL;
begin
VOpenSSL := TSSLOpenSSL.Create(nil);
try
Result := VOpenSSL.LibVersion <> '';
finally
VOpenSSL.Free;
end;
end;
{$ENDIF}
procedure SendMail(
const AHost, AUser, APassword: string; const ASSL, ATLS: Boolean;
const ASender, AReceivers, ASubject, AMessage: string;
const ACC: string; const ABCC: string; const AAttachments: string;
const APriority: TMessPriority; const AReadingConfirmation: Boolean;
const AContentType: TContentType; AProgress: TMailerProgress);
begin
with TSendMail.Create do
try
FOnProgress := AProgress;
// Smtp properties
Smtp.Host := AHost;
Smtp.UserName := AUser;
Smtp.Password := APassword;
Smtp.TLS := ATLS;
Smtp.SSL := ASSL;
// Mail properties
Sender := ASender;
Receivers.DelimitedText := AReceivers;
Subject := ASubject;
Message.Text := AMessage;
CC.DelimitedText := ACC;
BCC.DelimitedText := ABCC;
Attachments.DelimitedText := AAttachments;
Priority := APriority;
ReadingConfirmation := AReadingConfirmation;
ContentType := AContentType;
Send;
finally
Free;
end;
end;
procedure SendMail(const S: string; AArgs: array of const;
const AQuoteChar: Char; AProgress: TMailerProgress);
begin
SendMail(Format(S, AArgs), AQuoteChar, AProgress);
end;
procedure SendMail(const AParams: string; const AQuoteChar: Char;
AProgress: TMailerProgress);
var
S: TStrings;
begin
S := TStringList.Create;
try
ExtractStrings([' '], [], PChar(AParams), S);
with TSendMail.Create do
begin
FOnProgress := AProgress;
// Smtp properties
Smtp.Host := S.Values['host'];
Smtp.UserName := S.Values['user'];
Smtp.Password := S.Values['password'];
Smtp.TLS := StrToBoolDef(S.Values['tls'], False);
Smtp.SSL := StrToBoolDef(S.Values['ssl'], False);
// Mail properties
Sender := DequotedStr(S.Values['from'], AQuoteChar);
Receivers.DelimitedText := DequotedStr(S.Values['to'], AQuoteChar);
Subject := DequotedStr(S.Values['subject'], AQuoteChar);
Message.Text := DequotedStr(S.Values['message'], AQuoteChar);
CC.DelimitedText := DequotedStr(S.Values['cc'], AQuoteChar);
BCC.DelimitedText := DequotedStr(S.Values['bcc'], AQuoteChar);
Attachments.DelimitedText :=
DequotedStr(S.Values['attachments'], AQuoteChar);
case S.Values['priority'] of
'unknown': Priority := MP_unknown;
'low': Priority := MP_low;
'normal': Priority := MP_normal;
'high': Priority := MP_high;
end;
ReadingConfirmation := StrToBoolDef(S.Values['readingconfirmation'], False);
case S.Values['contenttype'] of
'plain': ContentType := ctTextPlain;
'html': ContentType := ctTextHTML;
end;
Send;
end;
finally
S.Free;
end;
end;
procedure FormatEmailAddress(const S: string; out AAddr, ADesc: string);
begin
AAddr := GetEmailAddr(S);
ADesc := GetEmailDesc(S);
end;
function DequotedStr(const S: string; AQuoteChar: Char): string;
var
L: SizeInt;
begin
Result := S;
L := Length(S);
if L = 0 then
Exit;
if Copy(Result, 1, 1) = AQuoteChar then
Delete(Result, 1, 1);
if Copy(S, L, 1) = AQuoteChar then
Delete(Result, L - 1, 1);
end;
{$IFDEF UTF_8_MIME}
function UTF8InlineEncodeEmail(const AAddr, ADesc: string): string;
begin
if ADesc <> '' then
Result := UTF8InlineEncode(ADesc) + ' <' + AAddr + '>'
else
Result := AAddr;
end;
function UTF8InlineEncodeEmail(const AEmail: string): string;
var
VAddr, VDesc: string;
begin
VAddr := GetEmailAddr(AEmail);
VDesc := GetEmailDesc(AEmail);
if VDesc <> '' then
Result := UTF8InlineEncode(VDesc) + ' <' + VAddr + '>'
else
Result := VAddr;
end;
function UTF8InlineEncode(const S: string): string;
begin
if NeedInline(S) then
Result := InlineEncode(S, UTF_8, UTF_8)
else
Result := S;
end;
{$ENDIF}
{ TSmtp }
function TSmtp.GetHost: string;
begin
Result := TargetHost;
end;
function TSmtp.GetPort: string;
begin
Result := TargetPort;
end;
function TSmtp.GetSSL: Boolean;
begin
Result := FullSSL;
end;
function TSmtp.GetTLS: Boolean;
begin
Result := AutoTLS;
end;
procedure TSmtp.SetHost(AValue: string);
var
S: string;
begin
if Pos(':', AValue) = 0 then
TargetHost := AValue
else
begin
TargetHost := Trim(SeparateLeft(AValue, ':'));
S := Trim(SeparateRight(AValue, ':'));
if (S <> '') and (S <> AValue) then
TargetPort := S;
end;
end;
procedure TSmtp.SetPort(AValue: string);
begin
TargetPort := AValue;
end;
procedure TSmtp.SetSSL(AValue: Boolean);
begin
FullSSL := AValue;
end;
procedure TSmtp.SetTLS(AValue: Boolean);
begin
AutoTLS := AValue;
end;
{ TMimeMessEx }
function TMimeMessEx.AddPartText(const AValue: TStrings;
const APartParent: TMimePart): TMimepart;
begin
Result := AddPart(APartParent);
with Result do
begin
AValue.SaveToStream(DecodedLines);
Primary := 'text';
Secondary := 'plain';
Description := 'Message text';
CharsetCode := UTF_8;
EncodingCode := ME_8BIT;
TargetCharset := UTF_8;
ConvertCharset := True;
EncodePart;
EncodePartHeader;
end;
end;
function TMimeMessEx.AddPartHTML(const AValue: TStrings;
const APartParent: TMimePart): TMimepart;
begin
Result := AddPart(APartParent);
with Result do
begin
AValue.SaveToStream(DecodedLines);
Primary := 'text';
Secondary := 'html';
Description := 'HTML text';
CharsetCode := UTF_8;
EncodingCode := ME_8BIT;
TargetCharset := UTF_8;
ConvertCharset := True;
EncodePart;
EncodePartHeader;
end;
end;
{ TSendMail }
constructor TSendMail.Create;
begin
inherited Create;
FSmtp := TSmtp.Create;
FReceivers := TStringList.Create;
FCC := TStringList.Create;
FBCC := TStringList.Create;
FHeader := TStringList.Create;
FMessage := TStringList.Create;
FAttachments := TStringList.Create;
FReceivers.StrictDelimiter := True;
FAttempts := 3;
FReceivers.Delimiter := ';';
FCC.StrictDelimiter := True;
FCC.Delimiter := ';';
FBCC.StrictDelimiter := True;
FBCC.Delimiter := ';';
FAttachments.StrictDelimiter := True;
FAttachments.Delimiter := ';';
FPriority := MP_unknown;
end;
destructor TSendMail.Destroy;
begin
FReceivers.Free;
FCC.Free;
FBCC.Free;
FHeader.Free;
FMessage.Free;
FAttachments.Free;
FSmtp.Free;
inherited Destroy;
end;
procedure TSendMail.Send;
var
VAttempts: Byte;
VMimePart: TMimePart;
I, C, VPMax, VPPos: Integer;
VSenderAddr{$IFDEF UTF_8_MIME}, VTo, VCC, VSenderDesc{$ENDIF}: string;
VMimeMess:{$IFDEF UTF_8_MIME}TMimeMessEx{$ELSE}TMimeMess{$ENDIF};
procedure _SetReadingConfirmation(const A: string);
begin
if FReadingConfirmation then
VMimeMess.Header.CustomHeaders.Insert(0,
'Disposition-Notification-To: ' + A);
end;
begin
{$IFDEF OPEN_SSL}
if not IsAvailableOpenSSL then
raise Exception.CreateFmt('%: SSL error: %s',
[Self.ClassName, 'Could not found the SSL library.']);
{$ENDIF}
VPMax := 10;
VPPos := 0;
Inc(VPPos);
Progress(VPPos, VPMax, 'Starting ...');
VMimeMess :={$IFDEF UTF_8_MIME}TMimeMessEx{$ELSE}TMimeMess{$ENDIF}.Create;
try
case FContentType of
ctTextPlain:
begin
if FAttachments.Count > 0 then
VMimePart := VMimeMess.AddPartMultipart('mixed', nil);
if FMessage.Count > 0 then
begin
if FAttachments.Count > 0 then
VMimeMess.AddPartText(FMessage, VMimePart)
else
VMimePart := VMimeMess.AddPartText(FMessage, nil);
end;
for I := 0 to Pred(FAttachments.Count) do
VMimeMess.AddPartBinaryFromFile(FAttachments.Strings[I], VMimePart);
end;
ctTextHTML:
begin
if FAttachments.Count > 0 then
VMimePart := VMimeMess.AddPartMultipart('related', nil);
if FMessage.Count > 0 then
begin
if FAttachments.Count > 0 then
VMimeMess.AddPartHTML(FMessage, VMimePart)
else
VMimePart := VMimeMess.AddPartHTML(FMessage, nil);
end;
for I := 0 to Pred(FAttachments.Count) do
VMimeMess.AddPartHTMLBinaryFromFile(FAttachments.Strings[I],
'<' + ExtractFileName(FAttachments.Strings[I]) + '>', VMimePart);
end;
end;
Inc(VPPos);
Progress(VPPos, VPMax, 'Formating headers ...');
{$IFDEF UTF_8_MIME}
VMimeMess.Header.CharsetCode := UTF_8;
VMimeMess.Header.CustomHeaders.Assign(FHeader);
VMimeMess.Header.CustomHeaders.Insert(0, 'Subject: ' +
UTF8InlineEncode(FSubject));
FormatEmailAddress(FSender, VSenderAddr, VSenderDesc);
if FReadingConfirmation then
_SetReadingConfirmation(VSenderAddr);
{$ELSE}
VMimeMess.Header.Subject := FSubject;
VMimeMess.Header.From := FSender;
VSenderAddr := GetEmailAddr(FSender);
VMimeMess.Header.ToList.AddStrings(FReceivers);
VMimeMess.Header.CCList.AddStrings(FCC);
if FReadingConfirmation then
_SetReadingConfirmation(VSenderAddr);
{$ENDIF}
VMimeMess.Header.XMailer := 'X-Mailer plugin';
if FPriority <> MP_unknown then
VMimeMess.Header.Priority := FPriority;
VMimeMess.EncodeMessage;
{$IFDEF UTF_8_MIME}
VTo := '';
for I := 0 to Pred(FReceivers.Count) do
VTo += UTF8InlineEncodeEmail(FReceivers.Strings[I]) + ', ';
VCC := '';
for I := 0 to Pred(FCC.Count) do
VCC := UTF8InlineEncodeEmail(FCC.Strings[I]) + ', ';
if VTo <> '' then
begin
SetLength(VTo, Length(VTo) - 2);
VMimeMess.Lines.Insert(0, 'To: ' + VTo);
end;
if VCC <> '' then
begin
SetLength(VCC, Length(VCC) - 2);
VMimeMess.Lines.Insert(0, 'CC: ' + VCC);
end;
VMimeMess.Lines.Delete(VMimeMess.Lines.IndexOf('From: '));
VMimeMess.Lines.Insert(0, 'From: ' +
UTF8InlineEncodeEmail(VSenderAddr, VSenderDesc));
{$ENDIF}
Inc(VPPos);
Progress(VPPos, VPMax, 'Logging on SMTP ...');
for VAttempts := 1 to FAttempts do
begin
if FSmtp.Login then
Break;
if VAttempts >= FAttempts then
Error('SMTP::Login');
end;
Inc(VPPos);
Progress(VPPos, VPMax, 'Sending the sender data ...');
for VAttempts := 1 to FAttempts do
begin
if FSmtp.MailFrom(VSenderAddr, Length(VSenderAddr)) then
Break;
if VAttempts >= FAttempts then
Error('SMTP::MailFrom');
end;
Inc(VPPos);
Progress(VPPos, VPMax, 'Sending receivers data ...');
for I := 0 to Pred(FReceivers.Count) do
for VAttempts := 1 to FAttempts do
begin
if FSmtp.MailTo(GetEmailAddr(FReceivers.Strings[I]))then
Break;
if VAttempts >= FAttempts then
Error('SMTP::MailTo');
end;
Inc(VPPos);
C := FCC.Count;
if C > 0 then
Progress(VPPos, VPMax, 'Sending CCs data ...');
for I := 0 to Pred(C) do
for VAttempts := 1 to FAttempts do
begin
if FSmtp.MailTo(GetEmailAddr(FCC.Strings[I])) then
Break;
if VAttempts >= FAttempts then
Error('SMTP::MailCC');
end;
Inc(VPPos);
C := FBCC.Count;
if C > 0 then
Progress(VPPos, VPMax, 'Sending BCCs data ...');
for I := 0 to Pred(C) do
for VAttempts := 1 to FAttempts do
begin
if FSmtp.MailTo(GetEmailAddr(FBCC.Strings[I])) then
Break;
if VAttempts >= FAttempts then
Error('SMTP::MailBCC');
end;
Inc(VPPos);
Progress(VPPos, VPMax, 'Sending the message data ...');
for VAttempts := 1 to FAttempts do
begin
if FSmtp.MailData(VMimeMess.Lines) then
Break;
if VAttempts >= FAttempts then
Error('SMTP::MailData');
end;
Inc(VPPos);
Progress(VPPos, VPMax, 'Exiting from SMTP ...');
for VAttempts := 1 to FAttempts do
begin
if FSmtp.Logout then
Break;
if VAttempts >= FAttempts then
Error('SMTP::Logout');
end;
Inc(VPPos);
Progress(VPPos, VPMax, 'Done.');
finally
VMimeMess.Free;
end;
end;
procedure TSendMail.Error(const AMsg: string);
begin
raise EMailer.CreateFmt('%s: SMTP error: %s' + LineEnding + '%s%s',
[Self.ClassName, AMsg, FSmtp.EnhCodeString, FSmtp.FullResult.Text]);
end;
procedure TSendMail.Progress(const APosition, AMax: Integer;
const AStatus: string);
begin
if Assigned(FOnProgress) then
FOnProgress(APosition, AMax, AStatus);
end;
end.
|
{
求多个数的最大公约数
@file gcd.pas
@author yjf_victor
@date 2014-11-01
}
program GreatestCommonDivisor(Input, Output);
{
求两个数的最大公约数
@param[in] n 第一个数
@param[in] m 第二个数
@return 最大公约数
}
function gcd(n, m: Integer) : Integer;
var r: Integer;
begin
repeat
r := m Mod n;
m := n;
n := r;
until r = 0;
gcd := m;
end;
{
主过程
}
var i, n, current_gcd, current_number: Integer;
begin
read(n);
read(current_gcd);
for i := 2 to n do
begin
read(current_number);
current_gcd := gcd(current_gcd, current_number);
end;
writeln(current_gcd);
end. |
unit MD5.Globals;
// Глобальные переменные.
interface
uses
MD5.Logs,
MD5.Console,
MD5.Version;
const
ATTR_STATNUMBER = $000B; // Число в статистике
ATTR_STATPERCENT = $000D; // Процент в статистике
ATTR_HIGHLIGHT = $000F; // Просто выделение
ATTR_NUMBER = $000F; // Число
ATTR_FILE = $0006; // Файл/путь
ATTR_ERROR = $000C; // ОШИБКА
ATTR_OK = $000A; // НЕТ_ОШИБКИ
ATTR_WORKMODE = $000F; // Режим работы программы
type
TOptions = record
_WorkPath: String; // рабочий каталог, где хранятся MD5 файлы
_BasePath: String; // базовый каталог, с файлами
LogPath: String; // каталог с лог-файлами
SpecialMode: Boolean;
Recursive: Boolean; // Рекурсивный поиск *.md5 файлов
end;
var
Log: TLog;
Console: TConsole;
Version: TVersion;
Options: TOptions;
implementation
initialization
Console := TConsole.Create;
finalization
Console.Free;
end.
|
unit UnPagamentosView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, JvExExtCtrls, JvExtComponent, JvPanel, Grids, DBGrids, DB,
StdCtrls,
{ Fluente }
UnModelo, Componentes, UnAplicacao;
type
TPagamentosView = class(TForm, ITela)
pnlCommand: TJvPanel;
btnOk: TPanel;
pnlDesktop: TPanel;
Panel8: TPanel;
Panel9: TPanel;
gPagamentos: TDBGrid;
lblPagamentos: TLabel;
procedure btnOkClick(Sender: TObject);
private
FControlador: IResposta;
FModelo: TModelo;
public
function Controlador(const Controlador: IResposta): ITela;
function Descarregar: ITela;
function ExibirTela: Integer;
function Modelo(const Modelo: TModelo): ITela;
function Preparar: ITela;
end;
var
PagamentosView: TPagamentosView;
implementation
{$R *.dfm}
procedure TPagamentosView.btnOkClick(Sender: TObject);
begin
Self.ModalResult := mrOk;
end;
function TPagamentosView.Descarregar: ITela;
begin
Self.gPagamentos.DataSource := nil;
Result := Self;
end;
function TPagamentosView.Preparar: ITela;
begin
Self.gPagamentos.DataSource := Self.FModelo.DataSource(
Self.FModelo.Parametros.Ler('datasource').ComoTexto);
Self.lblPagamentos.Caption := FormatFloat('R$ ###,##0.00',
Self.FModelo.Parametros.Ler('total').ComoDecimal);
Result := Self;
end;
function TPagamentosView.Controlador(
const Controlador: IResposta): ITela;
begin
Self.FControlador := Controlador;
Result := Self;
end;
function TPagamentosView.ExibirTela: Integer;
begin
Result := Self.ShowModal;
end;
function TPagamentosView.Modelo(const Modelo: TModelo): ITela;
begin
Self.FModelo := Modelo;
Result := Self;
end;
end.
|
unit xElecOrgan;
interface
uses SysUtils, Classes, xElecLine, xElecFunction, Math, xElecPoint;
type
/// <summary>
/// 电表计量元件类
/// </summary>
TElecOrgan = class
private
FOrganName: string;
FVolPointOut: TElecLine;
FVolPointIn: TElecLine;
FVolOrgan : TElecPoint;
FOnChange: TNotifyEvent;
FCurrentPointOut: TElecLine;
FCurrentPointIn: TElecLine;
FCurrentPoint: TElecPoint;
FIsReactive: Boolean;
/// <summary>
/// 电压或电流值改变
/// </summary>
procedure ValueChange(Sender: TObject);
function GetActivePower: Double;
function GetReactivePower: Double;
function GetPowerFactor: Double;
function GetPositiveActivePower: Double;
function GetReverseActivePower: Double;
function GetPositiveReactivePower: Double;
function GetReverseReactivePower: Double;
function GetQuadrantReactivePower(nSN: Integer): Double;
function GetAngle: Double;
function GetIsIBreak: Boolean;
function GetIsIReverse: Boolean;
function GetIsUBreak: Boolean;
function GetVolOrgan: TElecPoint;
procedure SetOrganName(const Value: string);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 元件名称
/// </summary>
property OrganName : string read FOrganName write SetOrganName;
/// <summary>
/// 电压线进
/// </summary>
property VolPointIn : TElecLine read FVolPointIn write FVolPointIn;
/// <summary>
/// 电压线出
/// </summary>
property VolPointOut : TElecLine read FVolPointOut write FVolPointOut;
/// <summary>
/// 元件电压合向量
/// </summary>
property VolOrgan : TElecPoint read GetVolOrgan;
/// <summary>
/// 电流进线
/// </summary>
property CurrentPointIn : TElecLine read FCurrentPointIn write FCurrentPointIn;
/// <summary>
/// 电流出线
/// </summary>
property CurrentPointOut : TElecLine read FCurrentPointOut write FCurrentPointOut;
/// <summary>
/// 获取原件电流值
/// </summary>
function GetOrganCurrent: TElecPoint;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
/// <summary>
/// 清空电压值
/// </summary>
procedure ClearVolVlaue;
/// <summary>
/// 改变事件
/// </summary>
property OnChange : TNotifyEvent read FOnChange write FOnChange;
/// <summary>
/// 相角
/// </summary>
property Angle : Double read GetAngle;
/// <summary>
/// 是否是无功表 无功表需要把电压合向量移动60度
/// </summary>
property IsReactive : Boolean read FIsReactive write FIsReactive;
{电能相关}
/// <summary>
/// 有功功率
/// </summary>
property ActivePower : Double read GetActivePower;
/// <summary>
/// 无功功率
/// </summary>
property ReactivePower : Double read GetReactivePower;
/// <summary>
/// 正向有功功率
/// </summary>
property PositiveActivePower : Double read GetPositiveActivePower;
/// <summary>
/// 反向有功功率
/// </summary>
property ReverseActivePower : Double read GetReverseActivePower;
/// <summary>
/// 正向无功功率
/// </summary>
property PositiveReactivePower : Double read GetPositiveReactivePower;
/// <summary>
/// 反向无功功率
/// </summary>
property ReverseReactivePower : Double read GetReverseReactivePower;
/// <summary>
/// 四象限无功功率
/// </summary>
property QuadrantReactivePower[nSN : Integer] : Double read GetQuadrantReactivePower;
/// <summary>
/// 功率因数
/// </summary>
property PowerFactor : Double read GetPowerFactor;
{故障相关}
/// <summary>
/// U失压
/// </summary>
property IsUBreak : Boolean read GetIsUBreak;
/// <summary>
/// I失流
/// </summary>
property IsIBreak : Boolean read GetIsIBreak;
/// <summary>
/// I反向
/// </summary>
property IsIReverse : Boolean read GetIsIReverse;
end;
implementation
{ TElecOrgan }
procedure TElecOrgan.ClearVolVlaue;
begin
FVolPointIn.Voltage.ClearValue;
FVolPointOut.Voltage.ClearValue;
end;
procedure TElecOrgan.ClearWValue;
begin
FCurrentPointOut.ClearWValue;
FCurrentPointIn.ClearWValue;
end;
constructor TElecOrgan.Create;
begin
FVolPointIn:= TElecLine.Create;
FVolPointOut:= TElecLine.Create;
FVolOrgan:= TElecPoint.Create;
FCurrentPointOut:= TElecLine.Create;
FCurrentPointIn:= TElecLine.Create;
FCurrentPoint:= TElecPoint.Create;
FVolPointIn.Onwner := Self;
FVolPointOut.Onwner := Self;
FCurrentPointIn.Onwner := Self;
FCurrentPointOut.Onwner := Self;
FIsReactive := False;
FCurrentPointOut.ConnPointAdd(FCurrentPointIn);
FOrganName := '默认元件名';
FVolPointIn.OnChange := ValueChange;
FVolPointOut.OnChange := ValueChange;
FCurrentPointIn.OnChange := ValueChange;
FCurrentPointOut.OnChange := ValueChange;
end;
destructor TElecOrgan.Destroy;
begin
FVolPointOut.Free;
FVolPointIn.Free;
FVolOrgan.Free;
FCurrentPointOut.Free;
FCurrentPointIn.Free;
FCurrentPoint.Free;
inherited;
end;
function TElecOrgan.GetActivePower: Double;
begin
Result := VolOrgan.Value*GetOrganCurrent.Value* PowerFactor;
end;
function TElecOrgan.GetAngle: Double;
begin
result := AdjustAngle(VolOrgan.Angle - GetOrganCurrent.Angle);
end;
function TElecOrgan.GetIsIBreak: Boolean;
begin
Result := Abs(GetOrganCurrent.Value) < 0.1;
end;
function TElecOrgan.GetIsIReverse: Boolean;
begin
Result := GetOrganCurrent.Value < -0.1;
end;
function TElecOrgan.GetIsUBreak: Boolean;
begin
Result := VolOrgan.Value < 30;
end;
function TElecOrgan.GetOrganCurrent: TElecPoint;
begin
GetTwoPointCurrent(FCurrentPointIn, FCurrentPointOut, FCurrentPoint);
Result := FCurrentPoint;
end;
function TElecOrgan.GetPositiveActivePower: Double;
var
dValue : Double;
begin
dValue := Angle;
case GetQuadrantSN(dValue) of
1 :
begin
Result := GetActivePower;
end;
2 :
begin
Result := 0;
end;
3 :
begin
Result := 0;
end;
else
begin
Result := GetActivePower;
end;
end;
Result := Abs(Result);
end;
function TElecOrgan.GetPositiveReactivePower: Double;
var
dValue : Double;
begin
dValue := Angle;
case GetQuadrantSN(dValue) of
1 :
begin
Result := GetReactivePower;
end;
2 :
begin
Result := GetReactivePower;
end;
3 :
begin
Result := 0;
end;
else
begin
Result := 0;
end;
end;
Result := Abs(Result);
end;
function TElecOrgan.GetPowerFactor: Double;
begin
// // Cosφ=1/(1+(无功力调电量/有功力调电量)^2)^0.5
// Result := 1 / sqrt( 1 + sqr( ReactivePower / ActivePower ));
Result := Cos(DegToRad(Angle))
end;
function TElecOrgan.GetQuadrantReactivePower(nSN: Integer): Double;
var
dValue : Double;
begin
dValue := Angle;
if GetQuadrantSN(dValue) = nSN then
Result := GetReactivePower
else
Result := 0;
Result := Abs(Result);
end;
function TElecOrgan.GetReactivePower: Double;
begin
Result := VolOrgan.Value*GetOrganCurrent.Value*
Sin(DegToRad(Angle))
end;
function TElecOrgan.GetReverseActivePower: Double;
var
dValue : Double;
begin
dValue := Angle;
case GetQuadrantSN(dValue) of
1 :
begin
Result := 0;
end;
2 :
begin
Result := GetActivePower;
end;
3 :
begin
Result := GetActivePower;
end;
else
begin
Result := 0;
end;
end;
Result := Abs(Result);
end;
function TElecOrgan.GetReverseReactivePower: Double;
var
dValue : Double;
begin
dValue := Angle;
case GetQuadrantSN(dValue) of
1 :
begin
Result := 0;
end;
2 :
begin
Result := 0;
end;
3 :
begin
Result := GetReactivePower;
end;
else
begin
Result := GetReactivePower;
end;
end;
Result := Abs(Result);
end;
function TElecOrgan.GetVolOrgan: TElecPoint;
begin
// 计算电压 和向量
GetOtherValue(FVolPointIn.Voltage, FVolPointOut.Voltage, FVolOrgan);
// 六十度无功需要移动60度
if FIsReactive then
FVolOrgan.Angle := AdjustAngle(FVolOrgan.Angle + 30);
Result := FVolOrgan;
end;
procedure TElecOrgan.SetOrganName(const Value: string);
begin
FOrganName := Value;
FVolPointIn.LineName := FOrganName + 'VolIn';
FVolPointOut.LineName := FOrganName + 'VolOut';
FCurrentPointIn.LineName := FOrganName + 'CurrentIn';
FCurrentPointOut.LineName := FOrganName + 'CurrentOut';
end;
//procedure TElecOrgan.SetIsIBreak(const Value: Boolean);
//begin
// if Value then
// begin
// if FCurrentPointIn.CurrentReal.Current.Value <> 0 then
// FCurTemp := FCurrentPointIn.CurrentReal.Current.Value;
//
// FCurrentPointIn.CurrentReal.Current.Value := 0;
// end
// else
// begin
// if FCurTemp <> 0 then
// FCurrentPointIn.CurrentReal.Current.Value := FCurTemp;
// end;
//end;
//procedure TElecOrgan.SetIsIReverse(const Value: Boolean);
//begin
// if Value then
// begin
// CurrentOrgan.Current.Value := -abs(FCurrentPointIn.CurrentReal.Current.Value);
// end
// else
// begin
// CurrentOrgan.Current.Value := abs(FCurrentPointIn.CurrentReal.Current.Value);
// end;
//
//end;
//procedure TElecOrgan.SetIsUBreak(const Value: Boolean);
//begin
// if Value then
// begin
// if FVolPointIn.Voltage.Value <> 0 then
// FVolTemp := FVolPointIn.Voltage.Value;
// FVolPointIn.Voltage.Value := 0;
//
// end
// else
// begin
// if FVolTemp <> 0 then
// FVolPointIn.Voltage.Value := FVolTemp;
// end;
//end;
procedure TElecOrgan.ValueChange(Sender: TObject);
begin
if Assigned(FOnChange) then
FOnChange(Self);
end;
end.
|
{******************************************************************
JEDI-VCL Demo
Copyright (C) 2002 Project JEDI
Original author:
Contributor(s):
You may retrieve the latest version of this file at the JEDI-JVCL
home page, located at http://jvcl.delphi-jedi.org
The contents of this file are used with permission, 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/MPL-1_1Final.html
Software distributed under the License is distributed on an
"AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
implied. See the License for the specific language governing
rights and limitations under the License.
******************************************************************}
unit DropFrm;
{$mode objfpc}{$H+}
interface
uses
LCLIntf, LCLType, //LMessages, Types,
SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ImgList, ShellCtrls;
type
TDropFrmAcceptEvent = procedure(Sender: TObject; Index: integer; const Value: string) of object;
{ TfrmDrop }
TfrmDrop = class(TForm)
Label1: TLabel;
btnCancel: TButton;
tvFolders: TShellTreeView;
ilSmallIcons: TImageList;
btnOK: TButton;
PathLabel: TLabel;
procedure tvFoldersDblClick(Sender: TObject);
procedure tvFoldersGetImageIndex(Sender: TObject; Node: TTreeNode);
{
procedure tvFolders_1Expanding(Sender: TObject; Node: TTreeNode;
var AllowExpansion: Boolean);
}
procedure FormClose(Sender: TObject; var TheAction: TCloseAction);
procedure btnCancelClick(Sender: TObject);
procedure btnOKClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure tvFoldersChange(Sender: TObject; Node: TTreeNode);
procedure tvFoldersGetSelectedIndex(Sender: TObject; Node: TTreeNode);
private
FOnAccept: TDropFrmAcceptEvent;
FIncludeFiles: boolean;
procedure SetIncludeFiles(AValue: Boolean);
protected
procedure CreateParams(var Params: TCreateParams); override;
// procedure WMActivate(var Message: TLMActivate); message LM_ACTIVATE;
public
property IncludeFiles: boolean read FIncludeFiles write SetIncludeFiles;
property OnAccept: TDropFrmAcceptEvent read FOnAccept write FOnAccept;
end;
var
frmDrop: TfrmDrop = nil;
implementation
uses
JvJCLUtils;
{$R *.lfm}
{ TfrmDrop }
procedure TfrmDrop.btnCancelClick(Sender: TObject);
begin
if not (fsModal in FormState) then
Close;
end;
procedure TfrmDrop.btnOKClick(Sender: TObject);
begin
if not (fsModal in FormState) then
Close;
end;
procedure TfrmDrop.CreateParams(var Params: TCreateParams);
begin
inherited;
if BorderStyle = bsDialog then
Params.Style := Params.Style and not WS_BORDER;
end;
procedure TfrmDrop.FormClose(Sender: TObject; var TheAction: TCloseAction);
begin
if (ModalResult = mrOK) and Assigned(FOnAccept) then
FOnAccept(self, -1, (tvFolders.Selected as TShellTreeNode).FullFilename);
end;
procedure TfrmDrop.FormShow(Sender: TObject);
begin
if tvFolders.CanFocus then tvFolders.SetFocus;
end;
procedure TfrmDrop.SetIncludeFiles(AValue: Boolean);
begin
if AValue then
tvFolders.ObjectTypes := tvFolders.ObjectTypes + [otNonFolders]
else
tvFolders.ObjectTypes := tvFolders.ObjectTypes - [otNonFolders];
end;
procedure TfrmDrop.tvFoldersChange(Sender: TObject; Node: TTreeNode);
begin
PathLabel.Caption := MinimizeFileName((Node as TShellTreeNode).FullFileName, Canvas, PathLabel.Width);
end;
procedure TfrmDrop.tvFoldersDblClick(Sender: TObject);
begin
if (tvFolders.Selected <> nil) and (not tvFolders.Selected.HasChildren) then
btnOK.Click;
end;
procedure TfrmDrop.tvFoldersGetImageIndex(Sender: TObject;
Node: TTreeNode);
begin
if not (Node as TShellTreeNode).IsDirectory then
Node.ImageIndex := -1
else
if Node = tvFolders.Selected then
Node.ImageIndex := 1
else
Node.ImageIndex := 0;
end;
procedure TfrmDrop.tvFoldersGetSelectedIndex(Sender: TObject;
Node: TTreeNode);
begin
if not (Node as TShellTreeNode).IsDirectory then
Node.SelectedIndex := -1
else
if Node = tvFolders.Selected then
Node.SelectedIndex := 1
else
Node.SelectedIndex := 0;
end;
end.
|
unit LoanClassCharge;
interface
type
TValueType = (vtFixed, vtPercentage, vtRatio);
type
TMaxValueType = (mvtMonths,mvtAmount);
type
TLoanClassCharge = class
private
FChargeType: string;
FChargeName: string;
FChargeValue: real;
FValueType: TValueType;
FRatioAmount: real;
FMaxValue: real;
FMaxValueType: TMaxValueType;
FForNew: boolean;
FForRenewal: boolean;
FForRestructure: boolean;
FForReloan: boolean;
public
property ChargeType: string read FChargeType write FChargeType;
property ChargeName: string read FChargeName write FChargeName;
property ChargeValue: real read FChargeValue write FChargeValue;
property ValueType: TValueType read FValueType write FValueType;
property RatioAmount: real read FRatioAmount write FRatioAmount;
property MaxValue: real read FMaxValue write FMaxValue;
property MaxValueType: TMaxValueType read FMaxValueType write FMaxValueType;
property ForNew: boolean read FForNew write FForNew;
property ForRenewal: boolean read FForRenewal write FForRenewal;
property ForRestructure: boolean read FForRestructure write FForRestructure;
property ForReloan: boolean read FForReloan write FForReloan;
constructor Create(const ct: string; const cv: real; vt: TValueType); overload;
constructor Create(const ct, cn: string; const cv: real; vt: TValueType;
const ratioAmt, maxVal: real; const mvt: TMaxValueType; fn, fr, ft, fl: boolean); overload;
end;
var
cg: TLoanClassCharge;
implementation
constructor TLoanClassCharge.Create(const ct: string; const cv: Real; vt: TValueType);
begin
FChargeType := ct;
FChargeValue := cv;
FValueType := vt;
end;
constructor TLoanClassCharge.Create(const ct, cn: string; const cv: real; vt: TValueType;
const ratioAmt, maxVal: real; const mvt: TMaxValueType; fn, fr, ft, fl: boolean);
begin
FChargeType := ct;
FChargeName := cn;
FChargeValue := cv;
FValueType := vt;
FRatioAmount := ratioAmt;
FMaxValue := maxVal;
FMaxValueType := mvt;
FForNew := fn;
FForRenewal := fr;
FForRestructure := ft;
FForReloan := fl;
end;
end.
|
unit Model.PhoneNumber;
interface
uses
iORM.Attributes;
type
[ioEntity]
TPhoneNumber = class
private
FID, FCustomerID: Integer;
FNumberType: String;
FNumber: String;
public
constructor Create(const ANumberType, ANumber: String);
property ID: Integer read FID write FID;
property CustomerID: Integer read FCustomerID write FCustomerID;
property NumberType: String read FNumberType write FNumberType;
property Number: String read FNumber write FNumber;
end;
implementation
{ TPhoneNumber }
constructor TPhoneNumber.Create(const ANumberType, ANumber: String);
begin
inherited Create;
FNumberType := ANumberType;
FNumber := ANumber;
end;
end.
|
unit ClassDefs;
interface
uses
Values, Codes, Functions, Strings;
const
STR_CLASSDEF = 'classdef';
type
TClassDefs = class;
TClassDef = class
private
FClassDefs: TClassDefs;
FID: TID;
FCID: TCID;
FFields: TArguments;
FMethods: TFunctions;
function GetIndex(): Integer;
public
constructor Create(AClassDefs: TClassDefs; AIndex: Integer = -1);
destructor Destroy(); override;
function Compile(AText: String): Boolean;
function Method(const AID: TID;
const AArguments: TValues; AClass: TValue): TValue;
property ClassDefs: TClassDefs read FClassDefs;
property Index: Integer read GetIndex;
property ID: TID read FID;
property CID: TCID read FCID;
property Fields: TArguments read FFields;
property Methods: TFunctions read FMethods;
end;
TClassDefArray = array of TClassDef;
TClassDefs = class
private
FClassDefs: TClassDefArray;
FOnDefine: TDefineProc;
FOnVariable: TVariableFunc;
FOnFunction: TFunctionFunc;
FOnMethod: TFunctionFunc;
function GetClassDef(Index: Integer): TClassDef;
function GetCount(): Integer;
procedure DoDefine(const AID: TID; AType_: TType_;
AExts: TType_Exts = []);
function DoVariable(const AID: TID): TValue;
function DoFunction(const AID: TID;
const AArguments: TValues; AClass: TValue = nil): TValue;
function DoMethod(const AID: TID;
const AArguments: TValues; AClass: TValue = nil): TValue;
public
constructor Create();
destructor Destroy(); override;
function CreateCID(): TCID;
procedure Add(AClassDef: TClassDef; AIndex: Integer = -1);
procedure Delete(AIndex: Integer);
procedure Clear();
function IndexOf(AClassDef: TClassDef): Integer;
function ClassDefByID(const AID: TID): TClassDef;
function ClassDefByCID(ACID: TCID): TClassDef;
property ClassDefs[Index: Integer]: TClassDef read GetClassDef; default;
property Count: Integer read GetCount;
property OnDefine: TDefineProc read FOnDefine write FOnDefine;
property OnVariable: TVariableFunc read FOnVariable write FOnVariable;
property OnFunction: TFunctionFunc read FOnFunction write FOnFunction;
property OnMethod: TFunctionFunc read FOnMethod write FOnMethod;
end;
implementation
uses
SysUtils;
{ TClassDef }
{ private }
function TClassDef.GetIndex(): Integer;
begin
if Assigned(FClassDefs) then
Result := FClassDefs.IndexOf(Self)
else
Result := -1;
end;
{ public }
constructor TClassDef.Create(AClassDefs: TClassDefs; AIndex: Integer);
begin
inherited Create();
FClassDefs := nil;
FID := '';
FCID := 0;
SetLength(FFields, 0);
FMethods := TFunctions.Create();
if Assigned(AClassDefs) then
AClassDefs.Add(Self, AIndex);
end;
destructor TClassDef.Destroy();
begin
SetLength(FFields, 0);
FMethods.Free();
inherited;
end;
function TClassDef.Compile(AText: String): Boolean;
var
lItem, lType_, lID: String;
lExts: TType_Exts;
begin
SetLength(FFields, 0);
FMethods.Clear();
lItem := ReadItem(AText, ' ');
Result := lItem = STR_CLASSDEF;
if Result then
begin
lItem := '';
while AText <> '' do
if AText[1] = '(' then
Break
else
begin
lItem := lItem + AText[1];
Delete(AText, 1, 1);
end;
FID := Trim(ReadItem(lItem, ':'));
while lItem <> '' do
Trim(ReadItem(lItem, ',')); // parents
AText := Brackets(AText);
if AText <> '' then
begin
Result := False;
while AText <> '' do
begin
lItem := ReadItem(AText, ';');
if Pos('(', lItem) = 0 then
begin
SetLength(FFields, High(FFields) + 2);
Type_ID(lItem, lType_, lID);
lExts := [];
if lType_ <> '' then
while lType_[1] in Type_Exts do
begin
if lType_[1] = '$' then
lExts := lExts + [teGlobal]
else if lType_[1] = '@' then
lExts := lExts + [teRef];
Delete(lType_, 1, 1);
end;
FFields[High(FFields)].ID := lID;
FFields[High(FFields)].Type_ := Values.Type_(lType_);
FFields[High(FFields)].Exts := lExts;
end
else
with TFunction.Create(FMethods) do
if Compile(lItem) then
Result := True
else
begin
Free();
Result := False;
Break;
end;
end;
end;
end;
end;
function TClassDef.Method(const AID: TID;
const AArguments: TValues; AClass: TValue): TValue;
var
lMethod: TFunction;
begin
lMethod := FMethods.FunctionByID(AID);
if Assigned(lMethod) then
Result := lMethod.Run(AArguments, AClass)
else
Result := nil;
end;
{ TClassDefs }
{ private }
function TClassDefs.GetClassDef(Index: Integer): TClassDef;
begin
if (Index < 0) or (Index > High(FClassDefs)) then
Result := nil
else
Result := FClassDefs[Index];
end;
function TClassDefs.GetCount(): Integer;
begin
Result := High(FClassDefs) + 1;
end;
procedure TClassDefs.DoDefine(const AID: TID; AType_: TType_;
AExts: TType_Exts);
begin
if Assigned(FOnDefine) then
FOnDefine(AID, AType_, AExts);
end;
function TClassDefs.DoVariable(const AID: TID): TValue;
begin
if Assigned(FOnVariable) then
Result := FOnVariable(AID)
else
Result := nil;
end;
function TClassDefs.DoFunction(const AID: TID;
const AArguments: TValues; AClass: TValue): TValue;
begin
if Assigned(FOnFunction) then
Result := FOnFunction(AID, AArguments, AClass)
else
Result := nil;
end;
function TClassDefs.DoMethod(const AID: TID; const AArguments: TValues;
AClass: TValue): TValue;
begin
if Assigned(FOnMethod) then
Result := FOnMethod(AID, AArguments, AClass)
else
Result := nil;
end;
{ public }
constructor TClassDefs.Create();
begin
inherited Create();
SetLength(FClassDefs, 0);
FOnDefine := nil;
FOnVariable := nil;
FOnFunction := nil;
FOnMethod := nil;
end;
destructor TClassDefs.Destroy();
begin
Clear();
inherited;
end;
function TClassDefs.CreateCID(): TCID;
var
lCID: TCID;
I: Integer;
lFlag: Boolean;
begin
Result := 0;
lCID := 0;
while lCID < High(TCID) do
begin
lCID := lCID + 1;
lFlag := True;
for I := 0 to High(FClassDefs) do
if lCID = FClassDefs[I].CID then
begin
lFlag := False;
Break;
end;
if lFlag then
begin
Result := lCID;
Break;
end;
end;
end;
procedure TClassDefs.Add(AClassDef: TClassDef; AIndex: Integer);
var
I: Integer;
begin
if (AIndex < -1) or (AIndex > High(FClassDefs) + 1) then
Exit;
if IndexOf(AClassDef) > -1 then
Exit;
AClassDef.FCID := CreateCID();
SetLength(FClassDefs, High(FClassDefs) + 2);
if AIndex = -1 then
AIndex := High(FClassDefs)
else
for I := High(FClassDefs) downto AIndex + 1 do
FClassDefs[I] := FClassDefs[I - 1];
FClassDefs[AIndex] := AClassDef;
AClassDef.FClassDefs := Self;
AClassDef.Methods.OnDefine := DoDefine;
AClassDef.Methods.OnVariable := DoVariable;
AClassDef.Methods.OnFunction := DoFunction;
AClassDef.Methods.OnMethod := DoMethod;
end;
procedure TClassDefs.Delete(AIndex: Integer);
var
I: Integer;
begin
if (AIndex < 0) or (AIndex > High(FClassDefs)) then
Exit;
FClassDefs[AIndex].Free();
for I := AIndex to High(FClassDefs) - 1 do
FClassDefs[I] := FClassDefs[I + 1];
SetLength(FClassDefs, High(FClassDefs));
end;
procedure TClassDefs.Clear();
var
I: Integer;
begin
for I := 0 to High(FClassDefs) do
FClassDefs[I].Free();
SetLength(FClassDefs, 0);
end;
function TClassDefs.IndexOf(AClassDef: TClassDef): Integer;
var
I: Integer;
begin
Result := -1;
for I := 0 to High(FClassDefs) do
if AClassDef = FClassDefs[I] then
begin
Result := I;
Exit;
end;
end;
function TClassDefs.ClassDefByID(const AID: TID): TClassDef;
var
I: Integer;
begin
Result := nil;
for I := High(FClassDefs) downto 0 do
if AID = FClassDefs[I].ID then
begin
Result := FClassDefs[I];
Exit;
end;
end;
function TClassDefs.ClassDefByCID(ACID: TCID): TClassDef;
var
I: Integer;
begin
Result := nil;
for I := High(FClassDefs) downto 0 do
if ACID = FClassDefs[I].CID then
begin
Result := FClassDefs[I];
Exit;
end;
end;
end.
|
unit chrome_init;
{$mode objfpc}{$H+}
{$I vrode.inc}
interface
{.$DEFINE SELECT_CHROME_BIN}
uses {$IFNDEF VER3}LazUTF8,{$ENDIF}
Classes, SysUtils, LCLIntf,
vr_types, vr_utils, vr_classes,
{$IFDEF WINDOWS}vr_WinAPI,{$ENDIF}
uCEFApplication, chrome_common, chrome_browser;
function chrome_Start(ARenderClass: TCustomChromeRenderClass = nil): Boolean;
procedure chrome_Stop;
var
UrlChromeEmbedDownload: string;
implementation
var
_ChromeRender: TCustomChromeRender = nil;
function chrome_Start(ARenderClass: TCustomChromeRenderClass): Boolean;
var
sChromeBinDir: UnicodeString;
sChromeVer: string = '3.3538.1852';
sCurrDir: String;
{$IFDEF WINDOWS}
sChromePlatform: string = 'win32';{$ENDIF}
//Chromium called app with param --type=gpu-process
function _ValidParams: Boolean;
begin
Result := (ParamCount = 0) or
not sys_ParamExists('--type');
end;
function _IsValidChromeBinDir(const ADir: string): Boolean;
begin
Result := dir_Exists(ADir) and file_Exists(IncludeTrailingPathDelimiter(ADir) + 'libcef.dll');
end;
{$IFDEF SELECT_CHROME_BIN}
procedure _DownloadChromeBinDir(ASilent: Boolean);
var
sUrl: string;
begin
IniDeleteKey(MainIni, GS_COMMON, 'ChromeBinDir');
sUrl := 'http://vrodesoft.com/download';
if ASilent then
OpenURL(sUrl)
else
PromptDownload(Format('Chromium Embedded %s', [sChromeVer]), sUrl);
end;
function _GetChromeBinDir: Boolean;
var
ini: IFPIniCachedFile;
S, sInit, sSelect: String;
begin
Result := False;
ini := ini_GetCacheFile(MainIni);
sInit := {$IFDEF WINDOWS}'libcef.dll'{$ELSE}'libcef.so'{$ENDIF};
S := ini.ReadString(GS_COMMON, 'ChromeBinDir');
if not _IsValidChromeBinDir(S) then
begin
{$IFDEF WINDOWS}
S := GetProgramFilesPath + Format('VrodeSoft\Chromium Embedded\%s\%s', [sChromeVer, sChromePlatform]);
if not _IsValidChromeBinDir(S) then{$ENDIF}
begin
sSelect := Format('Select Chromium Embedded %s Folder (contain %s)', [sChromeVer, sInit]);
case MessageDlg('Chromium Embedded Not Installed',
'OK: Download from vrodesoft.com' + sLineBreak +
'No: ' + sSelect,
mtConfirmation, [mbOK, mbNo, mbCancel], 0) of
mrOk:
begin
_DownloadChromeBinDir(True);
Exit;
end;
mrNo:
begin
if not SelectFile(S, False, sInit, '', '', [], sSelect) then
Exit;
S := file_ExtractDir(S);
end;
else
Exit;
end;//case
end;
if not _IsValidChromeBinDir(S) then Exit;
ini.WriteString(GS_COMMON, 'ChromeBinDir', S);
ini.UpdateFile;
end;
sChromeBinDir := utf_8To16(S);
Result := True;
end;
{$ELSE}
procedure _ShowInvalidChrome(const ASilent: Boolean = False);
var
S: String;
begin
//ShowError('Invalid Chromium Embedded. '+sLineBreak+'Reinstall Vrode Sheet Music.');
//IniDeleteKey(MainIni, GS_COMMON, 'ChromeBinDir');
//sUrl := 'http://vrodesoft.com/download';
S := 'Invalid Chromium Embedded.' + sLineBreak;
if UrlChromeEmbedDownload = '' then
begin
ShowErrorFmt(S + 'Reinstall "%s".', [ApplicationName]);
end
else if ASilent or
ShowConfirmFmt(S + RS_QUEST_DOWNLOAD, [UrlChromeEmbedDownload]) then
OpenURL(UrlChromeEmbedDownload);
//PromptDownload(Format('Chromium Embedded %s', [sChromeVer]), UrlChromeEmbedDownload);
end;
function _GetChromeBinDir: Boolean;
var
S: String;
begin
Result := False;
{$IFDEF WINDOWS}
S := GetProgramFilesPath + Format('VrodeSoft\Chromium Embedded\%s\%s', [sChromeVer, sChromePlatform]);
{$ELSE}
S := AppPath + Format('Chromium Embedded\%s\%s', [sChromeVer, sChromePlatform]);
{$ENDIF}
if not _IsValidChromeBinDir(S) then Exit;
sChromeBinDir := utf_8To16(S);
Result := True;
end;
{$ENDIF}
function _WaitChrome: Boolean;
var
iTicks: QWord;
//sWaitFile: String;
begin
Result := False;
iTicks := GetTickCount;
//if _ValidParams then
// ShowInfo(ParamStrUTF8(1));
//sWaitFile := CommonAppsDataAppPath + 'vrsheetwait.d';
if sys_ParamExists('/wait-chrome') {or file_Exists(sWaitFile)} then
begin
//file_Delete(sWaitFile);
iTicks += 60000;
end;
repeat
Result := _GetChromeBinDir;
if Result then Exit;
Sleep(1000);
until (GetTickCount > iTicks);
end;
begin
Result := False;
if CompareWindowsVersion(WIN_VER_7) < 0 then
begin
ShowError('Windows 7 or higher is only supported');
Exit;
end;
ParamValueDelim := '=';
sCurrDir := file_ExtractDir(ParamStrUTF8(0));
if not dir_SameName(dir_GetCurrent, sCurrDir) then
dir_SetCurrent(sCurrDir); //Chrome create blob_storage folder in current dir
//{$IFDEF TEST_MODE}
//sChromeBinDir := 'D:\pf\ChromiumEmbed\3.3440.1806\win32';{$ELSE}
//.{//ToDo}{$ENDIF}
if not _WaitChrome then
begin
{$IFNDEF SELECT_CHROME_BIN}
_ShowInvalidChrome;{$ENDIF}
//_DownloadChromeBinDir;
Exit;
end;
try
GlobalCEFApp := TCefApplication.Create;
if Assigned(OnAfterGlobalCEFAppCreate) then
OnAfterGlobalCEFAppCreate;
if ARenderClass = nil then
ARenderClass := TCustomChromeRender;
_ChromeRender := ARenderClass.Create;
//{$IFDEF TEST_MODE}GlobalCEFApp.SingleProcess := True;{$ENDIF} //only for debug render process
GlobalCEFApp.FrameworkDirPath := sChromeBinDir{%H-};
GlobalCEFApp.ResourcesDirPath := sChromeBinDir;
GlobalCEFApp.LocalesDirPath := sChromeBinDir + '\locales';
if GlobalCEFApp.StartMainProcess then
begin
Result := True;
ChromeInitialized := True;
end
else if _ValidParams then{$IFDEF SELECT_CHROME_BIN}
_DownloadChromeBinDir(False){$ELSE}
_ShowInvalidChrome
{$ENDIF};
finally
//if not Result then
// chrome_Stop;
end;
end;
procedure chrome_Stop;
begin
//? Remove
end;
procedure _chrome_Stop;
begin
FreeAndNil(_ChromeRender);
ChromeInitialized := False;
DestroyGlobalCEFApp;
end;
finalization
_chrome_Stop;//FreeAndNil(_ChromeRender);
end.
|
unit uFrmMsgBox;
interface
uses
Windows, Controls, StdCtrls, ExtCtrls, Classes, Forms, pngimage,
cxGraphics,
cxLookAndFeels, cxLookAndFeelPainters, Menus, cxButtons;
type
TFrmMsgBox = class(TForm)
pnlClient: TPanel;
img1: TImage;
lblText: TLabel;
pnlBottom: TPanel;
btnOk: TcxButton;
btnCancel: TcxButton;
bvl1: TBevel;
private
procedure LoadIcon(AFlag: Integer);
procedure LoadResStream(AImg: TImage; const ResName: string);
procedure InitMsgForm(const AText, ACaption: string; AFlag: Integer);
public
class function ShowDialogForm(const AText, ACaption: string;
AFlag: Integer): Boolean;
end;
var
FrmMsgBox: TFrmMsgBox;
implementation
{$R *.dfm}
{ TFrmMsg }
procedure TFrmMsgBox.LoadResStream(AImg: TImage; const ResName: string);
var
ResStream: TResourceStream;
png: TPNGObject;
begin
ResStream := TResourceStream.Create(HInstance, ResName, RT_RCDATA);
png := TPNGObject.Create;
try
ResStream.Position := 0;
png.LoadFromStream(ResStream);
AImg.Picture.Assign(png);
finally
png.Free;
ResStream.Free;
end;
end;
procedure TFrmMsgBox.LoadIcon(AFlag: Integer);
var
lResName: string;
begin
case AFlag of
16: lResName := 'ERROR';
33: lResName := 'QUESTION';
48: lResName := 'WARNING';
64: lResName := 'INFORMATION';
70: lResName := 'SUCCESS';
else
lResName := 'INFORMATION';
end;
LoadResStream(img1, lResName);
end;
procedure TFrmMsgBox.InitMsgForm(const AText, ACaption: string; AFlag: Integer);
begin
Self.Caption := ACaption;
lblText.Caption := AText;
if not (AFlag in [33]) then
begin
btnCancel.Visible := False;
btnOk.Left := btnCancel.Left;
end;
LoadIcon(AFlag);
end;
class function TFrmMsgBox.ShowDialogForm(const AText, ACaption: string;
AFlag: Integer): Boolean;
var
lForm: TFrmMsgBox;
lMsgEvent: TMessageEvent;
begin
lForm := TFrmMsgBox.Create(nil);
lMsgEvent := Application.OnMessage;
try
Application.OnMessage := nil;
lForm.InitMsgForm(AText, ACaption, AFlag);
Result := lForm.ShowModal = mrOk;
finally
Application.OnMessage := lMsgEvent;
lForm.Free;
end;
end;
end.
|
unit Financials_MutualFund_s;
{This file was generated on 11 Aug 2000 20:14:44 GMT by version 03.03.03.C1.06}
{of the Inprise VisiBroker idl2pas CORBA IDL compiler. }
{Please do not edit the contents of this file. You should instead edit and }
{recompile the original IDL which was located in the file account.idl. }
{Delphi Pascal unit : Financials_MutualFund_s }
{derived from IDL module : MutualFund }
interface
uses
CORBA,
Financials_MutualFund_i,
Financials_MutualFund_c;
type
TAssetSkeleton = class;
TAssetSkeleton = class(CORBA.TCorbaObject, Financials_MutualFund_i.Asset)
private
FImplementation : Asset;
public
constructor Create(const InstanceName: string; const Impl: Asset);
destructor Destroy; override;
function GetImplementation : Asset;
function nav : Single;
published
procedure _nav(const _Input: CORBA.InputStream; _Cookie: Pointer);
end;
implementation
constructor TAssetSkeleton.Create(const InstanceName : string; const Impl : Financials_MutualFund_i.Asset);
begin
inherited;
inherited CreateSkeleton(InstanceName, 'Asset', 'IDL:Financials/MutualFund/Asset:1.0');
FImplementation := Impl;
end;
destructor TAssetSkeleton.Destroy;
begin
FImplementation := nil;
inherited;
end;
function TAssetSkeleton.GetImplementation : Financials_MutualFund_i.Asset;
begin
result := FImplementation as Financials_MutualFund_i.Asset;
end;
function TAssetSkeleton.nav : Single;
begin
Result := FImplementation.nav;
end;
procedure TAssetSkeleton._nav(const _Input: CORBA.InputStream; _Cookie: Pointer);
var
_Output : CORBA.OutputStream;
_Result : Single;
begin
_Result := nav;
GetReplyBuffer(_Cookie, _Output);
_Output.WriteFloat(_Result);
end;
initialization
end. |
unit testrcondunit;
interface
uses Math, Sysutils, Ap, reflections, creflections, hqrnd, matgen, ablasf, ablas, trfac, trlinsolve, safesolve, rcond;
function TestRCond(Silent : Boolean):Boolean;
function testrcondunit_test_silent():Boolean;
function testrcondunit_test():Boolean;
implementation
const
Threshold50 = 0.25;
Threshold90 = 0.10;
procedure RMatrixMakeACopy(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var B : TReal2DArray);forward;
procedure RMatrixDropHalf(var A : TReal2DArray;
N : AlglibInteger;
DropLower : Boolean);forward;
procedure CMatrixDropHalf(var A : TComplex2DArray;
N : AlglibInteger;
DropLower : Boolean);forward;
procedure RMatrixGenZero(var A0 : TReal2DArray; N : AlglibInteger);forward;
function RMatrixInvMatTR(var A : TReal2DArray;
N : AlglibInteger;
IsUpper : Boolean;
IsunitTriangular : Boolean):Boolean;forward;
function RMatrixInvMatLU(var A : TReal2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Boolean;forward;
function RMatrixInvMat(var A : TReal2DArray;
N : AlglibInteger):Boolean;forward;
procedure RMatrixRefRCond(const A : TReal2DArray;
N : AlglibInteger;
var RC1 : Double;
var RCInf : Double);forward;
procedure CMatrixMakeACopy(const A : TComplex2DArray;
M : AlglibInteger;
N : AlglibInteger;
var B : TComplex2DArray);forward;
procedure CMatrixGenZero(var A0 : TComplex2DArray; N : AlglibInteger);forward;
function CMatrixInvMatTR(var A : TComplex2DArray;
N : AlglibInteger;
IsUpper : Boolean;
IsunitTriangular : Boolean):Boolean;forward;
function CMatrixInvMatLU(var A : TComplex2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Boolean;forward;
function CMatrixInvMat(var A : TComplex2DArray;
N : AlglibInteger):Boolean;forward;
procedure CMatrixRefRCond(const A : TComplex2DArray;
N : AlglibInteger;
var RC1 : Double;
var RCInf : Double);forward;
function TestRMatrixTRRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;forward;
function TestCMatrixTRRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;forward;
function TestRMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;forward;
function TestSPDMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;forward;
function TestCMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;forward;
function TestHPDMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;forward;
function TestRCond(Silent : Boolean):Boolean;
var
MaxN : AlglibInteger;
PassCount : AlglibInteger;
WasErrors : Boolean;
RTRErr : Boolean;
CTRErr : Boolean;
RErr : Boolean;
CErr : Boolean;
SPDErr : Boolean;
HPDErr : Boolean;
begin
MaxN := 10;
PassCount := 100;
//
// report
//
RTRErr := not TestRMatrixTRRCond(MaxN, PassCount);
CTRErr := not TestCMatrixTRRCond(MaxN, PassCount);
RErr := not TestRMatrixRCond(MaxN, PassCount);
CErr := not TestCMatrixRCond(MaxN, PassCount);
SPDErr := not TestSPDMatrixRCond(MaxN, PassCount);
HPDErr := not TestHPDMatrixRCond(MaxN, PassCount);
WasErrors := RTRErr or CTRErr or RErr or CErr or SPDErr or HPDErr;
if not Silent then
begin
Write(Format('TESTING RCOND'#13#10'',[]));
Write(Format('REAL TRIANGULAR: ',[]));
if not RTRErr then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('COMPLEX TRIANGULAR: ',[]));
if not CTRErr then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('REAL: ',[]));
if not RErr then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('SPD: ',[]));
if not SPDErr then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('HPD: ',[]));
if not HPDErr then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
Write(Format('COMPLEX: ',[]));
if not CErr then
begin
Write(Format('OK'#13#10'',[]));
end
else
begin
Write(Format('FAILED'#13#10'',[]));
end;
if WasErrors then
begin
Write(Format('TEST FAILED'#13#10'',[]));
end
else
begin
Write(Format('TEST PASSED'#13#10'',[]));
end;
Write(Format(''#13#10''#13#10'',[]));
end;
Result := not WasErrors;
end;
(*************************************************************************
Copy
*************************************************************************)
procedure RMatrixMakeACopy(const A : TReal2DArray;
M : AlglibInteger;
N : AlglibInteger;
var B : TReal2DArray);
var
I : AlglibInteger;
J : AlglibInteger;
begin
SetLength(B, M-1+1, N-1+1);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
B[I,J] := A[I,J];
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
Drops upper or lower half of the matrix - fills it by special pattern
which may be used later to ensure that this part wasn't changed
*************************************************************************)
procedure RMatrixDropHalf(var A : TReal2DArray;
N : AlglibInteger;
DropLower : Boolean);
var
I : AlglibInteger;
J : AlglibInteger;
begin
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
if DropLower and (I>J) or not DropLower and (I<J) then
begin
A[I,J] := 1+2*I+3*J;
end;
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
Drops upper or lower half of the matrix - fills it by special pattern
which may be used later to ensure that this part wasn't changed
*************************************************************************)
procedure CMatrixDropHalf(var A : TComplex2DArray;
N : AlglibInteger;
DropLower : Boolean);
var
I : AlglibInteger;
J : AlglibInteger;
begin
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
if DropLower and (I>J) or not DropLower and (I<J) then
begin
A[I,J] := C_Complex(1+2*I+3*J);
end;
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
Generate matrix with given condition number C (2-norm)
*************************************************************************)
procedure RMatrixGenZero(var A0 : TReal2DArray; N : AlglibInteger);
var
I : AlglibInteger;
J : AlglibInteger;
begin
SetLength(A0, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A0[I,J] := 0;
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
triangular inverse
*************************************************************************)
function RMatrixInvMatTR(var A : TReal2DArray;
N : AlglibInteger;
IsUpper : Boolean;
IsunitTriangular : Boolean):Boolean;
var
NOunit : Boolean;
I : AlglibInteger;
J : AlglibInteger;
V : Double;
AJJ : Double;
T : TReal1DArray;
i_ : AlglibInteger;
begin
Result := True;
SetLength(T, N-1+1);
//
// Test the input parameters.
//
NOunit := not IsunitTriangular;
if IsUpper then
begin
//
// Compute inverse of upper triangular matrix.
//
J:=0;
while J<=N-1 do
begin
if NOunit then
begin
if AP_FP_Eq(A[J,J],0) then
begin
Result := False;
Exit;
end;
A[J,J] := 1/A[J,J];
AJJ := -A[J,J];
end
else
begin
AJJ := -1;
end;
//
// Compute elements 1:j-1 of j-th column.
//
if J>0 then
begin
for i_ := 0 to J-1 do
begin
T[i_] := A[i_,J];
end;
I:=0;
while I<=J-1 do
begin
if I<J-1 then
begin
V := APVDotProduct(@A[I][0], I+1, J-1, @T[0], I+1, J-1);
end
else
begin
V := 0;
end;
if NOunit then
begin
A[I,J] := V+A[I,I]*T[I];
end
else
begin
A[I,J] := V+T[I];
end;
Inc(I);
end;
for i_ := 0 to J-1 do
begin
A[i_,J] := AJJ*A[i_,J];
end;
end;
Inc(J);
end;
end
else
begin
//
// Compute inverse of lower triangular matrix.
//
J:=N-1;
while J>=0 do
begin
if NOunit then
begin
if AP_FP_Eq(A[J,J],0) then
begin
Result := False;
Exit;
end;
A[J,J] := 1/A[J,J];
AJJ := -A[J,J];
end
else
begin
AJJ := -1;
end;
if J<N-1 then
begin
//
// Compute elements j+1:n of j-th column.
//
for i_ := J+1 to N-1 do
begin
T[i_] := A[i_,J];
end;
I:=J+1;
while I<=N-1 do
begin
if I>J+1 then
begin
V := APVDotProduct(@A[I][0], J+1, I-1, @T[0], J+1, I-1);
end
else
begin
V := 0;
end;
if NOunit then
begin
A[I,J] := V+A[I,I]*T[I];
end
else
begin
A[I,J] := V+T[I];
end;
Inc(I);
end;
for i_ := J+1 to N-1 do
begin
A[i_,J] := AJJ*A[i_,J];
end;
end;
Dec(J);
end;
end;
end;
(*************************************************************************
LU inverse
*************************************************************************)
function RMatrixInvMatLU(var A : TReal2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Boolean;
var
WORK : TReal1DArray;
I : AlglibInteger;
IWS : AlglibInteger;
J : AlglibInteger;
JB : AlglibInteger;
JJ : AlglibInteger;
JP : AlglibInteger;
V : Double;
i_ : AlglibInteger;
begin
Result := True;
//
// Quick return if possible
//
if N=0 then
begin
Exit;
end;
SetLength(WORK, N-1+1);
//
// Form inv(U)
//
if not RMatrixInvMatTR(A, N, True, False) then
begin
Result := False;
Exit;
end;
//
// Solve the equation inv(A)*L = inv(U) for inv(A).
//
J:=N-1;
while J>=0 do
begin
//
// Copy current column of L to WORK and replace with zeros.
//
I:=J+1;
while I<=N-1 do
begin
WORK[I] := A[I,J];
A[I,J] := 0;
Inc(I);
end;
//
// Compute current column of inv(A).
//
if J<N-1 then
begin
I:=0;
while I<=N-1 do
begin
V := APVDotProduct(@A[I][0], J+1, N-1, @WORK[0], J+1, N-1);
A[I,J] := A[I,J]-V;
Inc(I);
end;
end;
Dec(J);
end;
//
// Apply column interchanges.
//
J:=N-2;
while J>=0 do
begin
JP := Pivots[J];
if JP<>J then
begin
for i_ := 0 to N-1 do
begin
WORK[i_] := A[i_,J];
end;
for i_ := 0 to N-1 do
begin
A[i_,J] := A[i_,JP];
end;
for i_ := 0 to N-1 do
begin
A[i_,JP] := WORK[i_];
end;
end;
Dec(J);
end;
end;
(*************************************************************************
Matrix inverse
*************************************************************************)
function RMatrixInvMat(var A : TReal2DArray; N : AlglibInteger):Boolean;
var
Pivots : TInteger1DArray;
begin
RMatrixLU(A, N, N, Pivots);
Result := RMatrixInvMatLU(A, Pivots, N);
end;
(*************************************************************************
reference RCond
*************************************************************************)
procedure RMatrixRefRCond(const A : TReal2DArray;
N : AlglibInteger;
var RC1 : Double;
var RCInf : Double);
var
InvA : TReal2DArray;
Nrm1A : Double;
NrmInfA : Double;
Nrm1InvA : Double;
NrmInfInvA : Double;
V : Double;
K : AlglibInteger;
I : AlglibInteger;
begin
//
// inv A
//
RMatrixMakeACopy(A, N, N, InvA);
if not RMatrixInvMat(InvA, N) then
begin
RC1 := 0;
RCInf := 0;
Exit;
end;
//
// norm A
//
Nrm1A := 0;
NrmInfA := 0;
K:=0;
while K<=N-1 do
begin
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsReal(A[I,K]);
Inc(I);
end;
Nrm1A := Max(Nrm1A, V);
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsReal(A[K,I]);
Inc(I);
end;
NrmInfA := Max(NrmInfA, V);
Inc(K);
end;
//
// norm inv A
//
Nrm1InvA := 0;
NrmInfInvA := 0;
K:=0;
while K<=N-1 do
begin
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsReal(InvA[I,K]);
Inc(I);
end;
Nrm1InvA := Max(Nrm1InvA, V);
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsReal(InvA[K,I]);
Inc(I);
end;
NrmInfInvA := Max(NrmInfInvA, V);
Inc(K);
end;
//
// result
//
RC1 := Nrm1InvA*Nrm1A;
RCInf := NrmInfInvA*NrmInfA;
end;
(*************************************************************************
Copy
*************************************************************************)
procedure CMatrixMakeACopy(const A : TComplex2DArray;
M : AlglibInteger;
N : AlglibInteger;
var B : TComplex2DArray);
var
I : AlglibInteger;
J : AlglibInteger;
begin
SetLength(B, M-1+1, N-1+1);
I:=0;
while I<=M-1 do
begin
J:=0;
while J<=N-1 do
begin
B[I,J] := A[I,J];
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
Generate matrix with given condition number C (2-norm)
*************************************************************************)
procedure CMatrixGenZero(var A0 : TComplex2DArray; N : AlglibInteger);
var
I : AlglibInteger;
J : AlglibInteger;
begin
SetLength(A0, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A0[I,J] := C_Complex(0);
Inc(J);
end;
Inc(I);
end;
end;
(*************************************************************************
triangular inverse
*************************************************************************)
function CMatrixInvMatTR(var A : TComplex2DArray;
N : AlglibInteger;
IsUpper : Boolean;
IsunitTriangular : Boolean):Boolean;
var
NOunit : Boolean;
I : AlglibInteger;
J : AlglibInteger;
V : Complex;
AJJ : Complex;
T : TComplex1DArray;
i_ : AlglibInteger;
begin
Result := True;
SetLength(T, N-1+1);
//
// Test the input parameters.
//
NOunit := not IsunitTriangular;
if IsUpper then
begin
//
// Compute inverse of upper triangular matrix.
//
J:=0;
while J<=N-1 do
begin
if NOunit then
begin
if C_EqualR(A[J,J],0) then
begin
Result := False;
Exit;
end;
A[J,J] := C_RDiv(1,A[J,J]);
AJJ := C_Opposite(A[J,J]);
end
else
begin
AJJ := C_Complex(-1);
end;
//
// Compute elements 1:j-1 of j-th column.
//
if J>0 then
begin
for i_ := 0 to J-1 do
begin
T[i_] := A[i_,J];
end;
I:=0;
while I<=J-1 do
begin
if I<J-1 then
begin
V := C_Complex(0.0);
for i_ := I+1 to J-1 do
begin
V := C_Add(V,C_Mul(A[I,i_],T[i_]));
end;
end
else
begin
V := C_Complex(0);
end;
if NOunit then
begin
A[I,J] := C_Add(V,C_Mul(A[I,I],T[I]));
end
else
begin
A[I,J] := C_Add(V,T[I]);
end;
Inc(I);
end;
for i_ := 0 to J-1 do
begin
A[i_,J] := C_Mul(AJJ, A[i_,J]);
end;
end;
Inc(J);
end;
end
else
begin
//
// Compute inverse of lower triangular matrix.
//
J:=N-1;
while J>=0 do
begin
if NOunit then
begin
if C_EqualR(A[J,J],0) then
begin
Result := False;
Exit;
end;
A[J,J] := C_RDiv(1,A[J,J]);
AJJ := C_Opposite(A[J,J]);
end
else
begin
AJJ := C_Complex(-1);
end;
if J<N-1 then
begin
//
// Compute elements j+1:n of j-th column.
//
for i_ := J+1 to N-1 do
begin
T[i_] := A[i_,J];
end;
I:=J+1;
while I<=N-1 do
begin
if I>J+1 then
begin
V := C_Complex(0.0);
for i_ := J+1 to I-1 do
begin
V := C_Add(V,C_Mul(A[I,i_],T[i_]));
end;
end
else
begin
V := C_Complex(0);
end;
if NOunit then
begin
A[I,J] := C_Add(V,C_Mul(A[I,I],T[I]));
end
else
begin
A[I,J] := C_Add(V,T[I]);
end;
Inc(I);
end;
for i_ := J+1 to N-1 do
begin
A[i_,J] := C_Mul(AJJ, A[i_,J]);
end;
end;
Dec(J);
end;
end;
end;
(*************************************************************************
LU inverse
*************************************************************************)
function CMatrixInvMatLU(var A : TComplex2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Boolean;
var
WORK : TComplex1DArray;
I : AlglibInteger;
IWS : AlglibInteger;
J : AlglibInteger;
JB : AlglibInteger;
JJ : AlglibInteger;
JP : AlglibInteger;
V : Complex;
i_ : AlglibInteger;
begin
Result := True;
//
// Quick return if possible
//
if N=0 then
begin
Exit;
end;
SetLength(WORK, N-1+1);
//
// Form inv(U)
//
if not CMatrixInvMatTR(A, N, True, False) then
begin
Result := False;
Exit;
end;
//
// Solve the equation inv(A)*L = inv(U) for inv(A).
//
J:=N-1;
while J>=0 do
begin
//
// Copy current column of L to WORK and replace with zeros.
//
I:=J+1;
while I<=N-1 do
begin
WORK[I] := A[I,J];
A[I,J] := C_Complex(0);
Inc(I);
end;
//
// Compute current column of inv(A).
//
if J<N-1 then
begin
I:=0;
while I<=N-1 do
begin
V := C_Complex(0.0);
for i_ := J+1 to N-1 do
begin
V := C_Add(V,C_Mul(A[I,i_],WORK[i_]));
end;
A[I,J] := C_Sub(A[I,J],V);
Inc(I);
end;
end;
Dec(J);
end;
//
// Apply column interchanges.
//
J:=N-2;
while J>=0 do
begin
JP := Pivots[J];
if JP<>J then
begin
for i_ := 0 to N-1 do
begin
WORK[i_] := A[i_,J];
end;
for i_ := 0 to N-1 do
begin
A[i_,J] := A[i_,JP];
end;
for i_ := 0 to N-1 do
begin
A[i_,JP] := WORK[i_];
end;
end;
Dec(J);
end;
end;
(*************************************************************************
Matrix inverse
*************************************************************************)
function CMatrixInvMat(var A : TComplex2DArray; N : AlglibInteger):Boolean;
var
Pivots : TInteger1DArray;
begin
CMatrixLU(A, N, N, Pivots);
Result := CMatrixInvMatLU(A, Pivots, N);
end;
(*************************************************************************
reference RCond
*************************************************************************)
procedure CMatrixRefRCond(const A : TComplex2DArray;
N : AlglibInteger;
var RC1 : Double;
var RCInf : Double);
var
InvA : TComplex2DArray;
Nrm1A : Double;
NrmInfA : Double;
Nrm1InvA : Double;
NrmInfInvA : Double;
V : Double;
K : AlglibInteger;
I : AlglibInteger;
begin
//
// inv A
//
CMatrixMakeACopy(A, N, N, InvA);
if not CMatrixInvMat(InvA, N) then
begin
RC1 := 0;
RCInf := 0;
Exit;
end;
//
// norm A
//
Nrm1A := 0;
NrmInfA := 0;
K:=0;
while K<=N-1 do
begin
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsComplex(A[I,K]);
Inc(I);
end;
Nrm1A := Max(Nrm1A, V);
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsComplex(A[K,I]);
Inc(I);
end;
NrmInfA := Max(NrmInfA, V);
Inc(K);
end;
//
// norm inv A
//
Nrm1InvA := 0;
NrmInfInvA := 0;
K:=0;
while K<=N-1 do
begin
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsComplex(InvA[I,K]);
Inc(I);
end;
Nrm1InvA := Max(Nrm1InvA, V);
V := 0;
I:=0;
while I<=N-1 do
begin
V := V+AbsComplex(InvA[K,I]);
Inc(I);
end;
NrmInfInvA := Max(NrmInfInvA, V);
Inc(K);
end;
//
// result
//
RC1 := Nrm1InvA*Nrm1A;
RCInf := NrmInfInvA*NrmInfA;
end;
(*************************************************************************
Returns True for successful test, False - for failed test
*************************************************************************)
function TestRMatrixTRRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;
var
A : TReal2DArray;
EA : TReal2DArray;
P : TInteger1DArray;
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
J1 : AlglibInteger;
J2 : AlglibInteger;
Pass : AlglibInteger;
Err50 : Boolean;
Err90 : Boolean;
ErrSpec : Boolean;
ErrLess : Boolean;
ERC1 : Double;
ERCInf : Double;
Q50 : TReal1DArray;
Q90 : TReal1DArray;
V : Double;
IsUpper : Boolean;
IsUnit : Boolean;
begin
Err50 := False;
Err90 := False;
ErrLess := False;
ErrSpec := False;
SetLength(Q50, 2);
SetLength(Q90, 2);
N:=1;
while N<=MaxN do
begin
//
// special test for zero matrix
//
RMatrixGenZero(A, N);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixTRRCond1(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixTRRCondInf(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
//
// general test
//
SetLength(A, N, N);
I:=0;
while I<=1 do
begin
Q50[I] := 0;
Q90[I] := 0;
Inc(I);
end;
Pass:=1;
while Pass<=PassCount do
begin
IsUpper := AP_FP_Greater(RandomReal,0.5);
IsUnit := AP_FP_Greater(RandomReal,0.5);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := RandomReal-0.5;
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := 1+RandomReal;
Inc(I);
end;
RMatrixMakeACopy(A, N, N, EA);
I:=0;
while I<=N-1 do
begin
if IsUpper then
begin
J1 := 0;
J2 := I-1;
end
else
begin
J1 := I+1;
J2 := N-1;
end;
J:=J1;
while J<=J2 do
begin
EA[I,J] := 0;
Inc(J);
end;
if IsUnit then
begin
EA[I,I] := 1;
end;
Inc(I);
end;
RMatrixRefRCond(EA, N, ERC1, ERCInf);
//
// 1-norm
//
V := 1/RMatrixTRRCond1(A, N, IsUpper, IsUnit);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[0] := Q50[0]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[0] := Q90[0]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// Inf-norm
//
V := 1/RMatrixTRRCondInf(A, N, IsUpper, IsUnit);
if AP_FP_Greater_Eq(V,Threshold50*ERCInf) then
begin
Q50[1] := Q50[1]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERCInf) then
begin
Q90[1] := Q90[1]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERCInf*1.001);
Inc(Pass);
end;
I:=0;
while I<=1 do
begin
Err50 := Err50 or AP_FP_Less(Q50[I],0.50);
Err90 := Err90 or AP_FP_Less(Q90[I],0.90);
Inc(I);
end;
//
// degenerate matrix test
//
if N>=3 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 0.0;
Inc(J);
end;
Inc(I);
end;
A[0,0] := 1;
A[N-1,N-1] := 1;
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixTRRCond1(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixTRRCondInf(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
end;
//
// near-degenerate matrix test
//
if N>=2 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 0.0;
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := 1;
Inc(I);
end;
I := RandomInteger(N);
A[I,I] := 0.1*MaxRealNumber;
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixTRRCond1(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixTRRCondInf(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
end;
Inc(N);
end;
//
// report
//
Result := not (Err50 or Err90 or ErrLess or ErrSpec);
end;
(*************************************************************************
Returns True for successful test, False - for failed test
*************************************************************************)
function TestCMatrixTRRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;
var
A : TComplex2DArray;
EA : TComplex2DArray;
P : TInteger1DArray;
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
J1 : AlglibInteger;
J2 : AlglibInteger;
Pass : AlglibInteger;
Err50 : Boolean;
Err90 : Boolean;
ErrSpec : Boolean;
ErrLess : Boolean;
ERC1 : Double;
ERCInf : Double;
Q50 : TReal1DArray;
Q90 : TReal1DArray;
V : Double;
IsUpper : Boolean;
IsUnit : Boolean;
begin
Err50 := False;
Err90 := False;
ErrLess := False;
ErrSpec := False;
SetLength(Q50, 2);
SetLength(Q90, 2);
N:=1;
while N<=MaxN do
begin
//
// special test for zero matrix
//
CMatrixGenZero(A, N);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixTRRCond1(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixTRRCondInf(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
//
// general test
//
SetLength(A, N, N);
I:=0;
while I<=1 do
begin
Q50[I] := 0;
Q90[I] := 0;
Inc(I);
end;
Pass:=1;
while Pass<=PassCount do
begin
IsUpper := AP_FP_Greater(RandomReal,0.5);
IsUnit := AP_FP_Greater(RandomReal,0.5);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J].X := RandomReal-0.5;
A[I,J].Y := RandomReal-0.5;
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I].X := 1+RandomReal;
A[I,I].Y := 1+RandomReal;
Inc(I);
end;
CMatrixMakeACopy(A, N, N, EA);
I:=0;
while I<=N-1 do
begin
if IsUpper then
begin
J1 := 0;
J2 := I-1;
end
else
begin
J1 := I+1;
J2 := N-1;
end;
J:=J1;
while J<=J2 do
begin
EA[I,J] := C_Complex(0);
Inc(J);
end;
if IsUnit then
begin
EA[I,I] := C_Complex(1);
end;
Inc(I);
end;
CMatrixRefRCond(EA, N, ERC1, ERCInf);
//
// 1-norm
//
V := 1/CMatrixTRRCond1(A, N, IsUpper, IsUnit);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[0] := Q50[0]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[0] := Q90[0]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// Inf-norm
//
V := 1/CMatrixTRRCondInf(A, N, IsUpper, IsUnit);
if AP_FP_Greater_Eq(V,Threshold50*ERCInf) then
begin
Q50[1] := Q50[1]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERCInf) then
begin
Q90[1] := Q90[1]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERCInf*1.001);
Inc(Pass);
end;
I:=0;
while I<=1 do
begin
Err50 := Err50 or AP_FP_Less(Q50[I],0.50);
Err90 := Err90 or AP_FP_Less(Q90[I],0.90);
Inc(I);
end;
//
// degenerate matrix test
//
if N>=3 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := C_Complex(0.0);
Inc(J);
end;
Inc(I);
end;
A[0,0] := C_Complex(1);
A[N-1,N-1] := C_Complex(1);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixTRRCond1(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixTRRCondInf(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
end;
//
// near-degenerate matrix test
//
if N>=2 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := C_Complex(0.0);
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := C_Complex(1);
Inc(I);
end;
I := RandomInteger(N);
A[I,I] := C_Complex(0.1*MaxRealNumber);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixTRRCond1(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixTRRCondInf(A, N, AP_FP_Greater(RandomReal,0.5), False),0);
end;
Inc(N);
end;
//
// report
//
Result := not (Err50 or Err90 or ErrLess or ErrSpec);
end;
(*************************************************************************
Returns True for successful test, False - for failed test
*************************************************************************)
function TestRMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;
var
A : TReal2DArray;
LUA : TReal2DArray;
P : TInteger1DArray;
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
Err50 : Boolean;
Err90 : Boolean;
ErrSpec : Boolean;
ErrLess : Boolean;
ERC1 : Double;
ERCInf : Double;
Q50 : TReal1DArray;
Q90 : TReal1DArray;
V : Double;
begin
Err50 := False;
Err90 := False;
ErrLess := False;
ErrSpec := False;
SetLength(Q50, 3+1);
SetLength(Q90, 3+1);
N:=1;
while N<=MaxN do
begin
//
// special test for zero matrix
//
RMatrixGenZero(A, N);
RMatrixMakeACopy(A, N, N, LUA);
RMatrixLU(LUA, N, N, P);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixRCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixRCondInf(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixLURCond1(LUA, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixLURCondInf(LUA, N),0);
//
// general test
//
SetLength(A, N-1+1, N-1+1);
I:=0;
while I<=3 do
begin
Q50[I] := 0;
Q90[I] := 0;
Inc(I);
end;
Pass:=1;
while Pass<=PassCount do
begin
RMatrixRndCond(N, Exp(RandomReal*Ln(1000)), A);
RMatrixMakeACopy(A, N, N, LUA);
RMatrixLU(LUA, N, N, P);
RMatrixRefRCond(A, N, ERC1, ERCInf);
//
// 1-norm, normal
//
V := 1/RMatrixRCond1(A, N);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[0] := Q50[0]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[0] := Q90[0]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// 1-norm, LU
//
V := 1/RMatrixLURCond1(LUA, N);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[1] := Q50[1]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[1] := Q90[1]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// Inf-norm, normal
//
V := 1/RMatrixRCondInf(A, N);
if AP_FP_Greater_Eq(V,Threshold50*ERCInf) then
begin
Q50[2] := Q50[2]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERCInf) then
begin
Q90[2] := Q90[2]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERCInf*1.001);
//
// Inf-norm, LU
//
V := 1/RMatrixLURCondInf(LUA, N);
if AP_FP_Greater_Eq(V,Threshold50*ERCInf) then
begin
Q50[3] := Q50[3]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERCInf) then
begin
Q90[3] := Q90[3]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERCInf*1.001);
Inc(Pass);
end;
I:=0;
while I<=3 do
begin
Err50 := Err50 or AP_FP_Less(Q50[I],0.50);
Err90 := Err90 or AP_FP_Less(Q90[I],0.90);
Inc(I);
end;
//
// degenerate matrix test
//
if N>=3 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 0.0;
Inc(J);
end;
Inc(I);
end;
A[0,0] := 1;
A[N-1,N-1] := 1;
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixRCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixRCondInf(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixLURCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixLURCondInf(A, N),0);
end;
//
// near-degenerate matrix test
//
if N>=2 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 0.0;
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := 1;
Inc(I);
end;
I := RandomInteger(N);
A[I,I] := 0.1*MaxRealNumber;
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixRCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixRCondInf(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixLURCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(RMatrixLURCondInf(A, N),0);
end;
Inc(N);
end;
//
// report
//
Result := not (Err50 or Err90 or ErrLess or ErrSpec);
end;
(*************************************************************************
Returns True for successful test, False - for failed test
*************************************************************************)
function TestSPDMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;
var
A : TReal2DArray;
CHA : TReal2DArray;
P : TInteger1DArray;
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
Err50 : Boolean;
Err90 : Boolean;
ErrSpec : Boolean;
ErrLess : Boolean;
IsUpper : Boolean;
ERC1 : Double;
ERCInf : Double;
Q50 : TReal1DArray;
Q90 : TReal1DArray;
V : Double;
begin
Err50 := False;
Err90 := False;
ErrLess := False;
ErrSpec := False;
SetLength(Q50, 2);
SetLength(Q90, 2);
N:=1;
while N<=MaxN do
begin
IsUpper := AP_FP_Greater(RandomReal,0.5);
//
// general test
//
SetLength(A, N, N);
I:=0;
while I<=1 do
begin
Q50[I] := 0;
Q90[I] := 0;
Inc(I);
end;
Pass:=1;
while Pass<=PassCount do
begin
SPDMatrixRndCond(N, Exp(RandomReal*Ln(1000)), A);
RMatrixRefRCond(A, N, ERC1, ERCInf);
RMatrixDropHalf(A, N, IsUpper);
RMatrixMakeACopy(A, N, N, CHA);
SPDMatrixCholesky(CHA, N, IsUpper);
//
// normal
//
V := 1/SPDMatrixRCond(A, N, IsUpper);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[0] := Q50[0]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[0] := Q90[0]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// Cholesky
//
V := 1/SPDMatrixCholeskyRCond(CHA, N, IsUpper);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[1] := Q50[1]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[1] := Q90[1]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
Inc(Pass);
end;
I:=0;
while I<=1 do
begin
Err50 := Err50 or AP_FP_Less(Q50[I],0.50);
Err90 := Err90 or AP_FP_Less(Q90[I],0.90);
Inc(I);
end;
//
// degenerate matrix test
//
if N>=3 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 0.0;
Inc(J);
end;
Inc(I);
end;
A[0,0] := 1;
A[N-1,N-1] := 1;
ErrSpec := ErrSpec or AP_FP_Neq(SPDMatrixRCond(A, N, IsUpper),-1);
ErrSpec := ErrSpec or AP_FP_Neq(SPDMatrixCholeskyRCond(A, N, IsUpper),0);
end;
//
// near-degenerate matrix test
//
if N>=2 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := 0.0;
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := 1;
Inc(I);
end;
I := RandomInteger(N);
A[I,I] := 0.1*MaxRealNumber;
ErrSpec := ErrSpec or AP_FP_Neq(SPDMatrixRCond(A, N, IsUpper),0);
ErrSpec := ErrSpec or AP_FP_Neq(SPDMatrixCholeskyRCond(A, N, IsUpper),0);
end;
Inc(N);
end;
//
// report
//
Result := not (Err50 or Err90 or ErrLess or ErrSpec);
end;
(*************************************************************************
Returns True for successful test, False - for failed test
*************************************************************************)
function TestCMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;
var
A : TComplex2DArray;
LUA : TComplex2DArray;
P : TInteger1DArray;
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
Err50 : Boolean;
Err90 : Boolean;
ErrLess : Boolean;
ErrSpec : Boolean;
ERC1 : Double;
ERCInf : Double;
Q50 : TReal1DArray;
Q90 : TReal1DArray;
V : Double;
begin
SetLength(Q50, 3+1);
SetLength(Q90, 3+1);
Err50 := False;
Err90 := False;
ErrLess := False;
ErrSpec := False;
//
// process
//
N:=1;
while N<=MaxN do
begin
//
// special test for zero matrix
//
CMatrixGenZero(A, N);
CMatrixMakeACopy(A, N, N, LUA);
CMatrixLU(LUA, N, N, P);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixRCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixRCondInf(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixLURCond1(LUA, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixLURCondInf(LUA, N),0);
//
// general test
//
SetLength(A, N-1+1, N-1+1);
I:=0;
while I<=3 do
begin
Q50[I] := 0;
Q90[I] := 0;
Inc(I);
end;
Pass:=1;
while Pass<=PassCount do
begin
CMatrixRndCond(N, Exp(RandomReal*Ln(1000)), A);
CMatrixMakeACopy(A, N, N, LUA);
CMatrixLU(LUA, N, N, P);
CMatrixRefRCond(A, N, ERC1, ERCInf);
//
// 1-norm, normal
//
V := 1/CMatrixRCond1(A, N);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[0] := Q50[0]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[0] := Q90[0]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// 1-norm, LU
//
V := 1/CMatrixLURCond1(LUA, N);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[1] := Q50[1]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[1] := Q90[1]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// Inf-norm, normal
//
V := 1/CMatrixRCondInf(A, N);
if AP_FP_Greater_Eq(V,Threshold50*ERCInf) then
begin
Q50[2] := Q50[2]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERCInf) then
begin
Q90[2] := Q90[2]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERCInf*1.001);
//
// Inf-norm, LU
//
V := 1/CMatrixLURCondInf(LUA, N);
if AP_FP_Greater_Eq(V,Threshold50*ERCInf) then
begin
Q50[3] := Q50[3]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERCInf) then
begin
Q90[3] := Q90[3]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERCInf*1.001);
Inc(Pass);
end;
I:=0;
while I<=3 do
begin
Err50 := Err50 or AP_FP_Less(Q50[I],0.50);
Err90 := Err90 or AP_FP_Less(Q90[I],0.90);
Inc(I);
end;
//
// degenerate matrix test
//
if N>=3 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := C_Complex(0.0);
Inc(J);
end;
Inc(I);
end;
A[0,0] := C_Complex(1);
A[N-1,N-1] := C_Complex(1);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixRCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(cMatrixRCondInf(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixLURCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixLURCondInf(A, N),0);
end;
//
// near-degenerate matrix test
//
if N>=2 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := C_Complex(0.0);
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := C_Complex(1);
Inc(I);
end;
I := RandomInteger(N);
A[I,I] := C_Complex(0.1*MaxRealNumber);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixRCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(cMatrixRCondInf(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixLURCond1(A, N),0);
ErrSpec := ErrSpec or AP_FP_Neq(CMatrixLURCondInf(A, N),0);
end;
Inc(N);
end;
//
// report
//
Result := not (Err50 or Err90 or ErrLess or ErrSpec);
end;
(*************************************************************************
Returns True for successful test, False - for failed test
*************************************************************************)
function TestHPDMatrixRCond(MaxN : AlglibInteger;
PassCount : AlglibInteger):Boolean;
var
A : TComplex2DArray;
CHA : TComplex2DArray;
P : TInteger1DArray;
N : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
Pass : AlglibInteger;
Err50 : Boolean;
Err90 : Boolean;
ErrSpec : Boolean;
ErrLess : Boolean;
IsUpper : Boolean;
ERC1 : Double;
ERCInf : Double;
Q50 : TReal1DArray;
Q90 : TReal1DArray;
V : Double;
begin
Err50 := False;
Err90 := False;
ErrLess := False;
ErrSpec := False;
SetLength(Q50, 2);
SetLength(Q90, 2);
N:=1;
while N<=MaxN do
begin
IsUpper := AP_FP_Greater(RandomReal,0.5);
//
// general test
//
SetLength(A, N, N);
I:=0;
while I<=1 do
begin
Q50[I] := 0;
Q90[I] := 0;
Inc(I);
end;
Pass:=1;
while Pass<=PassCount do
begin
HPDMatrixRndCond(N, Exp(RandomReal*Ln(1000)), A);
CMatrixRefRCond(A, N, ERC1, ERCInf);
CMatrixDropHalf(A, N, IsUpper);
CMatrixMakeACopy(A, N, N, CHA);
HPDMatrixCholesky(CHA, N, IsUpper);
//
// normal
//
V := 1/HPDMatrixRCond(A, N, IsUpper);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[0] := Q50[0]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[0] := Q90[0]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
//
// Cholesky
//
V := 1/HPDMatrixCholeskyRCond(CHA, N, IsUpper);
if AP_FP_Greater_Eq(V,Threshold50*ERC1) then
begin
Q50[1] := Q50[1]+AP_Double(1)/PassCount;
end;
if AP_FP_Greater_Eq(V,Threshold90*ERC1) then
begin
Q90[1] := Q90[1]+AP_Double(1)/PassCount;
end;
ErrLess := ErrLess or AP_FP_Greater(V,ERC1*1.001);
Inc(Pass);
end;
I:=0;
while I<=1 do
begin
Err50 := Err50 or AP_FP_Less(Q50[I],0.50);
Err90 := Err90 or AP_FP_Less(Q90[I],0.90);
Inc(I);
end;
//
// degenerate matrix test
//
if N>=3 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := C_Complex(0.0);
Inc(J);
end;
Inc(I);
end;
A[0,0] := C_Complex(1);
A[N-1,N-1] := C_Complex(1);
ErrSpec := ErrSpec or AP_FP_Neq(HPDMatrixRCond(A, N, IsUpper),-1);
ErrSpec := ErrSpec or AP_FP_Neq(HPDMatrixCholeskyRCond(A, N, IsUpper),0);
end;
//
// near-degenerate matrix test
//
if N>=2 then
begin
SetLength(A, N, N);
I:=0;
while I<=N-1 do
begin
J:=0;
while J<=N-1 do
begin
A[I,J] := C_Complex(0.0);
Inc(J);
end;
Inc(I);
end;
I:=0;
while I<=N-1 do
begin
A[I,I] := C_Complex(1);
Inc(I);
end;
I := RandomInteger(N);
A[I,I] := C_Complex(0.1*MaxRealNumber);
ErrSpec := ErrSpec or AP_FP_Neq(HPDMatrixRCond(A, N, IsUpper),0);
ErrSpec := ErrSpec or AP_FP_Neq(HPDMatrixCholeskyRCond(A, N, IsUpper),0);
end;
Inc(N);
end;
//
// report
//
Result := not (Err50 or Err90 or ErrLess or ErrSpec);
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testrcondunit_test_silent():Boolean;
begin
Result := TestRCond(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testrcondunit_test():Boolean;
begin
Result := TestRCond(False);
end;
end. |
(*******************************************************************************
Author:
-> Jean-Pierre LESUEUR (@DarkCoderSc)
https://github.com/DarkCoderSc
https://gist.github.com/DarkCoderSc
https://www.phrozen.io/
License:
-> MIT
*******************************************************************************)
unit UntEnumModules;
interface
uses Classes, Windows, tlHelp32, SysUtils, Generics.Collections, psAPI;
function EnumModules(ATargetProcessID : Cardinal) : TList<TModuleEntry32>;
implementation
{-------------------------------------------------------------------------------
One possible method to get process image path from process id.
Doesn't support Windows XP and below, Windows XP is dead :-( - One technique
would be to use GetModuleFileNameExW()
-------------------------------------------------------------------------------}
function GetProcessName(AProcessID : Cardinal) : String;
var hProc : THandle;
ALength : DWORD;
hDLL : THandle;
QueryFullProcessImageNameW : function(
AProcess: THANDLE;
AFlags: DWORD;
AFileName: PWideChar;
var ASize: DWORD): BOOL; stdcall;
const PROCESS_QUERY_LIMITED_INFORMATION = $00001000;
begin
result := '';
///
if (TOSVersion.Major < 6) then
Exit();
///
QueryFullProcessImageNameW := nil;
hDLL := LoadLibrary('kernel32.dll');
if hDLL = 0 then
Exit();
try
@QueryFullProcessImageNameW := GetProcAddress(hDLL, 'QueryFullProcessImageNameW');
///
if Assigned(QueryFullProcessImageNameW) then begin
hProc := OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, AProcessID);
if hProc = 0 then exit;
try
ALength := (MAX_PATH * 2);
SetLength(result, ALength);
if NOT QueryFullProcessImageNameW(hProc, 0, @result[1], ALength) then
Exit();
SetLength(result, ALength); // Get rid of extra junk
finally
CloseHandle(hProc);
end;
end;
finally
FreeLibrary(hDLL);
end;
end;
{
Enumerate target process modules (Loaded DLL's)
}
function EnumModules(ATargetProcessID : Cardinal) : TList<TModuleEntry32>;
var ASnap : THandle;
AModuleEntry : TModuleEntry32;
AOwnerPath : String;
const TH32CS_SNAPMODULE32 = $00000010;
procedure Append();
begin
if AOwnerPath.ToLower = String(AModuleEntry.szExePath).ToLower then
Exit(); // Ignore
result.Add(AModuleEntry);
end;
begin
result := TList<TModuleEntry32>.Create();
///
AOwnerPath := GetProcessName(ATargetProcessId);
ASnap := CreateToolHelp32Snapshot(TH32CS_SNAPMODULE or TH32CS_SNAPMODULE32, ATargetProcessId);
if ASnap = INVALID_HANDLE_VALUE then begin
Exit;
end;
try
ZeroMemory(@AModuleEntry, SizeOf(TModuleEntry32));
AModuleEntry.dwSize := SizeOf(TModuleEntry32);
///
if NOT Module32First(ASnap, AModuleEntry) then begin
Exit();
end;
Append();
while True do begin
ZeroMemory(@AModuleEntry, SizeOf(TModuleEntry32));
AModuleEntry.dwSize := SizeOf(TModuleEntry32);
///
if NOT Module32Next(ASnap, AModuleEntry) then begin
Break;
end;
Append();
end;
finally
CloseHandle(ASnap);
end;
end;
end.
|
unit uHik86;
interface
uses
SysUtils, Classes, System.Generics.Collections, SyncObjs, DateUtils,
uGlobal, uTypes, IdHttp;
type
THik86 = class
private
FData: TStringStream;
FCount: integer;
public
constructor Create;
destructor Destroy; override;
procedure Add(pass: TPass);
function Save: boolean;
end;
var
Hik86: THik86;
implementation
procedure THik86.Add(pass: TPass);
var
s: string;
begin
s := pass.kdbh + #9 + pass.gcsj + #9 + pass.cdbh + #9 + pass.HPHM + #9
+ pass.HPZL + #9 + pass.hpys + #9 + pass.clsd + #9 + pass.FWQDZ +#9
+ pass.tp1 + #9 + pass.tp2 + #9 + pass.tp3 + #9 + pass.WFXW + #13#10;
FData.WriteString(s);
Inc(FCount);
end;
function THik86.Save: boolean;
var
http: TIdHttp;
begin
result := true;
logger.Info('[Hik86.Save]' + FCount.ToString);
if FCount = 0 then exit;
http := TIdHttp.Create(nil);
try
http.Post(gBdrUrl, FData);
except
on e: exception do
begin
logger.Error('[Hik86.Save]' + e.Message);
result := false;
end;
end;
http.Free;
end;
constructor THik86.Create;
begin
FData := TStringStream.Create;
FCount := 0;
end;
destructor THik86.Destroy;
begin
FData.Free;
inherited;
end;
end.
|
{$MODE OBJFPC}
unit List;
interface
uses sysutils, classes;
type
generic TList<T> = class(TObject)
private
Item : T;
Next : ^TList;
_count : LongInt;
public
property Count : Longint read _count;
procedure Add (Value : T);
procedure Clear ();
function Contains (Value : T) : boolean;
function Equals (list : TList) : boolean;
function Last () : T;
function IndexOf (Value : T) : LongInt;
procedure Insert (Value : T; Index : LongInt);
function ItemAt (Index : LongInt) : T;
procedure RemoveAt (Index : LongInt);
procedure SetValueAt(Value : T; Index : LongInt);
private
function Available (p : Pointer) : boolean;
function LastNode () : TList;
function MakeStep (List : TList; c : LongInt) : TList;
function NodeAt (Index : LongInt) : TList;
end;
{ordinals}
TBooleanList = specialize TList<boolean>;
TCharList = specialize TList<char>;
TByteList = specialize TList<byte>;
TShortIntList = specialize TList<shortint>;
TIntegerList = specialize TList<integer>;
TWordList = specialize TList<word>;
TPointerList = specialize TList<pointer>;
TLongIntList = specialize TList<longint>;
TLongWordList = specialize TList<longword>;
TInt64List = specialize TList<int64>;
TQWordList = specialize TList<qword>;
{reals}
TRealList = specialize TList<real>;
TSingleList = specialize TList<single>;
TDoubleList = specialize TList<double>;
TExtendedList = specialize TList<extended>;
TCompList = specialize TList<comp>;
TCurrencyList = specialize TList<currency>;
{string}
TStringList = specialize TList<string>;
implementation
uses Extensions;
function TList.Available(p : Pointer) : boolean;
var
temp : T;
begin
if (p = nil) then begin
Available := false;
exit;
end;
try
temp := T(p^);
except
Available := false;
exit;
end;
Available := true;
end;
function TList.LastNode() : TList;
begin
LastNode := NodeAt(_count-1);
end;
function TList.Last() : T;
begin
Last := LastNode.Item;
end;
procedure TList.Add(Value : T);
var
node, a : specialize TList<T>;
begin
if (_count = 0) then
Self.Item := Value
else begin
node := TList.Create;
node.Item := Value;
node.Next:= nil;
a := LastNode;
new(a.Next);
a.Next^ := node;
end;
Inc(_count);
end;
function TList.ItemAt(Index : LongInt) : T;
begin
ItemAt := NodeAt(Index).Item;
end;
procedure TList.RemoveAt(Index : LongInt);
var
pred, succ, temp : specialize TList<T>;
begin
temp := NodeAt(Index);
if (Index <> 0) then begin
pred := NodeAt(Index - 1);
if (Index = _count - 1) then begin
temp.Free;
pred.Next := nil;
end
else begin
succ := NodeAt(Index + 1);
pred.Next^ := succ;
temp.Free;
end;
end
else begin
temp.Free;
if (_count <> 1) then begin
self.item := self.next^.item;
self.next := self.next^.next;
end
else self.next := nil;
end;
dec(_count);
end;
function TList.NodeAt(Index : LongInt) : TList;
var
temp : specialize TList<T>;
begin
temp := self;
while ((Assigned(temp.Next)) and (Index > 0)) do begin
temp := temp.Next^;
dec(Index);
end;
if (Index <> 0) then
raise Exception.Create('No such element');
NodeAt := temp;
end;
procedure TList.Clear();
var
temp : specialize TList<T>;
begin
temp := Self;
while (Available(Self.Next)) do begin
temp := Self;
Self := Self.Next^;
temp._count := 0;
temp.Free;
end;
Free;
end;
function TList.Equals(list : TList) : boolean;
var
t1, t2 : TList;
i : LongInt;
begin
if (Self._count <> list._count) then begin
Equals := false;
exit;
end;
t1 := Self;
t2 := list;
for i := 0 to Self._count - 1 do begin
if (t1.Item <> t2.Item) then begin
Equals := false;
exit;
end
else begin
t1 := t1.Next^;
t2 := t2.Next^;
end;
end;
Equals := true;
end;
procedure TList.Insert(Value : T; Index : LongInt);
var
node, a : specialize TList<T>;
i : longint;
begin
if (Index = _count) then begin
Add(Value);
exit;
end;
if (Index > _count) then
raise Exception.Create('Too big index for this list');
a := NodeAt(Index - 1);
node := TList.Create;
node.Item := Value;
if (a.Next = nil) then begin
new(a.Next);
a.next^ := node;
node.Next := nil;
end
else begin
node.Next := a.Next;
a.Next := nil;
new(a.Next);
a.next^ := node;
end;
Inc(_count);
end;
function TList.IndexOf(Value : T) : LongInt;
var
temp : specialize TList<T>;
i : LongInt;
begin
temp := Self;
for i := 0 to _count - 1 do
if (temp.Item = Value) then begin
IndexOf := i;
exit;
end
else temp := MakeStep(temp, 1);
IndexOf := -1;
end;
function TList.Contains(Value : T) : boolean;
var
temp : specialize TList<T>;
i : LongInt;
begin
temp := Self;
for i := 0 to _count - 1 do
if (temp.Item = Value) then begin
Contains := true;
exit;
end
else if (i < _count - 1) then
temp := MakeStep(temp, 1);
Contains := false;
end;
function TList.MakeStep(List : TList; c : LongInt) : TList;
var
temp : specialize TList<T>;
begin
temp := List;
while (Available(temp.Next)) and (c > 0) do begin
temp := temp.Next^;
dec(c);
end;
if (c > 0) then
raise Exception.Create('No such element');
MakeStep := temp;
end;
procedure TList.SetValueAt(Value : T; Index : LongInt);
begin
NodeAt(Index).Item := Value;
end;
end.
|
unit UpDownImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls;
type
TUpDownX = class(TActiveXControl, IUpDownX)
private
{ Private declarations }
FDelphiControl: TUpDown;
FEvents: IUpDownXEvents;
procedure ChangingEvent(Sender: TObject; var AllowChange: Boolean);
procedure ClickEvent(Sender: TObject; Button: TUDBtnType);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_AlignButton: TxUDAlignButton; safecall;
function Get_ArrowKeys: WordBool; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Increment: Integer; safecall;
function Get_Max: Smallint; safecall;
function Get_Min: Smallint; safecall;
function Get_Orientation: TxUDOrientation; safecall;
function Get_Position: Smallint; safecall;
function Get_Thousands: WordBool; safecall;
function Get_Visible: WordBool; safecall;
function Get_Wrap: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_AlignButton(Value: TxUDAlignButton); safecall;
procedure Set_ArrowKeys(Value: WordBool); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Increment(Value: Integer); safecall;
procedure Set_Max(Value: Smallint); safecall;
procedure Set_Min(Value: Smallint); safecall;
procedure Set_Orientation(Value: TxUDOrientation); safecall;
procedure Set_Position(Value: Smallint); safecall;
procedure Set_Thousands(Value: WordBool); safecall;
procedure Set_Visible(Value: WordBool); safecall;
procedure Set_Wrap(Value: WordBool); safecall;
end;
implementation
uses ComObj, About37;
{ TUpDownX }
procedure TUpDownX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_UpDownXPage); }
end;
procedure TUpDownX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IUpDownXEvents;
end;
procedure TUpDownX.InitializeControl;
begin
FDelphiControl := Control as TUpDown;
FDelphiControl.OnChanging := ChangingEvent;
FDelphiControl.OnClick := ClickEvent;
end;
function TUpDownX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TUpDownX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TUpDownX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TUpDownX.Get_AlignButton: TxUDAlignButton;
begin
Result := Ord(FDelphiControl.AlignButton);
end;
function TUpDownX.Get_ArrowKeys: WordBool;
begin
Result := FDelphiControl.ArrowKeys;
end;
function TUpDownX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TUpDownX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TUpDownX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TUpDownX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TUpDownX.Get_Increment: Integer;
begin
Result := FDelphiControl.Increment;
end;
function TUpDownX.Get_Max: Smallint;
begin
Result := FDelphiControl.Max;
end;
function TUpDownX.Get_Min: Smallint;
begin
Result := FDelphiControl.Min;
end;
function TUpDownX.Get_Orientation: TxUDOrientation;
begin
Result := Ord(FDelphiControl.Orientation);
end;
function TUpDownX.Get_Position: Smallint;
begin
Result := FDelphiControl.Position;
end;
function TUpDownX.Get_Thousands: WordBool;
begin
Result := FDelphiControl.Thousands;
end;
function TUpDownX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TUpDownX.Get_Wrap: WordBool;
begin
Result := FDelphiControl.Wrap;
end;
function TUpDownX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TUpDownX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TUpDownX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TUpDownX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TUpDownX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TUpDownX.AboutBox;
begin
ShowUpDownXAbout;
end;
procedure TUpDownX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TUpDownX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TUpDownX.Set_AlignButton(Value: TxUDAlignButton);
begin
FDelphiControl.AlignButton := TUDAlignButton(Value);
end;
procedure TUpDownX.Set_ArrowKeys(Value: WordBool);
begin
FDelphiControl.ArrowKeys := Value;
end;
procedure TUpDownX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TUpDownX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TUpDownX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TUpDownX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TUpDownX.Set_Increment(Value: Integer);
begin
FDelphiControl.Increment := Value;
end;
procedure TUpDownX.Set_Max(Value: Smallint);
begin
FDelphiControl.Max := Value;
end;
procedure TUpDownX.Set_Min(Value: Smallint);
begin
FDelphiControl.Min := Value;
end;
procedure TUpDownX.Set_Orientation(Value: TxUDOrientation);
begin
FDelphiControl.Orientation := TUDOrientation(Value);
end;
procedure TUpDownX.Set_Position(Value: Smallint);
begin
FDelphiControl.Position := Value;
end;
procedure TUpDownX.Set_Thousands(Value: WordBool);
begin
FDelphiControl.Thousands := Value;
end;
procedure TUpDownX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TUpDownX.Set_Wrap(Value: WordBool);
begin
FDelphiControl.Wrap := Value;
end;
procedure TUpDownX.ChangingEvent(Sender: TObject;
var AllowChange: Boolean);
var
TempAllowChange: WordBool;
begin
TempAllowChange := WordBool(AllowChange);
if FEvents <> nil then FEvents.OnChanging(TempAllowChange);
AllowChange := Boolean(TempAllowChange);
end;
procedure TUpDownX.ClickEvent(Sender: TObject; Button: TUDBtnType);
begin
if FEvents <> nil then FEvents.OnClick(TxUDBtnType(Button));
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TUpDownX,
TUpDown,
Class_UpDownX,
37,
'{695CDBF7-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
{*********************************************}
{ TeePreviewPanel Component }
{ TChartPageNavigator Components }
{ Copyright (c) 1999-2004 by David Berneda }
{*********************************************}
unit TeePreviewPanel;
{$I TeeDefs.inc}
interface
Uses {$IFNDEF LINUX}
Windows,
{$ENDIF}
Classes,
{$IFDEF CLX}
QGraphics, QControls, QExtCtrls, QPrinters, QDialogs, QForms,
{$ELSE}
Printers, Graphics, Controls, ExtCtrls, Forms,
{$ENDIF}
{$IFDEF D6}
Types,
{$ENDIF}
TeeProcs, TeCanvas;
type
{$IFDEF CLX}
TPrinterSetupDialog=class(TCustomDialog)
protected
function CreateForm: TDialogForm; override;
function DoExecute:Boolean; override;
end;
TPrintDialog=class(TCustomDialog)
public
Copies,
FromPage,
MinPage,
ToPage,
MaxPage : Integer;
protected
function CreateForm: TDialogForm; override;
function DoExecute:Boolean; override;
end;
{$ENDIF}
TTeePreviewPanelOrientation=(ppoDefault,ppoPortrait,ppoLandscape);
TOnChangeMarginsEvent=Procedure( Sender:TObject; DisableProportional:Boolean;
Const NewMargins:TRect) of object;
TOnGetPaperRect=Procedure(Sender:TObject; var PaperRect:TRect) of object;
TPreviewChartPen=class(TChartPen)
published
property Style default psDot;
property SmallDots default True;
end;
TeePreviewZones=( teePrev_None,
teePrev_Left,
teePrev_Top,
teePrev_Right,
teePrev_Bottom,
teePrev_Image,
teePrev_LeftTop,
teePrev_RightTop,
teePrev_LeftBottom,
teePrev_RightBottom );
TTeePanelsList=class(TList)
private
Function Get(Index:Integer):TCustomTeePanel;
Procedure Put(Index:Integer; Value:TCustomTeePanel);
public
property Items[Index:Integer]:TCustomTeePanel read Get write Put; default;
end;
TTeePreviewPanel=class(TCustomTeePanelExtended)
private
FAllowResize : Boolean;
FAllowMove : Boolean;
FAsBitmap : Boolean;
FPanels : TTeePanelsList;
FDragImage : Boolean;
FMargins : TPreviewChartPen;
FOrientation : TTeePreviewPanelOrientation;
FOnChangeMargins : TOnChangeMarginsEvent;
FOnGetPaperRect : TOnGetPaperRect;
FPaperColor : TColor;
FPaperShadow : TTeeShadow;
FShowImage : Boolean;
FSmoothBitmap : Boolean;
FTitle : String;
{ internal }
IDragged : TeePreviewZones;
OldX : Integer;
OldY : Integer;
OldRect : TRect;
IOldShowImage : Boolean;
Procedure CheckPrinterOrientation;
Function GetPanel:TCustomTeePanel;
Function GetPrintingBitmap(APanel:TCustomTeePanel):TBitmap;
Function GetShadowColor:TColor; // obsolete
Function GetShadowSize:Integer; // obsolete
Procedure SendAsBitmap(APanel:TCustomTeePanel; ACanvas:TCanvas; Const R:TRect); overload;
Procedure SendAsBitmap(APanel:TCustomTeePanel; Const R:TRect); overload;
Procedure SetAsBitmap(Value:Boolean);
Procedure SetMargins(Value:TPreviewChartPen);
Procedure SetOrientation(Value:TTeePreviewPanelOrientation);
Procedure SetPanel(Value:TCustomTeePanel);
Procedure SetPaperColor(Value:TColor);
Procedure SetPaperShadow(Value:TTeeShadow);
Procedure SetShadowColor(Value:TColor); // obsolete
Procedure SetShadowSize(Value:Integer); // obsolete
Procedure SetShowImage(Value:Boolean);
procedure SetSmoothBitmap(const Value: Boolean);
protected
Function CalcImagePrintMargins(APanel:TCustomTeePanel):TRect;
Procedure DrawPaper;
Procedure DrawPanelImage(APanel:TCustomTeePanel);
Procedure DrawMargins(Const R:TRect);
Procedure InternalDraw(Const UserRectangle:TRect); override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X, Y: Integer); override;
procedure Notification( AComponent: TComponent;
Operation: TOperation); override;
Function WhereIsCursor(x,y:Integer):TeePreviewZones;
public
ImageRect : TRect;
PaperRect : TRect;
Constructor Create(AOwner:TComponent); override;
Destructor Destroy; override;
Procedure Print;
property Panels:TTeePanelsList read FPanels;
// compatibility with v5 (obsolete)
property ShadowColor:TColor read GetShadowColor write SetShadowColor;
property ShadowSize:Integer read GetShadowSize write SetShadowSize;
published
property AllowResize:Boolean read FAllowResize write FAllowResize default True;
property AllowMove:Boolean read FAllowMove write FAllowMove default True;
property AsBitmap:Boolean read FAsBitmap write SetAsBitmap default False;
property DragImage:Boolean read FDragImage write FDragImage default False;
property Margins:TPreviewChartPen read FMargins write SetMargins;
property Orientation:TTeePreviewPanelOrientation read FOrientation
write SetOrientation default ppoDefault;
property Panel:TCustomTeePanel read GetPanel write SetPanel;
property PaperColor:TColor read FPaperColor write SetPaperColor default clWhite;
property PaperShadow:TTeeShadow read FPaperShadow write SetPaperShadow; // 6.0
property Shadow; // 6.0
property ShowImage:Boolean read FShowImage write SetShowImage default True;
property SmoothBitmap:Boolean read FSmoothBitmap write SetSmoothBitmap default True; // 7.0
property Title:String read FTitle write FTitle;
property OnChangeMargins:TOnChangeMarginsEvent read FOnChangeMargins
write FOnChangeMargins;
property OnGetPaperRect:TOnGetPaperRect read FOnGetPaperRect
write FOnGetPaperRect;
{ TeePanelExtended }
property BackImage;
property BackImageMode;
property Border;
property BorderRound;
property Gradient;
{ TPanel properties }
property Align;
property BevelInner;
property BevelOuter;
property BevelWidth;
property BorderWidth;
property Color;
property DragMode;
{$IFNDEF CLX}
property DragCursor;
{$ENDIF}
property Enabled;
property ParentColor;
property ParentShowHint;
property PopupMenu;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property Anchors;
{$IFNDEF CLX}
property AutoSize;
{$ENDIF}
property Constraints;
{$IFNDEF CLX}
property DragKind;
property Locked;
{$ENDIF}
property OnAfterDraw;
{ TPanel events }
property OnClick;
{$IFNDEF CLX}
{$IFDEF D5}
property OnContextPopup;
{$ENDIF}
{$ENDIF}
property OnDblClick;
{$IFNDEF CLX}
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnStartDrag;
{$ENDIF}
property OnEnter;
property OnExit;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnResize;
property OnMouseWheel;
property OnMouseWheelDown;
property OnMouseWheelUp;
{$IFNDEF CLX}
property OnCanResize;
{$ENDIF}
property OnConstrainedResize;
{$IFNDEF CLX}
property OnDockDrop;
property OnDockOver;
property OnEndDock;
property OnGetSiteInfo;
property OnStartDock;
property OnUnDock;
{$ENDIF}
end;
implementation
uses
Math, SysUtils;
{$IFNDEF CLR}
type
TShadowAccess=class(TTeeShadow);
{$ENDIF}
Const TeePreviewCursors:Array[0..9] of TCursor=
( crDefault, { none }
crHSplit,
crVSplit,
crHSplit,
crVSplit,
crTeeHand,
crSizeNWSE,
crSizeNESW,
crSizeNESW,
crSizeNWSE );
{ TeePreviewPanel }
Constructor TTeePreviewPanel.Create(AOwner:TComponent);
Begin
inherited;
FPanels:=TTeePanelsList.Create;
FDragImage:=False;
FOrientation:=ppoDefault;
FMargins:=TPreviewChartPen.Create(CanvasChanged);
FMargins.SmallDots:=True;
FMargins.Style:=psDot;
FShowImage:=True;
IOldShowImage:=True;
IDragged:=teePrev_None;
FAsBitmap:=False;
FSmoothBitmap:=True;
FPaperColor:=clWhite;
FAllowResize:=True;
FAllowMove:=True;
FTitle:='';
FPaperShadow:=TTeeShadow.Create(CanvasChanged);
with {$IFNDEF CLR}TShadowAccess{$ENDIF}(FPaperShadow) do
begin
Color:=clDkGray;
Size:=4;
DefaultColor:=Color;
DefaultSize:=4;
end;
Width :=432;
Height:=312;
end;
Destructor TTeePreviewPanel.Destroy;
begin
Margins.Free;
FPaperShadow.Free;
FPanels.Free;
inherited;
end;
Function TTeePreviewPanel.GetPrintingBitmap(APanel:TCustomTeePanel):TBitmap;
var tmpR : TRect;
WinWidth : Integer;
WinHeight : Integer;
tmpW : Integer;
tmpH : Integer;
tmpWidth : Integer;
tmpHeight : Integer;
begin
APanel.Printing:=True;
try
With APanel.GetRectangle do
begin
tmpWidth:=Right-Left;
tmpHeight:=Bottom-Top;
end;
tmpR:=CalcImagePrintMargins(APanel);
APanel.CalcMetaBounds(tmpR,TeeRect(0,0,tmpWidth,tmpHeight),WinWidth,WinHeight,tmpW,tmpH);
result:=APanel.TeeCreateBitmap(FPaperColor,TeeRect(0,0,WinWidth,WinHeight),TeePixelFormat); // 7.0
finally
APanel.Printing:=False;
end;
end;
Procedure TTeePreviewPanel.SendAsBitmap(APanel:TCustomTeePanel; ACanvas:TCanvas; Const R:TRect);
var tmpBitmap : TBitmap;
begin
tmpBitmap:=GetPrintingBitmap(APanel);
try
ACanvas.StretchDraw(R,tmpBitmap);
finally
tmpBitmap.Free;
end;
end;
Procedure TTeePreviewPanel.SendAsBitmap(APanel:TCustomTeePanel; Const R:TRect);
var tmpBitmap : TBitmap;
tmpSmooth : TBitmap;
begin
tmpBitmap:=GetPrintingBitmap(APanel);
try
if SmoothBitmap then
begin
tmpSmooth:=TBitmap.Create;
try
tmpSmooth.Width:=R.Right-R.Left;
tmpSmooth.Height:=R.Bottom-R.Top;
SmoothStretch(tmpBitmap,tmpSmooth,ssBestQuality); // 7.0
Canvas.Draw(R.Left,R.Top,tmpSmooth);
finally
tmpSmooth.Free;
end;
end
else
Canvas.StretchDraw(R,tmpBitmap);
finally
tmpBitmap.Free;
end;
end;
Procedure TTeePreviewPanel.Print;
var t : Integer;
Begin
if FPanels.Count>0 then
Begin
Screen.Cursor:=crHourGlass;
try
CheckPrinterOrientation;
if FTitle='' then
begin
if Panel.Name<>'' then
Printer.Title:=Panel.Name;
end
else Printer.Title:=FTitle;
Printer.BeginDoc;
try
for t:=0 to Panels.Count-1 do
if FAsBitmap then SendAsBitmap(Panels[t],Printer.Canvas,Panels[t].ChartPrintRect)
else Panels[t].PrintPartial(Panels[t].ChartPrintRect);
if Assigned(FOnAfterDraw) then FOnAfterDraw(Self);
Printer.EndDoc;
except
on Exception do
begin
Printer.Abort;
if Printer.Printing then Printer.EndDoc;
Raise;
end;
end;
finally
Screen.Cursor:=crDefault;
end;
end;
end;
Procedure TTeePreviewPanel.DrawPaper;
Begin
With Canvas do
Begin
Pen.Style:=psSolid;
Pen.Color:=clBlack;
Pen.Width:=1;
Brush.Color:=FPaperColor;
Rectangle(PaperRect);
end;
PaperShadow.Draw(Canvas,PaperRect);
end;
Procedure TTeePreviewPanel.SetAsBitmap(Value:Boolean);
begin
SetBooleanProperty(FAsBitmap,Value);
end;
Procedure TTeePreviewPanel.SetPaperColor(Value:TColor);
begin
SetColorProperty(FPaperColor,Value);
end;
Procedure TTeePreviewPanel.SetShadowSize(Value:Integer);
begin
PaperShadow.Size:=Value;
end;
Procedure TTeePreviewPanel.SetShowImage(Value:Boolean);
begin
SetBooleanProperty(FShowImage,Value);
end;
Procedure TTeePreviewPanel.SetMargins(Value:TPreviewChartPen);
Begin
FMargins.Assign(Value);
End;
Procedure TTeePreviewPanel.SetPanel(Value:TCustomTeePanel);
Begin
if ((FPanels.Count=0) or (Panel<>Value)) and (Value<>Self) then
begin
if Assigned(Value) then
begin
if FPanels.IndexOf(Value)=-1 then
begin
FPanels.Add(Value);
Value.FreeNotification(Self); { 5.01 }
end;
end
else FPanels.Delete(0);
if Assigned(Panel) then FAsBitmap:=Panel.Canvas.SupportsFullRotation;
Invalidate;
end;
End;
Function TTeePreviewPanel.CalcImagePrintMargins(APanel:TCustomTeePanel):TRect;
var PaperWidth : Integer;
PaperHeight : Integer;
begin
RectSize(PaperRect,PaperWidth,PaperHeight);
if Assigned(APanel) then
begin
With APanel do
if PrintProportional and (Printer.Printers.Count>0) then
PrintMargins:=CalcProportionalMargins;
result:=APanel.PrintMargins
end
else result:=TeeRect(15,15,15,15);
With result do
begin
Left :=PaperRect.Left +MulDiv(Left ,PaperWidth,100);
Right :=PaperRect.Right -MulDiv(Right ,PaperWidth,100);
Top :=PaperRect.Top +MulDiv(Top ,PaperHeight,100);
Bottom:=PaperRect.Bottom-MulDiv(Bottom,PaperHeight,100);
end;
end;
Procedure TTeePreviewPanel.CheckPrinterOrientation;
begin
if Printer.Printers.Count>0 then
Case FOrientation of
ppoDefault: ;
ppoPortrait: Printer.Orientation:=poPortrait;
else
Printer.Orientation:=poLandscape;
end;
end;
Procedure TTeePreviewPanel.InternalDraw(Const UserRectangle:TRect);
Procedure CalcPaperRectangles;
Const Margin=5;
Var R : TRect;
tmpWidth : Integer;
tmpHeight : Integer;
PrinterWidth : Integer;
PrinterHeight : Integer;
begin
CheckPrinterOrientation;
if Printer.Printers.Count>0 then
begin
try
PrinterWidth :=Printer.PageWidth;
PrinterHeight:=Printer.PageHeight;
except
on EPrinter do
begin
PrinterWidth:=Screen.Width;
PrinterHeight:=Screen.Height;
end;
end;
end
else
begin
PrinterWidth:=Screen.Width;
PrinterHeight:=Screen.Height;
end;
R:=TeeRect(0,0,PrinterWidth,PrinterHeight);
if (ClientWidth*PrinterHeight)>(ClientHeight*PrinterWidth) then
Begin
tmpHeight:=ClientHeight-Round(ClientHeight/Margin);
PaperRect.Top:=Round(ClientHeight/(2*Margin));
PaperRect.Bottom:=PaperRect.Top+tmpHeight;
if PrinterHeight>0 then
tmpWidth:=MulDiv(tmpHeight,PrinterWidth,PrinterHeight)
else
tmpWidth:=ClientWidth;
PaperRect.Left:=(ClientWidth-tmpWidth) div 2;
PaperRect.Right:=PaperRect.Left+tmpWidth;
end
else
Begin
tmpWidth:=ClientWidth-Round(ClientWidth/Margin);
PaperRect.Left:=Round(ClientWidth/(2*Margin));
PaperRect.Right:=PaperRect.Left+tmpWidth;
if PrinterWidth>0 then
tmpHeight:=MulDiv(tmpWidth,PrinterHeight,PrinterWidth)
else
tmpHeight:=ClientHeight;
PaperRect.Top:=(ClientHeight-tmpHeight) div 2;
PaperRect.Bottom:=PaperRect.Top+tmpHeight;
end;
end;
var t : Integer;
begin
PanelPaint(UserRectangle);
RecalcWidthHeight;
InternalCanvas.Projection(100,ChartBounds,ChartRect);
Canvas.ResetState;
CalcPaperRectangles;
if Assigned(FOnGetPaperRect) then
FOnGetPaperRect(Self,PaperRect);
DrawPaper;
ImageRect:=CalcImagePrintMargins(Panel);
for t:=0 to Panels.Count-1 do DrawPanelImage(Panels[t]);
DrawMargins(ImageRect);
Canvas.ResetState;
if Assigned(FOnAfterDraw) then FOnAfterDraw(Self);
end;
Procedure TTeePreviewPanel.DrawMargins(Const R:TRect);
Begin
if Margins.Visible then
With Canvas do
Begin
AssignVisiblePen(Margins);
Pen.Mode:=pmNotXor;
Brush.Style:=bsClear;
Brush.Color:=FPaperColor;
BackMode:=cbmTransparent;
With R do
Begin
DoVertLine(Left-1,PaperRect.Top+1,PaperRect.Bottom);
DoVertLine(Right,PaperRect.Top+1,PaperRect.Bottom);
DoHorizLine(PaperRect.Left+1,PaperRect.Right,Top-1);
DoHorizLine(PaperRect.Left+1,PaperRect.Right,Bottom);
end;
BackMode:=cbmOpaque;
Pen.Mode:=pmCopy;
end;
end;
Procedure TTeePreviewPanel.DrawPanelImage(APanel:TCustomTeePanel);
Var PanelRect : TRect;
{$IFNDEF CLX}
Procedure DrawAsMetafile;
var tmpR : TRect;
tmpMeta : TMetafile;
WinWidth : Integer;
WinHeight : Integer;
tmpW : Integer;
tmpH : Integer;
begin
tmpR:=PanelRect;
APanel.CalcMetaBounds(tmpR,APanel.GetRectangle,WinWidth,WinHeight,tmpW,tmpH);
tmpMeta:=APanel.TeeCreateMetafile(True,TeeRect(0,0,WinWidth,WinHeight));
try
Canvas.StretchDraw(PanelRect,tmpMeta);
finally
tmpMeta.Free;
end;
end;
{$ENDIF}
Begin
PanelRect:=CalcImagePrintMargins(APanel);
APanel.Printing:=True;
if APanel.CanClip then Canvas.ClipRectangle(PanelRect)
else Canvas.ClipRectangle(PaperRect);
if FShowImage then
{$IFDEF CLX}
SendAsBitmap(APanel,Canvas.ReferenceCanvas,PanelRect);
{$ELSE}
if AsBitmap then
SendAsBitmap(APanel,PanelRect)
else
DrawAsMetafile;
{$ENDIF}
Canvas.UnClipRectangle;
APanel.Printing:=False;
end;
procedure TTeePreviewPanel.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation=opRemove) and Assigned(Panel) and (AComponent=Panel) then
Panel:=nil;
end;
Function TTeePreviewPanel.WhereIsCursor(x,y:Integer):TeePreviewZones;
Const MinPixels=5;
var xLeft : Integer;
xRight : Integer;
yTop : Integer;
yBottom : Integer;
Begin
With ImageRect do
begin
xLeft :=Abs(x-Left);
XRight :=Abs(x-Right);
yTop :=Abs(y-Top);
yBottom:=Abs(y-Bottom);
if (xLeft<MinPixels) and (yTop<MinPixels) then result:=teePrev_LeftTop else
if (xLeft<MinPixels) and (yBottom<MinPixels) then result:=teePrev_LeftBottom else
if (xRight<MinPixels) and (yTop<MinPixels) then result:=teePrev_RightTop else
if (xRight<MinPixels) and (yBottom<MinPixels) then result:=teePrev_RightBottom else
if xLeft<MinPixels then result:=teePrev_Left else
if xRight<MinPixels then result:=teePrev_Right else
if yTop<MinPixels then result:=teePrev_Top else
if yBottom<MinPixels then result:=teePrev_Bottom else
if PointInRect(ImageRect,x,y) then
begin
if FAllowMove then
begin
result:=teePrev_Image;
exit;
end else result:=teePrev_None;
end
else result:=teePrev_None;
if (result<>teePrev_None) and (not FAllowResize) then result:=teePrev_None;
end;
End;
Procedure TTeePreviewPanel.MouseMove(Shift: TShiftState; X, Y: Integer);
var tmpR : TRect;
PaperWidth : Integer;
PaperHeight : Integer;
{$IFDEF CLR}
R : TRect;
{$ENDIF}
begin
inherited;
if PointInRect(PaperRect,x,y) then
Begin
if IDragged=teePrev_None then
begin
Cursor:=TeePreviewCursors[Ord(WhereIsCursor(x,y))];
Exit;
end
else
begin
if not FDragImage then DrawMargins(ImageRect);
Case IDragged of
{ sides }
teePrev_Left : if (x>=PaperRect.Left) and (x<ImageRect.Right) then ImageRect.Left:=x;
teePrev_Top : if (y>=PaperRect.Top) and (y<ImageRect.Bottom) then ImageRect.Top:=y;
teePrev_Right : if (x<=PaperRect.Right) and (x>ImageRect.Left) then ImageRect.Right:=x;
teePrev_Bottom : if (y<=PaperRect.Bottom) and (y>ImageRect.Top) then ImageRect.Bottom:=y;
teePrev_Image : Begin
tmpR.Left :=Math.Max(PaperRect.Left,OldRect.Left+(x-OldX));
tmpR.Top :=Math.Max(PaperRect.Top,OldRect.Top+(y-OldY));
tmpR.Right :=Math.Min(PaperRect.Right,tmpR.Left+(OldRect.Right-OldRect.Left));
tmpR.Bottom:=Math.Min(PaperRect.Bottom,tmpR.Top+(OldRect.Bottom-OldRect.Top));
if PointInRect(PaperRect,tmpR.Left,tmpR.Top) and
PointInRect(PaperRect,tmpR.Right,tmpR.Bottom) then
ImageRect:=tmpR;
End;
{ corners }
teePrev_LeftTop : if (x>=PaperRect.Left) and (x<ImageRect.Right) and
(y>=PaperRect.Top) and (y<ImageRect.Bottom) then
Begin
ImageRect.Left:=x;
ImageRect.Top:=y;
end;
teePrev_LeftBottom : if (x>=PaperRect.Left) and (x<ImageRect.Right) and
(y<=PaperRect.Bottom) and (y>ImageRect.Top) then
Begin
ImageRect.Left:=x;
ImageRect.Bottom:=y;
end;
teePrev_RightTop : if (x<=PaperRect.Right) and (x>ImageRect.Left) and
(y>=PaperRect.Top) and (y<ImageRect.Bottom) then
Begin
ImageRect.Right:=x;
ImageRect.Top:=y;
end;
teePrev_RightBottom : if (x<=PaperRect.Right) and (x>ImageRect.Left) and
(y<=PaperRect.Bottom) and (y>ImageRect.Top) then
Begin
ImageRect.Right:=x;
ImageRect.Bottom:=y;
end;
end;
RectSize(PaperRect,PaperWidth,PaperHeight);
if Assigned(Panel) then
begin
Panel.PrintProportional:=False;
{$IFDEF CLR}
R:=Panel.PrintMargins;
with R do
{$ELSE}
With Panel.PrintMargins do
{$ENDIF}
Begin
Left :=MulDiv((ImageRect.Left-PaperRect.Left),100,PaperWidth);
Right :=MulDiv((PaperRect.Right-ImageRect.Right),100,PaperWidth);
Top :=MulDiv((ImageRect.Top-PaperRect.Top),100,PaperHeight);
Bottom:=MulDiv((PaperRect.Bottom-ImageRect.Bottom),100,PaperHeight);
end;
{$IFDEF CLR}
Panel.PrintMargins:=R;
{$ENDIF}
end;
if Assigned(FOnChangeMargins) and Assigned(Panel) then
FOnChangeMargins(Self,True,Panel.PrintMargins);
if FDragImage then Invalidate
else DrawMargins(ImageRect);
end;
end;
end;
procedure TTeePreviewPanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
CancelMouse:=False; { 5.03 }
inherited;
if IDragged<>teePrev_None then
begin
IDragged:=teePrev_None;
if not FDragImage then Invalidate;
end;
end;
procedure TTeePreviewPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
IDragged:=WhereIsCursor(x,y);
if IDragged=teePrev_Image then
Begin
OldX:=x;
OldY:=y;
OldRect:=ImageRect;
end;
end;
Procedure TTeePreviewPanel.SetOrientation(Value:TTeePreviewPanelOrientation);
begin
if Value<>FOrientation then
begin
FOrientation:=Value;
Invalidate;
end;
end;
procedure TTeePreviewPanel.SetShadowColor(Value: TColor); // obsolete
begin
PaperShadow.Color:=Value;
end;
function TTeePreviewPanel.GetShadowColor: TColor; // obsolete
begin
result:=PaperShadow.Color;
end;
function TTeePreviewPanel.GetShadowSize: Integer; // obsolete
begin
result:=PaperShadow.Size;
end;
procedure TTeePreviewPanel.SetPaperShadow(Value: TTeeShadow);
begin
PaperShadow.Assign(Value);
end;
function TTeePreviewPanel.GetPanel: TCustomTeePanel;
begin
if Panels.Count=0 then result:=nil
else result:=Panels[0];
end;
{ TTeePanelsList }
function TTeePanelsList.Get(Index: Integer): TCustomTeePanel;
begin
result:=TCustomTeePanel(inherited Items[Index]);
end;
procedure TTeePanelsList.Put(Index: Integer; Value: TCustomTeePanel);
begin
inherited Items[Index]:=Value;
end;
{$IFDEF CLX}
function TPrinterSetupDialog.CreateForm: TDialogForm;
begin
result:=TDialogForm.CreateNew(nil);
end;
function TPrinterSetupDialog.DoExecute:Boolean;
begin
result:=Printer.ExecuteSetup;
end;
{ TPrintDialog }
function TPrintDialog.CreateForm: TDialogForm;
begin
result:=TDialogForm.CreateNew(nil);
end;
function TPrintDialog.DoExecute: Boolean;
begin
result:=Printer.ExecuteSetup;
end;
{$ENDIF}
procedure TTeePreviewPanel.SetSmoothBitmap(const Value: Boolean);
begin
SetBooleanProperty(FSmoothBitmap,Value);
end;
end.
|
unit frmNetReflectorU;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
System.Actions, Vcl.ActnList, Vcl.ComCtrls,
Vcl.ToolWin, Vcl.StdCtrls, Vcl.Buttons, ReflectorsU, Vcl.Imaging.pngimage,
Vcl.ExtCtrls, Vcl.Imaging.jpeg, HTMLCredit, System.UITypes;
const
APPLICATION_SERVICE_NAME = 'NetReflectorService';
type
TfrmNetReflector = class(TForm)
PageControlReflectors: TPageControl;
tabGeneral: TTabSheet;
tabReflectors: TTabSheet;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ToolButton4: TToolButton;
ActionList: TActionList;
ActionAdd: TAction;
ActionDelete: TAction;
ActionEdit: TAction;
GroupBox1: TGroupBox;
BitBtn2: TBitBtn;
ActionStartStopService: TAction;
ActionRefresh: TAction;
ToolButton5: TToolButton;
ToolButton6: TToolButton;
imgLogo: TImage;
tabAbout: TTabSheet;
ScrollText: THTMLCredit;
ListViewReflectors: TListView;
procedure ActionAddExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure ActionRefreshExecute(Sender: TObject);
procedure ActionEditUpdate(Sender: TObject);
procedure ActionEditExecute(Sender: TObject);
procedure ActionDeleteExecute(Sender: TObject);
procedure PageControlReflectorsChange(Sender: TObject);
procedure ActionStartStopServiceUpdate(Sender: TObject);
procedure ActionStartStopServiceExecute(Sender: TObject);
procedure ActionAddUpdate(Sender: TObject);
procedure ListViewReflectorsDblClick(Sender: TObject);
private
FReflectors: TReflectors;
FApplicationActive: Boolean;
procedure RefreshSettings;
function IsServiceRunning(AServiceName: string): Boolean;
function StartService(AServiceName: string): Boolean;
function StopService(AServiceName: string): Boolean;
public
{ Public declarations }
end;
var
frmNetReflector: TfrmNetReflector;
implementation
{$R *.dfm}
uses
dmReflectorU, frmReflectorEditorU, ServiceControlU;
procedure TfrmNetReflector.ActionAddExecute(Sender: TObject);
var
LEditor: TfrmReflectorEditor;
LReflectorSettings: TReflectorSettings;
begin
LEditor := TfrmReflectorEditor.Create(Self);
LReflectorSettings := TReflectorSettings.Create;
try
if LEditor.Edit(LReflectorSettings) then
begin
FReflectors.Settings.Add(LReflectorSettings);
FReflectors.SaveSettings;
end
else
begin
FreeAndNil(LReflectorSettings);
end;
finally
FreeAndNil(LEditor);
end;
ActionRefresh.Execute;
end;
procedure TfrmNetReflector.ActionAddUpdate(Sender: TObject);
var
LAllowExecute: Boolean;
begin
LAllowExecute := not IsServiceRunning(APPLICATION_SERVICE_NAME);
(Sender as TAction).Enabled := LAllowExecute;
end;
procedure TfrmNetReflector.ActionDeleteExecute(Sender: TObject);
var
LReflectorSettings: TReflectorSettings;
begin
LReflectorSettings := TReflectorSettings(ListViewReflectors.Selected.Data);
if MessageDlg(Format('Delete "%s"?', [LReflectorSettings.ReflectorName]),
mtConfirmation, [mbYes, mbNo], 0) = mrYes then
begin
FReflectors.Settings.Remove(LReflectorSettings);
FReflectors.SaveSettings;
end;
ActionRefresh.Execute;
end;
procedure TfrmNetReflector.ActionEditExecute(Sender: TObject);
var
LEditor: TfrmReflectorEditor;
LReflectorSettings: TReflectorSettings;
begin
LEditor := TfrmReflectorEditor.Create(Self);
LReflectorSettings := TObject(ListViewReflectors.Selected.Data)
as TReflectorSettings;
try
if LEditor.Edit(LReflectorSettings) then
begin
FReflectors.SaveSettings;
end;
finally
FreeAndNil(LEditor);
end;
ActionRefresh.Execute;
end;
procedure TfrmNetReflector.ActionEditUpdate(Sender: TObject);
var
LAllowExecute: Boolean;
begin
LAllowExecute := not IsServiceRunning(APPLICATION_SERVICE_NAME);
if LAllowExecute then
begin
LAllowExecute := ListViewReflectors.ItemIndex <> -1;
end;
if LAllowExecute then
begin
LAllowExecute := ListViewReflectors.Selected.Data <> nil;
end;
if LAllowExecute then
begin
LAllowExecute := TObject(ListViewReflectors.Selected.Data)
is TReflectorSettings;
end;
(Sender as TAction).Enabled := LAllowExecute;
end;
procedure TfrmNetReflector.RefreshSettings;
var
LReflectorSettings: TReflectorSettings;
LListViewItem: TListItem;
begin
ListViewReflectors.Items.Clear;
ListViewReflectors.Items.BeginUpdate;
try
For LReflectorSettings in FReflectors.Settings do
begin
LListViewItem := ListViewReflectors.Items.Add;
LListViewItem.Caption := LReflectorSettings.ReflectorName;
LListViewItem.SubItems.Add(LReflectorSettings.MappedHost);
LListViewItem.SubItems.Add(LReflectorSettings.MappedPort.ToString);
LListViewItem.Data := LReflectorSettings;
end;
finally
ListViewReflectors.Items.EndUpdate;
end;
end;
procedure TfrmNetReflector.ActionRefreshExecute(Sender: TObject);
begin
if PageControlReflectors.ActivePage = tabReflectors then
begin
RefreshSettings;
end;
end;
procedure TfrmNetReflector.ActionStartStopServiceExecute(Sender: TObject);
begin
if IsServiceRunning(APPLICATION_SERVICE_NAME) then
begin
StopService(APPLICATION_SERVICE_NAME);
end
else
begin
StartService(APPLICATION_SERVICE_NAME);
end;
end;
procedure TfrmNetReflector.ActionStartStopServiceUpdate(Sender: TObject);
begin
if IsServiceRunning(APPLICATION_SERVICE_NAME) then
begin
ActionStartStopService.Caption := 'Stop';
ActionStartStopService.ImageIndex := 6;
end
else
begin
ActionStartStopService.Caption := 'Start';
ActionStartStopService.ImageIndex := 5;
end;
end;
procedure TfrmNetReflector.FormActivate(Sender: TObject);
begin
if not FApplicationActive then
begin
FApplicationActive := True;
FReflectors.LoadSettings;
end;
end;
procedure TfrmNetReflector.FormCreate(Sender: TObject);
begin
FApplicationActive := False;
FReflectors := TReflectors.Create(Self);
PageControlReflectors.ActivePageIndex := 0;
end;
procedure TfrmNetReflector.FormDestroy(Sender: TObject);
begin
FreeAndNil(FReflectors);
end;
function TfrmNetReflector.IsServiceRunning(AServiceName: string): Boolean;
var
NTServiceControl: TNTServiceControl;
begin
NTServiceControl := TNTServiceControl.Create(nil);
try
NTServiceControl.ServiceName := AServiceName;
Result := NTServiceControl.IsRunning;
finally
FreeAndNil(NTServiceControl);
end;
end;
procedure TfrmNetReflector.ListViewReflectorsDblClick(Sender: TObject);
begin
ActionEdit.Execute;
end;
function TfrmNetReflector.StartService(AServiceName: string): Boolean;
var
NTServiceControl: TNTServiceControl;
begin
NTServiceControl := TNTServiceControl.Create(nil);
try
NTServiceControl.ServiceName := AServiceName;
NTServiceControl.StartDependencies := True;
Result := NTServiceControl.Start;
finally
FreeAndNil(NTServiceControl);
end;
end;
function TfrmNetReflector.StopService(AServiceName: string): Boolean;
var
NTServiceControl: TNTServiceControl;
begin
NTServiceControl := TNTServiceControl.Create(nil);
try
NTServiceControl.ServiceName := AServiceName;
NTServiceControl.StopDependencies := True;
Result := NTServiceControl.Stop;
finally
FreeAndNil(NTServiceControl);
end;
end;
procedure TfrmNetReflector.PageControlReflectorsChange(Sender: TObject);
begin
ActionRefresh.Execute;
end;
end.
|
unit uInit;
interface
uses
Forms, Windows, Messages, SysUtils, ExtCtrls, ORSystem;
type
{$IFDEF GroupEncounter}
TCPRSTimeoutTimerCondition = function: boolean;
TCPRSTimeoutTimerAction = procedure;
{$ELSE}
TCPRSTimeoutTimerCondition = function: boolean of object;
TCPRSTimeoutTimerAction = procedure of object;
{$ENDIF}
procedure InitTimeOut(AUserCondition: TCPRSTimeoutTimerCondition;
AUserAction: TCPRSTimeoutTimerAction);
procedure UpdateTimeOutInterval(NewTime: Cardinal);
function TimedOut: boolean;
procedure ShutDownTimeOut;
procedure SuspendTimeout;
procedure ResumeTimeout;
implementation
uses
fTimeout;
type
TCPRSTimeoutTimer = class(TTimer)
private
FHooked: boolean;
FUserCondition: TCPRSTimeoutTimerCondition;
FUserAction: TCPRSTimeoutTimerAction;
uTimeoutInterval: Cardinal;
uTimeoutKeyHandle, uTimeoutMouseHandle: HHOOK;
protected
procedure ResetTimeout;
procedure timTimeoutTimer(Sender: TObject);
end;
var
timTimeout: TCPRSTimeoutTimer = nil;
FTimedOut: boolean = FALSE;
uSuspended: boolean = False;
function TimeoutKeyHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; StdCall; forward;
function TimeoutMouseHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; StdCall; forward;
{** Timeout Functions **}
function TimeoutKeyHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT;
{ this is called for every keyboard event that occurs while running CPRS }
begin
if lParam shr 31 = 1 then timTimeout.ResetTimeout; // on KeyUp only
Result := CallNextHookEx(timTimeout.uTimeoutKeyHandle, Code, wParam, lParam);
end;
function TimeoutMouseHook(Code: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT;
{ this is called for every mouse event that occurs while running CPRS }
begin
if (Code >= 0) and (wParam > WM_MOUSEFIRST) and (wParam <= WM_MOUSELAST)
then timTimeout.ResetTimeout; // all click events
Result := CallNextHookEx(timTimeout.uTimeoutMouseHandle, Code, wParam, lParam);
end;
procedure InitTimeOut(AUserCondition: TCPRSTimeoutTimerCondition;
AUserAction: TCPRSTimeoutTimerAction);
begin
if(not assigned(timTimeout)) then
begin
timTimeOut := TCPRSTimeoutTimer.Create(Application);
with timTimeOut do
begin
OnTimer := timTimeoutTimer;
FUserCondition := AUserCondition;
FUserAction := AUserAction;
uTimeoutInterval := 120000; // initially 2 minutes, will get DTIME after signon
uTimeoutKeyHandle := SetWindowsHookEx(WH_KEYBOARD, TimeoutKeyHook, 0, GetCurrentThreadID);
uTimeoutMouseHandle := SetWindowsHookEx(WH_MOUSE, TimeoutMouseHook, 0, GetCurrentThreadID);
FHooked := TRUE;
Interval := uTimeoutInterval;
Enabled := True;
end;
end;
end;
procedure UpdateTimeOutInterval(NewTime: Cardinal);
begin
if(assigned(timTimeout)) then
begin
with timTimeout do
begin
uTimeoutInterval := NewTime;
Interval := uTimeoutInterval;
Enabled := True;
end;
end;
end;
function TimedOut: boolean;
begin
Result := FTimedOut;
end;
procedure ShutDownTimeOut;
begin
if(assigned(timTimeout)) then
begin
with timTimeout do
begin
Enabled := False;
if(FHooked) then
begin
UnhookWindowsHookEx(uTimeoutKeyHandle);
UnhookWindowsHookEx(uTimeoutMouseHandle);
FHooked := FALSE;
end;
end;
timTimeout.Free;
timTimeout := nil;
end;
end;
{ TCPRSTimeoutTime }
procedure TCPRSTimeoutTimer.ResetTimeout;
{ this restarts the timer whenever there is a keyboard or mouse event }
begin
Enabled := False;
Interval := uTimeoutInterval;
Enabled := True;
end;
procedure TCPRSTimeoutTimer.timTimeoutTimer(Sender: TObject);
{ when the timer expires, the application is closed after warning the user }
begin
if uSuspended then
begin
ResetTimeout;
exit;
end;
Enabled := False;
if(assigned(FUserCondition)) then
FTimedOut := FUserCondition or AllowTimeout
else
FTimedOut := AllowTimeout;
if FTimedOut then
begin
if(assigned(FUserAction)) then FUserAction;
end
else
Enabled := True;
end;
procedure SuspendTimeout;
begin
uSuspended := True;
end;
procedure ResumeTimeout;
begin
if assigned(timTimeout) then
timTimeout.ResetTimeout;
uSuspended := False;
end;
initialization
finalization
ShutDownTimeOut;
end.
|
unit uVHA_ATE740X;
{
================================================================================
*
* Application: Vitals
* Revision: $Revision: 1 $ $Modtime: 1/20/09 3:56p $
* Developer: dddddddddomain.user@domain.ext
* Site: Hines OIFO
*
* Description: CASMED Vitals Signs Monitor support
*
* Notes:
================================================================================
}
interface
uses
RS232, Classes, SysUtils, Dialogs, Controls, Forms;
const
iLimit = 200; // milliseconds to wait for COM port
type
TStatusIndicator = procedure(aStatus:String) of object;
TATE740X = class(TObject)
private
ComPort: TComPort;
fBootVersion,
fPICVersion,
fNBPVersion,
fTempVersion,
fSoftwareVersion,
fSoftwaredate,
fModel,
fSerial,
fReadings:String;
fMeasurements: TStringList;
function getActionResult(anAction,aResultCode:String;
aResultLength:Integer;aTimeout:Integer = iLimit):String;
function getDateTime:String;
function getNumerics:String;
function getBatteryVoltage:String;
function getBatteryCharge:String;
// function getPneumaticTestResults:TStringList;
function getMeasurements:TStringList;
function getSystolic:Integer;
function getDiastolic:Integer;
function getTemp: Real;
function getMAP: Integer;
function getSpo2:Integer;
function getPulse:Integer;
function getTempUnits:String;
function getSBP:String;
function getSTemp:String;
function getSPulse:String;
function getSSpO2:String;
function getModel:String;
function getSerial:String;
function getDescription:String;
procedure getSoftwareVersion;
function getSWVersion:String;
public
// property ComPortname:String read fComPortName; zzzzzzandria 20080109
ComPortName:String; // zzzzzzandria 20080109
StatusIndicator: TStatusIndicator;
property SoftwareVersion:String read fSoftwareVersion;
property BootVersion:String read fBootVersion;
property PICVersion:String read fPICVersion;
property NBPVersion:String read fNBPVersion;
property TempVersion:String read fTempVersion;
property SoftwareDate:String read fSoftwareDate;
property Model:String read getModel;
property SerialNumber:String read getSerial;
property iSystolic:Integer read getSystolic;
property iDiastolic:Integer read getDiastolic;
property fTemp: Real read getTemp;
property TempUnit: String read getTempUnits;
property iMAP: Integer read getMap;
property iSpo2:Integer read getSpO2;
property iPulse:Integer read getPulse;
property sBP: String read getSBP;
property sTemp: String read getSTemp;
property sPulse:String read getsPulse;
property sSpO2:String read getSSpO2;
property DateTime:String read getDateTime;
property Numerics: String read getNumerics;
property BatteryVoltage:String read getbatteryVoltage;
property BatteryCharge: String read getBatteryCharge;
// property PneumaticTest:TStringList read getPneumaticTestResults;
property NIBP:TStringList read getMeasurements;
// property Measurements: TStringList read fMeasurements;
property Description:String read getDescription;
constructor Create(aPortName:String=''); // parameter added zzzzzzandria 20080109
destructor Destroy;override;
procedure NewPatient;
procedure ClosePort;
end;
const
cmsCreated = 'Created';
cmsError = 'Error';
cmsReady = 'Ready';
errCheckStatus = 'Please verify that the monitor is connected and turned on.';
_errCasmedNotFound = 'Monitor not found';
function getCasmedDescription(aCasmed: TATE740X;aCasmedPort:String;
StatusIndicator: TStatusIndicator=nil): String;
function newATE740X(var CasmedPort,ErrorMsg:String;
StatusIndicator: TStatusIndicator=nil): TATE740X;
implementation
const
cUnknown = 'Unknown';
arError = 'ERROR';
acDateTime = 'X08'+#13;
acNumericValues = 'X09'+#13;
// Requests ====================================================================
// X032 “X03 2.0” PIC Version 2.0
// X033 “X02 1.1” NIBP Module Version 1.1
// X034 “X02 14” Temp Module Version 14
cmGetBatteryVoltage = 'X20';
cmGetSoftwareVersion ='X030';
cmGetBootVersion = 'X031'; // “X032.0 “ Boot Version 2.0
cmGetPICVersion = 'X032';
cmGetNBPVersion = 'X033';
cmGetTempVersion = 'X034';
cmGetModel = 'X04';
cmGetSerial = 'X05';
cmGetDateTime = 'X08';
cmGetNumericValues = 'X09';
cmStopMeasurement = 'X130';
cmStartMeasurement = 'X131';
cmStartSTATMeasurement = 'X132';
cmExitmanometerMode = 'X140';
cmEnterManometerMode ='X141';
cmStartPneumaticTest ='X151';
cmStopPneumaticTest = 'X150';
cmGetBatteryCharge = 'X18';
cmNewPatient = 'X37';
// Responses ===================================================================
rspGetSoftwareVersion = 'X03';
rspGetBootVersion = 'X031';
rspGetPICVersion = 'X032';
rspGetNBPVersion = 'X033';
rspGetTempVersion = 'X034';
rspGetModel = 'X04';
rspGetSerial = 'X05';
rspDateTime = 'X08';
rspNumericValues = 'X09';
rspNIBPMeasurement = 'X13';
rspNIBPManometerMode ='X14';//response is sent while in the manometer mode
rspNIBPPneumaticTest ='X15';
rspBatteryCharge = 'X18';
rspBatteryVoltage = 'X20';
rspUnknown = 'X??';
rspATEDisabled = 'X**';
// CASMED supports 740-3MS 740-2T 740-3ML and software 2.2 and up
// 2008-04-23 zzzzzzandria 740-3NL added to the list of supportedinstruments.
// GUI version: 5.0.22.6
const
cSupportedUnits = '740-3MS 740-2T 740 2T 740-3NL 740M-3NL ';
cSupportedSoftvare = ' 2.2'; // v. 5.0.2.1
function StripFirstChar(aChar:Char;aValue:String):String;
var
s: String;
begin
Result := aValue;
s := aValue;
while pos(aChar,s) = 1 do
s := copy(s,2,Length(s));
Result := s;
end;
function getCasmedDescription(aCasmed: TATE740X;aCasmedPort:String;
StatusIndicator: TStatusIndicator=nil): String;
var
aCM: TATE740X;
sCasmedError: String;
begin
Screen.Cursor := crHourGlass;
if not Assigned(aCasmed) then
begin
aCM := newATE740X(aCasmedPort,sCasmedError,StatusIndicator); //TATE740X.Create(aCasmedPort);
if not Assigned(aCM) then
Result := errCheckStatus
else
Result := aCM.Description;
FreeAndNil(aCM);
end
else
Result := aCasmed.Description;
Screen.Cursor := crDefault;
end;
function newATE740X(var CasmedPort,ErrorMsg:String;
StatusIndicator: TStatusIndicator=nil): TATE740X;
var
CasmedModel,
CasmedSoftware,
ErrorItem,
ErrorList: String;
i: Integer;
CM: TATE740X;
sPortName:String;
function SupportedModel(aValue:String):Boolean;
begin
Result := pos(trim(uppercase(aValue)),cSupportedUnits) > 0;// aValue = cSupportedUnit;
end;
function SupportedSoftware(aValue:String):Boolean;
var
f: Double;
begin
try
f := strToFloat(aValue);
except
on E: Exception do
f := 0.0;
end;
Result := f >=2.2;
end;
function CasmedOnPort(aPortName:String): TATE740X;
var
sValue: String;
aCM: TATE740X;
begin
aCM := TATE740X.Create(aPortName);
if Assigned(aCM) then
begin
sValue := aCM.Model;
if not SupportedModel(sValue) then
begin
ErrorItem := 'Sorry. The model <'+sValue+'> is not supported.';
FreeAndNil(aCM);
end
else
CasmedModel := sValue;
end;
if Assigned(aCM) then
begin
sValue := aCM.getSWVersion;
if not SupportedSoftware(sValue) then
begin
ErrorItem := 'Sorry. The software version <'+sValue+'> is not supported.';
FreeAndNil(aCM);
end
else
CasmedSoftware := sValue;
end;
Result := aCM;
end;
begin
ErrorItem := '';
ErrorList := '';
if CasmedPort = '' then
begin
for i := 1 to 8 do
begin
sPortName := 'COM'+IntToStr(i);
if Assigned(StatusIndicator) then
StatusIndicator('Looking for CASMED on Port: '+sPortName);
CM := CasmedOnPort(sPortName);
if CM <> nil then
begin
CasmedPort := 'COM'+IntToStr(i);
break;
end;
ErrorList := ErrorList + ErrorItem+#13;
end;
end
else
begin
if Assigned(StatusIndicator) then
StatusIndicator('Looking for CASMED on Port: '+CasmedPort);
CM := CasmedOnPort(CasmedPort);
end;
if assigned(CM) then
CM.StatusIndicator := StatusIndicator;
if Assigned(StatusIndicator) then
begin
StatusIndicator('Port: '+CasmedPort);
if Assigned(CM) then
begin
StatusIndicator('Model: '+CasmedModel);
StatusIndicator('Status: Connected');
StatusIndicator('');
end
else
begin
StatusIndicator('Model: Unknown');
StatusIndicator('Status: Unknown');
StatusIndicator(errCheckStatus{errCasmedNotFound});
end;
end;
Result := CM;
ErrorMsg := ErrorList;
end;
////////////////////////////////////////////////////////////////////////////////
constructor TATE740X.Create(aPortName:String='');
begin
TObject.Create; // zzzzzzandria 20090109
ComPortName := aPortName; // zzzzzzandria 20090109
ComPort := TComPort.Create;
fMeasurements := TStringList.Create;
fBootVersion := cUnknown;
fPICVersion := cUnknown;
fNBPVersion := cUnknown;
fTempVersion := cUnknown;
fSoftwareversion := 'Unknown'
end;
destructor TATE740X.Destroy;
begin
FreeAndNil(ComPort);
FreeAndNil(fMeasurements);
inherited;
end;
function TATE740X.getActionResult(anAction,aResultCode:String;
aResultLength:Integer;aTimeout:Integer = iLimit):String;
var
i: Integer;
begin
result := arError;
if ComPort.ComPortStatus <> cpsOpened then // zzzzzzandria 20090115
if ComPort.Open(ComPortName) then // Port added. zzzzzzandria 20090109
ComPort.Config;
i := 0;
if ComPort.Write(anAction+#13) then
while (pos(aResultCode, ComPort.CommandResults) = 0) do
begin
inc(i);
sleep(aTimeout);
Comport.Read(aResultLength);
if i>1 then break;
end;
if (pos(aResultCode, ComPort.CommandResults) <> 0) then
result := ComPort.CommandResults;
ComPort.Purge;
ComPort.Close;// zzzzzzandria 2009-01-20
end;
function TATE740X.getModel:String;
begin
if Assigned(StatusIndicator) then
StatusIndicator('Collecting monitor model information...');
fModel := copy(GetActionResult(cmGetModel,rspGetModel,12),4,8);
Result := fModel;
if Assigned(StatusIndicator) then
StatusIndicator('');
end;
function TATE740X.getSWVersion:String;
var
sl: TSTringList;
begin
if Assigned(StatusIndicator) then
StatusIndicator('Collecting software version...');
Result := GetActionResult(cmGetSoftwareVersion,rspGetSoftwareVersion,80,1000);
if Result <> arError then
begin
sl := TstringList.Create;
sl.Text := Result;
if sl.Count > 0 then
Result := copy(sl[0],5,Length(sl[0]))
else
Result := 'Unknown';
end;
if Assigned(StatusIndicator) then
StatusIndicator('');
end;
procedure TATE740X.getSoftwareVersion;
var
s: String;
SL: TStringList;
function SetValue(aValue:String;aPos,aLen:Integer):String;
begin
if aValue = arError then Result := 'Unknown'
else
Result := copy(aValue,aPos,aLen);
end;
begin
if Assigned(StatusIndicator) then
StatusIndicator('Collecting software version information...');
s := GetActionResult(cmGetSoftwareVersion,rspGetSoftwareVersion,80,1000);
if s <> arError then
begin
SL:= TStringList.Create;
SL.Text := s;
if SL.Count > 0 then
fSoftwareVersion := copy(SL[0],5,Length(SL[0]));
if SL.Count > 1 then
fSoftwareDate := copy(SL[1],3,2)+'/'+copy(sl[1],1,2)+'/'+copy(sl[1],5,2)
else
fSoftwareDate := 'Unknown';
SL.Free;
if Assigned(StatusIndicator) then
StatusIndicator('Collecting Boot version...');
fBootVersion :=SetValue(GetActionResult(cmGetBootVersion,rspGetBootVersion,8),5,4);
if Assigned(StatusIndicator) then
StatusIndicator('Collecting RIC version...');
fPICVersion := SetValue(GetActionResult(cmGetPICVersion,rspGetPICVersion,8),5,4);
if Assigned(StatusIndicator) then
StatusIndicator('Collecting NBP version...');
fNBPVersion := Setvalue(GetActionResult(cmGetNBPVersion,rspGetNBPVersion,8),5,4);
if Assigned(StatusIndicator) then
StatusIndicator('Collecting Temp version...');
fTempVersion := Setvalue(GetActionResult(cmGetTempVersion,rspGetTempVersion,8),5,4);
end;
if Assigned(StatusIndicator) then
StatusIndicator('');
end;
function TATE740X.getSerial:String;
begin
if Assigned(StatusIndicator) then
StatusIndicator('Collecting monitor Serial number information...');
fSerial := copy(GetActionResult(cmGetSerial,rspGetSerial,12),4,8);
Result := fSerial;
if Assigned(StatusIndicator) then
StatusIndicator('');
end;
function TATE740X.getDescription:String;
begin
// Result := Model + #13#10+ SerialNumber;
if Assigned(StatusIndicator) then
StatusIndicator('Collecting version information...');
getSoftwareVersion;
Result :=
'CASMED '+Model+ ' (SN: '+SerialNumber+') at '+ComPortname+#13+
'___________________________________'+#13+#13+#9+
'Software: '+SoftwareVersion+' ( Date: '+SoftwareDate+')'+#13+#9+#9+
'Boot: '+#9+BootVersion+#13+#9+#9+
'PIC: '+#9+PICVersion+#13+#9+#9+
'NBP: '+#9+NBPVersion+#13+#9+#9+
'Temp: '+#9+TempVersion;
if Assigned(StatusIndicator) then
StatusIndicator('');
end;
function TATE740X.getDateTime:String;
begin
Result := GetActionResult(cmGetDateTime,rspDateTime,16);
end;
function TATE740X.getNumerics:String;
begin
if Assigned(StatusIndicator) then
StatusIndicator('Requesting monitor readings...');
fReadings := GetActionResult(cmGetNumericValues,rspNumericValues,24);
if Assigned(StatusIndicator) then
StatusIndicator('');
Result := fReadings;
end;
function TATE740X.getBatteryVoltage:String;
begin
Result := GetActionResult(cmGetBatteryVoltage,rspBatteryVoltage,9);
end;
function TATE740X.getBatteryCharge:String;
begin
Result := GetActionResult(cmGetBatteryCharge,rspBatteryCharge,7);
end;
function TATE740X.getMeasurements:TStringList;
var
i: Integer;
begin
i := 0;
fMeasurements.Clear;
ComPort.CommandResults := '';
if ComPort.Open(ComPortName) then // zzzzzzandria 20090109
ComPort.Config;
ComPort.Write(cmStartMeasurement+#13);
while i < iLimit do
begin
inc(i);
if ComPort.Read(7) then
if (pos('X13', ComPort.CommandResults) = 1) then
begin
fMeasurements.Add(ComPort.CommandResults);
i := 0;
end;
end;
ComPort.Write(cmStopMeasurement);
ComPort.Purge;
ComPort.Close;
Result := fMeasurements;
end;
function TATE740X.getSystolic:Integer;
begin
try
Result := StrToIntDef(copy(fReadings,4,3),-1);
except
Result := -1;
end;
end;
function TATE740X.getDiastolic:Integer;
begin
try
Result := StrToIntDef(copy(fReadings,7,3),-1);
except
Result := -1;
end;
end;
function TATE740X.getTemp: Real;
var
s,ss: String;
begin
try
s := copy(fReadings,19,3);
ss := copy(fReadings,22,1);
if pos(ss,'0123456789') > 0 then
s := s + ss;
Result := StrToIntDef(s,-1) / 10.0;
except
Result := -1;
end;
end;
function TATE740X.getMAP: Integer;
begin
try
Result := StrToIntDef(copy(fReadings,10,3),-1);
except
Result := -1;
end;
end;
function TATE740X.getSpo2:Integer;
begin
try
Result := StrToIntDef(copy(fReadings,16,3),-1);
except
Result := -1;
end;
end;
function TATE740X.getPulse:Integer;
begin
try
Result := StrToIntDef(copy(fReadings,13,3),-1);
except
Result := -1;
end;
end;
function TATE740X.getTempUnits:String;
var
s : String;
begin
try
s := copy(fReadings,22,1);
if pos(s,'0123456789') > 0 then
s := copy(fReadings,23,1);
if (s<>'C') and (s<>'F') then s := '';
Result := s;
except
Result := '';
end;
end;
function TATE740X.getSBP:String;
var
i: Integer;
s: String;
begin
Result := '';
try
s := copy(fReadings,4,3);
while copy(s,1,1) = '0' do s := Copy(s,2,length(s));
i := StrToIntDef(s,-1);
if i < 0 then Exit;
Result := s + '/';
s := copy(fReadings,7,3);
while copy(s,1,1) = '0' do s := Copy(s,2,length(s));
i := StrToIntDef(s,-1);
if i < 0 then
begin
Result := '';
Exit;
end;
Result := Result + s;
except
Result := '';
end;
end;
function TATE740X.getSTemp:String;
begin
try
if fTemp > 0 then
Result := Format('%5.1f',[fTemp])
else
Result := '';
except
Result := '';
end;
end;
function TATE740X.getSPulse:String;
begin
try
if iPulse < 0 then
Result := ''
else
begin
Result := copy(fReadings,13,3);
Result := StripFirstChar('-',Result);
Result := StripFirstChar(' ',Result);
Result := StripFirstChar('0',Result);
end;
except
Result := '';
end;
end;
function TATE740X.getSSpO2:String;
begin
try
if iSpO2 < 0 then
Result := ''
else
begin
Result := copy(fReadings,16,3);
Result := StripFirstChar('-',Result);
Result := StripFirstChar('0',Result);
end;
except
Result := '';
end;
end;
procedure TATE740X.NewPatient;
begin
if Assigned(StatusIndicator) then
StatusIndicator('Cleaning data buffer...');
getActionResult(cmNewPatient+#13,cmNewPatient+#13,Length(cmNewPatient+#13));
if Assigned(StatusIndicator) then
StatusIndicator('');
end;
procedure TATE740X.ClosePort;
begin
ComPort.Close;
end;
(*
function TATE740X.getPneumaticTestResults:TStringList;
var
i: Integer;
begin
i := 0;
fMeasurements.Clear;
ComPort.CommandResults := '';
if ComPort.Open(ComPortName) then // zzzzzzandria 20090109
ComPort.Config;
ComPort.Write(cmStartPneumaticTest+#13);
while i < iLimit do
begin
inc(i);
if ComPort.Read(8) then
if (pos('X15', ComPort.CommandResults) = 1) then
begin
fMeasurements.Add(ComPort.CommandResults);
i := 0;
if (ComPort.CommandResults = 'X15PASS') or
(ComPort.CommandResults = 'X15FAIL') then break;
end;
end;
ComPort.Write(cmStopPneumaticTest);
ComPort.Purge;
ComPort.Close;
Result := fMeasurements;
end;
*)
end.
|
unit dfm2xmlImpl;
interface
uses
System.Classes;
procedure ObjectBinaryToXml(Input, Output: TStream); overload;
procedure ObjectResourceToXml(Input, Output: TStream); overload;
implementation
uses
System.RTLConsts,
System.TypInfo,
System.SysUtils,
System.StrUtils;
{ Binary to xml conversion }
procedure ObjectBinaryToXml(Input, Output: TStream);
var
NestingLevel: Integer;
Reader: TReader;
Writer: TWriter;
ObjectName, PropName: string;
UTF8Idents: Boolean;
MemoryStream: TMemoryStream;
LFormatSettings: TFormatSettings;
procedure WriteIndent;
const
Blanks: array[0..0] of AnsiChar = (#9); //'<tab>';
var
I: Integer;
begin
for I := 1 to NestingLevel do Writer.Write(Blanks, SizeOf(Blanks));
end;
procedure WriteStr(const S: RawByteString); overload;
begin
Writer.Write(S[1], Length(S));
end;
procedure WriteStr(const S: UnicodeString); overload; inline;
begin
WriteStr(AnsiString(S));
end;
procedure WriteUTF8Str(const S: string);
var
Ident: UTF8String;
begin
Ident := UTF8Encode(S);
if not UTF8Idents and (Length(Ident) > Length(S)) then
UTF8Idents := True;
WriteStr(Ident);
end;
procedure NewLine;
begin
WriteStr(sLineBreak);
WriteIndent;
end;
procedure ConvertValue; forward;
procedure ConvertHeader;
var
ClassName: string;
Flags: TFilerFlags;
Position: Integer;
begin
Reader.ReadPrefix(Flags, Position);
ClassName := Reader.ReadStr;
ObjectName := Reader.ReadStr;
WriteIndent;
if ffInherited in Flags then
WriteStr('<object instance="inherited"')
else if ffInline in Flags then
WriteStr('<object instance="inline"')
else
WriteStr('<object');
if ObjectName <> '' then
begin
WriteStr(' name="');
WriteUTF8Str(ObjectName);
WriteStr('"');
end;
WriteStr(' class="');
WriteUTF8Str(ClassName);
WriteStr('"');
if ffChildPos in Flags then
begin
WriteStr(' index="');
WriteStr(IntToStr(Position));
WriteStr('"');
end;
if ObjectName = '' then
ObjectName := ClassName; // save for error reporting
WriteStr('>');
WriteStr(sLineBreak);
end;
procedure ConvertBinary;
const
BytesPerLine = 32;
var
MultiLine: Boolean;
I: Integer;
Count: Longint;
Buffer: array[0..BytesPerLine - 1] of AnsiChar;
Text: array[0..BytesPerLine * 2 - 1] of AnsiChar;
begin
Reader.ReadValue;
WriteStr('{');
Inc(NestingLevel);
Reader.Read(Count, SizeOf(Count));
MultiLine := Count >= BytesPerLine;
while Count > 0 do
begin
if MultiLine then NewLine;
if Count >= 32 then I := 32 else I := Count;
Reader.Read(Buffer, I);
BinToHex(Buffer, Text, I);
Writer.Write(Text, I * 2);
Dec(Count, I);
end;
Dec(NestingLevel);
WriteStr('}');
end;
procedure ConvertProperty; forward;
procedure ConvertValue;
const
LineLength = 64;
var
I, J, K, L: Integer;
S: AnsiString;
W: UnicodeString;
LineBreak: Boolean;
begin
case Reader.NextValue of
vaList:
begin
Reader.ReadValue;
WriteStr('(');
Inc(NestingLevel);
while not Reader.EndOfList do
begin
NewLine;
ConvertValue;
end;
Reader.ReadListEnd;
Dec(NestingLevel);
WriteStr(')');
end;
vaInt8, vaInt16, vaInt32:
WriteStr(IntToStr(Reader.ReadInteger));
vaExtended, vaDouble:
WriteStr(FloatToStrF(Reader.ReadFloat, ffFixed, 16, 18, LFormatSettings));
vaSingle:
WriteStr(FloatToStr(Reader.ReadSingle, LFormatSettings) + 's');
vaCurrency:
WriteStr(FloatToStr(Reader.ReadCurrency * 10000, LFormatSettings) + 'c');
vaDate:
WriteStr(FloatToStr(Reader.ReadDate, LFormatSettings) + 'd');
vaWString, vaUTF8String:
begin
W := Reader.ReadWideString;
W := ReplaceStr(W, '&', '&');
W := ReplaceStr(W, '"', '"');
W := ReplaceStr(W, '<', '<');
W := ReplaceStr(W, '>', '>');
WriteUTF8Str(W);
end;
vaString, vaLString:
begin
S := AnsiString(Reader.ReadString);
S := AnsiReplaceStr(S, '&', '&');
S := AnsiReplaceStr(S, '"', '"');
S := AnsiReplaceStr(S, '<', '<');
S := AnsiReplaceStr(S, '>', '>');
WriteStr(S);
end;
vaIdent, vaFalse, vaTrue, vaNil, vaNull:
WriteUTF8Str(Reader.ReadIdent);
vaBinary:
ConvertBinary;
vaSet:
begin
Reader.ReadValue;
WriteStr('[');
I := 0;
while True do
begin
S := AnsiString(Reader.ReadStr);
if S = '' then Break;
if I > 0 then WriteStr(', ');
WriteStr(S);
Inc(I);
end;
WriteStr(']');
end;
vaCollection:
begin
Reader.ReadValue;
///WriteStr('<');
Inc(NestingLevel);
while not Reader.EndOfList do
begin
NewLine;
WriteStr('item');
if Reader.NextValue in [vaInt8, vaInt16, vaInt32] then
begin
WriteStr(' [');
ConvertValue;
WriteStr(']');
end;
WriteStr(sLineBreak);
Reader.CheckValue(vaList);
Inc(NestingLevel);
while not Reader.EndOfList do
ConvertProperty;
Reader.ReadListEnd;
Dec(NestingLevel);
WriteIndent;
WriteStr('end');
end;
Reader.ReadListEnd;
Dec(NestingLevel);
///WriteStr('>');
end;
vaInt64:
WriteStr(IntToStr(Reader.ReadInt64));
else
raise EReadError.CreateResFmt(@sPropertyException,
[ObjectName, DotSep, PropName, IntToStr(Ord(Reader.NextValue))]);
end;
end;
procedure ConvertProperty;
begin
WriteIndent;
PropName := Reader.ReadStr; // save for error reporting
WriteStr('<property name="');
WriteUTF8Str(PropName);
WriteStr('" value="');
ConvertValue;
WriteStr('"/>');
WriteStr(sLineBreak);
end;
procedure ConvertObject;
begin
ConvertHeader;
Inc(NestingLevel);
while not Reader.EndOfList do
ConvertProperty;
Reader.ReadListEnd;
while not Reader.EndOfList do
ConvertObject;
Reader.ReadListEnd;
Dec(NestingLevel);
WriteIndent;
WriteStr('</object>' + sLineBreak);
end;
begin
NestingLevel := 0;
UTF8Idents := False;
Reader := TReader.Create(Input, 4096);
LFormatSettings := TFormatSettings.Create('en-US'); // do not localize
LFormatSettings.DecimalSeparator := AnsiChar('.');
try
MemoryStream := TMemoryStream.Create;
try
Writer := TWriter.Create(MemoryStream, 4096);
try
Reader.ReadSignature;
ConvertObject;
finally
Writer.Free;
end;
if UTF8Idents then
Output.Write(TEncoding.UTF8.GetPreamble[0], 3);
Output.Write(MemoryStream.Memory^, MemoryStream.Size);
finally
MemoryStream.Free;
end;
finally
Reader.Free;
end;
end;
procedure ObjectResourceToXml(Input, Output: TStream);
begin
Input.ReadResHeader;
ObjectBinaryToXml(Input, Output);
end;
end.
|
procedure DLLEntryPoint(dwReason: Integer);
begin
case dwReason of
DLL_PROCESS_ATTACH:
begin
NPlugin := TdsPlugin.Create;
end;
DLL_PROCESS_DETACH:
begin
if (Assigned(NPlugin)) then NPlugin.Destroy;
end;
end;
end;
procedure setInfo(NppData: TNppData); cdecl; export;
begin
NPlugin.SetInfo(NppData);
end;
function getName: nppPchar; cdecl; export;
begin
Result := NPlugin.GetName;
end;
function getFuncsArray(var nFuncs:integer):Pointer;cdecl; export;
begin
Result := NPlugin.GetFuncsArray(nFuncs);
end;
procedure beNotified(sn: PSCNotification); cdecl; export;
begin
NPlugin.BeNotified(sn);
end;
function messageProc(msg: Integer; wParam: WPARAM; lParam: LPARAM): LRESULT; cdecl; export;
var
Message:TMessage;
begin
Message.Msg := msg;
Message.WParam := wParam;
Message.LParam := lParam;
Message.Result := 0;
NPlugin.MessageProc(Message);
Result := Message.Result;
end;
{$IFDEF NPPUNICODE}
function isUnicode : Boolean; cdecl; export;
begin
Result := true;
end;
{$ENDIF}
exports
setInfo, getName, getFuncsArray, beNotified, messageProc;
{$IFDEF NPPUNICODE}
exports
isUnicode;
{$ENDIF}
|
unit FrmWEDetails;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, U_WE_EQUATION_DRAW, U_WE_DIAGRAM2,U_DIAGRAM_TYPE, U_WE_EQUATION, U_WE_PHASE_MAP,
StdCtrls, ExtCtrls, ImgList, ActnList, XPStyleActnCtrls, ActnMan, Menus,
U_WIRING_ERROR, IniFiles, System.Types, System.Actions, System.ImageList;
const
C_ZOOM_RATE_STEP = 0.1;
type
TfWEDetails = class(TForm)
scrlbxMap: TScrollBox;
imgMap: TImage;
pmMap: TPopupMenu;
N2: TMenuItem;
N3: TMenuItem;
N4: TMenuItem;
N5: TMenuItem;
actmgr1: TActionManager;
actZoomIn: TAction;
actZoomOut: TAction;
actImageReset: TAction;
actFitWindows: TAction;
il1: TImageList;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure actZoomInExecute(Sender: TObject);
procedure actZoomOutExecute(Sender: TObject);
procedure actImageResetExecute(Sender: TObject);
procedure actFitWindowsExecute(Sender: TObject);
procedure imgMapMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure imgMapMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure imgMapMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
dZoomRate : Double;
ptBefore : TPoint;
Bitmap : TBitmap;
PhaseDraw : TWE_PHASE_MAP;
EquationDraw : TWE_EQUATION_DRAW;
DiagramDraw : TWE_DIAGRAM2;
Equation : TWE_EQUATION;
/// <summary>
/// 改变图片大小
/// </summary>
procedure ResizeImages;
/// <summary>
/// 处理滚轮事件
/// </summary>
procedure ProcMouseWheel( var Msg : TWMMouseWheel ); message WM_MOUSEWHEEL;
public
{ Public declarations }
/// <summary>
/// 接线图类型
/// </summary>
ADiagramType : TDiagramType;
/// <summary>
/// 显示错误接线信息
/// </summary>
procedure LoadEquation( AEquation : TWE_EQUATION ); overload;
/// <summary>
/// 显示错误接线信息
/// </summary>
procedure LoadEquation( AWiringError : TWIRING_ERROR; AAngle : Double ); overload;
end;
var
fWEDetails: TfWEDetails;
implementation
{$R *.dfm}
procedure TfWEDetails.actFitWindowsExecute(Sender: TObject);
begin
dZoomRate := ClientWidth / imgMap.Picture.Width;
ResizeImages;
end;
procedure TfWEDetails.actImageResetExecute(Sender: TObject);
begin
dZoomRate := 1;
ResizeImages;
end;
procedure TfWEDetails.actZoomInExecute(Sender: TObject);
begin
if dZoomRate < 4 then
begin
dZoomRate := dZoomRate + C_ZOOM_RATE_STEP;
ResizeImages;
end;
end;
procedure TfWEDetails.actZoomOutExecute(Sender: TObject);
begin
if dZoomRate > 0.3 then
begin
dZoomRate := dZoomRate - C_ZOOM_RATE_STEP;
ResizeImages;
end;
end;
procedure TfWEDetails.FormCreate(Sender: TObject);
begin
imgMap.Left := 0;
imgMap.Top := 0;
ClientWidth := 1020;
ClientHeight := 730;
DoubleBuffered := True;
scrlbxMap.DoubleBuffered := True;
Bitmap := TBitmap.Create;
Bitmap.Width := 1020;
Bitmap.Height := 730;
EquationDraw := TWE_EQUATION_DRAW.Create( nil );
PhaseDraw := TWE_PHASE_MAP.Create( nil );
DiagramDraw := TWE_DIAGRAM2.Create( nil );
EquationDraw.Canvas := Bitmap.Canvas;
PhaseDraw.Canvas := Bitmap.Canvas;
// DiagramDraw.Canvas := Bitmap.Canvas;
dZoomRate := 1;
Equation := TWE_EQUATION.Create;
end;
procedure TfWEDetails.FormDestroy(Sender: TObject);
begin
Bitmap.Free;
PhaseDraw.Free;
EquationDraw.Free;
DiagramDraw.Free;
Equation.Free;
end;
procedure TfWEDetails.FormShow(Sender: TObject);
begin
PhaseDraw.MapColor := PhaseMapColor;
end;
procedure TfWEDetails.imgMapMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ptBefore.X := X;
ptBefore.Y := Y;
Screen.Cursor := crSize;
end;
procedure TfWEDetails.imgMapMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
nX, nY : Integer;
begin
if ( ptBefore.X > 0 ) and ( ptBefore.Y > 0 ) then
begin
nX := ptBefore.X - X;
nY := ptBefore.Y - Y;
scrlbxMap.VertScrollBar.Position := scrlbxMap.VertScrollBar.Position + nY;
scrlbxMap.HorzScrollBar.Position := scrlbxMap.HorzScrollBar.Position + nX;
end;
end;
procedure TfWEDetails.imgMapMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
ptBefore := Point( -1, -1 );
Screen.Cursor := crDefault;
end;
procedure TfWEDetails.LoadEquation(AWiringError: TWIRING_ERROR; AAngle: Double);
begin
if AWiringError.PhaseType = ptThree then
begin
if not (ADiagramType in[ dt3CTClear..dt3L4]) then
begin
ADiagramType := dt3L4;
end;
end
else if AWiringError.PhaseType = ptFour then
begin
if not (ADiagramType in[ dt4M_NoPT..dt4_NoPT_L6]) then
begin
ADiagramType := dt4_NoPT_L6;
end;
end
else
begin
if not (ADiagramType in[ dt4M_PT..dt4_PT_L6]) then
begin
ADiagramType := dt4_PT_L6;
end;
end;
Equation.GenerateEquations( AWiringError, AAngle );
LoadEquation( Equation );
end;
procedure TfWEDetails.LoadEquation(AEquation: TWE_EQUATION);
var
nY : Integer;
Analysis : TStrings;
// p3l3, p3l4,p3l4pt: TDiagramType;
begin
if not Assigned( AEquation ) then
Exit;
Caption := Format( '详细信息:(%s)%s', [ AEquation.WiringError.IDInStr,
AEquation.WiringError.Description ] );
with Bitmap.Canvas do // 清画布
begin
Brush.Style := bsSolid;
Brush.Color := clWhite;
FillRect( Rect( 0, 0, Bitmap.Width, Bitmap.Height ) );
end;
// with TIniFile.Create( ChangeFileExt( Application.ExeName, '.ini' ) ) do
// begin
// p3l3 := TDiagramType(ReadInteger('Like', '3p3l', 0));
// p3l4 := TDiagramType(ReadInteger('Like', '3p4l', 0) + 3);
// p3l4pt := TDiagramType(ReadInteger('Like', '3p4lpt', 0)+ 6);
// Free;
// end;
//// DiagramDraw.Rect := Rect( 20, 30, 20 + 380, 30 + 320 );
// if AEquation.WiringError.PhaseType = ptThree then
// begin
// DiagramDraw.DiagramType := p3l3;
//// if AEquation.WiringError.ProVersion = 'V2' then
//// DiagramDraw.DiagramType := dt3M ;
//// else
//// DiagramDraw.DiagramType := dt3L4;
// end
// else if AEquation.WiringError.PhaseType = ptFour then
// begin
// DiagramDraw.DiagramType := p3l4;
//// if AEquation.WiringError.ProVersion = 'V2' then
//// begin
//// DiagramDraw.DiagramType := dt4M_NoPT;
//// end;
//// else
//// DiagramDraw.DiagramType := dt4_NoPT_L6 ;
// end
// else //胡红明2013.5.23
// begin
// DiagramDraw.DiagramType := p3l4pt;
//// DiagramDraw.DiagramType := dt4_PT_L6;
// end;
DiagramDraw.DiagramType := ADiagramType;
DiagramDraw.WiringError := AEquation.WiringError;
DiagramDraw.DrawTo(Bitmap.Canvas, Rect(20, 30, 20 + 380, 30 + 320));
PhaseDraw.UIAngle := AEquation.UIAngle;
PhaseDraw.Rect := Rect( 20, 380, 20 + 380, 380 + 320 );
PhaseDraw.DrawPhaseMap( AEquation );
EquationDraw.Rect := Rect( 400, 30, 1020 - 20, 30 + 450 );
nY := EquationDraw.DrawEquationP( AEquation );
EquationDraw.Rect := Rect( 400, nY, 1020 - 20, 730 - 20 );
nY := EquationDraw.DrawEquationKH( AEquation );
Analysis := TStringList.Create;
AEquation.ShowAnalysis( Analysis, 120 );
EquationDraw.Rect := Rect( 400, nY + 20, 1020 - 20, 730 - 20 );
EquationDraw.DrawAnalysis( Analysis );
Analysis.Free;
imgmap.Picture.Bitmap := Bitmap;
ResizeImages;
end;
procedure TfWEDetails.ProcMouseWheel(var Msg: TWMMouseWheel);
begin
if Msg.Keys = 8 then
begin
if Msg.WheelDelta > 0 then
actZoomInExecute( nil )
else
actZoomOutExecute( nil );
end
else
begin
with scrlbxMap.VertScrollBar do
Position := Position - Msg.WheelDelta;
end;
end;
procedure TfWEDetails.ResizeImages;
begin
imgMap.Width := Round( imgMap.Picture.Width * dZoomRate );
imgMap.Height := Round( imgMap.Picture.Height * dZoomRate );
end;
end.
|
unit SoccerTests.MainTests;
interface
uses
System.SysUtils,
System.Generics.Collections,
DUnitX.TestFramework,
Soccer.Main,
Soccer.Exceptions;
type
[TestFixture]
TMainTests = class(TObject)
public
[Test]
procedure FullTest;
[Test]
procedure NoDecideCommand;
[Test]
procedure IncompletePreferencesTest;
end;
implementation
{ TMainTests }
procedure TMainTests.FullTest;
var
LSoccer: TSoccer;
LOutput: TList<string>;
begin
LSoccer := TSoccer.Create;
LOutput := LSoccer.ExecScript('START[voting] ' + 'IMPORT[plurality] ' + '//we use plurality\\ ' +
'VOTE(a->b->c) ' + 'VOTE(c->b->a) ' + 'VOTE(b->a->c) ' + 'VOTE(a->b->c) ' +
'DECIDE! ');
Assert.IsTrue(LOutput.Count = 2);
Assert.IsTrue(LOutput[0] = 'plurality');
Assert.IsTrue(LOutput[1] = 'a');
FreeAndNil(LOutput);
FreeAndNil(LSoccer);
end;
procedure TMainTests.IncompletePreferencesTest;
var
LSoccer: TSoccer;
begin
LSoccer := TSoccer.Create;
Assert.WillRaise(
procedure
begin
LSoccer.ExecScript('START[voting] ' + 'IMPORT[plurality] ' + 'VOTE(a->b) '
+ 'VOTE(a->b->c) ' + 'DECIDE!')
end, ESoccerParserException,
'Incompete profiles are for now not supported');
FreeAndNil(LSoccer);
end;
procedure TMainTests.NoDecideCommand;
var
LSoccer: TSoccer;
LOutput: TList<string>;
begin
LSoccer := TSoccer.Create;
Assert.WillRaise(
procedure
begin
LOutput := LSoccer.ExecScript('START[voting] ' + 'IMPORT[plurality] ' +
'VOTE(a->b->c) ' + 'VOTE(c->b->a) ' + 'VOTE(b->a->c) ' +
'VOTE(a->b->c) ');
end, ESoccerParserException, 'No "DECIDE!" command found');
FreeAndNil(LOutput);
FreeAndNil(LSoccer);
end;
initialization
TDUnitX.RegisterTestFixture(TMainTests);
end.
|
unit TreeView.DynamicDataTreeView;
interface
uses
FMX.TreeView, System.Classes, FMX.StdCtrls, System.Generics.Collections,
System.SysUtils;
type
TIndicatorTreeViewItem = class(TTreeViewItem)
private
fIndicator: TAniIndicator;
public
constructor Create(AOwner: TComponent); override;
end;
TDynamicDataTreeViewItem = class;
TFetchedItemList = TList<TDynamicDataTreeViewItem>;
TDynamicDataTreeViewItem = class(TTreeViewItem)
private
fOnExpand: TNotifyEvent;
fOnExpanded: TNotifyEvent;
fOnCollapse: TNotifyEvent;
fOnCollapsed: TNotifyEvent;
fOnFetch: TNotifyEvent;
procedure onExpandProc(Sender: TObject);
protected
procedure SetIsExpanded(const Value: Boolean); override;
public
constructor Create(AOwner: TComponent; ANeedIndicator: Boolean = True); overload;
procedure AddFetchedItems(AItemList: TFetchedItemList);
property OnExpand: TNotifyEvent read fOnExpand write fOnExpand;
property OnExpanded: TNotifyEvent read fOnExpanded write fOnExpanded;
property OnCollapse: TNotifyEvent read fOnCollapse write fOnCollapse;
property OnCollapsed: TNotifyEvent read fOnCollapsed write fOnCollapsed;
property OnFetch: TNotifyEvent read fOnFetch write fOnFetch;
end;
implementation
uses
System.UITypes, FMX.Types;
{ TIndicatorTreeViewItem }
constructor TIndicatorTreeViewItem.Create(AOwner: TComponent);
begin
inherited;
Self.Text := 'Loading...';
fIndicator := TAniIndicator.Create(Self);
fIndicator.Align := TAlignLayout.FitLeft;
fIndicator.Margins.Left := 5;
fIndicator.Margins.Right := 5;
fIndicator.Enabled := True;
AddObject(fIndicator);
end;
{ TDynamicDataTreeViewItem }
constructor TDynamicDataTreeViewItem.Create(AOwner: TComponent; ANeedIndicator: Boolean);
begin
inherited Create(AOwner);
Self.Height := Self.DefaultHeight;
Self.OnExpand := onExpandProc;
if ANeedIndicator then
Self.AddObject( TIndicatorTreeViewItem.Create(Self) );
end;
procedure TDynamicDataTreeViewItem.SetIsExpanded(const Value: Boolean);
begin
if IsExpanded <> Value then
begin
if Value AND Assigned(OnExpand) then
OnExpand(Self);
if (not Value) AND Assigned(OnCollapse) then
OnCollapse(Self);
inherited;
if Value AND Assigned(OnExpanded) then
OnExpanded(Self);
if (not Value) AND Assigned(OnCollapsed) then
OnCollapsed(Self);
end else begin
inherited;
end;
end;
procedure TDynamicDataTreeViewItem.onExpandProc(Sender: TObject);
begin
// Check whether children have already been fetched.
if (Self.Count = 0) OR
(not (Self.Items[0] is TIndicatorTreeViewItem)) then
exit();
// Try to fetch children.
if Assigned(fOnFetch) then
fOnFetch(Sender);
end;
procedure TDynamicDataTreeViewItem.AddFetchedItems(AItemList: TFetchedItemList);
var
wIndicatorItem: TIndicatorTreeViewItem;
wItem: TDynamicDataTreeViewItem;
begin
Self.TreeView.BeginUpdate();
// Remove indicator item.
if (Self.Count > 0) AND (Self.Items[0] is TIndicatorTreeViewItem) then
begin
wIndicatorItem := Self.Items[0] as TIndicatorTreeViewItem;
Self.RemoveObject(wIndicatorItem);
FreeAndNil(wIndicatorItem);
end;
// Add fetched items as children.
for wItem in AItemList do
Self.AddObject(wItem);
Self.TreeView.EndUpdate();
end;
end.
|
unit Tests.TPropertyList;
interface
uses
DUnitX.TestFramework,
System.Classes,
System.SysUtils,
System.TypInfo,
Pattern.Command;
{$M+}
type
[TestFixture]
TestPropertyList = class(TObject)
private
fComponent: TComponent;
procedure AssertMetadataItem(const expectedPropertyName
: string; const expectedClassName: string; expectedKind: TTypeKind;
const metadataItem: TPropertyInfo);
function AssertMetadataSize(const expectedSize: integer;
const metadataArray: TPropertyArray): boolean;
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
published
procedure ComponentWithoutProperties;
procedure OneProperty;
procedure ManyProperties_StrListTStringList;
procedure ManyProperties_IsDoneBoolean;
procedure ManyProperties_TCollection;
procedure ManyProperties_ValueIntInteger;
procedure ManyProperties_AnyDateTDateTime;
procedure ManyProperties_MemStreamTMemoryStream;
procedure ManyProperties_TextString;
end;
implementation
// ----------------------------------------------------------------------
// Tested samples (components)
// ----------------------------------------------------------------------
type
TComponentWithTList = class(TComponent)
private
FList: TList;
published
property List: TList read FList write FList;
end;
TComponentManyProps = class(TComponent)
private
FStrList: TStringList;
FIsDone: boolean;
FCollection: TCollection;
FValueInt: integer;
FAnyDate: TDateTime;
FMemStream: TMemoryStream;
FText: string;
published
property StrList: TStringList read FStrList write FStrList;
property IsDone: boolean read FIsDone write FIsDone;
property Collection: TCollection read FCollection write FCollection;
property ValueInt: integer read FValueInt write FValueInt;
property AnyDate: TDateTime read FAnyDate write FAnyDate;
property MemStream: TMemoryStream read FMemStream write FMemStream;
property Text: String read FText write FText;
end;
type
TTypeKindHelper = record helper for TTypeKind
function ToString: string;
end;
function TTypeKindHelper.ToString: string;
begin
Result := GetEnumName(TypeInfo(TTypeKind), integer(Self));
end;
// ----------------------------------------------------------------------
// Setup / TearDown
// ----------------------------------------------------------------------
procedure TestPropertyList.Setup;
begin
fComponent := TComponent.Create(nil);
end;
procedure TestPropertyList.TearDown;
begin
fComponent.Free;
end;
function TestPropertyList.AssertMetadataSize(const expectedSize: integer;
const metadataArray: TPropertyArray): boolean;
begin
Result := (expectedSize <= Length(metadataArray));
if not Result then
Assert.Fail
(Format('Expected %d items but got %d items (metadata TPropertyArray has not enough items)',
[expectedSize,Length(metadataArray)]));
end;
procedure TestPropertyList.AssertMetadataItem(const expectedPropertyName
: string; const expectedClassName: string; expectedKind: TTypeKind;
const metadataItem: TPropertyInfo);
begin
if (expectedPropertyName <> metadataItem.PropertyName) or
(expectedClassName <> metadataItem.ClassName) then
Assert.Fail(Format('Expected item %s:%s but got %s:%s',
[expectedPropertyName, expectedClassName, metadataItem.PropertyName,
metadataItem.ClassName]))
else if (expectedKind<>metadataItem.Kind) then
Assert.Fail(Format('Expected item kind %s but got %s',
[expectedKind.ToString, metadataItem.Kind.ToString]))
else
Assert.Pass;
end;
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
procedure TestPropertyList.ComponentWithoutProperties;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries(fComponent);
if AssertMetadataSize(0,metadata) then
Assert.Pass;
end;
procedure TestPropertyList.OneProperty;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentWithTList.Create(fComponent));
AssertMetadataSize(1,metadata);
AssertMetadataItem('List','TList',tkClass, metadata[0]);
end;
procedure TestPropertyList.ManyProperties_StrListTStringList;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('StrList','TStringList',tkClass, metadata[0]);
end;
procedure TestPropertyList.ManyProperties_IsDoneBoolean;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('IsDone', 'Boolean', tkEnumeration, metadata[1]);
end;
procedure TestPropertyList.ManyProperties_TCollection;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('Collection','TCollection',tkClass, metadata[2]);
end;
procedure TestPropertyList.ManyProperties_ValueIntInteger;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('ValueInt', 'Integer', tkInteger, metadata[3]);
end;
procedure TestPropertyList.ManyProperties_AnyDateTDateTime;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('AnyDate', 'TDateTime', tkFloat, metadata[4]);
end;
procedure TestPropertyList.ManyProperties_MemStreamTMemoryStream;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('MemStream', 'TMemoryStream', tkClass, metadata[5]);
end;
procedure TestPropertyList.ManyProperties_TextString;
var
metadata: TPropertyArray;
begin
metadata := TComponentMetadata.GetPublishedPropetries
(TComponentManyProps.Create(fComponent));
AssertMetadataSize(7,metadata);
AssertMetadataItem('Text', 'string', tkUString, metadata[6]);
end;
end.
|
{ Freepascal pipes unit converted to Delphi.
License: FPC Modified LGPL (okay to use in commercial projects)
Changes to the code marked with "L505" in comments }
{
This file is part of the Free Pascal run time library.
Copyright (c) 1999-2000 by Michael Van Canneyt
Implementation of pipe stream.
See the file COPYING.FPC, included in this distribution,
for details about the copyright.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
********************************************************************** }
unit dpipes;
interface
uses
system.types, // L505
sysutils, Classes;
type
EPipeError = Class(EStreamError);
EPipeSeek = Class(EPipeError);
EPipeCreation = Class(EPipeError);
{ TInputPipeStream }
TInputPipeStream = Class(THandleStream)
Private
FPos: Int64;
function GetNumBytesAvailable: DWord;
procedure WriteNotImplemented; // L505
procedure FakeSeekForward(Offset: Int64; const Origin: TSeekOrigin;
const Pos: Int64); // L505
procedure DiscardLarge(Count: Int64; const MaxBufferSize: Longint); // L505
procedure Discard(const Count: Int64); // L505
protected
function GetPosition: Int64; // override; //L505
procedure InvalidSeek; // override; //L505
public
destructor Destroy; override;
Function Write(Const Buffer; Count: Longint): Longint; Override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
Function Read(Var Buffer; Count: Longint): Longint; Override;
property NumBytesAvailable: DWord read GetNumBytesAvailable;
end;
TOutputPipeStream = Class(THandleStream)
Private
procedure ReadNotImplemented; // L505
procedure InvalidSeek; // L505
Public
destructor Destroy; override;
function Seek(const Offset: Int64; Origin: TSeekOrigin): Int64; override;
Function Read(Var Buffer; Count: Longint): Longint; Override;
end;
Function CreatePipeHandles(Var Inhandle, OutHandle: THandle;
APipeBufferSize: Cardinal = 1024): Boolean;
Procedure CreatePipeStreams(Var InPipe: TInputPipeStream;
Var OutPipe: TOutputPipeStream);
Const
EPipeMsg = 'Failed to create pipe.';
ENoSeekMsg = 'Cannot seek on pipes';
Implementation
{$IFDEF MACOS} // L505
{$I pipes_macos.inc}
{$ENDIF}
{$IFDEF MSWINDOWS} // L505
{$I pipes_win.inc}
{$ENDIF}
Procedure CreatePipeStreams(Var InPipe: TInputPipeStream;
Var OutPipe: TOutputPipeStream);
Var
Inhandle, OutHandle: THandle;
begin
if CreatePipeHandles(Inhandle, OutHandle) then
begin
InPipe := TInputPipeStream.Create(Inhandle);
OutPipe := TOutputPipeStream.Create(OutHandle);
end
Else
Raise EPipeCreation.Create(EPipeMsg)
end;
destructor TInputPipeStream.Destroy;
begin
PipeClose(Handle);
inherited;
end;
// L505
procedure TInputPipeStream.DiscardLarge(Count: Int64;
const MaxBufferSize: Longint);
var
Buffer: array of Byte;
begin
if Count = 0 then
Exit;
if Count > MaxBufferSize then
SetLength(Buffer, MaxBufferSize)
else
SetLength(Buffer, Count);
while (Count >= Length(Buffer)) do
begin
ReadBuffer(Buffer[0], Length(Buffer));
Dec(Count, Length(Buffer));
end;
if Count > 0 then
ReadBuffer(Buffer[0], Count);
end;
// L505
procedure TInputPipeStream.Discard(const Count: Int64);
const
CSmallSize = 255;
CLargeMaxBuffer = 32 * 1024; // 32 KiB
var
Buffer: array [1 .. CSmallSize] of Byte;
begin
if Count = 0 then
Exit;
if Count <= SizeOf(Buffer) then
ReadBuffer(Buffer, Count)
else
DiscardLarge(Count, CLargeMaxBuffer);
end;
// L505
procedure TInputPipeStream.FakeSeekForward(Offset: Int64;
const Origin: TSeekOrigin; const Pos: Int64);
// var
// Buffer: Pointer;
// BufferSize, i: LongInt;
begin
if Origin = soBeginning then
Dec(Offset, Pos);
if (Offset < 0) or (Origin = soEnd) then
InvalidSeek;
if Offset > 0 then
Discard(Offset);
end;
// L505
procedure TInputPipeStream.WriteNotImplemented;
begin
raise EStreamError.CreateFmt
('Cannot write to this stream, not implemented', []);
end;
// L505
procedure TOutputPipeStream.ReadNotImplemented;
begin
raise EStreamError.CreateFmt
('Cannot read from this stream, not implemented', []);
end;
Function TInputPipeStream.Write(Const Buffer; Count: Longint): Longint;
begin
WriteNotImplemented;
Result := 0;
end;
Function TInputPipeStream.Read(Var Buffer; Count: Longint): Longint;
begin
Result := Inherited Read(Buffer, Count);
Inc(FPos, Result);
end;
function TInputPipeStream.Seek(const Offset: Int64; Origin: TSeekOrigin): Int64;
begin
FakeSeekForward(Offset, Origin, FPos);
Result := FPos;
end;
destructor TOutputPipeStream.Destroy;
begin
PipeClose(Handle);
inherited;
end;
Function TOutputPipeStream.Read(Var Buffer; Count: Longint): Longint;
begin
ReadNotImplemented;
Result := 0;
end;
procedure TOutputPipeStream.InvalidSeek;
begin
raise EStreamError.CreateFmt('Invalid seek in TProcess', []);
end;
function TOutputPipeStream.Seek(const Offset: Int64;
Origin: TSeekOrigin): Int64;
begin
Result := 0; { to silence warning mostly }
InvalidSeek;
end;
end.
|
unit osXMLDOMUtils;
interface
uses
MSXML_TLB, DB;
type
TTipoObjeto = (toBD);
function getValueFromAttributes(attributes: IXMLDOMNamedNodeMap; name: string):OLEVariant;
function criarObjeto(doc: IXMLDOMDocument; tipoObjeto: TTipoObjeto; nome: string):IXMLDomElement;
function criarObjetoBD(doc: IXMLDOMDocument; nome: string):IXMLDomElement;
function criarObjetoMeta(doc: IXMLDOMDocument):IXMLDomElement;
procedure adicionarCampoMeta(nome: string; tipo: TFieldType; doc: IXMLDOMDocument; no: IXMLDomElement);
procedure adicionarCampoMetaBLOB(nome: string; subTipo: TBlobType;
doc: IXMLDOMDocument; no: IXMLDomElement);
function Encode64(S: string): string;
function Decode64(S: string): string;
const
Codes64 = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/';
implementation
function getValueFromAttributes(attributes: IXMLDOMNamedNodeMap; name: string): OLEVariant;
var
i: integer;
begin
for i := 0 to attributes.length-1 do
begin
if attributes[i].nodeName=name then
result := attributes[i].nodeValue;
end;
end;
function criarObjeto(doc: IXMLDOMDocument; tipoObjeto: TTipoObjeto; nome: string):IXMLDomElement;
var
elemento: IXMLDomElement;
begin
elemento := doc.createElement('Objeto');
elemento.setAttribute('Tipo', 'BD');
elemento.setAttribute('Nome', nome);
result := elemento;
end;
function criarObjetoBD(doc: IXMLDOMDocument; nome: string):IXMLDomElement;
begin
result := criarObjeto(doc, toBD, nome);
end;
function criarObjetoMeta(doc: IXMLDOMDocument):IXMLDomElement;
begin
result := doc.createElement('Meta');
end;
procedure adicionarCampoMeta(nome: string; tipo: TFieldType; doc: IXMLDOMDocument; no: IXMLDomElement);
var
elemento: IXMLDomElement;
begin
elemento := doc.createElement('Campo');
elemento.setAttribute('Nome', nome);
elemento.setAttribute('Tipo', tipo);
no.appendChild(elemento);
end;
procedure adicionarCampoMetaBLOB(nome: string; subTipo: TBlobType;
doc: IXMLDOMDocument; no: IXMLDomElement);
var
elemento: IXMLDomElement;
begin
elemento := doc.createElement('Campo');
elemento.setAttribute('Nome', nome);
elemento.setAttribute('Tipo', ftBlob);
elemento.setAttribute('SubTipo', subTipo);
no.appendChild(elemento);
end;
function Encode64(S: string): string;
var
i: Integer;
a: Integer;
x: Integer;
b: Integer;
begin
Result := '';
a := 0;
b := 0;
for i := 1 to Length(s) do
begin
x := Ord(s[i]);
b := b * 256 + x;
a := a + 8;
while a >= 6 do
begin
a := a - 6;
x := b div (1 shl a);
b := b mod (1 shl a);
Result := Result + Codes64[x + 1];
end;
end;
if a > 0 then
begin
x := b shl (6 - a);
Result := Result + Codes64[x + 1];
end;
end;
function Decode64(S: string): string;
var
i: Integer;
a: Integer;
x: Integer;
b: Integer;
begin
Result := '';
a := 0;
b := 0;
for i := 1 to Length(s) do
begin
x := Pos(s[i], codes64) - 1;
if x >= 0 then
begin
b := b * 64 + x;
a := a + 6;
if a >= 8 then
begin
a := a - 8;
x := b shr a;
b := b mod (1 shl a);
x := x mod 256;
Result := Result + chr(x);
end;
end
else
Exit;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.